Skip to content
Open
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
14 changes: 14 additions & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -997,6 +997,13 @@ export type ProxyOptions = {
injectTool: boolean;
injectNudge: boolean;
};
/** #5930: the configFileEpoch() generation the compress/routes/namedProviders
* layers above were resolved from — captured once per loadOptions / web Apply /
* reload. storeEffectiveConfig stamps THIS onto session snapshots (not the live
* hash at store time), so the #2960⑥ stale-stamp guard fires as soon as the file
* moves past the generation the snapshot was actually built from. Optional so
* inline test fixtures (which never exercise the guard) stay terse. */
configSourceEpoch?: string;
promptCache: { routing: PromptCacheRouting };
/** Wire-compat role map (global level; per-provider `compat.roles` overlays
* it per key). `{"developer":"system"}` rewrites developer→system on the
Expand Down Expand Up @@ -1658,6 +1665,12 @@ export function loadOptions(env: NodeJS.ProcessEnv = process.env): ProxyOptions
// The canonical, user-editable config. Loaded first so env vars below can
// override it (env wins for environment-specific overrides).
const fileConfig = loadConfigFile();
// #5930: identity of the file generation these options were resolved from.
// Captured HERE (not at session-store time): every layer below is built from
// this same read, and sessions must be stamped with this generation — stamping
// the live hash at store time let a direct edit between refresh and request
// mint a fresh-looking stamp onto a pre-edit snapshot (#2960⑥ guard defeated).
const configSourceEpoch = configFileEpoch();

// #4899: parse + publish the billing price overrides here so every reload
// path (startup, web Apply onChanged, /__bili/config reload) funnels
Expand Down Expand Up @@ -1788,6 +1801,7 @@ export function loadOptions(env: NodeJS.ProcessEnv = process.env): ProxyOptions
injectTool: (env.ACP_COMPRESS_TOOL ?? (fileConfig.compress?.injectTool === false ? "0" : "1")) !== "0",
injectNudge: (env.ACP_COMPRESS_NUDGE ?? (fileConfig.compress?.injectNudge === false ? "0" : "1")) !== "0",
},
configSourceEpoch,
promptCache: {
routing: parsePromptCacheRouting(env.ACP_PROMPT_CACHE_ROUTING ?? fileConfig.promptCache?.routing),
},
Expand Down
2 changes: 1 addition & 1 deletion src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ import { prepareResponses, prepareResponsesCompact } from "./server/prepare-resp
import { FORCE_TEXT_PROTOCOL } from "./server/inject.js";
export { isChatGptCodexUpstream, isCodexResponsesLite, resolvePromptCacheKey, shouldInjectPromptCacheKey } from "./server/prepare-responses.js";
import { biliToolsDeclaredOnWire, countBiliToolUses, evaluateSelfHealRound, nudgeSuppressed, pluginLaneDegraded, pluginLaneRestore } from "./session-self-heal.js";
import { getSession, hasProcessedState, listSessions, peekSession, type PendingRetrieval, type Session, type NudgeStamps, initSessions, markDirty, flushAllSessions, acquireInFlight, releaseInFlight, totalInFlight, snapshotMessages, ensureCanonicalId, storeEffectiveConfig, foldCoverage, postRebuildAnchorTokens, setPostRebuildAnchor, tickPostRebuildAnchor, splitSessionWarnings, usageAnchorCycleStale, staleSmallAnchorFallback } from "./session.js";
import { getSession, hasProcessedState, listSessions, peekSession, type PendingRetrieval, type Session, type NudgeStamps, initSessions, markDirty, flushAllSessions, acquireInFlight, releaseInFlight, totalInFlight, snapshotMessages, ensureCanonicalId, foldCoverage, postRebuildAnchorTokens, setPostRebuildAnchor, tickPostRebuildAnchor, splitSessionWarnings, usageAnchorCycleStale, staleSmallAnchorFallback } from "./session.js";
import type { SeparatorManifest } from "./server/responses-ordering.js";
import { detectStaleInstall, isVersionNewer } from "./update.js";
import { decideEaddrinuse, eaddrinuseExitCode, isPortBusyError, postBindCanLadder, UPGRADE_REPLACEMENT_ENV, type FailFastReason } from "./listen-policy.js";
Expand Down
4 changes: 4 additions & 0 deletions src/server/admin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -428,6 +428,8 @@ export async function handleAdminRoute(req: http.IncomingMessage, res: http.Serv
opts.auxProxyFallback = fresh.auxProxyFallback;
opts.compress = fresh.compress;
opts.compat = fresh.compat;
// #5930: the applied file generation travels with the options it was read from.
opts.configSourceEpoch = fresh.configSourceEpoch;
// #5079: routing must hot-apply too — the web switch changes it live.
opts.promptCache = fresh.promptCache;
resetProxyCache();
Expand Down Expand Up @@ -930,6 +932,8 @@ function handleConfigReload(opts: ProxyOptions, res: http.ServerResponse, log: (
const reloaded = loadOptions();
opts.compress = reloaded.compress;
opts.compat = reloaded.compat;
// #5930: the reloaded file generation travels with the options it was read from.
opts.configSourceEpoch = reloaded.configSourceEpoch;
opts.imageBilling = reloaded.imageBilling;
opts.imageTokenCap = reloaded.imageTokenCap;
// #6003 phase 2: egress transforms are file-only, so pull them off the fresh
Expand Down
2 changes: 1 addition & 1 deletion src/server/handle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2954,7 +2954,7 @@ async function handleRequest(
// turn's reqConfig so processTurn protects the carriers now.
// effectiveConfig() re-resolves both from the lane id at read time, so
// /__bili/plugin/tool sees them too.
storeEffectiveConfig(session, reqConfig);
storeEffectiveConfig(session, reqConfig, opts.configSourceEpoch);
const durableClassifier = pluginAgent ? durableMessageToolPaths[pluginAgent] : undefined;
if (durableClassifier !== undefined) reqConfig = withDurableProtection(reqConfig, durableClassifier);
// acquireInFlight must precede the lock so evictOldest() cannot flush
Expand Down
20 changes: 16 additions & 4 deletions src/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -807,7 +807,7 @@ type AnonymousPrefixAffinityStamp = {
// FORK_FAILED). Function fields are re-resolved at read time: effectiveConfig()
// merges over the base kernelConfig, which carries them again (isToolProtected
// #2578; isMessageProtected re-resolves from the lane id below).
export function storeEffectiveConfig(session: Session, config: Config): void {
export function storeEffectiveConfig(session: Session, config: Config, sourceEpoch?: string): void {
const cloneSafe: Record<string, unknown> = { ...config };
for (const key of Object.keys(cloneSafe)) {
if (typeof cloneSafe[key] === "function") delete cloneSafe[key];
Expand All @@ -816,15 +816,27 @@ export function storeEffectiveConfig(session: Session, config: Config): void {
// #2960⑥: identity of the config source this snapshot was resolved from.
// effectiveConfig() refuses the snapshot when the source has moved on
// (file edited, different BILI_CONFIG_FILE lane) — see the reader below.
session.metadata["effectiveConfigEpoch"] = configFileEpoch();
// #5930: callers pass the epoch of the generation the snapshot was ACTUALLY
// resolved from (opts.configSourceEpoch, captured where options loaded) —
// never the live hash at store time: a direct file edit between the options
// refresh and this request used to mint a fresh stamp onto a pre-edit
// snapshot, so the guard could never fire until a reload/restart. Unknown
// source identity (no epoch passed) stamps nothing — such snapshots keep
// the legacy behavior rather than claiming a freshness they cannot prove.
if (typeof sourceEpoch === "string" && sourceEpoch.length > 0) {
session.metadata["effectiveConfigEpoch"] = sourceEpoch;
}
}

/** True when the session's effectiveConfig stamp was resolved from a config
* source that no longer matches the live file (file edited since the last
* wire request, or a different lane's file whose content diverged — the
* epoch is a content hash, so byte-identical files validate across
* instances). Stamps without an epoch predate the guard and keep the legacy
* behavior (stamp wins). */
* instances). #5930: the stamp is the options-generation the snapshot was
* built from (captured at loadOptions / Apply / reload time), so a direct
* file edit goes stale even though no request re-resolved anything. Stamps
* without an epoch predate the guard and keep the legacy behavior
* (stamp wins). */
function staleEffectiveStamp(session: Session | undefined): boolean {
const stamped = session?.metadata?.["effectiveConfigEpoch"];
return typeof stamped === "string" && stamped !== configFileEpoch();
Expand Down
54 changes: 48 additions & 6 deletions tests/config-epoch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import path from "node:path";
import test from "node:test";
import { defaultConfig, createInitialState, type Config } from "acp-kernel";
import { effectiveConfig, storeEffectiveConfig, type Session } from "../src/session.js";
import { configFileEpoch, loadOptions } from "../src/config.js";
import { resolveRequestConfig } from "../src/compress-settings.js";
import { externalSummaryEnabled } from "../src/external-summary-surface.js";

// #3430: the effectiveConfig stamp is only valid while the config SOURCE it was
Expand All @@ -13,7 +15,10 @@ import { externalSummaryEnabled } from "../src/external-summary-surface.js";
// lane → the stamp is refused and the live file tier is re-resolved onto the
// fallback, so a retired setting (the October externalSummary incident: a
// user-disabled summary chain kept executing off one old stamp) can never ride
// a stale snapshot again.
// a stale snapshot again. #5930 moved stamp capture from store-time to
// source-load-time: stamps now carry the configFileEpoch() generation the
// options were loaded from, so a direct file edit goes stale even when no
// request has re-resolved anything since.

function makeSession(): Session {
return { id: "cfg-epoch-s1", metadata: {}, stats: {}, state: createInitialState() } as unknown as Session;
Expand All @@ -30,9 +35,10 @@ test("config epoch: same-source stamp still wins (merge semantics unchanged)", (
process.env.BILI_CONFIG_FILE = file;
try {
const session = makeSession();
const epoch = configFileEpoch(); // the generation these options were loaded from
const stamped = defaultConfig(200_000);
stamped.modelContextLimit = 123_456; // a request-cascade override worth keeping
storeEffectiveConfig(session, stamped);
storeEffectiveConfig(session, stamped, epoch);
const read = effectiveConfig(session, defaultConfig(200_000));
assert.equal(read.modelContextLimit, 123_456, "live stamp must win over the fallback");
} finally {
Expand All @@ -48,9 +54,10 @@ test("config epoch: edited file refuses the stamp and re-resolves the live compr
process.env.BILI_CONFIG_FILE = file;
try {
const session = makeSession();
const epoch = configFileEpoch();
const stamped = defaultConfig(200_000);
stamped.modelContextLimit = 123_456;
storeEffectiveConfig(session, stamped);
storeEffectiveConfig(session, stamped, epoch);
// The user edits the file AFTER the stamp: new window, new knob.
writeFileSync(file, JSON.stringify({ compress: { modelContextLimit: 777_000, nudgeGrowthTokens: 512 } }));
const read = effectiveConfig(session, defaultConfig(200_000));
Expand All @@ -71,7 +78,7 @@ test("config epoch: a retired externalSummary chain cannot ride a stale stamp (t
const session = makeSession();
const stamped = defaultConfig(200_000) as Config & { externalSummary?: { enabled: boolean } };
stamped.externalSummary = { enabled: true };
storeEffectiveConfig(session, stamped);
storeEffectiveConfig(session, stamped, configFileEpoch());
assert.equal(externalSummaryEnabled(effectiveConfig(session, defaultConfig(200_000))), true, "precondition: chain on while the file still declares it");
// The user deletes the chain from the file, but the session never sees
// another wire request on this instance.
Expand All @@ -94,7 +101,10 @@ test("config epoch: a live externalSummary chain survives the stale window with
const session = makeSession();
const stamped = defaultConfig(200_000) as Config & { externalSummary?: { enabled: boolean } };
stamped.externalSummary = { enabled: true };
storeEffectiveConfig(session, stamped);
// #5930: pass the source generation explicitly — under the new contract a
// missing epoch stamps nothing (legacy stamp-wins), so the stale-window
// path this test pins needs a real generation to go stale against.
storeEffectiveConfig(session, stamped, configFileEpoch());
assert.equal(externalSummaryEnabled(effectiveConfig(session, defaultConfig(200_000))), true, "precondition: chain on while the file still declares it");
// Any other edit moves the epoch into the stale-overlay window; the
// provider table and the chain itself are untouched.
Expand All @@ -120,9 +130,10 @@ test("config epoch: byte-identical files at different paths are the same source
process.env.BILI_CONFIG_FILE = fileA;
try {
const session = makeSession();
const epoch = configFileEpoch();
const stamped = defaultConfig(200_000);
stamped.modelContextLimit = 123_456;
storeEffectiveConfig(session, stamped);
storeEffectiveConfig(session, stamped, epoch);
// A second instance resolving the SAME bytes under a different lane
// path: identical file tier → the stamp is still a valid resolution.
process.env.BILI_CONFIG_FILE = fileB;
Expand Down Expand Up @@ -157,3 +168,34 @@ test("config epoch: stamps without an epoch keep the legacy behavior (stamp wins
rmSync(dir, { recursive: true, force: true });
}
});

test("config epoch #5930: a direct file edit between options-load and the next request goes stale", () => {
const dir = mkdtempSync(path.join(tmpdir(), "bili-epoch-5930-"));
const file = pinnedConfigFile(dir);
process.env.BILI_CONFIG_FILE = file;
try {
// v1: the generation the process loaded its options from at startup.
writeFileSync(file, JSON.stringify({ compress: { modelContextLimit: 333_000 } }));
const opts = loadOptions();
assert.ok(opts.configSourceEpoch, "loadOptions must carry the source-generation epoch");
const session = makeSession();
// First wire request: resolve from the loaded options, store latest-wins.
let reqConfig = resolveRequestConfig(opts.kernelConfig, opts.routes, undefined, "test-model", undefined, opts.compress);
storeEffectiveConfig(session, reqConfig, opts.configSourceEpoch);
let read = effectiveConfig(session, opts.kernelConfig);
assert.equal(read.modelContextLimit, 333_000, "precondition: the snapshot serves while its source generation is still live");
// The user edits the file directly — NO reload / Apply / restart follows.
writeFileSync(file, JSON.stringify({ compress: { modelContextLimit: 777_000 } }));
// Next wire request: the in-memory options are STILL the v1 generation;
// the request re-resolves from them and re-stores (per-request latest-wins).
// Pre-#5930 this store re-stamped the LIVE hash onto a pre-edit snapshot,
// so the guard could never fire until a reload/restart.
reqConfig = resolveRequestConfig(opts.kernelConfig, opts.routes, undefined, "test-model", undefined, opts.compress);
storeEffectiveConfig(session, reqConfig, opts.configSourceEpoch);
read = effectiveConfig(session, opts.kernelConfig);
assert.equal(read.modelContextLimit, 777_000, "stale options-generation stamp must be refused — the live file tier wins");
} finally {
delete process.env.BILI_CONFIG_FILE;
rmSync(dir, { recursive: true, force: true });
}
});
6 changes: 6 additions & 0 deletions tests/golden-storage-drive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import { SessionStore, _setStoreForTest } from "../src/persist.ts";
import { stripOneTimeAlignment } from "./corrupt-index-child.ts";
import { flushAllSessions, _resetSessionsForTest } from "../src/session.ts";
import type { ProxyOptions } from "../src/config.ts";
import { configFileEpoch } from "../src/config.ts";

/**
* #3325 lesson — the drive renders digests from `node_modules/acp-kernel/dist`
Expand Down Expand Up @@ -432,6 +433,11 @@ function goldenProxyOptions(upstreamPort: number, ctx: number): ProxyOptions {
modelContextLimit: ctx,
kernelConfig: defaultConfig(ctx),
compress: { injectTool: true, injectNudge: true },
// #5930: mirror loadOptions — production always carries the
// options-generation epoch; without it storeEffectiveConfig stops
// stamping effectiveConfigEpoch and the persisted metadata section
// drifts from every committed golden.
configSourceEpoch: configFileEpoch(),
promptCache: { routing: "auto" },
sessionHeader: "x-acp-session",
log: false,
Expand Down
Loading