Skip to content

perf(reef): attribute background plugin-state polling - #182247

Merged
steipete merged 6 commits into
mainfrom
dbasync/pluginstate
Oct 24, 2026
Merged

steipete merged 6 commits into
mainfrom
dbasync/pluginstate

Conversation

@steipete

@steipete steipete commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Reef repeatedly claims and releases replay state for inbound messages still waiting for review. Every retry writes the same available → in-flight → available cycle and repeats review/trust reads. A real isolated Gateway with bundled Reef and a loopback relay reproduces the live statement shapes, including empty scoped expiry deletes when an unrelated expired entry exists.

Design

Keep the existing watched review operation receipt in the flow's existing parked-entry state, bound to the exact envelope, effective policy, and envelope expiry. Unchanged pending polls assert the receipt and stay parked before replay/trust work. Review mutations invalidate the receipt, and approval, denial, policy/envelope changes, and expiry resume the full existing verification path. No SQL, schema, or public SDK signature changes.

The first retry after a newly created review can still observe and retain its pending receipt. This keeps the change within the existing owner contract. The old private lookup and forwarding adapter are removed.

Named accepted edge: Plugin-state epochs are process-local, so a review decision written by another process does not wake a parked entry until Gateway restart or the 30-day envelope expiry. This is accepted because decisions come only through the in-Gateway /reef review command: reviews.decide bumps the local epoch, invalidating the receipt so the entry is processed again. The edge is the same on SQLite and PostgreSQL.

Acceptance rule — registered before measurement

Run the bundled Reef channel in an isolated Gateway on the head under test, using a loopback HTTP/WebSocket relay, synthetic identities, and 18 queued messages with pending reviews. Run an empty inbox control. Separately exercise an expired entry in an unrelated synthetic namespace to identify expiry-sweep coupling. Preserve the real replay, trust, review, and state workers. No operator state or external services are used.

Count SQL statements and worker requests per retry and steady-state minute; report main-thread and total work separately. Keep boot/first delivery separate from warm polls. The first run attributes statement shapes to callers. Any change must preserve replay exclusion, pending-review decisions, TTL visibility, quota behavior, and supported other writers without a public SDK or schema change.

A win removes recurring work without increasing warm SQL, requests, or main-thread work. For wall-clock/CPU comparisons, run at least five alternating samples per arm and report median, p95, and range separately for cold and warm. Every user-facing metric must hold or improve; a 20% adverse cell stops the candidate. Timed comparisons acquire the campaign timing lock and require load below 24. Counts and profiles are independent of wall-clock qualification.

If current main does not reproduce the pattern, record the fixture, measured rates, and gap and stop that item. A direct-store microbenchmark is insufficient.

Evidence

Five alternating baseline/candidate samples used the committed real-channel workload with 18 synthetic pending-review envelopes, a 40-second settle and 60-second steady window. Each arm performs two unchanged inbox polls per warm minute. The baseline production source is 3a342c570186, built at d5c6ffab025 (its only diff from baseline is the preregistered workload document); the measured candidate runtime is 9ef9f874fd83. Final head ffd22dfb97cc changes only a test callback name; production and workload bytes are identical. The frozen comparison separately rebuilds the final head.

Run against each head's built entry and a fresh synthetic output directory; OBSERVER points to frozen v3.1.4. The first sample adds --profile; the empty control uses --messages 0 without --expired-peer.

node --import ./scripts/tsx.mjs scripts/perf/plugin-state-polling.mts \
  --entry "$ENTRY" --output "$OUT" --observer "$OBSERVER" \
  --seconds 60 --expired-peer
Steady minute, n=5 each Baseline median / p95 [min–max] Candidate median / p95 [min–max]
SQL statements 683 / 683 [683–683] 33 / 33 [33–33]
Worker requests 157 / 157 [157–157] 13 / 13 [13–13]
Main-thread SQL 0 / 0 [0–0] 0 / 0 [0–0]
Expiry probes 72 / 72 [72–72] 0 / 0 [0–0]
Scoped expiry deletes 72 / 72 [72–72] 0 / 0 [0–0]
Replay upserts 72 / 72 [72–72] 0 / 0 [0–0]
Keyed entry reads 148 / 148 [148–148] 4 / 4 [4–4]

