diff --git a/apps/server/src/environmentControl/EnvironmentControl.test.ts b/apps/server/src/environmentControl/EnvironmentControl.test.ts index d734da0125f1e..a8212a3d1a3a8 100644 --- a/apps/server/src/environmentControl/EnvironmentControl.test.ts +++ b/apps/server/src/environmentControl/EnvironmentControl.test.ts @@ -150,6 +150,95 @@ describe("managed cloud commands", () => { }); }); + it("puts a chat its upkeep moved off a Mac back on one without a client, retrying until it lands", async () => { + await withLease(async ({ registry, driver }) => { + const outcomes: Array = [new Error("no Mac yet"), "moved"]; + const reported: string[] = []; + const manager = createEnvironmentControl( + [], + { + ...driver, + resume: async () => { + const outcome = outcomes.shift(); + if (outcome instanceof Error) throw outcome; + if (outcome === undefined) throw new ProvisionedSandboxMissing(); + return { namespaceProxy: { proxyId: "proxy", proxyOrigin: "https://moved.example" } }; + }, + upkeepChat: async () => "reopen", + }, + registry, + async () => ({ activity: "busy" }), + async () => {}, + (message) => reported.push(message), + ); + await manager.upkeepCloudChats(); + expect(await registry.findById("lease")).toMatchObject({ state: "active" }); + expect(reported).toEqual(["cloud chat upkeep failed"]); + await manager.upkeepCloudChats(); + expect(await registry.findById("lease")).toMatchObject({ + state: "active", + namespaceProxy: { proxyId: "proxy", proxyOrigin: "https://moved.example" }, + }); + await manager.upkeepCloudChats(); + expect( + await registry.findById("lease"), + "an expired snapshot ends the retries", + ).toMatchObject({ state: "missing" }); + }); + }); + + it("moves a working chat at most three times in a row with no client, then lets it sleep until opened", async () => { + await withLease(async ({ registry, driver }) => { + const resumes: Array = [new Error("no Mac yet")]; + const paused: string[] = []; + const manager = createEnvironmentControl( + [], + { + ...driver, + resume: async () => { + const outcome = resumes.shift() ?? "moved"; + if (outcome instanceof Error) throw outcome; + return {}; + }, + pause: async ({ sandboxId }) => void paused.push(sandboxId), + // Every pass finds the chat still working at its Mac's deadline. + upkeepChat: async () => "reopen", + }, + registry, + async () => ({ activity: "busy" }), + ); + const pass = async () => { + await manager.upkeepCloudChats(); + return (await registry.findById("lease"))?.state; + }; + const passes = async (count: number) => { + const states: Array = []; + for (let index = 0; index < count; index++) states.push(await pass()); + return states; + }; + + expect(await passes(5), "a failed move is not counted").toEqual([ + "active", + "active", + "active", + "active", + "paused", + ]); + expect(paused).toEqual(["sandbox"]); + expect(await pass(), "a paused chat is not moved").toBe("paused"); + + expect(await manager.resume(resumeInput)).toEqual({ kind: "resumed" }); + expect(await passes(2)).toEqual(["active", "active"]); + expect(await manager.touch({ leaseId: "lease" })).toEqual({ kind: "touched" }); + expect(await passes(4), "a client heartbeat starts the count again").toEqual([ + "active", + "active", + "active", + "paused", + ]); + }); + }); + it("upkeeps each chat on its own, so one slow save never holds up another chat's deadline", async () => { await withSqlRegistry(async (registry) => { // The slow chat is listed first, so a pass that awaited chats in turn would never reach the other. diff --git a/apps/server/src/environmentControl/EnvironmentControl.ts b/apps/server/src/environmentControl/EnvironmentControl.ts index 741edee6852d8..64555c5aeae1c 100644 --- a/apps/server/src/environmentControl/EnvironmentControl.ts +++ b/apps/server/src/environmentControl/EnvironmentControl.ts @@ -150,14 +150,23 @@ const refused = (reason: keyof typeof refusalMessages): EnvironmentControlResult message: refusalMessages[reason], }); +/** + * Moves to a new Mac upkeep makes in a row for a chat still working at its Mac's deadline while no + * client heartbeats or resumes it. Each costs a Mac and prompts the agent to continue, so a chat + * that never settles is put to sleep after this many. + */ +const MAX_UNWATCHED_MOVES = 3; + /** * One upkeep pass for a chat on the Namespace instance engine: a periodic - * save, or a release ahead of its Mac's deadline. Null for any other lease. + * save, or a release ahead of its Mac's deadline. `reopen` when the chat is + * off its Mac but must not sleep, such as one still working at the deadline, + * or on a Mac a move never finished restoring. Null for any other lease. */ type UpkeepChat = (input: { readonly sandboxId: string; - readonly busy: () => Promise; -}) => Promise<"kept" | "released" | "missing" | null>; + readonly idle: () => Promise; +}) => Promise<"kept" | "released" | "reopen" | "missing" | null>; export function createEnvironmentControl( targets: ReadonlyArray, @@ -206,6 +215,23 @@ export function createEnvironmentControl( if (lease.state !== "active" || !lease.remoteAccess) return; await pullUsage(lease).catch(() => undefined); }; + /** Brings a lease's machine back and records it awake: a client's resume, or a moved chat's. */ + const wake = async ( + lease: ProvisionedLease, + environmentId: string | undefined, + hostMove = false, + ) => { + const resumed = await driver.resume({ + leaseId: lease.leaseId, + sandboxId: lease.sandboxId, + ...(environmentId ? { environmentId } : {}), + providerInstanceId: lease.providerInstanceId, + ...(lease.namespaceResource ? { namespaceResource: lease.namespaceResource } : {}), + ...(lease.namespaceProxy ? { namespaceProxy: lease.namespaceProxy } : {}), + }); + if (!(await leaseRegistry?.markActive({ leaseId: lease.leaseId, hostMove, ...resumed }))) + throw new Error("Lease could not be resumed"); + }; const snapshot = async (target: ManagedTarget): Promise => { let state: ComputeState; try { @@ -291,7 +317,7 @@ export function createEnvironmentControl( if ( lease.state === "active" && (await activity(lease)) === "busy" && - (await leaseRegistry.touch(lease.leaseId)) + (await leaseRegistry.touch(lease.leaseId, undefined, "host")) ) continue; const release = @@ -493,16 +519,7 @@ export function createEnvironmentControl( message: "This workspace could not be found. Reconnect was refused.", }; if (lease.state === "missing") throw new ProvisionedSandboxMissing(); - const resumed = await driver.resume({ - leaseId: lease.leaseId, - sandboxId: lease.sandboxId, - environmentId: input.environmentId, - providerInstanceId: lease.providerInstanceId, - ...(lease.namespaceResource ? { namespaceResource: lease.namespaceResource } : {}), - ...(lease.namespaceProxy ? { namespaceProxy: lease.namespaceProxy } : {}), - }); - if (!(await leaseRegistry.markActive({ leaseId: lease.leaseId, ...resumed }))) - throw new Error("Lease could not be resumed"); + await wake(lease, input.environmentId); return { kind: "resumed" }; })() .catch(async (cause): Promise => { @@ -636,11 +653,25 @@ export function createEnvironmentControl( try { const result = await upkeepChat({ sandboxId: lease.sandboxId, - busy: async () => (await activity(lease)) === "busy", + idle: async () => (await activity(lease)) === "idle", }); if (result === "released") await leaseRegistry.markPaused(lease.leaseId); if (result === "missing") await leaseRegistry.markMissing(lease.leaseId); + // Still held, so neither the reaper nor a client's pause lands between the move's + // release and its new Mac. A failed move leaves the lease awake for the next pass. + // Past the cap the chat sleeps as an idle one does, and opening it continues it; the + // release also ends a move a host restart left on a half-restored Mac. + if (result === "reopen") { + const moves = (await leaseRegistry.findById(lease.leaseId))?.unwatchedMoves ?? 0; + if (moves < MAX_UNWATCHED_MOVES) + await wake(lease, lease.owner?.environmentId, true); + else if ((await driver.pause({ sandboxId: lease.sandboxId })) === "missing") + await leaseRegistry.markMissing(lease.leaseId); + else await leaseRegistry.markPaused(lease.leaseId); + } } catch (cause) { + if (cause instanceof ProvisionedSandboxMissing) + await leaseRegistry.markMissing(lease.leaseId).catch(() => undefined); // The next pass retries. A snapshot over its cap fails here every pass until the // deadline, so it must be visible. reportFailure("cloud chat upkeep failed", { chatId: lease.leaseId, cause }); @@ -979,9 +1010,9 @@ export const layer = Layer.effect( const state = await chat.mac.touch(chat.operation); return state === "released" ? "paused" : state; }, - upkeepChat: async ({ sandboxId, busy }) => { + upkeepChat: async ({ sandboxId, idle }) => { const chat = await instanceChat(sandboxId); - return chat ? chat.mac.upkeep(chat.operation, chat.manifest, busy) : null; + return chat ? chat.mac.upkeep(chat.operation, chat.manifest, idle) : null; }, // A box this manager provisioned resumes through the runtime that // prepared it, which starts its T3 server again if it died and diff --git a/apps/server/src/environmentControl/NamespaceMacRuntime.test.ts b/apps/server/src/environmentControl/NamespaceMacRuntime.test.ts index 7f02632801aac..57e9df5cb8d05 100644 --- a/apps/server/src/environmentControl/NamespaceMacRuntime.test.ts +++ b/apps/server/src/environmentControl/NamespaceMacRuntime.test.ts @@ -635,12 +635,75 @@ describe("Namespace Mac runtime", () => { const ready = await t.runtime.prepare(t.operation("pending"), t.manifest); const op = t.operation(ready.environmentId); await t.write("agent.txt", "work\n"); - expect(await t.runtime.upkeep(op, t.manifest, async () => true)).toBe("kept"); - expect(await t.runtime.upkeep(op, t.manifest, async () => false)).toBe("released"); + expect(await t.runtime.upkeep(op, t.manifest, async () => false)).toBe("kept"); + expect(await t.runtime.upkeep(op, t.manifest, async () => true)).toBe("released"); expect(t.namespace.live()).toEqual([]); expect(await t.runtime.touch(op)).toBe("released"); expect(t.namespace.departures.map(({ departure }) => departure)).toEqual(["abandon"]); }); + + it("moves a chat still working at its deadline off its Mac, and asks for a new Mac until one holds it", async () => { + const t = await setup({ lifetimeMs: 5 * MINUTE }); + const ready = await t.runtime.prepare(t.operation("pending"), t.manifest); + const op = t.operation(ready.environmentId); + const idle = async () => false; + await t.write("agent.txt", "mid-turn\n"); + expect(await t.runtime.upkeep(op, t.manifest, idle)).toBe("reopen"); + expect(t.namespace.live()).toEqual([]); + expect(await t.record()).toMatchObject({ kind: "idle", snapshot: { mode: "final" } }); + expect( + await t.runtime.upkeep(op, t.manifest, idle), + "a host that restarted before reopening it still reopens it", + ).toBe("reopen"); + + await t.runtime.resume(op, t.manifest); + expect(await t.read("agent.txt")).toBe("mid-turn\n"); + const moved = await t.record(); + if (moved?.kind !== "live") throw new Error("expected a live Mac"); + await t.namespace.kill(moved.mac.incarnation.instanceId); + expect( + await t.runtime.upkeep(op, t.manifest, idle), + "an awake chat whose Mac died goes back on one", + ).toBe("reopen"); + + await t.runtime.resume(op, t.manifest); + expect( + await t.runtime.upkeep(op, t.manifest, async () => true), + "an idle chat at its deadline is released, not moved", + ).toBe("released"); + }); + + it("finishes a move a host restart cut off mid-restore, on the Mac it already made", async () => { + const t = await setup(); + const ready = await t.runtime.prepare(t.operation("pending"), t.manifest); + const op = t.operation(ready.environmentId); + const idle = async () => false; + await t.write("agent.txt", "mid-turn\n"); + expect(await t.runtime.release(op, t.manifest)).toBe("released"); + const released = await t.record(); + // The move's create was recorded, then the host died before the chat was restored onto it. + const mac = await t.namespace.instances.create({ + labels: { "t3.chat": chatId }, + cache: null, + deadline: Date.now() + 60 * MINUTE, + size: "m", + purpose: "t3 chat", + }); + await t.overwrite({ + kind: "live", + snapshot: released?.snapshot ?? null, + mac: { incarnation: mac, cache: "unknown" }, + }); + + expect( + await t.runtime.upkeep(op, t.manifest, idle), + "the restarted host's upkeep reopens it", + ).toBe("reopen"); + await t.runtime.resume(op, t.manifest); + expect(t.namespace.live(), "no second Mac").toEqual([mac.instanceId]); + expect(await t.read("agent.txt")).toBe("mid-turn\n"); + expect(await t.record()).toMatchObject({ kind: "live", mac: { cache: "ready" } }); + }); }); /** The cache tag the runtime derives for a repository. */ diff --git a/apps/server/src/environmentControl/NamespaceMacRuntime.ts b/apps/server/src/environmentControl/NamespaceMacRuntime.ts index a294ebbff2501..cc91692b63ba9 100644 --- a/apps/server/src/environmentControl/NamespaceMacRuntime.ts +++ b/apps/server/src/environmentControl/NamespaceMacRuntime.ts @@ -700,27 +700,37 @@ export function makeNamespaceMacRuntime(config: { }, /** * One upkeep pass for an awake chat: release a Mac nearing its deadline, - * idle ones first, otherwise save what changed since the last pass. + * idle ones first, otherwise save what changed since the last pass. Only a + * chat confirmed idle is released to sleep; any other awake chat off its Mac, + * or on one it was never restored onto, is `reopen`, owed a ready Mac, so a + * host restart at any point of a move still finishes it. */ upkeep: async ( operation: ProvisionOperation, manifest: ProvisionPreparationManifest, - busy: () => Promise, - ): Promise<"kept" | ChatOutcome> => { + idle: () => Promise, + ): Promise<"kept" | "reopen" | ChatOutcome> => { const chatId = operation.request.requestId; + const reopen = (outcome: ChatOutcome) => (outcome === "released" ? "reopen" : outcome); const record = await store.read(chatId); - if (record?.kind !== "live") return outcome(record); + if (record?.kind !== "live") return reopen(outcome(record)); const current = chat(operation, manifest); const facts = await current.ports.facts(); if (!facts.instances.includes(record.mac.incarnation.instanceId)) { const gone = await settleGone(chatId, record.mac.incarnation.instanceId); - return gone === "running" ? "kept" : gone; + return gone === "running" ? "kept" : reopen(gone); } + // A host that died while restoring the chat left this Mac unready; reopening restores onto it. + if (record.mac.cache === "unknown") return "reopen"; const instanceId = record.mac.incarnation.instanceId; const left = record.mac.incarnation.deadline - facts.now; - if (left < ROTATE_FORCE_MS || (left < ROTATE_IDLE_MS && !(await busy()))) { - log("namespace mac released before its deadline", { chatId, leftMs: left }); - return release(operation, manifest); + if (left < ROTATE_IDLE_MS) { + const asleep = await idle(); + if (asleep || left < ROTATE_FORCE_MS) { + log("namespace mac released before its deadline", { chatId, leftMs: left, asleep }); + const released = await release(operation, manifest); + return asleep ? released : reopen(released); + } } const last = lastSave.get(instanceId); if (last !== undefined && facts.now - last < SAVE_INTERVAL_MS) return "kept"; diff --git a/apps/server/src/environmentControl/ProvisionedLeaseRegistry.test.ts b/apps/server/src/environmentControl/ProvisionedLeaseRegistry.test.ts index 51439876aba3a..d6376425a2b60 100644 --- a/apps/server/src/environmentControl/ProvisionedLeaseRegistry.test.ts +++ b/apps/server/src/environmentControl/ProvisionedLeaseRegistry.test.ts @@ -95,6 +95,28 @@ it.effect("persists proxy identity, renews a claimed lease, and gives one releas }), ); +it.effect("counts the host's moves in a row until a client heartbeats or resumes the chat", () => + withRegistry(async (registry) => { + await registry.register({ + leaseId: "lease", + sandboxId: "sandbox", + providerInstanceId: "codex", + }); + await registry.claim({ leaseId: "lease", owner: { environmentId: "remote", threadId: "t" } }); + await registry.markActive({ leaseId: "lease", hostMove: true }); + expect(await registry.markActive({ leaseId: "lease", hostMove: true })).toMatchObject({ + unwatchedMoves: 2, + }); + expect( + await registry.touch("lease", undefined, "host"), + "the host keeping a busy box awake is not a client", + ).toMatchObject({ unwatchedMoves: 2 }); + expect((await registry.touch("lease"))?.unwatchedMoves).toBeUndefined(); + await registry.markActive({ leaseId: "lease", hostMove: true }); + expect((await registry.markActive({ leaseId: "lease" }))?.unwatchedMoves).toBeUndefined(); + }), +); + it.effect("records the proxy an attach opened after registration and never lets it change", () => withRegistry(async (first, second) => { const registration = { leaseId: "lease", sandboxId: "sandbox", providerInstanceId: "codex" }; diff --git a/apps/server/src/environmentControl/ProvisionedLeaseRegistry.ts b/apps/server/src/environmentControl/ProvisionedLeaseRegistry.ts index 25554ec8c009e..c840a1028c17c 100644 --- a/apps/server/src/environmentControl/ProvisionedLeaseRegistry.ts +++ b/apps/server/src/environmentControl/ProvisionedLeaseRegistry.ts @@ -72,6 +72,11 @@ export const StoredProvisionedLease = Schema.Struct({ */ firstTurn: Schema.optional(FirstTurnState), keep: Schema.optional(LeaseKeep), + /** + * Moves upkeep made in a row to keep a working chat on a new Mac, with no client heartbeat or + * resume since the first of them. Absent means none. + */ + unwatchedMoves: Schema.optional(Schema.Int), createdAt: Schema.String, updatedAt: Schema.String, expiresAt: Schema.String, @@ -109,7 +114,12 @@ export interface ProvisionedLeaseRegistry { readonly owner: ProvisionedLeaseOwner; readonly now?: Date; }) => Promise; - readonly touch: (leaseId: string, now?: Date) => Promise; + /** A client's heartbeat ends a run of unwatched moves; the host keeping a busy box awake does not. */ + readonly touch: ( + leaseId: string, + now?: Date, + by?: "client" | "host", + ) => Promise; /** * Records how a pending first turn ended. A failed one also drops the owner: that chat may * never exist, and the page that sends the message itself claims the box again. @@ -134,6 +144,8 @@ export interface ProvisionedLeaseRegistry { readonly namespaceResource?: NamespaceResource; readonly namespaceProxy?: { readonly proxyId: string; readonly proxyOrigin: string }; readonly remoteAccess?: RemoteAccess; + /** Upkeep moved the chat to a new Mac with no client asking; any other wake is a client's. */ + readonly hostMove?: boolean; readonly now?: Date; }) => Promise; readonly expired: (now?: Date) => Promise>; @@ -284,7 +296,7 @@ export function createProvisionedLeaseRegistry( next[index] = updated; return { leases: next, value: updated }; }), - touch: (leaseId, now) => + touch: (leaseId, now, by = "client") => mutate((leases) => { const index = leases.findIndex((lease) => lease.leaseId === leaseId); const current = index < 0 ? undefined : leases[index]; @@ -297,8 +309,9 @@ export function createProvisionedLeaseRegistry( const timestamp = now ?? new Date(); if (retentionExpired(current.retentionDeadline, timestamp.getTime())) return { leases, value: null }; + const { unwatchedMoves: _moves, ...rest } = current; const updated: ProvisionedLease = { - ...current, + ...(by === "host" ? current : rest), updatedAt: timestamp.toISOString(), expiresAt: new Date( Math.min( @@ -393,10 +406,11 @@ export function createProvisionedLeaseRegistry( ) throw new Error("Provisioned lease identity conflict"); const now = input.now ?? new Date(); - const { keep, ...rest } = current; + const { keep, unwatchedMoves, ...rest } = current; const updated: ProvisionedLease = { ...rest, ...(keep === "user" ? { keep } : {}), + ...(input.hostMove ? { unwatchedMoves: (unwatchedMoves ?? 0) + 1 } : {}), ...(input.namespaceResource ? { namespaceResource: input.namespaceResource } : {}), ...(input.namespaceProxy ? { namespaceProxy: input.namespaceProxy } : {}), ...(input.remoteAccess ? { remoteAccess: input.remoteAccess } : {}), diff --git a/docs/operations/cloud-provisioning.md b/docs/operations/cloud-provisioning.md index df0e1d7bf266f..2218bb8982d0e 100644 --- a/docs/operations/cloud-provisioning.md +++ b/docs/operations/cloud-provisioning.md @@ -87,7 +87,7 @@ node scripts/cloud/smoke-cloud-chat.ts --origin http://127.0.0.1:$(cat .t3/manag ## Run Mac chats on compute instances -A repository whose `provisioning.repositories[].namespace.engine` is `"instance"` runs new Mac chats on per-chat Namespace compute instances instead of Devboxes; the default is `"devbox"`, and a chat keeps the engine it was frozen with. The instance engine mounts a per-repository cache volume at `/Volumes/t3`, prepares every chat at `/Volumes/t3/root`, and keeps a released chat as a snapshot in Namespace artifact storage, so a pause costs nothing on Namespace and a resume can land on any Mac. A chat's Mac only reads the cache and is always destroyed without committing it. When a chat finds no current template (none, or one older than 12 hours or from different prepare commands), the manager starts one builder Mac per repository, labelled `t3.builder=`, that prepares the same checkout with no chat on it, seals it as the template and commits the volume. Only a chat frozen under the current prepare commands, artifacts and pinned runtime asks for one, so older chats never replace a newer template. A repository gets at most 3 builds an hour, a failed build backs off from 5 minutes doubling to 2 hours, and the manager abandons builders it left running before a restart. Namespace picks every Mac's site and each site keeps its own volume, so a builder fills only the site it lands in. The manager's chat records live in `/namespace-chats`, and Macs and snapshots carry the label `t3.chat=`. A prepare command written as `{ "command": "...", "background": true }` starts a service for the chat rather than preparing the checkout; chats run it as usual and builders skip it. A snapshot leaves out what preparation rebuilds. When a repository's prepare commands install a toolchain into the home, list it in `namespace.derivedHomePaths` (for megpt-mono, `.local/share/megpt-mind-python`, `.local/share/modal-cli` and `.bun/bin`) so its chats' snapshots carry only their own state. +A repository whose `provisioning.repositories[].namespace.engine` is `"instance"` runs new Mac chats on per-chat Namespace compute instances instead of Devboxes; the default is `"devbox"`, and a chat keeps the engine it was frozen with. The instance engine mounts a per-repository cache volume at `/Volumes/t3`, prepares every chat at `/Volumes/t3/root`, and keeps a released chat as a snapshot in Namespace artifact storage, so a pause costs nothing on Namespace and a resume can land on any Mac. Namespace ends every Mac five hours after it starts, so the manager saves the chat and lets the Mac go first: a chat idle in the Mac's last 30 minutes sleeps until a client opens it, and one still working 8 minutes before the end moves to a new Mac without waiting for a client, where its interrupted turn continues. After 3 such moves in a row with no client heartbeat or resume, the next deadline puts the chat to sleep instead, and opening it continues the turn. A chat's Mac only reads the cache and is always destroyed without committing it. When a chat finds no current template (none, or one older than 12 hours or from different prepare commands), the manager starts one builder Mac per repository, labelled `t3.builder=`, that prepares the same checkout with no chat on it, seals it as the template and commits the volume. Only a chat frozen under the current prepare commands, artifacts and pinned runtime asks for one, so older chats never replace a newer template. A repository gets at most 3 builds an hour, a failed build backs off from 5 minutes doubling to 2 hours, and the manager abandons builders it left running before a restart. Namespace picks every Mac's site and each site keeps its own volume, so a builder fills only the site it lands in. The manager's chat records live in `/namespace-chats`, and Macs and snapshots carry the label `t3.chat=`. A prepare command written as `{ "command": "...", "background": true }` starts a service for the chat rather than preparing the checkout; chats run it as usual and builders skip it. A snapshot leaves out what preparation rebuilds. When a repository's prepare commands install a toolchain into the home, list it in `namespace.derivedHomePaths` (for megpt-mono, `.local/share/megpt-mind-python`, `.local/share/modal-cli` and `.bun/bin`) so its chats' snapshots carry only their own state. Prove a change to it end to end against a local manager with the engine set in `.t3/manager/environment-control.json`: