diff --git a/changelog.d/account-computers-control-pulls.md b/changelog.d/account-computers-control-pulls.md new file mode 100644 index 000000000..a003cc9ee --- /dev/null +++ b/changelog.d/account-computers-control-pulls.md @@ -0,0 +1,3 @@ +## Changed + +- Speed up account computer lists on busy servers and control-only log reads on collections with long entry histories. diff --git a/runtime/deploy/cloudflare-do/bench/control-pull.mjs b/runtime/deploy/cloudflare-do/bench/control-pull.mjs new file mode 100644 index 000000000..fd087db32 --- /dev/null +++ b/runtime/deploy/cloudflare-do/bench/control-pull.mjs @@ -0,0 +1,157 @@ +// Linux, Node 24, npm ci in cloudflare-do. Run node bench/control-pull.mjs. +// Compare the same workerd cursor with and without the production partial index. +import assert from "node:assert/strict"; +import { once } from "node:events"; +import WebSocket from "ws"; +import { readFileSync, readdirSync } from "node:fs"; +import { Miniflare, convertV4MiniflareOptions } from "miniflare"; + +const source = readFileSync(new URL("../src/lib.rs", import.meta.url), "utf8"); +const schema = source.match(/"(CREATE TABLE IF NOT EXISTS items [^"]+)"/)[1]; +const index = source.match(/"(CREATE INDEX IF NOT EXISTS items_control_seq [^"]+)"/)[1]; +const method = source.slice(source.indexOf(" async fn items("), source.indexOf(" async fn tokens(")); +const filter = method.match(/if control_only \{ "([^"]+)"/)[1]; +const query = method.match(/let q = format!\(\s*"([^"]+)"/)[1].replace("{filter}", filter); + +// Serialized into the worker below; schema, index and query come from the adapter. +class Probe { + constructor(ctx) { this.sql = ctx.storage.sql; } + fetch(request) { + const { searchParams, pathname } = new URL(request.url); + const n = Number(searchParams.get("n")); + if (pathname === "/seed") { + this.sql.exec(schema); + this.sql.exec(`WITH RECURSIVE n(i) AS (VALUES(1) UNION ALL SELECT i+1 FROM n WHERE i < ?) + INSERT INTO items SELECT i, CASE WHEN i = 1 THEN 2 WHEN i = ? THEN 3 ELSE 1 END, + zeroblob(256), i FROM n`, n, n); + const tableSize = this.sql.databaseSize; + if (searchParams.get("arm") === "after") this.sql.exec(index); + const indexBytes = this.sql.databaseSize - tableSize; + const plan = this.sql.exec("EXPLAIN QUERY PLAN " + query, 128, 1, 8).toArray().map(row => row.detail); + // Include the write bill for each kind after the index has been installed. + const appendWrites = [1, 2].map(kind => + this.sql.exec("INSERT INTO items VALUES(?,?,zeroblob(256),?)", n + kind, kind, n + kind).rowsWritten); + return Response.json({ plan, appendWrites, indexBytes }); + } + const repeats = Number(searchParams.get("repeats")); + let rowsRead = 0, rowsWritten = 0, payloadBytes = 0; + let result; + for (let i = 0; i < repeats; i++) { + // A full first item advances even with a 128-byte cap. Stop on SQL NULL + // before converting the next control payload, as the Wasm adapter does. + const cursor = this.sql.exec(query, 128, 1, 8); + result = []; + for (const row of cursor) { + if (row.bytes === null) break; + payloadBytes += row.bytes.byteLength; + result.push([row.seq, row.kind, row.appended_at, row.bytes.byteLength]); + } + rowsRead += cursor.rowsRead; + rowsWritten += cursor.rowsWritten; + } + return Response.json({ rowsRead, rowsWritten, payloadBytes, result }); + } +} + +// Workerd executes the local isolate in this process's child. Sum its OS thread +// running times (nanoseconds); Node client CPU is outside that measurement. +function workerCpuMs(pid) { + let ns = 0; + for (const tid of readdirSync(`/proc/${pid}/task`)) { + try { ns += Number(readFileSync(`/proc/${pid}/task/${tid}/schedstat`, "utf8").split(" ")[0]); } + catch (error) { if (error.code !== "ENOENT") throw error; } + } + return ns / 1e6; +} +function workerPid() { + const children = readFileSync(`/proc/self/task/${process.pid}/children`, "utf8").trim().split(/\s+/); + const ids = children.filter(pid => readFileSync(`/proc/${pid}/comm`, "utf8").trim() === "workerd"); + assert.equal(ids.length, 1); + return ids[0]; +} + +// Sample isolate allocations separately so inspector overhead stays out of the +// CPU and latency measurements. Include short-lived objects collected during a batch. +async function profileAllocations(mf, call, repeats) { + const url = await mf.getInspectorURL(); + url.protocol = "http:"; + const targets = await (await fetch(new URL("/json/list", url))).json(); + const target = targets.find(t => t.id === "core:user:control-pull-bench"); + const socket = new WebSocket(target.webSocketDebuggerUrl); + await once(socket, "open"); + let id = 0; + async function command(method, params = {}) { + socket.send(JSON.stringify({ id: ++id, method, params })); + for (;;) { + const [message] = await once(socket, "message"); + const response = JSON.parse(message); + if (response.id !== id) continue; + assert.ok(!response.error, JSON.stringify(response.error)); + return response.result; + } + } + try { + const samples = { before: [], after: [] }; + await command("HeapProfiler.enable"); + for (let pair = 0; pair < 9; pair++) { + for (const arm of pair % 2 ? ["after", "before"] : ["before", "after"]) { + await command("HeapProfiler.startSampling", { samplingInterval: 256, + includeObjectsCollectedByMajorGC: true, includeObjectsCollectedByMinorGC: true }); + await call("page", arm); + const { profile } = await command("HeapProfiler.stopSampling"); + const allocated = node => node.selfSize + node.children.reduce((n, c) => n + allocated(c), 0); + samples[arm].push(allocated(profile.head) / repeats); + } + } + for (const [arm, values] of Object.entries(samples)) { + values.sort((a,b) => a-b); + console.log({ arm, medianSampledHeapBytesPerPage: values[4], p95SampledHeapBytesPerPage: values[8] }); + } + } finally { socket.terminate(); } +} + +const mf = new Miniflare(convertV4MiniflareOptions({ + name: "control-pull-bench", compatibilityDate: "2026-10-04", modules: true, inspectorPort: 0, + durableObjects: { LOG: { className: "Probe", useSQLite: true } }, + script: `const [schema,index,query] = ${JSON.stringify([schema, index, query])}; + export ${Probe.toString()} + export default { fetch(req, env) { + const q = new URL(req.url).searchParams; + return env.LOG.getByName(q.get("n") + q.get("arm")).fetch(req); + } };`, +})); +try { + const repeats = 64; + for (const n of [8, 25000]) { + const call = async (path, arm) => { + const res = await mf.dispatchFetch(`http://bench.local/${path}?arm=${arm}&n=${n}&repeats=${repeats}`); + assert.equal(res.status, 200); + return res.json(); + }; + const samples = { before: [], after: [] }; + for (const arm of Object.keys(samples)) { + const { plan, appendWrites, indexBytes } = await call("seed", arm); + assert.deepEqual(appendWrites, arm === "before" ? [1, 1] : [1, 2]); + console.log({ n, arm, plan, appendWrites, indexBytes }); + } + const pid = workerPid(); + for (let pair = 0; pair < 18; pair++) { + for (const arm of pair % 2 ? ["after", "before"] : ["before", "after"]) { + const start = performance.now(), cpu = workerCpuMs(pid); + const result = await call("page", arm); + const wallMs = (performance.now() - start) / repeats, cpuMs = (workerCpuMs(pid) - cpu) / repeats; + assert.deepEqual(result.result, [[n, 3, n, 256]]); + assert.equal(result.payloadBytes, repeats * 256); + assert.equal(result.rowsWritten, 0); + if (pair >= 3) samples[arm].push({ wallMs, cpuMs, rowsRead: result.rowsRead / repeats }); + } + } + for (const [arm, runs] of Object.entries(samples)) { + const percentile = (key, p) => runs.map(r => r[key]).sort((a,b) => a-b)[Math.ceil(runs.length * p) - 1]; + console.log({ n, arm, samples: runs.length, medianMs: percentile("wallMs", .5), p95Ms: percentile("wallMs", .95), + medianCpuMs: percentile("cpuMs", .5), p95CpuMs: percentile("cpuMs", .95), rowsRead: percentile("rowsRead", .5) }); + } + if (n === 25000) assert(samples.after.every(run => run.rowsRead < 10)); + await profileAllocations(mf, call, repeats); + } +} finally { await mf.dispose(); } diff --git a/runtime/deploy/cloudflare-do/src/lib.rs b/runtime/deploy/cloudflare-do/src/lib.rs index f5a8f8977..ed71777df 100644 --- a/runtime/deploy/cloudflare-do/src/lib.rs +++ b/runtime/deploy/cloudflare-do/src/lib.rs @@ -252,6 +252,8 @@ const SCHEMA: &[&str] = &[ "INSERT OR IGNORE INTO actor_route (k, id) SELECT 0, id FROM meta WHERE k = 0", "CREATE TABLE IF NOT EXISTS acl (device BLOB PRIMARY KEY, account BLOB NOT NULL, kind INTEGER NOT NULL, sign_pk BLOB NOT NULL, active INTEGER NOT NULL)", "CREATE TABLE IF NOT EXISTS items (seq INTEGER PRIMARY KEY, kind INTEGER NOT NULL, bytes BLOB NOT NULL, appended_at INTEGER NOT NULL)", + // Control-only readers seek past ordinary entries without indexing their payloads. + "CREATE INDEX IF NOT EXISTS items_control_seq ON items(seq) WHERE kind <> 1", "CREATE TABLE IF NOT EXISTS tokens (token BLOB PRIMARY KEY, seq INTEGER NOT NULL, expires_at INTEGER NOT NULL)", "CREATE TABLE IF NOT EXISTS snapshots (seq INTEGER PRIMARY KEY, manifest BLOB NOT NULL, author BLOB NOT NULL, created_at INTEGER NOT NULL, endorsed INTEGER NOT NULL)", "CREATE TABLE IF NOT EXISTS objects (address BLOB PRIMARY KEY, kind INTEGER NOT NULL, size INTEGER NOT NULL, checksum BLOB NOT NULL, committed INTEGER NOT NULL, created_at INTEGER NOT NULL)", diff --git a/runtime/deploy/cloudflare-do/tests/runtime.mjs b/runtime/deploy/cloudflare-do/tests/runtime.mjs index cda7ffc7f..de744d63e 100644 --- a/runtime/deploy/cloudflare-do/tests/runtime.mjs +++ b/runtime/deploy/cloudflare-do/tests/runtime.mjs @@ -318,6 +318,8 @@ try { let store = nonceStore(nonce); assert.equal(store.prepare("SELECT count(*) AS n FROM sqlite_master WHERE name = 'used_http_nonces_expiry'").get().n, 0); store.exec('CREATE INDEX used_http_nonces_expiry ON used_http_nonces (expires_at)'); + // This actor also predates the sparse index used for control-only reads. + store.exec('DROP INDEX items_control_seq'); const stale = store.prepare('INSERT INTO used_http_nonces (nonce, expires_at) VALUES (?, ?)'); for (let i = 0; i < 3; i++) stale.run(Buffer.alloc(32, 0xe0 + i), Date.now() - 120000); store.close(); @@ -339,6 +341,8 @@ try { try { assert.equal(store.prepare("SELECT count(*) AS n FROM sqlite_master WHERE name = 'used_http_nonces_expiry'").get().n, 0, 'actor startup drops the old expiry index'); + const plan = store.prepare('EXPLAIN QUERY PLAN SELECT seq FROM items WHERE seq > ? AND kind <> 1 ORDER BY seq').all(0); + assert.ok(plan.some(row => row.detail.startsWith('SEARCH items') && row.detail.includes('items_control_seq')), 'upgraded actor seeks control items by sequence'); assert.equal(store.prepare('SELECT count(*) AS n FROM used_http_nonces WHERE nonce IN (?, ?, ?)') .get(...[0, 1, 2].map(i => Buffer.alloc(32, 0xe0 + i))).n, 0, 'expired nonces are pruned without the index'); assert.equal(store.prepare('SELECT count(*) AS n FROM used_http_nonces WHERE nonce IN (?, ?)').get(nonce, freshNonce).n, 2, diff --git a/services/server/migrations/0113_active_account_computers.sql b/services/server/migrations/0113_active_account_computers.sql new file mode 100644 index 000000000..dd44cf03a --- /dev/null +++ b/services/server/migrations/0113_active_account_computers.sql @@ -0,0 +1,3 @@ +-- The Portal computer list reads one account's active connectors in creation order. +CREATE INDEX connectors_active_user_created_idx + ON connectors (user_id, created_at) WHERE revoked_at IS NULL; diff --git a/services/server/scripts/bench-account-computers.mjs b/services/server/scripts/bench-account-computers.mjs new file mode 100644 index 000000000..54864564f --- /dev/null +++ b/services/server/scripts/bench-account-computers.mjs @@ -0,0 +1,85 @@ +// Node 24, after building @mdbase-dev/connect-protocol. Set the same local test +// database URL and approval as the server PostgreSQL suites, then run: +// pnpm --filter @mdbase/connect-server exec tsx scripts/bench-account-computers.mjs +import assert from "node:assert/strict"; +import { randomUUID } from "node:crypto"; +import pg from "pg"; +import { createDatabase } from "../src/db.ts"; +import { listAccountComputers } from "../src/features/account/computers.ts"; + +const url = new URL(process.env.MDBASE_CONNECT_TEST_DATABASE_URL); +assert(["localhost", "127.0.0.1", "[::1]"].includes(url.hostname) && /test/i.test(url.pathname)); +assert.equal(process.env.MDBASE_CONNECT_DESTRUCTIVE_TEST_APPROVAL, "I APPROVE MDBASE CONNECT DESTRUCTIVE POSTGRES TESTS"); +const schema = "bench_computers_" + randomUUID().replaceAll("-", ""); +const admin = new pg.Client({ connectionString: url.href }); +await admin.connect(); +await admin.query(`CREATE SCHEMA "${schema}"`); +url.searchParams.set("options", `-csearch_path=${schema}`); +let db, client; +try { + db = await createDatabase(url.href); + client = await db.connect(); + const owner = randomUUID(); + await client.query("INSERT INTO users(id, email, name) VALUES ($1,'owner@example.test','Owner')", [owner]); + await client.query(`INSERT INTO connectors(id,user_id,name,token_hash,created_at,revoked_at) + SELECT gen_random_uuid(),$1,'computer-' || i,gen_random_uuid()::text, + now() - i * interval '1 day', CASE WHEN i = 3 THEN now() END FROM generate_series(1,3) i`, [owner]); + const app = randomUUID(); + await client.query(`INSERT INTO applications(id,canonical_identity,family_identity,name,homepage,redirect_uris) + VALUES($1,$1::uuid::text,'bundle:test.reader','Reader','https://reader.example','[]')`, [app]); + for (const appId of [app, "unregistered"]) { + const connector = randomUUID(), device = randomUUID(), key = Buffer.alloc(32); + await client.query(`INSERT INTO connectors(id,user_id,name,token_hash,created_at) + VALUES ($1,$2,$3,$1::uuid::text,now())`, [connector, owner, appId]); + await client.query(`INSERT INTO next_devices(id,connector_id,user_id,kind,sign_pk,kem_pk,noise_pk) + VALUES ($1,$2,$3,'app-runtime',$4,$4,$4)`, [device, connector, owner, key]); + await client.query(`INSERT INTO installation_device_credentials(pairing_id,connector_id,device_id,installation_id, + app_id,app_origin,kind,sign_pk,kem_pk,noise_pk,token_hash) + VALUES(gen_random_uuid(),$1,$2,gen_random_uuid(),$3,'https://reader.example','app-runtime',$4,$4,$4,$1::uuid::text)`, + [connector, device, appId, key]); + } + for (const unrelated of [0, 25000]) { + if (unrelated) { + await client.query(`INSERT INTO users(id,email,name) + SELECT md5(i::text)::uuid,i || '@example.test','Other' FROM generate_series(1,1000) i`); + await client.query(`INSERT INTO connectors(id,user_id,name,token_hash) + SELECT gen_random_uuid(),md5((1+i%1000)::text)::uuid,'Other',gen_random_uuid()::text + FROM generate_series(1,$1::int) i`, [unrelated]); + } + for (const table of ["connectors", "installation_device_credentials", "applications"]) await client.query("ANALYZE " + table); + const expected = await listAccountComputers(client, owner); + assert.deepEqual(expected.map(row => row.name), ["computer-2", "computer-1", "unregistered"]); + const samples = { before: [], after: [] }; + for (let pair = 0; pair < 34; pair++) { + for (const arm of pair % 2 ? ["after", "before"] : ["before", "after"]) { + await client.query("BEGIN"); + try { + if (arm === "before") await client.query("DROP INDEX connectors_active_user_created_idx"); + const rows = await listAccountComputers({ async query(sql, args) { + const result = await client.query("EXPLAIN (ANALYZE, BUFFERS, TIMING OFF, FORMAT JSON) " + sql, args); + const [{ Plan: plan, "Execution Time": ms }] = result.rows[0]["QUERY PLAN"]; + const nodes = node => [node, ...(node.Plans ?? []).flatMap(nodes)]; + const scan = nodes(plan).find(n => n["Relation Name"] === "connectors"); + if (pair >= 3) samples[arm].push({ ms, blocks: plan["Shared Hit Blocks"] + plan["Shared Read Blocks"], + scan: nodes(scan).find(n => n["Index Name"])?.["Index Name"] ?? scan["Node Type"] }); + return client.query(sql, args); + } }, owner); + assert.deepEqual(rows, expected); + } finally { + await client.query("ROLLBACK"); + } + } + } + for (const [arm, runs] of Object.entries(samples)) { + const percentile = (key, p) => runs.map(r => r[key]).sort((a,b) => a-b)[Math.ceil(runs.length * p) - 1]; + console.log({ unrelated, arm, runs: runs.length, medianMs: percentile("ms", .5), p95Ms: percentile("ms", .95), + medianBlocks: percentile("blocks", .5), scans: [...new Set(runs.map(r => r.scan))] }); + } + if (unrelated) assert(samples.after.every(r => r.scan === "connectors_active_user_created_idx")); + } +} finally { + client?.release(); + await db?.end(); + await admin.query(`DROP SCHEMA "${schema}" CASCADE`); + await admin.end(); +} diff --git a/services/server/src/features/account/installation-management.test.ts b/services/server/src/features/account/installation-management.test.ts index 8c91c5aab..7b57d9bcd 100644 --- a/services/server/src/features/account/installation-management.test.ts +++ b/services/server/src/features/account/installation-management.test.ts @@ -80,6 +80,11 @@ it("lists real installation consent as app access and preserves unknown/legacy c for (const hash of secretHashes) expect(response.body).not.toContain(hash); expect(response.body).not.toContain("sign_pk"); expect(response.body).not.toContain("token_hash"); + await db.query("UPDATE connectors SET revoked_at=now() WHERE id=$1", [legacy.id]); + const afterRevocation = await app.inject({ url: "/v1/me", headers: { cookie } }); + expect(afterRevocation.statusCode).toBe(200); + expect(afterRevocation.json().connectors.map((row: { id: string }) => row.id).sort()) + .toEqual([mobile.id, unknown.id].sort()); expect((await db.query("SELECT id FROM next_policy_outbox")).rows).toEqual([]); const globalPath = `/v1/account/installations/${empty.id}`; expect((await app.inject({ method: "DELETE", url: globalPath })).statusCode).toBe(401);