Skip to content

fix(cron): avoid loading off-page history payloads - #174175

Merged
steipete merged 2 commits into
mainfrom
dbasync/cronpage
Oct 16, 2026
Merged

steipete merged 2 commits into
mainfrom
dbasync/cronpage

Conversation

@steipete

@steipete steipete commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Cron history loaded every matching run's full retained JSON before paging, so a small summary page could read tens of megabytes of diagnostics, delivery traces, and recovery state.

User Impact

History pages load response details only for the selected runs. Completion ordering, offsets, exact totals, search, notification links, and session visibility retain their existing semantics. Summary reads omit diagnostics and delivery traces at the SQL boundary.

Why This Change Was Made

The existing indexes order by (created_at, task_id), but public history orders by completion time and uses locale-aware identity ties. Changing the public order or introducing a schema migration would be a larger contract change. The reader therefore scans only selection metadata in bounded, indexed keyset batches, selects the page with the existing codec, and hydrates its IDs with a bounded SQL query. Diagnostic search evaluates one batch at a time and retains match identities rather than diagnostic payloads. Exact totals still require a metadata scan; this is a payload reduction, not constant-time pagination.

The existing read worker owns all SQL. The former full-history asynchronous read is removed; the full-record kernel remains only for write, recovery, and retention responsibilities that need those facts. Shared engine JSON projection helpers and tuple comparisons keep new SQL portable.

Disclosure authority and session visibility are checked after hydration. Ordinary concurrent removal can shorten a page until refresh, and concurrent job renaming can leave search matches based on the captured name until refresh. Neither requires a generation or retry handshake.

Removed checks and accepted edges:

  • History reads no longer revalidate retained scope_kind, notify_policy, delivery_status, or terminal_outcome enums: malformed unused bookkeeping fields no longer reject an otherwise readable history entry.
  • History reads no longer revalidate the retained task status enum: the existing timestamp normalization and public history codec consume the stored facts; write/recovery admission retains its validation.
    The live caller/session disclosure check remains because it protects a security boundary.

Evidence

  • T1 in the touched history-read area: 0 -> 0. The new database module is worker-only; no Gateway main-thread SQL is added.
  • Focused tests pass: 30 cron owner tests (history 11, queue 10, recovery 9), all nine Gateway history cases, three publication cases, and validation tests. Coverage includes real-storage binding changes during hydration removing both entries and totals, hidden-key errors, archived bindings, notification links, raw-keyset versus normalized timestamps, completion order, page byte bounds, and write freshness. The new disclosure test initially had a response-tuple assertion mistake; its corrected focused replay passes. No production test failure remains.
  • Synthetic scale proof: all 18 shapes pass 126 exact-base response comparisons over 144 owner calls. Fixture: 7,312 rows, 112 jobs, largest job 2,059; synthetic content only. The 300.9 MB fixture has been deleted.
  • Harness v3: all three alternating pairs completed (M1,C1,M2,C2,M3,C3), each passing 14 turns, cron, compaction, restart and both shutdowns. Base 594e35ed589d, measured candidate 0c9ff57d5bd; pinned Node 24.22.0 / SQLite 3.54.0, unchanged harness, compile cache disabled. Final-head reuse is explained below. No warmed-turn or latency improvement is claimed.
  • Codex autoreview: two rounds, both scoped-clean through P2; the second includes complete unchanged search and timestamp helpers. Final-head CI 38897832754 passes the changed tests, types, lint, source contracts, Madge, T1 and dialect gates. The repository Knip export scan has zero production or script findings. Its two full-tree UI test-helper findings (proofCapture and renderActivityGroup) reproduce exactly on the tested main parent c489e8ce0a85; no findings are introduced, and both are already tracked for repair.
  • No SDK, schema, migration, update, Doctor, plugin-loading, or service-lifecycle contract change; SDK diff and published-driver update cell do not apply.

Payload and query evidence

The table reports logical database-cell bytes returned by the driver, not physical disk I/O. Response bytes exclude the RPC envelope and are identical before/after. Base: 594e35ed589d1441bc3d4d1304c8aae9bd09a55f.

Page Database bytes before After Response bytes Owner SQL before → after
All jobs, first, full 290,081,377 5,334,100 2,975,239 1 → 18
All jobs, deep, full 290,081,377 5,331,539 2,972,566 1 → 18
Largest job, first, full 81,693,621 2,155,432 1,487,541 1 → 8
Largest job, deep, full 81,693,621 2,155,292 1,487,528 1 → 8
All jobs, first, summary 290,081,377 2,668,238 309,377 1 → 18
All jobs, deep, summary 290,081,377 2,665,682 306,709 1 → 18
Largest job, first, summary 81,693,621 822,582 154,691 1 → 8
Largest job, deep, summary 81,693,621 822,118 154,354 1 → 8
Single run, full 81,693,621 674,852 14,978 1 → 8

All-job summary pages return 99.08% fewer database bytes; largest-job summary pages return 98.99% fewer. The added SQL is explicit: 15/five indexed metadata batches, two snapshot statements, and one hydration query. Hydration adds one worker request for a nonempty page; the Gateway harness confirms that cost. This is a payload reduction with a statement/request tradeoff, not a warmed-turn SQL-saving claim.

EXPLAIN uses the existing runtime/source (created_at, task_id) range indexes and the task-ID primary key for hydration. No OFFSET or temporary ordering B-tree is used. Exact totals and completion sorting still require all matching metadata; deep offsets do not add work.

All five search scenarios retain their diagnostic/delivery matching semantics, reduce database bytes by about 63.1%, and increase median measured CPU by 6.2–19.8% on this fixture. Ordinary pages and single-run reads use less measured CPU. Search remains the deliberate CPU tradeoff for bounded retained payloads.

Native query elapsed observations (three alternating samples, median [min–max] ms) were: all-first summary 536 [523–657] → 1,388 [996–1,964]; all-deep summary 509 [446–555] → 1,081 [881–1,543]; largest-job first summary 39 [38–50] → 142 [112–153]; largest-job deep summary 59 [54–74] → 191 [136–213]; single full run 94 [48–140] → 165 [101–186]. These are noisy observations from a loaded host (load approximately 82 on 32 CPUs), not latency or speedup evidence. A quiet remote allocation queued and was canceled without running a payload.

LOC: 13 files, +809/−146 overall; production TypeScript +396/−105 (net +291). The added code owns bounded metadata selection and page-only hydration; it replaces the full-history async reader. All six Gateway harness arms are complete; counts follow below.

CI correction: 31224243e9b fixes two TypeScript narrowing errors found on the first CI run. It validates the captured job-name map once and annotates a synthetic tuple as readonly; formatting and type-aware lint pass. The harness remains pinned to 0c9ff57d5bd, whose accepted-input SQL and dispatch path is unchanged by the correction. The first run also found an inherited src/media/media-facts.ts assertion allowance mismatch (14 actual versus 16 allowed), independently reproduced on its main base; the final-head CI is now green after main corrected that allowance. No CI bypass is needed.

Final-head CI tested merge 4468b83bfd81edffdafdecda09f771fb3741f614 (main c489e8ce0a851563b61bbd806adc5e4c5063036b plus PR 31224243e9bd5f073cd6096f6cd997e74a026c4c). Global T1 remains 222 → 222; all changed dialect groups remain 0 → 0.

Final Gateway measurements

Values are median [min–max], SQL / requests / MAIN. Warm rows pool 30 turns per side; other rows summarize three complete runs per side. Fixture setup is excluded.

Scope Base Candidate
Warm turn (causal) 72 [72–78] / 25 [25–27] / 0 [0–0] 72 [72–79] / 25 [25–28] / 0 [0–0]
Warm turn (raw) 72 [72–107] / 25 [25–29] / 0 [0–13] 72 [72–97] / 25 [25–33] / 0 [0–9]
Boot + connect + first 1430 [1423–1439] / 260 [258–265] / 80 [72–81] 1429 [1413–1435] / 258 [254–265] / 72 [71–72]
Restart combined 773 [765–806] / 228 [228–229] / 83 [83–83] 808 [805–809] / 229 [229–236] / 83 [83–83]
Observed workload (fixture setup excluded) 4126 [4107–4134] / 1077 [1072–1079] / 186 [185–186] 4154 [4142–4158] / 1082 [1075–1084] / 186 [185–186]

Each pair has causal warm medians of 72 SQL / 25 requests / 0 MAIN on both sides. Per-arm whole-workload totals:

Arm SQL Requests MAIN
M1 4126 1072 185
C1 4142 1082 186
M2 4134 1079 186
C2 4158 1084 185
M3 4107 1077 186
C3 4154 1075 186

Normalized history operation cost on the small harness fixture: an empty page changes from 1 → 3 SQL / 1 → 1 request; a nonempty page changes from 1 → 4 SQL / 1 → 2 requests. MAIN stays zero. Poll counts vary with completion timing; matched pair two uses three polls [0, 0, 1] and changes from 3 SQL / 3 requests to 10 SQL / 4 requests. No history operation runs inside the warmed chat windows.