The owner removes 648 SQL statements and 144 requests per minute, or 18 statements / 4 requests per pending message retry. Two passive checkpoints also disappear, making the measured total reduction 650 statements (95.2%) and 144 requests (91.7%). No work moves onto the main thread. Empty-inbox controls match at 33 statements / 13 requests / 0 main-thread SQL, and all samples preserve two polls with zero acknowledgments or unexpected requests.

Cold startup plus initial settle, n=5 each Baseline median / p95 [min–max] Candidate median / p95 [min–max]
SQL statements 1734 / 1736 [1729–1736] 1081 / 1090 [1080–1090]
Worker requests 419 / 420 [416–420] 273 / 278 [273–278]
Main-thread SQL 54 / 54 [53–54] 53 / 54 [53–54]

Captured 24 V8 thread profiles per first arm. These cover the complete process lifetime, including startup; the baseline exposes compare/apply, expiry-delete and replay-write work. Timing qualification waited more than 60 minutes, first for host load and an occupied lock, then for load below 24. The coordinator explicitly accepted the counts-plus-per-thread-profiles fallback on October 24; this PR makes no latency or CPU-speedup claim. Frozen v3.1.4 hashes pass (36 files). The first frozen baseline attempt stopped during synthetic account setup because its copied local stamps retained the documentation commit identity; it never started a Gateway and is not behavioral evidence. The replacement uses freshly built exact-baseline and final-head runtimes and verifies matching build-info/stamp identities plus native preparation before either frozen arm. The host-app restart interrupted its first baseline during idle; that incomplete sample is retained separately and excluded. Both resumed frozen arms completed all 14 turns, subagent, cron, compaction, shutdown and restart checks. The candidate needed a normal runtime-postbuild refresh for one missing Reef overlay after switching from baseline; exact commit identities were unchanged, and native preparation then reported build=false/runtime=false. All fixture children exited and all fixture ports closed. Knip reports 48 production / 43 full-tree / 6 script occurrences, with zero new entries. Production/full-tree results match reused same-base archive scans (whose dependency links can resolve candidate sources); all 35 reported files are byte-identical to baseline. The script scan was independently reproduced on the exact baseline in this worktree.

Frozen v3.1.4 control pair — accepted background placement

One completed alternating base/final-head pair, with a 60-second connected-idle window. This frozen control disables channels; the five-pair Reef reproduction above remains the owner-flow evidence. The raw comparison has three STOP cells: boot SQL 305→552 (+81.0%), boot requests 100→132 (+32.0%), and turn-03 requests 12→15 (+25.0%). The October 24 acceptance disposition explicitly accepts these cells as existing background-placement scatter, conditional on proving no Reef SQL executes in the frozen candidate. That condition is now verified below; it is separate from the accepted timing fallback.

Totals are 2,901→2,916 SQL (+15), 778→781 requests (+3), and 95→96 MAIN (+1). The following table reports the single observation in each arm, not a multi-sample estimate; each cell therefore also has identical median/p95/min/max. All cells, including smaller adverse moves, are retained.

Phase SQL base→candidate Requests base→candidate MAIN base→candidate
01.boot 305→552 100→132 49→49
01.connect 191→39 10→8 0→0
02.first-turn 284→202 94→68 0→0
03.turn-01 51→51 13→12 0→0
03.turn-02 61→62 19→20 0→0
03.turn-03 55→63 12→15 0→0
03.turn-04 55→45 15→11 0→0
03.turn-05 45→46 11→12 0→0
03.turn-06 45→45 11→11 0→0
03.turn-07 46→45 11→11 0→0
03.turn-08 45→46 11→11 0→0
03.turn-09 45→46 11→11 0→0
03.turn-10 46→45 11→11 0→0
04.second-session 489→489 119→119 0→0
05.control-plane 7→7 1→1 0→0
06.cron 241→242 64→64 0→0
07.compaction 142→142 26→26 0→0
07.idle-connected 74→79 28→30 0→0
07.idle-settle 108→103 17→14 0→0
08.shutdown 22→22 6→6 5→5
09.restart-boot 329→329 121→119 36→37
09.restart-connect 31→26 15→13 0→0
10.restart-first-turn 162→168 46→50 0→0
11.restart-shutdown 22→22 6→6 5→5
TOTAL 2901→2916 778→781 95→96

