Skip to content

Commit 5564671

Browse files
authored
fix(gateway): bound audit and Codex backlogs (#126154)
* fix(gateway): bound audit and Codex backlogs Live Gateway SQLite lock failures and process heap pressure exposed two independent queue owners. Route best-effort audit persistence through the canonical shared-state connection with bounded contention retries, and remove the per-notification Codex yield so the keyed turn queue can drain directly. Follow-up to #126033 and #126073. * fix(gateway): annotate raw SQLite cold-open probe * test(codex): register notification burst shard
1 parent caebee3 commit 5564671

29 files changed

Lines changed: 863 additions & 472 deletions

‎config/knip.config.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -152,7 +152,6 @@ const rootEntries = [
152152
// Docker/manual E2E executables and their nested assertion/probe entrypoints.
153153
"scripts/e2e/*.{js,mjs,ts}!",
154154
"scripts/e2e/lib/**/{assertions,probe,mock-server}.{js,mjs,ts}!",
155-
"src/audit/audit-event-writer.worker.ts!",
156155
// Loaded by URL from the SQLite lifecycle archive owner.
157156
"src/config/sessions/session-accessor.sqlite-archive.worker.ts!",
158157
"src/state/openclaw-database-verify.worker.ts!",

‎docs/cli/audit.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -219,7 +219,7 @@ with an expiry-and-rerun next step. After cleanup it can become `unknown` if no
219219
separately retained activity remains; this absence does not prove that the run
220220
did not occur. Startup and hourly maintenance prune at most 1,024 identity
221221
contexts per tick and continue when collection is disabled. Queue saturation,
222-
worker/storage failure, cleanup failure, or abrupt process termination can lose
222+
storage failure, cleanup failure, shutdown timeout, or abrupt process termination can lose
223223
best-effort evidence but never block or abort the agent run. Normal Gateway and
224224
direct-local CLI shutdown flushes accepted work when its writer lifecycle
225225
permits.
@@ -324,7 +324,7 @@ receipt comes from the authoritative first-answer-wins approval row, and a
324324
returned generic receipt comes from the additive immutable decision-fact
325325
table. All three surfaces use 30-day retention, but absence from the activity
326326
ledger cannot prove that an approval or action did not occur. Generic fact
327-
delivery is also best-effort until its bounded worker write persists the row;
327+
delivery is also best-effort until its bounded queue write persists the row;
328328
owner-native approval persistence does not use that queue.
329329

330330
The shipped `audit.list` RPC remains unchanged for older run/tool clients. When

‎docs/gateway/audit.md‎

Lines changed: 22 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -62,16 +62,17 @@ their 30-day expiry.
6262
After session work admission succeeds, OpenClaw validates and freezes
6363
one bounded identity envelope, immediately offers it to the existing audit
6464
writer queue, and continues the run without waiting for writer readiness,
65-
SQLite, or persistence. The worker initializes schema and HMAC-key state,
65+
SQLite, or persistence. The queue drain initializes schema and HMAC-key state,
6666
pseudonymizes raw references, constructs the immutable context, validates its
67-
canonical bytes, and persists it. An accepted envelope can therefore be
68-
temporarily unavailable to inspection while queued work finishes.
67+
canonical bytes, and persists it through the process-owned shared-state
68+
connection. An accepted envelope can therefore be temporarily unavailable to
69+
inspection while queued work finishes.
6970

70-
Persistence remains best-effort. Queue saturation, worker or storage failure,
71-
and process crashes can lose evidence; they log only a bounded operational
72-
warning and never abort the run. Normal Gateway and direct-local CLI shutdown
73-
flushes accepted work when the writer lifecycle permits, but abrupt termination
74-
can still lose queued evidence.
71+
Persistence remains best-effort. Queue saturation, storage failure, shutdown
72+
timeout, and process crashes can lose evidence; they log only a bounded
73+
operational warning and never abort the run. Normal Gateway and direct-local
74+
CLI shutdown flushes accepted work when the writer lifecycle permits, but
75+
abrupt termination can still lose queued evidence.
7576

7677
When identity collection is enabled, restart recovery stores only the safe
7778
execution/context/run ids and timestamp with its existing private recovery
@@ -321,8 +322,9 @@ Message records intentionally omit both.
321322
Execution identity contexts use the same installation-local key owner with a
322323
separate HMAC domain. Raw runtime, invoker, ingress-source, assurance, grant,
323324
and child-delegation references exist only in bounded private admission
324-
carriers. The deeply frozen worker message is capped at 16 KiB and 16 entries
325-
in each bounded evidence array. The worker replaces raw references with keyed
325+
carriers. The deeply frozen queue payload is capped at 16 KiB and 16 entries
326+
in each bounded evidence array. A structured clone strips prototypes at the
327+
queue boundary. The queue drain replaces raw references with keyed
326328
pseudonyms before persistence; they are never stored, exported, inspected, or
327329
logged. Configured agent ids plus context, execution, and run ids remain
328330
operator-visible.
@@ -343,8 +345,9 @@ what was recorded, not as proof of what happened:
343345
- **Absence of a row proves nothing.** Pre-admission inbound drops, sends from
344346
plugin-local or direct-send paths that bypass shared durable delivery, a
345347
dropped admission envelope, and crash-lost queued work can leave no record.
346-
- Writes go through a bounded background worker; worker failure or queue
347-
saturation drops records and logs one operational warning.
348+
- Writes go through a bounded asynchronous process-owned queue; queue
349+
saturation, storage failure, or a bounded shutdown timeout can drop records
350+
and log one operational warning.
348351
- Crash-ambiguous outbound sends are recorded as `unknown` rather than
349352
invented outcomes.
350353

@@ -357,8 +360,9 @@ compliance archive; if you need one, use an external system fed by
357360
Records live in the shared state database (`state/openclaw.sqlite`) and are
358361
written off the delivery hot path. Queries never return records older than 30
359362
days, and the ledger is capped at 100,000 rows; expired rows are pruned during
360-
startup, hourly maintenance, and later writes. Retention maintenance keeps
361-
running even when collection is disabled.
363+
startup, hourly maintenance, and later writes. Each ledger or progress cleanup
364+
transaction deletes at most 1,024 expired rows and schedules more work until
365+
settled. Retention maintenance keeps running even when collection is disabled.
362366

363367
Outbound `queued` and `platform-started` records live in the narrowly owned
364368
`outbound_message_progress` table. The table is created idempotently only on
@@ -385,7 +389,9 @@ additive table is created lazily on first use without a schema-version bump.
385389
Fresh and upgraded installations do not populate identity contexts until an
386390
operator enables collection.
387391
First-use schema creation, HMAC-key access, canonical context construction, and
388-
all SQLite work happen in the audit worker, never in agent admission.
392+
SQLite persistence happen in the process-owned audit queue drain, never in
393+
agent admission. Lock attempts fail fast and retry asynchronously with bounded
394+
backoff so SQLite contention does not synchronously wait on the Gateway thread.
389395
Contexts are retained for 30 days and capped at 100,000 rows. Exact-execution
390396
inspection and run discovery never return a context, candidate, or admission
391397
decision after that context is older than 30 days, even if physical cleanup
@@ -412,7 +418,7 @@ first generic fact write, retains facts for 30 days, caps the table at 250,000
412418
rows, and prunes at most 1,024 rows per write or maintenance tick. Approval
413419
paths never write this table. Its facts and approval rows are authoritative for
414420
their recorded decisions. Delivery to the generic table uses the bounded audit
415-
worker and remains best-effort until persisted; approval-owner writes do not
421+
queue and remains best-effort until persisted; approval-owner writes do not
416422
depend on that queue. The activity ledger cannot recreate either source after
417423
loss.
418424

‎docs/gateway/protocol.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -892,9 +892,9 @@ shared durable delivery; run inspection merges those sources. Chunking and
892892
adapter fan-out are aggregated in terminal `resultCount`. Ambiguous sends reach
893893
a terminal only after acknowledgement, dead
894894
letter, or reconciliation. Plugin-local and direct-send paths that bypass those
895-
shared boundaries are not yet covered. The bounded worker queue is best-effort
896-
and may drop records on failure or saturation, so this surface is not a
897-
lossless compliance archive.
895+
shared boundaries are not yet covered. The bounded process-owned async queue is
896+
best-effort and may drop records on saturation, terminal persistence failure,
897+
or shutdown timeout, so this surface is not a lossless compliance archive.
898898

899899
Recording is on by default and controlled by
900900
[`logging.audit.enabled`](/gateway/configuration-reference#audit). Message

‎extensions/codex/src/app-server/run-attempt-notification-controller.ts‎

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,7 @@ import { readCodexTurnCompletedNotification } from "./protocol-validators.js";
1414
import type { CodexServerNotification } from "./protocol.js";
1515
import type { CodexAttemptLifecycleController } from "./run-attempt-lifecycle-controller.js";
1616
import type { CodexAttemptResources } from "./run-attempt-resources.js";
17-
import {
18-
readCodexFinalizationHookNotification,
19-
waitForCodexNotificationDispatchTurn,
20-
} from "./run-attempt-state.js";
17+
import { readCodexFinalizationHookNotification } from "./run-attempt-state.js";
2118
import type { CodexAttemptTurnState } from "./run-attempt-turn-state.js";
2219
import { CODEX_APP_SERVER_NATIVE_TURN_WAIT_TIMEOUT_MS } from "./turn-router.js";
2320
import type { CodexThreadRouteScope } from "./turn-router.js";
@@ -123,7 +120,6 @@ export function createCodexAttemptNotificationController(
123120
state.terminalTurnNotificationQueued = true;
124121
}
125122
try {
126-
await waitForCodexNotificationDispatchTurn();
127123
await projector.handleNotification(notification);
128124
const canRelease =
129125
isAssistantCompletionReleaseNotification(notification, state.turnCrossedToolHandoff) ||

‎extensions/codex/src/app-server/run-attempt-state.ts‎

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -151,12 +151,6 @@ export function prependCurrentInboundContext(
151151
: prompt;
152152
}
153153

154-
export function waitForCodexNotificationDispatchTurn(): Promise<void> {
155-
return new Promise((resolve) => {
156-
setImmediate(resolve);
157-
});
158-
}
159-
160154
export function buildCodexAppServerTimeoutDiagnostics(params: {
161155
idleMs?: number;
162156
timeoutMs?: number;
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
import path from "node:path";
2+
import { describe, expect, it } from "vitest";
3+
import { itemNotification } from "./protocol.test-helpers.js";
4+
import {
5+
createParams,
6+
createStartedThreadHarness,
7+
runCodexAppServerAttempt,
8+
setupRunAttemptTestHooks,
9+
tempDir,
10+
} from "./run-attempt-test-harness.js";
11+
12+
setupRunAttemptTestHooks();
13+
14+
describe("Codex app-server notification bursts", () => {
15+
it("drains bound command output without one macrotask per notification", async () => {
16+
const harness = createStartedThreadHarness();
17+
const params = createParams(
18+
path.join(tempDir, "session-notification-burst.jsonl"),
19+
path.join(tempDir, "workspace-notification-burst"),
20+
);
21+
const run = runCodexAppServerAttempt(params);
22+
await harness.waitForMethod("turn/start");
23+
await harness.notify(
24+
itemNotification("item/started", {
25+
type: "commandExecution",
26+
id: "cmd-burst",
27+
command: "generate realistic output burst",
28+
cwd: params.workspaceDir,
29+
processId: null,
30+
source: "agent",
31+
status: "inProgress",
32+
commandActions: [],
33+
aggregatedOutput: null,
34+
exitCode: null,
35+
durationMs: null,
36+
}),
37+
);
38+
39+
const notificationCount = 128;
40+
const handledOrder: number[] = [];
41+
const notifications = Array.from({ length: notificationCount }, (_, index) =>
42+
harness
43+
.notify({
44+
method: "item/commandExecution/outputDelta",
45+
params: {
46+
threadId: "thread-1",
47+
turnId: "turn-1",
48+
itemId: "cmd-burst",
49+
delta: `${index.toString().padStart(3, "0")}:${"x".repeat(8_188)}`,
50+
},
51+
})
52+
.then(() => {
53+
handledOrder.push(index);
54+
}),
55+
);
56+
57+
await new Promise<void>((resolve) => {
58+
setImmediate(resolve);
59+
});
60+
expect(handledOrder).toHaveLength(notificationCount);
61+
await Promise.all(notifications);
62+
expect(handledOrder).toEqual(Array.from({ length: notificationCount }, (_, index) => index));
63+
64+
await harness.notify(
65+
itemNotification("item/completed", {
66+
type: "commandExecution",
67+
id: "cmd-burst",
68+
command: "generate realistic output burst",
69+
cwd: params.workspaceDir,
70+
processId: 42,
71+
source: "agent",
72+
status: "completed",
73+
commandActions: [],
74+
aggregatedOutput: null,
75+
exitCode: 0,
76+
durationMs: 20,
77+
}),
78+
);
79+
await harness.completeTurn({ threadId: "thread-1", turnId: "turn-1" });
80+
const result = await run;
81+
expect(JSON.stringify(result.messagesSnapshot)).toContain('"toolCallId":"cmd-burst"');
82+
});
83+
});

‎scripts/release-check.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,6 @@ const requiredPathGroups = [
110110
"dist/agents/compaction-planning.worker.js",
111111
"dist/agents/model-provider-auth.worker.js",
112112
"dist/agents/prepared-model-catalog.worker.js",
113-
"dist/audit/audit-event-writer.worker.js",
114113
"dist/config/sessions/session-accessor.sqlite-archive.worker.js",
115114
"dist/config/sessions/session-transcript-reconcile.worker.js",
116115
"dist/state/openclaw-database-verify.worker.js",

‎src/audit/agent-event-audit.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -273,6 +273,7 @@ export function createAgentEventAuditRecorder(options?: {
273273
options?.writer ??
274274
createAuditEventWriter({
275275
...(options?.stateDir ? { stateDir: options.stateDir } : {}),
276+
onContention: (message) => log.warn(message),
276277
onError: (error) => {
277278
if (!persistenceFailureWarned) {
278279
persistenceFailureWarned = true;

‎src/audit/audit-event-store.ts‎

Lines changed: 23 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -548,39 +548,43 @@ function bindAuditEvent(db: DatabaseSync, input: AuditEventInput): Insertable<Au
548548
}
549549

550550
function countAuditEvents(db: DatabaseSync): number {
551-
const kysely = getAuditKysely(db);
552551
const row = executeSqliteQueryTakeFirstSync(
553552
db,
554-
kysely
553+
getAuditKysely(db)
555554
.selectFrom("audit_events")
556555
.select((expression) => expression.fn.countAll<number>().as("count")),
557556
);
558557
return normalizeSqliteNumber(row?.count ?? null) ?? 0;
559558
}
560559

561-
function pruneAuditEventsAfterInsert(
562-
db: DatabaseSync,
563-
now: number,
564-
limits: { maxRows: number; pruneBatchRows: number } = {
565-
maxRows: AUDIT_EVENT_MAX_ROWS,
566-
pruneBatchRows: AUDIT_EVENT_PRUNE_BATCH_ROWS,
567-
},
568-
): void {
560+
function deleteExpiredAuditEvents(db: DatabaseSync, now: number) {
569561
const kysely = getAuditKysely(db);
570-
const expired = executeSqliteQuerySync(
562+
const expiredSequences = kysely
563+
.selectFrom("audit_events")
564+
.select("sequence")
565+
.where("occurred_at", "<", now - AUDIT_EVENT_RETENTION_MS)
566+
.orderBy("occurred_at", "asc")
567+
.orderBy("sequence", "asc")
568+
.limit(AUDIT_EVENT_PRUNE_BATCH_ROWS);
569+
return executeSqliteQuerySync(
571570
db,
572-
kysely.deleteFrom("audit_events").where("occurred_at", "<", now - AUDIT_EVENT_RETENTION_MS),
571+
kysely.deleteFrom("audit_events").where("sequence", "in", expiredSequences),
573572
);
573+
}
574+
575+
function pruneAuditEventsAfterInsert(db: DatabaseSync, now: number): void {
576+
const kysely = getAuditKysely(db);
577+
const expired = deleteExpiredAuditEvents(db, now);
574578
const cachedCount = auditEventRowCounts.get(db);
575579
let rowCount =
576580
cachedCount === undefined
577581
? countAuditEvents(db)
578582
: Math.max(0, cachedCount + 1 - Number(expired.numAffectedRows ?? 0n));
579-
if (rowCount <= limits.maxRows) {
583+
if (rowCount <= AUDIT_EVENT_MAX_ROWS) {
580584
auditEventRowCounts.set(db, rowCount);
581585
return;
582586
}
583-
const retainedRows = Math.max(0, limits.maxRows - limits.pruneBatchRows);
587+
const retainedRows = Math.max(0, AUDIT_EVENT_MAX_ROWS - AUDIT_EVENT_PRUNE_BATCH_ROWS);
584588
const overflowRow = executeSqliteQueryTakeFirstSync(
585589
db,
586590
kysely
@@ -720,20 +724,16 @@ export function listAuditEvents(params: {
720724
};
721725
}
722726

723-
/** Delete expired metadata during Gateway startup and periodic worker maintenance. */
727+
/** Delete one bounded batch during Gateway startup and periodic audit maintenance. */
724728
export function pruneExpiredAuditEvents(
725729
params: {
726730
now?: number;
727731
database?: OpenClawStateDatabaseOptions;
728732
} = {},
729-
): void {
730-
runOpenClawStateWriteTransaction(({ db }) => {
731-
executeSqliteQuerySync(
732-
db,
733-
getAuditKysely(db)
734-
.deleteFrom("audit_events")
735-
.where("occurred_at", "<", (params.now ?? Date.now()) - AUDIT_EVENT_RETENTION_MS),
736-
);
733+
): number {
734+
return runOpenClawStateWriteTransaction(({ db }) => {
735+
const deleted = deleteExpiredAuditEvents(db, params.now ?? Date.now());
737736
auditEventRowCounts.delete(db);
737+
return Number(deleted.numAffectedRows ?? 0n);
738738
}, params.database);
739739
}

0 commit comments

Comments
 (0)