Whole-workload medians rise by 28 SQL (+0.68%) and five requests (+0.46%), with unchanged MAIN. The bounded history reads intentionally add queries and one nonempty-page request. Restart-combined SQL rises by 35 at the median: an unchanged session-transcript projection publication operation contributes 34 statements in M1 and all three candidate runs, but not M2/M3. The trigger correlation is unresolved; this increase is disclosed, not classified as noise or attributed to a saving. Raw warm MAIN comes from existing background work; causal warm MAIN is zero throughout.

All six warmed shared-read-family histograms match: exact-entry facts, actor hydration, full entry-cache snapshots, row database facts and dedicated watermarks are zero; exact-entry candidate reads are 0.2 per turn, qualified session-node reads two per turn, and combined transcript-context reads one per turn. These owner-frame categories can overlap and are not summed. Native causal SELECT/WITH histograms match exactly within pairs two and three; pair one adds one auth-profile read across ten candidate turns. Family-specific request counts are not inferred from SQL frames.

Merged as afe03ab7249237d27a09f53605cca3907e442ab9. The landed patch exactly matches the reviewed final head. Native merge initially refused on a pending rollup projection despite green checks; a fresh native retry succeeded without REST fallback or CI bypass.

Scan selection metadata in indexed keyset batches and hydrate only the
requested history page through the existing read worker. Preserve public
completion ordering, exact totals, search, notification links and live
session-disclosure checks. Summary reads omit diagnostics and delivery
traces before crossing the database driver.

Synthetic 7,312-run proof preserves every tested response while reducing
all-job summary database values from 290 MB to 2.67 MB. Metadata batching
adds statements and page hydration adds one request; this is a payload
reduction, with no warmed-turn SQL-saving claim. Concurrent deletion may
shorten a page and captured-name search may lag renaming until refresh.
@clawsweeper

clawsweeper Bot commented Oct 16, 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.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 16, 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-16T11:38:47.440797Z 0c9ff57 PR opened
ℹ️ 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.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime size: L labels Oct 16, 2026
@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 16, 2026
@clawsweeper

clawsweeper Bot commented Oct 16, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR selects cron history using lightweight metadata and loads response payloads only for the requested page.

Example: Request a two-entry summary page from 520 diagnostic-heavy runs.

  • Before: The reader loads every run's full retained JSON before selecting two entries.
  • After: The reader scans selection metadata and hydrates two entries without their diagnostic or delivery traces.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The source change is coherent and useful, with substantial owner-level evidence; shipped-entry-point measurements are absent and exact-head CI failures remain unclassified.
Proof confidence 🦐 gold shrimp (3/6) The maintainer-authored PR is outside the ordinary contributor proof gate; supplied evidence covers synthetic real-storage owner calls and registered-handler disclosure tests, while the advertised Gateway workload measurements remain pending.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: A small cron history page loads off-page diagnostics, delivery traces, and recovery payloads.
Reason: The existing history owner can avoid substantial unnecessary payload acquisition while preserving its wire contract, and the maintainer-authored PR explicitly accepts the query tradeoff.

Merge readiness

✅ Ready for maintainer review

Keep this PR open: it addresses a concrete history-read payload problem that remains on current main, and the reviewed diff introduces no definite correctness or security defect.

Priority: P2
Reviewed head: 0c9ff57d5bd3ea31c44d0ad02cba15a6fa3d0c2f

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The supplied evidence does not show the changed reader through a shipped Gateway or CLI, or demonstrate the new payload-bound regression failing on the base.
Agent review details

How this fits together

Cron history RPCs read retained task_runs through the existing SQLite worker, apply caller visibility and pagination, and return history pages or transcript bindings.

flowchart TD
  A[History RPC request] --> B[Current job and visibility facts]
  B --> C[Worker metadata scan]
  C --> D[History page selection]
  D --> E[Worker page hydration]
  E --> F[Final authority and visibility checks]
  F --> G[History response]
Loading

Technical review

Best possible solution:

Land the existing-worker metadata selection and page hydration approach after the failing checks are resolved or conclusively attributed upstream.

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

Current-main source loads full detail_json for matching cron rows before pagination; the author also supplies synthetic before/after database-cell measurements, but this review ran no target code.

Is this the best way to solve the issue?

The approach preserves the existing completion-order and visibility owners, avoids a schema change, and explicitly accounts for the added query cost.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 9afcbdfea3cc.

Provenance checked

  • History ordering and visibility-aware pagination keeps the original intent (fix(cron): paginate history after session visibility filtering #136043: Filter visible history before sorting, counting, and slicing so restricted callers receive correct pages and totals.)
  • Worker-owned history acquisition keeps the original intent (refactor(cron): read run history through its worker #158222: Move history SQL off the Gateway thread while preserving response semantics and final authority checks.)
  • Compact transcript binding keeps the original intent (perf(cron): compact worker replies for run transcripts #163885: Return compact transcript identities while retaining cursor binding and publication checks; database acquisition was explicitly outside that earlier change.)
  • Read-side retained-enum validation changes intended behavior with a stated reason (6652f7e: The Cron-owned kernel retained released-row admission during Tasks removal; this PR explains why display reads now consume only relevant facts while write and recovery admission keep validation.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

  • Pinned change and current-main comparison: The introduced diff replaces the full-history asynchronous reader with candidate selection and page hydration; fetched main retains the original full-history path. (src/gateway/server-methods/cron-runs.ts:117, 0c9ff57d5bd3)
  • Bounded payload acquisition: The worker scans metadata in 512-row keyset batches, preserves raw indexed cursor values, and hydrates selected task IDs using view-specific JSON projections. (src/cron/store/run-history-read.worker.ts:99, 0c9ff57d5bd3)
  • Final disclosure boundary: After hydration, the handler checks current client/runtime authority, reconstructs current visibility, and filters hydrated records before responding; the added real-storage regression exercises a binding becoming hidden during hydration. (src/gateway/server-methods/cron-runs.ts:145, 0c9ff57d5bd3)
  • Accepted performance tradeoff: The maintainer-authored body explicitly accepts additional statements and worker requests, increased search CPU, transient short pages after deletion, and captured-name search until refresh; it claims payload reduction rather than latency improvement. (0c9ff57d5bd3)
  • Exact-head CI remains blocked: Production types, core test-types stripe 5, baseline ratchets, and the aggregate gate fail. Available annotations identify baseline complaints outside the introduced files but do not establish complete attribution. Detailed type logs redirect to a storage host blocked by this environment. (0c9ff57d5bd3)
  • Related maintenance failure is separate: cron.maintainHistory unbounded .all() over task_runs payload → SQLite worker OOM loop at 512MB (after #166581) #174078 concerns the full-record retention/recovery reader; this PR intentionally retains that kernel and does not fix its worker-OOM path. (src/cron/store/run-history.kernel.ts:75, 0c9ff57d5bd3)

Likely related people:

  • Peter Steinberger: Raw commit 4d90529 adds src/cron/task-run-history.ts:121 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 4d9052929bcc; files: src/cron/task-run-history.ts)
  • Vincent Koc: Raw commit 467fc82 adds src/cron/store/read-only.worker.ts:23 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 467fc82c4fd9; files: src/cron/store/read-only.worker.ts)

PR surface

Source +289, Tests +362, Docs +10. Total +661 across 13 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 7 394 105 +289
Tests 5 403 41 +362
Docs 1 10 0 +10
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 13 807 146 +661

Review metrics

Metric Value Why it matters
Production versus test changes Production TypeScript +394/−105; tests +403/−41 Production growth implements metadata selection and page-only hydration while removing the full-history asynchronous reader; tests cover payload bounds, ordering, freshness, and disclosure.

Labels

Label changes:

  • add P2: This reduces unnecessary retained-payload allocation during cron history reads without changing public defaults or introducing an established urgent user-facing 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 unnecessary retained-payload allocation during cron history reads without changing public defaults or introducing an established urgent user-facing 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.

  • Resolve or establish upstream attribution for the failing exact-head type and baseline checks.

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 16, 2026, 7:54 AM ET / 11:54 UTC.

@steipete
steipete merged commit afe03ab into main Oct 16, 2026
128 checks passed
@steipete
steipete deleted the dbasync/cronpage branch October 16, 2026 12:45
@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 17, 2026
* fix(cron): avoid loading off-page history payloads

Scan selection metadata in indexed keyset batches and hydrate only the
requested history page through the existing read worker. Preserve public
completion ordering, exact totals, search, notification links and live
session-disclosure checks. Summary reads omit diagnostics and delivery
traces before crossing the database driver.

Synthetic 7,312-run proof preserves every tested response while reducing
all-job summary database values from 290 MB to 2.67 MB. Metadata batching
adds statements and page hydration adds one request; this is a payload
reduction, with no warmed-turn SQL-saving claim. Concurrent deletion may
shorten a page and captured-name search may lag renaming until refresh.

* fix(cron): preserve worker history type narrowing
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation gateway Gateway runtime P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. 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