Skip to content

An open-source, faster Devin alternative

TypeScript

create edge billing cutover with feature flags for edge and cp

Brian Reardonfc881207388d
diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.ts
index d3193daa..13c1f725 100644
--- a/cloudflare-workers/api-edge/src/index.ts
+++ b/cloudflare-workers/api-edge/src/index.ts
@@ -872,6 +872,58 @@ async function orgPolicy(req: Request, env: Env): Promise<Response> {
});
}
+// ── /internal/usage-parity ────────────────────────────────────────────────
+
+// HMAC-auth'd read-only endpoint the cell's usage-parity checker polls to
+// compare edge-measured Pro usage against the cell's authoritative
+// sandbox_scale_events. Returns per-org GB-seconds over [from,to) computed from
+// the RAW tick samples (usage_samples), not the priced meter rows — the point
+// is to validate measurement (ticks vs scale-event intervals) independent of
+// the rollup/pricing layer, and it works for legacy and unified alike because
+// GB-seconds is mode-independent.
+//
+// from/to are unix seconds; samples are keyed by ts (unix ms). Same HMAC scheme
+// as haltList/orgPolicy. NOTE: this reads usage_samples, so the sample-retention
+// window must exceed the parity lookback (samples aren't deleted at rollup, only
+// flagged rolled_up).
+async function usageParity(req: Request, env: Env): Promise<Response> {
+ const ts = req.headers.get("X-Timestamp") ?? "";
+ const sig = req.headers.get("X-Signature") ?? "";
+ if (!ts || !sig) return json({ error: "missing signature headers" }, 400);
+ const tsNum = Number.parseInt(ts, 10);
+ if (!Number.isFinite(tsNum)) return json({ error: "invalid timestamp" }, 400);
+ const now = Math.floor(Date.now() / 1000);
+ if (Math.abs(now - tsNum) > 5 * 60) return json({ error: "timestamp out of window" }, 401);
+
+ const url = new URL(req.url);
+ const expected = await hmacHex(env.EVENT_SECRET, `${ts}.${url.pathname}${url.search}`);
+ if (!constantTimeEqual(expected, sig)) return json({ error: "signature mismatch" }, 401);
+
+ const from = Number.parseInt(url.searchParams.get("from") ?? "", 10);
+ const to = Number.parseInt(url.searchParams.get("to") ?? "", 10);
+ if (!Number.isFinite(from) || !Number.isFinite(to) || to <= from) {
+ return json({ error: "from/to required (unix seconds, to > from)" }, 400);
+ }
+
+ const res = await env.OPENCOMPUTER_DB.prepare(
+ `SELECT org_id AS org_id,
+ SUM(memory_mb * interval_s) AS mem_mb_secs,
+ COUNT(*) AS samples
+ FROM usage_samples
+ WHERE ts >= ?1 AND ts < ?2
+ GROUP BY org_id`,
+ )
+ .bind(from * 1000, to * 1000)
+ .all<{ org_id: string; mem_mb_secs: number; samples: number }>();
+
+ const orgs = (res.results ?? []).map((r) => ({
+ org_id: r.org_id,
+ gb_seconds: (r.mem_mb_secs ?? 0) / 1024,
+ samples: r.samples ?? 0,
+ }));
+ return json({ window: { from, to }, orgs, as_of: now });
+}
+
async function hmacHex(secret: string, data: string): Promise<string> {
const key = await crypto.subtle.importKey(
"raw",
@@ -1280,6 +1332,11 @@ export default {
return orgPolicy(req, env);
}
+ if (path === "/internal/usage-parity") {
+ if (req.method !== "GET") return json({ error: "method not allowed" }, 405);
+ return usageParity(req, env);
+ }
+
// /internal/admin/do-mark-free — operator-only escape hatch to flip a
// CreditAccount DO's internal plan from "pro" back to "free" without
// running a real Stripe subscription.deleted webhook. HMAC-auth'd with
diff --git a/cloudflare-workers/api-edge/wrangler.toml b/cloudflare-workers/api-edge/wrangler.toml
index f5d32907..e6235866 100644
--- a/cloudflare-workers/api-edge/wrangler.toml
+++ b/cloudflare-workers/api-edge/wrangler.toml
@@ -68,6 +68,19 @@ script_name = "opensandbox-edge-dev"
tag = "v1"
new_sqlite_classes = ["CreditAccount"]
+# v2 was applied to the deployed dev worker out-of-band (it created a
+# SandboxWsGateway DO from a branch never merged here). Placeholder so the
+# ledger is contiguous and wrangler can append v3.
+[[migrations]]
+tag = "v2"
+
+# This branch doesn't define SandboxWsGateway. Delete the orphaned class +
+# its DOs so this branch can deploy (CF blocks dropping a depended-on class
+# without an explicit delete-class migration). CreditAccount is untouched.
+[[migrations]]
+tag = "v3"
+deleted_classes = ["SandboxWsGateway"]
+
# Secrets (set via `wrangler secret put`):
# SESSION_JWT_SECRET — HMAC for session JWT (shared with all CPs in cell fleet)
# CF_ADMIN_SECRET — HMAC for /admin/halt-org and /admin/resume-org callbacks to CPs
diff --git a/cloudflare-workers/billing-rollup/package.json b/cloudflare-workers/billing-rollup/package.json
new file mode 100644
index 00000000..c0875722
--- /dev/null
+++ b/cloudflare-workers/billing-rollup/package.json
@@ -0,0 +1,17 @@
+{
+ "name": "opensandbox-billing-rollup",
+ "version": "0.1.0",
+ "private": true,
+ "type": "module",
+ "scripts": {
+ "dev": "wrangler dev",
+ "deploy": "wrangler deploy",
+ "test": "vitest"
+ },
+ "devDependencies": {
+ "@cloudflare/workers-types": "^4.20240924.0",
+ "typescript": "^5.5.0",
+ "vitest": "^2.0.0",
+ "wrangler": "^4.86.0"
+ }
+}
diff --git a/cloudflare-workers/billing-rollup/src/index.ts b/cloudflare-workers/billing-rollup/src/index.ts
new file mode 100644
index 00000000..2614cd67
--- /dev/null
+++ b/cloudflare-workers/billing-rollup/src/index.ts
@@ -0,0 +1,328 @@
+// billing-rollup Worker — the global Pro-billing rollup cron.
+//
+// Runs on a schedule (see wrangler [triggers]). Each run:
+// 1. ROLL: aggregate closed buckets of D1 `usage_samples` into the
+// `usage_meter_events` outbox — one row per Stripe meter event. Pricing is
+// billing_mode-aware: unified orgs get a single flat GB-second overage
+// meter; legacy orgs get one per-tier seconds meter per memory tier. Marks
+// the consumed samples rolled_up=1.
+// 2. SEND: ship pending outbox rows to Stripe meter events, mark them 'sent'.
+// Skipped entirely in shadow mode (rows are written as 'shadow' and never
+// ship) — that's the parity-validation phase: the edge computes meter
+// events next to the cell's billable_events so they can be diffed before
+// the edge ever bills a customer.
+//
+// This is the edge analog of the cell's capacity allocator + BillableEventsSender,
+// reading edge `usage_samples` (the `sandbox_scale_events` analog) instead of
+// Postgres. Reserved capacity and disk overage are NOT handled here — they don't
+// come from per-sandbox ticks and need their own paths.
+//
+// Idempotency: outbox `id` is deterministic ("{org}:{bucket_start}:{meter}"), so
+// re-running a bucket recomputes identical ids (ON CONFLICT DO NOTHING), and the
+// same id is the Stripe meter-event Identifier (Stripe dedups within 24h). A
+// crash anywhere in roll→send→mark is safe to replay.
+
+import { legacyMeterEventName, overageMeterEventName } from "./pricing";
+
+export interface Env {
+ OPENCOMPUTER_DB: D1Database;
+ STRIPE_API_KEY: string;
+ WORKER_ENV: string;
+ // "false" => live (ship to Stripe). Anything else (incl. unset) => shadow.
+ // Defaults to shadow so we never bill before the cutover is explicitly armed.
+ SHADOW?: string;
+ BUCKET_SECONDS?: string; // default 3600 (hourly)
+ GRACE_SECONDS?: string; // default 600 — watermark so late samples settle
+}
+
+const BUCKET_SECONDS_DEFAULT = 3600;
+const GRACE_SECONDS_DEFAULT = 600;
+const SEND_LIMIT = 500;
+
+function isShadow(env: Env): boolean {
+ return env.SHADOW !== "false";
+}
+function bucketSeconds(env: Env): number {
+ return Number.parseInt(env.BUCKET_SECONDS ?? "", 10) || BUCKET_SECONDS_DEFAULT;
+}
+function graceSeconds(env: Env): number {
+ const g = Number.parseInt(env.GRACE_SECONDS ?? "", 10);
+ return Number.isFinite(g) && g >= 0 ? g : GRACE_SECONDS_DEFAULT;
+}
+
+interface RollupStats {
+ buckets: number;
+ meterRows: number;
+ samplesRolled: number;
+}
+interface SendStats {
+ sent: number;
+ failed: number;
+ skippedNoCustomer: number;
+}
+
+export default {
+ async scheduled(_event: ScheduledController, env: Env, _ctx: ExecutionContext): Promise<void> {
+ const nowMs = Date.now();
+ const shadow = isShadow(env);
+ try {
+ const roll = await runRollup(env, nowMs);
+ console.log(
+ `billing-rollup: rolled ${roll.buckets} bucket(s) → ${roll.meterRows} meter row(s), ${roll.samplesRolled} sample(s) consumed (shadow=${shadow})`,
+ );
+ if (!shadow) {
+ const send = await sendPending(env, nowMs);
+ console.log(
+ `billing-rollup: sent=${send.sent} failed=${send.failed} skippedNoCustomer=${send.skippedNoCustomer} (failed rows stay pending for retry)`,
+ );
+ } else {
+ console.log("billing-rollup: shadow mode — outbox written as 'shadow', nothing shipped to Stripe");
+ }
+ } catch (err) {
+ console.error("billing-rollup: run failed", err);
+ throw err; // surface to CF so the failure is visible in dashboards
+ }
+ },
+
+ // Health + dev-only manual trigger. The manual /run is handy for dev smoke
+ // tests (the scheduled trigger fires hourly); it's disabled in prod so the
+ // cron is the only thing that can move money.
+ async fetch(req: Request, env: Env): Promise<Response> {
+ const url = new URL(req.url);
+ if (url.pathname === "/health") {
+ return json({ ok: true, env: env.WORKER_ENV, shadow: isShadow(env) });
+ }
+ if (url.pathname === "/run" && req.method === "POST") {
+ if (env.WORKER_ENV === "prod") return new Response("not found", { status: 404 });
+ const nowMs = Date.now();
+ const roll = await runRollup(env, nowMs);
+ const send = isShadow(env) ? null : await sendPending(env, nowMs);
+ return json({ ok: true, shadow: isShadow(env), roll, send });
+ }
+ return new Response("not found", { status: 404 });
+ },
+} satisfies ExportedHandler<Env>;
+
+// runRollup processes every closed bucket (bucket_end ≤ now − grace) that still
+// has unrolled samples. The grace window lets late-delivered samples (Redis
+// poll + forwarder + ingest latency, or PEL retries) land before we freeze a
+// bucket — a sample arriving after its bucket is rolled is a known, bounded
+// straggler (see runbook "acceptable drift").
+async function runRollup(env: Env, nowMs: number): Promise<RollupStats> {
+ const bucketSec = bucketSeconds(env);
+ const watermark = Math.floor(nowMs / 1000) - graceSeconds(env);
+
+ const bucketsRes = await env.OPENCOMPUTER_DB.prepare(
+ `SELECT DISTINCT ((ts / 1000) / ?1) * ?1 AS bucket_start
+ FROM usage_samples
+ WHERE rolled_up = 0
+ AND ((ts / 1000) / ?1) * ?1 + ?1 <= ?2
+ ORDER BY bucket_start`,
+ )
+ .bind(bucketSec, watermark)
+ .all<{ bucket_start: number }>();
+
+ const stats: RollupStats = { buckets: 0, meterRows: 0, samplesRolled: 0 };
+ for (const row of bucketsRes.results ?? []) {
+ const r = await rollBucket(env, row.bucket_start, bucketSec, nowMs);
+ stats.buckets += 1;
+ stats.meterRows += r.meterRows;
+ stats.samplesRolled += r.samplesRolled;
+ }
+ return stats;
+}
+
+interface TierAgg {
+ org_id: string;
+ memory_mb: number;
+ secs: number;
+ mem_mb_secs: number;
+ billing_mode: string;
+}
+
+async function rollBucket(
+ env: Env,
+ bucketStart: number,
+ bucketSec: number,
+ nowMs: number,
+): Promise<{ meterRows: number; samplesRolled: number }> {
+ const bucketEnd = bucketStart + bucketSec;
+ const startMs = bucketStart * 1000;
+ const endMs = bucketEnd * 1000;
+
+ // Aggregate unrolled samples in the bucket by (org, tier). We carry both
+ // seconds (legacy per-tier unit) and memory_mb·seconds (→ GB-seconds for
+ // unified) so the per-org branch below can pick whichever the mode needs.
+ const aggRes = await env.OPENCOMPUTER_DB.prepare(
+ `SELECT s.org_id AS org_id,
+ s.memory_mb AS memory_mb,
+ SUM(s.interval_s) AS secs,
+ SUM(s.memory_mb * s.interval_s) AS mem_mb_secs,
+ o.billing_mode AS billing_mode
+ FROM usage_samples s
+ JOIN orgs o ON o.id = s.org_id
+ WHERE s.rolled_up = 0 AND s.ts >= ?1 AND s.ts < ?2
+ GROUP BY s.org_id, s.memory_mb`,
+ )
+ .bind(startMs, endMs)
+ .all<TierAgg>();
+
+ // Group tier rows by org so we can decide the meter shape per billing_mode.
+ const byOrg = new Map<string, TierAgg[]>();
+ for (const r of aggRes.results ?? []) {
+ const list = byOrg.get(r.org_id);
+ if (list) list.push(r);
+ else byOrg.set(r.org_id, [r]);
+ }
+
+ const state = isShadow(env) ? "shadow" : "pending";
+ const nowSec = Math.floor(nowMs / 1000);
+ const insert = env.OPENCOMPUTER_DB.prepare(
+ `INSERT INTO usage_meter_events
+ (id, org_id, meter_event_name, value, billing_mode, bucket_start, bucket_end, state, created_at)
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)
+ ON CONFLICT(id) DO NOTHING`,
+ );
+
+ const stmts: D1PreparedStatement[] = [];
+ for (const [orgId, tiers] of byOrg) {
+ const mode = tiers[0].billing_mode;
+ if (mode === "legacy") {
+ // One meter event per memory tier; value = seconds at that tier.
+ for (const t of tiers) {
+ const meter = legacyMeterEventName(t.memory_mb);
+ if (!meter) {
+ console.warn(`billing-rollup: org=${orgId} unknown tier memory_mb=${t.memory_mb} — skipping (no legacy meter)`);
+ continue;
+ }
+ if (t.secs <= 0) continue;
+ stmts.push(
+ insert.bind(`${orgId}:${bucketStart}:${meter}`, orgId, meter, t.secs, "legacy", bucketStart, bucketEnd, state, nowSec),
+ );
+ }
+ } else {
+ // unified — single flat overage meter; value = GB-seconds across tiers.
+ let memMbSecs = 0;
+ for (const t of tiers) memMbSecs += t.mem_mb_secs;
+ const gbSeconds = memMbSecs / 1024;
+ if (gbSeconds <= 0) continue;
+ const meter = overageMeterEventName();
+ stmts.push(
+ insert.bind(`${orgId}:${bucketStart}:${meter}`, orgId, meter, gbSeconds, "unified", bucketStart, bucketEnd, state, nowSec),
+ );
+ }
+ }
+
+ // Outbox-first, then mark samples rolled — so a crash between the two just
+ // replays: re-aggregating recomputes identical deterministic ids (deduped),
+ // and the unmarked samples get picked up and marked next run. Marking first
+ // would risk dropping samples whose meter rows never landed (underbilling).
+ const markRolled = env.OPENCOMPUTER_DB.prepare(
+ `UPDATE usage_samples SET rolled_up = 1 WHERE rolled_up = 0 AND ts >= ?1 AND ts < ?2`,
+ ).bind(startMs, endMs);
+
+ const batchRes = await env.OPENCOMPUTER_DB.batch([...stmts, markRolled]);
+ const marked = batchRes[batchRes.length - 1]?.meta?.changes ?? 0;
+ return { meterRows: stmts.length, samplesRolled: marked };
+}
+
+interface PendingMeterRow {
+ id: string;
+ org_id: string;
+ meter_event_name: string;
+ value: number;
+ bucket_end: number;
+ cust: string | null;
+}
+
+// sendPending ships pending outbox rows to Stripe. stripe_customer_id is read
+// fresh from orgs at send time (it can be set after the usage was incurred —
+// e.g. an org metered while still finishing Stripe onboarding). Rows for an org
+// with no customer yet stay pending and retry on a later run.
+async function sendPending(env: Env, nowMs: number): Promise<SendStats> {
+ const res = await env.OPENCOMPUTER_DB.prepare(
+ `SELECT m.id AS id, m.org_id AS org_id, m.meter_event_name AS meter_event_name,
+ m.value AS value, m.bucket_end AS bucket_end, o.stripe_customer_id AS cust
+ FROM usage_meter_events m
+ JOIN orgs o ON o.id = m.org_id
+ WHERE m.state = 'pending'
+ ORDER BY m.bucket_start
+ LIMIT ?1`,
+ )
+ .bind(SEND_LIMIT)
+ .all<PendingMeterRow>();
+
+ const stats: SendStats = { sent: 0, failed: 0, skippedNoCustomer: 0 };
+ const nowSec = Math.floor(nowMs / 1000);
+ for (const r of res.results ?? []) {
+ if (!r.cust) {
+ stats.skippedNoCustomer += 1;
+ continue;
+ }
+ try {
+ const identifier = await reportMeterEvent(env, r.meter_event_name, r.cust, r.value, r.id, r.bucket_end);
+ await env.OPENCOMPUTER_DB.prepare(
+ `UPDATE usage_meter_events SET state = 'sent', stripe_identifier = ?1, sent_at = ?2 WHERE id = ?3`,
+ )
+ .bind(identifier, nowSec, r.id)
+ .run();
+ stats.sent += 1;
+ } catch (err) {
+ // Leave the row 'pending' — Stripe dedups on identifier, so re-send next
+ // run is safe even if Stripe actually accepted it but we failed to mark.
+ console.error(`billing-rollup: send ${r.id} (meter=${r.meter_event_name} org=${r.org_id}) failed`, err);
+ stats.failed += 1;
+ }
+ }
+ return stats;
+}
+
+// reportMeterEvent POSTs one Stripe meter event. identifier = outbox id makes
+// at-least-once shipping safe (Stripe dedups within 24h). timestamp = bucket_end,
+// the moment usage was "incurred" — stable across retries. Mirrors the Go
+// StripeClient.ReportMeterEvent; value is high-precision so fractional
+// GB-seconds aren't truncated.
+async function reportMeterEvent(
+ env: Env,
+ eventName: string,
+ customerID: string,
+ value: number,
+ identifier: string,
+ timestampSec: number,
+): Promise<string> {
+ const body = new URLSearchParams({
+ event_name: eventName,
+ identifier,
+ timestamp: String(timestampSec),
+ "payload[stripe_customer_id]": customerID,
+ "payload[value]": value.toFixed(6),
+ });
+ const resp = await fetch("https://api.stripe.com/v1/billing/meter_events", {
+ method: "POST",
+ headers: {
+ authorization: "Bearer " + env.STRIPE_API_KEY,
+ "stripe-version": "2024-06-20",
+ "content-type": "application/x-www-form-urlencoded",
+ },
+ body: body.toString(),
+ });
+ const text = await resp.text();
+ let parsed: any;
+ try {
+ parsed = JSON.parse(text);
+ } catch {
+ parsed = { raw: text };
+ }
+ if (!resp.ok) {
+ throw new Error(parsed?.error?.message ?? parsed?.raw ?? `stripe meter_events returned ${resp.status}`);
+ }
+ // Stripe echoes the identifier on success; fall back to ours if absent.
+ return parsed?.identifier ?? identifier;
+}
+
+function json(body: unknown, status = 200): Response {
+ return new Response(JSON.stringify(body), {
+ status,
+ headers: { "content-type": "application/json" },
+ });
+}
diff --git a/cloudflare-workers/billing-rollup/src/pricing.ts b/cloudflare-workers/billing-rollup/src/pricing.ts
new file mode 100644
index 00000000..2d44dce9
--- /dev/null
+++ b/cloudflare-workers/billing-rollup/src/pricing.ts
@@ -0,0 +1,39 @@
+// Pricing constants mirrored from internal/billing/pricing.go and stripe.go.
+//
+// KEEP IN SYNC with the Go side — these derive Stripe meter event_names, and
+// the whole point of the rollup cron is to emit the SAME meter events the
+// cell's billing pipeline does so the edge output is parity-checkable. If the
+// Go meter keys change, change them here too.
+//
+// Meter event_name derivation (stripe.go): "sandbox_compute_" + <key>.
+
+// All Stripe meter event_names share this prefix (stripe.go:80,247-248).
+const METER_PREFIX = "sandbox_compute_";
+
+// Legacy per-tier metering. memory_mb → Stripe meter key (pricing.go TierMeterKey).
+// NEVER change these values: meters hold historical usage across price versions.
+const TIER_METER_KEY: Record<number, string> = {
+ 1024: "sandbox_1gb",
+ 4096: "sandbox_4gb",
+ 8192: "sandbox_8gb",
+ 16384: "sandbox_16gb",
+ 32768: "sandbox_32gb",
+ 65536: "sandbox_64gb",
+};
+
+// Unified flat overage meter (pricing.go OverageMeterKey). A single meter,
+// flat across all sandbox sizes, billed in GB-seconds.
+const OVERAGE_METER_KEY = "sandbox_overage";
+
+// legacyMeterEventName returns the Stripe meter event_name for a legacy
+// per-tier meter, or null if memory_mb isn't an allowed tier (defensive — pro
+// sandboxes always run an allowed tier, but a malformed sample shouldn't bill).
+export function legacyMeterEventName(memoryMB: number): string | null {
+ const key = TIER_METER_KEY[memoryMB];
+ return key ? METER_PREFIX + key : null;
+}
+
+// overageMeterEventName returns the single unified overage meter event_name.
+export function overageMeterEventName(): string {
+ return METER_PREFIX + OVERAGE_METER_KEY;
+}
diff --git a/cloudflare-workers/billing-rollup/tsconfig.json b/cloudflare-workers/billing-rollup/tsconfig.json
new file mode 100644
index 00000000..50af4e47
--- /dev/null
+++ b/cloudflare-workers/billing-rollup/tsconfig.json
@@ -0,0 +1,17 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "ES2022",
+ "moduleResolution": "Bundler",
+ "lib": ["ES2022"],
+ "types": ["@cloudflare/workers-types"],
+ "strict": true,
+ "noImplicitAny": true,
+ "esModuleInterop": true,
+ "skipLibCheck": true,
+ "forceConsistentCasingInFileNames": true,
+ "isolatedModules": true,
+ "noEmit": true
+ },
+ "include": ["src/**/*.ts"]
+}
diff --git a/cloudflare-workers/billing-rollup/wrangler.prod.toml b/cloudflare-workers/billing-rollup/wrangler.prod.toml
new file mode 100644
index 00000000..5a8e2f52
--- /dev/null
+++ b/cloudflare-workers/billing-rollup/wrangler.prod.toml
@@ -0,0 +1,30 @@
+# billing-rollup Worker — PROD on Mo's CF account.
+# Mirrors wrangler.toml (dev). Deploy: `wrangler deploy -c wrangler.prod.toml`
+#
+# Ships nothing until SHADOW is flipped to "false" — keep it shadow on prod
+# until dev parity has been clean and prod has soaked.
+# Secrets: wrangler secret put STRIPE_API_KEY --config wrangler.prod.toml
+# (Stripe LIVE-mode key on prod)
+
+name = "opencomputer-billing-rollup-prod"
+main = "src/index.ts"
+compatibility_date = "2026-04-28"
+compatibility_flags = ["nodejs_compat"]
+account_id = "b8f23cb87a7a6c64040d3134643da448"
+
+[triggers]
+crons = ["*/15 * * * *"]
+
+[[d1_databases]]
+binding = "OPENCOMPUTER_DB"
+database_name = "opencomputer-prod"
+database_id = "8329e0f0-100d-445a-bf89-95c065f15dbb"
+
+[vars]
+WORKER_ENV = "prod"
+SHADOW = "true"
+BUCKET_SECONDS = "3600"
+GRACE_SECONDS = "600"
+
+[[tail_consumers]]
+service = "opencomputer-log-tail-prod"
diff --git a/cloudflare-workers/billing-rollup/wrangler.toml b/cloudflare-workers/billing-rollup/wrangler.toml
new file mode 100644
index 00000000..a4a873f2
--- /dev/null
+++ b/cloudflare-workers/billing-rollup/wrangler.toml
@@ -0,0 +1,37 @@
+# billing-rollup Worker — global Pro-billing rollup cron (DEV).
+#
+# Hourly: aggregates D1 `usage_samples` into the `usage_meter_events` outbox
+# (billing_mode-aware), then ships pending outbox rows to Stripe meter events.
+# In shadow mode it writes the outbox but ships nothing — that's the parity
+# phase where edge meter events are diffed against the cell's billable_events.
+#
+# Deploy: wrangler deploy
+# Secrets: wrangler secret put STRIPE_API_KEY (Stripe TEST-mode key on dev)
+# Manual: curl -X POST https://<worker>.workers.dev/run (dev only)
+
+name = "opensandbox-billing-rollup-dev"
+main = "src/index.ts"
+compatibility_date = "2026-04-28"
+compatibility_flags = ["nodejs_compat"]
+account_id = "1241f114453e32d292197e3fb36210b2"
+
+# Runs every 15 min; the grace watermark (GRACE_SECONDS) decides which buckets
+# are closed enough to roll, so a frequent trigger just means low latency to
+# pick up a freshly-settled bucket — it never double-bills (deterministic ids).
+[triggers]
+crons = ["*/15 * * * *"]
+
+[[d1_databases]]
+binding = "OPENCOMPUTER_DB"
+database_name = "opencomputer-dev"
+database_id = "f9e534bf-a9f3-4b30-81cd-f9eb9087e96d"
+
+[vars]
+WORKER_ENV = "dev"
+# Shadow until parity is clean. Set to "false" to arm live Stripe metering.
+SHADOW = "true"
+BUCKET_SECONDS = "3600"
+GRACE_SECONDS = "600"
+
+[[tail_consumers]]
+service = "opensandbox-log-tail"
diff --git a/cloudflare-workers/events-ingest/src/index.ts b/cloudflare-workers/events-ingest/src/index.ts
index 7487790c..14688930 100644
--- a/cloudflare-workers/events-ingest/src/index.ts
+++ b/cloudflare-workers/events-ingest/src/index.ts
@@ -345,8 +345,58 @@ export default {
];
});
+ // Authoritative plan resolution. The envelope's `plan` is the worker's
+ // cell-local-PG view, which goes stale on upgrade/downgrade — plan changes
+ // globally via the edge, and no single cell has the complete picture. D1
+ // orgs.plan is the source of truth and we're already on the edge with D1 in
+ // hand, so resolve it here and route by it. Without this, a free→pro upgrade
+ // leaks usage: stale 'free' ticks hit the DO (a no-op for a now-pro org) and
+ // never get sampled. Falls back to the (stale) envelope plan ONLY if the D1
+ // lookup itself fails — degraded, but no worse than trusting it outright.
+ const tickOrgIds = [
+ ...new Set(fresh.filter((e) => e.type === "usage_tick" && e.org_id).map((e) => e.org_id as string)),
+ ];
+ const planLookup = await resolvePlans(env, tickOrgIds);
+ const planFor = (e: SandboxEventEnvelope): string | undefined =>
+ planLookup.ok ? (e.org_id ? planLookup.byOrg.get(e.org_id) : undefined) : e.plan;
+
+ // Pro-tier usage samples: land each pro `usage_tick`'s resource dimensions
+ // into usage_samples for the rollup cron (the edge analog of the cell's
+ // sandbox_scale_events → billable_events path). Free orgs are debited via
+ // the DO fan-out below and need no sample row. id is the event UUID so the
+ // ON CONFLICT(id) DO NOTHING dedup matches the events table — the forwarder
+ // is at-least-once and additive billing must not double-count on replay.
+ //
+ // This goes in the main batch (not waitUntil) on purpose: unlike the
+ // cross-DO debit fan-out, it's a local D1 write, so it should share the
+ // batch's retry-on-failure guarantee (503 → CP forwarder keeps the PEL).
+ const usageSampleInsert = env.OPENCOMPUTER_DB.prepare(
+ `INSERT INTO usage_samples (id, org_id, sandbox_id, memory_mb, cpu_count, interval_s, ts, cell_id)
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)
+ ON CONFLICT(id) DO NOTHING`,
+ );
+ const usageSampleBatches = fresh
+ .filter((e) => e.type === "usage_tick" && planFor(e) === "pro" && e.org_id && e.sandbox_id)
+ .map((e) => {
+ const p = (e.payload ?? {}) as {
+ memory_mb?: number;
+ cpu_count?: number;
+ interval_s?: number;
+ };
+ return usageSampleInsert.bind(
+ e.id,
+ e.org_id,
+ e.sandbox_id,
+ p.memory_mb ?? 0,
+ p.cpu_count ?? 0,
+ p.interval_s ?? 0,
+ Date.parse(e.timestamp) || Date.now(),
+ e.cell_id,
+ );
+ });
+
try {
- await env.OPENCOMPUTER_DB.batch([...batches, ...capacityBatches, ...lifecycleBatches, ...checkpointBatches, ...imageBatches]);
+ await env.OPENCOMPUTER_DB.batch([...batches, ...capacityBatches, ...lifecycleBatches, ...checkpointBatches, ...imageBatches, ...usageSampleBatches]);
} catch (err) {
// Database errors are retryable — return 5xx so the CP forwarder
// leaves the batch in the PEL.
@@ -374,9 +424,10 @@ export default {
//
// Pro orgs are filtered here (cheap) rather than in the DO so we avoid
// even allocating the DO stub for orgs that don't need debit accounting.
- // Events without plan="free" are silently skipped — the CP forwarder
- // populates `plan` from PG at emit time.
- const debitTargets = fresh.filter((e) => e.type === "usage_tick" && e.plan === "free" && e.org_id);
+ // Plan comes from the authoritative D1 lookup (planFor), not the stale
+ // envelope value — so a free→pro upgrade stops debiting immediately and a
+ // pro→free downgrade resumes it, with no dependency on cell-PG freshness.
+ const debitTargets = fresh.filter((e) => e.type === "usage_tick" && planFor(e) === "free" && e.org_id);
if (debitTargets.length > 0) {
ctx.waitUntil(fanoutDebits(env, debitTargets));
}
@@ -415,6 +466,32 @@ async function fanoutDebits(env: Env, events: SandboxEventEnvelope[]): Promise<v
);
}
+// resolvePlans fetches the authoritative plan for each org from D1 orgs.plan
+// (the global source of truth) in one batched query. Returns ok=false if the
+// lookup fails, signalling callers to fall back to the envelope plan rather
+// than dropping billing entirely. Orgs absent from D1 (new-org race) are simply
+// missing from the map → treated as unknown plan → skipped, the safe default.
+async function resolvePlans(
+ env: Env,
+ orgIds: string[],
+): Promise<{ ok: boolean; byOrg: Map<string, string> }> {
+ const byOrg = new Map<string, string>();
+ if (orgIds.length === 0) return { ok: true, byOrg };
+ const placeholders = orgIds.map((_, i) => `?${i + 1}`).join(",");
+ try {
+ const res = await env.OPENCOMPUTER_DB.prepare(
+ `SELECT id, plan FROM orgs WHERE id IN (${placeholders})`,
+ )
+ .bind(...orgIds)
+ .all<{ id: string; plan: string }>();
+ for (const r of res.results ?? []) byOrg.set(r.id, r.plan);
+ return { ok: true, byOrg };
+ } catch (err) {
+ console.error("events-ingest: org plan lookup failed — falling back to envelope plan", err);
+ return { ok: false, byOrg };
+ }
+}
+
function jsonResponse(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), {
status,
diff --git a/cloudflare-workers/schema.sql b/cloudflare-workers/schema.sql
index eed849a9..52a4914e 100644
--- a/cloudflare-workers/schema.sql
+++ b/cloudflare-workers/schema.sql
@@ -167,6 +167,31 @@ CREATE INDEX IF NOT EXISTS idx_events_type_ts ON events(type, ts DESC);
-- Billing (pro tier) ------------------------------------------------------
+-- Raw per-tick resource samples for pro orgs — the edge analog of the cell's
+-- `sandbox_scale_events`. events-ingest writes one row per pro `usage_tick`;
+-- the rollup cron aggregates these into `usage_snapshots` (memory_gb_seconds
+-- per hourly bucket) and meters them to Stripe.
+--
+-- `id` is the originating event UUID, so the INSERT can use ON CONFLICT(id)
+-- DO NOTHING for the same at-least-once dedup the `events` table relies on —
+-- the CP forwarder retries batches, and additive billing must not double-count.
+-- Rows are disposable once rolled up (see rolled_up flag); kept short-lived,
+-- independent of the `events` audit log's retention.
+CREATE TABLE IF NOT EXISTS usage_samples (
+ id TEXT PRIMARY KEY, -- originating event UUID
+ org_id TEXT NOT NULL,
+ sandbox_id TEXT NOT NULL,
+ memory_mb INTEGER NOT NULL,
+ cpu_count INTEGER NOT NULL,
+ interval_s INTEGER NOT NULL, -- seconds this sample covers
+ ts INTEGER NOT NULL, -- unix ms (tick emit time)
+ cell_id TEXT NOT NULL,
+ rolled_up INTEGER NOT NULL DEFAULT 0
+);
+-- Rollup cron scans unrolled samples ordered by time; partial index keeps it
+-- tight as rolled-up rows accumulate before cleanup.
+CREATE INDEX IF NOT EXISTS idx_usage_samples_unrolled ON usage_samples(org_id, ts) WHERE rolled_up = 0;
+
CREATE TABLE IF NOT EXISTS usage_snapshots (
org_id TEXT NOT NULL,
snapshot_ts INTEGER NOT NULL, -- hourly bucket (unix s)
@@ -180,6 +205,36 @@ CREATE TABLE IF NOT EXISTS usage_snapshots (
);
CREATE INDEX IF NOT EXISTS idx_usage_unreported ON usage_snapshots(reported_to_stripe, org_id) WHERE reported_to_stripe = 0;
+-- Billing outbox — one row per Stripe meter event the rollup cron will ship.
+-- The edge analog of the cell's `billable_events`. Meter-grained (not one row
+-- per org/hour like usage_snapshots) because legacy orgs bill one meter event
+-- PER memory tier, while unified orgs bill a single flat overage meter — a
+-- per-org/hour row can't hold the legacy per-tier breakdown.
+--
+-- `id` is deterministic: "{org}:{bucket_start}:{meter_event_name}". That makes
+-- the whole rollup idempotent — re-running a bucket recomputes identical ids,
+-- so ON CONFLICT(id) DO NOTHING drops the dup, and it doubles as the Stripe
+-- meter-event Identifier (Stripe dedups the same identifier within 24h). So a
+-- crash anywhere in roll→send→mark is safe to replay.
+--
+-- `value` units depend on billing_mode: unified=GB-seconds (float), legacy=
+-- seconds at that tier (integer, the unit the cell's per-tier meter expects).
+CREATE TABLE IF NOT EXISTS usage_meter_events (
+ id TEXT PRIMARY KEY, -- {org}:{bucket_start}:{meter_event_name}
+ org_id TEXT NOT NULL,
+ meter_event_name TEXT NOT NULL, -- Stripe meter event_name
+ value REAL NOT NULL, -- GB-seconds (unified) | seconds (legacy tier)
+ billing_mode TEXT NOT NULL, -- 'legacy' | 'unified' (for the parity diff)
+ bucket_start INTEGER NOT NULL, -- unix s (inclusive)
+ bucket_end INTEGER NOT NULL, -- unix s (exclusive); meter event timestamp
+ state TEXT NOT NULL DEFAULT 'pending', -- 'pending' | 'sent' | 'shadow'
+ stripe_identifier TEXT, -- echoed back by Stripe on send
+ created_at INTEGER NOT NULL,
+ sent_at INTEGER
+);
+CREATE INDEX IF NOT EXISTS idx_meter_events_pending ON usage_meter_events(state, bucket_start) WHERE state = 'pending';
+CREATE INDEX IF NOT EXISTS idx_meter_events_org_bucket ON usage_meter_events(org_id, bucket_start);
+
CREATE TABLE IF NOT EXISTS org_subscription_items (
org_id TEXT NOT NULL,
tier TEXT NOT NULL, -- e.g. "memory" | "cpu"
diff --git a/cmd/server/main.go b/cmd/server/main.go
index efc2d557..63a6c113 100644
--- a/cmd/server/main.go
+++ b/cmd/server/main.go
@@ -26,8 +26,8 @@ import (
"github.com/opensandbox/opensandbox/internal/db"
"github.com/opensandbox/opensandbox/internal/edgeclient"
"github.com/opensandbox/opensandbox/internal/metrics"
- "github.com/opensandbox/opensandbox/internal/obslog"
"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"
@@ -82,6 +82,12 @@ func main() {
var ptyMgr *sandbox.PTYManager
log.Printf("opensandbox: server mode — delegating sandbox management to workers via gRPC")
+ // Pro-billing cutover switch (cell half): "edge" means the billing-rollup
+ // Worker is authoritative, so the cell billers stand down and creates must
+ // carry a cap-token (no direct API-key bypass of edge billing). Anything
+ // else = cell-authoritative (current behavior).
+ proBillingEdge := strings.EqualFold(strings.TrimSpace(cfg.ProBillingAuthority), "edge")
+
// Build server options
opts := &api.ServerOpts{
Mode: cfg.Mode,
@@ -92,6 +98,7 @@ func main() {
SessionJWTSecret: cfg.SessionJWTSecret,
CFAdminSecret: cfg.CFAdminSecret,
CFEventSecret: cfg.CFEventSecret,
+ RequireCapToken: proBillingEdge,
}
// Initialize PostgreSQL if configured
@@ -659,11 +666,17 @@ func main() {
log.Println("opensandbox: per-sandbox autoscaler started (interval=30s, leader-gated)")
}
+ if proBillingEdge {
+ log.Println("opensandbox: pro billing authority=edge — cell usage_reporter, capacity allocator, and billable-events sender DISABLED (billing-rollup Worker is authoritative); direct API-key creates require a cap-token")
+ }
+
// 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
- // logging instead of hibernating when free credits run out.
- if opts.Store != nil && stripeClient != nil {
+ // logging instead of hibernating when free credits run out. Disabled when
+ // pro billing authority is the edge (billing-rollup meters Pro; the DO
+ // owns free credits).
+ if opts.Store != nil && stripeClient != nil && !proBillingEdge {
var workers billing.WorkerClientSource
if redisRegistry != nil {
workers = redisRegistry
@@ -703,11 +716,32 @@ func main() {
}
}
+ // Usage-parity checker — shadow-parity gate for the Pro-billing edge
+ // cutover. Hourly, compares edge-measured GB-seconds (tick samples) against
+ // cell sandbox_scale_events and logs per-org drift. Read-only; never bills.
+ // Inert unless OPENSANDBOX_USAGE_PARITY_URL is set.
+ if cfg.UsageParityURL != "" && cfg.CFEventSecret != "" && opts.Store != nil {
+ parity := controlplane.NewUsageParityChecker(controlplane.UsageParityConfig{
+ Store: opts.Store,
+ ParityURL: cfg.UsageParityURL,
+ Secret: cfg.CFEventSecret,
+ })
+ if parity != nil {
+ parity.Start(ctx)
+ defer func() {
+ stopCtx, stopCancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer stopCancel()
+ _ = parity.Stop(stopCtx)
+ }()
+ log.Printf("opensandbox: usage-parity checker started (url=%s, period=1h)", cfg.UsageParityURL)
+ }
+ }
+
// 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 {
+ if opts.Store != nil && !proBillingEdge {
allocOpts := billing.CapacityReconcilerOpts{
Interval: getDurationEnv("CAPACITY_ALLOCATOR_INTERVAL", 5*time.Minute),
Settle: getDurationEnv("CAPACITY_ALLOCATOR_SETTLE", 30*time.Minute),
@@ -727,7 +761,7 @@ func main() {
// 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 {
+ if opts.Store != nil && stripeClient != nil && !proBillingEdge {
senderOpts := billing.BillableEventsSenderOpts{
Interval: getDurationEnv("BILLABLE_EVENTS_SENDER_INTERVAL", 5*time.Minute),
Batch: getIntEnv("BILLABLE_EVENTS_SENDER_BATCH", 200),
diff --git a/internal/api/router.go b/internal/api/router.go
index c492d1ea..5f4e2ef0 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -44,6 +44,7 @@ type Server struct {
store *db.Store // nil in combined/dev mode without PG
jwtIssuer *auth.JWTIssuer // nil if JWT not configured
capTokenIssuer *auth.JWTIssuer // verifies edge→CP capability tokens; nil if SESSION_JWT_SECRET unset
+ requireCapToken bool // derived from PRO_BILLING_AUTHORITY=edge: reject direct API-key creates that bypass edge billing (split mode only)
cfAdminSecret string // HMAC shared with CreditAccount DO for /admin/halt-org and /admin/resume-org; empty disables auth (dev only)
cfEventSecret string // HMAC shared with the api-edge Worker for /internal/secret-refresh and other edge-→cell push paths
cellID string // this control plane's cell_id (for the cap-token cell check)
@@ -102,6 +103,7 @@ type ServerOpts struct {
Store *db.Store
JWTIssuer *auth.JWTIssuer
SessionJWTSecret string // shared edge↔CP HMAC secret; enables /internal/sandboxes/create
+ RequireCapToken bool // set from PRO_BILLING_AUTHORITY=edge; rejects edge-bypassing direct API-key creates
CFAdminSecret string // HMAC shared with CF CreditAccount DO; enables /admin/halt-org and /admin/resume-org
CFEventSecret string // HMAC shared with the api-edge Worker; enables /internal/secret-refresh and other edge-→cell push paths
CellID string // this control plane's cell_id
@@ -142,6 +144,7 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o
if opts.SessionJWTSecret != "" {
s.capTokenIssuer = auth.NewJWTIssuer(opts.SessionJWTSecret)
}
+ s.requireCapToken = opts.RequireCapToken
s.cfAdminSecret = opts.CFAdminSecret
s.cfEventSecret = opts.CFEventSecret
s.cellID = opts.CellID
diff --git a/internal/api/sandbox.go b/internal/api/sandbox.go
index dbd4b400..fe81f3ac 100644
--- a/internal/api/sandbox.go
+++ b/internal/api/sandbox.go
@@ -42,13 +42,33 @@ func (s *Server) createSandbox(c echo.Context) error {
ctx := c.Request().Context()
+ // When the edge is the Pro-billing authority (PRO_BILLING_AUTHORITY=edge),
+ // a billing-relevant create must arrive via the edge (cap-token), not a raw
+ // API key hitting the CP directly — the direct path bypasses the edge's
+ // authoritative credit/halt gates. The cap-token branch is the only auth
+ // path that stamps a plan, so its absence in split mode means a direct API
+ // key. Combined mode (no cap-token issuer) is exempt.
+ if s.requireCapToken && s.capTokenIssuer != nil {
+ if _, viaCapToken := auth.GetPlan(c); !viaCapToken {
+ return c.JSON(http.StatusUnauthorized, map[string]string{
+ "error": "direct API-key sandbox creation is disabled; create through the edge endpoint",
+ })
+ }
+ }
+
// Check org quota and plan enforcement
orgID, hasOrg := auth.GetOrgID(c)
var org *db.Org
+ var effPlan string
if hasOrg && s.store != nil {
var err error
org, err = s.store.GetOrg(ctx, orgID)
if err == nil {
+ // Plan is a global signal — resolve it authoritatively (cap-token
+ // → D1 org-policy → cell-PG last resort), never trusting the stale
+ // cell-PG org row outright. See effectivePlan.
+ effPlan = s.effectivePlan(c, orgID)
+
// Concurrent sandbox limit applies to all plans.
count, err := s.store.CountActiveSandboxes(ctx, orgID)
if err == nil && count >= org.MaxConcurrentSandboxes {
@@ -58,7 +78,7 @@ func (s *Server) createSandbox(c echo.Context) error {
}
// Free-tier: trial credits gate + machine-size restriction.
- if org.Plan == "free" {
+ if effPlan == "free" {
if org.FreeCreditsRemainingCents <= 0 {
return c.JSON(http.StatusPaymentRequired, map[string]string{
"error": "free trial credits exhausted — upgrade to pro to create new sandboxes",
@@ -94,7 +114,7 @@ func (s *Server) createSandbox(c echo.Context) error {
})
}
if org != nil {
- if org.Plan == "free" && cfg.DiskMB > 20480 {
+ if effPlan == "free" && cfg.DiskMB > 20480 {
return c.JSON(http.StatusPaymentRequired, map[string]string{
"error": "upgrade to pro for larger disk sizes",
})
@@ -1167,17 +1187,30 @@ func (s *Server) migrateSandbox(c echo.Context) error {
})
}
-// effectivePlan returns the org's billing plan for org-policy gates. It
-// prefers the value the edge stamped into the cap-token (authoritative, fresh
-// from D1) and falls back to the cell-local orgs row for legacy direct-to-cell
-// callers that authenticate with a raw API key (no cap-token). Returns "" when
-// neither source is available, in which case callers should not gate.
+// effectivePlan returns the org's billing plan for billing gates, resolving it
+// from the most authoritative source available. Plan is a GLOBAL signal: it
+// changes via the edge (Stripe → DO mark-pro → D1), and no single cell has the
+// complete picture — the cell-PG copy goes stale on upgrade/downgrade. So:
+//
+// 1. Cap-token plan — edge requests already carry the D1-resolved plan.
+// 2. org-policy (D1) — for the legacy direct-to-CP API-key path (no cap-token):
+// resolve authoritatively from D1 rather than trusting stale cell PG.
+// 3. cell-PG org row — last resort ONLY when D1 is unreachable (edge outage)
+// or absent (combined/dev mode, where the cell is itself authoritative).
+//
+// Returns "" when nothing is available, in which case callers should not gate.
func (s *Server) effectivePlan(c echo.Context, orgID uuid.UUID) string {
if plan, ok := auth.GetPlan(c); ok {
return plan
}
+ ctx := c.Request().Context()
+ if s.edge != nil {
+ if pol, err := s.edge.GetOrgPolicy(ctx, orgID); err == nil && pol != nil {
+ return pol.Plan
+ }
+ }
if s.store != nil {
- if org, err := s.store.GetOrg(c.Request().Context(), orgID); err == nil && org != nil {
+ if org, err := s.store.GetOrg(ctx, orgID); err == nil && org != nil {
return org.Plan
}
}
diff --git a/internal/config/config.go b/internal/config/config.go
index 8a314487..6c0275de 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -212,6 +212,21 @@ type Config struct {
// to catch missed halt webhooks. Empty disables the reconciler.
HaltListURL string
+ // CF usage-parity endpoint (api-edge /internal/usage-parity). The
+ // usage-parity checker polls this to compare edge-measured Pro usage
+ // against cell sandbox_scale_events during the billing cutover soak.
+ // Empty disables the checker.
+ UsageParityURL string
+
+ // ProBillingAuthority selects who meters Pro usage to Stripe: "cell"
+ // (default — the in-CP usage_reporter / capacity allocator / billable-
+ // events sender) or "edge" (the billing-rollup Worker). This is the cell
+ // half of the Pro-billing cutover switch: setting it to "edge" stops the
+ // three cell billers AND requires cap-tokens for creates, so direct
+ // API-key clients can't bypass edge billing. Flip together with the edge
+ // SHADOW flag at the cutover boundary. Anything other than "edge" = cell.
+ ProBillingAuthority string
+
// CF edge base URL — root of the api-edge Worker (e.g.
// "https://app.dev.opensandbox.ai"). Used to construct /internal/*
// HMAC endpoints for stateless template + secret-store lookup at
@@ -379,6 +394,8 @@ func Load() (*Config, error) {
CFAdminSecret: os.Getenv("OPENSANDBOX_CF_ADMIN_SECRET"),
SessionJWTSecret: os.Getenv("OPENSANDBOX_SESSION_JWT_SECRET"),
HaltListURL: os.Getenv("OPENSANDBOX_HALT_LIST_URL"),
+ UsageParityURL: os.Getenv("OPENSANDBOX_USAGE_PARITY_URL"),
+ ProBillingAuthority: os.Getenv("OPENSANDBOX_PRO_BILLING_AUTHORITY"),
CFEdgeBaseURL: os.Getenv("OPENSANDBOX_CF_EDGE_BASE_URL"),
ComputeProvider: os.Getenv("OPENSANDBOX_COMPUTE_PROVIDER"),
diff --git a/internal/controlplane/usage_parity.go b/internal/controlplane/usage_parity.go
new file mode 100644
index 00000000..10bc2a0d
--- /dev/null
+++ b/internal/controlplane/usage_parity.go
@@ -0,0 +1,275 @@
+package controlplane
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "log"
+ "math"
+ "net/http"
+ "net/url"
+ "strconv"
+ "time"
+
+ "github.com/opensandbox/opensandbox/internal/db"
+)
+
+// UsageParityChecker is the Pro-tier shadow-parity gate for the billing
+// cutover. Every period it picks the most-recently-settled hour bucket and
+// compares, per org, the GB-seconds the EDGE measured (from tick samples, via
+// the api-edge /internal/usage-parity endpoint) against the GB-seconds the
+// CELL measured (from authoritative sandbox_scale_events). It only logs/alerts
+// drift — it never changes billing. This is the evidence that lets an operator
+// flip the edge rollup cron from shadow to live (runbook: parity clean 24h+).
+//
+// GB-seconds is the comparison metric because it's billing_mode-independent:
+// legacy (per-tier) and unified (flat) both reduce to the same compute-seconds,
+// so one scalar validates both. It compares raw measurement sources (ticks vs
+// intervals) on purpose — pricing is preserved by design, so measurement is the
+// risky part of the cutover.
+//
+// Expected, benign drift sources (don't alarm on these alone):
+// - ±1 tick interval (≤20s) per sandbox lifetime: sampling vs exact wall-time.
+// - Managed-agent sandboxes: the cell EXCLUDES sandboxes under an active
+// agent_subscription from GetOrgUsage (the sub covers compute), but the
+// worker's usage ticker currently emits ticks for them. So orgs with
+// managed agents will show edge > cell. That's a real edge-side gap to
+// close later (the edge has no agent-subscription awareness yet) — the
+// checker surfaces it rather than hiding it.
+type UsageParityChecker struct {
+ store usageParitySource
+ parityURL string // full api-edge /internal/usage-parity URL
+ path string // parsed path of parityURL, for the HMAC (path+query)
+ secret string // shared HMAC secret with the edge (EVENT_SECRET)
+
+ period time.Duration
+ grace time.Duration // wait this long past a bucket's end before checking
+ tolerance float64 // fractional drift to tolerate before flagging (e.g. 0.02)
+
+ client *http.Client
+ stopCh chan struct{}
+ doneCh chan struct{}
+}
+
+// usageParitySource is the slice of *db.Store the checker needs (interface for
+// testability).
+type usageParitySource interface {
+ GetOrgUsage(ctx context.Context, orgID string, from, to time.Time) ([]db.OrgUsageSummary, error)
+ ListOrgIDsWithScaleEvents(ctx context.Context, from, to time.Time) ([]string, error)
+}
+
+// UsageParityConfig configures the checker. ParityURL empty => disabled.
+type UsageParityConfig struct {
+ Store usageParitySource
+ ParityURL string
+ Secret string
+ Period time.Duration // default 1h (one closed bucket per run)
+ Grace time.Duration // default 10m, must match the rollup cron's GRACE_SECONDS
+ Tolerance float64 // default 0.02 (2%)
+}
+
+// NewUsageParityChecker returns nil if ParityURL/Secret/Store are unset.
+func NewUsageParityChecker(cfg UsageParityConfig) *UsageParityChecker {
+ if cfg.ParityURL == "" || cfg.Secret == "" || cfg.Store == nil {
+ return nil
+ }
+ u, err := url.Parse(cfg.ParityURL)
+ if err != nil {
+ log.Printf("usage_parity: bad ParityURL %q: %v — disabled", cfg.ParityURL, err)
+ return nil
+ }
+ if cfg.Period <= 0 {
+ cfg.Period = time.Hour
+ }
+ if cfg.Grace <= 0 {
+ cfg.Grace = 10 * time.Minute
+ }
+ if cfg.Tolerance <= 0 {
+ cfg.Tolerance = 0.02
+ }
+ return &UsageParityChecker{
+ store: cfg.Store,
+ parityURL: cfg.ParityURL,
+ path: u.Path,
+ secret: cfg.Secret,
+ period: cfg.Period,
+ grace: cfg.Grace,
+ tolerance: cfg.Tolerance,
+ client: &http.Client{Timeout: 20 * time.Second},
+ stopCh: make(chan struct{}),
+ doneCh: make(chan struct{}),
+ }
+}
+
+func (c *UsageParityChecker) Start(ctx context.Context) { go c.run(ctx) }
+
+func (c *UsageParityChecker) Stop(ctx context.Context) error {
+ close(c.stopCh)
+ select {
+ case <-c.doneCh:
+ case <-ctx.Done():
+ return ctx.Err()
+ }
+ return nil
+}
+
+func (c *UsageParityChecker) run(ctx context.Context) {
+ defer close(c.doneCh)
+ ticker := time.NewTicker(c.period)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-c.stopCh:
+ return
+ case <-ticker.C:
+ c.tickSafe(ctx)
+ }
+ }
+}
+
+func (c *UsageParityChecker) tickSafe(ctx context.Context) {
+ defer func() {
+ if v := recover(); v != nil {
+ log.Printf("usage_parity: recovered from panic: %v", v)
+ }
+ }()
+ tCtx, cancel := context.WithTimeout(ctx, 60*time.Second)
+ defer cancel()
+ if err := c.tick(tCtx); err != nil {
+ log.Printf("usage_parity: tick failed: %v", err)
+ }
+}
+
+const bucketSeconds = int64(3600)
+
+// tick compares the most-recently-settled hour bucket and logs per-org drift.
+func (c *UsageParityChecker) tick(ctx context.Context) error {
+ // Most recent fully-settled hour boundary: round (now-grace) down to the hour.
+ end := ((time.Now().Unix() - int64(c.grace.Seconds())) / bucketSeconds) * bucketSeconds
+ start := end - bucketSeconds
+ from := time.Unix(start, 0).UTC()
+ to := time.Unix(end, 0).UTC()
+
+ edge, err := c.fetchEdge(ctx, start, end)
+ if err != nil {
+ return fmt.Errorf("fetch edge: %w", err)
+ }
+
+ // Union of org_ids: cell-side (scale events) ∪ edge-side (samples). An org
+ // on only one side is a parity failure we want to see.
+ cellOrgs, err := c.store.ListOrgIDsWithScaleEvents(ctx, from, to)
+ if err != nil {
+ return fmt.Errorf("list cell orgs: %w", err)
+ }
+ union := map[string]struct{}{}
+ for _, id := range cellOrgs {
+ union[id] = struct{}{}
+ }
+ for id := range edge {
+ union[id] = struct{}{}
+ }
+
+ checked, flagged := 0, 0
+ var worstPct float64
+ var worstOrg string
+ for org := range union {
+ cellGB, err := c.cellGBSeconds(ctx, org, from, to)
+ if err != nil {
+ log.Printf("usage_parity: org=%s cell usage: %v", org, err)
+ continue
+ }
+ edgeGB := edge[org]
+ checked++
+ drift := edgeGB - cellGB
+ pct := driftPct(cellGB, edgeGB)
+ if math.Abs(pct) > c.tolerance {
+ flagged++
+ log.Printf("usage_parity: DRIFT org=%s bucket=%s cell=%.3f edge=%.3f gb·s drift=%+.3f (%+.1f%%)",
+ org, from.Format(time.RFC3339), cellGB, edgeGB, drift, pct*100)
+ }
+ if math.Abs(pct) > math.Abs(worstPct) {
+ worstPct = pct
+ worstOrg = org
+ }
+ }
+
+ log.Printf("usage_parity: bucket=%s checked=%d flagged=%d (tolerance=%.1f%%) worst=%s (%+.1f%%)",
+ from.Format(time.RFC3339), checked, flagged, c.tolerance*100, worstOrg, worstPct*100)
+ return nil
+}
+
+// cellGBSeconds sums the cell's authoritative GB-seconds for an org over the
+// window from sandbox_scale_events (via GetOrgUsage, which already clips to the
+// window and excludes agent-subscription sandboxes).
+func (c *UsageParityChecker) cellGBSeconds(ctx context.Context, org string, from, to time.Time) (float64, error) {
+ rows, err := c.store.GetOrgUsage(ctx, org, from, to)
+ if err != nil {
+ return 0, err
+ }
+ var gb float64
+ for _, r := range rows {
+ gb += (float64(r.MemoryMB) / 1024.0) * r.TotalSeconds
+ }
+ return gb, nil
+}
+
+// driftPct returns the signed fractional difference of edge vs cell. When cell
+// is ~0 it returns +1 (100%) if edge has any usage, else 0 — so a one-sided
+// org is always flagged rather than dividing by zero.
+func driftPct(cell, edge float64) float64 {
+ const eps = 1e-6
+ if math.Abs(cell) < eps {
+ if math.Abs(edge) < eps {
+ return 0
+ }
+ return 1
+ }
+ return (edge - cell) / cell
+}
+
+type usageParityResponse struct {
+ Orgs []struct {
+ OrgID string `json:"org_id"`
+ GBSeconds float64 `json:"gb_seconds"`
+ Samples int64 `json:"samples"`
+ } `json:"orgs"`
+ AsOf int64 `json:"as_of"`
+}
+
+// fetchEdge calls the api-edge /internal/usage-parity endpoint and returns a
+// map of org_id → edge GB-seconds for the window. Same HMAC scheme as the
+// halt_reconciler: sign "{ts}.{path+query}" with the shared EVENT_SECRET.
+func (c *UsageParityChecker) fetchEdge(ctx context.Context, fromSec, toSec int64) (map[string]float64, error) {
+ q := fmt.Sprintf("from=%d&to=%d", fromSec, toSec)
+ ts := strconv.FormatInt(time.Now().Unix(), 10)
+ sig := signGet(c.secret, ts, c.path+"?"+q)
+
+ req, err := http.NewRequestWithContext(ctx, "GET", c.parityURL+"?"+q, nil)
+ if err != nil {
+ return nil, fmt.Errorf("build request: %w", err)
+ }
+ req.Header.Set("X-Timestamp", ts)
+ req.Header.Set("X-Signature", sig)
+
+ resp, err := c.client.Do(req)
+ if err != nil {
+ return nil, fmt.Errorf("http: %w", err)
+ }
+ defer resp.Body.Close()
+ body, _ := io.ReadAll(resp.Body)
+ if resp.StatusCode != 200 {
+ return nil, fmt.Errorf("status %d: %s", resp.StatusCode, string(body))
+ }
+ var parsed usageParityResponse
+ if err := json.Unmarshal(body, &parsed); err != nil {
+ return nil, fmt.Errorf("decode body: %w", err)
+ }
+ out := make(map[string]float64, len(parsed.Orgs))
+ for _, o := range parsed.Orgs {
+ out[o.OrgID] = o.GBSeconds
+ }
+ return out, nil
+}
diff --git a/internal/db/usage.go b/internal/db/usage.go
index 5f172ce6..0956ee3a 100644
--- a/internal/db/usage.go
+++ b/internal/db/usage.go
@@ -220,6 +220,32 @@ func (s *Store) GetOrgUsage(ctx context.Context, orgID string, from, to time.Tim
return results, rows.Err()
}
+// ListOrgIDsWithScaleEvents returns the distinct org_ids that had any scale
+// event overlapping [from, to). Used by the usage-parity checker to know which
+// orgs to compare against the edge — the union of these and the edge's
+// reported orgs is the full set worth diffing (an org present on one side but
+// not the other is itself a parity failure).
+func (s *Store) ListOrgIDsWithScaleEvents(ctx context.Context, from, to time.Time) ([]string, error) {
+ rows, err := s.pool.Query(ctx, `
+ SELECT DISTINCT org_id
+ FROM sandbox_scale_events
+ WHERE started_at < $2 AND (ended_at IS NULL OR ended_at > $1)`,
+ from, to)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ var ids []string
+ for rows.Next() {
+ var id string
+ if err := rows.Scan(&id); err != nil {
+ return nil, err
+ }
+ ids = append(ids, id)
+ }
+ return ids, rows.Err()
+}
+
// --- Stripe billing methods ---
// SetStripeCustomerID sets the Stripe customer ID for an org.
diff --git a/internal/worker/usage_ticker.go b/internal/worker/usage_ticker.go
index 4d741f6b..8f1435cd 100644
--- a/internal/worker/usage_ticker.go
+++ b/internal/worker/usage_ticker.go
@@ -24,13 +24,22 @@ import (
// - The worker is the only place that actually owns running VMs.
// - The DO can't self-schedule per-sandbox debit cadence.
//
-// Cost model: every tick contributes a fixed cents amount per sandbox. For
-// the dev/test bed this is set so that a free org's $5 seed exhausts in
-// ~5 minutes of continuous running at the default interval — short enough
-// to validate the halt loop, long enough that quick smoke tests don't
-// burn the credit. Production should compute cents from RAM + CPU usage
-// (memory_gb_seconds, cpu_seconds) — wired the same way, just a richer
-// payload.
+// Cost model — two consumers off the same event:
+// - Free tier: every tick contributes a fixed `cost_cents` per sandbox,
+// debited against the org's DO balance. For the dev/test bed this is
+// set so a free org's $5 seed exhausts in ~5 minutes of continuous
+// running at the default interval — short enough to validate the halt
+// loop, long enough that quick smoke tests don't burn the credit.
+// - Pro tier: the tick also carries the sandbox's resource dimensions
+// (memory_mb, cpu_count, interval_s). events-ingest lands these into D1
+// `usage_samples` for pro orgs; a rollup cron turns the samples into
+// memory_gb_seconds and meters them to Stripe. This is the edge analog
+// of the cell's `sandbox_scale_events` table — sampled per tick rather
+// than recorded as open/close intervals, so a worker death just stops
+// the samples instead of leaving a dangling open billing row.
+//
+// The worker is the only component with per-sandbox tier granularity, which
+// is why the dimensions are stamped here rather than reconstructed downstream.
type UsageTicker struct {
manager sandbox.Manager
sandboxDBs *sandbox.SandboxDBManager
@@ -133,9 +142,15 @@ func (t *UsageTicker) tick(ctx context.Context) {
continue
}
if err := sdb.LogEvent("usage_tick", map[string]interface{}{
- "sandbox_id": sb.ID,
- "cost_cents": t.costPerTickCs,
- "interval_s": int(t.interval.Seconds()),
+ "sandbox_id": sb.ID,
+ "cost_cents": t.costPerTickCs,
+ "interval_s": int(t.interval.Seconds()),
+ // Resource dimensions for pro-tier metering on the edge. Free
+ // orgs ignore these (they debit cost_cents); pro orgs land them
+ // in D1 usage_samples. MemoryMB/CpuCount come straight off the
+ // running VM's tier — the worker owns the VM so these are exact.
+ "memory_mb": sb.MemoryMB,
+ "cpu_count": sb.CpuCount,
}); err != nil {
log.Printf("usage_ticker: %s: LogEvent failed: %v", sb.ID, err)
continue