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
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
import { checkpointWorkspace } from "@t3tools/provider-testing/replayWorkspace";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Queue from "effect/Queue";
Expand Down Expand Up @@ -52,6 +53,7 @@ const runDelegation = (input: {
Effect.gen(function* () {
const cwd = yield* checkpointWorkspace(input.name);
let armed = false;
const failedRead = Deferred.makeUnsafe<void>();
const turns: Array<{
readonly turn: ProviderAdapter.ProviderAdapterV2TurnInput;
readonly events: Queue.Queue<ProviderAdapter.ProviderAdapterV2Event>;
Expand Down Expand Up @@ -153,6 +155,7 @@ const runDelegation = (input: {
(yield* input.failRead({ store, threadId, fields, filter }))
) {
armed = false;
yield* Deferred.succeed(failedRead, undefined);
return yield* new ProjectionStore.ProjectionStoreReadError({ threadId });
}
return yield* store.getThreadRecords(threadId, fields, filter);
Expand Down Expand Up @@ -265,6 +268,11 @@ const runDelegation = (input: {
}

armed = true;
const parentWake = input.parentEndsFirst
? yield* watch(
(event) => event.type === "message.updated" && event.threadId === parentThreadId,
)
: undefined;
const childFailed = yield* watch(
(event) =>
event.type === "run.updated" &&
Expand All @@ -276,12 +284,19 @@ const runDelegation = (input: {
yield* TestClock.adjust("1 second");
}
yield* Fiber.join(childFailed);
if (input.parentEndsFirst && input.failRead !== undefined) {
yield* Deferred.await(failedRead);
}

if (!input.parentEndsFirst) yield* endParentTurn;
for (let attempt = 0; attempt < 5; attempt++) {
yield* worker.drain();
yield* TestClock.adjust("30 seconds");
}
if (parentWake !== undefined) {
yield* Fiber.join(parentWake);
yield* worker.drain();
}

assert.isFalse(armed, "the injected read failed once");
const parent = yield* orchestrator.getThreadProjection(parentThreadId);
Expand Down
59 changes: 50 additions & 9 deletions apps/server/src/orchestration-v2/Orchestrator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,7 @@ import {
import { planThreadDeletion } from "./ThreadDeletion.ts";
import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
import * as ServerSettings from "../serverSettings.ts";
import * as ServiceChangeAdmission from "../serviceChangeAdmission.ts";

const isMessageQuestionAnswer = Schema.is(
Schema.Union([TrimmedNonEmptyString, Schema.NonEmptyArray(TrimmedNonEmptyString)]),
Expand Down Expand Up @@ -3980,7 +3981,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
left.afterRunOrdinal - right.afterRunOrdinal || left.item.ordinal - right.item.ordinal,
);
for (const { run, message, steer, afterRunOrdinal } of placed) {
yield* dispatchWithReceiptEffect({
yield* dispatchWithAdmission({
type: "message.dispatch",
commandId: CommandId.make(`command:unread-steer:${run.id}:${message.id}`),
threadId,
Expand Down Expand Up @@ -16444,7 +16445,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
session.capabilities.sessions.supportsMultipleProviderThreadsPerSession
)
continue;
yield* dispatchWithReceiptEffect({
yield* dispatchWithAdmission({
type: "provider-session.detach",
commandId: CommandId.make(
`command:system:delegated-task-release:${resultRunId}:${session.id}`,
Expand Down Expand Up @@ -16947,7 +16948,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
node.id === request.nodeId && node.runId !== null && resultRunIds.has(node.runId),
)
) {
yield* dispatchWithReceipt({
yield* dispatchWithReceiptWithAdmission({
type: "thread.user-input.dismiss",
commandId: CommandId.make(`command:system:delegated-task-question:${request.id}`),
threadId: childThreadId,
Expand Down Expand Up @@ -18031,6 +18032,27 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
} satisfies OrchestratorV2DispatchResult;
}, withCommandMetrics);

const dispatchWithAdmission = Effect.fnUntraced(function* (
command: OrchestrationV2ServerCommand,
sideChatIds: ReadonlyArray<ThreadId> = [],
cancelledTask?: OrchestrationV2Subagent,
): Effect.fn.Return<OrchestratorV2DispatchResult, OrchestratorV2Error> {
return yield* ServiceChangeAdmission.withAdmissionAt(
config.baseDir,
dispatchWithReceiptEffect(command, sideChatIds, cancelledTask),
Comment thread
chrisohearn marked this conversation as resolved.
Resolved
Comment thread
chrisohearn marked this conversation as resolved.
Resolved
).pipe(
Effect.mapError((cause) =>
ServiceChangeAdmission.isServiceChangeAdmissionError(cause)
? new OrchestratorCommandRejectedError({
commandId: command.commandId,
commandType: command.type,
cause,
})
: cause,
),
);
});

// Follow-up intake and Stop serialize on the parent before taking the child lock.
const withSubagentParentLock = <A, E, R>(threadId: ThreadId, dispatch: Effect.Effect<A, E, R>) =>
appOwnedSubagentParentThreadId(threadId).pipe(
Expand Down Expand Up @@ -18102,6 +18124,25 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
: dispatch;
});

const dispatchWithReceiptWithAdmission = Effect.fnUntraced(function* (
command: OrchestrationV2ServerCommand,
): Effect.fn.Return<OrchestratorV2DispatchResult, OrchestratorV2Error> {
return yield* ServiceChangeAdmission.withAdmissionAt(
config.baseDir,
dispatchWithReceipt(command),
).pipe(
Effect.mapError((cause) =>
ServiceChangeAdmission.isServiceChangeAdmissionError(cause)
? new OrchestratorCommandRejectedError({
commandId: command.commandId,
commandType: command.type,
cause,
})
: cause,
),
);
});

const parentTaskSyncRetries = yield* FiberSet.make();
const syncDelegatedParentTask = Effect.fn("Orchestrator.syncDelegatedParentTask")(function* (
childThreadId: ThreadId,
Expand Down Expand Up @@ -18296,7 +18337,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
(left.queuePosition ?? left.ordinal) - (right.queuePosition ?? right.ordinal),
);
for (const queued of pending) {
yield* dispatchWithReceiptEffect({
yield* dispatchWithAdmission({
type: "queued-message.promote-to-steer",
commandId: CommandId.make(
`command:deferred-steer:${queued.id}:${run.id}:${turn.runAttemptId}`,
Expand Down Expand Up @@ -18611,8 +18652,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
// Hold intake closed until descendants stop and this thread's Stop commits.
yield* input.stopDescendants((command) =>
commandThreadId(command) === input.command.threadId
? dispatchWithReceiptEffect(command)
: dispatchWithReceipt(command),
? dispatchWithAdmission(command)
: dispatchWithReceiptWithAdmission(command),
);
const child = yield* projectionStore
.getThreadRecords(
Expand All @@ -18639,7 +18680,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
? { ...task, cancelledRunId: cancelledRun.id, updatedAt: now }
: undefined;
// The marker, Stop receipt and interrupt outbox commit together under both locks.
yield* dispatchWithReceiptEffect(command, [], cancelledTask);
yield* dispatchWithAdmission(command, [], cancelledTask);
}),
);
yield* finalizeAppOwnedSubagent(command.threadId).pipe(mapDispatchError(command));
Expand All @@ -18664,7 +18705,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
awaitRestartContinuation: Effect.fn("OrchestratorV2.awaitRestartContinuation")(function (run) {
return effectOutbox.awaitSettled(`effect:restart-continuation:${run.id}`).pipe(Effect.ignore);
}),
dispatch: dispatchWithReceipt,
dispatch: dispatchWithReceiptWithAdmission,
skipProviderFailover: Effect.fn("OrchestratorV2.skipProviderFailover")(function (input) {
return threadDispatch.withLock(
input.threadId,
Expand Down Expand Up @@ -18702,7 +18743,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
const command = { type: "thread.metadata.update", ...input } as const;
// A Stop that reached the run before its limit failure landed had nothing to disarm.
const stopped = yield* stopReachedRun(command, input.threadId, input.limitRecovery.runId);
yield* dispatchWithReceiptEffect(
yield* dispatchWithAdmission(
stopped
? {
...command,
Expand Down
6 changes: 6 additions & 0 deletions apps/server/src/orchestration-v2/ThreadFork.execution.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -444,6 +444,7 @@ it.effect.each([
"a $execution fork's first /compact is rejected only when no history reaches it: $rejected",
({ execution, rejected }) => {
const opened: Array<ProviderInstanceId> = [];
const openedSession = Deferred.makeUnsafe<void>();
const adapter = (driverName: "claudeAgent" | "codex") => {
const driver = ProviderDriverKind.make(driverName);
const instanceId = ProviderInstanceId.make(driverName);
Expand All @@ -457,6 +458,7 @@ it.effect.each([
planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }),
openSession: (input) =>
Effect.sync(() => opened.push(instanceId)).pipe(
Effect.tap(() => Deferred.succeed(openedSession, undefined)),
Effect.andThen(
new ProviderAdapter.ProviderAdapterOpenSessionError({
driver,
Expand Down Expand Up @@ -623,6 +625,10 @@ it.effect.each([
creationSource: "web",
});
yield* worker.drain();
if (!rejected) {
yield* Deferred.await(openedSession);
yield* worker.drain();
}

const projection = yield* orchestrator.getThreadProjection(targetThreadId);
if (execution === "portable_context") {
Expand Down
94 changes: 88 additions & 6 deletions apps/server/src/orchestration-v2/ThreadLaunchService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@ import * as Scheduler from "../scheduling/Scheduler.ts";
import * as WorktreeSetupTracker from "../project/WorktreeSetupTracker.ts";
import * as ProjectCloneTracker from "../project/ProjectCloneTracker.ts";
import * as TerminalManager from "../terminal/Manager.ts";
// @effect-diagnostics-next-line nodeBuiltinImport:off -- The test inspects the guard-compatible admission token directory.
import * as NodeFS from "node:fs";
// @effect-diagnostics-next-line nodeBuiltinImport:off -- The test locates the guard-compatible admission token directory.
import * as NodePath from "node:path";
import * as CheckpointStore from "../checkpointing/CheckpointStore.ts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as FileSystem from "effect/FileSystem";
Expand Down Expand Up @@ -165,10 +169,18 @@ interface HarnessOptions {
function makeHarness(options: HarnessOptions = {}) {
const layerDatabase = SqlitePersistence.layerMemory;
const layerRegistry = ProviderAdapterRegistry.layerFromAdapters(options.adapters ?? [adapter]);
const layerServerConfig = Layer.effect(
ServerConfig.ServerConfig,
ProviderReplayHarness.makeReplayServerConfig("thread-launch").pipe(Effect.orDie),
).pipe(Layer.provide(NodeServices.layer));
const layerOrchestrator = ProviderReplayHarness.layerWithRegistry(
{ name: "thread-launch" },
layerRegistry,
{ databaseLayer: layerDatabase, runEffectWorker: false },
{
databaseLayer: layerDatabase,
runEffectWorker: false,
serverConfigLayer: layerServerConfig,
},
);
const layerServerSettings = ServerSettings.layerTest(options.serverSettings);
const layerReceipts = CommandReceiptStore.layer.pipe(Layer.provide(layerDatabase));
Expand Down Expand Up @@ -293,6 +305,7 @@ function makeHarness(options: HarnessOptions = {}) {
layerLaunchThreads,
layerReceipts,
layerOrchestrator,
layerServerConfig,
ProjectionStore.layer.pipe(Layer.provide(layerDatabase)),
NodeServices.layer,
IdAllocator.layer,
Expand Down Expand Up @@ -342,6 +355,7 @@ function makeHarness(options: HarnessOptions = {}) {
return {
layer: Layer.mergeAll(
layerLaunch,
layerServerConfig,
layerRegistry,
layerThreadManagement,
layerTitleRegeneration,
Expand Down Expand Up @@ -480,6 +494,48 @@ it.effect.each(
},
);

it.effect("keeps admission active through a runless workspace preparation", () => {
const worktreeStarted = Deferred.makeUnsafe<void>();
const releaseWorktree = Deferred.makeUnsafe<void>();
const harness = makeHarness({
createWorktree: (input) =>
Deferred.succeed(worktreeStarted, undefined).pipe(
Effect.andThen(Deferred.await(releaseWorktree)),
Effect.as({
worktree: {
path: "/repo-worktrees/runless-admission",
refName: input.newRefName,
headSha: "abc",
},
} as never),
),
});

return Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
const launches = yield* ThreadLaunch.ThreadLaunchService;
const setups = yield* WorktreeSetupTracker.WorktreeSetupTracker;
const launched = yield* launches.launch(
launchInput({
command: "command:runless-admission",
thread: "thread:runless-admission",
workspace: worktreeStrategy,
}),
);
yield* Deferred.await(worktreeStarted);

const active = NodePath.join(config.baseDir, "runtime", "service-change-admission", "active");
assert.lengthOf(NodeFS.readdirSync(active), 1);

yield* Deferred.succeed(releaseWorktree, undefined);
yield* setups.stream(launched.threadId).pipe(
Stream.filter((snapshot) => snapshot?.phase === "done"),
Stream.runHead,
);
assert.isEmpty(NodeFS.readdirSync(active));
}).pipe(Effect.provide(harness.layer));
});

it.effect(
"returns no dispatched thread when sending an automation to a missing thread fails",
() => {
Expand Down Expand Up @@ -3521,11 +3577,30 @@ it.live.each(concurrentTaskFolderUses)("cancels task folder setup with %s", (con
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-launch-folders-" })),
Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
);
const layerTaskFolders = layerTaskFoldersWithGit(state).pipe(
Layer.provide(layerGit),
Layer.orDie,
);
return Effect.gen(function* () {
const taskFolderRemovalStarted = yield* Deferred.make<void>();
const allowTaskFolderRemoval = yield* Deferred.make<void>();
const baseTaskFolders = layerTaskFoldersWithGit(state).pipe(
Layer.provide(layerGit),
Layer.orDie,
);
const layerTaskFolders =
concurrent === "side chat without a run"
? Layer.effect(
TaskFolders.TaskFolders,
Effect.gen(function* () {
const folders = yield* TaskFolders.TaskFolders;
return {
...folders,
remove: (input) =>
Deferred.succeed(taskFolderRemovalStarted, undefined).pipe(
Effect.andThen(Deferred.await(allowTaskFolderRemoval)),
Effect.andThen(folders.remove(input)),
),
};
}),
).pipe(Layer.provide(baseTaskFolders))
: baseTaskFolders;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const git = yield* GitVcsDriver.GitVcsDriver;
Expand Down Expand Up @@ -3639,7 +3714,14 @@ it.live.each(concurrentTaskFolderUses)("cancels task folder setup with %s", (con
Effect.flip,
);
assert.equal(refused._tag, "OrchestratorDispatchError");
assert.isTrue(yield* tracker.cancel(launched.threadId));
if (concurrent === "side chat without a run") {
const cancellation = yield* tracker.cancel(launched.threadId).pipe(Effect.forkChild);
yield* Deferred.await(taskFolderRemovalStarted);
yield* Deferred.succeed(allowTaskFolderRemoval, undefined);
assert.isTrue(yield* Fiber.join(cancellation));
} else {
assert.isTrue(yield* tracker.cancel(launched.threadId));
}

assert.isNull((yield* threads.getThreadProjection(launched.threadId)).thread.worktreePath);
assert.isNull(yield* taskFolders.find(taskFolder!.root));
Expand Down
Loading
Loading