Skip to content

Commit f63e671

Browse files
j5codecodex
authored andcommitted
Recover missed owner archives and interrupt only their recorded holder turn
1 parent 6d74cb4 commit f63e671

3 files changed

Lines changed: 118 additions & 43 deletions

File tree

‎apps/server/src/j5/playbooks/PlaybookCrewRelay.test.ts‎

Lines changed: 55 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { assert, it } from "@effect/vitest";
44
import {
55
CommandId,
66
ProviderInstanceId,
7+
RunId,
78
ThreadId,
89
type OrchestrationV2Command,
910
type OrchestrationV2StoredEvent,
@@ -130,30 +131,35 @@ const fixture = Effect.gen(function* () {
130131
const dispatched = yield* Ref.make<ReadonlyArray<OrchestrationV2Command>>([]);
131132
const threads = ThreadManagementService.of({
132133
getThreadRecords: (id: ThreadId) =>
133-
Ref.get(archived).pipe(
134-
Effect.flatMap((ids) =>
135-
[owner, peer, crewMember, foreign].includes(id)
136-
? Ref.get(ownerPlan).pipe(
137-
Effect.map((plan) => {
138-
const result = projection(id, ids.has(id));
139-
return {
140-
...result,
141-
thread: {
142-
...result.thread,
143-
interactionMode:
144-
plan && id === owner ? ("plan" as const) : ("default" as const),
145-
},
146-
};
147-
}),
148-
)
149-
: Effect.fail(
150-
new OrchestratorProjectionError({
151-
threadId: id,
152-
cause: new ProjectionStoreThreadNotFoundError({ threadId: id }),
153-
}),
154-
),
155-
),
156-
),
134+
Effect.gen(function* () {
135+
if (![owner, peer, crewMember, foreign].includes(id))
136+
return yield* new OrchestratorProjectionError({
137+
threadId: id,
138+
cause: new ProjectionStoreThreadNotFoundError({ threadId: id }),
139+
});
140+
const result = projection(id, (yield* Ref.get(archived)).has(id));
141+
const plan = yield* Ref.get(ownerPlan);
142+
const notice = (yield* Ref.get(dispatched)).findLast(
143+
(item) => item.type === "message.dispatch" && item.threadId === id,
144+
);
145+
return {
146+
...result,
147+
runs:
148+
notice?.type === "message.dispatch"
149+
? [
150+
{
151+
id: RunId.make("run:" + notice.messageId),
152+
userMessageId: notice.messageId,
153+
status: "running",
154+
},
155+
]
156+
: [],
157+
thread: {
158+
...result.thread,
159+
interactionMode: plan && id === owner ? ("plan" as const) : ("default" as const),
160+
},
161+
};
162+
}),
157163
dispatch: (command: OrchestrationV2Command) =>
158164
Effect.gen(function* () {
159165
if (yield* Ref.get(fault))
@@ -789,12 +795,31 @@ it.effect(
789795
}
790796
}
791797
assert.equal(
792-
(yield* Ref.get(dispatched)).filter((item) => item.type === "thread.stop").length,
798+
(yield* Ref.get(dispatched)).filter((item) => item.type === "run.interrupt").length,
793799
4,
794800
);
795801
}).pipe(Effect.scoped, Effect.provide(TestLayer)),
796802
);
797803

804+
it.effect("boot recovers an archive followed by unarchive before the notifier saw it", () =>
805+
Effect.gen(function* () {
806+
const { start, relay, store, sql } = yield* fixture;
807+
const run = yield* start("original", peerId);
808+
for (const [index, type] of ["thread.archived", "thread.unarchived"].entries()) {
809+
yield* sql`INSERT INTO orchestration_events
810+
(event_id, aggregate_kind, stream_id, stream_version, event_type, occurred_at,
811+
actor_kind, payload_json, metadata_json, application_event_version)
812+
VALUES (${type}, 'thread', ${owner}, ${index + 1}, ${type}, ${run.createdAt},
813+
'system', '{}', '{}', 2)`;
814+
}
815+
yield* relay.reconcileOwners();
816+
assert.equal((yield* store.runById(run.runId))?.cancelReason, "owner_archived");
817+
const replacement = yield* start("replacement", peerId);
818+
yield* relay.reconcileOwners();
819+
assert.equal((yield* store.runById(replacement.runId))?.status, "active");
820+
}).pipe(Effect.scoped, Effect.provide(TestLayer)),
821+
);
822+
798823
it.effect("a delayed archive reconciles its owner without cancelling a replacement run", () =>
799824
Effect.gen(function* () {
800825
const { start, store, relay, root, sql, dispatched } = yield* fixture;
@@ -808,7 +833,7 @@ it.effect("a delayed archive reconciles its owner without cancelling a replaceme
808833
yield* sql`UPDATE orchestration_v2_projection_threads SET archived_at = ${at} WHERE thread_id = ${owner}`;
809834
assert.equal((yield* store.current(owner, original.runId)).status, "cancelled");
810835
yield* sql`UPDATE orchestration_v2_projection_threads SET archived_at = NULL WHERE thread_id = ${owner}`;
811-
const replacement = yield* start("replacement");
836+
const replacement = yield* start("replacement", peerId);
812837
const unrelated = yield* store.start(foreign, root, "review", "unrelated");
813838
yield* sql`UPDATE orchestration_v2_projection_threads SET archived_at = ${at} WHERE thread_id = ${foreign}`;
814839

@@ -822,8 +847,10 @@ it.effect("a delayed archive reconciles its owner without cancelling a replaceme
822847
assert.equal((yield* store.runById(unrelated.runId))?.status, "active");
823848
assert.equal((yield* store.runById(original.runId))?.holderStop?.status, "already_idle");
824849
assert.equal(
825-
(yield* Ref.get(dispatched)).filter((item) => item.type === "thread.stop").length,
826-
1,
850+
(yield* Ref.get(dispatched)).filter(
851+
(item) => item.type === "thread.stop" || item.type === "run.interrupt",
852+
).length,
853+
0,
827854
);
828855
}).pipe(Effect.scoped, Effect.provide(TestLayer)),
829856
);

‎apps/server/src/j5/playbooks/PlaybookCrewRelay.ts‎

Lines changed: 40 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,10 @@ import { ThreadManagementService } from "../../orchestration-v2/ThreadManagement
1414
import { AgentCrewInstanceService } from "../a2a/AgentCrewInstanceService.ts";
1515
import { participantIdForThread } from "../a2a/HomeRegistrar.ts";
1616
import { stopThread, agentStopReason } from "../a2a/stopThread.ts";
17-
import { exceededDispatchModeLimit } from "../../orchestration-v2/DispatchModeLimit.ts";
17+
import {
18+
DispatchModeLimit,
19+
exceededDispatchModeLimit,
20+
} from "../../orchestration-v2/DispatchModeLimit.ts";
1821
import { lifecycleCommandId, lifecycleId } from "../a2a/spawnIds.ts";
1922
import { getThreadRecordsIfPresent } from "../a2a/threadProjectionReads.ts";
2023
import { crewStepNoticeText } from "./crewStepNotice.ts";
@@ -75,6 +78,7 @@ export const makePlaybookCrewRelay = Effect.gen(function* () {
7578

7679
const finishCancellation = Effect.fn("PlaybookCrewRelay.finishCancellation")(function* (
7780
runId: string,
81+
immediate = false,
7882
) {
7983
const run = yield* store.runById(runId);
8084
if (run === null || run.status !== "cancelled" || !(yield* store.claimHolderStop(runId)))
@@ -106,19 +110,37 @@ export const makePlaybookCrewRelay = Effect.gen(function* () {
106110
status: "failed" as const,
107111
reason: "The holder runs above the owner's runtime or interaction mode.",
108112
};
109-
const stopped = yield* stopThread(
110-
threads,
111-
{
112-
commandId: lifecycleCommandId({
113-
providerSessionId: "j5-playbook-cancel",
114-
requestKey: runId,
115-
operation: "stop-holder",
116-
}),
117-
threadId: run.holderThreadId,
118-
reason: agentStopReason("Playbook cancelled"),
119-
},
120-
limit,
121-
);
113+
const command = {
114+
commandId: lifecycleCommandId({
115+
providerSessionId: "j5-playbook-cancel",
116+
requestKey: runId,
117+
operation: "stop-holder",
118+
}),
119+
threadId: run.holderThreadId,
120+
reason: agentStopReason("Playbook cancelled"),
121+
};
122+
// An explicit cancel stops the holder. Lifecycle events and retries may
123+
// arrive after it has taken on unrelated work, including delegated tasks.
124+
const stopped = immediate
125+
? yield* stopThread(threads, command, limit)
126+
: yield* Effect.gen(function* () {
127+
const landing = yield* store.latestLanding(runId, run.currentStepId);
128+
if (landing?.targetThreadId !== command.threadId) return null;
129+
const notice = stepMessageId(runId, landing.requestId);
130+
const { runs } = yield* threads.getThreadRecords(command.threadId, ["runs"], {
131+
runStatuses: ["preparing", "starting", "running"],
132+
});
133+
const turn = runs.find((entry) => entry.userMessageId === notice);
134+
if (!turn) return null;
135+
return yield* threads
136+
.dispatch({
137+
...command,
138+
type: "run.interrupt",
139+
runId: turn.id,
140+
})
141+
.pipe(Effect.provideService(DispatchModeLimit, limit));
142+
});
143+
if (stopped === null) return { status: "already_idle" as const, reason: null };
122144
const interrupted = stopped.storedEvents.some(
123145
({ event }) =>
124146
(event.type === "run.updated" && event.payload.status === "interrupted") ||
@@ -325,7 +347,10 @@ export const makePlaybookCrewRelay = Effect.gen(function* () {
325347
yield* drainLocked(run.runId);
326348
const response = yield* store.mutate(owner, input);
327349
if (input.operation === "cancel") {
328-
yield* finishCancellation(run.runId);
350+
yield* finishCancellation(
351+
run.runId,
352+
!response.replayed && response.cancelReason === "agent_cancelled",
353+
);
329354
return withDelivery(
330355
{ ...(yield* store.current(owner, run.runId)), replayed: response.replayed },
331356
null,

‎apps/server/src/j5/playbooks/PlaybookStore.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1124,6 +1124,29 @@ export const makePlaybookStore = Effect.gen(function* () {
11241124
}, Effect.mapError(storageError));
11251125
const unreconciledCancellations = Effect.fn("PlaybookStore.unreconciledCancellations")(
11261126
function* () {
1127+
// The daemon subscribes at the current high-water mark. An unarchive can
1128+
// already have hidden a missed archive in the owner's projection.
1129+
const missed = yield* sql<{
1130+
run_id: string;
1131+
owner_thread_id: string;
1132+
event_type: "thread.archived" | "thread.deleted";
1133+
}>`SELECT run.run_id, run.owner_thread_id, event.event_type
1134+
FROM j5_playbook_run run
1135+
JOIN orchestration_events event ON event.sequence = (
1136+
SELECT lifecycle.sequence FROM orchestration_events lifecycle
1137+
WHERE lifecycle.aggregate_kind = 'thread' AND lifecycle.stream_id = run.owner_thread_id
1138+
AND lifecycle.sequence > run.start_event_sequence
1139+
AND (run.start_event_sequence <> 0 OR lifecycle.occurred_at >= run.created_at)
1140+
AND lifecycle.event_type IN ('thread.archived', 'thread.deleted')
1141+
AND lifecycle.application_event_version = 2
1142+
ORDER BY lifecycle.sequence LIMIT 1)
1143+
WHERE run.status = 'active'`;
1144+
for (const row of missed)
1145+
yield* cancelOwner(
1146+
ThreadId.make(row.owner_thread_id),
1147+
row.event_type === "thread.archived" ? "owner_archived" : "owner_deleted",
1148+
row.run_id,
1149+
);
11271150
yield* cancelOrphans();
11281151
return (yield* sql<RunRow>`SELECT * FROM j5_playbook_run WHERE status = 'cancelled' AND holder_stop_json IS NULL AND cancel_reason IN ('owner_archived', 'owner_deleted', 'agent_cancelled')`).map(
11291152
fromRow,

0 commit comments

Comments
 (0)