Skip to content

perf(dashboard): index webhook receipt expiry - #1255

Merged
steipete merged 1 commit into
mainfrom
steipete/clawsweeper-webhook-expiry-index-20260826
Aug 27, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/clawsweeper-webhook-expiry-index-20260826

Conversation

@steipete

@steipete steipete commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Resolves a problem where accepted GitHub webhooks scan and sort the entire retained receipt history during expiry cleanup, even when nothing is expired. LIMIT 256 bounds deletion but does not bound the unindexed scan. This is one measured source of shared Durable Object CPU work, not an established sole or dominant cause of production overload.

Why This Change Was Made

Add one idempotent index on received_at immediately after delivery-table creation in GithubWebhookReadModelStore.ensureSchemaSync. Keep the v1 table and columns, primary/unique constraints, 30-day retention, strict less-than cutoff, ORDER BY received_at ASC, LIMIT 256, prune frequency, and transaction rollback unchanged. No composite index, schema-version bump, global SQLite setting, queue/cache/heartbeat refactor, sharding, retry, concurrency or policy change.

The single-column index removes the measured scan/sort without the composite index's larger storage and changed tied-batch membership in the earlier diagnostic. Equal timestamps still have no SQL ordering guarantee. Existing databases build the index once; older code can ignore it on rollback.

User Impact

Less local SQLite CPU work for expiry cleanup at substantial retained receipt populations. Deduplication, replay after pruning, object/global watermarks and cleanup outcomes remain unchanged in the tested runtime. No public API or UI changes. Added storage, insertion maintenance and one-time index-build cost are the tradeoffs; Deployed Cloudflare capacity is not measured here; the actual workerd Durable Object upgrade proof is recorded below.

OpenClaw Bay Impact

No Bay change is needed: this is an internal SQL access-path optimization with no read-model data-contract, public field, UI, navigation or control change. Bay remains observer-only.

Documentation Impact

Updated the active owning reference, docs/github-webhook-read-model.md, for index ownership, idempotent upgrade, strict-cutoff pruning, retained/pruned GUID behavior and initialization cost. Its owner remains the dashboard and queue maintainers. Added the expected concise maintainer changelog entry for openclaw/clawsweeper.

Policy scope: CONTRIBUTING.md lines 16–19 explicitly restricts normal changelog edits for openclaw/openclaw, then directs ClawSweeper PRs to this repository's release-note policy. Read AGENTS.md lines 50–52 in that scope; it is not a blanket ban on this maintainer-authored ClawSweeper entry. All existing memory-fix and contributor changelog entries are preserved.

Evidence

Final head: a5fdc6606095eeadef03b15191043e95d7b68c85; tested base and direct parent: 5cb6777eea2da37e2c2481e15215c2f8be9c774f. The rebase added no implementation changes: the four non-changelog task files remain byte-identical to the independently reviewed versions; the only conflict was additive changelog text, resolved by keeping every entry.

On the final committed head, Node 24.19.0 with pinned pnpm 11.10.0 passed pnpm run build:node, pnpm run check:static (including docs, formatting, limits and strict dashboard), focused lint below, and all 14 webhook tests. The four new expiry tests cover database upgrade/repeated initialization, real SQLite range-search plans, preserved constraints, 256/256/88/0 drain, strict cutoff, retained/pruned replay, tied timestamps and atomic rollback after receipt pruning. Existing late-object/global-watermark coverage is reused. There are no timing thresholds.

# Node 24.19.0 and repository-pinned pnpm 11.10.0 must be selected.
pnpm run build:node
node --test test/github-webhook-read-model.test.ts
pnpm run check:static
pnpm exec oxlint dashboard/github-webhook-read-model.ts test/github-webhook-read-model.test.ts scripts/proof-webhook-expiry-index.mjs --deny-warnings --report-unused-disable-directives -D correctness -D preserve-caught-error
git diff --check 5cb6777eea2da37e2c2481e15215c2f8be9c774f...a5fdc6606095eeadef03b15191043e95d7b68c85

Earlier, the local full pnpm run check was invoked once and exited 1: 3,695 passed, 48 failed, 9 skipped, 0 cancelled. Static checks, builds, lint and the 12-test focused coverage gate passed before the broad test stage. The failures match the known host baseline modes: 42 missing synthetic origin/main refs (2 command, 3 git-repo-utils, 37 target-validation) and 6 offline pnpm/@pnpm/exe 10.33.0 resolution failures from a v11 mirror. The full suite was not rerun on this rebased head; no unrelated tests, package pins, offline behavior, global SQLite/Git settings or timeouts were changed. No full-green claim is made.

Independent precommit and committed-branch Codex reviews are CLEAN, with no accepted/actionable findings. The parent independently reran the 14 tests and real SQLite proof. Exact-head hosted CI 33035001782 is green, including full pnpm check, sparse repair build, and Windows launcher; CodeQL is also green. The local baseline failures above remain a failed local run, not relabeled success. The new actual Durable Object proof and finding disposition below require a fresh review of this unchanged head and updated body before landing.

Real Behavior Proof — Node SQLite performance and semantics

Claim and surface: the additive received_at index removes the expiry scan and temporary sort while preserving production-store outcomes. The committed proof harness directly imports baseline and final GithubWebhookReadModelStore source snapshots with the real payload converter and unchanged stable-json dependency, and executes the production store through a local Node DatabaseSync storage adapter. It reads baseline source from Git object 5cb6777eea2da37e2c2481e15215c2f8be9c774f and asserts that final source differs by exactly the four index lines. Source/harness hashes are checked before and after execution and match committed head a5fdc6606095eeadef03b15191043e95d7b68c85.

Environment: actual provider local Node DatabaseSync, Node v24.19.0, SQLite 3.53.4, macOS (darwin 27.0.0 arm64), Apple M3 Ultra. The harness explicitly requires this measured Node patch version; another Node 24 patch is not silently substituted. No container image, Crabbox provider, remote lease, workerd, credentials, network, production data or live mutation was used. This is local macOS proof, not the Windows/container recipe. The measured run was serial: no build or other validation ran concurrently. Host one-minute load was 57.15 → 54.20; outliers were retained.

Corpus and method: six fixtures span 1k/10k/100k deterministic UUID-shaped receipts, with zero or 600 expired receipts, plus 128 synthetic item snapshots (~2 KiB bodies) and 100 workflow jobs. Actual production INSERTs seed history. Each accepted delivery updates one issue and receipt/global/class/item state, then performs both cleanup queries in a committed transaction. Five warmups precede 60 alternating baseline/final samples. DELETE measurements include prepare/execute but exclude BEGIN/ROLLBACK; full ingest includes commit and index write maintenance. Exact rowids and touched rows are restored outside timing so batches do not drain between samples; full state is checked afterward. Five fresh file copies per case measure existing-database initialization, index creation, five repeated initializations and reopened committed ingest. These are reopened connections, not physical disk-cold requests; OS caches were not flushed.

Reproduce once from the final checkout, with Node 24.19.0 on PATH. This portable Node command creates a fresh parent temp directory and passes a nonexistent child to the harness, which refuses existing output. It executes the entry exactly once, then asserts the resulting artifact; a terminal proof plan should use this one execution followed by its assertions, not run the entry again in a second step.

