diff --git a/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts b/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts index 6bd90e283e..65e9413b33 100644 --- a/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts +++ b/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts @@ -8,6 +8,7 @@ import { } from "@t3tools/contracts"; import * as Clock from "effect/Clock"; import * as DateTime from "effect/DateTime"; +import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as Layer from "effect/Layer"; @@ -183,8 +184,8 @@ describe("ProviderSessionReaper", () => { Layer.provide(runtimeRepositoryLayer), ); const layer = makeProviderSessionReaperLive({ - inactivityThresholdMs: 1_000, - sweepIntervalMs: 60_000, + inactivityThreshold: Duration.seconds(1), + sweepInterval: Duration.minutes(1), }).pipe( Layer.provideMerge(providerSessionDirectoryLayer), Layer.provideMerge(runtimeRepositoryLayer), @@ -408,6 +409,53 @@ describe("ProviderSessionReaper", () => { expect(Option.isSome(remaining)).toBe(true); }); + it("skips persisted sessions with invalid last-seen timestamps", async () => { + const threadId = ThreadId.make("thread-reaper-invalid-last-seen"); + const now = "2026-01-01T00:00:00.000Z"; + const harness = await createHarness({ + readModel: makeReadModel([ + { + id: threadId, + session: { + threadId, + status: "ready", + providerName: "claudeAgent", + runtimeMode: "full-access", + activeTurnId: null, + lastError: null, + updatedAt: now, + }, + }, + ]), + }); + const repository = await runtime!.runPromise(Effect.service(ProviderSessionRuntimeRepository)); + + await runtime!.runPromise( + repository.upsert({ + threadId, + providerName: "claudeAgent", + providerInstanceId: null, + adapterKey: "claudeAgent", + runtimeMode: "full-access", + status: "running", + lastSeenAt: "not-a-timestamp", + resumeCursor: { + opaque: "resume-invalid-last-seen", + }, + 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.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 () => { const failedThreadId = ThreadId.make("thread-reaper-stop-failure"); const reapedThreadId = ThreadId.make("thread-reaper-stop-success"); diff --git a/apps/server/src/provider/Layers/ProviderSessionReaper.ts b/apps/server/src/provider/Layers/ProviderSessionReaper.ts index ca396b4059..7c4bd8c8a7 100644 --- a/apps/server/src/provider/Layers/ProviderSessionReaper.ts +++ b/apps/server/src/provider/Layers/ProviderSessionReaper.ts @@ -1,4 +1,4 @@ -import * as Clock from "effect/Clock"; +import * as DateTime from "effect/DateTime"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; @@ -13,29 +13,39 @@ import { } from "../Services/ProviderSessionReaper.ts"; import { ProviderService } from "../Services/ProviderService.ts"; -const DEFAULT_INACTIVITY_THRESHOLD_MS = 30 * 60 * 1000; -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 { - readonly inactivityThresholdMs?: number; - readonly sweepIntervalMs?: number; + readonly inactivityThreshold?: Duration.Input; + readonly sweepInterval?: Duration.Input; } +const normalizePositiveDuration = ( + input: Duration.Input | undefined, + fallback: Duration.Duration, +) => { + const duration = input === undefined ? fallback : Duration.fromInputUnsafe(input); + return Duration.millis(Math.max(1, Duration.toMillis(duration))); +}; + const makeProviderSessionReaper = (options?: ProviderSessionReaperLiveOptions) => Effect.gen(function* () { const providerService = yield* ProviderService; const directory = yield* ProviderSessionDirectory; const projectionSnapshotQuery = yield* ProjectionSnapshotQuery; - const inactivityThresholdMs = Math.max( - 1, - options?.inactivityThresholdMs ?? DEFAULT_INACTIVITY_THRESHOLD_MS, + const inactivityThreshold = normalizePositiveDuration( + options?.inactivityThreshold, + DEFAULT_INACTIVITY_THRESHOLD, ); - const sweepIntervalMs = Math.max(1, options?.sweepIntervalMs ?? DEFAULT_SWEEP_INTERVAL_MS); + const sweepInterval = normalizePositiveDuration(options?.sweepInterval, DEFAULT_SWEEP_INTERVAL); + const inactivityThresholdMs = Duration.toMillis(inactivityThreshold); + const sweepIntervalMs = Duration.toMillis(sweepInterval); const sweep = Effect.gen(function* () { const bindings = yield* directory.listBindings(); - const now = yield* Clock.currentTimeMillis; + const now = yield* DateTime.now; let reapedCount = 0; for (const binding of bindings) { @@ -43,8 +53,8 @@ const makeProviderSessionReaper = (options?: ProviderSessionReaperLiveOptions) = continue; } - const lastSeenMs = Date.parse(binding.lastSeenAt); - if (Number.isNaN(lastSeenMs)) { + const lastSeen = DateTime.make(binding.lastSeenAt); + if (Option.isNone(lastSeen)) { yield* Effect.logWarning("provider.session.reaper.invalid-last-seen", { threadId: binding.threadId, provider: binding.provider, @@ -53,7 +63,10 @@ const makeProviderSessionReaper = (options?: ProviderSessionReaperLiveOptions) = continue; } - const idleDurationMs = now - lastSeenMs; + const idleDuration = Duration.millis( + DateTime.toEpochMillis(now) - DateTime.toEpochMillis(lastSeen.value), + ); + const idleDurationMs = Duration.toMillis(idleDuration); if (idleDurationMs < inactivityThresholdMs) { continue; } @@ -117,7 +130,7 @@ const makeProviderSessionReaper = (options?: ProviderSessionReaperLiveOptions) = defect, }), ), - Effect.repeat(Schedule.spaced(Duration.millis(sweepIntervalMs))), + Effect.repeat(Schedule.spaced(sweepInterval)), ), ); diff --git a/packages/ssh/src/tunnel.test.ts b/packages/ssh/src/tunnel.test.ts index 80e684d861..a2e7ce8696 100644 --- a/packages/ssh/src/tunnel.test.ts +++ b/packages/ssh/src/tunnel.test.ts @@ -242,9 +242,9 @@ describe("ssh tunnel scripts", () => { Effect.result( waitForHttpReady({ baseUrl: "http://127.0.0.1:41773/", - timeoutMs: 1_000, - intervalMs: 100, - probeTimeoutMs: 250, + timeout: Duration.seconds(1), + interval: Duration.millis(100), + probeTimeout: Duration.millis(250), }), ), ); diff --git a/packages/ssh/src/tunnel.ts b/packages/ssh/src/tunnel.ts index 5ee5c68477..4ce790809e 100644 --- a/packages/ssh/src/tunnel.ts +++ b/packages/ssh/src/tunnel.ts @@ -50,11 +50,19 @@ import { export const DEFAULT_REMOTE_PORT = 3773; const REMOTE_PORT_SCAN_WINDOW = 200; -const SSH_READY_TIMEOUT_MS = 20_000; -const SSH_READY_PROBE_TIMEOUT_MS = 1_000; -const TUNNEL_SHUTDOWN_TIMEOUT_MS = 2_000; -const REMOTE_READY_TIMEOUT_MS = 15_000; -const REMOTE_REUSE_READY_TIMEOUT_MS = 2_000; +const SSH_READY_TIMEOUT = Duration.seconds(20); +const SSH_READY_PROBE_TIMEOUT = Duration.seconds(1); +const TUNNEL_SHUTDOWN_TIMEOUT = Duration.seconds(2); +const REMOTE_READY_TIMEOUT = Duration.seconds(15); +const REMOTE_REUSE_READY_TIMEOUT = Duration.seconds(2); + +const normalizePositiveDuration = ( + input: Duration.Input | undefined, + fallback: Duration.Duration, +) => { + const duration = input === undefined ? fallback : Duration.fromInputUnsafe(input); + return Duration.millis(Math.max(1, Duration.toMillis(duration))); +}; export interface RemoteT3RunnerOptions { readonly packageSpec?: string; @@ -686,9 +694,9 @@ export function buildRemoteLaunchScript(input?: RemoteT3RunnerOptions): string { T3_WAIT_READY_SCRIPT: stripTrailingNewlines(REMOTE_WAIT_READY_SCRIPT), T3_DEFAULT_REMOTE_PORT: String(DEFAULT_REMOTE_PORT), T3_REMOTE_PORT_SCAN_WINDOW: String(REMOTE_PORT_SCAN_WINDOW), - T3_READY_TIMEOUT_MS: String(REMOTE_READY_TIMEOUT_MS), - T3_REUSE_READY_TIMEOUT_MS: String(REMOTE_REUSE_READY_TIMEOUT_MS), - T3_READY_PROBE_TIMEOUT_MS: String(SSH_READY_PROBE_TIMEOUT_MS), + T3_READY_TIMEOUT_MS: String(Duration.toMillis(REMOTE_READY_TIMEOUT)), + T3_REUSE_READY_TIMEOUT_MS: String(Duration.toMillis(REMOTE_REUSE_READY_TIMEOUT)), + T3_READY_PROBE_TIMEOUT_MS: String(Duration.toMillis(SSH_READY_PROBE_TIMEOUT)), }); } @@ -870,15 +878,18 @@ const readRemoteServerLogTail = Effect.fn("ssh/tunnel.readRemoteServerLogTail")( export const waitForHttpReady = Effect.fn("ssh/tunnel.waitForHttpReady")(function* (input: { readonly baseUrl: string; - readonly timeoutMs?: number; - readonly intervalMs?: number; - readonly probeTimeoutMs?: number; + readonly timeout?: Duration.Input; + readonly interval?: Duration.Input; + readonly probeTimeout?: Duration.Input; readonly path?: string; }): Effect.fn.Return { - const timeoutMs = input.timeoutMs ?? 30_000; - const intervalMs = input.intervalMs ?? 100; - const probeTimeoutMs = input.probeTimeoutMs ?? SSH_READY_PROBE_TIMEOUT_MS; - const retryPolicy = Schedule.spaced(Duration.millis(intervalMs)).pipe( + const timeout = normalizePositiveDuration(input.timeout, Duration.seconds(30)); + const interval = normalizePositiveDuration(input.interval, Duration.millis(100)); + const probeTimeout = normalizePositiveDuration(input.probeTimeout, SSH_READY_PROBE_TIMEOUT); + const timeoutMs = Duration.toMillis(timeout); + const intervalMs = Duration.toMillis(interval); + const probeTimeoutMs = Duration.toMillis(probeTimeout); + const retryPolicy = Schedule.spaced(interval).pipe( Schedule.take(Math.max(0, Math.ceil(timeoutMs / intervalMs))), ); const requestUrl = new URL(input.path ?? "/", input.baseUrl).toString(); @@ -900,7 +911,7 @@ export const waitForHttpReady = Effect.fn("ssh/tunnel.waitForHttpReady")(functio Effect.gen(function* () { attempt += 1; const responseOption = yield* effect.pipe( - Effect.timeoutOption(Duration.millis(probeTimeoutMs)), + Effect.timeoutOption(probeTimeout), Effect.mapError( (cause) => new SshReadinessError({ @@ -953,7 +964,7 @@ export const waitForHttpReady = Effect.fn("ssh/tunnel.waitForHttpReady")(functio cause, }), ), - Effect.timeoutOption(Duration.millis(timeoutMs)), + Effect.timeoutOption(timeout), ); return yield* Option.match(result, { @@ -1236,7 +1247,7 @@ const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input: yield* Effect.raceFirst( waitForHttpReady({ baseUrl: input.httpBaseUrl, - timeoutMs: SSH_READY_TIMEOUT_MS, + timeout: SSH_READY_TIMEOUT, }), exitFailure, ).pipe( @@ -1296,7 +1307,7 @@ const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input: : child .kill({ killSignal: "SIGTERM", - forceKillAfter: TUNNEL_SHUTDOWN_TIMEOUT_MS, + forceKillAfter: TUNNEL_SHUTDOWN_TIMEOUT, }) .pipe(Effect.ignore), ), @@ -1540,7 +1551,7 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma [ tunnelEntry.process.kill({ killSignal: "SIGTERM", - forceKillAfter: TUNNEL_SHUTDOWN_TIMEOUT_MS, + forceKillAfter: TUNNEL_SHUTDOWN_TIMEOUT, }), stopRemoteServer( tunnelEntry.target, @@ -1594,7 +1605,7 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma remotePort: entry.remotePort, }); const readinessExit = yield* Effect.exit( - waitForHttpReady({ baseUrl: entry.httpBaseUrl, timeoutMs: 2_000 }), + waitForHttpReady({ baseUrl: entry.httpBaseUrl, timeout: REMOTE_REUSE_READY_TIMEOUT }), ); if (Exit.isSuccess(readinessExit)) { yield* Effect.logDebug("ssh.environment.tunnel.reused", {