Skip to content
Open
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
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
218 changes: 208 additions & 10 deletions apps/server/src/provider/Layers/ProviderSessionReaper.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@ 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 { OrchestrationCommandInvariantError } from "../../orchestration/Errors.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 @@ -137,6 +142,8 @@ describe("ProviderSessionReaper", () => {

async function createHarness(input: {
readonly readModel: ReturnType<typeof makeReadModel>;
readonly dispatchImplementation?: OrchestrationEngineShape["dispatch"];
readonly sweepIntervalMs?: number;
readonly stopSessionImplementation?: (input: {
readonly threadId: ThreadId;
}) => ReturnType<ProviderServiceShape["stopSession"]>;
Expand Down Expand Up @@ -176,6 +183,9 @@ describe("ProviderSessionReaper", () => {
rollbackConversation: () => unsupported(),
streamEvents: Stream.empty,
};
const dispatch = vi.fn<OrchestrationEngineShape["dispatch"]>(
input.dispatchImplementation ?? (() => Effect.succeed({ sequence: 1 })),
);

const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(
Layer.provide(SqlitePersistenceMemory),
Expand All @@ -185,11 +195,19 @@ describe("ProviderSessionReaper", () => {
);
const layer = makeProviderSessionReaperLive({
inactivityThresholdMs: 1_000,
sweepIntervalMs: 60_000,
sweepIntervalMs: input.sweepIntervalMs ?? 60_000,
}).pipe(
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 +236,189 @@ 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 runtime!.runPromise(drainFibers);

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

it("uses a fresh command ID when retrying a rejected reconciliation", async () => {
const threadId = ThreadId.make("thread-reaper-retry-reconciliation");
const projectedAt = "2026-04-14T00:00:00.000Z";
const stoppedAt = "2026-04-14T00:01:00.000Z";
let attempt = 0;
const harness = await createHarness({
readModel: makeReadModel([
{
id: threadId,
session: {
threadId,
status: "starting",
providerName: "codex",
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: projectedAt,
},
},
]),
dispatchImplementation: (command) => {
attempt += 1;
return attempt === 1
? Effect.fail(
new OrchestrationCommandInvariantError({
commandType: command.type,
detail: "simulated concurrent session update",
}),
)
: Effect.succeed({ sequence: 1 });
},
sweepIntervalMs: 1,
});
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 runtime!.runPromise(Scope.make("sequential"));
await runtime!.runPromise(reaper.start().pipe(Scope.provide(scope)));

await waitFor(() => harness.dispatch.mock.calls.length >= 2);
await Effect.runPromise(Scope.close(scope, Exit.void));
scope = null;

const firstCommandId = harness.dispatch.mock.calls[0]?.[0].commandId;
const secondCommandId = harness.dispatch.mock.calls[1]?.[0].commandId;
expect(firstCommandId).toMatch(/^server:provider-session-reconcile:/);
expect(secondCommandId).toMatch(/^server:provider-session-reconcile:/);
expect(secondCommandId).not.toBe(firstCommandId);
});

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 +560,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,9 +607,9 @@ 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);
scope = await runtime!.runPromise(Scope.make("sequential"));
await runtime!.runPromise(reaper.start().pipe(Scope.provide(scope)));
await runtime!.runPromise(drainFibers);

expect(harness.stopSession).not.toHaveBeenCalled();
const remaining = await runtime!.runPromise(repository.getByThreadId({ threadId }));
Expand Down Expand Up @@ -495,8 +693,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 Expand Up @@ -578,8 +776,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
Loading
Loading