Skip to content

perf(storage): shrink Run writes and retire redundant products - #1187

Merged
XuPeng-SH merged 3 commits into
matrixorigin:mainfrom
XuPeng-SH:perf/persistence-wave2
Oct 31, 2026
Merged

XuPeng-SH merged 3 commits into
matrixorigin:mainfrom
XuPeng-SH:perf/persistence-wave2

Conversation

@XuPeng-SH

@XuPeng-SH XuPeng-SH commented Oct 31, 2026 •

Copy link
Copy Markdown
Collaborator

Capability assessment: Updated: retire legacy Context/Decision CRUD, Server harness snapshot history/SSE/admin controls, and personal-skill self-report evaluation; retain canonical Context/Run custody, decision trace, reflection, skill activation, harness enforcement and CLI inspection. Update API/configuration, storage contracts and system capability coverage for all supported profiles.

Summary

Frequent Run frontier and lease writes currently carry opening and checkpoint bodies through the mutable control row. This change moves immutable opening data to one owned row per Run and makes run_checkpoints the sole checkpoint-body owner, with an exact current ID/version/digest reference on agent_runs. Summary/control readers avoid loading cold bodies. Opening admission, checkpoint updates, Context work, fences and rollback stay within their existing transaction owners.

Remove five complete redundant persistence/product chains: generic Context snapshots, legacy Decision audits and their aggregation, durable Server harness snapshots and live snapshot APIs, duplicate skill-activation state events, and skill self-report evaluation. Remove their handlers, configuration, clients, readers, cleanup, fixtures and documentation together. Canonical activity, Context, policy, model usage, skill activation and harness verifier enforcement remain exercised through retained product paths.

Also remove three unused secondary indexes after actual query-plan controls, eliminate redundant guarded-action and guidance reads, and batch two existing commit-reconciliation loops with positional identity/byte bounds. The main append preflight was already batched; this does not claim to remove an N+1 there. Recovery keeps per-row locks because multi-row locking semantics were not sufficiently proven.

Related issue

Refs #1186. The issue remains open for the broader sustained-capacity matrix; this PR does not mark that acceptance complete.

Change type

  • Refactor or performance improvement
  • Bug fix
  • Documentation
  • Test

User and compatibility impact

Requires a fresh database. No migration, backfill, old-format reader or compatibility branch is provided. The schema marker stays at v116; startup requires the new shape and rejects the former shape even with the same marker.

Retired HTTP products return 404. Normal reports remove the retired fields/source rather than presenting empty counts or internal implementation warnings. Resume and conversation failures retain their status/code contracts and provide actionable messages; technical detail stays in logs. An unreadable saved checkpoint cannot execute or masquerade as a recoverable concurrent change.

Architecture and complexity delta

  • Canonical owner changed or extended: agent_runs remains mutable control; agent_run_openings owns opening bodies; run_checkpoints owns checkpoint bodies. A nullable triple represents the exact current reference. Full-reader validation and explicit unloaded opening state remain distinct from absence.
  • Existing implementations and callers searched: Run admission/append/action/checkpoint/recovery/terminal, Context coordinator, Session lists/conversation/delete, reflection/introspection, skill activation, Server/CLI harness, routing and thin clients.
  • Superseded code, states, tables, shims, or self-only tests removed: five complete chains and five tables; one narrow opening table added (121 → 117 declarations). Three secondary indexes removed. No new runtime state machine or persistence worker.
  • If parallel implementations remain, their boundary and retirement condition: no duplicate opening/checkpoint body owner. The existing bounded, process-local harness sink serves root and observe-only children; it does not add database writes or a replacement history product.

Verification

  • Historical evidence on the prior head (reconciled below): cargo fmt --all -- --check, git diff --check; schema inventory's 45 tests; affected eight-package all-target Clippy with warnings denied. 16,448 offline tests passed without retries under the repository's strict profile; subsequent review corrections receive the scoped normal/database checks recorded below.
  • Public entrypoint exercised: ordinary chat cold/warm/held-control, Session conversation, decision trace/reflection, personal-skill activation, retired-route 404 contracts, full product journey, configured Server harness, actual fork skill, feature-disabled harness and CLI inspection.
  • Unhappy paths exercised: missing opening, exact-current versus latest-history checkpoint, A→B→A, immutable handoff semantic replay preserving stored bytes, corrupt/oversized progress, rollback, unknown ACK, stale owner/generation, cancellation/delete races, optional agent identity, wrong Session, index overflow, bounded UTF-8 reconciliation, and independent concurrent appends/claims.
  • Database verification: MatrixOne 4.2.6; 96 services unit DB cases, 28 batch DB cases, three metadata/pagination delta cases, and runtime groups of 43 + 7 + 1 cases passed. Fresh bootstrap/idempotence and old same-marker shape rejection passed. 22 before/after read plans over 1,200 Runs / 48,000 events showed unchanged row results after the three index cuts. Stable Rust on macOS does not support ThreadSanitizer; real independent-connection database race tests provide supported concurrency validation.
  • SQL tradeoff: ordinary chat is 18 cold / 20 warm / 19 held-control statements, within the unchanged limit of 20; baseline is 17/19/18. The additional statement is the transactional opening insert once per Run. Read-only tool rounds add no SQL. No claim of zero admission overhead.
  • Payload evidence: on exact base/final DDL with the same 8 KiB checkpoint, the measured update/lock operator payload is 9.54 KiB → 1.50 KiB. This is operator-payload evidence, not physical disk-write amplification or end-to-end capacity.

Prior-head review and performance evidence

Prior-head source corrections: 70 scoped offline handoff/resume/harness cases passed. Four owning database cases passed, including exact-current corruption classification and concurrent resume/rollback. The new child-sink case separately passed through the actual database-backed lifecycle, invocation ledger and localhost provider; it also exercised canonical Session deletion cleanup. Prior-head services/runtime all-target Clippy passed with warnings denied; the other six package checks remain valid. The prior-head independent source review found no material source blocker; current repair validation is reported separately below.

Instrumented 100-Session comparison used fresh MatrixOne 4.2.6 instances with the same image, deterministic fixture seed, 4 vCPU / 2 GiB limit, 1536 MiB Go memory limit, 32 connections and unchanged timeouts/rates/assertions. Each case attempted 60 seconds warmup plus 600 seconds measurement on a shared 16 GiB host.

  • Base: the database container was OOM-killed (exit 137) around 481 seconds; the first recorded worker failure was renewal EOF, followed by connection-acquisition timeouts. The last client-acknowledged event count was 46,280; no final aggregate/frontier oracle was obtained. The driver was stopped after the engine was confirmed dead. No competing build was sampled before OOM; Go compilation appeared about 51 seconds later, so the complete run is marked contaminated and that later activity is not treated as the OOM cause.
  • Final: completed the full interval and exact per-Run event/frontier oracle: 66,000 events, 600 admission/terminal operations and 40 recovery claims, with zero operation/oracle errors, no database OOM, no independent health failures and no sampled competing builds. All ten owners made progress. Background and lifecycle arrivals had zero misses, but 2 of 12,000 foreground reads were missed. The unchanged strict benchmark therefore failed (exit 101). Completed-sample append p95 was 59.831 ms; these percentiles exclude missed arrivals.

This provides a bounded diagnostic observation, not a passing capacity gate or a comparable before/after latency speedup. The broader 1,000-Session, mixed-size, hot-owner, repeated-rate and sustained scripted-provider capacity matrix remains unproven and #1186 stays open. No production capacity, cross-process fairness, failover, physical disk-amplification or deterministic OOM-fix claim is made. Neither the benchmark assertions nor production limits/timeouts were loosened.

Rebase and review fixes

Rebased onto 2edb4566132cb69ef227fd0d6ef8affa3700aaee (main, scoped MOI forks). The new fork admission reads the explicitly loaded opening through its existing fail-closed accessor; provider authorization remains with the existing coordinator.

  • Checkpoint saves now use the shared admitted, locked control projection. A 6 MiB opening no longer enters this transaction; complete readers still validate its identity. Current checkpoint reference validation, Session fences, owner/generation/lease checks and final CAS stay in place. No extra query is added.
  • Durable read preflight preserves its existing 503/absent-code envelope while hiding storage field/decoder details. Authenticated resume tests cover malformed references, missing openings, healthy and foreign-owner controls, with no state/event/checkpoint changes on rejection.
  • Removed unused retired introspection query types, defaults and the self-only test; fixed the retention table.
  • Fixed CI fixture contamination without weakening production validation. On separate fresh MatrixOne 4.2.6 databases, crash recovery passed alone, failed with the same CI decoder error after S10 left nine incomplete Run pairs, and passed when the only intervention was adding their nine empty opening rows. Raw cancellation/S10/hydration fixtures now create each pair atomically; S10/hydration clean their Sessions.

Current-revision checks:

  • Ten affected packages passed all-target Clippy with warnings denied; services received a final check after the test fixes. Runtime without default features, formatting and whitespace checks passed.
  • Ordinary services/runtime tests: 7,314 passed and one local timing assertion failed in the initial strict run. That invocation omitted the previously recorded macOS system-CA setting. With the public system CA bundle configured, only that failed admission case was checked again and passed in 165 ms, retaining its 500 ms assertion and zero retries. The original failure is retained. The corrected result is consistent with earlier CA controls, but CA setup versus host scheduling is not proven as this specific failure’s cause; this is not presented as a clean first full-suite run.
  • Shared-database order: S10 1, hydration 8, recovery/resume 11, cancellation/connection reuse 6, batch writes 29, ordinary-chat SQL budgets 7, and checkpoint locking/custody/immutable handoff plus fork ownership/size 5: all passed. The actual pending owner save versus cancellation commit, save-first ordering and cancelled physical checkout passed.
  • Scoped provider-fork integration: 9 passed. A separate corruption-fixture → recovery sequence passed and confirmed the corrupted fixture left no Run behind.
  • make test-contract: 11 admin + 6 HTTP + 2 settings passed, with six pre-existing opt-in admin cases ignored.

Explicit gpt-6.1-terra / max design and overall source review completed with no unresolved material source finding. Stable macOS Rust lacks the requested ThreadSanitizer instrumentation; the supported independent-connection database concurrency checks above passed. Historical 16,448-test results do not claim this rebased revision passed that complete suite. CI for the updated head is not claimed passed.

Complete durable-read error presentation

Run lists, Session Run trees and resume preflight now share the existing lifecycle presentation owner: internal diagnostics are logged, while the established neutral 503/absent-code response reaches the client. No storage validation, ownership predicate, SQL statement or lock path changed.

The existing corruption fixture now exercises concurrent authenticated list/tree requests alongside resume, including healthy, malformed-reference, missing-opening and foreign-user controls and unchanged durable-state snapshots. Its permissive Session stub deliberately tests store-level filtering; production rejects a foreign Session before the Run reader. On this correction, all 11 phase-1 DB cases, 19 contracts, runtime all-target Clippy and formatting passed. Explicit Terra/max design and overall review found no material source blocker. Existing timing/capacity/TSan qualifications remain unchanged; CI is not claimed passed.

Final checklist

  • I added or updated tests at the layer that owns the behavior.
  • I updated public/design documentation for the changed contracts.
  • I checked the final diff for sensitive information and generated files.
  • The PR title follows the repository's Conventional Commit format.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewer verdict: Request changes. GitHub rejected the REQUEST_CHANGES event because the connected account is the PR author; this COMMENT records the verdict and findings without claiming a formal blocking review state.

Request changes on ad0d963ee321ede077317cd03165d0533b090004.

The overall ownership direction is sound: one mutable Run control owner, immutable opening storage, checkpoint-body ownership in run_checkpoints, and retirement of the redundant products rather than compatibility shims. Owner/CAS/transaction boundaries and the qualified performance claims are substantially better than the former duplicated state.

Two P2 gaps remain: checkpoint persistence still hydrates a cold opening it does not use, and new reference/opening decode errors can bypass the sanitized public resume boundary. Two P3 cleanup/documentation issues are also annotated. These are separate implementation, test-quality and documentation findings; the deletion count is not used as evidence of correctness.

Validation: read the exact-head production diff and directly affected consumers/contracts; executed bounded local MatrixOne probes through the public Run store for the large-opening checkpoint path and malformed-reference rejection (both completed successfully as diagnostic tests). Probes and databases were removed; no product fixes or source commits were made. Existing matching-head functional/static/concurrency evidence was reused rather than rerunning the whole suite. The two missed foreground arrivals and the unproven 1,000-Session capacity matrix remain declared limits, not a newly proven regression and not a reason to relax the benchmark.

At review start, GitHub had no prior comments, review submissions or inline threads, so there are no historical review threads to mark resolved. No subagents were used. Please resolve the findings and add the targeted behavior coverage before re-review.

Comment thread crates/services/src/runs.rs Resolved
Comment thread crates/services/src/runs.rs Resolved
Comment thread docs/design/data-and-storage.md Resolved
Keep cold opening and checkpoint bodies out of mutable Run control.
Preserve exact checkpoint custody, bounded reconciliation and owned
transactional lifecycle semantics while removing five redundant product
and persistence paths with their schema, endpoints and configuration.

Refs matrixorigin#1186
@XuPeng-SH
XuPeng-SH force-pushed the perf/persistence-wave2 branch from ad0d963 to 0b3c5b2 Compare October 31, 2026 10:54

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewer verdict: Request changes. GitHub rejected the REQUEST_CHANGES event because the connected account is this PR's author; this COMMENT records the same verdict.

Request changes on 0b3c5b2: one confirmed P2 remains in the public read-error boundary.

The four historical patches are present, including the sanitized resume preflight. However, the new checkpoint-reference decoder still leaks its internal diagnostics through the Run list and Session Run tree. The inline finding includes an executed authenticated HTTP reproduction and passing controls. Keep the storage validation fail-closed; finish the presentation-layer fix across these callers and cover the actual read routes.

I reviewed the storage/control ownership, current-reference versus history semantics, transaction/cancellation paths, bounded reconciliation and harness reuse, retirement closure, tests and documentation. No other material finding is asserted. Existing exact-content validation was reused; the new DB-backed probe exercised six HTTP requests and left durable controls unchanged. Its synthetic database and temporary test target were removed. No subagents or product edits.

Validation limits remain explicit: the earlier full normal run had 7,314 passes and one timing failure, followed by a separately passing CA-configured control; CI is not claimed green, and 1,000-Session/mixed capacity remains unproven.

Comment thread crates/services/src/runs.rs Resolved

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewer verdict: APPROVE. GitHub rejected the formal APPROVE event because the connected account is the PR author; this COMMENT records the same code-review conclusion and does not satisfy a separate reviewer's branch-protection approval.

Approve on 8660c66: no new actionable material finding.

All five historical review items are implemented and covered. In particular, load, list and Session Run-tree reads now share the existing lifecycle presentation owner; strict checkpoint validation remains in storage. The final correction adds no SQL, lock path, mutable state or compatibility layer. The metadata-versus-full-opening boundary and authentication/ownership owners remain intact.

The existing DB fixture now exercises actual authenticated list/tree requests concurrently, with healthy, malformed-reference, missing-opening and foreign-user filtering controls, resume behavior, unchanged durable-state assertions and canonical cleanup. The permissive Session stub qualification is documented; it does not redefine the production foreign-Session404 contract. Test and documentation changes are proportionate to the behavior fixed.

I reconciled this delta with the previously reviewed storage/reference, recovery/cancellation, bounded reconciliation/index, harness enforcement and retired-chain design. Exact-content validation is reusable: runtime all-target Clippy,11 phase1 DB cases,19 contracts and formatting passed; unaffected package/race evidence remains valid. No subagents or product edits; no duplicate unchanged test runs.

Qualifications remain: the earlier full normal run had7,314 passes and one timing failure, with a separately passing165ms CA-configured case; its exact environmental cause is not proven. CI on this head is not claimed green, TSan is unsupported on the recorded stablemacOS setup, and broader1,000-Session/mixed capacity remains unproven (#1186). This approval is a code-review verdict, not a claim that pending merge gates or capacity acceptance have passed.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant