Skip to content

fix(memory): confirm CLI archive writes and preserve consolidation cooldown - #997

Merged
mergify[bot] merged 2 commits into
matrixorigin:mainfrom
loveRhythm1990:fix/memoria-session-finalization
Oct 14, 2026
Merged

mergify[bot] merged 2 commits into
matrixorigin:mainfrom
loveRhythm1990:fix/memoria-session-finalization

Conversation

@loveRhythm1990

@loveRhythm1990 loveRhythm1990 commented Oct 13, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

CLI exit now persists a typed episode through the authenticated Server memory proxy before deleting its tracked working snapshot. The CLI transport also implements scene persistence and reflection instead of inheriting unsupported/no-op operations. It shares the direct transport's typed encoders, reflection decoder, and receipt validation.

Missing, empty, wrong-type, whitespace-only, and malformed write receipts cannot authorize working cleanup or a user-visible claim of storage. Unsupported persistence fails explicitly. Required episode/purge failures keep retry eligibility; optional reflection/scene failures remain diagnostic and do not prevent successful consolidation from starting the 15-minute debounce cooldown or cause those completed stages to replay. Successful backend reflection cooldown skips are accepted as empty optional results.

Related issue

Refs #996. This PR addresses write receipts, the CLI no-op archive/cleanup defect, and completion-cooldown classification. The issue remains open for its separate Astra/Memoria owner-namespace mismatch, cross-instance close/extraction coordination, and durable/idempotent retry concerns. This PR does not claim those broader lifecycle concerns are fixed.

Change type

  • Bug fix
  • Documentation
  • Test
  • Feature
  • Refactor or performance improvement
  • Build, CI, or maintenance

User and compatibility impact

  • CLI users with admitted memory access and a valid session snapshot can now archive the episode and complete working cleanup on normal exit.
  • Failed or unconfirmed archive writes preserve working memory. Existing fail-closed snapshot reads and owner/session validation are preserved.
  • An optional reflection failure no longer blocks consolidation cooldown. Scene receipt failures remain accurately counted without replaying episode/purge work.
  • Existing valid Memoria responses, credential policy, and timeout budgets remain compatible. No deployment, database, or secret changes.

Architecture and complexity delta

  • Canonical owners extended: astra-memoria owns reusable receipt-ID validation and reflection response decoding; runtime owns typed encoders and the one session-end governance sequence; CLI remains an authenticated transport adapter to that sequence.
  • Existing implementations and callers searched: direct/user-scoped Memoria ports, explicit memory gateway, CLI startup/exit, Server close scheduling, background extraction, and the session-end debouncer.
  • Removed empty successful write acknowledgments and inherited no-op CLI archive behavior. The receipt rule is defined once and reused for HTTP JSON responses and arbitrary port-returned IDs.
  • No new lifecycle state machine, credential fallback, table, or schema. Optional reflection is separated from required consolidation completion; no durable retry queue is introduced.

Verification

Passed locally:

  • cargo test -p astra-memoria --lib: 18 passed.
  • cargo test -p astra-tools --lib memoria::tests::: 49 passed.
  • cargo test -p astra-runtime --lib turn::cloud::session_end_governance::tests::: 20 passed.
  • Compiled runtime lib-test executable, filter turn::cloud::memoria_compact::tests::: 63 passed (including invalid receipts in all three HTTP store paths).
  • cargo test -p astra-cli --lib cli::session::session_startup::tests::cli_: 6 passed, including real CLI finalization through loopback HTTP mocks.
  • cargo test -p astra-cli --lib cli::session::session_cleanup::tests::: 8 passed.
  • make format-check and git diff --check: passed.
  • python3 scripts/ci/validate_repository.py: passed.

cargo clippy -p astra-memoria -p astra-tools -p astra-runtime -p astra-cli --all-targets -- -D warnings: passed. Repository CI is still running on the updated head; no failing check was reported when marking ready.

  • Public entrypoints exercised: CLI finalize_session_with_budget, canonical session-end governance, direct HTTP store operations, and explicit remember HTTP gateway.
  • Unhappy paths exercised: missing/empty/malformed receipts retain working state; unsupported transport persistence fails; optional reflection HTTP 503 and successful cooldown skips; unconfirmed scenes do not count as stored; required failures do not start successful cooldown.
  • Database verification: not applicable; no SQL, schema, or transaction changes.
  • Source review: 7/7 follow-up files reviewed, no skips, including the memory design/debounce documentation.

