Repository navigation
perf(services): reduce session admission database work - #1026
Conversation
XuPeng-SH
left a comment
There was a problem hiding this comment.
Recommendation: REQUEST_CHANGES.
Review of head 3178f8d4dc549f7a0c9b300732803042f9b858f3 against base 6aa6bcde1346a10f0118d83e1cc90280b1cbab86. Submitted as COMMENT because the authenticated account, XuPeng-SH, is also the PR author.
One substantive finding: the new expiry-frontier fast path uses a database timestamp sampled before a potentially blocking gate-lock acquisition. A lease can expire during that wait, yet admission skips reconciliation. This produces both a false capacity rejection for new work and a successful replay of an already-expired generation. See the inline comment at weighted_admission.rs:930–931.
I reviewed all 23 changed files and traced the durable admission callers, renewal/release, cancellation-safe transaction cleanup, session-deletion invalidation, materialized owner/global accounting, schema readiness and index shape, ordinary judgment formatting/normalization and its CLI/runtime/services callers, native TypeSafe provenance, and the changed harness contracts. The conservative frontier and capacity-before-insert design otherwise retain the existing serialization/accounting owner; the wider physical key and remaining global-gate bottleneck are acknowledged tradeoffs. I did not establish another blocking finding in these paths.
Validation:
- An external test crate called the unmodified head's public DatabaseWeightedAdmissionController against a dedicated fresh MatrixOne 4.2.5 container. With a two-second lease and a 3.25-second gate hold, both new regression assertions failed: new work returned GlobalExhausted with an expired row still present, while replay returned that expired row's original generation. An immediate retry of the new identity succeeded.
- The identical scenarios passed against the exact base weighted_admission.rs and cancellation_safe_db.rs modules with the base DDL. Source bytes were checked against both commit objects. The comparison run had 7 passes (including the base's five unit tests) and these 2 head failures.
- Existing local checks: turn types 266 passed; weighted admission unit tests 5 passed; storage 21 passed/1 database-only ignored; Work judgment 28 passed; semantic observations 30 passed/3 database-only ignored; skill judgment 5 passed; full offline harness 618 passed.
- Real MatrixOne admission integration: 18/18 passed; complete schema assertions: 9/9 passed. Initial integration attempts hit missing fixture catalogs in the isolated container; after creating those catalogs, the unchanged test binaries passed. Those setup failures were retained separately.
- Product worktrees remained unchanged. No remote CI rerun, provider call, production/shared-service access, deployment, branch update, or merge was performed.
Optional live-harness investigation: run 38951713633 completed 18 cases with 16 passes, 2 behavioral failures, and no unavailable verification. The child failure comes from exact comparison of the observed child terminal content with the required marker (execution_capture.rs:1099–1114), rather than the scalar judgment decoder. The Work failure root.3 maps to the exactly-one start_work journal-call assertion (case lines 54–57), not the removed settlement-attempt assertions; the semantic judge accepted delivery. That count includes failed calls, so this does not by itself prove duplicate durable Work. The public logs do not expose the child content or Work call details needed for causal attribution, and the artifact download URL returned HTTP 403. I have not classified either failure as infrastructure or flakiness. They remain unresolved behavioral evidence, not a standalone required-CI gate or the basis of this recommendation.
Publication gate: At 2026-10-16T19:40:35.711Z, the PR remained open/non-draft at the exact head/base above, with no existing reviews or inline comments to duplicate. Complete pagination returned 38/38 check runs, zero commit statuses, and both repository/parent rulesets. Accessible main-branch metadata lists 15 required contexts, all tied to GitHub Actions app 15368: 13 succeeded; Web and SDK were scope-skipped. Their exclusions are supported by static-checks.yml and the successful scope job, which reported web=false and sdk=false for the same 23-file change. Neither readable ruleset adds required CI. Mergify's neutral queue-management check is not required CI.
Limits: local validation used isolated databases, not deployed multi-pod load; no new live-model or sanitizer run was performed. Full classic protection/admin endpoints were already denied and were not retried; the unsupported rules/branches/main route was not requested. Required-check auditing uses accessible branch metadata and readable rulesets.
| if gate.usage_initialized && gate.earliest_expiry_at.is_none_or(|at| at > gate.now) { | ||
| return Ok(()); |
There was a problem hiding this comment.
[P2] Refresh the database clock after waiting for the gate
gate.now comes from the SELECT ... NOW(6) ... FOR UPDATE at lines 685–698. MatrixOne evaluates that timestamp before the row-lock wait completes, so this new early return can skip cleanup after a lease has actually expired. On the unmodified public controller, I reserved the only slot for 2 seconds, held the gate from a second connection, queued admission, and released the lock after 3.25 seconds: a new identity returned GlobalExhausted with the expired row still stored (an immediate retry succeeded); an exact replay instead returned the original generation with an expiry earlier than the current database time. The same two scenarios pass against the exact base admission/transaction modules and base DDL, whose expiry DELETE samples a later statement time. Please base this skip/replay decision on fresh post-lock database time and add both lock-wait-crosses-expiry regressions.
There was a problem hiding this comment.
Fixed in 5e9d075. The existing gate helper now samples database time after FOR UPDATE completes, in the same transaction and under the existing deadline/cancellation boundary. Renewal after a lock wait is also fenced. No local-clock approximation, fallback or second state owner was introduced.
The real MatrixOne regression observes lock waiting before expiry through processlist, then unlocks only after database time crosses expiry. It covers new identity, same-key replay and renewal; checks replacement generation/live lease, exact single capacity charge, and stale-generation renewal/release fencing. Native integration 19/19 and units 5/5 pass; services all-target clippy with warnings denied passes; actual instrumented-std TSan integration 19/19 and units 5/5 pass without suppression. Required gpt-6.1-sol/xhigh final reconciliation approved.
The extra clock query per gate acquisition, including release, is explicitly accounted for. Previous timings/SQL traces are labeled historical. Optional live CI 16/18 remains separately disclosed and is not claimed resolved by this fix.
XuPeng-SH
left a comment
There was a problem hiding this comment.
Recommendation: APPROVE.
Reviewed head 5e9d07534abc8ccdcdd93334b151f09060f18a1e against base 6aa6bcde1346a10f0118d83e1cc90280b1cbab86. Submitted as COMMENT because the authenticated account, XuPeng-SH, is also the PR author.
The prior P2 finding is addressed. In weighted_admission.rs:682–713, the gate-lock query completes before the separate database-clock read. The refreshed timestamp therefore governs expiry reconciliation, replay, and renewal after a contended lock wait. The read remains inside the existing deadline and cancellation-safe transaction boundary (lines 497–515), with an operation-specific database error. No local-clock approximation or fallback was introduced. I found no remaining substantive issue requiring changes.
Review coverage:
- Design and maintainability: reviewed all 23 changed files and relevant callers. Twenty files are byte-identical to the prior fully reviewed head; I reviewed all three subsequent file changes and rechecked the admission, schema, judgment, and harness contracts. The existing durable gate remains the single accounting authority, and the clock fix stays in its shared helper. Ordinary scalar judgment answers still normalize through request kinds and actual execution provenance; native TypeSafe probability answers retain their separate contract.
- Database I/O, concurrency, isolation, and resource costs: checked capacity-before-insert replay, the conservative expiry frontier, exact owner identity, session/branch mismatch handling, the logical idempotency primary key and unique generation, incremental owner/global accounting, and gate-first session deletion. Stale generations cannot renew or release replacements. Waiting callers acquire the local semaphore before a connection. The fix adds one database statement to every gate acquisition, including release; documentation now states that cost. The global gate remains a throughput boundary, and the wider primary key remains a storage tradeoff; earlier timings do not establish performance for this revision.
- Failure paths and boundaries: checked cancellation during lock/clock I/O, whole-transaction deadlines, discard of uncertain connections, renewal fencing, release retry, expiry/dirty-state repair, capacity-configuration fencing, aggregate overflow, malformed judgments, and canonical harness delivery requirements. The new regression at weighted_admission_db_it.rs:1213–1334 observes the actual locking statement before database time crosses expiry, then checks new identity, replay, and renewal, live replacement generation, exactly one capacity charge, and stale-generation fences.
Fresh local validation on this exact head, using unmodified product source:
- Both independent reproductions from the previous review now pass against the public controller: new admission reclaims the expired row; same-key replay returns a different, live generation. Both had failed on
3178f8d4dc549f7a0c9b300732803042f9b858f3, while the base comparison passed. - Dedicated fresh MatrixOne 4.2.5: admission integration 19/19; schema assertions 9/9.
- Weighted-admission unit tests 5/5; diff whitespace check passed.
- Initial repository database-suite attempts failed because my fixture CREATE DATABASE transactions were not committed (19 admission setup failures; 8 schema setup failures). I verified the missing catalogs, committed their creation, and reran the identical binaries successfully. Original logs were retained. The dedicated container was removed and the product worktree remained clean.
The earlier full local checks on the unchanged judgment/harness source remain supporting evidence, not claimed as new runs: turn types 266 passed; storage 21 passed/1 ignored; Work judgment 28 passed; semantic observations 30 passed/3 ignored; skill judgment 5 passed; offline harness 618 passed.
Optional live-harness evidence: run 38960486546 attests this exact source SHA and completed 18/18 with no failed, cancelled, or unavailable cases. The logs explicitly show both flash_child_question_parent_answer and work_two_step_execution_journey passing. I investigated their prior failures in the previous review; the unavailable private outputs still prevent proving those historical causes, and a successful later run does not establish that they were infrastructure or flaky. They are not a standalone publication gate.
Publication checks at 2026-10-16T20:52:39.241Z: PR open/non-draft, exact head/base unchanged, authenticated author confirmed. Complete pagination returned 40 check runs, zero commit statuses, and both readable repository/parent rulesets. Main-branch metadata lists 15 required contexts, all from GitHub Actions app 15368: 13 succeeded; Web and SDK were proven scope exclusions. The scope job reported web=false and sdk=false, consistent with the workflow conditions and independent classification of all 23 changed paths. Neither readable ruleset adds required CI. Mergify's neutral management check is not required CI. Deduplication checked substantive review bodies and original inline anchors: review 5552811590 targets the previous SHA; 5553163426 has an empty body and its reply retains the previous original anchor. No substantive review of this head was present.
Limits: local validation used one isolated database instance, not deployed multi-pod load; I ran no new live-model, sanitizer, or throughput benchmark. Full classic protection/admin endpoints were previously denied and were not retried; the unsupported rules/branches/main route was not used. Required-CI auditing relies on accessible branch metadata and readable rulesets. Cross-thread ownership evidence comes from the delegator's 20:39:59 UTC full sweep; this environment exposes only its local agent tree, rechecked before publication. No product edit, remote CI rerun, shared-service access, deployment, branch update, or merge was performed.
Summary
Reduce avoidable database work inside the existing distributed admission gate. Previously, every warm admission scanned live reservations for expiry, owner-only binary predicates missed compound-key pruning, and a new request at capacity attempted an INSERT before rolling it back.
Related issue
User-requested session-scale/database-pressure follow-up; no separate issue.
Change type
User and compatibility impact
Public admission limits, idempotency, owner isolation, cancellation and generation fencing are preserved. Fresh schema contract is
2026-10-16-v104; incompatible existing databases are rejected. No migration, dual path or compatibility decoder is introduced, and no existing user database was reset during validation.Ordinary model raw judgment output now uses
{"answers":{"id":"yes"}}(or a declared Choice key / ordered Score index, with explicit abstention). Old tagged raw answers are not accepted. Public normalized judgment responses and TypeSafe's native protocol are unchanged; this is a single adapter-wire replacement, not a second API or fallback.Architecture and complexity delta
DatabaseWeightedAdmissionControllerand the existing core schema inventory.3178f8d4d, physical-line delta against the branch base was: Rust implementation +236/-123 (net +113); Rust tests +480/-87 (net +393); live YAML +40/-39 (net +1); documentation +41/-3 (net +38), total net +545. The clock correction adds implementation +8/-5, tests +127/-0 and docs +4/-2 (net +132); combined net +677. Counts include comments/blank lines, with embeddedcfg(test)blocks classified as tests. This is a performance/correctness stage, not a code-size-reduction claim. The new single table-driven integration test covers three real lock-wait paths; there is no parallel test-only execution path.Verification
Required design and review use actual
gpt-6.1-sol/xhigh. The prior whole-branch approval on3178f8d4dis superseded by review finding 4298606389: database NOW in a locking statement can precede its lock wait. The follow-up samples database time after acquiring the existing gate, covering admission, replay and renewal without a local-clock fallback or new state owner. Final reconciliation is APPROVE for complete branch diff SHA-25626d46651383b91a1e19f904e0028a481e3dffc92a33cf81366da18addb0c6938against6aa6bcde1346a10f0118d83e1cc90280b1cbab86, after the new native/static/actual-TSan checks. Older unchanged-boundary evidence remains attributed to its original revision. This approval closes the database-clock finding, not the separately disclosed optional live failures.Remote optional live run
38951713633completed 16/18, with no unavailable verification. Remaining failures are child result mismatch and totalstart_workcount, despite the Work semantic-delivery check passing. The retained safe artifact does not include enough raw output/call details for causal attribution. These are unresolved behavioral results, not passes; this database-clock fix does not claim to resolve them or weaken their criteria.Current executed checks:
Post-lock correction static/race validation: services all-targets clippy
-D warningspasses (1m32s), format/diff checks pass; actual instrumented-std ThreadSanitizer, no suppression, admission units 5/5 and real MatrixOne admission 19/19 pass (25.77s). Other unchanged-boundary checks below are reused, not described as new runs.Post-lock clock correction: real MatrixOne admission integration 19/19 pass, 16.20s; admission units 5/5 pass. The new regression observes actual lock waiting before expiry and unlocks only after database time crosses expiry, covering new identity, expired replay and fenced renewal, replacement UUID, live lease, single capacity charge and stale-release safety. An initial fixture-only DECIMAL-to-i64 assertion decode failure was corrected with an explicit SQL cast, without changing the behavior oracle. The older 18/18 cohort predates this correction.
Native storage unit tests: 21 passed / 1 DB-only ignored; admission unit tests: 5 passed.
Actual runtime executor rejection/recovery/catalog regression: 1/1 pass; complete harness unit suite: 618/618 pass. These are not live-model results.
cargo clippy --locked -p astra-services -p astra-runtime -p astra-test-harness --all-targets -- -D warnings: pass;make format-check: pass.Real MatrixOne complete schema assertions: 9/9 pass, including idempotent bootstrap and the updated physical key/frontier contract.
Existing four-independent-pool/1000-request regression: pass; exactly 40 configured grants and 960 capacity rejections, owner limits preserved, zero reservations after release; admission P50/P95 807/978 ms on this shared host. This is a configured-capacity correctness test, not 1000 active agent executions.
Historical ThreadSanitizer before the clock correction (nightly, instrumented std, no suppression): admission 5/5, storage 21 passed / 1 DB-only ignored, real MatrixOne admission 18/18, complete harness 618/618, runtime executor regression 1/1 pass. Updated affected-boundary results are recorded separately below.
Final scalar protocol: native types 266/266, complete harness 618/618, CLI judgment 11/11, comparison 4/4 and lesson caller 10/10; runtime completion 20 passed / 2 DB-only ignored, memory relevance 23/23, typed-provider 11/11, summary client 20/20 and five host filters totaling 11/11; services Work 28/28, skills 5/5 and semantic observation 30 passed / 3 DB-only ignored. Runtime tests include
e2e-hooks. Work's original 16,000-byte complete chat-envelope cap is unchanged. All five affected packages pass all-targets clippy with-D warnings(6m27s). Actual additional TSan types 266/266 and complete harness 618/618 pass without suppression (2.59s / 40.87s).Historical live Flash selection at the primary milestone: 15/18, 495.499 seconds. Two cases completed all hard execution checks but their judges emitted a wrong wire discriminator (
noulinstead of requireddiscrete_noul); strict validation correctly rejected these, so they remainInfraVerificationUnavailable, not passes. The multi-turn case preserved local focus and later recall but added a truthful no-persistence disclaimer to its first acknowledgement; the old acceptance rubric rejected that prose. These results are retained unchanged. They motivated the shared protocol and semantic-rubric amendment, not a decoder alias, retry-until-green, provider-specific rule or weakened execution checks.Final ordinary-wire calibration: fixed eight controls, one call per arm/control, candidate 8/8 and static baseline 8/8, all structurally valid. Controls include truthful acknowledgements, real refusal/stale-topic/storage/tool violations, valid unknown on missing evidence and mixed Noul/Choice/Score. This small sample does not establish a population-level reliability guarantee or a timing improvement.
Actual complete Flash selection on scalar code: 17/18, 322.962 seconds, no unavailable verification. All cache, file-edit, child/fanout, rejection recovery, introspection and multi-turn checks passed. The sole Work failure was an incorrect demand for exactly two total settlement attempts and zero rejected attempts, despite two canonically delivered items and a correct final answer.
After correcting only that case contract, one fresh Work run passed 1/1, including two real deliveries and the semantic judge. It took 61.435 seconds (66.821-second suite); it recovered from two evidence-required settlement rejections, and its 13 rounds exceed the unchanged soft limit of 10. That efficiency warning remains visible. Runtime evidence guards were not changed. Real-capture controls reject missing, foreign, duplicate and blocked delivery. The original full report remains 17/18: final case coverage consists of 17 unchanged passes plus one corrected-case fresh pass, not a newly rerun single 18/18 suite. Case hashes and unchanged Rust code justify reusing native/SCA/race and the 17 unaffected results.
Historical SQL trace on
3178f8d4dagainst 1000 live reservations (before the post-lock clock correction):The prior owner predicate read 101 rows; the prior expiry check read approximately 1000 rows even when deleting none. The expiry predicate itself is not fixed: the new frontier avoids issuing it on the warm path. Forced simultaneous expiry of an existing 1000-row cohort reclaimed capacity and admitted a replacement in 39.8 ms; after release both reservation and owner-usage tables were empty.
The corrected helper adds one constant SQL command/round trip per gate acquisition, including release. Accordingly warm grant is now 8 commands rather than 7, and saturated new admission/exact replay are 5 rather than 4. These corrected counts follow the single added statement; the trace above and timings below have not been remeasured on the correction. The retained benefits are avoided live-set expiry scans, bounded identity reads and no provisional INSERT on saturated rejection, not removal of the clock round trip. Both locking and clock reads remain inside the existing transaction/deadline/cancellation boundary.
Historical matched public-controller workload before the clock correction, 1000 unique sessions / 100 owners / four independent pools / concurrency 32, then 1000 full-capacity denials and exact replay (not timings for the corrected head):
All barriers, replay and cleanup assertions passed. The extra handle is an idempotent replay, not an extra reservation. This was a shared machine with external compilation load; an earlier intermediate candidate had worse grant P95/P99 despite lower total time. Therefore these timings are observations, not an isolated-host tail guarantee. Direct SQL scan/write elimination is the primary cost evidence.
Limits: four pools in one process are not four deployed pods or 1000 active LLM agents. The global gate still serializes mutations; cold repair is proportional to outstanding capacity; durable parent parking and end-to-end large-pod capacity remain separate work. This change does not bound all historical session storage or claim ten-thousand-user capacity.
Final checklist