node --input-type=module <<'NODE'
import assert from 'node:assert/strict';
import { execFileSync } from 'node:child_process';
import { mkdtempSync, readFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
assert.equal(process.version, 'v24.19.0');
const base = '5cb6777eea2da37e2c2481e15215c2f8be9c774f';
const head = 'a5fdc6606095eeadef03b15191043e95d7b68c85';
assert.equal(execFileSync('git', ['rev-parse', 'HEAD'], { encoding: 'utf8' }).trim(), head);
const parent = mkdtempSync(join(tmpdir(), 'clawsweeper-webhook-expiry-'));
const output = join(parent, 'proof');
execFileSync(process.execPath, ['scripts/proof-webhook-expiry-index.mjs', base, output], { stdio: 'inherit' });
const result = JSON.parse(readFileSync(join(output, 'results.json'), 'utf8'));
assert.equal(result.result, 'PASS');
assert.equal(result.manifest.base, base);
assert.equal(result.manifest.head, head);
console.log('PASS: committed-head proof assertions; artifacts:', output);
NODE

Observed query plans: the captured production expiry DELETE and cutoff binding are identical. Every fixture replaces the inner scan/sort with the same indexed range search; the outer DELETE retains the delivery-ID primary-key access path. Cursor return counts are not treated as examined-row counts.

baseline expiry subquery:
  SCAN github_webhook_read_model_deliveries_v1
  USE TEMP B-TREE FOR ORDER BY
final expiry subquery:
  SEARCH github_webhook_read_model_deliveries_v1 USING INDEX github_webhook_read_model_deliveries_received_at_v1 (received_at<?)

Observed measurements, medians in milliseconds (baseline → final):

Receipts Expired DELETE wall Full ingest wall Full ingest process CPU
1,000 0 0.033 → 0.010 0.125 → 0.104 0.126 → 0.105
1,000 600 0.297 → 0.289 0.404 → 0.397 0.404 → 0.399
10,000 0 0.225 → 0.010 0.316 → 0.104 0.318 → 0.104
10,000 600 0.591 → 0.376 0.689 → 0.486 0.689 → 0.487
100,000 0 2.410 → 0.014 2.603 → 0.129 2.593 → 0.130
100,000 600 3.130 → 0.598 3.220 → 0.670 3.224 → 0.674

At 100k unexpired receipts, median ingest wall was 2.603459 → 0.128625 ms. Small fixture differences are not a universal promised speedup; no performance thresholds gate tests.

One-time build, storage and write costs: at 100k receipts, five reopened files per variant produced these wall-time measurements:

Variant Expired Index-build median (min–max), ms Repeated initializer median, ms Added bytes Reopened ingest median (min–max), ms
baseline 0 none 0.107 0 5.558 (5.265–6.113)
patched 0 26.030 (25.927–220.184) 0.137 1,482,752 1.611 (1.353–5.744)
baseline 600 none 0.120 0 21.480 (19.636–182.306)
patched 600 26.072 (23.541–298.473) 0.137 1,482,752 24.907 (18.848–29.445)

The index adds 1,482,752 bytes (~1.414 MiB) at 100k in this fixture. Median build cost was about 26 ms, with retained outliers up to 298.473 ms. The 100k/600-expired reopened ingest median was slower with the index (24.907 vs 21.480 ms); this proof does not promise a cold/reopened wall-time improvement. Receipt writes must maintain the new index; full-ingest measurements include that cost. Isolated insertion-only overhead was not remeasured, so no per-write numeric claim is made. Process CPU includes process background/GC work, not isolated SQLite CPU. These are rollout costs and noisy local observations, not Cloudflare initialization latency or billing evidence.

Behavior: all six baseline/final fixture pairs matched exact deleted IDs and full logical table state at every drain step, using deep equality during execution. Expired batches drained 256/256/88/0; no-expired fixtures deleted zero. Separate distinct/tied timestamp controls passed strict cutoff (cutoff−1 deleted, cutoff and cutoff+1 retained), retained GUID replay without state changes, pruned GUID acceptance at the next watermark, and rollback of all tables after a failure injected after receipt deletion, followed by successful retry. Existing-database initialization preserves rows, repeated initialization is idempotent, and SQLite integrity_check passes. Matching tied IDs is a control for this SQLite runtime, not an ordering guarantee across engines.

Durable proof artifact: the sanitized JSON summary and tables below/above are in this main PR body, with reproducible source and artifact hashes. Full raw samples, exact query plans, deletion-ID arrays, state hashes, compile options, source snapshots and seed/reopened databases are generated by the linked committed harness and retained by the PR owner; they are not represented as publicly downloadable attachments. The inline artifact is a compact summary, not a claim that hashes alone publish those raw files.

{
  "result": "PASS",
  "base": "5cb6777eea2da37e2c2481e15215c2f8be9c774f",
  "head": "a5fdc6606095eeadef03b15191043e95d7b68c85",
  "provider": "local Node DatabaseSync",
  "runtime": "v24.19.0",
  "sqlite": "3.53.4",
  "platform": "darwin 27.0.0 arm64",
  "cpu": "Apple M3 Ultra",
  "startedAt": "2026-08-27T02:56:31.978Z",
  "finishedAt": "2026-08-27T02:56:50.363Z",
  "load1m": [57.14892578125,54.2041015625],
  "fixtures": {"receipts":[1000,10000,100000],"expired":[0,600],"itemSnapshots":128,"workflowJobs":100,"warmups":5,"samplesPerVariantPerFixture":60},
  "assertions": {"exactFourLineSourceDelta":true,"sourceHashesStable":true,"indexedPlansWithoutScanOrSort":6,"exactDeletionAndFullStatePairs":6,"expiredDrain":[256,256,88,0],"unexpiredDrain":[0,0,0,0],"cutoffReplayRollback":["distinct timestamps: PASS","tied timestamps: PASS"],"upgradeRepeatedInitIntegrity":"PASS"},
  "artifactSha256": {"results.json":"359c3e8b93ff791188414c57defe3b093f28fc779aaac8ccfaf495ffcf7eca38","production-sql.json":"f82457e13fab68f35e3358162d0b1b2ae0f376b127b487a0a9f70099a9a35236","source-manifest.json":"21c187c1c8d0ecd0784b32333241d54bf11a2d4839923452a4534798b7319c41"}
}
Source Baseline SHA-256 Final SHA-256
dashboard/github-webhook-read-model.ts 3caf3ebe8e14a14c117a32fd688517ca875da321667c320074c702ec018bd5fc a0b8b4467d5f000ee44c8db270d3889ed4eea57107807c43daad376572085044
src/stable-json.ts 68e64b18ff6f9b874dfbbace8ea29552ffb40a1ba489d719a43540f2e08bcd05 68e64b18ff6f9b874dfbbace8ea29552ffb40a1ba489d719a43540f2e08bcd05

Harness SHA-256: 0eaf2f913bc7ac748f6585252cf2b327d2f69116cf9a2ccadc9fee256f709f37.

Scope, rollback and limits: no table, column, primary-key, unique-constraint or public-schema change, no schema-version bump and no data migration: only an additive index. Retention, strict cutoff, ORDER BY received_at ASC, LIMIT 256, prune frequency and transaction behavior remain exactly unchanged. Older code can ignore the extra index on rollback; there is no destructive rollback step. Queue/cache/heartbeat behavior, concurrency, retries, sharding and policy are untouched. OpenClaw Bay is unaffected: no data-contract, public field, UI, navigation or control change, and its observer-only boundary is unchanged.

This establishes a synthetic local SQLite cost and preserved behavior. It does not establish production receipt cardinality/rate, Cloudflare planner/runtime capacity, shared-object queueing delay, deployment readiness, or whole overload recovery; expiry cleanup is not established as the sole/dominant overload cause. No production load test or deployment was performed. The separate actual Durable Object upgrade proof below addresses the runtime boundary; production rollout remains a later verification step.

Real Behavior Proof — actual workerd Durable Object upgrade

Addressed: the review requested proof beyond Node DatabaseSync. The unchanged PR head a5fdc6606095eeadef03b15191043e95d7b68c85 now passed an actual persisted Durable Object upgrade on AWS Crabbox, lease cbx_3fb7fbda687f, run run_cadacc18e31f, exit 0. The command completed in 29.329 seconds; this is a functional upgrade test, not a performance benchmark. Runtime: Linux, Node v24.18.1, pnpm 11.10.0, Wrangler 4.107.0, workerd 1.20260701.1, compatibility date 2026-05-11.

The fixture subclasses the unchanged production ExactReviewQueue. An ordinary super.fetch() invokes its real ensureReady/initializeStorage/blockConcurrencyWhile path. The test uses the production GithubWebhookReadModelStore instance with native Durable Object SqlStorage and transactionSync: no fake storage adapter or Node SQLite. It warms initialization, removes only the new index in an isolated fixture database to model the legacy physical layout, seeds 1,000 receipts (600 expired) plus item/class/meta rows and watermark 1,000, then fully stops Wrangler/workerd. A new process opens the same persisted files and named DO identity using the candidate initializer. A third process checks idempotent reopening. This models legacy persisted layout; it does not claim to execute the entire base revision.

All assertions passed: the single-column index was created; every preexisting read-model table hash was preserved across upgrade; production store ingestions drained 256/256/88/0; cutoff and cutoff+1 survived; retained GUIDs returned their original watermark without pruning; a pruned GUID was reaccepted; an injected failure after actual production pruning rolled back receipts, item/class state and watermark together; retry succeeded; the final restart retained identical state and index. The fixed fixture clock is passed through the store's existing parameter, not a global clock replacement. The temporary failure hook calls the real pruning method before throwing. Fixture-only routes are never deployed.

Check Observed result
Legacy → upgraded state Same 1,000 receipts, 600 expired, watermark 1,000 and state SHA-256 b3022b9990f0e5e11828220fa06170de8e05056eea00b1aac4074911198cbfa0
Native receipt-selector counters Legacy: 1,600 rows read / 256 returned; upgraded: 256 rows read / 256 returned; zero rows written by the SELECT
Rollback Before/after state SHA-256 identical: 95eb8d3fb9f28af8c2d255ea2fda1d5fcaa7431170d32938a7feb7d9b15591ea
Final → third-process state Same 406 receipts, zero expired, watermark 1,007 and SHA-256 5a30f4622343200af85611552ddc3e62a489a8d6a73305e333ffedf32be37a99
Lifecycle cleanup Three distinct process groups/constructor identities; each stopped, loopback port closed, no surviving proof processes; owned leases explicitly released

Important EXPLAIN limitation: the warm legacy snapshot reused an EXPLAIN statement prepared before DROP INDEX and still displayed the absent index. That stale row is retained below and is not baseline-plan evidence. sqlite_master and PRAGMA index_info showed the index absent. The restarted process prepared a fresh indexed plan. The counters above are native workerd SqlStorageCursor counters for the SELECT subquery, not DELETE counters, returned-row approximations, CPU measurements, or Cloudflare billing claims.

Provider and safety: the repository configuration selects AWS, and its provider contract preserves that selection. No provider override was used. This is AWS-hosted local workerd, not Docker, local-container, Testbox, or deployed Cloudflare. The Windows-specific container wording does not describe this Mac/Linux execution. --fresh-pr verified the exact head, --no-hydrate and CRABBOX_ENV_ALLOW=CI avoided credentials, IMDSv2's IAM credential endpoint returned 404 before repository execution, and the bootstrap discarded inherited environment. Wrangler was local-only on loopback with isolated persistence, no account/routes/production bindings or secrets, and GitHub pointed at loopback port 9. Bay's observer contract is unchanged.

The first proof-only attempt failed before workerd startup because its runtime-version metadata lookup used the wrong package location; the corrected bootstrap then passed. A coordinator heartbeat timeout did not interrupt the successful run. Both sequential AWS leases were explicitly released after artifact capture; the successful run had already stopped all proof process groups. No production load test, deployment, or real webhook authentication is claimed. The existing 100k Node SQLite performance experiment remains complementary.

Reproduction artifact

Save the exact self-contained bootstrap below as /tmp/clawsweeper-expiry-do-proof/bootstrap.sh. SHA-256: 21fe68d4aa0b0cd681a08a31dc3cdcc9418a2916472feb1acb6ad62360c83560. The portable invocation below uses the already-verified installed Crabbox CLI from a ClawSweeper checkout; the recorded run used the repository-documented trusted wrapper. Preserve the configured AWS provider. The portal may require operator access; the script and selected observed trace are included here as durable public evidence.

env -u CRABBOX_AWS_INSTANCE_PROFILE -u CRABBOX_TAILSCALE -u CRABBOX_TAILSCALE_AUTH_KEY -u CRABBOX_TAILSCALE_AUTH_KEY_ENV -u CRABBOX_TAILSCALE_EXIT_NODE -u CRABBOX_TAILSCALE_EXIT_NODE_ALLOW_LAN_ACCESS -u CRABBOX_TAILSCALE_HOSTNAME_TEMPLATE -u CRABBOX_TAILSCALE_TAGS CRABBOX_ENV_ALLOW=CI CI=1 crabbox run --fresh-pr openclaw/clawsweeper#1255 --no-hydrate --network public --tailscale=false --tailscale-exit-node= --tailscale-exit-node-allow-lan-access=false --script /tmp/clawsweeper-expiry-do-proof/bootstrap.sh --stop-after always --ttl 40m --idle-timeout 15m --timing-json --label pr1255-real-do-upgrade-proof
Exact executed bootstrap
#!/usr/bin/env bash
set -euo pipefail
# Trusted, proof-only bootstrap. No production credentials, routes or deployment.
ROOT=/tmp/clawsweeper-expiry-do-proof
if [ "${1:-}" != sanitized ]; then
  mkdir -p "$ROOT"
  TASK=$(mktemp -d "$ROOT/runtime.XXXXXX")
  mkdir -p "$TASK/home" "$TASK/tmp"
  exec env -i PATH="$PATH" HOME="$TASK/home" TMPDIR="$TASK/tmp" CI=1 \
    COREPACK_ENABLE_DOWNLOAD_PROMPT=0 COREPACK_ENABLE_PROJECT_SPEC=0 \
    WRANGLER_SEND_METRICS=false WRANGLER_LOG_PATH="$TASK/wrangler-log" \
    bash "$0" sanitized "$TASK" "$PWD"
fi
TASK=$2
REPO=$3
EXPECTED=a5fdc6606095eeadef03b15191043e95d7b68c85
test "$(git -C "$REPO" rev-parse HEAD)" = "$EXPECTED"
test -z "$(git -C "$REPO" status --porcelain --untracked-files=no)"
node -e 'if (+process.versions.node.split(".")[0] < 24) throw Error("Node >=24 required")'
command -v corepack >/dev/null
# Fail closed if this ephemeral AWS instance can obtain any IAM role credentials.
IMDS_TOKEN=$(curl --noproxy '*' -fsS --max-time 5 -X PUT \
  -H 'X-aws-ec2-metadata-token-ttl-seconds: 60' http://169.254.169.254/latest/api/token)
IAM_CODE=$(curl --noproxy '*' -sS --max-time 5 -o /dev/null -w '%{http_code}' \
  -H "X-aws-ec2-metadata-token: $IMDS_TOKEN" \
  http://169.254.169.254/latest/meta-data/iam/security-credentials/)
unset IMDS_TOKEN
test "$IAM_CODE" = 404
printf 'SAFETY IMDSv2_IAM_HTTP=404 isolated_HOME=true forwarded_credentials=none\n'
sha256sum "$0" "$REPO/dashboard/exact-review-queue.ts" \
  "$REPO/dashboard/github-webhook-read-model.ts" "$REPO/src/stable-json.ts"
printf 'SOURCE_HEAD=%s NODE=%s\n' "$EXPECTED" "$(node --version)"
cd "$TASK"
printf '{"private":true,"packageManager":"[email protected]"}\n' > package.json
corepack [email protected] add --ignore-scripts --save-exact [email protected] > install.log 2>&1
node node_modules/wrangler/bin/wrangler.js dev --help > wrangler-dev-help.txt
for option in --local --ip --port --persist-to --inspector-port; do
  grep -q -- "$option" wrangler-dev-help.txt
done
cat > fixture.ts <<'WORKER'
import { ExactReviewQueue } from '__REPO__/dashboard/exact-review-queue.ts';
const NOW = Date.parse('2026-08-26T12:00:00.000Z');
const CUT = NOW - 30 * 86400000;
const P = 'github_webhook_read_model_';
const D = P + 'deliveries_v1';
const IDX = P + 'deliveries_received_at_v1';
const assert = (ok, label) => { if (!ok) throw Error(label); };
async function hash(value) {
  return [...new Uint8Array(await crypto.subtle.digest('SHA-256',
    new TextEncoder().encode(JSON.stringify(value))))].map(x => x.toString(16).padStart(2, '0')).join('');
}
export class ExpiryProof extends ExactReviewQueue {
  instance = crypto.randomUUID();
  async fetch(request) {
    // An ordinary production fetch runs ensureReady/initializeStorage through its
    // real blockConcurrencyWhile barrier. This unknown route has no queue work.
    const initialized = await super.fetch(new Request('http://fixture.invalid/__expiry_init__'));
    assert(initialized.status === 404, 'production initialization route');
    const sql = this.storage.sql;
    const rows = (q, ...args) => [...sql.exec(q, ...args)];
    const count = () => rows(`SELECT count(*) n FROM ${D}`)[0].n;
    const expired = () => rows(`SELECT count(*) n FROM ${D} WHERE received_at < ?`, CUT)[0].n;
    const watermark = () => rows(`SELECT watermark FROM ${P}meta_v1`)[0].watermark;
    const state = () => Object.fromEntries(rows(
      "SELECT name FROM sqlite_master WHERE type='table' AND name LIKE 'github_webhook_read_model_%' ORDER BY name"
    ).map(({name}) => [name, rows(`SELECT * FROM ${name} ORDER BY rowid`)]));
    const snapshot = async () => {
      const data = state();
      const select = `SELECT delivery_id FROM ${D} WHERE received_at < ? ORDER BY received_at ASC LIMIT 256`;
      let plan;
      try { plan = rows('EXPLAIN QUERY PLAN ' + select, CUT); }
      catch (error) { plan = {unavailable: String(error)}; }
      const cursor = sql.exec(select, CUT);
      const selected = [...cursor];
      const tableHashes = {};
      for (const [name, value] of Object.entries(data)) tableHashes[name] = {rows: value.length, sha256: await hash(value)};
      return {doId: this.state.id.toString(), instance: this.instance,
        storageType: sql.constructor.name, count: count(), expired: expired(), watermark: watermark(),
        stateHash: await hash(data), tables: tableHashes,
        index: rows('SELECT sql FROM sqlite_master WHERE type=\'index\' AND name=?', IDX),
        indexColumns: rows(`PRAGMA index_info('${IDX}')`),
        plan, selector: {returnedRows: selected.length,
          rowsRead: cursor.rowsRead ?? null, rowsWritten: cursor.rowsWritten ?? null},
        controls: rows(`SELECT delivery_id,received_at,watermark FROM ${D} WHERE delivery_id IN ('r600','r601','r999') ORDER BY delivery_id`)};
    };
    const store = this.githubWebhookReadModelStore;
    const delivery = (id, number = 2000) => ({version: 1, deliveryId: id,
      event: 'issues', action: 'opened', receivedAt: new Date(NOW).toISOString(),
      eventClasses: ['issues'], objects: [{kind: 'item', repository: 'synthetic/expiry',
        number, itemKind: 'issue', sourceUpdatedAt: new Date(NOW).toISOString(),
        snapshot: {number, title: 'Synthetic expiry proof'}}]});
    const action = new URL(request.url).pathname;
    let result;
    if (action === '/seed') {
      assert(count() === 0, 'fresh isolated fixture required');
      this.storage.transactionSync(() => {
        sql.exec(`DROP INDEX ${IDX}`);
        for (let i = 0; i < 1000; i++) {
          const at = i < 600 ? CUT - 600 + i : i === 600 ? CUT : i === 601 ? CUT + 1 : NOW;
          sql.exec(`INSERT INTO ${D} VALUES (?, 'issues', 'opened', ?, ?)`, 'r' + i, at, i + 1);
        }
        sql.exec(`UPDATE ${P}meta_v1 SET watermark=1000,created_at=?,updated_at=? WHERE singleton_id=1`, CUT - 600, NOW);
        sql.exec(`INSERT INTO ${P}classes_v1 VALUES ('issues',1000,?,?,1000)`, CUT - 600, NOW);
        for (const n of [10, 11]) sql.exec(`INSERT INTO ${P}items_v1 VALUES ('synthetic/expiry',?,'issue',?,?,?, ?,?)`,
          n, NOW, JSON.stringify({number: n, title: 'Preserve me'}), 'r' + (n - 1), n, NOW);
      });
      result = await snapshot();
      assert(result.count === 1000 && result.expired === 600 && result.index.length === 0, 'legacy baseline');
    } else if (action === '/snapshot') result = await snapshot();
    else if (action === '/exercise') {
      const before = await snapshot();
      assert(before.count === 1000 && before.expired === 600, 'exercise baseline');
      const retained = store.ingest(delivery('r999'), NOW);
      assert(retained.deduped && retained.watermark === 1000 && expired() === 600, 'dedupe must not prune');
      const batches = [];
      for (let i = 0; i < 4; i++) {
        const n = count(), e = expired();
        const accepted = store.ingest(delivery('new' + i, 2000 + i), NOW);
        batches.push({deleted: n + 1 - count(), expiredBefore: e, expiredAfter: expired(), ...accepted});
        assert(!accepted.deduped && accepted.watermark === 1001 + i, 'monotonic batch watermark');
      }
      assert(JSON.stringify(batches.map(x => x.deleted)) === '[256,256,88,0]', 'bounded receipt deletion');
      const duplicate = store.ingest(delivery('r999'), NOW);
      assert(duplicate.deduped && duplicate.watermark === 1000 && watermark() === 1004, 'original watermark');
      const replay = store.ingest(delivery('r0'), NOW);
      assert(!replay.deduped && replay.watermark === 1005, 'pruned GUID accepted');
      assert(rows(`SELECT * FROM ${D} WHERE delivery_id='r600'`)[0].received_at === CUT, 'strict cutoff');
      assert(rows(`SELECT * FROM ${D} WHERE delivery_id='r601'`)[0].received_at === CUT + 1, 'cutoff plus one');
      // Add one backdated receipt without pruning it, using the production
      // store's explicit now parameter. The fixed clock affects only fixture calls.
      const old = delivery('rollback-expired', 3000);
      old.receivedAt = new Date(CUT - 1).toISOString();
      assert(store.ingest(old, CUT - 1).watermark === 1006 && expired() === 1, 'rollback fixture');
      const rollbackBefore = await snapshot();
      const originalPrune = store.pruneSync;
      let observedExpiredAfterPrune = null, injected = false;
      store.pruneSync = function(now) {
        originalPrune.call(this, now);
        observedExpiredAfterPrune = expired();
        throw Error('fixture_failure_after_real_prune');
      };
      try { store.ingest(delivery('must-rollback', 4000), NOW); }
      catch (error) { assert(error.message === 'fixture_failure_after_real_prune', 'expected injected failure'); injected = true; }
      finally { store.pruneSync = originalPrune; }
      const rollbackAfter = await snapshot();
      assert(injected && observedExpiredAfterPrune === 0 && rollbackAfter.expired === 1, 'real pruning rolled back');
      assert(rollbackBefore.stateHash === rollbackAfter.stateHash, 'receipt/item/class/meta rollback');
      const finalRetry = store.ingest(delivery('must-rollback', 4000), NOW);
      assert(!finalRetry.deduped && finalRetry.watermark === 1007 && expired() === 0, 'rollback retry');
      const after = await snapshot();
      result = {retained, batches, duplicate, replay,
        rollback: {beforeHash: rollbackBefore.stateHash, afterHash: rollbackAfter.stateHash,
          observedExpiredAfterPrune, expiredAfterRollback: rollbackAfter.expired,
          watermarkAfterRollback: rollbackAfter.watermark, retry: finalRetry}, after};
    } else return new Response('fixture route not found', {status:404});
    return Response.json(result);
  }
}
export default {fetch(request, env) {
  return env.PROOF.get(env.PROOF.idFromName('expiry-upgrade-v1')).fetch(request);
}};
WORKER
node --input-type=module - "$REPO" <<'REPLACE'
import {readFileSync,writeFileSync} from 'node:fs';
writeFileSync('fixture.ts', readFileSync('fixture.ts','utf8').replace('__REPO__',process.argv[2]));
REPLACE
cat > wrangler.json <<'CONFIG'
{"name":"expiry-do-proof","main":"fixture.ts","compatibility_date":"2026-05-11","workers_dev":false,"send_metrics":false,"durable_objects":{"bindings":[{"name":"PROOF","class_name":"ExpiryProof"}]},"migrations":[{"tag":"v1","new_sqlite_classes":["ExpiryProof"]}],"vars":{"GITHUB_API_URL":"http://127.0.0.1:9","TARGET_REPOS":"synthetic/expiry","PUBLIC_BAY_REPOS":""}}
CONFIG
cat > run.mjs <<'DRIVER'
import assert from 'node:assert/strict';
import {spawn,execFileSync} from 'node:child_process';
import {openSync,writeFileSync,readFileSync,readdirSync} from 'node:fs';
import {createHash} from 'node:crypto';
import path from 'node:path';
const trace = [], children = [];
const emit = (phase, detail) => {const row={phase,...detail}; trace.push(row); console.log(JSON.stringify(row));};
const sha = file => createHash('sha256').update(readFileSync(file)).digest('hex');
const wait = ms => new Promise(resolve=>setTimeout(resolve,ms));
const wrangler = path.resolve('node_modules/wrangler/bin/wrangler.js');
const url = 'http://127.0.0.1:18787';
let current;
for (const signal of ['SIGINT','SIGTERM']) process.once(signal, async () => {
  try {await stop(signal);writeFileSync('trace.json',JSON.stringify(trace,null,2)+'\n');}
  finally {process.exit(128);}
});
function ownedPids(group) {
  return execFileSync('ps',['-eo','pid,pgid,stat,comm'],{encoding:'utf8'}).trim().split('\n').slice(1)
    .map(s=>s.trim().split(/\s+/)).filter(a=>+a[1]===group).map(a=>({pid:+a[0],pgid:+a[1],state:a[2],command:a[3]}));
}
async function api(route) {
  const response=await fetch(url+route,{method:'POST',signal:AbortSignal.timeout(15000)});
  const text=await response.text(); assert.equal(response.status,200,text.slice(0,2000)); return JSON.parse(text);
}
async function start(sequence) {
  const fd=openSync(`wrangler-${sequence}.log`,'w');
  const child=spawn(process.execPath,[wrangler,'dev','--local','--ip','127.0.0.1','--port','18787',
    '--inspector-port','18788','--persist-to',path.resolve('persistence'),'--config',path.resolve('wrangler.json')],
    {stdio:['ignore',fd,fd],detached:true});
  current=child; children.push(child);
  child.exited=new Promise(resolve=>child.once('exit',(code,signal)=>resolve({code,signal})));
  let ready;
  for(let i=0;i<120;i++) {
    if(child.exitCode!==null) throw Error(`Wrangler exited: ${readFileSync(`wrangler-${sequence}.log`,'utf8')}`);
    try {ready=await api('/snapshot');break;} catch(error) {if(i===119) throw error;await wait(500);}
  }
  const pids=ownedPids(child.pid);
  assert(pids.some(p=>p.command.includes('workerd')),'real workerd process required');
  emit('process_start',{sequence,group:child.pid,pids,doId:ready.doId,instance:ready.instance});
  return ready;
}
async function stop(sequence) {
  if(!current)return;
  const child=current;current=null;
  const before=ownedPids(child.pid);
  try{process.kill(-child.pid,'SIGTERM');}catch(e){if(e.code!=='ESRCH')throw e;}
  let exit=await Promise.race([child.exited,wait(8000).then(()=>null)]);
  if(!exit){try{process.kill(-child.pid,'SIGKILL');}catch(e){if(e.code!=='ESRCH')throw e;}exit=await child.exited;}
  for(let i=0;i<50 && ownedPids(child.pid).some(p=>!p.state.startsWith('Z'));i++) await wait(100);
  const remaining=ownedPids(child.pid).filter(p=>!p.state.startsWith('Z'));
  assert.equal(remaining.length,0,'owned process group stopped');
  let accepting=false;try{await fetch(url,{signal:AbortSignal.timeout(1000)});accepting=true;}catch{}
  assert.equal(accepting,false,'loopback server stopped');
  emit('process_stop',{sequence,group:child.pid,before,exit,remaining,loopbackClosed:true});
}
function persistedFiles(dir) {
  return readdirSync(dir,{withFileTypes:true}).flatMap(e=>e.isDirectory()?persistedFiles(path.join(dir,e.name)):
    [{path:path.join(dir,e.name),sha256:sha(path.join(dir,e.name))}]);
}
try {
  const pkg=JSON.parse(readFileSync('node_modules/wrangler/package.json'));
  const workerdPackages=readdirSync('node_modules/.pnpm').filter(name=>name.startsWith('workerd@'));
  assert.equal(workerdPackages.length,1,'one pinned workerd engine');
  const workerdPkg=JSON.parse(readFileSync(`node_modules/.pnpm/${workerdPackages[0]}/node_modules/workerd/package.json`));
  const pnpm=execFileSync('corepack',['[email protected]','--version'],{encoding:'utf8'}).trim();
  emit('runtime',{node:process.version,pnpm,wrangler:pkg.version,workerd:workerdPkg.version,
    fixtureSha256:sha('fixture.ts'),configSha256:sha('wrangler.json'),lockSha256:sha('pnpm-lock.yaml'),
    localOnly:true,fixtureNow:'2026-08-26T12:00:00.000Z',cutoff:'2026-07-27T12:00:00.000Z'});
  assert.equal(pkg.version,'4.107.0');
  await start(1);
  const baseline=await api('/seed'); emit('legacy_baseline',baseline);
  await stop(1); emit('persisted_legacy',{files:persistedFiles('persistence')});
  const upgraded=await start(2); emit('upgraded',upgraded);
  assert.equal(upgraded.doId,baseline.doId);assert.notEqual(upgraded.instance,baseline.instance);
  assert.equal(upgraded.stateHash,baseline.stateHash);assert.deepEqual(upgraded.tables,baseline.tables);
  assert.equal(upgraded.index.length,1);assert.deepEqual(upgraded.indexColumns.map(x=>x.name),['received_at']);
  if(Array.isArray(upgraded.plan)) {
    assert(upgraded.plan.some(x=>x.detail.includes('deliveries_received_at_v1')));
    assert(!upgraded.plan.some(x=>x.detail.includes('TEMP B-TREE')));
  }
  const exercise=await api('/exercise');emit('store_behavior',exercise);
  await stop(2);emit('persisted_after_behavior',{files:persistedFiles('persistence')});
  const reopened=await start(3);emit('idempotent_reopen',reopened);
  assert.equal(reopened.doId,upgraded.doId);assert.notEqual(reopened.instance,upgraded.instance);
  assert.equal(reopened.stateHash,exercise.after.stateHash);assert.deepEqual(reopened.index,upgraded.index);
  assert.deepEqual(reopened.indexColumns,upgraded.indexColumns);
  emit('assertions',{passed:true,legacyDataPreserved:true,realSqlStorage:true,
    boundedDeletes:[256,256,88,0],strictCutoff:true,dedupeOriginalWatermark:true,
    prunedGuidReaccepted:true,transactionRollback:true,idempotentRestart:true});
} finally {
  await stop('final');
  const remaining=children.flatMap(c=>ownedPids(c.pid).filter(p=>!p.state.startsWith('Z')));
  emit('process_cleanup',{ownedGroups:children.map(c=>c.pid),remaining});
  writeFileSync('trace.json',JSON.stringify(trace,null,2)+'\n');
  assert.equal(remaining.length,0);
}
DRIVER
node run.mjs
test "$(git -C "$REPO" rev-parse HEAD)" = "$EXPECTED"
test -z "$(git -C "$REPO" status --porcelain --untracked-files=no)"
printf 'FINAL source_head_unchanged=true tracked_source_clean=true\n'
printf 'ARTIFACT_ROOT=%s\n' "$TASK"
tar -czf "$ROOT/artifacts.tar.gz" fixture.ts wrangler.json run.mjs trace.json \
  pnpm-lock.yaml wrangler-dev-help.txt install.log wrangler-1.log wrangler-2.log wrangler-3.log
Selected observed workerd trace (including the known-stale legacy EXPLAIN)
{"phase":"runtime","node":"v24.18.1","pnpm":"11.10.0","wrangler":"4.107.0","workerd":"1.20260701.1","fixtureSha256":"269bbd77ba1fc637be0bd90855af593b835d48d25a9a8d963ac44b54f5f836c6","configSha256":"3b646b942b40bd01c894f25b34259bb0b34e55c398a72dde24f7845d9ff2ba48","lockSha256":"a86620583a7afb150d55345020a7cb1107a8610c8f4b69c0ace8c61184a7bcc4","localOnly":true,"fixtureNow":"2026-08-26T12:00:00.000Z","cutoff":"2026-07-27T12:00:00.000Z"}
{"phase":"process_start","sequence":1,"group":3532,"doId":"d0ab742d0ec7909873c0dda1fe7f0fbc969df5ab2b73952485f08936556a4252","instance":"c5abe40e-008a-4c7a-92fd-ea6ee11f9916"}
{"phase":"legacy_baseline","doId":"d0ab742d0ec7909873c0dda1fe7f0fbc969df5ab2b73952485f08936556a4252","instance":"c5abe40e-008a-4c7a-92fd-ea6ee11f9916","storageType":"SqlStorage","count":1000,"expired":600,"watermark":1000,"stateHash":"b3022b9990f0e5e11828220fa06170de8e05056eea00b1aac4074911198cbfa0","index":[],"indexColumns":[],"plan":[{"id":5,"parent":0,"notused":203,"detail":"SEARCH github_webhook_read_model_deliveries_v1 USING INDEX github_webhook_read_model_deliveries_received_at_v1 (received_at<?)"}],"selector":{"returnedRows":256,"rowsRead":1600,"rowsWritten":0},"controls":[{"delivery_id":"r600","received_at":1785153600000,"watermark":601},{"delivery_id":"r601","received_at":1785153600001,"watermark":602},{"delivery_id":"r999","received_at":1787745600000,"watermark":1000}],"explainKnownStaleNotUsedAsBaselineProof":true}
{"phase":"process_stop","sequence":1,"group":3532,"exit":{"code":143,"signal":null},"remaining":[],"loopbackClosed":true}
{"phase":"process_start","sequence":2,"group":3692,"doId":"d0ab742d0ec7909873c0dda1fe7f0fbc969df5ab2b73952485f08936556a4252","instance":"1af6de06-02aa-450e-b120-14f9171ab3dd"}
{"phase":"upgraded","doId":"d0ab742d0ec7909873c0dda1fe7f0fbc969df5ab2b73952485f08936556a4252","instance":"1af6de06-02aa-450e-b120-14f9171ab3dd","storageType":"SqlStorage","count":1000,"expired":600,"watermark":1000,"stateHash":"b3022b9990f0e5e11828220fa06170de8e05056eea00b1aac4074911198cbfa0","index":[{"sql":"CREATE INDEX github_webhook_read_model_deliveries_received_at_v1\n         ON github_webhook_read_model_deliveries_v1 (received_at)"}],"indexColumns":[{"seqno":0,"cid":3,"name":"received_at"}],"plan":[{"id":5,"parent":0,"notused":203,"detail":"SEARCH github_webhook_read_model_deliveries_v1 USING INDEX github_webhook_read_model_deliveries_received_at_v1 (received_at<?)"}],"selector":{"returnedRows":256,"rowsRead":256,"rowsWritten":0},"controls":[{"delivery_id":"r600","received_at":1785153600000,"watermark":601},{"delivery_id":"r601","received_at":1785153600001,"watermark":602},{"delivery_id":"r999","received_at":1787745600000,"watermark":1000}]}
{"phase":"store_behavior","retained":{"accepted":true,"deduped":true,"watermark":1000},"batches":[{"deleted":256,"expiredBefore":600,"expiredAfter":344,"accepted":true,"deduped":false,"watermark":1001},{"deleted":256,"expiredBefore":344,"expiredAfter":88,"accepted":true,"deduped":false,"watermark":1002},{"deleted":88,"expiredBefore":88,"expiredAfter":0,"accepted":true,"deduped":false,"watermark":1003},{"deleted":0,"expiredBefore":0,"expiredAfter":0,"accepted":true,"deduped":false,"watermark":1004}],"duplicate":{"accepted":true,"deduped":true,"watermark":1000},"replay":{"accepted":true,"deduped":false,"watermark":1005},"rollback":{"beforeHash":"95eb8d3fb9f28af8c2d255ea2fda1d5fcaa7431170d32938a7feb7d9b15591ea","afterHash":"95eb8d3fb9f28af8c2d255ea2fda1d5fcaa7431170d32938a7feb7d9b15591ea","observedExpiredAfterPrune":0,"expiredAfterRollback":1,"watermarkAfterRollback":1006,"retry":{"accepted":true,"deduped":false,"watermark":1007}},"after":{"count":406,"expired":0,"watermark":1007,"stateHash":"5a30f4622343200af85611552ddc3e62a489a8d6a73305e333ffedf32be37a99"}}
{"phase":"process_stop","sequence":2,"group":3692,"exit":{"code":143,"signal":null},"remaining":[],"loopbackClosed":true}
{"phase":"process_start","sequence":3,"group":3844,"doId":"d0ab742d0ec7909873c0dda1fe7f0fbc969df5ab2b73952485f08936556a4252","instance":"3609ce47-9ba1-45cf-80ef-4e5b9a0a155a"}
{"phase":"idempotent_reopen","doId":"d0ab742d0ec7909873c0dda1fe7f0fbc969df5ab2b73952485f08936556a4252","instance":"3609ce47-9ba1-45cf-80ef-4e5b9a0a155a","storageType":"SqlStorage","count":406,"expired":0,"watermark":1007,"stateHash":"5a30f4622343200af85611552ddc3e62a489a8d6a73305e333ffedf32be37a99","index":[{"sql":"CREATE INDEX github_webhook_read_model_deliveries_received_at_v1\n         ON github_webhook_read_model_deliveries_v1 (received_at)"}],"indexColumns":[{"seqno":0,"cid":3,"name":"received_at"}],"plan":[{"id":5,"parent":0,"notused":203,"detail":"SEARCH github_webhook_read_model_deliveries_v1 USING INDEX github_webhook_read_model_deliveries_received_at_v1 (received_at<?)"}],"selector":{"returnedRows":0,"rowsRead":1,"rowsWritten":0},"controls":[{"delivery_id":"r600","received_at":1785153600000,"watermark":601},{"delivery_id":"r601","received_at":1785153600001,"watermark":602},{"delivery_id":"r999","received_at":1787745600000,"watermark":1000}]}
{"phase":"assertions","passed":true,"legacyDataPreserved":true,"realSqlStorage":true,"boundedDeletes":[256,256,88,0],"strictCutoff":true,"dedupeOriginalWatermark":true,"prunedGuidReaccepted":true,"transactionRollback":true,"idempotentRestart":true}
{"phase":"process_stop","sequence":"final","group":3844,"exit":{"code":143,"signal":null},"remaining":[],"loopbackClosed":true}
{"phase":"process_cleanup","ownedGroups":[3532,3692,3844],"remaining":[]}

Finding Disposition — changelog scope

Rejected: “Remove the release-owned changelog entry.” The cited rule concerns a different target repository. This is openclaw/clawsweeper. AGENTS.md says “OpenClaw CHANGELOG.md is release-owned.” CONTRIBUTING.md explicitly scopes the restriction to “an openclaw/openclaw target PR” and separately directs ClawSweeper PRs to their own release-note policy. The maintainer-authored ClawSweeper entry intentionally remains; it neither edits OpenClaw's changelog nor publishes a release. The same scope error was resolved in the fresh review of #1254.

The objective DO-runtime proof request is addressed above. No production-code finding remains accepted or unresolved. Please reassess the unchanged head against this updated proof and policy disposition; no source, test, retention, timeout, or safety gate was changed to satisfy the review.

@clawsweeper

clawsweeper Bot commented Aug 27, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@clawsweeper clawsweeper Bot added merge-risk: 🚨 compatibility 🚨 Merging this PR could break existing users, config, migrations, defaults, or upgrades. P2 Normal priority bug or improvement with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Aug 27, 2026
@clawsweeper

clawsweeper Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 26, 2026, 11:55 PM ET / August 27, 2026, 03:55 UTC.

ClawSweeper review

What this changes

The PR adds an idempotent index on persisted webhook receipt time so expiry cleanup can seek old receipts instead of scanning and sorting the full retained history.

Merge readiness

⚠️ Ready for maintainer review - 2 items remain

Keep this open for normal maintainer landing: current main does not contain the receipt-time index, while the updated PR body supplies current-head Durable Object upgrade proof and the focused patch preserves the existing cleanup semantics.

Priority: P2
Reviewed head: a5fdc6606095eeadef03b15191043e95d7b68c85

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) A focused additive schema optimization with strong current-head runtime proof, targeted compatibility controls, and no actionable review finding.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (logs): The updated PR body provides an after-fix AWS Crabbox Durable Object upgrade trace for the current head, including native SqlStorage, persisted legacy data, initialization, bounded expiry, replay, rollback, and cleanup verification.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (logs): The updated PR body provides an after-fix AWS Crabbox Durable Object upgrade trace for the current head, including native SqlStorage, persisted legacy data, initialization, bounded expiry, replay, rollback, and cleanup verification.
Evidence reviewed 6 items Additive schema change: The PR creates an idempotent single-column index immediately after creating the existing receipt table.
Preserved cleanup contract: Expiry still deletes at most 256 receipt GUIDs strictly before the 30-day cutoff in receipt-time order; the PR changes the access path, not the query semantics.
Focused regression coverage: The added tests cover existing-database initialization, indexed query planning, bounded draining, strict cutoff, replay, tied timestamps, and rollback after pruning.
Findings None None.
Security None None.

Live Verification

Command: node scripts/proof-webhook-expiry-index.mjs 5cb6777eea2da37e2c2481e15215c2f8be9c774f /tmp/clawsweeper-webhook-expiry-proof

Result: FAIL (partial) — step 2 expect_output PASS: source identity, indexed plans, exact deleted IDs/full states, upgrade/idempotence, cutoff/replay and rollback.: expected terminal output was not visible within 30 seconds: "PASS: source identity, indexed plans, exact deleted IDs/full states, upgrade/idempotence, cutoff/replay and rollback."

{"n":1000,"expired":0,"variant":"baseline","delete":{"wallMs":{"median":0.057145,"p95":0.091085,"min":0.053298,"max":2.237627},"cpuMs":{"median":0.06,"p95":0.16
5,"min":0.055,"max":2.77}},"ingest":{"wallMs":{"median":0.271562,"p95":0.377998,"min":0.237591,"max":0.460791},"cpuMs":{"median":0.275,"p95":0.468,"min":0.24,"m
ax":0.807}}}
{"n":1000,"expired":0,"variant":"patched","delete":{"wallMs":{"median":0.02033,"p95":0.047501,"min":0.016785,"max":0.10182},"cpuMs":{"median":0.023,"p95":0.05,"
min":0.019,"max":0.471}},"ingest":{"wallMs":{"median":0.224492,"p95":0.319583,"min":0.204091,"max":0.382335},"cpuMs":{"median":0.228,"p95":0.357,"min":0.207,"ma
x":0.574}}}
{"n":1000,"expired":600,"variant":"baseline","delete":{"wallMs":{"median":0.475793,"p95":0.497485,"min":0.457526,"max":0.522852},"cpuMs":{"median":0.479,"p95":0
.5,"min":0.46,"max":0.823}},"ingest":{"wallMs":{"median":0.682939,"p95":0.71731,"min":0.657261,"max":0.926889},"cpuMs":{"median":0.686,"p95":0.721,"min":0.66,"m
ax":1.562}}}
{"n":1000,"expired":600,"variant":"patched","delete":{"wallMs":{"median":0.470315,"p95":0.498817,"min":0.434402,"max":0.506318},"cpuMs":{"median":0.474,"p95":0.
501,"min":0.437,"max":0.508}},"ingest":{"wallMs":{"median":0.686344,"p95":0.714936,"min":0.630963,"max":0.917786},"cpuMs":{"median":0.689,"p95":0.718,"min":0.63
4,"max":1.405}}}
{"n":10000,"expired":0,"variant":"baseline","delete":{"wallMs":{"median":0.382345,"p95":0.403977,"min":0.37205,"max":0.423086},"cpuMs":{"median":0.384,"p95":0.4
07,"min":0.374,"max":0.425}},"ingest":{"wallMs":{"median":0.584824,"p95":0.615619,"min":0.545145,"max":0.626135},"cpuMs":{"median":0.587,"p95":0.618,"min":0.548
,"max":0.629}}}
{"n":10000,"expired":0,"variant":"patched","delete":{"wallMs":{"median":0.018518,"p95":0.021071,"min":0.016073,"max":0.032377},"cpuMs":{"median":0.021,"p95":0.0
23,"min":0.018,"max":0.034}},"ingest":{"wallMs":{"median":0.214707,"p95":0.248066,"min":0.172074,"max":0.330889},"cpuMs":{"median":0.217,"p95":0.251,"min":0.174
,"max":0.663}}}
{"n":10000,"expired":600,"variant":"baseline","delete":{"wallMs":{"median":0.931677,"p95":0.984495,"min":0.894912,"max":1.707783},"cpuMs":{"median":0.935,"p95":
1.043,"min":0.898,"max":1.712}},"ingest":{"wallMs":{"median":1.163609,"p95":1.24532,"min":1.131591,"max":1.521508},"cpuMs":{"median":1.167,"p95":1.378,"min":1.1
35,"max":1.615}}}
{"n":10000,"expired":600,"variant":"patched","delete":{"wallMs":{"median":0.597113,"p95":0.639926,"min":0.563232,"max":0.730169},"cpuMs":{"median":0.6,"p95":0.6
43,"min":0.566,"max":0.735}},"ingest":{"wallMs":{"median":0.825399,"p95":0.85972,"min":0.800943,"max":1.108708},"cpuMs":{"median":0.828,"p95":0.864,"min":0.805,
"max":1.112}}}
{"n":100000,"expired":0,"variant":"baseline","delete":{"wallMs":{"median":3.786354,"p95":3.910137,"min":3.705674,"max":4.30481},"cpuMs":{"median":3.788,"p95":3.
913,"min":3.708,"max":4.311}},"ingest":{"wallMs":{"median":4.009633,"p95":4.215838,"min":3.926571,"max":4.806601},"cpuMs":{"median":4.009,"p95":4.346,"min":3.93
,"max":7.249}}}
{"n":100000,"expired":0,"variant":"patched","delete":{"wallMs":{"median":0.020019,"p95":0.025487,"min":0.016385,"max":0.03397},"cpuMs":{"median":0.022,"p95":0.0
28,"min":0.018,"max":0.035}},"ingest":{"wallMs":{"median":0.213045,"p95":0.263168,"min":0.185504,"max":0.312722},"cpuMs":{"median":0.216,"p95":0.276,"min":0.188
,"max":1.238}}}
{"n":100000,"expired":600,"variant":"baseline","delete":{"wallMs":{"median":4.706133,"p95":5.234624,"min":4.480499,"max":6.139},"cpuMs":{"median":4.71,"p95":5.2
38,"min":4.484,"max":6.143}},"ingest":{"wallMs":{"median":4.995159,"p95":5.456641,"min":4.754003,"max":5.579462},"cpuMs":{"median":5,"p95":5.481,"min":4.758,"ma
x":7.258}}}
{"n":100000,"expired":600,"variant":"patched","delete":{"wallMs":{"median":0.901942,"p95":1.084311,"min":0.751169,"max":1.179803},"cpuMs":{"median":0.905,"p95":
1.088,"min":0.754,"max":1.183}},"ingest":{"wallMs":{"median":1.046756,"p95":1.110921,"min":1.016942,"max":1.5
… output truncated …

Assertions:

  • FAIL expect_output: PASS: source identity, indexed plans, exact deleted IDs/full states, upgrade/idempotence, cutoff/replay and rollback.

How this fits together

The exact-review queue ingests signed GitHub deliveries into a Durable Object read model. Receipt cleanup runs during ingestion, and the retained state then supports review planning and dashboard reads.

flowchart LR
A[GitHub deliveries] --> B[Exact-review queue]
B --> C[Durable Object read model]
C --> D[Receipt table]
D --> E[Indexed expiry cleanup]
E --> F[Review planning]
F --> G[Dashboard reads]
Loading

Before merge

  • Resolve merge risk (P1) - Existing Durable Object databases will build and maintain an additional index, adding one-time initialization work and persistent storage; the supplied proof documents this tradeoff but it remains an upgrade consideration.
  • Complete next step (P2) - No repair lane is needed: the PR has no actionable finding and remains an ordinary maintainer-landing decision.
Agent review details

Security

None.

Review metrics

Metric Value Why it matters
Patch scope 5 files; +715, -3 lines The runtime change is four production lines, with focused regression coverage and a committed proof harness.
Production versus proof coverage production +4; tests +188; proof harness +509 Most growth is explicit validation for a persisted-schema optimization rather than expanded production behavior.

Merge-risk options

Maintainer options:

  1. Accept the documented additive upgrade cost (recommended)
    Merge the verified idempotent index upgrade while accepting its measured storage and one-time initialization overhead for existing receipt databases.

Technical review

Best possible solution:

Land the additive index with its documented upgrade cost, retaining the existing 30-day, strict-cutoff, bounded-pruning, replay, and rollback contracts.

Do we have a high-confidence way to reproduce the issue?

Yes: the committed tests and supplied current-head Durable Object trace exercise legacy database initialization, expiry, replay, and rollback through the production storage owner.

Is this the best way to solve the issue?

Yes: a single idempotent index matches the existing strict cutoff and bounded deletion query without adding a schema version, migration policy, or parallel cleanup path.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 387cf82c7eba.

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient. The updated PR body provides an after-fix AWS Crabbox Durable Object upgrade trace for the current head, including native SqlStorage, persisted legacy data, initialization, bounded expiry, replay, rollback, and cleanup verification.
  • add rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (logs): The updated PR body provides an after-fix AWS Crabbox Durable Object upgrade trace for the current head, including native SqlStorage, persisted legacy data, initialization, bounded expiry, replay, rollback, and cleanup verification.
  • remove status: 📣 needs proof: Current PR status label is status: 👀 ready for maintainer look.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🦞 diamond lobster, so this older rating label is no longer current.

Label justifications:

  • P2: This is a bounded internal performance improvement with no reported outage or security boundary change.
  • merge-risk: 🚨 compatibility: The new index is created against existing persisted Durable Object receipt databases during initialization.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (logs): The updated PR body provides an after-fix AWS Crabbox Durable Object upgrade trace for the current head, including native SqlStorage, persisted legacy data, initialization, bounded expiry, replay, rollback, and cleanup verification.
  • proof: sufficient: Contributor real behavior proof is sufficient. The updated PR body provides an after-fix AWS Crabbox Durable Object upgrade trace for the current head, including native SqlStorage, persisted legacy data, initialization, bounded expiry, replay, rollback, and cleanup verification.

Evidence

What I checked:

  • Additive schema change: The PR creates an idempotent single-column index immediately after creating the existing receipt table. (dashboard/github-webhook-read-model.ts:275, a5fdc6606095)
  • Preserved cleanup contract: Expiry still deletes at most 256 receipt GUIDs strictly before the 30-day cutoff in receipt-time order; the PR changes the access path, not the query semantics. (dashboard/github-webhook-read-model.ts:1208, a5fdc6606095)
  • Focused regression coverage: The added tests cover existing-database initialization, indexed query planning, bounded draining, strict cutoff, replay, tied timestamps, and rollback after pruning. (test/github-webhook-read-model.test.ts:93, a5fdc6606095)
  • Current-main necessity: Current main at 387cf82 does not contain the receipt-time index, so the central optimization is not already implemented or released. (dashboard/github-webhook-read-model.ts:275, 387cf82c7eba)
  • Current-head real behavior proof: The updated PR body and re-review request describe a passed AWS Crabbox Durable Object trace using native SqlStorage and the production initializer across persisted legacy-state restarts, including index creation, bounded expiry, replay, rollback, and cleanup controls. (a5fdc6606095)
  • Changelog policy scope: The repository contribution policy limits the release-owned changelog restriction to openclaw/openclaw target PRs and directs ClawSweeper PRs to this repository's release-note policy; the prior changelog finding is therefore not retained. (CONTRIBUTING.md:16, 387cf82c7eba)

Likely related people:

  • Jesse Merhi: Blame attributes the existing receipt-table schema and initializer to the original read-model commit. (role: introduced read-model behavior; confidence: high; commits: ad5cf512a448; files: dashboard/github-webhook-read-model.ts)
  • Vincent Koc: The current-main history includes recent work touching the dashboard read-model surface. (role: recent adjacent contributor; confidence: medium; commits: 387cf82c7eba; files: dashboard/github-webhook-read-model.ts)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (1 earlier review cycle)
  • reviewed 2026-08-27T03:02:56.381Z sha a5fdc66 :: needs real behavior proof before merge. :: [P3] Remove the release-owned changelog entry

@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

The main body now includes the passed actual workerd Durable Object upgrade proof for unchanged head a5fdc6606095eeadef03b15191043e95d7b68c85: native SqlStorage, the production ExactReviewQueue initializer, persisted legacy data across three process starts, index creation, bounded expiry, cutoff/dedupe/replay controls, transaction rollback, and verified cleanup. It ran on the repository-configured AWS Crabbox lane; the exact bootstrap and selected trace are included inline, with limits stated. Full exact-head CI and independent committed-branch review are green.

The changelog finding is rejected with the quoted repository scope: the release-owned rule applies to openclaw/openclaw, not this maintainer-authored openclaw/clawsweeper entry. No source, head, retention policy, timeout, or safety check changed in this proof update.

@clawsweeper

clawsweeper Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient Contributor real behavior proof is sufficient. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Aug 27, 2026
@steipete
steipete merged commit e4c442c into main Aug 27, 2026
29 checks passed
@steipete
steipete deleted the steipete/clawsweeper-webhook-expiry-index-20260826 branch August 27, 2026 04:14
@steipete

Copy link
Copy Markdown
Contributor Author

Merged the approved, unchanged head a5fdc6606095eeadef03b15191043e95d7b68c85 by squash as e4c442cbe5342b3e4b22999eac939baeed482266 at 2026-08-27 04:14:38 UTC, with actual parent 387cf82c7eba81fa6dfd1cff12765cf2c2d80a27. GitHub blob checks confirm all five approved production/test/proof/docs/changelog files are byte-identical in the merge. The intervening record-export change is disjoint from the index and initializer. Peter's authorship is preserved; no admin bypass or branch deletion was requested.

Before landing, fresh checks confirmed the exact head/body/discussion source revision, current durable review, no review threads or new findings, proof: sufficient, readiness for maintainer review, and mergeability. Independent precommit and committed-branch Codex reviews were clean. Existing validation includes 14 focused webhook tests, independently rerun by the parent, and successful exact-head CI 33035001782: full pnpm check, sparse repair build and Windows launcher, plus green CodeQL.

The real Node SQLite comparison measured median full-ingest wall time 2.603459 → 0.128625 ms (~20×) in the warm synthetic 100k-unexpired-receipt fixture, with preserved logical outcomes. This is a local fixture result, not a Cloudflare latency, throughput, billing or overload-recovery promise. The parent accepted the documented one-time index-build, storage and write-maintenance costs. Table/columns/constraints, 30-day retention, strict cutoff, ordering, LIMIT 256, replay and transactions remain unchanged. OpenClaw Bay needs no change because its public data and observer-only contract are unchanged.

The separate AWS Crabbox Durable Object proof passed on the approved head using the actual production ExactReviewQueue initializer, native SqlStorage and transactionSync. The same persisted legacy 1,000-row database survived process restarts; index creation, 256/256/88/0 cleanup, strict cutoff, dedupe/replay, transaction rollback/retry and idempotent reopening all passed. This was AWS-hosted local workerd, not a production Cloudflare load test or Docker/Testbox proof. The first proof attempt failed before workerd startup because of a runtime-version metadata lookup; the corrected bootstrap passed. A coordinator heartbeat timeout did not interrupt that successful run. Both sequential leases and all proof processes were released.

Limits remain explicit: the earlier local full check had 3,695 passed, 48 baseline fixture failures, 9 skipped, and was not rerun on the final head; it is not relabeled green. The durable review's auxiliary terminal-output assertion timed out and remains partial, rather than a claimed passing rerun; that review accepted the supplied native Durable Object evidence as sufficient. No new implementation or validation worker was started for this mechanical landing.

Automatic production rollout verified: normal push-triggered ClawSweeper Live Dashboard run 33038813458 completed successfully at 04:15:38 UTC; both Deploy Worker and Smoke test live dashboard passed. At 04:16:19 UTC, public health returned ok: true and deployment_sha: e4c442cbe5342b3e4b22999eac939baeed482266; remote main matched that SHA. No manual deploy, dispatch, rollback or queue/apply action was used. Merge-head CI 33038813473 is still in progress at this observation: pnpm check running, Windows successful, sparse repair skipped. Local source, refs and branches were left untouched for the active implementation worker and parent synchronization.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

merge-risk: 🚨 compatibility 🚨 Merging this PR could break existing users, config, migrations, defaults, or upgrades. P2 Normal priority bug or improvement with limited blast radius. proof: sufficient Contributor real behavior proof is sufficient. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant