diff --git a/docs/architecture/ecs/ecs-extension-compatibility-audit.md b/docs/architecture/ecs/ecs-extension-compatibility-audit.md index ffe6998d71b..4742d5da3b3 100644 --- a/docs/architecture/ecs/ecs-extension-compatibility-audit.md +++ b/docs/architecture/ecs/ecs-extension-compatibility-audit.md @@ -187,12 +187,94 @@ is later architecture work outside this data-centralization phase. 7. Preserve callback ordering assumptions only where covered below; subscribe to graph events when observation is sufficient and no override is required. +## Graph-level call-site atomicity audit + +Audited against `3d7c5d4df3` (2026-09-11). The audited population is every +call site outside `src/stores/linkStore.ts` itself that reaches one of: + +- `attachNodeToStores` (which wraps `registerNodeState`); +- `useLinkStore().replaceLink`, whether through `replaceLinkTopology` or + called on the store directly; +- `useLinkStore().updateEndpoints` as a multi-update batch. + +The table is the complete result of grepping those three identifiers across +`src/`, not a sample. Two other routes into the same store functions are +deliberately **out of scope and unaudited**: `useLinkStore().registerLink` +(the fresh-registration path, reached only from `registerLinkTopology`), and +the single-patch `LLink.updateEndpoints` → `updateEndpoint` wrapper, which has +no sibling mutations to leave half-applied. + +Every site in the table rejects without leaving graph indexes or topology +inconsistent. One of them — the remote `connect` applier in +`graphMutations.ts` — is atomic only because of a precondition validated +elsewhere, and is called out below. + +| Call site | Function called | Atomic? | Notes | +| --------------------------------------------------------------------- | ------------------------------------------ | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `LGraph.add()` (`LGraph.ts:1383`) | `attachNodeToStores` → `registerNodeState` | Yes | `attachNodeToStores` retries with a fresh minted id on collision; `node.graph = this` is set before the call but graph arrays mutate only after registration succeeds. | +| `LGraphNode.connect()` (`LGraphNode.ts:3211`) | `replaceLinkTopology` → `replaceLink` | Yes | Returns before any topology mutation when `replaceLinkTopology` returns `false`. `finalizeInputLinkRemoval`, slot updates, and `onConnectionsChange` all follow the guard. | +| `SubgraphInput.connect()` (`subgraph/SubgraphInput.ts:102`) | `replaceLinkTopology` → `replaceLink` | Yes | Returns before `_disconnectNodeInput`, `linkIds.push`, and `anchorRerouteChain` when `replaceLinkTopology` returns `false`. | +| `SubgraphOutput.connect()` (`subgraph/SubgraphOutput.ts:73`) | `replaceLinkTopology` → `replaceLink` | Yes | Returns before `existingLink.disconnect`, `linkIds[0]` assignment, and `anchorRerouteChain` when `replaceLinkTopology` returns `false`. | +| remote `connect` applier in `graphMutations.ts:713` | `replaceLink` (direct store call) | Cond. | `if (!replacement) break` precedes `detachLinkSlots` and the `updateNodeSlots` writes. Atomic only by that guard plus the `prepare()` precondition — see below. | +| `replaceNodeInputs()` (`node/slotLinks.ts:192`) | `updateEndpoints` | Yes | Returns on `!result.ok` before `node.inputs.splice` or `finalizeInputLinkRemoval`. | +| reminted endpoint remap in `LGraph.configure()` (`LGraph.ts:3203`) | `updateEndpoints` | Yes | Marks configuration as errored on `!result.ok`; the rejected endpoint batch does not mutate topology. Node and link registrations completed before this batch remain. | +| `realignInputLinkSlots()` (`linkDeduplication.ts:240`) | `updateEndpoints` | Yes | A rejected endpoint batch fires no callbacks and marks its blocked links as skipped. The pass loop continues, so later successful batches for remaining links can fire `onConnectionsChange`. | +| `replaceNodesInPlace()` (`nodeReplacement/useNodeReplacement.ts:308`) | `updateEndpoints` | Yes | The only site that rolls back rather than returning early: shell ownership moves to the replacement before the batch, and `!topologyResult.ok` reverses it with `transferReplacementOwnership(newNode, node)` before bailing out. | + +### `graphMutations.ts` is atomic by precondition, not locally + +The remote `connect` applier is the one audited site whose atomicity does not +follow from reading the call site alone. The store's rejection signal is a +plain `undefined` return, and the surrounding code performs three further +mutations (`detachLinkSlots`, `linkPresentationStore.take`, and two +`updateNodeSlots` writes) that all assume the replacement was placed. + +Two layers keep it correct, and only one of them was written for this purpose: + +1. `prepare()` rejects the whole batch before any write when the incoming link + id is already owned by a sibling graph. That is the only way `replaceLink` + can reject from this call site: the displaced occupant is read back out of + the same target index `replaceLink` validates against, so neither the + ownership check nor the occupied-slot check can fire. +2. The `if (!replacement) break` guard, added by #16219 (2026-09-08) as a side + effect of link-presentation work rather than as an atomicity fix. + +Because layer 1 makes the rejection unreachable, layer 2 has no test that +exercises it through the public API. `leaves the target occupant attached when +the link store rejects the replacement` in +`src/core/graph/graphMutations.test.ts` stubs `replaceLink` to return +`undefined` and asserts the occupant keeps both its topology and its endpoint +slots; deleting the `break` fails it. Without that guard — the shape this code +had before #16219 — a sibling-owned id collision that reached `commit()` left +the occupant's topology registered and target-indexed while its endpoint slots +were cleared. + +Removing layer 1 alone is not graph corruption but is still a silent failure: +`batch()` returns `true` having dropped a queued `connect`. + +A durable fix would be for `replaceLink` to return a discriminated result like +`updateEndpoints` does, so the rejection cannot be dropped by omission. That is +out of scope for this audit. + +### Declared-non-atomic edge cases + +This cosmetic side effect leaves no graph inconsistency. The +`LGraphNode.connect()` case is pinned by an `it.fails` assertion in +`src/lib/litegraph/src/node/graphCallSiteAtomicity.test.ts`; the equivalent +subgraph call sites remain audit findings rather than executable assertions. + +| Edge case | Observable partial state | Severity | +| --------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- | +| `mintLinkId` runs before `replaceLinkTopology` in `LGraphNode.connect()`. | `graph.state.lastLinkId` advances even when `replaceLinkTopology` is rejected, creating a gap in the link ID sequence. No topology is corrupted; no dangling link or double-registered slot results. | Cosmetic — IDs remain unique and monotonic, just non-contiguous. | +| `mintLinkId` also runs first in `SubgraphInput.connect()` and `SubgraphOutput.connect()`; these cases are audited but not pinned by this test file. | The subgraph's `state.lastLinkId` likewise advances on rejection without changing topology. | Cosmetic — IDs remain unique and monotonic, just non-contiguous. | + ## Required follow-up evidence Existing evidence includes `LLink.store.test.ts`, `NodeInputSlot.test.ts`, `NodeOutputSlot.test.ts`, `slotLinks.test.ts`, `LGraphNode.test.ts`, -`LGraph.test.ts`, `nodeBadgeDraw.test.ts`, and browser geometry/registration -specs under `browser_tests/tests/vueNodes/`. +`LGraph.test.ts`, `graphMutations.test.ts`, `useNodeReplacement.test.ts`, +`nodeBadgeDraw.test.ts`, and browser geometry/registration specs under +`browser_tests/tests/vueNodes/`. Before removing compatibility shims, collect ecosystem evidence for: diff --git a/src/core/graph/graphMutations.test.ts b/src/core/graph/graphMutations.test.ts index 5ba0bd0c778..1187361d3d8 100644 --- a/src/core/graph/graphMutations.test.ts +++ b/src/core/graph/graphMutations.test.ts @@ -125,6 +125,49 @@ describe('graphMutations', () => { expect(presentation.getPresentation(scope, toLinkId(10))).toBeUndefined() }) + it('leaves the target occupant attached when the link store rejects the replacement', () => { + const graph = mutations() + graph.batch(context, (batch) => { + batch.addNode(node(1)) + batch.addNode(node(2)) + batch.addNode(node(3)) + batch.connect({ + id: 50, + originNodeId: 1, + originSlot: 0, + targetNodeId: 3, + targetSlot: 0, + type: 'IMAGE', + originOutputs: [{ name: 'out', type: 'IMAGE', links: [50] }], + targetInputs: [{ name: 'in', type: 'IMAGE', link: 50 }] + }) + }) + + const links = useLinkStore() + vi.spyOn(links, 'replaceLink').mockReturnValueOnce(undefined) + + graph.connect( + { + id: 51, + originNodeId: 2, + originSlot: 0, + targetNodeId: 3, + targetSlot: 0, + type: 'IMAGE' + }, + context + ) + + const nodes = useNodeDataStore().getGraphNodesFor('root', 'root') + expect(links.getInputSlotLink(scope, toNodeId(3), 0)?.id).toBe(toLinkId(50)) + expect(nodes.find(({ id }) => id === toNodeId(3))?.inputs[0].link).toBe( + toLinkId(50) + ) + expect( + nodes.find(({ id }) => id === toNodeId(1))?.outputs[0].links + ).toEqual([toLinkId(50)]) + }) + it('preserves presentation when a remote batch reconnects the same link id', () => { const graph = mutations() const link = { diff --git a/src/lib/litegraph/src/node/graphCallSiteAtomicity.test.ts b/src/lib/litegraph/src/node/graphCallSiteAtomicity.test.ts new file mode 100644 index 00000000000..139aec6530e --- /dev/null +++ b/src/lib/litegraph/src/node/graphCallSiteAtomicity.test.ts @@ -0,0 +1,274 @@ +/** + * Atomicity contracts for graph-level call sites of attachNodeToStores, + * replaceLinkTopology, and updateEndpoints. + * + * Every site validated-then-mutates: a store rejection leaves no committed + * graph mutation. The one declared edge case is the cosmetic ID gap created + * by mintLinkId before replaceLinkTopology is called; that is documented in + * docs/architecture/ecs/ecs-extension-compatibility-audit.md under + * "Declared-non-atomic edge cases". + */ +import { describe, expect, it, vi } from 'vitest' + +import { realignInputLinkSlots } from '@/lib/litegraph/src/linkDeduplication' +import { LGraph, LGraphNode } from '@/lib/litegraph/src/litegraph' +import type { ISerialisedNode } from '@/lib/litegraph/src/types/serialisation' +import { useLinkStore } from '@/stores/linkStore' +import { useNodeDataStore } from '@/stores/nodeDataStore' + +// --------------------------------------------------------------------------- +// Fixtures +// --------------------------------------------------------------------------- + +function connectedPair() { + const graph = new LGraph() + const source = new LGraphNode('Source') + source.addOutput('out', 'INT') + graph.add(source) + + const target = new LGraphNode('Target') + target.addInput('in', 'INT') + graph.add(target) + + const link = source.connect(0, target, 0)! + return { graph, source, target, link } +} + +// --------------------------------------------------------------------------- +// attachNodeToStores call site: LGraph.add() +// --------------------------------------------------------------------------- + +describe('attachNodeToStores – LGraph.add() atomicity', () => { + it('resolves an id collision by re-minting before mutating graph arrays', () => { + // Pre-plant a node so its id is already taken in the store. + const graph = new LGraph() + const planted = new LGraphNode('Planted') + graph.add(planted) + + // The collision candidate starts with the same id as the planted node. + const candidate = new LGraphNode('Candidate') + candidate.id = planted.id + + graph.add(candidate) + + // Both nodes are registered with unique ids. + expect(candidate.id).not.toBe(planted.id) + expect(graph._nodes).toHaveLength(2) + // Each node appears exactly once under its id. + expect(graph._nodes_by_id[planted.id]).toBe(planted) + expect(graph._nodes_by_id[candidate.id]).toBe(candidate) + }) + + it('leaves graph indexes unchanged when store registration throws', () => { + const graph = new LGraph() + const node = new LGraphNode('N') + vi.spyOn(useNodeDataStore(), 'registerNode').mockImplementation(() => { + throw new Error('forced registration failure') + }) + + expect(() => graph.add(node)).toThrow('forced registration failure') + expect(graph._nodes).toEqual([]) + expect(graph._nodes_by_id).toEqual({}) + }) +}) + +// --------------------------------------------------------------------------- +// replaceLinkTopology call site: LGraphNode.connect() +// --------------------------------------------------------------------------- + +describe('replaceLinkTopology – LGraphNode.connect() atomicity', () => { + it('leaves the graph unchanged when the store rejects replaceLink', () => { + const { source, target, link } = connectedPair() + const graph = source.graph! + + const linksBefore = graph.links.size + const inputLinkBefore = target.getInputLink(0)?.id + + // Force every replaceLink call to fail. + vi.spyOn(useLinkStore(), 'replaceLink').mockReturnValue(undefined) + + // Attempt a second connection to the same input slot. + const second = new LGraphNode('Second') + second.addOutput('out', 'INT') + graph.add(second) + const result = second.connect(0, target, 0) + + // connect() returns null or undefined on rejection. + expect(result).toBeFalsy() + // The link store is unchanged. + expect(graph.links.size).toBe(linksBefore) + // The original link on the target input is still intact. + expect(target.getInputLink(0)?.id).toBe(inputLinkBefore) + // The incumbent link from the first source is still registered. + expect(graph.links.get(link.id)).toBeDefined() + }) + + it('commits the replacement and removes the incumbent on success', () => { + const graph = new LGraph() + const source1 = new LGraphNode('S1') + source1.addOutput('out', 'INT') + graph.add(source1) + const source2 = new LGraphNode('S2') + source2.addOutput('out', 'INT') + graph.add(source2) + const target = new LGraphNode('T') + target.addInput('in', 'INT') + graph.add(target) + + const first = source1.connect(0, target, 0)! + expect(graph.links.get(first.id)).toBeDefined() + + const second = source2.connect(0, target, 0)! + // The new link is registered. + expect(graph.links.get(second.id)).toBeDefined() + // The old link is gone. + expect(graph.links.has(first.id)).toBe(false) + // The target input reflects the new link. + expect(target.getInputLink(0)?.id).toBe(second.id) + }) + + /** + * Declared edge case (cosmetic, not a graph inconsistency): + * mintLinkId increments state.lastLinkId before replaceLinkTopology. + * A rejection wastes the minted id, leaving a gap in the sequence. + * The graph's _topology_ remains consistent — no dangling link, no + * double-registered slot. Only the monotonic counter advances. + */ + it.fails('does not advance lastLinkId when the store rejects replaceLink', () => { + const { source, target } = connectedPair() + const graph = source.graph! + const idBefore = Number(graph.state.lastLinkId) + + vi.spyOn(useLinkStore(), 'replaceLink').mockReturnValue(undefined) + + const second = new LGraphNode('S2') + second.addOutput('out', 'INT') + graph.add(second) + second.connect(0, target, 0) + + // This assertion FAILS: lastLinkId was already incremented by mintLinkId + // before the store call. The gap is cosmetic — no topology corruption. + expect(Number(graph.state.lastLinkId)).toBe(idBefore) + }) +}) + +// --------------------------------------------------------------------------- +// updateEndpoints call site: replaceNodeInputs (slotLinks.ts) +// --------------------------------------------------------------------------- + +describe('updateEndpoints – replaceNodeInputs() atomicity', () => { + it('does not splice node.inputs when updateEndpoints is rejected', () => { + const graph = new LGraph() + const source = new LGraphNode('S') + source.addOutput('out', 'INT') + graph.add(source) + const target = new LGraphNode('T') + target.addInput('a', 'INT') + target.addInput('b', 'INT') + graph.add(target) + source.connect(0, target, 0) + source.connect(0, target, 1) + + const inputsBefore = [...target.inputs] + const linkAtA = target.getInputLink(0)!.id + const linkAtB = target.getInputLink(1)!.id + const onInputRemoved = vi.fn() + target.onInputRemoved = onInputRemoved + + // The last test in legacySlotLinkMutations.test.ts already exercises the + // "keeps the input layout when the endpoint batch is rejected" path via + // removeInput. Here we drive it through the store rejection directly. + vi.spyOn(useLinkStore(), 'updateEndpoints').mockReturnValue({ + ok: false, + error: { code: 'occupied-target', message: 'forced rejection' } + }) + const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}) + + // removeInput triggers replaceNodeInputs → updateEndpoints. + target.removeInput(0) + + expect(consoleError).toHaveBeenCalledWith( + 'Failed to replace node inputs', + expect.objectContaining({ code: 'occupied-target' }) + ) + // node.inputs is unchanged — no partial splice committed. + expect(target.inputs.map((i) => i.name)).toEqual( + inputsBefore.map((i) => i.name) + ) + // Both links are still registered. + expect(graph.links.size).toBe(2) + // Which link sits in which slot, not just how many survive. + expect(target.getInputLink(0)?.id).toBe(linkAtA) + expect(target.getInputLink(1)?.id).toBe(linkAtB) + // A rejected splice must not have announced a removal. + expect(onInputRemoved).not.toHaveBeenCalled() + }) + + it('splices inputs and updates endpoints together on success', () => { + const graph = new LGraph() + const source = new LGraphNode('S') + source.addOutput('out', 'INT') + graph.add(source) + const target = new LGraphNode('T') + target.addInput('a', 'INT') + target.addInput('b', 'INT') + graph.add(target) + source.connect(0, target, 0) + source.connect(0, target, 1) + + const linkAtB = target.getInputLink(1)! + + // Remove slot 0; slot 1 (with its link) shifts to slot 0. + target.removeInput(0) + + expect(target.inputs).toHaveLength(1) + expect(target.inputs[0].name).toBe('b') + // The surviving link now targets slot 0. + expect(target.getInputLink(0)?.id).toBe(linkAtB.id) + expect(graph.links.size).toBe(1) + }) +}) + +// --------------------------------------------------------------------------- +// updateEndpoints call site: realignInputLinkSlots (linkDeduplication.ts) +// --------------------------------------------------------------------------- + +describe('updateEndpoints – realignInputLinkSlots() atomicity', () => { + it('keeps the original connection when updateEndpoints is rejected', () => { + const graph = new LGraph() + const source = new LGraphNode('S') + source.addOutput('out', 'INT') + graph.add(source) + const target = new LGraphNode('T') + target.addInput('other', 'INT') + target.addInput('x', 'INT') + graph.add(target) + const link = source.connect(0, target, 0)! + + const onConnectionsChange = vi.fn() + target.onConnectionsChange = onConnectionsChange + + const updateEndpoints = vi + .spyOn(useLinkStore(), 'updateEndpoints') + .mockReturnValue({ + ok: false, + error: { code: 'unowned-topology', message: 'forced' } + }) + vi.spyOn(console, 'error').mockImplementation(() => {}) + + const nodeData: Pick = { + id: target.id, + inputs: [{ name: 'x', type: 'INT', link: target.getInputLink(0)!.id }] + } + realignInputLinkSlots(graph, [[target.id, nodeData]]) + + expect(updateEndpoints).toHaveBeenCalledOnce() + expect(updateEndpoints).toHaveReturnedWith( + expect.objectContaining({ ok: false }) + ) + // onConnectionsChange must not fire — no partial side effects. + expect(onConnectionsChange).not.toHaveBeenCalled() + expect(target.getInputLink(0)?.id).toBe(link.id) + expect(target.getInputLink(1)).toBeNull() + }) +})