Retained-ledger attribution shows substantial phase movement, but does not establish a complete offset: boot gains 247 SQL while connect loses 152 and first-turn loses 82 (combined +13). Boot agentDatabaseDeletion.snapshot gains 14 SQL/3 requests and first-turn loses exactly 14/3; other startup operations move similarly, while some work is genuinely additional in this sample. The turn-03/turn-04 boundary moves six lease reads, one lease delete, and one two-event audit insertion into turn-03. Whole-run operation differences include one additional proactive-jobs request and one additional lifecycle-artifact-plan request. Restart MAIN adds one session_key_contract.canonical_ready read. The retained candidate ledger identifies its owner as loadOpenClawAgentCanonicalValidationReceipt (src/state/openclaw-agent-canonical-validation-receipt.ts), called by certifySessionCanonicalValidationPending from runSessionStartupMigration. This is session canonical-validation startup maintenance, outside Reef. The same receipt reader executes on base at ledger indices 628 (first-turn), 2289 (compaction), and 2431 (idle-settle), all worker-thread reads; candidate index 2400 is the restart MAIN read. The receipt owner, readiness module, and startup migration module are byte-identical between base and the approved head. This does not claim a baseline restart MAIN read.

The retained frozen candidate has zero Reef SQL stacks: all 2,916 executed statement entries have captured fullStack/originStack, with zero extensions/reef matches. An independent pass over the raw observer records resolves executed site references and excludes prepare-only records: zero matches across 2,720 executed SQL sites (2,761 calls, expanded by the ledger to 2,916 statements). Base likewise has zero matches across 2,901 ledger statements. This satisfies the acceptance disposition without another run; no CPU or latency claim is made. Exact-head PostgreSQL review is approved for ffd22dfb97cc.

  • Reef owner suites: 66/66 pass on pinned Bun. The isolated regression is behaviorally red on baseline (three replay claims instead of two) and all five candidate cases pass. Approval/denial, envelope/policy/expiry changes, sibling-handle invalidation, persistence, TTL and capacity remain covered.
  • Plugin-state operation receipt contracts: 13/13 pass. Local PostgreSQL shared-feature/schema conformance passes (133 state and 45 agent tables with catalog/index/check/trigger parity). This is generic conformance, not direct Reef PostgreSQL-flow proof.
  • Final independent Codex review: scoped clean after two rounds. The old private lookup and forwarding adapter are removed.
  • Required final-head openclaw/ci-gate passes, including types, lint, source/export contracts, Madge architecture and ratchets. T1 remains 170→170, compatibility 15→15, and dialect categories 0→0. Local declaration preparation rejects the mandated out-of-checkout pnpm virtual store; no containment bypass was used.
  • Separate, non-required Rust workspace CI fails Clippy on the unchanged 111-line native_signed_connect_preserves_product_fields_and_rejects_invalid_node_manifests test. The affected file is byte-identical to the baseline; this is not claimed as an executed main-branch failure.

Production delta is +41 lines: the existing parked Set becomes a receipt-bearing Map with exact-envelope/policy/TTL binding. No new generation, timer, schema, or generic state cache. A generic expiry-sweep redesign is unnecessary for this producer: eliminating the repeated calls removes its probes, deletes and writes together. The frozen-control disposition and exact-head PostgreSQL approval are satisfied for ffd22dfb97cc; no source changes were made after that approval.

