Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 89 additions & 0 deletions apps/server/src/environmentControl/EnvironmentControl.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Error | "moved"> = [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<Error | "moved"> = [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<string | undefined> = [];
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.
Expand Down
65 changes: 48 additions & 17 deletions apps/server/src/environmentControl/EnvironmentControl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<boolean>;
}) => Promise<"kept" | "released" | "missing" | null>;
readonly idle: () => Promise<boolean>;
}) => Promise<"kept" | "released" | "reopen" | "missing" | null>;

export function createEnvironmentControl(
targets: ReadonlyArray<ManagedTarget>,
Expand Down Expand Up @@ -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<ManagedEnvironment> => {
let state: ComputeState;
try {
Expand Down Expand Up @@ -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 =
Expand Down Expand Up @@ -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<EnvironmentProvisionResumeResult> => {
Expand Down Expand Up @@ -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 });
Expand Down Expand Up @@ -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
Expand Down
67 changes: 65 additions & 2 deletions apps/server/src/environmentControl/NamespaceMacRuntime.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down
26 changes: 18 additions & 8 deletions apps/server/src/environmentControl/NamespaceMacRuntime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<boolean>,
): Promise<"kept" | ChatOutcome> => {
idle: () => Promise<boolean>,
): 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";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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" };
Expand Down
Loading
Loading