Final checklist

  • Added or updated tests at the behavior-owning layer.
  • Updated the memory design contract and cooldown documentation.
  • Checked the diff for credentials, private endpoints, customer data, and generated files.
  • Conventional Commit-style PR title.

Latest upstream main (365e313c) was merged into this feature branch with merge commit 935f7f2c; the review fixes were appended in 6dbeb704.

@loveRhythm1990 loveRhythm1990 changed the title fix(memory): validate write receipts and preserve cleanup retry eligibility fix(memory): confirm CLI archive writes and preserve consolidation cooldown Oct 13, 2026
@loveRhythm1990
loveRhythm1990 marked this pull request as ready for review October 13, 2026 13:33

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

评审结论:APPROVE。实际代码评审:GPT-6 Astra / xhigh。

提交前核验(2026-10-14T05:59:44.535Z):PR 为 OPEN,head 为 6dbeb704bf361b5ac8589a96a0fea40331a34982;完整 CI 与下文证据一致,适用检查全部通过;没有新增可见实质评审。以下保留完整发现、验证范围与限制。


PR #997 独立评审建议:APPROVE,限定本次补丁;没有发现足以要求修改的新增高置信度缺陷。 实际评审由指定的 GPT-6 Astra / xhigh 完成。

评审对象是 fix(memory): confirm CLI archive writes and preserve consolidation cooldown。2026-10-14 05:08:15 UTC 最后复核时,PR 为 OPEN、非 draft;head 未在评审期间变化。

  • 精确 head:6dbeb704bf361b5ac8589a96a0fea40331a34982。
  • PR API advertised base:365e313cba7e018edd8c35ab1552f8e67b85c5db。
  • 本地 Git 核实的 merge-base:365e313cba7e018edd8c35ab1552f8e67b85c5db。
  • 最后复核的当前 main:83c0281d16e21a7d0ce6337a0c2604f3f9a41b34;PR 的 mergeable_state=behind。下述 CI 是这个 head 的既有检查,不能视作与当前 main 集成后的验证。

CI 与重复评审检查。 首次检查于 05:00:57 UTC 开始,05:08:15 UTC 再次核验了 checks、commit statuses、workflow runs 和全部可见评审记录。

  • checks:39/39 已完成,36 success、2 skipped(Web、SDK)、1 neutral(Mergify Merge Queue),没有失败或进行中的检查。
  • Actions:5/5 success,包括 Test Suite、Static Checks、两次 PR Title 和 Supersede stale PR runs。Test Suite 于 2026-10-13 13:38:28 UTC 完成;Summary check 于 13:38:55 UTC 成功。
  • commit statuses:0 条。Combined status 返回的字面值 pending 对应空 statuses 集合,不存在一条正在等待的传统 status check。
  • reviews、inline review comments、issue conversation comments 均为 0。可见记录中没有当前 head 的进行中或已完成实质评审;未将空 approval/comment 或旧 head 记录当作完成依据。API 各集合均不足每页 100 条,check/workflow 的返回数与 total_count 一致,无遗漏分页。

设计和代码判断。 完整阅读了全部 8 个改动文件(614 additions / 72 deletions),并将本地评审快照的 8 个文件逐一与 GitHub head blob SHA 对齐。已阅读 AGENTS.md、CONTRIBUTING.md、架构和 memory 设计、测试指南;仓库没有适用的 .agents/skills。评审同时追踪了 CLI finalizer、ThinClient、Server memory proxy、UserScoped/HTTP MemoriaPort、working snapshot loader、显式 memory gateway 和 Server close/debouncer 调用链。

文件与定位 结论
session_startup.rs:491;501、516、535 CLI 的新增 episode/scene 写入复用 canonical typed encoder 和已认证 Server proxy;episode 收据验证成功后治理才可进入 purge。反射请求显式使用 candidates 模式。
astra-memoria/lib.rs:283;413、494 收据规则集中在共享边界;不支持的 episode/scene 操作显式失败;reflection decoder 在直接和代理传输间复用。
astra-tools/memoria.rs:1436;1657 remember 不再从空成功响应构造“已存储”确认,正常错误响应仍保留原错误。
memoria_compact.rs:109;870、993、1036、1074 typed 编码成为复用接口,三个直接 HTTP store 路径使用统一收据验证;反射 JSON 解析失败可观察。
session_end_governance.rs:212;283、350 对非 HTTP port 返回的 ID 也进行校验;未确认的 episode 不授权 purge,未确认的 scene 不计成功;必需阶段和可选阶段的结果分类清楚。
session_handlers.rs:1901 必需 episode/purge 失败不再提交成功冷却,permit drop 释放后续调用资格;失败 flags 进入结构化日志。
session_end_debounce.rs:25 本文件仅修改注释;既有 owner+session key、代际 permit 和有界完成记录保持一致。
docs/design/memory.md:99 文档覆盖收据、失败分类、CLI 五秒维护预算与取消;durable retry 的范围限制已明确。可选阶段超时还有下述既有边界。

数据库 I/O、并发与资源成本。 这次补丁没有 SQL/schema/transaction 变更,但 CLI 成功归档现在实际产生 episode 写请求、一次 reflection 请求以及每个候选一次串行 scene 写请求;各代理操作继续经过 session ownership 和当前 Memoria authority 检查,因此会有相应鉴权/权限解析成本。没有把“无 SQL diff”解释为零数据库成本。新增收据处理是本地字符串/JSON 校验;没有额外读取探测、批量后台任务或共享凭证缓存。CLI 仍受总计五秒退出维护预算限制;Server 仍为六十秒。既有 debouncer 隔离 owner/session 的能力经本地测试验证,但它只协调单进程治理调用,不构成跨实例锁或 extraction fence。没有运行真实数据库性能或多实例负载测试。

非阻塞遗留边界。 有一个可确定、但已存在于 base 的超时限制,建议继续在 #996 的生命周期后续工作中追踪:如果 episode/purge 已完成,而可选 reflection 或 scene 持久化耗尽外层总预算,session_handlers.rs:1885 的 timeout 会丢弃治理 future,代码无法到达 1901 的 consolidation_complete() 判断;permit 随后释放,成功冷却不会被记录。再次关闭可再次进入治理;是否产生重复 episode 还取决于后续 snapshot/facts 状态。本地探针确认了“必需阶段已执行、reflection pending、超时后可重新获取 permit”。base 中已有同一外层 timeout 和释放路径,因此不作为本 PR 新增缺陷或阻塞项。文档中“可选失败不会影响冷却”应理解为返回 Ok(report) 的完成路径,不能外推至总预算取消。

此外,#996 已披露且本 PR 明确未解决的 Astra/Memoria owner namespace 不一致、close 与 extraction/跨实例协调、耐久/幂等重试问题仍然存在。本次评审不把保留重试资格当作已建立自动重试,也不把一个 ID 收据当作跨请求原子性或 exactly-once 证明。

本地验证。 所有检查使用 /tmp/astra-pr-997 隔离快照和合成数据;未调用生产/共享服务或付费模型接口,未修改产品代码、推送、重跑远端 CI或合并。

  • 当前 head 的真实 astra-memoria/src/lib.rs 用 rustc 和环境现有只读依赖工件编译:18/18 单元测试通过,包括无效收据、unsupported persistence、scope 和状态隔离用例。
  • 当前 head 的真实 session_end_debounce.rs 独立编译:10/10 单元测试通过,包括相同 session 不同 owner、独占 permit、取消/失败释放、旧代际清理和有界缓存。
  • 直接包含当前 head 的治理与 debouncer 模块的隔离探针:9 个场景断言通过,覆盖 4 类无效 episode ID、读失败、purge 失败、可选 reflection 失败、空 scene 收据,以及上述可选阶段 pending 后取消边界。该探针明确使用成功空 snapshot seam,不能代替真实 snapshot parser 或 HTTP/数据库集成测试。
  • 正常 cargo test --offline --locked -p astra-memoria --lib 在 workspace 依赖解析阶段因缓存缺少 rand_pcg 退出,尚未开始编译。没有绕过离线约束;直接源码验证结果不等价于完整 Cargo workspace 构建。完整 CLI/Server HTTP 测试本地未重跑,其既有 head CI 成功作为独立证据。

支持证据均保存在本目录:github-evidence.json(状态、SHA、39 checks、5 workflows、分页和评审检查)、memoria-direct-tests.log、debounce-tests.log、governance-probe.log、memoria-tests.log(Cargo 阻塞原因)、governance-probe.rs 和 verify.py。重放隔离源码检查可运行 python3 /tmp/astra-pr-997/verify.py。

@mergify mergify Bot added the queued label Oct 14, 2026
@mergify

mergify Bot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-10-14 06:00 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • 🚫 Left the queue — 2026-10-14 06:00 UTC · at 6dbeb704bf361b5ac8589a96a0fea40331a34982

This pull request spent 7 seconds in the queue, with no time running CI.

Reason

The pull request can't be updated

GitHub response: refusing to allow a GitHub App to create or update workflow .github/workflows/harness-manual.yml without workflows permission
GitHub only lets Mergify write to .github/workflows/ with the workflows permission. An organization owner can accept Mergify's pending permissions at https://dashboard.mergify.com/orgs/matrixorigin/repositories.

Hint

You should update or rebase your pull request manually. If you do, this pull request will automatically be requeued once the queue conditions match again.
If you think this was a flaky issue, you can requeue the pull request, without updating it, by posting a @mergifyio queue comment.

Requeued — the merge queue status continues in this comment ↓.

@mergify mergify Bot added dequeued and removed queued labels Oct 14, 2026
@XuPeng-SH
XuPeng-SH force-pushed the fix/memoria-session-finalization branch from 6dbeb70 to 0dc2234 Compare October 14, 2026 06:34
@mergify mergify Bot added queued and removed dequeued labels Oct 14, 2026
@mergify

mergify Bot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-10-14 07:38 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • ✅ Checks skipped · PR is already up-to-date
  • ✅ Merged — 2026-10-14 07:39 UTC · at 62d5f03e2e22d41f89aee31055c5ded040ea0d0d · squash

This pull request spent 17 seconds in the queue, including 1 second running CI.

Required conditions to merge
  • #review-threads-unresolved = 0 [🛡 GitHub branch protection]
  • github-review-approved [🛡 GitHub branch protection]
  • any of [🛡 GitHub branch protection]:
    • check-success = Check PR title
    • check-neutral = Check PR title
    • check-skipped = Check PR title
  • any of [🛡 GitHub branch protection]:
    • check-success = check
    • check-neutral = check
    • check-skipped = check
  • any of [🛡 GitHub branch protection]:
    • check-success = Test: core crates + bridge hooks
    • check-neutral = Test: core crates + bridge hooks
    • check-skipped = Test: core crates + bridge hooks
  • any of [🛡 GitHub branch protection]:
    • check-success = Test: astra-runtime
    • check-neutral = Test: astra-runtime
    • check-skipped = Test: astra-runtime
  • any of [🛡 GitHub branch protection]:
    • check-success = Test: astra-cli (edge-fs-tools)
    • check-neutral = Test: astra-cli (edge-fs-tools)
    • check-skipped = Test: astra-cli (edge-fs-tools)
  • any of [🛡 GitHub branch protection]:
    • check-success = Test: astra-cli (edge-git-gix)
    • check-neutral = Test: astra-cli (edge-git-gix)
    • check-skipped = Test: astra-cli (edge-git-gix)
  • any of [🛡 GitHub branch protection]:
    • check-success = Test: astra-cli (edge-rest)
    • check-neutral = Test: astra-cli (edge-rest)
    • check-skipped = Test: astra-cli (edge-rest)
  • any of [🛡 GitHub branch protection]:
    • check-success = Test: astra-cli (edge-shell)
    • check-neutral = Test: astra-cli (edge-shell)
    • check-skipped = Test: astra-cli (edge-shell)
  • any of [🛡 GitHub branch protection]:
    • check-success = Test: astra-cli (non-edge)
    • check-neutral = Test: astra-cli (non-edge)
    • check-skipped = Test: astra-cli (non-edge)
  • any of [🛡 GitHub branch protection]:
    • check-success = Test: online (core)
    • check-neutral = Test: online (core)
    • check-skipped = Test: online (core)
  • any of [🛡 GitHub branch protection]:
    • check-success = Test: online (integration)
    • check-neutral = Test: online (integration)
    • check-skipped = Test: online (integration)
  • any of [🛡 GitHub branch protection]:
    • check-success = Test: turn-core + services + plan
    • check-neutral = Test: turn-core + services + plan
    • check-skipped = Test: turn-core + services + plan
  • any of [🛡 GitHub branch protection]:
    • check-skipped = web (typecheck, test, build)
    • check-neutral = web (typecheck, test, build)
    • check-success = web (typecheck, test, build)
  • any of [🛡 GitHub branch protection]:
    • check-skipped = Astra SDK (typecheck, test+coverage, build)
    • check-neutral = Astra SDK (typecheck, test+coverage, build)
    • check-success = Astra SDK (typecheck, test+coverage, build)
  • any of [🛡 GitHub branch protection]:
    • check-success = Test: macOS workspace coordination
    • check-neutral = Test: macOS workspace coordination
    • check-skipped = Test: macOS workspace coordination

@mergify
mergify Bot merged commit 62d5f03 into matrixorigin:main Oct 14, 2026
@mergify mergify Bot removed the queued label Oct 14, 2026
mergify Bot pushed a commit that referenced this pull request Oct 16, 2026
## 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]>
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.

2 participants