Skip to content
Merged
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
164 changes: 124 additions & 40 deletions apps/server/src/orchestration-v2/Orchestrator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,7 @@ import {
subagentResultForRun,
delegatedTaskProgress,
delegatedTaskReportRuns,
monitorUpdateRunIds,
subagentThreadTitle,
} from "@t3tools/provider-core/server/subagentProjection";
import {
Expand Down Expand Up @@ -1286,6 +1287,41 @@ function runForSourcePoint(
}
}

const DELEGATED_CHILD_RUN_WINDOW = 20;

type DelegatedChildControls = ProjectionRecords<
"runs" | "messages" | "subagents" | "providerThreads"
> & {
/** Set when `runs` holds only what ran since this run, plus older unfinished and task runs. */
readonly runsFloor?: OrchestrationV2Run | undefined;
};

function ranSince(run: OrchestrationV2Run, floor: OrchestrationV2Run): boolean {
return run.id === floor.id || runRanAfter(run, floor);
}

/** The walk back to a report is exact when it stops at a run that ran since the floor. */
function reportRunsRead(
controls: DelegatedChildControls,
run: OrchestrationV2Run,
reportRuns: ReadonlyArray<OrchestrationV2Run>,
): boolean {
const floor = controls.runsFloor;
if (floor === undefined || run.status !== "completed") return true;
const oldest = reportRuns.at(-1) ?? run;
if (!ranSince(oldest, floor)) return false;
const monitorRuns = monitorUpdateRunIds(controls.messages);
return controls.runs.some(
(candidate) =>
candidate.id !== run.id &&
candidate.startedAt !== null &&
candidate.status !== "rolled_back" &&
!monitorRuns.has(candidate.id) &&
runRanAfter(oldest, candidate) &&
ranSince(candidate, floor),
);
}

function providerThreadForRun(
projection: Pick<OrchestrationV2ThreadProjection, "providerThreads">,
run: OrchestrationV2Run,
Expand Down Expand Up @@ -14621,23 +14657,24 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
// A finished delegate otherwise keeps its provider process until the idle timeout. Callers hold
// the parent lock; the child lock orders this after any follow-up that started a run meanwhile.
const releaseFinishedDelegateSessions = Effect.fn("Orchestrator.releaseFinishedDelegateSessions")(
function* (childThreadId: ThreadId, resultRunId: RunId) {
function* (childThreadId: ThreadId, resultRunId: RunId, taskId: NodeId) {
yield* threadDispatch.withLock(
childThreadId,
Effect.gen(function* () {
const child = yield* projectionStore.getThreadRecords(
childThreadId,
["runs", "messages", "subagents", "providerThreads", "providerSessions"],
{ messageRoles: ["user"] },
);
const { controls: child, progress } = yield* readDelegatedChildControls(childThreadId, [
taskId,
]);
// Unawaited background tasks still allow a result but die with the process; the idle
// timer keeps their process pinned.
if (
delegatedTaskProgress(child).state !== "result_available" ||
progress.state !== "result_available" ||
child.providerThreads.some((thread) => (thread.pendingBackgroundTasks ?? []).length > 0)
)
return;
for (const session of child.providerSessions) {
const { providerSessions } = yield* projectionStore.getThreadRecords(childThreadId, [
"providerSessions",
]);
for (const session of providerSessions) {
// Shared processes unload their threads themselves; only a per-thread process lingers.
if (
session.status === "stopped" ||
Expand All @@ -14663,15 +14700,39 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
),
);

const readAllDelegatedChildControls = (childThreadId: ThreadId) =>
projectionStore.getThreadRecords(
childThreadId,
["runs", "messages", "subagents", "providerThreads"],
{ messageRoles: ["user"], delegatedTaskMessagesOnly: true },
);

const readDelegatedChildControls = Effect.fn("Orchestrator.readDelegatedChildControls")(
function* (childThreadId: ThreadId, taskIds: ReadonlyArray<NodeId>) {
const controls: DelegatedChildControls = yield* projectionStore.getDelegatedChildControls(
childThreadId,
{ taskIds, windowSize: DELEGATED_CHILD_RUN_WINDOW },
);
const progress = delegatedTaskProgress(controls);
// The latest result may have ended before the runs read above; then read them all.
if (
controls.runsFloor !== undefined &&
(progress.resultRun === undefined || !ranSince(progress.resultRun, controls.runsFloor))
) {
const all = yield* readAllDelegatedChildControls(childThreadId);
return { controls: all, progress: delegatedTaskProgress(all) };
}
return { controls, progress };
},
);

/**
* Callers must hold the parent thread's dispatch lock: wake-policy updates the same
* subagent row with full-row payloads, so unserialized writers clobber policy or terminal status.
*/
const finalizeAppOwnedSubagentTask = Effect.fn("Orchestrator.finalizeAppOwnedSubagentTask")(
function* (
childControls: ProjectionRecords<
"runs" | "messages" | "subagents" | "providerThreads" | "providerTurns" | "attempts"
>,
childControls: DelegatedChildControls,
options: {
readonly settledContinuationOf?: RunId;
readonly syncRunId?: RunId;
Expand Down Expand Up @@ -14776,23 +14837,45 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
}

// A run queued behind the report can end the task without saying anything.
const reportRuns = delegatedTaskReportRuns(childControls, { ...childRun, status: outcome });
const reportFrom = { ...childRun, status: outcome };
let reportRuns = delegatedTaskReportRuns(childControls, reportFrom);
if (!reportRunsRead(childControls, reportFrom, reportRuns)) {
reportRuns = delegatedTaskReportRuns(
yield* readAllDelegatedChildControls(childThreadId),
reportFrom,
);
}
const resultRunIds = [childRun.id, ...reportRuns.map((run) => run.id)];
const childResult = yield* projectionStore.getThreadRecords(
childThreadId,
["messages", "turnItems"],
["messages", "turnItems", "providerTurns", "attempts"],
{
messageRoles: ["assistant"],
messageRunIds: resultRunIds,
turnItemRunIds: resultRunIds,
turnItemTypes: ["assistant_message", "error", "system_notice"],
providerTurnAttemptIds: [childRun, ...reportRuns].flatMap(
(run) => run.activeAttemptId ?? [],
),
attemptIds: childRun.activeAttemptId === null ? [] : [childRun.activeAttemptId],
},
);
// A steered run's attempt can point at a provider turn that another attempt started.
const attemptTurnId = childResult.attempts[0]?.providerTurnId;
const steeredTurns =
attemptTurnId == null ||
childResult.providerTurns.some((turn) => turn.runAttemptId === childRun.activeAttemptId)
? []
: (yield* projectionStore.getThreadRecords(childThreadId, ["providerTurns"], {
providerTurnIds: [attemptTurnId],
})).providerTurns;
const childProjection = {
...childControls,
runs: reportRuns,
messages: childResult.messages,
turnItems: childResult.turnItems,
providerTurns: [...childResult.providerTurns, ...steeredTurns],
attempts: childResult.attempts,
};
const parentThreadId = childControls.thread.lineage.parentThreadId;
// The task's node and turn item share its id.
Expand Down Expand Up @@ -14957,7 +15040,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
},
];
yield* writeSystemEvents(completionEvents, [], { updateDelegatedCompletionOnly: true });
yield* releaseFinishedDelegateSessions(childThreadId, childRun.id);
yield* releaseFinishedDelegateSessions(childThreadId, childRun.id, task.id);

if (completionPlan.offer && completionPlan.parentRun !== undefined) {
yield* offerDelegatedCompletionDelivery(parentThreadId, completionPlan.parentRun.id);
Expand All @@ -14978,41 +15061,41 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
childThreadId: ThreadId,
options?: { readonly settledContinuationOf?: RunId; readonly syncRunId?: RunId },
) {
const childControls = yield* projectionStore.getThreadRecords(
childThreadId,
["runs", "messages", "subagents", "providerThreads", "providerTurns", "attempts"],
{ messageRoles: ["user"] },
);
const parentThreadId = childControls.thread.lineage.parentThreadId;
const child = yield* projectionStore.getThreadRecords(childThreadId, ["contextTransfers"]);
const parentThreadId = child.thread.lineage.parentThreadId;
const forkedFrom = child.thread.forkedFrom;
if (
childControls.thread.lineage.relationshipToParent !== "subagent" ||
child.thread.lineage.relationshipToParent !== "subagent" ||
parentThreadId === null ||
childControls.thread.forkedFrom?.type !== "node"
forkedFrom?.type !== "node"
)
return;
const progress = delegatedTaskProgress(childControls);
// Each task of this child names it, so the parent's other tasks stay unread.
const parent = yield* projectionStore.getThreadRecords(parentThreadId, ["subagents"], {
subagentChildThreadIds: [childThreadId],
});
const { contextTransfers } = yield* projectionStore.getThreadRecords(childThreadId, [
"contextTransfers",
]);
for (const task of parent.subagents) {
const resultSent = child.contextTransfers.some(
(transfer) =>
transfer.type === "subagent_result" &&
transfer.sourceThreadId === childThreadId &&
transfer.targetThreadId === parentThreadId,
);
const openTasks = parent.subagents.filter(
(task) =>
task.origin === "app_owned" &&
task.childThreadId === childThreadId &&
!(task.result !== null && resultSent),
);
const { controls: childControls, progress } = yield* readDelegatedChildControls(
childThreadId,
openTasks.map((task) => task.id),
);
for (const task of openTasks) {
// A cancelled task does not wait for the work its cancel is stopping.
const cancelled = task.cancelledRunId !== undefined;
if (
task.origin !== "app_owned" ||
task.childThreadId !== childThreadId ||
(task.id === childControls.thread.forkedFrom.nodeId &&
(cancelled ? progress.state === "working" : progress.state !== "result_available")) ||
(task.result !== null &&
contextTransfers.some(
(transfer) =>
transfer.type === "subagent_result" &&
transfer.sourceThreadId === childThreadId &&
transfer.targetThreadId === parentThreadId,
))
task.id === forkedFrom.nodeId &&
(cancelled ? progress.state === "working" : progress.state !== "result_available")
)
continue;
yield* finalizeAppOwnedSubagentTask(childControls, {
Expand All @@ -15025,7 +15108,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
// Only the run a cancelled task settled from ends with it. The row read above has no
// such run yet when this call settled the task, from the same result run.
const { resultRun } = progress;
const resultTaskId = resultRun?.delegatedTaskId ?? childControls.thread.forkedFrom.nodeId;
const resultTaskId = resultRun?.delegatedTaskId ?? forkedFrom.nodeId;
const resultTask = parent.subagents.find((task) => task.id === resultTaskId);
const taskCancelled =
resultTask?.cancelledRunId !== undefined && resultTask.cancelledRunId === resultRun?.id;
Expand Down Expand Up @@ -15064,7 +15147,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
run =
previousRunId === undefined
? undefined
: childControls.runs.find((candidate) => candidate.id === previousRunId);
: (childControls.runs.find((candidate) => candidate.id === previousRunId) ??
(yield* projectionStore.getRun(childThreadId, previousRunId)));
}
for (const request of pendingQuestions) {
if (
Expand Down
86 changes: 76 additions & 10 deletions apps/server/src/orchestration-v2/ProjectionStore.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1385,6 +1385,7 @@ it.effect("record reads filter notification sources without dropping matching me
["monitor", "user", "monitor"],
["system", "user", "system"],
["assistant-monitor", "assistant", "monitor"],
["wake", "user", "wake"],
] as const) {
yield* store.apply({
id: EventId.make(`notification-filter:${id}`),
Expand All @@ -1406,13 +1407,21 @@ it.effect("record reads filter notification sources without dropping matching me
updatedAt: now,
...(kind === null
? {}
: {
notification: {
source: { kind },
outcome: "updated",
summary: "Background notification",
},
}),
: kind === "wake"
? {
delegatedCompletion: {
parentRunId: RunId.make("run:wake-parent"),
generation: 1,
taskIds: [],
},
}
: {
notification: {
source: { kind },
outcome: "updated",
summary: "Background notification",
},
}),
},
});
}
Expand All @@ -1424,11 +1433,19 @@ it.effect("record reads filter notification sources without dropping matching me
matching.messages.map((message) => [message.id, message.text]),
[["monitor", "Complete body for monitor"]],
);
const delegatedTaskMessages = yield* store.getThreadRecords(threadId, ["messages"], {
messageRoles: ["user"],
delegatedTaskMessagesOnly: true,
});
assert.deepEqual(
delegatedTaskMessages.messages.map((message) => message.id),
["monitor", "wake"],
);
const { statements, tracer } = traceSqlStatements();
const userMessages = yield* store
.getThreadRecords(threadId, ["messages"], { messageRoles: ["user"] })
.pipe(Effect.withTracer(tracer));
assert.lengthOf(userMessages.messages, 3);
assert.lengthOf(userMessages.messages, 4);
const ordinalLookup = statements.find((statement) => statement.includes("MIN(ordinal)"));
// User-only reads must seek the message-ordinal index instead of scanning every turn item.
yield* assertReadsThroughMessageOrdinalIndex(ordinalLookup, ["thread_id=?", "<expr>=?"]);
Expand All @@ -1442,7 +1459,7 @@ it.effect("record reads filter notification sources without dropping matching me
.pipe(Effect.withTracer(withItems.tracer));
assert.deepEqual(ordered.messages, userMessages.messages);
assert.isFalse(withItems.statements.some((statement) => statement.includes("MIN(ordinal)")));
assert.lengthOf((yield* store.getThreadRecords(threadId, ["messages"])).messages, 4);
assert.lengthOf((yield* store.getThreadRecords(threadId, ["messages"])).messages, 5);
assert.lengthOf(
(yield* store.getThreadRecords(threadId, ["messages"], {
monitorNotificationsOnly: true,
Expand All @@ -1453,7 +1470,56 @@ it.effect("record reads filter notification sources without dropping matching me
(yield* store.getThreadRecords(threadId, ["messages"], {
monitorNotificationsOnly: false,
})).messages,
4,
5,
);
}).pipe(Effect.provide(layerTest)),
);

it.effect("reads a delegated child's recent, unfinished and task runs without its history", () =>
Effect.gen(function* () {
const store = yield* ProjectionStore.ProjectionStoreV2;
const threadId = yield* addRolledBackRecoveryCandidate("delegated-child-runs");
const first = (yield* store.getThreadRecords(threadId, ["runs"])).runs[0]!;
const at = (minutes: number) => DateTime.add(first.requestedAt, { minutes: minutes + 60 });
const id = (ordinal: number) => RunId.make(`run:delegated-child-runs:${ordinal}`);
const unstartedCancel = { status: "cancelled", startedAt: null } as const;
for (const [ordinal, patch] of [
[3, { status: "running", completedAt: null }],
// Unstarted cancelled runs are outside the window's index: one ends after the floor.
[4, { ...unstartedCancel, completedAt: at(20) }],
[5, { ...unstartedCancel, completedAt: at(1) }],
...[2, 6, 7, 8, 9, 10, 11, 12].map((ordinal) => [ordinal, {}] as const),
] as const) {
yield* store.apply({
id: EventId.make(`event:delegated-child-runs:${ordinal}`),
type: "run.created",
threadId,
runId: id(ordinal),
occurredAt: first.requestedAt,
payload: {
...first,
id: id(ordinal),
ordinal,
status: "completed",
startedAt: at(ordinal),
completedAt: at(ordinal),
delegatedTaskId: NodeId.make(`node:delegated-child-runs:task:${ordinal}`),
...patch,
},
});
}
const taskIds = [NodeId.make("node:delegated-child-runs:task:2")];
const bounded = yield* store.getDelegatedChildControls(threadId, { taskIds, windowSize: 3 });
assert.equal(bounded.runsFloor?.id, id(11));
assert.deepEqual(
bounded.runs.map((run) => run.id),
[2, 3, 4, 11, 12].map(id),
);
const whole = yield* store.getDelegatedChildControls(threadId, { taskIds, windowSize: 100 });
assert.isUndefined(whole.runsFloor);
assert.deepEqual(
whole.runs.map((run) => run.id),
(yield* store.getThreadRecords(threadId, ["runs"])).runs.map((run) => run.id),
);
}).pipe(Effect.provide(layerTest)),
);
Expand Down
Loading
Loading