Skip to content

fix(v6.50.1): diagram view fetched every canvas element 4 times (ADR-248) - #299

Merged
cgbarlow merged 2 commits into
mainfrom
fix/diagram-view-element-fetches
Sep 24, 2026
Merged

cgbarlow merged 2 commits into
mainfrom
fix/diagram-view-element-fetches

Conversation

@cgbarlow

Copy link
Copy Markdown
Owner

Problem

Opening a diagram in the diagram view (/views/[id]) sent 4 × N GET /api/elements/{id} requests for a canvas with N element nodes. Measured locally (headless Chromium, 37-node diagram, anonymous): 166 API requests, 148 of them element GETs, and 136 came back 429, because the anonymous limit is 30 a minute. The 274-node "Full Family Tree" on UAT needs about 1,100 requests, so anonymous viewers see "Failed to load diagram" and a canvas of 429s.

There were three causes:

  1. The page loaded twice. The page.params.id $effect called loadDiagram(id). Before its first await, loadDiagram reads areThemesLoaded(), which is themesLoaded $state. When loadThemes() changed that value, the effect ran again and the whole page load repeated.
  2. Two loops per node on each load. refreshNodeDescriptions() fetched each element in parallel. loadInheritedTags() then fetched each element again, one at a time, only to read .tags.
  3. Server cost per element. get_element works out diagram_usage_count with dv.data LIKE '%<id>%', which scans all diagram data once per element.

Fix

  • Frontend: the effect now calls untrack(() => loadDiagram(id)). loadDiagram makes one GET /api/diagrams/${id}/elements call, and both the node refresh and the inherited tags come from that result. The logic sits in the pure helpers in frontend/src/lib/canvas/diagramElementHydration.ts. The call is skipped when no node links to an element. A stale response is ignored if the user has already moved to another diagram. If the call fails, the canvas stays as saved.
  • Backend: new GET /api/diagrams/{diagram_id}/elements. Anyone can read it (get_optional_user). It returns 404 if the diagram is missing or deleted. For every distinct entityId on the current canvas it returns an ElementResponse identical to GET /api/elements/{id}. Elements come back in canvas order, with duplicates removed; deleted elements and nodes without an entityId are skipped. The work is done in elements.service.get_elements_by_ids:
    • For each chunk of 400 ids, one grouped query each fetches element rows, tags and relationship counts.
    • Diagram usage counts come from one read of the live diagrams' current data per request. count_diagram_usage (app/elements/diagram_usage.py) then matches all the ids in one pass over each diagram: it finds UUID-shaped substrings, including overlapping ones, and intersects them with the requested ids. Any id that is not UUID-shaped gets an exact substring test instead.
    • The counts mean the same as LIKE '%<id>%', with two documented exceptions. Matching is case-sensitive, as PostgreSQL's LIKE is. _ and % are treated as literal characters.
  • Review fix (second commit): the first version counted usage with a per-chunk CROSS JOIN … LIKE '%' || e.id || '%'. That still ran one substring scan per element. In a local SQLite benchmark with 7.7 MB of diagram data it took 148, 1,015 and 1,390 ms for 37, 274 and 400 ids. The single pass takes 100–107 ms at every size and gives identical counts. The ADR and spec now describe what this actually costs.
  • Shared code (§13):
    • get_element and the batch use one shared SELECT and one shared row mapper.
    • The canvas-entityId extraction was inlined in get_diagram_relationships (ADR-184) and copied in list_element_relationships_for_diagram. It now lives in app/diagrams/canvas_entities.py.
  • Result: the page makes 1 element request on load instead of 4N. Measured locally, 37-node and 274-node diagrams each load with 11 API requests in total, with no duplicates and no 429s. The Full Family Tree on UAT should go from about 1,100 requests to about 18 at most.
  • Surface parity (§14): not applicable. This is a GET endpoint, and MCP and the CLI are unchanged. check_surface_parity.py reports "Parity clean".

Tests

