Skip to content

feat(v6.51.0): patch_diagram — atomic incremental canvas edits (ADR-252, #301) - #304

Merged
cgbarlow merged 1 commit into
mainfrom
feature/patch-diagram
Sep 24, 2026
Merged

cgbarlow merged 1 commit into
mainfrom
feature/patch-diagram

Conversation

@cgbarlow

Copy link
Copy Markdown
Owner

Problem

update_diagram only accepts a full replacement of the canvas. For large diagrams that makes small agent edits impractical:

  • Adding 13 nodes and 10 edges to the 274-node "Full Family Tree" meant resending ~170 KB of JSON.
  • Any node or edge the agent dropped or mangled in transit was silently deleted.
  • Agent and UI edits could overwrite each other.
  • Stale canvas labels (copied from elements at draw time, e.g. "Peter Barlow (single-parent family)") could only be fixed with a full replacement.

While working on this I also found a race in update_diagram: it read current_version, then ran an unconditional UPDATE, so two concurrent saves could both claim the same next version.

Fix

  • PATCH /api/diagrams/{id} takes {operations: [1..200], change_summary?}. The ops are add_node, update_node, remove_node (cascade_edges, default true), add_edge, update_edge, remove_edge and sync_labels (node_ids?). It returns {id, current_version, updated_at, applied, results[]}, with one result per op giving its index, op and affected id.
  • Atomic: every op is validated and applied in memory, on a deep copy, before anything is written. If any op fails, the response is a 422 with detail: {error: "operation_failed", op_index, op, message} and nothing is written.
  • Concurrency: follows the REST If-Match convention, but here the header is optional. On a mismatch the response is a 409 with detail: {error: "version_conflict", current_version, expected_version} and nothing is written. The MCP tool and CLI expose this as expected_version / --expected-version. Without it, the patch applies to the latest version, and if another write lands between the read and the write, the patch re-reads and re-applies (up to 3 attempts).
  • Same stored result as a full update: the patched canvas is saved through the existing update_diagram, keeping the current name, description and metadata. There is no second write path. Normalisation, notation detection, search index, thumbnails, set membership and edge → relationship auto-create (including the ADR-249 relationshipId either-direction skip) all behave as they do for a full update, and each patch creates exactly one new version.
  • update_diagram is now a compare-and-swap (UPDATE … WHERE id = ? AND current_version = ?). When it loses a race it writes nothing and returns a conflict.
  • Pure engine in backend/app/diagrams/canvas_patch.py (no I/O). Validation follows the issue:
    • Node and edge ids must be new, and a new node needs a numeric position; parentId must name an existing node.
    • entityId must be a live element in the diagram's set.
    • Edge endpoints must be existing nodes.
    • relationshipId must link the two nodes' elements, in either direction.
    • update_* shallow-merge data; null deletes a key; unknown fields are rejected.
    • remove_node refuses a node that other nodes are nested inside.
    • Only {nodes, edges} diagrams can be patched.
  • sync_labels changes only data.label, following ADR-230 F1 (the diagram owns presentation). Element names, sets and relationship endpoints are batch-fetched with chunked IN queries, never one query per node.
  • Surfaces:
    • IrisClient.patch_diagram.
    • MCP tool patch_diagram: structured 409/422 payloads, auth_required, web_url. update_diagram's description now warns that it replaces the whole canvas.
    • CLI iris patch diagram <id> --from-json FILE [--expected-version N].
    • The server instructions (seed and fallback) point agents at patch_diagram for small edits.
    • CORS allows PATCH.
  • Surface parity (§14): HTTP PATCH is now its own verb, patch, and needs a patch_<entity> MCP tool and an iris patch <entity> CLI command. Counting it as update would have let it pass with no patch tool at all, because update_diagram already exists.
  • Authz: the same assert_write_allowed(collection_of_diagram(...)) gate as PUT (ADR-237/238).
  • Postgres: no schema change. The new SQL uses ? placeholders, chunked IN lists and positional row reads, and the compare-and-swap relies on rowcount, which both adapters report.

Tests

All written first and seen failing before implementation.

  • Backend full suite (pytest --ignore=tests/test_startup.py): 2184 passed, 9 skipped, 15 failed. All 15 failures also fail on main and are unrelated: test_search/test_entity_indexing.py (6 × TestElementCrudIndexing), test_search/test_rebuild.py (5 × TestRebuildSearchIndex), test_import_sparx test_convert_raises_for_non_jet4 and test_import_accepts_eap_extension, and test_mnemos test_mnemos_installed_and_enabled and test_mnemos_installed_but_disabled.
    • New tests/test_diagrams/test_canvas_patch.py (57 engine unit tests) and tests/test_diagrams/test_patch_diagram.py (21 tests) cover every acceptance criterion:
      • a patch stores the same data and side effects as the equivalent full PUT;
      • validation of every op;
      • a failing op leaves data, versions and relationships unchanged;
      • If-Match mismatch returns 409 with the current version and writes nothing;
      • the compare-and-swap race, retry without expected_version, and no retry with it;
      • sync_labels after a rename leaves everything else byte-identical;
      • one version per patch;
      • scoped-user 403;
      • 404, 401 and the op-count limits.
    • New parity-script tests.
  • iris-client: 70 passed.
  • cli: 70 passed, including a new end-to-end test that drives the MCP patch_diagram tool against a real backend.
  • mcp: 286 passed, 2 failed. Both failures are known on main: test_create_element_schema_requires_type_and_name and test_create_element_template_required_fields.
  • scripts/check_surface_parity.py: ✅ Parity clean.

Rollout / merge notes

  • No migration, no frontend change.
  • Versions go to 6.51.0: backend, frontend, iris-client and iris-mcp.
  • CHANGELOG/version rebase: ADR-250 (v6.50.2, batch write-scope) and ADR-251 (v6.50.3, anonymous relationship reads) are in flight on other branches. Whichever merges later needs a trivial rebase of the CHANGELOG headings and version numbers.
  • update_diagram's compare-and-swap affects every diagram save. A save that loses a race now gets a 409 instead of racing.
  • Out of scope, listed as follow-ups in ADR-252: the issue's "nice to have" items (partial get_diagram reads, relative add_node placement, labels that follow element names automatically).

ADR / Spec

  • docs/adrs/ADR-252-Patch-Style-Diagram-Updates.md
  • docs/adrs/specs/SPEC-252-A-Patch-Style-Diagram-Updates.md

Closes #301

🤖 Generated with Claude Code

https://claude.ai/code/session_01EbTwcTX1wKVooS7oWd7cP9

…52, #301)

Problem: update_diagram only accepts a full replacement of the canvas. Adding
13 nodes and 10 edges to the 274-node Full Family Tree meant resending
~170 KB; anything an agent dropped in transit was silently deleted; agent
and UI edits could overwrite each other; and stale node labels (copied from
elements at draw time) could only be fixed by a full replacement. Separately,
update_diagram read current_version and then updated unconditionally, so two
concurrent saves could both claim the same next version.

Change
- PATCH /api/diagrams/{id}: {operations[1..200], change_summary?} with ops
  add_node, update_node, remove_node (cascade_edges, default true), add_edge,
  update_edge, remove_edge, sync_labels (node_ids?). Returns
  {id, current_version, updated_at, applied, results[]}. Optional If-Match:
  mismatch -> 409 {error: version_conflict, current_version}, nothing
  written. A failing op -> 422 {error: operation_failed, op_index, op,
  message}, nothing written. Same write-scope gate as PUT (ADR-237/238).
- Pure engine app/diagrams/canvas_patch.py (no I/O, deep copy, never mutates
  input). Validation per the issue: duplicate ids, positions, parentId,
  entityId must be a live element in the diagram's set, edge endpoints must
  exist, relationshipId must link the two nodes' elements (either
  direction), shallow data merge (null deletes), re-validated relinks.
  sync_labels sets data.label to the element's current name only (ADR-230
  F1). Element names/sets and relationship endpoints are batch-fetched
  (chunked IN queries, shared app/common/id_chunks.py).
- Persistence reuses update_diagram with the current name/description/
  metadata, so a patch stores exactly what a full update with that canvas
  would, with the same side effects (normalisation, notations, search,
  thumbnails, set membership, edge -> relationship auto-create incl. the
  ADR-249 relationshipId skip) and one new version.
- update_diagram is now a compare-and-swap (UPDATE ... AND current_version
  = ?; nothing written when it loses). A patch without an expected version
  re-reads and re-applies on a lost race (3 attempts).
- iris-client patch_diagram; structured error details surface their
  message. MCP tool patch_diagram (structured 409/422 payloads,
  auth_required, web_url); update_diagram's description warns it replaces
  the canvas. CLI `iris patch diagram <id> --from-json FILE
  [--expected-version N]`. Server instructions (seed + fallback) point
  agents at patch_diagram for small edits. CORS allows PATCH.
- Surface parity: HTTP PATCH is its own verb `patch`, requiring a
  patch_<entity> MCP tool and an `iris patch <entity>` CLI command.

Tests (written first; seen failing on missing module/service/client
method/tool/command and the parity checker mapping PATCH to update):
- backend: test_canvas_patch.py (57 engine unit tests),
  test_patch_diagram.py (21 route/service tests: patch == equivalent full
  PUT incl. side effects, atomicity, If-Match 409/400, CAS race, retry,
  sync_labels, one version per patch, write-scope, 404/401, op limits),
  parity-script tests. Full suite: 2184 passed, 9 skipped, 15 failed —
  the 15 pre-existing on main (6 TestElementCrudIndexing, 5
  TestRebuildSearchIndex, 2 import_sparx eap, 2 mnemos).
- iris-client 70 passed; cli 70 passed (incl. new end-to-end MCP
  patch_diagram lifecycle against a real backend); mcp 286 passed, 2
  pre-existing failures (create_element / element_template schema tests).
- scripts/check_surface_parity.py: parity clean.

Docs: ADR-252, SPEC-252-A, CHANGELOG [6.51.0], README, docs/api.md,
docs/mcp.md, docs/cli.md, mcp + cli READMEs. Version 6.51.0 (backend,
frontend, iris-client, iris-mcp).

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01EbTwcTX1wKVooS7oWd7cP9
@cgbarlow
cgbarlow force-pushed the feature/patch-diagram branch from 7b93c53 to dc4c583 Compare September 24, 2026 01:40
@cgbarlow

Copy link
Copy Markdown
Owner Author

Rebased onto main after #302 and #303 merged.

Rechecked after the rebase:

  • backend: 2202 passed; the 15 failures also fail on main
  • mcp: 286 passed; the 2 inventory failures also fail on main
  • cli: 70 passed
  • iris-client: 70 passed
  • surface-parity check: clean

🤖 Generated with Claude Code

@cgbarlow
cgbarlow merged commit 46a1a76 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.

MCP: add patch-style diagram updates (patch_diagram)

1 participant