diff --git a/apps/server/src/kin/host/sessionUpkeep.test.ts b/apps/server/src/kin/host/sessionUpkeep.test.ts index e46962d05526..b72e0089b264 100644 --- a/apps/server/src/kin/host/sessionUpkeep.test.ts +++ b/apps/server/src/kin/host/sessionUpkeep.test.ts @@ -1,22 +1,38 @@ import type { SDKMessage, SDKResultSuccess } from "@anthropic-ai/claude-agent-sdk"; -import { assert, it } from "@effect/vitest"; -import { KinAgentId, KinChatId, KinOrgId, KinWakeupId, ThreadId } from "@t3tools/contracts"; -import * as Fiber from "effect/Fiber"; +import { assert, it, vi } from "@effect/vitest"; +import { + DEFAULT_SERVER_SETTINGS, + EnvironmentId, + KinAgentId, + KinChatId, + KinOrgId, + KinWakeupId, + ProviderInstanceId, + ThreadId, +} from "@t3tools/contracts"; +import * as Clock from "effect/Clock"; import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; -import { KinChatRepository, layer as repositoryLayer } from "../chat/KinChatRepository.ts"; +import * as Stream from "effect/Stream"; import * as SqlClient from "effect/sql/SqlClient"; import * as TestClock from "effect/testing/TestClock"; +import type { ClaudeAgentSdkQuerySession } from "../../orchestration-v2/Adapters/ClaudeAdapterV2.ts"; +import { Scheduler } from "../../scheduling/Scheduler.ts"; +import { ServerSettingsService } from "../../serverSettings.ts"; +import * as Hub from "../chat/KinChatHub.ts"; +import { KinChatRepository, layer as repositoryLayer } from "../chat/KinChatRepository.ts"; import * as Budget from "../lead/KinBudget.ts"; import * as Queue from "../lead/KinEventQueue.ts"; -import * as Hub from "../chat/KinChatHub.ts"; +import { KEEP_WARM_PROMPT, KinLeadPrompt } from "../lead/LeadPrompt.ts"; import * as MemoryCache from "../memory/MemoryCache.ts"; +import { makeMigratedSqliteLayer } from "../persistence/migratedSqlite.testkit.ts"; import * as CacheParts from "./cacheParts.ts"; +import { KinCacheSessions } from "./cacheSessions.ts"; +import * as Compaction from "./sessionCompaction.ts"; import * as Upkeep from "./sessionUpkeep.ts"; -import { collectPing, makeCompactionRequest, makePingRequest } from "./sessionUpkeepQuery.ts"; -import { makeMigratedSqliteLayer } from "../persistence/migratedSqlite.testkit.ts"; -import { KEEP_WARM_PROMPT } from "../lead/LeadPrompt.ts"; +import * as Query from "./sessionUpkeepQuery.ts"; const minute = 60_000; const now = 1_794_009_600_000; @@ -59,21 +75,30 @@ const seed = Effect.fn("UpkeepTest.seed")(function* (gaps: ReadonlyArray let atMs = now - gaps.reduce((total, gap) => total + gap, 50) * minute; for (const [i, gap] of [0, ...gaps].entries()) { atMs += gap * minute; - const wakeupId = KinWakeupId.make(`turn-${i}`); - yield* sql`INSERT INTO kin_wakeups (wakeup_id, org_id, agent_id, model, started_at, ended_at, status, event_ids, thread_id, last_request_at) - VALUES (${wakeupId}, ${orgId}, ${agentId}, ${model}, ${atMs}, ${atMs}, 'completed', '[]', ${threadId}, ${atMs})`; - yield* CacheParts.recordUse(part, { - wakeupId, - startedAt: atMs, - lastRequestAt: atMs, - freshUsage: { - read: gap >= 60 ? 16_000 : 31_000, - written: gap >= 60 ? 19_000 : 4_000, - }, + yield* recordTurn(KinWakeupId.make(`turn-${i}`), atMs, part, { + read: gap >= 60 ? 16_000 : 31_000, + written: gap >= 60 ? 19_000 : 4_000, }); } }); +const recordTurn = Effect.fn("UpkeepTest.recordTurn")(function* ( + wakeupId: KinWakeupId, + at: number, + cachePart: CacheParts.CachePart, + freshUsage: CacheParts.CacheUsage, +) { + const sql = yield* SqlClient.SqlClient; + yield* sql`INSERT INTO kin_wakeups (wakeup_id, org_id, agent_id, model, started_at, ended_at, status, event_ids, thread_id, last_request_at) + VALUES (${wakeupId}, ${orgId}, ${agentId}, ${model}, ${at}, ${at}, 'completed', '[]', ${threadId}, ${at})`; + yield* CacheParts.recordUse(cachePart, { + wakeupId, + startedAt: at, + lastRequestAt: at, + freshUsage, + }); +}); + const usage = { read: 31_000, written: 100, input: 4, output: 1, cost: 0.008 }; const miss = { read: 16_000, written: 19_000, input: 4, output: 1, cost: 0.16 }; const run = ( @@ -103,12 +128,12 @@ const run = ( }); it.effect.each([ - ["fewer than 20 gaps", Array(19).fill(65), {}, false], + ["fewer than 20 gaps use startup windows", Array(19).fill(65), {}, true], ["50 minutes idle above threshold", Array(20).fill(65), {}, true], ["changed fingerprint", Array(20).fill(65), { fingerprint: "another-part" }, false], - ["system placement", Array(20).fill(65), { placement: "system" as const }, false], - ["host switch off", Array(20).fill(65), { enabled: false }, false], - ["daily use with too few observations", Array(20).fill(24 * 60), {}, false], + ["system placement before enough history", [], { placement: "system" as const }, false], + ["host switch off before enough history", [], { enabled: false }, false], + ["daily use with too few observations", Array(20).fill(24 * 60), {}, true], [ "no demand in the next 50 minutes despite enough samples", Array(20).fill(180), @@ -124,11 +149,117 @@ it.effect.each([ }).pipe(Effect.provide(layer)), ); +it.effect( + "a first real turn gets three startup pings, then another turn restarts the windows", + () => + Effect.gen(function* () { + yield* seed([]); + const sql = yield* SqlClient.SqlClient; + // Maintenance extends the cache clock but is not a ping or a predecessor. + yield* sql`INSERT INTO kin_wakeups (wakeup_id, org_id, agent_id, model, started_at, ended_at, + status, event_ids, kind, carry_json, last_request_at, cache_part, cache_request_started_at) + VALUES ('first-compaction', ${orgId}, ${agentId}, ${model}, ${now - minute}, + ${now - minute}, 'completed', '[]', 'upkeep', '{"action":"compaction"}', + ${now - minute}, ${part.fingerprint}, ${now - minute})`; + for (let window = 0; window < 3; window++) { + assert.deepEqual(yield* run(), [part.fingerprint], `startup window ${window + 1}`); + yield* TestClock.adjust("50 minutes"); + } + assert.deepEqual(yield* run(), []); + assert.deepEqual(yield* sql`SELECT last_turn_at FROM kin_cache_parts`, [ + { last_turn_at: now - 50 * minute }, + ]); + const realAt = now + 150 * minute; + yield* recordTurn(KinWakeupId.make("turn-after-startup"), realAt, part, usage); + yield* TestClock.adjust("50 minutes"); + assert.deepEqual(yield* run(), [part.fingerprint]); + }).pipe(Effect.provide(layer)), +); + +it.effect("maintenance does not open a late startup window", () => + Effect.gen(function* () { + yield* seed([]); + const sql = yield* SqlClient.SqlClient; + yield* sql`UPDATE kin_cache_parts SET last_request_at = ${now + 130 * minute}`; + yield* TestClock.adjust("180 minutes"); + assert.deepEqual(yield* run(), []); + }).pipe(Effect.provide(layer)), +); + +it.effect.each([ + ["regular returns", "owner", 65, true], + ["rare returns", "owner", 180, false], + ["a different seat does not supply the demand", "confined", 180, true], +] as const)("a new fingerprint follows the seat history: %s", ([, seat, gap, due]) => + Effect.gen(function* () { + yield* seed([10, ...Array(20).fill(gap)]); + const sql = yield* SqlClient.SqlClient; + yield* sql`UPDATE kin_cache_parts SET seat = ${seat} WHERE fingerprint = ${part.fingerprint}`; + const releasePart = { ...part, fingerprint: "release-part" }; + yield* recordTurn(KinWakeupId.make("first-after-release"), now, releasePart, miss); + yield* TestClock.adjust("50 minutes"); + assert.deepEqual( + yield* run({ fingerprint: releasePart.fingerprint }), + due ? [releasePart.fingerprint] : [], + ); + }).pipe(Effect.provide(layer)), +); + +it.effect("a new part waits after one measured miss and two misses stop across a newer turn", () => + Effect.gen(function* () { + yield* seed([]); + const sql = yield* SqlClient.SqlClient; + yield* sql`UPDATE kin_wakeups SET cache_measurement = ${JSON.stringify(miss)} WHERE wakeup_id = 'turn-0'`; + assert.deepEqual(yield* run({ outcome: { status: "completed", usage: miss } }), [ + part.fingerprint, + ]); + yield* TestClock.adjust("50 minutes"); + assert.deepEqual(yield* run(), [], "a lone miss waits"); + yield* recordTurn(KinWakeupId.make("turn-after-miss"), now + 50 * minute, part, miss); + yield* TestClock.adjust("50 minutes"); + assert.deepEqual(yield* run({ outcome: { status: "completed", usage: miss } }), [ + part.fingerprint, + ]); + yield* recordTurn(KinWakeupId.make("turn-after-second-miss"), now + 101 * minute, part, miss); + yield* TestClock.adjust("51 minutes"); + assert.deepEqual(yield* run(), [], "a second miss stops even after a real turn"); + }).pipe(Effect.provide(layer)), +); + +it.effect("a missed ping that rewrites only the prefix still counts as a miss on a new part", () => + Effect.gen(function* () { + yield* seed([]); + const sql = yield* SqlClient.SqlClient; + // The opening also wrote its first message; a missed ping rewrites only the shared prefix. + const opening = { read: 0, written: 39_672, input: 3 }; + const prefixMiss = { read: 0, written: 31_000, input: 4, output: 1, cost: 0.19 }; + yield* sql`UPDATE kin_wakeups SET cache_measurement = ${JSON.stringify(opening)} WHERE wakeup_id = 'turn-0'`; + assert.deepEqual(yield* run({ outcome: { status: "completed", usage: prefixMiss } }), [ + part.fingerprint, + ]); + yield* TestClock.adjust("50 minutes"); + assert.deepEqual(yield* run(), [], "a lone miss waits"); + yield* recordTurn(KinWakeupId.make("turn-after-miss"), now + 50 * minute, part, opening); + yield* TestClock.adjust("50 minutes"); + assert.deepEqual(yield* run({ outcome: { status: "completed", usage: prefixMiss } }), [ + part.fingerprint, + ]); + yield* recordTurn( + KinWakeupId.make("turn-after-second-miss"), + now + 101 * minute, + part, + opening, + ); + yield* TestClock.adjust("51 minutes"); + assert.deepEqual(yield* run(), [], "a second miss stops even after a real turn"); + }).pipe(Effect.provide(layer)), +); + it.effect( "writes a detached upkeep row only for the active company, and leaves history and the queue unchanged", () => Effect.gen(function* () { - yield* seed([10, ...Array(20).fill(65)]); + yield* seed([]); const sql = yield* SqlClient.SqlClient; yield* sql`INSERT INTO kin_org_state (org_id, paused, paused_at, paused_by) VALUES (${orgId}, 1, ${now}, 'rhea')`; @@ -136,7 +267,12 @@ it.effect( yield* sql`DELETE FROM kin_org_state WHERE org_id = ${orgId}`; yield* sql`UPDATE kin_agents SET retired_at = '2026-11-09T00:00:00.000Z' WHERE agent_id = ${agentId}`; assert.deepEqual(yield* run(), []); - yield* sql`UPDATE kin_agents SET retired_at = NULL WHERE agent_id = ${agentId}`; + yield* sql`UPDATE kin_agents SET retired_at = NULL, paused_at = '2026-11-09T00:00:00.000Z' WHERE agent_id = ${agentId}`; + assert.deepEqual(yield* run(), []); + yield* sql`UPDATE kin_agents SET paused_at = NULL WHERE agent_id = ${agentId}`; + yield* sql`UPDATE kin_wakeups SET status = 'running' WHERE wakeup_id = 'turn-0'`; + assert.deepEqual(yield* run(), []); + yield* sql`UPDATE kin_wakeups SET status = 'completed' WHERE wakeup_id = 'turn-0'`; assert.deepEqual(yield* run(), [part.fingerprint]); const rows = yield* sql`SELECT thread_id, run_id, status, event_ids, tokens_json FROM kin_wakeups WHERE kind = 'upkeep'`; @@ -164,17 +300,10 @@ it.effect( }).pipe(Effect.provide(repositoryLayer.pipe(Layer.provideMerge(layer)))), ); -it.effect("does not use another fingerprint's traffic and does not rewrite a dead cache", () => +it.effect("does not try to rewrite a dead cache", () => Effect.gen(function* () { - yield* seed([10, ...Array(20).fill(65)]); - const sql = yield* SqlClient.SqlClient; - yield* sql`UPDATE kin_wakeups SET cache_part = 'old-part' WHERE cache_part = ${part.fingerprint} AND wakeup_id = 'turn-21'`; - assert.deepEqual(yield* run(), []); - yield* sql`UPDATE kin_wakeups SET cache_part = ${part.fingerprint} WHERE cache_part = 'old-part'`; - yield* TestClock.adjust("9 minutes"); - assert.deepEqual(yield* run(), [part.fingerprint]); - yield* sql`UPDATE kin_cache_parts SET last_request_at = ${now - 50 * minute}`; - yield* TestClock.adjust("1 minute"); + yield* seed([]); + yield* TestClock.adjust("10 minutes"); assert.deepEqual(yield* run(), []); }).pipe(Effect.provide(layer)), ); @@ -287,7 +416,7 @@ it.effect("a ping's cost reaches the day's spend exactly once", () => it.effect("leaves the last sliver for a real turn when lowest priority is refused", () => Effect.gen(function* () { - yield* seed([10, ...Array(20).fill(65)]); + yield* seed([]); const sql = yield* SqlClient.SqlClient; yield* sql`INSERT INTO kin_budget_limits (org_id, limits_json) VALUES (${orgId}, '{"leadUnits":4000,"workerUnits":null}')`; const budget = yield* Budget.KinBudget; @@ -303,7 +432,7 @@ it.effect( "with budget to spare, a full rewrite leaves real turns and scheduled tasks admitted", () => Effect.gen(function* () { - yield* seed([10, ...Array(20).fill(65)]); + yield* seed([]); const sql = yield* SqlClient.SqlClient; yield* sql`INSERT INTO kin_budget_limits (org_id, limits_json) VALUES (${orgId}, '{"leadUnits":100000,"workerUnits":null}')`; const budget = yield* Budget.KinBudget; @@ -320,7 +449,7 @@ it.effect( it.effect("rechecks lowest priority at exactly 30% left after preparing a ping", () => Effect.gen(function* () { - yield* seed([10, ...Array(20).fill(65)]); + yield* seed([]); const sql = yield* SqlClient.SqlClient; yield* sql`INSERT INTO kin_budget_limits (org_id, limits_json) VALUES (${orgId}, '{"leadUnits":100,"workerUnits":null}')`; const budget = yield* Budget.KinBudget; @@ -344,16 +473,19 @@ it.effect("rechecks lowest priority at exactly 30% left after preparing a ping", }).pipe(Effect.provide(layer)), ); -it.effect("does not estimate from just three at-risk gaps even with 25 total", () => +it.effect("uses the startup windows for just three at-risk gaps even with 25 total", () => Effect.gen(function* () { yield* seed([...Array(22).fill(10), 65, 65, 65]); - assert.deepEqual(yield* run(), []); + assert.deepEqual(yield* run(), [part.fingerprint]); }).pipe(Effect.provide(layer)), ); -it.effect("treats a failed ping without usage as a miss until newer real demand", () => +it.effect.each([ + ["startup", []], + ["learned demand", [10, ...Array(20).fill(65)]], +] as const)("an unpriced failure waits for a real turn with %s", ([, gaps]) => Effect.gen(function* () { - yield* seed([10, ...Array(20).fill(65)]); + yield* seed(gaps); assert.deepEqual(yield* run({ outcome: { status: "failed", usage: null } }), [ part.fingerprint, ]); @@ -361,8 +493,9 @@ it.effect("treats a failed ping without usage as a miss until newer real demand" assert.deepEqual(yield* run(), []); const sql = yield* SqlClient.SqlClient; assert.isEmpty(yield* sql`SELECT * FROM kin_budget_charges`); - yield* sql`UPDATE kin_cache_parts SET last_turn_at = ${now + 15 * minute}, last_request_at = ${now + 15 * minute}`; - yield* TestClock.adjust("60 minutes"); + yield* TestClock.adjust("10 minutes"); + yield* recordTurn(KinWakeupId.make("after-unpriced-failure"), now + 15 * minute, part, miss); + yield* TestClock.adjust("50 minutes"); assert.deepEqual(yield* run(), [part.fingerprint]); }).pipe(Effect.provide(layer)), ); @@ -383,6 +516,175 @@ const startFrame = { }, }, } as SDKMessage; + +it.effect("the registered job gates ticks, orders work and rechecks settings after restart", () => + Effect.gen(function* () { + yield* seed([]); + const trace: string[] = []; + const cache = yield* KinCacheSessions; + let upkeepEnabled = true; + const hostSettings = () => ({ ...DEFAULT_SERVER_SETTINGS, kinSessionUpkeep: upkeepEnabled }); + const settings = Layer.mock(ServerSettingsService)({ + getSettings: Effect.sync(hostSettings), + }); + const observed = { + ...cache, + prune: (at: number) => { + trace.push("prune"); + cache.prune(at); + }, + current: (...args: Parameters) => { + trace.push("check"); + return cache.current(...args); + }, + keep: (...args: Parameters) => { + trace.push("keep"); + cache.keep(...args); + }, + }; + using _compaction = vi.spyOn(Compaction, "tick").mockImplementation(() => + Effect.sync(() => { + trace.push("compaction"); + }), + ); + let releases = 0; + using _send = vi.spyOn(Query, "send").mockImplementation((_cache, _session, stillDue) => + Effect.gen(function* () { + trace.push("send"); + if (++releases === 1) { + upkeepEnabled = false; + assert.isFalse(yield* stillDue); + return { status: "skipped" } as const; + } + assert.isTrue(yield* stillDue); + return { status: "completed", usage } as const; + }), + ); + const jobs: Effect.Effect[] = []; + const scheduler = Scheduler.of({ + register: (name: string, work: Effect.Effect) => + Effect.context().pipe( + Effect.tap((context) => + Effect.sync(() => { + assert.equal(name, "kin-session-upkeep"); + jobs.push(work.pipe(Effect.provideContext(context), Effect.orDie)); + }), + ), + Effect.asVoid, + ), + }); + yield* Layer.build( + Upkeep.layer.pipe( + Layer.provide(Layer.succeed(Scheduler, scheduler)), + Layer.provide(Layer.succeed(KinCacheSessions, observed)), + Layer.provide(settings), + Layer.provide(Layer.mock(KinLeadPrompt)({})), + ), + ); + assert.lengthOf(jobs, 1); + const tick = jobs[0]!; + yield* tick; + assert.deepEqual(trace.splice(0), ["prune", "compaction", "check"]); + yield* TestClock.adjust("4 minutes"); + yield* tick; + assert.isEmpty(trace); + yield* TestClock.adjust("1 minute"); + yield* tick; + assert.deepEqual(trace.splice(0), ["prune", "compaction", "check"]); + assert.equal(releases, 0, "stored rows alone cannot ping after restart"); + + const before = hostSettings(); + const unused = Effect.die("unexpected SDK operation"); + const query = yield* cache.observeQuery( + { + options: { + model, + sessionId: "fixture", + tools: [], + permissionMode: "default", + mcpServers: { + "t3-code": { + type: "http", + url: "http://127.0.0.1/kin/mcp", + headers: { Authorization: "Bearer invented-fixture" }, + }, + }, + }, + threadId, + seat: part.seat, + block: { + type: "text", + text: "Fixture instructions", + cache_control: { type: "ephemeral", ttl: "1h" }, + }, + }, + before, + { + offer: () => Effect.void, + messages: Stream.make(startFrame), + setModel: () => unused, + applyFlagSettings: () => unused, + setPermissionMode: () => unused, + renameSession: () => unused, + stopTask: () => unused, + backgroundTasks: () => unused, + mcpServerStatus: unused, + readMcpResource: () => unused, + mcpAuthenticate: () => unused, + mcpSubmitOAuthCallbackUrl: () => unused, + reconnectMcpServer: () => unused, + callMcpTool: () => unused, + listPermissionRules: unused, + interrupt: unused, + close: unused, + } satisfies ClaudeAgentSdkQuerySession, + ); + yield* cache.observeList( + { + environmentId: EnvironmentId.make("tidewater"), + requestNamespace: "fixture", + issuedAt: 0, + client: undefined, + capabilities: new Set(), + thread: { + threadId, + providerSessionId: "fixture", + providerInstanceId: ProviderInstanceId.make("claudeAgent"), + }, + }, + "Bearer invented-fixture", + "fixture-roster", + ); + const at = yield* Clock.currentTimeMillis; + const sql = yield* SqlClient.SqlClient; + const wakeupId = KinWakeupId.make("first-after-restart"); + yield* sql`INSERT INTO kin_wakeups (wakeup_id, org_id, agent_id, model, started_at, ended_at, status, event_ids, thread_id, last_request_at) + VALUES (${wakeupId}, ${orgId}, ${agentId}, ${model}, ${at}, ${at}, 'completed', '[]', ${threadId}, ${at})`; + yield* query.offer({ + type: "user", + message: { role: "user", content: "Ready?" }, + session_id: "fixture", + parent_tool_use_id: null, + }); + yield* Stream.runDrain(query.messages); + yield* cache.recordTurn({ orgId, agentId, threadId, wakeupId, lastRequestAt: at }); + yield* TestClock.adjust("50 minutes"); + yield* tick; + assert.deepEqual(trace.slice(0, 3), ["prune", "compaction", "check"]); + assert.equal(trace.at(-1), "send"); + trace.length = 0; + assert.isEmpty(yield* sql`SELECT 1 FROM kin_wakeups WHERE kind = 'upkeep'`); + upkeepEnabled = true; + yield* TestClock.adjust("5 minutes"); + yield* tick; + assert.equal(releases, 2); + assert.equal(trace.at(-1), "keep"); + assert.deepEqual(yield* sql`SELECT status FROM kin_wakeups WHERE kind = 'upkeep'`, [ + { status: "completed" }, + ]); + }).pipe(Effect.provide(Layer.mergeAll(layer, KinCacheSessions.layer))), +); + const deltaFrame = { type: "stream_event", parent_tool_use_id: null, @@ -396,7 +698,7 @@ it.effect("recovers reported usage on stream failure without charging frames twi yield deltaFrame; throw new Error("fixture disconnect"); } - const billed = yield* collectPing(interrupted()); + const billed = yield* Query.collectPing(interrupted()); assert.deepEqual(billed, { status: "failed", usage: { ...usage, output: 2, cost: null } }); }), ); @@ -434,7 +736,7 @@ it.effect( session_id: "saved-session", } satisfies SDKResultSuccess; } - const outcome = yield* collectPing(compacted(), { + const outcome = yield* Query.collectPing(compacted(), { counts: { read: 137_000 - usage.read, written: 6_000 - usage.written, @@ -459,7 +761,7 @@ it.effect.each([false, true])("keeps exactly the recorded usage at timeout (know started.resolve(); await done.promise; } - const collecting = yield* collectPing(stalled()).pipe(Effect.forkChild); + const collecting = yield* Query.collectPing(stalled()).pipe(Effect.forkChild); yield* Effect.promise(() => started.promise); yield* TestClock.adjust("90 seconds"); done.resolve(); @@ -507,7 +809,7 @@ it.effect("charges a first-response tool-use limit result as one completed ping" }, } as SDKMessage; } - const result = yield* collectPing(firstResponse()); + const result = yield* Query.collectPing(firstResponse()); assert.equal(requests, 1); assert.deepEqual(result, { status: "completed", usage }); yield* seed([10, ...Array(20).fill(65)]); @@ -520,9 +822,13 @@ it.effect("charges a first-response tool-use limit result as one completed ping" }).pipe(Effect.provide(layer)), ); -it.effect("a quiet company sends no pings for a week", () => +it.effect("a quiet company stops pinging after the startup windows", () => Effect.gen(function* () { yield* seed([]); + for (let window = 0; window < 3; window++) { + assert.deepEqual(yield* run(), [part.fingerprint]); + yield* TestClock.adjust("50 minutes"); + } for (let day = 0; day < 7; day++) { assert.deepEqual(yield* run(), []); yield* TestClock.adjust("1 day"); @@ -551,8 +857,8 @@ it.effect.each(["ping", "compaction"] as const)( const summaries: string[] = []; const request = kind === "ping" - ? makePingRequest(input, "new-session") - : makeCompactionRequest(input, "new-session", (text) => summaries.push(text)); + ? Query.makePingRequest(input, "new-session") + : Query.makeCompactionRequest(input, "new-session", (text) => summaries.push(text)); if ("resume" in request.options && "PostCompact" in request.options.hooks) { assert.equal(request.options.resume, "new-session"); assert.notProperty(request.options, "maxTurns"); diff --git a/apps/server/src/kin/host/sessionUpkeep.ts b/apps/server/src/kin/host/sessionUpkeep.ts index 1de1929d58bb..a6ff89a21751 100644 --- a/apps/server/src/kin/host/sessionUpkeep.ts +++ b/apps/server/src/kin/host/sessionUpkeep.ts @@ -7,6 +7,7 @@ import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import * as SqlClient from "effect/sql/SqlClient"; +import type { Fragment } from "effect/sql/Statement"; import * as Scheduler from "../../scheduling/Scheduler.ts"; import { ServerSettingsService } from "../../serverSettings.ts"; @@ -22,6 +23,8 @@ import { CACHE_LIFETIME_MS, KinCacheSessions } from "./cacheSessions.ts"; const EVERY_MS = 5 * MINUTE_MS; const PING_AT = 50 * MINUTE_MS; const LOOKBACK = 14 * DAY_MS; +// At about 1/12 of a cold Opus turn per hit, three windows cover ordinary pauses for about $0.075. +const STARTUP_WINDOWS = 3; const UsageJson = Schema.fromJsonString(PingUsage); const encodeUsage = Schema.encodeEffect(UsageJson); @@ -35,7 +38,7 @@ interface Candidate extends CachePart { interface Due extends Candidate { readonly idleMinutes: number; - readonly share: number; + readonly share: number | null; readonly coldRead: number; } @@ -44,51 +47,86 @@ type SendPing = (due: Due, stillDue: Effect.Effect) => Effect.Effect) => usage.read * 0.1 + usage.written * 2 + usage.input + usage.output * 5; +const oneOpening = Effect.fn("KinSessionUpkeep.oneOpening")(function* (turns: Fragment) { + const sql = yield* SqlClient.SqlClient; + const [sample] = yield* sql<{ read: number; written: number; input: number }>` + WITH turns AS (${turns}) + SELECT json_extract(usage, '$.read') AS read, json_extract(usage, '$.written') AS written, + COALESCE(json_extract(usage, '$.input'), 0) AS input + FROM turns WHERE usage IS NOT NULL ORDER BY started DESC, wakeup_id DESC LIMIT 1`; + if (sample === undefined) return undefined; + // One opening cannot separate the prefix from its tail; use its larger cache bucket as size. + return { + rewrite: Math.max(sample.read, sample.written) * 2, + warmCost: (sample.read + sample.written) * 0.1 + sample.input, + coldRead: sample.read <= sample.written ? sample.read : 0, + }; +}); + const estimate = Effect.fn("KinSessionUpkeep.estimate")(function* (part: Candidate, now: number) { const sql = yield* SqlClient.SqlClient; // Pings extend cache lifetime but are not demand; they must not reset the observed idle gap. const idle = now - part.lastTurnAt; const cutoff = now - LOOKBACK; - const [gaps] = yield* sql<{ - atRisk: number; - ended: number; - warmRead: number | null; - warmCost: number | null; - coldRead: number | null; - coldWrite: number | null; + const turns = sql` + SELECT w.cache_part AS fingerprint, w.wakeup_id, w.cache_request_started_at AS started, + w.last_request_at AS last, w.cache_measurement AS usage + FROM kin_cache_parts p JOIN kin_wakeups w + ON w.cache_part = p.fingerprint AND w.org_id = p.org_id AND w.agent_id = p.agent_id + WHERE p.org_id = ${part.orgId} AND p.agent_id = ${part.agentId} AND p.seat = ${part.seat} + AND w.kind = 'turn' AND w.cache_request_started_at BETWEEN ${cutoff} AND ${now} + AND w.last_request_at IS NOT NULL`; + const [demand] = yield* sql<{ atRisk: number; ended: number }>` + WITH turns AS (${turns}), requests AS ( + SELECT started, MAX(last) OVER ( + ORDER BY started, wakeup_id ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING + ) AS preceding FROM turns + ) + SELECT COUNT(CASE WHEN started - preceding >= ${idle} THEN 1 END) AS "atRisk", + COUNT(CASE WHEN started - preceding BETWEEN ${idle} AND ${idle + PING_AT} THEN 1 END) AS ended + FROM requests WHERE started > preceding`; + if (demand === undefined) return undefined; + const share = demand.atRisk < 20 ? null : demand.ended / demand.atRisk; + // Leave room for the scheduler's jitter; another upkeep action cannot extend these windows. + if (share === null && idle >= STARTUP_WINDOWS * CACHE_LIFETIME_MS) return undefined; + const [paired] = yield* sql<{ + warmRead: number; + warmCost: number; + coldRead: number; + coldWrite: number; }>` - WITH requests AS ( - SELECT cache_request_started_at AS started, cache_measurement AS usage, - MAX(last_request_at) OVER ( - ORDER BY cache_request_started_at, wakeup_id ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING - ) AS preceding - FROM kin_wakeups WHERE cache_part = ${part.fingerprint} AND kind = 'turn' - AND cache_request_started_at BETWEEN ${cutoff} AND ${now} - AND last_request_at IS NOT NULL + WITH turns AS (${turns}), requests AS ( + SELECT fingerprint, started, usage, MAX(last) OVER ( + PARTITION BY fingerprint ORDER BY started, wakeup_id + ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING + ) AS preceding FROM turns ), gaps AS ( - SELECT started - preceding AS gap, + SELECT fingerprint, started, started - preceding AS gap, json_extract(usage, '$.read') AS read, json_extract(usage, '$.written') AS written, COALESCE(json_extract(usage, '$.input'), 0) AS input - FROM requests WHERE preceding IS NOT NULL AND started > preceding + FROM requests WHERE usage IS NOT NULL AND started > preceding + ), prices AS ( + SELECT fingerprint, MAX(started) AS latest, + MIN(CASE WHEN gap < ${CACHE_LIFETIME_MS} THEN read END) AS "warmRead", + MIN(CASE WHEN gap < ${CACHE_LIFETIME_MS} THEN read * 0.1 + written * 2 + input END) AS "warmCost", + MAX(CASE WHEN gap >= ${CACHE_LIFETIME_MS} THEN read END) AS "coldRead", + MIN(CASE WHEN gap >= ${CACHE_LIFETIME_MS} THEN written END) AS "coldWrite" + FROM gaps GROUP BY fingerprint ) - SELECT COUNT(CASE WHEN gap >= ${idle} THEN 1 END) AS "atRisk", - COUNT(CASE WHEN gap BETWEEN ${idle} AND ${idle + PING_AT} THEN 1 END) AS ended, - MIN(CASE WHEN gap < ${CACHE_LIFETIME_MS} THEN read END) AS "warmRead", - MIN(CASE WHEN gap < ${CACHE_LIFETIME_MS} THEN read * 0.1 + written * 2 + input END) AS "warmCost", - MAX(CASE WHEN gap >= ${CACHE_LIFETIME_MS} THEN read END) AS "coldRead", - MIN(CASE WHEN gap >= ${CACHE_LIFETIME_MS} THEN written END) AS "coldWrite" - FROM gaps`; - if ( - gaps === undefined || - gaps.atRisk < 20 || - gaps.warmRead === null || - gaps.warmCost === null || - gaps.coldRead === null || - gaps.coldWrite === null - ) - return undefined; - const rewrite = Math.min(gaps.warmRead - gaps.coldRead, gaps.coldWrite) * 2; - if (rewrite <= 0) return undefined; + SELECT "warmRead", "warmCost", "coldRead", "coldWrite" FROM prices + WHERE "warmRead" IS NOT NULL AND "warmCost" IS NOT NULL + AND "coldRead" IS NOT NULL AND "coldWrite" IS NOT NULL + ORDER BY (fingerprint = ${part.fingerprint}) DESC, latest DESC, fingerprint LIMIT 1`; + const prices = + paired === undefined + ? yield* oneOpening(turns) + : { + rewrite: Math.min(paired.warmRead - paired.coldRead, paired.coldWrite) * 2, + warmCost: paired.warmCost, + coldRead: paired.coldRead, + }; + if (prices === undefined || prices.rewrite <= 0) return undefined; + const { rewrite, warmCost, coldRead } = prices; const [measured] = yield* sql<{ tokens: string | null; endedAt: number; @@ -106,25 +144,31 @@ const estimate = Effect.fn("KinSessionUpkeep.estimate")(function* (part: Candida sample !== undefined && (sample.cost !== null || measured?.status === "completed") ? costUnits(sample) : undefined; - if (measured?.status === "completed" && price !== undefined && price > rewrite) { + // One opening counts its first message as prefix, so a full miss can cost under `rewrite`. + const missed = (usage: typeof PingUsage.Type) => + costUnits(usage) > rewrite || usage.read <= coldRead; + if (measured?.status === "completed" && sample !== undefined && missed(sample)) { // A real turn permits the retry; only another upkeep request can break its miss streak. const [previous] = yield* sql<{ status: string; tokens: string | null }>` SELECT status, tokens_json AS tokens FROM kin_wakeups WHERE cache_part = ${part.fingerprint} AND kind = 'upkeep' AND cache_request_started_at >= ${cutoff} + AND COALESCE(json_extract(carry_json, '$.action'), 'ping') = 'ping' AND (cache_request_started_at, wakeup_id) < (${measured.requestAt}, ${measured.wakeupId}) ORDER BY cache_request_started_at DESC, wakeup_id DESC LIMIT 1`; const prior = previous?.status === "completed" ? Option.getOrUndefined(decodeUsage(previous.tokens)) : undefined; - if (prior === undefined || costUnits(prior) <= rewrite) price = undefined; + if (prior !== undefined && missed(prior)) return undefined; + price = undefined; } // A lone miss or unpriced failure waits for a newer turn before using the warm-opening estimate. if (price === undefined && measured !== undefined && measured.endedAt >= part.lastTurnAt) return undefined; - const ping = price ?? gaps.warmCost + 5; - const share = gaps.ended / gaps.atRisk; - return share >= ping / rewrite ? { share, coldRead: gaps.coldRead } : undefined; + const ping = price ?? warmCost + 5; + return ping <= rewrite && (share === null || share >= ping / rewrite) + ? { share, coldRead } + : undefined; }); export const check = Effect.fn("KinSessionUpkeep.check")(function* (input: {