Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
14 changes: 14 additions & 0 deletions apps/api/src/lib/shared-flight.ts
Original file line number Diff line number Diff line change
@@ -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';
12 changes: 10 additions & 2 deletions apps/api/src/services/admin-settings-cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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;
Expand All @@ -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;
Expand Down
12 changes: 10 additions & 2 deletions apps/api/src/services/admin-settings-resolution.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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))
Expand Down Expand Up @@ -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 ||
Expand Down
3 changes: 3 additions & 0 deletions apps/api/src/services/lifecycle-latency/range-report.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,12 @@ function watchSignatures(watch: LifecycleWatch): Promise<string[]> {
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;
}

Expand Down
50 changes: 38 additions & 12 deletions apps/api/src/services/llm-endpoint-snapshot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -30,7 +31,13 @@ type Snapshot = {
rows: v.InferOutput<typeof overrideSchema>[];
credentials: v.InferOutput<typeof credentialSchema>[];
};
type Entry = { generation: number; expiresAt: number; promise: Promise<Snapshot> };
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<Snapshot>;
};
const snapshots = new WeakMap<D1Database, Entry>();

async function load(env: Env, db: D1Database): Promise<Snapshot> {
Expand Down Expand Up @@ -76,22 +83,41 @@ async function load(env: Env, db: D1Database): Promise<Snapshot> {
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)
Expand All @@ -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;
}
Expand Down
47 changes: 41 additions & 6 deletions apps/api/src/services/platform-config-core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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<ResolvedPlatformConfig> {
// 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
Expand Down Expand Up @@ -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;
}

Expand All @@ -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) {
Expand Down
116 changes: 116 additions & 0 deletions apps/api/tests/unit/lib/shared-flight.test.ts
Original file line number Diff line number Diff line change
@@ -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<never>(() => 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<string>((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<string>((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);
});
});
Loading
Loading