Skip to content

perf(services)!: batch session writes and partition admission capacity - #1027

Merged
XuPeng-SH merged 4 commits into
matrixorigin:mainfrom
XuPeng-SH:perf/admission-refill-coalescing
Oct 17, 2026
Merged

XuPeng-SH merged 4 commits into
matrixorigin:mainfrom
XuPeng-SH:perf/admission-refill-coalescing

Conversation

@XuPeng-SH

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

Copy link
Copy Markdown
Collaborator

Summary

Reduce database coordination and write amplification across concurrent sessions, within the existing admission and ingestion owners.

  • Partition durable admission capacity into 16 conserved owner scopes; borrow only locked, unused credit. Coalesce refills before fresh donor selection without holding an owner permit or SQL connection while queued.
  • Let the existing bounded ingestion worker combine eligible session heads into a shared transaction, multi-value event INSERT and precisely scoped session-effect UPDATE. Reuse the existing capture codec, replay/collision classification and causal-edge batch writer.
  • Preserve post-commit delivery confirmation, per-session FIFO, user isolation, foreground pool headroom and cancellation-safe connection ownership. Failed shared attempts retry their retained heads independently.
  • Bound normalized causal-edge INSERTs to 10,922 rows (65,532 binds) per statement in the same caller-owned transaction. Legal event/byte batches cannot poison retry heads by exceeding MySQL's parameter limit; ordinary small batches remain one statement.

Related issue

Follow-up to the already merged #1026; this is new work beyond that merge.

Change type

  • Refactor or performance improvement
  • Test
  • Documentation

User and compatibility impact

Fresh schema contract 2026-10-17-v105 replaces singleton admission accounting with owner-partition accounting. Older schema markers are rejected: there is no migration, compatibility decoder or dual writer. This change does not recreate an operator's database or delete existing user data.

batch_size bounds aggregate events across eligible ingestion session heads; count, charged bytes and existing absolute deadlines bound batching. A batch of one preserves independent-session operation. Synchronous event API writes and conditional run admission are not redirected into the asynchronous observation queue.

Architecture and complexity delta

  • Canonical owners: DatabaseWeightedAdmissionController, EventIngestionWorker, and canonical storage admission/effect helpers.
  • No new table, background worker, durable queue, per-pod capacity lease or authority cache. Durable allocations remain conserved across pods; a snapshot suggests donor locks but never authorizes a grant.
  • Replace singleton/global repair and overlapping local refill-lock sets. Remove obsolete event-insert accumulation helper and its self-only tests. Both single- and multi-session ingestion use one capture/settlement path; a single non-ended stored-session delta reuses the existing point counter update.
  • Session admission returns stored identities in the existing read. Set-based updates include exact candidate predicates: a real plan with 10,000 unrelated rows scanned only the two selected session rows.
  • Measured physical-line delta against the base, including comments/blanks: implementation +994/-499 = +495, tests +1240/-265 = +975, documentation +80/-57 = +23. This is not a code-reduction claim; the additional admission accounting and concurrency contracts must justify their cost.

Measured effect and limitations

Same isolated database generation/resources, unchanged finite-burst comparison, pool size 8, three retained runs per shape; no concurrent task-owned compilation. These are 1,000 event writes, not 1,000 or 10,000 concurrent LLM executions.

Workload Base completion Candidate completion Committed flushes
1,000 sessions, 1,000 events 6.29 / 7.75 / 8.85 s 1.10 / 1.00 / 1.61 s 1,000 → 10
10 sessions, 1,000 events 0.54 / 0.99 / 0.99 s 0.51 / 0.67 / 0.99 s 10 → 10

Tradeoffs are explicit:

  • Foreground SELECT1 p95 increased: sparse 3.44/6.15/10.72 → 7.00/8.71/19.69 ms; dense 37.16/39.13/43.45 → 52.62/57.91/62.38 ms. Small sample counts do not establish an SLO. Pool availability tests are not evidence of unchanged foreground latency.
  • The fixture starts without lifecycle fences, so first-use fence creation remains in the measured work. 99% fewer commits is not 99% fewer total DML statements or stored bytes. Already-fenced plain session heads share one event INSERT and one counter-effect UPDATE; physical rows, WAL/index work and lifecycle reads remain.
  • Shared transactions couple selected session locks for one bounded attempt. Rejection rolls the attempt back; healthy heads recover through their existing isolated retry path. There is no claim of zero head-of-line blocking.
  • A historical backend pre-execution stall remains unexplained; passing isolated cohorts do not prove it fixed. Earlier admission-tail and ingestion regressions are retained, not averaged away or relabelled successful.
  • No claim of 10,000 concurrent execution capacity, unlimited horizontal scaling, global historical-data bounds or improved latency in every metric.

Verification

  • cargo fmt --all -- --check: PASS.
  • cargo clippy --locked -p astra-services --features capacity-probes --all-targets -- -D warnings: PASS.
  • cargo clippy --locked -p astra-runtime --features e2e-hooks --lib --tests -- -D warnings: PASS.
  • Native owning checks: weighted unit 6/6, weighted owner DB 4/4, weighted DB integration 22/22, ingestion unit 96/96, ingestion DB 26/26.
  • Existing ingestion_batch_tradeoff_db_it with --features capacity-probes --ignored --nocapture: all six final measurements PASS; rows, exact session counters and flush counts checked. Fixture cleanup now includes lifecycle fences.
  • Actual ThreadSanitizer: event-ingestion units 104/104, admission units 6/6, storage units 21/21, admission-owner DB 4/4, admission DB integration 22/22, event-ingestion DB integration 26/26, runtime trace units 6/6, and quota/Trace→Reflect DB journeys 2/2 PASS. Nightly with instrumented standard library, external LLVM runtime, no suppression or raised test stack; builds use one Cargo job. Ignored tests are not counted as passes.
  • Public boundaries: controller reserve/renew/release, real ingestion sender/worker and durable delivery, and runtime Trace→Reflect multi-owner path.
  • Unhappy coverage: deletion/lazy-root rollback, same-ID owner isolation, exact replay/collision effects, selected-donor staleness, cancellation after credit transfer, bounded pool/gate waits, blocked shared-batch timeout, no premature acknowledgment, healthy isolated retry, cross-process identity/delete fencing, and terminal delivery before blocked quota cleanup.
  • Design and overall review: actual gpt-6.1-sol / xhigh; all local validation gates complete. CI is not claimed passed.

Latest review correction

  • Adopted review comment 4300711913 at the shared storage owner, not by lowering ingestion limits or dropping causal edges. Single-edge and batch consumers now require the existing sealed transaction boundary; no autocommit compatibility path.
  • Added real MatrixOne coverage for 100 events / 12,000 parent edges in one flush, ordered single-child chunk boundaries, later-chunk database failure and full rollback, replay and following-session progress. The cancellation case checks an observed blocked second statement, no premature delivery, rollback, pool recovery, retry and following events in the same worker.
  • Current correction: native DB 29/29 PASS (31.38s); actual TSan DB 29/29 PASS (39.81s), ingestion units 104/104, storage units 21/21, runtime trace units 3/3, real Trace→Reflect and auxiliary-write consumers 2/2 PASS. Ignored tests are not counted. Services/runtime all-target SCA and final owning-test SCA PASS; workspace formatting and diff checks PASS. Prior unchanged admission/performance evidence above retains its original scope.
  • Correction complexity: implementation net +6, tests +290, documentation +2 physical lines. Three real DB cases cover distinct batch, transaction-error and future-cancellation boundaries; no new production state, worker, storage table or retry owner.
  • Previous optional live CI was 16/18, not a pass: child-question adoption reported expected_result_mismatch; missing-model control omitted required /description and was rejected at schema validation before the intended model-resolution check. The sanitized artifact does not contain the child terminal text, so it does not establish a runtime/model/infrastructure root cause. This SQL correction does not claim to fix either failure or weaken their criteria.

Final checklist

  • Tests cover the owning implementation and real public boundaries.
  • Contract documentation updated.
  • Checked for credentials, private endpoints, customer data and generated artifacts.
  • Conventional Commit-style PR title.

XuPeng-SH added 3 commits October 17, 2026 07:19
Replace the singleton capacity gate with sixteen conserved owner partitions and ordered donor borrowing through one transaction owner. Keep identity, expiry, deletion and cancellation accounting on the existing durable authority.

Checkpoint validation: 6 owner unit tests, 3 real owner DB contracts, 22 DB integration tests, services all-target Clippy and format checks pass. Required gpt-6.1-sol/xhigh checkpoint review accepted.

Not merge-ready: matched four-process/100-concurrency grants improve total time from 9.32s to 4.17s but P95 regresses from 1.02s to 2.14s. Denial latency, historical backend long-wait attribution, current TSan and affected runtime validation remain open. Private policy experiments are excluded.

BREAKING CHANGE: fresh schema contract v105 replaces singleton weighted admission counters; no compatibility or migration path is retained.
Reuse the bounded ingestion worker for count- and byte-bounded cross-session transactions, multi-value event capture, and exact scoped session effects. Preserve owner identity, post-commit delivery, cancellation quarantine, and isolated retry heads. Coalesce admission refills before fresh donor probes without retaining owner gates or SQL connections.

Checkpoint validation: owner unit 6/6, owner DB 4/4, weighted integration 22/22, ingestion unit 96/96, ingestion DB 26/26; services all-target clippy and workspace format pass. Sparse 1000-session finite-burst commits fall from 1000 to 10 and completion from 6.3-8.8s to 1.0-1.6s. Dense completion returns to baseline range; foreground probe tails increase and remain disclosed. Full race/runtime verification is pending; this is not a claim of 10000 concurrent executions or closure of the historical backend stall.

@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.

Recommendation: REQUEST_CHANGES.

Reviewed head f7799b0151bda3ee3c61eb17de50897a609e4b55 against base/main 75b5b02eac60788e2b5f7bc27e5014399980c427, including every changed hunk in all 12 files and the runtime admission, session lifecycle, storage, scheduler, and cancellation call chains. This is a COMMENT review because the authenticated reviewer is also the PR author.

One correctness issue needs a fix: [P2] Bound the bulk causal-edge INSERT by the database parameter limit (inline at event_ingestion.rs:2848–2850). The new batching call can aggregate an otherwise accepted default-size batch into 72,000 bound parameters, exceeding the MySQL protocol/SQLx limit of 65,535. The previous per-event writes stay below that limit for the same events. An affected same-session batch remains an indivisible retry head, repeatedly rolls back, and prevents later events in that session from advancing. Chunk the edge rows within the existing transaction and cover the boundary plus retry progress.

The remaining review covered these four dimensions:

  • Design: The 16 stable owner partitions, conserved five-dimensional allocations, ordinary owner-partition path, and serialized refill path are coherent. The capacity snapshot is advisory; grants still revalidate under ordered database locks. Schema v105 explicitly changes the fresh-database contract, and the documentation reflects the mixed-session batching and capacity partitioning.
  • I/O, isolation, concurrency, and cost: I traced stored owner/session admission facts through replay classification, canonical session deltas, causal edges, and commit. I checked owner ceilings, partition credit transfer, stale-donor rollback/full-inventory fallback, capacity configuration changes, expiry repair, and generation-fenced release/deletion. The scheduler retains count/byte bounds, pool headroom, owner fairness, and one in-flight head per session. The edge statement above is the uncovered resource boundary.
  • Clarity and complexity: Reservation attempts share the canonical locked grant path instead of duplicating admission rules in the probe/refill paths. The new session-effects helper has a bounded keyed update and preserves the single-session path. I reviewed the added state transitions and their tests; I found no additional actionable duplication or complexity defect.
  • Failures and recovery: I checked replay/collision handling, rejected-session rollback and isolation, retained retries, shutdown outcomes, timeout/cancellation connection cleanup, post-commit acknowledgement, expiry reconciliation, and release idempotence. Existing and added tests cover these paths, but do not cover the accumulated causal-edge bind count.

Validation: local cargo test --locked -p astra-services --lib completed with 1,773 passed, 0 failed, 96 ignored. A separate local capture-only executor exercised the exact head edge helper without connecting to a database: a default-size accepted batch charged 504,200 JSON bytes under the 1,048,576-byte aggregate bound and generated one 72,000-parameter statement; per-event calls generated at most 720 parameters. This is statement-construction evidence, not a live database reproduction. The SQLx 0.8.6 parameter-limit documentation and the driver's 16-bit prepared-statement parameter count establish the backend boundary.

Required CI was rechecked against branch/main and both active rulesets: 12 applicable required contexts succeeded, all from GitHub Actions app 15368. The other three required-context names (core crates, Web, SDK) are scope exclusions proven by the scope job outputs and the head workflow conditions, not assumed passes. Required workflows tested merge d1e7cf702d0d6a6be46f6c959f30056baf0f9b43 with the exact base/head above. I also inspected the actual services/runtime/CLI and online core-services execution logs; the online shard reports the new owner tests and the ingestion and weighted-admission integration suites passing. The full protection/admin endpoints remain unavailable (403); accessible branch requirements and active rulesets were used without retrying those endpoints.

The optional Harness run remains failed, with 16/18 cases passing and two BehaviorContractViolation results:

  • flash_child_question_parent_answer: child-result verification reports expected_result_mismatch; the verifier compares the captured child terminal content with the required result.
  • flash_missing_child_model_fail_closed: missing /description produces tool_invalid_args before the intended model-resolution check, so the same-call predicates are unsatisfied.

The relevant schema, cases, and verifier are unchanged by this PR. Ingestion participates in the captured evidence path, so the logs do not establish that the PR is unrelated or caused these failures. These are unresolved behavior observations, not demonstrated infrastructure failures. This optional failure does not prevent publishing this review, but remains a direct-merge blocker under the requested all-applicable-code-CI rule.

Local database integration, TSAN, live-provider, and performance runs were not repeated. Database integration coverage here relies on the inspected CI logs; I did not independently reproduce the PR's performance or TSAN claims.

Comment thread crates/services/src/event_ingestion.rs Outdated
Comment on lines +2848 to +2850
crate::storage::insert_agent_event_edges_batch(&mut *tx, &edges)
.await
.map_err(|e| format!("session close for {session_id}: {e}"))?;
}
.map_err(|error| format!("ingestion edge insert: {error}"))?;

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.

[P2] Chunk the accumulated causal edges before executing the INSERT

This now passes every inserted event in the batch to a helper that emits one statement with six bound parameters per normalized parent edge (storage.rs:1585–1622). The event-count and JSON-byte bounds do not bound that expanded parameter count. A capture-only check of the exact helper with an accepted default-size batch produced 72,000 parameters while charging only 504,200 of the allowed 1,048,576 JSON bytes; the previous per-event calls required at most 720 parameters for the same events. MySQL prepared statements/SQLx support at most 65,535 parameters.

The resulting failure rolls back the entire ingestion transaction. For a same-session batch, complete_scheduled_attempt retains all of its events as one retry_head, and dispatch_ready_sessions takes that head whole, so retrying cannot recover and later session events remain blocked.

Please split normalized edge rows into statements below the backend bind limit within the same transaction, preserving each event's parent order and atomic commit. Add a boundary test for accepted aggregate batches with many parent edges and verify that commit and subsequent session progress succeed.

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.

Fixed in 2280fa6. The shared storage writer now splits normalized edges into at most 10,922 six-bind rows per statement, retaining parent order and using the existing sealed caller-owned transaction for every chunk. Production consumers pass their existing transaction; no autocommit compatibility path or ingestion-specific retry was added. Real MatrixOne regression: native 29/29 and actual ThreadSanitizer 29/29 pass, including 100 events/12,000 edges, later-chunk failure rollback, and an observed blocked second chunk timing out then recovering in the same worker without premature acknowledgement or partial commit. Affected storage/ingestion units and runtime Trace→Reflect/auxiliary consumers also pass under TSan; final SCA and gpt-6.1-sol/xhigh whole-branch review pass. PR body retains the separate optional harness 16/18 failures; this correction does not claim to resolve them.

@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.

Recommendation: APPROVE.

Re-reviewed head 2280fa68ab1d98efc9cc42a890b64c41bddceb9d against base/current main 75b5b02eac60788e2b5f7bc27e5014399980c427. Coverage includes the full 15-file, 139-hunk base-to-head range, all seven files changed since my previous review, and the relevant runtime, storage, ingestion, admission, lifecycle, and cancellation call chains. I found no remaining actionable correctness issue in that reviewed scope. This is an author COMMENT review because the authenticated identity and PR author are both XuPeng-SH.

The previous P2 bind-limit finding, originally anchored to f7799b0151bda3ee3c61eb17de50897a609e4b55 at event_ingestion.rs:2848–2850, is resolved by the actual implementation:

  • The shared edge writer normalizes parents and assigns each event's parent order before splitting into at most 10,922 rows / 65,532 binds per statement. Empty input avoids a statement, and order survives chunk boundaries.
  • Its sealed TransactionConnection bound requires an existing caller-owned transaction. All four production consumers—ingestion, trace batches, auxiliary turn events, and direct event creation—pass their transaction and propagate a chunk error before commit. The existing cancellation guards remain responsible for disposing of an interrupted connection.
  • The added regressions exercise a 100-event / 12,000-edge batch and subsequent progress, order across the chunk boundary, second-statement failure with rollback of the first, and an observed blocked second chunk followed by timeout and recovery in the same worker without premature acknowledgement or partial commit. I inspected their assertions and independently verified their current-head CI passes.

The broader review covered all four requested dimensions:

  • Design: The fixed owner partitions and conserved five-dimensional capacity allocations remain coherent. The fresh snapshot only rejects or proposes donors; the canonical locked attempt revalidates grants, including stale-donor fallback and configuration changes. The edge repair belongs in the shared writer and adds no separate ingestion retry state machine. The fresh-schema contract and documentation agree with the implementation.
  • Database I/O, isolation, concurrency, and resource cost: I rechecked sorted session admission, stored owner/session identities, inserted-only effects, replay/collision classification, bounded batching, pool headroom, owner fairness, and one in-flight head per session. Admission retains exact owner accounting, per-owner ceilings, ordered donor locks, atomic credit transfer, and generation-fenced release. Chunking now bounds expanded SQL parameters while preserving the transaction boundary; total normalization memory remains proportional to the admitted parent data.
  • Clarity and duplication: Ordinary, donor, and full-inventory admission share the canonical reservation path. Session effects remain a keyed helper with the single-session fast path. The repair reuses the existing sealed transaction abstraction and shared normalization logic across callers.
  • Failures, recovery, and boundaries: I traced lifecycle rejection, rollback isolation, retained retries, cancellation/timeout cleanup, commit-before-acknowledgement, shutdown outcomes, expiry repair, and idempotent release. The new later-chunk failure and timeout tests cover the specific partial-write and recovery risks introduced by splitting a statement.

Validation on this head:

  • Local cargo test --locked -p astra-services --lib: 1,773 passed, 0 failed, 96 ignored.
  • Inspected online core-services execution: 500 passed, including all three new regressions and the 29 ingestion database tests.
  • Inspected execution logs for services/turn-core/plan (5,443 passed), runtime (5,977 passed, plus two history checks), and core crates (3,932 passed, plus 129 additional selected tests).
  • The final required-CI gate has 13 applicable required contexts successful, with exact-head job/workflow provenance and GitHub Actions app 15368. Only Web and SDK are excluded, proven by current scope outputs and workflow conditions. Core crates applies and passed. Test Suite run 38992220820 has all 28 jobs successful and tested merge e7d4c51745dfdead0cd9a4760fa83d2b9b036809, whose parents are the exact base/head above.

The current optional Harness run is a separate unresolved observation: 17/18 passed, with introspection_reflection_source_boundary failing hard journal_tool_call_count conditions root.4 and root.6 as BehaviorContractViolation. Those conditions require exactly one introspect call and one with /facet = overview; the verifier reads deduplicated persisted turn/round tool records. Public logs withhold the detailed payload, so they do not establish the observed call counts, an infrastructure cause, or PR causality. The case and verifier are unchanged; persistence is relevant, and I reviewed the affected writers without finding a demonstrated defect linking them to this failure. Both cases that failed on the previous head pass in this run. The optional failure does not by itself block this code-review recommendation, but remains a direct-merge blocker under the requested all-applicable-code-CI gate.

Local database integration, TSAN, provider, and performance runs were not repeated. Database integration evidence above comes from the inspected CI execution logs; the author's additional native/TSAN and performance claims were not independently reproduced. Previously denied protection/admin endpoints were not retried; accessible branch requirements and both active rulesets were rechecked. This review covers this exact head and does not treat the earlier empty current-head COMMENT or repair reply as substantive coverage.

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