diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 00dbbf093e..576d292c70 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -913,6 +913,9 @@ jobs: - name: AST-based code quality checks run: pnpm quality:ast-checks + - name: Shared in-flight join guard (no unbounded await of another request's promise) + run: pnpm quality:shared-flight-joins + - name: File size limit enforcement run: pnpm quality:file-sizes diff --git a/apps/api/src/lib/shared-flight.ts b/apps/api/src/lib/shared-flight.ts new file mode 100644 index 0000000000..765e553b79 --- /dev/null +++ b/apps/api/src/lib/shared-flight.ts @@ -0,0 +1,14 @@ +// The Worker's import path for @simple-agent-manager/worker-core's shared-flight helpers. The +// self-host build's generated celld entry imports this file through its `src` link to apps/api/src, +// because that entry module lives outside the workspace and cannot resolve the package name +// itself. The celld resume mode lives in the one worker-core module, so the entry's call reaches +// every joiner, including packages/project-data's compact-r2 joins. +export { + __setSharedFlightResumeOnOwnTimerForTest, + DEFAULT_SHARED_FLIGHT_JOIN_GRACE_MS, + joinSharedFlight, + resumeSharedFlightJoinsOnOwnTimer, + settleSharedFlight, + SHARED_FLIGHT_POLL_MS, + SharedFlightAbandonedError, +} from '@simple-agent-manager/worker-core'; diff --git a/apps/api/src/services/admin-settings-cache.ts b/apps/api/src/services/admin-settings-cache.ts index 27463fa2be..e4d8c5aa41 100644 --- a/apps/api/src/services/admin-settings-cache.ts +++ b/apps/api/src/services/admin-settings-cache.ts @@ -2,6 +2,7 @@ import * as v from 'valibot'; import type { Env } from '../env'; import { resolveD1BindingIdentity } from '../lib/d1-session'; +import { joinSharedFlight, SharedFlightAbandonedError } from '../lib/shared-flight'; import type { AdminSettingName } from './admin-settings-registry'; import { DEFAULT_CONFIG_READ_TIMEOUT_MS } from './config-read-deadline'; import { withDeadline } from './fetch-timeout'; @@ -170,7 +171,9 @@ export class AdminSettingsCache { if (snapshot) return snapshot; const flight = this.flight(primary, state, useCache, readTimeoutMs); try { - const rows = await flight.promise; + // Joined under this request's own timer: on celld a flight whose starter's client went + // away never settles (lib/shared-flight.ts). + const rows = await joinSharedFlight(flight.promise, flight.deadlineAt, this.now()); if (state.generation !== flight.generation) return undefined; if (useCache && state.inFlight !== flight) { if (state.inFlight || state.snapshot) return undefined; @@ -186,7 +189,12 @@ export class AdminSettingsCache { expiresAt: flight.startedAt + ttlMs, }; return structuredClone(rows); - } catch { + } catch (error) { + if (error instanceof SharedFlightAbandonedError) { + // Drop the dead flight; the bounded outer loop starts this request's own read. + if (state.inFlight === flight) delete state.inFlight; + return undefined; + } if (state.generation !== flight.generation) return undefined; if (useCache && state.inFlight !== flight) { if (state.inFlight || state.snapshot) return undefined; diff --git a/apps/api/src/services/admin-settings-resolution.ts b/apps/api/src/services/admin-settings-resolution.ts index 2569aca25c..411af03025 100644 --- a/apps/api/src/services/admin-settings-resolution.ts +++ b/apps/api/src/services/admin-settings-resolution.ts @@ -2,6 +2,7 @@ import type { Env } from '../env'; import { resolveD1BindingIdentity } from '../lib/d1-session'; import { getCredentialEncryptionKey } from '../lib/secrets'; +import { settleSharedFlight } from '../lib/shared-flight'; import { errors } from '../middleware/error'; import { adminSettingCacheMs, @@ -78,7 +79,11 @@ export async function credentialRows( (!existing.pending || Date.now() < existing.deadlineAt) && Math.min(existing.expiresAt, existing.startedAt + ttlMs) > Date.now() ) { - const rows = await existing.promise; + // Own-timer join: a celld flight whose starter left never settles (lib/shared-flight.ts). + const joined = await settleSharedFlight(existing.promise, existing.deadlineAt); + if (joined.abandoned && credentialCache.get(db) === existing) credentialCache.delete(db); + if (joined.abandoned) return credentialRows(env, false, attempt + 1); + const rows = joined.value; if (credentialCache.get(db) !== existing) return credentialRows(env, false, attempt + 1); assertGeneration(db, generation); if (Date.now() >= Math.min(existing.expiresAt, existing.startedAt + ttlMs)) @@ -167,7 +172,10 @@ async function legacyKv( (!cached.pending || Date.now() < cached.deadlineAt) && Math.min(cached.expiresAt, cached.startedAt + ttlMs) > Date.now() ) { - const value = await cached.promise; + const joined = await settleSharedFlight(cached.promise, cached.deadlineAt); // as above + if (joined.abandoned && map.get(key) === cached) map.delete(key); + if (joined.abandoned) return legacyKv(env, key, false, ttlMs, attempt + 1); + const value = joined.value; if (map.get(key) !== cached) return legacyKv(env, key, false, ttlMs, attempt + 1); if ( adminSettingsGeneration(db) !== generation || diff --git a/apps/api/src/services/lifecycle-latency/range-report.ts b/apps/api/src/services/lifecycle-latency/range-report.ts index bf7c15895c..9df0531e6a 100644 --- a/apps/api/src/services/lifecycle-latency/range-report.ts +++ b/apps/api/src/services/lifecycle-latency/range-report.ts @@ -71,9 +71,12 @@ function watchSignatures(watch: LifecycleWatch): Promise { platformErrorSignature('api', regressionMessage(watch)), ]); // A failed digest is not cached, so the next request retries it. + // shared-flight-join-allowed: local SHA-256 digests only (crypto.subtle), no request I/O to drop. cached.catch(() => signatureCache.delete(key)); + // shared-flight-join-allowed: local SHA-256 digests only (crypto.subtle), no request I/O to drop. signatureCache.set(key, cached); } + // shared-flight-join-allowed: local SHA-256 digests only (crypto.subtle), no request I/O to drop. return cached; } diff --git a/apps/api/src/services/llm-endpoint-snapshot.ts b/apps/api/src/services/llm-endpoint-snapshot.ts index d5aa021129..88c8fb5aff 100644 --- a/apps/api/src/services/llm-endpoint-snapshot.ts +++ b/apps/api/src/services/llm-endpoint-snapshot.ts @@ -4,6 +4,7 @@ import * as v from 'valibot'; import type { Env } from '../env'; import { resolveD1BindingIdentity } from '../lib/d1-session'; +import { settleSharedFlight } from '../lib/shared-flight'; import { ADMIN_SETTINGS_CACHE_MAX_MS, AdminSettingsUnavailableError } from './admin-settings-cache'; import { type AdminSettingName } from './admin-settings-registry'; import { adminSettingsGeneration, requiredDefinition, resolved } from './admin-settings-resolution'; @@ -30,7 +31,13 @@ type Snapshot = { rows: v.InferOutput[]; credentials: v.InferOutput[]; }; -type Entry = { generation: number; expiresAt: number; promise: Promise }; +type Entry = { + generation: number; + expiresAt: number; + /** When the load's own deadline fires; joiners wait until then (plus grace), never longer. */ + deadlineAt: number; + promise: Promise; +}; const snapshots = new WeakMap(); async function load(env: Env, db: D1Database): Promise { @@ -76,22 +83,41 @@ async function load(env: Env, db: D1Database): Promise { return { rows: rows.output, credentials }; } +/** The cached load for this generation, or a fresh one when absent, superseded or expired. */ +function currentEntry(env: Env, db: D1Database, generation: number): Entry { + const cached = snapshots.get(db); + if (cached?.generation === generation && Date.now() < cached.expiresAt) return cached; + const entry: Entry = { + generation, + expiresAt: Date.now() + ADMIN_SETTINGS_CACHE_MAX_MS, + deadlineAt: Date.now() + DEFAULT_CONFIG_READ_TIMEOUT_MS, + promise: withDeadline(() => load(env, db), DEFAULT_CONFIG_READ_TIMEOUT_MS), + }; + snapshots.set(db, entry); + return entry; +} + +/** Drop `entry` from the cache unless another request has already replaced it. */ +function forgetEntry(db: D1Database, entry: Entry): void { + if (snapshots.get(db) === entry) snapshots.delete(db); +} + /** One atomic batch per isolate TTL, shared across purposes and request-scoped D1 facades. */ export async function resolveLlmEndpointSettings(env: Env, names: AdminSettingName[]) { const db = resolveD1BindingIdentity(env.DATABASE); for (let attempt = 0; attempt < 3; attempt++) { const generation = adminSettingsGeneration(db); - let entry = snapshots.get(db); - if (!entry || entry.generation !== generation || Date.now() >= entry.expiresAt) { - entry = { - generation, - expiresAt: Date.now() + ADMIN_SETTINGS_CACHE_MAX_MS, - promise: withDeadline(() => load(env, db), DEFAULT_CONFIG_READ_TIMEOUT_MS), - }; - snapshots.set(db, entry); - } + const entry = currentEntry(env, db, generation); try { - const snapshot = await entry.promise; + // Another request may have started this load; on a runtime that drops a disconnected + // request's I/O it can never settle, so join it with a bound (packages/worker-core + // shared-flight.ts) and start a fresh load if it was abandoned. + const joined = await settleSharedFlight(entry.promise, entry.deadlineAt); + if (joined.abandoned) { + forgetEntry(db, entry); + continue; + } + const snapshot = joined.value; const values = await Promise.all( names.map((name) => resolved(env, requiredDefinition(name), snapshot.rows, true, snapshot.credentials) @@ -101,7 +127,7 @@ export async function resolveLlmEndpointSettings(env: Env, names: AdminSettingNa if (Date.now() >= entry.expiresAt) throw new AdminSettingsUnavailableError(); return values; } catch (error) { - if (snapshots.get(db) === entry) snapshots.delete(db); + forgetEntry(db, entry); if (generation !== adminSettingsGeneration(db)) continue; throw error; } diff --git a/apps/api/src/services/platform-config-core.ts b/apps/api/src/services/platform-config-core.ts index a57635ee2c..d673cf71b0 100644 --- a/apps/api/src/services/platform-config-core.ts +++ b/apps/api/src/services/platform-config-core.ts @@ -3,6 +3,7 @@ import { SYSTEM_USER_ID } from '@simple-agent-manager/shared'; import type { Env } from '../env'; import { resolveD1BindingIdentity } from '../lib/d1-session'; import { log } from '../lib/logger'; +import { settleSharedFlight } from '../lib/shared-flight'; import { commitAdminSettingsStatements, resolveAdminSettingDetailsMany, @@ -57,6 +58,13 @@ import type { */ const DEFAULT_PLATFORM_CONFIG_CACHE_MS = 60_000; +/** + * How many times one resolve may join another request's read, or retry after a write revoked + * its own, before it makes one unregistered read for itself. Bounds the recursion when flights + * keep being abandoned or revoked. Internal safety margin, not an operator setting. + */ +const MAX_PLATFORM_CONFIG_JOIN_ATTEMPTS = 3; + /* * The writers below never return resolved values ON PURPOSE. A `ResolvedPlatformConfig` carries * every platform secret as plaintext `.value`, and a since-removed `PUT /api/setup/config` once @@ -309,7 +317,8 @@ export async function resolvePlatformConfig( async function resolveLegacyPlatformConfig( env: Env, now: number = Date.now(), - timeoutMs = DEFAULT_CONFIG_READ_TIMEOUT_MS + timeoutMs = DEFAULT_CONFIG_READ_TIMEOUT_MS, + joinAttempt = 0 ): Promise { // A missing binding is NOT a usable cache key: `undefined === undefined` would make every // database-less env share one entry. Such an env also resolves purely from `env` values @@ -346,14 +355,38 @@ async function resolveLegacyPlatformConfig( joinable && joinable.database === database && joinable.generation === platformConfigCacheGeneration && - Date.now() < joinable.deadlineAt + Date.now() < joinable.deadlineAt && + joinAttempt < MAX_PLATFORM_CONFIG_JOIN_ATTEMPTS ) { - const config = await joinable.promise; + // Joined under this request's own timer, and resumed in its own turn (lib/shared-flight.ts): + // on celld a flight whose starter's client went away never settles, and a plain await would + // also run the rest of this request as part of the starter's. + const joined = await settleSharedFlight(joinable.promise, joinable.deadlineAt); + if (joined.abandoned) { + // The first caller to notice drops the dead flight and starts the replacement read; the + // other waiters, woken by their own timers just after, join that one. + if (platformConfigInFlight === joinable) platformConfigInFlight = null; + return resolveLegacyPlatformConfig(env, Date.now(), timeoutMs, joinAttempt + 1); + } if ( platformConfigCacheGeneration !== joinable.generation || platformConfigInFlight !== joinable ) - return resolveLegacyPlatformConfig(env); + return resolveLegacyPlatformConfig(env, Date.now(), timeoutMs, joinAttempt + 1); + return joined.value; + } + + // Past the attempt bound (flights kept being abandoned or revoked): one read of our own, not + // registered and not published, so it cannot displace another request's live flight. Like the + // starter and joiner paths, it never returns a read a write revoked while it was pending. It + // cannot retry (that is what the bound stops), so it fails the same way a read that outlived + // its deadline does: config unavailable for this request, which the caller may retry. + if (joinAttempt >= MAX_PLATFORM_CONFIG_JOIN_ATTEMPTS) { + const fallbackGeneration = platformConfigCacheGeneration; + const config = await withDeadline(() => readPlatformConfigFromStore(env), timeoutMs); + if (platformConfigCacheGeneration !== fallbackGeneration) { + throw new IoTimeoutError('Platform configuration changed while it was being read'); + } return config; } @@ -364,14 +397,16 @@ async function resolveLegacyPlatformConfig( try { const config = await promise; - if (platformConfigInFlight?.promise !== promise) return resolveLegacyPlatformConfig(env); + if (platformConfigInFlight?.promise !== promise) + return resolveLegacyPlatformConfig(env, Date.now(), timeoutMs, joinAttempt + 1); if (Date.now() >= deadlineAt) throw new IoTimeoutError('Platform configuration read exceeded its deadline'); if (platformConfigCacheGeneration === generation) { // No write landed while we were reading, so this result is still current: publish it. platformConfigCache = { database, config, expiresAt: now + ttl }; } - if (platformConfigCacheGeneration !== generation) return resolveLegacyPlatformConfig(env); + if (platformConfigCacheGeneration !== generation) + return resolveLegacyPlatformConfig(env, Date.now(), timeoutMs, joinAttempt + 1); return config; } finally { if (platformConfigInFlight?.promise === promise) { diff --git a/apps/api/tests/unit/lib/shared-flight.test.ts b/apps/api/tests/unit/lib/shared-flight.test.ts new file mode 100644 index 0000000000..82a94f83f0 --- /dev/null +++ b/apps/api/tests/unit/lib/shared-flight.test.ts @@ -0,0 +1,116 @@ +/** + * Joining another request's in-flight promise under the joiner's own timer (src/lib/shared-flight.ts). + * On celld a flight whose starter's client disconnected never settles; the joiner must not wait + * past the flight's deadline plus the grace. The real-runtime proof is + * scripts/selfhost/live/shared-flight-cancel.live.test.ts. + */ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { + __setSharedFlightResumeOnOwnTimerForTest, + DEFAULT_SHARED_FLIGHT_JOIN_GRACE_MS, + joinSharedFlight, + settleSharedFlight, + SHARED_FLIGHT_POLL_MS, + SharedFlightAbandonedError, +} from '../../../src/lib/shared-flight'; + +const never = () => new Promise(() => undefined); + +beforeEach(() => vi.useFakeTimers()); +afterEach(() => { + vi.useRealTimers(); + __setSharedFlightResumeOnOwnTimerForTest(false); +}); + +describe.each([ + { runtime: 'Cloudflare', ownTimer: false }, + { runtime: 'celld', ownTimer: true }, +])('joinSharedFlight ($runtime)', ({ ownTimer }) => { + beforeEach(() => __setSharedFlightResumeOnOwnTimerForTest(ownTimer)); + + it('returns a live flight’s value and leaves no timer behind', async () => { + const now = Date.now(); + await expect(joinSharedFlight(Promise.resolve('v'), now + 5000, now)).resolves.toBe('v'); + expect(vi.getTimerCount()).toBe(0); + }); + + it('passes a live flight’s own failure through unchanged', async () => { + const failure = new Error('read failed'); + const now = Date.now(); + await expect(joinSharedFlight(Promise.reject(failure), now + 5000, now)).rejects.toBe(failure); + }); + + it('reports a flight that never settles as abandoned at deadline plus grace, not before', async () => { + const now = Date.now(); + const joined = joinSharedFlight(never(), now + 5000, now); + const outcome = joined.then( + () => 'resolved', + (error: unknown) => error + ); + await vi.advanceTimersByTimeAsync(5000 + DEFAULT_SHARED_FLIGHT_JOIN_GRACE_MS - 1); + let settled = false; + void outcome.then(() => (settled = true)); + await Promise.resolve(); + expect(settled).toBe(false); + await vi.advanceTimersByTimeAsync(1); + expect(await outcome).toBeInstanceOf(SharedFlightAbandonedError); + }); + + it('gives a flight already past its deadline only the grace', async () => { + const now = Date.now(); + const outcome = settleSharedFlight(never(), now - 10_000, now); + await vi.advanceTimersByTimeAsync(DEFAULT_SHARED_FLIGHT_JOIN_GRACE_MS); + await expect(outcome).resolves.toEqual({ abandoned: true }); + }); + + it('settleSharedFlight returns the value of a live flight and rethrows its failure', async () => { + const now = Date.now(); + await expect(settleSharedFlight(Promise.resolve(3), now + 10, now)).resolves.toEqual({ + abandoned: false, + value: 3, + }); + const failure = new Error('x'); + await expect(settleSharedFlight(Promise.reject(failure), now + 10, now)).rejects.toBe(failure); + }); +}); + +describe('where a joiner resumes', () => { + it('resumes a joiner of a pending flight on its own timer, never on the settlement', async () => { + // On celld the code that runs when a promise settles belongs to the request that settled it, + // so a joiner must not continue there (task R6). Settling the flight alone must not resume it. + __setSharedFlightResumeOnOwnTimerForTest(true); + let settle: (value: string) => void = () => undefined; + const flight = new Promise((resolve) => (settle = resolve)); + const now = Date.now(); + let resumed = false; + const joined = joinSharedFlight(flight, now + 5000, now).then((value) => { + resumed = true; + return value; + }); + await vi.advanceTimersByTimeAsync(SHARED_FLIGHT_POLL_MS * 3); + settle('v'); + for (let i = 0; i < 10; i++) await Promise.resolve(); + expect(resumed).toBe(false); + await vi.advanceTimersByTimeAsync(SHARED_FLIGHT_POLL_MS); + expect(resumed).toBe(true); + await expect(joined).resolves.toBe('v'); + expect(vi.getTimerCount()).toBe(0); + }); + + it('on Cloudflare resumes a joiner directly on the settlement, with no added timer', async () => { + let settle: (value: string) => void = () => undefined; + const flight = new Promise((resolve) => (settle = resolve)); + const now = Date.now(); + let resumed = false; + const joined = joinSharedFlight(flight, now + 5000, now).then((value) => { + resumed = true; + return value; + }); + settle('v'); + for (let i = 0; i < 10; i++) await Promise.resolve(); + expect(resumed).toBe(true); + await expect(joined).resolves.toBe('v'); + expect(vi.getTimerCount()).toBe(0); + }); +}); diff --git a/apps/api/tests/unit/services/shared-flight-abandonment.test.ts b/apps/api/tests/unit/services/shared-flight-abandonment.test.ts new file mode 100644 index 0000000000..2655987916 --- /dev/null +++ b/apps/api/tests/unit/services/shared-flight-abandonment.test.ts @@ -0,0 +1,362 @@ +/** + * Abandonment branches of every per-isolate in-flight cache (task F1, review V1 of #2706). + * + * On the self-hosted celld runtime a request's async ops (D1 call, KV read, DO RPC, its deadline + * timer) are dropped when that request's client disconnects, so a flight it started never + * settles (src/lib/shared-flight.ts). Each case below models that exactly: the starter's read + * never resolves, and `vi.clearAllTimers()` drops the starter's own deadline timer, as celld does. + * Then several requests join the dead flight. They must + * - keep waiting until the flight's deadline plus the join grace (a slow live read is never + * duplicated early), then + * - share ONE replacement read between them (no storm), and answer. + * + * Each case runs in both join modes (task R7): Cloudflare, where the flight's settlement resumes + * a joiner, and celld, where a joiner resumes on its own timer (lib/shared-flight.ts). On celld the + * waiters of the replacement read wake on their own poll timer, so each case advances by one poll + * interval past the bound before it reads the answers. + * + * Proven discriminating (F1): removing the abandonment retry in `credentialRows` / `legacyKv` / + * `resolveLegacyPlatformConfig` turns the matching case red. The AdminSettingsCache and LLM + * endpoint snapshot cases (L22a) cover the two sites the static check cannot see, because their + * cache entry reaches the join through a function parameter. (The ProjectData ensure memo no + * longer shares in-flight ensures, so it has no abandonment branch to test here.) + */ +import type Database from 'better-sqlite3'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import type { Env } from '../../../src/env'; +import { + __setSharedFlightResumeOnOwnTimerForTest, + DEFAULT_SHARED_FLIGHT_JOIN_GRACE_MS, + SHARED_FLIGHT_POLL_MS, +} from '../../../src/lib/shared-flight'; +import { resolveAdminSetting } from '../../../src/services/admin-settings'; +import { + __resetAdminSettingsCacheForTest, + credentialRows, +} from '../../../src/services/admin-settings-resolution'; +import { DEFAULT_CONFIG_READ_TIMEOUT_MS } from '../../../src/services/config-read-deadline'; +import { IoTimeoutError } from '../../../src/services/fetch-timeout'; +import { resolveLlmEndpointSettings } from '../../../src/services/llm-endpoint-snapshot'; +import { + __resetPlatformConfigCacheForTest, + resolvePlatformConfig, +} from '../../../src/services/platform-config'; +import { createAdminSettingsEnv } from '../../helpers/admin-settings-env'; +import { createEnv } from '../../helpers/platform-config-counting-fixture'; + +const never = () => new Promise(() => undefined); +/** How long a joiner waits on a flight whose deadline is `DEFAULT_CONFIG_READ_TIMEOUT_MS` away. */ +const JOIN_BOUND_MS = DEFAULT_CONFIG_READ_TIMEOUT_MS + DEFAULT_SHARED_FLIGHT_JOIN_GRACE_MS; + +let open: Database.Database[] = []; +beforeEach(() => { + vi.useFakeTimers(); + __resetAdminSettingsCacheForTest(); + __resetPlatformConfigCacheForTest(); +}); +afterEach(() => { + vi.useRealTimers(); + __setSharedFlightResumeOnOwnTimerForTest(false); + for (const sqlite of open) sqlite.close(); + open = []; +}); + +/** Track settlement of each promise without awaiting it. */ +function watch(promises: Promise[]) { + const settled = promises.map(() => false); + promises.forEach((p, i) => { + void p.then( + () => (settled[i] = true), + () => (settled[i] = true) + ); + }); + return settled; +} + +/** + * Advance fake time one poll interval at a time until `done()`. On celld a request waits even on + * its own settings flight through the join poll, so its next read starts a poll interval later. + */ +async function advanceUntil(done: () => boolean): Promise { + for (let i = 0; i < 100 && !done(); i++) await vi.advanceTimersByTimeAsync(SHARED_FLIGHT_POLL_MS); + expect(done()).toBe(true); +} + +/** Await a call that may wait on join-poll timers, advancing fake time until it settles. */ +async function untilSettled(promise: Promise): Promise { + let done = false; + void promise.then( + () => (done = true), + () => (done = true) + ); + await vi.advanceTimersByTimeAsync(0); + await advanceUntil(() => done); + return promise; +} + +/** + * Start a flight, wait until its read is in flight, then drop every timer the way celld drops a + * cancelled request's ops (its deadline timer included). + */ +async function startAndDrop(start: () => Promise, inFlight: () => boolean): Promise { + void start().catch(() => undefined); + await vi.advanceTimersByTimeAsync(0); + await advanceUntil(inFlight); + vi.clearAllTimers(); +} + +/** The statements one legacy platform-config read runs. */ +const isLegacyConfigRead = (sql: string) => /WHERE key = \?|AS encryptedToken/.test(sql); + +/** + * A counting env whose admin-settings caches are warm, so only the legacy platform-config read + * runs below, plus how many statements that read takes. The platform-config cache is cleared. + */ +async function warmPlatformConfigEnv() { + const { env, counter } = createEnv(); + await untilSettled(resolvePlatformConfig(env)); + __resetPlatformConfigCacheForTest(); + counter.reset(); + await untilSettled(resolvePlatformConfig(env)); + const perRead = counter.executed.filter(isLegacyConfigRead).length; + expect(perRead).toBeGreaterThan(0); + __resetPlatformConfigCacheForTest(); + counter.reset(); + return { env, counter, perRead }; +} + +/** + * Lands a settings write (the revocation invalidatePlatformConfigCache performs) at the start of + * each of the first `reads` legacy reads. Returns the count of legacy statements run since. + */ +function revokePlatformConfigReads(env: Env, perRead: number, reads: number): () => number { + let statements = 0; + const realPrepare = env.DATABASE.prepare.bind(env.DATABASE); + env.DATABASE.prepare = ((sql: string) => { + if (isLegacyConfigRead(sql)) { + if (statements % perRead === 0 && statements / perRead < reads) { + __resetPlatformConfigCacheForTest(); + } + statements += 1; + } + return realPrepare(sql); + }) as typeof env.DATABASE.prepare; + return () => statements; +} + +describe.each([ + { runtime: 'Cloudflare', ownTimer: false }, + { runtime: 'celld', ownTimer: true }, +])('$runtime joins', ({ ownTimer }) => { + beforeEach(() => __setSharedFlightResumeOnOwnTimerForTest(ownTimer)); + + describe('credentialRows: joiners of a dropped credential read', () => { + it('wait out its deadline, then share one replacement read', async () => { + const { sqlite, env } = createAdminSettingsEnv(); + open.push(sqlite); + let reads = 0; + const realPrepare = env.DATABASE.prepare.bind(env.DATABASE); + env.DATABASE.prepare = ((sql: string) => { + const statement = realPrepare(sql); + if (!sql.includes('credential_kind AS kind')) return statement; + return { + bind: (...args: unknown[]) => { + const bound = statement.bind(...args); + return { + all: () => { + reads += 1; + return reads === 1 ? never() : bound.all(); + }, + }; + }, + }; + }) as typeof env.DATABASE.prepare; + + await startAndDrop( + () => credentialRows(env), + () => reads >= 1 + ); + expect(reads).toBe(1); + + const joiners = [credentialRows(env), credentialRows(env), credentialRows(env)]; + const settled = watch(joiners); + await vi.advanceTimersByTimeAsync(JOIN_BOUND_MS - 1); + expect(settled).toEqual([false, false, false]); + expect(reads).toBe(1); + + await vi.advanceTimersByTimeAsync(1 + SHARED_FLIGHT_POLL_MS); + // Liveness: every joiner answers with the real (empty) result. + await expect(Promise.all(joiners)).resolves.toEqual([[], [], []]); + expect(reads).toBe(2); + }); + }); + + describe('legacyKv: joiners of a dropped kill-switch KV read', () => { + it('wait out its deadline, then share one replacement read', async () => { + const { sqlite, env } = createAdminSettingsEnv(); + open.push(sqlite); + await env.KV.put('control-loops:cron-enabled', 'false'); + let reads = 0; + const realGet = env.KV.get.bind(env.KV); + env.KV.get = ((key: string, options?: unknown) => { + if (key !== 'control-loops:cron-enabled') return realGet(key, options as never); + reads += 1; + return reads === 1 ? never() : realGet(key, options as never); + }) as typeof env.KV.get; + + await startAndDrop( + () => resolveAdminSetting(env, 'operations.cronSweepsEnabled'), + () => reads >= 1 + ); + expect(reads).toBe(1); + + const joiners = [ + resolveAdminSetting(env, 'operations.cronSweepsEnabled'), + resolveAdminSetting(env, 'operations.cronSweepsEnabled'), + resolveAdminSetting(env, 'operations.cronSweepsEnabled'), + ]; + const settled = watch(joiners); + await vi.advanceTimersByTimeAsync(JOIN_BOUND_MS - 1); + expect(settled).toEqual([false, false, false]); + + await vi.advanceTimersByTimeAsync(1 + SHARED_FLIGHT_POLL_MS); + // The KV kill switch still wins: the joiners read the real value, not a default. + await expect(Promise.all(joiners)).resolves.toEqual([false, false, false]); + expect(reads).toBe(2); + }); + }); + + describe('AdminSettingsCache: joiners of a dropped overrides read', () => { + it('wait out its deadline, then share one replacement read', async () => { + const { sqlite, env } = createAdminSettingsEnv(); + open.push(sqlite); + const expected = await untilSettled(resolveAdminSetting(env, 'connector.enabled')); + __resetAdminSettingsCacheForTest(); + let reads = 0; + const realPrepare = env.DATABASE.prepare.bind(env.DATABASE); + env.DATABASE.prepare = ((sql: string) => { + const statement = realPrepare(sql); + if (!sql.startsWith('SELECT key, value, updated_at AS updatedAt')) return statement; + return { + all: () => { + reads += 1; + return reads === 1 ? never() : statement.all(); + }, + }; + }) as typeof env.DATABASE.prepare; + + await startAndDrop( + () => resolveAdminSetting(env, 'connector.enabled'), + () => reads >= 1 + ); + expect(reads).toBe(1); + + const joiners = [ + resolveAdminSetting(env, 'connector.enabled'), + resolveAdminSetting(env, 'connector.enabled'), + ]; + const settled = watch(joiners); + await vi.advanceTimersByTimeAsync(JOIN_BOUND_MS - 1); + expect(settled).toEqual([false, false]); + expect(reads).toBe(1); + + await advanceUntil(() => settled.every(Boolean)); + await expect(Promise.all(joiners)).resolves.toEqual([expected, expected]); + expect(reads).toBe(2); + }); + }); + + describe('LLM endpoint snapshot: joiners of a dropped snapshot read', () => { + it('wait out its deadline, then share one replacement read', async () => { + const { sqlite, env } = createAdminSettingsEnv(); + open.push(sqlite); + const names = ['llm.openAICompatible.baseUrl', 'outbound.maxRedirects'] as const; + const expected = await untilSettled(resolveLlmEndpointSettings(env, [...names])); + // A fresh binding identity is not available here, so drop the cached snapshot by + // invalidating the admin-settings generation it is keyed on. + __resetAdminSettingsCacheForTest(); + let reads = 0; + const realBatch = env.DATABASE.batch.bind(env.DATABASE); + env.DATABASE.batch = ((statements: Parameters[0]) => { + reads += 1; + return reads === 1 ? never() : realBatch(statements); + }) as typeof env.DATABASE.batch; + + await startAndDrop( + () => resolveLlmEndpointSettings(env, [...names]), + () => reads >= 1 + ); + expect(reads).toBe(1); + + const joiners = [ + resolveLlmEndpointSettings(env, [...names]), + resolveLlmEndpointSettings(env, [...names]), + ]; + const settled = watch(joiners); + await vi.advanceTimersByTimeAsync(JOIN_BOUND_MS - 1); + expect(settled).toEqual([false, false]); + expect(reads).toBe(1); + + await advanceUntil(() => settled.every(Boolean)); + await expect(Promise.all(joiners)).resolves.toEqual([expected, expected]); + expect(reads).toBe(2); + }); + }); + + describe('platform config: joiners of a dropped legacy-config read', () => { + it('wait out its deadline, then share one replacement read', async () => { + const { env, counter, perRead } = await warmPlatformConfigEnv(); + const legacyReads = () => counter.executed.filter(isLegacyConfigRead).length; + + const gate = counter.stall(); + await startAndDrop( + () => resolvePlatformConfig(env), + () => legacyReads() >= perRead + ); + gate.disarm(); // the dropped read stays stuck; new reads run + expect(legacyReads()).toBe(perRead); + + const joiners = [resolvePlatformConfig(env), resolvePlatformConfig(env)]; + const settled = watch(joiners); + await vi.advanceTimersByTimeAsync(JOIN_BOUND_MS - 1); + expect(settled).toEqual([false, false]); + expect(legacyReads()).toBe(perRead); + + await vi.advanceTimersByTimeAsync(1 + SHARED_FLIGHT_POLL_MS); + const [a, b] = await Promise.all(joiners); + expect(a.github.appSlug.value).toBe('env-app-slug'); + expect(b).toStrictEqual(a); + expect(legacyReads()).toBe(2 * perRead); + // The replacement was published: the next caller is served from the cache. + counter.reset(); + await untilSettled(resolvePlatformConfig(env)); + expect(legacyReads()).toBe(0); + }); + + it('after three revoked reads, answers from one read of its own that it does not publish', async () => { + const { env, perRead } = await warmPlatformConfigEnv(); + // A settings write lands during each of the first three reads, so each loses its right + // to publish. + const statements = revokePlatformConfigReads(env, perRead, 3); + + const config = await untilSettled(resolvePlatformConfig(env)); + expect(config.github.appSlug.value).toBe('env-app-slug'); + // Three revoked reads, then exactly one more: the bounded fallback, not a fourth retry. + expect(statements()).toBe(4 * perRead); + + // The fallback read was not published, so the next caller reads again. + await untilSettled(resolvePlatformConfig(env)); + expect(statements()).toBe(5 * perRead); + }); + + it('refuses the fallback read when a write also lands while it is pending', async () => { + const { env, perRead } = await warmPlatformConfigEnv(); + // A write lands during all four reads, the fallback included. + const statements = revokePlatformConfigReads(env, perRead, Number.POSITIVE_INFINITY); + + await expect(untilSettled(resolvePlatformConfig(env))).rejects.toBeInstanceOf(IoTimeoutError); + expect(statements()).toBe(4 * perRead); + }); + }); +}); diff --git a/package.json b/package.json index 631dabb7f9..084c067118 100644 --- a/package.json +++ b/package.json @@ -43,6 +43,7 @@ "quality:agent-install-manifest": "tsx scripts/quality/check-agent-install-manifest.ts", "quality:skill-references": "tsx scripts/quality/check-skill-references.ts", "quality:ast-checks": "tsx scripts/quality/ast-checks.ts", + "quality:shared-flight-joins": "tsx scripts/quality/check-shared-flight-joins.ts", "quality:file-sizes": "tsx scripts/quality/check-file-sizes.ts", "quality:stale-artifacts": "tsx scripts/quality/check-stale-artifacts.ts", "quality:migration-safety": "tsx scripts/quality/check-migration-safety.ts", diff --git a/packages/project-data/src/archive/compact-r2.ts b/packages/project-data/src/archive/compact-r2.ts index 2b644be5aa..ea50b489d2 100644 --- a/packages/project-data/src/archive/compact-r2.ts +++ b/packages/project-data/src/archive/compact-r2.ts @@ -1,5 +1,7 @@ import { createHash } from 'node:crypto'; +import { joinSharedFlight, SharedFlightAbandonedError } from '@simple-agent-manager/worker-core'; + import { PROJECT_DATA_ARCHIVE_MAX_CHUNK_BYTES, type ProjectDataArchiveChunk } from './contract'; import { sha256Hex } from './hashing'; @@ -54,6 +56,33 @@ async function timed(promise: Promise, deadline: number, stage: string): P type PendingR2Operation = { stage: string; promise: Promise }; const pendingR2Operations = new WeakMap>(); +/** + * Wait for an R2 operation another caller started, under this caller's own deadline. Joined + * through worker-core's shared-flight.ts like every other per-isolate flight: the cron sweep + * reaches this from stateless code, and on the self-hosted celld runtime a caller that resumed on + * another request's settlement would lose its next R2 call and its own deadline timer when that + * request answered (task R7). On Cloudflare this is the same race against a deadline timer as `timed`. + * + * Unlike the other shared flights, an abandoned operation is NOT evicted: a second provider call + * must never race the first on an immutable key (see timedR2). On celld a dropped operation + * therefore keeps failing joiners for that key with a timeout until the isolate is retired + * (tracked: tasks/backlog/2026-11-19-compact-r2-celld-abandoned-op-eviction.md). + */ +async function joinR2Operation( + pending: PendingR2Operation, + deadline: number, + stage: string +): Promise { + void pending.promise.catch(() => undefined); + if (deadline - Date.now() <= 0) throw new CompactArchiveTimeoutError(stage); + try { + return await joinSharedFlight(pending.promise, deadline, Date.now(), 0); + } catch (error) { + if (error instanceof SharedFlightAbandonedError) throw new CompactArchiveTimeoutError(stage); + throw error; + } +} + /** * Keep one provider operation in flight per bucket/key. A deadline may release * the request, but a retry in the same isolate waits for the original provider @@ -78,12 +107,12 @@ async function timedR2( // GET results carry a single-use body stream. Wait for the provider call, // then fetch an independent body for the joining reader. if (stage === 'get') { - await timed(pending.promise, deadline, stage); + await joinR2Operation(pending, deadline, stage); return timedR2(r2, key, deadline, stage, start); } - return timed(pending.promise as Promise, deadline, stage); + return (await joinR2Operation(pending, deadline, stage)) as T; } - await timed(pending.promise, deadline, `${stage}_pending`); + await joinR2Operation(pending, deadline, `${stage}_pending`); return timedR2(r2, key, deadline, stage, start); } const promise = start(); diff --git a/packages/project-data/tests/unit/project-data-compact-archive.test.ts b/packages/project-data/tests/unit/project-data-compact-archive.test.ts index 67243bccf1..0a30f2d66f 100644 --- a/packages/project-data/tests/unit/project-data-compact-archive.test.ts +++ b/packages/project-data/tests/unit/project-data-compact-archive.test.ts @@ -1,5 +1,9 @@ +import { + __setSharedFlightResumeOnOwnTimerForTest, + SHARED_FLIGHT_POLL_MS, +} from '@simple-agent-manager/worker-core'; import Database from 'better-sqlite3'; -import { describe, expect, it, vi } from 'vitest'; +import { describe, expect, it, onTestFinished, vi } from 'vitest'; import { ARCHIVE_IMMUTABLE_JSON_MAX_OBJECT_BYTES, @@ -652,55 +656,139 @@ describe('compact archive bounded failures', () => { expect(bucket.put).toHaveBeenCalledTimes(2); }); - it('does not race a retry against a timed-out immutable provider write', async () => { + it.each([ + { runtime: 'Cloudflare', ownTimer: false }, + { runtime: 'celld', ownTimer: true }, + ])( + 'does not race a retry against a timed-out immutable provider write ($runtime join)', + async ({ ownTimer }) => { + // Both join modes of lib/shared-flight.ts: on celld a joiner resumes on its own timer. + __setSharedFlightResumeOnOwnTimerForTest(ownTimer); + onTestFinished(() => __setSharedFlightResumeOnOwnTimerForTest(false)); + let finishPut: ((value: R2Object) => void) | undefined; + const stored = new Map(); + const bucket = { + head: vi.fn(async (key: string) => { + const body = stored.get(key); + return body + ? ({ + size: body.byteLength, + customMetadata: { + archiveBodySha256: await crypto.subtle + .digest('SHA-256', body) + .then((digest) => + Array.from(new Uint8Array(digest), (byte) => + byte.toString(16).padStart(2, '0') + ).join('') + ), + }, + } as R2Object) + : null; + }), + put: vi.fn( + (key: string, body: Uint8Array) => + new Promise((resolve) => { + stored.set(key, new Uint8Array(body)); + finishPut = resolve; + }) + ), + get: vi.fn(), + } as unknown as R2Bucket; + + await expect( + writeImmutableJson(bucket, 'pending.json', { ok: true }, 250) + ).rejects.toMatchObject({ + name: 'CompactArchiveTimeoutError', + stage: 'put', + }); + await expect( + writeImmutableJson(bucket, 'pending.json', { ok: true }, 5) + ).rejects.toMatchObject({ + name: 'CompactArchiveTimeoutError', + stage: 'head_pending', + }); + expect(bucket.put).toHaveBeenCalledTimes(1); + // A writer that joins the still-pending PUT inside its deadline answers once the PUT lands, + // without a second provider write. + const joiner = writeImmutableJson(bucket, 'pending.json', { ok: true }, 2_000); + await new Promise((resolve) => setTimeout(resolve, 20)); + finishPut?.({} as R2Object); + await expect(joiner).resolves.toBeUndefined(); + await expect( + writeImmutableJson(bucket, 'pending.json', { ok: true }, 50) + ).resolves.toBeUndefined(); + expect(bucket.put).toHaveBeenCalledTimes(1); + } + ); + + it('on celld, a writer joining a pending PUT resumes on its own timer, not on the PUT settling', async () => { + // On celld the code that runs when a promise settles belongs to the request that settled + // it, so a joiner must wake on a timer it owns (lib/shared-flight.ts). Only the timers are + // faked: the joiner's poll timer cannot fire until the test advances it. + __setSharedFlightResumeOnOwnTimerForTest(true); + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); + onTestFinished(() => { + vi.useRealTimers(); + __setSharedFlightResumeOnOwnTimerForTest(false); + }); + const sha256 = async (body: Uint8Array) => + Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', body)), (byte) => + byte.toString(16).padStart(2, '0') + ).join(''); let finishPut: ((value: R2Object) => void) | undefined; - const stored = new Map(); + let stored: Promise | undefined; const bucket = { - head: vi.fn(async (key: string) => { - const body = stored.get(key); - return body - ? ({ - size: body.byteLength, - customMetadata: { - archiveBodySha256: await crypto.subtle - .digest('SHA-256', body) - .then((digest) => - Array.from(new Uint8Array(digest), (byte) => - byte.toString(16).padStart(2, '0') - ).join('') - ), - }, - } as R2Object) - : null; + head: vi.fn(async () => (stored ? await stored : null)), + put: vi.fn((_key: string, body: Uint8Array) => { + // The digest is computed eagerly, so a later HEAD answers within microtasks. + const object = sha256(new Uint8Array(body)).then( + (archiveBodySha256) => + ({ size: body.byteLength, customMetadata: { archiveBodySha256 } }) as R2Object + ); + return new Promise((resolve) => { + finishPut = (value) => { + stored = object; + resolve(value); + }; + }); }), - put: vi.fn( - (key: string, body: Uint8Array) => - new Promise((resolve) => { - stored.set(key, new Uint8Array(body)); - finishPut = resolve; - }) - ), get: vi.fn(), } as unknown as R2Bucket; + const flush = async () => { + for (let i = 0; i < 20; i++) await new Promise((resolve) => setImmediate(resolve)); + }; - await expect( - writeImmutableJson(bucket, 'pending.json', { ok: true }, 250) - ).rejects.toMatchObject({ - name: 'CompactArchiveTimeoutError', - stage: 'put', - }); - await expect(writeImmutableJson(bucket, 'pending.json', { ok: true }, 5)).rejects.toMatchObject( - { - name: 'CompactArchiveTimeoutError', - stage: 'head_pending', + // Each writer hashes its body with real async crypto before touching R2, so wait on the + // condition itself rather than a fixed number of ticks (CI coverage runs are slow). + const waitFor = async (condition: () => boolean) => { + for (let i = 0; i < 1_000 && !condition(); i++) { + await new Promise((resolve) => setImmediate(resolve)); } + expect(condition()).toBe(true); + }; + const starter = writeImmutableJson(bucket, 'own-timer.json', { ok: true }, 2_000); + await waitFor(() => vi.mocked(bucket.put).mock.calls.length === 1); + // Wait until the joiner is parked on the pending PUT, signalled by the timer it registers + // there (its poll timer on celld, its deadline timer otherwise). + const timersBefore = vi.getTimerCount(); + const joiner = writeImmutableJson(bucket, 'own-timer.json', { ok: true }, 2_000); + let joinerSettled = false; + void joiner.then( + () => (joinerSettled = true), + () => (joinerSettled = true) ); - expect(bucket.put).toHaveBeenCalledTimes(1); + await waitFor(() => vi.getTimerCount() > timersBefore); + expect(joinerSettled).toBe(false); + finishPut?.({} as R2Object); - await new Promise((resolve) => setTimeout(resolve, 0)); - await expect( - writeImmutableJson(bucket, 'pending.json', { ok: true }, 50) - ).resolves.toBeUndefined(); + await expect(starter).resolves.toBeUndefined(); + await flush(); + // The PUT has settled and the starter answered, but the joiner has not resumed with it. + expect(joinerSettled).toBe(false); + + await vi.advanceTimersByTimeAsync(SHARED_FLIGHT_POLL_MS); + await flush(); + await expect(joiner).resolves.toBeUndefined(); expect(bucket.put).toHaveBeenCalledTimes(1); }); diff --git a/packages/worker-core/src/index.ts b/packages/worker-core/src/index.ts index 93875f269c..29df206cfd 100644 --- a/packages/worker-core/src/index.ts +++ b/packages/worker-core/src/index.ts @@ -104,4 +104,13 @@ export { type SearchQueryLimitEnv, type SearchQueryLimits, } from './search-query-limits'; +export { + __setSharedFlightResumeOnOwnTimerForTest, + DEFAULT_SHARED_FLIGHT_JOIN_GRACE_MS, + joinSharedFlight, + resumeSharedFlightJoinsOnOwnTimer, + settleSharedFlight, + SHARED_FLIGHT_POLL_MS, + SharedFlightAbandonedError, +} from './shared-flight'; export { ulid } from './ulid'; diff --git a/packages/worker-core/src/shared-flight.ts b/packages/worker-core/src/shared-flight.ts new file mode 100644 index 0000000000..6d37448758 --- /dev/null +++ b/packages/worker-core/src/shared-flight.ts @@ -0,0 +1,124 @@ +/** + * Joining a promise that another request started (a per-isolate "in-flight" cache entry). + * + * On Cloudflare a shared flight settles by its own deadline. On the self-hosted celld runtime + * (0.6.3) every async op (fetch, D1 call, setTimeout) belongs to the request that started it, and + * celld drops the op when that request's client disconnects: the flight never settles, and the + * deadline timer its starter set is dropped with it. A request that joined it would wait until + * its own client gave up or celld's 300 s handler budget ran out (task H2, the one-minute hangs + * on the self-host box). + * + * `joinSharedFlight` waits under a timer the JOINING request owns, until the flight's own + * deadline plus a grace, then reports the flight abandoned so the caller can start its own. A + * live flight always settles at its deadline, before this timer, so callers on Cloudflare see + * exactly the result they saw before. + * + * The joiner must also never RESUME on the flight's settlement. On celld the code that runs when + * a promise settles belongs to the request whose op settled it, so a joiner that simply awaited + * the flight continued as part of the starter's request: every D1 call, fetch and timer it made + * afterwards was dropped as soon as the starter answered, and the joiner hung with no abort + * anywhere (task R6 on the box: authenticated requests hung to the client cap after #2706). So + * on celld the flight's settlement only records the outcome, and the joiner wakes on its own short + * timer. + */ + +/** + * Margin past a flight's own deadline before the joiner gives up on it. Internal safety margin, + * not an operator setting: it only has to outlast the starter's own deadline timer. + */ +export const DEFAULT_SHARED_FLIGHT_JOIN_GRACE_MS = 1_000; + +/** + * How often a joiner checks whether the flight has settled. Internal, not an operator setting: it + * bounds the latency a joiner adds (only when it joins a read still in flight), and each check is + * one timer with no I/O. + */ +export const SHARED_FLIGHT_POLL_MS = 10; + +/** + * Whether a joiner resumes on its own timer instead of on the flight's settlement. Only the celld + * runtime needs it: the self-host build's generated celld entry module turns it on at startup, + * so Cloudflare keeps resuming joiners directly, with no added poll timer or latency. + */ +let resumeOnOwnTimer = false; + +/** Called once by the celld entry module, before any request runs. */ +export function resumeSharedFlightJoinsOnOwnTimer(): void { + resumeOnOwnTimer = true; +} + +/** Test seam: the mode the celld entry module selects, or back to the Cloudflare default. */ +export function __setSharedFlightResumeOnOwnTimerForTest(enabled: boolean): void { + resumeOnOwnTimer = enabled; +} + +/** The flight did not settle by its deadline: its starter's request is gone. Start your own. */ +export class SharedFlightAbandonedError extends Error { + constructor() { + super('A shared in-flight read did not settle by its deadline'); + this.name = 'SharedFlightAbandonedError'; + } +} + +/** + * `flight`'s result, or `SharedFlightAbandonedError` once `deadlineAt + graceMs` passes. + * `now` is the caller's clock for `deadlineAt`; the wait itself is a real timer. + */ +export async function joinSharedFlight( + flight: Promise, + deadlineAt: number, + now: number = Date.now(), + graceMs: number = DEFAULT_SHARED_FLIGHT_JOIN_GRACE_MS +): Promise { + const waitMs = Math.max(0, deadlineAt - now) + graceMs; + if (!resumeOnOwnTimer) return await raceOwnTimer(flight, waitMs); + const giveUpAt = Date.now() + waitMs; + const state: { outcome?: { ok: true; value: T } | { ok: false; error: unknown } } = {}; + // These callbacks run in the turn of whoever settles the flight. They only record the outcome: + // no I/O, no timers, no awaits, so nothing of the joiner's is created on the starter's behalf. + flight.then( + (value) => (state.outcome = { ok: true, value }), + (error: unknown) => (state.outcome = { ok: false, error }) + ); + // Yield exactly one microtask, still in this request's own turn: an already-settled flight's + // reaction above was queued first, so it has recorded the outcome before the loop and no timer + // is needed. (An already-resolved native promise, like `await null`, resumes after one tick.) + await Promise.resolve(); + while (!state.outcome) { + const remaining = giveUpAt - Date.now(); + if (remaining <= 0) throw new SharedFlightAbandonedError(); + // A timer this request owns: the code after it, and everything that code starts, is ours. + await new Promise((resume) => + setTimeout(resume, Math.min(SHARED_FLIGHT_POLL_MS, remaining)) + ); + } + if (state.outcome.ok) return state.outcome.value; + throw state.outcome.error; +} + +/** Cloudflare: the flight's settlement resumes the joiner; the joiner's timer only bounds it. */ +async function raceOwnTimer(flight: Promise, waitMs: number): Promise { + let timer: ReturnType | undefined; + const abandoned = new Promise((_, reject) => { + timer = setTimeout(() => reject(new SharedFlightAbandonedError()), waitMs); + }); + try { + return await Promise.race([flight, abandoned]); + } finally { + if (timer !== undefined) clearTimeout(timer); + } +} + +/** `joinSharedFlight` for callers that retry: `abandoned` instead of a thrown abandonment. */ +export async function settleSharedFlight( + flight: Promise, + deadlineAt: number, + now: number = Date.now() +): Promise<{ abandoned: true } | { abandoned: false; value: T }> { + try { + return { abandoned: false, value: await joinSharedFlight(flight, deadlineAt, now) }; + } catch (error) { + if (error instanceof SharedFlightAbandonedError) return { abandoned: true }; + throw error; + } +} diff --git a/scripts/quality/README.md b/scripts/quality/README.md index d13693a3f2..77c77e5379 100644 --- a/scripts/quality/README.md +++ b/scripts/quality/README.md @@ -55,6 +55,26 @@ download several runs' `workers-timings-*` artifacts and run the 2026-08-11 ai-slop debt burn-down, promoted after reaching 0 diagnostics), any new diagnostic fails the run with a nonzero exit code — no `--fail-on-findings` flag required. Other scopes remain advisory (exit 0 regardless of findings) until their own evidence is promoted. +- `pnpm quality:shared-flight-joins` (blocking in CI) fails when Worker code (`apps/api/src`, the + shared, providers and cloud-init packages, and the worker packages #2681 split out) resumes after another request's in-flight read + in any way other than `joinSharedFlight` / `settleSharedFlight` + (`packages/worker-core/src/shared-flight.ts`). On the self-hosted celld runtime such a promise never + settles once its starter's client disconnects, and a request that resumes on its settlement + runs as part of the starter's request and loses its later D1 calls, fetches and timers when + the starter answers; the helpers wait under the joiner's own timer. Resuming the joiner on that + timer is opt-in and off by default: only the self-host build's generated celld entry turns it on + (`resumeSharedFlightJoinsOnOwnTimer()`), so a deployment without that entry does not get it. Flagged: an `await`/`return` of the shared promise, a `.then`/`.catch`/`.finally` + on it (awaited or not), and handing it to any other function (a `Promise.race`, a timeout + wrapper). Shared state is module-scope state, or a field of a class with an instance held in + module scope (the admin-settings cache). Mark a reviewed exception with + `// shared-flight-join-allowed: ` on the line above. `--inventory` lists every + module-scope variable that holds a promise. It does not follow state reached through a + function parameter (a helper handed a shared entry object is trusted), iteration over a shared + collection, Durable Object fields (an object's ops survive one of its requests + answering on celld 0.6.3), `for await`, or a flight held inside a library (jose's JWKS fetch). + The parameter-reached sites (AdminSettingsCache, the LLM endpoint snapshot, compact-r2) have + behavioural abandonment tests instead + (`apps/api/tests/unit/services/shared-flight-abandonment.test.ts`). - `pnpm lint:oxlint` is report-only. Promotion is forbidden until `scripts/quality/lint-adoption-evidence.json` records finding, fix-diff, scope, template, suppression, and cold-performance parity. Type-aware Oxlint is disabled. diff --git a/scripts/quality/ast-checks.ts b/scripts/quality/ast-checks.ts index a20e610639..7d18cb45cc 100644 --- a/scripts/quality/ast-checks.ts +++ b/scripts/quality/ast-checks.ts @@ -388,6 +388,8 @@ function main() { resolve(ROOT, 'packages/app-deployment/src/**/*.ts'), resolve(ROOT, 'packages/operations/src/**/*.ts'), resolve(ROOT, 'packages/repo-hosting/src/**/*.ts'), + // The shared in-flight join helper lives in worker-core and runs in this Worker; keep its checks. + resolve(ROOT, 'packages/worker-core/src/shared-flight.ts'), resolve(ROOT, 'packages/cron/src/**/*.ts'), ]); } diff --git a/scripts/quality/check-shared-flight-joins.test.ts b/scripts/quality/check-shared-flight-joins.test.ts new file mode 100644 index 0000000000..20e5894179 --- /dev/null +++ b/scripts/quality/check-shared-flight-joins.test.ts @@ -0,0 +1,219 @@ +import { spawnSync } from 'node:child_process'; +import { mkdtempSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; + +import { Project } from 'ts-morph'; +import { describe, expect, it } from 'vitest'; + +import { + ALLOW_DIRECTIVE, + findSharedFlightJoins, + listModulePromiseHolders, +} from './check-shared-flight-joins'; + +function scan(code: string) { + const project = new Project({ + useInMemoryFileSystem: true, + compilerOptions: { target: 99, lib: ['lib.es2022.d.ts'], strict: true }, + }); + const file = project.createSourceFile('/src/flight.ts', code); + return { + findings: findSharedFlightJoins([file], '/'), + holders: listModulePromiseHolders([file], '/'), + }; +} + +const HELPER = ` +declare function settleSharedFlight(p: Promise, deadlineAt: number): Promise<{ abandoned: true } | { abandoned: false; value: T }>; +declare function read(): Promise; +`; + +describe('shared-flight join guard', () => { + it('flags the platform-config shape: an entry object in a module-scope `let`', () => { + const { findings, holders } = scan(`${HELPER} + let inFlight: { deadlineAt: number; promise: Promise } | null = null; + export async function resolve(): Promise { + const joinable = inFlight; + if (joinable) return await joinable.promise; + const promise = read(); + inFlight = { deadlineAt: Date.now() + 5000, promise }; + return await promise; + }`); + expect(findings).toEqual([ + expect.objectContaining({ + file: 'src/flight.ts', + root: 'inFlight', + code: 'joinable.promise', + }), + ]); + expect(holders.map((h) => h.name)).toEqual(['inFlight']); + }); + + it('flags a Map of promises joined through .get(), with and without await', () => { + const { findings } = scan(`${HELPER} + const pending = new Map>(); + export async function viaAwait(key: string) { + const hit = pending.get(key); + if (hit) await hit; + } + export function viaReturn(key: string): Promise | undefined { + return pending.get(key); + } + export async function viaRace(key: string) { + await Promise.race([pending.get(key)!, read()]); + } + export const viaArrow = async (key: string) => pending.get(key);`); + expect(findings.map((f) => f.code).sort()).toEqual([ + 'hit', + 'pending.get(key)', + 'pending.get(key)', + 'pending.get(key)!', + ]); + expect(findings.every((f) => f.root === 'pending')).toBe(true); + }); + + it('flags a destructured alias and a nested entry map', () => { + const { findings } = scan(`${HELPER} + const cache = new WeakMap }>>(); + export async function nested(db: object, key: string) { + const entry = cache.get(db)?.get(key); + if (!entry) return; + const { promise } = entry; + await promise; + }`); + expect(findings).toHaveLength(1); + expect(findings[0]?.root).toBe('cache'); + }); + + it('passes the sanctioned helper, a starter awaiting its own read, and non-promise state', () => { + const { findings } = scan(`${HELPER} + let inFlight: { deadlineAt: number; promise: Promise } | null = null; + let cached: { value: string } | null = null; + export async function resolve(): Promise { + if (cached) return cached.value; + const joinable = inFlight; + if (joinable) { + const joined = await settleSharedFlight(joinable.promise, joinable.deadlineAt); + if (!joined.abandoned) return joined.value; + } + const promise = read(); + const entry = { deadlineAt: Date.now() + 5000, promise }; + inFlight = entry; + const value = await entry.promise; + cached = { value }; + return value; + }`); + expect(findings).toEqual([]); + }); + + it('flags a module-held class instance joining its own flight field (the R6 shape)', () => { + // One instance in module scope serves every request in the isolate, so its fields are + // request-shared state: the admin-settings cache, where task R6's hangs were. + const { findings } = scan(`${HELPER} + class Cache { private flight?: Promise; async read() { return (this.flight ??= read()); } } + export const cache = new Cache(); + export async function use() { return await cache.read(); }`); + expect(findings).toEqual([expect.objectContaining({ root: 'this.flight', kind: 'awaits' })]); + }); + + it('does not treat fields of a class instantiated per call as shared', () => { + // Control for the case above: the same class, with no module-scope instance. + const { findings } = scan(`${HELPER} + class Cache { private flight?: Promise; async read() { return (this.flight ??= read()); } } + export async function use() { return await new Cache().read(); }`); + expect(findings).toEqual([]); + }); + + it('flags a continuation attached to a shared flight, awaited or not', () => { + // On celld the continuation runs as part of the request that settles the flight (task R6). + const { findings } = scan(`${HELPER} + const pending = new Map>(); + export function onSettle(key: string, record: (value: string) => void) { + pending.get(key)?.then(record); + } + export function onFailure(key: string) { + void pending.get(key)?.catch(() => undefined); + }`); + expect(findings.map((f) => f.kind)).toEqual(['continues', 'continues']); + expect(findings.every((f) => f.root === 'pending')).toBe(true); + }); + + it('flags a shared flight handed to a helper other than the sanctioned joins (the compact-r2 shape)', () => { + const { findings } = scan(`${HELPER} + declare function timed(p: Promise, deadline: number): Promise; + declare function joinSharedFlight(p: Promise, deadlineAt: number): Promise; + const pending = new Map }>(); + export async function viaTimed(key: string) { + const entry = pending.get(key); + if (entry) return timed(entry.promise, entry.deadlineAt); + } + export async function viaRace(key: string) { + const entry = pending.get(key); + if (entry) void Promise.race([entry.promise, read()]); + } + export async function sanctioned(key: string) { + const entry = pending.get(key); + if (entry) await joinSharedFlight(entry.promise, entry.deadlineAt); + if (entry) await settleSharedFlight(entry.promise, entry.deadlineAt); + }`); + expect(findings.map((f) => [f.kind, f.code])).toEqual([ + ['hands-off', 'entry.promise'], + ['hands-off', 'entry.promise'], + ]); + }); + + it('flags a shared flight behind a module-scope boolean in && and in a conditional', () => { + const { findings } = scan(`${HELPER} + let enabled = true; + const pending = new Map>(); + export async function viaAnd(key: string) { + return enabled && pending.get(key); + } + export async function viaConditional(key: string) { + return await (enabled ? pending.get(key) : undefined); + } + `); + // The `&&` return (line 8) and the awaited conditional (line 11), each rooted at `pending`. + expect( + findings.map((f) => [f.line, f.root]).sort((a, b) => Number(a[0]) - Number(b[0])) + ).toEqual([ + [8, 'pending'], + [11, 'pending'], + ]); + }); + + it('honours a reviewed exception on the line above', () => { + const { findings } = scan(`${HELPER} + const ready: Promise = read(); + export async function use() { + // ${ALLOW_DIRECTIVE} settles in the same turn on every runtime + return await ready; + }`); + expect(findings).toEqual([]); + }); +}); + +describe('shared-flight join guard CLI', () => { + const script = resolve(import.meta.dirname, 'check-shared-flight-joins.ts'); + const run = (code: string) => { + const file = join(mkdtempSync(join(tmpdir(), 'shared-flight-')), 'planted.ts'); + writeFileSync(file, code); + return spawnSync('npx', ['tsx', script, '--file', file], { encoding: 'utf8' }); + }; + + it('exits 1 and names the line for a planted violation, 0 for the sanctioned join', () => { + const planted = run(` + const pending = new Map>(); + export async function join(key: string) { return await pending.get(key); }`); + expect(planted.status, planted.stderr).toBe(1); + expect(planted.stderr).toMatch( + /planted\.ts:3 awaits a promise read from module-scope `pending`/ + ); + const clean = run(` + const cached = new Map(); + export async function read(key: string) { return cached.get(key); }`); + expect(clean.status, clean.stderr).toBe(0); + expect(clean.stdout).toMatch(/1 files, 0 finding\(s\)/); + }, 120_000); +}); diff --git a/scripts/quality/check-shared-flight-joins.ts b/scripts/quality/check-shared-flight-joins.ts new file mode 100644 index 0000000000..a95172d12d --- /dev/null +++ b/scripts/quality/check-shared-flight-joins.ts @@ -0,0 +1,546 @@ +/** + * Shared-flight join guard (`pnpm quality:shared-flight-joins`). + * + * Fails when Worker code awaits (or returns) a promise it reads out of module scope: a per-isolate + * "in-flight" cache entry that some OTHER request may have started. On the self-hosted celld + * runtime every async op belongs to the request that started it and is dropped when that + * request's client disconnects, so such a promise can never settle and every request that joined + * it hangs until its own client gives up or the 300 s handler budget runs out (task H2, + * packages/worker-core/src/shared-flight.ts, + * scripts/selfhost/live/shared-flight-cancel.live.test.ts). + * + * The sanctioned way to join another request's flight is `joinSharedFlight` / + * `settleSharedFlight`, which wait under a timer the JOINING request owns. Passing the flight to + * one of those is not an await of it, so it passes this check by construction. + * + * The helpers are also the only sanctioned way to RESUME after another request's flight. On celld + * the code that runs when a promise settles belongs to the request whose op settled it, so any + * continuation a joiner attaches to the flight (an await, a `.then`, a race inside some other + * helper) runs as part of the starter's request, and every D1 call, fetch or timer it makes is + * dropped when the starter answers (task R6). The helpers resume the joiner on its own timer. + * + * What counts as a violation, where X is promise-typed and X's root is shared state that holds a + * promise: + * - `await X`, `return X`, or an async-arrow body `X` (and the elements of an awaited + * `Promise.all/race/allSettled/any([...])`); + * - `X.then(...)`, `X.catch(...)`, `X.finally(...)`, awaited or not: a continuation on X; + * - X passed as an argument to any function other than `joinSharedFlight`/`settleSharedFlight`: + * a helper that awaits or races it resumes in the starter's turn just the same. + * Shared state is a module-scope variable, or a `this` field of a class with an instance held in + * module scope (the admin-settings cache, where R6's hangs were: one instance serves every request + * in the isolate). Fields of a Durable Object, or of a class only instantiated per request or per + * object, are not request-shared in this sense; on celld 0.6.3 an object's ops also survive one of + * its requests answering (task R7). Roots are traced + * through property and element access, `.get()/.at()/.find()/.then()/.catch()/.finally()`, + * `??`/`||`/`&&` and their assignment forms, and local aliases (`const pending = inFlight.get(id)`, + * `const { promise } = entry`). + * + * A reviewed exception carries `// shared-flight-join-allowed: ` on the line above. + * + * Usage: tsx scripts/quality/check-shared-flight-joins.ts [--inventory] [--json] [--file ...] + * --inventory also list every module-scope variable whose type holds a promise (the audit) + * --file check only these files (type-checked with the API's tsconfig) + * + * Not covered (state it in review instead): state reached through a function parameter (the + * admin-settings cache passes its per-binding state as one, and compact-r2 passes its pending entry + * to joinR2Operation), so a helper that receives a shared ENTRY object is trusted to join through + * the two helpers; iteration over a shared collection (`for (const e of flights.values())`, + * `.map`, spreads); fields declared in a base class or as constructor parameters; a class whose + * module-scope instance lives in another scanned project; `for await` over a shared promise; and + * a flight held inside a library (jose's `createRemoteJWKSet` keeps one pending JWKS fetch, but + * drops instead of joining it when it detects a Workers runtime, which celld reports itself as). + * The parameter-reached sites (AdminSettingsCache, the LLM endpoint snapshot, compact-r2) are + * covered by behavioural abandonment tests instead + * (apps/api/tests/unit/services/shared-flight-abandonment.test.ts, + * packages/project-data/tests/unit/project-data-compact-archive.test.ts). + */ +import { relative, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import { + type CallExpression, + type Node, + Project, + type SourceFile, + SyntaxKind, + ts, + type Type, + type VariableDeclaration, +} from 'ts-morph'; + +const ROOT = resolve(fileURLToPath(import.meta.url), '../../..'); + +/** Worker code: the API itself and the workspace packages it bundles. */ +export const SCANNED_PROJECTS = [ + { tsconfig: 'apps/api/tsconfig.json', glob: 'apps/api/src/**/*.ts' }, + { tsconfig: 'packages/shared/tsconfig.json', glob: 'packages/shared/src/**/*.ts' }, + { tsconfig: 'packages/providers/tsconfig.json', glob: 'packages/providers/src/**/*.ts' }, + { tsconfig: 'packages/cloud-init/tsconfig.json', glob: 'packages/cloud-init/src/**/*.ts' }, + // Worker modules the package split (#2681) moved out of apps/api/src; they still run in this + // Worker, so a join of another request's flight there hangs the same way on celld. + { tsconfig: 'packages/worker-core/tsconfig.json', glob: 'packages/worker-core/src/**/*.ts' }, + { + tsconfig: 'packages/scheduler-core/tsconfig.json', + glob: 'packages/scheduler-core/src/**/*.ts', + }, + { tsconfig: 'packages/project-data/tsconfig.json', glob: 'packages/project-data/src/**/*.ts' }, + { tsconfig: 'packages/operations/tsconfig.json', glob: 'packages/operations/src/**/*.ts' }, + { + tsconfig: 'packages/app-deployment/tsconfig.json', + glob: 'packages/app-deployment/src/**/*.ts', + }, + { tsconfig: 'packages/ai-proxy/tsconfig.json', glob: 'packages/ai-proxy/src/**/*.ts' }, + { tsconfig: 'packages/agent-email/tsconfig.json', glob: 'packages/agent-email/src/**/*.ts' }, + { tsconfig: 'packages/repo-hosting/tsconfig.json', glob: 'packages/repo-hosting/src/**/*.ts' }, +] as const; + +export const ALLOW_DIRECTIVE = 'shared-flight-join-allowed:'; +/** The sanctioned joins (worker-core shared-flight.ts): the joiner resumes on its own timer. */ +export const SANCTIONED_JOINS = new Set(['joinSharedFlight', 'settleSharedFlight']); +const CONTINUATIONS = new Set(['then', 'catch', 'finally']); +const TRACED_METHODS = new Set(['get', 'at', 'find', 'then', 'catch', 'finally']); +const COMBINATORS = new Set(['all', 'race', 'allSettled', 'any']); +const COLLECTIONS = new Set(['Map', 'WeakMap', 'Set', 'Array', 'ReadonlyMap', 'Promise']); + +/** How the code resumes after the shared flight. */ +export type SharedFlightJoinKind = 'awaits' | 'continues' | 'hands-off'; + +export interface SharedFlightFinding { + file: string; + line: number; + root: string; + code: string; + kind: SharedFlightJoinKind; +} + +export interface ModulePromiseHolder { + file: string; + line: number; + name: string; + type: string; +} + +function isThenable(type: Type, depth = 0): boolean { + if (depth > 3) return false; + if (type.isUnion()) return type.getUnionTypes().some((t) => isThenable(t, depth + 1)); + const then = type.getProperty('then'); + return Boolean(then); +} + +/** Whether a value of this type holds a promise anywhere a reader can reach it. */ +function holdsPromise(type: Type, seen = new Set(), depth = 0): boolean { + if (depth > 6 || seen.has(type)) return false; + seen.add(type); + if (type.isAny() || type.isUnknown()) return false; + if (isThenable(type)) return true; + if (type.isUnion() || type.isIntersection()) { + const parts = type.isUnion() ? type.getUnionTypes() : type.getIntersectionTypes(); + return parts.some((t) => holdsPromise(t, seen, depth + 1)); + } + if (type.getTypeArguments().some((t) => holdsPromise(t, seen, depth + 1))) return true; + const element = type.getArrayElementType(); + if (element && holdsPromise(element, seen, depth + 1)) return true; + if (!type.isObject() || type.getCallSignatures().length > 0) return false; + // Map/Set values and plain object fields (entry shapes like `{ deadlineAt; promise }`). + for (const symbol of type.getProperties()) { + const declaration = symbol.getValueDeclaration() ?? symbol.getDeclarations()[0]; + if (!declaration) continue; + if (holdsPromise(symbol.getTypeAtLocation(declaration), seen, depth + 1)) return true; + } + return false; +} + +function isModuleScopeVariable(node: Node): boolean { + if (!node.isKind(SyntaxKind.VariableDeclaration)) return false; + return node.getVariableStatement()?.getParent()?.isKind(SyntaxKind.SourceFile) ?? false; +} + +/** + * Classes with an instance held in module scope (`export const cache = new AdminSettingsCache()`): + * their fields are shared by every request in the isolate. Filled per scan by findSharedFlightJoins. + * A class only ever instantiated inside a request or a Durable Object is not request-shared. + */ +let moduleHeldClasses = new Set(); + +function collectModuleHeldClasses(sourceFiles: SourceFile[]): Set { + const held = new Set(); + for (const declaration of moduleVariableDeclarations(sourceFiles)) { + for (const node of classDeclarationsOf(declaration.getType())) held.add(node); + } + return held; +} + +/** Every module-scope variable declaration in these files, in source order. */ +function moduleVariableDeclarations(sourceFiles: SourceFile[]): VariableDeclaration[] { + return sourceFiles.flatMap((sourceFile) => + sourceFile.getVariableStatements().flatMap((statement) => statement.getDeclarations()) + ); +} + +/** The class declarations a value of this type (or any member of its union) is an instance of. */ +function classDeclarationsOf(type: Type): Node[] { + const parts = type.isUnion() ? type.getUnionTypes() : [type]; + return parts.flatMap((part) => + (part.getSymbol()?.getDeclarations() ?? []).filter((node) => + node.isKind(SyntaxKind.ClassDeclaration) + ) + ); +} + +/** `this.field` of a module-held class: the field's declaration, else undefined. */ +function sharedThisField(access: Node): Node | undefined { + if (!access.isKind(SyntaxKind.PropertyAccessExpression)) return undefined; + if (!access.getExpression().isKind(SyntaxKind.ThisKeyword)) return undefined; + const owner = access.getFirstAncestorByKind(SyntaxKind.ClassDeclaration); + if (!owner || !moduleHeldClasses.has(owner)) return undefined; + const declaration = access.getNameNode().getSymbol()?.getDeclarations()[0]; + return declaration?.isKind(SyntaxKind.PropertyDeclaration) ? declaration : undefined; +} + +export function rootName(root: Node): string { + if (root.isKind(SyntaxKind.VariableDeclaration)) return root.getName(); + if (root.isKind(SyntaxKind.PropertyDeclaration)) return `this.${root.getName()}`; + return root.getText(); +} + +/** Wrappers that do not change the value: parentheses, `as`, `!`, `satisfies`, `x`. */ +function unwrapped(expression: Node): Node | undefined { + if ( + expression.isKind(SyntaxKind.ParenthesizedExpression) || + expression.isKind(SyntaxKind.AsExpression) || + expression.isKind(SyntaxKind.NonNullExpression) || + expression.isKind(SyntaxKind.SatisfiesExpression) || + expression.isKind(SyntaxKind.TypeAssertionExpression) + ) { + return expression.getExpression(); + } + return undefined; +} + +/** Binary operators whose result may be one of their operands. */ +const TRACED_OPERATORS = new Set([ + SyntaxKind.QuestionQuestionToken, + SyntaxKind.BarBarToken, + SyntaxKind.AmpersandAmpersandToken, + SyntaxKind.QuestionQuestionEqualsToken, + SyntaxKind.BarBarEqualsToken, + SyntaxKind.AmpersandAmpersandEqualsToken, +]); + +/** The receiver of a traced method call (`x.get(...)`, `x.then(...)`), else none. */ +function tracedCallReceiver(call: CallExpression): Node[] { + const callee = call.getExpression(); + return callee.isKind(SyntaxKind.PropertyAccessExpression) && TRACED_METHODS.has(callee.getName()) + ? [callee.getExpression()] + : []; +} + +/** The sub-expressions a non-identifier's value may be read from, in the order to try them. */ +function tracedOperands(expression: Node): Node[] { + const inner = unwrapped(expression); + if (inner) return [inner]; + if ( + expression.isKind(SyntaxKind.PropertyAccessExpression) || + expression.isKind(SyntaxKind.ElementAccessExpression) + ) { + return [expression.getExpression()]; + } + if (expression.isKind(SyntaxKind.CallExpression)) return tracedCallReceiver(expression); + if (expression.isKind(SyntaxKind.ConditionalExpression)) { + return [expression.getWhenTrue(), expression.getWhenFalse()]; + } + if ( + expression.isKind(SyntaxKind.BinaryExpression) && + TRACED_OPERATORS.has(expression.getOperatorToken().getKind()) + ) { + return [expression.getLeft(), expression.getRight()]; + } + return []; +} + +/** The initializer a local alias reads from (`const x = ...`, `const { x } = ...`). */ +function aliasInitializer(declaration: Node): Node | undefined { + if (declaration.isKind(SyntaxKind.VariableDeclaration)) return declaration.getInitializer(); + if (declaration.isKind(SyntaxKind.BindingElement)) { + return declaration.getFirstAncestorByKind(SyntaxKind.VariableDeclaration)?.getInitializer(); + } + return undefined; +} + +/** An identifier's module-scope roots: the variable itself, or what its local alias reads. */ +function identifierRoots(identifier: Node, depth: number): Node[] { + const declaration = identifier.getSymbol()?.getDeclarations()[0]; + if (!declaration) return []; + if (isModuleScopeVariable(declaration)) return [declaration]; + const initializer = aliasInitializer(declaration); + return initializer ? moduleRoots(initializer, depth + 1) : []; +} + +/** + * Every module-scope variable a value may be read from, in the order to try them. A value can + * have several: `enabled && pending.get(key)` may be either operand, so a boolean on the left + * must not hide the shared promise on the right. Empty when the value is local, a parameter, + * `this` state, or a fresh call result. + */ +export function moduleRoots(expression: Node, depth = 0): Node[] { + if (depth > 12) return []; + if (expression.isKind(SyntaxKind.Identifier)) return identifierRoots(expression, depth); + const field = sharedThisField(expression); + if (field) return [field]; + return tracedOperands(expression).flatMap((operand) => moduleRoots(operand, depth + 1)); +} + +/** The first module-scope variable a value may be read from (see moduleRoots). */ +export function moduleRoot(expression: Node, depth = 0): Node | undefined { + return moduleRoots(expression, depth)[0]; +} + +function isAllowed(node: Node): boolean { + const sourceFile = node.getSourceFile(); + const line = node.getStartLineNumber(); + const previous = sourceFile.getFullText().split('\n')[line - 2] ?? ''; + return previous.includes(ALLOW_DIRECTIVE); +} + +/** The name of the function a call invokes (`f(...)`, `a.f(...)`), else undefined. */ +function calleeName(call: Node): string | undefined { + if (!call.isKind(SyntaxKind.CallExpression)) return undefined; + const callee = call.getExpression(); + if (callee.isKind(SyntaxKind.Identifier)) return callee.getText(); + if (callee.isKind(SyntaxKind.PropertyAccessExpression)) return callee.getName(); + return undefined; +} + +type Resumption = { node: Node; kind: SharedFlightJoinKind }; + +/** The elements of `Promise.all/race/allSettled/any([...])`, else none. */ +function combinatorElements(operand: Node): Node[] { + if (!operand.isKind(SyntaxKind.CallExpression)) return []; + const callee = operand.getExpression(); + const isCombinator = + callee.isKind(SyntaxKind.PropertyAccessExpression) && + callee.getExpression().getText() === 'Promise' && + COMBINATORS.has(callee.getName()); + const list = isCombinator ? operand.getArguments()[0] : undefined; + return list?.isKind(SyntaxKind.ArrayLiteralExpression) ? list.getElements() : []; +} + +/** Operands the code awaits: `await X`, `return X`, and an async-arrow body `X`, in that order. */ +function awaitedOperands(sourceFile: SourceFile): Node[] { + const operands: Array = [ + ...sourceFile + .getDescendantsOfKind(SyntaxKind.AwaitExpression) + .map((node) => node.getExpression()), + ...sourceFile + .getDescendantsOfKind(SyntaxKind.ReturnStatement) + .map((node) => node.getExpression()), + ...sourceFile + .getDescendantsOfKind(SyntaxKind.ArrowFunction) + .map((arrow) => arrow.getBody()) + .filter((body) => !body.isKind(SyntaxKind.Block)), + ]; + return operands.filter((operand): operand is Node => operand !== undefined); +} + +/** What a call resumes on: `X.then/catch/finally(...)`, and every argument it is handed. */ +function callResumptions(call: CallExpression): Resumption[] { + const out: Resumption[] = []; + const callee = call.getExpression(); + if (callee.isKind(SyntaxKind.PropertyAccessExpression) && CONTINUATIONS.has(callee.getName())) { + out.push({ node: callee.getExpression(), kind: 'continues' }); + } + // `Promise.race([X, ...])` that is not awaited directly still resumes on X. + const name = calleeName(call); + if (name && SANCTIONED_JOINS.has(name)) return out; + for (const argument of call.getArguments()) { + const handed = argument.isKind(SyntaxKind.ArrayLiteralExpression) + ? argument.getElements() + : [argument]; + for (const node of handed) out.push({ node, kind: 'hands-off' }); + } + return out; +} + +/** Expressions whose settlement the enclosing code resumes on, and how. */ +function resumptions(sourceFile: SourceFile): Resumption[] { + const awaited = awaitedOperands(sourceFile) + .flatMap((operand) => [operand, ...combinatorElements(operand)]) + .map((node): Resumption => ({ node, kind: 'awaits' })); + const handed = sourceFile + .getDescendantsOfKind(SyntaxKind.CallExpression) + .flatMap((call) => callResumptions(call)); + return [...awaited, ...handed]; +} + +/** Whether the root holds a promise, computed once per root across the scan. */ +function rootHoldsPromise(cache: Map, rootDeclaration: Node): boolean { + let holds = cache.get(rootDeclaration); + if (holds === undefined) { + holds = holdsPromise(rootDeclaration.getType()); + cache.set(rootDeclaration, holds); + } + return holds; +} + +/** Whether the expression's own type may be a promise (thenable, `any` or `unknown`). */ +function mayBePromise(expression: Node): boolean { + const type = expression.getType(); + return isThenable(type) || type.isAny() || type.isUnknown(); +} + +function fileFindings( + sourceFile: SourceFile, + holderCache: Map, + root: string +): SharedFlightFinding[] { + const findings: SharedFlightFinding[] = []; + // One finding per line and root: `await X.then(...)` both awaits and continues. + const seen = new Set(); + for (const { node: expression, kind } of resumptions(sourceFile)) { + const rootDeclaration = moduleRoots(expression).find((candidate) => + rootHoldsPromise(holderCache, candidate) + ); + if (!rootDeclaration) continue; + if (!mayBePromise(expression)) continue; + const key = `${expression.getStartLineNumber()}:${rootName(rootDeclaration)}`; + if (seen.has(key)) continue; + seen.add(key); + if (isAllowed(expression)) continue; + findings.push({ + file: relative(root, sourceFile.getFilePath()), + line: expression.getStartLineNumber(), + root: rootName(rootDeclaration), + code: expression.getText().split('\n')[0] ?? '', + kind, + }); + } + return findings; +} + +export function findSharedFlightJoins( + sourceFiles: SourceFile[], + root = ROOT +): SharedFlightFinding[] { + const holderCache = new Map(); + moduleHeldClasses = collectModuleHeldClasses(sourceFiles); + return sourceFiles.flatMap((sourceFile) => fileFindings(sourceFile, holderCache, root)); +} + +/** A module-scope function or class is not state, whatever it returns. */ +function isCallable(type: Type): boolean { + return type.getCallSignatures().length > 0 || type.getConstructSignatures().length > 0; +} + +/** Library objects (a Hono app, a logger) are not request-shared flights SAM wrote. */ +function isLibraryObject(type: Type): boolean { + const symbol = type.getSymbol() ?? type.getAliasSymbol(); + const declaredIn = symbol?.getDeclarations()[0]; + return ( + Boolean(declaredIn?.getSourceFile().isInNodeModules()) && + !COLLECTIONS.has(symbol?.getName() ?? '') + ); +} + +export function listModulePromiseHolders( + sourceFiles: SourceFile[], + root = ROOT +): ModulePromiseHolder[] { + const out: ModulePromiseHolder[] = []; + for (const declaration of moduleVariableDeclarations(sourceFiles)) { + const type = declaration.getType(); + if (isCallable(type) || isLibraryObject(type) || !holdsPromise(type)) continue; + out.push({ + file: relative(root, declaration.getSourceFile().getFilePath()), + line: declaration.getStartLineNumber(), + name: declaration.getName(), + type: type.getText(declaration, ts.TypeFormatFlags.NoTruncation).slice(0, 160), + }); + } + return out; +} + +export function describeFinding(finding: Pick): string { + const from = `${finding.root.startsWith('this.') ? 'shared field' : 'module-scope'} \`${finding.root}\``; + if (finding.kind === 'continues') return `attaches a continuation to a promise read from ${from}`; + if (finding.kind === 'hands-off') return `hands a promise read from ${from} to another function`; + return `awaits a promise read from ${from}`; +} + +function loadProject(tsconfig: string, glob: string): SourceFile[] { + const project = new Project({ + tsConfigFilePath: resolve(ROOT, tsconfig), + skipAddingFilesFromTsConfig: true, + }); + return project.addSourceFilesAtPaths([ + resolve(ROOT, glob), + `!${resolve(ROOT, '**/*.test.ts')}`, + `!${resolve(ROOT, 'apps/api/src/vendor/**')}`, + ]); +} + +function explicitFiles(argv: string[]): string[] { + return argv.flatMap((arg, index) => (argv[index - 1] === '--file' ? [resolve(arg)] : [])); +} + +interface ScanResult { + scanned: number; + findings: SharedFlightFinding[]; + holders: ModulePromiseHolder[]; +} + +/** `--file`: only these files, type-checked with the API's tsconfig (no inventory). */ +function scanExplicitFiles(paths: string[]): ScanResult { + const project = new Project({ + tsConfigFilePath: resolve(ROOT, SCANNED_PROJECTS[0].tsconfig), + skipAddingFilesFromTsConfig: true, + }); + const files = paths.map((path) => project.addSourceFileAtPath(path)); + return { scanned: files.length, findings: findSharedFlightJoins(files), holders: [] }; +} + +function scanAllProjects(inventory: boolean): ScanResult { + const result: ScanResult = { scanned: 0, findings: [], holders: [] }; + for (const { tsconfig, glob } of SCANNED_PROJECTS) { + const files = loadProject(tsconfig, glob); + result.scanned += files.length; + result.findings.push(...findSharedFlightJoins(files)); + if (inventory) result.holders.push(...listModulePromiseHolders(files)); + } + return result; +} + +function printReport({ scanned, findings, holders }: ScanResult, args: Set): void { + if (args.has('--json')) { + console.log(JSON.stringify({ scanned, findings, holders }, null, 2)); + return; + } + if (args.has('--inventory')) { + console.log('Module-scope state that holds a promise:'); + for (const h of holders) console.log(` ${h.file}:${h.line} ${h.name}: ${h.type}`); + } + for (const f of findings) { + console.error( + `✗ ${f.file}:${f.line} ${describeFinding(f)}: ${f.code}\n` + + ' Join another request’s flight with joinSharedFlight/settleSharedFlight ' + + '(packages/worker-core/src/shared-flight.ts).' + ); + } + console.log(`shared-flight-joins: ${scanned} files, ${findings.length} finding(s)`); +} + +function main(): void { + const argv = process.argv.slice(2); + const args = new Set(argv); + const only = explicitFiles(argv); + const result = + only.length > 0 ? scanExplicitFiles(only) : scanAllProjects(args.has('--inventory')); + // A full scan that read almost nothing would report "all clear"; refuse that (rule 02). + if (only.length === 0 && result.scanned < 500) { + console.error(`shared-flight-joins: scanned only ${result.scanned} files; the glob is broken`); + process.exit(1); + } + printReport(result, args); + process.exit(result.findings.length > 0 ? 1 : 0); +} + +if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) main(); diff --git a/tasks/active/2026-11-19-l22-selfhost-core-packaging.md b/tasks/active/2026-11-19-l22-selfhost-core-packaging.md new file mode 100644 index 0000000000..c25eabebb6 --- /dev/null +++ b/tasks/active/2026-11-19-l22-selfhost-core-packaging.md @@ -0,0 +1,79 @@ +# L22: self-host core packaging (land from sam/selfhost-pass-2 in 3 PRs) + +Task `01M7RPE328YRAM3RBA67Q3Z8N0`. Landing plan: idea `01M72M9AEB933ZY8269D376DKC` (part 6, row L22). +Coordination channel: `feature.selfhost-landing`. Integration tip at start: `2f61cea9a`. + +## Problem + +The self-host (celld, single VM) packaging lives only on the integration branch. L22 lands its core +on main in three PRs, each cut from main with `git restore --source=origin/sam/selfhost-pass-2` +and trimmed. Nothing in L22 may change Cloudflare behaviour. + +## Research findings + +- `scripts/selfhost/deploy.ts` imports the egress fence (L23), key agent / sealed secrets (held), + guided login and docker-proxy (held). The L22 copy must drop those and run legacy-plaintext only. +- `upgrade.ts` imports `backup-cli` (L24). L22's upgrade has no automatic backup step. +- The hosted-git "local backend" (`services/hosted-git/local-backend.ts`) is the HostedGitRepo + Durable Object (D7, held), so no L22 PR adds `isLocalHostedGitActive` to Worker files (M4 HIGH-4). +- `durable-objects/sandbox-do.ts` exists for guided-login containers only (held), so main's + `index.ts` keeps exporting the SDK `Sandbox` (M4 HIGH-1). +- `SELFHOST_DURABLE_OBJECTS` holds only HostedGitRepo, so the L22 celld entry mounts no + self-host-only class or route, and `apps/api/src/app.ts` is not needed. +- F25 (GET /api/credentials/agent hung 300 s on a cold isolate) is the shared-flight join + problem: celld drops a request's ops when its client disconnects, and a per-isolate shared + promise then never settles. The fix is Worker-loaded (`packages/worker-core/src/shared-flight.ts` + and its call sites), so it gets its own staging-verified PR. +- F21 Caddy items (PR #2625 security notes L1, L4, L5, L6, L7): double-encoding, `port_range_cooling_down` + transient classification, .env-only port check, broad 404 matcher, Login rate limit on `/~!frp`. +- F11 (#2666): image build runs unfenced on every compose build. +- M5 carry-over: an `s3://` operator store needs `R2_S3_REGION`; the operator docs must say so. +- D9: the Docker live suite runs only on self-host paths in CI, not on the cloud-init filter. + +## PR split + +### PR 1 (L22a): shared-flight joins for celld (F25), Worker-loaded + +- [x] `packages/worker-core/src/shared-flight.ts` + `apps/api/src/lib/shared-flight.ts` re-export +- [x] Bounded joins: admin-settings-cache, admin-settings-resolution, llm-endpoint-snapshot, + platform-config-core, project-data `compact-r2`; reviewed allow markers in range-report +- [x] Unrelated OAuth `validStoredValue` hunk trimmed out +- [x] `pnpm quality:shared-flight-joins` check + tests, wired into CI and ast-checks scope +- [x] Discrimination, one surgical revert per site, each turning only its own cases red: + platform-config-core (main), AdminSettingsCache and LLM snapshot (plain await), the + platform-config attempt cap (raised to 99), compact-r2 (main: the celld own-timer test) +- [x] Full lint / typecheck / test (41/41 tasks; API 17,686 passed) +- [x] Reviews: security-auditor PASS, architecture-reviewer ADDRESSED, cloudflare-specialist PASS, + task-completion-validator ADDRESSED +- [x] Deferred MEDIUM (rule 42): compact-r2 does not evict an abandoned R2 operation on celld, + tracked in tasks/backlog/2026-11-19-compact-r2-celld-abandoned-op-eviction.md +- [ ] Staging smoke on primary (settings, platform config, agent credential path) +- [ ] Merge, Deploy Production success + +### PR 2 (L22b): celld build and deploy core (self-host only) + +- [ ] celld-binary, celld-config (trimmed), celld-project (plain entry only), celld-adopt +- [ ] deploy, deploy-steps, deploy-harness, box-settings, mail/inbound-mail settings, + install-record, secret-files, versions, vm-agent-artifacts, platform-probe +- [ ] create-account (with the #2888 F13c owner guard) + account-sql +- [ ] upgrade + upgrade-lib without the L24 backup step +- [ ] `apps/api/src/selfhost/build.ts` (celld entry only) + import-graph test +- [ ] `selfhost:*` scripts, scripts/selfhost tsconfig and vitest config, unit tests in CI + +### PR 3 (L22c): box runtime (self-host only) + +- [ ] deploy/selfhost compose (no key-agent, fence, docker-proxy, metadata-proxy), Caddy with the + F21 fixes, frps, celld/start.sh, objectstore, .env.example, gcp-bootstrap.sh +- [ ] F11 fix +- [ ] Docker live tests + CI job on self-host paths only (D9) +- [ ] Operator README marked experimental, including R2_S3_REGION for s3:// +- [ ] BOX: fresh teardown + rebuild from this head; prove 0255 lease table on a fresh box; + L19 celld teardown OWED (guided login not installed); L13 metered ceiling only if a platform + AI key exists + +## Acceptance criteria + +- Cloudflare Worker import graph unchanged by PRs 2-3; Worker behaviour unchanged except the + bounded joins in PR 1. +- A box installed from main alone deploys, serves the app, creates an admin by email, runs one + agent session and heartbeats a reverse-tunnel node. diff --git a/tasks/backlog/2026-11-19-compact-r2-celld-abandoned-op-eviction.md b/tasks/backlog/2026-11-19-compact-r2-celld-abandoned-op-eviction.md new file mode 100644 index 0000000000..51c47a466e --- /dev/null +++ b/tasks/backlog/2026-11-19-compact-r2-celld-abandoned-op-eviction.md @@ -0,0 +1,24 @@ +# compact-r2: an abandoned R2 operation blocks its key until the celld isolate retires + +## Problem + +`packages/project-data/src/archive/compact-r2.ts` keeps one provider operation in flight per +bucket/key (`timedR2`), and joiners wait through `joinR2Operation`. On the self-hosted celld +runtime, an operation whose starter request was dropped never settles, and its `.finally` cleanup +never runs. The entry stays in `pendingR2Operations`, so every later operation on that key fails +with `CompactArchiveTimeoutError` until the isolate is retired, which on a long-lived celld process +means until restart. On Cloudflare a provider operation always settles, so this cannot happen there. + +Found by the security-auditor and architecture-reviewer on PR #2901 (L22a), MEDIUM. Deferred +because the behaviour is unchanged from main and from the integration branch the self-host box has +run for days. The compact archive runs from Durable Objects (whose ops survive on celld 0.6.3) and +from the cron sweep (no client to disconnect), so the dropped-starter case is not known to occur. + +## Acceptance criteria + +- [ ] Record `startedAt` on `PendingR2Operation`. Let a new caller replace an entry older than a + bound derived from the archive R2 deadline plus a margin, only when the celld resume mode is + on, so Cloudflare behaviour stays byte-identical. +- [ ] Confirm a re-issued PUT on the immutable content-addressed key is safe (identical bytes, + reads verify `bodySha256`), or keep the refusal and surface the stuck key in a log/metric. +- [ ] Test: a pending entry older than the bound is replaced on celld and still refused on Cloudflare.