Open-PR conflict comparison (55 overlapping main PRs)

Compared base 3a342c570186 and candidate ffd22dfb97cc against each pinned head from 2,657 open main PRs. All 55 overlapping heads are unchanged from the completed exact-head comparisons, which add zero conflicting paths and zero conflict hunks.

PR Pinned head Added paths / hunks
#182104 b5cf2ab14490 0 / 0
#174900 cb69b03e9c46 0 / 0
#174317 4a92429c25c6 0 / 0
#171315 d9b6e3ff2055 0 / 0
#171189 5aed8180f8ba 0 / 0
#162989 86fa13012988 0 / 0
#162287 ecf01c151961 0 / 0
#161357 871d6381c5f1 0 / 0
#161322 022433d1daa3 0 / 0
#161315 0117a21b6dc3 0 / 0
#160908 6e1aba7c8c29 0 / 0
#160868 5ca7f4ecaca0 0 / 0
#159678 43276169ca3f 0 / 0
#159255 6a4070accd3b 0 / 0
#158558 804b31748af9 0 / 0
#157860 b4e164f08f6e 0 / 0
#156924 fc5d1d5c8370 0 / 0
#156522 5ea5656d2577 0 / 0
#156383 a359e092e3ad 0 / 0
#156348 c4edc655fa8a 0 / 0
#156200 e3f591d1333d 0 / 0
#155667 1aa70ab0c258 0 / 0
#153113 bf0232649376 0 / 0
#151924 d0f38d4f06f5 0 / 0
#151346 622762b3ba98 0 / 0
#148530 116130492c08 0 / 0
#147886 cf24913fc0e9 0 / 0
#144984 e7efb8c99265 0 / 0
#143015 06dfd0889535 0 / 0
#141305 a113687985e3 0 / 0
#137300 a7c456b504a2 0 / 0
#137097 5424e93c0382 0 / 0
#135400 27eb8ed0000d 0 / 0
#134173 45ee899f426a 0 / 0
#129388 f4675cff003d 0 / 0
#125913 e721d349d2b6 0 / 0
#121204 248cf1774a21 0 / 0
#181528 0f97a98b4c35 0 / 0
#180935 ddf42e31bd57 0 / 0
#178125 511587cf101d 0 / 0
#177863 10bb769a218b 0 / 0
#174074 27a7b13237eb 0 / 0
#172450 ae122ad86db5 0 / 0
#172232 fc15ce824c0d 0 / 0
#171389 b3edf2583347 0 / 0
#171383 a03482c1deee 0 / 0
#169820 87f58c6a9b4c 0 / 0
#168797 5ebed9858af6 0 / 0
#167569 65196c9a6b23 0 / 0
#165078 c3677719ea19 0 / 0
#160873 28dfc4980b5e 0 / 0
#159178 57cd0bcdb90a 0 / 0
#159143 e22c8de5acf8 0 / 0
#146651 a727f6161413 0 / 0
#111020 b611cb2f0396 0 / 0

@clawsweeper

clawsweeper Bot commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added scripts Repository scripts size: XS labels Oct 24, 2026
Carry the existing watched review receipt in parked inbox state. A decision mutation, policy or envelope change, or expiry resumes the normal trust and replay path. Avoid repeated replay claims and releases while an owner review is pending.

Release note: reduce background SQL and worker requests for Reef messages waiting on owner review. No schema or public Plugin SDK change.
@openclaw-barnacle openclaw-barnacle Bot added channel: reef Channel integration: reef size: L and removed size: XS labels Oct 24, 2026
@steipete
steipete marked this pull request as ready for review October 24, 2026 05:12
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-24T05:23:47.280366Z 5f0fb1e New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 24, 2026
@clawsweeper

clawsweeper Bot commented Oct 24, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR retains watched pending-review receipts so unchanged Reef inbox polls skip repeated trust reads and replay writes.

