Skip to content

An open-source, faster Devin alternative

TypeScript

perf(edge): make Durable Object placement measurable so the shard set can be selected instead of aimed

Brian Reardonac06d2f6c3f0
diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.ts
index 0a70307c..65dd75b9 100644
--- a/cloudflare-workers/api-edge/src/index.ts
+++ b/cloudflare-workers/api-edge/src/index.ts
@@ -1263,11 +1263,38 @@ function indexSandboxFromSSE(
// a region, not a metro, so within enam the placement still falls out of which
// colo touches the object first. That is the part only the arming run controls
// — see the note above about first-touching from the cell's own metro.
-const POOL_STOCK_SHARDS = 8;
+// g5 stops trying to AIM placement and starts SELECTING it. Four generations
+// were armed exactly as the note above prescribes — first-touched from a
+// sandbox inside the cell's own metro — and all four still scattered across
+// five colos. The conclusion is that first-touch-colo does not decide placement
+// within a region; Cloudflare spreads inside enam and the arming client cannot
+// override that. So placement is not something to get right, it is something to
+// measure: mint far more candidate shard names than we need, ask each one where
+// it landed (GET /internal/pool/colo-probe), and keep only the indices that
+// answer IAD. Selection is deterministic where placement is not, and it is
+// permanent for the same reason placement was a trap — a placed DO never moves.
+//
+// POOL_STOCK_SHARD_IDS is therefore a MEASUREMENT, not a configuration. Re-run
+// the probe and re-pick if the shard set is ever regenerated; do not hand-edit
+// it to indices nobody has verified.
+// STILL g4 with the identity list — i.e. exactly today's behaviour. The gen
+// flips only once the probe below has run against prod and named the winning
+// indices; shipping a fresh generation before then would empty the live shards
+// (every create falling through to a cold CP launch) to land on placements
+// nobody has looked at yet.
const POOL_STOCK_SHARD_GEN = "g4";
+const POOL_STOCK_SHARD_IDS = [0, 1, 2, 3, 4, 5, 6, 7];
+const POOL_STOCK_SHARDS = POOL_STOCK_SHARD_IDS.length;
+// How many candidate names the probe route sweeps. Only the ones that report
+// the target colo get promoted into POOL_STOCK_SHARD_IDS above.
+const POOL_STOCK_CANDIDATES = 64;
+
+function poolStockShardName(cellID: string, id: number): string {
+ return `${cellID}#${POOL_STOCK_SHARD_GEN}#${id}`;
+}
function poolStockStub(env: Env, cellID: string, shard: number): DurableObjectStub {
- const name = `${cellID}#${POOL_STOCK_SHARD_GEN}#${shard}`;
+ const name = poolStockShardName(cellID, POOL_STOCK_SHARD_IDS[shard] ?? shard);
// Deterministic placement hint: pin the stock DO to eastern North America
// (covers eastus2 / the IAD leaderboard runner) so a claim never eats a
// cross-colo hop even if the first touch comes from an off-metro edge. A
@@ -4150,6 +4177,50 @@ export default {
await runPausedCapEnforcer(env);
return json({ ok: true });
}
+ // Placement probe for the pool shards. HMAC-auth'd (CF_ADMIN_SECRET) so it
+ // is safe to run against prod, which is the only place the answer matters —
+ // the colo a DO lands in is a property of the account and region, and dev
+ // cannot stand in for it.
+ //
+ // Touching a candidate PLACES it, permanently. That is the point: this
+ // sweep is how a generation of shards gets minted, and its output is the
+ // POOL_STOCK_SHARD_IDS list. Sweeping a gen that is already live is
+ // harmless (the candidates beyond the selected ones just sit empty and
+ // never claim), but do not sweep with a `target` you are not about to ship.
+ //
+ // ?child=1 also asks each candidate to parent a throwaway MicrovmSession
+ // and report where the CHILD landed — the one measurement that decides
+ // whether pinning shards also pins the session DOs warmed from them.
+ if (path === "/internal/pool/colo-probe" && req.method === "GET") {
+ const ts = req.headers.get("X-Timestamp") ?? "";
+ const sig = req.headers.get("X-Signature") ?? "";
+ const expected = await hmacHex(env.CF_ADMIN_SECRET, `${ts}.${path}${url.search}`);
+ if (!constantTimeEqual(expected, sig)) return json({ error: "signature mismatch" }, 401);
+ if (Math.abs(Math.floor(Date.now() / 1000) - Number(ts)) > 300)
+ return json({ error: "timestamp out of window" }, 401);
+ const cellID = url.searchParams.get("cell") ?? "";
+ if (!cellID) return json({ error: "cell required" }, 400);
+ const gen = url.searchParams.get("gen") ?? POOL_STOCK_SHARD_GEN;
+ const n = Math.min(Number(url.searchParams.get("n")) || POOL_STOCK_CANDIDATES, 256);
+ const wantChild = url.searchParams.get("child") === "1";
+ const probe = async (i: number) => {
+ const name = `${cellID}#${gen}#${i}`;
+ const q = wantChild ? `?child=${encodeURIComponent(`probe-${gen}-${i}`)}` : "";
+ try {
+ const r = await env.POOL_STOCK.get(env.POOL_STOCK.idFromName(name), {
+ locationHint: "enam",
+ }).fetch(`https://pool-stock/colo${q}`);
+ const j = (await r.json()) as { colo: string; stock: number; child: string | null };
+ return { i, colo: j.colo, stock: j.stock, child: j.child };
+ } catch (e) {
+ return { i, colo: "err", stock: -1, child: String(e).slice(0, 60) };
+ }
+ };
+ const results = await Promise.all(Array.from({ length: n }, (_, i) => probe(i)));
+ const byColo: Record<string, number[]> = {};
+ for (const r of results) (byColo[r.colo] ??= []).push(r.i);
+ return json({ cell: cellID, gen, edgeColo: req.headers.get("cf-ray")?.split("-")[1] ?? "?", byColo, results });
+ }
// Force a model-meter run (token billing §5.4). HMAC-auth'd (CF_ADMIN_SECRET) so
// it's safe to run in prod for testing/ops — useful to debit + push caps right
// after a Managed turn instead of waiting for the cron.
diff --git a/cloudflare-workers/api-edge/src/pool_stock.ts b/cloudflare-workers/api-edge/src/pool_stock.ts
index 572efccd..74f3c81e 100644
--- a/cloudflare-workers/api-edge/src/pool_stock.ts
+++ b/cloudflare-workers/api-edge/src/pool_stock.ts
@@ -217,6 +217,19 @@ export class PoolStock {
// Resolved once per isolate alongside coloLogged; reported on every claim so
// the create path can see whether its stock DO is even in the same colo.
private colo = "?";
+ // Blocking form, for the /colo probe only — never on a claim, which must not
+ // wait on a diagnostic round trip.
+ private async coloNow(): Promise<string> {
+ if (this.colo !== "?") return this.colo;
+ this.coloLogged = true;
+ try {
+ const t = await fetch("https://www.cloudflare.com/cdn-cgi/trace").then((r) => r.text());
+ this.colo = (t.match(/^colo=(\w+)/m) ?? [])[1] ?? "?";
+ } catch {
+ /* leave "?" — the probe reports unknown rather than failing */
+ }
+ return this.colo;
+ }
// Last cell seen on a /claim, persisted so the proactive alarm can restock
// without waiting for the next claim (a fresh DO after eviction still knows
// which cell to reserve from).
@@ -269,6 +282,31 @@ export class PoolStock {
if (req.method === "GET" && url.pathname === "/status") {
return Response.json({ stock: this.stock.length, restocking: this.restockInFlight });
}
+ // Placement probe. A DO pins to a colo at first touch, permanently, and
+ // locationHint only picks a REGION — four generations of shards were armed
+ // from an in-metro client and still scattered across five colos inside
+ // enam. So placement is not something to aim; it is something to measure
+ // and then select on. /colo reports where this object actually landed.
+ //
+ // ?child=<name> additionally asks a MicrovmSession this shard parents where
+ // IT landed. That is the load-bearing question for stock-prep warming: if a
+ // child inherits its parent's colo, pinning the shards pins every session
+ // DO with them; if it does not, session placement needs its own lever.
+ if (req.method === "GET" && url.pathname === "/colo") {
+ const self = await this.coloNow();
+ const child = url.searchParams.get("child");
+ const ns = this.env.MICROVM_SESSIONS;
+ let childColo: string | null = null;
+ if (child && ns) {
+ childColo = await ns
+ .get(ns.idFromName(child), { locationHint: "enam" })
+ .fetch("https://do/colo")
+ .then((r) => r.json() as Promise<{ colo: string }>)
+ .then((j) => j.colo)
+ .catch(() => "err");
+ }
+ return Response.json({ colo: self, stock: this.stock.length, child: childColo });
+ }
return new Response("not found", { status: 404 });
}
diff --git a/cloudflare-workers/vm-do/src/microvm_session.ts b/cloudflare-workers/vm-do/src/microvm_session.ts
index dd52e16b..be33a504 100644
--- a/cloudflare-workers/vm-do/src/microvm_session.ts
+++ b/cloudflare-workers/vm-do/src/microvm_session.ts
@@ -96,6 +96,11 @@ export class MicrovmSession {
warmUntil: this.warmUntil,
failures: this.failures,
});
+ // Awaited colo, unlike resolveColo()'s fire-and-forget. Placement is
+ // decided at first touch and is permanent, so the only way to get a shard
+ // set that is actually in one metro is to mint candidates, ask each where
+ // it landed, and keep the ones that answer correctly. This is the "ask".
+ if (path === "/colo") return json({ colo: await this.coloNow() });
if (path === "/detach") return await this.detach();
} catch (e) {
return json({ error: String(e) }, 500);
@@ -295,6 +300,20 @@ export class MicrovmSession {
.catch(() => {});
}
+ // Blocking form of resolveColo, for /colo only. Never used on the exec path:
+ // an exec must not wait on a diagnostic round trip to cdn-cgi/trace.
+ private async coloNow(): Promise<string> {
+ if (this.colo !== "?") return this.colo;
+ this.coloResolved = true;
+ try {
+ const t = await fetch("https://www.cloudflare.com/cdn-cgi/trace").then((r) => r.text());
+ this.colo = (t.match(/^colo=(\w+)/m) ?? [])[1] ?? "?";
+ } catch {
+ /* leave "?" — the probe reports it as unknown rather than failing */
+ }
+ return this.colo;
+ }
+
private async exec(req: Request): Promise<Response> {
// Everything the caller cannot see from outside. do;dur on the edge is one
// opaque number covering the hop to this object, this object's cold start,