An open-source, faster Devin alternative
TypeScript
merge main
Brian Reardon36ce1c983a79
diff --git a/.agents/design/cohort-usage-analysis.md b/.agents/design/cohort-usage-analysis.mdnew file mode 100644index 00000000..b484bddf--- /dev/null+++ b/.agents/design/cohort-usage-analysis.md@@ -0,0 +1,342 @@+# Cohort usage analysis++How to reconstruct *who* drove a usage figure on a given day, what+they did, and where they dropped off — using only the production+databases. Pattern arose from investigating a 10K GB-hour spike that+turned out to be ~30 users abandoning the agent product after hitting+provisioning errors. Same recipe applies to any "who's burning the+compute" or "where's the funnel breaking" question.++## When to use this++The question pattern: a metric (usage, signups, errors) jumped on a+given day, and you need to know which users contributed, what they+were doing, and what stopped them. Output is a per-user timeline+spreadsheet that a non-engineer can read.++Not for: aggregate billing reconciliation (use `sandbox_scale_events`+joined to Stripe meter events), real-time alerting, or anything+requiring sub-minute resolution. Sample resolution is 60s; agent+events are sparse and append-only.++## Two databases, joined on user ID++Two separate Postgres instances hold complementary state:++- **OpenComputer DB** (Azure-hosted, behind SSH bastion): orgs,+ users, sandboxes, scale events, usage samples, preview URLs,+ secret stores, hibernations. Connection details and tunnel+ pattern: see `~/.claude` memory `reference_prod_debugging.md`,+ or the `OPENSANDBOX_DB_*` block in `~/Digger/gstack/opencomputer/.env`.+- **sessions-api DB** (Xata-hosted, public reach with credentials):+ agents, instances, sessions, agent_events, agent_operations.+ Connection string: `DATABASE_URL` in+ `~/Digger/gstack/sessions-api/.env`. No bastion needed.++The join key is **OC `users.id`** (UUID). In sessions-api,+`agents.owner_id` carries that same UUID. Three things this is *not*:++- not `orgs.id` — agents are owned per-user, not per-org+- not `workos_user_id` — that lives on `users.workos_user_id`,+ unrelated+- not `app_users.id` in sessions-api — that table is mostly empty+ test data, ignore it for cohort joins++`sessions-api.app_users` looks tempting because of the `email` column,+but it has on the order of ten rows total, all of which are+smoke-test or pivot accounts. Don't join via email.++## Identify the cohort++Step one is "who's in the relevant set." For a usage spike, the+canonical filter is "every org that emitted at least one+`sandbox_usage_samples` row in the window." This is the closed+universe — `usage_collector` writes one sample per running sandbox+per 60s, and every billable second flows through this table, so+nothing else can contribute.++```sql+SELECT DISTINCT us.org_id+FROM sandbox_usage_samples us+WHERE us.sampled_at >= '<window_start>'+ AND us.sampled_at < '<window_end>';+```++Resolve to users and emails via `users JOIN orgs`. Decide whether+you want internal accounts in or out — internal here means+`orgs.name IN ('opencomputer', 'diggerhq')` plus any user whose+email ends in `@digger.dev`. Amplitude dashboards filter internal+out, so for parity with what stakeholders see, exclude them.++## Reconciliation: prove the cohort accounts for the metric++The first thing to do after defining the cohort is verify it sums+to the metric you're investigating. Without this step the analysis+is suggestive, not conclusive — there could be hidden contributors+or double-counting.++The key property of `sandbox_usage_samples` is that the universe of+contributors is *enumerable*: a closed `SELECT DISTINCT org_id`.+Per-org GB-hour sums therefore reconcile to the total exactly:++```sql+SELECT+ bucket,+ count(DISTINCT org_id) AS orgs,+ ROUND(SUM(memory_mb / 1024.0 * 60.0) / 3600.0, 1) AS gb_hours+FROM (+ SELECT+ us.org_id,+ us.memory_mb,+ CASE+ WHEN o.name IN ('opencomputer', 'diggerhq') THEN 'internal'+ WHEN EXISTS (SELECT 1 FROM users u+ WHERE u.org_id = o.id AND u.email LIKE '%@digger.dev')+ THEN 'internal'+ ELSE 'external'+ END AS bucket+ FROM sandbox_usage_samples us+ JOIN orgs o ON o.id = us.org_id+ WHERE us.sampled_at >= '<window_start>' AND us.sampled_at < '<window_end>'+) x+GROUP BY bucket;+```++Sanity checks:++1. `count(DISTINCT org_id)` from the unfiltered samples query+ equals the sum of bucket org counts (no orgs leak through).+2. Sum of bucket GB-hours equals the total from the unfiltered query.+3. No orphaned org_ids:+ ```sql+ SELECT count(*) FROM (+ SELECT DISTINCT org_id FROM sandbox_usage_samples+ WHERE sampled_at >= '<window_start>' AND sampled_at < '<window_end>'+ ) a WHERE NOT EXISTS (SELECT 1 FROM orgs o WHERE o.id = a.org_id);+ ```+ Should be `0`.++Once these three hold, the cohort *is* the metric, by construction.+Don't move on until they do.++## Per-user event collection++For each user in the cohort, pull every high-signal event that maps+to either intentional usage or a discrete failure. Skip everything+that's noise (heartbeats, periodic samples themselves, keepalives).+The list below is what worked for the agent-product cohort and+generalises to most spike investigations.++From the OpenComputer DB:++| Source | Event | Signal type |+|---|---|---|+| `orgs.created_at` | signup | start anchor |+| `sandbox_sessions.started_at` / `.stopped_at` | sandbox lifecycle | usage |+| `sandbox_hibernations.hibernated_at` / `.restored_at` | reaper / wake | system action |+| `api_keys.created_at` / `.last_used` | API engagement | usage |+| `sandbox_checkpoints.created_at` | user saved state | strong intent |+| `sandbox_preview_urls.created_at` | user exposed a service | strong intent |+| `secret_store_entries.created_at` | user configured credential | strong intent |++From the sessions-api DB:++| Source | Event | Signal type |+|---|---|---|+| `agents.created_at` | created an agent | intent |+| `instances.created_at` | spun up agent runtime | usage |+| `agent_operations` (`kind`, `status`, `phase`) | lifecycle ops | success/failure |+| `agent_events` (`type`, `phase`, `code`, `message`) | platform-recorded outcomes | failures, recoveries |+| `sessions.created_at` | actual agent invocation | usage (terminal funnel step) |++`agent_operations.kind` values worth tracking: `create_instance`,+`install_package`, `connect_channel`. Statuses: `succeeded`,+`failed`. Phase names line up with `agent_events.phase` so the two+streams cross-reference cleanly.++`agent_events.type` is one of `error`, `warning`, `info`. Errors+are the dropoff causes. `warning` is mostly retry chatter+(`webhook_delivery_retrying`). `info` includes+`webhook_delivery_recovered`, which is a positive signal worth+counting separately from `succeeded` ops.++What *not* to pull as activity proxy:++- `sandbox_usage_samples.cpu_usec` is hardcoded `0` —+ `internal/worker/usage_collector.go` has a `TODO: parse from+ cgroup cpu.stat`. Looks like activity data, isn't.+- `sandbox_usage_samples.memory_bytes` is real RSS but reports the+ guest-OS baseline (~1 GB) for almost any idle sandbox. Useful as+ "is anything happening" proxy, not as activity volume.+- `command_logs` and `pty_session_logs` are zero across all+ agent-product sandboxes. The agent runtime executes via internal+ paths that don't surface to the public Exec/PTY APIs that get+ logged. Don't conclude "user did nothing" from these alone — they+ only catch direct sandbox API usage.++## Pitfalls++These cost real time the first time around. Capturing here so the+next investigation starts ahead.++**`sandbox_sessions.status` is current state, not point-in-time.**+A sandbox shown as `hibernated` was running while it emitted samples.+Falsifiable test: `SELECT count(*) FROM sandbox_usage_samples WHERE+sandbox_id = X AND sampled_at > <hibernated_at>` — returns zero.+Don't filter samples by session status — filter by `sampled_at`.++**`sandbox_scale_events` is undercount-prone.** It's append-only on+explicit scale operations, but several lifecycle paths (notably+restore-from-hibernation cycles, possibly others) skip the write.+On any given day a meaningful fraction of running sandboxes lack+covering scale_event rows. Use `sandbox_usage_samples` as the+source of truth for "what was running when"; use scale_events only+for what billing actually saw.++**Amplitude's number is the external bucket.** A "12K GB-hours"+metric in the DB and "10.8K" in Amplitude is the internal/external+split, not a discrepancy. Reconcile both.++**Sandboxes outlive their visible activity.** Agent product+sandboxes default to 16 GB / 4 CPU / 1 hour timeout, but with no+idle reaper they often persist for days after the user has+abandoned them. Their per-day GB-hour cost is real even when zero+real work is happening inside.++**The `agent:*` secret_store name is the agent product's+fingerprint.** `sandbox_sessions.config->>'secretStore' LIKE+'agent:%'` distinguishes agent-runtime sandboxes from direct+sandbox-API usage (`hyperaide-user-*`, `summun-browser-egress`,+custom names). When the question is product-specific, filter on+this.++**Internal orgs leak in via fresh employee accounts.** The+`opencomputer` and `diggerhq` orgs are obviously internal. New+internal users sometimes sign up with `<name>[email protected]` or+similar and end up under their own personal workspace. The robust+filter is `users.email NOT LIKE '%@digger.dev'`, not just an+org-name allowlist.++## Output formats++Three artefacts, each useful for a different consumer:++- **Long-format event log** (`events.csv`): one row per event,+ columns `email | uid | abs_ts | min_since_signup | source | kind+ | detail`. Pivots well in any spreadsheet. Source for the+ others.+- **Wide funnel** (`funnel.csv`): one row per user, columns are+ per-stage milestones (signup, first sandbox, first agent, first+ instance, first install op, first install ok, first channel ok,+ first session, last activity) plus counts and the user's+ terminal failure phase. Good for "where did each user drop off"+ questions.+- **Calendar timeline** (`cohort_calendar.xlsx`): rows =+ users (sorted by signup), columns = real calendar days, sub-columns+ = first 15m / 15-60m / 1-3h / 3h+ of each day's activity (anchored+ to user's first event of that day). Plus a single "before+ <start>" column. Cells are descriptive multi-line text with+ counts (e.g. "openclaw binary missing on PATH \n install failed+ ×2 \n agent created"); colored red/orange/green/grey by severity;+ thin grey horizontal rules between users; medium grey vertical+ rules between days; first two columns and header rows frozen.++The xlsx is what stakeholders look at. Per-day sub-buckets anchored+to the user's first daily event capture intensity-of-engagement+("they did everything in 15 minutes vs spread across hours") which+plain-time bins miss.++## Reproducing the analysis++Concrete recipe. Adjust the date window and the cohort filter.++### 1. Open the OC tunnel++```bash+ssh -i ~/.ssh/opensandbox-shared -o ExitOnForwardFailure=yes \+ -L 15432:$OPENSANDBOX_DB_HOST:5432 -N -f \+ azureuser@$OPENSANDBOX_DB_BASTION_HOST+```++`$OPENSANDBOX_DB_HOST` and `$OPENSANDBOX_DB_BASTION_HOST` from+`~/Digger/gstack/opencomputer/.env`. Tear down with+`pkill -f "ssh.*15432:.*:5432"`.++### 2. Define the cohort++Build a `uid|email` map of the cohort users to a flat file:++```sql+-- run via psql against OC; emit user_id|email pairs+SELECT u.id::text || '|' || u.email+FROM users u JOIN orgs o ON o.id = u.org_id+WHERE o.id IN (+ SELECT DISTINCT org_id FROM sandbox_usage_samples+ WHERE sampled_at >= '<start>' AND sampled_at < '<end>'+)+AND u.email NOT LIKE '%@digger.dev'+AND o.name NOT IN ('opencomputer', 'diggerhq')+ORDER BY u.email;+```++### 3. Reconcile (sanity-check first)++Run the bucket reconciliation query above. Sum to the headline+metric (Amplitude / dashboard / wherever it came from). Verify+zero orphans. Don't proceed otherwise — the cohort is wrong and+the rest of the analysis will be too.++### 4. Build `events.csv`++Single Python script, two psql connections, one row per event,+parse timestamps, sort by `(email, abs_ts)`, write CSV with columns+`email,uid,abs_ts,min_since_signup,source,kind,detail`.++The query set:++- OC: `users JOIN orgs` for signup; `sandbox_sessions` for+ start/stop; `sandbox_hibernations` for hibernate/restore;+ `api_keys` for created/last_used; `sandbox_checkpoints` for+ saved state; `sandbox_preview_urls` for exposed services;+ `secret_store_entries JOIN secret_stores` for stored credentials.+- sessions-api: `agents` for creation; `instances` for runtime+ starts; `agent_operations` (use `COALESCE(completed_at,+ started_at, created_at)` for the timestamp); `agent_events`+ for errors/warnings/info; `sessions` for actual invocations.++Tab-delimited psql output (`-tAF '\t'`) splits cleanly. NULLs at+the end of a row appear as missing trailing fields; pad to expected+column count.++### 5. Build `cohort_calendar.xlsx` from `events.csv`++Open the events log, group by user, then by calendar date. For+each (user, date), find first event of the day, bucket subsequent+events by relative offset (0-15m / 15-60m / 1-3h / 3h+).+Aggregate per cell as a `Counter` of (label, severity), render as+multi-line text with counts. Colour cells by worst severity in+the cell. Use `openpyxl`; freeze panes at C3; row height ~80pt;+column widths 22 for sub-buckets, 32 for email.++The describe() function — mapping (kind, detail) → (human label,+severity) — is the hand-tuned bit. The agent-product version+shipped with this analysis covers `error/warning/info` events+(with phase-specific labels), all the agent_operations+(succeeded/failed × create_instance/install_package/connect_channel),+and the OC lifecycle/intent events listed above. Extend+`describe()` for new failure modes as they appear; everything else+(severity ordering, cell formatting, layout) doesn't need changes.++Severity ordering for cell colour: `err > warn > ok > neutral >+info`. Cell text orders the same way (errors first, then warnings,+then successes, then lifecycle).++### 6. Verify the xlsx visually++A handful of users at the top by signup date should show signup+followed quickly by a cluster of activity. The right-hand columns+should thin out as users abandoned the product. If the right side+is unexpectedly busy, you have an unkilled-sandboxes long-tail+worth flagging separately. If a user's row is empty across all+columns, double-check the `users.id` → `agents.owner_id` join —+that's the most common mistake.diff --git a/.agents/design/openclaw-image-pull.md b/.agents/design/openclaw-image-pull.mdnew file mode 100644index 00000000..2574cb75--- /dev/null+++ b/.agents/design/openclaw-image-pull.md@@ -0,0 +1,255 @@+# OpenClaw managed-agent runtime: image-pull instead of checkpoint-fork++## TL;DR++Move OpenClaw managed agents from "fork from a baked OC checkpoint" to+"pull a Docker image into a fresh sandbox at agent-create time." The+checkpoint path is the leading source of paywall-flow incidents in+prod (silent fork failures, golden-version rebase races, snapshot drift+between OpenClaw releases). We trade ~1s warm forks for ~10s cold+pulls in exchange for two layers we can debug independently: a Docker+registry pull, and an in-sandbox boot of a known image. The OpenClaw+team's image becomes the source of truth for the runtime, and we stop+re-baking a snapshot every release.++The Stripe paywall, sandbox-billing exemption, agent metadata, and+sessions-api adapter shape are all unchanged — only the provisioning+path is.++## Problem++Today's flow:++```+sessions-api POST /v1/agents+ → OC POST /api/sandboxes/from-checkpoint/<OPENCLAW_CHECKPOINT_ID>+ → worker fork-from-checkpoint+ → restored sandbox has supervisord + openclaw running with build-time placeholder env+ → entrypoint writes ~/.openclaw/env, supervisorctl restart openclaw+ → adapter.waitReady polls /health+```++Recurring failure modes in prod, each of which has fired this week:++- **Fork race / orphan reaper.** worker's orphan-reaper kills the+ forked QEMU process before the VM registry sees it+ (commit `9fb6c9a` introduced this). User sees+ `instance_boot: rpc error ... QMP cont: connection reset by peer`+ and the agent stays in `error`. Repro is intermittent under load.+- **Golden-version rebase loops.** When we rebuild the rootfs, every+ in-flight checkpoint references the old golden. The worker+ downloads the prior rootfs to `bases/<ver>/default.ext4`; on slow+ blob storage this stalls the first fork of every new agent for 30++ seconds and occasionally times out.+- **Snapshot drift between OpenClaw releases.** OpenClaw 2026.4.16++ changed the channel-config schema; our adapter writes the old+ shape; OpenClaw silently rolls writes back. We pin to 2026.4.15 to+ avoid this and have to rebuild the snapshot for every bump.+- **Reboot recovery is supervisord-restart-dependent.** A guest reboot+ wipes everything; we need PID-1 (osb-agent) to start supervisord+ via the `f7f57a7` hook, then need ~18s of openclaw-gateway warm-up+ before chat works. Users hit "Agent ended the turn without sending+ any text" if they message during the warm-up window.+- **Cross-checkpoint org leakage.** Public-checkpoint forks via the+ `is_public` relaxation work, but checkpoint authorship is brittle —+ if we accidentally rebuild a checkpoint as private the entire user+ base hits 403.++The common thread: we treat the OpenClaw runtime as part of our+infra, but we ship it from a different repo on a different release+cadence. Every interaction between them (config schema, supervisord+program shape, checkpoint format) is a place state can diverge.++## Proposed flow++```+sessions-api POST /v1/agents (core=openclaw)+ → OC POST /api/sandboxes (fresh sandbox from default rootfs, secretStore=agent:<id>)+ → exec.run "docker pull diggerhq/openclaw-managed:<version>"+ → exec.run "docker run -d --name openclaw \+ -p 18789:18789 -p 8787:8787 \+ -v /home/sandbox/.openclaw:/data \+ --env-file /home/sandbox/.openclaw/env \+ --restart unless-stopped \+ diggerhq/openclaw-managed:<version>"+ → adapter.waitReady polls http://localhost:18789/health+```++Two new pieces of plumbing:++### 1. `digger/openclaw-managed:<version>` image++Built nightly via a workflow that pulls the official upstream+OpenClaw image, layers our supervisord + reload hooks + agent+metadata on top, and pushes to a registry. Layout sketch:++```dockerfile+ARG OPENCLAW_VERSION=2026.5.1+FROM openclaw/runtime:${OPENCLAW_VERSION}++# Base config — no per-agent secrets; those come from /data/env at runtime.+COPY openclaw.json /etc/openclaw/openclaw.json++# Launcher script that sources /data/env and execs the gateway in foreground.+COPY launcher.sh /usr/local/bin/openclaw-launcher+RUN chmod +x /usr/local/bin/openclaw-launcher++# Healthcheck baked in so docker can mark the container unhealthy without+# us shipping an external probe.+HEALTHCHECK --interval=10s --timeout=3s --start-period=30s --retries=3 \+ CMD curl -sf http://localhost:18789/health || exit 1++EXPOSE 18789 8787+ENTRYPOINT ["/usr/local/bin/openclaw-launcher"]+```++The image is the only place the OpenClaw runtime version lives.+Bumping OpenClaw is a tag bump, not a checkpoint rebuild. Rollback+is `docker run` with a previous tag — no rootfs surgery. CI tests+can `docker pull` and curl `/health` before promoting a tag.++### 2. Sessions-api adapter rewrite++`src/lib/cores.ts:openclaw` changes from "fork checkpoint, run+entrypoint" to "create sandbox, install image, start container."+The "core ready" gate becomes:++```ts+async function bootOpenclaw(sandbox, agentId, env) {+ await sandbox.files.makeDir("/home/sandbox/.openclaw");+ await sandbox.files.write(+ "/home/sandbox/.openclaw/env",+ Object.entries(env).map(([k, v]) => `${k}=${v}`).join("\n"),+ );+ await sandbox.exec.run(+ "docker pull diggerhq/openclaw-managed:" + OPENCLAW_VERSION,+ { timeout: 120 },+ );+ await sandbox.exec.run(+ `docker run -d --name openclaw --restart unless-stopped \+ -p 18789:18789 -p 8787:8787 \+ -v /home/sandbox/.openclaw:/data \+ --env-file /home/sandbox/.openclaw/env \+ diggerhq/openclaw-managed:${OPENCLAW_VERSION}`,+ { timeout: 30 },+ );+ await waitReady(sandbox);+}+```++Adapter methods that exist today (`restart`, `setModel`, `wireChannel`,+`waitChannelReady`) get simpler — they shell into the running container+or call its HTTP endpoints. Reboot recovery is free: `--restart+unless-stopped` brings the container back when the sandbox boots.++## Tradeoffs++| | Checkpoint fork (today) | Image pull (proposed) |+|---|---|---|+| Cold-start latency | ~3-5s warm fork + ~18s gateway | ~10s docker pull + ~5s warm boot |+| Warm-pool latency | ~1s | ~3s (cache hit) |+| Failure surface | rootfs/checkpoint/openclaw all coupled | layers debuggable independently |+| Runtime version control | rebuild snapshot, redeploy sessions-api | docker tag bump |+| Reboot recovery | osb-agent → supervisord → openclaw (~18s gap) | docker daemon → container (auto, ~3s) |+| Per-agent env | env file written post-fork, supervisorctl restart | env file mounted at container start |+| Cross-org issues | checkpoint ownership / `is_public` | none — image is a public dep |+| Worker disk pressure | one rootfs per template | rootfs + image cache (~500MB-1GB) |+| Storage growth | checkpoint blob per release | docker registry per release |++The honest cost: cold start is slower for the first agent on each+worker. A warm pool of "openclaw-image-prepulled" sandboxes mitigates+this — image is in the worker's overlay, fork-from-warmpool is fast,+agent-create just needs to run-the-container. The autoscaler already+maintains warm pools for the base template; we'd add a second pool+keyed on `template=openclaw-managed`.++The dishonest cost: nothing. We've been spending more eng-time on+checkpoint debugging this month than the latency difference can ever+charge back.++## Migration plan++Phased so we can roll back per-stage if anything misbehaves.++**Phase 0 — image registry plumbing (no user-visible change).**+1. Spin up `ghcr.io/diggerhq/openclaw-managed` (or push to the existing+ Azure Container Registry — `opencomputer-prod-acr` if it exists,+ easier vault story).+2. Author `Dockerfile.openclaw-managed` in this repo. Build via a new+ `.github/workflows/build-openclaw-image.yml` that runs nightly ++ on-demand, tags with `<openclaw-version>-<git-sha>`, pushes to+ registry.+3. Test: pull the image into a stock sandbox, `docker run`, curl+ `/health`. Verify Telegram + chat-completions still work. This is+ purely additive; no production code changes yet.++**Phase 1 — adapter behind a feature flag.**+1. Add `OPENCLAW_PROVISIONER` env to sessions-api: `checkpoint` (default,+ today's behaviour) or `image` (new).+2. New code path lives alongside the existing one in `src/lib/cores.ts`+ and `src/lib/adapters/openclaw.ts`. Old code keeps shipping.+3. Wire OC's billing exemption through metadata.agent_id same as today+ — provisioning path doesn't matter for billing.+4. Test on dev VM with `OPENCLAW_PROVISIONER=image`. Validate full+ create → connect Telegram → chat round-trip. Compare end-to-end+ timings.++**Phase 2 — flip prod, keep checkpoint as fallback.**+1. Set `OPENCLAW_PROVISIONER=image` on Fly's `bolt-platform` app.+2. Existing agents (created off the old checkpoint) continue to work+ — they're not re-provisioned. Only new agents take the image+ path.+3. Watch error rates, fork latencies (now image-pull latencies), and+ chat-turn latencies for 1 week.+4. If anything regresses, flip the flag back. No rollback needed+ beyond the env change.++**Phase 3 — retire the checkpoint path.**+1. Once a week of clean prod, delete the checkpoint code in+ `cores.ts` / adapter / `OPENCLAW_CHECKPOINT_ID` env.+2. Delete `scripts/build-openclaw-snapshot.ts`.+3. Remove the `is_public` checkpoint surface for OpenClaw (we keep+ it for any other public-checkpoint use cases).++**Phase 4 (optional) — warm pool for openclaw image.**+1. Teach the autoscaler to keep N idle sandboxes per region with the+ image already pulled. New OpenClaw agent grabs one off the pool;+ provisioning becomes "container start" only.+2. Trade-off is cost (idle worker capacity); only worth doing once+ we've got steady demand for managed agents.++## Open questions / unknowns++- **Does the official OpenClaw image exist?** If it doesn't, we'd+ build our own from source; same plan, more upstream-tracking+ obligation.+- **Networking for Telegram webhooks.** Today the sandbox listens on+ `:8787` directly; the outside world reaches it via OC's reverse+ proxy. With docker we'd port-publish 8787 from container to+ sandbox-host; same proxy contract holds. Want to confirm there's no+ bridge-mode quirk on the worker's docker daemon.+- **Image cache GC.** Workers will accumulate openclaw image layers;+ need an eviction policy on the worker. Probably reuse the existing+ base-image cleanup hook.+- **Versioning across regions.** If we eventually run multi-region,+ we want each region's worker pool pulling from the closest registry+ mirror to keep cold start under control.++## What we're NOT changing++- Stripe paywall + per-agent subscription gating (entitlement check+ still happens on `connect telegram`).+- Sandbox-billing exemption for subscribed-agent sandboxes+ (metadata.agent_id is set the same way regardless of provisioner).+- Sessions-api ↔ OC auth flow (identity JWTs, downstream tokens).+- CLI surface (`oc agent send/chat`, paywall preflight).+- Dashboard UX.++## Decision needed before phase 0++- Registry choice: `ghcr.io/diggerhq` or Azure ACR? ACR keeps the+ pull entirely on the Azure backbone for prod workers, which is+ faster and avoids GitHub rate limits.+- Image build cadence: nightly is fine; tag scheme like+ `<upstream-openclaw-version>-<our-build-sha>` makes per-build+ rollback trivial. Confirm before we ship.diff --git a/.agents/design/sandbox-session-logs.md b/.agents/design/sandbox-session-logs.mdnew file mode 100644index 00000000..66757441--- /dev/null+++ b/.agents/design/sandbox-session-logs.md@@ -0,0 +1,530 @@+# Sandbox session logs: capture, ship, and surface++## TL;DR++Give every sandbox a "Logs" tab in the dashboard that shows+**everything happening inside it** — every line written to+`/var/log/*`, every byte of stdout/stderr from every command exec'd+through the platform — with live tail and free-text search.++The shape: a small in-guest log forwarder embedded in `osb-agent`+ships events directly to **Axiom** over HTTPS, using a long-lived+**dataset-scoped ingest-only token** baked into sandbox env at+creation. The control plane is **not on the hot path** for log bytes+— it only mints the token at sandbox-create and proxies read queries+back to the UI. The UI's Logs tab is a thin SSE consumer over a new+`GET /api/sandboxes/:id/logs` endpoint that runs APL queries against+Axiom server-side.++This is a strict superset of what comparable sandbox platforms+surface today (process lifecycle only — `pid X started`, `pid X+ended` — no command text, no stdout, no network, no file ops).+Closing this gap is high-leverage: the same five lines of output+that resolve "why did my LLM call fail?" today require an+SSH-grade investigation.++A small precedent for the same architecture already exists in our+own agentbox-poc workspace (Go log-shipper, ~150 lines, identical+batch-and-POST shape). We're copying that shape, narrowing the+integration to osb-agent's existing exec path, and adding a+control-plane-proxied read API.++## Problem++Today, "what's happening inside my sandbox?" has no answer in the UI.++The closest existing surfaces are all partial:++- `command_logs` (`internal/db/migrations/001_initial.up.sql:58-68`,+ populated from `internal/db/store.go:821-848`) captures command ++ exit_code + duration_ms — no stdout/stderr, and never queried by+ the dashboard.+- `pty_session_logs` captures only metadata (bytes in/out, timestamps)+ — not the actual PTY bytes.+- `agent_events` / `agent_operations` (sessions-api) cover lifecycle+ for *agents*, not *sandboxes*; they're sparse and structured.+- The Logs tab on `AgentDetail.tsx` (line 322-419) tails+ `/tmp/openclaw-gateway.log` for OpenClaw-only managed agents via a+ per-call `getAgentLogs` SDK invocation, and the `GET+ /v1/agents/:id/logs` endpoint it calls **doesn't exist server-side**+ — that tab silently 404s.++What users actually need to see:++1. **Their own application logs.** Whatever they write to+ `/var/log/myapp.log` or stdout from a server they started.+2. **Command output.** Every `exec` they (or their SDK code) ran:+ command, args, stdout, stderr, exit code.+3. **System events that affect them.** OOM kills, kernel messages,+ the start/stop of services they configured.++A recent customer-support investigation hinges on exactly this gap:+a curl from inside a customer's sandbox to an external URL returned+an opaque upstream error, but nothing in the OC dashboard showed the+request, the response, or the failure mode. Resolving the ticket+required us to manually reproduce the call from a fresh sandbox in+another org. With a Logs tab, the user could have self-served — a+search for the destination hostname would have returned the line.++## Proposed architecture++Five components, three new:++```+┌──────────────────────── sandbox VM ────────────────────────┐+│ │+│ /var/log/* ──┐ │+│ Exec stdout ───┤ osb-agent (existing PID 1) │+│ Exec stderr ───┤ ┌──────────────────────────────┐ │+│ └─► │ log forwarder goroutine pool │ ──┐ │+│ │ - tails /var/log via fsnotify│ │ │+│ │ - tees from Exec/ExecStream │ │ │+│ │ - batches: 100 lines/200ms │ │ │+│ └──────────────────────────────┘ │ │+│ │ │+└────────────────────────────────────────────────────────┼───┘+ │+ worker → agent gRPC at boot: │+ ConfigureLogship( │+ ingest_token, dataset, │ HTTPS+ sandbox_id, org_id) │ POST+ │+ ▼+ ┌──────────────────┐+ │ Axiom │+ │ dataset: │+ │ oc-sandbox-logs │+ └────────┬─────────┘+ │+ │ APL query+ │ (server-side+ │ token, never+ │ leaves OC)+ │+┌──────── OC control plane ──────────────────────┐ │+│ │ │+│ GET /api/sandboxes/:id/logs ◄──────────────┼─────┘+│ - auth: org owns sandbox │+│ - APL: where sandbox_id == :id │+│ - SSE: emit historical batch + poll loop │+│ │+└────────────────────┬───────────────────────────┘+ │ EventSource+ ▼+ SessionDetail.tsx → Logs tab+ (live tail + search)+```++### 1. In-guest log forwarder (in `osb-agent`)++A new goroutine pool inside the existing `osb-agent` (PID 1 of every+sandbox VM). Lives in `internal/logship/` (new package).++**Why in-process, not a separate binary:** half the data we want to+ship — exec stdout/stderr — is already produced inside the agent+(`Exec` / `ExecStream` RPC handlers). Routing it through IPC to a+sidecar would duplicate buffering and add a second crash surface.+The other half (`/var/log/*` tailing) is a generic concern but+small. A separate `osb-log-shipper` binary buys us nothing useful+and adds a process-supervision problem inside the VM.++**Data sources:**++- **`/var/log/**`** via `fsnotify`: on start, list and tail every+ regular file under `/var/log`. On `IN_CREATE` for new files+ (rotation, app-created), start a new tailer. On `IN_MODIFY`, read+ appended bytes. Standard inotify-tail pattern; total state is+ one file descriptor + offset per file.+- **Exec output (Exec, ExecStream, ExecSession*)**: a one-line tee+ in each handler. Existing handlers already produce stdout/stderr+ buffers; we hand the buffers to a non-blocking channel send into+ the forwarder. The current behaviour (returning stdout/stderr to+ the gRPC caller) is preserved unchanged.+- **PTY output**: out of scope for v1. PTY content is interactive+ (passwords, secrets typed by the user); shipping it by default+ has a different consent shape. We can add it behind an opt-in+ flag later.++**Event schema** (one Axiom row per line):++```json+{+ "_time": "2026-05-05T16:55:51.123456789Z",+ "sandbox_id": "sb-0a1b2c3d",+ "org_id": "org-7e8f9a",+ "source": "var_log" | "exec_stdout" | "exec_stderr" | "agent",+ "line": "May 5 16:55:51 sandbox sshd[1234]: ...",++ // when source == "var_log":+ "path": "/var/log/syslog",++ // when source == "exec_*":+ "exec_id": "ulid-of-this-exec",+ "command": "curl",+ "argv": ["-sS", "https://example.com"],+ "exit_code": 0+}+```++`exit_code` is set on the *final* line of the exec's output (the+EOF marker), not on every line — that lets the UI render+"command X exited 0/1" without joining to a separate table.++**Batching:** 100 lines or 200ms, whichever fires first. Same+discipline as agentbox's shipper. POST to+`https://api.axiom.co/v1/datasets/${AXIOM_DATASET}/ingest` with+`Authorization: Bearer ${AXIOM_INGEST_TOKEN}`.++**Backpressure:** the channel feeding the shipper has a fixed+buffer (10k events ≈ a few MB). If full, drop **oldest** with a+counter (`logship_dropped_total`). Drop-oldest matches user+intuition for "tail" — the recent stuff is what they're looking at;+the old stuff is the loss. The counter is itself shipped as an+event so the UI can show "logs dropped: N" if it ever happens.++**Reliability:** if Axiom returns 5xx or the network is partitioned,+retry with backoff up to 30s. After 30s, drop the batch with a+counter event. We do **not** spool to disk in v1: it adds an+unbounded-disk-usage failure mode (a partitioned sandbox running+for days could fill the disk) and the failure case it covers+(brief Axiom blip) is already handled by retry.++**Hot-upgrade:** none. The agent.proto stability contract+(`proto/agent/agent.proto:11-34`) means old sandboxes keep their+old agent forever. Sandboxes created before this lands won't have+log shipping. That's fine — the feature is opt-in by virtue of+sandbox-create timing, and old sandboxes typically don't live+longer than a week or two anyway.++### 2. osb-agent tee on Exec/ExecStream++Modify the four exec entry points to route output through the+forwarder in addition to the existing return path:++- `Exec` (`agent.proto:37`): collects full stdout/stderr buffers;+ on completion, hand both to the forwarder split into lines, with+ one final EOF event carrying `exit_code`.+- `ExecStream` (`agent.proto:40`): wraps the existing chunk+ pump with a goroutine that line-buffers and forwards.+- `ExecSessionAttach` (`agent.proto:72`): same wrap, but the exec+ session can outlive the attach — the forwarder needs to keep+ reading scrollback even after the gRPC client disconnects, so+ this hooks at the session level not the attach level.+- `PTYAttach` (`agent.proto:68`): **NOT** wrapped in v1. PTY content+ is interactive and includes typed passwords / secrets.++In all four, every line generated also gets a unique `exec_id`+(ULID generated when the exec starts), the `command` and `argv`,+and on the final EOF line the `exit_code`. Schema above.++Implementation note: do this with a `io.Writer` adaptor wrapped+around the existing stdout/stderr pipes. The forwarder is+`io.Writer`; chain it as a `io.MultiWriter` alongside the existing+buffer. Zero new buffering, ~20 lines of code per entry point.++### 3. Axiom dataset & schema++One dataset: `oc-sandbox-logs`. Same dataset across all OC+sandboxes (per-sandbox isolation enforced at query time, not+storage time — a separate dataset per sandbox would not scale).++**Token:** a single, long-lived, **dataset-scoped, ingest-only**+Axiom token. Stored in OC's secret store; injected into every+sandbox at create time as `AXIOM_INGEST_TOKEN`. Ingest tokens in+Axiom can only POST to `/ingest` for the named dataset — they+cannot read or query, cannot list other datasets, cannot administer.+A sandbox compromised by a malicious user can at worst write+spurious events claiming arbitrary `sandbox_id` / `org_id`, which+is an **annoyance, not a breach** — the read API filters on+`sandbox_id` matching the sandbox the user is viewing, and that+filter is enforced server-side based on the user's authenticated+session, not on data inside the event.++Spoofing isolation: a user *could* pollute another org's view by+emitting events with someone else's `sandbox_id`. We mitigate by+adding `_event_source` on ingest equal to the sandbox's worker+hostname, validated server-side at query time:++```apl+['oc-sandbox-logs']+ | where sandbox_id == "sb-0a1b2c3d"+ | where _event_source startswith "worker-" // dropped events that+ // claim to be from+ // somewhere unexpected+ | sort by _time asc+```++This isn't airtight but it's the level of defence-in-depth that+matches the threat model: Axiom is not the source of truth for+billing or auth; it's a debugging surface.++Retention: whatever Axiom's default is for the plan we're on+(30 days at the time of writing). Out of scope for v1; we'll+revisit when we look at cost.++### 4. Configuration injection at sandbox boot++There is no existing path to inject env vars into the *agent+process's own* environment at PID 1 startup. The existing `SetEnvs`+RPC (`proto/agent/agent.proto:78-79`) stores envs in agent memory+**for user commands run via Exec/ExecStream** — it does not modify+the agent's own `os.Environ()`. The agent at PID 1 startup has only+the kernel-supplied minimal env (`PATH` is set explicitly in+`cmd/agent/main.go:26`, nothing else).++So we add **one new RPC** to `proto/agent/agent.proto` —+the only proto change in this design. Additive, allowed under the+proto stability contract:++```proto+// ConfigureLogship sets log-shipping configuration. Worker calls+// this immediately after VM boot, before any user-facing operations.+// Sandboxes whose worker doesn't call this never ship logs (kill-+// switch by omission).+rpc ConfigureLogship(ConfigureLogshipRequest) returns (ConfigureLogshipResponse);++message ConfigureLogshipRequest {+ string ingest_token = 1; // empty = disable; treated as kill-switch+ string dataset = 2;+ string sandbox_id = 3;+ string org_id = 4;+}++message ConfigureLogshipResponse {}+```++Flow:++1. Add `AXIOM_INGEST_TOKEN` and `AXIOM_DATASET` to the worker's+ environment (deploy plumbing — the worker process reads these+ at startup, not the agent).+2. Worker calls `ConfigureLogship` over the worker→agent gRPC+ channel right after sandbox boot, passing the token, dataset,+ and the per-sandbox `sandbox_id` / `org_id` identifiers it+ already has in scope.+3. The agent receives the call and hands the four values to the+ forwarder, which lazy-initialises and starts shipping.+4. If `AXIOM_INGEST_TOKEN` is unset on the worker, the worker+ skips the call. Agent's forwarder stays dormant. This is the+ rollback / kill-switch — clear the env var, redeploy workers,+ new sandboxes don't ship.++**Brief startup window where shipping is inactive** (~50–100ms+between agent ready and worker's `ConfigureLogship` call). Logs+written in that window are not captured. Acceptable: we don't+backfill `/var/log` history anyway (we tail from current EOF), and+no exec runs before the worker is talking to the agent.++### 5. Read API: control-plane-proxied SSE++New endpoint: `GET /api/sandboxes/:sandboxId/logs`.++**Auth:** existing dashboard auth path (cookie / JWT). The handler+verifies `sandboxId` belongs to an org the user is a member of —+same check `sandbox.go` already performs for other dashboard reads.++**Query params:**++- `tail=true|false` (default `true`): if true, after returning+ historical batch, keep the SSE open and poll for new events.+- `since=<rfc3339>` / `until=<rfc3339>`: time window. Default is+ `since=sandbox.created_at`, `until=now`.+- `q=<text>`: free-text search; appends `| where line contains "..."`+ to the APL query (with escaping).+- `source=var_log|exec_stdout|exec_stderr|agent`: filter by source.+- `limit=<n>` (default 1000, max 10000): cap on the historical+ batch. Live tail isn't capped.++**Response shape:** SSE stream. Each `data:` line is a JSON event+matching the ingest schema (sans `_time` parsing — leave the wire+format identical so the client doesn't have to know two shapes).+A `comment` line every 15s as an SSE keepalive.++**Live tail loop:** poll Axiom every 1s with `since=<last_event_time>`,+emit any new rows. Same shape as agentbox's+`packages/api/src/routes/sessions.ts:240-275`. We can revisit this+to use Axiom's [streaming query API](https://axiom.co/docs/restapi/endpoints/queryApl)+once we confirm it's stable, but the polling path is fine for v1+and matches the proven precedent.++**Why not a direct Axiom query from the browser?** Two reasons:+(a) it would require shipping a query token to the client, which+is an entirely separate auth surface to manage; (b) we want one+chokepoint where we enforce "this user can only see their org's+sandboxes." The control plane already owns that check; let it own+the query.++### 6. UI: Logs tab on SessionDetail++`web/src/pages/SessionDetail.tsx` gets a new tab next to the+existing Terminal button. Components:++- **Stream viewer:** a virtualised list (the same library+ `AgentDetail` uses for its broken Logs tab — we can lift that+ component). Each row is one event, color-coded by `source`+ (stdout neutral, stderr red-tinted, var_log gray, agent purple).+ Auto-scroll-to-bottom unless the user scrolls up; pause/resume+ toggle.+- **Header bar:** time-range picker (last 1h / 6h / 24h / since+ sandbox boot / custom), source-filter chips, a search box, and+ a small status indicator showing live-tail state.+- **Search:** debounced 200ms, sends the query string to the+ endpoint, replaces the visible stream with the filtered batch.+ When cleared, returns to live tail.+- **Per-event drill-in:** click a `source=exec_*` row to scroll the+ view to all rows with the same `exec_id` — equivalent to "show+ me the full output of this command."++Out of scope for v1: log download, retention controls, alert rules,+saved searches. We can add any of these later without re-architecting.++## Tradeoffs++| | **Tee in osb-agent + Axiom (proposed)** | **Run rsyslog/journald + ship via Vector** | **Stream over existing gRPC, store in OC's DB** |+|---|---|---|---|+| Hot path through control plane | None — guest pushes direct | None — guest pushes direct | Yes — every byte through worker → control plane |+| New infra to operate | One Axiom dataset | rsyslog + Vector + storage backend | Schema, retention, indexing on our DB |+| Search latency | <1s (Axiom indexed) | depends on backend | minutes-to-hours unless we add OpenSearch |+| Time to v1 | 3-5 days | 2-3 weeks | 2-3 weeks + ongoing index ops |+| Vendor lock-in | Yes — Axiom | Low — Vector swaps backends | None |+| Cost at our scale (today) | small (decide later) | similar | high (storage + index) |+| Supports live tail | Yes (1s poll) | Yes if backend supports | Yes if we build it |+| Supports search | Yes (APL) | Yes if backend supports | Painful without index |+| Captures ad-hoc user processes | No (only platform-exec'd) | Yes (everything goes through syslog) | No (only platform-exec'd) |++The sharpest tradeoff is **vendor lock-in for ingest and query+shape**. Mitigation: the forwarder's egress is one HTTP POST with a+small JSON shape. If we ever want to move off Axiom, we+re-target the URL and rewrite the query path; no code outside the+forwarder and the read endpoint depends on Axiom-specifics.++The "captures ad-hoc user processes" gap is real — if a user+runs `nohup my-server &` inside an interactive shell, the platform+never sees the process and its stdout never reaches the tee. The+auditd-based process tracking I sketched in chat-history is the+follow-up that closes this; that's a Tier-3 enhancement on top of+this design, not a prerequisite.++## Open design questions++These are deliberately deferred:++- **Cost.** Ingest is cheap; query / retention is the variable.+ Need a back-of-envelope based on the GB-hours data we already+ have, plus a per-sandbox rate cap (e.g. 1MB/s ingest). Can do+ this once we have a week of v1 data.+- **Retention.** Default is whatever Axiom defaults to. We may+ want shorter (cheaper, less risk for sensitive data) or longer+ (deeper investigation window). Decide once we see the cost+ envelope.+- **Privacy / opt-out.** Some customers will run sensitive code+ inside sandboxes. Default-on log capture without a per-org+ opt-out is a soft commitment we should think about before broad+ GA. Easy to add: a flag on `orgs` that, when set, makes the+ worker skip injecting `AXIOM_INGEST_TOKEN` for that org's+ sandboxes.+- **PTY content.** Excluded from v1 for the consent reasons above.+ If we want to add it, the natural shape is a per-sandbox flag+ ("Capture PTY output to logs?") visible in the UI when the user+ opens a terminal.+- **Per-org or per-tier rate caps.** A pathological sandbox can+ push hundreds of MB of logs/sec. The forwarder's drop-oldest+ semantics protect us from unbounded memory; a hard rate cap at+ the egress (e.g. drop events past N/sec) protects Axiom and our+ bill.+- **How `command_logs` and `agent_events` interact with this.**+ Log events overlap conceptually with `command_logs` (which has+ cmd + exit + duration) and `agent_events` (sparse error events).+ We don't propose deleting either — they're cheap, structured,+ and useful as authoritative summaries. Logs are the unstructured+ firehose for drill-in. The Logs tab and the existing Events tab+ on AgentDetail can coexist.++## Migration plan++Phased so each phase is independently shippable and revertible.++**Phase 0 — Axiom plumbing (no user-visible change).**+1. Provision the Axiom workspace (or add a dataset to the existing+ one used by agentbox, if we share). Create:+ - Dataset `oc-sandbox-logs` (30-day retention default).+ - One ingest token, dataset-scoped, ingest-only.+ - One query token, dataset-scoped, read-only — stored in OC+ control plane secret store.+2. Add `AXIOM_INGEST_TOKEN`, `AXIOM_DATASET`, `AXIOM_QUERY_TOKEN`+ to the deploy env templates.++**Phase 1 — osb-agent forwarder behind a flag.**+1. Implement `internal/logship/` with `/var/log` tail and+ one `io.Writer` interface that wraps stdout/stderr.+2. Implement the in-`Exec` / `ExecStream` / `ExecSessionAttach`+ tees as a `io.MultiWriter` chain.+3. Gate with `AXIOM_INGEST_TOKEN`-empty-means-disabled; default off+ in dev, on in prod.+4. Bake into a new agent build; new sandboxes pick it up+ automatically. Test on a single dev worker first.++**Phase 2 — read API.**+1. Add `internal/api/sandbox_logs.go` with the SSE endpoint and the+ APL query builder.+2. Wire into `internal/api/router.go`.+3. Test end-to-end: spin up a sandbox, run a few execs, hit the+ endpoint, see events.++**Phase 3 — UI Logs tab.**+1. Add the tab to `web/src/pages/SessionDetail.tsx`.+2. Lift the virtualised list component pattern from+ `AgentDetail.tsx`'s Logs tab.+3. Implement the search box + source filter + time picker.+4. QA on a few real sandboxes; check tail latency, search latency,+ memory footprint of the page after 30 minutes of streaming.++**Phase 4 — turn it on broadly.**+1. Watch ingest volume and Axiom cost for a week.+2. Decide on rate cap, retention, and any per-org opt-out.+3. Document in the public docs.++Each phase is reversible by a config / deploy change without+schema migrations on our DB.++## What we're NOT changing++- `command_logs` table — keeps populating from+ `internal/db/store.go:821-848`. Still useful as authoritative+ cmd + exit + duration summary, especially for billing-adjacent+ audits.+- `agent_events` / `agent_operations` in sessions-api — unchanged.+- `AgentDetail.tsx` Logs tab — that's an OpenClaw-specific+ thing; stays as-is. (It's separately broken — the+ `GET /v1/agents/:id/logs` endpoint doesn't exist in sessions-api+ — but that's tracked separately and unrelated to sandbox-level+ logs.)+- The egress proxy (`internal/secretsproxy/`) — no proposed+ changes. We do propose teeing the proxy's request log to Axiom+ too as a follow-up (Tier-2), but it's not in v1 scope.+- The `osb-agent` ↔ worker proto — exactly **one** new RPC+ (`ConfigureLogship`, see §4). Log bytes themselves do not flow+ over this channel; they go out a separate egress path entirely+ (HTTPS to Axiom). The proto change is configuration only.+- Per-sandbox secret store — no new secrets per sandbox.+ `AXIOM_INGEST_TOKEN` is a single global config value.++## Decisions needed before phase 0++- **Dataset name and shape.** Proposed: `oc-sandbox-logs` (one+ dataset, one shape, every sandbox writes to it).+- **Reuse agentbox's Axiom workspace, or stand up our own?**+ Proposed: stand up our own — different product, different+ retention/cost tradeoffs likely, and we don't want a single+ Axiom outage to take down both.+- **Token rotation cadence.** Proposed: none. Long-lived, ingest-+ only, baked into worker env at deploy time. Rotate when the+ threat surface changes (e.g. if we suspect a leak), not on a+ schedule.+- **Should we ship to Axiom *and* our own DB?** Proposed: no.+ Axiom is the only store. `command_logs` and `agent_events` stay+ as their own narrow surfaces and don't try to be log stores.++Once these are agreed, phase 0 is a half-day of Axiom + deploy+plumbing; phase 1-3 is the bulk of the work (3-5 days of focused+engineering).diff --git a/.agents/work/logship-empty-token-warn.md b/.agents/work/logship-empty-token-warn.mdnew file mode 100644index 00000000..3ab0b64b--- /dev/null+++ b/.agents/work/logship-empty-token-warn.md@@ -0,0 +1,195 @@+# Logship: warn loudly when the Axiom token is empty++> ⚠️ **NO PII IN GIT.** Audit before every Write/Edit. Rule:+> `feedback_no_pii_in_git.md` in project memory.++Status: **planned, not started.** Builds on PR #226 (the+sandbox-session-logs feature, merged `2af73c4`) and Brian's+follow-up `d6c2985` (KV mapping for Axiom secrets).++## Context++After PR #226 merged and rolled out, prod workers silently weren't+shipping logs. Two independent gaps:++1. **KV-mapping gap** — `internal/config/keyvault.go` only loads+ secrets in `secretMapping`; `AXIOM_*` weren't there. Fixed by+ `d6c2985`.+2. **Stale-cfg gap** — `cfg.AxiomIngestToken` is read from+ `os.Getenv` once at server startup. A server that started+ before the secret was added to KV (or before any rotation)+ keeps an empty cfg and bakes empty tokens into every worker.++Both were silent. This PR is three log lines that make the second+gap loud the next time it happens.++## Code in this PR (all in `cmd/server/main.go`)++1. **Startup log** mirroring the existing `"sandbox session logs+ read API enabled"` line on the query-token side. Empty+ ingest-token logs `WARNING`; populated logs the ok message.+2. **Spawn-time warning** when `cfg.AxiomIngestToken == ""` and+ the Azure-pool path renders `workerEnv` — catches stale-cfg+ post-rotation.+3. **One-line `deploy/ec2/README.md` note**: any `AXIOM_*` rotation+ requires a server restart.++~10 lines of code, no proto, no schema, no UI, no tests.++## Rollout — what happens after this PR merges++The actual prod recovery doesn't need any manual ops; it falls+out of the standard deploy. Sequence:++1. **Merge + deploy.** CI builds and ships the new control-plane+ binary. `deploy-server.sh:97` runs `systemctl restart+ opensandbox-server`.+2. **Server restart re-reads cfg.** With `d6c2985` already in main,+ `LoadSecretsFromKeyVault` populates `AXIOM_INGEST_TOKEN` /+ `AXIOM_QUERY_TOKEN` / `AXIOM_DATASET` from KV before+ `config.Load`. New diagnostic should print+ `"opensandbox: workers spawned by this server will ship logs+ to Axiom (dataset=oc-sandbox-logs)"`. If `WARNING` fires+ instead, the secret isn't in KV — fix KV before continuing.+3. **`targetWorkerVersion` bumps.** Server learns the new SHA+ from the deploy and the autoscaler's+ `internal/controlplane/scaler.go:118` field updates. Every+ currently-running worker now reports a `WorkerVersion` that+ doesn't match.+4. **Rolling-replace runs automatically.** `scaler.go:823+ rollingReplace` — quota-aware loop: pick the lightest stale+ worker, drain it (no new sandboxes routed there), live-+ migrate its existing sandboxes onto a peer, destroy the+ Azure VM, spawn a fresh one. Repeat until no stale workers+ remain. Wall-clock takes minutes-to-hours depending on pool+ size + sandbox migration latency, but unattended.+5. **Fresh workers bake the correct env.** Each spawn renders+ `workerEnv` from the now-populated `cfg.AxiomIngestToken`.+ Worker boots → `cmd/worker/main.go` logs `"sandbox session log+ shipping enabled (dataset=oc-sandbox-logs)"`.+6. **New sandboxes ship.** Any sandbox created on a fresh worker+ gets `ConfigureLogship` with the real token. In-VM agent+ activates the shipper. Logs flow to Axiom and the dashboard+ Logs panel within seconds of the events being produced.++**No prod SSH, no manual drain, no admin destroy endpoint, no+Azure CLI required.**++## What stays broken — and why we're not fixing it in this PR++**Existing sandboxes never start shipping.** Their in-VM agent+already received `ConfigureLogship` once with an empty token; the+shipper is dormant in agent memory and stays that way for the+sandbox's lifetime. Hibernate + wake preserves the dormant state+(memory snapshot). Live migration to a fresh worker preserves it+too — the agent's struct moves with the VM.++The only way to flip an existing sandbox to shipping is to+recreate it. We're choosing not to push customers to do that,+because:+- It's not a regression — these sandboxes never shipped logs.+- New sandboxes do ship.+- Customer-visible only in the dashboard Logs panel; pre-fix+ sandboxes show empty.++If a customer specifically asks why their old sandbox has no+logs, the workflow is: kill + recreate. That's a docs/CS thing,+not a code thing.++## Deliberately out of scope (PR-internal)++- **Re-reading `os.Getenv` per spawn.** Right fix for+ rotation-without-restart is a periodic config reloader; scope+ creep.+- **Fail-fast on empty.** Server has legit reasons to run+ without logship (dev, combined mode, kill-switch).+- **A metric.** No control-plane-side metric pipeline.+- **Retroactive sandbox fix.** See above.++## Pre-merge prod state (verified 2026-05-06)++Confirmed the bug is live in prod, not just theoretical. Test+ran via the public API; no SSH, no log access required.++```+SBX=$(curl -sf -X POST $PROD_URL/api/sandboxes \+ -H "X-API-Key: $KEY" -d '{"templateID":"default"}' \+ | jq -r .sandboxID)+curl -X POST $PROD_URL/api/sandboxes/$SBX/exec \+ -H "X-API-Key: $KEY" \+ -d '{"cmd":"bash","args":["-c","echo PROD_VERIFY_$(date +%s)"]}'+sleep 6+curl -N $PROD_URL/api/sandboxes/$SBX/logs?tail=false \+ -H "X-API-Key: $KEY"+```++Result on `sb-a4de01f8`:+- Sandbox create → **201**+- Exec → **201** (session created, command ran on worker)+- Logs query → **HTTP 200 with empty body**++What that tells us:+- 200 (not 503) → server has `AXIOM_QUERY_TOKEN` and the read API+ is wired. Brian's `d6c2985` landed and the control plane has+ been restarted since.+- Empty body → the worker that booted this sandbox shipped+ nothing to Axiom. Not even the boot-time worker-internal exec+ EOFs (which are unconditional in dev). The worker's+ `cfg.AxiomIngestToken` is empty → `configureLogshipForSandbox`+ silently bails → in-VM agent activates a dormant shipper.++This is the exact failure mode this PR's WARNING lines are+designed to surface.++## Expected post-merge result++Re-run the same three-call sequence (create → exec → read logs)+post-deploy. Expected:++- Sandbox create → 201+- Exec → 201+- Logs query → **HTTP 200 with at least the synthesised exec EOF+ rows** (`✓ bash exited 0`) and ideally the `PROD_VERIFY_<ts>`+ line itself.++Plus, in the control plane's journalctl right after the deploy:++```+opensandbox: workers spawned by this server will ship sandbox+ session logs to Axiom (dataset=oc-sandbox-logs)+```++If `WARNING: AXIOM_INGEST_TOKEN empty` shows up instead, the+rollout is unsafe — the secret is missing from KV and pre-deploy+state holds. Stop and fix KV before continuing.++### Timing++Server log: instant on restart. First fresh worker: ~5 min.+Start retrying create+exec+logs at +5 min, every 2-3 min — first+hit = verified. Full pool replacement (when single-shot becomes+reliable) is minutes to hours depending on sandbox-migration+load.++## Verification (dev)++On the EC2 dev host:+- Unset `AXIOM_INGEST_TOKEN`, daemon-reload, restart server →+ expect WARNING line in journalctl.+- Re-set, restart → expect the ok line.+- Spawn-time warning fires only on the Azure-pool path; not+ reachable from EC2 dev. Verified by code inspection.++## Status log++- *2026-05-06* — branch + working doc created. No code yet.+ Awaiting review before implementation.+- *2026-05-06* — code changes landed: startup log + spawn-time+ warning in `cmd/server/main.go`, README rotation note in+ `deploy/ec2/README.md`. ~15 lines net. `go build ./cmd/server/...`+ clean. Ready for review.+- *2026-05-06* — verified in prod via public API only (no SSH /+ KV / journalctl access needed): create-sandbox → exec → read+ logs returned HTTP 200 + empty body, confirming workers are+ silently not shipping. Captured in "Pre-merge prod state"+ above.diff --git a/.agents/work/sandbox-session-logs-impl.md b/.agents/work/sandbox-session-logs-impl.mdnew file mode 100644index 00000000..acdb2156--- /dev/null+++ b/.agents/work/sandbox-session-logs-impl.md@@ -0,0 +1,1095 @@+# Sandbox session logs — implementation plan++> ⚠️ **NO PII IN GIT.** Customer emails, person/org names, ticket+> identifiers tying activity to a specific individual must never+> appear in any committed file. Use generic stand-ins ("a customer",+> anonymised IDs). Full rule in project memory+> `feedback_no_pii_in_git.md`. Audit before every Write/Edit.++Status: **design approved, implementation not started.** Builds on+[`.agents/design/sandbox-session-logs.md`](../design/sandbox-session-logs.md)+(design doc, draft PR #226) and the OC architecture as of `main` at+the time of writing.++This is a **complete reference** for the implementation. Future agents+should be able to work from this doc + the design doc without+needing conversation history.++Decisions locked in (from design doc; do not relitigate without+re-opening the design):++| Decision | Locked value |+|---|---|+| Log host | Axiom |+| Forwarder placement | In-process inside `osb-agent` (no sidecar) |+| Token model | One long-lived, dataset-scoped, **ingest-only** Axiom token, baked into worker env at deploy time |+| `/var/log` capture | Push-only, via `fsnotify`-based tail in the forwarder |+| Exec stdout/stderr capture | Tee in osb-agent's `Exec` / `ExecStream` / `ExecSessionAttach` handlers via `io.MultiWriter` |+| PTY content | **Excluded** from v1 (consent surface is different) |+| Read API | SSE-based, control-plane-proxied; never expose Axiom token to client |+| Auth on read | Existing dashboard auth + `org owns sandbox` check |+| Live tail mechanism | Poll Axiom every 1s (matches agentbox precedent; revisit if Axiom streaming-query proves stable) |+| MVP scope | Live tail + free-text search |+| Out of MVP | Retention controls, log download, alert rules, saved searches, per-org opt-out, rate caps, PTY capture, ad-hoc-process tracking |+| Backpressure | Drop-oldest with counter event; in-memory only (no on-disk spool) |++## What lives where++All work is in this repo (`opencomputer`). No cross-repo coordination+needed.++```+.agents/+├── design/sandbox-session-logs.md (design doc — same PR)+└── work/sandbox-session-logs-impl.md (this file)++proto/agent/+└── agent.proto (one new RPC: ConfigureLogship)++cmd/agent/ (the in-guest agent)+└── main.go (wire shipper + tailer at startup)++internal/logship/ (new package, all forwarder code)+├── shipper.go (Axiom HTTP client + batcher + drop-oldest)+├── varlog.go (fsnotify tail of /var/log/**)+├── tee.go (io.Writer adapter for exec output)+└── shipper_test.go (unit tests)++internal/agent/ (in-VM agent server)+├── server.go (add logshipCfg + shipper handle)+├── logship.go (new: ConfigureLogship handler)+└── exec.go (existing — wrap pipes with tee in Phase 1)++internal/config/+└── config.go (add AxiomIngestToken + AxiomDataset)++internal/api/+├── router.go (one new line: register sandbox_logs route)+└── sandbox_logs.go (new: SSE handler + APL query builder)++internal/worker/+└── grpc_server.go (call ConfigureLogship after sandbox create)++web/src/pages/SessionDetail.tsx (add Logs tab)+```++No new tables in OC's Postgres. **One** new RPC in `agent.proto`+(additive — `ConfigureLogship` for config delivery; log bytes never+flow over this channel, only configuration). The forwarder is a+pure addition to the agent binary; the read API is a single new+HTTP handler; the UI gain is one tab.++## Pre-flight (do once, before any phase)++1. Confirm the design PR (#226) is approved/merged or that the team+ is OK with implementation proceeding off the draft.+2. Provision Axiom workspace + dataset:+ - Decide: shared-with-agentbox workspace, or new OC-only workspace?+ **Default: new workspace.** Agentbox is a different product+ with different retention/cost tradeoffs and shouldn't share+ blast radius.+ - Create dataset `oc-sandbox-logs` (default 30-day retention).+ - Create one **ingest-only** API token, scoped to the dataset.+ Note this is the ingest token that goes into every worker.+ - Create one **read-only** API token, scoped to the dataset.+ Note this is the query token that goes into the OC control+ plane secret store.+3. Add three secrets to OC deploy plumbing+ ([`deploy/server.env.example`](../../deploy/server.env.example)+ pattern, but actually wired through Azure Key Vault per the+ existing convention):+ - `AXIOM_INGEST_TOKEN` (workers need this)+ - `AXIOM_DATASET` (= `oc-sandbox-logs`)+ - `AXIOM_QUERY_TOKEN` (control plane needs this)++Phase 0 (next section) is the engineering work that consumes these.++---++## Phase 0 — config + new RPC plumbing (no behaviour change)++Goal: token reaches the worker process, `ConfigureLogship` RPC is+defined and wired through worker→agent, and the agent stores the+config in memory. **No actual shipping yet** — Phase 1 introduces+the forwarder that consumes the config.++### 0.1 Why a new RPC (and not env injection)++Initial assumption was "inject env vars at sandbox boot via the+existing mechanism." Verified false:++- The agent's own `os.Environ()` at PID 1 startup is minimal —+ only `PATH` is set explicitly in+ [`cmd/agent/main.go:26`](../../cmd/agent/main.go).+- The existing `SetEnvs` RPC+ ([`proto/agent/agent.proto:78-79`](../../proto/agent/agent.proto))+ stores envs in agent memory **for user commands only**+ (injected into `Exec`/`ExecStream`); it does not modify the+ agent's own process env.+- Implementations live in `internal/agent/server.go` and+ `internal/agent/exec.go:58-66, 88-96` — they append the stored+ envs to each user `cmd.Env`, never to the agent itself.++So the cleanest fix is one new RPC that the worker calls right+after VM boot. Additive proto change, allowed under the agent.proto+stability contract (`proto/agent/agent.proto:11-34`).++### 0.2 Worker config++Add two fields to OC's `Config` struct+([`internal/config/config.go:140`](../../internal/config/config.go)),+near the existing external-service config (Segment / Stripe):++```go+// Axiom — log shipping for sandbox session logs.+// Empty token = log shipping disabled (kill-switch).+AxiomIngestToken string+AxiomDataset string+```++In `Load()` (around line 228, near `SegmentWriteKey`):++```go+AxiomIngestToken: os.Getenv("AXIOM_INGEST_TOKEN"),+AxiomDataset: envOrDefault("AXIOM_DATASET", "oc-sandbox-logs"),+```++### 0.3 New proto RPC++Add to [`proto/agent/agent.proto`](../../proto/agent/agent.proto)+(near the `SetEnvs` RPC for adjacency, since they're conceptually+related):++```proto+// ConfigureLogship sets log-shipping configuration. Worker calls+// this immediately after VM boot, before any user-facing operations.+// If never called, the forwarder stays dormant — this is the+// kill-switch (worker doesn't call when ingest_token is unset).+rpc ConfigureLogship(ConfigureLogshipRequest) returns (ConfigureLogshipResponse);+```++```proto+// --- Logship ---++message ConfigureLogshipRequest {+ string ingest_token = 1;+ string dataset = 2;+ string sandbox_id = 3;+ string org_id = 4;+}++message ConfigureLogshipResponse {}+```++Regenerate via the existing proto-gen pipeline (likely a `make+proto` or equivalent — verify in the Makefile / scripts before+running).++### 0.4 Agent-side handler++Add to `internal/agent/server.go` (or a new `logship.go` in the+same package) a handler that stores the config and exposes it to+the forwarder:++```go+type LogshipConfig struct {+ IngestToken string+ Dataset string+ SandboxID string+ OrgID string+}++func (s *Server) ConfigureLogship(ctx context.Context, req *pb.ConfigureLogshipRequest) (*pb.ConfigureLogshipResponse, error) {+ s.logshipMu.Lock()+ s.logshipCfg = LogshipConfig{+ IngestToken: req.IngestToken,+ Dataset: req.Dataset,+ SandboxID: req.SandboxId,+ OrgID: req.OrgId,+ }+ s.logshipMu.Unlock()++ // Phase 1 will: signal the forwarder goroutine that config is ready.+ // Phase 0 just stores the config.++ return &pb.ConfigureLogshipResponse{}, nil+}+```++Add `logshipMu sync.Mutex` and `logshipCfg LogshipConfig` fields to+the server struct.++### 0.5 Worker calls `ConfigureLogship` at sandbox boot++In `internal/worker/grpc_server.go`, in `CreateSandbox` after `sb,+err := s.manager.Create(ctx, cfg)` succeeds (around line 224 — verify+before editing), add:++```go+if s.cfg.AxiomIngestToken != "" {+ orgID, _ := s.store.GetSandboxOrgID(ctx, sb.ID)+ if err := s.callConfigureLogship(ctx, sb.ID, orgID); err != nil {+ // Don't fail sandbox create on a logship config failure —+ // shipping just stays dormant for this sandbox. Log loudly.+ log.Printf("grpc: ConfigureLogship for %s failed: %v", sb.ID, err)+ }+}+```++`callConfigureLogship` opens a (probably-cached) gRPC connection to+the agent inside the sandbox and calls the new RPC. The exact+plumbing follows whatever pattern the manager already uses for+agent RPCs (manager exposes an `agent client` per sandbox; reuse).++Same insertion in the `ForkFromCheckpoint` paths (lines ~169 and+~191) — restored sandboxes also need their forwarder configured.++### 0.6 Verify++Boot a dev sandbox with `AXIOM_INGEST_TOKEN=test-token` set on the+worker. Inside the sandbox, no env vars appear yet (correct — that+was the old design). Instead:++- Check the worker log shows `ConfigureLogship for <sb_id>` did not+ fail.+- Add temporary debug logging in the agent's `ConfigureLogship`+ handler to confirm it received the call with the right values.+- Remove the debug logging before commit.++### 0.7 Verification checklist++- [ ] Config struct has `AxiomIngestToken` and `AxiomDataset`+ fields, populated from env in `Load()`+- [ ] `proto/agent/agent.proto` has `ConfigureLogship` RPC and+ `ConfigureLogshipRequest` / `ConfigureLogshipResponse`+ messages with the right field numbers+- [ ] Generated proto code committed (`agent.pb.go` /+ `agent_grpc.pb.go`)+- [ ] Agent server handles `ConfigureLogship` and stores the+ config in `s.logshipCfg`+- [ ] Worker calls `ConfigureLogship` when token is set, both in+ fresh-create and fork-from-checkpoint paths+- [ ] Worker skips the call when token is unset (kill-switch works)+- [ ] Worker tolerates a `ConfigureLogship` failure (logs loudly,+ sandbox still boots successfully)+- [ ] No regression in existing sandbox boot path+- [ ] Three secrets visible in deploy templates / vault config++---++## Phase 1 — in-guest forwarder++Goal: every line written to `/var/log/**` and every line of stdout/+stderr produced by `Exec`/`ExecStream`/`ExecSessionAttach` lands in+Axiom under the schema in the design doc.++### 1.1 Package layout++`internal/logship/`:++- **`shipper.go`** — owns the Axiom HTTP client, the in-memory+ ring buffer (drop-oldest), and the batch flusher.+- **`varlog.go`** — fsnotify-based tail of `/var/log/**`.+- **`tee.go`** — `io.Writer` that adapts a stream of bytes from+ exec handlers into line-segmented events.+- **`shipper_test.go`** — unit tests, especially for the tee+ line-buffering and the drop-oldest ring.++### 1.2 Core types++```go+package logship++type Source string++const (+ SourceVarLog Source = "var_log"+ SourceExecStdout Source = "exec_stdout"+ SourceExecStderr Source = "exec_stderr"+ SourceAgent Source = "agent"+)++type Event struct {+ Time time.Time `json:"_time"`+ SandboxID string `json:"sandbox_id"`+ OrgID string `json:"org_id"`+ Source Source `json:"source"`+ Line string `json:"line"`++ // optional, depending on source:+ Path string `json:"path,omitempty"` // var_log+ ExecID string `json:"exec_id,omitempty"` // exec_*+ Command string `json:"command,omitempty"` // exec_*+ Argv []string `json:"argv,omitempty"` // exec_*+ ExitCode *int `json:"exit_code,omitempty"` // exec_*, set on EOF only+}++type Shipper struct {+ cfg Config+ in chan Event // bounded; drop-oldest when full+ closed atomic.Bool+}++type Config struct {+ IngestToken string+ Dataset string+ SandboxID string+ OrgID string+ BatchSize int // default 100+ FlushEvery time.Duration // default 200ms+ BufferSize int // default 10_000+ HTTPTimeout time.Duration // default 10s+}+```++### 1.3 Drop-oldest ring++Exact behaviour:++```go+func (s *Shipper) Send(ev Event) {+ if s.closed.Load() { return }+ select {+ case s.in <- ev:+ // delivered+ default:+ // buffer full — drop the oldest, retry once+ select {+ case <-s.in: // discard one old event+ atomic.AddUint64(&s.droppedTotal, 1)+ default:+ }+ select {+ case s.in <- ev:+ default:+ atomic.AddUint64(&s.droppedTotal, 1)+ }+ }+}+```++Every 30s the shipper synthesises a `source: "agent"` event with+`line: "logship: dropped N events since last report"` if N > 0,+and resets the counter. That way the UI sees the dropped count+without us building a separate metric pipeline.++### 1.4 Batch flusher++Standard ticker-or-batch-full pattern, modeled on+agentbox's `log-shipper/main.go:60-108` (in our local agentbox-poc+workspace):++```go+func (s *Shipper) run(ctx context.Context) {+ var batch []Event+ flush := func() {+ if len(batch) == 0 { return }+ s.post(ctx, batch)+ batch = batch[:0]+ }+ tick := time.NewTicker(s.cfg.FlushEvery)+ defer tick.Stop()+ for {+ select {+ case <-ctx.Done():+ flush()+ return+ case ev := <-s.in:+ batch = append(batch, ev)+ if len(batch) >= s.cfg.BatchSize {+ flush()+ }+ case <-tick.C:+ flush()+ }+ }+}+```++`post` does an HTTPS POST to+`https://api.axiom.co/v1/datasets/{dataset}/ingest` with+`Authorization: Bearer {token}`, JSON body of the batch slice. On+non-2xx, retry up to 30s of backoff (250ms → 500ms → 1s → 2s → 5s+caps), then drop the batch and emit a counter event. **Don't block+ingestion** while a POST is in flight — the loop should keep+draining `s.in` while a separate goroutine handles the POST.+Easiest shape: flusher pushes batches to a second buffered channel+that a small worker pool drains.++### 1.5 `/var/log` tail++```go+type VarLogTailer struct {+ shipper *Shipper+ root string // "/var/log"+}++// On start: walk root, open every regular file at offset = file end+// (we don't backfill historical content), register fsnotify on root+// (recursive). On WRITE event for a tracked file: read appended+// bytes, split into lines, Send to shipper. On CREATE: start+// tracking. On RENAME (rotation): close current fd, the new file+// will trigger CREATE.+```++Edge cases:++- Files truncated in place (rare, some loggers do this): the read+ position becomes invalid. Handle by stat'ing on each read — if+ `size < lastOffset`, reset `lastOffset = 0`.+- Binary files in `/var/log` (unlikely but possible — `wtmp`,+ `btmp`): skip files we can't decode as UTF-8 (or where the first+ N bytes contain NUL). Decision: skip files whose name matches+ `(wtmp|btmp|lastlog|*.gz|*.[0-9])`. Compressed rotated logs+ don't get tailed.+- Nested directories: recursive watch. Some apps log to+ `/var/log/myapp/output.log`. Use `filepath.Walk` once on start;+ fsnotify recursive isn't built in but a small directory watcher+ on top of `IN_CREATE` for new dirs is straightforward.++### 1.6 Exec tee++The tee point is the exec handlers in the agent. Today they look+roughly (verify exact shape in+[`cmd/agent/main.go`](../../cmd/agent/main.go) before+editing):++```go+func (s *agentServer) ExecStream(req *pb.ExecRequest, stream pb.SandboxAgent_ExecStreamServer) error {+ cmd := exec.Command(...)+ stdout, _ := cmd.StdoutPipe()+ stderr, _ := cmd.StderrPipe()+ cmd.Start()+ // pump stdout/stderr into stream chunks ...+}+```++Insertion: wrap the pipes with `io.MultiWriter`-style tees that+also feed a per-exec `*logship.LineWriter`:++```go+execID := ulid.Make().String()+cmdName, argv := req.Command, req.Args+stdoutTee := logship.NewLineWriter(s.shipper, logship.SourceExecStdout,+ execID, cmdName, argv)+stderrTee := logship.NewLineWriter(s.shipper, logship.SourceExecStderr,+ execID, cmdName, argv)++stdoutR := io.TeeReader(stdout, stdoutTee)+stderrR := io.TeeReader(stderr, stderrTee)++// pump stdoutR/stderrR into stream chunks (existing logic) ...++// after cmd.Wait(), emit final EOF event with exit_code+exitCode := cmd.ProcessState.ExitCode()+stdoutTee.Close(exitCode) // emits one final event with the code+stderrTee.Close(exitCode)+```++`LineWriter` line-buffers writes (split on `\n`, hold a partial+last line until next write or Close). On `Close(exitCode)`, flush+any partial line and emit one synthetic event with `exit_code`+set.++The same wrapper applies to `Exec` (no streaming — just operate on+the buffered stdout/stderr after `cmd.Run()`) and to+`ExecSessionAttach` (wraps the session-internal pty/pipe; needs+care because exec sessions can outlive a single attach call).++### 1.7 Wiring into agent main and the ConfigureLogship handler++The shipper is created up-front but **dormant** — it doesn't start+shipping until `ConfigureLogship` arrives from the worker.++```go+// cmd/agent/main.go (sketch)++func main() {+ // ... existing init++ shipper := logship.New() // dormant; no token yet+ go shipper.Run(ctx) // run loop is a no-op until Activate is called++ tailer := logship.NewVarLogTailer(shipper, "/var/log")+ go tailer.Run(ctx) // tails always; events queue but don't ship++ srv := newAgentServer(shipper)+ // ... existing serve loop (existing flow registers the new+ // ConfigureLogship handler alongside the rest)+}+```++The agent's `ConfigureLogship` handler (added in Phase 0; activated+in Phase 1) calls `shipper.Activate(cfg)`:++```go+// internal/agent/logship.go+func (s *Server) ConfigureLogship(ctx context.Context, req *pb.ConfigureLogshipRequest) (*pb.ConfigureLogshipResponse, error) {+ if req.IngestToken == "" {+ return &pb.ConfigureLogshipResponse{}, nil // kill-switch+ }+ s.shipper.Activate(logship.Config{+ IngestToken: req.IngestToken,+ Dataset: req.Dataset,+ SandboxID: req.SandboxId,+ OrgID: req.OrgId,+ })+ return &pb.ConfigureLogshipResponse{}, nil+}+```++Why dormant-then-activate (vs. lazy-create-on-first-Configure):++- The `/var/log` tailer wants to start as early as possible (catch+ appends from supervisord, OS init scripts, etc.). Creating it+ only after `ConfigureLogship` arrives means we miss the boot+ window entirely.+- Pre-Activate, `shipper.Send(ev)` queues into the bounded ring+ exactly as it would otherwise; the run loop just doesn't POST+ yet. Once Activate fires, the buffered events get flushed+ with the worker-supplied `sandbox_id` / `org_id` populated+ on each event at flush time (not at Send time).+- If Activate is never called (kill-switch case), the ring drops+ oldest indefinitely. Negligible memory cost since `/var/log`+ on an idle sandbox is quiet.++### 1.8 Verification++End-to-end check on a dev worker pointing at a real (cheap) Axiom+dataset:++1. Boot a sandbox with all four env vars set.+2. From the host: `oc exec <sbx> -- echo "hello world"`.+3. Query Axiom:+ ```+ ['oc-sandbox-logs']+ | where sandbox_id == "<sbx_id>" and source == "exec_stdout"+ | sort by _time desc+ | limit 5+ ```+ Expect to see one row with `line: "hello world"` and the next+ row with `line: ""` and `exit_code: 0`.+4. Inside the sandbox: `echo "from inside" >> /var/log/my.log`.+5. Query Axiom for `source == "var_log" and path == "/var/log/my.log"`.+ Expect one row.+6. Inside the sandbox: `seq 1 100000 | tee /tmp/big.log`.+7. Verify the dropped-events counter event eventually shows up+ (or doesn't, if the buffer keeps up — both are valid; we want+ to confirm the path works).++### 1.9 Verification checklist++- [ ] `logship` package builds and unit tests pass+- [ ] LineWriter handles partial-line writes correctly (no+ duplicates, no losses)+- [ ] Drop-oldest ring confirmed under synthetic flood test+- [ ] `/var/log` tail picks up appends to existing files+- [ ] `/var/log` tail picks up newly created files+- [ ] `/var/log` tail handles rotation (file moved out, new file+ created with same name)+- [ ] Exec stdout reaches Axiom with correct `exec_id` and `command`+- [ ] Exit code appears on the synthetic EOF event for an exec+- [ ] Killswitch works: agent runs cleanly with `AXIOM_INGEST_TOKEN`+ unset, no panics, no goroutine leaks+- [ ] Existing exec contract unchanged: same stdout/stderr/exit_code+ on the gRPC return path++---++## Phase 2 — read API++Goal: `GET /api/sandboxes/:sandboxId/logs` returns historical batch++ live tail via SSE, with auth and a control-plane-side query token.++### 2.1 Files++- New: `internal/api/sandbox_logs.go` — handler + APL query builder+- Modify: `internal/api/router.go` — register one new route++### 2.2 Handler skeleton++```go+package api++func (s *Server) sandboxLogs(c echo.Context) error {+ orgID := auth.GetOrgID(c)+ sandboxID := c.Param("sandboxId")++ // Existing pattern: verify the sandbox is in the caller's org.+ sb, err := s.db.GetSandbox(c.Request().Context(), sandboxID)+ if err != nil { return echo.ErrNotFound }+ if sb.OrgID != orgID { return echo.ErrNotFound }++ q := buildAPL(sandboxID, c.QueryParams())++ // SSE setup+ c.Response().Header().Set("Content-Type", "text/event-stream")+ c.Response().Header().Set("Cache-Control", "no-cache")+ c.Response().Header().Set("Connection", "keep-alive")+ c.Response().WriteHeader(http.StatusOK)+ flusher := c.Response().Writer.(http.Flusher)++ // Initial historical batch+ rows, err := axiomQuery(ctx, q.historical())+ if err != nil { return err }+ for _, r := range rows {+ writeSSE(c.Response(), r)+ flusher.Flush()+ }++ // Live tail loop (only if `tail=true`, default true)+ if q.tail {+ lastTime := rows[len(rows)-1].Time+ ticker := time.NewTicker(1 * time.Second)+ defer ticker.Stop()+ for {+ select {+ case <-c.Request().Context().Done():+ return nil+ case <-ticker.C:+ newRows, _ := axiomQuery(ctx, q.tailSince(lastTime))+ for _, r := range newRows {+ writeSSE(c.Response(), r)+ flusher.Flush()+ lastTime = r.Time+ }+ // SSE keepalive every 15s+ if time.Since(lastFlush) > 15*time.Second {+ fmt.Fprint(c.Response(), ": keepalive\n\n")+ flusher.Flush()+ }+ }+ }+ }+ return nil+}+```++### 2.3 APL query builder++```go+type aplQuery struct {+ sandboxID string+ since time.Time+ until time.Time+ text string // free-text search (escaped)+ sources []string // filter by source+ limit int+ tail bool+}++func buildAPL(sandboxID string, qs url.Values) aplQuery {+ // parse query params; defaults:+ // tail=true, since=sandbox.created_at, until=now, limit=1000+ // text="", sources=[] (no filter)+}++func (q aplQuery) historical() string {+ var b strings.Builder+ fmt.Fprintf(&b, "['oc-sandbox-logs']\n")+ fmt.Fprintf(&b, " | where sandbox_id == %q\n", q.sandboxID)+ fmt.Fprintf(&b, " | where _event_source startswith \"worker-\"\n")+ if !q.since.IsZero() {+ fmt.Fprintf(&b, " | where _time >= datetime(%q)\n", q.since.Format(time.RFC3339Nano))+ }+ if !q.until.IsZero() {+ fmt.Fprintf(&b, " | where _time <= datetime(%q)\n", q.until.Format(time.RFC3339Nano))+ }+ if q.text != "" {+ fmt.Fprintf(&b, " | where line contains %q\n", q.text)+ }+ if len(q.sources) > 0 {+ // build | where source in ('a','b')+ }+ fmt.Fprintf(&b, " | sort by _time asc\n")+ fmt.Fprintf(&b, " | limit %d\n", q.limit)+ return b.String()+}+```++**Important:** all string interpolation uses `%q` (Go's quoted+string). APL injection isn't a credential-leak risk (the token is+read-only and dataset-scoped), but it could let a user craft a+query that returns *another sandbox's* events by overriding the+`sandbox_id` filter. The `%q` rules combined with the `where+sandbox_id == "..."` first-line filter should be airtight, but+write a unit test that feeds malicious `?q=` values and confirms+the resulting APL still has the sandbox filter.++### 2.4 Axiom client++Tiny package (could live in `internal/axiom/` or stay inline in+`sandbox_logs.go` for v1):++```go+func axiomQuery(ctx context.Context, apl string) ([]Event, error) {+ body, _ := json.Marshal(map[string]any{+ "apl": apl,+ "startTime": ..., // pulled from APL; Axiom requires both+ "endTime": ...,+ })+ req, _ := http.NewRequestWithContext(ctx, "POST",+ "https://api.axiom.co/v1/datasets/_apl/query",+ bytes.NewReader(body))+ req.Header.Set("Authorization", "Bearer " + cfg.AxiomQueryToken)+ req.Header.Set("Content-Type", "application/json")+ resp, err := httpClient.Do(req)+ // parse resp.matches[].data into []Event+}+```++The Axiom APL query endpoint is `/v1/datasets/_apl/query` (note+`_apl`, not the dataset name — the dataset is referenced inside+the APL string itself). Confirm exact shape against current Axiom+docs at implementation time.++### 2.5 Router wiring++In `internal/api/router.go`, alongside other dashboard routes:++```go+e.GET("/api/sandboxes/:sandboxId/logs", s.sandboxLogs,+ auth.PGAPIKeyMiddleware(s.db))+```++Use the same auth middleware that protects the existing dashboard+sandbox routes.++### 2.6 Verification checklist++- [ ] `GET /api/sandboxes/:id/logs` returns 404 for sandbox not+ in caller's org+- [ ] Returns 200 + SSE for own sandbox+- [ ] Initial batch contains historical events (verified against+ direct Axiom query)+- [ ] Live tail emits new events within ~2s of ingest+- [ ] `?q=foo` filters server-side+- [ ] `?source=exec_stdout` filters server-side+- [ ] `?tail=false` returns batch and closes+- [ ] APL injection unit test passes (malicious `q` cannot bypass+ sandbox-id filter)+- [ ] Keepalive comments arrive every 15s on idle streams++---++## Phase 3 — UI Logs tab++Goal: `web/src/pages/SessionDetail.tsx` gains a Logs tab next to the+existing Terminal button. Live tail by default; search box; source+filter chips; time-range picker.++### 3.1 Files++- Modify: `web/src/pages/SessionDetail.tsx` (add tab)+- New: `web/src/components/LogsTab.tsx` (the tab body)+- Possibly new: `web/src/components/LogStreamView.tsx` (the+ virtualised list — could be inline if small)+- Modify: `web/src/api/client.ts` (one new method)++### 3.2 API client++```ts+// web/src/api/client.ts+export function streamSandboxLogs(+ sandboxId: string,+ opts: { tail?: boolean; q?: string; source?: string; since?: string }+): EventSource {+ const url = new URL(`/api/sandboxes/${sandboxId}/logs`, location.origin);+ if (opts.tail !== undefined) url.searchParams.set("tail", String(opts.tail));+ if (opts.q) url.searchParams.set("q", opts.q);+ if (opts.source) url.searchParams.set("source", opts.source);+ if (opts.since) url.searchParams.set("since", opts.since);+ return new EventSource(url.toString());+}+```++### 3.3 Component sketch++```tsx+// web/src/components/LogsTab.tsx+export function LogsTab({ sandboxId }: { sandboxId: string }) {+ const [events, setEvents] = useState<LogEvent[]>([]);+ const [query, setQuery] = useState("");+ const [source, setSource] = useState<string | undefined>();+ const [paused, setPaused] = useState(false);++ const debouncedQuery = useDebounce(query, 200);++ useEffect(() => {+ if (paused) return;+ const es = streamSandboxLogs(sandboxId, {+ q: debouncedQuery, source, tail: true,+ });+ setEvents([]); // clear on filter change+ es.onmessage = e => {+ const ev = JSON.parse(e.data) as LogEvent;+ setEvents(prev => [...prev, ev]);+ };+ return () => es.close();+ }, [sandboxId, debouncedQuery, source, paused]);++ return (+ <div className="logs-tab">+ <header>+ <SearchBox value={query} onChange={setQuery} />+ <SourceFilter value={source} onChange={setSource} />+ <PauseToggle value={paused} onToggle={() => setPaused(!paused)} />+ </header>+ <LogStreamView events={events} />+ </div>+ );+}+```++### 3.4 Stream view++Virtualised list (use `react-window` if not already a dep —+otherwise lift the same approach `AgentDetail.tsx` uses for its+existing Logs tab pattern). Each row:++- Time (relative or absolute, toggle)+- Source chip (color-coded: stdout neutral, stderr red-tinged,+ var_log gray, agent purple)+- Line content (monospace, truncated with click-to-expand for long+ lines)+- For `exec_*` events: small badge with truncated `command` and a+ link/click that scrolls to the matching `exec_id` window++Auto-scroll-to-bottom unless the user scrolls up. Standard pattern:+track `userIsAtBottom` state, only auto-scroll when true.++### 3.5 Verification checklist++- [ ] Logs tab appears in SessionDetail next to Terminal+- [ ] Live events arrive without page refresh+- [ ] Search filters server-side (verify Axiom query in network tab)+- [ ] Source filter chips work+- [ ] Pause/resume freezes the stream client-side+- [ ] Page doesn't OOM after 30 min of streaming (virtualised list+ working)+- [ ] EventSource reconnects on transient network blips++---++## Phase 4 — turn it on++Once phases 0-3 are reviewed and merged:++1. Set the three Axiom secrets in prod's vault.+2. Deploy worker (picks up `AXIOM_INGEST_TOKEN`).+3. Existing sandboxes don't ship — they have the old agent binary+ without the forwarder. **Only sandboxes created after the+ worker deploy** will start shipping. This is fine and expected.+4. Watch for one week:+ - Axiom ingest volume per day+ - Axiom query latency p50 / p95+ - Any errors in the agent forwarder log+ - Any user-reported issues with the Logs tab+5. After one week, decide on:+ - Rate cap (likely 1MB/s ingest per sandbox, but informed by+ observed volumes)+ - Retention (whatever makes cost sense)+ - Per-org opt-out (if any customer asks for it)+ - Whether to extend ingest-token rotation discipline++## Open questions / decisions still pending++These are not blocking phases 0-3 but should be answered before+phase 4 broad turn-on:++- **Cost model.** Axiom charges per GB ingested. Need a back-of-+ envelope from the GB-hours data we already have to predict+ monthly Axiom bill at current sandbox volume. If it's >$X/month+ (decide threshold), rate-cap before turning on.+- **Retention default.** Stick with Axiom's default for v1; revisit+ once we see costs.+- **What about sandboxes that run for weeks/months?** The forwarder+ is in-memory; we never spool to disk. Long-lived sandboxes+ with bursty activity should be fine. Long-lived sandboxes with+ *steady high* output volume could mask drops if the user only+ occasionally checks the Logs tab. Acceptable for v1.+- **Defence-in-depth on `_event_source`.** Design doc proposes+ filtering on `_event_source startswith "worker-"` server-side+ to defeat trivial spoofing. Need to confirm that Axiom's `_event_source`+ field is indeed reliable / whether we need to use+ `_ingester` or a different metadata field. Verify at phase 1 time.+- **Should we capture egress proxy access logs?** The secrets+ proxy at `internal/secretsproxy/proxy.go` already logs every+ outbound request (verify). Teeing that to Axiom under+ `source: "egress_proxy"` would surface the highest-leverage+ failure mode (network errors that look like app bugs). Out of v1+ scope but a strong tier-2 add.+- **Should we capture user-launched ad-hoc processes?** Not via+ this design. The auditd-based process-watcher I sketched in+ prior conversation is a separate tier-3 enhancement; scope it+ separately if/when there's demand.++## Verification: end-to-end++Once all four phases land, the full test:++1. Boot a fresh sandbox.+2. Open the dashboard → Sessions → that sandbox → Logs tab.+3. From the SDK or CLI, run a few execs:+ `echo "hello"; ls -la /tmp; curl -sS https://example.com`.+4. Inside the sandbox, write to `/var/log/test.log`.+5. Within ~2s, all four lines should appear in the Logs tab+ in the right order with the right source colours.+6. Type "hello" into the search box; only the first row remains.+7. Clear search; live tail resumes.+8. Click the `curl` row; tab scrolls to the EOF event showing+ `exit_code: 0`.++If all of that works, we're done with v1 and can start the+phase-4 turn-on watch.++## Status log (fill in as we go)++- *2026-05-05* — design doc merged-pending (PR #226 draft).+ Implementation plan written. No code changes yet. Phase 0 is+ next.+- *2026-05-05* — Phase 0 shipped (`f49de82`): config + ConfigureLogship+ RPC plumbing. No behaviour change yet. Mid-implementation pivot:+ the design's "existing env-injection mechanism" assumption was+ wrong — `SetEnvs` is for user commands, not the agent process —+ so we added one new RPC instead. Both docs updated.+- *2026-05-05* — Phase 1 shipped (`9d0804b`): in-VM forwarder ++ exec tee. Package moved from `cmd/agent/internal/logship/` to+ `internal/logship/` because of Go's `internal/` visibility rule+ (the original location couldn't be imported by `internal/agent/`,+ which we need). Unit tests for LineWriter / drop-oldest / pre-+ Activate hold all pass.+- *2026-05-05* — Phase 2 shipped: read API at+ `GET /api/sandboxes/:id/logs` (SSE). Adds `AxiomQueryToken` to+ config (server-only; never reaches the browser). Auth via+ existing dashboard middleware + `GetSandboxSessionInOrg` for+ org ownership. APL builder pins `sandbox_id == :id` as the first+ predicate (security-load-bearing — covered by unit test). Live+ tail polls Axiom every 1s with a moving `_time` cursor; SSE+ keepalive every 15s. Phase 3 (UI tab) is next.+- *2026-05-05* — Phase 2 route moved: was on the `api` group+ (`/api/sandboxes/:id/logs`, X-API-Key auth) but the dashboard+ uses cookie auth via `/api/dashboard/sessions/:sandboxId/...`.+ Browser EventSource can't auth there. Moved to+ `dash.GET("/sessions/:sandboxId/logs", s.getSandboxLogs)`. SDK+ consumers can be added later as a separate route if asked.+- *2026-05-05* — Phase 3 shipped: UI Logs panel on+ `web/src/pages/SessionDetail.tsx`. New `Logs` button next to+ `Terminal` toggles a `<LogsPanel>` (new component at+ `web/src/components/LogsPanel.tsx`). EventSource via+ `streamSessionLogs` in `web/src/api/client.ts`; source-color-+ coded rows; debounced search re-opens the SSE with `?q=`;+ source filter chips re-open with `?source=`; pause toggle is+ client-side (stream keeps running); auto-scroll to bottom+ unless the user scrolled up; visible-event cap of 3000 to+ bound memory. Synthetic exec EOF events render as "✓ exited 0"+ / "✗ exited 1" rows inline. PTY content remains excluded from+ this view — different consent surface (per design doc).+- *2026-05-05* — first end-to-end on EC2 dev host caught three+ Axiom integration bugs, fixed in `0da0bcc`: (1) Axiom's per-dataset+ `/query` endpoint requires `startTime` + `endTime` in the body —+ earlier code only sent `apl` and got a 422; (2) the URL was+ `/v1/datasets/_apl/query?format=legacy` which 404'd — switched to+ `/v1/datasets/<dataset>/query` matching the agentbox precedent;+ (3) Axiom's response surfaces `_time` at the match level not+ inside `data` (event body has zero-value time). Same commit added+ the SDK-side `GET /api/sandboxes/:id/logs` (X-API-Key auth) next+ to the dashboard variant — handler reads either `:id` or+ `:sandboxId` so a single function backs both routes.+- *2026-05-05* — UI iteration: first user-driven testing surfaced+ a pile of UX issues. Captured fixes in LogsPanel.tsx:+ - **Filter-flicker.** Re-opening the SSE on every search keystroke+ or chip toggle made events disappear and reappear. Switched to+ a single SSE per sandbox with all filtering done client-side+ against the in-memory buffer. The `?q=` and `?source=` SSE+ params still exist server-side but the UI doesn't currently use+ them.+ - **Filter semantics inverted** from "additive (show only)" to+ "subtractive (hide selected)" — matches Datadog / Cypress /+ typical log-viewer mental model. Default = all four sources+ visible; click a chip to hide that source.+ - **Chip styling** collapsed from tri-state to two clear states.+ ON uses an 18% color-mix tint (not a full solid fill — too+ bright when four chips are on by default); OFF is transparent+ + dim.+ - **Color palette** — `var/log` moved from emerald to amber so it+ doesn't clash with the emerald used for `✓ exited 0` rows.+ - **Row left-border** — each row gets a 3px colored left bar+ matching its source. Previously only the small label inside the+ row carried the source color, which made the chip-to-row visual+ link weak.+ - **EOF dedup must run BEFORE the source filter.** Agent emits one+ EOF on stdout AND one on stderr per exec (closeExecLineWriters+ closes both); previously the second-pass dedup happened after+ source filtering, so hiding stdout let the suppressed stderr-EOF+ leak through and the row appeared to "switch" sources. Reordered+ to dedup-first; canonical EOF is the first one in time order+ (always stdout under current emit ordering).+ - **Search corpus** for EOF rows: `line` is empty but the rendered+ text is "command argv exited N". Search now matches against the+ rendered string, so typing "exit" or a command name finds the+ EOF rows users expect.+ - **Native search-input clear button** swapped for a custom thin+ SVG X — macOS default has a heavy blue gradient that clashes+ with the dashboard palette.+- *2026-05-05* — ExecSession tee shipped. Phase 1 originally+ covered `Exec` and `ExecStream` only, leaving the most-used path+ uncovered: every command run via `POST /api/sandboxes/:id/exec`+ goes through `ExecSession{Create,Attach}`, so users couldn't see+ their own command output. Added a per-session pair of+ `LineWriter`s (`stdoutTee`/`stderrTee`) created in+ `ExecSessionCreate` via the existing `newExecLineWriters` helper;+ the two pipe-pumping goroutines write to the LineWriter alongside+ the existing scrollback; on cmd.Wait() + pipeWg.Wait(),+ `closeExecLineWriters` flushes any partial trailing line and+ emits the synthesised EOF event with exit_code. Verified on the+ EC2 dev host: bash exec via the API now produces visible content+ rows in the dashboard. PTY content stays excluded.+- *2026-05-05* — three deploy-side gotchas caught during the e2e:+ 1. `deploy/ec2/deploy-qemu-dev.sh` writes `worker.env` /+ `server.env` but doesn't `systemctl daemon-reload`. New env+ entries (we added `AXIOM_*`) silently don't propagate to the+ running service env until daemon-reload — confirmed by reading+ `/proc/$pid/environ` and seeing AXIOM_* missing despite the+ file having them. The diagnostic log in+ `configureLogshipForSandbox` now reports+ "ConfigureLogship skipped … no axiom ingest token set on+ worker" so this misconfiguration is loud, not silent.+ 2. The deploy script only builds the rootfs ext4 image when it+ doesn't exist on disk (`if [ ! -f .../default.ext4 ]`). After+ the first deploy, freshly-built `osb-agent` binaries land at+ `/usr/local/bin/` but the rootfs keeps the old one. Need+ either an explicit `delete + redeploy` or a manual splice+ (mount loop, cp, umount). Worth either re-baking on every+ deploy or surfacing a `--rebuild-rootfs` flag.+ 3. Even with a fresh rootfs, the `golden` snapshot under+ `/data/sandboxes/golden/` caches a memory snapshot of the+ agent process from the *initial* boot. New sandboxes restore+ from that snapshot, so they keep running the snapshotted+ agent rather than the on-disk one. Invalidate by `rm -rf+ /data/sandboxes/golden && systemctl restart opensandbox-+ worker` — worker rebuilds it on first sandbox create.+- *2026-05-05* — final cleanup before review. Bug fix `217da20`:+ the SSE tail handler subtracted 1s from the cursor before the+ first poll, intending to catch events ingested in the gap+ between the historical query and tail-start. In practice Axiom+ returns stable `_time` so the overlap re-fetched events already+ in the historical batch and the UI rendered them twice (visible+ on the dev host: "hello-from-claude" + step-1/2/3 + "oops"+ duplicated; EOFs were spared because LogsPanel dedups them by+ exec_id, but content rows have no equivalent identity hook).+ Removed the overlap. Tradeoff: events ingested out-of-order+ with `_time` before the historical batch's last event are now+ missed. Until we add a server-side seen-set, no overlap.+- *2026-05-05* — merged `origin/main` (`12b4e7c`). Two clean+ conflicts in `internal/worker/grpc_server.go` where main's+ PR #222 added `s.recordInitialScaleEvent(ctx, sb.ID, cfg)` and+ this branch added `s.configureLogshipForSandbox(ctx, sb.ID)` at+ the same two return points (the warm-fork and S3-fork paths in+ `CreateSandbox`). Resolved by keeping both — they're orthogonal+ and the order doesn't matter. Other main changes pulled in:+ PR #219 (network-enabled-default), #220 (UI hide network field),+ #221 (secret-proxy allowlist-only stores) — all fixes from a+ recent customer-support investigation, fittingly merging into+ this branch alongside the feature that would have made that+ ticket self-serve.diff --git a/.github/workflows/build-worker-ami.yml b/.github/workflows/build-worker-ami.ymlindex 53a3920e..2a8e5d1c 100644--- a/.github/workflows/build-worker-ami.yml+++ b/.github/workflows/build-worker-ami.yml@@ -31,6 +31,10 @@ on:- 'deploy/azure/setup-azure-host.sh'- 'deploy/ec2/build-rootfs-docker.sh'- 'deploy/packer/**'+ # Vector configs + install.sh + KV populator are all baked into the+ # AMI by the Packer provisioner (deploy/packer/worker-ami.pkr.hcl §4.5).+ # A change here needs to roll through a new AMI to reach prod workers.+ - 'deploy/vector/**'- 'scripts/claude-agent-wrapper/**'- 'go.mod'- 'go.sum'@@ -94,6 +98,14 @@ jobs:deploy/ec2/build-rootfs-docker.sh \scripts/claude-agent-wrapper/+ - name: Package Vector configs+ # Bundled separately so Packer's file provisioner has a known+ # tarball path (it can't reliably upload an arbitrary directory).+ # install.sh on the builder extracts and installs Vector + the+ # KV-token populator into the AMI.+ run: |+ tar czf /tmp/packer-vector-ctx.tar.gz -C deploy vector+- name: Azure Loginuses: azure/login@v2with:@@ -139,6 +151,10 @@ jobs:-var "base_archive_account=${{ secrets.AZURE_STORAGE_ACCOUNT }}" \-var "base_archive_key=${{ secrets.AZURE_STORAGE_KEY }}" \-var "prev_golden_version=${{ steps.prev-golden.outputs.prev }}" \+ -var "tigris_endpoint=${{ secrets.TIGRIS_ENDPOINT }}" \+ -var "tigris_access_key_id=${{ secrets.TIGRIS_ACCESS_KEY_ID }}" \+ -var "tigris_secret_access_key=${{ secrets.TIGRIS_SECRET_ACCESS_KEY }}" \+ -var "tigris_goldens_bucket=${{ secrets.TIGRIS_GOLDENS_BUCKET }}" \deploy/packer/worker-ami.pkr.hcl | tee /tmp/packer-output.txt# Use the gallery image ID (NVMe-compatible for v7 VMs)diff --git a/.github/workflows/ci-gc.yml b/.github/workflows/ci-gc.ymlnew file mode 100644index 00000000..aea2d4cd--- /dev/null+++ b/.github/workflows/ci-gc.yml@@ -0,0 +1,39 @@+name: CI GC (stale PR stacks)++on:+ schedule:+ - cron: '0 6 * * *' # daily 06:00 UTC+ workflow_dispatch:+ inputs:+ max_age_hours:+ description: 'Tear down PR stacks older than this many hours'+ type: number+ default: 24++permissions:+ id-token: write+ contents: read++jobs:+ gc:+ runs-on: ubuntu-latest+ timeout-minutes: 30+ steps:+ - uses: actions/checkout@v4++ - name: Install SSH key+ run: |+ mkdir -p ~/.ssh+ echo "${{ secrets.OPENCOMPUTER_CI_SSH_KEY }}" > ~/.ssh/opencomputer-ci+ chmod 600 ~/.ssh/opencomputer-ci++ - uses: azure/login@v2+ with:+ client-id: ${{ secrets.AZURE_CLIENT_ID }}+ tenant-id: ${{ secrets.AZURE_TENANT_ID }}+ subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }}++ - name: GC stale PR stacks+ env:+ MAX_AGE_HOURS: ${{ inputs.max_age_hours || 24 }}+ run: ./ci/persistent/gc.shdiff --git a/.github/workflows/deploy-server.yml b/.github/workflows/deploy-server.ymlindex 7fd2f01e..15c1c909 100644--- a/.github/workflows/deploy-server.yml+++ b/.github/workflows/deploy-server.yml@@ -42,11 +42,21 @@ jobs:-o bin/opensandbox-server ./cmd/server/- name: Build web dashboard+ env:+ VITE_PUBLIC_POSTHOG_PROJECT_TOKEN: ${{ secrets.POSTHOG_PROJECT_TOKEN }}+ VITE_PUBLIC_POSTHOG_HOST: ${{ secrets.POSTHOG_HOST }}run: cd web && npm ci && npm run build- name: Package web assetsrun: tar czf bin/web-dist.tar.gz -C web dist+ - name: Package Vector configs+ # Bundle deploy/vector/ for distribution to control-plane hosts.+ # install.sh is idempotent: skips Vector install if already present,+ # always refreshes config + restarts. Workers get the same files via+ # the Packer image bake (build-worker-ami.yml).+ run: tar czf bin/vector-deploy.tar.gz -C deploy vector+- name: Azure Loginuses: azure/login@v2with:@@ -72,6 +82,14 @@ jobs:--file bin/web-dist.tar.gz \--overwrite true -o none+ az storage blob upload \+ --account-name ${{ secrets.AZURE_STORAGE_ACCOUNT }} \+ --account-key "${{ secrets.AZURE_STORAGE_KEY }}" \+ --container-name checkpoints \+ --name deploy/vector-deploy.tar.gz \+ --file bin/vector-deploy.tar.gz \+ --overwrite true -o none+echo "Artifacts uploaded to blob storage"- name: Discover control planes@@ -117,6 +135,12 @@ jobs:--container-name checkpoints --name deploy/web-dist.tar.gz \--file /tmp/web-dist.tar.gz --overwrite true -o none+ az storage blob download \+ --account-name ${{ secrets.AZURE_STORAGE_ACCOUNT }} \+ --account-key '${{ secrets.AZURE_STORAGE_KEY }}' \+ --container-name checkpoints --name deploy/vector-deploy.tar.gz \+ --file /tmp/vector-deploy.tar.gz --overwrite true -o none+# Stop, replace binary, extract frontendsystemctl stop opensandbox-serversleep 1@@ -133,6 +157,17 @@ jobs:fisystemctl start opensandbox-server++ # Install/refresh Vector + the KV token populator. install.sh+ # is idempotent (skips Vector install if already present,+ # always refreshes config + reloads). populate-vector-env+ # fetches AXIOM_PLATFORM_TOKEN from KV via the VM's managed+ # identity at every boot (and on this restart).+ mkdir -p /tmp/vector-deploy+ tar xzf /tmp/vector-deploy.tar.gz -C /tmp/vector-deploy+ bash /tmp/vector-deploy/vector/install.sh control-plane+ rm -rf /tmp/vector-deploy /tmp/vector-deploy.tar.gz+echo 'Deploy complete'" -o nonediff --git a/.github/workflows/pr-integration.yml b/.github/workflows/pr-integration.ymlnew file mode 100644index 00000000..3d514d7e--- /dev/null+++ b/.github/workflows/pr-integration.yml@@ -0,0 +1,82 @@+name: PR Integration Test++# Runs in the PR's context (not pull_request_target), so fork PRs run WITHOUT+# secrets — eliminating the standard pull_request_target exfiltration vector.+# For PRs from branches in this repo (org-member flow), the workflow does have+# secrets, so we additionally gate behind an explicit `osb-ci-approve` label+# applied by a maintainer. A companion workflow (pr-strip-approval.yml) auto-+# removes the label on each push, forcing a fresh per-SHA approval.+on:+ pull_request:+ types: [labeled]++concurrency:+ group: pr-${{ github.event.pull_request.number }}+ cancel-in-progress: true++permissions:+ id-token: write+ contents: read+ pull-requests: write++jobs:+ gate:+ # Only the osb-ci-approve label triggers CI; other labels do nothing.+ if: github.event.label.name == 'osb-ci-approve'+ runs-on: ubuntu-latest+ outputs:+ approved: ${{ steps.check.outputs.approved }}+ steps:+ - id: check+ run: echo "approved=true" >> "$GITHUB_OUTPUT"++ ci:+ needs: gate+ if: needs.gate.outputs.approved == 'true'+ runs-on: ubuntu-latest+ timeout-minutes: 45+ steps:+ - name: Checkout PR head+ uses: actions/checkout@v4+ with:+ ref: ${{ github.event.pull_request.head.sha }}++ - uses: actions/setup-go@v5+ with:+ go-version-file: go.mod++ - name: Pre-flight tests (no infra)+ run: go test -count=1 ./ci/tests/migration/...++ - name: Install SSH key+ run: |+ mkdir -p ~/.ssh+ echo "${{ secrets.OPENCOMPUTER_CI_SSH_KEY }}" > ~/.ssh/opencomputer-ci+ chmod 600 ~/.ssh/opencomputer-ci+ # Public half is derived once from the private key.+ ssh-keygen -y -f ~/.ssh/opencomputer-ci > ~/.ssh/opencomputer-ci.pub++ - uses: azure/login@v2+ with:+ client-id: ${{ secrets.AZURE_CLIENT_ID }}+ tenant-id: ${{ secrets.AZURE_TENANT_ID }}+ subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }}++ - name: Bring up PR stack (2 workers, cross-version baseline)+ id: up+ env:+ BASELINE_FROM_GALLERY: "1"+ run: |+ ./ci/pr/up.sh ${{ github.event.pull_request.number }} 2++ - name: API test suite+ env:+ OSB_TEST_SERVER_URL: ${{ steps.up.outputs.server_url }}+ OSB_TEST_API_KEY: ${{ steps.up.outputs.api_key }}+ OSB_TEST_WORKERS: ${{ steps.up.outputs.workers }}+ run: go test -count=1 -v ./ci/tests/api/...++ - name: Tear down PR stack+ if: always()+ run: |+ ./ci/pr/down.sh ${{ github.event.pull_request.number }} || truediff --git a/.github/workflows/pr-strip-approval.yml b/.github/workflows/pr-strip-approval.ymlnew file mode 100644index 00000000..7e31ab4b--- /dev/null+++ b/.github/workflows/pr-strip-approval.yml@@ -0,0 +1,23 @@+name: Strip CI Approval On Push++# Removes the osb-ci-approve label whenever a PR receives new commits, forcing+# a maintainer to re-review the new SHA before integration tests can run again.+# Pairs with pr-integration.yml, which only fires on the `labeled` event.+on:+ pull_request:+ types: [synchronize]++permissions:+ pull-requests: write++jobs:+ strip:+ runs-on: ubuntu-latest+ steps:+ - name: Remove osb-ci-approve label+ env:+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}+ run: |+ gh pr edit ${{ github.event.pull_request.number }} \+ --remove-label osb-ci-approve \+ -R ${{ github.repository }} 2>/dev/null || truediff --git a/.gitignore b/.gitignoreindex 032cf9b9..0d870b97 100644--- a/.gitignore+++ b/.gitignore@@ -65,4 +65,5 @@ delmedeploy/azure/.dev-env-state-*deploy/azure/.dev-env-secrets*!deploy/azure/.dev-env-secrets.example+deploy/azure/.dev-vector-token-*/serverdiff --git a/AGENTS.md b/AGENTS.mdindex ff82986f..6b391d2f 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -28,6 +28,9 @@ truth they come from.- `README.md` — product overview and human quick start- `Makefile` — local dev, build, test, and common run targets+- `deploy/ec2/README.md` — personal end-to-end dev host on EC2 bare metal+ (real QEMU VMs, server + worker + UI); use when in-process Makefile tiers+ aren't enough- `internal/config/config.go` — environment variables and runtime config- `proto/` — inter-tier contracts- `docs/mint.json` — docs navigation@@ -42,6 +45,35 @@ Managed-agent product behavior is mostly **not** implemented here:## Hard rules+**⚠️ PRODUCTION DATABASE IS EFFECTIVELY READ-ONLY.** This is the most+load-bearing safety rule in this repo. Any Postgres connection that reaches the+production DB — i.e. anything other than a developer's `localhost` Postgres,+including connections via the Azure bastion or using credentials sourced from+the production environment — is governed by two tiers, both stricter than+normal collaboration:++- **Modifying SQL** (`INSERT`, `UPDATE`, `DELETE` with WHERE, `COPY` into a+ table, mutating function calls, manual migrations, `cmd/migrate-prices`-style+ tools pointed at prod): requires **explicit per-statement approval** from+ the user. Show the exact statement, ask, wait. A general "yes go ahead"+ earlier in the conversation does NOT carry across to a different statement.+ Blanket approvals ("just do whatever you need") MUST NOT be accepted for+ prod writes — confirm each statement individually.++- **Destructive SQL** (`DROP`, `TRUNCATE`, schema-changing `ALTER`, unbounded+ `DELETE` / `UPDATE`, anything `CASCADE`, anything bulk-mutating that can't be+ undone with a single inverse statement, any direct write to+ `schema_migrations`): **REFUSE OUTRIGHT.** First response is always no.+ Tell the user this is the standing safety rule; require them to insist+ across multiple turns with explicit acknowledgement of what will be lost+ before any such command runs. There is no "production emergency"+ justification for shortcutting this — an emergency is exactly when wrong+ commands cause the most damage.++`localhost` Postgres on a developer machine is exempt — these tiers apply only+to production. Read-only queries (`SELECT`, `EXPLAIN`) against prod are fine+and do not require approval.+**NEVER force push.** `git push --force`, `git push -f`, and`git push --force-with-lease` are forbidden. No exceptions. Make a new commitinstead.diff --git a/README.md b/README.mdindex 545ca84c..00376685 100644--- a/README.md+++ b/README.md@@ -150,3 +150,5 @@ VMs hibernate instead of dying. State survives across sessions without manual sn## LicenseLicensed under the Apache License, Version 2.0. See [LICENSE](LICENSE) for details.++diff --git a/ci/persistent/down.sh b/ci/persistent/down.shnew file mode 100755index 00000000..b327fc01--- /dev/null+++ b/ci/persistent/down.sh@@ -0,0 +1,23 @@+#!/usr/bin/env bash+# Tear down the entire opencomputer-ci RG. Big red button — only for full reset.+# Storage account contents (compat-corpus + checkpoints) and KV secrets are+# unrecoverable after this runs (KV soft-delete retains for 90 days; storage+# is gone). Confirm before invoking.++set -euo pipefail++RG="${RG:-opencomputer-ci}"++if ! az group exists --name "$RG" 2>/dev/null | grep -q true; then+ echo "RG $RG doesn't exist; nothing to do."+ exit 0+fi++echo ">>> About to delete EVERYTHING in resource group: $RG"+echo " (KV: opencomputer-ci-kv goes into 90-day soft-delete)"+echo " (Storage: data is permanently lost)"+read -r -p "Type 'yes' to proceed: " confirm+[[ "$confirm" == "yes" ]] || { echo "aborted."; exit 1; }++az group delete -n "$RG" --yes --no-wait+echo "delete initiated (running in background, takes ~5 min to complete)."diff --git a/ci/persistent/gc.sh b/ci/persistent/gc.shnew file mode 100755index 00000000..e253a853--- /dev/null+++ b/ci/persistent/gc.sh@@ -0,0 +1,62 @@+#!/usr/bin/env bash+# Garbage-collect stale PR stacks (older than MAX_AGE_HOURS, default 24).+#+# Lists pr-*-server VMs, checks their creation time, and tears down any older+# than the threshold. Designed to run from a GitHub Actions scheduled workflow+# (daily). Safe to re-run; idempotent.+#+# Usage: ./gc.sh # default: stacks >24h old+# MAX_AGE_HOURS=4 ./gc.sh # tighter window++set -euo pipefail++RG="${RG:-opencomputer-ci}"+MAX_AGE_HOURS="${MAX_AGE_HOURS:-24}"+DOWN_SCRIPT="${DOWN_SCRIPT:-$(dirname "$0")/../pr/down.sh}"++[[ -x "$DOWN_SCRIPT" ]] || { echo "FATAL: $DOWN_SCRIPT not executable"; exit 1; }++echo ">>> scanning pr-*-server VMs in $RG (cutoff: ${MAX_AGE_HOURS}h)"++cutoff_epoch=$(($(date -u +%s) - MAX_AGE_HOURS * 3600))++# VM names don't contain whitespace, so simple word-splitting works (and is+# portable to macOS bash 3.2, which lacks mapfile).+VMS=$(az vm list -g "$RG" --query "[?starts_with(name,'pr-') && ends_with(name,'-server')].name" -o tsv)+if [[ -z "$VMS" ]]; then+ echo "no PR stacks found."+ exit 0+fi++KILLED=0+for vm in $VMS; do+ created=$(az vm show -g "$RG" -n "$vm" --query "timeCreated" -o tsv 2>/dev/null || echo "")+ if [[ -z "$created" ]]; then+ echo " $vm: no timeCreated metadata, skipping"+ continue+ fi++ # Strip fractional seconds + parse to epoch (BSD/macOS and Linux tolerant).+ ts=$(echo "$created" | sed -E 's/\.[0-9]+//; s/\+.*//')+ if date --version >/dev/null 2>&1; then+ created_epoch=$(date -u -d "$ts" +%s)+ else+ created_epoch=$(date -u -j -f "%Y-%m-%dT%H:%M:%S" "$ts" +%s)+ fi++ age_h=$(( ($(date -u +%s) - created_epoch) / 3600 ))+ pr_num=$(echo "$vm" | sed -E 's/^pr-([0-9]+)-server$/\1/')++ if [[ "$created_epoch" -lt "$cutoff_epoch" ]]; then+ echo " $vm (PR $pr_num, age=${age_h}h) — TEARING DOWN"+ if "$DOWN_SCRIPT" "$pr_num"; then+ KILLED=$((KILLED + 1))+ else+ echo " down.sh failed for PR $pr_num — continuing"+ fi+ else+ echo " $vm (PR $pr_num, age=${age_h}h) — keeping"+ fi+done++echo "DONE. tore down $KILLED stale stack(s)."diff --git a/ci/persistent/up.sh b/ci/persistent/up.shnew file mode 100755index 00000000..300bca50--- /dev/null+++ b/ci/persistent/up.sh@@ -0,0 +1,205 @@+#!/usr/bin/env bash+# Bring up the persistent layer for the opencomputer-ci test stack.+# Idempotent: safe to re-run. Existing resources are skipped or updated in place.+#+# Creates: VNet+subnets+NSGs, two managed identities, Key Vault, storage account+# (with checkpoints/ and compat-corpus/ containers), and a single B4ms VM running+# Postgres 16 + Redis 7 via systemd. Generates secrets and stores them in KV.+#+# Run once. To tear down: ./down.sh.++set -euo pipefail++RG="${RG:-opencomputer-ci}"+LOCATION="${LOCATION:-centralus}"+VNET="oc-ci-vnet"+KV="${KV:-opencomputer-ci-kv}"+STORAGE="${STORAGE:-occiblob$(openssl rand -hex 2)}" # globally unique+DATA_VM="oc-ci-data"+DATA_IDENTITY="osb-ci-data-identity"+WORKER_IDENTITY="osb-ci-worker-identity"+SSH_KEY="${SSH_KEY:-$HOME/.ssh/opencomputer-ci.pub}"++[[ -f "$SSH_KEY" ]] || { echo "FATAL: SSH key $SSH_KEY not found"; exit 1; }++ME=$(az ad signed-in-user show --query id -o tsv)+SUB=$(az account show --query id -o tsv)+echo ">>> subscription=$SUB me=$ME rg=$RG region=$LOCATION"++echo ">>> [1/9] resource group"+az group create -n "$RG" -l "$LOCATION" --tags purpose=ci -o none++echo ">>> [2/9] vnet + subnets + nsgs"+az network vnet create -g "$RG" -n "$VNET" \+ --address-prefix 10.210.0.0/16 \+ --subnet-name data --subnet-prefix 10.210.1.0/24 \+ -o none+az network vnet subnet show -g "$RG" --vnet-name "$VNET" -n compute -o none 2>/dev/null \+ || az network vnet subnet create -g "$RG" --vnet-name "$VNET" \+ -n compute --address-prefix 10.210.2.0/24 -o none++az network nsg create -g "$RG" -n oc-ci-nsg-data -o none+az network nsg rule create -g "$RG" --nsg-name oc-ci-nsg-data -n allow-pg-compute \+ --priority 100 --source-address-prefixes 10.210.2.0/24 --destination-port-ranges 5432 \+ --protocol Tcp --access Allow --direction Inbound -o none 2>/dev/null || true+az network nsg rule create -g "$RG" --nsg-name oc-ci-nsg-data -n allow-redis-compute \+ --priority 110 --source-address-prefixes 10.210.2.0/24 --destination-port-ranges 6379 \+ --protocol Tcp --access Allow --direction Inbound -o none 2>/dev/null || true+az network nsg rule create -g "$RG" --nsg-name oc-ci-nsg-data -n allow-ssh \+ --priority 200 --destination-port-ranges 22 \+ --protocol Tcp --access Allow --direction Inbound -o none 2>/dev/null || true+az network vnet subnet update -g "$RG" --vnet-name "$VNET" -n data \+ --network-security-group oc-ci-nsg-data -o none++az network nsg create -g "$RG" -n oc-ci-nsg-compute -o none+az network nsg rule create -g "$RG" --nsg-name oc-ci-nsg-compute -n allow-ssh \+ --priority 100 --destination-port-ranges 22 \+ --protocol Tcp --access Allow --direction Inbound -o none 2>/dev/null || true+az network nsg rule create -g "$RG" --nsg-name oc-ci-nsg-compute -n allow-http \+ --priority 110 --destination-port-ranges 8080 8081 9090 \+ --protocol Tcp --access Allow --direction Inbound -o none 2>/dev/null || true+az network vnet subnet update -g "$RG" --vnet-name "$VNET" -n compute \+ --network-security-group oc-ci-nsg-compute -o none++echo ">>> [3/9] managed identities"+az identity create -g "$RG" -n "$DATA_IDENTITY" -o none+az identity create -g "$RG" -n "$WORKER_IDENTITY" -o none+DATA_PRINCIPAL=$(az identity show -g "$RG" -n "$DATA_IDENTITY" --query principalId -o tsv)+WORKER_PRINCIPAL=$(az identity show -g "$RG" -n "$WORKER_IDENTITY" --query principalId -o tsv)+DATA_IDENTITY_ID=$(az identity show -g "$RG" -n "$DATA_IDENTITY" --query id -o tsv)+WORKER_IDENTITY_ID=$(az identity show -g "$RG" -n "$WORKER_IDENTITY" --query id -o tsv)++echo ">>> [4/9] key vault (RBAC mode)"+az keyvault show -n "$KV" -o none 2>/dev/null \+ || az keyvault create -g "$RG" -n "$KV" --enable-rbac-authorization true -o none+KV_SCOPE="/subscriptions/$SUB/resourceGroups/$RG/providers/Microsoft.KeyVault/vaults/$KV"++az role assignment create --assignee-object-id "$ME" --assignee-principal-type User \+ --role "Key Vault Administrator" --scope "$KV_SCOPE" -o none 2>/dev/null || true+az role assignment create --assignee-object-id "$DATA_PRINCIPAL" --assignee-principal-type ServicePrincipal \+ --role "Key Vault Secrets User" --scope "$KV_SCOPE" -o none 2>/dev/null || true+az role assignment create --assignee-object-id "$WORKER_PRINCIPAL" --assignee-principal-type ServicePrincipal \+ --role "Key Vault Secrets User" --scope "$KV_SCOPE" -o none 2>/dev/null || true++echo ">>> waiting 45s for RBAC propagation..."+sleep 45++echo ">>> [5/9] generating + storing secrets"+gen_or_keep() {+ local name="$1" gen_cmd="$2"+ if az keyvault secret show --vault-name "$KV" --name "$name" -o none 2>/dev/null; then+ echo " $name (kept)"+ else+ local val+ val=$(eval "$gen_cmd")+ az keyvault secret set --vault-name "$KV" --name "$name" --value "$val" -o none+ echo " $name (generated)"+ fi+}+gen_or_keep "pg-password" "openssl rand -base64 24 | tr -dc 'A-Za-z0-9' | head -c 32"+gen_or_keep "redis-password" "openssl rand -base64 24 | tr -dc 'A-Za-z0-9' | head -c 32"+gen_or_keep "server-api-key" "echo osb_ci_\$(openssl rand -hex 32)"+gen_or_keep "server-jwt-secret" "openssl rand -hex 32"+gen_or_keep "worker-jwt-secret" "az keyvault secret show --vault-name $KV --name server-jwt-secret --query value -o tsv"+gen_or_keep "server-secret-encryption-key" "openssl rand -hex 32"++PG_PASS=$(az keyvault secret show --vault-name "$KV" --name pg-password --query value -o tsv)+REDIS_PASS=$(az keyvault secret show --vault-name "$KV" --name redis-password --query value -o tsv)++echo ">>> [6/9] storage account + containers"+if ! az storage account show -g "$RG" -n "$STORAGE" -o none 2>/dev/null; then+ EXISTING=$(az keyvault secret show --vault-name "$KV" --name storage-account-name --query value -o tsv 2>/dev/null || echo "")+ if [[ -n "$EXISTING" ]]; then STORAGE="$EXISTING"; fi+fi+if ! az storage account show -g "$RG" -n "$STORAGE" -o none 2>/dev/null; then+ az storage account create -g "$RG" -n "$STORAGE" -l "$LOCATION" \+ --sku Standard_LRS --kind StorageV2 -o none+ az keyvault secret set --vault-name "$KV" --name storage-account-name --value "$STORAGE" -o none+fi+STORAGE_KEY=$(az storage account keys list -g "$RG" -n "$STORAGE" --query "[0].value" -o tsv)+az storage container create --account-name "$STORAGE" --account-key "$STORAGE_KEY" -n checkpoints -o none 2>/dev/null || true+az storage container create --account-name "$STORAGE" --account-key "$STORAGE_KEY" -n compat-corpus -o none 2>/dev/null || true+az keyvault secret set --vault-name "$KV" --name worker-s3-access-key --value "$STORAGE" -o none+az keyvault secret set --vault-name "$KV" --name worker-s3-secret-key --value "$STORAGE_KEY" -o none++echo ">>> [7/9] data VM cloud-init"+CLOUD_INIT=$(mktemp)+trap "rm -f $CLOUD_INIT" EXIT+cat > "$CLOUD_INIT" <<EOF+#cloud-config+package_update: true+packages:+ - postgresql-16+ - postgresql-contrib-16+ - redis-server+runcmd:+ - bash -c "echo \"listen_addresses = '*'\" >> /etc/postgresql/16/main/postgresql.conf"+ - bash -c "echo 'host all all 10.210.0.0/16 md5' >> /etc/postgresql/16/main/pg_hba.conf"+ - sudo -u postgres psql -c "ALTER USER postgres WITH PASSWORD '${PG_PASS}';"+ - sudo -u postgres psql -c "CREATE USER osbciuser WITH PASSWORD '${PG_PASS}' CREATEDB;"+ - sudo -u postgres psql -c "GRANT pg_read_all_data, pg_write_all_data TO osbciuser;"+ - sed -i 's/^bind 127.0.0.1.*/bind 0.0.0.0/' /etc/redis/redis.conf+ - sed -i 's|^# requirepass.*|requirepass ${REDIS_PASS}|' /etc/redis/redis.conf+ - sed -i 's/^protected-mode yes/protected-mode no/' /etc/redis/redis.conf+ - systemctl restart postgresql+ - systemctl restart redis-server+ - systemctl enable postgresql redis-server+EOF++echo ">>> [8/9] data VM"+if ! az vm show -g "$RG" -n "$DATA_VM" -o none 2>/dev/null; then+ az vm create -g "$RG" -n "$DATA_VM" \+ --image Ubuntu2404 \+ --size Standard_B4ms \+ --vnet-name "$VNET" --subnet data \+ --public-ip-address "${DATA_VM}-pip" \+ --public-ip-sku Standard \+ --admin-username azureuser \+ --ssh-key-values "$SSH_KEY" \+ --assign-identity "$DATA_IDENTITY_ID" \+ --custom-data "$CLOUD_INIT" \+ --os-disk-size-gb 64 \+ --nsg oc-ci-nsg-data \+ -o none+else+ echo " $DATA_VM already exists (cloud-init not re-run; rebuild with down.sh + up.sh)"+fi++DATA_VM_PIP=$(az vm show -d -g "$RG" -n "$DATA_VM" --query publicIps -o tsv)+DATA_VM_PRIVATE=$(az vm show -d -g "$RG" -n "$DATA_VM" --query privateIps -o tsv)++echo ">>> [9/9] connection strings into KV"+az keyvault secret set --vault-name "$KV" --name data-vm-private-ip --value "$DATA_VM_PRIVATE" -o none+az keyvault secret set --vault-name "$KV" --name server-database-url \+ --value "postgres://osbciuser:${PG_PASS}@${DATA_VM_PRIVATE}:5432/postgres?sslmode=disable" -o none+az keyvault secret set --vault-name "$KV" --name worker-database-url \+ --value "postgres://osbciuser:${PG_PASS}@${DATA_VM_PRIVATE}:5432/postgres?sslmode=disable" -o none+az keyvault secret set --vault-name "$KV" --name server-redis-url \+ --value "redis://default:${REDIS_PASS}@${DATA_VM_PRIVATE}:6379/0" -o none+az keyvault secret set --vault-name "$KV" --name worker-redis-url \+ --value "redis://default:${REDIS_PASS}@${DATA_VM_PRIVATE}:6379/0" -o none++cat <<DONE++================================================================+DONE. opencomputer-ci persistent layer is up.++ resource group: $RG+ region: $LOCATION+ data VM: $DATA_VM public=$DATA_VM_PIP private=$DATA_VM_PRIVATE+ key vault: $KV+ storage: $STORAGE+ data identity: $DATA_IDENTITY_ID+ worker identity: $WORKER_IDENTITY_ID++ postgres: postgres://osbciuser:***@${DATA_VM_PRIVATE}:5432/postgres+ redis: redis://default:***@${DATA_VM_PRIVATE}:6379/0++ smoke test: ./verify.sh+ ssh: ssh azureuser@${DATA_VM_PIP}+ cloud-init log: /var/log/cloud-init-output.log on the VM++ IMPORTANT: cloud-init takes ~3-4 min after VM create to finish installing+ Postgres + Redis. Run ./verify.sh after a few minutes.+================================================================+DONEdiff --git a/ci/persistent/verify.sh b/ci/persistent/verify.shnew file mode 100755index 00000000..0bca4329--- /dev/null+++ b/ci/persistent/verify.sh@@ -0,0 +1,38 @@+#!/usr/bin/env bash+# Smoke-test the persistent layer: SSH to data VM, prove Postgres + Redis are up+# and listening on the data subnet, prove KV is reachable from the worker identity.++set -euo pipefail++RG="${RG:-opencomputer-ci}"+KV="${KV:-opencomputer-ci-kv}"+DATA_VM="oc-ci-data"++DATA_VM_PIP=$(az vm show -d -g "$RG" -n "$DATA_VM" --query publicIps -o tsv)+DATA_VM_PRIVATE=$(az vm show -d -g "$RG" -n "$DATA_VM" --query privateIps -o tsv)++echo ">>> data VM: public=$DATA_VM_PIP private=$DATA_VM_PRIVATE"++PG_PASS=$(az keyvault secret show --vault-name "$KV" --name pg-password --query value -o tsv)+REDIS_PASS=$(az keyvault secret show --vault-name "$KV" --name redis-password --query value -o tsv)++echo ">>> SSH check"+ssh -i ~/.ssh/opencomputer-ci -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o ConnectTimeout=10 azureuser@"$DATA_VM_PIP" "uptime" || {+ echo "SSH failed — VM may still be cloud-init'ing. Wait 1-2 min and re-run."+ exit 1+}++echo ">>> postgres check (psql via SSH tunnel)"+ssh -i ~/.ssh/opencomputer-ci -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null azureuser@"$DATA_VM_PIP" "PGPASSWORD='$PG_PASS' psql -h localhost -U osbciuser -d postgres -c 'SELECT version();'"++echo ">>> redis check"+ssh -i ~/.ssh/opencomputer-ci -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null azureuser@"$DATA_VM_PIP" "redis-cli -a '$REDIS_PASS' ping"++echo ">>> postgres listening on 0.0.0.0:5432?"+ssh -i ~/.ssh/opencomputer-ci -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null azureuser@"$DATA_VM_PIP" "ss -tln | grep ':5432' || echo 'NOT LISTENING'"++echo ">>> redis listening on 0.0.0.0:6379?"+ssh -i ~/.ssh/opencomputer-ci -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null azureuser@"$DATA_VM_PIP" "ss -tln | grep ':6379' || echo 'NOT LISTENING'"++echo+echo "all checks passed."diff --git a/ci/pr/down.sh b/ci/pr/down.shnew file mode 100755index 00000000..832c5c58--- /dev/null+++ b/ci/pr/down.sh@@ -0,0 +1,67 @@+#!/usr/bin/env bash+# Tear down a PR's ephemeral test stack.+#+# Usage: ./down.sh <PR_NUM>+#+# Deletes: pr-<num>-* VMs (and their NICs/disks/IPs), pr-<num>-checkpoints+# storage container, and the pr_<num> Postgres database. Leaves persistent+# resources (data VM, KV, storage account) untouched.++set -euo pipefail++PR_NUM="${1:-}"+[[ -n "$PR_NUM" ]] || { echo "usage: $0 <PR_NUM>"; exit 1; }+[[ "$PR_NUM" =~ ^[0-9]+$ ]] || { echo "PR_NUM must be numeric"; exit 1; }++RG="opencomputer-ci"+KV="opencomputer-ci-kv"+SSH_KEY_PRIV="$HOME/.ssh/opencomputer-ci"+SSH_OPTS="-i $SSH_KEY_PRIV -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null"++DATA_VM_PIP=$(az vm show -d -g "$RG" -n oc-ci-data --query publicIps -o tsv 2>/dev/null || echo "")+PG_PASS=$(az keyvault secret show --vault-name "$KV" --name pg-password --query value -o tsv 2>/dev/null || echo "")+STORAGE=$(az keyvault secret show --vault-name "$KV" --name storage-account-name --query value -o tsv 2>/dev/null || echo "")+STORAGE_KEY=$(az keyvault secret show --vault-name "$KV" --name worker-s3-secret-key --query value -o tsv 2>/dev/null || echo "")++DB_NAME="pr_$PR_NUM"+CONTAINER="pr-${PR_NUM}-checkpoints"++echo ">>> [1/3] delete VMs (and their NICs/disks/IPs)"+VMS=$(az vm list -g "$RG" --query "[?starts_with(name,'pr-${PR_NUM}-')].name" -o tsv 2>/dev/null || echo "")+if [[ -z "$VMS" ]]; then+ echo " no pr-${PR_NUM}-* VMs found"+else+ for vm in $VMS; do+ echo " $vm"+ osdisk=$(az vm show -g "$RG" -n "$vm" --query "storageProfile.osDisk.name" -o tsv 2>/dev/null || echo "")+ nic_ids=$(az vm show -g "$RG" -n "$vm" --query "networkProfile.networkInterfaces[].id" -o tsv 2>/dev/null || echo "")+ pip_name="${vm}-pip"+ az vm delete -g "$RG" -n "$vm" --yes -o none+ for nic_id in $nic_ids; do+ az network nic delete --ids "$nic_id" -o none 2>/dev/null || true+ done+ # Disk deletion can race with VM deletion (Azure detach lag); retry.+ if [[ -n "$osdisk" ]]; then+ for _ in 1 2 3 4 5; do+ if az disk delete -g "$RG" -n "$osdisk" --yes -o none 2>/dev/null; then+ break+ fi+ sleep 5+ done+ fi+ az network public-ip delete -g "$RG" -n "$pip_name" -o none 2>/dev/null || true+ done+fi++echo ">>> [2/3] DROP DATABASE $DB_NAME"+if [[ -n "$DATA_VM_PIP" && -n "$PG_PASS" ]]; then+ ssh $SSH_OPTS azureuser@"$DATA_VM_PIP" \+ "PGPASSWORD='$PG_PASS' psql -h localhost -U postgres -d postgres -c \"DROP DATABASE IF EXISTS $DB_NAME WITH (FORCE);\""+fi++echo ">>> [3/3] delete container $CONTAINER"+if [[ -n "$STORAGE" && -n "$STORAGE_KEY" ]]; then+ az storage container delete --account-name "$STORAGE" --account-key "$STORAGE_KEY" -n "$CONTAINER" -o none 2>/dev/null || true+fi++echo "DONE. PR-$PR_NUM stack torn down."diff --git a/ci/pr/up.sh b/ci/pr/up.shnew file mode 100755index 00000000..18e42ac3--- /dev/null+++ b/ci/pr/up.sh@@ -0,0 +1,456 @@+#!/usr/bin/env bash+# Bring up an ephemeral test stack for a PR.+#+# Usage: ./up.sh <PR_NUM> [WORKERS=0]+#+# Creates: pr_<num> Postgres database, pr-<num>-checkpoints storage container,+# pr-<num>-server VM, and N pr-<num>-worker-X VMs. Deploys server + worker+# binaries (built from the current tree) and replaces the gallery-baked agent+# inside default.ext4 with the PR's agent. Waits for /healthz green and worker+# registration. Echoes connection info.++set -euo pipefail++PR_NUM="${1:-}"+WORKERS="${2:-0}"++[[ -n "$PR_NUM" ]] || { echo "usage: $0 <PR_NUM> [WORKERS=0]"; exit 1; }+[[ "$PR_NUM" =~ ^[0-9]+$ ]] || { echo "PR_NUM must be numeric"; exit 1; }+[[ "$WORKERS" =~ ^[0-9]+$ ]] || { echo "WORKERS must be numeric"; exit 1; }++RG="opencomputer-ci"+LOCATION="${CI_LOCATION:-eastus2}"+KV="opencomputer-ci-kv"+VNET="oc-ci-vnet"+SUBNET="compute"+SSH_KEY_PRIV="$HOME/.ssh/opencomputer-ci"+SSH_KEY_PUB="$HOME/.ssh/opencomputer-ci.pub"+SSH_OPTS="-i $SSH_KEY_PRIV -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null"+MAX_CONCURRENT_PRS="${MAX_CONCURRENT_PRS:-8}"+WORKER_SIZE="${WORKER_SIZE:-Standard_D16ads_v7}"++# Prod gallery image — CI grants opensandbox-test-gh-action SP Reader on this.+WORKER_IMAGE_VERSION="${WORKER_IMAGE_VERSION:-1.0.66}"+WORKER_IMAGE_ID="/subscriptions/070cd7a5-4e38-4ad2-9f40-bf261000a040/resourceGroups/opencomputer-prod/providers/Microsoft.Compute/galleries/oc_prod_gallery/images/osb-worker-v7/versions/${WORKER_IMAGE_VERSION}"++REPO_ROOT=$(git -C "$(dirname "$0")" rev-parse --show-toplevel)++ACTIVE=$(az vm list -g "$RG" --query "[?starts_with(name,'pr-') && ends_with(name,'-server') && name != 'pr-${PR_NUM}-server'] | length(@)" -o tsv)+if [[ "$ACTIVE" -ge "$MAX_CONCURRENT_PRS" ]]; then+ echo "FATAL: $ACTIVE PR stacks already active (cap=$MAX_CONCURRENT_PRS). Wait or tear one down."+ az vm list -g "$RG" --query "[?starts_with(name,'pr-') && ends_with(name,'-server')].{name:name,created:timeCreated}" -o table+ exit 1+fi++echo ">>> [0/9] read persistent state from KV"+kv() { az keyvault secret show --vault-name "$KV" --name "$1" --query value -o tsv; }+DATA_VM_PRIV=$(kv data-vm-private-ip)+DATA_VM_PIP=$(az vm show -d -g "$RG" -n oc-ci-data --query publicIps -o tsv)+PG_PASS=$(kv pg-password)+REDIS_PASS=$(kv redis-password)+API_KEY=$(kv server-api-key)+JWT=$(kv server-jwt-secret)+ENC_KEY=$(kv server-secret-encryption-key)+STORAGE=$(kv storage-account-name)+STORAGE_KEY=$(kv worker-s3-secret-key)++DB_NAME="pr_$PR_NUM"+CONTAINER="pr-${PR_NUM}-checkpoints"+SERVER_VM="pr-${PR_NUM}-server"++SCRATCH=$(mktemp -d)+trap "rm -rf $SCRATCH" EXIT++echo ">>> [1/9] build linux/amd64 binaries (server + worker + agent)"+SERVER_BIN="$SCRATCH/opensandbox-server"+WORKER_BIN="$SCRATCH/opensandbox-worker"+AGENT_BIN="$SCRATCH/osb-agent"+(cd "$REPO_ROOT" && GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -o "$SERVER_BIN" ./cmd/server/) >/dev/null+if [[ "$WORKERS" -gt 0 ]]; then+ (cd "$REPO_ROOT" && GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -o "$WORKER_BIN" ./cmd/worker/) >/dev/null+ (cd "$REPO_ROOT" && GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -o "$AGENT_BIN" ./cmd/agent/) >/dev/null+ echo " current: server=$(du -h "$SERVER_BIN" | cut -f1) worker=$(du -h "$WORKER_BIN" | cut -f1) agent=$(du -h "$AGENT_BIN" | cut -f1)"+else+ echo " server=$(du -h "$SERVER_BIN" | cut -f1) (workers=0, skipping worker+agent build)"+fi++# Optional cross-version setup: if BASELINE_FROM_GALLERY=1 and WORKERS>=2,+# worker 1 keeps the gallery image's pre-baked agent + worker binaries (= the+# current prod golden), while workers 2..N get the PR's overrides. Lets the+# migrate test exercise real old-golden → new-golden upgrade on every PR.+BASELINE_FROM_GALLERY="${BASELINE_FROM_GALLERY:-0}"+if [[ "$BASELINE_FROM_GALLERY" == "1" && "$WORKERS" -lt 2 ]]; then+ echo " BASELINE_FROM_GALLERY=1 requires WORKERS>=2, ignoring"+ BASELINE_FROM_GALLERY=0+fi+if [[ "$BASELINE_FROM_GALLERY" == "1" ]]; then+ echo " cross-version mode: worker 1 uses gallery-baked binaries (current prod golden)"+fi++echo ">>> [2/9] CREATE DATABASE $DB_NAME"+ssh $SSH_OPTS azureuser@"$DATA_VM_PIP" \+ "PGPASSWORD='$PG_PASS' psql -h localhost -U postgres -d postgres -tc \"SELECT 1 FROM pg_database WHERE datname='$DB_NAME'\" | grep -q 1 \+ || PGPASSWORD='$PG_PASS' psql -h localhost -U postgres -d postgres -c \"CREATE DATABASE $DB_NAME OWNER osbciuser;\""++echo ">>> [3/9] storage container $CONTAINER"+# Azure soft-deletes containers and refuses recreation for ~30s after delete.+# If down.sh just ran for this PR, the first `container create` will silently+# fail and workers boot without a container to upload bases to. Poll until+# the container actually exists.+for i in $(seq 1 24); do+ if az storage container show --account-name "$STORAGE" --account-key "$STORAGE_KEY" -n "$CONTAINER" -o none 2>/dev/null; then+ break+ fi+ out=$(az storage container create --account-name "$STORAGE" --account-key "$STORAGE_KEY" -n "$CONTAINER" 2>&1 || true)+ if echo "$out" | grep -q '"created": true'; then+ break+ fi+ echo " container not ready yet (attempt $i, retrying in 5s)"+ sleep 5+done+if ! az storage container show --account-name "$STORAGE" --account-key "$STORAGE_KEY" -n "$CONTAINER" -o none 2>/dev/null; then+ echo "FATAL: container $CONTAINER did not become available"+ exit 1+fi++echo ">>> [4/9] provision $SERVER_VM"+if ! az vm show -g "$RG" -n "$SERVER_VM" -o none 2>/dev/null; then+ az vm create -g "$RG" -n "$SERVER_VM" \+ --image Ubuntu2404 \+ --size Standard_B2s \+ --vnet-name "$VNET" --subnet "$SUBNET" \+ --public-ip-address "${SERVER_VM}-pip" \+ --public-ip-sku Standard \+ --admin-username azureuser \+ --ssh-key-values "$SSH_KEY_PUB" \+ --os-disk-size-gb 32 \+ --nsg oc-ci-nsg-compute \+ --tags purpose=ci pr="$PR_NUM" role=server \+ -o none+fi+SERVER_PIP=$(az vm show -d -g "$RG" -n "$SERVER_VM" --query publicIps -o tsv)+SERVER_PRIV=$(az vm show -d -g "$RG" -n "$SERVER_VM" --query privateIps -o tsv)++echo ">>> [5/9] wait for SSH on $SERVER_PIP"+for _ in $(seq 1 40); do+ ssh $SSH_OPTS -o ConnectTimeout=5 azureuser@"$SERVER_PIP" "echo ok" 2>/dev/null | grep -q ok && break+ sleep 5+done++echo ">>> [6/9] deploy server (env + binary + systemd)"+cat > "$SCRATCH/server.env" <<EOF+OPENSANDBOX_MODE=server+OPENSANDBOX_PORT=8080+OPENSANDBOX_HTTP_ADDR=http://$SERVER_PIP:8080+OPENSANDBOX_DATABASE_URL=postgres://osbciuser:$PG_PASS@$DATA_VM_PRIV:5432/$DB_NAME?sslmode=disable+OPENSANDBOX_REDIS_URL=redis://default:$REDIS_PASS@$DATA_VM_PRIV:6379/0+OPENSANDBOX_API_KEY=$API_KEY+OPENSANDBOX_JWT_SECRET=$JWT+OPENSANDBOX_SECRET_ENCRYPTION_KEY=$ENC_KEY+OPENSANDBOX_REGION=$LOCATION+OPENSANDBOX_S3_BUCKET=$CONTAINER+OPENSANDBOX_S3_ENDPOINT=https://$STORAGE.blob.core.windows.net+OPENSANDBOX_S3_REGION=$LOCATION+OPENSANDBOX_S3_ACCESS_KEY_ID=$STORAGE+OPENSANDBOX_S3_SECRET_ACCESS_KEY=$STORAGE_KEY+OPENSANDBOX_S3_FORCE_PATH_STYLE=false+OPENSANDBOX_MIN_WORKERS=0+OPENSANDBOX_MAX_WORKERS=$WORKERS+OPENSANDBOX_DEFAULT_SANDBOX_CPUS=2+OPENSANDBOX_DEFAULT_SANDBOX_MEMORY_MB=1024+OPENSANDBOX_DEFAULT_SANDBOX_DISK_MB=20480+OPENSANDBOX_SANDBOX_DOMAIN=ci.local+OPENSANDBOX_IDLE_RESERVE=0+EOF++cat > "$SCRATCH/server.service" <<EOF+[Unit]+Description=opensandbox server (PR $PR_NUM)+After=network.target++[Service]+Type=simple+ExecStart=/opt/opensandbox/server+EnvironmentFile=/etc/opensandbox/server.env+WorkingDirectory=/opt/opensandbox+Restart=on-failure+RestartSec=5+KillMode=process+TimeoutStopSec=60++[Install]+WantedBy=multi-user.target+EOF++scp $SSH_OPTS "$SERVER_BIN" "$SCRATCH/server.env" "$SCRATCH/server.service" azureuser@"$SERVER_PIP":/tmp/ >/dev/null+ssh $SSH_OPTS azureuser@"$SERVER_PIP" "sudo bash -se" <<'REMOTE'+set -e+mkdir -p /opt/opensandbox /etc/opensandbox+mv /tmp/opensandbox-server /opt/opensandbox/server+chmod +x /opt/opensandbox/server+mv /tmp/server.env /etc/opensandbox/server.env+chmod 600 /etc/opensandbox/server.env+mv /tmp/server.service /etc/systemd/system/opensandbox-server.service+systemctl daemon-reload+systemctl enable opensandbox-server >/dev/null 2>&1+systemctl restart opensandbox-server+REMOTE++echo ">>> [7/9] wait for /healthz"+HEALTHY=0+for i in $(seq 1 40); do+ resp=$(curl -s -m 3 "http://$SERVER_PIP:8080/healthz" 2>/dev/null || true)+ if [[ -n "$resp" ]] && echo "$resp" | grep -qiE "ok|status"; then+ HEALTHY=1+ echo " healthy after ${i}x3s"+ break+ fi+ sleep 3+done+if [[ "$HEALTHY" == "0" ]]; then+ echo " /healthz did not respond. server logs:"+ ssh $SSH_OPTS azureuser@"$SERVER_PIP" "sudo journalctl -u opensandbox-server --no-pager -n 50 || true"+ exit 1+fi++# Seed the static API key into pr_<num>.api_keys so PG-backed auth accepts it.+# Server-mode validates X-API-Key against the api_keys table, not the env var.+KEY_HASH=$(printf '%s' "$API_KEY" | { sha256sum 2>/dev/null || shasum -a 256; } | cut -d' ' -f1)+KEY_PREFIX=$(printf '%s' "$API_KEY" | cut -c1-8)+ssh $SSH_OPTS azureuser@"$DATA_VM_PIP" "PGPASSWORD='$PG_PASS' psql -h localhost -U postgres -d $DB_NAME" <<SQL >/dev/null+INSERT INTO orgs (id, name, slug) VALUES ('00000000-0000-0000-0000-000000000001', 'CI Org', 'ci')+ON CONFLICT DO NOTHING;+INSERT INTO api_keys (id, org_id, key_hash, key_prefix, name)+VALUES ('00000000-0000-0000-0000-000000000002', '00000000-0000-0000-0000-000000000001', '$KEY_HASH', '$KEY_PREFIX', 'ci-key')+ON CONFLICT DO NOTHING;+SQL++# ─── Worker provisioning ────────────────────────────────────────────────────+if [[ "$WORKERS" -gt 0 ]]; then+ # Disk setup happens over SSH after VM boot. The gallery image's cloud-init+ # config skips runcmd, so embedding it as custom-data is unreliable.++ provision_worker() {+ local idx=$1+ local vm_name="pr-${PR_NUM}-worker-${idx}"+ local stage="[worker $idx]"++ if ! az vm show -g "$RG" -n "$vm_name" -o none 2>/dev/null; then+ echo " $stage az vm create (cross-region first boot is ~3-4 min slower)"+ az vm create -g "$RG" -n "$vm_name" \+ --image "$WORKER_IMAGE_ID" \+ --size "$WORKER_SIZE" \+ --vnet-name "$VNET" --subnet "$SUBNET" \+ --public-ip-address "${vm_name}-pip" \+ --public-ip-sku Standard \+ --admin-username azureuser \+ --ssh-key-values "$SSH_KEY_PUB" \+ --os-disk-size-gb 64 \+ --nsg oc-ci-nsg-compute \+ --tags purpose=ci pr="$PR_NUM" role=worker \+ -o none+ fi+ local pip=$(az vm show -d -g "$RG" -n "$vm_name" --query publicIps -o tsv)+ local priv=$(az vm show -d -g "$RG" -n "$vm_name" --query privateIps -o tsv)++ echo " $stage waiting for SSH on $pip"+ for _ in $(seq 1 60); do+ ssh $SSH_OPTS -o ConnectTimeout=5 azureuser@"$pip" "echo ok" 2>/dev/null | grep -q ok && break+ sleep 5+ done++ cat > "$SCRATCH/worker-${idx}.env" <<EOF+OPENSANDBOX_MODE=worker+OPENSANDBOX_VM_BACKEND=qemu+OPENSANDBOX_QEMU_BIN=qemu-system-x86_64+OPENSANDBOX_DATA_DIR=/data2/sandboxes+OPENSANDBOX_KERNEL_PATH=/opt/opensandbox/vmlinux+OPENSANDBOX_IMAGES_DIR=/data/firecracker/images+OPENSANDBOX_GRPC_ADVERTISE=$priv:9090+OPENSANDBOX_HTTP_ADDR=http://$priv:8081+OPENSANDBOX_PORT=8081+OPENSANDBOX_JWT_SECRET=$JWT+OPENSANDBOX_WORKER_ID=w-pr${PR_NUM}-${idx}+OPENSANDBOX_REGION=$LOCATION+OPENSANDBOX_SANDBOX_DOMAIN=ci.local+OPENSANDBOX_MAX_CAPACITY=20+OPENSANDBOX_DEFAULT_SANDBOX_CPUS=2+OPENSANDBOX_DEFAULT_SANDBOX_MEMORY_MB=1024+OPENSANDBOX_DEFAULT_SANDBOX_DISK_MB=20480+OPENSANDBOX_DATABASE_URL=postgres://osbciuser:$PG_PASS@$DATA_VM_PRIV:5432/$DB_NAME?sslmode=disable+OPENSANDBOX_REDIS_URL=redis://default:$REDIS_PASS@$DATA_VM_PRIV:6379/0+OPENSANDBOX_S3_BUCKET=$CONTAINER+OPENSANDBOX_S3_ENDPOINT=https://$STORAGE.blob.core.windows.net+OPENSANDBOX_S3_REGION=$LOCATION+OPENSANDBOX_S3_ACCESS_KEY_ID=$STORAGE+OPENSANDBOX_S3_SECRET_ACCESS_KEY=$STORAGE_KEY+OPENSANDBOX_S3_FORCE_PATH_STYLE=false+EOF++ # Worker 1 uses the gallery image's pre-baked binaries when in cross-version+ # mode — that represents the current prod golden. Other workers get the+ # PR's freshly-built binaries.+ local use_gallery_baseline=0+ if [[ "$idx" == "1" && "$BASELINE_FROM_GALLERY" == "1" ]]; then+ use_gallery_baseline=1+ echo " $stage cross-version mode: keeping gallery-baked binaries"+ fi+ echo " $stage scp env"+ scp $SSH_OPTS "$SCRATCH/worker-${idx}.env" azureuser@"$pip":/tmp/worker.env >/dev/null+ if [[ "$use_gallery_baseline" == "0" ]]; then+ echo " $stage scp PR-built worker + agent"+ scp $SSH_OPTS "$WORKER_BIN" azureuser@"$pip":/tmp/opensandbox-worker >/dev/null+ scp $SSH_OPTS "$AGENT_BIN" azureuser@"$pip":/tmp/osb-agent >/dev/null+ fi+ ssh $SSH_OPTS azureuser@"$pip" "sudo bash -se" <<REMOTE+set -e+USE_GALLERY_BASELINE=$use_gallery_baseline+systemctl stop opensandbox-worker 2>/dev/null || true++# Mount the local NVMe at /data2 with XFS+reflink (required by the worker's+# QEMU manager). On D-d-series_v7 the local disk is an unformatted nvme device+# that isn't the OS disk.+if ! mountpoint -q /data2; then+ ROOT_DEV=\$(findmnt -no SOURCE / | sed "s|p\\?[0-9]*\$||")+ DEV=""+ for d in /dev/nvme*n1; do+ [ -b "\$d" ] || continue+ [ "\$d" = "\$ROOT_DEV" ] && continue+ if ! blkid "\$d" >/dev/null 2>&1; then DEV="\$d"; break; fi+ done+ if [ -z "\$DEV" ]; then echo "FATAL: no unformatted local NVMe found" >&2; exit 1; fi+ echo "formatting \$DEV"+ mkfs.xfs -m reflink=1 -f "\$DEV"+ mkdir -p /data2+ mount "\$DEV" /data2+fi+mkdir -p /data2/sandboxes /data2/checkpoints+chmod 0777 /data2 /data2/sandboxes /data2/checkpoints++mkdir -p /etc/opensandbox+mv /tmp/worker.env /etc/opensandbox/worker.env+chmod 600 /etc/opensandbox/worker.env++if [[ "\$USE_GALLERY_BASELINE" == "1" ]]; then+ echo "cross-version mode: keeping gallery-baked /usr/local/bin/opensandbox-worker and ext4-baked agent"+else+ # Override worker binary + swap PR's agent into default.ext4 via loop-mount.+ mv /tmp/opensandbox-worker /usr/local/bin/opensandbox-worker+ chmod +x /usr/local/bin/opensandbox-worker+ mkdir -p /mnt/rootfs-${idx}+ mount -o loop /data/firecracker/images/default.ext4 /mnt/rootfs-${idx}+ cp /tmp/osb-agent /mnt/rootfs-${idx}/usr/local/bin/osb-agent+ chmod +x /mnt/rootfs-${idx}/usr/local/bin/osb-agent+ sync+ umount /mnt/rootfs-${idx}+ rm /tmp/osb-agent+ # Drop any cached golden snapshot — agent change invalidates it.+ rm -rf /data/sandboxes/golden /data2/sandboxes/golden 2>/dev/null || true+fi++systemctl daemon-reload+systemctl enable opensandbox-worker >/dev/null 2>&1 || true+systemctl restart opensandbox-worker+REMOTE+ echo " $stage ready (priv=$priv)"+ }++ echo ">>> [8/9] provision $WORKERS worker(s) in parallel"+ pids=()+ for i in $(seq 1 "$WORKERS"); do+ provision_worker "$i" &+ pids+=($!)+ done+ fail=0+ for pid in "${pids[@]}"; do+ if ! wait "$pid"; then fail=1; fi+ done+ if [[ "$fail" -ne 0 ]]; then+ echo " one or more workers failed to provision"+ exit 1+ fi++ echo ">>> wait for worker readiness via /api/workers (golden_version populated)"+ REGISTERED=0+ for i in $(seq 1 60); do+ # A worker is "ready" when it shows up in /api/workers AND has golden_version+ # set — that field is only populated after the golden snapshot finishes+ # building (~25s post-startup), which is when the worker can actually+ # accept sandbox creation requests.+ ready=$(curl -s -m 5 -H "X-API-Key: $API_KEY" "http://$SERVER_PIP:8080/api/workers" 2>/dev/null \+ | jq '[.[] // empty | select(.golden_version != null and .golden_version != "")] | length' 2>/dev/null || echo 0)+ if [[ "$ready" =~ ^[0-9]+$ ]] && [[ "$ready" -ge "$WORKERS" ]]; then+ REGISTERED=1+ echo " $ready worker(s) ready (golden built) after ${i}x5s"+ break+ fi+ sleep 5+ done+ if [[ "$REGISTERED" == "0" ]]; then+ echo " workers did not register. Last /api/workers response:"+ curl -s -H "X-API-Key: $API_KEY" "http://$SERVER_PIP:8080/api/workers" 2>&1 | head -20+ echo " --- worker 1 logs:"+ pip=$(az vm show -d -g "$RG" -n "pr-${PR_NUM}-worker-1" --query publicIps -o tsv 2>/dev/null || true)+ [[ -n "$pip" ]] && ssh $SSH_OPTS azureuser@"$pip" "sudo journalctl -u opensandbox-worker --no-pager -n 50 || true"+ exit 1+ fi++ # Warmup probe: golden_version populated means the snapshot is built, but+ # the first exec round-trip (API → gRPC → vsock → agent → process spawn)+ # often takes longer than tests' 30s HTTP timeout on a cold worker. Spin+ # a throwaway sandbox + echo to confirm the full exec path is hot before+ # declaring the stack ready.+ echo ">>> warmup probe: spawn sandbox + echo + delete"+ WARM=0+ for i in $(seq 1 18); do+ sbox=$(curl -s -m 30 -X POST -H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \+ -d '{"cpuCount":1,"memoryMB":1024,"diskMB":20480,"timeout":60}' \+ "http://$SERVER_PIP:8080/api/sandboxes" 2>/dev/null | jq -r '.sandboxID // empty')+ if [[ -n "$sbox" ]]; then+ out=$(curl -s -m 30 -X POST -H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \+ -d '{"cmd":"echo","args":["warmup"],"timeout":10}' \+ "http://$SERVER_PIP:8080/api/sandboxes/$sbox/exec/run" 2>/dev/null)+ curl -s -X DELETE -H "X-API-Key: $API_KEY" "http://$SERVER_PIP:8080/api/sandboxes/$sbox" >/dev/null 2>&1+ if echo "$out" | grep -q '"exitCode":0'; then+ WARM=1+ echo " warmup OK after ${i} attempt(s)"+ break+ fi+ fi+ sleep 5+ done+ if [[ "$WARM" == "0" ]]; then+ echo " FATAL: warmup probe never succeeded (worker exec path not ready)"+ exit 1+ fi+fi++echo ">>> [9/9] DONE"++# Emit step outputs for the GitHub Actions workflow.+if [[ -n "${GITHUB_OUTPUT:-}" ]]; then+ {+ echo "server_url=http://$SERVER_PIP:8080"+ echo "api_key=$API_KEY"+ echo "workers=$WORKERS"+ } >> "$GITHUB_OUTPUT"+fi++cat <<DONE++================================================================+PR-$PR_NUM stack is up.++ server URL: http://$SERVER_PIP:8080+ api key: $API_KEY+ database: $DB_NAME (on data VM $DATA_VM_PRIV)+ storage: $CONTAINER (account: $STORAGE)+ workers: $WORKERS (image: osb-worker-v7:${WORKER_IMAGE_VERSION})++ smoke: curl -H "X-API-Key: $API_KEY" http://$SERVER_PIP:8080/api/orgs+ ssh server: ssh -i ~/.ssh/opencomputer-ci azureuser@$SERVER_PIP+ ssh worker 1: ssh -i ~/.ssh/opencomputer-ci azureuser@\$(az vm show -d -g $RG -n pr-${PR_NUM}-worker-1 --query publicIps -o tsv 2>/dev/null)+ logs: ssh ... 'sudo journalctl -u opensandbox-{server,worker} -f'+ teardown: ./down.sh $PR_NUM+================================================================+DONEdiff --git a/ci/tests/api/auth_test.go b/ci/tests/api/auth_test.gonew file mode 100644index 00000000..804afea3--- /dev/null+++ b/ci/tests/api/auth_test.go@@ -0,0 +1,41 @@+package api_test++import (+ "net/http"+ "testing"+)++// TestAuth_RejectsBadKeys covers the three negative auth paths against an+// authenticated endpoint (/api/workers, which requires a valid API key in PG).+func TestAuth_RejectsBadKeys(t *testing.T) {+ c := newClient(t)+ cases := []struct {+ name string+ headers map[string]string+ wantMin int // accept >= this+ wantMax int // accept <= this (so 401 or 403 both pass)+ }{+ {"no key", map[string]string{}, 401, 403},+ {"empty key", map[string]string{"X-API-Key": ""}, 401, 403},+ {"wrong key", map[string]string{"X-API-Key": "osb_ci_definitely_not_a_real_key"}, 401, 403},+ {"bearer of api key", map[string]string{"Authorization": "Bearer " + c.apiKey}, 401, 403},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ code, body := c.raw(t, http.MethodGet, "/api/workers", tc.headers)+ if code < tc.wantMin || code > tc.wantMax {+ t.Fatalf("want %d-%d, got %d (body=%q)", tc.wantMin, tc.wantMax, code, body)+ }+ })+ }+}++func TestAuth_AcceptsValidKey(t *testing.T) {+ c := newClient(t)+ code, body := c.raw(t, http.MethodGet, "/api/workers", map[string]string{+ "X-API-Key": c.apiKey,+ })+ if code != http.StatusOK {+ t.Fatalf("/api/workers with valid key: want 200, got %d (body=%q)", code, body)+ }+}diff --git a/ci/tests/api/checkpoints_test.go b/ci/tests/api/checkpoints_test.gonew file mode 100644index 00000000..4db3f3cb--- /dev/null+++ b/ci/tests/api/checkpoints_test.go@@ -0,0 +1,244 @@+package api_test++import (+ "fmt"+ "net/http"+ "os"+ "strconv"+ "testing"+ "time"+)++// TestCheckpoints_CreateAndFork covers the warm-cache checkpoint path:+// create sandbox → checkpoint → wait status=ready → fork → verify keys.+//+// Key assertion: when status=ready, both rootfsS3Key and workspaceS3Key+// must be non-empty. This catches the regression class where the worker's+// async upload silently failed but the DB row was still marked ready+// (leading to forks of empty workspaces). The /api/sandboxes/from-checkpoint+// path then has real keys to download, exercising the upload-and-fetch flow.+func TestCheckpoints_CreateAndFork(t *testing.T) {+ if v, _ := strconv.Atoi(os.Getenv(envWorkers)); v < 1 {+ t.Skipf("%s<1, skipping checkpoint test", envWorkers)+ }+ c := newClient(t)+ sourceID, _ := createReadySandbox(t, c, map[string]any{+ "cpuCount": 1, "memoryMB": 1024, "diskMB": 20480, "timeout": 300,+ })+ t.Logf("source sandbox: %s", sourceID)++ // Write a marker into the workspace so we can verify the fork inherited it.+ const marker = "ci-checkpoint-marker"+ writeMarker(t, c, sourceID, marker)++ // Step 2: create checkpoint+ cpName := fmt.Sprintf("ci-cp-%d", time.Now().UnixNano())+ var cp struct {+ ID string `json:"id"`+ Status string `json:"status"`+ Name string `json:"name"`+ RootfsS3Key *string `json:"rootfsS3Key"`+ WorkspaceS3Key *string `json:"workspaceS3Key"`+ }+ code, err := c.do(t, http.MethodPost,+ "/api/sandboxes/"+sourceID+"/checkpoints",+ map[string]any{"name": cpName}, &cp)+ if err != nil || code/100 != 2 {+ t.Fatalf("create checkpoint: code=%d err=%v", code, err)+ }+ if cp.ID == "" || cp.Status != "processing" {+ t.Fatalf("create checkpoint response: %+v", cp)+ }+ t.Logf("checkpoint created: id=%s status=processing", cp.ID)++ // Step 3: poll until status=ready (or timeout). Empty sandboxes take ~20-40s.+ deadline := time.Now().Add(5 * time.Minute)+ var ready struct {+ Status string+ RootfsS3Key *string+ WorkspaceS3Key *string+ SizeBytes int64+ }+ for time.Now().Before(deadline) {+ var cps []struct {+ ID string `json:"id"`+ Status string `json:"status"`+ RootfsS3Key *string `json:"rootfsS3Key"`+ WorkspaceS3Key *string `json:"workspaceS3Key"`+ SizeBytes int64 `json:"sizeBytes"`+ }+ code, err := c.do(t, http.MethodGet,+ "/api/sandboxes/"+sourceID+"/checkpoints", nil, &cps)+ if err == nil && code == http.StatusOK {+ for _, x := range cps {+ if x.ID == cp.ID {+ ready.Status = x.Status+ ready.RootfsS3Key = x.RootfsS3Key+ ready.WorkspaceS3Key = x.WorkspaceS3Key+ ready.SizeBytes = x.SizeBytes+ break+ }+ }+ }+ if ready.Status == "ready" || ready.Status == "failed" {+ break+ }+ time.Sleep(3 * time.Second)+ }+ if ready.Status != "ready" {+ t.Fatalf("checkpoint never reached ready (final status=%q)", ready.Status)+ }+ t.Logf("checkpoint ready: size=%d bytes", ready.SizeBytes)++ // Step 4: critical regression check — keys must be populated.+ if ready.RootfsS3Key == nil || *ready.RootfsS3Key == "" {+ t.Errorf("checkpoint status=ready but rootfsS3Key is empty (regression: empty-key checkpoint)")+ }+ if ready.WorkspaceS3Key == nil || *ready.WorkspaceS3Key == "" {+ t.Errorf("checkpoint status=ready but workspaceS3Key is empty (regression: empty-key checkpoint)")+ }+ if ready.SizeBytes <= 0 {+ t.Errorf("checkpoint sizeBytes=%d (regression: size not persisted)", ready.SizeBytes)+ }+ if t.Failed() {+ t.FailNow() // don't try forking against a broken checkpoint+ }++ // Step 5: fork — POST /api/sandboxes/from-checkpoint/:checkpointId+ var fork struct {+ SandboxID string `json:"sandboxID"`+ Status string `json:"status"`+ WorkerID string `json:"workerID"`+ }+ code, err = c.do(t, http.MethodPost,+ "/api/sandboxes/from-checkpoint/"+cp.ID,+ map[string]any{+ "cpuCount": 1,+ "memoryMB": 1024,+ "diskMB": 20480,+ "timeout": 120,+ }, &fork)+ if err != nil || code/100 != 2 {+ t.Fatalf("fork: code=%d err=%v", code, err)+ }+ if fork.SandboxID == "" || fork.Status != "running" {+ t.Fatalf("fork response: %+v", fork)+ }+ t.Logf("forked sandbox: %s on %s", fork.SandboxID, fork.WorkerID)+ t.Cleanup(func() {+ c.do(t, http.MethodDelete, "/api/sandboxes/"+fork.SandboxID, nil, nil)+ c.do(t, http.MethodDelete,+ "/api/sandboxes/"+sourceID+"/checkpoints/"+cp.ID, nil, nil)+ })++ // Step 6: confirm fork shows up in list+ var sandboxes []struct {+ SandboxID string `json:"sandboxID"`+ }+ code, err = c.do(t, http.MethodGet, "/api/sandboxes", nil, &sandboxes)+ if err != nil || code != http.StatusOK {+ t.Fatalf("list: %v code=%d", err, code)+ }+ var found bool+ for _, s := range sandboxes {+ if s.SandboxID == fork.SandboxID {+ found = true+ break+ }+ }+ if !found {+ t.Fatalf("fork %s not in /api/sandboxes list", fork.SandboxID)+ }++ // Step 7: verify the workspace state survived. This catches the+ // "fork succeeded but workspace is empty" regression class (e.g. the+ // empty-key bug where SetCheckpointReady got "" keys and forks landed+ // on an empty rootfs).+ time.Sleep(5 * time.Second) // post-fork agent readiness+ if got := readMarker(t, c, fork.SandboxID); got != marker {+ t.Errorf("fork workspace state: want marker=%q, got %q", marker, got)+ }+}++// TestCheckpoints_MultipleForks creates a checkpoint, then forks it twice+// back-to-back. With WORKERS>=2 the scheduler typically lands the second fork+// on the worker that didn't create the checkpoint — that fork has to download+// the rootfs/workspace from blob (cold path), which is the case where the+// empty-key regression manifested (no local cache to fall back to, must use+// real S3 keys). Without the keys, the worker errors loudly.+func TestCheckpoints_MultipleForks(t *testing.T) {+ if v, _ := strconv.Atoi(os.Getenv(envWorkers)); v < 1 {+ t.Skipf("%s<1, skipping multi-fork test", envWorkers)+ }+ c := newClient(t)+ sourceID, _ := createReadySandbox(t, c, map[string]any{+ "cpuCount": 1, "memoryMB": 1024, "diskMB": 20480, "timeout": 300,+ })+ const marker = "ci-multi-fork-marker"+ writeMarker(t, c, sourceID, marker)++ cpName := fmt.Sprintf("ci-multi-cp-%d", time.Now().UnixNano())+ var cp struct {+ ID string `json:"id"`+ Status string `json:"status"`+ }+ code, err := c.do(t, http.MethodPost,+ "/api/sandboxes/"+sourceID+"/checkpoints",+ map[string]any{"name": cpName}, &cp)+ if err != nil || code/100 != 2 {+ t.Fatalf("create checkpoint: code=%d err=%v", code, err)+ }++ // Wait for status=ready+ deadline := time.Now().Add(5 * time.Minute)+ for time.Now().Before(deadline) {+ var cps []struct {+ ID string `json:"id"`+ Status string `json:"status"`+ }+ c.do(t, http.MethodGet, "/api/sandboxes/"+sourceID+"/checkpoints", nil, &cps)+ var s string+ for _, x := range cps {+ if x.ID == cp.ID {+ s = x.Status+ break+ }+ }+ if s == "ready" {+ break+ }+ if s == "failed" {+ t.Fatalf("checkpoint failed during multi-fork setup")+ }+ time.Sleep(3 * time.Second)+ }+ t.Cleanup(func() {+ c.do(t, http.MethodDelete, "/api/sandboxes/"+sourceID+"/checkpoints/"+cp.ID, nil, nil)+ })++ // Two forks back-to-back. With 2+ workers the scheduler distributes,+ // so at least one is on a worker that doesn't have the cache locally.+ for i := 1; i <= 2; i++ {+ var fork struct {+ SandboxID string `json:"sandboxID"`+ Status string `json:"status"`+ WorkerID string `json:"workerID"`+ }+ code, err := c.do(t, http.MethodPost,+ "/api/sandboxes/from-checkpoint/"+cp.ID,+ map[string]any{+ "cpuCount": 1, "memoryMB": 1024, "diskMB": 20480, "timeout": 120,+ }, &fork)+ if err != nil || code/100 != 2 || fork.SandboxID == "" {+ t.Fatalf("fork %d: code=%d err=%v resp=%+v", i, code, err, fork)+ }+ t.Logf("fork %d: %s on %s (status=%s)", i, fork.SandboxID, fork.WorkerID, fork.Status)+ t.Cleanup(func() {+ c.do(t, http.MethodDelete, "/api/sandboxes/"+fork.SandboxID, nil, nil)+ })+ time.Sleep(5 * time.Second) // post-fork agent readiness+ if got := readMarker(t, c, fork.SandboxID); got != marker {+ t.Errorf("fork %d workspace: want marker=%q, got %q", i, marker, got)+ }+ }+}diff --git a/ci/tests/api/cli_test.go b/ci/tests/api/cli_test.gonew file mode 100644index 00000000..8c1e0bfe--- /dev/null+++ b/ci/tests/api/cli_test.go@@ -0,0 +1,65 @@+package api_test++import (+ "os"+ "os/exec"+ "path/filepath"+ "strings"+ "testing"+)++// TestCLI_Smoke builds the oc CLI binary and exercises a few subcommands.+// Catches argparse / output regressions invisible to direct-API tests.+//+// Builds via `go build` so the binary is consistent with the rest of the PR.+// Skips if go isn't on PATH (shouldn't happen in CI).+func TestCLI_Smoke(t *testing.T) {+ if _, err := exec.LookPath("go"); err != nil {+ t.Skip("go not on PATH")+ }+ root := repoRoot(t)+ cliBin := filepath.Join(t.TempDir(), "oc")+ build := exec.Command("go", "build", "-o", cliBin, "./cmd/oc")+ build.Dir = root+ if out, err := build.CombinedOutput(); err != nil {+ t.Fatalf("build oc: %v\n%s", err, out)+ }++ // --help: every CLI must expose usage. Catches malformed cobra trees.+ out, err := exec.Command(cliBin, "--help").CombinedOutput()+ if err != nil {+ t.Fatalf("oc --help: %v\n%s", err, out)+ }+ if !strings.Contains(string(out), "Usage:") {+ t.Errorf("oc --help: missing 'Usage:' in output: %q", out)+ }++ // version: smoke check that the version subcommand exists and exits 0+ out, err = exec.Command(cliBin, "version").CombinedOutput()+ if err != nil {+ // version is optional in some CLIs — log but don't fail+ t.Logf("oc version: %v (output=%q) — skipping version assertion", err, out)+ } else if len(strings.TrimSpace(string(out))) == 0 {+ t.Errorf("oc version: empty output")+ }++ // If we have a running stack, exercise an API-authenticated command.+ server := os.Getenv(envServerURL)+ apiKey := os.Getenv(envAPIKey)+ if server == "" || apiKey == "" {+ t.Logf("no live stack — skipping live CLI command test")+ return+ }+ cmd := exec.Command(cliBin, "agent", "list")+ cmd.Env = append(os.Environ(),+ "OPENCOMPUTER_API_URL="+server,+ "OPENCOMPUTER_API_KEY="+apiKey,+ )+ out, err = cmd.CombinedOutput()+ if err != nil {+ t.Fatalf("oc agent list: %v\n%s", err, out)+ }+ // Just confirm it returned without error — the org may have zero agents.+ t.Logf("oc agent list returned %d bytes", len(out))+}+diff --git a/ci/tests/api/cross_golden_test.go b/ci/tests/api/cross_golden_test.gonew file mode 100644index 00000000..266c6f86--- /dev/null+++ b/ci/tests/api/cross_golden_test.go@@ -0,0 +1,138 @@+package api_test++import (+ "fmt"+ "net/http"+ "os"+ "strconv"+ "testing"+ "time"+)++// TestCheckpoint_ForkCrossGolden creates a checkpoint on a worker running the+// OLD golden (gallery-baked binaries), drains that worker, then forks. The+// fork lands on a worker running the NEW golden (PR binaries) and must+// successfully resume the checkpoint's workspace.+//+// This is the canonical regression class: a customer's checkpoint was taken+// against last week's golden, and now they fork after a rolling-replace+// upgraded all workers. If the new code can't load the old checkpoint's+// rootfs/workspace formats, every customer using that checkpoint breaks.+//+// Requires BASELINE_FROM_GALLERY=1 + WORKERS>=2 (i.e. distinct goldens on the+// two workers). Skips if goldens are the same.+func TestCheckpoint_ForkCrossGolden(t *testing.T) {+ if v, _ := strconv.Atoi(os.Getenv(envWorkers)); v < 2 {+ t.Skipf("%s<2, skipping cross-golden test", envWorkers)+ }+ c := newClient(t)++ // Verify workers have distinct goldens; otherwise this test isn't testing+ // the cross-golden path.+ var workers []struct {+ WorkerID string `json:"worker_id"`+ GoldenVersion string `json:"golden_version"`+ Draining bool `json:"draining"`+ }+ code, err := c.do(t, http.MethodGet, "/api/workers", nil, &workers)+ if err != nil || code != http.StatusOK {+ t.Fatalf("list workers: code=%d err=%v", code, err)+ }+ if len(workers) < 2 {+ t.Skipf("need 2 workers, got %d", len(workers))+ }+ goldens := map[string]bool{}+ for _, w := range workers {+ if !w.Draining {+ goldens[w.GoldenVersion] = true+ }+ }+ if len(goldens) < 2 {+ t.Skipf("workers share the same golden_version (%v); set BASELINE_FROM_GALLERY=1 in up.sh to get distinct goldens", goldens)+ }++ // Create sandbox, write marker+ sourceID, sourceWorker := createReadySandbox(t, c, map[string]any{+ "cpuCount": 1, "memoryMB": 1024, "diskMB": 20480, "timeout": 600,+ })+ sourceGolden := goldenVersionOf(t, c, sourceWorker)+ t.Logf("source sandbox: %s on %s (golden=%s)", sourceID, sourceWorker, sourceGolden)++ const marker = "ci-cross-golden-marker"+ writeMarker(t, c, sourceID, marker)++ // Create checkpoint against the source golden+ cpName := fmt.Sprintf("ci-xgolden-%d", time.Now().UnixNano())+ var cp struct {+ ID string `json:"id"`+ Status string `json:"status"`+ }+ code, err = c.do(t, http.MethodPost, "/api/sandboxes/"+sourceID+"/checkpoints",+ map[string]any{"name": cpName}, &cp)+ if err != nil || code/100 != 2 {+ t.Fatalf("create checkpoint: code=%d err=%v", code, err)+ }+ t.Cleanup(func() {+ c.do(t, http.MethodDelete, "/api/sandboxes/"+sourceID+"/checkpoints/"+cp.ID, nil, nil)+ })++ // Wait for status=ready+ deadline := time.Now().Add(5 * time.Minute)+ for time.Now().Before(deadline) {+ var cps []struct {+ ID string `json:"id"`+ Status string `json:"status"`+ }+ c.do(t, http.MethodGet, "/api/sandboxes/"+sourceID+"/checkpoints", nil, &cps)+ var s string+ for _, x := range cps {+ if x.ID == cp.ID {+ s = x.Status+ break+ }+ }+ if s == "ready" {+ break+ }+ if s == "failed" {+ t.Fatalf("checkpoint failed during setup")+ }+ time.Sleep(3 * time.Second)+ }+ t.Logf("checkpoint ready (captured against golden %s)", sourceGolden)++ // Drain the source worker so the fork lands on a different-golden worker.+ drainWorker(t, c, sourceWorker)++ // Fork+ var fork struct {+ SandboxID string `json:"sandboxID"`+ Status string `json:"status"`+ WorkerID string `json:"workerID"`+ }+ code, err = c.do(t, http.MethodPost, "/api/sandboxes/from-checkpoint/"+cp.ID,+ map[string]any{+ "cpuCount": 1, "memoryMB": 1024, "diskMB": 20480, "timeout": 120,+ }, &fork)+ if err != nil || code/100 != 2 {+ t.Fatalf("fork: code=%d err=%v resp=%+v", code, err, fork)+ }+ if fork.SandboxID == "" || fork.Status != "running" {+ t.Fatalf("fork response: %+v", fork)+ }+ t.Cleanup(func() { c.do(t, http.MethodDelete, "/api/sandboxes/"+fork.SandboxID, nil, nil) })++ // Verify fork landed on a DIFFERENT golden than the source+ forkGolden := goldenVersionOf(t, c, fork.WorkerID)+ t.Logf("fork: %s on %s (golden=%s)", fork.SandboxID, fork.WorkerID, forkGolden)+ if forkGolden == sourceGolden {+ t.Fatalf("fork landed on same-golden worker (%s); drain didn't redirect — expected cross-golden", forkGolden)+ }++ // Verify marker survived the cross-golden fork.+ time.Sleep(5 * time.Second)+ if got := readMarker(t, c, fork.SandboxID); got != marker {+ t.Errorf("marker corrupted across golden boundary (%s → %s): want %q, got %q",+ sourceGolden, forkGolden, marker, got)+ }+}diff --git a/ci/tests/api/cross_worker_test.go b/ci/tests/api/cross_worker_test.gonew file mode 100644index 00000000..3cd8582d--- /dev/null+++ b/ci/tests/api/cross_worker_test.go@@ -0,0 +1,77 @@+package api_test++import (+ "net/http"+ "os"+ "strconv"+ "testing"+ "time"+)++// TestHibernate_WakeCrossWorker hibernates a sandbox on worker A, drains A so+// the scheduler can't pick it again, then wakes — should land on worker B.+// Verifies the workspace state survives the S3 round-trip + handoff.+//+// This is distinct from TestMigrate_CrossWorker: that one uses live migration+// (direct TCP between workers). This one goes through blob storage, which is+// the path customers feel during worker retirements / rolling-replace.+func TestHibernate_WakeCrossWorker(t *testing.T) {+ if v, _ := strconv.Atoi(os.Getenv(envWorkers)); v < 2 {+ t.Skipf("%s<2, skipping cross-worker hibernate test", envWorkers)+ }+ c := newClient(t)++ sandboxID, sourceWorker := createReadySandbox(t, c, map[string]any{+ "cpuCount": 1, "memoryMB": 1024, "diskMB": 20480, "timeout": 600,+ })+ t.Logf("source sandbox: %s on %s", sandboxID, sourceWorker)++ const marker = "ci-hib-cross-marker"+ writeMarker(t, c, sandboxID, marker)++ // Hibernate+ code, err := c.do(t, http.MethodPost, "/api/sandboxes/"+sandboxID+"/hibernate", nil, nil)+ if err != nil || code/100 != 2 {+ t.Fatalf("hibernate: code=%d err=%v", code, err)+ }+ if !waitForStatus(t, c, sandboxID, "hibernated", 3*time.Minute) {+ t.Fatalf("sandbox never reached hibernated")+ }+ t.Logf("hibernated on %s", sourceWorker)++ // Hibernation upload to S3 is async — `status=hibernated` is set before+ // uploaded_at. If we drain the source before upload completes, wake on+ // the other worker correctly refuses with 503 ("source unavailable and+ // upload not complete"). Wait long enough for the upload to finish.+ // For a 1GB empty sandbox this is ~5-15s; 30s gives margin.+ t.Logf("waiting 30s for hibernation S3 upload to complete...")+ time.Sleep(30 * time.Second)++ // Drain the source worker so the scheduler will pick the other one for wake.+ drainWorker(t, c, sourceWorker)++ // Wake+ code, err = c.do(t, http.MethodPost, "/api/sandboxes/"+sandboxID+"/wake", nil, nil)+ if err != nil || code/100 != 2 {+ t.Fatalf("wake: code=%d err=%v", code, err)+ }+ if !waitForStatus(t, c, sandboxID, "running", 3*time.Minute) {+ t.Fatalf("sandbox never returned to running")+ }++ // Verify the wake landed on the OTHER worker.+ var sb struct {+ WorkerID string `json:"workerID"`+ }+ c.do(t, http.MethodGet, "/api/sandboxes/"+sandboxID, nil, &sb)+ if sb.WorkerID == sourceWorker {+ t.Fatalf("wake landed on same worker %s despite drain; expected cross-worker", sourceWorker)+ }+ t.Logf("woke on %s (different worker)", sb.WorkerID)++ // Verify marker survived.+ time.Sleep(5 * time.Second)+ if got := readMarker(t, c, sandboxID); got != marker {+ t.Errorf("marker corrupted across hibernate→wake→cross-worker: want %q, got %q", marker, got)+ }+}diff --git a/ci/tests/api/exec_test.go b/ci/tests/api/exec_test.gonew file mode 100644index 00000000..07254efd--- /dev/null+++ b/ci/tests/api/exec_test.go@@ -0,0 +1,64 @@+package api_test++import (+ "net/http"+ "os"+ "strconv"+ "strings"+ "testing"+)++// TestExec_Run runs a one-shot command inside a fresh sandbox and verifies the+// output. This exercises the full path: API → worker gRPC → agent inside the+// guest VM → process spawn → output round-trip.+func TestExec_Run(t *testing.T) {+ if v, _ := strconv.Atoi(os.Getenv(envWorkers)); v < 1 {+ t.Skipf("%s<1, skipping exec test", envWorkers)+ }+ c := newClient(t)+ sandboxID, _ := createReadySandbox(t, c, map[string]any{+ "cpuCount": 1, "memoryMB": 1024, "diskMB": 20480, "timeout": 120,+ })++ // Run commands and verify stdout/exit codes+ cases := []struct {+ name string+ cmd string+ args []string+ wantExit int+ wantStdoutPart string+ }{+ {"echo prints to stdout", "echo", []string{"hello-ci"}, 0, "hello-ci"},+ {"true exits 0", "true", nil, 0, ""},+ {"false exits 1", "false", nil, 1, ""},+ {"uname returns linux", "uname", []string{"-s"}, 0, "Linux"},+ {"hostname matches sandbox", "hostname", nil, 0, ""},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ var result struct {+ ExitCode int `json:"exitCode"`+ Stdout string `json:"stdout"`+ Stderr string `json:"stderr"`+ }+ body := map[string]any{"cmd": tc.cmd, "timeout": 30}+ if len(tc.args) > 0 {+ body["args"] = tc.args+ }+ code, err := c.do(t, http.MethodPost,+ "/api/sandboxes/"+sandboxID+"/exec/run", body, &result)+ if err != nil {+ t.Fatalf("exec: %v", err)+ }+ if code != http.StatusOK {+ t.Fatalf("exec: code=%d", code)+ }+ if result.ExitCode != tc.wantExit {+ t.Errorf("exit: want %d, got %d (stderr=%q)", tc.wantExit, result.ExitCode, result.Stderr)+ }+ if tc.wantStdoutPart != "" && !strings.Contains(result.Stdout, tc.wantStdoutPart) {+ t.Errorf("stdout: want substring %q, got %q", tc.wantStdoutPart, result.Stdout)+ }+ })+ }+}diff --git a/ci/tests/api/exec_variants_test.go b/ci/tests/api/exec_variants_test.gonew file mode 100644index 00000000..4bb40715--- /dev/null+++ b/ci/tests/api/exec_variants_test.go@@ -0,0 +1,161 @@+package api_test++import (+ "net/http"+ "os"+ "strconv"+ "testing"+ "time"+)++// These variants help characterize the worker→agent exec flake we observed:+// the current TestExec_Run (5 commands ~50ms apart on a fresh sandbox) shows+// ~30-40% flake. Customers don't usually fire commands that fast, but agents+// running setup-style sequences (`cat /etc/...`, `which X`, `pwd`) can.+//+// Each variant isolates one dimension. Compare flake rates across variants:+// - Burst (baseline) : matches TestExec_Run; expected ~30% flake+// - Paced : same 5 cmds with 1s sleeps — customer-like cadence+// - Stress : 50 fast cmds on one sandbox — bursty leak detector+// - Warm : burst cmds on a sandbox after 10s warmup — separates "cold sandbox" from "fast burst"++func runExecCmd(t *testing.T, c *client, sandboxID, cmd string, args []string) (exitCode int, stdout string, latency time.Duration) {+ t.Helper()+ body := map[string]any{"cmd": cmd, "timeout": 10}+ if len(args) > 0 {+ body["args"] = args+ }+ var result struct {+ ExitCode int `json:"exitCode"`+ Stdout string `json:"stdout"`+ Stderr string `json:"stderr"`+ }+ start := time.Now()+ code, err := c.do(t, http.MethodPost,+ "/api/sandboxes/"+sandboxID+"/exec/run", body, &result)+ latency = time.Since(start)+ if err != nil {+ t.Errorf("exec %q: %v (latency=%s)", cmd, err, latency)+ return -1, "", latency+ }+ if code != http.StatusOK {+ t.Errorf("exec %q: HTTP %d (latency=%s, stderr=%q)", cmd, code, latency, result.Stderr)+ return -1, "", latency+ }+ return result.ExitCode, result.Stdout, latency+}++func createSandboxForExec(t *testing.T, c *client, timeout int) string {+ t.Helper()+ var sb struct {+ SandboxID string `json:"sandboxID"`+ Status string `json:"status"`+ }+ code, err := c.do(t, http.MethodPost, "/api/sandboxes", map[string]any{+ "cpuCount": 1, "memoryMB": 1024, "diskMB": 20480, "timeout": timeout,+ }, &sb)+ if err != nil || code/100 != 2 || sb.Status != "running" {+ t.Fatalf("create sandbox: code=%d err=%v resp=%+v", code, err, sb)+ }+ t.Cleanup(func() { c.do(t, http.MethodDelete, "/api/sandboxes/"+sb.SandboxID, nil, nil) })+ return sb.SandboxID+}++// Variant A: Burst — current pattern. 5 trivial commands back-to-back on a+// fresh sandbox.+func TestExecVariant_Burst(t *testing.T) {+ if os.Getenv("OSB_TEST_VARIANTS") != "1" {+ t.Skip("variant diagnostics gated by OSB_TEST_VARIANTS=1")+ }+ if v, _ := strconv.Atoi(os.Getenv(envWorkers)); v < 1 {+ t.Skipf("%s<1, skipping", envWorkers)+ }+ c := newClient(t)+ sbox := createSandboxForExec(t, c, 120)++ cmds := []string{"echo", "true", "false", "uname", "hostname"}+ for i, cmd := range cmds {+ exit, _, lat := runExecCmd(t, c, sbox, cmd, nil)+ t.Logf("burst[%d] %s: exit=%d latency=%s", i, cmd, exit, lat)+ }+}++// Variant B: Paced — same 5 commands but with 1s sleeps between.+// If this is much less flaky than Burst, the issue is timing-specific+// (fast back-to-back exec) and customers at normal pace are fine.+func TestExecVariant_Paced(t *testing.T) {+ if os.Getenv("OSB_TEST_VARIANTS") != "1" {+ t.Skip("variant diagnostics gated by OSB_TEST_VARIANTS=1")+ }+ if v, _ := strconv.Atoi(os.Getenv(envWorkers)); v < 1 {+ t.Skipf("%s<1, skipping", envWorkers)+ }+ c := newClient(t)+ sbox := createSandboxForExec(t, c, 120)++ cmds := []string{"echo", "true", "false", "uname", "hostname"}+ for i, cmd := range cmds {+ exit, _, lat := runExecCmd(t, c, sbox, cmd, nil)+ t.Logf("paced[%d] %s: exit=%d latency=%s", i, cmd, exit, lat)+ if i < len(cmds)-1 {+ time.Sleep(1 * time.Second)+ }+ }+}++// Variant C: Stress — 50 fast commands on one sandbox. Hammers the worker→agent+// path. If the flake is a leak (e.g. accumulating stuck channels), the failure+// rate should rise across the 50 calls. If it's a fixed-probability transient,+// it should hit early and then either recover or stay flaky.+func TestExecVariant_Stress(t *testing.T) {+ if os.Getenv("OSB_TEST_VARIANTS") != "1" {+ t.Skip("variant diagnostics gated by OSB_TEST_VARIANTS=1")+ }+ if v, _ := strconv.Atoi(os.Getenv(envWorkers)); v < 1 {+ t.Skipf("%s<1, skipping", envWorkers)+ }+ c := newClient(t)+ sbox := createSandboxForExec(t, c, 300)++ const n = 50+ var slow, failed int+ for i := range n {+ exit, _, lat := runExecCmd(t, c, sbox, "true", nil)+ if lat > 2*time.Second {+ slow+++ t.Logf("stress[%d] SLOW: latency=%s exit=%d", i, lat, exit)+ }+ if exit < 0 || exit > 1 {+ failed+++ }+ }+ t.Logf("stress summary: n=%d slow(>2s)=%d failed=%d", n, slow, failed)+ if failed > 0 {+ t.Errorf("stress: %d/%d calls failed", failed, n)+ }+}++// Variant D: Warm — burst the same 5 commands but only after a 10-second pause+// post-create. If this is much less flaky than Burst, the issue is specific+// to "cold sandbox + immediate exec" (something inside the agent or worker's+// per-sandbox bookkeeping isn't ready yet right after boot).+func TestExecVariant_Warm(t *testing.T) {+ if os.Getenv("OSB_TEST_VARIANTS") != "1" {+ t.Skip("variant diagnostics gated by OSB_TEST_VARIANTS=1")+ }+ if v, _ := strconv.Atoi(os.Getenv(envWorkers)); v < 1 {+ t.Skipf("%s<1, skipping", envWorkers)+ }+ c := newClient(t)+ sbox := createSandboxForExec(t, c, 120)++ t.Logf("warm: sleeping 10s before first exec")+ time.Sleep(10 * time.Second)++ cmds := []string{"echo", "true", "false", "uname", "hostname"}+ for i, cmd := range cmds {+ exit, _, lat := runExecCmd(t, c, sbox, cmd, nil)+ t.Logf("warm[%d] %s: exit=%d latency=%s", i, cmd, exit, lat)+ }+}+diff --git a/ci/tests/api/files_test.go b/ci/tests/api/files_test.gonew file mode 100644index 00000000..20a361c9--- /dev/null+++ b/ci/tests/api/files_test.go@@ -0,0 +1,107 @@+package api_test++import (+ "bytes"+ "io"+ "net/http"+ "os"+ "strconv"+ "strings"+ "testing"+)++// TestFiles_UploadDownload exercises the signed-URL file path: get an upload+// URL, PUT content to it, get a download URL, GET it back, verify byte match.+// Also confirms exec sees the same content (proves the upload landed in the+// sandbox's workspace, not just a server-side cache).+func TestFiles_UploadDownload(t *testing.T) {+ if v, _ := strconv.Atoi(os.Getenv(envWorkers)); v < 1 {+ t.Skipf("%s<1, skipping file ops test", envWorkers)+ }+ c := newClient(t)+ sandboxID, _ := createReadySandbox(t, c, map[string]any{+ "cpuCount": 1, "memoryMB": 1024, "diskMB": 20480, "timeout": 300,+ })++ const path = "/home/sandbox/upload-test.txt"+ payload := []byte("hello-ci-upload " + strconv.FormatInt(int64(len(path)), 10))++ // Get upload URL+ var uploadResp struct {+ URL string `json:"url"`+ }+ code, err := c.do(t, http.MethodPost,+ "/api/sandboxes/"+sandboxID+"/files/upload-url",+ map[string]any{"path": path, "expiresIn": 60}, &uploadResp)+ if err != nil || code/100 != 2 || uploadResp.URL == "" {+ t.Fatalf("upload-url: code=%d err=%v resp=%+v", code, err, uploadResp)+ }++ // PUT content to the upload URL. Signed URLs are HMAC-authenticated so+ // they don't need our X-API-Key header.+ uploadURL := uploadResp.URL+ if strings.HasPrefix(uploadURL, "/") {+ uploadURL = c.baseURL + uploadURL+ }+ req, err := http.NewRequest(http.MethodPut, uploadURL, bytes.NewReader(payload))+ if err != nil {+ t.Fatalf("build PUT: %v", err)+ }+ req.Header.Set("Content-Type", "application/octet-stream")+ resp, err := c.http.Do(req)+ if err != nil {+ t.Fatalf("PUT: %v", err)+ }+ body, _ := io.ReadAll(resp.Body)+ resp.Body.Close()+ if resp.StatusCode/100 != 2 {+ t.Fatalf("PUT upload: status=%d body=%q", resp.StatusCode, body)+ }++ // Get download URL+ var downloadResp struct {+ URL string `json:"url"`+ }+ code, err = c.do(t, http.MethodPost,+ "/api/sandboxes/"+sandboxID+"/files/download-url",+ map[string]any{"path": path, "expiresIn": 60}, &downloadResp)+ if err != nil || code/100 != 2 || downloadResp.URL == "" {+ t.Fatalf("download-url: code=%d err=%v resp=%+v", code, err, downloadResp)+ }++ downloadURL := downloadResp.URL+ if strings.HasPrefix(downloadURL, "/") {+ downloadURL = c.baseURL + downloadURL+ }+ req, err = http.NewRequest(http.MethodGet, downloadURL, nil)+ if err != nil {+ t.Fatalf("build GET: %v", err)+ }+ resp, err = c.http.Do(req)+ if err != nil {+ t.Fatalf("GET: %v", err)+ }+ defer resp.Body.Close()+ if resp.StatusCode/100 != 2 {+ raw, _ := io.ReadAll(resp.Body)+ t.Fatalf("GET download: status=%d body=%q", resp.StatusCode, raw)+ }+ got, _ := io.ReadAll(resp.Body)+ if !bytes.Equal(got, payload) {+ t.Errorf("download bytes mismatch: want %q, got %q", payload, got)+ }++ // Cross-check via exec — the file should be in the workspace.+ body2 := map[string]any{"cmd": "cat", "args": []string{path}, "timeout": 10}+ var r struct {+ ExitCode int `json:"exitCode"`+ Stdout string `json:"stdout"`+ }+ code, err = c.do(t, http.MethodPost, "/api/sandboxes/"+sandboxID+"/exec/run", body2, &r)+ if err != nil || code != http.StatusOK || r.ExitCode != 0 {+ t.Fatalf("exec cat: code=%d err=%v exit=%d", code, err, r.ExitCode)+ }+ if !strings.Contains(r.Stdout, string(payload)) {+ t.Errorf("exec sees different content: want %q, got %q", payload, r.Stdout)+ }+}diff --git a/ci/tests/api/health_test.go b/ci/tests/api/health_test.gonew file mode 100644index 00000000..b30e4c66--- /dev/null+++ b/ci/tests/api/health_test.go@@ -0,0 +1,23 @@+package api_test++import (+ "net/http"+ "testing"+)++func TestHealthz(t *testing.T) {+ c := newClient(t)+ var resp struct {+ Status string `json:"status"`+ }+ code, err := c.do(t, http.MethodGet, "/healthz", nil, &resp)+ if err != nil {+ t.Fatalf("/healthz: %v", err)+ }+ if code != http.StatusOK {+ t.Fatalf("/healthz: want 200, got %d", code)+ }+ if resp.Status != "alive" {+ t.Fatalf("/healthz: want status=alive, got %q", resp.Status)+ }+}diff --git a/ci/tests/api/helpers_test.go b/ci/tests/api/helpers_test.gonew file mode 100644index 00000000..1bec52fb--- /dev/null+++ b/ci/tests/api/helpers_test.go@@ -0,0 +1,219 @@+// Package api contains integration tests against a running opensandbox stack.+// Tests connect to OSB_TEST_SERVER_URL with OSB_TEST_API_KEY (set by ci/pr/up.sh).+// If those env vars are missing, every test in the package skips so `go test ./...`+// stays green for unit-test runs that don't have a stack provisioned.+package api_test++import (+ "bytes"+ "encoding/json"+ "fmt"+ "io"+ "net/http"+ "os"+ "strings"+ "testing"+ "time"+)++const (+ envServerURL = "OSB_TEST_SERVER_URL"+ envAPIKey = "OSB_TEST_API_KEY"+ envWorkers = "OSB_TEST_WORKERS"+)++type client struct {+ baseURL string+ apiKey string+ http *http.Client+}++func newClient(t *testing.T) *client {+ t.Helper()+ url := os.Getenv(envServerURL)+ key := os.Getenv(envAPIKey)+ if url == "" || key == "" {+ t.Skipf("%s and %s must be set to run integration tests", envServerURL, envAPIKey)+ }+ return &client{+ baseURL: strings.TrimRight(url, "/"),+ apiKey: key,+ http: &http.Client{Timeout: 60 * time.Second},+ }+}++// do issues a request and decodes JSON into out (if non-nil). Returns the+// response status code and any error. The body is fully consumed.+//+// No retries on 5xx — we want failures visible. The product surface is what+// customers see; if the worker→agent transport is flaky, tests should mirror+// that, not paper over it.+func (c *client) do(t *testing.T, method, path string, body, out any) (int, error) {+ t.Helper()+ var rdr io.Reader+ if body != nil {+ b, err := json.Marshal(body)+ if err != nil {+ return 0, fmt.Errorf("marshal body: %w", err)+ }+ rdr = bytes.NewReader(b)+ }+ req, err := http.NewRequest(method, c.baseURL+path, rdr)+ if err != nil {+ return 0, err+ }+ req.Header.Set("X-API-Key", c.apiKey)+ if body != nil {+ req.Header.Set("Content-Type", "application/json")+ }+ resp, err := c.http.Do(req)+ if err != nil {+ return 0, err+ }+ defer resp.Body.Close()+ raw, _ := io.ReadAll(resp.Body)+ if out != nil && len(raw) > 0 {+ if err := json.Unmarshal(raw, out); err != nil {+ return resp.StatusCode, fmt.Errorf("decode %s %s (status=%d, body=%q): %w",+ method, path, resp.StatusCode, truncate(raw, 200), err)+ }+ }+ return resp.StatusCode, nil+}++// raw issues a request without auth headers (for testing missing/wrong keys).+func (c *client) raw(t *testing.T, method, path string, headers map[string]string) (int, []byte) {+ t.Helper()+ req, err := http.NewRequest(method, c.baseURL+path, nil)+ if err != nil {+ t.Fatalf("new request: %v", err)+ }+ for k, v := range headers {+ req.Header.Set(k, v)+ }+ resp, err := c.http.Do(req)+ if err != nil {+ t.Fatalf("do: %v", err)+ }+ defer resp.Body.Close()+ raw, _ := io.ReadAll(resp.Body)+ return resp.StatusCode, raw+}++func truncate(b []byte, n int) []byte {+ if len(b) <= n {+ return b+ }+ return append(b[:n:n], []byte("…")...)+}++// createReadySandbox creates a sandbox and waits 5s before returning.+//+// The API returns status:"running" once the VM has booted and the worker+// Pinged the agent, but the agent has a known post-boot window where Exec+// calls can hang. Tests that hit Exec immediately see ~40% flake. A short+// pause sidesteps the worst of it. Tracked separately as a product bug;+// the real fix is the worker doing an Exec round-trip readiness probe+// before declaring the sandbox running.+//+// Use for any test that will Exec right after creating a sandbox. Tests+// that only verify list/get/delete don't need it.+func createReadySandbox(t *testing.T, c *client, cfg map[string]any) (string, string) {+ t.Helper()+ var sb struct {+ SandboxID string `json:"sandboxID"`+ Status string `json:"status"`+ WorkerID string `json:"workerID"`+ }+ code, err := c.do(t, http.MethodPost, "/api/sandboxes", cfg, &sb)+ if err != nil || code/100 != 2 {+ t.Fatalf("create sandbox: code=%d err=%v resp=%+v", code, err, sb)+ }+ if sb.SandboxID == "" || sb.Status != "running" {+ t.Fatalf("create sandbox: unexpected response %+v", sb)+ }+ t.Cleanup(func() { c.do(t, http.MethodDelete, "/api/sandboxes/"+sb.SandboxID, nil, nil) })+ time.Sleep(5 * time.Second)+ return sb.SandboxID, sb.WorkerID+}++// writeMarker writes content to /home/sandbox/marker via exec. Asserts the+// echo-back. Used by tests that need to verify workspace state survives a+// round-trip (checkpoint, hibernate, migrate, etc.).+func writeMarker(t *testing.T, c *client, sandboxID, content string) {+ t.Helper()+ body := map[string]any{+ "cmd": "sh",+ "args": []string{"-c", "echo " + content + " > /home/sandbox/marker && cat /home/sandbox/marker"},+ "timeout": 10,+ }+ var r struct {+ ExitCode int `json:"exitCode"`+ Stdout string `json:"stdout"`+ Stderr string `json:"stderr"`+ }+ code, err := c.do(t, http.MethodPost, "/api/sandboxes/"+sandboxID+"/exec/run", body, &r)+ if err != nil || code != http.StatusOK || r.ExitCode != 0 {+ t.Fatalf("writeMarker(%q): code=%d err=%v exit=%d stderr=%q", content, code, err, r.ExitCode, r.Stderr)+ }+ if !strings.Contains(r.Stdout, content) {+ t.Fatalf("writeMarker(%q): echo didn't return content, stdout=%q", content, r.Stdout)+ }+}++// drainWorker marks a worker as draining (POST /admin/workers/:id/drain) so+// the scheduler won't place new sandboxes / wakes on it. Tests use this to+// force a wake or fork onto a specific other worker. Returns a cleanup func+// that un-drains the worker (call via t.Cleanup).+func drainWorker(t *testing.T, c *client, workerID string) {+ t.Helper()+ code, _ := c.raw(t, http.MethodPost, "/admin/workers/"+workerID+"/drain",+ map[string]string{"X-API-Key": c.apiKey})+ if code/100 != 2 {+ t.Fatalf("drain %s: code=%d", workerID, code)+ }+ t.Cleanup(func() {+ c.raw(t, http.MethodPost, "/admin/workers/"+workerID+"/drain?drain=false",+ map[string]string{"X-API-Key": c.apiKey})+ })+}++// goldenVersionOf returns the golden_version of the named worker, or "" if+// unknown. Used by cross-golden tests to assert old/new pairs differ.+func goldenVersionOf(t *testing.T, c *client, workerID string) string {+ t.Helper()+ var workers []struct {+ WorkerID string `json:"worker_id"`+ GoldenVersion string `json:"golden_version"`+ }+ code, err := c.do(t, http.MethodGet, "/api/workers", nil, &workers)+ if err != nil || code != http.StatusOK {+ t.Fatalf("list workers: code=%d err=%v", code, err)+ }+ for _, w := range workers {+ if w.WorkerID == workerID {+ return w.GoldenVersion+ }+ }+ return ""+}++// readMarker returns the contents of /home/sandbox/marker as read by `cat`.+// Fails the test if the file can't be read.+func readMarker(t *testing.T, c *client, sandboxID string) string {+ t.Helper()+ body := map[string]any{"cmd": "cat", "args": []string{"/home/sandbox/marker"}, "timeout": 10}+ var r struct {+ ExitCode int `json:"exitCode"`+ Stdout string `json:"stdout"`+ Stderr string `json:"stderr"`+ }+ code, err := c.do(t, http.MethodPost, "/api/sandboxes/"+sandboxID+"/exec/run", body, &r)+ if err != nil || code != http.StatusOK {+ t.Fatalf("readMarker: code=%d err=%v stderr=%q", code, err, r.Stderr)+ }+ if r.ExitCode != 0 {+ t.Fatalf("readMarker: exit=%d stderr=%q (file missing?)", r.ExitCode, r.Stderr)+ }+ return strings.TrimSpace(r.Stdout)+}diff --git a/ci/tests/api/hibernate_test.go b/ci/tests/api/hibernate_test.gonew file mode 100644index 00000000..a3c13d22--- /dev/null+++ b/ci/tests/api/hibernate_test.go@@ -0,0 +1,122 @@+package api_test++import (+ "net/http"+ "os"+ "strconv"+ "strings"+ "testing"+ "time"+)++// TestHibernate_Wake exercises the hibernate→S3→wake round-trip and verifies+// workspace state survives. Writes a marker file in the workspace, hibernates,+// waits for status=hibernated, wakes, waits for running, reads the marker back.+//+// This catches a class of regressions: hibernate upload silently failing,+// wake fetching an empty workspace, status transitions stuck mid-flight, or+// the marker file being lost across the round-trip.+func TestHibernate_Wake(t *testing.T) {+ if v, _ := strconv.Atoi(os.Getenv(envWorkers)); v < 1 {+ t.Skipf("%s<1, skipping hibernate test", envWorkers)+ }+ c := newClient(t)+ sandboxID, _ := createReadySandbox(t, c, map[string]any{+ "cpuCount": 1, "memoryMB": 1024, "diskMB": 20480, "timeout": 600,+ })+ t.Logf("source sandbox: %s", sandboxID)++ // Step 1: write a marker file in the workspace.+ const marker = "ci-hibernate-marker-v1"+ body := map[string]any{+ "cmd": "sh",+ "args": []string{"-c", "echo " + marker + " > /home/sandbox/marker && cat /home/sandbox/marker"},+ "timeout": 10,+ }+ var execResult struct {+ ExitCode int `json:"exitCode"`+ Stdout string `json:"stdout"`+ Stderr string `json:"stderr"`+ }+ code, err := c.do(t, http.MethodPost, "/api/sandboxes/"+sandboxID+"/exec/run", body, &execResult)+ if err != nil || code != http.StatusOK {+ t.Fatalf("write marker: code=%d err=%v stderr=%q", code, err, execResult.Stderr)+ }+ if !strings.Contains(execResult.Stdout, marker) {+ t.Fatalf("marker write didn't echo back: stdout=%q", execResult.Stdout)+ }++ // Step 2: hibernate+ code, err = c.do(t, http.MethodPost, "/api/sandboxes/"+sandboxID+"/hibernate", nil, nil)+ if err != nil || code/100 != 2 {+ t.Fatalf("hibernate: code=%d err=%v", code, err)+ }+ t.Logf("hibernate request sent")++ // Step 3: poll until status=hibernated. Upload of mem+workspace can take+ // 10-30s on a small sandbox; allow generous budget.+ if !waitForStatus(t, c, sandboxID, "hibernated", 3*time.Minute) {+ t.Fatalf("sandbox never reached hibernated status")+ }+ t.Logf("hibernate complete")++ // Step 4: wake+ code, err = c.do(t, http.MethodPost, "/api/sandboxes/"+sandboxID+"/wake", nil, nil)+ if err != nil || code/100 != 2 {+ t.Fatalf("wake: code=%d err=%v", code, err)+ }+ t.Logf("wake request sent")++ if !waitForStatus(t, c, sandboxID, "running", 3*time.Minute) {+ t.Fatalf("sandbox never returned to running status")+ }+ t.Logf("wake complete")++ // Step 5: wait for exec readiness post-wake, then verify marker survived.+ time.Sleep(2 * time.Second)+ body = map[string]any{+ "cmd": "cat",+ "args": []string{"/home/sandbox/marker"},+ "timeout": 10,+ }+ execResult = struct {+ ExitCode int `json:"exitCode"`+ Stdout string `json:"stdout"`+ Stderr string `json:"stderr"`+ }{}+ code, err = c.do(t, http.MethodPost, "/api/sandboxes/"+sandboxID+"/exec/run", body, &execResult)+ if err != nil || code != http.StatusOK {+ t.Fatalf("read marker post-wake: code=%d err=%v stderr=%q", code, err, execResult.Stderr)+ }+ if execResult.ExitCode != 0 {+ t.Fatalf("read marker post-wake: exit=%d stderr=%q (file lost?)", execResult.ExitCode, execResult.Stderr)+ }+ if !strings.Contains(execResult.Stdout, marker) {+ t.Errorf("marker survived hibernate→wake but content corrupted: want %q, got %q", marker, execResult.Stdout)+ }+}++// waitForStatus polls /api/sandboxes/:id and returns true when status matches+// `want` within `timeout`, false otherwise.+func waitForStatus(t *testing.T, c *client, sandboxID, want string, timeout time.Duration) bool {+ t.Helper()+ deadline := time.Now().Add(timeout)+ last := ""+ for time.Now().Before(deadline) {+ var sb struct {+ Status string `json:"status"`+ }+ code, err := c.do(t, http.MethodGet, "/api/sandboxes/"+sandboxID, nil, &sb)+ if err == nil && code == http.StatusOK {+ if sb.Status == want {+ return true+ }+ if sb.Status != last {+ t.Logf(" status: %s", sb.Status)+ last = sb.Status+ }+ }+ time.Sleep(3 * time.Second)+ }+ return false+}diff --git a/ci/tests/api/migrate_test.go b/ci/tests/api/migrate_test.gonew file mode 100644index 00000000..6f699599--- /dev/null+++ b/ci/tests/api/migrate_test.go@@ -0,0 +1,136 @@+package api_test++import (+ "net/http"+ "os"+ "strconv"+ "strings"+ "testing"+ "time"+)++// TestMigrate_CrossWorker exercises live migration: create sandbox on worker A,+// write a marker, migrate to worker B, verify the marker survives AND that the+// sandbox is actually now on worker B.+//+// Catches: migration upload/download bugs, vmstate replay races, sandbox session+// row not updated post-migration, workspace state lost across handoff.+//+// Requires WORKERS>=2. Skipped on single-worker stacks.+func TestMigrate_CrossWorker(t *testing.T) {+ if v, _ := strconv.Atoi(os.Getenv(envWorkers)); v < 2 {+ t.Skipf("%s<2 (need at least 2 workers), skipping cross-worker test", envWorkers)+ }+ c := newClient(t)++ // Discover available workers. Cross-golden migration is supported as long+ // as each worker has uploaded its golden base to blob (uploadBaseImageIfNew+ // runs in background after golden snapshot creation).+ var workers []struct {+ WorkerID string `json:"worker_id"`+ Draining bool `json:"draining"`+ }+ code, err := c.do(t, http.MethodGet, "/api/workers", nil, &workers)+ if err != nil || code != http.StatusOK {+ t.Fatalf("list workers: code=%d err=%v", code, err)+ }+ var liveIDs []string+ for _, w := range workers {+ if !w.Draining {+ liveIDs = append(liveIDs, w.WorkerID)+ }+ }+ if len(liveIDs) < 2 {+ t.Fatalf("need 2 live workers, got %d: %+v", len(liveIDs), liveIDs)+ }++ // Create sandbox.+ sandboxID, sourceWorker := createReadySandbox(t, c, map[string]any{+ "cpuCount": 1, "memoryMB": 1024, "diskMB": 20480, "timeout": 600,+ })+ t.Logf("source sandbox: %s on %s", sandboxID, sourceWorker)++ // Pick a destination worker that's NOT the current one.+ var target string+ for _, w := range liveIDs {+ if w != sourceWorker {+ target = w+ break+ }+ }+ if target == "" {+ t.Fatalf("no candidate target worker (all %d workers match source %q)", len(liveIDs), sourceWorker)+ }+ t.Logf("migrating: %s → %s", sourceWorker, target)++ // Write marker.+ const marker = "ci-migrate-marker-v1"+ body := map[string]any{+ "cmd": "sh",+ "args": []string{"-c", "echo " + marker + " > /home/sandbox/marker && cat /home/sandbox/marker"},+ "timeout": 10,+ }+ var execResult struct {+ ExitCode int `json:"exitCode"`+ Stdout string `json:"stdout"`+ Stderr string `json:"stderr"`+ }+ code, err = c.do(t, http.MethodPost, "/api/sandboxes/"+sandboxID+"/exec/run", body, &execResult)+ if err != nil || code != http.StatusOK {+ t.Fatalf("write marker: code=%d err=%v stderr=%q", code, err, execResult.Stderr)+ }+ if !strings.Contains(execResult.Stdout, marker) {+ t.Fatalf("marker write didn't echo back: stdout=%q", execResult.Stdout)+ }++ // Migrate.+ code, err = c.do(t, http.MethodPost, "/api/sandboxes/"+sandboxID+"/migrate",+ map[string]any{"targetWorker": target}, nil)+ if err != nil || code/100 != 2 {+ t.Fatalf("migrate: code=%d err=%v", code, err)+ }+ t.Logf("migrate request accepted")++ // Wait for status to return to "running" (it goes via "migrating").+ if !waitForStatus(t, c, sandboxID, "running", 3*time.Minute) {+ t.Fatalf("sandbox didn't return to running after migrate")+ }++ // Verify the sandbox's workerID changed.+ var sb struct {+ SandboxID string `json:"sandboxID"`+ Status string `json:"status"`+ WorkerID string `json:"workerID"`+ }+ code, err = c.do(t, http.MethodGet, "/api/sandboxes/"+sandboxID, nil, &sb)+ if err != nil || code != http.StatusOK {+ t.Fatalf("get post-migrate: code=%d err=%v", code, err)+ }+ if sb.WorkerID != target {+ t.Errorf("workerID after migrate: want %q, got %q", target, sb.WorkerID)+ }+ t.Logf("sandbox now on: %s", sb.WorkerID)++ // Verify the marker survived.+ time.Sleep(2 * time.Second)+ body = map[string]any{+ "cmd": "cat",+ "args": []string{"/home/sandbox/marker"},+ "timeout": 10,+ }+ execResult = struct {+ ExitCode int `json:"exitCode"`+ Stdout string `json:"stdout"`+ Stderr string `json:"stderr"`+ }{}+ code, err = c.do(t, http.MethodPost, "/api/sandboxes/"+sandboxID+"/exec/run", body, &execResult)+ if err != nil || code != http.StatusOK {+ t.Fatalf("read marker post-migrate: code=%d err=%v stderr=%q", code, err, execResult.Stderr)+ }+ if execResult.ExitCode != 0 {+ t.Fatalf("read marker post-migrate: exit=%d stderr=%q (file lost?)", execResult.ExitCode, execResult.Stderr)+ }+ if !strings.Contains(execResult.Stdout, marker) {+ t.Errorf("marker corrupted across migrate: want %q, got %q", marker, execResult.Stdout)+ }+}diff --git a/ci/tests/api/sandboxes_test.go b/ci/tests/api/sandboxes_test.gonew file mode 100644index 00000000..60786a7c--- /dev/null+++ b/ci/tests/api/sandboxes_test.go@@ -0,0 +1,76 @@+package api_test++import (+ "net/http"+ "os"+ "strconv"+ "testing"+)++// TestSandboxes_Lifecycle creates a sandbox, confirms it shows up in list/get,+// then deletes it. Skipped when WORKERS=0 since sandbox creation requires an+// actual worker to spawn the VM. Sandbox returns already-running on create.+func TestSandboxes_Lifecycle(t *testing.T) {+ if v, _ := strconv.Atoi(os.Getenv(envWorkers)); v < 1 {+ t.Skipf("%s<1, skipping sandbox lifecycle test", envWorkers)+ }+ c := newClient(t)+ sandboxID, workerID := createReadySandbox(t, c, map[string]any{+ "cpuCount": 1, "memoryMB": 1024, "diskMB": 20480, "timeout": 120,+ })+ t.Logf("created %s on %s", sandboxID, workerID)++ t.Run("get returns same sandbox", func(t *testing.T) {+ var sb struct {+ SandboxID string `json:"sandboxID"`+ Status string `json:"status"`+ WorkerID string `json:"workerID"`+ }+ code, err := c.do(t, http.MethodGet, "/api/sandboxes/"+sandboxID, nil, &sb)+ if err != nil {+ t.Fatalf("get: %v", err)+ }+ if code != http.StatusOK {+ t.Fatalf("get: want 200, got %d", code)+ }+ if sb.SandboxID != sandboxID {+ t.Fatalf("get: sandboxID mismatch (want %q, got %q)", sandboxID, sb.SandboxID)+ }+ if sb.Status != "running" {+ t.Fatalf("get: status=%q", sb.Status)+ }+ })++ t.Run("list includes new sandbox", func(t *testing.T) {+ var sandboxes []struct {+ SandboxID string `json:"sandboxID"`+ }+ code, err := c.do(t, http.MethodGet, "/api/sandboxes", nil, &sandboxes)+ if err != nil {+ t.Fatalf("list: %v", err)+ }+ if code != http.StatusOK {+ t.Fatalf("list: want 200, got %d", code)+ }+ var found bool+ for _, s := range sandboxes {+ if s.SandboxID == sandboxID {+ found = true+ break+ }+ }+ if !found {+ t.Fatalf("created %s not in list (got %d sandboxes)", sandboxID, len(sandboxes))+ }+ })++ t.Run("delete returns 2xx", func(t *testing.T) {+ code, err := c.do(t, http.MethodDelete, "/api/sandboxes/"+sandboxID, nil, nil)+ if err != nil {+ t.Fatalf("delete: %v", err)+ }+ if code/100 != 2 {+ t.Fatalf("delete: want 2xx, got %d", code)+ }+ })+}diff --git a/ci/tests/api/sdk_test.go b/ci/tests/api/sdk_test.gonew file mode 100644index 00000000..5cb8e804--- /dev/null+++ b/ci/tests/api/sdk_test.go@@ -0,0 +1,97 @@+package api_test++import (+ "os"+ "os/exec"+ "path/filepath"+ "runtime"+ "strings"+ "testing"+)++// TestSDK_PythonImport installs the Python SDK + its runtime deps (httpx,+// websockets) into a temp venv and imports it. Catches missing-dep / syntax /+// package-config regressions. Skipped only if python3 has no venv module —+// in which case the runner setup is broken, not the SDK.+func TestSDK_PythonImport(t *testing.T) {+ py, err := exec.LookPath("python3")+ if err != nil {+ t.Skip("python3 not on PATH")+ }+ sdk := filepath.Join(repoRoot(t), "sdks", "python")+ if _, err := os.Stat(filepath.Join(sdk, "pyproject.toml")); err != nil {+ t.Skipf("python SDK dir missing: %v", err)+ }++ venv := filepath.Join(t.TempDir(), "venv")+ if out, err := exec.Command(py, "-m", "venv", venv).CombinedOutput(); err != nil {+ t.Skipf("python3 -m venv failed (no venv module?): %v\n%s", err, out)+ }+ venvPy := filepath.Join(venv, "bin", "python")+ venvPip := filepath.Join(venv, "bin", "pip")++ // Editable install pulls in httpx + websockets per pyproject.toml deps.+ install := exec.Command(venvPip, "install", "-q", "--disable-pip-version-check", "-e", sdk)+ if out, err := install.CombinedOutput(); err != nil {+ t.Fatalf("pip install -e %s: %v\n%s", sdk, err, out)+ }++ out, err := exec.Command(venvPy, "-c",+ "import opencomputer; from opencomputer import Sandbox; print(opencomputer.__name__)").+ CombinedOutput()+ if err != nil {+ t.Fatalf("python import: %v\n%s", err, out)+ }+ if !strings.Contains(string(out), "opencomputer") {+ t.Errorf("python import: unexpected output: %q", out)+ }+}++// TestSDK_TypeScriptBuild verifies the TS SDK compiles. Catches type / package+// drift between the Go API and the published types.+func TestSDK_TypeScriptBuild(t *testing.T) {+ npm, err := exec.LookPath("npm")+ if err != nil {+ t.Skip("npm not on PATH")+ }+ sdk := filepath.Join(repoRoot(t), "sdks", "typescript")+ if _, err := os.Stat(filepath.Join(sdk, "package.json")); err != nil {+ t.Skipf("ts SDK dir missing: %v", err)+ }+ // Install (idempotent if node_modules cached)+ install := exec.Command(npm, "ci", "--prefer-offline", "--no-audit", "--no-fund")+ install.Dir = sdk+ if out, err := install.CombinedOutput(); err != nil {+ // `npm ci` requires package-lock.json; if missing, fall back to install+ install = exec.Command(npm, "install", "--prefer-offline", "--no-audit", "--no-fund")+ install.Dir = sdk+ if out2, err2 := install.CombinedOutput(); err2 != nil {+ t.Logf("npm install: %v\n%s\n(after ci failure: %v\n%s)", err2, out2, err, out)+ t.Skip("npm install failed — SDK runtime deps unavailable in this env")+ }+ }+ build := exec.Command(npm, "run", "build")+ build.Dir = sdk+ if out, err := build.CombinedOutput(); err != nil {+ t.Fatalf("npm run build: %v\n%s", err, out)+ }+}++func repoRoot(t *testing.T) string {+ t.Helper()+ _, file, _, ok := runtime.Caller(0)+ if !ok {+ t.Fatal("runtime.Caller failed")+ }+ dir := filepath.Dir(file)+ for {+ if _, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil {+ return dir+ }+ parent := filepath.Dir(dir)+ if parent == dir {+ t.Fatal("no go.mod found")+ }+ dir = parent+ }+}diff --git a/ci/tests/api/secret_stores_test.go b/ci/tests/api/secret_stores_test.gonew file mode 100644index 00000000..2fc64eba--- /dev/null+++ b/ci/tests/api/secret_stores_test.go@@ -0,0 +1,140 @@+package api_test++import (+ "fmt"+ "net/http"+ "testing"+ "time"+)++// TestSecretStores_CRUD covers the full lifecycle of a secret store and the+// secret entries inside it. The store is created with a unique name per test+// run so concurrent runs don't collide.+func TestSecretStores_CRUD(t *testing.T) {+ c := newClient(t)+ storeName := fmt.Sprintf("ci-test-store-%d", time.Now().UnixNano())++ // Create store+ var created struct {+ ID string `json:"id"`+ Name string `json:"name"`+ }+ code, err := c.do(t, http.MethodPost, "/api/secret-stores",+ map[string]any{"name": storeName}, &created)+ if err != nil {+ t.Fatalf("create: %v", err)+ }+ if code/100 != 2 {+ t.Fatalf("create: want 2xx, got %d", code)+ }+ if created.ID == "" || created.Name != storeName {+ t.Fatalf("create response: %+v", created)+ }+ storeID := created.ID+ t.Cleanup(func() { cleanupStore(t, c, storeID) })++ t.Run("list includes new store", func(t *testing.T) {+ var stores []struct {+ ID string `json:"id"`+ Name string `json:"name"`+ }+ code, err := c.do(t, http.MethodGet, "/api/secret-stores", nil, &stores)+ if err != nil {+ t.Fatalf("list: %v", err)+ }+ if code != http.StatusOK {+ t.Fatalf("list: want 200, got %d", code)+ }+ var found bool+ for _, s := range stores {+ if s.ID == storeID {+ found = true+ break+ }+ }+ if !found {+ t.Fatalf("created store %s not in list (got %d stores)", storeID, len(stores))+ }+ })++ t.Run("get", func(t *testing.T) {+ var s struct {+ ID string `json:"id"`+ Name string `json:"name"`+ }+ code, err := c.do(t, http.MethodGet, "/api/secret-stores/"+storeID, nil, &s)+ if err != nil {+ t.Fatalf("get: %v", err)+ }+ if code != http.StatusOK || s.ID != storeID {+ t.Fatalf("get: code=%d resp=%+v", code, s)+ }+ })++ t.Run("set + list + delete entry", func(t *testing.T) {+ // Set+ code, err := c.do(t, http.MethodPut,+ "/api/secret-stores/"+storeID+"/secrets/MY_KEY",+ map[string]any{"value": "super-secret-value"}, nil)+ if err != nil {+ t.Fatalf("set entry: %v", err)+ }+ if code/100 != 2 {+ t.Fatalf("set entry: want 2xx, got %d", code)+ }++ // List (try both shapes)+ var entries []struct {+ Name string `json:"name"`+ }+ code, err = c.do(t, http.MethodGet,+ "/api/secret-stores/"+storeID+"/secrets", nil, &entries)+ if err != nil {+ var wrapped struct {+ Entries []struct {+ Name string `json:"name"`+ } `json:"entries"`+ }+ code2, err2 := c.do(t, http.MethodGet,+ "/api/secret-stores/"+storeID+"/secrets", nil, &wrapped)+ if err2 != nil {+ t.Fatalf("list entries: %v / %v", err, err2)+ }+ code = code2+ entries = wrapped.Entries+ }+ if code != http.StatusOK {+ t.Fatalf("list entries: want 200, got %d", code)+ }+ var found bool+ for _, e := range entries {+ if e.Name == "MY_KEY" {+ found = true+ break+ }+ }+ if !found {+ t.Fatalf("MY_KEY not in entries: %+v", entries)+ }++ // Delete+ code, err = c.do(t, http.MethodDelete,+ "/api/secret-stores/"+storeID+"/secrets/MY_KEY", nil, nil)+ if err != nil {+ t.Fatalf("delete entry: %v", err)+ }+ if code/100 != 2 {+ t.Fatalf("delete entry: want 2xx, got %d", code)+ }+ })+}++func cleanupStore(t *testing.T, c *client, storeID string) {+ if storeID == "" {+ return+ }+ code, _ := c.do(t, http.MethodDelete, "/api/secret-stores/"+storeID, nil, nil)+ if code/100 != 2 && code != http.StatusNotFound {+ t.Logf("cleanup: failed to delete store %s (code=%d)", storeID, code)+ }+}diff --git a/ci/tests/api/workers_test.go b/ci/tests/api/workers_test.gonew file mode 100644index 00000000..b7287078--- /dev/null+++ b/ci/tests/api/workers_test.go@@ -0,0 +1,49 @@+package api_test++import (+ "net/http"+ "os"+ "strconv"+ "testing"+)++// TestWorkers_List queries /api/workers and asserts the count matches what+// up.sh provisioned (OSB_TEST_WORKERS env var). If WORKERS is 0 the test+// just confirms the endpoint returns successfully.+func TestWorkers_List(t *testing.T) {+ c := newClient(t)+ want := 0+ if v := os.Getenv(envWorkers); v != "" {+ n, err := strconv.Atoi(v)+ if err != nil {+ t.Fatalf("parse %s: %v", envWorkers, err)+ }+ want = n+ }++ // /api/workers returns either an array or {"workers":[...]} — accept both.+ var arr []map[string]any+ var wrapped struct {+ Workers []map[string]any `json:"workers"`+ }++ // Try array first.+ code, err := c.do(t, http.MethodGet, "/api/workers", nil, &arr)+ got := len(arr)+ if err != nil {+ // Try the wrapped form.+ code2, err2 := c.do(t, http.MethodGet, "/api/workers", nil, &wrapped)+ if err2 != nil {+ t.Fatalf("/api/workers: %v / %v", err, err2)+ }+ code = code2+ got = len(wrapped.Workers)+ }+ if code != http.StatusOK {+ t.Fatalf("/api/workers: want 200, got %d", code)+ }+ if got < want {+ t.Fatalf("/api/workers: want at least %d worker(s), got %d", want, got)+ }+ t.Logf("workers registered: %d (expected at least %d)", got, want)+}diff --git a/ci/tests/migration/registered_test.go b/ci/tests/migration/registered_test.gonew file mode 100644index 00000000..b3aff509--- /dev/null+++ b/ci/tests/migration/registered_test.go@@ -0,0 +1,120 @@+// Package migration validates that every *.up.sql file in+// internal/db/migrations/ is registered in store.go's hand-maintained+// migration slice. The slice is the source of truth at runtime: a SQL file+// that's only on disk but not in the slice will silently never run.+//+// This test is the cheapest defense against the listed migrations.md pitfall.+// It needs no infrastructure — runs as a plain unit test.+package migration_test++import (+ "os"+ "path/filepath"+ "regexp"+ "runtime"+ "sort"+ "strings"+ "testing"+)++// repoRoot walks up from the test source file to find go.mod.+func repoRoot(t *testing.T) string {+ t.Helper()+ _, file, _, ok := runtime.Caller(0)+ if !ok {+ t.Fatal("runtime.Caller failed")+ }+ dir := filepath.Dir(file)+ for {+ if _, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil {+ return dir+ }+ parent := filepath.Dir(dir)+ if parent == dir {+ t.Fatal("walked to filesystem root without finding go.mod")+ }+ dir = parent+ }+}++func TestMigrations_AllSQLFilesRegistered(t *testing.T) {+ root := repoRoot(t)+ migrationsDir := filepath.Join(root, "internal", "db", "migrations")++ // Collect on-disk *.up.sql files.+ entries, err := os.ReadDir(migrationsDir)+ if err != nil {+ t.Fatalf("read migrations dir: %v", err)+ }+ onDisk := map[string]bool{}+ for _, e := range entries {+ if !e.IsDir() && strings.HasSuffix(e.Name(), ".up.sql") {+ onDisk[e.Name()] = true+ }+ }+ if len(onDisk) == 0 {+ t.Fatal("found zero *.up.sql files — migrations dir layout changed?")+ }++ // Extract registered entries from store.go's migration slice.+ storeGo, err := os.ReadFile(filepath.Join(root, "internal", "db", "store.go"))+ if err != nil {+ t.Fatalf("read store.go: %v", err)+ }+ re := regexp.MustCompile(`\{\s*(\d+)\s*,\s*"migrations/([^"]+)"\s*\}`)+ matches := re.FindAllStringSubmatch(string(storeGo), -1)+ if len(matches) == 0 {+ t.Fatal("no migration entries found in store.go — slice format changed?")+ }+ registered := map[string]int{} // filename → version+ versions := map[int]string{} // version → filename+ for _, m := range matches {+ ver := m[1]+ fn := m[2]+ registered[fn] = atoi(t, ver)+ if existing, dup := versions[atoi(t, ver)]; dup {+ t.Errorf("duplicate migration version %s: %q and %q", ver, existing, fn)+ }+ versions[atoi(t, ver)] = fn+ }++ // Every on-disk file must be registered.+ var unregistered []string+ for fn := range onDisk {+ if _, ok := registered[fn]; !ok {+ unregistered = append(unregistered, fn)+ }+ }+ if len(unregistered) > 0 {+ sort.Strings(unregistered)+ t.Errorf("unregistered migrations (in dir but not in store.go's slice — they will never run!):\n %s",+ strings.Join(unregistered, "\n "))+ }++ // Every registered entry must have a real file.+ var dangling []string+ for fn := range registered {+ if !onDisk[fn] {+ dangling = append(dangling, fn)+ }+ }+ if len(dangling) > 0 {+ sort.Strings(dangling)+ t.Errorf("dangling references in store.go (in slice but no .up.sql file):\n %s",+ strings.Join(dangling, "\n "))+ }++ t.Logf("validated %d migrations: dir=%d registered=%d", len(onDisk), len(onDisk), len(registered))+}++func atoi(t *testing.T, s string) int {+ t.Helper()+ var n int+ for _, c := range s {+ if c < '0' || c > '9' {+ t.Fatalf("non-digit in version %q", s)+ }+ n = n*10 + int(c-'0')+ }+ return n+}diff --git a/cmd/agent/listen_linux.go b/cmd/agent/listen_linux.goindex a6b2895b..06f52a8e 100644--- a/cmd/agent/listen_linux.go+++ b/cmd/agent/listen_linux.go@@ -115,6 +115,9 @@ func (l *virtioSerialListener) Accept() (net.Conn, error) {// After a gRPC connection drops, the serial port may have leftover// bytes (GOAWAY frames, partial HTTP/2 frames). If we hand these to// the new gRPC session, it gets a protocol error and closes immediately.+ if instrumentVirtioSerial {+ log.Printf("virtio-serial: Accept iter: active=false, draining stale...")+ }drainStaleData(l.f)// Wait for the host to connect (port becomes readable with fresh data)@@ -214,10 +217,41 @@ type virtioSerialConn struct {once sync.Once}-func (c *virtioSerialConn) Read(b []byte) (int, error) { return c.f.Read(b) }-func (c *virtioSerialConn) Write(b []byte) (int, error) { return c.f.Write(b) }+// instrumentVirtioSerial controls per-Read logging on the conn. Set true via+// OSB_AGENT_TRACE_VIRTIO=1 env var to debug post-loadvm protocol confusion.+// HARDCODED TO TRUE FOR INVESTIGATION BUILD — revert before merging.+var instrumentVirtioSerial = true || os.Getenv("OSB_AGENT_TRACE_VIRTIO") == "1"++func (c *virtioSerialConn) Read(b []byte) (int, error) {+ n, err := c.f.Read(b)+ if instrumentVirtioSerial {+ // Log first 16 bytes (or fewer) so we can spot HTTP/2 prefaces+ // that might be from a NEW gRPC session being fed to the OLD parser.+ // HTTP/2 preface is 24 bytes starting with "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n".+ preview := ""+ if n > 0 {+ max := n+ if max > 16 {+ max = 16+ }+ preview = fmt.Sprintf(" first=%q", b[:max])+ }+ log.Printf("virtio-serial: conn.Read n=%d err=%v%s", n, err, preview)+ }+ return n, err+}+func (c *virtioSerialConn) Write(b []byte) (int, error) {+ n, err := c.f.Write(b)+ if instrumentVirtioSerial && err != nil {+ log.Printf("virtio-serial: conn.Write n=%d err=%v", n, err)+ }+ return n, err+}func (c *virtioSerialConn) Close() error {c.once.Do(func() {+ if instrumentVirtioSerial {+ log.Printf("virtio-serial: conn.Close called (gRPC dropped this conn)")+ }if c.onClose != nil {c.onClose()}diff --git a/cmd/agent/main.go b/cmd/agent/main.goindex 929f5598..1467aa88 100644--- a/cmd/agent/main.go+++ b/cmd/agent/main.go@@ -6,11 +6,14 @@package mainimport (+ "context""log""os"+ "os/exec""os/signal""syscall"+ "github.com/opensandbox/opensandbox/internal/logship""github.com/opensandbox/opensandbox/internal/agent")@@ -33,6 +36,20 @@ func main() {}srv := agent.NewServer(Version)++ // Sandbox session log shipping. The shipper boots dormant — events+ // queue in its bounded ring but don't POST anywhere until the+ // worker delivers ConfigureLogship after VM boot. The /var/log+ // tailer starts immediately so we don't miss the boot window.+ // If the worker never calls ConfigureLogship (kill-switch), the+ // ring keeps dropping oldest indefinitely; cost is negligible.+ shipperCtx, shipperCancel := context.WithCancel(context.Background())+ defer shipperCancel()+ shipper := logship.New()+ go shipper.Run(shipperCtx)+ go logship.NewVarLogTailer(shipper, "/var/log").Run(shipperCtx)+ srv.Shipper = shipper+// Only set ListenPort for vsock-based backends (Firecracker).// For virtio-serial (QEMU), PTY I/O flows over gRPC PTYAttach instead.if vsl, isVirtioSerial := lis.(*virtioSerialListener); isVirtioSerial {@@ -51,6 +68,24 @@ func main() {// running. Drain on each SIGCHLD; signals coalesce so we loop.startReaper()+ // Best-effort: start supervisord if installed and configured. Run as a+ // daemon (default mode, not -n) so it returns immediately and we don't+ // block agent startup. Supervisord becomes a regular child of PID 1; its+ // own children (configured programs) are reparented to it, not to us, so+ // our SIGCHLD reaper doesn't conflict with supervisord's own wait4 calls.+ // Without this, "supervisord baked into rootfs" only works while the user+ // manually starts it — programs don't auto-start at boot the way they do+ // on a systemd-managed VM.+ if _, err := os.Stat("/usr/bin/supervisord"); err == nil {+ if _, err := os.Stat("/etc/supervisor/supervisord.conf"); err == nil {+ if err := exec.Command("/usr/bin/supervisord", "-c", "/etc/supervisor/supervisord.conf").Start(); err != nil {+ log.Printf("agent: supervisord start failed: %v (continuing)", err)+ } else {+ log.Printf("agent: supervisord started (config=/etc/supervisor/supervisord.conf)")+ }+ }+ }+// Signal handling:// SIGTERM/SIGINT: clean shutdown (exit)// SIGUSR1: hibernate prep — reset virtio-serial listener so Acceptdiff --git a/cmd/agent/reaper_linux.go b/cmd/agent/reaper_linux.goindex 19256aac..073c1b62 100644--- a/cmd/agent/reaper_linux.go+++ b/cmd/agent/reaper_linux.go@@ -8,6 +8,8 @@ import ("os/signal""sync/atomic""syscall"++ "github.com/opensandbox/opensandbox/internal/agent")// startReaper spawns a goroutine that waits on SIGCHLD and reaps any@@ -19,6 +21,17 @@ import (//// Also calls prctl(PR_SET_CHILD_SUBREAPER) defensively so reaping still// works even if some future setup parents us to PID > 1.+//+// Coordination with os/exec: when the agent forks a child via os/exec+// (the Exec/PrepareHibernate paths), os/exec wants to call Wait4 on its+// own child. Without coordination the reaper and os/exec race; whichever+// wait4 lands first gets the exit status and the other gets ECHILD. The+// loser returns "waitid: no child processes" up the stack — visible to+// users as ~30% fork failures with empty stdout when bench-style workloads+// hit the agent right after a fork. We fix this via RegisterManagedPid:+// the reaper checks the registry before recording a reap, and if the pid+// is managed it delivers the exit status via channel instead of letting+// os/exec call wait4 (since the reaper already did).func startReaper() {// Best-effort: PR_SET_CHILD_SUBREAPER (option 36). If running as PID 1// this is a no-op; if not, it makes us inherit orphans of our subtree.@@ -39,6 +52,13 @@ var reapedTotal atomic.Int64// drainZombies repeatedly waits for any child in non-blocking mode until// none are available. Multiple SIGCHLDs that arrive while we're already// reaping coalesce into one delivery, so each notification must drain all.+//+// For each reaped pid, agent.TryDeliverReap is consulted: if the pid is+// in the registry (explicit-wait by Exec/PrepareHibernate/PTY), the status+// is forwarded via channel rather than logged as an orphan reap. The+// caller's cmd.Wait() will see ECHILD (the kernel already gave up the+// status to us) and pull the WaitStatus from the channel. See+// internal/agent/reap_registry.go for the protocol.func drainZombies() {for {var ws syscall.WaitStatus@@ -50,6 +70,11 @@ func drainZombies() {}return}+ // If a caller is explicitly waiting on this pid, hand off the+ // status and skip the orphan-reap logging path.+ if agent.TryDeliverReap(pid, ws) {+ continue+ }n := reapedTotal.Add(1)// Log first few + every 100th so the journal stays readable.if n <= 5 || n%100 == 0 {diff --git a/cmd/capacity-shadow-verify/main.go b/cmd/capacity-shadow-verify/main.gonew file mode 100644index 00000000..3a239b57--- /dev/null+++ b/cmd/capacity-shadow-verify/main.go@@ -0,0 +1,271 @@+// capacity-shadow-verify compares the phase-2 outbox against the legacy+// UsageReporter pipeline for orgs that have zero capacity reservations+// in the window. With reservedGb=0 the integration walk's per-tier+// overage equals legacy `tier_GB × total_seconds` — any divergence+// surfaces an allocator bug before phase 3 starts shipping outbox rows+// to Stripe.+//+// Usage:+//+// DATABASE_URL=postgres://... \+// go run ./cmd/capacity-shadow-verify \+// --from=2026-04-26T00:00:00Z \+// --to=2026-04-27T00:00:00Z \+// [--org-id=<uuid>] [--epsilon=0.01]+//+// Both bounds must be UTC and 15-minute aligned. Org filter is optional+// — when omitted, every org with at least one outbox row in the window+// is checked.+package main++import (+ "context"+ "flag"+ "fmt"+ "log"+ "math"+ "os"+ "time"++ "github.com/google/uuid"+ "github.com/jackc/pgx/v5/pgxpool"+)++func main() {+ fromS := flag.String("from", "", "window start (RFC3339, UTC, 15-min aligned)")+ toS := flag.String("to", "", "window end (RFC3339, UTC, 15-min aligned)")+ orgFilter := flag.String("org-id", "", "limit comparison to one org id (optional)")+ epsilon := flag.Float64("epsilon", 0.01, "fractional delta tolerated before flagging a mismatch")+ flag.Parse()++ dbURL := os.Getenv("DATABASE_URL")+ if dbURL == "" {+ log.Fatal("DATABASE_URL is required")+ }+ if *fromS == "" || *toS == "" {+ log.Fatal("--from and --to are required")+ }+ from, err := time.Parse(time.RFC3339, *fromS)+ if err != nil {+ log.Fatalf("parse --from: %v", err)+ }+ to, err := time.Parse(time.RFC3339, *toS)+ if err != nil {+ log.Fatalf("parse --to: %v", err)+ }+ if from.Truncate(15*time.Minute) != from.UTC() || to.Truncate(15*time.Minute) != to.UTC() {+ log.Fatal("--from and --to must be UTC and 15-minute aligned")+ }+ if !to.After(from) {+ log.Fatal("--to must be after --from")+ }++ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)+ defer cancel()++ pool, err := pgxpool.New(ctx, dbURL)+ if err != nil {+ log.Fatalf("connect db: %v", err)+ }+ defer pool.Close()++ orgs, err := orgsToCheck(ctx, pool, from, to, *orgFilter)+ if err != nil {+ log.Fatalf("list orgs: %v", err)+ }+ if len(orgs) == 0 {+ log.Println("no orgs with outbox rows in window — nothing to verify")+ return+ }+ log.Printf("comparing %d org(s) over [%s, %s)", len(orgs), from.Format(time.RFC3339), to.Format(time.RFC3339))++ var mismatches int+ for _, orgID := range orgs {+ ok, err := checkOrg(ctx, pool, orgID, from, to, *epsilon)+ if err != nil {+ log.Printf("org %s: error: %v", orgID, err)+ mismatches+++ continue+ }+ if !ok {+ mismatches+++ }+ }+ if mismatches > 0 {+ log.Printf("RESULT: %d/%d org(s) had mismatches", mismatches, len(orgs))+ os.Exit(1)+ }+ log.Printf("RESULT: all %d org(s) match within epsilon=%.4f", len(orgs), *epsilon)+}++// orgsToCheck returns the set of orgs that have either outbox or legacy+// usage activity in the window, AND zero reservations in the window+// (so the comparison is apples-to-apples — outbox overage should equal+// legacy tier-GB-seconds).+func orgsToCheck(ctx context.Context, pool *pgxpool.Pool, from, to time.Time, orgFilter string) ([]uuid.UUID, error) {+ args := []any{from, to}+ filter := ""+ if orgFilter != "" {+ filter = `AND org_id = $3::uuid`+ args = append(args, orgFilter)+ }+ rows, err := pool.Query(ctx, `+ WITH activity AS (+ SELECT DISTINCT org_id FROM billable_events+ WHERE bucket_start >= $1 AND bucket_start < $2+ UNION+ SELECT DISTINCT org_id FROM sandbox_scale_events+ WHERE started_at < $2 AND (ended_at IS NULL OR ended_at > $1)+ ),+ reserved AS (+ SELECT DISTINCT org_id FROM capacity_reservation_intervals+ WHERE starts_at >= $1 AND starts_at < $2+ )+ SELECT a.org_id+ FROM activity a+ WHERE a.org_id NOT IN (SELECT org_id FROM reserved)+ `+filter+`+ ORDER BY a.org_id+ `, args...)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ var out []uuid.UUID+ for rows.Next() {+ var id uuid.UUID+ if err := rows.Scan(&id); err != nil {+ return nil, err+ }+ out = append(out, id)+ }+ return out, rows.Err()+}++func checkOrg(ctx context.Context, pool *pgxpool.Pool, orgID uuid.UUID, from, to time.Time, epsilon float64) (bool, error) {+ outbox, err := outboxTotals(ctx, pool, orgID, from, to)+ if err != nil {+ return false, fmt.Errorf("outbox: %w", err)+ }+ legacy, err := legacyTotals(ctx, pool, orgID, from, to)+ if err != nil {+ return false, fmt.Errorf("legacy: %w", err)+ }++ // Compare per tier and disk overage. With zero reservations, every+ // outbox overage row should match legacy tier-GB-seconds.+ allTiers := map[int]struct{}{}+ for tier := range outbox.tierGBSec {+ allTiers[tier] = struct{}{}+ }+ for tier := range legacy.tierGBSec {+ allTiers[tier] = struct{}{}+ }++ ok := true+ for tier := range allTiers {+ o := outbox.tierGBSec[tier]+ l := legacy.tierGBSec[tier]+ if !approxEq(o, l, epsilon) {+ fmt.Printf("MISMATCH org=%s tier=%dMB outbox=%.2f legacy=%.2f delta=%.2f (%.2f%%)\n",+ orgID, tier, o, l, o-l, percentDelta(o, l))+ ok = false+ }+ }+ if !approxEq(outbox.diskGBSec, legacy.diskGBSec, epsilon) {+ fmt.Printf("MISMATCH org=%s disk_overage outbox=%.2f legacy=%.2f delta=%.2f (%.2f%%)\n",+ orgID, outbox.diskGBSec, legacy.diskGBSec, outbox.diskGBSec-legacy.diskGBSec,+ percentDelta(outbox.diskGBSec, legacy.diskGBSec))+ ok = false+ }+ if ok {+ log.Printf("OK org=%s (%d tier(s), disk=%.2f)", orgID, len(allTiers), outbox.diskGBSec)+ }+ return ok, nil+}++type totals struct {+ tierGBSec map[int]float64 // memory_mb → GB-seconds (overage only)+ diskGBSec float64+}++func outboxTotals(ctx context.Context, pool *pgxpool.Pool, orgID uuid.UUID, from, to time.Time) (totals, error) {+ out := totals{tierGBSec: map[int]float64{}}+ rows, err := pool.Query(ctx, `+ SELECT event_type, memory_mb, COALESCE(SUM(gb_seconds), 0)::float8+ FROM billable_events+ WHERE org_id = $1 AND bucket_start >= $2 AND bucket_start < $3+ GROUP BY event_type, memory_mb+ `, orgID, from, to)+ if err != nil {+ return out, err+ }+ defer rows.Close()+ for rows.Next() {+ var typ string+ var mem int+ var gbs float64+ if err := rows.Scan(&typ, &mem, &gbs); err != nil {+ return out, err+ }+ switch typ {+ case "overage_usage":+ out.tierGBSec[mem] += gbs+ case "disk_overage_usage":+ out.diskGBSec += gbs+ }+ // reserved_usage rows are skipped: the comparison restricts to+ // orgs with zero reservations in the window.+ }+ return out, rows.Err()+}++// legacyTotals derives the same shape from sandbox_scale_events the way+// UsageReporter does: per-tier total seconds × tier_GB, disk overage as+// (disk_mb − 20480) × seconds / 1024. Window-clipped via GREATEST/LEAST+// to mirror GetOrgUsage.+func legacyTotals(ctx context.Context, pool *pgxpool.Pool, orgID uuid.UUID, from, to time.Time) (totals, error) {+ out := totals{tierGBSec: map[int]float64{}}+ rows, err := pool.Query(ctx, `+ SELECT memory_mb, disk_mb,+ SUM(EXTRACT(EPOCH FROM (LEAST(COALESCE(ended_at, $3), $3) - GREATEST(started_at, $2))))::float8 AS secs+ FROM sandbox_scale_events+ WHERE org_id = $1 AND started_at < $3 AND (ended_at IS NULL OR ended_at > $2)+ GROUP BY memory_mb, disk_mb+ `, orgID, from, to)+ if err != nil {+ return out, err+ }+ defer rows.Close()+ for rows.Next() {+ var mem, disk int+ var secs float64+ if err := rows.Scan(&mem, &disk, &secs); err != nil {+ return out, err+ }+ gbs := float64(mem/1024) * secs+ out.tierGBSec[mem] += gbs+ if disk > 20480 {+ out.diskGBSec += float64(disk-20480) / 1024.0 * secs+ }+ }+ return out, rows.Err()+}++func approxEq(a, b, epsilon float64) bool {+ if a == 0 && b == 0 {+ return true+ }+ denom := math.Max(math.Abs(a), math.Abs(b))+ return math.Abs(a-b)/denom <= epsilon+}++func percentDelta(a, b float64) float64 {+ if b == 0 {+ if a == 0 {+ return 0+ }+ return math.Inf(1)+ }+ return (a - b) / b * 100.0+}diff --git a/cmd/oc/internal/client/client.go b/cmd/oc/internal/client/client.goindex cbf6d0ed..fca6dc54 100644--- a/cmd/oc/internal/client/client.go+++ b/cmd/oc/internal/client/client.go@@ -170,6 +170,40 @@ func (c *Client) Post(ctx context.Context, path string, body, result interface{}return nil}+// GetStream performs a GET request and returns the raw response so the+// caller can stream chunks (e.g. SSE log feeds). Caller closes resp.Body.+func (c *Client) GetStream(ctx context.Context, path string) (*http.Response, error) {+ req, err := http.NewRequestWithContext(ctx, "GET", c.baseURL+path, nil)+ if err != nil {+ return nil, err+ }+ req.Header.Set("Accept", "text/event-stream")+ return c.do(req)+}++// PostStream performs a POST request and returns the raw response so the+// caller can stream chunks (e.g. SSE / chat-completions). Caller is+// responsible for closing resp.Body.+func (c *Client) PostStream(ctx context.Context, path string, body interface{}) (*http.Response, error) {+ var bodyReader io.Reader+ if body != nil {+ data, err := json.Marshal(body)+ if err != nil {+ return nil, err+ }+ bodyReader = bytes.NewReader(data)+ }+ req, err := http.NewRequestWithContext(ctx, "POST", c.baseURL+path, bodyReader)+ if err != nil {+ return nil, err+ }+ if body != nil {+ req.Header.Set("Content-Type", "application/json")+ }+ req.Header.Set("Accept", "text/event-stream")+ return c.do(req)+}+// Put performs a PUT request with a raw body.func (c *Client) Put(ctx context.Context, path string, body io.Reader) error {req, err := http.NewRequestWithContext(ctx, "PUT", c.baseURL+path, body)diff --git a/cmd/oc/internal/commands/agent.go b/cmd/oc/internal/commands/agent.goindex bcbb67d7..b5acabc9 100644--- a/cmd/oc/internal/commands/agent.go+++ b/cmd/oc/internal/commands/agent.go@@ -234,4 +234,6 @@ func init() {agentCmd.AddCommand(agentUninstallCmd)agentCmd.AddCommand(agentPackagesCmd)agentCmd.AddCommand(agentEventsCmd)+ agentCmd.AddCommand(agentSendCmd)+ agentCmd.AddCommand(agentChatCmd)}diff --git a/cmd/oc/internal/commands/agent_chat.go b/cmd/oc/internal/commands/agent_chat.gonew file mode 100644index 00000000..e0f834fa--- /dev/null+++ b/cmd/oc/internal/commands/agent_chat.go@@ -0,0 +1,237 @@+package commands++// `oc agent send` (one-shot) and `oc agent chat` (interactive REPL).+//+// Both stream the SSE response from sessions-api's instance-message endpoint+// (POST /v1/agents/:id/instances/:instId/messages) chunk-by-chunk. The+// endpoint emits OpenAI-style frames: data: {"type":"text","content":"..."}+// per chunk, and data: {"type":"done"} on the last frame.+//+// `chat` keeps the full message history in memory and resends it every turn+// — OpenClaw's chat-completions is stateless, so context only persists if+// the client supplies it.++import (+ "bufio"+ "context"+ "encoding/json"+ "fmt"+ "io"+ "net/http"+ "os"+ "strings"++ "github.com/spf13/cobra"++ "github.com/opensandbox/opensandbox/cmd/oc/internal/client"+)++type chatTurn struct {+ Role string `json:"role"`+ Content string `json:"content"`+}++// resolveAgentInstance fetches the agent and returns its current instance+// ID. Returns a friendly error when the agent has no running instance.+func resolveAgentInstance(ctx context.Context, sc *client.Client, agentID string) (string, error) {+ var agent agentResponse+ if err := sc.Get(ctx, "/v1/agents/"+agentID, &agent); err != nil {+ return "", err+ }+ if agent.InstanceID == nil || *agent.InstanceID == "" {+ return "", fmt.Errorf("agent %s has no running instance yet (status=%s) — wait for it to come up and retry",+ agentID, derefOrDash(agent.Status))+ }+ return *agent.InstanceID, nil+}++func derefOrDash(s *string) string {+ if s == nil {+ return "-"+ }+ return *s+}++// streamChatTurn posts to /messages and prints text chunks as they arrive.+// Returns the assembled assistant text so callers can append it to a+// running history (used by `oc agent chat`).+func streamChatTurn(+ ctx context.Context,+ sc *client.Client,+ agentID, instanceID string,+ history []chatTurn,+ w io.Writer,+) (string, error) {+ body := map[string]interface{}{+ "messages": history,+ }+ resp, err := sc.PostStream(ctx, "/v1/agents/"+agentID+"/instances/"+instanceID+"/messages", body)+ if err != nil {+ return "", err+ }+ defer resp.Body.Close()+ if resp.StatusCode != http.StatusOK {+ buf, _ := io.ReadAll(resp.Body)+ return "", fmt.Errorf("chat failed (HTTP %d): %s", resp.StatusCode, strings.TrimSpace(string(buf)))+ }++ var assembled strings.Builder+ reader := bufio.NewReader(resp.Body)+ for {+ line, err := reader.ReadString('\n')+ if line != "" {+ line = strings.TrimRight(line, "\r\n")+ if !strings.HasPrefix(line, "data:") {+ if err == io.EOF {+ break+ }+ continue+ }+ payload := strings.TrimSpace(strings.TrimPrefix(line, "data:"))+ if payload == "" || payload == "[DONE]" {+ if err == io.EOF {+ break+ }+ continue+ }+ var ev struct {+ Type string `json:"type"`+ Content string `json:"content"`+ Message string `json:"message"`+ Code string `json:"code"`+ }+ if jerr := json.Unmarshal([]byte(payload), &ev); jerr != nil {+ if err == io.EOF {+ break+ }+ continue+ }+ switch ev.Type {+ case "text":+ if ev.Content != "" {+ assembled.WriteString(ev.Content)+ _, _ = io.WriteString(w, ev.Content)+ }+ case "error":+ return assembled.String(), fmt.Errorf("agent error: %s (%s)", ev.Message, ev.Code)+ case "done":+ return assembled.String(), nil+ }+ }+ if err != nil {+ if err == io.EOF {+ break+ }+ return assembled.String(), err+ }+ }+ return assembled.String(), nil+}++var agentSendCmd = &cobra.Command{+ Use: "send <agent-id> <message>",+ Short: "Send one message to an agent and stream the reply",+ Long: "Send a single message to an agent and stream the reply to stdout.\n" ++ "Convenient for smoke-testing core/gateway changes from a shell:\n\n" ++ " oc agent send my-bot 'hello'\n" ++ " echo 'translate this to french: hello' | oc agent send my-bot",+ Args: cobra.RangeArgs(1, 2),+ RunE: func(cmd *cobra.Command, args []string) error {+ sc, err := sessionsClient(cmd)+ if err != nil {+ return err+ }+ agentID := args[0]++ var message string+ if len(args) >= 2 {+ message = args[1]+ } else if !stdinIsTTY() {+ buf, rerr := io.ReadAll(os.Stdin)+ if rerr != nil {+ return rerr+ }+ message = strings.TrimRight(string(buf), "\n")+ }+ if strings.TrimSpace(message) == "" {+ return fmt.Errorf("message is required (positional arg or piped stdin)")+ }++ instanceID, err := resolveAgentInstance(cmd.Context(), sc, agentID)+ if err != nil {+ return err+ }++ history := []chatTurn{{Role: "user", Content: message}}+ _, err = streamChatTurn(cmd.Context(), sc, agentID, instanceID, history, os.Stdout)+ // Trailing newline so shell prompts return cleanly.+ fmt.Println()+ return err+ },+}++var agentChatCmd = &cobra.Command{+ Use: "chat <agent-id>",+ Short: "Open an interactive chat with an agent",+ Long: "Open an interactive REPL chat with an agent. Each turn streams\n" ++ "the assistant reply live. Type ':exit' or send EOF (Ctrl-D) to quit.\n" ++ "History is kept client-side and resent every turn (OpenClaw's chat-\n" ++ "completions is stateless).",+ Args: cobra.ExactArgs(1),+ RunE: func(cmd *cobra.Command, args []string) error {+ sc, err := sessionsClient(cmd)+ if err != nil {+ return err+ }+ agentID := args[0]++ instanceID, err := resolveAgentInstance(cmd.Context(), sc, agentID)+ if err != nil {+ return err+ }++ fmt.Fprintf(os.Stderr, "Chat with %s — type ':exit' or Ctrl-D to quit.\n\n", agentID)++ history := []chatTurn{}+ reader := bufio.NewReader(os.Stdin)+ for {+ fmt.Fprint(os.Stderr, "you> ")+ line, rerr := reader.ReadString('\n')+ if rerr == io.EOF {+ if strings.TrimSpace(line) == "" {+ fmt.Fprintln(os.Stderr)+ return nil+ }+ } else if rerr != nil {+ return rerr+ }+ msg := strings.TrimRight(line, "\r\n")+ if strings.TrimSpace(msg) == "" {+ if rerr == io.EOF {+ return nil+ }+ continue+ }+ if msg == ":exit" || msg == ":quit" {+ return nil+ }++ history = append(history, chatTurn{Role: "user", Content: msg})+ fmt.Fprint(os.Stderr, "bot> ")+ reply, serr := streamChatTurn(cmd.Context(), sc, agentID, instanceID, history, os.Stdout)+ fmt.Println()+ if serr != nil {+ // Drop the unanswered user turn so the next try doesn't+ // re-send the failed pair as context.+ history = history[:len(history)-1]+ fmt.Fprintf(os.Stderr, " error: %v\n", serr)+ continue+ }+ history = append(history, chatTurn{Role: "assistant", Content: reply})++ if rerr == io.EOF {+ return nil+ }+ }+ },+}diff --git a/cmd/oc/internal/commands/agent_connect.go b/cmd/oc/internal/commands/agent_connect.goindex cdc15575..a05c45e1 100644--- a/cmd/oc/internal/commands/agent_connect.go+++ b/cmd/oc/internal/commands/agent_connect.go@@ -5,12 +5,28 @@ package commandsimport ("bufio""fmt"+ "net/url""os""strings""github.com/spf13/cobra"++ "github.com/opensandbox/opensandbox/cmd/oc/internal/client"+ "github.com/opensandbox/opensandbox/cmd/oc/internal/config")+// dashboardAgentURL builds the dashboard URL for an agent, used in the+// CLI's paywall-redirect message. APIURL doubles as the dashboard origin+// (the OC server serves /api/dashboard/* and the SPA from the same host).+func dashboardAgentURL(cmd *cobra.Command, agentID string) string {+ cfg := config.Load(cmd)+ base := strings.TrimRight(cfg.APIURL, "/")+ if base == "" {+ base = config.DefaultAPIURL+ }+ return base + "/agents/" + url.PathEscape(agentID)+}+var agentConnectCmd = &cobra.Command{Use: "connect <id> <channel>",Short: "Connect a channel to an agent",@@ -31,6 +47,36 @@ var agentConnectCmd = &cobra.Command{body := map[string]interface{}{}if channel == "telegram" {+ // Pre-flight entitlement check — bail with a clean upgrade+ // message before asking for a bot token if the agent isn't+ // subscribed. The actual connect endpoint also gates, but+ // hitting that path first means the user has to paste a token+ // just to see the paywall, which is jarring.+ var ent struct {+ Entitled bool `json:"entitled"`+ Reason string `json:"reason"`+ PriceMonthlyCents int64 `json:"price_monthly_cents"`+ }+ err := sc.Get(cmd.Context(), "/v1/agents/"+agentID+"/channels/"+channel+"/entitlement", &ent)+ if err != nil {+ if apiErr, ok := err.(*client.APIError); ok && apiErr.StatusCode == 402 {+ upgradeURL := dashboardAgentURL(cmd, agentID)+ price := "$20/mo"+ if ent.PriceMonthlyCents > 0 {+ price = fmt.Sprintf("$%.2f/mo", float64(ent.PriceMonthlyCents)/100)+ }+ fmt.Fprintf(os.Stderr,+ "\nThis agent isn't subscribed to %s yet (%s per agent).\n"++ "Subscribe in the dashboard, then re-run this command:\n\n"++ " %s\n\n",+ channel, price, upgradeURL,+ )+ return fmt.Errorf("subscription required for %s on %s", channel, agentID)+ }+ // Soft-fail on other lookup errors — fall through to the+ // real connect, which will surface a more specific error.+ }+token, _ := cmd.Flags().GetString("bot-token")if token == "" {if !stdinIsTTY() {@@ -62,6 +108,20 @@ var agentConnectCmd = &cobra.Command{var result operationSubmissionResponseif err := sc.Post(cmd.Context(), "/v1/agents/"+agentID+"/channels/"+channel, body, &result); err != nil {+ // HTTP 402 → paywalled feature. The dashboard owns+ // subscription flow (Stripe Checkout needs a browser);+ // surface a clean message and the upgrade URL instead of+ // a raw API error.+ if apiErr, ok := err.(*client.APIError); ok && apiErr.StatusCode == 402 {+ upgradeURL := dashboardAgentURL(cmd, agentID)+ fmt.Fprintf(os.Stderr,+ "\nThis agent is not subscribed to %s ($20/mo per agent).\n"++ "Subscribe in the dashboard, then re-run this command:\n"++ " %s\n\n",+ channel, upgradeURL,+ )+ return fmt.Errorf("subscription required for %s on %s", channel, agentID)+ }return err}diff --git a/cmd/oc/internal/commands/allowed_hosts.go b/cmd/oc/internal/commands/allowed_hosts.gonew file mode 100644index 00000000..3a9d3266--- /dev/null+++ b/cmd/oc/internal/commands/allowed_hosts.go@@ -0,0 +1,75 @@+package commands++import (+ "fmt"+ "sort"++ "github.com/opensandbox/opensandbox/cmd/oc/internal/client"+ "github.com/spf13/cobra"+)++var sandboxAllowedHostsCmd = &cobra.Command{+ Use: "allowed-hosts <sandbox-id>",+ Short: "Show the egress allowlist + per-secret allowed hosts for a sandbox",+ Long: `Show the egress allowlist (and any per-secret host restrictions) the+sandbox's secrets proxy enforces. Useful for debugging "why is my+outbound HTTP call being blocked" without having to cross-reference the+secret store config separately.++Sandboxes created without --secret-store have no per-store egress+restriction; this command reports an empty list for those.`,+ Args: cobra.ExactArgs(1),+ RunE: func(cmd *cobra.Command, args []string) error {+ c := client.FromContext(cmd.Context())+ var resp struct {+ SandboxID string `json:"sandboxID"`+ SecretStore string `json:"secretStore"`+ EgressAllowlist []string `json:"egressAllowlist"`+ PerSecretAllowedHosts map[string][]string `json:"perSecretAllowedHosts"`+ }+ if err := c.Get(cmd.Context(), "/sandboxes/"+args[0]+"/allowed-hosts", &resp); err != nil {+ return err+ }++ printer.Print(resp, func() {+ if resp.SecretStore == "" {+ fmt.Printf("Sandbox %s has no secret store attached — no per-store egress restriction.\n", resp.SandboxID)+ return+ }+ fmt.Printf("Sandbox %s (secret store: %s)\n", resp.SandboxID, resp.SecretStore)++ fmt.Println()+ fmt.Println("Egress allowlist:")+ if len(resp.EgressAllowlist) == 0 {+ fmt.Println(" (empty — store has no allowlist; egress is governed by platform-level policy)")+ } else {+ for _, h := range resp.EgressAllowlist {+ fmt.Printf(" • %s\n", h)+ }+ }++ if len(resp.PerSecretAllowedHosts) > 0 {+ fmt.Println()+ fmt.Println("Per-secret allowed hosts:")+ // Sort keys for deterministic output+ names := make([]string, 0, len(resp.PerSecretAllowedHosts))+ for k := range resp.PerSecretAllowedHosts {+ names = append(names, k)+ }+ sort.Strings(names)+ for _, name := range names {+ hosts := resp.PerSecretAllowedHosts[name]+ fmt.Printf(" %s:\n", name)+ for _, h := range hosts {+ fmt.Printf(" • %s\n", h)+ }+ }+ }+ })+ return nil+ },+}++func init() {+ sandboxCmd.AddCommand(sandboxAllowedHostsCmd)+}diff --git a/cmd/oc/internal/commands/logs.go b/cmd/oc/internal/commands/logs.gonew file mode 100644index 00000000..97360aca--- /dev/null+++ b/cmd/oc/internal/commands/logs.go@@ -0,0 +1,183 @@+package commands++import (+ "bufio"+ "encoding/json"+ "fmt"+ "io"+ "net/url"+ "os"+ "strconv"+ "strings"+ "time"++ "github.com/opensandbox/opensandbox/cmd/oc/internal/client"+ "github.com/spf13/cobra"+)++var logsCmd = &cobra.Command{+ Use: "logs <sandbox-id>",+ Short: "Stream a sandbox's session logs (live tail by default)",+ Long: `Stream logs from a sandbox session — /var/log/* and every exec'd+command's stdout/stderr — shipped from inside the sandbox to Axiom and+served back through the control plane.++Default behaviour: tail. Prints the historical batch starting at+the sandbox's createdAt, then polls forever for new lines until you+hit Ctrl-C. Stopped/hibernated sandboxes flip to historical-only+automatically (no new lines will arrive after stop) so --no-tail is+not strictly needed for those.++Examples:+ oc logs sb-abc # live tail+ oc logs sb-abc --no-tail # one historical batch, then exit+ oc logs sb-abc --since 30m # last 30 minutes+ oc logs sb-abc --grep error # server-side substring filter+ oc logs sb-abc --source exec_stdout,exec_stderr+ oc logs sb-abc --json # raw event JSON, one per line`,+ Args: cobra.ExactArgs(1),+ RunE: func(cmd *cobra.Command, args []string) error {+ ctx := cmd.Context()+ c := client.FromContext(ctx)+ sandboxID := args[0]++ noTail, _ := cmd.Flags().GetBool("no-tail")+ since, _ := cmd.Flags().GetString("since")+ until, _ := cmd.Flags().GetString("until")+ grep, _ := cmd.Flags().GetString("grep")+ sources, _ := cmd.Flags().GetStringSlice("source")+ limit, _ := cmd.Flags().GetInt("limit")+ jsonOut, _ := cmd.Flags().GetBool("json")++ qs := url.Values{}+ if noTail {+ qs.Set("tail", "false")+ }+ if since != "" {+ // Accept both Go duration (e.g. "30m", "2h") and RFC3339.+ if d, err := time.ParseDuration(since); err == nil {+ qs.Set("since", time.Now().UTC().Add(-d).Format(time.RFC3339))+ } else if _, err := time.Parse(time.RFC3339, since); err == nil {+ qs.Set("since", since)+ } else {+ return fmt.Errorf("--since must be a Go duration (e.g. 30m) or RFC3339 timestamp")+ }+ }+ if until != "" {+ if _, err := time.Parse(time.RFC3339, until); err != nil {+ return fmt.Errorf("--until must be an RFC3339 timestamp")+ }+ qs.Set("until", until)+ }+ if grep != "" {+ qs.Set("q", grep)+ }+ if len(sources) > 0 {+ qs.Set("source", strings.Join(sources, ","))+ }+ if limit > 0 {+ qs.Set("limit", strconv.Itoa(limit))+ }++ // client.New() already appends /api to baseURL — use the bare+ // path here, matching the convention in exec/sandbox commands.+ path := "/sandboxes/" + url.PathEscape(sandboxID) + "/logs"+ if encoded := qs.Encode(); encoded != "" {+ path += "?" + encoded+ }++ resp, err := c.GetStream(ctx, path)+ if err != nil {+ return err+ }+ defer resp.Body.Close()+ if resp.StatusCode != 200 {+ buf, _ := io.ReadAll(resp.Body)+ return fmt.Errorf("logs request failed (HTTP %d): %s", resp.StatusCode, strings.TrimSpace(string(buf)))+ }++ return streamSandboxLogs(resp.Body, os.Stdout, jsonOut)+ },+}++// logEvent mirrors the on-the-wire shape from internal/api/sandbox_logs.go.+// Unknown extra fields from server are tolerated by json.Unmarshal.+type logEvent struct {+ Time time.Time `json:"_time"`+ Source string `json:"source"`+ Line string `json:"line"`+ Path string `json:"path,omitempty"`+ ExecID string `json:"exec_id,omitempty"`+ Command string `json:"command,omitempty"`+ Argv []string `json:"argv,omitempty"`+ ExitCode *int `json:"exit_code,omitempty"`+}++// streamSandboxLogs parses an SSE stream and writes each event to w.+// Splits out from the cobra RunE so it's unit-testable.+func streamSandboxLogs(r io.Reader, w io.Writer, jsonOut bool) error {+ reader := bufio.NewReader(r)+ for {+ line, err := reader.ReadString('\n')+ if line != "" {+ line = strings.TrimRight(line, "\r\n")+ // SSE comments start with ":" — keepalives, errors. Ignore.+ if strings.HasPrefix(line, ":") {+ if err == io.EOF {+ return nil+ }+ continue+ }+ if strings.HasPrefix(line, "data:") {+ payload := strings.TrimSpace(strings.TrimPrefix(line, "data:"))+ if payload != "" {+ if jsonOut {+ fmt.Fprintln(w, payload)+ } else {+ var ev logEvent+ if jerr := json.Unmarshal([]byte(payload), &ev); jerr == nil {+ renderEvent(w, ev)+ }+ }+ }+ }+ }+ if err != nil {+ if err == io.EOF {+ return nil+ }+ return err+ }+ }+}++func renderEvent(w io.Writer, ev logEvent) {+ ts := ev.Time.Local().Format("15:04:05.000")+ color := sourceColor(ev.Source)+ fmt.Fprintf(w, "%s %s%-12s\033[0m %s\n", ts, color, ev.Source, ev.Line)+}++func sourceColor(s string) string {+ switch s {+ case "var_log":+ return "\033[36m" // cyan+ case "exec_stdout":+ return "\033[37m" // light gray+ case "exec_stderr":+ return "\033[31m" // red+ case "agent":+ return "\033[33m" // yellow+ default:+ return "\033[37m"+ }+}++func init() {+ logsCmd.Flags().Bool("no-tail", false, "exit after the historical batch instead of tailing")+ logsCmd.Flags().String("since", "", "Go duration (e.g. 30m, 2h) or RFC3339 timestamp")+ logsCmd.Flags().String("until", "", "RFC3339 timestamp; ignored when tailing")+ logsCmd.Flags().String("grep", "", "server-side substring filter on the log line")+ logsCmd.Flags().StringSlice("source", nil, "comma-separated filter: var_log, exec_stdout, exec_stderr, agent")+ logsCmd.Flags().Int("limit", 0, "max historical rows (0 = server default of 1000)")+ logsCmd.Flags().Bool("json", false, "emit raw event JSON instead of formatted lines")+}diff --git a/cmd/oc/internal/commands/logs_test.go b/cmd/oc/internal/commands/logs_test.gonew file mode 100644index 00000000..75228529--- /dev/null+++ b/cmd/oc/internal/commands/logs_test.go@@ -0,0 +1,73 @@+package commands++import (+ "bytes"+ "encoding/json"+ "strings"+ "testing"+)++func TestStreamSandboxLogs_FormattedMode(t *testing.T) {+ sse := "" ++ ": keepalive\n\n" ++ "data: {\"_time\":\"2026-05-13T12:00:00Z\",\"source\":\"var_log\",\"line\":\"hello\"}\n\n" ++ ": ping\n\n" ++ "data: {\"_time\":\"2026-05-13T12:00:01Z\",\"source\":\"exec_stdout\",\"line\":\"world\"}\n\n"++ var out bytes.Buffer+ if err := streamSandboxLogs(strings.NewReader(sse), &out, false); err != nil {+ t.Fatalf("stream: %v", err)+ }+ s := out.String()+ for _, want := range []string{"hello", "world", "var_log", "exec_stdout"} {+ if !strings.Contains(s, want) {+ t.Errorf("formatted output missing %q:\n%s", want, s)+ }+ }+}++func TestStreamSandboxLogs_JSONMode(t *testing.T) {+ payload := `{"_time":"2026-05-13T12:00:00Z","source":"var_log","line":"hello"}`+ sse := "data: " + payload + "\n\n"++ var out bytes.Buffer+ if err := streamSandboxLogs(strings.NewReader(sse), &out, true); err != nil {+ t.Fatalf("stream: %v", err)+ }+ // In JSON mode, the payload is printed verbatim. Verify it parses back+ // to the same shape — protects against accidental wrapping/quoting.+ got := strings.TrimSpace(out.String())+ var rt map[string]any+ if err := json.Unmarshal([]byte(got), &rt); err != nil {+ t.Fatalf("output is not valid JSON: %v\n%s", err, got)+ }+ if rt["line"] != "hello" {+ t.Errorf("round-tripped line = %v, want hello", rt["line"])+ }+}++func TestStreamSandboxLogs_SkipsCommentsAndBlanks(t *testing.T) {+ sse := ": just a keepalive\n\n: another\n\n\n\n"+ var out bytes.Buffer+ if err := streamSandboxLogs(strings.NewReader(sse), &out, false); err != nil {+ t.Fatalf("stream: %v", err)+ }+ if out.Len() != 0 {+ t.Errorf("expected no output for comment-only stream, got: %q", out.String())+ }+}++func TestStreamSandboxLogs_TolerantOfMalformedPayload(t *testing.T) {+ // A bad payload shouldn't kill the whole stream — subsequent good+ // events should still render.+ sse := "" ++ "data: not-json\n\n" ++ "data: {\"_time\":\"2026-05-13T12:00:00Z\",\"source\":\"var_log\",\"line\":\"after-bad\"}\n\n"+ var out bytes.Buffer+ if err := streamSandboxLogs(strings.NewReader(sse), &out, false); err != nil {+ t.Fatalf("stream: %v", err)+ }+ if !strings.Contains(out.String(), "after-bad") {+ t.Errorf("good event after malformed payload was dropped:\n%s", out.String())+ }+}diff --git a/cmd/oc/internal/commands/root.go b/cmd/oc/internal/commands/root.goindex fe089839..4ad73120 100644--- a/cmd/oc/internal/commands/root.go+++ b/cmd/oc/internal/commands/root.go@@ -71,6 +71,7 @@ func init() {rootCmd.AddCommand(secretCmd)rootCmd.AddCommand(configCmd)rootCmd.AddCommand(agentCmd)+ rootCmd.AddCommand(logsCmd)// Top-level shortcutsrootCmd.AddCommand(createShortcut)diff --git a/cmd/oc/internal/commands/sandbox.go b/cmd/oc/internal/commands/sandbox.goindex 3f53c42e..e263c108 100644--- a/cmd/oc/internal/commands/sandbox.go+++ b/cmd/oc/internal/commands/sandbox.go@@ -186,6 +186,50 @@ var sandboxWakeCmd = &cobra.Command{},}+var sandboxRebootCmd = &cobra.Command{+ Use: "reboot <sandbox-id>",+ Short: "Soft restart of a running sandbox (guest-only kernel reboot, disks preserved)",+ Long: `Soft restart of a running sandbox via in-guest reset.++The QEMU process, network mapping, and persistent disks all stay; only+the guest CPU is reset and the kernel reboots from scratch. Recovers+from in-guest wedges: zombie pile-ups, OOM-killed agents, runaway+processes, broken-but-isolated systemd state.++For the rare case where the QEMU process itself is wedged, use+'oc sandbox power-cycle' instead.`,+ Args: cobra.ExactArgs(1),+ RunE: func(cmd *cobra.Command, args []string) error {+ c := client.FromContext(cmd.Context())+ if err := c.Post(cmd.Context(), "/sandboxes/"+args[0]+"/reboot", nil, nil); err != nil {+ return err+ }+ fmt.Printf("Sandbox %s rebooted.\n", args[0])+ return nil+ },+}++var sandboxPowerCycleCmd = &cobra.Command{+ Use: "power-cycle <sandbox-id>",+ Short: "Hard restart of a sandbox (kill QEMU + cold-boot, drives preserved)",+ Long: `Hard restart of a sandbox.++The QEMU process is killed and a fresh one is started with the same+on-disk drives (rootfs.qcow2 + workspace.qcow2). The sandbox keeps its+ID, project, secrets, env, and persistent workspace data; gets a new+external host port and TAP. Use when the QEMU process itself is wedged+or 'oc sandbox reboot' didn't recover.`,+ Args: cobra.ExactArgs(1),+ RunE: func(cmd *cobra.Command, args []string) error {+ c := client.FromContext(cmd.Context())+ if err := c.Post(cmd.Context(), "/sandboxes/"+args[0]+"/power-cycle", nil, nil); err != nil {+ return err+ }+ fmt.Printf("Sandbox %s power-cycled.\n", args[0])+ return nil+ },+}+var sandboxSetTimeoutCmd = &cobra.Command{Use: "set-timeout <sandbox-id> <seconds>",Short: "Update sandbox timeout",@@ -241,6 +285,8 @@ func init() {sandboxCmd.AddCommand(sandboxKillCmd)sandboxCmd.AddCommand(sandboxHibernateCmd)sandboxCmd.AddCommand(sandboxWakeCmd)+ sandboxCmd.AddCommand(sandboxRebootCmd)+ sandboxCmd.AddCommand(sandboxPowerCycleCmd)sandboxCmd.AddCommand(sandboxSetTimeoutCmd)}diff --git a/cmd/oc/internal/commands/scaling.go b/cmd/oc/internal/commands/scaling.gonew file mode 100644index 00000000..bd4024e7--- /dev/null+++ b/cmd/oc/internal/commands/scaling.go@@ -0,0 +1,206 @@+package commands++import (+ "fmt"++ "github.com/opensandbox/opensandbox/cmd/oc/internal/client"+ "github.com/spf13/cobra"+)++var sandboxScaleCmd = &cobra.Command{+ Use: "scale <sandbox-id> <memory-mb>",+ Short: "Manually resize a sandbox",+ Long: `Manually resize a sandbox to a specific memory tier. CPU follows memory+per the platform's tier table (e.g. 8 GB → 4 vCPU). Allowed tiers:+1024, 4096, 8192, 16384, 32768, 65536 MB.++A manual scale disables autoscale on this sandbox as a side effect; re-+enable with 'oc sandbox autoscale --on' if you want it back.++Errors:+ scaling_locked Sandbox has a scaling lock — unlock first.+ 402 Payment... Requested size exceeds your plan cap.`,+ Args: cobra.ExactArgs(2),+ RunE: func(cmd *cobra.Command, args []string) error {+ c := client.FromContext(cmd.Context())++ var memoryMB int+ if _, err := fmt.Sscanf(args[1], "%d", &memoryMB); err != nil || memoryMB <= 0 {+ return fmt.Errorf("invalid memory-mb: %s", args[1])+ }++ var resp struct {+ SandboxID string `json:"sandboxID"`+ MemoryMB int `json:"memoryMB"`+ CPUPercent int `json:"cpuPercent"`+ }+ if err := c.Post(cmd.Context(), "/sandboxes/"+args[0]+"/scale", map[string]int{"memoryMB": memoryMB}, &resp); err != nil {+ return err+ }++ printer.Print(resp, func() {+ fmt.Printf("Scaled %s to %dMB / %d%% CPU\n", resp.SandboxID, resp.MemoryMB, resp.CPUPercent)+ })+ return nil+ },+}++var sandboxAutoscaleCmd = &cobra.Command{+ Use: "autoscale <sandbox-id>",+ Short: "Configure or inspect per-sandbox autoscale",+ Long: `Configure or inspect per-sandbox autoscale.++Run with no flags to print the current configuration.+Use --on with --min/--max to enable; --off to disable.++When enabled, the platform resizes the sandbox between min and max based+on observed memory pressure: scale up fast on a 1-min spike (>75%), scale+down only after sustained idle (1m + 5m + 15m all below 25%, 5-min+cooldown).++Errors:+ scaling_locked Sandbox has a scaling lock — unlock first to enable.+ 402 Payment... --max exceeds your plan cap.`,+ Args: cobra.ExactArgs(1),+ RunE: func(cmd *cobra.Command, args []string) error {+ c := client.FromContext(cmd.Context())+ on, _ := cmd.Flags().GetBool("on")+ off, _ := cmd.Flags().GetBool("off")+ minMB, _ := cmd.Flags().GetInt("min")+ maxMB, _ := cmd.Flags().GetInt("max")++ // No flags → status+ if !on && !off && minMB == 0 && maxMB == 0 {+ var status struct {+ SandboxID string `json:"sandboxID"`+ Enabled bool `json:"enabled"`+ MinMemoryMB int `json:"minMemoryMB"`+ MaxMemoryMB int `json:"maxMemoryMB"`+ }+ if err := c.Get(cmd.Context(), "/sandboxes/"+args[0]+"/autoscale", &status); err != nil {+ return err+ }+ printer.Print(status, func() {+ if status.Enabled {+ fmt.Printf("Autoscale enabled for %s (%d–%d MB)\n", status.SandboxID, status.MinMemoryMB, status.MaxMemoryMB)+ } else {+ fmt.Printf("Autoscale disabled for %s\n", status.SandboxID)+ }+ })+ return nil+ }++ if on && off {+ return fmt.Errorf("--on and --off are mutually exclusive")+ }++ body := map[string]interface{}{"enabled": on}+ if on {+ if minMB == 0 || maxMB == 0 {+ return fmt.Errorf("--on requires both --min and --max")+ }+ body["minMemoryMB"] = minMB+ body["maxMemoryMB"] = maxMB+ }++ var resp struct {+ SandboxID string `json:"sandboxID"`+ Enabled bool `json:"enabled"`+ MinMemoryMB int `json:"minMemoryMB"`+ MaxMemoryMB int `json:"maxMemoryMB"`+ }+ if err := c.PutJSON(cmd.Context(), "/sandboxes/"+args[0]+"/autoscale", body, &resp); err != nil {+ return err+ }+ printer.Print(resp, func() {+ if resp.Enabled {+ fmt.Printf("Autoscale enabled for %s (%d–%d MB)\n", resp.SandboxID, resp.MinMemoryMB, resp.MaxMemoryMB)+ } else {+ fmt.Printf("Autoscale disabled for %s\n", resp.SandboxID)+ }+ })+ return nil+ },+}++var sandboxLockCmd = &cobra.Command{+ Use: "lock <sandbox-id>",+ Short: "Pin a sandbox at its current size (block scaling)",+ Long: `Lock the sandbox against any size change. While locked, both 'scale'+and 'autoscale --on' are rejected with a scaling_locked error, and the+platform autoscaler skips the sandbox entirely.++Locking ALSO disables autoscale (single-knob: "I don't want this scaling,+period"). Unlocking does NOT re-enable autoscale; run 'autoscale --on'+explicitly if you want it back.`,+ Args: cobra.ExactArgs(1),+ RunE: func(cmd *cobra.Command, args []string) error {+ return setScalingLock(cmd, args[0], true)+ },+}++var sandboxUnlockCmd = &cobra.Command{+ Use: "unlock <sandbox-id>",+ Short: "Allow scaling on a sandbox again (clear the lock)",+ Args: cobra.ExactArgs(1),+ RunE: func(cmd *cobra.Command, args []string) error {+ return setScalingLock(cmd, args[0], false)+ },+}++var sandboxLockStatusCmd = &cobra.Command{+ Use: "lock-status <sandbox-id>",+ Short: "Show the scaling-lock state of a sandbox",+ Args: cobra.ExactArgs(1),+ RunE: func(cmd *cobra.Command, args []string) error {+ c := client.FromContext(cmd.Context())+ var resp struct {+ SandboxID string `json:"sandboxID"`+ Locked bool `json:"locked"`+ }+ if err := c.Get(cmd.Context(), "/sandboxes/"+args[0]+"/scaling-lock", &resp); err != nil {+ return err+ }+ printer.Print(resp, func() {+ if resp.Locked {+ fmt.Printf("Sandbox %s is LOCKED (no scaling)\n", resp.SandboxID)+ } else {+ fmt.Printf("Sandbox %s is unlocked\n", resp.SandboxID)+ }+ })+ return nil+ },+}++func setScalingLock(cmd *cobra.Command, sandboxID string, locked bool) error {+ c := client.FromContext(cmd.Context())+ var resp struct {+ SandboxID string `json:"sandboxID"`+ Locked bool `json:"locked"`+ }+ body := map[string]bool{"locked": locked}+ if err := c.PutJSON(cmd.Context(), "/sandboxes/"+sandboxID+"/scaling-lock", body, &resp); err != nil {+ return err+ }+ printer.Print(resp, func() {+ if resp.Locked {+ fmt.Printf("Sandbox %s locked (scaling disabled)\n", resp.SandboxID)+ } else {+ fmt.Printf("Sandbox %s unlocked\n", resp.SandboxID)+ }+ })+ return nil+}++func init() {+ sandboxAutoscaleCmd.Flags().Bool("on", false, "Enable autoscale (requires --min and --max)")+ sandboxAutoscaleCmd.Flags().Bool("off", false, "Disable autoscale")+ sandboxAutoscaleCmd.Flags().Int("min", 0, "Minimum memory tier in MB (allowed: 1024, 4096, 8192, 16384, 32768, 65536)")+ sandboxAutoscaleCmd.Flags().Int("max", 0, "Maximum memory tier in MB (allowed: 1024, 4096, 8192, 16384, 32768, 65536)")++ sandboxCmd.AddCommand(sandboxScaleCmd)+ sandboxCmd.AddCommand(sandboxAutoscaleCmd)+ sandboxCmd.AddCommand(sandboxLockCmd)+ sandboxCmd.AddCommand(sandboxUnlockCmd)+ sandboxCmd.AddCommand(sandboxLockStatusCmd)+}diff --git a/cmd/server/main.go b/cmd/server/main.goindex 2b52bb66..1eea671d 100644--- a/cmd/server/main.go+++ b/cmd/server/main.go@@ -2,13 +2,15 @@ package mainimport ("context"+ "encoding/base64""fmt""log"+ "log/slog""os"- "strings""os/signal"+ "strconv"+ "strings""syscall"-"time""github.com/opensandbox/opensandbox/internal/api"@@ -20,6 +22,8 @@ import ("github.com/opensandbox/opensandbox/internal/controlplane""github.com/opensandbox/opensandbox/internal/crypto""github.com/opensandbox/opensandbox/internal/db"+ "github.com/opensandbox/opensandbox/internal/metrics"+ "github.com/opensandbox/opensandbox/internal/obslog""github.com/opensandbox/opensandbox/internal/observability""github.com/opensandbox/opensandbox/internal/proxy""github.com/opensandbox/opensandbox/internal/sandbox"@@ -47,6 +51,21 @@ func main() {log.Fatalf("failed to load config: %v", err)}+ // Structured logging (JSON to stdout, host envelope baked in). Installs+ // itself as slog.Default AND redirects stdlib log.Printf through slog so+ // existing log call sites emit JSON automatically. Vector reads stdout+ // from the Docker logging driver and ships to Axiom.+ cpHostname, _ := os.Hostname()+ obslog.Init(obslog.HostFields{+ Service: obslog.ServiceControlPlane,+ ServiceID: cpHostname, // hostname distinguishes HA replicas+ CellID: cfg.CellID,+ Region: cfg.Region,+ Hostname: cpHostname,+ HostIP: cfg.HostIP,+ Version: ServerVersion,+ }, slog.LevelInfo)+// Sentry error reporting — no-op if OPENSANDBOX_SENTRY_DSN is unset.flushSentry := observability.Init(cfg, "control-plane", ServerVersion)defer flushSentry()@@ -215,6 +234,13 @@ func main() {}}+ // Hoisted at function scope so the per-sandbox autoscaler (created+ // later, after the API server) can consult IsLeader() each tick — keeps+ // a single elector authoritative across both the cluster scaler and the+ // per-sandbox autoscaler in HA setups. nil when there's no compute pool+ // (combined / dev mode) — autoscaler then runs unconditionally.+ var leaderElector *controlplane.LeaderElector+// Initialize compute pool + autoscaler (server mode)if cfg.Mode == "server" && redisRegistry != nil {// Build the WorkerSpec: cloud-neutral config that the CP supplies to@@ -274,15 +300,107 @@ func main() {switch provider {case "azure":+ // Build worker env template — new VMs get this via cloud-init.+ // GRPC_ADVERTISE, HTTP_ADDR, and WORKER_ID are patched by cloud-init+ // with the VM's actual private IP and hostname.+ // Workers need to reach Postgres/Redis on the control plane's private IP,+ // not localhost. Replace localhost with the control plane's IP.+ cpIP := os.Getenv("OPENSANDBOX_CONTROLPLANE_IP")+ workerDBURL := cfg.DatabaseURL+ workerRedisURL := cfg.RedisURL+ if cpIP != "" {+ workerDBURL = strings.ReplaceAll(workerDBURL, "localhost", cpIP)+ workerDBURL = strings.ReplaceAll(workerDBURL, "127.0.0.1", cpIP)+ workerRedisURL = strings.ReplaceAll(workerRedisURL, "localhost", cpIP)+ workerRedisURL = strings.ReplaceAll(workerRedisURL, "127.0.0.1", cpIP)+ }++ // Warn loud if we're about to bake an empty AXIOM_INGEST_TOKEN+ // into a worker. Reachable when the server's cfg was empty at+ // startup but the secret has since been added to KV and no+ // restart has happened yet — every worker minted from here will+ // silently skip log shipping.+ if cfg.AxiomIngestToken == "" {+ log.Printf("opensandbox: WARNING: spawning Azure-pool worker with empty AXIOM_INGEST_TOKEN — this worker will not ship sandbox session logs (restart this control plane after the secret is in KV)")+ }++ workerEnv := fmt.Sprintf(+ "OPENSANDBOX_MODE=worker\n"++ "OPENSANDBOX_VM_BACKEND=qemu\n"++ "OPENSANDBOX_QEMU_BIN=qemu-system-x86_64\n"++ "OPENSANDBOX_DATA_DIR=/data/sandboxes\n"++ "OPENSANDBOX_KERNEL_PATH=/opt/opensandbox/vmlinux\n"++ "OPENSANDBOX_IMAGES_DIR=/data/firecracker/images\n"++ "OPENSANDBOX_GRPC_ADVERTISE=PLACEHOLDER:9090\n"++ "OPENSANDBOX_HTTP_ADDR=http://PLACEHOLDER:8081\n"++ "OPENSANDBOX_JWT_SECRET=%s\n"++ "OPENSANDBOX_WORKER_ID=PLACEHOLDER\n"++ "OPENSANDBOX_REGION=%s\n"++ "OPENSANDBOX_MAX_CAPACITY=%d\n"++ "OPENSANDBOX_PORT=8081\n"++ "OPENSANDBOX_DEFAULT_SANDBOX_MEMORY_MB=%d\n"++ "OPENSANDBOX_DEFAULT_SANDBOX_CPUS=%d\n"++ "OPENSANDBOX_DATABASE_URL=%s\n"++ "OPENSANDBOX_REDIS_URL=%s\n"++ "OPENSANDBOX_S3_BUCKET=%s\n"++ "OPENSANDBOX_S3_REGION=%s\n"++ "OPENSANDBOX_S3_ENDPOINT=%s\n"++ "OPENSANDBOX_S3_ACCESS_KEY_ID=%s\n"++ "OPENSANDBOX_S3_SECRET_ACCESS_KEY=%s\n"++ "OPENSANDBOX_S3_FORCE_PATH_STYLE=%v\n"++ "OPENSANDBOX_S3_FALLBACK_ENDPOINT=%s\n"++ "OPENSANDBOX_S3_FALLBACK_REGION=%s\n"++ "OPENSANDBOX_S3_FALLBACK_ACCESS_KEY_ID=%s\n"++ "OPENSANDBOX_S3_FALLBACK_SECRET_ACCESS_KEY=%s\n"++ "OPENSANDBOX_S3_FALLBACK_FORCE_PATH_STYLE=%v\n"++ "OPENSANDBOX_S3_FALLBACK_BUCKET=%s\n"++ "OPENSANDBOX_BLOB_MIGRATION_MODE=%v\n"++ "OPENSANDBOX_SANDBOX_DOMAIN=%s\n"++ "OPENSANDBOX_DEFAULT_SANDBOX_DISK_MB=%d\n"++ "OPENSANDBOX_AZURE_KEY_VAULT_NAME=%s\n"++ "SEGMENT_WRITE_KEY=%s\n"++ "AXIOM_INGEST_TOKEN=%s\n"++ "AXIOM_DATASET=%s\n",+ cfg.JWTSecret,+ cfg.Region,+ cfg.MaxCapacity,+ cfg.DefaultSandboxMemoryMB,+ cfg.DefaultSandboxCPUs,+ workerDBURL,+ workerRedisURL,+ cfg.S3Bucket,+ cfg.S3Region,+ cfg.S3Endpoint,+ cfg.S3AccessKeyID,+ cfg.S3SecretAccessKey,+ cfg.S3ForcePathStyle,+ cfg.S3FallbackEndpoint,+ cfg.S3FallbackRegion,+ cfg.S3FallbackAccessKeyID,+ cfg.S3FallbackSecretAccessKey,+ cfg.S3FallbackForcePathStyle,+ cfg.S3FallbackBucket,+ cfg.BlobMigrationMode,+ cfg.SandboxDomain,+ cfg.DefaultSandboxDiskMB,+ cfg.AzureKeyVaultName,+ cfg.SegmentWriteKey,+ cfg.AxiomIngestToken,+ cfg.AxiomDataset,+ )+ workerEnvB64 := base64.StdEncoding.EncodeToString([]byte(workerEnv))+azPool, err := compute.NewAzurePool(compute.AzurePoolConfig{- SubscriptionID: cfg.AzureSubscriptionID,- ResourceGroup: cfg.AzureResourceGroup,- Region: cfg.Region,- VMSize: cfg.AzureVMSize,- ImageID: cfg.AzureImageID,- SubnetID: cfg.AzureSubnetID,- SSHPublicKey: cfg.AzureSSHPublicKey,- KeyVaultName: cfg.AzureKeyVaultName,+ SubscriptionID: cfg.AzureSubscriptionID,+ ResourceGroup: cfg.AzureResourceGroup,+ Region: cfg.Region,+ VMSize: cfg.AzureVMSize,+ ImageID: cfg.AzureImageID,+ SubnetID: cfg.AzureSubnetID,+ SSHPublicKey: cfg.AzureSSHPublicKey,+ KeyVaultName: cfg.AzureKeyVaultName,+ WorkerIdentityID: cfg.AzureWorkerIdentityID,+ WorkerEnvBase64: workerEnvB64,})if err != nil {log.Fatalf("opensandbox: failed to create Azure pool: %v", err)@@ -333,33 +451,50 @@ func main() {}if pool != nil {+ // Pick the per-provider ranked size list. Empty → scaler defers to+ // the pool's single configured default (cfg.AzureVMSize / cfg.EC2InstanceType).+ var machineSizes []string+ switch {+ case len(cfg.AzureVMSizes) > 0 && cfg.AzureSubscriptionID != "":+ machineSizes = cfg.AzureVMSizes+ case len(cfg.EC2InstanceTypes) > 0 && (cfg.EC2AMI != "" || cfg.EC2SSMParameterName != ""):+ machineSizes = cfg.EC2InstanceTypes+ }+ if len(machineSizes) > 0 {+ log.Printf("opensandbox: scaler size fallback ranked: %v", machineSizes)+ }+scalerState := controlplane.NewRedisScalerState(redisRegistry.RedisClient())scaler := controlplane.NewScaler(controlplane.ScalerConfig{- Pool: pool,- Registry: redisRegistry,- Store: opts.Store,- StateStore: scalerState,- WorkerImage: cfg.EC2WorkerImage,- Cooldown: time.Duration(cfg.ScaleCooldownSec) * time.Second,- MinWorkers: cfg.MinWorkersPerRegion,- MaxWorkers: cfg.MaxWorkersPerRegion,- IdleReserve: cfg.IdleReserveWorkers,+ Pool: pool,+ Registry: redisRegistry,+ Store: opts.Store,+ StateStore: scalerState,+ WorkerImage: cfg.EC2WorkerImage,+ Cooldown: time.Duration(cfg.ScaleCooldownSec) * time.Second,+ MinWorkers: cfg.MinWorkersPerRegion,+ MaxWorkers: cfg.MaxWorkersPerRegion,+ IdleReserve: cfg.IdleReserveWorkers,+ MachineSizes: machineSizes,})defer scaler.Stop()- // Leader election: only the leader runs the scaler- elector := controlplane.NewLeaderElector(redisRegistry.RedisClient(), cfg.WorkerID)- elector.OnBecomeLeader(func() {+ // Leader election: only the leader runs the scaler. The+ // per-sandbox autoscaler (created later) consults this same+ // elector via IsLeader() to skip ticks when not leader, so we+ // don't double-fire scale decisions across CPs in HA setups.+ leaderElector = controlplane.NewLeaderElector(redisRegistry.RedisClient(), cfg.WorkerID)+ leaderElector.OnBecomeLeader(func() {scaler.Start()log.Printf("opensandbox: became leader, autoscaler started (%s)", poolName)})- elector.OnLoseLeadership(func() {+ leaderElector.OnLoseLeadership(func() {scaler.Stop()log.Println("opensandbox: lost leadership, autoscaler stopped")})- elector.Start()- defer elector.Stop()- log.Printf("opensandbox: leader election started (instance=%s)", elector.InstanceID())+ leaderElector.Start()+ defer leaderElector.Stop()+ log.Printf("opensandbox: leader election started (instance=%s)", leaderElector.InstanceID())}}@@ -415,6 +550,7 @@ func main() {var stripeClient *billing.StripeClientif cfg.StripeSecretKey != "" {stripeClient = billing.NewStripeClient(cfg.StripeSecretKey, cfg.StripeWebhookSecret, cfg.StripeSuccessURL, cfg.StripeCancelURL)+ stripeClient.TelegramAgentPriceID = cfg.StripeTelegramAgentPriceIDif err := stripeClient.EnsureProducts(); err != nil {log.Printf("opensandbox: Stripe product setup failed: %v (billing may not work)", err)} else {@@ -426,6 +562,50 @@ func main() {// Create API serverserver := api.NewServer(mgr, ptyMgr, cfg.APIKey, opts)+ // Wire Axiom read-only token for the sandbox session logs API.+ // Token never leaves this process; the UI proxies its queries through+ // /api/sandboxes/:id/logs. Empty token disables the endpoint (503).+ server.SetAxiomQueryConfig(cfg.AxiomQueryToken, cfg.AxiomDataset)+ if cfg.AxiomQueryToken != "" {+ log.Printf("opensandbox: sandbox session logs read API enabled (dataset=%s)", cfg.AxiomDataset)+ }++ // Worker-bake side: report whether sandboxes spawned by this control+ // plane will ship logs. The token's value here is whatever cfg.Load+ // pulled from os.Getenv at startup; it stays frozen until the next+ // process restart. If a deployment puts the secret in KV but never+ // restarts this process, every Azure-pool worker baked from here on+ // will land with an empty AXIOM_INGEST_TOKEN and silently skip+ // shipping. Logging once at startup turns the silent case into a+ // paged-on-able journalctl line.+ if cfg.AxiomIngestToken != "" {+ log.Printf("opensandbox: workers spawned by this server will ship sandbox session logs to Axiom (dataset=%s)", cfg.AxiomDataset)+ } else {+ log.Printf("opensandbox: WARNING: AXIOM_INGEST_TOKEN empty — workers spawned by this server will NOT ship sandbox session logs (set the secret in your secret store and restart this process)")+ }++ // Per-sandbox autoscaler. Tier-aligned (1/4/8/16 GB), opt-in per+ // sandbox via PUT /api/sandboxes/:id/autoscale.+ //+ // Leader-gated when an elector exists. With HA (multiple CPs) we don't+ // want two instances both reading stats and double-firing scale events.+ // SetSandboxLimits is technically idempotent for memory targets, but+ // the cooldown CAS races and the cooldown timestamp gets clobbered if+ // both CPs UPDATE — see ClaimAutoscaleEvent. Gating on the leader is+ // cheaper than relying on the CAS alone. When there's no elector+ // (single-CP / no cloud pool), isLeader is nil and the loop runs+ // unconditionally.+ if opts.Store != nil && redisRegistry != nil {+ var isLeader func() bool+ if leaderElector != nil {+ isLeader = leaderElector.IsLeader+ }+ autoscaler := controlplane.NewAutoscaler(opts.Store, redisRegistry, api.NewAutoscalerSetter(server), isLeader)+ autoscaler.Start(ctx)+ defer autoscaler.Stop()+ log.Println("opensandbox: per-sandbox autoscaler started (interval=30s, leader-gated)")+ }+// Start usage reporter — reports Pro org usage to Stripe and deducts// free-tier trial credits (force-hibernates on empty) every 5 min.// redisRegistry may be nil in combined mode; reporter tolerates that by@@ -441,6 +621,42 @@ func main() {log.Println("opensandbox: usage reporter started (interval=5m)")}+ // Phase-2 capacity allocator. Writes outbox rows for unified-mode+ // pro orgs after each settled bucket. Allocator skips legacy and+ // free orgs (see ListAllocatorCandidates); rollback is by+ // reverting the deploy.+ if opts.Store != nil {+ allocOpts := billing.CapacityReconcilerOpts{+ Interval: getDurationEnv("CAPACITY_ALLOCATOR_INTERVAL", 5*time.Minute),+ Settle: getDurationEnv("CAPACITY_ALLOCATOR_SETTLE", 30*time.Minute),+ Lookback: getDurationEnv("CAPACITY_ALLOCATOR_LOOKBACK", 24*time.Hour),+ Limit: getIntEnv("CAPACITY_ALLOCATOR_BATCH_LIMIT", 500),+ }+ allocator := billing.NewCapacityReconciler(opts.Store, allocOpts)+ allocator.Start()+ defer allocator.Stop()+ log.Printf("opensandbox: capacity allocator started (interval=%s, settle=%s, lookback=%s)",+ allocOpts.Interval, allocOpts.Settle, allocOpts.Lookback)+ }++ // Phase-3 billable-events sender. Ships pending outbox rows to+ // Stripe via meter events for orgs in `billing_mode='unified'`+ // with a Stripe customer ID. New orgs default to unified per+ // migration 031; existing orgs are pinned to legacy and stay+ // untouched on UsageReporter. Idempotency is per-row via+ // `billable_events.id` as Stripe meter event Identifier.+ if opts.Store != nil && stripeClient != nil {+ senderOpts := billing.BillableEventsSenderOpts{+ Interval: getDurationEnv("BILLABLE_EVENTS_SENDER_INTERVAL", 5*time.Minute),+ Batch: getIntEnv("BILLABLE_EVENTS_SENDER_BATCH", 200),+ }+ sender := billing.NewBillableEventsSender(opts.Store, stripeClient, senderOpts)+ sender.Start()+ defer sender.Stop()+ log.Printf("opensandbox: billable events sender started (interval=%s, batch=%d)",+ senderOpts.Interval, senderOpts.Batch)+ }+// Start NATS sync consumer if both PG and NATS are configuredif opts.Store != nil && cfg.NATSURL != "" {consumer, err := db.NewSyncConsumer(opts.Store, cfg.NATSURL)@@ -463,6 +679,13 @@ func main() {addr := fmt.Sprintf(":%d", cfg.Port)log.Printf("opensandbox: starting server on %s (mode=%s)", addr, cfg.Mode)+ // Prometheus /metrics endpoint on a separate port. Different from the+ // worker's :9091 so a dev-host (worker+server on one VM) doesn't collide.+ // Vector scrapes this and ships to Axiom alongside platform logs.+ metricsSrv := metrics.StartMetricsServer(":9092")+ defer metricsSrv.Close()+ log.Println("opensandbox: metrics server started on :9092")+go func() {if err := server.Start(addr); err != nil {log.Printf("server error: %v", err)@@ -490,3 +713,26 @@ func main() {}log.Println("opensandbox: server stopped")}++// getDurationEnv reads a Go duration string (e.g. "5m", "30m", "24h")+// from env or returns the default. Used for the capacity allocator+// knobs which are off the hot path of config.Load().+func getDurationEnv(key string, def time.Duration) time.Duration {+ if v := os.Getenv(key); v != "" {+ if d, err := time.ParseDuration(v); err == nil {+ return d+ }+ log.Printf("opensandbox: invalid duration in %s=%q, using default %s", key, v, def)+ }+ return def+}++func getIntEnv(key string, def int) int {+ if v := os.Getenv(key); v != "" {+ if n, err := strconv.Atoi(v); err == nil {+ return n+ }+ log.Printf("opensandbox: invalid int in %s=%q, using default %d", key, v, def)+ }+ return def+}diff --git a/cmd/worker/main.go b/cmd/worker/main.goindex fe8e8fcc..5426e4dc 100644--- a/cmd/worker/main.go+++ b/cmd/worker/main.go@@ -5,6 +5,7 @@ import ("fmt""io""log"+ "log/slog""os""os/signal""path/filepath"@@ -20,6 +21,7 @@ import ("github.com/opensandbox/opensandbox/internal/db""github.com/opensandbox/opensandbox/internal/metrics""github.com/opensandbox/opensandbox/internal/observability"+ "github.com/opensandbox/opensandbox/internal/obslog""github.com/opensandbox/opensandbox/internal/proxy"qm "github.com/opensandbox/opensandbox/internal/qemu""github.com/opensandbox/opensandbox/internal/sandbox"@@ -93,6 +95,21 @@ func main() {log.Fatalf("failed to load config: %v", err)}+ // Structured logging (JSON to stdout/journald, host envelope baked in).+ // Installs itself as slog.Default AND redirects stdlib log.Printf through+ // slog so existing log call sites emit JSON automatically. Vector on the+ // host reads journald and ships to Axiom.+ workerHostname, _ := os.Hostname()+ obslog.Init(obslog.HostFields{+ Service: obslog.ServiceWorker,+ ServiceID: cfg.WorkerID,+ CellID: cfg.CellID,+ Region: cfg.Region,+ Hostname: workerHostname,+ HostIP: cfg.HostIP,+ Version: WorkerVersion,+ }, slog.LevelInfo)+// Sentry error reporting — no-op if OPENSANDBOX_SENTRY_DSN is unset.flushSentry := observability.Init(cfg, "worker", WorkerVersion)defer flushSentry()@@ -118,7 +135,32 @@ func main() {// Initialize secrets proxy for MITM token substitution.// Runs on :3128 — VMs route HTTPS through this to keep real secrets off-VM.- secretsCA, err := secretsproxy.LoadOrCreateCA(filepath.Join(cfg.DataDir, "proxy-ca"))+ //+ // CA must be region-scoped (shared across all workers in the same KV)+ // so live migration of a sandbox doesn't break TLS substitution. The+ // guest's trust store has the source worker's CA cert baked in; if the+ // destination presents certs signed by a different CA, every outbound+ // HTTPS call after migration fails with "authority and subject key+ // identifier mismatch". With KV-backed shared CA, every worker in the+ // region presents the same cert and migration is transparent.+ //+ // Falls back to per-worker CA when no KV is configured (dev / EC2+ // without SSM bridging) — single-worker setups still work, but live+ // migration of secrets-using sandboxes will fail TLS until a shared+ // store is wired.+ caDir := filepath.Join(cfg.DataDir, "proxy-ca")+ var kvStore secretsproxy.KVStore+ if cfg.AzureKeyVaultName != "" {+ if kv, kvErr := secretsproxy.NewAzureKVStore(cfg.AzureKeyVaultName); kvErr != nil {+ log.Printf("opensandbox-worker: shared CA: KV client failed (%v) — falling back to per-worker CA", kvErr)+ } else {+ kvStore = kv+ log.Printf("opensandbox-worker: shared CA: using Azure Key Vault %s", cfg.AzureKeyVaultName)+ }+ }+ caCtx, caCancel := context.WithTimeout(context.Background(), 30*time.Second)+ secretsCA, err := secretsproxy.LoadOrCreateSharedCA(caCtx, kvStore, "proxy-ca-cert", "proxy-ca-key", caDir)+ caCancel()if err != nil {log.Printf("opensandbox-worker: secrets proxy CA failed: %v (secrets proxy disabled)", err)}@@ -128,6 +170,15 @@ func main() {if err != nil {log.Printf("opensandbox-worker: secrets proxy listen failed: %v", err)} else {+ // Make 169.254.169.253:3128 reachable from every TAP via lo. The+ // proxy already binds 0.0.0.0:3128 so this is just the host-side+ // address the kernel should answer. Without this, VMs created+ // with the new HTTPS_PROXY env (anycast) can't reach the proxy.+ if anyErr := secretsproxy.EnsureAnycastInterface(); anyErr != nil {+ log.Printf("opensandbox-worker: WARNING: failed to set up secrets-proxy anycast address (%v) — VMs with anycast HTTPS_PROXY env will lose outbound until this is fixed", anyErr)+ } else {+ log.Printf("opensandbox-worker: secrets-proxy anycast address %s assigned to lo", secretsproxy.AnycastIP)+ }secretsProxy.Start()defer secretsProxy.Stop()log.Println("opensandbox-worker: secrets proxy started on :3128")@@ -163,8 +214,12 @@ func main() {var globalBlob blobstore.Storeif blobPrimary != nil {if blobFallback != nil {- globalBlob, _ = blobstore.NewFallback(blobPrimary, blobFallback)- log.Printf("opensandbox-worker: global blob store: %s primary, %s fallback", blobPrimary.Name(), blobFallback.Name())+ if cfg.BlobMigrationMode {+ globalBlob, _ = blobstore.NewMigrationFallback(blobPrimary, blobFallback)+ } else {+ globalBlob, _ = blobstore.NewFallback(blobPrimary, blobFallback)+ }+ log.Printf("opensandbox-worker: global blob store: %s primary, %s fallback (migration=%v)", blobPrimary.Name(), blobFallback.Name(), cfg.BlobMigrationMode)} else {globalBlob = blobPrimarylog.Printf("opensandbox-worker: global blob store: %s (no fallback)", blobPrimary.Name())@@ -174,15 +229,16 @@ func main() {}qmCfg := qm.Config{- DataDir: cfg.DataDir,- KernelPath: cfg.KernelPath,- ImagesDir: cfg.ImagesDir,- QEMUBin: cfg.QEMUBin,- AgentBinaryPath: "/usr/local/bin/osb-agent",- AgentVersion: AgentVersion,- DefaultMemoryMB: cfg.DefaultSandboxMemoryMB,- DefaultCPUs: cfg.DefaultSandboxCPUs,- DefaultDiskMB: cfg.DefaultSandboxDiskMB,+ DataDir: cfg.DataDir,+ KernelPath: cfg.KernelPath,+ ImagesDir: cfg.ImagesDir,+ QEMUBin: cfg.QEMUBin,+ AgentBinaryPath: "/usr/local/bin/osb-agent",+ AgentVersion: AgentVersion,+ Region: cfg.Region,+ DefaultMemoryMB: cfg.DefaultSandboxMemoryMB,+ DefaultCPUs: cfg.DefaultSandboxCPUs,+ DefaultDiskMB: cfg.DefaultSandboxDiskMB,GlobalBlob: globalBlob,GlobalBlobGoldensBucket: cfg.GlobalBlobGoldensBucket,GlobalBlobGoldenKey: "default.ext4",@@ -201,6 +257,12 @@ func main() {qmMgr.CleanupOrphanedProcesses()+ // Start the periodic orphan reaper. Catches qemu processes that+ // survived a destroyVM-path failure (state-inconsistency / panic /+ // hibernate race) so they don't pile up and silently shrink worker+ // capacity. See internal/qemu/orphan_reaper.go.+ qmMgr.StartOrphanReaper(ctx)+// Prepare golden snapshot for fast VM creationif err := qmMgr.PrepareGoldenSnapshot(); err != nil {log.Printf("opensandbox-worker: WARNING: golden snapshot failed, using cold boot: %v", err)@@ -294,22 +356,42 @@ func main() {}jwtIssuer := auth.NewJWTIssuer(cfg.JWTSecret)- // S3 checkpoint store+ // Checkpoint store — built on top of a blobstore.Store. The primary+ // endpoint is OPENSANDBOX_S3_*; an optional secondary OPENSANDBOX_S3_FALLBACK_*+ // provides HA / lazy-migration fallback. Migration semantics (NotFound+ // cascades to fallback) are gated on cfg.BlobMigrationMode.var checkpointStore *storage.CheckpointStoreif cfg.S3Bucket != "" {- var err error- checkpointStore, err = storage.NewCheckpointStore(storage.S3Config{- Endpoint: cfg.S3Endpoint,- Bucket: cfg.S3Bucket,- Region: cfg.S3Region,- AccessKeyID: cfg.S3AccessKeyID,- SecretAccessKey: cfg.S3SecretAccessKey,- ForcePathStyle: cfg.S3ForcePathStyle,- })+ // Primary: no bucket override (CheckpointStore passes cfg.S3Bucket per call).+ cpPrimary, err := buildCheckpointBackend("primary", cfg.S3Endpoint, cfg.S3Region, cfg.S3AccessKeyID, cfg.S3SecretAccessKey, "", cfg.S3ForcePathStyle)+ if err != nil {+ log.Fatalf("failed to build checkpoint store primary: %v", err)+ }+ if cpPrimary == nil {+ log.Fatalf("OPENSANDBOX_S3_BUCKET set but primary backend has no credentials")+ }+ // Fallback: if S3FallbackBucket is set, the fallback uses its own+ // bucket name (e.g. Azure container "checkpoints") regardless of+ // what bucket the primary uses (e.g. Tigris bucket "opencomputer-prod").+ cpFallback, err := buildCheckpointBackend("fallback", cfg.S3FallbackEndpoint, cfg.S3FallbackRegion, cfg.S3FallbackAccessKeyID, cfg.S3FallbackSecretAccessKey, cfg.S3FallbackBucket, cfg.S3FallbackForcePathStyle)if err != nil {- log.Fatalf("failed to initialize checkpoint store: %v", err)+ log.Fatalf("failed to build checkpoint store fallback: %v", err)}- log.Printf("opensandbox-worker: S3 checkpoint store configured (bucket=%s, region=%s)", cfg.S3Bucket, cfg.S3Region)++ var cpStore blobstore.Store = cpPrimary+ if cpFallback != nil {+ if cfg.BlobMigrationMode {+ cpStore, _ = blobstore.NewMigrationFallback(cpPrimary, cpFallback)+ } else {+ cpStore, _ = blobstore.NewFallback(cpPrimary, cpFallback)+ }+ log.Printf("opensandbox-worker: checkpoint store: %s primary, %s fallback (migration=%v)", cpPrimary.Name(), cpFallback.Name(), cfg.BlobMigrationMode)+ } else {+ log.Printf("opensandbox-worker: checkpoint store: %s (no fallback)", cpPrimary.Name())+ }++ checkpointStore = storage.NewCheckpointStoreFromStore(cpStore, cfg.S3Bucket)+ log.Printf("opensandbox-worker: checkpoint store configured (bucket=%s, region=%s)", cfg.S3Bucket, cfg.S3Region)if cfg.DataDir != "" {cacheDir := filepath.Join(cfg.DataDir, "checkpoints")@@ -356,6 +438,27 @@ func main() {_ = st.RecordScaleEvent(context.Background(), sandboxID, orgID, memoryMB, cpuPercent, 0)})}++ // Wire hibernation upload completion → DB so silent S3 upload+ // failures stop hiding behind a "hibernated" row that points at a+ // blob that was never written. The callback runs from the async+ // archive goroutine in qemu/snapshot.go after upload finishes.+ if qemuMgr != nil {+ st := store // capture for closure+ qemuMgr.SetHibernationUploadCallback(func(sandboxID, hibernationKey string, sizeBytes int64, uploadErr error) {+ ctx2, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()+ if uploadErr != nil {+ if err := st.MarkHibernationUploadFailed(ctx2, hibernationKey, uploadErr.Error()); err != nil {+ log.Printf("opensandbox-worker: failed to record hibernation upload error for %s: %v", sandboxID, err)+ }+ return+ }+ if err := st.MarkHibernationUploaded(ctx2, hibernationKey, sizeBytes); err != nil {+ log.Printf("opensandbox-worker: failed to mark hibernation uploaded for %s: %v", sandboxID, err)+ }+ })+ }}}@@ -403,8 +506,27 @@ func main() {defer metricsSrv.Close()log.Println("opensandbox-worker: metrics server started on :9091")+ // Periodic resource-stats sampler: disk bytes (used/avail/total on the+ // data mount), memory bytes (total/avail from /proc/meminfo), allocated+ // memory (sum of MemoryMB across running VMs), CPU pressure (PSI 'some'+ // avg10/avg60/avg300, or loadavg/nproc fallback).+ var allocator worker.MemoryAllocator+ var sbCounter worker.SandboxCounter+ if qemuMgr != nil {+ allocator = qemuMgr+ sbCounter = qemuMgr+ }+ worker.StartResourceMetricsTick(ctx, allocator, sbCounter, cfg.Region, cfg.WorkerID, cfg.DataDir, 30*time.Second)+// gRPC server (nil builder — template building via podman not needed for QEMU)grpcServer := worker.NewGRPCServer(mgr, ptyMgr, execMgr, sandboxDBMgr, checkpointStore, sbRouter, nil, store)+ // Wire up Axiom log-shipping. Empty token disables shipping (kill-switch).+ grpcServer.SetAxiomConfig(cfg.AxiomIngestToken, cfg.AxiomDataset)+ // Tag wake-source metrics with the worker's region.+ grpcServer.SetRegion(cfg.Region)+ if cfg.AxiomIngestToken != "" {+ log.Printf("opensandbox-worker: sandbox session log shipping enabled (dataset=%s)", cfg.AxiomDataset)+ }// Wire up live migration if using QEMU managerif migrator, ok := mgr.(worker.LiveMigrator); ok {grpcServer.SetMigrator(migrator)@@ -473,6 +595,27 @@ func main() {hb.SetMemoryInfoFunc(func() (int, int) {return qemuMgr.HostMemoryMB(), qemuMgr.TotalCommittedMemoryMB()})+ // Per-sandbox stats for the CP autoscaler. The stats collector+ // runs on a 10s tick (matching heartbeat cadence) and the+ // heartbeat reads the cached snapshot non-blockingly.+ qemuMgr.StartStatsCollector(ctx, 10*time.Second)+ hb.SetSandboxStatsFunc(func() map[string]worker.SandboxStatsWire {+ raw := qemuMgr.GetAllSandboxStats()+ out := make(map[string]worker.SandboxStatsWire, len(raw))+ for id, s := range raw {+ memPct := 0.0+ if s.MemLimit > 0 {+ memPct = float64(s.MemUsage) / float64(s.MemLimit) * 100+ }+ out[id] = worker.SandboxStatsWire{+ MemUsage: s.MemUsage,+ MemLimit: s.MemLimit,+ MemPct: memPct,+ CPUPct: s.CPUPercent,+ }+ }+ return out+ })}// On reconnect after outage, reconcile sandbox state with DBif store != nil {@@ -616,6 +759,39 @@ func getDBURL(cfg *config.Config) string {return os.Getenv("DATABASE_URL")}+// buildCheckpointBackend constructs a blobstore.Store for the checkpoint+// path, picking Azure or S3-compat based on endpoint shape. Returns (nil, nil)+// if no credentials are configured for this slot (caller treats nil as+// "fallback disabled"). The auto-detect preserves the historical behavior of+// storage.NewCheckpointStore.+//+// bucketOverride, if non-empty, tells the backend to use that bucket name+// regardless of what bucket the caller passes at runtime. Empty means the+// backend honors the caller's bucket (which the CheckpointStore sets to+// cfg.S3Bucket).+func buildCheckpointBackend(label, endpoint, region, accessKeyID, secretAccessKey, bucketOverride string, forcePathStyle bool) (blobstore.Store, error) {+ if endpoint == "" && accessKeyID == "" && secretAccessKey == "" {+ return nil, nil+ }+ if strings.Contains(endpoint, ".blob.core.windows.net") {+ return blobstore.NewAzure(blobstore.AzureConfig{+ Name: "azure-blob-" + label,+ AccountName: accessKeyID,+ AccountKey: secretAccessKey,+ Bucket: bucketOverride,+ })+ }+ return blobstore.NewS3(blobstore.S3Config{+ Name: "s3-" + label,+ Endpoint: endpoint,+ Region: region,+ AccessKeyID: accessKeyID,+ SecretAccessKey: secretAccessKey,+ UsePathStyle: forcePathStyle || strings.Contains(endpoint, ".blob.core.windows.net"),+ Bucket: bucketOverride,+ })+}+// createExecSessionQEMU creates an exec session using a QEMU agent client.func createExecSessionQEMU(agent *qm.AgentClient, sandboxID string, req types.ExecSessionCreateRequest) (*sandbox.ExecSessionHandle, error) {agentPB := &agentpb.ExecSessionCreateRequest{diff --git a/deploy/azure/bootstrap-worker-identity.sh b/deploy/azure/bootstrap-worker-identity.shnew file mode 100755index 00000000..0f097db0--- /dev/null+++ b/deploy/azure/bootstrap-worker-identity.sh@@ -0,0 +1,79 @@+#!/usr/bin/env bash+#+# bootstrap-worker-identity.sh — one-time per-region setup for the worker+# UserAssigned managed identity. Workers use this identity to fetch the+# shared secrets-proxy CA from Azure Key Vault. Without this, freshly-+# launched workers generate per-worker CAs and live migration of any+# sandbox using a secret store will fail TLS substitution.+#+# Run ONCE per region. Idempotent — re-running is safe (skips work that's+# already done). The output is the resource ID of the identity; set it as+# OPENSANDBOX_AZURE_WORKER_IDENTITY_ID in the control plane's server.env.+#+# Usage:+# bash bootstrap-worker-identity.sh <resource-group> <key-vault-name> [identity-name]+#+# Example:+# bash bootstrap-worker-identity.sh opensandbox-prod opensandbox-dev-kv+#+set -euo pipefail++if [[ $# -lt 2 ]]; then+ echo "usage: $0 <resource-group> <key-vault-name> [identity-name]" >&2+ exit 1+fi++RG="$1"+KV="$2"+NAME="${3:-osb-worker-identity}"++LOCATION=$(az group show --name "$RG" --query location -o tsv)+echo "==> resource-group: $RG (location=$LOCATION)"+echo "==> key-vault: $KV"+echo "==> identity name: $NAME"++# 1. Create UserAssigned identity (idempotent — show first, create if missing).+if EXISTING=$(az identity show --resource-group "$RG" --name "$NAME" --query id -o tsv 2>/dev/null); then+ echo "==> identity already exists: $EXISTING"+ IDENTITY_ID="$EXISTING"+else+ echo "==> creating identity..."+ IDENTITY_ID=$(az identity create --resource-group "$RG" --name "$NAME" --location "$LOCATION" --query id -o tsv)+ echo "==> created: $IDENTITY_ID"+ # Wait for the identity's principalId to be queryable (eventual consistency).+ sleep 5+fi++PRINCIPAL_ID=$(az identity show --resource-group "$RG" --name "$NAME" --query principalId -o tsv)+echo "==> principalId: $PRINCIPAL_ID"++# 2. Grant "Key Vault Secrets Officer" on the regional KV (RBAC mode).+KV_ID=$(az keyvault show --name "$KV" --query id -o tsv)+echo "==> granting Key Vault Secrets Officer on $KV_ID..."+# az role assignment create is idempotent: returns an error if it already+# exists, but the role is granted either way. Grep the error to ignore it.+if ! az role assignment create \+ --assignee-object-id "$PRINCIPAL_ID" \+ --assignee-principal-type ServicePrincipal \+ --role "Key Vault Secrets Officer" \+ --scope "$KV_ID" \+ -o none 2>&1 | tee /tmp/_role_out; then+ if grep -q "RoleAssignmentExists" /tmp/_role_out; then+ echo "==> role already assigned (idempotent OK)"+ else+ echo "ERROR: role assignment failed" >&2+ cat /tmp/_role_out >&2+ exit 1+ fi+fi++echo ""+echo "===================================================================="+echo "Done. Set this in the control plane's /etc/opensandbox/server.env:"+echo ""+echo "OPENSANDBOX_AZURE_WORKER_IDENTITY_ID=$IDENTITY_ID"+echo ""+echo "Then restart opensandbox-server. New worker VMs will attach this"+echo "identity automatically. Existing workers need a manual roll to pick"+echo "it up (terminate, scaler relaunches with identity attached)."+echo "===================================================================="diff --git a/deploy/azure/deploy-azure-dev.sh b/deploy/azure/deploy-azure-dev.shindex 9989369d..3931dceb 100755--- a/deploy/azure/deploy-azure-dev.sh+++ b/deploy/azure/deploy-azure-dev.sh@@ -125,7 +125,9 @@ SETUP_DISKlog "Syncing codebase..."rsync -az --progress \--exclude '.git' --exclude 'bin/' --exclude 'node_modules/' \- --exclude '.dev-env-state*' --exclude '*.ext4' --exclude 'vendor/' \+ --exclude '.dev-env-state*' --exclude '.dev-env-secrets*' \+ --exclude '.dev-vector-token-*' \+ --exclude '*.ext4' --exclude 'vendor/' \"$REPO_ROOT/" "${AZURE_ADMIN_USER}@${VM_PUBLIC_IP}:~/opensandbox/"log "Running host setup..."@@ -190,7 +192,9 @@ cmd_deploy() {log "Syncing code..."rsync -az --progress \--exclude '.git' --exclude 'bin/' --exclude 'node_modules/' \- --exclude '.dev-env-state*' --exclude '*.ext4' --exclude 'vendor/' \+ --exclude '.dev-env-state*' --exclude '.dev-env-secrets*' \+ --exclude '.dev-vector-token-*' \+ --exclude '*.ext4' --exclude 'vendor/' \"$REPO_ROOT/" "${AZURE_ADMIN_USER}@${VM_PUBLIC_IP}:~/opensandbox/"# Build binaries on instancediff --git a/deploy/ec2/README.md b/deploy/ec2/README.mdindex 07685591..5575db02 100644--- a/deploy/ec2/README.md+++ b/deploy/ec2/README.md@@ -1,55 +1,280 @@-# EC2 Worker Deployment+# Personal dev host on EC2-## Software Stack+Spin up a personal end-to-end OpenComputer dev environment on a single EC2+bare-metal instance. Use this when you need to test a feature that touches the+**control plane, the worker, and real QEMU/KVM VMs** — anything where the+in-process combined-mode targets in `Makefile` (`run`, `run-pg`,+`run-pg-workos`) won't exercise enough of the system.-| Component | Version | Notes |-|-----------|---------|-------|-| Firecracker | latest | MicroVM hypervisor for sandbox isolation |-| Caddy | latest | Wildcard TLS for `*.workers.opencomputer.dev` (DNS-01 via Route53) |-| Redis | 7.0.15 | Local, used for sandbox state/routing |-| Go worker | custom | `/usr/local/bin/opensandbox-worker` |+For control-plane-only or UI-only iteration, prefer the local Makefile tiers+first — they're cheaper and faster.++## What you get++- One bare-metal EC2 instance running both server and worker as systemd services+- Real QEMU VMs (KVM-accelerated, so requires bare metal — Nitro doesn't expose+ VMX to non-`.metal` instance types)+- Local Postgres + Redis on the host+- Vite dev server on your laptop, proxying to the dev host+- WorkOS staging login working in the browser+- ~$1.50/hr while running; `stop` between sessions to keep state and avoid charges## Architecture```-Internet- |- v-Caddy (port 443) -- wildcard TLS for *.workers.opencomputer.dev (DNS-01 via Route53)- |- v-opensandbox-worker (port 8080) -- HTTP API + gRPC (9090)- |- v-Firecracker microVMs -- one per sandbox- |- v-Snapshot hibernate/wake -- pause to S3, resume on demand+laptop EC2 c5d.metal (us-east-2)+────── ────────────────────────+Vite :3000 ───── /api, /auth, /webhooks ───► opensandbox-server :8080+browser │+ ├── Postgres :5432 (local)+ ├── Redis :6379 (local)+ └── opensandbox-worker+ │+ └── QEMU VMs (KVM)+ │+ └── osb-agent (vsock)+```++Server reaches Axiom (logs) and your S3 bucket (checkpoints) over the public+internet.++## Prerequisites++| Need | Verify |+|---|---|+| AWS account access (IAM user, region us-east-2) | `aws sts get-caller-identity` |+| AWS CLI profile with EC2/S3 perms | `aws configure list` |+| Local SSH private key | `ls ~/.ssh/<your-key>` |+| WorkOS staging project access | API key + client ID from team |+| Axiom workspace access | ingest token + query token from team |++## One-time setup++### 1. Register your SSH key with EC2++If your local key isn't already a key pair in EC2 us-east-2:++```bash+ssh-keygen -y -f ~/.ssh/<your-key> > /tmp/pubkey+aws ec2 import-key-pair --region us-east-2 \+ --key-name opensandbox-<your-name> \+ --public-key-material fileb:///tmp/pubkey+rm /tmp/pubkey+```++### 2. Create a personal S3 bucket for checkpoints++```bash+BUCKET=opensandbox-<your-name>-dev+aws s3api create-bucket --bucket "$BUCKET" --region us-east-2 \+ --create-bucket-configuration LocationConstraint=us-east-2+aws s3api put-public-access-block --bucket "$BUCKET" \+ --public-access-block-configuration \+ "BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true"+```++### 3. Get Axiom tokens++From the team Axiom workspace (or personal, free tier): generate an **ingest+token** and a **read/query token**, both scoped to the dataset. The default+dataset name is `oc-sandbox-logs` — override `AXIOM_DATASET` only if you want+isolation from other developers.++> ⚠️ Rotating any `AXIOM_*` value (ingest token, query token, dataset)+> requires a **server restart** to take effect — the values are read from+> the environment once at `config.Load` and frozen for the process lifetime.+> Workers spawned by a server with a stale `cfg.AxiomIngestToken` silently+> bake an empty value into their cloud-init. Watch for the+> `WARNING: AXIOM_INGEST_TOKEN empty` line in `journalctl -u+> opensandbox-server` after any rotation.++### 4. Get WorkOS staging keys + register the redirect URI++From the team WorkOS staging project, grab the API key (`sk_test_...`) and+client ID (`client_...`).++In the **WorkOS dashboard** → Redirects, add:++```+http://localhost:3000/auth/callback```-## Scripts+WorkOS rejects callbacks not on the allowlist. The redirect URI must point at+the Vite host (not the EC2 IP) so the session cookie is set on the same origin+the browser is using.-- `setup-instance.sh` - Full instance setup from a fresh Ubuntu 24.04 AMI-- `deploy-worker.sh` - Build and deploy the worker binary (run from repo root)-- `opensandbox-worker.service` - Systemd unit template (fill in env vars)-- `caddy.service` - Caddy systemd unit file-- `Caddyfile` - Caddy configuration+### 5. Create your dev env file-## Quick Commands+Save to `~/.opensandbox-dev.env` (mode 600, outside the repo):```bash-# Deploy worker (from repo root on your Mac)-./deploy/ec2/deploy-worker.sh+# Pull AXIOM_INGEST_TOKEN, AXIOM_DATASET etc from repo .env if present+REPO=~/path/to/opencomputer+set -a+[ -f "$REPO/.env" ] && . "$REPO/.env"+set +a-# SSH into the instance-ssh -i ~/.ssh/opensandbox-worker.pem ubuntu@$WORKER_IP+# AWS + SSH+export AWS_PROFILE=default+export KEY_NAME=opensandbox-<your-name>+export SSH_KEY=~/.ssh/<your-key>-# Check worker logs-sudo journalctl -u opensandbox-worker -f+# S3 (your bucket + your local AWS creds)+export S3_BUCKET=opensandbox-<your-name>-dev+export S3_ACCESS_KEY_ID=$(aws configure get aws_access_key_id --profile default)+export S3_SECRET_ACCESS_KEY=$(aws configure get aws_secret_access_key --profile default)-# Check caddy logs-sudo journalctl -u caddy -f+# Axiom — INGEST/DATASET come from $REPO/.env; QUERY token must be set explicitly+export AXIOM_QUERY_TOKEN=xaat-...-# Restart worker-sudo systemctl restart opensandbox-worker+# WorkOS staging+export WORKOS_API_KEY=sk_test_...+export WORKOS_CLIENT_ID=client_...+export WORKOS_REDIRECT_URI=http://localhost:3000/auth/callback++# Dev host (set after first `create`; updated on each spot recreate)+export DEV_IP=++# Vite proxy target — read by web/vite.config.ts+export OC_API_TARGET="http://$DEV_IP:8080"++# API key for SDK/curl (server hashes this for the DB seed)+export API_KEY=test-dev-key```++```bash+chmod 600 ~/.opensandbox-dev.env+```++### 6. Launch the host++```bash+source ~/.opensandbox-dev.env+cd <repo>+./deploy/ec2/deploy-qemu-dev.sh create # ~5–10 min, prints the public IP+```++Update `DEV_IP=` in `~/.opensandbox-dev.env` to the printed IP, then re-source.++### 7. First deploy++```bash+source ~/.opensandbox-dev.env+./deploy/ec2/deploy-qemu-dev.sh deploy # ~10–15 min on first run (rootfs build dominates)+```++## Daily workflow++```bash+source ~/.opensandbox-dev.env++# Backend changes+./deploy/ec2/deploy-qemu-dev.sh deploy # rsync + rebuild + restart, ~30–60s++# UI iteration (separate terminal, also source the env)+cd web && npm install && npm run dev # http://localhost:3000+```++`deploy` is `rsync --delete` from your local tree, so each run is a fresh+snapshot. If a parallel agent is editing files, finish their changes before+deploying, or use a worktree pinned to `main` to deploy stable code while you+keep editing.++## UI auth flow (so you can debug if it hangs)++1. Browser at `localhost:3000` clicks Sign in → hits `/auth/login`+2. Vite proxies to EC2 server → 302 to `workos.com/...`+3. WorkOS auths → redirects to `WORKOS_REDIRECT_URI` (`localhost:3000/auth/callback`)+4. Vite proxies callback to EC2 → server processes code, sets session cookie on+ `localhost:3000`+5. Server's `FrontendURL` auto-detects to `localhost:3000` (because `web/dist`+ isn't on the host) and final-redirects you to the dashboard++Step 3 fails with "redirect URI mismatch" → step 4 of the WorkOS dashboard+setup wasn't done.++## Lifecycle++```bash+./deploy/ec2/deploy-qemu-dev.sh ssh # shell into the host+./deploy/ec2/deploy-qemu-dev.sh status # health check + service status+./deploy/ec2/deploy-qemu-dev.sh stop # stop instance, preserve disk, no compute charges+./deploy/ec2/deploy-qemu-dev.sh start # bring it back, same disk+./deploy/ec2/deploy-qemu-dev.sh destroy # tear down completely+```++`stop` is the right default between sessions. `destroy` only when starting+fresh — it forces a full rootfs rebuild on next `deploy`.++## Smoke tests++```bash+# 1. Server health+curl -sf http://$DEV_IP:8080/health++# 2. Create a sandbox (control plane + worker + QEMU)+SBX=$(curl -s -X POST http://$DEV_IP:8080/api/sandboxes \+ -H 'Content-Type: application/json' -H "X-API-Key: $API_KEY" \+ -d '{"templateID":"default"}' | jq -r .sandboxID)++# 3. Exec inside the VM (proves agent + vsock)+curl -s -X POST http://$DEV_IP:8080/api/sandboxes/$SBX/exec \+ -H 'Content-Type: application/json' -H "X-API-Key: $API_KEY" \+ -d '{"cmd":"uname -a && date"}'++# 4. Stream sandbox session logs (tests Axiom wiring)+curl -N http://$DEV_IP:8080/api/sandboxes/$SBX/logs -H "X-API-Key: $API_KEY"+```++## Troubleshooting++**`/auth/login` returns 404.** WorkOS routes register only when+`WORKOS_API_KEY` is non-empty (`internal/api/router.go`). Verify+`server.env` on the host has the keys (`ssh ... 'sudo cat /etc/opensandbox/server.env | grep WORKOS'`),+then `sudo systemctl restart opensandbox-server`. Most often: you ran `deploy`+without sourcing the env file first.++**WorkOS sign-in shows "redirect URI mismatch".** Add+`http://localhost:3000/auth/callback` to the WorkOS dashboard Redirects list+under your project. The URI must exactly match `WORKOS_REDIRECT_URI`.++**Sandbox creation returns `{"error":"missing API key"}`.** `$API_KEY` isn't+exported in your shell. `source ~/.opensandbox-dev.env`.++**`deploy` fails with `S3_ACCESS_KEY_ID: unbound variable`.** The script uses+`set -u`. Set both `S3_ACCESS_KEY_ID` and `S3_SECRET_ACCESS_KEY` (the dev env+file does this from your AWS profile).++**S3 operations 403.** Your AWS IAM principal doesn't have access to the+bucket — set `S3_BUCKET` to your personal one, not someone else's.++**Build fails with `cannot use orgID … as string value`** or similar mid-edit+errors. The parallel agent's working tree was caught mid-edit by rsync. Either+run `go build ./cmd/server ./cmd/worker ./cmd/agent` locally first, or deploy+from a worktree pinned to `main`.++**`./deploy-qemu-dev.sh ssh` says "Cannot reach via SSH".** Spot instance was+reclaimed. `create` again (the state file at `.qemu-dev-state-us-east-2` will+be reset).++## Lighter alternatives in `Makefile`++If you don't need real VMs, these are faster (no EC2):++- `make run` — combined mode, in-memory, no Postgres+- `make run-pg` — combined mode + local Postgres + Redis (`make infra-up` first)+- `make run-pg-workos` — same plus WorkOS browser login++Worker logic runs in-process in combined mode but sandbox VM lifecycle isn't+exercised — anything touching `internal/qemu/` should use the dev host.++## Files in this directory++- `deploy-qemu-dev.sh` — main lifecycle script (`create | deploy | ssh | status | stop | start | destroy`)+- `setup-azure-host.sh` (in `../azure/`) — host provisioning, reused for AWS+- `build-rootfs-docker.sh` — builds the guest rootfs ext4 image+- `setup-dev-env.sh`, `setup-secrets.sh` — env file installers run remotely+- `opensandbox-server.service`, `opensandbox-worker.service` — systemd units+- `setup-instance.sh`, `setup-single-host.sh`, `deploy-server.sh`,+ `deploy-worker.sh`, `deploy-aws-dev.sh` — older paths, currently unused by+ `deploy-qemu-dev.sh` workflowdiff --git a/deploy/firecracker/rootfs/Dockerfile.default b/deploy/firecracker/rootfs/Dockerfile.defaultindex a739e87c..f811ebeb 100644--- a/deploy/firecracker/rootfs/Dockerfile.default+++ b/deploy/firecracker/rootfs/Dockerfile.default@@ -64,6 +64,13 @@ RUN apt-get update && apt-get install -y --no-install-recommends \tree \rsync \man-db \+ # Container runtime — dockerd does NOT auto-start (osb-agent is PID 1, no+ # systemd). Users opt in via `sudo dockerd &` or supervisord. Keeps idle+ # snapshots clean of daemon state.+ docker.io \+ # Process supervisor — for users who want declarative service management+ # without systemd. Started on demand by users (`sudo supervisord -c ...`).+ supervisor \&& rm -rf /var/lib/apt/lists/*# ── Python setup ─────────────────────────────────────────────────────────────@@ -102,9 +109,17 @@ ENV LC_ALL=en_US.UTF-8# The agent (PID 1) runs as root, but all user commands run as "sandbox".# This matches user expectations for a normal Linux environment and allows# Claude Code to work without --allow-dangerously-skip-permissions.+# /etc/hosts gets the sandbox hostname baked in so sudo doesn't print+# `unable to resolve host sandbox` on every invocation. The runtime network+# patch in manager.go also writes this, but that path can short-circuit if+# an earlier `ip addr add` fails — bake it as defense-in-depth.RUN useradd -m -s /bin/bash -G sudo sandbox \&& echo "sandbox ALL=(ALL) NOPASSWD:ALL" > /etc/sudoers.d/sandbox \- && chmod 440 /etc/sudoers.d/sandbox+ && chmod 440 /etc/sudoers.d/sandbox \+ && (grep -q sandbox /etc/hosts || echo "127.0.0.1 sandbox" >> /etc/hosts) \+ # Add sandbox user to docker group so `docker` CLI works without sudo+ # once dockerd is started.+ && usermod -aG docker sandbox# /workspace is a symlink to ~ for backward compatibilityRUN ln -s /home/sandbox /workspacediff --git a/deploy/packer/worker-ami.pkr.hcl b/deploy/packer/worker-ami.pkr.hclindex 52126a4e..8aa93d72 100644--- a/deploy/packer/worker-ami.pkr.hcl+++ b/deploy/packer/worker-ami.pkr.hcl@@ -115,6 +115,44 @@ variable "prev_golden_version" {description = "Previous AMI's golden version. When set, Packer downloads bases/{prev}/default.ext4 from blob storage and bakes it into the AMI at /opt/opensandbox/images/bases/{prev}/default.ext4 so forks of checkpoints pinned to the previous golden don't need a runtime blob download."}+# Tigris dual-write: during the Azure→Tigris migration window, the AMI bake+# uploads each new golden to BOTH Azure (via the legacy Python step) AND+# Tigris (via opensandbox-worker golden-upload). Leave these empty to skip+# the Tigris upload — falls back to Azure-only behavior. Drop the Python+# Azure upload entirely once the cutover is complete (Phase 5+).++variable "tigris_endpoint" {+ type = string+ default = ""+ description = "Tigris (or any S3-compat) endpoint for the goldens dual-write. Empty skips."+}++variable "tigris_access_key_id" {+ type = string+ default = ""+ sensitive = true+ description = "Tigris access key. Paired with tigris_endpoint."+}++variable "tigris_secret_access_key" {+ type = string+ default = ""+ sensitive = true+ description = "Tigris secret key. Paired with tigris_endpoint."+}++variable "tigris_goldens_bucket" {+ type = string+ default = ""+ description = "Tigris bucket where goldens land (e.g. opencomputer-prod). Empty skips."+}++variable "tigris_region" {+ type = string+ default = "auto"+ description = "Tigris region. 'auto' works for Tigris/R2; AWS would need a real region."+}+# ---------------------------------------------------------------------# Source: Ubuntu 24.04 x86_64 on Azure# ---------------------------------------------------------------------@@ -320,6 +358,36 @@ build {]}+ # 4.5. Install Vector + the KV-token-populator for platform-logs shipping.+ #+ # Vector is enabled but NOT started (Packer captures the image before+ # systemd has run). At first boot:+ # 1. cloud-init writes /etc/opensandbox/worker.env+ # 2. populate-vector-env.service fires (Before=vector.service), reads+ # SECRETS_VAULT_NAME from worker.env, fetches AXIOM_PLATFORM_TOKEN+ # from KV via the VM's managed identity, writes /etc/opensandbox/vector.env+ # 3. vector.service starts, reads both env files, ships to oc-platform-logs+ #+ # PACKER_BUILD=1 tells install.sh to skip `systemctl start` — systemd in a+ # baking image is offline.+ #+ # CI is expected to pre-tar deploy/vector/ at /tmp/packer-vector-ctx.tar.gz+ # (see .github/workflows/build-worker-ami.yml).+ provisioner "file" {+ source = "/tmp/packer-vector-ctx.tar.gz"+ destination = "/tmp/vector-ctx.tar.gz"+ }+ provisioner "shell" {+ execute_command = "chmod +x {{ .Path }}; {{ .Vars }} sudo -E bash '{{ .Path }}'"+ environment_vars = ["PACKER_BUILD=1"]+ inline = [+ "mkdir -p /tmp/vector-ctx",+ "tar xzf /tmp/vector-ctx.tar.gz -C /tmp/vector-ctx",+ "cd /tmp/vector-ctx/vector && PACKER_BUILD=1 bash install.sh worker",+ "rm -rf /tmp/vector-ctx /tmp/vector-ctx.tar.gz",+ ]+ }+# 4b. Archive base image to blob storage keyed by goldenVersion so that old# checkpoints referencing this base can be rebased even after workers roll.provisioner "shell" {@@ -394,6 +462,33 @@ build {]}+ # 4b'. Dual-write the new golden to Tigris via the worker's golden-upload+ # subcommand. Runs only when tigris_endpoint + creds + bucket are set.+ # Uses the same blobstore.S3 backend the worker uses at runtime — no+ # separate Tigris client code in the AMI bake. Skips cleanly (exit 0)+ # when any required var is unset, so this step is safe to leave in+ # the pipeline once we drop the Azure upload entirely (Phase 5+).+ provisioner "shell" {+ execute_command = "chmod +x {{ .Path }}; {{ .Vars }} sudo -E bash '{{ .Path }}'"+ environment_vars = [+ "OPENSANDBOX_GLOBAL_BLOB_ENDPOINT=${var.tigris_endpoint}",+ "OPENSANDBOX_GLOBAL_BLOB_REGION=${var.tigris_region}",+ "OPENSANDBOX_GLOBAL_BLOB_ACCESS_KEY_ID=${var.tigris_access_key_id}",+ "OPENSANDBOX_GLOBAL_BLOB_SECRET_ACCESS_KEY=${var.tigris_secret_access_key}",+ "OPENSANDBOX_GLOBAL_BLOB_USE_PATH_STYLE=true",+ "OPENSANDBOX_GLOBAL_BLOB_GOLDENS_BUCKET=${var.tigris_goldens_bucket}",+ "OPENSANDBOX_GLOBAL_BLOB_NAME=tigris",+ ]+ inline = [+ "if [ -z \"$OPENSANDBOX_GLOBAL_BLOB_ENDPOINT\" ] || [ -z \"$OPENSANDBOX_GLOBAL_BLOB_ACCESS_KEY_ID\" ] || [ -z \"$OPENSANDBOX_GLOBAL_BLOB_GOLDENS_BUCKET\" ]; then",+ " echo 'Tigris dual-write: env vars not set, skipping'",+ " exit 0",+ "fi",+ "echo 'Tigris dual-write: uploading /opt/opensandbox/images/default.ext4 via golden-upload subcommand'",+ "/usr/local/bin/opensandbox-worker golden-upload /opt/opensandbox/images/default.ext4",+ ]+ }+# 4c. Bake previous golden's default.ext4 into the AMI under# /opt/opensandbox/images/bases/{prev}/default.ext4. At first boot the# Azure custom-data script copies /opt/opensandbox/images/bases/* todiff --git a/deploy/vector/control-plane.yaml b/deploy/vector/control-plane.yamlnew file mode 100644index 00000000..69dfca28--- /dev/null+++ b/deploy/vector/control-plane.yaml@@ -0,0 +1,108 @@+# Vector config for the control-plane host (Azure prod: systemd binary,+# not Docker). Reads opensandbox-server.service from journald, scrapes the+# control plane's Prometheus /metrics on :9092, enriches both streams with+# the host envelope, and ships to oc-platform-logs.+#+# Install path: /etc/vector/vector.yaml+# Env file: /etc/opensandbox/vector.env (populated by+# populate-vector-env.service from Key Vault at boot)++data_dir: /var/lib/vector++sources:+ control_plane_journald:+ type: journald+ include_units:+ - opensandbox-server.service+ # Default current_boot_only=true is fine — Vector tracks its own cursor+ # in data_dir, so restarts resume cleanly without replaying the journal.++ # Scrape the control plane's own /metrics on :9092. Different port from the+ # worker's :9091 so a dev host running both binaries doesn't collide. The+ # control-plane binary serves Prometheus via metrics.StartMetricsServer+ # (cmd/server/main.go).+ control_plane_metrics:+ type: prometheus_scrape+ endpoints:+ - http://127.0.0.1:9092/metrics+ scrape_interval_secs: 30++transforms:+ control_plane_parse:+ type: remap+ inputs:+ - control_plane_journald+ source: |+ parsed, err = parse_json(.message)+ if err == null && is_object(parsed) {+ . = merge(., object!(parsed))+ # Drop stringified duplicate; non-JSON lines (panics, systemd boot)+ # keep .message as the readable content.+ del(.message)+ }+ if !exists(.service) { .service = "control-plane" }+ if !exists(.service_id) { .service_id, _ = get_hostname() }+ if !exists(.cell_id) { .cell_id = "${OPENCOMPUTER_CELL_ID:-unknown}" }+ if !exists(.region) { .region = "${OPENSANDBOX_REGION:-unknown}" }+ if !exists(.host_ip) { .host_ip = "${OPENCOMPUTER_HOST_IP:-unknown}" }+ if !exists(.hostname) { .hostname, _ = get_hostname() }++ # Convert metric events to log shape (metric_to_log is a transform type;+ # VRL has no `to_log` function in Vector 0.55+).+ control_plane_metrics_to_log:+ type: metric_to_log+ inputs:+ - control_plane_metrics++ # Envelope: same fields as logs so cross-event-type joins work in Axiom+ # (event_type="metric" filter, then group by region/cell_id/...).+ # metric_name carries the Prom name; namespaced to dodge a clash with any+ # log payload that happens to contain a literal `name` field.+ control_plane_metrics_envelope:+ type: remap+ inputs:+ - control_plane_metrics_to_log+ source: |+ .event_type = "metric"+ if exists(.name) {+ .metric_name = .name+ del(.name)+ }+ .service = "control-plane"+ .service_id, _ = get_hostname()+ .cell_id = "${OPENCOMPUTER_CELL_ID:-unknown}"+ .region = "${OPENSANDBOX_REGION:-unknown}"+ .host_ip = "${OPENCOMPUTER_HOST_IP:-unknown}"+ .hostname, _ = get_hostname()++sinks:+ # Logs sink: ships journald (parsed + enveloped) to the platform-logs dataset.+ axiom_platform:+ type: axiom+ inputs:+ - control_plane_parse+ dataset: "${AXIOM_PLATFORM_DATASET}"+ token: "${AXIOM_PLATFORM_TOKEN}"+ buffer:+ type: disk+ max_size: 268435488+ when_full: drop_newest+ healthcheck:+ enabled: true++ # Metrics sink: separate dataset + token. See worker.yaml for the rationale+ # (histogram-bucket volume, independent retention/budget, independent+ # rollout). Soft-fails on missing creds — buffers to disk and doesn't take+ # the logs sink down.+ axiom_metrics:+ type: axiom+ inputs:+ - control_plane_metrics_envelope+ dataset: "${AXIOM_PLATFORM_METRICS_DATASET}"+ token: "${AXIOM_PLATFORM_METRICS_TOKEN}"+ buffer:+ type: disk+ max_size: 268435488+ when_full: drop_newest+ healthcheck:+ enabled: truediff --git a/deploy/vector/dev-host.yaml b/deploy/vector/dev-host.yamlnew file mode 100644index 00000000..8965dd26--- /dev/null+++ b/deploy/vector/dev-host.yaml@@ -0,0 +1,174 @@+# Vector config for a dev host that runs BOTH opensandbox-server AND+# opensandbox-worker as systemd services on the same VM (the layout produced+# by deploy/azure/deploy-azure-dev.sh).+#+# Production hosts use worker.yaml or control-plane.yaml — one role per host.+# This config exists so the request-id join can be validated end-to-end on a+# single dev VM before standing up a multi-VM dev cluster.+#+# The journald source captures both units in one stream; the parse transform+# tags `service` based on which unit emitted each line. Two Prometheus+# scrape sources (9091=worker, 9092=control-plane) feed metric events through+# the same envelope path.+#+# Install path: /etc/vector/vector.yaml+# Env file: /etc/opensandbox/vector.env (provides AXIOM_PLATFORM_TOKEN)++data_dir: /var/lib/vector++sources:+ dev_journald:+ type: journald+ include_units:+ - opensandbox-server.service+ - opensandbox-worker.service+ # `current_boot_only: false` is rejected on systemd 250-257 (Vector+ # limitation). Default (true) is fine — Vector tracks its own cursor in+ # data_dir, so restarts pick up where they left off rather than replaying.++ # Two scrape sources so each emitted metric event can carry the correct+ # service label (worker vs control-plane). Vector doesn't expose the scrape+ # endpoint as a field, so we split sources and tag in the transforms.+ dev_worker_metrics:+ type: prometheus_scrape+ endpoints:+ - http://127.0.0.1:9091/metrics+ scrape_interval_secs: 30++ dev_control_plane_metrics:+ type: prometheus_scrape+ endpoints:+ - http://127.0.0.1:9092/metrics+ scrape_interval_secs: 30++transforms:+ dev_parse:+ type: remap+ inputs:+ - dev_journald+ source: |+ parsed, err = parse_json(.message)+ if err == null && is_object(parsed) {+ . = merge(., object!(parsed))+ # The structured fields (msg, level, request_id, ...) are now at+ # root. Drop the stringified copy so events don't duplicate the+ # payload in Axiom. Non-JSON lines (panics, kernel) fall through+ # this branch and keep .message as the readable content.+ del(.message)+ }+ # Tag service based on the systemd unit. obslog.Init already sets+ # `service` inside JSON log lines, so this only fires for non-JSON+ # output (panics, plain stderr, systemd boot messages).+ if !exists(.service) {+ unit = string(.SYSTEMD_UNIT) ?? ""+ if unit == "opensandbox-server.service" {+ .service = "control-plane"+ } else if unit == "opensandbox-worker.service" {+ .service = "worker"+ } else {+ .service = "unknown"+ }+ }+ if !exists(.service_id) {+ # Worker exports OPENSANDBOX_WORKER_ID; control plane has no+ # equivalent on a binary-deployed dev host — fall back to hostname.+ unit = string(.SYSTEMD_UNIT) ?? ""+ if unit == "opensandbox-worker.service" {+ .service_id = "${OPENSANDBOX_WORKER_ID:-unknown}"+ } else {+ .service_id, _ = get_hostname()+ }+ }+ if !exists(.cell_id) { .cell_id = "${OPENCOMPUTER_CELL_ID:-unknown}" }+ if !exists(.region) { .region = "${OPENSANDBOX_REGION:-unknown}" }+ if !exists(.host_ip) { .host_ip = "${OPENCOMPUTER_HOST_IP:-unknown}" }+ if !exists(.hostname) { .hostname, _ = get_hostname() }+ # Stamp every event with environment so dev traffic is filterable inside+ # a shared dataset. Only the dev-host config sets this — production+ # worker.yaml / control-plane.yaml deliberately omit it so prod events+ # don't claim the dev tag.+ .environment = "dev"++ # Convert each scrape source to log shape (metric_to_log is a transform+ # type; VRL has no `to_log` function in Vector 0.55+). Two parallel+ # converters so we can stamp the right service label downstream without+ # re-parsing the scrape endpoint URL.+ dev_worker_metrics_to_log:+ type: metric_to_log+ inputs:+ - dev_worker_metrics++ dev_control_plane_metrics_to_log:+ type: metric_to_log+ inputs:+ - dev_control_plane_metrics++ # Envelopes: same shape as dev_parse for join-friendly events. event_type="metric"+ # is the cross-type discriminator.+ dev_worker_metrics_envelope:+ type: remap+ inputs:+ - dev_worker_metrics_to_log+ source: |+ .event_type = "metric"+ if exists(.name) {+ .metric_name = .name+ del(.name)+ }+ .service = "worker"+ .service_id = "${OPENSANDBOX_WORKER_ID:-unknown}"+ .cell_id = "${OPENCOMPUTER_CELL_ID:-unknown}"+ .region = "${OPENSANDBOX_REGION:-unknown}"+ .host_ip = "${OPENCOMPUTER_HOST_IP:-unknown}"+ .hostname, _ = get_hostname()+ .environment = "dev"++ dev_control_plane_metrics_envelope:+ type: remap+ inputs:+ - dev_control_plane_metrics_to_log+ source: |+ .event_type = "metric"+ if exists(.name) {+ .metric_name = .name+ del(.name)+ }+ .service = "control-plane"+ .service_id, _ = get_hostname()+ .cell_id = "${OPENCOMPUTER_CELL_ID:-unknown}"+ .region = "${OPENSANDBOX_REGION:-unknown}"+ .host_ip = "${OPENCOMPUTER_HOST_IP:-unknown}"+ .hostname, _ = get_hostname()+ .environment = "dev"++sinks:+ # Logs sink: ships journald (parsed + enveloped) to the platform-logs dataset.+ axiom_platform:+ type: axiom+ inputs:+ - dev_parse+ dataset: "${AXIOM_PLATFORM_DATASET}"+ token: "${AXIOM_PLATFORM_TOKEN}"+ buffer:+ type: disk+ max_size: 268435488+ when_full: drop_newest+ healthcheck:+ enabled: true++ # Metrics sink: separate dataset + token. Both scrape sources funnel through+ # here. See worker.yaml for the rationale (histogram-bucket volume,+ # independent retention/budget, independent rollout).+ axiom_metrics:+ type: axiom+ inputs:+ - dev_worker_metrics_envelope+ - dev_control_plane_metrics_envelope+ dataset: "${AXIOM_PLATFORM_METRICS_DATASET}"+ token: "${AXIOM_PLATFORM_METRICS_TOKEN}"+ buffer:+ type: disk+ max_size: 268435488+ when_full: drop_newest+ healthcheck:+ enabled: truediff --git a/deploy/vector/install.sh b/deploy/vector/install.shnew file mode 100755index 00000000..d290eb19--- /dev/null+++ b/deploy/vector/install.sh@@ -0,0 +1,118 @@+#!/usr/bin/env bash+# install.sh — Install Vector on a host and wire it to a role-specific config.+#+# Usage (run as root on the target host):+# ./install.sh worker # for prod worker VMs (reads journald)+# ./install.sh control-plane # for prod control plane VM (reads journald)+# ./install.sh dev-host # single VM running both server + worker as systemd+#+# Two ways the env file (with the Axiom token) reaches the host:+#+# 1. Production (Azure VMs with managed identity to KV): populate-vector-env.service+# is installed alongside vector.service. At each boot it fetches the+# `shared-axiom-platform-ingest-token` secret from $SECRETS_VAULT_NAME and+# writes /etc/opensandbox/vector.env. Vector starts after. No human in the+# loop, no static token on disk.+#+# 2. Operator-managed (dev hosts, ad-hoc): the operator writes+# /etc/opensandbox/vector.env manually before running this script (or any+# other way). The KV oneshot finds no SECRETS_VAULT_NAME and exits clean,+# and Vector reads whatever the operator put there.+set -euo pipefail++ROLE="${1:-}"+case "$ROLE" in+ worker|control-plane|dev-host) ;;+ *)+ echo "usage: $0 worker|control-plane|dev-host" >&2+ exit 2+ ;;+esac++SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+CONFIG_SRC="$SCRIPT_DIR/${ROLE}.yaml"+if [ ! -f "$CONFIG_SRC" ]; then+ echo "config not found: $CONFIG_SRC" >&2+ exit 1+fi++echo "=== Installing Vector (role: $ROLE) ==="++# --- Install Vector via official setup script ---+# setup.vector.dev configures the right apt repo + key for the host's distro.+# (Vector moved off repositories.timber.io after the Datadog acquisition; the+# old URL no longer resolves.)+if ! command -v vector &>/dev/null; then+ echo "Installing Vector..."+ bash -c "$(curl -fsSL https://setup.vector.dev)"+ apt-get install -y -qq vector+fi+vector --version++# --- Drop the role config ---+mkdir -p /etc/vector /var/lib/vector+install -m 0644 "$CONFIG_SRC" /etc/vector/vector.yaml+chown -R vector:vector /var/lib/vector++# --- Install the KV → env-file populator (oneshot, runs Before=vector.service) ---+# Both the script and the unit file are tracked in this dir so they roll+# atomically with config changes.+install -m 0755 "$SCRIPT_DIR/populate-vector-env.sh" /usr/local/bin/populate-vector-env.sh+install -m 0644 "$SCRIPT_DIR/populate-vector-env.service" \+ /etc/systemd/system/populate-vector-env.service++# --- Wire env file + KV oneshot into the vector.service unit ---+# Use a drop-in instead of editing the package file so a Vector upgrade+# doesn't clobber our changes.+mkdir -p /etc/systemd/system/vector.service.d+cat > /etc/systemd/system/vector.service.d/override.conf <<'EOF'+[Unit]+# Soft dependency: if the KV fetch fails, vector still starts so we+# preserve whatever state was on disk from a previous boot.+Wants=populate-vector-env.service+After=populate-vector-env.service++[Service]+EnvironmentFile=-/etc/opensandbox/worker.env+EnvironmentFile=-/etc/opensandbox/server.env+EnvironmentFile=-/etc/opensandbox/vector.env+# Vector needs to read journald — add the user to the right group.+SupplementaryGroups=systemd-journal+EOF++# --- Auto-detect HOST_IP if not provisioned ---+# Vector enriches log lines with OPENCOMPUTER_HOST_IP from the env file. If the+# operator didn't set it (and the KV oneshot hasn't run yet), fill it in from+# the primary interface so the field isn't "unknown" in Axiom.+if [ -f /etc/opensandbox/vector.env ] && \+ ! grep -q '^OPENCOMPUTER_HOST_IP=' /etc/opensandbox/vector.env 2>/dev/null; then+ # `ip route get` returns the kernel's chosen source IP for outbound — bypasses+ # Azure's 169.254.169.253 IMDS address which is also scope=global on lo.+ HOST_IP=$(ip route get 8.8.8.8 2>/dev/null | \+ awk '/src/ {for(i=1;i<NF;i++) if($i=="src") print $(i+1); exit}')+ if [ -n "$HOST_IP" ]; then+ echo "OPENCOMPUTER_HOST_IP=$HOST_IP" >> /etc/opensandbox/vector.env+ echo "Detected HOST_IP=$HOST_IP"+ fi+fi++# --- Start ---+systemctl daemon-reload+systemctl enable populate-vector-env.service vector.service++# In a Packer image bake, systemd may not actually run units (the image is+# captured before reboot). Skip the start in that case so packer's+# deprovision step doesn't trip over a started service. PACKER_BUILD is set+# by the Packer provisioner.+if [ -z "${PACKER_BUILD:-}" ]; then+ systemctl restart populate-vector-env.service 2>&1 || true+ systemctl restart vector+ sleep 2+ systemctl status vector --no-pager -l | head -15+fi++echo+echo "=== Done ==="+echo "Check vector status: systemctl status vector"+echo "Tail vector logs: journalctl -u vector -f"+echo "Confirm Axiom ingest: look for events in dataset \${AXIOM_PLATFORM_DATASET}"diff --git a/deploy/vector/populate-vector-env.service b/deploy/vector/populate-vector-env.servicenew file mode 100644index 00000000..6cab5bf3--- /dev/null+++ b/deploy/vector/populate-vector-env.service@@ -0,0 +1,45 @@+# Pulls AXIOM_PLATFORM_TOKEN + AXIOM_PLATFORM_DATASET from Key Vault via+# the VM's managed identity and writes /etc/opensandbox/vector.env before+# vector.service starts.+#+# Reads OPENSANDBOX_AZURE_KEY_VAULT_NAME (and OPENCOMPUTER_CELL_ID /+# OPENSANDBOX_REGION for tagging) from whichever role-env file exists —+# worker.env on workers, server.env on the control plane. EnvironmentFile+# lines with a leading `-` are silently skipped if the file is absent, so+# this unit works on both roles.+#+# Ordering note: on Azure workers, cloud-init's final stage writes+# /etc/opensandbox/worker.env from a base64 payload baked by the control+# plane (internal/compute/azure.go). Without `After=cloud-final.service`+# the populator races cloud-init, reads an empty environ, exits 0 on+# the "OPENSANDBOX_AZURE_KEY_VAULT_NAME not set" branch, and never+# retries (Restart=on-failure doesn't fire on exit 0). Vector then can't+# start because vector.env was never written. Ordering after cloud-final+# guarantees worker.env exists by the time we read it.++[Unit]+Description=Populate /etc/opensandbox/vector.env from Key Vault+After=network-online.target cloud-final.service+Wants=network-online.target cloud-final.service+Before=vector.service+DefaultDependencies=no+# Retry budget for the Restart= below. StartLimit* belongs in [Unit] per+# systemd 229+; in [Service] systemd-255 logs an "Unknown key" warning+# and ignores them (then Restart=on-failure can crash-loop without a cap).+StartLimitBurst=5+StartLimitIntervalSec=120++[Service]+Type=oneshot+EnvironmentFile=-/etc/opensandbox/worker.env+EnvironmentFile=-/etc/opensandbox/server.env+ExecStart=/usr/local/bin/populate-vector-env.sh+RemainAfterExit=yes+# Retry a few times if KV is briefly unreachable at boot. The script+# itself exits 0 on graceful failure paths (no IMDS, no secret, etc.) so+# this only fires on truly unexpected errors.+Restart=on-failure+RestartSec=10s++[Install]+WantedBy=multi-user.targetdiff --git a/deploy/vector/populate-vector-env.sh b/deploy/vector/populate-vector-env.shnew file mode 100755index 00000000..89b2b4a2--- /dev/null+++ b/deploy/vector/populate-vector-env.sh@@ -0,0 +1,129 @@+#!/bin/bash+# populate-vector-env.sh — Fetch the Axiom platform ingest credentials+# (token + dataset name) from Azure Key Vault via the VM's managed identity,+# write them to /etc/opensandbox/vector.env so Vector picks them up at start.+#+# Runs as a one-shot systemd unit (populate-vector-env.service) before+# vector.service. Idempotent on every boot.+#+# Required env (sourced from /etc/opensandbox/worker.env or server.env by+# the systemd unit's EnvironmentFile=). This is the same var the+# autoscaler bakes into prod worker.env at VM-create time, so the+# populator picks it up automatically without any extra plumbing.+# OPENSANDBOX_AZURE_KEY_VAULT_NAME Key Vault name (e.g. opencomputer-prod-kv)+#+# Optional env (used to enrich Vector's host envelope for non-JSON lines):+# OPENCOMPUTER_CELL_ID e.g. eastus2-default+# OPENSANDBOX_REGION e.g. eastus2+#+# KV secrets fetched:+# shared-axiom-platform-ingest-token → AXIOM_PLATFORM_TOKEN (required — logs)+# shared-axiom-platform-dataset → AXIOM_PLATFORM_DATASET (required — logs)+# shared-axiom-platform-metrics-ingest-token → AXIOM_PLATFORM_METRICS_TOKEN (optional — metrics)+# shared-axiom-platform-metrics-dataset → AXIOM_PLATFORM_METRICS_DATASET (optional — metrics)+# shared-cell-id → OPENCOMPUTER_CELL_ID (optional — cell tag)+#+# Logs secrets are hard-required: missing → exit 0 without writing env file,+# Vector fails healthcheck and buffers to disk until the secret appears+# (don't break the worker boot path over a logging credential).+#+# Metrics secrets are soft-optional: missing → env file still gets written+# with logs creds set, metrics ones empty. The metrics sink fails healthcheck+# and buffers to disk independently. Lets operators roll out the metrics+# dataset asynchronously without coordinating with the worker fleet.+#+# shared-cell-id is soft-optional too: missing → fall back to whatever+# OPENCOMPUTER_CELL_ID was already in the populator's shell env (typically+# unset on prod), then to literal "unknown". Vector keeps shipping; events+# just won't be tagged with the right cell until KV gets the secret.+set -euo pipefail++VAULT_NAME="${OPENSANDBOX_AZURE_KEY_VAULT_NAME:-}"+ENV_FILE=/etc/opensandbox/vector.env+TOKEN_SECRET=shared-axiom-platform-ingest-token+DATASET_SECRET=shared-axiom-platform-dataset+METRICS_TOKEN_SECRET=shared-axiom-platform-metrics-ingest-token+METRICS_DATASET_SECRET=shared-axiom-platform-metrics-dataset+CELL_ID_SECRET=shared-cell-id++log() { logger -t populate-vector-env "$*"; echo "$*"; }++if [ -z "$VAULT_NAME" ]; then+ log "OPENSANDBOX_AZURE_KEY_VAULT_NAME not set — skipping (Vector will start without a token)"+ exit 0+fi++# IMDS → AAD token for Key Vault+IMDS_RESP=$(curl -sf -H 'Metadata: true' \+ "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https%3A%2F%2Fvault.azure.net" \+ || true)+AAD_TOKEN=$(echo "$IMDS_RESP" | python3 -c 'import sys,json; print(json.load(sys.stdin).get("access_token",""))' 2>/dev/null)+if [ -z "$AAD_TOKEN" ]; then+ log "failed to acquire IMDS token (managed identity not attached?); skipping"+ exit 0+fi++# Helper: fetch one secret value or empty string.+kv_get() {+ local name=$1+ local resp+ resp=$(curl -sf -H "Authorization: Bearer $AAD_TOKEN" \+ "https://${VAULT_NAME}.vault.azure.net/secrets/${name}?api-version=7.4" \+ || true)+ echo "$resp" | python3 -c 'import sys,json; print(json.load(sys.stdin).get("value",""))' 2>/dev/null+}++TOKEN_VALUE=$(kv_get "$TOKEN_SECRET")+if [ -z "$TOKEN_VALUE" ]; then+ log "secret $TOKEN_SECRET not found in $VAULT_NAME (or no access); skipping"+ exit 0+fi++DATASET_VALUE=$(kv_get "$DATASET_SECRET")+if [ -z "$DATASET_VALUE" ]; then+ log "secret $DATASET_SECRET not found in $VAULT_NAME (or no access); skipping — Vector won't have a dataset to ship to"+ exit 0+fi++# Metrics creds are soft-optional. Empty values land in the env file and the+# axiom_metrics sink in Vector fails its healthcheck; the logs sink keeps+# working. Lets operators provision the metrics dataset on their own schedule+# without coordinating with worker boots.+METRICS_TOKEN_VALUE=$(kv_get "$METRICS_TOKEN_SECRET")+METRICS_DATASET_VALUE=$(kv_get "$METRICS_DATASET_SECRET")+if [ -z "$METRICS_TOKEN_VALUE" ] || [ -z "$METRICS_DATASET_VALUE" ]; then+ log "metrics secrets ($METRICS_TOKEN_SECRET / $METRICS_DATASET_SECRET) missing — metrics sink will buffer to disk until configured"+fi++# Cell tag — fall through KV → inherited env → "unknown". KV wins so the+# value matches what the Go binary will load via secretMapping in+# internal/config/keyvault.go; events from both pipelines stay coherent.+CELL_ID_VALUE=$(kv_get "$CELL_ID_SECRET")+if [ -z "$CELL_ID_VALUE" ]; then+ CELL_ID_VALUE="${OPENCOMPUTER_CELL_ID:-unknown}"+ log "secret $CELL_ID_SECRET not found in $VAULT_NAME — falling back to OPENCOMPUTER_CELL_ID=$CELL_ID_VALUE"+fi++# Auto-detect HOST_IP via the kernel's source-address selection (skips link-local).+HOST_IP=$(ip route get 8.8.8.8 2>/dev/null | awk '/src/ {for(i=1;i<NF;i++) if($i=="src") print $(i+1); exit}' || true)++install -d -m 0755 /etc/opensandbox+umask 077+cat > "${ENV_FILE}.tmp" <<EOF+AXIOM_PLATFORM_TOKEN=${TOKEN_VALUE}+AXIOM_PLATFORM_DATASET=${DATASET_VALUE}+AXIOM_PLATFORM_METRICS_TOKEN=${METRICS_TOKEN_VALUE}+AXIOM_PLATFORM_METRICS_DATASET=${METRICS_DATASET_VALUE}+OPENCOMPUTER_CELL_ID=${CELL_ID_VALUE}+OPENSANDBOX_REGION=${OPENSANDBOX_REGION:-unknown}+OPENCOMPUTER_HOST_IP=${HOST_IP:-unknown}+EOF+chown root:root "${ENV_FILE}.tmp"+chmod 0600 "${ENV_FILE}.tmp"+mv -f "${ENV_FILE}.tmp" "$ENV_FILE"++metrics_status="absent"+if [ -n "$METRICS_TOKEN_VALUE" ] && [ -n "$METRICS_DATASET_VALUE" ]; then+ metrics_status="present"+fi+log "populated $ENV_FILE (logs token+dataset from $VAULT_NAME, metrics=$metrics_status, cell_id=$CELL_ID_VALUE, host_ip=${HOST_IP:-unknown})"diff --git a/deploy/vector/vector.env.example b/deploy/vector/vector.env.examplenew file mode 100644index 00000000..f035c8d5--- /dev/null+++ b/deploy/vector/vector.env.example@@ -0,0 +1,31 @@+# /etc/opensandbox/vector.env+#+# Vector reads this at startup (via systemd EnvironmentFile= drop-in). Only+# these variables are needed — everything else is in worker.env / set on the+# host by cloud-init.+#+# Production hosts: this file is written by populate-vector-env.service at+# every boot, fetching `shared-axiom-platform-ingest-token` and+# `shared-axiom-platform-dataset` from Azure Key Vault via the VM's managed+# identity. Operators do not need to maintain this file manually.+#+# Dev/operator-managed hosts: write this file by hand before running+# install.sh (populate-vector-env will exit 0 if SECRETS_VAULT_NAME isn't+# set, leaving the operator's file in place).++# Axiom platform-logs ingest token. Create in Axiom: Settings → API tokens,+# capability Ingest only, scoped to your platform dataset only. Do not reuse+# the customer-sandbox-logs token — different blast radius.+AXIOM_PLATFORM_TOKEN=xaat-...++# Axiom dataset name. Required, no default — explicit per environment so a+# misconfigured prod host doesn't silently ship into the wrong stream.+AXIOM_PLATFORM_DATASET=oc-platform-logs++# Optional: cell ID for the host envelope. Set to "<region>-<pool>" (e.g.+# eastus2-default). The control plane / worker daemons get this from their+# own worker.env / server.env; this is only needed if you have non-slog log+# lines (kernel, systemd, panic stack traces) and want them tagged with cell.+# OPENCOMPUTER_CELL_ID=eastus2-default++# OPENCOMPUTER_HOST_IP is auto-detected by install.sh if absent.diff --git a/deploy/vector/worker.yaml b/deploy/vector/worker.yamlnew file mode 100644index 00000000..143fa2ae--- /dev/null+++ b/deploy/vector/worker.yaml@@ -0,0 +1,142 @@+# Vector config for worker hosts (Azure VMs and EC2).+#+# Two pipelines, two Axiom datasets:+# • logs: journald → parse → axiom_platform sink → AXIOM_PLATFORM_DATASET+# • metrics: /metrics scrape → envelope → axiom_metrics sink → AXIOM_PLATFORM_METRICS_DATASET+#+# Separate datasets because histogram-bucket volume dwarfs log volume at scale+# and the two streams want different retention/cost policies.+#+# Install path: /etc/vector/vector.yaml+# Env file: /etc/opensandbox/vector.env (provides AXIOM_PLATFORM_TOKEN ++# AXIOM_PLATFORM_METRICS_TOKEN, populated by+# populate-vector-env.service from Key Vault at boot)+#+# Field shape after this pipeline:+# service "worker"+# service_id worker_id (e.g. w-oc-eastus2-1)+# cell_id <region>-<pool>+# region e.g. eastus2+# hostname VM hostname+# host_ip primary IPv4+# event_type "metric" for scraped Prom samples, absent on logs+# metric_name Prom metric name when event_type=="metric"+# tags Prom label map when event_type=="metric"+# request_id set per request by control plane, forwarded to worker+# sandbox_id set per request when in scope+# msg, level, ts present from slog++data_dir: /var/lib/vector++sources:+ worker_journald:+ type: journald+ include_units:+ - opensandbox-worker.service+ # Default current_boot_only=true. (Explicit `false` is rejected on+ # systemd 250-257 — Vector limitation.) Vector tracks its own cursor in+ # data_dir, so restarts pick up where they left off rather than replaying.++ # Scrape the worker's own /metrics on :9091. The worker binary serves+ # Prometheus via metrics.StartMetricsServer (cmd/worker/main.go). 30s+ # matches the worker's internal resource-stats tick so we don't capture+ # interpolated transient values.+ worker_metrics:+ type: prometheus_scrape+ endpoints:+ - http://127.0.0.1:9091/metrics+ scrape_interval_secs: 30++transforms:+ worker_parse:+ type: remap+ inputs:+ - worker_journald+ # VRL: parse_json fails for non-JSON lines (e.g. systemd boot messages,+ # panic stack traces from Go's runtime). For those we keep the original+ # message and just stamp the host envelope so they're still queryable.+ source: |+ parsed, err = parse_json(.message)+ if err == null && is_object(parsed) {+ . = merge(., object!(parsed))+ # See dev-host.yaml — drop stringified duplicate; non-JSON lines+ # keep .message as the readable content.+ del(.message)+ }+ if !exists(.service) { .service = "worker" }+ if !exists(.service_id) { .service_id = "${OPENSANDBOX_WORKER_ID:-unknown}" }+ if !exists(.cell_id) { .cell_id = "${OPENCOMPUTER_CELL_ID:-unknown}" }+ if !exists(.region) { .region = "${OPENSANDBOX_REGION:-unknown}" }+ if !exists(.host_ip) { .host_ip = "${OPENCOMPUTER_HOST_IP:-unknown}" }+ if !exists(.hostname) { .hostname, _ = get_hostname() }++ # Convert Prom metric events to log-shaped events so the Axiom sink can+ # ingest them. metric_to_log is a dedicated transform type — VRL has no+ # `to_log` function (Vector 0.55+).+ worker_metrics_to_log:+ type: metric_to_log+ inputs:+ - worker_metrics++ # Envelope: same fields as logs (service/service_id/cell_id/region/host_ip/+ # hostname) so dashboards can join across event_type and cross-filter by+ # infra dimension. event_type="metric" is the discriminator vs logs — we+ # deliberately don't reuse `kind`, which metric_to_log writes as+ # "incremental"/"absolute".+ #+ # metric_name carries the Prom name (namespaced to dodge clashes with log+ # payloads that might contain a literal `name` field). Label values stay+ # under `.tags` (region, worker_id, template, status, ...).+ worker_metrics_envelope:+ type: remap+ inputs:+ - worker_metrics_to_log+ source: |+ .event_type = "metric"+ if exists(.name) {+ .metric_name = .name+ del(.name)+ }+ .service = "worker"+ .service_id = "${OPENSANDBOX_WORKER_ID:-unknown}"+ .cell_id = "${OPENCOMPUTER_CELL_ID:-unknown}"+ .region = "${OPENSANDBOX_REGION:-unknown}"+ .host_ip = "${OPENCOMPUTER_HOST_IP:-unknown}"+ .hostname, _ = get_hostname()++sinks:+ # Logs sink: ships journald (parsed + enveloped) to the platform-logs dataset.+ # Unchanged from pre-metrics behavior.+ axiom_platform:+ type: axiom+ inputs:+ - worker_parse+ dataset: "${AXIOM_PLATFORM_DATASET}"+ token: "${AXIOM_PLATFORM_TOKEN}"+ # Disk buffer so a network blip or Axiom outage doesn't lose worker logs.+ # 256 MiB is enough for a few hours at typical worker rates; drop_newest+ # keeps the most-recent context if the buffer fills (better than blocking).+ buffer:+ type: disk+ max_size: 268435488+ when_full: drop_newest+ healthcheck:+ enabled: true++ # Metrics sink: separate Axiom dataset (typically `oc-platform-metrics`)+ # with its own ingest token. Volume is histogram-bucket-multiplied and+ # belongs on a different retention/budget than logs. If the secrets aren't+ # provisioned yet the populator writes empty values; this sink fails its+ # healthcheck and buffers to disk independently — the logs sink keeps working.+ axiom_metrics:+ type: axiom+ inputs:+ - worker_metrics_envelope+ dataset: "${AXIOM_PLATFORM_METRICS_DATASET}"+ token: "${AXIOM_PLATFORM_METRICS_TOKEN}"+ buffer:+ type: disk+ max_size: 268435488+ when_full: drop_newest+ healthcheck:+ enabled: truediff --git a/docs/api-reference/capacity/create-reservations.mdx b/docs/api-reference/capacity/create-reservations.mdxindex 046a0204..7b5fbc4b 100644--- a/docs/api-reference/capacity/create-reservations.mdx+++ b/docs/api-reference/capacity/create-reservations.mdx@@ -3,11 +3,6 @@ title: 'Create Reservation'api: 'POST /api/capacity/reservations'----<Info>- **Coming soon.** Reserved capacity is not yet available. See the- [Reserved Capacity overview](/reserved-capacity/overview).-</Info>-Commit capacity across one or more 15-minute UTC intervals in a singleatomic write. The result is one reservation event with a server-generated`reservationId` covering all intervals in the request. Seediff --git a/docs/api-reference/capacity/get-calendar.mdx b/docs/api-reference/capacity/get-calendar.mdxindex 238d734d..3a623d7a 100644--- a/docs/api-reference/capacity/get-calendar.mdx+++ b/docs/api-reference/capacity/get-calendar.mdx@@ -3,11 +3,6 @@ title: 'Get Calendar'api: 'GET /api/capacity/calendar'----<Info>- **Coming soon.** Reserved capacity is not yet available. See the- [Reserved Capacity overview](/reserved-capacity/overview).-</Info>-Return a planning snapshot of 15-minute UTC intervals in the requested window.One row per interval with current `reservedGb`, `reservableGb`, and theper-org `reservationLimitGb`. See@@ -24,11 +19,9 @@ per-org `reservationLimitGb`. See<ResponseExample>```json 200{- "generatedAt": "2026-04-28T18:00:00Z",- "staleAt": "2026-04-28T18:00:10Z",- "intervalDuration": "PT15M",- "timezone": "UTC",- "earliestReservableStart": "2026-04-28T18:30:00Z",+ "from": "2026-04-29T02:00:00Z",+ "to": "2026-04-29T04:00:00Z",+ "resource": "memory_gb","intervals": [{"startsAt": "2026-04-29T02:00:00Z",diff --git a/docs/api-reference/capacity/list-reservations.mdx b/docs/api-reference/capacity/list-reservations.mdxindex 3c4ea73c..7f60c91c 100644--- a/docs/api-reference/capacity/list-reservations.mdx+++ b/docs/api-reference/capacity/list-reservations.mdx@@ -3,21 +3,16 @@ title: 'List Reservations'api: 'GET /api/capacity/reservations'----<Info>- **Coming soon.** Reserved capacity is not yet available. See the- [Reserved Capacity overview](/reserved-capacity/overview).-</Info>-Return reservation events made by the authenticated org, inreverse-chronological order by `createdAt`. Each reservation row includesall the intervals it committed to. Useful for end-of-month reconciliationand audit.-<ParamField query="from" type="string">+<ParamField query="from" type="string" required>Return reservations whose `createdAt >= from`. RFC 3339, UTC.</ParamField>-<ParamField query="to" type="string">+<ParamField query="to" type="string" required>Return reservations whose `createdAt < to`. RFC 3339, UTC.</ParamField>@@ -32,6 +27,8 @@ and audit.<ResponseExample>```json 200{+ "from": "2026-04-01T00:00:00Z",+ "to": "2026-05-01T00:00:00Z","reservations": [{"reservationId": "9f67b8f7-7b91-4d2d-b1cb-19d0d0a14562",diff --git a/docs/blobstore-tigris-cutover.md b/docs/blobstore-tigris-cutover.mdnew file mode 100644index 00000000..c68f1f74--- /dev/null+++ b/docs/blobstore-tigris-cutover.md@@ -0,0 +1,242 @@+# Tigris cutover runbook++Zero-downtime migration of all worker object storage (checkpoints,+hibernation archives, templates, goldens) from Azure Blob to Tigris using+`internal/blobstore.FallbackStore` in migration mode as the safety net during+the soak window.++> **Why not Tigris shadow buckets?** Tigris shadow buckets require an+> S3-compatible source endpoint. Azure Blob has no native S3 API, so shadow+> buckets don't apply without a separate S3↔Azure gateway. `FallbackStore`+> accomplishes the same goal (transparent fallback on cold reads) entirely+> in-process — no extra infrastructure.++## What this covers++| Data | Old backend | Cutover mechanism |+|---|---|---|+| Checkpoints / hibernation archives / templates | Azure Blob | rclone bulk copy + FallbackStore in migration mode |+| Goldens — existing (`bases/<old-versions>/default.ext4`) | Azure Blob | rclone bulk copy (they live in the same container as checkpoints) |+| Goldens — new ones produced by future AMI bakes | Azure Blob | **AMI bake dual-writes to both Azure and Tigris** until Phase 5 |+| pg-backups / pg-wal | Azure Blob | Out of scope (managed by separate path) |++All worker-managed paths flow through `internal/blobstore.Store`, so a+single set of env-var changes switches them all.++## How worker.env is sourced++Worker `/etc/opensandbox/worker.env` is **not** baked into the AMI. The+control plane generates it per-VM at spawn time from its own `cfg`+(loaded from `/etc/opensandbox/server.env` on the CP):++```+server.env on CP → CP cfg → workerEnv template → cloud-init userdata → worker.env on each VM+```++Practical consequence: **for env-var-only changes, you edit `server.env`+on the CP and cycle workers. No AMI rebake needed.** AMI rebakes are only+required for binary or system-level changes.++> The `workerEnv` template lives in `cmd/server/main.go`. If you add new+> env vars that workers need, the template must be updated to propagate+> them. This PR added `OPENSANDBOX_S3_FALLBACK_*` and+> `OPENSANDBOX_BLOB_MIGRATION_MODE` to the template.++## Pre-flight inventory (prod, opencomputer-prod RG, eastus2)++- Storage account: `occkpt3ccf3c31`+- `checkpoints` container: ~1,854 blobs, ~2.08 TB (includes goldens in+ `bases/<hash>/default.ext4`)+- `pg-backups` / `pg-wal`: managed by postgres infra, not part of this cutover++## Tigris target++- Bucket: `opencomputer-prod` (Region Earth or `iad`, snapshots enabled)+- Layout: identical to Azure — rclone copies keys verbatim; no key+ rewriting required+- Per-backend bucket override is available: primary uses Tigris bucket+ `opencomputer-prod`, fallback uses Azure container `checkpoints`,+ configured via `OPENSANDBOX_S3_FALLBACK_BUCKET`++## Phase 1 — Ship the new binary + start dual-writing goldens++**Goal**: get the new code into the worker pool AND start uploading each+new AMI's golden to Tigris in parallel with Azure. No worker behavior+change yet (`OPENSANDBOX_S3_FALLBACK_*` unset means workers log "no+fallback" and behave identically to before).++1. Before merging: stash Tigris creds in GitHub Actions secrets used by+ `build-worker-ami.yml`:+ - `TIGRIS_ENDPOINT` = `https://t3.storage.dev`+ - `TIGRIS_ACCESS_KEY_ID` = `tid_...`+ - `TIGRIS_SECRET_ACCESS_KEY` = `tsec_...`+ - `TIGRIS_GOLDENS_BUCKET` = `opencomputer-prod`+2. Merge the PR.+3. CI builds a new worker AMI. The bake now performs **two** golden+ uploads:+ - Existing Python step → Azure container `checkpoints` (unchanged)+ - New step → Tigris bucket `opencomputer-prod` via+ `opensandbox-worker golden-upload` (skips silently if Tigris secrets+ aren't set, so this is safe on dev/PR branches that don't have them)+4. CI bumps KV `worker-image-version`. Scaler does rolling-replace.+5. Verify all workers report the new version via `GET /api/workers`.+6. Smoke test: create / hibernate / wake. Behavior identical.+7. Verify the new golden landed in Tigris:+ ```+ tigris ls "opencomputer-prod/bases/$(<the hash from packer output>)/"+ ```+ Should show `default.ext4` at the expected size.++**Rollback**: bump KV `worker-image-version` back. Scaler rolls back. The+Tigris-uploaded golden stays in Tigris as a no-op (no reader yet).++## Phase 2 — Bulk rclone Azure → Tigris++**Goal**: get ~all checkpoint data into Tigris before flipping. Workers+still on Azure — zero production impact.++1. Run `scripts/rclone-azure-to-tigris.sh` from a bastion VM in eastus2.+ - ~2 TB, ~1-3 hours on D4-class network (depends on bastion size)+2. Required rclone flags (already in the script):+ - `--s3-storage-class STANDARD` — Tigris rejects Azure's `Hot`/`Cool`+ tier names; force STANDARD or every PUT fails with 400 InvalidStorageClass+ - `--metadata=false` — skip Azure-specific metadata to avoid edge-case+ translation issues+3. Parity check when done:+ ```+ rclone size az:checkpoints+ rclone size tigris:opencomputer-prod+ ```+ Sizes should match within a small delta (new writes during the run).++**Rollback**: nothing to undo. Abandon Tigris copy; costs nothing.++## Phase 3 — Atomic flip (server.env + CP restart + worker cycle)++**Goal**: workers start writing to Tigris and reading Tigris-then-Azure.++1. **Delta rclone sync** — run again right before the next step. Picks+ up anything written to Azure since Phase 2. Should be fast (minutes).++2. **Edit `/etc/opensandbox/server.env`** on the control plane to add the+ Tigris primary, Azure fallback, and migration-mode flag:+ ```+ # Primary: Tigris+ OPENSANDBOX_S3_ENDPOINT=https://t3.storage.dev+ OPENSANDBOX_S3_BUCKET=opencomputer-prod+ OPENSANDBOX_S3_REGION=auto+ OPENSANDBOX_S3_FORCE_PATH_STYLE=true+ OPENSANDBOX_S3_ACCESS_KEY_ID=<tigris key>+ OPENSANDBOX_S3_SECRET_ACCESS_KEY=<tigris secret>++ # Fallback: Azure+ OPENSANDBOX_S3_FALLBACK_ENDPOINT=https://occkpt3ccf3c31.blob.core.windows.net+ OPENSANDBOX_S3_FALLBACK_REGION=eastus2+ OPENSANDBOX_S3_FALLBACK_ACCESS_KEY_ID=occkpt3ccf3c31+ OPENSANDBOX_S3_FALLBACK_SECRET_ACCESS_KEY=<azure key>+ OPENSANDBOX_S3_FALLBACK_BUCKET=checkpoints++ # Lazy-migration: Tigris-miss falls through to Azure+ OPENSANDBOX_BLOB_MIGRATION_MODE=true+ ```++3. **Restart the control plane**:+ ```+ systemctl restart opensandbox-server+ ```+ Re-reads `server.env`. From now on, every new worker spawned by the+ scaler is templated with the new env via cloud-init.++4. **Cycle workers** — two options:+ - **Soft (gradual)**: do nothing. Existing workers keep their old env+ until the scaler cycles them (could be hours/days). Mixed pool during+ the window is fine — cross-worker ops still work because the+ new-config workers can fallback-read whatever the old-config workers+ wrote. The reverse direction (new writes Tigris, old needs to read)+ is avoided by the scaler's drain semantics — old workers are drained,+ not given new placements.+ - **Aggressive (forced)**: delete workers one at a time via+ `az vm delete -g opencomputer-prod -n osb-worker-<id>`. Scaler+ replaces each with a new VM that gets the new env. Whole pool+ flipped in minutes.++5. **Verify** as each worker cycles, log line:+ ```+ checkpoint store: tigris primary, azure-blob-fallback fallback (migration=true)+ ```++**Rollback**: revert `server.env`, restart CP, cycle workers. Data+already in Tigris stays there (passive replica); Azure remains+authoritative throughout the soak window.++## Phase 4 — Soak (1–2 weeks)++Monitor:+- Worker logs for `blobstore: primary tigris failed (...); trying fallback azure-blob` — expected near-zero and trending down as the warm working set lands in Tigris.+- Tigris dashboard: error rate, latency, ingress volume.+- Synthetic daily test: create / checkpoint / fork on another worker / hibernate / wake.++If fallback hit rate stays elevated, run another delta rclone sync to+warm cold keys into Tigris proactively.++## Phase 5 — Disable fallback + drop Azure golden upload (commit to Tigris)++1. Edit `server.env`: remove the `OPENSANDBOX_S3_FALLBACK_*` block and+ `OPENSANDBOX_BLOB_MIGRATION_MODE`.+2. Restart CP.+3. Cycle workers (same options as Phase 3 step 4).+4. Verify log: `checkpoint store: tigris primary (no fallback)`.+5. **Remove the Python Azure-upload step from `deploy/packer/worker-ami.pkr.hcl`.**+ At this point Tigris is the authoritative store and Azure shouldn't+ receive new writes. The Tigris-upload step stays.+6. Optionally also remove the "download previous golden from Azure" step+ and replace with a Tigris fetch (or accept the runtime fetch cost for+ forks of stale-pinned checkpoints, which should be rare).++**Rollback past this point** is harder. Re-adding the fallback re-enables+the safety net, but any keys written to Tigris during the no-fallback+window don't exist in Azure. If Azure must become authoritative again,+run a reverse rclone (Tigris → Azure). Don't enter this phase until+Phase 4 has been clean for at least a week.++## Phase 6 — Decommission Azure++After ~30 days of zero observed reads on the Azure side (verify via Azure+storage metrics):++1. Snapshot the `checkpoints` container to a different storage account+ as a one-time backup (optional).+2. `az storage container delete --account-name occkpt3ccf3c31 -n checkpoints`+3. Eventually delete the storage account.++## Operational rules++- **Never `systemctl restart opensandbox-worker` by hand in prod.** The+ scaler treats the heartbeat gap as "worker unhealthy" and replaces the+ VM from the current AMI — losing any local state. We hit this during+ dev validation. Always cycle workers by deleting them so the scaler+ replaces them cleanly.++- **Don't hold the leader lock in prod.** Holding+ `controlplane:leader = MAINTENANCE-HOLD` pauses the scaler — including+ the rolling-replace that the cutover relies on. The lock trick is for+ one-off dev hot-swaps only.++- **Live migration during the rolling window works** because the new+ workers are in migration mode. Drain direction is OLD → NEW: old+ worker writes drives to Azure, new worker reads Tigris (miss) →+ fallback to Azure (hit) → migration succeeds. The reverse direction+ (NEW writes, OLD reads) doesn't happen — old workers are being+ drained, not receiving new placements.++## Code surface++- `internal/blobstore/store.go` — `Store` interface (Get / GetRange / Put / Head / Exists / Delete / Name)+- `internal/blobstore/s3.go` — S3-compatible backend (Tigris, R2, AWS S3, MinIO); supports per-backend `Bucket` override+- `internal/blobstore/azure.go` — Azure Blob backend; same `Bucket` override pattern+- `internal/blobstore/fallback.go` — `FallbackStore` with `NewFallback` (HA mode) and `NewMigrationFallback` (lazy-migration mode)+- `internal/storage/s3.go` — `CheckpointStore` higher-level type, built on top of `blobstore.Store`+- `cmd/server/main.go` — `workerEnv` template propagates `OPENSANDBOX_S3_FALLBACK_*` and `OPENSANDBOX_BLOB_MIGRATION_MODE` to each spawned worker+- `cmd/worker/main.go` — `buildCheckpointBackend` helper; combines primary + fallback for the checkpoint path+- `internal/config/config.go` — env-var parsing for the new vars+- `scripts/rclone-azure-to-tigris.sh` — bulk + delta rclone driver (with `--s3-storage-class STANDARD --metadata=false`)diff --git a/docs/docs.json b/docs/docs.jsonindex 2b8bbf5c..5012e24b 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -122,6 +122,7 @@"pages": ["reference/typescript-sdk/overview","reference/typescript-sdk/sandbox",+ "reference/typescript-sdk/scaling","reference/typescript-sdk/exec","reference/typescript-sdk/filesystem","reference/typescript-sdk/pty",@@ -135,6 +136,7 @@"pages": ["reference/python-sdk/overview","reference/python-sdk/sandbox",+ "reference/python-sdk/scaling","reference/python-sdk/exec","reference/python-sdk/filesystem","reference/python-sdk/pty",@@ -149,6 +151,7 @@"reference/cli/overview","reference/cli/agent","reference/cli/sandbox",+ "reference/cli/scaling","reference/cli/exec","reference/cli/shell","reference/cli/checkpoint",diff --git a/docs/reference/cli/sandbox.mdx b/docs/reference/cli/sandbox.mdxindex 49985521..76bcb029 100644--- a/docs/reference/cli/sandbox.mdx+++ b/docs/reference/cli/sandbox.mdx@@ -87,3 +87,63 @@ Update the idle timeout for a running sandbox. [HTTP API →](/api-reference/san```bashoc sandbox set-timeout sb-abc123 600```++---++For commands that resize a sandbox or freeze its size — `scale`, `autoscale`, `lock`, `unlock`, `lock-status` — see [Scaling](/reference/cli/scaling).++---++## `oc sandbox allowed-hosts <id>`++Show the egress allowlist + per-secret allowed hosts the sandbox's secrets proxy enforces. Useful for debugging "why is my outbound HTTP call being blocked" without having to cross-reference the [secret store](/sandboxes/secrets) config separately.++Sandboxes created without `--secret-store` return an empty allowlist — the sandbox has no per-store egress restriction.++```bash+oc sandbox allowed-hosts sb-abc123+# Sandbox sb-abc123 (secret store: my-store)+#+# Egress allowlist:+# • api.openai.com+# • api.anthropic.com+#+# Per-secret allowed hosts:+# OPENAI_API_KEY:+# • api.openai.com+```++Use `--json` for the structured form:++```bash+oc sandbox allowed-hosts sb-abc123 --json+```++```json+{+ "sandboxID": "sb-abc123",+ "secretStore": "my-store",+ "egressAllowlist": ["api.openai.com", "api.anthropic.com"],+ "perSecretAllowedHosts": {+ "OPENAI_API_KEY": ["api.openai.com"]+ }+}+```++### Layered forks++When a fork layers an additional `--secret-store` on top of an inherited one, `egressAllowlist` is the **union** of both stores' allowlists (matches what the runtime proxy enforces). The response includes both store names — `secretStore` is the primary (whose secrets shadow the base on env-name collisions), `baseSecretStore` is the inherited parent:++```json+{+ "sandboxID": "sb-fork456",+ "secretStore": "fork-override",+ "baseSecretStore": "fork-parent",+ "egressAllowlist": ["api.openai.com", "api.anthropic.com", "api.example.com"],+ "perSecretAllowedHosts": {+ "OPENAI_API_KEY": ["api.openai.com"]+ }+}+```++`baseSecretStore` is omitted in the single-store case (no layering).diff --git a/docs/reference/cli/scaling.mdx b/docs/reference/cli/scaling.mdxnew file mode 100644index 00000000..4a6b200d--- /dev/null+++ b/docs/reference/cli/scaling.mdx@@ -0,0 +1,121 @@+---+title: "oc sandbox scaling"+description: "Resize sandboxes, configure autoscale, and manage scaling locks from the CLI"+---++The CLI groups three related actions for sizing a sandbox:++| Command | What it does |+| --- | --- |+| [`oc sandbox autoscale`](#oc-sandbox-autoscale-id) | Turn the platform autoscaler on/off and inspect its config |+| [`oc sandbox scale`](#oc-sandbox-scale-id-memory-mb) | Manually resize once |+| [`oc sandbox lock`](#oc-sandbox-lock-id) / [`unlock`](#oc-sandbox-unlock-id) / [`lock-status`](#oc-sandbox-lock-status-id) | Freeze or unfreeze the current size |++Memory tiers are fixed: `1024`, `4096`, `8192`, `16384`, `32768`, `65536` MB. CPU follows memory per the platform's tier table (e.g. 8 GB → 4 vCPU); you don't pick CPU separately.++For the underlying concepts and how these three modes interact, see the [Elasticity](/sandboxes/elasticity) guide.++---++## `oc sandbox autoscale <id>`++Configure or inspect per-sandbox autoscale. [HTTP API →](/api-reference/sandboxes/autoscale)++Run with no flags to print the current configuration:++```bash+oc sandbox autoscale sb-abc123+# Autoscale enabled for sb-abc123 (1024–16384 MB)+```++Enable with bounds:++```bash+oc sandbox autoscale sb-abc123 --on --min 1024 --max 16384+```++Disable:++```bash+oc sandbox autoscale sb-abc123 --off+```++When enabled, the platform watches memory pressure and resizes the sandbox between `--min` and `--max`:++- **Scale up** on a single 1-min sample above 75 % memory utilization. Cooldown 60 s between up-scales.+- **Scale down** only when the 1-min, 5-min, AND 15-min averages all sit below 25 %. Cooldown 5 min between down-scales.++The asymmetry is deliberate: rapid response when the user notices lag, conservative shrink after sustained idle.++**Flags**++| Flag | Description |+| --- | --- |+| `--on` | Enable autoscale (requires `--min` and `--max`). |+| `--off` | Disable autoscale. Mutually exclusive with `--on`. |+| `--min N` | Minimum memory tier in MB. Must be an allowed tier. |+| `--max N` | Maximum memory tier in MB. Must be an allowed tier and ≥ `--min`. |++**Errors**++- `scaling_locked` — the sandbox has a scaling lock active. Run `oc sandbox unlock <id>` first.+- `402 Payment Required` — `--max` exceeds your plan cap.++---++## `oc sandbox scale <id> <memory-mb>`++Manually resize a sandbox to a specific memory tier. [HTTP API →](/api-reference/sandboxes/scale)++```bash+oc sandbox scale sb-abc123 8192+# Scaled sb-abc123 to 8192MB / 400% CPU+```++A manual scale **disables autoscale** on this sandbox as a side effect — explicit intent overrides the loop. Re-enable with `oc sandbox autoscale --on` if you want size to track load again.++**Errors**++- `scaling_locked` — the sandbox has a scaling lock active. Run `oc sandbox unlock <id>` first.+- `402 Payment Required` — requested size exceeds your plan cap.++---++## `oc sandbox lock <id>`++Pin a sandbox at its current size. [HTTP API →](/api-reference/sandboxes/scaling-lock)++```bash+oc sandbox lock sb-abc123+# Sandbox sb-abc123 locked (scaling disabled)+```++While locked:++- `oc sandbox scale` is rejected with `scaling_locked`.+- `oc sandbox autoscale --on` is rejected with `scaling_locked`.+- The platform autoscaler skips the sandbox entirely.++Locking **also** disables autoscale (single knob — "I don't want this scaling, period"). Unlocking does NOT re-enable autoscale; run `oc sandbox autoscale --on` explicitly if you want it back.++---++## `oc sandbox unlock <id>`++Clear the scaling lock.++```bash+oc sandbox unlock sb-abc123+# Sandbox sb-abc123 unlocked+```++---++## `oc sandbox lock-status <id>`++Print the current scaling-lock state.++```bash+oc sandbox lock-status sb-abc123+# Sandbox sb-abc123 is unlocked+```diff --git a/docs/reference/python-sdk/sandbox.mdx b/docs/reference/python-sdk/sandbox.mdxindex d844b2bd..04c1cced 100644--- a/docs/reference/python-sdk/sandbox.mdx+++ b/docs/reference/python-sdk/sandbox.mdx@@ -234,6 +234,34 @@ Generate a signed upload URL. [HTTP API →](/api-reference/files/generate-uploa[HTTP API →](/api-reference/preview/delete) — **Returns:** `None`+### `await sandbox.get_allowed_hosts()`++Return the egress allowlist + per-secret allowed hosts the sandbox's secrets proxy enforces. Useful for debugging "why is my outbound HTTP call being blocked" without having to cross-reference the [secret store](/sandboxes/secrets) config separately.++Sandboxes created without a `secret_store` option return an empty allowlist with `secretStore` omitted — the sandbox has no per-store egress restriction.++**Returns:** `dict` with the shape:++```python+{+ "sandboxID": "sb-...",+ "secretStore": "my-store", # omitted if no store+ "baseSecretStore": "parent-store", # omitted unless this is a layered fork+ "egressAllowlist": ["api.openai.com", ...],+ "perSecretAllowedHosts": {+ "OPENAI_API_KEY": ["api.openai.com"],+ },+}+```++For forks that layered an additional ``secret_store`` on top of an inherited one, ``egressAllowlist`` is the **union** of both stores' allowlists (matches what the runtime proxy enforces) and ``baseSecretStore`` is populated with the inherited parent's name. For sandboxes with a single store (or none), ``baseSecretStore`` is omitted.++```python+info = await sandbox.get_allowed_hosts()+print(info["egressAllowlist"]) # ['api.openai.com', 'api.anthropic.com']+print(info["perSecretAllowedHosts"]) # {'OPENAI_API_KEY': ['api.openai.com']}+```+### `await sandbox.close()`Close HTTP clients. Called automatically by the context manager.diff --git a/docs/reference/python-sdk/scaling.mdx b/docs/reference/python-sdk/scaling.mdxnew file mode 100644index 00000000..214f16c9--- /dev/null+++ b/docs/reference/python-sdk/scaling.mdx@@ -0,0 +1,171 @@+---+title: "Scaling"+description: "Resize a sandbox manually, autoscale on memory pressure, or freeze its resources."+---++OpenComputer sandboxes can change size at runtime. There are three knobs:++| What you want | Use |+| --- | --- |+| Resize once, predictably | [`scale()`](#sandbox-scale-memory-mb) |+| Track memory pressure automatically | [`set_autoscale()`](#sandbox-set-autoscale) |+| Freeze the current size | [`set_scaling_lock()`](#sandbox-set-scaling-lock-locked) |++Memory tiers are fixed: `1024`, `4096`, `8192`, `16384`, `32768`, `65536` MB. CPU follows memory per the platform's tier table (e.g. 8 GB → 4 vCPU). You don't pick CPU separately.++## How the three interact++- **Manual `scale()`** disables autoscale on the sandbox as a side effect — explicit user intent overrides the loop. Re-enable with `set_autoscale(enabled=True, ...)` after if you want.+- **Setting a scaling lock** disables autoscale at the same time (single knob: "I don't want this scaling, period"). While locked, both `scale()` and `set_autoscale(enabled=True)` raise `ScalingLockedError`. Unlocking does NOT auto-re-enable autoscale.+- **Plan caps** apply everywhere. Free-tier orgs are capped at 4 GB. Calls above the cap raise `PlanLimitError`.++---++## `sandbox.scale(memory_mb)`++Manually resize the sandbox. [HTTP API →](/api-reference/sandboxes/scale)++<ParamField body="memory_mb" type="int" required>+ Target memory tier in MB. Must be one of the allowed tiers.+</ParamField>++**Returns:** `dict` with `sandboxID`, `memoryMB`, `cpuPercent`.++**Raises:**++- `ScalingLockedError` — sandbox has a scaling lock active.+- `PlanLimitError` — `memory_mb` exceeds the org's plan cap.++```python+from opencomputer import Sandbox, ScalingLockedError, PlanLimitError++sandbox = await Sandbox.connect("sb-abc123")++try:+ result = await sandbox.scale(memory_mb=8192)+ print(f"scaled to {result['memoryMB']}MB / {result['cpuPercent']}% CPU")+except ScalingLockedError:+ print("sandbox is locked — unlock to scale")+except PlanLimitError:+ print("upgrade required for larger instances")+```++---++## `sandbox.set_autoscale(enabled, *, min_memory_mb=None, max_memory_mb=None)`++Enable or disable per-sandbox autoscale.++<ParamField body="enabled" type="bool" required>+ Whether autoscale should be active.+</ParamField>++<ParamField body="min_memory_mb" type="int">+ Lower bound when `enabled=True`. Must be an allowed tier.+</ParamField>++<ParamField body="max_memory_mb" type="int">+ Upper bound when `enabled=True`. Must be an allowed tier and ≥ `min_memory_mb`.+</ParamField>++**Returns:** `dict` with `sandboxID`, `enabled`, `minMemoryMB`, `maxMemoryMB`.++**Raises:**++- `ScalingLockedError` — sandbox has a scaling lock active.+- `PlanLimitError` — `max_memory_mb` exceeds the org's plan cap.++When `enabled=True`, the platform watches the sandbox's memory pressure and resizes it within the bounds:++- **Scale up** on a single 1-min sample above 75% memory utilization. Cooldown 60s between up-scales.+- **Scale down** only when 1-min, 5-min, AND 15-min averages all sit below 25%. Cooldown 5 min between down-scales.++The asymmetry matches user perception: rapid response when the user notices lag, conservative shrink after sustained idle. The 15-min window is the dominant constraint on shrink, so a sandbox that briefly idles and resumes won't sawtooth.++```python+await sandbox.set_autoscale(+ enabled=True,+ min_memory_mb=1024,+ max_memory_mb=16384,+)+```++To turn off:++```python+await sandbox.set_autoscale(enabled=False)+```++---++## `sandbox.get_autoscale()`++Get the current autoscale configuration.++**Returns:** `dict` with `sandboxID`, `enabled`, `minMemoryMB`, `maxMemoryMB`.++```python+cfg = await sandbox.get_autoscale()+if cfg["enabled"]:+ print(f"autoscale {cfg['minMemoryMB']}–{cfg['maxMemoryMB']} MB")+```++---++## `sandbox.set_scaling_lock(locked)`++Lock or unlock the sandbox's resources against any size change.++<ParamField body="locked" type="bool" required>+ `True` to freeze, `False` to allow scaling again.+</ParamField>++**Returns:** `dict` with `sandboxID`, `locked`.++While locked:++- `scale()` raises `ScalingLockedError`.+- `set_autoscale(enabled=True)` raises `ScalingLockedError`.+- The platform autoscaler skips this sandbox entirely.++Locking ALSO disables autoscale (single knob — "I don't want this scaling"). Unlocking does **not** re-enable autoscale; call `set_autoscale(enabled=True, ...)` explicitly if you want it back.++```python+# Pin a sandbox at its current size during a critical workload+await sandbox.set_scaling_lock(True)++# ...++# Allow scaling again after+await sandbox.set_scaling_lock(False)+```++---++## `sandbox.get_scaling_lock()`++Get the current scaling-lock state.++**Returns:** `dict` with `sandboxID`, `locked`.++---++## Errors++### `ScalingLockedError`++Raised when the sandbox has a scaling lock active. Has a class attribute `code = "scaling_locked"` for parity with the HTTP API's error code.++```python+from opencomputer import ScalingLockedError++try:+ await sandbox.scale(memory_mb=8192)+except ScalingLockedError:+ # unlock first, or surface to user+ ...+```++### `PlanLimitError`++Raised when the requested size exceeds the org's plan cap. The HTTP API returns 402 Payment Required for this case.diff --git a/docs/reference/typescript-sdk/sandbox.mdx b/docs/reference/typescript-sdk/sandbox.mdxindex 8db74229..45525539 100644--- a/docs/reference/typescript-sdk/sandbox.mdx+++ b/docs/reference/typescript-sdk/sandbox.mdx@@ -286,6 +286,44 @@ Generate a signed upload URL. [HTTP API →](/api-reference/files/generate-uploa---+### `sandbox.getAllowedHosts()`++Return the egress allowlist + per-secret allowed hosts the sandbox's secrets proxy enforces. Useful for debugging "why is my outbound HTTP call being blocked" without having to cross-reference the [secret store](/sandboxes/secrets) config separately.++Sandboxes created without a `secretStore` option return an empty allowlist with `secretStore` undefined — the sandbox has no per-store egress restriction.++**Returns:** `Promise<AllowedHostsInfo>`++```typescript+const info = await sandbox.getAllowedHosts();+console.log(info.egressAllowlist); // ['api.openai.com', 'api.anthropic.com']+console.log(info.perSecretAllowedHosts); // { 'OPENAI_API_KEY': ['api.openai.com'] }+```++The returned `AllowedHostsInfo`:++<ParamField body="sandboxID" type="string">+ Sandbox ID+</ParamField>++<ParamField body="secretStore" type="string">+ Name of the primary secret store the sandbox is bound to (the "winning" store on the row, whose secrets shadow the base store on env-name collisions). Empty when the sandbox was created without a `secretStore` option.+</ParamField>++<ParamField body="baseSecretStore" type="string">+ Name of the inherited parent store, present only when a fork layered an additional `secretStore` on top of an inherited one. Empty for sandboxes created from scratch and for forks without an override.+</ParamField>++<ParamField body="egressAllowlist" type="string[]">+ Hosts the sandbox can reach via the secrets proxy. For layered forks this is the **union** of every layered store's allowlist (base first, primary's additions appended, deduped) — matches what the runtime proxy actually enforces.+</ParamField>++<ParamField body="perSecretAllowedHosts" type="Record<string, string[]>">+ Optional per-secret restrictions. When the sandbox uses a listed secret in a request, only the listed hosts are reachable for that request. For layered forks, the primary store's secrets shadow the base on name collisions (matches runtime env-collision behavior).+</ParamField>++---+## Properties<ParamField body="sandboxId" type="string">diff --git a/docs/reference/typescript-sdk/scaling.mdx b/docs/reference/typescript-sdk/scaling.mdxnew file mode 100644index 00000000..4ca44ae5--- /dev/null+++ b/docs/reference/typescript-sdk/scaling.mdx@@ -0,0 +1,179 @@+---+title: "Scaling"+description: "Resize a sandbox manually, autoscale on memory pressure, or freeze its resources."+---++OpenComputer sandboxes can change size at runtime. There are three knobs:++| What you want | Use |+| --- | --- |+| Resize once, predictably | [`scale()`](#sandbox-scale-opts) |+| Track memory pressure automatically | [`setAutoscale()`](#sandbox-setautoscale-opts) |+| Freeze the current size | [`setScalingLock()`](#sandbox-setscalinglock-locked) |++Memory tiers are fixed: `1024`, `4096`, `8192`, `16384`, `32768`, `65536` MB. CPU follows memory per the platform's tier table (e.g. 8 GB → 4 vCPU). You don't pick CPU separately.++## How the three interact++- **Manual `scale()`** disables autoscale on the sandbox as a side effect — explicit user intent overrides the loop. Re-enable autoscale with `setAutoscale({ enabled: true, ... })` after if you want.+- **Setting a scaling lock** disables autoscale at the same time (single-knob: "I don't want this scaling, period"). While locked, both `scale()` and `setAutoscale({ enabled: true })` reject with `ScalingLockedError`. Unlocking does NOT auto-re-enable autoscale.+- **Plan caps** apply everywhere. Free-tier orgs are capped at 4 GB. Calls above the cap throw `PlanLimitError`.++---++## `sandbox.scale(opts)`++Manually resize the sandbox. [HTTP API →](/api-reference/sandboxes/scale)++<ParamField body="memoryMB" type="number" required>+ Target memory tier in MB. Must be one of the allowed tiers.+</ParamField>++**Returns:** `Promise<{ sandboxID: string; memoryMB: number; cpuPercent: number }>`++**Throws:**++- `ScalingLockedError` — sandbox has a scaling lock active.+- `PlanLimitError` — `memoryMB` exceeds the org's plan cap.++```typescript+import { Sandbox, ScalingLockedError, PlanLimitError } from "@opencomputer/sdk";++const sandbox = await Sandbox.connect("sb-abc123");++try {+ const result = await sandbox.scale({ memoryMB: 8192 });+ console.log(`scaled to ${result.memoryMB}MB / ${result.cpuPercent}% CPU`);+} catch (err) {+ if (err instanceof ScalingLockedError) {+ console.warn("sandbox is locked — unlock to scale");+ } else if (err instanceof PlanLimitError) {+ console.warn("upgrade required for larger instances");+ } else {+ throw err;+ }+}+```++---++## `sandbox.setAutoscale(opts)`++Enable or disable per-sandbox autoscale.++<ParamField body="enabled" type="boolean" required>+ Whether autoscale should be active.+</ParamField>++<ParamField body="minMemoryMB" type="number">+ Lower bound when `enabled=true`. Must be an allowed tier.+</ParamField>++<ParamField body="maxMemoryMB" type="number">+ Upper bound when `enabled=true`. Must be an allowed tier and ≥ `minMemoryMB`.+</ParamField>++**Returns:** `Promise<{ sandboxID: string; enabled: boolean; minMemoryMB: number; maxMemoryMB: number }>`++**Throws:**++- `ScalingLockedError` — sandbox has a scaling lock active.+- `PlanLimitError` — `maxMemoryMB` exceeds the org's plan cap.++When `enabled=true`, the platform watches the sandbox's memory pressure and resizes it within the bounds:++- **Scale up** on a single 1-min sample above 75% memory utilization. Cooldown 60s between up-scales.+- **Scale down** only when 1-min, 5-min, AND 15-min averages all sit below 25%. Cooldown 5 min between down-scales.++The asymmetry matches user perception: rapid response when the user notices lag, conservative shrink after sustained idle. The 15-min window is the dominant constraint on shrink, so a sandbox that briefly idles and resumes won't sawtooth.++```typescript+await sandbox.setAutoscale({+ enabled: true,+ minMemoryMB: 1024,+ maxMemoryMB: 16384,+});+```++To turn off:++```typescript+await sandbox.setAutoscale({ enabled: false });+```++---++## `sandbox.getAutoscale()`++Get the current autoscale configuration.++**Returns:** `Promise<{ sandboxID: string; enabled: boolean; minMemoryMB: number; maxMemoryMB: number }>`++```typescript+const cfg = await sandbox.getAutoscale();+if (cfg.enabled) {+ console.log(`autoscale ${cfg.minMemoryMB}–${cfg.maxMemoryMB} MB`);+}+```++---++## `sandbox.setScalingLock(locked)`++Lock or unlock the sandbox's resources against any size change.++<ParamField body="locked" type="boolean" required>+ `true` to freeze, `false` to allow scaling again.+</ParamField>++**Returns:** `Promise<{ sandboxID: string; locked: boolean }>`++While locked:++- `scale()` rejects with `ScalingLockedError`.+- `setAutoscale({ enabled: true })` rejects with `ScalingLockedError`.+- The platform autoscaler skips this sandbox entirely.++Locking ALSO disables autoscale (single knob — "I don't want this scaling"). Unlocking does **not** re-enable autoscale; call `setAutoscale({ enabled: true, ... })` explicitly if you want it back.++```typescript+// Pin a sandbox at its current size during a critical workload+await sandbox.setScalingLock(true);++// ...++// Allow scaling again after+await sandbox.setScalingLock(false);+```++---++## `sandbox.getScalingLock()`++Get the current scaling-lock state.++**Returns:** `Promise<{ sandboxID: string; locked: boolean }>`++---++## Errors++### `ScalingLockedError`++Thrown when the sandbox has a scaling lock active. Has a `code` property of `"scaling_locked"` for parity with the HTTP API's error code.++```typescript+import { ScalingLockedError } from "@opencomputer/sdk";++try {+ await sandbox.scale({ memoryMB: 8192 });+} catch (err) {+ if (err instanceof ScalingLockedError) {+ // unlock first, or surface to user+ }+}+```++### `PlanLimitError`++Thrown when the requested size exceeds the org's plan cap. The HTTP API returns 402 Payment Required for this case.diff --git a/docs/reserved-capacity/calendar.mdx b/docs/reserved-capacity/calendar.mdxindex 96a7362f..9a2687c6 100644--- a/docs/reserved-capacity/calendar.mdx+++ b/docs/reserved-capacity/calendar.mdx@@ -3,11 +3,6 @@ title: "Reading the Calendar"description: "Preview reservable capacity and existing commitments per 15-minute interval"----<Info>- **Coming soon.** Reserved capacity is not yet available. The contract below- may change before launch.-</Info>-The calendar is how you plan. It answers, per 15-minute interval:1. How much GB can I still reserve here?@@ -33,11 +28,9 @@ curl "https://app.opencomputer.dev/api/capacity/calendar?from=2026-04-29T02:00:0```json{- "generatedAt": "2026-04-28T18:00:00Z",- "staleAt": "2026-04-28T18:00:10Z",- "intervalDuration": "PT15M",- "timezone": "UTC",- "earliestReservableStart": "2026-04-28T18:30:00Z",+ "from": "2026-04-29T02:00:00Z",+ "to": "2026-04-29T04:00:00Z",+ "resource": "memory_gb","intervals": [{"startsAt": "2026-04-29T02:00:00Z",@@ -54,11 +47,9 @@ curl "https://app.opencomputer.dev/api/capacity/calendar?from=2026-04-29T02:00:0| Field | Meaning || --- | --- |-| `generatedAt` | When the server computed this snapshot. |-| `staleAt` | After this, refresh before using the snapshot for planning. |-| `intervalDuration` | Always `PT15M` in v1. |-| `timezone` | Always `UTC` in v1. |-| `earliestReservableStart` | First interval currently eligible for new reservations. The server enforces a minimum lead time between `now` and a bookable `startsAt`. |+| `from`, `to` | The query window, echoed back. |+| `resource` | Always `memory_gb` in v1. |+| `intervals` | One row per 15-minute interval in the window. |### Per-interval fields@@ -69,6 +60,11 @@ curl "https://app.opencomputer.dev/api/capacity/calendar?from=2026-04-29T02:00:0| `reservedGb` | Total GB this org already has reserved in this interval. || `reservableGb` | Additional GB the server would currently accept. **This is the number to plan against.** |+The server enforces a **30-minute minimum lead time** between `now`+and a reservation's `startsAt`. Intervals starting sooner are returned+in the calendar (so you can see your existing commitments) but the+write endpoint rejects new reservations against them.+## `reservableGb` is the planning fieldEverything you need to decide "can I reserve 50 GB at 02:00?" is in@@ -80,11 +76,11 @@ Everything you need to decide "can I reserve 50 GB at 02:00?" is in- `reservedGb` lets you confirm what you already hold without a separatecall to `GET /api/capacity/reservations`.-## `staleAt` is a freshness marker, not a hold+## The calendar is a snapshot, not a hold-The calendar snapshot is cheap and immediate. `staleAt` tells you when to-refresh, but capacity can change at any moment — another tenant (or you,-in another tab) may reserve between `generatedAt` and your write.+The calendar reflects state at the moment the request was served.+Capacity can change between read and write — another tenant (or you,+in another tab) may reserve in the meantime.This is fine. Writes are atomic and validation is authoritative: ifcapacity moved, the write returns `capacity_not_available` and you readdiff --git a/docs/reserved-capacity/concepts.mdx b/docs/reserved-capacity/concepts.mdxindex ef717d97..feef8c77 100644--- a/docs/reserved-capacity/concepts.mdx+++ b/docs/reserved-capacity/concepts.mdx@@ -3,11 +3,6 @@ title: "Concepts"description: "Intervals, reservations, the reservation log, and the per-org cap"----<Info>- **Coming soon.** Reserved capacity is not yet available. The contract below- may change before launch.-</Info>-A small vocabulary. Learn these and the rest of the API reads itself.## Interval@@ -96,20 +91,13 @@ See [Reading the calendar](/reserved-capacity/calendar) for the full shape.## Per-org capacity cap-Your org has a single configured ceiling: `max_memory_gb`. It applies in-two places:--| Where | What it limits |-| --- | --- |-| Reservations | Across any single interval, your `reservedGb` cannot exceed `max_memory_gb`. |-| Runtime | Your concurrent running memory across all sandboxes cannot exceed `max_memory_gb` either. |--Same number, two enforcement points. The mental model: "I can have up to-N GB of memory in flight at once, whether reserved or running." If you-need to reserve more than your current limit allows, ask to have the-limit raised.+Your org has a configured ceiling: `max_memory_gb`. It limits how+much capacity you can hold in any single 15-minute interval — your+`reservedGb` for an interval cannot exceed it. The cap appears as+`reservationLimitGb` in calendar interval rows.-This appears as `reservationLimitGb` in calendar interval rows.+If you need to reserve more than your current limit allows, ask to+have the limit raised.## Usage and overagediff --git a/docs/reserved-capacity/overview.mdx b/docs/reserved-capacity/overview.mdxindex b66e195b..1a5df02d 100644--- a/docs/reserved-capacity/overview.mdx+++ b/docs/reserved-capacity/overview.mdx@@ -3,13 +3,6 @@ title: "Reserved Capacity"description: "Commit memory capacity to future 15-minute intervals at a discounted rate"----<Info>- **Coming soon.** Reserved capacity is not yet available. These pages describe- the forthcoming v1 API. The contract may change before launch. [Book a- call](https://cal.com/team/digger/opencomputer-founder-chat) to be notified- when it ships or to influence the design.-</Info>-Reserved capacity lets you pre-commit to memory you'll use later. OpenComputerplans for it instead of holding margin against uncertain demand; you get alower effective rate on the committed usage. Pure on-demand still works for@@ -85,9 +78,9 @@ that interval falls back to on-demand rates.## Why reserve instead of running on-demand?-| | On-demand | Reserved |+| | On-demand (instant) | Reserved (pre-booked) || --- | --- | --- |-| Cost per GB-second | Higher (includes reserve-margin premium) | Lower |+| Rate | $0.060/GB-hour | $0.012/GB-hour || Commitment | None | Full — you pay regardless of usage || Availability | Subject to platform headroom | Guaranteed for the interval you booked || Best for | Unpredictable or bursty workloads | Nightly batch jobs, scheduled runs, known traffic patterns |@@ -121,8 +114,9 @@ window.</Tip><Note>- **Pricing is intentionally out of scope here.** This API manages capacity- rights only. Reserved usage is billed at a discounted rate, overage at the- on-demand rate. Specific dollar amounts will be announced separately before- launch.+ **Pricing.** Pre-booked capacity bills at **$0.012/GB-hour**; instant+ (overage) bills at **$0.060/GB-hour** — a 5× ratio that's the price of+ optionality for capacity you didn't pre-commit. Both rates are flat+ across sandbox sizes. Disk above the 20 GB allowance is billed+ separately at the disk-overage rate (unchanged).</Note>diff --git a/docs/reserved-capacity/reserving.mdx b/docs/reserved-capacity/reserving.mdxindex 529c9aea..dddb7bfb 100644--- a/docs/reserved-capacity/reserving.mdx+++ b/docs/reserved-capacity/reserving.mdx@@ -3,11 +3,6 @@ title: "Reserving Capacity"description: "Write flow, idempotency, atomicity, and the audit list"----<Info>- **Coming soon.** Reserved capacity is not yet available. The contract below- may change before launch.-</Info>-There are two write-side endpoints: `POST` to commit, `GET` to audit. Bothwork in terms of intervals and integer GB; there are no individual blocksor unit IDs.@@ -51,16 +46,22 @@ Response (success):### Validation-| Rule | Behavior |+The server rejects malformed requests with `400 Bad Request` and a+plain text error message:++| Rule | Failure || --- | --- |-| `startsAt` and `endsAt` UTC and 15-minute aligned | Reject misaligned. |-| `endsAt == startsAt + 15 minutes` | Reject longer spans; enumerate intervals. |-| `capacityGb` is a positive multiple of 4 | Reject anything else. The grain is 1 GB-hour (= 4 GB × 15 min). |-| `startsAt >= earliestReservableStart` | Reject intervals too soon. |-| Requested capacity fits current `reservableGb` | Reject instead of overbooking. |-| `Idempotency-Key` stable on retry | Replaying same key + body returns original result. |+| `startsAt` / `endsAt` UTC and 15-minute aligned | Misaligned values rejected. |+| `endsAt == startsAt + 15 minutes` | Multi-interval spans rejected — enumerate intervals instead. |+| `capacityGb` is a positive multiple of 4 | Other values rejected. The grain is 1 GB-hour (= 4 GB × 15 min). |+| `startsAt >= now + 30 minutes` | Lead-time violation rejected. |++### Capacity shortfall (409)-### Rejected write+When the request is well-formed but doesn't fit available capacity,+the server returns `409 capacity_not_available` with a list of every+problematic interval, so the client can retry with adjusted numbers in+a single round-trip:```json{@@ -76,16 +77,12 @@ Response (success):}```-The response lists every problematic interval, so the client can retry-with adjusted numbers in a single round-trip.+`reason` is one of:| `reason` | Meaning || --- | --- |-| `insufficient_capacity` | Request exceeds current `reservableGb` (platform-side). |-| `reservation_limit_exceeded` | Would exceed your org's `max_memory_gb` for the interval. |-| `too_soon` | `startsAt` is before `earliestReservableStart`. |-| `misaligned` | `startsAt`/`endsAt` not on the 15-minute grid. |-| `capacity_grain` | `capacityGb` is not a positive multiple of 4. |+| `insufficient_capacity` | Request exceeds current `reservableGb` for the interval (either the platform-side limit or your org's `max_memory_gb`). |+| `concurrent_write` | Another reservation for the same interval committed first; retry with the updated `reservableGb`. |## Idempotency@@ -125,6 +122,8 @@ Response:```json{+ "from": "2026-04-01T00:00:00Z",+ "to": "2026-05-01T00:00:00Z","reservations": [{"reservationId": "9f67b8f7-7b91-4d2d-b1cb-19d0d0a14562",@@ -139,12 +138,12 @@ Response:}```-| Query param | Meaning |-| --- | --- |-| `from` | Return reservations whose `createdAt >= from`. |-| `to` | Return reservations whose `createdAt < to`. |-| `cursor` | Pagination cursor from a previous response. |-| `limit` | Max reservations per page. |+| Query param | Required | Meaning |+| --- | --- | --- |+| `from` | yes | Return reservations whose `createdAt >= from`. |+| `to` | yes | Return reservations whose `createdAt < to`. |+| `cursor` | no | Pagination cursor from a previous response's `nextCursor`. |+| `limit` | no | Max reservations per page. Server applies a ceiling. |For end-of-month reconciliation, list reservations and group totals byinterval. The calendar gives you the current per-interval state; the listdiff --git a/docs/reserved-capacity/usage-and-overage.mdx b/docs/reserved-capacity/usage-and-overage.mdxindex c55320e9..60708919 100644--- a/docs/reserved-capacity/usage-and-overage.mdx+++ b/docs/reserved-capacity/usage-and-overage.mdx@@ -3,11 +3,6 @@ title: "Usage and Overage"description: "How reserved capacity is consumed and how overage is calculated"----<Info>- **Coming soon.** Reserved capacity is not yet available. The contract below- may change before launch.-</Info>-## Every second is its own settlementReserved capacity is billed and settled per second. Not per minute, not per@@ -120,7 +115,7 @@ reserve a higher amount.| You hold a reservation in one interval but run in another | No carryover. Allocation is per interval. || Multiple sandboxes' memory sums above the ceiling | Concurrent memory is summed before the ceiling is applied. No per-sandbox attribution. || A sandbox crashes mid-interval | Memory drops as soon as the scale event closes; subsequent seconds see the lower number. |-| You try to reserve for an interval you're already in | Rejected — reservations require lead time (`earliestReservableStart`). |+| You try to reserve for an interval you're already in | Rejected — reservations require a 30-minute minimum lead time. |## Why per-seconddiff --git a/docs/sandboxes/elasticity.mdx b/docs/sandboxes/elasticity.mdxindex 0dce154b..5a1333c5 100644--- a/docs/sandboxes/elasticity.mdx+++ b/docs/sandboxes/elasticity.mdx@@ -1,19 +1,156 @@---title: "Elasticity"-description: "Dynamically scale sandbox memory and CPU from inside the VM"+description: "Dynamically scale sandbox memory and CPU — automatically, manually, or via the in-VM API"----Sandboxes expose an internal metadata API at `http://169.254.169.254` that lets code **inside** the VM scale memory up or down on the fly. CPU scales proportionally to memory.+A sandbox's memory and CPU can be resized at runtime. The platform's recommended path is **Autoscaling** — opt the sandbox in once and we resize it for you based on observed memory pressure. Lower-level controls are also available if you want to drive sizing yourself or freeze it.-This is useful for workloads with variable resource needs — scale up before a heavy compilation or ML inference, then scale back down to save resources.+CPU scales proportionally to memory in all modes (1 vCPU per ~4 GB up to 16 GB / 4 vCPU). The permissible memory tiers are:++| Memory | vCPU |+| --- | --- |+| 1 GB | 1 (best-effort) |+| 4 GB | 1 |+| 8 GB | 2 |+| 16 GB | 4 |++If you want a sandbox to **stay at a fixed size**, see [Locking Resources](#locking-resources).++## Autoscaling++Opt a sandbox into the per-sandbox autoscaler and the platform resizes it for you based on observed memory pressure. Autoscale is **opt-in per sandbox** and **disabled by default**.++This is the recommended way to size a sandbox: turn it on once with bounds you're comfortable with, then leave it. Manual `scale` and the in-VM API are escape hatches for cases where the autoscaler isn't a good fit (e.g. you want a hard guarantee for a benchmark, or you're scripting your own logic).++### Enable++<CodeGroup>+```typescript TypeScript+await sandbox.setAutoscale({+ enabled: true,+ minMemoryMB: 1024,+ maxMemoryMB: 16384,+});+```++```python Python+await sandbox.set_autoscale(+ enabled=True,+ min_memory_mb=1024,+ max_memory_mb=16384,+)+```++```bash CLI+oc sandbox autoscale sb-abc123 --on --min 1024 --max 16384+```++```bash HTTP+curl -sf -X PUT "$API/api/sandboxes/$SANDBOX_ID/autoscale" \+ -H "X-API-Key: $API_KEY" \+ -H "Content-Type: application/json" \+ -d '{"enabled": true, "minMemoryMB": 1024, "maxMemoryMB": 16384}'+```+</CodeGroup>++`minMemoryMB` and `maxMemoryMB` must be values from the tier table above. The autoscaler keeps the sandbox between these bounds, in tier steps.++### Behavior++- **Scale up**: when the sandbox's 1-minute average memory utilization exceeds 75 %, jump to the next tier. 60-second cooldown between up-events.+- **Scale down**: when **all** of the 1-min, 5-min, and 15-min utilization averages stay below 25 %, drop one tier. 5-minute cooldown between down-events. Down requires at least 15 minutes of low-utilization data, so a brief idle pause won't shrink you.+- **Manual override**: any explicit `scale` call disables autoscale on that sandbox. Re-enable explicitly via `setAutoscale({ enabled: true, ... })` (or the equivalent in any SDK) if you want it back.++### Disable++<CodeGroup>+```typescript TypeScript+await sandbox.setAutoscale({ enabled: false });+```++```python Python+await sandbox.set_autoscale(enabled=False)+```++```bash CLI+oc sandbox autoscale sb-abc123 --off+```++```bash HTTP+curl -sf -X PUT "$API/api/sandboxes/$SANDBOX_ID/autoscale" \+ -H "X-API-Key: $API_KEY" \+ -d '{"enabled": false}'+```+</CodeGroup>++### Inspect++<CodeGroup>+```typescript TypeScript+const cfg = await sandbox.getAutoscale();+// { sandboxID: "sb-...", enabled: true, minMemoryMB: 1024, maxMemoryMB: 16384 }+```++```python Python+cfg = await sandbox.get_autoscale()+# {"sandboxID": "sb-...", "enabled": True, "minMemoryMB": 1024, "maxMemoryMB": 16384}+```++```bash CLI+oc sandbox autoscale sb-abc123+# Autoscale enabled for sb-abc123 (1024–16384 MB)+```++```bash HTTP+curl -sf "$API/api/sandboxes/$SANDBOX_ID/autoscale" -H "X-API-Key: $API_KEY"+# {"sandboxID":"sb-...","enabled":true,"minMemoryMB":1024,"maxMemoryMB":16384}+```+</CodeGroup>++## Manual Scaling (Control Plane)++When you want to resize once — predictable size for a benchmark, a one-off scale-up before a known-heavy task, an operator response to an alert — call `scale` from your application or operator tooling:++<CodeGroup>+```typescript TypeScript+await sandbox.scale({ memoryMB: 4096 });+```++```python Python+await sandbox.scale(memory_mb=4096)+```++```bash CLI+oc sandbox scale sb-abc123 4096+```++```bash HTTP+curl -sf -X POST "$API/api/sandboxes/$SANDBOX_ID/scale" \+ -H "X-API-Key: $API_KEY" \+ -H "Content-Type: application/json" \+ -d '{"memoryMB": 4096}'+```+</CodeGroup>++A manual scale **disables autoscale** on the sandbox — explicit user intent overrides the loop. Re-enable it later if you want size to track load again.++The endpoint can return:++- **403 `scaling_locked`** — the sandbox is locked. See [Locking Resources](#locking-resources).+- **409 `oom_floor`** — the requested size would force a guest OOM-kill because the current working set exceeds it. Free memory inside the guest, then retry.+- **402 Payment Required** — the requested size exceeds your plan cap.++## In-VM Scaling++Sandboxes expose an internal metadata API at `http://169.254.169.254` that lets code **inside** the VM scale itself. Useful for workload-aware scripts where the workload knows its own demand better than the platform autoscaler can infer (e.g. "scale up before this build, back down after").<Note>- The elasticity endpoint is only accessible from inside the sandbox. It is not exposed through the control plane API or SDKs.+ This endpoint is only reachable from inside the sandbox. It is not exposed through the control plane API or SDKs.</Note>-## Scale Memory+### Scale Memory-Send a `POST` to `/v1/scale` with the desired memory in MB:+Send a `POST` to `/v1/scale` with the desired memory in MB. CPU is adjusted proportionally.```bashcurl -s -X POST http://169.254.169.254/v1/scale \@@ -21,22 +158,13 @@ curl -s -X POST http://169.254.169.254/v1/scale \-d '{"memoryMB": 4096}'```-CPU is adjusted proportionally — you only need to specify memory. The permissible sizes are:--| Memory | vCPU |-| --- | --- |-| 1GB | 1 (best-effort) |-| 4GB | 1 |-| 8GB | 2 |-| 16GB | 4 |--## Check Current Limits+### Check Current Limits```bashcurl -s http://169.254.169.254/v1/limits```-## Example: Rust Compilation+### Example: Rust CompilationRust builds are memory-hungry. You can alias `cargo` to scale up before compilation and scale back down after:@@ -61,9 +189,9 @@ _cargo_scaled() {Add this to your sandbox's `~/.bashrc` or inject it via `sandbox.exec.run` so every `cargo build`, `cargo test`, etc. automatically gets the extra resources.-## Example: Auto-Scaling Script+### Example: Custom Scaling Loop-A simple shell script that monitors memory pressure and scales automatically:+A simple shell script that monitors memory pressure and scales automatically. Useful when you want fine-grained control inside the sandbox itself; for the platform-managed equivalent see [Autoscaling](#autoscaling) above.```bash#!/bin/sh@@ -108,3 +236,72 @@ while true; dosleep 5done```++## Locking Resources++If you want a sandbox to **stay at a fixed size** — predictable billing, a benchmark, a long-running pinned workload — lock it. Locking blocks both manual scaling and autoscaling on the sandbox.++<CodeGroup>+```typescript TypeScript+await sandbox.setScalingLock(true);+```++```python Python+await sandbox.set_scaling_lock(True)+```++```bash CLI+oc sandbox lock sb-abc123+```++```bash HTTP+curl -sf -X PUT "$API/api/sandboxes/$SANDBOX_ID/scaling-lock" \+ -H "X-API-Key: $API_KEY" \+ -H "Content-Type: application/json" \+ -d '{"locked": true}'+```+</CodeGroup>++While locked:++- `scale` returns **403** `scaling_locked`+- `setAutoscale({ enabled: true })` returns **403** `scaling_locked`+- The autoscaler skips the sandbox++Locking automatically disables autoscale on the sandbox, so you have a single user-facing toggle. Unlocking does **not** auto-re-enable autoscale; turn it back on explicitly if you want it.++<CodeGroup>+```typescript TypeScript+// Unlock+await sandbox.setScalingLock(false);++// Inspect+const lock = await sandbox.getScalingLock();+// { sandboxID: "sb-...", locked: false }+```++```python Python+# Unlock+await sandbox.set_scaling_lock(False)++# Inspect+lock = await sandbox.get_scaling_lock()+# {"sandboxID": "sb-...", "locked": False}+```++```bash CLI+oc sandbox unlock sb-abc123+oc sandbox lock-status sb-abc123+```++```bash HTTP+# Unlock+curl -sf -X PUT "$API/api/sandboxes/$SANDBOX_ID/scaling-lock" \+ -H "X-API-Key: $API_KEY" \+ -d '{"locked": false}'++# Inspect+curl -sf "$API/api/sandboxes/$SANDBOX_ID/scaling-lock" -H "X-API-Key: $API_KEY"+# {"sandboxID":"sb-...","locked":false}+```+</CodeGroup>diff --git a/docs/sandboxes/templates.mdx b/docs/sandboxes/templates.mdxindex 65afc60c..378497e4 100644--- a/docs/sandboxes/templates.mdx+++ b/docs/sandboxes/templates.mdx@@ -3,6 +3,8 @@ title: "Templates"description: "Define sandbox environments programmatically with the Image builder and Snapshots"---+<Warning>Templates are an alpha, experimental feature. APIs, behavior, and manifest formats may change without notice.</Warning>+Templates provide a code-first approach to defining sandbox environments. Instead of configuring images manually, you define them programmatically using the SDK.The system supports two workflows:diff --git a/go.mod b/go.modindex 6ae176a7..1a75b5a1 100644--- a/go.mod+++ b/go.mod@@ -61,6 +61,7 @@ require (github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869 // indirectgithub.com/cespare/xxhash/v2 v2.3.0 // indirectgithub.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect+ github.com/fsnotify/fsnotify v1.10.1 // indirectgithub.com/golang-jwt/jwt v3.2.2+incompatible // indirectgithub.com/google/go-querystring v1.0.0 // indirectgithub.com/inconshreveable/mousetrap v1.1.0 // indirectdiff --git a/go.sum b/go.sumindex 993a3270..98b238bd 100644--- a/go.sum+++ b/go.sum@@ -90,6 +90,8 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97cgithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=+github.com/fsnotify/fsnotify v1.10.1 h1:b0/UzAf9yR5rhf3RPm9gf3ehBPpf0oZKIjtpKrx59Ho=+github.com/fsnotify/fsnotify v1.10.1/go.mod h1:TLheqan6HD6GBK6PrDWyDPBaEV8LspOxvPSjC+bVfgo=github.com/getsentry/sentry-go v0.46.0 h1:mbdDaarbUdOt9X+dx6kDdntkShLEX3/+KyOsVDTPDj0=github.com/getsentry/sentry-go v0.46.0/go.mod h1:evVbw2qotNUdYG8KxXbAdjOQWWvWIwKxpjdZZIvcIPw=github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA=diff --git a/internal/agent/exec.go b/internal/agent/exec.goindex 0403c5dc..12cba9eb 100644--- a/internal/agent/exec.go+++ b/internal/agent/exec.go@@ -3,13 +3,17 @@ package agentimport ("bytes""context"+ "errors""fmt"+ "io""os""os/exec""strings""syscall""time"+ "github.com/google/uuid"+ "github.com/opensandbox/opensandbox/internal/logship"pb "github.com/opensandbox/opensandbox/proto/agent")@@ -101,14 +105,26 @@ func (s *Server) Exec(ctx context.Context, req *pb.ExecRequest) (*pb.ExecRespons}var stdout, stderr bytes.Buffer- cmd.Stdout = &stdout- cmd.Stderr = &stderr+ stdoutTee, stderrTee := s.newExecLineWriters(req.Command, req.Args)+ if stdoutTee != nil {+ cmd.Stdout = io.MultiWriter(&stdout, stdoutTee)+ cmd.Stderr = io.MultiWriter(&stderr, stderrTee)+ } else {+ cmd.Stdout = &stdout+ cmd.Stderr = &stderr+ }// Start + move to sandbox cgroup + wait (instead of Run)if err := cmd.Start(); err != nil {+ closeExecLineWriters(stdoutTee, stderrTee, -1)return nil, fmt.Errorf("exec start: %w", err)}- moveToCgroup(cmd.Process.Pid)+ pid := cmd.Process.Pid+ // Register with reaper BEFORE the child can exit. If the SIGCHLD reaper+ // races us and reaps the child first, cmd.Wait() returns ECHILD; we+ // recover the status from this channel. See reap_registry.go.+ exitCh := RegisterReap(pid)+ moveToCgroup(pid)// Wait with cgroup kill on timeout — if the process doesn't exit when the// context deadline fires, kill the entire sandbox cgroup to clean up fork@@ -127,6 +143,8 @@ func (s *Server) Exec(ctx context.Context, req *pb.ExecRequest) (*pb.ExecRespons}killCgroup()<-waitDone // wait for cmd.Wait to return after kills+ UnregisterReap(pid)+ closeExecLineWriters(stdoutTee, stderrTee, -1)return &pb.ExecResponse{ExitCode: -1,Stdout: stdout.String(),@@ -136,13 +154,26 @@ func (s *Server) Exec(ctx context.Context, req *pb.ExecRequest) (*pb.ExecResponsexitCode := 0if err != nil {- if exitErr, ok := err.(*exec.ExitError); ok {- exitCode = exitErr.ExitCode()- } else {+ switch {+ case isExitError(err):+ exitCode = err.(*exec.ExitError).ExitCode()+ UnregisterReap(pid)+ case errors.Is(err, syscall.ECHILD):+ // Reaper got there first; pull WaitStatus from registry channel.+ // The reaper has already populated it (otherwise wait4 would+ // have returned the status to cmd.Wait, not ECHILD).+ ws := <-exitCh+ exitCode = ws.ExitStatus()+ default:+ UnregisterReap(pid)+ closeExecLineWriters(stdoutTee, stderrTee, -1)return nil, fmt.Errorf("exec failed: %w", err)}+ } else {+ UnregisterReap(pid)}+ closeExecLineWriters(stdoutTee, stderrTee, exitCode)return &pb.ExecResponse{ExitCode: int32(exitCode),Stdout: stdout.String(),@@ -150,6 +181,11 @@ func (s *Server) Exec(ctx context.Context, req *pb.ExecRequest) (*pb.ExecRespons}, nil}+func isExitError(err error) bool {+ _, ok := err.(*exec.ExitError)+ return ok+}+// ExecStream runs a command and streams stdout/stderr chunks.func (s *Server) ExecStream(req *pb.ExecRequest, stream pb.SandboxAgent_ExecStreamServer) error {timeout := time.Duration(req.TimeoutSeconds) * time.Second@@ -193,7 +229,16 @@ func (s *Server) ExecStream(req *pb.ExecRequest, stream pb.SandboxAgent_ExecStrereturn fmt.Errorf("stderr pipe: %w", err)}+ stdoutTee, stderrTee := s.newExecLineWriters(req.Command, req.Args)+ var stdoutR io.Reader = stdoutPipe+ var stderrR io.Reader = stderrPipe+ if stdoutTee != nil {+ stdoutR = io.TeeReader(stdoutPipe, stdoutTee)+ stderrR = io.TeeReader(stderrPipe, stderrTee)+ }+if err := cmd.Start(); err != nil {+ closeExecLineWriters(stdoutTee, stderrTee, -1)return fmt.Errorf("start: %w", err)}moveToCgroup(cmd.Process.Pid)@@ -204,7 +249,7 @@ func (s *Server) ExecStream(req *pb.ExecRequest, stream pb.SandboxAgent_ExecStrego func() {buf := make([]byte, 4096)for {- n, err := stdoutPipe.Read(buf)+ n, err := stdoutR.Read(buf)if n > 0 {if sendErr := stream.Send(&pb.ExecOutputChunk{Stream: pb.ExecOutputChunk_STDOUT,@@ -224,7 +269,7 @@ func (s *Server) ExecStream(req *pb.ExecRequest, stream pb.SandboxAgent_ExecStrego func() {buf := make([]byte, 4096)for {- n, err := stderrPipe.Read(buf)+ n, err := stderrR.Read(buf)if n > 0 {if sendErr := stream.Send(&pb.ExecOutputChunk{Stream: pb.ExecOutputChunk_STDERR,@@ -246,11 +291,46 @@ func (s *Server) ExecStream(req *pb.ExecRequest, stream pb.SandboxAgent_ExecStre<-errCh// Wait for command to finish- _ = cmd.Wait()+ waitErr := cmd.Wait()+ exitCode := 0+ if waitErr != nil {+ if isExitError(waitErr) {+ exitCode = waitErr.(*exec.ExitError).ExitCode()+ } else {+ exitCode = -1+ }+ }+ closeExecLineWriters(stdoutTee, stderrTee, exitCode)return nil}+// newExecLineWriters returns matching stdout/stderr LineWriters that+// ship into the agent's logship Shipper, tagged with a fresh exec_id+// and the command + argv. Returns (nil, nil) if logship isn't wired+// into this agent (callers must tolerate nil and skip teeing).+func (s *Server) newExecLineWriters(command string, args []string) (*logship.LineWriter, *logship.LineWriter) {+ if s.Shipper == nil {+ return nil, nil+ }+ execID := uuid.NewString()+ stdoutW := logship.NewLineWriter(s.Shipper, logship.SourceExecStdout, execID, command, args)+ stderrW := logship.NewLineWriter(s.Shipper, logship.SourceExecStderr, execID, command, args)+ return stdoutW, stderrW+}++// closeExecLineWriters flushes any partial trailing line and emits one+// synthetic EOF event per stream carrying the exit code. Safe to call+// with nil writers (when logship isn't wired).+func closeExecLineWriters(stdout, stderr *logship.LineWriter, exitCode int) {+ if stdout != nil {+ stdout.Close(exitCode)+ }+ if stderr != nil {+ stderr.Close(exitCode)+ }+}+// mapToEnv converts a map to KEY=VALUE slice.func mapToEnv(m map[string]string) []string {env := make([]string, 0, len(m))diff --git a/internal/agent/exec_session.go b/internal/agent/exec_session.goindex 320891d3..f08f4baa 100644--- a/internal/agent/exec_session.go+++ b/internal/agent/exec_session.go@@ -11,6 +11,7 @@ import ("time""github.com/google/uuid"+ "github.com/opensandbox/opensandbox/internal/logship""github.com/opensandbox/opensandbox/internal/sandbox"pb "github.com/opensandbox/opensandbox/proto/agent")@@ -28,6 +29,13 @@ type execSession struct {exitCode *int32exited chan struct{}+ // Logship tees: shadow each pipe's bytes into a per-session+ // LineWriter that ships line-by-line to Axiom alongside the+ // existing scrollback. Both nil if logship isn't wired (Shipper+ // not set on Server) — LineWriter is nil-safe.+ stdoutTee *logship.LineWriter+ stderrTee *logship.LineWriter+mu sync.MutexattachedClients intlastDisconnect time.Time@@ -82,6 +90,8 @@ func (s *Server) ExecSessionCreate(ctx context.Context, req *pb.ExecSessionCreatmaxScrollback := int(req.ScrollbackMaxBytes)scrollback := sandbox.NewScrollbackBuffer(maxScrollback)+ stdoutTee, stderrTee := s.newExecLineWriters(req.Command, req.Args)+sess := &execSession{id: sessionID,cmd: cmd,@@ -91,6 +101,8 @@ func (s *Server) ExecSessionCreate(ctx context.Context, req *pb.ExecSessionCreatstarted: time.Now(),scrollback: scrollback,stdinPipe: stdinPipe,+ stdoutTee: stdoutTee,+ stderrTee: stderrTee,exited: make(chan struct{}),}@@ -121,6 +133,9 @@ func (s *Server) ExecSessionCreate(ctx context.Context, req *pb.ExecSessionCreatn, err := stdoutPipe.Read(buf)if n > 0 {scrollback.Write(1, buf[:n])+ if stdoutTee != nil {+ stdoutTee.Write(buf[:n])+ }}if err != nil {return@@ -135,6 +150,9 @@ func (s *Server) ExecSessionCreate(ctx context.Context, req *pb.ExecSessionCreatn, err := stderrPipe.Read(buf)if n > 0 {scrollback.Write(2, buf[:n])+ if stderrTee != nil {+ stderrTee.Write(buf[:n])+ }}if err != nil {return@@ -151,6 +169,10 @@ func (s *Server) ExecSessionCreate(ctx context.Context, req *pb.ExecSessionCreatsess.mu.Lock()sess.exitCode = &codesess.mu.Unlock()+ // Flush any trailing partial line and emit the synthesised+ // EOF event with exit_code so the UI can render the row.+ // Same shape as one-shot Exec / streaming ExecStream.+ closeExecLineWriters(stdoutTee, stderrTee, int(code))close(sess.exited)// Schedule cleanup after 5 minutesdiff --git a/internal/agent/logship.go b/internal/agent/logship.gonew file mode 100644index 00000000..681d907c--- /dev/null+++ b/internal/agent/logship.go@@ -0,0 +1,61 @@+package agent++import (+ "context"+ "log"++ "github.com/opensandbox/opensandbox/internal/logship"+ pb "github.com/opensandbox/opensandbox/proto/agent"+)++// LogshipConfig captures the parameters needed to ship sandbox session+// logs to the configured backend (Axiom). The forwarder reads this at+// flush time so it can stamp each event with the right sandbox/org IDs.+//+// IngestToken empty = log shipping disabled. The worker decides whether+// to call ConfigureLogship at all based on its own AXIOM_INGEST_TOKEN+// env; passing an empty token here is a defensive no-op path.+type LogshipConfig struct {+ IngestToken string+ Dataset string+ SandboxID string+ OrgID string+}++// ConfigureLogship is called by the worker once per sandbox boot to+// hand the agent its log-shipping configuration. Phase 0 just stores+// the config; Phase 1 wires it into the forwarder's Activate path.+func (s *Server) ConfigureLogship(ctx context.Context, req *pb.ConfigureLogshipRequest) (*pb.ConfigureLogshipResponse, error) {+ cfg := LogshipConfig{+ IngestToken: req.IngestToken,+ Dataset: req.Dataset,+ SandboxID: req.SandboxId,+ OrgID: req.OrgId,+ }+ s.logshipMu.Lock()+ s.logshipCfg = cfg+ s.logshipMu.Unlock()++ if cfg.IngestToken == "" {+ log.Printf("agent: ConfigureLogship received empty ingest_token (kill-switch); shipping disabled")+ } else {+ log.Printf("agent: ConfigureLogship received (sandbox_id=%s, dataset=%s)", cfg.SandboxID, cfg.Dataset)+ if s.Shipper != nil {+ s.Shipper.Activate(logship.Config{+ IngestToken: cfg.IngestToken,+ Dataset: cfg.Dataset,+ SandboxID: cfg.SandboxID,+ OrgID: cfg.OrgID,+ })+ }+ }+ return &pb.ConfigureLogshipResponse{}, nil+}++// LogshipConfig returns the current log-shipping configuration.+// Returns the zero value if ConfigureLogship has not yet been called.+func (s *Server) GetLogshipConfig() LogshipConfig {+ s.logshipMu.RLock()+ defer s.logshipMu.RUnlock()+ return s.logshipCfg+}diff --git a/internal/agent/reap_registry.go b/internal/agent/reap_registry.gonew file mode 100644index 00000000..7fc562fa--- /dev/null+++ b/internal/agent/reap_registry.go@@ -0,0 +1,58 @@+package agent++import (+ "sync"+ "syscall"+)++// ReapRegistry coordinates the agent's SIGCHLD reaper with explicit-wait+// callers (Exec, PrepareHibernate, PTY). Without coordination the reaper's+// Wait4(-1, ...) races with cmd.Wait() — whichever lands first gets the+// child's exit status, and the other returns ECHILD. The loser's caller+// reports `exec failed: waitid: no child processes`, surfacing to users+// as ~30% fork failures with empty stdout when bench-style workloads hit+// the agent immediately after a fresh fork.+//+// Coordination protocol:+// 1. Caller (Exec handler) calls RegisterReap(pid) BEFORE the child can+// exit (immediately after cmd.Start()).+// 2. Caller calls cmd.Wait() in the usual way.+// 3a. If cmd.Wait() succeeds, child status is in cmd.ProcessState. Caller+// should call UnregisterReap(pid) to drop the dangling registration.+// 3b. If cmd.Wait() returns ECHILD, the reaper got there first; pull+// the WaitStatus from the channel and synthesize the exit code.+//+// The reaper (cmd/agent/reaper_linux.go) calls TryDeliverReap on every+// child it consumes. If the pid is registered, it forwards the status via+// channel; otherwise it logs the orphan reap as before.+var reapRegistry sync.Map // pid (int) → chan syscall.WaitStatus++// RegisterReap claims a pid for explicit-wait. Returns a channel that+// receives the wait status when the reaper picks up the child. Channel is+// closed after the status is delivered.+func RegisterReap(pid int) <-chan syscall.WaitStatus {+ ch := make(chan syscall.WaitStatus, 1)+ reapRegistry.Store(pid, ch)+ return ch+}++// UnregisterReap removes a pid registration without consuming a status.+// Use when cmd.Wait() succeeded and you no longer need the channel.+func UnregisterReap(pid int) {+ reapRegistry.Delete(pid)+}++// TryDeliverReap is called by the SIGCHLD reaper for each child it reaps.+// If the pid is registered, the status is delivered via channel and true+// is returned (so the reaper can skip its orphan-log path). Otherwise+// returns false — caller should log this as an orphan reap.+func TryDeliverReap(pid int, ws syscall.WaitStatus) bool {+ v, ok := reapRegistry.LoadAndDelete(pid)+ if !ok {+ return false+ }+ ch := v.(chan syscall.WaitStatus)+ ch <- ws+ close(ch)+ return true+}diff --git a/internal/agent/server.go b/internal/agent/server.goindex 2f32fb82..ff6ae641 100644--- a/internal/agent/server.go+++ b/internal/agent/server.go@@ -14,6 +14,7 @@ import ("syscall""time"+ "github.com/opensandbox/opensandbox/internal/logship"pb "github.com/opensandbox/opensandbox/proto/agent""google.golang.org/grpc")@@ -56,6 +57,18 @@ type Server struct {ptySessions map[string]*ptySessionnextPTYPort uint32+ // Sandbox session log shipping configuration. Set once via the+ // ConfigureLogship RPC, called by the worker right after VM boot.+ // If never set, the forwarder stays dormant.+ logshipMu sync.RWMutex+ logshipCfg LogshipConfig++ // Shipper is the in-VM forwarder that ships /var/log + exec output+ // to Axiom. Set by cmd/agent/main.go before Serve. Nil = log+ // shipping not wired (the forwarder package isn't built into this+ // agent binary). The exec handlers tolerate nil and skip teeing.+ Shipper *logship.Shipper+// gRPC server reference for hibernate GracefulStopmu sync.MutexgrpcServer *grpc.Serverdiff --git a/internal/agent/stats.go b/internal/agent/stats.goindex 3281492c..ba22107c 100644--- a/internal/agent/stats.go+++ b/internal/agent/stats.go@@ -37,7 +37,14 @@ func (s *Server) Shutdown(ctx context.Context, req *pb.ShutdownRequest) (*pb.Shufunc (s *Server) Stats(ctx context.Context, req *pb.StatsRequest) (*pb.StatsResponse, error) {resp := &pb.StatsResponse{}- // Memory from /proc/meminfo+ // Memory from /proc/meminfo. Note we use MemAvailable, not MemFree —+ // MemAvailable is the kernel's own working-set estimate that subtracts+ // reclaimable page cache + slab. So MemTotal-MemAvailable already+ // excludes file-cache pressure (e.g. a `dd` workload won't make this+ // climb to 100% even though page cache fills RAM). The autoscaler reads+ // this value via mem_pct; treating it as a working-set proxy is correct.+ // It is also an upper bound on resident anon memory, so the worker's+ // scale-down OOM floor uses MemUsage * 1.05 as a safe lower bound.memTotal, memAvail := readMemInfo()resp.MemLimit = memTotalresp.MemUsage = memTotal - memAvail@@ -51,9 +58,34 @@ func (s *Server) Stats(ctx context.Context, req *pb.StatsRequest) (*pb.StatsResp// Network from /proc/net/devresp.NetInput, resp.NetOutput = readNetStats()+ // Disk usage via statvfs(). The worker uses these to refuse hibernate /+ // checkpoint when rootfs is critically full, before the qcow2 ends up+ // captured in an inconsistent state. Errors silently zero the fields —+ // the worker treats 0/0 as "unknown" and falls back to no pressure gate.+ resp.RootfsUsedBytes, resp.RootfsTotalBytes = diskUsage("/")+ resp.WorkspaceUsedBytes, resp.WorkspaceTotalBytes = diskUsage("/home/sandbox")+return resp, nil}+// diskUsage returns (used, total) in bytes for the filesystem containing path.+// On any error, returns (0, 0) — caller treats that as "unknown".+func diskUsage(path string) (used, total uint64) {+ var st syscall.Statfs_t+ if err := syscall.Statfs(path, &st); err != nil {+ return 0, 0+ }+ bsize := uint64(st.Bsize)+ total = st.Blocks * bsize+ avail := st.Bavail * bsize+ if avail > total {+ // Should never happen on ext4, but guard against underflow if it does.+ return 0, total+ }+ used = total - avail+ return used, total+}+// readMemInfo parses /proc/meminfo for MemTotal and MemAvailable.func readMemInfo() (total, available uint64) {f, err := os.Open("/proc/meminfo")diff --git a/internal/api/admin_workers.go b/internal/api/admin_workers.gonew file mode 100644index 00000000..2dd5e206--- /dev/null+++ b/internal/api/admin_workers.go@@ -0,0 +1,51 @@+package api++import (+ "net/http"++ "github.com/labstack/echo/v4"+)++// adminSetWorkerDraining toggles the in-memory `Draining` flag on a worker so+// the placement filter (RedisWorkerRegistry.GetLeastLoadedWorker and+// findScaleMigrationTargets) stops routing new sandboxes to it. Existing+// sandboxes on the worker are unaffected.+//+// POST /admin/workers/:id/drain — mark draining (default)+// POST /admin/workers/:id/drain?drain=false — clear draining+//+// The flag is per-controlplane-instance memory: call this on every active+// control plane to drain consistently across replicas. Heartbeats do not+// overwrite the flag.+func (s *Server) adminSetWorkerDraining(c echo.Context) error {+ if s.workerRegistry == nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{+ "error": "worker registry not configured (combined/worker mode)",+ })+ }++ workerID := c.Param("id")+ if workerID == "" {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "worker id required"})+ }++ drain := c.QueryParam("drain") != "false"++ known := false+ for _, w := range s.workerRegistry.GetAllWorkers() {+ if w.ID == workerID {+ known = true+ break+ }+ }+ if !known {+ return c.JSON(http.StatusNotFound, map[string]string{"error": "worker not registered"})+ }++ s.workerRegistry.SetDraining(workerID, drain)++ return c.JSON(http.StatusOK, map[string]any{+ "workerID": workerID,+ "draining": drain,+ })+}diff --git a/internal/api/capacity.go b/internal/api/capacity.goindex 264612b3..d38bb2d8 100644--- a/internal/api/capacity.go+++ b/internal/api/capacity.go@@ -217,6 +217,92 @@ func (s *Server) listCapacityReservations(c echo.Context) error {return c.JSON(http.StatusOK, resp)}+// getCapacityBillableEvents → GET /api/capacity/billable-events+//+// **INTERNAL — INTENTIONALLY UNDOCUMENTED.**+// This endpoint surfaces the phase-2 outbox (`billable_events`) for the+// caller's org so the allocator can be verified end-to-end without DB+// access. It is deliberately not in the public spec+// (ws-pricing/design/001-reserved-capacity-squares.md), not advertised+// to customers, and may be removed once the unified pipeline is fully+// cut over and the dashboard exposes this data through a proper UI.+//+// Future agents: do **not** add this to the spec or to docs. If the+// debugging need has gone away (phase 3 cut over, dashboard view+// landed), feel free to delete it.+//+// Response shape mirrors the DB row 1:1 — no normalisation — so it's+// useful as a raw inspection tool, not a customer-facing contract.+func (s *Server) getCapacityBillableEvents(c echo.Context) error {+ if s.store == nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "database not configured"})+ }+ orgID, ok := auth.GetOrgID(c)+ if !ok {+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "org context required"})+ }++ from, to, err := parseAlignedRange(c.QueryParam("from"), c.QueryParam("to"), capacityMaxListSpan)+ if err != nil {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()})+ }++ eventType := c.QueryParam("eventType")+ switch eventType {+ case "", db.BillableEventReservedUsage, db.BillableEventOverageUsage, db.BillableEventDiskOverageUsage:+ // ok+ default:+ return c.JSON(http.StatusBadRequest, map[string]string{+ "error": "eventType must be one of reserved_usage, overage_usage, disk_overage_usage (or omitted for all)",+ })+ }++ limit := capacityListDefaultLimit+ if raw := c.QueryParam("limit"); raw != "" {+ var n int+ if _, perr := fmt.Sscanf(raw, "%d", &n); perr != nil || n <= 0 {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "`limit` must be a positive integer"})+ }+ if n > capacityListMaxLimit {+ n = capacityListMaxLimit+ }+ limit = n+ }++ ctx, cancel := context.WithTimeout(c.Request().Context(), capacityHandlerTimeout)+ defer cancel()++ events, err := s.store.ListBillableEventsForOrg(ctx, orgID, from, to, eventType, limit)+ if err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})+ }++ items := make([]map[string]any, 0, len(events))+ for _, e := range events {+ row := map[string]any{+ "id": e.ID.String(),+ "eventType": e.EventType,+ "memoryMb": e.MemoryMB,+ "gbSeconds": e.GBSeconds,+ "bucketStart": e.BucketStart.UTC().Format(time.RFC3339),+ "bucketEnd": e.BucketEnd.UTC().Format(time.RFC3339),+ "deliveryState": e.DeliveryState,+ "createdAt": e.CreatedAt.UTC().Format(time.RFC3339),+ }+ if e.StripeEventID != nil {+ row["stripeEventId"] = *e.StripeEventID+ }+ if e.DeliveredAt != nil {+ row["deliveredAt"] = e.DeliveredAt.UTC().Format(time.RFC3339)+ }+ items = append(items, row)+ }+ return c.JSON(http.StatusOK, map[string]any{+ "events": items,+ "count": len(items),+ })+}+// --- request parsing / validation ---type reservationRequestBody struct {diff --git a/internal/api/dashboard.go b/internal/api/dashboard.goindex 82747ea9..3faa4771 100644--- a/internal/api/dashboard.go+++ b/internal/api/dashboard.go@@ -1016,6 +1016,68 @@ func (s *Server) dashboardKillPTY(c echo.Context) error {return c.NoContent(http.StatusNoContent)}+// dashboardRebootSession soft-restarts a running sandbox owned by the+// authenticated org. Equivalent of POST /api/sandboxes/:id/reboot but+// scoped to the dashboard's org-membership auth.+func (s *Server) dashboardRebootSession(c echo.Context) error {+ sandboxID, session, err := s.dashboardResolveSandbox(c)+ if err != nil {+ return err+ }+ if s.workerRegistry != nil {+ client, err := s.workerRegistry.GetWorkerClient(session.WorkerID)+ if err != nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "worker unreachable: " + err.Error()})+ }+ ctx, cancel := context.WithTimeout(c.Request().Context(), 90*time.Second)+ defer cancel()+ if _, err := client.RebootSandbox(ctx, &pb.RebootSandboxRequest{SandboxId: sandboxID}); err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "reboot failed: " + err.Error()})+ }+ s.emitEvent("reboot", sandboxID, session.WorkerID, "rebooted")+ return c.NoContent(http.StatusNoContent)+ }+ if s.manager == nil {+ return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)+ }+ if err := s.manager.RebootSandbox(c.Request().Context(), sandboxID); err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})+ }+ return c.NoContent(http.StatusNoContent)+}++// dashboardPowerCycleSession hard-restarts a running sandbox owned by the+// authenticated org.+func (s *Server) dashboardPowerCycleSession(c echo.Context) error {+ sandboxID, session, err := s.dashboardResolveSandbox(c)+ if err != nil {+ return err+ }+ if s.workerRegistry != nil {+ client, err := s.workerRegistry.GetWorkerClient(session.WorkerID)+ if err != nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "worker unreachable: " + err.Error()})+ }+ ctx, cancel := context.WithTimeout(c.Request().Context(), 120*time.Second)+ defer cancel()+ if _, err := client.PowerCycleSandbox(ctx, &pb.PowerCycleSandboxRequest{SandboxId: sandboxID}); err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "power-cycle failed: " + err.Error()})+ }+ if s.sandboxAPIProxy != nil {+ s.sandboxAPIProxy.InvalidateRouteCache(sandboxID)+ }+ s.emitEvent("power-cycle", sandboxID, session.WorkerID, "power-cycled")+ return c.NoContent(http.StatusNoContent)+ }+ if s.manager == nil {+ return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)+ }+ if _, err := s.manager.PowerCycleSandbox(c.Request().Context(), sandboxID); err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})+ }+ return c.NoContent(http.StatusNoContent)+}+// dashboardResolveSandbox validates the sandbox belongs to the authenticated org and is running.func (s *Server) dashboardResolveSandbox(c echo.Context) (string, *db.SandboxSession, error) {if s.store == nil {diff --git a/internal/api/dashboard_agent_subscriptions.go b/internal/api/dashboard_agent_subscriptions.gonew file mode 100644index 00000000..8a02865b--- /dev/null+++ b/internal/api/dashboard_agent_subscriptions.go@@ -0,0 +1,519 @@+package api++import (+ "context"+ "fmt"+ "log"+ "net/http"+ "time"++ "github.com/google/uuid"+ "github.com/labstack/echo/v4"++ "github.com/opensandbox/opensandbox/internal/auth"+ "github.com/opensandbox/opensandbox/internal/db"+)++// Per-agent paywalled-feature subscription endpoints. v1 ships with one+// feature ("telegram") but the data model is feature-keyed so adding+// Discord / Slack / etc. later is a matter of a new env var + a new+// frontend tile, no schema change.+//+// Auth: cookie-protected (mounted under /api/dashboard) for end-user+// flows; sessions-api hits the API-key-protected entitlement endpoint+// (see dashboardAgentEntitlements wired in router.go).++const (+ telegramFeature = "telegram"+)++// reconcileAgentFeatureFromStripe checks Stripe for an existing+// subscription matching (agent_id, feature) and persists a local row+// if Stripe has it but we don't. Used to recover from a missing+// webhook (e.g. STRIPE_WEBHOOK_SECRET unset, transient network glitch).+//+// Returns the resulting active subscription, or nil if Stripe also+// has nothing.+func (s *Server) reconcileAgentFeatureFromStripe(ctx context.Context, orgID uuid.UUID, agentID, feature string) (*db.AgentSubscription, error) {+ if s.stripeClient == nil || s.store == nil {+ return nil, nil+ }+ org, err := s.store.GetOrg(ctx, orgID)+ if err != nil || org.StripeCustomerID == nil {+ return nil, err+ }+ stripeSub, err := s.stripeClient.FindAgentFeatureSubscription(*org.StripeCustomerID, agentID, feature)+ if err != nil || stripeSub == nil {+ return nil, err+ }++ // Idempotent: if we already have it, just nudge status.+ row, err := s.store.GetAgentSubscriptionByStripeID(ctx, stripeSub.ID)+ if err != nil {+ return nil, err+ }++ var currentPeriodEnd *time.Time+ if stripeSub.Items != nil && len(stripeSub.Items.Data) > 0 && stripeSub.Items.Data[0].CurrentPeriodEnd > 0 {+ t := time.Unix(stripeSub.Items.Data[0].CurrentPeriodEnd, 0).UTC()+ currentPeriodEnd = &t+ }+ priceID := ""+ if stripeSub.Items != nil && len(stripeSub.Items.Data) > 0 && stripeSub.Items.Data[0].Price != nil {+ priceID = stripeSub.Items.Data[0].Price.ID+ }++ if row != nil {+ // Update status from Stripe (in case we missed the webhook update).+ if err := s.store.UpdateAgentSubscriptionFromStripe(ctx, stripeSub.ID, string(stripeSub.Status), currentPeriodEnd, stripeSub.CancelAtPeriodEnd, nil); err != nil {+ return nil, err+ }+ row.Status = string(stripeSub.Status)+ row.CurrentPeriodEnd = currentPeriodEnd+ row.CancelAtPeriodEnd = stripeSub.CancelAtPeriodEnd+ return row, nil+ }++ saved, err := s.store.CreateAgentSubscription(ctx, db.AgentSubscription{+ OrgID: orgID,+ AgentID: agentID,+ Feature: feature,+ StripeCustomerID: *org.StripeCustomerID,+ StripeSubscriptionID: stripeSub.ID,+ StripePriceID: priceID,+ Status: string(stripeSub.Status),+ CurrentPeriodEnd: currentPeriodEnd,+ CancelAtPeriodEnd: stripeSub.CancelAtPeriodEnd,+ })+ if err != nil {+ return nil, err+ }+ log.Printf("billing: reconciled agent_subscription from Stripe (agent=%s feature=%s sub=%s status=%s)",+ agentID, feature, stripeSub.ID, stripeSub.Status)+ return saved, nil+}++// dashboardSubscribeAgentFeature creates a Stripe subscription for the+// given (agent_id, feature) pair. Two flows:+//+// 1. Customer has a saved default payment method → call+// subscriptions.create directly. Returns {status:"active", agent_id}.+// 2. No card on file → create a Stripe Checkout session+// (mode=subscription) and return its URL. Frontend redirects.+//+// Idempotent: if an active subscription already exists for this+// (agent_id, feature), returns the existing one with status:"already_subscribed".+func (s *Server) dashboardSubscribeAgentFeature(c echo.Context) error {+ if s.stripeClient == nil || s.store == nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "billing not configured"})+ }++ feature := c.Param("feature")+ agentID := c.Param("agentId")+ if agentID == "" {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "agent_id required"})+ }++ priceID, ok := s.priceIDForFeature(feature)+ if !ok {+ return c.JSON(http.StatusBadRequest, map[string]string{+ "error": fmt.Sprintf("unknown feature %q or price not configured", feature),+ })+ }+ if priceID == "" {+ // Feature exists but is ungated on this deployment (dev mode)+ // — surface that explicitly so the caller knows there's nothing+ // to pay for. UI treats this like already-entitled.+ return c.JSON(http.StatusOK, map[string]any{+ "status": "ungated",+ "feature": feature,+ "agent_id": agentID,+ })+ }++ orgID, ok := auth.GetOrgID(c)+ if !ok {+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "auth required"})+ }++ ctx := c.Request().Context()++ // Already subscribed? Return existing.+ existing, err := s.store.GetActiveAgentSubscription(ctx, agentID, feature)+ if err != nil {+ log.Printf("billing: get active sub failed: %v", err)+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "internal"})+ }+ if existing == nil {+ // Reconcile path: maybe Stripe has the sub but our DB lost the+ // webhook (or signature wasn't configured). Re-import before+ // telling the user to pay again.+ if reconciled, rerr := s.reconcileAgentFeatureFromStripe(ctx, orgID, agentID, feature); rerr == nil && reconciled != nil {+ existing = reconciled+ }+ }+ if existing != nil && existing.OrgID == orgID && db.AgentSubscriptionIsActive(existing.Status) {+ return c.JSON(http.StatusOK, map[string]any{+ "status": "already_subscribed",+ "feature": feature,+ "agent_id": agentID,+ "subscription_id": existing.StripeSubscriptionID,+ })+ }++ // Need a Stripe customer ID for the org. Existing billing flow+ // creates one when the org first enters checkout for the pro plan.+ // For per-agent subs we may need to create one here lazily so the+ // user can pay for telegram even on a free plan.+ org, err := s.store.GetOrg(ctx, orgID)+ if err != nil {+ log.Printf("billing: get org failed: %v", err)+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "org not found"})+ }+ customerID := ""+ if org.StripeCustomerID != nil {+ customerID = *org.StripeCustomerID+ }+ if customerID == "" {+ newCustomer, err := s.stripeClient.CreateCustomer(org.Name, "")+ if err != nil {+ log.Printf("billing: create customer failed: %v", err)+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "stripe customer create failed"})+ }+ customerID = newCustomer+ if err := s.store.SetStripeCustomerID(ctx, orgID, customerID); err != nil {+ log.Printf("billing: persist customer id failed: %v", err)+ // Don't fail the request — we have the ID locally and will+ // use it; persistence retry happens on next request.+ }+ }++ metadata := map[string]string{+ "type": "agent_feature_subscription",+ "org_id": orgID.String(),+ "agent_id": agentID,+ "feature": feature,+ }++ pmID, err := s.stripeClient.GetCustomerDefaultPaymentMethod(customerID)+ if err != nil {+ log.Printf("billing: fetch default pm failed: %v", err)+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "stripe lookup failed"})+ }++ if pmID == "" {+ // No card on file — bounce through Checkout. The webhook+ // handler will record the subscription on completion.+ successURL := s.stripeClient.SuccessURL()+ cancelURL := s.stripeClient.CancelURL()+ url, err := s.stripeClient.CreateAgentFeatureCheckoutSession(customerID, priceID, successURL, cancelURL, metadata)+ if err != nil {+ log.Printf("billing: create checkout failed: %v", err)+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "checkout create failed"})+ }+ return c.JSON(http.StatusOK, map[string]any{+ "status": "checkout_required",+ "checkout_url": url,+ "feature": feature,+ "agent_id": agentID,+ })+ }++ // Saved card path — direct subscription, no redirect.+ sub, err := s.stripeClient.CreateAgentFeatureSubscription(customerID, priceID, metadata)+ if err != nil {+ log.Printf("billing: direct subscribe failed: %v", err)+ return c.JSON(http.StatusInternalServerError, map[string]string{+ "error": "subscribe failed",+ "detail": err.Error(),+ })+ }++ // stripe-go v82 moved CurrentPeriodEnd off the Subscription onto each+ // SubscriptionItem; for our single-item subs we just read the first.+ var currentPeriodEnd time.Time+ if sub.Items != nil && len(sub.Items.Data) > 0 && sub.Items.Data[0].CurrentPeriodEnd > 0 {+ currentPeriodEnd = time.Unix(sub.Items.Data[0].CurrentPeriodEnd, 0).UTC()+ }+ row := db.AgentSubscription{+ OrgID: orgID,+ AgentID: agentID,+ Feature: feature,+ StripeCustomerID: customerID,+ StripeSubscriptionID: sub.ID,+ StripePriceID: priceID,+ Status: string(sub.Status),+ CancelAtPeriodEnd: sub.CancelAtPeriodEnd,+ }+ if !currentPeriodEnd.IsZero() {+ row.CurrentPeriodEnd = ¤tPeriodEnd+ }+ saved, err := s.store.CreateAgentSubscription(ctx, row)+ if err != nil {+ // Stripe sub exists but DB write failed — log loudly. The+ // webhook handler will reconcile on next event.+ log.Printf("billing: persist agent_subscription failed (stripe sub=%s, agent=%s): %v", sub.ID, agentID, err)+ return c.JSON(http.StatusInternalServerError, map[string]string{+ "error": "subscription created in Stripe but local persist failed; will reconcile on next webhook",+ })+ }++ return c.JSON(http.StatusOK, map[string]any{+ "status": "active",+ "feature": feature,+ "agent_id": agentID,+ "subscription_id": saved.StripeSubscriptionID,+ "price_id": saved.StripePriceID,+ })+}++// dashboardCancelAgentFeature schedules the per-agent subscription to+// stop renewing at period end. Customer keeps the feature until the+// current billing period ends (no proration, no immediate cutoff).+// The webhook handler flips the local row to canceled when Stripe+// confirms the deletion.+func (s *Server) dashboardCancelAgentFeature(c echo.Context) error {+ if s.stripeClient == nil || s.store == nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "billing not configured"})+ }++ feature := c.Param("feature")+ agentID := c.Param("agentId")+ orgID, ok := auth.GetOrgID(c)+ if !ok {+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "auth required"})+ }++ ctx := c.Request().Context()+ existing, err := s.store.GetActiveAgentSubscription(ctx, agentID, feature)+ if err != nil {+ log.Printf("billing: get active sub failed: %v", err)+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "internal"})+ }+ if existing == nil {+ return c.JSON(http.StatusNotFound, map[string]string{"error": "no active subscription"})+ }+ if existing.OrgID != orgID {+ return c.JSON(http.StatusNotFound, map[string]string{"error": "no active subscription"})+ }++ if _, err := s.stripeClient.CancelAgentFeatureSubscription(existing.StripeSubscriptionID, false); err != nil {+ log.Printf("billing: cancel subscription failed: %v", err)+ return c.JSON(http.StatusBadGateway, map[string]string{+ "error": "stripe cancel failed",+ "detail": err.Error(),+ })+ }+ // Optimistic local update — webhook will reconcile.+ if err := s.store.UpdateAgentSubscriptionFromStripe(ctx, existing.StripeSubscriptionID, existing.Status, existing.CurrentPeriodEnd, true, nil); err != nil {+ log.Printf("billing: persist cancel-at-period-end failed: %v", err)+ }+ return c.JSON(http.StatusOK, map[string]any{+ "status": "scheduled_cancel",+ "feature": feature,+ "agent_id": agentID,+ "cancel_at_period_end": true,+ "current_period_end": existing.CurrentPeriodEnd,+ })+}++// dashboardListAgentEntitlements returns which paywalled features the+// caller's org has paid for on a given agent. Used by the agent detail+// page to decide whether to show the paywall or the connect flow.+func (s *Server) dashboardListAgentEntitlements(c echo.Context) error {+ if s.store == nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "not configured"})+ }+ agentID := c.Param("agentId")+ orgID, ok := auth.GetOrgID(c)+ if !ok {+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "auth required"})+ }++ type entRow struct {+ Feature string `json:"feature"`+ Entitled bool `json:"entitled"`+ Reason string `json:"reason,omitempty"`+ PriceMonthlyCents int64 `json:"price_monthly_cents,omitempty"`+ Status string `json:"status,omitempty"`+ CurrentPeriodEnd *time.Time `json:"current_period_end,omitempty"`+ CancelAtPeriodEnd bool `json:"cancel_at_period_end,omitempty"`+ StripeSubscriptionID string `json:"stripe_subscription_id,omitempty"`+ }++ out := []entRow{}+ for _, feature := range []string{telegramFeature} {+ priceID, _ := s.priceIDForFeature(feature)+ row := entRow{Feature: feature}+ if priceID == "" {+ // Ungated on this deployment.+ row.Entitled = true+ row.Reason = "ungated"+ out = append(out, row)+ continue+ }+ sub, err := s.store.GetActiveAgentSubscription(c.Request().Context(), agentID, feature)+ if err != nil {+ log.Printf("billing: list entitlements lookup failed: %v", err)+ }+ if sub == nil {+ // Reconcile path — see subscribe handler.+ if reconciled, rerr := s.reconcileAgentFeatureFromStripe(c.Request().Context(), orgID, agentID, feature); rerr == nil && reconciled != nil {+ sub = reconciled+ }+ }+ if sub != nil && sub.OrgID == orgID && db.AgentSubscriptionIsActive(sub.Status) {+ row.Entitled = true+ row.Status = sub.Status+ row.CurrentPeriodEnd = sub.CurrentPeriodEnd+ row.CancelAtPeriodEnd = sub.CancelAtPeriodEnd+ row.StripeSubscriptionID = sub.StripeSubscriptionID+ } else {+ row.Entitled = false+ row.Reason = "subscription_required"+ }+ row.PriceMonthlyCents = priceMonthlyCentsForFeature(feature)+ out = append(out, row)+ }+ return c.JSON(http.StatusOK, map[string]any{"agent_id": agentID, "entitlements": out})+}++// dashboardListOrgAgentSubscriptions returns every per-agent subscription+// the org owns (active and historical). Powers the Billing → Agents tab.+//+// We deliberately do not filter by status here — past subscriptions+// (canceled, etc.) are useful billing context. The UI groups by agent+// and feature and shows the most-recent per pair.+func (s *Server) dashboardListOrgAgentSubscriptions(c echo.Context) error {+ if s.store == nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "not configured"})+ }+ orgID, ok := auth.GetOrgID(c)+ if !ok {+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "auth required"})+ }+ subs, err := s.store.ListAgentSubscriptionsByOrg(c.Request().Context(), orgID)+ if err != nil {+ log.Printf("billing: list org agent subscriptions failed: %v", err)+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "internal"})+ }++ type row struct {+ AgentID string `json:"agent_id"`+ Feature string `json:"feature"`+ Status string `json:"status"`+ Active bool `json:"active"`+ PriceMonthlyCents int64 `json:"price_monthly_cents"`+ CurrentPeriodEnd *time.Time `json:"current_period_end,omitempty"`+ CancelAtPeriodEnd bool `json:"cancel_at_period_end"`+ CanceledAt *time.Time `json:"canceled_at,omitempty"`+ CreatedAt time.Time `json:"created_at"`+ StripeSubscriptionID string `json:"stripe_subscription_id"`+ }+ out := make([]row, 0, len(subs))+ for _, sub := range subs {+ out = append(out, row{+ AgentID: sub.AgentID,+ Feature: sub.Feature,+ Status: sub.Status,+ Active: db.AgentSubscriptionIsActive(sub.Status),+ PriceMonthlyCents: priceMonthlyCentsForFeature(sub.Feature),+ CurrentPeriodEnd: sub.CurrentPeriodEnd,+ CancelAtPeriodEnd: sub.CancelAtPeriodEnd,+ CanceledAt: sub.CanceledAt,+ CreatedAt: sub.CreatedAt,+ StripeSubscriptionID: sub.StripeSubscriptionID,+ })+ }+ return c.JSON(http.StatusOK, map[string]any{"subscriptions": out})+}++// apiAgentEntitlement is the sessions-api-callable variant — accepts+// JWT identity auth (aud=opencomputer-api) and returns a tight+// {entitled: bool, reason} payload. Used by sessions-api right before+// allowing a connect-channel operation.+func (s *Server) apiAgentEntitlement(c echo.Context) error {+ if s.store == nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "not configured"})+ }+ agentID := c.Param("agentId")+ feature := c.Param("feature")+ orgID, ok := auth.GetOrgID(c)+ if !ok {+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "auth required"})+ }++ priceID, knownFeature := s.priceIDForFeature(feature)+ if !knownFeature {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "unknown feature"})+ }+ if priceID == "" {+ // Feature ungated on this deployment.+ return c.JSON(http.StatusOK, map[string]any{+ "entitled": true,+ "reason": "ungated",+ "feature": feature,+ "agent_id": agentID,+ })+ }++ sub, err := s.store.GetActiveAgentSubscription(c.Request().Context(), agentID, feature)+ if err != nil {+ log.Printf("billing: entitlement lookup failed: %v", err)+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "internal"})+ }+ if sub == nil {+ // Same reconcile path as the dashboard handler — Stripe is the+ // source of truth, so look there before telling the CLI/sessions-api+ // the user hasn't paid.+ if reconciled, rerr := s.reconcileAgentFeatureFromStripe(c.Request().Context(), orgID, agentID, feature); rerr == nil && reconciled != nil {+ sub = reconciled+ }+ }+ if sub == nil || sub.OrgID != orgID || !db.AgentSubscriptionIsActive(sub.Status) {+ return c.JSON(http.StatusPaymentRequired, map[string]any{+ "entitled": false,+ "reason": "subscription_required",+ "feature": feature,+ "agent_id": agentID,+ "price_monthly_cents": priceMonthlyCentsForFeature(feature),+ })+ }+ return c.JSON(http.StatusOK, map[string]any{+ "entitled": true,+ "feature": feature,+ "agent_id": agentID,+ "status": sub.Status,+ "current_period_end": sub.CurrentPeriodEnd,+ "cancel_at_period_end": sub.CancelAtPeriodEnd,+ })+}++// priceIDForFeature maps a feature string to its configured Stripe+// price ID. Returns ("", true) if the feature is known but ungated on+// this deployment (used as the dev-mode escape). Returns ("", false)+// for unknown features.+func (s *Server) priceIDForFeature(feature string) (string, bool) {+ if s.stripeClient == nil {+ return "", feature == telegramFeature // unknown stripe → behave as ungated for the known features+ }+ switch feature {+ case telegramFeature:+ return s.stripeClient.TelegramAgentPriceID, true+ default:+ return "", false+ }+}++// priceMonthlyCentsForFeature is the human-readable price the UI+// surfaces. Hardcoded for now — Stripe is the source of truth for+// what the customer is actually charged; this is just for display.+// If the two diverge, that's a config bug.+func priceMonthlyCentsForFeature(feature string) int64 {+ switch feature {+ case telegramFeature:+ return 2000 // $20.00/mo+ }+ return 0+}+diff --git a/internal/api/dashboard_agents.go b/internal/api/dashboard_agents.gonew file mode 100644index 00000000..a6209fc0--- /dev/null+++ b/internal/api/dashboard_agents.go@@ -0,0 +1,194 @@+package api++import (+ "io"+ "log"+ "net/http"+ "net/url"+ "os"+ "strings"+ "time"++ "github.com/labstack/echo/v4"++ "github.com/opensandbox/opensandbox/internal/auth"+)++const (+ // inboundJWTTTL is the lifetime of the bearer token sessions-api verifies+ // on the proxied request. Sessions-api validates once at the route entry,+ // so this only needs to cover the initial verification — keep it tight.+ inboundJWTTTL = 90 * time.Second++ // downstreamJWTTTL is the lifetime of the JWT sessions-api forwards on+ // its OC API calls (sandbox creation, secret stores, exec.run via SDK).+ // Has to outlast the longest single agent operation: managed-core boot+ // involves checkpoint restore + entrypoint start + adapter waitReady,+ // which can take several minutes. 10m is a comfortable upper bound.+ downstreamJWTTTL = 10 * time.Minute++ // downstreamHeaderName is the header sessions-api relays as a Bearer+ // token on its calls back into OC's /api/sandboxes and /api/secret-stores.+ // Sessions-api never mints; OC pre-mints both tokens here.+ downstreamHeaderName = "X-OC-Downstream-Token"+)++// sessionsAPIBaseURL returns the upstream URL for the agents service. The env+// var matches the CLI's SESSIONS_API_URL (cmd/oc/internal/config) so a single+// value drives both surfaces.+func sessionsAPIBaseURL() string {+ if v := os.Getenv("SESSIONS_API_URL"); v != "" {+ return strings.TrimRight(v, "/")+ }+ return "https://api.opencomputer.dev"+}++// dashboardAgentsProxy is a thin reverse proxy from /api/dashboard/agents/*+// → ${SESSIONS_API_URL}/v1/agents/*. It runs after the WorkOS cookie+// middleware, so the request is already authenticated as a real user.+//+// Auth handling:+// - Mint two identity JWTs (sessions-api inbound, opencomputer-api downstream)+// using the user's identity from the echo context.+// - Strip Cookie / X-API-Key on the way out (sessions-api should rely on the+// Bearer token, never the dashboard cookie).+// - Set Authorization: Bearer <inbound-jwt>.+// - Set X-OC-Downstream-Token: <downstream-jwt> for sessions-api to relay.+//+// The CLI continues to use sessions-api directly with X-API-Key — that path+// is untouched.+func (s *Server) dashboardAgentsProxy(c echo.Context) error {+ if s.jwtIssuer == nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{+ "error": "agents proxy unavailable: jwt issuer not configured",+ })+ }++ orgID, ok := auth.GetOrgID(c)+ if !ok {+ return c.JSON(http.StatusUnauthorized, map[string]string{+ "error": "org context required",+ })+ }++ in := auth.IdentityTokenInput{OrgID: orgID.String(), Audience: auth.AudSessionsAPI}+ if userID := auth.GetUserID(c); userID != nil {+ userStr := userID.String()+ in.UserID = &userStr+ }+ if email, ok := c.Get("user_email").(string); ok && email != "" {+ in.Email = &email+ }+ // Lookup workos_user_id (best-effort — used for analytics attribution).+ if s.store != nil {+ if userID := auth.GetUserID(c); userID != nil {+ if user, err := s.store.GetUserByID(c.Request().Context(), *userID); err == nil {+ if user.WorkOSUserID != nil && *user.WorkOSUserID != "" {+ in.WorkOSUserID = user.WorkOSUserID+ }+ }+ }+ }++ inboundToken, err := s.jwtIssuer.IssueIdentityToken(in, inboundJWTTTL)+ if err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{+ "error": "failed to mint inbound token",+ })+ }++ downstreamIn := in+ downstreamIn.Audience = auth.AudOpenComputerAPI+ downstreamToken, err := s.jwtIssuer.IssueIdentityToken(downstreamIn, downstreamJWTTTL)+ if err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{+ "error": "failed to mint downstream token",+ })+ }++ // Map /api/dashboard/agents[/...] → /v1/agents[/...]+ upstreamPath := "/v1/agents"+ if rest := strings.TrimPrefix(c.Request().URL.Path, "/api/dashboard/agents"); rest != "" {+ upstreamPath += rest+ }+ upstream, err := url.Parse(sessionsAPIBaseURL() + upstreamPath)+ if err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{+ "error": "invalid upstream URL",+ })+ }+ upstream.RawQuery = c.Request().URL.RawQuery++ req, err := http.NewRequestWithContext(c.Request().Context(), c.Request().Method, upstream.String(), c.Request().Body)+ if err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{+ "error": "failed to build upstream request",+ })+ }++ // Forward request headers, but drop the ones that should not cross the+ // service boundary. The cookie carries the dashboard session; sessions-api+ // must rely on the Bearer token instead.+ for k, v := range c.Request().Header {+ switch strings.ToLower(k) {+ case "cookie", "authorization", "x-api-key", "host", "content-length":+ continue+ }+ req.Header[k] = v+ }+ req.Header.Set("Authorization", "Bearer "+inboundToken)+ req.Header.Set(downstreamHeaderName, downstreamToken)+ if ct := c.Request().Header.Get("Content-Type"); ct != "" {+ req.Header.Set("Content-Type", ct)+ }++ // Use a client without a fixed timeout so SSE streams (e.g. the+ // instance messages endpoint) can stay open. Idle reads are bounded+ // by the upstream's own keep-alive / write deadlines.+ streamingClient := &http.Client{}+ resp, err := streamingClient.Do(req)+ if err != nil {+ log.Printf("dashboard_agents: upstream call failed: %v", err)+ return c.JSON(http.StatusBadGateway, map[string]string{+ "error": "upstream request failed",+ })+ }+ defer resp.Body.Close()++ for k, v := range resp.Header {+ // Hop-by-hop headers shouldn't be forwarded.+ switch strings.ToLower(k) {+ case "transfer-encoding", "connection", "keep-alive":+ continue+ }+ c.Response().Header()[k] = v+ }+ c.Response().WriteHeader(resp.StatusCode)++ // Streaming-aware copy: flush after every read so SSE events from the+ // upstream (text/event-stream Content-Type) reach the browser as soon+ // as they're produced. io.Copy on its own does not call Flush; the+ // browser would only see events when net/http's own buffer fills,+ // which kills the chat UX.+ flusher, _ := c.Response().Writer.(http.Flusher)+ buf := make([]byte, 4096)+ for {+ n, readErr := resp.Body.Read(buf)+ if n > 0 {+ if _, writeErr := c.Response().Writer.Write(buf[:n]); writeErr != nil {+ log.Printf("dashboard_agents: write to client failed: %v", writeErr)+ return nil+ }+ if flusher != nil {+ flusher.Flush()+ }+ }+ if readErr != nil {+ if readErr != io.EOF {+ log.Printf("dashboard_agents: read from upstream failed: %v", readErr)+ }+ return nil+ }+ }+}+diff --git a/internal/api/dashboard_billing.go b/internal/api/dashboard_billing.goindex 42bd7f09..a2a03fe2 100644--- a/internal/api/dashboard_billing.go+++ b/internal/api/dashboard_billing.go@@ -1,15 +1,18 @@package apiimport (+ "context""encoding/json""io""log""net/http""strconv"+ "time""github.com/google/uuid""github.com/labstack/echo/v4""github.com/opensandbox/opensandbox/internal/auth"+ "github.com/opensandbox/opensandbox/internal/db")// billingSetup initiates the upgrade flow: creates Stripe customer + Checkout session.@@ -246,7 +249,8 @@ func (s *Server) stripeWebhook(c echo.Context) error {if err := json.Unmarshal(event.Data.Raw, &sess); err != nil {return c.JSON(http.StatusBadRequest, map[string]string{"error": "bad event data"})}- if sess.Metadata["type"] == "setup" {+ switch sess.Metadata["type"] {+ case "setup":orgIDStr := sess.Metadata["org_id"]orgID, err := uuid.Parse(orgIDStr)if err != nil {@@ -277,8 +281,19 @@ func (s *Server) stripeWebhook(c echo.Context) error {}log.Printf("billing: org %s upgraded to pro (subscription=%s, $30 credit applied)", orgID, subID)++ case "agent_feature_subscription":+ // Customer paid for a per-agent feature via Checkout. The+ // Stripe-side subscription is already created (Checkout+ // mode=subscription); we just persist the local row so+ // the entitlement check finds it. Subscription metadata+ // carries (org_id, agent_id, feature).+ s.recordAgentFeatureCheckoutCompletion(ctx, sess.Metadata, event.Data.Raw)}+ case "customer.subscription.created", "customer.subscription.updated", "customer.subscription.deleted":+ s.handleAgentFeatureSubscriptionEvent(ctx, string(event.Type), event.Data.Raw)+case "invoice.paid":log.Printf("billing: invoice paid: %s", string(event.Data.Raw)[:100])@@ -288,3 +303,137 @@ func (s *Server) stripeWebhook(c echo.Context) error {return c.JSON(http.StatusOK, map[string]string{"status": "ok"})}++// recordAgentFeatureCheckoutCompletion persists a freshly-created+// per-agent feature subscription that was set up via Checkout. The+// Subscription object is already on Stripe; we just need to insert+// the local row. Metadata is propagated from the Checkout Session+// into the Subscription, so the subsequent customer.subscription.*+// events will also trigger handleAgentFeatureSubscriptionEvent which+// fills in current_period_end / status / etc.+func (s *Server) recordAgentFeatureCheckoutCompletion(ctx context.Context, metadata map[string]string, raw []byte) {+ orgID, err := uuid.Parse(metadata["org_id"])+ if err != nil {+ log.Printf("billing: agent_feature_subscription checkout missing org_id: %v", err)+ return+ }+ agentID := metadata["agent_id"]+ feature := metadata["feature"]+ if agentID == "" || feature == "" {+ log.Printf("billing: agent_feature_subscription checkout missing agent_id/feature in metadata")+ return+ }++ // Pull the subscription_id out of the checkout session payload —+ // Stripe attaches it after Checkout creates the subscription.+ var sess struct {+ Subscription string `json:"subscription"`+ Customer string `json:"customer"`+ }+ if err := json.Unmarshal(raw, &sess); err != nil {+ log.Printf("billing: agent_feature_subscription checkout: unmarshal: %v", err)+ return+ }+ if sess.Subscription == "" {+ log.Printf("billing: agent_feature_subscription checkout has no subscription id")+ return+ }++ // Idempotent: skip if we already recorded it.+ existing, err := s.store.GetAgentSubscriptionByStripeID(ctx, sess.Subscription)+ if err == nil && existing != nil {+ return+ }++ priceID := ""+ if s.stripeClient != nil {+ switch feature {+ case "telegram":+ priceID = s.stripeClient.TelegramAgentPriceID+ }+ }++ if _, err := s.store.CreateAgentSubscription(ctx, db.AgentSubscription{+ OrgID: orgID,+ AgentID: agentID,+ Feature: feature,+ StripeCustomerID: sess.Customer,+ StripeSubscriptionID: sess.Subscription,+ StripePriceID: priceID,+ Status: "incomplete", // will be updated by subscription.updated event+ }); err != nil {+ log.Printf("billing: persist agent_subscription from checkout failed: %v", err)+ } else {+ log.Printf("billing: agent_feature_subscription recorded: agent=%s feature=%s sub=%s", agentID, feature, sess.Subscription)+ }+}++// handleAgentFeatureSubscriptionEvent reconciles status on every+// customer.subscription.* event. We filter to subscriptions that we+// have a local row for — anything else is the org-level pro-plan+// subscription which is handled elsewhere.+//+// `customer.subscription.deleted` fires when Stripe finally removes+// the subscription (after period end if cancel_at_period_end was+// scheduled, or immediately for a hard cancel). At that point we+// flip the local row to canceled and disconnect any active Telegram+// webhook so the user actually loses access.+func (s *Server) handleAgentFeatureSubscriptionEvent(ctx context.Context, eventType string, raw []byte) {+ var sub struct {+ ID string `json:"id"`+ Status string `json:"status"`+ CancelAtPeriodEnd bool `json:"cancel_at_period_end"`+ CanceledAt *int64 `json:"canceled_at"`+ Metadata map[string]string `json:"metadata"`+ Items struct {+ Data []struct {+ CurrentPeriodEnd int64 `json:"current_period_end"`+ } `json:"data"`+ } `json:"items"`+ }+ if err := json.Unmarshal(raw, &sub); err != nil {+ log.Printf("billing: subscription event unmarshal: %v", err)+ return+ }++ row, err := s.store.GetAgentSubscriptionByStripeID(ctx, sub.ID)+ if err != nil {+ log.Printf("billing: lookup agent_subscription %s failed: %v", sub.ID, err)+ return+ }+ if row == nil {+ // Not a per-agent subscription — ignore.+ return+ }++ var currentPeriodEnd *time.Time+ if len(sub.Items.Data) > 0 && sub.Items.Data[0].CurrentPeriodEnd > 0 {+ t := time.Unix(sub.Items.Data[0].CurrentPeriodEnd, 0).UTC()+ currentPeriodEnd = &t+ }+ var canceledAt *time.Time+ if sub.CanceledAt != nil && *sub.CanceledAt > 0 {+ t := time.Unix(*sub.CanceledAt, 0).UTC()+ canceledAt = &t+ }++ if err := s.store.UpdateAgentSubscriptionFromStripe(+ ctx, sub.ID, sub.Status, currentPeriodEnd, sub.CancelAtPeriodEnd, canceledAt,+ ); err != nil {+ log.Printf("billing: update agent_subscription %s failed: %v", sub.ID, err)+ return+ }++ // On terminal statuses, the entitlement check will start denying+ // new connect attempts immediately. We deliberately don't auto-+ // disconnect a currently-connected Telegram channel from here —+ // that side-effect needs an authenticated call into sessions-api,+ // and the cleanest way to do it is from the user-facing flow+ // (e.g. show "subscription expired" in the UI and let them click+ // Disconnect, or have sessions-api re-check entitlement on each+ // inbound webhook). Phase-1 leaves this as a "soft" gate.+ if eventType == "customer.subscription.deleted" {+ log.Printf("billing: agent_subscription terminated: agent=%s feature=%s sub=%s status=%s",+ row.AgentID, row.Feature, sub.ID, sub.Status)+ }+}diff --git a/internal/api/identity.go b/internal/api/identity.goindex f862e28b..3d66fd18 100644--- a/internal/api/identity.go+++ b/internal/api/identity.go@@ -29,7 +29,7 @@ func (s *Server) createAuthToken(c echo.Context) error {})}- in := auth.IdentityTokenInput{OrgID: orgID.String()}+ in := auth.IdentityTokenInput{OrgID: orgID.String(), Audience: auth.AudSessionsAPI}if userID := auth.GetUserID(c); userID != nil {userStr := userID.String()in.UserID = &userStrdiff --git a/internal/api/image_builder.go b/internal/api/image_builder.goindex 2321afb3..a07344db 100644--- a/internal/api/image_builder.go+++ b/internal/api/image_builder.go@@ -399,7 +399,8 @@ func (s *Server) buildImage(ctx context.Context, orgID uuid.UUID, manifest *Imag}_ = resp} else if s.manager != nil {- cfg.NetworkEnabled = true+ t := true+ cfg.NetworkEnabled = &tsb, err := s.manager.Create(ctx, cfg)if err != nil {return uuid.Nil, fmt.Errorf("failed to create build sandbox: %w", err)@@ -441,7 +442,9 @@ func (s *Server) buildImage(ctx context.Context, orgID uuid.UUID, manifest *Imagif workerID == "" {workerID = "w-local-1"}- _, _ = s.store.CreateSandboxSession(ctx, buildSandboxID, orgID, nil, cfg.Template, region, workerID, cfgJSON, []byte("{}"))+ // Image-builder sandboxes never bind to a customer secret store —+ // secret_store_id stays NULL. They run a Dockerfile build, not user code.+ _, _ = s.store.CreateSandboxSession(ctx, buildSandboxID, orgID, nil, cfg.Template, region, workerID, cfgJSON, []byte("{}"), nil)if s.workerRegistry != nil {if w := s.workerRegistry.GetWorker(workerID); w != nil && w.GoldenVersion != "" {_ = s.store.SetSandboxGoldenVersion(ctx, buildSandboxID, w.GoldenVersion)@@ -499,36 +502,41 @@ func (s *Server) buildImage(ctx context.Context, orgID uuid.UUID, manifest *Imag}}- // Create checkpoint on worker+ // Create checkpoint on worker. 20-min budget matches the regular+ // checkpoint create path (api/sandbox.go) — image builder checkpoints+ // can be just as large, and the previous 2-min ceiling silently failed+ // big builds the same way the regular path failed Oliviero's 7-9 GB+ // sandbox.if grpcClient != nil {- cpCtx, cancel := context.WithTimeout(ctx, 120*time.Second)+ cpCtx, cancel := context.WithTimeout(ctx, 20*time.Minute)defer cancel()resp, err := grpcClient.CreateCheckpoint(cpCtx, &pb.CreateCheckpointRequest{- SandboxId: buildSandboxID,- CheckpointId: checkpointID.String(),- PrepareGolden: true, // prepare golden snapshot for instant template creates+ SandboxId: buildSandboxID,+ CheckpointId: checkpointID.String(),+ PrepareGolden: true, // prepare golden snapshot for instant template creates})if err != nil {return uuid.Nil, fmt.Errorf("failed to checkpoint build sandbox: %w", err)}- // Update checkpoint with S3 keys+ // Persist S3 keys + actual archive size on the row. Pre-fix the size+ // field was hardcoded to 0 even though the gRPC response carries it.if s.store != nil {- _ = s.store.SetCheckpointReady(ctx, checkpointID, resp.RootfsS3Key, resp.WorkspaceS3Key, 0)+ _ = s.store.SetCheckpointReady(ctx, checkpointID, resp.RootfsS3Key, resp.WorkspaceS3Key, resp.SizeBytes)}} else if s.manager != nil {// Combined mode: call CreateCheckpoint via reflection-free approach.// The concrete firecracker.Manager implements CreateCheckpoint directly.type checkpointer interface {- CreateCheckpoint(ctx context.Context, sandboxID, checkpointID string, checkpointStore *storage.CheckpointStore, onReady func()) (string, string, error)+ CreateCheckpoint(ctx context.Context, sandboxID, checkpointID string, checkpointStore *storage.CheckpointStore, onReady func()) (string, string, int64, error)}cpMgr, ok := s.manager.(checkpointer)if !ok {return uuid.Nil, fmt.Errorf("manager does not support checkpoints")}- rootfsKey, workspaceKey, err := cpMgr.CreateCheckpoint(ctx, buildSandboxID, checkpointID.String(), s.checkpointStore, func() {})+ rootfsKey, workspaceKey, sizeBytes, err := cpMgr.CreateCheckpoint(ctx, buildSandboxID, checkpointID.String(), s.checkpointStore, func() {})if err != nil {return uuid.Nil, fmt.Errorf("failed to checkpoint build sandbox: %w", err)}@@ -542,7 +550,7 @@ func (s *Server) buildImage(ctx context.Context, orgID uuid.UUID, manifest *Imag}if s.store != nil {- _ = s.store.SetCheckpointReady(ctx, checkpointID, rootfsKey, workspaceKey, 0)+ _ = s.store.SetCheckpointReady(ctx, checkpointID, rootfsKey, workspaceKey, sizeBytes)}// Prepare golden snapshot for combined modediff --git a/internal/api/internal_sandbox.go b/internal/api/internal_sandbox.goindex f2737fa9..73a08822 100644--- a/internal/api/internal_sandbox.go+++ b/internal/api/internal_sandbox.go@@ -82,6 +82,7 @@ func (s *Server) internalCreateSandbox(c echo.Context) error {// Reuse the normal remote-create path — picks a worker, dispatches via// gRPC, persists the session, writes the {sandboxID, token, status, ...}- // response body.- return s.createSandboxRemote(c, c.Request().Context(), cfg, orgID, true)+ // response body. secretStoreID is nil here — cap-token callers don't+ // reference an org-uploaded secret store (that's a /api/sandboxes feature).+ return s.createSandboxRemote(c, c.Request().Context(), cfg, orgID, true, nil)}diff --git a/internal/api/projects.go b/internal/api/projects.goindex 0525a0e1..791c216b 100644--- a/internal/api/projects.go+++ b/internal/api/projects.go@@ -1,13 +1,22 @@package apiimport (+ "context"+ "fmt"+ "log""net/http""strings"+ "sync"+ "time""github.com/google/uuid""github.com/labstack/echo/v4"+ "google.golang.org/grpc/codes"+ "google.golang.org/grpc/status""github.com/opensandbox/opensandbox/internal/auth"+ "github.com/opensandbox/opensandbox/internal/db"+ pb "github.com/opensandbox/opensandbox/proto/worker")// ── Secret Stores ─────────────────────────────────────────────────────────────@@ -182,7 +191,27 @@ func (s *Server) setSecretEntry(c echo.Context) error {if err := s.store.SetSecretEntry(c.Request().Context(), storeID, name, []byte(req.Value), req.AllowedHosts); err != nil {return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})}- return c.JSON(http.StatusOK, map[string]string{"name": name, "status": "set"})++ // Fan the new value out to running sandboxes that resolve envs from this+ // store. The proxy on each affected worker updates the value its sealed+ // token resolves to — the sandbox env keeps the same `osb_sealed_xxx`+ // string, so no restart, no env re-injection, and no agent involvement+ // inside the guest. Synchronous: PUT returns only after every reachable+ // affected worker has confirmed (or hit the timeout). Per-sandbox failures+ // are logged + included in the response but don't fail the whole call —+ // the DB write is the source of truth and fresh values will propagate+ // on the next sandbox handoff (wake, fork, migrate).+ refreshed, refreshErrs := s.fanoutSecretRefresh(c.Request().Context(), storeID, name, req.Value)++ resp := map[string]any{+ "name": name,+ "status": "set",+ "refreshed": refreshed,+ }+ if len(refreshErrs) > 0 {+ resp["refreshErrors"] = refreshErrs+ }+ return c.JSON(http.StatusOK, resp)}func (s *Server) deleteSecretEntry(c echo.Context) error {@@ -234,3 +263,127 @@ func (s *Server) listSecretEntries(c echo.Context) error {}return c.JSON(http.StatusOK, entries)}++// secretRefreshTimeout is the per-call deadline for the worker fan-out. Picked+// to comfortably exceed the worst-case gRPC RTT to a healthy worker (~1s) plus+// migration windows where source/destination both need a push. PUT /secrets+// returns within this bound regardless of how many sandboxes are affected.+const secretRefreshTimeout = 15 * time.Second++// fanoutSecretRefresh tells every worker hosting a sandbox that uses this+// SecretStore to update its proxy session's value for `name` to `newValue`.+// Synchronous: caller blocks until all in-flight RPCs complete or hit the+// timeout. Returns the count of sandboxes successfully refreshed and a slice+// of human-readable per-sandbox failures.+//+// Migration awareness: if a sandbox is mid-migration (`migrating_to_worker`+// non-empty), the update is pushed to BOTH source and destination workers in+// parallel. The "winner" depends on which worker's gRPC call lands last; both+// are correct because the proxy session on the destination is re-registered+// during PrepareIncomingMigration, which means by the time we're pushing+// updates the destination has a session to update. Idempotent on either side+// — pushing to a worker that doesn't have a session for this sandbox returns+// updated=false (transient miss, logged but not fatal).+func (s *Server) fanoutSecretRefresh(parentCtx context.Context, storeID uuid.UUID, name, newValue string) (refreshed int, failures []string) {+ if s.store == nil || s.workerRegistry == nil {+ return 0, nil+ }++ // Use a separate context with our own timeout — the parent is the HTTP+ // request, which we don't want to bleed onto. Caller ultimately waits up+ // to secretRefreshTimeout regardless of the request's deadline.+ ctx, cancel := context.WithTimeout(context.Background(), secretRefreshTimeout)+ defer cancel()+ _ = parentCtx // not propagated; we want bounded fanout time++ targets, err := s.store.ListRunningSandboxesByStore(ctx, storeID)+ if err != nil {+ log.Printf("secret-refresh: list sandboxes for store %s failed: %v", storeID, err)+ failures = append(failures, fmt.Sprintf("list affected sandboxes: %v", err))+ return 0, failures+ }+ if len(targets) == 0 {+ return 0, nil+ }++ type result struct {+ sandboxID string+ ok bool+ err error+ }++ // Dedup: a sandbox mid-migration appears once but spawns 2 RPC calls+ // (source + destination). pushOne handles a single (sandboxID, workerID)+ // pair so we can reuse for both halves of the dual-push.+ pushOne := func(sandboxID, workerID string) result {+ client, err := s.workerRegistry.GetWorkerClient(workerID)+ if err != nil {+ return result{sandboxID: sandboxID, err: fmt.Errorf("worker %s unreachable: %w", workerID, err)}+ }+ callCtx, callCancel := context.WithTimeout(ctx, 5*time.Second)+ defer callCancel()+ resp, err := client.UpdateSandboxSecret(callCtx, &pb.UpdateSandboxSecretRequest{+ SandboxId: sandboxID,+ SecretName: name,+ Value: newValue,+ })+ if err != nil {+ // Rollout safety: a worker that hasn't picked up the new binary yet+ // returns Unimplemented for this RPC. Treat as a soft skip — the+ // sandbox keeps its old value until its next handoff (wake/fork/+ // migrate) re-resolves from the store. This lets the server be+ // deployed before the worker fleet has fully rolled over without+ // every PUT /secrets call surfacing failures during the dance.+ if status.Code(err) == codes.Unimplemented {+ log.Printf("secret-refresh: worker %s on old binary (Unimplemented); skipping sandbox=%s, will refresh on next handoff", workerID, sandboxID)+ return result{sandboxID: sandboxID, ok: false}+ }+ return result{sandboxID: sandboxID, err: fmt.Errorf("worker %s rpc: %w", workerID, err)}+ }+ return result{sandboxID: sandboxID, ok: resp.Updated}+ }++ var wg sync.WaitGroup+ resultsCh := make(chan result, len(targets)*2)+ for _, t := range targets {+ wg.Add(1)+ go func(t db.SecretRefreshTarget) {+ defer wg.Done()+ // Always push to the source worker.+ resultsCh <- pushOne(t.SandboxID, t.WorkerID)+ // During an in-flight migration, also push to the destination+ // so the cutover doesn't leave it serving stale values.+ if t.MigratingToWorker != "" {+ resultsCh <- pushOne(t.SandboxID, t.MigratingToWorker)+ }+ }(t)+ }+ wg.Wait()+ close(resultsCh)++ // Roll up results. A sandbox is "refreshed" if at least one of its push+ // attempts (source or destination) returned updated=true. A failure on+ // only one side of a migration is logged but doesn't downgrade the+ // sandbox's refreshed status — the other side handled it.+ successBySandbox := make(map[string]bool, len(targets))+ for r := range resultsCh {+ if r.err != nil {+ log.Printf("secret-refresh: store=%s name=%s sandbox=%s: %v", storeID, name, r.sandboxID, r.err)+ failures = append(failures, fmt.Sprintf("%s: %v", r.sandboxID, r.err))+ continue+ }+ if r.ok {+ successBySandbox[r.sandboxID] = true+ }+ }+ for _, ok := range successBySandbox {+ if ok {+ refreshed+++ }+ }+ if refreshed > 0 {+ log.Printf("secret-refresh: store=%s name=%s refreshed=%d failures=%d", storeID, name, refreshed, len(failures))+ }+ return refreshed, failures+}+diff --git a/internal/api/router.go b/internal/api/router.goindex 5e3f27eb..f9995605 100644--- a/internal/api/router.go+++ b/internal/api/router.go@@ -22,7 +22,9 @@ import ("github.com/opensandbox/opensandbox/internal/cloudflare""github.com/opensandbox/opensandbox/internal/controlplane""github.com/opensandbox/opensandbox/internal/db"+ "github.com/opensandbox/opensandbox/internal/metrics""github.com/opensandbox/opensandbox/internal/observability"+ "github.com/opensandbox/opensandbox/internal/obslog""github.com/opensandbox/opensandbox/internal/proxy""github.com/opensandbox/opensandbox/internal/sandbox""github.com/opensandbox/opensandbox/internal/storage"@@ -59,6 +61,19 @@ type Server struct {redisClient *redis.Client // nil if Redis not configured (for health checks)adminEvents *AdminEventBus // real-time event bus for admin dashboardready int32 // atomic: 1 = ready, 0 = not ready++ // Axiom log query (sandbox session logs read API).+ // Empty token = endpoint returns 503.+ axiomQueryToken string+ axiomDataset string+}++// SetAxiomQueryConfig wires the read-only Axiom token and dataset for+// the sandbox session logs read API. Token never leaves the control+// plane; the UI proxies through us.+func (s *Server) SetAxiomQueryConfig(queryToken, dataset string) {+ s.axiomQueryToken = queryToken+ s.axiomDataset = dataset}// pendingCreate tracks an async sandbox creation.@@ -148,11 +163,19 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o// Global middleware. Sentry goes first so it can attach request context and// observe panics before echo's Recover middleware converts them to 500s.+ // RequestID() runs before obslog.EchoMiddleware so the X-Request-Id header+ // is on the response by the time obslog reads it. obslog replaces Echo's+ // built-in Logger() — same access log line, but JSON with the host+ // envelope and request_id/sandbox_id pulled from context.e.Use(observability.EchoMiddleware())e.Use(middleware.Recover())- e.Use(middleware.Logger())- e.Use(middleware.CORS())e.Use(middleware.RequestID())+ e.Use(obslog.EchoMiddleware())+ // Prometheus instrumentation: counts requests by status, observes handler+ // latency, tracks in-flight. Uses c.Path() (route template) for the path+ // label so high-cardinality IDs don't blow up the metric.+ e.Use(metrics.EchoMiddleware())+ e.Use(middleware.CORS())// Subdomain proxy middleware (before auth — subdomain traffic is public)if opts != nil && opts.SandboxProxy != nil {@@ -224,6 +247,7 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, oadmin.GET("/events/history", s.adminEventsHistory)admin.GET("/report", s.adminReport)admin.POST("/events/clear", s.adminClearEvents)+ admin.POST("/workers/:id/drain", s.adminSetWorkerDraining)admin.GET("/demo/migration", s.demoPingPongPage)admin.GET("/demo/chaos", s.demoChaosPage)@@ -242,21 +266,35 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o// API routes (with API key auth)api := e.Group("/api")- api.Use(auth.PGAPIKeyMiddleware(s.store, apiKey))+ api.Use(auth.PGAPIKeyMiddleware(s.store, apiKey, s.jwtIssuer))// Identityapi.POST("/auth/token", s.createAuthToken)+ // Per-agent paywalled-feature entitlement check, callable from+ // sessions-api with a JWT (aud=opencomputer-api) right before+ // allowing a connect-channel operation.+ api.GET("/agents/:agentId/entitlements/:feature", s.apiAgentEntitlement)+// Sandbox lifecycleapi.POST("/sandboxes", s.createSandbox)api.GET("/sandboxes", s.listSandboxes)api.GET("/sandboxes/:id", s.getSandbox)api.DELETE("/sandboxes/:id", s.killSandbox)+ // Sandbox session logs — SDK / curl variant. Same handler as the+ // dashboard's /api/dashboard/sessions/:sandboxId/logs route below;+ // auth here is X-API-Key (or identity-JWT) instead of cookie.+ // Useful for headless testing and SDK consumers.+ api.GET("/sandboxes/:id/logs", s.getSandboxLogs)+// Reserved capacity (spec: ws-pricing/design/001-reserved-capacity-squares.md)api.GET("/capacity/calendar", s.getCapacityCalendar)api.POST("/capacity/reservations", s.createCapacityReservation)api.GET("/capacity/reservations", s.listCapacityReservations)+ // Internal/undocumented — phase-2 outbox inspection. See note in+ // getCapacityBillableEvents handler.+ api.GET("/capacity/billable-events", s.getCapacityBillableEvents)// Usage + tags (design: .agents/design/sandbox-tags-and-usage.md)api.GET("/usage", s.getUsage)@@ -269,12 +307,23 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, oapi.POST("/sandboxes/:id/hibernate", s.hibernateSandbox)api.POST("/sandboxes/:id/wake", s.wakeSandbox)+ // Reset operations: reboot is a soft, in-place guest restart; power-cycle+ // is a hard restart that re-creates the QEMU process. Both preserve the+ // sandbox's identity and persistent data.+ api.POST("/sandboxes/:id/reboot", s.rebootSandbox)+ api.POST("/sandboxes/:id/power-cycle", s.powerCycleSandbox)+// Live migrationapi.POST("/sandboxes/:id/migrate", s.migrateSandbox)// Resource limitsapi.PUT("/sandboxes/:id/limits", s.setLimits)api.POST("/sandboxes/:id/scale", s.scaleSandbox)+ api.PUT("/sandboxes/:id/autoscale", s.setAutoscale)+ api.GET("/sandboxes/:id/autoscale", s.getAutoscale)+ api.PUT("/sandboxes/:id/scaling-lock", s.setScalingLock)+ api.GET("/sandboxes/:id/scaling-lock", s.getScalingLock)+ api.GET("/sandboxes/:id/allowed-hosts", s.getSandboxAllowedHosts)// Checkpointsapi.POST("/sandboxes/:id/checkpoints", s.createCheckpoint)@@ -451,12 +500,35 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, odash.GET("/billing/invoices", s.billingInvoices)dash.POST("/billing/redeem", s.billingRedeem)dash.POST("/billing/portal", s.billingPortal)+ dash.GET("/billing/agent-subscriptions", s.dashboardListOrgAgentSubscriptions)// Admin endpoints+ // Agents — reverse-proxy to sessions-api. Mints short-lived identity+ // JWTs for the inbound (sessions-api) and downstream (OC API) hops so+ // no API key is needed end-to-end. CLI users bypass this and hit+ // sessions-api directly with X-API-Key.+ dash.Any("/agents", s.dashboardAgentsProxy)+ // Per-agent paywalled-feature subscriptions (telegram et al).+ // Mounted BEFORE the catch-all /agents/* proxy so they don't+ // get forwarded to sessions-api.+ dash.GET("/agents/:agentId/entitlements", s.dashboardListAgentEntitlements)+ dash.POST("/agents/:agentId/subscriptions/:feature", s.dashboardSubscribeAgentFeature)+ dash.DELETE("/agents/:agentId/subscriptions/:feature", s.dashboardCancelAgentFeature)++ dash.Any("/agents/*", s.dashboardAgentsProxy)+// Session detail + statsdash.GET("/sessions/:sandboxId", s.dashboardGetSession)dash.GET("/sessions/:sandboxId/stats", s.dashboardGetSessionStats)+ // Reset operations+ dash.POST("/sessions/:sandboxId/reboot", s.dashboardRebootSession)+ dash.POST("/sessions/:sandboxId/power-cycle", s.dashboardPowerCycleSession)+ // Sandbox session logs (SSE; historical + 1s-poll live tail).+ // Server queries Axiom server-side with a read-only token that+ // never reaches the browser. Org-ownership enforced via+ // GetSandboxSessionInOrg (404 on mismatch — no cross-org leak).+ dash.GET("/sessions/:sandboxId/logs", s.getSandboxLogs)// PTY (terminal)dash.POST("/sessions/:sandboxId/pty", s.dashboardCreatePTY)dash.GET("/sessions/:sandboxId/pty/:sessionId", s.dashboardPTYWebSocket)diff --git a/internal/api/sandbox.go b/internal/api/sandbox.goindex 685fe624..64e35dd2 100644--- a/internal/api/sandbox.go+++ b/internal/api/sandbox.go@@ -26,6 +26,9 @@ func (s *Server) createSandbox(c echo.Context) error {"error": "invalid request body: " + err.Error(),})}+ // Default networkEnabled=true when caller omits it, so the value persisted+ // to sandbox_sessions.config_json is explicit and forks inherit it correctly.+ cfg.EnsureNetworkEnabledDefault()// Validate CPU/memory against allowed tiers.// Allowed tiers (memoryMB → vCPU): 1024→1, 4096→1, 8192→2, 16384→4, 32768→8, 65536→16.@@ -136,7 +139,7 @@ func (s *Server) createSandbox(c echo.Context) error {// on the fork. User envs override checkpoint's stored envs.// Secret store: if checkpoint has none, user can attach one at fork time.// If checkpoint already has one, user cannot override it.- result, status, cpErr := s.createFromCheckpointCore(c, cfg.Envs, cfg.SecretStore)+ result, status, cpErr := s.createFromCheckpointCore(c, cfg.Envs, cfg.SecretStore, cfg.Metadata)if cpErr != nil {return c.JSON(status, map[string]string{"error": cpErr.Error()})}@@ -146,8 +149,11 @@ func (s *Server) createSandbox(c echo.Context) error {// Fresh-create path: resolve the secret store (if any) into cfg.SecretEnvs.// This is intentionally below the snapshot/image branch so the snapshot// path never resolves a user-supplied store — forks inherit only.+ var secretStoreID *uuid.UUIDif cfg.SecretStore != "" && hasOrg {- if err := s.resolveSecretStoreInto(ctx, orgID, &cfg); err != nil {+ var err error+ secretStoreID, err = s.resolveSecretStoreInto(ctx, orgID, &cfg)+ if err != nil {log.Printf("api: %v", err)return c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()})}@@ -155,7 +161,7 @@ func (s *Server) createSandbox(c echo.Context) error {// Server mode with worker registry: dispatch to remote worker via gRPCif s.workerRegistry != nil {- return s.createSandboxRemote(c, ctx, cfg, orgID, hasOrg)+ return s.createSandboxRemote(c, ctx, cfg, orgID, hasOrg, secretStoreID)}// Combined/worker mode: create locally@@ -216,7 +222,7 @@ func (s *Server) createSandbox(c echo.Context) error {if template == "" {template = "default"}- _, _ = s.store.CreateSandboxSession(ctx, sb.ID, orgID, auth.GetUserID(c), template, region, workerID, cfgJSON, metadataJSON)+ _, _ = s.store.CreateSandboxSession(ctx, sb.ID, orgID, auth.GetUserID(c), template, region, workerID, cfgJSON, metadataJSON, secretStoreID)}return c.JSON(http.StatusCreated, sb)@@ -292,7 +298,7 @@ func (s *Server) createSandboxWithSSE(c echo.Context, ctx context.Context, orgIDc.SetParamNames("checkpointId")c.SetParamValues(checkpointID.String())- result, _, cpErr := s.createFromCheckpointCore(c, cfg.Envs, cfg.SecretStore)+ result, _, cpErr := s.createFromCheckpointCore(c, cfg.Envs, cfg.SecretStore, cfg.Metadata)if cpErr != nil {emit("error", map[string]string{"error": cpErr.Error()})return nil@@ -312,23 +318,28 @@ func (s *Server) createSandboxWithSSE(c echo.Context, ctx context.Context, orgID// happens, so the same logic runs on both fresh creates and on// fork-from-checkpoint inheritance. If the user updates a secret between// snapshot and fork, the fork sees the new value.-func (s *Server) resolveSecretStoreInto(ctx context.Context, orgID [16]byte, cfg *types.SandboxConfig) error {+// resolveSecretStoreInto looks up the named secret store, decrypts entries+// into cfg, and returns the store's UUID (or nil if no store was bound).+// The UUID is plumbed back to CreateSandboxSession so sandbox_sessions.+// secret_store_id gets populated — required for the secret-refresh fanout+// (ListRunningSandboxesByStore filters on this column).+func (s *Server) resolveSecretStoreInto(ctx context.Context, orgID [16]byte, cfg *types.SandboxConfig) (*uuid.UUID, error) {if cfg.SecretStore == "" || s.store == nil {- return nil+ return nil, nil}store, err := s.store.GetSecretStoreByName(ctx, orgID, cfg.SecretStore)if err != nil {- return fmt.Errorf("secret store not found: %s", cfg.SecretStore)+ return nil, fmt.Errorf("secret store not found: %s", cfg.SecretStore)}cfg.EgressAllowlist = store.EgressAllowlistsecrets, err := s.store.DecryptSecretEntries(ctx, store.ID)if err != nil {- return fmt.Errorf("failed to decrypt secrets for store %s: %w", cfg.SecretStore, err)+ return nil, fmt.Errorf("failed to decrypt secrets for store %s: %w", cfg.SecretStore, err)}if len(secrets) == 0 {- return nil+ return &store.ID, nil}if cfg.SecretEnvs == nil {cfg.SecretEnvs = make(map[string]string, len(secrets))@@ -342,7 +353,7 @@ func (s *Server) resolveSecretStoreInto(ctx context.Context, orgID [16]byte, cfgcfg.SecretAllowedHosts[secret.Name] = secret.AllowedHosts}}- return nil+ return &store.ID, nil}// cfgForPersistence returns a copy of cfg suitable for marshaling into PG@@ -393,7 +404,10 @@ func flattenSecretAllowedHosts(m map[string][]string) map[string]string {}// createSandboxRemote dispatches sandbox creation to a remote worker via gRPC.-func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg types.SandboxConfig, orgID [16]byte, hasOrg bool) error {+// secretStoreID is the resolved store UUID (or nil) from resolveSecretStoreInto;+// passed straight to CreateSandboxSessionWithStatus so the row's secret_store_id+// column is populated and the secret-refresh fanout can find this sandbox.+func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg types.SandboxConfig, orgID [16]byte, hasOrg bool, secretStoreID *uuid.UUID) error {// Select region (explicit header, or default to server's region)region := c.Request().Header.Get("Fly-Region")if region == "" {@@ -448,8 +462,13 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg ty// Dispatch via persistent gRPC connection.// Worker uses local cache for checkpoint forks (300ms) and downloads from S3- // only on cold starts (~30s). 60s is enough for both paths.- grpcTimeout := 60 * time.Second+ // only on cold starts. The pre-fix 60s budget was tight for cold forks of+ // multi-GB checkpoints — under any blob-side contention or rebase work,+ // the call could time out before the worker finished. Bumped to a generous+ // flat 5min so cold forks of large checkpoints land cleanly. The happy+ // path is unchanged: this RPC returns as soon as the VM is up, so warm+ // forks still complete in well under a second.+ grpcTimeout := 5 * time.MinutegrpcCtx, cancel := context.WithTimeout(ctx, grpcTimeout)defer cancel()@@ -471,7 +490,7 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg ty}cfgJSON, _ := json.Marshal(cfgForPersistence(cfg))metadataJSON, _ := json.Marshal(cfg.Metadata)- _, _ = s.store.CreateSandboxSessionWithStatus(ctx, sandboxID, orgID, auth.GetUserID(c), template, region, worker.ID, cfgJSON, metadataJSON, "pending")+ _, _ = s.store.CreateSandboxSessionWithStatus(ctx, sandboxID, orgID, auth.GetUserID(c), template, region, worker.ID, cfgJSON, metadataJSON, "pending", secretStoreID)if worker.GoldenVersion != "" {_ = s.store.SetSandboxGoldenVersion(ctx, sandboxID, worker.GoldenVersion)}@@ -485,7 +504,7 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg tyTemplate: cfg.Template,Timeout: int32(cfg.Timeout),Envs: cfg.Envs,- NetworkEnabled: cfg.NetworkEnabled,+ NetworkEnabled: cfg.IsNetworkEnabled(),Port: int32(cfg.Port),TemplateRootfsKey: templateRootfsKey,TemplateWorkspaceKey: templateWorkspaceKey,@@ -958,12 +977,20 @@ func (s *Server) migrateSandbox(c echo.Context) error {WorkspaceS3Key: preCopyResp.WorkspaceKey,OverlayMode: true,SourceGoldenVersion: preCopyResp.GoldenVersion,+ // Carry the secrets-proxy session from source → target. Without+ // this the destination has no substitution map and outbound HTTPS+ // from the migrated VM would leak `osb_sealed_xxx` env vars+ // verbatim to upstream services. Empty when no secret store.+ SealedTokens: preCopyResp.SealedTokens,+ EgressAllowlist: preCopyResp.EgressAllowlist,+ TokenHosts: preCopyResp.TokenHosts,+ SealedNames: preCopyResp.SealedNames,})if err != nil {return c.JSON(http.StatusInternalServerError, map[string]string{"error": "prepare target: " + err.Error()})}- log.Printf("migrate %s: target prepared at %s (host port %d)", id, prepResp.IncomingAddr, prepResp.HostPort)+ log.Printf("migrate %s: target prepared at %s (host port %d, secrets=%d)", id, prepResp.IncomingAddr, prepResp.HostPort, len(preCopyResp.SealedTokens))// Step 3: Live migrate from source to targetmigrateCtx, migrateCancel := context.WithTimeout(ctx, 5*time.Minute)@@ -1117,11 +1144,40 @@ func (s *Server) scaleSandbox(c echo.Context) error {}}+ // Scaling lock: refuse if the user has explicitly pinned this sandbox's+ // resources. Same code that the autoscale endpoint and the autoscaler+ // loop use, so SDK consumers can branch on a single error code.+ if s.store != nil {+ if locked, err := s.store.GetScalingLock(c.Request().Context(), id); err == nil && locked {+ return c.JSON(http.StatusForbidden, map[string]any{+ "error": "scaling is locked on this sandbox — unlock via PUT /scaling-lock to allow size changes",+ "code": "scaling_locked",+ })+ }+ }+cpuPercent := vcpus * 100maxMemoryBytes := int64(req.MemoryMB) * 1024 * 1024cpuMaxUsec := int64(cpuPercent) * 1000cpuPeriodUsec := int64(100000)+ // Manual scale disables autoscale. Rationale: a user explicitly setting a+ // size has signalled they want predictability — letting the autoscaler+ // override would surprise them. They can re-enable via PUT /autoscale.+ // Best-effort — failure to disable is logged but doesn't fail the scale.+ // We capture whether it WAS enabled so the response can flag the side-+ // effect to SDK callers (otherwise autoscale silently flips off).+ var autoscaleWasEnabled bool+ if s.store != nil {+ if enabled, _, _, err := s.store.GetSandboxAutoscale(c.Request().Context(), id); err == nil {+ autoscaleWasEnabled = enabled+ }+ if err := s.store.SetSandboxAutoscale(c.Request().Context(), id, false, 0, 0); err != nil {+ log.Printf("scale: failed to disable autoscale on %s after manual scale: %v", id, err)+ }+ }+ c.Set("autoscaleWasEnabled", autoscaleWasEnabled)+if s.workerRegistry != nil {return s.setLimitsRemote(c, id, 0, maxMemoryBytes, cpuMaxUsec, cpuPeriodUsec)}@@ -1264,6 +1320,18 @@ func (s *Server) setLimitsRemote(c echo.Context, sandboxID string, maxPids int32log.Printf("scale-migrate %s: migrated to %s and scaled to %dMB", sandboxID, workerID, requestedMemMB)} else if err != nil {+ // OOM-floor refusal: returned by the worker when the requested limit+ // is below the guest's current working set. This is a "user can fix+ // it" condition (free memory in the guest, then retry) — surface it+ // as 409 Conflict with a structured code so SDK consumers can branch+ // on it without string-matching the wrapped gRPC error.+ if strings.Contains(err.Error(), "oom_floor:") {+ return c.JSON(http.StatusConflict, map[string]any{+ "error": "memory limit below guest working set — would OOM-kill processes",+ "code": "oom_floor",+ "details": err.Error(),+ })+ }return c.JSON(http.StatusInternalServerError, map[string]string{"error": "set limits failed: " + err.Error(),})@@ -1277,14 +1345,21 @@ func (s *Server) setLimitsRemote(c echo.Context, sandboxID string, maxPids int32s.emitEvent("scale", sandboxID, workerID, fmt.Sprintf("scaled to %dMB (migrated=%v)", requestedMemMB, migrated))}- return c.JSON(http.StatusOK, map[string]interface{}{+ resp := map[string]any{"sandboxID": sandboxID,"workerID": workerID,"memoryMB": requestedMemMB,"cpuPercent": int(cpuMaxUsec / 1000),"migrated": migrated,"ok": true,- })+ }+ // Surface the autoscale-was-disabled side-effect when the request came+ // from /scale (scaleSandbox stashes this on the echo context). Quiet+ // when called from /limits (no autoscale toggle there).+ if v := c.Get("autoscaleWasEnabled"); v != nil {+ resp["autoscaleDisabled"] = v.(bool)+ }+ return c.JSON(http.StatusOK, resp)}// findScaleMigrationTargets finds workers with enough memory headroom for a scaled-up sandbox.@@ -1387,6 +1462,11 @@ func (s *Server) migrateForScale(ctx context.Context, sandboxID string, sessionOverlayMode: true,SourceGoldenVersion: preCopyResp.GoldenVersion,TargetMemoryMb: int32(memoryMB),+ // Carry secrets-proxy session from source to target (see PreCopyDrives).+ SealedTokens: preCopyResp.SealedTokens,+ EgressAllowlist: preCopyResp.EgressAllowlist,+ TokenHosts: preCopyResp.TokenHosts,+ SealedNames: preCopyResp.SealedNames,})if err != nil {log.Printf("scale-migrate %s: prepare target failed: %v", sandboxID, err)@@ -1663,13 +1743,52 @@ func (s *Server) wakeSandboxRemote(c echo.Context, sandboxID string, req types.Wreturn c.JSON(http.StatusBadRequest, map[string]string{"error": "sandbox is not hibernated"})}- // Pick ANY worker in the same region+ // Prefer the source worker (where hibernation actually happened) so wake+ // can use the local qcow2 files instead of downloading from S3. Two reasons:+ //+ // 1. Same-worker wake is dramatically faster (~300ms vs. 30+s for a 1GB+ // download+extract).+ // 2. Avoids a wake-vs-upload race: hibernate's S3 upload is async and+ // takes tens of seconds for a 4GB sandbox. A wake routed to a+ // different worker that runs before the upload finishes fails with+ // "blob: object not found" because it tries HEAD before the goroutine+ // finished writing. uploaded_at is the canonical signal — if it's+ // NULL, the source worker is the only safe target.+ //+ // Fall back to least-loaded only when source is gone, draining, or under+ // resource pressure. If upload isn't complete yet, prefer source even at+ // the cost of some imbalance — the alternative is a 500 to the user.region := hibernation.Region- worker, grpcClient, err := s.workerRegistry.GetLeastLoadedWorker(region)- if err != nil {- return c.JSON(http.StatusServiceUnavailable, map[string]string{- "error": "no workers available in region " + region,- })+ var worker *controlplane.WorkerEntry+ var grpcClient pb.SandboxWorkerClient+ uploadComplete := hibernation.UploadedAt != nil+ if session.WorkerID != "" {+ if src := s.workerRegistry.GetWorker(session.WorkerID); src != nil &&+ !src.Draining && src.CPUPct < 90 && src.MemPct < 90 && src.DiskPct < 90 {+ if cli, cerr := s.workerRegistry.GetWorkerClient(session.WorkerID); cerr == nil {+ worker = src+ grpcClient = cli+ log.Printf("wake %s: routing to source worker %s (upload_complete=%v)",+ sandboxID, session.WorkerID, uploadComplete)+ }+ }+ }+ if worker == nil {+ // Source unavailable. Cross-worker wake will need to download from S3,+ // so refuse if upload hasn't completed — better a clear error than a+ // confusing "blob: object not found" once the worker actually tries.+ if !uploadComplete {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{+ "error": "source worker unavailable and hibernation upload not yet complete; retry shortly",+ })+ }+ var lerr error+ worker, grpcClient, lerr = s.workerRegistry.GetLeastLoadedWorker(region)+ if lerr != nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{+ "error": "no workers available in region " + region,+ })+ }}grpcCtx, cancel := context.WithTimeout(c.Request().Context(), 60*time.Second)@@ -1727,6 +1846,103 @@ func (s *Server) wakeSandboxRemote(c echo.Context, sandboxID string, req types.Wreturn c.JSON(http.StatusOK, resp)}+// rebootSandbox triggers a soft, in-place guest restart on a running+// sandbox. The QEMU process, network mapping, and persistent disks all+// stay; only the guest CPU is reset and the kernel reboots. Recovers from+// in-guest wedges (zombie pile-up, OOM-killed agent, runaway processes).+//+// POST /api/sandboxes/:id/reboot+func (s *Server) rebootSandbox(c echo.Context) error {+ id := c.Param("id")++ if s.workerRegistry != nil {+ return s.rebootSandboxRemote(c, id)+ }++ if s.manager == nil {+ return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)+ }++ if err := s.manager.RebootSandbox(c.Request().Context(), id); err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})+ }+ return c.NoContent(http.StatusNoContent)+}++func (s *Server) rebootSandboxRemote(c echo.Context, sandboxID string) error {+ if s.store == nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "database not configured"})+ }+ session, err := s.store.GetSandboxSession(c.Request().Context(), sandboxID)+ if err != nil {+ return c.JSON(http.StatusNotFound, map[string]string{"error": "sandbox not found"})+ }+ client, err := s.workerRegistry.GetWorkerClient(session.WorkerID)+ if err != nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "worker unreachable: " + err.Error()})+ }+ grpcCtx, cancel := context.WithTimeout(c.Request().Context(), 90*time.Second)+ defer cancel()+ if _, err := client.RebootSandbox(grpcCtx, &pb.RebootSandboxRequest{SandboxId: sandboxID}); err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "reboot failed: " + err.Error()})+ }+ s.emitEvent("reboot", sandboxID, session.WorkerID, "rebooted")+ return c.NoContent(http.StatusNoContent)+}++// powerCycleSandbox tears down the QEMU process and cold-boots a fresh VM+// with the existing on-disk drives. Use when the VMM itself is wedged or+// a soft reboot didn't recover. Sandbox keeps its ID, project, secrets,+// and persistent data; gets a new TAP and host port.+//+// POST /api/sandboxes/:id/power-cycle+func (s *Server) powerCycleSandbox(c echo.Context) error {+ id := c.Param("id")++ if s.workerRegistry != nil {+ return s.powerCycleSandboxRemote(c, id)+ }++ if s.manager == nil {+ return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)+ }++ if _, err := s.manager.PowerCycleSandbox(c.Request().Context(), id); err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})+ }+ return c.NoContent(http.StatusNoContent)+}++func (s *Server) powerCycleSandboxRemote(c echo.Context, sandboxID string) error {+ if s.store == nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "database not configured"})+ }+ session, err := s.store.GetSandboxSession(c.Request().Context(), sandboxID)+ if err != nil {+ return c.JSON(http.StatusNotFound, map[string]string{"error": "sandbox not found"})+ }+ client, err := s.workerRegistry.GetWorkerClient(session.WorkerID)+ if err != nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "worker unreachable: " + err.Error()})+ }+ grpcCtx, cancel := context.WithTimeout(c.Request().Context(), 120*time.Second)+ defer cancel()+ if _, err := client.PowerCycleSandbox(grpcCtx, &pb.PowerCycleSandboxRequest{SandboxId: sandboxID}); err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "power-cycle failed: " + err.Error()})+ }++ // Worker re-allocated the TAP/host port. The CP→worker mapping is+ // unchanged so the sandbox API proxy doesn't need refreshing, but the+ // proxy's per-sandbox cache might hold a stale workerURL/JWT — drop it+ // so the next request re-resolves cleanly.+ if s.sandboxAPIProxy != nil {+ s.sandboxAPIProxy.InvalidateRouteCache(sandboxID)+ }++ s.emitEvent("power-cycle", sandboxID, session.WorkerID, "power-cycled")+ return c.NoContent(http.StatusNoContent)+}+// --- Checkpoint handlers ---// createCheckpoint creates a named checkpoint of a running sandbox.@@ -1813,7 +2029,13 @@ func (s *Server) createCheckpoint(c echo.Context) error {}go func() {- grpcCtx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)+ // 20-min budget for the full create+archive+upload chain. Pre-fix+ // this was 5 min — too tight for >3 GB compressed archives under+ // any blob-side contention. Customer hit this on a 7–9 GB sandbox+ // (status processing for ~280 s → failed, no detail). The worker+ // internal upload is bounded at 15 min; the extra 5 min here gives+ // headroom for archive build + worker-side tar + transit.+ grpcCtx, cancel := context.WithTimeout(context.Background(), 20*time.Minute)defer cancel()grpcResp, err := grpcClient.CreateCheckpoint(grpcCtx, &pb.CreateCheckpointRequest{@@ -1828,20 +2050,23 @@ func (s *Server) createCheckpoint(c echo.Context) error {if err != nil {log.Printf("api: async checkpoint %s failed: %v", checkpointID, err)+ // SetCheckpointFailed now persists the reason via the+ // error_msg/failed_at columns added in migration 039.+ // Pre-fix the reason was silently discarded._ = s.store.SetCheckpointFailed(context.Background(), checkpointID, err.Error())return}- // Mark ready immediately — S3 upload continues async inside CreateCheckpoint- // but the checkpoint is locally usable now.- _ = s.store.SetCheckpointReady(context.Background(), checkpointID, grpcResp.RootfsS3Key, grpcResp.WorkspaceS3Key, 0)- log.Printf("api: checkpoint %s ready", checkpointID)+ // Persist the actual archive size from the worker's response.+ // Pre-fix this was hardcoded to 0, leaving size_bytes meaningless.+ _ = s.store.SetCheckpointReady(context.Background(), checkpointID, grpcResp.RootfsS3Key, grpcResp.WorkspaceS3Key, grpcResp.SizeBytes)+ log.Printf("api: checkpoint %s ready (size=%d bytes)", checkpointID, grpcResp.SizeBytes)}()} else if s.manager != nil {go func() {- bgCtx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)+ bgCtx, cancel := context.WithTimeout(context.Background(), 20*time.Minute)defer cancel()- rootfsKey, workspaceKey, err := s.manager.CreateCheckpoint(bgCtx, sandboxID, checkpointID.String(), s.checkpointStore, func() {})+ rootfsKey, workspaceKey, sizeBytes, err := s.manager.CreateCheckpoint(bgCtx, sandboxID, checkpointID.String(), s.checkpointStore, func() {})// Signal sandbox usablepending.err = err@@ -1852,8 +2077,8 @@ func (s *Server) createCheckpoint(c echo.Context) error {_ = s.store.SetCheckpointFailed(context.Background(), checkpointID, err.Error())return}- _ = s.store.SetCheckpointReady(context.Background(), checkpointID, rootfsKey, workspaceKey, 0)- log.Printf("api: checkpoint %s ready", checkpointID)+ _ = s.store.SetCheckpointReady(context.Background(), checkpointID, rootfsKey, workspaceKey, sizeBytes)+ log.Printf("api: checkpoint %s ready (size=%d bytes)", checkpointID, sizeBytes)}()} else {s.pendingCreates.Delete(sandboxID)@@ -1993,15 +2218,19 @@ func (s *Server) restoreCheckpoint(c echo.Context) error {// createFromCheckpoint creates a new sandbox from an existing checkpoint (fork).func (s *Server) createFromCheckpoint(c echo.Context) error {- // Direct route (POST /sandboxes/from-checkpoint/:checkpointId): only the- // envs override is currently supported on the fork path; everything else- // is inherited from the checkpoint's stored config.+ // Direct route (POST /sandboxes/from-checkpoint/:checkpointId): the+ // envs / secretStore / metadata fields are supported on the fork path;+ // everything else is inherited from the checkpoint's stored config.+ // Metadata is merged onto the checkpoint's persisted metadata+ // (caller wins) so callers can stamp identifiers like agent_id without+ // losing whatever the snapshot author originally set.var body struct {Envs map[string]string `json:"envs"`SecretStore string `json:"secretStore"`+ Metadata map[string]string `json:"metadata"`}_ = c.Bind(&body)- result, httpStatus, err := s.createFromCheckpointCore(c, body.Envs, body.SecretStore)+ result, httpStatus, err := s.createFromCheckpointCore(c, body.Envs, body.SecretStore, body.Metadata)if err != nil {return c.JSON(httpStatus, map[string]string{"error": err.Error()})}@@ -2022,7 +2251,12 @@ func (s *Server) createFromCheckpoint(c echo.Context) error {//// userEnvs (may be nil) overrides the envs from the checkpoint's stored config.// User keys win over keys re-resolved from the secret store.-func (s *Server) createFromCheckpointCore(c echo.Context, userEnvs map[string]string, userSecretStore string) (map[string]interface{}, int, error) {+//+// userMetadata (may be nil) is merged into the checkpoint's persisted+// metadata before the sandbox session row is recorded — so callers can+// stamp request-time identifiers (e.g. agent_id) without losing whatever+// the snapshot author baked in.+func (s *Server) createFromCheckpointCore(c echo.Context, userEnvs map[string]string, userSecretStore string, userMetadata map[string]string) (map[string]interface{}, int, error) {checkpointIDStr := c.Param("checkpointId")ctx := c.Request().Context()@@ -2035,6 +2269,22 @@ func (s *Server) createFromCheckpointCore(c echo.Context, userEnvs map[string]streturn nil, http.StatusUnauthorized, fmt.Errorf("org context required")}+ // Enforce per-org concurrency limit on the fork path, mirroring the gate+ // in the direct-create path at the top of CreateSandbox (around line 50).+ // Without this, callers using POST /api/sandboxes/from-checkpoint/<id>+ // (i.e. `oc checkpoint spawn` and equivalent SDK calls) can fork unbounded+ // sandboxes past their plan's max_concurrent_sandboxes — every other+ // per-plan gate (free-tier credits, machine size, disk size) is also+ // missing on this path, but concurrency is the load-bearing one because+ // it directly drives runaway billing.+ //+ // Fail-open on DB errors to match the existing direct-create behavior.+ if org, gerr := s.store.GetOrg(ctx, orgID); gerr == nil {+ if count, cerr := s.store.CountActiveSandboxes(ctx, orgID); cerr == nil && count >= org.MaxConcurrentSandboxes {+ return nil, http.StatusTooManyRequests, fmt.Errorf("concurrent sandbox limit reached")+ }+ }+checkpointID, err := uuid.Parse(checkpointIDStr)if err != nil {return nil, http.StatusBadRequest, fmt.Errorf("invalid checkpoint ID")@@ -2089,6 +2339,10 @@ func (s *Server) createFromCheckpointCore(c echo.Context, userEnvs map[string]st// Parse the original sandbox config to reuse settingsvar originalCfg types.SandboxConfig_ = json.Unmarshal(cp.SandboxConfig, &originalCfg)+ // Older checkpoints predate the networkEnabled default-to-true normalization+ // and persisted no value (or false from the old non-pointer bool). Forks+ // should still come up with networking on.+ originalCfg.EnsureNetworkEnabledDefault()// Secret store resolution — supports layering:// Resolve stores in order: BaseSecretStore → SecretStore → user's store.@@ -2115,13 +2369,23 @@ func (s *Server) createFromCheckpointCore(c echo.Context, userEnvs map[string]stuniqueStores = append(uniqueStores, name)}}+ // secretStoreID tracks the resolved store of the LAST (winning) layer in+ // uniqueStores — that's the one we want recorded on the sandbox row, since+ // later layers shadow earlier ones for env collisions. Plumbed back to+ // CreateSandboxSessionWithStatus below so secret_store_id is populated for+ // the refresh fanout.+ var secretStoreID *uuid.UUIDif len(uniqueStores) > 0 {var allEgress []stringfor _, storeName := range uniqueStores {originalCfg.SecretStore = storeName- if err := s.resolveSecretStoreInto(ctx, orgID, &originalCfg); err != nil {+ storeID, err := s.resolveSecretStoreInto(ctx, orgID, &originalCfg)+ if err != nil {return nil, http.StatusBadRequest, err}+ if storeID != nil {+ secretStoreID = storeID+ }allEgress = append(allEgress, originalCfg.EgressAllowlist...)}// Deduplicate egress@@ -2214,6 +2478,30 @@ func (s *Server) createFromCheckpointCore(c echo.Context, userEnvs map[string]st}}+ // Pre-write the sandbox_sessions row with status='pending' so the worker+ // can resolve org_id during CreateSandbox — the worker's+ // recordInitialScaleEvent looks up sandbox→org via this row. Without the+ // pre-write, fork-path scale events are silently skipped and both free-tier+ // credit deduction and pro-tier Stripe metering miss the usage. Mirrors+ // the from-scratch path's CreateSandboxSessionWithStatus(..., "pending")+ // call. Status flips to 'running' on success / 'failed' on error below.+ template := originalCfg.Template+ if template == "" {+ template = "default"+ }+ mergedMeta := map[string]string{}+ for k, v := range originalCfg.Metadata {+ mergedMeta[k] = v+ }+ for k, v := range userMetadata {+ mergedMeta[k] = v+ }+ if s.store != nil {+ cfgJSON, _ := json.Marshal(cfgForPersistence(originalCfg))+ metadataJSON, _ := json.Marshal(mergedMeta)+ _, _ = s.store.CreateSandboxSessionWithStatus(ctx, sandboxID, orgID, auth.GetUserID(c), template, region, workerID, cfgJSON, metadataJSON, "pending", secretStoreID)+ }+// Boot VM synchronously so the worker's in-memory sandbox map is populated// before we respond or record the session. Previously this ran in a goroutine// with the session row written first as status=running, which allowed@@ -2231,7 +2519,7 @@ func (s *Server) createFromCheckpointCore(c echo.Context, userEnvs map[string]stEnvs: originalCfg.Envs,MemoryMb: int32(originalCfg.MemoryMB),CpuCount: int32(originalCfg.CpuCount),- NetworkEnabled: originalCfg.NetworkEnabled,+ NetworkEnabled: originalCfg.IsNetworkEnabled(),Port: int32(originalCfg.Port),TemplateRootfsKey: *cp.RootfsS3Key,TemplateWorkspaceKey: *cp.WorkspaceS3Key,@@ -2268,21 +2556,18 @@ func (s *Server) createFromCheckpointCore(c echo.Context, userEnvs map[string]st}if createErr != nil {+ if s.store != nil {+ errMsg := createErr.Error()+ _ = s.store.UpdateSandboxSessionStatus(ctx, sandboxID, "failed", &errMsg)+ }s.pendingCreates.Delete(sandboxID)log.Printf("api: fork %s failed: %v", sandboxID, createErr)return nil, http.StatusInternalServerError, fmt.Errorf("fork from checkpoint: %w", createErr)}- // Record session only after the worker has the VM registered so the session- // row never points at a worker that does not yet own the VM.+ // Flip the pre-written session row to 'running' and stamp lineage fields.if s.store != nil {- template := originalCfg.Template- if template == "" {- template = "default"- }- cfgJSON, _ := json.Marshal(cfgForPersistence(originalCfg))- metadataJSON, _ := json.Marshal(originalCfg.Metadata)- _, _ = s.store.CreateSandboxSession(ctx, sandboxID, orgID, auth.GetUserID(c), template, region, workerID, cfgJSON, metadataJSON)+ _ = s.store.UpdateSandboxSessionStatus(ctx, sandboxID, "running", nil)// Set golden version from worker heartbeatif s.workerRegistry != nil {if w := s.workerRegistry.GetWorker(workerID); w != nil && w.GoldenVersion != "" {diff --git a/internal/api/sandbox_allowed_hosts.go b/internal/api/sandbox_allowed_hosts.gonew file mode 100644index 00000000..529286b8--- /dev/null+++ b/internal/api/sandbox_allowed_hosts.go@@ -0,0 +1,135 @@+package api++import (+ "context"+ "net/http"++ "github.com/labstack/echo/v4"+ "github.com/opensandbox/opensandbox/internal/auth"+ "github.com/opensandbox/opensandbox/internal/db"+)++// AllowedHostsResponse is the shape returned by GET /api/sandboxes/:id/allowed-hosts.+//+// EgressAllowlist + PerSecretAllowedHosts represent the runtime view — the+// union of every layered store's allowlist, exactly as the secrets proxy+// enforces it. Most sandboxes have a single store and the union is trivially+// that one store's allowlist; forks that layer an additional store on top of+// an inherited one have BOTH stores' allowlists merged here.+//+// SecretStoreName is the "primary" (last/winning) store on the sandbox row —+// the one whose secrets shadow the base store on env-name collisions.+// BaseSecretStoreName is the inherited parent store from the fork chain;+// populated only when there's actual layering. Both empty = sandbox created+// without a secretStore (no per-store egress restriction enforced).+type AllowedHostsResponse struct {+ SandboxID string `json:"sandboxID"`+ SecretStoreName string `json:"secretStore,omitempty"`+ BaseSecretStoreName string `json:"baseSecretStore,omitempty"`+ EgressAllowlist []string `json:"egressAllowlist"`+ PerSecretAllowedHosts map[string][]string `json:"perSecretAllowedHosts"`+}++// getSandboxAllowedHosts handles GET /api/sandboxes/:id/allowed-hosts.+//+// Returns the egress allowlist + per-secret allowed hosts the sandbox's+// secrets proxy enforces. Useful for debugging "why is my outbound HTTP call+// being blocked" without having to cross-reference store config separately.+//+// For forks that layered a new secretStore on top of an inherited one, the+// response merges both stores' allowlists — the runtime proxy enforces the+// union, so this matches actual behavior. The primary store's secrets shadow+// the base store on env-name collisions.+//+// Auth: same as other /api/sandboxes/:id routes — PGAPIKeyMiddleware sets+// orgID on the context. Sandbox lookup is org-scoped to prevent cross-tenant+// reads via guessed sandbox IDs.+func (s *Server) getSandboxAllowedHosts(c echo.Context) error {+ if s.store == nil {+ return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)+ }++ orgID, hasOrg := auth.GetOrgID(c)+ if !hasOrg {+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "auth required"})+ }++ sandboxID := c.Param("id")+ ctx := c.Request().Context()++ primaryID, baseStoreName, err := s.store.GetSandboxStoreRefs(ctx, orgID, sandboxID)+ if err != nil {+ return c.JSON(http.StatusNotFound, map[string]string{"error": "sandbox not found"})+ }++ // Sandbox has neither a primary store nor an inherited base. Return an+ // empty (well-formed) response so callers always see the same shape.+ if primaryID == nil && baseStoreName == "" {+ return c.JSON(http.StatusOK, AllowedHostsResponse{+ SandboxID: sandboxID,+ EgressAllowlist: []string{},+ PerSecretAllowedHosts: map[string][]string{},+ })+ }++ resp := AllowedHostsResponse{+ SandboxID: sandboxID,+ EgressAllowlist: []string{},+ PerSecretAllowedHosts: map[string][]string{},+ }++ // Fetch base store first so primary's per-secret entries can shadow on+ // name collision (matches the runtime proxy: later layer wins for envs).+ if baseStoreName != "" {+ base, err := s.store.GetSecretStoreByName(ctx, orgID, baseStoreName)+ if err == nil {+ resp.BaseSecretStoreName = base.Name+ mergeStoreInto(ctx, s.store, base, &resp)+ }+ // Base store missing (deleted under us) is treated as a soft no-op+ // rather than 500 — proxy already snapshotted whatever it needs.+ }++ if primaryID != nil {+ primary, err := s.store.GetSecretStore(ctx, orgID, *primaryID)+ if err == nil {+ resp.SecretStoreName = primary.Name+ mergeStoreInto(ctx, s.store, primary, &resp)+ }+ }++ return c.JSON(http.StatusOK, resp)+}++// mergeStoreInto folds one store's allowlist + per-secret restrictions into+// the running response. Egress hosts dedupe (preserving insertion order so+// base-store hosts appear before primary's additions). Per-secret entries+// with empty AllowedHosts are skipped — empty means "inherits store+// allowlist," and surfacing them as [] would falsely imply "no hosts allowed+// for this secret." Per-secret name collisions are last-write-wins, so the+// primary store (called second) shadows the base.+func mergeStoreInto(ctx context.Context, store *db.Store, ss *db.SecretStore, resp *AllowedHostsResponse) {+ // Build a set view of existing egress hosts so we can dedupe in O(1).+ existing := make(map[string]bool, len(resp.EgressAllowlist))+ for _, h := range resp.EgressAllowlist {+ existing[h] = true+ }+ for _, h := range ss.EgressAllowlist {+ if !existing[h] {+ existing[h] = true+ resp.EgressAllowlist = append(resp.EgressAllowlist, h)+ }+ }++ entries, err := store.ListSecretEntries(ctx, ss.ID)+ if err != nil {+ return+ }+ for _, e := range entries {+ if len(e.AllowedHosts) == 0 {+ continue+ }+ resp.PerSecretAllowedHosts[e.Name] = e.AllowedHosts+ }+}+diff --git a/internal/api/sandbox_autoscale.go b/internal/api/sandbox_autoscale.gonew file mode 100644index 00000000..6a56b14e--- /dev/null+++ b/internal/api/sandbox_autoscale.go@@ -0,0 +1,189 @@+package api++import (+ "context"+ "fmt"+ "net/http"+ "time"++ "github.com/labstack/echo/v4"+ "github.com/opensandbox/opensandbox/internal/auth"+ "github.com/opensandbox/opensandbox/pkg/types"+ pbw "github.com/opensandbox/opensandbox/proto/worker"+)++// PUT /api/sandboxes/:id/autoscale+//+// Enables/disables per-sandbox autoscaler. Body:+//+// {+// "enabled": true,+// "minMemoryMB": 1024,+// "maxMemoryMB": 16384+// }+//+// minMemoryMB and maxMemoryMB must be allowed memory tiers (validated via+// types.ValidateMemoryMB). vCPU follows the tier table — there's no+// independent CPU bound. If `enabled=false`, min/max are cleared.+//+// Plan-level cap: an org's plan max_memory_gb (in orgs table) is the hard+// upper bound regardless of what the user requests. Free tier is capped at+// 4 GB just like the manual scale endpoint.+func (s *Server) setAutoscale(c echo.Context) error {+ sandboxID := c.Param("id")+ if s.store == nil {+ return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)+ }++ var req struct {+ Enabled bool `json:"enabled"`+ MinMemoryMB int `json:"minMemoryMB"`+ MaxMemoryMB int `json:"maxMemoryMB"`+ }+ if err := c.Bind(&req); err != nil {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid body"})+ }++ if req.Enabled {+ // Refuse if the sandbox is scaling-locked. The lock auto-disables+ // autoscale on toggle; refusing here prevents a user from+ // re-enabling it while the lock is still on (which would be a+ // confusing two-state mismatch).+ if locked, err := s.store.GetScalingLock(c.Request().Context(), sandboxID); err == nil && locked {+ return c.JSON(http.StatusForbidden, map[string]any{+ "error": "scaling is locked on this sandbox — unlock via PUT /scaling-lock to enable autoscale",+ "code": "scaling_locked",+ })+ }+ if _, err := types.ValidateMemoryMB(req.MinMemoryMB); err != nil {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "minMemoryMB: " + err.Error()})+ }+ if _, err := types.ValidateMemoryMB(req.MaxMemoryMB); err != nil {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "maxMemoryMB: " + err.Error()})+ }+ if req.MinMemoryMB > req.MaxMemoryMB {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "minMemoryMB must be ≤ maxMemoryMB"})+ }+ // Plan cap: free tier is bounded at 4 GB just like manual /scale.+ // Without this a free-tier user could PUT max=16GB and the+ // autoscaler would obediently scale them past their plan. Mirror the+ // same check we apply in scaleSandbox so the two paths can't diverge.+ if orgID, hasOrg := auth.GetOrgID(c); hasOrg {+ if org, err := s.store.GetOrg(c.Request().Context(), orgID); err == nil && org.Plan == "free" {+ if req.MaxMemoryMB > 4096 {+ return c.JSON(http.StatusPaymentRequired, map[string]string{+ "error": "free plan caps autoscale at 4096 MB — upgrade to pro for larger instances",+ })+ }+ }+ }+ }++ if err := s.store.SetSandboxAutoscale(c.Request().Context(), sandboxID, req.Enabled, req.MinMemoryMB, req.MaxMemoryMB); err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})+ }+ return c.JSON(http.StatusOK, map[string]any{+ "sandboxID": sandboxID,+ "enabled": req.Enabled,+ "minMemoryMB": req.MinMemoryMB,+ "maxMemoryMB": req.MaxMemoryMB,+ })+}++// GET /api/sandboxes/:id/autoscale+func (s *Server) getAutoscale(c echo.Context) error {+ sandboxID := c.Param("id")+ if s.store == nil {+ return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)+ }+ enabled, minMB, maxMB, err := s.store.GetSandboxAutoscale(c.Request().Context(), sandboxID)+ if err != nil {+ return c.JSON(http.StatusNotFound, map[string]string{"error": "sandbox not found"})+ }+ return c.JSON(http.StatusOK, map[string]any{+ "sandboxID": sandboxID,+ "enabled": enabled,+ "minMemoryMB": minMB,+ "maxMemoryMB": maxMB,+ })+}++// AutoscalerSetter implements controlplane.AutoscalerScaleSetter by routing+// the scale request through the same SetSandboxLimits gRPC call that the+// manual /scale endpoint uses. We don't go through the HTTP layer — the+// autoscaler runs in-process and we already have direct access to the+// worker registry.+//+// CPU follows memory per types.AllowedResourceTiers (e.g., 8 GB ⇒ 4 vCPU).+type AutoscalerSetter struct {+ server *Server+}++// NewAutoscalerSetter wires the existing Server's worker registry into the+// autoscaler's scale-applier interface.+func NewAutoscalerSetter(server *Server) *AutoscalerSetter {+ return &AutoscalerSetter{server: server}+}++// SetSandboxMemoryMB applies a tier-aligned memory size to a sandbox. The+// autoscaler should only ever pass values that are already allowed tiers,+// but we re-validate here as defense in depth — if a future caller passes+// 6 GB we'd silently corrupt the worker's expected scaling table.+//+// On success we also emit an admin event so the operator dashboard sees+// every autoscaler-driven scale event ("why did sandbox X grow last+// night?" — answer is now visible without grepping logs).+func (a *AutoscalerSetter) SetSandboxMemoryMB(ctx context.Context, sandboxID string, fromMB, toMB int) error {+ memoryMB := toMB+ vcpus, err := types.ValidateMemoryMB(memoryMB)+ if err != nil {+ return fmt.Errorf("invalid memoryMB %d: %w", memoryMB, err)+ }+ if a.server.workerRegistry == nil || a.server.store == nil {+ return fmt.Errorf("autoscaler: server not configured for remote worker calls")+ }++ session, err := a.server.store.GetSandboxSession(ctx, sandboxID)+ if err != nil {+ return fmt.Errorf("get session: %w", err)+ }+ if session.Status != "running" {+ // Don't try to scale stopped/hibernated sandboxes — the autoscaler+ // shouldn't have picked them, but better to no-op cleanly than fail.+ return nil+ }++ // Defense in depth: re-check the org plan cap here in case the autoscale+ // row was set before a downgrade or the cap was raised by another path.+ // The PUT /autoscale handler already enforces this; this is the second+ // gate so an obsolete row can't keep scaling past plan limits.+ if org, err := a.server.store.GetOrg(ctx, session.OrgID); err == nil && org.Plan == "free" && memoryMB > 4096 {+ return fmt.Errorf("plan cap: free plan limited to 4096 MB, refusing autoscale to %d", memoryMB)+ }++ client, err := a.server.workerRegistry.GetWorkerClient(session.WorkerID)+ if err != nil {+ return fmt.Errorf("get worker client: %w", err)+ }++ rpcCtx, cancel := context.WithTimeout(ctx, 30*time.Second)+ defer cancel()++ cpuPercent := vcpus * 100+ _, err = client.SetSandboxLimits(rpcCtx, &pbw.SetSandboxLimitsRequest{+ SandboxId: sandboxID,+ MaxPids: 0,+ MaxMemoryBytes: int64(memoryMB) * 1024 * 1024,+ CpuMaxUsec: int64(cpuPercent) * 1000,+ CpuPeriodUsec: 100000,+ })+ if err != nil {+ return err+ }+ // Audit event — visible in /admin/events SSE + /admin/events/history.+ if a.server.adminEvents != nil {+ a.server.adminEvents.Publish("autoscale", sandboxID, session.WorkerID,+ fmt.Sprintf("autoscaler: %dMB → %dMB", fromMB, toMB))+ }+ return nil+}diff --git a/internal/api/sandbox_logs.go b/internal/api/sandbox_logs.gonew file mode 100644index 00000000..149ec6a9--- /dev/null+++ b/internal/api/sandbox_logs.go@@ -0,0 +1,506 @@+package api++import (+ "bytes"+ "context"+ "encoding/json"+ "fmt"+ "io"+ "log"+ "net/http"+ "net/url"+ "strconv"+ "strings"+ "time"++ "github.com/labstack/echo/v4"++ "github.com/opensandbox/opensandbox/internal/auth"+)++// allowedSources is the closed set of source values a client may filter+// on. Anything else gets a 400 — never fed into the query.+var allowedSources = map[string]struct{}{+ "var_log": {},+ "exec_stdout": {},+ "exec_stderr": {},+ "agent": {},+}++// WARNING: Axiom's /v1/datasets/<dataset>/query endpoint silently+// ignores body it doesn't recognize — including AND-wrapped filter+// trees. Empirically, `{"filter":{"op":"and","filters":[{...}]}}`+// returns the unfiltered dataset (full leak); only a FLAT predicate+// `{"filter":{"op":"==","field":"sandbox_id","value":"..."}}` actually+// narrows. So toFilter() returns a single flat predicate on sandbox_id;+// secondary filters (text search, source list) are applied client-side+// in applyClientFilters after the query returns.+//+// The Filters slice is kept on the type for potential future+// composition (e.g. if Axiom adds support, or if we move to /v1/datasets/_apl)+// but is unset in the current shape.+type queryFilter struct {+ Op string `json:"op"`+ Field string `json:"field,omitempty"`+ Value any `json:"value,omitempty"`+ Filters []queryFilter `json:"filters,omitempty"`+}++type queryOrderField struct {+ Field string `json:"field"`+ Desc bool `json:"desc,omitempty"`+}++type queryRequest struct {+ StartTime string `json:"startTime"`+ EndTime string `json:"endTime"`+ Filter queryFilter `json:"filter"`+ Limit int `json:"limit,omitempty"`+ Order []queryOrderField `json:"order,omitempty"`+}++// getSandboxLogs streams sandbox session logs as Server-Sent Events.+//+// Flow:+//+// 1. Auth check via existing dashboard middleware (caller has an org).+// 2. Sandbox-ownership check via GetSandboxSessionInOrg — refuses if+// the caller's org doesn't own this sandbox.+// 3. Initial historical batch: APL with sandbox_id == :id + the+// caller's filters, sort asc, limit. Emit one SSE event per row.+// 4. If tail=true (default), poll Axiom every 1s with a moving+// `_time > last_seen` cursor; emit deltas. Send `: keepalive\n\n`+// every 15s if nothing new arrived to keep proxies happy.+// 5. Stream ends when the client disconnects or the request context+// is otherwise cancelled.+//+// The query token is held server-side and never reaches the browser —+// this whole endpoint exists to keep that invariant clean.+//+// Query params:+//+// tail true|false (default true)+// since RFC3339 (default sandbox.StartedAt)+// until RFC3339 (default now; ignored when tail=true)+// q free-text search (escaped, "where line contains")+// source comma-separated subset of allowedSources+// limit int, default 1000, max 10000 (historical batch only)+func (s *Server) getSandboxLogs(c echo.Context) error {+ if s.axiomQueryToken == "" || s.axiomDataset == "" {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{+ "error": "sandbox session logs are not configured on this deployment",+ })+ }++ orgUUID, hasOrg := auth.GetOrgID(c)+ if !hasOrg {+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "unauthorized"})+ }++ // Both routes mount this handler:+ // /api/sandboxes/:id/logs (SDK/X-API-Key)+ // /api/dashboard/sessions/:sandboxId/logs (browser/cookie)+ // Try both names — Echo will only set whichever is in the URL pattern.+ sandboxID := c.Param("sandboxId")+ if sandboxID == "" {+ sandboxID = c.Param("id")+ }+ if sandboxID == "" {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "missing sandbox id"})+ }++ // Authorization: the caller's org must own this sandbox. Returns+ // 404 (not 403) on mismatch to avoid leaking sandbox existence+ // across orgs — same contract as the rest of /api/sandboxes/:id/*.+ ctx := c.Request().Context()+ if s.store == nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{+ "error": "sandbox session logs require a database",+ })+ }+ session, err := s.store.GetSandboxSessionInOrg(ctx, orgUUID, sandboxID)+ if err != nil || session == nil {+ return c.JSON(http.StatusNotFound, map[string]string{"error": "sandbox not found"})+ }++ q, err := parseLogQuery(sandboxID, session.StartedAt, c.QueryParams())+ if err != nil {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()})+ }+ // Non-running sandboxes (stopped / error / hibernated): no new events+ // will arrive post-stop, so tail mode is wasted polling. Cap the window+ // at stoppedAt+grace too — the shipper finishes flushing within a few+ // seconds of process exit; 30s covers ingest latency comfortably.+ q = applySessionState(q, session.Status, session.StoppedAt)++ // SSE headers + immediate flush so the browser knows the stream is open.+ c.Response().Header().Set("Content-Type", "text/event-stream")+ c.Response().Header().Set("Cache-Control", "no-cache")+ c.Response().Header().Set("Connection", "keep-alive")+ c.Response().Header().Set("X-Accel-Buffering", "no") // disable nginx buffering+ c.Response().WriteHeader(http.StatusOK)+ c.Response().Flush()++ // Initial historical batch.+ histStart, histEnd := q.timeWindow(false)+ rows, err := s.queryAxiom(ctx, q.toRequest(histStart, histEnd, false))+ if err != nil {+ log.Printf("api: sandbox %s logs: initial query failed: %v", sandboxID, err)+ writeSSEComment(c.Response(), "initial query failed")+ return nil+ }+ rows = applyClientFilters(rows, q)+ for _, ev := range rows {+ writeSSEEvent(c.Response(), ev)+ }+ c.Response().Flush()++ if !q.tail {+ return nil+ }++ // If the sandbox is not running, no new events will arrive — skip+ // the Axiom poll loop entirely. But keep the SSE connection open+ // with keepalive comments so the browser EventSource doesn't+ // interpret a server-side close as a disconnect and auto-reconnect+ // (which would re-fetch the historical batch and visibly duplicate+ // events: see the 3× duplication report after #243).+ if session.Status != "running" {+ keepalive := time.NewTicker(15 * time.Second)+ defer keepalive.Stop()+ for {+ select {+ case <-ctx.Done():+ return nil+ case <-keepalive.C:+ writeSSEComment(c.Response(), "keepalive")+ c.Response().Flush()+ }+ }+ }++ // Live tail. Cursor starts at the last historical event's _time.+ // Tail polls strictly require `ev.Time.After(cursor)`, so events+ // at exactly the cursor are skipped — no double-emit of historical+ // rows.+ //+ // Tradeoff: events ingested after the historical query window+ // closed but with _time falling before the historical batch's+ // last event (out-of-order ingest, e.g. network jitter on the+ // shipper) are missed. Earlier we tried subtracting a 1s overlap+ // to catch those, but Axiom returns events with stable _time so+ // the overlap re-fetched events already emitted in the+ // historical batch — visible duplicates in the UI. Until we add+ // a server-side seen-set, no overlap.+ var cursor time.Time+ if len(rows) > 0 {+ cursor = rows[len(rows)-1].Time+ } else {+ cursor = q.since+ }++ tick := time.NewTicker(1 * time.Second)+ defer tick.Stop()+ keepalive := time.NewTicker(15 * time.Second)+ defer keepalive.Stop()++ for {+ select {+ case <-ctx.Done():+ return nil+ case <-tick.C:+ tailQ := q+ tailQ.since = cursor+ tailQ.until = time.Time{} // open-ended+ tailStart, tailEnd := tailQ.timeWindow(true)+ newRows, err := s.queryAxiom(ctx, tailQ.toRequest(tailStart, tailEnd, true))+ if err != nil {+ // Don't kill the stream on a single failed poll — log+ // and try again next tick. Persistent failures will+ // show as a stalled stream which the UI can detect.+ log.Printf("api: sandbox %s logs: tail poll failed: %v", sandboxID, err)+ continue+ }+ newRows = applyClientFilters(newRows, tailQ)+ for _, ev := range newRows {+ if !ev.Time.After(cursor) {+ continue+ }+ writeSSEEvent(c.Response(), ev)+ cursor = ev.Time+ }+ if len(newRows) > 0 {+ c.Response().Flush()+ }+ case <-keepalive.C:+ writeSSEComment(c.Response(), "keepalive")+ c.Response().Flush()+ }+ }+}++// logQuery is the validated form of incoming query params, ready to+// render into APL.+type logQuery struct {+ sandboxID string+ since time.Time+ until time.Time+ text string // already-escaped+ sources []string // already-validated against allowedSources+ limit int+ tail bool+}++// applySessionState narrows a parsed query based on the sandbox's+// lifecycle. For stopped/error/hibernated sandboxes:+// - until is capped at stoppedAt + 30s grace (the in-VM shipper+// finishes flushing within a few seconds of process exit; 30s+// covers ingest latency comfortably)+//+// q.tail is preserved — it reflects the client's explicit intent+// (URL ?tail=false / CLI --no-tail). The handler reads session.Status+// separately to decide whether to actually poll Axiom; for non-running+// sandboxes it holds the SSE connection open with keepalives instead+// of closing, so the browser EventSource doesn't auto-reconnect and+// re-fetch the historical batch (which visibly duplicated events).+//+// Pure function (no DB dep) so the lifecycle behaviour is unit-testable.+func applySessionState(q logQuery, status string, stoppedAt *time.Time) logQuery {+ if status == "running" {+ return q+ }+ if stoppedAt != nil {+ bound := stoppedAt.Add(30 * time.Second)+ if q.until.IsZero() || q.until.After(bound) {+ q.until = bound+ }+ }+ return q+}++func parseLogQuery(sandboxID string, sandboxStarted time.Time, qs url.Values) (logQuery, error) {+ q := logQuery{+ sandboxID: sandboxID,+ since: sandboxStarted,+ limit: 1000,+ tail: true,+ }++ if v := qs.Get("tail"); v != "" {+ b, err := strconv.ParseBool(v)+ if err != nil {+ return q, fmt.Errorf("tail must be true or false")+ }+ q.tail = b+ }++ if v := qs.Get("since"); v != "" {+ t, err := time.Parse(time.RFC3339, v)+ if err != nil {+ return q, fmt.Errorf("since must be RFC3339")+ }+ q.since = t+ }++ if v := qs.Get("until"); v != "" {+ t, err := time.Parse(time.RFC3339, v)+ if err != nil {+ return q, fmt.Errorf("until must be RFC3339")+ }+ q.until = t+ }++ if v := qs.Get("limit"); v != "" {+ n, err := strconv.Atoi(v)+ if err != nil || n <= 0 {+ return q, fmt.Errorf("limit must be a positive integer")+ }+ if n > 10000 {+ n = 10000+ }+ q.limit = n+ }++ if v := qs.Get("q"); v != "" {+ // Defense in depth: reject control chars; Axiom's `contains`+ // operator takes the value as a JSON string so quote escaping+ // isn't needed.+ if strings.ContainsAny(v, "\r\n\x00") {+ return q, fmt.Errorf("q must not contain control characters")+ }+ q.text = v+ }++ if v := qs.Get("source"); v != "" {+ for _, src := range strings.Split(v, ",") {+ src = strings.TrimSpace(src)+ if src == "" {+ continue+ }+ if _, ok := allowedSources[src]; !ok {+ return q, fmt.Errorf("source %q not allowed", src)+ }+ q.sources = append(q.sources, src)+ }+ }++ return q, nil+}++// timeWindow returns (startTime, endTime) suitable for Axiom's APL+// API body fields. Axiom requires them; we send them separately and+// also embed `_time >=` filters in the APL so the query plan is+// equivalent regardless of which the engine prefers.+//+// Historical: since..until (until defaults to now if unset).+// Tail: since..now (no upper bound logically; Axiom needs a value).+func (q logQuery) timeWindow(tail bool) (time.Time, time.Time) {+ end := q.until+ if tail || end.IsZero() {+ end = time.Now().UTC().Add(1 * time.Minute) // small skew tolerance+ }+ return q.since, end+}++// toFilter returns a FLAT `sandbox_id == q.sandboxID` predicate. Do not+// wrap it in {op:"and", filters:[...]} — Axiom's per-dataset /query+// endpoint silently drops AND-wrapped filters and returns the full+// dataset (cross-tenant leak). The regression test in+// sandbox_logs_test.go pins the flat shape.+//+// Secondary predicates (text search via `q`, source list via `source`)+// are applied client-side in applyClientFilters after the query+// returns — Axiom doesn't compose them in the per-dataset filter shape.+func (q logQuery) toFilter() queryFilter {+ return queryFilter{Op: "==", Field: "sandbox_id", Value: q.sandboxID}+}++// applyClientFilters narrows a row set by predicates Axiom did not apply+// server-side (text contains, source list). The sandbox_id predicate is+// always applied by Axiom via toFilter; this function is purely UX —+// it must NOT be relied on for tenant isolation.+func applyClientFilters(rows []logEvent, q logQuery) []logEvent {+ if q.text == "" && len(q.sources) == 0 {+ return rows+ }+ var sourceSet map[string]struct{}+ if len(q.sources) > 0 {+ sourceSet = make(map[string]struct{}, len(q.sources))+ for _, s := range q.sources {+ sourceSet[s] = struct{}{}+ }+ }+ out := rows[:0]+ for _, ev := range rows {+ if q.text != "" && !strings.Contains(ev.Line, q.text) {+ continue+ }+ if sourceSet != nil {+ if _, ok := sourceSet[ev.Source]; !ok {+ continue+ }+ }+ out = append(out, ev)+ }+ return out+}++// toRequest: time range goes in startTime/endTime (server-side bound);+// only the structural predicate goes in `filter`. Tail variant omits+// Limit so every poll surfaces every new row since the cursor.+func (q logQuery) toRequest(startTime, endTime time.Time, tail bool) queryRequest {+ req := queryRequest{+ StartTime: startTime.UTC().Format(time.RFC3339Nano),+ EndTime: endTime.UTC().Format(time.RFC3339Nano),+ Filter: q.toFilter(),+ Order: []queryOrderField{{Field: "_time"}},+ }+ if !tail {+ req.Limit = q.limit+ }+ return req+}++// logEvent is the on-the-wire shape we re-emit to SSE clients. Mirrors+// the agent-side schema but only includes fields the UI needs to+// render a row. Unknown extra fields from Axiom are tolerated.+type logEvent struct {+ Time time.Time `json:"_time"`+ Source string `json:"source"`+ Line string `json:"line"`+ SandboxID string `json:"sandbox_id,omitempty"`+ Path string `json:"path,omitempty"`+ ExecID string `json:"exec_id,omitempty"`+ Command string `json:"command,omitempty"`+ Argv []string `json:"argv,omitempty"`+ ExitCode *int `json:"exit_code,omitempty"`+}++// queryAxiom POSTs a filter-style query and parses the response.+//+// Endpoint: /v1/datasets/<dataset>/query. Response shape:+//+// { "matches": [ { "_time": "...", "data": {<event fields>} }, ... ] }+func (s *Server) queryAxiom(ctx context.Context, qreq queryRequest) ([]logEvent, error) {+ body, _ := json.Marshal(qreq)+ req, err := http.NewRequestWithContext(ctx, "POST",+ fmt.Sprintf("https://api.axiom.co/v1/datasets/%s/query", url.PathEscape(s.axiomDataset)),+ bytes.NewReader(body))+ if err != nil {+ return nil, err+ }+ req.Header.Set("Authorization", "Bearer "+s.axiomQueryToken)+ req.Header.Set("Content-Type", "application/json")++ httpClient := &http.Client{Timeout: 15 * time.Second}+ resp, err := httpClient.Do(req)+ if err != nil {+ return nil, err+ }+ defer resp.Body.Close()+ if resp.StatusCode >= 400 {+ raw, _ := io.ReadAll(resp.Body)+ return nil, fmt.Errorf("axiom %d: %s", resp.StatusCode, string(raw))+ }++ // Axiom's per-dataset /query response surfaces `_time` at the match+ // level, NOT inside `data`. Parse both and use the match-level time+ // when present (the data-level time is often the zero value because+ // Axiom strips _time from the indexed event body on ingest).+ var parsed struct {+ Matches []struct {+ Time time.Time `json:"_time"`+ Data json.RawMessage `json:"data"`+ } `json:"matches"`+ }+ if err := json.NewDecoder(resp.Body).Decode(&parsed); err != nil {+ return nil, fmt.Errorf("decode axiom response: %w", err)+ }++ out := make([]logEvent, 0, len(parsed.Matches))+ for _, m := range parsed.Matches {+ var ev logEvent+ if err := json.Unmarshal(m.Data, &ev); err != nil {+ continue // skip malformed, don't fail the whole batch+ }+ if !m.Time.IsZero() {+ ev.Time = m.Time+ }+ out = append(out, ev)+ }+ return out, nil+}++// writeSSEEvent writes one event in SSE wire format. Errors here mean+// the client disconnected; the caller's ctx will see Done shortly.+func writeSSEEvent(w io.Writer, ev logEvent) {+ data, err := json.Marshal(ev)+ if err != nil {+ return+ }+ fmt.Fprintf(w, "data: %s\n\n", data)+}++func writeSSEComment(w io.Writer, comment string) {+ fmt.Fprintf(w, ": %s\n\n", comment)+}diff --git a/internal/api/sandbox_logs_test.go b/internal/api/sandbox_logs_test.gonew file mode 100644index 00000000..fc33f94e--- /dev/null+++ b/internal/api/sandbox_logs_test.go@@ -0,0 +1,292 @@+package api++import (+ "encoding/json"+ "net/url"+ "strings"+ "testing"+ "time"+)++// TestFilter_AlwaysFlatSandboxID is the load-bearing security test:+// no matter what the user supplies in query params, the filter sent+// to Axiom must be a FLAT `sandbox_id == <url-path>` predicate.+//+// Axiom's per-dataset /query endpoint silently drops AND-wrapped+// filters and returns the unfiltered dataset (verified empirically+// against api.axiom.co), so a wrapped shape == a tenant leak. The+// flat shape is the only one Axiom actually honors.+func TestFilter_AlwaysFlatSandboxID(t *testing.T) {+ cases := []struct {+ name string+ qs url.Values+ }{+ {"empty", url.Values{}},+ {"with text", url.Values{"q": {"hello"}}},+ {"with sources", url.Values{"source": {"exec_stdout,exec_stderr"}}},+ {"with limit", url.Values{"limit": {"500"}}},+ {+ "injection attempt — quotes in q",+ url.Values{"q": {`" or sandbox_id != "anything`}},+ },+ }++ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ q, err := parseLogQuery("sb-target", time.Now().Add(-time.Hour), tc.qs)+ if err != nil {+ t.Fatalf("parse: %v", err)+ }+ f := q.toFilter()++ if f.Op != "==" {+ t.Errorf("filter op = %q, want == (NEVER and/or — Axiom drops those)", f.Op)+ }+ if f.Field != "sandbox_id" {+ t.Errorf("filter field = %q, want sandbox_id", f.Field)+ }+ if f.Value != "sb-target" {+ t.Errorf("filter value = %v, want sb-target", f.Value)+ }+ if len(f.Filters) != 0 {+ t.Errorf("filter must be flat (no nested .Filters), got %d sub-filters", len(f.Filters))+ }+ })+ }+}++// TestFilter_RejectsBadSource: source values not in allowedSources are a+// 400 at parse time, never interpolated.+func TestFilter_RejectsBadSource(t *testing.T) {+ for _, bad := range []string{"system", "stdout", "exec_stdout'); drop --"} {+ t.Run(bad, func(t *testing.T) {+ _, err := parseLogQuery("sb-x", time.Now(), url.Values{"source": {bad}})+ if err == nil {+ t.Errorf("expected error for source=%q", bad)+ }+ })+ }+}++// TestFilter_RejectsControlCharsInQ: newlines / NULs in `q` are rejected+// at parse time. We rely on this since q.text is applied client-side+// via strings.Contains — any operator-side parsing here is moot, but+// defending against control chars protects future code paths.+func TestFilter_RejectsControlCharsInQ(t *testing.T) {+ for _, bad := range []string{"hello\nworld", "x\x00y", "\r"} {+ _, err := parseLogQuery("sb-x", time.Now(), url.Values{"q": {bad}})+ if err == nil {+ t.Errorf("expected error for q=%q", bad)+ }+ }+}++// TestRequest_TailOmitsLimit: tail polls don't impose a row cap (every+// poll wants every new event since the cursor).+func TestRequest_TailOmitsLimit(t *testing.T) {+ q, err := parseLogQuery("sb-x", time.Now().Add(-time.Hour), url.Values{"limit": {"50"}})+ if err != nil {+ t.Fatalf("parse: %v", err)+ }+ tailReq := q.toRequest(time.Now().Add(-time.Hour), time.Now(), true)+ if tailReq.Limit != 0 {+ t.Errorf("tail request limit = %d, want 0 (omitted)", tailReq.Limit)+ }+ histReq := q.toRequest(time.Now().Add(-time.Hour), time.Now(), false)+ if histReq.Limit != 50 {+ t.Errorf("historical request limit = %d, want 50", histReq.Limit)+ }+}++// TestRequest_BodyShape — full marshaled-JSON smoke test. Failure here+// likely means the body shape has drifted in a way Axiom won't+// understand; verify with an actual Axiom probe before changing.+func TestRequest_BodyShape(t *testing.T) {+ q, err := parseLogQuery("sb-x", time.Now().Add(-time.Hour), url.Values{+ "q": {"oops"},+ "source": {"exec_stdout"},+ })+ if err != nil {+ t.Fatalf("parse: %v", err)+ }+ start := time.Date(2026, 5, 13, 0, 0, 0, 0, time.UTC)+ end := time.Date(2026, 5, 13, 1, 0, 0, 0, time.UTC)+ req := q.toRequest(start, end, false)+ body, err := json.Marshal(req)+ if err != nil {+ t.Fatalf("marshal: %v", err)+ }+ for _, must := range []string{+ `"startTime":"2026-05-13T00:00:00Z"`,+ `"endTime":"2026-05-13T01:00:00Z"`,+ // Flat filter — exactly what Axiom honors.+ `"filter":{"op":"==","field":"sandbox_id","value":"sb-x"}`,+ `"limit":1000`,+ `"order":[{"field":"_time"}]`,+ } {+ if !strings.Contains(string(body), must) {+ t.Errorf("body missing %q:\n%s", must, body)+ }+ }+ // Regression: the body must NOT carry an `apl` field (legacy bug+ // fixed in #242) AND must NOT use the AND wrapper (broken in #242,+ // fixed by this change — Axiom silently drops AND-wrapped filter+ // trees and returns every event in the dataset, see commit message).+ for _, mustNot := range []string{`"apl"`, `"op":"and"`, `"op":"or"`} {+ if strings.Contains(string(body), mustNot) {+ t.Errorf("body contains %q — Axiom drops this shape:\n%s", mustNot, body)+ }+ }+}++// TestParseLogQuery_LimitClamp: caller-supplied limit > 10000 is silently+// clamped to 10000 (the cap is a defense, not a contract).+func TestParseLogQuery_LimitClamp(t *testing.T) {+ q, err := parseLogQuery("sb-x", time.Now(), url.Values{"limit": {"99999"}})+ if err != nil {+ t.Fatalf("parse: %v", err)+ }+ if q.limit != 10000 {+ t.Errorf("expected limit clamped to 10000, got %d", q.limit)+ }+}++// TestApplyClientFilters_NoOp: when the query has no text/source+// narrowing, all rows pass through.+func TestApplyClientFilters_NoOp(t *testing.T) {+ rows := []logEvent{+ {Line: "alpha", Source: "exec_stdout"},+ {Line: "beta", Source: "var_log"},+ }+ got := applyClientFilters(rows, logQuery{})+ if len(got) != 2 {+ t.Errorf("got %d rows, want 2 (no narrowing)", len(got))+ }+}++// TestApplyClientFilters_TextSubstring: q.text narrows by substring on+// the line field, case-sensitive (matches Axiom's `contains` operator+// semantics — we just don't trust Axiom to apply it).+func TestApplyClientFilters_TextSubstring(t *testing.T) {+ rows := []logEvent{+ {Line: "hello world", Source: "exec_stdout"},+ {Line: "goodbye", Source: "exec_stdout"},+ {Line: "Hello again", Source: "exec_stdout"},+ }+ got := applyClientFilters(rows, logQuery{text: "hello"})+ if len(got) != 1 || got[0].Line != "hello world" {+ t.Errorf("got %v, want only 'hello world'", got)+ }+}++// TestApplyClientFilters_SourceList: q.sources narrows to the listed+// sources; events with other source values are dropped.+func TestApplyClientFilters_SourceList(t *testing.T) {+ rows := []logEvent{+ {Line: "a", Source: "exec_stdout"},+ {Line: "b", Source: "exec_stderr"},+ {Line: "c", Source: "var_log"},+ {Line: "d", Source: "agent"},+ }+ got := applyClientFilters(rows, logQuery{sources: []string{"exec_stdout", "exec_stderr"}})+ if len(got) != 2 {+ t.Fatalf("got %d rows, want 2 (exec_stdout + exec_stderr only)", len(got))+ }+ if got[0].Source != "exec_stdout" || got[1].Source != "exec_stderr" {+ t.Errorf("unexpected sources: %v", got)+ }+}++// TestApplyClientFilters_TextAndSourceComposed: both predicates apply+// (AND semantics — row must satisfy both).+func TestApplyClientFilters_TextAndSourceComposed(t *testing.T) {+ rows := []logEvent{+ {Line: "error in foo", Source: "exec_stderr"},+ {Line: "error in bar", Source: "var_log"},+ {Line: "ok in foo", Source: "exec_stderr"},+ }+ got := applyClientFilters(rows, logQuery{+ text: "error",+ sources: []string{"exec_stderr"},+ })+ if len(got) != 1 || got[0].Line != "error in foo" {+ t.Errorf("got %v, want only 'error in foo'", got)+ }+}++// TestApplySessionState_RunningPassthrough: a running sandbox keeps the+// query exactly as parsed — no narrowing.+func TestApplySessionState_RunningPassthrough(t *testing.T) {+ q := logQuery{tail: true, until: time.Time{}}+ got := applySessionState(q, "running", nil)+ if !got.tail {+ t.Errorf("running sandbox: tail = false, want true (caller-set default)")+ }+ if !got.until.IsZero() {+ t.Errorf("running sandbox: until set to %v, want zero", got.until)+ }+}++// TestApplySessionState_PreservesTail: q.tail reflects the client's+// explicit intent (URL ?tail=false / CLI --no-tail) and is NOT+// rewritten by applySessionState. The handler reads session.Status+// separately to decide whether to actually poll Axiom; on non-running+// sandboxes it holds the SSE connection open with keepalives.+//+// History: an earlier version flipped q.tail=false for non-running+// sandboxes. The handler then `return nil`-ed after the historical+// batch, closing the SSE stream. Browsers' EventSource auto-reconnects+// on close → server re-sent the same historical batch → events+// visibly duplicated in the UI (one copy per reconnect). Reverted.+func TestApplySessionState_PreservesTail(t *testing.T) {+ for _, status := range []string{"running", "stopped", "error", "hibernated", "migrating"} {+ t.Run(status, func(t *testing.T) {+ for _, clientTail := range []bool{true, false} {+ q := logQuery{tail: clientTail}+ got := applySessionState(q, status, nil)+ if got.tail != clientTail {+ t.Errorf("status=%s clientTail=%v: tail = %v, want preserved", status, clientTail, got.tail)+ }+ }+ })+ }+}++// TestApplySessionState_CapsUntilAtStoppedAtGrace: non-running sandboxes+// with a stoppedAt timestamp get `until` bounded to stoppedAt + 30s. If+// the caller already passed a tighter `until`, theirs wins.+func TestApplySessionState_CapsUntilAtStoppedAtGrace(t *testing.T) {+ stopped := time.Date(2026, 5, 13, 12, 0, 0, 0, time.UTC)+ t.Run("unset until gets capped", func(t *testing.T) {+ q := logQuery{tail: true}+ got := applySessionState(q, "stopped", &stopped)+ want := stopped.Add(30 * time.Second)+ if !got.until.Equal(want) {+ t.Errorf("until = %v, want %v", got.until, want)+ }+ })+ t.Run("tighter until kept", func(t *testing.T) {+ tighter := stopped.Add(-1 * time.Hour)+ q := logQuery{tail: true, until: tighter}+ got := applySessionState(q, "stopped", &stopped)+ if !got.until.Equal(tighter) {+ t.Errorf("until = %v, want caller-set %v", got.until, tighter)+ }+ })+ t.Run("until in future gets clamped", func(t *testing.T) {+ future := stopped.Add(1 * time.Hour)+ q := logQuery{tail: true, until: future}+ got := applySessionState(q, "stopped", &stopped)+ want := stopped.Add(30 * time.Second)+ if !got.until.Equal(want) {+ t.Errorf("until = %v, want %v (capped at stoppedAt+30s)", got.until, want)+ }+ })+ t.Run("no stoppedAt → no until set", func(t *testing.T) {+ q := logQuery{tail: true}+ got := applySessionState(q, "error", nil)+ if !got.until.IsZero() {+ t.Errorf("error+no-stoppedAt: until = %v, want zero", got.until)+ }+ })+}diff --git a/internal/api/sandbox_scaling_lock.go b/internal/api/sandbox_scaling_lock.gonew file mode 100644index 00000000..ca84b8de--- /dev/null+++ b/internal/api/sandbox_scaling_lock.go@@ -0,0 +1,74 @@+package api++import (+ "log"+ "net/http"++ "github.com/labstack/echo/v4"+)++// PUT /api/sandboxes/:id/scaling-lock+//+// Locks (or unlocks) a sandbox against any size change. When locked:+//+// - POST /scale returns 403 with code "scaling_locked"+// - PUT /autoscale {enabled:true} returns 403 with code "scaling_locked"+// - The per-sandbox autoscaler skips the sandbox (filter in+// ListAutoscaleEnabled, defense in depth)+//+// Locking ALSO disables autoscale on the row — a user who doesn't want+// their sandbox to scale almost certainly doesn't want autoscale either,+// and leaving it half-on would be confusing the next time they unlock.+// Unlocking does NOT auto-re-enable autoscale; the user re-enables+// explicitly via PUT /autoscale.+func (s *Server) setScalingLock(c echo.Context) error {+ sandboxID := c.Param("id")+ if s.store == nil {+ return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)+ }++ var req struct {+ Locked bool `json:"locked"`+ }+ if err := c.Bind(&req); err != nil {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid body"})+ }++ if err := s.store.SetScalingLock(c.Request().Context(), sandboxID, req.Locked); err != nil {+ // Distinguish "not found" from internal errors.+ if err.Error() == "sandbox "+sandboxID+" not found" {+ return c.JSON(http.StatusNotFound, map[string]string{"error": "sandbox not found"})+ }+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})+ }++ if req.Locked {+ // Disable autoscale alongside the lock — single user-visible state+ // instead of two overlapping toggles. Best-effort, logged on failure.+ if err := s.store.SetSandboxAutoscale(c.Request().Context(), sandboxID, false, 0, 0); err != nil {+ log.Printf("scaling-lock: failed to disable autoscale on %s after lock: %v", sandboxID, err)+ }+ }++ return c.JSON(http.StatusOK, map[string]any{+ "sandboxID": sandboxID,+ "locked": req.Locked,+ })+}++// GET /api/sandboxes/:id/scaling-lock+func (s *Server) getScalingLock(c echo.Context) error {+ sandboxID := c.Param("id")+ if s.store == nil {+ return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)+ }++ locked, err := s.store.GetScalingLock(c.Request().Context(), sandboxID)+ if err != nil {+ return c.JSON(http.StatusNotFound, map[string]string{"error": "sandbox not found"})+ }+ return c.JSON(http.StatusOK, map[string]any{+ "sandboxID": sandboxID,+ "locked": locked,+ })+}diff --git a/internal/auth/jwt.go b/internal/auth/jwt.goindex d6ff4e80..e418be29 100644--- a/internal/auth/jwt.go+++ b/internal/auth/jwt.go@@ -45,10 +45,20 @@ func (j *JWTIssuer) IssueSandboxToken(orgID uuid.UUID, sandboxID, workerID strinreturn token.SignedString(j.secret)}+// Audience constants for identity tokens. Each consumer requires its own+// audience so that a token minted for one surface cannot be replayed against+// another (e.g. a token meant for sessions-api can't be used to call OC's+// sandbox API directly).+const (+ AudSessionsAPI = "sessions-api"+ AudOpenComputerAPI = "opencomputer-api"+)+// IdentityClaims are the JWT claims for identity tokens issued to downstream-// services (e.g. sessions-api). They carry the caller's org and user identity-// so the downstream can authorize and attribute analytics events without-// calling back to the control plane.+// services (e.g. sessions-api, OC's own /api/sandboxes when called by+// sessions-api). They carry the caller's org and user identity so the+// downstream can authorize and attribute analytics events without calling+// back to the control plane.type IdentityClaims struct {jwt.RegisteredClaimsOrgID string `json:"org_id"`@@ -58,16 +68,21 @@ type IdentityClaims struct {}// IdentityTokenInput bundles the identity fields embedded in an identity JWT.-// Nil pointers are omitted from the resulting token.+// Nil pointers are omitted from the resulting token. Audience is required —+// see the Aud* constants.type IdentityTokenInput struct {OrgID stringUserID *stringEmail *stringWorkOSUserID *string+ Audience string}// IssueIdentityToken creates a short-lived JWT carrying the caller's identity.func (j *JWTIssuer) IssueIdentityToken(in IdentityTokenInput, ttl time.Duration) (string, error) {+ if in.Audience == "" {+ return "", fmt.Errorf("audience is required")+ }now := time.Now()claims := IdentityClaims{RegisteredClaims: jwt.RegisteredClaims{@@ -75,6 +90,7 @@ func (j *JWTIssuer) IssueIdentityToken(in IdentityTokenInput, ttl time.Duration)IssuedAt: jwt.NewNumericDate(now),ExpiresAt: jwt.NewNumericDate(now.Add(ttl)),Issuer: "opensandbox",+ Audience: jwt.ClaimStrings{in.Audience},},OrgID: in.OrgID,UserID: in.UserID,@@ -86,14 +102,15 @@ func (j *JWTIssuer) IssueIdentityToken(in IdentityTokenInput, ttl time.Duration)return token.SignedString(j.secret)}-// ValidateIdentityToken parses and validates an identity JWT.-func (j *JWTIssuer) ValidateIdentityToken(tokenStr string) (*IdentityClaims, error) {+// ValidateIdentityToken parses and validates an identity JWT, requiring the+// expected audience. Pass one of the Aud* constants.+func (j *JWTIssuer) ValidateIdentityToken(tokenStr, expectedAudience string) (*IdentityClaims, error) {token, err := jwt.ParseWithClaims(tokenStr, &IdentityClaims{}, func(t *jwt.Token) (interface{}, error) {if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {return nil, fmt.Errorf("unexpected signing method: %v", t.Header["alg"])}return j.secret, nil- })+ }, jwt.WithIssuer("opensandbox"), jwt.WithAudience(expectedAudience))if err != nil {return nil, fmt.Errorf("invalid token: %w", err)}diff --git a/internal/auth/middleware.go b/internal/auth/middleware.goindex f98730b7..c6a01ab1 100644--- a/internal/auth/middleware.go+++ b/internal/auth/middleware.go@@ -53,7 +53,13 @@ func GetUserID(c echo.Context) *uuid.UUID {// PGAPIKeyMiddleware validates API keys against PostgreSQL.// Falls back to static API key comparison if store is nil (combined/dev mode).-func PGAPIKeyMiddleware(store *db.Store, staticKey string) echo.MiddlewareFunc {+//+// Also accepts an identity JWT (aud=opencomputer-api) when jwtIssuer is non-nil.+// The JWT can arrive either in `Authorization: Bearer <jwt>` or as the X-API-Key+// value (JWTs are detected by the two-dot signature: "header.payload.signature").+// This lets sessions-api act on behalf of a dashboard user without holding a+// long-lived API key — see internal/auth/jwt.go for the audience constants.+func PGAPIKeyMiddleware(store *db.Store, staticKey string, jwtIssuer *JWTIssuer) echo.MiddlewareFunc {return func(next echo.HandlerFunc) echo.HandlerFunc {return func(c echo.Context) error {// Try static API key first (backward compat for combined mode)@@ -61,12 +67,32 @@ func PGAPIKeyMiddleware(store *db.Store, staticKey string) echo.MiddlewareFunc {return APIKeyMiddleware(staticKey)(next)(c)}+ // Identity-JWT path: Authorization: Bearer <jwt> with aud=opencomputer-api.+ if jwtIssuer != nil {+ authHeader := c.Request().Header.Get("Authorization")+ if strings.HasPrefix(authHeader, "Bearer ") {+ tokenStr := strings.TrimPrefix(authHeader, "Bearer ")+ if claims, err := jwtIssuer.ValidateIdentityToken(tokenStr, AudOpenComputerAPI); err == nil {+ return applyIdentityClaims(c, claims, next)+ }+ }+ }+// Get API key from header or querykey := c.Request().Header.Get("X-API-Key")if key == "" {key = c.QueryParam("api_key")}+ // JWTs may also arrive in the X-API-Key slot (the OC SDK takes a single+ // `apiKey` field and ships it as X-API-Key — no Authorization option).+ // Detect JWT by the two-dot signature; opaque API keys never contain dots.+ if jwtIssuer != nil && key != "" && strings.Count(key, ".") == 2 {+ if claims, err := jwtIssuer.ValidateIdentityToken(key, AudOpenComputerAPI); err == nil {+ return applyIdentityClaims(c, claims, next)+ }+ }+// If no key and no store, pass through (dev mode)if key == "" && store == nil && staticKey == "" {return next(c)@@ -99,6 +125,25 @@ func PGAPIKeyMiddleware(store *db.Store, staticKey string) echo.MiddlewareFunc {}}+func applyIdentityClaims(c echo.Context, claims *IdentityClaims, next echo.HandlerFunc) error {+ orgID, err := uuid.Parse(claims.OrgID)+ if err != nil {+ return c.JSON(http.StatusForbidden, map[string]string{+ "error": "identity token: invalid org_id",+ })+ }+ SetOrgID(c, orgID)+ if claims.UserID != nil {+ if userID, err := uuid.Parse(*claims.UserID); err == nil {+ SetUserID(c, userID)+ }+ }+ if claims.Email != nil {+ c.Set("user_email", *claims.Email)+ }+ return next(c)+}+// SandboxJWTMiddleware validates sandbox-scoped JWTs for direct worker access.// It verifies the token and checks that the sandbox_id in the token matches the :id URL param.func SandboxJWTMiddleware(jwtIssuer *JWTIssuer) echo.MiddlewareFunc {diff --git a/internal/auth/oauth_handlers.go b/internal/auth/oauth_handlers.goindex e906ea2c..19d82668 100644--- a/internal/auth/oauth_handlers.go+++ b/internal/auth/oauth_handlers.go@@ -10,8 +10,17 @@ import ("github.com/google/uuid""github.com/labstack/echo/v4""github.com/workos/workos-go/v4/pkg/usermanagement"++ "github.com/opensandbox/opensandbox/internal/metrics")+// authType label values for opensandbox_auth_attempts_total. The type+// column groups by entry point (WorkOS callback today; add more on demand).+// Result is the binary outcome — success when the session cookie is set,+// failure for any earlier error return. Sub-reasons live in logs, not in+// metric labels, to keep label cardinality bounded.+const authTypeWorkOS = "workos"+// OAuthHandlers provides HTTP handlers for WorkOS OAuth flow.type OAuthHandlers struct {workos *WorkOSMiddleware@@ -64,6 +73,7 @@ func (h *OAuthHandlers) HandleCallback(c echo.Context) error {state := c.QueryParam("state")if code == "" {+ metrics.AuthAttemptsTotal.WithLabelValues(authTypeWorkOS, "failure").Inc()return c.JSON(http.StatusBadRequest, map[string]string{"error": "missing authorization code",})@@ -75,6 +85,7 @@ func (h *OAuthHandlers) HandleCallback(c echo.Context) error {if err == nil {// Cookie exists — verify it matches (normal login flow)if stateCookie.Value != state {+ metrics.AuthAttemptsTotal.WithLabelValues(authTypeWorkOS, "failure").Inc()return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid state parameter",})@@ -98,6 +109,7 @@ func (h *OAuthHandlers) HandleCallback(c echo.Context) error {Code: code,})if err != nil {+ metrics.AuthAttemptsTotal.WithLabelValues(authTypeWorkOS, "failure").Inc()log.Printf("workos: callback authentication failed: %v", err)return c.JSON(http.StatusUnauthorized, map[string]string{"error": "authentication failed",@@ -118,6 +130,7 @@ func (h *OAuthHandlers) HandleCallback(c echo.Context) error {orgName := authResult.User.EmaillocalUser, err := h.workos.ProvisionOrgAndUser(ctx, authResult.User.Email, name, orgName, authResult.User.ID, authResult.OrganizationID)if err != nil {+ metrics.AuthAttemptsTotal.WithLabelValues(authTypeWorkOS, "failure").Inc()log.Printf("workos: provisioning failed: %v", err)return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to provision user",@@ -142,6 +155,8 @@ func (h *OAuthHandlers) HandleCallback(c echo.Context) error {SameSite: http.SameSiteLaxMode,})+ metrics.AuthAttemptsTotal.WithLabelValues(authTypeWorkOS, "success").Inc()+// Redirect to dashboard after loginreturn c.Redirect(http.StatusFound, "/")}diff --git a/internal/billing/billable_events_sender.go b/internal/billing/billable_events_sender.gonew file mode 100644index 00000000..0dd17c5e--- /dev/null+++ b/internal/billing/billable_events_sender.go@@ -0,0 +1,164 @@+package billing++import (+ "context"+ "fmt"+ "log"+ "time"++ "github.com/opensandbox/opensandbox/internal/db"+)++// BillableEventsSender is the phase-3 Stripe shipper. Every `interval`,+// it pulls pending rows from `billable_events` for orgs in+// `billing_mode='unified'` and submits them to Stripe meter events+// using `billable_events.id` as the idempotency key. On success the+// row's `delivery_state` flips to `'sent'`. On error the row stays+// `'pending'` and gets retried next tick — Stripe meter events are+// idempotent by identifier within 24h, so retrying is safe.+//+// New orgs default to `billing_mode='unified'` (per migration 031);+// existing orgs are pinned to `'legacy'`. So on deploy this goroutine+// has zero work to do until the first new pro signup or until an org+// is manually flipped.+type BillableEventsSender struct {+ store *db.Store+ stripe *StripeClient+ interval time.Duration+ batch int+ stop chan struct{}+ stopped chan struct{}+}++// BillableEventsSenderOpts allows the server bootstrap to override the+// defaults via env. Zero values fall back to defaults.+type BillableEventsSenderOpts struct {+ Interval time.Duration // default 5m — same cadence as UsageReporter+ Batch int // pending rows per tick, default 200+}++func NewBillableEventsSender(store *db.Store, stripe *StripeClient, opts BillableEventsSenderOpts) *BillableEventsSender {+ if opts.Interval <= 0 {+ opts.Interval = 5 * time.Minute+ }+ if opts.Batch <= 0 {+ opts.Batch = 200+ }+ return &BillableEventsSender{+ store: store,+ stripe: stripe,+ interval: opts.Interval,+ batch: opts.Batch,+ stop: make(chan struct{}),+ stopped: make(chan struct{}),+ }+}++func (s *BillableEventsSender) Start() { go s.loop() }+func (s *BillableEventsSender) Stop() { close(s.stop); <-s.stopped }++func (s *BillableEventsSender) loop() {+ defer close(s.stopped)+ ticker := time.NewTicker(s.interval)+ defer ticker.Stop()+ for {+ select {+ case <-ticker.C:+ s.tickSafe()+ case <-s.stop:+ return+ }+ }+}++func (s *BillableEventsSender) tickSafe() {+ defer func() {+ if v := recover(); v != nil {+ log.Printf("billable-events-sender: recovered from panic: %v", v)+ }+ }()+ s.tick()+}++func (s *BillableEventsSender) tick() {+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)+ defer cancel()++ pending, err := s.store.ListPendingBillableEventsForSender(ctx, s.batch)+ if err != nil {+ log.Printf("billable-events-sender: list pending: %v", err)+ return+ }+ if len(pending) == 0 {+ return+ }+ log.Printf("billable-events-sender: shipping %d pending event(s)", len(pending))++ sent, failed := 0, 0+ for _, p := range pending {+ if err := s.shipOne(ctx, p); err != nil {+ log.Printf("billable-events-sender: event=%s org=%s type=%s tier=%d: %v",+ p.Event.ID, p.Event.OrgID, p.Event.EventType, p.Event.MemoryMB, err)+ failed+++ continue+ }+ sent+++ }+ log.Printf("billable-events-sender: sent=%d failed=%d (failed rows stay 'pending' for retry)", sent, failed)+}++// shipOne maps one outbox row to its Stripe meter event_name, submits+// the meter event with `Identifier = billable_events.id` for at-least-+// once safety, and marks the row 'sent' on success.+func (s *BillableEventsSender) shipOne(ctx context.Context, p db.PendingBillableEventForSender) error {+ eventName, err := s.meterEventNameFor(p.Event.EventType, p.Event.MemoryMB)+ if err != nil {+ return err+ }++ // Stripe wants a unix timestamp for the meter event. Use the+ // bucket end — that's the moment the usage was "incurred" from+ // Stripe's perspective and is stable across retries.+ timestamp := p.Event.BucketEnd.Unix()+ identifier := p.Event.ID.String()++ stripeID, err := s.stripe.ReportMeterEvent(eventName, p.StripeCustomerID, p.Event.GBSeconds, identifier, timestamp)+ if err != nil {+ return fmt.Errorf("submit meter event: %w", err)+ }++ if err := s.store.MarkBillableEventSent(ctx, p.Event.ID, stripeID); err != nil {+ // Stripe accepted the event but we couldn't update the row.+ // Next tick will resubmit; the Identifier dedup makes this+ // safe — Stripe will return the same event ID without+ // double-counting.+ return fmt.Errorf("mark sent (will retry): %w", err)+ }+ return nil+}++// meterEventNameFor maps an outbox event_type → Stripe meter event_name.+// All three event types route to a single meter each — overage is flat+// (the per-tier memory_mb on the outbox row is preserved for analytics+// but ignored when shipping; Stripe sums GB-seconds across rows).+func (s *BillableEventsSender) meterEventNameFor(eventType string, memoryMB int) (string, error) {+ switch eventType {+ case db.BillableEventReservedUsage:+ if s.stripe.ReservedMeterEventName == "" {+ return "", fmt.Errorf("reserved meter not provisioned (run EnsureProducts)")+ }+ return s.stripe.ReservedMeterEventName, nil+ case db.BillableEventOverageUsage:+ if s.stripe.OverageMeterEventName == "" {+ return "", fmt.Errorf("overage meter not provisioned (run EnsureProducts)")+ }+ return s.stripe.OverageMeterEventName, nil+ case db.BillableEventDiskOverageUsage:+ if s.stripe.DiskOverageMeterEventName == "" {+ return "", fmt.Errorf("disk overage meter not provisioned")+ }+ return s.stripe.DiskOverageMeterEventName, nil+ default:+ return "", fmt.Errorf("unknown event_type %q", eventType)+ }+}diff --git a/internal/billing/billable_events_sender_test.go b/internal/billing/billable_events_sender_test.gonew file mode 100644index 00000000..5d7d9d96--- /dev/null+++ b/internal/billing/billable_events_sender_test.go@@ -0,0 +1,85 @@+package billing++import (+ "strings"+ "testing"++ "github.com/opensandbox/opensandbox/internal/db"+)++// meterEventNameFor pins the (event_type, memory_mb) → Stripe meter+// routing. Overage is flat — memory_mb is preserved on the outbox row+// for analytics but ignored at ship time so a 1 GB and 64 GB sandbox+// hit the same meter.++func newSenderForTest() *BillableEventsSender {+ stripe := &StripeClient{+ ReservedMeterEventName: "sandbox_compute_sandbox_reserved",+ OverageMeterEventName: "sandbox_compute_sandbox_overage",+ DiskOverageMeterEventName: "sandbox_compute_sandbox_disk_overage",+ }+ return &BillableEventsSender{stripe: stripe}+}++func TestSender_meterEventName_reservedFlat(t *testing.T) {+ s := newSenderForTest()+ got, err := s.meterEventNameFor(db.BillableEventReservedUsage, 0)+ if err != nil {+ t.Fatalf("err: %v", err)+ }+ if got != "sandbox_compute_sandbox_reserved" {+ t.Errorf("got %q", got)+ }+}++func TestSender_meterEventName_overageFlatAcrossTiers(t *testing.T) {+ s := newSenderForTest()+ for _, tier := range []int{1024, 4096, 8192, 16384, 32768, 65536} {+ got, err := s.meterEventNameFor(db.BillableEventOverageUsage, tier)+ if err != nil {+ t.Fatalf("tier %d: err: %v", tier, err)+ }+ if got != "sandbox_compute_sandbox_overage" {+ t.Errorf("tier %d: got %q, want flat overage meter", tier, got)+ }+ }+}++func TestSender_meterEventName_diskOverage(t *testing.T) {+ s := newSenderForTest()+ got, err := s.meterEventNameFor(db.BillableEventDiskOverageUsage, 0)+ if err != nil {+ t.Fatalf("err: %v", err)+ }+ if got != "sandbox_compute_sandbox_disk_overage" {+ t.Errorf("got %q", got)+ }+}++func TestSender_meterEventName_unknownTypeRejected(t *testing.T) {+ s := newSenderForTest()+ _, err := s.meterEventNameFor("totally_made_up", 0)+ if err == nil || !strings.Contains(err.Error(), "unknown event_type") {+ t.Errorf("expected unknown event_type error, got %v", err)+ }+}++func TestSender_meterEventName_missingProvisionRejected(t *testing.T) {+ // Empty stripe client — no meters provisioned. Sender must error+ // loudly rather than ship to an empty event_name.+ s := &BillableEventsSender{stripe: &StripeClient{}}+ cases := []struct {+ eventType string+ want string+ }{+ {db.BillableEventReservedUsage, "reserved meter not provisioned"},+ {db.BillableEventOverageUsage, "overage meter not provisioned"},+ {db.BillableEventDiskOverageUsage, "disk overage meter not provisioned"},+ }+ for _, tc := range cases {+ _, err := s.meterEventNameFor(tc.eventType, 0)+ if err == nil || !strings.Contains(err.Error(), tc.want) {+ t.Errorf("event_type=%s: expected %q, got %v", tc.eventType, tc.want, err)+ }+ }+}diff --git a/internal/billing/capacity_reconciler.go b/internal/billing/capacity_reconciler.gonew file mode 100644index 00000000..5b99dd5e--- /dev/null+++ b/internal/billing/capacity_reconciler.go@@ -0,0 +1,337 @@+package billing++import (+ "context"+ "log"+ "sort"+ "time"++ "github.com/google/uuid"+ "github.com/opensandbox/opensandbox/internal/db"+)++// CapacityReconciler is the phase-2 outbox allocator. Every `interval`,+// it scans for closed 15-min buckets that are at least `settle` past+// their end and haven't been processed yet, runs the per-second+// integration walk for each (org, bucket), and emits the resulting+// reserved_usage / overage_usage / disk_overage_usage rows to the+// `billable_events` outbox.+//+// Phase 2 runs in shadow: the rows are written but not delivered to+// Stripe. UsageReporter continues to drive real billing. Shadow-verify+// (cmd/capacity-shadow-verify) compares the two for orgs with zero+// reservations to validate the new pipeline before phase 3 cuts over.+//+// The outbox unique constraint+// `(org_id, event_type, memory_mb, bucket_start)` makes the allocator+// idempotent at the DB level — a crashed or restarted reconciler can+// replay any bucket safely.+type CapacityReconciler struct {+ store *db.Store+ interval time.Duration+ settle time.Duration+ lookback time.Duration+ limit int+ stop chan struct{}+ stopped chan struct{}+}++// CapacityReconcilerOpts allows the server bootstrap to override the+// defaults via env (CAPACITY_ALLOCATOR_INTERVAL, _SETTLE_MINUTES,+// _LOOKBACK_HOURS, _BATCH_LIMIT). Zero values fall back to defaults.+type CapacityReconcilerOpts struct {+ Interval time.Duration // default 5m+ Settle time.Duration // default 30m+ Lookback time.Duration // default 24h+ Limit int // candidates per tick, default 500+}++func NewCapacityReconciler(store *db.Store, opts CapacityReconcilerOpts) *CapacityReconciler {+ if opts.Interval <= 0 {+ opts.Interval = 5 * time.Minute+ }+ if opts.Settle <= 0 {+ opts.Settle = 30 * time.Minute+ }+ if opts.Lookback <= 0 {+ opts.Lookback = 24 * time.Hour+ }+ if opts.Limit <= 0 {+ opts.Limit = 500+ }+ return &CapacityReconciler{+ store: store,+ interval: opts.Interval,+ settle: opts.Settle,+ lookback: opts.Lookback,+ limit: opts.Limit,+ stop: make(chan struct{}),+ stopped: make(chan struct{}),+ }+}++func (r *CapacityReconciler) Start() { go r.loop() }+func (r *CapacityReconciler) Stop() { close(r.stop); <-r.stopped }++func (r *CapacityReconciler) loop() {+ defer close(r.stopped)+ ticker := time.NewTicker(r.interval)+ defer ticker.Stop()+ for {+ select {+ case <-ticker.C:+ r.tickSafe()+ case <-r.stop:+ return+ }+ }+}++func (r *CapacityReconciler) tickSafe() {+ defer func() {+ if v := recover(); v != nil {+ log.Printf("capacity-reconciler: recovered from panic: %v", v)+ }+ }()+ r.tick()+}++func (r *CapacityReconciler) tick() {+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)+ defer cancel()++ // Cutoff: only buckets whose end is at least `settle` ago are eligible.+ // Truncate to a 15-min boundary so we don't accidentally include a+ // half-finished bucket if `settle` happens to land mid-bucket.+ cutoff := time.Now().UTC().Add(-r.settle).Truncate(15 * time.Minute)+ lookbackStart := cutoff.Add(-r.lookback)++ candidates, err := r.store.ListAllocatorCandidates(ctx, lookbackStart, cutoff, r.limit)+ if err != nil {+ log.Printf("capacity-reconciler: list candidates: %v", err)+ return+ }+ if len(candidates) == 0 {+ return+ }+ log.Printf("capacity-reconciler: processing %d candidate bucket(s)", len(candidates))++ processed := 0+ for _, c := range candidates {+ if err := r.processBucket(ctx, c.OrgID, c.BucketStart); err != nil {+ log.Printf("capacity-reconciler: org=%s bucket=%s: %v", c.OrgID, c.BucketStart.Format(time.RFC3339), err)+ continue+ }+ processed+++ }+ log.Printf("capacity-reconciler: emitted outbox rows for %d/%d bucket(s)", processed, len(candidates))+}++// processBucket runs the per-second integration walk for one (org,+// bucket) and emits the resulting outbox rows. The outbox UNIQUE+// constraint absorbs replays.+func (r *CapacityReconciler) processBucket(ctx context.Context, orgID uuid.UUID, bucketStart time.Time) error {+ bucketEnd := bucketStart.Add(15 * time.Minute)++ reservedGB, err := r.store.GetReservedGBForBucket(ctx, orgID, bucketStart)+ if err != nil {+ return err+ }++ events, err := r.store.GetScaleEventsForBucket(ctx, orgID, bucketStart, bucketEnd)+ if err != nil {+ return err+ }++ totals := IntegrateBucket(bucketStart, bucketEnd, reservedGB, events)+ return emitBucket(ctx, r.store, orgID, bucketStart, bucketEnd, reservedGB, totals)+}++// BucketTotals is the output of the per-bucket integration walk.+// Memory tier keys are `memory_mb` (1024 / 4096 / ...). DiskOverageGBSeconds+// is org-level, summed across all running events at each segment.+type BucketTotals struct {+ OverageGBSecondsByTier map[int]float64+ DiskOverageGBSeconds float64+ ReservedFloorGBSeconds float64 // reservedGb × secs accumulated across segments — for shadow validation only+}++// IntegrateBucket runs the full clip → segments → integrate pipeline+// for one (org, bucket). Pure-Go, deterministic, unit-testable.+func IntegrateBucket(bucketStart, bucketEnd time.Time, reservedGB int, events []db.ScaleEvent) BucketTotals {+ clipped := make([]clippedEvent, 0, len(events))+ for _, e := range events {+ c, ok := clipEvent(e, bucketStart, bucketEnd)+ if !ok {+ continue+ }+ clipped = append(clipped, c)+ }+ boundaries := collectBoundaries(clipped, bucketStart, bucketEnd)+ segs := walkSegments(boundaries, clipped)+ return integrateSegments(segs, reservedGB)+}++type clippedEvent struct {+ From, To time.Time+ TierMB int+ DiskMB int+}++// clipEvent restricts a ScaleEvent's lifetime to the bucket window.+// Returns ok=false if the event's clipped span is empty.+func clipEvent(e db.ScaleEvent, bucketStart, bucketEnd time.Time) (clippedEvent, bool) {+ from := e.StartedAt+ if from.Before(bucketStart) {+ from = bucketStart+ }+ to := bucketEnd+ if e.EndedAt != nil && e.EndedAt.Before(bucketEnd) {+ to = *e.EndedAt+ }+ if !to.After(from) {+ return clippedEvent{}, false+ }+ return clippedEvent{From: from, To: to, TierMB: e.MemoryMB, DiskMB: e.DiskMB}, true+}++func collectBoundaries(events []clippedEvent, bucketStart, bucketEnd time.Time) []time.Time {+ seen := map[int64]struct{}{+ bucketStart.UnixNano(): {},+ bucketEnd.UnixNano(): {},+ }+ out := []time.Time{bucketStart, bucketEnd}+ for _, e := range events {+ if _, ok := seen[e.From.UnixNano()]; !ok {+ seen[e.From.UnixNano()] = struct{}{}+ out = append(out, e.From)+ }+ if _, ok := seen[e.To.UnixNano()]; !ok {+ seen[e.To.UnixNano()] = struct{}{}+ out = append(out, e.To)+ }+ }+ sort.Slice(out, func(i, j int) bool { return out[i].Before(out[j]) })+ return out+}++type segment struct {+ From, To time.Time+ RunningByTier map[int]int // tier_mb → running GB at this tier+ DiskOverageMB int // sum of (disk_mb − 20480) over running events+}++func walkSegments(boundaries []time.Time, events []clippedEvent) []segment {+ segs := make([]segment, 0, len(boundaries)-1)+ for i := 0; i < len(boundaries)-1; i++ {+ from, to := boundaries[i], boundaries[i+1]+ if !to.After(from) {+ continue+ }+ tiers := map[int]int{}+ diskOver := 0+ for _, e := range events {+ // Event is "running" in [from, to) if it covers the segment+ // fully — i.e. e.From <= from AND e.To >= to. Since the+ // boundary set includes every event endpoint, every segment+ // is fully contained in any event whose span covers `from`.+ if !e.From.After(from) && !e.To.Before(to) {+ tiers[e.TierMB] += e.TierMB / 1024+ if e.DiskMB > 20480 {+ diskOver += e.DiskMB - 20480+ }+ }+ }+ segs = append(segs, segment{From: from, To: to, RunningByTier: tiers, DiskOverageMB: diskOver})+ }+ return segs+}++func integrateSegments(segs []segment, reservedGB int) BucketTotals {+ out := BucketTotals{OverageGBSecondsByTier: map[int]float64{}}+ for _, s := range segs {+ secs := s.To.Sub(s.From).Seconds()+ usage := 0+ for _, gb := range s.RunningByTier {+ usage += gb+ }++ if usage > reservedGB {+ spike := float64(usage - reservedGB)+ for tier, gb := range s.RunningByTier {+ share := float64(gb) / float64(usage)+ out.OverageGBSecondsByTier[tier] += spike * share * secs+ }+ out.ReservedFloorGBSeconds += float64(reservedGB) * secs+ } else {+ out.ReservedFloorGBSeconds += float64(usage) * secs+ }++ if s.DiskOverageMB > 0 {+ out.DiskOverageGBSeconds += float64(s.DiskOverageMB) / 1024.0 * secs+ }+ }+ return out+}++// emitBucket writes the outbox rows for one settled bucket.+//+// - reserved_usage — one row per (org, bucket) when reservedGB > 0.+// `gb_seconds = reservedGB × 900` (full bucket charge regardless of+// actual usage — the customer paid for the floor whether or not+// they used it).+// - overage_usage — one row per (org, sandbox_tier, bucket) where+// the tier's overage contribution is non-zero.+// - disk_overage_usage — one row per (org, bucket) when any sandbox+// in the bucket exceeded the 20 GB allowance.+//+// `INSERT ... ON CONFLICT DO NOTHING` (inside `UpsertBillableEvent`)+// makes each emission idempotent at the unique constraint.+func emitBucket(ctx context.Context, store *db.Store, orgID uuid.UUID, bucketStart, bucketEnd time.Time, reservedGB int, totals BucketTotals) error {+ if reservedGB > 0 {+ ev := db.BillableEvent{+ OrgID: orgID,+ EventType: db.BillableEventReservedUsage,+ MemoryMB: 0,+ GBSeconds: float64(reservedGB) * 900.0,+ BucketStart: bucketStart,+ BucketEnd: bucketEnd,+ }+ if _, err := store.UpsertBillableEvent(ctx, ev); err != nil {+ return err+ }+ }++ for tier, gbs := range totals.OverageGBSecondsByTier {+ if gbs <= 0 {+ continue+ }+ ev := db.BillableEvent{+ OrgID: orgID,+ EventType: db.BillableEventOverageUsage,+ MemoryMB: tier,+ GBSeconds: gbs,+ BucketStart: bucketStart,+ BucketEnd: bucketEnd,+ }+ if _, err := store.UpsertBillableEvent(ctx, ev); err != nil {+ return err+ }+ }++ if totals.DiskOverageGBSeconds > 0 {+ ev := db.BillableEvent{+ OrgID: orgID,+ EventType: db.BillableEventDiskOverageUsage,+ MemoryMB: 0,+ GBSeconds: totals.DiskOverageGBSeconds,+ BucketStart: bucketStart,+ BucketEnd: bucketEnd,+ }+ if _, err := store.UpsertBillableEvent(ctx, ev); err != nil {+ return err+ }+ }++ return nil+}diff --git a/internal/billing/capacity_reconciler_test.go b/internal/billing/capacity_reconciler_test.gonew file mode 100644index 00000000..75671d11--- /dev/null+++ b/internal/billing/capacity_reconciler_test.go@@ -0,0 +1,239 @@+package billing++import (+ "math"+ "testing"+ "time"++ "github.com/opensandbox/opensandbox/internal/db"+)++// IntegrateBucket is the load-bearing math of the unified billing+// pipeline. These tests pin every branch of the spec from+// ws-pricing/work/001 "Per-second integration walk in detail":+//+// - zero-reservation collapses to legacy reporter totals+// - full-coverage reservation produces zero overage+// - partial overage attributes spike across running tiers+// proportionally to share-of-memory+// - disk overage accumulates per-second per-MB above 20 GB+// - mid-bucket scale events split into segments correctly++const (+ bucketStartCanon = 0+ bucketEndCanon = 900+)++func eventAt(memMB, diskMB, fromSec, toSec int) db.ScaleEvent {+ base := time.Date(2030, 6, 1, 0, 0, 0, 0, time.UTC)+ from := base.Add(time.Duration(fromSec) * time.Second)+ to := base.Add(time.Duration(toSec) * time.Second)+ return db.ScaleEvent{+ MemoryMB: memMB,+ DiskMB: diskMB,+ StartedAt: from,+ EndedAt: &to,+ }+}++func canonicalBucket() (time.Time, time.Time) {+ base := time.Date(2030, 6, 1, 0, 0, 0, 0, time.UTC)+ return base, base.Add(15 * time.Minute)+}++func eq(t *testing.T, label string, got, want float64) {+ t.Helper()+ if math.Abs(got-want) > 1e-6 {+ t.Errorf("%s: got %v, want %v", label, got, want)+ }+}++func TestIntegrateBucket_zeroReservation_replaysLegacy(t *testing.T) {+ bs, be := canonicalBucket()+ // One 8 GB sandbox running the full bucket.+ totals := IntegrateBucket(bs, be, 0, []db.ScaleEvent{+ eventAt(8192, 20480, 0, 900),+ })+ // Zero reservation → all usage is overage. 8 GB × 900 s = 7200 GB-s+ // at tier 8192. Legacy reporter would report tier-seconds=900 at+ // 8192 MB, which corresponds to 8 × 900 = 7200 GB-seconds — exact+ // replay (modulo the legacy per-tick ceil() which we don't apply+ // at the bucket grain).+ eq(t, "tier 8192", totals.OverageGBSecondsByTier[8192], 7200)+ eq(t, "disk overage", totals.DiskOverageGBSeconds, 0)+ if len(totals.OverageGBSecondsByTier) != 1 {+ t.Errorf("expected only tier 8192, got %v", totals.OverageGBSecondsByTier)+ }+}++func TestIntegrateBucket_fullCoverage_noOverage(t *testing.T) {+ bs, be := canonicalBucket()+ // One 8 GB sandbox, reservation covers it.+ totals := IntegrateBucket(bs, be, 8, []db.ScaleEvent{+ eventAt(8192, 20480, 0, 900),+ })+ if len(totals.OverageGBSecondsByTier) != 0 {+ t.Errorf("expected no overage tiers, got %v", totals.OverageGBSecondsByTier)+ }+ eq(t, "reserved floor", totals.ReservedFloorGBSeconds, 8*900)+}++func TestIntegrateBucket_partialOverage_proportionalSplit(t *testing.T) {+ bs, be := canonicalBucket()+ // 8 GB + 16 GB running concurrently for the full bucket; reserved=8.+ // usage=24, spike=16. Tier 8192 share=8/24, tier 16384 share=16/24.+ totals := IntegrateBucket(bs, be, 8, []db.ScaleEvent{+ eventAt(8192, 20480, 0, 900),+ eventAt(16384, 20480, 0, 900),+ })+ eq(t, "tier 8192 overage", totals.OverageGBSecondsByTier[8192], 16.0*(8.0/24.0)*900.0)+ eq(t, "tier 16384 overage", totals.OverageGBSecondsByTier[16384], 16.0*(16.0/24.0)*900.0)+ // Sum of shares is 1.0: total overage = 16 GB × 900 s = 14400.+ total := totals.OverageGBSecondsByTier[8192] + totals.OverageGBSecondsByTier[16384]+ eq(t, "sum-of-shares", total, 14400)+}++func TestIntegrateBucket_sameTierAccumulates(t *testing.T) {+ bs, be := canonicalBucket()+ // Two 8 GB sandboxes, reserved=8. usage=16, spike=8, all on tier 8192.+ // share=16/16=1.0 → overage[8192] = 8 × 900 = 7200.+ totals := IntegrateBucket(bs, be, 8, []db.ScaleEvent{+ eventAt(8192, 20480, 0, 900),+ eventAt(8192, 20480, 0, 900),+ })+ eq(t, "tier 8192", totals.OverageGBSecondsByTier[8192], 7200)+ if len(totals.OverageGBSecondsByTier) != 1 {+ t.Errorf("expected only tier 8192, got %v", totals.OverageGBSecondsByTier)+ }+}++func TestIntegrateBucket_diskOverage(t *testing.T) {+ bs, be := canonicalBucket()+ // 1 sandbox at 8 GB memory, 30 GB disk (10 GB over the 20 GB+ // allowance) running the full bucket.+ totals := IntegrateBucket(bs, be, 0, []db.ScaleEvent{+ eventAt(8192, 30720, 0, 900),+ })+ // 10 GB × 900 s = 9000 GB-seconds disk overage.+ eq(t, "disk overage", totals.DiskOverageGBSeconds, 9000)+}++func TestIntegrateBucket_segmentedTimeline(t *testing.T) {+ bs, be := canonicalBucket()+ // Mid-bucket scaling:+ // [000s, 300s) one 8 GB sandbox running+ // [300s, 600s) empty+ // [600s, 900s) one 4 GB sandbox running+ // reserved=0.+ totals := IntegrateBucket(bs, be, 0, []db.ScaleEvent{+ eventAt(8192, 20480, 0, 300),+ eventAt(4096, 20480, 600, 900),+ })+ // Segment 1: 8 GB × 300 s = 2400 at tier 8192.+ // Segment 3: 4 GB × 300 s = 1200 at tier 4096.+ eq(t, "tier 8192", totals.OverageGBSecondsByTier[8192], 2400)+ eq(t, "tier 4096", totals.OverageGBSecondsByTier[4096], 1200)+}++func TestIntegrateBucket_eventClippedToBucket(t *testing.T) {+ bs, be := canonicalBucket()+ // Event spans 60 s before bucket through 60 s after. Should clip+ // to the full bucket (900 s).+ base := time.Date(2030, 6, 1, 0, 0, 0, 0, time.UTC)+ preStart := base.Add(-60 * time.Second)+ postEnd := base.Add(960 * time.Second)+ totals := IntegrateBucket(bs, be, 0, []db.ScaleEvent{+ {MemoryMB: 8192, DiskMB: 20480, StartedAt: preStart, EndedAt: &postEnd},+ })+ eq(t, "tier 8192 (clipped to bucket)", totals.OverageGBSecondsByTier[8192], 7200)+}++func TestIntegrateBucket_openEvent(t *testing.T) {+ bs, be := canonicalBucket()+ // Event with EndedAt=nil (still open) starting mid-bucket. Should+ // run until bucket_end.+ base := time.Date(2030, 6, 1, 0, 0, 0, 0, time.UTC)+ totals := IntegrateBucket(bs, be, 0, []db.ScaleEvent{+ {MemoryMB: 8192, DiskMB: 20480, StartedAt: base.Add(450 * time.Second), EndedAt: nil},+ })+ // 8 GB × 450 s (00:07:30 → 00:15:00) = 3600.+ eq(t, "tier 8192 open", totals.OverageGBSecondsByTier[8192], 3600)+}++func TestIntegrateBucket_emptyBucket(t *testing.T) {+ bs, be := canonicalBucket()+ totals := IntegrateBucket(bs, be, 0, nil)+ if len(totals.OverageGBSecondsByTier) != 0 {+ t.Errorf("expected empty overage, got %v", totals.OverageGBSecondsByTier)+ }+ eq(t, "disk", totals.DiskOverageGBSeconds, 0)+ eq(t, "floor", totals.ReservedFloorGBSeconds, 0)+}++func TestIntegrateBucket_reservationOnly_bucketEmittedFromReservedFloor(t *testing.T) {+ // Reservation with no scale events: emitter still must emit the+ // reserved_usage row from the bucket-level call site, but the walk+ // itself produces no overage and no floor (no usage to account for).+ bs, be := canonicalBucket()+ totals := IntegrateBucket(bs, be, 8, nil)+ if len(totals.OverageGBSecondsByTier) != 0 {+ t.Errorf("expected no overage, got %v", totals.OverageGBSecondsByTier)+ }+ eq(t, "disk", totals.DiskOverageGBSeconds, 0)+ // The walk itself doesn't manufacture floor when there's no usage —+ // the emitter charges the full reservedGb × 900 separately. This+ // behaviour is what lets the reserved row stay independent of+ // whether the customer actually used the capacity.+ eq(t, "floor", totals.ReservedFloorGBSeconds, 0)+}++func TestIntegrateBucket_sumOfSharesAlwaysOne(t *testing.T) {+ // Property: at any segment with usage > reservedGb, the per-tier+ // overage shares add up to the total spike × secs exactly. This is+ // the invariant that lets the unified pipeline reproduce the legacy+ // per-tier totals when reservedGb=0.+ bs, be := canonicalBucket()+ cases := []struct {+ name string+ reserved int+ events []db.ScaleEvent+ }{+ {"three tiers concurrent", 4, []db.ScaleEvent{+ eventAt(4096, 20480, 0, 900),+ eventAt(8192, 20480, 0, 900),+ eventAt(16384, 20480, 0, 900),+ }},+ {"two tiers staggered", 8, []db.ScaleEvent{+ eventAt(8192, 20480, 0, 900),+ eventAt(16384, 20480, 300, 900),+ }},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ totals := IntegrateBucket(bs, be, tc.reserved, tc.events)+ // Brute force: integrate the spike second-by-second and+ // confirm the sum matches.+ expected := 0.0+ for sec := 0; sec < 900; sec++ {+ usageGB := 0+ for _, e := range tc.events {+ base := time.Date(2030, 6, 1, 0, 0, 0, 0, time.UTC)+ t0 := e.StartedAt+ t1 := *e.EndedAt+ tNow := base.Add(time.Duration(sec) * time.Second)+ if !tNow.Before(t0) && tNow.Before(t1) {+ usageGB += e.MemoryMB / 1024+ }+ }+ if usageGB > tc.reserved {+ expected += float64(usageGB - tc.reserved)+ }+ }+ actual := 0.0+ for _, gbs := range totals.OverageGBSecondsByTier {+ actual += gbs+ }+ eq(t, "sum-of-shares == brute-force spike", actual, expected)+ })+ }+}diff --git a/internal/billing/pricing.go b/internal/billing/pricing.goindex 508310cc..62db397b 100644--- a/internal/billing/pricing.go+++ b/internal/billing/pricing.go@@ -59,6 +59,41 @@ const (DiskOverageMetadataKey = "sandbox_disk_overage")+// --- Phase-3 unified pipeline meters ---+//+// New orgs (`billing_mode='unified'`, default per migration 031) are+// billed via two flat meters with `unit = GB-seconds`:+//+// - Reserved: customer-facing name "pre-booked." Only orgs that+// reserve capacity pay this.+// - Overage: customer-facing name "instant." Flat per-GB rate+// regardless of sandbox tier.+//+// **Dollar rates are deliberately not in code.** Stripe Prices are+// configured in the Stripe Dashboard (or via Stripe API by the+// pricing team) and linked to the meters below. The sender ships+// meter events with `value = GB-seconds`; Stripe computes invoice+// dollars from Price × value at billing time. This decouples+// pricing changes from code deploys.+//+// **Existing orgs (`billing_mode='legacy'`) are completely unaffected+// by these meters.** They continue to bill via `TierPricePerSecond`+// and the legacy `sandbox_compute_<tier>` meters through+// `UsageReporter`. The dollar amounts in `TierPricePerSecond` stay+// in code because free-tier credit deduction+// (`CalculateUsageCostCents`) computes cents locally without a+// Stripe round-trip — a real reason for those constants. Phase 3+// just doesn't add new ones.+const (+ // Pre-booked: single meter, no tier breakdown.+ ReservedMeterKey = "sandbox_reserved"+ ReservedPriceKey = "sandbox_reserved_v1"++ // Instant (overage): single meter, flat across all sandbox sizes.+ OverageMeterKey = "sandbox_overage"+ OveragePriceKey = "sandbox_overage_v1"+)+// DiskOverageGBSeconds returns the chargeable GB-seconds for one usage summary// row (zero if the sandbox stayed within the free allowance).func DiskOverageGBSeconds(s db.OrgUsageSummary) float64 {diff --git a/internal/billing/stripe.go b/internal/billing/stripe.goindex ea7ca527..a66b391d 100644--- a/internal/billing/stripe.go+++ b/internal/billing/stripe.go@@ -34,6 +34,20 @@ type StripeClient struct {// Disk overage meter / price (single dimension: GB-seconds above 20GB).DiskOveragePriceID stringDiskOverageMeterEventName string++ // Phase-3 unified-pipeline meters and prices. Two flat meters+ // (overage + reserved) used by new orgs (`billing_mode='unified'`).+ // Legacy per-tier meters above are untouched and continue to serve+ // existing orgs via UsageReporter.+ OveragePriceID string // flat overage Price for `overage_usage` events+ OverageMeterEventName string // "sandbox_compute_sandbox_overage"+ ReservedPriceID string // flat reserved Price for `reserved_usage` events+ ReservedMeterEventName string // "sandbox_compute_sandbox_reserved"++ // Per-agent paywalled-feature prices. Configured from env and+ // referenced by name from the dashboard subscribe handlers. Empty+ // string means the feature is not gated on this deployment (dev mode).+ TelegramAgentPriceID string // recurring $20/mo price for the per-agent Telegram feature}// NewStripeClient creates a new Stripe client.@@ -222,9 +236,64 @@ func (s *StripeClient) EnsureProducts() error {log.Printf("billing: created disk overage price (id=%s)", p.ID)}+ // 5. Phase-3 unified-pipeline meters. Two flat meters (overage ++ // reserved) at unit GB-seconds. Code creates the *meters* (their+ // event names are stable wire-protocol coupling) but **does not+ // create Prices** — those are configured in the Stripe Dashboard+ // so pricing changes don't need a code deploy. The Price IDs+ // are discovered below if present; if missing, meter events+ // still flow but won't appear on invoices until a Price is+ // linked to the meter in Stripe.+ s.OverageMeterEventName = ensureMeter(existingMeters, "sandbox_compute_"+OverageMeterKey, "Sandbox Instant Compute (GB-seconds)")+ s.ReservedMeterEventName = ensureMeter(existingMeters, "sandbox_compute_"+ReservedMeterKey, "Sandbox Reserved Capacity (GB-seconds)")++ if id, ok := existingPrices[OveragePriceKey]; ok {+ s.OveragePriceID = id+ log.Printf("billing: found existing overage price (id=%s)", id)+ } else {+ log.Printf("billing: no overage price configured for meter %s — meter events will flow but won't appear on invoices until a Price is created in Stripe", s.OverageMeterEventName)+ }+ if id, ok := existingPrices[ReservedPriceKey]; ok {+ s.ReservedPriceID = id+ log.Printf("billing: found existing reserved price (id=%s)", id)+ } else {+ log.Printf("billing: no reserved price configured for meter %s — meter events will flow but won't appear on invoices until a Price is created in Stripe", s.ReservedMeterEventName)+ }+return nil}+// ensureMeter is a small helper that returns the event_name after+// creating or finding the meter. Used only for the phase-3 flat+// meters; legacy per-tier meters retain their inline creation so the+// unrelated stripe.go diff stays small.+func ensureMeter(existing map[string]*stripe.BillingMeter, eventName, displayName string) string {+ if m, ok := existing[eventName]; ok {+ log.Printf("billing: found existing meter %s (id=%s)", eventName, m.ID)+ return eventName+ }+ m, err := meter.New(&stripe.BillingMeterParams{+ DisplayName: stripe.String(displayName),+ EventName: stripe.String(eventName),+ DefaultAggregation: &stripe.BillingMeterDefaultAggregationParams{+ Formula: stripe.String(string(stripe.BillingMeterDefaultAggregationFormulaSum)),+ },+ CustomerMapping: &stripe.BillingMeterCustomerMappingParams{+ EventPayloadKey: stripe.String("stripe_customer_id"),+ Type: stripe.String(string(stripe.BillingMeterCustomerMappingTypeByID)),+ },+ ValueSettings: &stripe.BillingMeterValueSettingsParams{+ EventPayloadKey: stripe.String("value"),+ },+ })+ if err != nil {+ log.Printf("billing: WARN failed to create meter %s: %v", eventName, err)+ return eventName // return name anyway; sender will fail loudly if used+ }+ log.Printf("billing: created meter %s (id=%s)", eventName, m.ID)+ return eventName+}+// CreateCustomer creates a Stripe customer for an org.func (s *StripeClient) CreateCustomer(orgName, email string) (string, error) {params := &stripe.CustomerParams{@@ -275,7 +344,10 @@ func (s *StripeClient) CreatePortalSession(customerID, returnURL string) (string}// CreateSubscription creates a subscription with metered prices for all tiers.-// Returns subscription ID and map of memoryMB → subscription item ID.+// Returns subscription ID and map of memoryMB → subscription item ID+// (legacy per-second tier items only; phase-3 overage/reserved items+// are added to the subscription but not returned in the map since+// `org_subscription_items` only tracks the legacy mapping).func (s *StripeClient) CreateSubscription(customerID string) (string, map[int]string, error) {var items []*stripe.SubscriptionItemsParamsfor _, priceID := range s.PriceIDs {@@ -288,6 +360,21 @@ func (s *StripeClient) CreateSubscription(customerID string) (string, map[int]stPrice: stripe.String(s.DiskOveragePriceID),})}+ // Phase-3 unified-pipeline items: flat overage + flat reserved.+ // New orgs default to `billing_mode='unified'` so meter events+ // flow to these items. Existing legacy orgs sit at zero usage+ // on these line items (Stripe omits zero-usage rows from invoices,+ // so they're invisible to the customer).+ if s.OveragePriceID != "" {+ items = append(items, &stripe.SubscriptionItemsParams{+ Price: stripe.String(s.OveragePriceID),+ })+ }+ if s.ReservedPriceID != "" {+ items = append(items, &stripe.SubscriptionItemsParams{+ Price: stripe.String(s.ReservedPriceID),+ })+ }sub, err := subscription.New(&stripe.SubscriptionParams{Customer: stripe.String(customerID),@@ -346,6 +433,34 @@ func (s *StripeClient) ReportUsage(customerID string, memoryMB int, seconds int6return nil}+// ReportMeterEvent sends a single Stripe meter event with an+// idempotency identifier. Used by the phase-3 sender to ship outbox+// rows; the identifier (typically `billable_events.id`) makes+// at-least-once shipping safe — Stripe dedups repeated submissions+// of the same identifier within 24h.+//+// Returns the resulting BillingMeterEvent.Identifier echo'd by Stripe+// (which equals the input on successful submission). Caller stores+// this in `billable_events.stripe_event_id` for traceability.+func (s *StripeClient) ReportMeterEvent(eventName, customerID string, value float64, identifier string, timestamp int64) (string, error) {+ resp, err := meterevent.New(&stripe.BillingMeterEventParams{+ EventName: stripe.String(eventName),+ Identifier: stripe.String(identifier),+ Timestamp: stripe.Int64(timestamp),+ Payload: map[string]string{+ "stripe_customer_id": customerID,+ // Stripe accepts string-encoded values; use a high-precision+ // format so fractional GB-seconds (the proportional split+ // produces them) don't get truncated to integers.+ "value": fmt.Sprintf("%.6f", value),+ },+ })+ if err != nil {+ return "", fmt.Errorf("report meter event %s: %w", eventName, err)+ }+ return resp.Identifier, nil+}+// ReportDiskOverageUsage sends a meter event for disk overage GB-seconds// (provisioned disk above 20GB, integrated over time).func (s *StripeClient) ReportDiskOverageUsage(customerID string, gbSeconds int64, timestamp int64) error {@@ -366,6 +481,13 @@ func (s *StripeClient) ReportDiskOverageUsage(customerID string, gbSeconds int64return nil}+// SuccessURL returns the configured Stripe Checkout success URL. Public+// because per-feature subscribe handlers reuse the same redirect targets.+func (s *StripeClient) SuccessURL() string { return s.successURL }++// CancelURL returns the configured Stripe Checkout cancel URL.+func (s *StripeClient) CancelURL() string { return s.cancelURL }+// GetCustomerBalance returns the customer's balance in cents (negative = credit).func (s *StripeClient) GetCustomerBalance(customerID string) (int64, error) {c, err := customer.Get(customerID, nil)@@ -375,6 +497,138 @@ func (s *StripeClient) GetCustomerBalance(customerID string) (int64, error) {return c.Balance, nil}+// GetCustomerDefaultPaymentMethod returns the saved default payment+// method ID for a customer, or "" if none is on file. Used by the+// per-agent subscribe flow: with a card on file we can call subscriptions.New+// directly; without one we have to bounce through Stripe Checkout.+func (s *StripeClient) GetCustomerDefaultPaymentMethod(customerID string) (string, error) {+ c, err := customer.Get(customerID, nil)+ if err != nil {+ return "", err+ }+ if c.InvoiceSettings != nil && c.InvoiceSettings.DefaultPaymentMethod != nil {+ return c.InvoiceSettings.DefaultPaymentMethod.ID, nil+ }+ return "", nil+}++// CreateAgentFeatureSubscription creates a per-agent paywalled-feature+// subscription using a saved payment method. Caller must have verified+// a default payment method exists (via GetCustomerDefaultPaymentMethod).+//+// metadata is stamped onto the Stripe Subscription so the webhook+// handler can route updates back to the right (org, agent, feature)+// triple without a DB lookup. Caller passes (org_id, agent_id, feature, type).+//+// Returns the Stripe subscription. Status will typically be "active"+// (paid immediately), or "incomplete" if the saved card was declined —+// callers should check.+func (s *StripeClient) CreateAgentFeatureSubscription(+ customerID, priceID string,+ metadata map[string]string,+) (*stripe.Subscription, error) {+ params := &stripe.SubscriptionParams{+ Customer: stripe.String(customerID),+ Items: []*stripe.SubscriptionItemsParams{{+ Price: stripe.String(priceID),+ }},+ // Charge the saved card immediately. Subscription becomes+ // active on first invoice payment success.+ PaymentBehavior: stripe.String("error_if_incomplete"),+ }+ for k, v := range metadata {+ params.AddMetadata(k, v)+ }+ sub, err := subscription.New(params)+ if err != nil {+ return nil, fmt.Errorf("create agent-feature subscription: %w", err)+ }+ return sub, nil+}++// CreateAgentFeatureCheckoutSession redirects the customer to Stripe+// Checkout to add a payment method AND start the subscription+// atomically. Used when the customer has no card on file.+//+// metadata is propagated to both the Checkout Session and (via+// SubscriptionData) the resulting Subscription so the webhook can wire+// it back to the right agent on completion.+func (s *StripeClient) CreateAgentFeatureCheckoutSession(+ customerID, priceID string,+ successURL, cancelURL string,+ metadata map[string]string,+) (string, error) {+ params := &stripe.CheckoutSessionParams{+ Customer: stripe.String(customerID),+ Mode: stripe.String(string(stripe.CheckoutSessionModeSubscription)),+ SuccessURL: stripe.String(successURL),+ CancelURL: stripe.String(cancelURL),+ LineItems: []*stripe.CheckoutSessionLineItemParams{{+ Price: stripe.String(priceID),+ Quantity: stripe.Int64(1),+ }},+ SubscriptionData: &stripe.CheckoutSessionSubscriptionDataParams{},+ }+ for k, v := range metadata {+ params.AddMetadata(k, v)+ params.SubscriptionData.AddMetadata(k, v)+ }+ sess, err := checkoutsession.New(params)+ if err != nil {+ return "", fmt.Errorf("create agent-feature checkout: %w", err)+ }+ return sess.URL, nil+}++// FindAgentFeatureSubscription looks up an active subscription on a+// customer for a given (agent_id, feature) combo, identified by the+// metadata stamps we set at create time. Used by the reconciliation+// path: if our local DB lost a row (webhook never arrived because+// STRIPE_WEBHOOK_SECRET wasn't set, network blip, etc.), Stripe is+// the source of truth and we re-import from there.+func (s *StripeClient) FindAgentFeatureSubscription(customerID, agentID, feature string) (*stripe.Subscription, error) {+ iter := subscription.List(&stripe.SubscriptionListParams{+ Customer: stripe.String(customerID),+ Status: stripe.String("all"), // include past_due/incomplete; caller decides+ })+ for iter.Next() {+ sub := iter.Subscription()+ if sub.Metadata == nil {+ continue+ }+ if sub.Metadata["agent_id"] == agentID && sub.Metadata["feature"] == feature {+ // Return the first (most recent — Stripe lists newest-first).+ // Caller handles status filtering.+ return sub, nil+ }+ }+ if err := iter.Err(); err != nil {+ return nil, fmt.Errorf("list subscriptions: %w", err)+ }+ return nil, nil+}++// CancelAgentFeatureSubscription cancels a Stripe subscription. By+// default cancels at period end so the customer keeps the feature+// until the end of what they've paid for. Pass immediate=true to cut+// service off now (used by the disconnect-on-payment-failure flow).+func (s *StripeClient) CancelAgentFeatureSubscription(subscriptionID string, immediate bool) (*stripe.Subscription, error) {+ if immediate {+ sub, err := subscription.Cancel(subscriptionID, nil)+ if err != nil {+ return nil, fmt.Errorf("cancel subscription: %w", err)+ }+ return sub, nil+ }+ sub, err := subscription.Update(subscriptionID, &stripe.SubscriptionParams{+ CancelAtPeriodEnd: stripe.Bool(true),+ })+ if err != nil {+ return nil, fmt.Errorf("schedule subscription cancel: %w", err)+ }+ return sub, nil+}+// ListInvoices returns past invoices for a customer.func (s *StripeClient) ListInvoices(customerID string, limit int) ([]*stripe.Invoice, error) {params := &stripe.InvoiceListParams{diff --git a/internal/blobstore/azure.go b/internal/blobstore/azure.gonew file mode 100644index 00000000..86eb2590--- /dev/null+++ b/internal/blobstore/azure.go@@ -0,0 +1,204 @@+package blobstore++import (+ "context"+ "fmt"+ "io"+ "strings"+ "sync"++ "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"+ "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/bloberror"+)++// AzureConfig configures an Azure Blob backend.+type AzureConfig struct {+ Name string // logging label, e.g. "azure-blob"+ AccountName string+ AccountKey string++ // Bucket (Azure container), if set, overrides any bucket argument passed+ // at runtime. Use this to give the Azure backend its own container name+ // — e.g. caller uses Tigris bucket "opencomputer-prod" but the Azure+ // fallback should read from container "checkpoints".+ Bucket string+}++// azureStore implements Store against Azure Blob Storage. We dial the SDK+// lazily on first use so a worker that never touches the fallback never+// opens an Azure connection (and never logs Azure 401s if creds are wrong).+type azureStore struct {+ name string+ bucket string // container override; empty means use caller's runtime bucket+ connStr string++ mu sync.Mutex+ client *azblob.Client+}++// NewAzure constructs an Azure Blob backed Store. Returns nil, nil when+// account + key are both empty (caller treats nil as "this backend+// disabled, fall through to next").+func NewAzure(cfg AzureConfig) (Store, error) {+ if cfg.AccountName == "" && cfg.AccountKey == "" {+ return nil, nil+ }+ if cfg.AccountName == "" || cfg.AccountKey == "" {+ return nil, fmt.Errorf("blobstore: Azure requires both AccountName and AccountKey")+ }+ if cfg.Name == "" {+ cfg.Name = "azure-blob"+ }+ connStr := fmt.Sprintf(+ "DefaultEndpointsProtocol=https;AccountName=%s;AccountKey=%s;EndpointSuffix=core.windows.net",+ cfg.AccountName, cfg.AccountKey,+ )+ return &azureStore{name: cfg.Name, bucket: cfg.Bucket, connStr: connStr}, nil+}++func (a *azureStore) Name() string { return a.name }++// resolveBucket returns the configured container if set, else the caller's bucket.+func (a *azureStore) resolveBucket(bucket string) string {+ if a.bucket != "" {+ return a.bucket+ }+ return bucket+}++func (a *azureStore) ensureClient() error {+ a.mu.Lock()+ defer a.mu.Unlock()+ if a.client != nil {+ return nil+ }+ c, err := azblob.NewClientFromConnectionString(a.connStr, nil)+ if err != nil {+ return fmt.Errorf("%s connect: %w", a.name, err)+ }+ a.client = c+ return nil+}++// normalizeKey strips a leading "<bucket>/" if present. S3-style keys often+// embed the bucket name (e.g. "checkpoints/sb-xxx/..."); Azure addresses+// container + blob name separately, so we drop the redundant prefix.+func normalizeKey(bucket, key string) string {+ if trimmed, ok := strings.CutPrefix(key, bucket+"/"); ok {+ return trimmed+ }+ return key+}++func (a *azureStore) wrapNotFound(err error, bucket, key, op string) error {+ if err == nil {+ return nil+ }+ if bloberror.HasCode(err, bloberror.BlobNotFound) || bloberror.HasCode(err, bloberror.ContainerNotFound) {+ return fmt.Errorf("%s://%s/%s: %w", a.name, bucket, key, ErrNotFound)+ }+ return fmt.Errorf("%s %s %s/%s: %w", a.name, op, bucket, key, err)+}++func (a *azureStore) Get(ctx context.Context, bucket, key string) (io.ReadCloser, error) {+ if err := a.ensureClient(); err != nil {+ return nil, err+ }+ c := a.resolveBucket(bucket)+ resp, err := a.client.DownloadStream(ctx, c, normalizeKey(c, key), nil)+ if err != nil {+ return nil, a.wrapNotFound(err, c, key, "DownloadStream")+ }+ return resp.Body, nil+}++func (a *azureStore) GetRange(ctx context.Context, bucket, key string, offset, length int64) (io.ReadCloser, error) {+ if err := a.ensureClient(); err != nil {+ return nil, err+ }+ c := a.resolveBucket(bucket)+ resp, err := a.client.DownloadStream(ctx, c, normalizeKey(c, key), &azblob.DownloadStreamOptions{+ Range: azblob.HTTPRange{Offset: offset, Count: length},+ })+ if err != nil {+ return nil, a.wrapNotFound(err, c, key, "DownloadStream(range)")+ }+ return resp.Body, nil+}++// uploadStreamOpts is shared by every Put. The Azure SDK's nil-default is+// BlockSize=1MB / Concurrency=1, a serial chain of small PutBlock calls that's+// HTTP-overhead bound at 30–60 MB/s per blob — that turned a 10 GB checkpoint+// into a 5+ minute upload. The values below are sized for a 64-vCPU worker+// (D-series, ~30 Gbps NIC, Premium SSD ~700 MB/s read):+//+// - BlockSize 8 MB amortizes PutBlock HTTP overhead (~10x fewer round-trips+// than the SDK default); per-blob in-flight memory stays bounded under+// concurrent uploads.+// - Concurrency 8 keeps the worker NIC fed when HTTP latency dominates a+// single block. Per-upload buffer is 8 × 8 MB = 64 MB, negligible vs RAM.+//+// Practical ceiling per blob is ~600–1000 MB/s — already above the disk-read+// rate at which bytes can be fed from the on-disk archive. Bumping further+// just wastes memory.+var azureUploadStreamOpts = &azblob.UploadStreamOptions{+ BlockSize: 8 * 1024 * 1024,+ Concurrency: 8,+}++func (a *azureStore) Put(ctx context.Context, bucket, key string, body io.Reader, contentLength int64) error {+ if err := a.ensureClient(); err != nil {+ return err+ }+ c := a.resolveBucket(bucket)+ _, err := a.client.UploadStream(ctx, c, normalizeKey(c, key), body, azureUploadStreamOpts)+ if err != nil {+ return fmt.Errorf("%s UploadStream %s/%s: %w", a.name, c, key, err)+ }+ return nil+}++func (a *azureStore) Head(ctx context.Context, bucket, key string) (int64, error) {+ if err := a.ensureClient(); err != nil {+ return 0, err+ }+ c := a.resolveBucket(bucket)+ resp, err := a.client.ServiceClient().+ NewContainerClient(c).+ NewBlobClient(normalizeKey(c, key)).+ GetProperties(ctx, nil)+ if err != nil {+ return 0, a.wrapNotFound(err, c, key, "GetProperties")+ }+ if resp.ContentLength == nil {+ return 0, nil+ }+ return *resp.ContentLength, nil+}++func (a *azureStore) Exists(ctx context.Context, bucket, key string) (bool, error) {+ _, err := a.Head(ctx, bucket, key)+ if err == nil {+ return true, nil+ }+ if isNotFound(err) {+ return false, nil+ }+ return false, err+}++func (a *azureStore) Delete(ctx context.Context, bucket, key string) error {+ if err := a.ensureClient(); err != nil {+ return err+ }+ c := a.resolveBucket(bucket)+ _, err := a.client.DeleteBlob(ctx, c, normalizeKey(c, key), nil)+ if err != nil {+ // Idempotent: not-found is success.+ if bloberror.HasCode(err, bloberror.BlobNotFound) {+ return nil+ }+ return fmt.Errorf("%s DeleteBlob %s/%s: %w", a.name, c, key, err)+ }+ return nil+}diff --git a/internal/blobstore/fallback.go b/internal/blobstore/fallback.goindex 199b3452..2dbc6a67 100644--- a/internal/blobstore/fallback.go+++ b/internal/blobstore/fallback.go@@ -9,25 +9,45 @@ import ()// FallbackStore wraps a primary Store with one or more fallback Stores.-// Read operations (Get, Exists) try the primary first; on transient-// errors (network, 5xx) they cascade through fallbacks. NotFound is-// authoritative — we don't try fallbacks for missing objects.+// Reads (Get / GetRange / Head / Exists) try the primary first; on transient+// errors (network, 5xx) they cascade through fallbacks. NotFound is normally+// authoritative on primary — we don't try fallbacks for missing objects —+// because resurrecting deleted state from a stale mirror is surprising.//-// Writes (Put) go to the primary only — multi-write would create-// consistency challenges and is overkill for the use case.+// During a backend migration (e.g. lazy Tigris cutover with Azure as the+// safety net), set TryFallbacksOnNotFound=true so a miss on primary falls+// through to fallbacks. Flip back to false once the soak window closes.//-// Use case: configure Tigris as primary, R2 as fallback. If Tigris has-// an outage, golden pulls keep working from the R2 mirror (assuming-// you've populated it; that's an upload-side concern out of scope here).+// Writes (Put / Delete) go to the primary only — dual-write would create+// consistency challenges and is overkill for the migration use case.+//+// Use case: Tigris primary, Azure fallback during cutover. While running+// FallbackStore in migration mode, any cold key that hasn't yet been+// rclone-synced into Tigris transparently fetches from Azure.type FallbackStore struct {- primary Store- fallbacks []Store+ primary Store+ fallbacks []Store+ TryFallbacksOnNotFound bool}-// NewFallback wraps primary with fallback Stores. Nil primary is an error;-// nil entries in fallbacks are ignored (so callers can pass disabled-// backends without filtering).+// NewFallback wraps primary with fallback Stores in HA mode: fallbacks are+// consulted only on transient errors from primary. NotFound on primary is+// authoritative. Nil primary is an error; nil entries in fallbacks are+// ignored (so callers can pass disabled backends without filtering).func NewFallback(primary Store, fallbacks ...Store) (Store, error) {+ return newFallback(false, primary, fallbacks...)+}++// NewMigrationFallback wraps primary with fallback Stores in migration mode:+// NotFound on primary cascades through fallbacks too. Use during a backend+// cutover where the primary is being lazily populated (e.g. Tigris primary,+// Azure fallback during the soak window). Switch back to NewFallback (or+// remove the fallback entirely) once the migration completes.+func NewMigrationFallback(primary Store, fallbacks ...Store) (Store, error) {+ return newFallback(true, primary, fallbacks...)+}++func newFallback(migrationMode bool, primary Store, fallbacks ...Store) (Store, error) {if primary == nil {return nil, errors.New("blobstore: FallbackStore requires non-nil primary")}@@ -40,7 +60,11 @@ func NewFallback(primary Store, fallbacks ...Store) (Store, error) {if len(cleaned) == 0 {return primary, nil // no fallbacks configured — just return primary}- return &FallbackStore{primary: primary, fallbacks: cleaned}, nil+ return &FallbackStore{+ primary: primary,+ fallbacks: cleaned,+ TryFallbacksOnNotFound: migrationMode,+ }, nil}func (f *FallbackStore) Name() string {@@ -51,13 +75,24 @@ func (f *FallbackStore) Name() string {return names}+// shouldFallThrough is the shared policy across read methods. Transient+// errors always cascade. NotFound only cascades when migration mode is on.+func (f *FallbackStore) shouldFallThrough(err error) bool {+ if err == nil {+ return false+ }+ if errors.Is(err, ErrNotFound) {+ return f.TryFallbacksOnNotFound+ }+ return true+}+func (f *FallbackStore) Get(ctx context.Context, bucket, key string) (io.ReadCloser, error) {r, err := f.primary.Get(ctx, bucket, key)if err == nil {return r, nil}- if errors.Is(err, ErrNotFound) {- // Authoritative — primary says it doesn't exist. Don't ask fallbacks.+ if !f.shouldFallThrough(err) {return nil, err}for i, fb := range f.fallbacks {@@ -68,8 +103,29 @@ func (f *FallbackStore) Get(ctx context.Context, bucket, key string) (io.ReadCloreturn r2, nil}if errors.Is(err2, ErrNotFound) {- // Fallback also says missing — call it ErrNotFound. Probably means- // the fallback isn't populated; surface so caller can decide.+ return nil, err2+ }+ err = err2+ }+ return nil, fmt.Errorf("blobstore: all backends failed: %w", err)+}++func (f *FallbackStore) GetRange(ctx context.Context, bucket, key string, offset, length int64) (io.ReadCloser, error) {+ r, err := f.primary.GetRange(ctx, bucket, key, offset, length)+ if err == nil {+ return r, nil+ }+ if !f.shouldFallThrough(err) {+ return nil, err+ }+ for i, fb := range f.fallbacks {+ log.Printf("blobstore: primary %s GetRange failed (%v); trying fallback %s [%d/%d]",+ f.primary.Name(), err, fb.Name(), i+1, len(f.fallbacks))+ r2, err2 := fb.GetRange(ctx, bucket, key, offset, length)+ if err2 == nil {+ return r2, nil+ }+ if errors.Is(err2, ErrNotFound) {return nil, err2}err = err2@@ -82,17 +138,59 @@ func (f *FallbackStore) Put(ctx context.Context, bucket, key string, body io.Reareturn f.primary.Put(ctx, bucket, key, body, contentLength)}+func (f *FallbackStore) Head(ctx context.Context, bucket, key string) (int64, error) {+ n, err := f.primary.Head(ctx, bucket, key)+ if err == nil {+ return n, nil+ }+ if !f.shouldFallThrough(err) {+ return 0, err+ }+ for _, fb := range f.fallbacks {+ n2, err2 := fb.Head(ctx, bucket, key)+ if err2 == nil {+ return n2, nil+ }+ if errors.Is(err2, ErrNotFound) {+ return 0, err2+ }+ err = err2+ }+ return 0, err+}+func (f *FallbackStore) Exists(ctx context.Context, bucket, key string) (bool, error) {ok, err := f.primary.Exists(ctx, bucket, key)if err == nil {- return ok, nil+ if ok || !f.TryFallbacksOnNotFound {+ return ok, nil+ }+ // Primary returned (false, nil) — "not found" but no error. In migration+ // mode, treat that the same as ErrNotFound and ask fallbacks too.+ }+ if err != nil && !f.shouldFallThrough(err) {+ return false, err}for _, fb := range f.fallbacks {ok2, err2 := fb.Exists(ctx, bucket, key)if err2 == nil {- return ok2, nil+ if ok2 {+ return true, nil+ }+ continue}err = err2}- return false, err+ if err != nil {+ return false, err+ }+ return false, nil+}++func (f *FallbackStore) Delete(ctx context.Context, bucket, key string) error {+ // Deletes go only to primary. Migration mode does not propagate deletes+ // to the fallback — that would defeat lazy migration by removing the+ // authoritative copy from the old backend before its data is fully+ // mirrored.+ return f.primary.Delete(ctx, bucket, key)}diff --git a/internal/blobstore/fallback_live_test.go b/internal/blobstore/fallback_live_test.gonew file mode 100644index 00000000..7f3c83fa--- /dev/null+++ b/internal/blobstore/fallback_live_test.go@@ -0,0 +1,94 @@+package blobstore_test++import (+ "context"+ "errors"+ "io"+ "os"+ "testing"+ "time"++ "github.com/opensandbox/opensandbox/internal/blobstore"+)++// TestFallback_LiveMigration exercises NewMigrationFallback against a real+// Tigris primary + Azure fallback. Skipped unless these env vars are set:+//+// BLOBSTORE_TEST_ENDPOINT https://t3.storage.dev+// BLOBSTORE_TEST_ACCESS_KEY tid_...+// BLOBSTORE_TEST_SECRET_KEY tsec_...+// BLOBSTORE_TEST_BUCKET tigris bucket name+// BLOBSTORE_TEST_AZURE_ACCOUNT azure storage account name+// BLOBSTORE_TEST_AZURE_KEY azure account key+// BLOBSTORE_TEST_AZURE_CONTAINER azure container override+// BLOBSTORE_TEST_PROBE_KEY a key that exists in Azure but NOT Tigris+//+// Confirms: migration mode falls through to Azure on Tigris NotFound; HA+// mode does NOT fall through.+func TestFallback_LiveMigration(t *testing.T) {+ endpoint := os.Getenv("BLOBSTORE_TEST_ENDPOINT")+ azureAccount := os.Getenv("BLOBSTORE_TEST_AZURE_ACCOUNT")+ probeKey := os.Getenv("BLOBSTORE_TEST_PROBE_KEY")+ if endpoint == "" || azureAccount == "" || probeKey == "" {+ t.Skip("BLOBSTORE_TEST_* + AZURE_* + PROBE_KEY env not set; skipping live migration smoke")+ }++ primary, err := blobstore.NewS3(blobstore.S3Config{+ Name: "tigris",+ Endpoint: endpoint,+ Region: "auto",+ AccessKeyID: os.Getenv("BLOBSTORE_TEST_ACCESS_KEY"),+ SecretAccessKey: os.Getenv("BLOBSTORE_TEST_SECRET_KEY"),+ UsePathStyle: true,+ Bucket: os.Getenv("BLOBSTORE_TEST_BUCKET"),+ })+ if err != nil {+ t.Fatalf("NewS3 primary: %v", err)+ }+ fallback, err := blobstore.NewAzure(blobstore.AzureConfig{+ Name: "azure-blob",+ AccountName: azureAccount,+ AccountKey: os.Getenv("BLOBSTORE_TEST_AZURE_KEY"),+ Bucket: os.Getenv("BLOBSTORE_TEST_AZURE_CONTAINER"),+ })+ if err != nil {+ t.Fatalf("NewAzure fallback: %v", err)+ }++ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)+ defer cancel()++ t.Run("MigrationMode_FallsThroughOnNotFound", func(t *testing.T) {+ store, err := blobstore.NewMigrationFallback(primary, fallback)+ if err != nil {+ t.Fatalf("NewMigrationFallback: %v", err)+ }+ // Caller passes the primary's bucket (Tigris); fallback override+ // rewrites to its own container.+ r, err := store.Get(ctx, "ignored-because-overridden", probeKey)+ if err != nil {+ t.Fatalf("Get via migration fallback: %v", err)+ }+ body, err := io.ReadAll(r)+ r.Close()+ if err != nil {+ t.Fatalf("read: %v", err)+ }+ if len(body) == 0 {+ t.Fatalf("expected non-empty body from Azure fallback, got 0 bytes")+ }+ t.Logf("MIGRATION: fetched %d bytes from %s via fallback chain (probe=%q)", len(body), store.Name(), probeKey)+ })++ t.Run("HAMode_DoesNotFallThroughOnNotFound", func(t *testing.T) {+ store, err := blobstore.NewFallback(primary, fallback)+ if err != nil {+ t.Fatalf("NewFallback: %v", err)+ }+ _, err = store.Get(ctx, "ignored", probeKey)+ if !errors.Is(err, blobstore.ErrNotFound) {+ t.Fatalf("HA mode: want ErrNotFound (primary authoritative), got %v", err)+ }+ t.Logf("HA: got expected ErrNotFound from primary (no fall-through)")+ })+}diff --git a/internal/blobstore/s3.go b/internal/blobstore/s3.goindex 2f80a60e..f5a9a98b 100644--- a/internal/blobstore/s3.go+++ b/internal/blobstore/s3.go@@ -21,12 +21,19 @@ type S3Config struct {AccessKeyID stringSecretAccessKey stringUsePathStyle bool // true for R2/Tigris/MinIO; false for AWS S3.++ // Bucket, if set, overrides any bucket argument passed at runtime. Use+ // this to give each backend its own bucket name — useful when primary+ // and fallback live in different namespaces (e.g. Tigris bucket+ // "opencomputer-prod" + Azure container "checkpoints").+ Bucket string}// s3Store is an S3-compatible backend.type s3Store struct {- name string- s3 *s3.Client+ name string+ bucket string // override; empty means use caller's runtime bucket+ s3 *s3.Client}// NewS3 constructs an S3-compatible Store. Returns nil, nil if Endpoint@@ -55,41 +62,87 @@ func NewS3(cfg S3Config) (Store, error) {}o.UsePathStyle = cfg.UsePathStyle})- return &s3Store{name: cfg.Name, s3: client}, nil+ return &s3Store{name: cfg.Name, bucket: cfg.Bucket, s3: client}, nil}func (s *s3Store) Name() string { return s.name }+// resolveBucket returns the override if configured, else the caller's bucket.+func (s *s3Store) resolveBucket(bucket string) string {+ if s.bucket != "" {+ return s.bucket+ }+ return bucket+}+func (s *s3Store) Get(ctx context.Context, bucket, key string) (io.ReadCloser, error) {+ b := s.resolveBucket(bucket)out, err := s.s3.GetObject(ctx, &s3.GetObjectInput{- Bucket: &bucket,+ Bucket: &b,Key: &key,})if err != nil {if isNotFound(err) {- return nil, fmt.Errorf("%s://%s/%s: %w", s.name, bucket, key, ErrNotFound)+ return nil, fmt.Errorf("%s://%s/%s: %w", s.name, b, key, ErrNotFound)}- return nil, fmt.Errorf("%s GetObject %s/%s: %w", s.name, bucket, key, err)+ return nil, fmt.Errorf("%s GetObject %s/%s: %w", s.name, b, key, err)+ }+ return out.Body, nil+}++func (s *s3Store) GetRange(ctx context.Context, bucket, key string, offset, length int64) (io.ReadCloser, error) {+ b := s.resolveBucket(bucket)+ rangeStr := fmt.Sprintf("bytes=%d-%d", offset, offset+length-1)+ out, err := s.s3.GetObject(ctx, &s3.GetObjectInput{+ Bucket: &b,+ Key: &key,+ Range: &rangeStr,+ })+ if err != nil {+ if isNotFound(err) {+ return nil, fmt.Errorf("%s://%s/%s: %w", s.name, b, key, ErrNotFound)+ }+ return nil, fmt.Errorf("%s GetObject(range=%s) %s/%s: %w", s.name, rangeStr, b, key, err)}return out.Body, nil}func (s *s3Store) Put(ctx context.Context, bucket, key string, body io.Reader, contentLength int64) error {+ b := s.resolveBucket(bucket)_, err := s.s3.PutObject(ctx, &s3.PutObjectInput{- Bucket: &bucket,+ Bucket: &b,Key: &key,Body: body,ContentLength: &contentLength,})if err != nil {- return fmt.Errorf("%s PutObject %s/%s: %w", s.name, bucket, key, err)+ return fmt.Errorf("%s PutObject %s/%s: %w", s.name, b, key, err)}return nil}+func (s *s3Store) Head(ctx context.Context, bucket, key string) (int64, error) {+ b := s.resolveBucket(bucket)+ out, err := s.s3.HeadObject(ctx, &s3.HeadObjectInput{+ Bucket: &b,+ Key: &key,+ })+ if err != nil {+ if isNotFound(err) {+ return 0, fmt.Errorf("%s://%s/%s: %w", s.name, b, key, ErrNotFound)+ }+ return 0, fmt.Errorf("%s HeadObject %s/%s: %w", s.name, b, key, err)+ }+ if out.ContentLength == nil {+ return 0, nil+ }+ return *out.ContentLength, nil+}+func (s *s3Store) Exists(ctx context.Context, bucket, key string) (bool, error) {+ b := s.resolveBucket(bucket)_, err := s.s3.HeadObject(ctx, &s3.HeadObjectInput{- Bucket: &bucket,+ Bucket: &b,Key: &key,})if err == nil {@@ -98,7 +151,19 @@ func (s *s3Store) Exists(ctx context.Context, bucket, key string) (bool, error)if isNotFound(err) {return false, nil}- return false, fmt.Errorf("%s HeadObject %s/%s: %w", s.name, bucket, key, err)+ return false, fmt.Errorf("%s HeadObject %s/%s: %w", s.name, b, key, err)+}++func (s *s3Store) Delete(ctx context.Context, bucket, key string) error {+ b := s.resolveBucket(bucket)+ _, err := s.s3.DeleteObject(ctx, &s3.DeleteObjectInput{+ Bucket: &b,+ Key: &key,+ })+ if err != nil {+ return fmt.Errorf("%s DeleteObject %s/%s: %w", s.name, b, key, err)+ }+ return nil}// isNotFound matches the various ways the v2 SDK signals 404. The typeddiff --git a/internal/blobstore/s3_smoke_test.go b/internal/blobstore/s3_smoke_test.gonew file mode 100644index 00000000..33953d69--- /dev/null+++ b/internal/blobstore/s3_smoke_test.go@@ -0,0 +1,104 @@+package blobstore_test++import (+ "bytes"+ "context"+ "errors"+ "io"+ "os"+ "testing"+ "time"++ "github.com/opensandbox/opensandbox/internal/blobstore"+)++// TestS3_Smoke exercises Put + Get + Exists against a real S3-compatible+// endpoint. Skipped unless these env vars are set:+//+// BLOBSTORE_TEST_ENDPOINT - e.g. https://t3.storage.dev+// BLOBSTORE_TEST_ACCESS_KEY - access key id+// BLOBSTORE_TEST_SECRET_KEY - secret access key+// BLOBSTORE_TEST_BUCKET - bucket name (must exist)+// BLOBSTORE_TEST_REGION - optional, defaults to "auto"+//+// Designed to run against Tigris but works with any S3-compat backend.+func TestS3_Smoke(t *testing.T) {+ endpoint := os.Getenv("BLOBSTORE_TEST_ENDPOINT")+ accessKey := os.Getenv("BLOBSTORE_TEST_ACCESS_KEY")+ secretKey := os.Getenv("BLOBSTORE_TEST_SECRET_KEY")+ bucket := os.Getenv("BLOBSTORE_TEST_BUCKET")+ if endpoint == "" || accessKey == "" || secretKey == "" || bucket == "" {+ t.Skip("BLOBSTORE_TEST_* env not set; skipping live smoke")+ }+ region := os.Getenv("BLOBSTORE_TEST_REGION")+ if region == "" {+ region = "auto"+ }++ store, err := blobstore.NewS3(blobstore.S3Config{+ Name: "smoke-test",+ Endpoint: endpoint,+ Region: region,+ AccessKeyID: accessKey,+ SecretAccessKey: secretKey,+ UsePathStyle: true,+ })+ if err != nil {+ t.Fatalf("NewS3: %v", err)+ }+ if store == nil {+ t.Fatal("NewS3 returned nil with no error")+ }++ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)+ defer cancel()++ key := "blobstore-smoke/" + time.Now().Format("20060102-150405.000")+ payload := []byte("hello tigris from blobstore smoke test\n")++ // Put+ if err := store.Put(ctx, bucket, key, bytes.NewReader(payload), int64(len(payload))); err != nil {+ t.Fatalf("Put: %v", err)+ }+ t.Logf("Put %s/%s (%d bytes)", bucket, key, len(payload))++ // Exists+ ok, err := store.Exists(ctx, bucket, key)+ if err != nil {+ t.Fatalf("Exists: %v", err)+ }+ if !ok {+ t.Fatalf("Exists: want true immediately after Put, got false")+ }++ // Get+ r, err := store.Get(ctx, bucket, key)+ if err != nil {+ t.Fatalf("Get: %v", err)+ }+ got, err := io.ReadAll(r)+ r.Close()+ if err != nil {+ t.Fatalf("read: %v", err)+ }+ if !bytes.Equal(got, payload) {+ t.Fatalf("Get bytes mismatch: want %q, got %q", payload, got)+ }++ // Exists on missing key+ ok, err = store.Exists(ctx, bucket, key+".does-not-exist")+ if err != nil {+ t.Fatalf("Exists(missing): %v", err)+ }+ if ok {+ t.Errorf("Exists(missing): want false, got true")+ }++ // Get on missing key returns ErrNotFound+ _, err = store.Get(ctx, bucket, key+".does-not-exist")+ if !errors.Is(err, blobstore.ErrNotFound) {+ t.Errorf("Get(missing): want ErrNotFound, got %v", err)+ }++ t.Logf("smoke: backend=%s endpoint=%s bucket=%s key=%s all ops OK", store.Name(), endpoint, bucket, key)+}diff --git a/internal/blobstore/store.go b/internal/blobstore/store.goindex 891b33da..51968ffa 100644--- a/internal/blobstore/store.go+++ b/internal/blobstore/store.go@@ -34,14 +34,28 @@ type Store interface {// Returns ErrNotFound if the object isn't present.Get(ctx context.Context, bucket, key string) (io.ReadCloser, error)+ // GetRange streams a byte range of the object. Used for parallel+ // chunked downloads of large objects (e.g. checkpoint archives).+ // Returns ErrNotFound if the object isn't present.+ GetRange(ctx context.Context, bucket, key string, offset, length int64) (io.ReadCloser, error)+// Put writes body of length contentLength bytes to bucket/key.// Streams from the reader — no in-memory buffering of the full body.Put(ctx context.Context, bucket, key string, body io.Reader, contentLength int64) error+ // Head returns the content length of the object. Distinct from Exists+ // in that callers needing size (e.g. for range planning) avoid a second+ // round trip. Returns ErrNotFound if the object isn't present.+ Head(ctx context.Context, bucket, key string) (int64, error)+// Exists returns true if the object is present at bucket/key.// Returns (false, nil) on NotFound; (false, err) on other errors.Exists(ctx context.Context, bucket, key string) (bool, error)+ // Delete removes the object at bucket/key. Returns nil if the object+ // didn't exist (idempotent).+ Delete(ctx context.Context, bucket, key string) error+// Name returns a short identifier for logging ("tigris", "r2",// "azure-blob"). Never empty.Name() stringdiff --git a/internal/compute/azure.go b/internal/compute/azure.goindex 0a36361e..0418c227 100644--- a/internal/compute/azure.go+++ b/internal/compute/azure.go@@ -19,6 +19,51 @@ import ("github.com/opensandbox/opensandbox/internal/secrets")+// azureQuotaCodes are the error-message fragments the Azure ARM API uses for+// quota and SKU-availability rejections. Detected via substring match against+// the wrapped error string because the SDK surfaces these through several+// layers (BeginCreateOrUpdate immediate failure, PollUntilDone async failure,+// nested ResponseError) and pinning to a single concrete type misses cases.+// All of these are recoverable by retrying with a different VM size, so the+// autoscaler treats them as the ErrQuotaExceeded class.+var azureQuotaCodes = []string{+ "QuotaExceeded",+ "OperationNotAllowed",+ "SkuNotAvailable",+ "AllocationFailed",+ "ZonalAllocationFailed",+ "OverconstrainedAllocationRequest",+ "exceeding approved quota",+ "exceeding approved Total Regional Cores quota",+ "exceeding approved Standard",+}++// isAzureQuotaErr reports whether err matches one of the documented quota /+// capacity rejection codes from Azure ARM.+func isAzureQuotaErr(err error) bool {+ if err == nil {+ return false+ }+ msg := err.Error()+ for _, code := range azureQuotaCodes {+ if strings.Contains(msg, code) {+ return true+ }+ }+ return false+}++// wrapAzureCreateErr tags createMachine errors with ErrQuotaExceeded when the+// underlying ARM failure was a quota/capacity rejection, so the scaler can+// fall through to the next VM size in its ranked list.+func wrapAzureCreateErr(err error, format string, args ...any) error {+ wrapped := fmt.Errorf(format, args...)+ if isAzureQuotaErr(err) {+ return errors.Join(ErrQuotaExceeded, wrapped)+ }+ return wrapped+}+const (azureTagRole = "opensandbox-role"azureTagDraining = "opensandbox-draining"@@ -26,16 +71,27 @@ const (// AzurePoolConfig configures the Azure compute pool.type AzurePoolConfig struct {- SubscriptionID string- ResourceGroup string- Region string // e.g. "westus2"- VMSize string // e.g. "Standard_D16s_v5"- ImageID string // custom image ID or URN (e.g. "Canonical:ubuntu-24_04-lts:server:latest")- SubnetID string // full resource ID of the subnet- AdminUsername string // SSH username (default: "azureuser")- SSHPublicKey string // SSH public key content- DataDiskSizeGB int // data disk size (default: 256)- KeyVaultName string // Azure Key Vault name for dynamic image ID refresh+ SubscriptionID string+ ResourceGroup string+ Region string // e.g. "westus2"+ VMSize string // e.g. "Standard_D16s_v5"+ ImageID string // custom image ID or URN (e.g. "Canonical:ubuntu-24_04-lts:server:latest")+ SubnetID string // full resource ID of the subnet+ AdminUsername string // SSH username (default: "azureuser")+ SSHPublicKey string // SSH public key content+ DataDiskSizeGB int // data disk size (default: 256)+ WorkerEnvBase64 string // base64-encoded worker.env content (injected via cloud-init)+ KeyVaultName string // Azure Key Vault name for dynamic image ID refresh (e.g. "opensandbox-prod")+ // WorkerIdentityID is the full resource ID of a UserAssigned managed+ // identity to attach to every worker VM. Bootstrap once per region+ // (see deploy/azure/bootstrap-worker-identity.sh): create the identity,+ // grant "Key Vault Secrets Officer" on the regional KV, then set this+ // to the identity's resource ID. Required for live migration of+ // secrets-using sandboxes — workers fetch the shared MITM CA from KV+ // using this identity. Empty string = no identity attached (workers+ // can't fetch shared CA; live migration of secrets sandboxes will TLS-+ // fail across worker boundaries — see secretsproxy.LoadOrCreateSharedCA).+ WorkerIdentityID string}// AzurePool implements compute.Pool using Azure VMs.@@ -161,14 +217,28 @@ func (p *AzurePool) CreateMachine(ctx context.Context, opts MachineOpts) (*MachiimageID := p.cfg.ImageIDp.mu.RUnlock()- // Create VM- log.Printf("azure: creating VM %s (size=%s, image=%s)", vmName, vmSize, imageID)+ // Create VM. Identity is attached when WorkerIdentityID is configured —+ // the worker uses this identity to fetch the shared secrets-proxy CA+ // from Key Vault. Without it, freshly-launched workers generate per-+ // worker CAs and live migration of secrets-using sandboxes fails TLS.+ var identity *armcompute.VirtualMachineIdentity+ if p.cfg.WorkerIdentityID != "" {+ identity = &armcompute.VirtualMachineIdentity{+ Type: to.Ptr(armcompute.ResourceIdentityTypeUserAssigned),+ UserAssignedIdentities: map[string]*armcompute.UserAssignedIdentitiesValue{+ p.cfg.WorkerIdentityID: {},+ },+ }+ }++ log.Printf("azure: creating VM %s (size=%s, image=%s, identity=%v)", vmName, vmSize, imageID, p.cfg.WorkerIdentityID != "")vmPoller, err := p.vmClient.BeginCreateOrUpdate(ctx, p.cfg.ResourceGroup, vmName, armcompute.VirtualMachine{Location: to.Ptr(p.cfg.Region),Tags: map[string]*string{"Name": to.Ptr(vmName),azureTagRole: to.Ptr("worker"),},+ Identity: identity,Properties: &armcompute.VirtualMachineProperties{HardwareProfile: &armcompute.HardwareProfile{VMSize: to.Ptr(armcompute.VirtualMachineSizeTypes(vmSize)),@@ -205,12 +275,12 @@ func (p *AzurePool) CreateMachine(ctx context.Context, opts MachineOpts) (*Machiif err != nil {log.Printf("azure: VM %s BeginCreateOrUpdate error detail: %+v", vmName, err)go p.cleanupNIC(nicName, "create failed")- return nil, fmt.Errorf("azure: create VM %s failed: %w", vmName, err)+ return nil, wrapAzureCreateErr(err, "azure: create VM %s failed: %w", vmName, err)}vmResp, err := vmPoller.PollUntilDone(ctx, nil)if err != nil {go p.cleanupNIC(nicName, "poll failed")- return nil, fmt.Errorf("azure: VM %s poll failed: %w", vmName, err)+ return nil, wrapAzureCreateErr(err, "azure: VM %s poll failed: %w", vmName, err)}log.Printf("azure: VM %s created successfully", vmName)diff --git a/internal/compute/ec2.go b/internal/compute/ec2.goindex 95f98a68..4d3673a4 100644--- a/internal/compute/ec2.go+++ b/internal/compute/ec2.go@@ -3,6 +3,7 @@ package computeimport ("context""encoding/base64"+ "errors""fmt""log""strings"@@ -16,6 +17,39 @@ import ("github.com/aws/aws-sdk-go-v2/service/ssm")+// ec2QuotaCodes are the AWS EC2 error codes that indicate a vCPU quota,+// per-account instance limit, or AZ-level capacity exhaustion. All of these+// are recoverable by retrying with a different instance type, so the+// autoscaler treats them as the ErrQuotaExceeded class.+var ec2QuotaCodes = []string{+ "VcpuLimitExceeded",+ "InstanceLimitExceeded",+ "InsufficientInstanceCapacity",+ "MaxSpotInstanceCountExceeded",+ "Unsupported", // returned when a region/AZ doesn't offer the requested type+}++func isEC2QuotaErr(err error) bool {+ if err == nil {+ return false+ }+ msg := err.Error()+ for _, code := range ec2QuotaCodes {+ if strings.Contains(msg, code) {+ return true+ }+ }+ return false+}++func wrapEC2CreateErr(err error, format string, args ...any) error {+ wrapped := fmt.Errorf(format, args...)+ if isEC2QuotaErr(err) {+ return errors.Join(ErrQuotaExceeded, wrapped)+ }+ return wrapped+}+const (// AWS tag keys (kept consistent with the Azure pool's azure-prefixed tags).awsTagRole = "opensandbox:role"@@ -160,7 +194,7 @@ func (p *EC2Pool) CreateMachine(ctx context.Context, opts MachineOpts) (*Machineresult, err := p.client.RunInstances(ctx, input)if err != nil {- return nil, fmt.Errorf("ec2: RunInstances failed: %w", err)+ return nil, wrapEC2CreateErr(err, "ec2: RunInstances failed: %w", err)}if len(result.Instances) == 0 {return nil, fmt.Errorf("ec2: no instances returned")diff --git a/internal/compute/pool.go b/internal/compute/pool.goindex b7ce0c7c..901388cf 100644--- a/internal/compute/pool.go+++ b/internal/compute/pool.go@@ -1,6 +1,17 @@package compute-import "context"+import (+ "context"+ "errors"+)++// ErrQuotaExceeded indicates a provider quota or capacity constraint that may+// be resolved by trying a different machine size. Pool implementations wrap+// (via errors.Join or fmt.Errorf %w) when they detect provider-specific quota+// or "no capacity in this SKU/zone" failures. The autoscaler uses errors.Is to+// decide whether to fall through to the next size in a ranked list versus+// abort the launch.+var ErrQuotaExceeded = errors.New("quota or capacity exceeded")// Machine represents a worker machine in the compute pool.type Machine struct {diff --git a/internal/compute/quota_test.go b/internal/compute/quota_test.gonew file mode 100644index 00000000..422bd84c--- /dev/null+++ b/internal/compute/quota_test.go@@ -0,0 +1,96 @@+package compute++import (+ "errors"+ "fmt"+ "testing"+)++func TestIsAzureQuotaErr(t *testing.T) {+ tests := []struct {+ name string+ err error+ isQuota bool+ }{+ {"nil", nil, false},+ {"unrelated", errors.New("network timeout"), false},+ {"QuotaExceeded code", errors.New("ERROR CODE: QuotaExceeded\noperation failed"), true},+ {"OperationNotAllowed", errors.New("OperationNotAllowed: regional cores"), true},+ {"SkuNotAvailable", errors.New("SkuNotAvailable: Standard_D16ads_v7 in eastus2"), true},+ {"AllocationFailed", errors.New("AllocationFailed: capacity unavailable"), true},+ {"ZonalAllocationFailed", errors.New("ZonalAllocationFailed in zone 1"), true},+ {"OverconstrainedAllocationRequest", errors.New("OverconstrainedAllocationRequest"), true},+ {"approved quota text", errors.New("operation results in exceeding approved quota"), true},+ {"regional cores phrasing", errors.New("Operation could not be completed as it results in exceeding approved Total Regional Cores quota"), true},+ {"wrapped quota", fmt.Errorf("azure: create VM failed: %w", errors.New("QuotaExceeded")), true},+ }++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ got := isAzureQuotaErr(tc.err)+ if got != tc.isQuota {+ t.Fatalf("isAzureQuotaErr(%v) = %v, want %v", tc.err, got, tc.isQuota)+ }+ })+ }+}++func TestIsEC2QuotaErr(t *testing.T) {+ tests := []struct {+ name string+ err error+ isQuota bool+ }{+ {"nil", nil, false},+ {"unrelated", errors.New("connection reset"), false},+ {"VcpuLimitExceeded", errors.New("VcpuLimitExceeded: max 32 in region"), true},+ {"InstanceLimitExceeded", errors.New("InstanceLimitExceeded"), true},+ {"InsufficientInstanceCapacity", errors.New("InsufficientInstanceCapacity in us-east-1a"), true},+ {"MaxSpotInstanceCountExceeded", errors.New("MaxSpotInstanceCountExceeded"), true},+ {"Unsupported in AZ", errors.New("Unsupported: c7gd.metal not offered in this AZ"), true},+ }++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ got := isEC2QuotaErr(tc.err)+ if got != tc.isQuota {+ t.Fatalf("isEC2QuotaErr(%v) = %v, want %v", tc.err, got, tc.isQuota)+ }+ })+ }+}++func TestWrapAzureCreateErrTagsQuota(t *testing.T) {+ quotaSrc := errors.New("AllocationFailed: no capacity")+ wrapped := wrapAzureCreateErr(quotaSrc, "azure: create VM foo failed: %w", quotaSrc)+ if !errors.Is(wrapped, ErrQuotaExceeded) {+ t.Fatalf("expected wrapped quota error to match ErrQuotaExceeded, got %v", wrapped)+ }+ // The original error chain must remain reachable so callers can still log+ // the underlying provider message.+ if !errors.Is(wrapped, quotaSrc) {+ t.Fatalf("expected wrapped error to preserve original chain, got %v", wrapped)+ }+}++func TestWrapAzureCreateErrPassesThroughNonQuota(t *testing.T) {+ src := errors.New("network unreachable")+ wrapped := wrapAzureCreateErr(src, "azure: create VM foo failed: %w", src)+ if errors.Is(wrapped, ErrQuotaExceeded) {+ t.Fatalf("non-quota error should not be tagged as ErrQuotaExceeded: %v", wrapped)+ }+ if !errors.Is(wrapped, src) {+ t.Fatalf("expected wrapped error to preserve original chain, got %v", wrapped)+ }+}++func TestWrapEC2CreateErrTagsQuota(t *testing.T) {+ src := errors.New("VcpuLimitExceeded: max 32 in us-east-1")+ wrapped := wrapEC2CreateErr(src, "ec2: RunInstances failed: %w", src)+ if !errors.Is(wrapped, ErrQuotaExceeded) {+ t.Fatalf("expected wrapped quota error to match ErrQuotaExceeded, got %v", wrapped)+ }+ if !errors.Is(wrapped, src) {+ t.Fatalf("expected wrapped error to preserve original chain, got %v", wrapped)+ }+}diff --git a/internal/config/config.go b/internal/config/config.goindex affcaf3e..e22560da 100644--- a/internal/config/config.go+++ b/internal/config/config.go@@ -37,6 +37,19 @@ type Config struct {WorkerID string // Unique worker ID (e.g., "w-iad-1")HTTPAddr string // Public HTTP address for direct SDK access+ // Platform observability host identity (used by internal/obslog for log+ // envelope so all Axiom records carry host + service ID). HostIP is+ // auto-detected from the first non-loopback IPv4 at startup if+ // OPENCOMPUTER_HOST_IP is not provisioned via cloud-init.+ //+ // CellID — the cell this process belongs to — is declared further down+ // as part of the cf-cutover block. Same field, dual purpose: obslog+ // reads it for log envelope, routing/event_forwarder reads it for cell+ // identity. Falls back to "<region>-default" at the bottom of Load() so+ // legacy paths still log a sensible label when OPENSANDBOX_CELL_ID is+ // unset.+ HostIP string+// WorkOSWorkOSAPIKey stringWorkOSClientID string@@ -61,6 +74,26 @@ type Config struct {S3SecretAccessKey stringS3ForcePathStyle bool // true for R2/MinIO+ // Fallback backend for the checkpoint store. When set, primary reads that+ // fail (or, in migration mode, return NotFound) cascade here. Writes go+ // only to primary. Intended for the Tigris-cutover soak window — flip+ // BlobMigrationMode off and unset once the soak finishes.+ S3FallbackEndpoint string+ S3FallbackRegion string+ S3FallbackAccessKeyID string+ S3FallbackSecretAccessKey string+ S3FallbackForcePathStyle bool+ // S3FallbackBucket lets the fallback backend use a different bucket /+ // Azure container name than the primary. Example: primary points at+ // Tigris bucket "opencomputer-prod"; fallback points at Azure container+ // "checkpoints". When empty, the fallback reuses S3Bucket.+ S3FallbackBucket string++ // BlobMigrationMode flips FallbackStore semantics so primary NotFound+ // cascades to fallbacks (lazy-migration behavior). Applies to both the+ // checkpoint-store fallback and the global blob fallback.+ BlobMigrationMode bool+// Sandbox resource defaults (overridable per-sandbox via API)DefaultSandboxMemoryMB int // default RAM per sandbox (MB), default 1024DefaultSandboxCPUs int // default vCPUs per sandbox, default 1@@ -73,7 +106,8 @@ type Config struct {// AWS EC2 compute pool (server mode only — for auto-scaling worker machines)EC2AMI string // Custom AMI for worker instances- EC2InstanceType string // e.g. "c7gd.metal", "r6gd.metal", "r7gd.metal"+ EC2InstanceType string // single fallback type; used only when EC2InstanceTypes is empty+ EC2InstanceTypes []string // ranked list of instance types tried in order on quota/capacity errorsEC2SubnetID string // VPC subnet for worker instancesEC2SecurityGroupID string // Security group (allow 8080, 9090, 9091)EC2KeyName string // SSH key pair name (for debugging)@@ -84,11 +118,21 @@ type Config struct {// Azure compute pool (server mode — for auto-scaling worker VMs)AzureSubscriptionID string // Azure subscription IDAzureResourceGroup string // Resource group for worker VMs- AzureVMSize string // e.g. "Standard_D16s_v5"+ AzureVMSize string // single fallback size; used only when AzureVMSizes is empty+ AzureVMSizes []string // ranked list of VM sizes tried in order on quota/capacity errorsAzureImageID string // Custom image ID or URNAzureSubnetID string // Full resource ID of the VNet subnetAzureSSHPublicKey string // SSH public key for worker VMsAzureKeyVaultName string // Key Vault name for dynamic image ID refresh (e.g. "opensandbox-prod")+ // AzureWorkerIdentityID is the full resource ID of a UserAssigned managed+ // identity to attach to every worker VM. The identity must already have+ // "Key Vault Secrets Officer" on the regional KV so workers can fetch+ // the shared secrets-proxy CA. Created once per region as a bootstrap+ // step (see deploy/azure/bootstrap-worker-identity.sh). Without this,+ // workers can't reach KV for the shared CA and live migration of+ // secret-store-using sandboxes will fail TLS substitution after the+ // migration completes (per-worker CAs don't match each other).+ AzureWorkerIdentityID string// Cloudflare (custom hostname for org sandbox domains)CFAPIToken string // Cloudflare API token with Custom Hostnames permission@@ -106,9 +150,22 @@ type Config struct {StripeSuccessURL stringStripeCancelURL string+ // Per-agent paywalled-feature prices (set in Stripe dashboard, referenced+ // by ID here). Empty = feature ungated on this deployment (dev mode).+ StripeTelegramAgentPriceID string+// Segment analytics — if set, GB-minute usage events are shipped per org.SegmentWriteKey string+ // Axiom — log shipping for sandbox session logs.+ // AxiomIngestToken empty = log shipping disabled (kill-switch).+ // Worker uses AxiomIngestToken + AxiomDataset to deliver via the+ // ConfigureLogship RPC at sandbox boot. Server uses+ // AxiomQueryToken + AxiomDataset to serve the read API.+ AxiomIngestToken string+ AxiomQueryToken string+ AxiomDataset string+// AWS Secrets Manager — if set, secrets are fetched at startup using IAM credentials.// The secret should be a JSON object with keys matching env var names (e.g. OPENSANDBOX_JWT_SECRET).// Env vars take precedence over secret values (for local overrides).@@ -168,8 +225,8 @@ type Config struct {// Global blob store — abstract S3-compatible backend for canonical golden// rootfs blobs, template blobs, and the events archive. Currently Tigris- // in dev (Region Earth replication), but works with any S3-compatible- // endpoint (R2, S3, GCS interop, Azure Blob via S3 compat). Switching+ // (Region Earth global replication) but works with any S3-compatible+ // endpoint (R2, AWS S3, GCS interop, Azure Blob via S3 compat). Switching// providers is a config change; see internal/blobstore.//// Empty Endpoint disables — workers fall back to whatever's baked into@@ -179,7 +236,7 @@ type Config struct {GlobalBlobRegion string // "auto" for Tigris/R2; real region for AWS S3GlobalBlobAccessKeyID stringGlobalBlobSecretAccessKey string- GlobalBlobUsePathStyle bool // true for R2/Tigris/MinIO; false for AWS S3+ GlobalBlobUsePathStyle bool // true for R2/Tigris/MinIO; false for AWS S3GlobalBlobGoldensBucket stringGlobalBlobTemplatesBucket stringGlobalBlobEventsBucket string@@ -222,6 +279,8 @@ func Load() (*Config, error) {WorkerID: envOrDefault("OPENSANDBOX_WORKER_ID", "w-local-1"),HTTPAddr: envOrDefault("OPENSANDBOX_HTTP_ADDR", "http://localhost:8080"),+ HostIP: os.Getenv("OPENCOMPUTER_HOST_IP"),+WorkOSAPIKey: os.Getenv("WORKOS_API_KEY"),WorkOSClientID: os.Getenv("WORKOS_CLIENT_ID"),WorkOSRedirectURI: envOrDefault("WORKOS_REDIRECT_URI", "http://localhost:8080/auth/callback"),@@ -241,6 +300,15 @@ func Load() (*Config, error) {S3SecretAccessKey: os.Getenv("OPENSANDBOX_S3_SECRET_ACCESS_KEY"),S3ForcePathStyle: os.Getenv("OPENSANDBOX_S3_FORCE_PATH_STYLE") == "true",+ S3FallbackEndpoint: os.Getenv("OPENSANDBOX_S3_FALLBACK_ENDPOINT"),+ S3FallbackRegion: os.Getenv("OPENSANDBOX_S3_FALLBACK_REGION"),+ S3FallbackAccessKeyID: os.Getenv("OPENSANDBOX_S3_FALLBACK_ACCESS_KEY_ID"),+ S3FallbackSecretAccessKey: os.Getenv("OPENSANDBOX_S3_FALLBACK_SECRET_ACCESS_KEY"),+ S3FallbackForcePathStyle: os.Getenv("OPENSANDBOX_S3_FALLBACK_FORCE_PATH_STYLE") == "true",+ S3FallbackBucket: os.Getenv("OPENSANDBOX_S3_FALLBACK_BUCKET"),++ BlobMigrationMode: os.Getenv("OPENSANDBOX_BLOB_MIGRATION_MODE") == "true",+DefaultSandboxMemoryMB: envOrDefaultInt("OPENSANDBOX_DEFAULT_SANDBOX_MEMORY_MB", 256),DefaultSandboxCPUs: envOrDefaultInt("OPENSANDBOX_DEFAULT_SANDBOX_CPUS", 1),DefaultSandboxDiskMB: envOrDefaultInt("OPENSANDBOX_DEFAULT_SANDBOX_DISK_MB", 0),@@ -251,6 +319,7 @@ func Load() (*Config, error) {EC2AMI: os.Getenv("OPENSANDBOX_EC2_AMI"),EC2InstanceType: envOrDefault("OPENSANDBOX_EC2_INSTANCE_TYPE", "c7gd.metal"),+ EC2InstanceTypes: splitCSV(os.Getenv("OPENSANDBOX_EC2_INSTANCE_TYPES")),EC2SubnetID: os.Getenv("OPENSANDBOX_EC2_SUBNET_ID"),EC2SecurityGroupID: os.Getenv("OPENSANDBOX_EC2_SECURITY_GROUP_ID"),EC2KeyName: os.Getenv("OPENSANDBOX_EC2_KEY_NAME"),@@ -261,10 +330,12 @@ func Load() (*Config, error) {AzureSubscriptionID: os.Getenv("OPENSANDBOX_AZURE_SUBSCRIPTION_ID"),AzureResourceGroup: os.Getenv("OPENSANDBOX_AZURE_RESOURCE_GROUP"),AzureVMSize: envOrDefault("OPENSANDBOX_AZURE_VM_SIZE", "Standard_D16s_v5"),+ AzureVMSizes: splitCSV(os.Getenv("OPENSANDBOX_AZURE_VM_SIZES")),AzureImageID: os.Getenv("OPENSANDBOX_AZURE_IMAGE_ID"),AzureSubnetID: os.Getenv("OPENSANDBOX_AZURE_SUBNET_ID"),AzureSSHPublicKey: os.Getenv("OPENSANDBOX_AZURE_SSH_PUBLIC_KEY"),AzureKeyVaultName: os.Getenv("OPENSANDBOX_AZURE_KEY_VAULT_NAME"),+ AzureWorkerIdentityID: os.Getenv("OPENSANDBOX_AZURE_WORKER_IDENTITY_ID"),CFAPIToken: os.Getenv("OPENSANDBOX_CF_API_TOKEN"),CFZoneID: os.Getenv("OPENSANDBOX_CF_ZONE_ID"),@@ -274,13 +345,18 @@ func Load() (*Config, error) {MaxWorkersPerRegion: envOrDefaultInt("OPENSANDBOX_MAX_WORKERS", 10),IdleReserveWorkers: envOrDefaultInt("OPENSANDBOX_IDLE_RESERVE", 1),- StripeSecretKey: os.Getenv("STRIPE_SECRET_KEY"),- StripeWebhookSecret: os.Getenv("STRIPE_WEBHOOK_SECRET"),+ StripeSecretKey: os.Getenv("STRIPE_SECRET_KEY"),+ StripeWebhookSecret: os.Getenv("STRIPE_WEBHOOK_SECRET"),+ StripeTelegramAgentPriceID: os.Getenv("STRIPE_TELEGRAM_AGENT_PRICE_ID"),StripeSuccessURL: envOrDefault("STRIPE_SUCCESS_URL", "http://localhost:3000/billing?success=true"),StripeCancelURL: envOrDefault("STRIPE_CANCEL_URL", "http://localhost:3000/billing?cancelled=true"),SegmentWriteKey: os.Getenv("SEGMENT_WRITE_KEY"),+ AxiomIngestToken: os.Getenv("AXIOM_INGEST_TOKEN"),+ AxiomQueryToken: os.Getenv("AXIOM_QUERY_TOKEN"),+ AxiomDataset: envOrDefault("AXIOM_DATASET", "oc-sandbox-logs"),+SecretsARN: os.Getenv("OPENSANDBOX_SECRETS_ARN"),SecretEncryptionKey: os.Getenv("OPENSANDBOX_SECRET_ENCRYPTION_KEY"),@@ -327,6 +403,13 @@ func Load() (*Config, error) {cfg.S3Region = cfg.Region}+ // Default cell ID to "<region>-default" so logs always have a cell tag.+ // Fleet can split a region into multiple cells later by setting the env+ // var explicitly at provisioning time.+ if cfg.CellID == "" {+ cfg.CellID = cfg.Region + "-default"+ }+if portStr := os.Getenv("OPENSANDBOX_PORT"); portStr != "" {port, err := strconv.Atoi(portStr)if err != nil {@@ -345,6 +428,27 @@ func envOrDefault(key, fallback string) string {return fallback}+// splitCSV parses a comma-separated value into a non-empty trimmed slice.+// Empty input or all-whitespace entries return nil so callers can use len() == 0+// to detect "not configured." Leaves the order intact since rank matters+// for the autoscaler's machine-size fallback list.+func splitCSV(s string) []string {+ if s == "" {+ return nil+ }+ parts := strings.Split(s, ",")+ out := make([]string, 0, len(parts))+ for _, p := range parts {+ if trimmed := strings.TrimSpace(p); trimmed != "" {+ out = append(out, trimmed)+ }+ }+ if len(out) == 0 {+ return nil+ }+ return out+}+func envOrDefaultInt(key string, fallback int) int {if v := os.Getenv(key); v != "" {if n, err := strconv.Atoi(v); err == nil {diff --git a/internal/config/config_test.go b/internal/config/config_test.goindex 574d09b4..284551ea 100644--- a/internal/config/config_test.go+++ b/internal/config/config_test.go@@ -2,9 +2,55 @@ package configimport ("os"+ "reflect""testing")+func TestSplitCSV(t *testing.T) {+ tests := []struct {+ name string+ in string+ want []string+ }{+ {"empty", "", nil},+ {"whitespace only", " , ,", nil},+ {"single", "Standard_D16ads_v7", []string{"Standard_D16ads_v7"}},+ {"multiple", "Standard_D16ads_v7,Standard_D16ds_v6,Standard_D16s_v5",+ []string{"Standard_D16ads_v7", "Standard_D16ds_v6", "Standard_D16s_v5"}},+ {"trim whitespace", " Standard_D16ads_v7 , Standard_D16ds_v6 ",+ []string{"Standard_D16ads_v7", "Standard_D16ds_v6"}},+ {"drop empty entries", "a,,b,,,c", []string{"a", "b", "c"}},+ {"order preserved", "c7gd.metal,r7gd.metal,r6gd.metal",+ []string{"c7gd.metal", "r7gd.metal", "r6gd.metal"}},+ }+ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ got := splitCSV(tc.in)+ if !reflect.DeepEqual(got, tc.want) {+ t.Fatalf("splitCSV(%q) = %v, want %v", tc.in, got, tc.want)+ }+ })+ }+}++func TestLoadParsesMachineSizeLists(t *testing.T) {+ t.Setenv("OPENSANDBOX_AZURE_VM_SIZES", "Standard_D16ads_v7, Standard_D16ds_v6 ,Standard_D16s_v5")+ t.Setenv("OPENSANDBOX_EC2_INSTANCE_TYPES", "c7gd.metal,r7gd.metal")++ cfg, err := Load()+ if err != nil {+ t.Fatalf("Load() error: %v", err)+ }+ wantAzure := []string{"Standard_D16ads_v7", "Standard_D16ds_v6", "Standard_D16s_v5"}+ if !reflect.DeepEqual(cfg.AzureVMSizes, wantAzure) {+ t.Errorf("AzureVMSizes = %v, want %v", cfg.AzureVMSizes, wantAzure)+ }+ wantEC2 := []string{"c7gd.metal", "r7gd.metal"}+ if !reflect.DeepEqual(cfg.EC2InstanceTypes, wantEC2) {+ t.Errorf("EC2InstanceTypes = %v, want %v", cfg.EC2InstanceTypes, wantEC2)+ }+}+func TestLoadDefaults(t *testing.T) {// Clear env to test defaultsos.Unsetenv("OPENSANDBOX_PORT")diff --git a/internal/config/keyvault.go b/internal/config/keyvault.goindex 6e5316fa..2f687939 100644--- a/internal/config/keyvault.go+++ b/internal/config/keyvault.go@@ -48,6 +48,19 @@ var kvMapping = map[string]string{"server-stripe-secret-key": "STRIPE_SECRET_KEY","server-stripe-webhook-secret": "STRIPE_WEBHOOK_SECRET","server-sentry-dsn": "OPENSANDBOX_SENTRY_DSN",+ // Machine-size fallback lists (PR #209). Comma-separated ranked+ // instance types the autoscaler tries in order on quota / capacity+ // errors. Empty value = use the single VMSize / InstanceType+ // configured on the pool (pre-fallback behavior).+ "server-azure-vm-sizes": "OPENSANDBOX_AZURE_VM_SIZES",+ "server-ec2-instance-types": "OPENSANDBOX_EC2_INSTANCE_TYPES",+ // Legacy Axiom mappings — kept for backwards compat with existing prod+ // KVs that pre-date the `shared-` prefix. New deploys should use+ // `shared-axiom-*` instead. Safe to leave: in server mode only+ // `server-axiom-*` is loaded; in worker mode only `worker-axiom-*`. New+ // `shared-*` mappings below win for new envs that have only those.+ "server-axiom-query-token": "AXIOM_QUERY_TOKEN",+ "server-axiom-dataset": "AXIOM_DATASET",// Server-side cell config + shared secrets. These mirror the worker-* keys// of the same name — both sides need them, and the prefix filter loads only@@ -62,12 +75,14 @@ var kvMapping = map[string]string{"server-session-jwt-secret": "OPENSANDBOX_SESSION_JWT_SECRET",// Worker secrets- "worker-jwt-secret": "OPENSANDBOX_JWT_SECRET",- "worker-database-url": "OPENSANDBOX_DATABASE_URL",- "worker-redis-url": "OPENSANDBOX_REDIS_URL",- "worker-s3-access-key": "OPENSANDBOX_S3_ACCESS_KEY_ID",- "worker-s3-secret-key": "OPENSANDBOX_S3_SECRET_ACCESS_KEY",- "worker-sentry-dsn": "OPENSANDBOX_SENTRY_DSN",+ "worker-jwt-secret": "OPENSANDBOX_JWT_SECRET",+ "worker-database-url": "OPENSANDBOX_DATABASE_URL",+ "worker-redis-url": "OPENSANDBOX_REDIS_URL",+ "worker-s3-access-key": "OPENSANDBOX_S3_ACCESS_KEY_ID",+ "worker-s3-secret-key": "OPENSANDBOX_S3_SECRET_ACCESS_KEY",+ "worker-sentry-dsn": "OPENSANDBOX_SENTRY_DSN",+ "worker-axiom-ingest-token": "AXIOM_INGEST_TOKEN", // legacy; superseded by shared-axiom-ingest-token+ "worker-axiom-dataset": "AXIOM_DATASET", // legacy; superseded by shared-axiom-dataset// Worker per-cell config (non-secret but cell-scoped — every worker in the// cell shares these, so KV is the single source of truth)@@ -108,8 +123,29 @@ var kvMapping = map[string]string{"worker-global-blob-fallback-access-key-id": "OPENSANDBOX_GLOBAL_BLOB_FALLBACK_ACCESS_KEY_ID","worker-global-blob-fallback-secret-access-key": "OPENSANDBOX_GLOBAL_BLOB_FALLBACK_SECRET_ACCESS_KEY",- // Shared- "pg-password": "OPENSANDBOX_PG_PASSWORD",+ // Shared (mode-agnostic — loaded in both server and worker)+ "pg-password": "OPENSANDBOX_PG_PASSWORD",+ "shared-axiom-ingest-token": "AXIOM_INGEST_TOKEN",+ "shared-axiom-query-token": "AXIOM_QUERY_TOKEN",+ "shared-axiom-dataset": "AXIOM_DATASET",+ // Platform-logs: Vector reads these from /etc/opensandbox/vector.env,+ // populated by populate-vector-env.service via its own IMDS+KV REST call+ // (not by this Go-side loader, because Vector starts as its own systemd+ // unit before the Go binary). The entries here exist for two reasons:+ // 1. Discoverability — kvMapping is the single source of truth for+ // "what shared-* secrets does this deployment need in KV".+ // 2. Side-effect: the Go binary ALSO loads them into its own env at+ // startup; future Go code that wants to surface platform-stream+ // config (e.g. an admin endpoint) gets them for free.+ "shared-axiom-platform-ingest-token": "AXIOM_PLATFORM_TOKEN",+ "shared-axiom-platform-dataset": "AXIOM_PLATFORM_DATASET",+ // Cell identifier — stamped on every log + metric event so platform+ // dashboards can filter per cell. Same dual-consumer pattern as the+ // platform-* secrets above: Vector reads it from /etc/opensandbox/vector.env+ // (written by populate-vector-env.sh) for its remap substitutions, and+ // the Go binary reads it from cfg.CellID (which falls back to+ // "<region>-default" when this isn't in KV — see config.go).+ "shared-cell-id": "OPENSANDBOX_CELL_ID",}// LoadSecretsFromKeyVault fetches secrets from Azure Key Vault and sets themdiff --git a/internal/controlplane/autoscaler.go b/internal/controlplane/autoscaler.gonew file mode 100644index 00000000..d1496419--- /dev/null+++ b/internal/controlplane/autoscaler.go@@ -0,0 +1,368 @@+package controlplane++import (+ "context"+ "log"+ "sort"+ "sync"+ "time"++ "github.com/opensandbox/opensandbox/internal/db"+ "github.com/opensandbox/opensandbox/pkg/types"+)++// Per-sandbox autoscaler. Resizes a sandbox's memory tier (with vCPU bundled+// per types.AllowedResourceTiers) based on observed memory pressure, bounded+// by user-configured min/max.+//+// Design choices:+// - Tier-aligned. We never pick a half-step size — only values from+// types.AllowedResourceTiers (1G/4G/8G/16G/32G/64G). This keeps billing+// predictable and avoids the configuration explosion of a free-form+// step_gb knob. vCPU follows memory by the tier table.+// - Asymmetric thresholds and cooldowns. Scale up FAST on a brief 1-min+// spike (>75% mem) — user notices lag, we want to fix it before they+// OOM. Scale down SLOW: require all of {1m, 5m, 15m} averages below+// 25% AND at least 5 minutes since the last scale event. This stops+// the sawtooth pattern from a workload that briefly idles.+// - In-memory state. Moving averages and last-event timestamps live in+// CP memory. On CP restart we lose history; the autoscaler self-+// corrects within ~15 minutes (the longest window). Worth the cost+// vs adding Redis writes per sandbox per tick.+// - No live-migrate fallback. If a SetSandboxLimits up-call fails because+// the host can't fit the new size, we log and try again next tick. A+// migration fallback is Phase 3 (depends on the fork-reliability work+// in PR #207 being solid first).+const (+ autoscaleTickInterval = 30 * time.Second++ // Scale-up triggers on a single 1-min sample exceeding the threshold.+ // One window is enough because users feel pressure immediately.+ scaleUpMemPctThreshold = 75.0++ // Scale-down requires ALL three averaging windows below the threshold.+ // 1-min protects against transient idle, 5-min/15-min confirm steady-+ // state. The 15-min window is the dominant constraint — at 30-second+ // ticks that's 30 samples of agreement before we shrink.+ scaleDownMemPctThreshold = 25.0++ // Cooldowns. After scaling up, wait at least 60s before another up.+ // After scaling down, wait 5 min before considering more scaling+ // (either direction). The asymmetry matches user perception: rapid+ // scale-up on demand, conservative shrink after sustained idle.+ scaleUpCooldown = 60 * time.Second+ scaleDownCooldown = 5 * time.Minute+)++// Sample windows (counts of 30s ticks).+const (+ window1m = 2 // 60s / 30s+ window5m = 10 // 300s / 30s+ window15m = 30 // 900s / 30s+)++// AutoscalerSandboxStore is the subset of the DB we need.+type AutoscalerSandboxStore interface {+ // ListAutoscaleEnabled returns running sandboxes with autoscale_enabled=true.+ ListAutoscaleEnabled(ctx context.Context) ([]db.AutoscaleSandbox, error)+ // ClaimAutoscaleEvent atomically claims the right to apply a scale event,+ // guarding against (a) a manual scale that disabled autoscale concurrently+ // and (b) two CPs deciding on the same pre-event row. Returns true if the+ // caller has the claim and may proceed with the gRPC.+ ClaimAutoscaleEvent(ctx context.Context, sandboxID string, prev, now time.Time) (bool, error)+}++// AutoscalerRegistry is the small subset of WorkerRegistry the autoscaler+// uses. The autoscaler reads cached per-sandbox stats off the registry —+// stats are populated from worker heartbeats, not pulled per-tick by the+// CP. See redis_registry.go's GetSandboxStats for the cache.+type AutoscalerRegistry interface {+ // GetSandboxStats returns the latest snapshot for a sandbox plus the+ // worker hosting it, or ok=false if no recent heartbeat has carried it.+ GetSandboxStats(sandboxID string) (SandboxStats, string, bool)+}++// AutoscalerScaleSetter applies a scale decision via the existing setLimits+// machinery (worker gRPC SetSandboxLimits). Decoupled so we can test without+// a real worker. The from→to pair is passed so implementations can emit+// audit events (admin dashboard, structured logs) showing the transition,+// not just the new size.+type AutoscalerScaleSetter interface {+ SetSandboxMemoryMB(ctx context.Context, sandboxID string, fromMB, toMB int) error+}++type Autoscaler struct {+ store AutoscalerSandboxStore+ registry AutoscalerRegistry+ setter AutoscalerScaleSetter+ isLeader func() bool // optional: skip ticks when not leader (HA setup)++ mu sync.Mutex+ stats map[string]*sandboxStats // sandboxID → samples+ stop chan struct{}+}++type sandboxStats struct {+ memSamples []float64 // most recent first; trimmed to window15m+}++// NewAutoscaler wires up the loop. Caller invokes Start to begin ticking.+//+// isLeader (optional) is consulted at the top of each tick. When non-nil and+// returning false, the tick is skipped entirely — used in HA setups where+// only one CP should drive scaling decisions. Passing nil makes the loop+// run unconditionally (single-CP / dev / no-leader-election deployments).+func NewAutoscaler(store AutoscalerSandboxStore, registry AutoscalerRegistry, setter AutoscalerScaleSetter, isLeader func() bool) *Autoscaler {+ return &Autoscaler{+ store: store,+ registry: registry,+ setter: setter,+ isLeader: isLeader,+ stats: make(map[string]*sandboxStats),+ stop: make(chan struct{}),+ }+}++// Start runs the autoscaler loop until ctx is cancelled or Stop is called.+func (a *Autoscaler) Start(ctx context.Context) {+ go a.run(ctx)+}++func (a *Autoscaler) Stop() { close(a.stop) }++func (a *Autoscaler) run(ctx context.Context) {+ log.Println("autoscaler: started")+ ticker := time.NewTicker(autoscaleTickInterval)+ defer ticker.Stop()+ for {+ select {+ case <-ctx.Done():+ return+ case <-a.stop:+ return+ case <-ticker.C:+ a.tick(ctx)+ }+ }+}++func (a *Autoscaler) tick(ctx context.Context) {+ if a.isLeader != nil && !a.isLeader() {+ return+ }+ sandboxes, err := a.store.ListAutoscaleEnabled(ctx)+ if err != nil {+ log.Printf("autoscaler: ListAutoscaleEnabled failed: %v", err)+ return+ }++ // Drop stats for sandboxes that are no longer autoscale-enabled (or are gone).+ a.mu.Lock()+ keep := make(map[string]bool, len(sandboxes))+ for _, sb := range sandboxes {+ keep[sb.SandboxID] = true+ }+ for id := range a.stats {+ if !keep[id] {+ delete(a.stats, id)+ }+ }+ a.mu.Unlock()++ for _, sb := range sandboxes {+ a.evaluateOne(ctx, sb)+ }+}++func (a *Autoscaler) evaluateOne(ctx context.Context, sb db.AutoscaleSandbox) {+ // 1. Fetch current stats from the worker. The registry's cached stats+ // also provide the live MemLimit which is the authoritative current+ // memory size (sandbox_sessions.config does NOT update on scale).+ stats, _, ok := a.registry.GetSandboxStats(sb.SandboxID)+ if !ok {+ // No recent heartbeat — skip this tick; data should appear within ~10s.+ return+ }+ if stats.MemLimit == 0 {+ // Defensive: without a known limit we can't compute a tier. Skip.+ log.Printf("autoscaler: %s no MemLimit in heartbeat; skipping", sb.SandboxID)+ return+ }+ // MemLimit comes from the guest's /proc/meminfo MemTotal — which is+ // ~10% smaller than the QEMU -m due to kernel reservations (e.g. a+ // sandbox configured at 1024 MB shows 896 MB). Round UP to the nearest+ // tier so the autoscaler reasons about the *configured* size, not the+ // kernel-visible size. Without this, a 1 GB sandbox with mem pressure+ // loops forever scaling 896→1024 (which is a no-op on virtio-mem+ // because base=1024 already), never reaching the next real tier.+ rawMB := int(stats.MemLimit / (1024 * 1024))+ sb.CurrentMB = roundUpToTier(rawMB)+ memPct := stats.MemPct++ // 2. Record sample.+ a.recordSample(sb.SandboxID, memPct)++ // 3. Decide.+ target := a.decideTarget(sb)+ if target == 0 || target == sb.CurrentMB {+ return+ }++ // 4. Claim the right to scale (atomic CAS — closes manual-vs-auto race+ // and multi-CP race in one step). If 0 rows updated, someone else won.+ now := time.Now()+ claimed, err := a.store.ClaimAutoscaleEvent(ctx, sb.SandboxID, sb.LastEventAt, now)+ if err != nil {+ log.Printf("autoscaler: %s claim failed: %v", sb.SandboxID, err)+ return+ }+ if !claimed {+ log.Printf("autoscaler: %s claim lost (manual scale or peer CP raced); skipping", sb.SandboxID)+ return+ }++ // 5. Apply. Cooldown is already burned (intentional — gRPC failures+ // shouldn't retry-storm at every tick; wait the cooldown out).+ if err := a.setter.SetSandboxMemoryMB(ctx, sb.SandboxID, sb.CurrentMB, target); err != nil {+ log.Printf("autoscaler: %s scale %d→%d MB failed: %v", sb.SandboxID, sb.CurrentMB, target, err)+ return+ }+ // Structured audit log line — `autoscaler: scaled` is greppable. Setter+ // also emits this to the admin event bus so the dashboard surfaces it.+ log.Printf("autoscaler: scaled sandbox=%s from=%dMB to=%dMB mem_pct=%.1f min=%d max=%d worker=%s",+ sb.SandboxID, sb.CurrentMB, target, memPct, sb.MinMB, sb.MaxMB, sb.WorkerID)+}++func (a *Autoscaler) recordSample(sandboxID string, memPct float64) {+ a.mu.Lock()+ defer a.mu.Unlock()+ s, ok := a.stats[sandboxID]+ if !ok {+ s = &sandboxStats{}+ a.stats[sandboxID] = s+ }+ // Most recent first. Trim to longest window.+ s.memSamples = append([]float64{memPct}, s.memSamples...)+ if len(s.memSamples) > window15m {+ s.memSamples = s.memSamples[:window15m]+ }+}++// decideTarget returns the memory MB to scale to, or 0 if no change.+func (a *Autoscaler) decideTarget(sb db.AutoscaleSandbox) int {+ a.mu.Lock()+ s := a.stats[sb.SandboxID]+ a.mu.Unlock()+ if s == nil || len(s.memSamples) == 0 {+ return 0+ }++ currentMB := sb.CurrentMB+ if currentMB == 0 {+ return 0 // unknown current — don't risk scaling+ }++ avg1 := windowAvg(s.memSamples, window1m)+ avg5 := windowAvg(s.memSamples, window5m)+ avg15 := windowAvg(s.memSamples, window15m)++ now := time.Now()++ // Scale up: 1-min above threshold, current < max, off scale-up cooldown.+ // Require at least window1m samples (≥2) so a single noisy reading on a+ // freshly-(re)started CP can't trigger a scale-up before we've had a+ // chance to confirm it.+ if avg1 > scaleUpMemPctThreshold && currentMB < sb.MaxMB && len(s.memSamples) >= window1m {+ if !sb.LastEventAt.IsZero() && now.Sub(sb.LastEventAt) < scaleUpCooldown {+ return 0+ }+ next := nextTier(currentMB, sb.MaxMB)+ if next > currentMB {+ return next+ }+ }++ // Scale down: ALL three windows below threshold, current > min, off scale-down cooldown.+ // Need at least window15m samples — otherwise the long window is misleading.+ if avg1 < scaleDownMemPctThreshold && avg5 < scaleDownMemPctThreshold && avg15 < scaleDownMemPctThreshold &&+ len(s.memSamples) >= window15m && currentMB > sb.MinMB {+ if !sb.LastEventAt.IsZero() && now.Sub(sb.LastEventAt) < scaleDownCooldown {+ return 0+ }+ prev := prevTier(currentMB, sb.MinMB)+ if prev < currentMB {+ return prev+ }+ }++ return 0+}++// windowAvg returns the mean of the most recent n samples (or all of them if+// fewer exist). Caller must hold no lock — operates on the slice argument.+func windowAvg(samples []float64, n int) float64 {+ if n > len(samples) {+ n = len(samples)+ }+ if n == 0 {+ return 0+ }+ var sum float64+ for i := 0; i < n; i++ {+ sum += samples[i]+ }+ return sum / float64(n)+}++// nextTier returns the next memory tier above current, capped at maxMB.+// Returns current if no higher tier is allowed.+func nextTier(currentMB, maxMB int) int {+ tiers := tierMBs()+ for _, t := range tiers {+ if t > currentMB && t <= maxMB {+ return t+ }+ }+ return currentMB+}++// prevTier returns the next memory tier below current, floored at minMB.+// Returns current if no lower tier is allowed.+func prevTier(currentMB, minMB int) int {+ tiers := tierMBs()+ // Iterate descending.+ for i := len(tiers) - 1; i >= 0; i-- {+ if tiers[i] < currentMB && tiers[i] >= minMB {+ return tiers[i]+ }+ }+ return currentMB+}++// roundUpToTier returns the smallest tier ≥ mb. If mb is already at or above+// the highest tier, returns the highest. If mb ≤ 0, returns the lowest tier.+// Used to reconcile guest-reported MemTotal (which is ~10% below QEMU -m)+// to the operator-configured tier.+func roundUpToTier(mb int) int {+ tiers := tierMBs()+ if len(tiers) == 0 {+ return mb+ }+ for _, t := range tiers {+ if mb <= t {+ return t+ }+ }+ return tiers[len(tiers)-1]+}++// tierMBs returns the allowed memory tier values in ascending order.+// Pulled from the canonical tier list in pkg/types so we can never disagree.+func tierMBs() []int {+ out := make([]int, 0, len(types.AllowedResourceTiers))+ for _, t := range types.AllowedResourceTiers {+ out = append(out, t.MemoryMB)+ }+ sort.Ints(out)+ return out+}diff --git a/internal/controlplane/redis_registry.go b/internal/controlplane/redis_registry.goindex 48836951..c028bc74 100644--- a/internal/controlplane/redis_registry.go+++ b/internal/controlplane/redis_registry.go@@ -14,10 +14,42 @@ import ("google.golang.org/grpc/keepalive""github.com/opensandbox/opensandbox/internal/grpctls"+ "github.com/opensandbox/opensandbox/internal/metrics"pb "github.com/opensandbox/opensandbox/proto/worker")+const (+ // routingCountTTL bounds how long a per-worker placement counter survives+ // without further increments. Heartbeat reconciles every 10s; 60s gives the+ // counter enough headroom to bridge several heartbeat windows so a quiet+ // stretch between placements doesn't drop us back to heartbeat-only data.+ routingCountTTL = 60 * time.Second++ // routingHardCapPct excludes workers whose actual CPU/mem/disk pressure is+ // at or above this level. The score below handles the gradient up to this+ // cap, so 0–85%-loaded workers are ranked smoothly; only at 85% do we stop+ // considering a worker entirely. Aligned with the scaler's 80% evacuation+ // threshold — by the time a worker is being evacuated we should have+ // already stopped sending it traffic.+ routingHardCapPct = 85.0++ // drainKeyPrefix is the Redis key prefix used to publish per-worker drain+ // state across all control planes. SetDraining writes this key; every+ // heartbeat applies it to the in-memory worker entry so any CP's view of+ // "is this worker draining?" stays consistent regardless of which CP+ // initiated the drain.+ drainKeyPrefix = "drain:"++ // drainKeyTTL bounds how long a drain marker survives without renewal.+ // Longer than any reasonable drain (45min drainTimeout in scaler.go) so+ // long-running drains don't unexpectedly re-route traffic to the worker,+ // but short enough that a forgotten "drain forever" doesn't outlive the+ // worker's lifetime — pending operator clearing, the worker will rejoin+ // the pool after 24h.+ drainKeyTTL = 24 * time.Hour+)+// WorkerEntry represents a worker in the Redis-backed registry.type WorkerEntry struct {ID string `json:"worker_id"`@@ -35,6 +67,21 @@ type WorkerEntry struct {GoldenVersion string `json:"golden_version,omitempty"`WorkerVersion string `json:"worker_version,omitempty"`Draining bool `json:"draining,omitempty"`++ // Per-sandbox stats published by the worker. Bounded by per-host sandbox+ // capacity (~50-150 entries) so the heartbeat doesn't grow unboundedly.+ // Consumed by the autoscaler — see GetSandboxStats accessor below.+ Sandboxes map[string]SandboxStats `json:"sandboxes,omitempty"`+}++// SandboxStats is the per-sandbox snapshot ingested from worker heartbeats.+// Mirrors internal/worker.SandboxStatsWire — kept separate to avoid an+// import cycle (CP shouldn't depend on the worker package).+type SandboxStats struct {+ MemUsage uint64 `json:"mem_usage"`+ MemLimit uint64 `json:"mem_limit"`+ MemPct float64 `json:"mem_pct"`+ CPUPct float64 `json:"cpu_pct"`}// RedisWorkerRegistry maintains an in-memory cache of worker state@@ -48,6 +95,13 @@ type RedisWorkerRegistry struct {clients map[string]pb.SandboxWorkerClient // cached gRPC clientsrrCounter uint64 // round-robin counter for tie-breakingstop chan struct{}++ // Per-sandbox stats indexed by sandboxID for O(1) autoscaler lookup. Updated+ // from each worker heartbeat. Lock-protected separately from workers so the+ // autoscaler doesn't contend with the routing path (which holds workersMu).+ sandboxStatsMu sync.RWMutex+ sandboxStats map[string]SandboxStats // sandboxID → latest snapshot+ sandboxOnWorker map[string]string // sandboxID → workerID (for prune-on-disappear)}// RedisClient returns the underlying Redis client (for health checks, shared state, etc.).@@ -55,6 +109,20 @@ func (r *RedisWorkerRegistry) RedisClient() *redis.Client {return r.rdb}+// GetSandboxStats returns the latest cached stats for a sandbox along with+// its host worker, or ok=false if no recent heartbeat has carried that+// sandbox. The autoscaler's per-tick fetchMemPct uses this — replaces the+// previous gRPC fan-out which scaled O(total sandboxes) per tick.+func (r *RedisWorkerRegistry) GetSandboxStats(sandboxID string) (SandboxStats, string, bool) {+ r.sandboxStatsMu.RLock()+ defer r.sandboxStatsMu.RUnlock()+ stats, ok := r.sandboxStats[sandboxID]+ if !ok {+ return SandboxStats{}, "", false+ }+ return stats, r.sandboxOnWorker[sandboxID], true+}+// NewRedisWorkerRegistry connects to Redis and returns a new registry.func NewRedisWorkerRegistry(redisURL string) (*RedisWorkerRegistry, error) {opts, err := redis.ParseURL(redisURL)@@ -77,11 +145,13 @@ func NewRedisWorkerRegistry(redisURL string) (*RedisWorkerRegistry, error) {}return &RedisWorkerRegistry{- rdb: rdb,- workers: make(map[string]*WorkerEntry),- conns: make(map[string]*grpc.ClientConn),- clients: make(map[string]pb.SandboxWorkerClient),- stop: make(chan struct{}),+ rdb: rdb,+ workers: make(map[string]*WorkerEntry),+ conns: make(map[string]*grpc.ClientConn),+ clients: make(map[string]pb.SandboxWorkerClient),+ sandboxStats: make(map[string]SandboxStats),+ sandboxOnWorker: make(map[string]string),+ stop: make(chan struct{}),}, nil}@@ -202,10 +272,38 @@ func (r *RedisWorkerRegistry) reconcileAndPrune() {}}}++ // Publish the opensandbox_workers_total gauge, keyed by (region, status).+ // Reset first so a region that drained to zero stops reporting its last+ // non-zero value forever; only the (region, status) combos still observed+ // in r.workers will emit a time series on this tick.+ metrics.WorkersTotal.Reset()+ type key struct{ region, status string }+ counts := make(map[key]int)+ for _, w := range r.workers {+ status := "active"+ if w.Draining {+ status = "draining"+ }+ counts[key{w.Region, status}]+++ }+ for k, n := range counts {+ metrics.WorkersTotal.WithLabelValues(k.region, k.status).Set(float64(n))+ }}// handleHeartbeat updates the in-memory worker map and dials gRPC if this is a new worker.func (r *RedisWorkerRegistry) handleHeartbeat(entry WorkerEntry) {+ // Read drain state outside the lock — this is a network call and we don't+ // want to block other registry ops on Redis latency. The drain key is the+ // cross-CP source of truth; per-CP SetDraining writes it on the admin+ // path or scaler-initiated drain, and every CP's heartbeat applies it+ // here so all CPs converge on the same view.+ drainCtx, drainCancel := context.WithTimeout(context.Background(), time.Second)+ drainExists, _ := r.rdb.Exists(drainCtx, drainKeyPrefix+entry.ID).Result()+ drainCancel()+ drainOverride := drainExists > 0+r.mu.Lock()defer r.mu.Unlock()@@ -219,6 +317,7 @@ func (r *RedisWorkerRegistry) handleHeartbeat(entry WorkerEntry) {existing.DiskPct = entry.DiskPctexisting.TotalMemoryMB = entry.TotalMemoryMBexisting.CommittedMemoryMB = entry.CommittedMemoryMB+ existing.Draining = drainOverrideif entry.GoldenVersion != "" {existing.GoldenVersion = entry.GoldenVersion}@@ -236,9 +335,37 @@ func (r *RedisWorkerRegistry) handleHeartbeat(entry WorkerEntry) {}} else {// New worker+ entry.Draining = drainOverrider.workers[entry.ID] = &entry- log.Printf("redis_registry: new worker registered: %s (region=%s, grpc=%s)", entry.ID, entry.Region, entry.GRPCAddr)+ log.Printf("redis_registry: new worker registered: %s (region=%s, grpc=%s, draining=%v)", entry.ID, entry.Region, entry.GRPCAddr, drainOverride)+ }++ // Per-sandbox stats indexing. Update fresh entries; prune sandboxes that+ // the worker reported last time but didn't this time (sandbox destroyed+ // between heartbeats). Done under a separate mutex so the autoscaler's+ // stats lookups don't contend with the routing path's worker map updates.+ r.sandboxStatsMu.Lock()+ if len(entry.Sandboxes) > 0 {+ for sbID, stats := range entry.Sandboxes {+ r.sandboxStats[sbID] = stats+ r.sandboxOnWorker[sbID] = entry.ID+ }+ }+ // Prune: any sandbox previously associated with this worker that's no+ // longer in the heartbeat is gone (destroyed/migrated). We don't prune on+ // `len(entry.Sandboxes) == 0` because that may legitimately mean "0+ // sandboxes on this worker right now" (after dance drained it) — and we+ // still want to remove our stale memories.+ for sbID, wID := range r.sandboxOnWorker {+ if wID != entry.ID {+ continue+ }+ if _, still := entry.Sandboxes[sbID]; !still {+ delete(r.sandboxStats, sbID)+ delete(r.sandboxOnWorker, sbID)+ }}+ r.sandboxStatsMu.Unlock()// Ensure gRPC connection exists and is healthy.// Re-dial if address changed, connection is failed/idle, or worker is newly registered.@@ -312,90 +439,137 @@ func (r *RedisWorkerRegistry) dialWorkerLocked(workerID, grpcAddr string) {log.Printf("redis_registry: gRPC connection initiated to worker %s at %s", workerID, grpcAddr)}-// GetLeastLoadedWorker returns the worker with the best combination of remaining capacity-// and resource headroom. Workers under heavy resource pressure (CPU > 90% or mem > 90%)-// are skipped. If region is non-empty, only workers in that region are considered.-// If no workers match the region, falls back to all workers.+// GetLeastLoadedWorker returns the worker with the best combination of slot+// allocation and actual host-memory headroom. Workers above routingHardCapPct+// on CPU/mem/disk, with no slot capacity left, or marked draining are skipped.+// If region is non-empty, only workers in that region are considered; if none+// match, falls back to all workers.+//+// Ranking score (lower is better):+//+// score = Current/Capacity + MemPct/100+//+// MemPct is real RSS-based usage, not committed memory: an idle 16GB-max+// sandbox occupying 200MB of host RAM should not be treated as if it had+// reserved 16GB. Committed-memory accounting over-reserves for the common+// idle-but-large case and pushed traffic away from workers that actually had+// plenty of headroom. CPU and disk are handled by the hard cap, not the+// score, since they're spikier and a transient burst shouldn't permanently+// disprefer a worker.func (r *RedisWorkerRegistry) GetLeastLoadedWorker(region string) (*WorkerEntry, pb.SandboxWorkerClient, error) {r.mu.Lock()defer r.mu.Unlock()- // Simple strategy: pick the worker with fewest sandboxes.- // Skip workers under heavy resource pressure.- // Skip idle reserves unless all active workers are above 60% committed.- // Read Redis routing counters to get real-time sandbox counts across both CPsroutingCtx, routingCancel := context.WithTimeout(context.Background(), time.Second)defer routingCancel()- var eligible []*WorkerEntry- for _, w := range r.workers {- if region != "" && w.Region != region {- continue- }- if w.Draining {- continue- }- if w.CPUPct > 90 || w.MemPct > 90 || w.DiskPct > 90 {- continue- }- // Use Redis routing counter if higher than heartbeat count+ eligible := r.collectEligibleLocked(region, false /* anyRegion */)+ if len(eligible) == 0 && region != "" {+ eligible = r.collectEligibleLocked(region, true /* anyRegion */)+ }+ if len(eligible) == 0 {+ return nil, nil, fmt.Errorf("no workers available")+ }++ // Apply the cross-CP routing counter so an in-flight placement on the+ // other CP is reflected before we score. Heartbeats reconcile to truth+ // within 10s; until then this counter is the only way the other CP's+ // recent picks show up here.+ for _, w := range eligible {rCount, err := r.rdb.Get(routingCtx, "routing:count:"+w.ID).Int()if err == nil && rCount > w.Current {w.Current = rCount}- eligible = append(eligible, w)- }-- // Fallback: try any region- if len(eligible) == 0 && region != "" {- for _, w := range r.workers {- if w.CPUPct > 90 || w.MemPct > 90 || w.DiskPct > 90 {- continue- }- eligible = append(eligible, w)- }}- if len(eligible) == 0 {- return nil, nil, fmt.Errorf("no workers available")+ // Score each eligible worker; track the minimum so we can tie-break.+ type scored struct {+ w *WorkerEntry+ s float64}-- // Find workers tied for fewest sandboxes, round-robin among them- minCount := eligible[0].Current- for _, w := range eligible[1:] {- if w.Current < minCount {- minCount = w.Current+ scoredWorkers := make([]scored, 0, len(eligible))+ minScore := scoreWorker(eligible[0])+ for _, w := range eligible {+ s := scoreWorker(w)+ if s < minScore {+ minScore = s}+ scoredWorkers = append(scoredWorkers, scored{w, s})}++ // Strict tie window. With float scores genuine ties are rare except in the+ // clean-cluster case (all workers at 0 sandboxes, equal MemPct), where RR+ // across both CPs keeps the spread even. Any real difference in load —+ // one extra sandbox or a percent more memory — picks a single winner, so+ // we get the bias toward the lighter worker that the old +1-smoothing+ // logic was failing to provide.+ const tieEpsilon = 1e-9var tied []*WorkerEntry- for _, w := range eligible {- if w.Current <= minCount+1 { // within 1 of the minimum- tied = append(tied, w)+ for _, sc := range scoredWorkers {+ if sc.s-minScore < tieEpsilon {+ tied = append(tied, sc.w)}}- // Use Redis-based round-robin counter so both CPs spread evenly- ctx, cancel := context.WithTimeout(context.Background(), time.Second)- rr, _ := r.rdb.Incr(ctx, "routing:rr").Result()- cancel()- best := tied[rr%int64(len(tied))]+ var best *WorkerEntry+ if len(tied) == 1 {+ best = tied[0]+ } else {+ // Cross-CP round-robin among genuine ties.+ ctx, cancel := context.WithTimeout(context.Background(), time.Second)+ rr, _ := r.rdb.Incr(ctx, "routing:rr").Result()+ cancel()+ best = tied[rr%int64(len(tied))]+ }client, ok := r.clients[best.ID]if !ok {return nil, nil, fmt.Errorf("no gRPC connection to worker %s", best.ID)}- // Atomically increment sandbox count in Redis so BOTH CPs see it instantly.- // The heartbeat will correct to the real count within 10s.+ // Publish the increment so the other CP sees this placement before its+ // next heartbeat reconcile. TTL bridges quiet windows between placements.ctx2, cancel2 := context.WithTimeout(context.Background(), time.Second)r.rdb.Incr(ctx2, "routing:count:"+best.ID)- r.rdb.Expire(ctx2, "routing:count:"+best.ID, 15*time.Second)+ r.rdb.Expire(ctx2, "routing:count:"+best.ID, routingCountTTL)cancel2()- best.Current++ // also update local for this CP+ best.Current++return best, client, nil}+// collectEligibleLocked returns workers passing the routing eligibility gates.+// If anyRegion is true the region filter is dropped (used for cross-region+// fallback when a region is starved). Caller must hold r.mu.+func (r *RedisWorkerRegistry) collectEligibleLocked(region string, anyRegion bool) []*WorkerEntry {+ var out []*WorkerEntry+ for _, w := range r.workers {+ if !anyRegion && region != "" && w.Region != region {+ continue+ }+ if w.Draining {+ continue+ }+ if w.CPUPct >= routingHardCapPct || w.MemPct >= routingHardCapPct || w.DiskPct >= routingHardCapPct {+ continue+ }+ if w.Capacity <= 0 || w.Current >= w.Capacity {+ continue+ }+ out = append(out, w)+ }+ return out+}++// scoreWorker computes a placement score where lower is better. Combines slot+// allocation with actual memory pressure. See GetLeastLoadedWorker comment for+// rationale.+func scoreWorker(w *WorkerEntry) float64 {+ slotPressure := float64(w.Current) / float64(w.Capacity)+ memPressure := w.MemPct / 100.0+ return slotPressure + memPressure+}+// GetWorkerClient returns the gRPC client for a specific worker.func (r *RedisWorkerRegistry) GetWorkerClient(workerID string) (pb.SandboxWorkerClient, error) {// Fast path: read lock, check connection state, return if healthy.@@ -470,8 +644,31 @@ func (r *RedisWorkerRegistry) GetAllWorkers() []*WorkerEntry {return result}-// SetDraining marks a worker as draining — it will not receive new sandboxes.+// SetDraining marks a worker as draining cluster-wide. The drain state is+// published to Redis under drainKeyPrefix+workerID, where every CP's+// handleHeartbeat reads it on the next heartbeat (≤10s) and applies it to its+// in-memory entry. This makes drain state a cross-CP fact rather than a+// per-CP local override.+//+// The local in-memory map is also updated immediately so the calling CP's+// next placement decision sees the change without waiting for the heartbeat+// roundtrip. Redis errors are logged but not returned — local state still+// takes effect, and the worker will undrain naturally via the 24h TTL even if+// the operator can't reach the API to clear it explicitly.func (r *RedisWorkerRegistry) SetDraining(workerID string, draining bool) {+ ctx, cancel := context.WithTimeout(context.Background(), time.Second)+ defer cancel()+ key := drainKeyPrefix + workerID+ if draining {+ if err := r.rdb.Set(ctx, key, "1", drainKeyTTL).Err(); err != nil {+ log.Printf("redis_registry: SetDraining(%s, true): Redis SET failed: %v (local-only)", workerID, err)+ }+ } else {+ if err := r.rdb.Del(ctx, key).Err(); err != nil {+ log.Printf("redis_registry: SetDraining(%s, false): Redis DEL failed: %v (local-only)", workerID, err)+ }+ }+r.mu.Lock()defer r.mu.Unlock()if w, ok := r.workers[workerID]; ok {diff --git a/internal/controlplane/redis_registry_test.go b/internal/controlplane/redis_registry_test.gonew file mode 100644index 00000000..59a9b1c2--- /dev/null+++ b/internal/controlplane/redis_registry_test.go@@ -0,0 +1,197 @@+package controlplane++import (+ "context"+ "fmt"+ "testing"+ "time"++ "github.com/redis/go-redis/v9"+)++// newTestRegistries creates two RedisWorkerRegistry instances against the same+// test Redis instance, simulating two control planes sharing state. Skips the+// test when Redis is not reachable. Returns the registries and a cleanup+// function that removes any keys created under the supplied workerID.+func newTestRegistries(t *testing.T, workerID string) (*RedisWorkerRegistry, *RedisWorkerRegistry) {+ t.Helper()+ const redisURL = "redis://localhost:6379/15"++ probe := redis.NewClient(&redis.Options{Addr: "localhost:6379", DB: 15})+ pingCtx, pingCancel := context.WithTimeout(context.Background(), 2*time.Second)+ defer pingCancel()+ if err := probe.Ping(pingCtx).Err(); err != nil {+ probe.Close()+ t.Skipf("skipping: Redis not available at localhost:6379: %v", err)+ }++ cleanupKeys := func() {+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)+ defer cancel()+ probe.Del(ctx, drainKeyPrefix+workerID)+ probe.Del(ctx, "worker:"+workerID)+ probe.Del(ctx, "routing:count:"+workerID)+ }+ cleanupKeys()++ cp1, err := NewRedisWorkerRegistry(redisURL)+ if err != nil {+ t.Fatalf("cp1 NewRedisWorkerRegistry: %v", err)+ }+ cp2, err := NewRedisWorkerRegistry(redisURL)+ if err != nil {+ cp1.Stop()+ t.Fatalf("cp2 NewRedisWorkerRegistry: %v", err)+ }++ t.Cleanup(func() {+ cp1.Stop()+ cp2.Stop()+ cleanupKeys()+ probe.Close()+ })++ return cp1, cp2+}++func TestSetDrainingPublishesToRedis(t *testing.T) {+ workerID := fmt.Sprintf("test-drain-publish-%d", time.Now().UnixNano())+ cp, _ := newTestRegistries(t, workerID)++ // Bootstrap so SetDraining has a local entry to flip.+ cp.handleHeartbeat(WorkerEntry{ID: workerID, Region: "us-east-1", Capacity: 50})++ cp.SetDraining(workerID, true)++ // Local cache reflects the change immediately.+ if w := cp.GetWorker(workerID); w == nil || !w.Draining {+ t.Fatalf("expected local cache draining=true, got %+v", w)+ }++ // Redis has the key with content "1" and a TTL.+ ctx := context.Background()+ val, err := cp.rdb.Get(ctx, drainKeyPrefix+workerID).Result()+ if err != nil || val != "1" {+ t.Fatalf("expected drain key value \"1\", got val=%q err=%v", val, err)+ }+ ttl, err := cp.rdb.TTL(ctx, drainKeyPrefix+workerID).Result()+ if err != nil {+ t.Fatalf("TTL fetch failed: %v", err)+ }+ if ttl <= 0 || ttl > drainKeyTTL {+ t.Fatalf("expected TTL within (0, %s], got %s", drainKeyTTL, ttl)+ }++ // Clearing removes the key.+ cp.SetDraining(workerID, false)+ if exists, _ := cp.rdb.Exists(ctx, drainKeyPrefix+workerID).Result(); exists != 0 {+ t.Fatalf("expected drain key removed after SetDraining(false)")+ }+ if w := cp.GetWorker(workerID); w == nil || w.Draining {+ t.Fatalf("expected local cache draining=false, got %+v", w)+ }+}++func TestHeartbeatAppliesRedisDrainOverride(t *testing.T) {+ workerID := fmt.Sprintf("test-drain-heartbeat-%d", time.Now().UnixNano())+ cp, _ := newTestRegistries(t, workerID)++ // Worker exists, not draining locally.+ cp.handleHeartbeat(WorkerEntry{ID: workerID, Region: "us-east-1", Capacity: 50})+ if w := cp.GetWorker(workerID); w == nil || w.Draining {+ t.Fatalf("expected initial draining=false, got %+v", w)+ }++ // External actor sets the drain key directly (e.g. another CP).+ ctx := context.Background()+ if err := cp.rdb.Set(ctx, drainKeyPrefix+workerID, "1", drainKeyTTL).Err(); err != nil {+ t.Fatalf("seeding drain key: %v", err)+ }++ // Next heartbeat picks up the override.+ cp.handleHeartbeat(WorkerEntry{ID: workerID, Region: "us-east-1", Capacity: 50})+ if w := cp.GetWorker(workerID); w == nil || !w.Draining {+ t.Fatalf("expected heartbeat to apply drain override, got %+v", w)+ }++ // Clearing the key in Redis lets the next heartbeat reset draining.+ if err := cp.rdb.Del(ctx, drainKeyPrefix+workerID).Err(); err != nil {+ t.Fatalf("deleting drain key: %v", err)+ }+ cp.handleHeartbeat(WorkerEntry{ID: workerID, Region: "us-east-1", Capacity: 50})+ if w := cp.GetWorker(workerID); w == nil || w.Draining {+ t.Fatalf("expected heartbeat to clear drain when key removed, got %+v", w)+ }+}++func TestSetDrainingPropagatesAcrossControlPlanes(t *testing.T) {+ workerID := fmt.Sprintf("test-drain-cross-cp-%d", time.Now().UnixNano())+ cp1, cp2 := newTestRegistries(t, workerID)++ entry := WorkerEntry{ID: workerID, Region: "us-east-1", Capacity: 50}+ cp1.handleHeartbeat(entry)+ cp2.handleHeartbeat(entry)++ // Initially neither CP sees the worker as draining.+ if cp1.GetWorker(workerID).Draining || cp2.GetWorker(workerID).Draining {+ t.Fatal("neither CP should see drain initially")+ }++ // Operator hits CP1 with drain. CP1 reflects immediately; CP2 lags until+ // its next heartbeat.+ cp1.SetDraining(workerID, true)+ if !cp1.GetWorker(workerID).Draining {+ t.Fatal("cp1 should reflect drain immediately on SetDraining")+ }+ if cp2.GetWorker(workerID).Draining {+ t.Fatal("cp2 should not yet reflect drain — its local map hasn't been refreshed")+ }++ // CP2's next heartbeat for that worker pulls the Redis key and converges.+ cp2.handleHeartbeat(entry)+ if !cp2.GetWorker(workerID).Draining {+ t.Fatal("cp2 should converge to draining after heartbeat reads Redis key")+ }++ // Operator clears drain via CP2. CP1 converges on its next heartbeat.+ cp2.SetDraining(workerID, false)+ if cp2.GetWorker(workerID).Draining {+ t.Fatal("cp2 should clear drain immediately on SetDraining(false)")+ }+ cp1.handleHeartbeat(entry)+ if cp1.GetWorker(workerID).Draining {+ t.Fatal("cp1 should converge to not-draining after heartbeat reads cleared key")+ }+}++func TestPlacementSkipsDrainingMarkedViaRedis(t *testing.T) {+ workerID := fmt.Sprintf("test-drain-placement-%d", time.Now().UnixNano())+ cp, _ := newTestRegistries(t, workerID)++ // Single eligible-looking worker entry.+ cp.handleHeartbeat(WorkerEntry{+ ID: workerID,+ Region: "us-east-1",+ GRPCAddr: "127.0.0.1:1", // dial will fail async; placement only needs the entry+ Capacity: 50,+ Current: 0,+ MemPct: 10,+ })++ // Without the drain marker, placement finds the worker (or fails on the+ // gRPC client lookup, which still proves it passed the eligibility gate).+ _, _, err := cp.GetLeastLoadedWorker("us-east-1")+ preDrainNoWorkers := err != nil && err.Error() == "no workers available"+ if preDrainNoWorkers {+ t.Fatal("worker should be eligible before drain marker is set")+ }++ // Set the drain marker via the public API.+ cp.SetDraining(workerID, true)++ // Now placement should report no workers available.+ _, _, err = cp.GetLeastLoadedWorker("us-east-1")+ if err == nil || err.Error() != "no workers available" {+ t.Fatalf("expected no-workers error after drain, got err=%v", err)+ }+}diff --git a/internal/controlplane/scaler.go b/internal/controlplane/scaler.goindex 6b94c893..ded3cf65 100644--- a/internal/controlplane/scaler.go+++ b/internal/controlplane/scaler.go@@ -2,8 +2,10 @@ package controlplaneimport ("context"+ "errors""fmt""log"+ "sort""strings""sync""sync/atomic"@@ -79,6 +81,13 @@ type ScalerConfig struct {MinWorkers int // minimum total workers per region (0 = default 1). Always kept running.MaxWorkers int // maximum workers per region (0 = default 10). Hard cap to prevent runaway launches.IdleReserve int // target idle (0 sandbox) workers for burst absorption (0 = default 1). Separate from MinWorkers.++ // MachineSizes is a ranked list of provider-specific machine sizes the+ // scaler tries in order on each scale-up. On a quota or capacity error+ // (compute.ErrQuotaExceeded), the scaler falls through to the next size.+ // Empty → use the pool's configured default. Non-quota errors fail the+ // launch immediately without burning the rest of the list.+ MachineSizes []string}// pendingLaunch tracks an EC2 instance that was launched but hasn't registered yet.@@ -113,6 +122,8 @@ type Scaler struct {wg sync.WaitGrouprunning bool+ machineSizes []string // ranked list of provider-specific sizes for scale-up fallback+// Rolling replacement: version-aware AMI updatestargetWorkerVersion string // desired worker version (from SSM); workers not matching this get replacedrefreshCount int // tick counter for AMI refresh interval@@ -146,16 +157,17 @@ func NewScaler(cfg ScalerConfig) *Scaler {}return &Scaler{- pool: cfg.Pool,- registry: cfg.Registry,- store: cfg.Store,- state: stateStore,- image: cfg.WorkerImage,- cooldown: cooldown,- interval: interval,- minWorkers: minWorkers,- maxWorkers: maxWorkers,- idleReserve: idleReserve,+ pool: cfg.Pool,+ registry: cfg.Registry,+ store: cfg.Store,+ state: stateStore,+ image: cfg.WorkerImage,+ cooldown: cooldown,+ interval: interval,+ minWorkers: minWorkers,+ maxWorkers: maxWorkers,+ idleReserve: idleReserve,+ machineSizes: cfg.MachineSizes,}}@@ -360,36 +372,43 @@ func (s *Scaler) evaluateRegion(ctx context.Context, region string) {}if needsScaleUp {- // Check cooldown before scaling up+ // Cascade of guards. Important: each guard logs and SKIPS scale-up but+ // must NOT `return` from Evaluate — Phase 5 (rollingReplace) below has+ // to run regardless. Without this, a cluster pinned at maxWorkers with+ // all stale workers can't ever roll because the early-return short-+ // circuits both scaleUp AND rollingReplace, and rollingReplace is the+ // only path that actually frees a slot (drain → terminate → scaleUp).+ canScaleUp := trueif last, ok := s.state.GetLastScaleUp(region); ok && time.Since(last) < s.cooldown {log.Printf("scaler: region %s needs scale-up (%s) but cooldown active (%s remaining)",region, reason, s.cooldown-time.Since(last))- return- }-- // Don't scale up if there are already pending (unregistered) workers- pending := s.state.GetPendingLaunches(region)- if len(pending) > 0 {- log.Printf("scaler: region %s needs scale-up (%s) but %d worker(s) still pending registration",- region, reason, len(pending))- return+ canScaleUp = false+ }+ if canScaleUp {+ pending := s.state.GetPendingLaunches(region)+ if len(pending) > 0 {+ log.Printf("scaler: region %s needs scale-up (%s) but %d worker(s) still pending registration",+ region, reason, len(pending))+ canScaleUp = false+ }}-- // Don't exceed max workers per region (exclude draining workers from capacity)- effectiveWorkers := 0- for _, w := range workers {- if !s.state.IsDraining(w.MachineID) {- effectiveWorkers+++ if canScaleUp {+ effectiveWorkers := 0+ for _, w := range workers {+ if !s.state.IsDraining(w.MachineID) {+ effectiveWorkers+++ }+ }+ if effectiveWorkers+len(s.state.GetPendingLaunches(region)) >= s.maxWorkers {+ log.Printf("scaler: region %s at max workers (%d/%d), skipping scale-up", region, effectiveWorkers, s.maxWorkers)+ canScaleUp = false}}- if effectiveWorkers+len(s.state.GetPendingLaunches(region)) >= s.maxWorkers {- log.Printf("scaler: region %s at max workers (%d/%d), skipping scale-up", region, effectiveWorkers, s.maxWorkers)- return+ if canScaleUp {+ log.Printf("scaler: region %s %s, scaling up (cpu=%.1f%% mem=%.1f%% disk=%.1f%% util=%.1f%%)",+ region, reason, maxCPU, maxMem, maxDisk, utilization*100)+ s.scaleUp(ctx, region)}-- log.Printf("scaler: region %s %s, scaling up (cpu=%.1f%% mem=%.1f%% disk=%.1f%% util=%.1f%%)",- region, reason, maxCPU, maxMem, maxDisk, utilization*100)- s.scaleUp(ctx, region)} else if utilization < scaleDownThreshold && len(workers) > s.minWorkers {// Phase 4: Scale down via smart drain (live-migrate sandboxes, then destroy)log.Printf("scaler: region %s utilization %.1f%% < %.0f%%, initiating smart drain", region, utilization*100, scaleDownThreshold*100)@@ -423,12 +442,7 @@ func (s *Scaler) scaleUp(_ context.Context, region string) {createCtx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)defer cancel()- opts := compute.MachineOpts{- Region: region,- Image: s.image,- }-- machine, err := s.pool.CreateMachine(createCtx, opts)+ machine, usedSize, err := s.createMachineWithFallback(createCtx, region)if err != nil {log.Printf("scaler: failed to create machine in %s: %v", region, err)s.state.RemovePendingLaunch(region, placeholderID)@@ -453,10 +467,51 @@ func (s *Scaler) scaleUp(_ context.Context, region string) {LaunchedAt: time.Now(),})s.state.ResetCreationFailures(region)- log.Printf("scaler: created machine %s in %s (addr=%s), pending registration", machine.ID, region, machine.Addr)+ if usedSize != "" {+ log.Printf("scaler: created machine %s in %s (addr=%s, size=%s), pending registration", machine.ID, region, machine.Addr, usedSize)+ } else {+ log.Printf("scaler: created machine %s in %s (addr=%s), pending registration", machine.ID, region, machine.Addr)+ }}()}+// createMachineWithFallback walks the configured ranked size list and returns+// on the first successful CreateMachine, or after exhausting all sizes. A+// non-quota error short-circuits the loop — we don't burn through fallbacks+// on a malformed image ref or a network timeout. usedSize is the size that+// succeeded (empty when machineSizes is unset and the pool default is used).+func (s *Scaler) createMachineWithFallback(ctx context.Context, region string) (*compute.Machine, string, error) {+ sizes := s.machineSizes+ if len(sizes) == 0 {+ // Empty Size → pool falls back to its own configured default. Preserves+ // the pre-fallback behaviour for deployments that haven't opted in.+ sizes = []string{""}+ }++ var lastErr error+ for i, size := range sizes {+ opts := compute.MachineOpts{+ Region: region,+ Image: s.image,+ Size: size,+ }+ machine, err := s.pool.CreateMachine(ctx, opts)+ if err == nil {+ return machine, size, nil+ }+ lastErr = err+ if !errors.Is(err, compute.ErrQuotaExceeded) {+ return nil, "", err+ }+ remaining := len(sizes) - i - 1+ if remaining > 0 {+ log.Printf("scaler: %s quota/capacity for size=%q, trying next (%d remaining): %v",+ region, size, remaining, err)+ }+ }+ return nil, "", fmt.Errorf("all %d machine sizes exhausted in %s: %w", len(sizes), region, lastErr)+}+// expirePending removes pending launches that have either registered or timed out.func (s *Scaler) expirePending(region string) {pending := s.state.GetPendingLaunches(region)@@ -560,37 +615,86 @@ func (s *Scaler) hibernateBatch(workerID string, count int) {// --- Pressure Evacuation ----// evacuateHotWorkers live-migrates sandboxes off workers that exceed critical thresholds.+// evacuateHotWorkers live-migrates sandboxes off workers that exceed critical+// thresholds.+//+// Two scheduling rules that matter under quota pressure:+//+// 1. **One source at a time.** Earlier versions spawned a goroutine per hot+// source in parallel, which under quota constraints (e.g. eastus2 prod+// where the Dadsv7 family is at ~60% of limit) means every source races+// for the same one or two viable target workers. The first migration+// wins, the others stall on capacity, and we get the imbalance pattern+// we saw on prod: 60 sandboxes piled onto a single worker while the+// others stayed lightly loaded. Serializing means we drain one source+// completely before starting the next.+//+// 2. **Lightest source first.** A 5-sandbox source drains in seconds and+// the now-empty worker becomes a viable target for subsequent drains.+// A 60-sandbox source drained first would block all subsequent+// evacuations behind it. Going lightest-first organically grows our+// target pool from drained sources, so by the time we reach the+// heaviest source we have N workers worth of target capacity instead+// of 1.+//+// Per-sandbox target selection (inside evacuateBatch via liveMigrateSandbox)+// remains in place — it spreads the migrations within a single source's+// drain across whatever targets exist at the moment.func (s *Scaler) evacuateHotWorkers(_ context.Context, region string, workers []*WorkerInfo) {+ // If an evacuation is already in flight, skip this tick — the active+ // drain will finish and release the lock; the next tick picks up.+ if !s.state.TryAcquireEvacuationLock() {+ return+ }+ releaseLock := true+ defer func() {+ if releaseLock {+ s.state.ReleaseEvacuationLock()+ }+ }()++ // Collect hot, non-draining workers off cooldown.+ hot := make([]*WorkerInfo, 0)for _, w := range workers {if w.CPUPct < evacuationCPUThreshold && w.MemPct < evacuationMemThreshold && w.DiskPct < evacuationDiskThreshold {continue}- // Skip if already being drained for scale-downif s.state.IsDraining(w.MachineID) {continue}- // Cooldown — don't evacuate the same worker every tickif last, ok := s.state.GetLastEvacuation(w.ID); ok && time.Since(last) < evacuationCooldown {continue}+ hot = append(hot, w)+ }+ if len(hot) == 0 {+ return+ }- // Find target: least-loaded worker that isn't the hot one and isn't draining.- // Pass 0 for requiredMemMB — evacuateBatch migrates whatever fits; individual- // over-size sandboxes fail their own prepare and are retried elsewhere.- target := s.findMigrationTarget(region, w.ID, 0)- if target == nil {- log.Printf("scaler: worker %s under pressure (cpu=%.1f%% mem=%.1f%% disk=%.1f%%) but no migration target available",- w.ID, w.CPUPct, w.MemPct, w.DiskPct)- continue- }+ // Sort lightest first — see rule 2 in the function comment.+ sort.Slice(hot, func(i, j int) bool {+ return hot[i].Current < hot[j].Current+ })+ src := hot[0]++ // Pre-flight: confirm SOME viable target exists in the region. Pass 0 for+ // requiredMemMB; per-sandbox memory fit is checked inside liveMigrateSandbox+ // after PreCopyDrives reports the real RSS.+ if probe := s.findMigrationTarget(region, src.ID, 0); probe == nil {+ log.Printf("scaler: worker %s under pressure (cpu=%.1f%% mem=%.1f%% disk=%.1f%%, current=%d) but no migration target available — letting scale-up handle this",+ src.ID, src.CPUPct, src.MemPct, src.DiskPct, src.Current)+ return+ }- log.Printf("scaler: worker %s under pressure (cpu=%.1f%% mem=%.1f%% disk=%.1f%%), evacuating up to %d sandboxes to %s",- w.ID, w.CPUPct, w.MemPct, w.DiskPct, evacuationBatchSize, target.ID)+ log.Printf("scaler: worker %s selected for evacuation (lightest of %d hot, current=%d, cpu=%.1f%% mem=%.1f%% disk=%.1f%%) — draining serially",+ src.ID, len(hot), src.Current, src.CPUPct, src.MemPct, src.DiskPct)- s.state.SetLastEvacuation(w.ID, time.Now())- go s.evacuateBatch(w.ID, target.ID, evacuationBatchSize)- }+ s.state.SetLastEvacuation(src.ID, time.Now())+ releaseLock = false // goroutine will release on its own+ go func() {+ defer s.state.ReleaseEvacuationLock()+ s.evacuateBatch(src.ID, evacuationBatchSize)+ }()}// findMigrationTarget returns the best worker to receive migrated sandboxes.@@ -646,8 +750,18 @@ func (s *Scaler) findMigrationTarget(region, excludeWorkerID string, requiredMemreturn best}-// evacuateBatch live-migrates up to count sandboxes from sourceWorker to targetWorker.-func (s *Scaler) evacuateBatch(sourceWorkerID, targetWorkerID string, count int) {+// evacuateBatch live-migrates up to count sandboxes off sourceWorker, picking+// a fresh target per sandbox.+//+// Why per-sandbox target selection: an earlier version pinned all migrations+// in a batch to one target (chosen up front by evacuateHotWorkers). Result —+// during the prod event where 60 sandboxes were rehydrating, every batch+// piled onto whichever worker was least-loaded at batch start, blowing past+// it while the other targets stayed nearly empty. By passing "" to+// liveMigrateSandbox (which then calls findMigrationTarget after PreCopyDrives+// reports actual RSS), each migration sees up-to-date in-flight counts and+// the load distributes naturally across all viable targets.+func (s *Scaler) evacuateBatch(sourceWorkerID string, count int) {ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)defer cancel()@@ -671,15 +785,18 @@ func (s *Scaler) evacuateBatch(sourceWorkerID, targetWorkerID string, count int)if sb.Status != "running" {continue}- if err := s.liveMigrateSandbox(ctx, sb.SandboxId, sourceWorkerID, targetWorkerID); err != nil {+ // Empty targetWorkerID → liveMigrateSandbox re-picks per call. This is+ // what produces the load-distribution behavior described in the+ // function comment.+ if err := s.liveMigrateSandbox(ctx, sb.SandboxId, sourceWorkerID, ""); err != nil {log.Printf("scaler: evacuate: migrate %s failed: %v", sb.SandboxId, err)continue}migrated++}- log.Printf("scaler: evacuation batch complete for %s: %d/%d migrated to %s",- sourceWorkerID, migrated, count, targetWorkerID)+ log.Printf("scaler: evacuation batch complete for %s: %d/%d migrated (per-sandbox target selection)",+ sourceWorkerID, migrated, count)}// --- Smart Scale-Down ---@@ -750,15 +867,42 @@ func (s *Scaler) smartScaleDown(_ context.Context, region string, workers []*Worgo s.drainWorker(target.ID, target.MachineID, region)}-// rollingReplace drains workers running an old version one at a time,-// allowing the scaler to replace them with new-AMI workers.+// rollingReplace executes a quota-aware rolling replacement of stale workers+// (workers whose WorkerVersion != targetWorkerVersion).+//+// The dance under quota pressure (e.g., eastus2 prod with 1-2 spare worker+// slots in the Dadsv7 family quota):+//+// loop {+// pick lightest stale worker S+// drain S (sandboxes migrate onto current-version workers)+// once S is empty: terminate S — frees one quota slot+// if more stale workers remain: scaleUp (consume the freed slot)+// next tick: repeat+// }+//+// At any moment in the dance the cluster holds at most N+1 workers (N stale+// before the dance starts + 1 freshly-launched). The number of new-version+// workers grows by one each cycle: cycle 1 lands all of S1 onto NV1; cycle 2+// lands S2 across {NV1, NV2}; cycle 3 across {NV1, NV2, NV3}; etc. By the+// time we drain the heaviest stale worker, our target pool is N-1 workers+// wide and per-sandbox findMigrationTarget can spread the load evenly.+//+// Without this dance (the prior implementation): drain ran async per tick,+// terminate happened via the separate idle-scale-down path on a different+// tick, and replacement scaleUp only triggered when current==0. So all+// stale workers' sandboxes piled onto whichever single new-version worker+// existed first, overloading it and triggering the agent-reconnect-timeout+// failure modes that this PR also addresses elsewhere.+//+// Serialized via Redis lock so concurrent ticks across CPs don't double-fire.func (s *Scaler) rollingReplace(ctx context.Context, region string, workers []*WorkerInfo) {if s.targetWorkerVersion == "" {return}var stale []*WorkerInfo- var current int+ var current []*WorkerInfofor _, w := range workers {// Skip workers already being drainedif s.state.IsDraining(w.MachineID) {@@ -775,7 +919,7 @@ func (s *Scaler) rollingReplace(ctx context.Context, region string, workers []*Wcontinue // static worker, not autoscaled}if w.WorkerVersion == s.targetWorkerVersion {- current+++ current = append(current, w)} else {stale = append(stale, w)}@@ -785,23 +929,35 @@ func (s *Scaler) rollingReplace(ctx context.Context, region string, workers []*Wreturn}- // If no current-version workers exist, try to launch a replacement first.- // If launch fails (e.g., quota), fall back to draining one stale worker- // to free capacity — the min-workers check will launch a replacement next tick.- if current < 1 {+ // Take the rolling-replace lock so concurrent ticks (or the other CP)+ // don't pick a different stale worker and double-drain. Released after+ // the synchronous dance returns.+ if !s.state.TryAcquireReplacingLock() {+ return+ }+ releaseLock := true+ defer func() {+ if releaseLock {+ s.state.ReleaseReplacingLock()+ }+ }()++ // Need at least one current-version worker (or pending one) to migrate+ // onto. If none, scale up first and wait for next tick.+ if len(current) == 0 {pendingCount := len(s.state.GetPendingLaunches(region))if pendingCount > 0 {- log.Printf("scaler: region %s has %d stale workers, waiting for pending replacement to register",- region, len(stale))+ log.Printf("scaler: rolling replace: %d stale workers, waiting for pending replacement to register",+ len(stale))return}- log.Printf("scaler: rolling replace: all %d workers stale — launching replacement with new version",+ log.Printf("scaler: rolling replace: all %d workers stale — launching first replacement",len(stale))s.scaleUp(ctx, region)return}- // Only drain one stale worker at a time (conservative rolling update)+ // Pick lightest stale — see header comment.target := stale[0]for _, w := range stale[1:] {if w.Current < target.Current {@@ -809,8 +965,9 @@ func (s *Scaler) rollingReplace(ctx context.Context, region string, workers []*W}}- log.Printf("scaler: rolling replace: draining stale worker %s (version=%q, want=%q, sandboxes=%d)",- target.ID, target.WorkerVersion, s.targetWorkerVersion, target.Current)+ moreStaleAfter := len(stale) > 1+ log.Printf("scaler: rolling replace: draining stale worker %s (version=%q, want=%q, sandboxes=%d, %d stale total, %d current)",+ target.ID, target.WorkerVersion, s.targetWorkerVersion, target.Current, len(stale), len(current))s.state.SetDraining(target.MachineID, &drainState{WorkerID: target.ID,@@ -819,7 +976,55 @@ func (s *Scaler) rollingReplace(ctx context.Context, region string, workers []*WStartedAt: time.Now(),})- go s.drainWorker(target.ID, target.MachineID, region)+ // Run the dance in a goroutine so we don't block the scaler tick.+ // The lock is held for the duration via releaseLock = false here.+ releaseLock = false+ go func() {+ defer s.state.ReleaseReplacingLock()+ s.replaceOneStale(ctx, region, target, moreStaleAfter)+ }()+}++// replaceOneStale executes one cycle of the rolling-replace dance:+// drain the target stale worker, terminate it (freeing one quota slot),+// then if more stale workers remain, immediately scale up a replacement+// so the next tick has somewhere to drain to.+//+// Synchronous within the goroutine so the next scaler tick observes the+// post-terminate state cleanly. Lock is held by the caller across this+// function via the defer in rollingReplace.+func (s *Scaler) replaceOneStale(ctx context.Context, region string, target *WorkerInfo, moreStaleAfter bool) {+ // 1. Drain — synchronous; returns when the worker is empty or drainTimeout+ // fires. drainWorker handles per-sandbox findMigrationTarget so each+ // sandbox lands on whichever current-version worker has the most room+ // at that exact moment.+ s.drainWorker(target.ID, target.MachineID, region)++ // 2. Terminate the (now-empty) stale worker. Frees the quota slot for the+ // replacement scaleUp below. We do this even on partial drain — the+ // natural-expiry path will catch any stragglers on the source via+ // sandbox timeouts; better to free quota and unblock the dance than+ // keep an old-version worker around.+ if s.pool != nil && target.MachineID != "" {+ termCtx, cancel := context.WithTimeout(context.Background(), 60*time.Second)+ if err := s.pool.DestroyMachine(termCtx, target.MachineID); err != nil {+ log.Printf("scaler: rolling replace: failed to terminate drained worker %s (%s): %v — letting natural expiry take it",+ target.ID, target.MachineID, err)+ } else {+ log.Printf("scaler: rolling replace: terminated drained worker %s (%s)", target.ID, target.MachineID)+ }+ cancel()+ }++ // 3. If more stale workers remain, fire the next replacement now so it's+ // boot-warm by the time the next tick picks the next stale source.+ // Without this, the next tick would either drain another stale onto+ // the same single new-version worker (the "killer" pile-up) or stall+ // waiting for organic scale-up.+ if moreStaleAfter {+ log.Printf("scaler: rolling replace: more stale workers remain, launching next replacement")+ s.scaleUp(ctx, region)+ }}// drainWorker attempts to live-migrate sandboxes off a worker. If migration fails@@ -1297,6 +1502,10 @@ func (s *Scaler) liveMigrateSandbox(ctx context.Context, sandboxID, sourceWorkerOverlayMode: true,SourceGoldenVersion: sourceGoldenVersion,TargetMemoryMb: actualMemMB,+ // Carry secrets-proxy session from source to target (see PreCopyDrives).+ SealedTokens: preCopyResp.SealedTokens,+ EgressAllowlist: preCopyResp.EgressAllowlist,+ TokenHosts: preCopyResp.TokenHosts,})if err != nil {return fmt.Errorf("prepare target: %w", err)diff --git a/internal/controlplane/scaler_state.go b/internal/controlplane/scaler_state.goindex 3ecc73d4..348d4496 100644--- a/internal/controlplane/scaler_state.go+++ b/internal/controlplane/scaler_state.go@@ -38,6 +38,22 @@ type ScalerStateStore interface {AcquireMigrationLock(sandboxID string) boolReleaseMigrationLock(sandboxID string)+ // Evacuation serialization — only one source worker drains at a time+ // (see evacuateHotWorkers). Held across goroutine boundaries; TTL'd so+ // a crashed CP doesn't permanently block evacuations on restart.+ TryAcquireEvacuationLock() bool+ ReleaseEvacuationLock()++ // Rolling-replace serialization — only one stale-worker replacement is+ // in flight at a time (see rollingReplace). Without this, two ticks+ // could each pick a different stale worker to drain, both targeting the+ // single new-version worker, piling sandboxes onto it and starving the+ // rest of the cluster of capacity. 30-min TTL — a single replacement+ // (drain + terminate + scaleUp + new-worker boot) is bounded but can+ // take 5-10 minutes.+ TryAcquireReplacingLock() bool+ ReleaseReplacingLock()+// In-flight migration trackingIncrInFlight(workerID string)DecrInFlight(workerID string)@@ -243,6 +259,44 @@ func (r *RedisScalerState) ReleaseMigrationLock(sandboxID string) {r.rdb.Del(ctx, "scaler:migrating:"+sandboxID)}+// TryAcquireEvacuationLock takes a region-wide (actually global, single-key)+// lock that serializes evacuateHotWorkers across CPs. 10-min TTL so a CP+// crash doesn't pin the lock — evacuations can resume on the next tick.+func (r *RedisScalerState) TryAcquireEvacuationLock() bool {+ ctx, cancel := r.ctx()+ defer cancel()+ ok, err := r.rdb.SetArgs(ctx, "scaler:evacuating", "1", redis.SetArgs{+ Mode: "NX",+ TTL: 10 * time.Minute,+ }).Result()+ return err == nil && ok == "OK"+}++func (r *RedisScalerState) ReleaseEvacuationLock() {+ ctx, cancel := r.ctx()+ defer cancel()+ r.rdb.Del(ctx, "scaler:evacuating")+}++// TryAcquireReplacingLock serializes rollingReplace across CPs. 30-min TTL+// so a CP crash doesn't pin the lock indefinitely — but long enough that a+// real drain+terminate+scaleUp cycle (5-10 min normally) won't expire it.+func (r *RedisScalerState) TryAcquireReplacingLock() bool {+ ctx, cancel := r.ctx()+ defer cancel()+ ok, err := r.rdb.SetArgs(ctx, "scaler:replacing", "1", redis.SetArgs{+ Mode: "NX",+ TTL: 30 * time.Minute,+ }).Result()+ return err == nil && ok == "OK"+}++func (r *RedisScalerState) ReleaseReplacingLock() {+ ctx, cancel := r.ctx()+ defer cancel()+ r.rdb.Del(ctx, "scaler:replacing")+}+// --- In-flight ---func (r *RedisScalerState) IncrInFlight(workerID string) {@@ -442,6 +496,20 @@ func (m *InMemoryScalerState) AcquireMigrationLock(sandboxID string) bool {func (m *InMemoryScalerState) ReleaseMigrationLock(sandboxID string) {m.migrating.Delete(sandboxID)}+func (m *InMemoryScalerState) TryAcquireEvacuationLock() bool {+ _, loaded := m.migrating.LoadOrStore("__evacuation__", struct{}{})+ return !loaded+}+func (m *InMemoryScalerState) ReleaseEvacuationLock() {+ m.migrating.Delete("__evacuation__")+}+func (m *InMemoryScalerState) TryAcquireReplacingLock() bool {+ _, loaded := m.migrating.LoadOrStore("__replacing__", struct{}{})+ return !loaded+}+func (m *InMemoryScalerState) ReleaseReplacingLock() {+ m.migrating.Delete("__replacing__")+}func (m *InMemoryScalerState) IncrInFlight(workerID string) {m.mu.Lock()defer m.mu.Unlock()diff --git a/internal/controlplane/scaler_test.go b/internal/controlplane/scaler_test.goindex b1d32718..663bed17 100644--- a/internal/controlplane/scaler_test.go+++ b/internal/controlplane/scaler_test.go@@ -2,8 +2,10 @@ package controlplaneimport ("context"+ "errors""fmt""math/rand"+ "reflect""sync""sync/atomic""testing"@@ -131,6 +133,15 @@ type mockPool struct {machines map[string]string // machineID -> regioncreated int32destroyed int32++ // Test hooks for createMachineWithFallback. createErrs is consumed left to+ // right: each CreateMachine call pops one entry; if non-nil it's returned+ // as the error, otherwise the call falls through to the success path.+ // Once empty the pool always succeeds (preserves prior test behaviour).+ // attemptedSizes captures opts.Size on every call so tests can assert the+ // fallback list was walked in order.+ createErrs []error+ attemptedSizes []string}func newMockPool() *mockPool {@@ -138,8 +149,17 @@ func newMockPool() *mockPool {}func (p *mockPool) CreateMachine(_ context.Context, opts compute.MachineOpts) (*compute.Machine, error) {- id := fmt.Sprintf("osb-worker-%d", atomic.AddInt32(&p.created, 1))p.mu.Lock()+ p.attemptedSizes = append(p.attemptedSizes, opts.Size)+ if len(p.createErrs) > 0 {+ err := p.createErrs[0]+ p.createErrs = p.createErrs[1:]+ if err != nil {+ p.mu.Unlock()+ return nil, err+ }+ }+ id := fmt.Sprintf("osb-worker-%d", atomic.AddInt32(&p.created, 1))p.machines[id] = opts.Regionp.mu.Unlock()return &compute.Machine{ID: id, Addr: "10.0.0.1", Region: opts.Region}, nil@@ -886,6 +906,155 @@ func TestDrainCompletesWhenEmpty(t *testing.T) {}}+// ============================================================+// Test: Rolling-replace quota-aware dance+// ============================================================++// TestRollingReplaceDance_StartsWithScaleUpWhenAllStale validates that when+// every worker is stale and no current-version worker exists, the first+// rollingReplace tick scales up a replacement (doesn't drain blindly with+// nowhere to go).+func TestRollingReplaceDance_StartsWithScaleUpWhenAllStale(t *testing.T) {+ reg := newMockRegistry()+ pool := newMockPool()++ // 3 stale workers, all running the old version, none current.+ for i := 1; i <= 3; i++ {+ reg.addWorker(&WorkerInfo{+ ID: fmt.Sprintf("w%d", i), MachineID: fmt.Sprintf("osb-worker-w%d", i),+ Region: "us-east-1", Capacity: 50, Current: 5,+ WorkerVersion: "v-old",+ })+ }++ s := newTestScaler(reg, pool)+ s.targetWorkerVersion = "v-new"++ ctx := context.Background()+ s.rollingReplace(ctx, "us-east-1", reg.GetWorkersByRegion("us-east-1"))++ time.Sleep(150 * time.Millisecond)+ if atomic.LoadInt32(&pool.created) == 0 {+ t.Error("expected scaler to launch a replacement when no current-version worker exists")+ }+ if atomic.LoadInt32(&pool.destroyed) != 0 {+ t.Errorf("expected NO destroys until a current-version worker is up; got %d",+ atomic.LoadInt32(&pool.destroyed))+ }+}++// TestRollingReplaceDance_LightestStaleFirst validates that when multiple+// stale workers exist, the lightest one is picked for drain.+func TestRollingReplaceDance_LightestStaleFirst(t *testing.T) {+ reg := newMockRegistry()+ pool := newMockPool()++ // Heavy stale (30 sandboxes) + Light stale (5 sandboxes) + one current.+ reg.addWorker(&WorkerInfo{+ ID: "wHeavy", MachineID: "osb-worker-wHeavy", Region: "us-east-1",+ Capacity: 50, Current: 30, WorkerVersion: "v-old",+ })+ reg.addWorker(&WorkerInfo{+ ID: "wLight", MachineID: "osb-worker-wLight", Region: "us-east-1",+ Capacity: 50, Current: 5, WorkerVersion: "v-old",+ })+ reg.addWorker(&WorkerInfo{+ ID: "wNew", MachineID: "osb-worker-wNew", Region: "us-east-1",+ Capacity: 50, Current: 0, WorkerVersion: "v-new",+ })++ s := newTestScaler(reg, pool)+ s.targetWorkerVersion = "v-new"++ ctx := context.Background()+ s.rollingReplace(ctx, "us-east-1", reg.GetWorkersByRegion("us-east-1"))++ // Light should be picked, draining state should be set on it (not heavy).+ time.Sleep(50 * time.Millisecond)+ if !s.state.IsDraining("osb-worker-wLight") {+ t.Error("expected lightest stale (wLight) to be picked for drain")+ }+ if s.state.IsDraining("osb-worker-wHeavy") {+ t.Error("expected heavy stale (wHeavy) to be left alone for now")+ }+}++// TestRollingReplaceDance_LockSerializes validates that two concurrent ticks+// can't both fire rollingReplace — only the first acquires the lock.+func TestRollingReplaceDance_LockSerializes(t *testing.T) {+ reg := newMockRegistry()+ pool := newMockPool()++ reg.addWorker(&WorkerInfo{+ ID: "w1", MachineID: "osb-worker-w1", Region: "us-east-1",+ Capacity: 50, Current: 5, WorkerVersion: "v-old",+ })+ reg.addWorker(&WorkerInfo{+ ID: "w2", MachineID: "osb-worker-w2", Region: "us-east-1",+ Capacity: 50, Current: 5, WorkerVersion: "v-old",+ })+ reg.addWorker(&WorkerInfo{+ ID: "wNew", MachineID: "osb-worker-wNew", Region: "us-east-1",+ Capacity: 50, Current: 0, WorkerVersion: "v-new",+ })++ s := newTestScaler(reg, pool)+ s.targetWorkerVersion = "v-new"++ // First call grabs the lock and dispatches the goroutine.+ ctx := context.Background()+ s.rollingReplace(ctx, "us-east-1", reg.GetWorkersByRegion("us-east-1"))++ // Second call — should be a no-op because the lock is held.+ // To detect: count how many SetDraining calls actually pinned a worker.+ // Both w1 and w2 are stale; if the lock didn't hold, the second call would+ // pick the OTHER stale and pin it as draining too.+ s.rollingReplace(ctx, "us-east-1", reg.GetWorkersByRegion("us-east-1"))++ time.Sleep(50 * time.Millisecond)+ pinned := 0+ for _, id := range []string{"osb-worker-w1", "osb-worker-w2"} {+ if s.state.IsDraining(id) {+ pinned+++ }+ }+ if pinned > 1 {+ t.Errorf("expected lock to serialize: only one stale worker should be draining; got %d", pinned)+ }+ if pinned == 0 {+ t.Error("expected at least one stale worker to be draining after first rollingReplace call")+ }+}++// TestRollingReplaceDance_NoOpOnAllCurrent validates that when every worker+// already matches targetWorkerVersion, rollingReplace does nothing.+func TestRollingReplaceDance_NoOpOnAllCurrent(t *testing.T) {+ reg := newMockRegistry()+ pool := newMockPool()++ for i := 1; i <= 3; i++ {+ reg.addWorker(&WorkerInfo{+ ID: fmt.Sprintf("w%d", i), MachineID: fmt.Sprintf("osb-worker-w%d", i),+ Region: "us-east-1", Capacity: 50, Current: 5,+ WorkerVersion: "v-current",+ })+ }++ s := newTestScaler(reg, pool)+ s.targetWorkerVersion = "v-current"++ ctx := context.Background()+ s.rollingReplace(ctx, "us-east-1", reg.GetWorkersByRegion("us-east-1"))++ time.Sleep(50 * time.Millisecond)+ if atomic.LoadInt32(&pool.created) != 0 {+ t.Error("expected no machine creation when all workers are current")+ }+ if atomic.LoadInt32(&pool.destroyed) != 0 {+ t.Error("expected no destroys when all workers are current")+ }+}+// ============================================================// Test: Golden version in migration target selection// ============================================================@@ -1281,6 +1450,140 @@ func TestPendingLaunchRegistered(t *testing.T) {}}+// ============================================================+// Test: Machine-size fallback on quota / capacity errors+// ============================================================++func TestCreateMachineWithFallback_SkipsQuotaErrors(t *testing.T) {+ reg := newMockRegistry()+ pool := newMockPool()+ // First two sizes hit quota, third size succeeds.+ pool.createErrs = []error{+ errors.Join(compute.ErrQuotaExceeded, errors.New("Standard_D16ads_v7: QuotaExceeded")),+ errors.Join(compute.ErrQuotaExceeded, errors.New("Standard_D16ds_v6: ZonalAllocationFailed")),+ nil, // Standard_D16s_v5 — succeeds+ }++ s := NewScaler(ScalerConfig{+ Pool: pool,+ Registry: reg,+ Cooldown: time.Second,+ Interval: 100 * time.Millisecond,+ MinWorkers: 1,+ MaxWorkers: 20,+ MachineSizes: []string{"Standard_D16ads_v7", "Standard_D16ds_v6", "Standard_D16s_v5"},+ })++ machine, used, err := s.createMachineWithFallback(context.Background(), "us-east-1")+ if err != nil {+ t.Fatalf("expected success after fallback, got error: %v", err)+ }+ if machine == nil {+ t.Fatal("expected machine to be returned")+ }+ if used != "Standard_D16s_v5" {+ t.Errorf("expected last size to win, got %q", used)+ }++ wantSizes := []string{"Standard_D16ads_v7", "Standard_D16ds_v6", "Standard_D16s_v5"}+ if !reflect.DeepEqual(pool.attemptedSizes, wantSizes) {+ t.Errorf("expected sizes attempted in order %v, got %v", wantSizes, pool.attemptedSizes)+ }+}++func TestCreateMachineWithFallback_NonQuotaShortCircuits(t *testing.T) {+ reg := newMockRegistry()+ pool := newMockPool()+ // First size fails with a non-quota error — must not iterate further.+ pool.createErrs = []error{+ errors.New("network timeout"),+ nil,+ nil,+ }++ s := NewScaler(ScalerConfig{+ Pool: pool,+ Registry: reg,+ Cooldown: time.Second,+ Interval: 100 * time.Millisecond,+ MinWorkers: 1,+ MaxWorkers: 20,+ MachineSizes: []string{"Standard_D16ads_v7", "Standard_D16ds_v6", "Standard_D16s_v5"},+ })++ _, _, err := s.createMachineWithFallback(context.Background(), "us-east-1")+ if err == nil {+ t.Fatal("expected error from non-quota failure")+ }+ if errors.Is(err, compute.ErrQuotaExceeded) {+ t.Errorf("non-quota error must not be tagged ErrQuotaExceeded: %v", err)+ }+ if len(pool.attemptedSizes) != 1 {+ t.Errorf("expected exactly one attempt on non-quota error, got %d (%v)",+ len(pool.attemptedSizes), pool.attemptedSizes)+ }+}++func TestCreateMachineWithFallback_AllSizesQuota(t *testing.T) {+ reg := newMockRegistry()+ pool := newMockPool()+ pool.createErrs = []error{+ errors.Join(compute.ErrQuotaExceeded, errors.New("a: QuotaExceeded")),+ errors.Join(compute.ErrQuotaExceeded, errors.New("b: SkuNotAvailable")),+ }++ s := NewScaler(ScalerConfig{+ Pool: pool,+ Registry: reg,+ Cooldown: time.Second,+ Interval: 100 * time.Millisecond,+ MinWorkers: 1,+ MaxWorkers: 20,+ MachineSizes: []string{"a", "b"},+ })++ _, _, err := s.createMachineWithFallback(context.Background(), "us-east-1")+ if err == nil {+ t.Fatal("expected error when all sizes fail")+ }+ if !errors.Is(err, compute.ErrQuotaExceeded) {+ t.Errorf("expected wrapped ErrQuotaExceeded after exhausting all sizes, got %v", err)+ }+ if len(pool.attemptedSizes) != 2 {+ t.Errorf("expected both sizes attempted, got %d", len(pool.attemptedSizes))+ }+}++func TestCreateMachineWithFallback_EmptyListUsesPoolDefault(t *testing.T) {+ reg := newMockRegistry()+ pool := newMockPool()++ s := NewScaler(ScalerConfig{+ Pool: pool,+ Registry: reg,+ Cooldown: time.Second,+ Interval: 100 * time.Millisecond,+ MinWorkers: 1,+ MaxWorkers: 20,+ // MachineSizes intentionally empty — should call CreateMachine once+ // with empty Size, deferring to the pool's configured default.+ })++ machine, used, err := s.createMachineWithFallback(context.Background(), "us-east-1")+ if err != nil {+ t.Fatalf("expected success, got %v", err)+ }+ if machine == nil {+ t.Fatal("expected machine")+ }+ if used != "" {+ t.Errorf("expected empty usedSize when MachineSizes is unset, got %q", used)+ }+ if len(pool.attemptedSizes) != 1 || pool.attemptedSizes[0] != "" {+ t.Errorf("expected exactly one attempt with empty Size, got %v", pool.attemptedSizes)+ }+}+// ============================================================// Test: In-flight migration tracking// ============================================================diff --git a/internal/controlplane/server.go b/internal/controlplane/server.goindex 6ec984c2..a9743601 100644--- a/internal/controlplane/server.go+++ b/internal/controlplane/server.go@@ -8,6 +8,7 @@ import ("strings""time"+ "github.com/google/uuid""github.com/labstack/echo/v4""github.com/labstack/echo/v4/middleware""google.golang.org/grpc"@@ -15,6 +16,7 @@ import ("github.com/opensandbox/opensandbox/internal/auth""github.com/opensandbox/opensandbox/internal/db""github.com/opensandbox/opensandbox/internal/grpctls"+ "github.com/opensandbox/opensandbox/internal/obslog"pb "github.com/opensandbox/opensandbox/proto/worker")@@ -39,11 +41,13 @@ func NewServer(store *db.Store, jwtIssuer *auth.JWTIssuer, registry *WorkerRegisregistry: registry,}- // Global middleware+ // Global middleware. RequestID() comes first so the X-Request-Id header+ // is present when obslog.EchoMiddleware tags the request context — that+ // way every log line emitted inside the handler carries the same id.e.Use(middleware.Recover())- e.Use(middleware.Logger())- e.Use(middleware.CORS())e.Use(middleware.RequestID())+ e.Use(obslog.EchoMiddleware())+ e.Use(middleware.CORS())// Health checke.GET("/health", func(c echo.Context) error {@@ -52,7 +56,7 @@ func NewServer(store *db.Store, jwtIssuer *auth.JWTIssuer, registry *WorkerRegis// Auth middlewareapi := e.Group("")- api.Use(auth.PGAPIKeyMiddleware(store, apiKey))+ api.Use(auth.PGAPIKeyMiddleware(store, apiKey, jwtIssuer))// Sandbox lifecycle (control plane only handles create/destroy/discover)api.POST("/sandboxes", s.createSandbox)@@ -99,13 +103,21 @@ func (s *Server) createSandbox(c echo.Context) error {MemoryMB int `json:"memoryMB"`CpuCount int `json:"cpuCount"`Metadata map[string]string `json:"metadata"`- NetworkEnabled bool `json:"networkEnabled"`+ NetworkEnabled *bool `json:"networkEnabled"`SecretStore string `json:"secretStore"` // secret store name — resolves secrets + egress config}if err := c.Bind(&req); err != nil {return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid request: " + err.Error()})}+ // Default networkEnabled to true when caller omits the field. The worker+ // currently sets up networking unconditionally, so a missing field that+ // marshaled to false caused the UI to mislabel sandboxes as "Disabled".+ if req.NetworkEnabled == nil {+ t := true+ req.NetworkEnabled = &t+ }+orgID, ok := auth.GetOrgID(c)if !ok {return c.JSON(http.StatusUnauthorized, map[string]string{"error": "auth required"})@@ -124,11 +136,13 @@ func (s *Server) createSandbox(c echo.Context) error {// Resolve secret store: decrypt secrets + inherit egress allowlistvar egressAllowlist []stringvar secretAllowedHosts map[string]string // env var name → comma-separated hosts (for proto)+ var secretStoreID *uuid.UUID // populated below; passed to CreateSandboxSession so the row's secret_store_id column is set for the refresh fanoutif req.SecretStore != "" {store, err := s.store.GetSecretStoreByName(c.Request().Context(), orgID, req.SecretStore)if err != nil {return c.JSON(http.StatusBadRequest, map[string]string{"error": "secret store not found: " + req.SecretStore})}+ secretStoreID = &store.IDegressAllowlist = store.EgressAllowlist@@ -194,7 +208,7 @@ func (s *Server) createSandbox(c echo.Context) error {Envs: req.Envs,MemoryMb: int32(req.MemoryMB),CpuCount: int32(req.CpuCount),- NetworkEnabled: req.NetworkEnabled,+ NetworkEnabled: *req.NetworkEnabled,EgressAllowlist: egressAllowlist,SecretAllowedHosts: secretAllowedHosts,})@@ -209,7 +223,7 @@ func (s *Server) createSandbox(c echo.Context) error {}cfgJSON, _ := json.Marshal(req)metadataJSON, _ := json.Marshal(req.Metadata)- _, _ = s.store.CreateSandboxSession(ctx, grpcResp.SandboxId, orgID, auth.GetUserID(c), template, region, worker.ID, cfgJSON, metadataJSON)+ _, _ = s.store.CreateSandboxSession(ctx, grpcResp.SandboxId, orgID, auth.GetUserID(c), template, region, worker.ID, cfgJSON, metadataJSON, secretStoreID)// Persist golden version from worker heartbeat so the scaler can read it// from PG instead of relying on in-memory state via gRPC.diff --git a/internal/db/billable_events.go b/internal/db/billable_events.gonew file mode 100644index 00000000..a0bc014a--- /dev/null+++ b/internal/db/billable_events.go@@ -0,0 +1,429 @@+package db++import (+ "context"+ "fmt"+ "time"++ "github.com/google/uuid"+)++// Outbox of metered events for the unified billing pipeline. Phase 2+// (capacity allocator) writes rows here after each 15-min bucket+// settles. Phase 3 (Stripe sender) reads pending rows and ships them.+//+// The (org_id, event_type, memory_mb, bucket_start) UNIQUE constraint+// makes allocator reruns DB-level no-ops, so a crashed or restarted+// allocator can replay any bucket safely.++// Event types written to billable_events.event_type. Mirror the schema+// CHECK constraint in migration 030.+const (+ BillableEventReservedUsage = "reserved_usage"+ BillableEventOverageUsage = "overage_usage"+ BillableEventDiskOverageUsage = "disk_overage_usage"+)++// Delivery states. Mirror the schema CHECK constraint in migration 030.+const (+ BillableDeliveryPending = "pending"+ BillableDeliverySent = "sent"+ BillableDeliveryFailed = "failed"+)++// BillableEvent is one outbox row.+//+// `MemoryMB` is 0 for `reserved_usage` and `disk_overage_usage` (sentinel+// for "not a sandbox tier"), and the running sandbox tier for+// `overage_usage` (one row per tier per bucket via the proportional split+// rule — see ws-pricing/work/001 "Per-second integration walk").+type BillableEvent struct {+ ID uuid.UUID `json:"id"`+ OrgID uuid.UUID `json:"orgId"`+ EventType string `json:"eventType"`+ MemoryMB int `json:"memoryMB"`+ GBSeconds float64 `json:"gbSeconds"`+ BucketStart time.Time `json:"bucketStart"`+ BucketEnd time.Time `json:"bucketEnd"`+ DeliveryState string `json:"deliveryState"`+ StripeEventID *string `json:"stripeEventId,omitempty"`+ CreatedAt time.Time `json:"createdAt"`+ DeliveredAt *time.Time `json:"deliveredAt,omitempty"`+}++// UpsertBillableEvent inserts a new outbox row, or no-ops if a row with+// the same (org_id, event_type, memory_mb, bucket_start) already exists.+// Returns true when a fresh row was written, false when the conflict+// path was taken. Either outcome is success — the allocator is allowed+// to replay buckets without coordination.+func (s *Store) UpsertBillableEvent(ctx context.Context, ev BillableEvent) (inserted bool, err error) {+ if ev.GBSeconds <= 0 {+ return false, fmt.Errorf("billable event gb_seconds must be > 0, got %v", ev.GBSeconds)+ }+ if ev.BucketEnd.Sub(ev.BucketStart) != 15*time.Minute {+ return false, fmt.Errorf("billable event bucket must span exactly 15 minutes")+ }++ tag, err := s.pool.Exec(ctx, `+ INSERT INTO billable_events+ (org_id, event_type, memory_mb, gb_seconds, bucket_start, bucket_end)+ VALUES ($1, $2, $3, $4, $5, $6)+ ON CONFLICT (org_id, event_type, memory_mb, bucket_start) DO NOTHING+ `, ev.OrgID, ev.EventType, ev.MemoryMB, ev.GBSeconds, ev.BucketStart, ev.BucketEnd)+ if err != nil {+ return false, fmt.Errorf("upsert billable event: %w", err)+ }+ return tag.RowsAffected() == 1, nil+}++// ListPendingBillableEvents returns up to `limit` rows in+// `delivery_state = 'pending'` ordered by `(created_at, id)`. The+// ordering is stable across the partial index, so the Stripe sender can+// resume from the oldest pending row without missing or repeating+// anything.+func (s *Store) ListPendingBillableEvents(ctx context.Context, limit int) ([]BillableEvent, error) {+ if limit <= 0 {+ limit = 100+ }+ rows, err := s.pool.Query(ctx, `+ SELECT id, org_id, event_type, memory_mb, gb_seconds,+ bucket_start, bucket_end, delivery_state,+ stripe_event_id, created_at, delivered_at+ FROM billable_events+ WHERE delivery_state = 'pending'+ ORDER BY created_at, id+ LIMIT $1+ `, limit)+ if err != nil {+ return nil, fmt.Errorf("list pending billable events: %w", err)+ }+ defer rows.Close()++ out := make([]BillableEvent, 0, limit)+ for rows.Next() {+ var e BillableEvent+ if err := rows.Scan(+ &e.ID, &e.OrgID, &e.EventType, &e.MemoryMB, &e.GBSeconds,+ &e.BucketStart, &e.BucketEnd, &e.DeliveryState,+ &e.StripeEventID, &e.CreatedAt, &e.DeliveredAt,+ ); err != nil {+ return nil, fmt.Errorf("scan billable event: %w", err)+ }+ out = append(out, e)+ }+ if err := rows.Err(); err != nil {+ return nil, fmt.Errorf("billable events rows: %w", err)+ }+ return out, nil+}++// AllocatorCandidate is one (org, bucket) tuple that may need outbox+// emission. The reconciler runs per-bucket integration on each candidate.+type AllocatorCandidate struct {+ OrgID uuid.UUID+ BucketStart time.Time+}++// PendingBillableEventForSender carries the row plus the joined+// `orgs.stripe_customer_id` so the sender can submit a meter event+// without a second per-event DB lookup. Only orgs with+// `billing_mode='unified'` and a non-null Stripe customer ID are+// returned — legacy orgs and unset-billing orgs are filtered out at+// query time.+type PendingBillableEventForSender struct {+ Event BillableEvent+ StripeCustomerID string+}++// ListPendingBillableEventsForSender returns up to `limit` pending+// rows ordered by `(created_at, id)` from orgs in unified mode that+// have a Stripe customer ID set. Skipped:+// - rows where the org is `billing_mode='legacy'` (UsageReporter+// ships those)+// - rows where the org has no Stripe customer (free-tier or+// unfinished checkout)+// - rows already in `delivery_state='sent'` or `'failed'`+func (s *Store) ListPendingBillableEventsForSender(ctx context.Context, limit int) ([]PendingBillableEventForSender, error) {+ if limit <= 0 {+ limit = 100+ }+ rows, err := s.pool.Query(ctx, `+ SELECT be.id, be.org_id, be.event_type, be.memory_mb, be.gb_seconds,+ be.bucket_start, be.bucket_end, be.delivery_state,+ be.stripe_event_id, be.created_at, be.delivered_at,+ o.stripe_customer_id+ FROM billable_events be+ JOIN orgs o ON o.id = be.org_id+ WHERE be.delivery_state = 'pending'+ AND o.billing_mode = 'unified'+ AND o.stripe_customer_id IS NOT NULL+ ORDER BY be.created_at, be.id+ LIMIT $1+ `, limit)+ if err != nil {+ return nil, fmt.Errorf("list pending billable events for sender: %w", err)+ }+ defer rows.Close()++ out := make([]PendingBillableEventForSender, 0, limit)+ for rows.Next() {+ var p PendingBillableEventForSender+ if err := rows.Scan(+ &p.Event.ID, &p.Event.OrgID, &p.Event.EventType, &p.Event.MemoryMB, &p.Event.GBSeconds,+ &p.Event.BucketStart, &p.Event.BucketEnd, &p.Event.DeliveryState,+ &p.Event.StripeEventID, &p.Event.CreatedAt, &p.Event.DeliveredAt,+ &p.StripeCustomerID,+ ); err != nil {+ return nil, fmt.Errorf("scan pending event for sender: %w", err)+ }+ out = append(out, p)+ }+ if err := rows.Err(); err != nil {+ return nil, fmt.Errorf("pending events for sender rows: %w", err)+ }+ return out, nil+}++// MarkBillableEventSent flips delivery_state to 'sent', stamps+// stripe_event_id and delivered_at. Idempotent at the row level: a+// concurrent re-run with the same id is harmless.+func (s *Store) MarkBillableEventSent(ctx context.Context, id uuid.UUID, stripeEventID string) error {+ _, err := s.pool.Exec(ctx, `+ UPDATE billable_events+ SET delivery_state = 'sent',+ stripe_event_id = $2,+ delivered_at = now()+ WHERE id = $1+ `, id, stripeEventID)+ if err != nil {+ return fmt.Errorf("mark billable event sent: %w", err)+ }+ return nil+}++// ListAllocatorCandidates returns (org, bucket_start) pairs in+// `[lookbackStart, cutoff)` where there's either a reservation or+// scale-event activity, and no row exists yet in `billable_events` for+// that (org, bucket). Result is the work queue for one allocator tick.+//+// `cutoff` should be `now() - settle` truncated to a 15-min boundary —+// only fully-settled buckets become candidates.+//+// **Filter:** only orgs with `plan='pro' AND billing_mode='unified'`.+// Legacy-mode orgs are billed by `UsageReporter`, so writing outbox+// rows for them would be both wasted work and a landmine on a+// later flip (the historical rows would ship at once). Free-plan+// orgs use the legacy credit-deduction path; the future free-tier+// drainer will revisit allocator scope when it ships.+func (s *Store) ListAllocatorCandidates(ctx context.Context, lookbackStart, cutoff time.Time, limit int) ([]AllocatorCandidate, error) {+ if limit <= 0 {+ limit = 500+ }+ rows, err := s.pool.Query(ctx, `+ WITH eligible_orgs AS (+ SELECT id FROM orgs+ WHERE plan = 'pro' AND billing_mode = 'unified'+ ),+ reservation_buckets AS (+ SELECT org_id, starts_at AS bucket_start+ FROM capacity_reservation_intervals+ WHERE starts_at >= $1 AND starts_at < $2+ AND org_id IN (SELECT id FROM eligible_orgs)+ GROUP BY org_id, starts_at+ ),+ scale_buckets AS (+ SELECT se.org_id, b.bucket_start+ FROM sandbox_scale_events se+ CROSS JOIN LATERAL generate_series(+ date_bin('15 minutes', GREATEST(se.started_at, $1), '2000-01-01 00:00:00+00'::timestamptz),+ date_bin('15 minutes', LEAST(COALESCE(se.ended_at, $2), $2) - INTERVAL '1 microsecond', '2000-01-01 00:00:00+00'::timestamptz),+ INTERVAL '15 minutes'+ ) AS b(bucket_start)+ WHERE se.started_at < $2+ AND COALESCE(se.ended_at, $2) > $1+ AND se.org_id IN (SELECT id FROM eligible_orgs)+ GROUP BY se.org_id, b.bucket_start+ ),+ candidates AS (+ SELECT * FROM reservation_buckets+ UNION+ SELECT * FROM scale_buckets+ )+ SELECT c.org_id, c.bucket_start+ FROM candidates c+ WHERE NOT EXISTS (+ SELECT 1 FROM billable_events be+ WHERE be.org_id = c.org_id AND be.bucket_start = c.bucket_start+ )+ ORDER BY c.bucket_start, c.org_id+ LIMIT $3+ `, lookbackStart, cutoff, limit)+ if err != nil {+ return nil, fmt.Errorf("list allocator candidates: %w", err)+ }+ defer rows.Close()++ out := make([]AllocatorCandidate, 0, limit)+ for rows.Next() {+ var c AllocatorCandidate+ if err := rows.Scan(&c.OrgID, &c.BucketStart); err != nil {+ return nil, fmt.Errorf("scan allocator candidate: %w", err)+ }+ out = append(out, c)+ }+ if err := rows.Err(); err != nil {+ return nil, fmt.Errorf("allocator candidate rows: %w", err)+ }+ return out, nil+}++// GetReservedGBForBucket returns the total reserved GB across all+// reservations in `(orgID, ResourceMemoryGB, bucketStart)`. Returns 0+// when no rows exist (no reservation for that bucket).+func (s *Store) GetReservedGBForBucket(ctx context.Context, orgID uuid.UUID, bucketStart time.Time) (int, error) {+ var gb int+ err := s.pool.QueryRow(ctx, `+ SELECT COALESCE(SUM(capacity_gb), 0)::int+ FROM capacity_reservation_intervals+ WHERE org_id = $1 AND resource = $2 AND starts_at = $3+ `, orgID, ResourceMemoryGB, bucketStart).Scan(&gb)+ if err != nil {+ return 0, fmt.Errorf("read reserved gb for bucket: %w", err)+ }+ return gb, nil+}++// GetScaleEventsForBucket returns every scale-event row whose lifetime+// overlaps `[bucketStart, bucketEnd)` for the given org. Open events+// (`ended_at IS NULL`) are returned with `EndedAt = nil`; the caller+// clips them to the bucket boundary.+//+// Sandboxes that back a managed agent with an active per-agent+// subscription are excluded — their compute is paid for by the+// subscription, so they must not also flow through reserved/overage+// metering. See the same NOT EXISTS in GetOrgUsage for rationale.+func (s *Store) GetScaleEventsForBucket(ctx context.Context, orgID uuid.UUID, bucketStart, bucketEnd time.Time) ([]ScaleEvent, error) {+ rows, err := s.pool.Query(ctx, `+ SELECT id, sandbox_id, org_id, memory_mb, cpu_percent, disk_mb, started_at, ended_at+ FROM sandbox_scale_events se+ WHERE org_id = $1+ AND started_at < $3+ AND (ended_at IS NULL OR ended_at > $2)+ AND NOT EXISTS (+ SELECT 1+ FROM sandbox_sessions ss+ JOIN agent_subscriptions asub+ ON asub.org_id = ss.org_id+ AND asub.agent_id = ss.metadata->>'agent_id'+ AND asub.status IN ('active', 'trialing', 'past_due', 'incomplete')+ WHERE ss.sandbox_id = se.sandbox_id+ AND ss.metadata->>'agent_id' IS NOT NULL+ )+ ORDER BY started_at+ `, orgID, bucketStart, bucketEnd)+ if err != nil {+ return nil, fmt.Errorf("read scale events for bucket: %w", err)+ }+ defer rows.Close()++ var out []ScaleEvent+ for rows.Next() {+ var e ScaleEvent+ var orgUUID uuid.UUID+ if err := rows.Scan(&e.ID, &e.SandboxID, &orgUUID, &e.MemoryMB, &e.CPUPct, &e.DiskMB, &e.StartedAt, &e.EndedAt); err != nil {+ return nil, fmt.Errorf("scan scale event: %w", err)+ }+ e.OrgID = orgUUID.String()+ out = append(out, e)+ }+ if err := rows.Err(); err != nil {+ return nil, fmt.Errorf("scale events rows: %w", err)+ }+ return out, nil+}++// ListBillableEventsForOrg returns rows for one org in+// `[from, to)` ordered by `(bucket_start, event_type, memory_mb)`.+// `eventType` is optional — empty string returns all types.+// Used only by the org-scoped debugging endpoint+// `GET /api/capacity/billable-events`; not part of the public spec.+func (s *Store) ListBillableEventsForOrg(ctx context.Context, orgID uuid.UUID, from, to time.Time, eventType string, limit int) ([]BillableEvent, error) {+ if limit <= 0 {+ limit = 200+ }+ args := []any{orgID, from, to, limit}+ typeFilter := ""+ if eventType != "" {+ typeFilter = "AND event_type = $5"+ args = append(args, eventType)+ }+ rows, err := s.pool.Query(ctx, `+ SELECT id, org_id, event_type, memory_mb, gb_seconds,+ bucket_start, bucket_end, delivery_state,+ stripe_event_id, created_at, delivered_at+ FROM billable_events+ WHERE org_id = $1+ AND bucket_start >= $2+ AND bucket_start < $3+ `+typeFilter+`+ ORDER BY bucket_start, event_type, memory_mb+ LIMIT $4+ `, args...)+ if err != nil {+ return nil, fmt.Errorf("list billable events for org: %w", err)+ }+ defer rows.Close()++ out := make([]BillableEvent, 0, limit)+ for rows.Next() {+ var e BillableEvent+ if err := rows.Scan(+ &e.ID, &e.OrgID, &e.EventType, &e.MemoryMB, &e.GBSeconds,+ &e.BucketStart, &e.BucketEnd, &e.DeliveryState,+ &e.StripeEventID, &e.CreatedAt, &e.DeliveredAt,+ ); err != nil {+ return nil, fmt.Errorf("scan billable event: %w", err)+ }+ out = append(out, e)+ }+ if err := rows.Err(); err != nil {+ return nil, fmt.Errorf("billable events rows: %w", err)+ }+ return out, nil+}++// ListBillableEventsForBucket returns every emitted row for a single+// (org, bucket) pair across all event types. Used by the shadow-verify+// script and the dashboard breakdown view to reconcile against+// UsageReporter output.+func (s *Store) ListBillableEventsForBucket(ctx context.Context, orgID uuid.UUID, bucketStart time.Time) ([]BillableEvent, error) {+ rows, err := s.pool.Query(ctx, `+ SELECT id, org_id, event_type, memory_mb, gb_seconds,+ bucket_start, bucket_end, delivery_state,+ stripe_event_id, created_at, delivered_at+ FROM billable_events+ WHERE org_id = $1 AND bucket_start = $2+ ORDER BY event_type, memory_mb+ `, orgID, bucketStart)+ if err != nil {+ return nil, fmt.Errorf("list bucket billable events: %w", err)+ }+ defer rows.Close()++ out := make([]BillableEvent, 0, 8)+ for rows.Next() {+ var e BillableEvent+ if err := rows.Scan(+ &e.ID, &e.OrgID, &e.EventType, &e.MemoryMB, &e.GBSeconds,+ &e.BucketStart, &e.BucketEnd, &e.DeliveryState,+ &e.StripeEventID, &e.CreatedAt, &e.DeliveredAt,+ ); err != nil {+ return nil, fmt.Errorf("scan billable event: %w", err)+ }+ out = append(out, e)+ }+ if err := rows.Err(); err != nil {+ return nil, fmt.Errorf("billable events rows: %w", err)+ }+ return out, nil+}diff --git a/internal/db/billable_events_pgfixture_test.go b/internal/db/billable_events_pgfixture_test.gonew file mode 100644index 00000000..132cafa0--- /dev/null+++ b/internal/db/billable_events_pgfixture_test.go@@ -0,0 +1,491 @@+//go:build pgfixture++// Integration tests for the billable_events outbox. Run only under+// `go test -tags=pgfixture` against a real Postgres pointed at by+// TEST_DATABASE_URL.+//+// TEST_DATABASE_URL=postgres://user:pass@localhost:5432/dbname?sslmode=disable \+// go test -tags=pgfixture ./internal/db/ -run BillableEvents -v+package db++import (+ "context"+ "strings"+ "testing"+ "time"++ "github.com/google/uuid"+)++// makeBucketEvent builds a valid BillableEvent for a 15-min bucket+// starting at base + (m × 15 min).+func makeBucketEvent(orgID uuid.UUID, eventType string, memoryMB int, gbSeconds float64, base time.Time, m int) BillableEvent {+ start := base.Truncate(15 * time.Minute).Add(time.Duration(m) * 15 * time.Minute)+ return BillableEvent{+ OrgID: orgID,+ EventType: eventType,+ MemoryMB: memoryMB,+ GBSeconds: gbSeconds,+ BucketStart: start,+ BucketEnd: start.Add(15 * time.Minute),+ }+}++func TestBillableEvents_upsertIdempotent_pgfixture(t *testing.T) {+ ctx := context.Background()+ store := openPgStore(t)+ orgID := seedOrgWithCap(t, store, 64)++ base := time.Date(2030, 6, 1, 0, 0, 0, 0, time.UTC)+ ev := makeBucketEvent(orgID, BillableEventReservedUsage, 0, 14400, base, 0) // 16 GB × 900s++ inserted, err := store.UpsertBillableEvent(ctx, ev)+ if err != nil {+ t.Fatalf("first upsert: %v", err)+ }+ if !inserted {+ t.Error("expected first upsert to insert, got conflict no-op")+ }++ // Same key — must no-op.+ inserted, err = store.UpsertBillableEvent(ctx, ev)+ if err != nil {+ t.Fatalf("replay upsert: %v", err)+ }+ if inserted {+ t.Error("expected replay to no-op, got fresh insert")+ }++ // Different gb_seconds, same key — should still no-op (UNIQUE wins+ // over the new value; allocator must not be able to "correct" a+ // historical row by reinserting).+ ev2 := ev+ ev2.GBSeconds = 99999+ inserted, err = store.UpsertBillableEvent(ctx, ev2)+ if err != nil {+ t.Fatalf("differing-value upsert: %v", err)+ }+ if inserted {+ t.Error("expected differing-value replay to no-op, got fresh insert")+ }++ // Verify the persisted row still has the original gb_seconds.+ rows, err := store.ListBillableEventsForBucket(ctx, orgID, ev.BucketStart)+ if err != nil {+ t.Fatalf("list: %v", err)+ }+ if len(rows) != 1 {+ t.Fatalf("expected 1 row, got %d", len(rows))+ }+ if rows[0].GBSeconds != 14400 {+ t.Errorf("gb_seconds: got %v, want 14400 (replay must not overwrite)", rows[0].GBSeconds)+ }+}++func TestBillableEvents_distinctKeys_pgfixture(t *testing.T) {+ ctx := context.Background()+ store := openPgStore(t)+ orgID := seedOrgWithCap(t, store, 64)++ base := time.Date(2030, 7, 1, 0, 0, 0, 0, time.UTC)++ // All four of these must be distinct rows: same org, same bucket,+ // but different (event_type, memory_mb) tuples.+ cases := []BillableEvent{+ makeBucketEvent(orgID, BillableEventReservedUsage, 0, 7200, base, 0),+ makeBucketEvent(orgID, BillableEventOverageUsage, 4096, 1800, base, 0),+ makeBucketEvent(orgID, BillableEventOverageUsage, 8192, 900, base, 0),+ makeBucketEvent(orgID, BillableEventDiskOverageUsage, 0, 18000, base, 0),+ }+ for i, ev := range cases {+ ins, err := store.UpsertBillableEvent(ctx, ev)+ if err != nil {+ t.Fatalf("upsert[%d]: %v", i, err)+ }+ if !ins {+ t.Errorf("upsert[%d] expected insert, got conflict no-op", i)+ }+ }++ rows, err := store.ListBillableEventsForBucket(ctx, orgID, cases[0].BucketStart)+ if err != nil {+ t.Fatalf("list: %v", err)+ }+ if len(rows) != 4 {+ t.Fatalf("expected 4 rows, got %d", len(rows))+ }+}++func TestBillableEvents_listPendingOrder_pgfixture(t *testing.T) {+ ctx := context.Background()+ store := openPgStore(t)+ orgID := seedOrgWithCap(t, store, 64)++ base := time.Date(2030, 8, 1, 0, 0, 0, 0, time.UTC)++ for i := 0; i < 5; i++ {+ ev := makeBucketEvent(orgID, BillableEventReservedUsage, 0, 900, base, i)+ if _, err := store.UpsertBillableEvent(ctx, ev); err != nil {+ t.Fatalf("upsert[%d]: %v", i, err)+ }+ time.Sleep(2 * time.Millisecond) // distinct created_at ordering+ }++ pending, err := store.ListPendingBillableEvents(ctx, 100)+ if err != nil {+ t.Fatalf("list pending: %v", err)+ }+ mine := 0+ var prev time.Time+ for _, e := range pending {+ if e.OrgID != orgID {+ continue // other tests may have left rows around+ }+ mine+++ if !prev.IsZero() && e.CreatedAt.Before(prev) {+ t.Errorf("pending list out of created_at order")+ }+ prev = e.CreatedAt+ if e.DeliveryState != BillableDeliveryPending {+ t.Errorf("expected pending, got %q", e.DeliveryState)+ }+ }+ if mine != 5 {+ t.Errorf("expected 5 of our rows in pending list, got %d", mine)+ }+}++func TestBillableEvents_allocatorCandidates_pgfixture(t *testing.T) {+ ctx := context.Background()+ store := openPgStore(t)+ orgID := seedOrgWithCap(t, store, 64)++ // Use a far-future window so we don't intersect with state from+ // other tests in the same DB.+ bucket := time.Date(2031, 1, 1, 12, 0, 0, 0, time.UTC)+ cutoff := bucket.Add(15 * time.Minute) // bucket end = candidate window end+ lookbackStart := bucket.Add(-1 * time.Hour)++ // Seed one scale event covering the bucket and one reservation+ // for the same bucket.+ end := bucket.Add(15 * time.Minute)+ if _, err := store.pool.Exec(ctx,+ `INSERT INTO sandbox_scale_events (sandbox_id, org_id, memory_mb, cpu_percent, disk_mb, started_at, ended_at)+ VALUES ($1, $2, $3, $4, $5, $6, $7)`,+ "sbx-alloc", orgID, 8192, 200, 20480, bucket, &end); err != nil {+ t.Fatalf("seed scale event: %v", err)+ }+ if _, err := store.pool.Exec(ctx, `+ INSERT INTO capacity_reservation_intervals+ (reservation_id, org_id, resource, starts_at, ends_at, capacity_gb)+ VALUES ($1, $2, $3, $4, $5, $6)+ `, uuid.New(), orgID, ResourceMemoryGB, bucket, end, 4); err != nil {+ t.Fatalf("seed reservation: %v", err)+ }++ cands, err := store.ListAllocatorCandidates(ctx, lookbackStart, cutoff, 100)+ if err != nil {+ t.Fatalf("list candidates: %v", err)+ }+ found := false+ for _, c := range cands {+ if c.OrgID == orgID && c.BucketStart.Equal(bucket) {+ found = true+ break+ }+ }+ if !found {+ t.Fatalf("expected candidate (orgID=%s, bucket=%s) in result, got %d candidates", orgID, bucket, len(cands))+ }++ // Now emit a row for that bucket and confirm the candidate+ // disappears (NOT EXISTS clause).+ ev := makeBucketEvent(orgID, BillableEventReservedUsage, 0, 4*900, bucket, 0)+ if _, err := store.UpsertBillableEvent(ctx, ev); err != nil {+ t.Fatalf("upsert: %v", err)+ }+ cands, err = store.ListAllocatorCandidates(ctx, lookbackStart, cutoff, 100)+ if err != nil {+ t.Fatalf("list candidates 2: %v", err)+ }+ for _, c := range cands {+ if c.OrgID == orgID && c.BucketStart.Equal(bucket) {+ t.Fatalf("expected candidate to be excluded after emission, got it back")+ }+ }+}++func TestBillableEvents_reservedAndScaleHelpers_pgfixture(t *testing.T) {+ ctx := context.Background()+ store := openPgStore(t)+ orgID := seedOrgWithCap(t, store, 64)++ bucket := time.Date(2031, 2, 1, 12, 0, 0, 0, time.UTC)+ end := bucket.Add(15 * time.Minute)++ // Two reservations (4 GB + 8 GB) on the same bucket → SUM = 12.+ for _, gb := range []int{4, 8} {+ if _, err := store.pool.Exec(ctx, `+ INSERT INTO capacity_reservation_intervals+ (reservation_id, org_id, resource, starts_at, ends_at, capacity_gb)+ VALUES ($1, $2, $3, $4, $5, $6)+ `, uuid.New(), orgID, ResourceMemoryGB, bucket, end, gb); err != nil {+ t.Fatalf("seed reservation %dGB: %v", gb, err)+ }+ }+ got, err := store.GetReservedGBForBucket(ctx, orgID, bucket)+ if err != nil {+ t.Fatalf("get reserved gb: %v", err)+ }+ if got != 12 {+ t.Errorf("reserved gb: got %d, want 12", got)+ }++ // Scale events: one fully inside, one straddling the start, one+ // straddling the end, and one completely outside (must not be+ // returned).+ insertSE := func(sandboxID string, memMB, diskMB int, started time.Time, ended *time.Time) {+ if _, err := store.pool.Exec(ctx,+ `INSERT INTO sandbox_scale_events (sandbox_id, org_id, memory_mb, cpu_percent, disk_mb, started_at, ended_at)+ VALUES ($1, $2, $3, $4, $5, $6, $7)`,+ sandboxID, orgID, memMB, memMB/40, diskMB, started, ended); err != nil {+ t.Fatalf("seed scale event %s: %v", sandboxID, err)+ }+ }+ preEnd := bucket.Add(5 * time.Minute)+ postStart := bucket.Add(10 * time.Minute)+ farPast := bucket.Add(-2 * time.Hour)+ farPastEnd := bucket.Add(-1 * time.Hour)+ insertSE("sbx-inside", 4096, 20480, bucket.Add(2*time.Minute), &preEnd)+ insertSE("sbx-pre", 8192, 20480, bucket.Add(-3*time.Minute), &postStart)+ insertSE("sbx-post", 16384, 20480, postStart, nil) // open+ insertSE("sbx-outside", 1024, 20480, farPast, &farPastEnd)++ events, err := store.GetScaleEventsForBucket(ctx, orgID, bucket, end)+ if err != nil {+ t.Fatalf("get scale events: %v", err)+ }+ if len(events) != 3 {+ t.Errorf("expected 3 in-window events, got %d", len(events))+ }+ for _, e := range events {+ if e.SandboxID == "sbx-outside" {+ t.Errorf("expected sbx-outside excluded, got it")+ }+ }+}++// seedOrgWithBillingMode inserts an org with explicit plan, billing_mode,+// and optional Stripe customer ID — used by the sender's filtering+// tests so we can exercise every branch of the JOIN+WHERE clause.+func seedOrgWithBillingMode(t *testing.T, store *Store, plan, billingMode string, stripeCustomerID *string) uuid.UUID {+ t.Helper()+ ctx := context.Background()+ orgID := uuid.New()+ _, err := store.pool.Exec(ctx, `+ INSERT INTO orgs (id, name, slug, plan, billing_mode, stripe_customer_id, max_concurrent_sandboxes, max_sandbox_timeout_sec, max_disk_mb, max_memory_gb)+ VALUES ($1, $2, $3, $4, $5, $6, 100, 86400, 20480, 64)+ `, orgID, "sender-"+orgID.String()[:8], "sender-"+orgID.String()[:8], plan, billingMode, stripeCustomerID)+ if err != nil {+ t.Fatalf("seed org plan=%s billing_mode=%s: %v", plan, billingMode, err)+ }+ return orgID+}++func TestSender_listFiltersCorrectly_pgfixture(t *testing.T) {+ ctx := context.Background()+ store := openPgStore(t)++ // Three orgs covering all branches of the sender's JOIN+WHERE filter.+ // Each gets a distinct stripe_customer_id (unique constraint on orgs).+ cusUnified := "cus_test_unified_" + uuid.New().String()[:8]+ cusLegacy := "cus_test_legacy_" + uuid.New().String()[:8]+ orgUnified := seedOrgWithBillingMode(t, store, "pro", "unified", &cusUnified)+ orgLegacy := seedOrgWithBillingMode(t, store, "pro", "legacy", &cusLegacy)+ orgUnifiedNoCustomer := seedOrgWithBillingMode(t, store, "pro", "unified", nil)++ // Use far-future buckets to avoid cross-test interference.+ base := time.Date(2032, 1, 1, 12, 0, 0, 0, time.UTC)+ for i, orgID := range []uuid.UUID{orgUnified, orgLegacy, orgUnifiedNoCustomer} {+ ev := makeBucketEvent(orgID, BillableEventOverageUsage, 8192, 7200, base, i)+ if _, err := store.UpsertBillableEvent(ctx, ev); err != nil {+ t.Fatalf("upsert org %d: %v", i, err)+ }+ }++ pending, err := store.ListPendingBillableEventsForSender(ctx, 100)+ if err != nil {+ t.Fatalf("list pending: %v", err)+ }++ mine := map[uuid.UUID]bool{}+ for _, p := range pending {+ mine[p.Event.OrgID] = true+ if p.Event.OrgID == orgUnified && p.StripeCustomerID != cusUnified {+ t.Errorf("expected stripe_customer_id=%q, got %q", cusUnified, p.StripeCustomerID)+ }+ }+ if !mine[orgUnified] {+ t.Errorf("expected unified+customer org in result")+ }+ if mine[orgLegacy] {+ t.Errorf("legacy org must be excluded (UsageReporter handles it)")+ }+ if mine[orgUnifiedNoCustomer] {+ t.Errorf("unified org without stripe_customer_id must be excluded")+ }+}++func TestSender_markSent_pgfixture(t *testing.T) {+ ctx := context.Background()+ store := openPgStore(t)++ customerID := "cus_test_marksent"+ orgID := seedOrgWithBillingMode(t, store, "pro", "unified", &customerID)+ base := time.Date(2032, 2, 1, 12, 0, 0, 0, time.UTC)+ ev := makeBucketEvent(orgID, BillableEventOverageUsage, 8192, 7200, base, 0)+ if _, err := store.UpsertBillableEvent(ctx, ev); err != nil {+ t.Fatalf("upsert: %v", err)+ }++ // Find the event we just inserted (id is generated by the DB).+ pending, err := store.ListPendingBillableEventsForSender(ctx, 100)+ if err != nil {+ t.Fatalf("list: %v", err)+ }+ var eventID uuid.UUID+ for _, p := range pending {+ if p.Event.OrgID == orgID {+ eventID = p.Event.ID+ break+ }+ }+ if eventID == uuid.Nil {+ t.Fatalf("could not locate inserted event")+ }++ if err := store.MarkBillableEventSent(ctx, eventID, "stripe_test_event_42"); err != nil {+ t.Fatalf("mark sent: %v", err)+ }++ // Confirm row flipped + sender no longer sees it.+ rows, err := store.ListBillableEventsForBucket(ctx, orgID, ev.BucketStart)+ if err != nil {+ t.Fatalf("list bucket: %v", err)+ }+ if len(rows) != 1 {+ t.Fatalf("expected 1 row, got %d", len(rows))+ }+ if rows[0].DeliveryState != BillableDeliverySent {+ t.Errorf("delivery_state: got %q, want sent", rows[0].DeliveryState)+ }+ if rows[0].StripeEventID == nil || *rows[0].StripeEventID != "stripe_test_event_42" {+ t.Errorf("stripe_event_id mismatch: %v", rows[0].StripeEventID)+ }+ if rows[0].DeliveredAt == nil {+ t.Errorf("delivered_at should be set")+ }++ pending2, err := store.ListPendingBillableEventsForSender(ctx, 100)+ if err != nil {+ t.Fatalf("list pending 2: %v", err)+ }+ for _, p := range pending2 {+ if p.Event.ID == eventID {+ t.Errorf("sender still sees event after mark sent")+ }+ }+}++func TestAllocatorCandidates_filtersByBillingMode_pgfixture(t *testing.T) {+ ctx := context.Background()+ store := openPgStore(t)++ cusUnified := "cus_test_alloc_unified_" + uuid.New().String()[:8]+ cusLegacy := "cus_test_alloc_legacy_" + uuid.New().String()[:8]+ orgUnified := seedOrgWithBillingMode(t, store, "pro", "unified", &cusUnified)+ orgLegacy := seedOrgWithBillingMode(t, store, "pro", "legacy", &cusLegacy)+ orgFree := seedOrgWithBillingMode(t, store, "free", "unified", nil)++ // Far-future window so other tests don't interfere.+ bucket := time.Date(2032, 3, 1, 12, 0, 0, 0, time.UTC)+ end := bucket.Add(15 * time.Minute)+ cutoff := end+ lookbackStart := bucket.Add(-1 * time.Hour)++ // Each org gets one scale event covering the bucket.+ for _, orgID := range []uuid.UUID{orgUnified, orgLegacy, orgFree} {+ if _, err := store.pool.Exec(ctx,+ `INSERT INTO sandbox_scale_events (sandbox_id, org_id, memory_mb, cpu_percent, disk_mb, started_at, ended_at)+ VALUES ($1, $2, $3, $4, $5, $6, $7)`,+ "sbx-"+orgID.String()[:8], orgID, 8192, 200, 20480, bucket, &end); err != nil {+ t.Fatalf("seed scale event: %v", err)+ }+ }++ cands, err := store.ListAllocatorCandidates(ctx, lookbackStart, cutoff, 100)+ if err != nil {+ t.Fatalf("list candidates: %v", err)+ }++ mine := map[uuid.UUID]bool{}+ for _, c := range cands {+ if c.BucketStart.Equal(bucket) {+ mine[c.OrgID] = true+ }+ }+ if !mine[orgUnified] {+ t.Errorf("expected pro+unified org as candidate")+ }+ if mine[orgLegacy] {+ t.Errorf("legacy pro org must NOT be a candidate (UsageReporter handles it)")+ }+ if mine[orgFree] {+ t.Errorf("free org must NOT be a candidate (legacy credit deduction handles it)")+ }+}++func TestBillableEvents_validation_pgfixture(t *testing.T) {+ ctx := context.Background()+ store := openPgStore(t)+ orgID := seedOrgWithCap(t, store, 64)++ base := time.Date(2030, 9, 1, 0, 0, 0, 0, time.UTC)++ cases := []struct {+ name string+ mutate func(*BillableEvent)+ wantSub string+ }{+ {+ name: "zero gb_seconds rejected by handler",+ mutate: func(e *BillableEvent) { e.GBSeconds = 0 },+ wantSub: "gb_seconds must be > 0",+ },+ {+ name: "non-15-minute bucket rejected by handler",+ mutate: func(e *BillableEvent) { e.BucketEnd = e.BucketStart.Add(20 * time.Minute) },+ wantSub: "bucket must span exactly 15 minutes",+ },+ {+ name: "unknown event_type rejected by schema CHECK",+ mutate: func(e *BillableEvent) {+ e.EventType = "totally_made_up"+ },+ wantSub: "billable_events_event_type_check",+ },+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ ev := makeBucketEvent(orgID, BillableEventReservedUsage, 0, 900, base, 0)+ tc.mutate(&ev)+ _, err := store.UpsertBillableEvent(ctx, ev)+ if err == nil {+ t.Fatalf("expected error containing %q, got nil", tc.wantSub)+ }+ if !strings.Contains(err.Error(), tc.wantSub) {+ t.Errorf("error %q does not contain %q", err.Error(), tc.wantSub)+ }+ })+ }+}diff --git a/internal/db/migrations/030_billable_events.down.sql b/internal/db/migrations/030_billable_events.down.sqlnew file mode 100644index 00000000..e3974688--- /dev/null+++ b/internal/db/migrations/030_billable_events.down.sql@@ -0,0 +1 @@+DROP TABLE IF EXISTS billable_events;diff --git a/internal/db/migrations/030_billable_events.up.sql b/internal/db/migrations/030_billable_events.up.sqlnew file mode 100644index 00000000..443da3eb--- /dev/null+++ b/internal/db/migrations/030_billable_events.up.sql@@ -0,0 +1,46 @@+-- Outbox of metered events for the unified billing pipeline.+-- The capacity allocator (phase 2) writes one row per (org, event_type,+-- memory_mb, bucket_start) after each 15-min bucket settles. The Stripe+-- sender (phase 3) reads delivery_state='pending' rows and ships them.+--+-- The (org_id, event_type, memory_mb, bucket_start) UNIQUE constraint+-- makes allocator reruns idempotent at the DB level — a crashed+-- allocator can replay any bucket without producing duplicate charges.+--+-- v1 event_types:+-- 'reserved_usage' — pre-booked capacity charge, single synthetic+-- tier per (org, bucket); memory_mb = 0+-- 'overage_usage' — instant usage above the reserved floor,+-- emitted per running sandbox tier with the+-- tier as memory_mb+-- 'disk_overage_usage' — disk above the 20 GB allowance, org-level+-- per bucket; memory_mb = 0+CREATE TABLE IF NOT EXISTS billable_events (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ org_id UUID NOT NULL,+ event_type TEXT NOT NULL,+ memory_mb INTEGER NOT NULL,+ gb_seconds NUMERIC NOT NULL,+ bucket_start TIMESTAMPTZ NOT NULL,+ bucket_end TIMESTAMPTZ NOT NULL,+ delivery_state TEXT NOT NULL DEFAULT 'pending',+ stripe_event_id TEXT,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ delivered_at TIMESTAMPTZ,+ UNIQUE (org_id, event_type, memory_mb, bucket_start),+ CHECK (event_type IN ('reserved_usage', 'overage_usage', 'disk_overage_usage')),+ CHECK (delivery_state IN ('pending', 'sent', 'failed')),+ CHECK (gb_seconds > 0),+ CHECK (memory_mb >= 0),+ CHECK (bucket_end = bucket_start + INTERVAL '15 minutes')+);++-- Sender query: pending rows in arrival order. Partial index keeps the+-- index small as 'sent' rows accumulate.+CREATE INDEX IF NOT EXISTS idx_billable_events_pending+ ON billable_events (created_at, id)+ WHERE delivery_state = 'pending';++-- Per-org scans (shadow-verify, audit, dashboard breakdown).+CREATE INDEX IF NOT EXISTS idx_billable_events_org_bucket+ ON billable_events (org_id, bucket_start);diff --git a/internal/db/migrations/031_orgs_billing_mode.down.sql b/internal/db/migrations/031_orgs_billing_mode.down.sqlnew file mode 100644index 00000000..5dca6648--- /dev/null+++ b/internal/db/migrations/031_orgs_billing_mode.down.sql@@ -0,0 +1 @@+ALTER TABLE orgs DROP COLUMN IF EXISTS billing_mode;diff --git a/internal/db/migrations/031_orgs_billing_mode.up.sql b/internal/db/migrations/031_orgs_billing_mode.up.sqlnew file mode 100644index 00000000..65f7ac0d--- /dev/null+++ b/internal/db/migrations/031_orgs_billing_mode.up.sql@@ -0,0 +1,14 @@+-- Per-org billing pipeline selector. The unified pipeline (allocator+-- + outbox + sender) ships outbox rows to Stripe for orgs in+-- 'unified' mode; UsageReporter ships for orgs in 'legacy' mode.+-- Both paths use the same dollar amounts via current tiered rates —+-- the column controls which goroutine emits the meter events, not+-- what the customer pays.+--+-- Policy: new orgs default to 'unified' (covered by the column+-- DEFAULT). Existing orgs are pinned to 'legacy' below to preserve+-- their current billing path until an explicit decision flips them.+ALTER TABLE orgs ADD COLUMN billing_mode TEXT NOT NULL DEFAULT 'unified'+ CHECK (billing_mode IN ('legacy', 'unified'));++UPDATE orgs SET billing_mode = 'legacy';diff --git a/internal/db/migrations/035_sandbox_autoscale.down.sql b/internal/db/migrations/035_sandbox_autoscale.down.sqlnew file mode 100644index 00000000..e0642605--- /dev/null+++ b/internal/db/migrations/035_sandbox_autoscale.down.sql@@ -0,0 +1,7 @@+DROP INDEX IF EXISTS idx_sandbox_sessions_autoscale_active;++ALTER TABLE sandbox_sessions+ DROP COLUMN IF EXISTS autoscale_last_event_at,+ DROP COLUMN IF EXISTS autoscale_max_mb,+ DROP COLUMN IF EXISTS autoscale_min_mb,+ DROP COLUMN IF EXISTS autoscale_enabled;diff --git a/internal/db/migrations/035_sandbox_autoscale.up.sql b/internal/db/migrations/035_sandbox_autoscale.up.sqlnew file mode 100644index 00000000..db695569--- /dev/null+++ b/internal/db/migrations/035_sandbox_autoscale.up.sql@@ -0,0 +1,19 @@+-- Per-sandbox autoscaler config. NULL columns mean autoscale is disabled+-- (default for all existing sandboxes). When enabled, CP autoscaler resizes+-- the sandbox between min and max along the configured tier list (1, 4, 8,+-- 16 GB today) based on observed memory pressure.+--+-- Asymmetric thresholds: scale up fast on a brief 1m spike (>75%); scale+-- down only after sustained low utilization across 1m AND 5m AND 15m moving+-- averages (<25% on each). Cooldowns prevent flapping.++ALTER TABLE sandbox_sessions+ ADD COLUMN autoscale_enabled BOOLEAN NOT NULL DEFAULT FALSE,+ ADD COLUMN autoscale_min_mb INT,+ ADD COLUMN autoscale_max_mb INT,+ ADD COLUMN autoscale_last_event_at TIMESTAMPTZ;++-- Partial index lets the autoscaler scan the active set cheaply.+CREATE INDEX idx_sandbox_sessions_autoscale_active+ ON sandbox_sessions (sandbox_id)+ WHERE autoscale_enabled = TRUE AND status = 'running';diff --git a/internal/db/migrations/036_sandbox_scaling_lock.down.sql b/internal/db/migrations/036_sandbox_scaling_lock.down.sqlnew file mode 100644index 00000000..3f60ac4a--- /dev/null+++ b/internal/db/migrations/036_sandbox_scaling_lock.down.sql@@ -0,0 +1 @@+ALTER TABLE sandbox_sessions DROP COLUMN scaling_locked;diff --git a/internal/db/migrations/036_sandbox_scaling_lock.up.sql b/internal/db/migrations/036_sandbox_scaling_lock.up.sqlnew file mode 100644index 00000000..dfaccb2d--- /dev/null+++ b/internal/db/migrations/036_sandbox_scaling_lock.up.sql@@ -0,0 +1,11 @@+-- Sandbox-level "scaling lock". When true, blocks BOTH manual scaling+-- (POST /scale) AND automatic scaling (per-sandbox autoscaler). Useful when+-- the user wants predictable, fixed resources for a sandbox — e.g. a+-- benchmark, a long-running pinned workload, or a billing-sensitive setup.+--+-- Locking auto-disables autoscale (the lock handler clears autoscale_enabled+-- alongside setting scaling_locked=TRUE), but the partial-index filter here+-- is defense in depth in case the two columns ever drift.++ALTER TABLE sandbox_sessions+ ADD COLUMN scaling_locked BOOLEAN NOT NULL DEFAULT FALSE;diff --git a/internal/db/migrations/037_agent_subscriptions.up.sql b/internal/db/migrations/037_agent_subscriptions.up.sqlnew file mode 100644index 00000000..1ef4c1ce--- /dev/null+++ b/internal/db/migrations/037_agent_subscriptions.up.sql@@ -0,0 +1,39 @@+-- Per-agent paid feature subscriptions.+--+-- Each row represents one Stripe subscription gating one feature on one+-- agent (e.g. Telegram channel). Modeled as a separate table — not+-- columns on `orgs` — because:+-- - agent IDs are owned by sessions-api (text, not a UUID FK).+-- - more features (Discord, Slack, etc.) will land here without+-- adding columns.+-- - terminal subscriptions (canceled, past_due) need to be retained+-- for billing history without polluting active-state queries.+--+-- The (org_id, agent_id, feature) tuple is unique among non-terminal+-- rows — partial unique index below — so a single agent can be+-- "subscribed to telegram" only once at a time, but historic rows+-- coexist for audit.+CREATE TABLE agent_subscriptions (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ org_id UUID NOT NULL REFERENCES orgs(id) ON DELETE CASCADE,+ agent_id TEXT NOT NULL,+ feature TEXT NOT NULL, -- 'telegram', future: 'discord', 'slack', ...+ stripe_customer_id TEXT NOT NULL,+ stripe_subscription_id TEXT NOT NULL,+ stripe_price_id TEXT NOT NULL,+ status TEXT NOT NULL, -- 'active' | 'trialing' | 'past_due' | 'canceled' | 'incomplete' | 'incomplete_expired' | 'unpaid'+ current_period_end TIMESTAMPTZ,+ cancel_at_period_end BOOLEAN NOT NULL DEFAULT FALSE,+ canceled_at TIMESTAMPTZ,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()+);++-- One active row per (agent, feature). Terminal rows can stack so+-- billing history is preserved across resubscriptions.+CREATE UNIQUE INDEX agent_subscriptions_active_per_feature+ ON agent_subscriptions (agent_id, feature)+ WHERE status NOT IN ('canceled', 'incomplete_expired', 'unpaid');++CREATE INDEX agent_subscriptions_org ON agent_subscriptions (org_id);+CREATE INDEX agent_subscriptions_stripe_sub ON agent_subscriptions (stripe_subscription_id);diff --git a/internal/db/migrations/038_hibernation_upload_status.down.sql b/internal/db/migrations/038_hibernation_upload_status.down.sqlnew file mode 100644index 00000000..e22bc6ea--- /dev/null+++ b/internal/db/migrations/038_hibernation_upload_status.down.sql@@ -0,0 +1,5 @@+DROP INDEX IF EXISTS idx_hibernations_pending_upload;++ALTER TABLE sandbox_hibernations+ DROP COLUMN IF EXISTS uploaded_at,+ DROP COLUMN IF EXISTS upload_error;diff --git a/internal/db/migrations/038_hibernation_upload_status.up.sql b/internal/db/migrations/038_hibernation_upload_status.up.sqlnew file mode 100644index 00000000..144d8632--- /dev/null+++ b/internal/db/migrations/038_hibernation_upload_status.up.sql@@ -0,0 +1,15 @@+-- Track whether a hibernation's S3 upload actually completed.+-- Pre-fix: size_bytes was hardcoded to 0 by qemu hibernate, so the DB had no+-- signal of upload success. Async upload failures were only logged. This made+-- the missing-blob bug invisible — sandboxes appeared hibernated but couldn't+-- be woken cross-worker because the blob was never uploaded.++ALTER TABLE sandbox_hibernations+ ADD COLUMN uploaded_at TIMESTAMPTZ,+ ADD COLUMN upload_error TEXT;++-- Find hibernations that have not finished uploading. Useful for monitoring+-- and for the periodic backstop scan.+CREATE INDEX idx_hibernations_pending_upload+ ON sandbox_hibernations (hibernated_at)+ WHERE uploaded_at IS NULL AND upload_error IS NULL AND expired_at IS NULL;diff --git a/internal/db/migrations/039_checkpoint_failure_detail.down.sql b/internal/db/migrations/039_checkpoint_failure_detail.down.sqlnew file mode 100644index 00000000..eb34726c--- /dev/null+++ b/internal/db/migrations/039_checkpoint_failure_detail.down.sql@@ -0,0 +1,3 @@+ALTER TABLE sandbox_checkpoints+ DROP COLUMN IF EXISTS error_msg,+ DROP COLUMN IF EXISTS failed_at;diff --git a/internal/db/migrations/039_checkpoint_failure_detail.up.sql b/internal/db/migrations/039_checkpoint_failure_detail.up.sqlnew file mode 100644index 00000000..e61fcf02--- /dev/null+++ b/internal/db/migrations/039_checkpoint_failure_detail.up.sql@@ -0,0 +1,15 @@+-- Persist the actual reason a checkpoint create failed.+--+-- Pre-fix: SetCheckpointFailed(ctx, id, reason) accepted a `reason` argument+-- but its UPDATE only set status='failed' — the reason string was silently+-- discarded. Operators and customers had no signal beyond "failed", which+-- was the entire detail Oliviero saw on the May 6 incident: "status+-- processing for ~280s → failed, no error detail".+--+-- error_msg holds the formatted error chain from CreateCheckpoint (timeout,+-- archive failure, upload failure, etc.). failed_at marks when the failure+-- was recorded so we can correlate with worker journals.++ALTER TABLE sandbox_checkpoints+ ADD COLUMN error_msg TEXT,+ ADD COLUMN failed_at TIMESTAMPTZ;diff --git a/internal/db/sandbox_autoscale.go b/internal/db/sandbox_autoscale.gonew file mode 100644index 00000000..708464c3--- /dev/null+++ b/internal/db/sandbox_autoscale.go@@ -0,0 +1,142 @@+package db++import (+ "context"+ "fmt"+ "time"+)++// AutoscaleSandbox is the per-sandbox row the autoscaler loop reads each+// tick. Defined here (not in internal/controlplane) so the db package owns+// its own row type and the autoscaler imports from db rather than the+// other way around — avoids the controlplane↔db import cycle.+//+// CurrentMB is intentionally NOT set from sandbox_sessions.config: that+// column is the original creation memory and never updates after a scale+// event (manual or autoscale). The autoscaler populates CurrentMB from the+// live worker heartbeat (registry.SandboxStats.MemLimit) before deciding+// scale targets — that's the only authoritative current size.+type AutoscaleSandbox struct {+ SandboxID string+ WorkerID string+ OrgID string+ CurrentMB int // populated by autoscaler from registry stats, NOT from DB+ MinMB int // user-configured floor (0 = unset)+ MaxMB int // user-configured ceiling (0 = unset)+ LastEventAt time.Time // zero if never scaled+}++// SetSandboxAutoscale enables/disables autoscale for a sandbox and writes+// the min/max bounds. Caller is responsible for validating min/max are+// allowed memory tiers (see types.AllowedResourceTiers).+func (s *Store) SetSandboxAutoscale(ctx context.Context, sandboxID string, enabled bool, minMB, maxMB int) error {+ _, err := s.pool.Exec(ctx, `+ UPDATE sandbox_sessions+ SET autoscale_enabled = $1,+ autoscale_min_mb = NULLIF($2, 0),+ autoscale_max_mb = NULLIF($3, 0)+ WHERE sandbox_id = $4+ `, enabled, minMB, maxMB, sandboxID)+ if err != nil {+ return fmt.Errorf("set autoscale on %s: %w", sandboxID, err)+ }+ return nil+}++// GetSandboxAutoscale returns the autoscale config for a sandbox.+func (s *Store) GetSandboxAutoscale(ctx context.Context, sandboxID string) (enabled bool, minMB, maxMB int, err error) {+ var minVal, maxVal *int+ err = s.pool.QueryRow(ctx, `+ SELECT autoscale_enabled, autoscale_min_mb, autoscale_max_mb+ FROM sandbox_sessions WHERE sandbox_id = $1+ `, sandboxID).Scan(&enabled, &minVal, &maxVal)+ if err != nil {+ return false, 0, 0, err+ }+ if minVal != nil {+ minMB = *minVal+ }+ if maxVal != nil {+ maxMB = *maxVal+ }+ return enabled, minMB, maxMB, nil+}++// ListAutoscaleEnabled returns running sandboxes with autoscale_enabled=true+// that are NOT currently being migrated. We exclude rows with a non-empty+// migrating_to_worker because:+// - the worker_id column is the source worker but the gRPC routes there+// would land on a sandbox that's mid-handoff+// - the heartbeat stats are racey across the source/dest workers during+// the cutover, so a scaling decision based on either is unreliable+// - autoscaling resumes naturally on the next tick after the migration+// completes (CompleteMigration clears migrating_to_worker)+//+// The partial index added in migration 035 keeps this scan cheap regardless+// of total session count. CurrentMB is left at zero — populated by the+// caller from live heartbeat stats. See the AutoscaleSandbox doc comment.+func (s *Store) ListAutoscaleEnabled(ctx context.Context) ([]AutoscaleSandbox, error) {+ rows, err := s.pool.Query(ctx, `+ SELECT sandbox_id, worker_id, org_id::text,+ COALESCE(autoscale_min_mb, 0) AS min_mb,+ COALESCE(autoscale_max_mb, 0) AS max_mb,+ COALESCE(autoscale_last_event_at, '1970-01-01'::timestamptz) AS last_event_at+ FROM sandbox_sessions+ WHERE autoscale_enabled = TRUE+ AND status = 'running'+ AND migrating_to_worker = ''+ AND scaling_locked = FALSE+ `)+ if err != nil {+ return nil, fmt.Errorf("list autoscale-enabled: %w", err)+ }+ defer rows.Close()++ var out []AutoscaleSandbox+ for rows.Next() {+ var sb AutoscaleSandbox+ if err := rows.Scan(&sb.SandboxID, &sb.WorkerID, &sb.OrgID,+ &sb.MinMB, &sb.MaxMB, &sb.LastEventAt); err != nil {+ return nil, err+ }+ out = append(out, sb)+ }+ return out, rows.Err()+}++// ClaimAutoscaleEvent atomically claims the right to apply a scale event for+// this sandbox. Performs a CAS on (autoscale_enabled, autoscale_last_event_at):+//+// - autoscale_enabled must still be TRUE — guards against a manual /scale+// call (which sets enabled=false) racing with an in-flight autoscaler tick.+// - autoscale_last_event_at must equal the value the caller observed —+// guards against two control planes both deciding to scale on the same+// pre-event row.+//+// If either guard fails, RowsAffected is 0 and the caller MUST NOT proceed+// with the scale: another writer either disabled autoscale or already+// claimed the event. On success the cooldown anchor is updated to `now`,+// so a subsequent gRPC failure simply means we'll retry on the next cooldown+// boundary rather than retry-storming.+//+// `prev` is the LastEventAt value the caller read from ListAutoscaleEnabled+// (zero-valued for never-scaled sandboxes — handled via IS NOT DISTINCT FROM).+func (s *Store) ClaimAutoscaleEvent(ctx context.Context, sandboxID string, prev, now time.Time) (bool, error) {+ // Treat the seeded sentinel from ListAutoscaleEnabled (1970-01-01) as+ // "never scaled" so the CAS matches the actual NULL stored on the row.+ var prevArg interface{} = prev+ if prev.Year() <= 1970 {+ prevArg = nil+ }+ tag, err := s.pool.Exec(ctx, `+ UPDATE sandbox_sessions+ SET autoscale_last_event_at = $1+ WHERE sandbox_id = $2+ AND autoscale_enabled = TRUE+ AND autoscale_last_event_at IS NOT DISTINCT FROM $3+ `, now, sandboxID, prevArg)+ if err != nil {+ return false, err+ }+ return tag.RowsAffected() == 1, nil+}diff --git a/internal/db/sandbox_scaling_lock.go b/internal/db/sandbox_scaling_lock.gonew file mode 100644index 00000000..317f5e2c--- /dev/null+++ b/internal/db/sandbox_scaling_lock.go@@ -0,0 +1,40 @@+package db++import (+ "context"+ "fmt"+)++// SetScalingLock toggles the per-sandbox scaling lock. When true, the sandbox+// is exempt from both manual /scale calls and the per-sandbox autoscaler.+// The handler that calls this should also clear autoscale_enabled when+// locking — done at the API layer, not here, so this function is a pure+// column setter.+func (s *Store) SetScalingLock(ctx context.Context, sandboxID string, locked bool) error {+ tag, err := s.pool.Exec(ctx, `+ UPDATE sandbox_sessions+ SET scaling_locked = $1+ WHERE sandbox_id = $2+ `, locked, sandboxID)+ if err != nil {+ return fmt.Errorf("set scaling lock on %s: %w", sandboxID, err)+ }+ if tag.RowsAffected() == 0 {+ return fmt.Errorf("sandbox %s not found", sandboxID)+ }+ return nil+}++// GetScalingLock returns the current lock state for a sandbox. Returns false+// (and no error) if the sandbox doesn't exist — the caller is expected to+// have already validated the sandbox via GetSandboxSession.+func (s *Store) GetScalingLock(ctx context.Context, sandboxID string) (bool, error) {+ var locked bool+ err := s.pool.QueryRow(ctx, `+ SELECT scaling_locked FROM sandbox_sessions WHERE sandbox_id = $1+ `, sandboxID).Scan(&locked)+ if err != nil {+ return false, err+ }+ return locked, nil+}diff --git a/internal/db/secret_refresh.go b/internal/db/secret_refresh.gonew file mode 100644index 00000000..8d4271f6--- /dev/null+++ b/internal/db/secret_refresh.go@@ -0,0 +1,47 @@+package db++import (+ "context"+ "fmt"++ "github.com/google/uuid"+)++// SecretRefreshTarget is one running sandbox affected by a secret-store update.+// MigratingToWorker is empty when the sandbox is steady-state on WorkerID;+// non-empty during a migration in flight, in which case the refresh fanout+// must push to BOTH workers (source and destination) to avoid a window where+// one of them serves outbound HTTPS with the stale value after the cutover.+type SecretRefreshTarget struct {+ SandboxID string+ WorkerID string+ MigratingToWorker string+}++// ListRunningSandboxesByStore returns the running sandboxes that resolve their+// envs from the given SecretStore. Used by the secret-store-update flow to+// fanout UpdateSandboxSecret RPCs to the right workers.+//+// Filters: status='running' (no-op for stopped/hibernated; they'll get fresh+// values when the customer next wakes/recreates them).+func (s *Store) ListRunningSandboxesByStore(ctx context.Context, storeID uuid.UUID) ([]SecretRefreshTarget, error) {+ rows, err := s.pool.Query(ctx, `+ SELECT sandbox_id, worker_id, COALESCE(migrating_to_worker, '')+ FROM sandbox_sessions+ WHERE secret_store_id = $1 AND status = 'running'+ `, storeID)+ if err != nil {+ return nil, fmt.Errorf("list sandboxes by store %s: %w", storeID, err)+ }+ defer rows.Close()++ var out []SecretRefreshTarget+ for rows.Next() {+ var t SecretRefreshTarget+ if err := rows.Scan(&t.SandboxID, &t.WorkerID, &t.MigratingToWorker); err != nil {+ return nil, err+ }+ out = append(out, t)+ }+ return out, rows.Err()+}diff --git a/internal/db/store.go b/internal/db/store.goindex 5c518dba..69e5218e 100644--- a/internal/db/store.go+++ b/internal/db/store.go@@ -123,6 +123,13 @@ func (s *Store) Migrate(ctx context.Context) error {{30, "migrations/027_capacity_reservation_intervals.up.sql"},{31, "migrations/028_capacity_idempotency_keys.up.sql"},{32, "migrations/029_orgs_max_memory_gb.up.sql"},+ {33, "migrations/030_billable_events.up.sql"},+ {34, "migrations/031_orgs_billing_mode.up.sql"},+ {35, "migrations/035_sandbox_autoscale.up.sql"},+ {36, "migrations/036_sandbox_scaling_lock.up.sql"},+ {37, "migrations/037_agent_subscriptions.up.sql"},+ {38, "migrations/038_hibernation_upload_status.up.sql"},+ {39, "migrations/039_checkpoint_failure_detail.up.sql"},}for _, m := range migrations {@@ -193,6 +200,13 @@ type Org struct {StripeSubscriptionID *string `json:"stripeSubscriptionId,omitempty"`LastUsageReportedAt time.Time `json:"lastUsageReportedAt"`PriceLocked bool `json:"priceLocked"`++ // Per-org billing pipeline selector. 'legacy' = UsageReporter ships+ // to Stripe; 'unified' = the phase-3 sender ships from+ // billable_events. Both paths produce the same dollar amounts via+ // today's tiered rates — the column controls *how* events are+ // emitted, not what the customer pays.+ BillingMode string `json:"billingMode"`}// orgColumns is the list of columns returned by all Org queries.@@ -201,7 +215,7 @@ const orgColumns = `id, name, slug, plan, max_concurrent_sandboxes, max_sandbox_verification_txt_name, verification_txt_value, ssl_txt_name, ssl_txt_value,workos_org_id, is_personal, owner_user_id, credit_balance_cents,stripe_customer_id, stripe_subscription_id, last_usage_reported_at, price_locked,- free_credits_remaining_cents`+ free_credits_remaining_cents, billing_mode`// scanOrg scans a row into an Org struct.func scanOrg(row pgx.Row) (*Org, error) {@@ -214,7 +228,7 @@ func scanOrg(row pgx.Row) (*Org, error) {&org.WorkOSOrgID, &org.IsPersonal, &org.OwnerUserID, &org.CreditBalanceCents,&org.StripeCustomerID, &org.StripeSubscriptionID, &org.LastUsageReportedAt,&org.PriceLocked,- &org.FreeCreditsRemainingCents,+ &org.FreeCreditsRemainingCents, &org.BillingMode,)return org, err}@@ -504,17 +518,25 @@ type SandboxSession struct {GoldenVersion *string `json:"goldenVersion,omitempty"`}-func (s *Store) CreateSandboxSession(ctx context.Context, sandboxID string, orgID uuid.UUID, userID *uuid.UUID, template, region, workerID string, config, metadata json.RawMessage) (*SandboxSession, error) {- return s.CreateSandboxSessionWithStatus(ctx, sandboxID, orgID, userID, template, region, workerID, config, metadata, "running")+func (s *Store) CreateSandboxSession(ctx context.Context, sandboxID string, orgID uuid.UUID, userID *uuid.UUID, template, region, workerID string, config, metadata json.RawMessage, secretStoreID *uuid.UUID) (*SandboxSession, error) {+ return s.CreateSandboxSessionWithStatus(ctx, sandboxID, orgID, userID, template, region, workerID, config, metadata, "running", secretStoreID)}-func (s *Store) CreateSandboxSessionWithStatus(ctx context.Context, sandboxID string, orgID uuid.UUID, userID *uuid.UUID, template, region, workerID string, config, metadata json.RawMessage, status string) (*SandboxSession, error) {+// CreateSandboxSessionWithStatus inserts a new sandbox_sessions row.+//+// secretStoreID is the resolved secret_stores.id when the sandbox is bound to+// a store (nil otherwise). The column is required for the secret-refresh+// fan-out: ListRunningSandboxesByStore filters on it. Pre-fix the column was+// silently NULL because the INSERT omitted it, which made the fanout a no-op+// and meant a customer's PUT to /secret-stores/:id/entries/:name didn't+// propagate to running sandboxes — they kept the value from create-time.+func (s *Store) CreateSandboxSessionWithStatus(ctx context.Context, sandboxID string, orgID uuid.UUID, userID *uuid.UUID, template, region, workerID string, config, metadata json.RawMessage, status string, secretStoreID *uuid.UUID) (*SandboxSession, error) {session := &SandboxSession{}err := s.pool.QueryRow(ctx,- `INSERT INTO sandbox_sessions (sandbox_id, org_id, user_id, template, region, worker_id, config, metadata, status)- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)+ `INSERT INTO sandbox_sessions (sandbox_id, org_id, user_id, template, region, worker_id, config, metadata, status, secret_store_id)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)RETURNING id, sandbox_id, org_id, user_id, template, region, worker_id, status, config, metadata, started_at, based_on_checkpoint_id, last_patch_sequence, patch_error, golden_version`,- sandboxID, orgID, userID, template, region, workerID, config, metadata, status,+ sandboxID, orgID, userID, template, region, workerID, config, metadata, status, secretStoreID,).Scan(&session.ID, &session.SandboxID, &session.OrgID, &session.UserID, &session.Template,&session.Region, &session.WorkerID, &session.Status, &session.Config, &session.Metadata, &session.StartedAt,&session.BasedOnCheckpointID, &session.LastPatchSequence, &session.PatchError, &session.GoldenVersion)@@ -1019,6 +1041,8 @@ type SandboxHibernation struct {HibernatedAt time.Time `json:"hibernatedAt"`RestoredAt *time.Time `json:"restoredAt,omitempty"`ExpiredAt *time.Time `json:"expiredAt,omitempty"`+ UploadedAt *time.Time `json:"uploadedAt,omitempty"`+ UploadError *string `json:"uploadError,omitempty"`}// CreateHibernation inserts a new hibernation record, marking any prior active@@ -1067,11 +1091,11 @@ func (s *Store) CreateHibernation(ctx context.Context, sandboxID string, orgID ufunc (s *Store) GetActiveHibernation(ctx context.Context, sandboxID string) (*SandboxHibernation, error) {cp := &SandboxHibernation{}err := s.pool.QueryRow(ctx,- `SELECT id, sandbox_id, org_id, hibernation_key, size_bytes, region, template, sandbox_config, hibernated_at, restored_at, expired_at+ `SELECT id, sandbox_id, org_id, hibernation_key, size_bytes, region, template, sandbox_config, hibernated_at, restored_at, expired_at, uploaded_at, upload_errorFROM sandbox_hibernationsWHERE sandbox_id = $1 AND restored_at IS NULL AND expired_at IS NULL`, sandboxID,).Scan(&cp.ID, &cp.SandboxID, &cp.OrgID, &cp.HibernationKey, &cp.SizeBytes,- &cp.Region, &cp.Template, &cp.SandboxConfig, &cp.HibernatedAt, &cp.RestoredAt, &cp.ExpiredAt)+ &cp.Region, &cp.Template, &cp.SandboxConfig, &cp.HibernatedAt, &cp.RestoredAt, &cp.ExpiredAt, &cp.UploadedAt, &cp.UploadError)if err != nil {return nil, fmt.Errorf("active hibernation not found: %w", err)}@@ -1087,6 +1111,31 @@ func (s *Store) MarkHibernationRestored(ctx context.Context, sandboxID string) ereturn err}+// MarkHibernationUploaded records that the async S3 archive upload completed+// for a specific hibernation_key. Matches by key (not sandbox_id) because a+// sandbox can have multiple hibernation rows in flight when hibernate→wake→+// hibernate cycles run faster than the upload goroutine.+func (s *Store) MarkHibernationUploaded(ctx context.Context, hibernationKey string, sizeBytes int64) error {+ _, err := s.pool.Exec(ctx,+ `UPDATE sandbox_hibernations+ SET uploaded_at = now(), size_bytes = $2, upload_error = NULL+ WHERE hibernation_key = $1`,+ hibernationKey, sizeBytes)+ return err+}++// MarkHibernationUploadFailed records the failure reason for an upload that+// did not land in S3. Without this, async upload failures were silent and the+// row stayed in a misleading "hibernated, blob present" state.+func (s *Store) MarkHibernationUploadFailed(ctx context.Context, hibernationKey, errMsg string) error {+ _, err := s.pool.Exec(ctx,+ `UPDATE sandbox_hibernations+ SET upload_error = $2+ WHERE hibernation_key = $1`,+ hibernationKey, errMsg)+ return err+}+// UpdateSandboxSessionForWake changes a hibernated session back to running on a new worker.func (s *Store) UpdateSandboxSessionForWake(ctx context.Context, sandboxID, newWorkerID string) error {_, err := s.pool.Exec(ctx,@@ -1188,17 +1237,23 @@ func (s *Store) UpsertWorkspaceBackup(ctx context.Context, sandboxID string, org// Checkpoint represents a named checkpoint for a sandbox.type Checkpoint struct {- ID uuid.UUID `json:"id"`- SandboxID string `json:"sandboxId"`- OrgID uuid.UUID `json:"orgId"`- Name string `json:"name"`- RootfsS3Key *string `json:"rootfsS3Key,omitempty"`- WorkspaceS3Key *string `json:"workspaceS3Key,omitempty"`- SandboxConfig json.RawMessage `json:"sandboxConfig"`- Status string `json:"status"`- SizeBytes int64 `json:"sizeBytes"`- IsPublic bool `json:"isPublic"`- CreatedAt time.Time `json:"createdAt"`+ ID uuid.UUID `json:"id"`+ SandboxID string `json:"sandboxId"`+ OrgID uuid.UUID `json:"orgId"`+ Name string `json:"name"`+ RootfsS3Key *string `json:"rootfsS3Key,omitempty"`+ WorkspaceS3Key *string `json:"workspaceS3Key,omitempty"`+ SandboxConfig json.RawMessage `json:"sandboxConfig"`+ Status string `json:"status"`+ SizeBytes int64 `json:"sizeBytes"`+ IsPublic bool `json:"isPublic"`+ CreatedAt time.Time `json:"createdAt"`+ // ErrorMsg holds the failure reason when Status == "failed". Persisted by+ // SetCheckpointFailed so customers/operators can see WHY a checkpoint+ // failed (timeout, archive error, S3 upload error, etc.) instead of just+ // status="failed" with no detail.+ ErrorMsg *string `json:"errorMsg,omitempty"`+ FailedAt *time.Time `json:"failedAt,omitempty"`}// CreateCheckpoint inserts a new checkpoint record.@@ -1211,11 +1266,23 @@ func (s *Store) CreateCheckpoint(ctx context.Context, cp *Checkpoint) error {).Scan(&cp.CreatedAt)}-// SetCheckpointReady marks a checkpoint as ready after async S3 upload completes.+// SetCheckpointReady marks a checkpoint as ready after the S3 upload completes.+// Also clears error_msg/failed_at so a row that previously failed and was then+// recovered ends up in a consistent state (no leftover failure detail on a+// "ready" row). Today no code path flips failed→ready — the API's checkpoint+// goroutine calls either SetCheckpointFailed or SetCheckpointReady but never+// both — but the defensive clear matches the column semantics (failed_at /+// error_msg are only meaningful when status='failed').func (s *Store) SetCheckpointReady(ctx context.Context, checkpointID uuid.UUID, rootfsKey, workspaceKey string, sizeBytes int64) error {_, err := s.pool.Exec(ctx,- `UPDATE sandbox_checkpoints SET status = 'ready', rootfs_s3_key = $2, workspace_s3_key = $3, size_bytes = $4- WHERE id = $1`,+ `UPDATE sandbox_checkpoints+ SET status = 'ready',+ rootfs_s3_key = $2,+ workspace_s3_key = $3,+ size_bytes = $4,+ error_msg = NULL,+ failed_at = NULL+ WHERE id = $1`,checkpointID, rootfsKey, workspaceKey, sizeBytes)return err}@@ -1228,11 +1295,18 @@ func (s *Store) UpdateCheckpointS3Keys(ctx context.Context, checkpointID uuid.UUreturn err}-// SetCheckpointFailed marks a checkpoint as failed.+// SetCheckpointFailed marks a checkpoint as failed and records the reason.+// Pre-fix the `reason` argument was silently discarded — operators saw+// status='failed' with no detail. The error_msg / failed_at columns are+// added in migration 039.func (s *Store) SetCheckpointFailed(ctx context.Context, checkpointID uuid.UUID, reason string) error {_, err := s.pool.Exec(ctx,- `UPDATE sandbox_checkpoints SET status = 'failed' WHERE id = $1`,- checkpointID)+ `UPDATE sandbox_checkpoints+ SET status = 'failed',+ error_msg = $2,+ failed_at = now()+ WHERE id = $1`,+ checkpointID, reason)return err}@@ -1240,10 +1314,11 @@ func (s *Store) SetCheckpointFailed(ctx context.Context, checkpointID uuid.UUID,func (s *Store) GetCheckpoint(ctx context.Context, checkpointID uuid.UUID) (*Checkpoint, error) {cp := &Checkpoint{}err := s.pool.QueryRow(ctx,- `SELECT id, sandbox_id, org_id, name, rootfs_s3_key, workspace_s3_key, sandbox_config, status, size_bytes, is_public, created_at+ `SELECT id, sandbox_id, org_id, name, rootfs_s3_key, workspace_s3_key, sandbox_config, status, size_bytes, is_public, created_at, error_msg, failed_atFROM sandbox_checkpoints WHERE id = $1`, checkpointID,).Scan(&cp.ID, &cp.SandboxID, &cp.OrgID, &cp.Name, &cp.RootfsS3Key, &cp.WorkspaceS3Key,- &cp.SandboxConfig, &cp.Status, &cp.SizeBytes, &cp.IsPublic, &cp.CreatedAt)+ &cp.SandboxConfig, &cp.Status, &cp.SizeBytes, &cp.IsPublic, &cp.CreatedAt,+ &cp.ErrorMsg, &cp.FailedAt)if err != nil {return nil, fmt.Errorf("checkpoint not found: %w", err)}@@ -1253,7 +1328,7 @@ func (s *Store) GetCheckpoint(ctx context.Context, checkpointID uuid.UUID) (*Che// ListCheckpoints returns all checkpoints for a sandbox, newest first.func (s *Store) ListCheckpoints(ctx context.Context, sandboxID string) ([]Checkpoint, error) {rows, err := s.pool.Query(ctx,- `SELECT id, sandbox_id, org_id, name, rootfs_s3_key, workspace_s3_key, sandbox_config, status, size_bytes, is_public, created_at+ `SELECT id, sandbox_id, org_id, name, rootfs_s3_key, workspace_s3_key, sandbox_config, status, size_bytes, is_public, created_at, error_msg, failed_atFROM sandbox_checkpoints WHERE sandbox_id = $1 ORDER BY created_at DESC`, sandboxID)if err != nil {return nil, err@@ -1264,7 +1339,8 @@ func (s *Store) ListCheckpoints(ctx context.Context, sandboxID string) ([]Checkpfor rows.Next() {var cp Checkpointif err := rows.Scan(&cp.ID, &cp.SandboxID, &cp.OrgID, &cp.Name, &cp.RootfsS3Key, &cp.WorkspaceS3Key,- &cp.SandboxConfig, &cp.Status, &cp.SizeBytes, &cp.IsPublic, &cp.CreatedAt); err != nil {+ &cp.SandboxConfig, &cp.Status, &cp.SizeBytes, &cp.IsPublic, &cp.CreatedAt,+ &cp.ErrorMsg, &cp.FailedAt); err != nil {return nil, err}checkpoints = append(checkpoints, cp)@@ -1291,6 +1367,7 @@ func (s *Store) ListOrgCheckpoints(ctx context.Context, orgID uuid.UUID, limit,rows, err := s.pool.Query(ctx,`SELECT c.id, c.sandbox_id, c.org_id, c.name, c.rootfs_s3_key, c.workspace_s3_key,c.sandbox_config, c.status, c.size_bytes, c.is_public, c.created_at,+ c.error_msg, c.failed_at,(SELECT COUNT(*) FROM sandbox_sessions ss WHERE ss.based_on_checkpoint_id = c.id AND ss.status IN ('running', 'hibernated')) AS active_forks,(SELECT COUNT(*) FROM sandbox_sessions ss WHERE ss.based_on_checkpoint_id = c.id) AS total_forksFROM sandbox_checkpoints c WHERE c.org_id = $1@@ -1305,6 +1382,7 @@ func (s *Store) ListOrgCheckpoints(ctx context.Context, orgID uuid.UUID, limit,var cf CheckpointWithForksif err := rows.Scan(&cf.ID, &cf.SandboxID, &cf.OrgID, &cf.Name, &cf.RootfsS3Key, &cf.WorkspaceS3Key,&cf.SandboxConfig, &cf.Status, &cf.SizeBytes, &cf.IsPublic, &cf.CreatedAt,+ &cf.ErrorMsg, &cf.FailedAt,&cf.ActiveForks, &cf.TotalForks); err != nil {return nil, 0, err}@@ -1317,10 +1395,11 @@ func (s *Store) ListOrgCheckpoints(ctx context.Context, orgID uuid.UUID, limit,func (s *Store) GetCheckpointByName(ctx context.Context, sandboxID, name string) (*Checkpoint, error) {cp := &Checkpoint{}err := s.pool.QueryRow(ctx,- `SELECT id, sandbox_id, org_id, name, rootfs_s3_key, workspace_s3_key, sandbox_config, status, size_bytes, is_public, created_at+ `SELECT id, sandbox_id, org_id, name, rootfs_s3_key, workspace_s3_key, sandbox_config, status, size_bytes, is_public, created_at, error_msg, failed_atFROM sandbox_checkpoints WHERE sandbox_id = $1 AND name = $2`, sandboxID, name,).Scan(&cp.ID, &cp.SandboxID, &cp.OrgID, &cp.Name, &cp.RootfsS3Key, &cp.WorkspaceS3Key,- &cp.SandboxConfig, &cp.Status, &cp.SizeBytes, &cp.IsPublic, &cp.CreatedAt)+ &cp.SandboxConfig, &cp.Status, &cp.SizeBytes, &cp.IsPublic, &cp.CreatedAt,+ &cp.ErrorMsg, &cp.FailedAt)if err != nil {return nil, fmt.Errorf("checkpoint not found: %w", err)}@@ -1955,6 +2034,35 @@ func (s *Store) GetSecretStoreByName(ctx context.Context, orgID uuid.UUID, namereturn &ss, nil}+// GetSandboxStoreRefs returns the secret stores attached to a sandbox:+//+// - primaryID is sandbox_sessions.secret_store_id, the "winning" store on+// the row (last layer for env-collision resolution; nil if no store).+// - baseStoreName is config->>'baseSecretStore' (parent store from the+// fork chain), populated when a fork layered an additional store on top+// of an inherited one. Empty string when there's no parent.+//+// Both are needed to reconstruct the runtime egress allowlist accurately:+// the secrets proxy enforces the union of egress hosts from EVERY layered+// store, while sandbox_sessions.secret_store_id only records the last one.+// Without including the base store, an /allowed-hosts response on a layered+// fork would underrepresent what the proxy actually allows.+//+// Org-scoped: sandbox IDs aren't globally unique, so a leaked ID from+// another org won't return that org's data.+func (s *Store) GetSandboxStoreRefs(ctx context.Context, orgID uuid.UUID, sandboxID string) (primaryID *uuid.UUID, baseStoreName string, err error) {+ err = s.pool.QueryRow(ctx,+ `SELECT secret_store_id, COALESCE(config->>'baseSecretStore', '')+ FROM sandbox_sessions+ WHERE org_id = $1 AND sandbox_id = $2 ORDER BY started_at DESC LIMIT 1`,+ orgID, sandboxID,+ ).Scan(&primaryID, &baseStoreName)+ if err != nil {+ return nil, "", fmt.Errorf("get sandbox store refs: %w", err)+ }+ return primaryID, baseStoreName, nil+}+// ListSecretStores returns all secret stores for an org.func (s *Store) ListSecretStores(ctx context.Context, orgID uuid.UUID) ([]SecretStore, error) {rows, err := s.pool.Query(ctx,@@ -2108,3 +2216,169 @@ func (s *Store) DecryptSecretEntries(ctx context.Context, storeID uuid.UUID) ([]}return secrets, nil}++// --- Agent feature subscriptions (per-agent paywalled features) ---++type AgentSubscription struct {+ ID uuid.UUID `json:"id"`+ OrgID uuid.UUID `json:"orgId"`+ AgentID string `json:"agentId"`+ Feature string `json:"feature"`+ StripeCustomerID string `json:"stripeCustomerId"`+ StripeSubscriptionID string `json:"stripeSubscriptionId"`+ StripePriceID string `json:"stripePriceId"`+ Status string `json:"status"`+ CurrentPeriodEnd *time.Time `json:"currentPeriodEnd,omitempty"`+ CancelAtPeriodEnd bool `json:"cancelAtPeriodEnd"`+ CanceledAt *time.Time `json:"canceledAt,omitempty"`+ CreatedAt time.Time `json:"createdAt"`+ UpdatedAt time.Time `json:"updatedAt"`+}++// AgentSubscriptionIsActive returns true for statuses where the feature+// should be enabled. Mirrors the partial-unique-index condition in+// migration 032; keep them in sync.+func AgentSubscriptionIsActive(status string) bool {+ switch status {+ case "active", "trialing", "past_due", "incomplete":+ // past_due/incomplete are grace-period states — Stripe still+ // considers them billable. We let the bot run during grace and+ // rely on the webhook to flip to canceled when Stripe gives up.+ return true+ default:+ return false+ }+}++// GetActiveAgentSubscription returns the single active subscription for+// (agent_id, feature) if one exists. Used for entitlement checks.+func (s *Store) GetActiveAgentSubscription(ctx context.Context, agentID, feature string) (*AgentSubscription, error) {+ var sub AgentSubscription+ var currentPeriodEnd, canceledAt *time.Time+ err := s.pool.QueryRow(ctx, `+ SELECT id, org_id, agent_id, feature, stripe_customer_id, stripe_subscription_id,+ stripe_price_id, status, current_period_end, cancel_at_period_end,+ canceled_at, created_at, updated_at+ FROM agent_subscriptions+ WHERE agent_id = $1 AND feature = $2+ AND status NOT IN ('canceled','incomplete_expired','unpaid')+ LIMIT 1`, agentID, feature).Scan(+ &sub.ID, &sub.OrgID, &sub.AgentID, &sub.Feature, &sub.StripeCustomerID,+ &sub.StripeSubscriptionID, &sub.StripePriceID, &sub.Status,+ ¤tPeriodEnd, &sub.CancelAtPeriodEnd, &canceledAt,+ &sub.CreatedAt, &sub.UpdatedAt,+ )+ if err != nil {+ if errors.Is(err, pgx.ErrNoRows) {+ return nil, nil+ }+ return nil, err+ }+ sub.CurrentPeriodEnd = currentPeriodEnd+ sub.CanceledAt = canceledAt+ return &sub, nil+}++// ListAgentSubscriptionsByOrg returns all subscriptions for an org, used+// by the billing page's per-agent-features section.+func (s *Store) ListAgentSubscriptionsByOrg(ctx context.Context, orgID uuid.UUID) ([]AgentSubscription, error) {+ rows, err := s.pool.Query(ctx, `+ SELECT id, org_id, agent_id, feature, stripe_customer_id, stripe_subscription_id,+ stripe_price_id, status, current_period_end, cancel_at_period_end,+ canceled_at, created_at, updated_at+ FROM agent_subscriptions+ WHERE org_id = $1+ ORDER BY created_at DESC`, orgID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ var subs []AgentSubscription+ for rows.Next() {+ var sub AgentSubscription+ var currentPeriodEnd, canceledAt *time.Time+ if err := rows.Scan(+ &sub.ID, &sub.OrgID, &sub.AgentID, &sub.Feature, &sub.StripeCustomerID,+ &sub.StripeSubscriptionID, &sub.StripePriceID, &sub.Status,+ ¤tPeriodEnd, &sub.CancelAtPeriodEnd, &canceledAt,+ &sub.CreatedAt, &sub.UpdatedAt,+ ); err != nil {+ return nil, err+ }+ sub.CurrentPeriodEnd = currentPeriodEnd+ sub.CanceledAt = canceledAt+ subs = append(subs, sub)+ }+ return subs, rows.Err()+}++// GetAgentSubscriptionByStripeID is the lookup path used by the Stripe+// webhook handler — it gets a subscription_id from Stripe and needs to+// find the matching internal row.+func (s *Store) GetAgentSubscriptionByStripeID(ctx context.Context, stripeSubscriptionID string) (*AgentSubscription, error) {+ var sub AgentSubscription+ var currentPeriodEnd, canceledAt *time.Time+ err := s.pool.QueryRow(ctx, `+ SELECT id, org_id, agent_id, feature, stripe_customer_id, stripe_subscription_id,+ stripe_price_id, status, current_period_end, cancel_at_period_end,+ canceled_at, created_at, updated_at+ FROM agent_subscriptions+ WHERE stripe_subscription_id = $1+ LIMIT 1`, stripeSubscriptionID).Scan(+ &sub.ID, &sub.OrgID, &sub.AgentID, &sub.Feature, &sub.StripeCustomerID,+ &sub.StripeSubscriptionID, &sub.StripePriceID, &sub.Status,+ ¤tPeriodEnd, &sub.CancelAtPeriodEnd, &canceledAt,+ &sub.CreatedAt, &sub.UpdatedAt,+ )+ if err != nil {+ if errors.Is(err, pgx.ErrNoRows) {+ return nil, nil+ }+ return nil, err+ }+ sub.CurrentPeriodEnd = currentPeriodEnd+ sub.CanceledAt = canceledAt+ return &sub, nil+}++// CreateAgentSubscription records a fresh Stripe subscription. Caller+// is responsible for ensuring the Stripe-side object exists first.+func (s *Store) CreateAgentSubscription(ctx context.Context, sub AgentSubscription) (*AgentSubscription, error) {+ row := s.pool.QueryRow(ctx, `+ INSERT INTO agent_subscriptions+ (org_id, agent_id, feature, stripe_customer_id, stripe_subscription_id,+ stripe_price_id, status, current_period_end, cancel_at_period_end)+ VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)+ RETURNING id, created_at, updated_at`,+ sub.OrgID, sub.AgentID, sub.Feature, sub.StripeCustomerID,+ sub.StripeSubscriptionID, sub.StripePriceID, sub.Status,+ sub.CurrentPeriodEnd, sub.CancelAtPeriodEnd,+ )+ if err := row.Scan(&sub.ID, &sub.CreatedAt, &sub.UpdatedAt); err != nil {+ return nil, err+ }+ return &sub, nil+}++// UpdateAgentSubscriptionFromStripe applies status/period/cancel fields+// from a Stripe webhook event onto the local row. Identifies by stripe+// subscription_id.+func (s *Store) UpdateAgentSubscriptionFromStripe(+ ctx context.Context,+ stripeSubscriptionID, status string,+ currentPeriodEnd *time.Time,+ cancelAtPeriodEnd bool,+ canceledAt *time.Time,+) error {+ _, err := s.pool.Exec(ctx, `+ UPDATE agent_subscriptions+ SET status = $2,+ current_period_end = $3,+ cancel_at_period_end = $4,+ canceled_at = $5,+ updated_at = now()+ WHERE stripe_subscription_id = $1`,+ stripeSubscriptionID, status, currentPeriodEnd, cancelAtPeriodEnd, canceledAt,+ )+ return err+}diff --git a/internal/db/usage.go b/internal/db/usage.goindex bfb6a716..5f172ce6 100644--- a/internal/db/usage.go+++ b/internal/db/usage.go@@ -172,14 +172,35 @@ type OrgUsageSummary struct {}// GetOrgUsage returns billing summary for an org.+//+// Sandboxes that back a managed agent with an active per-agent subscription+// (e.g. the $20/mo Telegram plan) are *excluded* from this aggregation —+// the subscription is meant to cover the underlying compute, so we mustn't+// also bill the org's compute meter or deduct trial credits for it.+//+// The link is sandbox_sessions.metadata.agent_id, which sessions-api stamps+// at sandbox-create time for managed agents. If a sandbox row is missing+// (rare race during creation) or has no agent_id, the EXISTS check+// short-circuits and the scale event is billed normally — i.e. the default+// is "bill it", which keeps us safe in all the unknown cases.func (s *Store) GetOrgUsage(ctx context.Context, orgID string, from, to time.Time) ([]OrgUsageSummary, error) {rows, err := s.pool.Query(ctx, `SELECT memory_mb, cpu_percent, disk_mb,SUM(EXTRACT(EPOCH FROM (COALESCE(ended_at, LEAST(now(), $3)) - GREATEST(started_at, $2)))) as total_seconds- FROM sandbox_scale_events+ FROM sandbox_scale_events seWHERE org_id = $1AND started_at < $3AND (ended_at IS NULL OR ended_at > $2)+ AND NOT EXISTS (+ SELECT 1+ FROM sandbox_sessions ss+ JOIN agent_subscriptions asub+ ON asub.org_id = ss.org_id+ AND asub.agent_id = ss.metadata->>'agent_id'+ AND asub.status IN ('active', 'trialing', 'past_due', 'incomplete')+ WHERE ss.sandbox_id = se.sandbox_id+ AND ss.metadata->>'agent_id' IS NOT NULL+ )GROUP BY memory_mb, cpu_percent, disk_mbORDER BY memory_mb, disk_mb`,orgID, from, to)@@ -233,14 +254,19 @@ func (s *Store) UpdateLastUsageReportedAt(ctx context.Context, orgID uuid.UUID,return err}-// ListBillableOrgIDs returns org IDs with plan="pro" that have unreported usage:-// either a currently-running sandbox or a scale event that ended after the last report.+// ListBillableOrgIDs returns org IDs with plan="pro" AND+// billing_mode='legacy' that have unreported usage: either a+// currently-running sandbox or a scale event that ended after the last+// report. Orgs in billing_mode='unified' are shipped via the phase-3+// `BillableEventsSender` reading from `billable_events`, so they must+// be skipped here to prevent double-billing.func (s *Store) ListBillableOrgIDs(ctx context.Context) ([]uuid.UUID, error) {rows, err := s.pool.Query(ctx,`SELECT DISTINCT se.org_idFROM sandbox_scale_events seJOIN orgs o ON o.id = se.org_idWHERE o.plan = 'pro'+ AND o.billing_mode = 'legacy'AND (se.ended_at IS NULL OR se.ended_at > o.last_usage_reported_at)`)if err != nil {return nil, errdiff --git a/internal/firecracker/manager.go b/internal/firecracker/manager.goindex c2ebf1ce..536d4800 100644--- a/internal/firecracker/manager.go+++ b/internal/firecracker/manager.go@@ -82,7 +82,11 @@ type SecretsProxyIntegration interface {// GetSessionTokenHosts returns the per-token host restrictions for persisting during hibernate.GetSessionTokenHosts(guestIP string) map[string][]string// ReregisterSession re-creates a proxy session from a persisted token map (used on wake).- ReregisterSession(sandboxID, guestIP string, tokens map[string]string, allowlist []string, tokenHosts map[string][]string)+ ReregisterSession(sandboxID, guestIP string, tokens map[string]string, allowlist []string, tokenHosts map[string][]string, names map[string]string)+ // GetSessionNames returns the env-var-name → sealed-token index for persistence.+ GetSessionNames(guestIP string) map[string]string+ // UpdateSecretValue replaces the value the sealed token for secretName resolves to.+ UpdateSecretValue(sandboxID, secretName, newValue string) bool// CACertPEM returns the CA certificate PEM for injection into the VM trust store.CACertPEM() []byte}diff --git a/internal/logship/shipper.go b/internal/logship/shipper.gonew file mode 100644index 00000000..6648222f--- /dev/null+++ b/internal/logship/shipper.go@@ -0,0 +1,312 @@+// Package logship is the in-VM forwarder that ships sandbox session logs+// (lines from /var/log/* and stdout/stderr from platform-exec'd commands)+// to Axiom.+//+// Lifecycle:+//+// 1. cmd/agent/main starts a Shipper at boot via New(). The shipper is+// DORMANT: events accepted via Send() queue in a bounded ring but+// do not POST anywhere yet. The /var/log tailer starts immediately+// so we don't miss the boot window.+// 2. Worker calls the agent's ConfigureLogship RPC after VM boot. The+// RPC handler calls Shipper.Activate(cfg), passing the ingest token,+// dataset, and per-sandbox identifiers.+// 3. Once activated, queued events are flushed (batches of up to 100 or+// every 200ms) to https://api.axiom.co/v1/datasets/<dataset>/ingest+// with the activation cfg's identifiers stamped on each event at+// flush time.+// 4. If Activate is never called (kill-switch: worker had no ingest+// token), the ring keeps dropping oldest indefinitely. Memory cost+// is bounded by the ring; CPU cost is one no-op tick per 200ms.+//+// This package only depends on the standard library + fsnotify; no other+// internal packages, so tests are self-contained.+package logship++import (+ "bytes"+ "context"+ "encoding/json"+ "fmt"+ "log"+ "net/http"+ "sync"+ "sync/atomic"+ "time"+)++// Source identifies where an event came from.+type Source string++const (+ SourceVarLog Source = "var_log"+ SourceExecStdout Source = "exec_stdout"+ SourceExecStderr Source = "exec_stderr"+ SourceAgent Source = "agent"+)++// Event is one log line as serialised to Axiom. The JSON shape matches+// Axiom's ingest API (top-level _time field; arbitrary other fields are+// stored verbatim).+type Event struct {+ Time time.Time `json:"_time"`+ Source Source `json:"source"`+ Line string `json:"line"`++ // Stamped at flush time from the active config; empty until+ // activated. Sent to Axiom anyway so events captured pre-Activate+ // are still tagged with whatever's set when they finally flush.+ SandboxID string `json:"sandbox_id,omitempty"`+ OrgID string `json:"org_id,omitempty"`++ // Set when source == "var_log".+ Path string `json:"path,omitempty"`++ // Set when source == "exec_*".+ ExecID string `json:"exec_id,omitempty"`+ Command string `json:"command,omitempty"`+ Argv []string `json:"argv,omitempty"`+ ExitCode *int `json:"exit_code,omitempty"`+}++// Config is the activation payload delivered via the worker's+// ConfigureLogship RPC.+type Config struct {+ IngestToken string+ Dataset string+ SandboxID string+ OrgID string+}++// Shipper buffers events in a bounded ring and flushes batches to Axiom+// once Activate has been called.+type Shipper struct {+ bufSize int+ batchSize int+ flushEvery time.Duration+ httpTimeout time.Duration+ httpClient *http.Client++ in chan Event // bounded; drop-oldest on full++ mu sync.RWMutex+ cfg Config // zero until Activate+ activated bool++ droppedTotal atomic.Uint64+ closed atomic.Bool+}++// New returns a dormant Shipper. Run it via Run(ctx) (typically in a+// goroutine) to start the flush loop.+func New() *Shipper {+ return &Shipper{+ bufSize: 10_000,+ batchSize: 100,+ flushEvery: 200 * time.Millisecond,+ httpTimeout: 10 * time.Second,+ httpClient: &http.Client{Timeout: 10 * time.Second},+ in: make(chan Event, 10_000),+ }+}++// Activate enables flushing with the given configuration. Calling+// Activate with an empty IngestToken is a no-op (kill-switch).+// Subsequent calls (e.g. token rotation) replace the config atomically.+func (s *Shipper) Activate(cfg Config) {+ if cfg.IngestToken == "" {+ return+ }+ s.mu.Lock()+ s.cfg = cfg+ s.activated = true+ s.mu.Unlock()+}++// Send enqueues an event. Non-blocking; if the buffer is full, the+// oldest queued event is dropped to make room.+func (s *Shipper) Send(ev Event) {+ if s.closed.Load() {+ return+ }+ if ev.Time.IsZero() {+ ev.Time = time.Now().UTC()+ }+ select {+ case s.in <- ev:+ return+ default:+ // Full — drop oldest to make room.+ select {+ case <-s.in:+ s.droppedTotal.Add(1)+ default:+ }+ select {+ case s.in <- ev:+ default:+ s.droppedTotal.Add(1)+ }+ }+}++// Run drives the flush loop. Returns when ctx is cancelled. The loop is+// safe to call before Activate; pre-Activate it just keeps draining the+// ring into the local batch but does not POST anywhere — flushing is+// gated on having a valid token.+func (s *Shipper) Run(ctx context.Context) {+ defer s.closed.Store(true)++ // Worker pool for HTTP POSTs. Decoupled from the batch loop so a+ // slow Axiom POST never blocks ingestion.+ postCh := make(chan []Event, 8)+ var workersDone sync.WaitGroup+ workersDone.Add(2)+ for i := 0; i < 2; i++ {+ go func() {+ defer workersDone.Done()+ for batch := range postCh {+ s.post(ctx, batch)+ }+ }()+ }++ var batch []Event+ flush := func() {+ if len(batch) == 0 {+ return+ }+ s.mu.RLock()+ cfg := s.cfg+ activated := s.activated+ s.mu.RUnlock()+ if !activated {+ // Hold the batch; it'll get re-flushed once Activate fires.+ // To avoid unbounded growth, cap the held batch at 10× normal.+ if len(batch) > s.batchSize*10 {+ batch = batch[len(batch)-s.batchSize*10:]+ }+ return+ }+ // Stamp identifiers on each event at flush time.+ for i := range batch {+ batch[i].SandboxID = cfg.SandboxID+ batch[i].OrgID = cfg.OrgID+ }+ select {+ case postCh <- batch:+ case <-ctx.Done():+ }+ batch = nil+ }++ tick := time.NewTicker(s.flushEvery)+ defer tick.Stop()++ dropTicker := time.NewTicker(30 * time.Second)+ defer dropTicker.Stop()+ var lastDropped uint64++ for {+ select {+ case <-ctx.Done():+ flush()+ close(postCh)+ workersDone.Wait()+ return+ case ev := <-s.in:+ batch = append(batch, ev)+ if len(batch) >= s.batchSize {+ flush()+ }+ case <-tick.C:+ flush()+ case <-dropTicker.C:+ n := s.droppedTotal.Load()+ if n > lastDropped {+ dropped := n - lastDropped+ lastDropped = n+ batch = append(batch, Event{+ Time: time.Now().UTC(),+ Source: SourceAgent,+ Line: fmt.Sprintf("logship: dropped %d events in last 30s (total %d)", dropped, n),+ })+ }+ }+ }+}++func (s *Shipper) post(ctx context.Context, batch []Event) {+ s.mu.RLock()+ cfg := s.cfg+ s.mu.RUnlock()+ if cfg.IngestToken == "" {+ return // shouldn't happen — flush() gates on activated — defensive+ }++ body, err := json.Marshal(batch)+ if err != nil {+ log.Printf("logship: marshal: %v", err)+ return+ }++ url := fmt.Sprintf("https://api.axiom.co/v1/datasets/%s/ingest", cfg.Dataset)++ // Backoff: 250ms → 500ms → 1s → 2s → 5s, total ~30s before drop.+ delays := []time.Duration{0, 250 * time.Millisecond, 500 * time.Millisecond, 1 * time.Second, 2 * time.Second, 5 * time.Second, 5 * time.Second, 5 * time.Second, 5 * time.Second, 5 * time.Second}+ for i, d := range delays {+ if d > 0 {+ select {+ case <-time.After(d):+ case <-ctx.Done():+ return+ }+ }++ req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(body))+ if err != nil {+ log.Printf("logship: NewRequest: %v", err)+ return+ }+ req.Header.Set("Authorization", "Bearer "+cfg.IngestToken)+ req.Header.Set("Content-Type", "application/json")++ resp, err := s.httpClient.Do(req)+ if err != nil {+ if i == len(delays)-1 {+ log.Printf("logship: POST after %d retries: %v (dropping %d events)", i, err, len(batch))+ s.droppedTotal.Add(uint64(len(batch)))+ return+ }+ continue+ }+ resp.Body.Close()+ if resp.StatusCode < 400 {+ return+ }+ if resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden {+ // Token's bad — retry won't help.+ log.Printf("logship: POST %d (auth) — dropping %d events", resp.StatusCode, len(batch))+ s.droppedTotal.Add(uint64(len(batch)))+ return+ }+ if i == len(delays)-1 {+ log.Printf("logship: POST %d after %d retries (dropping %d events)", resp.StatusCode, i, len(batch))+ s.droppedTotal.Add(uint64(len(batch)))+ return+ }+ }+}++// Stats returns counters for observability.+type Stats struct {+ Dropped uint64+ Queued int+}++func (s *Shipper) Stats() Stats {+ return Stats{+ Dropped: s.droppedTotal.Load(),+ Queued: len(s.in),+ }+}diff --git a/internal/logship/shipper_test.go b/internal/logship/shipper_test.gonew file mode 100644index 00000000..8f4e184b--- /dev/null+++ b/internal/logship/shipper_test.go@@ -0,0 +1,187 @@+package logship++import (+ "context"+ "strings"+ "sync"+ "testing"+ "time"+)++// TestLineWriter_BasicLines: simple newline-separated lines emit+// one Event each with the right source/exec metadata.+func TestLineWriter_BasicLines(t *testing.T) {+ got := captureShipper(t)+ w := NewLineWriter(got.s, SourceExecStdout, "exec-1", "echo", []string{"hi"})++ w.Write([]byte("hello\nworld\n"))+ w.Close(0)++ evs := got.drain(t, 3)++ if evs[0].Line != "hello" || evs[0].Source != SourceExecStdout || evs[0].ExecID != "exec-1" {+ t.Errorf("event[0] = %+v", evs[0])+ }+ if evs[1].Line != "world" {+ t.Errorf("event[1] line = %q, want %q", evs[1].Line, "world")+ }+ // Final EOF event.+ if evs[2].ExitCode == nil || *evs[2].ExitCode != 0 || evs[2].Line != "" {+ t.Errorf("event[2] = %+v, want EOF with exit=0", evs[2])+ }+}++// TestLineWriter_PartialLines: bytes split across multiple Writes+// must be re-assembled on the next newline. No premature emission.+func TestLineWriter_PartialLines(t *testing.T) {+ got := captureShipper(t)+ w := NewLineWriter(got.s, SourceExecStdout, "e", "x", nil)++ w.Write([]byte("hel"))+ w.Write([]byte("lo "))+ w.Write([]byte("world\nrest"))+ w.Close(0)++ evs := got.drain(t, 3)+ if evs[0].Line != "hello world" {+ t.Errorf("expected re-assembled 'hello world', got %q", evs[0].Line)+ }+ // 'rest' is the tail flushed at Close.+ if evs[1].Line != "rest" {+ t.Errorf("expected tail 'rest', got %q", evs[1].Line)+ }+ if evs[2].ExitCode == nil || *evs[2].ExitCode != 0 {+ t.Errorf("expected final EOF, got %+v", evs[2])+ }+}++// TestLineWriter_NoPartialFlushIfTrailingNewline: when Close is+// called and the buffer is already empty (input ended on \n), the+// only synthesised event is the EOF marker — no spurious empty line.+func TestLineWriter_NoPartialFlushIfTrailingNewline(t *testing.T) {+ got := captureShipper(t)+ w := NewLineWriter(got.s, SourceExecStdout, "e", "x", nil)++ w.Write([]byte("a\nb\n"))+ w.Close(7)++ evs := got.drain(t, 3)+ if evs[0].Line != "a" || evs[1].Line != "b" {+ t.Errorf("unexpected lines: %v / %v", evs[0].Line, evs[1].Line)+ }+ if evs[2].Line != "" || evs[2].ExitCode == nil || *evs[2].ExitCode != 7 {+ t.Errorf("expected EOF with exit=7, got %+v", evs[2])+ }+}++// TestLineWriter_NilShipper: a nil shipper must be tolerated (we use+// shipper=nil to disable shipping) — Write/Close must be safe no-ops.+func TestLineWriter_NilShipper(t *testing.T) {+ w := NewLineWriter(nil, SourceExecStdout, "e", "x", nil)+ if _, err := w.Write([]byte("hello\n")); err != nil {+ t.Fatalf("Write returned error with nil shipper: %v", err)+ }+ w.Close(0)+}++// TestLineWriter_LongLines: a single huge line spread across many+// Writes is re-assembled correctly on the trailing newline.+func TestLineWriter_LongLines(t *testing.T) {+ got := captureShipper(t)+ w := NewLineWriter(got.s, SourceExecStdout, "e", "x", nil)++ chunk := strings.Repeat("a", 1024)+ for i := 0; i < 100; i++ {+ w.Write([]byte(chunk))+ }+ w.Write([]byte("\n"))+ w.Close(0)++ evs := got.drain(t, 2)+ if len(evs[0].Line) != 100*1024 {+ t.Errorf("expected re-assembled 100KB line, got %d bytes", len(evs[0].Line))+ }+}++// TestShipper_DropOldest: under flood, the bounded channel drops+// oldest events and reports the dropped count.+func TestShipper_DropOldest(t *testing.T) {+ s := New()+ // Force a tiny buffer to make the test fast.+ s.in = make(chan Event, 4)++ for i := 0; i < 100; i++ {+ s.Send(Event{Line: "x"})+ }+ st := s.Stats()+ if st.Dropped < 90 {+ t.Errorf("expected ~96 drops, got %d", st.Dropped)+ }+ if st.Queued != 4 {+ t.Errorf("expected buffer at capacity 4, got %d", st.Queued)+ }+}++// TestShipper_PreActivateHolds: Send before Activate queues into the+// ring; the flush loop holds the batch (no POST) and discards+// gracefully under cancellation.+func TestShipper_PreActivateHolds(t *testing.T) {+ s := New()+ ctx, cancel := context.WithCancel(context.Background())+ go s.Run(ctx)++ for i := 0; i < 10; i++ {+ s.Send(Event{Line: "pre"})+ }+ // Let the flush ticker fire a couple of times.+ time.Sleep(500 * time.Millisecond)++ st := s.Stats()+ // No drops yet — buffer is well below capacity.+ if st.Dropped != 0 {+ t.Errorf("unexpected drops pre-activate: %d", st.Dropped)+ }+ cancel()+}++// captureShipper steals events directly off the Shipper's channel and+// stashes them in a slice. No Run/HTTP needed — perfect for unit+// testing the producers (LineWriter, etc.) in isolation.+type fakeShipper struct {+ s *Shipper+ mu sync.Mutex+ got []Event+}++func captureShipper(t *testing.T) *fakeShipper {+ t.Helper()+ fs := &fakeShipper{s: New()}+ go func() {+ for ev := range fs.s.in {+ fs.mu.Lock()+ fs.got = append(fs.got, ev)+ fs.mu.Unlock()+ }+ }()+ return fs+}++func (fs *fakeShipper) drain(t *testing.T, want int) []Event {+ t.Helper()+ deadline := time.Now().Add(2 * time.Second)+ for time.Now().Before(deadline) {+ fs.mu.Lock()+ if len(fs.got) >= want {+ out := make([]Event, want)+ copy(out, fs.got[:want])+ fs.mu.Unlock()+ return out+ }+ fs.mu.Unlock()+ time.Sleep(5 * time.Millisecond)+ }+ fs.mu.Lock()+ defer fs.mu.Unlock()+ t.Fatalf("only got %d events, wanted %d", len(fs.got), want)+ return nil+}diff --git a/internal/logship/tee.go b/internal/logship/tee.gonew file mode 100644index 00000000..4350d7d2--- /dev/null+++ b/internal/logship/tee.go@@ -0,0 +1,121 @@+package logship++import (+ "bytes"+ "sync"+)++// LineWriter adapts a stream of bytes (e.g. exec stdout/stderr) into+// line-segmented Events fed to a Shipper. Implements io.Writer so it+// drops cleanly into io.MultiWriter alongside the existing per-exec+// pipes.+//+// Lines are split on '\n'. A trailing partial line (no terminating+// newline) is held in an internal buffer and emitted on Close, along+// with one synthetic "EOF" event carrying the exit code so the UI can+// render "command X exited 0/1".+type LineWriter struct {+ shipper *Shipper+ source Source+ execID string+ command string+ argv []string++ mu sync.Mutex+ buf bytes.Buffer+ final bool // Close() called+}++// NewLineWriter returns a LineWriter that ships to the given Shipper+// under the given Source. execID is a unique-per-exec identifier (the+// caller generates it; ULID/UUID both fine). command + argv are+// stamped on every line so the UI can drill into "all output of this+// exec" without joining tables.+func NewLineWriter(shipper *Shipper, source Source, execID, command string, argv []string) *LineWriter {+ return &LineWriter{+ shipper: shipper,+ source: source,+ execID: execID,+ command: command,+ argv: argv,+ }+}++// Write splits incoming bytes on '\n' and ships each completed line as+// an Event. A trailing partial is held in the buffer.+func (w *LineWriter) Write(p []byte) (int, error) {+ if w.shipper == nil {+ return len(p), nil+ }+ w.mu.Lock()+ defer w.mu.Unlock()+ if w.final {+ // Close already called — don't ship more.+ return len(p), nil+ }++ w.buf.Write(p)++ for {+ data := w.buf.Bytes()+ idx := bytes.IndexByte(data, '\n')+ if idx < 0 {+ break+ }+ line := string(data[:idx])+ // Drop the consumed bytes (including the newline).+ w.buf.Next(idx + 1)++ w.shipper.Send(Event{+ Source: w.source,+ Line: line,+ ExecID: w.execID,+ Command: w.command,+ Argv: w.argv,+ })+ }+ return len(p), nil+}++// Close flushes any partial-line residue and emits one final synthetic+// event carrying the exit code. After Close, further Writes are+// silently dropped (defensive — a well-behaved caller should not Write+// after Close, but stdout/stderr pipes can race with Wait).+//+// Pass exitCode = -1 if the process did not exit cleanly (signal /+// timeout / killed); the EOF event records it as -1 unchanged so the+// UI can distinguish "exited" from "killed".+func (w *LineWriter) Close(exitCode int) {+ if w.shipper == nil {+ return+ }+ w.mu.Lock()+ defer w.mu.Unlock()+ if w.final {+ return+ }+ w.final = true++ // Flush any trailing partial line.+ if w.buf.Len() > 0 {+ w.shipper.Send(Event{+ Source: w.source,+ Line: w.buf.String(),+ ExecID: w.execID,+ Command: w.command,+ Argv: w.argv,+ })+ w.buf.Reset()+ }++ // Final synthetic event marking the exec's end.+ ec := exitCode+ w.shipper.Send(Event{+ Source: w.source,+ Line: "",+ ExecID: w.execID,+ Command: w.command,+ Argv: w.argv,+ ExitCode: &ec,+ })+}diff --git a/internal/logship/varlog.go b/internal/logship/varlog.gonew file mode 100644index 00000000..d9414e07--- /dev/null+++ b/internal/logship/varlog.go@@ -0,0 +1,205 @@+package logship++import (+ "bufio"+ "context"+ "io"+ "log"+ "os"+ "path/filepath"+ "regexp"+ "strings"+ "sync"++ "github.com/fsnotify/fsnotify"+)++// skipFilenamePattern matches files inside /var/log/* that we never+// tail: rotated/compressed archives and binary system logs.+var skipFilenamePattern = regexp.MustCompile(`(^|\.)(wtmp|btmp|lastlog|gz|bz2|xz|zst)$|\.\d+(\.\w+)?$`)++// VarLogTailer watches a root directory (typically /var/log) recursively+// and ships every line appended to any regular file there. New files+// (created during the sandbox's lifetime) are picked up via inotify+// IN_CREATE.+//+// Files are tailed from their *current* end, not from the beginning —+// we don't backfill historical content (it's noisy, often binary, and+// would dump megabytes of irrelevant context every sandbox boot).+type VarLogTailer struct {+ root string+ shipper *Shipper++ mu sync.Mutex+ tailing map[string]*tailedFile // path → state+}++type tailedFile struct {+ path string+ offset int64+}++// NewVarLogTailer creates a tailer rooted at the given directory.+func NewVarLogTailer(shipper *Shipper, root string) *VarLogTailer {+ return &VarLogTailer{+ root: root,+ shipper: shipper,+ tailing: make(map[string]*tailedFile),+ }+}++// Run starts watching. Returns when ctx is cancelled or the watcher+// fails to initialise. Errors from individual file reads are logged+// but do not stop the loop.+func (t *VarLogTailer) Run(ctx context.Context) {+ w, err := fsnotify.NewWatcher()+ if err != nil {+ log.Printf("logship/varlog: NewWatcher: %v (logs from %s will not be shipped)", err, t.root)+ return+ }+ defer w.Close()++ // Walk root once; register every existing regular file at offset =+ // EOF, register every dir for IN_CREATE notifications.+ if err := filepath.Walk(t.root, func(path string, info os.FileInfo, err error) error {+ if err != nil || info == nil {+ return nil+ }+ if info.IsDir() {+ _ = w.Add(path)+ return nil+ }+ if t.skipFile(path, info) {+ return nil+ }+ t.startTail(path, info.Size())+ return nil+ }); err != nil {+ log.Printf("logship/varlog: walk %s: %v", t.root, err)+ }++ for {+ select {+ case <-ctx.Done():+ return+ case ev, ok := <-w.Events:+ if !ok {+ return+ }+ t.handleEvent(w, ev)+ case err, ok := <-w.Errors:+ if !ok {+ return+ }+ log.Printf("logship/varlog: watcher error: %v", err)+ }+ }+}++func (t *VarLogTailer) handleEvent(w *fsnotify.Watcher, ev fsnotify.Event) {+ switch {+ case ev.Op&fsnotify.Create != 0:+ info, err := os.Stat(ev.Name)+ if err != nil {+ return+ }+ if info.IsDir() {+ _ = w.Add(ev.Name)+ return+ }+ if t.skipFile(ev.Name, info) {+ return+ }+ // New file: tail from byte 0 (it's brand new).+ t.startTail(ev.Name, 0)+ t.readAvailable(ev.Name)+ case ev.Op&fsnotify.Write != 0:+ t.readAvailable(ev.Name)+ case ev.Op&fsnotify.Remove != 0, ev.Op&fsnotify.Rename != 0:+ t.mu.Lock()+ delete(t.tailing, ev.Name)+ t.mu.Unlock()+ }+}++func (t *VarLogTailer) startTail(path string, offset int64) {+ t.mu.Lock()+ defer t.mu.Unlock()+ if _, exists := t.tailing[path]; exists {+ return+ }+ t.tailing[path] = &tailedFile{path: path, offset: offset}+}++func (t *VarLogTailer) readAvailable(path string) {+ t.mu.Lock()+ tf, ok := t.tailing[path]+ t.mu.Unlock()+ if !ok {+ return+ }++ f, err := os.Open(path)+ if err != nil {+ return+ }+ defer f.Close()++ info, err := f.Stat()+ if err != nil {+ return+ }++ // Truncation: file shrank. Reset to start.+ if info.Size() < tf.offset {+ tf.offset = 0+ }++ if _, err := f.Seek(tf.offset, io.SeekStart); err != nil {+ return+ }++ br := bufio.NewReader(f)+ var newOffset = tf.offset+ for {+ line, err := br.ReadString('\n')+ newOffset += int64(len(line))+ // Trim the trailing newline before shipping.+ stripped := strings.TrimRight(line, "\r\n")+ if stripped != "" {+ t.shipper.Send(Event{+ Source: SourceVarLog,+ Line: stripped,+ Path: path,+ })+ }+ if err != nil {+ break+ }+ }+ tf.offset = newOffset+}++func (t *VarLogTailer) skipFile(path string, info os.FileInfo) bool {+ if !info.Mode().IsRegular() {+ return true+ }+ name := filepath.Base(path)+ if skipFilenamePattern.MatchString(name) {+ return true+ }+ // Skip files that look binary (first 256 bytes contain a NUL).+ f, err := os.Open(path)+ if err != nil {+ return true+ }+ defer f.Close()+ var sniff [256]byte+ n, _ := f.Read(sniff[:])+ for i := 0; i < n; i++ {+ if sniff[i] == 0 {+ return true+ }+ }+ return false+}diff --git a/internal/metrics/metrics.go b/internal/metrics/metrics.goindex 4f714058..54a78aea 100644--- a/internal/metrics/metrics.go+++ b/internal/metrics/metrics.go@@ -10,6 +10,9 @@ import ("github.com/prometheus/client_golang/prometheus/promhttp")+// lifecycleBuckets covers from sub-second warm forks to slow checkpoint uploads.+var lifecycleBuckets = []float64{0.1, 0.25, 0.5, 1.0, 2.0, 5.0, 10.0, 30.0, 60.0}+// Worker metricsvar (SandboxesActive = prometheus.NewGaugeVec(@@ -24,9 +27,47 @@ var (prometheus.HistogramOpts{Name: "opensandbox_sandbox_create_duration_seconds",Help: "Time to create a sandbox",- Buckets: []float64{0.1, 0.25, 0.5, 1.0, 2.0, 5.0, 10.0},+ Buckets: lifecycleBuckets,+ },+ []string{"region", "template", "status"},+ )++ CheckpointDuration = prometheus.NewHistogramVec(+ prometheus.HistogramOpts{+ Name: "opensandbox_checkpoint_duration_seconds",+ Help: "Time to create a sandbox checkpoint (savevm + archive + upload)",+ Buckets: lifecycleBuckets,+ },+ []string{"region", "template", "status"},+ )++ // Exists alongside CheckpointDuration{status="failure"} so failures can be+ // attributed by *cause* without log parsing.+ CheckpointFailuresTotal = prometheus.NewCounterVec(+ prometheus.CounterOpts{+ Name: "opensandbox_checkpoint_failures_total",+ Help: "Checkpoint failures by classified reason",},- []string{"region", "template"},+ []string{"region", "template", "reason"},+ )++ HibernateDuration = prometheus.NewHistogramVec(+ prometheus.HistogramOpts{+ Name: "opensandbox_hibernate_duration_seconds",+ Help: "Time to hibernate a sandbox (quiesce + savevm + upload)",+ Buckets: lifecycleBuckets,+ },+ []string{"region", "template", "status"},+ )++ // source=warm_cache: local snapshot reused. source=s3: downloaded archive.+ WakeDuration = prometheus.NewHistogramVec(+ prometheus.HistogramOpts{+ Name: "opensandbox_wake_duration_seconds",+ Help: "Time to create a sandbox from a checkpoint",+ Buckets: lifecycleBuckets,+ },+ []string{"region", "template", "source", "status"},)ExecDuration = prometheus.NewHistogramVec(@@ -54,6 +95,44 @@ var ([]string{"region", "worker_id"},)+ // Worker resource gauges. Populated by a periodic tick in cmd/worker/main.go.+ WorkerDiskUsedBytes = prometheus.NewGaugeVec(+ prometheus.GaugeOpts{Name: "opensandbox_worker_disk_used_bytes", Help: "Disk bytes used on the worker's data mount"},+ []string{"region", "worker_id", "mount"},+ )+ WorkerDiskAvailableBytes = prometheus.NewGaugeVec(+ prometheus.GaugeOpts{Name: "opensandbox_worker_disk_available_bytes", Help: "Disk bytes available on the worker's data mount"},+ []string{"region", "worker_id", "mount"},+ )+ WorkerDiskTotalBytes = prometheus.NewGaugeVec(+ prometheus.GaugeOpts{Name: "opensandbox_worker_disk_total_bytes", Help: "Total disk bytes on the worker's data mount"},+ []string{"region", "worker_id", "mount"},+ )++ WorkerMemoryTotalBytes = prometheus.NewGaugeVec(+ prometheus.GaugeOpts{Name: "opensandbox_worker_memory_total_bytes", Help: "Total physical memory (MemTotal)"},+ []string{"region", "worker_id"},+ )+ WorkerMemoryAvailableBytes = prometheus.NewGaugeVec(+ prometheus.GaugeOpts{Name: "opensandbox_worker_memory_available_bytes", Help: "Memory available to userspace (MemAvailable)"},+ []string{"region", "worker_id"},+ )+ // Sum of MemoryMB committed to running sandboxes. Measures oversubscription+ // independent of actual guest workload.+ WorkerMemoryAllocatedBytes = prometheus.NewGaugeVec(+ prometheus.GaugeOpts{Name: "opensandbox_worker_memory_allocated_bytes", Help: "Sum of memory allocated to running sandboxes"},+ []string{"region", "worker_id"},+ )++ // CPU pressure percent. window: avg10/avg60/avg300.+ // source=psi: PSI "some" stall pct from /proc/pressure/cpu (preferred).+ // source=loadavg: loadavg/nproc*100 fallback (older kernels / macOS dev hosts);+ // different semantics — interpret with care.+ WorkerCPUPressure = prometheus.NewGaugeVec(+ prometheus.GaugeOpts{Name: "opensandbox_worker_cpu_pressure", Help: "CPU pressure percent (PSI 'some' or loadavg/nproc*100 fallback)"},+ []string{"region", "worker_id", "window", "source"},+ )+DirectConnectionsActive = prometheus.NewGaugeVec(prometheus.GaugeOpts{Name: "opensandbox_direct_connections_active",@@ -81,6 +160,23 @@ var ([]string{"method", "path", "status"},)+ HTTPRequestDuration = prometheus.NewHistogramVec(+ prometheus.HistogramOpts{+ Name: "opensandbox_http_request_duration_seconds",+ Help: "HTTP request handler latency",+ Buckets: []float64{0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30},+ },+ []string{"method", "path", "status"},+ )++ HTTPRequestsInFlight = prometheus.NewGaugeVec(+ prometheus.GaugeOpts{+ Name: "opensandbox_http_requests_in_flight",+ Help: "Currently in-flight HTTP requests",+ },+ []string{"method"},+ )+SandboxCreatesTotal = prometheus.NewCounterVec(prometheus.CounterOpts{Name: "opensandbox_sandbox_creates_total",@@ -115,16 +211,28 @@ var ()func init() {- // Register all metricsprometheus.MustRegister(SandboxesActive,SandboxCreateDuration,+ CheckpointDuration,+ CheckpointFailuresTotal,+ HibernateDuration,+ WakeDuration,ExecDuration,PTYSessionsActive,WorkerUtilization,+ WorkerDiskUsedBytes,+ WorkerDiskAvailableBytes,+ WorkerDiskTotalBytes,+ WorkerMemoryTotalBytes,+ WorkerMemoryAvailableBytes,+ WorkerMemoryAllocatedBytes,+ WorkerCPUPressure,DirectConnectionsActive,SQLiteSyncLag,HTTPRequestsTotal,+ HTTPRequestDuration,+ HTTPRequestsInFlight,SandboxCreatesTotal,AuthAttemptsTotal,WorkersTotal,@@ -138,9 +246,16 @@ func Handler() http.Handler {}// EchoMiddleware returns Echo middleware that instruments HTTP requests.+//+// path label uses c.Path() (the route template, e.g. /api/sandboxes/:id) rather+// than c.Request().URL.Path so high-cardinality IDs don't explode the metric.func EchoMiddleware() echo.MiddlewareFunc {return func(next echo.HandlerFunc) echo.HandlerFunc {return func(c echo.Context) error {+ method := c.Request().Method+ HTTPRequestsInFlight.WithLabelValues(method).Inc()+ defer HTTPRequestsInFlight.WithLabelValues(method).Dec()+start := time.Now()err := next(c)duration := time.Since(start)@@ -152,13 +267,11 @@ func EchoMiddleware() echo.MiddlewareFunc {}}- HTTPRequestsTotal.WithLabelValues(- c.Request().Method,- c.Path(),- strconv.Itoa(status),- ).Inc()+ statusStr := strconv.Itoa(status)+ path := c.Path()+ HTTPRequestsTotal.WithLabelValues(method, path, statusStr).Inc()+ HTTPRequestDuration.WithLabelValues(method, path, statusStr).Observe(duration.Seconds())- _ = duration // Could add request duration histogram herereturn err}}diff --git a/internal/obslog/echo.go b/internal/obslog/echo.gonew file mode 100644index 00000000..df53c36e--- /dev/null+++ b/internal/obslog/echo.go@@ -0,0 +1,78 @@+package obslog++import (+ "log/slog"+ "time"++ "github.com/labstack/echo/v4"+)++// EchoMiddleware stashes the X-Request-Id header and the :id URL param+// (sandbox_id) into the request context so downstream handler logs are+// automatically tagged. On request completion it emits a single structured+// access-log line.+//+// Place this AFTER middleware.RequestID() — that middleware generates the+// X-Request-Id if absent. Replaces middleware.Logger().+func EchoMiddleware() echo.MiddlewareFunc {+ return func(next echo.HandlerFunc) echo.HandlerFunc {+ return func(c echo.Context) error {+ start := time.Now()+ req := c.Request()++ // middleware.RequestID() (which runs before us) sets the id on+ // the RESPONSE header — that's the authoritative location whether+ // the id was forwarded inbound or generated here. Falling back to+ // the request header is defensive: a future caller might want+ // only the request header set.+ rid := c.Response().Header().Get(echo.HeaderXRequestID)+ if rid == "" {+ rid = req.Header.Get(echo.HeaderXRequestID)+ }+ rf := RequestFields{+ RequestID: rid,+ SandboxID: c.Param("id"),+ }+ ctx := WithRequest(req.Context(), rf)+ c.SetRequest(req.WithContext(ctx))++ err := next(c)++ res := c.Response()+ attrs := []any{+ slog.String("event", "http_request"),+ slog.String("method", req.Method),+ slog.String("path", c.Path()),+ slog.String("uri", req.RequestURI),+ slog.Int("status", res.Status),+ slog.Int64("duration_ms", time.Since(start).Milliseconds()),+ slog.String("remote_ip", c.RealIP()),+ slog.Int64("bytes_in", req.ContentLength),+ slog.Int64("bytes_out", res.Size),+ }+ if err != nil {+ attrs = append(attrs, slog.String("err", err.Error()))+ }++ level := slog.LevelInfo+ switch {+ case res.Status >= 500:+ level = slog.LevelError+ case res.Status >= 400:+ level = slog.LevelWarn+ }+ slog.LogAttrs(ctx, level, "http_request", toSlogAttrs(attrs)...)+ return err+ }+ }+}++func toSlogAttrs(in []any) []slog.Attr {+ out := make([]slog.Attr, 0, len(in))+ for _, a := range in {+ if attr, ok := a.(slog.Attr); ok {+ out = append(out, attr)+ }+ }+ return out+}diff --git a/internal/obslog/echo_test.go b/internal/obslog/echo_test.gonew file mode 100644index 00000000..e408043b--- /dev/null+++ b/internal/obslog/echo_test.go@@ -0,0 +1,134 @@+package obslog++import (+ "bytes"+ "context"+ "encoding/json"+ "log/slog"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "github.com/labstack/echo/v4"+ "github.com/labstack/echo/v4/middleware"+)++// TestEchoMiddlewareForwardsRequestIDIntoHandlerContext exercises the real+// middleware chain a server uses: middleware.RequestID generates the header+// (or reuses an inbound one), obslog.EchoMiddleware pulls it into context,+// and a handler emits a log line via slog.InfoContext that carries the same+// id. This is the contract that makes the cross-service join in Axiom work.+func TestEchoMiddlewareForwardsRequestIDIntoHandlerContext(t *testing.T) {+ var buf bytes.Buffer+ // Capture slog output to buf. slog.Default is process-wide so other tests+ // running in parallel would see this; run sequentially.+ prevDefault := slog.Default()+ t.Cleanup(func() { slog.SetDefault(prevDefault) })++ handler := &ctxHandler{+ inner: slog.NewJSONHandler(&buf, &slog.HandlerOptions{Level: slog.LevelDebug}),+ }+ slog.SetDefault(slog.New(handler))++ e := echo.New()+ e.Use(middleware.RequestID())+ e.Use(EchoMiddleware())+ e.GET("/sandboxes/:id/files", func(c echo.Context) error {+ slog.InfoContext(c.Request().Context(), "handler_invoked")+ return c.String(http.StatusOK, "ok")+ })++ req := httptest.NewRequest(http.MethodGet, "/sandboxes/sb-test-1/files", nil)+ req.Header.Set(echo.HeaderXRequestID, "req-from-control-plane")+ rec := httptest.NewRecorder()+ e.ServeHTTP(rec, req)++ if rec.Code != http.StatusOK {+ t.Fatalf("status = %d, want 200", rec.Code)+ }++ // Parse every JSON line; we expect at least one with msg=handler_invoked+ // and one with msg=http_request, both carrying the same request_id ++ // sandbox_id.+ var handlerLine, accessLine map[string]any+ for _, line := range strings.Split(strings.TrimSpace(buf.String()), "\n") {+ var m map[string]any+ if err := json.Unmarshal([]byte(line), &m); err != nil {+ t.Fatalf("non-JSON log line: %q (err=%v)", line, err)+ }+ switch m["msg"] {+ case "handler_invoked":+ handlerLine = m+ case "http_request":+ accessLine = m+ }+ }++ if handlerLine == nil {+ t.Fatalf("no handler log line found in:\n%s", buf.String())+ }+ if accessLine == nil {+ t.Fatalf("no http_request access log line found in:\n%s", buf.String())+ }++ for _, ll := range []map[string]any{handlerLine, accessLine} {+ if ll["request_id"] != "req-from-control-plane" {+ t.Errorf("request_id = %v, want req-from-control-plane (msg=%v)", ll["request_id"], ll["msg"])+ }+ if ll["sandbox_id"] != "sb-test-1" {+ t.Errorf("sandbox_id = %v, want sb-test-1 (msg=%v)", ll["sandbox_id"], ll["msg"])+ }+ }++ if accessLine["status"] != float64(200) {+ t.Errorf("access log status = %v, want 200", accessLine["status"])+ }+ if accessLine["method"] != "GET" {+ t.Errorf("access log method = %v, want GET", accessLine["method"])+ }+}++// TestEchoMiddlewareGeneratesRequestIDIfMissing verifies that Echo's+// middleware.RequestID generates an id when no inbound header is present,+// and that obslog still picks it up. This is the case when a client hits+// the control plane directly.+func TestEchoMiddlewareGeneratesRequestIDIfMissing(t *testing.T) {+ var buf bytes.Buffer+ prevDefault := slog.Default()+ t.Cleanup(func() { slog.SetDefault(prevDefault) })++ handler := &ctxHandler{+ inner: slog.NewJSONHandler(&buf, &slog.HandlerOptions{Level: slog.LevelDebug}),+ }+ slog.SetDefault(slog.New(handler))++ e := echo.New()+ e.Use(middleware.RequestID())+ e.Use(EchoMiddleware())+ e.GET("/health", func(c echo.Context) error {+ return c.String(http.StatusOK, "ok")+ })++ req := httptest.NewRequest(http.MethodGet, "/health", nil)+ rec := httptest.NewRecorder()+ e.ServeHTTP(rec, req)++ if rec.Code != http.StatusOK {+ t.Fatalf("status = %d, want 200", rec.Code)+ }++ var got map[string]any+ if err := json.Unmarshal(bytes.TrimSpace(buf.Bytes()), &got); err != nil {+ t.Fatalf("unmarshal: %v\n%s", err, buf.String())+ }+ rid, _ := got["request_id"].(string)+ if rid == "" {+ t.Fatalf("expected generated request_id, got %v", got["request_id"])+ }+}++// Compile-time check: ctxHandler implements slog.Handler so it can be passed+// to slog.New.+var _ slog.Handler = (*ctxHandler)(nil)+var _ context.Context = context.Background()diff --git a/internal/obslog/obslog.go b/internal/obslog/obslog.gonew file mode 100644index 00000000..a948fd43--- /dev/null+++ b/internal/obslog/obslog.go@@ -0,0 +1,206 @@+// Package obslog provides structured JSON logging with a stable per-host+// envelope (service, service_id, cell_id, region, hostname, host_ip, version)+// shared across the control plane and worker daemon. Per-request fields+// (request_id, sandbox_id, worker_id) are added via context.+//+// All logs are emitted as JSON on stdout/stderr; Vector reads journald/Docker+// stdout on each host and ships to Axiom. Field names are snake_case and+// fixed — adding a new well-known field requires a code change here so that+// the dashboard schema stays stable across services.+package obslog++import (+ "context"+ "log"+ "log/slog"+ "net"+ "os"+ "strings"+)++// Service identifiers used in the `service` field. Keep this list short and+// stable; adding a value is fine but renaming one breaks dashboards.+const (+ ServiceControlPlane = "control-plane"+ ServiceWorker = "worker"+ ServiceDB = "db"+)++// HostFields is the per-process envelope, captured at startup and attached+// to every log line. Empty values are omitted.+type HostFields struct {+ Service string // "control-plane" | "worker" | "db"+ ServiceID string // worker_id for workers; hostname for control plane+ CellID string // <region>-<pool>, e.g. "eastus2-default"+ Region string+ Hostname string+ HostIP string+ Version string+}++// contextKey is unexported to prevent collisions with other packages.+type contextKey struct{}++// RequestFields are per-request attributes attached to log lines via context.+// Empty fields are omitted from output.+type RequestFields struct {+ RequestID string // X-Request-Id, propagated across services+ SandboxID string // when in scope+ WorkerID string // on control-plane logs, the worker chosen for this request+}++// Init builds a JSON slog.Logger with HostFields baked in, installs it as the+// default slog logger, AND redirects the stdlib `log` package through it so+// existing `log.Printf` call sites are picked up automatically. Returns the+// logger for explicit use.+//+// Call this once from main() before any logging happens.+func Init(h HostFields, level slog.Level) *slog.Logger {+ if h.Hostname == "" {+ h.Hostname, _ = os.Hostname()+ }+ if h.HostIP == "" {+ h.HostIP = detectHostIP()+ }++ handler := &ctxHandler{+ inner: slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{+ Level: level,+ }),+ }++ attrs := []slog.Attr{}+ if h.Service != "" {+ attrs = append(attrs, slog.String("service", h.Service))+ }+ if h.ServiceID != "" {+ attrs = append(attrs, slog.String("service_id", h.ServiceID))+ }+ if h.CellID != "" {+ attrs = append(attrs, slog.String("cell_id", h.CellID))+ }+ if h.Region != "" {+ attrs = append(attrs, slog.String("region", h.Region))+ }+ if h.Hostname != "" {+ attrs = append(attrs, slog.String("hostname", h.Hostname))+ }+ if h.HostIP != "" {+ attrs = append(attrs, slog.String("host_ip", h.HostIP))+ }+ if h.Version != "" {+ attrs = append(attrs, slog.String("version", h.Version))+ }++ logger := slog.New(handler.WithAttrs(attrs))+ slog.SetDefault(logger)++ // Redirect stdlib log.Printf / log.Println / log.Fatalf through slog so+ // existing call sites emit JSON with the host envelope. Stdlib log calls+ // land at INFO; this loses no semantics because the existing call sites+ // don't differentiate levels.+ log.SetFlags(0)+ log.SetOutput(&slogWriter{logger: logger, level: slog.LevelInfo})++ return logger+}++// WithRequest returns a new context carrying request fields. Subsequent log+// lines emitted with this context (via slog.InfoContext etc.) include them.+func WithRequest(ctx context.Context, f RequestFields) context.Context {+ if existing, ok := ctx.Value(contextKey{}).(RequestFields); ok {+ // Merge — non-empty new fields win, but don't clobber an existing+ // request_id mid-flight.+ if f.RequestID == "" {+ f.RequestID = existing.RequestID+ }+ if f.SandboxID == "" {+ f.SandboxID = existing.SandboxID+ }+ if f.WorkerID == "" {+ f.WorkerID = existing.WorkerID+ }+ }+ return context.WithValue(ctx, contextKey{}, f)+}++// Request returns the RequestFields stored on ctx, or the zero value.+func Request(ctx context.Context) RequestFields {+ if ctx == nil {+ return RequestFields{}+ }+ f, _ := ctx.Value(contextKey{}).(RequestFields)+ return f+}++// ctxHandler wraps a slog.Handler, injecting per-request fields from ctx into+// every record. This means call sites don't have to pass attrs manually —+// `slog.InfoContext(ctx, "msg")` automatically picks up request_id etc.+type ctxHandler struct {+ inner slog.Handler+}++func (h *ctxHandler) Enabled(ctx context.Context, level slog.Level) bool {+ return h.inner.Enabled(ctx, level)+}++func (h *ctxHandler) Handle(ctx context.Context, r slog.Record) error {+ rf := Request(ctx)+ if rf.RequestID != "" {+ r.AddAttrs(slog.String("request_id", rf.RequestID))+ }+ if rf.SandboxID != "" {+ r.AddAttrs(slog.String("sandbox_id", rf.SandboxID))+ }+ if rf.WorkerID != "" {+ r.AddAttrs(slog.String("worker_id", rf.WorkerID))+ }+ return h.inner.Handle(ctx, r)+}++func (h *ctxHandler) WithAttrs(attrs []slog.Attr) slog.Handler {+ return &ctxHandler{inner: h.inner.WithAttrs(attrs)}+}++func (h *ctxHandler) WithGroup(name string) slog.Handler {+ return &ctxHandler{inner: h.inner.WithGroup(name)}+}++// slogWriter adapts an io.Writer call (used by stdlib log.Logger) to a slog+// call so legacy `log.Printf("...")` lines flow through the JSON pipeline.+type slogWriter struct {+ logger *slog.Logger+ level slog.Level+}++func (w *slogWriter) Write(p []byte) (int, error) {+ msg := strings.TrimRight(string(p), "\n")+ w.logger.Log(context.Background(), w.level, msg)+ return len(p), nil+}++// detectHostIP returns the first non-loopback IPv4 address on the host, or ""+// if none can be discovered. Used as a fallback when OPENSANDBOX_HOST_IP is+// not provisioned at boot.+func detectHostIP() string {+ addrs, err := net.InterfaceAddrs()+ if err != nil {+ return ""+ }+ for _, a := range addrs {+ ipnet, ok := a.(*net.IPNet)+ // Skip loopback (127.x) and link-local (169.254.x). On Azure, the+ // IMDS metadata interface advertises 169.254.169.253 and shows up+ // first in InterfaceAddrs() — without this filter, every Azure host+ // reports the same IP, which collapses per-host filtering in Axiom.+ if !ok || ipnet.IP.IsLoopback() || ipnet.IP.IsLinkLocalUnicast() {+ continue+ }+ ip4 := ipnet.IP.To4()+ if ip4 == nil {+ continue+ }+ return ip4.String()+ }+ return ""+}diff --git a/internal/obslog/obslog_test.go b/internal/obslog/obslog_test.gonew file mode 100644index 00000000..2531fe6c--- /dev/null+++ b/internal/obslog/obslog_test.go@@ -0,0 +1,125 @@+package obslog++import (+ "bytes"+ "context"+ "encoding/json"+ "log/slog"+ "net"+ "testing"+)++// newTestLogger builds an isolated logger writing to buf, with the same+// ctxHandler wrapping the real package uses. Init() can't be used in tests+// because it mutates process globals.+func newTestLogger(buf *bytes.Buffer, host HostFields) *slog.Logger {+ handler := &ctxHandler{+ inner: slog.NewJSONHandler(buf, &slog.HandlerOptions{Level: slog.LevelDebug}),+ }+ attrs := []slog.Attr{+ slog.String("service", host.Service),+ slog.String("service_id", host.ServiceID),+ slog.String("cell_id", host.CellID),+ }+ return slog.New(handler.WithAttrs(attrs))+}++func TestHostEnvelopeAppearsOnEveryLine(t *testing.T) {+ var buf bytes.Buffer+ logger := newTestLogger(&buf, HostFields{+ Service: ServiceControlPlane,+ ServiceID: "cp-1",+ CellID: "eastus2-default",+ })+ logger.Info("hello")++ var got map[string]any+ if err := json.Unmarshal(buf.Bytes(), &got); err != nil {+ t.Fatalf("unmarshal: %v\n%s", err, buf.String())+ }+ if got["service"] != "control-plane" {+ t.Errorf("service = %v, want control-plane", got["service"])+ }+ if got["service_id"] != "cp-1" {+ t.Errorf("service_id = %v, want cp-1", got["service_id"])+ }+ if got["cell_id"] != "eastus2-default" {+ t.Errorf("cell_id = %v, want eastus2-default", got["cell_id"])+ }+ if got["msg"] != "hello" {+ t.Errorf("msg = %v, want hello", got["msg"])+ }+}++func TestRequestFieldsFromContext(t *testing.T) {+ var buf bytes.Buffer+ logger := newTestLogger(&buf, HostFields{Service: ServiceWorker})++ ctx := WithRequest(context.Background(), RequestFields{+ RequestID: "req-abc",+ SandboxID: "sb-xyz",+ })+ logger.InfoContext(ctx, "handling")++ var got map[string]any+ if err := json.Unmarshal(buf.Bytes(), &got); err != nil {+ t.Fatalf("unmarshal: %v\n%s", err, buf.String())+ }+ if got["request_id"] != "req-abc" {+ t.Errorf("request_id = %v, want req-abc", got["request_id"])+ }+ if got["sandbox_id"] != "sb-xyz" {+ t.Errorf("sandbox_id = %v, want sb-xyz", got["sandbox_id"])+ }+}++func TestRequestFieldsMergeWithoutClobbering(t *testing.T) {+ ctx := WithRequest(context.Background(), RequestFields{RequestID: "req-1"})+ ctx = WithRequest(ctx, RequestFields{SandboxID: "sb-1"})++ got := Request(ctx)+ if got.RequestID != "req-1" {+ t.Errorf("RequestID = %q, want req-1 (must survive second WithRequest)", got.RequestID)+ }+ if got.SandboxID != "sb-1" {+ t.Errorf("SandboxID = %q, want sb-1", got.SandboxID)+ }+}++func TestDetectHostIPSkipsLinkLocal(t *testing.T) {+ // We can't easily inject fake interfaces, but we can assert the returned+ // IP — if any — is not in the link-local or loopback ranges. On a host+ // with at least one normal interface this guards against the Azure IMDS+ // regression where 169.254.169.253 was being reported.+ ip := detectHostIP()+ if ip == "" {+ t.Skip("no non-loopback interface available in test environment")+ }+ parsed := net.ParseIP(ip)+ if parsed == nil {+ t.Fatalf("detectHostIP returned %q which is not a valid IP", ip)+ }+ if parsed.IsLoopback() {+ t.Errorf("detectHostIP returned loopback %q", ip)+ }+ if parsed.IsLinkLocalUnicast() {+ t.Errorf("detectHostIP returned link-local %q", ip)+ }+}++func TestRequestFieldsOmittedWhenAbsent(t *testing.T) {+ var buf bytes.Buffer+ logger := newTestLogger(&buf, HostFields{Service: ServiceWorker})+ logger.Info("no request context")++ var got map[string]any+ if err := json.Unmarshal(buf.Bytes(), &got); err != nil {+ t.Fatalf("unmarshal: %v", err)+ }+ if _, exists := got["request_id"]; exists {+ t.Errorf("request_id should be absent when not set, got %v", got["request_id"])+ }+ if _, exists := got["sandbox_id"]; exists {+ t.Errorf("sandbox_id should be absent when not set, got %v", got["sandbox_id"])+ }+}diff --git a/internal/proxy/proxy.go b/internal/proxy/proxy.goindex 444f984e..ed1b13eb 100644--- a/internal/proxy/proxy.go+++ b/internal/proxy/proxy.go@@ -252,7 +252,7 @@ func (p *SandboxProxy) doHTTP(c echo.Context, sandboxID, addr string, hostPort iDialContext: (&net.Dialer{Timeout: 2 * time.Second,}).DialContext,- ResponseHeaderTimeout: 10 * time.Second,+ ResponseHeaderTimeout: 60 * time.Second,}var proxyErr errordiff --git a/internal/proxy/sandbox_api_proxy.go b/internal/proxy/sandbox_api_proxy.goindex 611d70f9..05b53cca 100644--- a/internal/proxy/sandbox_api_proxy.go+++ b/internal/proxy/sandbox_api_proxy.go@@ -266,6 +266,13 @@ func (p *SandboxAPIProxy) doHTTP(c echo.Context, sandboxID, workerURL, token strr.URL.RawQuery = c.Request().URL.RawQueryr.Host = target.Host+ // Forward X-Request-Id so worker log lines share the same id as the+ // control plane log line for this request. Echo's middleware.RequestID+ // on the worker side reuses the inbound header if present.+ if rid := c.Request().Header.Get(echo.HeaderXRequestID); rid != "" {+ r.Header.Set(echo.HeaderXRequestID, rid)+ }+// Set sandbox JWT auth for the workerif token != "" {r.Header.Set("Authorization", "Bearer "+token)diff --git a/internal/qemu/agent_client.go b/internal/qemu/agent_client.goindex 01292c15..cc8db1e6 100644--- a/internal/qemu/agent_client.go+++ b/internal/qemu/agent_client.go@@ -4,14 +4,19 @@ import ("context""fmt""io"+ "log""net"+ "strings"+ "sync""time""golang.org/x/sys/unix""google.golang.org/grpc""google.golang.org/grpc/backoff"+ "google.golang.org/grpc/codes""google.golang.org/grpc/credentials/insecure""google.golang.org/grpc/keepalive"+ "google.golang.org/grpc/status"pb "github.com/opensandbox/opensandbox/proto/agent")@@ -19,51 +24,61 @@ import (const streamChunkSize = 256 * 1024 // 256KB per gRPC chunk// AgentClient is the host-side gRPC client that connects to the-// osb-agent running inside a QEMU VM via AF_VSOCK.+// osb-agent running inside a QEMU VM via AF_VSOCK or virtio-serial.+//+// dialer captures the constructor's dial logic so Redial can rebuild the+// connection without the caller knowing whether this is vsock or virtio-+// serial transport. This is the recovery path for the post-loadvm protocol-+// confusion bug and the prod 10-min-after-restore agent disconnect: when an+// RPC fails with a transport error, the caller invokes Redial and retries.type AgentClient struct {+ mu sync.Mutexconn *grpc.ClientConnclient pb.SandboxAgentClient+ dialer func() (*grpc.ClientConn, error)}// NewAgentClient connects to the agent via AF_VSOCK using the guest CID.// QEMU uses the kernel's vhost-vsock directly — no UDS file needed.// Port 1024 is the agent gRPC server inside the VM.func NewAgentClient(guestCID uint32) (*AgentClient, error) {- ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)- defer cancel()-- conn, err := grpc.DialContext(ctx,- "passthrough:///vsock",- grpc.WithTransportCredentials(insecure.NewCredentials()),- grpc.WithBlock(),- grpc.WithConnectParams(grpc.ConnectParams{- Backoff: backoff.Config{- BaseDelay: 10 * time.Millisecond,- Multiplier: 1.6,- Jitter: 0.2,- MaxDelay: 1 * time.Second,- },- }),- grpc.WithKeepaliveParams(keepalive.ClientParameters{- Time: 30 * time.Second,- Timeout: 10 * time.Second,- PermitWithoutStream: true,- }),- grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) {- return dialVsock(ctx, guestCID, 1024)- }),- grpc.WithDefaultCallOptions(- grpc.MaxCallRecvMsgSize(256*1024*1024),- grpc.MaxCallSendMsgSize(256*1024*1024),- ),- )+ dialer := func() (*grpc.ClientConn, error) {+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()+ return grpc.DialContext(ctx,+ "passthrough:///vsock",+ grpc.WithTransportCredentials(insecure.NewCredentials()),+ grpc.WithBlock(),+ grpc.WithConnectParams(grpc.ConnectParams{+ Backoff: backoff.Config{+ BaseDelay: 10 * time.Millisecond,+ Multiplier: 1.6,+ Jitter: 0.2,+ MaxDelay: 1 * time.Second,+ },+ }),+ grpc.WithKeepaliveParams(keepalive.ClientParameters{+ Time: 30 * time.Second,+ Timeout: 10 * time.Second,+ PermitWithoutStream: true,+ }),+ grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) {+ return dialVsock(ctx, guestCID, 1024)+ }),+ grpc.WithDefaultCallOptions(+ grpc.MaxCallRecvMsgSize(256*1024*1024),+ grpc.MaxCallSendMsgSize(256*1024*1024),+ ),+ )+ }+ conn, err := dialer()if err != nil {return nil, fmt.Errorf("connect to agent at CID %d: %w", guestCID, err)}-return &AgentClient{conn: conn,client: pb.NewSandboxAgentClient(conn),+ dialer: dialer,}, nil}@@ -180,6 +195,18 @@ func (c *AgentClient) SetEnvs(ctx context.Context, envs map[string]string) errorreturn err}+// ConfigureLogship hands the in-VM agent its log-shipping configuration.+// Empty ingestToken is a no-op on the agent side (kill-switch).+func (c *AgentClient) ConfigureLogship(ctx context.Context, ingestToken, dataset, sandboxID, orgID string) error {+ _, err := c.client.ConfigureLogship(ctx, &pb.ConfigureLogshipRequest{+ IngestToken: ingestToken,+ Dataset: dataset,+ SandboxId: sandboxID,+ OrgId: orgID,+ })+ return err+}+// Ping verifies the agent is responsive.func (c *AgentClient) Ping(ctx context.Context) (*pb.PingResponse, error) {return c.client.Ping(ctx, &pb.PingRequest{})@@ -479,37 +506,89 @@ func (c *AgentClient) ConnectPTYData(guestCID uint32, dataPort uint32) (net.Conn// NewAgentClientSocket connects to the agent via a Unix socket (virtio-serial chardev).// Used by QEMU backend — virtio-serial survives QEMU live migration.func NewAgentClientSocket(socketPath string) (*AgentClient, error) {- ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)- defer cancel()-- conn, err := grpc.DialContext(ctx,- "unix://"+socketPath,- grpc.WithTransportCredentials(insecure.NewCredentials()),- grpc.WithBlock(),- grpc.WithConnectParams(grpc.ConnectParams{- Backoff: backoff.Config{- BaseDelay: 10 * time.Millisecond,- Multiplier: 1.6,- Jitter: 0.2,- MaxDelay: 1 * time.Second,- },- }),- grpc.WithKeepaliveParams(keepalive.ClientParameters{- Time: 30 * time.Second,- Timeout: 10 * time.Second,- PermitWithoutStream: true,- }),- grpc.WithDefaultCallOptions(- grpc.MaxCallRecvMsgSize(256*1024*1024),- grpc.MaxCallSendMsgSize(256*1024*1024),- ),- )+ dialer := func() (*grpc.ClientConn, error) {+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()+ return grpc.DialContext(ctx,+ "unix://"+socketPath,+ grpc.WithTransportCredentials(insecure.NewCredentials()),+ grpc.WithBlock(),+ grpc.WithConnectParams(grpc.ConnectParams{+ Backoff: backoff.Config{+ BaseDelay: 10 * time.Millisecond,+ Multiplier: 1.6,+ Jitter: 0.2,+ MaxDelay: 1 * time.Second,+ },+ }),+ grpc.WithKeepaliveParams(keepalive.ClientParameters{+ Time: 30 * time.Second,+ Timeout: 10 * time.Second,+ PermitWithoutStream: true,+ }),+ grpc.WithDefaultCallOptions(+ grpc.MaxCallRecvMsgSize(256*1024*1024),+ grpc.MaxCallSendMsgSize(256*1024*1024),+ ),+ )+ }+ conn, err := dialer()if err != nil {return nil, fmt.Errorf("connect to agent at %s: %w", socketPath, err)}-return &AgentClient{conn: conn,client: pb.NewSandboxAgentClient(conn),+ dialer: dialer,}, nil}++// Redial closes the current gRPC conn and dials a new one using the dialer+// captured at construction. Safe under concurrent callers — only one+// redial happens at a time, others wait and reuse the result.+//+// Use this when an RPC fails with a transport error (Unavailable, EOF,+// closed network connection). After Redial, retry the RPC on the fresh+// conn. If the agent inside the VM is fundamentally wedged this won't+// help — but for the common "stale conn after savevm/loadvm" or+// "control channel dropped at idle" case it recovers transparently.+func (c *AgentClient) Redial() error {+ c.mu.Lock()+ defer c.mu.Unlock()+ if c.dialer == nil {+ return fmt.Errorf("AgentClient has no dialer (already closed?)")+ }+ if c.conn != nil {+ _ = c.conn.Close()+ }+ conn, err := c.dialer()+ if err != nil {+ return fmt.Errorf("redial agent: %w", err)+ }+ c.conn = conn+ c.client = pb.NewSandboxAgentClient(conn)+ log.Printf("agent-client: redial succeeded")+ return nil+}++// IsTransportError returns true if err looks like a gRPC transport-level+// failure that a Redial+retry would plausibly fix. Distinguished from+// application errors (NotFound, InvalidArgument, etc.) which are caller+// problems and shouldn't trigger reconnect storms.+func IsTransportError(err error) bool {+ if err == nil {+ return false+ }+ if st, ok := status.FromError(err); ok {+ switch st.Code() {+ case codes.Unavailable, codes.DeadlineExceeded, codes.Canceled:+ return true+ }+ }+ msg := err.Error()+ return strings.Contains(msg, "use of closed network connection") ||+ strings.Contains(msg, "EOF") ||+ strings.Contains(msg, "broken pipe") ||+ strings.Contains(msg, "connection reset") ||+ strings.Contains(msg, "transport is closing")+}diff --git a/internal/qemu/checkpoint_memextract.go b/internal/qemu/checkpoint_memextract.godeleted file mode 100644index a3ac8b4a..00000000--- a/internal/qemu/checkpoint_memextract.go+++ /dev/null@@ -1,157 +0,0 @@-package qemu--import (- "context"- "fmt"- "log"- "os"- "os/exec"- "path/filepath"- "time"-)--// extractCheckpointMemory converts a savevm-based checkpoint (memory embedded-// in qcow2 as an internal snapshot) into an external mem.zst + plain qcow2-// drives without internal snapshots. Fork restore paths already prefer the-// external-memory format (see ForkFromCheckpoint restore-mode logic) and-// qemu-img rebase composes cleanly with plain overlays — so cross-golden-// forks work correctly after this runs.-//-// The function is destructive on stagingDir: it may delete the internal-// snapshot from the qcow2 files and create mem.zst. Callers should invoke it-// on a staging directory that has been reflinked from the live VM, not on-// live drives.-//-// Runs out-of-band in the async upload goroutine so user-visible save-// latency is unchanged. On failure, the staging directory is left in its-// savevm-only state — fork restore falls back to loadvm, which still works-// for same-golden forks.-func (m *Manager) extractCheckpointMemory(ctx context.Context, stagingDir, snapshotName, guestMAC string, memMB, cpuCount int) error {- rootfs := filepath.Join(stagingDir, "rootfs.qcow2")- workspace := filepath.Join(stagingDir, "workspace.qcow2")- if !fileExists(rootfs) || !fileExists(workspace) {- return fmt.Errorf("qcow2 drives missing in %s", stagingDir)- }-- memFile := filepath.Join(stagingDir, "mem")- // Linux UNIX socket paths max 108 bytes. Staging dir- // (/data/sandboxes/checkpoint-snapshots/<uuid>.staging/...) is already- // over the limit with a reasonable filename, so put the throwaway- // sockets in /tmp.- shortID := fmt.Sprintf("osb-ex-%d", time.Now().UnixNano())- qmpSock := filepath.Join("/tmp", shortID+".qmp")- agentSock := filepath.Join("/tmp", shortID+".ag")- logFile := filepath.Join(stagingDir, "extract-qemu.log")- os.Remove(memFile)- os.Remove(qmpSock)- os.Remove(agentSock)-- // loadvm requires the runtime device layout to match what savevm recorded- // byte-for-byte (device IDs, order, -serial stdio, even virtio-mem pool- // size). Reuse buildQEMUArgs — same function the live VM was started with- // — plus -S and -loadvm to hold the restored state paused so we can- // migrate the memory out of it.- //- // A temporary TAP is allocated because the virtio-net device in the- // savevm stream expects a netdev backend, and "-netdev user" is a- // different backend type that QEMU rejects during loadvm.- netCfg, err := m.subnets.Allocate()- if err != nil {- return fmt.Errorf("allocate tap: %w", err)- }- if err := CreateTAP(netCfg); err != nil {- m.subnets.Release(netCfg.TAPName)- return fmt.Errorf("create tap: %w", err)- }- defer func() {- DeleteTAP(netCfg.TAPName)- m.subnets.Release(netCfg.TAPName)- }()-- // bootArgs don't matter for loadvm — the guest doesn't actually boot,- // we only load the snapshot's memory+device state and migrate out.- args := m.buildQEMUArgs(cpuCount, memMB, rootfs, workspace, netCfg.TAPName, guestMAC, agentSock, qmpSock, "")- args = append(args, "-S", "-loadvm", snapshotName)-- logf, err := os.Create(logFile)- if err != nil {- return fmt.Errorf("create extract log: %w", err)- }- defer logf.Close()-- cmd := exec.CommandContext(ctx, m.cfg.QEMUBin, args...)- cmd.Stdout = logf- cmd.Stderr = logf- if err := cmd.Start(); err != nil {- return fmt.Errorf("start extract qemu: %w", err)- }-- killQEMU := func() {- if cmd.Process != nil {- _ = cmd.Process.Kill()- cmd.Wait()- }- }-- qmp, err := waitForQMP(qmpSock, 30*time.Second)- if err != nil {- killQEMU()- return fmt.Errorf("extract qmp connect: %w", err)- }-- // Migrate memory+device state to an external file. VM stays paused (-S)- // the whole time; migrate tolerates that.- if err := qmp.Migrate(fmt.Sprintf("exec:cat > %s", memFile)); err != nil {- qmp.Close()- killQEMU()- return fmt.Errorf("extract migrate: %w", err)- }- if err := qmp.WaitMigration(5 * time.Minute); err != nil {- qmp.Close()- killQEMU()- return fmt.Errorf("extract migrate wait: %w", err)- }-- _ = qmp.Quit()- qmp.Close()-- done := make(chan error, 1)- go func() { done <- cmd.Wait() }()- select {- case <-done:- case <-time.After(10 * time.Second):- killQEMU()- }- os.Remove(qmpSock)- os.Remove(agentSock)-- // Compress memory file with zstd -3 (same level golden uses). -3 on an- // uncompressed VM memory dump typically achieves 3-5x reduction at- // ~500MB/s on a single core.- memZst := memFile + ".zst"- zstdOut, zstdErr := exec.Command("zstd", "-3", "--rm", memFile, "-o", memZst).CombinedOutput()- if zstdErr != nil {- os.Remove(memFile)- os.Remove(memZst)- return fmt.Errorf("zstd compress mem: %w (%s)", zstdErr, string(zstdOut))- }-- // Strip the internal savevm snapshot from the qcow2 drives. After this,- // the overlays are plain qcow2 files with only their backing-file- // reference — qemu-img rebase operates on them correctly, and fork- // restore uses the external mem.zst instead of loadvm.- for _, f := range []string{rootfs, workspace} {- if out, derr := exec.Command("qemu-img", "snapshot", "-d", snapshotName, f).CombinedOutput(); derr != nil {- // Workspace may not actually carry the snapshot entry (savevm stores- // VMSTATE in only one drive); a "snapshot not found" error here is- // benign. Log and continue.- log.Printf("qemu: extractCheckpointMemory: snapshot -d %s on %s: %v (%s)", snapshotName, f, derr, string(out))- }- }-- // Remove the snapshot-name file — restore logic only uses it when an- // external mem file is absent, and we've now guaranteed one is present.- // Leave it in place for backward compat: old worker binaries that predate- // this code only understand the loadvm path and would break without it.- return nil-}diff --git a/internal/qemu/checkpoint_rebase.go b/internal/qemu/checkpoint_rebase.goindex 017e777d..50ee260e 100644--- a/internal/qemu/checkpoint_rebase.go+++ b/internal/qemu/checkpoint_rebase.go@@ -3,6 +3,7 @@ package qemuimport ("context""encoding/json"+ "errors""fmt""io""log"@@ -12,6 +13,8 @@ import ("strings""sync""time"++ "github.com/opensandbox/opensandbox/internal/storage")// Pin-to-base: checkpoints stay tied to the exact goldenVersion they were@@ -101,6 +104,12 @@ func (m *Manager) resolveBaseForVersion(ctx context.Context, goldenVersion strin// downloadBaseToLocal fetches bases/{goldenVersion}/default.ext4 from blob// storage. Concurrent callers share one download through an in-flight map.+//+// Cleans up the destination directory if download fails — otherwise an empty+// bases/<ver>/ would be left behind, indistinguishable from a partial state+// on the next attempt. Retries a small number of times on ErrNotFound to+// tolerate the brief window between a peer worker calling+// UploadBaseImageIfNew and the blob becoming visible to the downloader.func (m *Manager) downloadBaseToLocal(ctx context.Context, goldenVersion, destPath string) error {flightMu.Lock()if ch, downloading := downloadFlight[goldenVersion]; downloading {@@ -128,21 +137,33 @@ func (m *Manager) downloadBaseToLocal(ctx context.Context, goldenVersion, destPaif fileExists(destPath) {return nil}- if err := os.MkdirAll(filepath.Dir(destPath), 0755); err != nil {+ dir := filepath.Dir(destPath)+ if err := os.MkdirAll(dir, 0755); err != nil {return fmt.Errorf("mkdir base cache: %w", err)}+ // On failure, clean up the empty dir so subsequent resolves don't see a+ // stub directory that masks the missing base.+ cleanupOnFail := true+ defer func() {+ if !cleanupOnFail {+ return+ }+ if entries, err := os.ReadDir(dir); err == nil && len(entries) == 0 {+ os.Remove(dir)+ }+ }()log.Printf("qemu: downloading base %s from blob storage", goldenVersion)t0 := time.Now()key := fmt.Sprintf("bases/%s/default.ext4", goldenVersion)- reader, err := m.checkpointStore.Download(ctx, key)+ reader, err := m.openBaseReaderWithRetry(ctx, key)if err != nil {return fmt.Errorf("download %s: %w", key, err)}defer reader.Close()- tmpFile, err := os.CreateTemp(filepath.Dir(destPath), "default-dl-*.ext4")+ tmpFile, err := os.CreateTemp(dir, "default-dl-*.ext4")if err != nil {return fmt.Errorf("create temp file: %w", err)}@@ -162,10 +183,40 @@ func (m *Manager) downloadBaseToLocal(ctx context.Context, goldenVersion, destPareturn fmt.Errorf("rename: %w", err)}+ cleanupOnFail = falselog.Printf("qemu: base %s cached at %s (%dms)", goldenVersion, destPath, time.Since(t0).Milliseconds())return nil}+// openBaseReaderWithRetry retries Download on ErrNotFound with exponential+// backoff (250ms → 500ms → 1s → 2s → 4s, ~8s total). The retry exists for+// the race where a peer worker that just took a checkpoint is still+// uploading its base via UploadBaseImageIfNew. Other errors fail fast.+func (m *Manager) openBaseReaderWithRetry(ctx context.Context, key string) (io.ReadCloser, error) {+ var lastErr error+ delay := 250 * time.Millisecond+ for attempt := 0; attempt < 5; attempt++ {+ if attempt > 0 {+ select {+ case <-ctx.Done():+ return nil, ctx.Err()+ case <-time.After(delay):+ delay *= 2+ }+ }+ reader, err := m.checkpointStore.Download(ctx, key)+ if err == nil {+ return reader, nil+ }+ if !errors.Is(err, storage.ErrNotFound) && !strings.Contains(err.Error(), "object not found") {+ return nil, err+ }+ lastErr = err+ log.Printf("qemu: base download for %s: not found yet (attempt %d), retrying", key, attempt+1)+ }+ return nil, lastErr+}+var (flightMu sync.MutexdownloadFlight = map[string]chan struct{}{}diff --git a/internal/qemu/checkpoint_rebase_test.go b/internal/qemu/checkpoint_rebase_test.goindex ff0212d8..b62ae52b 100644--- a/internal/qemu/checkpoint_rebase_test.go+++ b/internal/qemu/checkpoint_rebase_test.go@@ -4,7 +4,6 @@ import ("bytes""context""encoding/json"- "fmt""io""os""path/filepath"@@ -13,11 +12,12 @@ import ("testing""time"+ "github.com/opensandbox/opensandbox/internal/blobstore""github.com/opensandbox/opensandbox/internal/storage")// ----------------------------------------------------------------------------// Mock blob client — in-memory store for testing without real S3/Azure+// Mock Store — in-memory blobstore.Store for testing without real S3/Azure.// ---------------------------------------------------------------------------type mockBlobClient struct {@@ -30,7 +30,9 @@ func newMockBlobClient() *mockBlobClient {return &mockBlobClient{objects: make(map[string][]byte)}}-func (m *mockBlobClient) Upload(_ context.Context, bucket, key string, body io.ReadSeeker, _ int64) error {+func (m *mockBlobClient) Name() string { return "mock" }++func (m *mockBlobClient) Put(_ context.Context, bucket, key string, body io.Reader, _ int64) error {data, err := io.ReadAll(body)if err != nil {return err@@ -41,22 +43,22 @@ func (m *mockBlobClient) Upload(_ context.Context, bucket, key string, body io.Rreturn nil}-func (m *mockBlobClient) Download(_ context.Context, bucket, key string) (io.ReadCloser, error) {+func (m *mockBlobClient) Get(_ context.Context, bucket, key string) (io.ReadCloser, error) {m.mu.Lock()data, ok := m.objects[bucket+"/"+key]m.mu.Unlock()if !ok {- return nil, fmt.Errorf("not found: %s/%s", bucket, key)+ return nil, blobstore.ErrNotFound}return io.NopCloser(bytes.NewReader(data)), nil}-func (m *mockBlobClient) DownloadRange(_ context.Context, bucket, key string, offset, length int64) (io.ReadCloser, error) {+func (m *mockBlobClient) GetRange(_ context.Context, bucket, key string, offset, length int64) (io.ReadCloser, error) {m.mu.Lock()data, ok := m.objects[bucket+"/"+key]m.mu.Unlock()if !ok {- return nil, fmt.Errorf("not found: %s/%s", bucket, key)+ return nil, blobstore.ErrNotFound}end := offset + lengthif end > int64(len(data)) {@@ -71,11 +73,18 @@ func (m *mockBlobClient) Head(_ context.Context, bucket, key string) (int64, errdata, ok := m.objects[bucket+"/"+key]m.mu.Unlock()if !ok {- return 0, fmt.Errorf("not found: %s/%s", bucket, key)+ return 0, blobstore.ErrNotFound}return int64(len(data)), nil}+func (m *mockBlobClient) Exists(_ context.Context, bucket, key string) (bool, error) {+ m.mu.Lock()+ _, ok := m.objects[bucket+"/"+key]+ m.mu.Unlock()+ return ok, nil+}+func (m *mockBlobClient) Delete(_ context.Context, bucket, key string) error {m.mu.Lock()delete(m.objects, bucket+"/"+key)@@ -83,8 +92,6 @@ func (m *mockBlobClient) Delete(_ context.Context, bucket, key string) error {return nil}-func (m *mockBlobClient) BackendName() string { return "mock" }-func (m *mockBlobClient) put(bucket, key string, data []byte) {m.mu.Lock()m.objects[bucket+"/"+key] = data@@ -111,7 +118,7 @@ func testManager(t *testing.T, goldenVersion string) (mgr *Manager, store *stora}mock = newMockBlobClient()- store = storage.NewCheckpointStoreFromClient(mock, "checkpoints")+ store = storage.NewCheckpointStoreFromStore(mock, "checkpoints")mgr = &Manager{cfg: Config{diff --git a/internal/qemu/docs_compliance_test.go b/internal/qemu/docs_compliance_test.goindex 12e5f62f..cacaf3e6 100644--- a/internal/qemu/docs_compliance_test.go+++ b/internal/qemu/docs_compliance_test.go@@ -398,7 +398,7 @@ var (_ func(context.Context, string, string) ([]types.EntryInfo, error) = (*Manager)(nil).ListDir_ func(context.Context, string, *storage.CheckpointStore) (*sandbox.HibernateResult, error) = (*Manager)(nil).Hibernate_ func(context.Context, string, string, *storage.CheckpointStore, int) (*types.Sandbox, error) = (*Manager)(nil).Wake- _ func(context.Context, string, string, *storage.CheckpointStore, func()) (string, string, error) = (*Manager)(nil).CreateCheckpoint+ _ func(context.Context, string, string, *storage.CheckpointStore, func()) (string, string, int64, error) = (*Manager)(nil).CreateCheckpoint_ func(context.Context, string, string) error = (*Manager)(nil).RestoreFromCheckpoint_ func(context.Context, string, types.SandboxConfig) (*types.Sandbox, error) = (*Manager)(nil).ForkFromCheckpoint)diff --git a/internal/qemu/manager.go b/internal/qemu/manager.goindex 4d68b7cf..45e1f564 100644--- a/internal/qemu/manager.go+++ b/internal/qemu/manager.go@@ -21,6 +21,7 @@ import ("github.com/google/uuid""github.com/opensandbox/opensandbox/internal/blobstore"+ "github.com/opensandbox/opensandbox/internal/metrics""github.com/opensandbox/opensandbox/internal/sandbox""github.com/opensandbox/opensandbox/internal/storage""github.com/opensandbox/opensandbox/pkg/types"@@ -29,34 +30,152 @@ import ("google.golang.org/grpc/status")+// ErrAgentUnresponsive is returned by quiesceAndCloseAgent when the in-VM agent+// is unreachable. Callers must not proceed to savevm when this fires: capturing+// a snapshot of a guest with un-synced page cache and pending EXT4 journal+// entries produces a qcow2 that won't mount on next cold-boot (inode #2+// metadata-checksum failure → kernel panic loop). Surface a clean error to the+// API caller instead of silently corrupting the rootfs.+var ErrAgentUnresponsive = fmt.Errorf("guest agent unresponsive, refusing to capture potentially-inconsistent snapshot")++// ErrRootfsCritical is returned when the guest's rootfs (/dev/vda) is so full+// that destructive operations could leave it in a corrupted state. dpkg/apt+// mid-rename of system files plus an ENOSPC trip plus a savevm is the path+// that causes EXT4 metadata checksum failure on next cold-mount. Refuse the+// op early; let the caller / customer free space first.+var ErrRootfsCritical = fmt.Errorf("rootfs disk usage too high — refusing destructive operation to prevent corruption")++const (+ // rootfsRefuseThresholdPct: above this, refuse destructive operations.+ rootfsRefuseThresholdPct = 95+ // rootfsWarnThresholdPct: above this, log a warning on the next destructive+ // op so the customer sees it surface in their logs / our telemetry.+ rootfsWarnThresholdPct = 85+)+// prepareAgentForHibernate synchronously syncs the guest filesystems and quiesces-// the virtio-serial listener. Returns when the guest is fully prepared — no sleep-// needed afterward.+// the virtio-serial listener. Returns nil when the guest is fully prepared — no+// sleep needed afterward.//-// On agents that don't implement the PrepareHibernate RPC (older builds), falls-// back to the legacy Exec("sync; kill -USR1 1") path with a 1s sleep.-func prepareAgentForHibernate(ctx context.Context, agent *AgentClient) {+// On transport-class errors (Unavailable, Canceled, EOF, "client connection is+// closing") the RPC is retried once after a Redial — matching the pattern used+// by SyncFS / Exec / patchGuestNetwork elsewhere in this file. This handles+// the common transient where the gRPC channel is mid-recycle (e.g. right after+// a heavy Exec just completed). Only after redial+retry also fails do we+// surface ErrAgentUnresponsive.+//+// An Unimplemented response from PrepareHibernate (older agent builds) is not+// itself a failure — the legacy Exec("sync; kill -USR1 1") fallback is what+// counts. ErrAgentUnresponsive (wrapped) is returned only when neither the+// modern path nor the fallback succeeds, even after redial.+func prepareAgentForHibernate(ctx context.Context, agent *AgentClient) error {if agent == nil {- return+ return nil+ }++ prepareOnce := func() error {+ rpcCtx, cancel := context.WithTimeout(ctx, 10*time.Second)+ defer cancel()+ _, err := agent.PrepareHibernate(rpcCtx, &pb.PrepareHibernateRequest{})+ return err+ }+ err := prepareOnce()+ if err != nil && IsTransportError(err) {+ log.Printf("qemu: PrepareHibernate transport error (%v), redialing", err)+ if rdErr := agent.Redial(); rdErr == nil {+ err = prepareOnce()+ } else {+ log.Printf("qemu: PrepareHibernate redial failed: %v (orig: %v)", rdErr, err)+ }}- rpcCtx, cancel := context.WithTimeout(ctx, 10*time.Second)- defer cancel()- _, err := agent.PrepareHibernate(rpcCtx, &pb.PrepareHibernateRequest{})if err == nil {- return+ return nil}+if st, ok := status.FromError(err); !ok || st.Code() != codes.Unimplemented {log.Printf("qemu: PrepareHibernate RPC failed: %v (falling back to legacy path)", err)}- // Fallback for older agents: sync + SIGUSR1 + sleep.- execCtx, cancel2 := context.WithTimeout(ctx, 10*time.Second)- defer cancel2()- _, _ = agent.Exec(execCtx, &pb.ExecRequest{- Command: "/bin/sh",- Args: []string{"-c", "sync; blockdev --flushbufs /dev/vda 2>/dev/null; blockdev --flushbufs /dev/vdb 2>/dev/null; sync; kill -USR1 1"},- RunAsRoot: true,- })++ execOnce := func() error {+ execCtx, cancel := context.WithTimeout(ctx, 10*time.Second)+ defer cancel()+ _, e := agent.Exec(execCtx, &pb.ExecRequest{+ Command: "/bin/sh",+ Args: []string{"-c", "sync; blockdev --flushbufs /dev/vda 2>/dev/null; blockdev --flushbufs /dev/vdb 2>/dev/null; sync; kill -USR1 1"},+ RunAsRoot: true,+ })+ return e+ }+ fallbackErr := execOnce()+ if fallbackErr != nil && IsTransportError(fallbackErr) {+ log.Printf("qemu: prepareHibernate fallback Exec transport error (%v), redialing", fallbackErr)+ if rdErr := agent.Redial(); rdErr == nil {+ fallbackErr = execOnce()+ } else {+ log.Printf("qemu: prepareHibernate fallback redial failed: %v", rdErr)+ }+ }+ if fallbackErr != nil {+ return fmt.Errorf("%w: PrepareHibernate=%v, fallback Exec=%v", ErrAgentUnresponsive, err, fallbackErr)+ }time.Sleep(1 * time.Second)+ return nil+}++// checkRootfsPressure polls the in-guest agent for filesystem usage and+// returns ErrRootfsCritical if rootfs use% is at or above the refuse threshold.+// Best-effort: returns nil on agent unreachable / older agent that doesn't+// fill the new fields (RootfsTotalBytes==0). In those cases the caller falls+// back to the pre-existing behavior — backward compatible for long-lived+// sandboxes whose in-guest agent predates this change.+//+// Logs a warning when use% crosses rootfsWarnThresholdPct so customers see+// the early signal in their logs even when the op is allowed to proceed.+func (m *Manager) checkRootfsPressure(ctx context.Context, vm *VMInstance) error {+ if vm == nil || vm.agent == nil {+ return nil+ }+ statsCtx, cancel := context.WithTimeout(ctx, 5*time.Second)+ defer cancel()+ resp, err := vm.agent.Stats(statsCtx)+ if err != nil || resp == nil || resp.RootfsTotalBytes == 0 {+ return nil+ }+ pct := int(resp.RootfsUsedBytes * 100 / resp.RootfsTotalBytes)+ if pct >= rootfsRefuseThresholdPct {+ return fmt.Errorf("%w: rootfs at %d%% (refuse threshold %d%%) — free space and retry, or kill and respawn from a checkpoint", ErrRootfsCritical, pct, rootfsRefuseThresholdPct)+ }+ if pct >= rootfsWarnThresholdPct {+ log.Printf("qemu: %s: rootfs at %d%% — destructive operations will be refused at %d%%", vm.ID, pct, rootfsRefuseThresholdPct)+ }+ return nil+}++// quiesceAndCloseAgent prepares the agent for hibernate, closes the host-side+// gRPC client connection, and waits 200ms for the guest's gRPC server to+// process the EOF and re-enter its Accept poll loop. After this returns nil it+// is safe for the caller to call savevm — the captured snapshot will not have+// a stale virtioSerialConn whose buffered HTTP/2 framer state could corrupt the+// next host's gRPC handshake on fork/restore, AND the guest filesystem state is+// known-quiesced.+//+// The 200ms is empirically sufficient for the guest virtio-serial driver to+// surface EOF on /dev/virtio-ports/agent → for the gRPC server's Read goroutine+// to drop its conn → for onClose to run (active=false). Without this wait the+// snapshot can land mid-tear-down and the bug returns.+//+// Returns ErrAgentUnresponsive (wrapped) when the agent cannot be reached for+// the prep step. Callers must abort their savevm path on this error.+func quiesceAndCloseAgent(ctx context.Context, agent *AgentClient) error {+ if agent == nil {+ return nil+ }+ if err := prepareAgentForHibernate(ctx, agent); err != nil {+ return err+ }+ _ = agent.Close()+ time.Sleep(200 * time.Millisecond)+ return nil}// Compile-time check that Manager implements sandbox.Manager.@@ -92,6 +211,7 @@ type VMInstance struct {restoring chan struct{}opMu sync.Mutex // serializes destructive VM ops (checkpoint, restore, hibernate)archiveDone chan struct{} // closed when async hibernate archive completes (nil if no archive in flight)+ memoryReady chan struct{} // closed once virtio-mem hotplug has committed enough memory for user workloads (nil = pre-existing hotplug, treat as ready)baseMemoryMB int // initial memory passed to -m (before virtio-mem)virtioMemRequestedMB int // additional memory via virtio-mem (beyond base)goldenVersion string // golden version this sandbox was created from (empty if cold-booted)@@ -124,7 +244,16 @@ type SecretsProxyIntegration interface {// GetSessionTokenHosts returns the per-token host restrictions for persisting during hibernate.GetSessionTokenHosts(guestIP string) map[string][]string// ReregisterSession re-creates a proxy session from a persisted token map (used on wake).- ReregisterSession(sandboxID, guestIP string, tokens map[string]string, allowlist []string, tokenHosts map[string][]string)+ // names is the env-var-name → sealed-token index needed for refresh-by-name+ // (UpdateSecretValue) to keep working after a wake/migration.+ ReregisterSession(sandboxID, guestIP string, tokens map[string]string, allowlist []string, tokenHosts map[string][]string, names map[string]string)+ // GetSessionNames returns the env-var-name → sealed-token map; persisted alongside+ // SealedTokens so refresh-by-name survives a handoff.+ GetSessionNames(guestIP string) map[string]string+ // UpdateSecretValue replaces the value the sealed token for secretName resolves+ // to, on the session for the given sandbox. Sealed token unchanged; the+ // next outbound HTTPS substitutes the new value. Returns true on success.+ UpdateSecretValue(sandboxID, secretName, newValue string) bool// CACertPEM returns the CA certificate PEM for injection into the VM trust store.CACertPEM() []byte}@@ -137,6 +266,7 @@ type Config struct {QEMUBin string // path to qemu-system-x86_64 binaryAgentBinaryPath string // path to osb-agent binary on host (for hot-upgrade)AgentVersion string // expected agent version (for hot-upgrade check)+ Region string // worker region (e.g. eastus2); used as a metric labelDefaultMemoryMB intDefaultCPUs intDefaultDiskMB int@@ -178,8 +308,19 @@ type Manager struct {onSandboxReady func(sandboxID, guestIP, template string, startedAt time.Time)onSandboxDestroy func(sandboxID string)+ // Hibernation upload status callback (set via SetHibernationUploadCallback).+ // Invoked from the async archive+upload goroutine in doHibernate exactly once+ // per hibernation, with err=nil on success or non-nil on archive/upload+ // failure. The worker uses this to write uploaded_at / upload_error in the+ // sandbox_hibernations row so missing-blob failures stop being silent.+ onHibernationUpload func(sandboxID, hibernationKey string, sizeBytes int64, uploadErr error)+secretsProxy SecretsProxyIntegration // nil if secrets proxy is not configuredcheckpointStore *storage.CheckpointStore // for base image archival + checkpoint rebasing (nil until set)++ // Per-sandbox stats cache populated by a background collector and read by+ // the heartbeat path. See stats_collector.go.+ statsCache *SandboxStatsCache}// NewManager creates a new QEMU-backed sandbox manager.@@ -263,12 +404,53 @@ func (m *Manager) SetCheckpointStore(cs *storage.CheckpointStore) {m.checkpointStore = cs}+// SetHibernationUploadCallback registers a callback invoked from the async+// hibernation archive+upload goroutine when it finishes. err is nil on+// success; sizeBytes is the archive size (only meaningful on success). The+// worker uses this to update sandbox_hibernations.uploaded_at / upload_error+// so silent upload failures become visible.+func (m *Manager) SetHibernationUploadCallback(cb func(sandboxID, hibernationKey string, sizeBytes int64, uploadErr error)) {+ m.onHibernationUpload = cb+}+// GoldenVersion returns the hash identifying this worker's golden snapshot base image.// Empty string means no golden snapshot is available.func (m *Manager) GoldenVersion() string {return m.goldenVersion}+// MemoryAllocatedBytes returns the sum of memory committed to currently-running+// sandboxes, in bytes. Used by the worker's resource-stats tick to report+// oversubscription independent of actual guest workload.+func (m *Manager) MemoryAllocatedBytes() uint64 {+ m.mu.RLock()+ defer m.mu.RUnlock()+ var total uint64+ for _, vm := range m.vms {+ if vm == nil {+ continue+ }+ total += uint64(vm.MemoryMB) * 1024 * 1024+ }+ return total+}++// ActiveSandboxesByTemplate returns the count of currently-running sandboxes+// grouped by template. Drives the opensandbox_sandboxes_active gauge from+// the worker's resource-stats tick.+func (m *Manager) ActiveSandboxesByTemplate() map[string]int {+ m.mu.RLock()+ defer m.mu.RUnlock()+ counts := make(map[string]int)+ for _, vm := range m.vms {+ if vm == nil {+ continue+ }+ counts[vm.Template]+++ }+ return counts+}+// sealSandboxEnvs runs cfg.Envs through the secrets proxy to swap real values// for sealed tokens, registers a proxy session for the guest IP, and writes the// proxy CA cert into the guest trust store. Returns the env map that should be@@ -288,7 +470,7 @@ func (m *Manager) sealSandboxEnvs(ctx context.Context, sandboxID string, netCfg}return merged}- if len(cfg.Envs) == 0 && len(cfg.SecretEnvs) == 0 {+ if len(cfg.Envs) == 0 && len(cfg.SecretEnvs) == 0 && len(cfg.EgressAllowlist) == 0 {return cfg.Envs}sealed := m.secretsProxy.CreateSealedEnvs(sandboxID, netCfg.GuestIP, netCfg.HostIP, cfg.Envs, cfg.SecretEnvs, cfg.EgressAllowlist, cfg.SecretAllowedHosts)@@ -305,6 +487,75 @@ func (m *Manager) sealSandboxEnvs(ctx context.Context, sandboxID string, netCfgreturn sealed}+// reinstallProxyCA overwrites the proxy CA cert in the guest's trust store+// with the destination worker's current CA. Called from any handoff path+// where the sandbox can land on a different worker than it was created on:+// live migration, hibernate→wake (cross-worker), checkpoint fork.+//+// The guest's env vars (SSL_CERT_FILE / REQUESTS_CA_BUNDLE / NODE_EXTRA_CA_CERTS)+// point at the fixed path the proxy injected at sandbox creation, so we+// only need to overwrite the file content; no update-ca-certificates run+// is required because the consuming libraries read the file directly.+//+// Idempotent: in steady state where every worker shares the same CA via KV,+// the destination's CA equals the source's and this is a no-op write. The+// value is in the transition window (sandboxes created before shared-CA+// rollout) and any future "the destination's CA differs" scenario (cross-+// cell migration, planned CA rotation, etc.).+//+// Best-effort — errors are logged but don't fail the handoff. A migration+// that successfully moves the workload but fails to refresh the cert is+// strictly better than refusing the migration.+func (m *Manager) reinstallProxyCA(ctx context.Context, sandboxID string, agent *AgentClient) {+ if m.secretsProxy == nil || agent == nil {+ return+ }+ certPEM := m.secretsProxy.CACertPEM()+ if len(certPEM) == 0 {+ return+ }+ writeCtx, cancel := context.WithTimeout(ctx, 5*time.Second)+ defer cancel()+ if err := agent.WriteFile(writeCtx, "/usr/local/share/ca-certificates/opensandbox-proxy.crt", certPEM); err != nil {+ log.Printf("qemu: %s: reinstall proxy CA failed: %v (sandbox is alive but TLS substitution may break until next handoff)", sandboxID, err)+ return+ }+ log.Printf("qemu: %s: reinstalled proxy CA on guest", sandboxID)+}++// setupAptCacheBindMount redirects /var/cache/apt/archives onto the workspace+// disk via bind-mount, so apt's package-download traffic (commonly 1-3 GB+// during a base build) doesn't compete with the OS for rootfs space.+//+// Idempotent: mountpoint -q short-circuits when the bind is already in place,+// so re-applying on every wake/migrate/golden-create costs nothing. Lives in+// the kernel mount table only — does NOT modify guest /etc/fstab — so it+// re-runs on every resume through this hook. Best-effort: failure is logged+// but doesn't fail the handoff (apt-cache stays on rootfs as before).+//+// Called from: golden-create (inline with the workspace mount block), wake,+// migration. All three paths converge on a guest with /home/sandbox already+// mounted on /dev/vdb.+func (m *Manager) setupAptCacheBindMount(ctx context.Context, sandboxID string, agent *AgentClient) {+ if agent == nil {+ return+ }+ execCtx, cancel := context.WithTimeout(ctx, 5*time.Second)+ defer cancel()+ _, err := agent.Exec(execCtx, &pb.ExecRequest{+ Command: "/bin/sh",+ Args: []string{"-c", strings.Join([]string{+ "mkdir -p /home/sandbox/.osb-apt-cache /var/cache/apt/archives",+ "mountpoint -q /var/cache/apt/archives || mount --bind /home/sandbox/.osb-apt-cache /var/cache/apt/archives",+ }, " && ")},+ RunAsRoot: true,+ })+ if err != nil {+ log.Printf("qemu: %s: apt-cache bind-mount failed: %v (apt cache will live on rootfs)", sandboxID, err)+ return+ }+}+// PrepareGoldenSnapshot boots a temporary VM, waits for the agent, then// hibernates it to create a reusable snapshot. Subsequent Create() calls// restore from this snapshot instead of cold-booting, cutting start time@@ -913,6 +1164,14 @@ func (m *Manager) createFromGolden(ctx context.Context, cfg types.SandboxConfig,// golden workspace. The new sandbox has a DIFFERENT workspace qcow2 on the same// virtio-blk device. Without dropping caches, the kernel uses stale superblock/// journal data → ext4 checksum errors ("Bad message").+ //+ // After /home/sandbox is mounted, redirect /var/cache/apt/archives onto+ // workspace via bind-mount. apt downloads packages there before installing+ // (commonly 1-3 GB during a base build); without the redirect, that traffic+ // lands on the 4 GiB rootfs and can fill it. The bind-mount is idempotent+ // (mountpoint -q short-circuits) and survives only in the running kernel —+ // re-applied on every wake/spawn through this same hook. Failure to bind-+ // mount is non-fatal (apt-cache stays on rootfs, status quo).mountCtx, mountCancel := context.WithTimeout(context.Background(), 10*time.Second)_, mountErr := agentClient.Exec(mountCtx, &pb.ExecRequest{Command: "/bin/sh",@@ -922,6 +1181,8 @@ func (m *Manager) createFromGolden(ctx context.Context, cfg types.SandboxConfig,"mount /dev/vdb /home/sandbox 2>/dev/null || true","resize2fs /dev/vdb 2>/dev/null || true","chown 1000:1000 /home/sandbox",+ "mkdir -p /home/sandbox/.osb-apt-cache /var/cache/apt/archives",+ "mountpoint -q /var/cache/apt/archives || mount --bind /home/sandbox/.osb-apt-cache /var/cache/apt/archives 2>/dev/null || true",}, " && ")},RunAsRoot: true,})@@ -980,30 +1241,73 @@ func (m *Manager) createFromGolden(ctx context.Context, cfg types.SandboxConfig,// patchGuestNetwork reconfigures the guest's eth0 with the new IP/gateway.// This is needed because the golden snapshot was booted with a different IP.+//+// Each step is independent and idempotent — DNS and /etc/hosts writes always+// run regardless of whether the network ops succeed. Earlier versions chained+// every step with `&&`, so a transient `ip addr add` failure (e.g. address+// already configured) short-circuited the chain and left /etc/hosts un-patched,+// which surfaces downstream as `sudo: unable to resolve host sandbox` on every+// sudo call. We verify the final network state at the end and only fail then.func patchGuestNetwork(ctx context.Context, agent *AgentClient, netCfg *NetworkConfig) error {// Calculate prefix length from mask (e.g. "255.255.255.252" → 30)prefixLen := maskToPrefixLen(netCfg.Mask)- script := fmt.Sprintf(- "ip addr flush dev eth0 && "+- "ip addr add %s/%d dev eth0 && "+- "ip link set eth0 up && "+- "ip route add default via %s && "+- "echo 'nameserver 8.8.8.8' > /etc/resolv.conf && "+- "echo 'nameserver 1.1.1.1' >> /etc/resolv.conf && "+- "grep -q \"$(hostname)\" /etc/hosts || echo \"127.0.0.1 $(hostname)\" >> /etc/hosts",+ // `ip route replace` is idempotent — works whether the route exists or not.+ // `ip addr add` may say "File exists" if the address is already there, which+ // is a no-op for our purposes; suppress and verify at the end.+ //+ // `ip neigh flush all` is critical on cross-worker fork: the captured ARP+ // cache has the SOURCE worker's gateway MAC, but the destination worker's+ // TAP has a different MAC. Without flushing, the kernel keeps the stale+ // REACHABLE entry for ~30s (base_reachable_time) and every outbound packet+ // silently drops. Flush forces a fresh ARP resolve on the next packet.+ script := fmt.Sprintf(`set +e+ip addr flush dev eth0+ip addr add %s/%d dev eth0 2>/dev/null+ip link set eth0 up+ip route replace default via %s+ip neigh flush all++# DNS — always write, independent of network ops+echo 'nameserver 8.8.8.8' > /etc/resolv.conf+echo 'nameserver 1.1.1.1' >> /etc/resolv.conf++# /etc/hosts — always ensure entry for current hostname+grep -q "$(hostname)" /etc/hosts || echo "127.0.0.1 $(hostname)" >> /etc/hosts++# Final verification — only fail if the network didn't reach desired state+ip addr show eth0 | grep -q "%s" || exit 1+ip route show default | grep -q "%s" || exit 2+exit 0+`,netCfg.GuestIP, prefixLen, netCfg.HostIP,+ netCfg.GuestIP, netCfg.HostIP,)- execCtx, cancel := context.WithTimeout(ctx, 5*time.Second)- defer cancel()-- resp, err := agent.Exec(execCtx, &pb.ExecRequest{+ // 30s deadline (bumped from 5s) — under host load `ip link` and arping+ // can take several seconds, and the prior 5s budget left no room for the+ // agent's Exec round-trip on top of that. The 5s timeout produced the+ // `network patch failed: rpc error: code = DeadlineExceeded` cluster in+ // load tests. One Redial-on-transport-error retry handles the post-loadvm+ // stale-conn case where the first call hits a wedged virtio-serial channel.+ req := &pb.ExecRequest{Command: "/bin/sh",Args: []string{"-c", script},- TimeoutSeconds: 5,+ TimeoutSeconds: 25,RunAsRoot: true,- })+ }+ rpcCtx, cancel := context.WithTimeout(ctx, 30*time.Second)+ defer cancel()+ resp, err := agent.Exec(rpcCtx, req)+ if err != nil && IsTransportError(err) {+ log.Printf("qemu: patchGuestNetwork: transport error %v, redialing and retrying once", err)+ if rdErr := agent.Redial(); rdErr != nil {+ return fmt.Errorf("network patch redial: %w (orig: %v)", rdErr, err)+ }+ rpcCtx2, cancel2 := context.WithTimeout(ctx, 30*time.Second)+ defer cancel2()+ resp, err = agent.Exec(rpcCtx2, req)+ }if err != nil {return fmt.Errorf("exec network patch: %w", err)}@@ -1103,8 +1407,7 @@ func (m *Manager) buildQEMUArgs(cpus, memMB int, rootfsPath, workspacePath, tapN// The virtio-mem backend allocates lazily (only requested-size is committed),// but maxmem must exceed base+pool for QEMU to accept the device.// Pool = 16GB - base, so any sandbox can scale up to 16GB total regardless of base.- // Round up to 128MB block alignment.- virtioMemPoolMB := ((16384 - memMB + 127) / 128) * 128+ virtioMemPoolMB := alignVirtioMemBlock(16384 - memMB)if virtioMemPoolMB < 1024 {virtioMemPoolMB = 1024 // minimum 1GB pool}@@ -1137,7 +1440,20 @@ func (m *Manager) buildQEMUArgs(cpus, memMB int, rootfsPath, workspacePath, tapN}// Create launches a new QEMU VM.-func (m *Manager) Create(ctx context.Context, cfg types.SandboxConfig) (*types.Sandbox, error) {+func (m *Manager) Create(ctx context.Context, cfg types.SandboxConfig) (sb *types.Sandbox, retErr error) {+ t0 := time.Now()+ template := cfg.Template+ if template == "" || template == "base" {+ template = "default"+ }+ defer func() {+ status := "success"+ if retErr != nil {+ status = "failure"+ }+ metrics.SandboxCreateDuration.WithLabelValues(m.cfg.Region, template, status).Observe(time.Since(t0).Seconds())+ }()+// Check disk space before creating — refuse if >95% to prevent ENOSPC corruptionif usage, err := diskUsagePercent(m.cfg.DataDir); err == nil && usage > 95 {return nil, fmt.Errorf("disk usage at %d%%, refusing new sandbox (threshold: 95%%)", usage)@@ -1149,10 +1465,6 @@ func (m *Manager) Create(ctx context.Context, cfg types.SandboxConfig) (*types.S}// Fast path: restore from golden snapshot if available and using default template- template := cfg.Template- if template == "" || template == "base" {- template = "default"- }if m.goldenDir != "" && template == "default" && cfg.TemplateRootfsKey == "" {sb, err := m.createFromGolden(ctx, cfg, id)if err != nil {@@ -1699,13 +2011,24 @@ func (m *Manager) Exec(ctx context.Context, sandboxID string, cfg types.ProcessCcommand = "/bin/sh"}- resp, err := vm.agent.Exec(ctx, &pb.ExecRequest{+ req := &pb.ExecRequest{Command: command,Args: args,Envs: cfg.Env,Cwd: cfg.Cwd,TimeoutSeconds: timeout,- })+ }+ resp, err := vm.agent.Exec(ctx, req)+ if err != nil && IsTransportError(err) {+ // Same recovery path as SyncFS: the gRPC client conn can be in a+ // transient-failure state immediately after fork (waitForAgentSocket+ // passes with one ping, but the next RPC races with conn state).+ // Redial and retry once.+ log.Printf("qemu: Exec %s: transport error (%v), redialing agent", sandboxID, err)+ if rdErr := vm.agent.Redial(); rdErr == nil {+ resp, err = vm.agent.Exec(ctx, req)+ }+ }if err != nil {return nil, fmt.Errorf("exec in %s: %w", sandboxID, err)}@@ -1834,6 +2157,45 @@ func (m *Manager) SetResourceLimits(ctx context.Context, sandboxID string, maxPireturn err}+ // Shrink-safety: refuse any request whose total memory falls below the+ // guest's working set + 5% headroom. This guards against:+ // (a) virtio-mem unplug below resident anon memory → guest OOM-killer,+ // (b) cgroup memory.max set below current RSS → guest OOM-killer,+ // in both directions and across all entry points (manual /scale,+ // per-sandbox autoscaler, post-wake, post-fork). Lifted above the+ // virtio-mem branch so it fires regardless of the worker's own+ // virtioMemRequestedMB bookkeeping (which fork doesn't track and wake+ // only started tracking recently).+ //+ // MemUsage = MemTotal - MemAvailable from /proc/meminfo inside the+ // guest — a conservative upper bound on resident anon (it includes some+ // active page cache, which is fine; we'd rather refuse a few legit+ // shrinks than silently OOM the guest).+ //+ // Fail-closed on stats errors during a shrink — better to bounce back+ // to the caller (who can retry) than apply a limit we can't validate.+ if maxMemoryBytes > 0 && vm.agent != nil {+ newTotalMB := int(maxMemoryBytes / (1024 * 1024))+ shrinking := newTotalMB < vm.MemoryMB+ statsCtx, cancel := context.WithTimeout(ctx, 3*time.Second)+ stats, statsErr := vm.agent.Stats(statsCtx)+ cancel()+ switch {+ case statsErr != nil && shrinking:+ log.Printf("qemu: %s shrink to %dMB refused: stats fetch failed: %v", sandboxID, newTotalMB, statsErr)+ return fmt.Errorf("oom_floor: cannot verify guest working set: %w", statsErr)+ case stats != nil && stats.MemUsage > 0:+ usedMB := int(stats.MemUsage / (1024 * 1024))+ floorMB := usedMB * 105 / 100+ if newTotalMB < floorMB {+ log.Printf("qemu: %s: refusing memory limit %dMB — working set %dMB requires ≥%dMB",+ sandboxID, newTotalMB, usedMB, floorMB)+ return fmt.Errorf("oom_floor: target %dMB below guest working set (%dMB used, %dMB floor)",+ newTotalMB, usedMB, floorMB)+ }+ }+ }+// virtio-mem: adjust pluggable memory to match requested totalif maxMemoryBytes > 0 && vm.qmp != nil {totalDesiredMB := int(maxMemoryBytes) / (1024 * 1024)@@ -1841,23 +2203,29 @@ func (m *Manager) SetResourceLimits(ctx context.Context, sandboxID string, maxPiif additionalMB < 0 {additionalMB = 0}- // Round up to 128MB block size- additionalMB = ((additionalMB + 127) / 128) * 128-- // Check committed memory across all VMs before attempting hotplug.- // Reserve 20% of host RAM for OS, QEMU overhead, page cache, etc.+ additionalMB = alignVirtioMemBlock(additionalMB)++ // Check actual host memory before attempting hotplug. Uses real RSS-based+ // usage (MemTotal - MemAvailable from /proc/meminfo) rather than the+ // committed sum: a sandbox configured with maxmem=16GB but actually+ // using 200MB RSS holds 200MB of host RAM, not 16GB. Committed-based+ // admission rejects grow requests on workers that have plenty of real+ // headroom — same misleading-signal bug that was already fixed for+ // migration admission (grpc_server.go PrepareMigrationIncoming).+ // Reserve 20% of host RAM as a safety margin for OS, QEMU overhead,+ // page cache, and the burst the grow request itself will pull in.if additionalMB > vm.virtioMemRequestedMB {deltaMB := additionalMB - vm.virtioMemRequestedMB- committedMB := m.totalCommittedMemoryMB()hostTotalMB := m.hostMemoryMB()+ hostUsedMB := m.hostUsedMemoryMB()reserveMB := hostTotalMB / 5 // 20% safety margin- availableMB := hostTotalMB - committedMB - reserveMB+ availableMB := hostTotalMB - hostUsedMB - reserveMBif deltaMB > availableMB {- log.Printf("qemu: virtio-mem %s: need %dMB but only %dMB available (committed=%dMB, host=%dMB, reserve=%dMB)",- sandboxID, deltaMB, availableMB, committedMB, hostTotalMB, reserveMB)- return fmt.Errorf("insufficient_capacity: need %dMB additional but only %dMB available on this worker (committed=%dMB/%dMB)",- deltaMB, availableMB, committedMB, hostTotalMB)+ log.Printf("qemu: virtio-mem %s: need %dMB but only %dMB available (used=%dMB, host=%dMB, reserve=%dMB)",+ sandboxID, deltaMB, availableMB, hostUsedMB, hostTotalMB, reserveMB)+ return fmt.Errorf("insufficient_capacity: need %dMB additional but only %dMB available on this worker (used=%dMB/%dMB)",+ deltaMB, availableMB, hostUsedMB, hostTotalMB)}}@@ -1866,9 +2234,19 @@ func (m *Manager) SetResourceLimits(ctx context.Context, sandboxID string, maxPilog.Printf("qemu: virtio-mem %s: set %dMB failed: %v — returning insufficient capacity error", sandboxID, additionalMB, err)return fmt.Errorf("insufficient_capacity: cannot hotplug %dMB on this worker: %w", additionalMB, err)} else {+ prevRequestedMB := vm.virtioMemRequestedMBvm.virtioMemRequestedMB = additionalMBvm.MemoryMB = vm.baseMemoryMB + additionalMBlog.Printf("qemu: virtio-mem %s: %dMB additional (total %dMB)", sandboxID, additionalMB, vm.MemoryMB)++ // Scaling UP? Gate exec/write until enough memory is plugged in so+ // user workloads (git clone, npm install, etc.) don't race the+ // hotplug and crash trying to use memory that's allocated-but-not-backed.+ // Remaining hotplug continues in the background after the gate opens.+ if additionalMB > prevRequestedMB {+ vm.memoryReady = make(chan struct{})+ go m.watchMemoryHotplug(vm, additionalMB)+ }}}}@@ -1876,6 +2254,68 @@ func (m *Manager) SetResourceLimits(ctx context.Context, sandboxID string, maxPireturn vm.agent.SetResourceLimits(ctx, maxPids, maxMemoryBytes, cpuMaxUsec, cpuPeriodUsec)}+// UpdateSandboxSecret refreshes the proxy session value for one secret name.+// Returns (true, nil) on success, (false, nil) if there's no session for the+// sandbox or the secret name isn't on the session — both treated as transient+// (e.g. mid-migration); the caller may log + move on. Returns an error only+// on hard failure (no proxy at all).+func (m *Manager) UpdateSandboxSecret(_ context.Context, sandboxID, secretName, value string) (bool, error) {+ if m.secretsProxy == nil {+ return false, fmt.Errorf("secrets proxy not configured on this worker")+ }+ return m.secretsProxy.UpdateSecretValue(sandboxID, secretName, value), nil+}++// watchMemoryHotplug polls the guest's /proc/meminfo until at least 1GB of+// virtio-mem memory has been onlined (or target if smaller), then closes+// vm.memoryReady to unblock getReadyVM. Bounded by a 10s timeout so the+// channel always closes even if hotplug stalls.+func (m *Manager) watchMemoryHotplug(vm *VMInstance, targetAdditionalMB int) {+ defer func() {+ if vm.memoryReady != nil {+ select {+ case <-vm.memoryReady:+ default:+ close(vm.memoryReady)+ }+ }+ }()++ // We only need ~1GB plugged for most workloads to have breathing room.+ // The rest hotplugs in the background and is usually done within seconds.+ readyThresholdMB := 1024+ if targetAdditionalMB < readyThresholdMB {+ readyThresholdMB = targetAdditionalMB+ }+ requiredTotalMB := vm.baseMemoryMB + readyThresholdMB++ deadline := time.Now().Add(10 * time.Second)+ for time.Now().Before(deadline) {+ if vm.agent == nil {+ return+ }+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)+ resp, err := vm.agent.Exec(ctx, &pb.ExecRequest{+ Command: "/bin/sh",+ Args: []string{"-c", "awk '/MemTotal/ {print $2}' /proc/meminfo"},+ TimeoutSeconds: 2,+ })+ cancel()+ if err == nil && resp != nil {+ // MemTotal is in kB+ var kB int+ fmt.Sscanf(string(resp.Stdout), "%d", &kB)+ if kB/1024 >= requiredTotalMB {+ log.Printf("qemu: virtio-mem %s: hotplug gate opened (%dMB onlined, needed %dMB)",+ vm.ID, kB/1024, requiredTotalMB)+ return+ }+ }+ time.Sleep(100 * time.Millisecond)+ }+ log.Printf("qemu: virtio-mem %s: hotplug gate timed out after 10s, unblocking anyway", vm.ID)+}+// TotalCommittedMemoryMB returns the sum of MemoryMB (base + virtio-mem) across all running VMs.// This represents the maximum host memory that could be consumed if all VMs use their full allocation.func (m *Manager) TotalCommittedMemoryMB() int {@@ -1969,6 +2409,21 @@ func (m *Manager) HostUsedMemoryMB() int {return m.hostUsedMemoryMB()}+// virtioMemBlockSizeMB is the QEMU virtio-mem device block size. All plug+// requests must be a multiple of this — QMP qom-set rejects non-aligned+// values. Set in -device virtio-mem-pci,block-size=128M; keep them in sync.+const virtioMemBlockSizeMB = 128++// alignVirtioMemBlock rounds an additional-memory request up to the virtio-mem+// device's block size so the QMP qom-set call is accepted. Negative or zero+// inputs return zero.+func alignVirtioMemBlock(mb int) int {+ if mb <= 0 {+ return 0+ }+ return ((mb + virtioMemBlockSizeMB - 1) / virtioMemBlockSizeMB) * virtioMemBlockSizeMB+}+// VMActualMemoryMB returns the QEMU process RSS for a sandbox — true physical// memory the host kernel has backed with RAM. Includes QEMU overhead plus// faulted-in guest pages. Scaler passes this value to PrepareMigrationIncoming@@ -2052,9 +2507,30 @@ func (m *Manager) ContainerName(id string) string {}// Hibernate snapshots a VM and uploads to S3.-func (m *Manager) Hibernate(ctx context.Context, sandboxID string, checkpointStore *storage.CheckpointStore) (*sandbox.HibernateResult, error) {+func (m *Manager) Hibernate(ctx context.Context, sandboxID string, checkpointStore *storage.CheckpointStore) (res *sandbox.HibernateResult, retErr error) {vm, err := m.getVM(sandboxID)if err != nil {+ // Pre-lookup failure — observe with an "unknown" template label so the+ // histogram still records the failure surface without inventing a+ // template we didn't find.+ metrics.HibernateDuration.WithLabelValues(m.cfg.Region, "unknown", "failure").Observe(0)+ return nil, err+ }++ t0 := time.Now()+ defer func() {+ status := "success"+ if retErr != nil {+ status = "failure"+ }+ metrics.HibernateDuration.WithLabelValues(m.cfg.Region, vm.Template, status).Observe(time.Since(t0).Seconds())+ }()++ // Refuse hibernate if rootfs is critically full. dpkg/apt mid-rename + an+ // unsynced page cache + a savevm produces qcow2 EXT4 metadata corruption+ // that won't cold-mount on the next wake. Cheap pre-flight check; the+ // customer should free space (or kill+respawn from a checkpoint) instead.+ if err := m.checkRootfsPressure(ctx, vm); err != nil {return nil, err}@@ -2077,7 +2553,7 @@ func (m *Manager) Hibernate(ctx context.Context, sandboxID string, checkpointSto// Wake restores a VM from a snapshot.// Guards against double-wake: if the sandbox is already running, returns it.-func (m *Manager) Wake(ctx context.Context, sandboxID string, checkpointKey string, checkpointStore *storage.CheckpointStore, timeout int) (*types.Sandbox, error) {+func (m *Manager) Wake(ctx context.Context, sandboxID string, checkpointKey string, checkpointStore *storage.CheckpointStore, timeout int) (sb *types.Sandbox, retErr error) {// Prevent double wake — if sandbox is already running, return itm.mu.RLock()if existing, ok := m.vms[sandboxID]; ok {@@ -2086,6 +2562,23 @@ func (m *Manager) Wake(ctx context.Context, sandboxID string, checkpointKey strireturn vmToSandbox(existing), nil}m.mu.RUnlock()++ // Wake = resume hibernated sandbox from S3 — by definition the checkpoint+ // archive lives in object storage. ForkFromCheckpoint in grpc_server.go+ // observes the warm_cache path separately.+ t0 := time.Now()+ defer func() {+ status := "success"+ template := "unknown"+ if sb != nil {+ template = sb.Template+ }+ if retErr != nil {+ status = "failure"+ }+ metrics.WakeDuration.WithLabelValues(m.cfg.Region, template, "s3", status).Observe(time.Since(t0).Seconds())+ }()+return m.doWake(ctx, sandboxID, checkpointKey, checkpointStore, timeout)}@@ -2125,31 +2618,73 @@ func (m *Manager) CheckpointCachePath(checkpointID, filename string) string {// CreateCheckpoint creates an internal VM snapshot using QEMU's savevm.// The snapshot is stored inside the qcow2 drive files — no external migration file needed.// The VM pauses briefly for the snapshot, then resumes automatically.-func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointID string, checkpointStore *storage.CheckpointStore, onReady func()) (rootfsKey, workspaceKey string, err error) {+//+// Returns the S3 keys, the actual archive size in bytes (or 0 when no+// checkpointStore is configured / the upload failed), and any error. The+// archive size replaces the previous hardcoded 0 stamped on the+// sandbox_checkpoints row so operators and customers can see how big a+// checkpoint actually is. Upload failures now propagate as an error rather+// than being silently logged — the control plane gets the reason and+// persists it via SetCheckpointFailed (migration 039 added error_msg).+func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointID string, checkpointStore *storage.CheckpointStore, onReady func()) (rootfsKey, workspaceKey string, sizeBytes int64, err error) {+ tStart := time.Now()+ // failureReason is updated at each error site below so the defer can attribute+ // failures by cause. Stays "other" for any unclassified path (which is a+ // signal to add an explicit classification when seen).+ failureReason := "other"+ template := "unknown"+ defer func() {+ status := "success"+ if err != nil {+ status = "failure"+ metrics.CheckpointFailuresTotal.WithLabelValues(m.cfg.Region, template, failureReason).Inc()+ }+ metrics.CheckpointDuration.WithLabelValues(m.cfg.Region, template, status).Observe(time.Since(tStart).Seconds())+ }()+vm, err := m.getVM(sandboxID)if err != nil {- return "", "", err+ failureReason = "vm_not_found"+ return "", "", 0, err+ }+ template = vm.Template++ // Refuse if rootfs is critically full — same corruption risk as hibernate+ // (dpkg/apt mid-rename + savevm = qcow2 EXT4 metadata broken on next mount).+ if err := m.checkRootfsPressure(ctx, vm); err != nil {+ failureReason = "disk_pressure"+ return "", "", 0, err}// Reject if another destructive operation (checkpoint, hibernate, restore) is in progress.// Without this, rapid-fire checkpoints queue up and the agent gets into a bad state// from overlapping SIGUSR1/reconnect cycles.if !vm.opMu.TryLock() {- return "", "", fmt.Errorf("another operation is in progress on sandbox %s — try again shortly", sandboxID)+ failureReason = "op_in_progress"+ return "", "", 0, fmt.Errorf("another operation is in progress on sandbox %s — try again shortly", sandboxID)}defer vm.opMu.Unlock()t0 := time.Now()if vm.qmp == nil {- return "", "", fmt.Errorf("QMP connection not available for %s", sandboxID)+ failureReason = "qmp_unavailable"+ return "", "", 0, fmt.Errorf("QMP connection not available for %s", sandboxID)}- // Sync filesystem and quiesce virtio-serial before snapshot. The PrepareHibernate- // RPC returns only after the guest is fully prepared, so no sleep is needed.+ // Sync filesystem, quiesce virtio-serial, close host conn, and WAIT for+ // the guest to process EOF before savevm. Critical for clean snapshot+ // state — see quiesceAndCloseAgent for the protocol details.+ //+ // If quiesce fails (agent unresponsive), refuse the checkpoint: a savevm+ // against an un-synced guest captures inconsistent qcow2 metadata that+ // becomes unbootable on next cold-mount. See ErrAgentUnresponsive.if vm.agent != nil {- prepareAgentForHibernate(ctx, vm.agent)- vm.agent.Close()+ if qErr := quiesceAndCloseAgent(ctx, vm.agent); qErr != nil {+ log.Printf("qemu: CreateCheckpoint %s/%s: refusing savevm — %v", sandboxID, checkpointID, qErr)+ failureReason = "agent_unresponsive"+ return "", "", 0, fmt.Errorf("checkpoint %s: %w", sandboxID, qErr)+ }vm.agent = nil}@@ -2168,22 +2703,40 @@ func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointID// (close agent + let SIGUSR1 reset the virtio-serial listener before// savevm) is preserved above.if vm.qmp == nil {- return "", "", fmt.Errorf("QMP connection not available for %s", sandboxID)+ failureReason = "qmp_unavailable"+ return "", "", 0, fmt.Errorf("QMP connection not available for %s", sandboxID)}cacheDir := m.checkpointCacheDir(checkpointID)stagingDir := cacheDir + ".staging"if mkErr := os.MkdirAll(filepath.Join(stagingDir, "snapshot"), 0755); mkErr != nil {- return "", "", fmt.Errorf("mkdir staging: %w", mkErr)+ failureReason = "staging_setup"+ return "", "", 0, fmt.Errorf("mkdir staging: %w", mkErr)}// savevm pauses the VM, writes memory+device+disk-delta into every qcow2// drive as an internal snapshot, then resumes. The qcow2 files now carry// the full VM state; no external memory file is needed.+ //+ // Explicit Stop() before savevm halts vCPUs to close the small race where+ // in-flight virtio-blk writes can land in the qcow2 between the agent's+ // `sync` (above) and the start of savevm. We Cont() unconditionally after+ // savevm completes (success or failure) — the sandbox is supposed to keep+ // running post-checkpoint, so we must not leave it in stopped state.snapshotName := "cp-" + checkpointID- if err := vm.qmp.SaveVM(snapshotName); err != nil {+ if stopErr := vm.qmp.Stop(); stopErr != nil {os.RemoveAll(stagingDir)- return "", "", fmt.Errorf("savevm: %w", err)+ failureReason = "qmp_stop"+ return "", "", 0, fmt.Errorf("qmp stop before savevm: %w", stopErr)+ }+ saveErr := vm.qmp.SaveVM(snapshotName)+ if contErr := vm.qmp.Cont(); contErr != nil {+ log.Printf("qemu: CreateCheckpoint %s/%s: failed to resume VM after savevm: %v", sandboxID, checkpointID, contErr)+ }+ if saveErr != nil {+ os.RemoveAll(stagingDir)+ failureReason = "qmp_savevm"+ return "", "", 0, fmt.Errorf("savevm: %w", saveErr)}log.Printf("qemu: CreateCheckpoint %s/%s: savevm complete (%dms)", sandboxID, checkpointID, time.Since(t0).Milliseconds())@@ -2195,11 +2748,13 @@ func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointIDsrcWorkspace := filepath.Join(vm.sandboxDir, "workspace.qcow2")if err := copyFileReflink(srcRootfs, filepath.Join(stagingDir, "rootfs.qcow2")); err != nil {os.RemoveAll(stagingDir)- return "", "", fmt.Errorf("copy rootfs: %w", err)+ failureReason = "qcow2_copy"+ return "", "", 0, fmt.Errorf("copy rootfs: %w", err)}if err := copyFileReflink(srcWorkspace, filepath.Join(stagingDir, "workspace.qcow2")); err != nil {os.RemoveAll(stagingDir)- return "", "", fmt.Errorf("copy workspace: %w", err)+ failureReason = "qcow2_copy"+ return "", "", 0, fmt.Errorf("copy workspace: %w", err)}// Record the savevm snapshot name so ForkFromCheckpoint / RestoreFromCheckpoint// know which internal snapshot to loadvm.@@ -2218,15 +2773,19 @@ func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointIDif reconnErr == nil {vm.agent = agentClient} else {- log.Printf("qemu: CreateCheckpoint %s/%s: CRITICAL: agent reconnect failed, killing orphan VM", sandboxID, checkpointID)- if vm.qmp != nil {- _ = vm.qmp.Quit()- vm.qmp.Close()- vm.qmp = nil- }+ // Agent didn't come back after savevm — the VM is unmanageable. Full+ // teardown via destroyVM, not the partial QMP-quit-only cleanup that+ // used to live here. The old path left the qemu process and TAP/dir+ // behind any time qmp.Quit didn't reach the process, producing the+ // orphan qemu we observed under load (m.vms removed but qemu alive,+ // invisible to the rest of the worker until the orphan reaper runs).+ log.Printf("qemu: CreateCheckpoint %s/%s: CRITICAL: agent reconnect failed, destroying VM cleanly", sandboxID, checkpointID)m.mu.Lock()delete(m.vms, sandboxID)m.mu.Unlock()+ if err := m.destroyVM(vm); err != nil {+ log.Printf("qemu: CreateCheckpoint %s/%s: destroyVM also failed: %v (orphan reaper will catch)", sandboxID, checkpointID, err)+ }}// Write metadata and finalize cache.@@ -2256,28 +2815,16 @@ func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointIDmetaJSON, _ := json.Marshal(meta)_ = os.WriteFile(filepath.Join(stagingDir, "snapshot", "snapshot-meta.json"), metaJSON, 0644)- // Extract memory into an external mem.zst and strip the internal savevm- // snapshot from the staging qcow2s. This converts the checkpoint into a- // format fork restore prefers (-incoming exec:zstdcat over loadvm) and- // that qemu-img rebase composes cleanly with for cross-golden forks.- // Done before the rename so the local cache never exposes a- // half-converted state to concurrent fork readers.- //- // Best-effort: on failure, leave the savevm-based layout in place. Fork- // restore still works via loadvm for same-golden forks; cross-golden- // will fail the same way it does without this step, so we're no worse- // off than before.- extractCtx, extractCancel := context.WithTimeout(context.Background(), 10*time.Minute)- // Pass baseMemoryMB (initial -m value), not MemoryMB (which reflects the- // current virtio-mem balloon). The extract QEMU's cmdline must match the- // original VM's -m for loadvm to restore correctly; virtio-mem state- // inside the snapshot replays the balloon up to the ballooned size.- if extractErr := m.extractCheckpointMemory(extractCtx, stagingDir, snapshotName, vm.guestMAC, vm.baseMemoryMB, vm.CpuCount); extractErr != nil {- log.Printf("qemu: checkpoint %s: memory extract failed (falling back to savevm format): %v", checkpointID, extractErr)- } else {- log.Printf("qemu: checkpoint %s: memory extracted to mem.zst (%dms total)", checkpointID, time.Since(t0).Milliseconds())- }- extractCancel()+ // Note: an earlier version of this code extracted the memory into an+ // external mem.zst and stripped the internal savevm snapshot from the+ // staging qcow2s, intending to make qemu-img rebase compose cleanly for+ // cross-golden forks (loaded via `-incoming exec:zstdcat`). In practice+ // the resulting checkpoints would not load: QEMU sat in `prelaunch`+ // indefinitely while reading the migration stream, never transitioning+ // to `paused`. Reverted to the savevm/loadvm path which has months of+ // production track record. Cross-golden forks rely on pin-to-base+ // (ensureCheckpointRebased) to align the qcow2's backing file at fork+ // time without touching the captured savevm state.// Atomic rename into cache under write lock.m.checkpointCacheMu.Lock()@@ -2312,26 +2859,45 @@ func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointIDt1 := time.Now()archivePath := filepath.Join(cacheDir, "checkpoint.tar.zst")- if err := createArchive(archivePath, cacheDir, archiveFiles); err != nil {- log.Printf("qemu: checkpoint %s: archive failed: %v", checkpointID, err)- } else {- uploadCtx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)- if _, uerr := checkpointStore.Upload(uploadCtx, rootfsKey, archivePath); uerr != nil {- log.Printf("qemu: checkpoint %s: S3 upload failed: %v", checkpointID, uerr)- } else {- log.Printf("qemu: checkpoint %s: S3 upload complete (%dms, files=%v)",- checkpointID, time.Since(t1).Milliseconds(), archiveFiles)- }- cancel()- os.Remove(archivePath)+ if archErr := createArchive(archivePath, cacheDir, archiveFiles); archErr != nil {+ log.Printf("qemu: checkpoint %s: archive failed: %v", checkpointID, archErr)+ // Surface as the function's error so the API can persist it via+ // SetCheckpointFailed instead of silently logging.+ failureReason = "archive"+ return rootfsKey, workspaceKey, 0, fmt.Errorf("create checkpoint archive: %w", archErr)+ }+ // 15-min upload budget. Pre-fix this was 5 min, which combined with+ // the API's 5-min gRPC ctx left no headroom for ~5+ GB compressed+ // archives under any blob-side contention. Customer hit this on a+ // 7–9 GB sandbox: status flipped to `failed` after ~280 s (≈ the+ // 5-min ceiling) with no error detail, since SetCheckpointFailed+ // also dropped the reason. Migration 039 + the 20-min API gRPC+ // timeout + this 15-min upload give a generous flat budget without+ // memory-scaling complexity.+ uploadCtx, cancel := context.WithTimeout(context.Background(), 15*time.Minute)+ _, uerr := checkpointStore.Upload(uploadCtx, rootfsKey, archivePath)+ cancel()+ // Stat the archive before deleting so we can return the actual size+ // even on success (the upload doesn't return it). Any stat error here+ // is non-fatal — we'd rather report 0 than fail the checkpoint.+ if info, statErr := os.Stat(archivePath); statErr == nil {+ sizeBytes = info.Size()}+ os.Remove(archivePath)+ if uerr != nil {+ log.Printf("qemu: checkpoint %s: S3 upload failed: %v", checkpointID, uerr)+ failureReason = "s3_upload"+ return rootfsKey, workspaceKey, sizeBytes, fmt.Errorf("upload checkpoint to S3: %w", uerr)+ }+ log.Printf("qemu: checkpoint %s: S3 upload complete (%dms, %.1f MB, files=%v)",+ checkpointID, time.Since(t1).Milliseconds(), float64(sizeBytes)/(1024*1024), archiveFiles)}if onReady != nil {onReady()}- return rootfsKey, workspaceKey, nil+ return rootfsKey, workspaceKey, sizeBytes, nil}// RestoreFromCheckpoint reverts a sandbox to a checkpoint by killing the current@@ -2547,8 +3113,7 @@ func (m *Manager) RestoreFromCheckpoint(ctx context.Context, sandboxID, checkpoi// memory immediately on resume. Without this, restored processes that were using// >baseMemMB would OOM before the post-resume re-scale completes.if desiredMemMB > bootMemMB {- additionalMB := desiredMemMB - bootMemMB- additionalMB = ((additionalMB + 127) / 128) * 128 // align to 128MB block size+ additionalMB := alignVirtioMemBlock(desiredMemMB - bootMemMB)if err := qmpClient.SetVirtioMemSize(additionalMB); err != nil {log.Printf("qemu: RestoreFromCheckpoint %s: pre-resume scale to %dMB failed: %v (continuing with base %dMB)",sandboxID, desiredMemMB, err, bootMemMB)@@ -2583,10 +3148,11 @@ func (m *Manager) RestoreFromCheckpoint(ctx context.Context, sandboxID, checkpoilog.Printf("qemu: RestoreFromCheckpoint %s: clock sync failed: %v", sandboxID, err)}- // Re-register secrets proxy session from checkpoint metadata.- if m.secretsProxy != nil && len(cpMeta.SealedTokens) > 0 {- m.secretsProxy.ReregisterSession(sandboxID, netCfg.GuestIP, cpMeta.SealedTokens, cpMeta.EgressAllowlist, cpMeta.TokenHosts)- log.Printf("qemu: RestoreFromCheckpoint %s: re-registered secrets proxy session (%d tokens)", sandboxID, len(cpMeta.SealedTokens))+ // Re-register secrets proxy session from checkpoint metadata. An allowlist+ // alone is enough — without a session the proxy 407s every request.+ if m.secretsProxy != nil && (len(cpMeta.SealedTokens) > 0 || len(cpMeta.EgressAllowlist) > 0) {+ m.secretsProxy.ReregisterSession(sandboxID, netCfg.GuestIP, cpMeta.SealedTokens, cpMeta.EgressAllowlist, cpMeta.TokenHosts, cpMeta.SealedNames)+ log.Printf("qemu: RestoreFromCheckpoint %s: re-registered secrets proxy session (%d tokens, %d allowlist, %d names)", sandboxID, len(cpMeta.SealedTokens), len(cpMeta.EgressAllowlist), len(cpMeta.SealedNames))}// Step 8: Update VM instance@@ -2603,7 +3169,7 @@ func (m *Manager) RestoreFromCheckpoint(ctx context.Context, sandboxID, checkpoivm.CpuCount = bootCpusvm.baseMemoryMB = bootMemMBif desiredMemMB > bootMemMB {- additionalMB := ((desiredMemMB - bootMemMB + 127) / 128) * 128+ additionalMB := alignVirtioMemBlock(desiredMemMB - bootMemMB)vm.MemoryMB = bootMemMB + additionalMBvm.virtioMemRequestedMB = additionalMB} else {@@ -2861,13 +3427,36 @@ func (m *Manager) ForkFromCheckpoint(ctx context.Context, checkpointID string, clog.Printf("qemu: ForkFromCheckpoint %s → %s: agent connected, patching network...", checkpointID, id)- // Patch network (fork gets new IPs) + sync clock+ // Patch network (fork gets new IPs) + sync clock — both LOAD-BEARING.+ // Earlier this code only logged failures; the fork would "complete" with+ // the wrong IP/route/DNS and an unresponsive agent gRPC channel, leaking+ // a half-broken VM. Now: propagate errors, destroy the half-built fork,+ // and return — caller retries against a clean slate.+ patchT0 := time.Now()if err := patchGuestNetwork(context.Background(), agent, netCfg); err != nil {- log.Printf("qemu: ForkFromCheckpoint %s: network patch failed: %v", id, err)+ log.Printf("qemu: ForkFromCheckpoint %s: ABORT network patch failed (%dms): %v",+ id, time.Since(patchT0).Milliseconds(), err)+ _ = agent.Close()+ _ = qmpClient.Close()+ _ = cmd.Process.Kill()+ _ = cmd.Wait()+ m.cleanupVM(netCfg, sandboxDir)+ return nil, fmt.Errorf("fork %s: network patch failed: %w", id, err)}+ log.Printf("qemu: ForkFromCheckpoint %s: network patched (%dms)", id, time.Since(patchT0).Milliseconds())++ clockT0 := time.Now()if err := syncGuestClock(context.Background(), agent); err != nil {- log.Printf("qemu: ForkFromCheckpoint %s: clock sync failed: %v", id, err)+ log.Printf("qemu: ForkFromCheckpoint %s: ABORT clock sync failed (%dms): %v",+ id, time.Since(clockT0).Milliseconds(), err)+ _ = agent.Close()+ _ = qmpClient.Close()+ _ = cmd.Process.Kill()+ _ = cmd.Wait()+ m.cleanupVM(netCfg, sandboxDir)+ return nil, fmt.Errorf("fork %s: clock sync failed: %w", id, err)}+ log.Printf("qemu: ForkFromCheckpoint %s: clock synced (%dms)", id, time.Since(clockT0).Milliseconds())// Set env vars (sealed via secrets proxy if configured)envsToInject := m.sealSandboxEnvs(context.Background(), id, netCfg, agent, cfg)@@ -2912,6 +3501,12 @@ func (m *Manager) ForkFromCheckpoint(ctx context.Context, checkpointID string, cm.vms[id] = vmm.mu.Unlock()+ // Refresh the proxy CA in the forked guest's trust store. The fork+ // inherits the source checkpoint's disk + RAM, so its trust store has+ // whatever CA the original sandbox was created against — which is+ // probably a different worker. Idempotent in the shared-CA case.+ m.reinstallProxyCA(ctx, id, agent)+// Notify metadata serverif m.onSandboxReady != nil {m.onSandboxReady(id, netCfg.GuestIP, meta.Template, now)@@ -2962,6 +3557,21 @@ func (m *Manager) getReadyVM(ctx context.Context, id string) (*VMInstance, error}}+ // Block until virtio-mem has plugged in enough memory for user workloads.+ // Sandbox is marked "running" as soon as QEMU boots, but the scaler's+ // SetResourceLimits kicks off hotplug async — user code (e.g. git clone)+ // running immediately can hit memory that's allocated-but-not-backed.+ // Bounded wait so we never hang if hotplug stalls.+ if vm.memoryReady != nil {+ select {+ case <-vm.memoryReady:+ case <-ctx.Done():+ return nil, ctx.Err()+ case <-time.After(5 * time.Second):+ log.Printf("qemu: sandbox %s: memory hotplug wait exceeded 5s, proceeding anyway", id)+ }+ }+if vm.agent == nil {return nil, fmt.Errorf("sandbox %s: agent not available", id)}@@ -3014,16 +3624,41 @@ func (m *Manager) GetAgent(sandboxID string) (*AgentClient, error) {return vm.agent, nil}-// GetWorkspacePath returns the host path to a sandbox's workspace.ext4.+// ConfigureLogship hands the in-VM agent its sandbox session log-shipping+// configuration. Called by the worker right after a sandbox is created+// (or warm-forked from a checkpoint) so the agent's forwarder knows+// where to ship and how to tag events. Empty ingestToken disables+// shipping for this sandbox (kill-switch).+func (m *Manager) ConfigureLogship(ctx context.Context, sandboxID, ingestToken, dataset, orgID string) error {+ agent, err := m.GetAgent(sandboxID)+ if err != nil {+ return err+ }+ if agent == nil {+ return fmt.Errorf("agent client not ready for sandbox %s", sandboxID)+ }+ return agent.ConfigureLogship(ctx, ingestToken, dataset, sandboxID, orgID)+}++// GetWorkspacePath returns the host path to a sandbox's workspace qcow2.+// Used by the autosave loop to gate SyncFS on mtime — no point syncing if+// the workspace hasn't been touched since the last successful sync.func (m *Manager) GetWorkspacePath(sandboxID string) (string, error) {vm, err := m.getVM(sandboxID)if err != nil {return "", err}- return filepath.Join(vm.sandboxDir, "workspace.ext4"), nil+ return filepath.Join(vm.sandboxDir, "workspace.qcow2"), nil}// SyncFS flushes filesystem buffers inside the VM.+//+// On transport errors (Unavailable, EOF, "closed network connection"), the+// agent client redials and retries once. This is the recovery path for the+// prod scenario where an agent connection silently dropped ~10 min after+// migration restore and stayed dropped: every autosave-driven SyncFS would+// hit a closed conn and log a failure forever, with no reconnect attempt.+// Now we redial on demand and the next autosave succeeds.func (m *Manager) SyncFS(ctx context.Context, sandboxID string) error {vm, err := m.getVM(sandboxID)if err != nil {@@ -3032,7 +3667,17 @@ func (m *Manager) SyncFS(ctx context.Context, sandboxID string) error {if vm.agent == nil {return fmt.Errorf("no agent connection for %s", sandboxID)}- return vm.agent.SyncFS(ctx)+ if err := vm.agent.SyncFS(ctx); err != nil {+ if !IsTransportError(err) {+ return err+ }+ log.Printf("qemu: SyncFS %s: transport error (%v), redialing agent", sandboxID, err)+ if rdErr := vm.agent.Redial(); rdErr != nil {+ return fmt.Errorf("syncfs failed and redial failed: orig=%v redial=%w", err, rdErr)+ }+ return vm.agent.SyncFS(ctx)+ }+ return nil}// CleanupOrphanedProcesses kills any QEMU processes and TAP devicesdiff --git a/internal/qemu/migration.go b/internal/qemu/migration.goindex 508e1081..afb74313 100644--- a/internal/qemu/migration.go+++ b/internal/qemu/migration.go@@ -12,6 +12,7 @@ import ("sync""time"+ "github.com/opensandbox/opensandbox/internal/sandbox""github.com/opensandbox/opensandbox/internal/storage""github.com/opensandbox/opensandbox/pkg/types"pb "github.com/opensandbox/opensandbox/proto/agent"@@ -323,6 +324,14 @@ func (mc *MigrationCoordinator) LiveMigrate(ctx context.Context, sandboxID, inco}}+ // Tear down the secrets-proxy session for this sandbox on the source.+ // The destination has already re-registered it during+ // PrepareMigrationIncoming, so leaving it here would leak plaintext+ // secrets in the source worker's process memory until restart.+ if mc.manager.secretsProxy != nil && vm.network != nil && vm.network.GuestIP != "" {+ mc.manager.secretsProxy.UnregisterSession(vm.network.GuestIP)+ }+if vm.network != nil {RemoveMetadataDNAT(vm.network.TAPName, vm.network.HostIP)RemoveDNAT(vm.network)@@ -529,6 +538,21 @@ func (m *Manager) CompleteIncomingMigration(ctx context.Context, sandboxID strinreturn err}+ // Wait for QEMU to finish loading the migrated state before resuming.+ // The source's `migrate` command completes when it has SENT all data;+ // the dest's QEMU may still be in `inmigrate` parsing/applying it when+ // the server calls CompleteIncomingMigration. On a contended or smaller+ // dest, that load can take >10s, in which case Cont blocks waiting for+ // QEMU to transition and our 10s response read fires before QEMU answers.+ // Polling query-status until `paused`/`postmigrate` makes Cont a no-op+ // from QEMU's perspective and turns this from "Cont times out, agent+ // reconnect times out, migration fails" into a clean wait.+ if vm.qmp != nil {+ if err := m.waitForMigrationReady(vm.qmp, 60*time.Second); err != nil {+ log.Printf("qemu: migration %s: waitForMigrationReady failed: %v (attempting cont anyway)", sandboxID, err)+ }+ }+// Resume the VM — after live migration the target is pausedif vm.qmp != nil {if err := vm.qmp.Cont(); err != nil {@@ -554,6 +578,24 @@ func (m *Manager) CompleteIncomingMigration(ctx context.Context, sandboxID strinlog.Printf("qemu: migration %s: clock sync failed: %v", sandboxID, err)}+ // Re-install the secrets-proxy CA cert into the guest so the destination+ // worker's cert chain is trusted by anything the guest does next. Even+ // with the shared-CA-via-KV path, this is belt-and-suspenders that also+ // retrofits sandboxes which were created BEFORE the shared CA rollout+ // (their trust store has the source's per-worker CA baked in). The+ // guest's env vars (SSL_CERT_FILE / REQUESTS_CA_BUNDLE / NODE_EXTRA_CA_CERTS)+ // already point to this fixed path; overwriting the file is enough — no+ // update-ca-certificates run required because consumers read the file+ // directly. Cheap (~1ms agent RPC) and idempotent: in steady state the+ // new content equals the old, so this is a no-op write.+ m.reinstallProxyCA(ctx, sandboxID, agentClient)++ // Re-apply the apt-cache bind-mount on the destination. Migration carries+ // the loadvm-restored mount table, so this is normally a no-op (mountpoint+ // -q short-circuits), but it covers sandboxes that were migrated before+ // this fix shipped and never had the bind set up.+ m.setupAptCacheBindMount(ctx, sandboxID, agentClient)+// Sync VM memory tracking with actual QEMU state.// After migration, the QEMU process has the source's virtio-mem hotplugged memory,// but the Go struct still has the prep values (virtioMemRequestedMB=0, MemoryMB=baseMem).@@ -581,15 +623,22 @@ func (m *Manager) CompleteIncomingMigration(ctx context.Context, sandboxID strin// Always uploads the thin overlay (never flattens). The target worker rebases// to its own base image if golden versions differ.// Returns S3 keys, golden version, and base CPU/memory for QEMU matching.-func (m *Manager) PreCopyDrives(ctx context.Context, sandboxID string, checkpointStore *storage.CheckpointStore) (rootfsKey, workspaceKey, goldenVer string, baseCPU, baseMem, actualMem int, err error) {+// See sandbox.MigrationSecrets for the canonical type. We use the shared+// type so the worker gRPC layer can refer to it without an import cycle.++func (m *Manager) PreCopyDrives(ctx context.Context, sandboxID string, checkpointStore *storage.CheckpointStore) (rootfsKey, workspaceKey, goldenVer string, baseCPU, baseMem, actualMem int, secrets sandbox.MigrationSecrets, err error) {m.mu.RLock()vm, exists := m.vms[sandboxID]var pid int+ var guestIP stringif exists {goldenVer = vm.goldenVersionbaseCPU = vm.CpuCountbaseMem = vm.baseMemoryMBpid = vm.pid+ if vm.network != nil {+ guestIP = vm.network.GuestIP+ }}m.mu.RUnlock()@@ -597,6 +646,18 @@ func (m *Manager) PreCopyDrives(ctx context.Context, sandboxID string, checkpoinactualMem = readProcRSSMB(pid)}+ // Capture secrets-proxy state BEFORE we start uploading drives. The+ // proxy session is keyed by guest IP; we look it up here so the+ // orchestrator can hand it to the target via PrepareMigrationIncoming.+ // Empty maps when no secrets are registered — orchestrator just passes+ // nil/empty through and target's ReregisterSession is a no-op.+ if m.secretsProxy != nil && guestIP != "" {+ secrets.SealedTokens = m.secretsProxy.GetSessionTokens(guestIP)+ secrets.EgressAllowlist = m.secretsProxy.GetSessionAllowlist(guestIP)+ secrets.TokenHosts = m.secretsProxy.GetSessionTokenHosts(guestIP)+ secrets.SealedNames = m.secretsProxy.GetSessionNames(guestIP)+ }+mc := &MigrationCoordinator{manager: m,checkpointStore: checkpointStore,@@ -612,7 +673,15 @@ func (m *Manager) PreCopyDrives(ctx context.Context, sandboxID string, checkpoin// matches the target's current golden version, a fast metadata-only repoint is used.// When versions differ, a full rebase downloads the old base from S3 and migrates// the overlay to the current base — same logic as checkpoint fork rebase.-func (m *Manager) PrepareIncomingMigrationWithS3(ctx context.Context, sandboxID, rootfsS3Key, workspaceS3Key string, cpus, memMB, guestPort int, template string, checkpointStore *storage.CheckpointStore, overlayMode bool, sourceGoldenVersion string) (incomingAddr string, hostPort int, err error) {+//+// secrets is the per-sandbox secrets-proxy state captured by PreCopyDrives on+// the source. We register it with this worker's secrets proxy AFTER the+// destination QEMU is staged (so vm.network.GuestIP is known) but BEFORE the+// source initiates the live migration. Once the migration completes and+// CompleteIncomingMigration unpauses the VM, the first outbound HTTPS+// request finds its substitution map already in place. Empty maps are a+// no-op (sandboxes without a secret store).+func (m *Manager) PrepareIncomingMigrationWithS3(ctx context.Context, sandboxID, rootfsS3Key, workspaceS3Key string, cpus, memMB, guestPort int, template string, checkpointStore *storage.CheckpointStore, overlayMode bool, sourceGoldenVersion string, secrets sandbox.MigrationSecrets) (incomingAddr string, hostPort int, err error) {sandboxDir := filepath.Join(m.cfg.DataDir, "sandboxes", sandboxID)// Clean any leftover state from a prior failed prepare attempt. Without this,// zstd refuses to overwrite an existing workspace.qcow2 and the retry fails@@ -691,7 +760,26 @@ func (m *Manager) PrepareIncomingMigrationWithS3(ctx context.Context, sandboxID,return "", 0, r.err}- return m.PrepareIncomingMigration(ctx, sandboxID, rootfsPath, workspacePath, cpus, memMB, guestPort, template)+ incomingAddr, hostPort, err = m.PrepareIncomingMigration(ctx, sandboxID, rootfsPath, workspacePath, cpus, memMB, guestPort, template)+ if err != nil {+ return "", 0, err+ }++ // Re-register the secrets-proxy session on this worker, keyed by the+ // guest IP we just allocated in PrepareIncomingMigration. Done before+ // returning so the source can issue the LiveMigrate RPC immediately+ // without a races window where the migrated VM is running but the+ // proxy has no substitution map.+ // An allowlist alone is enough — without a session the proxy 407s every request.+ if m.secretsProxy != nil && (len(secrets.SealedTokens) > 0 || len(secrets.EgressAllowlist) > 0) {+ if vm, getErr := m.getVM(sandboxID); getErr == nil && vm.network != nil && vm.network.GuestIP != "" {+ m.secretsProxy.ReregisterSession(sandboxID, vm.network.GuestIP, secrets.SealedTokens, secrets.EgressAllowlist, secrets.TokenHosts, secrets.SealedNames)+ log.Printf("qemu: migration %s: re-registered secrets proxy session (%d tokens, %d allowlist, guestIP=%s)",+ sandboxID, len(secrets.SealedTokens), len(secrets.EgressAllowlist), vm.network.GuestIP)+ }+ }++ return incomingAddr, hostPort, nil}// downloadS3ToFile downloads an S3 object to a local file.diff --git a/internal/qemu/network.go b/internal/qemu/network.goindex 710cbd55..4d59c491 100644--- a/internal/qemu/network.go+++ b/internal/qemu/network.go@@ -134,21 +134,24 @@ func CreateTAP(cfg *NetworkConfig) error {return fmt.Errorf("bring up %s: %w", cfg.TAPName, err)}- // Apply network rate limiting: 50 Mbps bandwidth + packet rate police.- // Prevents DDoS, network abuse, and protects host bandwidth.- // tc: token bucket filter on egress (VM → host → internet)+ // Apply network rate limiting: 500 Mbps bandwidth cap per VM.+ // Prevents noisy-neighbor abuse without throttling normal sandbox use.+ // Pre-fix the cap was 50 Mbps which was tight enough to noticeably slow+ // npm install, docker pull, model downloads, and large uploads — all+ // real-world sandbox workloads. 500 Mbps gives sandboxes a credible+ // link speed while still bounding aggregate worker NIC pressure.applyRateLimit(cfg.TAPName)return nil}// applyRateLimit sets tc rate limiting on a TAP device.-// 50 Mbps bandwidth cap + 10000 pps packet rate to prevent abuse.+// Token bucket filter: 500 Mbps sustained, 10 MB burst, 50 ms latency.+// Burst is sized so a typical TLS handshake + first request fits in one shot+// rather than being shaped from packet 1.func applyRateLimit(tapName string) {- // Egress from VM (ingress to TAP from host perspective)- // Use tc on the TAP device to limit what the VM can send out_ = run("tc", "qdisc", "add", "dev", tapName, "root", "tbf",- "rate", "50mbit", "burst", "1mb", "latency", "50ms")+ "rate", "500mbit", "burst", "10mb", "latency", "50ms")}// DeleteTAP removes a TAP device and its tc qdisc.diff --git a/internal/qemu/orphan_reaper.go b/internal/qemu/orphan_reaper.gonew file mode 100644index 00000000..aa7bbf94--- /dev/null+++ b/internal/qemu/orphan_reaper.go@@ -0,0 +1,187 @@+package qemu++import (+ "context"+ "log"+ "os"+ "path/filepath"+ "regexp"+ "strconv"+ "strings"+ "syscall"+ "time"+)++// orphanReapInterval is how often we scan /proc for leaked qemu processes.+// 60s is short enough that a leak doesn't accumulate for hours, long enough+// that the scan cost is negligible (one sweep of /proc per minute).+const orphanReapInterval = 60 * time.Second++// orphanGraceTermDelay is how long we wait between SIGTERM and SIGKILL when+// reaping an orphan. QEMU usually exits cleanly on SIGTERM within ~1s; 5s is+// generous and bounds the reap pass at ~5s per orphan in the worst case.+const orphanGraceTermDelay = 5 * time.Second++// sandboxIDRe extracts an sb-xxxxxxxx sandbox ID from a qemu command line.+// QEMU's cmdline embeds the sandboxDir as a -drive file=… and -chardev path=…+// argument, so the ID always appears in the form /data/sandboxes/sandboxes/sb-XXX/.+var sandboxIDRe = regexp.MustCompile(`/sandboxes/(sb-[a-z0-9]+)/`)++// StartOrphanReaper launches a background goroutine that periodically scans+// /proc for qemu-system processes whose sandbox ID is not in the worker's VM+// registry, and kills them.+//+// Why this is needed: when destroyVM races with a state inconsistency (e.g.,+// a hibernate-on-timeout that ran without the VM being in m.vms, a panic in+// a sandbox goroutine that exits before cleanup, or a worker crash that left+// children behind), a qemu-system-x86_64 process can survive past the worker's+// knowledge of it. Those orphans hold a TAP, an agent.sock, and a vCPU — they+// silently shrink real worker capacity until the worker is restarted. We saw+// this in the field: after a load test, Worker A had 2 zombie + 1 live qemu+// from a session that ended 30 minutes earlier, which then made every new+// fork on that worker fail.+func (m *Manager) StartOrphanReaper(ctx context.Context) {+ go m.orphanReaperLoop(ctx)+}++func (m *Manager) orphanReaperLoop(ctx context.Context) {+ ticker := time.NewTicker(orphanReapInterval)+ defer ticker.Stop()+ // First scan happens after one interval — gives the worker time to+ // register VMs at startup before we start judging them as orphans.+ for {+ select {+ case <-ctx.Done():+ return+ case <-ticker.C:+ m.reapOrphans()+ }+ }+}++// reapOrphans scans /proc for qemu-system processes belonging to sandboxes+// that are no longer in m.vms, and kills them.+func (m *Manager) reapOrphans() {+ pidByID, err := scanQEMUProcesses()+ if err != nil {+ log.Printf("qemu: orphan-reaper: scan failed: %v", err)+ return+ }+ if len(pidByID) == 0 {+ return+ }++ m.mu.RLock()+ known := make(map[string]bool, len(m.vms))+ for id := range m.vms {+ known[id] = true+ }+ m.mu.RUnlock()++ for sandboxID, pid := range pidByID {+ if known[sandboxID] {+ continue+ }+ log.Printf("qemu: orphan-reaper: found leaked qemu pid=%d sandbox=%s (not in vm registry), terminating",+ pid, sandboxID)+ if err := terminateAndWait(pid); err != nil {+ log.Printf("qemu: orphan-reaper: failed to terminate pid=%d: %v", pid, err)+ continue+ }+ // Best-effort sandbox dir cleanup. If destroyVM was supposed to remove+ // it but never did, do it now.+ sandboxDir := filepath.Join(m.cfg.DataDir, "sandboxes", "sandboxes", sandboxID)+ if _, err := os.Stat(sandboxDir); err == nil {+ if err := os.RemoveAll(sandboxDir); err != nil {+ log.Printf("qemu: orphan-reaper: removed pid=%d but failed to clean %s: %v",+ pid, sandboxDir, err)+ } else {+ log.Printf("qemu: orphan-reaper: cleaned up sandbox dir %s", sandboxDir)+ }+ }+ }+}++// scanQEMUProcesses walks /proc and returns a map of sandboxID -> pid for+// every qemu-system-x86_64 process whose cmdline references a sandbox dir.+func scanQEMUProcesses() (map[string]int, error) {+ procEntries, err := os.ReadDir("/proc")+ if err != nil {+ return nil, err+ }+ out := make(map[string]int)+ for _, entry := range procEntries {+ if !entry.IsDir() {+ continue+ }+ pid, err := strconv.Atoi(entry.Name())+ if err != nil {+ continue+ }+ // Read /proc/PID/comm — cheap, only ~16 bytes; skip non-qemu fast.+ commBytes, err := os.ReadFile(filepath.Join("/proc", entry.Name(), "comm"))+ if err != nil {+ continue+ }+ comm := strings.TrimSpace(string(commBytes))+ if !strings.HasPrefix(comm, "qemu-system") {+ continue+ }+ // /proc/PID/cmdline is NUL-separated; we scan it as a single blob.+ cmdlineBytes, err := os.ReadFile(filepath.Join("/proc", entry.Name(), "cmdline"))+ if err != nil {+ continue+ }+ cmdline := string(cmdlineBytes)+ match := sandboxIDRe.FindStringSubmatch(cmdline)+ if len(match) < 2 {+ continue+ }+ sandboxID := match[1]+ // Multiple qemu processes for the same sandbox shouldn't exist —+ // if they do, the first one wins; the duplicate will be reaped on+ // the next pass after the registered one is removed.+ if _, dup := out[sandboxID]; !dup {+ out[sandboxID] = pid+ }+ }+ return out, nil+}++// terminateAndWait sends SIGTERM, waits up to orphanGraceTermDelay, then+// SIGKILLs if the process is still alive. Returns nil if the process is+// gone (whatever the path).+func terminateAndWait(pid int) error {+ proc, err := os.FindProcess(pid)+ if err != nil {+ return err+ }+ // SIGTERM lets QEMU shut down its devices cleanly, which avoids leaving+ // stale qcow2 locks. If it's already wedged it won't help; we'll SIGKILL+ // after the grace window.+ _ = proc.Signal(syscall.SIGTERM)++ deadline := time.Now().Add(orphanGraceTermDelay)+ for time.Now().Before(deadline) {+ if !pidAlive(pid) {+ return nil+ }+ time.Sleep(200 * time.Millisecond)+ }+ if pidAlive(pid) {+ _ = proc.Kill()+ // Brief wait for kernel to flush the kill.+ for i := 0; i < 25 && pidAlive(pid); i++ {+ time.Sleep(40 * time.Millisecond)+ }+ }+ return nil+}++// pidAlive returns true if /proc/PID still exists. We don't use kill(0)+// because that fails with EPERM if the worker isn't root for some reason —+// /proc is more permissive.+func pidAlive(pid int) bool {+ _, err := os.Stat(filepath.Join("/proc", strconv.Itoa(pid)))+ return err == nil+}diff --git a/internal/qemu/qmp.go b/internal/qemu/qmp.goindex 1f79a10d..322c7fc1 100644--- a/internal/qemu/qmp.go+++ b/internal/qemu/qmp.go@@ -194,6 +194,15 @@ func (q *QMPClient) Quit() error {return err}+// SystemReset issues a hardware reset to the guest, equivalent to pressing+// the reset button on a physical machine. The QEMU process and its+// resources (TAP, drives, QMP socket) stay alive; the guest CPU is reset+// and re-runs the boot sequence from scratch. RAM contents are wiped.+func (q *QMPClient) SystemReset() error {+ _, err := q.execute(qmpCommand{Execute: "system_reset"}, 10*time.Second)+ return err+}+// QueryStatus returns the current VM status.func (q *QMPClient) QueryStatus() (*QMPStatus, error) {resp, err := q.execute(qmpCommand{Execute: "query-status"}, 10*time.Second)diff --git a/internal/qemu/reset.go b/internal/qemu/reset.gonew file mode 100644index 00000000..299a2a62--- /dev/null+++ b/internal/qemu/reset.go@@ -0,0 +1,313 @@+package qemu++import (+ "context"+ "encoding/json"+ "fmt"+ "log"+ "os"+ "os/exec"+ "path/filepath"+ "time"++ pb "github.com/opensandbox/opensandbox/proto/agent"+)++// RebootSandbox performs a soft, in-place guest reset on a running sandbox.+// The QEMU process, network (TAP/DNAT/host port), and disks all stay; only+// the guest CPU is reset and re-runs its boot path. This recovers the+// sandbox from in-guest wedges (zombie pile, OOM-killed agent, runaway+// processes) without touching anything externally observable.+//+// Implementation:+// 1. Best-effort `sync` via the agent so dirty pages reach the workspace+// disk before we pull the rug. Best-effort because the agent may already+// be wedged — that's the case we're trying to recover from.+// 2. QMP `system_reset`. Guest sees a hardware reset signal, kernel+// re-boots from scratch.+// 3. The host-side gRPC connection to the agent dies as virtio-serial+// resets. Close the old client, dial fresh after the new agent comes+// up.+// 4. Re-sync clock (the guest reboot doesn't preserve wall time).+func (m *Manager) RebootSandbox(ctx context.Context, sandboxID string) error {+ vm, err := m.getVM(sandboxID)+ if err != nil {+ return err+ }++ if !vm.opMu.TryLock() {+ return fmt.Errorf("another operation is in progress on sandbox %s — try again shortly", sandboxID)+ }+ defer vm.opMu.Unlock()++ if vm.qmp == nil {+ return fmt.Errorf("sandbox %s: QMP not connected (try power-cycle instead)", sandboxID)+ }++ t0 := time.Now()++ // Best-effort sync. If the agent is wedged this fails fast and we+ // continue — the user is reaching for reboot precisely because state+ // is broken, so we don't gate the recovery on a graceful sync.+ if vm.agent != nil {+ syncCtx, cancel := context.WithTimeout(ctx, 3*time.Second)+ _, _ = vm.agent.Exec(syncCtx, &pb.ExecRequest{Command: "sync", RunAsRoot: true})+ cancel()+ }++ // Close the host-side agent gRPC client. The underlying virtio-serial+ // socket will be torn down when the guest resets; we want a clean+ // shutdown of our end so it can be re-dialed.+ if vm.agent != nil {+ vm.agent.Close()+ vm.agent = nil+ }++ if err := vm.qmp.SystemReset(); err != nil {+ return fmt.Errorf("system_reset: %w", err)+ }++ // Wait for the new agent to boot inside the guest and reconnect via+ // virtio-serial. waitForAgentSocket dials with backoff and verifies a+ // gRPC handshake before returning.+ agentClient, err := m.waitForAgentSocket(ctx, vm.agentSockPath, 60*time.Second)+ if err != nil {+ return fmt.Errorf("agent did not reconnect after reboot: %w", err)+ }+ vm.agent = agentClient++ if err := syncGuestClock(ctx, agentClient); err != nil {+ log.Printf("qemu: RebootSandbox %s: clock sync failed: %v", sandboxID, err)+ }++ log.Printf("qemu: RebootSandbox %s: complete (%dms)", sandboxID, time.Since(t0).Milliseconds())+ return nil+}++// PowerCycleSandbox performs a hard reset: the QEMU VMM is killed and a+// fresh QEMU process is started with the same on-disk drives. The sandbox+// keeps its identity (ID, project, secrets, env, persistent workspace+// data) but gets a new TAP, host port, and PID. Use this when the QEMU+// process itself is wedged (QMP unresponsive) or a soft reboot didn't+// recover.+//+// We deliberately keep the existing rootfs.qcow2 — it carries any user+// system-package installs and /etc edits the customer made. Resetting all+// the way back to the template is a separate, more drastic operation.+//+// Returns the sandbox's new external host port (TAP/DNAT changed). Caller+// is expected to update any stored routing record.+func (m *Manager) PowerCycleSandbox(ctx context.Context, sandboxID string) (hostPort int, err error) {+ vm, err := m.getVM(sandboxID)+ if err != nil {+ return 0, err+ }++ if !vm.opMu.TryLock() {+ return 0, fmt.Errorf("another operation is in progress on sandbox %s — try again shortly", sandboxID)+ }+ defer vm.opMu.Unlock()++ t0 := time.Now()++ // Best-effort sync before we yank the rug. The QEMU drive is opened+ // with cache=writethrough so the host always has a consistent view+ // once the guest issues a write — but the guest kernel's own page+ // cache may hold dirty data that hasn't been flushed yet. Skipping+ // this lost a workspace file in dev testing.+ if vm.agent != nil {+ syncCtx, cancel := context.WithTimeout(ctx, 5*time.Second)+ _, _ = vm.agent.Exec(syncCtx, &pb.ExecRequest{Command: "sync", RunAsRoot: true})+ cancel()+ }++ // Step 1: Kill the current VM. Mirrors RestoreFromCheckpoint's teardown.+ if vm.agent != nil {+ vm.agent.Close()+ vm.agent = nil+ }+ if vm.qmp != nil {+ _ = vm.qmp.Quit()+ vm.qmp.Close()+ vm.qmp = nil+ }+ if vm.cmd != nil && vm.cmd.Process != nil {+ done := make(chan error, 1)+ go func() { done <- vm.cmd.Wait() }()+ select {+ case <-done:+ case <-time.After(5 * time.Second):+ vm.cmd.Process.Kill()+ <-done+ }+ }++ // Step 2: Tear down the old network. New TAP/host port will be+ // allocated below. We can't reuse the old subnet entry because we've+ // already started releasing it.+ if vm.network != nil {+ RemoveMetadataDNAT(vm.network.TAPName, vm.network.HostIP)+ RemoveDNAT(vm.network)+ DeleteTAP(vm.network.TAPName)+ m.subnets.Release(vm.network.TAPName)+ vm.network = nil+ }++ // Step 3: Re-read sandbox metadata so we boot with the same template+ // and resource shape. The on-disk rootfs.qcow2 / workspace.qcow2 are+ // unchanged — this is "same box, freshly powered."+ sandboxDir := vm.sandboxDir+ rootfsPath := filepath.Join(sandboxDir, "rootfs.qcow2")+ workspacePath := filepath.Join(sandboxDir, "workspace.qcow2")+ if !fileExists(rootfsPath) || !fileExists(workspacePath) {+ return 0, fmt.Errorf("sandbox %s: drives missing (rootfs=%v, workspace=%v)",+ sandboxID, fileExists(rootfsPath), fileExists(workspacePath))+ }++ var meta SandboxMeta+ if data, err := os.ReadFile(filepath.Join(sandboxDir, "sandbox-meta.json")); err == nil {+ _ = json.Unmarshal(data, &meta)+ }+ cpus := vm.CpuCount+ if cpus <= 0 {+ cpus = m.cfg.DefaultCPUs+ }+ // Boot the new QEMU at the ORIGINAL base memory and re-plug virtio-mem+ // to the prior amount after the agent comes up. Booting at vm.MemoryMB+ // (current total) bakes the scaled-up size into the QEMU `-m` flag,+ // which means subsequent shrinks below that size only adjust the cgroup+ // limit (additional clamps to 0) — the host can never give back the+ // memory until the sandbox is destroyed. Booting at base + re-plug+ // preserves the user-visible size while keeping virtio-mem unplug+ // available going forward.+ bootMemMB := vm.baseMemoryMB+ if bootMemMB <= 0 {+ bootMemMB = m.cfg.DefaultMemoryMB+ }+ prevPlugMB := vm.virtioMemRequestedMB+ memMB := bootMemMB+ guestPort := vm.GuestPort+ if guestPort == 0 {+ guestPort = meta.GuestPort+ }+ if guestPort == 0 {+ guestPort = 80+ }++ // Step 4: Allocate fresh network plumbing.+ netCfg, err := m.subnets.Allocate()+ if err != nil {+ return 0, fmt.Errorf("allocate subnet: %w", err)+ }+ if err := CreateTAP(netCfg); err != nil {+ m.subnets.Release(netCfg.TAPName)+ return 0, fmt.Errorf("create TAP: %w", err)+ }+ freshPort, err := FindFreePort()+ if err != nil {+ DeleteTAP(netCfg.TAPName)+ m.subnets.Release(netCfg.TAPName)+ return 0, fmt.Errorf("find free port: %w", err)+ }+ netCfg.HostPort = freshPort+ netCfg.GuestPort = guestPort+ if err := AddDNAT(netCfg); err != nil {+ DeleteTAP(netCfg.TAPName)+ m.subnets.Release(netCfg.TAPName)+ return 0, fmt.Errorf("add DNAT: %w", err)+ }+ if err := AddMetadataDNAT(netCfg.TAPName, netCfg.HostIP); err != nil {+ log.Printf("qemu: PowerCycleSandbox %s: metadata DNAT failed: %v", sandboxID, err)+ }++ // Step 5: Start a fresh QEMU.+ guestMAC := generateMAC(sandboxID)+ bootArgs := fmt.Sprintf(+ "console=ttyS0 reboot=k panic=1 root=/dev/vda rw ip=%s::%s:%s::eth0:off init=/sbin/init osb.gateway=%s",+ netCfg.GuestIP, netCfg.HostIP, netCfg.Mask, netCfg.HostIP,+ )+ qmpSockPath := filepath.Join(sandboxDir, "qmp.sock")+ agentSockPath := filepath.Join(sandboxDir, "agent.sock")+ os.Remove(qmpSockPath)+ os.Remove(agentSockPath)++ logFile, _ := os.Create(filepath.Join(sandboxDir, "qemu.log"))+ args := m.buildQEMUArgs(cpus, memMB, rootfsPath, workspacePath,+ netCfg.TAPName, guestMAC, agentSockPath, qmpSockPath, bootArgs)++ cmd := exec.Command(m.cfg.QEMUBin, args...)+ cmd.Stdout = logFile+ cmd.Stderr = logFile+ if err := cmd.Start(); err != nil {+ if logFile != nil {+ logFile.Close()+ }+ m.cleanupVM(netCfg, "")+ return 0, fmt.Errorf("start QEMU: %w", err)+ }+ if logFile != nil {+ logFile.Close()+ }++ qmpClient, err := waitForQMP(qmpSockPath, 30*time.Second)+ if err != nil {+ cmd.Process.Kill()+ cmd.Wait()+ m.cleanupVM(netCfg, "")+ return 0, fmt.Errorf("QMP connect: %w", err)+ }++ agentClient, err := m.waitForAgentSocket(ctx, agentSockPath, 60*time.Second)+ if err != nil {+ qmpClient.Close()+ cmd.Process.Kill()+ cmd.Wait()+ m.cleanupVM(netCfg, "")+ return 0, fmt.Errorf("agent connect: %w", err)+ }++ if err := syncGuestClock(ctx, agentClient); err != nil {+ log.Printf("qemu: PowerCycleSandbox %s: clock sync failed: %v", sandboxID, err)+ }++ // Step 5b: Re-plug virtio-mem to match the size the sandbox had before+ // the cycle. The fresh QEMU boots at base; we now bring it back to the+ // pre-cycle total so the user doesn't perceive a memory shrink. If the+ // re-plug fails, log loudly and continue at base — the sandbox is+ // alive and the user can re-scale via the API.+ finalMemMB := bootMemMB+ finalPlugMB := 0+ if prevPlugMB > 0 {+ if err := qmpClient.SetVirtioMemSize(prevPlugMB); err != nil {+ log.Printf("qemu: PowerCycleSandbox %s: virtio-mem re-plug %dMB failed: %v — sandbox alive at %dMB",+ sandboxID, prevPlugMB, err, bootMemMB)+ } else {+ finalPlugMB = prevPlugMB+ finalMemMB = bootMemMB + prevPlugMB+ log.Printf("qemu: PowerCycleSandbox %s: virtio-mem re-plugged %dMB (total %dMB)",+ sandboxID, prevPlugMB, finalMemMB)+ }+ }++ // Step 6: Swap fresh state into the existing VMInstance so callers+ // holding pointers to it continue to see a live sandbox. baseMemoryMB+ // stays at the original boot mem (preserves virtio-mem flexibility);+ // MemoryMB and virtioMemRequestedMB reflect the post-replug total.+ vm.cmd = cmd+ vm.qmp = qmpClient+ vm.agent = agentClient+ vm.network = netCfg+ vm.HostPort = freshPort+ vm.qmpSockPath = qmpSockPath+ vm.agentSockPath = agentSockPath+ vm.guestMAC = guestMAC+ vm.bootArgs = bootArgs+ vm.pid = cmd.Process.Pid+ vm.MemoryMB = finalMemMB+ vm.baseMemoryMB = bootMemMB+ vm.virtioMemRequestedMB = finalPlugMB++ log.Printf("qemu: PowerCycleSandbox %s: complete (%dms, port=%d, tap=%s)",+ sandboxID, time.Since(t0).Milliseconds(), freshPort, netCfg.TAPName)+ return freshPort, nil+}diff --git a/internal/qemu/snapshot.go b/internal/qemu/snapshot.goindex 131d27e5..2bab77e1 100644--- a/internal/qemu/snapshot.go+++ b/internal/qemu/snapshot.go@@ -36,6 +36,10 @@ type SnapshotMeta struct {GoldenVersion string `json:"goldenVersion,omitempty"`SnapshotedAt time.Time `json:"snapshotedAt,omitempty"`SealedTokens map[string]string `json:"sealedTokens,omitempty"`+ // SealedNames is the env-var-name → sealed-token index. Persisted alongside+ // SealedTokens so secret-store refresh-by-name (UpdateSecretValue) keeps+ // working after a wake or migration handoff.+ SealedNames map[string]string `json:"sealedNames,omitempty"`EgressAllowlist []string `json:"egressAllowlist,omitempty"`TokenHosts map[string][]string `json:"tokenHosts,omitempty"`}@@ -62,13 +66,20 @@ func (m *Manager) doHibernate(ctx context.Context, vm *VMInstance, checkpointStoreturn nil, fmt.Errorf("mkdir snapshot dir: %w", err)}- // Step 1: Sync filesystems and quiesce agent.+ // Step 1: Sync filesystems, quiesce agent, close host conn, and WAIT for+ // the guest to process EOF before savevm. See quiesceAndCloseAgent.// Don't unmount /workspace — open FDs prevent clean unmount and cause ext4 corruption.- // PrepareHibernate syncs dirty pages and resets the virtio-serial listener- // synchronously, so no post-close sleep is needed.+ //+ // If quiesce fails (agent unresponsive), DO NOT proceed to savevm: the+ // captured qcow2 would carry un-synced page cache + pending EXT4 journal+ // entries and become unbootable on the next cold-mount (inode #2 checksum+ // failure → kernel panic loop). Bubble the error up so the API caller+ // gets a clear refusal instead of a silently-corrupted sandbox.if vm.agent != nil {- prepareAgentForHibernate(ctx, vm.agent)- vm.agent.Close()+ if err := quiesceAndCloseAgent(ctx, vm.agent); err != nil {+ log.Printf("qemu: hibernate %s: refusing savevm — %v", vm.ID, err)+ return nil, fmt.Errorf("hibernate %s: %w", vm.ID, err)+ }vm.agent = nil}log.Printf("qemu: hibernate %s: guest sync + unmount done (%dms)", vm.ID, time.Since(t0).Milliseconds())@@ -76,12 +87,23 @@ func (m *Manager) doHibernate(ctx context.Context, vm *VMInstance, checkpointSto// Step 2: savevm — saves memory + device state INTO the qcow2 files.// Same mechanism as CreateCheckpoint. On wake, loadvm restores everything// including running processes, open files, and memory contents.+ //+ // Explicit Stop() before savevm: although savevm internally pauses and+ // resumes the VM, the explicit pause closes the small race where in-flight+ // virtio-blk writes from the guest can still land in the qcow2 between+ // the agent's `sync` and the start of savevm. Halting vCPUs first makes+ // the captured state strictly post-sync. doHibernate proceeds straight+ // to Quit on success, so leaving the VM in stopped state is fine; only+ // the failure path resumes (so we don't leak a wedged paused VM).if vm.qmp == nil {return nil, fmt.Errorf("no QMP client for VM %s", vm.ID)}snapshotName := "hibernate"+ if stopErr := vm.qmp.Stop(); stopErr != nil {+ return nil, fmt.Errorf("qmp stop before savevm: %w", stopErr)+ }if err := vm.qmp.SaveVM(snapshotName); err != nil {- // Try to resume VM so it's not left in a broken paused state+ // Resume so we don't leave the VM wedged paused on the error path.if contErr := vm.qmp.Cont(); contErr != nil {log.Printf("qemu: hibernate %s: failed to resume after savevm failure: %v", vm.ID, contErr)}@@ -132,6 +154,7 @@ func (m *Manager) doHibernate(ctx context.Context, vm *VMInstance, checkpointSto// Persist secrets proxy state so wake can re-register the session.if m.secretsProxy != nil && vm.network != nil {meta.SealedTokens = m.secretsProxy.GetSessionTokens(vm.network.GuestIP)+ meta.SealedNames = m.secretsProxy.GetSessionNames(vm.network.GuestIP)meta.EgressAllowlist = m.secretsProxy.GetSessionAllowlist(vm.network.GuestIP)meta.TokenHosts = m.secretsProxy.GetSessionTokenHosts(vm.network.GuestIP)}@@ -161,7 +184,16 @@ func (m *Manager) doHibernate(ctx context.Context, vm *VMInstance, checkpointStoos.Remove(vm.qmpSockPath)}- checkpointKey := fmt.Sprintf("checkpoints/%s/%d.tar.zst", vm.ID, time.Now().Unix())+ // Per-hibernation unique paths. Pre-fix used a single sandbox-scoped+ // `archive-staging/` and `checkpoint.tar.zst`, so back-to-back+ // hibernate→wake→hibernate cycles raced: the second hibernate's+ // copyFileReflink overwrote the first goroutine's staging files mid-tar,+ // and both goroutines wrote the same checkpoint.tar.zst path. End state:+ // neither blob landed in S3, the DB still showed both rows as hibernated,+ // and cross-worker wake failed with "blob: object not found". Including+ // UnixNano in the staging dir name is enough to make the paths unique.+ epochSec := time.Now().Unix()+ checkpointKey := fmt.Sprintf("checkpoints/%s/%d.tar.zst", vm.ID, epochSec)localElapsed := time.Since(t0)log.Printf("qemu: hibernate %s: local snapshot complete (%dms), starting async S3 upload",vm.ID, localElapsed.Milliseconds())@@ -176,7 +208,7 @@ func (m *Manager) doHibernate(ctx context.Context, vm *VMInstance, checkpointStoworkspaceFile := filepath.Base(detectDrivePath(sandboxDir, "workspace"))rootfsFile := filepath.Base(detectDrivePath(sandboxDir, "rootfs"))- archiveDir := filepath.Join(sandboxDir, "archive-staging")+ archiveDir := filepath.Join(sandboxDir, fmt.Sprintf("archive-staging-%d", time.Now().UnixNano()))if err := os.MkdirAll(archiveDir, 0755); err != nil {return nil, fmt.Errorf("mkdir archive-staging: %w", err)}@@ -205,19 +237,31 @@ func (m *Manager) doHibernate(ctx context.Context, vm *VMInstance, checkpointStolog.Printf("qemu: hibernate %s: rootfs rebase failed (archive may not be portable): %v (%s)",sandboxID, err, strings.TrimSpace(string(out)))}- log.Printf("qemu: hibernate %s: archive staging ready", sandboxID)+ log.Printf("qemu: hibernate %s: archive staging ready (dir=%s)", sandboxID, filepath.Base(archiveDir))// Signal channel so destroyVM can wait for archive completion before deleting files.archiveDone := make(chan struct{})vm.archiveDone = archiveDone+ uploadCb := m.onHibernationUploadm.uploadWg.Add(1)go func() {defer m.uploadWg.Done()defer close(archiveDone)defer os.RemoveAll(archiveDir) // clean up staging copies when done++ var sizeBytes int64+ var goroutineErr error+ defer func() {+ if uploadCb != nil {+ uploadCb(sandboxID, checkpointKey, sizeBytes, goroutineErr)+ }+ }()+t1 := time.Now()- archivePath := filepath.Join(sandboxDir, "checkpoint.tar.zst")+ // Tar lives inside the per-hibernation staging dir so concurrent+ // hibernations of the same sandbox don't write to the same path.+ archivePath := filepath.Join(archiveDir, "checkpoint.tar.zst")// Archive from the staging copies — originals are free for wake/QEMU.if err := createArchive(archivePath, archiveDir, []string{@@ -225,29 +269,30 @@ func (m *Manager) doHibernate(ctx context.Context, vm *VMInstance, checkpointStorootfsFile,workspaceFile,}); err != nil {+ goroutineErr = fmt.Errorf("archive: %w", err)log.Printf("qemu: async archive failed for %s: %v", sandboxID, err)return}archiveInfo, err := os.Stat(archivePath)if err != nil {+ goroutineErr = fmt.Errorf("stat archive: %w", err)log.Printf("qemu: async archive stat failed for %s: %v", sandboxID, err)return}+ sizeBytes = archiveInfo.Size()log.Printf("qemu: hibernate %s: archive created (%dms, %.1f MB)",- sandboxID, time.Since(t1).Milliseconds(), float64(archiveInfo.Size())/(1024*1024))+ sandboxID, time.Since(t1).Milliseconds(), float64(sizeBytes)/(1024*1024))t2 := time.Now()uploadCtx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)defer cancel()if _, err := checkpointStore.Upload(uploadCtx, checkpointKey, archivePath); err != nil {+ goroutineErr = fmt.Errorf("upload: %w", err)log.Printf("qemu: async S3 upload failed for %s: %v", sandboxID, err)- os.Remove(archivePath) // clean up — local qcow2 files are the source of truth for same-worker wake- return+ return // archiveDir cleanup via defer takes the tar with it}log.Printf("qemu: hibernate %s: S3 upload complete (%dms, key=%s)",sandboxID, time.Since(t2).Milliseconds(), checkpointKey)-- os.Remove(archivePath) // only delete after successful upload}()return &sandbox.HibernateResult{@@ -275,25 +320,11 @@ func (m *Manager) doWake(ctx context.Context, sandboxID, checkpointKey string, csnapshotDir := filepath.Join(sandboxDir, "snapshot")metaPath := filepath.Join(snapshotDir, "snapshot-meta.json")- // Wait for any in-flight hibernate archive to finish before proceeding.- // Same-worker wake: archive reads from staging copies (safe), but we need- // archive-staging/ cleaned up before starting QEMU to avoid disk waste.- // Cross-worker wake: S3 upload must complete before download can succeed.- archiveStagingDir := filepath.Join(sandboxDir, "archive-staging")- if fileExists(archiveStagingDir) {- log.Printf("qemu: wake %s: waiting for in-flight archive to complete", sandboxID)- for i := 0; i < 60; i++ { // up to 30 seconds- if !fileExists(archiveStagingDir) {- break- }- time.Sleep(500 * time.Millisecond)- }- if fileExists(archiveStagingDir) {- // Don't force-remove — the archive goroutine's defer will clean up.- // Removing while tar is mid-read corrupts the S3 archive.- log.Printf("qemu: wake %s: archive staging still present after 30s, proceeding (goroutine will clean up)", sandboxID)- }- }+ // Per-hibernation archive staging dirs are named `archive-staging-<nano>` and+ // each goroutine cleans up its own dir via defer. Wake doesn't need the+ // archive (same-worker uses local qcow2; cross-worker downloads from S3),+ // so there is nothing to wait for here. Pre-fix this loop watched a single+ // fixed `archive-staging/` path — irrelevant under the new scheme.// Step 1: Ensure qcow2 files are localt0 := time.Now()@@ -360,10 +391,31 @@ func (m *Manager) doWake(ctx context.Context, sandboxID, checkpointKey string, creturn nil, fmt.Errorf("workspace not found at %s", workspacePath)}- // Step 3: Set up network- netCfg, err := m.subnets.Allocate()- if err != nil {- return nil, fmt.Errorf("allocate subnet: %w", err)+ // Step 3: Set up network. Prefer the original TAP/subnet so the gateway+ // IP remains stable across hibernate→wake cycles. The VM's HTTPS_PROXY+ // env var was baked at create time pointing at the original gateway IP+ // (e.g. 172.16.0.1). If wake reallocates a fresh subnet, the env still+ // points at the stale gateway and every outbound HTTPS through the+ // secrets proxy times out — silent breakage of the entire proxy path+ // for any sandbox with a secret store.+ //+ // Fall back to a fresh allocation if the original block was claimed by a+ // different sandbox while this one was hibernated. The fallback path+ // will leave HTTPS_PROXY stale, so log a clear warning — operators who+ // see this in journal know why post-wake outbound HTTPS is broken.+ var netCfg *NetworkConfig+ if meta.Network != nil && meta.Network.TAPName != "" {+ netCfg, err = m.subnets.AllocateSpecific(meta.Network.TAPName)+ if err != nil {+ log.Printf("qemu: wake %s: original TAP %q unavailable (%v) — falling back to fresh subnet; HTTPS_PROXY env will be stale, outbound HTTPS through proxy will fail until sandbox is recreated",+ sandboxID, meta.Network.TAPName, err)+ }+ }+ if netCfg == nil {+ netCfg, err = m.subnets.Allocate()+ if err != nil {+ return nil, fmt.Errorf("allocate subnet: %w", err)+ }}if err := CreateTAP(netCfg); err != nil {m.subnets.Release(netCfg.TAPName)@@ -452,6 +504,26 @@ func (m *Manager) doWake(ctx context.Context, sandboxID, checkpointKey string, creturn m.coldBootLocal(ctx, sandboxID, timeout)}+ // Re-plug virtio-mem to match the pre-hibernate total BEFORE Cont. The VM+ // is paused, so the kernel sees the full memory map immediately on resume+ // — without this, restored processes that were using more than baseMem+ // OOM before any post-resume scale could land. Mirrors the+ // RestoreFromCheckpoint path (manager.go:2536). Also keeps host-side+ // accounting honest: vm.MemoryMB stays equal to what's actually plugged,+ // not the ceiling, so TotalCommittedMemoryMB reflects reality.+ pluggedMB := 0+ if meta.MemoryMB > baseMem {+ additionalMB := alignVirtioMemBlock(meta.MemoryMB - baseMem)+ if err := qmpClient.SetVirtioMemSize(additionalMB); err != nil {+ log.Printf("qemu: wake %s: pre-resume virtio-mem plug to %dMB failed: %v (continuing with base %dMB)",+ sandboxID, additionalMB, err, baseMem)+ } else {+ pluggedMB = additionalMB+ log.Printf("qemu: wake %s: pre-resume virtio-mem plug %dMB (base=%d, total=%d)",+ sandboxID, additionalMB, baseMem, baseMem+additionalMB)+ }+ }+if err := qmpClient.Cont(); err != nil {qmpClient.Close()cmd.Process.Kill()@@ -488,11 +560,23 @@ func (m *Manager) doWake(ctx context.Context, sandboxID, checkpointKey string, clog.Printf("qemu: wake %s: clock sync failed: %v", sandboxID, err)}- // Re-register secrets proxy session from persisted tokens.- if m.secretsProxy != nil && len(meta.SealedTokens) > 0 {- m.secretsProxy.ReregisterSession(sandboxID, netCfg.GuestIP, meta.SealedTokens, meta.EgressAllowlist, meta.TokenHosts)- log.Printf("qemu: wake %s: re-registered secrets proxy session (%d tokens)", sandboxID, len(meta.SealedTokens))+ // Re-register secrets proxy session from persisted tokens. An allowlist+ // alone is enough — without a session the proxy 407s every request.+ if m.secretsProxy != nil && (len(meta.SealedTokens) > 0 || len(meta.EgressAllowlist) > 0) {+ m.secretsProxy.ReregisterSession(sandboxID, netCfg.GuestIP, meta.SealedTokens, meta.EgressAllowlist, meta.TokenHosts, meta.SealedNames)+ log.Printf("qemu: wake %s: re-registered secrets proxy session (%d tokens, %d allowlist, %d names)", sandboxID, len(meta.SealedTokens), len(meta.EgressAllowlist), len(meta.SealedNames))}+ // Refresh the proxy CA in the guest's trust store. Wake may land on a+ // different worker than the one that hibernated the sandbox, in which+ // case the cert in the guest's trust store no longer matches what this+ // worker's proxy presents. Idempotent on same-worker wake.+ m.reinstallProxyCA(context.Background(), sandboxID, agentClient)++ // Re-apply the apt-cache bind-mount. Idempotent: no-op if already in place+ // (e.g., same-worker wake where the loadvm-restored mount table preserved+ // the bind). On cross-worker wake or sandboxes that pre-date this fix,+ // this is the first chance to set it up.+ m.setupAptCacheBindMount(context.Background(), sandboxID, agentClient)log.Printf("qemu: wake %s: golden restore complete (port=%d, tap=%s)",sandboxID, hostPort, netCfg.TAPName)@@ -504,16 +588,17 @@ func (m *Manager) doWake(ctx context.Context, sandboxID, checkpointKey string, c}vm := &VMInstance{- ID: sandboxID,- Template: meta.Template,- Status: types.SandboxStatusRunning,- StartedAt: now,- EndAt: now.Add(ttl),- CpuCount: meta.CpuCount,- MemoryMB: meta.MemoryMB,- baseMemoryMB: baseMem,- HostPort: hostPort,- GuestPort: netCfg.GuestPort,+ ID: sandboxID,+ Template: meta.Template,+ Status: types.SandboxStatusRunning,+ StartedAt: now,+ EndAt: now.Add(ttl),+ CpuCount: meta.CpuCount,+ MemoryMB: baseMem + pluggedMB, // actually-plugged total, not the ceiling — keeps committed accounting honest+ baseMemoryMB: baseMem,+ virtioMemRequestedMB: pluggedMB,+ HostPort: hostPort,+ GuestPort: netCfg.GuestPort,pid: cmd.Process.Pid,cmd: cmd,network: netCfg,@@ -526,6 +611,14 @@ func (m *Manager) doWake(ctx context.Context, sandboxID, checkpointKey string, cbootArgs: bootArgs,goldenVersion: m.goldenVersion, // set on wake — VM runs on the current worker's base}+ // Recompute virtio-mem amount from the meta. Without this the field+ // stays at zero on wake, which would (a) make grow deltas under-charge+ // the host capacity check and (b) make the shrink-OOM-floor in+ // SetResourceLimits silently no-op since `additional == requested == 0`+ // is treated as "no change" and skips the check entirely.+ if meta.MemoryMB > baseMem {+ vm.virtioMemRequestedMB = meta.MemoryMB - baseMem+ }vm.agent = agentClient// Agent binary updates happen via qemu-img rebase of the rootfs, not via@@ -796,15 +889,33 @@ func copyFileReflink(src, dst string) error {}// syncGuestClock sets the guest clock to the current host time via agent exec.+//+// Wraps the underlying RPC with a 10s deadline (caller-side timeout, NOT just+// the agent-side TimeoutSeconds) and one Redial-on-transport-error retry. Prior+// version used the caller's context.Background() which had no deadline at all,+// so a wedged virtio-serial channel would block until gRPC keepalive (~7 min)+// gave up. That stall is what produced the multi-minute "from-checkpoint"+// requests in load tests.func syncGuestClock(ctx context.Context, agent *AgentClient) error {now := time.Now().Unix()- cmd := fmt.Sprintf("date -s @%d > /dev/null 2>&1", now)- resp, err := agent.Exec(ctx, &pb.ExecRequest{+ req := &pb.ExecRequest{Command: "/bin/sh",- Args: []string{"-c", cmd},+ Args: []string{"-c", fmt.Sprintf("date -s @%d > /dev/null 2>&1", now)},TimeoutSeconds: 5,RunAsRoot: true,- })+ }+ rpcCtx, cancel := context.WithTimeout(ctx, 10*time.Second)+ defer cancel()+ resp, err := agent.Exec(rpcCtx, req)+ if err != nil && IsTransportError(err) {+ log.Printf("qemu: syncGuestClock: transport error %v, redialing and retrying once", err)+ if rdErr := agent.Redial(); rdErr != nil {+ return fmt.Errorf("clock sync redial: %w (orig: %v)", rdErr, err)+ }+ rpcCtx2, cancel2 := context.WithTimeout(ctx, 10*time.Second)+ defer cancel2()+ resp, err = agent.Exec(rpcCtx2, req)+ }if err != nil {return fmt.Errorf("exec clock sync: %w", err)}diff --git a/internal/qemu/stats_collector.go b/internal/qemu/stats_collector.gonew file mode 100644index 00000000..3c3d38c6--- /dev/null+++ b/internal/qemu/stats_collector.go@@ -0,0 +1,122 @@+package qemu++import (+ "context"+ "sync"+ "time"++ "github.com/opensandbox/opensandbox/internal/sandbox"+)++// SandboxStatsCache holds the latest per-sandbox resource snapshots gathered+// by a periodic background collector. The autoscaler in the control plane+// reads these via the worker's heartbeat — see internal/worker/redis_heartbeat.go.+//+// Why a cache: collecting stats requires a gRPC round-trip to the agent in+// each VM (over virtio-serial). Doing that lazily inside the heartbeat publish+// path would block heartbeats for ~5-10ms × N sandboxes. A separate goroutine+// polls in parallel and the heartbeat reads from a snapshot map — heartbeats+// stay fast and stats are at most one collection interval stale.+type SandboxStatsCache struct {+ mu sync.RWMutex+ stats map[string]sandbox.SandboxStats // sandboxID → latest snapshot+}++// StartStatsCollector launches a goroutine that polls every running sandbox's+// agent.Stats and caches the response. The heartbeat path reads the cached+// snapshot. Stops when ctx is cancelled.+//+// Concurrency: limited to 8 in-flight collections so a worker hosting 100++// sandboxes doesn't spike its virtio-serial channel pool. 100 sandboxes × 10ms+// per call ÷ 8 concurrent ≈ 125ms per collection round. Comfortable inside+// the 10s heartbeat cadence.+func (m *Manager) StartStatsCollector(ctx context.Context, interval time.Duration) {+ if m.statsCache == nil {+ m.statsCache = &SandboxStatsCache{stats: make(map[string]sandbox.SandboxStats)}+ }+ go func() {+ ticker := time.NewTicker(interval)+ defer ticker.Stop()+ // Collect once immediately so the first heartbeat after worker boot+ // has data instead of an empty map.+ m.collectAllStats(ctx)+ for {+ select {+ case <-ctx.Done():+ return+ case <-ticker.C:+ m.collectAllStats(ctx)+ }+ }+ }()+}++func (m *Manager) collectAllStats(ctx context.Context) {+ m.mu.RLock()+ ids := make([]string, 0, len(m.vms))+ for id := range m.vms {+ ids = append(ids, id)+ }+ m.mu.RUnlock()++ const maxConcurrent = 8+ sem := make(chan struct{}, maxConcurrent)+ var wg sync.WaitGroup+ for _, id := range ids {+ wg.Add(1)+ sem <- struct{}{}+ go func(sandboxID string) {+ defer wg.Done()+ defer func() { <-sem }()++ statsCtx, cancel := context.WithTimeout(ctx, 3*time.Second)+ defer cancel()+ stats, err := m.Stats(statsCtx, sandboxID)+ if err != nil {+ // Stats call can fail transiently (agent restarting, etc.)+ // We just skip this sandbox this round; next collection picks+ // it up. Stale entry stays in cache for one cycle which is+ // fine for the autoscaler — it's looking at moving averages+ // over a 1-15 min window.+ return+ }+ m.statsCache.mu.Lock()+ m.statsCache.stats[sandboxID] = *stats+ m.statsCache.mu.Unlock()+ }(id)+ }+ wg.Wait()++ // Prune entries for vanished sandboxes so the cache doesn't leak across+ // destroy events.+ m.mu.RLock()+ live := make(map[string]bool, len(m.vms))+ for id := range m.vms {+ live[id] = true+ }+ m.mu.RUnlock()++ m.statsCache.mu.Lock()+ for id := range m.statsCache.stats {+ if !live[id] {+ delete(m.statsCache.stats, id)+ }+ }+ m.statsCache.mu.Unlock()+}++// GetAllSandboxStats returns a snapshot map of the latest cached stats. Safe+// to call concurrently with the collector. Used by the heartbeat to populate+// the per-sandbox stats portion of the worker:* Redis entry.+func (m *Manager) GetAllSandboxStats() map[string]sandbox.SandboxStats {+ if m.statsCache == nil {+ return nil+ }+ m.statsCache.mu.RLock()+ defer m.statsCache.mu.RUnlock()+ out := make(map[string]sandbox.SandboxStats, len(m.statsCache.stats))+ for id, s := range m.statsCache.stats {+ out[id] = s+ }+ return out+}diff --git a/internal/qemu/virtio_mem_test.go b/internal/qemu/virtio_mem_test.gonew file mode 100644index 00000000..04419421--- /dev/null+++ b/internal/qemu/virtio_mem_test.go@@ -0,0 +1,41 @@+package qemu++import "testing"++func TestAlignVirtioMemBlock(t *testing.T) {+ tests := []struct {+ name string+ in int+ want int+ }{+ {"zero stays zero", 0, 0},+ {"negative stays zero", -10, 0},+ {"exactly one block", 128, 128},+ {"under one block rounds up", 1, 128},+ {"between blocks rounds up", 200, 256},+ {"exactly two blocks", 256, 256},+ {"non-aligned mid-range", 1000, 1024},+ {"aligned 1GB", 1024, 1024},+ {"7GB-ish — wake replug case", 7168, 7168},+ {"7GB-ish minus a hair", 7167, 7168},+ {"7GB-ish plus a hair", 7169, 7296},+ // 16GB ceiling — buildQEMUArgs uses 16384-base; test the boundary.+ {"16GB", 16384, 16384},+ {"16GB minus base 1024", 16384 - 1024, 15360},+ }+ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ got := alignVirtioMemBlock(tc.in)+ if got != tc.want {+ t.Errorf("alignVirtioMemBlock(%d) = %d, want %d", tc.in, got, tc.want)+ }+ if got > 0 && got%virtioMemBlockSizeMB != 0 {+ t.Errorf("alignVirtioMemBlock(%d) = %d is not a multiple of block size %d",+ tc.in, got, virtioMemBlockSizeMB)+ }+ if tc.in > 0 && got < tc.in {+ t.Errorf("alignVirtioMemBlock(%d) = %d, must round up (>= input)", tc.in, got)+ }+ })+ }+}diff --git a/internal/sandbox/interface.go b/internal/sandbox/interface.goindex 8bab4e86..a91523ff 100644--- a/internal/sandbox/interface.go+++ b/internal/sandbox/interface.go@@ -15,6 +15,27 @@ type HibernateResult struct {SizeBytes int64 `json:"sizeBytes"`}+// MigrationSecrets is the per-sandbox secrets-proxy state that must move+// with the VM during a live migration. The proxy keeps these in-process+// per-worker (see internal/secretsproxy), so without an explicit handoff+// the destination has no substitution map and the guest's env vars+// (`osb_sealed_xxx`) leak verbatim to upstream services. Hibernate+// persists the same data into snapshot-meta.json; live migration carries+// it through the PreCopyDrives → PrepareMigrationIncoming RPC chain.+//+// Lives in package sandbox (not qemu) so the worker grpc layer can name+// it without importing qemu (which would create a cycle).+type MigrationSecrets struct {+ SealedTokens map[string]string+ EgressAllowlist []string+ TokenHosts map[string][]string+ // SealedNames is the env-var-name → sealed-token index. Carried across+ // migration so refresh-by-name (UpdateSecretValue) keeps working on the+ // destination. Without it, post-migration secret-store updates would+ // silently miss because the destination's session has no name index.+ SealedNames map[string]string+}+// SandboxStats holds live resource usage for a sandbox.// Runtime-agnostic interface for sandbox resource stats.type SandboxStats struct {@@ -55,6 +76,13 @@ type Manager interface {// Resource limitsSetResourceLimits(ctx context.Context, sandboxID string, maxPids int32, maxMemoryBytes, cpuMaxUsec, cpuPeriodUsec int64) error+ // UpdateSandboxSecret refreshes the proxy session value for one secret name+ // (env var name) without changing the sealed token id seen by the sandbox.+ // Used by the secret-store-update flow to push new values to running+ // sandboxes. Returns (true, nil) on success; (false, nil) if no session+ // or no name match (transient miss e.g. mid-migration; caller logs).+ UpdateSandboxSecret(ctx context.Context, sandboxID, secretName, value string) (bool, error)+// MonitoringStats(ctx context.Context, sandboxID string) (*SandboxStats, error)HostPort(ctx context.Context, sandboxID string) (int, error)@@ -68,12 +96,24 @@ type Manager interface {Hibernate(ctx context.Context, sandboxID string, checkpointStore *storage.CheckpointStore) (*HibernateResult, error)Wake(ctx context.Context, sandboxID string, checkpointKey string, checkpointStore *storage.CheckpointStore, timeout int) (*types.Sandbox, error)+ // Reset operations. RebootSandbox is a soft, in-place guest restart;+ // PowerCycleSandbox is a hard restart that re-creates the QEMU process+ // with the same on-disk drives. Both preserve the sandbox's identity+ // and persistent data; power-cycle returns a new external host port.+ RebootSandbox(ctx context.Context, sandboxID string) error+ PowerCycleSandbox(ctx context.Context, sandboxID string) (newHostPort int, err error)+// TemplateCachePath returns the local path to a cached template drive file (e.g., "rootfs.ext4"),// or "" if the template is not cached locally. Used to skip S3 download when creating from template.TemplateCachePath(templateID, filename string) string- // Checkpointing- CreateCheckpoint(ctx context.Context, sandboxID, checkpointID string, checkpointStore *storage.CheckpointStore, onReady func()) (rootfsKey, workspaceKey string, err error)+ // Checkpointing.+ // CreateCheckpoint returns rootfs/workspace S3 keys, the actual archive+ // size in bytes (0 when no checkpoint store is configured or upload+ // failed), and any error. sizeBytes plumbs through to+ // store.SetCheckpointReady so the DB row carries the truthful archive+ // size instead of the previous hardcoded 0.+ CreateCheckpoint(ctx context.Context, sandboxID, checkpointID string, checkpointStore *storage.CheckpointStore, onReady func()) (rootfsKey, workspaceKey string, sizeBytes int64, err error)RestoreFromCheckpoint(ctx context.Context, sandboxID, checkpointID string) errorForkFromCheckpoint(ctx context.Context, checkpointID string, cfg types.SandboxConfig) (*types.Sandbox, error)CheckpointCachePath(checkpointID, filename string) stringdiff --git a/internal/secrets/keyvault.go b/internal/secrets/keyvault.goindex e599d82f..ea59a701 100644--- a/internal/secrets/keyvault.go+++ b/internal/secrets/keyvault.go@@ -107,9 +107,14 @@ func (b *KeyVaultBackend) LoadAllToEnv(ctx context.Context) (loaded, skipped intif !mapped {continue}+ // Bypass the mode filter for genuinely shared keys:+ // - "pg-" — historic, postgres bootstrap shared between server/worker+ // - "shared-" — formal "this secret goes to both modes" prefix+ // (e.g. shared-axiom-ingest-token, shared-cell-id)if b.ModePrefixFilter != "" &&!strings.HasPrefix(name, b.ModePrefixFilter+"-") &&- !strings.HasPrefix(name, "pg-") {+ !strings.HasPrefix(name, "pg-") &&+ !strings.HasPrefix(name, "shared-") {continue}if os.Getenv(envVar) != "" {diff --git a/internal/secrets/secretsmanager.go b/internal/secrets/secretsmanager.goindex ef093c18..f41220a7 100644--- a/internal/secrets/secretsmanager.go+++ b/internal/secrets/secretsmanager.go@@ -120,7 +120,8 @@ func (b *SecretsManagerBackend) LoadAllToEnv(ctx context.Context) (loaded, skipp}if b.ModePrefixFilter != "" &&!strings.HasPrefix(k, b.ModePrefixFilter+"-") &&- !strings.HasPrefix(k, "pg-") {+ !strings.HasPrefix(k, "pg-") &&+ !strings.HasPrefix(k, "shared-") {continue}if os.Getenv(envVar) != "" {diff --git a/internal/secretsproxy/ca_shared.go b/internal/secretsproxy/ca_shared.gonew file mode 100644index 00000000..50f8de2c--- /dev/null+++ b/internal/secretsproxy/ca_shared.go@@ -0,0 +1,194 @@+package secretsproxy++import (+ "context"+ "crypto/ecdsa"+ "crypto/elliptic"+ "crypto/rand"+ "crypto/x509"+ "crypto/x509/pkix"+ "encoding/pem"+ "errors"+ "fmt"+ "math/big"+ "os"+ "path/filepath"+ "sync"+ "time"+)++// KVStore is a tiny KV-shaped interface a shared CA loader uses to+// publish/fetch the CA cert and key. Backed by Azure Key Vault, AWS Secrets+// Manager, or anything else that maps a string name to an opaque blob.+//+// Implementations must:+// - Get returns ErrNotFound (or any error) when the name doesn't exist;+// the caller treats both as "go generate".+// - Set is allowed to overwrite. The shared-CA loader handles races by+// re-reading after writing — last writer wins, then everyone converges+// on what's actually in the store.+type KVStore interface {+ Get(ctx context.Context, name string) ([]byte, error)+ Set(ctx context.Context, name string, value []byte) error+}++// ErrNotFound is the canonical "this key doesn't exist" sentinel that KVStore+// implementations should return when a Get misses. Callers can check via+// errors.Is — though the loader treats any Get error as a miss anyway.+var ErrNotFound = errors.New("secretsproxy: KV key not found")++// LoadOrCreateSharedCA fetches the proxy CA from a region-scoped KV, or+// generates one and publishes it. Required for live migration: each worker+// in the region MUST present the same CA so a sandbox migrated between+// workers continues to trust the proxy's MITM TLS certs (the source's CA+// cert is baked into the guest's trust store — if the destination's proxy+// presents certs signed by a different CA, every outbound HTTPS call after+// migration fails with "authority and subject key identifier mismatch").+//+// The function is idempotent under concurrent worker startup: multiple+// workers booting at once may each generate locally, but after the+// re-fetch step they all converge on whatever cert ended up in KV.+//+// fallbackDir is mirrored from KV so an operator can inspect the cert with+// `openssl x509` and so the worker has a copy if KV becomes briefly+// unreachable later.+func LoadOrCreateSharedCA(ctx context.Context, kv KVStore, certName, keyName, fallbackDir string) (*CA, error) {+ if kv == nil {+ // No shared store configured — fall back to per-worker behavior.+ // Live migration of secrets-proxy-using sandboxes will TLS-fail+ // across worker boundaries, but at least single-worker setups+ // keep working. Production deployments should always pass a KV.+ return LoadOrCreateCA(fallbackDir)+ }+ if err := os.MkdirAll(fallbackDir, 0700); err != nil {+ return nil, fmt.Errorf("create CA dir: %w", err)+ }++ // 1. Try to fetch the existing shared CA.+ if certPEM, keyPEM, err := fetchSharedCA(ctx, kv, certName, keyName); err == nil {+ ca, parseErr := parseCA(certPEM, keyPEM)+ if parseErr != nil {+ // The KV value exists but is corrupted. Refusing here is+ // safer than regenerating (which would silently invalidate+ // every existing sandbox's trust store).+ return nil, fmt.Errorf("shared CA in KV is malformed: %w", parseErr)+ }+ if writeErr := mirrorCAToDir(fallbackDir, certPEM, keyPEM); writeErr != nil {+ // Non-fatal — we have a valid CA in memory.+ fmt.Fprintf(os.Stderr, "secretsproxy: mirror CA to %s failed: %v\n", fallbackDir, writeErr)+ }+ return ca, nil+ }++ // 2. KV miss — generate a fresh CA.+ certPEM, keyPEM, err := generateCAPEM()+ if err != nil {+ return nil, fmt.Errorf("generate shared CA: %w", err)+ }++ // 3. Publish to KV. If publish fails we continue with the locally-+ // generated CA so the worker can still serve sandboxes — but live+ // migration to other workers will still mismatch certs until the+ // publish succeeds on a future restart.+ pubCertErr := kv.Set(ctx, certName, certPEM)+ pubKeyErr := kv.Set(ctx, keyName, keyPEM)+ if pubCertErr != nil || pubKeyErr != nil {+ fmt.Fprintf(os.Stderr, "secretsproxy: publishing shared CA to KV failed (cert=%v key=%v) — using local CA only\n", pubCertErr, pubKeyErr)+ ca, parseErr := parseCA(certPEM, keyPEM)+ if parseErr != nil {+ return nil, fmt.Errorf("parse generated CA: %w", parseErr)+ }+ _ = mirrorCAToDir(fallbackDir, certPEM, keyPEM)+ return ca, nil+ }++ // 4. Race resolution: another worker may have published a CA between+ // our miss and our Set. Re-fetch and prefer whatever's actually in+ // the store as canonical. This converges all racing workers onto a+ // single CA without needing a distributed lock.+ if remoteCert, remoteKey, refetchErr := fetchSharedCA(ctx, kv, certName, keyName); refetchErr == nil {+ if !pemEqual(remoteCert, certPEM) || !pemEqual(remoteKey, keyPEM) {+ ca, parseErr := parseCA(remoteCert, remoteKey)+ if parseErr == nil {+ _ = mirrorCAToDir(fallbackDir, remoteCert, remoteKey)+ return ca, nil+ }+ }+ }++ ca, parseErr := parseCA(certPEM, keyPEM)+ if parseErr != nil {+ return nil, fmt.Errorf("parse generated CA: %w", parseErr)+ }+ _ = mirrorCAToDir(fallbackDir, certPEM, keyPEM)+ return ca, nil+}++func fetchSharedCA(ctx context.Context, kv KVStore, certName, keyName string) ([]byte, []byte, error) {+ certPEM, certErr := kv.Get(ctx, certName)+ if certErr != nil {+ return nil, nil, certErr+ }+ keyPEM, keyErr := kv.Get(ctx, keyName)+ if keyErr != nil {+ return nil, nil, keyErr+ }+ if len(certPEM) == 0 || len(keyPEM) == 0 {+ return nil, nil, ErrNotFound+ }+ return certPEM, keyPEM, nil+}++func generateCAPEM() (certPEM, keyPEM []byte, err error) {+ key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)+ if err != nil {+ return nil, nil, fmt.Errorf("generate key: %w", err)+ }+ serial, _ := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))+ tmpl := &x509.Certificate{+ SerialNumber: serial,+ Subject: pkix.Name{+ CommonName: "OpenSandbox Proxy CA",+ Organization: []string{"OpenSandbox"},+ },+ NotBefore: time.Now().Add(-time.Minute),+ NotAfter: time.Now().Add(caValidYears * 365 * 24 * time.Hour),+ KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,+ BasicConstraintsValid: true,+ IsCA: true,+ }+ certDER, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)+ if err != nil {+ return nil, nil, fmt.Errorf("create cert: %w", err)+ }+ certPEM = pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certDER})+ keyDER, err := x509.MarshalECPrivateKey(key)+ if err != nil {+ return nil, nil, fmt.Errorf("marshal key: %w", err)+ }+ keyPEM = pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: keyDER})+ return certPEM, keyPEM, nil+}++var mirrorMu sync.Mutex++func mirrorCAToDir(dir string, certPEM, keyPEM []byte) error {+ mirrorMu.Lock()+ defer mirrorMu.Unlock()+ if err := os.WriteFile(filepath.Join(dir, "ca.crt"), certPEM, 0644); err != nil {+ return err+ }+ return os.WriteFile(filepath.Join(dir, "ca.key"), keyPEM, 0600)+}++func pemEqual(a, b []byte) bool {+ if len(a) != len(b) {+ return false+ }+ for i := range a {+ if a[i] != b[i] {+ return false+ }+ }+ return true+}diff --git a/internal/secretsproxy/kvstore_azure.go b/internal/secretsproxy/kvstore_azure.gonew file mode 100644index 00000000..cdc6dee2--- /dev/null+++ b/internal/secretsproxy/kvstore_azure.go@@ -0,0 +1,66 @@+package secretsproxy++import (+ "context"+ "errors"+ "fmt"+ "strings"++ "github.com/Azure/azure-sdk-for-go/sdk/azcore"+ "github.com/Azure/azure-sdk-for-go/sdk/azidentity"+ "github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets"+)++// AzureKVStore is a KVStore backed by Azure Key Vault. Uses the+// DefaultAzureCredential chain (managed identity in production, az-cli /+// service principal in dev).+type AzureKVStore struct {+ client *azsecrets.Client+}++// NewAzureKVStore opens a client against the named Key Vault. vaultName is+// the short name (e.g. "opensandbox-dev-kv"); the URL is derived. Returns+// nil + error if credentials can't be obtained or the vault URL is invalid.+func NewAzureKVStore(vaultName string) (*AzureKVStore, error) {+ if vaultName == "" {+ return nil, errors.New("vault name required")+ }+ cred, err := azidentity.NewDefaultAzureCredential(nil)+ if err != nil {+ return nil, fmt.Errorf("azure credentials: %w", err)+ }+ url := fmt.Sprintf("https://%s.vault.azure.net/", vaultName)+ client, err := azsecrets.NewClient(url, cred, nil)+ if err != nil {+ return nil, fmt.Errorf("kv client: %w", err)+ }+ return &AzureKVStore{client: client}, nil+}++func (s *AzureKVStore) Get(ctx context.Context, name string) ([]byte, error) {+ resp, err := s.client.GetSecret(ctx, name, "", nil)+ if err != nil {+ // Azure SDK doesn't expose a direct "not found" sentinel, but the+ // ResponseError carries the status code.+ var respErr *azcore.ResponseError+ if errors.As(err, &respErr) && respErr.StatusCode == 404 {+ return nil, ErrNotFound+ }+ // SecretNotFound is the canonical body code for the same condition;+ // older SDK versions surface it as a string rather than via status.+ if strings.Contains(err.Error(), "SecretNotFound") {+ return nil, ErrNotFound+ }+ return nil, err+ }+ if resp.Value == nil {+ return nil, ErrNotFound+ }+ return []byte(*resp.Value), nil+}++func (s *AzureKVStore) Set(ctx context.Context, name string, value []byte) error {+ v := string(value)+ _, err := s.client.SetSecret(ctx, name, azsecrets.SetSecretParameters{Value: &v}, nil)+ return err+}diff --git a/internal/secretsproxy/proxy.go b/internal/secretsproxy/proxy.goindex 652f86bb..df8a390d 100644--- a/internal/secretsproxy/proxy.go+++ b/internal/secretsproxy/proxy.go@@ -11,11 +11,52 @@ import ("log""net""net/http"+ "os/exec""strings""sync""time")+// AnycastAddr is the link-local IP every VM uses to reach the secrets proxy.+// One byte off the metadata server (169.254.169.254) so the two services have+// adjacent, easy-to-remember addresses.+//+// Why link-local instead of the per-VM TAP gateway: HTTPS_PROXY is baked into+// the VM env at create time. If we used the gateway IP, that env became stale+// the moment the VM moved to a different /30 subnet (wake → reallocated+// block, migrate → different worker's allocator). Customers saw "every+// outbound HTTPS times out post-handoff" because the env pointed at an+// unreachable address. Link-local is host-scoped, so each worker answers the+// same address locally — the env is correct on whichever host the VM lives on.+const (+ AnycastIP = "169.254.169.253"+ AnycastPort = 3128+)++// AnycastEndpoint returns the proxy URL VMs should use as HTTPS_PROXY.+func AnycastEndpoint() string {+ return fmt.Sprintf("http://%s:%d", AnycastIP, AnycastPort)+}++// EnsureAnycastInterface assigns AnycastIP to the loopback interface so the+// kernel answers it locally. Idempotent — succeeds even if already assigned+// (the underlying `ip addr add` returns "File exists" which we treat as ok).+//+// Worker startup must call this before sandboxes are created or the proxy+// won't be reachable at the stable address.+func EnsureAnycastInterface() error {+ cmd := exec.Command("ip", "addr", "add", AnycastIP+"/32", "dev", "lo")+ out, err := cmd.CombinedOutput()+ if err != nil {+ // "RTNETLINK answers: File exists" → already configured, fine.+ if strings.Contains(string(out), "File exists") {+ return nil+ }+ return fmt.Errorf("ip addr add %s/32 dev lo: %w (%s)", AnycastIP, err, strings.TrimSpace(string(out)))+ }+ return nil+}+// privateIPNets contains the CIDR ranges considered private/internal.// Connections to these ranges are blocked to prevent SSRF attacks.var privateIPNets []*net.IPNet@@ -57,6 +98,7 @@ const (type Session struct {SandboxID stringSecrets map[string]string // "osb_sealed_xxx" → real value+ Names map[string]string // envVarName → "osb_sealed_xxx" — lets us update by name without re-sealingTokenHosts map[string][]string // sealed token → allowed hosts; nil/empty entry = all allowed hostsAllowlist []string // nil = all hosts allowed; supports "*." prefix wildcardsExpiresAt time.Time@@ -178,12 +220,26 @@ func (p *SecretsProxy) GetSessionTokenHosts(guestIP string) map[string][]stringreturn session.TokenHosts}+// GetSessionNames returns the env-var-name → sealed-token map for the given+// guest IP's session. Used to persist the name index across hibernate/wake+// and live migration so secret-refresh-by-name keeps working after a handoff.+func (p *SecretsProxy) GetSessionNames(guestIP string) map[string]string {+ p.mu.RLock()+ session := p.sessions[guestIP]+ p.mu.RUnlock()+ if session == nil {+ return nil+ }+ return session.Names+}+// ReregisterSession creates a new proxy session from a previously persisted token map.// Used on wake to restore the proxy session without re-generating tokens.-func (p *SecretsProxy) ReregisterSession(sandboxID, guestIP string, tokens map[string]string, allowlist []string, tokenHosts map[string][]string) {+func (p *SecretsProxy) ReregisterSession(sandboxID, guestIP string, tokens map[string]string, allowlist []string, tokenHosts map[string][]string, names map[string]string) {session := &Session{SandboxID: sandboxID,Secrets: tokens,+ Names: names,TokenHosts: tokenHosts,Allowlist: allowlist,ExpiresAt: time.Now().Add(defaultSessionTTL),@@ -191,19 +247,51 @@ func (p *SecretsProxy) ReregisterSession(sandboxID, guestIP string, tokens map[sp.mu.Lock()p.sessions[guestIP] = sessionp.mu.Unlock()- log.Printf("secrets-proxy: re-registered session sandbox=%s ip=%s secrets=%d allowlist=%d tokenHosts=%d",- sandboxID, guestIP, len(tokens), len(allowlist), len(tokenHosts))+ log.Printf("secrets-proxy: re-registered session sandbox=%s ip=%s secrets=%d allowlist=%d tokenHosts=%d names=%d",+ sandboxID, guestIP, len(tokens), len(allowlist), len(tokenHosts), len(names))+}++// UpdateSecretValue replaces the value the sealed token for `secretName` resolves+// to, on the session for the given sandbox. The sealed token ID itself stays+// the same — sandbox env vars don't change, but the next outbound HTTPS that+// the proxy substitutes uses the new value.+//+// Returns true if the update landed (session found, name matched a known+// sealed token, value replaced). Returns false if there's no session for the+// sandbox or the name isn't in the session — caller can use this to log a+// stale/missed update.+func (p *SecretsProxy) UpdateSecretValue(sandboxID, secretName, newValue string) bool {+ p.mu.Lock()+ defer p.mu.Unlock()+ for _, session := range p.sessions {+ if session.SandboxID != sandboxID {+ continue+ }+ token, ok := session.Names[secretName]+ if !ok {+ return false+ }+ if session.Secrets == nil {+ session.Secrets = make(map[string]string, 1)+ }+ session.Secrets[token] = newValue+ log.Printf("secrets-proxy: updated value for sandbox=%s name=%s (token unchanged)", sandboxID, secretName)+ return true+ }+ return false}// CreateSealedEnvs generates sealed tokens for the given env vars, registers a// proxy session, and returns the complete env map to inject into the VM.// Includes sealed tokens + proxy config vars (HTTP_PROXY, CA certs, etc.).-// Returns nil if envVars is empty.+// Returns nil only if there is nothing to enforce: no envs, no secrets, and no+// allowlist. An allowlist alone is still enough to require routing through the+// proxy so the allowlist actually gates egress.//// allowlist controls which hosts the sandbox can reach (nil = all).// secretAllowedHosts maps env var name → allowed hosts for that secret (nil = all allowed hosts).func (p *SecretsProxy) CreateSealedEnvs(sandboxID, guestIP, gatewayIP string, plaintextEnvs, secretEnvs map[string]string, allowlist []string, secretAllowedHosts map[string][]string) map[string]string {- if len(plaintextEnvs) == 0 && len(secretEnvs) == 0 {+ if len(plaintextEnvs) == 0 && len(secretEnvs) == 0 && len(allowlist) == 0 {return nil}@@ -237,18 +325,39 @@ func (p *SecretsProxy) CreateSealedEnvs(sandboxID, guestIP, gatewayIP string, pl}}- // Only register a proxy session if there's actually something to substitute.- if len(tokenMap) > 0 {+ // Register a proxy session whenever the sandbox has anything for the proxy+ // to act on: tokens to substitute OR an egress allowlist to enforce. Without+ // a session the proxy rejects every CONNECT with 407 no_session, so an+ // allowlist-only store would otherwise leave the sandbox with zero egress.+ if len(tokenMap) > 0 || len(allowlist) > 0 {+ // Build the env-var-name → sealed-token index. Required for+ // UpdateSecretValue (refresh-by-name without re-sealing). Always+ // included on the session so allowlist-only stores can later add+ // secrets via UpdateSecretValue without dropping the session.+ names := make(map[string]string, len(sealed))+ for envVar, token := range sealed {+ names[envVar] = token+ }p.RegisterSession(guestIP, &Session{SandboxID: sandboxID,Secrets: tokenMap,+ Names: names,TokenHosts: tokenHosts,Allowlist: allowlist,})}// Merge into the env map for the VM. plaintextEnvs win on collision.- proxyURL := fmt.Sprintf("http://%s:3128", gatewayIP)+ //+ // Use the anycast link-local address (169.254.169.253:3128) instead of the+ // per-VM gateway IP. The env value is baked into the VM at create time and+ // must keep working through hibernate/wake (subnet may be reallocated) and+ // live migration (target worker has its own subnet allocator). Each worker+ // answers the anycast IP locally on lo (see EnsureAnycastInterface) so the+ // VM reaches the right proxy regardless of which host it's currently on.+ // gatewayIP is still a parameter for backwards compat / non-anycast paths.+ _ = gatewayIP+ proxyURL := AnycastEndpoint()caCertPath := "/usr/local/share/ca-certificates/opensandbox-proxy.crt"noProxy := "localhost,127.0.0.1,::1"diff --git a/internal/secretsproxy/proxy_test.go b/internal/secretsproxy/proxy_test.gonew file mode 100644index 00000000..624cfd28--- /dev/null+++ b/internal/secretsproxy/proxy_test.go@@ -0,0 +1,253 @@+package secretsproxy++import (+ "io"+ "log"+ "reflect"+ "testing"+)++// newProxyForTest builds a SecretsProxy with no listener — sufficient for+// exercising session registration / CreateSealedEnvs without going on the wire.+//+// Sets the package-global log output to io.Discard for the duration of the+// test. bench_test.go leaves log.SetOutput(nil) behind on cleanup, which would+// otherwise panic any log.Printf in tests that run after it.+func newProxyForTest(t *testing.T) *SecretsProxy {+ t.Helper()+ log.SetOutput(io.Discard)+ return &SecretsProxy{+ sessions: make(map[string]*Session),+ closed: make(chan struct{}),+ }+}++func TestCreateSealedEnvs_AllowlistOnlyRegistersSession(t *testing.T) {+ p := newProxyForTest(t)++ allowlist := []string{"example.com", "api.openai.com"}+ envs := p.CreateSealedEnvs("sb-test", "10.0.0.5", "10.0.0.1",+ map[string]string{"FOO": "bar"}, // user envs+ nil, // no secret envs+ allowlist, // allowlist only+ nil,+ )++ if envs == nil {+ t.Fatal("CreateSealedEnvs returned nil; expected non-nil env map for allowlist-only sandbox")+ }+ if envs["HTTPS_PROXY"] == "" {+ t.Errorf("expected HTTPS_PROXY to be injected when allowlist is set; got %q", envs["HTTPS_PROXY"])+ }++ got := p.sessions["10.0.0.5"]+ if got == nil {+ t.Fatal("no session registered for guest IP; allowlist-only sandboxes must still get a session")+ }+ if !reflect.DeepEqual(got.Allowlist, allowlist) {+ t.Errorf("session allowlist = %v, want %v", got.Allowlist, allowlist)+ }+ if len(got.Secrets) != 0 {+ t.Errorf("session unexpectedly has secrets: %v", got.Secrets)+ }+}++func TestCreateSealedEnvs_NoEnvsNoSecretsNoAllowlistReturnsNil(t *testing.T) {+ p := newProxyForTest(t)+ envs := p.CreateSealedEnvs("sb-empty", "10.0.0.6", "10.0.0.1", nil, nil, nil, nil)+ if envs != nil {+ t.Errorf("expected nil env map when there is nothing to enforce; got %v", envs)+ }+ if _, exists := p.sessions["10.0.0.6"]; exists {+ t.Errorf("did not expect a registered session when there is nothing to enforce")+ }+}++func TestCreateSealedEnvs_AllowlistOnlyEnforcesViaSession(t *testing.T) {+ p := newProxyForTest(t)+ p.CreateSealedEnvs("sb-allow", "10.0.0.7", "10.0.0.1",+ map[string]string{"K": "v"},+ nil,+ []string{"example.com"},+ nil,+ )++ sess := p.sessions["10.0.0.7"]+ if sess == nil {+ t.Fatal("allowlist-only session should be registered")+ }+ if !hostAllowed("example.com", sess.Allowlist) {+ t.Errorf("example.com should be allowed by registered session")+ }+ if hostAllowed("evil.com", sess.Allowlist) {+ t.Errorf("evil.com should NOT be allowed by registered session")+ }+}++func TestCreateSealedEnvs_SecretsOnlyStillRegisters(t *testing.T) {+ // Regression guard: the pre-fix behavior (register only when secrets exist)+ // must still hold. Sandboxes with secrets but no allowlist get a session.+ p := newProxyForTest(t)+ p.CreateSealedEnvs("sb-secret", "10.0.0.8", "10.0.0.1",+ nil,+ map[string]string{"API_KEY": "real-secret"},+ nil,+ nil,+ )++ sess := p.sessions["10.0.0.8"]+ if sess == nil {+ t.Fatal("session must still register when only secrets are present")+ }+ if len(sess.Secrets) != 1 {+ t.Errorf("expected 1 sealed secret in session; got %d", len(sess.Secrets))+ }+ if len(sess.Allowlist) != 0 {+ t.Errorf("expected empty allowlist; got %v", sess.Allowlist)+ }+}++// TestCreateSealedEnvs_NamesIndexBuilt asserts the env-var-name → sealed-token+// index is populated whenever a session is registered. UpdateSecretValue uses+// this index; if it isn't built, refresh-by-name silently misses every time.+func TestCreateSealedEnvs_NamesIndexBuilt(t *testing.T) {+ cases := []struct {+ name string+ secretEnvs map[string]string+ allowlist []string+ wantNames []string // env var names expected in session.Names+ guestIP string+ }{+ {+ name: "secrets only",+ secretEnvs: map[string]string{"API_KEY": "v1", "DB_URL": "v2"},+ allowlist: nil,+ wantNames: []string{"API_KEY", "DB_URL"},+ guestIP: "10.0.0.10",+ },+ {+ name: "secrets + allowlist",+ secretEnvs: map[string]string{"TOKEN": "v"},+ allowlist: []string{"api.example.com"},+ wantNames: []string{"TOKEN"},+ guestIP: "10.0.0.11",+ },+ {+ name: "allowlist only",+ secretEnvs: nil,+ allowlist: []string{"api.example.com"},+ wantNames: []string{}, // no secrets, no name entries — but session still exists+ guestIP: "10.0.0.12",+ },+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ p := newProxyForTest(t)+ p.CreateSealedEnvs("sb-"+tc.name, tc.guestIP, "10.0.0.1",+ nil, tc.secretEnvs, tc.allowlist, nil)+ sess := p.sessions[tc.guestIP]+ if sess == nil {+ t.Fatal("expected session to be registered")+ }+ if len(sess.Names) != len(tc.wantNames) {+ t.Errorf("session.Names len = %d, want %d (names=%v)", len(sess.Names), len(tc.wantNames), sess.Names)+ }+ for _, n := range tc.wantNames {+ token, ok := sess.Names[n]+ if !ok {+ t.Errorf("expected Names[%q] to be set", n)+ continue+ }+ // And the token must point back to a real entry in Secrets.+ if _, ok := sess.Secrets[token]; !ok {+ t.Errorf("Names[%q] = %q but Secrets has no such token (index out of sync)", n, token)+ }+ }+ })+ }+}++// TestUpdateSecretValue_HappyPath replaces the value the sealed token resolves+// to without changing the token id. Sandbox env vars stay the same; the next+// outbound HTTPS substitution uses the new value.+func TestUpdateSecretValue_HappyPath(t *testing.T) {+ p := newProxyForTest(t)+ p.CreateSealedEnvs("sb-update", "10.0.0.20", "10.0.0.1",+ nil,+ map[string]string{"API_KEY": "old-value"},+ nil, nil,+ )+ sess := p.sessions["10.0.0.20"]+ if sess == nil {+ t.Fatal("expected session")+ }+ originalToken, ok := sess.Names["API_KEY"]+ if !ok {+ t.Fatal("expected API_KEY in Names index")+ }++ if !p.UpdateSecretValue("sb-update", "API_KEY", "new-value") {+ t.Fatal("UpdateSecretValue returned false on a known sandbox+name")+ }++ // Sealed token id must NOT change — VM env vars hold this string.+ tokenAfter, ok := sess.Names["API_KEY"]+ if !ok || tokenAfter != originalToken {+ t.Errorf("sealed token id changed: before=%q after=%q (must be stable so guest env vars stay valid)", originalToken, tokenAfter)+ }+ if got := sess.Secrets[originalToken]; got != "new-value" {+ t.Errorf("Secrets[token] = %q, want %q", got, "new-value")+ }+}++// TestUpdateSecretValue_NameMiss covers a refresh for a name the session+// doesn't know about — possible mid-migration or if the customer added a new+// secret to the store after the sandbox was created (env vars are baked at+// create-time, so a brand new name has no sealed token in the session).+// Returns false; caller logs but doesn't treat as fatal.+func TestUpdateSecretValue_NameMiss(t *testing.T) {+ p := newProxyForTest(t)+ p.CreateSealedEnvs("sb-miss", "10.0.0.21", "10.0.0.1",+ nil,+ map[string]string{"API_KEY": "v"},+ nil, nil,+ )+ if p.UpdateSecretValue("sb-miss", "UNKNOWN_NAME", "x") {+ t.Error("UpdateSecretValue returned true for an unknown name; expected false")+ }+ // Existing secret untouched.+ sess := p.sessions["10.0.0.21"]+ tok := sess.Names["API_KEY"]+ if sess.Secrets[tok] != "v" {+ t.Errorf("existing secret value clobbered by miss; got %q", sess.Secrets[tok])+ }+}++// TestUpdateSecretValue_NoSession covers fanout to a worker that has no+// session for the sandbox — happens during the brief window where the source+// has unregistered post-migration but the destination hasn't re-registered+// yet, or when the worker simply isn't hosting the sandbox. Must not panic+// and must return false.+func TestUpdateSecretValue_NoSession(t *testing.T) {+ p := newProxyForTest(t)+ if p.UpdateSecretValue("sb-nope", "API_KEY", "x") {+ t.Error("UpdateSecretValue returned true with no registered session; expected false")+ }+}++// TestUpdateSecretValue_NamesNilNoPanic guards the "session exists but Names+// is nil" case — possible for sessions registered before the SealedNames+// index existed (e.g. a sandbox hibernated on an old binary, woken on a new+// one with no SealedNames in snapshot-meta.json). Must return false, not+// crash.+func TestUpdateSecretValue_NamesNilNoPanic(t *testing.T) {+ p := newProxyForTest(t)+ p.RegisterSession("10.0.0.22", &Session{+ SandboxID: "sb-legacy",+ Secrets: map[string]string{"osb_sealed_xxx": "value"},+ // Names intentionally nil — pre-fix session shape.+ })+ if p.UpdateSecretValue("sb-legacy", "API_KEY", "x") {+ t.Error("UpdateSecretValue returned true on a session with nil Names; expected false")+ }+}diff --git a/internal/storage/blob.go b/internal/storage/blob.godeleted file mode 100644index 8a81ca86..00000000--- a/internal/storage/blob.go+++ /dev/null@@ -1,71 +0,0 @@-// Package storage provides blob storage backends for checkpoint archives.-//-// BlobClient is the abstraction — implementations exist for Azure Blob Storage-// (default) and AWS S3. The CheckpointStore uses a BlobClient for all remote-// operations (upload, download, head, delete).-//-// Detection is automatic: if the endpoint contains ".blob.core.windows.net",-// the Azure client is used. Otherwise, the AWS S3 client is used.-package storage--import (- "context"- "errors"- "fmt"- "io"- "strings"-)--// ErrNotFound is returned by Head / Download when the object does not exist.-// Callers should use errors.Is(err, ErrNotFound) — other errors (auth, network,-// etc.) must not be treated as "not found" to avoid triggering spurious-// uploads/retries on real outages.-var ErrNotFound = errors.New("blob: object not found")--// BlobClient abstracts remote object storage operations.-// Implementations: azureBlobClient (Azure Blob Storage), s3BlobClient (AWS S3).-type BlobClient interface {- // Upload writes data from reader to the given key. Returns bytes written.- Upload(ctx context.Context, bucket, key string, body io.ReadSeeker, contentLength int64) error- // Download returns a reader for the object at the given key.- Download(ctx context.Context, bucket, key string) (io.ReadCloser, error)- // DownloadRange returns a reader for a byte range of the object.- DownloadRange(ctx context.Context, bucket, key string, offset, length int64) (io.ReadCloser, error)- // Head returns the content length of the object, or error if not found.- Head(ctx context.Context, bucket, key string) (int64, error)- // Delete removes the object at the given key.- Delete(ctx context.Context, bucket, key string) error- // BackendName returns a human-readable name for the storage backend (e.g. "S3", "Azure Blob").- BackendName() string-}--// NewBlobClient creates the appropriate blob client based on the endpoint.-// Azure Blob Storage endpoints (*.blob.core.windows.net) use the native Azure SDK.-// All other endpoints use the AWS S3 SDK.-func NewBlobClient(cfg S3Config) (BlobClient, error) {- if strings.Contains(cfg.Endpoint, ".blob.core.windows.net") {- return newAzureBlobClient(cfg)- }- return newS3BlobClient(cfg)-}--// newAzureBlobClient creates an Azure Blob Storage client.-func newAzureBlobClient(cfg S3Config) (BlobClient, error) {- // Azure Blob Storage uses the storage account name as the access key ID- // and the account key as the secret. The endpoint is the full URL.- connStr := fmt.Sprintf(- "DefaultEndpointsProtocol=https;AccountName=%s;AccountKey=%s;EndpointSuffix=core.windows.net",- cfg.AccessKeyID, cfg.SecretAccessKey,- )- return &azureBlobClient{connStr: connStr}, nil-}--// newS3BlobClient creates an AWS S3-compatible client.-func newS3BlobClient(cfg S3Config) (BlobClient, error) {- // Reuse the existing S3 client setup- client, err := buildS3Client(cfg)- if err != nil {- return nil, err- }- return &s3BlobClient{client: client}, nil-}diff --git a/internal/storage/blob_azure.go b/internal/storage/blob_azure.godeleted file mode 100644index d570c000..00000000--- a/internal/storage/blob_azure.go+++ /dev/null@@ -1,100 +0,0 @@-package storage--import (- "context"- "fmt"- "io"- "strings"-- "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"- "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/bloberror"-)--// azureBlobClient implements BlobClient using the native Azure Blob SDK.-type azureBlobClient struct {- client *azblob.Client- connStr string-}--func (c *azureBlobClient) BackendName() string { return "Azure Blob" }--// normalizeKey strips the container name prefix from the key if present.-// S3 keys often include the bucket name (e.g., "checkpoints/sb-xxx/...") because-// S3 treats bucket and key as separate. Azure Blob uses container + blob name,-// so we strip the redundant prefix to avoid "container/container/..." paths.-func normalizeKey(container, key string) string {- prefix := container + "/"- if strings.HasPrefix(key, prefix) {- return strings.TrimPrefix(key, prefix)- }- return key-}--func (c *azureBlobClient) ensureClient() error {- if c.client != nil {- return nil- }- client, err := azblob.NewClientFromConnectionString(c.connStr, nil)- if err != nil {- return fmt.Errorf("azure blob: %w", err)- }- c.client = client- return nil-}--func (c *azureBlobClient) Upload(ctx context.Context, container, key string, body io.ReadSeeker, contentLength int64) error {- if err := c.ensureClient(); err != nil {- return err- }- _, err := c.client.UploadStream(ctx, container, normalizeKey(container, key), body, nil)- return err-}--func (c *azureBlobClient) Download(ctx context.Context, container, key string) (io.ReadCloser, error) {- if err := c.ensureClient(); err != nil {- return nil, err- }- resp, err := c.client.DownloadStream(ctx, container, normalizeKey(container, key), nil)- if err != nil {- return nil, err- }- return resp.Body, nil-}--func (c *azureBlobClient) DownloadRange(ctx context.Context, container, key string, offset, length int64) (io.ReadCloser, error) {- if err := c.ensureClient(); err != nil {- return nil, err- }- resp, err := c.client.DownloadStream(ctx, container, normalizeKey(container, key), &azblob.DownloadStreamOptions{- Range: azblob.HTTPRange{Offset: offset, Count: length},- })- if err != nil {- return nil, err- }- return resp.Body, nil-}--func (c *azureBlobClient) Head(ctx context.Context, container, key string) (int64, error) {- if err := c.ensureClient(); err != nil {- return 0, err- }- resp, err := c.client.ServiceClient().NewContainerClient(container).NewBlobClient(normalizeKey(container, key)).GetProperties(ctx, nil)- if err != nil {- if bloberror.HasCode(err, bloberror.BlobNotFound) {- return 0, ErrNotFound- }- return 0, err- }- if resp.ContentLength == nil {- return 0, nil- }- return *resp.ContentLength, nil-}--func (c *azureBlobClient) Delete(ctx context.Context, container, key string) error {- if err := c.ensureClient(); err != nil {- return err- }- _, err := c.client.DeleteBlob(ctx, container, normalizeKey(container, key), nil)- return err-}diff --git a/internal/storage/blob_s3.go b/internal/storage/blob_s3.godeleted file mode 100644index aef46b2e..00000000--- a/internal/storage/blob_s3.go+++ /dev/null@@ -1,121 +0,0 @@-package storage--import (- "context"- "errors"- "fmt"- "io"- "strings"-- "github.com/aws/aws-sdk-go-v2/aws"- awsconfig "github.com/aws/aws-sdk-go-v2/config"- "github.com/aws/aws-sdk-go-v2/credentials"- "github.com/aws/aws-sdk-go-v2/service/s3"- s3types "github.com/aws/aws-sdk-go-v2/service/s3/types"-)--// s3BlobClient implements BlobClient using the AWS S3 SDK.-type s3BlobClient struct {- client *s3.Client-}--func (c *s3BlobClient) BackendName() string { return "S3" }--// buildS3Client creates an S3 client from config.-func buildS3Client(cfg S3Config) (*s3.Client, error) {- forcePathStyle := cfg.ForcePathStyle- if !forcePathStyle && strings.Contains(cfg.Endpoint, ".blob.core.windows.net") {- forcePathStyle = true- }-- if cfg.AccessKeyID != "" {- opts := []func(*s3.Options){- func(o *s3.Options) {- o.Region = cfg.Region- o.Credentials = credentials.NewStaticCredentialsProvider(- cfg.AccessKeyID, cfg.SecretAccessKey, "",- )- if forcePathStyle {- o.UsePathStyle = true- }- if cfg.Endpoint != "" {- o.BaseEndpoint = aws.String(cfg.Endpoint)- }- },- }- return s3.New(s3.Options{}, opts...), nil- }-- awsCfg, err := awsconfig.LoadDefaultConfig(context.Background(),- awsconfig.WithRegion(cfg.Region),- )- if err != nil {- return nil, fmt.Errorf("failed to load AWS config: %w", err)- }- var s3Opts []func(*s3.Options)- if forcePathStyle {- s3Opts = append(s3Opts, func(o *s3.Options) { o.UsePathStyle = true })- }- if cfg.Endpoint != "" {- s3Opts = append(s3Opts, func(o *s3.Options) { o.BaseEndpoint = aws.String(cfg.Endpoint) })- }- return s3.NewFromConfig(awsCfg, s3Opts...), nil-}--func (c *s3BlobClient) Upload(ctx context.Context, bucket, key string, body io.ReadSeeker, contentLength int64) error {- _, err := c.client.PutObject(ctx, &s3.PutObjectInput{- Bucket: aws.String(bucket),- Key: aws.String(key),- Body: body,- ContentLength: aws.Int64(contentLength),- })- return err-}--func (c *s3BlobClient) Download(ctx context.Context, bucket, key string) (io.ReadCloser, error) {- resp, err := c.client.GetObject(ctx, &s3.GetObjectInput{- Bucket: aws.String(bucket),- Key: aws.String(key),- })- if err != nil {- return nil, err- }- return resp.Body, nil-}--func (c *s3BlobClient) DownloadRange(ctx context.Context, bucket, key string, offset, length int64) (io.ReadCloser, error) {- rangeStr := fmt.Sprintf("bytes=%d-%d", offset, offset+length-1)- resp, err := c.client.GetObject(ctx, &s3.GetObjectInput{- Bucket: aws.String(bucket),- Key: aws.String(key),- Range: aws.String(rangeStr),- })- if err != nil {- return nil, err- }- return resp.Body, nil-}--func (c *s3BlobClient) Head(ctx context.Context, bucket, key string) (int64, error) {- resp, err := c.client.HeadObject(ctx, &s3.HeadObjectInput{- Bucket: aws.String(bucket),- Key: aws.String(key),- })- if err != nil {- var nsk *s3types.NoSuchKey- var nf *s3types.NotFound- if errors.As(err, &nsk) || errors.As(err, &nf) {- return 0, ErrNotFound- }- return 0, err- }- return aws.ToInt64(resp.ContentLength), nil-}--func (c *s3BlobClient) Delete(ctx context.Context, bucket, key string) error {- _, err := c.client.DeleteObject(ctx, &s3.DeleteObjectInput{- Bucket: aws.String(bucket),- Key: aws.String(key),- })- return err-}diff --git a/internal/storage/s3.go b/internal/storage/s3.goindex cc8905b0..628ba214 100644--- a/internal/storage/s3.go+++ b/internal/storage/s3.go@@ -10,13 +10,21 @@ import ("os""path/filepath""sort"+ "strings""sync""time"+ "github.com/opensandbox/opensandbox/internal/blobstore""golang.org/x/sys/unix")-// S3Config holds the configuration for the S3 storage backend.+// ErrNotFound is re-exported from blobstore so existing callers+// (errors.Is(err, storage.ErrNotFound)) keep working.+var ErrNotFound = blobstore.ErrNotFound++// S3Config holds the configuration for the checkpoint store's backend.+// The "S3" in the name is historical — the same config drives Azure Blob via+// blobstore.NewAzure when the endpoint resolves there.type S3Config struct {Endpoint stringBucket string@@ -26,42 +34,67 @@ type S3Config struct {ForcePathStyle bool}-// CheckpointStore manages checkpoint archives in S3-compatible object storage,-// with an optional local NVMe cache for fast same-machine wake.+// CheckpointStore manages checkpoint archives in object storage, with an+// optional local NVMe cache for fast same-machine wake.//-// S3 is always the source of truth. Local NVMe is a hot cache.-// On hibernate: CRIU checkpoint + workspace both uploaded to S3, kept locally.-// On wake: check NVMe first, fall back to S3 download.+// Object storage is always the source of truth. Local NVMe is a hot cache.+// On hibernate: CRIU checkpoint + workspace both uploaded, kept locally.+// On wake: check NVMe first, fall back to object-store download.// Eviction: LRU based on real filesystem pressure (keep 20% free for active sandboxes).type CheckpointStore struct {- blob BlobClient+ blob blobstore.Storebucket stringcacheDir string // local NVMe cache for CRIU checkpoints (empty = disabled)cacheMu sync.Mutex}-// NewCheckpointStoreFromClient creates a CheckpointStore using an existing-// BlobClient. Useful for testing with a mock backend.-func NewCheckpointStoreFromClient(blob BlobClient, bucket string) *CheckpointStore {- return &CheckpointStore{blob: blob, bucket: bucket}+// NewCheckpointStoreFromStore creates a CheckpointStore wrapping a+// pre-constructed blobstore.Store. Use this when the worker has already+// built a Store (e.g. with FallbackStore wrapping primary+fallback) and+// wants the same instance shared with the checkpoint code path.+func NewCheckpointStoreFromStore(store blobstore.Store, bucket string) *CheckpointStore {+ return &CheckpointStore{blob: store, bucket: bucket}}-// NewCheckpointStore creates a new checkpoint store.-// Automatically selects Azure Blob or AWS S3 based on the endpoint URL.+// NewCheckpointStore creates a new checkpoint store from an S3Config,+// auto-detecting Azure Blob or S3-compatible based on the endpoint URL.+//+// Prefer NewCheckpointStoreFromStore when the caller already has a configured+// blobstore.Store (e.g. with fallback wrapping). This constructor exists for+// simple single-backend setups.func NewCheckpointStore(cfg S3Config) (*CheckpointStore, error) {- blob, err := NewBlobClient(cfg)+ store, err := buildStoreFromS3Config(cfg)if err != nil {- return nil, fmt.Errorf("failed to create blob client: %w", err)+ return nil, err}-- log.Printf("storage: using %s backend (endpoint=%s, bucket=%s)", blob.BackendName(), cfg.Endpoint, cfg.Bucket)-+ log.Printf("storage: using %s backend (endpoint=%s, bucket=%s)", store.Name(), cfg.Endpoint, cfg.Bucket)return &CheckpointStore{- blob: blob,+ blob: store,bucket: cfg.Bucket,}, nil}+// buildStoreFromS3Config picks Azure or S3-compat based on endpoint shape,+// preserving the previous auto-detection contract.+func buildStoreFromS3Config(cfg S3Config) (blobstore.Store, error) {+ if strings.Contains(cfg.Endpoint, ".blob.core.windows.net") {+ // Azure: storage account name lives in AccessKeyID, account key in SecretAccessKey.+ return blobstore.NewAzure(blobstore.AzureConfig{+ Name: "azure-blob",+ AccountName: cfg.AccessKeyID,+ AccountKey: cfg.SecretAccessKey,+ })+ }+ return blobstore.NewS3(blobstore.S3Config{+ Name: "s3",+ Endpoint: cfg.Endpoint,+ Region: cfg.Region,+ AccessKeyID: cfg.AccessKeyID,+ SecretAccessKey: cfg.SecretAccessKey,+ UsePathStyle: cfg.ForcePathStyle || strings.Contains(cfg.Endpoint, ".blob.core.windows.net"),+ })+}+// SetCacheDir enables local NVMe checkpoint caching at the given directory.func (s *CheckpointStore) SetCacheDir(dir string) error {if err := os.MkdirAll(dir, 0755); err != nil {@@ -128,7 +161,7 @@ func (s *CheckpointStore) Upload(ctx context.Context, key, localPath string) (inreturn 0, fmt.Errorf("failed to stat checkpoint file: %w", err)}- if err := s.blob.Upload(ctx, s.bucket, key, f, stat.Size()); err != nil {+ if err := s.blob.Put(ctx, s.bucket, key, f, stat.Size()); err != nil {return 0, fmt.Errorf("failed to upload checkpoint: %w", err)}@@ -275,7 +308,7 @@ func (s *CheckpointStore) downloadAndCache(ctx context.Context, key string) (io.}chunkLen := end - start + 1- body, err := s.blob.DownloadRange(ctx, s.bucket, key, start, chunkLen)+ body, err := s.blob.GetRange(ctx, s.bucket, key, start, chunkLen)if err != nil {errs[idx] = fmt.Errorf("chunk %d: %w", idx, err)return@@ -324,9 +357,10 @@ func (s *CheckpointStore) downloadAndCache(ctx context.Context, key string) (io.return f, nil}-// downloadFromS3 streams directly from S3 (no caching).+// downloadFromS3 streams directly from S3 (no caching). Despite the name,+// works against any blobstore.Store backend.func (s *CheckpointStore) downloadFromS3(ctx context.Context, key string) (io.ReadCloser, error) {- body, err := s.blob.Download(ctx, s.bucket, key)+ body, err := s.blob.Get(ctx, s.bucket, key)if err != nil {return nil, fmt.Errorf("failed to download checkpoint: %w", err)}diff --git a/internal/worker/autosave.go b/internal/worker/autosave.goindex 092baf2f..b3f02f92 100644--- a/internal/worker/autosave.go+++ b/internal/worker/autosave.go@@ -3,21 +3,39 @@ package workerimport ("context""log"+ "os""sync""time""github.com/opensandbox/opensandbox/internal/sandbox")-// SyncFSer is implemented by any VM manager that can flush filesystem buffers.+// SyncFSer is implemented by any VM manager that can flush filesystem buffers+// and report the workspace path so we can gate sync on mtime.type SyncFSer interface {SyncFS(ctx context.Context, sandboxID string) error+ GetWorkspacePath(sandboxID string) (string, error)}+// maxConsecutiveFailures: after this many failed sync attempts in a row for+// the same sandbox, we stop trying. Prevents a wedged sandbox (e.g. agent+// stuck after savevm/loadvm protocol confusion) from emitting an autosave+// failure log every 5 minutes forever, and stops us churning the broken+// gRPC channel — which is itself part of the post-loadvm flake surface.+// Operator can re-enable by reviving the sandbox or restarting the worker.+const maxConsecutiveFailures = 5+// WorkspaceAutosaver periodically flushes filesystem buffers inside each-// running VM. This ensures workspace.ext4 on the host NVMe is crash-consistent.-// On hard kill recovery, the worker cold-boots from template + existing-// workspace.ext4 on disk (processes lost, but user files in /workspace are safe).+// running VM so workspace.qcow2 on the host NVMe is crash-consistent for+// cold-boot recovery on worker death.+//+// Two correctness/cost gates:+// - skip a sandbox if its workspace.qcow2 hasn't been modified since the+// last successful sync (idle sandboxes are common and a sync per tick+// is wasted work and gRPC roundtrip).+// - circuit-breaker after N consecutive failures: stop trying for a+// sandbox where the agent is wedged. Prevents log flood and churn on+// the broken control channel.type WorkspaceAutosaver struct {manager sandbox.Managersyncer SyncFSer@@ -25,6 +43,15 @@ type WorkspaceAutosaver struct {concurrency intstop chan struct{}done chan struct{}++ mu sync.Mutex+ state map[string]*sandboxSyncState // keyed by sandboxID+}++type sandboxSyncState struct {+ lastSyncedMtime time.Time // mtime of workspace.qcow2 at last successful sync+ consecutiveFails int+ disabled bool // circuit-breaker tripped — skip until restart}// NewWorkspaceAutosaver creates a new autosaver.@@ -40,13 +67,15 @@ func NewWorkspaceAutosaver(concurrency: 10,stop: make(chan struct{}),done: make(chan struct{}),+ state: map[string]*sandboxSyncState{},}}// Start begins the periodic SyncFS loop.func (a *WorkspaceAutosaver) Start() {go a.loop()- log.Printf("autosave: started (interval=%s, concurrency=%d)", a.interval, a.concurrency)+ log.Printf("autosave: started (interval=%s, concurrency=%d, fail-threshold=%d)",+ a.interval, a.concurrency, maxConsecutiveFailures)}// Stop signals the loop to exit and waits for it to finish.@@ -70,6 +99,29 @@ func (a *WorkspaceAutosaver) loop() {}}+func (a *WorkspaceAutosaver) getOrCreateState(sandboxID string) *sandboxSyncState {+ a.mu.Lock()+ defer a.mu.Unlock()+ s, ok := a.state[sandboxID]+ if !ok {+ s = &sandboxSyncState{}+ a.state[sandboxID] = s+ }+ return s+}++// pruneState removes per-sandbox state for sandboxes no longer in the active+// set. Without this the map grows unbounded across the worker's lifetime.+func (a *WorkspaceAutosaver) pruneState(active map[string]struct{}) {+ a.mu.Lock()+ defer a.mu.Unlock()+ for id := range a.state {+ if _, ok := active[id]; !ok {+ delete(a.state, id)+ }+ }+}+func (a *WorkspaceAutosaver) syncAll() {sandboxes, err := a.manager.List(context.Background())if err != nil {@@ -77,18 +129,25 @@ func (a *WorkspaceAutosaver) syncAll() {return}if len(sandboxes) == 0 {+ a.pruneState(map[string]struct{}{})return}+ active := make(map[string]struct{}, len(sandboxes))+ for _, sb := range sandboxes {+ active[sb.ID] = struct{}{}+ }+ a.pruneState(active)+sem := make(chan struct{}, a.concurrency)var wg sync.WaitGroup- var successCount, failCount int32+ var successCount, skipCount, failCount, disabledCount int32var mu sync.Mutexfor _, sb := range sandboxes {select {case <-a.stop:- break+ returndefault:}@@ -98,23 +157,88 @@ func (a *WorkspaceAutosaver) syncAll() {defer wg.Done()defer func() { <-sem }()- syncCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)- defer cancel()- if err := a.syncer.SyncFS(syncCtx, sandboxID); err != nil {- log.Printf("autosave: syncfs failed for %s: %v", sandboxID, err)- mu.Lock()- failCount++- mu.Unlock()- } else {- mu.Lock()+ outcome := a.syncOne(sandboxID)+ mu.Lock()+ switch outcome {+ case syncOK:successCount++- mu.Unlock()+ case syncSkipped:+ skipCount+++ case syncFailed:+ failCount+++ case syncDisabled:+ disabledCount++}+ mu.Unlock()}(sb.ID)}wg.Wait()- if failCount > 0 {- log.Printf("autosave: syncfs complete (%d ok, %d failed)", successCount, failCount)+ if failCount > 0 || disabledCount > 0 {+ log.Printf("autosave: tick complete (ok=%d skip=%d fail=%d disabled=%d)",+ successCount, skipCount, failCount, disabledCount)+ }+}++type syncOutcome int++const (+ syncOK syncOutcome = iota+ syncSkipped // workspace unchanged since last sync+ syncFailed // sync attempted, returned error+ syncDisabled // circuit-breaker tripped — skipped without attempting+)++func (a *WorkspaceAutosaver) syncOne(sandboxID string) syncOutcome {+ state := a.getOrCreateState(sandboxID)++ a.mu.Lock()+ if state.disabled {+ a.mu.Unlock()+ return syncDisabled+ }+ lastMtime := state.lastSyncedMtime+ a.mu.Unlock()++ // Gate on workspace mtime — skip if nothing changed since last successful sync.+ wsPath, err := a.syncer.GetWorkspacePath(sandboxID)+ if err == nil && wsPath != "" {+ if stat, statErr := os.Stat(wsPath); statErr == nil {+ if !lastMtime.IsZero() && !stat.ModTime().After(lastMtime) {+ return syncSkipped+ }+ }+ }++ syncCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()+ if err := a.syncer.SyncFS(syncCtx, sandboxID); err != nil {+ a.mu.Lock()+ state.consecutiveFails+++ hitThreshold := state.consecutiveFails >= maxConsecutiveFailures+ if hitThreshold {+ state.disabled = true+ }+ fails := state.consecutiveFails+ a.mu.Unlock()++ if hitThreshold {+ log.Printf("autosave: %s disabled after %d consecutive failures (last=%v) — operator must intervene to re-enable",+ sandboxID, fails, err)+ } else if fails == 1 {+ log.Printf("autosave: syncfs failed for %s: %v", sandboxID, err)+ }+ return syncFailed+ }++ // Success — record current mtime to gate next tick.+ a.mu.Lock()+ state.consecutiveFails = 0+ if wsPath != "" {+ if stat, err := os.Stat(wsPath); err == nil {+ state.lastSyncedMtime = stat.ModTime()+ }}+ a.mu.Unlock()+ return syncOK}diff --git a/internal/worker/grpc_server.go b/internal/worker/grpc_server.goindex c11e2103..84d01314 100644--- a/internal/worker/grpc_server.go+++ b/internal/worker/grpc_server.go@@ -21,6 +21,7 @@ import ("github.com/opensandbox/opensandbox/internal/db""github.com/opensandbox/opensandbox/internal/grpctls"+ "github.com/opensandbox/opensandbox/internal/metrics""github.com/opensandbox/opensandbox/internal/observability""github.com/opensandbox/opensandbox/internal/sandbox""github.com/opensandbox/opensandbox/internal/sparse"@@ -33,8 +34,8 @@ import (// LiveMigrator is implemented by VM managers that support live migration (e.g. QEMU).type LiveMigrator interface {PrepareIncomingMigration(ctx context.Context, sandboxID, rootfsPath, workspacePath string, cpus, memMB, guestPort int, template string) (incomingAddr string, hostPort int, err error)- PrepareIncomingMigrationWithS3(ctx context.Context, sandboxID, rootfsS3Key, workspaceS3Key string, cpus, memMB, guestPort int, template string, checkpointStore *storage.CheckpointStore, overlayMode bool, sourceGoldenVersion string) (incomingAddr string, hostPort int, err error)- PreCopyDrives(ctx context.Context, sandboxID string, checkpointStore *storage.CheckpointStore) (rootfsKey, workspaceKey, goldenVersion string, baseCPU, baseMem, actualMem int, err error)+ PrepareIncomingMigrationWithS3(ctx context.Context, sandboxID, rootfsS3Key, workspaceS3Key string, cpus, memMB, guestPort int, template string, checkpointStore *storage.CheckpointStore, overlayMode bool, sourceGoldenVersion string, secrets sandbox.MigrationSecrets) (incomingAddr string, hostPort int, err error)+ PreCopyDrives(ctx context.Context, sandboxID string, checkpointStore *storage.CheckpointStore) (rootfsKey, workspaceKey, goldenVersion string, baseCPU, baseMem, actualMem int, secrets sandbox.MigrationSecrets, err error)CompleteIncomingMigration(ctx context.Context, sandboxID string) errorLiveMigrate(ctx context.Context, sandboxID, incomingAddr string) error}@@ -57,6 +58,15 @@ type GoldenRebuilder interface {GoldenVersion() string}+// LogshipConfigurator is implemented by VM managers that can deliver+// log-shipping configuration to the in-VM agent over the existing+// worker→agent gRPC channel. Managers without an agent channel just+// don't implement this — the worker silently skips configuration for+// those sandboxes.+type LogshipConfigurator interface {+ ConfigureLogship(ctx context.Context, sandboxID, ingestToken, dataset, orgID string) error+}+type GRPCServer struct {pb.UnimplementedSandboxWorkerServermanager sandbox.Manager@@ -69,6 +79,28 @@ type GRPCServer struct {checkpointStore *storage.CheckpointStorestore *db.Store // nil if no DB configuredserver *grpc.Server++ // Axiom log-shipping config. Empty token = log shipping disabled+ // (kill-switch). Set via SetAxiomConfig at startup.+ axiomIngestToken string+ axiomDataset string++ // region is the worker's region label, used to tag operation metrics.+ // Set via SetRegion at startup. Empty = "unknown".+ region string+}++// SetRegion stamps the worker's region onto operation metrics emitted from+// this gRPC server (e.g. WakeDuration for warm-fork vs s3 paths).+func (s *GRPCServer) SetRegion(region string) { s.region = region }++// SetAxiomConfig wires Axiom log-shipping credentials. The worker+// passes them down to each sandbox's agent on create via the+// LogshipConfigurator interface (implemented by the QEMU manager).+// Empty token disables shipping for every sandbox this worker boots.+func (s *GRPCServer) SetAxiomConfig(ingestToken, dataset string) {+ s.axiomIngestToken = ingestToken+ s.axiomDataset = dataset}// NewGRPCServer creates a new gRPC server wrapping the sandbox manager.@@ -127,6 +159,32 @@ func (s *GRPCServer) Stop() {s.server.GracefulStop()}+// configureLogshipForSandbox delivers Axiom log-shipping configuration+// to the in-VM agent. Best-effort: a failure here does not fail the+// sandbox-create — log shipping just stays dormant for this sandbox.+// No-op if the worker has no Axiom token set or the manager doesn't+// implement LogshipConfigurator.+func (s *GRPCServer) configureLogshipForSandbox(ctx context.Context, sandboxID string) {+ if s.axiomIngestToken == "" {+ log.Printf("grpc: ConfigureLogship skipped for %s: no axiom ingest token set on worker", sandboxID)+ return+ }+ cfger, ok := s.manager.(LogshipConfigurator)+ if !ok {+ log.Printf("grpc: ConfigureLogship skipped for %s: manager %T does not implement LogshipConfigurator", sandboxID, s.manager)+ return+ }+ var orgID string+ if s.store != nil {+ orgID, _ = s.store.GetSandboxOrgID(ctx, sandboxID)+ }+ if err := cfger.ConfigureLogship(ctx, sandboxID, s.axiomIngestToken, s.axiomDataset, orgID); err != nil {+ log.Printf("grpc: ConfigureLogship for %s failed: %v (logs disabled for this sandbox)", sandboxID, err)+ return+ }+ log.Printf("grpc: ConfigureLogship sent for %s (org=%s, dataset=%s)", sandboxID, orgID, s.axiomDataset)+}+// parseSecretAllowedHosts converts the proto map (env var → comma-separated hosts)// to the internal map (env var → host slice). Returns nil if input is empty.func parseSecretAllowedHosts(m map[string]string) map[string][]string {@@ -152,7 +210,7 @@ func (s *GRPCServer) CreateSandbox(ctx context.Context, req *pb.CreateSandboxReqEnvs: req.Envs,MemoryMB: int(req.MemoryMb),CpuCount: int(req.CpuCount),- NetworkEnabled: req.NetworkEnabled,+ NetworkEnabled: &req.NetworkEnabled,ImageRef: req.ImageRef,Port: int(req.Port),SandboxID: req.SandboxId, // use server-assigned ID if provided@@ -166,8 +224,17 @@ func (s *GRPCServer) CreateSandbox(ctx context.Context, req *pb.CreateSandboxReq// Warm fork: if checkpoint_id is set, fork from the local checkpoint cache.// ForkFromCheckpoint uses the local cache directly — no S3 needed.if req.CheckpointId != "" {+ // WakeDuration covers "create from checkpoint" end-to-end. source label+ // distinguishes a local-cache hit (fast, ~hundreds of ms) from a path+ // that had to pull the archive from S3 (slow, seconds to minutes).+ tWake := time.Now()+ observeWake := func(source, status string) {+ metrics.WakeDuration.WithLabelValues(s.region, cfg.Template, source, status).Observe(time.Since(tWake).Seconds())+ }+sb, err := s.manager.ForkFromCheckpoint(ctx, req.CheckpointId, cfg)if err == nil {+ observeWake("warm_cache", "success")if s.router != nil {// timeout == 0 means "persistent" (no auto-hibernate).timeout := cfg.Timeout@@ -176,39 +243,61 @@ func (s *GRPCServer) CreateSandbox(ctx context.Context, req *pb.CreateSandboxReq}s.router.Register(sb.ID, time.Duration(timeout)*time.Second)}+ s.recordInitialScaleEvent(ctx, sb.ID, cfg)+ s.configureLogshipForSandbox(ctx, sb.ID)return &pb.CreateSandboxResponse{SandboxId: sb.ID,Status: string(sb.Status),}, nil}- // If not in local cache, download the full checkpoint from S3 and retry.- // The archive includes drives + memory dump — everything needed for restore.- if strings.Contains(err.Error(), "not found in cache") && req.TemplateRootfsKey != "" && s.checkpointStore != nil {- log.Printf("grpc: warm fork %s: not in local cache, downloading from S3", req.CheckpointId)- if dlErr := s.downloadFullCheckpoint(ctx, req.CheckpointId, req.TemplateRootfsKey); dlErr != nil {- log.Printf("grpc: warm fork %s: S3 download failed: %v, falling back to template create", req.CheckpointId, dlErr)- } else {- sb, err = s.manager.ForkFromCheckpoint(ctx, req.CheckpointId, cfg)- if err == nil {- if s.router != nil {- // timeout == 0 means "persistent" (no auto-hibernate).- timeout := cfg.Timeout- if timeout < 0 {- timeout = 0- }- s.router.Register(sb.ID, time.Duration(timeout)*time.Second)- }- return &pb.CreateSandboxResponse{- SandboxId: sb.ID,- Status: string(sb.Status),- }, nil- }- log.Printf("grpc: warm fork %s: retry after S3 download failed: %v, falling back to template create", req.CheckpointId, err)- }- } else if !strings.Contains(err.Error(), "not found in cache") {+ // Cache miss path: try to recover by downloading the checkpoint from+ // S3, then retry the fork. The archive at TemplateRootfsKey holds+ // drives + memory dump + metadata — everything ForkFromCheckpoint+ // needs.+ notInCache := strings.Contains(err.Error(), "not found in cache")+ if !notInCache {+ // Some other error (rebase failure, agent reconnect, etc.).+ // Don't try to mask it — return the real reason. Attribute as+ // warm_cache failure since we never got to the S3 path.+ observeWake("warm_cache", "failure")return nil, fmt.Errorf("fork from checkpoint %s: %w", req.CheckpointId, err)}- log.Printf("grpc: warm fork %s: resolve drives failed: %v, continuing with ForkFromCheckpoint", req.CheckpointId, err)+ if req.TemplateRootfsKey == "" || s.checkpointStore == nil {+ // We can't recover this fork — the controlplane gave us a+ // checkpoint id but no S3 key, and we don't have it cached+ // locally. Pre-fix this fell through to plain Create() at the+ // bottom of this function, silently producing an empty sandbox+ // from the base golden — exactly the "only lost+found"+ // symptom Oliviero hit on a checkpoint whose DB row had+ // empty rootfs_s3_key. Fail loud instead so the customer (and+ // us) sees an actionable error rather than a corrupt sandbox.+ observeWake("s3", "failure")+ return nil, fmt.Errorf("fork from checkpoint %s: not in local cache and no S3 key to recover from (DB row may be missing rootfs_s3_key)", req.CheckpointId)+ }+ log.Printf("grpc: warm fork %s: not in local cache, downloading from S3", req.CheckpointId)+ if dlErr := s.downloadFullCheckpoint(ctx, req.CheckpointId, req.TemplateRootfsKey); dlErr != nil {+ observeWake("s3", "failure")+ return nil, fmt.Errorf("fork from checkpoint %s: cache miss + S3 download failed: %w", req.CheckpointId, dlErr)+ }+ sb, retryErr := s.manager.ForkFromCheckpoint(ctx, req.CheckpointId, cfg)+ if retryErr != nil {+ observeWake("s3", "failure")+ return nil, fmt.Errorf("fork from checkpoint %s: retry after S3 download failed: %w", req.CheckpointId, retryErr)+ }+ observeWake("s3", "success")+ if s.router != nil {+ timeout := cfg.Timeout+ if timeout < 0 {+ timeout = 0+ }+ s.router.Register(sb.ID, time.Duration(timeout)*time.Second)+ }+ s.recordInitialScaleEvent(ctx, sb.ID, cfg)+ s.configureLogshipForSandbox(ctx, sb.ID)+ return &pb.CreateSandboxResponse{+ SandboxId: sb.ID,+ Status: string(sb.Status),+ }, nil}// Handle sandbox snapshot template: resolve S3 keys to local paths.@@ -247,27 +336,9 @@ func (s *GRPCServer) CreateSandbox(ctx context.Context, req *pb.CreateSandboxReq}}- // Record initial scale event for billing- if s.store != nil {- memMB := cfg.MemoryMB- if memMB <= 0 {- memMB = 1024 // default- }- cpuPct := (memMB * 100) / 1024- if cpuPct < 100 {- cpuPct = 100- }- diskMB := cfg.DiskMB- if diskMB <= 0 {- diskMB = 20480- }- orgID, _ := s.store.GetSandboxOrgID(ctx, sb.ID)- if orgID != "" {- if err := s.store.RecordScaleEvent(ctx, sb.ID, orgID, memMB, cpuPct, diskMB); err != nil {- log.Printf("grpc: failed to record initial scale event for %s: %v", sb.ID, err)- }- }- }+ s.recordInitialScaleEvent(ctx, sb.ID, cfg)++ s.configureLogshipForSandbox(ctx, sb.ID)return &pb.CreateSandboxResponse{SandboxId: sb.ID,@@ -275,6 +346,41 @@ func (s *GRPCServer) CreateSandbox(ctx context.Context, req *pb.CreateSandboxReq}, nil}+// recordInitialScaleEvent writes a sandbox_scale_events row marking the start+// of billable usage for a freshly-created sandbox. Called from every successful+// CreateSandbox return path — fork from checkpoint (local + S3-fallback) and+// from-scratch — so billing accounting works for forks too. Without this on+// the fork paths, sandbox_scale_events stays empty for the org, the+// usage-reporter excludes it from ListFreeOrgIDsWithOpenUsage / ListBillableOrgIDs,+// and no credits/usage are deducted or reported to Stripe.+//+// Best-effort: never returns an error. Defaults mirror the worker's own+// fallbacks for unset CPU/memory/disk so downstream pricing math is consistent.+func (s *GRPCServer) recordInitialScaleEvent(ctx context.Context, sandboxID string, cfg types.SandboxConfig) {+ if s.store == nil {+ return+ }+ memMB := cfg.MemoryMB+ if memMB <= 0 {+ memMB = 1024+ }+ cpuPct := (memMB * 100) / 1024+ if cpuPct < 100 {+ cpuPct = 100+ }+ diskMB := cfg.DiskMB+ if diskMB <= 0 {+ diskMB = 20480+ }+ orgID, _ := s.store.GetSandboxOrgID(ctx, sandboxID)+ if orgID == "" {+ return+ }+ if err := s.store.RecordScaleEvent(ctx, sandboxID, orgID, memMB, cpuPct, diskMB); err != nil {+ log.Printf("grpc: failed to record initial scale event for %s: %v", sandboxID, err)+ }+}+func (s *GRPCServer) DestroySandbox(ctx context.Context, req *pb.DestroySandboxRequest) (*pb.DestroySandboxResponse, error) {// End billing scale event before destroyingif s.store != nil {@@ -639,6 +745,23 @@ func (s *GRPCServer) WakeSandbox(ctx context.Context, req *pb.WakeSandboxRequest}, nil}+func (s *GRPCServer) RebootSandbox(ctx context.Context, req *pb.RebootSandboxRequest) (*pb.RebootSandboxResponse, error) {+ if err := s.manager.RebootSandbox(ctx, req.SandboxId); err != nil {+ return nil, fmt.Errorf("reboot sandbox: %w", err)+ }+ return &pb.RebootSandboxResponse{}, nil+}++func (s *GRPCServer) PowerCycleSandbox(ctx context.Context, req *pb.PowerCycleSandboxRequest) (*pb.PowerCycleSandboxResponse, error) {+ port, err := s.manager.PowerCycleSandbox(ctx, req.SandboxId)+ if err != nil {+ return nil, fmt.Errorf("power-cycle sandbox: %w", err)+ }+ return &pb.PowerCycleSandboxResponse{+ HostPort: int32(port),+ }, nil+}+func (s *GRPCServer) BuildTemplate(ctx context.Context, req *pb.BuildTemplateRequest) (*pb.BuildTemplateResponse, error) {return nil, status.Errorf(codes.Unimplemented, "deprecated")}@@ -657,30 +780,25 @@ func (s *GRPCServer) CreateCheckpoint(ctx context.Context, req *pb.CreateCheckporeturn nil, fmt.Errorf("invalid checkpoint ID: %w", err)}- // The onReady callback fires after the async mem file move + S3 upload completes.- // If prepare_golden is set, it also creates a golden snapshot from the cache.+ // The onReady callback fires after the S3 upload completes inside+ // CreateCheckpoint. We only use it to trigger golden-snapshot prep here;+ // the DB row is marked ready by the API using the actual keys + size from+ // the gRPC response (see api/sandbox.go SetCheckpointReady call).+ //+ // Why not also mark ready here: the previous version of this callback+ // called SetCheckpointReady(cpID, "", "", 0) — empty strings — and lost a+ // race against the API's proper write under timeout. When the gRPC ctx+ // timed out (large checkpoints, ~5 min budget), the API marked the row+ // failed; minutes later the worker's upload finished, this onReady fired,+ // and SetCheckpointReady flipped the row back to status='ready' with+ // empty keys. Forks then saw a "ready" checkpoint with no S3 key and+ // silently fell through to a fresh Create — empty /home/sandbox, only+ // lost+found. Removing the worker-side write makes the API the single+ // source of truth for the DB row's ready state.prepareGolden := req.PrepareGoldenmgr := s.managervar onReady func()- if s.store != nil {- cpID, _ := uuid.Parse(checkpointID)- onReady = func() {- if err := s.store.SetCheckpointReady(context.Background(), cpID, "", "", 0); err != nil {- log.Printf("grpc: CreateCheckpoint: failed to mark checkpoint %s ready: %v", checkpointID, err)- } else {- log.Printf("grpc: CreateCheckpoint: checkpoint %s is now ready", checkpointID)- }- // Create golden snapshot after mem file is in place- if prepareGolden {- type goldenPreparer interface {- RegisterTemplateGoldenFromCache(checkpointID string)- }- if gp, ok := mgr.(goldenPreparer); ok {- gp.RegisterTemplateGoldenFromCache(checkpointID)- }- }- }- } else if prepareGolden {+ if prepareGolden {onReady = func() {type goldenPreparer interface {RegisterTemplateGoldenFromCache(checkpointID string)@@ -696,7 +814,7 @@ func (s *GRPCServer) CreateCheckpoint(ctx context.Context, req *pb.CreateCheckpo// it's marked "ready" — forks poll for "ready" before downloading.// The gRPC call returns immediately with the S3 keys — the CP's fork path// polls for checkpoint readiness and blocks until onReady fires.- rootfsKey, workspaceKey, err := s.manager.CreateCheckpoint(ctx, req.SandboxId, checkpointID, s.checkpointStore, onReady)+ rootfsKey, workspaceKey, sizeBytes, err := s.manager.CreateCheckpoint(ctx, req.SandboxId, checkpointID, s.checkpointStore, onReady)if err != nil {return nil, fmt.Errorf("create checkpoint failed: %w", err)}@@ -704,6 +822,7 @@ func (s *GRPCServer) CreateCheckpoint(ctx context.Context, req *pb.CreateCheckporeturn &pb.CreateCheckpointResponse{RootfsS3Key: rootfsKey,WorkspaceS3Key: workspaceKey,+ SizeBytes: sizeBytes,}, nil}@@ -958,6 +1077,17 @@ func (s *GRPCServer) SetSandboxLimits(ctx context.Context, req *pb.SetSandboxLimreturn &pb.SetSandboxLimitsResponse{}, nil}+func (s *GRPCServer) UpdateSandboxSecret(ctx context.Context, req *pb.UpdateSandboxSecretRequest) (*pb.UpdateSandboxSecretResponse, error) {+ if req.SandboxId == "" || req.SecretName == "" {+ return nil, fmt.Errorf("sandbox_id and secret_name required")+ }+ updated, err := s.manager.UpdateSandboxSecret(ctx, req.SandboxId, req.SecretName, req.Value)+ if err != nil {+ return nil, fmt.Errorf("update secret: %w", err)+ }+ return &pb.UpdateSandboxSecretResponse{Updated: updated}, nil+}+// SetMigrator sets the live migration handler (call after NewGRPCServer if the manager supports it).func (s *GRPCServer) SetMigrator(m LiveMigrator) {s.migrator = m@@ -972,18 +1102,32 @@ func (s *GRPCServer) PreCopyDrives(ctx context.Context, req *pb.PreCopyDrivesReqif s.migrator == nil {return nil, fmt.Errorf("live migration not supported on this worker")}- rootfsKey, workspaceKey, goldenVersion, baseCPU, baseMem, actualMem, err := s.migrator.PreCopyDrives(ctx, req.SandboxId, s.checkpointStore)+ rootfsKey, workspaceKey, goldenVersion, baseCPU, baseMem, actualMem, secrets, err := s.migrator.PreCopyDrives(ctx, req.SandboxId, s.checkpointStore)if err != nil {return nil, fmt.Errorf("pre-copy drives: %w", err)}- return &pb.PreCopyDrivesResponse{+ resp := &pb.PreCopyDrivesResponse{RootfsKey: rootfsKey,WorkspaceKey: workspaceKey,GoldenVersion: goldenVersion,BaseMemoryMb: int32(baseMem),BaseCpuCount: int32(baseCPU),ActualMemoryMb: int32(actualMem),- }, nil+ }+ // Marshal the secrets-proxy session into the proto. Skipped silently+ // when the sandbox has no secret store registered (empty maps).+ if len(secrets.SealedTokens) > 0 {+ resp.SealedTokens = secrets.SealedTokens+ resp.EgressAllowlist = secrets.EgressAllowlist+ resp.SealedNames = secrets.SealedNames+ if len(secrets.TokenHosts) > 0 {+ resp.TokenHosts = make(map[string]*pb.HostList, len(secrets.TokenHosts))+ for tok, hosts := range secrets.TokenHosts {+ resp.TokenHosts[tok] = &pb.HostList{Hosts: hosts}+ }+ }+ }+ return resp, nil}func (s *GRPCServer) PrepareMigrationIncoming(ctx context.Context, req *pb.PrepareMigrationIncomingRequest) (*pb.PrepareMigrationIncomingResponse, error) {@@ -1011,6 +1155,24 @@ func (s *GRPCServer) PrepareMigrationIncoming(ctx context.Context, req *pb.Prepa}}+ // Unmarshal the secrets-proxy session from the request, if any. The+ // orchestrator will have copied this from PreCopyDrives. Empty when+ // the sandbox has no secret store.+ var secrets sandbox.MigrationSecrets+ if len(req.SealedTokens) > 0 {+ secrets.SealedTokens = req.SealedTokens+ secrets.EgressAllowlist = req.EgressAllowlist+ secrets.SealedNames = req.SealedNames+ if len(req.TokenHosts) > 0 {+ secrets.TokenHosts = make(map[string][]string, len(req.TokenHosts))+ for tok, hl := range req.TokenHosts {+ if hl != nil {+ secrets.TokenHosts[tok] = hl.Hosts+ }+ }+ }+ }+var (addr stringhostPort int@@ -1019,7 +1181,7 @@ func (s *GRPCServer) PrepareMigrationIncoming(ctx context.Context, req *pb.Prepaif req.RootfsS3Key != "" && req.WorkspaceS3Key != "" {addr, hostPort, err = s.migrator.PrepareIncomingMigrationWithS3(ctx,req.SandboxId, req.RootfsS3Key, req.WorkspaceS3Key,- int(req.CpuCount), int(req.MemoryMb), int(req.GuestPort), req.Template, s.checkpointStore, req.OverlayMode, req.SourceGoldenVersion)+ int(req.CpuCount), int(req.MemoryMb), int(req.GuestPort), req.Template, s.checkpointStore, req.OverlayMode, req.SourceGoldenVersion, secrets)} else {addr, hostPort, err = s.migrator.PrepareIncomingMigration(ctx,req.SandboxId, req.RootfsPath, req.WorkspacePath,diff --git a/internal/worker/http_server.go b/internal/worker/http_server.goindex 58e13bbc..14eae37f 100644--- a/internal/worker/http_server.go+++ b/internal/worker/http_server.go@@ -7,6 +7,7 @@ import ("github.com/labstack/echo/v4/middleware""github.com/opensandbox/opensandbox/internal/auth""github.com/opensandbox/opensandbox/internal/observability"+ "github.com/opensandbox/opensandbox/internal/obslog""github.com/opensandbox/opensandbox/internal/proxy""github.com/opensandbox/opensandbox/internal/sandbox")@@ -43,11 +44,15 @@ func NewHTTPServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, execMgr *san// Global middleware. Sentry goes first so it can observe panics and// attach request context before echo's Recover middleware handles them.+ // RequestID() before obslog so the request_id is on the context when+ // our middleware tags it — and the control plane forwards X-Request-Id+ // from its proxy, which Echo's RequestID() reuses instead of generating+ // a new id, so the same id appears on both control plane and worker logs.e.Use(observability.EchoMiddleware())e.Use(middleware.Recover())- e.Use(middleware.Logger())- e.Use(middleware.CORS())e.Use(middleware.RequestID())+ e.Use(obslog.EchoMiddleware())+ e.Use(middleware.CORS())// Subdomain proxy middleware (before auth — subdomain traffic is public)if sbProxy != nil {diff --git a/internal/worker/redis_heartbeat.go b/internal/worker/redis_heartbeat.goindex 278156b8..1b53e5bd 100644--- a/internal/worker/redis_heartbeat.go+++ b/internal/worker/redis_heartbeat.go@@ -26,6 +26,24 @@ type redisHeartbeatPayload struct {CommittedMemoryMB int `json:"committed_memory_mb,omitempty"`GoldenVersion string `json:"golden_version,omitempty"`WorkerVersion string `json:"worker_version,omitempty"`++ // Per-sandbox stats snapshot. Populated by the worker's stats collector+ // (see internal/qemu/stats_collector.go) and consumed by the CP autoscaler+ // (see internal/controlplane/autoscaler.go). Bounded by the worker's+ // physical sandbox capacity (~50-150 entries on a D64 host) regardless of+ // total cluster size, so the heartbeat payload doesn't grow unboundedly.+ Sandboxes map[string]SandboxStatsWire `json:"sandboxes,omitempty"`+}++// SandboxStatsWire is the wire form of per-sandbox stats included in the+// heartbeat. Subset of internal/sandbox.SandboxStats — only what the+// autoscaler / dashboard consumers actually need. Pre-computed mem_pct+// avoids divide-by-zero handling at every consumer.+type SandboxStatsWire struct {+ MemUsage uint64 `json:"mem_usage"`+ MemLimit uint64 `json:"mem_limit"`+ MemPct float64 `json:"mem_pct"`+ CPUPct float64 `json:"cpu_pct"`}// RedisHeartbeat publishes periodic heartbeats to Redis for worker discovery.@@ -39,9 +57,10 @@ type RedisHeartbeat struct {region stringgrpcAddr stringhttpAddr string- getStats func() (capacity, current int, cpuPct, memPct, diskPct float64)- getMemoryInfo func() (totalMB, committedMB int) // optional: committed memory for dynamic capacity- onReconnect func() // called when heartbeat succeeds after a previous failure+ getStats func() (capacity, current int, cpuPct, memPct, diskPct float64)+ getMemoryInfo func() (totalMB, committedMB int) // optional: committed memory for dynamic capacity+ getSandboxStats func() map[string]SandboxStatsWire // optional: per-sandbox stats for autoscaler+ onReconnect func() // called when heartbeat succeeds after a previous failuregoldenVersion stringworkerVersion stringwasDown bool // true if the last publish failed (used to detect reconnect)@@ -101,6 +120,13 @@ func (h *RedisHeartbeat) SetMemoryInfoFunc(fn func() (totalMB, committedMB int))h.getMemoryInfo = fn}+// SetSandboxStatsFunc registers a callback that returns the latest per-sandbox+// stats snapshot. The heartbeat publishes this map under the "sandboxes" field+// for the CP autoscaler. Wire it to qemu.Manager's stats cache.+func (h *RedisHeartbeat) SetSandboxStatsFunc(fn func() map[string]SandboxStatsWire) {+ h.getSandboxStats = fn+}+// OnReconnect sets a callback that fires when heartbeat succeeds after a failure.// Used to reconcile sandbox state after a network outage.func (h *RedisHeartbeat) OnReconnect(fn func()) {@@ -154,6 +180,13 @@ func (h *RedisHeartbeat) publish() {payload.CommittedMemoryMB = committedMB}+ // Per-sandbox stats for the CP autoscaler. Skipped silently if no+ // collector is wired — preserves backward compat with deployments where+ // the autoscaler is disabled.+ if h.getSandboxStats != nil {+ payload.Sandboxes = h.getSandboxStats()+ }+data, err := json.Marshal(payload)if err != nil {log.Printf("redis_heartbeat: marshal error: %v", err)diff --git a/internal/worker/resource_metrics.go b/internal/worker/resource_metrics.gonew file mode 100644index 00000000..e1369505--- /dev/null+++ b/internal/worker/resource_metrics.go@@ -0,0 +1,98 @@+package worker++import (+ "context"+ "log"+ "path/filepath"+ "time"++ "github.com/opensandbox/opensandbox/internal/metrics"+)++// MemoryAllocator is the slice of the QEMU manager interface needed to report+// per-worker memory allocation. Duck-typed so this package doesn't depend on+// internal/qemu directly.+type MemoryAllocator interface {+ MemoryAllocatedBytes() uint64+}++// SandboxCounter reports the count of currently-active sandboxes grouped by+// template, used to drive the opensandbox_sandboxes_active gauge.+type SandboxCounter interface {+ ActiveSandboxesByTemplate() map[string]int+}++// StartResourceMetricsTick runs a goroutine that samples disk, memory, allocated+// memory, CPU pressure, and active-sandbox count every interval and writes them+// to the worker-side Prometheus gauges. Cancel via the provided context.+//+// dataDir is the worker data directory (e.g. /data/sandboxes) — its mountpoint+// is what the disk gauges report on. mount is just the label value, defaulted+// to filepath.Clean(dataDir).+//+// allocator may be nil (non-QEMU backend); allocated-memory gauge is then left+// unwritten. counter may be nil for the same reason; sandboxes_active gauge is+// then left unwritten.+func StartResourceMetricsTick(ctx context.Context, allocator MemoryAllocator, counter SandboxCounter, region, workerID, dataDir string, interval time.Duration) {+ if interval <= 0 {+ interval = 30 * time.Second+ }+ mount := filepath.Clean(dataDir)+ go func() {+ // Emit one sample immediately so the gauges aren't reported empty for+ // the first interval after worker boot.+ collectAndPublish(allocator, counter, region, workerID, dataDir, mount)+ t := time.NewTicker(interval)+ defer t.Stop()+ for {+ select {+ case <-ctx.Done():+ return+ case <-t.C:+ collectAndPublish(allocator, counter, region, workerID, dataDir, mount)+ }+ }+ }()+ log.Printf("opensandbox-worker: resource-stats tick started (interval=%s, mount=%s)", interval, mount)+}++func collectAndPublish(allocator MemoryAllocator, counter SandboxCounter, region, workerID, dataDir, mount string) {+ if total, used, avail, err := DiskBytes(dataDir); err == nil {+ metrics.WorkerDiskTotalBytes.WithLabelValues(region, workerID, mount).Set(float64(total))+ metrics.WorkerDiskUsedBytes.WithLabelValues(region, workerID, mount).Set(float64(used))+ metrics.WorkerDiskAvailableBytes.WithLabelValues(region, workerID, mount).Set(float64(avail))+ }++ if total, avail, err := MemoryBytes(); err == nil && total > 0 {+ metrics.WorkerMemoryTotalBytes.WithLabelValues(region, workerID).Set(float64(total))+ metrics.WorkerMemoryAvailableBytes.WithLabelValues(region, workerID).Set(float64(avail))+ }++ if allocator != nil {+ metrics.WorkerMemoryAllocatedBytes.WithLabelValues(region, workerID).Set(float64(allocator.MemoryAllocatedBytes()))+ }++ psi := ReadCPUPressure()+ metrics.WorkerCPUPressure.WithLabelValues(region, workerID, "avg10", psi.Source).Set(psi.Avg10)+ metrics.WorkerCPUPressure.WithLabelValues(region, workerID, "avg60", psi.Source).Set(psi.Avg60)+ metrics.WorkerCPUPressure.WithLabelValues(region, workerID, "avg300", psi.Source).Set(psi.Avg300)++ if counter != nil {+ // Reset clears stale template label combos (sandbox stopped → its+ // template would otherwise stay at its last value forever). The+ // Reset/re-emit window is sub-microsecond and Vector scrapes on a+ // 15-30s cadence, so the race is negligible.+ metrics.SandboxesActive.Reset()+ counts := counter.ActiveSandboxesByTemplate()+ if len(counts) == 0 {+ // Heartbeat so the dashboard query has at least one row to+ // summarize on (otherwise APL trips on the by-tags.worker_id+ // group-by with "field not found").+ metrics.SandboxesActive.WithLabelValues(region, workerID, "").Set(0)+ } else {+ for tmpl, n := range counts {+ metrics.SandboxesActive.WithLabelValues(region, workerID, tmpl).Set(float64(n))+ }+ }+ }+}diff --git a/internal/worker/stats.go b/internal/worker/stats.goindex 4131c72c..473ae7a1 100644--- a/internal/worker/stats.go+++ b/internal/worker/stats.go@@ -147,3 +147,154 @@ func diskPercent() float64 {}return float64(total-free) / float64(total) * 100.0}++// DiskBytes returns total / used / available bytes for the filesystem+// containing path. Used for the per-worker disk metrics.+// Available uses Bavail (free to non-privileged users) rather than Bfree —+// matches what `df` reports and is the number that actually constrains us.+func DiskBytes(path string) (total, used, available uint64, err error) {+ var stat syscall.Statfs_t+ if err = syscall.Statfs(path, &stat); err != nil {+ return 0, 0, 0, err+ }+ total = stat.Blocks * uint64(stat.Bsize)+ available = stat.Bavail * uint64(stat.Bsize)+ if free := stat.Bfree * uint64(stat.Bsize); total >= free {+ used = total - free+ }+ return total, used, available, nil+}++// MemoryBytes returns total and available bytes on Linux from /proc/meminfo.+// Returns (0, 0, nil) on non-Linux platforms so callers can skip the metric+// without treating it as an error.+func MemoryBytes() (total, available uint64, err error) {+ if runtime.GOOS != "linux" {+ return 0, 0, nil+ }+ f, err := os.Open("/proc/meminfo")+ if err != nil {+ return 0, 0, err+ }+ defer f.Close()+ scanner := bufio.NewScanner(f)+ for scanner.Scan() {+ line := scanner.Text()+ switch {+ case strings.HasPrefix(line, "MemTotal:"):+ total = parseMeminfoKB(line) * 1024+ case strings.HasPrefix(line, "MemAvailable:"):+ available = parseMeminfoKB(line) * 1024+ }+ if total > 0 && available > 0 {+ break+ }+ }+ return total, available, nil+}++// CPUPressure reports stall percentages for the host CPU across three+// rolling windows (avg10, avg60, avg300).+//+// On modern Linux kernels (4.20+) with CONFIG_PSI enabled, source="psi" and+// values come from /proc/pressure/cpu's "some" line — percent of wall time+// during which at least one task was stalled on CPU. This is the right CPU+// pressure signal: it captures CPU saturation independent of utilization+// (a worker at 95% CPU with 0% PSI is fine; one at 60% with rising PSI is+// already in trouble).+//+// On older kernels or non-Linux dev hosts the fallback is source="loadavg":+// /proc/loadavg's 1/5/15-minute values divided by nproc and scaled to a+// percent. Different semantics — loadavg measures runqueue depth, not stall+// time — but it's the same 0..100+ scale and dashboards can flag the source+// label to interpret accordingly.+type CPUPressure struct {+ Avg10, Avg60, Avg300 float64+ Source string // "psi" or "loadavg"+}++func ReadCPUPressure() CPUPressure {+ if runtime.GOOS == "linux" {+ if p, ok := readPSI("/proc/pressure/cpu"); ok {+ p.Source = "psi"+ return p+ }+ }+ return readLoadavgFallback()+}++// readPSI parses /proc/pressure/cpu format:+//+// some avg10=0.00 avg60=0.00 avg300=0.00 total=...+// full avg10=...+//+// We use the "some" line — "full" doesn't apply to CPU pressure anyway+// (it's always 0 for CPU, only meaningful for memory/io).+func readPSI(path string) (CPUPressure, bool) {+ f, err := os.Open(path)+ if err != nil {+ return CPUPressure{}, false+ }+ defer f.Close()+ scanner := bufio.NewScanner(f)+ for scanner.Scan() {+ line := scanner.Text()+ if !strings.HasPrefix(line, "some ") {+ continue+ }+ var p CPUPressure+ for _, field := range strings.Fields(line)[1:] {+ kv := strings.SplitN(field, "=", 2)+ if len(kv) != 2 {+ continue+ }+ v, err := strconv.ParseFloat(kv[1], 64)+ if err != nil {+ continue+ }+ switch kv[0] {+ case "avg10":+ p.Avg10 = v+ case "avg60":+ p.Avg60 = v+ case "avg300":+ p.Avg300 = v+ }+ }+ return p, true+ }+ return CPUPressure{}, false+}++// readLoadavgFallback reads /proc/loadavg (Linux) or returns zero on macOS.+// Scales by 100/nproc so values are roughly comparable to PSI percent+// (loadavg == nproc → ~100%).+func readLoadavgFallback() CPUPressure {+ p := CPUPressure{Source: "loadavg"}+ if runtime.GOOS != "linux" {+ return p+ }+ data, err := os.ReadFile("/proc/loadavg")+ if err != nil {+ return p+ }+ fields := strings.Fields(string(data))+ if len(fields) < 3 {+ return p+ }+ nproc := float64(runtime.NumCPU())+ if nproc < 1 {+ nproc = 1+ }+ parse := func(s string) float64 {+ v, _ := strconv.ParseFloat(s, 64)+ return v / nproc * 100.0+ }+ // /proc/loadavg windows: 1min, 5min, 15min. Map onto avg10/avg60/avg300+ // purely so the same label set works — the windows aren't equivalent but+ // the source="loadavg" label tells dashboards not to mix them with PSI.+ p.Avg10 = parse(fields[0])+ p.Avg60 = parse(fields[1])+ p.Avg300 = parse(fields[2])+ return p+}diff --git a/pkg/types/sandbox.go b/pkg/types/sandbox.goindex f72d77bd..9919dd47 100644--- a/pkg/types/sandbox.go+++ b/pkg/types/sandbox.go@@ -48,7 +48,9 @@ type SandboxConfig struct {DiskMB int `json:"diskMB,omitempty"` // workspace disk in MB (default 20480)Envs map[string]string `json:"envs,omitempty"`Port int `json:"port,omitempty"` // container port to expose via subdomain (default 80)- NetworkEnabled bool `json:"networkEnabled,omitempty"`+ // NetworkEnabled is a pointer so we can distinguish "unset" from+ // "explicitly false". Unset defaults to true (see IsNetworkEnabled).+ NetworkEnabled *bool `json:"networkEnabled,omitempty"`ImageRef string `json:"imageRef,omitempty"` // resolved ECR URI for custom templates// Sandbox snapshot template: S3 keys for rootfs and workspace drives.// When set, the sandbox boots from these drives instead of the standard base image.@@ -107,6 +109,26 @@ var AllowedResourceTiers = []ResourceTier{{MemoryMB: 65536, VCPUs: 16},}+// IsNetworkEnabled returns the effective NetworkEnabled value, defaulting to+// true when unset. Direct deref is unsafe because older persisted configs and+// clients that omit the field produce nil.+func (c SandboxConfig) IsNetworkEnabled() bool {+ if c.NetworkEnabled == nil {+ return true+ }+ return *c.NetworkEnabled+}++// EnsureNetworkEnabledDefault sets NetworkEnabled to true when unset, so the+// value persisted into the DB is explicit and survives round-trips (e.g. fork+// from checkpoint).+func (c *SandboxConfig) EnsureNetworkEnabledDefault() {+ if c.NetworkEnabled == nil {+ t := true+ c.NetworkEnabled = &t+ }+}+// ValidateMemoryMB checks that memoryMB matches an allowed tier and returns the corresponding vCPU count.// Returns 0, nil if memoryMB is 0 (use defaults).func ValidateMemoryMB(memoryMB int) (vcpus int, err error) {diff --git a/proto/agent/agent.pb.go b/proto/agent/agent.pb.goindex faacfcc5..9e3d004d 100644--- a/proto/agent/agent.pb.go+++ b/proto/agent/agent.pb.go@@ -1,7 +1,7 @@// Code generated by protoc-gen-go. DO NOT EDIT.// versions:// protoc-gen-go v1.36.11-// protoc v6.33.4+// protoc v7.34.0// source: proto/agent/agent.protopackage agent@@ -1268,15 +1268,24 @@ func (*StatsRequest) Descriptor() ([]byte, []int) {}type StatsResponse struct {- state protoimpl.MessageState `protogen:"open.v1"`- CpuPercent float64 `protobuf:"fixed64,1,opt,name=cpu_percent,json=cpuPercent,proto3" json:"cpu_percent,omitempty"`- MemUsage uint64 `protobuf:"varint,2,opt,name=mem_usage,json=memUsage,proto3" json:"mem_usage,omitempty"` // bytes- MemLimit uint64 `protobuf:"varint,3,opt,name=mem_limit,json=memLimit,proto3" json:"mem_limit,omitempty"` // bytes- NetInput uint64 `protobuf:"varint,4,opt,name=net_input,json=netInput,proto3" json:"net_input,omitempty"` // bytes- NetOutput uint64 `protobuf:"varint,5,opt,name=net_output,json=netOutput,proto3" json:"net_output,omitempty"` // bytes- Pids int32 `protobuf:"varint,6,opt,name=pids,proto3" json:"pids,omitempty"`- unknownFields protoimpl.UnknownFields- sizeCache protoimpl.SizeCache+ state protoimpl.MessageState `protogen:"open.v1"`+ CpuPercent float64 `protobuf:"fixed64,1,opt,name=cpu_percent,json=cpuPercent,proto3" json:"cpu_percent,omitempty"`+ MemUsage uint64 `protobuf:"varint,2,opt,name=mem_usage,json=memUsage,proto3" json:"mem_usage,omitempty"` // bytes+ MemLimit uint64 `protobuf:"varint,3,opt,name=mem_limit,json=memLimit,proto3" json:"mem_limit,omitempty"` // bytes+ NetInput uint64 `protobuf:"varint,4,opt,name=net_input,json=netInput,proto3" json:"net_input,omitempty"` // bytes+ NetOutput uint64 `protobuf:"varint,5,opt,name=net_output,json=netOutput,proto3" json:"net_output,omitempty"` // bytes+ Pids int32 `protobuf:"varint,6,opt,name=pids,proto3" json:"pids,omitempty"`+ // Disk usage from statvfs() inside the guest. Used by the worker to refuse+ // destructive ops (hibernate, checkpoint) before the rootfs runs out of+ // space and corrupts. Older agents that don't fill these fields report 0,+ // which the worker treats as "unknown" (no pressure gate, falls back to+ // existing behavior).+ RootfsUsedBytes uint64 `protobuf:"varint,7,opt,name=rootfs_used_bytes,json=rootfsUsedBytes,proto3" json:"rootfs_used_bytes,omitempty"`+ RootfsTotalBytes uint64 `protobuf:"varint,8,opt,name=rootfs_total_bytes,json=rootfsTotalBytes,proto3" json:"rootfs_total_bytes,omitempty"`+ WorkspaceUsedBytes uint64 `protobuf:"varint,9,opt,name=workspace_used_bytes,json=workspaceUsedBytes,proto3" json:"workspace_used_bytes,omitempty"`+ WorkspaceTotalBytes uint64 `protobuf:"varint,10,opt,name=workspace_total_bytes,json=workspaceTotalBytes,proto3" json:"workspace_total_bytes,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache}func (x *StatsResponse) Reset() {@@ -1351,6 +1360,34 @@ func (x *StatsResponse) GetPids() int32 {return 0}+func (x *StatsResponse) GetRootfsUsedBytes() uint64 {+ if x != nil {+ return x.RootfsUsedBytes+ }+ return 0+}++func (x *StatsResponse) GetRootfsTotalBytes() uint64 {+ if x != nil {+ return x.RootfsTotalBytes+ }+ return 0+}++func (x *StatsResponse) GetWorkspaceUsedBytes() uint64 {+ if x != nil {+ return x.WorkspaceUsedBytes+ }+ return 0+}++func (x *StatsResponse) GetWorkspaceTotalBytes() uint64 {+ if x != nil {+ return x.WorkspaceTotalBytes+ }+ return 0+}+type PingRequest struct {state protoimpl.MessageState `protogen:"open.v1"`unknownFields protoimpl.UnknownFields@@ -2445,6 +2482,110 @@ func (*SetEnvsResponse) Descriptor() ([]byte, []int) {return file_proto_agent_agent_proto_rawDescGZIP(), []int{44}}+type ConfigureLogshipRequest struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ IngestToken string `protobuf:"bytes,1,opt,name=ingest_token,json=ingestToken,proto3" json:"ingest_token,omitempty"`+ Dataset string `protobuf:"bytes,2,opt,name=dataset,proto3" json:"dataset,omitempty"`+ SandboxId string `protobuf:"bytes,3,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"`+ OrgId string `protobuf:"bytes,4,opt,name=org_id,json=orgId,proto3" json:"org_id,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *ConfigureLogshipRequest) Reset() {+ *x = ConfigureLogshipRequest{}+ mi := &file_proto_agent_agent_proto_msgTypes[45]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *ConfigureLogshipRequest) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*ConfigureLogshipRequest) ProtoMessage() {}++func (x *ConfigureLogshipRequest) ProtoReflect() protoreflect.Message {+ mi := &file_proto_agent_agent_proto_msgTypes[45]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use ConfigureLogshipRequest.ProtoReflect.Descriptor instead.+func (*ConfigureLogshipRequest) Descriptor() ([]byte, []int) {+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{45}+}++func (x *ConfigureLogshipRequest) GetIngestToken() string {+ if x != nil {+ return x.IngestToken+ }+ return ""+}++func (x *ConfigureLogshipRequest) GetDataset() string {+ if x != nil {+ return x.Dataset+ }+ return ""+}++func (x *ConfigureLogshipRequest) GetSandboxId() string {+ if x != nil {+ return x.SandboxId+ }+ return ""+}++func (x *ConfigureLogshipRequest) GetOrgId() string {+ if x != nil {+ return x.OrgId+ }+ return ""+}++type ConfigureLogshipResponse struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *ConfigureLogshipResponse) Reset() {+ *x = ConfigureLogshipResponse{}+ mi := &file_proto_agent_agent_proto_msgTypes[46]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *ConfigureLogshipResponse) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*ConfigureLogshipResponse) ProtoMessage() {}++func (x *ConfigureLogshipResponse) ProtoReflect() protoreflect.Message {+ mi := &file_proto_agent_agent_proto_msgTypes[46]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use ConfigureLogshipResponse.ProtoReflect.Descriptor instead.+func (*ConfigureLogshipResponse) Descriptor() ([]byte, []int) {+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{46}+}+type ShutdownRequest struct {state protoimpl.MessageState `protogen:"open.v1"`unknownFields protoimpl.UnknownFields@@ -2453,7 +2594,7 @@ type ShutdownRequest struct {func (x *ShutdownRequest) Reset() {*x = ShutdownRequest{}- mi := &file_proto_agent_agent_proto_msgTypes[45]+ mi := &file_proto_agent_agent_proto_msgTypes[47]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -2465,7 +2606,7 @@ func (x *ShutdownRequest) String() string {func (*ShutdownRequest) ProtoMessage() {}func (x *ShutdownRequest) ProtoReflect() protoreflect.Message {- mi := &file_proto_agent_agent_proto_msgTypes[45]+ mi := &file_proto_agent_agent_proto_msgTypes[47]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -2478,7 +2619,7 @@ func (x *ShutdownRequest) ProtoReflect() protoreflect.Message {// Deprecated: Use ShutdownRequest.ProtoReflect.Descriptor instead.func (*ShutdownRequest) Descriptor() ([]byte, []int) {- return file_proto_agent_agent_proto_rawDescGZIP(), []int{45}+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{47}}type ShutdownResponse struct {@@ -2489,7 +2630,7 @@ type ShutdownResponse struct {func (x *ShutdownResponse) Reset() {*x = ShutdownResponse{}- mi := &file_proto_agent_agent_proto_msgTypes[46]+ mi := &file_proto_agent_agent_proto_msgTypes[48]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -2501,7 +2642,7 @@ func (x *ShutdownResponse) String() string {func (*ShutdownResponse) ProtoMessage() {}func (x *ShutdownResponse) ProtoReflect() protoreflect.Message {- mi := &file_proto_agent_agent_proto_msgTypes[46]+ mi := &file_proto_agent_agent_proto_msgTypes[48]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -2514,7 +2655,7 @@ func (x *ShutdownResponse) ProtoReflect() protoreflect.Message {// Deprecated: Use ShutdownResponse.ProtoReflect.Descriptor instead.func (*ShutdownResponse) Descriptor() ([]byte, []int) {- return file_proto_agent_agent_proto_rawDescGZIP(), []int{46}+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{48}}type SyncFSRequest struct {@@ -2525,7 +2666,7 @@ type SyncFSRequest struct {func (x *SyncFSRequest) Reset() {*x = SyncFSRequest{}- mi := &file_proto_agent_agent_proto_msgTypes[47]+ mi := &file_proto_agent_agent_proto_msgTypes[49]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -2537,7 +2678,7 @@ func (x *SyncFSRequest) String() string {func (*SyncFSRequest) ProtoMessage() {}func (x *SyncFSRequest) ProtoReflect() protoreflect.Message {- mi := &file_proto_agent_agent_proto_msgTypes[47]+ mi := &file_proto_agent_agent_proto_msgTypes[49]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -2550,7 +2691,7 @@ func (x *SyncFSRequest) ProtoReflect() protoreflect.Message {// Deprecated: Use SyncFSRequest.ProtoReflect.Descriptor instead.func (*SyncFSRequest) Descriptor() ([]byte, []int) {- return file_proto_agent_agent_proto_rawDescGZIP(), []int{47}+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{49}}type SyncFSResponse struct {@@ -2561,7 +2702,7 @@ type SyncFSResponse struct {func (x *SyncFSResponse) Reset() {*x = SyncFSResponse{}- mi := &file_proto_agent_agent_proto_msgTypes[48]+ mi := &file_proto_agent_agent_proto_msgTypes[50]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -2573,7 +2714,7 @@ func (x *SyncFSResponse) String() string {func (*SyncFSResponse) ProtoMessage() {}func (x *SyncFSResponse) ProtoReflect() protoreflect.Message {- mi := &file_proto_agent_agent_proto_msgTypes[48]+ mi := &file_proto_agent_agent_proto_msgTypes[50]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -2586,7 +2727,7 @@ func (x *SyncFSResponse) ProtoReflect() protoreflect.Message {// Deprecated: Use SyncFSResponse.ProtoReflect.Descriptor instead.func (*SyncFSResponse) Descriptor() ([]byte, []int) {- return file_proto_agent_agent_proto_rawDescGZIP(), []int{48}+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{50}}type PrepareHibernateRequest struct {@@ -2597,7 +2738,7 @@ type PrepareHibernateRequest struct {func (x *PrepareHibernateRequest) Reset() {*x = PrepareHibernateRequest{}- mi := &file_proto_agent_agent_proto_msgTypes[49]+ mi := &file_proto_agent_agent_proto_msgTypes[51]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -2609,7 +2750,7 @@ func (x *PrepareHibernateRequest) String() string {func (*PrepareHibernateRequest) ProtoMessage() {}func (x *PrepareHibernateRequest) ProtoReflect() protoreflect.Message {- mi := &file_proto_agent_agent_proto_msgTypes[49]+ mi := &file_proto_agent_agent_proto_msgTypes[51]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -2622,7 +2763,7 @@ func (x *PrepareHibernateRequest) ProtoReflect() protoreflect.Message {// Deprecated: Use PrepareHibernateRequest.ProtoReflect.Descriptor instead.func (*PrepareHibernateRequest) Descriptor() ([]byte, []int) {- return file_proto_agent_agent_proto_rawDescGZIP(), []int{49}+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{51}}type PrepareHibernateResponse struct {@@ -2633,7 +2774,7 @@ type PrepareHibernateResponse struct {func (x *PrepareHibernateResponse) Reset() {*x = PrepareHibernateResponse{}- mi := &file_proto_agent_agent_proto_msgTypes[50]+ mi := &file_proto_agent_agent_proto_msgTypes[52]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -2645,7 +2786,7 @@ func (x *PrepareHibernateResponse) String() string {func (*PrepareHibernateResponse) ProtoMessage() {}func (x *PrepareHibernateResponse) ProtoReflect() protoreflect.Message {- mi := &file_proto_agent_agent_proto_msgTypes[50]+ mi := &file_proto_agent_agent_proto_msgTypes[52]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -2658,7 +2799,7 @@ func (x *PrepareHibernateResponse) ProtoReflect() protoreflect.Message {// Deprecated: Use PrepareHibernateResponse.ProtoReflect.Descriptor instead.func (*PrepareHibernateResponse) Descriptor() ([]byte, []int) {- return file_proto_agent_agent_proto_rawDescGZIP(), []int{50}+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{52}}type SetResourceLimitsRequest struct {@@ -2673,7 +2814,7 @@ type SetResourceLimitsRequest struct {func (x *SetResourceLimitsRequest) Reset() {*x = SetResourceLimitsRequest{}- mi := &file_proto_agent_agent_proto_msgTypes[51]+ mi := &file_proto_agent_agent_proto_msgTypes[53]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -2685,7 +2826,7 @@ func (x *SetResourceLimitsRequest) String() string {func (*SetResourceLimitsRequest) ProtoMessage() {}func (x *SetResourceLimitsRequest) ProtoReflect() protoreflect.Message {- mi := &file_proto_agent_agent_proto_msgTypes[51]+ mi := &file_proto_agent_agent_proto_msgTypes[53]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -2698,7 +2839,7 @@ func (x *SetResourceLimitsRequest) ProtoReflect() protoreflect.Message {// Deprecated: Use SetResourceLimitsRequest.ProtoReflect.Descriptor instead.func (*SetResourceLimitsRequest) Descriptor() ([]byte, []int) {- return file_proto_agent_agent_proto_rawDescGZIP(), []int{51}+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{53}}func (x *SetResourceLimitsRequest) GetMaxPids() int32 {@@ -2737,7 +2878,7 @@ type SetResourceLimitsResponse struct {func (x *SetResourceLimitsResponse) Reset() {*x = SetResourceLimitsResponse{}- mi := &file_proto_agent_agent_proto_msgTypes[52]+ mi := &file_proto_agent_agent_proto_msgTypes[54]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -2749,7 +2890,7 @@ func (x *SetResourceLimitsResponse) String() string {func (*SetResourceLimitsResponse) ProtoMessage() {}func (x *SetResourceLimitsResponse) ProtoReflect() protoreflect.Message {- mi := &file_proto_agent_agent_proto_msgTypes[52]+ mi := &file_proto_agent_agent_proto_msgTypes[54]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -2762,7 +2903,7 @@ func (x *SetResourceLimitsResponse) ProtoReflect() protoreflect.Message {// Deprecated: Use SetResourceLimitsResponse.ProtoReflect.Descriptor instead.func (*SetResourceLimitsResponse) Descriptor() ([]byte, []int) {- return file_proto_agent_agent_proto_rawDescGZIP(), []int{52}+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{54}}type GetVersionRequest struct {@@ -2773,7 +2914,7 @@ type GetVersionRequest struct {func (x *GetVersionRequest) Reset() {*x = GetVersionRequest{}- mi := &file_proto_agent_agent_proto_msgTypes[53]+ mi := &file_proto_agent_agent_proto_msgTypes[55]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -2785,7 +2926,7 @@ func (x *GetVersionRequest) String() string {func (*GetVersionRequest) ProtoMessage() {}func (x *GetVersionRequest) ProtoReflect() protoreflect.Message {- mi := &file_proto_agent_agent_proto_msgTypes[53]+ mi := &file_proto_agent_agent_proto_msgTypes[55]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -2798,7 +2939,7 @@ func (x *GetVersionRequest) ProtoReflect() protoreflect.Message {// Deprecated: Use GetVersionRequest.ProtoReflect.Descriptor instead.func (*GetVersionRequest) Descriptor() ([]byte, []int) {- return file_proto_agent_agent_proto_rawDescGZIP(), []int{53}+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{55}}type GetVersionResponse struct {@@ -2810,7 +2951,7 @@ type GetVersionResponse struct {func (x *GetVersionResponse) Reset() {*x = GetVersionResponse{}- mi := &file_proto_agent_agent_proto_msgTypes[54]+ mi := &file_proto_agent_agent_proto_msgTypes[56]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -2822,7 +2963,7 @@ func (x *GetVersionResponse) String() string {func (*GetVersionResponse) ProtoMessage() {}func (x *GetVersionResponse) ProtoReflect() protoreflect.Message {- mi := &file_proto_agent_agent_proto_msgTypes[54]+ mi := &file_proto_agent_agent_proto_msgTypes[56]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -2835,7 +2976,7 @@ func (x *GetVersionResponse) ProtoReflect() protoreflect.Message {// Deprecated: Use GetVersionResponse.ProtoReflect.Descriptor instead.func (*GetVersionResponse) Descriptor() ([]byte, []int) {- return file_proto_agent_agent_proto_rawDescGZIP(), []int{54}+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{56}}func (x *GetVersionResponse) GetVersion() string {@@ -2854,7 +2995,7 @@ type UpgradeRequest struct {func (x *UpgradeRequest) Reset() {*x = UpgradeRequest{}- mi := &file_proto_agent_agent_proto_msgTypes[55]+ mi := &file_proto_agent_agent_proto_msgTypes[57]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -2866,7 +3007,7 @@ func (x *UpgradeRequest) String() string {func (*UpgradeRequest) ProtoMessage() {}func (x *UpgradeRequest) ProtoReflect() protoreflect.Message {- mi := &file_proto_agent_agent_proto_msgTypes[55]+ mi := &file_proto_agent_agent_proto_msgTypes[57]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -2879,7 +3020,7 @@ func (x *UpgradeRequest) ProtoReflect() protoreflect.Message {// Deprecated: Use UpgradeRequest.ProtoReflect.Descriptor instead.func (*UpgradeRequest) Descriptor() ([]byte, []int) {- return file_proto_agent_agent_proto_rawDescGZIP(), []int{55}+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{57}}func (x *UpgradeRequest) GetBinaryPath() string {@@ -2898,7 +3039,7 @@ type UpgradeResponse struct {func (x *UpgradeResponse) Reset() {*x = UpgradeResponse{}- mi := &file_proto_agent_agent_proto_msgTypes[56]+ mi := &file_proto_agent_agent_proto_msgTypes[58]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -2910,7 +3051,7 @@ func (x *UpgradeResponse) String() string {func (*UpgradeResponse) ProtoMessage() {}func (x *UpgradeResponse) ProtoReflect() protoreflect.Message {- mi := &file_proto_agent_agent_proto_msgTypes[56]+ mi := &file_proto_agent_agent_proto_msgTypes[58]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -2923,7 +3064,7 @@ func (x *UpgradeResponse) ProtoReflect() protoreflect.Message {// Deprecated: Use UpgradeResponse.ProtoReflect.Descriptor instead.func (*UpgradeResponse) Descriptor() ([]byte, []int) {- return file_proto_agent_agent_proto_rawDescGZIP(), []int{56}+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{58}}func (x *UpgradeResponse) GetOk() bool {@@ -3009,7 +3150,7 @@ const file_proto_agent_agent_proto_rawDesc = "" +"\x04mode\x18\x04 \x01(\tR\x04mode\x12\x19\n" +"\bmod_time\x18\x05 \x01(\tR\amodTime\x12\x12\n" +"\x04path\x18\x06 \x01(\tR\x04path\"\x0e\n" +- "\fStatsRequest\"\xba\x01\n" ++ "\fStatsRequest\"\xfa\x02\n" +"\rStatsResponse\x12\x1f\n" +"\vcpu_percent\x18\x01 \x01(\x01R\n" +"cpuPercent\x12\x1b\n" +@@ -3018,7 +3159,12 @@ const file_proto_agent_agent_proto_rawDesc = "" +"\tnet_input\x18\x04 \x01(\x04R\bnetInput\x12\x1d\n" +"\n" +"net_output\x18\x05 \x01(\x04R\tnetOutput\x12\x12\n" +- "\x04pids\x18\x06 \x01(\x05R\x04pids\"\r\n" ++ "\x04pids\x18\x06 \x01(\x05R\x04pids\x12*\n" ++ "\x11rootfs_used_bytes\x18\a \x01(\x04R\x0frootfsUsedBytes\x12,\n" ++ "\x12rootfs_total_bytes\x18\b \x01(\x04R\x10rootfsTotalBytes\x120\n" ++ "\x14workspace_used_bytes\x18\t \x01(\x04R\x12workspaceUsedBytes\x122\n" ++ "\x15workspace_total_bytes\x18\n" ++ " \x01(\x04R\x13workspaceTotalBytes\"\r\n" +"\vPingRequest\"O\n" +"\fPingResponse\x12\x18\n" +"\aversion\x18\x01 \x01(\tR\aversion\x12%\n" +@@ -3103,7 +3249,14 @@ const file_proto_agent_agent_proto_rawDesc = "" +"\tEnvsEntry\x12\x10\n" +"\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +"\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"\x11\n" +- "\x0fSetEnvsResponse\"\x11\n" ++ "\x0fSetEnvsResponse\"\x8c\x01\n" ++ "\x17ConfigureLogshipRequest\x12!\n" ++ "\fingest_token\x18\x01 \x01(\tR\vingestToken\x12\x18\n" ++ "\adataset\x18\x02 \x01(\tR\adataset\x12\x1d\n" ++ "\n" ++ "sandbox_id\x18\x03 \x01(\tR\tsandboxId\x12\x15\n" ++ "\x06org_id\x18\x04 \x01(\tR\x05orgId\"\x1a\n" ++ "\x18ConfigureLogshipResponse\"\x11\n" +"\x0fShutdownRequest\"\x12\n" +"\x10ShutdownResponse\"\x0f\n" +"\rSyncFSRequest\"\x10\n" +@@ -3124,7 +3277,7 @@ const file_proto_agent_agent_proto_rawDesc = "" +"\vbinary_path\x18\x01 \x01(\tR\n" +"binaryPath\"!\n" +"\x0fUpgradeResponse\x12\x0e\n" +- "\x02ok\x18\x01 \x01(\bR\x02ok2\x96\x0e\n" ++ "\x02ok\x18\x01 \x01(\bR\x02ok2\xeb\x0e\n" +"\fSandboxAgent\x12/\n" +"\x04Exec\x12\x12.agent.ExecRequest\x1a\x13.agent.ExecResponse\x12:\n" +"\n" +@@ -3148,7 +3301,8 @@ const file_proto_agent_agent_proto_rawDesc = "" +"\x11ExecSessionAttach\x12\x17.agent.ExecSessionInput\x1a\x18.agent.ExecSessionOutput(\x010\x01\x12P\n" +"\x0fExecSessionList\x12\x1d.agent.ExecSessionListRequest\x1a\x1e.agent.ExecSessionListResponse\x12P\n" +"\x0fExecSessionKill\x12\x1d.agent.ExecSessionKillRequest\x1a\x1e.agent.ExecSessionKillResponse\x128\n" +- "\aSetEnvs\x12\x15.agent.SetEnvsRequest\x1a\x16.agent.SetEnvsResponse\x12;\n" ++ "\aSetEnvs\x12\x15.agent.SetEnvsRequest\x1a\x16.agent.SetEnvsResponse\x12S\n" ++ "\x10ConfigureLogship\x12\x1e.agent.ConfigureLogshipRequest\x1a\x1f.agent.ConfigureLogshipResponse\x12;\n" +"\bShutdown\x12\x16.agent.ShutdownRequest\x1a\x17.agent.ShutdownResponse\x125\n" +"\x06SyncFS\x12\x14.agent.SyncFSRequest\x1a\x15.agent.SyncFSResponse\x12S\n" +"\x10PrepareHibernate\x12\x1e.agent.PrepareHibernateRequest\x1a\x1f.agent.PrepareHibernateResponse\x12V\n" +@@ -3170,7 +3324,7 @@ func file_proto_agent_agent_proto_rawDescGZIP() []byte {}var file_proto_agent_agent_proto_enumTypes = make([]protoimpl.EnumInfo, 2)-var file_proto_agent_agent_proto_msgTypes = make([]protoimpl.MessageInfo, 60)+var file_proto_agent_agent_proto_msgTypes = make([]protoimpl.MessageInfo, 62)var file_proto_agent_agent_proto_goTypes = []any{(ExecOutputChunk_Stream)(0), // 0: agent.ExecOutputChunk.Stream(ExecSessionOutput_Type)(0), // 1: agent.ExecSessionOutput.Type@@ -3219,30 +3373,32 @@ var file_proto_agent_agent_proto_goTypes = []any{(*ExecSessionKillResponse)(nil), // 44: agent.ExecSessionKillResponse(*SetEnvsRequest)(nil), // 45: agent.SetEnvsRequest(*SetEnvsResponse)(nil), // 46: agent.SetEnvsResponse- (*ShutdownRequest)(nil), // 47: agent.ShutdownRequest- (*ShutdownResponse)(nil), // 48: agent.ShutdownResponse- (*SyncFSRequest)(nil), // 49: agent.SyncFSRequest- (*SyncFSResponse)(nil), // 50: agent.SyncFSResponse- (*PrepareHibernateRequest)(nil), // 51: agent.PrepareHibernateRequest- (*PrepareHibernateResponse)(nil), // 52: agent.PrepareHibernateResponse- (*SetResourceLimitsRequest)(nil), // 53: agent.SetResourceLimitsRequest- (*SetResourceLimitsResponse)(nil), // 54: agent.SetResourceLimitsResponse- (*GetVersionRequest)(nil), // 55: agent.GetVersionRequest- (*GetVersionResponse)(nil), // 56: agent.GetVersionResponse- (*UpgradeRequest)(nil), // 57: agent.UpgradeRequest- (*UpgradeResponse)(nil), // 58: agent.UpgradeResponse- nil, // 59: agent.ExecRequest.EnvsEntry- nil, // 60: agent.ExecSessionCreateRequest.EnvsEntry- nil, // 61: agent.SetEnvsRequest.EnvsEntry+ (*ConfigureLogshipRequest)(nil), // 47: agent.ConfigureLogshipRequest+ (*ConfigureLogshipResponse)(nil), // 48: agent.ConfigureLogshipResponse+ (*ShutdownRequest)(nil), // 49: agent.ShutdownRequest+ (*ShutdownResponse)(nil), // 50: agent.ShutdownResponse+ (*SyncFSRequest)(nil), // 51: agent.SyncFSRequest+ (*SyncFSResponse)(nil), // 52: agent.SyncFSResponse+ (*PrepareHibernateRequest)(nil), // 53: agent.PrepareHibernateRequest+ (*PrepareHibernateResponse)(nil), // 54: agent.PrepareHibernateResponse+ (*SetResourceLimitsRequest)(nil), // 55: agent.SetResourceLimitsRequest+ (*SetResourceLimitsResponse)(nil), // 56: agent.SetResourceLimitsResponse+ (*GetVersionRequest)(nil), // 57: agent.GetVersionRequest+ (*GetVersionResponse)(nil), // 58: agent.GetVersionResponse+ (*UpgradeRequest)(nil), // 59: agent.UpgradeRequest+ (*UpgradeResponse)(nil), // 60: agent.UpgradeResponse+ nil, // 61: agent.ExecRequest.EnvsEntry+ nil, // 62: agent.ExecSessionCreateRequest.EnvsEntry+ nil, // 63: agent.SetEnvsRequest.EnvsEntry}var file_proto_agent_agent_proto_depIdxs = []int32{- 59, // 0: agent.ExecRequest.envs:type_name -> agent.ExecRequest.EnvsEntry+ 61, // 0: agent.ExecRequest.envs:type_name -> agent.ExecRequest.EnvsEntry0, // 1: agent.ExecOutputChunk.stream:type_name -> agent.ExecOutputChunk.Stream14, // 2: agent.ListDirResponse.entries:type_name -> agent.DirEntry- 60, // 3: agent.ExecSessionCreateRequest.envs:type_name -> agent.ExecSessionCreateRequest.EnvsEntry+ 62, // 3: agent.ExecSessionCreateRequest.envs:type_name -> agent.ExecSessionCreateRequest.EnvsEntry1, // 4: agent.ExecSessionOutput.type:type_name -> agent.ExecSessionOutput.Type42, // 5: agent.ExecSessionListResponse.sessions:type_name -> agent.ExecSessionInfo- 61, // 6: agent.SetEnvsRequest.envs:type_name -> agent.SetEnvsRequest.EnvsEntry+ 63, // 6: agent.SetEnvsRequest.envs:type_name -> agent.SetEnvsRequest.EnvsEntry2, // 7: agent.SandboxAgent.Exec:input_type -> agent.ExecRequest2, // 8: agent.SandboxAgent.ExecStream:input_type -> agent.ExecRequest5, // 9: agent.SandboxAgent.ReadFile:input_type -> agent.ReadFileRequest@@ -3265,42 +3421,44 @@ var file_proto_agent_agent_proto_depIdxs = []int32{40, // 26: agent.SandboxAgent.ExecSessionList:input_type -> agent.ExecSessionListRequest43, // 27: agent.SandboxAgent.ExecSessionKill:input_type -> agent.ExecSessionKillRequest45, // 28: agent.SandboxAgent.SetEnvs:input_type -> agent.SetEnvsRequest- 47, // 29: agent.SandboxAgent.Shutdown:input_type -> agent.ShutdownRequest- 49, // 30: agent.SandboxAgent.SyncFS:input_type -> agent.SyncFSRequest- 51, // 31: agent.SandboxAgent.PrepareHibernate:input_type -> agent.PrepareHibernateRequest- 53, // 32: agent.SandboxAgent.SetResourceLimits:input_type -> agent.SetResourceLimitsRequest- 55, // 33: agent.SandboxAgent.GetVersion:input_type -> agent.GetVersionRequest- 57, // 34: agent.SandboxAgent.Upgrade:input_type -> agent.UpgradeRequest- 3, // 35: agent.SandboxAgent.Exec:output_type -> agent.ExecResponse- 4, // 36: agent.SandboxAgent.ExecStream:output_type -> agent.ExecOutputChunk- 6, // 37: agent.SandboxAgent.ReadFile:output_type -> agent.ReadFileResponse- 8, // 38: agent.SandboxAgent.WriteFile:output_type -> agent.WriteFileResponse- 10, // 39: agent.SandboxAgent.ReadFileStream:output_type -> agent.FileChunk- 12, // 40: agent.SandboxAgent.WriteFileStream:output_type -> agent.WriteFileStreamResponse- 15, // 41: agent.SandboxAgent.ListDir:output_type -> agent.ListDirResponse- 17, // 42: agent.SandboxAgent.MakeDir:output_type -> agent.MakeDirResponse- 19, // 43: agent.SandboxAgent.Remove:output_type -> agent.RemoveResponse- 21, // 44: agent.SandboxAgent.Exists:output_type -> agent.ExistsResponse- 23, // 45: agent.SandboxAgent.Stat:output_type -> agent.StatResponse- 25, // 46: agent.SandboxAgent.Stats:output_type -> agent.StatsResponse- 27, // 47: agent.SandboxAgent.Ping:output_type -> agent.PingResponse- 29, // 48: agent.SandboxAgent.PTYCreate:output_type -> agent.PTYCreateResponse- 31, // 49: agent.SandboxAgent.PTYResize:output_type -> agent.PTYResizeResponse- 33, // 50: agent.SandboxAgent.PTYKill:output_type -> agent.PTYKillResponse- 35, // 51: agent.SandboxAgent.PTYAttach:output_type -> agent.PTYOutput- 37, // 52: agent.SandboxAgent.ExecSessionCreate:output_type -> agent.ExecSessionCreateResponse- 39, // 53: agent.SandboxAgent.ExecSessionAttach:output_type -> agent.ExecSessionOutput- 41, // 54: agent.SandboxAgent.ExecSessionList:output_type -> agent.ExecSessionListResponse- 44, // 55: agent.SandboxAgent.ExecSessionKill:output_type -> agent.ExecSessionKillResponse- 46, // 56: agent.SandboxAgent.SetEnvs:output_type -> agent.SetEnvsResponse- 48, // 57: agent.SandboxAgent.Shutdown:output_type -> agent.ShutdownResponse- 50, // 58: agent.SandboxAgent.SyncFS:output_type -> agent.SyncFSResponse- 52, // 59: agent.SandboxAgent.PrepareHibernate:output_type -> agent.PrepareHibernateResponse- 54, // 60: agent.SandboxAgent.SetResourceLimits:output_type -> agent.SetResourceLimitsResponse- 56, // 61: agent.SandboxAgent.GetVersion:output_type -> agent.GetVersionResponse- 58, // 62: agent.SandboxAgent.Upgrade:output_type -> agent.UpgradeResponse- 35, // [35:63] is the sub-list for method output_type- 7, // [7:35] is the sub-list for method input_type+ 47, // 29: agent.SandboxAgent.ConfigureLogship:input_type -> agent.ConfigureLogshipRequest+ 49, // 30: agent.SandboxAgent.Shutdown:input_type -> agent.ShutdownRequest+ 51, // 31: agent.SandboxAgent.SyncFS:input_type -> agent.SyncFSRequest+ 53, // 32: agent.SandboxAgent.PrepareHibernate:input_type -> agent.PrepareHibernateRequest+ 55, // 33: agent.SandboxAgent.SetResourceLimits:input_type -> agent.SetResourceLimitsRequest+ 57, // 34: agent.SandboxAgent.GetVersion:input_type -> agent.GetVersionRequest+ 59, // 35: agent.SandboxAgent.Upgrade:input_type -> agent.UpgradeRequest+ 3, // 36: agent.SandboxAgent.Exec:output_type -> agent.ExecResponse+ 4, // 37: agent.SandboxAgent.ExecStream:output_type -> agent.ExecOutputChunk+ 6, // 38: agent.SandboxAgent.ReadFile:output_type -> agent.ReadFileResponse+ 8, // 39: agent.SandboxAgent.WriteFile:output_type -> agent.WriteFileResponse+ 10, // 40: agent.SandboxAgent.ReadFileStream:output_type -> agent.FileChunk+ 12, // 41: agent.SandboxAgent.WriteFileStream:output_type -> agent.WriteFileStreamResponse+ 15, // 42: agent.SandboxAgent.ListDir:output_type -> agent.ListDirResponse+ 17, // 43: agent.SandboxAgent.MakeDir:output_type -> agent.MakeDirResponse+ 19, // 44: agent.SandboxAgent.Remove:output_type -> agent.RemoveResponse+ 21, // 45: agent.SandboxAgent.Exists:output_type -> agent.ExistsResponse+ 23, // 46: agent.SandboxAgent.Stat:output_type -> agent.StatResponse+ 25, // 47: agent.SandboxAgent.Stats:output_type -> agent.StatsResponse+ 27, // 48: agent.SandboxAgent.Ping:output_type -> agent.PingResponse+ 29, // 49: agent.SandboxAgent.PTYCreate:output_type -> agent.PTYCreateResponse+ 31, // 50: agent.SandboxAgent.PTYResize:output_type -> agent.PTYResizeResponse+ 33, // 51: agent.SandboxAgent.PTYKill:output_type -> agent.PTYKillResponse+ 35, // 52: agent.SandboxAgent.PTYAttach:output_type -> agent.PTYOutput+ 37, // 53: agent.SandboxAgent.ExecSessionCreate:output_type -> agent.ExecSessionCreateResponse+ 39, // 54: agent.SandboxAgent.ExecSessionAttach:output_type -> agent.ExecSessionOutput+ 41, // 55: agent.SandboxAgent.ExecSessionList:output_type -> agent.ExecSessionListResponse+ 44, // 56: agent.SandboxAgent.ExecSessionKill:output_type -> agent.ExecSessionKillResponse+ 46, // 57: agent.SandboxAgent.SetEnvs:output_type -> agent.SetEnvsResponse+ 48, // 58: agent.SandboxAgent.ConfigureLogship:output_type -> agent.ConfigureLogshipResponse+ 50, // 59: agent.SandboxAgent.Shutdown:output_type -> agent.ShutdownResponse+ 52, // 60: agent.SandboxAgent.SyncFS:output_type -> agent.SyncFSResponse+ 54, // 61: agent.SandboxAgent.PrepareHibernate:output_type -> agent.PrepareHibernateResponse+ 56, // 62: agent.SandboxAgent.SetResourceLimits:output_type -> agent.SetResourceLimitsResponse+ 58, // 63: agent.SandboxAgent.GetVersion:output_type -> agent.GetVersionResponse+ 60, // 64: agent.SandboxAgent.Upgrade:output_type -> agent.UpgradeResponse+ 36, // [36:65] is the sub-list for method output_type+ 7, // [7:36] is the sub-list for method input_type7, // [7:7] is the sub-list for extension type_name7, // [7:7] is the sub-list for extension extendee0, // [0:7] is the sub-list for field type_name@@ -3317,7 +3475,7 @@ func file_proto_agent_agent_proto_init() {GoPackagePath: reflect.TypeOf(x{}).PkgPath(),RawDescriptor: unsafe.Slice(unsafe.StringData(file_proto_agent_agent_proto_rawDesc), len(file_proto_agent_agent_proto_rawDesc)),NumEnums: 2,- NumMessages: 60,+ NumMessages: 62,NumExtensions: 0,NumServices: 1,},diff --git a/proto/agent/agent.proto b/proto/agent/agent.protoindex d99d3c6f..ef52e45c 100644--- a/proto/agent/agent.proto+++ b/proto/agent/agent.proto@@ -78,6 +78,13 @@ service SandboxAgent {// between the base OS env and per-command envs.rpc SetEnvs(SetEnvsRequest) returns (SetEnvsResponse);+ // ConfigureLogship sets sandbox session log-shipping configuration.+ // Worker calls this immediately after VM boot, before any user-facing+ // operations. Empty ingest_token disables shipping (kill-switch).+ // If never called, the agent's forwarder stays dormant — log events+ // queue in a bounded ring and are dropped oldest-first.+ rpc ConfigureLogship(ConfigureLogshipRequest) returns (ConfigureLogshipResponse);+// Shutdown gracefully terminates the agent and syncs disks.rpc Shutdown(ShutdownRequest) returns (ShutdownResponse);@@ -227,6 +234,15 @@ message StatsResponse {uint64 net_input = 4; // bytesuint64 net_output = 5; // bytesint32 pids = 6;+ // Disk usage from statvfs() inside the guest. Used by the worker to refuse+ // destructive ops (hibernate, checkpoint) before the rootfs runs out of+ // space and corrupts. Older agents that don't fill these fields report 0,+ // which the worker treats as "unknown" (no pressure gate, falls back to+ // existing behavior).+ uint64 rootfs_used_bytes = 7;+ uint64 rootfs_total_bytes = 8;+ uint64 workspace_used_bytes = 9;+ uint64 workspace_total_bytes = 10;}// --- Ping ---@@ -342,6 +358,17 @@ message SetEnvsRequest {message SetEnvsResponse {}+// --- Logship ---++message ConfigureLogshipRequest {+ string ingest_token = 1;+ string dataset = 2;+ string sandbox_id = 3;+ string org_id = 4;+}++message ConfigureLogshipResponse {}+// --- Shutdown ---message ShutdownRequest {}diff --git a/proto/agent/agent_grpc.pb.go b/proto/agent/agent_grpc.pb.goindex 39d04b42..ae83f1f0 100644--- a/proto/agent/agent_grpc.pb.go+++ b/proto/agent/agent_grpc.pb.go@@ -1,7 +1,7 @@// Code generated by protoc-gen-go-grpc. DO NOT EDIT.// versions:// - protoc-gen-go-grpc v1.6.1-// - protoc v6.33.4+// - protoc v7.34.0// source: proto/agent/agent.protopackage agent@@ -41,6 +41,7 @@ const (SandboxAgent_ExecSessionList_FullMethodName = "/agent.SandboxAgent/ExecSessionList"SandboxAgent_ExecSessionKill_FullMethodName = "/agent.SandboxAgent/ExecSessionKill"SandboxAgent_SetEnvs_FullMethodName = "/agent.SandboxAgent/SetEnvs"+ SandboxAgent_ConfigureLogship_FullMethodName = "/agent.SandboxAgent/ConfigureLogship"SandboxAgent_Shutdown_FullMethodName = "/agent.SandboxAgent/Shutdown"SandboxAgent_SyncFS_FullMethodName = "/agent.SandboxAgent/SyncFS"SandboxAgent_PrepareHibernate_FullMethodName = "/agent.SandboxAgent/PrepareHibernate"@@ -53,8 +54,34 @@ const (//// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.//-// SandboxAgent runs inside each Firecracker microVM and handles-// exec, file ops, PTY, and stats over gRPC via vsock.+// SandboxAgent is the in-guest RPC surface. It runs as PID 1 (or under+// systemd) inside every sandbox VM and is reachable from the host worker+// over virtio-serial (Unix domain socket) or vsock.+//+// === STABILITY CONTRACT ===+// This proto is a stable, backward-compatible public API. Long-running+// sandboxes can live for weeks or months; their in-guest agent continues+// running whatever version was baked into the rootfs at sandbox-creation+// time. The worker must be able to talk to those old agents indefinitely.+//+// Allowed changes:+// - Adding new RPCs+// - Adding new optional fields to existing messages (with new field numbers)+// - Adding new enum values+//+// FORBIDDEN changes:+// - Removing or renaming RPCs, messages, fields, or enum values+// - Repurposing existing field numbers for different semantics+// - Making previously-optional fields required+// - Changing field types in a non-wire-compatible way+//+// New capabilities should prefer being implemented worker-side, composing+// Exec + file primitives, rather than adding a new agent RPC. An agent+// binary update requires the sandbox to be destroyed and recreated; there+// is intentionally no runtime upgrade path.+//+// See internal/qemu/manager.go "Runtime agent upgrade" comment for the+// full rationale on why we don't hot-upgrade.type SandboxAgentClient interface {// Exec runs a command and returns the result after completion.Exec(ctx context.Context, in *ExecRequest, opts ...grpc.CallOption) (*ExecResponse, error)@@ -91,6 +118,12 @@ type SandboxAgentClient interface {// These are injected into every subsequent Exec/ExecStream call,// between the base OS env and per-command envs.SetEnvs(ctx context.Context, in *SetEnvsRequest, opts ...grpc.CallOption) (*SetEnvsResponse, error)+ // ConfigureLogship sets sandbox session log-shipping configuration.+ // Worker calls this immediately after VM boot, before any user-facing+ // operations. Empty ingest_token disables shipping (kill-switch).+ // If never called, the agent's forwarder stays dormant — log events+ // queue in a bounded ring and are dropped oldest-first.+ ConfigureLogship(ctx context.Context, in *ConfigureLogshipRequest, opts ...grpc.CallOption) (*ConfigureLogshipResponse, error)// Shutdown gracefully terminates the agent and syncs disks.Shutdown(ctx context.Context, in *ShutdownRequest, opts ...grpc.CallOption) (*ShutdownResponse, error)// SyncFS flushes all filesystem buffers without exiting.@@ -366,6 +399,16 @@ func (c *sandboxAgentClient) SetEnvs(ctx context.Context, in *SetEnvsRequest, opreturn out, nil}+func (c *sandboxAgentClient) ConfigureLogship(ctx context.Context, in *ConfigureLogshipRequest, opts ...grpc.CallOption) (*ConfigureLogshipResponse, error) {+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)+ out := new(ConfigureLogshipResponse)+ err := c.cc.Invoke(ctx, SandboxAgent_ConfigureLogship_FullMethodName, in, out, cOpts...)+ if err != nil {+ return nil, err+ }+ return out, nil+}+func (c *sandboxAgentClient) Shutdown(ctx context.Context, in *ShutdownRequest, opts ...grpc.CallOption) (*ShutdownResponse, error) {cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)out := new(ShutdownResponse)@@ -430,8 +473,34 @@ func (c *sandboxAgentClient) Upgrade(ctx context.Context, in *UpgradeRequest, op// All implementations must embed UnimplementedSandboxAgentServer// for forward compatibility.//-// SandboxAgent runs inside each Firecracker microVM and handles-// exec, file ops, PTY, and stats over gRPC via vsock.+// SandboxAgent is the in-guest RPC surface. It runs as PID 1 (or under+// systemd) inside every sandbox VM and is reachable from the host worker+// over virtio-serial (Unix domain socket) or vsock.+//+// === STABILITY CONTRACT ===+// This proto is a stable, backward-compatible public API. Long-running+// sandboxes can live for weeks or months; their in-guest agent continues+// running whatever version was baked into the rootfs at sandbox-creation+// time. The worker must be able to talk to those old agents indefinitely.+//+// Allowed changes:+// - Adding new RPCs+// - Adding new optional fields to existing messages (with new field numbers)+// - Adding new enum values+//+// FORBIDDEN changes:+// - Removing or renaming RPCs, messages, fields, or enum values+// - Repurposing existing field numbers for different semantics+// - Making previously-optional fields required+// - Changing field types in a non-wire-compatible way+//+// New capabilities should prefer being implemented worker-side, composing+// Exec + file primitives, rather than adding a new agent RPC. An agent+// binary update requires the sandbox to be destroyed and recreated; there+// is intentionally no runtime upgrade path.+//+// See internal/qemu/manager.go "Runtime agent upgrade" comment for the+// full rationale on why we don't hot-upgrade.type SandboxAgentServer interface {// Exec runs a command and returns the result after completion.Exec(context.Context, *ExecRequest) (*ExecResponse, error)@@ -468,6 +537,12 @@ type SandboxAgentServer interface {// These are injected into every subsequent Exec/ExecStream call,// between the base OS env and per-command envs.SetEnvs(context.Context, *SetEnvsRequest) (*SetEnvsResponse, error)+ // ConfigureLogship sets sandbox session log-shipping configuration.+ // Worker calls this immediately after VM boot, before any user-facing+ // operations. Empty ingest_token disables shipping (kill-switch).+ // If never called, the agent's forwarder stays dormant — log events+ // queue in a bounded ring and are dropped oldest-first.+ ConfigureLogship(context.Context, *ConfigureLogshipRequest) (*ConfigureLogshipResponse, error)// Shutdown gracefully terminates the agent and syncs disks.Shutdown(context.Context, *ShutdownRequest) (*ShutdownResponse, error)// SyncFS flushes all filesystem buffers without exiting.@@ -562,6 +637,9 @@ func (UnimplementedSandboxAgentServer) ExecSessionKill(context.Context, *ExecSesfunc (UnimplementedSandboxAgentServer) SetEnvs(context.Context, *SetEnvsRequest) (*SetEnvsResponse, error) {return nil, status.Error(codes.Unimplemented, "method SetEnvs not implemented")}+func (UnimplementedSandboxAgentServer) ConfigureLogship(context.Context, *ConfigureLogshipRequest) (*ConfigureLogshipResponse, error) {+ return nil, status.Error(codes.Unimplemented, "method ConfigureLogship not implemented")+}func (UnimplementedSandboxAgentServer) Shutdown(context.Context, *ShutdownRequest) (*ShutdownResponse, error) {return nil, status.Error(codes.Unimplemented, "method Shutdown not implemented")}@@ -950,6 +1028,24 @@ func _SandboxAgent_SetEnvs_Handler(srv interface{}, ctx context.Context, dec funreturn interceptor(ctx, in, info, handler)}+func _SandboxAgent_ConfigureLogship_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {+ in := new(ConfigureLogshipRequest)+ if err := dec(in); err != nil {+ return nil, err+ }+ if interceptor == nil {+ return srv.(SandboxAgentServer).ConfigureLogship(ctx, in)+ }+ info := &grpc.UnaryServerInfo{+ Server: srv,+ FullMethod: SandboxAgent_ConfigureLogship_FullMethodName,+ }+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {+ return srv.(SandboxAgentServer).ConfigureLogship(ctx, req.(*ConfigureLogshipRequest))+ }+ return interceptor(ctx, in, info, handler)+}+func _SandboxAgent_Shutdown_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {in := new(ShutdownRequest)if err := dec(in); err != nil {@@ -1133,6 +1229,10 @@ var SandboxAgent_ServiceDesc = grpc.ServiceDesc{MethodName: "SetEnvs",Handler: _SandboxAgent_SetEnvs_Handler,},+ {+ MethodName: "ConfigureLogship",+ Handler: _SandboxAgent_ConfigureLogship_Handler,+ },{MethodName: "Shutdown",Handler: _SandboxAgent_Shutdown_Handler,diff --git a/proto/worker/worker.pb.go b/proto/worker/worker.pb.goindex 1a6a3e0a..6de6efe5 100644--- a/proto/worker/worker.pb.go+++ b/proto/worker/worker.pb.go@@ -64,7 +64,7 @@ func (x ExecOutputChunk_Stream) Number() protoreflect.EnumNumber {// Deprecated: Use ExecOutputChunk_Stream.Descriptor instead.func (ExecOutputChunk_Stream) EnumDescriptor() ([]byte, []int) {- return file_proto_worker_worker_proto_rawDescGZIP(), []int{10, 0}+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{14, 0}}type CreateSandboxRequest struct {@@ -370,6 +370,178 @@ func (*DestroySandboxResponse) Descriptor() ([]byte, []int) {return file_proto_worker_worker_proto_rawDescGZIP(), []int{3}}+type RebootSandboxRequest struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ SandboxId string `protobuf:"bytes,1,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *RebootSandboxRequest) Reset() {+ *x = RebootSandboxRequest{}+ mi := &file_proto_worker_worker_proto_msgTypes[4]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *RebootSandboxRequest) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*RebootSandboxRequest) ProtoMessage() {}++func (x *RebootSandboxRequest) ProtoReflect() protoreflect.Message {+ mi := &file_proto_worker_worker_proto_msgTypes[4]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use RebootSandboxRequest.ProtoReflect.Descriptor instead.+func (*RebootSandboxRequest) Descriptor() ([]byte, []int) {+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{4}+}++func (x *RebootSandboxRequest) GetSandboxId() string {+ if x != nil {+ return x.SandboxId+ }+ return ""+}++type RebootSandboxResponse struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *RebootSandboxResponse) Reset() {+ *x = RebootSandboxResponse{}+ mi := &file_proto_worker_worker_proto_msgTypes[5]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *RebootSandboxResponse) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*RebootSandboxResponse) ProtoMessage() {}++func (x *RebootSandboxResponse) ProtoReflect() protoreflect.Message {+ mi := &file_proto_worker_worker_proto_msgTypes[5]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use RebootSandboxResponse.ProtoReflect.Descriptor instead.+func (*RebootSandboxResponse) Descriptor() ([]byte, []int) {+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{5}+}++type PowerCycleSandboxRequest struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ SandboxId string `protobuf:"bytes,1,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *PowerCycleSandboxRequest) Reset() {+ *x = PowerCycleSandboxRequest{}+ mi := &file_proto_worker_worker_proto_msgTypes[6]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *PowerCycleSandboxRequest) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*PowerCycleSandboxRequest) ProtoMessage() {}++func (x *PowerCycleSandboxRequest) ProtoReflect() protoreflect.Message {+ mi := &file_proto_worker_worker_proto_msgTypes[6]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use PowerCycleSandboxRequest.ProtoReflect.Descriptor instead.+func (*PowerCycleSandboxRequest) Descriptor() ([]byte, []int) {+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{6}+}++func (x *PowerCycleSandboxRequest) GetSandboxId() string {+ if x != nil {+ return x.SandboxId+ }+ return ""+}++type PowerCycleSandboxResponse struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ // host_port is the new external port the sandbox is reachable on after+ // power-cycle. Power-cycle re-allocates the TAP and DNAT mapping, so the+ // port may differ from the original. Control plane uses this to update+ // its routing record.+ HostPort int32 `protobuf:"varint,1,opt,name=host_port,json=hostPort,proto3" json:"host_port,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *PowerCycleSandboxResponse) Reset() {+ *x = PowerCycleSandboxResponse{}+ mi := &file_proto_worker_worker_proto_msgTypes[7]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *PowerCycleSandboxResponse) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*PowerCycleSandboxResponse) ProtoMessage() {}++func (x *PowerCycleSandboxResponse) ProtoReflect() protoreflect.Message {+ mi := &file_proto_worker_worker_proto_msgTypes[7]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use PowerCycleSandboxResponse.ProtoReflect.Descriptor instead.+func (*PowerCycleSandboxResponse) Descriptor() ([]byte, []int) {+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{7}+}++func (x *PowerCycleSandboxResponse) GetHostPort() int32 {+ if x != nil {+ return x.HostPort+ }+ return 0+}+type GetSandboxRequest struct {state protoimpl.MessageState `protogen:"open.v1"`SandboxId string `protobuf:"bytes,1,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"`@@ -379,7 +551,7 @@ type GetSandboxRequest struct {func (x *GetSandboxRequest) Reset() {*x = GetSandboxRequest{}- mi := &file_proto_worker_worker_proto_msgTypes[4]+ mi := &file_proto_worker_worker_proto_msgTypes[8]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -391,7 +563,7 @@ func (x *GetSandboxRequest) String() string {func (*GetSandboxRequest) ProtoMessage() {}func (x *GetSandboxRequest) ProtoReflect() protoreflect.Message {- mi := &file_proto_worker_worker_proto_msgTypes[4]+ mi := &file_proto_worker_worker_proto_msgTypes[8]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -404,7 +576,7 @@ func (x *GetSandboxRequest) ProtoReflect() protoreflect.Message {// Deprecated: Use GetSandboxRequest.ProtoReflect.Descriptor instead.func (*GetSandboxRequest) Descriptor() ([]byte, []int) {- return file_proto_worker_worker_proto_rawDescGZIP(), []int{4}+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{8}}func (x *GetSandboxRequest) GetSandboxId() string {@@ -427,7 +599,7 @@ type GetSandboxResponse struct {func (x *GetSandboxResponse) Reset() {*x = GetSandboxResponse{}- mi := &file_proto_worker_worker_proto_msgTypes[5]+ mi := &file_proto_worker_worker_proto_msgTypes[9]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -439,7 +611,7 @@ func (x *GetSandboxResponse) String() string {func (*GetSandboxResponse) ProtoMessage() {}func (x *GetSandboxResponse) ProtoReflect() protoreflect.Message {- mi := &file_proto_worker_worker_proto_msgTypes[5]+ mi := &file_proto_worker_worker_proto_msgTypes[9]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -452,7 +624,7 @@ func (x *GetSandboxResponse) ProtoReflect() protoreflect.Message {// Deprecated: Use GetSandboxResponse.ProtoReflect.Descriptor instead.func (*GetSandboxResponse) Descriptor() ([]byte, []int) {- return file_proto_worker_worker_proto_rawDescGZIP(), []int{5}+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{9}}func (x *GetSandboxResponse) GetSandboxId() string {@@ -498,7 +670,7 @@ type ListSandboxesRequest struct {func (x *ListSandboxesRequest) Reset() {*x = ListSandboxesRequest{}- mi := &file_proto_worker_worker_proto_msgTypes[6]+ mi := &file_proto_worker_worker_proto_msgTypes[10]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -510,7 +682,7 @@ func (x *ListSandboxesRequest) String() string {func (*ListSandboxesRequest) ProtoMessage() {}func (x *ListSandboxesRequest) ProtoReflect() protoreflect.Message {- mi := &file_proto_worker_worker_proto_msgTypes[6]+ mi := &file_proto_worker_worker_proto_msgTypes[10]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -523,7 +695,7 @@ func (x *ListSandboxesRequest) ProtoReflect() protoreflect.Message {// Deprecated: Use ListSandboxesRequest.ProtoReflect.Descriptor instead.func (*ListSandboxesRequest) Descriptor() ([]byte, []int) {- return file_proto_worker_worker_proto_rawDescGZIP(), []int{6}+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{10}}type ListSandboxesResponse struct {@@ -535,7 +707,7 @@ type ListSandboxesResponse struct {func (x *ListSandboxesResponse) Reset() {*x = ListSandboxesResponse{}- mi := &file_proto_worker_worker_proto_msgTypes[7]+ mi := &file_proto_worker_worker_proto_msgTypes[11]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -547,7 +719,7 @@ func (x *ListSandboxesResponse) String() string {func (*ListSandboxesResponse) ProtoMessage() {}func (x *ListSandboxesResponse) ProtoReflect() protoreflect.Message {- mi := &file_proto_worker_worker_proto_msgTypes[7]+ mi := &file_proto_worker_worker_proto_msgTypes[11]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -560,7 +732,7 @@ func (x *ListSandboxesResponse) ProtoReflect() protoreflect.Message {// Deprecated: Use ListSandboxesResponse.ProtoReflect.Descriptor instead.func (*ListSandboxesResponse) Descriptor() ([]byte, []int) {- return file_proto_worker_worker_proto_rawDescGZIP(), []int{7}+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{11}}func (x *ListSandboxesResponse) GetSandboxes() []*GetSandboxResponse {@@ -584,7 +756,7 @@ type ExecCommandRequest struct {func (x *ExecCommandRequest) Reset() {*x = ExecCommandRequest{}- mi := &file_proto_worker_worker_proto_msgTypes[8]+ mi := &file_proto_worker_worker_proto_msgTypes[12]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -596,7 +768,7 @@ func (x *ExecCommandRequest) String() string {func (*ExecCommandRequest) ProtoMessage() {}func (x *ExecCommandRequest) ProtoReflect() protoreflect.Message {- mi := &file_proto_worker_worker_proto_msgTypes[8]+ mi := &file_proto_worker_worker_proto_msgTypes[12]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -609,7 +781,7 @@ func (x *ExecCommandRequest) ProtoReflect() protoreflect.Message {// Deprecated: Use ExecCommandRequest.ProtoReflect.Descriptor instead.func (*ExecCommandRequest) Descriptor() ([]byte, []int) {- return file_proto_worker_worker_proto_rawDescGZIP(), []int{8}+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{12}}func (x *ExecCommandRequest) GetSandboxId() string {@@ -665,7 +837,7 @@ type ExecCommandResponse struct {func (x *ExecCommandResponse) Reset() {*x = ExecCommandResponse{}- mi := &file_proto_worker_worker_proto_msgTypes[9]+ mi := &file_proto_worker_worker_proto_msgTypes[13]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -677,7 +849,7 @@ func (x *ExecCommandResponse) String() string {func (*ExecCommandResponse) ProtoMessage() {}func (x *ExecCommandResponse) ProtoReflect() protoreflect.Message {- mi := &file_proto_worker_worker_proto_msgTypes[9]+ mi := &file_proto_worker_worker_proto_msgTypes[13]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -690,7 +862,7 @@ func (x *ExecCommandResponse) ProtoReflect() protoreflect.Message {// Deprecated: Use ExecCommandResponse.ProtoReflect.Descriptor instead.func (*ExecCommandResponse) Descriptor() ([]byte, []int) {- return file_proto_worker_worker_proto_rawDescGZIP(), []int{9}+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{13}}func (x *ExecCommandResponse) GetExitCode() int32 {@@ -724,7 +896,7 @@ type ExecOutputChunk struct {func (x *ExecOutputChunk) Reset() {*x = ExecOutputChunk{}- mi := &file_proto_worker_worker_proto_msgTypes[10]+ mi := &file_proto_worker_worker_proto_msgTypes[14]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -736,7 +908,7 @@ func (x *ExecOutputChunk) String() string {func (*ExecOutputChunk) ProtoMessage() {}func (x *ExecOutputChunk) ProtoReflect() protoreflect.Message {- mi := &file_proto_worker_worker_proto_msgTypes[10]+ mi := &file_proto_worker_worker_proto_msgTypes[14]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -749,7 +921,7 @@ func (x *ExecOutputChunk) ProtoReflect() protoreflect.Message {// Deprecated: Use ExecOutputChunk.ProtoReflect.Descriptor instead.func (*ExecOutputChunk) Descriptor() ([]byte, []int) {- return file_proto_worker_worker_proto_rawDescGZIP(), []int{10}+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{14}}func (x *ExecOutputChunk) GetStream() ExecOutputChunk_Stream {@@ -776,7 +948,7 @@ type ReadFileRequest struct {func (x *ReadFileRequest) Reset() {*x = ReadFileRequest{}- mi := &file_proto_worker_worker_proto_msgTypes[11]+ mi := &file_proto_worker_worker_proto_msgTypes[15]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -788,7 +960,7 @@ func (x *ReadFileRequest) String() string {func (*ReadFileRequest) ProtoMessage() {}func (x *ReadFileRequest) ProtoReflect() protoreflect.Message {- mi := &file_proto_worker_worker_proto_msgTypes[11]+ mi := &file_proto_worker_worker_proto_msgTypes[15]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -801,7 +973,7 @@ func (x *ReadFileRequest) ProtoReflect() protoreflect.Message {// Deprecated: Use ReadFileRequest.ProtoReflect.Descriptor instead.func (*ReadFileRequest) Descriptor() ([]byte, []int) {- return file_proto_worker_worker_proto_rawDescGZIP(), []int{11}+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{15}}func (x *ReadFileRequest) GetSandboxId() string {@@ -827,7 +999,7 @@ type ReadFileResponse struct {func (x *ReadFileResponse) Reset() {*x = ReadFileResponse{}- mi := &file_proto_worker_worker_proto_msgTypes[12]+ mi := &file_proto_worker_worker_proto_msgTypes[16]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -839,7 +1011,7 @@ func (x *ReadFileResponse) String() string {func (*ReadFileResponse) ProtoMessage() {}func (x *ReadFileResponse) ProtoReflect() protoreflect.Message {- mi := &file_proto_worker_worker_proto_msgTypes[12]+ mi := &file_proto_worker_worker_proto_msgTypes[16]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -852,7 +1024,7 @@ func (x *ReadFileResponse) ProtoReflect() protoreflect.Message {// Deprecated: Use ReadFileResponse.ProtoReflect.Descriptor instead.func (*ReadFileResponse) Descriptor() ([]byte, []int) {- return file_proto_worker_worker_proto_rawDescGZIP(), []int{12}+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{16}}func (x *ReadFileResponse) GetContent() []byte {@@ -873,7 +1045,7 @@ type WriteFileRequest struct {func (x *WriteFileRequest) Reset() {*x = WriteFileRequest{}- mi := &file_proto_worker_worker_proto_msgTypes[13]+ mi := &file_proto_worker_worker_proto_msgTypes[17]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -885,7 +1057,7 @@ func (x *WriteFileRequest) String() string {func (*WriteFileRequest) ProtoMessage() {}func (x *WriteFileRequest) ProtoReflect() protoreflect.Message {- mi := &file_proto_worker_worker_proto_msgTypes[13]+ mi := &file_proto_worker_worker_proto_msgTypes[17]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -898,7 +1070,7 @@ func (x *WriteFileRequest) ProtoReflect() protoreflect.Message {// Deprecated: Use WriteFileRequest.ProtoReflect.Descriptor instead.func (*WriteFileRequest) Descriptor() ([]byte, []int) {- return file_proto_worker_worker_proto_rawDescGZIP(), []int{13}+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{17}}func (x *WriteFileRequest) GetSandboxId() string {@@ -930,7 +1102,7 @@ type WriteFileResponse struct {func (x *WriteFileResponse) Reset() {*x = WriteFileResponse{}- mi := &file_proto_worker_worker_proto_msgTypes[14]+ mi := &file_proto_worker_worker_proto_msgTypes[18]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -942,7 +1114,7 @@ func (x *WriteFileResponse) String() string {func (*WriteFileResponse) ProtoMessage() {}func (x *WriteFileResponse) ProtoReflect() protoreflect.Message {- mi := &file_proto_worker_worker_proto_msgTypes[14]+ mi := &file_proto_worker_worker_proto_msgTypes[18]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -955,7 +1127,7 @@ func (x *WriteFileResponse) ProtoReflect() protoreflect.Message {// Deprecated: Use WriteFileResponse.ProtoReflect.Descriptor instead.func (*WriteFileResponse) Descriptor() ([]byte, []int) {- return file_proto_worker_worker_proto_rawDescGZIP(), []int{14}+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{18}}type ListDirRequest struct {@@ -968,7 +1140,7 @@ type ListDirRequest struct {func (x *ListDirRequest) Reset() {*x = ListDirRequest{}- mi := &file_proto_worker_worker_proto_msgTypes[15]+ mi := &file_proto_worker_worker_proto_msgTypes[19]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -980,7 +1152,7 @@ func (x *ListDirRequest) String() string {func (*ListDirRequest) ProtoMessage() {}func (x *ListDirRequest) ProtoReflect() protoreflect.Message {- mi := &file_proto_worker_worker_proto_msgTypes[15]+ mi := &file_proto_worker_worker_proto_msgTypes[19]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -993,7 +1165,7 @@ func (x *ListDirRequest) ProtoReflect() protoreflect.Message {// Deprecated: Use ListDirRequest.ProtoReflect.Descriptor instead.func (*ListDirRequest) Descriptor() ([]byte, []int) {- return file_proto_worker_worker_proto_rawDescGZIP(), []int{15}+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{19}}func (x *ListDirRequest) GetSandboxId() string {@@ -1022,7 +1194,7 @@ type DirEntry struct {func (x *DirEntry) Reset() {*x = DirEntry{}- mi := &file_proto_worker_worker_proto_msgTypes[16]+ mi := &file_proto_worker_worker_proto_msgTypes[20]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -1034,7 +1206,7 @@ func (x *DirEntry) String() string {func (*DirEntry) ProtoMessage() {}func (x *DirEntry) ProtoReflect() protoreflect.Message {- mi := &file_proto_worker_worker_proto_msgTypes[16]+ mi := &file_proto_worker_worker_proto_msgTypes[20]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -1047,7 +1219,7 @@ func (x *DirEntry) ProtoReflect() protoreflect.Message {// Deprecated: Use DirEntry.ProtoReflect.Descriptor instead.func (*DirEntry) Descriptor() ([]byte, []int) {- return file_proto_worker_worker_proto_rawDescGZIP(), []int{16}+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{20}}func (x *DirEntry) GetName() string {@@ -1087,7 +1259,7 @@ type ListDirResponse struct {func (x *ListDirResponse) Reset() {*x = ListDirResponse{}- mi := &file_proto_worker_worker_proto_msgTypes[17]+ mi := &file_proto_worker_worker_proto_msgTypes[21]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -1099,7 +1271,7 @@ func (x *ListDirResponse) String() string {func (*ListDirResponse) ProtoMessage() {}func (x *ListDirResponse) ProtoReflect() protoreflect.Message {- mi := &file_proto_worker_worker_proto_msgTypes[17]+ mi := &file_proto_worker_worker_proto_msgTypes[21]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -1112,7 +1284,7 @@ func (x *ListDirResponse) ProtoReflect() protoreflect.Message {// Deprecated: Use ListDirResponse.ProtoReflect.Descriptor instead.func (*ListDirResponse) Descriptor() ([]byte, []int) {- return file_proto_worker_worker_proto_rawDescGZIP(), []int{17}+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{21}}func (x *ListDirResponse) GetEntries() []*DirEntry {@@ -1134,7 +1306,7 @@ type CreatePTYRequest struct {func (x *CreatePTYRequest) Reset() {*x = CreatePTYRequest{}- mi := &file_proto_worker_worker_proto_msgTypes[18]+ mi := &file_proto_worker_worker_proto_msgTypes[22]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -1146,7 +1318,7 @@ func (x *CreatePTYRequest) String() string {func (*CreatePTYRequest) ProtoMessage() {}func (x *CreatePTYRequest) ProtoReflect() protoreflect.Message {- mi := &file_proto_worker_worker_proto_msgTypes[18]+ mi := &file_proto_worker_worker_proto_msgTypes[22]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -1159,7 +1331,7 @@ func (x *CreatePTYRequest) ProtoReflect() protoreflect.Message {// Deprecated: Use CreatePTYRequest.ProtoReflect.Descriptor instead.func (*CreatePTYRequest) Descriptor() ([]byte, []int) {- return file_proto_worker_worker_proto_rawDescGZIP(), []int{18}+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{22}}func (x *CreatePTYRequest) GetSandboxId() string {@@ -1199,7 +1371,7 @@ type CreatePTYResponse struct {func (x *CreatePTYResponse) Reset() {*x = CreatePTYResponse{}- mi := &file_proto_worker_worker_proto_msgTypes[19]+ mi := &file_proto_worker_worker_proto_msgTypes[23]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -1211,7 +1383,7 @@ func (x *CreatePTYResponse) String() string {func (*CreatePTYResponse) ProtoMessage() {}func (x *CreatePTYResponse) ProtoReflect() protoreflect.Message {- mi := &file_proto_worker_worker_proto_msgTypes[19]+ mi := &file_proto_worker_worker_proto_msgTypes[23]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -1224,7 +1396,7 @@ func (x *CreatePTYResponse) ProtoReflect() protoreflect.Message {// Deprecated: Use CreatePTYResponse.ProtoReflect.Descriptor instead.func (*CreatePTYResponse) Descriptor() ([]byte, []int) {- return file_proto_worker_worker_proto_rawDescGZIP(), []int{19}+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{23}}func (x *CreatePTYResponse) GetSessionId() string {@@ -1248,7 +1420,7 @@ type PTYInput struct {func (x *PTYInput) Reset() {*x = PTYInput{}- mi := &file_proto_worker_worker_proto_msgTypes[20]+ mi := &file_proto_worker_worker_proto_msgTypes[24]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -1260,7 +1432,7 @@ func (x *PTYInput) String() string {func (*PTYInput) ProtoMessage() {}func (x *PTYInput) ProtoReflect() protoreflect.Message {- mi := &file_proto_worker_worker_proto_msgTypes[20]+ mi := &file_proto_worker_worker_proto_msgTypes[24]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -1273,7 +1445,7 @@ func (x *PTYInput) ProtoReflect() protoreflect.Message {// Deprecated: Use PTYInput.ProtoReflect.Descriptor instead.func (*PTYInput) Descriptor() ([]byte, []int) {- return file_proto_worker_worker_proto_rawDescGZIP(), []int{20}+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{24}}func (x *PTYInput) GetSessionId() string {@@ -1334,7 +1506,7 @@ type PTYResize struct {func (x *PTYResize) Reset() {*x = PTYResize{}- mi := &file_proto_worker_worker_proto_msgTypes[21]+ mi := &file_proto_worker_worker_proto_msgTypes[25]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -1346,7 +1518,7 @@ func (x *PTYResize) String() string {func (*PTYResize) ProtoMessage() {}func (x *PTYResize) ProtoReflect() protoreflect.Message {- mi := &file_proto_worker_worker_proto_msgTypes[21]+ mi := &file_proto_worker_worker_proto_msgTypes[25]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -1359,7 +1531,7 @@ func (x *PTYResize) ProtoReflect() protoreflect.Message {// Deprecated: Use PTYResize.ProtoReflect.Descriptor instead.func (*PTYResize) Descriptor() ([]byte, []int) {- return file_proto_worker_worker_proto_rawDescGZIP(), []int{21}+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{25}}func (x *PTYResize) GetCols() int32 {@@ -1386,7 +1558,7 @@ type PTYOutput struct {func (x *PTYOutput) Reset() {*x = PTYOutput{}- mi := &file_proto_worker_worker_proto_msgTypes[22]+ mi := &file_proto_worker_worker_proto_msgTypes[26]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -1398,7 +1570,7 @@ func (x *PTYOutput) String() string {func (*PTYOutput) ProtoMessage() {}func (x *PTYOutput) ProtoReflect() protoreflect.Message {- mi := &file_proto_worker_worker_proto_msgTypes[22]+ mi := &file_proto_worker_worker_proto_msgTypes[26]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -1411,7 +1583,7 @@ func (x *PTYOutput) ProtoReflect() protoreflect.Message {// Deprecated: Use PTYOutput.ProtoReflect.Descriptor instead.func (*PTYOutput) Descriptor() ([]byte, []int) {- return file_proto_worker_worker_proto_rawDescGZIP(), []int{22}+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{26}}func (x *PTYOutput) GetSessionId() string {@@ -1437,7 +1609,7 @@ type HibernateSandboxRequest struct {func (x *HibernateSandboxRequest) Reset() {*x = HibernateSandboxRequest{}- mi := &file_proto_worker_worker_proto_msgTypes[23]+ mi := &file_proto_worker_worker_proto_msgTypes[27]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -1449,7 +1621,7 @@ func (x *HibernateSandboxRequest) String() string {func (*HibernateSandboxRequest) ProtoMessage() {}func (x *HibernateSandboxRequest) ProtoReflect() protoreflect.Message {- mi := &file_proto_worker_worker_proto_msgTypes[23]+ mi := &file_proto_worker_worker_proto_msgTypes[27]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -1462,7 +1634,7 @@ func (x *HibernateSandboxRequest) ProtoReflect() protoreflect.Message {// Deprecated: Use HibernateSandboxRequest.ProtoReflect.Descriptor instead.func (*HibernateSandboxRequest) Descriptor() ([]byte, []int) {- return file_proto_worker_worker_proto_rawDescGZIP(), []int{23}+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{27}}func (x *HibernateSandboxRequest) GetSandboxId() string {@@ -1483,7 +1655,7 @@ type HibernateSandboxResponse struct {func (x *HibernateSandboxResponse) Reset() {*x = HibernateSandboxResponse{}- mi := &file_proto_worker_worker_proto_msgTypes[24]+ mi := &file_proto_worker_worker_proto_msgTypes[28]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -1495,7 +1667,7 @@ func (x *HibernateSandboxResponse) String() string {func (*HibernateSandboxResponse) ProtoMessage() {}func (x *HibernateSandboxResponse) ProtoReflect() protoreflect.Message {- mi := &file_proto_worker_worker_proto_msgTypes[24]+ mi := &file_proto_worker_worker_proto_msgTypes[28]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -1508,7 +1680,7 @@ func (x *HibernateSandboxResponse) ProtoReflect() protoreflect.Message {// Deprecated: Use HibernateSandboxResponse.ProtoReflect.Descriptor instead.func (*HibernateSandboxResponse) Descriptor() ([]byte, []int) {- return file_proto_worker_worker_proto_rawDescGZIP(), []int{24}+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{28}}func (x *HibernateSandboxResponse) GetSandboxId() string {@@ -1543,7 +1715,7 @@ type WakeSandboxRequest struct {func (x *WakeSandboxRequest) Reset() {*x = WakeSandboxRequest{}- mi := &file_proto_worker_worker_proto_msgTypes[25]+ mi := &file_proto_worker_worker_proto_msgTypes[29]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -1555,7 +1727,7 @@ func (x *WakeSandboxRequest) String() string {func (*WakeSandboxRequest) ProtoMessage() {}func (x *WakeSandboxRequest) ProtoReflect() protoreflect.Message {- mi := &file_proto_worker_worker_proto_msgTypes[25]+ mi := &file_proto_worker_worker_proto_msgTypes[29]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -1568,7 +1740,7 @@ func (x *WakeSandboxRequest) ProtoReflect() protoreflect.Message {// Deprecated: Use WakeSandboxRequest.ProtoReflect.Descriptor instead.func (*WakeSandboxRequest) Descriptor() ([]byte, []int) {- return file_proto_worker_worker_proto_rawDescGZIP(), []int{25}+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{29}}func (x *WakeSandboxRequest) GetSandboxId() string {@@ -1602,7 +1774,7 @@ type WakeSandboxResponse struct {func (x *WakeSandboxResponse) Reset() {*x = WakeSandboxResponse{}- mi := &file_proto_worker_worker_proto_msgTypes[26]+ mi := &file_proto_worker_worker_proto_msgTypes[30]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -1614,7 +1786,7 @@ func (x *WakeSandboxResponse) String() string {func (*WakeSandboxResponse) ProtoMessage() {}func (x *WakeSandboxResponse) ProtoReflect() protoreflect.Message {- mi := &file_proto_worker_worker_proto_msgTypes[26]+ mi := &file_proto_worker_worker_proto_msgTypes[30]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -1627,7 +1799,7 @@ func (x *WakeSandboxResponse) ProtoReflect() protoreflect.Message {// Deprecated: Use WakeSandboxResponse.ProtoReflect.Descriptor instead.func (*WakeSandboxResponse) Descriptor() ([]byte, []int) {- return file_proto_worker_worker_proto_rawDescGZIP(), []int{26}+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{30}}func (x *WakeSandboxResponse) GetSandboxId() string {@@ -1654,7 +1826,7 @@ type SaveAsTemplateRequest struct {func (x *SaveAsTemplateRequest) Reset() {*x = SaveAsTemplateRequest{}- mi := &file_proto_worker_worker_proto_msgTypes[27]+ mi := &file_proto_worker_worker_proto_msgTypes[31]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -1666,7 +1838,7 @@ func (x *SaveAsTemplateRequest) String() string {func (*SaveAsTemplateRequest) ProtoMessage() {}func (x *SaveAsTemplateRequest) ProtoReflect() protoreflect.Message {- mi := &file_proto_worker_worker_proto_msgTypes[27]+ mi := &file_proto_worker_worker_proto_msgTypes[31]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -1679,7 +1851,7 @@ func (x *SaveAsTemplateRequest) ProtoReflect() protoreflect.Message {// Deprecated: Use SaveAsTemplateRequest.ProtoReflect.Descriptor instead.func (*SaveAsTemplateRequest) Descriptor() ([]byte, []int) {- return file_proto_worker_worker_proto_rawDescGZIP(), []int{27}+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{31}}func (x *SaveAsTemplateRequest) GetSandboxId() string {@@ -1706,7 +1878,7 @@ type SaveAsTemplateResponse struct {func (x *SaveAsTemplateResponse) Reset() {*x = SaveAsTemplateResponse{}- mi := &file_proto_worker_worker_proto_msgTypes[28]+ mi := &file_proto_worker_worker_proto_msgTypes[32]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -1718,7 +1890,7 @@ func (x *SaveAsTemplateResponse) String() string {func (*SaveAsTemplateResponse) ProtoMessage() {}func (x *SaveAsTemplateResponse) ProtoReflect() protoreflect.Message {- mi := &file_proto_worker_worker_proto_msgTypes[28]+ mi := &file_proto_worker_worker_proto_msgTypes[32]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -1731,7 +1903,7 @@ func (x *SaveAsTemplateResponse) ProtoReflect() protoreflect.Message {// Deprecated: Use SaveAsTemplateResponse.ProtoReflect.Descriptor instead.func (*SaveAsTemplateResponse) Descriptor() ([]byte, []int) {- return file_proto_worker_worker_proto_rawDescGZIP(), []int{28}+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{32}}func (x *SaveAsTemplateResponse) GetRootfsS3Key() string {@@ -1760,7 +1932,7 @@ type BuildTemplateRequest struct {func (x *BuildTemplateRequest) Reset() {*x = BuildTemplateRequest{}- mi := &file_proto_worker_worker_proto_msgTypes[29]+ mi := &file_proto_worker_worker_proto_msgTypes[33]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -1772,7 +1944,7 @@ func (x *BuildTemplateRequest) String() string {func (*BuildTemplateRequest) ProtoMessage() {}func (x *BuildTemplateRequest) ProtoReflect() protoreflect.Message {- mi := &file_proto_worker_worker_proto_msgTypes[29]+ mi := &file_proto_worker_worker_proto_msgTypes[33]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -1785,7 +1957,7 @@ func (x *BuildTemplateRequest) ProtoReflect() protoreflect.Message {// Deprecated: Use BuildTemplateRequest.ProtoReflect.Descriptor instead.func (*BuildTemplateRequest) Descriptor() ([]byte, []int) {- return file_proto_worker_worker_proto_rawDescGZIP(), []int{29}+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{33}}func (x *BuildTemplateRequest) GetName() string {@@ -1826,7 +1998,7 @@ type BuildTemplateResponse struct {func (x *BuildTemplateResponse) Reset() {*x = BuildTemplateResponse{}- mi := &file_proto_worker_worker_proto_msgTypes[30]+ mi := &file_proto_worker_worker_proto_msgTypes[34]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -1838,7 +2010,7 @@ func (x *BuildTemplateResponse) String() string {func (*BuildTemplateResponse) ProtoMessage() {}func (x *BuildTemplateResponse) ProtoReflect() protoreflect.Message {- mi := &file_proto_worker_worker_proto_msgTypes[30]+ mi := &file_proto_worker_worker_proto_msgTypes[34]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -1851,7 +2023,7 @@ func (x *BuildTemplateResponse) ProtoReflect() protoreflect.Message {// Deprecated: Use BuildTemplateResponse.ProtoReflect.Descriptor instead.func (*BuildTemplateResponse) Descriptor() ([]byte, []int) {- return file_proto_worker_worker_proto_rawDescGZIP(), []int{30}+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{34}}func (x *BuildTemplateResponse) GetImageRef() string {@@ -1883,7 +2055,7 @@ type ExecSessionCreateRequest struct {func (x *ExecSessionCreateRequest) Reset() {*x = ExecSessionCreateRequest{}- mi := &file_proto_worker_worker_proto_msgTypes[31]+ mi := &file_proto_worker_worker_proto_msgTypes[35]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -1895,7 +2067,7 @@ func (x *ExecSessionCreateRequest) String() string {func (*ExecSessionCreateRequest) ProtoMessage() {}func (x *ExecSessionCreateRequest) ProtoReflect() protoreflect.Message {- mi := &file_proto_worker_worker_proto_msgTypes[31]+ mi := &file_proto_worker_worker_proto_msgTypes[35]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -1908,7 +2080,7 @@ func (x *ExecSessionCreateRequest) ProtoReflect() protoreflect.Message {// Deprecated: Use ExecSessionCreateRequest.ProtoReflect.Descriptor instead.func (*ExecSessionCreateRequest) Descriptor() ([]byte, []int) {- return file_proto_worker_worker_proto_rawDescGZIP(), []int{31}+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{35}}func (x *ExecSessionCreateRequest) GetSandboxId() string {@@ -1969,7 +2141,7 @@ type ExecSessionCreateResponse struct {func (x *ExecSessionCreateResponse) Reset() {*x = ExecSessionCreateResponse{}- mi := &file_proto_worker_worker_proto_msgTypes[32]+ mi := &file_proto_worker_worker_proto_msgTypes[36]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -1981,7 +2153,7 @@ func (x *ExecSessionCreateResponse) String() string {func (*ExecSessionCreateResponse) ProtoMessage() {}func (x *ExecSessionCreateResponse) ProtoReflect() protoreflect.Message {- mi := &file_proto_worker_worker_proto_msgTypes[32]+ mi := &file_proto_worker_worker_proto_msgTypes[36]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -1994,7 +2166,7 @@ func (x *ExecSessionCreateResponse) ProtoReflect() protoreflect.Message {// Deprecated: Use ExecSessionCreateResponse.ProtoReflect.Descriptor instead.func (*ExecSessionCreateResponse) Descriptor() ([]byte, []int) {- return file_proto_worker_worker_proto_rawDescGZIP(), []int{32}+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{36}}func (x *ExecSessionCreateResponse) GetSessionId() string {@@ -2013,7 +2185,7 @@ type ExecSessionListRequest struct {func (x *ExecSessionListRequest) Reset() {*x = ExecSessionListRequest{}- mi := &file_proto_worker_worker_proto_msgTypes[33]+ mi := &file_proto_worker_worker_proto_msgTypes[37]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -2025,7 +2197,7 @@ func (x *ExecSessionListRequest) String() string {func (*ExecSessionListRequest) ProtoMessage() {}func (x *ExecSessionListRequest) ProtoReflect() protoreflect.Message {- mi := &file_proto_worker_worker_proto_msgTypes[33]+ mi := &file_proto_worker_worker_proto_msgTypes[37]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -2038,7 +2210,7 @@ func (x *ExecSessionListRequest) ProtoReflect() protoreflect.Message {// Deprecated: Use ExecSessionListRequest.ProtoReflect.Descriptor instead.func (*ExecSessionListRequest) Descriptor() ([]byte, []int) {- return file_proto_worker_worker_proto_rawDescGZIP(), []int{33}+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{37}}func (x *ExecSessionListRequest) GetSandboxId() string {@@ -2057,7 +2229,7 @@ type ExecSessionListResponse struct {func (x *ExecSessionListResponse) Reset() {*x = ExecSessionListResponse{}- mi := &file_proto_worker_worker_proto_msgTypes[34]+ mi := &file_proto_worker_worker_proto_msgTypes[38]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -2069,7 +2241,7 @@ func (x *ExecSessionListResponse) String() string {func (*ExecSessionListResponse) ProtoMessage() {}func (x *ExecSessionListResponse) ProtoReflect() protoreflect.Message {- mi := &file_proto_worker_worker_proto_msgTypes[34]+ mi := &file_proto_worker_worker_proto_msgTypes[38]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -2082,7 +2254,7 @@ func (x *ExecSessionListResponse) ProtoReflect() protoreflect.Message {// Deprecated: Use ExecSessionListResponse.ProtoReflect.Descriptor instead.func (*ExecSessionListResponse) Descriptor() ([]byte, []int) {- return file_proto_worker_worker_proto_rawDescGZIP(), []int{34}+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{38}}func (x *ExecSessionListResponse) GetSessions() []*ExecSessionInfoEntry {@@ -2107,7 +2279,7 @@ type ExecSessionInfoEntry struct {func (x *ExecSessionInfoEntry) Reset() {*x = ExecSessionInfoEntry{}- mi := &file_proto_worker_worker_proto_msgTypes[35]+ mi := &file_proto_worker_worker_proto_msgTypes[39]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -2119,7 +2291,7 @@ func (x *ExecSessionInfoEntry) String() string {func (*ExecSessionInfoEntry) ProtoMessage() {}func (x *ExecSessionInfoEntry) ProtoReflect() protoreflect.Message {- mi := &file_proto_worker_worker_proto_msgTypes[35]+ mi := &file_proto_worker_worker_proto_msgTypes[39]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -2132,7 +2304,7 @@ func (x *ExecSessionInfoEntry) ProtoReflect() protoreflect.Message {// Deprecated: Use ExecSessionInfoEntry.ProtoReflect.Descriptor instead.func (*ExecSessionInfoEntry) Descriptor() ([]byte, []int) {- return file_proto_worker_worker_proto_rawDescGZIP(), []int{35}+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{39}}func (x *ExecSessionInfoEntry) GetSessionId() string {@@ -2195,7 +2367,7 @@ type ExecSessionKillRequest struct {func (x *ExecSessionKillRequest) Reset() {*x = ExecSessionKillRequest{}- mi := &file_proto_worker_worker_proto_msgTypes[36]+ mi := &file_proto_worker_worker_proto_msgTypes[40]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -2207,7 +2379,7 @@ func (x *ExecSessionKillRequest) String() string {func (*ExecSessionKillRequest) ProtoMessage() {}func (x *ExecSessionKillRequest) ProtoReflect() protoreflect.Message {- mi := &file_proto_worker_worker_proto_msgTypes[36]+ mi := &file_proto_worker_worker_proto_msgTypes[40]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -2220,7 +2392,7 @@ func (x *ExecSessionKillRequest) ProtoReflect() protoreflect.Message {// Deprecated: Use ExecSessionKillRequest.ProtoReflect.Descriptor instead.func (*ExecSessionKillRequest) Descriptor() ([]byte, []int) {- return file_proto_worker_worker_proto_rawDescGZIP(), []int{36}+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{40}}func (x *ExecSessionKillRequest) GetSandboxId() string {@@ -2252,7 +2424,7 @@ type ExecSessionKillResponse struct {func (x *ExecSessionKillResponse) Reset() {*x = ExecSessionKillResponse{}- mi := &file_proto_worker_worker_proto_msgTypes[37]+ mi := &file_proto_worker_worker_proto_msgTypes[41]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -2264,7 +2436,7 @@ func (x *ExecSessionKillResponse) String() string {func (*ExecSessionKillResponse) ProtoMessage() {}func (x *ExecSessionKillResponse) ProtoReflect() protoreflect.Message {- mi := &file_proto_worker_worker_proto_msgTypes[37]+ mi := &file_proto_worker_worker_proto_msgTypes[41]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -2277,7 +2449,7 @@ func (x *ExecSessionKillResponse) ProtoReflect() protoreflect.Message {// Deprecated: Use ExecSessionKillResponse.ProtoReflect.Descriptor instead.func (*ExecSessionKillResponse) Descriptor() ([]byte, []int) {- return file_proto_worker_worker_proto_rawDescGZIP(), []int{37}+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{41}}type GetSandboxStatsRequest struct {@@ -2289,7 +2461,7 @@ type GetSandboxStatsRequest struct {func (x *GetSandboxStatsRequest) Reset() {*x = GetSandboxStatsRequest{}- mi := &file_proto_worker_worker_proto_msgTypes[38]+ mi := &file_proto_worker_worker_proto_msgTypes[42]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -2301,7 +2473,7 @@ func (x *GetSandboxStatsRequest) String() string {func (*GetSandboxStatsRequest) ProtoMessage() {}func (x *GetSandboxStatsRequest) ProtoReflect() protoreflect.Message {- mi := &file_proto_worker_worker_proto_msgTypes[38]+ mi := &file_proto_worker_worker_proto_msgTypes[42]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -2314,7 +2486,7 @@ func (x *GetSandboxStatsRequest) ProtoReflect() protoreflect.Message {// Deprecated: Use GetSandboxStatsRequest.ProtoReflect.Descriptor instead.func (*GetSandboxStatsRequest) Descriptor() ([]byte, []int) {- return file_proto_worker_worker_proto_rawDescGZIP(), []int{38}+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{42}}func (x *GetSandboxStatsRequest) GetSandboxId() string {@@ -2338,7 +2510,7 @@ type GetSandboxStatsResponse struct {func (x *GetSandboxStatsResponse) Reset() {*x = GetSandboxStatsResponse{}- mi := &file_proto_worker_worker_proto_msgTypes[39]+ mi := &file_proto_worker_worker_proto_msgTypes[43]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -2350,7 +2522,7 @@ func (x *GetSandboxStatsResponse) String() string {func (*GetSandboxStatsResponse) ProtoMessage() {}func (x *GetSandboxStatsResponse) ProtoReflect() protoreflect.Message {- mi := &file_proto_worker_worker_proto_msgTypes[39]+ mi := &file_proto_worker_worker_proto_msgTypes[43]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -2363,7 +2535,7 @@ func (x *GetSandboxStatsResponse) ProtoReflect() protoreflect.Message {// Deprecated: Use GetSandboxStatsResponse.ProtoReflect.Descriptor instead.func (*GetSandboxStatsResponse) Descriptor() ([]byte, []int) {- return file_proto_worker_worker_proto_rawDescGZIP(), []int{39}+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{43}}func (x *GetSandboxStatsResponse) GetCpuPercent() float64 {@@ -2419,7 +2591,7 @@ type CreateCheckpointRequest struct {func (x *CreateCheckpointRequest) Reset() {*x = CreateCheckpointRequest{}- mi := &file_proto_worker_worker_proto_msgTypes[40]+ mi := &file_proto_worker_worker_proto_msgTypes[44]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -2431,7 +2603,7 @@ func (x *CreateCheckpointRequest) String() string {func (*CreateCheckpointRequest) ProtoMessage() {}func (x *CreateCheckpointRequest) ProtoReflect() protoreflect.Message {- mi := &file_proto_worker_worker_proto_msgTypes[40]+ mi := &file_proto_worker_worker_proto_msgTypes[44]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -2444,7 +2616,7 @@ func (x *CreateCheckpointRequest) ProtoReflect() protoreflect.Message {// Deprecated: Use CreateCheckpointRequest.ProtoReflect.Descriptor instead.func (*CreateCheckpointRequest) Descriptor() ([]byte, []int) {- return file_proto_worker_worker_proto_rawDescGZIP(), []int{40}+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{44}}func (x *CreateCheckpointRequest) GetSandboxId() string {@@ -2472,13 +2644,19 @@ type CreateCheckpointResponse struct {state protoimpl.MessageState `protogen:"open.v1"`RootfsS3Key string `protobuf:"bytes,1,opt,name=rootfs_s3_key,json=rootfsS3Key,proto3" json:"rootfs_s3_key,omitempty"`WorkspaceS3Key string `protobuf:"bytes,2,opt,name=workspace_s3_key,json=workspaceS3Key,proto3" json:"workspace_s3_key,omitempty"`- unknownFields protoimpl.UnknownFields- sizeCache protoimpl.SizeCache+ // Size of the uploaded checkpoint archive in bytes. The control plane+ // persists this on the sandbox_checkpoints row instead of the previous+ // hardcoded 0, so customers and operators can see how big a checkpoint+ // actually is. Zero is reported when the archive failed to upload (the+ // checkpoint is still locally usable but cross-worker forks won't work).+ SizeBytes int64 `protobuf:"varint,3,opt,name=size_bytes,json=sizeBytes,proto3" json:"size_bytes,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache}func (x *CreateCheckpointResponse) Reset() {*x = CreateCheckpointResponse{}- mi := &file_proto_worker_worker_proto_msgTypes[41]+ mi := &file_proto_worker_worker_proto_msgTypes[45]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -2490,7 +2668,7 @@ func (x *CreateCheckpointResponse) String() string {func (*CreateCheckpointResponse) ProtoMessage() {}func (x *CreateCheckpointResponse) ProtoReflect() protoreflect.Message {- mi := &file_proto_worker_worker_proto_msgTypes[41]+ mi := &file_proto_worker_worker_proto_msgTypes[45]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -2503,7 +2681,7 @@ func (x *CreateCheckpointResponse) ProtoReflect() protoreflect.Message {// Deprecated: Use CreateCheckpointResponse.ProtoReflect.Descriptor instead.func (*CreateCheckpointResponse) Descriptor() ([]byte, []int) {- return file_proto_worker_worker_proto_rawDescGZIP(), []int{41}+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{45}}func (x *CreateCheckpointResponse) GetRootfsS3Key() string {@@ -2520,6 +2698,13 @@ func (x *CreateCheckpointResponse) GetWorkspaceS3Key() string {return ""}+func (x *CreateCheckpointResponse) GetSizeBytes() int64 {+ if x != nil {+ return x.SizeBytes+ }+ return 0+}+type RestoreCheckpointRequest struct {state protoimpl.MessageState `protogen:"open.v1"`SandboxId string `protobuf:"bytes,1,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"`@@ -2530,7 +2715,7 @@ type RestoreCheckpointRequest struct {func (x *RestoreCheckpointRequest) Reset() {*x = RestoreCheckpointRequest{}- mi := &file_proto_worker_worker_proto_msgTypes[42]+ mi := &file_proto_worker_worker_proto_msgTypes[46]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -2542,7 +2727,7 @@ func (x *RestoreCheckpointRequest) String() string {func (*RestoreCheckpointRequest) ProtoMessage() {}func (x *RestoreCheckpointRequest) ProtoReflect() protoreflect.Message {- mi := &file_proto_worker_worker_proto_msgTypes[42]+ mi := &file_proto_worker_worker_proto_msgTypes[46]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -2555,7 +2740,7 @@ func (x *RestoreCheckpointRequest) ProtoReflect() protoreflect.Message {// Deprecated: Use RestoreCheckpointRequest.ProtoReflect.Descriptor instead.func (*RestoreCheckpointRequest) Descriptor() ([]byte, []int) {- return file_proto_worker_worker_proto_rawDescGZIP(), []int{42}+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{46}}func (x *RestoreCheckpointRequest) GetSandboxId() string {@@ -2581,7 +2766,7 @@ type RestoreCheckpointResponse struct {func (x *RestoreCheckpointResponse) Reset() {*x = RestoreCheckpointResponse{}- mi := &file_proto_worker_worker_proto_msgTypes[43]+ mi := &file_proto_worker_worker_proto_msgTypes[47]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -2593,7 +2778,7 @@ func (x *RestoreCheckpointResponse) String() string {func (*RestoreCheckpointResponse) ProtoMessage() {}func (x *RestoreCheckpointResponse) ProtoReflect() protoreflect.Message {- mi := &file_proto_worker_worker_proto_msgTypes[43]+ mi := &file_proto_worker_worker_proto_msgTypes[47]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -2606,7 +2791,7 @@ func (x *RestoreCheckpointResponse) ProtoReflect() protoreflect.Message {// Deprecated: Use RestoreCheckpointResponse.ProtoReflect.Descriptor instead.func (*RestoreCheckpointResponse) Descriptor() ([]byte, []int) {- return file_proto_worker_worker_proto_rawDescGZIP(), []int{43}+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{47}}func (x *RestoreCheckpointResponse) GetSuccess() bool {@@ -2629,7 +2814,7 @@ type SetSandboxLimitsRequest struct {func (x *SetSandboxLimitsRequest) Reset() {*x = SetSandboxLimitsRequest{}- mi := &file_proto_worker_worker_proto_msgTypes[44]+ mi := &file_proto_worker_worker_proto_msgTypes[48]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -2641,7 +2826,7 @@ func (x *SetSandboxLimitsRequest) String() string {func (*SetSandboxLimitsRequest) ProtoMessage() {}func (x *SetSandboxLimitsRequest) ProtoReflect() protoreflect.Message {- mi := &file_proto_worker_worker_proto_msgTypes[44]+ mi := &file_proto_worker_worker_proto_msgTypes[48]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -2654,7 +2839,7 @@ func (x *SetSandboxLimitsRequest) ProtoReflect() protoreflect.Message {// Deprecated: Use SetSandboxLimitsRequest.ProtoReflect.Descriptor instead.func (*SetSandboxLimitsRequest) Descriptor() ([]byte, []int) {- return file_proto_worker_worker_proto_rawDescGZIP(), []int{44}+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{48}}func (x *SetSandboxLimitsRequest) GetSandboxId() string {@@ -2700,7 +2885,7 @@ type SetSandboxLimitsResponse struct {func (x *SetSandboxLimitsResponse) Reset() {*x = SetSandboxLimitsResponse{}- mi := &file_proto_worker_worker_proto_msgTypes[45]+ mi := &file_proto_worker_worker_proto_msgTypes[49]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -2712,7 +2897,7 @@ func (x *SetSandboxLimitsResponse) String() string {func (*SetSandboxLimitsResponse) ProtoMessage() {}func (x *SetSandboxLimitsResponse) ProtoReflect() protoreflect.Message {- mi := &file_proto_worker_worker_proto_msgTypes[45]+ mi := &file_proto_worker_worker_proto_msgTypes[49]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -2725,7 +2910,7 @@ func (x *SetSandboxLimitsResponse) ProtoReflect() protoreflect.Message {// Deprecated: Use SetSandboxLimitsResponse.ProtoReflect.Descriptor instead.func (*SetSandboxLimitsResponse) Descriptor() ([]byte, []int) {- return file_proto_worker_worker_proto_rawDescGZIP(), []int{45}+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{49}}// Live migration messages@@ -2738,7 +2923,7 @@ type PreCopyDrivesRequest struct {func (x *PreCopyDrivesRequest) Reset() {*x = PreCopyDrivesRequest{}- mi := &file_proto_worker_worker_proto_msgTypes[46]+ mi := &file_proto_worker_worker_proto_msgTypes[50]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -2750,7 +2935,7 @@ func (x *PreCopyDrivesRequest) String() string {func (*PreCopyDrivesRequest) ProtoMessage() {}func (x *PreCopyDrivesRequest) ProtoReflect() protoreflect.Message {- mi := &file_proto_worker_worker_proto_msgTypes[46]+ mi := &file_proto_worker_worker_proto_msgTypes[50]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -2763,7 +2948,7 @@ func (x *PreCopyDrivesRequest) ProtoReflect() protoreflect.Message {// Deprecated: Use PreCopyDrivesRequest.ProtoReflect.Descriptor instead.func (*PreCopyDrivesRequest) Descriptor() ([]byte, []int) {- return file_proto_worker_worker_proto_rawDescGZIP(), []int{46}+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{50}}func (x *PreCopyDrivesRequest) GetSandboxId() string {@@ -2785,13 +2970,29 @@ type PreCopyDrivesResponse struct {// Used for actual-memory-based scheduling instead of committed/configured// memory (which over-reserves on idle sandboxes).ActualMemoryMb int32 `protobuf:"varint,6,opt,name=actual_memory_mb,json=actualMemoryMb,proto3" json:"actual_memory_mb,omitempty"`- unknownFields protoimpl.UnknownFields- sizeCache protoimpl.SizeCache+ // Secrets-proxy session state for the migrating sandbox. Live migration+ // moves the QEMU process (which carries the in-VM env vars containing+ // sealed token IDs) but the proxy's plaintext-substitution map is+ // per-worker in-process state. Without these the destination worker has+ // no way to substitute the literal `osb_sealed_xxx` strings on outbound+ // HTTPS, so the guest's first secret-using call after migration fails+ // auth. Mirrors the SealedTokens/EgressAllowlist/TokenHosts fields the+ // hibernate path persists into snapshot-meta.json.+ SealedTokens map[string]string `protobuf:"bytes,7,rep,name=sealed_tokens,json=sealedTokens,proto3" json:"sealed_tokens,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` // sealed_id -> plaintext secret value+ EgressAllowlist []string `protobuf:"bytes,8,rep,name=egress_allowlist,json=egressAllowlist,proto3" json:"egress_allowlist,omitempty"` // host allowlist for the secrets proxy+ TokenHosts map[string]*HostList `protobuf:"bytes,9,rep,name=token_hosts,json=tokenHosts,proto3" json:"token_hosts,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` // sealed_id -> per-token allowed hosts+ // env-var-name -> sealed_id index. Required so refresh-by-name+ // (UpdateSandboxSecret) keeps working on the destination worker after+ // migration. Without it, post-migration secret-store updates would silently+ // miss because the destination's session has no name → token mapping.+ SealedNames map[string]string `protobuf:"bytes,10,rep,name=sealed_names,json=sealedNames,proto3" json:"sealed_names,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache}func (x *PreCopyDrivesResponse) Reset() {*x = PreCopyDrivesResponse{}- mi := &file_proto_worker_worker_proto_msgTypes[47]+ mi := &file_proto_worker_worker_proto_msgTypes[51]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -2803,7 +3004,7 @@ func (x *PreCopyDrivesResponse) String() string {func (*PreCopyDrivesResponse) ProtoMessage() {}func (x *PreCopyDrivesResponse) ProtoReflect() protoreflect.Message {- mi := &file_proto_worker_worker_proto_msgTypes[47]+ mi := &file_proto_worker_worker_proto_msgTypes[51]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -2816,7 +3017,7 @@ func (x *PreCopyDrivesResponse) ProtoReflect() protoreflect.Message {// Deprecated: Use PreCopyDrivesResponse.ProtoReflect.Descriptor instead.func (*PreCopyDrivesResponse) Descriptor() ([]byte, []int) {- return file_proto_worker_worker_proto_rawDescGZIP(), []int{47}+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{51}}func (x *PreCopyDrivesResponse) GetRootfsKey() string {@@ -2861,6 +3062,79 @@ func (x *PreCopyDrivesResponse) GetActualMemoryMb() int32 {return 0}+func (x *PreCopyDrivesResponse) GetSealedTokens() map[string]string {+ if x != nil {+ return x.SealedTokens+ }+ return nil+}++func (x *PreCopyDrivesResponse) GetEgressAllowlist() []string {+ if x != nil {+ return x.EgressAllowlist+ }+ return nil+}++func (x *PreCopyDrivesResponse) GetTokenHosts() map[string]*HostList {+ if x != nil {+ return x.TokenHosts+ }+ return nil+}++func (x *PreCopyDrivesResponse) GetSealedNames() map[string]string {+ if x != nil {+ return x.SealedNames+ }+ return nil+}++// HostList is a wrapper because proto3 maps cannot have a repeated value type.+type HostList struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Hosts []string `protobuf:"bytes,1,rep,name=hosts,proto3" json:"hosts,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *HostList) Reset() {+ *x = HostList{}+ mi := &file_proto_worker_worker_proto_msgTypes[52]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *HostList) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*HostList) ProtoMessage() {}++func (x *HostList) ProtoReflect() protoreflect.Message {+ mi := &file_proto_worker_worker_proto_msgTypes[52]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use HostList.ProtoReflect.Descriptor instead.+func (*HostList) Descriptor() ([]byte, []int) {+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{52}+}++func (x *HostList) GetHosts() []string {+ if x != nil {+ return x.Hosts+ }+ return nil+}+type PrepareMigrationIncomingRequest struct {state protoimpl.MessageState `protogen:"open.v1"`SandboxId string `protobuf:"bytes,1,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"`@@ -2875,13 +3149,21 @@ type PrepareMigrationIncomingRequest struct {OverlayMode bool `protobuf:"varint,10,opt,name=overlay_mode,json=overlayMode,proto3" json:"overlay_mode,omitempty"` // if true, rootfs is thin overlay — rebase to local golden on targetTargetMemoryMb int32 `protobuf:"varint,11,opt,name=target_memory_mb,json=targetMemoryMb,proto3" json:"target_memory_mb,omitempty"` // final memory after scale — worker checks capacity and reserves atomicallySourceGoldenVersion string `protobuf:"bytes,12,opt,name=source_golden_version,json=sourceGoldenVersion,proto3" json:"source_golden_version,omitempty"` // source's golden version — target rebases overlay if different from its own- unknownFields protoimpl.UnknownFields- sizeCache protoimpl.SizeCache+ // Secrets-proxy session state captured from the source by PreCopyDrives.+ // Target re-registers these on its in-process secrets proxy BEFORE the+ // VM resumes (Cont) so the first outbound HTTPS request after migration+ // has its `osb_sealed_xxx` env vars correctly substituted.+ SealedTokens map[string]string `protobuf:"bytes,13,rep,name=sealed_tokens,json=sealedTokens,proto3" json:"sealed_tokens,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`+ EgressAllowlist []string `protobuf:"bytes,14,rep,name=egress_allowlist,json=egressAllowlist,proto3" json:"egress_allowlist,omitempty"`+ TokenHosts map[string]*HostList `protobuf:"bytes,15,rep,name=token_hosts,json=tokenHosts,proto3" json:"token_hosts,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`+ SealedNames map[string]string `protobuf:"bytes,16,rep,name=sealed_names,json=sealedNames,proto3" json:"sealed_names,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache}func (x *PrepareMigrationIncomingRequest) Reset() {*x = PrepareMigrationIncomingRequest{}- mi := &file_proto_worker_worker_proto_msgTypes[48]+ mi := &file_proto_worker_worker_proto_msgTypes[53]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -2893,7 +3175,7 @@ func (x *PrepareMigrationIncomingRequest) String() string {func (*PrepareMigrationIncomingRequest) ProtoMessage() {}func (x *PrepareMigrationIncomingRequest) ProtoReflect() protoreflect.Message {- mi := &file_proto_worker_worker_proto_msgTypes[48]+ mi := &file_proto_worker_worker_proto_msgTypes[53]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -2906,7 +3188,7 @@ func (x *PrepareMigrationIncomingRequest) ProtoReflect() protoreflect.Message {// Deprecated: Use PrepareMigrationIncomingRequest.ProtoReflect.Descriptor instead.func (*PrepareMigrationIncomingRequest) Descriptor() ([]byte, []int) {- return file_proto_worker_worker_proto_rawDescGZIP(), []int{48}+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{53}}func (x *PrepareMigrationIncomingRequest) GetSandboxId() string {@@ -2993,6 +3275,34 @@ func (x *PrepareMigrationIncomingRequest) GetSourceGoldenVersion() string {return ""}+func (x *PrepareMigrationIncomingRequest) GetSealedTokens() map[string]string {+ if x != nil {+ return x.SealedTokens+ }+ return nil+}++func (x *PrepareMigrationIncomingRequest) GetEgressAllowlist() []string {+ if x != nil {+ return x.EgressAllowlist+ }+ return nil+}++func (x *PrepareMigrationIncomingRequest) GetTokenHosts() map[string]*HostList {+ if x != nil {+ return x.TokenHosts+ }+ return nil+}++func (x *PrepareMigrationIncomingRequest) GetSealedNames() map[string]string {+ if x != nil {+ return x.SealedNames+ }+ return nil+}+type PrepareMigrationIncomingResponse struct {state protoimpl.MessageState `protogen:"open.v1"`IncomingAddr string `protobuf:"bytes,1,opt,name=incoming_addr,json=incomingAddr,proto3" json:"incoming_addr,omitempty"` // TCP address for source to migrate to (e.g. "10.100.1.7:49152")@@ -3003,7 +3313,7 @@ type PrepareMigrationIncomingResponse struct {func (x *PrepareMigrationIncomingResponse) Reset() {*x = PrepareMigrationIncomingResponse{}- mi := &file_proto_worker_worker_proto_msgTypes[49]+ mi := &file_proto_worker_worker_proto_msgTypes[54]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -3015,7 +3325,7 @@ func (x *PrepareMigrationIncomingResponse) String() string {func (*PrepareMigrationIncomingResponse) ProtoMessage() {}func (x *PrepareMigrationIncomingResponse) ProtoReflect() protoreflect.Message {- mi := &file_proto_worker_worker_proto_msgTypes[49]+ mi := &file_proto_worker_worker_proto_msgTypes[54]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -3028,7 +3338,7 @@ func (x *PrepareMigrationIncomingResponse) ProtoReflect() protoreflect.Message {// Deprecated: Use PrepareMigrationIncomingResponse.ProtoReflect.Descriptor instead.func (*PrepareMigrationIncomingResponse) Descriptor() ([]byte, []int) {- return file_proto_worker_worker_proto_rawDescGZIP(), []int{49}+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{54}}func (x *PrepareMigrationIncomingResponse) GetIncomingAddr() string {@@ -3045,6 +3355,113 @@ func (x *PrepareMigrationIncomingResponse) GetHostPort() int32 {return 0}+type UpdateSandboxSecretRequest struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ SandboxId string `protobuf:"bytes,1,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"`+ SecretName string `protobuf:"bytes,2,opt,name=secret_name,json=secretName,proto3" json:"secret_name,omitempty"` // env var name (the key in the secret store)+ Value string `protobuf:"bytes,3,opt,name=value,proto3" json:"value,omitempty"` // new plaintext value+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *UpdateSandboxSecretRequest) Reset() {+ *x = UpdateSandboxSecretRequest{}+ mi := &file_proto_worker_worker_proto_msgTypes[55]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *UpdateSandboxSecretRequest) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*UpdateSandboxSecretRequest) ProtoMessage() {}++func (x *UpdateSandboxSecretRequest) ProtoReflect() protoreflect.Message {+ mi := &file_proto_worker_worker_proto_msgTypes[55]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use UpdateSandboxSecretRequest.ProtoReflect.Descriptor instead.+func (*UpdateSandboxSecretRequest) Descriptor() ([]byte, []int) {+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{55}+}++func (x *UpdateSandboxSecretRequest) GetSandboxId() string {+ if x != nil {+ return x.SandboxId+ }+ return ""+}++func (x *UpdateSandboxSecretRequest) GetSecretName() string {+ if x != nil {+ return x.SecretName+ }+ return ""+}++func (x *UpdateSandboxSecretRequest) GetValue() string {+ if x != nil {+ return x.Value+ }+ return ""+}++type UpdateSandboxSecretResponse struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ // updated is false if the worker has no proxy session for this sandbox+ // or the secret_name isn't registered on the session. Caller logs ++ // surfaces; not necessarily a hard error (sandbox may be mid-migration).+ Updated bool `protobuf:"varint,1,opt,name=updated,proto3" json:"updated,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *UpdateSandboxSecretResponse) Reset() {+ *x = UpdateSandboxSecretResponse{}+ mi := &file_proto_worker_worker_proto_msgTypes[56]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *UpdateSandboxSecretResponse) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*UpdateSandboxSecretResponse) ProtoMessage() {}++func (x *UpdateSandboxSecretResponse) ProtoReflect() protoreflect.Message {+ mi := &file_proto_worker_worker_proto_msgTypes[56]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use UpdateSandboxSecretResponse.ProtoReflect.Descriptor instead.+func (*UpdateSandboxSecretResponse) Descriptor() ([]byte, []int) {+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{56}+}++func (x *UpdateSandboxSecretResponse) GetUpdated() bool {+ if x != nil {+ return x.Updated+ }+ return false+}+type LiveMigrateRequest struct {state protoimpl.MessageState `protogen:"open.v1"`SandboxId string `protobuf:"bytes,1,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"`@@ -3055,7 +3472,7 @@ type LiveMigrateRequest struct {func (x *LiveMigrateRequest) Reset() {*x = LiveMigrateRequest{}- mi := &file_proto_worker_worker_proto_msgTypes[50]+ mi := &file_proto_worker_worker_proto_msgTypes[57]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -3067,7 +3484,7 @@ func (x *LiveMigrateRequest) String() string {func (*LiveMigrateRequest) ProtoMessage() {}func (x *LiveMigrateRequest) ProtoReflect() protoreflect.Message {- mi := &file_proto_worker_worker_proto_msgTypes[50]+ mi := &file_proto_worker_worker_proto_msgTypes[57]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -3080,7 +3497,7 @@ func (x *LiveMigrateRequest) ProtoReflect() protoreflect.Message {// Deprecated: Use LiveMigrateRequest.ProtoReflect.Descriptor instead.func (*LiveMigrateRequest) Descriptor() ([]byte, []int) {- return file_proto_worker_worker_proto_rawDescGZIP(), []int{50}+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{57}}func (x *LiveMigrateRequest) GetSandboxId() string {@@ -3105,7 +3522,7 @@ type LiveMigrateResponse struct {func (x *LiveMigrateResponse) Reset() {*x = LiveMigrateResponse{}- mi := &file_proto_worker_worker_proto_msgTypes[51]+ mi := &file_proto_worker_worker_proto_msgTypes[58]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -3117,7 +3534,7 @@ func (x *LiveMigrateResponse) String() string {func (*LiveMigrateResponse) ProtoMessage() {}func (x *LiveMigrateResponse) ProtoReflect() protoreflect.Message {- mi := &file_proto_worker_worker_proto_msgTypes[51]+ mi := &file_proto_worker_worker_proto_msgTypes[58]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -3130,7 +3547,7 @@ func (x *LiveMigrateResponse) ProtoReflect() protoreflect.Message {// Deprecated: Use LiveMigrateResponse.ProtoReflect.Descriptor instead.func (*LiveMigrateResponse) Descriptor() ([]byte, []int) {- return file_proto_worker_worker_proto_rawDescGZIP(), []int{51}+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{58}}type CompleteMigrationIncomingRequest struct {@@ -3142,7 +3559,7 @@ type CompleteMigrationIncomingRequest struct {func (x *CompleteMigrationIncomingRequest) Reset() {*x = CompleteMigrationIncomingRequest{}- mi := &file_proto_worker_worker_proto_msgTypes[52]+ mi := &file_proto_worker_worker_proto_msgTypes[59]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -3154,7 +3571,7 @@ func (x *CompleteMigrationIncomingRequest) String() string {func (*CompleteMigrationIncomingRequest) ProtoMessage() {}func (x *CompleteMigrationIncomingRequest) ProtoReflect() protoreflect.Message {- mi := &file_proto_worker_worker_proto_msgTypes[52]+ mi := &file_proto_worker_worker_proto_msgTypes[59]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -3167,7 +3584,7 @@ func (x *CompleteMigrationIncomingRequest) ProtoReflect() protoreflect.Message {// Deprecated: Use CompleteMigrationIncomingRequest.ProtoReflect.Descriptor instead.func (*CompleteMigrationIncomingRequest) Descriptor() ([]byte, []int) {- return file_proto_worker_worker_proto_rawDescGZIP(), []int{52}+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{59}}func (x *CompleteMigrationIncomingRequest) GetSandboxId() string {@@ -3185,7 +3602,7 @@ type CompleteMigrationIncomingResponse struct {func (x *CompleteMigrationIncomingResponse) Reset() {*x = CompleteMigrationIncomingResponse{}- mi := &file_proto_worker_worker_proto_msgTypes[53]+ mi := &file_proto_worker_worker_proto_msgTypes[60]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -3197,7 +3614,7 @@ func (x *CompleteMigrationIncomingResponse) String() string {func (*CompleteMigrationIncomingResponse) ProtoMessage() {}func (x *CompleteMigrationIncomingResponse) ProtoReflect() protoreflect.Message {- mi := &file_proto_worker_worker_proto_msgTypes[53]+ mi := &file_proto_worker_worker_proto_msgTypes[60]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -3210,7 +3627,7 @@ func (x *CompleteMigrationIncomingResponse) ProtoReflect() protoreflect.Message// Deprecated: Use CompleteMigrationIncomingResponse.ProtoReflect.Descriptor instead.func (*CompleteMigrationIncomingResponse) Descriptor() ([]byte, []int) {- return file_proto_worker_worker_proto_rawDescGZIP(), []int{53}+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{60}}// Golden snapshot management@@ -3222,7 +3639,7 @@ type RebuildGoldenSnapshotRequest struct {func (x *RebuildGoldenSnapshotRequest) Reset() {*x = RebuildGoldenSnapshotRequest{}- mi := &file_proto_worker_worker_proto_msgTypes[54]+ mi := &file_proto_worker_worker_proto_msgTypes[61]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -3234,7 +3651,7 @@ func (x *RebuildGoldenSnapshotRequest) String() string {func (*RebuildGoldenSnapshotRequest) ProtoMessage() {}func (x *RebuildGoldenSnapshotRequest) ProtoReflect() protoreflect.Message {- mi := &file_proto_worker_worker_proto_msgTypes[54]+ mi := &file_proto_worker_worker_proto_msgTypes[61]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -3247,7 +3664,7 @@ func (x *RebuildGoldenSnapshotRequest) ProtoReflect() protoreflect.Message {// Deprecated: Use RebuildGoldenSnapshotRequest.ProtoReflect.Descriptor instead.func (*RebuildGoldenSnapshotRequest) Descriptor() ([]byte, []int) {- return file_proto_worker_worker_proto_rawDescGZIP(), []int{54}+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{61}}type RebuildGoldenSnapshotResponse struct {@@ -3260,7 +3677,7 @@ type RebuildGoldenSnapshotResponse struct {func (x *RebuildGoldenSnapshotResponse) Reset() {*x = RebuildGoldenSnapshotResponse{}- mi := &file_proto_worker_worker_proto_msgTypes[55]+ mi := &file_proto_worker_worker_proto_msgTypes[62]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -3272,7 +3689,7 @@ func (x *RebuildGoldenSnapshotResponse) String() string {func (*RebuildGoldenSnapshotResponse) ProtoMessage() {}func (x *RebuildGoldenSnapshotResponse) ProtoReflect() protoreflect.Message {- mi := &file_proto_worker_worker_proto_msgTypes[55]+ mi := &file_proto_worker_worker_proto_msgTypes[62]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -3285,7 +3702,7 @@ func (x *RebuildGoldenSnapshotResponse) ProtoReflect() protoreflect.Message {// Deprecated: Use RebuildGoldenSnapshotResponse.ProtoReflect.Descriptor instead.func (*RebuildGoldenSnapshotResponse) Descriptor() ([]byte, []int) {- return file_proto_worker_worker_proto_rawDescGZIP(), []int{55}+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{62}}func (x *RebuildGoldenSnapshotResponse) GetOldVersion() string {@@ -3343,7 +3760,16 @@ const file_proto_worker_worker_proto_rawDesc = "" +"\x15DestroySandboxRequest\x12\x1d\n" +"\n" +"sandbox_id\x18\x01 \x01(\tR\tsandboxId\"\x18\n" +- "\x16DestroySandboxResponse\"2\n" ++ "\x16DestroySandboxResponse\"5\n" ++ "\x14RebootSandboxRequest\x12\x1d\n" ++ "\n" ++ "sandbox_id\x18\x01 \x01(\tR\tsandboxId\"\x17\n" ++ "\x15RebootSandboxResponse\"9\n" ++ "\x18PowerCycleSandboxRequest\x12\x1d\n" ++ "\n" ++ "sandbox_id\x18\x01 \x01(\tR\tsandboxId\"8\n" ++ "\x19PowerCycleSandboxResponse\x12\x1b\n" ++ "\thost_port\x18\x01 \x01(\x05R\bhostPort\"2\n" +"\x11GetSandboxRequest\x12\x1d\n" +"\n" +"sandbox_id\x18\x01 \x01(\tR\tsandboxId\"\x9d\x01\n" +@@ -3515,10 +3941,12 @@ const file_proto_worker_worker_proto_rawDesc = "" +"\n" +"sandbox_id\x18\x01 \x01(\tR\tsandboxId\x12#\n" +"\rcheckpoint_id\x18\x02 \x01(\tR\fcheckpointId\x12%\n" +- "\x0eprepare_golden\x18\x03 \x01(\bR\rprepareGolden\"h\n" ++ "\x0eprepare_golden\x18\x03 \x01(\bR\rprepareGolden\"\x87\x01\n" +"\x18CreateCheckpointResponse\x12\"\n" +"\rrootfs_s3_key\x18\x01 \x01(\tR\vrootfsS3Key\x12(\n" +- "\x10workspace_s3_key\x18\x02 \x01(\tR\x0eworkspaceS3Key\"^\n" ++ "\x10workspace_s3_key\x18\x02 \x01(\tR\x0eworkspaceS3Key\x12\x1d\n" ++ "\n" ++ "size_bytes\x18\x03 \x01(\x03R\tsizeBytes\"^\n" +"\x18RestoreCheckpointRequest\x12\x1d\n" +"\n" +"sandbox_id\x18\x01 \x01(\tR\tsandboxId\x12#\n" +@@ -3536,7 +3964,7 @@ const file_proto_worker_worker_proto_rawDesc = "" +"\x18SetSandboxLimitsResponse\";\n" +"\x14PreCopyDrivesRequest\x12\x1d\n" +"\n" +- "sandbox_id\x18\x01 \x01(\tR\tsandboxIdJ\x04\b\x02\x10\x03\"\xf8\x01\n" ++ "sandbox_id\x18\x01 \x01(\tR\tsandboxIdJ\x04\b\x02\x10\x03\"\xee\x05\n" +"\x15PreCopyDrivesResponse\x12\x1d\n" +"\n" +"rootfs_key\x18\x01 \x01(\tR\trootfsKey\x12#\n" +@@ -3544,7 +3972,24 @@ const file_proto_worker_worker_proto_rawDesc = "" +"\x0egolden_version\x18\x03 \x01(\tR\rgoldenVersion\x12$\n" +"\x0ebase_memory_mb\x18\x04 \x01(\x05R\fbaseMemoryMb\x12$\n" +"\x0ebase_cpu_count\x18\x05 \x01(\x05R\fbaseCpuCount\x12(\n" +- "\x10actual_memory_mb\x18\x06 \x01(\x05R\x0eactualMemoryMb\"\xcc\x03\n" ++ "\x10actual_memory_mb\x18\x06 \x01(\x05R\x0eactualMemoryMb\x12T\n" ++ "\rsealed_tokens\x18\a \x03(\v2/.worker.PreCopyDrivesResponse.SealedTokensEntryR\fsealedTokens\x12)\n" ++ "\x10egress_allowlist\x18\b \x03(\tR\x0fegressAllowlist\x12N\n" ++ "\vtoken_hosts\x18\t \x03(\v2-.worker.PreCopyDrivesResponse.TokenHostsEntryR\n" ++ "tokenHosts\x12Q\n" ++ "\fsealed_names\x18\n" ++ " \x03(\v2..worker.PreCopyDrivesResponse.SealedNamesEntryR\vsealedNames\x1a?\n" ++ "\x11SealedTokensEntry\x12\x10\n" ++ "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" ++ "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\x1aO\n" ++ "\x0fTokenHostsEntry\x12\x10\n" ++ "\x03key\x18\x01 \x01(\tR\x03key\x12&\n" ++ "\x05value\x18\x02 \x01(\v2\x10.worker.HostListR\x05value:\x028\x01\x1a>\n" ++ "\x10SealedNamesEntry\x12\x10\n" ++ "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" ++ "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\" \n" ++ "\bHostList\x12\x14\n" ++ "\x05hosts\x18\x01 \x03(\tR\x05hosts\"\xe0\a\n" +"\x1fPrepareMigrationIncomingRequest\x12\x1d\n" +"\n" +"sandbox_id\x18\x01 \x01(\tR\tsandboxId\x12\x1f\n" +@@ -3561,10 +4006,32 @@ const file_proto_worker_worker_proto_rawDesc = "" +"\foverlay_mode\x18\n" +" \x01(\bR\voverlayMode\x12(\n" +"\x10target_memory_mb\x18\v \x01(\x05R\x0etargetMemoryMb\x122\n" +- "\x15source_golden_version\x18\f \x01(\tR\x13sourceGoldenVersion\"d\n" ++ "\x15source_golden_version\x18\f \x01(\tR\x13sourceGoldenVersion\x12^\n" ++ "\rsealed_tokens\x18\r \x03(\v29.worker.PrepareMigrationIncomingRequest.SealedTokensEntryR\fsealedTokens\x12)\n" ++ "\x10egress_allowlist\x18\x0e \x03(\tR\x0fegressAllowlist\x12X\n" ++ "\vtoken_hosts\x18\x0f \x03(\v27.worker.PrepareMigrationIncomingRequest.TokenHostsEntryR\n" ++ "tokenHosts\x12[\n" ++ "\fsealed_names\x18\x10 \x03(\v28.worker.PrepareMigrationIncomingRequest.SealedNamesEntryR\vsealedNames\x1a?\n" ++ "\x11SealedTokensEntry\x12\x10\n" ++ "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" ++ "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\x1aO\n" ++ "\x0fTokenHostsEntry\x12\x10\n" ++ "\x03key\x18\x01 \x01(\tR\x03key\x12&\n" ++ "\x05value\x18\x02 \x01(\v2\x10.worker.HostListR\x05value:\x028\x01\x1a>\n" ++ "\x10SealedNamesEntry\x12\x10\n" ++ "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" ++ "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"d\n" +" PrepareMigrationIncomingResponse\x12#\n" +"\rincoming_addr\x18\x01 \x01(\tR\fincomingAddr\x12\x1b\n" +- "\thost_port\x18\x02 \x01(\x05R\bhostPort\"X\n" ++ "\thost_port\x18\x02 \x01(\x05R\bhostPort\"r\n" ++ "\x1aUpdateSandboxSecretRequest\x12\x1d\n" ++ "\n" ++ "sandbox_id\x18\x01 \x01(\tR\tsandboxId\x12\x1f\n" ++ "\vsecret_name\x18\x02 \x01(\tR\n" ++ "secretName\x12\x14\n" ++ "\x05value\x18\x03 \x01(\tR\x05value\"7\n" ++ "\x1bUpdateSandboxSecretResponse\x12\x18\n" ++ "\aupdated\x18\x01 \x01(\bR\aupdated\"X\n" +"\x12LiveMigrateRequest\x12\x1d\n" +"\n" +"sandbox_id\x18\x01 \x01(\tR\tsandboxId\x12#\n" +@@ -3579,7 +4046,7 @@ const file_proto_worker_worker_proto_rawDesc = "" +"\vold_version\x18\x01 \x01(\tR\n" +"oldVersion\x12\x1f\n" +"\vnew_version\x18\x02 \x01(\tR\n" +- "newVersion2\x83\x11\n" ++ "newVersion2\x8b\x13\n" +"\rSandboxWorker\x12L\n" +"\rCreateSandbox\x12\x1c.worker.CreateSandboxRequest\x1a\x1d.worker.CreateSandboxResponse\x12O\n" +"\x0eDestroySandbox\x12\x1d.worker.DestroySandboxRequest\x1a\x1e.worker.DestroySandboxResponse\x12C\n" +@@ -3597,13 +4064,16 @@ const file_proto_worker_worker_proto_rawDesc = "" +"\x0fExecSessionList\x12\x1e.worker.ExecSessionListRequest\x1a\x1f.worker.ExecSessionListResponse\x12R\n" +"\x0fExecSessionKill\x12\x1e.worker.ExecSessionKillRequest\x1a\x1f.worker.ExecSessionKillResponse\x12U\n" +"\x10HibernateSandbox\x12\x1f.worker.HibernateSandboxRequest\x1a .worker.HibernateSandboxResponse\x12F\n" +- "\vWakeSandbox\x12\x1a.worker.WakeSandboxRequest\x1a\x1b.worker.WakeSandboxResponse\x12O\n" ++ "\vWakeSandbox\x12\x1a.worker.WakeSandboxRequest\x1a\x1b.worker.WakeSandboxResponse\x12L\n" ++ "\rRebootSandbox\x12\x1c.worker.RebootSandboxRequest\x1a\x1d.worker.RebootSandboxResponse\x12X\n" ++ "\x11PowerCycleSandbox\x12 .worker.PowerCycleSandboxRequest\x1a!.worker.PowerCycleSandboxResponse\x12O\n" +"\x0eSaveAsTemplate\x12\x1d.worker.SaveAsTemplateRequest\x1a\x1e.worker.SaveAsTemplateResponse\x12U\n" +"\x10CreateCheckpoint\x12\x1f.worker.CreateCheckpointRequest\x1a .worker.CreateCheckpointResponse\x12X\n" +"\x11RestoreCheckpoint\x12 .worker.RestoreCheckpointRequest\x1a!.worker.RestoreCheckpointResponse\x12L\n" +"\rBuildTemplate\x12\x1c.worker.BuildTemplateRequest\x1a\x1d.worker.BuildTemplateResponse\x12R\n" +"\x0fGetSandboxStats\x12\x1e.worker.GetSandboxStatsRequest\x1a\x1f.worker.GetSandboxStatsResponse\x12U\n" +- "\x10SetSandboxLimits\x12\x1f.worker.SetSandboxLimitsRequest\x1a .worker.SetSandboxLimitsResponse\x12L\n" ++ "\x10SetSandboxLimits\x12\x1f.worker.SetSandboxLimitsRequest\x1a .worker.SetSandboxLimitsResponse\x12^\n" ++ "\x13UpdateSandboxSecret\x12\".worker.UpdateSandboxSecretRequest\x1a#.worker.UpdateSandboxSecretResponse\x12L\n" +"\rPreCopyDrives\x12\x1c.worker.PreCopyDrivesRequest\x1a\x1d.worker.PreCopyDrivesResponse\x12m\n" +"\x18PrepareMigrationIncoming\x12'.worker.PrepareMigrationIncomingRequest\x1a(.worker.PrepareMigrationIncomingResponse\x12F\n" +"\vLiveMigrate\x12\x1a.worker.LiveMigrateRequest\x1a\x1b.worker.LiveMigrateResponse\x12p\n" +@@ -3623,141 +4093,168 @@ func file_proto_worker_worker_proto_rawDescGZIP() []byte {}var file_proto_worker_worker_proto_enumTypes = make([]protoimpl.EnumInfo, 1)-var file_proto_worker_worker_proto_msgTypes = make([]protoimpl.MessageInfo, 61)+var file_proto_worker_worker_proto_msgTypes = make([]protoimpl.MessageInfo, 74)var file_proto_worker_worker_proto_goTypes = []any{(ExecOutputChunk_Stream)(0), // 0: worker.ExecOutputChunk.Stream(*CreateSandboxRequest)(nil), // 1: worker.CreateSandboxRequest(*CreateSandboxResponse)(nil), // 2: worker.CreateSandboxResponse(*DestroySandboxRequest)(nil), // 3: worker.DestroySandboxRequest(*DestroySandboxResponse)(nil), // 4: worker.DestroySandboxResponse- (*GetSandboxRequest)(nil), // 5: worker.GetSandboxRequest- (*GetSandboxResponse)(nil), // 6: worker.GetSandboxResponse- (*ListSandboxesRequest)(nil), // 7: worker.ListSandboxesRequest- (*ListSandboxesResponse)(nil), // 8: worker.ListSandboxesResponse- (*ExecCommandRequest)(nil), // 9: worker.ExecCommandRequest- (*ExecCommandResponse)(nil), // 10: worker.ExecCommandResponse- (*ExecOutputChunk)(nil), // 11: worker.ExecOutputChunk- (*ReadFileRequest)(nil), // 12: worker.ReadFileRequest- (*ReadFileResponse)(nil), // 13: worker.ReadFileResponse- (*WriteFileRequest)(nil), // 14: worker.WriteFileRequest- (*WriteFileResponse)(nil), // 15: worker.WriteFileResponse- (*ListDirRequest)(nil), // 16: worker.ListDirRequest- (*DirEntry)(nil), // 17: worker.DirEntry- (*ListDirResponse)(nil), // 18: worker.ListDirResponse- (*CreatePTYRequest)(nil), // 19: worker.CreatePTYRequest- (*CreatePTYResponse)(nil), // 20: worker.CreatePTYResponse- (*PTYInput)(nil), // 21: worker.PTYInput- (*PTYResize)(nil), // 22: worker.PTYResize- (*PTYOutput)(nil), // 23: worker.PTYOutput- (*HibernateSandboxRequest)(nil), // 24: worker.HibernateSandboxRequest- (*HibernateSandboxResponse)(nil), // 25: worker.HibernateSandboxResponse- (*WakeSandboxRequest)(nil), // 26: worker.WakeSandboxRequest- (*WakeSandboxResponse)(nil), // 27: worker.WakeSandboxResponse- (*SaveAsTemplateRequest)(nil), // 28: worker.SaveAsTemplateRequest- (*SaveAsTemplateResponse)(nil), // 29: worker.SaveAsTemplateResponse- (*BuildTemplateRequest)(nil), // 30: worker.BuildTemplateRequest- (*BuildTemplateResponse)(nil), // 31: worker.BuildTemplateResponse- (*ExecSessionCreateRequest)(nil), // 32: worker.ExecSessionCreateRequest- (*ExecSessionCreateResponse)(nil), // 33: worker.ExecSessionCreateResponse- (*ExecSessionListRequest)(nil), // 34: worker.ExecSessionListRequest- (*ExecSessionListResponse)(nil), // 35: worker.ExecSessionListResponse- (*ExecSessionInfoEntry)(nil), // 36: worker.ExecSessionInfoEntry- (*ExecSessionKillRequest)(nil), // 37: worker.ExecSessionKillRequest- (*ExecSessionKillResponse)(nil), // 38: worker.ExecSessionKillResponse- (*GetSandboxStatsRequest)(nil), // 39: worker.GetSandboxStatsRequest- (*GetSandboxStatsResponse)(nil), // 40: worker.GetSandboxStatsResponse- (*CreateCheckpointRequest)(nil), // 41: worker.CreateCheckpointRequest- (*CreateCheckpointResponse)(nil), // 42: worker.CreateCheckpointResponse- (*RestoreCheckpointRequest)(nil), // 43: worker.RestoreCheckpointRequest- (*RestoreCheckpointResponse)(nil), // 44: worker.RestoreCheckpointResponse- (*SetSandboxLimitsRequest)(nil), // 45: worker.SetSandboxLimitsRequest- (*SetSandboxLimitsResponse)(nil), // 46: worker.SetSandboxLimitsResponse- (*PreCopyDrivesRequest)(nil), // 47: worker.PreCopyDrivesRequest- (*PreCopyDrivesResponse)(nil), // 48: worker.PreCopyDrivesResponse- (*PrepareMigrationIncomingRequest)(nil), // 49: worker.PrepareMigrationIncomingRequest- (*PrepareMigrationIncomingResponse)(nil), // 50: worker.PrepareMigrationIncomingResponse- (*LiveMigrateRequest)(nil), // 51: worker.LiveMigrateRequest- (*LiveMigrateResponse)(nil), // 52: worker.LiveMigrateResponse- (*CompleteMigrationIncomingRequest)(nil), // 53: worker.CompleteMigrationIncomingRequest- (*CompleteMigrationIncomingResponse)(nil), // 54: worker.CompleteMigrationIncomingResponse- (*RebuildGoldenSnapshotRequest)(nil), // 55: worker.RebuildGoldenSnapshotRequest- (*RebuildGoldenSnapshotResponse)(nil), // 56: worker.RebuildGoldenSnapshotResponse- nil, // 57: worker.CreateSandboxRequest.EnvsEntry- nil, // 58: worker.CreateSandboxRequest.SecretAllowedHostsEntry- nil, // 59: worker.CreateSandboxRequest.SecretEnvsEntry- nil, // 60: worker.ExecCommandRequest.EnvsEntry- nil, // 61: worker.ExecSessionCreateRequest.EnvsEntry+ (*RebootSandboxRequest)(nil), // 5: worker.RebootSandboxRequest+ (*RebootSandboxResponse)(nil), // 6: worker.RebootSandboxResponse+ (*PowerCycleSandboxRequest)(nil), // 7: worker.PowerCycleSandboxRequest+ (*PowerCycleSandboxResponse)(nil), // 8: worker.PowerCycleSandboxResponse+ (*GetSandboxRequest)(nil), // 9: worker.GetSandboxRequest+ (*GetSandboxResponse)(nil), // 10: worker.GetSandboxResponse+ (*ListSandboxesRequest)(nil), // 11: worker.ListSandboxesRequest+ (*ListSandboxesResponse)(nil), // 12: worker.ListSandboxesResponse+ (*ExecCommandRequest)(nil), // 13: worker.ExecCommandRequest+ (*ExecCommandResponse)(nil), // 14: worker.ExecCommandResponse+ (*ExecOutputChunk)(nil), // 15: worker.ExecOutputChunk+ (*ReadFileRequest)(nil), // 16: worker.ReadFileRequest+ (*ReadFileResponse)(nil), // 17: worker.ReadFileResponse+ (*WriteFileRequest)(nil), // 18: worker.WriteFileRequest+ (*WriteFileResponse)(nil), // 19: worker.WriteFileResponse+ (*ListDirRequest)(nil), // 20: worker.ListDirRequest+ (*DirEntry)(nil), // 21: worker.DirEntry+ (*ListDirResponse)(nil), // 22: worker.ListDirResponse+ (*CreatePTYRequest)(nil), // 23: worker.CreatePTYRequest+ (*CreatePTYResponse)(nil), // 24: worker.CreatePTYResponse+ (*PTYInput)(nil), // 25: worker.PTYInput+ (*PTYResize)(nil), // 26: worker.PTYResize+ (*PTYOutput)(nil), // 27: worker.PTYOutput+ (*HibernateSandboxRequest)(nil), // 28: worker.HibernateSandboxRequest+ (*HibernateSandboxResponse)(nil), // 29: worker.HibernateSandboxResponse+ (*WakeSandboxRequest)(nil), // 30: worker.WakeSandboxRequest+ (*WakeSandboxResponse)(nil), // 31: worker.WakeSandboxResponse+ (*SaveAsTemplateRequest)(nil), // 32: worker.SaveAsTemplateRequest+ (*SaveAsTemplateResponse)(nil), // 33: worker.SaveAsTemplateResponse+ (*BuildTemplateRequest)(nil), // 34: worker.BuildTemplateRequest+ (*BuildTemplateResponse)(nil), // 35: worker.BuildTemplateResponse+ (*ExecSessionCreateRequest)(nil), // 36: worker.ExecSessionCreateRequest+ (*ExecSessionCreateResponse)(nil), // 37: worker.ExecSessionCreateResponse+ (*ExecSessionListRequest)(nil), // 38: worker.ExecSessionListRequest+ (*ExecSessionListResponse)(nil), // 39: worker.ExecSessionListResponse+ (*ExecSessionInfoEntry)(nil), // 40: worker.ExecSessionInfoEntry+ (*ExecSessionKillRequest)(nil), // 41: worker.ExecSessionKillRequest+ (*ExecSessionKillResponse)(nil), // 42: worker.ExecSessionKillResponse+ (*GetSandboxStatsRequest)(nil), // 43: worker.GetSandboxStatsRequest+ (*GetSandboxStatsResponse)(nil), // 44: worker.GetSandboxStatsResponse+ (*CreateCheckpointRequest)(nil), // 45: worker.CreateCheckpointRequest+ (*CreateCheckpointResponse)(nil), // 46: worker.CreateCheckpointResponse+ (*RestoreCheckpointRequest)(nil), // 47: worker.RestoreCheckpointRequest+ (*RestoreCheckpointResponse)(nil), // 48: worker.RestoreCheckpointResponse+ (*SetSandboxLimitsRequest)(nil), // 49: worker.SetSandboxLimitsRequest+ (*SetSandboxLimitsResponse)(nil), // 50: worker.SetSandboxLimitsResponse+ (*PreCopyDrivesRequest)(nil), // 51: worker.PreCopyDrivesRequest+ (*PreCopyDrivesResponse)(nil), // 52: worker.PreCopyDrivesResponse+ (*HostList)(nil), // 53: worker.HostList+ (*PrepareMigrationIncomingRequest)(nil), // 54: worker.PrepareMigrationIncomingRequest+ (*PrepareMigrationIncomingResponse)(nil), // 55: worker.PrepareMigrationIncomingResponse+ (*UpdateSandboxSecretRequest)(nil), // 56: worker.UpdateSandboxSecretRequest+ (*UpdateSandboxSecretResponse)(nil), // 57: worker.UpdateSandboxSecretResponse+ (*LiveMigrateRequest)(nil), // 58: worker.LiveMigrateRequest+ (*LiveMigrateResponse)(nil), // 59: worker.LiveMigrateResponse+ (*CompleteMigrationIncomingRequest)(nil), // 60: worker.CompleteMigrationIncomingRequest+ (*CompleteMigrationIncomingResponse)(nil), // 61: worker.CompleteMigrationIncomingResponse+ (*RebuildGoldenSnapshotRequest)(nil), // 62: worker.RebuildGoldenSnapshotRequest+ (*RebuildGoldenSnapshotResponse)(nil), // 63: worker.RebuildGoldenSnapshotResponse+ nil, // 64: worker.CreateSandboxRequest.EnvsEntry+ nil, // 65: worker.CreateSandboxRequest.SecretAllowedHostsEntry+ nil, // 66: worker.CreateSandboxRequest.SecretEnvsEntry+ nil, // 67: worker.ExecCommandRequest.EnvsEntry+ nil, // 68: worker.ExecSessionCreateRequest.EnvsEntry+ nil, // 69: worker.PreCopyDrivesResponse.SealedTokensEntry+ nil, // 70: worker.PreCopyDrivesResponse.TokenHostsEntry+ nil, // 71: worker.PreCopyDrivesResponse.SealedNamesEntry+ nil, // 72: worker.PrepareMigrationIncomingRequest.SealedTokensEntry+ nil, // 73: worker.PrepareMigrationIncomingRequest.TokenHostsEntry+ nil, // 74: worker.PrepareMigrationIncomingRequest.SealedNamesEntry}var file_proto_worker_worker_proto_depIdxs = []int32{- 57, // 0: worker.CreateSandboxRequest.envs:type_name -> worker.CreateSandboxRequest.EnvsEntry- 58, // 1: worker.CreateSandboxRequest.secret_allowed_hosts:type_name -> worker.CreateSandboxRequest.SecretAllowedHostsEntry- 59, // 2: worker.CreateSandboxRequest.secret_envs:type_name -> worker.CreateSandboxRequest.SecretEnvsEntry- 6, // 3: worker.ListSandboxesResponse.sandboxes:type_name -> worker.GetSandboxResponse- 60, // 4: worker.ExecCommandRequest.envs:type_name -> worker.ExecCommandRequest.EnvsEntry+ 64, // 0: worker.CreateSandboxRequest.envs:type_name -> worker.CreateSandboxRequest.EnvsEntry+ 65, // 1: worker.CreateSandboxRequest.secret_allowed_hosts:type_name -> worker.CreateSandboxRequest.SecretAllowedHostsEntry+ 66, // 2: worker.CreateSandboxRequest.secret_envs:type_name -> worker.CreateSandboxRequest.SecretEnvsEntry+ 10, // 3: worker.ListSandboxesResponse.sandboxes:type_name -> worker.GetSandboxResponse+ 67, // 4: worker.ExecCommandRequest.envs:type_name -> worker.ExecCommandRequest.EnvsEntry0, // 5: worker.ExecOutputChunk.stream:type_name -> worker.ExecOutputChunk.Stream- 17, // 6: worker.ListDirResponse.entries:type_name -> worker.DirEntry- 22, // 7: worker.PTYInput.resize:type_name -> worker.PTYResize- 61, // 8: worker.ExecSessionCreateRequest.envs:type_name -> worker.ExecSessionCreateRequest.EnvsEntry- 36, // 9: worker.ExecSessionListResponse.sessions:type_name -> worker.ExecSessionInfoEntry- 1, // 10: worker.SandboxWorker.CreateSandbox:input_type -> worker.CreateSandboxRequest- 3, // 11: worker.SandboxWorker.DestroySandbox:input_type -> worker.DestroySandboxRequest- 5, // 12: worker.SandboxWorker.GetSandbox:input_type -> worker.GetSandboxRequest- 7, // 13: worker.SandboxWorker.ListSandboxes:input_type -> worker.ListSandboxesRequest- 9, // 14: worker.SandboxWorker.ExecCommand:input_type -> worker.ExecCommandRequest- 9, // 15: worker.SandboxWorker.ExecCommandStream:input_type -> worker.ExecCommandRequest- 12, // 16: worker.SandboxWorker.ReadFile:input_type -> worker.ReadFileRequest- 14, // 17: worker.SandboxWorker.WriteFile:input_type -> worker.WriteFileRequest- 16, // 18: worker.SandboxWorker.ListDir:input_type -> worker.ListDirRequest- 19, // 19: worker.SandboxWorker.CreatePTY:input_type -> worker.CreatePTYRequest- 21, // 20: worker.SandboxWorker.PTYStream:input_type -> worker.PTYInput- 32, // 21: worker.SandboxWorker.ExecSessionCreate:input_type -> worker.ExecSessionCreateRequest- 34, // 22: worker.SandboxWorker.ExecSessionList:input_type -> worker.ExecSessionListRequest- 37, // 23: worker.SandboxWorker.ExecSessionKill:input_type -> worker.ExecSessionKillRequest- 24, // 24: worker.SandboxWorker.HibernateSandbox:input_type -> worker.HibernateSandboxRequest- 26, // 25: worker.SandboxWorker.WakeSandbox:input_type -> worker.WakeSandboxRequest- 28, // 26: worker.SandboxWorker.SaveAsTemplate:input_type -> worker.SaveAsTemplateRequest- 41, // 27: worker.SandboxWorker.CreateCheckpoint:input_type -> worker.CreateCheckpointRequest- 43, // 28: worker.SandboxWorker.RestoreCheckpoint:input_type -> worker.RestoreCheckpointRequest- 30, // 29: worker.SandboxWorker.BuildTemplate:input_type -> worker.BuildTemplateRequest- 39, // 30: worker.SandboxWorker.GetSandboxStats:input_type -> worker.GetSandboxStatsRequest- 45, // 31: worker.SandboxWorker.SetSandboxLimits:input_type -> worker.SetSandboxLimitsRequest- 47, // 32: worker.SandboxWorker.PreCopyDrives:input_type -> worker.PreCopyDrivesRequest- 49, // 33: worker.SandboxWorker.PrepareMigrationIncoming:input_type -> worker.PrepareMigrationIncomingRequest- 51, // 34: worker.SandboxWorker.LiveMigrate:input_type -> worker.LiveMigrateRequest- 53, // 35: worker.SandboxWorker.CompleteMigrationIncoming:input_type -> worker.CompleteMigrationIncomingRequest- 55, // 36: worker.SandboxWorker.RebuildGoldenSnapshot:input_type -> worker.RebuildGoldenSnapshotRequest- 2, // 37: worker.SandboxWorker.CreateSandbox:output_type -> worker.CreateSandboxResponse- 4, // 38: worker.SandboxWorker.DestroySandbox:output_type -> worker.DestroySandboxResponse- 6, // 39: worker.SandboxWorker.GetSandbox:output_type -> worker.GetSandboxResponse- 8, // 40: worker.SandboxWorker.ListSandboxes:output_type -> worker.ListSandboxesResponse- 10, // 41: worker.SandboxWorker.ExecCommand:output_type -> worker.ExecCommandResponse- 11, // 42: worker.SandboxWorker.ExecCommandStream:output_type -> worker.ExecOutputChunk- 13, // 43: worker.SandboxWorker.ReadFile:output_type -> worker.ReadFileResponse- 15, // 44: worker.SandboxWorker.WriteFile:output_type -> worker.WriteFileResponse- 18, // 45: worker.SandboxWorker.ListDir:output_type -> worker.ListDirResponse- 20, // 46: worker.SandboxWorker.CreatePTY:output_type -> worker.CreatePTYResponse- 23, // 47: worker.SandboxWorker.PTYStream:output_type -> worker.PTYOutput- 33, // 48: worker.SandboxWorker.ExecSessionCreate:output_type -> worker.ExecSessionCreateResponse- 35, // 49: worker.SandboxWorker.ExecSessionList:output_type -> worker.ExecSessionListResponse- 38, // 50: worker.SandboxWorker.ExecSessionKill:output_type -> worker.ExecSessionKillResponse- 25, // 51: worker.SandboxWorker.HibernateSandbox:output_type -> worker.HibernateSandboxResponse- 27, // 52: worker.SandboxWorker.WakeSandbox:output_type -> worker.WakeSandboxResponse- 29, // 53: worker.SandboxWorker.SaveAsTemplate:output_type -> worker.SaveAsTemplateResponse- 42, // 54: worker.SandboxWorker.CreateCheckpoint:output_type -> worker.CreateCheckpointResponse- 44, // 55: worker.SandboxWorker.RestoreCheckpoint:output_type -> worker.RestoreCheckpointResponse- 31, // 56: worker.SandboxWorker.BuildTemplate:output_type -> worker.BuildTemplateResponse- 40, // 57: worker.SandboxWorker.GetSandboxStats:output_type -> worker.GetSandboxStatsResponse- 46, // 58: worker.SandboxWorker.SetSandboxLimits:output_type -> worker.SetSandboxLimitsResponse- 48, // 59: worker.SandboxWorker.PreCopyDrives:output_type -> worker.PreCopyDrivesResponse- 50, // 60: worker.SandboxWorker.PrepareMigrationIncoming:output_type -> worker.PrepareMigrationIncomingResponse- 52, // 61: worker.SandboxWorker.LiveMigrate:output_type -> worker.LiveMigrateResponse- 54, // 62: worker.SandboxWorker.CompleteMigrationIncoming:output_type -> worker.CompleteMigrationIncomingResponse- 56, // 63: worker.SandboxWorker.RebuildGoldenSnapshot:output_type -> worker.RebuildGoldenSnapshotResponse- 37, // [37:64] is the sub-list for method output_type- 10, // [10:37] is the sub-list for method input_type- 10, // [10:10] is the sub-list for extension type_name- 10, // [10:10] is the sub-list for extension extendee- 0, // [0:10] is the sub-list for field type_name+ 21, // 6: worker.ListDirResponse.entries:type_name -> worker.DirEntry+ 26, // 7: worker.PTYInput.resize:type_name -> worker.PTYResize+ 68, // 8: worker.ExecSessionCreateRequest.envs:type_name -> worker.ExecSessionCreateRequest.EnvsEntry+ 40, // 9: worker.ExecSessionListResponse.sessions:type_name -> worker.ExecSessionInfoEntry+ 69, // 10: worker.PreCopyDrivesResponse.sealed_tokens:type_name -> worker.PreCopyDrivesResponse.SealedTokensEntry+ 70, // 11: worker.PreCopyDrivesResponse.token_hosts:type_name -> worker.PreCopyDrivesResponse.TokenHostsEntry+ 71, // 12: worker.PreCopyDrivesResponse.sealed_names:type_name -> worker.PreCopyDrivesResponse.SealedNamesEntry+ 72, // 13: worker.PrepareMigrationIncomingRequest.sealed_tokens:type_name -> worker.PrepareMigrationIncomingRequest.SealedTokensEntry+ 73, // 14: worker.PrepareMigrationIncomingRequest.token_hosts:type_name -> worker.PrepareMigrationIncomingRequest.TokenHostsEntry+ 74, // 15: worker.PrepareMigrationIncomingRequest.sealed_names:type_name -> worker.PrepareMigrationIncomingRequest.SealedNamesEntry+ 53, // 16: worker.PreCopyDrivesResponse.TokenHostsEntry.value:type_name -> worker.HostList+ 53, // 17: worker.PrepareMigrationIncomingRequest.TokenHostsEntry.value:type_name -> worker.HostList+ 1, // 18: worker.SandboxWorker.CreateSandbox:input_type -> worker.CreateSandboxRequest+ 3, // 19: worker.SandboxWorker.DestroySandbox:input_type -> worker.DestroySandboxRequest+ 9, // 20: worker.SandboxWorker.GetSandbox:input_type -> worker.GetSandboxRequest+ 11, // 21: worker.SandboxWorker.ListSandboxes:input_type -> worker.ListSandboxesRequest+ 13, // 22: worker.SandboxWorker.ExecCommand:input_type -> worker.ExecCommandRequest+ 13, // 23: worker.SandboxWorker.ExecCommandStream:input_type -> worker.ExecCommandRequest+ 16, // 24: worker.SandboxWorker.ReadFile:input_type -> worker.ReadFileRequest+ 18, // 25: worker.SandboxWorker.WriteFile:input_type -> worker.WriteFileRequest+ 20, // 26: worker.SandboxWorker.ListDir:input_type -> worker.ListDirRequest+ 23, // 27: worker.SandboxWorker.CreatePTY:input_type -> worker.CreatePTYRequest+ 25, // 28: worker.SandboxWorker.PTYStream:input_type -> worker.PTYInput+ 36, // 29: worker.SandboxWorker.ExecSessionCreate:input_type -> worker.ExecSessionCreateRequest+ 38, // 30: worker.SandboxWorker.ExecSessionList:input_type -> worker.ExecSessionListRequest+ 41, // 31: worker.SandboxWorker.ExecSessionKill:input_type -> worker.ExecSessionKillRequest+ 28, // 32: worker.SandboxWorker.HibernateSandbox:input_type -> worker.HibernateSandboxRequest+ 30, // 33: worker.SandboxWorker.WakeSandbox:input_type -> worker.WakeSandboxRequest+ 5, // 34: worker.SandboxWorker.RebootSandbox:input_type -> worker.RebootSandboxRequest+ 7, // 35: worker.SandboxWorker.PowerCycleSandbox:input_type -> worker.PowerCycleSandboxRequest+ 32, // 36: worker.SandboxWorker.SaveAsTemplate:input_type -> worker.SaveAsTemplateRequest+ 45, // 37: worker.SandboxWorker.CreateCheckpoint:input_type -> worker.CreateCheckpointRequest+ 47, // 38: worker.SandboxWorker.RestoreCheckpoint:input_type -> worker.RestoreCheckpointRequest+ 34, // 39: worker.SandboxWorker.BuildTemplate:input_type -> worker.BuildTemplateRequest+ 43, // 40: worker.SandboxWorker.GetSandboxStats:input_type -> worker.GetSandboxStatsRequest+ 49, // 41: worker.SandboxWorker.SetSandboxLimits:input_type -> worker.SetSandboxLimitsRequest+ 56, // 42: worker.SandboxWorker.UpdateSandboxSecret:input_type -> worker.UpdateSandboxSecretRequest+ 51, // 43: worker.SandboxWorker.PreCopyDrives:input_type -> worker.PreCopyDrivesRequest+ 54, // 44: worker.SandboxWorker.PrepareMigrationIncoming:input_type -> worker.PrepareMigrationIncomingRequest+ 58, // 45: worker.SandboxWorker.LiveMigrate:input_type -> worker.LiveMigrateRequest+ 60, // 46: worker.SandboxWorker.CompleteMigrationIncoming:input_type -> worker.CompleteMigrationIncomingRequest+ 62, // 47: worker.SandboxWorker.RebuildGoldenSnapshot:input_type -> worker.RebuildGoldenSnapshotRequest+ 2, // 48: worker.SandboxWorker.CreateSandbox:output_type -> worker.CreateSandboxResponse+ 4, // 49: worker.SandboxWorker.DestroySandbox:output_type -> worker.DestroySandboxResponse+ 10, // 50: worker.SandboxWorker.GetSandbox:output_type -> worker.GetSandboxResponse+ 12, // 51: worker.SandboxWorker.ListSandboxes:output_type -> worker.ListSandboxesResponse+ 14, // 52: worker.SandboxWorker.ExecCommand:output_type -> worker.ExecCommandResponse+ 15, // 53: worker.SandboxWorker.ExecCommandStream:output_type -> worker.ExecOutputChunk+ 17, // 54: worker.SandboxWorker.ReadFile:output_type -> worker.ReadFileResponse+ 19, // 55: worker.SandboxWorker.WriteFile:output_type -> worker.WriteFileResponse+ 22, // 56: worker.SandboxWorker.ListDir:output_type -> worker.ListDirResponse+ 24, // 57: worker.SandboxWorker.CreatePTY:output_type -> worker.CreatePTYResponse+ 27, // 58: worker.SandboxWorker.PTYStream:output_type -> worker.PTYOutput+ 37, // 59: worker.SandboxWorker.ExecSessionCreate:output_type -> worker.ExecSessionCreateResponse+ 39, // 60: worker.SandboxWorker.ExecSessionList:output_type -> worker.ExecSessionListResponse+ 42, // 61: worker.SandboxWorker.ExecSessionKill:output_type -> worker.ExecSessionKillResponse+ 29, // 62: worker.SandboxWorker.HibernateSandbox:output_type -> worker.HibernateSandboxResponse+ 31, // 63: worker.SandboxWorker.WakeSandbox:output_type -> worker.WakeSandboxResponse+ 6, // 64: worker.SandboxWorker.RebootSandbox:output_type -> worker.RebootSandboxResponse+ 8, // 65: worker.SandboxWorker.PowerCycleSandbox:output_type -> worker.PowerCycleSandboxResponse+ 33, // 66: worker.SandboxWorker.SaveAsTemplate:output_type -> worker.SaveAsTemplateResponse+ 46, // 67: worker.SandboxWorker.CreateCheckpoint:output_type -> worker.CreateCheckpointResponse+ 48, // 68: worker.SandboxWorker.RestoreCheckpoint:output_type -> worker.RestoreCheckpointResponse+ 35, // 69: worker.SandboxWorker.BuildTemplate:output_type -> worker.BuildTemplateResponse+ 44, // 70: worker.SandboxWorker.GetSandboxStats:output_type -> worker.GetSandboxStatsResponse+ 50, // 71: worker.SandboxWorker.SetSandboxLimits:output_type -> worker.SetSandboxLimitsResponse+ 57, // 72: worker.SandboxWorker.UpdateSandboxSecret:output_type -> worker.UpdateSandboxSecretResponse+ 52, // 73: worker.SandboxWorker.PreCopyDrives:output_type -> worker.PreCopyDrivesResponse+ 55, // 74: worker.SandboxWorker.PrepareMigrationIncoming:output_type -> worker.PrepareMigrationIncomingResponse+ 59, // 75: worker.SandboxWorker.LiveMigrate:output_type -> worker.LiveMigrateResponse+ 61, // 76: worker.SandboxWorker.CompleteMigrationIncoming:output_type -> worker.CompleteMigrationIncomingResponse+ 63, // 77: worker.SandboxWorker.RebuildGoldenSnapshot:output_type -> worker.RebuildGoldenSnapshotResponse+ 48, // [48:78] is the sub-list for method output_type+ 18, // [18:48] is the sub-list for method input_type+ 18, // [18:18] is the sub-list for extension type_name+ 18, // [18:18] is the sub-list for extension extendee+ 0, // [0:18] is the sub-list for field type_name}func init() { file_proto_worker_worker_proto_init() }@@ -3765,7 +4262,7 @@ func file_proto_worker_worker_proto_init() {if File_proto_worker_worker_proto != nil {return}- file_proto_worker_worker_proto_msgTypes[20].OneofWrappers = []any{+ file_proto_worker_worker_proto_msgTypes[24].OneofWrappers = []any{(*PTYInput_Data)(nil),(*PTYInput_Resize)(nil),}@@ -3775,7 +4272,7 @@ func file_proto_worker_worker_proto_init() {GoPackagePath: reflect.TypeOf(x{}).PkgPath(),RawDescriptor: unsafe.Slice(unsafe.StringData(file_proto_worker_worker_proto_rawDesc), len(file_proto_worker_worker_proto_rawDesc)),NumEnums: 1,- NumMessages: 61,+ NumMessages: 74,NumExtensions: 0,NumServices: 1,},diff --git a/proto/worker/worker.proto b/proto/worker/worker.protoindex 12a2d216..942f50e0 100644--- a/proto/worker/worker.proto+++ b/proto/worker/worker.proto@@ -27,6 +27,19 @@ service SandboxWorker {rpc HibernateSandbox(HibernateSandboxRequest) returns (HibernateSandboxResponse);rpc WakeSandbox(WakeSandboxRequest) returns (WakeSandboxResponse);+ // Reboot performs a soft, in-place guest reset (QMP system_reset). The+ // QEMU process, network, and workspace stay in place; only the guest+ // kernel and processes are reset. Recovers from in-guest wedges (zombie+ // pile, OOM-killed agent, runaway process).+ rpc RebootSandbox(RebootSandboxRequest) returns (RebootSandboxResponse);++ // PowerCycle does a hard reset: tears down the QEMU process and+ // cold-boots a fresh VM with the existing workspace.qcow2. Use when the+ // VMM itself is wedged (QMP unresponsive) or a soft reboot didn't+ // recover. Sandbox keeps its ID, project, secrets, and persistent data;+ // it gets a new TAP, host port, and PID.+ rpc PowerCycleSandbox(PowerCycleSandboxRequest) returns (PowerCycleSandboxResponse);+rpc SaveAsTemplate(SaveAsTemplateRequest) returns (SaveAsTemplateResponse);rpc CreateCheckpoint(CreateCheckpointRequest) returns (CreateCheckpointResponse);@@ -38,6 +51,14 @@ service SandboxWorker {rpc SetSandboxLimits(SetSandboxLimitsRequest) returns (SetSandboxLimitsResponse);+ // UpdateSandboxSecret refreshes the value the proxy substitutes for a+ // sealed token, by env-var name. Used by the secret-store update flow:+ // when a customer PUTs a new value, the CP fans out this RPC to every+ // worker hosting a sandbox that uses the store. Sealed token IDs and+ // sandbox env vars are unchanged — only the proxy session's value map+ // updates, so the next outbound HTTPS substitution uses the new value.+ rpc UpdateSandboxSecret(UpdateSandboxSecretRequest) returns (UpdateSandboxSecretResponse);+// Live migration between workersrpc PreCopyDrives(PreCopyDrivesRequest) returns (PreCopyDrivesResponse);rpc PrepareMigrationIncoming(PrepareMigrationIncomingRequest) returns (PrepareMigrationIncomingResponse);@@ -85,6 +106,24 @@ message DestroySandboxRequest {message DestroySandboxResponse {}+message RebootSandboxRequest {+ string sandbox_id = 1;+}++message RebootSandboxResponse {}++message PowerCycleSandboxRequest {+ string sandbox_id = 1;+}++message PowerCycleSandboxResponse {+ // host_port is the new external port the sandbox is reachable on after+ // power-cycle. Power-cycle re-allocates the TAP and DNAT mapping, so the+ // port may differ from the original. Control plane uses this to update+ // its routing record.+ int32 host_port = 1;+}+message GetSandboxRequest {string sandbox_id = 1;}@@ -298,6 +337,12 @@ message CreateCheckpointRequest {message CreateCheckpointResponse {string rootfs_s3_key = 1;string workspace_s3_key = 2;+ // Size of the uploaded checkpoint archive in bytes. The control plane+ // persists this on the sandbox_checkpoints row instead of the previous+ // hardcoded 0, so customers and operators can see how big a checkpoint+ // actually is. Zero is reported when the archive failed to upload (the+ // checkpoint is still locally usable but cross-worker forks won't work).+ int64 size_bytes = 3;}message RestoreCheckpointRequest {@@ -336,6 +381,27 @@ message PreCopyDrivesResponse {// Used for actual-memory-based scheduling instead of committed/configured// memory (which over-reserves on idle sandboxes).int32 actual_memory_mb = 6;+ // Secrets-proxy session state for the migrating sandbox. Live migration+ // moves the QEMU process (which carries the in-VM env vars containing+ // sealed token IDs) but the proxy's plaintext-substitution map is+ // per-worker in-process state. Without these the destination worker has+ // no way to substitute the literal `osb_sealed_xxx` strings on outbound+ // HTTPS, so the guest's first secret-using call after migration fails+ // auth. Mirrors the SealedTokens/EgressAllowlist/TokenHosts fields the+ // hibernate path persists into snapshot-meta.json.+ map<string, string> sealed_tokens = 7; // sealed_id -> plaintext secret value+ repeated string egress_allowlist = 8; // host allowlist for the secrets proxy+ map<string, HostList> token_hosts = 9; // sealed_id -> per-token allowed hosts+ // env-var-name -> sealed_id index. Required so refresh-by-name+ // (UpdateSandboxSecret) keeps working on the destination worker after+ // migration. Without it, post-migration secret-store updates would silently+ // miss because the destination's session has no name → token mapping.+ map<string, string> sealed_names = 10;+}++// HostList is a wrapper because proto3 maps cannot have a repeated value type.+message HostList {+ repeated string hosts = 1;}message PrepareMigrationIncomingRequest {@@ -351,6 +417,14 @@ message PrepareMigrationIncomingRequest {bool overlay_mode = 10; // if true, rootfs is thin overlay — rebase to local golden on targetint32 target_memory_mb = 11; // final memory after scale — worker checks capacity and reserves atomicallystring source_golden_version = 12; // source's golden version — target rebases overlay if different from its own+ // Secrets-proxy session state captured from the source by PreCopyDrives.+ // Target re-registers these on its in-process secrets proxy BEFORE the+ // VM resumes (Cont) so the first outbound HTTPS request after migration+ // has its `osb_sealed_xxx` env vars correctly substituted.+ map<string, string> sealed_tokens = 13;+ repeated string egress_allowlist = 14;+ map<string, HostList> token_hosts = 15;+ map<string, string> sealed_names = 16;}message PrepareMigrationIncomingResponse {@@ -358,6 +432,19 @@ message PrepareMigrationIncomingResponse {int32 host_port = 2; // mapped host port on target worker}+message UpdateSandboxSecretRequest {+ string sandbox_id = 1;+ string secret_name = 2; // env var name (the key in the secret store)+ string value = 3; // new plaintext value+}++message UpdateSandboxSecretResponse {+ // updated is false if the worker has no proxy session for this sandbox+ // or the secret_name isn't registered on the session. Caller logs ++ // surfaces; not necessarily a hard error (sandbox may be mid-migration).+ bool updated = 1;+}+message LiveMigrateRequest {string sandbox_id = 1;string incoming_addr = 2; // TCP address from PrepareMigrationIncomingdiff --git a/proto/worker/worker_grpc.pb.go b/proto/worker/worker_grpc.pb.goindex d8fb4551..2f2b14bd 100644--- a/proto/worker/worker_grpc.pb.go+++ b/proto/worker/worker_grpc.pb.go@@ -35,12 +35,15 @@ const (SandboxWorker_ExecSessionKill_FullMethodName = "/worker.SandboxWorker/ExecSessionKill"SandboxWorker_HibernateSandbox_FullMethodName = "/worker.SandboxWorker/HibernateSandbox"SandboxWorker_WakeSandbox_FullMethodName = "/worker.SandboxWorker/WakeSandbox"+ SandboxWorker_RebootSandbox_FullMethodName = "/worker.SandboxWorker/RebootSandbox"+ SandboxWorker_PowerCycleSandbox_FullMethodName = "/worker.SandboxWorker/PowerCycleSandbox"SandboxWorker_SaveAsTemplate_FullMethodName = "/worker.SandboxWorker/SaveAsTemplate"SandboxWorker_CreateCheckpoint_FullMethodName = "/worker.SandboxWorker/CreateCheckpoint"SandboxWorker_RestoreCheckpoint_FullMethodName = "/worker.SandboxWorker/RestoreCheckpoint"SandboxWorker_BuildTemplate_FullMethodName = "/worker.SandboxWorker/BuildTemplate"SandboxWorker_GetSandboxStats_FullMethodName = "/worker.SandboxWorker/GetSandboxStats"SandboxWorker_SetSandboxLimits_FullMethodName = "/worker.SandboxWorker/SetSandboxLimits"+ SandboxWorker_UpdateSandboxSecret_FullMethodName = "/worker.SandboxWorker/UpdateSandboxSecret"SandboxWorker_PreCopyDrives_FullMethodName = "/worker.SandboxWorker/PreCopyDrives"SandboxWorker_PrepareMigrationIncoming_FullMethodName = "/worker.SandboxWorker/PrepareMigrationIncoming"SandboxWorker_LiveMigrate_FullMethodName = "/worker.SandboxWorker/LiveMigrate"@@ -68,12 +71,30 @@ type SandboxWorkerClient interface {ExecSessionKill(ctx context.Context, in *ExecSessionKillRequest, opts ...grpc.CallOption) (*ExecSessionKillResponse, error)HibernateSandbox(ctx context.Context, in *HibernateSandboxRequest, opts ...grpc.CallOption) (*HibernateSandboxResponse, error)WakeSandbox(ctx context.Context, in *WakeSandboxRequest, opts ...grpc.CallOption) (*WakeSandboxResponse, error)+ // Reboot performs a soft, in-place guest reset (QMP system_reset). The+ // QEMU process, network, and workspace stay in place; only the guest+ // kernel and processes are reset. Recovers from in-guest wedges (zombie+ // pile, OOM-killed agent, runaway process).+ RebootSandbox(ctx context.Context, in *RebootSandboxRequest, opts ...grpc.CallOption) (*RebootSandboxResponse, error)+ // PowerCycle does a hard reset: tears down the QEMU process and+ // cold-boots a fresh VM with the existing workspace.qcow2. Use when the+ // VMM itself is wedged (QMP unresponsive) or a soft reboot didn't+ // recover. Sandbox keeps its ID, project, secrets, and persistent data;+ // it gets a new TAP, host port, and PID.+ PowerCycleSandbox(ctx context.Context, in *PowerCycleSandboxRequest, opts ...grpc.CallOption) (*PowerCycleSandboxResponse, error)SaveAsTemplate(ctx context.Context, in *SaveAsTemplateRequest, opts ...grpc.CallOption) (*SaveAsTemplateResponse, error)CreateCheckpoint(ctx context.Context, in *CreateCheckpointRequest, opts ...grpc.CallOption) (*CreateCheckpointResponse, error)RestoreCheckpoint(ctx context.Context, in *RestoreCheckpointRequest, opts ...grpc.CallOption) (*RestoreCheckpointResponse, error)BuildTemplate(ctx context.Context, in *BuildTemplateRequest, opts ...grpc.CallOption) (*BuildTemplateResponse, error)GetSandboxStats(ctx context.Context, in *GetSandboxStatsRequest, opts ...grpc.CallOption) (*GetSandboxStatsResponse, error)SetSandboxLimits(ctx context.Context, in *SetSandboxLimitsRequest, opts ...grpc.CallOption) (*SetSandboxLimitsResponse, error)+ // UpdateSandboxSecret refreshes the value the proxy substitutes for a+ // sealed token, by env-var name. Used by the secret-store update flow:+ // when a customer PUTs a new value, the CP fans out this RPC to every+ // worker hosting a sandbox that uses the store. Sealed token IDs and+ // sandbox env vars are unchanged — only the proxy session's value map+ // updates, so the next outbound HTTPS substitution uses the new value.+ UpdateSandboxSecret(ctx context.Context, in *UpdateSandboxSecretRequest, opts ...grpc.CallOption) (*UpdateSandboxSecretResponse, error)// Live migration between workersPreCopyDrives(ctx context.Context, in *PreCopyDrivesRequest, opts ...grpc.CallOption) (*PreCopyDrivesResponse, error)PrepareMigrationIncoming(ctx context.Context, in *PrepareMigrationIncomingRequest, opts ...grpc.CallOption) (*PrepareMigrationIncomingResponse, error)@@ -263,6 +284,26 @@ func (c *sandboxWorkerClient) WakeSandbox(ctx context.Context, in *WakeSandboxRereturn out, nil}+func (c *sandboxWorkerClient) RebootSandbox(ctx context.Context, in *RebootSandboxRequest, opts ...grpc.CallOption) (*RebootSandboxResponse, error) {+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)+ out := new(RebootSandboxResponse)+ err := c.cc.Invoke(ctx, SandboxWorker_RebootSandbox_FullMethodName, in, out, cOpts...)+ if err != nil {+ return nil, err+ }+ return out, nil+}++func (c *sandboxWorkerClient) PowerCycleSandbox(ctx context.Context, in *PowerCycleSandboxRequest, opts ...grpc.CallOption) (*PowerCycleSandboxResponse, error) {+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)+ out := new(PowerCycleSandboxResponse)+ err := c.cc.Invoke(ctx, SandboxWorker_PowerCycleSandbox_FullMethodName, in, out, cOpts...)+ if err != nil {+ return nil, err+ }+ return out, nil+}+func (c *sandboxWorkerClient) SaveAsTemplate(ctx context.Context, in *SaveAsTemplateRequest, opts ...grpc.CallOption) (*SaveAsTemplateResponse, error) {cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)out := new(SaveAsTemplateResponse)@@ -323,6 +364,16 @@ func (c *sandboxWorkerClient) SetSandboxLimits(ctx context.Context, in *SetSandbreturn out, nil}+func (c *sandboxWorkerClient) UpdateSandboxSecret(ctx context.Context, in *UpdateSandboxSecretRequest, opts ...grpc.CallOption) (*UpdateSandboxSecretResponse, error) {+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)+ out := new(UpdateSandboxSecretResponse)+ err := c.cc.Invoke(ctx, SandboxWorker_UpdateSandboxSecret_FullMethodName, in, out, cOpts...)+ if err != nil {+ return nil, err+ }+ return out, nil+}+func (c *sandboxWorkerClient) PreCopyDrives(ctx context.Context, in *PreCopyDrivesRequest, opts ...grpc.CallOption) (*PreCopyDrivesResponse, error) {cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)out := new(PreCopyDrivesResponse)@@ -393,12 +444,30 @@ type SandboxWorkerServer interface {ExecSessionKill(context.Context, *ExecSessionKillRequest) (*ExecSessionKillResponse, error)HibernateSandbox(context.Context, *HibernateSandboxRequest) (*HibernateSandboxResponse, error)WakeSandbox(context.Context, *WakeSandboxRequest) (*WakeSandboxResponse, error)+ // Reboot performs a soft, in-place guest reset (QMP system_reset). The+ // QEMU process, network, and workspace stay in place; only the guest+ // kernel and processes are reset. Recovers from in-guest wedges (zombie+ // pile, OOM-killed agent, runaway process).+ RebootSandbox(context.Context, *RebootSandboxRequest) (*RebootSandboxResponse, error)+ // PowerCycle does a hard reset: tears down the QEMU process and+ // cold-boots a fresh VM with the existing workspace.qcow2. Use when the+ // VMM itself is wedged (QMP unresponsive) or a soft reboot didn't+ // recover. Sandbox keeps its ID, project, secrets, and persistent data;+ // it gets a new TAP, host port, and PID.+ PowerCycleSandbox(context.Context, *PowerCycleSandboxRequest) (*PowerCycleSandboxResponse, error)SaveAsTemplate(context.Context, *SaveAsTemplateRequest) (*SaveAsTemplateResponse, error)CreateCheckpoint(context.Context, *CreateCheckpointRequest) (*CreateCheckpointResponse, error)RestoreCheckpoint(context.Context, *RestoreCheckpointRequest) (*RestoreCheckpointResponse, error)BuildTemplate(context.Context, *BuildTemplateRequest) (*BuildTemplateResponse, error)GetSandboxStats(context.Context, *GetSandboxStatsRequest) (*GetSandboxStatsResponse, error)SetSandboxLimits(context.Context, *SetSandboxLimitsRequest) (*SetSandboxLimitsResponse, error)+ // UpdateSandboxSecret refreshes the value the proxy substitutes for a+ // sealed token, by env-var name. Used by the secret-store update flow:+ // when a customer PUTs a new value, the CP fans out this RPC to every+ // worker hosting a sandbox that uses the store. Sealed token IDs and+ // sandbox env vars are unchanged — only the proxy session's value map+ // updates, so the next outbound HTTPS substitution uses the new value.+ UpdateSandboxSecret(context.Context, *UpdateSandboxSecretRequest) (*UpdateSandboxSecretResponse, error)// Live migration between workersPreCopyDrives(context.Context, *PreCopyDrivesRequest) (*PreCopyDrivesResponse, error)PrepareMigrationIncoming(context.Context, *PrepareMigrationIncomingRequest) (*PrepareMigrationIncomingResponse, error)@@ -464,6 +533,12 @@ func (UnimplementedSandboxWorkerServer) HibernateSandbox(context.Context, *Hiberfunc (UnimplementedSandboxWorkerServer) WakeSandbox(context.Context, *WakeSandboxRequest) (*WakeSandboxResponse, error) {return nil, status.Error(codes.Unimplemented, "method WakeSandbox not implemented")}+func (UnimplementedSandboxWorkerServer) RebootSandbox(context.Context, *RebootSandboxRequest) (*RebootSandboxResponse, error) {+ return nil, status.Error(codes.Unimplemented, "method RebootSandbox not implemented")+}+func (UnimplementedSandboxWorkerServer) PowerCycleSandbox(context.Context, *PowerCycleSandboxRequest) (*PowerCycleSandboxResponse, error) {+ return nil, status.Error(codes.Unimplemented, "method PowerCycleSandbox not implemented")+}func (UnimplementedSandboxWorkerServer) SaveAsTemplate(context.Context, *SaveAsTemplateRequest) (*SaveAsTemplateResponse, error) {return nil, status.Error(codes.Unimplemented, "method SaveAsTemplate not implemented")}@@ -482,6 +557,9 @@ func (UnimplementedSandboxWorkerServer) GetSandboxStats(context.Context, *GetSanfunc (UnimplementedSandboxWorkerServer) SetSandboxLimits(context.Context, *SetSandboxLimitsRequest) (*SetSandboxLimitsResponse, error) {return nil, status.Error(codes.Unimplemented, "method SetSandboxLimits not implemented")}+func (UnimplementedSandboxWorkerServer) UpdateSandboxSecret(context.Context, *UpdateSandboxSecretRequest) (*UpdateSandboxSecretResponse, error) {+ return nil, status.Error(codes.Unimplemented, "method UpdateSandboxSecret not implemented")+}func (UnimplementedSandboxWorkerServer) PreCopyDrives(context.Context, *PreCopyDrivesRequest) (*PreCopyDrivesResponse, error) {return nil, status.Error(codes.Unimplemented, "method PreCopyDrives not implemented")}@@ -788,6 +866,42 @@ func _SandboxWorker_WakeSandbox_Handler(srv interface{}, ctx context.Context, dereturn interceptor(ctx, in, info, handler)}+func _SandboxWorker_RebootSandbox_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {+ in := new(RebootSandboxRequest)+ if err := dec(in); err != nil {+ return nil, err+ }+ if interceptor == nil {+ return srv.(SandboxWorkerServer).RebootSandbox(ctx, in)+ }+ info := &grpc.UnaryServerInfo{+ Server: srv,+ FullMethod: SandboxWorker_RebootSandbox_FullMethodName,+ }+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {+ return srv.(SandboxWorkerServer).RebootSandbox(ctx, req.(*RebootSandboxRequest))+ }+ return interceptor(ctx, in, info, handler)+}++func _SandboxWorker_PowerCycleSandbox_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {+ in := new(PowerCycleSandboxRequest)+ if err := dec(in); err != nil {+ return nil, err+ }+ if interceptor == nil {+ return srv.(SandboxWorkerServer).PowerCycleSandbox(ctx, in)+ }+ info := &grpc.UnaryServerInfo{+ Server: srv,+ FullMethod: SandboxWorker_PowerCycleSandbox_FullMethodName,+ }+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {+ return srv.(SandboxWorkerServer).PowerCycleSandbox(ctx, req.(*PowerCycleSandboxRequest))+ }+ return interceptor(ctx, in, info, handler)+}+func _SandboxWorker_SaveAsTemplate_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {in := new(SaveAsTemplateRequest)if err := dec(in); err != nil {@@ -896,6 +1010,24 @@ func _SandboxWorker_SetSandboxLimits_Handler(srv interface{}, ctx context.Contexreturn interceptor(ctx, in, info, handler)}+func _SandboxWorker_UpdateSandboxSecret_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {+ in := new(UpdateSandboxSecretRequest)+ if err := dec(in); err != nil {+ return nil, err+ }+ if interceptor == nil {+ return srv.(SandboxWorkerServer).UpdateSandboxSecret(ctx, in)+ }+ info := &grpc.UnaryServerInfo{+ Server: srv,+ FullMethod: SandboxWorker_UpdateSandboxSecret_FullMethodName,+ }+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {+ return srv.(SandboxWorkerServer).UpdateSandboxSecret(ctx, req.(*UpdateSandboxSecretRequest))+ }+ return interceptor(ctx, in, info, handler)+}+func _SandboxWorker_PreCopyDrives_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {in := new(PreCopyDrivesRequest)if err := dec(in); err != nil {@@ -1049,6 +1181,14 @@ var SandboxWorker_ServiceDesc = grpc.ServiceDesc{MethodName: "WakeSandbox",Handler: _SandboxWorker_WakeSandbox_Handler,},+ {+ MethodName: "RebootSandbox",+ Handler: _SandboxWorker_RebootSandbox_Handler,+ },+ {+ MethodName: "PowerCycleSandbox",+ Handler: _SandboxWorker_PowerCycleSandbox_Handler,+ },{MethodName: "SaveAsTemplate",Handler: _SandboxWorker_SaveAsTemplate_Handler,@@ -1073,6 +1213,10 @@ var SandboxWorker_ServiceDesc = grpc.ServiceDesc{MethodName: "SetSandboxLimits",Handler: _SandboxWorker_SetSandboxLimits_Handler,},+ {+ MethodName: "UpdateSandboxSecret",+ Handler: _SandboxWorker_UpdateSandboxSecret_Handler,+ },{MethodName: "PreCopyDrives",Handler: _SandboxWorker_PreCopyDrives_Handler,diff --git a/scripts/qemu-tests/40-corruption-guards.sh b/scripts/qemu-tests/40-corruption-guards.shnew file mode 100755index 00000000..4760d0a6--- /dev/null+++ b/scripts/qemu-tests/40-corruption-guards.sh@@ -0,0 +1,355 @@+#!/usr/bin/env bash+# 40-corruption-guards.sh — Stress the four hibernate/checkpoint corruption+# guards landed in fix/savevm-corruption-guards. Each section asserts the+# guard actually fires under the conditions it's designed to catch.+#+# Sections (set SECTION=<n> to run only one):+# 1. Hibernate refusal when the in-guest agent is unresponsive.+# Suspend the agent with SIGSTOP, issue Hibernate, expect a clean error+# (NOT "guest sync + unmount done (0ms)" followed by a savevm). The+# rootfs.qcow2 mtime on the worker must not change during the attempt.+#+# 2. Checkpoint+fork under sustained I/O.+# Regression test for the explicit Stop/SaveVM/Cont sequence: a busy+# writer thread must not produce a corrupt qcow2 when checkpointed,+# and the forked child must boot cleanly with the checkpointed file+# contents intact.+#+# 3. Apt-cache bind-mount lifecycle.+# Fresh sandbox: /var/cache/apt/archives must be a bind-mount onto+# /home/sandbox/.osb-apt-cache. Across hibernate+wake the bind-mount+# must still be in place. apt-get update writes must land on /dev/vdb,+# not /dev/vda.+#+# 4. Disk-pressure refusal.+# Fill rootfs to >=95%, attempt Hibernate, expect ErrRootfsCritical+# with the actual % surfaced. Free space below threshold and confirm+# the next Hibernate succeeds.+#+# Required env:+# OPENSANDBOX_API_URL (e.g. https://dev.opencomputer.dev)+# OPENSANDBOX_API_KEY+# SSH_KEY path to a key with worker access, optional but+# required for the rootfs.qcow2 mtime assertion in+# section 1 (skipped without it)+#+# Optional:+# ITERATIONS=<n> repeat each section's main loop n times (default 3)+# SECTION=<1|2|3|4> run only one section+# FILL_PCT=<n> section 4 target % (default 96)++set +u+source "$(dirname "$0")/common.sh"++ITERATIONS="${ITERATIONS:-3}"+SECTION="${SECTION:-all}"+FILL_PCT="${FILL_PCT:-96}"+TIMEOUT=180+SANDBOXES=()+PASS=0+FAIL=0+SKIP=0++cleanup() {+ set +u+ for sb in "${SANDBOXES[@]+"${SANDBOXES[@]}"}"; do+ [ -n "$sb" ] && destroy_sandbox "$sb" 2>/dev/null+ done+ set -u+}+trap cleanup EXIT INT TERM++# Helper: parse error message + status from a JSON error response.+err_msg() { python3 -c "import sys,json; d=json.load(sys.stdin); print(d.get('error') or d.get('message') or d)" 2>/dev/null; }++# Helper: read worker-side mtime of a sandbox's rootfs.qcow2 over SSH.+# Returns "skip" if SSH_KEY isn't set or worker host can't be inferred.+worker_rootfs_mtime() {+ local sb="$1"+ [ -z "${SSH_KEY:-}" ] && { echo skip; return; }+ local worker_id worker_host path+ worker_id=$(api "$API_URL/api/sandboxes/$sb" 2>/dev/null | python3 -c "import sys,json; print(json.load(sys.stdin).get('worker_id',''))" 2>/dev/null)+ [ -z "$worker_id" ] && { echo skip; return; }+ # Workers expose their grpc_addr in the workers list — strip port.+ worker_host=$(api "$API_URL/api/workers" 2>/dev/null | python3 -c "+import sys, json+target = '$worker_id'+for w in json.load(sys.stdin):+ if w.get('worker_id') == target:+ addr = w.get('grpc_addr') or w.get('http_addr') or ''+ print(addr.split(':')[0])+ break+" 2>/dev/null)+ [ -z "$worker_host" ] && { echo skip; return; }+ path="/data/sandboxes/sandboxes/$sb/rootfs.qcow2"+ ssh -o StrictHostKeyChecking=no -o ConnectTimeout=5 -i "$SSH_KEY" \+ "azureuser@$worker_host" "stat -c %Y $path 2>/dev/null" 2>/dev/null || echo skip+}++# Helper: freeze the entire VM from the host so the in-guest agent stops+# responding to gRPC. We can't SIGSTOP the agent directly because it runs as+# PID 1 (SIGNAL_UNKILLABLE — the kernel rejects user-space SIGSTOP to init).+# Instead, find the QEMU process for this sandbox on the host and SIGSTOP it.+# Restoring is symmetric (SIGCONT). Requires SSH access to the host (set+# DEV_VM_HOST + SSH_KEY); skips the section if unavailable.+#+# Action: stop|cont+freeze_guest_agent() {+ local sb="$1"+ local action="${2:-stop}"+ local sig="STOP"+ [ "$action" = "cont" ] && sig="CONT"+ if [ -z "${DEV_VM_HOST:-}" ] || [ -z "${SSH_KEY:-}" ]; then+ return 2 # not configured — caller should skip+ fi+ ssh -o StrictHostKeyChecking=no -o ConnectTimeout=5 -i "$SSH_KEY" \+ "${DEV_VM_USER:-azureuser}@$DEV_VM_HOST" \+ "sudo pkill -$sig -f 'qemu.*$sb' 2>/dev/null; sleep 0.5; sudo pgrep -f 'qemu.*$sb' >/dev/null && echo found || echo nopid" 2>/dev/null+}++# ── Section 1: Hibernate refusal on unresponsive agent ────────────────+section1() {+ h "Section 1: Hibernate refusal when guest agent is unresponsive ($ITERATIONS iters)"+ if [ -z "${DEV_VM_HOST:-}" ] || [ -z "${SSH_KEY:-}" ]; then+ skip "Section 1 needs DEV_VM_HOST + SSH_KEY for host-side QEMU SIGSTOP (PID-1 freeze inside guest is blocked by SIGNAL_UNKILLABLE)."+ return+ fi+ for i in $(seq 1 "$ITERATIONS"); do+ SB=$(create_sandbox)+ SANDBOXES+=("$SB")++ # Wait for the QEMU process to be fully up and the agent registered.+ sleep 4++ # SIGSTOP the QEMU process for this sandbox on the host. Freezes the+ # whole VM, including the agent's gRPC server. The host's prepare-+ # hibernate RPC will hit its 10s timeout (PrepareHibernate), then the+ # 10s fallback Exec timeout, then bubble up ErrAgentUnresponsive.+ local freeze_result+ freeze_result=$(freeze_guest_agent "$SB" stop)+ if ! echo "$freeze_result" | grep -q found; then+ skip "iter $i: could not locate QEMU process for $SB on host"+ destroy_sandbox "$SB"+ continue+ fi++ local resp http_status+ resp=$(api -X POST -w '\nHTTP_STATUS:%{http_code}\n' "$API_URL/api/sandboxes/$SB/hibernate" 2>/dev/null)+ http_status=$(echo "$resp" | grep '^HTTP_STATUS:' | cut -d: -f2)++ # ALWAYS resume the QEMU process — even on test failure — so we don't+ # leak frozen VMs in the dev environment.+ freeze_guest_agent "$SB" cont >/dev/null 2>&1++ if [ "$http_status" = "200" ] || [ "$http_status" = "204" ]; then+ fail "iter $i: Hibernate succeeded against frozen VM (expected refusal)"+ elif echo "$resp" | grep -qi "agent unresponsive\|ErrAgentUnresponsive\|guest agent"; then+ pass "iter $i: Hibernate refused with agent-unresponsive error (HTTP $http_status)"+ else+ fail "iter $i: Hibernate failed (HTTP $http_status) but error did not mention agent unresponsiveness"+ echo "$resp" | tail -3 | sed 's/^/ /'+ fi++ destroy_sandbox "$SB"+ done+}++# ── Section 2: Checkpoint+fork under sustained I/O ────────────────────+section2() {+ h "Section 2: Checkpoint+fork under heavy I/O ($ITERATIONS iters)"+ for i in $(seq 1 "$ITERATIONS"); do+ SB=$(create_sandbox)+ SANDBOXES+=("$SB")++ # Start a background writer producing churn into rootfs+workspace.+ # 50 MB/s into rootfs for 30s plus a tight rename loop on workspace.+ exec_run "$SB" "bash" "-c" "+ (dd if=/dev/urandom of=/tmp/churn bs=1M count=200 oflag=direct 2>/dev/null) &+ (for j in \$(seq 1 200); do echo j-\$j > /home/sandbox/.churn.\$j; mv /home/sandbox/.churn.\$j /home/sandbox/.churn-final.\$j; done) &+ sleep 0.5; echo writers-launched+ " >/dev/null++ # Drop a deterministic blob whose hash we'll verify post-fork.+ local blob_hash+ exec_run "$SB" "bash" "-c" "dd if=/dev/urandom of=/home/sandbox/blob.bin bs=1M count=20 2>/dev/null && sync" >/dev/null+ blob_hash=$(exec_stdout "$SB" "bash" "-c" "sha256sum /home/sandbox/blob.bin | cut -d' ' -f1")++ # Take the checkpoint while the writers are still going. The API uses+ # capital-N "Name" on input; response field is "id" (not checkpoint_id).+ local cp_resp cp_id+ cp_resp=$(api -X POST "$API_URL/api/sandboxes/$SB/checkpoints" -d "{\"Name\":\"guard-test-$i\"}" 2>/dev/null)+ cp_id=$(echo "$cp_resp" | python3 -c "import sys,json; print(json.load(sys.stdin).get('id',''))" 2>/dev/null)+ if [ -z "$cp_id" ]; then+ fail "iter $i: checkpoint create failed: $(echo $cp_resp | err_msg)"+ destroy_sandbox "$SB"+ continue+ fi+ pass "iter $i: checkpoint $cp_id created under load"++ # Checkpoint create returns immediately with status=processing; wait+ # for it to finish before forking from it. There is no+ # GET /api/checkpoints/<id> endpoint — we list per-sandbox and filter.+ local waited=0+ local cp_status=""+ while [ "$waited" -lt 90 ]; do+ cp_status=$(CP_ID="$cp_id" api "$API_URL/api/sandboxes/$SB/checkpoints" 2>/dev/null \+ | CP_ID="$cp_id" python3 -c "import sys,json,os+target=os.environ['CP_ID']+for cp in (json.load(sys.stdin) or []):+ if cp.get('id')==target:+ print(cp.get('status','')); break" 2>/dev/null)+ [ "$cp_status" = "ready" ] && break+ [ "$cp_status" = "failed" ] && { fail "iter $i: checkpoint $cp_id failed during processing"; break; }+ sleep 2; waited=$((waited+2))+ done+ if [ "$cp_status" != "ready" ]; then+ fail "iter $i: checkpoint $cp_id never reached ready (last status=$cp_status, waited ${waited}s)"+ destroy_sandbox "$SB"+ continue+ fi++ # Source sandbox should still be running afterward (Cont was issued).+ local status+ status=$(api "$API_URL/api/sandboxes/$SB" 2>/dev/null | python3 -c "import sys,json; print(json.load(sys.stdin).get('status',''))" 2>/dev/null)+ if [ "$status" = "running" ]; then+ pass "iter $i: source sandbox still running post-checkpoint"+ else+ fail "iter $i: source sandbox status=$status after checkpoint (expected running) — Cont may have failed"+ fi++ # Fork from the checkpoint and verify blob hash matches.+ # Endpoint is POST /api/sandboxes/from-checkpoint/<id> (per router.go).+ local fork_resp fork_sb fork_hash+ fork_resp=$(api -X POST "$API_URL/api/sandboxes/from-checkpoint/$cp_id" -d '{}' 2>/dev/null)+ fork_sb=$(echo "$fork_resp" | python3 -c "import sys,json; print(json.load(sys.stdin).get('sandboxID',''))" 2>/dev/null)+ if [ -z "$fork_sb" ]; then+ fail "iter $i: fork from checkpoint failed: $(echo $fork_resp | err_msg)"+ else+ SANDBOXES+=("$fork_sb")+ sleep 3+ fork_hash=$(exec_stdout "$fork_sb" "bash" "-c" "sha256sum /home/sandbox/blob.bin | cut -d' ' -f1")+ if [ "$blob_hash" = "$fork_hash" ]; then+ pass "iter $i: fork blob.bin hash matches source"+ else+ fail "iter $i: fork blob hash MISMATCH (expected $blob_hash, got $fork_hash)"+ fi+ destroy_sandbox "$fork_sb"+ fi+ destroy_sandbox "$SB"+ done+}++# ── Section 3: Apt-cache bind-mount lifecycle ─────────────────────────+section3() {+ h "Section 3: Apt-cache bind-mount survives lifecycle events ($ITERATIONS iters)"+ for i in $(seq 1 "$ITERATIONS"); do+ SB=$(create_sandbox)+ SANDBOXES+=("$SB")++ # Fresh-spawn check.+ local mp_status+ mp_status=$(exec_exit_code "$SB" "bash" "-c" "mountpoint -q /var/cache/apt/archives")+ if [ "$mp_status" = "0" ]; then+ pass "iter $i: bind-mount in place on fresh spawn"+ else+ fail "iter $i: /var/cache/apt/archives is NOT a bind-mount on fresh spawn"+ fi++ # Verify the underlying device is /dev/vdb (workspace), not /dev/vda.+ local mount_dev+ mount_dev=$(exec_stdout "$SB" "bash" "-c" "findmnt -no SOURCE /var/cache/apt/archives 2>/dev/null | head -1")+ if [[ "$mount_dev" == *"vdb"* ]] || [[ "$mount_dev" == *"sandbox/.osb-apt-cache"* ]]; then+ pass "iter $i: bind-mount source is workspace ($mount_dev)"+ else+ fail "iter $i: bind-mount source is unexpected: $mount_dev"+ fi++ # apt-get update writes index files into /var/cache/apt — write a+ # marker file there and verify it actually lands on workspace.+ exec_run "$SB" "bash" "-c" "sudo touch /var/cache/apt/archives/.bind-test-$i" >/dev/null+ local on_workspace+ on_workspace=$(exec_stdout "$SB" "bash" "-c" "[ -f /home/sandbox/.osb-apt-cache/.bind-test-$i ] && echo yes || echo no")+ if [ "$on_workspace" = "yes" ]; then+ pass "iter $i: writes through /var/cache/apt/archives land on /home/sandbox/.osb-apt-cache"+ else+ fail "iter $i: bind-mount is not redirecting writes correctly"+ fi++ # Hibernate + wake. Bind-mount must be re-applied (or survive) on wake.+ api -X POST "$API_URL/api/sandboxes/$SB/hibernate" >/dev/null 2>&1+ sleep 5+ api -X POST "$API_URL/api/sandboxes/$SB/wake" -d '{"timeout":3600}' >/dev/null 2>&1+ sleep 5+ mp_status=$(exec_exit_code "$SB" "bash" "-c" "mountpoint -q /var/cache/apt/archives")+ if [ "$mp_status" = "0" ]; then+ pass "iter $i: bind-mount in place after hibernate+wake"+ else+ fail "iter $i: bind-mount lost after hibernate+wake"+ fi++ destroy_sandbox "$SB"+ done+}++# ── Section 4: Disk-pressure refusal ──────────────────────────────────+section4() {+ h "Section 4: Hibernate/checkpoint refused at >=95% rootfs use ($ITERATIONS iters, fill=$FILL_PCT%)"+ for i in $(seq 1 "$ITERATIONS"); do+ SB=$(create_sandbox)+ SANDBOXES+=("$SB")++ # Fill the rootfs (NOT workspace) to FILL_PCT% using dd (fallocate+ # allocates lazily on this ext4 — sparse files don't show in df). dd+ # writes zeros in 1 MiB blocks with conv=fsync so blocks are really+ # reserved. NB: must be a single line — common.sh's exec_run flattens+ # multi-line args via newline-split, which truncates a multi-line+ # bash -c body to just its first line.+ exec_run "$SB" "bash" "-c" "set -e; B=\$(stat -fc %s /); T=\$(stat -fc %b /); A=\$(stat -fc %a /); TOT=\$((B*T)); USED=\$((TOT-A*B)); TGT=\$((TOT*$FILL_PCT/100)); FILL_MB=\$(( (TGT-USED)/1024/1024 )); [ \$FILL_MB -gt 0 ] && sudo dd if=/dev/zero of=/.fill bs=1M count=\$FILL_MB conv=fsync status=none 2>&1 || true; df -h / | tail -1" >/dev/null++ local pct_used+ pct_used=$(exec_stdout "$SB" "bash" "-c" "df --output=pcent / | tail -1 | tr -dc '0-9'")+ if [ -z "$pct_used" ] || [ "$pct_used" -lt 95 ]; then+ skip "iter $i: rootfs only at ${pct_used:-?}% — fallocate may have failed; can't exercise refusal"+ destroy_sandbox "$SB"+ continue+ fi+ pass "iter $i: rootfs at $pct_used%"++ local resp http_status+ resp=$(api -X POST -w '\nHTTP_STATUS:%{http_code}\n' "$API_URL/api/sandboxes/$SB/hibernate" 2>/dev/null)+ http_status=$(echo "$resp" | grep '^HTTP_STATUS:' | cut -d: -f2)++ if [ "$http_status" = "200" ] || [ "$http_status" = "204" ]; then+ fail "iter $i: Hibernate succeeded against full rootfs at $pct_used% (expected refusal)"+ elif echo "$resp" | grep -qi "rootfs disk usage\|ErrRootfsCritical\|rootfs at"; then+ pass "iter $i: Hibernate refused with disk-pressure error"+ else+ fail "iter $i: Hibernate failed (HTTP $http_status) but error did not mention disk pressure"+ echo "$resp" | tail -3 | sed 's/^/ /'+ fi++ # Free space and confirm Hibernate now succeeds.+ exec_run "$SB" "bash" "-c" "sudo rm -f /.fill && sync" >/dev/null+ sleep 1+ resp=$(api -X POST -w '\nHTTP_STATUS:%{http_code}\n' "$API_URL/api/sandboxes/$SB/hibernate" 2>/dev/null)+ http_status=$(echo "$resp" | grep '^HTTP_STATUS:' | cut -d: -f2)+ if [ "$http_status" = "200" ] || [ "$http_status" = "204" ]; then+ pass "iter $i: Hibernate succeeded after freeing space"+ else+ fail "iter $i: Hibernate still failed after freeing space (HTTP $http_status)"+ fi+ destroy_sandbox "$SB"+ done+}++# ── Dispatch ──────────────────────────────────────────────────────────+case "$SECTION" in+ 1) section1 ;;+ 2) section2 ;;+ 3) section3 ;;+ 4) section4 ;;+ all|"") section1; section2; section3; section4 ;;+ *) echo "unknown SECTION=$SECTION (expected 1|2|3|4|all)"; exit 64 ;;+esac++summarydiff --git a/scripts/rclone-azure-to-tigris.sh b/scripts/rclone-azure-to-tigris.shnew file mode 100755index 00000000..70aeaddb--- /dev/null+++ b/scripts/rclone-azure-to-tigris.sh@@ -0,0 +1,134 @@+#!/usr/bin/env bash+# rclone-azure-to-tigris.sh+#+# Copies worker-managed object storage from Azure Blob to Tigris.+# Idempotent; safe to re-run for delta syncs.+#+# Required env vars:+# AZURE_STORAGE_ACCOUNT e.g. occkpt3ccf3c31+# AZURE_STORAGE_KEY az storage account keys list -g <rg> -n <account> --query "[0].value" -o tsv+# TIGRIS_ACCESS_KEY_ID+# TIGRIS_SECRET_ACCESS_KEY+#+# Optional:+# SRC_CONTAINER default: checkpoints+# TIGRIS_BUCKET default: opencomputer-prod+# TIGRIS_ENDPOINT default: https://t3.storage.dev+#+# ---------------------------------------------------------------------------+# Why two passes (don't simplify this without understanding):+#+# The legacy Azure backend stripped a leading "<container>/" from keys on+# write (internal/storage/blob_azure.go's normalizeKey). So a key like+# "checkpoints/sb-xxx/123.tar.zst" passed by the worker was stored at Azure+# blob name "sb-xxx/123.tar.zst" (no checkpoints/ prefix).+#+# The new S3-compat backend (internal/blobstore/s3.go) does NOT strip.+# Workers calling Get(bucket="opencomputer-prod", key="checkpoints/sb-xxx/...")+# expect Tigris to have it at exactly that key.+#+# So sandbox archives in Azure ("sb-XXXX/...") must be re-prefixed with+# "checkpoints/" when copying to Tigris. Other prefixes (bases/, migrations/,+# templates/) were never stripped — their keys never started with+# "checkpoints/" — so they stay at their current paths.+#+# Skipped on purpose: deploy/, db-backups/, rootfs-cache/ — no worker+# code reads these (build artifacts / out-of-band backups).+# ---------------------------------------------------------------------------+#+# Required rclone flags:+# --s3-storage-class STANDARD Tigris rejects Azure's "Hot"/"Cool" tier+# names — without this every PUT fails with+# 400 InvalidStorageClass.+# --metadata=false Skip Azure-specific metadata that doesn't+# translate and isn't needed by our code.++set -euo pipefail++: "${AZURE_STORAGE_ACCOUNT:?required}"+: "${AZURE_STORAGE_KEY:?required}"+: "${TIGRIS_ACCESS_KEY_ID:?required}"+: "${TIGRIS_SECRET_ACCESS_KEY:?required}"++SRC_CONTAINER="${SRC_CONTAINER:-checkpoints}"+TIGRIS_BUCKET="${TIGRIS_BUCKET:-opencomputer-prod}"+TIGRIS_ENDPOINT="${TIGRIS_ENDPOINT:-https://t3.storage.dev}"++export RCLONE_CONFIG_AZ_TYPE=azureblob+export RCLONE_CONFIG_AZ_ACCOUNT="$AZURE_STORAGE_ACCOUNT"+export RCLONE_CONFIG_AZ_KEY="$AZURE_STORAGE_KEY"++export RCLONE_CONFIG_TIGRIS_TYPE=s3+export RCLONE_CONFIG_TIGRIS_PROVIDER=Other+export RCLONE_CONFIG_TIGRIS_ENDPOINT="$TIGRIS_ENDPOINT"+export RCLONE_CONFIG_TIGRIS_REGION=auto+export RCLONE_CONFIG_TIGRIS_ACCESS_KEY_ID="$TIGRIS_ACCESS_KEY_ID"+export RCLONE_CONFIG_TIGRIS_SECRET_ACCESS_KEY="$TIGRIS_SECRET_ACCESS_KEY"+export RCLONE_CONFIG_TIGRIS_FORCE_PATH_STYLE=true++TIMESTAMP="$(date +%Y%m%d-%H%M%S)"+LOG_SB="${LOG_SB:-rclone-az-to-tigris-sb-${TIMESTAMP}.log}"+LOG_REST="${LOG_REST:-rclone-az-to-tigris-rest-${TIMESTAMP}.log}"++# Shared flags. --s3-storage-class STANDARD + --metadata=false are required+# for Tigris compatibility; the rest is throughput tuning.+#+# Memory sizing: rclone holds (transfers × multi-thread-streams ×+# upload-concurrency × chunk-size) bytes in flight as a worst case. The+# settings below cap at ~4 GB resident on the bastion, fitting D4s_v3+# (16 GB) comfortably. An earlier tuning with transfers=16, streams=8,+# concurrency=4, chunk=64M OOM-killed rclone on Pass 2's 4 GB golden files.+# If you upsize the bastion to D8s_v3 (32 GB) or larger you can crank these+# back up.+COMMON_FLAGS=(+ --s3-storage-class STANDARD+ --metadata=false+ --transfers 8+ --checkers 32+ --multi-thread-streams 4+ --multi-thread-cutoff 512M+ --s3-chunk-size 32M+ --s3-upload-concurrency 2+ --progress+ --stats 30s+ --stats-one-line+ --log-level INFO+)++echo "==> $(date) Pass 1: sb-* sandbox archives → tigris:${TIGRIS_BUCKET}/checkpoints/"+echo " log: $LOG_SB"+echo " extra args: $*"++# Pass 1: relocate sb-* archives under the "checkpoints/" prefix so the+# new worker code's HibernationKey() ("checkpoints/sb-xxx/...") finds them.+rclone copy \+ "az:$SRC_CONTAINER" \+ "tigris:$TIGRIS_BUCKET/checkpoints" \+ --include "sb-*/**" \+ --log-file "$LOG_SB" \+ "${COMMON_FLAGS[@]}" \+ "$@"++echo "==> $(date) Pass 2: bases/, migrations/, templates/ → tigris:${TIGRIS_BUCKET}/ (unchanged paths)"+echo " log: $LOG_REST"++# Pass 2: copy other worker-managed prefixes verbatim. These already match+# what the new code expects (no prefix transform needed).+rclone copy \+ "az:$SRC_CONTAINER" \+ "tigris:$TIGRIS_BUCKET" \+ --include "bases/**" \+ --include "migrations/**" \+ --include "templates/**" \+ --log-file "$LOG_REST" \+ "${COMMON_FLAGS[@]}" \+ "$@"++echo "==> $(date) done. logs: $LOG_SB, $LOG_REST"+echo ""+echo "Parity check:"+echo " rclone size az:$SRC_CONTAINER --include 'sb-*/**'"+echo " rclone size tigris:$TIGRIS_BUCKET/checkpoints"+echo ""+echo " rclone size az:$SRC_CONTAINER --include 'bases/**' --include 'migrations/**' --include 'templates/**'"+echo " rclone size tigris:$TIGRIS_BUCKET --include 'bases/**' --include 'migrations/**' --include 'templates/**'"diff --git a/sdks/python/opencomputer/__init__.py b/sdks/python/opencomputer/__init__.pyindex 80d8015c..cb7b40c3 100644--- a/sdks/python/opencomputer/__init__.py+++ b/sdks/python/opencomputer/__init__.py@@ -1,6 +1,6 @@"""OpenComputer Python SDK - cloud sandbox platform."""-from opencomputer.sandbox import Sandbox+from opencomputer.sandbox import Sandbox, ScalingLockedError, PlanLimitErrorfrom opencomputer.agent import Agent, AgentEvent, AgentSession, AgentSessionInfofrom opencomputer.filesystem import Filesystemfrom opencomputer.exec import Exec, ProcessResult, ExecSession, ExecSessionInfo@@ -25,6 +25,8 @@ from opencomputer.usage import (__all__ = ["Sandbox",+ "ScalingLockedError",+ "PlanLimitError","Agent","AgentEvent","AgentSession",@@ -55,4 +57,4 @@ __all__ = ["TagKeyInfo",]-__version__ = "0.5.2"+__version__ = "0.5.4"diff --git a/sdks/python/opencomputer/sandbox.py b/sdks/python/opencomputer/sandbox.pyindex dfcd4ce7..84a15153 100644--- a/sdks/python/opencomputer/sandbox.py+++ b/sdks/python/opencomputer/sandbox.py@@ -16,6 +16,42 @@ from opencomputer.pty import Ptyfrom opencomputer.sse import parse_sse_stream+class ScalingLockedError(Exception):+ """Raised by ``scale``, ``set_autoscale``, and other resource-changing+ calls when the sandbox has a scaling lock active. Catch this to handle+ the lock case specifically — typically by surfacing a clear message to+ the user, or unlocking via ``sandbox.set_scaling_lock(False)`` first.+ """++ code = "scaling_locked"+++class PlanLimitError(Exception):+ """Raised by ``scale`` and ``set_autoscale`` when the requested size+ exceeds the organization's plan cap (e.g. free tier blocks > 4 GB).+ The HTTP layer returns 402 Payment Required for this case.+ """+++def _raise_scaling_error(resp: httpx.Response, action: str) -> None:+ """Inspect a non-OK scaling response and raise the most specific error.+ Falls back to ``raise_for_status`` so callers still see HTTP details for+ unknown shapes."""+ try:+ body = resp.json()+ except Exception:+ body = {}+ if resp.status_code == 403 and isinstance(body, dict) and body.get("code") == "scaling_locked":+ raise ScalingLockedError(body.get("error", "scaling is locked on this sandbox"))+ if resp.status_code == 402:+ msg = body.get("error", "plan limit exceeded") if isinstance(body, dict) else "plan limit exceeded"+ raise PlanLimitError(msg)+ # Re-raise as the generic httpx error so callers get the status + body.+ resp.raise_for_status()+ # Defensive: shouldn't reach here on a non-OK response.+ raise httpx.HTTPStatusError(f"failed to {action}: {resp.status_code}", request=resp.request, response=resp)++@dataclassclass Sandbox:"""E2B-compatible sandbox interface."""@@ -205,6 +241,35 @@ class Sandbox:resp.raise_for_status()self.status = "stopped"+ async def reboot(self) -> None:+ """Soft restart the running sandbox.++ Resets the guest CPU and reboots the kernel — equivalent to running+ ``reboot`` inside the sandbox. The QEMU process, network mapping,+ and persistent disks all stay; only in-memory state (running+ processes, page caches) is wiped.++ Use to recover from in-guest wedges: zombie pile-ups, OOM-killed+ agents, runaway processes, broken-but-isolated systemd state.++ For the rare case where the VMM itself is wedged (e.g. QMP+ unresponsive), use :meth:`power_cycle` instead.+ """+ resp = await self._client.post(f"/sandboxes/{self.sandbox_id}/reboot")+ resp.raise_for_status()++ async def power_cycle(self) -> None:+ """Hard restart the sandbox.++ The QEMU process is killed and a fresh one is started with the+ same on-disk drives. Sandbox keeps its ID, project, secrets, env,+ and persistent workspace data; gets a new external host port and+ TAP. Use when the VMM itself is wedged or :meth:`reboot` doesn't+ recover.+ """+ resp = await self._client.post(f"/sandboxes/{self.sandbox_id}/power-cycle")+ resp.raise_for_status()+async def is_running(self) -> bool:"""Check if the sandbox is still running."""try:@@ -216,6 +281,155 @@ class Sandbox:except httpx.HTTPStatusError:return False+ async def scale(self, memory_mb: int) -> dict:+ """Manually resize the sandbox to a specific memory tier.++ CPU is bundled with memory per the platform's tier table (e.g. 8 GB+ → 4 vCPU). Allowed tiers: 1024, 4096, 8192, 16384, 32768, 65536 MB.++ A manual scale disables autoscale on this sandbox as a side effect.+ Re-enable with :meth:`set_autoscale` if you want size to track load.++ Args:+ memory_mb: Target memory tier in MB.++ Raises:+ ScalingLockedError: The sandbox has a scaling lock active.+ PlanLimitError: ``memory_mb`` exceeds the org's plan cap.++ Returns:+ Dict with ``sandboxID``, ``memoryMB``, ``cpuPercent``.+ """+ resp = await self._client.post(+ f"/sandboxes/{self.sandbox_id}/scale",+ json={"memoryMB": memory_mb},+ )+ if resp.status_code >= 400:+ _raise_scaling_error(resp, "scale")+ return resp.json()++ async def set_autoscale(+ self,+ enabled: bool,+ *,+ min_memory_mb: int | None = None,+ max_memory_mb: int | None = None,+ ) -> dict:+ """Enable or disable per-sandbox autoscale.++ When enabled, the platform resizes the sandbox between+ ``min_memory_mb`` and ``max_memory_mb`` based on observed memory+ pressure — scaling up fast on a 1-min spike, down slowly after+ sustained idle.++ Both bounds must be allowed memory tiers (1024, 4096, 8192, 16384,+ 32768, 65536 MB). Pass ``enabled=False`` to turn autoscale off+ (bounds are ignored in that case).++ Args:+ enabled: Whether autoscale should be active.+ min_memory_mb: Lower bound when ``enabled=True``.+ max_memory_mb: Upper bound when ``enabled=True``. Must be ≥+ ``min_memory_mb``.++ Raises:+ ScalingLockedError: The sandbox has a scaling lock active.+ PlanLimitError: ``max_memory_mb`` exceeds the org's plan cap.++ Returns:+ Dict with ``sandboxID``, ``enabled``, ``minMemoryMB``,+ ``maxMemoryMB``.+ """+ body: dict[str, Any] = {"enabled": enabled}+ if min_memory_mb is not None:+ body["minMemoryMB"] = min_memory_mb+ if max_memory_mb is not None:+ body["maxMemoryMB"] = max_memory_mb+ resp = await self._client.put(+ f"/sandboxes/{self.sandbox_id}/autoscale",+ json=body,+ )+ if resp.status_code >= 400:+ _raise_scaling_error(resp, "set autoscale")+ return resp.json()++ async def get_autoscale(self) -> dict:+ """Return the current autoscale configuration.++ Returns:+ Dict with ``sandboxID``, ``enabled``, ``minMemoryMB``,+ ``maxMemoryMB``.+ """+ resp = await self._client.get(f"/sandboxes/{self.sandbox_id}/autoscale")+ resp.raise_for_status()+ return resp.json()++ async def set_scaling_lock(self, locked: bool) -> dict:+ """Lock or unlock the sandbox's resources against scaling.++ When locked:++ - :meth:`scale` raises :class:`ScalingLockedError`.+ - :meth:`set_autoscale` with ``enabled=True`` raises+ :class:`ScalingLockedError`.+ - The platform autoscaler skips this sandbox entirely.++ Locking ALSO disables autoscale as a side effect (single-knob+ semantics — "I don't want this scaling, period"). Unlocking does+ NOT re-enable autoscale; call :meth:`set_autoscale` explicitly if+ you want it back.++ Args:+ locked: ``True`` to freeze, ``False`` to allow scaling again.++ Returns:+ Dict with ``sandboxID``, ``locked``.+ """+ resp = await self._client.put(+ f"/sandboxes/{self.sandbox_id}/scaling-lock",+ json={"locked": locked},+ )+ resp.raise_for_status()+ return resp.json()++ async def get_scaling_lock(self) -> dict:+ """Return the current scaling-lock state.++ Returns:+ Dict with ``sandboxID``, ``locked``.+ """+ resp = await self._client.get(f"/sandboxes/{self.sandbox_id}/scaling-lock")+ resp.raise_for_status()+ return resp.json()++ async def get_allowed_hosts(self) -> dict:+ """Return the egress allowlist + per-secret allowed hosts the+ sandbox's secrets proxy enforces.++ Useful for debugging "why is my outbound HTTP call being blocked"+ without having to cross-reference the secret store config separately.++ Sandboxes created without a ``secret_store`` option return an empty+ allowlist and ``secretStore`` is omitted — the sandbox has no+ per-store egress restriction.++ Returns:+ Dict with::++ {+ "sandboxID": "sb-...",+ "secretStore": "<store-name>", # omitted if no store+ "egressAllowlist": ["api.openai.com", ...],+ "perSecretAllowedHosts": {+ "OPENAI_API_KEY": ["api.openai.com"],+ ...+ },+ }+ """+ resp = await self._client.get(f"/sandboxes/{self.sandbox_id}/allowed-hosts")+ resp.raise_for_status()+ return resp.json()+async def set_timeout(self, timeout: int) -> None:"""Update the sandbox timeout in seconds."""# Route to worker directly (like commands/files/pty) — the control planediff --git a/sdks/python/pyproject.toml b/sdks/python/pyproject.tomlindex e4cc8f41..d44d2101 100644--- a/sdks/python/pyproject.toml+++ b/sdks/python/pyproject.toml@@ -4,7 +4,7 @@ build-backend = "hatchling.build"[project]name = "opencomputer-sdk"-version = "0.5.3"+version = "0.5.4"description = "Python SDK for OpenComputer - cloud sandbox platform"readme = "README.md"requires-python = ">=3.10"diff --git a/sdks/typescript/examples/test-allowed-hosts.ts b/sdks/typescript/examples/test-allowed-hosts.tsnew file mode 100644index 00000000..f452edc7--- /dev/null+++ b/sdks/typescript/examples/test-allowed-hosts.ts@@ -0,0 +1,196 @@+/**+ * sandbox.getAllowedHosts() Test+ *+ * Verifies AllowedHostsInfo returned by sandbox.getAllowedHosts():+ * - sandboxID string+ * - secretStore string | undefined (undefined when no store)+ * - egressAllowlist string[] (hosts reachable via secrets proxy)+ * - perSecretAllowedHosts Record<string, string[]> (per-secret host restrictions)+ *+ * The server response also includes `baseSecretStore` (parent name for layered+ * forks; omitted when empty). The SDK type doesn't expose it yet, so the test+ * reads it via cast.+ *+ * Cases covered:+ * 1. Sandbox with no secret store → secretStore undefined, empty allowlist+ * 2. Sandbox with secret store → store name + aggregated egress allowlist+ * 3. Per-secret allowedHosts → surfaced under perSecretAllowedHosts+ * 4. Forked store (createFromCheckpoint) → baseSecretStore reflects parent+ *+ * Usage:+ * OPENCOMPUTER_API_URL=... OPENCOMPUTER_API_KEY=... npx tsx examples/test-allowed-hosts.ts+ */++import { Sandbox, SecretStore } from "../src/index";++function green(msg: string) { console.log(`\x1b[32m✓ ${msg}\x1b[0m`); }+function red(msg: string, detail?: string) {+ console.log(`\x1b[31m✗ ${msg}${detail ? ` — ${detail}` : ""}\x1b[0m`);+}+function bold(msg: string) { console.log(`\x1b[1m${msg}\x1b[0m`); }+function dim(msg: string) { console.log(`\x1b[2m ${msg}\x1b[0m`); }++let passed = 0;+let failed = 0;++function check(desc: string, condition: boolean, detail?: string) {+ if (condition) { green(desc); passed++; }+ else { red(desc, detail); failed++; }+}++async function main() {+ bold("\n=== sandbox.getAllowedHosts() ===\n");++ const suffix = Date.now();+ const baseStoreName = `allowed-hosts-base-${suffix}`;+ const forkStoreName = `allowed-hosts-fork-${suffix}`;++ let baseStoreId: string | null = null;+ let forkStoreId: string | null = null;+ let plainSandbox: Sandbox | null = null;+ let storeSandbox: Sandbox | null = null;+ let forkedSandbox: Sandbox | null = null;+ let checkpointId: string | null = null;++ try {+ // ── Setup: two secret stores ──────────────────────────────────────+ bold("--- Setup: create base + fork secret stores ---\n");++ const baseStore = await SecretStore.create({+ name: baseStoreName,+ egressAllowlist: ["api.anthropic.com", "github.com"],+ });+ baseStoreId = baseStore.id;+ await SecretStore.setSecret(baseStoreId, "GIT_TOKEN", "git_xyz", {+ allowedHosts: ["github.com"],+ });+ await SecretStore.setSecret(baseStoreId, "ANTHROPIC_KEY", "sk-ant-xyz");+ dim(`Base store: ${baseStoreId} (${baseStoreName})`);++ const forkStore = await SecretStore.create({+ name: forkStoreName,+ egressAllowlist: ["httpbin.org"],+ });+ forkStoreId = forkStore.id;+ await SecretStore.setSecret(forkStoreId, "EXTRA_KEY", "extra_val", {+ allowedHosts: ["httpbin.org"],+ });+ dim(`Fork store: ${forkStoreId} (${forkStoreName})`);+ console.log();++ // ── Case 1: sandbox with no secret store ──────────────────────────+ bold("--- Case 1: sandbox with no secret store ---\n");++ plainSandbox = await Sandbox.create({ timeout: 120 });+ const plainInfo = await plainSandbox.getAllowedHosts();+ const plainBase = (plainInfo as { baseSecretStore?: string }).baseSecretStore;++ check("sandboxID matches", plainInfo.sandboxID === plainSandbox.sandboxId,+ `got "${plainInfo.sandboxID}"`);+ check("secretStore is unset", plainInfo.secretStore === undefined,+ `got ${JSON.stringify(plainInfo.secretStore)}`);+ check("baseSecretStore is unset", plainBase === undefined || plainBase === "",+ `got ${JSON.stringify(plainBase)}`);+ check("egressAllowlist is empty array",+ Array.isArray(plainInfo.egressAllowlist) && plainInfo.egressAllowlist.length === 0,+ `got ${JSON.stringify(plainInfo.egressAllowlist)}`);+ check("perSecretAllowedHosts has no entries",+ Object.keys(plainInfo.perSecretAllowedHosts ?? {}).length === 0,+ `got ${JSON.stringify(plainInfo.perSecretAllowedHosts)}`);+ console.log();++ // ── Case 2 + 3: sandbox with secret store + per-secret hosts ──────+ bold("--- Case 2/3: sandbox with secret store ---\n");++ storeSandbox = await Sandbox.create({+ secretStore: baseStoreName,+ timeout: 120,+ });+ const storeInfo = await storeSandbox.getAllowedHosts();+ const storeBase = (storeInfo as { baseSecretStore?: string }).baseSecretStore;++ check("sandboxID matches", storeInfo.sandboxID === storeSandbox.sandboxId);+ check("secretStore name matches", storeInfo.secretStore === baseStoreName,+ `got "${storeInfo.secretStore}"`);+ check("baseSecretStore is unset (no fork)",+ storeBase === undefined || storeBase === "",+ `got ${JSON.stringify(storeBase)}`);++ const egress = storeInfo.egressAllowlist ?? [];+ check("egressAllowlist contains api.anthropic.com",+ egress.includes("api.anthropic.com"), `got ${JSON.stringify(egress)}`);+ check("egressAllowlist contains github.com",+ egress.includes("github.com"), `got ${JSON.stringify(egress)}`);++ const perSecret = storeInfo.perSecretAllowedHosts ?? {};+ check("perSecretAllowedHosts has GIT_TOKEN", "GIT_TOKEN" in perSecret,+ `keys: ${Object.keys(perSecret).join(", ")}`);+ check("GIT_TOKEN restricted to github.com",+ Array.isArray(perSecret.GIT_TOKEN) &&+ perSecret.GIT_TOKEN.length === 1 &&+ perSecret.GIT_TOKEN[0] === "github.com",+ `got ${JSON.stringify(perSecret.GIT_TOKEN)}`);+ check("ANTHROPIC_KEY has no per-secret restriction",+ !("ANTHROPIC_KEY" in perSecret),+ "secret without allowedHosts should not appear in perSecretAllowedHosts");+ console.log();++ // ── Case 4: forked sandbox via createFromCheckpoint ──────────────+ bold("--- Case 4: forked sandbox (baseSecretStore) ---\n");++ checkpointId = (await storeSandbox.createCheckpoint(`allowed-hosts-cp-${suffix}`)).id;+ dim(`Checkpoint: ${checkpointId}`);++ forkedSandbox = await Sandbox.createFromCheckpoint(checkpointId, {+ secretStore: forkStoreName,+ timeout: 120,+ });+ const forkInfo = await forkedSandbox.getAllowedHosts();+ const forkBase = (forkInfo as { baseSecretStore?: string }).baseSecretStore;++ check("sandboxID matches", forkInfo.sandboxID === forkedSandbox.sandboxId);+ check("secretStore is fork store", forkInfo.secretStore === forkStoreName,+ `got "${forkInfo.secretStore}"`);+ check("baseSecretStore is parent store",+ forkBase === baseStoreName,+ `got ${JSON.stringify(forkBase)}`);++ const forkEgress = forkInfo.egressAllowlist ?? [];+ check("forked egress includes parent host (github.com)",+ forkEgress.includes("github.com"), `got ${JSON.stringify(forkEgress)}`);+ check("forked egress includes child host (httpbin.org)",+ forkEgress.includes("httpbin.org"), `got ${JSON.stringify(forkEgress)}`);++ const forkPerSecret = forkInfo.perSecretAllowedHosts ?? {};+ check("forked perSecret includes parent GIT_TOKEN",+ "GIT_TOKEN" in forkPerSecret);+ check("forked perSecret includes child EXTRA_KEY",+ "EXTRA_KEY" in forkPerSecret);+ console.log();++ } catch (err: any) {+ red(`Fatal error: ${err.message}`);+ if (err.stack) dim(err.stack);+ failed++;+ } finally {+ // Cleanup+ for (const sb of [plainSandbox, storeSandbox, forkedSandbox]) {+ if (sb) { try { await sb.kill(); } catch {} }+ }+ if (checkpointId && storeSandbox) {+ try { await storeSandbox.deleteCheckpoint(checkpointId); } catch {}+ }+ if (forkStoreId) { try { await SecretStore.delete(forkStoreId); } catch {} }+ if (baseStoreId) { try { await SecretStore.delete(baseStoreId); } catch {} }+ }++ bold("========================================");+ bold(` Results: ${passed} passed, ${failed} failed`);+ bold("========================================\n");+ if (failed > 0) process.exit(1);+}++main().catch((err) => {+ console.error("Fatal error:", err);+ process.exit(1);+});diff --git a/sdks/typescript/package.json b/sdks/typescript/package.jsonindex 603d1ede..84483112 100644--- a/sdks/typescript/package.json+++ b/sdks/typescript/package.json@@ -1,6 +1,6 @@{"name": "@opencomputer/sdk",- "version": "0.5.16",+ "version": "0.5.17","description": "TypeScript SDK for OpenComputer - cloud sandbox platform","type": "module","main": "dist/index.js",diff --git a/sdks/typescript/src/index.ts b/sdks/typescript/src/index.tsindex e18372b5..1632fd68 100644--- a/sdks/typescript/src/index.ts+++ b/sdks/typescript/src/index.ts@@ -1,4 +1,17 @@-export { Sandbox, type SandboxOpts, type CheckpointInfo, type PatchInfo, type PatchResult } from "./sandbox.js";+export {+ Sandbox,+ ScalingLockedError,+ PlanLimitError,+ type SandboxOpts,+ type CheckpointInfo,+ type PatchInfo,+ type PatchResult,+ type ScaleResult,+ type AutoscaleConfig,+ type AutoscaleStatus,+ type ScalingLockStatus,+ type AllowedHostsInfo,+} from "./sandbox.js";export { Agent, type AgentEvent, type AgentConfig, type AgentStartOpts, type AgentSession, type McpServerConfig } from "./agent.js";export { Filesystem, type EntryInfo } from "./filesystem.js";export { Exec, type ProcessResult, type RunOpts, type ExecSession, type ExecSessionInfo, type ExecStartOpts, type ExecAttachOpts } from "./exec.js";diff --git a/sdks/typescript/src/sandbox.ts b/sdks/typescript/src/sandbox.tsindex 17fc2f8b..b1f9cb1a 100644--- a/sdks/typescript/src/sandbox.ts+++ b/sdks/typescript/src/sandbox.ts@@ -91,6 +91,100 @@ export interface PreviewURLResult {createdAt: string;}+/**+ * Thrown by `scale`, `setAutoscale`, and resource-changing calls when the+ * sandbox has a scaling lock active. Catch this to handle the lock case+ * specifically — typically by surfacing a clear message to the user, or+ * unlocking via `sandbox.setScalingLock(false)` first.+ */+export class ScalingLockedError extends Error {+ readonly code = "scaling_locked";+ constructor(message?: string) {+ super(message ?? "scaling is locked on this sandbox");+ this.name = "ScalingLockedError";+ }+}++/**+ * Thrown by `scale` and `setAutoscale` when the requested size exceeds the+ * organization's plan cap (e.g. free tier blocks > 4 GB). The HTTP layer+ * returns 402 Payment Required for this case.+ */+export class PlanLimitError extends Error {+ constructor(message?: string) {+ super(message ?? "plan limit exceeded for requested resources");+ this.name = "PlanLimitError";+ }+}++/**+ * Inspect a non-OK response from a scaling endpoint and throw the most+ * specific error type. Falls back to a generic Error when the response+ * doesn't match a known shape so callers still see the status + body.+ */+async function throwScalingError(resp: Response, action: string): Promise<never> {+ const text = await resp.text();+ let body: { error?: string; code?: string } = {};+ try {+ body = JSON.parse(text);+ } catch {+ // Non-JSON body — fall through to generic Error below.+ }+ if (resp.status === 403 && body.code === "scaling_locked") {+ throw new ScalingLockedError(body.error);+ }+ if (resp.status === 402) {+ throw new PlanLimitError(body.error);+ }+ throw new Error(`Failed to ${action}: ${resp.status} ${text}`);+}++export interface ScaleResult {+ sandboxID: string;+ memoryMB: number;+ cpuPercent: number;+}++export interface AutoscaleConfig {+ enabled: boolean;+ /** Minimum tier the autoscaler will shrink to. Must be an allowed memory tier (1024, 4096, 8192, 16384, 32768, 65536). */+ minMemoryMB?: number;+ /** Maximum tier the autoscaler will grow to. Must be an allowed memory tier and ≥ minMemoryMB. */+ maxMemoryMB?: number;+}++export interface AutoscaleStatus {+ sandboxID: string;+ enabled: boolean;+ minMemoryMB: number;+ maxMemoryMB: number;+}++export interface ScalingLockStatus {+ sandboxID: string;+ locked: boolean;+}++/**+ * Result of `sandbox.getAllowedHosts()`. Describes the egress-allowlist that+ * a sandbox's secrets proxy enforces.+ *+ * - `egressAllowlist` is the cluster-wide list of hosts the sandbox can+ * reach via the secrets proxy. Comes from the secret store the sandbox+ * was created with.+ * - `perSecretAllowedHosts` is an optional finer restriction per individual+ * secret. When the sandbox uses one of these secrets in a request, only+ * the listed hosts are reachable for that request.+ * - `secretStore` is the name of the store the sandbox is bound to. Empty+ * when the sandbox was created without a `secretStore` option.+ */+export interface AllowedHostsInfo {+ sandboxID: string;+ secretStore?: string;+ egressAllowlist: string[];+ perSecretAllowedHosts: Record<string, string[]>;+}+export class Sandbox {readonly sandboxId: string;readonly agent: Agent;@@ -277,6 +371,197 @@ export class Sandbox {(this as any).pty = new Pty(this.apiUrl, this.apiKey, this.sandboxId, "");}+ /**+ * Soft restart of the running sandbox. The guest CPU is reset and the+ * kernel reboots — equivalent to running `reboot` inside the box. The+ * QEMU process, network mapping, and persistent disks all stay; only+ * in-memory state (running processes, page caches) is wiped.+ *+ * Use to recover from in-guest wedges: zombie pile-ups, OOM-killed+ * agents, runaway processes, broken-but-isolated systemd state.+ *+ * For the rare case where the VMM itself is wedged (e.g. QMP+ * unresponsive), use `powerCycle()` instead.+ */+ async reboot(): Promise<void> {+ const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/reboot`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ ...(this.apiKey ? { "X-API-Key": this.apiKey } : {}),+ },+ });++ if (!resp.ok) {+ const text = await resp.text();+ throw new Error(`Failed to reboot sandbox: ${resp.status} ${text}`);+ }+ }++ /**+ * Hard restart of the sandbox. The QEMU process is killed and a fresh+ * one is started with the same on-disk drives. Sandbox keeps its ID,+ * project, secrets, env, and persistent workspace data; gets a new+ * external host port and TAP. Use when the VMM itself is wedged or a+ * `reboot()` doesn't recover.+ */+ async powerCycle(): Promise<void> {+ const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/power-cycle`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ ...(this.apiKey ? { "X-API-Key": this.apiKey } : {}),+ },+ });++ if (!resp.ok) {+ const text = await resp.text();+ throw new Error(`Failed to power-cycle sandbox: ${resp.status} ${text}`);+ }+ }++ /**+ * Manually resize the sandbox to a specific memory tier. CPU is bundled+ * with memory per the platform's tier table (e.g. 8 GB → 4 vCPU). Allowed+ * tiers: 1024, 4096, 8192, 16384, 32768, 65536 MB.+ *+ * Side effect: a manual scale disables autoscale on this sandbox. If you+ * want size to track load again, call `setAutoscale({ enabled: true, ... })`+ * after.+ *+ * Throws `ScalingLockedError` if the sandbox has a scaling lock; throws+ * `PlanLimitError` if the requested size exceeds your plan cap.+ *+ * [HTTP API →](/api-reference/sandboxes/scale)+ */+ async scale(opts: { memoryMB: number }): Promise<ScaleResult> {+ const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/scale`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ ...(this.apiKey ? { "X-API-Key": this.apiKey } : {}),+ },+ body: JSON.stringify({ memoryMB: opts.memoryMB }),+ });++ if (!resp.ok) {+ await throwScalingError(resp, "scale sandbox");+ }++ return resp.json();+ }++ /**+ * Enable or disable per-sandbox autoscale. When enabled, the platform+ * resizes the sandbox between `minMemoryMB` and `maxMemoryMB` based on+ * observed memory pressure — scaling up fast on a 1-min spike, down+ * slowly after sustained idle.+ *+ * Both bounds must be allowed memory tiers (1024, 4096, 8192, 16384,+ * 32768, 65536). Pass `enabled: false` to turn autoscale off (bounds+ * are ignored in that case).+ *+ * Throws `ScalingLockedError` if the sandbox has a scaling lock; throws+ * `PlanLimitError` if `maxMemoryMB` exceeds your plan cap.+ */+ async setAutoscale(opts: AutoscaleConfig): Promise<AutoscaleStatus> {+ const body: Record<string, unknown> = { enabled: opts.enabled };+ if (opts.minMemoryMB != null) body.minMemoryMB = opts.minMemoryMB;+ if (opts.maxMemoryMB != null) body.maxMemoryMB = opts.maxMemoryMB;++ const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/autoscale`, {+ method: "PUT",+ headers: {+ "Content-Type": "application/json",+ ...(this.apiKey ? { "X-API-Key": this.apiKey } : {}),+ },+ body: JSON.stringify(body),+ });++ if (!resp.ok) {+ await throwScalingError(resp, "set autoscale");+ }++ return resp.json();+ }++ /**+ * Get the current autoscale configuration for the sandbox.+ */+ async getAutoscale(): Promise<AutoscaleStatus> {+ const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/autoscale`, {+ headers: this.apiKey ? { "X-API-Key": this.apiKey } : {},+ });+ if (!resp.ok) {+ const text = await resp.text();+ throw new Error(`Failed to get autoscale: ${resp.status} ${text}`);+ }+ return resp.json();+ }++ /**+ * Lock or unlock the sandbox's resources against scaling. When locked:+ *+ * - `scale()` rejects with `ScalingLockedError`.+ * - `setAutoscale({ enabled: true })` rejects with `ScalingLockedError`.+ * - The platform autoscaler skips this sandbox entirely.+ *+ * Locking ALSO disables autoscale as a side effect (single-knob+ * semantics — "I don't want this scaling, period"). Unlocking does NOT+ * re-enable autoscale; call `setAutoscale({ enabled: true, ... })`+ * explicitly if you want it back.+ */+ async setScalingLock(locked: boolean): Promise<ScalingLockStatus> {+ const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/scaling-lock`, {+ method: "PUT",+ headers: {+ "Content-Type": "application/json",+ ...(this.apiKey ? { "X-API-Key": this.apiKey } : {}),+ },+ body: JSON.stringify({ locked }),+ });+ if (!resp.ok) {+ const text = await resp.text();+ throw new Error(`Failed to set scaling lock: ${resp.status} ${text}`);+ }+ return resp.json();+ }++ /**+ * Get the current scaling-lock state for the sandbox.+ */+ async getScalingLock(): Promise<ScalingLockStatus> {+ const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/scaling-lock`, {+ headers: this.apiKey ? { "X-API-Key": this.apiKey } : {},+ });+ if (!resp.ok) {+ const text = await resp.text();+ throw new Error(`Failed to get scaling lock: ${resp.status} ${text}`);+ }+ return resp.json();+ }++ /**+ * Get the egress-allowlist + per-secret allowed hosts the sandbox's+ * secrets proxy enforces. Useful for debugging "why is my outbound HTTP+ * call being blocked" without having to cross-reference the secret store+ * config separately.+ *+ * Sandboxes created without a `secretStore` option return an empty+ * allowlist and `secretStore` is undefined — the sandbox has no+ * per-store egress restriction.+ */+ async getAllowedHosts(): Promise<AllowedHostsInfo> {+ const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/allowed-hosts`, {+ headers: this.apiKey ? { "X-API-Key": this.apiKey } : {},+ });+ if (!resp.ok) {+ const text = await resp.text();+ throw new Error(`Failed to get allowed hosts: ${resp.status} ${text}`);+ }+ return resp.json();+ }+async setTimeout(timeout: number): Promise<void> {const headers: Record<string, string> = { "Content-Type": "application/json" };if (this.apiKey) {diff --git a/tests/manual/README.md b/tests/manual/README.mdnew file mode 100644index 00000000..eb3b8daa--- /dev/null+++ b/tests/manual/README.md@@ -0,0 +1,62 @@+# Manual integration tests++End-to-end verification scripts that need a deployed environment, real+sandboxes, and DB access. Not runnable in CI — they require the live+control plane + worker + Postgres on a target VM and an SSH key into+that VM.++Each script exits non-zero on failure so you can chain it into ad-hoc+deploy-verify pipelines if you want.++## Conventions++- Each script self-cleans on EXIT (via `trap`). It will best-effort+ destroy any sandboxes, secret stores, or other resources it created+ even on failure.+- All required env vars are checked up front and the script exits 2+ with a clear message if anything is missing.+- Scripts MUST use placeholder hosts (`example.com`, `httpbin.org`)+ rather than real customer or production endpoints.+- Output is colour-coded: yellow = section header, green = PASS,+ red = FAIL.++## Scripts++### `verify-billing-and-proxy-fixes.sh`++Verifies two related fixes that ship together:++1. **Bug A — billing scale event on fork** (`fix/worker-record-scale-event-on-fork`):+ forks-from-checkpoint must produce a `sandbox_scale_events` row so the+ usage-reporter can see them and credit/billable_events flow.++2. **Bug B — allowlist-only secret store** (`fix/secret-proxy-allowlist-only-stores`):+ a secret store carrying only an egress allowlist (no secret entries)+ must register a proxy session and enforce the allowlist (allowed host+ passes, disallowed host gets 403). Pre-fix both got `407 no_session`.++Required env:++```+OPENCOMPUTER_API_URL e.g. http://10.0.0.5:8080+OPENCOMPUTER_API_KEY e.g. opensandbox-dev+DEV_VM public IP of the dev VM+DEV_KEY path to SSH private key for the VM+```++Optional env (defaults shown):++```+DEV_USER=ubuntu+PG_USER=opensandbox+PG_DB=opensandbox+PG_PASS=opensandbox+OC=oc+```++Run:++```bash+chmod +x tests/manual/verify-billing-and-proxy-fixes.sh+tests/manual/verify-billing-and-proxy-fixes.sh+```diff --git a/tests/manual/verify-billing-and-proxy-fixes.sh b/tests/manual/verify-billing-and-proxy-fixes.shnew file mode 100755index 00000000..bb791757--- /dev/null+++ b/tests/manual/verify-billing-and-proxy-fixes.sh@@ -0,0 +1,256 @@+#!/usr/bin/env bash+# Verifies the two billing/proxy fixes deployed on a single-host dev VM.+#+# Required env (export before running):+# OPENCOMPUTER_API_URL — dev API URL, e.g. http://20.101.100.215:8080+# OPENCOMPUTER_API_KEY — dev API key, e.g. opensandbox-dev+# DEV_VM — public IP of the dev VM, e.g. 20.101.100.215+# DEV_KEY — path to SSH private key for the VM+#+# Optional env (with defaults shown):+# DEV_USER=ubuntu+# PG_USER=opensandbox+# PG_DB=opensandbox+# PG_PASS=opensandbox+# OC=oc — path to the oc binary if not on PATH+#+# Exit code 0 = both PASS. Non-zero on any failure.+#+# Tests:+# A) Scale event recorded on fork-from-checkpoint (worker grpc fix)+# B) Allowlist-only secret store registers a proxy session and enforces+# the allowlist (secrets-proxy + qemu fix)++set -euo pipefail++DEV_USER=${DEV_USER:-ubuntu}+PG_USER=${PG_USER:-opensandbox}+PG_DB=${PG_DB:-opensandbox}+PG_PASS=${PG_PASS:-opensandbox}+OC=${OC:-oc}++red() { printf '\033[31m%s\033[0m\n' "$*"; }+green() { printf '\033[32m%s\033[0m\n' "$*"; }+yellow(){ printf '\033[33m%s\033[0m\n' "$*"; }+hr() { printf '%s\n' '────────────────────────────────────────────────────────────'; }++require() {+ local name=$1+ if [ -z "${!name:-}" ]; then+ red "missing required env: $name"+ exit 2+ fi+}++require OPENCOMPUTER_API_URL+require OPENCOMPUTER_API_KEY+require DEV_VM+require DEV_KEY++if ! command -v "$OC" >/dev/null 2>&1; then+ red "oc binary not found on PATH (set OC=/path/to/oc to override)"+ exit 2+fi+if [ ! -r "$DEV_KEY" ]; then+ red "DEV_KEY not readable: $DEV_KEY"+ exit 2+fi++ssh_dev() {+ ssh -i "$DEV_KEY" \+ -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null \+ -o ConnectTimeout=10 -o LogLevel=ERROR \+ "${DEV_USER}@${DEV_VM}" "$@"+}++psql_dev() {+ ssh_dev "PGPASSWORD=${PG_PASS} psql -h localhost -U ${PG_USER} -d ${PG_DB} -t -A -c \"$1\""+}++# Quick reachability checks+hr; yellow "Pre-flight checks"+ssh_dev 'echo VM reachable && systemctl is-active opensandbox-worker && systemctl is-active opensandbox-server' \+ || { red "ssh / services check failed"; exit 2; }+$OC sandbox list >/dev/null \+ || { red "oc API check failed (OPENCOMPUTER_API_URL=$OPENCOMPUTER_API_URL)"; exit 2; }+green "OK"++# State for cleanup+CREATED_SBS=()+CREATED_CHECKPOINTS=()+CREATED_STORES=()++cleanup() {+ hr; yellow "Cleanup"+ for sb in "${CREATED_SBS[@]:-}"; do+ [ -n "$sb" ] && $OC sandbox kill "$sb" 2>/dev/null || true+ done+ # NOTE: checkpoints are tied to source sandbox; killed source cleans up its own+ # checkpoints? If not, they'll remain in DB but stop being usable.+ for store in "${CREATED_STORES[@]:-}"; do+ [ -n "$store" ] && $OC secret-store delete "$store" 2>/dev/null || true+ done+ green "Cleanup done"+}+trap cleanup EXIT++# Helper: parse `Created sandbox sb-XXXXX (status: ...)` style output for the ID+extract_sb_id() {+ grep -oE 'sb-[a-f0-9]+' | head -1+}+extract_store_id() {+ grep -oE '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}' | head -1+}++############################################+# Test A — scale event recorded on fork+############################################+TEST_A_PASS=0+hr; yellow "Test A — scale event recorded on fork-from-checkpoint"++# Snapshot global count for sanity (not used as assertion)+PRE_TOTAL=$(psql_dev "SELECT COUNT(*) FROM sandbox_scale_events;" | tr -d ' ')+echo " baseline sandbox_scale_events row count: $PRE_TOTAL"++# 1. Source sandbox+echo " creating source sandbox..."+SRC_OUT=$($OC sandbox create --memory 1024 --cpu 1 --timeout 600 2>&1)+SRC=$(echo "$SRC_OUT" | extract_sb_id)+if [ -z "$SRC" ]; then+ red " could not extract source sandbox id from: $SRC_OUT"+ exit 1+fi+CREATED_SBS+=("$SRC")+echo " source sandbox: $SRC"++# Wait briefly for it to settle+sleep 3++# 2. Checkpoint+echo " creating checkpoint..."+CK_OUT=$($OC checkpoint create "$SRC" --name verify-fork-test 2>&1)+CK_ID=$(echo "$CK_OUT" | grep -oE '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}' | head -1)+if [ -z "$CK_ID" ]; then+ red " could not extract checkpoint id from: $CK_OUT"+ exit 1+fi+CREATED_CHECKPOINTS+=("$CK_ID")+echo " checkpoint: $CK_ID"++# Wait for checkpoint to be 'ready'+echo " waiting for checkpoint to be ready..."+for i in $(seq 1 30); do+ STATUS=$(psql_dev "SELECT status FROM sandbox_checkpoints WHERE id='$CK_ID';" | tr -d ' ')+ [ "$STATUS" = "ready" ] && break+ sleep 2+done+if [ "$STATUS" != "ready" ]; then+ red " checkpoint did not become ready (last status: $STATUS)"+ exit 1+fi++# 3. Spawn fork from checkpoint+echo " spawning fork from checkpoint..."+FORK_OUT=$($OC checkpoint spawn "$CK_ID" --timeout 300 2>&1)+FORK=$(echo "$FORK_OUT" | extract_sb_id)+if [ -z "$FORK" ]; then+ red " could not extract fork sandbox id from: $FORK_OUT"+ exit 1+fi+CREATED_SBS+=("$FORK")+echo " fork: $FORK"++# 4. Assert: scale_event row exists for the fork (this is the bug being fixed)+sleep 2+FORK_ROW=$(psql_dev "SELECT sandbox_id||'|'||memory_mb||'|'||cpu_percent||'|'||disk_mb FROM sandbox_scale_events WHERE sandbox_id='$FORK';" | tr -d ' ')+if [ -z "$FORK_ROW" ]; then+ red " FAIL: no sandbox_scale_events row for fork $FORK"+ echo " query: SELECT * FROM sandbox_scale_events WHERE sandbox_id='$FORK';"+else+ green " PASS: scale_event row present → $FORK_ROW"+ TEST_A_PASS=1+fi++############################################+# Test B — allowlist-only proxy session+############################################+TEST_B_PASS=0+hr; yellow "Test B — allowlist-only secret store registers proxy session"++# 1. Allowlist-only store+echo " creating allowlist-only secret store..."+STORE_OUT=$($OC secret-store create --name "allowlist-verify-$$" \+ --egress-allowlist example.com,httpbin.org 2>&1)+STORE_ID=$(echo "$STORE_OUT" | extract_store_id)+if [ -z "$STORE_ID" ]; then+ red " could not extract store id from: $STORE_OUT"+ exit 1+fi+CREATED_STORES+=("$STORE_ID")+echo " store: $STORE_ID"++# 2. Sandbox using that store. --env required so HTTP_PROXY actually gets injected+# (mirrors the real openclaw failure conditions).+echo " creating sandbox with allowlist-only store + dummy env..."+ALLOW_OUT=$($OC sandbox create --secret-store "allowlist-verify-$$" \+ --memory 1024 --cpu 1 --env DUMMY=1 --timeout 300 2>&1)+ALLOW=$(echo "$ALLOW_OUT" | extract_sb_id)+if [ -z "$ALLOW" ]; then+ red " could not extract sandbox id from: $ALLOW_OUT"+ exit 1+fi+CREATED_SBS+=("$ALLOW")+echo " sandbox: $ALLOW"++# Wait for sandbox to be ready for exec+sleep 4++# 3. Allowed host → expect HTTP 200+# 4. Disallowed host → expect 403 from proxy+# Wrap in set +e so a non-zero exit from oc-exec / curl doesn't trip set -e+# and abort the script before we can read the HTTP status.+set +e+echo " curl https://example.com/ (allowed) ..."+ALLOWED_HTTP=$($OC exec "$ALLOW" -- curl -s -o /dev/null -w '%{http_code}' \+ --max-time 10 https://example.com/ 2>/dev/null | tr -d '[:space:]' | tail -c 4)+echo " HTTP ${ALLOWED_HTTP:-<none>}"++echo " curl https://www.google.com/ (NOT allowed) ..."+DENIED_HTTP=$($OC exec "$ALLOW" -- curl -s -o /dev/null -w '%{http_code}' \+ --max-time 10 https://www.google.com/ 2>/dev/null | tr -d '[:space:]' | tail -c 4)+echo " HTTP ${DENIED_HTTP:-<none>}"+set -e++# 5. Cross-check worker logs: should see action=connect for example.com,+# action=blocked reason=allowlist for google.com.+echo " recent secrets-proxy audit lines:"+ssh_dev "sudo journalctl -u opensandbox-worker --since '2 minutes ago' --no-pager 2>/dev/null \+ | grep 'secrets-proxy: audit' | tail -8" || true++# Pass conditions:+# - Allowed host returned 200 (proxy session exists + allowlist permits)+# - Disallowed host returned 403 (proxy session exists + allowlist blocks)+# Failure mode pre-fix would be 407 on BOTH.+if [ "$ALLOWED_HTTP" = "200" ] && [ "$DENIED_HTTP" = "403" ]; then+ green " PASS: allowed=200, denied=403 → session registered + allowlist enforced"+ TEST_B_PASS=1+elif [ "$ALLOWED_HTTP" = "407" ]; then+ red " FAIL: got 407 — the fix is not active (no session registered for allowlist-only store)"+elif [ "$ALLOWED_HTTP" = "200" ] && [ "$DENIED_HTTP" = "200" ]; then+ red " FAIL: both allowed AND denied returned 200 — proxy is being bypassed entirely"+else+ red " FAIL: unexpected combination allowed=$ALLOWED_HTTP denied=$DENIED_HTTP"+fi++############################################+# Summary+############################################+hr; yellow "Summary"+[ "$TEST_A_PASS" = 1 ] && green " A) scale-event-on-fork: PASS" || red " A) scale-event-on-fork: FAIL"+[ "$TEST_B_PASS" = 1 ] && green " B) allowlist-only proxy: PASS" || red " B) allowlist-only proxy: FAIL"+hr++if [ "$TEST_A_PASS" = 1 ] && [ "$TEST_B_PASS" = 1 ]; then+ exit 0+fi+exit 1diff --git a/web/package-lock.json b/web/package-lock.jsonindex 1b3b2744..c24917d9 100644--- a/web/package-lock.json+++ b/web/package-lock.json@@ -8,10 +8,12 @@"name": "opensandbox-dashboard","version": "0.1.0","dependencies": {+ "@posthog/react": "^1.9.0","@tanstack/react-query": "^5.60.0","@xterm/addon-fit": "^0.11.0","@xterm/addon-web-links": "^0.12.0","@xterm/xterm": "^6.0.0",+ "posthog-js": "^1.372.0","react": "^18.3.1","react-dom": "^18.3.1","react-router-dom": "^6.28.0",@@ -56,6 +58,7 @@"integrity": "sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA==","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"@babel/code-frame": "^7.29.0","@babel/generator": "^7.29.0",@@ -799,6 +802,348 @@"@jridgewell/sourcemap-codec": "^1.4.14"}},+ "node_modules/@opentelemetry/api": {+ "version": "1.9.1",+ "resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.9.1.tgz",+ "integrity": "sha512-gLyJlPHPZYdAk1JENA9LeHejZe1Ti77/pTeFm/nMXmQH/HFZlcS/O2XJB+L8fkbrNSqhdtlvjBVjxwUYanNH5Q==",+ "license": "Apache-2.0",+ "peer": true,+ "engines": {+ "node": ">=8.0.0"+ }+ },+ "node_modules/@opentelemetry/api-logs": {+ "version": "0.208.0",+ "resolved": "https://registry.npmjs.org/@opentelemetry/api-logs/-/api-logs-0.208.0.tgz",+ "integrity": "sha512-CjruKY9V6NMssL/T1kAFgzosF1v9o6oeN+aX5JB/C/xPNtmgIJqcXHG7fA82Ou1zCpWGl4lROQUKwUNE1pMCyg==",+ "license": "Apache-2.0",+ "dependencies": {+ "@opentelemetry/api": "^1.3.0"+ },+ "engines": {+ "node": ">=8.0.0"+ }+ },+ "node_modules/@opentelemetry/core": {+ "version": "2.2.0",+ "resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-2.2.0.tgz",+ "integrity": "sha512-FuabnnUm8LflnieVxs6eP7Z383hgQU4W1e3KJS6aOG3RxWxcHyBxH8fDMHNgu/gFx/M2jvTOW/4/PHhLz6bjWw==",+ "license": "Apache-2.0",+ "dependencies": {+ "@opentelemetry/semantic-conventions": "^1.29.0"+ },+ "engines": {+ "node": "^18.19.0 || >=20.6.0"+ },+ "peerDependencies": {+ "@opentelemetry/api": ">=1.0.0 <1.10.0"+ }+ },+ "node_modules/@opentelemetry/exporter-logs-otlp-http": {+ "version": "0.208.0",+ "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-logs-otlp-http/-/exporter-logs-otlp-http-0.208.0.tgz",+ "integrity": "sha512-jOv40Bs9jy9bZVLo/i8FwUiuCvbjWDI+ZW13wimJm4LjnlwJxGgB+N/VWOZUTpM+ah/awXeQqKdNlpLf2EjvYg==",+ "license": "Apache-2.0",+ "dependencies": {+ "@opentelemetry/api-logs": "0.208.0",+ "@opentelemetry/core": "2.2.0",+ "@opentelemetry/otlp-exporter-base": "0.208.0",+ "@opentelemetry/otlp-transformer": "0.208.0",+ "@opentelemetry/sdk-logs": "0.208.0"+ },+ "engines": {+ "node": "^18.19.0 || >=20.6.0"+ },+ "peerDependencies": {+ "@opentelemetry/api": "^1.3.0"+ }+ },+ "node_modules/@opentelemetry/otlp-exporter-base": {+ "version": "0.208.0",+ "resolved": "https://registry.npmjs.org/@opentelemetry/otlp-exporter-base/-/otlp-exporter-base-0.208.0.tgz",+ "integrity": "sha512-gMd39gIfVb2OgxldxUtOwGJYSH8P1kVFFlJLuut32L6KgUC4gl1dMhn+YC2mGn0bDOiQYSk/uHOdSjuKp58vvA==",+ "license": "Apache-2.0",+ "dependencies": {+ "@opentelemetry/core": "2.2.0",+ "@opentelemetry/otlp-transformer": "0.208.0"+ },+ "engines": {+ "node": "^18.19.0 || >=20.6.0"+ },+ "peerDependencies": {+ "@opentelemetry/api": "^1.3.0"+ }+ },+ "node_modules/@opentelemetry/otlp-transformer": {+ "version": "0.208.0",+ "resolved": "https://registry.npmjs.org/@opentelemetry/otlp-transformer/-/otlp-transformer-0.208.0.tgz",+ "integrity": "sha512-DCFPY8C6lAQHUNkzcNT9R+qYExvsk6C5Bto2pbNxgicpcSWbe2WHShLxkOxIdNcBiYPdVHv/e7vH7K6TI+C+fQ==",+ "license": "Apache-2.0",+ "dependencies": {+ "@opentelemetry/api-logs": "0.208.0",+ "@opentelemetry/core": "2.2.0",+ "@opentelemetry/resources": "2.2.0",+ "@opentelemetry/sdk-logs": "0.208.0",+ "@opentelemetry/sdk-metrics": "2.2.0",+ "@opentelemetry/sdk-trace-base": "2.2.0",+ "protobufjs": "^7.3.0"+ },+ "engines": {+ "node": "^18.19.0 || >=20.6.0"+ },+ "peerDependencies": {+ "@opentelemetry/api": "^1.3.0"+ }+ },+ "node_modules/@opentelemetry/otlp-transformer/node_modules/@opentelemetry/resources": {+ "version": "2.2.0",+ "resolved": "https://registry.npmjs.org/@opentelemetry/resources/-/resources-2.2.0.tgz",+ "integrity": "sha512-1pNQf/JazQTMA0BiO5NINUzH0cbLbbl7mntLa4aJNmCCXSj0q03T5ZXXL0zw4G55TjdL9Tz32cznGClf+8zr5A==",+ "license": "Apache-2.0",+ "dependencies": {+ "@opentelemetry/core": "2.2.0",+ "@opentelemetry/semantic-conventions": "^1.29.0"+ },+ "engines": {+ "node": "^18.19.0 || >=20.6.0"+ },+ "peerDependencies": {+ "@opentelemetry/api": ">=1.3.0 <1.10.0"+ }+ },+ "node_modules/@opentelemetry/resources": {+ "version": "2.7.1",+ "resolved": "https://registry.npmjs.org/@opentelemetry/resources/-/resources-2.7.1.tgz",+ "integrity": "sha512-DeT6KKolmC4e/dRQvMQ/RwlnzhaqeiFOXY5ngoOPJ07GgVVKxZOg9EcrNZb5aTzUn+iCrJldAgOfQm1O/QfPAQ==",+ "license": "Apache-2.0",+ "dependencies": {+ "@opentelemetry/core": "2.7.1",+ "@opentelemetry/semantic-conventions": "^1.29.0"+ },+ "engines": {+ "node": "^18.19.0 || >=20.6.0"+ },+ "peerDependencies": {+ "@opentelemetry/api": ">=1.3.0 <1.10.0"+ }+ },+ "node_modules/@opentelemetry/resources/node_modules/@opentelemetry/core": {+ "version": "2.7.1",+ "resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-2.7.1.tgz",+ "integrity": "sha512-QAqIj32AtK6+pEVNG7EOVxHdE06RP+FM5qpiEJ4RtDcFIqKUZHYhl7/7UY5efhwmwNAg7j8QbJVBLxMerc0+gw==",+ "license": "Apache-2.0",+ "dependencies": {+ "@opentelemetry/semantic-conventions": "^1.29.0"+ },+ "engines": {+ "node": "^18.19.0 || >=20.6.0"+ },+ "peerDependencies": {+ "@opentelemetry/api": ">=1.0.0 <1.10.0"+ }+ },+ "node_modules/@opentelemetry/sdk-logs": {+ "version": "0.208.0",+ "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-logs/-/sdk-logs-0.208.0.tgz",+ "integrity": "sha512-QlAyL1jRpOeaqx7/leG1vJMp84g0xKP6gJmfELBpnI4O/9xPX+Hu5m1POk9Kl+veNkyth5t19hRlN6tNY1sjbA==",+ "license": "Apache-2.0",+ "dependencies": {+ "@opentelemetry/api-logs": "0.208.0",+ "@opentelemetry/core": "2.2.0",+ "@opentelemetry/resources": "2.2.0"+ },+ "engines": {+ "node": "^18.19.0 || >=20.6.0"+ },+ "peerDependencies": {+ "@opentelemetry/api": ">=1.4.0 <1.10.0"+ }+ },+ "node_modules/@opentelemetry/sdk-logs/node_modules/@opentelemetry/resources": {+ "version": "2.2.0",+ "resolved": "https://registry.npmjs.org/@opentelemetry/resources/-/resources-2.2.0.tgz",+ "integrity": "sha512-1pNQf/JazQTMA0BiO5NINUzH0cbLbbl7mntLa4aJNmCCXSj0q03T5ZXXL0zw4G55TjdL9Tz32cznGClf+8zr5A==",+ "license": "Apache-2.0",+ "dependencies": {+ "@opentelemetry/core": "2.2.0",+ "@opentelemetry/semantic-conventions": "^1.29.0"+ },+ "engines": {+ "node": "^18.19.0 || >=20.6.0"+ },+ "peerDependencies": {+ "@opentelemetry/api": ">=1.3.0 <1.10.0"+ }+ },+ "node_modules/@opentelemetry/sdk-metrics": {+ "version": "2.2.0",+ "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-metrics/-/sdk-metrics-2.2.0.tgz",+ "integrity": "sha512-G5KYP6+VJMZzpGipQw7Giif48h6SGQ2PFKEYCybeXJsOCB4fp8azqMAAzE5lnnHK3ZVwYQrgmFbsUJO/zOnwGw==",+ "license": "Apache-2.0",+ "dependencies": {+ "@opentelemetry/core": "2.2.0",+ "@opentelemetry/resources": "2.2.0"+ },+ "engines": {+ "node": "^18.19.0 || >=20.6.0"+ },+ "peerDependencies": {+ "@opentelemetry/api": ">=1.9.0 <1.10.0"+ }+ },+ "node_modules/@opentelemetry/sdk-metrics/node_modules/@opentelemetry/resources": {+ "version": "2.2.0",+ "resolved": "https://registry.npmjs.org/@opentelemetry/resources/-/resources-2.2.0.tgz",+ "integrity": "sha512-1pNQf/JazQTMA0BiO5NINUzH0cbLbbl7mntLa4aJNmCCXSj0q03T5ZXXL0zw4G55TjdL9Tz32cznGClf+8zr5A==",+ "license": "Apache-2.0",+ "dependencies": {+ "@opentelemetry/core": "2.2.0",+ "@opentelemetry/semantic-conventions": "^1.29.0"+ },+ "engines": {+ "node": "^18.19.0 || >=20.6.0"+ },+ "peerDependencies": {+ "@opentelemetry/api": ">=1.3.0 <1.10.0"+ }+ },+ "node_modules/@opentelemetry/sdk-trace-base": {+ "version": "2.2.0",+ "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-trace-base/-/sdk-trace-base-2.2.0.tgz",+ "integrity": "sha512-xWQgL0Bmctsalg6PaXExmzdedSp3gyKV8mQBwK/j9VGdCDu2fmXIb2gAehBKbkXCpJ4HPkgv3QfoJWRT4dHWbw==",+ "license": "Apache-2.0",+ "dependencies": {+ "@opentelemetry/core": "2.2.0",+ "@opentelemetry/resources": "2.2.0",+ "@opentelemetry/semantic-conventions": "^1.29.0"+ },+ "engines": {+ "node": "^18.19.0 || >=20.6.0"+ },+ "peerDependencies": {+ "@opentelemetry/api": ">=1.3.0 <1.10.0"+ }+ },+ "node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/resources": {+ "version": "2.2.0",+ "resolved": "https://registry.npmjs.org/@opentelemetry/resources/-/resources-2.2.0.tgz",+ "integrity": "sha512-1pNQf/JazQTMA0BiO5NINUzH0cbLbbl7mntLa4aJNmCCXSj0q03T5ZXXL0zw4G55TjdL9Tz32cznGClf+8zr5A==",+ "license": "Apache-2.0",+ "dependencies": {+ "@opentelemetry/core": "2.2.0",+ "@opentelemetry/semantic-conventions": "^1.29.0"+ },+ "engines": {+ "node": "^18.19.0 || >=20.6.0"+ },+ "peerDependencies": {+ "@opentelemetry/api": ">=1.3.0 <1.10.0"+ }+ },+ "node_modules/@opentelemetry/semantic-conventions": {+ "version": "1.40.0",+ "resolved": "https://registry.npmjs.org/@opentelemetry/semantic-conventions/-/semantic-conventions-1.40.0.tgz",+ "integrity": "sha512-cifvXDhcqMwwTlTK04GBNeIe7yyo28Mfby85QXFe1Yk8nmi36Ab/5UQwptOx84SsoGNRg+EVSjwzfSZMy6pmlw==",+ "license": "Apache-2.0",+ "engines": {+ "node": ">=14"+ }+ },+ "node_modules/@posthog/core": {+ "version": "1.28.2",+ "resolved": "https://registry.npmjs.org/@posthog/core/-/core-1.28.2.tgz",+ "integrity": "sha512-Dii3pxDheG1WioztvV/MqHQMnb16jSFrl2HkDR1T5yf5/R7lPqJCFYt+eXkEdp/oAv/PD+1joyG6Ap/2quFmtQ==",+ "license": "MIT",+ "dependencies": {+ "@posthog/types": "1.372.8"+ }+ },+ "node_modules/@posthog/react": {+ "version": "1.9.0",+ "resolved": "https://registry.npmjs.org/@posthog/react/-/react-1.9.0.tgz",+ "integrity": "sha512-lVdTsWT5+PtHBu44gSQ7QohbLjAYqHkFAIGAQ+HV8Eh9yj+OcnQ7mXCmyhaMlTBD3z7D0H1eWMp4vQaFnsIyWQ==",+ "license": "MIT",+ "peerDependencies": {+ "@types/react": ">=16.8.0",+ "posthog-js": ">=1.257.2",+ "react": ">=16.8.0"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/@posthog/types": {+ "version": "1.372.8",+ "resolved": "https://registry.npmjs.org/@posthog/types/-/types-1.372.8.tgz",+ "integrity": "sha512-ALpfCnWsMSM9Cw/6kyLPVpd81ZReEdZwmDxOi+DTJuIo7wDxBiu2cAsjOuA6D/AL22v7HOJrHsmBAPAWqS5X7Q==",+ "license": "MIT"+ },+ "node_modules/@protobufjs/aspromise": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/@protobufjs/aspromise/-/aspromise-1.1.2.tgz",+ "integrity": "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==",+ "license": "BSD-3-Clause"+ },+ "node_modules/@protobufjs/base64": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/@protobufjs/base64/-/base64-1.1.2.tgz",+ "integrity": "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==",+ "license": "BSD-3-Clause"+ },+ "node_modules/@protobufjs/codegen": {+ "version": "2.0.5",+ "resolved": "https://registry.npmjs.org/@protobufjs/codegen/-/codegen-2.0.5.tgz",+ "integrity": "sha512-zgXFLzW3Ap33e6d0Wlj4MGIm6Ce8O89n/apUaGNB/jx+hw+ruWEp7EwGUshdLKVRCxZW12fp9r40E1mQrf/34g==",+ "license": "BSD-3-Clause"+ },+ "node_modules/@protobufjs/eventemitter": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/@protobufjs/eventemitter/-/eventemitter-1.1.0.tgz",+ "integrity": "sha512-j9ednRT81vYJ9OfVuXG6ERSTdEL1xVsNgqpkxMsbIabzSo3goCjDIveeGv5d03om39ML71RdmrGNjG5SReBP/Q==",+ "license": "BSD-3-Clause"+ },+ "node_modules/@protobufjs/fetch": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/@protobufjs/fetch/-/fetch-1.1.0.tgz",+ "integrity": "sha512-lljVXpqXebpsijW71PZaCYeIcE5on1w5DlQy5WH6GLbFryLUrBD4932W/E2BSpfRJWseIL4v/KPgBFxDOIdKpQ==",+ "license": "BSD-3-Clause",+ "dependencies": {+ "@protobufjs/aspromise": "^1.1.1",+ "@protobufjs/inquire": "^1.1.0"+ }+ },+ "node_modules/@protobufjs/float": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/@protobufjs/float/-/float-1.0.2.tgz",+ "integrity": "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==",+ "license": "BSD-3-Clause"+ },+ "node_modules/@protobufjs/inquire": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/@protobufjs/inquire/-/inquire-1.1.1.tgz",+ "integrity": "sha512-mnzgDV26ueAvk7rsbt9L7bE0SuAoqyuys/sMMrmVcN5x9VsxpcG3rqAUSgDyLp0UZlmNfIbQ4fHfCtreVBk8Ew==",+ "license": "BSD-3-Clause"+ },+ "node_modules/@protobufjs/path": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/@protobufjs/path/-/path-1.1.2.tgz",+ "integrity": "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA==",+ "license": "BSD-3-Clause"+ },+ "node_modules/@protobufjs/pool": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/@protobufjs/pool/-/pool-1.1.0.tgz",+ "integrity": "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw==",+ "license": "BSD-3-Clause"+ },+ "node_modules/@protobufjs/utf8": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/@protobufjs/utf8/-/utf8-1.1.1.tgz",+ "integrity": "sha512-oOAWABowe8EAbMyWKM0tYDKi8Yaox52D+HWZhAIJqQXbqe0xI/GV7FhLWqlEKreMkfDjshR5FKgi3mnle0h6Eg==",+ "license": "BSD-3-Clause"+ },"node_modules/@reduxjs/toolkit": {"version": "2.11.2","resolved": "https://registry.npmjs.org/@reduxjs/toolkit/-/toolkit-2.11.2.tgz",@@ -1354,6 +1699,15 @@"dev": true,"license": "MIT"},+ "node_modules/@types/node": {+ "version": "25.6.0",+ "resolved": "https://registry.npmjs.org/@types/node/-/node-25.6.0.tgz",+ "integrity": "sha512-+qIYRKdNYJwY3vRCZMdJbPLJAtGjQBudzZzdzwQYkEPQd+PJGixUL5QfvCLDaULoLv+RhT3LDkwEfKaAkgSmNQ==",+ "license": "MIT",+ "dependencies": {+ "undici-types": "~7.19.0"+ }+ },"node_modules/@types/prop-types": {"version": "15.7.15","resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.15.tgz",@@ -1367,6 +1721,7 @@"integrity": "sha512-z9VXpC7MWrhfWipitjNdgCauoMLRdIILQsAEV+ZesIzBq/oUlxk0m3ApZuMFCXdnS4U7KrI+l3WRUEGQ8K1QKw==","devOptional": true,"license": "MIT",+ "peer": true,"dependencies": {"@types/prop-types": "*","csstype": "^3.2.2"@@ -1382,6 +1737,13 @@"@types/react": "^18.0.0"}},+ "node_modules/@types/trusted-types": {+ "version": "2.0.7",+ "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz",+ "integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==",+ "license": "MIT",+ "optional": true+ },"node_modules/@types/use-sync-external-store": {"version": "0.0.6","resolved": "https://registry.npmjs.org/@types/use-sync-external-store/-/use-sync-external-store-0.0.6.tgz",@@ -1460,6 +1822,7 @@}],"license": "MIT",+ "peer": true,"dependencies": {"baseline-browser-mapping": "^2.9.0","caniuse-lite": "^1.0.30001759",@@ -1511,6 +1874,17 @@"dev": true,"license": "MIT"},+ "node_modules/core-js": {+ "version": "3.49.0",+ "resolved": "https://registry.npmjs.org/core-js/-/core-js-3.49.0.tgz",+ "integrity": "sha512-es1U2+YTtzpwkxVLwAFdSpaIMyQaq0PBgm3YD1W3Qpsn1NAmO3KSgZfu+oGSWVu6NvLHoHCV/aYcsE5wiB7ALg==",+ "hasInstallScript": true,+ "license": "MIT",+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/core-js"+ }+ },"node_modules/csstype": {"version": "3.2.3","resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",@@ -1663,6 +2037,15 @@"integrity": "sha512-qIMFpTMZmny+MMIitAB6D7iVPEorVw6YQRWkvarTkT4tBeSLLiHzcwj6q0MmYSFCiVpiqPJTJEYIrpcPzVEIvg==","license": "MIT"},+ "node_modules/dompurify": {+ "version": "3.4.2",+ "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.2.tgz",+ "integrity": "sha512-lHeS9SA/IKeIFFyYciHBr2n0v1VMPlSj843HdLOwjb2OxNwdq9Xykxqhk+FE42MzAdHvInbAolSE4mhahPpjXA==",+ "license": "(MPL-2.0 OR Apache-2.0)",+ "optionalDependencies": {+ "@types/trusted-types": "^2.0.7"+ }+ },"node_modules/electron-to-chromium": {"version": "1.5.286","resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.286.tgz",@@ -1756,6 +2139,12 @@}}},+ "node_modules/fflate": {+ "version": "0.4.8",+ "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.4.8.tgz",+ "integrity": "sha512-FJqqoDBR00Mdj9ppamLa/Y7vxm+PRmNWA67N846RvsoYVMKB4q3y/de5PA7gUmRMYK/8CMz2GDZQmCRN1wBcWA==",+ "license": "MIT"+ },"node_modules/fsevents": {"version": "2.3.3","resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",@@ -1832,6 +2221,12 @@"node": ">=6"}},+ "node_modules/long": {+ "version": "5.3.2",+ "resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz",+ "integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==",+ "license": "Apache-2.0"+ },"node_modules/loose-envify": {"version": "1.4.0","resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",@@ -1900,6 +2295,7 @@"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==","dev": true,"license": "MIT",+ "peer": true,"engines": {"node": ">=12"},@@ -1936,11 +2332,74 @@"node": "^10 || ^12 || >=14"}},+ "node_modules/posthog-js": {+ "version": "1.372.8",+ "resolved": "https://registry.npmjs.org/posthog-js/-/posthog-js-1.372.8.tgz",+ "integrity": "sha512-NAFWVScFGnU5jgGNLkrY/UnGH82uULs9RsJ/f26LkLn1l0MOZfq+/z+2RaOOQQX4NHruIVuxqz3J/50bgRG68A==",+ "license": "SEE LICENSE IN LICENSE",+ "peer": true,+ "dependencies": {+ "@opentelemetry/api": "^1.9.0",+ "@opentelemetry/api-logs": "^0.208.0",+ "@opentelemetry/exporter-logs-otlp-http": "^0.208.0",+ "@opentelemetry/resources": "^2.2.0",+ "@opentelemetry/sdk-logs": "^0.208.0",+ "@posthog/core": "1.28.2",+ "@posthog/types": "1.372.8",+ "core-js": "^3.38.1",+ "dompurify": "^3.3.2",+ "fflate": "^0.4.8",+ "preact": "^10.28.2",+ "query-selector-shadow-dom": "^1.0.1",+ "web-vitals": "^5.1.0"+ }+ },+ "node_modules/preact": {+ "version": "10.29.1",+ "resolved": "https://registry.npmjs.org/preact/-/preact-10.29.1.tgz",+ "integrity": "sha512-gQCLc/vWroE8lIpleXtdJhTFDogTdZG9AjMUpVkDf2iTCNwYNWA+u16dL41TqUDJO4gm2IgrcMv3uTpjd4Pwmg==",+ "license": "MIT",+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/preact"+ }+ },+ "node_modules/protobufjs": {+ "version": "7.5.6",+ "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-7.5.6.tgz",+ "integrity": "sha512-M71sTMB146U3u0di3yup8iM+zv8yPRNQVr1KK4tyBitl3qFvEGucq/rGDRShD2rsJhtN02RJaJ7j5X5hmy8SJg==",+ "hasInstallScript": true,+ "license": "BSD-3-Clause",+ "dependencies": {+ "@protobufjs/aspromise": "^1.1.2",+ "@protobufjs/base64": "^1.1.2",+ "@protobufjs/codegen": "^2.0.5",+ "@protobufjs/eventemitter": "^1.1.0",+ "@protobufjs/fetch": "^1.1.0",+ "@protobufjs/float": "^1.0.2",+ "@protobufjs/inquire": "^1.1.1",+ "@protobufjs/path": "^1.1.2",+ "@protobufjs/pool": "^1.1.0",+ "@protobufjs/utf8": "^1.1.1",+ "@types/node": ">=13.7.0",+ "long": "^5.0.0"+ },+ "engines": {+ "node": ">=12.0.0"+ }+ },+ "node_modules/query-selector-shadow-dom": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/query-selector-shadow-dom/-/query-selector-shadow-dom-1.0.1.tgz",+ "integrity": "sha512-lT5yCqEBgfoMYpf3F2xQRK7zEr1rhIIZuceDK6+xRkJQ4NMbHTwXqk4NkwDwQMNqXgG9r9fyHnzwNVs6zV5KRw==",+ "license": "MIT"+ },"node_modules/react": {"version": "18.3.1","resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz","integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==","license": "MIT",+ "peer": true,"dependencies": {"loose-envify": "^1.1.0"},@@ -1953,6 +2412,7 @@"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz","integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==","license": "MIT",+ "peer": true,"dependencies": {"loose-envify": "^1.1.0","scheduler": "^0.23.2"@@ -1973,6 +2433,7 @@"resolved": "https://registry.npmjs.org/react-redux/-/react-redux-9.2.0.tgz","integrity": "sha512-ROY9fvHhwOD9ySfrF0wmvu//bKCQ6AeZZq1nJNtbDC+kk5DuSuNX/n6YWYF/SYy7bSba4D4FSz8DJeKY/S/r+g==","license": "MIT",+ "peer": true,"dependencies": {"@types/use-sync-external-store": "^0.0.6","use-sync-external-store": "^1.4.0"@@ -2067,7 +2528,8 @@"version": "5.0.1","resolved": "https://registry.npmjs.org/redux/-/redux-5.0.1.tgz","integrity": "sha512-M9/ELqF6fy8FwmkpnF0S3YKOqMyoWJ4+CS5Efg2ct3oY9daQvd/Pc71FpGZsVsbl3Cpb+IIcjBDUnnyBdQbq4w==",- "license": "MIT"+ "license": "MIT",+ "peer": true},"node_modules/redux-thunk": {"version": "3.1.0",@@ -2195,6 +2657,12 @@"node": ">=14.17"}},+ "node_modules/undici-types": {+ "version": "7.19.2",+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.19.2.tgz",+ "integrity": "sha512-qYVnV5OEm2AW8cJMCpdV20CDyaN3g0AjDlOGf1OW4iaDEx8MwdtChUp4zu4H0VP3nDRF/8RKWH+IPp9uW0YGZg==",+ "license": "MIT"+ },"node_modules/update-browserslist-db": {"version": "1.2.3","resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz",@@ -2263,6 +2731,7 @@"integrity": "sha512-+Oxm7q9hDoLMyJOYfUYBuHQo+dkAloi33apOPP56pzj+vsdJDzr+j1NISE5pyaAuKL4A3UD34qd0lx5+kfKp2g==","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"esbuild": "^0.25.0","fdir": "^6.4.4",@@ -2332,6 +2801,12 @@}}},+ "node_modules/web-vitals": {+ "version": "5.2.0",+ "resolved": "https://registry.npmjs.org/web-vitals/-/web-vitals-5.2.0.tgz",+ "integrity": "sha512-i2z98bEmaCqSDiHEDu+gHl/dmR4Q+TxFmG3/13KkMO+o8UxQzCqWaDRCiLgEa41nlO4VpXSI0ASa1xWmO9sBlA==",+ "license": "Apache-2.0"+ },"node_modules/yallist": {"version": "3.1.1","resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz",diff --git a/web/package.json b/web/package.jsonindex 3c43984b..46e71503 100644--- a/web/package.json+++ b/web/package.json@@ -9,10 +9,12 @@"preview": "vite preview"},"dependencies": {+ "@posthog/react": "^1.9.0","@tanstack/react-query": "^5.60.0","@xterm/addon-fit": "^0.11.0","@xterm/addon-web-links": "^0.12.0","@xterm/xterm": "^6.0.0",+ "posthog-js": "^1.372.0","react": "^18.3.1","react-dom": "^18.3.1","react-router-dom": "^6.28.0",diff --git a/web/src/App.tsx b/web/src/App.tsxindex f9737438..88b35183 100644--- a/web/src/App.tsx+++ b/web/src/App.tsx@@ -5,6 +5,8 @@ import Layout from './components/Layout'import Login from './pages/Login'import Dashboard from './pages/Dashboard'import Sessions from './pages/Sessions'+import Agents from './pages/Agents'+import AgentDetail from './pages/AgentDetail'import APIKeys from './pages/APIKeys'import Checkpoints from './pages/Checkpoints'import Templates from './pages/Templates'@@ -22,6 +24,8 @@ export default function App() {<Route index element={<Dashboard />} /><Route path="sessions" element={<Sessions />} /><Route path="sessions/:sandboxId" element={<SessionDetail />} />+ <Route path="agents" element={<Agents />} />+ <Route path="agents/:agentId" element={<AgentDetail />} /><Route path="checkpoints" element={<Checkpoints />} /><Route path="templates" element={<Templates />} /><Route path="api-keys" element={<APIKeys />} />diff --git a/web/src/api/client.ts b/web/src/api/client.tsindex 50cbc5b0..441abf14 100644--- a/web/src/api/client.ts+++ b/web/src/api/client.ts@@ -1,3 +1,5 @@+import posthog from 'posthog-js'+const API_BASE = '/api/dashboard'export async function apiFetch<T>(path: string, options: RequestInit = {}): Promise<T> {@@ -18,7 +20,15 @@ export async function apiFetch<T>(path: string, options: RequestInit = {}): Promif (!res.ok) {const body = await res.json().catch(() => ({}))- throw new Error(body.error || `Request failed: ${res.status}`)+ // OC dashboard returns {error: "string"}; sessions-api returns+ // {error: {type, message}}. Handle both so we don't surface+ // "[object Object]" when the proxy talks to sessions-api.+ let msg: string+ if (typeof body.error === 'string') msg = body.error+ else if (body.error && typeof body.error.message === 'string') msg = body.error.message+ else if (typeof body.message === 'string') msg = body.message+ else msg = `Request failed: ${res.status}`+ throw new Error(msg)}if (res.status === 204) {@@ -31,6 +41,7 @@ export async function apiFetch<T>(path: string, options: RequestInit = {}): Prom// Logout: clears server session, then navigates to loginexport async function logout(): Promise<void> {await fetch('/auth/logout', { method: 'POST', credentials: 'include' }).catch(() => {})+ posthog.reset()// Navigate to login page — use replace to prevent back-button loopwindow.location.replace('/login')}@@ -70,6 +81,51 @@ export const getSessionDetail = (sandboxId: string) =>export const getSessionStats = (sandboxId: string) =>apiFetch<SandboxStats>(`/sessions/${sandboxId}/stats`)+// Soft restart: guest kernel reboots, QEMU process + workspace stay.+export const rebootSession = (sandboxId: string) =>+ apiFetch<void>(`/sessions/${sandboxId}/reboot`, { method: 'POST' })++// Hard restart: QEMU process recreated, workspace data preserved.+export const powerCycleSession = (sandboxId: string) =>+ apiFetch<void>(`/sessions/${sandboxId}/power-cycle`, { method: 'POST' })++// Sandbox session logs: SSE stream of /var/log + exec stdout/stderr.+// The server proxies queries through to Axiom; the read token never+// reaches the browser. The returned EventSource emits one `message`+// event per log line (event.data = JSON-stringified LogEvent).+export interface LogEvent {+ _time: string+ source: 'var_log' | 'exec_stdout' | 'exec_stderr' | 'agent'+ line: string+ sandbox_id?: string+ path?: string+ exec_id?: string+ command?: string+ argv?: string[]+ exit_code?: number+}++export interface LogStreamOptions {+ tail?: boolean // default true; if false, returns historical batch then closes+ q?: string // free-text search (server applies "line contains")+ source?: string // comma-separated subset of source values+ since?: string // RFC3339; default = sandbox.startedAt+ limit?: number // historical batch cap; default 1000, max 10000+}++export function streamSessionLogs(+ sandboxId: string,+ opts: LogStreamOptions = {},+): EventSource {+ const url = new URL(`${API_BASE}/sessions/${encodeURIComponent(sandboxId)}/logs`, window.location.origin)+ if (opts.tail !== undefined) url.searchParams.set('tail', String(opts.tail))+ if (opts.q) url.searchParams.set('q', opts.q)+ if (opts.source) url.searchParams.set('source', opts.source)+ if (opts.since) url.searchParams.set('since', opts.since)+ if (opts.limit !== undefined) url.searchParams.set('limit', String(opts.limit))+ return new EventSource(url.toString(), { withCredentials: true })+}+export const getOrg = () => apiFetch<Org>('/org')export const updateOrg = (name: string) =>@@ -164,6 +220,13 @@ export interface CheckpointItem {activeForks: numbertotalForks: numbercreatedAt: string+ // errorMsg / failedAt are populated when status === 'failed'.+ // Pre-fix the API returned status='failed' with no detail; now the row+ // carries the actual reason (timeout, archive failure, S3 upload failure,+ // etc.) and the failure timestamp. Server-side: db.Checkpoint.ErrorMsg /+ // FailedAt (sandbox_checkpoints columns added in migration 039).+ errorMsg?: string+ failedAt?: string}export interface CheckpointsResponse {@@ -310,3 +373,261 @@ export const redeemPromoCode = (code: string) =>method: 'POST',body: JSON.stringify({ code }),})++// ── Agents (proxied to sessions-api at /api/dashboard/agents/*) ──++export interface Agent {+ id: string+ display_name: string+ core: string | null+ model: string | null+ channels: Array<{ name: string; bot_username?: string | null; connected_at?: string }>+ packages: Array<{ name: string; installed_at?: string }>+ secret_store: string | null+ config: Record<string, unknown>+ created_at: string+ updated_at: string+}++export interface AgentDetail extends Agent {+ status: 'ready' | 'starting' | 'degraded' | 'error' | 'unknown'+ instance_id: string | null+ instance_status: string | null+ sandbox_id: string | null+ core_status: { status: string; reason?: string; message?: string; updated_at?: string } | null+ channel_status: Record<string, { status: string; phase?: string; message?: string }>+ package_status: Record<string, { status: string; phase?: string; message?: string }>+ conditions: Array<{ type: string; status: string; reason?: string; message?: string }>+ current_operation: AgentOperation | null+ last_error: { phase: string; message: string; at: string } | null+}++export interface AgentOperation {+ id: string+ agent_id: string+ kind: string+ target_type?: string | null+ target_key?: string | null+ phase: string+ state: 'queued' | 'running' | 'success' | 'error' | 'canceled'+ message?: string | null+ created_at: string+ updated_at: string+}++export const listAgents = () =>+ apiFetch<{ agents: Agent[] }>('/agents')++export const getAgent = (id: string) =>+ apiFetch<AgentDetail>(`/agents/${encodeURIComponent(id)}`)++export const createAgent = (input: {+ id: string+ display_name?: string+ core?: string+ model?: string+ config?: Record<string, unknown>+ secrets?: Record<string, string>+}) =>+ apiFetch<AgentDetail>('/agents', {+ method: 'POST',+ body: JSON.stringify(input),+ })++export const deleteAgent = (id: string) =>+ apiFetch<{ id: string; deleted: boolean }>(`/agents/${encodeURIComponent(id)}`, {+ method: 'DELETE',+ })++export const installGbrain = (agentId: string) =>+ apiFetch<{ agent_id: string; package: string; status: string; operation: AgentOperation }>(+ `/agents/${encodeURIComponent(agentId)}/packages/gbrain`,+ { method: 'POST' },+ )++export const uninstallGbrain = (agentId: string) =>+ apiFetch<{ agent_id: string; package: string; status: string }>(+ `/agents/${encodeURIComponent(agentId)}/packages/gbrain`,+ { method: 'DELETE' },+ )++export const connectTelegram = (agentId: string, botToken: string) =>+ apiFetch<{ agent_id: string; channel: string; status: string; operation: AgentOperation }>(+ `/agents/${encodeURIComponent(agentId)}/channels/telegram`,+ {+ method: 'POST',+ body: JSON.stringify({ bot_token: botToken }),+ },+ )++export const disconnectTelegram = (agentId: string) =>+ apiFetch<{ agent_id: string; channel: string; status: string }>(+ `/agents/${encodeURIComponent(agentId)}/channels/telegram`,+ { method: 'DELETE' },+ )++export interface AgentEvent {+ id: string+ agent_id: string+ type: 'info' | 'warning' | 'error'+ phase: string+ message: string+ at: string+}++export const getAgentEvents = (agentId: string, limit = 50) =>+ apiFetch<{ events: AgentEvent[]; next_before: string | null }>(+ `/agents/${encodeURIComponent(agentId)}/events?limit=${limit}`,+ )++export const getAgentOperations = (agentId: string, limit = 20) =>+ apiFetch<{ operations: AgentOperation[]; next_before: string | null }>(+ `/agents/${encodeURIComponent(agentId)}/operations?limit=${limit}`,+ )++export const restartAgent = (agentId: string) =>+ apiFetch<{ agent_id: string; status: string }>(+ `/agents/${encodeURIComponent(agentId)}/restart`,+ { method: 'POST' },+ )++export const getAgentLogs = (agentId: string, tail = 300) =>+ apiFetch<{ agent_id: string; sandbox_id: string; source: string; lines: number; content: string }>(+ `/agents/${encodeURIComponent(agentId)}/logs?tail=${tail}`,+ )++// ── Per-agent paywalled feature subscriptions (Telegram et al) ──++export type EntitlementReason = 'ungated' | 'subscription_required' | string++export interface AgentEntitlement {+ feature: string+ entitled: boolean+ reason?: EntitlementReason+ price_monthly_cents?: number+ status?: string+ current_period_end?: string+ cancel_at_period_end?: boolean+ stripe_subscription_id?: string+}++export const listAgentEntitlements = (agentId: string) =>+ apiFetch<{ agent_id: string; entitlements: AgentEntitlement[] }>(+ `/agents/${encodeURIComponent(agentId)}/entitlements`,+ )++export type SubscribeResult =+ | { status: 'active'; feature: string; agent_id: string; subscription_id: string; price_id: string }+ | { status: 'already_subscribed'; feature: string; agent_id: string; subscription_id: string }+ | { status: 'ungated'; feature: string; agent_id: string }+ | { status: 'checkout_required'; feature: string; agent_id: string; checkout_url: string }++export const subscribeAgentFeature = (agentId: string, feature: string) =>+ apiFetch<SubscribeResult>(+ `/agents/${encodeURIComponent(agentId)}/subscriptions/${encodeURIComponent(feature)}`,+ { method: 'POST' },+ )++export interface OrgAgentSubscription {+ agent_id: string+ feature: string+ status: string+ active: boolean+ price_monthly_cents: number+ current_period_end?: string+ cancel_at_period_end: boolean+ canceled_at?: string+ created_at: string+ stripe_subscription_id: string+}++export const listOrgAgentSubscriptions = () =>+ apiFetch<{ subscriptions: OrgAgentSubscription[] }>(+ '/billing/agent-subscriptions',+ )++export const cancelAgentFeature = (agentId: string, feature: string) =>+ apiFetch<{+ status: string+ feature: string+ agent_id: string+ cancel_at_period_end: boolean+ current_period_end?: string+ }>(+ `/agents/${encodeURIComponent(agentId)}/subscriptions/${encodeURIComponent(feature)}`,+ { method: 'DELETE' },+ )++/**+ * Streams a chat turn to an agent's instance and yields parsed SSE events+ * as they arrive. The upstream (sessions-api POST /v1/agents/:id/instances/:id/messages)+ * emits `data: {type:"text",content:"..."}` and `data: {type:"done"}`.+ *+ * Uses fetch + ReadableStream because EventSource is GET-only.+ */+export type ChatEvent =+ | { type: 'text'; content: string; conversation_id?: string }+ | { type: 'done' }+ | { type: 'raw'; data: string }++export interface ChatTurn { role: 'user' | 'assistant' | 'system'; content: string }++export async function* streamAgentChat(+ agentId: string,+ instanceId: string,+ content: string,+ conversationId?: string,+ history?: ChatTurn[],+): AsyncGenerator<ChatEvent, void, unknown> {+ // OpenAI-style chat-completions is stateless: the gateway needs the+ // full conversation each turn to have any memory of prior messages.+ // Caller passes `history` (already including the new user turn).+ // For backwards compat with older callers, we still accept `content`+ // as a single-turn shortcut.+ const body: Record<string, unknown> = {}+ if (history && history.length > 0) {+ body.messages = history+ } else {+ body.content = content+ }+ if (conversationId) body.conversation_id = conversationId++ const res = await fetch(+ `/api/dashboard/agents/${encodeURIComponent(agentId)}/instances/${encodeURIComponent(instanceId)}/messages`,+ {+ method: 'POST',+ credentials: 'include',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(body),+ },+ )+ if (!res.ok || !res.body) {+ const text = await res.text().catch(() => '')+ throw new Error(`chat ${res.status}: ${text || 'no body'}`)+ }++ const reader = res.body.getReader()+ const decoder = new TextDecoder()+ let buffer = ''+ while (true) {+ const { done, value } = await reader.read()+ if (done) return+ buffer += decoder.decode(value, { stream: true })+ let idx: number+ while ((idx = buffer.indexOf('\n\n')) !== -1) {+ const block = buffer.slice(0, idx)+ buffer = buffer.slice(idx + 2)+ const data = block+ .split('\n')+ .filter((line) => line.startsWith('data:'))+ .map((line) => line.slice(5).trimStart())+ .join('\n')+ if (!data) continue+ try {+ yield JSON.parse(data) as ChatEvent+ } catch {+ yield { type: 'raw', data }+ }+ }+ }+}diff --git a/web/src/components/Layout.tsx b/web/src/components/Layout.tsxindex ce51bd8a..3a79697b 100644--- a/web/src/components/Layout.tsx+++ b/web/src/components/Layout.tsx@@ -44,6 +44,16 @@ const icons = {<line x1="1" y1="10" x2="23" y2="10" /></svg>),+ bot: (+ <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">+ <rect x="4" y="7" width="16" height="12" rx="2" />+ <path d="M12 7V3" />+ <circle cx="12" cy="3" r="1" />+ <circle cx="9" cy="13" r="1" fill="currentColor" />+ <circle cx="15" cy="13" r="1" fill="currentColor" />+ <path d="M9 17h6" />+ </svg>+ ),gear: (<svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="3" />@@ -62,6 +72,7 @@ const icons = {const navItems = [{ to: '/', label: 'Dashboard', end: true, icon: icons.grid },{ to: '/sessions', label: 'Sessions', icon: icons.clock },+ { to: '/agents', label: 'Agents', icon: icons.bot },{ to: '/checkpoints', label: 'Checkpoints', icon: icons.layers },{ to: '/templates', label: 'Templates', icon: icons.box },{ to: '/api-keys', label: 'API Keys', icon: icons.key },diff --git a/web/src/components/LogsPanel.tsx b/web/src/components/LogsPanel.tsxnew file mode 100644index 00000000..4c54990a--- /dev/null+++ b/web/src/components/LogsPanel.tsx@@ -0,0 +1,454 @@+// LogsPanel — sandbox session logs view.+//+// Streams from /api/dashboard/sessions/:sandboxId/logs (SSE) and renders+// a live, source-color-coded timeline of events: lines from /var/log+// inside the sandbox, stdout/stderr of every platform-exec'd command,+// and synthetic "exit_code" markers showing how each command finished.+//+// Design contract:+//+// - Auto-scroll to bottom unless the user has scrolled up. Scrolling+// up "pins" the view; scrolling back to within ~40px of the bottom+// unpins it.+// - Hard cap on retained events (visibleCap below). Once exceeded,+// drop the oldest. Memory grows linearly with cap and is bounded.+// - Search filters server-side (the SSE re-opens with `?q=...`); we+// debounce so each keystroke isn't a new connection.+// - Source filter is a comma-separated allowlist that maps directly+// to the server's ?source= param.+// - Pause toggle freezes display only — the EventSource keeps+// receiving so unpausing catches up; if buffer overflows, oldest+// pending events drop.+//+// PTY content is intentionally not part of this view (consent surface+// is different — see design doc).++import { useEffect, useMemo, useRef, useState } from 'react'+import { streamSessionLogs, type LogEvent } from '../api/client'++const visibleCap = 3000 // hard cap on retained events+const debounceMs = 200 // search-box debounce+const nearBottomPx = 40 // "auto-scroll if within this many px of bottom"++// One colour per source. Distinct hues across the four; no overlap+// with the green used for success-EOF rows (✓ exited 0) and the rose+// used for failure-EOF rows.+const sources: { value: LogEvent['source']; label: string; color: string }[] = [+ { value: 'exec_stdout', label: 'stdout', color: 'var(--text-secondary)' },+ { value: 'exec_stderr', label: 'stderr', color: 'var(--accent-rose)' },+ { value: 'var_log', label: 'var/log', color: '#f59e0b' /* amber — distinct from emerald used for ✓ exited */ },+ { value: 'agent', label: 'agent', color: 'var(--accent-violet)' },+]++function useDebouncedValue<T>(value: T, delayMs: number): T {+ const [debounced, setDebounced] = useState(value)+ useEffect(() => {+ const t = setTimeout(() => setDebounced(value), delayMs)+ return () => clearTimeout(t)+ }, [value, delayMs])+ return debounced+}++interface LogsPanelProps {+ sandboxId: string+ onClose?: () => void+}++export default function LogsPanel({ sandboxId, onClose }: LogsPanelProps) {+ const [query, setQuery] = useState('')+ const [paused, setPaused] = useState(false)+ // Subtractive filter: every source is shown by default. Clicking a+ // chip *hides* that source; clicking again brings it back.+ const [hiddenSources, setHiddenSources] = useState<Set<LogEvent['source']>>(new Set())+ const [events, setEvents] = useState<LogEvent[]>([])+ const [connState, setConnState] = useState<'connecting' | 'open' | 'error' | 'closed'>('connecting')++ const debouncedQuery = useDebouncedValue(query, debounceMs)++ // Buffered events that arrived while paused; flushed on resume.+ const pausedBufRef = useRef<LogEvent[]>([])+ const containerRef = useRef<HTMLDivElement | null>(null)+ const stickToBottomRef = useRef(true)++ // Open the EventSource ONCE per sandbox. Search and source filters+ // are applied client-side against the in-memory buffer — no SSE+ // re-open on filter change, no flicker. The historical batch is+ // bounded by visibleCap so memory stays cheap; if a user really+ // wants to search beyond the current buffer they can adjust the+ // since= URL param later.+ useEffect(() => {+ setEvents([])+ pausedBufRef.current = []+ stickToBottomRef.current = true+ setConnState('connecting')++ const es = streamSessionLogs(sandboxId, { tail: true })++ es.onopen = () => setConnState('open')+ es.onerror = () => setConnState('error')+ es.onmessage = (e) => {+ let ev: LogEvent+ try {+ ev = JSON.parse(e.data) as LogEvent+ } catch {+ return+ }+ if (paused) {+ pausedBufRef.current.push(ev)+ // Defensive cap on the paused buffer.+ if (pausedBufRef.current.length > visibleCap) {+ pausedBufRef.current = pausedBufRef.current.slice(-visibleCap)+ }+ return+ }+ setEvents((prev) => {+ const next = prev.length >= visibleCap ? prev.slice(prev.length - visibleCap + 1) : prev.slice()+ next.push(ev)+ return next+ })+ }++ return () => {+ es.close()+ setConnState('closed')+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [sandboxId])++ // When unpausing, drain the paused buffer into events.+ useEffect(() => {+ if (!paused && pausedBufRef.current.length > 0) {+ const buf = pausedBufRef.current+ pausedBufRef.current = []+ setEvents((prev) => {+ const merged = prev.concat(buf)+ return merged.length > visibleCap ? merged.slice(merged.length - visibleCap) : merged+ })+ }+ }, [paused])++ // Auto-scroll to bottom when new events arrive — but only if the+ // user is already near the bottom (i.e. they haven't scrolled up to+ // read older lines).+ useEffect(() => {+ if (!stickToBottomRef.current) return+ const el = containerRef.current+ if (!el) return+ el.scrollTop = el.scrollHeight+ }, [events])++ const handleScroll = () => {+ const el = containerRef.current+ if (!el) return+ const distFromBottom = el.scrollHeight - el.scrollTop - el.clientHeight+ stickToBottomRef.current = distFromBottom <= nearBottomPx+ }++ const toggleSource = (src: LogEvent['source']) => {+ setHiddenSources((prev) => {+ const next = new Set(prev)+ if (next.has(src)) next.delete(src)+ else next.add(src)+ return next+ })+ }++ // Client-side filter pipeline: source filter → text search → EOF+ // dedup. Each command emits one EOF event per stream (stdout AND+ // stderr) so without dedup the timeline shows "exited 0" twice for+ // the same exec. We collapse them to one per exec_id.+ const visible = useMemo(() => {+ const lowerQuery = debouncedQuery.trim().toLowerCase()++ // Two-pass:+ // 1. Dedupe EOFs by exec_id — agent emits one EOF on stdout AND+ // one on stderr per exec; we keep the first (stdout, by emit+ // order), drop the rest. Must happen BEFORE the source filter+ // — otherwise hiding stdout lets the suppressed stderr-EOF+ // through and the row "moves" from stdout-coloured to stderr.+ // 2. Apply source + text filters to the deduped list.+ const seenEofExecIDs = new Set<string>()+ const deduped: LogEvent[] = []+ for (const ev of events) {+ const isEof = ev.line === '' && ev.exit_code !== undefined+ if (isEof && ev.exec_id) {+ if (seenEofExecIDs.has(ev.exec_id)) continue+ seenEofExecIDs.add(ev.exec_id)+ }+ deduped.push(ev)+ }++ return deduped.filter((ev) => {+ if (hiddenSources.has(ev.source)) return false+ if (lowerQuery && !searchCorpus(ev).includes(lowerQuery)) return false+ return true+ })+ }, [events, hiddenSources, debouncedQuery])++ return (+ <div style={{ display: 'flex', flexDirection: 'column', height: 480 }}>+ {/* Header */}+ <div style={{+ display: 'flex',+ alignItems: 'center',+ gap: 12,+ marginBottom: 12,+ flexWrap: 'wrap',+ }}>+ <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--text-tertiary)', textTransform: 'uppercase', letterSpacing: '0.05em' }}>+ Logs+ </div>++ <ConnectionDot state={connState} />++ <div style={{ flex: 1, minWidth: 160, position: 'relative' }}>+ <input+ type="text"+ value={query}+ onChange={(e) => setQuery(e.target.value)}+ placeholder="Search…"+ style={{+ width: '100%',+ boxSizing: 'border-box',+ background: 'var(--bg-deep)',+ border: '1px solid var(--border-subtle)',+ borderRadius: 'var(--radius-sm)',+ color: 'var(--text-primary)',+ fontSize: 13,+ padding: '6px 28px 6px 10px',+ fontFamily: 'inherit',+ }}+ />+ {query && (+ <button+ type="button"+ onClick={() => setQuery('')}+ aria-label="Clear search"+ title="Clear"+ style={{+ position: 'absolute',+ right: 6,+ top: '50%',+ transform: 'translateY(-50%)',+ background: 'none',+ border: 'none',+ padding: 4,+ cursor: 'pointer',+ color: 'var(--text-tertiary)',+ display: 'inline-flex',+ alignItems: 'center',+ justifyContent: 'center',+ lineHeight: 0,+ opacity: 0.7,+ transition: 'opacity 0.1s',+ }}+ onMouseEnter={(e) => (e.currentTarget.style.opacity = '1')}+ onMouseLeave={(e) => (e.currentTarget.style.opacity = '0.7')}+ >+ <svg width="11" height="11" viewBox="0 0 12 12" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round">+ <line x1="2" y1="2" x2="10" y2="10" />+ <line x1="10" y1="2" x2="2" y2="10" />+ </svg>+ </button>+ )}+ </div>++ <div style={{ display: 'flex', gap: 4 }}>+ {sources.map((src) => {+ // Subtractive filter: chip ON = source visible (the+ // default); chip OFF = source hidden. Click toggles.+ // ON state uses a subtle ~18% tint of the source color+ // rather than a full fill — keeps the four chips legible+ // when all four are active by default.+ const isVisible = !hiddenSources.has(src.value)+ const tinted = `color-mix(in srgb, ${src.color} 18%, transparent)`+ return (+ <button+ key={src.value}+ onClick={() => toggleSource(src.value)}+ title={isVisible ? `Hide ${src.label}` : `Show ${src.label}`}+ style={{+ background: isVisible ? tinted : 'transparent',+ color: src.color,+ border: `1px solid ${src.color}`,+ borderRadius: 'var(--radius-sm)',+ fontSize: 11,+ fontWeight: isVisible ? 600 : 400,+ opacity: isVisible ? 1 : 0.45,+ padding: '3px 8px',+ cursor: 'pointer',+ fontFamily: 'var(--font-mono)',+ transition: 'background 0.1s, opacity 0.1s',+ }}+ >+ {src.label}+ </button>+ )+ })}+ </div>++ <button+ onClick={() => setPaused((p) => !p)}+ className="btn-ghost"+ title={paused ? 'Resume live tail' : 'Pause display (stream keeps running)'}+ >+ {paused ? 'Resume' : 'Pause'}+ {paused && pausedBufRef.current.length > 0 && (+ <span style={{ marginLeft: 6, color: 'var(--text-tertiary)' }}>+ ({pausedBufRef.current.length} buffered)+ </span>+ )}+ </button>++ {onClose && (+ <button onClick={onClose} className="btn-ghost" title="Close logs">+ Close+ </button>+ )}+ </div>++ {/* Stream view */}+ <div+ ref={containerRef}+ onScroll={handleScroll}+ style={{+ flex: 1,+ background: 'var(--bg-deep)',+ border: '1px solid var(--border-subtle)',+ borderRadius: 'var(--radius-sm)',+ padding: '8px 0',+ overflowY: 'auto',+ fontFamily: 'var(--font-mono)',+ fontSize: 12,+ lineHeight: 1.45,+ }}+ >+ {visible.length === 0 && connState === 'open' && (+ <div style={{ padding: '20px', textAlign: 'center', color: 'var(--text-tertiary)' }}>+ No logs yet. Run a command, write to <code>/var/log/...</code>, or wait for system activity.+ </div>+ )}+ {visible.length === 0 && connState === 'error' && (+ <div style={{ padding: '20px', textAlign: 'center', color: 'var(--accent-rose)' }}>+ Couldn't connect to log stream. Logs may not be configured for this deployment.+ </div>+ )}+ {visible.map((ev, i) => (+ <Row key={i} ev={ev} />+ ))}+ </div>++ {/* Footer: cap notice */}+ {visible.length >= visibleCap && (+ <div style={{ marginTop: 6, fontSize: 11, color: 'var(--text-tertiary)' }}>+ Showing latest {visibleCap} events; older events scrolled off.+ </div>+ )}+ </div>+ )+}++function ConnectionDot({ state }: { state: 'connecting' | 'open' | 'error' | 'closed' }) {+ const color =+ state === 'open' ? 'var(--accent-emerald, #10b981)' :+ state === 'error' ? 'var(--accent-rose)' :+ 'var(--text-tertiary)'+ return (+ <span+ title={`Connection: ${state}`}+ style={{+ display: 'inline-block',+ width: 8,+ height: 8,+ borderRadius: '50%',+ background: color,+ }}+ />+ )+}++function Row({ ev }: { ev: LogEvent }) {+ const sourceMeta = sources.find((s) => s.value === ev.source)+ const sourceColor = sourceMeta?.color || 'var(--text-tertiary)'+ const time = formatTime(ev._time)++ // 3px left border in the source color so the chip palette and the+ // row palette obviously share a key. Padding matches the+ // non-bordered baseline so rows of different sources align.+ const baseStyle: React.CSSProperties = {+ display: 'flex',+ gap: 10,+ padding: '1px 14px',+ borderLeft: `3px solid ${sourceColor}`,+ paddingLeft: 11, // 14 - 3 to keep content alignment+ }++ // Exec EOF marker: line is empty + exit_code is present. Render as a+ // synthetic system row so users can see "command X exited 0/1" inline.+ if (ev.line === '' && ev.exit_code !== undefined) {+ const ok = ev.exit_code === 0+ return (+ <div style={{+ ...baseStyle,+ padding: '2px 14px 2px 11px',+ color: ok ? 'var(--accent-emerald, #10b981)' : 'var(--accent-rose)',+ fontStyle: 'italic',+ opacity: 0.85,+ }}>+ <span style={{ color: 'var(--text-tertiary)', fontStyle: 'normal' }}>{time}</span>+ <span>+ {ok ? '✓' : '✗'} {ev.command || 'command'} exited {ev.exit_code}+ </span>+ </div>+ )+ }++ return (+ <div style={{+ ...baseStyle,+ whiteSpace: 'pre-wrap',+ wordBreak: 'break-word',+ }}>+ <span style={{ color: 'var(--text-tertiary)', flexShrink: 0 }}>{time}</span>+ <span+ style={{+ color: sourceColor,+ flexShrink: 0,+ minWidth: 56,+ fontSize: 11,+ paddingTop: 1,+ }}+ >+ {sourceMeta?.label || ev.source}+ </span>+ <span style={{ color: 'var(--text-primary)', flex: 1 }}>+ {ev.line}+ </span>+ </div>+ )+}++// searchCorpus returns the text the search box matches against for a+// given event, lower-cased. For real lines it's just `line`; for EOF+// markers (which have line=='' and a synthesized "X exited N"+// rendering) we include the synthesized text plus the command name ++// argv so users can search for "exit", a command, or its args.+function searchCorpus(ev: LogEvent): string {+ if (ev.line === '' && ev.exit_code !== undefined) {+ const cmd = ev.command || 'command'+ const argv = ev.argv ? ev.argv.join(' ') : ''+ return `${cmd} ${argv} exited ${ev.exit_code}`.toLowerCase()+ }+ return ev.line.toLowerCase()+}++function formatTime(rfc3339: string): string {+ // Display HH:MM:SS.mmm — matches the granularity shippers use.+ const d = new Date(rfc3339)+ if (isNaN(d.getTime())) return ''+ const hh = String(d.getHours()).padStart(2, '0')+ const mm = String(d.getMinutes()).padStart(2, '0')+ const ss = String(d.getSeconds()).padStart(2, '0')+ const ms = String(d.getMilliseconds()).padStart(3, '0')+ return `${hh}:${mm}:${ss}.${ms}`+}diff --git a/web/src/hooks/useAuth.tsx b/web/src/hooks/useAuth.tsxindex 75fe6145..a2c7aae7 100644--- a/web/src/hooks/useAuth.tsx+++ b/web/src/hooks/useAuth.tsx@@ -1,4 +1,5 @@import { createContext, useContext, useEffect, useState, useCallback, type ReactNode } from 'react'+import posthog from 'posthog-js'import { getMe, switchOrg as switchOrgApi, type OrgInfo } from '../api/client'interface AuthUser {@@ -33,6 +34,9 @@ export function AuthProvider({ children }: { children: ReactNode }) {try {const me = await getMe()setUser(me)+ if (me?.id) {+ posthog.identify(me.id, { email: me.email, org_id: me.orgId })+ }} catch (err: unknown) {if (err instanceof Error && !err.message.includes('Unauthorized')) {setError(err.message)diff --git a/web/src/main.tsx b/web/src/main.tsxindex 915c6ea0..20bc803a 100644--- a/web/src/main.tsx+++ b/web/src/main.tsx@@ -2,6 +2,8 @@ import React from 'react'import ReactDOM from 'react-dom/client'import { QueryClient, QueryClientProvider } from '@tanstack/react-query'import { BrowserRouter } from 'react-router-dom'+import posthog from 'posthog-js'+import { PostHogProvider } from '@posthog/react'import App from './App'import './styles/theme.css'@@ -14,12 +16,24 @@ const queryClient = new QueryClient({},})+const PH_TOKEN = import.meta.env.VITE_PUBLIC_POSTHOG_PROJECT_TOKEN+const PH_HOST = import.meta.env.VITE_PUBLIC_POSTHOG_HOST+if (PH_TOKEN) {+ posthog.init(PH_TOKEN, {+ api_host: PH_HOST || 'https://us.i.posthog.com',+ defaults: '2025-05-24',+ person_profiles: 'identified_only',+ })+}+ReactDOM.createRoot(document.getElementById('root')!).render(<React.StrictMode>- <QueryClientProvider client={queryClient}>- <BrowserRouter>- <App />- </BrowserRouter>- </QueryClientProvider>+ <PostHogProvider client={posthog}>+ <QueryClientProvider client={queryClient}>+ <BrowserRouter>+ <App />+ </BrowserRouter>+ </QueryClientProvider>+ </PostHogProvider></React.StrictMode>,)diff --git a/web/src/pages/AgentDetail.tsx b/web/src/pages/AgentDetail.tsxnew file mode 100644index 00000000..0e65a061--- /dev/null+++ b/web/src/pages/AgentDetail.tsx@@ -0,0 +1,1892 @@+import { useEffect, useRef, useState } from 'react'+import { useNavigate, useParams } from 'react-router-dom'+import {+ getAgent,+ deleteAgent,+ installGbrain,+ uninstallGbrain,+ connectTelegram,+ disconnectTelegram,+ restartAgent,+ rebootSession,+ getAgentEvents,+ getAgentOperations,+ getAgentLogs,+ streamAgentChat,+ listAgentEntitlements,+ subscribeAgentFeature,+ cancelAgentFeature,+ type AgentEntitlement,+ type AgentDetail,+ type AgentOperation,+ type AgentEvent as AgentEventRow,+} from '../api/client'++type Tab = 'overview' | 'channels' | 'plugins' | 'events' | 'logs' | 'advanced'+type Banner = { kind: 'info' | 'error' | 'success'; text: string } | null++const statusColor: Record<string, string> = {+ ready: 'var(--accent-emerald, #34d399)',+ starting: 'var(--accent-amber, #fbbf24)',+ degraded: 'var(--accent-amber, #fbbf24)',+ error: 'var(--accent-rose, #f87171)',+ unknown: 'var(--text-tertiary)',+}++export default function AgentDetailPage() {+ const { agentId = '' } = useParams<{ agentId: string }>()+ const navigate = useNavigate()+ const [detail, setDetail] = useState<AgentDetail | null>(null)+ const [entitlementsByFeature, setEntitlementsByFeature] = useState<Record<string, AgentEntitlement>>({})+ const [loading, setLoading] = useState(true)+ const [tab, setTab] = useState<Tab>('overview')+ const [banner, setBanner] = useState<Banner>(null)+ const [acting, setActing] = useState<string | null>(null)++ async function refresh() {+ try {+ const d = await getAgent(agentId)+ setDetail(d)+ // Refresh entitlements alongside detail so the header upgrade+ // pill stays in sync with the latest subscription state.+ try {+ const e = await listAgentEntitlements(agentId)+ const map: Record<string, AgentEntitlement> = {}+ for (const ent of e.entitlements) map[ent.feature] = ent+ setEntitlementsByFeature(map)+ } catch {+ // best-effort — don't block the page on entitlement fetch+ }+ } catch (err) {+ setBanner({ kind: 'error', text: `Failed to load agent: ${(err as Error).message}` })+ } finally {+ setLoading(false)+ }+ }++ useEffect(() => {+ void refresh()+ const interval = setInterval(() => void refresh(), 5000)+ return () => clearInterval(interval)+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [agentId])++ async function act<T>(label: string, fn: () => Promise<T>, ok: string) {+ setActing(label)+ try {+ await fn()+ setBanner({ kind: 'success', text: ok })+ await refresh()+ } catch (err) {+ setBanner({ kind: 'error', text: `${label} failed: ${(err as Error).message}` })+ } finally {+ setActing(null)+ }+ }++ async function handleDelete() {+ if (!window.confirm(`Delete agent "${agentId}"? Sandbox will be killed.`)) return+ setActing('delete')+ try {+ await deleteAgent(agentId)+ navigate('/agents')+ } catch (err) {+ setBanner({ kind: 'error', text: `Delete failed: ${(err as Error).message}` })+ setActing(null)+ }+ }++ if (loading && !detail) {+ return (+ <div style={{ display: 'flex', alignItems: 'center', gap: 10, color: 'var(--text-tertiary)', fontSize: 13, padding: '32px 0' }}>+ <span className="loading-spinner" style={{ width: 14, height: 14, borderWidth: 1.5 }} />+ Loading agent…+ </div>+ )+ }++ if (!detail) {+ return (+ <div>+ <button onClick={() => navigate('/agents')} style={secondaryButton}>← Back</button>+ <p style={{ color: 'var(--accent-rose, #f87171)', marginTop: 16 }}>Agent not found.</p>+ </div>+ )+ }++ const sandboxId = detail.sandbox_id++ return (+ <div>+ {/* Top bar with back link */}+ <button+ onClick={() => navigate('/agents')}+ style={{ ...secondaryButton, marginBottom: 16 }}+ >+ ← Agents+ </button>++ {/* Header card */}+ <div+ style={{+ background: 'rgba(255,255,255,0.02)',+ border: '1px solid var(--border-subtle)',+ borderRadius: 10,+ padding: '18px 22px',+ display: 'flex',+ alignItems: 'flex-start',+ gap: 18,+ marginBottom: 18,+ }}+ >+ <div+ className={+ detail.status === 'starting' || detail.status === 'degraded' || detail.current_operation+ ? 'pulse-dot'+ : undefined+ }+ style={{+ width: 12,+ height: 12,+ borderRadius: '50%',+ background: statusColor[detail.status] ?? statusColor.unknown,+ boxShadow:+ detail.status === 'starting' || detail.current_operation+ ? `0 0 0 4px ${statusColor[detail.status]}22`+ : undefined,+ flexShrink: 0,+ marginTop: 6,+ }}+ />+ <div style={{ flex: 1, minWidth: 0 }}>+ <div style={{ display: 'flex', alignItems: 'baseline', gap: 10 }}>+ <h1 style={{ margin: 0, fontSize: 20, fontFamily: 'var(--font-display)', fontWeight: 700 }}>+ {detail.display_name}+ </h1>+ <span style={{ fontSize: 12, color: 'var(--text-tertiary)', fontFamily: 'var(--font-mono)' }}>+ {detail.id}+ </span>+ <span style={pill(detail.status === 'ready' ? 'emerald' : detail.status === 'error' ? 'rose' : 'amber')}>+ {detail.status}+ </span>+ </div>+ <div style={{ fontSize: 12, color: 'var(--text-secondary)', marginTop: 6, display: 'flex', gap: 14, flexWrap: 'wrap' }}>+ {detail.core && <span>core: <code style={codeInline}>{detail.core}</code></span>}+ {detail.model && <span>model: <code style={codeInline}>{detail.model}</code></span>}+ {detail.instance_id && <span>instance: <code style={codeInline}>{detail.instance_id.slice(0, 18)}…</code></span>}+ {sandboxId && <span>sandbox: <code style={codeInline}>{sandboxId}</code></span>}+ </div>+ {detail.current_operation && (+ <div style={{ fontSize: 11, color: 'var(--text-tertiary)', marginTop: 8, fontFamily: 'var(--font-mono)' }}>+ {detail.current_operation.kind} · {detail.current_operation.phase}+ {detail.current_operation.message ? ` — ${detail.current_operation.message}` : ''}+ </div>+ )}+ {detail.last_error && detail.status !== 'ready' && (+ <div style={{ fontSize: 12, color: 'var(--accent-rose, #f87171)', marginTop: 8 }}>+ {detail.last_error.phase}: {detail.last_error.message}+ </div>+ )}+ </div>+ <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', justifyContent: 'flex-end' }}>+ {(() => {+ const tg = entitlementsByFeature.telegram+ const needsUpgrade = tg && tg.entitled === false && tg.reason !== 'ungated'+ if (!needsUpgrade) return null+ const priceCents = tg.price_monthly_cents ?? 2000+ return (+ <button+ onClick={() => setTab('channels')}+ style={{+ background: 'rgba(99,102,241,0.08)',+ color: 'var(--accent-indigo, #818cf8)',+ border: '1px solid rgba(99,102,241,0.35)',+ padding: '6px 12px',+ borderRadius: 999,+ cursor: 'pointer',+ fontSize: 12,+ fontFamily: 'var(--font-body)',+ display: 'inline-flex',+ alignItems: 'center',+ gap: 6,+ }}+ title={`Subscribe to Telegram channel for $${(priceCents / 100).toFixed(0)}/mo`}+ >+ <span style={{ fontSize: 11 }}>★</span>+ Upgrade — ${(priceCents / 100).toFixed(0)}/mo+ </button>+ )+ })()}+ <button+ onClick={() =>+ act('restart core', () => restartAgent(agentId), 'Core restarted.')+ }+ disabled={!!acting}+ style={secondaryButton}+ title="Kill and respawn the core process; sandbox VM stays up."+ >+ {acting === 'restart core' ? <BusyLabel text="Restarting…" /> : 'Restart core'}+ </button>+ <button+ onClick={() =>+ sandboxId+ ? act('reboot sandbox', () => rebootSession(sandboxId), 'Sandbox rebooted.')+ : null+ }+ disabled={!!acting || !sandboxId}+ style={secondaryButton}+ title="Reboot the sandbox VM (guest kernel restart)."+ >+ {acting === 'reboot sandbox' ? <BusyLabel text="Rebooting…" /> : 'Reboot sandbox'}+ </button>+ <button onClick={handleDelete} disabled={!!acting} style={dangerButton}>+ {acting === 'delete' ? <BusyLabel text="Deleting…" /> : 'Delete'}+ </button>+ </div>+ </div>++ {detail.current_operation && detail.status !== 'ready' && (+ <BootingClawPanel operation={detail.current_operation} />+ )}++ {banner && (+ <div+ style={{+ padding: '10px 14px',+ borderRadius: 6,+ marginBottom: 14,+ fontSize: 13,+ background:+ banner.kind === 'error' ? 'rgba(248,113,113,0.08)'+ : banner.kind === 'success' ? 'rgba(52,211,153,0.08)'+ : 'rgba(99,102,241,0.08)',+ border: `1px solid ${+ banner.kind === 'error' ? 'rgba(248,113,113,0.3)'+ : banner.kind === 'success' ? 'rgba(52,211,153,0.3)'+ : 'rgba(99,102,241,0.3)'+ }`,+ display: 'flex', justifyContent: 'space-between', alignItems: 'center',+ }}+ >+ <span>{banner.text}</span>+ <button onClick={() => setBanner(null)} style={iconButton}>×</button>+ </div>+ )}++ {/* Tabs */}+ <div style={{ display: 'flex', borderBottom: '1px solid var(--border-subtle)', marginBottom: 18, gap: 4 }}>+ {(['overview', 'channels', 'plugins', 'events', 'logs', 'advanced'] as Tab[]).map((t) => (+ <button+ key={t}+ onClick={() => setTab(t)}+ style={{+ background: 'none',+ border: 'none',+ borderBottom: tab === t ? '2px solid var(--accent-indigo)' : '2px solid transparent',+ padding: '10px 14px',+ color: tab === t ? 'var(--text-primary)' : 'var(--text-secondary)',+ fontSize: 13,+ fontFamily: 'var(--font-body)',+ fontWeight: tab === t ? 600 : 400,+ cursor: 'pointer',+ textTransform: 'capitalize',+ }}+ >+ {t}+ </button>+ ))}+ </div>++ {tab === 'overview' && <OverviewTab agentId={agentId} detail={detail} />}+ {tab === 'channels' && (+ <ChannelsTab+ detail={detail}+ acting={acting}+ onAction={(label, fn, ok) => act(label, fn, ok)}+ />+ )}+ {tab === 'plugins' && (+ <PluginsTab+ detail={detail}+ acting={acting}+ onAction={(label, fn, ok) => act(label, fn, ok)}+ />+ )}+ {tab === 'events' && <EventsTab agentId={agentId} />}+ {tab === 'logs' && <LogsTab agentId={agentId} core={detail.core} />}+ {tab === 'advanced' && <AdvancedTab detail={detail} />}+ </div>+ )+}++function LogsTab({ agentId, core }: { agentId: string; core: string | null }) {+ const [content, setContent] = useState<string>('')+ const [error, setError] = useState<string | null>(null)+ const [paused, setPaused] = useState(false)+ const [loading, setLoading] = useState(true)+ const scrollRef = useRef<HTMLPreElement | null>(null)++ async function load() {+ try {+ const r = await getAgentLogs(agentId, 500)+ setContent(r.content)+ setError(null)+ } catch (err) {+ setError((err as Error).message)+ } finally {+ setLoading(false)+ }+ }++ useEffect(() => {+ if (paused) return+ void load()+ const interval = setInterval(() => void load(), 3000)+ return () => clearInterval(interval)+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [agentId, paused])++ // Stick to bottom when new content arrives, unless the user scrolled up.+ useEffect(() => {+ const el = scrollRef.current+ if (!el) return+ const distanceFromBottom = el.scrollHeight - el.scrollTop - el.clientHeight+ if (distanceFromBottom < 80) {+ el.scrollTop = el.scrollHeight+ }+ }, [content])++ if (core !== 'openclaw') {+ return (+ <p style={{ fontSize: 13, color: 'var(--text-tertiary)' }}>+ Process logs are only available for OpenClaw agents right now.+ </p>+ )+ }++ return (+ <div style={{ display: 'grid', gap: 10 }}>+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}>+ <div style={{ fontSize: 12, color: 'var(--text-tertiary)' }}>+ Tailing <code style={codeInline}>/tmp/openclaw-gateway.log</code> · refresh every 3s ·{' '}+ <span style={{ color: paused ? 'var(--accent-amber, #fbbf24)' : 'var(--accent-emerald, #34d399)' }}>+ {paused ? 'paused' : 'live'}+ </span>+ </div>+ <div style={{ display: 'flex', gap: 6 }}>+ <button+ onClick={() => setPaused((p) => !p)}+ style={secondaryButton}+ >+ {paused ? 'Resume' : 'Pause'}+ </button>+ <button onClick={() => void load()} style={secondaryButton}>Refresh</button>+ </div>+ </div>++ {error ? (+ <div style={{+ fontSize: 12, color: '#f87171',+ background: 'rgba(248,113,113,0.06)',+ border: '1px solid rgba(248,113,113,0.2)',+ padding: '8px 10px', borderRadius: 6,+ }}>+ {error}+ </div>+ ) : null}++ <pre+ ref={scrollRef}+ style={{+ fontSize: 11,+ fontFamily: 'var(--font-mono)',+ background: 'rgba(255,255,255,0.02)',+ border: '1px solid var(--border-subtle)',+ padding: 12,+ borderRadius: 6,+ margin: 0,+ height: '60vh',+ overflow: 'auto',+ whiteSpace: 'pre-wrap',+ wordBreak: 'break-word',+ color: 'var(--text-secondary)',+ }}+ >+ {loading && !content ? 'Loading…' : (content || '(no log lines yet)')}+ </pre>+ </div>+ )+}++function AdvancedTab({ detail }: { detail: AgentDetail }) {+ const navigate = useNavigate()+ const sandboxId = detail.sandbox_id+ return (+ <div style={{ display: 'grid', gap: 18, maxWidth: 720 }}>+ <Section title="Underlying sandbox">+ <p style={{ fontSize: 13, color: 'var(--text-secondary)', margin: 0 }}>+ Each managed agent runs inside an OC sandbox VM. Open the sandbox view to inspect+ processes, terminal access, preview URLs, reboot/power-cycle controls, and+ checkpoint history.+ </p>+ <div style={{ display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap', marginTop: 4 }}>+ {sandboxId ? (+ <>+ <code style={codeInline}>{sandboxId}</code>+ <button+ onClick={() => navigate(`/sessions/${encodeURIComponent(sandboxId)}`)}+ style={primaryButton}+ >+ Open sandbox details →+ </button>+ </>+ ) : (+ <span style={{ fontSize: 12, color: 'var(--text-tertiary)' }}>+ No sandbox provisioned yet.+ </span>+ )}+ </div>+ </Section>++ <Section title="Identifiers">+ <div style={{ display: 'grid', gap: 6, fontSize: 12 }}>+ <KVRow label="Agent ID" value={detail.id} />+ {detail.instance_id && <KVRow label="Instance ID" value={detail.instance_id} />}+ {sandboxId && <KVRow label="Sandbox ID" value={sandboxId} />}+ {detail.secret_store && <KVRow label="Secret store" value={detail.secret_store} />}+ {detail.core && <KVRow label="Core" value={detail.core} />}+ </div>+ </Section>++ <Section title="Raw config">+ <details>+ <summary style={{ cursor: 'pointer', fontSize: 12, color: 'var(--text-secondary)' }}>+ Show JSON+ </summary>+ <pre style={{+ fontSize: 11, fontFamily: 'var(--font-mono)',+ background: 'rgba(255,255,255,0.02)', border: '1px solid var(--border-subtle)',+ padding: 10, borderRadius: 6, overflow: 'auto', margin: '8px 0 0 0', maxHeight: 320,+ }}>+ {JSON.stringify(detail.config, null, 2)}+ </pre>+ </details>+ </Section>+ </div>+ )+}++function KVRow({ label, value }: { label: string; value: string }) {+ return (+ <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>+ <span style={{ color: 'var(--text-tertiary)', minWidth: 100 }}>{label}</span>+ <code style={{ ...codeInline, fontSize: 11, wordBreak: 'break-all' }}>{value}</code>+ </div>+ )+}++// ── Tabs ──────────────────────────────────────────────────────────++function OverviewTab({ agentId, detail }: { agentId: string; detail: AgentDetail }) {+ // Two-column layout: chat takes the bulk of the room; health summary+ // sits alongside as a compact side panel. Drops the JSON config dump+ // and other plumbing detail — the Events tab covers operational depth.+ return (+ <div+ style={{+ display: 'grid',+ gridTemplateColumns: 'minmax(0, 1fr) 280px',+ gap: 18,+ alignItems: 'start',+ }}+ >+ <ChatTab+ agentId={agentId}+ instanceId={detail.instance_id}+ disabled={detail.status !== 'ready'}+ />+ <HealthSidePanel detail={detail} />+ </div>+ )+}++function HealthSidePanel({ detail }: { detail: AgentDetail }) {+ const tone = detail.status === 'ready' ? 'emerald' : detail.status === 'error' ? 'rose' : 'amber'+ const channelTone = (status?: string) => status === 'connected' ? 'emerald' : status === 'error' ? 'rose' : 'amber'+ const packageTone = (status?: string) => status === 'installed' ? 'emerald' : status === 'error' ? 'rose' : 'amber'++ return (+ <aside+ style={{+ background: 'rgba(255,255,255,0.02)',+ border: '1px solid var(--border-subtle)',+ borderRadius: 10,+ padding: '16px 18px',+ display: 'grid',+ gap: 16,+ position: 'sticky',+ top: 16,+ }}+ >+ <div>+ <h3 style={sectionTitleStyle}>Health</h3>+ <div style={{ display: 'grid', gap: 8 }}>+ <HealthRow label="Agent" value={detail.status} tone={tone} />+ <HealthRow+ label="Core"+ value={detail.core_status?.status ?? 'unknown'}+ tone={+ detail.core_status?.status === 'ready' ? 'emerald'+ : detail.core_status?.status === 'error' ? 'rose' : 'amber'+ }+ />+ <HealthRow+ label="Instance"+ value={detail.instance_status ?? '—'}+ tone={detail.instance_status === 'running' ? 'emerald' : 'amber'}+ />+ </div>+ {detail.core_status?.message && detail.status !== 'ready' && (+ <div style={{ fontSize: 11, color: 'var(--text-tertiary)', marginTop: 8 }}>+ {detail.core_status.message}+ </div>+ )}+ </div>++ {Object.keys(detail.channel_status ?? {}).length > 0 && (+ <div>+ <h3 style={sectionTitleStyle}>Channels</h3>+ <div style={{ display: 'grid', gap: 6 }}>+ {Object.entries(detail.channel_status).map(([name, s]) => (+ <HealthRow+ key={name}+ label={name}+ value={s.status}+ tone={channelTone(s.status)}+ detail={s.message}+ />+ ))}+ </div>+ </div>+ )}++ {Object.keys(detail.package_status ?? {}).length > 0 && (+ <div>+ <h3 style={sectionTitleStyle}>Packages</h3>+ <div style={{ display: 'grid', gap: 6 }}>+ {Object.entries(detail.package_status).map(([name, s]) => (+ <HealthRow+ key={name}+ label={name}+ value={s.status}+ tone={packageTone(s.status)}+ detail={s.message}+ />+ ))}+ </div>+ </div>+ )}++ {detail.last_error && detail.status !== 'ready' && (+ <div>+ <h3 style={sectionTitleStyle}>Last error</h3>+ <div style={{+ fontSize: 11, fontFamily: 'var(--font-mono)',+ color: '#f87171',+ background: 'rgba(248,113,113,0.06)',+ border: '1px solid rgba(248,113,113,0.2)',+ padding: '8px 10px', borderRadius: 6,+ wordBreak: 'break-word',+ }}>+ <div style={{ color: '#fca5a5', marginBottom: 4 }}>{detail.last_error.phase}</div>+ {detail.last_error.message}+ </div>+ </div>+ )}+ </aside>+ )+}++const sectionTitleStyle: React.CSSProperties = {+ fontSize: 10,+ textTransform: 'uppercase',+ letterSpacing: '0.08em',+ color: 'var(--text-tertiary)',+ margin: '0 0 8px 0',+ fontFamily: 'var(--font-mono)',+ fontWeight: 600,+}++function HealthRow({+ label,+ value,+ tone,+ detail,+}: {+ label: string+ value: string+ tone: 'emerald' | 'amber' | 'rose'+ detail?: string+}) {+ return (+ <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8, fontSize: 12 }}>+ <span style={{ color: 'var(--text-secondary)', textTransform: 'capitalize' }}>{label}</span>+ <span style={pill(tone)}>{value}</span>+ </div>+ {detail && (+ <div style={{ fontSize: 11, color: 'var(--text-tertiary)', wordBreak: 'break-word' }}>+ {detail}+ </div>+ )}+ </div>+ )+}++function ChatTab({+ agentId,+ instanceId,+ disabled,+}: {+ agentId: string+ instanceId: string | null+ disabled: boolean+}) {+ type Msg = { role: 'user' | 'assistant' | 'system'; text: string }+ const [history, setHistory] = useState<Msg[]>([])+ const [input, setInput] = useState('')+ const [streaming, setStreaming] = useState(false)+ const [conversationId] = useState(() =>+ typeof crypto !== 'undefined' && 'randomUUID' in crypto ? crypto.randomUUID() : `c-${Date.now()}`,+ )+ const scrollRef = useRef<HTMLDivElement | null>(null)+ const inputRef = useRef<HTMLInputElement | null>(null)++ useEffect(() => {+ if (scrollRef.current) {+ scrollRef.current.scrollTop = scrollRef.current.scrollHeight+ }+ }, [history, streaming])++ // Refocus the composer when streaming ends (or starts disabled→enabled)+ // so the user can keep typing without grabbing the mouse.+ useEffect(() => {+ if (!streaming && !disabled) {+ inputRef.current?.focus()+ }+ }, [streaming, disabled])++ async function send() {+ if (!input.trim() || !instanceId || streaming) return+ const userMsg = input.trim()+ setInput('')+ // Build the full history we'll send to the gateway BEFORE we mutate+ // local state. Includes every prior user/assistant turn (skipping+ // 'system' rows we generate locally for error display) plus the+ // new user turn. Empty-text turns are dropped — the placeholder+ // assistant bubble we add for UX must not be sent.+ const apiHistory = history+ .filter((m) => (m.role === 'user' || m.role === 'assistant') && m.text.length > 0)+ .map((m) => ({ role: m.role as 'user' | 'assistant', content: m.text }))+ apiHistory.push({ role: 'user', content: userMsg })++ setHistory((h) => [...h, { role: 'user', text: userMsg }, { role: 'assistant', text: '' }])+ setStreaming(true)+ let receivedText = false+ let saw_done = false+ try {+ for await (const ev of streamAgentChat(agentId, instanceId, userMsg, conversationId, apiHistory)) {+ if (ev.type === 'text' && ev.content) {+ receivedText = true+ setHistory((h) => {+ const next = [...h]+ const last = next[next.length - 1]+ if (last && last.role === 'assistant') {+ next[next.length - 1] = { ...last, text: last.text + ev.content }+ }+ return next+ })+ } else if (ev.type === 'done') {+ saw_done = true+ break+ }+ }+ // Stream closed without producing any assistant text — almost always+ // means the agent runtime failed to start inside the sandbox (missing+ // ANTHROPIC_API_KEY, claude CLI not found, etc). Surface it instead of+ // leaving the user staring at an empty bubble.+ if (!receivedText) {+ setHistory((h) => {+ const next = [...h]+ // Replace the empty assistant placeholder with a system error+ if (next[next.length - 1]?.role === 'assistant' && !next[next.length - 1].text) {+ next.pop()+ }+ next.push({+ role: 'system',+ text: saw_done+ ? 'Agent ended the turn without sending any text. Likely the OpenClaw chat-completions endpoint is disabled (snapshot needs gateway.http.endpoints.chatCompletions.enabled=true), or OPENROUTER_API_KEY is missing from the agent\'s secret store.'+ : 'Stream closed before any response. Likely sessions-api or the proxy timed out.',+ })+ return next+ })+ }+ } catch (err) {+ setHistory((h) => {+ const next = [...h]+ if (next[next.length - 1]?.role === 'assistant' && !next[next.length - 1].text) {+ next.pop()+ }+ next.push({ role: 'system', text: `Error: ${(err as Error).message}` })+ return next+ })+ } finally {+ setStreaming(false)+ }+ }++ if (!instanceId) {+ return (+ <p style={{ color: 'var(--text-tertiary)', fontSize: 13 }}>+ Agent has no instance yet. Once the sandbox is up you'll be able to chat here.+ </p>+ )+ }++ return (+ <div style={{ display: 'flex', flexDirection: 'column', height: '60vh', minHeight: 400 }}>+ <div+ ref={scrollRef}+ style={{+ flex: 1,+ overflowY: 'auto',+ background: 'rgba(255,255,255,0.02)',+ border: '1px solid var(--border-subtle)',+ borderRadius: 8,+ padding: 16,+ marginBottom: 12,+ display: 'flex',+ flexDirection: 'column',+ gap: 10,+ }}+ >+ {history.length === 0 && (+ <p style={{ color: 'var(--text-tertiary)', fontSize: 13, margin: 0 }}>+ Talk to the agent here. Messages don't go through Telegram — direct via the platform's instance API.+ </p>+ )}+ {history.map((m, i) => (+ <div key={i} style={{+ alignSelf: m.role === 'user' ? 'flex-end' : 'flex-start',+ maxWidth: '78%',+ background: m.role === 'user'+ ? 'var(--gradient-primary, #6366f1)'+ : m.role === 'system' ? 'rgba(248,113,113,0.1)'+ : 'rgba(255,255,255,0.04)',+ color: m.role === 'user' ? '#fff' : m.role === 'system' ? '#f87171' : 'var(--text-primary)',+ padding: '8px 12px',+ borderRadius: 10,+ fontSize: 13,+ whiteSpace: 'pre-wrap',+ border: m.role === 'system' ? '1px solid rgba(248,113,113,0.3)' : 'none',+ }}>+ {m.text || (streaming && m.role === 'assistant' && i === history.length - 1 ? '…' : '')}+ </div>+ ))}+ </div>++ <form+ onSubmit={(e) => { e.preventDefault(); void send() }}+ style={{ display: 'flex', gap: 8 }}+ >+ <input+ ref={inputRef}+ value={input}+ onChange={(e) => setInput(e.target.value)}+ placeholder={disabled ? 'Agent not ready' : 'Send a message…'}+ disabled={disabled || streaming}+ style={{ ...input1, flex: 1 }}+ autoFocus+ />+ <button type="submit" disabled={disabled || streaming || !input.trim()} style={primaryButton}>+ {streaming ? <BusyLabel text="Sending…" /> : 'Send'}+ </button>+ </form>+ </div>+ )+}++function ChannelsTab({+ detail,+ acting,+ onAction,+}: {+ detail: AgentDetail+ acting: string | null+ onAction: <T>(label: string, fn: () => Promise<T>, ok: string) => Promise<void>+}) {+ const [telegramModal, setTelegramModal] = useState(false)+ const [paywallModal, setPaywallModal] = useState(false)+ const [subscribing, setSubscribing] = useState(false)+ const [entitlements, setEntitlements] = useState<Record<string, AgentEntitlement>>({})+ const telegramConnected = detail.channels.some((c) => c.name === 'telegram')+ const canMutate = detail.core !== null++ async function refreshEntitlements() {+ try {+ const res = await listAgentEntitlements(detail.id)+ const map: Record<string, AgentEntitlement> = {}+ for (const e of res.entitlements) map[e.feature] = e+ setEntitlements(map)+ } catch {+ // best-effort: leave previous state+ }+ }++ useEffect(() => {+ void refreshEntitlements()+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [detail.id])++ if (!canMutate) {+ return (+ <p style={{ fontSize: 13, color: 'var(--text-tertiary)' }}>+ This agent has no managed core, so channels aren't applicable.+ </p>+ )+ }++ const telegramEntitlement = entitlements.telegram+ const telegramEntitled = telegramEntitlement?.entitled !== false // undefined treated as entitled (loading) to avoid flash+ const telegramUngated = telegramEntitlement?.reason === 'ungated'+ const telegramPriceCents = telegramEntitlement?.price_monthly_cents ?? 2000++ async function handleTelegramAction() {+ if (telegramConnected) {+ // Already connected — manage flow+ setTelegramModal(true)+ return+ }+ if (!telegramEntitled) {+ // Show paywall first+ setPaywallModal(true)+ return+ }+ // Entitled but not connected — connect flow+ setTelegramModal(true)+ }++ async function handleSubscribe() {+ setSubscribing(true)+ try {+ const result = await subscribeAgentFeature(detail.id, 'telegram')+ if (result.status === 'checkout_required') {+ // Bounce to Stripe Checkout for first-time card capture.+ // Intentional: we lose the "open the connect modal next" flow,+ // because Stripe redirects out and back. The user comes back+ // to /agents/:id/?success=true and has to click Connect again+ // — entitlement check will pass at that point.+ window.location.href = result.checkout_url+ return+ }+ // active / already_subscribed / ungated → entitled now+ await refreshEntitlements()+ setPaywallModal(false)+ setTelegramModal(true)+ } catch (err) {+ alert(`Subscription failed: ${(err as Error).message}`)+ } finally {+ setSubscribing(false)+ }+ }++ return (+ <>+ <div style={integrationGrid}>+ <IntegrationCard+ tag="channel"+ accent="sky"+ icon="✈️"+ name="Telegram"+ description={+ telegramUngated+ ? 'Talk to the agent through a Telegram bot. (Paywall not configured on this deployment.)'+ : telegramEntitled+ ? 'Talk to the agent through a Telegram bot.'+ : `Talk to the agent through a Telegram bot. $${(telegramPriceCents / 100).toFixed(0)}/mo per agent.`+ }+ status={telegramConnected ? 'connected' : 'available'}+ actionLabel={+ telegramConnected+ ? 'Configure'+ : telegramEntitled+ ? 'Connect'+ : `Subscribe & connect — $${(telegramPriceCents / 100).toFixed(0)}/mo`+ }+ actionTone={telegramConnected ? 'secondary' : 'primary'}+ busy={acting === 'connect telegram' || acting === 'disconnect telegram'}+ disabled={!!acting}+ onAction={handleTelegramAction}+ />++ {COMING_SOON_CHANNELS.map((it) => (+ <IntegrationCard+ key={it.name}+ tag="channel"+ accent="muted"+ icon={it.icon}+ name={it.name}+ description={it.description}+ status="coming"+ />+ ))}+ </div>++ {paywallModal && (+ <TelegramPaywallModal+ priceCents={telegramPriceCents}+ subscribing={subscribing}+ onClose={() => setPaywallModal(false)}+ onSubscribe={handleSubscribe}+ />+ )}++ {telegramModal && (+ <TelegramConnectModal+ alreadyConnected={telegramConnected}+ ungated={telegramUngated}+ subscriptionActive={!!entitlements.telegram?.entitled && !telegramUngated}+ subscriptionWillCancel={!!entitlements.telegram?.cancel_at_period_end}+ subscriptionRenewsAt={entitlements.telegram?.current_period_end}+ onClose={() => setTelegramModal(false)}+ onSubmit={async (token) => {+ setTelegramModal(false)+ await onAction(+ 'connect telegram',+ () => connectTelegram(detail.id, token),+ telegramConnected+ ? 'Telegram bot token updated — webhook re-registered.'+ : 'Telegram connect queued — webhook will register shortly.',+ )+ }}+ onDisconnect={async () => {+ setTelegramModal(false)+ await onAction(+ 'disconnect telegram',+ () => disconnectTelegram(detail.id),+ 'Telegram disconnected.',+ )+ }}+ onCancelSubscription={async () => {+ try {+ await cancelAgentFeature(detail.id, 'telegram')+ await refreshEntitlements()+ setTelegramModal(false)+ alert('Subscription scheduled to cancel at period end. Telegram remains active until then.')+ } catch (err) {+ alert(`Cancel failed: ${(err as Error).message}`)+ }+ }}+ />+ )}+ </>+ )+}++function TelegramPaywallModal({+ priceCents,+ subscribing,+ onClose,+ onSubscribe,+}: {+ priceCents: number+ subscribing: boolean+ onClose: () => void+ onSubscribe: () => Promise<void>+}) {+ return (+ <div+ onClick={onClose}+ style={{+ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.5)', zIndex: 100,+ display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20,+ }}+ >+ <div+ onClick={(e) => e.stopPropagation()}+ style={{+ background: 'var(--bg-deep)',+ border: '1px solid var(--border-subtle)',+ borderRadius: 12, width: '100%', maxWidth: 460, padding: 22,+ }}+ >+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14 }}>+ <h2 style={{ fontSize: 16, margin: 0, fontFamily: 'var(--font-display)' }}>Subscribe to Telegram for this agent</h2>+ <button onClick={onClose} style={iconButton}>×</button>+ </div>+ <div style={{ fontSize: 13, color: 'var(--text-secondary)', lineHeight: 1.6, marginBottom: 16 }}>+ Connecting Telegram to a managed agent costs <b>${(priceCents / 100).toFixed(0)}/month</b>. Each agent+ you connect to Telegram is billed separately. Cancel any time — service runs to the end of the+ current billing period.+ </div>+ <div style={{+ background: 'rgba(99,102,241,0.08)',+ border: '1px solid rgba(99,102,241,0.2)',+ borderRadius: 6, padding: '10px 12px',+ fontSize: 12, color: 'var(--text-secondary)', marginBottom: 16,+ }}>+ Your card on file will be charged immediately and prorated to the end of the current billing+ period. If no card is on file, Stripe Checkout will collect one.+ </div>+ <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>+ <button type="button" onClick={onClose} style={secondaryButton}>Cancel</button>+ <button onClick={() => void onSubscribe()} disabled={subscribing} style={primaryButton}>+ {subscribing ? <BusyLabel text="Subscribing…" /> : `Subscribe — $${(priceCents / 100).toFixed(0)}/mo`}+ </button>+ </div>+ </div>+ </div>+ )+}++function PluginsTab({+ detail,+ acting,+ onAction,+}: {+ detail: AgentDetail+ acting: string | null+ onAction: <T>(label: string, fn: () => Promise<T>, ok: string) => Promise<void>+}) {+ const hasGbrain = detail.packages.some((p) => p.name === 'gbrain')+ const canMutate = detail.core !== null+ const gbrainStatus = detail.package_status?.gbrain+ // package_status reflects the latest install attempt; agent.packages+ // only contains successfully-installed packages. Surface install+ // progress and failures from package_status here, scoped to this card,+ // since the agent itself stays "ready" (the failure is plugin-local).+ const gbrainInstalling = gbrainStatus?.status === 'installing'+ const gbrainErrored = gbrainStatus?.status === 'error'+ const gbrainErrorMessage = gbrainErrored ? (gbrainStatus?.message ?? 'Install failed') : undefined++ if (!canMutate) {+ return (+ <p style={{ fontSize: 13, color: 'var(--text-tertiary)' }}>+ This agent has no managed core, so plugins aren't applicable.+ </p>+ )+ }++ // Card shape for gbrain depends on three independent signals:+ // - hasGbrain (agent.packages has it → the success terminal state)+ // - gbrainInstalling (in-flight)+ // - gbrainErrored (last attempt failed, packageStatus carries the reason)+ let gbrainCardStatus: IntegrationStatus = hasGbrain ? 'connected' : 'available'+ let gbrainStatusLabel: string | undefined = hasGbrain ? 'installed' : undefined+ let gbrainActionLabel: string | undefined = hasGbrain ? 'Uninstall' : 'Install'+ let gbrainActionTone: ActionTone = hasGbrain ? 'danger' : 'primary'+ if (gbrainInstalling) {+ gbrainStatusLabel = 'installing…'+ gbrainActionLabel = undefined // no action while in-flight+ } else if (gbrainErrored) {+ gbrainCardStatus = 'error'+ gbrainStatusLabel = 'install failed'+ gbrainActionLabel = 'Retry'+ gbrainActionTone = 'primary'+ }++ return (+ <div style={integrationGrid}>+ <IntegrationCard+ tag="plugin"+ accent="indigo"+ icon="🧠"+ name="gbrain"+ description="Long-term memory + vector recall."+ status={gbrainCardStatus}+ statusLabel={gbrainStatusLabel}+ errorMessage={gbrainErrorMessage}+ actionLabel={gbrainActionLabel}+ actionTone={gbrainActionTone}+ // The "Clear" button on errored state runs uninstall — that's the+ // only path that wipes packageStatus.gbrain on the backend, since+ // install never resets the previous error before queuing.+ secondaryActionLabel={gbrainErrored ? 'Clear' : undefined}+ secondaryActionTone="secondary"+ onSecondaryAction={+ gbrainErrored+ ? () => onAction('clear gbrain error', () => uninstallGbrain(detail.id), 'gbrain install state cleared.')+ : undefined+ }+ busy={acting === 'install gbrain' || acting === 'uninstall gbrain' || acting === 'clear gbrain error'}+ disabled={!!acting}+ onAction={+ gbrainActionLabel+ ? () =>+ hasGbrain+ ? onAction('uninstall gbrain', () => uninstallGbrain(detail.id), 'gbrain uninstalled.')+ : onAction('install gbrain', () => installGbrain(detail.id), 'gbrain install queued.')+ : undefined+ }+ />++ {COMING_SOON_PLUGINS.map((it) => (+ <IntegrationCard+ key={it.name}+ tag="plugin"+ accent="muted"+ icon={it.icon}+ name={it.name}+ description={it.description}+ status="coming"+ />+ ))}+ </div>+ )+}++// Inspired by Pipedream Connect's most-popular integrations — surfaces+// what the agent will eventually be able to act on without misleading+// users about current capability.+const COMING_SOON_PLUGINS: Array<{ icon: string; name: string; description: string }> = [+ { icon: '📝', name: 'Notion', description: 'Read/write pages and databases.' },+ { icon: '🐙', name: 'GitHub', description: 'Issues, PRs, comments, files.' },+ { icon: '#', name: 'Slack', description: 'Post messages, react, search.' },+ { icon: '📧', name: 'Gmail', description: 'Read/send mail, labels, drafts.' },+ { icon: '📅', name: 'Google Calendar', description: 'Events, scheduling, busy/free.' },+ { icon: '📄', name: 'Google Drive', description: 'Search, read, share files.' },+ { icon: '🎫', name: 'Linear', description: 'Issues, cycles, projects.' },+ { icon: '🎨', name: 'Figma', description: 'Files, comments, frames.' },+ { icon: '💳', name: 'Stripe', description: 'Customers, payments, subscriptions.' },+ { icon: '🛠️', name: 'MCP servers', description: 'Bring your own tool integrations.' },+]++const integrationGrid: React.CSSProperties = {+ display: 'grid',+ gridTemplateColumns: 'repeat(auto-fill, minmax(220px, 1fr))',+ gap: 14,+}++const COMING_SOON_CHANNELS: Array<{ icon: string; name: string; description: string }> = [+ { icon: '💬', name: 'Discord', description: 'Server chat + DMs.' },+ { icon: '📱', name: 'WhatsApp', description: 'Cloud API webhook.' },+ { icon: '#', name: 'Slack', description: 'Workspace bot.' },+ { icon: '✉️', name: 'Email', description: 'IMAP / inbound webhook.' },+]++type IntegrationStatus = 'connected' | 'available' | 'coming' | 'error'+type IntegrationAccent = 'indigo' | 'sky' | 'muted'+type ActionTone = 'primary' | 'secondary' | 'danger'++function IntegrationCard({+ tag,+ accent,+ icon,+ name,+ description,+ status,+ statusLabel,+ errorMessage,+ actionLabel,+ actionTone,+ secondaryActionLabel,+ secondaryActionTone,+ onSecondaryAction,+ busy,+ disabled,+ onAction,+}: {+ tag: 'channel' | 'plugin'+ accent: IntegrationAccent+ icon: string+ name: string+ description: string+ status: IntegrationStatus+ statusLabel?: string+ errorMessage?: string+ actionLabel?: string+ actionTone?: ActionTone+ secondaryActionLabel?: string+ secondaryActionTone?: ActionTone+ onSecondaryAction?: () => void+ busy?: boolean+ disabled?: boolean+ onAction?: () => void+}) {+ const accentColor =+ accent === 'indigo' ? 'rgba(99,102,241,0.7)'+ : accent === 'sky' ? 'rgba(56,189,248,0.7)'+ : 'rgba(255,255,255,0.12)'++ return (+ <div+ style={{+ background: 'rgba(255,255,255,0.02)',+ border: '1px solid var(--border-subtle)',+ borderRadius: 10,+ padding: 14,+ display: 'flex',+ flexDirection: 'column',+ gap: 12,+ opacity: status === 'coming' ? 0.55 : 1,+ minHeight: 168,+ }}+ >+ <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 8 }}>+ <div+ style={{+ width: 34, height: 34, borderRadius: 8,+ background: `linear-gradient(135deg, ${accentColor}, rgba(255,255,255,0.04))`,+ display: 'flex', alignItems: 'center', justifyContent: 'center',+ fontSize: 18,+ }}+ aria-hidden+ >+ {icon}+ </div>+ <span style={{+ fontSize: 9,+ textTransform: 'uppercase',+ letterSpacing: '0.08em',+ color: 'var(--text-tertiary)',+ fontFamily: 'var(--font-mono)',+ }}>+ {tag}+ </span>+ </div>++ <div style={{ flex: 1 }}>+ <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--text-primary)' }}>{name}</div>+ <div style={{ fontSize: 12, color: 'var(--text-secondary)', marginTop: 4, lineHeight: 1.4 }}>+ {description}+ </div>+ </div>++ {status === 'connected' && (+ <span style={pill('emerald')}>{statusLabel ?? 'connected'}</span>+ )}+ {status === 'error' && (+ <span style={pill('rose')}>{statusLabel ?? 'error'}</span>+ )}+ {status === 'coming' && (+ <span style={{+ alignSelf: 'flex-start',+ fontSize: 10, fontFamily: 'var(--font-mono)',+ color: 'var(--text-tertiary)',+ background: 'rgba(255,255,255,0.04)',+ border: '1px solid var(--border-subtle)',+ padding: '3px 8px', borderRadius: 999,+ textTransform: 'uppercase', letterSpacing: '0.08em',+ }}>+ coming soon+ </span>+ )}++ {errorMessage && (+ <div style={{+ fontSize: 11,+ color: 'rgba(252,165,165,0.95)',+ background: 'rgba(239,68,68,0.08)',+ border: '1px solid rgba(239,68,68,0.25)',+ borderRadius: 6,+ padding: '6px 8px',+ lineHeight: 1.4,+ fontFamily: 'var(--font-mono)',+ whiteSpace: 'pre-wrap',+ wordBreak: 'break-word',+ }}>+ {errorMessage}+ </div>+ )}++ {(actionLabel || secondaryActionLabel) && status !== 'coming' && (+ <div style={{ display: 'flex', gap: 8 }}>+ {actionLabel && (+ <button+ onClick={onAction}+ disabled={disabled || busy}+ style={+ actionTone === 'danger' ? dangerButton+ : actionTone === 'secondary' ? secondaryButton+ : primaryButton+ }+ >+ {busy ? <BusyLabel text="Working…" /> : actionLabel}+ </button>+ )}+ {secondaryActionLabel && (+ <button+ onClick={onSecondaryAction}+ disabled={disabled || busy}+ style={+ secondaryActionTone === 'danger' ? dangerButton+ : secondaryActionTone === 'primary' ? primaryButton+ : secondaryButton+ }+ >+ {secondaryActionLabel}+ </button>+ )}+ </div>+ )}+ </div>+ )+}++function TelegramConnectModal({+ alreadyConnected,+ ungated,+ subscriptionActive,+ subscriptionWillCancel,+ subscriptionRenewsAt,+ onClose,+ onSubmit,+ onDisconnect,+ onCancelSubscription,+}: {+ alreadyConnected: boolean+ ungated: boolean+ subscriptionActive: boolean+ subscriptionWillCancel: boolean+ subscriptionRenewsAt?: string+ onClose: () => void+ onSubmit: (token: string) => void | Promise<void>+ onDisconnect: () => void | Promise<void>+ onCancelSubscription: () => void | Promise<void>+}) {+ const [token, setToken] = useState('')+ const title = alreadyConnected ? 'Configure Telegram' : 'Connect Telegram'+ return (+ <div+ onClick={onClose}+ style={{+ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.5)', zIndex: 100,+ display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20,+ }}+ >+ <div+ onClick={(e) => e.stopPropagation()}+ style={{+ background: 'var(--bg-deep)',+ border: '1px solid var(--border-subtle)',+ borderRadius: 12, width: '100%', maxWidth: 460, padding: 22,+ }}+ >+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>+ <h2 style={{ fontSize: 16, margin: 0, fontFamily: 'var(--font-display)' }}>{title}</h2>+ <button onClick={onClose} style={iconButton}>×</button>+ </div>++ {alreadyConnected && (+ <p style={{ fontSize: 12, color: 'var(--text-secondary)', margin: '0 0 14px 0', lineHeight: 1.5 }}>+ Telegram is currently connected. Paste a new bot token to swap it,+ or disconnect to detach this agent from Telegram entirely.+ </p>+ )}++ {ungated && (+ <div style={{+ background: 'rgba(251,191,36,0.08)',+ border: '1px solid rgba(251,191,36,0.25)',+ borderRadius: 6, padding: '8px 12px', marginBottom: 14,+ fontSize: 12, color: 'var(--text-secondary)',+ }}>+ <b style={{ color: '#fbbf24' }}>Not gated yet</b> on this deployment — connect proceeds without+ a subscription. Set <code style={codeInline}>STRIPE_TELEGRAM_AGENT_PRICE_ID</code> on the server+ to enable the paywall.+ </div>+ )}++ {!ungated && subscriptionActive && (+ <div style={{+ background: 'rgba(52,211,153,0.08)',+ border: '1px solid rgba(52,211,153,0.2)',+ borderRadius: 6, padding: '8px 12px', marginBottom: 14,+ fontSize: 12, color: 'var(--text-secondary)',+ }}>+ {subscriptionWillCancel ? (+ <>+ Subscription <b>scheduled to cancel</b>+ {subscriptionRenewsAt && ` on ${new Date(subscriptionRenewsAt).toLocaleDateString()}`}+ . Telegram remains active until then.+ </>+ ) : (+ <>+ Subscription <b style={{ color: '#34d399' }}>active</b>+ {subscriptionRenewsAt && ` · renews ${new Date(subscriptionRenewsAt).toLocaleDateString()}`}+ .{' '}+ <button+ type="button"+ onClick={() => {+ if (window.confirm('Cancel Telegram subscription? Service continues until period end.')) {+ void onCancelSubscription()+ }+ }}+ style={{ background: 'none', border: 'none', color: 'var(--accent-rose, #f87171)', cursor: 'pointer', padding: 0, fontSize: 12, textDecoration: 'underline' }}+ >+ Cancel subscription+ </button>+ </>+ )}+ </div>+ )}++ <form+ onSubmit={(e) => { e.preventDefault(); if (token.trim()) void onSubmit(token.trim()) }}+ style={{ display: 'grid', gap: 14 }}+ >+ <Field+ label={alreadyConnected ? 'New bot token' : 'Bot token'}+ hint="Paste the token @BotFather gave you. Stored in this agent's secret store."+ >+ <input+ autoFocus+ value={token}+ onChange={(e) => setToken(e.target.value)}+ placeholder="1234567890:AAA…"+ style={input1}+ />+ </Field>+ <div style={{ display: 'flex', gap: 8, justifyContent: 'space-between', alignItems: 'center' }}>+ {alreadyConnected ? (+ <button+ type="button"+ onClick={() => {+ if (window.confirm('Disconnect Telegram from this agent? Subscription remains active until cancelled separately.')) {+ void onDisconnect()+ }+ }}+ style={dangerButton}+ >+ Disconnect+ </button>+ ) : <span />}+ <div style={{ display: 'flex', gap: 8 }}>+ <button type="button" onClick={onClose} style={secondaryButton}>Cancel</button>+ <button type="submit" disabled={!token.trim()} style={primaryButton}>+ {alreadyConnected ? 'Update' : 'Connect'}+ </button>+ </div>+ </div>+ </form>+ </div>+ </div>+ )+}++function EventsTab({ agentId }: { agentId: string }) {+ const [events, setEvents] = useState<AgentEventRow[]>([])+ const [operations, setOperations] = useState<AgentOperation[]>([])+ const [loading, setLoading] = useState(true)++ async function load() {+ try {+ const [e, o] = await Promise.all([+ getAgentEvents(agentId, 100),+ getAgentOperations(agentId, 30),+ ])+ setEvents(e.events)+ setOperations(o.operations)+ } catch {+ // silent — UI will just show nothing+ } finally {+ setLoading(false)+ }+ }++ useEffect(() => {+ void load()+ const interval = setInterval(() => void load(), 5000)+ return () => clearInterval(interval)+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [agentId])++ if (loading) {+ return (+ <div style={{ display: 'flex', alignItems: 'center', gap: 10, color: 'var(--text-tertiary)', fontSize: 13 }}>+ <span className="loading-spinner" style={{ width: 14, height: 14, borderWidth: 1.5 }} />+ Loading events…+ </div>+ )+ }++ return (+ <div style={{ display: 'grid', gap: 22 }}>+ <Section title="Events">+ {events.length === 0 ? (+ <p style={{ fontSize: 12, color: 'var(--text-tertiary)' }}>No events yet.</p>+ ) : (+ <div style={{ display: 'grid', gap: 6 }}>+ {events.map((e) => (+ <div key={e.id} style={{+ fontSize: 12,+ fontFamily: 'var(--font-mono)',+ display: 'flex', gap: 10,+ padding: '6px 10px',+ background: 'rgba(255,255,255,0.02)',+ borderLeft: `2px solid ${e.type === 'error' ? '#f87171' : e.type === 'warning' ? '#fbbf24' : '#6366f1'}`,+ borderRadius: 4,+ }}>+ <span style={{ color: 'var(--text-tertiary)', flexShrink: 0 }}>{new Date(e.at).toLocaleTimeString()}</span>+ <span style={{ color: e.type === 'error' ? '#f87171' : e.type === 'warning' ? '#fbbf24' : 'var(--text-secondary)', flexShrink: 0 }}>+ {e.phase}+ </span>+ <span style={{ color: 'var(--text-primary)', wordBreak: 'break-word' }}>{e.message}</span>+ </div>+ ))}+ </div>+ )}+ </Section>++ <Section title="Operations">+ {operations.length === 0 ? (+ <p style={{ fontSize: 12, color: 'var(--text-tertiary)' }}>No operations recorded.</p>+ ) : (+ <div style={{ display: 'grid', gap: 6 }}>+ {operations.map((op) => (+ <div key={op.id} style={{+ fontSize: 12,+ display: 'flex', gap: 10,+ padding: '6px 10px',+ background: 'rgba(255,255,255,0.02)',+ borderRadius: 4,+ }}>+ <span style={{ color: 'var(--text-tertiary)', fontFamily: 'var(--font-mono)', flexShrink: 0 }}>+ {new Date(op.created_at).toLocaleTimeString()}+ </span>+ <span style={{ color: 'var(--text-primary)', fontFamily: 'var(--font-mono)', flexShrink: 0 }}>+ {op.kind}+ </span>+ {op.target_key && <span style={{ color: 'var(--text-tertiary)' }}>{op.target_key}</span>}+ <span style={pill(op.state === 'success' ? 'emerald' : op.state === 'error' ? 'rose' : 'amber')}>+ {op.state}+ </span>+ {op.message && <span style={{ color: 'var(--text-secondary)', wordBreak: 'break-word' }}>{op.message}</span>}+ </div>+ ))}+ </div>+ )}+ </Section>+ </div>+ )+}++// ── helpers ─────────────────────────────────────────────────────++function Section({ title, children }: { title: string; children: React.ReactNode }) {+ return (+ <div>+ <h3 style={{+ fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.06em',+ color: 'var(--text-tertiary)', marginBottom: 10, fontFamily: 'var(--font-mono)',+ }}>+ {title}+ </h3>+ <div style={{ display: 'grid', gap: 8 }}>{children}</div>+ </div>+ )+}++function Field({ label, hint, children }: { label: string; hint?: string; children: React.ReactNode }) {+ return (+ <label style={{ display: 'grid', gap: 4 }}>+ <span style={{ fontSize: 12, color: 'var(--text-secondary)', fontWeight: 500 }}>{label}</span>+ {children}+ {hint && <span style={{ fontSize: 11, color: 'var(--text-tertiary)' }}>{hint}</span>}+ </label>+ )+}++function BusyLabel({ text }: { text: string }) {+ return (+ <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>+ <span+ className="loading-spinner"+ style={{ width: 11, height: 11, borderWidth: 1.5, borderColor: 'rgba(255,255,255,0.25)', borderTopColor: 'currentColor' }}+ />+ {text}+ </span>+ )+}++function pill(tone: 'emerald' | 'amber' | 'rose'): React.CSSProperties {+ const palette = {+ emerald: { bg: 'rgba(52,211,153,0.12)', border: 'rgba(52,211,153,0.35)', fg: '#34d399' },+ amber: { bg: 'rgba(251,191,36,0.12)', border: 'rgba(251,191,36,0.35)', fg: '#fbbf24' },+ rose: { bg: 'rgba(248,113,113,0.12)', border: 'rgba(248,113,113,0.35)', fg: '#f87171' },+ }[tone]+ return {+ background: palette.bg, border: `1px solid ${palette.border}`, color: palette.fg,+ padding: '3px 9px', borderRadius: 999, fontSize: 11, fontWeight: 500, fontFamily: 'var(--font-mono)',+ }+}++const primaryButton: React.CSSProperties = {+ background: 'var(--gradient-primary, #6366f1)', color: '#fff',+ padding: '8px 14px', border: 'none', borderRadius: 6, cursor: 'pointer',+ fontSize: 13, fontWeight: 600, fontFamily: 'var(--font-body)',+}+const secondaryButton: React.CSSProperties = {+ background: 'rgba(255,255,255,0.04)', color: 'var(--text-primary)',+ padding: '7px 12px', border: '1px solid var(--border-subtle)', borderRadius: 6,+ cursor: 'pointer', fontSize: 12, fontFamily: 'var(--font-body)',+}+const dangerButton: React.CSSProperties = {+ background: 'rgba(248,113,113,0.08)', color: '#f87171',+ padding: '7px 12px', border: '1px solid rgba(248,113,113,0.35)', borderRadius: 6,+ cursor: 'pointer', fontSize: 12, fontFamily: 'var(--font-body)',+}+const iconButton: React.CSSProperties = {+ background: 'none', border: 'none', color: 'var(--text-tertiary)',+ cursor: 'pointer', fontSize: 22, padding: 0, width: 22, height: 22, lineHeight: 1,+}+const input1: React.CSSProperties = {+ background: 'rgba(255,255,255,0.02)', border: '1px solid var(--border-subtle)',+ borderRadius: 6, padding: '8px 10px',+ color: 'var(--text-primary)', fontSize: 13, fontFamily: 'var(--font-body)', outline: 'none',+}+const codeInline: React.CSSProperties = {+ fontFamily: 'var(--font-mono)', background: 'rgba(255,255,255,0.04)',+ padding: '1px 5px', borderRadius: 3, fontSize: 10.5,+}++// ── Booting claw panel ─────────────────────────────────────────────────+//+// Shown while a managed agent has an in-flight current_operation. Existing+// raw-status copy is intentionally engineery ("create_instance · pull_image+// — pulling opencomputerdeveuacr.azurecr.io/openclaw-managed:2026.5.2-npm")+// — perfect for debugging, miserable to stare at for ~30s on cold start.+// This panel translates that into something with a heartbeat: the OpenClaw+// lobster mark animated, a friendly per-phase headline, and a rotating+// flavour-text subtitle so the page feels alive rather than stuck.+//+// Psychology: research on progress-bar perception (Harrison et al, CHI '07)+// suggests that *any* movement reduces perceived wait time, and rotating+// micro-copy creates the illusion of forward progress even when the+// underlying step is genuinely slow (a 4 GB docker pull doesn't move per-+// frame). We just need to look busy convincingly.+const PHASE_LABELS: Record<string, string> = {+ queued: 'Queued',+ provision_sandbox: 'Carving out a fresh tide pool',+ pull_image: 'Reeling in the lobster',+ start_entrypoint: 'Lighting the burner',+ wait_core_ready: 'Warming up the gateway',+ materialize_declared_state: 'Dressing the claw',+ install_gbrain: 'Wiring up the long-term memory',+ uninstall_gbrain: 'Pulling out the memory module',+ connect_telegram: 'Threading the Telegram leash',+ disconnect_telegram: 'Unhooking Telegram',+ configure_channel: 'Configuring the channel',+}++// Rotating subtitles by phase. Random selection on each tick keeps the+// page feeling lively without claiming progress that hasn't happened.+const PHASE_FLAVOUR: Record<string, string[]> = {+ queued: [+ 'In line behind some other lobsters…',+ 'Politely waiting our turn',+ 'The maître d\' is checking the list',+ ],+ provision_sandbox: [+ 'Booting a microVM just for you',+ 'Stretching the sandbox awake',+ 'Wiring up the pretend internet',+ 'Tuning the network qdisc',+ ],+ pull_image: [+ 'Tracking down a fresh claw image',+ 'Negotiating with the registry',+ 'Thawing 953 MB of OpenClaw',+ 'Decompressing layers, one at a time',+ 'The lobster is doing leg day',+ 'Pinching some bytes from the cache',+ 'Still pulling — bigger than it looks',+ ],+ wait_core_ready: [+ 'OpenClaw is checking its config',+ 'Booting the OpenAI-compat gateway',+ 'Loading 3 plugins (and not 39)',+ 'Waiting on /health to turn green',+ 'The lobster cleared its throat',+ ],+ start_entrypoint: [+ 'Launching the gateway process',+ 'Sourcing the per-agent env',+ 'Telling supervisord to do its thing',+ ],+ materialize_declared_state: [+ 'Reconciling channels and packages',+ 'Snapping things into place',+ 'Almost there, just dressing it up',+ ],+ install_gbrain: [+ 'Spinning up a Postgres for memories',+ 'Teaching the agent how to remember',+ 'Plumbing in pgvector',+ ],+ connect_telegram: [+ 'Registering the Telegram webhook',+ 'Bot meets API, API meets bot',+ 'Confirming the bot can phone home',+ ],+ default: [+ 'The lobster is busy. Please clap softly.',+ 'Crustacean cogs turning',+ 'Working on it',+ 'Just a moment, the claws are tangled',+ ],+}++function friendlyPhase(phase: string | null | undefined): string {+ if (!phase) return 'Working on it'+ return PHASE_LABELS[phase] ?? phase.replace(/_/g, ' ')+}++function flavourFor(phase: string | null | undefined): string[] {+ return (phase && PHASE_FLAVOUR[phase]) || PHASE_FLAVOUR.default+}++function BootingClawPanel({ operation }: { operation: AgentOperation }) {+ const [tick, setTick] = useState(0)+ useEffect(() => {+ const id = setInterval(() => setTick((t) => t + 1), 2600)+ return () => clearInterval(id)+ }, [])+ const lines = flavourFor(operation.phase)+ const flavour = lines[tick % lines.length]++ // Approximate elapsed time since the operation was created — gives the+ // user a sense of "how much longer". AgentOperation only carries+ // created_at; if it's ever omitted we fall through to "now" so the UI+ // doesn't crash, just shows 0s.+ const startedMs = operation.created_at ? new Date(operation.created_at).getTime() : Date.now()+ const elapsedSec = Math.max(0, Math.round((Date.now() - startedMs) / 1000))++ return (+ <div+ style={{+ display: 'flex', alignItems: 'center', gap: 18,+ padding: '20px 24px',+ borderRadius: 14,+ border: '1px solid rgba(255,77,77,0.22)',+ background:+ 'radial-gradient(ellipse at 0% 50%, rgba(255,77,77,0.10), transparent 55%), rgba(255,77,77,0.025)',+ marginBottom: 14,+ }}+ >+ <ScuttlingClaw />+ <div style={{ flex: 1, minWidth: 0 }}>+ <div style={{ fontSize: 17, fontWeight: 700, fontFamily: 'var(--font-display)', color: 'var(--text-primary)' }}>+ {friendlyPhase(operation.phase)}+ </div>+ <div+ key={tick}+ style={{+ fontSize: 13, color: 'var(--text-secondary)', marginTop: 5,+ animation: 'fadeUp 380ms ease-out',+ }}+ >+ {flavour}+ </div>+ <div style={{ fontSize: 11, color: 'var(--text-tertiary)', marginTop: 8, fontFamily: 'var(--font-mono)' }}>+ {operation.kind} · {operation.phase} · {elapsedSec}s elapsed+ </div>+ </div>+ <ProgressDots />++ {/* Animations defined inline so this component is self-contained;+ if we end up reusing them, lift to web/src/index.css. */}+ <style>{`+ @keyframes fadeUp {+ from { opacity: 0; transform: translateY(4px); }+ to { opacity: 1; transform: translateY(0); }+ }+ @keyframes claw-wave-left {+ 0%, 100% { transform: rotate(-4deg) translateX(0); }+ 50% { transform: rotate(8deg) translateX(-1px); }+ }+ @keyframes claw-wave-right {+ 0%, 100% { transform: rotate(4deg) translateX(0); }+ 50% { transform: rotate(-8deg) translateX(1px); }+ }+ @keyframes lobster-bob {+ 0%, 100% { transform: translateY(0); }+ 50% { transform: translateY(-3px); }+ }+ @keyframes eye-blink {+ 0%, 92%, 100% { transform: scaleY(1); }+ 95% { transform: scaleY(0.1); }+ }+ @keyframes dot-pulse {+ 0%, 80%, 100% { opacity: 0.25; transform: scale(0.7); }+ 40% { opacity: 1; transform: scale(1); }+ }+ `}</style>+ </div>+ )+}++// Animated lobster — derived from openclaw.ai/favicon.svg, with the two+// claws split into separate <g> tags so they can wave independently and the+// body bobs gently.+function ScuttlingClaw() {+ return (+ <svg+ width="68"+ height="68"+ viewBox="0 0 120 120"+ fill="none"+ xmlns="http://www.w3.org/2000/svg"+ aria-hidden="true"+ style={{+ flexShrink: 0,+ filter: 'drop-shadow(0 0 18px rgba(255,77,77,0.45))',+ animation: 'lobster-bob 2.4s ease-in-out infinite',+ }}+ >+ <defs>+ <linearGradient id="boot-lobster-gradient" x1="0%" y1="0%" x2="100%" y2="100%">+ <stop offset="0%" stopColor="#ff4d4d" />+ <stop offset="100%" stopColor="#991b1b" />+ </linearGradient>+ </defs>+ {/* body */}+ <path d="M60 10 C30 10 15 35 15 55 C15 75 30 95 45 100 L45 110 L55 110 L55 100 C55 100 60 102 65 100 L65 110 L75 110 L75 100 C90 95 105 75 105 55 C105 35 90 10 60 10Z" fill="url(#boot-lobster-gradient)" />+ {/* left claw — waves */}+ <g style={{ transformOrigin: '20px 55px', animation: 'claw-wave-left 1.4s ease-in-out infinite' }}>+ <path d="M20 45 C5 40 0 50 5 60 C10 70 20 65 25 55 C28 48 25 45 20 45Z" fill="url(#boot-lobster-gradient)" />+ </g>+ {/* right claw — waves opposite */}+ <g style={{ transformOrigin: '100px 55px', animation: 'claw-wave-right 1.4s ease-in-out infinite' }}>+ <path d="M100 45 C115 40 120 50 115 60 C110 70 100 65 95 55 C92 48 95 45 100 45Z" fill="url(#boot-lobster-gradient)" />+ </g>+ {/* antennae */}+ <path d="M45 15 Q35 5 30 8" stroke="#ff4d4d" strokeWidth="3" strokeLinecap="round" />+ <path d="M75 15 Q85 5 90 8" stroke="#ff4d4d" strokeWidth="3" strokeLinecap="round" />+ {/* eyes — blink */}+ <g style={{ transformOrigin: 'center 35px', animation: 'eye-blink 4.6s ease-in-out infinite' }}>+ <circle cx="45" cy="35" r="6" fill="#050810" />+ <circle cx="75" cy="35" r="6" fill="#050810" />+ <circle cx="46" cy="34" r="2.5" fill="#00e5cc" />+ <circle cx="76" cy="34" r="2.5" fill="#00e5cc" />+ </g>+ </svg>+ )+}++function ProgressDots() {+ return (+ <div style={{ display: 'flex', gap: 6, alignItems: 'center', flexShrink: 0 }}>+ {[0, 1, 2].map((i) => (+ <span+ key={i}+ style={{+ width: 8, height: 8, borderRadius: '50%',+ background: 'rgba(255,77,77,0.85)',+ animation: `dot-pulse 1.4s ease-in-out ${i * 0.18}s infinite`,+ }}+ />+ ))}+ </div>+ )+}diff --git a/web/src/pages/Agents.tsx b/web/src/pages/Agents.tsxnew file mode 100644index 00000000..2695d9eb--- /dev/null+++ b/web/src/pages/Agents.tsx@@ -0,0 +1,509 @@+import { useEffect, useState } from 'react'+import { useNavigate } from 'react-router-dom'+import {+ listAgents,+ getAgent,+ createAgent,+ deleteAgent,+ type Agent,+ type AgentDetail,+} from '../api/client'++type Banner = { kind: 'info' | 'error' | 'success'; text: string } | null++const statusColor: Record<string, string> = {+ ready: 'var(--accent-emerald, #34d399)',+ starting: 'var(--accent-amber, #fbbf24)',+ degraded: 'var(--accent-amber, #fbbf24)',+ error: 'var(--accent-rose, #f87171)',+ unknown: 'var(--text-tertiary)',+}++export default function Agents() {+ const [agents, setAgents] = useState<Agent[]>([])+ const [details, setDetails] = useState<Record<string, AgentDetail>>({})+ const [loading, setLoading] = useState(true)+ const [banner, setBanner] = useState<Banner>(null)+ const [showCreate, setShowCreate] = useState(false)+ const navigate = useNavigate()++ async function refresh() {+ try {+ const { agents } = await listAgents()+ setAgents(agents)+ const detailMap: Record<string, AgentDetail> = {}+ await Promise.all(+ agents.map(async (a) => {+ try {+ detailMap[a.id] = await getAgent(a.id)+ } catch {+ // best-effort: skip if detail fetch fails+ }+ }),+ )+ setDetails(detailMap)+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err)+ setBanner({ kind: 'error', text: `Failed to load agents: ${msg}` })+ } finally {+ setLoading(false)+ }+ }++ useEffect(() => {+ void refresh()+ // Poll every 5s while the page is open — operation states change fast.+ const interval = setInterval(() => void refresh(), 5000)+ return () => clearInterval(interval)+ }, [])++ async function handleDelete(id: string) {+ if (!window.confirm(`Delete agent "${id}"? The sandbox will be killed.`)) return+ try {+ await deleteAgent(id)+ setBanner({ kind: 'success', text: `Agent ${id} deleted.` })+ await refresh()+ } catch (err) {+ setBanner({ kind: 'error', text: `Delete failed: ${(err as Error).message}` })+ }+ }++ return (+ <div>+ <header style={{ marginBottom: 28, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>+ <div>+ <h1 style={{ fontSize: 22, margin: 0, fontFamily: 'var(--font-display)', fontWeight: 700 }}>Agents</h1>+ <p style={{ color: 'var(--text-secondary)', fontSize: 13, marginTop: 6 }}>+ Managed agent runtimes powered by OpenClaw. Add channels and packages to extend what they do.+ </p>+ </div>+ <button onClick={() => setShowCreate(true)} style={primaryButton}>+ New agent</button>+ </header>++ {banner && (+ <div+ style={{+ padding: '10px 14px',+ borderRadius: 6,+ marginBottom: 16,+ fontSize: 13,+ background:+ banner.kind === 'error'+ ? 'rgba(248,113,113,0.08)'+ : banner.kind === 'success'+ ? 'rgba(52,211,153,0.08)'+ : 'rgba(99,102,241,0.08)',+ border: `1px solid ${+ banner.kind === 'error'+ ? 'rgba(248,113,113,0.3)'+ : banner.kind === 'success'+ ? 'rgba(52,211,153,0.3)'+ : 'rgba(99,102,241,0.3)'+ }`,+ color: 'var(--text-primary)',+ display: 'flex',+ justifyContent: 'space-between',+ alignItems: 'center',+ }}+ >+ <span>{banner.text}</span>+ <button onClick={() => setBanner(null)} style={iconButton}>×</button>+ </div>+ )}++ {loading ? (+ <div style={{+ display: 'flex', alignItems: 'center', gap: 10,+ color: 'var(--text-tertiary)', fontSize: 13, padding: '32px 0',+ }}>+ <span className="loading-spinner" style={{ width: 14, height: 14, borderWidth: 1.5 }} />+ Loading agents…+ </div>+ ) : agents.length === 0 ? (+ <EmptyState onCreate={() => setShowCreate(true)} />+ ) : (+ <div style={{ display: 'grid', gap: 10 }}>+ {agents.map((a) => {+ const d = details[a.id]+ return (+ <div+ key={a.id}+ role="button"+ tabIndex={0}+ onClick={() => navigate(`/agents/${encodeURIComponent(a.id)}`)}+ onKeyDown={(e) => {+ if (e.key === 'Enter' || e.key === ' ') {+ e.preventDefault()+ navigate(`/agents/${encodeURIComponent(a.id)}`)+ }+ }}+ onMouseEnter={(e) => { e.currentTarget.style.background = 'rgba(255,255,255,0.04)' }}+ onMouseLeave={(e) => { e.currentTarget.style.background = 'rgba(255,255,255,0.02)' }}+ style={{+ background: 'rgba(255,255,255,0.02)',+ border: '1px solid var(--border-subtle)',+ borderRadius: 10,+ padding: '14px 18px',+ display: 'flex',+ alignItems: 'center',+ gap: 16,+ cursor: 'pointer',+ transition: 'background 0.12s ease',+ }}+ >+ <div+ className={+ d?.status === 'starting' || d?.status === 'degraded' || d?.current_operation+ ? 'pulse-dot'+ : undefined+ }+ style={{+ width: 8,+ height: 8,+ borderRadius: '50%',+ background: statusColor[d?.status ?? 'unknown'] ?? statusColor.unknown,+ flexShrink: 0,+ boxShadow:+ d?.status === 'starting' || d?.current_operation+ ? `0 0 0 3px ${statusColor[d?.status ?? 'starting']}22`+ : undefined,+ }}+ title={d?.current_operation ? `${d.current_operation.kind} · ${d.current_operation.phase}` : (d?.status ?? 'unknown')}+ />+ <div style={{ flex: 1, minWidth: 0 }}>+ <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>+ <span style={{ fontWeight: 600, fontSize: 14 }}>{a.display_name}</span>+ <span style={{ fontSize: 11, color: 'var(--text-tertiary)', fontFamily: 'var(--font-mono)' }}>+ {a.id}+ </span>+ </div>+ <div style={{ fontSize: 11, color: 'var(--text-secondary)', marginTop: 4, display: 'flex', gap: 12 }}>+ {a.core && <span>core: <code style={codeInline}>{a.core}</code></span>}+ <span>+ packages: {a.packages.length === 0 ? '—' : a.packages.map((p) => p.name).join(', ')}+ </span>+ <span>+ channels: {a.channels.length === 0 ? '—' : a.channels.map((c) => c.name).join(', ')}+ </span>+ </div>+ {d?.current_operation && (+ <div style={{+ fontSize: 11, color: 'var(--accent-amber, #fbbf24)', marginTop: 4,+ display: 'flex', alignItems: 'center', gap: 6,+ }}>+ <span+ className="loading-spinner"+ style={{+ width: 10, height: 10, borderWidth: 1.5,+ borderColor: 'rgba(251,191,36,0.25)',+ borderTopColor: 'var(--accent-amber, #fbbf24)',+ }}+ />+ <span>+ {d.current_operation.kind} · {d.current_operation.phase}+ {d.current_operation.message ? ` — ${d.current_operation.message}` : ''}+ </span>+ </div>+ )}+ {d?.last_error && d.status !== 'ready' && (+ <div style={{ fontSize: 11, color: 'var(--accent-rose, #f87171)', marginTop: 4 }}>+ {d.last_error.phase}: {d.last_error.message}+ </div>+ )}+ </div>+ <div style={{ display: 'flex', gap: 6 }} onClick={(e) => e.stopPropagation()}>+ <button+ onClick={(e) => {+ e.stopPropagation()+ handleDelete(a.id)+ }}+ style={dangerButton}+ >+ Delete+ </button>+ </div>+ </div>+ )+ })}+ </div>+ )}++ {showCreate && (+ <CreateAgentModal+ onClose={() => setShowCreate(false)}+ onCreated={(agentId) => {+ setShowCreate(false)+ // Drop the user straight onto the agent's detail page so they+ // see the booting lobster animation while the sandbox provisions,+ // rather than landing back on the list with a flat success banner.+ navigate(`/agents/${encodeURIComponent(agentId)}`)+ }}+ onError={(msg) => setBanner({ kind: 'error', text: msg })}+ />+ )}++ </div>+ )+}++function EmptyState({ onCreate }: { onCreate: () => void }) {+ return (+ <div+ style={{+ textAlign: 'center',+ padding: '56px 24px 64px',+ border: '1px solid rgba(255,77,77,0.22)',+ borderRadius: 14,+ background:+ 'radial-gradient(ellipse at top, rgba(255,77,77,0.10), transparent 60%), rgba(255,255,255,0.015)',+ position: 'relative',+ overflow: 'hidden',+ }}+ >+ <ClawLogo />+ <div style={{ fontSize: 22, fontWeight: 700, marginTop: 18, fontFamily: 'var(--font-display)' }}>+ Deploy an OpenClaw managed agent+ </div>+ <p style={{+ color: 'var(--text-secondary)', fontSize: 14, marginTop: 10, marginBottom: 26,+ maxWidth: 520, marginLeft: 'auto', marginRight: 'auto', lineHeight: 1.55,+ }}>+ OpenClaw runs the gateway, model routing, and tool execution inside a sandbox we+ manage for you. Connect Telegram, install gbrain for long-term memory, and you're+ live in under a minute.+ </p>+ <button onClick={onCreate} style={primaryButton}>Create your first agent</button>+ </div>+ )+}++// OpenClaw lobster mark — pulled from openclaw.ai/favicon.svg so the dashboard+// and agents-empty-state both use the same brand asset as the marketing site.+// Inlined so it ships with the bundle. Gradient id is scoped (`agents-…`) to+// avoid colliding with the same logo on other pages.+function ClawLogo() {+ return (+ <svg+ width="80"+ height="80"+ viewBox="0 0 120 120"+ fill="none"+ xmlns="http://www.w3.org/2000/svg"+ aria-hidden="true"+ style={{ filter: 'drop-shadow(0 0 22px rgba(255,77,77,0.40))' }}+ >+ <defs>+ <linearGradient id="agents-lobster-gradient" x1="0%" y1="0%" x2="100%" y2="100%">+ <stop offset="0%" stopColor="#ff4d4d" />+ <stop offset="100%" stopColor="#991b1b" />+ </linearGradient>+ </defs>+ <path d="M60 10 C30 10 15 35 15 55 C15 75 30 95 45 100 L45 110 L55 110 L55 100 C55 100 60 102 65 100 L65 110 L75 110 L75 100 C90 95 105 75 105 55 C105 35 90 10 60 10Z" fill="url(#agents-lobster-gradient)" />+ <path d="M20 45 C5 40 0 50 5 60 C10 70 20 65 25 55 C28 48 25 45 20 45Z" fill="url(#agents-lobster-gradient)" />+ <path d="M100 45 C115 40 120 50 115 60 C110 70 100 65 95 55 C92 48 95 45 100 45Z" fill="url(#agents-lobster-gradient)" />+ <path d="M45 15 Q35 5 30 8" stroke="#ff4d4d" strokeWidth="3" strokeLinecap="round" />+ <path d="M75 15 Q85 5 90 8" stroke="#ff4d4d" strokeWidth="3" strokeLinecap="round" />+ <circle cx="45" cy="35" r="6" fill="#050810" />+ <circle cx="75" cy="35" r="6" fill="#050810" />+ <circle cx="46" cy="34" r="2.5" fill="#00e5cc" />+ <circle cx="76" cy="34" r="2.5" fill="#00e5cc" />+ </svg>+ )+}++function CreateAgentModal({+ onClose,+ onCreated,+ onError,+}: {+ onClose: () => void+ onCreated: (agentId: string) => void+ onError: (msg: string) => void+}) {+ const [id, setId] = useState('')+ const [displayName, setDisplayName] = useState('')+ const [core, setCore] = useState<'openclaw'>('openclaw')+ const [submitting, setSubmitting] = useState(false)++ async function submit(e: React.FormEvent) {+ e.preventDefault()+ if (!/^[a-z0-9][a-z0-9-]*$/.test(id)) {+ onError('id must be lowercase alphanumeric + hyphens, starting with a letter or digit')+ return+ }+ setSubmitting(true)+ try {+ await createAgent({+ id,+ display_name: displayName || id,+ core,+ })+ onCreated(id)+ } catch (err) {+ onError(`Create failed: ${(err as Error).message}`)+ } finally {+ setSubmitting(false)+ }+ }++ return (+ <ModalShell onClose={onClose} title="Create agent">+ <form onSubmit={submit} style={{ display: 'grid', gap: 14 }}>+ <Field label="Agent ID" hint="lowercase, hyphens, must be unique">+ <input+ autoFocus+ value={id}+ onChange={(e) => setId(e.target.value)}+ placeholder="my-bot"+ style={input}+ required+ />+ </Field>+ <Field label="Display name (optional)">+ <input value={displayName} onChange={(e) => setDisplayName(e.target.value)} placeholder={id || 'My Bot'} style={input} />+ </Field>+ <Field label="Core" hint="OpenClaw is the only runtime available right now. Hermes support is coming soon.">+ <select value={core} onChange={(e) => setCore(e.target.value as 'openclaw')} style={input}>+ <option value="openclaw">openclaw</option>+ <option value="hermes" disabled>hermes (coming soon)</option>+ </select>+ </Field>+ <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 4 }}>+ <button type="button" onClick={onClose} style={secondaryButton}>Cancel</button>+ <button type="submit" disabled={submitting || !id} style={primaryButton}>+ {submitting ? <BusyLabel text="Creating…" /> : 'Create agent'}+ </button>+ </div>+ </form>+ </ModalShell>+ )+}++function ModalShell({ children, title, onClose }: { children: React.ReactNode; title: string; onClose: () => void }) {+ return (+ <div+ onClick={onClose}+ style={{+ position: 'fixed',+ inset: 0,+ background: 'rgba(0,0,0,0.5)',+ zIndex: 100,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ padding: 20,+ }}+ >+ <div+ onClick={(e) => e.stopPropagation()}+ style={{+ background: 'var(--bg-deep)',+ border: '1px solid var(--border-subtle)',+ borderRadius: 12,+ width: '100%',+ maxWidth: 480,+ maxHeight: '90vh',+ overflowY: 'auto',+ padding: 22,+ }}+ >+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 18 }}>+ <h2 style={{ fontSize: 16, margin: 0, fontFamily: 'var(--font-display)' }}>{title}</h2>+ <button onClick={onClose} style={iconButton}>×</button>+ </div>+ {children}+ </div>+ </div>+ )+}++function Field({ label, hint, children }: { label: string; hint?: string; children: React.ReactNode }) {+ return (+ <label style={{ display: 'grid', gap: 4 }}>+ <span style={{ fontSize: 12, color: 'var(--text-secondary)', fontWeight: 500 }}>{label}</span>+ {children}+ {hint && <span style={{ fontSize: 11, color: 'var(--text-tertiary)' }}>{hint}</span>}+ </label>+ )+}++function BusyLabel({ text }: { text: string }) {+ return (+ <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>+ <span+ className="loading-spinner"+ style={{+ width: 11, height: 11, borderWidth: 1.5,+ borderColor: 'rgba(255,255,255,0.25)',+ borderTopColor: 'currentColor',+ }}+ />+ {text}+ </span>+ )+}++const primaryButton: React.CSSProperties = {+ background: 'var(--gradient-primary, #6366f1)',+ color: '#fff',+ padding: '8px 14px',+ border: 'none',+ borderRadius: 6,+ cursor: 'pointer',+ fontSize: 13,+ fontWeight: 600,+ fontFamily: 'var(--font-body)',+}++const secondaryButton: React.CSSProperties = {+ background: 'rgba(255,255,255,0.04)',+ color: 'var(--text-primary)',+ padding: '7px 12px',+ border: '1px solid var(--border-subtle)',+ borderRadius: 6,+ cursor: 'pointer',+ fontSize: 12,+ fontFamily: 'var(--font-body)',+}++const dangerButton: React.CSSProperties = {+ background: 'rgba(248,113,113,0.08)',+ color: '#f87171',+ padding: '7px 12px',+ border: '1px solid rgba(248,113,113,0.35)',+ borderRadius: 6,+ cursor: 'pointer',+ fontSize: 12,+ fontFamily: 'var(--font-body)',+}++const iconButton: React.CSSProperties = {+ background: 'none',+ border: 'none',+ color: 'var(--text-tertiary)',+ cursor: 'pointer',+ fontSize: 22,+ padding: 0,+ width: 22,+ height: 22,+ lineHeight: 1,+}++const input: React.CSSProperties = {+ background: 'rgba(255,255,255,0.02)',+ border: '1px solid var(--border-subtle)',+ borderRadius: 6,+ padding: '8px 10px',+ color: 'var(--text-primary)',+ fontSize: 13,+ fontFamily: 'var(--font-body)',+ outline: 'none',+}++const codeInline: React.CSSProperties = {+ fontFamily: 'var(--font-mono)',+ background: 'rgba(255,255,255,0.04)',+ padding: '1px 5px',+ borderRadius: 3,+ fontSize: 10.5,+}diff --git a/web/src/pages/Billing.tsx b/web/src/pages/Billing.tsxindex d913440e..40c78eaa 100644--- a/web/src/pages/Billing.tsx+++ b/web/src/pages/Billing.tsx@@ -1,14 +1,62 @@-import { useState } from 'react'+import { useMemo, useState } from 'react'+import { Link } from 'react-router-dom'import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'import {getBilling, billingSetup, billingPortal, getBillingInvoices, redeemPromoCode,- type StripeInvoice,+ listOrgAgentSubscriptions, listAgents, cancelAgentFeature,+ type StripeInvoice, type OrgAgentSubscription, type Agent,} from '../api/client'+type Tab = 'sandboxes' | 'agents' | 'invoices'+export default function Billing() {+ const [tab, setTab] = useState<Tab>('sandboxes')++ return (+ <div>+ <div style={{ marginBottom: 24 }}>+ <h1 className="page-title">Billing</h1>+ <p className="page-subtitle">Manage your plan, per-agent subscriptions, and invoices</p>+ </div>++ {/* Tabs */}+ <div style={{ display: 'flex', borderBottom: '1px solid var(--border-subtle)', marginBottom: 18, gap: 4 }}>+ {(['sandboxes', 'agents', 'invoices'] as Tab[]).map((t) => (+ <button+ key={t}+ onClick={() => setTab(t)}+ style={{+ background: 'none',+ border: 'none',+ borderBottom: tab === t ? '2px solid var(--accent-indigo)' : '2px solid transparent',+ padding: '10px 14px',+ color: tab === t ? 'var(--text-primary)' : 'var(--text-secondary)',+ fontSize: 13,+ fontFamily: 'var(--font-body)',+ fontWeight: tab === t ? 600 : 400,+ cursor: 'pointer',+ textTransform: 'capitalize',+ }}+ >+ {t}+ </button>+ ))}+ </div>++ {tab === 'sandboxes' && <PlanTab />}+ {tab === 'agents' && <AgentsTab />}+ {tab === 'invoices' && <InvoicesTab />}+ </div>+ )+}++// ───────────── Plan & Usage tab ─────────────++function PlanTab() {const queryClient = useQueryClient()- const { data: billing, isLoading } = useQuery({ queryKey: ['billing'], queryFn: getBilling, refetchInterval: 30_000 })- const { data: invoiceData } = useQuery({ queryKey: ['invoices'], queryFn: () => getBillingInvoices() })+ const { data: billing, isLoading } = useQuery({+ queryKey: ['billing'], queryFn: getBilling, refetchInterval: 30_000,+ })const [promoCode, setPromoCode] = useState('')const [redeemSuccess, setRedeemSuccess] = useState('')@@ -17,12 +65,10 @@ export default function Billing() {mutationFn: billingSetup,onSuccess: (data) => { window.location.href = data.url },})-const portalMutation = useMutation({mutationFn: billingPortal,onSuccess: (data) => { window.location.href = data.url },})-const redeemMutation = useMutation({mutationFn: () => redeemPromoCode(promoCode),onSuccess: (data) => {@@ -35,226 +81,489 @@ export default function Billing() {const isPro = billing?.plan === 'pro'- return (- <div>- <div style={{ marginBottom: 32 }}>- <h1 className="page-title">Billing</h1>- <p className="page-subtitle">Manage your plan and payment settings</p>+ if (isLoading) {+ return (+ <div style={{ display: 'flex', justifyContent: 'center', padding: 80 }}>+ <div className="loading-spinner" /></div>+ )+ }- {isLoading ? (- <div style={{ display: 'flex', justifyContent: 'center', padding: 80 }}>- <div className="loading-spinner" />+ return (+ <>+ {/* Plan Card */}+ <div className="glass-card animate-in stagger-1" style={{ padding: 28, marginBottom: 14 }}>+ <span className="section-title" style={{ marginBottom: 16, display: 'block' }}>+ Current Plan+ </span>+ <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, marginBottom: 8 }}>+ <span className="metric-value" style={{+ fontSize: 36, fontWeight: 700,+ color: isPro ? 'var(--accent-indigo)' : 'var(--text-primary)',+ }}>+ {isPro ? 'Pro' : 'Free'}+ </span>+ <span style={{ fontSize: 12, color: 'var(--text-tertiary)' }}>+ {isPro+ ? `${billing?.maxConcurrentSandboxes ?? 5} concurrent sandboxes, all tiers`+ : `${billing?.maxConcurrentSandboxes ?? 5} concurrent sandboxes, up to 4GB / 1 vCPU`}+ </span></div>- ) : (- <>- {/* Plan Card */}- <div className="glass-card animate-in stagger-1" style={{ padding: 28, marginBottom: 14 }}>- <span className="section-title" style={{ marginBottom: 16, display: 'block' }}>- Current Plan- </span>- <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, marginBottom: 8 }}>- <span className="metric-value" style={{- fontSize: 36, fontWeight: 700,- color: isPro ? 'var(--accent-indigo)' : 'var(--text-primary)',- }}>- {isPro ? 'Pro' : 'Free'}- </span>- <span style={{ fontSize: 12, color: 'var(--text-tertiary)' }}>- {isPro- ? `${billing?.maxConcurrentSandboxes ?? 5} concurrent sandboxes, all tiers`- : `${billing?.maxConcurrentSandboxes ?? 5} concurrent sandboxes, up to 4GB / 1 vCPU`}- </span>- </div>- {isPro && billing?.stripeCreditCents != null && billing.stripeCreditCents > 0 && (- <div style={{ fontSize: 13, color: 'var(--accent-emerald)', marginBottom: 12 }}>- ${(billing.stripeCreditCents / 100).toFixed(2)} promotional credit remaining- </div>- )}+ {isPro && billing?.stripeCreditCents != null && billing.stripeCreditCents > 0 && (+ <div style={{ fontSize: 13, color: 'var(--accent-emerald)', marginBottom: 12 }}>+ ${(billing.stripeCreditCents / 100).toFixed(2)} promotional credit remaining+ </div>+ )}- {!isPro && billing != null && (- <div style={{ marginTop: 12 }}>- {billing.freeCreditsRemainingCents > 0 ? (- <div style={{- fontSize: 14, fontWeight: 600, fontFamily: 'var(--font-mono)',- color: 'var(--accent-emerald)', marginBottom: 12,- }}>- ${(billing.freeCreditsRemainingCents / 100).toFixed(2)} free trial credit remaining- </div>- ) : (- <div style={{- fontSize: 13, color: 'var(--accent-rose)', marginBottom: 12,- display: 'flex', alignItems: 'center', gap: 6,- }}>- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">- <circle cx="12" cy="12" r="10" /><line x1="12" y1="8" x2="12" y2="12" /><line x1="12" y1="16" x2="12.01" y2="16" />- </svg>- Free trial credits exhausted — upgrade to continue using sandboxes- </div>- )}-- <div style={{ fontSize: 13, color: 'var(--text-secondary)', marginBottom: 10 }}>- Upgrade to Pro for an additional $30 free credit and larger machine sizes- </div>- <button- onClick={() => setupMutation.mutate()}- disabled={setupMutation.isPending}- style={{- padding: '10px 24px', fontSize: 14, fontWeight: 600,- fontFamily: 'var(--font-body)', cursor: 'pointer',- border: 'none', borderRadius: 'var(--radius-sm)',- background: 'var(--accent-indigo)', color: '#fff',- opacity: setupMutation.isPending ? 0.6 : 1,- }}- >- {setupMutation.isPending ? 'Redirecting...' : 'Upgrade to Pro'}- </button>- {setupMutation.isError && (- <p style={{ fontSize: 12, color: 'var(--accent-rose)', marginTop: 8 }}>- {(setupMutation.error as Error).message}- </p>- )}+ {!isPro && billing != null && (+ <div style={{ marginTop: 12 }}>+ {billing.freeCreditsRemainingCents > 0 ? (+ <div style={{+ fontSize: 14, fontWeight: 600, fontFamily: 'var(--font-mono)',+ color: 'var(--accent-emerald)', marginBottom: 12,+ }}>+ ${(billing.freeCreditsRemainingCents / 100).toFixed(2)} free trial credit remaining</div>- )}-- {isPro && (+ ) : (<div style={{- fontSize: 11, color: 'var(--accent-emerald)', marginTop: 4,+ fontSize: 13, color: 'var(--accent-rose)', marginBottom: 12,display: 'flex', alignItems: 'center', gap: 6,}}>- <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><polyline points="20 6 9 17 4 12" /></svg>- Payment method on file — billed monthly via Stripe+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">+ <circle cx="12" cy="12" r="10" /><line x1="12" y1="8" x2="12" y2="12" /><line x1="12" y1="16" x2="12.01" y2="16" />+ </svg>+ Free trial credits exhausted — upgrade to continue using sandboxes</div>)}- <div style={{ fontSize: 12, color: 'var(--text-tertiary)', marginTop: 12 }}>- Need more concurrency?{' '}- <a href="https://cal.com/team/digger/opencomputer-founder-chat" target="_blank" rel="noreferrer"- style={{ color: 'var(--accent-indigo)', textDecoration: 'none' }}>- Talk to us- </a>+ <div style={{ fontSize: 13, color: 'var(--text-secondary)', marginBottom: 10 }}>+ Upgrade to Pro for an additional $30 free credit and larger machine sizes</div>+ <button+ onClick={() => setupMutation.mutate()}+ disabled={setupMutation.isPending}+ style={{+ padding: '10px 24px', fontSize: 14, fontWeight: 600,+ fontFamily: 'var(--font-body)', cursor: 'pointer',+ border: 'none', borderRadius: 'var(--radius-sm)',+ background: 'var(--accent-indigo)', color: '#fff',+ opacity: setupMutation.isPending ? 0.6 : 1,+ }}+ >+ {setupMutation.isPending ? 'Redirecting...' : 'Upgrade to Pro'}+ </button>+ {setupMutation.isError && (+ <p style={{ fontSize: 12, color: 'var(--accent-rose)', marginTop: 8 }}>+ {(setupMutation.error as Error).message}+ </p>+ )}</div>+ )}- {/* Stripe Billing Portal CTA (pro only) */}- {isPro && (- <div className="glass-card animate-in stagger-2" style={{ padding: '22px 24px', marginBottom: 14 }}>- <span className="section-title" style={{ marginBottom: 10, display: 'block' }}>- Usage & Invoices- </span>- <p style={{ fontSize: 13, color: 'var(--text-secondary)', marginBottom: 14, lineHeight: 1.5 }}>- View your current-cycle usage, invoices, and manage your payment method on Stripe.- </p>- <button- onClick={() => portalMutation.mutate()}- disabled={portalMutation.isPending}- style={{- padding: '10px 20px', fontSize: 13, fontWeight: 600,- fontFamily: 'var(--font-body)', cursor: 'pointer',- border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-sm)',- background: 'rgba(255,255,255,0.02)', color: 'var(--text-primary)',- opacity: portalMutation.isPending ? 0.6 : 1,- }}- >- {portalMutation.isPending ? 'Opening Stripe…' : 'Open Stripe billing portal ↗'}- </button>- {portalMutation.isError && (- <p style={{ fontSize: 12, color: 'var(--accent-rose)', marginTop: 10 }}>- {(portalMutation.error as Error).message}- </p>- )}- </div>- )}+ {isPro && (+ <div style={{+ fontSize: 11, color: 'var(--accent-emerald)', marginTop: 4,+ display: 'flex', alignItems: 'center', gap: 6,+ }}>+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><polyline points="20 6 9 17 4 12" /></svg>+ Payment method on file — billed monthly via Stripe+ </div>+ )}- {/* Redeem Promotion Code (pro only) */}- {isPro && (- <div className="glass-card animate-in stagger-3" style={{ padding: '22px 24px', marginBottom: 14 }}>- <span className="section-title" style={{ marginBottom: 12, display: 'block' }}>Promotion Code</span>- <div style={{ display: 'flex', alignItems: 'end', gap: 14 }}>- <div>- <label style={{ fontSize: 11, color: 'var(--text-tertiary)', display: 'block', marginBottom: 6 }}>- Enter a promotion code to apply credit- </label>- <input- className="input"- type="text"- placeholder="e.g. WELCOME100"- value={promoCode}- onChange={e => setPromoCode(e.target.value.toUpperCase())}- style={{ width: 240, fontFamily: 'var(--font-mono)', fontSize: 13 }}- />- </div>- <button- onClick={() => redeemMutation.mutate()}- disabled={redeemMutation.isPending || !promoCode.trim()}- style={{- padding: '8px 20px', fontSize: 13, fontWeight: 600,- fontFamily: 'var(--font-body)', cursor: 'pointer',- border: 'none', borderRadius: 'var(--radius-sm)',- background: 'var(--accent-indigo)', color: '#fff',- opacity: redeemMutation.isPending || !promoCode.trim() ? 0.5 : 1,- }}- >- {redeemMutation.isPending ? 'Applying...' : 'Redeem'}- </button>- </div>- {redeemSuccess && (- <p style={{ fontSize: 13, color: 'var(--accent-emerald)', marginTop: 10 }}>{redeemSuccess}</p>- )}- {redeemMutation.isError && (- <p style={{ fontSize: 12, color: 'var(--accent-rose)', marginTop: 10 }}>- {(redeemMutation.error as Error).message}- </p>- )}- </div>+ <div style={{ fontSize: 12, color: 'var(--text-tertiary)', marginTop: 12 }}>+ Need more concurrency?{' '}+ <a href="https://cal.com/team/digger/opencomputer-founder-chat" target="_blank" rel="noreferrer"+ style={{ color: 'var(--accent-indigo)', textDecoration: 'none' }}>+ Talk to us+ </a>+ </div>+ </div>++ {/* Stripe Billing Portal CTA (pro only) */}+ {isPro && (+ <div className="glass-card animate-in stagger-2" style={{ padding: '22px 24px', marginBottom: 14 }}>+ <span className="section-title" style={{ marginBottom: 10, display: 'block' }}>+ Usage & Payment Method+ </span>+ <p style={{ fontSize: 13, color: 'var(--text-secondary)', marginBottom: 14, lineHeight: 1.5 }}>+ View your current-cycle usage, manage your payment method, and download invoices on Stripe.+ </p>+ <button+ onClick={() => portalMutation.mutate()}+ disabled={portalMutation.isPending}+ style={{+ padding: '10px 20px', fontSize: 13, fontWeight: 600,+ fontFamily: 'var(--font-body)', cursor: 'pointer',+ border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-sm)',+ background: 'rgba(255,255,255,0.02)', color: 'var(--text-primary)',+ opacity: portalMutation.isPending ? 0.6 : 1,+ }}+ >+ {portalMutation.isPending ? 'Opening Stripe…' : 'Open Stripe billing portal ↗'}+ </button>+ {portalMutation.isError && (+ <p style={{ fontSize: 12, color: 'var(--accent-rose)', marginTop: 10 }}>+ {(portalMutation.error as Error).message}+ </p>)}+ </div>+ )}- {/* Invoice History (pro only) */}- {isPro && (- <div className="glass-card animate-in stagger-4" style={{ padding: '22px 24px' }}>- <span className="section-title" style={{ marginBottom: 14, display: 'block' }}>Invoices</span>- {!invoiceData?.invoices?.length ? (- <div style={{ textAlign: 'center', padding: '40px 20px', color: 'var(--text-tertiary)', fontSize: 13 }}>- No invoices yet — your first invoice will appear at the end of the billing period- </div>- ) : (- <table className="data-table">- <thead>- <tr><th>Date</th><th>Number</th><th>Status</th><th>Amount</th><th></th></tr>- </thead>- <tbody>- {invoiceData.invoices.map((inv: StripeInvoice) => (- <tr key={inv.id}>- <td style={{ fontFamily: 'var(--font-mono)', fontSize: 12 }}>- {new Date(inv.created * 1000).toLocaleDateString()}- </td>- <td style={{ fontSize: 12 }}>{inv.number}</td>- <td><InvoiceStatus status={inv.status} /></td>- <td style={{ fontFamily: 'var(--font-mono)', fontSize: 13, fontWeight: 600 }}>- ${(inv.amountDue / 100).toFixed(2)}- </td>- <td>- {inv.hostedUrl && (- <a href={inv.hostedUrl} target="_blank" rel="noreferrer"- style={{ fontSize: 12, color: 'var(--accent-indigo)', textDecoration: 'none' }}>- View- </a>- )}- </td>- </tr>- ))}- </tbody>- </table>- )}+ {/* Redeem Promotion Code (pro only) */}+ {isPro && (+ <div className="glass-card animate-in stagger-3" style={{ padding: '22px 24px', marginBottom: 14 }}>+ <span className="section-title" style={{ marginBottom: 12, display: 'block' }}>Promotion Code</span>+ <div style={{ display: 'flex', alignItems: 'end', gap: 14 }}>+ <div>+ <label style={{ fontSize: 11, color: 'var(--text-tertiary)', display: 'block', marginBottom: 6 }}>+ Enter a promotion code to apply credit+ </label>+ <input+ className="input"+ type="text"+ placeholder="e.g. WELCOME100"+ value={promoCode}+ onChange={e => setPromoCode(e.target.value.toUpperCase())}+ style={{ width: 240, fontFamily: 'var(--font-mono)', fontSize: 13 }}+ /></div>+ <button+ onClick={() => redeemMutation.mutate()}+ disabled={redeemMutation.isPending || !promoCode.trim()}+ style={{+ padding: '8px 20px', fontSize: 13, fontWeight: 600,+ fontFamily: 'var(--font-body)', cursor: 'pointer',+ border: 'none', borderRadius: 'var(--radius-sm)',+ background: 'var(--accent-indigo)', color: '#fff',+ opacity: redeemMutation.isPending || !promoCode.trim() ? 0.5 : 1,+ }}+ >+ {redeemMutation.isPending ? 'Applying...' : 'Redeem'}+ </button>+ </div>+ {redeemSuccess && (+ <p style={{ fontSize: 13, color: 'var(--accent-emerald)', marginTop: 10 }}>{redeemSuccess}</p>+ )}+ {redeemMutation.isError && (+ <p style={{ fontSize: 12, color: 'var(--accent-rose)', marginTop: 10 }}>+ {(redeemMutation.error as Error).message}+ </p>)}- </>+ </div>+ )}+ </>+ )+}++// ───────────── Agents tab ─────────────++function AgentsTab() {+ const queryClient = useQueryClient()+ const { data: subsData, isLoading: subsLoading } = useQuery({+ queryKey: ['org-agent-subscriptions'],+ queryFn: listOrgAgentSubscriptions,+ refetchInterval: 30_000,+ })+ const { data: agentsData } = useQuery({+ queryKey: ['agents'], queryFn: listAgents,+ })++ const cancelMutation = useMutation({+ mutationFn: ({ agentId, feature }: { agentId: string; feature: string }) =>+ cancelAgentFeature(agentId, feature),+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: ['org-agent-subscriptions'] })+ },+ })++ // Index agents by ID so we can show display names instead of raw IDs.+ const agentsById = useMemo(() => {+ const map: Record<string, Agent> = {}+ for (const a of agentsData?.agents ?? []) map[a.id] = a+ return map+ }, [agentsData])++ // De-duplicate to one row per (agent_id, feature). We sort by created_at+ // desc so the freshest row wins — covers cases where a user canceled then+ // re-subscribed.+ const rows = useMemo(() => {+ const seen = new Set<string>()+ const sorted = [...(subsData?.subscriptions ?? [])].sort((a, b) =>+ b.created_at.localeCompare(a.created_at),+ )+ const out: OrgAgentSubscription[] = []+ for (const sub of sorted) {+ const key = `${sub.agent_id}::${sub.feature}`+ if (seen.has(key)) continue+ seen.add(key)+ out.push(sub)+ }+ return out+ }, [subsData])++ const activeRows = rows.filter(r => r.active)+ const inactiveRows = rows.filter(r => !r.active)++ const totalMonthlyCents = activeRows.reduce((sum, r) => sum + r.price_monthly_cents, 0)++ if (subsLoading) {+ return (+ <div style={{ display: 'flex', justifyContent: 'center', padding: 80 }}>+ <div className="loading-spinner" />+ </div>+ )+ }++ return (+ <>+ {/* Summary card */}+ <div className="glass-card animate-in stagger-1" style={{ padding: 28, marginBottom: 14 }}>+ <span className="section-title" style={{ marginBottom: 12, display: 'block' }}>+ Per-agent features+ </span>+ <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, marginBottom: 6 }}>+ <span className="metric-value" style={{ fontSize: 32, fontWeight: 700 }}>+ ${(totalMonthlyCents / 100).toFixed(2)}+ </span>+ <span style={{ fontSize: 12, color: 'var(--text-tertiary)' }}>+ /mo across {activeRows.length} active subscription{activeRows.length === 1 ? '' : 's'}+ </span>+ </div>+ <p style={{ fontSize: 13, color: 'var(--text-secondary)', lineHeight: 1.5, marginTop: 6 }}>+ Each connected channel (e.g. Telegram) is billed per-agent. Subscribe or cancel from each+ agent's page.+ </p>+ </div>++ {/* Active subscriptions */}+ <div className="glass-card animate-in stagger-2" style={{ padding: '22px 24px', marginBottom: 14 }}>+ <span className="section-title" style={{ marginBottom: 14, display: 'block' }}>+ Active+ </span>+ {activeRows.length === 0 ? (+ <div style={{ textAlign: 'center', padding: '32px 20px', color: 'var(--text-tertiary)', fontSize: 13 }}>+ No active per-agent subscriptions yet.+ </div>+ ) : (+ <table className="data-table">+ <thead>+ <tr>+ <th>Agent</th>+ <th>Feature</th>+ <th>Status</th>+ <th>Renews</th>+ <th style={{ textAlign: 'right' }}>Price</th>+ <th></th>+ </tr>+ </thead>+ <tbody>+ {activeRows.map((sub) => {+ const agent = agentsById[sub.agent_id]+ const label = agent?.display_name || sub.agent_id+ const renewLabel = sub.cancel_at_period_end+ ? `Ends ${formatDate(sub.current_period_end)}`+ : sub.current_period_end+ ? formatDate(sub.current_period_end)+ : '—'+ return (+ <tr key={sub.stripe_subscription_id}>+ <td>+ <Link to={`/agents/${encodeURIComponent(sub.agent_id)}`}+ style={{ color: 'var(--accent-indigo)', textDecoration: 'none', fontWeight: 600 }}>+ {label}+ </Link>+ {agent && (+ <div style={{ fontSize: 11, color: 'var(--text-tertiary)', fontFamily: 'var(--font-mono)' }}>+ {sub.agent_id}+ </div>+ )}+ </td>+ <td style={{ textTransform: 'capitalize', fontSize: 13 }}>{sub.feature}</td>+ <td><SubscriptionStatus status={sub.status} cancelAtPeriodEnd={sub.cancel_at_period_end} /></td>+ <td style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--text-secondary)' }}>+ {renewLabel}+ </td>+ <td style={{ fontFamily: 'var(--font-mono)', fontSize: 13, fontWeight: 600, textAlign: 'right' }}>+ ${(sub.price_monthly_cents / 100).toFixed(2)}/mo+ </td>+ <td style={{ textAlign: 'right' }}>+ {!sub.cancel_at_period_end && (+ <button+ onClick={() => {+ if (confirm(`Cancel ${sub.feature} for ${label} at end of billing period?`)) {+ cancelMutation.mutate({ agentId: sub.agent_id, feature: sub.feature })+ }+ }}+ disabled={cancelMutation.isPending}+ style={{+ background: 'none',+ border: '1px solid var(--border-subtle)',+ color: 'var(--text-secondary)',+ fontSize: 12,+ padding: '4px 10px',+ borderRadius: 'var(--radius-sm)',+ cursor: 'pointer',+ fontFamily: 'var(--font-body)',+ }}+ >+ Cancel+ </button>+ )}+ </td>+ </tr>+ )+ })}+ </tbody>+ </table>+ )}+ </div>++ {/* Past subscriptions (collapsed-feeling) */}+ {inactiveRows.length > 0 && (+ <div className="glass-card animate-in stagger-3" style={{ padding: '22px 24px' }}>+ <span className="section-title" style={{ marginBottom: 14, display: 'block' }}>+ Past+ </span>+ <table className="data-table">+ <thead>+ <tr>+ <th>Agent</th>+ <th>Feature</th>+ <th>Status</th>+ <th>Ended</th>+ </tr>+ </thead>+ <tbody>+ {inactiveRows.map((sub) => {+ const agent = agentsById[sub.agent_id]+ const label = agent?.display_name || sub.agent_id+ return (+ <tr key={sub.stripe_subscription_id}>+ <td>+ <Link to={`/agents/${encodeURIComponent(sub.agent_id)}`}+ style={{ color: 'var(--text-secondary)', textDecoration: 'none' }}>+ {label}+ </Link>+ </td>+ <td style={{ textTransform: 'capitalize', fontSize: 13 }}>{sub.feature}</td>+ <td><SubscriptionStatus status={sub.status} cancelAtPeriodEnd={false} /></td>+ <td style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--text-tertiary)' }}>+ {formatDate(sub.canceled_at || sub.current_period_end)}+ </td>+ </tr>+ )+ })}+ </tbody>+ </table>+ </div>+ )}+ </>+ )+}++// ───────────── Invoices tab ─────────────++function InvoicesTab() {+ const { data: billing } = useQuery({ queryKey: ['billing'], queryFn: getBilling })+ const { data: invoiceData, isLoading } = useQuery({+ queryKey: ['invoices'], queryFn: () => getBillingInvoices(),+ })++ const isPro = billing?.plan === 'pro'++ if (isLoading) {+ return (+ <div style={{ display: 'flex', justifyContent: 'center', padding: 80 }}>+ <div className="loading-spinner" />+ </div>+ )+ }++ if (!isPro) {+ return (+ <div className="glass-card" style={{ padding: 28, textAlign: 'center' }}>+ <p style={{ fontSize: 14, color: 'var(--text-secondary)' }}>+ Invoices appear here once you're on the Pro plan or have a per-agent subscription.+ </p>+ </div>+ )+ }++ return (+ <div className="glass-card animate-in stagger-1" style={{ padding: '22px 24px' }}>+ <span className="section-title" style={{ marginBottom: 14, display: 'block' }}>Invoices</span>+ {!invoiceData?.invoices?.length ? (+ <div style={{ textAlign: 'center', padding: '40px 20px', color: 'var(--text-tertiary)', fontSize: 13 }}>+ No invoices yet — your first invoice will appear at the end of the billing period+ </div>+ ) : (+ <table className="data-table">+ <thead>+ <tr><th>Date</th><th>Number</th><th>Status</th><th>Amount</th><th></th></tr>+ </thead>+ <tbody>+ {invoiceData.invoices.map((inv: StripeInvoice) => (+ <tr key={inv.id}>+ <td style={{ fontFamily: 'var(--font-mono)', fontSize: 12 }}>+ {new Date(inv.created * 1000).toLocaleDateString()}+ </td>+ <td style={{ fontSize: 12 }}>{inv.number}</td>+ <td><InvoiceStatus status={inv.status} /></td>+ <td style={{ fontFamily: 'var(--font-mono)', fontSize: 13, fontWeight: 600 }}>+ ${(inv.amountDue / 100).toFixed(2)}+ </td>+ <td>+ {inv.hostedUrl && (+ <a href={inv.hostedUrl} target="_blank" rel="noreferrer"+ style={{ fontSize: 12, color: 'var(--accent-indigo)', textDecoration: 'none' }}>+ View+ </a>+ )}+ </td>+ </tr>+ ))}+ </tbody>+ </table>)}</div>)}+// ───────────── Helpers ─────────────++function formatDate(s?: string | null) {+ if (!s) return '—'+ const d = new Date(s)+ if (isNaN(d.getTime())) return '—'+ return d.toLocaleDateString()+}++function SubscriptionStatus({ status, cancelAtPeriodEnd }: { status: string; cancelAtPeriodEnd: boolean }) {+ let color = 'var(--text-tertiary)'+ let bg = 'rgba(255,255,255,0.04)'+ let label = status++ if (cancelAtPeriodEnd) {+ color = 'var(--accent-amber, #f59e0b)'+ bg = 'rgba(245,158,11,0.1)'+ label = 'cancels'+ } else if (status === 'active' || status === 'trialing') {+ color = 'var(--accent-emerald)'; bg = 'rgba(52,211,153,0.1)'+ } else if (status === 'past_due' || status === 'incomplete') {+ color = 'var(--accent-amber, #f59e0b)'; bg = 'rgba(245,158,11,0.1)'+ } else if (status === 'canceled' || status === 'unpaid' || status === 'incomplete_expired') {+ color = 'var(--accent-rose)'; bg = 'rgba(244,63,94,0.1)'+ }+ return (+ <span style={{+ display: 'inline-block', padding: '2px 8px', borderRadius: 4,+ fontSize: 11, fontWeight: 600, color, background: bg,+ textTransform: 'uppercase', letterSpacing: '0.5px',+ }}>{label}</span>+ )+}+function InvoiceStatus({ status }: { status: string }) {let color = 'var(--text-tertiary)'let bg = 'rgba(255,255,255,0.04)'diff --git a/web/src/pages/Checkpoints.tsx b/web/src/pages/Checkpoints.tsxindex 46c54a17..87985d2e 100644--- a/web/src/pages/Checkpoints.tsx+++ b/web/src/pages/Checkpoints.tsx@@ -58,29 +58,33 @@ export default function Checkpoints() {<code style={{ fontSize: 12 }}>{cp.sandboxId}</code></td><td>- <span style={{- fontSize: 11,- fontWeight: 600,- padding: '2px 8px',- borderRadius: 10,- background: cp.status === 'ready'- ? 'rgba(34, 197, 94, 0.08)'- : cp.status === 'failed'- ? 'rgba(251, 113, 133, 0.08)'- : 'rgba(234, 179, 8, 0.08)',- color: cp.status === 'ready'- ? 'var(--accent-green)'- : cp.status === 'failed'- ? 'var(--accent-rose)'- : '#eab308',- border: `1px solid ${- cp.status === 'ready'- ? 'rgba(34, 197, 94, 0.15)'+ <span+ style={{+ fontSize: 11,+ fontWeight: 600,+ padding: '2px 8px',+ borderRadius: 10,+ background: cp.status === 'ready'+ ? 'rgba(34, 197, 94, 0.08)': cp.status === 'failed'- ? 'rgba(251, 113, 133, 0.15)'- : 'rgba(234, 179, 8, 0.15)'- }`,- }}>+ ? 'rgba(251, 113, 133, 0.08)'+ : 'rgba(234, 179, 8, 0.08)',+ color: cp.status === 'ready'+ ? 'var(--accent-green)'+ : cp.status === 'failed'+ ? 'var(--accent-rose)'+ : '#eab308',+ border: `1px solid ${+ cp.status === 'ready'+ ? 'rgba(34, 197, 94, 0.15)'+ : cp.status === 'failed'+ ? 'rgba(251, 113, 133, 0.15)'+ : 'rgba(234, 179, 8, 0.15)'+ }`,+ cursor: cp.status === 'failed' && cp.errorMsg ? 'help' : 'default',+ }}+ title={cp.status === 'failed' && cp.errorMsg ? cp.errorMsg : undefined}+ >{cp.status === 'ready' ? 'Ready' : cp.status === 'failed' ? 'Failed' : 'Processing'}</span></td>diff --git a/web/src/pages/Dashboard.tsx b/web/src/pages/Dashboard.tsxindex 798c1889..10ed2f39 100644--- a/web/src/pages/Dashboard.tsx+++ b/web/src/pages/Dashboard.tsx@@ -177,6 +177,8 @@ function GettingStarted() {return (<div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>+ <DeployAgentBanner />+<StepCardindex={1}title="Install the OpenComputer skill"@@ -460,3 +462,89 @@ function formatDuration(session: Session): string {if (secs < 3600) return `${Math.round(secs / 60)}m`return `${Math.round(secs / 3600 * 10) / 10}h`}++// Deploy-managed-agent banner shown above the getting-started checklist on+// fresh signups. The Agents page has the same lobster mark in its empty+// state; keeping the two consistent makes the OpenClaw / managed-agent+// product visible from minute one without asking the user to navigate.+function DeployAgentBanner() {+ const navigate = useNavigate()+ return (+ <div+ onClick={() => navigate('/agents')}+ onKeyDown={(e) => {+ if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); navigate('/agents') }+ }}+ role="button"+ tabIndex={0}+ style={{+ display: 'flex', alignItems: 'center', gap: 18,+ padding: '20px 24px',+ border: '1px solid rgba(255,77,77,0.30)',+ borderRadius: 14,+ background:+ 'radial-gradient(ellipse at left, rgba(255,77,77,0.14), transparent 62%), rgba(255,77,77,0.04)',+ cursor: 'pointer',+ transition: 'background 0.12s ease, border-color 0.12s ease',+ }}+ onMouseEnter={(e) => { (e.currentTarget as HTMLDivElement).style.borderColor = 'rgba(255,77,77,0.55)' }}+ onMouseLeave={(e) => { (e.currentTarget as HTMLDivElement).style.borderColor = 'rgba(255,77,77,0.30)' }}+ >+ <DashClawLogo />+ <div style={{ flex: 1 }}>+ <div style={{ fontSize: 16, fontWeight: 700, fontFamily: 'var(--font-display)', marginBottom: 4 }}>+ Deploy an OpenClaw managed agent+ </div>+ <div style={{ fontSize: 13, color: 'var(--text-secondary)', lineHeight: 1.5 }}>+ Spin up a managed agent runtime with built-in chat, Telegram, and gbrain memory.+ We host the gateway and the model routing — you bring the prompt.+ </div>+ </div>+ <div+ style={{+ padding: '9px 18px',+ fontSize: 13, fontWeight: 600,+ background: 'var(--accent-indigo)', color: '#fff',+ borderRadius: 'var(--radius-sm)',+ whiteSpace: 'nowrap',+ }}+ >+ Deploy →+ </div>+ </div>+ )+}++// OpenClaw lobster mark — pulled directly from openclaw.ai/favicon.svg so the+// dashboard banner uses the same brand asset as the marketing site. Inline so+// it ships with the bundle (no extra HTTP fetch); gradient ID is scoped per+// page (`dash-…`) to avoid collisions when multiple copies render at once.+function DashClawLogo() {+ return (+ <svg+ width="56"+ height="56"+ viewBox="0 0 120 120"+ fill="none"+ xmlns="http://www.w3.org/2000/svg"+ aria-hidden="true"+ style={{ filter: 'drop-shadow(0 0 16px rgba(255,77,77,0.45))', flexShrink: 0 }}+ >+ <defs>+ <linearGradient id="dash-lobster-gradient" x1="0%" y1="0%" x2="100%" y2="100%">+ <stop offset="0%" stopColor="#ff4d4d" />+ <stop offset="100%" stopColor="#991b1b" />+ </linearGradient>+ </defs>+ <path d="M60 10 C30 10 15 35 15 55 C15 75 30 95 45 100 L45 110 L55 110 L55 100 C55 100 60 102 65 100 L65 110 L75 110 L75 100 C90 95 105 75 105 55 C105 35 90 10 60 10Z" fill="url(#dash-lobster-gradient)" />+ <path d="M20 45 C5 40 0 50 5 60 C10 70 20 65 25 55 C28 48 25 45 20 45Z" fill="url(#dash-lobster-gradient)" />+ <path d="M100 45 C115 40 120 50 115 60 C110 70 100 65 95 55 C92 48 95 45 100 45Z" fill="url(#dash-lobster-gradient)" />+ <path d="M45 15 Q35 5 30 8" stroke="#ff4d4d" strokeWidth="3" strokeLinecap="round" />+ <path d="M75 15 Q85 5 90 8" stroke="#ff4d4d" strokeWidth="3" strokeLinecap="round" />+ <circle cx="45" cy="35" r="6" fill="#050810" />+ <circle cx="75" cy="35" r="6" fill="#050810" />+ <circle cx="46" cy="34" r="2.5" fill="#00e5cc" />+ <circle cx="76" cy="34" r="2.5" fill="#00e5cc" />+ </svg>+ )+}diff --git a/web/src/pages/SessionDetail.tsx b/web/src/pages/SessionDetail.tsxindex ae0c0918..60e02003 100644--- a/web/src/pages/SessionDetail.tsx+++ b/web/src/pages/SessionDetail.tsx@@ -1,8 +1,9 @@import { useState } from 'react'import { useParams, useNavigate } from 'react-router-dom'-import { useQuery } from '@tanstack/react-query'-import { getSessionDetail, getSessionStats } from '../api/client'+import { useQuery, useQueryClient } from '@tanstack/react-query'+import { getSessionDetail, getSessionStats, rebootSession, powerCycleSession } from '../api/client'import Terminal from '../components/Terminal'+import LogsPanel from '../components/LogsPanel'function StatusBadge({ status }: { status: string }) {const cls =@@ -59,9 +60,54 @@ function StatCard({ label, value, sub }: { label: string; value: string; sub?: sexport default function SessionDetail() {const { sandboxId } = useParams<{ sandboxId: string }>()const navigate = useNavigate()+ const queryClient = useQueryClient()const [copiedUrl, setCopiedUrl] = useState<string | null>(null)const [showTerminal, setShowTerminal] = useState(false)+ const [showLogs, setShowLogs] = useState(false)const [showInternal, setShowInternal] = useState(false)+ const [resetState, setResetState] = useState<'idle' | 'rebooting' | 'power-cycling'>('idle')+ const [resetError, setResetError] = useState<string | null>(null)++ const handleReboot = async () => {+ if (resetState !== 'idle') return+ if (!confirm(+ 'Reboot this sandbox?\n\n' ++ 'The guest kernel will restart. Running processes are killed; ' ++ 'workspace data is preserved. Takes a few seconds.'+ )) return+ setResetState('rebooting')+ setResetError(null)+ try {+ await rebootSession(sandboxId!)+ queryClient.invalidateQueries({ queryKey: ['session-detail', sandboxId] })+ queryClient.invalidateQueries({ queryKey: ['session-stats', sandboxId] })+ } catch (e) {+ setResetError(e instanceof Error ? e.message : String(e))+ } finally {+ setResetState('idle')+ }+ }++ const handlePowerCycle = async () => {+ if (resetState !== 'idle') return+ if (!confirm(+ 'Power-cycle this sandbox?\n\n' ++ 'The QEMU process is destroyed and recreated with the same disks. ' ++ 'Use this if a regular reboot didn\'t recover. ' ++ 'Workspace data is preserved; takes ~30 seconds.'+ )) return+ setResetState('power-cycling')+ setResetError(null)+ try {+ await powerCycleSession(sandboxId!)+ queryClient.invalidateQueries({ queryKey: ['session-detail', sandboxId] })+ queryClient.invalidateQueries({ queryKey: ['session-stats', sandboxId] })+ } catch (e) {+ setResetError(e instanceof Error ? e.message : String(e))+ } finally {+ setResetState('idle')+ }+ }const { data: session, isLoading } = useQuery({queryKey: ['session-detail', sandboxId],@@ -133,6 +179,24 @@ export default function SessionDetail() {{/* Actions */}<div style={{ display: 'flex', gap: 8 }}>+ {/* Logs is available regardless of sandbox status — Axiom+ retains events past the sandbox's lifetime, so users can+ fetch logs of stopped / hibernated / errored sandboxes. */}+ <button+ className={showLogs ? 'btn-primary' : 'btn-ghost'}+ onClick={() => setShowLogs(!showLogs)}+ title="Live logs from /var/log + every exec'd command"+ >+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">+ <line x1="8" y1="6" x2="21" y2="6" />+ <line x1="8" y1="12" x2="21" y2="12" />+ <line x1="8" y1="18" x2="21" y2="18" />+ <line x1="3" y1="6" x2="3.01" y2="6" />+ <line x1="3" y1="12" x2="3.01" y2="12" />+ <line x1="3" y1="18" x2="3.01" y2="18" />+ </svg>+ Logs+ </button>{session.status === 'running' && (<><button@@ -145,10 +209,47 @@ export default function SessionDetail() {</svg>Terminal</button>+ <button+ className="btn-ghost"+ onClick={handleReboot}+ disabled={resetState !== 'idle'}+ title="Soft restart: kernel reboots, workspace preserved"+ >+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">+ <polyline points="23 4 23 10 17 10" />+ <path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10" />+ </svg>+ {resetState === 'rebooting' ? 'Rebooting…' : 'Reboot'}+ </button>+ <button+ className="btn-ghost"+ onClick={handlePowerCycle}+ disabled={resetState !== 'idle'}+ title="Hard restart: rebuilds VM, workspace preserved. Use if reboot didn't recover."+ >+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">+ <path d="M18.36 6.64a9 9 0 1 1-12.73 0" />+ <line x1="12" y1="2" x2="12" y2="12" />+ </svg>+ {resetState === 'power-cycling' ? 'Power-cycling…' : 'Power Cycle'}+ </button></>)}</div></div>+ {resetError && (+ <div style={{+ marginTop: 12,+ padding: '10px 14px',+ background: 'rgba(239,68,68,0.08)',+ border: '1px solid rgba(239,68,68,0.3)',+ borderRadius: 'var(--radius-sm)',+ color: 'var(--text-error, #f87171)',+ fontSize: 13,+ }}>+ Reset failed: {resetError}+ </div>+ )}</div>{/* Terminal */}@@ -158,6 +259,13 @@ export default function SessionDetail() {</div>)}+ {/* Logs — works for all sandbox states (Axiom retains past-lifetime). */}+ {showLogs && (+ <div className="glass-card animate-in" style={{ padding: 20, marginBottom: 16 }}>+ <LogsPanel sandboxId={sandboxId!} onClose={() => setShowLogs(false)} />+ </div>+ )}+{/* Stats cards — only for running sandboxes */}{session.status === 'running' && (<div className="glass-card animate-in stagger-1" style={{ padding: 20, marginBottom: 16 }}>@@ -301,7 +409,6 @@ export default function SessionDetail() {<DetailRow label="Timeout" value={session.config?.timeout ? `${session.config.timeout}s` : '300s'} /><DetailRow label="CPUs" value={String(session.config?.cpuCount ?? 1)} /><DetailRow label="Memory" value={`${session.config?.memoryMB ?? 512} MB`} />- <DetailRow label="Network" value={session.config?.networkEnabled ? 'Enabled' : 'Disabled'} /><DetailRow label="Started" value={new Date(session.startedAt).toLocaleString()} />{session.stoppedAt && (<DetailRow label="Stopped" value={new Date(session.stoppedAt).toLocaleString()} />diff --git a/web/src/vite-env.d.ts b/web/src/vite-env.d.tsindex 11f02fe2..a5f23e11 100644--- a/web/src/vite-env.d.ts+++ b/web/src/vite-env.d.ts@@ -1 +1,10 @@/// <reference types="vite/client" />++interface ImportMetaEnv {+ readonly VITE_PUBLIC_POSTHOG_PROJECT_TOKEN?: string+ readonly VITE_PUBLIC_POSTHOG_HOST?: string+}++interface ImportMeta {+ readonly env: ImportMetaEnv+}