Skip to content
Open
Show file tree
Hide file tree
Changes from 2 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
22 changes: 22 additions & 0 deletions apps/server/src/orchestration/decider.settled.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -470,6 +470,28 @@ it.layer(NodeServices.layer)("settled thread decider", (it) => {
}),
);

it.effect("rejects a conditional session write after the projected session changes", () =>
Effect.gen(function* () {
const currentSession = makeSession("running");
const error = yield* decideOrchestrationCommand({
command: {
type: "thread.session.set",
commandId: CommandId.make("cmd-stale-session-write"),
threadId: ThreadId.make("thread-1"),
expectedSessionUpdatedAt: "2025-12-31T23:59:00.000Z",
session: {
...currentSession,
status: "stopped",
},
createdAt: NOW,
},
readModel: makeReadModel(null, null, currentSession),
}).pipe(Effect.flip);

expect(error._tag).toBe("OrchestrationCommandInvariantError");
}),
);

it.effect("unsettles for approval and user-input activities but not others", () =>
Effect.gen(function* () {
const approvalResult = yield* decideOrchestrationCommand({
Expand Down
9 changes: 9 additions & 0 deletions apps/server/src/orchestration/decider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -946,6 +946,15 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
command,
threadId: command.threadId,
});
if (
command.expectedSessionUpdatedAt !== undefined &&
thread.session?.updatedAt !== command.expectedSessionUpdatedAt
) {
return yield* new OrchestrationCommandInvariantError({
commandType: command.type,
detail: `Thread '${command.threadId}' session changed after the command was prepared.`,
});
}
const sessionSetEvent: Omit<OrchestrationEvent, "sequence"> = {
...(yield* withEventBase({
aggregateKind: "thread",
Expand Down
141 changes: 135 additions & 6 deletions apps/server/src/provider/Layers/ProviderSessionReaper.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import { afterEach, describe, expect, it, vi } from "vite-plus/test";

import {
OrchestrationEngineService,
type OrchestrationEngineShape,
} from "../../orchestration/Services/OrchestrationEngine.ts";
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
import * as ProviderSessionRuntime from "../../persistence/ProviderSessionRuntime.ts";
Expand Down Expand Up @@ -176,6 +180,9 @@ describe("ProviderSessionReaper", () => {
rollbackConversation: () => unsupported(),
streamEvents: Stream.empty,
};
const dispatch = vi.fn<OrchestrationEngineShape["dispatch"]>(() =>
Effect.succeed({ sequence: 1 }),
);

const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(
Layer.provide(SqlitePersistenceMemory),
Expand All @@ -190,6 +197,14 @@ describe("ProviderSessionReaper", () => {
Layer.provideMerge(providerSessionDirectoryLayer),
Layer.provideMerge(runtimeRepositoryLayer),
Layer.provideMerge(Layer.succeed(ProviderService, providerService)),
Layer.provideMerge(
Layer.succeed(OrchestrationEngineService, {
dispatch,
readEvents: () => Stream.empty,
streamDomainEvents: Stream.empty,
latestSequence: Effect.succeed(0),
}),
),
Layer.provideMerge(
Layer.succeed(ProjectionSnapshotQuery, {
getCommandReadModel: () => Effect.die("unused"),
Expand Down Expand Up @@ -218,9 +233,123 @@ describe("ProviderSessionReaper", () => {
);

runtime = ManagedRuntime.make(layer);
return { stopSession, stoppedThreadIds };
return { dispatch, stopSession, stoppedThreadIds };
}

it("projects durable stopped bindings that were left working during shutdown", async () => {
const threadId = ThreadId.make("thread-reaper-stopped-during-shutdown");
const projectedAt = "2026-04-14T00:00:00.000Z";
const stoppedAt = "2026-04-14T00:01:00.000Z";
const harness = await createHarness({
readModel: makeReadModel([
{
id: threadId,
session: {
threadId,
status: "starting",
providerName: "codex",
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: projectedAt,
},
},
]),
});
const repository = await runtime!.runPromise(
Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository),
);

await runtime!.runPromise(
repository.upsert({
threadId,
providerName: "codex",
providerInstanceId: ProviderInstanceId.make("codex"),
adapterKey: "codex",
runtimeMode: "full-access",
status: "stopped",
lastSeenAt: stoppedAt,
resumeCursor: null,
runtimePayload: {
activeTurnId: null,
lastRuntimeEvent: "provider.stopAll",
lastRuntimeEventAt: stoppedAt,
},
}),
);

const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
scope = await Effect.runPromise(Scope.make("sequential"));
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));

await waitFor(() => harness.dispatch.mock.calls.length === 1);

expect(harness.stopSession).not.toHaveBeenCalled();
expect(harness.dispatch.mock.calls[0]?.[0]).toMatchObject({
type: "thread.session.set",
threadId,
expectedSessionUpdatedAt: projectedAt,
createdAt: stoppedAt,
session: {
threadId,
status: "stopped",
providerName: "codex",
providerInstanceId: "codex",
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: stoppedAt,
},
});
});

it("does not overwrite a projected session newer than the stopped binding", async () => {
const threadId = ThreadId.make("thread-reaper-stale-stopped-binding");
const stoppedAt = "2026-04-14T00:00:00.000Z";
const projectedAt = "2026-04-14T00:01:00.000Z";
const harness = await createHarness({
readModel: makeReadModel([
{
id: threadId,
session: {
threadId,
status: "starting",
providerName: "codex",
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: projectedAt,
},
},
]),
});
const repository = await runtime!.runPromise(
Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository),
);

await runtime!.runPromise(
repository.upsert({
threadId,
providerName: "codex",
providerInstanceId: ProviderInstanceId.make("codex"),
adapterKey: "codex",
runtimeMode: "full-access",
status: "stopped",
lastSeenAt: stoppedAt,
resumeCursor: null,
runtimePayload: null,
}),
);

const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
scope = await Effect.runPromise(Scope.make("sequential"));
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
await Effect.runPromise(drainFibers);

expect(harness.dispatch).not.toHaveBeenCalled();
expect(harness.stopSession).not.toHaveBeenCalled();
});

it("reaps stale persisted sessions without active turns", async () => {
const threadId = ThreadId.make("thread-reaper-stale");
const now = "2026-01-01T00:00:00.000Z";
Expand Down Expand Up @@ -362,7 +491,7 @@ describe("ProviderSessionReaper", () => {
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
scope = await Effect.runPromise(Scope.make("sequential"));
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
await Effect.runPromise(drainFibers);
await runtime!.runPromise(drainFibers);

expect(harness.stopSession).not.toHaveBeenCalled();
const remaining = await runtime!.runPromise(repository.getByThreadId({ threadId }));
Expand Down Expand Up @@ -409,8 +538,8 @@ describe("ProviderSessionReaper", () => {
);

const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
scope = await Effect.runPromise(Scope.make("sequential"));
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
scope = await runtime!.runPromise(Scope.make("sequential"));
await runtime!.runPromise(reaper.start().pipe(Scope.provide(scope)));
await Effect.runPromise(drainFibers);

expect(harness.stopSession).not.toHaveBeenCalled();
Expand Down Expand Up @@ -495,8 +624,8 @@ describe("ProviderSessionReaper", () => {
);

const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
scope = await Effect.runPromise(Scope.make("sequential"));
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
scope = await runtime!.runPromise(Scope.make("sequential"));
await runtime!.runPromise(reaper.start().pipe(Scope.provide(scope)));

await waitFor(() => harness.stopSession.mock.calls.length === 2);

Expand Down
93 changes: 92 additions & 1 deletion apps/server/src/provider/Layers/ProviderSessionReaper.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
import { CommandId } from "@t3tools/contracts";
import * as Clock from "effect/Clock";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schedule from "effect/Schedule";

import { OrchestrationEngineService } from "../../orchestration/Services/OrchestrationEngine.ts";
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
import {
ProviderSessionDirectory,
type ProviderRuntimeBindingWithMetadata,
} from "../Services/ProviderSessionDirectory.ts";
import {
ProviderSessionReaper,
type ProviderSessionReaperShape,
Expand All @@ -25,6 +30,7 @@ const makeProviderSessionReaper = (options?: ProviderSessionReaperLiveOptions) =
Effect.gen(function* () {
const providerService = yield* ProviderService;
const directory = yield* ProviderSessionDirectory;
const orchestrationEngine = yield* OrchestrationEngineService;
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;

const inactivityThresholdMs = Math.max(
Expand All @@ -33,13 +39,98 @@ const makeProviderSessionReaper = (options?: ProviderSessionReaperLiveOptions) =
);
const sweepIntervalMs = Math.max(1, options?.sweepIntervalMs ?? DEFAULT_SWEEP_INTERVAL_MS);

// Provider shutdown can persist "stopped" after runtime event consumers
// have closed, leaving the projection on its last transient status.
const reconcileStoppedBinding = Effect.fn("ProviderSessionReaper.reconcileStoppedBinding")(
function* (binding: ProviderRuntimeBindingWithMetadata) {
const thread = yield* projectionSnapshotQuery
.getThreadShellById(binding.threadId)
.pipe(Effect.map(Option.getOrUndefined));
const session = thread?.session;
if (!session || session.status === "stopped") {
return;
}

const stoppedAtMs = Date.parse(binding.lastSeenAt);
if (Number.isNaN(stoppedAtMs)) {
yield* Effect.logWarning("provider.session.reaper.invalid-last-seen", {
threadId: binding.threadId,
provider: binding.provider,
lastSeenAt: binding.lastSeenAt,
});
return;
}

const projectedAtMs = Date.parse(session.updatedAt);
if (!Number.isNaN(projectedAtMs) && stoppedAtMs < projectedAtMs) {
yield* Effect.logDebug("provider.session.reaper.skipped-stale-stopped-binding", {
threadId: binding.threadId,
provider: binding.provider,
bindingLastSeenAt: binding.lastSeenAt,
projectedSessionUpdatedAt: session.updatedAt,
});
return;
}

yield* orchestrationEngine
Comment thread
macroscopeapp[bot] marked this conversation as resolved.
.dispatch({
type: "thread.session.set",
commandId: CommandId.make(
`server:provider-session-reconcile:${binding.threadId}:${binding.lastSeenAt}`,
),
threadId: binding.threadId,
expectedSessionUpdatedAt: session.updatedAt,
session: {
threadId: binding.threadId,
status: "stopped",
providerName: binding.provider,
...(binding.providerInstanceId !== undefined
? { providerInstanceId: binding.providerInstanceId }
: session.providerInstanceId !== undefined
? { providerInstanceId: session.providerInstanceId }
: {}),
runtimeMode: binding.runtimeMode ?? session.runtimeMode,
activeTurnId: null,
lastError: session.lastError,
updatedAt: binding.lastSeenAt,
},
createdAt: binding.lastSeenAt,
})
.pipe(
Effect.tap(() =>
Effect.logInfo("provider.session.reaper.reconciled-stopped-binding", {
threadId: binding.threadId,
provider: binding.provider,
stoppedAt: binding.lastSeenAt,
projectedStatus: session.status,
}),
),
Effect.catchTag("OrchestrationCommandInvariantError", () =>
Effect.logDebug("provider.session.reaper.skipped-concurrent-session-update", {
threadId: binding.threadId,
provider: binding.provider,
projectedSessionUpdatedAt: session.updatedAt,
}),
),
Comment thread
cursor[bot] marked this conversation as resolved.
Effect.catchCause((cause) =>
Effect.logWarning("provider.session.reaper.reconcile-stopped-binding-failed", {
threadId: binding.threadId,
provider: binding.provider,
cause,
}),
),
);
Comment thread
cursor[bot] marked this conversation as resolved.
},
);

const sweep = Effect.gen(function* () {
const bindings = yield* directory.listBindings();
const now = yield* Clock.currentTimeMillis;
let reapedCount = 0;

for (const binding of bindings) {
if (binding.status === "stopped") {
yield* reconcileStoppedBinding(binding);
continue;
}

Expand Down
1 change: 1 addition & 0 deletions packages/contracts/src/orchestration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -800,6 +800,7 @@ const ThreadSessionSetCommand = Schema.Struct({
commandId: CommandId,
threadId: ThreadId,
session: OrchestrationSession,
expectedSessionUpdatedAt: Schema.optional(IsoDateTime),
createdAt: IsoDateTime,
});

Expand Down
Loading