Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
80f0439006 | ||
|
|
ac7e71c5c5 | ||
|
|
dd1104337d |
No files matched your search
@@ -1,21 +1,12 @@
|
|||||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||||
import {
|
import { assert, describe, it, vi } from "@effect/vitest";
|
||||||
ProjectId,
|
import { ProjectId, ProviderInstanceId, ThreadId, TurnId } from "@t3tools/contracts";
|
||||||
ThreadId,
|
|
||||||
TurnId,
|
|
||||||
ProviderDriverKind,
|
|
||||||
ProviderInstanceId,
|
|
||||||
} from "@t3tools/contracts";
|
|
||||||
import * as Clock from "effect/Clock";
|
|
||||||
import * as DateTime from "effect/DateTime";
|
import * as DateTime from "effect/DateTime";
|
||||||
|
import * as Duration from "effect/Duration";
|
||||||
import * as Effect from "effect/Effect";
|
import * as Effect from "effect/Effect";
|
||||||
import * as Exit from "effect/Exit";
|
|
||||||
import * as Layer from "effect/Layer";
|
import * as Layer from "effect/Layer";
|
||||||
import * as ManagedRuntime from "effect/ManagedRuntime";
|
|
||||||
import * as Option from "effect/Option";
|
import * as Option from "effect/Option";
|
||||||
import * as Scope from "effect/Scope";
|
import * as TestClock from "effect/testing/TestClock";
|
||||||
import * as Stream from "effect/Stream";
|
|
||||||
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
|
|
||||||
|
|
||||||
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
|
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||||
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
|
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
|
||||||
@@ -31,31 +22,19 @@ const defaultModelSelection = {
|
|||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
async function waitFor(
|
const TEST_NOW = DateTime.makeUnsafe("2026-04-14T00:30:00.000Z");
|
||||||
predicate: () => boolean | Promise<boolean>,
|
const TEST_NOW_ISO = DateTime.formatIso(TEST_NOW);
|
||||||
timeoutMs = 2_000,
|
const STALE_LAST_SEEN_AT = DateTime.formatIso(
|
||||||
): Promise<void> {
|
DateTime.subtractDuration(TEST_NOW, Duration.seconds(2)),
|
||||||
const deadline = (await Effect.runPromise(Clock.currentTimeMillis)) + timeoutMs;
|
);
|
||||||
const poll = async (): Promise<void> => {
|
const FRESH_LAST_SEEN_AT = DateTime.formatIso(
|
||||||
if (await predicate()) {
|
DateTime.subtractDuration(TEST_NOW, Duration.millis(500)),
|
||||||
return;
|
);
|
||||||
}
|
|
||||||
if ((await Effect.runPromise(Clock.currentTimeMillis)) >= deadline) {
|
|
||||||
throw new Error("Timed out waiting for expectation.");
|
|
||||||
}
|
|
||||||
await Effect.runPromise(Effect.yieldNow);
|
|
||||||
return poll();
|
|
||||||
};
|
|
||||||
|
|
||||||
return poll();
|
|
||||||
}
|
|
||||||
|
|
||||||
const drainFibers = Effect.forEach(Array.from({ length: 10 }), () => Effect.yieldNow, {
|
const drainFibers = Effect.forEach(Array.from({ length: 10 }), () => Effect.yieldNow, {
|
||||||
discard: true,
|
discard: true,
|
||||||
});
|
});
|
||||||
|
|
||||||
const unsupported = () => Effect.die(new Error("Unsupported provider call in test")) as never;
|
|
||||||
|
|
||||||
function makeReadModel(
|
function makeReadModel(
|
||||||
threads: ReadonlyArray<{
|
threads: ReadonlyArray<{
|
||||||
readonly id: ThreadId;
|
readonly id: ThreadId;
|
||||||
@@ -70,12 +49,11 @@ function makeReadModel(
|
|||||||
} | null;
|
} | null;
|
||||||
}>,
|
}>,
|
||||||
) {
|
) {
|
||||||
const now = "2026-01-01T00:00:00.000Z";
|
|
||||||
const projectId = ProjectId.make("project-provider-session-reaper");
|
const projectId = ProjectId.make("project-provider-session-reaper");
|
||||||
|
|
||||||
return {
|
return {
|
||||||
snapshotSequence: 0,
|
snapshotSequence: 0,
|
||||||
updatedAt: now,
|
updatedAt: TEST_NOW_ISO,
|
||||||
projects: [
|
projects: [
|
||||||
{
|
{
|
||||||
id: projectId,
|
id: projectId,
|
||||||
@@ -83,8 +61,8 @@ function makeReadModel(
|
|||||||
workspaceRoot: "/tmp/provider-reaper-project",
|
workspaceRoot: "/tmp/provider-reaper-project",
|
||||||
defaultModelSelection,
|
defaultModelSelection,
|
||||||
scripts: [],
|
scripts: [],
|
||||||
createdAt: now,
|
createdAt: TEST_NOW_ISO,
|
||||||
updatedAt: now,
|
updatedAt: TEST_NOW_ISO,
|
||||||
deletedAt: null,
|
deletedAt: null,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
@@ -97,8 +75,8 @@ function makeReadModel(
|
|||||||
runtimeMode: "full-access" as const,
|
runtimeMode: "full-access" as const,
|
||||||
branch: null,
|
branch: null,
|
||||||
worktreePath: null,
|
worktreePath: null,
|
||||||
createdAt: now,
|
createdAt: TEST_NOW_ISO,
|
||||||
updatedAt: now,
|
updatedAt: TEST_NOW_ISO,
|
||||||
archivedAt: null,
|
archivedAt: null,
|
||||||
latestUserMessageAt: null,
|
latestUserMessageAt: null,
|
||||||
hasPendingApprovals: false,
|
hasPendingApprovals: false,
|
||||||
@@ -115,113 +93,99 @@ function makeReadModel(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
describe("ProviderSessionReaper", () => {
|
function createHarness(input: {
|
||||||
let runtime: ManagedRuntime.ManagedRuntime<
|
readonly readModel: ReturnType<typeof makeReadModel>;
|
||||||
ProviderSessionReaper | ProviderSessionRuntime.ProviderSessionRuntimeRepository,
|
readonly stopSessionImplementation?: (input: {
|
||||||
unknown
|
readonly threadId: ThreadId;
|
||||||
> | null = null;
|
}) => ReturnType<ProviderServiceShape["stopSession"]>;
|
||||||
let scope: Scope.Closeable | null = null;
|
}) {
|
||||||
|
const stoppedThreadIds = new Set<ThreadId>();
|
||||||
|
const stopSession = vi.fn<ProviderServiceShape["stopSession"]>(
|
||||||
|
(request) =>
|
||||||
|
(input.stopSessionImplementation
|
||||||
|
? input.stopSessionImplementation(request)
|
||||||
|
: Effect.sync(() => {
|
||||||
|
stoppedThreadIds.add(request.threadId);
|
||||||
|
})) as ReturnType<ProviderServiceShape["stopSession"]>,
|
||||||
|
);
|
||||||
|
|
||||||
afterEach(async () => {
|
const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(
|
||||||
if (scope) {
|
Layer.provide(SqlitePersistenceMemory),
|
||||||
await Effect.runPromise(Scope.close(scope, Exit.void));
|
);
|
||||||
}
|
const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe(
|
||||||
scope = null;
|
Layer.provide(runtimeRepositoryLayer),
|
||||||
if (runtime) {
|
);
|
||||||
await runtime.dispose();
|
const layer = makeProviderSessionReaperLive({
|
||||||
}
|
inactivityThreshold: Duration.seconds(1),
|
||||||
runtime = null;
|
sweepInterval: Duration.seconds(60),
|
||||||
});
|
}).pipe(
|
||||||
|
Layer.provideMerge(providerSessionDirectoryLayer),
|
||||||
|
Layer.provideMerge(runtimeRepositoryLayer),
|
||||||
|
Layer.provideMerge(
|
||||||
|
Layer.mock(ProviderService)({
|
||||||
|
stopSession,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
Layer.provideMerge(
|
||||||
|
Layer.mock(ProjectionSnapshotQuery)({
|
||||||
|
getThreadShellById: (threadId) =>
|
||||||
|
Effect.succeed(
|
||||||
|
Option.fromNullishOr(input.readModel.threads.find((thread) => thread.id === threadId)),
|
||||||
|
),
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
Layer.provideMerge(NodeServices.layer),
|
||||||
|
Layer.provideMerge(TestClock.layer()),
|
||||||
|
);
|
||||||
|
|
||||||
async function createHarness(input: {
|
return { layer, stopSession, stoppedThreadIds };
|
||||||
readonly readModel: ReturnType<typeof makeReadModel>;
|
}
|
||||||
readonly stopSessionImplementation?: (input: {
|
|
||||||
readonly threadId: ThreadId;
|
|
||||||
}) => ReturnType<ProviderServiceShape["stopSession"]>;
|
|
||||||
}) {
|
|
||||||
const stoppedThreadIds = new Set<ThreadId>();
|
|
||||||
const stopSession = vi.fn<ProviderServiceShape["stopSession"]>(
|
|
||||||
(request) =>
|
|
||||||
(input.stopSessionImplementation
|
|
||||||
? input.stopSessionImplementation(request)
|
|
||||||
: Effect.sync(() => {
|
|
||||||
stoppedThreadIds.add(request.threadId);
|
|
||||||
})) as ReturnType<ProviderServiceShape["stopSession"]>,
|
|
||||||
);
|
|
||||||
|
|
||||||
const providerService: ProviderServiceShape = {
|
function seedSession(input: {
|
||||||
startSession: () => unsupported(),
|
readonly threadId: ThreadId;
|
||||||
sendTurn: () => unsupported(),
|
readonly providerName: "codex" | "claudeAgent";
|
||||||
interruptTurn: () => unsupported(),
|
readonly status?: "starting" | "running" | "stopped" | "error";
|
||||||
respondToRequest: () => unsupported(),
|
readonly lastSeenAt: string;
|
||||||
respondToUserInput: () => unsupported(),
|
readonly resumeOpaque: string;
|
||||||
stopSession,
|
}) {
|
||||||
listSessions: () => Effect.succeed([]),
|
return Effect.gen(function* () {
|
||||||
getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }),
|
const repository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
|
||||||
getInstanceInfo: (instanceId) => {
|
yield* repository.upsert({
|
||||||
const driverKind = ProviderDriverKind.make(String(instanceId));
|
threadId: input.threadId,
|
||||||
return Effect.succeed({
|
providerName: input.providerName,
|
||||||
instanceId,
|
providerInstanceId: null,
|
||||||
driverKind,
|
adapterKey: input.providerName,
|
||||||
displayName: undefined,
|
runtimeMode: "full-access",
|
||||||
enabled: true,
|
status: input.status ?? "running",
|
||||||
continuationIdentity: {
|
lastSeenAt: input.lastSeenAt,
|
||||||
driverKind,
|
resumeCursor: {
|
||||||
continuationKey: `${driverKind}:instance:${instanceId}`,
|
opaque: input.resumeOpaque,
|
||||||
},
|
|
||||||
});
|
|
||||||
},
|
},
|
||||||
rollbackConversation: () => unsupported(),
|
runtimePayload: null,
|
||||||
streamEvents: Stream.empty,
|
});
|
||||||
};
|
});
|
||||||
|
}
|
||||||
|
|
||||||
const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(
|
const runInitialSweep = Effect.gen(function* () {
|
||||||
Layer.provide(SqlitePersistenceMemory),
|
const reaper = yield* ProviderSessionReaper;
|
||||||
);
|
yield* reaper.start();
|
||||||
const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe(
|
yield* drainFibers;
|
||||||
Layer.provide(runtimeRepositoryLayer),
|
});
|
||||||
);
|
|
||||||
const layer = makeProviderSessionReaperLive({
|
|
||||||
inactivityThresholdMs: 1_000,
|
|
||||||
sweepIntervalMs: 60_000,
|
|
||||||
}).pipe(
|
|
||||||
Layer.provideMerge(providerSessionDirectoryLayer),
|
|
||||||
Layer.provideMerge(runtimeRepositoryLayer),
|
|
||||||
Layer.provideMerge(Layer.succeed(ProviderService, providerService)),
|
|
||||||
Layer.provideMerge(
|
|
||||||
Layer.succeed(ProjectionSnapshotQuery, {
|
|
||||||
getCommandReadModel: () => Effect.die("unused"),
|
|
||||||
getSnapshot: () => Effect.die("unused"),
|
|
||||||
getShellSnapshot: () => Effect.die("unused"),
|
|
||||||
getArchivedShellSnapshot: () => Effect.die("unused"),
|
|
||||||
getSnapshotSequence: () =>
|
|
||||||
Effect.succeed({ snapshotSequence: input.readModel.snapshotSequence }),
|
|
||||||
getCounts: () => Effect.die("unused"),
|
|
||||||
getActiveProjectByWorkspaceRoot: () => Effect.die("unused"),
|
|
||||||
getProjectShellById: () => Effect.die("unused"),
|
|
||||||
getFirstActiveThreadIdByProjectId: () => Effect.die("unused"),
|
|
||||||
getThreadCheckpointContext: () => Effect.die("unused"),
|
|
||||||
getFullThreadDiffContext: () => Effect.die("unused"),
|
|
||||||
getThreadShellById: (threadId) =>
|
|
||||||
Effect.succeed(
|
|
||||||
input.readModel.threads.find((thread) => thread.id === threadId)
|
|
||||||
? Option.some(input.readModel.threads.find((thread) => thread.id === threadId)!)
|
|
||||||
: Option.none(),
|
|
||||||
),
|
|
||||||
getThreadDetailById: () => Effect.die("unused"),
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
Layer.provideMerge(NodeServices.layer),
|
|
||||||
);
|
|
||||||
|
|
||||||
runtime = ManagedRuntime.make(layer);
|
function runWithHarness<A, E, R>(
|
||||||
return { stopSession, stoppedThreadIds };
|
harness: ReturnType<typeof createHarness>,
|
||||||
}
|
effect: Effect.Effect<A, E, R>,
|
||||||
|
) {
|
||||||
|
return Effect.gen(function* () {
|
||||||
|
yield* TestClock.setTime(TEST_NOW.epochMilliseconds);
|
||||||
|
return yield* effect;
|
||||||
|
}).pipe(Effect.scoped, Effect.provide(harness.layer));
|
||||||
|
}
|
||||||
|
|
||||||
it("reaps stale persisted sessions without active turns", async () => {
|
describe("ProviderSessionReaper", () => {
|
||||||
|
it.effect("reaps stale persisted sessions without active turns", () => {
|
||||||
const threadId = ThreadId.make("thread-reaper-stale");
|
const threadId = ThreadId.make("thread-reaper-stale");
|
||||||
const now = "2026-01-01T00:00:00.000Z";
|
const harness = createHarness({
|
||||||
const harness = await createHarness({
|
|
||||||
readModel: makeReadModel([
|
readModel: makeReadModel([
|
||||||
{
|
{
|
||||||
id: threadId,
|
id: threadId,
|
||||||
@@ -232,46 +196,33 @@ describe("ProviderSessionReaper", () => {
|
|||||||
runtimeMode: "full-access",
|
runtimeMode: "full-access",
|
||||||
activeTurnId: null,
|
activeTurnId: null,
|
||||||
lastError: null,
|
lastError: null,
|
||||||
updatedAt: now,
|
updatedAt: TEST_NOW_ISO,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
]),
|
]),
|
||||||
});
|
});
|
||||||
const repository = await runtime!.runPromise(
|
|
||||||
Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository),
|
|
||||||
);
|
|
||||||
|
|
||||||
await runtime!.runPromise(
|
return runWithHarness(
|
||||||
repository.upsert({
|
harness,
|
||||||
threadId,
|
Effect.gen(function* () {
|
||||||
providerName: "claudeAgent",
|
yield* seedSession({
|
||||||
providerInstanceId: null,
|
threadId,
|
||||||
adapterKey: "claudeAgent",
|
providerName: "claudeAgent",
|
||||||
runtimeMode: "full-access",
|
lastSeenAt: STALE_LAST_SEEN_AT,
|
||||||
status: "running",
|
resumeOpaque: "resume-stale",
|
||||||
lastSeenAt: "2026-04-14T00:00:00.000Z",
|
});
|
||||||
resumeCursor: {
|
yield* runInitialSweep;
|
||||||
opaque: "resume-stale",
|
|
||||||
},
|
assert.deepStrictEqual(harness.stopSession.mock.calls[0]?.[0], { threadId });
|
||||||
runtimePayload: null,
|
assert.isTrue(harness.stoppedThreadIds.has(threadId));
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
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.stopSession.mock.calls.length === 1);
|
|
||||||
|
|
||||||
expect(harness.stopSession.mock.calls[0]?.[0]).toEqual({ threadId });
|
|
||||||
expect(harness.stoppedThreadIds.has(threadId)).toBe(true);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it("skips stale sessions when the thread still has an active turn", async () => {
|
it.effect("skips stale sessions when the thread still has an active turn", () => {
|
||||||
const threadId = ThreadId.make("thread-reaper-active-turn");
|
const threadId = ThreadId.make("thread-reaper-active-turn");
|
||||||
const turnId = TurnId.make("turn-reaper-active");
|
const turnId = TurnId.make("turn-reaper-active");
|
||||||
const now = "2026-01-01T00:00:00.000Z";
|
const harness = createHarness({
|
||||||
const harness = await createHarness({
|
|
||||||
readModel: makeReadModel([
|
readModel: makeReadModel([
|
||||||
{
|
{
|
||||||
id: threadId,
|
id: threadId,
|
||||||
@@ -282,45 +233,34 @@ describe("ProviderSessionReaper", () => {
|
|||||||
runtimeMode: "full-access",
|
runtimeMode: "full-access",
|
||||||
activeTurnId: turnId,
|
activeTurnId: turnId,
|
||||||
lastError: null,
|
lastError: null,
|
||||||
updatedAt: now,
|
updatedAt: TEST_NOW_ISO,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
]),
|
]),
|
||||||
});
|
});
|
||||||
const repository = await runtime!.runPromise(
|
|
||||||
Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository),
|
|
||||||
);
|
|
||||||
|
|
||||||
await runtime!.runPromise(
|
return runWithHarness(
|
||||||
repository.upsert({
|
harness,
|
||||||
threadId,
|
Effect.gen(function* () {
|
||||||
providerName: "claudeAgent",
|
yield* seedSession({
|
||||||
providerInstanceId: null,
|
threadId,
|
||||||
adapterKey: "claudeAgent",
|
providerName: "claudeAgent",
|
||||||
runtimeMode: "full-access",
|
lastSeenAt: STALE_LAST_SEEN_AT,
|
||||||
status: "running",
|
resumeOpaque: "resume-active-turn",
|
||||||
lastSeenAt: "2026-04-14T00:00:00.000Z",
|
});
|
||||||
resumeCursor: {
|
const repository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
|
||||||
opaque: "resume-active-turn",
|
yield* runInitialSweep;
|
||||||
},
|
|
||||||
runtimePayload: null,
|
assert.equal(harness.stopSession.mock.calls.length, 0);
|
||||||
|
const remaining = yield* repository.getByThreadId({ threadId });
|
||||||
|
assert.isTrue(Option.isSome(remaining));
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
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.stopSession).not.toHaveBeenCalled();
|
|
||||||
const remaining = await runtime!.runPromise(repository.getByThreadId({ threadId }));
|
|
||||||
expect(Option.isSome(remaining)).toBe(true);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it("does not reap sessions that are still within the inactivity threshold", async () => {
|
it.effect("does not reap sessions that are still within the inactivity threshold", () => {
|
||||||
const threadId = ThreadId.make("thread-reaper-fresh");
|
const threadId = ThreadId.make("thread-reaper-fresh");
|
||||||
const now = DateTime.formatIso(await Effect.runPromise(DateTime.now));
|
const harness = createHarness({
|
||||||
const harness = await createHarness({
|
|
||||||
readModel: makeReadModel([
|
readModel: makeReadModel([
|
||||||
{
|
{
|
||||||
id: threadId,
|
id: threadId,
|
||||||
@@ -331,45 +271,34 @@ describe("ProviderSessionReaper", () => {
|
|||||||
runtimeMode: "full-access",
|
runtimeMode: "full-access",
|
||||||
activeTurnId: null,
|
activeTurnId: null,
|
||||||
lastError: null,
|
lastError: null,
|
||||||
updatedAt: now,
|
updatedAt: TEST_NOW_ISO,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
]),
|
]),
|
||||||
});
|
});
|
||||||
const repository = await runtime!.runPromise(
|
|
||||||
Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository),
|
|
||||||
);
|
|
||||||
|
|
||||||
await runtime!.runPromise(
|
return runWithHarness(
|
||||||
repository.upsert({
|
harness,
|
||||||
threadId,
|
Effect.gen(function* () {
|
||||||
providerName: "claudeAgent",
|
yield* seedSession({
|
||||||
providerInstanceId: null,
|
threadId,
|
||||||
adapterKey: "claudeAgent",
|
providerName: "claudeAgent",
|
||||||
runtimeMode: "full-access",
|
lastSeenAt: FRESH_LAST_SEEN_AT,
|
||||||
status: "running",
|
resumeOpaque: "resume-fresh",
|
||||||
lastSeenAt: now,
|
});
|
||||||
resumeCursor: {
|
const repository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
|
||||||
opaque: "resume-fresh",
|
yield* runInitialSweep;
|
||||||
},
|
|
||||||
runtimePayload: null,
|
assert.equal(harness.stopSession.mock.calls.length, 0);
|
||||||
|
const remaining = yield* repository.getByThreadId({ threadId });
|
||||||
|
assert.isTrue(Option.isSome(remaining));
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
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.stopSession).not.toHaveBeenCalled();
|
|
||||||
const remaining = await runtime!.runPromise(repository.getByThreadId({ threadId }));
|
|
||||||
expect(Option.isSome(remaining)).toBe(true);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it("skips persisted sessions that are already marked stopped", async () => {
|
it.effect("skips persisted sessions that are already marked stopped", () => {
|
||||||
const threadId = ThreadId.make("thread-reaper-stopped");
|
const threadId = ThreadId.make("thread-reaper-stopped");
|
||||||
const now = "2026-01-01T00:00:00.000Z";
|
const harness = createHarness({
|
||||||
const harness = await createHarness({
|
|
||||||
readModel: makeReadModel([
|
readModel: makeReadModel([
|
||||||
{
|
{
|
||||||
id: threadId,
|
id: threadId,
|
||||||
@@ -380,46 +309,36 @@ describe("ProviderSessionReaper", () => {
|
|||||||
runtimeMode: "full-access",
|
runtimeMode: "full-access",
|
||||||
activeTurnId: null,
|
activeTurnId: null,
|
||||||
lastError: null,
|
lastError: null,
|
||||||
updatedAt: now,
|
updatedAt: TEST_NOW_ISO,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
]),
|
]),
|
||||||
});
|
});
|
||||||
const repository = await runtime!.runPromise(
|
|
||||||
Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository),
|
|
||||||
);
|
|
||||||
|
|
||||||
await runtime!.runPromise(
|
return runWithHarness(
|
||||||
repository.upsert({
|
harness,
|
||||||
threadId,
|
Effect.gen(function* () {
|
||||||
providerName: "claudeAgent",
|
yield* seedSession({
|
||||||
providerInstanceId: null,
|
threadId,
|
||||||
adapterKey: "claudeAgent",
|
providerName: "claudeAgent",
|
||||||
runtimeMode: "full-access",
|
status: "stopped",
|
||||||
status: "stopped",
|
lastSeenAt: STALE_LAST_SEEN_AT,
|
||||||
lastSeenAt: "2026-04-14T00:00:00.000Z",
|
resumeOpaque: "resume-stopped",
|
||||||
resumeCursor: {
|
});
|
||||||
opaque: "resume-stopped",
|
const repository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
|
||||||
},
|
yield* runInitialSweep;
|
||||||
runtimePayload: null,
|
|
||||||
|
assert.equal(harness.stopSession.mock.calls.length, 0);
|
||||||
|
const remaining = yield* repository.getByThreadId({ threadId });
|
||||||
|
assert.isTrue(Option.isSome(remaining));
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
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.stopSession).not.toHaveBeenCalled();
|
|
||||||
const remaining = await runtime!.runPromise(repository.getByThreadId({ threadId }));
|
|
||||||
expect(Option.isSome(remaining)).toBe(true);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it("continues reaping other sessions when one stop attempt fails", async () => {
|
it.effect("continues reaping other sessions when one stop attempt fails", () => {
|
||||||
const failedThreadId = ThreadId.make("thread-reaper-stop-failure");
|
const failedThreadId = ThreadId.make("thread-reaper-stop-failure");
|
||||||
const reapedThreadId = ThreadId.make("thread-reaper-stop-success");
|
const reapedThreadId = ThreadId.make("thread-reaper-stop-success");
|
||||||
const now = "2026-01-01T00:00:00.000Z";
|
const harness = createHarness({
|
||||||
const harness = await createHarness({
|
|
||||||
readModel: makeReadModel([
|
readModel: makeReadModel([
|
||||||
{
|
{
|
||||||
id: failedThreadId,
|
id: failedThreadId,
|
||||||
@@ -430,7 +349,7 @@ describe("ProviderSessionReaper", () => {
|
|||||||
runtimeMode: "full-access",
|
runtimeMode: "full-access",
|
||||||
activeTurnId: null,
|
activeTurnId: null,
|
||||||
lastError: null,
|
lastError: null,
|
||||||
updatedAt: now,
|
updatedAt: TEST_NOW_ISO,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -442,7 +361,7 @@ describe("ProviderSessionReaper", () => {
|
|||||||
runtimeMode: "full-access",
|
runtimeMode: "full-access",
|
||||||
activeTurnId: null,
|
activeTurnId: null,
|
||||||
lastError: null,
|
lastError: null,
|
||||||
updatedAt: now,
|
updatedAt: TEST_NOW_ISO,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
]),
|
]),
|
||||||
@@ -456,58 +375,37 @@ describe("ProviderSessionReaper", () => {
|
|||||||
)
|
)
|
||||||
: Effect.void,
|
: Effect.void,
|
||||||
});
|
});
|
||||||
const repository = await runtime!.runPromise(
|
|
||||||
Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository),
|
|
||||||
);
|
|
||||||
|
|
||||||
await runtime!.runPromise(
|
return runWithHarness(
|
||||||
repository.upsert({
|
harness,
|
||||||
threadId: failedThreadId,
|
Effect.gen(function* () {
|
||||||
providerName: "claudeAgent",
|
yield* seedSession({
|
||||||
providerInstanceId: null,
|
threadId: failedThreadId,
|
||||||
adapterKey: "claudeAgent",
|
providerName: "claudeAgent",
|
||||||
runtimeMode: "full-access",
|
lastSeenAt: STALE_LAST_SEEN_AT,
|
||||||
status: "running",
|
resumeOpaque: "resume-failure",
|
||||||
lastSeenAt: "2026-04-14T00:00:00.000Z",
|
});
|
||||||
resumeCursor: {
|
yield* seedSession({
|
||||||
opaque: "resume-failure",
|
threadId: reapedThreadId,
|
||||||
},
|
providerName: "codex",
|
||||||
runtimePayload: null,
|
lastSeenAt: STALE_LAST_SEEN_AT,
|
||||||
|
resumeOpaque: "resume-success",
|
||||||
|
});
|
||||||
|
yield* runInitialSweep;
|
||||||
|
|
||||||
|
assert.equal(harness.stopSession.mock.calls.length, 2);
|
||||||
|
assert.deepStrictEqual(
|
||||||
|
new Set(harness.stopSession.mock.calls.map(([request]) => request.threadId)),
|
||||||
|
new Set([failedThreadId, reapedThreadId]),
|
||||||
|
);
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
await runtime!.runPromise(
|
|
||||||
repository.upsert({
|
|
||||||
threadId: reapedThreadId,
|
|
||||||
providerName: "codex",
|
|
||||||
providerInstanceId: null,
|
|
||||||
adapterKey: "codex",
|
|
||||||
runtimeMode: "full-access",
|
|
||||||
status: "running",
|
|
||||||
lastSeenAt: "2026-04-14T00:01:00.000Z",
|
|
||||||
resumeCursor: {
|
|
||||||
opaque: "resume-success",
|
|
||||||
},
|
|
||||||
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 waitFor(() => harness.stopSession.mock.calls.length === 2);
|
|
||||||
|
|
||||||
expect(harness.stopSession.mock.calls.map(([request]) => request.threadId)).toEqual([
|
|
||||||
failedThreadId,
|
|
||||||
reapedThreadId,
|
|
||||||
]);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it("continues reaping other sessions when one stop attempt defects", async () => {
|
it.effect("continues reaping other sessions when one stop attempt defects", () => {
|
||||||
const defectThreadId = ThreadId.make("thread-reaper-stop-defect");
|
const defectThreadId = ThreadId.make("thread-reaper-stop-defect");
|
||||||
const reapedThreadId = ThreadId.make("thread-reaper-stop-after-defect");
|
const reapedThreadId = ThreadId.make("thread-reaper-stop-after-defect");
|
||||||
const now = "2026-01-01T00:00:00.000Z";
|
const harness = createHarness({
|
||||||
const harness = await createHarness({
|
|
||||||
readModel: makeReadModel([
|
readModel: makeReadModel([
|
||||||
{
|
{
|
||||||
id: defectThreadId,
|
id: defectThreadId,
|
||||||
@@ -518,7 +416,7 @@ describe("ProviderSessionReaper", () => {
|
|||||||
runtimeMode: "full-access",
|
runtimeMode: "full-access",
|
||||||
activeTurnId: null,
|
activeTurnId: null,
|
||||||
lastError: null,
|
lastError: null,
|
||||||
updatedAt: now,
|
updatedAt: TEST_NOW_ISO,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -530,7 +428,7 @@ describe("ProviderSessionReaper", () => {
|
|||||||
runtimeMode: "full-access",
|
runtimeMode: "full-access",
|
||||||
activeTurnId: null,
|
activeTurnId: null,
|
||||||
lastError: null,
|
lastError: null,
|
||||||
updatedAt: now,
|
updatedAt: TEST_NOW_ISO,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
]),
|
]),
|
||||||
@@ -539,50 +437,30 @@ describe("ProviderSessionReaper", () => {
|
|||||||
? Effect.die(new Error("simulated stop defect"))
|
? Effect.die(new Error("simulated stop defect"))
|
||||||
: Effect.void,
|
: Effect.void,
|
||||||
});
|
});
|
||||||
const repository = await runtime!.runPromise(
|
|
||||||
Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository),
|
|
||||||
);
|
|
||||||
|
|
||||||
await runtime!.runPromise(
|
return runWithHarness(
|
||||||
repository.upsert({
|
harness,
|
||||||
threadId: defectThreadId,
|
Effect.gen(function* () {
|
||||||
providerName: "claudeAgent",
|
yield* seedSession({
|
||||||
providerInstanceId: null,
|
threadId: defectThreadId,
|
||||||
adapterKey: "claudeAgent",
|
providerName: "claudeAgent",
|
||||||
runtimeMode: "full-access",
|
lastSeenAt: STALE_LAST_SEEN_AT,
|
||||||
status: "running",
|
resumeOpaque: "resume-defect",
|
||||||
lastSeenAt: "2026-04-14T00:00:00.000Z",
|
});
|
||||||
resumeCursor: {
|
yield* seedSession({
|
||||||
opaque: "resume-defect",
|
threadId: reapedThreadId,
|
||||||
},
|
providerName: "codex",
|
||||||
runtimePayload: null,
|
lastSeenAt: STALE_LAST_SEEN_AT,
|
||||||
|
resumeOpaque: "resume-after-defect",
|
||||||
|
});
|
||||||
|
yield* runInitialSweep;
|
||||||
|
|
||||||
|
assert.equal(harness.stopSession.mock.calls.length, 2);
|
||||||
|
assert.deepStrictEqual(
|
||||||
|
new Set(harness.stopSession.mock.calls.map(([request]) => request.threadId)),
|
||||||
|
new Set([defectThreadId, reapedThreadId]),
|
||||||
|
);
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
await runtime!.runPromise(
|
|
||||||
repository.upsert({
|
|
||||||
threadId: reapedThreadId,
|
|
||||||
providerName: "codex",
|
|
||||||
providerInstanceId: null,
|
|
||||||
adapterKey: "codex",
|
|
||||||
runtimeMode: "full-access",
|
|
||||||
status: "running",
|
|
||||||
lastSeenAt: "2026-04-14T00:01:00.000Z",
|
|
||||||
resumeCursor: {
|
|
||||||
opaque: "resume-after-defect",
|
|
||||||
},
|
|
||||||
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 waitFor(() => harness.stopSession.mock.calls.length === 2);
|
|
||||||
|
|
||||||
expect(harness.stopSession.mock.calls.map(([request]) => request.threadId)).toEqual([
|
|
||||||
defectThreadId,
|
|
||||||
reapedThreadId,
|
|
||||||
]);
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import * as Clock from "effect/Clock";
|
import * as DateTime from "effect/DateTime";
|
||||||
import * as Duration from "effect/Duration";
|
import * as Duration from "effect/Duration";
|
||||||
import * as Effect from "effect/Effect";
|
import * as Effect from "effect/Effect";
|
||||||
import * as Layer from "effect/Layer";
|
import * as Layer from "effect/Layer";
|
||||||
@@ -13,12 +13,17 @@ import {
|
|||||||
} from "../Services/ProviderSessionReaper.ts";
|
} from "../Services/ProviderSessionReaper.ts";
|
||||||
import { ProviderService } from "../Services/ProviderService.ts";
|
import { ProviderService } from "../Services/ProviderService.ts";
|
||||||
|
|
||||||
const DEFAULT_INACTIVITY_THRESHOLD_MS = 30 * 60 * 1000;
|
const MINIMUM_DURATION = Duration.millis(1);
|
||||||
const DEFAULT_SWEEP_INTERVAL_MS = 5 * 60 * 1000;
|
const DEFAULT_INACTIVITY_THRESHOLD = Duration.minutes(30);
|
||||||
|
const DEFAULT_SWEEP_INTERVAL = Duration.minutes(5);
|
||||||
|
|
||||||
export interface ProviderSessionReaperLiveOptions {
|
export interface ProviderSessionReaperLiveOptions {
|
||||||
readonly inactivityThresholdMs?: number;
|
readonly inactivityThreshold?: Duration.Input;
|
||||||
readonly sweepIntervalMs?: number;
|
readonly sweepInterval?: Duration.Input;
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeDuration(input: Duration.Input | undefined, fallback: Duration.Duration) {
|
||||||
|
return Duration.max(Duration.fromInputUnsafe(input ?? fallback), MINIMUM_DURATION);
|
||||||
}
|
}
|
||||||
|
|
||||||
const makeProviderSessionReaper = (options?: ProviderSessionReaperLiveOptions) =>
|
const makeProviderSessionReaper = (options?: ProviderSessionReaperLiveOptions) =>
|
||||||
@@ -27,15 +32,15 @@ const makeProviderSessionReaper = (options?: ProviderSessionReaperLiveOptions) =
|
|||||||
const directory = yield* ProviderSessionDirectory;
|
const directory = yield* ProviderSessionDirectory;
|
||||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||||
|
|
||||||
const inactivityThresholdMs = Math.max(
|
const inactivityThreshold = normalizeDuration(
|
||||||
1,
|
options?.inactivityThreshold,
|
||||||
options?.inactivityThresholdMs ?? DEFAULT_INACTIVITY_THRESHOLD_MS,
|
DEFAULT_INACTIVITY_THRESHOLD,
|
||||||
);
|
);
|
||||||
const sweepIntervalMs = Math.max(1, options?.sweepIntervalMs ?? DEFAULT_SWEEP_INTERVAL_MS);
|
const sweepInterval = normalizeDuration(options?.sweepInterval, DEFAULT_SWEEP_INTERVAL);
|
||||||
|
|
||||||
const sweep = Effect.gen(function* () {
|
const sweep = Effect.gen(function* () {
|
||||||
const bindings = yield* directory.listBindings();
|
const bindings = yield* directory.listBindings();
|
||||||
const now = yield* Clock.currentTimeMillis;
|
const now = yield* DateTime.now;
|
||||||
let reapedCount = 0;
|
let reapedCount = 0;
|
||||||
|
|
||||||
for (const binding of bindings) {
|
for (const binding of bindings) {
|
||||||
@@ -43,8 +48,8 @@ const makeProviderSessionReaper = (options?: ProviderSessionReaperLiveOptions) =
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
const lastSeenMs = Date.parse(binding.lastSeenAt);
|
const lastSeen = DateTime.make(binding.lastSeenAt);
|
||||||
if (Number.isNaN(lastSeenMs)) {
|
if (Option.isNone(lastSeen)) {
|
||||||
yield* Effect.logWarning("provider.session.reaper.invalid-last-seen", {
|
yield* Effect.logWarning("provider.session.reaper.invalid-last-seen", {
|
||||||
threadId: binding.threadId,
|
threadId: binding.threadId,
|
||||||
provider: binding.provider,
|
provider: binding.provider,
|
||||||
@@ -53,8 +58,9 @@ const makeProviderSessionReaper = (options?: ProviderSessionReaperLiveOptions) =
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
const idleDurationMs = now - lastSeenMs;
|
const idleDuration = DateTime.distance(lastSeen.value, now);
|
||||||
if (idleDurationMs < inactivityThresholdMs) {
|
const idleDurationMs = Duration.toMillis(idleDuration);
|
||||||
|
if (Duration.isLessThan(idleDuration, inactivityThreshold)) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -117,13 +123,13 @@ const makeProviderSessionReaper = (options?: ProviderSessionReaperLiveOptions) =
|
|||||||
defect,
|
defect,
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
Effect.repeat(Schedule.spaced(Duration.millis(sweepIntervalMs))),
|
Effect.repeat(Schedule.spaced(sweepInterval)),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
yield* Effect.logInfo("provider.session.reaper.started", {
|
yield* Effect.logInfo("provider.session.reaper.started", {
|
||||||
inactivityThresholdMs,
|
inactivityThresholdMs: Duration.toMillis(inactivityThreshold),
|
||||||
sweepIntervalMs,
|
sweepIntervalMs: Duration.toMillis(sweepInterval),
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user