diff --git a/src/datasource/catmaid/spatial_skeleton_edit/edit_planner.ts b/src/datasource/catmaid/spatial_skeleton_edit/edit_planner.ts index 5b018ff117..b7f6546333 100644 --- a/src/datasource/catmaid/spatial_skeleton_edit/edit_planner.ts +++ b/src/datasource/catmaid/spatial_skeleton_edit/edit_planner.ts @@ -50,6 +50,7 @@ import type { SpatialSkeletonEditCommand, } from "#src/skeleton/edit/edit_commands.js"; import type { + SpatialSkeletonAdmissionContext, SpatialSkeletonIntentCreationContext, SpatialSkeletonEditPlanner, SpatialSkeletonIntentPlan, @@ -64,7 +65,10 @@ import type { SpatialSkeletonEditDelta, SpatialSkeletonEditInverseDelta, } from "#src/skeleton/edit_queue/complete_skeleton_edits.js"; -import { getSkeletonNodeChanges } from "#src/skeleton/edit_queue/complete_skeleton_edits.js"; +import { + assertCanMergeUnder, + getSkeletonNodeChanges, +} from "#src/skeleton/edit_queue/complete_skeleton_edits.js"; import type { SpatialSkeletonIntentResource } from "#src/skeleton/edit_queue/edit_intent_journal.js"; import type { SpatialSkeletonAuthoritativeReconciliation, @@ -942,6 +946,31 @@ export class CatmaidEditPlanner super(identity); } + checkAdmission( + input: CatmaidSpatialSkeletonCommandDescriptor, + { + requiredInput, + unpreparedEarlierInputs, + }: SpatialSkeletonAdmissionContext, + ) { + if (input.payload.kind !== "merge") return; + if ( + unpreparedEarlierInputs.some(({ payload }) => payload.kind === "true-end") + ) { + return; + } + const { payload } = resolveCatmaidPreparedCommand( + input, + requiredInput, + this.identity, + ); + if (payload.kind !== "merge") return; + const firstNode = requiredInput.segments + .map(({ snapshot }) => snapshot.getNode(payload.options.firstNode.nodeId)) + .find((node) => node !== undefined); + if (firstNode !== undefined) assertCanMergeUnder(firstNode); + } + describeIntent(input: CatmaidSpatialSkeletonCommandDescriptor) { const { payload } = input; return Object.freeze({ diff --git a/src/skeleton/edit/spatial_skeleton_edit_session.spec.ts b/src/skeleton/edit/spatial_skeleton_edit_session.spec.ts index a029925b2b..4d31014529 100644 --- a/src/skeleton/edit/spatial_skeleton_edit_session.spec.ts +++ b/src/skeleton/edit/spatial_skeleton_edit_session.spec.ts @@ -310,6 +310,7 @@ function makeRegistration( return { planner: { describeIntent: () => ({ kind: "test", commandLabel: "Test" }), + checkAdmission: () => undefined, planIntent: (_command, context) => ({ kind: "test", commandLabel: "Test", @@ -358,6 +359,7 @@ function makeHeldCommitProvider(cleanup = vi.fn()) { return { planner: { describeIntent: () => ({ kind: "test", commandLabel: "Test" }), + checkAdmission: () => undefined, planIntent: () => ({ kind: "test", commandLabel: "Controlled edit", @@ -428,6 +430,7 @@ function makeUnsavedMoveProvider( return { planner: { describeIntent: () => ({ kind: "move", commandLabel: "Move" }), + checkAdmission: () => undefined, planIntent: () => { const inspected = state.getCachedSegmentSnapshotHandle( move.segmentId, diff --git a/src/skeleton/edit/submit_edits.spec.ts b/src/skeleton/edit/submit_edits.spec.ts index 4eb3f76088..cca669267c 100644 --- a/src/skeleton/edit/submit_edits.spec.ts +++ b/src/skeleton/edit/submit_edits.spec.ts @@ -27,7 +27,11 @@ import { TrackableDataSelectionState } from "#src/layer/index.js"; import { SkeletonNodeSelection } from "#src/layer/segmentation/skeleton_node_selection.js"; import { SkeletonSourceConnection } from "#src/layer/segmentation/skeleton_source_connection.js"; import type { SegmentationGroupState } from "#src/segmentation_display_state/frontend.js"; -import { SkeletonEdgeDirection, type SkeletonNode } from "#src/skeleton/api.js"; +import { + KnownSkeletonNodeAttribute, + SkeletonEdgeDirection, + type SkeletonNode, +} from "#src/skeleton/api.js"; import type { SpatialSkeletonEditCommand } from "#src/skeleton/edit/edit_commands.js"; import { SpatialSkeletonActions } from "#src/skeleton/edit/edit_commands.js"; import { @@ -6307,6 +6311,114 @@ describe("skeleton edit commands", () => { expect(spatialSkeletonEditSession.commandHistory.canUndo.value).toBe(false); expect(spatialSkeletonEditSession.commandHistory.canRedo.value).toBe(false); }); + + it("a merge from a true end on an inspected skeleton is refused before the other skeleton downloads, and an edit made after it still saves", async () => { + suppressStatusMessages(); + const root: SkeletonNode = { + nodeId: 101n, + segmentId: 11n, + position: new Float32Array([1, 2, 3]), + }; + const trueEnd: SkeletonNode = { + nodeId: 102n, + segmentId: 11n, + parentNodeId: root.nodeId, + position: new Float32Array([4, 5, 6]), + attributes: { [KnownSkeletonNodeAttribute.IS_TRUE_END]: [1] }, + }; + const otherSkeletonNode: SkeletonNode = { + nodeId: 201n, + segmentId: 17n, + position: new Float32Array([7, 8, 9]), + }; + const getSkeleton = vi.fn(async () => [otherSkeletonNode]); + const mergeSkeletons = vi.fn(); + const moveNode = vi.fn().mockResolvedValue(undefined); + const { layer } = makeAddNodeTestLayer({ + initialNodes: [root, trueEnd], + segmentId: 11n, + getSkeleton, + mergeSkeletons, + moveNode, + }); + + const merge = executeSpatialSkeletonMerge( + layer as any, + trueEnd, + otherSkeletonNode, + ); + const move = executeSpatialSkeletonMoveNode(layer as any, { + node: root, + nextPositionInModelSpace: new Float32Array([10, 11, 12]), + }); + await expect(merge).rejects.toThrow( + "Cannot merge under a true end node. Clear the true end state first.", + ); + await expect(merge.acceptedByQueue).rejects.toThrow(); + await expect(move.settled).resolves.toMatchObject({ + outcome: "committed", + }); + + expect(getSkeleton).not.toHaveBeenCalled(); + expect(mergeSkeletons).not.toHaveBeenCalled(); + expect(moveNode).toHaveBeenCalledOnce(); + }); + + it("a merge from a true end is accepted while an earlier edit that clears the true end is still preparing", async () => { + const root: SkeletonNode = { + nodeId: 101n, + segmentId: 11n, + position: new Float32Array([1, 2, 3]), + }; + const trueEnd: SkeletonNode = { + nodeId: 102n, + segmentId: 11n, + parentNodeId: root.nodeId, + position: new Float32Array([4, 5, 6]), + attributes: { [KnownSkeletonNodeAttribute.IS_TRUE_END]: [1] }, + }; + const otherSkeletonNode: SkeletonNode = { + nodeId: 201n, + segmentId: 17n, + position: new Float32Array([7, 8, 9]), + }; + const toggleTrueEnd = vi.fn().mockResolvedValue(undefined); + const mergeSkeletons = vi.fn().mockResolvedValue({ + resultSegmentId: 11n, + deletedSegmentId: 17n, + directionAdjusted: false, + }); + const { layer } = makeAddNodeTestLayer({ + initialNodes: [root, trueEnd, otherSkeletonNode], + segmentId: 11n, + segmentIds: [11n, 17n], + toggleTrueEnd, + mergeSkeletons, + }); + + const clearTrueEnd = executeSpatialSkeletonNodeTrueEndUpdate(layer as any, { + node: trueEnd, + nextIsTrueEnd: false, + }); + const merge = executeSpatialSkeletonMerge( + layer as any, + trueEnd, + otherSkeletonNode, + ); + await merge.acceptedByQueue; + await expect(clearTrueEnd.settled).resolves.toMatchObject({ + outcome: "committed", + }); + await expect(merge.settled).resolves.toMatchObject({ + outcome: "committed", + }); + + expect(toggleTrueEnd).toHaveBeenCalledWith(trueEnd.nodeId, false); + expect(mergeSkeletons).toHaveBeenCalledWith( + trueEnd.nodeId, + otherSkeletonNode.nodeId, + ); + }); }); describe("skeleton edit failure messages", () => { @@ -6381,7 +6493,7 @@ describe("skeletons an edit reads", () => { [{ segmentId: 21n }], ), ); - const releaseAdmission = policy.validate("execute"); + const releaseAdmission = policy.validate("execute").release; const prepared = await policy.acquire( new AbortController().signal, "execute", @@ -6400,7 +6512,7 @@ describe("skeletons an edit reads", () => { layer, makeQueueInputCommand([]), ); - const release = policy.validate("execute"); + const release = policy.validate("execute").release; const prepared = await policy.acquire( new AbortController().signal, "execute", @@ -6417,7 +6529,7 @@ describe("skeletons an edit reads", () => { layer, makeQueueInputCommand([{ segmentId: 11n }]), ); - const release = policy.validate("execute"); + const release = policy.validate("execute").release; state.replaceCachedSegmentSnapshots([[11n, []]]); const prepared = await policy.acquire( new AbortController().signal, @@ -6437,7 +6549,7 @@ describe("skeletons an edit reads", () => { layer, makeQueueInputCommand([{ segmentId: 11n, nodeId: 12n }]), ); - const release = policy.validate("execute"); + const release = policy.validate("execute").release; expect(policy.getProtectedSegmentIds()).toEqual([11n]); state.replaceCachedSegmentSnapshots([ [11n, []], @@ -6602,9 +6714,9 @@ describe("skeletons an edit reads", () => { layer, makeQueueInputCommand([{ segmentId: 11n }], [{ segmentId: 21n }]), ); - policy.validate("execute")(); + policy.validate("execute").release(); state.evictInactiveSegmentNodes([]); - const release = policy.validate("redo"); + const release = policy.validate("redo").release; const prepared = await policy.acquire(new AbortController().signal, "redo"); expect(getSkeleton.mock.calls.map((call) => call[0])).toEqual([11n, 21n]); expect(prepared.input.segments.map(({ segmentId }) => segmentId)).toEqual([ diff --git a/src/skeleton/edit/submit_edits.ts b/src/skeleton/edit/submit_edits.ts index b08e329d1d..28c80d00e9 100644 --- a/src/skeleton/edit/submit_edits.ts +++ b/src/skeleton/edit/submit_edits.ts @@ -366,11 +366,20 @@ export function createSpatialSkeletonQueueInputPreparation( : [{ requirement, reference }]; }); let released = false; - return () => { + const release = () => { if (released) return; released = true; releaseInputReferences(bindings); }; + try { + return Object.freeze({ + input: createQueueInput(intent === "execute" ? bindings : []), + release, + }); + } catch (error) { + release(); + throw error; + } }, async acquire( signal: AbortSignal, diff --git a/src/skeleton/edit_queue/README.md b/src/skeleton/edit_queue/README.md index a44fac737b..e7503c2fc9 100644 --- a/src/skeleton/edit_queue/README.md +++ b/src/skeleton/edit_queue/README.md @@ -455,6 +455,8 @@ callback. The high-level order is: 1. Check Reload-required state, capacity, and required-source inspection; pin cached sources. + Ask the planner's `checkAdmission` whether the pinned sources already prove + that the intent cannot succeed. 2. Reserve an intent ID and stage the previewed history transition. 3. Register the description, input policy, conservative resources/dependencies, and any truthful preparation cue in the canonical journal. @@ -557,7 +559,13 @@ affected lease is released. Unknown outcomes and partial commits retain their existing Reload-required reset and lane-fencing behavior. A failure before canonical admission abandons only the newly staged history -transition and creates no Queue row or preview. History exposes only the +transition and creates no Queue row or preview. `checkAdmission` uses this to +refuse a locally invalid Execute before it can cancel later edits. The pinned +sources lack the deltas of earlier intents that are still Reserved or +Preparing, so the planner receives those intents' inputs and skips any rule +that one of them can change. For example, CATMAID refuses a merge from a true +end unless an earlier unprepared intent edits a true end. Redo is not checked. +History exposes only the operations needed by this model: `abandonLatest(ticket)`, `rollbackFrom(ticket)`, `confirm(ticket)`, and `reset()`. Confirming a discarded ticket is a no-op. diff --git a/src/skeleton/edit_queue/api.ts b/src/skeleton/edit_queue/api.ts index cc89de8b09..0b27d85ff0 100644 --- a/src/skeleton/edit_queue/api.ts +++ b/src/skeleton/edit_queue/api.ts @@ -166,6 +166,12 @@ export interface SpatialSkeletonEditRequestAttempt { export type SpatialSkeletonEditRequestMaterializationContext = SpatialSkeletonEditRequestContext; +export interface SpatialSkeletonAdmissionContext { + readonly requiredInput: SpatialSkeletonQueueInput; + /** Earlier intents whose deltas are not yet in `requiredInput`. */ + readonly unpreparedEarlierInputs: readonly TInput[]; +} + /** Provider plan boundary for one logical optimistic intent. */ export interface SpatialSkeletonEditPlanner< TInput, @@ -179,6 +185,12 @@ export interface SpatialSkeletonEditPlanner< /** Describes a complete user intent without fetching or reading topology. */ describeIntent(input: TInput): SpatialSkeletonIntentDescription; + /** Throws when the required inputs already prove that the intent cannot succeed. */ + checkAdmission( + input: TInput, + context: SpatialSkeletonAdmissionContext, + ): void; + /** Creates the exact recipe from complete inputs acquired inside the queue. */ planIntent( input: TInput, @@ -583,6 +595,7 @@ export function assertSpatialSkeletonEditPlannerRegistration( const planner = (value as { planner: Record }).planner; for (const method of [ "describeIntent", + "checkAdmission", "planIntent", "nextAttempt", "createReconciliation", diff --git a/src/skeleton/edit_queue/complete_skeleton_edits.ts b/src/skeleton/edit_queue/complete_skeleton_edits.ts index 9f7802fa2b..ca908705cb 100644 --- a/src/skeleton/edit_queue/complete_skeleton_edits.ts +++ b/src/skeleton/edit_queue/complete_skeleton_edits.ts @@ -606,6 +606,14 @@ function getSubtreeNodeIds(snapshot: CompleteSkeleton, rootNodeId: bigint) { return result; } +export function assertCanMergeUnder(node: SkeletonNode) { + if (isSkeletonNodeTrueEnd(node)) { + throw new SpatialSkeletonEditValidationError( + "Cannot merge under a true end node. Clear the true end state first.", + ); + } +} + function rerootSnapshot(snapshot: CompleteSkeleton, targetNodeId: bigint) { const target = snapshot.getNode(targetNodeId); if (target === undefined) { @@ -1032,11 +1040,7 @@ function applyMerge( delta.secondNode, mappings, ); - if (isSkeletonNodeTrueEnd(firstNode)) { - throw new SpatialSkeletonEditValidationError( - "Cannot merge under a true end node. Clear the true end state first.", - ); - } + assertCanMergeUnder(firstNode); const rerooted = rerootSnapshot(secondEntry.snapshot, secondNode.nodeId); const resultSegmentId = requireSegmentId(mappings, delta.resultSegment); const snapshot = mergeCompleteSkeletons( diff --git a/src/skeleton/edit_queue/edit_queue.spec.ts b/src/skeleton/edit_queue/edit_queue.spec.ts index 57b237cd10..94ee1bcb4e 100644 --- a/src/skeleton/edit_queue/edit_queue.spec.ts +++ b/src/skeleton/edit_queue/edit_queue.spec.ts @@ -224,6 +224,7 @@ function makeHarness( string > = { describeIntent: (input) => ({ kind: "test", commandLabel: input.name }), + checkAdmission: () => undefined, planIntent: (input, context) => ({ kind: "test", commandLabel: input.name, @@ -291,7 +292,7 @@ function pendingInputs(read = deferred()) { const signals: AbortSignal[] = []; const policy: SpatialSkeletonQueueInputPreparation = { getProtectedSegmentIds: () => [], - validate: vi.fn(() => released), + validate: vi.fn(() => ({ input: queueInput, release: released })), acquire: vi.fn(async (signal) => { signals.push(signal); await read.promise; diff --git a/src/skeleton/edit_queue/edit_queue.ts b/src/skeleton/edit_queue/edit_queue.ts index e8d7d28292..7c168d933f 100644 --- a/src/skeleton/edit_queue/edit_queue.ts +++ b/src/skeleton/edit_queue/edit_queue.ts @@ -667,7 +667,26 @@ export class SpatialSkeletonEditQueue< queueInput !== undefined && "acquire" in queueInput ? queueInput : undefined; - let releaseAdmissionInputs = inputPreparation?.validate("execute"); + const admittedInput = inputPreparation?.validate("execute"); + if (admittedInput !== undefined) { + try { + this.options.planner.checkAdmission(input!, { + requiredInput: admittedInput.input, + unpreparedEarlierInputs: this.journal + .getEntries({ includeTerminal: false }) + .filter( + ({ lifecycle }) => + lifecycle.preview === "reserved" || + lifecycle.preview === "preparing", + ) + .map(({ metadata }) => metadata.input), + }); + } catch (error) { + admittedInput.release(); + throw error; + } + } + let releaseAdmissionInputs = admittedInput?.release; const reservation = this.journal.reserveSequence(); let historyTicket: THistoryTicket | undefined; try { @@ -752,7 +771,7 @@ export class SpatialSkeletonEditQueue< intent === "redo" && inputPreparation !== undefined ) { - releaseAdmissionInputs = inputPreparation.validate("redo"); + releaseAdmissionInputs = inputPreparation.validate("redo").release; descriptor = this.options.planner.describeIntent(transitionInput); } else { if ( diff --git a/src/skeleton/edit_queue/queue_input.ts b/src/skeleton/edit_queue/queue_input.ts index f22cdd9bea..37fecfc3ce 100644 --- a/src/skeleton/edit_queue/queue_input.ts +++ b/src/skeleton/edit_queue/queue_input.ts @@ -61,20 +61,25 @@ export interface SpatialSkeletonQueueInput { readonly segments: readonly SpatialSkeletonQueueSegmentInput[]; } -/** Inputs acquired inside the queue's Preparing phase, pinned until publication. */ -export interface SpatialSkeletonPreparedQueueInput { +/** Required inputs pinned at admission, before the intent enters the queue. */ +export interface SpatialSkeletonAdmittedQueueInput { readonly input: SpatialSkeletonQueueInput; - assertCurrent(): void; release(): void; } +/** Inputs acquired inside the queue's Preparing phase, pinned until publication. */ +export interface SpatialSkeletonPreparedQueueInput + extends SpatialSkeletonAdmittedQueueInput { + assertCurrent(): void; +} + /** Reusable input policy retained with the original intent for an unprepared Redo. */ export interface SpatialSkeletonQueueInputPreparation { /** Current physical inputs that a live intent protects from visual eviction. */ getProtectedSegmentIds(): readonly bigint[]; /** Synchronous inspection gate and admission-lifetime cache retention. */ - validate(intent: "execute" | "redo"): () => void; + validate(intent: "execute" | "redo"): SpatialSkeletonAdmittedQueueInput; acquire( signal: AbortSignal, intent: "execute" | "redo", diff --git a/tests/skeleton_edit/harness/serve_mock_catmaid.ts b/tests/skeleton_edit/harness/serve_mock_catmaid.ts index d1d066f53c..de82c3b97d 100644 --- a/tests/skeleton_edit/harness/serve_mock_catmaid.ts +++ b/tests/skeleton_edit/harness/serve_mock_catmaid.ts @@ -63,7 +63,7 @@ const viewer = spawn( console.log( `\nMock CATMAID (in memory, reset on restart): ${mockServer.url}\n` + - `Open once the viewer reports it has compiled, then press E to edit:\n` + + `Open once the viewer reports it has compiled, then press shift+E to edit:\n` + `http://127.0.0.1:${viewerPort}/#!${encodeURIComponent(JSON.stringify(viewerState))}\n`, );