Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 30 additions & 1 deletion src/datasource/catmaid/spatial_skeleton_edit/edit_planner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ import type {
SpatialSkeletonEditCommand,
} from "#src/skeleton/edit/edit_commands.js";
import type {
SpatialSkeletonAdmissionContext,
SpatialSkeletonIntentCreationContext,
SpatialSkeletonEditPlanner,
SpatialSkeletonIntentPlan,
Expand All @@ -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,
Expand Down Expand Up @@ -942,6 +946,31 @@ export class CatmaidEditPlanner
super(identity);
}

checkAdmission(
input: CatmaidSpatialSkeletonCommandDescriptor,
{
requiredInput,
unpreparedEarlierInputs,
}: SpatialSkeletonAdmissionContext<CatmaidSpatialSkeletonCommandDescriptor>,
) {
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({
Expand Down
3 changes: 3 additions & 0 deletions src/skeleton/edit/spatial_skeleton_edit_session.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,7 @@ function makeRegistration(
return {
planner: {
describeIntent: () => ({ kind: "test", commandLabel: "Test" }),
checkAdmission: () => undefined,
planIntent: (_command, context) => ({
kind: "test",
commandLabel: "Test",
Expand Down Expand Up @@ -358,6 +359,7 @@ function makeHeldCommitProvider(cleanup = vi.fn()) {
return {
planner: {
describeIntent: () => ({ kind: "test", commandLabel: "Test" }),
checkAdmission: () => undefined,
planIntent: () => ({
kind: "test",
commandLabel: "Controlled edit",
Expand Down Expand Up @@ -428,6 +430,7 @@ function makeUnsavedMoveProvider(
return {
planner: {
describeIntent: () => ({ kind: "move", commandLabel: "Move" }),
checkAdmission: () => undefined,
planIntent: () => {
const inspected = state.getCachedSegmentSnapshotHandle(
move.segmentId,
Expand Down
126 changes: 119 additions & 7 deletions src/skeleton/edit/submit_edits.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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", () => {
Expand Down Expand Up @@ -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",
Expand All @@ -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",
Expand All @@ -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,
Expand All @@ -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, []],
Expand Down Expand Up @@ -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([
Expand Down
11 changes: 10 additions & 1 deletion src/skeleton/edit/submit_edits.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
10 changes: 9 additions & 1 deletion src/skeleton/edit_queue/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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.

Expand Down
13 changes: 13 additions & 0 deletions src/skeleton/edit_queue/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,12 @@ export interface SpatialSkeletonEditRequestAttempt<TEditRequest> {
export type SpatialSkeletonEditRequestMaterializationContext =
SpatialSkeletonEditRequestContext;

export interface SpatialSkeletonAdmissionContext<TInput> {
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,
Expand All @@ -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<TInput>,
): void;

/** Creates the exact recipe from complete inputs acquired inside the queue. */
planIntent(
input: TInput,
Expand Down Expand Up @@ -583,6 +595,7 @@ export function assertSpatialSkeletonEditPlannerRegistration(
const planner = (value as { planner: Record<string, unknown> }).planner;
for (const method of [
"describeIntent",
"checkAdmission",
"planIntent",
"nextAttempt",
"createReconciliation",
Expand Down
14 changes: 9 additions & 5 deletions src/skeleton/edit_queue/complete_skeleton_edits.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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(
Expand Down
3 changes: 2 additions & 1 deletion src/skeleton/edit_queue/edit_queue.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,7 @@ function makeHarness(
string
> = {
describeIntent: (input) => ({ kind: "test", commandLabel: input.name }),
checkAdmission: () => undefined,
planIntent: (input, context) => ({
kind: "test",
commandLabel: input.name,
Expand Down Expand Up @@ -291,7 +292,7 @@ function pendingInputs(read = deferred<void>()) {
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;
Expand Down
Loading
Loading