The tests were written first and failed before each change.

  • New backend tests:
    • tests/test_diagrams/test_diagram_elements.py (13 tests): each payload equals GET /api/elements/{id}; dedup; deleted and unknown ids excluded; nodes without an entityId skipped; empty canvas; 404 for a missing or deleted diagram; anonymous read; the query count doesn't depend on node count (5, and at most 6); chunking; one diagram-data read and no LIKE for usage; usage counts across several diagrams match the single-element endpoint.
    • tests/test_diagrams/test_canvas_entities.py and tests/test_elements/test_diagram_usage.py (11 matcher unit tests).
  • pytest tests/test_elements/test_diagram_usage.py tests/test_diagrams/test_diagram_elements.py tests/test_diagrams/test_canvas_entities.py: 28 passed.
  • Full backend suite (pytest tests --ignore=tests/test_startup.py): 2072 passed, 15 failed, 9 skipped. All 15 failures also fail on main and are unrelated to this change:
    • test_search/test_entity_indexing.py (6)
    • test_search/test_rebuild.py (5)
    • test_import_sparx test_convert_raises_for_non_jet4 and test_import_accepts_eap_extension
    • test_mnemos test_mnemos_installed_and_enabled and test_mnemos_installed_but_disabled
  • Frontend: npx vitest run tests/unit/diagramElementHydration.test.ts tests/unit/descriptionSync.test.ts tests/unit/elementToNodeData.test.ts: 26 passed. Across the full vitest run, the 7 failing tests also fail with main's +page.svelte. svelte-check reports no errors in new or changed code.
  • scripts/check_surface_parity.py: Parity clean, exit 0.

Rollout / merge notes

  • Only a new read endpoint was added: no schema change and no migration. Existing clients of GET /api/elements/{id} are unaffected.
  • Supabase:
    • The new SQL uses only syntax that works on both databases: ? placeholders, rows read by position, is_deleted = 0, and a UNION subquery with an alias. The usage query is a plain SELECT dv.data … WHERE d.is_deleted = 0.
    • It has not been run against PostgreSQL, because no IRIS_TEST_POSTGRES_DSN was available. After deploying, check on UAT that the Full Family Tree opens anonymously without 429s.
  • Cost per request: each request moves every live diagram's current data from the database to the app once. That is a few MB on a large instance, where before the database read the same bytes once per element.
  • Merge order: PR fix(v6.49.2): PATs 500 on Supabase deployments (ADR-247) #297 (v6.49.2) is already merged, and this branch is built on it, so no rebase is needed for CHANGELOG or version. The version is bumped to 6.49.3 in backend/pyproject.toml and frontend/package.json.

ADR / Spec

  • docs/adrs/ADR-248-Batch-Diagram-Element-Hydration.md
  • docs/adrs/specs/SPEC-248-A-Batch-Diagram-Element-Hydration.md
  • CHANGELOG.md [6.49.3], docs/api.md

🤖 Generated with Claude Code

https://claude.ai/code/session_01EbTwcTX1wKVooS7oWd7cP9

Chris Barlow and others added 2 commits September 24, 2026 00:17
…248)

Opening /views/[id] made 4N GET /api/elements/{id} requests for N element
nodes (37-node diagram: 166 requests, 148 element GETs, 136 x 429 for an
anonymous viewer; the 274-node Full Family Tree needed ~1,100).

Root causes:
- The page.params.id $effect called loadDiagram(id), which reads
  areThemesLoaded() ($state in themeStore) before its first await; when
  loadThemes() flipped it the effect re-ran and the whole load ran twice.
- Each load ran refreshNodeDescriptions() (one element GET per node) and
  loadInheritedTags() (another, sequential, just for .tags).
- get_element's diagram_usage_count is a LIKE scan over all current diagram
  data, so the server paid one full scan per request.

Changes:
- Frontend: untrack(() => loadDiagram(id)); loadDiagramElements(id) makes
  ONE GET /api/diagrams/{id}/elements (none when no node has an entityId)
  and derives the node refresh and inherited tags from it; on failure the
  canvas stays as stored. Pure logic in lib/canvas/diagramElementHydration.ts.
- Backend: new GET /api/diagrams/{id}/elements (anonymous-readable, 404 for
  missing/deleted diagram) returning ElementResponse per distinct entityId
  on the current canvas, identical to GET /api/elements/{id}.
  elements.service.get_elements_by_ids batches it: 4 queries per chunk of
  400 ids (rows, tags, grouped relationship counts, usage counts in one
  diagram scan with get_element's exact LIKE semantics). get_element and
  the batch share one SELECT and row mapper. The canvas entityId
  extraction (ADR-184) moves to diagrams/canvas_entities.py and is reused
  by get_diagram_relationships and list_element_relationships_for_diagram.
- Surface parity N/A (GET only); no schema change.

Measured after (local, headless Chromium, anonymous): 37- and 274-node
diagrams each load with 11 API requests, one elements call, no 429s.

Tests (TDD, red first): tests/test_diagrams/test_diagram_elements.py
(payload equality with GET /api/elements/{id}, dedup/order, deleted and
unknown excluded, entityId-less nodes, empty canvas, 404 missing/deleted,
anonymous, query count independent of node count, chunking) and
test_canvas_entities.py; frontend diagramElementHydration.test.ts, and
descriptionSync.test.ts updated. Backend full suite: 2059 passed, 15
failed (the known pre-existing test_search/Sparx .eap/mnemos failures),
9 skipped. Frontend vitest: 1301 passed, 7 failed (same 7 fail on
origin/main). Surface parity clean.

See docs/adrs/ADR-248-Batch-Diagram-Element-Hydration.md and
docs/adrs/specs/SPEC-248-A-Batch-Diagram-Element-Hydration.md.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01EbTwcTX1wKVooS7oWd7cP9
Review finding: the batched endpoint computed diagram_usage_count with a
per-chunk CROSS JOIN ... WHERE dv.data LIKE '%' || e.id || '%'. That reads
each diagram row once but still runs one substring scan of it per element,
so the database did the same O(N x diagram bytes) work as N single-element
requests, inside one statement on the page's critical path (root cause #3
was not actually removed, and ADR/SPEC overstated it).

Change: get_elements_by_ids now reads every live diagram's current data in
ONE query per request (not per chunk) and hands it to the new pure
count_diagram_usage (app/elements/diagram_usage.py). It finds every
UUID-shaped substring per diagram (overlapping matches included) and
intersects with the requested ids, so the cost is O(total diagram bytes)
regardless of id count; non-UUID ids fall back to an exact substring test.
Semantics match LIKE '%<id>%' except: case-sensitive (PostgreSQL LIKE
behaviour) and '_'/'%' are literal. get_element keeps its single-id LIKE.

Local SQLite benchmark, 7.7 MB of diagram data: old CROSS JOIN 148/1015/
1390 ms for 37/274/400 ids; new single pass 100-107 ms at every size, with
identical counts.

Tests (written first, red before the change):
- test_elements/test_diagram_usage.py: 11 matcher unit tests (distinct
  counts, repeats, substring/edge-id mentions, overlapping UUIDs, case
  sensitivity, non-UUID fallback, literal wildcards, None data).
- test_diagram_elements.py: diagram_versions read exactly twice and no
  LIKE query with 5 chunks; chunk query formula updated; usage counts
  across several diagrams (repeat, edge-only, deleted, superseded version)
  equal GET /api/elements/{id}.
ADR-248, SPEC-248-A and CHANGELOG updated to describe the real cost.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01EbTwcTX1wKVooS7oWd7cP9
@cgbarlow
cgbarlow force-pushed the fix/diagram-view-element-fetches branch from 61a0161 to 4ae2d43 Compare September 24, 2026 00:22
@cgbarlow cgbarlow changed the title fix(v6.49.3): diagram view fetched every canvas element 4 times (ADR-248) fix(v6.50.1): diagram view fetched every canvas element 4 times (ADR-248) Sep 24, 2026
@cgbarlow

Copy link
Copy Markdown
Owner Author

Rebased onto main after #300 merged. Renumbered from v6.49.3 to v6.50.1 (CHANGELOG, backend/pyproject.toml, frontend/package.json and code comments); ADR-248 is unchanged. Merged the docs/api.md sections from both PRs. Full backend suite: 2104 passed, and the 15 failures are the same ones that fail on main. Frontend unit tests (26) and the surface-parity check pass.

🤖 Generated with Claude Code

@cgbarlow
cgbarlow merged commit 6d6e183 into main Sep 24, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant