Repository navigation
perf(services)!: batch session writes and partition admission capacity - #1027
Conversation
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
left a comment
There was a problem hiding this comment.
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 reportsexpected_result_mismatch; the verifier compares the captured child terminal content with the required result.flash_missing_child_model_fail_closed: missing/descriptionproducestool_invalid_argsbefore 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.
| 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}"))?; |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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
TransactionConnectionbound 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
38992220820has all 28 jobs successful and tested mergee7d4c51745dfdead0cd9a4760fa83d2b9b036809, 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.
Summary
Reduce database coordination and write amplification across concurrent sessions, within the existing admission and ingestion owners.
Related issue
Follow-up to the already merged #1026; this is new work beyond that merge.
Change type
User and compatibility impact
Fresh schema contract
2026-10-17-v105replaces 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_sizebounds 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
DatabaseWeightedAdmissionController,EventIngestionWorker, and canonical storage admission/effect helpers.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.
Tradeoffs are explicit:
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.ingestion_batch_tradeoff_db_itwith--features capacity-probes --ignored --nocapture: all six final measurements PASS; rows, exact session counters and flush counts checked. Fixture cleanup now includes lifecycle fences.gpt-6.1-sol/xhigh; all local validation gates complete. CI is not claimed passed.Latest review correction
expected_result_mismatch; missing-model control omitted required/descriptionand 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