Repository navigation
perf(runtime): reduce database-bound turn latency - #999
mergify[bot] merged 24 commits into
Conversation
2d13ebe to
c8ec557
Compare
XuPeng-SH
left a comment
There was a problem hiding this comment.
Reviewed all 12 changed files at c8ec557 against 20abb63, including the surrounding fanout, interaction delivery, canonical writer, terminal settlement, projection repair, and resume paths.
Request changes for two P2 latency regressions:
- The blanket pending-batch branch also buffers already-durable approval prompts and tool execution requests. The existing immediate-flush branch only covers approvals that still need persistence, so the normal committed interaction paths lose their immediate delivery boundary.
- The 2-second projector interval throttles active backlog recovery as well as idle polling. With the existing one-Work-per-owner selection and bounded sweep, the additional delay accumulates across sweeps; it is not limited to one extra interval.
Validation: compiled unchanged production function fragments from both base and head into an isolated Rust harness, using the repository's locked versions of serde_json, Tokio, tokio-util, and tracing. Persistence/delivery were replaced by boundary doubles; the projector probe used the actual scheduler with a double representing ten pending Works belonging to one owner. Four regression probes passed on base and failed on head: committed Edge approval, durable-gate approval, committed tool request, and active backlog drain. An uncommitted-approval control passed on both. This is targeted behavioral evidence, not a full runtime or MatrixOne integration run. git diff --check passed. GitHub Static Checks, Test Suite, and PR Title were green for this head.
The exact writer/replay guards, retained-writer behavior, checkpoint metadata preservation, and Explain request propagation did not reveal another actionable blocker in this review. The settlement-start fence is still present after 4c0b12e reverted its removal; please update the PR summary's claim that it was removed. I did not run the full workspace suite, live MatrixOne tests, or provider benchmarks.
a931f77 to
ccf9f90
Compare
|
Follow-up on live harness: the previous e82e567 run completed 7/8 cases; required Test Suite and Static Checks passed. Its sole failure was the hard cache-reuse witness on GLM, not authentication. Direct streaming probes confirmed GLM returns prompt_tokens_details=null (cache usage unreported), whereas DeepSeek-v4.1-Flash reports cached_tokens=0 then 9856 on the repeated prefix. Updated this PR to 8ed406f: the regression matrix binds only the cache case to DeepSeek using a generic exact-case model override. Prompts, required cache scope and all assertions are unchanged; other parents and judges remain GLM. Local harness tests: 604/604; CI script tests: 129/129. Because automatic privileged runs use the base-owned workflow, validating the new definition requires an explicit dispatch until that definition reaches main. Full eight-case validation of this exact PR head is running here: https://github.com/matrixorigin/Astra/actions/runs/38556727951 . It is not yet a pass. Cancelled only the duplicate optional run using the old GLM-only definition; required CI was not cancelled. No new PR or default-branch update. |
8ed406f to
9c2c9a1
Compare
XuPeng-SH
left a comment
There was a problem hiding this comment.
Reviewed all 22 changed files at exact head 754db2c against base/merge-base d2d4404, including surrounding producer/consumer and recovery call chains.
Request changes for one P2 regression: the terminal transaction now publishes run_settlement_finished before Explain artifact publication. Both durable live-attach paths treat that marker as proof that publication has finished; an observer arriving in that interval emits publication_outcome_unrecorded and closes, missing the subsequent successful report. Keep the publication-completion contract intact when folding the settlement marker into the transaction. Details and exact consumer references are in the inline comment.
Review coverage:
- Design and lifecycle: ordered durable/transient fanout, interaction boundaries, Explain opt-in and resume propagation, shared-loop versus Server memory settlement, terminal projection ownership and lost-COMMIT-ACK reconciliation.
- Database and concurrency: session/execution/run lock order, exact owner/session predicates, cancellation lineage, inference control frontier, atomic canonical commit/writer release, retained-writer and archived-receipt replay, session-create admission facts, and WAL retirement. The new writer helper guards both lease/epoch identity and an existing later reservation.
- Resource/error paths: bounded fanout queues and failed persistence, cancellation-safe checkouts, resident/distributed permit cleanup, terminal conflicts, projection/checkpoint metadata, and post-loop work. Reviewed the new regression tests and their coverage boundaries.
Validation: a standalone Rust probe compiled unchanged consumer predicates/status helpers extracted from both revisions and derived terminal-marker timing from each producer. Before publication, base keeps both reconnect and polling paths open; this head prematurely closes both. Published-outcome and no-finished-marker controls remain correct. This is isolated decision/ordering evidence, not a full HTTP or MatrixOne integration test. The existing durable_live_attach_keeps_terminal_explain_run_open_until_publication_settles test still models publication followed by settlement, so it does not exercise the new producer order. git diff --check passed; product source is unchanged.
Independently paginated exact-head CI: 39 check-runs (36 success, 2 justified scope skips, 1 neutral Mergify), no commit statuses, and all five workflow runs/latest attempts complete successfully. Test Suite 38604996314 passed all 28 jobs; live harness 38604996301 logs identify this exact SHA and 8/8 passed. Scope logs explicitly report sdk=false and web=false. Branch-protection settings could not be read with this integration (403); no claim is made about inaccessible protection configuration. I did not rerun remote CI, use live databases/providers, or validate the PR's performance benchmark independently.
The prior review 5512883437 and its original inline anchors concern c8ec557, not this head; its interaction-delivery issue is fixed and its projector change is absent from this diff. This review does not authorize merge or a draft-status change.
754db2c to
ab03c53
Compare
|
@XuPeng-SH The previously failing A re-review is requested for @XuPeng-SH. The current implementation intentionally keeps |
XuPeng-SH
left a comment
There was a problem hiding this comment.
Request changes: one P2 publication-order regression remains at exact head e6953b9b47fc926777319d8a59535b66421d8b20, reviewed against base/merge-base b091b23b00b579369e5070162488a59926b34343.
The terminal transaction still writes run_settlement_finished before Explain publication. Both durable live-attach consumers still interpret that marker as permission to synthesize publication_outcome_unrecorded and close. A subscriber observing the normal interval between those commits therefore misses the later successful report. The inline comment gives current producer/consumer anchors and the missing regression case.
I considered the author's response on the resolved thread. Keeping optional artifact publication outside the authoritative terminal transaction is sound. It does not make the current subscribers correct: neither closing branch waits for the publication timeout nor invokes snapshot recovery. Narrowing the marker's meaning requires changing those consumers, or retaining a separate post-publication completion boundary. This request does not require putting artifact persistence inside the terminal transaction.
Coverage: all 24 changed files and relevant call chains, including ordered durable/transient fanout and immediate interactions; Explain opt-in, child/resume propagation and publication/recovery; terminal evidence, display/checkpoint projection, cancellation lineage and lost-COMMIT-ACK reconciliation; canonical writer commit/release and retained-writer/archived-receipt replay; inference admission/frontier and WAL retirement; session creation/admission/quota, parallel authentication reads and permission snapshots; post-loop memory ownership, context/SSE cleanup, permit drop and TTL recovery. I checked bounded queues, owner/session predicates, lock ownership, error propagation and the added boundary tests. No additional material blocker was established. The earlier committed-interaction issue is fixed; the projector interval change is absent.
Local validation in a detached checkout, without product edits:
- Compiled unchanged status helpers and both actual consumer predicates extracted independently from base and head with Rust 1.97.0; derived marker timing from each producer. For completed/failed/delegated runs with either live or expired owners, base has zero premature-close decisions and head has 12 across the two paths. Published-outcome, no-marker, ordinary-run, running and live-paused controls pass. This proves the ordering/decision defect; it is not an HTTP or MatrixOne integration run.
- The two existing
session_create_transaction_contracttests pass when compiled directly withrustc --test. git diff --checkpasses. The exact changed-file classifier independently returnssdk=false,web=false.- The existing
durable_live_attach_keeps_terminal_explain_run_open_until_publication_settlestest still appends publication before settlement, so it misses the producer order introduced here.
Publication gate: the current Mergify summary exposes 15 protected check names: 13 succeeded, and the SDK/Web skips are supported by fresh exact-head static-scope logs, workflow conditions and the local classifier. All 39 latest check-runs are complete (36 success, those 2 scope skips, 1 neutral Mergify); no commit statuses are present. Direct branch-protection access returns 403, so the protected-name evidence is Mergify's current evaluated protection summary.
Optional live run 38723261338, attempt 2 is successful; its logs identify this exact head and 8/8 passed. Artifact 11968319484's metadata digest matches its upload log (ea90f13e9ab4fb883b8939879842fd6a4e6e75a55f08f8ab57ff4c5539dd7a1e). This environment could not download the returned archive URL (403), so I did not independently recompute the ZIP digest. Optional CI is not a publication blocker.
I did not rerun CI, execute live database/provider tests, or independently reproduce the latency benchmark or concurrent-session capacity claims. The prior review 5525694820 and its original anchor were verified against 754db2cf275de900e34ef4934b54620009b404ff; this is a fresh current-head assessment.
e6953b9 to
1f750f0
Compare
|
CI follow-up for head |
XuPeng-SH
left a comment
There was a problem hiding this comment.
Approve at exact head 1a67de1bacb3ff919716fd46af764f72ade2b829, reviewed against base 40012430c17977ac6bbda24c24a1800615710a04. The completed review covered all 24 changed files and their surrounding call chains. No remaining material blocker was established.
The Explain publication defect from review 5532615673 is fixed. Both the initial durable live attach and an already-following observer no longer use run_settlement_finished as permission to close before publication. They retain the bounded publication grace and final durable read. The new settlement-first, delayed-publication regression exercises the corrected producer order. Keeping optional artifact publication outside the authoritative terminal transaction remains appropriate.
Coverage included durable/transient fanout and immediate interaction delivery; Explain opt-in and resume behavior; terminal evidence, display/checkpoint projection and lost-COMMIT-ACK reconciliation; canonical writer commit/release and later-reservation replay protection; session admission/quota and authentication reads; inference frontier and cancellation lineage; permission snapshots; WAL retirement; and owned-task context/SSE cleanup with permit-drop and TTL recovery. Owner, session, generation, lease and cancellation checks remain intact. The earlier committed-interaction issue is fixed, and the projector-interval change is absent.
Validation from the completed source review: 12 isolated checks and both existing session-create transaction contract tests passed. The isolated checks distinguish the historical premature close from this head's wait in both consumer paths and cover timeout, last-moment publication, storage failure, invalid publication, disconnect and the 512-event queue bound. These are targeted behavioral checks, not a full HTTP/MatrixOne runtime run. Full local runtime validation was blocked by unavailable locked dependencies, including the cached toml version. No live provider/database test, performance benchmark or multi-session capacity claim was independently reproduced.
Fresh prepublication CI verification covered all 42 check runs, seven suites, six workflow runs and all 40 jobs across their attempts, with terminal pagination checked. The current protected-branch metadata names 15 required contexts from GitHub Actions app 15368: 13 succeeded; SDK/Web are justified scope exclusions, confirmed by exact-head static-scope logs (sdk=false, web=false) and the head's workflow conditions. Required macOS coordination also passed. Optional live Harness run 38848116860, attempt 3 identifies this exact head and passed 8/8; its earlier failed attempts remain recorded.
The PR was rechecked open at the reviewed head, authenticated reviewer XuPeng-SH differs from the author, and no duplicate substantive review exists at this head. All four historical review threads are resolved and their original commit/line anchors remain intact. The protected-context evidence comes from branch metadata; the integration's inaccessible classic protection administration fields are not claimed as verified.
Merge Queue Status
This pull request spent 17 minutes 6 seconds in the queue, including 16 minutes 30 seconds running CI. Required conditions to merge
|
This reverts commit 93750a9.
… boundary Canonical turn commit keeps its durable authority contract. The absorbed provider-WAL payload retirement is a lagging DELETE whose retry already happens at the session boundary; awaiting it on the user-visible terminal boundary adds a high-latency transaction (lock, two DELETEs, COMMIT) to every successful turn. Run the retirement as an observed background side effect after the commit result is decided, only when the commit succeeded (Option::is_some). Failures still log through the existing canonical_wal target, and the retry schedule is unchanged. Benchmark: 12 same-session trials against production MO with deepseek-v4-flash, P50 8.32s -> 6.73s and P90 10.34s -> 7.78s compared with the settlement-fence-inline candidate on the same session/database.
1a67de1 to
4f92328
Compare
## Summary CLI strict recall compares Astra session identity with Memoria record ownership even when UC or connected personal accounts use distinct namespaces. Explicit close also races detached extraction, and process-local governance cannot recover a partial archive/purge after restart or a lost response. This completes the remaining owner/finalization work from #996 after #997: - Strict recall carries fresh Server attestation of both identities and session; CLI validates that attestation and every row before admitting content or tracking a working ID. - CLI exit and explicit close use the canonical Server-owned memory lifecycle. Exit preserves resumability and cannot fall back to local purge after an unsuccessful handoff. - A durable owner/session journal freezes extraction inputs, uncertain write payloads, consolidation plans and stage receipts. Database leases and the existing Session fence coordinate separate server instances. Missed handoffs recover from immutable canonical context; purge waits for execution settlement and verified final-turn freshness, and removes only captured working IDs. - Required failures retain source state and retry with bounded backoff. Optional reflection/scene retries reuse completed episode and purge stages. Current authority is resolved for each operation; queued input/credentials are not exposed through the owner-only status endpoint. Session deletion removes queued journal inputs. ## Related issue Refs #996. This is the remaining implementation after #997; the issue should remain open until the matched backend protocol is available and the changes have been reviewed together. **Backend dependency:** [matrixorigin/memoria#310](matrixorigin/memoria#310). Deploy Memoria's dedicated idempotent-store endpoint before enabling this Astra image. The endpoint's owner/branch/key primary-key arbitration is needed to safely replay a request after its response is lost; vector similarity deduplication cannot provide that guarantee. Old backends fail before a write and never authorize cleanup. Neither PR should be merged automatically. ## Change type - [x] Bug fix - [x] Documentation - [x] Test ## User and compatibility impact **Database rollout:** this adds fresh schema contract `2026-10-14-v102`. Astra rejects older completion markers and does not migrate databases automatically. Existing deployments require an operator-owned database rollout/preservation plan; this PR performs no reset. Upgrading only the image is insufficient. Adds authenticated `POST /sessions/{session_id}/memory/finalize` and `GET /sessions/{session_id}/memory/status`. A queue acknowledgment is not a confirmed archive. CLI retains its five-second exit budget; extraction/finalization retain 20/60-second attempt budgets. Worker leases last 90 seconds, polling every two seconds with concurrency two and retry backoff from five seconds to 16 minutes. Strict session recall adds a `memory_scope` envelope and requires a matched Server for the updated CLI. UC, connected personal and explicitly enabled self-hosted owners remain separate from Astra session authorization. Consent revocation/disconnect stops future remote operations without promising remote erasure. Astra Session deletion removes queued inputs; Memoria's retention and explicit deletion govern remote records. ## Architecture and complexity delta - Canonical owner extended: existing Session lifecycle, context coordinator and memory extraction/governance algorithms. One new owner/session work journal stores retry checkpoints, not a second session/context or memory authority. - Existing implementations/callers searched: CLI startup/cleanup, memory proxy and authority resolver, extraction runner/service, turn finalization, explicit close, write fence, context heads and deletion catalog. - Superseded paths removed: untracked close-time governance task and its process-local coordination. The managed background recovery task participates in Server cancellation/shutdown. Remote CLI maintenance now queues canonical Server work. - Direct/in-process providers retain the same governance algorithm and ordinary transport contract. Only bounded destructive working cleanup holds the Session fence across network I/O; optional reads, writes and reflection use short preparation/checkpoint transactions. ## Verification Current head: `40cbadd5`, based on main `7375abe0`. Targeted E2E Clippy, formatting and whitespace checks passed locally. The repaired handoff/resume regression passed real database CI and integration passed 295/295; the optional live harness also passed 8/8. All current test and static-check workflows have passed. At `26271bdc`, core-services passed 481/481 and core-runtime passed 104/104, including the memory regressions; earlier evidence below applies to its recorded commits/runs. Passed locally on rebased main (synthetic fixtures; designated isolated MatrixOne): - `make format-check` - `cargo test -p astra-memoria --lib` (19 tests) - `cargo test -p astra-services --test session_memory_lifecycle_db_it -- --ignored --test-threads=1` (3 tests on fresh v102; rerun of the freshly built test binary passed) - `cargo test -p astra-services --test schema_assertions core_schema_catalog_matches_live_idempotent_bootstrap -- --ignored --test-threads=1` (1 test; idempotent fresh bootstrap, generated catalog, rejection of unsupported old marker) - `cargo test -p astra-runtime --lib session_memory::durable::tests -- --ignored --test-threads=1` (4 tests before the schema-version follow-up; local package debug=0) - `cargo test -p astra-cli --lib cli::session::session_startup::tests::cli_ -- --test-threads=1` (7 tests; local runtime/CLI package debug=0) - Fresh CLI test binary: `browser_identity_services_replace_generation_and_private_skill_cache` and `escape_browser_login_restores_memory_and_external_discovery` (2 tests) - `cargo clippy -p astra-memoria -p astra-services -p astra-runtime -p astra-cli -p astra-thin-client --all-targets -- -D warnings`; CLI all-target recheck after fixture updates - `python3 scripts/schema/test_schema_inventory.py` (47 tests) - `git diff --check` The first CI run exposed a missing schema inventory classification and stale login-maintenance mocks; this follow-up classifies the journal and aligns those fixtures with Server handoff. The positive owner fixture now contains a real working-memory entry rather than arbitrary text. An unrelated macOS PTY timing case also failed on that head; terminal-reader code is unchanged. Updated-head CI is rerunning and must pass before the draft becomes ready. A full repository `make check` was not completed locally; the relevant all-target Rust checks are listed above. No online/live provider tests were enabled locally. Public entrypoints and unhappy paths: authenticated exit/close/status; unauthenticated finalization; valid UC/personal/local owner namespaces and foreign identity/owner/session; unsuccessful/malformed queue acknowledgments without purge; lost episode/scene/delete receipts; optional-stage retries without re-archive; stale final-turn watermark; unsupported backend retaining working memory; lease takeover and old worker rejection; canonical-context recovery after missed handoff. Database verification uses newly created isolated local MatrixOne databases and synthetic identities. No QA/production mutation or live model calls. CI's runtime online lane explicitly designates its isolated database for the shared test guard. Rebased on current upstream `main` at `89dcde88`. Host review used the open-code-review delegate skill: all 28 selected code/build files reviewed; all four documentation changes also read; 0 skipped, 100% change coverage. ## Final checklist - [x] Tests added at the owning layer, including public entrypoints and failures. - [x] Public/design/configuration and test documentation updated. - [x] Diff checked for credentials, private URLs, customer data and generated files. - [x] Conventional Commit-style title. ### Review follow-up: explicit Memoria branch scope Memoria #310 now derives keyed receipt identity from the resolved storage branch and freezes its routed store/table across embedding. Astra's durable HTTP adapter explicitly selects main for archive/working writes, typed/strict reads and exact-ID cleanup, matching its deterministic main-scoped receipt verification. Normal direct memory tools retain their existing checkout behavior. The loopback/MatrixOne durable lifecycle regressions now enforce the main selector in write bodies and read/delete queries. This branch also includes current main (`d2d44040`, #1006), including the upstream live-harness model/cache configuration and child-answer verification changes. Format checks and live-harness workflow contract tests pass (6 passed, 2 optional skips). Runtime all-target Clippy passes with warnings denied against this combined source tree. The updated online durable lifecycle regressions are executing in CI; full CI is still running. Follow-up review covered all 5 changed Rust files across Astra and Memoria (100%, zero skips); both accompanying protocol/design document changes were also read. ### Live harness follow-up: missing configured model The missing-model case required `invalid_request` without constraining how the model was selected. The canonical admission contract distinguishes an unknown configured name (`model_selection_invalid` / `invalid_request`) from an unknown Offering ID (`model_offering_not_found` / `tool_unavailable`). The probe now supplies an explicit fixed configured-name request and additionally verifies its policy mode, selector kind and requested name in canonical execution evidence. The failed result, exact error kind, no-child and no-fallback assertions remain required. The previous head's deterministic checks and four durable memory DB/loopback regressions passed. One rerun also passed the recovered-validation quality case, while the ambiguous missing-model assertion failed again. This follow-up changes only that fixture; it does not change runtime admission, quality thresholds or CI gates. YAML/JSON parsing, diff and format checks pass. All 47 strict case-loading tests pass. The live regression on `c653517` passed 8/8 cases. The stricter fixture also required updating the synthetic baseline in `shipped_rejection_cases_reject_extra_attempts_with_different_outcomes`; `5c9a3cd` supplies the complete fixed-name request and adds a negative Offering-ID-selector control, while retaining the extra-attempt rejection checks. The complete Harness library suite passes serially: 607/607, zero skipped. The initial default parallel local run hit six process/readiness timeout tests; the original timeouts were retained. All-target Harness Clippy passes with warnings denied. Full CI on `5c9a3cd` passes (40 successful checks), including the 8/8 live regression, core + Server-hooks shard, online memory regressions and CLI inventory/aggregates. Follow-up review covered both changed files (2/2, 100%, zero skips). ### Review follow-up: missing journal and complete inventory Commits `b56f26f7` and `94228684` address both new recovery findings: - Explicit close now ensures the owned journal row exists inside the canonical close transaction before recording finalization intent. A failed first bounded handoff can no longer produce a successfully closed session that recovery never discovers. The new database regression starts with committed canonical context and no journal, closes through `DatabaseSessionService`, reconstructs the store after restart, and recovers the final extraction and governance intent. - Finalization now uses a complete inventory mode in the shared HTTP typed-list implementation. It follows cursor pages under the existing ten-second read budget, accepts up to 4096 memories only with explicit pagination completion, and rejects overflow, invalid/missing/repeated cursor evidence, duplicate rows, and failed pages before freezing a plan. Ordinary typed recall retains its top-k behavior. Every page preserves the owner/session/type scope and the durable `main` branch. - HTTP regressions cover 501 rows, exact-bound completion, overflow, malformed pagination, repeated data, foreign ownership, and later-page failure. Database/HTTP regressions cover the final working receipt on either page and verify overflow leaves the plan unset, working memory retained, and maintenance pending without archive or delete calls. The new 501-row database regression also exposed a journal read defect: MatrixOne's default `CAST(state_json AS CHAR)` truncates at 65535 characters. All five journal read paths now decode the native JSON column via SQLx, with its JSON feature explicitly enabled. An additional database regression round-trips a large multibyte input through close, status, claim, fenced reload, and canonical recovery lookup. No schema change is required. Validation for this follow-up at `94228684`: - Local: all five isolated MatrixOne lifecycle regressions pass, including absent-journal close/restart and the large multibyte journal round-trip; formatting, diff checks, and all 47 schema inventory tests pass. The task-owned local database was removed afterward. - Exact-head CI: all eight added regression tests pass (four HTTP pagination tests, two durable runtime database tests, and two lifecycle database tests). Runtime offline tests, online core-runtime/core-services checks, and all six Static Checks jobs pass. - Full exact-head Test Suite: **28/28 jobs passed** ([run](https://github.com/matrixorigin/Astra/actions/runs/38672051447)). Static Checks: **6/6 jobs passed** ([run](https://github.com/matrixorigin/Astra/actions/runs/38672051457)). - The optional live harness first stopped in model-availability preflight with zero executed cases and a registered-but-inactive model. Attempt 2 is running (currently building Server/CLI/harness), with configuration and assertions unchanged ([run](https://github.com/matrixorigin/Astra/actions/runs/38672048150)). This optional lane is not yet verified as passing. - Incremental review covered all seven code/configuration files, zero skipped (100%); the memory design documentation was also reviewed and updated. ### Review follow-up: preserve confirmed working receipts Commit `a059246d` addresses [the stale-cleanup receipt review](#1005 (comment)). Before this fix, a cleanup read could replace a confirmed new working receipt with a stale ID from the first 16 backend rows. A successful deletion with a lost response could then leave completed extraction permanently unable to finalize. The typed-read adapter now preserves receipt identity once the current generation has prepared its working write. Pre-write observations can still update the previous generation's receipt, while frozen-plan reads retain their existing behavior. The fix reuses the existing durable write checkpoint; it adds no journal fields or alternate lifecycle. Two MatrixOne/loopback regressions exercise the canonical extraction writer and actual stale cleanup, acknowledged/lost delete responses, extraction settlement, owned explicit close, three restart-style claims, plan reconciliation, and final governance cleanup. The lost-response scenario places all 16 stale snapshots ahead of the confirmed hash-derived receipt in the backend list. The happy control uses one stale snapshot to stay within the existing one-second best-effort cleanup budget. Model inference uses the supported rule fallback, with no paid-provider dependency. Validation at `a059246d`: - Local runtime library/test compilation (`cargo check -p astra-runtime --lib --tests`), formatting, and diff checks pass. - [Online core-runtime](https://github.com/matrixorigin/Astra/actions/runs/38698235410/job/116299887310): **98/98 tests pass**, including both added close/restart regressions. The job log explicitly records each new test as PASS. - [Complete Test Suite](https://github.com/matrixorigin/Astra/actions/runs/38698235410): **28/28 jobs pass**, including CLI, integration, and macOS terminal checks. [Static Checks](https://github.com/matrixorigin/Astra/actions/runs/38698235321): **6/6 jobs pass**. - [Optional live harness](https://github.com/matrixorigin/Astra/actions/runs/38698232207) stopped during `glm-5.3` preflight, with zero executed cases; Server readiness and the DeepSeek status check succeeded. This lane is not passing, and its published diagnostics do not identify the underlying GLM failure. - Incremental review: 2/2 code files reviewed, zero skipped (100%); the memory design documentation was also reviewed and updated. ### Integration follow-up: latest main - Commit `a4bc6653` merges main `b091b23b` into this branch and resolves both harness conflicts without rewriting previous commits. - Preserve main's strict fixed-model admission policy, rejected/unexecuted result checks, no-child guarantee, and failure controls. Retain the configured-name versus Offering ID prompt distinction and extend the selector negative control to all three shipped model-rejection cases. Extra spawn attempts use a valid fixed-model request. - The Memoria durable finalization fixes, including confirmed working receipt preservation, remain intact. - Local validation on this commit: harness library **611/611 passed**; harness CI script suite **13 passed, 5 Linux-only skips** on macOS; runtime `cargo check -p astra-runtime --lib --tests`, workspace Rust formatting, and diff whitespace checks passed. - New GitHub CI is pending. Results recorded above apply to their explicitly identified earlier commits/runs. ### Diagnostic follow-up: child adoption failure reasons Commit `c683db37` follows a rebase onto latest main `45f56984` (including #1012). Existing Memoria changes are preserved. - The canonical child custody verifier now returns closed reason codes for failed conditions and unavailable evidence. The deterministic grader, semantic-evidence admission and safe progress projection share that verifier. Existing verdicts and failure classifications are preserved. - CI summaries distinguish child lifecycle/count, fanout group/slot/identity, repeated versus unsuccessful starts, model selection, result/digest consistency, parent finalization order, missing physical execution, and invalid or incomplete result windows. Public artifacts contain fixed codes only; no raw child results, arguments, identities, expected values, or provider error bodies. - The Python summary consumer validates the same 42-code vocabulary and rejects unknown codes, incompatible status/reason pairs, and additional payload fields. Existing progress records remain supported. - Validation on this exact commit: harness library **612/612 passed**, including **21 producer fault/control scenarios**; targeted harness Clippy with warnings denied passed; harness CI script tests **15 passed / 5 Linux-only skips** on macOS; workspace formatting and diff checks passed. - This adds diagnosis, not certification that the previous live fanout failure is fixed. A new normal PR CI run must reproduce or clear it with the more precise evidence. No performance gate or case acceptance criterion was changed. ### Rebase follow-up: main b95f234 - Rebased onto latest main `b95f2341` (#1013), resolving harness conflicts while preserving upstream explicit ID/title fanout selectors, pre-execution rejection handling, receipt-identity checks, and bounded tool-outcome diagnostics. Adapted the existing typed reason codes and fixtures to those canonical checks; the safe producer and consumer share 47 reason codes. - Confirmed the Memoria session-memory implementation is unchanged from the prior PR head. - Exact-head validation: harness library **614/614 passed**; targeted harness Clippy with warnings denied, workspace Rust formatting, and diff checks passed. Harness CI script tests: **15 passed / 5 Linux-only skips** on macOS. - New normal PR CI is pending; this update does not claim the live regression has passed. ### Review follow-up: close during a resumed admitted turn Commit `32f1149f` addresses [the latest P2 finding](#1005 (comment)). - Explicit close now reuses the existing Session-fenced execution-slot idle proof before preserving a prior generation's maintenance completion. An already-admitted follow-up invalidates the old plan even if its canonical watermark has not advanced. Late publication and canonical recovery remain discoverable through the existing journal and worker. - No new lifecycle state, schema, or migration. Idle repeated closes preserve stage receipts and completion; already-consolidated closed sessions continue rejecting new publications. - Added a real MatrixOne regression through actual Run admission, canonical writer reservation/commit, and the owned Session close service. It covers successful exit finalization, close before a resumed turn publishes/commits, rejection of early destructive work, normal late handoff and missed-handoff recovery after restart, final settlement, and repeated completed idle closes. - Local validation: integration-target compilation, targeted service library/integration-test Clippy with warnings denied, workspace formatting, and diff checks passed. The local database engine is unavailable, so database execution used the existing isolated MatrixOne CI lane. [Core-services job 116795821909](https://github.com/matrixorigin/Astra/actions/runs/38845746558/job/116795821909) passed **477/477**, with all **6/6 journal DB regressions** explicitly PASS, including `close_during_resumed_turn_recovers_after_prior_exit_finalization`. That regression exercised both normal late publication and missed-handoff canonical recovery, followed by completed repeated-close controls. Remaining PR checks are still running. ### Review follow-up: canonical settlement after terminal slot release Addresses [the remaining settlement-window review](#1005 (comment)). Terminal Run persistence releases the execution slot before canonical context commit. The shared memory idle check now also checks the coordinator's existing live writer/reservation expiry columns, using database time and current reads under the existing Session fence. Explicit close resets prior exit completion while either execution or canonical settlement remains outstanding; destructive checkpoints use the same guard. No new lifecycle state or schema is introduced. Repeated close after settlement still preserves receipts. The new `close_after_terminal_slot_release_waits_for_canonical_commit` database regression reproduces prior successful exit finalization followed by an admitted turn with a missed handoff, terminal status/slot release, close, then canonical commit. It asserts that the slot is empty and the old canonical watermark is still present before close, verifies pending work and rejection of early cleanup, then verifies restarted recovery through turn 2 and idempotent repeated close. The earlier occupied-slot cases now also commit terminal status before canonical context, matching production order. All cases additionally reject cleanup after commit while writer authority remains live. Validation at `0adda4c2`: - `cargo clippy -p astra-services --lib --test session_memory_lifecycle_db_it -- -D warnings`: passed (with the existing local debug-profile overrides). - `cargo fmt --all --check` and `git diff --check`: passed. - Local MatrixOne/Docker is unavailable. [Normal PR core-services CI](https://github.com/matrixorigin/Astra/actions/runs/38859768037/job/116839203868) passed **478/478 tests**, including `close_after_terminal_slot_release_waits_for_canonical_commit` and all **7/7 journal database cases**. This regression requires no live provider/model. Other CI checks are still running. ### Main rebase: preserve durable handoff and sole post-loop dispatch Rebased onto main `7375abe0`, retaining the merged runtime/storage latency improvements and sandbox fixes. The harness conflict resolutions preserve the existing typed child-proof diagnostics and fail-closed case without changing their content. Main now gives Server a sole detached post-loop memory-dispatch owner. The integration preserves that ownership while still publishing this PR's bounded durable input before terminal completion. Finalization always performs the bounded preparation, then defers dispatch when the host owns post-loop settlement. Skipping preparation together with dispatch would leave the post-loop worker without its durable input; dispatching in both places would undo main's ownership fix. The new ignored MatrixOne regression `post_loop_owner_preserves_durable_handoff_before_dispatch` calls actual turn finalization with the post-loop-owner host and a durable service. It requires the owner/session journal input and fingerprint to be persisted before return, while extraction remains unrequested and no memory backend write has occurred. Existing direct-dispatch and deferred-owner tests remain in place. Validation: `cargo check -p astra-runtime --lib --tests`, `cargo clippy -p astra-runtime --lib --tests -p astra-services --test session_memory_lifecycle_db_it -- -D warnings`, `cargo fmt --all --check` and `git diff --check` passed locally (using the existing local debug-profile overrides). The runtime database regressions share one test-only isolated-database guard module, preserving Clippy duplicate-module enforcement. Normal PR CI has restarted for `26271bdc`; the new database regression is not claimed as locally executed. ### CI follow-up: wait for canonical context after terminal settlement At `26271bdc`, ordinary unit-test shards and the three core online shards passed. [Integration CI](https://github.com/matrixorigin/Astra/actions/runs/38869788360/job/116871693438) ran 295 tests with 294 passing; `e2e_matrix_execution_handoff_resume_reaches_provider_http` observed canonical `completed_turn=0` while expecting 1. The failed online-core aggregate reflects that integration failure rather than additional failing test suites. Merged main #999 moved `run_settlement_finished` into the atomic terminal transaction, which precedes canonical context commit. The E2E test was still treating that event as a canonical-commit barrier. It now polls the actual owner/session context watermark under a 15-second deadline before retaining the original exact-turn assertion. A missing commit still fails by timeout and an unexpected higher turn still fails the assertion. No product acceptance condition is weakened. Validation at `40cbadd5`: `cargo clippy -p astra-runtime --features e2e-hooks --test system_matrix_http_e2e -- -D warnings`, `cargo fmt --all --check` and `git diff --check` passed (using the existing local debug-profile overrides). [The normal PR integration rerun](https://github.com/matrixorigin/Astra/actions/runs/38874422974/job/116886451691) passed **295/295 tests**, with an explicit PASS for `e2e_matrix_execution_handoff_resume_reaches_provider_http`. Baseline memory regression evidence at `26271bdc`: [core-services 481/481](https://github.com/matrixorigin/Astra/actions/runs/38869788360/job/116871693462), including the terminal-slot-release regression, and [core-runtime 104/104](https://github.com/matrixorigin/Astra/actions/runs/38869788360/job/116871693406), including the pre-terminal durable-handoff/post-loop-dispatch regression. The separate [optional live harness run](https://github.com/matrixorigin/Astra/actions/runs/38869785427/job/116871492386) completed 8 cases, 7 passing. Its failed fanout case passed root exit, successful fanout-tool count, two-child count and child-adoption proof; its hard semantic judge reported `assessment=unavailable` / `InfraVerificationUnavailable`. Model preflight passed. The retained safe artifact does not distinguish input preparation, judge invocation or response-parsing errors, so it does not establish a model-quality failure. No model selection, grading threshold or fail-closed behavior is changed by this test synchronization fix. Current-head CI follow-up: [optional live harness run 38874421050](https://github.com/matrixorigin/Astra/actions/runs/38874421050) completed **8/8 passed**, with no failed, cancelled or unavailable cases. The prior unavailable semantic assessment did not recur. No grading or model change was required for this rerun. Integration passed **295/295**, including the original failing recovery case; all test and static-check workflows have passed. Approved-by: XuPeng-SH <[email protected]>
"## Summary\n\n优化高延迟 MatrixOne 连接下的 Server
POST /chat/stream完整耗时,继续保持“权威事实先提交,再发布终态”的边界。\n\n- 合并 durable live fanout 的稀疏事件:微批窗口由 25ms 调整为 250ms;审批、工具执行请求、显式 drain、关闭和容量边界仍立即 flush。临时帧不因此变成持久化事实,提交失败不发布未提交事件。\n- 普通 Server turn 的 canonical commit 和精确 writer release 共用一次 coordinator 事务;复用事务内已锁定的 head,不重复读取。幂等重放不能释放后续 writer/reservation,外部保留的 writer 不改变生命周期。\n- 删除 run 创建后的重复完整 display projection 重建。终态 display projection、run_settlement_finished、run 状态 CAS、usage 和终态事件在既有终态事务中提交;保留 checkpoint 元数据、失去 COMMIT ACK 后的权威核对及冲突修复。独立的 settlement-start fence 保持不变。\n- Explain Analyze 产品图只在根 run 显式请求 Explain 时生成;恢复读取 durable request,子 run 不继承。普通 run 的生命周期、transcript、trace、恢复和计费事实继续保留。\n- permission round snapshot 使用单次索引只读查询;权限控制写入仍经原 owner 和事务。Server lifecycle 独占 post-loop memory settlement,删除共享 loop 的重复准入。\n- 新会话复用创建事务实际读到的 admission facts;成功创建后才记录 quota 用量。幂等创建重试返回当前实际 facts,不制造默认值。既有鉴权逻辑不变。\n- 既有 owned run task 在终态、post-loop projection/hook 和 runtime context settlement 后释放 resident state/SSE sender,再进行 distributed quota release 和已吸收 provider WAL 的退休。不新增独立清理任务;失败继续使用既有 permit-drop/TTL 和 session-boundary 重试合同。\n- WAL 退休的空、可写快照只做索引读取;非空、缺失和删除状态仍走原有锁定边界。同一 cancellation-safe checkout 用于读取及后续事务,保留租户、生命周期和取消隔离。\n- 增加结构化 DEBUG 终态阶段计时,区分 fence、drain、preparation、terminal transaction 和 canonical completion,不记录请求正文或凭证。\n- 终态准入一次读取已锁定的 run 元数据及取消标记,结算复用同一事务拥有的 facts,根 run 不重复读取自身取消标记;子 run 仍锁定并校验完整祖先链。推理准入在 control epoch 等于锁定事件 frontier 时不查后续 guidance;旧 epoch 保留原查询,全部 owner/generation/lease/cancellation 检查不变。\n\n## Related issue\n\nCloses #998.\n\n## Change type\n\n- [x] Refactor or performance improvement\n- [x] Bug fix\n- [x] Test\n- [x] Documentation\n\n## User and compatibility impact\n\n不新增数据库 schema、迁移、基础设施、公开协议或配置项。正常流式请求减少重复事务和查询;普通请求不再额外生成未请求的 Explain 产品图。显式 Explain、权限、认证、计费、durable replay、owner generation fencing 和外部 writer 保留合同不变。\n\ndistributed quota 清理可以晚于客户端完成,但在 context 仍驻留期间保守保留配额,不提前承诺容量释放。首次请求、provider 抖动和远端数据库抖动仍计入耗时;本 PR 不承诺任意模型/复杂任务的固定时限。\n\n## Architecture and complexity delta\n\n- Canonical owner changed or extended: 既有 live fanout、DatabaseSessionContextCoordinator、DatabaseRunStateStore、Server lifecycle、permission store 和 SessionService。\n- Existing implementations and callers searched: run 创建、终态、恢复、取消、interaction closure、lost-ACK reconciliation、writer replay/release、session admission/deletion、WAL retirement、memory settlement 和 session quota 调用点及测试。\n- Superseded code, states, tables, shims, or self-only tests removed: 重复 projection rebuild、独立 normal-path projection repair、重复 Server memory admission;commit/release 共用commit_turn_inner。没有新增表或第二套状态权威。\n- If parallel implementations remain, their boundary and retirement condition: 原commit_turn用于外部保留 writer,commit_turn_and_release_writer仅用于本 run 内部取得的精确 writer;二者共享实现。非正常终态和失去提交确认继续使用既有显式 reconciliation,不引入新的 fallback。\n\n## Verification\n\n- Commands and results:\n -cargo fmt --all --check、git diff --check:通过。\n -cargo clippy --locked -p astra-services -p astra-runtime --lib -- -D warnings:通过。\n -cargo test --locked -p astra-runtime --lib server::run::lifecycle:614 passed,56 个 opt-in DB tests ignored。\n -cargo test --locked -p astra-runtime --lib chat_handlers::session_resolution_tests --quiet:9 passed,包含创建失败不消费 quota。\n -cargo test --locked -p astra-services --lib auth:: --quiet:105 passed;cargo test --locked -p astra-services --test session_create_transaction_contract --quiet:2 passed。\n - 已执行的 fanout/host/auth/terminal-settlement 专项覆盖事件顺序、即时 interaction、Explain opt-in、Memoria TTL 和 checkpoint/lost-ACK 合同;未以放宽断言或跳过失败替代修复。\n- Public entrypoint exercised: 本地 debug Astra 经真实 HTTPPOST /chat/stream访问生产 MatrixOne 的隔离临时 account/database;只发送hi,不经过 MOI,不启用 Memoria/Edge。测量 POST 开始至 completedrun_finished,同时验证 SSE EOF。\n- Unhappy paths exercised: 注入 fanout 提交失败、canonical writer commit 拒绝、后续 writer 重放保护、删除 fencing,以及会话创建失败;既有生命周期/恢复测试继续通过。\n- Database verification: 使用随机独立测试 database 实测下列回归,不修改任何客户 workspace:\n -db_stream_terminal_precedes_blocked_quota_cleanup:锁住 distributed admission gate,完整流仍结束;canonical context/writer 已正确提交,reservation 保守保留;解锁后 owned task 清理完成。\n -empty_canonical_wal_retirement_preserves_lifecycle_fencing:空快照不等待无关 child-write lock;缺失 fence 沿用原路径,durable deletion 仍拒绝。\n -canonical_transition_wal_is_isolated_by_owner_and_session:非空 WAL 清理保持 owner/session 隔离。\n -provider_session_creation_is_idempotent_across_service_instances:跨实例并发只有一个创建者;quota 已用尽时允许精确重试,重试返回期间变更的实际 admission facts,冲突参数拒绝。\n -database_terminal_admission_preserves_identity_and_lineage_cancellation:事务准入不可跨 session;根直接取消和子 run 祖先取消都拒绝 completed,正常准入仍成功,回滚不留状态/usage。\n -run_inference_admission_fences_generation_owner_lease_guidance_and_cancel、provider_attempt_revalidates_scope_authority_after_logical_admission:精确空 frontier 准入,以及旧 guidance、取消、owner/generation/lease 变化均按原合同处理。\n -canonical_terminal_success_commits_evidence_usage_and_terminal_together、canonical_terminal_rejects_colliding_evidence_before_settlement:checkpoint/terminal/transcript/usage 同事务及证据冲突回滚通过。\n - 一次 provider-attempt 测试在 fixture INSERT 阶段发生远端 I/O timeout;未执行到修改路径,同源重跑通过。未放宽 deadline 或断言。\n\n延迟验证使用同一临时 account/database、同一已验证deepseek-v4-flashroute,thinking off、32-token 输出上限、不请求 Explain、默认 trace profile、内置连接池上限 80、不启用 SQL tracing。下表既有批次显式设置turn_intent=fixed_default、skill_auto_route=disabled;生产请求路径(MOI 硬编码turn_intent=fixed_default、其他字段缺省)单独以等效配置验证。每批重新启动进程和创建会话;冷样本、慢样本及失败均保留。未独立确认该配置与生产部署全部参数一致,不将此测试等同于 MOI/MOMO 用户请求。\n\n| 代码/测试 | 请求数 | P50 | P90(nearest-rank) | 结果 |\n| --- | ---: | ---: | ---: | --- |\n| 未修改 main89dcde88f,批内复用会话 | 24 | 7.85s | 9.51s | 24/24 completed |\n|6dcbaa977,独立复测,批内复用会话 | 24 | 5.79s | 6.89s | 24/24 completed |\n|973c3dc9,批内复用会话 | 24 | 5.63s | 9.13s | 24/24 completed;未达到稳定 P90 <7s |\n|973c3dc9,每次新建会话 | 60 | 6.11s | 6.94s | 60/60 completed;SSE EOF P90 6.94s |\n|781804710,每次新建会话,独立复测 | 60 | 6.22s | 7.30s | 60/60 completed;仍未证明稳定 P90 <7s |\n|8f90108c9,每次新建会话,受控策略 | 60 | 5.88s | 6.54s | 60/60 completed;冷样本保留 |\n|8f90108c9,每次新建会话,默认策略 | 60 | 5.84s | 7.59s | 60/60 completed;默认策略未达标 |\n| base20abb6320vs headab03c53b9(每请求新会话、MOI 等效生产turn_intent=fixed_default+skill_auto_route=auto、生产 DB + 生产模型路由,2026-10-15) | base 60/60、head 60/60 | base 10.80s / head 8.55s | base 12.14s / head 10.39s | mean base 11.50s / head 8.82s;10-trial 块对齐均值优势 -4.86s、-2.10s、-3.03s、-1.77s、-2.13s、-2.15s,六组全为 head 更快 |\n|8f90108c9受控策略其余批次(交互、session、authorization、work/server docs 专项) | 96 | — | — | 全部通过,未修改断言或排除 |\n\n早期两批逐请求新会话结果为 6.94s 和 7.30s,未据此声明稳定达标。减少同一事务的重复锁定事实读取后,受控策略 60 次 P90 为 6.54s,但默认execution_policy的独立 60 次 P90 为 7.59s,仍未达标,不能用受控配置替代默认请求的验收。按用户要求,完整 CI/gates 不阻塞本轮优化;未声明所有 CI 已通过。\n\n- Review follow-up (head 1a67de1):run_settlement_finished不再作为 durable live attach 的提前关闭条件;终态 Explain run 无论是重连后观察还是原订阅持续跟随,都保持同一 publication grace/final durable read。新增durable_live_attach_waits_for_delayed_publication_after_settlement_committed覆盖 settlement 先提交、publication 延后到达的顺序。本地验证:cargo test -p astra-runtime --lib durable_live_attach -- --nocapture7 passed;cargo clippy --locked -p astra-runtime --lib -- -D warnings、cargo fmt --all、git diff --check通过。\n\n## Final checklist\n\n- [x] I added or updated tests at the layer that owns the behavior.\n- [x] I updated design documentation for lifecycle and Explain behavior.\n- [x] I checked the diff for credentials, private URLs, customer data, generated files, and other sensitive information.\n- [x] The PR title follows the repository's Conventional Commit format."