Example: An isolated Gateway polls 18 Reef messages awaiting owner review.

  • Before: The reported baseline performs 683 SQL statements and 157 worker requests per warm minute.
  • After: The first reported candidate performs 33 SQL statements and 13 worker requests, with messages still parked.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) A focused, source-supported optimization with useful regression coverage; the reported runtime measurements are preliminary and their final acceptance results remain pending.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored PR is outside the ordinary contributor proof gate; its body reports bundled Reef running in an isolated Gateway against a loopback relay with real workers and reduced warm statement counts, while final measurements remain unfinished.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Reef consumes repeated database and worker work while messages are waiting for an owner decision.
Reason: The maintainer-authored direction addresses measured recurring work using existing state ownership and preserves the documented review behavior.

Merge readiness

✅ Ready for maintainer review

Keep this PR open: it removes identifiable recurring Reef database work, preserves the review owner’s decisions, and has no concrete introduced correctness finding; the author’s explicit landing hold remains.

Priority: P2
Reviewed head: ffd22dfb97ccae1d933e5ab10953df4e5abcea11

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The final alternating Gateway measurements and frozen warm-path checks remain marked in progress; the inspected prepared images concern other PRs.
Agent review details

How this fits together

Reef receives encrypted envelopes from the relay, consults trust, replay and review state, and either parks them or proceeds through verification to ingress and acknowledgment.

flowchart TD
  A[Relay inbox poll] --> B[Reef message flow]
  B --> C[Watched pending review receipt]
  C --> D[Remain parked]
  C --> E[Full trust and replay verification]
  E --> F[Review and guard decision]
  F --> D
  F --> G[Ingress and acknowledgment]
Loading

Technical review

Best possible solution:

Retain pending receipts in the existing parked-entry owner while preserving full verification whenever their binding or validity changes.

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

Current main enters composeInbound on each pending retry, claiming and releasing replay state before returning the pending outcome; the author also reports reproducing these statement shapes through an isolated Gateway.

Is this the best way to solve the issue?

The change follows the existing ownership contract by carrying the review owner’s watched fact, removing its forwarding adapter, and avoiding new schemas, generations or parallel decision owners.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 4e62be1ab7fd.

Provenance checked

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

PR surface

Source +41, Tests +113, Docs +29, Other +363. Total +546 across 8 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 2 63 22 +41
Tests 4 148 35 +113
Docs 1 29 0 +29
Config 0 0 0 0
Generated 0 0 0 0
Other 1 363 0 +363
Total 8 603 57 +546

Review metrics

Metric Value Why it matters
Runtime production versus tests Runtime production +63/−22 lines; Reef tests +147/−35 lines The net 41 runtime lines carry existing owner receipts and their envelope, policy and expiry binding; the tests cover repeated replay writes and invalidation boundaries.

Labels

Label changes:

  • add P2: This reduces recurring background database work for Reef messages waiting on review without establishing an urgent availability or delivery regression.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P2: This reduces recurring background database work for Reef messages waiting on review without establishing an urgent availability or delivery regression.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Complete the declared Gateway measurement campaign and publish its final results.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed October 24, 2026, 1:49 AM ET / 05:49 UTC.

@steipete
steipete merged commit dc3ce57 into main Oct 24, 2026
166 of 167 checks passed
@steipete
steipete deleted the dbasync/pluginstate branch October 24, 2026 07:09
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 25, 2026
* docs(perf): preregister plugin-state polling workload

* perf(reef): skip unchanged pending-review retries

Carry the existing watched review receipt in parked inbox state. A decision mutation, policy or envelope change, or expiry resumes the normal trust and replay path. Avoid repeated replay claims and releases while an owner review is pending.

Release note: reduce background SQL and worker requests for Reef messages waiting on owner review. No schema or public Plugin SDK change.

* fix(perf): satisfy polling workload lint rules

* test(reef): isolate pending-review regression coverage

* test(reef): route receipt regressions through the database broker

* test(reef): avoid shadowing the observed review receipt

Co-authored-by: Peter Steinberger <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

channel: reef Channel integration: reef P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts size: L 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