Skip to content
Draft
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
6 changes: 6 additions & 0 deletions .changeset/session-idle-reclaim.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@pstdio/pocketcoder-cli": minor
"@pstdio/pocketcoder-sdk": minor
---

Release a managed session's compute after a profile's `idleSeconds` warm period; the next message resumes the chat on new compute.
3 changes: 2 additions & 1 deletion docs/managed-consumers.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ Mount this file only into the controller and set `POCKETCODER_PRINCIPALS_FILE`:
"issuer": "chat",
"placement": "shared",
"limits": { "workspacesPerOwner": 1, "sessionsPerWorkspace": 5 },
"dispatchDeadlineSeconds": 600
"dispatchDeadlineSeconds": 600,
"idleSeconds": 900
}
}
}]
Expand Down
7 changes: 7 additions & 0 deletions docs/managed-runtime.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,13 @@ cleanup evidence for that workspace generation. Its sessions become suspended
and place again when they have work. A new message also moves an older live
binding to the profile's current template release once its work has finished.

A profile's optional `idleSeconds` sets a warm period. When a workspace has had
no queued or unfinished request for that long, PocketCoder drains it the same
way, and its sessions become `suspended` with reason `workspace_idle`. The next
message places new compute and starts the session from its last saved turn (see
[session files](#session-files)), so the chat keeps its ID, history and files.
Without `idleSeconds`, idle compute stays until its deadline or a drain for room.

The controller-wide and per-principal admission limits still apply. Managed
placements wait when the principal limit is full; they do not bypass admission.

Expand Down
149 changes: 149 additions & 0 deletions examples/e2e/e2b-idle-reclaim.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
// Live check: a profile's warm period (idleSeconds) releases an idle chat's E2B VM. Another
// owner then uses the freed capacity, and the first chat continues on new compute with its
// history, files and attachment. It samples guest CPU and memory with one and five warm chats
// and prints a timestamped mark at each step, so host samples taken on the workers can be
// matched to it. See e2b-live-fixture.ts for the host it needs.
import assert from "node:assert/strict";
import { randomUUID } from "node:crypto";
import { Sandbox } from "e2b";
import { e2bLiveFixture } from "./e2b-live-fixture";
import { waitFor } from "./local-process";

const IDLE_SECONDS = 60;
const QUIET_MS = 30_000;
const live = await e2bLiveFixture();
const evidence: Record<string, unknown> = {};
const lines = (text: string) => text.trim().split("\n");
const mark = (step: string) => console.log(JSON.stringify({ mark: step, at: new Date().toISOString() }));

async function timed<T>(call: () => Promise<T>) {
const started = Date.now();
const result = await call();
return { result, ms: Date.now() - started };
}

// Whole-VM CPU use over five seconds and memory in use, as the guest kernel sees them.
async function guestSample(sandboxId: string) {
const vm = await Sandbox.connect(sandboxId, live.connection);
const script = "head -1 /proc/stat; sleep 5; head -1 /proc/stat; grep -E '^Mem(Total|Available):' /proc/meminfo";
const [before, after, total, available] = lines((await vm.commands.run(script, { user: "root" })).stdout);
const ticks = (line = "") => line.split(/\s+/).slice(1).map(Number);
const sum = (values: number[]) => values.reduce((a, b) => a + b, 0);
const [a, b] = [ticks(before), ticks(after)];
const busy = sum(b) - sum(a) - ((b[3] ?? 0) + (b[4] ?? 0) - (a[3] ?? 0) - (a[4] ?? 0));
const kib = (line = "") => Number(line.split(/\s+/)[1]);
return {
cpuPercent: Math.round((1000 * busy) / (sum(b) - sum(a))) / 10,
memUsedMiB: Math.round((kib(total) - kib(available)) / 1024),
};
}

try {
const template = await live.rivetTemplate();
const { keyFile, principalsFile } = await live.consumerPrincipals(template.name, ["consumer"], false, {
idleSeconds: IDLE_SECONDS,
limits: { workspacesPerOwner: 1, sessionsPerWorkspace: 5 },
});
const controller = await live.startController(template.directory, { POCKETCODER_PRINCIPALS_FILE: principalsFile });
const { api, consumer, completed, settled } = await live.managedClient(controller.baseUrl, keyFile);
const vmIds = async () => (await live.vms()).map((vm) => vm.sandboxId);
mark("no chats");
await Bun.sleep(QUIET_MS);

// The first chat remembers a token, edits a file and reads an attachment.
const first = await consumer.startSession("chat", "alice", randomUUID(), "team-1");
const id = first.sessionId;
const token = `pocketcoder-doctor-${randomUUID()}`;
await completed(id, `Reply with exactly this diagnostic token: ${token}`, "token turn");
const saved = `line-${randomUUID()}`;
const code = `brief-${randomUUID()}`;
const brief = await consumer.attach("user", id, {
inputId: randomUUID(),
name: "brief.txt",
mediaType: "text/plain",
bytes: new TextEncoder().encode(code),
});
const withFile = await consumer.ask("user", id, `Append ${saved} to ledger.txt after 1 seconds`, {
attachments: [brief.inputId],
});
assert.equal((await settled(id, withFile.requestId, "file turn")).outcome, "completed");
const [vm] = await vmIds();
const ledger = `/workspace/${id}/ledger.txt`;
assert.deepEqual(lines(await live.readFile(vm as string, ledger)), [saved]);
// The turn's inputs leave the VM when it ends, so check that the agent was given the file.
const mentions = () => live.modelRequests.filter((body) => JSON.stringify(body).includes("brief.txt")).length;
const seen = mentions();
assert.ok(
seen > 0,
`the agent got the attachment: ${JSON.stringify(live.modelRequests.at(-1)?.messages?.at(-1)).slice(0, 600)}`,
);

// A gap shorter than the warm period keeps the VM. A warm turn sets the latency baseline.
mark("one chat");
await Bun.sleep(QUIET_MS);
const oneChat = await guestSample(vm as string);
const warm = await timed(() => completed(id, "Repeat the earlier diagnostic token.", "warm turn"));
assert.equal(warm.result.finalResponse, token);
assert.deepEqual(await vmIds(), [vm], "a short gap keeps the VM");

// Four more chats share the VM.
const others = [];
for (let i = 0; i < 4; i++) {
const other = await consumer.startSession("chat", "alice", randomUUID(), "team-1");
await completed(
other.sessionId,
`Reply with exactly this diagnostic token: pocketcoder-doctor-${randomUUID()}`,
"chat",
);
others.push(other.sessionId);
}
assert.deepEqual(await vmIds(), [vm], "five chats share one VM");
const lastActivity = Date.now();
mark("five chats");
await Bun.sleep(QUIET_MS);
const fiveChats = await guestSample(vm as string);
evidence.guest = { oneChat, fiveChats };

// Past the warm period the VM is released and every chat on it waits for new work.
await waitFor(() => live.gone(vm as string), (IDLE_SECONDS + 120) * 1000, "idle release");
const releasedAfterMs = Date.now() - lastActivity;
mark("released");
for (const sessionId of [id, ...others]) {
const session = await api.sessions.get(sessionId);
assert.deepEqual([session.state, session.reasonCode], ["suspended", "workspace_idle"], sessionId);
}
assert.deepEqual(await vmIds(), [], "no VM runs after the release");
evidence.release = { vm, idleSeconds: IDLE_SECONDS, releasedAfterMs };
await Bun.sleep(QUIET_MS);

// Another owner takes the freed capacity.
const bob = await consumer.startSession("chat", "bob", randomUUID(), "team-1");
await completed(bob.sessionId, `Reply with exactly this diagnostic token: pocketcoder-doctor-${randomUUID()}`, "bob");
const [bobVm] = await vmIds();
assert.ok(bobVm && bobVm !== vm, "bob runs on new compute");
await consumer.close("user", bob.sessionId);
await waitFor(async () => (await vmIds()).length === 0, 180_000, "bob's VM cleanup");
evidence.otherOwner = { vm: bobVm };
mark("other owner done");

// The first chat continues on new compute with the same ID, history, file and attachment.
const resumed = await timed(() => completed(id, "Repeat the earlier diagnostic token.", "resumed turn"));
assert.equal(resumed.result.finalResponse, token, "the resumed chat has its history");
const [next] = await vmIds();
assert.ok(next && next !== vm && next !== bobVm, "the resumed chat runs on new compute");
assert.deepEqual(lines(await live.readFile(next, ledger)), [saved], "the resumed chat has its file");
assert.equal((await api.files.get(id, brief.inputId)).state, "ready", "the attachment is kept");
const again = await consumer.ask("user", id, `Append ${saved}-2 to ledger.txt after 1 seconds`, {
attachments: [brief.inputId],
});
assert.equal((await settled(id, again.requestId, "attachment after resume")).outcome, "completed");
assert.ok(mentions() > seen, "the resumed chat can use its attachment");
evidence.resume = { vm: next, warmTurnMs: warm.ms, resumedTurnMs: resumed.ms };
mark("resumed");

for (const sessionId of [id, ...others]) await consumer.close("user", sessionId);
await waitFor(async () => (await vmIds()).length === 0, 180_000, "VM cleanup");
console.log(JSON.stringify({ revision: await live.revision(), template: template.alias, ...evidence }, null, 2));
} finally {
await live.close();
}
19 changes: 15 additions & 4 deletions examples/e2e/e2b-live-fixture.ts
Original file line number Diff line number Diff line change
Expand Up @@ -172,8 +172,12 @@ export async function e2bLiveFixture() {
tempDir,
lease,
modelRequests,
consumerPrincipals: (templateName: string, names = ["consumer"], revoke = false) =>
writePrincipals(tempDir, lease, templateName, names, revoke),
consumerPrincipals: (
templateName: string,
names = ["consumer"],
revoke = false,
profile: Partial<managed.ProfileConfig> = {},
) => writePrincipals(tempDir, lease, templateName, { names, revoke, profile }),
rivetTemplate,
startController,
managedClient,
Expand Down Expand Up @@ -253,8 +257,14 @@ async function gatewayAccepts(gateway: string, credential: string) {
type Lease = Awaited<ReturnType<typeof startLeaseGateway>>;

// One consumer principal per name, each with its own key file. "chat" shares one VM per owner
// between two sessions. With revoke, the issuer revokes a lost generation's model leases.
async function writePrincipals(tempDir: string, lease: Lease, templateName: string, names: string[], revoke: boolean) {
// between two sessions unless profile overrides it. With revoke, the issuer revokes a lost
// generation's model leases.
async function writePrincipals(
tempDir: string,
lease: Lease,
templateName: string,
{ names, revoke, profile }: { names: string[]; revoke: boolean; profile: Partial<managed.ProfileConfig> },
) {
const tokenFile = resolve(tempDir, "issuer.token");
const principalsFile = resolve(tempDir, "principals.json");
await writeFile(tokenFile, lease.config.authorization.replace(/^Bearer /, ""));
Expand All @@ -273,6 +283,7 @@ async function writePrincipals(tempDir: string, lease: Lease, templateName: stri
issuer: GATEWAY_POLICY,
placement: "shared",
limits: { workspacesPerOwner: 1, sessionsPerWorkspace: 2 },
...profile,
},
},
}));
Expand Down
1 change: 1 addition & 0 deletions examples/e2e/tsconfig.sessions.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"e2b-live-fixture.ts",
"e2b-managed-sessions.ts",
"e2b-controller-restart.ts",
"e2b-idle-reclaim.ts",
"e2b-recovery-points.ts",
"e2b-tenants.ts",
"local-echo.ts",
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@
"example:e2e:e2b-rivet": "bun --no-env-file examples/e2e/e2b-rivet.ts",
"example:e2e:e2b-managed-sessions": "bun --no-env-file examples/e2e/e2b-managed-sessions.ts",
"example:e2e:e2b-controller-restart": "bun --no-env-file examples/e2e/e2b-controller-restart.ts",
"example:e2e:e2b-idle-reclaim": "bun --no-env-file examples/e2e/e2b-idle-reclaim.ts",
"example:e2e:e2b-recovery-points": "bun --no-env-file examples/e2e/e2b-recovery-points.ts",
"example:e2e:e2b-tenants": "bun --no-env-file examples/e2e/e2b-tenants.ts"
},
Expand Down
3 changes: 3 additions & 0 deletions packages/contracts/src/sessions/profile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ export const ProfileConfigSchema = z.strictObject({
})
.default({ workspacesPerOwner: 1, sessionsPerWorkspace: 1 }),
dispatchDeadlineSeconds: z.number().int().positive().default(600),
// Compute with no queued or unfinished request for this long is released; the next message
// places new compute and restores the session from its last recovery point.
idleSeconds: z.number().int().positive().optional(),
});
export type ProfileConfig = z.infer<typeof ProfileConfigSchema>;
export const SessionProfileSchema = ProfileConfigSchema.extend({
Expand Down
8 changes: 6 additions & 2 deletions packages/db/assets/core-seed.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
"app": "pocketcoder",
"pgliteVersion": "0.5.8",
"postgresVersion": "18.3",
"checksum": "32a53837d64c80bce4d14ee1a3cf3fd39edc4b3f7e22ec858fe867446dc2ab7a",
"sourceChecksum": "b795bdccb7f219f6f6048c8262da7bea0c42a8d163014858664f91f2ffb5ebaa",
"checksum": "72e5b0c9d9742b1418439828ff782095d2f74aed383638640a9c837121350d09",
"sourceChecksum": "135fc541158a14329ca9e15d17c9377b41c5475bd281a532c35f77ac1ff29d60",
"engine": {
"wasm": {
"checksum": "ce6af6ff027cbf1f22da3f5bbc8b0b30082123e2826f38a27fb91847cd16046f",
Expand Down Expand Up @@ -122,6 +122,10 @@
{
"name": "20261203131024_pretty_tomas",
"hash": "7d05caf4aa8a44fc769e2b45378513ad861ce7fd192d5405e747c928443fc5a3"
},
{
"name": "20261203233219_mighty_triton",
"hash": "14a6189a6dd7560ef83bc0a7917d5d41c96ea10c0ca3cbd834ee8a639978ae8b"
}
]
}
Binary file modified packages/db/assets/core-seed.tar.zst
Binary file not shown.
7 changes: 7 additions & 0 deletions packages/db/assets/migrations.json
Original file line number Diff line number Diff line change
Expand Up @@ -457,5 +457,12 @@
"folderMillis": 1796303424000,
"hash": "7d05caf4aa8a44fc769e2b45378513ad861ce7fd192d5405e747c928443fc5a3",
"name": "20261203131024_pretty_tomas"
},
{
"sql": ["ALTER TABLE \"managed_profiles\" ADD COLUMN \"idle_seconds\" integer;"],
"bps": true,
"folderMillis": 1796340739000,
"hash": "14a6189a6dd7560ef83bc0a7917d5d41c96ea10c0ca3cbd834ee8a639978ae8b",
"name": "20261203233219_mighty_triton"
}
]
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
ALTER TABLE "managed_profiles" ADD COLUMN "idle_seconds" integer;
Loading
Loading