Repository navigation
fix(v6.50.1): diagram view fetched every canvas element 4 times (ADR-248) - #299
Merged
Merged
Conversation
…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
force-pushed
the
fix/diagram-view-element-fetches
branch
from
September 24, 2026 00:22
61a0161 to
4ae2d43
Compare
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
Opening a diagram in the diagram view (
/views/[id]) sent 4 × NGET /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 back429, 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:
page.params.id$effectcalledloadDiagram(id). Before its firstawait,loadDiagramreadsareThemesLoaded(), which isthemesLoaded$state. WhenloadThemes()changed that value, the effect ran again and the whole page load repeated.refreshNodeDescriptions()fetched each element in parallel.loadInheritedTags()then fetched each element again, one at a time, only to read.tags.get_elementworks outdiagram_usage_countwithdv.data LIKE '%<id>%', which scans all diagram data once per element.Fix
untrack(() => loadDiagram(id)).loadDiagrammakes oneGET /api/diagrams/${id}/elementscall, and both the node refresh and the inherited tags come from that result. The logic sits in the pure helpers infrontend/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.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 distinctentityIdon the current canvas it returns anElementResponseidentical toGET /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 inelements.service.get_elements_by_ids: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.LIKE '%<id>%', with two documented exceptions. Matching is case-sensitive, as PostgreSQL'sLIKEis._and%are treated as literal characters.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.get_elementand the batch use one sharedSELECTand one shared row mapper.get_diagram_relationships(ADR-184) and copied inlist_element_relationships_for_diagram. It now lives inapp/diagrams/canvas_entities.py.GETendpoint, and MCP and the CLI are unchanged.check_surface_parity.pyreports "Parity clean".Tests
The tests were written first and failed before each change.
tests/test_diagrams/test_diagram_elements.py(13 tests): each payload equalsGET /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 noLIKEfor usage; usage counts across several diagrams match the single-element endpoint.tests/test_diagrams/test_canvas_entities.pyandtests/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.pytest tests --ignore=tests/test_startup.py): 2072 passed, 15 failed, 9 skipped. All 15 failures also fail onmainand are unrelated to this change:test_search/test_entity_indexing.py(6)test_search/test_rebuild.py(5)test_import_sparxtest_convert_raises_for_non_jet4andtest_import_accepts_eap_extensiontest_mnemostest_mnemos_installed_and_enabledandtest_mnemos_installed_but_disablednpx 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 withmain's+page.svelte.svelte-checkreports no errors in new or changed code.scripts/check_surface_parity.py: Parity clean, exit 0.Rollout / merge notes
GET /api/elements/{id}are unaffected.?placeholders, rows read by position,is_deleted = 0, and aUNIONsubquery with an alias. The usage query is a plainSELECT dv.data … WHERE d.is_deleted = 0.IRIS_TEST_POSTGRES_DSNwas available. After deploying, check on UAT that the Full Family Tree opens anonymously without 429s.backend/pyproject.tomlandfrontend/package.json.ADR / Spec
docs/adrs/ADR-248-Batch-Diagram-Element-Hydration.mddocs/adrs/specs/SPEC-248-A-Batch-Diagram-Element-Hydration.mdCHANGELOG.md[6.49.3],docs/api.md🤖 Generated with Claude Code
https://claude.ai/code/session_01EbTwcTX1wKVooS7oWd7cP9