diff --git a/.gitignore b/.gitignore index fd4337af8..ff93b54b8 100755 --- a/.gitignore +++ b/.gitignore @@ -159,6 +159,7 @@ demo/memcell_outputs/ # AI agent tooling (local agent skills/config, not part of the project) .agents/ AGENTS.md +smartcomment_docs/ *.duckdb diff --git a/CHANGELOG.md b/CHANGELOG.md index 125efb310..c53aceea0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,8 +7,60 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Fixed + +- **A resent `/memory/add` no longer cuts the same messages twice** (#274). + Messages were deduplicated only against the session buffer, so a client + retrying after a timeout re-sent messages the first call had already cut + into a memory cell, and they became a second memcell and episode. The + boundary stage now drops fresh messages a memcell of the session already + holds. Message ids no longer depend on where a message sits in its request: + `m___`, `digest` covering who said what (a + message repeated verbatim in one request is told apart by its repeat + count), so a resend -- whole, split or regrouped, within one millisecond + too -- keeps its ids, and two different messages sent in separate requests + with one timestamp are no longer merged into one. Messages sharing a + timestamp keep arrival order in the buffer rather than sorting by id. + The internal helper `everos.memory.extract.ingest.gen_message_id` is + replaced by `message_ids`. Buffered messages from an earlier version keep + their old ids; a batch sent before the upgrade and resent after it is not + recognized as a resend. + +## [1.7.1] - 2026-11-20 + +EverOS 1.7.1 writes each conversation's memory in its own language: a short +call names the language of every memcell before its episode is written, and +the episode, its summary, its atomic facts and a first profile follow it. +Episode summaries are now written offline from the stored episode, a +memcell's atomic facts and clustering embedding are computed once for all of +its owners, and episode `hybrid` search ranks over three recall lanes, with +bounded recall pools for `agentic` and `vector` search. A new +`POST /memory/device/add` route lets one hardware device keep separate memory +for each person it hears. Foresight, off by default since 1.2.3, is removed. + +What changes for an existing setup: `hybrid` search's `top_k` now counts +episodes, each carrying at most one atomic fact; a store that ran foresight +has its foresight data removed on first start; and the Python API for +building `UserMemoryPipeline` and `ReflectionOrchestrator`, and for +implementing `EpisodeStore`, changed. HTTP request bodies and the CLI are +unchanged apart from additions. See Upgrade below. + ### Added +- **An episode's language is named before it is written.** Each memcell with + a user sender first gets one short call on the new `language` LLM task + (everalgo `LanguageDetector`), which names the language of its + conversation -- Chinese, Japanese or English, any other language as English + -- from the sentences the participants write to each other, not from + pasted code or documents, names, or a few words of another language mixed + in. The episode is extracted in that language and stores + it, and its summary, atomic facts and (on first build) profile follow it. + A failed or slow call leaves the language to the episode model, as before, + and the episode stores the language its text is written in; a memcell with + no chat text makes no call. `[llm.language]` defaults to temperature 0, + 64 output tokens, a 3-second timeout and no retries, so the call adds at + most 3 seconds per memcell to a synchronous `/add`. See + `docs/how-memory-works.md` and `docs/configuration.md`. - **OME strategies `summarize_episode` and `split_episode_by_owner`**, both on by default and named so in `ome.toml`. `summarize_episode` writes each episode's display summary (below); `split_episode_by_owner` hands each @@ -30,6 +82,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed +- **Reflection merges in the owner's profile language.** Without one, the + merged episodes vote with their stored languages and a language held by + more than 60% of them is used; a closer split leaves it to the reflector + and the language is read off the merged text. The merged episode stores + that language and its atomic facts are written in it; before, the merge + chose its own language and stored none. +- **Log lines name the language each step writes in.** + `episode_language_decided` / `episode_language_undecided` (`reason` + `no_chat` or `failed`) per memcell; `episode_written` with `language` and + `language_from` (`decided` or `text`); `atomic_facts_extracted` gains + `language`; `user_profile_extracted` gains `language` and `language_from` + (`frozen` or `event`); `reflection_merged` gains `language` and + `language_from` (`profile`, `vote` or `text`). +- **`everalgo-user-memory` 0.9.0 -> 0.10.1**, which only adds + `LanguageDetector`. - **Episode `hybrid` search ranks three recall lanes.** BM25 and the episode vector are fused with an atomic-fact lane (200 facts max-pooled onto at most 50 episodes) by two RRF passes, and each kept episode is scored on the @@ -105,6 +172,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 `.foresights/` folder removed (logged as `retired_kind_data_removed`): nothing reads them, and purge and deletion no longer reach them. +### Fixed + +- **`everos demo` keeps the conversation on its newest line.** The conversation + panel follows every new line, also after the reader scrolled up; on a slow + machine it could stay at the top. +- **Agent-skill extraction no longer fails when the agent is deleted + mid-run.** A `SKILL.md` (or a skill's reference or script) removed between + being found and being read now reads as absent instead of raising + `FileNotFoundError`, which failed the `extract_agent_skill` run. + ### Upgrade | If you | Then | @@ -117,6 +194,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 | want no summary call at all | disable `summarize_episode`; episodes keep their placeholder summary | | read `owner_id`, `episode_entry_id` or `owner_name` from `EpisodeExtracted` in your own strategy | read `copies` (one entry per owner), or subscribe to `EpisodeExtractedForOwner` | | build `UserMemoryPipeline` or implement `EpisodeStore` in Python | drop `summary_llm`; add `replace_summary` | +| build `UserMemoryPipeline` or `ReflectionOrchestrator` in Python | pass `language_llm`, or `profile_store` | +| point `[llm]` at a model that thinks before it answers | set `[llm.language]` to a model with thinking off: thinking runs out of its 64 tokens, and every episode falls back to the model's own language choice (`episode_language_undecided`, `reason="failed"`) | Stop the old server normally so it finishes its queued background runs. A profile run still pending under the 1.7.0 event when the old server stopped @@ -2722,7 +2801,8 @@ for AI agents. - **Decoupled algorithms** — memory extraction algorithms live in the standalone `everalgo-*` libraries published on PyPI. -[Unreleased]: https://github.com/EverMind-AI/EverOS/compare/v1.7.0...HEAD +[Unreleased]: https://github.com/EverMind-AI/EverOS/compare/v1.7.1...HEAD +[1.7.1]: https://github.com/EverMind-AI/EverOS/compare/v1.7.0...v1.7.1 [1.7.0]: https://github.com/EverMind-AI/EverOS/compare/v1.6.0...v1.7.0 [1.6.0]: https://github.com/EverMind-AI/EverOS/compare/v1.5.1...v1.6.0 [1.3.1]: https://github.com/EverMind-AI/everos/compare/v1.3.0...v1.3.1 diff --git a/README.md b/README.md index d3755d883..fc6cca873 100644 --- a/README.md +++ b/README.md @@ -22,6 +22,7 @@
- [Why EverOS](#why-ever-os) +- [Benchmarks](#benchmarks) - [Ecosystem Integrations](#ecosystem-integrations) - [Quick Start](#quick-start) - [Use Cases](#use-cases) @@ -87,6 +88,25 @@ for fast retrieval and self-evolving reuse.
+## Benchmarks + +| Benchmark | Questions | Accuracy | Answer model | +|---|---|---|---| +| [LoCoMo](benchmarks/locomo.md) | 1,540 | **94.61%**\* | `openai/gpt-4.1-mini` | +| LongMemEval | 500 | **94.00%** | `google/gemini-3.6-flash` | +| EverMemBench | 2,400 | **66.67%** | `google/gemini-3-flash-preview` | +| SubtleMemory | 1,522 | **71.75%** | `openai/gpt-5.4` | + +\* Re-judged: the 99 questions whose gold answer the LoCoMo audit disputes are graded +against its corrected answers. + +On LoCoMo, `hybrid` search, which calls no LLM, returns in 0.27 s at the median. +Accuracy and search time across models and retrieval methods are in +[benchmarks/locomo.md](benchmarks/locomo.md); how to reproduce every number is in +[benchmarks/README.md](benchmarks/README.md). + +
+ ## Ecosystem Integrations EverOS adds durable memory to the agent and workflow platforms below—and comes @@ -276,8 +296,10 @@ OpenAI-compatible model can replace them. | Multimodal parsing | `[multimodal]` | `google/gemini-3.8-flash` | The extraction model and the deciders above produced our published benchmark -results; [benchmarks/README.md](benchmarks/README.md#6-results) lists which -model ran in which role for each benchmark, and how to reproduce them. +results; [benchmarks/README.md](benchmarks/README.md#results) lists which +model ran in which role for each benchmark, and how to reproduce them. To choose +other models, the [LoCoMo results table](benchmarks/locomo.md#results-by-model-and-retrieval-method) +compares accuracy and search time across models and retrieval methods. ### Optional: Ingest Multimodal Files diff --git a/README.zh-CN.md b/README.zh-CN.md index 3d620ead7..f9ed4487b 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -22,6 +22,7 @@
- [为什么选择 EverOS](#为什么选择-everos) +- [评测](#评测) - [生态集成](#生态集成) - [快速开始](#快速开始) - [使用场景](#使用场景) @@ -87,6 +88,23 @@ agent trajectories 保存为可读 Markdown,并同步本地 SQLite 与 LanceDB
+## 评测 + +| 评测 | 题量 | 准确率 | 答题模型 | +|---|---|---|---| +| [LoCoMo](benchmarks/locomo.zh.md) | 1,540 | **94.61%**\* | `openai/gpt-4.1-mini` | +| LongMemEval | 500 | **94.00%** | `google/gemini-3.6-flash` | +| EverMemBench | 2,400 | **66.67%** | `google/gemini-3-flash-preview` | +| SubtleMemory | 1,522 | **71.75%** | `openai/gpt-5.4` | + +\* 重判口径:LoCoMo 审计认为标准答案有误的 99 道题,按审计修正后的答案判分。 + +在 LoCoMo 上,不调用 LLM 的 `hybrid` 检索中位数 0.27 秒。不同模型、不同检索方式的分数和检索耗时见 +[benchmarks/locomo.zh.md](benchmarks/locomo.zh.md),每个数字怎么复现见 +[benchmarks/README.zh.md](benchmarks/README.zh.md)。 + +
+ ## 生态集成 EverOS 为下列 Agent 与工作流平台提供持久记忆,并已内置于 Raven。选择一个 @@ -279,7 +297,8 @@ curl -X POST http://127.0.0.1:8000/api/v2/memory/search \ | 多模态解析 | `[multimodal]` | `google/gemini-3.8-flash` | 其中抽取模型和 decider 就是我们已发表 benchmark 指标所用的模型;每个 benchmark 各角色用的 -是哪个模型、怎么复现,见 [benchmarks/README.zh.md](benchmarks/README.zh.md)。 +是哪个模型、怎么复现,见 [benchmarks/README.zh.md](benchmarks/README.zh.md)。想换用其他模型, +[LoCoMo 结果总表](benchmarks/locomo.zh.md#各模型和检索方式的分数与耗时) 按模型和检索方式对比了分数和检索耗时。 ### 可选:摄取多模态文件 diff --git a/benchmarks/README.md b/benchmarks/README.md index 2f8a2d6e2..5f6133e11 100644 --- a/benchmarks/README.md +++ b/benchmarks/README.md @@ -1,10 +1,40 @@ -# Running the benchmarks +# Benchmarks One runner, four benchmarks, four stages: ADD, SEARCH, ANSWER, JUDGE. Per-benchmark rules live in `benchmarks/adapters/.py`. > Also available in Chinese: [README.zh.md](README.zh.md). +## Results + +Each benchmark's published number, from its config in `benchmarks/configs/`. + +| Benchmark | Questions | Accuracy | Decider | Answer model | +|---|---|---|---|---| +| [LoCoMo](locomo.md) | 1,540 | **94.61\*** | -- (`agentic` uses none) | `openai/gpt-4.1-mini` | +| LongMemEval | 500 | **94.00** | `qwen3.6-27B` | `google/gemini-3.6-flash` | +| EverMemBench | 2,400 | **66.67** | `qwen3.6-27B` | `google/gemini-3-flash-preview` | +| SubtleMemory | 1,522 | **71.75** | `qwen3.6-27B` | `openai/gpt-5.4` | + +\* Re-judged: the 99 questions whose gold answer the LoCoMo audit disputes are graded against +its corrected answers. + +> **Accuracy** is a micro accuracy for every benchmark in this table: +> `sum(correct) / sum(total)` over all graded questions. The per-category lines in +> `report.txt` are reported, never averaged into it, so a category with few questions +> moves the headline less than a large one does. +> +> **EverMemBench** -- most rows of its published comparison table are the macro mean of +> their category columns, a different statistic from the micro accuracy here. +> +> **SubtleMemory** — routes each question between two answer contracts on whether +> fact extraction found a conflict; the adapter does this automatically. + +### More results + +- [LoCoMo](locomo.md): accuracy and search time of every retrieval method across models, + batch or step boundary detection, and write latency per stage. + ## Quick start A smoke test on LoCoMo, from a fresh clone. Run every command from the repository @@ -32,11 +62,14 @@ so a failed first attempt costs nothing. - Python 3.12+ and [uv](https://docs.astral.sh/uv/) - `bash` and `curl` (macOS or Linux; on Windows use WSL2, see [docs/windows.md](../docs/windows.md)) -- An [OpenRouter](https://openrouter.ai) key (extraction, answer and judge models). - With it alone you can run `--methods keyword`. -- A [DeepInfra](https://deepinfra.com) key for EverOS's default embedding and rerank - models. LoCoMo searches with `agentic`, which needs both; the other three benchmarks - search with `llm_multiround`, which needs embedding only. +- An [OpenRouter](https://openrouter.ai) key for the LLMs: extraction, answer and judge, + and the search-time calls of `agentic` and `llm_multiround`. With it alone you can run + `--methods keyword`. +- A [DeepInfra](https://deepinfra.com) key, when the retrieval methods you run need + EverOS's default embedding (`Qwen/Qwen3-Embedding-4B`) or rerank + (`Qwen/Qwen3-Reranker-4B`) model: `vector`, `hybrid` and `llm_multiround` need + embedding, `agentic` needs both, `keyword` needs neither. See + [Which keys you need](#which-keys-you-need). --- @@ -94,7 +127,7 @@ works as shipped. |---|---|---| | `EVEROS_LLM__API_KEY` | OpenRouter key | the EverOS servers: extraction (ADD) and the retrieval decider | | `EVEROS_EMBEDDING__API_KEY` | DeepInfra key | the EverOS servers: embedding (Qwen3-Embedding-4B by default) -- every retrieval method except `keyword` | -| `EVEROS_RERANK__API_KEY` | DeepInfra key | the EverOS servers: rerank (Qwen3-Reranker-4B by default) -- `agentic`, LoCoMo's method; without it every agentic search fails | +| `EVEROS_RERANK__API_KEY` | DeepInfra key | the EverOS servers: rerank (Qwen3-Reranker-4B by default) -- `agentic` only; without it every `agentic` search fails | | `ANSWER_API_KEY` | OpenRouter key | ANSWER | | `JUDGE_API_KEY` | OpenRouter key | JUDGE | @@ -106,16 +139,19 @@ A benchmark therefore needs what its retrieval method needs -- `methods` in `configs/.toml` (`agentic` for LoCoMo, `llm_multiround` for the other three), or `--methods` for one run: -| Retrieval method | OpenRouter key | DeepInfra key: embedding | DeepInfra key: rerank | +| Retrieval method | OpenRouter key: LLMs | DeepInfra key: embedding, `Qwen/Qwen3-Embedding-4B` | DeepInfra key: rerank, `Qwen/Qwen3-Reranker-4B` | |---|---|---|---| -| `agentic` (LoCoMo) | yes | yes | yes | -| `llm_multiround` (the other three) | yes | yes | -- | -| `vector`, `hybrid` | yes | yes | -- | | `keyword` (BM25 only) | yes | -- | -- | +| `vector`, `hybrid` | yes | yes | -- | +| `llm_multiround` | yes | yes | -- | +| `agentic` | yes | yes | yes | + +Every method needs the LLMs for extraction, answers and judging; `agentic` and +`llm_multiround` also call one while they search. Without an embedding provider EverOS also skips reflection and skill extraction during ADD, so a `keyword` run measures a smaller pipeline, and its score is not comparable -to [6. Results](#6-results). The run checks exactly these requirements for the +to [Results](#results). The run checks exactly these requirements for the methods you chose, before anything starts. Models, `top_k`, retrieval settings and concurrency are set in @@ -135,7 +171,7 @@ refused for datasets whose sessions carry their own ids. **Optional -- a separate retrieval decider** (`llm_multiround` only). Each config comes pre-filled with the decider behind its published number (the Decider column in -[6. Results](#6-results); for LoCoMo, [its methods table](#by-retrieval-method)). +[Results](#results); for LoCoMo, [Batch or step](locomo.md#batch-or-step)). To use it, set `BENCH_DECIDER_BASE_URL` to an OpenAI-compatible endpoint that serves it and `BENCH_DECIDER_API_KEY` to its key; set `BENCH_DECIDER_MODEL` only to run another model. LoCoMo's decider is on OpenRouter: `BENCH_DECIDER_BASE_URL=https://openrouter.ai/api/v1` @@ -164,7 +200,7 @@ DATASET=locomo bash benchmarks/reproduce.sh --smoke A smoke run ingests the first 50 messages of conversation 0, answers up to 10 sampled questions (LongMemEval has one question per conversation, so one) and judges each once. It exercises every stage end to end; its score is not comparable to -[6. Results](#6-results), and `report.txt` says so on its first lines. Use it to check +[Results](#results), and `report.txt` says so on its first lines. Use it to check the setup and to watch what one conversation costs with your provider before a full run. The report counts answer and judge tokens only; extraction and embedding usage shows on your providers' dashboards. @@ -220,7 +256,7 @@ starts, so two runs never share a store. `locomo-step` is LoCoMo with step boundary detection and prompt-only replies on every EverOS call: `configs/locomo-step.toml` is `locomo.toml` with those two server settings -changed. See [Batch or step](#batch-or-step) for what each one costs and scores. +changed. See [Batch or step](locomo.md#batch-or-step) for what each one costs and scores. Without the wrapper, the same smoke test is: @@ -269,7 +305,7 @@ earlier search, answer and judge files as `*.superseded.jsonl`. | `No rerank provider is configured` | set `EVEROS_RERANK__API_KEY`, or choose a method other than `agentic` | | `decider ... did not answer` | the decider of an `llm_multiround` run refused the probe request; the message says why. See the decider option in [3. Configure](#3-configure) | | `llm_multiround round(s) fell back to a fixed core` | the decider failed on those rounds; the server log's `llm_multiround_decider_error` lines say why. Fix that, then search again under a new `RUN` | -| `decider no endpoint for ...` | a warning, not an error (`llm_multiround` only): the run continues on the extraction model and its score is not comparable to [6. Results](#6-results) | +| `decider no endpoint for ...` | a warning, not an error (`llm_multiround` only): the run continues on the extraction model and its score is not comparable to [Results](#results) | | `Refusing to start: these stores already hold memories` | delete the listed store for a clean run, or pass `--reuse-store` | | `No SubtleMemory personas under ...` | `bash benchmarks/download_data.sh subtlememory` | @@ -306,7 +342,7 @@ side by side, overall and per category: | Line | Grades | Use it for | |---|---|---| | `Accuracy` | every answer against the dataset's gold | comparing with other systems' published results, which use it | -| `Re-judged` | the same answers, with the questions a third-party audit disputes graded against the audit's corrected answers | the LoCoMo numbers in [6. Results](#6-results) (marked \*): a question with a wrong gold answer measures the dataset, not the system | +| `Re-judged` | the same answers, with the questions a third-party audit disputes graded against the audit's corrected answers | the LoCoMo numbers in [Results](#results) (marked \*): a question with a wrong gold answer measures the dataset, not the system | Re-judging changes only the gold: nothing is searched or answered again, and the disputed answers are graded by the same judge model, the same number of times, with @@ -351,81 +387,6 @@ rm -f benchmarks/.env ps -eo pid,command | grep "[e]veros server start" # stray servers, if any ``` -## 6. Results - -Each benchmark's published number. LoCoMo's comes from `benchmarks/configs/locomo-step.toml`, the -others from `benchmarks/configs/.toml`. - -| Benchmark | Questions | Accuracy | Decider | Answer model | -|---|---|---|---|---| -| LoCoMo | 1,540 | **94.61\*** | -- (`agentic` uses none) | `openai/gpt-4.1-mini` | -| LongMemEval | 500 | **94.00** | `qwen3.6-27B` | `google/gemini-3.6-flash` | -| EverMemBench | 2,400 | **66.67** | `qwen3.6-27B` | `google/gemini-3-flash-preview` | -| SubtleMemory | 1,522 | **71.75** | `qwen3.6-27B` | `openai/gpt-5.4` | - -> **Accuracy** is a micro accuracy for every benchmark in this table: -> `sum(correct) / sum(total)` over all graded questions. The per-category lines in -> `report.txt` are reported, never averaged into it, so a category with few questions -> moves the headline less than a large one does. -> -> **EverMemBench** -- most rows of its published comparison table are the macro mean of -> their category columns, a different statistic from the micro accuracy here. -> -> **SubtleMemory** — routes each question between two answer contracts on whether -> fact extraction found a conflict; the adapter does this automatically. - -### LoCoMo - -**EverOS scores 94.61%\* on LoCoMo.** - -#### By retrieval method - -| Retrieval method | Step boundary detection (`locomo-step`) | Batch boundary detection (`locomo`, default) | -|---|---|---| -| `agentic` | **94.61\*** | 94.35\* | -| `llm_multiround` | 94.29\* | 94.29\* | -| `hybrid` | 93.64\* | 93.38\* | -| `vector` | 92.73\* | 92.08\* | -| `keyword` | 91.04\* | 92.27\* | - -\* Re-judged: the 99 questions whose gold answer the LoCoMo audit disputes are graded against -its corrected answers. - -Best of three `agentic` runs per config; every other method searched that run's stores once. -Extraction and answers by `openai/gpt-4.1-mini`, judging by `openai/gpt-4o-mini` three times, -`llm_multiround`'s decider `deepseek/deepseek-v4-flash-0731` with thinking off; everalgo-core -0.7.0, everalgo-boundary 0.5.0. - -### Batch or step - -The two LoCoMo configs differ in two EverOS settings, and EverOS ships the first pair as its -defaults: - -| | `locomo` (default) | `locomo-step` | -|---|---|---| -| Boundary detection, `[boundary_detection] strategy` | `batch`: one call per add | `step`: one call per message | -| Reply format, `[llm] response_format_mode` | `json_schema`: the provider holds each reply to its schema | `prompt_only`: the prompt asks for the schema | -| `agentic`, best of three runs | 94.35\* | **94.61\*** | -| Boundary calls per run | 544 | about 5,250 | -| ADD with 10 servers | about 4 minutes | about 17–22 minutes | -| Episodes stored | about 320 | about 550 | -| Agent conversations (tool calls) | supported | chat messages only | - -- **`locomo` is faster and more stable.** Batch needs a tenth of step's boundary calls and - ingests about five times faster. Strict replies always match the schema they were asked for; - they need a provider that supports `json_schema`. -- **`locomo-step` scores higher.** Its best `agentic` run is 0.26 points above batch's, within - LoCoMo's run-to-run spread of about one point. A prompt-only reply that does not parse is - asked for again. - -Choose step for chat memory when slower ingest is acceptable; keep the defaults for agents and -for fast ingest. In an EverOS deployment, see -[`[boundary_detection]`](../docs/configuration.md#boundary_detection) and -[`[llm]`](../docs/configuration.md#llm). - -\* Re-judged, as above. - - --- ## run.py flags diff --git a/benchmarks/README.zh.md b/benchmarks/README.zh.md index d6910cc28..7fcacc503 100644 --- a/benchmarks/README.zh.md +++ b/benchmarks/README.zh.md @@ -1,10 +1,38 @@ -# 评测运行指南 +# 评测 一个运行器,四个评测,四个阶段:ADD、SEARCH、ANSWER、JUDGE。 各评测自己的规则在 `benchmarks/adapters/.py`。 > English version: [README.md](README.md). +## 结果 + +各评测的已发表数字,由 `benchmarks/configs/` 里各自的配置产出。 + +| 评测 | 题量 | 准确率 | decider | 答题模型 | +|---|---|---|---|---| +| [LoCoMo](locomo.zh.md) | 1,540 | **94.61\*** | --(`agentic` 不用) | `openai/gpt-4.1-mini` | +| LongMemEval | 500 | **94.00** | `qwen3.6-27B` | `google/gemini-3.6-flash` | +| EverMemBench | 2,400 | **66.67** | `qwen3.6-27B` | `google/gemini-3-flash-preview` | +| SubtleMemory | 1,522 | **71.75** | `qwen3.6-27B` | `openai/gpt-5.4` | + +\* 重判口径:LoCoMo 审计认为标准答案有误的 99 道题,按审计修正后的答案判分。 + +> **准确率**——表中每个评测都是微平均准确率:所有已判分题目的 `sum(correct) / sum(total)`。 +> `report.txt` 里的分类目各行只做报告,从不平均进总分,所以题量少的类目对总分的影响小于 +> 题量大的类目。 +> +> **EverMemBench**——它已发表的对比表里,大多数行是各类目列的宏平均,和这里的微平均是两种 +> 不同的统计量。 +> +> **SubtleMemory**——按事实抽取是否发现冲突,在两套答题契约之间逐题路由, +> 适配器自动完成。 + +### 更多结果 + +- [LoCoMo](locomo.zh.md):不同模型、不同检索方式的分数和检索耗时,批量和逐条边界检测的对比, + 以及各环节的写入耗时。 + ## 快速开始 从一个全新 clone 跑 LoCoMo 冒烟测试。所有命令都在仓库根目录执行。 @@ -30,10 +58,12 @@ key,一次列出所有缺项,所以第一次失败不会花一分钱。 - Python 3.12+ 和 [uv](https://docs.astral.sh/uv/) - `bash` 和 `curl`(macOS 或 Linux;Windows 请用 WSL2,见 [docs/windows.zh.md](../docs/windows.zh.md)) -- 一个 [OpenRouter](https://openrouter.ai) key(抽取、答题、判分模型)。只有它就能跑 - `--methods keyword`。 -- 一个 [DeepInfra](https://deepinfra.com) key,用于 EverOS 默认的 embedding 和 rerank 模型。 - LoCoMo 用 `agentic` 检索,两者都要;另外三个评测用 `llm_multiround` 检索,只要 embedding。 +- 一个 [OpenRouter](https://openrouter.ai) key,用于各个 LLM:抽取、答题、判分,以及 `agentic` 和 + `llm_multiround` 检索时的 LLM 调用。只有它就能跑 `--methods keyword`。 +- 一个 [DeepInfra](https://deepinfra.com) key,要不要取决于你测的检索方式是否用到 EverOS 默认的 + embedding 模型(`Qwen/Qwen3-Embedding-4B`)或 rerank 模型(`Qwen/Qwen3-Reranker-4B`): + `vector`、`hybrid`、`llm_multiround` 要 embedding,`agentic` 两个都要,`keyword` 都不要。见 + [需要哪些 key](#需要哪些-key)。 --- @@ -86,7 +116,7 @@ cp benchmarks/.env.example benchmarks/.env |---|---|---| | `EVEROS_LLM__API_KEY` | OpenRouter key | EverOS server:抽取(ADD)和检索 decider | | `EVEROS_EMBEDDING__API_KEY` | DeepInfra key | EverOS server:embedding(默认 Qwen3-Embedding-4B)——除 `keyword` 外的所有检索方法 | -| `EVEROS_RERANK__API_KEY` | DeepInfra key | EverOS server:rerank(默认 Qwen3-Reranker-4B)——LoCoMo 用的 `agentic`;没有它,每次 agentic 检索都会失败 | +| `EVEROS_RERANK__API_KEY` | DeepInfra key | EverOS server:rerank(默认 Qwen3-Reranker-4B)——只有 `agentic` 用;没有它,每次 `agentic` 检索都会失败 | | `ANSWER_API_KEY` | OpenRouter key | ANSWER | | `JUDGE_API_KEY` | OpenRouter key | JUDGE | @@ -97,15 +127,17 @@ EverOS 本身只强依赖 LLM;embedding 和 rerank 是可选能力,配上之 什么,取决于它的检索方法——`configs/.toml` 里的 `methods`(LoCoMo 是 `agentic`, 另外三个是 `llm_multiround`),或单次运行的 `--methods`: -| 检索方法 | OpenRouter key | DeepInfra key:embedding | DeepInfra key:rerank | +| 检索方法 | OpenRouter key:LLM | DeepInfra key:embedding,`Qwen/Qwen3-Embedding-4B` | DeepInfra key:rerank,`Qwen/Qwen3-Reranker-4B` | |---|---|---|---| -| `agentic`(LoCoMo) | 要 | 要 | 要 | -| `llm_multiround`(另外三个) | 要 | 要 | — | -| `vector`、`hybrid` | 要 | 要 | — | | `keyword`(仅 BM25) | 要 | — | — | +| `vector`、`hybrid` | 要 | 要 | — | +| `llm_multiround` | 要 | 要 | — | +| `agentic` | 要 | 要 | 要 | + +每种方法都要用 LLM 抽取、答题和判分;`agentic` 和 `llm_multiround` 检索时还会调用 LLM。 没有 embedding 时,EverOS 在 ADD 阶段也会跳过反思(reflection)和技能抽取,所以 `keyword` 运行 -测的是一条更短的流水线,分数不能和 [6. 结果](#6-结果) 对比。运行会在启动任何东西之前,按你选的 +测的是一条更短的流水线,分数不能和 [结果](#结果) 对比。运行会在启动任何东西之前,按你选的 方法检查这些要求。 模型、`top_k`、检索设置和并发在 `benchmarks/configs/.toml` 中设置,不在 `.env` 里; @@ -121,7 +153,7 @@ EverOS 从那里读取。LoCoMo 的配置还把每条消息都记在被提问的 数据集 session。session 自带 id 的数据集不接受 `"conversation"`。 **可选:单独的检索 decider**(只用于 `llm_multiround`)。各配置已预填已发表数字所用的 decider -(见 [6. 结果](#6-结果) 的 decider 列;LoCoMo 见 [各检索方式](#各检索方式))。 +(见 [结果](#结果) 的 decider 列;LoCoMo 见 [batch 还是 step](locomo.zh.md#batch-还是-step))。 要使用它,把 `BENCH_DECIDER_BASE_URL` 设为一个提供该模型的 OpenAI 兼容端点,`BENCH_DECIDER_API_KEY` 填它的 key;只有想换别的模型时才设 `BENCH_DECIDER_MODEL`。LoCoMo 的 decider 在 OpenRouter 上: `BENCH_DECIDER_BASE_URL=https://openrouter.ai/api/v1`,key 填你的 OpenRouter key;它的配置让 decider 关着思考运行。不设端点时由 @@ -145,7 +177,7 @@ DATASET=locomo bash benchmarks/reproduce.sh --smoke ``` 冒烟测试只灌入对话 0 的前 50 条消息,最多抽样回答 10 题(LongMemEval 每个对话只有一题,所以只答 -一题),每题判分一次。它端到端跑通每个阶段,但分数不能和 [6. 结果](#6-结果) 对比,`report.txt` +一题),每题判分一次。它端到端跑通每个阶段,但分数不能和 [结果](#结果) 对比,`report.txt` 开头几行也会注明这一点。用它确认配置无误,并在跑全量之前看清一个对话在你的服务商那里花多少钱。 报告只统计答题和判分的 token;抽取和 embedding 的用量请看各服务商的控制台。 @@ -192,7 +224,7 @@ DATASET=locomo bash benchmarks/reproduce.sh `locomo-step` 是用逐条边界检测、且 EverOS 每次调用都只在 prompt 里要求回复格式的 LoCoMo: `configs/locomo-step.toml` 就是 `locomo.toml` 改了这两项 server 设置。两者各自的分数和代价见 -[batch 还是 step](#batch-还是-step)。 +[batch 还是 step](locomo.zh.md#batch-还是-step)。 不用这个包装脚本时,同样的冒烟测试是: @@ -238,7 +270,7 @@ DATASET=locomo RUN=locomo_hybrid STAGES="search answer judge" \ | `No rerank provider is configured` | 设置 `EVEROS_RERANK__API_KEY`,或换一个不是 `agentic` 的方法 | | `decider ... did not answer` | `llm_multiround` 运行的 decider 没有回答探测请求,提示里写了原因;见 [3. 配置](#3-配置) 中的 decider 选项 | | `llm_multiround round(s) fell back to a fixed core` | decider 在这些轮里失败了,server 日志里的 `llm_multiround_decider_error` 写明了原因;处理好后换一个新的 `RUN` 重新检索 | -| `decider no endpoint for ...` | 是警告,不是错误(只在 `llm_multiround` 出现):运行会继续,改用抽取模型,分数不能和 [6. 结果](#6-结果) 对比 | +| `decider no endpoint for ...` | 是警告,不是错误(只在 `llm_multiround` 出现):运行会继续,改用抽取模型,分数不能和 [结果](#结果) 对比 | | `Refusing to start: these stores already hold memories` | 删除列出的库后重跑,或加 `--reuse-store` | | `No SubtleMemory personas under ...` | `bash benchmarks/download_data.sh subtlememory` | @@ -272,7 +304,7 @@ benchmarks/results/// | 行 | 怎么判 | 用途 | |---|---|---| | `Accuracy` | 每个回答都对照数据集的金标 | 和其他系统已发表的结果比较,它们用这个口径 | -| `Re-judged` | 同样的回答,其中第三方审计认为金标有问题的题改为对照审计给出的正确答案 | [6. 结果](#6-结果) 里的 LoCoMo 数字(标 \*):金标本身错了的题,测的是数据集而不是系统 | +| `Re-judged` | 同样的回答,其中第三方审计认为金标有问题的题改为对照审计给出的正确答案 | [结果](#结果) 里的 LoCoMo 数字(标 \*):金标本身错了的题,测的是数据集而不是系统 | 重判只换金标:不重新检索、不重新答题,有争议的回答用同一个判分模型、同样的判分次数和同样的 多数票再判一次。JUDGE 把结果写进 `rejudge_.jsonl`,已判过的会跳过;审计文件下载之前 @@ -311,74 +343,6 @@ rm -f benchmarks/.env ps -eo pid,command | grep "[e]veros server start" # 查残留的 server ``` -## 6. 结果 - -各评测的已发表数字。LoCoMo 由 `benchmarks/configs/locomo-step.toml` 产出,其余由 -`benchmarks/configs/.toml` 产出。 - -| 评测 | 题量 | 准确率 | decider | 答题模型 | -|---|---|---|---|---| -| LoCoMo | 1,540 | **94.61\*** | --(`agentic` 不用) | `openai/gpt-4.1-mini` | -| LongMemEval | 500 | **94.00** | `qwen3.6-27B` | `google/gemini-3.6-flash` | -| EverMemBench | 2,400 | **66.67** | `qwen3.6-27B` | `google/gemini-3-flash-preview` | -| SubtleMemory | 1,522 | **71.75** | `qwen3.6-27B` | `openai/gpt-5.4` | - -> **准确率**——表中每个评测都是微平均准确率:所有已判分题目的 `sum(correct) / sum(total)`。 -> `report.txt` 里的分类目各行只做报告,从不平均进总分,所以题量少的类目对总分的影响小于 -> 题量大的类目。 -> -> **EverMemBench**——它已发表的对比表里,大多数行是各类目列的宏平均,和这里的微平均是两种 -> 不同的统计量。 -> -> **SubtleMemory**——按事实抽取是否发现冲突,在两套答题契约之间逐题路由, -> 适配器自动完成。 - -### LoCoMo - -**EverOS 在 LoCoMo 上得分 94.61%\*。** - -#### 各检索方式 - -| 检索方式 | 逐条边界检测(`locomo-step`) | 批量边界检测(`locomo`,默认) | -|---|---|---| -| `agentic` | **94.61\*** | 94.35\* | -| `llm_multiround` | 94.29\* | 94.29\* | -| `hybrid` | 93.64\* | 93.38\* | -| `vector` | 92.73\* | 92.08\* | -| `keyword` | 91.04\* | 92.27\* | - -\* 重判口径:LoCoMo 审计认为标准答案有误的 99 道题,按审计修正后的答案判分。 - -每份配置的 `agentic` 跑 3 次取最高的一次,其余检索方式在那次运行建好的库上各跑 1 次。抽取和答题用 -`openai/gpt-4.1-mini`,判分用 `openai/gpt-4o-mini` 判 3 次,`llm_multiround` 的 decider 用 -`deepseek/deepseek-v4-flash-0731`(关思考);everalgo-core 0.7.0、everalgo-boundary 0.5.0。 - -### batch 还是 step - -两份 LoCoMo 配置只差两项 EverOS 设置,EverOS 的默认值是第一组: - -| | `locomo`(默认) | `locomo-step` | -|---|---|---| -| 边界检测,`[boundary_detection] strategy` | `batch`:每次写入调用一次 | `step`:每条消息调用一次 | -| 回复格式,`[llm] response_format_mode` | `json_schema`:由服务商保证每条回复符合 schema | `prompt_only`:只在 prompt 里要求 schema | -| `agentic`,3 次运行取最高 | 94.35\* | **94.61\*** | -| 每次运行的边界检测调用 | 544 次 | 约 5,250 次 | -| ADD 耗时(10 个 server) | 约 4 分钟 | 约 17–22 分钟 | -| 存下的 episode | 约 320 个 | 约 550 个 | -| agent 对话(含工具调用) | 支持 | 只处理对话消息 | - -- **`locomo` 更快、更稳。** batch 的边界检测调用只有 step 的十分之一,写入快约 5 倍。strict 回复 - 一定符合所要求的 schema;需要服务商支持 `json_schema`。 -- **`locomo-step` 分数更高。** 它 `agentic` 的最高分比 batch 高 0.26 个百分点,在 LoCoMo 单次运行 - 之间约 1 个百分点的波动以内。`prompt_only` 的回复解析不了时会重新请求。 - -做对话记忆、能接受较慢的写入时选 step;agent 场景和需要快速写入时保持默认。在 EverOS 部署里见 -[`[boundary_detection]`](../docs/configuration.md#boundary_detection) 和 -[`[llm]`](../docs/configuration.md#llm)。 - -\* 重判口径,同上。 - - --- ## run.py 参数 diff --git a/benchmarks/locomo.md b/benchmarks/locomo.md new file mode 100644 index 000000000..10cfde950 --- /dev/null +++ b/benchmarks/locomo.md @@ -0,0 +1,279 @@ +# LoCoMo results + +EverOS scores **94.61%** on LoCoMo, the best of three `agentic` runs with +`benchmarks/configs/locomo-step.toml`. Across the models below, `hybrid` calls no LLM and returns +in 0.27 s at the median while scoring up to 94.94; `agentic` scores up to +95.78, and with `deepseek-v4.1-flash` returns in 4.0 s at 95.52. +The sections after the table compare batch and step boundary detection and break down write and +search latency. To run LoCoMo yourself, start with [README.md](README.md). + +> Also available in Chinese: [locomo.zh.md](locomo.zh.md). + +All scores on this page are re-judged: the 99 questions whose gold answer the LoCoMo audit +disputes are graded against its corrected answers; see [Two scores per run](README.md#two-scores-per-run). + +## Results by model and retrieval method + +Accuracy for each retrieval method (rows) and model configuration (columns). `hybrid`, `vector` +and `keyword` call no LLM, so every model shares one search time; `agentic`'s search time follows +its model and stands in brackets. + +| Retrieval method | Search time, median | `gpt-4.1-mini` (published) | `deepseek-v4.1-flash` | `claude-haiku-5.5` | `gemini-2.5-flash-lite` | `qwen3-32b` | `gpt-5.4-mini` + `qwen3-235b` | `qwen3-4b` + `gpt-5.4-mini` + `qwen3-235b` | +|---|---|---|---|---|---|---|---|---| +| `agentic` | by model, in brackets | 94.61 (6.7 s) | 95.52 (4.0 s) | 95.32 (8.5 s) | 94.29 (4.9 s) | 93.38 (14.8 s) | **95.78** (14.7 s†) | 94.68 (12.5 s) | +| `hybrid` | 0.27 s | 93.64 | 94.61 | **94.94** | 93.25 | 92.99 | 94.22 | 93.64 | +| `vector` | 0.25 s | 92.73 | **94.22** | 93.64 | 92.60 | 92.73 | | | +| `keyword` | 0.01 s | 91.04 | **92.86** | 92.34 | 91.43 | 91.17 | | | + +† Measured separately, when `qwen/qwen3-235b-a22b-2507` took two to three times as long per call as in the `qwen3-4b` + `gpt-5.4-mini` + `qwen3-235b` measurements (34 s against 18 s per atomic-fact call); the time reflects that provider's speed then. + +What each column runs: + +| Column | Models | +|---|---| +| `gpt-4.1-mini` (published) | `openai/gpt-4.1-mini` for every stage | +| `deepseek-v4.1-flash` | `deepseek/deepseek-v4.1-flash-1017` for every stage | +| `claude-haiku-5.5` | `anthropic/claude-haiku-5.5` for every stage | +| `gemini-2.5-flash-lite` | `google/gemini-2.5-flash-lite` for every stage | +| `qwen3-32b` | `qwen/qwen3-32b` for every stage | +| `gpt-5.4-mini` + `qwen3-235b` | boundary detection `openai/gpt-5.4-mini`; episode and summary `openai/gpt-5.4-mini`; atomic facts and `agentic` search `qwen/qwen3-235b-a22b-2507` | +| `qwen3-4b` + `gpt-5.4-mini` + `qwen3-235b` | boundary detection `qwen3-4b-instruct-2507`, self-hosted; episode and summary `openai/gpt-5.4-mini`; atomic facts and `agentic` search `qwen/qwen3-235b-a22b-2507` | + +What each retrieval method does: + +| Retrieval method | What it does | Calls an LLM | +|---|---|---| +| `agentic` | Recalls memories, reranks them with a cross-encoder and has the LLM judge whether they answer the question; if not, the LLM writes follow-up queries for a second round. | yes | +| `hybrid` | Fuses keyword and vector rankings, plus a lane of atomic facts for episodes. | no | +| `vector` | Semantic match on embeddings only. | no | +| `keyword` | BM25 full-text match only. | no | + +- **Bold** marks the highest score in a row. Its gap to the others in the row is not + necessarily real: the differences that hold statistically are in the paragraph that ends + this section. +- **Accuracy.** `agentic` and `hybrid`: best of three full runs, except `openai/gpt-4.1-mini`'s + `hybrid`, which searched its best run's stores once. `vector` and `keyword`: one search of one + run's stores; the per-stage columns were not measured with them. Every column answers with + `openai/gpt-4.1-mini` and judges with `openai/gpt-4o-mini` three times; every run is in the + [appendix](#appendix-full-results). +- **Search time.** Median of single requests, one at a time: 10 questions from conversation 0, + three times each, on each configuration's own stores. The `hybrid`, `vector` and `keyword` + times pool every configuration's searches ([Search latency](#search-latency)). +- **Configurations.** `gpt-4.1-mini` is the published configuration, + `benchmarks/configs/locomo-step.toml`: step boundary detection and prompt-only replies. Every + other column is `benchmarks/configs/locomo.toml`, with batch boundary detection, and its models + set in `[llm]`, which every stage inherits, and in the + [`[llm.]`](../docs/configuration.md#llmtask) sections `boundary`, `episode`, `summary`, + `atomic_fact` and `search`. Embedding and rerank are `Qwen/Qwen3-Embedding-4B` and + `Qwen/Qwen3-Reranker-4B` throughout. `openai/gpt-4.1-mini` is the model memory systems + commonly report LoCoMo with; scores with another model do not compare with those. + +Most configurations sit within two points of each other, and three runs separate few of them. +Four differences hold in a statistical test (a paired bootstrap over runs and questions, +corrected for every pair compared): `deepseek-v4.1-flash` above `gemini-2.5-flash-lite` +(+2.0 points on the mean of three runs) and above `qwen3-32b` (+2.4), `claude-haiku-5.5` above +`qwen3-32b` (+2.2), and `gpt-5.4-mini` + `qwen3-235b` above `qwen3-32b` (+2.1). The two per-stage +columns, which differ only in the boundary detection model, do not differ measurably (0.5 points). + +## Batch or step + +The two LoCoMo configs differ in two EverOS settings, and EverOS ships the first pair as its +defaults: + +| | `locomo` (default) | `locomo-step` | +|---|---|---| +| Boundary detection, `[boundary_detection] strategy` | `batch`: one call per add | `step`: one call per message | +| Reply format, `[llm] response_format_mode` | `json_schema`: the provider holds each reply to its schema | `prompt_only`: the prompt asks for the schema | +| `agentic`, best of three runs | 94.35 | **94.61** | +| Boundary calls per run | 544 | about 5,250 | +| ADD with 10 servers | about 4 minutes | about 17–22 minutes | +| Episodes stored | about 320 | about 550 | +| Agent conversations (tool calls) | supported | chat messages only | + +- **`locomo` is faster and more stable.** Batch needs a tenth of step's boundary calls and + ingests about five times faster. Strict replies always match the schema they were asked for; + they need a provider that supports `json_schema`. +- **`locomo-step` scores higher.** Its best `agentic` run is 0.26 points above batch's, within + LoCoMo's run-to-run spread of about one point. A prompt-only reply that does not parse is + asked for again. + +Choose step for chat memory when slower ingest is acceptable; keep the defaults for agents and +for fast ingest. In an EverOS deployment, see +[`[boundary_detection]`](../docs/configuration.md#boundary_detection) and +[`[llm]`](../docs/configuration.md#llm). + +Every retrieval method on the two configs' stores: + +| Retrieval method | Step boundary detection (`locomo-step`) | Batch boundary detection (`locomo`, default) | +|---|---|---| +| `agentic` | **94.61** | 94.35 | +| `llm_multiround` | 94.29 | 94.29 | +| `hybrid` | **93.64** | 93.38 | +| `vector` | **92.73** | 92.08 | +| `keyword` | 91.04 | **92.27** | + +Bold marks the higher score of the two. Best of three `agentic` runs per config; every other +method searched that run's stores once. `llm_multiround` lets an LLM decider run several +retrieval rounds; its decider is `deepseek/deepseek-v4-flash-0731` with thinking off. +everalgo-core 0.7.0, everalgo-boundary 0.5.0. + +## Write latency + +A write runs four model stages. Boundary detection decides where a stretch of conversation ends; +episode extraction writes that stretch up as one episode, and the request returns once it is on +disk; the summary and the atomic facts (single-sentence facts) are then extracted from the +episode in the background. + +Each configuration wrote three sessions, the first of LoCoMo conversations 0, 2 and 7 (16–18 +messages each), each to a fresh store on a freshly started server: one `/memory/add` of the whole +session and one `/memory/flush`, timed at the client. Each cell is the median of the three. + +| Configuration | add | flush | add + flush | All extraction done | +|---|---|---|---|---| +| `deepseek-v4.1-flash` | 0.9 s | 3.1 s | 4.3 s | 10.3 s | +| `claude-haiku-5.5` | 2.3 s | 5.5 s | 7.8 s | 16.9 s | +| `gemini-2.5-flash-lite` | 1.1 s | 2.5 s | 3.6 s | 9.6 s | +| `qwen3-32b` | 1.5 s | 9.2 s | 10.9 s | 21.4 s | +| `gpt-5.4-mini` + `qwen3-235b` | 1.6 s | 4.1 s | 5.7 s | 46.0 s† | +| `qwen3-4b` + `gpt-5.4-mini` + `qwen3-235b` | 1.4 s | 4.7 s | 6.0 s | 27.0 s | + +† Measured separately, when `qwen/qwen3-235b-a22b-2507` took two to three times as long per call as in the `qwen3-4b` + `gpt-5.4-mini` + `qwen3-235b` measurements (34 s against 18 s per atomic-fact call); the time reflects that provider's speed then. + +- Every column is its own median, so add and flush do not sum to add + flush. +- **add** detects boundaries: with batch detection, one model call per add. In these sessions + the flush cut the episode, so **flush** is mostly the episode call. +- **All extraction done** runs from the add's start until the summary and the atomic facts are + written too. Their models change only this column. + +The published configuration detects boundaries per message, one model call each, so its add is +timed per message: + +| Configuration | add per message: one boundary call | flush | All extraction done | +|---|---|---|---| +| `gpt-4.1-mini` (published) | 1.3 s | 4.2 s | 38.9 s | + +An add of one message waits for one boundary call, plus the episode call (3.1 s) when that +message closes an episode. Its flush and all-extraction-done times are for a whole session; an +add of the whole session at once took 22 s, one boundary call per message. + +Each session's times and the model time per call are in the [appendix](#write-latency-per-session). +LLMs ran through OpenRouter, embedding and rerank through DeepInfra, and `qwen3-4b-instruct-2507` +on a self-hosted endpoint; other providers and networks give other times. + +## Search latency + +Each configuration searched its own LoCoMo stores: 10 questions sampled from conversation 0, +three times each, one request at a time, through the same providers as the writes. The results +are in the [table above](#results-by-model-and-retrieval-method). + +- `hybrid`, `vector` and `keyword` call no LLM, so their time does not depend on the models. + Pooled over every configuration, 210 searches each, their medians were 0.27 s, 0.25 s and + 0.01 s, almost all of it the query embedding for the first two. +- EverOS's own work in an `agentic` search took about 0.1 s; the rest is model calls. Each + search makes at least one LLM call, to judge whether the recalled memories suffice; a second + round adds an LLM call for follow-up queries and another rerank. The time of each kind of + model call, the 90th percentiles and the share of second rounds are in the + [appendix](#search-latency-in-detail). + +## Appendix: full results + +Every number behind the results table and the latency sections, with the results table's +columns. + +### Accuracy per run + +Each cell reads original / re-judged: original grades every answer against the dataset's gold +answer, re-judged grades the 99 disputed questions against the audit's corrected answers +([Two scores per run](README.md#two-scores-per-run)). Each score is the majority of three judge +runs over all 1,540 questions. Bold marks the run the tables above report. + +`agentic`, three full runs per configuration: + +| Configuration | Run 1 | Run 2 | Run 3 | Mean | +|---|---|---|---|---| +| `gpt-4.1-mini` (published) | 92.86 / 93.70 | 92.99 / 93.70 | 93.25 / **94.61** | 93.03 / 94.00 | +| `deepseek-v4.1-flash` | 94.61 / **95.52** | 94.68 / 95.26 | 93.70 / 95.00 | 94.33 / 95.26 | +| `claude-haiku-5.5` | 94.55 / 95.26 | 94.55 / **95.32** | 93.77 / 94.74 | 94.29 / 95.11 | +| `gemini-2.5-flash-lite` | 91.36 / 92.60 | 93.51 / **94.29** | 92.08 / 92.99 | 92.32 / 93.29 | +| `qwen3-32b` | 91.30 / 92.40 | 92.40 / **93.38** | 92.34 / 92.92 | 92.01 / 92.90 | +| `gpt-5.4-mini` + `qwen3-235b` | 93.31 / 94.42 | 94.74 / **95.78** | 94.09 / 94.74 | 94.05 / 94.98 | +| `qwen3-4b` + `gpt-5.4-mini` + `qwen3-235b` | 93.51 / 94.61 | 93.25 / 94.22 | 93.83 / **94.68** | 93.53 / 94.50 | + +`hybrid`, searching each run's stores: + +| Configuration | Run 1 | Run 2 | Run 3 | Mean | +|---|---|---|---|---| +| `deepseek-v4.1-flash` | 93.44 / **94.61** | 92.86 / 93.90 | 93.83 / 94.48 | 93.38 / 94.33 | +| `claude-haiku-5.5` | 93.57 / 94.61 | 93.90 / **94.94** | 93.70 / 94.68 | 93.72 / 94.74 | +| `gemini-2.5-flash-lite` | 91.82 / **93.25** | 92.08 / 93.05 | 91.82 / 92.86 | 91.90 / 93.05 | +| `qwen3-32b` | 91.69 / 92.47 | 91.75 / **92.99** | 91.75 / 92.66 | 91.73 / 92.71 | +| `gpt-5.4-mini` + `qwen3-235b` | 92.60 / 93.38 | 93.12 / **94.22** | 92.47 / 93.57 | 92.73 / 93.72 | +| `qwen3-4b` + `gpt-5.4-mini` + `qwen3-235b` | 92.53 / 93.57 | 92.66 / **93.64** | 92.47 / 93.38 | 92.55 / 93.53 | + +`vector` and `keyword`, one search of one run's stores: + +| Configuration | Stores of | `vector`, original / re-judged | `keyword`, original / re-judged | +|---|---|---|---| +| `gpt-4.1-mini` (published) | run 3 | 91.75 / 92.73 | 89.74 / 91.04 | +| `deepseek-v4.1-flash` | run 1 | 93.57 / 94.22 | 91.62 / 92.86 | +| `claude-haiku-5.5` | run 2 | 92.99 / 93.64 | 91.43 / 92.34 | +| `gemini-2.5-flash-lite` | run 2 | 91.69 / 92.60 | 90.32 / 91.43 | +| `qwen3-32b` | run 2 | 91.82 / 92.73 | 89.81 / 91.17 | +| `gpt-5.4-mini` + `qwen3-235b` | | | | +| `qwen3-4b` + `gpt-5.4-mini` + `qwen3-235b` | | | | + +### Write latency per session + +Each cell reads add / flush / all extraction done, in seconds, for the first session of that +conversation. `gpt-4.1-mini` added each whole session at once, one boundary call per message. + +| Configuration | Conversation 0 | Conversation 2 | Conversation 7 | +|---|---|---|---| +| `gpt-4.1-mini` (published) | 21.8 / 5.2 / 45.0 | 19.2 / 3.1 / 34.4 | 22.7 / 4.2 / 38.9 | +| `deepseek-v4.1-flash` | 0.9 / 3.4 / 10.3 | 0.9 / 1.9 / 8.8 | 7.0 / 3.1 / 16.1 | +| `claude-haiku-5.5` | 2.4 / 5.7 / 17.1 | 2.3 / 5.5 / 16.9 | 1.8 / 5.5 / 16.4 | +| `gemini-2.5-flash-lite` | 1.1 / 3.1 / 10.2 | 1.0 / 2.1 / 9.1 | 1.1 / 2.5 / 9.6 | +| `qwen3-32b` | 1.2 / 5.1 / 21.4 | 2.4 / 9.2 / 26.6 | 1.5 / 9.4 / 19.9 | +| `gpt-5.4-mini` + `qwen3-235b` | 1.6 / 4.1 / 50.8 | 1.4 / 4.0 / 35.5 | 2.5 / 4.4 / 46.0 | +| `qwen3-4b` + `gpt-5.4-mini` + `qwen3-235b` | 1.4 / 4.7 / 21.1 | 1.1 / 4.8 / 27.0 | 1.4 / 4.6 / 36.1 | + +Model time per call, median over every call in the three sessions. For batch detection the +boundary column leaves out the add's call: it is the first model call after the server starts, +and slower. Step detection makes one boundary call per message. + +| Configuration | Boundary detection | Episode | Summary | Atomic facts | +|---|---|---|---|---| +| `gpt-4.1-mini` (published) | 1.3 s | 3.1 s | 1.4 s | 3.8 s | +| `deepseek-v4.1-flash` | 0.6 s | 1.4 s | 0.8 s | 1.9 s | +| `claude-haiku-5.5` | 1.2 s | 4.3 s | 2.0 s | 3.7 s | +| `gemini-2.5-flash-lite` | 0.7 s | 1.2 s | 1.1 s | 1.3 s | +| `qwen3-32b` | 0.8 s | 7.9 s | 3.2 s | 9.4 s | +| `gpt-5.4-mini` + `qwen3-235b` | 1.2 s | 2.9 s | 1.6 s | 34.1 s† | +| `qwen3-4b` + `gpt-5.4-mini` + `qwen3-235b` | 0.8 s | 3.8 s | 1.3 s | 17.6 s | + +† Measured while `qwen/qwen3-235b-a22b-2507` answered slowly; see the note under the first table. + +### Search latency in detail + +`agentic`, 30 searches per configuration. LLM, rerank, embedding and EverOS (the time outside +model calls) are separate medians and do not sum to the total. + +| Configuration | Median | Mean | 90th percentile | LLM | Rerank | Embedding | EverOS | Second round | +|---|---|---|---|---|---|---|---|---| +| `gpt-4.1-mini` (published) | 6.7 s | 6.4 s | 9.1 s | 3.8 s | 1.9 s | 0.8 s | 0.1 s | 12 of 30 | +| `deepseek-v4.1-flash` | 4.0 s | 5.1 s | 8.7 s | 1.2 s | 1.6 s | 0.8 s | 0.1 s | 12 of 30 | +| `claude-haiku-5.5` | 8.5 s | 8.2 s | 11.2 s | 4.7 s | 2.3 s | 1.2 s | 0.1 s | 20 of 30 | +| `gemini-2.5-flash-lite` | 4.9 s | 4.7 s | 6.8 s | 1.8 s | 1.9 s | 0.5 s | 0.1 s | 15 of 30 | +| `qwen3-32b` | 14.8 s | 12.7 s | 17.1 s | 10.4 s | 2.5 s | 1.0 s | 0.1 s | 21 of 30 | +| `gpt-5.4-mini` + `qwen3-235b`† | 14.7 s | 15.3 s | 26.5 s | 11.6 s | 1.7 s | 1.0 s | 0.1 s | 13 of 30 | +| `qwen3-4b` + `gpt-5.4-mini` + `qwen3-235b` | 12.5 s | 12.4 s | 19.1 s | 8.2 s | 2.3 s | 1.0 s | 0.1 s | 18 of 30 | + +† Measured while `qwen/qwen3-235b-a22b-2507` answered slowly; see the note under the first table. + +`hybrid`, `vector` and `keyword` call no LLM, so every configuration's searches are pooled: + +| Retrieval method | Median | 90th percentile | Searches | +|---|---|---|---| +| `hybrid` | 0.27 s | 0.65 s | 210 | +| `vector` | 0.25 s | 1.11 s | 210 | +| `keyword` | 0.01 s | 0.01 s | 210 | diff --git a/benchmarks/locomo.zh.md b/benchmarks/locomo.zh.md new file mode 100644 index 000000000..6bf0bff41 --- /dev/null +++ b/benchmarks/locomo.zh.md @@ -0,0 +1,250 @@ +# LoCoMo 结果 + +EverOS 在 LoCoMo 上得分 **94.61%**,是用 `benchmarks/configs/locomo-step.toml` 跑 3 次 `agentic` 里最高的 +一次。在下面这些模型上,`hybrid` 不调用 LLM,检索中位数 0.27 秒,分数最高 94.94;`agentic` +分数最高 95.78,用 `deepseek-v4.1-flash` 时 4.0 秒、95.52 分。总表之后的几节对比批量和 +逐条边界检测,并拆开写入和检索耗时。想自己跑 LoCoMo,从 [README.zh.md](README.zh.md) 开始。 + +> English version: [locomo.md](locomo.md). + +本文所有分数都按重判口径:LoCoMo 审计认为标准答案有误的 99 道题,按审计修正后的答案判分;见 +[每次运行给出两个分数](README.zh.md#每次运行给出两个分数)。 + +## 各模型和检索方式的分数与耗时 + +每行一种检索方式,每列一份模型配置,格子里是 LoCoMo 分数。`hybrid`、`vector`、`keyword` 不调用 LLM, +各模型共用一个检索耗时;`agentic` 的检索耗时随模型变化,写在分数后的括号里。 + +| 检索方式 | 检索耗时中位数 | `gpt-4.1-mini`(已发表) | `deepseek-v4.1-flash` | `claude-haiku-5.5` | `gemini-2.5-flash-lite` | `qwen3-32b` | `gpt-5.4-mini` + `qwen3-235b` | `qwen3-4b` + `gpt-5.4-mini` + `qwen3-235b` | +|---|---|---|---|---|---|---|---|---| +| `agentic` | 随模型,见括号 | 94.61(6.7 秒) | 95.52(4.0 秒) | 95.32(8.5 秒) | 94.29(4.9 秒) | 93.38(14.8 秒) | **95.78**(14.7 秒†) | 94.68(12.5 秒) | +| `hybrid` | 0.27 秒 | 93.64 | 94.61 | **94.94** | 93.25 | 92.99 | 94.22 | 93.64 | +| `vector` | 0.25 秒 | 92.73 | **94.22** | 93.64 | 92.60 | 92.73 | | | +| `keyword` | 0.01 秒 | 91.04 | **92.86** | 92.34 | 91.43 | 91.17 | | | + +† 单独测的,当时 `qwen/qwen3-235b-a22b-2507` 每次调用的耗时是测 `qwen3-4b` + `gpt-5.4-mini` + `qwen3-235b` 那份时的 2–3 倍(原子事实每次 34 秒对 18 秒),这个耗时反映的是服务商当时的速度。 + +每一列用的模型: + +| 列 | 模型 | +|---|---| +| `gpt-4.1-mini`(已发表) | 所有环节都用 `openai/gpt-4.1-mini` | +| `deepseek-v4.1-flash` | 所有环节都用 `deepseek/deepseek-v4.1-flash-1017` | +| `claude-haiku-5.5` | 所有环节都用 `anthropic/claude-haiku-5.5` | +| `gemini-2.5-flash-lite` | 所有环节都用 `google/gemini-2.5-flash-lite` | +| `qwen3-32b` | 所有环节都用 `qwen/qwen3-32b` | +| `gpt-5.4-mini` + `qwen3-235b` | 边界检测 `openai/gpt-5.4-mini`;episode 和 summary `openai/gpt-5.4-mini`;原子事实和 `agentic` 检索 `qwen/qwen3-235b-a22b-2507` | +| `qwen3-4b` + `gpt-5.4-mini` + `qwen3-235b` | 边界检测 `qwen3-4b-instruct-2507`(自部署);episode 和 summary `openai/gpt-5.4-mini`;原子事实和 `agentic` 检索 `qwen/qwen3-235b-a22b-2507` | + +每种检索方式做什么: + +| 检索方式 | 做什么 | 调用 LLM | +|---|---|---| +| `agentic` | 召回记忆、用交叉编码器重排,再让 LLM 判断够不够回答问题;不够时由 LLM 写补充查询再检索一轮。 | 是 | +| `hybrid` | 把关键词和向量两路排名合并,episode 还多一路原子事实。 | 否 | +| `vector` | 只用 embedding 做语义匹配。 | 否 | +| `keyword` | 只用 BM25 做全文匹配。 | 否 | + +- **加粗**:这一行的最高分。它和同一行其他分数的差距不一定显著,统计上成立的差别见本节最后一段。 +- **分数**:`agentic` 和 `hybrid` 是完整跑 3 次取最高,其中 `gpt-4.1-mini` 的 `hybrid` 只在最高那次运行的库上 + 检索 1 次;`vector` 和 `keyword` 是在某一次运行的库上检索 1 次,两份分环节配置没测这两种方式。每一列都用 + `openai/gpt-4.1-mini` 答题、`openai/gpt-4o-mini` 判 3 次;每次运行的分数见[附录](#附录完整结果)。 +- **检索耗时**:单次请求的中位数,一次一个请求,在每份配置自己的库上对第 0 个对话的 10 道题各检索 3 次; + `hybrid`、`vector`、`keyword` 把所有配置的检索合在一起统计(见[检索耗时](#检索耗时))。 +- **配置**:`gpt-4.1-mini` 是已发表的配置 `benchmarks/configs/locomo-step.toml`:逐条边界检测、只在 prompt + 里要求回复格式。其余各列都是 `benchmarks/configs/locomo.toml`(批量边界检测),模型写在 `[llm]`(所有环节 + 都继承)和 [`[llm.]`](../docs/configuration.md#llmtask) 的 `boundary`、`episode`、`summary`、 + `atomic_fact`、`search` 几节里。embedding 和重排始终用 `Qwen/Qwen3-Embedding-4B` 和 + `Qwen/Qwen3-Reranker-4B`。`openai/gpt-4.1-mini` 是记忆系统发表 LoCoMo 分数时常用的模型,换用其他模型的分数 + 和这类已发表分数不可直接比较。 + +这些配置大多相差不到 2 个百分点,3 次运行能分出高下的很少。经过统计检验(对运行和题目两层抽样的配对 +bootstrap,并对所有两两比较做校正),有 4 个差别成立:`deepseek-v4.1-flash` 高于 `gemini-2.5-flash-lite` +(3 次平均高 2.0 个百分点)和 `qwen3-32b`(高 2.4),`claude-haiku-5.5` 高于 `qwen3-32b`(高 2.2), +`gpt-5.4-mini` + `qwen3-235b` 高于 `qwen3-32b`(高 2.1)。两份分环节配置只有边界检测模型不同,差 0.5 个 +百分点,这个差别不成立。 + +## batch 还是 step + +两份 LoCoMo 配置只差两项 EverOS 设置,EverOS 的默认值是第一组: + +| | `locomo`(默认) | `locomo-step` | +|---|---|---| +| 边界检测,`[boundary_detection] strategy` | `batch`:每次写入调用一次 | `step`:每条消息调用一次 | +| 回复格式,`[llm] response_format_mode` | `json_schema`:由服务商保证每条回复符合 schema | `prompt_only`:只在 prompt 里要求 schema | +| `agentic`,3 次运行取最高 | 94.35 | **94.61** | +| 每次运行的边界检测调用 | 544 次 | 约 5,250 次 | +| ADD 耗时(10 个 server) | 约 4 分钟 | 约 17–22 分钟 | +| 存下的 episode | 约 320 个 | 约 550 个 | +| agent 对话(含工具调用) | 支持 | 只处理对话消息 | + +- **`locomo` 更快、更稳。** batch 的边界检测调用只有 step 的十分之一,写入快约 5 倍。strict 回复 + 一定符合所要求的 schema;需要服务商支持 `json_schema`。 +- **`locomo-step` 分数更高。** 它 `agentic` 的最高分比 batch 高 0.26 个百分点,在 LoCoMo 单次运行 + 之间约 1 个百分点的波动以内。`prompt_only` 的回复解析不了时会重新请求。 + +做对话记忆、能接受较慢的写入时选 step;agent 场景和需要快速写入时保持默认。在 EverOS 部署里见 +[`[boundary_detection]`](../docs/configuration.md#boundary_detection) 和 +[`[llm]`](../docs/configuration.md#llm)。 + +各检索方式在两份配置建好的库上的分数: + +| 检索方式 | 逐条边界检测(`locomo-step`) | 批量边界检测(`locomo`,默认) | +|---|---|---| +| `agentic` | **94.61** | 94.35 | +| `llm_multiround` | 94.29 | 94.29 | +| `hybrid` | **93.64** | 93.38 | +| `vector` | **92.73** | 92.08 | +| `keyword` | 91.04 | **92.27** | + +加粗的是两份配置里较高的分数。每份配置的 `agentic` 跑 3 次取最高的一次,其余检索方式在那次运行建好的库上 +各跑 1 次。`llm_multiround` 由一个 LLM decider 主导多轮检索,decider 用 `deepseek/deepseek-v4-flash-0731` +(关思考);everalgo-core 0.7.0、everalgo-boundary 0.5.0。 + +## 写入耗时 + +一次写入要经过 4 个模型环节:边界检测判断一段对话在哪里结束;episode 抽取把这段对话写成一条 episode, +写进磁盘后请求才返回;summary 和原子事实(一句话一条的事实)随后在后台从 episode 里抽取。 + +每份配置写 3 段会话:LoCoMo 第 0、2、7 个对话各自的第一段会话(每段 16–18 条消息),每段都写进新库、用新 +启动的 server;整段会话做一次 `/memory/add`,再做一次 `/memory/flush`,在客户端计时。每格是 3 段的中位数。 + +| 配置 | add | flush | add + flush | 全部抽取完成 | +|---|---|---|---|---| +| `deepseek-v4.1-flash` | 0.9 秒 | 3.1 秒 | 4.3 秒 | 10.3 秒 | +| `claude-haiku-5.5` | 2.3 秒 | 5.5 秒 | 7.8 秒 | 16.9 秒 | +| `gemini-2.5-flash-lite` | 1.1 秒 | 2.5 秒 | 3.6 秒 | 9.6 秒 | +| `qwen3-32b` | 1.5 秒 | 9.2 秒 | 10.9 秒 | 21.4 秒 | +| `gpt-5.4-mini` + `qwen3-235b` | 1.6 秒 | 4.1 秒 | 5.7 秒 | 46.0 秒† | +| `qwen3-4b` + `gpt-5.4-mini` + `qwen3-235b` | 1.4 秒 | 4.7 秒 | 6.0 秒 | 27.0 秒 | + +† 单独测的,当时 `qwen/qwen3-235b-a22b-2507` 每次调用的耗时是测 `qwen3-4b` + `gpt-5.4-mini` + `qwen3-235b` 那份时的 2–3 倍(原子事实每次 34 秒对 18 秒),这个耗时反映的是服务商当时的速度。 + +- 每列各取各的中位数,所以 add 和 flush 加起来不等于 add + flush。 +- **add** 做边界检测,批量检测每次 add 调用一次模型。这几段会话里 episode 是在 flush 时切出来的,所以 + **flush** 主要是抽取 episode 的那次调用。 +- **全部抽取完成**:从 add 开始,到 summary 和原子事实也写完为止。这两个环节的模型只影响这一列。 + +已发表的配置逐条检测边界,每条消息调用一次模型,所以它的 add 按每条消息计时: + +| 配置 | 每条消息的 add:一次边界检测调用 | flush | 全部抽取完成 | +|---|---|---|---| +| `gpt-4.1-mini`(已发表) | 1.3 秒 | 4.2 秒 | 38.9 秒 | + +每条消息的 add 等待一次边界检测调用;这条消息结束一个 episode 时,再加上抽取 episode 的那次调用 +(3.1 秒)。flush 和全部抽取完成是整段会话的耗时;一次 add 写入整段会话约需 22 秒,每条消息各调用 +一次边界检测。 + +每段会话的耗时和每次模型调用的耗时见[附录](#每段会话的写入耗时)。LLM 走 OpenRouter,embedding 和重排走 +DeepInfra,`qwen3-4b-instruct-2507` 用自部署的端点;换服务商或网络会改变这些数字。 + +## 检索耗时 + +每份配置在自己的 LoCoMo 库上检索:从第 0 个对话里抽 10 道题,每题 3 次,一次一个请求,服务商和写入相同; +结果见[上面的总表](#各模型和检索方式的分数与耗时)。 + +- `hybrid`、`vector`、`keyword` 不调用 LLM,耗时和模型无关:把所有配置的检索合在一起,每种方式各 210 次, + 中位数分别为 0.27 秒、0.25 秒和 0.01 秒,`hybrid` 和 `vector` 的耗时几乎都花在查询的 embedding 上。 +- 一次 `agentic` 检索里 EverOS 自身只花约 0.1 秒,其余都是模型调用。每次检索至少调用一次 LLM,判断召回的 + 记忆是否足够;进入第二轮时,再调用一次 LLM 生成补充查询,并再做一次重排。各类模型调用的耗时、90 分位 + 和进入第二轮的比例见[附录](#检索耗时明细)。 + +## 附录:完整结果 + +总表和写入、检索耗时两节背后的全部数字,各表的配置名和总表的列名一致。 + +### 每次运行的分数 + +每格是「原始 / 重判」:原始分按数据集自带的标准答案判分,重判分把有争议的 99 道题改按审计修正后的 +答案判分([每次运行给出两个分数](README.zh.md#每次运行给出两个分数))。每个分数都是全部 1,540 道题、 +判分 3 次取多数的结果。加粗的是上面各表引用的那次运行。 + +`agentic`,每份配置完整跑 3 次: + +| 配置 | 第 1 次 | 第 2 次 | 第 3 次 | 平均 | +|---|---|---|---|---| +| `gpt-4.1-mini`(已发表) | 92.86 / 93.70 | 92.99 / 93.70 | 93.25 / **94.61** | 93.03 / 94.00 | +| `deepseek-v4.1-flash` | 94.61 / **95.52** | 94.68 / 95.26 | 93.70 / 95.00 | 94.33 / 95.26 | +| `claude-haiku-5.5` | 94.55 / 95.26 | 94.55 / **95.32** | 93.77 / 94.74 | 94.29 / 95.11 | +| `gemini-2.5-flash-lite` | 91.36 / 92.60 | 93.51 / **94.29** | 92.08 / 92.99 | 92.32 / 93.29 | +| `qwen3-32b` | 91.30 / 92.40 | 92.40 / **93.38** | 92.34 / 92.92 | 92.01 / 92.90 | +| `gpt-5.4-mini` + `qwen3-235b` | 93.31 / 94.42 | 94.74 / **95.78** | 94.09 / 94.74 | 94.05 / 94.98 | +| `qwen3-4b` + `gpt-5.4-mini` + `qwen3-235b` | 93.51 / 94.61 | 93.25 / 94.22 | 93.83 / **94.68** | 93.53 / 94.50 | + +`hybrid`,在每次运行建好的库上检索: + +| 配置 | 第 1 次 | 第 2 次 | 第 3 次 | 平均 | +|---|---|---|---|---| +| `deepseek-v4.1-flash` | 93.44 / **94.61** | 92.86 / 93.90 | 93.83 / 94.48 | 93.38 / 94.33 | +| `claude-haiku-5.5` | 93.57 / 94.61 | 93.90 / **94.94** | 93.70 / 94.68 | 93.72 / 94.74 | +| `gemini-2.5-flash-lite` | 91.82 / **93.25** | 92.08 / 93.05 | 91.82 / 92.86 | 91.90 / 93.05 | +| `qwen3-32b` | 91.69 / 92.47 | 91.75 / **92.99** | 91.75 / 92.66 | 91.73 / 92.71 | +| `gpt-5.4-mini` + `qwen3-235b` | 92.60 / 93.38 | 93.12 / **94.22** | 92.47 / 93.57 | 92.73 / 93.72 | +| `qwen3-4b` + `gpt-5.4-mini` + `qwen3-235b` | 92.53 / 93.57 | 92.66 / **93.64** | 92.47 / 93.38 | 92.55 / 93.53 | + +`vector` 和 `keyword`,各在一次运行建好的库上检索 1 次: + +| 配置 | 库来自 | `vector`(原始 / 重判) | `keyword`(原始 / 重判) | +|---|---|---|---| +| `gpt-4.1-mini`(已发表) | 第 3 次运行 | 91.75 / 92.73 | 89.74 / 91.04 | +| `deepseek-v4.1-flash` | 第 1 次运行 | 93.57 / 94.22 | 91.62 / 92.86 | +| `claude-haiku-5.5` | 第 2 次运行 | 92.99 / 93.64 | 91.43 / 92.34 | +| `gemini-2.5-flash-lite` | 第 2 次运行 | 91.69 / 92.60 | 90.32 / 91.43 | +| `qwen3-32b` | 第 2 次运行 | 91.82 / 92.73 | 89.81 / 91.17 | +| `gpt-5.4-mini` + `qwen3-235b` | | | | +| `qwen3-4b` + `gpt-5.4-mini` + `qwen3-235b` | | | | + +### 每段会话的写入耗时 + +每格是这个对话第一段会话的「add / flush / 全部抽取完成」,单位秒。`gpt-4.1-mini` 也是一次 add 写入整段会话, +每条消息各调用一次边界检测。 + +| 配置 | 第 0 个对话 | 第 2 个对话 | 第 7 个对话 | +|---|---|---|---| +| `gpt-4.1-mini`(已发表) | 21.8 / 5.2 / 45.0 | 19.2 / 3.1 / 34.4 | 22.7 / 4.2 / 38.9 | +| `deepseek-v4.1-flash` | 0.9 / 3.4 / 10.3 | 0.9 / 1.9 / 8.8 | 7.0 / 3.1 / 16.1 | +| `claude-haiku-5.5` | 2.4 / 5.7 / 17.1 | 2.3 / 5.5 / 16.9 | 1.8 / 5.5 / 16.4 | +| `gemini-2.5-flash-lite` | 1.1 / 3.1 / 10.2 | 1.0 / 2.1 / 9.1 | 1.1 / 2.5 / 9.6 | +| `qwen3-32b` | 1.2 / 5.1 / 21.4 | 2.4 / 9.2 / 26.6 | 1.5 / 9.4 / 19.9 | +| `gpt-5.4-mini` + `qwen3-235b` | 1.6 / 4.1 / 50.8 | 1.4 / 4.0 / 35.5 | 2.5 / 4.4 / 46.0 | +| `qwen3-4b` + `gpt-5.4-mini` + `qwen3-235b` | 1.4 / 4.7 / 21.1 | 1.1 / 4.8 / 27.0 | 1.4 / 4.6 / 36.1 | + +每次模型调用的耗时,取 3 段会话里所有调用的中位数。批量边界检测这一列不含 add 时的那次调用: +它是 server 启动后的第一次模型调用,比较慢。逐条边界检测每条消息调用一次。 + +| 配置 | 边界检测 | episode | summary | 原子事实 | +|---|---|---|---|---| +| `gpt-4.1-mini`(已发表) | 1.3 秒 | 3.1 秒 | 1.4 秒 | 3.8 秒 | +| `deepseek-v4.1-flash` | 0.6 秒 | 1.4 秒 | 0.8 秒 | 1.9 秒 | +| `claude-haiku-5.5` | 1.2 秒 | 4.3 秒 | 2.0 秒 | 3.7 秒 | +| `gemini-2.5-flash-lite` | 0.7 秒 | 1.2 秒 | 1.1 秒 | 1.3 秒 | +| `qwen3-32b` | 0.8 秒 | 7.9 秒 | 3.2 秒 | 9.4 秒 | +| `gpt-5.4-mini` + `qwen3-235b` | 1.2 秒 | 2.9 秒 | 1.6 秒 | 34.1 秒† | +| `qwen3-4b` + `gpt-5.4-mini` + `qwen3-235b` | 0.8 秒 | 3.8 秒 | 1.3 秒 | 17.6 秒 | + +† 测量时 `qwen/qwen3-235b-a22b-2507` 偏慢,见总表下的说明。 + +### 检索耗时明细 + +`agentic`,每份配置 30 次检索。LLM、重排、embedding 和 EverOS 自身(模型调用之外的时间)各取各的 +中位数,加起来不等于总耗时。 + +| 配置 | 中位数 | 平均 | 90 分位 | LLM | 重排 | embedding | EverOS 自身 | 进入第二轮 | +|---|---|---|---|---|---|---|---|---| +| `gpt-4.1-mini`(已发表) | 6.7 秒 | 6.4 秒 | 9.1 秒 | 3.8 秒 | 1.9 秒 | 0.8 秒 | 0.1 秒 | 30 次中 12 次 | +| `deepseek-v4.1-flash` | 4.0 秒 | 5.1 秒 | 8.7 秒 | 1.2 秒 | 1.6 秒 | 0.8 秒 | 0.1 秒 | 30 次中 12 次 | +| `claude-haiku-5.5` | 8.5 秒 | 8.2 秒 | 11.2 秒 | 4.7 秒 | 2.3 秒 | 1.2 秒 | 0.1 秒 | 30 次中 20 次 | +| `gemini-2.5-flash-lite` | 4.9 秒 | 4.7 秒 | 6.8 秒 | 1.8 秒 | 1.9 秒 | 0.5 秒 | 0.1 秒 | 30 次中 15 次 | +| `qwen3-32b` | 14.8 秒 | 12.7 秒 | 17.1 秒 | 10.4 秒 | 2.5 秒 | 1.0 秒 | 0.1 秒 | 30 次中 21 次 | +| `gpt-5.4-mini` + `qwen3-235b`† | 14.7 秒 | 15.3 秒 | 26.5 秒 | 11.6 秒 | 1.7 秒 | 1.0 秒 | 0.1 秒 | 30 次中 13 次 | +| `qwen3-4b` + `gpt-5.4-mini` + `qwen3-235b` | 12.5 秒 | 12.4 秒 | 19.1 秒 | 8.2 秒 | 2.3 秒 | 1.0 秒 | 0.1 秒 | 30 次中 18 次 | + +† 测量时 `qwen/qwen3-235b-a22b-2507` 偏慢,见总表下的说明。 + +`hybrid`、`vector`、`keyword` 不调用 LLM,所有配置的检索合在一起统计: + +| 检索方式 | 中位数 | 90 分位 | 检索次数 | +|---|---|---|---| +| `hybrid` | 0.27 秒 | 0.65 秒 | 210 | +| `vector` | 0.25 秒 | 1.11 秒 | 210 | +| `keyword` | 0.01 秒 | 0.01 秒 | 210 | diff --git a/docs/api.md b/docs/api.md index a2f7d65a9..c7bc8f2a6 100644 --- a/docs/api.md +++ b/docs/api.md @@ -606,6 +606,19 @@ correlation. LLM ran extraction and the writers persisted at least one memory cell. The buffer is empty after the call returns. +**Resending a batch.** A client that retries `/add` after a timeout may +resend messages the first call already processed. A message's identity is +its session, its `timestamp` and what was said by whom (`sender_id`, `role`, +`content`, `tool_call_id`, `tool_calls`); `sender_name` and its place in the +request are not part of it (a message repeated verbatim within one request +counts as many times as it appears). +A resent message that is still buffered, or already part of a memory cell +of the session, is dropped, so a retry (whole, split or regrouped) never +writes it twice and answers `200` (`"accumulated"` when it cut nothing +new). Two different messages with one `timestamp` are both kept. After the +session's memories are deleted (`/memory/delete` with its `session_id`), a +resend is memorized again. + `202 Accepted` — only with `async_mode`, or when the session already has queued batches (see [Asynchronous mode](#asynchronous-mode)) — returns a SuccessEnvelope wrapping: diff --git a/docs/architecture.md b/docs/architecture.md index 9b0baa16d..7406f5c0e 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -421,11 +421,13 @@ budget and failure-classification checks described above. Daemon that watches markdown changes and syncs to the configured derived index backend: -- inotify / FSEvents file watcher (cross-platform via `watchdog`) -- 500ms debounce +- inotify / FSEvents file watcher (cross-platform via `watchdog`); events + enqueue immediately, with no debounce window - Entry-level diff (added / changed / removed) - Per-entry index upsert / delete (text + vector columns update together) -- LSN-based crash recovery via the SQLite `md_change_state` queue +- Crash recovery: startup resets orphaned `processing` rows with + `recover_orphan_processing`, then the periodic scanner reconciles the + tree against the ledger - Handlers for all seven business kinds: episode, atomic_fact, user_profile, agent_case, agent_skill, knowledge_document, knowledge_topic diff --git a/docs/configuration.md b/docs/configuration.md index 6dbd79c08..c655732d3 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -186,6 +186,7 @@ inherits too, so a template's `api_key = ""` cannot mask `[llm]`'s key. | Task | What it calls the model for | |---|---| | `boundary` | Cutting a session's messages into memcells (user and agent tracks) | +| `language` | Naming each memcell's conversation language, which its episode and everything extracted from it are written in | | `episode` | Extracting each memcell's episode | | `summary` | The episode's display summary, written offline from the stored episode (`summarize_episode`) | | `atomic_fact` | Atomic-fact extraction | @@ -197,12 +198,28 @@ inherits too, so a template's `api_key = ""` cannot mask `[llm]`'s key. | `search` | Search-time calls: agentic retrieval and the LLM rerank lane | | `decider` | The multi-round retrieval decider (`llm_multiround`) | +LoCoMo accuracy and write / search latency for several models per stage are in +[benchmarks/locomo.md](../benchmarks/locomo.md#results-by-model-and-retrieval-method). + The task names are a stable interface. Environment variables nest one more level: `EVEROS_LLM____`, e.g. `EVEROS_LLM__BOUNDARY__MODEL`. `everos config show` prints what every task resolves to -- model, endpoint host and the section each field came from -- and the server logs the same at startup (`llm.task.resolved`; the key is never printed). +**The language task's own defaults.** The language call runs in the write +path, once per memcell before its episode, and its reply is one word. When +`[llm.language]` leaves these fields unset, they take the language task's own +values instead of `[llm]`'s: + +| Field | Language default | Why | +|---|---|---| +| `temperature` | `0.0` | The same conversation is named the same way every time. | +| `max_tokens` | `64` | The reply is one label; a model that thinks before it answers runs out, so give this task a model with thinking off. | +| `timeout_seconds` | `3.0` | A synchronous `/add` waits for it. A call that runs out of time only leaves the language to the episode model. | +| `sdk_max_retries` | `0` | The timeout is the whole wait. | +| `invalid_reply_retries` | `0` | An unusable reply is given up, as a timeout is. | + **The decider's own defaults.** The decider runs inside a search request, so the time and retry budget of one round is bounded by the caller waiting on it, not by `[llm]`'s background-extraction values. These three fields, when @@ -300,6 +317,38 @@ Episodes are folded one owner at a time. A run folds the episode that triggered |---|---|---|---|---| | `max_episodes_per_call` | int | `10` | No | Most episodes one extraction call folds, the triggering one included; `1` folds each alone. | +#### NVIDIA NIM + +[NVIDIA NIM](https://build.nvidia.com/) serves an OpenAI-compatible Chat +Completions API, so it plugs into `[llm]` like OpenRouter does: set the model, +key, and base URL. Model ids use the `/` form; pick one from +the endpoint's `/models` list. + +```toml +[llm] +model = "nvidia/nemotron-3.5-super-vl-120b-a12b" +api_key = "" +base_url = "https://integrate.api.nvidia.com/v1" +``` + +Or keep the key out of the file and pass your `NVIDIA_API_KEY` through the +environment: + +```bash +export EVEROS_LLM__API_KEY="$NVIDIA_API_KEY" +export EVEROS_LLM__BASE_URL=https://integrate.api.nvidia.com/v1 +export EVEROS_LLM__MODEL=nvidia/nemotron-3.5-super-vl-120b-a12b +``` + +Other hosted models you can use include `nvidia/nemotron-3-ultra-550b-a55b` +and `nvidia/nemotron-3.5-lightning-30b-a3b`. For a self-hosted NIM, point +`base_url` at your deployment instead (for example +`http://localhost:8000/v1`) and set `model` to the id it serves. + +The default `response_format_mode = "json_schema"` sends a strict JSON schema +with every extraction call. If your NIM model rejects or ignores it, set +`response_format_mode = "json_object"`, or `"prompt_only"` as the last resort. + ### `[multimodal]` | Field | Type | Default | Required | Description | @@ -390,11 +439,22 @@ unaffected: nothing is probed, compared, or recorded. ### `[rerank]` +Every model section names its service by `base_url`. The LLM, multimodal and +embedding sections need nothing more: their endpoints all speak the +OpenAI-compatible protocol. Rerank endpoints share no request format, so +`[rerank]` also takes `provider`, which picks the format `base_url` speaks: + +| `provider` | Request | `api_key` | +|---|---|---| +| `deepinfra` (default) | `POST {base_url}/{model}`, DeepInfra's inference API; EverOS wraps the query and documents in the Qwen3-Reranker template | Required | +| `vllm` | `POST {base_url}/rerank` with `model`, `query` and `documents`, an OpenAI-compatible rerank endpoint such as vLLM's | Optional, for a self-hosted server | +| `dashscope` | `POST {base_url}/api/v1/services/rerank/text-rerank/text-rerank`, DashScope's native text-rerank API for `gte-rerank-v2`; `base_url` is the host, not the `compatible-mode` path | Required | + | Field | Type | Default | Required | Description | |---|---|---|---|---| -| `provider` | string | `"deepinfra"` | No | Rerank provider: `deepinfra` or `vllm`. | +| `provider` | string | `"deepinfra"` | No | Request format of the rerank endpoint: `deepinfra`, `vllm` or `dashscope` (see above). | | `model` | string | — | **Yes** | Reranker model identifier. | -| `api_key` | string | — | **Yes** | API key. | +| `api_key` | string | — | Except `vllm` | API key; a self-hosted `vllm` server may take none. | | `base_url` | string | — | **Yes** | Rerank endpoint URL. | | `timeout_seconds` | float | `30.0` | No | Request timeout. | | `max_retries` | int | `3` | No | Retry count on failure. | @@ -421,16 +481,10 @@ everalgo's `BoundaryDetector` default. | LoCoMo ingest, 10 servers | about 4 minutes | about 17–22 minutes | | Episodes stored for LoCoMo | about 320 | about 550, each shorter | | Agent conversations (tool calls) | supported | chat messages only | -| LoCoMo `agentic`, best of three runs | 94.35%\* | 94.61%\* | - -The two scores are within LoCoMo's run-to-run spread of about one point. They -were measured with the reply format of each benchmark config: `batch` with the -default `[llm] response_format_mode = "json_schema"`, which keeps every reply to -its schema, and `step` with `"prompt_only"` for every call -([benchmarks/README.md](../benchmarks/README.md#batch-or-step)). -\* Graded against the corrected answers of the LoCoMo gold audit for the 99 -questions it disputes. +`step`'s lead on LoCoMo is within the benchmark's run-to-run spread of about one +point. Both scores, and the reply format each config was measured with, are in +[benchmarks/locomo.md](../benchmarks/locomo.md#batch-or-step). ### `[memorize]` @@ -459,6 +513,20 @@ joins it only behind its session's backlog) | `max_replays` | int | `3` | A batch in flight when the process died is replayed on the next start; after this many replays without finishing it is marked `failed` (`error_code: replays_exhausted`). | | `row_retention_hours` | float | `168.0` | Rows of any status are deleted this long after creation (seven days), including rows never delivered; the purge logs a warning for those. Delivered rows drop their request body at once, `failed` rows keep it. | +### `[memorize.input_log]` + +An append-only JSONL record of accepted `/add` requests, independent of +extraction (issue #537). The first PR ships it **disabled**; deletion and +purge integration, plus the default-on switch, follow separately. + +| Field | Type | Default | Description | +|---|---|---|---| +| `enabled` | bool | `false` | When on, one line per accepted `/add` goes to `///.input_log/YYYY-MM-DD.jsonl`. `/flush` is not logged. | +| `retention_days` | int | `30` | Daily files older than this are removed when the scope next writes. | +| `max_inline_bytes` | int | `1048576` | A line larger than this keeps text verbatim but replaces each `base64` attachment with its byte length and SHA-256. | + +A failed log write is reported at error level and **never fails `/add`**. + ### `[agent_memory]` | Field | Type | Default | Description | diff --git a/docs/device-assistant.md b/docs/device-assistant.md index 8e33010ce..b67da24d3 100644 --- a/docs/device-assistant.md +++ b/docs/device-assistant.md @@ -122,7 +122,7 @@ For device `D`, speaker slot `S`, in scope `app_id`/`project_id`: └── .index/ # sqlite + lancedb: one row set, owner-scoped ``` -- The episode **text** of a memcell is shared (one model call), but its +- The episode **text** of a memcell is shared (one episode call), but its **copies** are per owner: what S said and what T said land in two directories, each readable on its own. - The device directory holds exactly what belongs to no person: unattributed diff --git a/docs/how-memory-works.md b/docs/how-memory-works.md index bdd2afadd..22fd591bf 100644 --- a/docs/how-memory-works.md +++ b/docs/how-memory-works.md @@ -149,11 +149,22 @@ index catches up asynchronously. and reflection prompts with [custom instructions](custom_instructions.md). - Episode markdown is written **synchronously** — when `/flush` returns - `extracted`, the episode file is already on disk. A memcell costs one - extraction call: the episode is copied into the files of every user - sender of the memcell, each copy with a placeholder summary (the + `extracted`, the episode file is already on disk. A memcell costs two + calls: a short one names the language of its conversation, then the + episode is extracted in that language and copied into the files of every + user sender of the memcell, each copy with a placeholder summary (the episode's opening, cut and closed with `…`) that the OME replaces with a model-written preview shortly after. +- **Language.** The language call answers Chinese, Japanese or English (any + other language is written in English), judging the sentences the + participants write to each other rather than pasted code or documents, + names, or a few words of another language mixed in. The episode + stores that language, and its summary and atomic facts are written in it; + the profile takes the language of the first episode it is built from and + keeps it, and a Reflection merge follows the profile's language (else the + language most of the merged episodes share). When the language call fails + or times out, the episode model picks the language and the episode stores + the one its text is written in. - Everything else (atomic facts, profile, agent cases/skills) is produced **asynchronously** by the OME — see [the OME section](#the-offline-memory-engine-ome). diff --git a/docs/index.md b/docs/index.md index 92d952a9a..2e4e05d7f 100644 --- a/docs/index.md +++ b/docs/index.md @@ -54,7 +54,9 @@ specific thing (drain a queue, recover from a stuck row, etc.). | [windows.md](windows.md) | Install and run EverOS on Windows — natively or via WSL2 | | [windows.zh.md](windows.zh.md) | Chinese mirror of the Windows / WSL2 guide | | [github-sync.md](github-sync.md) | Guardrails for refreshing GitHub from internal exports without overwriting GitHub-only workflow files | +| [memtrace-graphs.md](memtrace-graphs.md) | Export MemTrace execution graphs with the default black/white, per-query, top-2 layout | | [benchmarks/README.md](../benchmarks/README.md) | Benchmarks (LoCoMo, LongMemEval, EverMemBench, SubtleMemory) — get the data, configure, smoke-test, reproduce | +| [benchmarks/locomo.md](../benchmarks/locomo.md) | LoCoMo results in detail — accuracy and search time across models and retrieval methods, batch or step boundary detection, write latency | ## Engineering / Internal diff --git a/docs/memtrace-attribution-review.zh-CN.md b/docs/memtrace-attribution-review.zh-CN.md new file mode 100644 index 000000000..abd5b8e99 --- /dev/null +++ b/docs/memtrace-attribution-review.zh-CN.md @@ -0,0 +1,313 @@ +# EverOS 图归因代码审查:与 MemTrace 主实现的对照 + +审查日期:2026-10-11。审查方式:源码对照、现有单元测试、虚构数据的离线复现。第 1–5 节保留修改前的审查结果;用户随后授权实施修复,实施状态见第 6 节。 + +## 1. 结论与范围 + +**当前 EverOS 已有可运行的 MemTrace 风格图归因闭环,但图的版本、实际输入和依赖关系仍存在足以改变归因结论的问题。不能仅凭归因返回 `status=success`,就认定它与 MemTrace 主实现具有等价的诊断能力。** + +优先处理的三项是:跨图版本错位(R1)、回答模型实际上下文与图中上下文不一致(R2)、skill bridge 的错误依赖连边(R4)。它们会直接改变归因算法看到的事实。其次处理请求隔离、占位节点、请求身份和大图探索问题。 + +本次以工作区实际代码为准: + +| 对象 | 位置 | HEAD | 范围 | +| --- | --- | --- | --- | +| EverOS | `EverOS/` | `6ff07ef` | `infra/memtrace`、service hooks、search collector、`examples/memtrace/graphtrace` 及驱动脚本 | +| MemTrace 主实现 | `MemTrace/` | `d027ed0` | `graphtrace`、`toolkits/memtrace_utils.py`、`bench_utils.py`、图合并工具、membase 部分插桩 | +| smartcomment | `smartcomment/` | `6683bf8` | identity、version、`identity_only`、操作子图语义 | + +这些 checkout 均存在预先已有的本地改动,HEAD 仅用于定位,**不代表被审查内容全部已提交**。目标是 `EverOS/`,不是 `EverOS-1/`。已有 `problem.md` 描述的部分旧问题已经被后续代码修复,本文没有将其直接作为当前缺陷依据。 + +实际验证使用 EverOS `.venv`:`everos` 指向本 checkout 的 `src/everos`,`smartcomment` 来自该 `.venv` 的 site-packages。已核对其 `api/_helpers.py` 与本地 smartcomment checkout 的同名文件 SHA-256 一致,所以下文关于版本分配和 `identity_only` 的分析与验证环境一致。 + +## 2. 算法对照:已经实现什么,尚不等价在哪里 + +| 环节 | MemTrace 主实现 | EverOS 当前实现 | 判断 | +| --- | --- | --- | --- | +| 归因目标 | 最早、局部错误且对最终错误具有决定性的操作 | 保留同一判定原则与五类错误 | 核心目标一致 | +| 起始证据 | 原始证据、伪证据或 synthetic root;伪证据支持 sparse/dense/hybrid,默认 hybrid | 对解码后的 message content 做 BM25,使用问题和参考答案 | 是稀疏检索子集,不能直接等同于主实现默认配置 | +| 图探索 | 七个 notebook tools、版本化节点、frontier 和每轮 hint | 保留七个工具与相同工作流 | 已实现核心机制 | +| active node | 主实现以排序容器首项表示 active | active 单独存储 | EverOS 避免了新增较早节点挤掉 active 的问题,不是缺陷 | +| 模型驱动 | AgentScope ReAct 与结构化输出 | OpenAI function calling、串行工具执行 | 可接受的实现替换 | +| 上下文管理 | token 计数、LLM 压缩、保留近期完整工具组 | 字符预算、删除旧工具组、保留最新组和全部完成记录 hint | 大图下存在 R8;不是同等的压缩策略 | +| QA 识别 | `llm-judge`、独立 `judge_score` | 同时支持 native QA 和 EverOS `judge_answer_*` | 兼容入口已补齐,但实际 QA 数据链有 R2、R7 | +| 输出 | `{error_type, op_id, reason}` | 同一 schema,加 transcript、失败状态和 inspected checks | 结构兼容;不能保证诊断正确,见 R10 | +| 批处理与实验 | `MemTraceRunner.arun`、缓存、多案例与统计 | CLI 默认选择 `cases[0]`,一次一例 | README 已明确,属于功能范围差异 | +| 图输入 | 消费已有 execution graph | 依赖文件差分、检索阶段快照及离线 QA 注入 | 归因可信度主要受 R1–R7、R9 限制 | + +对照位置:MemTrace `toolkits/memtrace_utils.py:286,933,1009,1065,1200`、`graphtrace/graph_trace_agent.py:164,189`;EverOS `examples/memtrace/graphtrace/{agent,retrieval,models,notebook,prompts}.py`、`examples/memtrace/attribute.py:124`。 + +英文 tokenizer `[a-z0-9_]+` 是从主实现继承的行为。纯中文问题和消息可能全部得到零分,进而按创建时间选起点;这不是本次移植新增的 BM25 错误,但 EverOS 没有 dense/hybrid 补偿路径。主实现是否表现更好仍需同数据、同模型对照,本文不作准确率推断。 + +## 3. 问题清单 + +P1:可能直接改变记忆历史、真实依赖或故障归属,应在将归因结果用于实验结论前处理。P2:特定条件下丢失证据、误连请求、终止探索或接受不合规结果。 + +“复现”表示已经执行虚构数据验证;“源码确认”表示控制流可直接确定;“条件性限制”表示明确触发条件下存在信息缺口,不等于已证明真实业务运行出现该故障。 + +| 编号 | 级别 | 问题 | 证据 | +| --- | --- | --- | --- | +| R1 | P1 | 同一记忆在不同图中独立编号,合并后接错历史版本 | 复现 | +| R2 | P1 | 图中的回答上下文并非示例真正交给模型的上下文 | 源码确认 | +| R3 | P1 | 文件差分无法保证恢复真实操作历史和检索时刻状态 | 条件性限制、源码确认 | +| R4 | P1 | skill bridge 与 fusion 的输入连边不符合实际计算 | 复现、源码确认 | +| R5 | P2 | 持久记忆节点复用使不同 query 的下游相互串联 | 复现;主代码部分插桩也有同类模式 | +| R6 | P2 | candidate stub 后续成为 hit,仍不保存已经可得的正文 | 复现 | +| R7 | P2 | request id 重复与重启时的 query 身份、QA 解析不可靠 | 复现、源码确认 | +| R8 | P2 | 无值预览不分页,与保护最新工具组的策略共同导致大图直接失败 | 复现 | +| R9 | P2 | 失败的 add 没有记录本次输入消息,错误操作与源证据脱离 | 源码确认、离线验证 | +| R10 | P2 | 提交校验仍接受 judge 等不应被归因的操作 | 复现;校验能力缺口 | + +### R1:跨图版本号不是同一条版本时间线 + +**位置**:`src/everos/infra/memtrace/tracker.py:1170–1181,1389–1421,1776–1885`;smartcomment `api/_helpers.py:214–288`;MemTrace `toolkits/graph_merge_utils.py:124–150`。 + +写入按 `(app, project, owner, session)` 分图,而不带 session filter 的查询通常进入 `global` 图。smartcomment 只在当前图内查找最新版本:新图第一次看到一个 identity,版本就是 `@1`。相同 identity 并不意味着不同图内的 `@1` 对应同一历史内容。 + +**已复现**: + +```text +写入图:alice_ep_1@1 = Friday;alice_ep_1@2 = Monday +搜索图:第一次搜索发生在更新后,alice_ep_1@1 = Monday +合并冲突:alice_ep_1@1 +``` + +主仓库 merge 工具按 `full_node_id` 合并,冲突保留较早图的快照,只在 metadata 报告冲突。因此搜索边仍指向 `@1`,但合并后的 `@1` 是 Friday;真正被检索的 Monday 成了写入图中的另一版本。图能成功 import,也不代表版本语义正确。 + +**影响**:丢失信息的更新可能被绕过,或把一次正确检索解释成返回旧记忆。针对 UpdateError、DeletionError、RetrievalError 的结论均受影响。仅增加“合并成功”检查不够。 + +另一个边界是 app/project:图文件名有租户隔离,但 entry identity 仅为 `{owner}_{entry_id}`。若将不同 app/project 的图放进同一 merge 输入,相同 owner/entry id 仍可能误合并。 + +**建议**:建立带 app/project 的稳定逻辑身份和跨图一致的 revision 引用;或采用统一的构建版本图并显式引用其版本。合并前拒绝无法消解的内容冲突,不能仅凭局部版本号认定相同节点。回归样例必须覆盖“先更新、后首次跨会话搜索”。 + +### R2:图中声称模型看到了实际上没有送入提示词的事实 + +**位置**:`tracker.py:1316–1334,1467–1508`;`examples/memtrace/filetrace_locomo_drive.py:167–176`;`src/everos/infra/memtrace/qa.py:147–158`。对照 MemTrace `membase/runners/evaluation.py:170–175,193–205,241–265`。 + +tracker 的 context 包含 episode、atomic facts、profile、agent case、skill 对应的 passages,并将返回的 unprocessed message 连到 context。可是示例 `_qa_record()` 的实际 prompt 只拼接 `episodes[].episode`,缺失时才退回 subject/id;没有拼接 atomic facts、profile 或 unprocessed message。QA 注入又把 tracker context 作为 answer generation 的输入。 + +例如:episode 摘要没有日期,atomic fact 含 `Friday`。归因图的 context 包含 Friday,但实际回答 prompt 不包含它。若回答失败,模型可能据此选择 ResponseError;真正需要检查的却是 response 数据到 QA prompt 的组装过程。 + +MemTrace evaluation 会记录实际用于 `qa_operator` 的 `contexts[idx]`,并保留 context builder 的来源信息。这正是 EverOS 此处需要对齐的契约。 + +**建议**:分别记录检索响应和实际 `answer_context`,显式记录从前者到后者的组装操作;QA 只连接实际使用的 context。unprocessed message 的正文也应与 context 的值一致。prompt 已存入图,人工能发现冲突,但这不能抵消错误的输入连边。 + +### R3:观察时间和磁盘终态不能恢复真实操作历史 + +**位置**:`tracker.py:493–547,619–645,1679–1749,1820–1857,2122–2202`;`src/everos/service/search.py:108–124`。对照 MemTrace `membase/layers/naive_rag.py:146–249` 的运行路径内插桩。 + +当前文件差分在业务执行之后记录状态。它捕获的是两个扫描时刻之间的终态变化,存在以下明确边界: + +1. 一次扫描间隔内经历“创建正确记忆 → 错误更新”,图可能只看到错误的首次创建,无法区分 ExtractionError 与 UpdateError;若经历“创建 → 删除”,甚至没有 entry 节点。 +2. 一个 memcell 没有产生 Markdown entry 时,不会进入 `_apply_entry()`,也就不会因该 entry 调用 `_record_parent()`。空抽取、全部输出被过滤等情况无法得到与成功 entry 同等粒度的输入、操作和输出。显式 flush op 已存在,但其 `outputs=[]` 和请求级状态不等于真实抽取结果。 +3. 新 profile/skill 等 whole-file artifact 只记录变量,没有抽取操作及输入来源。归因不能沿构建链判断关键事实最初是否被保存。 +4. 搜索完成后才 `_sync_files()`,随后 hits 优先使用 `_entries` 的磁盘快照。若索引滞后,或磁盘在搜索期间更新,hit 节点可能描述较新的磁盘内容,而 context passage 仍是本次搜索实际返回的旧文本。 + +**影响**:`event_seq` 可以排列记录动作,却不能还原被观察前的真实事件顺序,无法普遍保证“最早决定性故障”。文档和 prompt 已承认 file-diff 的观察性质;这是已知架构限制,但仍是达到用户目标的重要缺口。 + +**建议**:在 boundary/extraction/update/delete、索引投影、实际 context assembly 的必要边界补充真实事件与输入输出;至少保留操作尝试、空结果和实际读到的 revision。无法补齐时,应输出“不足以区分”的范围或 InsufficientEvidence,不能用终态推断唯一真实故障操作。 + +### R4:skill bridge 的阶段排序被错误地当成依赖关系 + +**位置**:`tracker.py:1235–1286`;`src/everos/memory/search/manager.py:302–321,546–604`。 + +实际计算是: + +```text +agent_case 最终结果 + skill dense → bridged_dense +skill sparse + bridged_dense → skill fusion/rerank +``` + +tracker 按 kind 维护 `pending`。遇到 `bridged_dense` 时,将同 kind 累积的 sparse/dense 都接为输入,再将 pending 替换为 bridged_dense。因此记录成: + +```text +skill sparse + skill dense → bridged_dense +bridged_dense → skill fusion +``` + +离线复现确认了这两组实际图边。agent_case 到 skill bridge 的跨 kind 依赖丢失;sparse 被误认为参与 dense 合并;fusion 又丢失实际的独立 sparse 输入。 + +**影响**:归因无法准确判断错误来自 case 检索、bridge 扩展还是 sparse/fusion,也可能把未参与该步计算的数据作为该步输入证据。 + +**建议**:stage record 提供显式 stage id 和 input stage ids,包含跨 kind 的依赖;不能根据列表出现顺序推断通用 DAG。验证时应检查每个 op 的输入集合与 manager 的实参一致。 + +### R5:共享记忆节点产生跨 query 的虚假可达路径 + +**位置**:`tracker.py:1411–1508,1617–1675`;`examples/memtrace/graphtrace/notebook.py:181–201`。 + +两个查询命中同一持久记忆版本时,都会连到同一个 entry 节点,随后该节点又连向各自的 context: + +```text +Q1 → pool1 → E@1 → context1 +Q2 → pool2 → E@1 → context2 +``` + +因此同时存在 `Q2 → E@1 → context1`。离线复现中,后发生的 Q2 可以到达先前 Q1 的 context。notebook 又会展示该节点参与的全部操作,没有以当前 failed case 做请求范围或时间截断。 + +**影响**:追踪“沿最终输出继续向下游”时可能进入其他问题的回答链,或者把当前问题之后才发生的操作当作候选故障。此处未必产生图论意义上的环,但已经不再是严格的请求因果图。 + +**对照说明**:MemTrace 的 `membase/layers/naive_rag.py:307` 也存在 query 输出到稳定 memory identity 的模式,因此这不能宣称是 EverOS 独有回归。EverOS 的长期、多请求合并图使这一风险更突出;照搬主代码本身并不能解决。 + +**建议**:为每次检索建立请求独立的 hit/result 节点,将持久 entry 作为其来源输入或显式引用;context 使用本次 hit。归因探索同时约束 case、请求和历史截止点,保留必要的构建祖先。 + +### R6:占位节点不会因后续命中而补全 + +**位置**:`tracker.py:1395–1404,1617–1658`;smartcomment `api/_helpers.py:240–255`;MemTrace `toolkits/graph_merge_utils.py:57–78`。 + +当未知 candidate 首次出现,会记录 `{"id": ..., "source": "candidate_pool"}`。之后它真正出现在 search response 中,只要当前图已有版本,tracker 就设置 `identity_only=True`,复用旧节点,不使用新返回的正文。 + +**已复现**:先在 terminal pool 中出现 `ep_late`,再让它成为包含正文的 hit;最终 `alice_ep_late` 仍只有 candidate_pool stub。context 虽另存 response 文本,但 memory 节点和其历史链缺少这份已知证据。 + +此外,主仓库 merge 工具只把键集合恰好为 `{"id"}` 的快照识别为占位。带 `source` 的 stub 不满足条件,不能依赖“合并时 rich snapshot 覆盖 stub”的既有规则自动补救。 + +**建议**:用显式占位标记并统一合并契约;将“补全一次观察内容”与“业务记忆更新”区分开,或记录独立的请求 hit。避免永久冻结缺正文的节点,也避免把观察补全伪造成 UpdateError。 + +### R7:query 的碰撞处理与 QA 回连没有使用同一个稳定请求身份 + +**位置**:`tracker.py:261–283,1183–1204,1310–1311,2384–2454`;`qa.py:88–94`。 + +有两个问题: + +1. **重启**:`_next_query_identity()` 在 `_update_graph()` 恢复磁盘图之前调用,此时 `_graphs.get(key)` 可能为空;`_query_seq` 又从零开始。同 request id,或未传 request id 的首个直接调用,可能复用历史 query identity。复现得到同一请求名下的 `@1`、`@2`,而不是不同请求节点。context/pool/QA identity 也由 query identity 派生,风险会扩散。 +2. **同进程重试**:记录侧给重复 request id 添加 `-NNNN` 后缀,但 `resolve_query_node()` 一旦发现无后缀 base,就直接返回 base 的最新版本。正常碰撞时 base 本来就存在,suffix 分支不会被使用;新的 QA 很容易回连到第一次查询。 + +**影响**:把回答、参考答案或 judge 接到错误的检索上下文。现有 `query_id` 自洽检查仅检查快照字符串是否一致,不能证明绑定的是正确请求实例。 + +同进程复现中同时存在 `query-alice-q2` 和 `query-alice-q2-0006`,QA resolver 返回前者,确认没有定位到新一次请求。 + +**建议**:先恢复图,再分配请求 identity;向 QA 返回和传递确切的 query full node id 或不可重复的 execution id。对确实属于同一次请求的重试明确幂等规则;无法唯一解析时拒绝注入,不能静默选择 base。 + +### R8:推荐的无值预览可以使归因在下一轮直接失败 + +**位置**:`examples/memtrace/graphtrace/notebook.py:158–202,316–352`;`agent.py:62–90,190–201`。对照 MemTrace `graphtrace/graph_trace_agent.py:189`。 + +`include_variable_value=False` 会返回所有相关操作,忽略 `offset/limit`;但 `trim_history()` 不能裁剪最新工具组,也不能裁剪 fresh hint。大图一次预览就可能超过默认 `context_chars=100000`,下一轮调用模型前直接返回 ContextBudgetError。 + +**已复现**:用虚构图给同一 message 增加 180 个操作,无值预览长度为 **215149 字符**。脚本模型只调用一次预览,归因便在第 2 轮准备阶段失败:`iterations=1`、`failure.type=ContextBudgetError`。模型没有机会遵循报错建议缩小工具页;这个模式本身还忽略页大小。 + +另外,hint 包含所有已完成节点的 outcome,随探索持续增长,即使旧对话已删除,保护部分仍可能溢出。主实现有 token 计数和摘要压缩,当前移植的直接裁剪不是等价替换。 + +**建议**:无值预览也按操作分页并遵守预算;对历史 outcome 做有界摘要或按需查询;单个超大工具结果应给可恢复的分页提示。保留工具请求/响应配对的现有约束。 + +### R9:失败 add 的错误记录没有保留导致错误的本次消息 + +**位置**:`tracker.py:549–617`;`src/everos/service/memorize.py:236–250`。 + +成功路径先 `_record_messages()`,失败路径却先扫描文件,然后把非 flush 错误记录到 `(app, project, "unknown", session)`。失败 hook 不调用 `_record_messages()`,通常在 unknown owner 图里也找不到输入 buffer,最终只是一个没有本次源消息的错误操作。 + +**触发**:首次 add 在 ingest 之后、抽取或写入过程中抛错,随后用户对本应被保存的事实提问。即使 payload 中有关键消息,归因侧也无法从 message 起点走到该失败操作;部分 Markdown 写入时还可能出现 source stub 与 unknown error op 分离。 + +离线向错误 hook 传入含一条虚构消息的 payload 后,失败请求图中的 `category=message` 节点数量为 **0**。 + +**对照**:主代码内联记录在执行过程中建立 message、buffer 和中间输出。它也不保证所有异常都完整可归因,但当前 EverOS 的错误 hook 明确拥有 payload 却没有保存它。 + +**建议**:将本次输入作为“提交/尝试处理的消息”记录,并与正确 owner/session 的失败请求操作相连;区分提交、接受、成功落盘,避免把失败请求误记成成功构建。新增回归样例应检查输入可达性,不能只检查错误 op 存在。 + +### R10:结果通过校验,不代表满足已声明的归因约束 + +**位置**:`examples/memtrace/graphtrace/agent.py:228–246`、`notebook.py:201`、`prompts.py:127–136`。 + +目前校验包括 schema、op 存在、探索已结束、非 insufficient evidence、op 标题出现在工具输出。但没有排除 judge/reference injection,也不要求 reason 包含节点证据;“inspected”来自对返回文本中标题的正则匹配,标题出现不代表读到了该操作的输入输出值。 + +**已复现**:查看 query 的无值预览后,结束探索,提交: + +```json +{"error_type":"DeletionError","op_id":"judge-op","reason":"Test guard"} +``` + +结果为 `status=success`。这违反本地 prompt 中“不要把 judge/reference injection 当成 memory-system fault”的要求。这里只证明校验接受该结果,不声称真实模型必然如此回答。 + +**对照说明**:主实现的结构化输出也不是诊断正确性证明;EverOS 新增的 inspected guard 是改进,但仍未覆盖可机械验证的限制。不要简单禁止所有 `category=evaluation`:主实现的 `question-answering` 操作也属于 evaluation。 + +**建议**:按操作角色明确排除 judge/reference injection,保留 native answer generation 兼容;记录结构化的已展示 operation ids 和已读取证据,而不是从正文识别标题;输出区分 schema-valid 与经过证据规则检查。诊断语义仍需人工标签或受控故障实验评估。 + +## 4. 其他需要保留的边界 + +以下不另列为主问题,避免把设计取舍全部当作新增 bug: + +- **扫描重试不是完整事务**:`tracker.py:1744` 在 graph apply/export 成功之前更新 `_file_state`;`1821–1822` 也提前写 entry cache。若后续构图失败,下一次未变动文件可能直接跳过。解析异常已支持重试,但这不覆盖 apply 异常。建议后续以失败注入测试验证提交/回滚边界。 +- **不完整候选集**:pool cap 为 50,已有 `total_count/truncated` 标记;不能据此把“未出现”解释成“从未召回”。中间 pool 只保留 id/score/source,只有 terminal pool 展开 candidate,无法普遍仅凭图恢复中途被过滤记忆的当时正文。 +- **多进程写图**:当前 portalocker 能防止半文件,不能合并各 worker 的内存图。单 writer/独立输出目录是现有明确限制,不应写成“当前没有文件锁”。 +- **QA 注入需按既有流程停服执行**:运行中的 tracker 保留内存图;离线注入后的边并不会自动进入它的内存。重复注入也会增加 judge 操作,收集案例时可能出现同 query 多次评估;应明确注入幂等键和评估版本。 +- **没有伪造主实现等价性**:只支持 BM25、单案例 CLI、没有 OBS 和缓存,是 README 已说明的范围差异。是否需要移植取决于实验目标,不能单凭缺少这些功能判定核心算法错误。 + +## 5. 验证结果与覆盖空白 + +现有测试命令(EverOS 根目录): + +```bash +PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -m pytest \ + tests/unit/test_memtrace_example \ + tests/unit/test_infra/test_memtrace_tracker.py \ + tests/unit/test_infra/test_memtrace_qa.py \ + -q -p no:cacheprovider \ + --basetemp=/tmp/everos-attribution-review-pytest-escalated +``` + +结果:**94 passed in 8.29s**。最初沙箱内运行出现 asyncio 线程收尾卡住;允许在沙箱外执行后通过,未将该环境现象计为项目 bug。 + +额外的临时离线脚本使用真实 tracker/graphtrace API、现有虚构图 fixture 和 scripted provider;输出图只写入 `/tmp/everos-review-*`。没有调用线上 LLM、没有读取凭据内容、没有启动或修改 EverOS 服务、没有改写已有实验图。关键观测如下: + +| 验证 | 观测 | +| --- | --- | +| 写入 v2 后首次跨图搜索 | 写入图 v1=Friday、v2=Monday;搜索图 v1=Monday;merge 报同 id 冲突 | +| 两次查询复用同一 entry | Q2 到 Q1 context 的有向可达性为 True | +| skill 阶段依赖 | bridge 输入为 skill sparse+dense;fusion 输入只有 bridge | +| stub 后续命中 | 节点仍为 `id + source=candidate_pool` | +| 重启后重复 request id | 同 query identity 出现 @1/@2 | +| 同进程重复 request id | 新 query 有后缀,QA resolver 仍选择无后缀的旧 query | +| 首次 add 失败 | 已传入消息,但失败请求图的 message 数为 0 | +| 大图无值预览 | 215149 字符;仅完成一次模型请求便因上下文预算停止 | +| 错误提交 judge-op | 以 DeletionError 提交仍被接受为 success | + +这些样例验证的是图和运行时契约,**不是归因准确率评测**。94 个测试通过与上述问题存在并不矛盾:当前 scripted end-to-end 测试预先指定探索路线,主要证明工具调用闭环,不能证明真实 tracker 生成的跨图、跨请求版本和依赖正确。 + +建议补充的验收顺序: + +1. **先验证图事实**:单租户及多租户 identity、更新后的跨图命中、真实 QA context、bridge 输入集合、失败 add 的源消息、重启后的精确 query 回连。 +2. **再验证探索能力**:大图分页、历史摘要、当前 case 的范围限制、非法 judge 归因的拒绝。 +3. **最后比较归因结果**:构建 Extraction/Update/Deletion/Retrieval/Response 五类受控故障,在同一份语义正确的图、同一模型、同一 sparse 起点条件下比较 EverOS 和主实现;另行比较 hybrid 起点效果。分别统计归因正确、证据不足、图不完整和运行失败,不能把这些结果混为一个准确率。 + +当前更有价值的下一步是先修正图的事实与连接,再扩充检索策略或模型能力。否则更强的归因模型仍可能依据错误的图得出看似合理的结论。 + +## 6. 修改实施状态(2026-10-11) + +本次修改针对图事实、连接和可机械验证的归因约束,不宣称达到 MemTrace 主实现的全部功能或归因准确率。 + +| 编号 | 实施结果 | +| --- | --- | +| R1 | 搜索图引用构建图的原始 revision,保留 `@2` 等版本号;新增 `examples/memtrace/merge.py`,按 app/project 隔离节点并拒绝内容冲突;CLI 拒绝带未解决冲突标记的旧合并图。 | +| R2 | 新增实际 `answer_context` 及组装操作;LoCoMo 驱动传入真正使用的 episode context;回答只消费该节点。未记录的 context 保持 unknown,不能据此提交 ResponseError。 | +| R3 | boundary cell、episode extractor 尝试/结果、持久化关联改为采集真实事件;空结果可见。持久化关联只在正文与实际抽取输出一致时成立,后续磁盘改写不能冒充 extractor 输出。hit 保留搜索响应正文,无法匹配历史内容时 revision 明确未解决。其余文件差分标为 `observation_only`,提交时拒绝把观察动作当作执行故障。**背景 OME 的所有中间更新/删除尚未实现逐步事件采集,证据不足时必须停止,不能从终态推断唯一故障。** | +| R4 | stage 增加显式 id 和 input ids;真实 LLM bridge 路径验证 case fusion + skill dense,随后 sparse + bridged dense。普通路径不虚构 case 输入。 | +| R5 | 检索 hit 按请求独立,context 消费本次 hit;探索和起始证据选择限制租户、当前请求和历史截止点。 | +| R6 | candidate 使用请求内的显式占位观察,后续请求 hit 独立保存正文,不再冻结持久记忆节点或伪造业务更新。 | +| R7 | 恢复图后再分配 query id;重复 request id 默认拒绝歧义,QA 支持确切 `query_full_node_id`;离线注入也检查跨文件/租户唯一性。 | +| R8 | 无值预览、value、history 均分页;工具页随预算缩小;跨页累计真实 operation 阅读范围;hint 仅保留有界摘要,完整历史可按需查询。 | +| R9 | 失败 add 的本次消息保存为 attempted,与各参与 owner/session 的失败操作相连,不伪装为接受成功。 | +| R10 | 检查实际已展示的操作和已读节点,reason 必须引用相关 full node id;明确拒绝 judge、reference injection、其他请求/未来操作及纯文件观察归因,保留 native QA 角色兼容。 | + +额外修复:相同 QA record 用摘要标识实现幂等(包括仅 answer、仅 golden);构图或导出异常会恢复扫描指纹,未变化文件仍可重试,entry/artifact/deletion cache 在成功后提交。这不是整个图的强事务回滚,仍需区分局部记录异常与完整业务执行历史。 + +运行顺序:重新采集 → 停止服务 → 注入 QA → 用新增 safe merger 合并构建图和搜索图 → 列出并执行归因。旧图中缺失的输入、正文、版本历史和背景中间状态无法通过事后合并恢复,不应覆盖旧实验结果或猜测修复版本。 + +新增验证均使用虚构数据和 scripted provider,没有运行线上 LLM、修改真实实验数据或启动服务。最终受影响测试 **483 passed in 14.71s**: + +```bash +.venv/bin/python -m pytest -q \ + tests/unit/test_infra/test_memtrace_tracker.py \ + tests/unit/test_infra/test_memtrace_qa.py \ + tests/unit/test_infra/test_memtrace_regressions.py \ + tests/unit/test_memtrace_example tests/unit/test_service \ + tests/unit/test_memory/test_search tests/unit/test_memory/test_extract \ + tests/unit/test_entrypoints/test_api/test_lifespans/test_memtrace.py +``` + +其他检查结果: + +- `ruff check src tests examples/memtrace`、`ruff format --check`:通过,673 个文件格式一致。 +- `lint-imports`:3 个依赖契约全部通过;datetime discipline、OpenAPI drift、`git diff --check`:通过。 +- 新增 safe merge CLI → 离线 `--list-cases`:通过,无凭据及外部模型请求。 +- `scripts/check_docs.py`:未通过,错误全部位于已有、gitignored 的 `smartcomment_docs/` 本地镜像,其中 README/code reading guide 的相对源码链接不存在;本次修改文档没有新增该检查报告的失效链接。 + +这些验证证明图契约和工具行为,不代表真实模型在 LoCoMo 或五类受控故障上的归因准确率。完整项目测试、真实 LLM 对照和背景 OME 全事件历史不在本次验证结果内。 diff --git a/docs/memtrace-graphs.md b/docs/memtrace-graphs.md new file mode 100644 index 000000000..49b2175e6 --- /dev/null +++ b/docs/memtrace-graphs.md @@ -0,0 +1,179 @@ +# MemTrace graph export + +## Recorded topology + +Search graphs retain every stage and its candidate-list snapshot, but only the +last pool of each memory kind expands candidates into request-local +`retrieval_hit` nodes. A returned hit stores the response text and, when an exact +content match exists, references its canonical `memory_entry` revision through +`source_revision` and a source-to-hit edge. Version numbers are preserved across +graphs. Unknown candidates carry `identity_only=true`; they do not create +persistent entry stubs or freeze later requests' observations. +If response shaping introduces an episode absent from the last pool's +snapshot, or a capped snapshot omits a returned entry, its membership edge +carries `response_only: true`; the actual pool list stays unchanged. Searches +without stage records retain the query-to-hit chain. A failed search expands +only the last observed pool of each kind. + +Construction graphs remain partitioned by sender, but each participating +sender's buffer records the complete add batch, including assistant replies. +Both messages therefore feed the same buffer version in a two-message chat +request. Later adds link the previous buffer version and both new messages to +the next buffer version. The first observed empty buffer is a node too. +Boundary detection follows `message_buffer -> boundary_detection_result -> memcell`. +There is no raw-response node or direct buffer-to-memcell edge. Membership +IDs remain on the memcell snapshot and match SQLite. Derived episodes and foresights +reuse that boundary operation; missing child `sender_ids` never creates a +new memcell version. SQLite supplies the boundary's message and sender IDs. + +The boundary service captures the real loaded, deduplicated and persisted buffer +IDs. Non-final detection records the persisted tail; a successful flush records +the consumed buffer-to-tail transition as its request-level operation. Empty +flushes also receive their own version. Calls without a captured buffer state +use a request-specific completion receipt, rather than sharing the global +`COMMENT:NONE` output sentinel. `message_count` in a flush response counts fresh +input messages and does not describe how many buffered messages were drained. + +Profile tracing is temporarily disabled: searches do not record profile-read +operations, pools, or hits, including when callers supply older stage records. +The actual profile fetch and response are unchanged, and the context snapshot +still includes returned profile content. + +Pending-message retrieval is an independent `query -> retrieval_results -> context` +branch. Its single `retrieval_result` variable contains the complete returned +message collection; search no longer expands individual message nodes. Reads +require a top-level `filters.session_id` equality predicate. The operation and +result preserve success, empty reads, skips, errors and the completion timestamp. +Empty and skipped results still connect directly to the context; failed searches +record the result without fabricating a context. Responses without collected +stages also receive this aggregate result when they contain pending messages. + +The service also captures actual boundary cells and episode extractor results, +including empty results, through a request-local collector. +Every successful deferred add also records a boundary outcome with +`decision=deferred` and `detection_performed=false`; it does not imply an LLM call. +Deferred adds retain `message_buffer -> boundary_detection_result -> no_split_marker`. +An observed model call records `message_buffer -> boundary_detection_result`; +the result then feeds either MemCells or a no-split +marker. The result preserves the actual batch response under `model_result` +(boundary indices, waiting flag, and reasoning), alongside the applied message +groups and `is_final`. A final flush can close a cell even when the model reports +no topic boundary; these two decisions are not conflated. Model boundary indices +refer to the detector's chat input after any forced prefix splits, whereas the +applied groups use canonical message IDs. No incremental-detector confidence or +should-end fields are fabricated. Unobserved model calls remain service outcomes. +File-only observations use the same path through a recovered grouping result, +marked `observation_only=true` with unknown `detection_performed`; they do not +fabricate model decisions. Messages feed that result directly when the matching +buffer version is unavailable. +These operations carry `source=construction_event` and the original observation +timestamp. The episode chain is `memcell -> cell-input -> extracted -> episode`. +Extraction-start events do not create placeholder attempt nodes or operations. +Failed adds keep the attempted messages connected to the owning session's error +operation without treating them as accepted buffer contents. + +Skill stages declare their input stage ids. With the case bridge enabled, dense +skills and the case fusion pool feed `bridged_dense`; sparse skills and that +bridged pool feed skill fusion. The non-bridge path uses only direct dense input. + +The retrieval response's `context` includes the actual returned unprocessed +messages. QA uses a separate `answer_context` snapshot containing exactly the +text supplied to the answer model, connected through a context-assembly operation. +If the caller omits it, the value remains unknown rather than borrowing the +retrieval response. + +Foresight entries consume the same original input as episode extraction through +`memcell -> cell-input -> foresight`, rather than depending on the episode result. +The input node and its incoming edge are shared across derived foresights and +survive restarts. Missing input snapshots are restored from the matching app, +project and session's SQLite `Memcell.payload_json`; unavailable payloads remain +null with `content_observed=false`. Generation is disabled by default; enable +`[strategies.extract_foresight]` +with `enabled = true` in the memory root's `ome.toml`. These asynchronous OME +writes are observed at subsequent requests or the final shutdown sync. +Such file-diff operations carry `observation_only=true`; their timestamps do not +establish when extraction, update or deletion actually executed. The attribution +runner rejects them as executed fault operations. Background transformations +between scans still require more event instrumentation to distinguish reliably. +Foresights are currently construction artifacts and are not search results. +The `reranked_results` class on an episode `hierarchy` pool denotes the +hierarchy scoring stage, rather than a separate reranker invocation. + +Nodes, operations and edges carry concise English comments describing their +contents or action without function names. Search-stage identifiers remain in +metadata. Live and offline QA exports also describe their context-assembly steps; +exported system placeholders receive fixed descriptions. These recording changes +apply to newly collected graphs and do not rewrite historical experiments. + +`examples/memtrace/export_png.py` converts smartcomment execution-graph JSON +files into report-ready PNGs. Run it from the EverOS checkout after a replay +or server run: + +```bash +python examples/memtrace/export_png.py /path/to/memtrace \ + --out /path/to/memtrace/png +``` + +## Default presentation + +- Nodes, borders, labels, and edges use a white/black palette so the graph is + readable in papers and logs. +- A graph with multiple `query-*` nodes produces one image per query. The + filename contains the query number and request-id prefix, for example + `...__search-01-a55a090d.png`. +- Every candidate pool displays only its first two items. The pool still shows + its original `total_count`. Membership edges show those displayed candidates + plus every actual returned entry, including response-only episode wrappers. + This limits candidate fan-out without disconnecting the assembled context. +- Construction-only graphs (without query nodes) are rendered as one image. + Input JSON files are read-only and are never rewritten. + +## Options + +Use `--top-k N` to choose the displayed pool size (`--top-k 2` is the default; +`--top-k 0` keeps every item). Use `--combined` when a single whole-graph +image is needed instead of query-specific images. The exporter validates each +display graph through `ExecNetwork.import_graph` before invoking Graphviz. + +The `dot` executable must be available on `PATH`. The exporter intentionally +does not change how EverOS records searches: a `hybrid` pool is the RRF merge +of sparse and dense candidates, and remains visible as one stage in the +query-specific graph. + +## Merging and QA + +Stop the server before offline QA injection; an idle server still holds a live +graph that can overwrite injected edges. Duplicate identical QA records are +idempotent. Reused request ids require an exact `query_full_node_id`; ambiguous +tenant matches additionally require `app_id`/`project_id`. + +Use the safe merger on the original construction and search exports: + +```bash +.venv/bin/python examples/memtrace/merge.py /path/to/memtrace \ + --output /path/to/merged.json +``` + +It namespaces every variable by tenant, adds scope metadata for exploration, and +rejects conflicting immutable revisions. Older exports with inconsistent local +versions require recollection. File locking protects atomic writes but does not +merge independent workers' live graphs; use one writer or separate directories. + +## Repairing older construction graphs + +Older trackers repeated boundary detection for every derived foresight and +used child-specific sender metadata, creating duplicate message edges and +false memcell versions. After stopping the server, inspect a repair against +the memory root's real SQLite boundary records: + +```bash +uv run --frozen --no-sync python examples/memtrace/repair_construction.py \ + /path/to/experiment/everos_root +``` + +Add `--apply` to merge only repeated exact boundaries, retain their derived +memory edges, and connect the buffer version observed at the first boundary. +Real membership changes are preserved. Original graph files are backed up in +`experiment/construction_before_fix/memtrace/`; `construction_repair.json` +records changes and before/after hashes. Markdown and indexes are read-only. +Rerun the experiment's renderer to refresh its display copies and images. diff --git a/docs/memtrace-instrumentation.zh-CN.md b/docs/memtrace-instrumentation.zh-CN.md new file mode 100644 index 000000000..d7f64750b --- /dev/null +++ b/docs/memtrace-instrumentation.zh-CN.md @@ -0,0 +1,162 @@ +# EverOS MemTrace:开发者接入指南 + +MemTrace 是我们ZJUNLP实验室的工作,它相当于是为 EverOS 增加了一条可回看的“记忆流水线”。这个pipeline把一次对话从写入、整理、保存,到下一次检索和回答的关键数据串起来,并导出为可查看、可合并、可供归因工具消费的执行图。 + +本文面向需要开发、调试或评估 EverOS 的工程师, 本文内容包括: + +1. 这个功能能为 EverOS 带来什么; +2. 如何在本地打开它并找到输出; +3. 如果新增一条记忆路径或检索阶段,应该在哪里补记录。 + +## 接入EverOS的好处 + +EverOS 的记忆不是一次简单的“写入数据库”。一条用户消息可能先进入缓冲区,经边界判断后切成 memcell,再抽取为 Episode,落到 Markdown,最后在另一个请求中被检索出来。只看最终的 Markdown 或搜索结果,很难判断错误发生在哪一步。这也是MemTrace的核心功能。 + +MemTrace 把这些步骤放在同一条可追溯链上: + +```mermaid +flowchart LR + M[用户消息] --> B[消息缓冲区] + B --> D[边界判断] + D --> C[memcell] + C --> E[记忆抽取] + E --> P[Markdown 记忆] + P --> R[检索候选] + R --> H[命中与上下文] + H --> A[回答与评测(可选)] +``` + +这对 EverOS 的实际价值是: + +| 价值 | 对开发者意味着什么 | +| --- | --- | +| 更快定位记忆问题 | 可以区分“没有正确抽取”“被更新或删除”“没有召回”和“回答阶段使用错误上下文”,减少只看日志猜原因的时间。 | +| 让 Markdown 记忆可解释 | EverOS 的 Markdown 仍是事实来源;执行图补充“这条记忆如何产生、何时被引用”的来路,不替代 Markdown、SQLite 或 LanceDB。 | +| 支持质量回归 | 同一份图可以复盘失败问答、比较候选池变化,并交给 MemTrace 做错误归因。 | +| 降低插桩成本 | 业务层只提交真实的输入、输出和依赖;`smartcomment` 负责图、版本和导出,开发者不需要自己维护一套 trace JSON。 | +| 对线上路径友好 | 这是可选能力。没有 `smartcomment` 或关闭开关时,hook 退化为 no-op;采集失败也不会让记忆请求失败。 | + +## 先用起来 + +### 安装与开关 + +在 EverOS checkout 中安装可选依赖: + +```bash +uv sync --frozen --extra memtrace +``` + +MemTrace 默认开启。需要临时关闭时: + +```bash +export EVEROS_MEMTRACE_ENABLED=0 +``` + +图默认写到 `/memtrace/`。调试时可以指定一个独立目录: + +```bash +export EVEROS_MEMTRACE_ENABLED=1 +export EVEROS_MEMTRACE_DIR=/tmp/everos-memtrace +``` + +启动 EverOS,正常执行几次 `/memory/add`、`/memory/flush` 和 `/memory/search`。请求结束后,在上述目录中可以看到一个或多个 `.json` 图文件。服务关闭时,API lifespan 会再做一次同步,补上最后的 Markdown 变化。 + +### 用图做一次本地检查 + +这个可以先把图导出为 PNG,快速确认消息、记忆和检索结果是否连得起来: + +```bash +.venv/bin/python examples/memtrace/export_png.py \ + /tmp/everos-memtrace --out /tmp/everos-memtrace-png +``` + +默认每个 query 输出一张图,并只展示候选池的前两项;源 JSON 不会被修改。需要展示完整候选池时,加 `--top-k 0`;需要一张总图时,加 `--combined`。 + +### 把失败问答交给归因工具 + +`/memory/search` 只负责返回记忆,不负责生成最终答案。因此回答和评测需要由调用方补录。HTTP 实验通常在服务停止后执行: + +```bash +.venv/bin/python examples/memtrace/inject_qa.py \ + --graph-dir /tmp/everos-memtrace \ + --qa-results /path/to/qa_results.json + +.venv/bin/python examples/memtrace/merge.py /tmp/everos-memtrace \ + --output /tmp/everos-merged.json + +.venv/bin/python examples/memtrace/attribute.py \ + --graph /tmp/everos-merged.json --list-cases +``` + +`inject_qa.py` 会把 prompt(可选)、实际回答、参考答案和 judge 结果接到对应的 query 上。`merge.py` 用于合并构建和检索图;不要把合并结果写回输入目录。更多归因参数见 [examples/memtrace/README.md](../examples/memtrace/README.md)。 + +## 当前会记录什么 + +记录点集中在用户真正会关心的业务边界,而不是把每个函数调用都写进图里。 + +| 场景 | 图中会看到什么 | 适合回答的问题 | +| --- | --- | --- | +| `/memory/add` | 输入消息、缓冲区变化、边界结果、memcell、Episode 抽取结果、成功落盘的记忆 | 这条消息有没有被接收、切分和抽取? | +| `/memory/flush` | 剩余缓冲区、最终边界结果、flush 请求,即使本次没有新文件也会留下请求记录 | 为什么这批消息仍未形成记忆? | +| `/memory/search` | query、稀疏/稠密/融合等候选池、实际命中、检索上下文、未处理消息分支 | 记忆是没有生成,还是没有被召回?哪一步改变了候选? | +| Markdown 观察 | Episode、atomic fact、foresight、agent case、profile、skill 和 knowledge 文件的新增、修改、删除 | 磁盘上的事实何时变化? | +| 请求失败 | add、flush、search 的失败状态和有限的错误信息;搜索失败会保留已收集的候选阶段 | 请求失败前已经走到哪一步? | +| 回答与评测(可选) | prediction、参考答案、judge response,以及回答实际使用的上下文 | 错误是检索问题,还是回答阶段的问题? | + +构建和搜索图按 `app_id`、`project_id`、owner、session bucket 分区。相同业务对象使用稳定 identity,内容变化会形成新版本,因此可以看到一条记忆的演变,而不是只有最后状态。 + +## 怎么读一张图 + +不需要先掌握 smartcomment 的内部 schema。: + +1. **先找 query 或输入消息。** 它们是这次请求的起点。 +2. **沿着箭头看业务链。** 常见路径是“消息 → buffer → boundary result → memcell → 抽取结果 → Markdown 记忆 → 候选池 → hit → context”。 +3. **再看版本和来源。** `construction_event` 表示在业务步骤中现场捕获;`file_diff` 表示请求结束时扫描 Markdown 发现的变化,只能证明“观察到变化”,不能证明是哪一个请求造成的。 +4. **最后看回答链。** 只有调用方补录了实际回答和评测,图中才会出现 prediction、golden answers 和 judge response。 + +候选池是阶段快照,默认只保存最多 50 个 ID、分数和来源,同时保存 `total_count` 与 `truncated`。所以“图里没有某个候选”不等于“它从未被召回”。命中(hit)是本次 query 的结果;持久记忆是它引用的历史版本,两者不要混为一谈。 + +空结果、跳过、失败和没有采集到是不同情况。例如: + +- `deferred` 表示消息先进入缓冲区,暂不做边界判断和抽取; +- `no_split` 表示本次没有切出 memcell,仍应有结果节点; +- `status: error` 表示请求失败,业务异常仍会继续抛出; +- 没有节点可能只是路径尚未接入,不能直接当成“没有执行”。 + +## smartcomment 快速介绍 + +`smartcomment` 是我们开发的一个执行图记录器,不会自动拦截 EverOS 的所有函数、文件写入或 LLM 调用(相当于是插桩)。EverOS 在真实业务边界显式声明: + +- **变量**:消息、buffer、记忆、候选池、context 等业务数据; +- **操作**:add、boundary detection、extraction、retrieval、update、deletion 等业务步骤; +- **依赖边**:说明哪个输入产生了哪个输出; +- **版本**:说明同一条记忆或 buffer 如何变化。 + +图最终以 smartcomment 的 JSON 格式导出,既可以用 `ExecNetwork.import_graph()` 读取,也可以交给 MemTrace 的图探索和归因工具。EverOS 的 `MemTraceTracker` 负责请求分组、Markdown 扫描、重启恢复、文件锁和导出;业务代码只需要通过 tracker 或 trace collector 提交数据。 + +## 运行成本与边界 + +- **它不是零成本日志。** add、flush、search 请求结束时会扫描 memory root,并对脏图做序列化;启用后会增加一定延迟和磁盘占用。 +- **它不是完整录屏。** 当前不会自动保存所有 LLM prompt、原始 response、每轮 retry、OME 内部演化、LanceDB/embedding 的每个索引步骤,也不会自动记录回答模型。 +- **文件差分是后验观察。** 两次扫描之间发生又被覆盖的中间状态可能不可见;`file_diff` 不能单独证明因果关系。 +- **多进程需要规划写入方式。** 文件锁可以避免导出文件写坏,但不会合并不同 worker 的内存图。生产环境请选择单写者,或为每个 worker 指定独立的 `EVEROS_MEMTRACE_DIR`。 +- **图可能包含正文。** 消息、记忆和回答内容可能出现在 JSON 中。共享图或提交 issue 前,请按数据敏感级别设置目录权限并做好脱敏。 + +如果项目只需要 EverOS 的正常记忆能力,可以不安装 `memtrace` extra,核心路径照常运行。安装并启用它的主要收益,是在出现“记忆为什么不对”或“回答为什么错”时,多一条可以复盘的证据链。 + +## 验证改动 + +在 EverOS checkout 中运行与本功能最相关的测试: + +```bash +.venv/bin/python -m pytest -q \ + tests/unit/test_service/test_memorize_memtrace_hook.py \ + tests/unit/test_memory/test_extract/test_trace.py \ + tests/unit/test_memory/test_search/test_trace.py \ + tests/unit/test_infra/test_memtrace_no_split.py \ + tests/unit/test_infra/test_memtrace_boundary_decision.py \ + tests/unit/test_infra/test_memtrace_buffer_lifecycle.py \ + tests/unit/test_infra/test_memtrace_regressions.py +``` + +新增插桩后,至少补充一条对应的成功、空结果或失败测试,并检查导出的 JSON 能被 `smartcomment.runtime.ExecNetwork.import_graph()` 重新读取。更完整的图归因示例见 [memtrace-graphs.md](memtrace-graphs.md),历史审阅记录见 [memtrace-attribution-review.zh-CN.md](memtrace-attribution-review.zh-CN.md)。 diff --git a/docs/openapi.json b/docs/openapi.json index 2cb1da239..a777c251f 100644 --- a/docs/openapi.json +++ b/docs/openapi.json @@ -3,7 +3,7 @@ "info": { "title": "everos", "description": "md-first memory extraction framework", - "version": "1.7.0" + "version": "1.7.1" }, "paths": { "/health": { diff --git a/examples/memtrace/README.md b/examples/memtrace/README.md new file mode 100644 index 000000000..8ca6ebceb --- /dev/null +++ b/examples/memtrace/README.md @@ -0,0 +1,313 @@ +# MemTrace graph attribution for EverOS + +This example ports the **core MemTrace graph-attribution algorithm** to an +independent package under `graphtrace/`. It consumes existing SmartComment +execution graphs and diagnoses a failed question-answering case. It does not +require a running EverOS server or change the server's instrumentation. + +MemTrace is an LLM-driven graph exploration algorithm. BM25 selects candidate +source messages; the model uses graph tools to inspect operations and follows +the evidence through memory construction, preservation, retrieval and response +generation. The goal is the **earliest locally faulty, decisive operation**: +correcting that operation, with earlier operations unchanged and ideal downstream +behavior, should prevent the wrong answer. + +## Setup + +Run commands from the EverOS checkout. Use its existing environment, or install +the locked environment with the existing tracing extra: + +```bash +uv sync --frozen --extra memtrace +``` + +The runtime uses `smartcomment`, `openai`, Pydantic and the standard library. +It does not import the sibling MemTrace checkout, install AgentScope, or require +`rank_bm25`, `networkx`, an embedding endpoint, or a vector database. + +## List and attribute failed cases + +For newly collected EverOS traces, stop the server, inject the QA records, and +merge construction and search exports with the tenant-aware merger: + +```bash +.venv/bin/python examples/memtrace/inject_qa.py \ + --graph-dir /path/to/memtrace --qa-results /path/to/qa_results.json +.venv/bin/python examples/memtrace/merge.py /path/to/memtrace \ + --output /path/to/merged.json +.venv/bin/python examples/memtrace/attribute.py \ + --graph /path/to/merged.json --list-cases +``` + +The merger namespaces identities by app/project and rejects conflicting values +for the same immutable revision. Search exports preserve canonical construction +revision numbers, even when their first observed revision is `@2`. Merge both +construction and search graphs to retain the revision's producing operations. +Older exports with conflicting local versions need a fresh replay; the merger +does not guess which content was used. Graphs flagged with unresolved merge +conflicts are rejected by the attribution CLI. + +The existing local LoCoMo trace can be inspected without credentials: + +```bash +.venv/bin/python examples/memtrace/attribute.py \ + --graph ../MemTrace/outputs/everos_locomo_adapt/merged/merged.json \ + --list-cases +``` + +Run one case with the already-existing MemTrace credential configuration: + +```bash +.venv/bin/python examples/memtrace/attribute.py \ + --graph ../MemTrace/outputs/everos_locomo_adapt/merged/merged.json \ + --query-id query-caroline-cfa8035aae4845cda7729e6dc4e00877 \ + --api-config ../MemTrace/input_files/api_config.json \ + --model qwen3.8-flash \ + --output ../MemTrace/outputs/everos_graphtrace_core/caroline_qwen3_8_flash.json +``` + +`--query-id` accepts the exact versioned node identifier, the unversioned full +name, or the query identity shown above. Without it, one case is selected in +judge-operation creation order. The input graph is never rewritten. The output +must differ from the input graph and credential file. + +Alternatively, omit `--api-config` and set `OPENAI_API_KEY`, optionally +`OPENAI_BASE_URL` and `OPENAI_MODEL`. A configuration file contains paired, +nonempty `api_keys` and `base_urls` lists; this single-case runner uses the first +pair. Credentials are only given to the client and never included in reports. +Provider exception text is also excluded from reports. + +In the local workspace, `all_proxy` points to a SOCKS proxy but `socksio` is not +installed. If the OpenAI client fails at startup with that import error, prefix +the command with `env -u all_proxy`. This retains the configured HTTP/HTTPS +proxies; no package installation is necessary. + +### Defaults and limits + +| Option | Default | Meaning | +| --- | --- | --- | +| `--model` | `qwen3.8-flash` | Model, unless `OPENAI_MODEL` is set | +| `--max-iters` | `200` | Maximum model requests per case | +| `--max-trace-nodes` | `16` | Queued variables, excluding the active node | +| `--num-starting-points` | `8` | BM25 candidate messages, capped to leave query space | +| `--context-chars` | `100000` | Serialized messages and tools character budget | + +Tool pages default to 16,000 characters. Offsets +are one-based character positions. A truncated result gives the next offset. +Previews, value reads and exploration history all paginate, including previews +that omit values. The agent reduces the page cap to fit its character budget and +the number of tool calls in the current batch. Continue through pages to inspect +a large operation, or use previews followed by regex value searches. + +The character budget is a lightweight estimate, not the provider's token count. +Oldest complete assistant/tool-response groups are removed when necessary. +System instructions, the case, the fresh notebook hint and the newest turn are +retained. If these alone exceed the budget, the run fails explicitly instead +of breaking tool-call pairing. The transcript retains all removed turns. + +## Workflow and tools + +1. Import the graph and inspect `judge_answer_*` evaluation operations. + Decode the query, prediction, reference-answer list and judge snapshots from + the same subgraph. Only complete cases with score `0.0` are selected. + Malformed or mismatched QA chains produce diagnostics. Native `llm-judge` + chains with a `judge_score` node are also supported. +2. Rank raw `message` content by BM25Okapi using question plus reference answer. + Initialize with the query and candidate messages. These are **pseudo evidence**, + not human-labeled source evidence. If there are no message candidates, initialize + with a synthetic root and let the model select graph roots. +3. Before each model request, provide the current active node, ordered frontier + and the last four completed outcomes with bounded summaries. Full history + stays available through a paginated tool. Execute tool calls serially, even if + the model emits several calls in one response. Tool errors let the model correct + invalid actions. +4. Follow locally correct operations downstream. Inspect input/produced variables, + direct successors, final output variables, versioned values and observation + ordering. Finish graph exploration, then submit one structured attribution. + +| Tool | Purpose | +| --- | --- | +| `initialize_execution_graph` | Initialize selected nodes or a synthetic root; restart after finishing | +| `explore_graph_trace_node` | Inspect operations producing or consuming the active/earliest variable | +| `update_to_explore_nodes` | Add/delete queued nodes; record discovery provenance | +| `view_node_value` | Read a value or search regex matches with character pagination | +| `finish_node_exploration` | Archive the active node and its findings | +| `finish_graph_exploration` | Archive graph state, or stop because evidence is insufficient | +| `view_exploration_history` | Read completed exploration records | +| `submit_attribution` | Validate and return one inspected operation's fault | + +Queued nodes use `(created_at, full_node_id)` ordering; adding an older node does +not displace the active node. Recorded operations use unique `event_seq` values; +offline QA operations without sequences follow those observations. Duplicate +sequences trigger timestamp ordering instead. Sequence values from independent +processes do not establish a reliable global execution order. File-diff timestamps +are observation times, not actual extraction/update execution times. + +An operation's structured rendering must have been read, possibly across pages, +before submission. The reason must cite a relevant versioned node whose value +was read. Judge and reference-injection operations are excluded. Exploration and +source-message selection respect the failed query's tenant and exclude later +construction and other requests' retrieval/answer operations. +The result schema is the original `{error_type, op_id, reason}`, with these types: +`ExtractionError`, `UpdateError`, `DeletionError`, `RetrievalError`, `ResponseError`. +Schema and graph membership checks do not establish that an LLM diagnosis is correct. + +When critical source evidence is absent, the model can call +`finish_graph_exploration(insufficient_evidence=True, outcome=...)`. This returns +an `InsufficientEvidence` failure with no fabricated attribution. API failures, +context overflow and iteration exhaustion likewise retain the trace and state. + +Search `context` and actual `answer_context` are separate snapshots. The latter +must be supplied by the caller; LoCoMo QA records its exact episode-only context. +An omitted answer context stays `null` and cannot establish a `ResponseError`. +File-diff operations carry `observation_only=true` and cannot be submitted as +executed faults. Boundary and episode extraction attempts/results record actual +values, including empty extractor results. Background OME updates/deletions are +still file observations; the tracer cannot reconstruct intermediate states that +never reached a scan. In that situation, stop with `InsufficientEvidence`. + +## Reports and Python API + +The output contains `status`, decoded `case`, `graph_id`, `model`, runtime `config`, +`pseudo_evidence_nodes`, `attribution`, `failure`, `iterations`, token `usage`, +`inspected_operations`, `final_state`, `diagnostics` and the complete `transcript`. +The transcript includes initialization, fresh hints, model/tool messages and +context-trimming events. Reports contain conversation data and should stay in +local output directories. + +Exit codes: `0` for a valid attribution or successful case listing, `1` for a run +without attribution (including insufficient evidence), and `2` for invalid input +or setup. An insufficient-evidence result is not an accuracy score. + +```python +from examples.memtrace.graphtrace import ( + AttributionConfig, + OpenAIChatProvider, + attribute, + collect_failed_queries, +) + +cases, diagnostics = collect_failed_queries(graph) +report = await attribute( + graph, + cases[0], + OpenAIChatProvider(async_openai_client, "qwen3.8-flash"), + AttributionConfig(max_iters=200), +) +``` + +The public facade also exports `FailedQueryCase`, `GraphTraceState`, +`GraphTraceNotebook`, `AttributionResult` and the injectable `ChatProvider` protocol. +The script and module entry points both work: +`python examples/memtrace/attribute.py` or +`python -m examples.memtrace.attribute`. + +## Verification and fidelity + +```bash +.venv/bin/python -m pytest tests/unit/test_memtrace_example -q +.venv/bin/ruff check examples/memtrace/graphtrace \ + examples/memtrace/attribute.py tests/unit/test_memtrace_example +.venv/bin/ruff format --check examples/memtrace/graphtrace \ + examples/memtrace/attribute.py tests/unit/test_memtrace_example +.venv/bin/python -m compileall -q examples/memtrace/graphtrace \ + examples/memtrace/attribute.py +``` + +Offline tests use invented graphs and scripted model responses. The end-to-end +test verifies a known retrieval failure: extraction preserves `Friday` in a memory +entry but retrieval produces unrelated context. It also verifies that a nonexistent +operation submission is rejected and corrected. Other tests cover frontier ordering, +capacity, restarts, graph immutability, pagination/regex search, QA parsing, source +ranking, complete tool-call pairs during trimming, and explicit failure paths. + +This port preserves the attribution instructions, seven-tool exploration workflow, +versioned-node state and per-request hints. Differences from the original: + +- OpenAI function calling replaces AgentScope's agent and final-response tool. +- Standard-library mappings replace sorted containers while keeping frontier order. +- BM25 uses decoded EverOS message content rather than encoded snapshot metadata. + It retains the original English tokenizer and BM25Okapi parameters. +- Dense/hybrid evidence retrieval and LLM summary compression are deferred. +- Deterministic context pruning replaces summary compression; default page sizes + are smaller. A fresh hint replaces accumulated hint messages. +- EverOS QA decoding, observation ordering, submission evidence checks and the + insufficient-evidence stop are additional integration behavior. + +The attribution instructions are adapted from +`MemTrace/toolkits/memtrace_utils.py`; notebook/state behavior follows +`MemTrace/graphtrace/`. The original MIT notice is preserved in +[`graphtrace/MEMTRACE_LICENSE.txt`](graphtrace/MEMTRACE_LICENSE.txt). + +## Existing tracing helpers + +The existing scripts remain separate from attribution: + +- `filetrace_locomo_drive.py`: replay LoCoMo against a running EverOS server; + `--qa` also answers and judges queries. +- `inject_qa.py`: append an out-of-process QA chain to existing exports. +- `merge.py`: merge tenant-scoped exports and reject revision conflicts. +- `export_png.py`: render exported graphs. + +When collecting a new attribution case, replay the conversation containing the +actual source evidence before querying and injecting QA. A reference answer +about a later, unreplayed session is not evidence of an extraction failure. + +Inject QA before merging, with the server stopped. Records identify a search by +`user_id` and `request_id`; repeated ids require `query_full_node_id`, and ambiguous +tenants require `app_id`/`project_id`. Missing or ambiguous matches are skipped. +Reinjecting an identical record is idempotent, including answer-only records. +Changed records retain their separate evaluation operations. Use a single trace +writer or separate per-worker directories: a file lock does not merge workers' +in-memory graphs. + +## Recorded verification (2026-10-03) + +The 35 offline tests passed; branch-aware coverage over the new example code was +86.79%. Ruff checks, formatting checks and syntax compilation passed. + +A real `qwen3.8-flash` run on the invented, known-fault retrieval graph completed +in 12 model requests. It attributed `RetrievalError` to `retrieve-op`, correctly +distinguishing the preserved source fact from the missing retrieval context. +Reported usage was 58,369 input and 1,669 output tokens (60,038 total). +The local input and full tool transcript are stored under +`../MemTrace/outputs/everos_graphtrace_core/` as +`synthetic_retrieval_graph.json` and `synthetic_retrieval_qwen3_8_flash.json`. +This checks the model/tool integration on invented data, not benchmark accuracy. + +To generate the same invented input from the offline test fixture and run it: + +```bash +.venv/bin/python - <<'PY' +import json +from pathlib import Path +from tests.unit.test_memtrace_example.conftest import make_graph + +Path('/tmp/memtrace_synthetic.json').write_text( + json.dumps(make_graph().export_graph(), indent=2) +) +PY + +.venv/bin/python examples/memtrace/attribute.py \ + --graph /tmp/memtrace_synthetic.json \ + --api-config ../MemTrace/input_files/api_config.json \ + --model qwen3.8-flash --max-iters 40 \ + --output /tmp/memtrace_synthetic_report.json +``` + +The existing LoCoMo merged graph contains two failed QA cases and no human +operation-attribution labels. Its recorded source messages end on July 3, 2023, +while Caroline's reference answer concerns the Friday before July 15. The raw +messages mention researching adoption agencies but do not establish the meeting +date. This graph cannot support a confident earliest-fault diagnosis for that +question; source absence alone does not establish an extraction or retrieval error. + +The `qwen3.8-flash` LoCoMo run stopped at request 79 with `APIConnectionError`, +after 78 complete model/tool turns. The partial report retains the exploration +state and 21 context-pruning events in `caroline_qwen3_8_flash.json`. A bounded +continuation replayed the saved model responses through the read-only tools +without repeating paid requests; its first new model request was rejected with +HTTP 403 (`PermissionDeniedError`). That separate result is preserved in +`caroline_qwen3_8_flash_resumed.json`. Neither report contains an attribution. +This run validates import, QA selection, exploration, pruning and failure +reporting, but does not establish a LoCoMo fault or attribution accuracy. diff --git a/examples/memtrace/attribute.py b/examples/memtrace/attribute.py new file mode 100644 index 000000000..bee4da815 --- /dev/null +++ b/examples/memtrace/attribute.py @@ -0,0 +1,170 @@ +"""Run core MemTrace graph attribution on an exported EverOS QA graph.""" + +from __future__ import annotations + +import argparse +import asyncio +import json +import os +import sys +from pathlib import Path +from typing import Any + +from openai import AsyncOpenAI +from smartcomment.runtime import ExecNetwork + +if __package__: + from .graphtrace import ( + AttributionConfig, + OpenAIChatProvider, + attribute, + collect_failed_queries, + ) + from .graphtrace.cases import decode_snapshot +else: + from graphtrace import ( + AttributionConfig, + OpenAIChatProvider, + attribute, + collect_failed_queries, + ) + from graphtrace.cases import decode_snapshot + + +def load_credentials(path: Path | None) -> tuple[str, str | None]: + """Read one credential pair without copying secrets into the report.""" + if path is not None: + config = json.loads(path.read_text(encoding="utf-8")) + keys, urls = config.get("api_keys"), config.get("base_urls") + if not isinstance(keys, list) or not isinstance(urls, list): + raise ValueError("api_config must contain api_keys and base_urls lists.") + if not keys or len(keys) != len(urls): + raise ValueError( + "Credential lists must be nonempty and have equal lengths." + ) + key, url = keys[0], urls[0] + else: + key = os.environ.get("OPENAI_API_KEY") + url = os.environ.get("OPENAI_BASE_URL") + if not isinstance(key, str) or not key.strip(): + raise ValueError("Set OPENAI_API_KEY or provide --api-config.") + if url is not None and (not isinstance(url, str) or not url.strip()): + raise ValueError("The base URL must be a nonempty string.") + return key, url + + +async def _run( + graph: ExecNetwork, + case: Any, + args: argparse.Namespace, + config: AttributionConfig, + key: str, + url: str | None, +) -> dict[str, Any]: + async with AsyncOpenAI( + api_key=key, base_url=url, timeout=120, max_retries=1 + ) as client: + report = await attribute( + graph, case, OpenAIChatProvider(client, args.model), config + ) + report["model"] = args.model + return report + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--graph", type=Path, required=True) + parser.add_argument("--list-cases", action="store_true") + parser.add_argument("--query-id", help="Exact full_node_id or query identity.") + parser.add_argument("--api-config", type=Path) + parser.add_argument("--model", default=os.getenv("OPENAI_MODEL", "qwen3.8-flash")) + parser.add_argument("--max-iters", type=int, default=200) + parser.add_argument("--max-trace-nodes", type=int, default=16) + parser.add_argument("--num-starting-points", type=int, default=8) + parser.add_argument("--context-chars", type=int, default=100_000) + parser.add_argument("--output", type=Path) + args = parser.parse_args() + try: + payload = json.loads(args.graph.read_text(encoding="utf-8")) + if payload.get("metadata", {}).get("merge_value_conflicts"): + print( + "The input graph has unresolved revision conflicts; " + "recollect traces and use the safe merger.", + file=sys.stderr, + ) + return 2 + graph = ExecNetwork.import_graph(payload) + cases, diagnostics = collect_failed_queries(graph) + for diagnostic in diagnostics: + print(diagnostic, file=sys.stderr) + if args.list_cases: + print(json.dumps([case.model_dump() for case in cases], indent=2)) + return 0 + if args.output is None: + parser.error("--output is required when running attribution.") + protected_paths = {args.graph.resolve()} + if args.api_config: + protected_paths.add(args.api_config.resolve()) + if args.output.resolve() in protected_paths: + parser.error("The report must not overwrite the graph or credential file.") + if args.query_id: + cases = [ + case + for case in cases + if args.query_id + in { + case.query_full_node_id, + case.query_full_node_id.rsplit("@", 1)[0], + case.query_full_node_id.rsplit("@", 1)[0].removeprefix("query:"), + _query_identity(graph, case.query_full_node_id), + } + ] + if len(cases) != 1: + parser.error("--query-id must match exactly one complete failed case.") + if not cases: + parser.error("No complete failed QA cases found in this graph.") + config = AttributionConfig( + max_iters=args.max_iters, + max_trace_nodes=args.max_trace_nodes, + num_starting_points=args.num_starting_points, + context_chars=args.context_chars, + ) + key, url = load_credentials(args.api_config) + case = cases[0] + print(f"Attributing {case.query_full_node_id} using {args.model}.", flush=True) + report = asyncio.run(_run(graph, case, args, config, key, url)) + report["diagnostics"] = diagnostics + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2), encoding="utf-8") + except (OSError, TypeError, ValueError, KeyError) as exc: + # Credential parsing exceptions must not print the supplied file contents. + print(f"Cannot run attribution: {type(exc).__name__}.", file=sys.stderr) + return 2 + print( + json.dumps( + { + "status": report["status"], + "attribution": report["attribution"], + "failure": report["failure"], + "iterations": report["iterations"], + "usage": report["usage"], + "report": str(args.output), + }, + indent=2, + ) + ) + return 0 if report["status"] == "success" else 1 + + +def _query_identity(graph: ExecNetwork, full_node_id: str) -> str: + node = graph.get_variable(full_node_id) + snapshot = decode_snapshot(node.value) + if isinstance(snapshot, dict) and snapshot.get("id"): + return str(snapshot["id"]) + return node.full_name.removeprefix("query:").removeprefix( + node.metadata.get("tenant_scope", "") + ) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/examples/memtrace/export_png.py b/examples/memtrace/export_png.py new file mode 100644 index 000000000..0e58cbcf5 --- /dev/null +++ b/examples/memtrace/export_png.py @@ -0,0 +1,321 @@ +"""Export MemTrace execution graphs (smartcomment JSON) to readable PNGs. + +The default presentation is intentionally stable and report-friendly: white +nodes with black borders/edges, one image per query, and only the first two +items from each candidate pool. The source JSON is never modified. + +Usage: + python examples/memtrace/export_png.py [--out DIR] + python examples/memtrace/export_png.py --top-k 5 + python examples/memtrace/export_png.py --combined +""" + +from __future__ import annotations + +import argparse +import copy +import json +import re +import subprocess +import sys +import tempfile +from pathlib import Path +from typing import Any + +from smartcomment.runtime import ExecNetwork + +_ID_VERSION = re.compile(r"^(?P.+)@(?P\d+)$") +_COLOUR = re.compile(r'(?PBGCOLOR|color|fontcolor)="#[0-9A-Fa-f]{6}"') + + +def _node_full_id(node: dict[str, Any]) -> str: + """Return the smartcomment identity used by graph edges.""" + return str(node.get("full_node_id") or node.get("node_id") or "") + + +def _base_id(full_id: str) -> str: + """Remove the version suffix and optional class-name prefix.""" + match = _ID_VERSION.match(full_id) + value = match.group("base") if match else full_id + return value.split(":", 1)[-1] + + +def _snapshot(node: dict[str, Any]) -> dict[str, Any]: + try: + value = json.loads(str(node.get("value", ""))) + except (ValueError, TypeError): + return {} + return value if isinstance(value, dict) else {} + + +def _belongs_to_query(node: dict[str, Any], query: dict[str, Any]) -> bool: + scope = query.get("metadata", {}).get("tenant_scope", "") + if node.get("metadata", {}).get("tenant_scope", "") != scope: + return False + identity = _snapshot(query).get("id") or str(query["name"]).removeprefix(scope) + return _snapshot(node).get("query_id") == identity or str( + node.get("name", "") + ).removeprefix(scope).endswith(identity) + + +def _pool_info(node: dict[str, Any], top_k: int) -> tuple[list[str], bool]: + """Truncate a candidate-pool value and return (kept ids, is_pool).""" + try: + value = json.loads(str(node.get("value", ""))) + except (TypeError, json.JSONDecodeError): + return [], False + if not isinstance(value, dict) or not isinstance(value.get("ids"), list): + return [], False + + original_ids = [str(item) for item in value["ids"]] + kept = original_ids if top_k == 0 else original_ids[:top_k] + if top_k != 0: + original_count = int(value.get("total_count", len(original_ids))) + value["ids"] = kept + value["scores"] = list(value.get("scores", []))[: len(kept)] + value["sources"] = list(value.get("sources", []))[: len(kept)] + value["count"] = len(kept) + value["total_count"] = original_count + value["display_only_top_k"] = top_k + node["value"] = json.dumps(value, ensure_ascii=False, indent=2) + metadata = node.setdefault("metadata", {}) + metadata["display_only_top_k"] = top_k + metadata["total_count"] = original_count + return kept, True + + +def _display_payload( + payload: dict[str, Any], top_k: int, query_name: str | None = None +) -> dict[str, Any]: + """Copy a graph payload and optionally select one query subgraph.""" + result = copy.deepcopy(payload) + data = result.get("data", result) + nodes = data.get("nodes", []) + edges = data.get("edges", []) + candidate_ids = { + _node_full_id(node): _snapshot(node).get("memory_identity") + or _base_id(_node_full_id(node)).removeprefix( + node.get("metadata", {}).get("tenant_scope", "") + ) + for node in nodes + } + + pool_ids: dict[str, set[str]] = {} + pool_nodes: set[str] = set() + query_nodes: list[dict[str, Any]] = [] + for node in nodes: + full_id = _node_full_id(node) + kept, is_pool = _pool_info(node, top_k) + if is_pool: + pool_ids[full_id] = set(kept) + pool_nodes.add(full_id) + if node.get("class_name") == "query" or str(node.get("name", "")).startswith( + "query-" + ): + query_nodes.append(node) + + # Pool snapshots use raw entry ids; graph nodes are owner-prefixed. + # Normalize only the selection keys, leaving the observed lists intact. + for query in query_nodes: + try: + value = json.loads(str(query.get("value", ""))) + except (TypeError, json.JSONDecodeError): + continue + if not isinstance(value, dict): + continue + owner = value.get("user_id") or value.get("agent_id") + if not owner: + continue + prefix = f"{owner}_" + for node in nodes: + pool_id = _node_full_id(node) + if pool_id in pool_ids and _belongs_to_query(node, query): + pool_ids[pool_id] = { + eid if eid.startswith(prefix) else f"{prefix}{eid}" + for eid in pool_ids[pool_id] + } + + if query_name is None: + included = {_node_full_id(node) for node in nodes} + else: + selected_query = next( + (node for node in query_nodes if node.get("name") == query_name), None + ) + if selected_query is None: + raise ValueError(f"query node not found: {query_name}") + included = {_node_full_id(selected_query)} + for node in nodes: + if node.get("class_name") != "retrieval_hit" and _belongs_to_query( + node, selected_query + ): + included.add(_node_full_id(node)) + for pool_id, kept in pool_ids.items(): + pool_node = next( + (node for node in nodes if _node_full_id(node) == pool_id), None + ) + if pool_node is None or not _belongs_to_query(pool_node, selected_query): + continue + included.add(pool_id) + for edge in edges: + target = str(edge.get("target_full_node_id", "")) + if ( + edge.get("source_full_node_id") == pool_id + and candidate_ids.get(target) in kept + ): + included.add(target) + + contexts = { + _node_full_id(node) + for node in nodes + if node.get("class_name") == "context" and _node_full_id(node) in included + } + returned = { + str(edge.get("source_full_node_id", "")) + for edge in edges + if edge.get("target_full_node_id") in contexts + } + included.update(returned) + + kept_edges: list[dict[str, Any]] = [] + used_operations: set[str] = set() + for edge in edges: + source = str(edge.get("source_full_node_id", "")) + target = str(edge.get("target_full_node_id", "")) + if source not in included or target not in included: + continue + if ( + source in pool_ids + and target not in pool_nodes + and target not in contexts + and target not in returned + and candidate_ids.get(target) not in pool_ids[source] + ): + continue + kept_edges.append(edge) + op_id = edge.get("op_id") + if op_id: + used_operations.add(str(op_id)) + + data["nodes"] = [node for node in nodes if _node_full_id(node) in included] + data["edges"] = kept_edges + data["operations"] = [ + operation + for operation in data.get("operations", []) + if str(operation.get("op_id", "")) in used_operations + ] + return result + + +def _black_and_white(dot: str) -> str: + """Normalize smartcomment's category palette to the report style.""" + return _COLOUR.sub(lambda match: f'{match.group("key")}="#000000"', dot).replace( + 'BGCOLOR="#000000"', 'BGCOLOR="#FFFFFF"' + ) + + +def export_graph_to_png( + graph: ExecNetwork, png_path: Path, *, black_and_white: bool = True +) -> None: + """Render one execution graph to PNG with the graphviz ``dot`` binary.""" + dot_str = graph.visualize(backend="dot") + if black_and_white: + dot_str = _black_and_white(dot_str) + with tempfile.NamedTemporaryFile(mode="w", suffix=".dot", delete=False) as f: + f.write(dot_str) + dot_file = f.name + try: + subprocess.run( + ["dot", "-Tpng", dot_file, "-o", str(png_path)], + check=True, + capture_output=True, + ) + finally: + Path(dot_file).unlink(missing_ok=True) + + +def _query_names(payload: dict[str, Any]) -> list[str]: + data = payload.get("data", payload) + return [ + str(node["name"]) + for node in data.get("nodes", []) + if node.get("class_name") == "query" + or str(node.get("name", "")).startswith("query-") + ] + + +def _request_suffix(payload: dict[str, Any], query_name: str, index: int) -> str: + data = payload.get("data", payload) + for node in data.get("nodes", []): + if node.get("name") != query_name: + continue + try: + value = json.loads(str(node.get("value", ""))) + except (TypeError, json.JSONDecodeError): + break + request_id = value.get("request_id") if isinstance(value, dict) else None + if request_id: + return str(request_id)[:8] + return f"query-{index:02d}" + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("graph_dir", type=Path, help="Directory with *.json graphs") + parser.add_argument( + "--out", + type=Path, + default=None, + help="Output directory (default: /png)", + ) + parser.add_argument( + "--top-k", + type=int, + default=2, + help="Candidate items shown per pool (default: 2; 0 shows all)", + ) + parser.add_argument( + "--combined", + action="store_true", + help="Render each source JSON as one graph instead of one image per query", + ) + args = parser.parse_args() + if args.top_k < 0: + parser.error("--top-k must be non-negative") + + graph_dir: Path = args.graph_dir + if not graph_dir.is_dir(): + print(f"error: {graph_dir} is not a directory", file=sys.stderr) + return 1 + out_dir: Path = args.out or (graph_dir / "png") + out_dir.mkdir(parents=True, exist_ok=True) + json_files = sorted(graph_dir.glob("*.json")) + if not json_files: + print(f"no *.json files in {graph_dir}", file=sys.stderr) + return 1 + + print(f"exporting {len(json_files)} graphs to {out_dir}") + failed = 0 + for json_file in json_files: + try: + payload = json.loads(json_file.read_text()) + queries = _query_names(payload) + selections = [None] if args.combined or not queries else queries + for index, query_name in enumerate(selections, start=1): + display = _display_payload(payload, args.top_k, query_name) + graph = ExecNetwork.import_graph(display) + if query_name is None: + filename = f"{json_file.stem}.png" + else: + suffix = _request_suffix(payload, query_name, index) + filename = f"{json_file.stem}__search-{index:02d}-{suffix}.png" + png_path = out_dir / filename + export_graph_to_png(graph, png_path) + print(f" ok {json_file.name} -> {png_path.name}") + except Exception as exc: + failed += 1 + print(f" FAIL {json_file.name}: {exc}", file=sys.stderr) + return 1 if failed else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/examples/memtrace/filetrace_locomo_drive.py b/examples/memtrace/filetrace_locomo_drive.py new file mode 100644 index 000000000..394c440e3 --- /dev/null +++ b/examples/memtrace/filetrace_locomo_drive.py @@ -0,0 +1,366 @@ +"""Drive a running, memtrace-enabled EverOS server through part of the first +LoCoMo conversation (Caroline / Melanie), reconstructed from the MemTraceBench +mem0 split (``MemTraceBench/mem0/locomo_locomo-1.json``, whose message nodes +carry content/name/role/timestamp for all 419 messages across 19 session +dates). + +Sequence: + +1. add + flush the first ``--sessions`` sessions (default 5) +2. wait for the memory-root markdown tree to settle +3. run a few annotated queries via /memory/search (default: the first three + annotations, attributed to the user the question is about) +4. with ``--qa``: answer each query with an LLM (``EVEROS_QA_BASE_URL`` / + ``EVEROS_QA_API_KEY`` / ``EVEROS_QA_MODEL``), judge it against the bench + annotations, and write ``qa_results.json`` — feed that file to + ``inject_qa.py`` to stitch the answer/evaluation chain onto the graphs +5. one final light search so the file tracker observes any late background + (OME) writes + +Stdlib only — run against a server started with, e.g.:: + + EVEROS_MEMTRACE_ENABLED=1 everos server start --root --port 8016 + + python examples/memtrace/filetrace_locomo_drive.py \ + --base http://127.0.0.1:8016 \ + --graph ../MemTrace/MemTraceBench/mem0/locomo_locomo-1.json \ + --memory-root +""" + +from __future__ import annotations + +import argparse +import json +import os +import pathlib +import sys +import time +import urllib.request +from datetime import UTC, datetime + +_DEFAULT_GRAPH = str( + pathlib.Path(__file__).resolve().parents[3] + / "MemTrace/MemTraceBench/mem0/locomo_locomo-1.json" +) + +# (query, user_id) — the first annotated MemTraceBench queries for conv-1. +_DEFAULT_QUERIES = [ + ("What career path has Caroline decided to persue?", "caroline"), + ("When did Caroline go to the adoption meeting?", "caroline"), + ("When did Melanie go camping in July?", "melanie"), +] + +_META_SUFFIX = "\nBelow is this message's metadata:" + + +def _load_sessions(graph_path: str) -> list[tuple[str, list[dict]]]: + """Rebuild (date, messages) sessions from the bench graph's message nodes.""" + with open(graph_path, encoding="utf-8") as f: + graph_data = json.load(f) + nodes = graph_data["data"]["nodes"] + by_date: dict[str, list[dict]] = {} + for node in nodes: + if node.get("category") != "message": + continue + value = json.loads(node["value"]) + text = value["content"].split(_META_SUFFIX, 1)[0] + ts = datetime.fromisoformat(value["timestamp"]).replace(tzinfo=UTC) + by_date.setdefault(value["timestamp"][:10], []).append( + { + "role": "user", + "sender_id": value["name"].lower(), + "timestamp": int(ts.timestamp() * 1000), + "content": text, + } + ) + sessions = sorted(by_date.items()) + return [ + (f"locomo1-session-{i:02d}", sorted(msgs, key=lambda m: m["timestamp"])) + for i, (_, msgs) in enumerate(sessions, start=1) + ] + + +def _post( + base: str, path: str, body: dict, timeout: float = 600.0 +) -> tuple[dict, dict]: + req = urllib.request.Request( + base + path, + data=json.dumps(body).encode(), + headers={"content-type": "application/json"}, + method="POST", + ) + with urllib.request.urlopen(req, timeout=timeout) as resp: + return json.load(resp), dict(resp.headers) + + +def _header(headers: dict, name: str) -> str: + """Case-insensitive header lookup (uvicorn may lowercase header names).""" + for key, value in headers.items(): + if key.lower() == name.lower(): + return value + return "" + + +def _normalize_query(text: str) -> str: + """Normalize a query for annotation matching (bench quotes its queries).""" + return text.strip().strip("'\"").strip() + + +def _load_annotations(graph_path: str) -> dict[str, list[str]]: + """Map query text -> golden answers from the bench graph annotations.""" + with open(graph_path, encoding="utf-8") as f: + graph_data = json.load(f) + golden: dict[str, list[str]] = {} + for annotation in graph_data.get("data", {}).get("annotations") or []: + query = annotation.get("query") + answers = annotation.get("golden_answers") + if query and answers: + golden.setdefault(_normalize_query(query), list(answers)) + return golden + + +def _chat(prompt: str, *, timeout: float = 300.0) -> str: + """One OpenAI-compatible chat completion for the QA / judge calls. + + Endpoint credentials come from the environment (``EVEROS_QA_BASE_URL`` / + ``EVEROS_QA_API_KEY`` / ``EVEROS_QA_MODEL``); nothing is hardcoded. + """ + base_url = os.environ["EVEROS_QA_BASE_URL"].rstrip("/") + req = urllib.request.Request( + base_url + "/chat/completions", + data=json.dumps( + { + "model": os.environ["EVEROS_QA_MODEL"], + "messages": [{"role": "user", "content": prompt}], + } + ).encode(), + headers={ + "content-type": "application/json", + "authorization": f"Bearer {os.environ['EVEROS_QA_API_KEY']}", + }, + method="POST", + ) + with urllib.request.urlopen(req, timeout=timeout) as resp: + payload = json.load(resp) + return payload["choices"][0]["message"]["content"] + + +_ANSWER_TEMPLATE = ( + "Answer the question using only the retrieved memory context below.\n\n" + "Memory context:\n{context}\n\nQuestion: {query}\nAnswer:" +) + +_JUDGE_TEMPLATE = ( + "Question: {query}\nReference answers: {golden}\nPredicted answer: {answer}\n" + "Does the predicted answer match any reference answer? The first line must be " + "'VERDICT: 1' (correct) or 'VERDICT: 0' (incorrect), then one sentence why." +) + + +def _qa_record( + query: str, + user_id: str, + request_id: str, + data: dict, + golden: dict[str, list[str]], +) -> dict: + """Answer one searched query with an LLM and judge it (for injection).""" + episodes = data.get("episodes") or [] + context = ( + "\n".join( + f"- {ep.get('episode') or ep.get('subject') or ep.get('id')}" + for ep in episodes + ) + or "(no memories retrieved)" + ) + prompt = _ANSWER_TEMPLATE.format(context=context, query=query) + answer = _chat(prompt) + record = { + "user_id": user_id, + "request_id": request_id, + "query": query, + "prompt": prompt, + "answer_context": context, + "answer": answer, + "golden_answers": golden.get(_normalize_query(query), []), + } + if record["golden_answers"]: + verdict = _chat( + _JUDGE_TEMPLATE.format( + query=query, + golden="; ".join(record["golden_answers"]), + answer=answer, + ) + ) + record["judge_response"] = verdict + record["judge_score"] = 1.0 if "VERDICT: 1" in verdict else 0.0 + return record + + +def _wait_settled( + directory: pathlib.Path, + pattern: str, + *, + settle_checks: int = 5, + timeout: float = 1800.0, + label: str = "", +) -> None: + """Wait until the files matching `pattern` stop changing.""" + deadline = time.time() + timeout + last, stable = None, 0 + while time.time() < deadline: + state = ( + sorted( + (str(p), p.stat().st_mtime_ns, p.stat().st_size) + for p in directory.rglob(pattern) + ) + if directory.exists() + else [] + ) + if state == last: + stable += 1 + if state and stable >= settle_checks: + print( + f"[settle] {label or pattern}: stable at {len(state)} files", + flush=True, + ) + return + else: + stable = 0 + last = state + time.sleep(2) + print(f"[settle] {label or pattern}: timeout", flush=True) + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--base", default=os.environ.get("EVEROS_BASE", "http://127.0.0.1:8016") + ) + parser.add_argument( + "--graph", default=_DEFAULT_GRAPH, help="MemTraceBench conversation graph JSON" + ) + parser.add_argument( + "--sessions", type=int, default=5, help="Number of leading sessions to replay" + ) + parser.add_argument( + "--memory-root", default="", help="EverOS memory root (for settle waiting)" + ) + parser.add_argument( + "--queries", default="", help="Optional JSON file with [[query, user_id], ...]" + ) + parser.add_argument( + "--qa", + action="store_true", + help="Answer each query with an LLM and judge it against " + "the bench annotations (needs EVEROS_QA_BASE_URL / " + "EVEROS_QA_API_KEY / EVEROS_QA_MODEL)", + ) + parser.add_argument( + "--qa-out", + default="qa_results.json", + help="Where to write the QA records for inject_qa.py", + ) + args = parser.parse_args() + + if args.qa: + missing = [ + var + for var in ("EVEROS_QA_BASE_URL", "EVEROS_QA_API_KEY", "EVEROS_QA_MODEL") + if not os.environ.get(var) + ] + if missing: + raise SystemExit(f"--qa requires env vars: {', '.join(missing)}") + + sessions = _load_sessions(args.graph)[: args.sessions] + total = sum(len(msgs) for _, msgs in sessions) + print( + f"driving {args.base}: {len(sessions)} sessions, {total} messages", flush=True + ) + + for session_id, messages in sessions: + r, _ = _post( + args.base, + "/api/v2/memory/add", + {"session_id": session_id, "messages": messages}, + ) + print( + f"[add] {session_id} ({len(messages)} msgs) -> {r['data'].get('status')}", + flush=True, + ) + r, _ = _post( + args.base, + "/api/v2/memory/flush", + {"session_id": session_id, "messages": []}, + ) + print(f"[flush] {session_id} -> {r['data'].get('status')}", flush=True) + + if args.memory_root: + root = pathlib.Path(args.memory_root) + _wait_settled(root, "*.md", label="memory markdown") + else: + time.sleep(30) + + queries = _DEFAULT_QUERIES + if args.queries: + with open(args.queries, encoding="utf-8") as f: + queries = [tuple(item) for item in json.load(f)] + + golden = _load_annotations(args.graph) if args.qa else {} + qa_records = [] + for query, user_id in queries: + r, headers = _post( + args.base, + "/api/v2/memory/search", + {"user_id": user_id, "query": query, "method": "hybrid", "top_k": 5}, + ) + data = r.get("data", {}) + episodes = data.get("episodes") or [] + print(f"[search] {user_id} {query!r} -> episodes={len(episodes)}", flush=True) + for ep in episodes[:5]: + print( + f" hit id={ep.get('id')} score={ep.get('score', 0):.3f} " + f"subject={str(ep.get('subject'))[:60]}", + flush=True, + ) + if args.qa: + request_id = _header(headers, "X-Request-Id") + record = _qa_record(query, user_id, request_id, data, golden) + qa_records.append(record) + print( + f" [qa] request_id={request_id} " + f"judge_score={record.get('judge_score')}", + flush=True, + ) + + if args.qa: + out = pathlib.Path(args.qa_out) + out.write_text( + json.dumps({"records": qa_records}, ensure_ascii=False, indent=2), + encoding="utf-8", + ) + print(f"[qa] wrote {len(qa_records)} record(s) -> {out}", flush=True) + + # Final light request: lets the file tracker observe late background writes. + if args.memory_root: + _wait_settled( + pathlib.Path(args.memory_root), + "*.md", + label="memory markdown (post-search)", + ) + _post( + args.base, + "/api/v2/memory/search", + { + "user_id": queries[0][1], + "query": "final sync", + "method": "keyword", + "top_k": 1, + }, + ) + print("done", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/examples/memtrace/graphtrace/MEMTRACE_LICENSE.txt b/examples/memtrace/graphtrace/MEMTRACE_LICENSE.txt new file mode 100644 index 000000000..e213f97fd --- /dev/null +++ b/examples/memtrace/graphtrace/MEMTRACE_LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 ZJUNLP + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/examples/memtrace/graphtrace/__init__.py b/examples/memtrace/graphtrace/__init__.py new file mode 100644 index 000000000..2d1768371 --- /dev/null +++ b/examples/memtrace/graphtrace/__init__.py @@ -0,0 +1,28 @@ +"""Standalone graph-attribution example; imports no MemTrace source checkout. + +Use ``await attribute(graph, case, provider)`` with an exported ExecNetwork. +""" + +from __future__ import annotations + +from .agent import ChatProvider as ChatProvider +from .agent import OpenAIChatProvider as OpenAIChatProvider +from .agent import attribute as attribute +from .cases import collect_failed_queries as collect_failed_queries +from .models import AttributionConfig as AttributionConfig +from .models import AttributionResult as AttributionResult +from .models import FailedQueryCase as FailedQueryCase +from .models import GraphTraceState as GraphTraceState +from .notebook import GraphTraceNotebook as GraphTraceNotebook + +__all__ = [ + "AttributionConfig", + "AttributionResult", + "ChatProvider", + "FailedQueryCase", + "GraphTraceNotebook", + "GraphTraceState", + "OpenAIChatProvider", + "attribute", + "collect_failed_queries", +] diff --git a/examples/memtrace/graphtrace/agent.py b/examples/memtrace/graphtrace/agent.py new file mode 100644 index 000000000..b6aeb4928 --- /dev/null +++ b/examples/memtrace/graphtrace/agent.py @@ -0,0 +1,339 @@ +"""Bounded, serial tool-calling attribution with a complete audit transcript.""" + +from __future__ import annotations + +import asyncio +import json +from typing import TYPE_CHECKING, Any, Protocol + +from .cases import decode_snapshot +from .models import AttributionConfig, AttributionResult +from .notebook import GraphTraceNotebook, graph_tools +from .prompts import ATTRIBUTION_INSTRUCTIONS, EVEROS_PRIOR, TOOL_INSTRUCTIONS +from .retrieval import retrieve_starting_nodes + +if TYPE_CHECKING: + from openai import AsyncOpenAI + from smartcomment.runtime import ExecNetwork + + from .models import FailedQueryCase + + +class ChatProvider(Protocol): + """Small injectable model boundary; tests use scripted responses.""" + + async def complete( + self, messages: list[dict[str, Any]], tools: list[dict[str, Any]] + ) -> dict[str, Any]: + """Return a message and optional integer token usage.""" + ... + + +class OpenAIChatProvider: + """Use an already-configured OpenAI-compatible async client.""" + + def __init__(self, client: AsyncOpenAI, model: str) -> None: + self.client = client + self.model = model + + async def complete( + self, messages: list[dict[str, Any]], tools: list[dict[str, Any]] + ) -> dict[str, Any]: + response = await self.client.chat.completions.create( + model=self.model, + messages=messages, + tools=tools, # type: ignore[arg-type] + parallel_tool_calls=False, + temperature=0, + ) + message = response.choices[0].message + payload: dict[str, Any] = {"role": "assistant", "content": message.content} + if message.tool_calls: + payload["tool_calls"] = [call.model_dump() for call in message.tool_calls] + return { + "message": payload, + "usage": response.usage.model_dump() if response.usage else {}, + } + + +class ContextBudgetError(ValueError): + """The protected task, tool schema and newest turn exceed the budget.""" + + +def trim_history( + history: list[dict[str, Any]], hint: str, tools: list[dict[str, Any]], budget: int +) -> tuple[list[dict[str, Any]], int]: + """Drop whole oldest turns; never split one assistant's tool-call batch.""" + protected = history[:2] + groups: list[list[dict[str, Any]]] = [] + for message in history[2:]: + if message["role"] != "tool": + groups.append([message]) + elif not groups: + raise ValueError("Orphaned tool response in history.") + else: + groups[-1].append(message) + removed = 0 + while True: + messages = protected + [message for group in groups for message in group] + request = [messages[0], {"role": "system", "content": hint}, *messages[1:]] + size = len( + json.dumps({"messages": request, "tools": tools}, ensure_ascii=False) + ) + if size <= budget: + return messages, removed + if len(groups) <= 1: + raise ContextBudgetError( + "Protected messages and latest turn exceed context_chars. " + "Increase the budget or use smaller tool pages." + ) + groups.pop(0) + removed += 1 + + +def _validate_arguments(schema: dict[str, Any], arguments: Any) -> dict[str, Any]: + if not isinstance(arguments, dict): + raise ValueError("Tool arguments must be an object.") + properties = schema["properties"] + if arguments.keys() - properties.keys(): + raise ValueError("Unknown tool argument.") + if set(schema.get("required", [])) - arguments.keys(): + raise ValueError("Required tool argument is missing.") + types = {"string": str, "integer": int, "boolean": bool, "array": list} + for name, value in arguments.items(): + spec = properties[name] + if type(value) is not types[spec["type"]]: + raise ValueError(f"Invalid type for {name}.") + if "minimum" in spec and value < spec["minimum"]: + raise ValueError(f"{name} is below its minimum.") + if "enum" in spec and value not in spec["enum"]: + raise ValueError(f"Invalid value for {name}.") + if spec["type"] == "array" and any(not isinstance(v, str) for v in value): + raise ValueError(f"{name} must contain strings.") + return arguments + + +async def attribute( + graph: ExecNetwork, + case: FailedQueryCase, + provider: ChatProvider, + config: AttributionConfig | None = None, +) -> dict[str, Any]: + """Run one case and return a report; service/limit failures have no attribution.""" + config = config or AttributionConfig() + notebook = GraphTraceNotebook( + graph, config.max_trace_nodes, case.query_full_node_id + ) + notebook.page_limit = min(16_000, max(128, config.context_chars // 4)) + starting = await asyncio.to_thread( + retrieve_starting_nodes, + graph, + case, + min(config.num_starting_points, max(1, config.max_trace_nodes - 1)), + ) + initial = [case.query_full_node_id, *starting][: config.max_trace_nodes] + initialized = notebook.initialize_execution_graph(initial if starting else None) + tools = [ + *graph_tools(), + { + "type": "function", + "function": { + "name": "submit_attribution", + "description": "Submit a fault after graph exploration.", + "parameters": AttributionResult.model_json_schema(), + }, + }, + ] + schemas = { + tool["function"]["name"]: tool["function"]["parameters"] for tool in tools + } + history: list[dict[str, Any]] = [ + { + "role": "system", + "content": ATTRIBUTION_INSTRUCTIONS + + "\n" + + EVEROS_PRIOR + + "\n" + + TOOL_INSTRUCTIONS, + }, + { + "role": "user", + "content": json.dumps( + { + "question": case.query, + "golden_answers": case.golden_answers, + "wrong_answer": case.prediction, + "query_node": case.query_full_node_id, + "pseudo_evidence_nodes": starting, + "initialization": initialized, + } + ), + }, + ] + transcript: list[dict[str, Any]] = [ + { + "event": "initialization", + "initial_nodes": initial if starting else [], + "content": initialized, + }, + *[{"event": "message", "message": message} for message in history], + ] + report: dict[str, Any] = { + "status": "failed", + "graph_id": graph.graph_id, + "case": case.model_dump(), + "config": config.model_dump(), + "pseudo_evidence_nodes": starting, + "attribution": None, + "failure": None, + "iterations": 0, + "transcript": transcript, + "usage": {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0}, + } + operation_ids = {op.op_id for op in graph.search_operations()} + try: + for iteration in range(config.max_iters): + hint = notebook.hint() + history, removed = trim_history(history, hint, tools, config.context_chars) + if removed: + transcript.append({"event": "context_trim", "removed_turns": removed}) + transcript.append( + {"event": "hint", "iteration": iteration + 1, "content": hint} + ) + request = [history[0], {"role": "system", "content": hint}, *history[1:]] + report["iterations"] = iteration + 1 + response = await provider.complete(request, tools) + for key in report["usage"]: + report["usage"][key] += int(response.get("usage", {}).get(key, 0) or 0) + message = response["message"] + history.append(message) + transcript.append({"event": "message", "message": message}) + calls = message.get("tool_calls") or [] + if not calls: + correction = { + "role": "user", + "content": ( + "Inspect evidence, finish graph exploration, then call " + "submit_attribution. Plain text is not a result." + ), + } + history.append(correction) + transcript.append({"event": "message", "message": correction}) + continue + attribution = None + notebook.page_limit = min( + 16_000, max(128, config.context_chars // (4 * len(calls))) + ) + for call in calls: + name = call["function"]["name"] + try: + if name not in schemas: + raise ValueError("Unknown tool.") + arguments = _validate_arguments( + schemas[name], json.loads(call["function"]["arguments"]) + ) + if name == "submit_attribution": + if len(calls) != 1: + raise ValueError( + "Submit attribution in a separate tool call." + ) + result = AttributionResult.model_validate(arguments) + if result.op_id not in operation_ids: + raise ValueError("The submitted operation does not exist.") + if notebook.state is not None or notebook.final_state is None: + raise ValueError( + "Finish graph exploration before submitting." + ) + if notebook.insufficient_evidence is not None: + raise ValueError( + "Exploration ended with insufficient evidence." + ) + if result.op_id not in notebook.inspected_operations: + raise ValueError("Inspect the submitted operation first.") + op = graph.get_operation(result.op_id) + if op.op_name == "llm-judge" or op.op_name.startswith( + ("judge_answer_", "inject_golden_answers_") + ): + raise ValueError( + "Judging and reference injection are " + "not attributable faults." + ) + if not notebook.operation_allowed(op): + raise ValueError( + "The submitted operation belongs to " + "another request or a future event." + ) + if ( + op.metadata.get("observation_only") + or op.metadata.get("source") == "file_diff" + ): + raise ValueError( + "File observations do not establish the faulty " + "operation; stop with insufficient_evidence." + ) + evidence = { + node.full_node_id + for node in graph.filter_by_operation(op.op_id).nodes + } + if result.error_type == "ResponseError": + for node in graph.filter_by_operation(op.op_id).nodes: + snapshot = decode_snapshot(node.value) + if ( + node.class_name == "answer_context" + and isinstance(snapshot, dict) + and snapshot.get("observed") is False + ): + raise ValueError( + "The actual answer context is unrecorded; " + "stop with insufficient_evidence." + ) + cited = { + node_id for node_id in evidence if node_id in result.reason + } + if not cited & notebook.read_nodes: + raise ValueError( + "Cite a relevant node whose value was read " + "in the attribution reason." + ) + attribution = result.model_dump() + content = "Attribution accepted." + else: + content = await asyncio.to_thread( + getattr(notebook, name), **arguments + ) + except (KeyError, TypeError, ValueError) as exc: + content = f"Tool error: {exc}" + tool_message = { + "role": "tool", + "tool_call_id": call["id"], + "content": content, + } + history.append(tool_message) + transcript.append( + {"event": "message", "tool_name": name, "message": tool_message} + ) + if attribution is not None: + report.update(status="success", attribution=attribution) + break + if notebook.insufficient_evidence is not None: + report["failure"] = { + "type": "InsufficientEvidence", + "message": notebook.insufficient_evidence, + } + break + else: + report["failure"] = { + "type": "IterationLimit", + "message": "No validated attribution before max_iters.", + } + except ContextBudgetError as exc: + report["failure"] = {"type": "ContextBudgetError", "message": str(exc)} + except Exception as exc: + # Do not serialize provider exceptions: request URLs/headers may hold secrets. + report["failure"] = { + "type": type(exc).__name__, + "status_code": getattr(exc, "status_code", None), + } + report["final_state"] = notebook.snapshot() + report["inspected_operations"] = sorted(notebook.inspected_operations) + return report diff --git a/examples/memtrace/graphtrace/cases.py b/examples/memtrace/graphtrace/cases.py new file mode 100644 index 000000000..eecf540e8 --- /dev/null +++ b/examples/memtrace/graphtrace/cases.py @@ -0,0 +1,118 @@ +"""Read EverOS QA snapshots without changing execution graphs or annotations.""" + +from __future__ import annotations + +import ast +import json +import math +from typing import TYPE_CHECKING, Any + +from .models import FailedQueryCase + +if TYPE_CHECKING: + from smartcomment.runtime import ExecNetwork + + +def decode_snapshot(value: str) -> Any: + """Decode JSON when present, preserving ordinary text values.""" + try: + return json.loads(value) + except (ValueError, TypeError): + return value + + +def _text(value: str, key: str) -> str: + decoded = decode_snapshot(value) + if isinstance(decoded, dict): + decoded = decoded.get(key) + if not isinstance(decoded, str) or not decoded.strip(): + raise ValueError(f"Missing or invalid {key} text.") + return decoded + + +def _answers(value: str) -> list[str]: + decoded = decode_snapshot(value) + if isinstance(decoded, dict): + decoded = decoded.get("answers") + if isinstance(decoded, str): + # The existing tracer stores lists as Python repr inside JSON snapshots. + try: + parsed = ast.literal_eval(decoded) + except (ValueError, SyntaxError): + parsed = decoded + decoded = parsed if isinstance(parsed, list) else [decoded] + if not isinstance(decoded, list) or not decoded: + raise ValueError("Missing reference answers.") + if any(not isinstance(item, str) or not item.strip() for item in decoded): + raise ValueError("Reference answers must be nonempty strings.") + return decoded + + +def collect_failed_queries( + graph: ExecNetwork, +) -> tuple[list[FailedQueryCase], list[str]]: + """Return complete failed cases and diagnostics for malformed QA chains.""" + cases: list[FailedQueryCase] = [] + diagnostics: list[str] = [] + operations = graph.search_operations( + name_pattern=r"^(judge_answer_.*|llm-judge)$", category="evaluation" + ) + for op in sorted(operations, key=lambda item: (item.created_at, item.op_id)): + try: + nodes: dict[str, Any] = {} + for node in graph.filter_by_operation(op.op_id).nodes: + if node.class_name in ( + "query", + "prediction", + "golden_answers", + "judge_response", + "judge_score", + ): + if node.class_name in nodes: + raise ValueError(f"Ambiguous {node.class_name} nodes.") + nodes[node.class_name] = node + judge = nodes["judge_response"] + snapshot = decode_snapshot(judge.value) + score = ( + nodes["judge_score"].value + if "judge_score" in nodes + else snapshot.get("score") + if isinstance(snapshot, dict) + else None + ) + score = float(score) + if not math.isfinite(score): + raise ValueError("Judge score is not finite.") + if score != 0.0: + continue + query = nodes["query"] + query_snapshot = decode_snapshot(query.value) + original_name = query.full_name.removeprefix("query:").removeprefix( + query.metadata.get("tenant_scope", "") + ) + query_identity = ( + query_snapshot.get("id", original_name) + if isinstance(query_snapshot, dict) + else original_name + ) + for node in nodes.values(): + decoded = decode_snapshot(node.value) + if ( + isinstance(decoded, dict) + and decoded.get("query_id") is not None + and decoded["query_id"] != query_identity + ): + raise ValueError("QA snapshots refer to different queries.") + cases.append( + FailedQueryCase( + query_full_node_id=query.full_node_id, + query=_text(query.value, "query"), + golden_answers=_answers(nodes["golden_answers"].value), + prediction=_text(nodes["prediction"].value, "answer"), + judge_response=_text(judge.value, "response"), + judge_op_id=op.op_id, + ) + ) + except (KeyError, TypeError, ValueError) as exc: + diagnostics.append(f"Skipped judge operation {op.op_id}: {exc}") + return cases, diagnostics diff --git a/examples/memtrace/graphtrace/models.py b/examples/memtrace/graphtrace/models.py new file mode 100644 index 000000000..a20a27fa8 --- /dev/null +++ b/examples/memtrace/graphtrace/models.py @@ -0,0 +1,141 @@ +"""Typed case, exploration state, and attribution contracts for the example.""" + +from __future__ import annotations + +from typing import Literal + +from pydantic import BaseModel, ConfigDict, Field, field_validator + +from everos.core.utils.datetime import get_utc_now + + +def _timestamp() -> str: + return get_utc_now().isoformat() + + +class FailedQueryCase(BaseModel): + """One failed QA chain, with decoded user-facing text.""" + + query_full_node_id: str + query: str + golden_answers: list[str] + prediction: str + judge_response: str + judge_op_id: str + + +class GraphTraceNodeRecord(BaseModel): + """A versioned variable and the provenance of its exploration.""" + + full_node_id: str + created_at: str + category: str = "variable" + comment: str | None = None + state: Literal["to_explore", "exploring", "explored"] = "to_explore" + added_at: str = Field(default_factory=_timestamp) + discovered_from: str | None = None + discovered_by_op_id: str | None = None + explored_at: str | None = None + outcome: str | None = None + + @field_validator("full_node_id") + @classmethod + def validate_version(cls, value: str) -> str: + name, separator, version = value.rpartition("@") + if not name or not separator or not version.isdigit(): + raise ValueError("A full node id must have the form name@integer.") + return value + + def priority(self) -> tuple[str, str]: + return self.created_at, self.full_node_id + + +class GraphTraceState(BaseModel): + """Keep the active node separate so adding older nodes cannot displace it.""" + + to_explore_nodes: dict[str, GraphTraceNodeRecord] = Field(default_factory=dict) + exploring_node: GraphTraceNodeRecord | None = None + exploration_history: dict[str, GraphTraceNodeRecord] = Field(default_factory=dict) + finished_at: str | None = None + outcome: str | None = None + + def add(self, record: GraphTraceNodeRecord, capacity: int) -> None: + node_id = record.full_node_id + if ( + node_id in self.to_explore_nodes + or node_id in self.exploration_history + or (self.exploring_node and self.exploring_node.full_node_id == node_id) + ): + raise ValueError( + f"Variable {node_id} is already queued, active, or explored." + ) + if len(self.to_explore_nodes) >= capacity: + raise ValueError("The frontier is full; delete a queued node first.") + self.to_explore_nodes[node_id] = record + + def delete(self, node_id: str) -> None: + if node_id not in self.to_explore_nodes: + raise ValueError("Only a queued node can be deleted.") + del self.to_explore_nodes[node_id] + + def start_next(self) -> GraphTraceNodeRecord: + if self.exploring_node is None: + if not self.to_explore_nodes: + raise ValueError( + "The frontier is empty. Finish or restart exploration." + ) + record = min( + self.to_explore_nodes.values(), key=lambda item: item.priority() + ) + del self.to_explore_nodes[record.full_node_id] + record.state = "exploring" + self.exploring_node = record + return self.exploring_node + + def finish_node(self, outcome: str) -> None: + if self.exploring_node is None: + raise ValueError("There is no active node.") + record = self.exploring_node + record.state = "explored" + record.outcome = outcome + record.explored_at = _timestamp() + self.exploration_history[record.full_node_id] = record + self.exploring_node = None + + def finish(self, outcome: str) -> None: + if self.exploring_node is not None: + self.finish_node(outcome) + self.outcome = outcome + self.finished_at = _timestamp() + + +class AttributionResult(BaseModel): + """The same single-operation output schema used by MemTrace.""" + + model_config = ConfigDict(extra="forbid") + + error_type: Literal[ + "ExtractionError", + "UpdateError", + "DeletionError", + "RetrievalError", + "ResponseError", + ] + op_id: str = Field(min_length=1) + reason: str = Field(min_length=1) + + @field_validator("reason") + @classmethod + def validate_reason(cls, value: str) -> str: + if not value.strip(): + raise ValueError("The reason must not be blank.") + return value + + +class AttributionConfig(BaseModel): + """Bounded example runtime; the character budget is not a tokenizer.""" + + max_iters: int = Field(default=200, ge=1) + max_trace_nodes: int = Field(default=16, ge=1) + num_starting_points: int = Field(default=8, ge=1) + context_chars: int = Field(default=100_000, ge=1) diff --git a/examples/memtrace/graphtrace/notebook.py b/examples/memtrace/graphtrace/notebook.py new file mode 100644 index 000000000..ba884849a --- /dev/null +++ b/examples/memtrace/graphtrace/notebook.py @@ -0,0 +1,540 @@ +"""Seven graph tools and state hints, independent of an agent framework.""" + +from __future__ import annotations + +import json +import re +from collections import Counter +from typing import TYPE_CHECKING, Any, Literal + +from .cases import decode_snapshot +from .models import GraphTraceNodeRecord, GraphTraceState +from .scope import same_tenant + +if TYPE_CHECKING: + from smartcomment.runtime import ExecNetwork + from smartcomment.runtime.operation import RuntimeOp + +DUMMY_ROOT = "__memtrace_root__@0" +PAGE_LIMIT = 128_000 +DEFAULT_PAGE = 16_000 + + +def paginate(text: str, offset: int = 1, limit: int = DEFAULT_PAGE) -> str: + """Return one-based character pagination and the next readable offset.""" + if offset < 1 or limit < 1: + raise ValueError("offset and limit must be positive integers.") + limit = min(limit, PAGE_LIMIT) + end = min(offset - 1 + limit, len(text)) + content = text[offset - 1 : end] + status = f"Characters {offset}-{end} of {len(text)}." + if offset > len(text): + status = f"No content at offset {offset}; total characters: {len(text)}." + elif end < len(text): + status += f" Truncated; next offset={end + 1}." + else: + status += " End of content." + return content + "\n\n" + status + + +class GraphTraceNotebook: + """Explore an existing graph; tools never mutate or re-export that graph.""" + + def __init__( + self, + graph: ExecNetwork, + max_trace_nodes: int = 16, + query_full_node_id: str | None = None, + ) -> None: + if max_trace_nodes < 1: + raise ValueError("max_trace_nodes must be positive.") + self.graph = graph + self.max_trace_nodes = max_trace_nodes + self.state: GraphTraceState | None = None + self.final_state: GraphTraceState | None = None + self.insufficient_evidence: str | None = None + self.inspected_operations: set[str] = set() + self.read_nodes: set[str] = set() + self._page_coverage: dict[tuple[str, str, bool], list[tuple[int, int]]] = {} + self.page_limit = DEFAULT_PAGE + self.query_node = ( + graph.get_variable(query_full_node_id) if query_full_node_id else None + ) + query_value = decode_snapshot(self.query_node.value) if self.query_node else {} + self.request_id = ( + query_value.get("request_id") if isinstance(query_value, dict) else None + ) + self.query_identity = ( + query_value.get("id") if isinstance(query_value, dict) else None + ) + sequences = Counter( + op.metadata["event_seq"] + for op in graph.search_operations() + if isinstance(op.metadata.get("event_seq"), int) + ) + self.unique_event_sequences = all(count == 1 for count in sequences.values()) + + def _state(self) -> GraphTraceState: + if self.state is None: + raise ValueError("Initialize the execution graph before using this tool.") + return self.state + + def _record(self, node_id: str, op_id: str | None = None) -> GraphTraceNodeRecord: + if node_id == DUMMY_ROOT: + return GraphTraceNodeRecord( + full_node_id=DUMMY_ROOT, created_at="", category="synthetic_root" + ) + try: + node = self.graph.get_variable(node_id) + except KeyError as exc: + raise ValueError(f"Unknown variable {node_id}.") from exc + if self.query_node is not None and not same_tenant(node, self.query_node): + raise ValueError("The variable belongs to another tenant.") + active = self.state.exploring_node if self.state else None + return GraphTraceNodeRecord( + full_node_id=node.full_node_id, + created_at=node.created_at, + category=node.category, + comment=node.comment, + discovered_from=active.full_node_id if active else None, + discovered_by_op_id=op_id, + ) + + def initialize_execution_graph( + self, initial_full_node_ids: list[str] | None = None + ) -> str: + """Initialize with selected variables, or a synthetic root if omitted.""" + if self.state is not None: + raise ValueError("The execution graph is already initialized.") + ids = list(dict.fromkeys(initial_full_node_ids or [DUMMY_ROOT])) + records = [self._record(node_id) for node_id in ids] + state = GraphTraceState() + for record in records: + state.add(record, self.max_trace_nodes) + self.state = state + self.insufficient_evidence = None + return f"Initialized graph with {len(records)} frontier nodes." + + def _operation_key(self, op: RuntimeOp) -> tuple[Any, ...]: + seq = op.metadata.get("event_seq") + if self.unique_event_sequences: + # Offline QA operations lack event_seq and were appended after recording. + return ( + not isinstance(seq, int), + seq if isinstance(seq, int) else 0, + op.created_at, + op.op_id, + ) + return (op.created_at, seq if isinstance(seq, int) else 0, op.op_id) + + def _render_operation(self, op: RuntimeOp, node_id: str, values: bool) -> str: + subgraph = self.graph.filter_by_operation(op.op_id) + sources = {edge.source_full_node_id for edge in subgraph.edges} + targets = {edge.target_full_node_id for edge in subgraph.edges} + inputs = [ + node.full_node_id + for node in subgraph.nodes + if node.full_node_id not in targets + ] + outputs = [ + node.full_node_id for node in subgraph.nodes if node.full_node_id in targets + ] + successors = sorted( + { + edge.target_full_node_id + for edge in subgraph.edges + if edge.source_full_node_id == node_id + } + ) + role = ( + "intermediate" + if node_id in sources and node_id in targets + else "input" + if node_id in sources + else "output" + if node_id in targets + else "isolated" + ) + ordering = { + key: op.metadata[key] + for key in ("event_seq", "observed_at", "source", "trigger") + if key in op.metadata + } + return "\n".join( + [ + f"# Operation `{op.op_id}`", + f"Name: {op.op_name}; Category: {op.category}; " + f"Created: {op.created_at}", + f"Comment: {op.comment or ''}", + f"Observation ordering: {json.dumps(ordering)}", + f"Focus variable: {node_id}; Role: {role}", + f"Inputs: {sorted(inputs)}", + f"Produced variables: {sorted(outputs)}", + f"Direct successors: {successors}", + "Final output variables: " + + str(sorted(node.full_node_id for node in subgraph.get_leaf_nodes())), + subgraph.to_xml(include_metadata=True, include_variable_value=values), + ] + ) + + def explore_graph_trace_node( + self, + offset: int = 1, + limit: int = DEFAULT_PAGE, + include_variable_value: bool = True, + ) -> str: + """Inspect the active/earliest node's producing and consuming operations.""" + if offset < 1 or limit < 1: + raise ValueError("offset and limit must be positive.") + record = self._state().start_next() + if record.full_node_id == DUMMY_ROOT: + roots = sorted( + ( + node + for node in self.graph.get_root_nodes() + if self.query_node is None + or ( + same_tenant(node, self.query_node) + and node.created_at <= self.query_node.created_at + ) + ), + key=lambda node: (node.created_at, node.full_node_id), + ) + text = "# Synthetic root: choose roots using update_to_explore_nodes\n" + text += "\n".join( + node.to_xml( + include_metadata=True, include_variable_value=include_variable_value + ) + for node in roots + ) + else: + operations = sorted( + self.graph.get_operations_by_variable(record.full_node_id), + key=self._operation_key, + ) + text = f"# Graph trace node {record.full_node_id}\n\n" + spans = [] + for op in operations: + if not self.operation_allowed(op): + continue + start = len(text) + text += self._render_operation( + op, record.full_node_id, include_variable_value + ) + spans.append((op, start, len(text))) + text += "\n\n---\n\n" + end = min(offset - 1 + min(limit, self.page_limit), len(text)) + for op, start, stop in spans: + left, right = max(start, offset - 1), min(stop, end) + if left >= right: + continue + key = (op.op_id, record.full_node_id, include_variable_value) + coverage = self._page_coverage.setdefault(key, []) + coverage.append((left - start, right - start)) + covered = 0 + for left, right in sorted(coverage): + if left > covered: + break + covered = max(covered, right) + self._page_coverage[key] = [(0, covered)] + [ + (left, right) for left, right in coverage if left > covered + ] + if covered >= stop - start: + self.inspected_operations.add(op.op_id) + if include_variable_value: + self.read_nodes.update( + n.full_node_id + for n in self.graph.filter_by_operation(op.op_id).nodes + ) + return paginate(text, offset, min(limit, self.page_limit)) + + def operation_allowed(self, op: RuntimeOp) -> bool: + """Keep the current request plus earlier construction history in scope.""" + if self.query_node is None: + return True + scope = self.query_node.metadata.get("tenant_scope") + if scope is not None and op.metadata.get("tenant_scope") != scope: + return False + if op.category in ("retrieval", "response", "evaluation"): + if op.metadata.get("query_id"): + return op.metadata["query_id"] == self.query_identity + if self.request_id and op.metadata.get("request_id"): + return op.metadata["request_id"] == self.request_id + queries = [ + node + for node in self.graph.filter_by_operation(op.op_id).nodes + if node.class_name == "query" + ] + if queries: + return all( + node.full_node_id == self.query_node.full_node_id + for node in queries + ) + if ( + op.created_at > self.query_node.created_at + and op.category == "retrieval" + ): + return False + elif op.created_at > self.query_node.created_at: + return False + return True + + def update_to_explore_nodes( + self, + action: Literal["add", "delete"], + full_node_id: str, + discovered_by_op_id: str | None = None, + ) -> str: + """Maintain the frontier and record which inspected operation exposed a node.""" + state = self._state() + if action == "delete": + state.delete(full_node_id) + elif action == "add": + if discovered_by_op_id is not None: + try: + subgraph = self.graph.filter_by_operation(discovered_by_op_id) + except KeyError as exc: + raise ValueError("Unknown discovery operation.") from exc + if full_node_id not in {node.full_node_id for node in subgraph.nodes}: + raise ValueError( + "The discovery operation does not contain this node." + ) + state.add( + self._record(full_node_id, discovered_by_op_id), self.max_trace_nodes + ) + else: + raise ValueError("action must be add or delete.") + return f"Frontier action {action} succeeded for {full_node_id}." + + def view_node_value( + self, + full_node_id: str, + pattern: str | None = None, + max_surrounding_chars: int = 120, + offset: int = 1, + limit: int = DEFAULT_PAGE, + ) -> str: + """Read stored text, or paginate regex matches with source character ranges.""" + self._state() + if offset < 1 or limit < 1 or max_surrounding_chars < 0: + raise ValueError("Invalid pagination or surrounding-character count.") + try: + node = self.graph.get_variable(full_node_id) + except KeyError as exc: + raise ValueError(f"Unknown variable {full_node_id}.") from exc + if self.query_node is not None and not same_tenant(node, self.query_node): + raise ValueError("The variable belongs to another tenant.") + value = node.value + if pattern is None: + if offset <= len(value): + self.read_nodes.add(full_node_id) + return paginate(value, offset, min(limit, self.page_limit)) + try: + regex = re.compile(pattern) + except re.error as exc: + raise ValueError(f"Invalid regex: {exc}") from exc + limit = min(limit, PAGE_LIMIT, self.page_limit) + parts = [] + size = 0 + next_offset = None + for match in regex.finditer(value, offset - 1): + start = max(0, match.start() - max_surrounding_chars) + end = min(len(value), match.end() + max_surrounding_chars) + snippet = f"Match at {match.start() + 1}-{match.end()}: {value[start:end]}" + if parts and size + len(snippet) + 1 > limit: + next_offset = match.start() + 1 + break + if len(snippet) > limit: + # Never silently discard a large match; direct reading stays available. + snippet = snippet[:limit] + " [snippet truncated; read value directly]" + parts.append(snippet) + size += len(snippet) + 1 + if parts: + self.read_nodes.add(full_node_id) + status = ( + f"More matches; next offset={next_offset}." + if next_offset + else "End of matches." + ) + return "\n".join(parts or ["No matches."]) + "\n" + status + + def finish_node_exploration(self, outcome: str) -> str: + """Move the active node into immutable exploration history.""" + self._state().finish_node(outcome) + return "Node exploration finished." + + def finish_graph_exploration( + self, outcome: str, insufficient_evidence: bool = False + ) -> str: + """Archive final state; allow a later explicit initialization to restart.""" + state = self._state() + state.finish(outcome) + self.final_state = state.model_copy(deep=True) + self.state = None + if insufficient_evidence: + self.insufficient_evidence = outcome + return ( + "Exploration stopped: insufficient evidence; no attribution submitted." + ) + return "Graph exploration finished. Submit attribution or explicitly restart." + + def view_exploration_history( + self, offset: int = 1, limit: int = DEFAULT_PAGE + ) -> str: + """Return completed node records without returning full node values.""" + return paginate( + json.dumps( + { + key: node.model_dump() + for key, node in self._state().exploration_history.items() + }, + indent=2, + ), + offset, + min(limit, self.page_limit), + ) + + def hint(self) -> str: + """Generate a fresh state hint rather than accumulating stale hints.""" + if self.state is None: + return ( + "Graph exploration finished; call submit_attribution, or initialize " + "again if more evidence is needed." + if self.final_state + else "Call initialize_execution_graph before exploring." + ) + state = self.state + active = state.exploring_node + queued = sorted( + state.to_explore_nodes.values(), key=lambda node: node.priority() + ) + + def brief(node: GraphTraceNodeRecord) -> dict[str, Any]: + return { + "full_node_id": node.full_node_id, + "category": node.category, + "comment": (node.comment or "")[:240], + "discovered_by_op_id": node.discovered_by_op_id, + } + + summary = { + "active": brief(active) if active else None, + "frontier_count": len(queued), + "frontier": [brief(node) for node in queued[:16]], + "completed_count": len(state.exploration_history), + "completed": [ + { + "full_node_id": node.full_node_id, + "outcome": (node.outcome or "")[:400], + } + for node in list(state.exploration_history.values())[-4:] + ], + } + actions = ( + "Inspect more pages or selected values, add downstream nodes, then " + "finish_node_exploration." + if active + else "Explore the earliest node or finish_graph_exploration if ready." + ) + return ( + "\n" + json.dumps(summary) + "\n" + actions + "" + ) + + def snapshot(self) -> dict[str, Any] | None: + state = self.state or self.final_state + return state.model_dump() if state is not None else None + + +def _tool( + name: str, + description: str, + properties: dict[str, Any], + required: list[str] | None = None, +) -> dict[str, Any]: + return { + "type": "function", + "function": { + "name": name, + "description": description, + "parameters": { + "type": "object", + "properties": properties, + "required": required or [], + "additionalProperties": False, + }, + }, + } + + +def graph_tools() -> list[dict[str, Any]]: + """Expose the notebook tools through OpenAI function calling.""" + pagination = { + "offset": {"type": "integer", "minimum": 1, "default": 1}, + "limit": {"type": "integer", "minimum": 1, "default": DEFAULT_PAGE}, + } + node_id = {"type": "string", "description": "Exact versioned full_node_id."} + outcome = {"outcome": {"type": "string"}} + return [ + _tool( + "initialize_execution_graph", + "Initialize or restart graph exploration.", + {"initial_full_node_ids": {"type": "array", "items": node_id}}, + ), + _tool( + "explore_graph_trace_node", + "Inspect operations involving the active node.", + { + **pagination, + "include_variable_value": {"type": "boolean", "default": True}, + }, + ), + _tool( + "update_to_explore_nodes", + "Add/delete one future exploration node.", + { + "action": {"type": "string", "enum": ["add", "delete"]}, + "full_node_id": node_id, + "discovered_by_op_id": {"type": "string"}, + }, + ["action", "full_node_id"], + ), + _tool( + "view_node_value", + "Read a value or search it with a regex.", + { + **pagination, + "full_node_id": node_id, + "pattern": {"type": "string"}, + "max_surrounding_chars": { + "type": "integer", + "minimum": 0, + "default": 120, + }, + }, + ["full_node_id"], + ), + _tool( + "finish_node_exploration", + "Finish the active node with findings.", + outcome, + ["outcome"], + ), + _tool( + "finish_graph_exploration", + "Finish graph exploration before submitting.", + { + **outcome, + "insufficient_evidence": { + "type": "boolean", + "default": False, + "description": "Stop if critical evidence is absent.", + }, + }, + ["outcome"], + ), + _tool( + "view_exploration_history", + "Read completed node exploration records.", + pagination, + ), + ] diff --git a/examples/memtrace/graphtrace/prompts.py b/examples/memtrace/graphtrace/prompts.py new file mode 100644 index 000000000..2a11a7cb6 --- /dev/null +++ b/examples/memtrace/graphtrace/prompts.py @@ -0,0 +1,145 @@ +"""MemTrace attribution instructions and the EverOS observation prior. + +Attribution instructions adapted from MemTrace/toolkits/memtrace_utils.py. +See MEMTRACE_LICENSE.txt for the original MIT license. +""" + +from __future__ import annotations + +ATTRIBUTION_INSTRUCTIONS = """ +Your task is to inspect the execution graph and identify the earliest decisive + faulty operation. + +How to read the execution graph: +- The execution graph consists of operations. Each operation forms a single-hop or + multi-hop subgraph. +- Within one operation subgraph, variables with in-degree 0 relative to that + subgraph are the operation's input variables. +- Variables with in-degree >= 1 relative to that subgraph are variables produced by + the operation. +- Variables with out-degree 0 relative to that subgraph are the operation's final + output variables. +- To judge an operation, inspect its operation name, category, comment, input + variables, produced variables, final output variables, variable values, variable + comments, variable relationships, and creation timestamps. +- If the current operation is locally correct for its role, it is not the error. + Continue downstream by adding one or more final output variables from the current + operation to the exploration frontier and inspect the subsequent operations that + consume them. +- Pay close attention to creation time. The earliest decisive fault is based on + operation execution order, not on which source message is created first. + +Ideal memory-system behavior: +- When a raw input containing critical information arrives, the memory construction + stage should create or update memory-unit containers so that the critical + information enters the memory store. +- Later operations over a memory-unit container should preserve the critical + information. They should not accidentally remove, overwrite, over-summarize, or + degrade it during updates, consolidation, or deletion. +- When a query requiring that critical information arrives, retrieval should surface + memory units or context containing the needed information. +- The downstream answer model should then use the retrieved context to answer the + question correctly. +- Compare the observed trace against this ideal behavior to decide where the first + decisive break occurs. + +Definition of earliest decisive faulty operation: +- An operation is faulty only if its outputs are wrong or insufficient for the role + it is supposed to perform, given its operation name, category, comment, inputs, + and available evidence at that point in the workflow. +- Do not mark an operation faulty merely because it appears early or because a + downstream failure can be traced back to one of its inputs. First decide whether + the operation itself behaved incorrectly under its own local responsibility. +- Decisive means that correcting this operation's faulty output, while keeping all + strictly earlier operations unchanged and assuming ideal downstream behavior, + would have prevented the final wrong answer. +- Earliest means the first such locally faulty and decisive operation in execution + order. + +Required reasoning checklist before returning the final answer: +1. Identify the critical information needed to answer the question. +2. Inspect candidate operations in execution order and decide whether each one is + locally correct for its own function. +3. If an operation is locally correct, follow its final output variables downstream + instead of labeling it as the error. +4. Once the critical information enters a memory unit, do not stop at that + operation. You must keep following downstream operations involving that memory + unit and check whether the critical information remains present throughout the + lifetime of the memory unit. If an operation causes this critical information to + be transferred from one memory unit to another memory unit or to some intermediate + variables, and the original memory unit no longer contains this information, then + track the other memory unit or intermediate variables (that contain this key + information) to ensure that there exists a memory unit that will hold this key + information. +5. If the critical information never enters any memory unit, label the responsible + construction operation as ExtractionError. +6. If the critical information enters a memory unit but a later operation removes or + degrades it, label that later operation as UpdateError or DeletionError depending + on whether it updates the unit or explicitly deletes it. +7. For retrieval candidates, verify that the memory store contains the required + information before retrieval, but the retrieval pipeline fails to include it in + the final retrieved context. +8. For response candidates, verify that the final retrieved context contains all + necessary evidence and the answer model still answers incorrectly. + +Return exactly one error attribution using the required structured schema: +- error_type: one of ExtractionError, UpdateError, DeletionError, RetrievalError, + ResponseError. +- op_id: the operation identifier of the earliest decisive faulty operation. +- reason: a concise explanation grounded in graph evidence. The reason must state + why the chosen operation is locally faulty, why correcting it would rescue the + answer, and why earlier candidate operations are not the decisive fault when + relevant. + +Error type definitions: +- ExtractionError: The critical information is never captured into any memory unit + during memory construction, and thus never enters the memory store. +- UpdateError: A memory unit initially contains the critical information, but a + subsequent update removes or degrades it. +- DeletionError: A memory unit containing critical information is explicitly + removed. +- RetrievalError: The memory store contains the required information, but retrieval + fails to include it in the final retrieved context. +- ResponseError: The retrieved context contains all necessary evidence, but the + final LLM still answers incorrectly.""" + +EVEROS_PRIOR = """System-specific prior (EverOS file tracking): +- Messages enter buffers; boundaries form memcells, and extraction writes memory + entries. Updates and deletions change versioned entries on disk. +- Retrieval can include sparse/dense candidate pools, fusion, filtering and final + context assembly. Follow the actually recorded stages and final context. +- identity_only candidates are references, not proof of memory contents. A + retrieval_hit is request-local; memory_identity and source_revision reference + the persistent entry. Unresolved revisions do not establish stored contents. +- context records the search response. answer_context records the exact text + given to the answer model. Inspect answer_context for ResponseError; null or + observed=false means the actual answer input is unknown. +- event_seq orders observations within a recording process. File-diff operations + are post-hoc observations; observed_at is not the real pipeline execution time. + Duplicate sequences in merged graphs require timestamp fallback; do not infer + a reliable global order across independent processes from sequence alone. +- source=construction_event records actual boundary/extractor values, including + empty results and attempts. source=file_diff / observation_only=true describe + disk observations, not proof of a specific executed extraction/update/delete. + If only these observations support the suspected fault, stop with + insufficient_evidence rather than selecting an observation as the fault. +- Approximate memcell membership and truncated candidate pools limit what can be + concluded. Missing edges or unrecorded values are not proof of a faulty operation. +- Verify source evidence, memory preservation, final retrieval context, then + response generation, using the earliest locally faulty decisive operation rule. +""" + +TOOL_INSTRUCTIONS = """Use the graph tools to inspect evidence before deciding. +The graph may already be initialized with the query and retrieved source-message +candidates. These are pseudo evidence, not human annotations; verify their content. +Use operation previews (include_variable_value=false) and view_node_value with a +regex for large values. Follow next offset when a page is truncated. All offsets +are one-based character positions, not line numbers. Keep the active node until +finish_node_exploration; queued nodes are ordered by creation time and identifier. +Finish graph exploration, then call submit_attribution with one inspected op_id. +The report reason must cite an exact relevant full_node_id whose value you read. +Do not treat the judge or reference-answer injection as a memory-system fault. +If critical source information is absent from the recorded graph, do not assume +an extraction or retrieval error. Finish exploration with insufficient_evidence +set to true and explain the missing evidence; do not submit an attribution. +""" diff --git a/examples/memtrace/graphtrace/retrieval.py b/examples/memtrace/graphtrace/retrieval.py new file mode 100644 index 000000000..5d7198bef --- /dev/null +++ b/examples/memtrace/graphtrace/retrieval.py @@ -0,0 +1,85 @@ +"""Dependency-free BM25Okapi selection of candidate source messages.""" + +from __future__ import annotations + +import math +import re +from collections import Counter +from typing import TYPE_CHECKING + +from .cases import decode_snapshot +from .scope import same_tenant + +if TYPE_CHECKING: + from smartcomment.runtime import ExecNetwork + + from .models import FailedQueryCase + + +def tokenize(text: str) -> list[str]: + """Match the original MemTrace English lexical tokenizer.""" + return re.findall(r"[a-z0-9_]+", text.lower()) + + +def bm25_scores(documents: list[str], query: str) -> list[float]: + """BM25Okapi defaults: k1=1.5, b=0.75, negative-IDF epsilon=0.25.""" + corpus = [tokenize(text) for text in documents] + if not corpus: + return [] + frequencies = [Counter(tokens) for tokens in corpus] + document_frequency: Counter[str] = Counter() + for counts in frequencies: + document_frequency.update(counts.keys()) + n = len(corpus) + average_length = sum(map(len, corpus)) / n + if not document_frequency or not average_length: + return [0.0] * n + idf = { + term: math.log(n - count + 0.5) - math.log(count + 0.5) + for term, count in document_frequency.items() + } + epsilon = 0.25 * sum(idf.values()) / len(idf) + idf = {term: epsilon if weight < 0 else weight for term, weight in idf.items()} + scores = [] + for tokens, counts in zip(corpus, frequencies, strict=True): + normalizer = 1.5 * (0.25 + 0.75 * len(tokens) / average_length) + scores.append( + sum( + idf.get(term, 0.0) * counts[term] * 2.5 / (counts[term] + normalizer) + for term in tokenize(query) + ) + ) + return scores + + +def retrieve_starting_nodes( + graph: ExecNetwork, case: FailedQueryCase, limit: int = 8 +) -> list[str]: + """Rank raw messages by question plus reference; these are pseudo evidence.""" + if limit < 1: + raise ValueError("The retrieval limit must be positive.") + query_node = graph.get_variable(case.query_full_node_id) + nodes = sorted( + ( + node + for node in graph.search_variables(category="message") + if same_tenant(node, query_node) + and node.created_at <= query_node.created_at + ), + key=lambda node: (node.created_at, node.full_node_id), + ) + documents = [] + usable_nodes = [] + for node in nodes: + snapshot = decode_snapshot(node.value) + text = snapshot.get("content", "") if isinstance(snapshot, dict) else snapshot + if isinstance(text, str) and text.strip(): + documents.append(text) + usable_nodes.append(node) + query = case.query + "\n" + "\n".join(case.golden_answers) + scores = bm25_scores(documents, query) + ranked = sorted( + zip(usable_nodes, scores, strict=True), + key=lambda item: (-item[1], item[0].created_at, item[0].full_node_id), + ) + return [node.full_node_id for node, _score in ranked[:limit]] diff --git a/examples/memtrace/graphtrace/scope.py b/examples/memtrace/graphtrace/scope.py new file mode 100644 index 000000000..9accf5d39 --- /dev/null +++ b/examples/memtrace/graphtrace/scope.py @@ -0,0 +1,14 @@ +"""Tenant boundaries for safely merged execution graphs.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from smartcomment.runtime.variable import RuntimeVariable + + +def same_tenant(node: RuntimeVariable, query: RuntimeVariable) -> bool: + """Unmerged graphs share scope; merged records declare it explicitly.""" + scope = query.metadata.get("tenant_scope") + return scope is None or node.metadata.get("tenant_scope") == scope diff --git a/examples/memtrace/inject_qa.py b/examples/memtrace/inject_qa.py new file mode 100644 index 000000000..bf12831bb --- /dev/null +++ b/examples/memtrace/inject_qa.py @@ -0,0 +1,52 @@ +"""Inject LoCoMo QA results into exported EverOS MemTrace graphs. + +The file-tracking tracer records everything up to the assembled +``memory_context``; the QA answer stage runs out-of-process (the drive +script), so this post-hoc step stitches ``prompt`` / ``prediction`` / +``golden_answers`` / ``judge_response`` onto the recorded query nodes with +the native MemTraceBench vocabulary (see ``everos.infra.memtrace.qa``). + +Run against a stopped server, after ``filetrace_locomo_drive.py +--qa`` has written ``qa_results.json``:: + + python examples/memtrace/inject_qa.py \ + --graph-dir /memtrace \ + --qa-results qa_results.json +""" + +from __future__ import annotations + +import argparse +import json +import pathlib +import sys + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--graph-dir", required=True, help="Directory holding the exported graph JSONs" + ) + parser.add_argument( + "--qa-results", + required=True, + help="qa_results.json written by filetrace_locomo_drive.py --qa", + ) + args = parser.parse_args() + + from everos.infra.memtrace.qa import inject_qa_dir + + payload = json.loads(pathlib.Path(args.qa_results).read_text(encoding="utf-8")) + records = payload.get("records", payload) if isinstance(payload, dict) else payload + injected = inject_qa_dir(pathlib.Path(args.graph_dir), records) + for name, count in injected.items(): + print(f"[inject] {name}: {count} record(s)", flush=True) + print( + f"injected {sum(injected.values())} record(s) into {len(injected)} graph(s)", + flush=True, + ) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/examples/memtrace/merge.py b/examples/memtrace/merge.py new file mode 100644 index 000000000..3f5813110 --- /dev/null +++ b/examples/memtrace/merge.py @@ -0,0 +1,128 @@ +"""Merge stopped EverOS traces, separating tenants and rejecting revision conflicts.""" + +from __future__ import annotations + +import argparse +import copy +import hashlib +import json +from pathlib import Path +from typing import Any + +from smartcomment.runtime import ExecNetwork + + +def merge_graphs(graphs: list[dict[str, Any]]) -> dict[str, Any]: + """Namespace all identities by tenant; conflicting immutable values are errors.""" + if not graphs: + raise ValueError("No execution graphs supplied.") + result = copy.deepcopy(graphs[0]) + buckets: dict[str, dict[str, dict[str, Any]]] = { + kind: {} for kind in ("nodes", "edges", "operations", "sessions") + } + for original in graphs: + graph = copy.deepcopy(original) + metadata = graph.get("metadata", {}) + scope = [ + metadata.get("app_id"), + metadata.get("project_id", graph.get("project_id")), + ] + if any(value is None for value in scope): + raise ValueError( + "Every input graph must declare its app and project scope." + ) + prefix = ( + "scope-" + hashlib.sha256(json.dumps(scope).encode()).hexdigest()[:16] + "/" + ) + aliases = {} + for node in graph["data"]["nodes"]: + old_id = node["full_node_id"] + node["name"] = prefix + node["name"] + node["full_name"] = ( + (node["class_name"] + ":") if node.get("class_name") else "" + ) + node["name"] + node["full_node_id"] = f"{node['full_name']}@{node['version']}" + aliases[old_id] = node["full_node_id"] + node.setdefault("metadata", {})["tenant_scope"] = prefix + for op in graph["data"]["operations"]: + op.setdefault("metadata", {})["tenant_scope"] = prefix + for edge in graph["data"]["edges"]: + for field in ("source_full_node_id", "target_full_node_id"): + edge[field] = aliases.get(edge[field], edge[field]) + for node in graph["data"]["nodes"]: + try: + snapshot = json.loads(node["value"]) + except (TypeError, ValueError): + continue + if isinstance(snapshot, dict) and snapshot.get("source_revision"): + revision = snapshot["source_revision"] + snapshot["source_revision"] = aliases.get(revision, revision) + node["value"] = json.dumps(snapshot, ensure_ascii=False, sort_keys=True) + for op in graph["data"]["operations"]: + for field in ("source_node", "query_full_node_id"): + reference = op["metadata"].get(field) + if reference in aliases: + op["metadata"][field] = aliases[reference] + for kind, id_field in ( + ("sessions", "session_id"), + ("nodes", "full_node_id"), + ("operations", "op_id"), + ("edges", "edge_id"), + ): + for item in graph["data"][kind]: + key = item[id_field] + prior = buckets[kind].get(key) + if ( + kind == "nodes" + and prior is not None + and prior["value"] != item["value"] + ): + raise ValueError(f"Conflicting memory revision: {key}") + if ( + kind in ("edges", "operations") + and prior is not None + and any( + prior.get(field) != item.get(field) + for field in ( + "source_full_node_id", + "target_full_node_id", + "op_name", + "metadata", + ) + ) + ): + raise ValueError(f"Conflicting trace record: {key}") + buckets[kind].setdefault(key, item) + result["data"] = {kind: list(items.values()) for kind, items in buckets.items()} + result["data"]["annotations"] = [] + result["graph_id"] = ( + "merged-" + + hashlib.sha256( + json.dumps([graph["graph_id"] for graph in graphs]).encode() + ).hexdigest()[:16] + ) + result["metadata"] = { + "merged_from": [g["graph_id"] for g in graphs], + "identity_namespace": "app_project", + "history_complete": False, + } + ExecNetwork.import_graph(result) + return result + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("graph_dir", type=Path) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + paths = sorted(args.graph_dir.glob("*.json")) + if args.output.resolve() in {path.resolve() for path in paths}: + parser.error("The merged graph must not overwrite a source graph.") + graphs = [json.loads(path.read_text()) for path in paths] + merged = merge_graphs(graphs) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(merged, ensure_ascii=False, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/examples/memtrace/repair_construction.py b/examples/memtrace/repair_construction.py new file mode 100644 index 000000000..defacdb2e --- /dev/null +++ b/examples/memtrace/repair_construction.py @@ -0,0 +1,226 @@ +"""Repair repeated boundary observations in stopped EverOS experiment graphs. + +SQLite supplies immutable memcell membership. Only sender-only duplicate exact +versions and repeated operations for that same boundary are merged. Other +operations and real membership changes remain intact. Applying writes backups +and an audit; dry runs never change source graphs. +""" + +from __future__ import annotations + +import argparse +import copy +import hashlib +import json +import sqlite3 +from pathlib import Path +from typing import Any + +import portalocker +from smartcomment.runtime import ExecNetwork + + +def repair_payload(payload: dict, boundaries: dict[str, dict]) -> tuple[dict, dict]: + """Repair only boundaries whose exact graph snapshots agree with SQLite.""" + result = copy.deepcopy(payload) + data = result["data"] + ops = {op["op_id"]: op for op in data["operations"]} + groups: dict[str, list[dict]] = {} + for node in data["nodes"]: + if node["category"] == "memory_entry" and node["name"].startswith("mc_"): + groups.setdefault(node["name"], []).append(node) + audit: dict[str, Any] = {"cells": [], "removed_nodes": 0, "removed_edges": 0} + aliases = {} + removed_ops = set() + removed_nodes = set() + extra_edges = [] + for identity, versions in groups.items(): + boundary = boundaries.get(identity) + if boundary is None: + continue + versions.sort(key=lambda node: node["version"]) + canonical = versions[0] + snapshots = [json.loads(node["value"]) for node in versions] + expected = { + key: boundary[key] for key in ("app_id", "project_id", "session_id") + } + if any( + node["metadata"].get("membership") != "exact" + or any(value.get(key) != item for key, item in expected.items()) + or value.get("message_ids") != boundary["message_ids"] + or {key: item for key, item in value.items() if key != "sender_ids"} + != {key: item for key, item in snapshots[0].items() if key != "sender_ids"} + for node, value in zip(versions, snapshots, strict=True) + ): + continue + boundary_ops = [ + op + for op in ops.values() + if op["category"] == "boundary_detection" + and op["op_name"] == f"boundary_detection_{identity}" + ] + if not boundary_ops: + continue + boundary_ops.sort(key=lambda op: op["metadata"].get("event_seq", 0)) + first = boundary_ops[0] + first_seq = first["metadata"].get("event_seq", 0) + old_ids = {node["full_node_id"] for node in versions} + for node in versions[1:]: + aliases[node["full_node_id"]] = canonical["full_node_id"] + removed_nodes.add(node["full_node_id"]) + removed_ops.update(op["op_id"] for op in boundary_ops[1:]) + value = snapshots[0] + value["sender_ids"] = boundary["sender_ids"] + encoded = json.dumps(value, ensure_ascii=False, indent=2, sort_keys=True) + value_changed = canonical["value"] != encoded + canonical["value"] = encoded + + buffer_inputs = [] + for node in data["nodes"]: + if node["category"] != "message_buffer": + continue + buffered = json.loads(node["value"]) + if any(buffered.get(key) != item for key, item in expected.items()): + continue + if not boundary["message_ids"] or not set(boundary["message_ids"]).issubset( + buffered["message_ids"] + ): + continue + seqs = [ + ops[edge["op_id"]]["metadata"].get("event_seq", 0) + for edge in data["edges"] + if edge["target_full_node_id"] == node["full_node_id"] + and ops[edge["op_id"]]["op_name"] + == f"memory_add_{expected['session_id']}" + ] + if seqs and max(seqs) <= first_seq: + buffer_inputs.append(node) + buffer = max(buffer_inputs, key=lambda node: node["version"], default=None) + added_buffer = False + if buffer is not None and not any( + edge["source_full_node_id"] == buffer["full_node_id"] + and edge["target_full_node_id"] in old_ids + for edge in data["edges"] + ): + template = next( + edge for edge in data["edges"] if edge["op_id"] == first["op_id"] + ) + edge = copy.deepcopy(template) + edge["source_full_node_id"] = buffer["full_node_id"] + edge["target_full_node_id"] = canonical["full_node_id"] + digest = hashlib.sha256( + f"{first['op_id']}:{buffer['full_node_id']}:{canonical['full_node_id']}".encode() + ).hexdigest()[:32] + edge["edge_id"] = f"edge-{digest}" + edge.setdefault("metadata", {}).update( + {"boundary_input": True, "construction_repaired": True} + ) + extra_edges.append(edge) + added_buffer = True + if len(versions) > 1 or len(boundary_ops) > 1 or added_buffer or value_changed: + audit["cells"].append( + { + "memcell_id": identity, + "removed_versions": len(versions) - 1, + "removed_boundary_ops": len(boundary_ops) - 1, + "buffer_input": buffer["full_node_id"] + if buffer is not None + else None, + "buffer_edge_added": added_buffer, + } + ) + original_edges = len(data["edges"]) + retained = [] + seen = set() + for edge in data["edges"]: + if edge["op_id"] in removed_ops: + continue + for field in ("source_full_node_id", "target_full_node_id"): + edge[field] = aliases.get(edge[field], edge[field]) + if edge["category"] == "boundary_detection": + pair = ( + edge["source_full_node_id"], + edge["target_full_node_id"], + edge["op_id"], + ) + if pair in seen or pair[0] == pair[1]: + continue + seen.add(pair) + retained.append(edge) + data["edges"] = retained + extra_edges + data["nodes"] = [ + node for node in data["nodes"] if node["full_node_id"] not in removed_nodes + ] + data["operations"] = [ + op for op in data["operations"] if op["op_id"] not in removed_ops + ] + audit["removed_nodes"] = len(removed_nodes) + audit["removed_edges"] = original_edges - len(retained) + audit["added_buffer_edges"] = len(extra_edges) + ExecNetwork.import_graph(result) + return result, audit + + +def repair_root(root: Path, *, apply: bool) -> dict: + """Use read-only SQLite boundary data and preserve every changed original.""" + database = root / ".index/sqlite/system.db" + with sqlite3.connect(f"file:{database}?mode=ro", uri=True) as connection: + connection.row_factory = sqlite3.Row + boundaries = { + row["memcell_id"]: { + key: row[key] for key in ("app_id", "project_id", "session_id") + } + | { + "message_ids": json.loads(row["message_ids_json"]), + "sender_ids": json.loads(row["sender_ids_json"]), + } + for row in connection.execute("SELECT * FROM memcell") + } + backup = root.parent / "construction_before_fix/memtrace" + results = [] + for path in sorted((root / "memtrace").glob("*.json")): + with portalocker.Lock(str(path) + ".lock", timeout=30): + raw = path.read_bytes() + original = json.loads(raw) + repaired, audit = repair_payload(original, boundaries) + if repaired == original: + continue + after = (json.dumps(repaired, ensure_ascii=False, indent=2) + "\n").encode() + if apply: + backup.mkdir(parents=True, exist_ok=True) + saved = backup / path.name + if saved.exists() and saved.read_bytes() != raw: + raise RuntimeError(f"A different backup already exists: {saved}") + saved.write_bytes(raw) + temporary = path.with_suffix(".construction.tmp") + temporary.write_bytes(after) + temporary.replace(path) + results.append( + { + "file": path.name, + "before_sha256": hashlib.sha256(raw).hexdigest(), + "after_sha256": hashlib.sha256(after).hexdigest(), + **audit, + } + ) + report = {"root": str(root), "applied": apply, "graphs": results} + if apply and results: + (root.parent / "construction_repair.json").write_text( + json.dumps(report, ensure_ascii=False, indent=2) + "\n" + ) + return report + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("roots", nargs="+", type=Path) + parser.add_argument("--apply", action="store_true") + args = parser.parse_args() + for root in args.roots: + report = repair_root(root, apply=args.apply) + print(json.dumps(report, ensure_ascii=False)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/pyproject.toml b/pyproject.toml index c978c905a..71a14fab9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "everos" -version = "1.7.0" +version = "1.7.1" description = "EverOS — local-first markdown memory framework for AI agents and user chats; lightweight, dev-friendly, small-team" license = {text = "Apache-2.0"} readme = "README.md" @@ -96,12 +96,13 @@ dependencies = [ # # All eight everalgo packages (including the four transitive ones) ship on one # contract line -- currently the 2026-11-13 line (everalgo-core 0.7.0), - # still on the `LLMClient.achat` contract of everalgo-core 0.6.0. The + # still on the `LLMClient.achat` contract of everalgo-core 0.6.0; + # everalgo-user-memory 0.10.1 only adds `LanguageDetector` to it. The # packages declare loose ranges on one another, so a fresh # `pip install everos` would otherwise mix lines the suite has never run # together. Pin every one with `==` and raise them together, with a run of # the release smoke against a PyPI-resolved install. - "everalgo-user-memory==0.9.0", + "everalgo-user-memory==0.10.1", "everalgo-agent-memory==0.6.0", "everalgo-rank==0.5.0", "everalgo-knowledge==0.3.0", @@ -113,6 +114,9 @@ dependencies = [ [project.optional-dependencies] multimodal = ["everalgo-parser[svg]==0.3.0"] # [svg] bundles cairosvg → SVG works by default +# MemTrace execution-graph tracer (infra/memtrace). Optional — the hooks are +# no-ops without it. Install with: uv sync --extra memtrace +memtrace = ["smartcomment>=0.1.2"] # Native OpenTelemetry tracing export. Optional — EverOS never imports these # unless [observability] is enabled. Install with: pip install everos[otel] otel = [ @@ -563,6 +567,9 @@ dev = [ # [otel] stack is always present in the dev / CI environment. "opentelemetry-sdk>=1.27.0", "opentelemetry-exporter-otlp-proto-http>=1.27.0", + # MemTrace tests must run in the default dev / CI environment without + # installing the optional [memtrace] extra explicitly. + "smartcomment>=0.1.2", "pymilvus>=3.0.0", # The NLTK tokenizer tests must run, not skip, so the [nltk] extra is present too. "nltk==3.9.4", diff --git a/src/everos/component/llm/openai_provider.py b/src/everos/component/llm/openai_provider.py index 1c2abc1f4..f20f9e666 100644 --- a/src/everos/component/llm/openai_provider.py +++ b/src/everos/component/llm/openai_provider.py @@ -18,7 +18,8 @@ or absent content raises (§3.4, §3.5); no choice and ``abort`` / ``error`` fail only this attempt. 4. ``_validate`` -- ``model_validate_json`` against the caller's - ``response_format``; a mismatch fails only this attempt (§7.1). + ``response_format``; a mismatch fails only this attempt (§7.1). A reply + that validates once its trailing commas are removed is returned repaired. 5. ``_request_valid_reply`` -- at most ``1 + invalid_reply_retries`` attempts of the identical request, each completion reported to the observer. """ @@ -243,8 +244,7 @@ async def _attempt( completion = await self._send(request) self._observe(completion, attempt) text = _check_upstream(completion) - _validate(text, response_format) - return text + return _validate(text, response_format) async def _send(self, request: dict[str, Any]) -> ChatCompletion: """Issue one SDK call; the SDK applies its own transport retries. @@ -327,18 +327,67 @@ def _check_upstream(completion: ChatCompletion) -> str: return choice.message.content -def _validate(text: str, response_format: type[BaseModel]) -> None: +def _validate(text: str, response_format: type[BaseModel]) -> str: """Check ``text`` against the caller's own model, as the operator will. + Some OpenAI-compatible models (in JSON mode or prompt-only) end an object + or array with a trailing comma, ``{"a": 1,}``, which strict JSON rejects + and which resending the identical request tends to reproduce. Such a + reply is validated once more with those commas removed. + + Returns: + The text the operator should parse: ``text``, or its repair. + Raises: - _AttemptFailedError: ``text`` does not validate; chained to the - ``ValidationError``. + _AttemptFailedError: Neither ``text`` nor its repair validates; + chained to the ``ValidationError`` of ``text``. """ try: response_format.model_validate_json(text) except ValidationError as exc: + repaired = _strip_trailing_commas(text) + if repaired != text and _validates(repaired, response_format): + return repaired raise _AttemptFailedError( f"reply failed validation against {response_format.__name__}", reason="invalid_reply", error_count=exc.error_count(), ) from exc + return text + + +def _validates(text: str, response_format: type[BaseModel]) -> bool: + try: + response_format.model_validate_json(text) + except ValidationError: + return False + return True + + +def _strip_trailing_commas(text: str) -> str: + """Drop each comma that only whitespace separates from a ``}`` or ``]``. + + Commas inside string literals are kept, escaped quotes included. + """ + out: list[str] = [] + comma: int | None = None # index in ``out`` of the last comma seen + in_string = escaped = False + for ch in text: + if in_string: + out.append(ch) + if escaped: + escaped = False + elif ch == "\\": + escaped = True + elif ch == '"': + in_string = False + continue + if ch.isspace(): + out.append(ch) + continue + if ch in "}]" and comma is not None: + del out[comma] + comma = len(out) if ch == "," else None + out.append(ch) + in_string = ch == '"' + return "".join(out) diff --git a/src/everos/config/__init__.py b/src/everos/config/__init__.py index f3de5b9af..57f6972a6 100644 --- a/src/everos/config/__init__.py +++ b/src/everos/config/__init__.py @@ -22,6 +22,7 @@ from .settings import DeciderSettings as DeciderSettings from .settings import EmbeddingSettings as EmbeddingSettings from .settings import IndexSettings as IndexSettings +from .settings import InputLogSettings as InputLogSettings from .settings import LanceDBSettings as LanceDBSettings from .settings import LLMClientSettings as LLMClientSettings from .settings import LLMSettings as LLMSettings @@ -49,6 +50,7 @@ "DeciderSettings", "EmbeddingSettings", "IndexSettings", + "InputLogSettings", "LLMClientSettings", "LLMSettings", "LLMTask", diff --git a/src/everos/config/default.toml b/src/everos/config/default.toml index ecde6b251..877290154 100644 --- a/src/everos/config/default.toml +++ b/src/everos/config/default.toml @@ -101,7 +101,7 @@ base_url = "https://openrouter.ai/api/v1" # Per-task overrides. Each [llm.] takes any [llm] field for that task only; # every field it leaves unset comes from [llm] (extra is replaced whole, never -# merged). Tasks: boundary, episode, summary, atomic_fact, profile, +# merged). Tasks: boundary, language, episode, summary, atomic_fact, profile, # reflection, agent_case, agent_skill, knowledge, search, decider. An unknown task # or field fails startup. Env: EVEROS_LLM____, e.g. # EVEROS_LLM__BOUNDARY__MODEL. `everos config show` prints what each task resolves to. @@ -109,6 +109,15 @@ base_url = "https://openrouter.ai/api/v1" # [llm.boundary] # model = "openai/gpt-4.1-nano" # +# The language task names each memcell's language before its episode is written, +# so the episode and everything extracted after it come out in that language. The +# fields it leaves unset among temperature (0), max_tokens (64), timeout_seconds (3), +# sdk_max_retries (0) and invalid_reply_retries (0) take these values of its own +# instead of [llm]'s; a failed or slow call only leaves the language to the episode +# model. 64 tokens leave no room to think first. +# [llm.language] +# model = "" +# # [llm.profile] # recommended: a reasoning model, thinking on # model = "" # timeout_seconds = 240.0 @@ -201,9 +210,12 @@ query_max_concurrent = 16 # Rerank provider. Override via env: # EVEROS_RERANK__PROVIDER, EVEROS_RERANK__MODEL, EVEROS_RERANK__API_KEY, # EVEROS_RERANK__BASE_URL -# `provider` picks the request-shape: +# Rerank endpoints share no request format, so `provider` picks the one +# base_url speaks: # - "deepinfra" -> POST {base_url}/{model} (DeepInfra inference API) # - "vllm" -> POST {base_url}/rerank (OpenAI-compat rerank endpoint) +# - "dashscope" -> POST {base_url}/api/v1/services/rerank/text-rerank/text-rerank +# (DashScope native API, gte-rerank-v2; base_url is the host) provider = "deepinfra" model = "Qwen/Qwen3-Reranker-4B" api_key = "" @@ -270,6 +282,15 @@ max_replays = 3 # Rows (any status) are deleted this many hours after they were created. row_retention_hours = 168.0 +[memorize.input_log] +# First PR ships the log disabled: enabling it also requires the deletion and +# purge path that removes a scope's lines (issue #537, second PR). +enabled = false +retention_days = 30 +# A line larger than this keeps text verbatim but replaces each base64 +# attachment with its length and SHA-256. +max_inline_bytes = 1048576 + [agent_memory] # Put everalgo's correctness gate in front of agent-case extraction: the # extraction LLM judges whether the work in a conversation was completed diff --git a/src/everos/config/settings.py b/src/everos/config/settings.py index d12658dd4..2051bac92 100644 --- a/src/everos/config/settings.py +++ b/src/everos/config/settings.py @@ -171,6 +171,7 @@ class LLMTask(StrEnum): """ BOUNDARY = "boundary" + LANGUAGE = "language" EPISODE = "episode" SUMMARY = "summary" ATOMIC_FACT = "atomic_fact" @@ -185,6 +186,15 @@ class LLMTask(StrEnum): LLM_TASK_DEFAULTS: Final[Mapping[LLMTask, Mapping[str, Any]]] = MappingProxyType( { + LLMTask.LANGUAGE: MappingProxyType( + { + "temperature": 0.0, + "max_tokens": 64, + "timeout_seconds": 3.0, + "sdk_max_retries": 0, + "invalid_reply_retries": 0, + } + ), LLMTask.DECIDER: MappingProxyType( { "timeout_seconds": 60.0, @@ -197,10 +207,17 @@ class LLMTask(StrEnum): """Fields a task takes from its own default, not from ``[llm]``, when its section leaves them unset. -Only the decider has any. It runs inside a search request, so one round's -deadline and retry budget are bounded by the caller waiting on it, not by -``[llm]``'s background-extraction values. The values are the ones ``[decider]`` -shipped with. The output cap is not among them: the decider inherits ``[llm]``'s +The language decision runs in the write path, before every memcell's episode, +and a failed one only leaves the episode's language to the episode model. So +it gets one bounded attempt: the reply is a one-word label (64 tokens, no room +for a model that thinks first), and a slow or unusable reply is given up after +3 seconds rather than resent -- the SDK retries are 0 so the deadline is the +whole wait. + +The decider runs inside a search request, so one round's deadline and retry +budget are bounded by the caller waiting on it, not by ``[llm]``'s +background-extraction values. The values are the ones ``[decider]`` shipped +with. The output cap is not among them: the decider inherits ``[llm]``'s ``max_tokens``, so a model that thinks before it answers has room to. ``sdk_max_retries`` is 0 because ``[decider].retries`` already retries at its own layer and the two multiply -- four decider attempts times three SDK @@ -379,11 +396,11 @@ class LLMSettings(LLMClientSettings): Configuring ``[llm]`` alone runs everything. A task section (:class:`LLMTaskSettings`) overrides any field for that one task; what it - leaves unset comes from ``[llm]``, except the decider fields listed in - :data:`LLM_TASK_DEFAULTS`. The section names are :class:`LLMTask`'s values; - an unknown section or field fails the load, naming the valid ones, except a - retired task's (:data:`RETIRED_LLM_TASKS`), which is dropped and reported in - :attr:`retired_tasks`. + leaves unset comes from ``[llm]``, except the language and decider fields + listed in :data:`LLM_TASK_DEFAULTS`. The section names are + :class:`LLMTask`'s values; an unknown section or field fails the load, + naming the valid ones, except a retired task's (:data:`RETIRED_LLM_TASKS`), + which is dropped and reported in :attr:`retired_tasks`. Env binding (via parent ``Settings``): EVEROS_LLM__MODEL, EVEROS_LLM__API_KEY, EVEROS_LLM__BASE_URL ... one @@ -393,6 +410,9 @@ class LLMSettings(LLMClientSettings): boundary: LLMTaskSettings = LLMTaskSettings() """Boundary detection: cutting a session's messages into memcells.""" + language: LLMTaskSettings = LLMTaskSettings() + """Naming each memcell's conversation language, which its episode and the + extractions after it are written in.""" episode: LLMTaskSettings = LLMTaskSettings() """Episode extraction from each memcell.""" summary: LLMTaskSettings = LLMTaskSettings() @@ -755,6 +775,19 @@ class AsyncQueueSettings(BaseModel): row_retention_hours: float = Field(default=7 * 24.0, gt=0, le=366 * 24.0) +class InputLogSettings(BaseModel): + """``/add`` input log (``[memorize.input_log]``). + + Disabled in the first PR that introduces it: enabling the log also + requires the deletion/purge path that removes a scope's lines, which + follows in the second PR (issue #537). + """ + + enabled: bool = False + retention_days: int = Field(default=30, ge=1) + max_inline_bytes: int = Field(default=1024 * 1024, ge=1) + + class MemorizeSettings(BaseModel): """Memorize use-case configuration. @@ -783,12 +816,14 @@ class MemorizeSettings(BaseModel): EVEROS_MEMORIZE__SESSION_LOCK_TIMEOUT_SECONDS EVEROS_MEMORIZE__DELETE_WAIT_SECONDS EVEROS_MEMORIZE__ASYNC_QUEUE__* (see :class:`AsyncQueueSettings`) + EVEROS_MEMORIZE__INPUT_LOG__* (see :class:`InputLogSettings`) """ mode: Literal["chat", "agent"] = "agent" session_lock_timeout_seconds: float = Field(default=360.0, gt=0) delete_wait_seconds: float = Field(default=10.0, gt=0) async_queue: AsyncQueueSettings = AsyncQueueSettings() + input_log: InputLogSettings = InputLogSettings() class AgentMemorySettings(BaseModel): diff --git a/src/everos/entrypoints/api/routes/memorize.py b/src/everos/entrypoints/api/routes/memorize.py index 6ea4fbf09..cd10e1ef3 100644 --- a/src/everos/entrypoints/api/routes/memorize.py +++ b/src/everos/entrypoints/api/routes/memorize.py @@ -76,6 +76,10 @@ async def add_memory( ) -> SuccessEnvelope[AddResponseData] | SuccessEnvelope[AcceptedResponseData]: """Add messages into the user-memory + agent-memory pipelines.""" app.purge.refuse_writes_to(req.app_id, req.project_id) + await app.memory.log_add( + req.model_dump(mode="json", exclude_unset=True), + request_id=request_id, + ) result = await app.memory.add( req.model_dump(exclude={"async_mode", "defer_extraction"}), request_id=request_id, diff --git a/src/everos/entrypoints/tui/demo/app.py b/src/everos/entrypoints/tui/demo/app.py index 1bb1cd50e..cb5496133 100644 --- a/src/everos/entrypoints/tui/demo/app.py +++ b/src/everos/entrypoints/tui/demo/app.py @@ -464,8 +464,11 @@ def _record_line(self, speaker: str, text: str) -> None: self.query_one("#conversation-log", Static).update( _conversation_text(self._log) ) - # Keep the newest line in view as the log grows past the panel height. - self.query_one("#conversation", VerticalScroll).scroll_end(animate=False) + # Keep the newest line in view. An anchored panel is pinned to the bottom + # by the layout pass that sizes the new line; a deferred scroll_end() can + # run before that pass and land on the stale height. Re-anchoring every + # line also brings back a reader who scrolled up. + self.query_one("#conversation", VerticalScroll).anchor() def _enter_done(self, message: Text) -> None: # Cap reached: keep the input usable (so /live, /quit still work and the diff --git a/src/everos/infra/memtrace/__init__.py b/src/everos/infra/memtrace/__init__.py new file mode 100644 index 000000000..2484f07aa --- /dev/null +++ b/src/everos/infra/memtrace/__init__.py @@ -0,0 +1,13 @@ +"""MemTrace file-tracking instrumentation (optional smartcomment tracing). + +Public facade for the MemTrace execution-graph tracer. Application bootstrap +injects :class:`MemTraceTracker` into the memory service for the +``/memory/add``, ``/memory/flush`` and ``/memory/search`` boundaries; see +:mod:`everos.infra.memtrace.tracker` for the tracing strategy and configuration. +""" + +from __future__ import annotations + +from .tracker import MemTraceTracker as MemTraceTracker + +__all__ = ["MemTraceTracker"] diff --git a/src/everos/infra/memtrace/answer_context.py b/src/everos/infra/memtrace/answer_context.py new file mode 100644 index 000000000..5da9a5428 --- /dev/null +++ b/src/everos/infra/memtrace/answer_context.py @@ -0,0 +1,47 @@ +"""Record the exact answer input separately from the retrieved response.""" + +from __future__ import annotations + +import json +from typing import Any + +from smartcomment import comment_op, comment_variable + + +def record_answer_context( + *, + query_id: str, + query_handle: Any, + retrieved: Any, + answer_context: str | None, + request_id: str, +) -> Any: + """Unknown answer input stays unknown; it is never inferred from retrieval.""" + snapshot = { + "id": f"answer-context-{query_id}", + "query_id": query_id, + "content": answer_context, + "observed": answer_context is not None, + } + handle = comment_variable( + snapshot, + to_runtime=True, + id_strategy=lambda value: value["id"], + encoding_fn=lambda value: json.dumps(value, ensure_ascii=False, sort_keys=True), + category="memory_context", + class_name="answer_context", + comment="This is the exact answer-model context, or null when unrecorded.", + ) + comment_op( + inputs=[h for h in (query_handle, retrieved) if h is not None], + outputs=[handle], + op_name=f"answer_context_assembly_{query_id}", + category="retrieval", + comment="Record the exact context supplied to the answer model for this query.", + metadata={ + "request_id": request_id, + "query_id": query_id, + "context_observed": answer_context is not None, + }, + ) + return handle diff --git a/src/everos/infra/memtrace/descriptions.py b/src/everos/infra/memtrace/descriptions.py new file mode 100644 index 000000000..6d8365baa --- /dev/null +++ b/src/everos/infra/memtrace/descriptions.py @@ -0,0 +1,101 @@ +"""Readable graph descriptions without exposing implementation identifiers. + +Stage names remain in metadata; comments describe the data and its transformation. +Export-only sentinel descriptions leave smartcomment's graph semantics unchanged. +""" + +from __future__ import annotations + +from typing import Any + +_KINDS = { + "episode": "conversation episodes", + "agent_case": "agent experiences", + "agent_skill": "agent skills", +} + +_STAGES = { + "sparse": ( + "Retrieve {kind} that match the query's keywords.", + "These {kind} match the query's keywords.", + ), + "dense": ( + "Retrieve {kind} with meanings similar to the query.", + "These {kind} are semantically similar to the query.", + ), + "single_route": ( + "Retrieve matching {kind} using the selected search method.", + "These {kind} were retrieved using the selected search method.", + ), + "maxsim_atomic": ( + "Rank {kind} by their strongest matching atomic facts.", + "These {kind} are ranked by their strongest matching atomic facts.", + ), + "rrf": ( + "Combine keyword and semantic rankings of {kind}.", + "These {kind} combine keyword and semantic search rankings.", + ), + "hierarchy": ( + "Score {kind} using episode and atomic-fact relevance.", + "These {kind} are scored using episode and atomic-fact relevance.", + ), + "filtered": ( + "Select {kind} that pass the relevance threshold and result limit.", + "These {kind} pass the relevance threshold and result limit.", + ), + "fusion": ( + "Combine retrieved {kind} into a ranked candidate list.", + "These {kind} form the combined search ranking.", + ), + "bridged_dense": ( + "Combine directly retrieved skills with skills linked to matching experiences.", + "These skills combine direct matches with links from matching experiences.", + ), + "agentic": ( + "Select relevant {kind} through iterative reasoning and retrieval.", + "These {kind} were selected through iterative reasoning and retrieval.", + ), +} + + +def stage_comments( + phase: str, kind: str, *, status: str = "success" +) -> tuple[str, str]: + """Return one-sentence operation and result descriptions for a search stage.""" + if kind == "unprocessed": + if status == "skipped": + return ( + "Skip pending-message retrieval because no session was specified.", + "This empty result belongs to a search without a session filter.", + ) + if status == "error": + return ( + "Record a failure to retrieve the session's pending messages.", + "This result records a failed read of the session's pending messages.", + ) + return ( + "Retrieve session messages that have not yet been stored as memories.", + "These session messages are waiting to be stored as memories.", + ) + operation, result = _STAGES.get( + phase, + ( + "Record the memory candidates produced during this search.", + "These memory candidates were produced during this search.", + ), + ) + label = _KINDS.get(kind, "memory entries") + return operation.format(kind=label), result.format(kind=label) + + +def describe_sentinels(data: dict[str, Any]) -> None: + """Describe built-in placeholders in an exported copy of a runtime graph.""" + payload = data.get("data", {}) + for node in payload.get("nodes", []): + if node.get("category") == "sentinel" and not node.get("comment"): + node["comment"] = ( + "This placeholder represents an operation's missing input or output." + ) + for op in payload.get("operations", []): + if op.get("category") == "sentinel" and not op.get("comment"): + op["comment"] = "This operation groups links recorded without a named step." diff --git a/src/everos/infra/memtrace/parsing.py b/src/everos/infra/memtrace/parsing.py new file mode 100644 index 000000000..96947a8dd --- /dev/null +++ b/src/everos/infra/memtrace/parsing.py @@ -0,0 +1,272 @@ +"""Parse EverOS memory markdown files into entry records. + +EverOS persists memory as human-readable markdown (the single source of +truth). Daily-log files (episodes, atomic facts, foresights, agent cases) +hold entry blocks delimited by ```` markers, each with +inline ``**field**: value`` lines and ``### Subject / ### Summary / +### Content`` sections. Single-file artifacts (``user.md``, ``agent.md``, +skill files) carry no entry markers and are treated as one whole-file +artifact instead. + +This module is a pure, dependency-free parser used by the MemTrace +file-tracking tracer (:mod:`everos.infra.memtrace.tracker`). +""" + +from __future__ import annotations + +import re +from dataclasses import dataclass, field +from pathlib import Path + +_ENTRY_OPEN = re.compile(r"") +_ENTRY_CLOSE = re.compile(r"") +_INLINE_FIELD = re.compile(r"^\*\*([A-Za-z_0-9]+)\*\*:\s*(.*)$") +_SECTION_HEAD = re.compile(r"^###\s+(.+?)\s*$") +_FRONTMATTER_LINE = re.compile(r"^([A-Za-z_0-9]+):\s*(.*)$") + +# Daily-log kinds whose writer emits kind-specific body sections instead of +# the generic ``### Content`` (atomic facts: ``### Fact``; foresights: +# ``### Foresight`` / ``### Evidence``; agent cases: ``### TaskIntent`` / +# ``### Approach`` / ``### KeyInsight``). Their sections are folded into +# ``content`` (in writer order) so the tracker's entry snapshot carries the +# entry body text; a generic ``### Content`` section, when present, wins. +_BODY_SECTIONS_BY_KIND: dict[str, tuple[str, ...]] = { + "atomic_fact": ("fact",), + "foresight": ("foresight", "evidence"), + "agent_case": ("taskintent", "approach", "keyinsight"), +} + +# Path components that identify the memory kind of a markdown file. +_KIND_BY_DIR = { + "episodes": "episode", + ".atomic_facts": "atomic_fact", + ".foresights": "foresight", + ".cases": "agent_case", + "knowledge": "knowledge", +} + +_DEFAULT_APP_DIR = "default_app" +_DEFAULT_PROJECT_DIR = "default_project" + + +@dataclass +class MemoryFileEntry: + """One ```` block parsed from a memory markdown file.""" + + entry_id: str + app_id: str + project_id: str + owner_id: str | None + session_id: str | None + timestamp: str | None + parent_type: str | None + parent_id: str | None + sender_ids: list[str] = field(default_factory=list) + subject: str = "" + summary: str = "" + content: str = "" + fields: dict[str, str] = field(default_factory=dict) + path: str = "" + kind: str = "memory_entry" + + +@dataclass +class MemoryFileSnapshot: + """Parsed view of one memory markdown file.""" + + path: str + kind: str + app_id: str + project_id: str + owner_id: str | None + frontmatter: dict[str, str] + entries: list[MemoryFileEntry] + body: str + + +def _parse_frontmatter(text: str) -> dict[str, str]: + """Naively parse the leading YAML frontmatter block (flat keys only).""" + if not text.startswith("---"): + return {} + end = text.find("\n---", 3) + if end == -1: + return {} + frontmatter: dict[str, str] = {} + for line in text[3:end].splitlines(): + m = _FRONTMATTER_LINE.match(line.strip()) + if m: + frontmatter[m.group(1)] = m.group(2).strip().strip("'\"") + return frontmatter + + +def _parse_sender_ids(raw: str) -> list[str]: + """Parse an inline ``sender_ids`` value such as ``[alice, bob]``.""" + raw = raw.strip() + if raw.startswith("[") and raw.endswith("]"): + raw = raw[1:-1] + return [part.strip() for part in raw.split(",") if part.strip()] + + +def _kind_from_path(path: Path) -> str: + """Derive the memory kind from the file's path components.""" + parts = set(path.parts) + if "skills" in parts: + # Only the main file represents the skill memory unit. Reference + # markdown files are attachments, not independent AgentSkills. + return "agent_skill" if path.name == "SKILL.md" else "skill_reference" + for part, kind in _KIND_BY_DIR.items(): + if part in parts: + return kind + if path.name == "user.md": + return "profile" + if path.name == "agent.md": + return "agent_profile" + return "memory_file" + + +def _owner_from_path(path: Path) -> str | None: + """Recover the owner id from a ``users//`` or ``agents//`` segment.""" + parts = path.parts + for marker in ("users", "agents"): + if marker in parts: + idx = parts.index(marker) + if idx + 1 < len(parts): + return parts[idx + 1] + return None + + +def _scope_from_path(path: Path) -> tuple[str, str]: + """Recover the app/project scope preceding a business root directory.""" + parts = path.parts + for marker in ("users", "agents", "knowledge"): + if marker not in parts: + continue + idx = parts.index(marker) + if idx < 2: + break + app_dir, project_dir = parts[idx - 2], parts[idx - 1] + app_id = "default" if app_dir == _DEFAULT_APP_DIR else app_dir + project_id = "default" if project_dir == _DEFAULT_PROJECT_DIR else project_dir + return app_id, project_id + # Legacy/unscoped test data and hand-written memory roots belong to the + # default business partition. + return "default", "default" + + +def _parse_entry_block( + entry_id: str, + block: str, + *, + path: str, + kind: str, + app_id: str, + project_id: str, + default_owner: str | None, +) -> MemoryFileEntry: + """Parse one entry block body (between the entry markers).""" + fields: dict[str, str] = {} + sections: dict[str, list[str]] = {} + current_section: str | None = None + for line in block.splitlines(): + field_match = _INLINE_FIELD.match(line.strip()) + section_match = _SECTION_HEAD.match(line.strip()) + if section_match: + current_section = section_match.group(1).strip().lower() + sections.setdefault(current_section, []) + elif field_match and current_section is None: + fields[field_match.group(1)] = field_match.group(2).strip() + elif current_section is not None: + sections[current_section].append(line) + subject = "\n".join(sections.get("subject", [])).strip() + summary = "\n".join(sections.get("summary", [])).strip() + content = "\n".join(sections.get("content", [])).strip() + if not content and kind in _BODY_SECTIONS_BY_KIND: + content = "\n\n".join( + body + for body in ( + "\n".join(sections.get(name, [])).strip() + for name in _BODY_SECTIONS_BY_KIND[kind] + ) + if body + ) + return MemoryFileEntry( + entry_id=entry_id, + app_id=app_id, + project_id=project_id, + owner_id=fields.get("owner_id") or default_owner, + session_id=fields.get("session_id") or None, + timestamp=fields.get("timestamp") or None, + parent_type=fields.get("parent_type") or None, + parent_id=fields.get("parent_id") or None, + sender_ids=_parse_sender_ids(fields.get("sender_ids", "")), + subject=subject, + summary=summary, + content=content, + fields=fields, + path=path, + kind=kind, + ) + + +def parse_memory_file( + path: Path, + *, + relative_to: Path | None = None, +) -> MemoryFileSnapshot: + """Parse one memory markdown file into a snapshot. + + Args: + path (`Path`): + The markdown file to parse. + relative_to (`Path | None`, optional): + Root used to compute the relative path stored on the snapshot. + + Returns: + `MemoryFileSnapshot`: + The parsed file: frontmatter, entry blocks (if any) and the + raw body. + """ + text = path.read_text(encoding="utf-8") + rel = str(path.relative_to(relative_to)) if relative_to else str(path) + kind = _kind_from_path(path) + frontmatter = _parse_frontmatter(text) + app_id, project_id = _scope_from_path(Path(rel)) + owner = ( + frontmatter.get("user_id") + or frontmatter.get("agent_id") + or _owner_from_path(path) + ) + + entries: list[MemoryFileEntry] = [] + opens = list(_ENTRY_OPEN.finditer(text)) + for i, open_match in enumerate(opens): + entry_id = open_match.group(1) + close_match = _ENTRY_CLOSE.search(text, open_match.end()) + block_end = ( + close_match.start() + if close_match + else (opens[i + 1].start() if i + 1 < len(opens) else len(text)) + ) + block = text[open_match.end() : block_end] + entries.append( + _parse_entry_block( + entry_id, + block, + path=rel, + kind=kind, + app_id=app_id, + project_id=project_id, + default_owner=owner, + ) + ) + + return MemoryFileSnapshot( + path=rel, + kind=kind, + app_id=app_id, + project_id=project_id, + owner_id=owner, + frontmatter=frontmatter, + entries=entries, + body=text, + ) diff --git a/src/everos/infra/memtrace/qa.py b/src/everos/infra/memtrace/qa.py new file mode 100644 index 000000000..7a506f603 --- /dev/null +++ b/src/everos/infra/memtrace/qa.py @@ -0,0 +1,268 @@ +"""Post-hoc QA-stage injection into exported MemTrace execution graphs. + +The file-tracking tracer (:mod:`everos.infra.memtrace.tracker`) records the +memory-side pipeline (messages -> entries -> retrieval -> context), but the +QA answer stage runs outside the EverOS server process — e.g. in the LoCoMo +drive script, which talks to the server over HTTP. This module closes that +gap offline: it loads an already-exported graph, appends the missing +``prompt`` / ``prediction`` / ``golden_answers`` / ``judge_response`` chain +onto the recorded query node, and re-exports the graph atomically. + +The injection uses exactly the same identity / category / operation +vocabulary as the live tracker hooks (:meth:`MemTraceTracker.on_answer` / +:meth:`MemTraceTracker.on_evaluation`), so a graph is coherent whether the +QA stage was recorded in-process or injected afterwards. Records whose +query node cannot be resolved are skipped with a log line, never an error. +""" + +from __future__ import annotations + +import hashlib +import json +import re +from pathlib import Path +from typing import Any + +import portalocker +from smartcomment import ( + comment_graph, + comment_op, + comment_session, + comment_variable, + enable_tracing, +) +from smartcomment.runtime import ExecNetwork + +from everos.core.observability.logging import get_logger + +from .answer_context import record_answer_context +from .descriptions import describe_sentinels +from .tracker import ( + _by_id, + _encode, + _latest_handle, + _qa_golden_snapshot, + _qa_judge_snapshot, + _qa_prediction_snapshot, + _qa_prompt_snapshot, + resolve_query_node, +) + +logger = get_logger(__name__) + +# One QA record per searched query. ``user_id`` + ``request_id`` locate the +# query node (``query-{user_id}-{request_id}``); the rest is the QA payload. +QaRecord = dict[str, Any] + + +def inject_qa_dir(graph_dir: Path, records: list[QaRecord]) -> dict[str, int]: + """Inject QA records into every exported graph under ``graph_dir``. + + Each graph is loaded once. A record must uniquely resolve across all files. + Use app/project scope and an exact query id when request ids are reused. + Identical records are idempotent; only changed graphs are re-exported. + The server must be stopped so its live graph cannot overwrite the injection. + + Args: + graph_dir: Directory holding the exported ``*.json`` graphs. + records: The QA records to inject (see :data:`QaRecord`). + + Returns: + `dict[str, int]`: + Per graph file name, how many records were injected into it. + """ + enable_tracing() + loaded: dict[Path, tuple[dict[str, Any], ExecNetwork]] = {} + injected: dict[str, int] = {} + for path in sorted(Path(graph_dir).glob("*.json")): + try: + data = json.loads(path.read_text(encoding="utf-8")) + graph = ExecNetwork.import_graph(data) + except Exception as exc: # an unreadable graph must not stop the batch + logger.warning( + "memtrace_inject_graph_unreadable", path=str(path), error=str(exc) + ) + continue + loaded[path] = (data, graph) + matched: dict[Path, list[tuple[QaRecord, str, Any]]] = {} + for record in records: + owner = str(record.get("user_id") or "") + request_id = str(record.get("request_id") or "") + candidates = [] + for path, (_data, graph) in loaded.items(): + if ( + not owner + or not request_id + or any( + record.get(field) is not None + and record[field] != graph.metadata.get(field) + for field in ("app_id", "project_id") + ) + ): + continue + resolved = resolve_query_node( + graph, + owner=owner, + request_id=request_id, + query_full_node_id=record.get("query_full_node_id"), + ) + if resolved is not None: + candidates.append((path, *resolved)) + if len(candidates) != 1: + logger.warning( + "memtrace_inject_query_not_unique", + user_id=owner, + request_id=request_id, + matches=len(candidates), + ) + continue + path, query_id, query_handle = candidates[0] + matched.setdefault(path, []).append((record, query_id, query_handle)) + for path, batch in matched.items(): + data, graph = loaded[path] + count = 0 + with ( + comment_graph(graph=graph), + comment_session(session_name="qa_injection", category="memory_retrieval"), + ): + for record, query_id, query_handle in batch: + count += _inject_one( + graph, record, query_id=query_id, query_handle=query_handle + ) + if count: + _export(path, data, graph) + injected[path.name] = count + return injected + + +def _inject_one( + graph: ExecNetwork, record: QaRecord, *, query_id: str, query_handle: Any +) -> bool: + """Inject one QA record's nodes and operations into the graph context.""" + request_id = str(record.get("request_id") or "") + op_metadata = { + "request_id": request_id, + "query_id": query_id, + "source": "qa_injection", + } + signature = hashlib.sha256(_encode(record).encode()).hexdigest() + prior = graph.search_operations( + name_pattern=( + f"^(answer_generation|inject_golden_answers|judge_answer)_" + f"{re.escape(query_id)}$" + ) + ) + if any(op.metadata.get("qa_record_digest") == signature for op in prior): + return False + op_metadata["qa_record_digest"] = signature + answer = record.get("answer") + if answer is not None: + prompt = record.get("prompt") + prompt_handle = ( + comment_variable( + _qa_prompt_snapshot(query_id, str(prompt)), + to_runtime=True, + id_strategy=_by_id, + encoding_fn=_encode, + category="prompt", + comment="The answer-generation prompt for this query.", + ) + if prompt is not None + else None + ) + prediction_handle = comment_variable( + _qa_prediction_snapshot(query_id, str(answer)), + to_runtime=True, + id_strategy=_by_id, + encoding_fn=_encode, + category="llm_response", + class_name="prediction", + comment="The answer generated from the retrieved memory context.", + ) + context_handle = record_answer_context( + query_id=query_id, + query_handle=query_handle, + retrieved=_latest_handle(graph, f"context:context-{query_id}"), + answer_context=record.get("answer_context"), + request_id=request_id, + ) + comment_op( + inputs=[ + handle + for handle in (query_handle, context_handle, prompt_handle) + if handle is not None + ], + outputs=[prediction_handle], + op_name=f"answer_generation_{query_id}", + category="response", + comment="Generate the final answer from the retrieved memory context.", + metadata=dict(op_metadata), + ) + golden_answers = record.get("golden_answers") + if golden_answers: + golden_handle = comment_variable( + _qa_golden_snapshot(query_id, golden_answers), + to_runtime=True, + id_strategy=_by_id, + encoding_fn=_encode, + category="golden_answers", + class_name="golden_answers", + comment="Reference answers injected by the evaluation batch.", + ) + comment_op( + inputs=[query_handle], + outputs=[golden_handle], + op_name=f"inject_golden_answers_{query_id}", + category="evaluation", + comment="Reference answers injected by the evaluation batch.", + metadata=dict(op_metadata), + ) + judge_response = record.get("judge_response") + judge_score = record.get("judge_score") + if judge_response is not None or judge_score is not None: + judge_handle = comment_variable( + _qa_judge_snapshot(query_id, judge_response, judge_score), + to_runtime=True, + id_strategy=_by_id, + encoding_fn=_encode, + category="judge_response", + class_name="judge_response", + comment="The judge verdict for this query's answer.", + ) + prediction_handle = _latest_handle( + graph, f"prediction:prediction-{query_id}" + ) + comment_op( + inputs=[ + handle + for handle in (prediction_handle, golden_handle, query_handle) + if handle is not None + ], + outputs=[judge_handle], + op_name=f"judge_answer_{query_id}", + category="evaluation", + comment="Judge the predicted answer against the reference answers.", + metadata=dict(op_metadata), + ) + return answer is not None or bool(golden_answers) + + +def _export(path: Path, original: dict[str, Any], graph: ExecNetwork) -> None: + """Re-export the graph atomically, preserving bench annotations. + + ``ExecNetwork.export_graph`` drops keys the schema does not know (the + MemTraceBench ``data.annotations`` block), so the annotations from the + file we just read are re-attached before the atomic tmp-write + replace, + under the same inter-process lock the tracker uses. + """ + data = graph.export_graph() + describe_sentinels(data) + annotations = original.get("data", {}).get("annotations") or [] + data.setdefault("data", {})["annotations"] = annotations + lock_path = path.with_suffix(".json.lock") + with portalocker.Lock(str(lock_path), mode="w", timeout=30): + tmp_path = path.with_suffix(".json.tmp") + tmp_path.write_text( + json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8" + ) + tmp_path.replace(path) diff --git a/src/everos/infra/memtrace/tracker.py b/src/everos/infra/memtrace/tracker.py new file mode 100644 index 000000000..30857b79b --- /dev/null +++ b/src/everos/infra/memtrace/tracker.py @@ -0,0 +1,3496 @@ +"""MemTrace file-tracking tracer for EverOS. + +This tracer combines **file tracking** with captured pipeline events. The +application injects it into :class:`everos.service.memory.MemoryService`, whose +add, flush and search methods call it at each request boundary. It diffs the +memory-root markdown files at every request +boundary. File observations capture terminal disk changes; they cannot recover +every intermediate construction/update/deletion between scans. Actual boundary +and episode extractor inputs/results come from request-local construction events. + +The ``/memory/search`` hook additionally records the per-stage candidate +pools of the retrieval pipeline (sparse / dense recall, fusion, rerank) +collected by :mod:`everos.memory.search.trace` — a zero-dependency +``ContextVar`` collector in the memory layer, so the ``smartcomment`` +dependency stays confined to this package. + +All observations are recorded into `smartcomment`_ execution graphs keyed by +``(app_id, project_id, user_id, session_id)``: one long-lived graph per user +per session and business scope, exported as MemTraceBench-compatible JSON to +``/memtrace/`` (default; ``EVEROS_MEMTRACE_DIR`` overrides). +Exports are batched: a request that dirties the same graph several times +(message recording plus an N-entry file diff) writes it out once per phase, +not once per change. + +The exported graphs double as the tracker's restart-recovery state. The +first post-restart diff restores unchanged entry snapshots from them and +reconciles downtime deletions — a tracked entry/artifact whose file +disappeared (or vanished from its file) while the process was down gets its +deletion mutation then. The message-content index is process-local; the +memcell rows persisted by boundary detection +(:class:`everos.infra.persistence.sqlite.Memcell`) carry the exact boundary +message ids, so post-restart extractions still re-link their buffer +messages (as identity-only stubs where the content index no longer covers +them). + +Configuration (environment variables, no settings-schema change): + +* ``EVEROS_MEMTRACE_ENABLED`` — ``1`` (default) records; ``0``/``false`` + turns every hook into a no-op. +* ``EVEROS_MEMTRACE_DIR`` — export directory (default ``/memtrace``). + +Identity / category vocabulary (aligned with MemTraceBench and the earlier +inline-instrumentation experiment): + +* variables: ``message`` (identity ``m___`` — the + ingest-side ``gen_message_id`` format, so ``/add`` messages stitch onto + the in-flight buffer messages returned by ``/search``), + ``message_buffer`` (``buffer--``), ``memory_entry`` + (memcell ``mc_*`` bare; entries ``{owner}_{entry_id}``; profile + ``profile-{owner}``), ``message & query`` + class ``query``, + ``memory_context`` + classes ``context`` / ``answer_context``, and request-local + ``retrieval_result`` + class ``retrieval_hit``; +* candidate pools: ``memory_context`` variables with identity + ``candidates_{kind}_{phase}-{query_id}`` — one per recorded search stage + (``sparse`` / ``dense`` / ``single_route`` / ``maxsim_atomic`` recall, + ``rrf`` / ``hierarchy`` / ``filtered`` / ``fusion`` / ``bridged_dense`` + fusion, ``agentic``); the pool snapshot carries the capped + ``ids`` / ``scores`` / ``sources`` lists. Only the last pool of each kind + expands candidates into request-local ``retrieval_hit`` nodes (identity-only + observations when content is unknown). Returned hits share membership edges; + a returned entry absent from the snapshot gets a ``response_only`` edge, + without changing the real pool's candidate list. Each pool also carries + a native-style ``class_name`` + (``sparse_retrieval_results`` / ``dense_retrieval_results`` / + ``hybrid_retrieval_results`` / ``reranked_results`` / …, see + ``_POOL_CLASS_NAMES``) so downstream attribution can group pools the way + the native MemTraceBench graphs do. The retrieval chain runs + ``query -> recall pools -> fusion pools -> last pool -> hits``; stage-less + searches keep the legacy ``query -> hits`` chain; +* pending session messages: one ``retrieval_result`` variable of class + ``retrieval_results`` (produced from the query and linked into the + assembled context) carries the pending messages without expanding message + nodes; profile tracing is disabled while + actual profile response content remains in the context snapshot; +* construction inputs: ``memcell -> cell-input`` is shared by episode and + foresight extraction, with separate ``cell-input -> extracted -> episode`` + and ``cell-input -> foresight`` branches and no extraction-start placeholders; +* boundary results: each boundary event records one ``boundary_outcome`` / + ``boundary_detection_result`` variable (identity + ``boundary-result--``, content-addressed by the sorted + boundary message ids, so a deferred add and the flush that later decides + over the same messages become versions of one node instead of duplicate + results on the same buffer version) carrying the detection status + plus the carved cell/message ids, chained + ``message_buffer -> boundary_detection_result -> memcell`` under a single + event-level ``boundary_detection`` operation (mirroring the native + membase/EverMemOS graphs); a detection that splits nothing ends in a + ``no_split_marker`` ``marker`` node; deferred adds also record an outcome + with ``decision=deferred`` and ``detection_performed=false``; +* operations: ``initialization`` (memory_add), ``boundary_detection``, + ``extraction`` (entry extractions and the request-level ``memory_flush`` + op), ``update`` / ``deletion`` (mutations), ``retrieval`` + (memory_search / context_assembly plus one explicit op per recorded + search stage — ``{kind}_{phase}_{seq}`` — with the stage's real + inputs/outputs, mirroring the native graphs). Failed requests still leave + a request-level op (``memory_add_*`` / ``memory_flush_*`` / + ``memory_search_*``) carrying ``status: "error"`` plus the exception + type / message, so a failed add / flush / search is visible in the graph. +* QA chain (native MemTraceBench answer/evaluation vocabulary): + :meth:`MemTraceTracker.on_answer` appends ``query (+ context + prompt) -> + prediction`` (``llm_response`` / class ``prediction`` node, + ``answer_generation_*`` op of category ``response``) and + :meth:`MemTraceTracker.on_evaluation` appends ``query -> + golden_answers`` (``inject_golden_answers_*``) and ``prediction + + golden_answers -> judge_response`` (``judge_answer_*``), both of + category ``evaluation``. Both hooks resolve the query node by request id + (honouring the ``-NNNN`` collision suffix) and are fail-safe no-ops for + unrecorded searches. For out-of-process QA (e.g. the LoCoMo drive + script), :mod:`everos.infra.memtrace.qa` injects the same chain into an + already-exported graph offline; ``examples/memtrace/inject_qa.py`` is the + CLI wrapper. + +Operation metadata vocabulary: every ``comment_op`` / ``comment_op_scope`` +/ ``comment_mutation`` carries ``event_seq`` (a process-local monotonic +sequence restoring the true observation order of the post-hoc records) and +``observed_at`` (UTC ISO timestamp). Ops produced by the file diff +additionally carry ``source: "file_diff"`` and ``trigger`` (``add`` / +``flush`` / ``search`` / ``shutdown`` — the hook that drove the diff); +request-level ops carry the request's ``request_id``. Stage pools carry +``total_count`` (pre-truncation pool size) and ``truncated`` so consumers +can tell a capped pool from a complete one. + +Graph files are named with one ``{safe}-{digest}`` fragment per key +component, joined by ``__``: ``safe`` keeps the name readable, the SHA-1 +``digest`` suffix keeps colliding ids (CJK names, ``a@b`` vs ``a_b``) in +distinct files. The naming scheme changed after the first instrumented +drop; files written with the old collision-prone names are orphans (the +raw ids cannot be recovered from them) — delete or ignore them, there is +no migration. + +Version-semantics notes: + +* Memcell nodes carry a ``membership`` marker: ``exact`` when the message + list came from the memcell's SQLite row, ``approximate`` when the + session heuristic had to substitute (row missing or unparsable), and + ``lookup_failed`` when the SQLite read itself failed — the heuristic + result is then marked as suspect rather than merely approximate. A + non-``exact`` node also carries ``membership_detail`` with the raw + status (``row_missing`` / ``invalid_payload`` / ``lookup_failed``). + SQLite also supplies their immutable sender ids. Each boundary is recorded + once — buffer (or message fallback) → ``boundary_detection_result`` → + memcell — then reused by entries. + Restart recovery reuses the exported boundary; an exact lookup can upgrade + an approximation without a later failed read downgrading it. +* Candidates are always recorded ``identity_only``; a search hit creates a + rich snapshot node only when the identity has none yet, otherwise it + reuses the existing node and the score rides on the edge metadata. A + later hit therefore never silently forks a candidate stub into a second + version. +* An entry that only moves files (log rotation, OME rewrite) updates the + file index without producing a new version — ``path`` never participates + in change detection. +* The in-memory message index is capped per session; the graph registry + itself grows with the number of scopes (an eviction policy is future + work). + +Every hook is fail-safe: tracing errors are logged and never propagate into +the memory request path. + +Deployment constraint: graph exports are guarded by an inter-process +``portalocker`` file lock, so concurrent writers cannot corrupt or +last-write-trample a file — but each process still holds its own in-memory +graph instance, so multi-worker deployments should either run a single +writer or point each worker at its own ``EVEROS_MEMTRACE_DIR``. +""" + +from __future__ import annotations + +import asyncio +import hashlib +import json +import os +import re +import uuid +from collections.abc import Callable, Mapping, Sequence +from pathlib import Path +from typing import TYPE_CHECKING, Any + +import portalocker + +from everos.core.observability.logging import get_logger +from everos.core.utils.datetime import from_iso_format, get_utc_now +from everos.infra.persistence.memory_root import MemoryRoot + +from .descriptions import describe_sentinels, stage_comments +from .parsing import MemoryFileEntry, MemoryFileSnapshot, parse_memory_file + +if TYPE_CHECKING: + from everos.memory.search.dto import ( + SearchRequest, + SearchResponse, + UnprocessedMessageDTO, + ) + from everos.memory.search.trace import SearchStageRecord + +logger = get_logger(__name__) + +try: # smartcomment is an optional tracing dependency. + from smartcomment import ( + comment_graph, + comment_link, + comment_mutation, + comment_op, + comment_op_scope, + comment_session, + comment_variable, + is_tracing_enabled, + ) + from smartcomment.runtime import ExecNetwork + + _SMARTCOMMENT_AVAILABLE = True +except ImportError: # pragma: no cover - exercised only without smartcomment + _SMARTCOMMENT_AVAILABLE = False + +# Directories that never hold memory markdown (indexes / staging / exports). +_SKIP_DIR_NAMES = {".index", ".tmp", "memtrace"} + +# Per-session cap on the tracked message index; the oldest identities (and +# their snapshots / binding state) are dropped when a session outgrows it. +_MAX_TRACKED_MESSAGES_PER_SESSION = 10_000 + +# Error messages recorded on failed-request ops are capped so a pathological +# exception cannot bloat the exported graph. +_MAX_ERROR_MESSAGE_CHARS = 500 + +_ENTRY_KIND_COMMENT = { + "episode": "A narrative memory extracted from a conversation.", + "atomic_fact": "A factual statement extracted from a conversation episode.", + "foresight": "A future expectation inferred from a conversation.", + "agent_case": "A stored account of an agent's approach to a task.", +} + +_ENTRY_FILE_KINDS = frozenset({"episode", "atomic_fact", "foresight", "agent_case"}) + +# app_id, project_id, owner_id, session bucket +GraphKey = tuple[str, str, str, str] +# app_id, project_id, smartcomment identity +ScopedIdentity = tuple[str, str, str] + + +def _encode(value: Any) -> str: + """Deterministically encode a variable snapshot as sorted JSON.""" + return json.dumps(value, ensure_ascii=False, indent=2, sort_keys=True) + + +def _encode_without_path(value: dict[str, Any]) -> str: + """Encode an entry snapshot for change detection, ignoring its location. + + A pure file move (log rotation, OME rewrite) must not register as an + entry update, so ``path`` never participates in the comparison. + """ + return _encode({key: item for key, item in value.items() if key != "path"}) + + +def _by_id(value: dict[str, Any]) -> str: + """Identity strategy: every traced variable is a dict carrying ``id``.""" + return str(value["id"]) + + +def _safe_name(raw: str) -> str: + """Make an id safe for use in file names.""" + return re.sub(r"[^A-Za-z0-9_.-]+", "_", raw) + + +def _scoped_name(raw: str) -> str: + """Readable-but-unique file-name fragment for one graph-key component. + + ``_safe_name`` alone folds ids like ``张三``/``李四`` or ``a@b``/``a_b`` + onto the same graph file; the SHA-1 digest suffix keeps every distinct + raw id in its own file while the truncated safe prefix stays readable. + """ + digest = hashlib.sha1(raw.encode()).hexdigest()[:8] + return f"{_safe_name(raw)[:40]}-{digest}" + + +def _hit_identity(owner: str, raw_id: str) -> str: + """Map a search-hit id to the tracker's entry identity. + + Entry identities are ``{owner}_{entry_id}``; some EverOS versions already + prefix the owner onto response ids, so only add the prefix when missing. + """ + return raw_id if raw_id.startswith(f"{owner}_") else f"{owner}_{raw_id}" + + +def _boundary_result_identity(session: str, message_ids: Sequence[str]) -> str: + """Content-addressed identity for a boundary-detection result. + + The same buffered messages can be observed twice: a deferred add records + an outcome without running detection and the flush that later drains them + records the real decision. Addressing the result by its sorted message + ids makes the second observation a new version of the same node instead + of a duplicate result hanging off the same buffer version. + """ + digest = hashlib.sha256(json.dumps(sorted(message_ids)).encode()).hexdigest() + return f"boundary-result-{session}-{digest[:16]}" + + +def resolve_query_node( + graph: ExecNetwork, + *, + owner: str, + request_id: str, + query_full_node_id: str | None = None, +) -> tuple[str, Any] | None: + """Resolve the recorded query node of one search by its request id. + + Repeated request ids require an exact ``query_full_node_id`` selector. + Return ``None`` for missing or ambiguous matches rather than choosing an + arbitrary execution. Matching uses snapshots, including after namespacing. + """ + matches = [] + for node in graph.search_variables(class_name="query"): + if query_full_node_id is not None and node.full_node_id != query_full_node_id: + continue + try: + snapshot = json.loads(node.value) + except (ValueError, TypeError): + continue + if ( + isinstance(snapshot, dict) + and snapshot.get("id") + and snapshot.get("request_id") == request_id + and snapshot.get("user_id") == owner + ): + matches.append(node) + if len(matches) != 1: + return None + node = matches[0] + return str(json.loads(node.value)["id"]), node + + +def _latest_handle(graph: ExecNetwork, full_name: str) -> Any | None: + """Return the latest-version handle of ``full_name``, or ``None``.""" + versions = graph.get_versions(full_name) + return versions[-1] if versions else None + + +def _qa_prompt_snapshot(query_id: str, prompt: str) -> dict[str, Any]: + """Snapshot of the answer-generation prompt of one query.""" + return {"id": f"prompt-{query_id}", "query_id": query_id, "prompt": prompt} + + +def _qa_prediction_snapshot(query_id: str, answer: str) -> dict[str, Any]: + """Snapshot of the predicted answer of one query.""" + return { + "id": f"prediction-{query_id}", + "query_id": query_id, + "answer": answer, + } + + +def _qa_golden_snapshot(query_id: str, golden_answers: Sequence[str]) -> dict[str, Any]: + """Snapshot of the reference answers of one query.""" + return { + "id": f"golden-{query_id}", + "query_id": query_id, + "answers": list(golden_answers), + } + + +def _qa_judge_snapshot( + query_id: str, judge_response: str | None, judge_score: float | None +) -> dict[str, Any]: + """Snapshot of the judge verdict of one query.""" + return { + "id": f"judge-{query_id}", + "query_id": query_id, + "response": judge_response, + "score": judge_score, + } + + +# Stage phases that draw candidates straight from a recall route — these +# pools hang directly off the query node. Every other phase (``rrf``, +# ``hierarchy``, ``filtered``, ``fusion``, ``bridged_dense``) is a fusion / +# filter stage and chains off the previous pools of the same kind. Mirrors +# the vocabulary in :mod:`everos.memory.search.trace`. +_RECALL_PHASES = frozenset( + {"sparse", "dense", "single_route", "maxsim_atomic", "agentic"} +) + +# Class names for stage-pool variables, aligned with the retrieval-result +# vocabulary of the native MemTraceBench graphs (the pool's ``category`` stays +# ``memory_context`` so existing consumers keep working; the class name lets +# downstream attribution group sparse / dense / fused / reranked pools the way +# the native graphs do). +_POOL_CLASS_NAMES: dict[str, str] = { + "sparse": "sparse_retrieval_results", + "dense": "dense_retrieval_results", + "rrf": "hybrid_retrieval_results", + "fusion": "hybrid_retrieval_results", + "bridged_dense": "hybrid_retrieval_results", + "hierarchy": "reranked_results", + "filtered": "reranked_results", + "single_route": "retrieval_results", + "maxsim_atomic": "retrieval_results", + "agentic": "agentic_results", +} + +# Per-input options used when a request-level flush op wires the session +# buffer in as its input (the unchanged snapshot reuses the buffer's +# existing node version). +_BUFFER_INPUT_OPTIONS: dict[str, Any] = { + "id_strategy": _by_id, + "encoding_fn": _encode, + "category": "message_buffer", + "comment": "The session message buffer drained by this flush.", +} + + +def _unprocessed_message_snapshot(message: UnprocessedMessageDTO) -> dict[str, Any]: + """Snapshot one in-flight buffer message returned alongside a search.""" + content = message.content + if not isinstance(content, str): + content = json.dumps(content, ensure_ascii=False) + return { + "id": message.id, + "content": content, + "name": message.sender_name or message.sender_id, + "role": message.role, + "session_id": message.session_id, + "timestamp": message.timestamp.isoformat(), + "source": "unprocessed_buffer", + } + + +class MemTraceTracker: + """File-tracking tracer that maintains one execution graph per + ``(app_id, project_id, user_id, session_id)``. + + The tracker keeps a snapshot index of every memory markdown entry under + the memory root. :meth:`on_memorize` and :meth:`on_search` are called by + the service layer at each request boundary; both first diff the markdown + tree (catching asynchronous OME writes) and then record the request + itself. Graphs are exported as MemTraceBench-compatible JSON, batched so + each graph is written at most once per request phase; the exports double + as restart-recovery and downtime-reconciliation state (see the module + docstring). + """ + + def __init__(self) -> None: + self._memcell_repo: Any = None + self._root: Path = MemoryRoot.resolve().root + env_enabled = os.environ.get("EVEROS_MEMTRACE_ENABLED", "1").lower() not in ( + "0", + "false", + "no", + ) + if env_enabled and not _SMARTCOMMENT_AVAILABLE: + logger.warning( + "memtrace_smartcomment_missing", + hint=( + "smartcomment is not installed; MemTrace hooks are no-ops " + "— install with `uv sync --extra memtrace`" + ), + ) + self._enabled: bool = _SMARTCOMMENT_AVAILABLE and env_enabled + self._out_dir = Path( + os.environ.get("EVEROS_MEMTRACE_DIR", str(self._root / "memtrace")) + ) + # (app_id, project_id, owner_id, session_bucket) -> graph / lock. + self._graphs: dict[GraphKey, ExecNetwork] = {} + self._locks: dict[GraphKey, asyncio.Lock] = {} + # Graphs dirtied since the last batched export. + self._dirty_keys: set[GraphKey] = set() + # Serialises the global filesystem index and its in-memory mirrors. + self._sync_lock = asyncio.Lock() + # Whether the first post-start diff (and with it the downtime + # deletion reconciliation) has run. + self._first_scan_done = False + # Scoped message index: (app, project, identity) -> snapshot dict. + self._messages: dict[ScopedIdentity, dict[str, Any]] = {} + # (app, project, session) -> ordered message identities ever added. + self._session_messages: dict[tuple[str, str, str], list[str]] = {} + # Message identities already bound to a memcell by boundary detection. + self._bound_messages: set[ScopedIdentity] = set() + # Graph key -> session-buffer snapshot dict (mutation target). + self._buffers: dict[GraphKey, dict[str, Any]] = {} + # Scoped entry identity -> snapshot dict / source file. + self._entries: dict[ScopedIdentity, dict[str, Any]] = {} + self._entry_file: dict[ScopedIdentity, str] = {} + # Scoped whole-file artifact identity -> snapshot dict / source file. + self._artifacts: dict[ScopedIdentity, dict[str, Any]] = {} + self._artifact_file: dict[ScopedIdentity, str] = {} + # File path -> (mtime_ns, size) at last parse. + self._file_state: dict[str, tuple[int, int]] = {} + self._query_seq: dict[GraphKey, int] = {} + # Process-local monotonic operation counter: restores the true + # observation order of the post-hoc records for downstream + # attribution (see ``_op_metadata``). + self._event_seq = 0 + self._entry_observations: dict[ScopedIdentity, dict[str, Any]] = {} + # Which hook is driving the current file diff (``add`` / ``flush`` / + # ``search`` / ``shutdown`` / ``manual``); set by ``_sync_files``, + # read by the file-diff op metadata. + self._trigger = "manual" + + # ── public hooks ───────────────────────────────────────────────────── + + def set_memcell_repo(self, repo: Any) -> None: + """Inject the application's memcell repository for exact boundary recovery.""" + self._memcell_repo = repo + + @property + def enabled(self) -> bool: + """Whether recording is active (smartcomment present + env toggle).""" + return self._enabled and is_tracing_enabled() + + @property + def out_dir(self) -> Path: + """Directory the MemTraceBench-compatible graph JSONs are exported to.""" + return self._out_dir + + @property + def smartcomment_available(self) -> bool: + """Whether the optional ``smartcomment`` dependency is importable.""" + return _SMARTCOMMENT_AVAILABLE + + def _op_metadata(self, extra: Mapping[str, Any] | None = None) -> dict[str, Any]: + """Build operation metadata with the shared ordering fields. + + Every ``comment_op`` / ``comment_op_scope`` / ``comment_mutation`` + goes through this helper so downstream attribution can sort the + post-hoc records back into true observation order (``event_seq``) + and wall-clock time (``observed_at``). + """ + self._event_seq += 1 + metadata: dict[str, Any] = { + "event_seq": self._event_seq, + "observed_at": get_utc_now().isoformat(), + } + if extra: + metadata.update(extra) + return metadata + + def _file_diff_metadata( + self, extra: Mapping[str, Any] | None = None + ) -> dict[str, Any]: + """Operation metadata for ops produced by the markdown file diff.""" + base: dict[str, Any] = { + "source": "file_diff", + "trigger": self._trigger, + "observation_only": True, + } + if extra: + base.update(extra) + return self._op_metadata(base) + + async def on_memorize( + self, + payload: dict[str, Any], + *, + is_final: bool, + defer_extraction: bool, + result: Any, + request_id: str | None = None, + construction_events: Sequence[Mapping[str, Any]] | None = None, + ) -> None: + """Record one ``/add`` or ``/flush`` request into the session graphs. + + Args: + payload: The service-layer payload ``{"session_id", "app_id", + "project_id", "messages": [...]}``. + is_final: ``True`` for flush requests. + defer_extraction: ``True`` when the add only buffered messages. + result: The :class:`MemorizeResult` returned by the pipeline. + request_id: The propagated request id (written onto the + request-level ops). + """ + if not self.enabled: + return + try: + session_id = str(payload.get("session_id", "")) + app_id = str(payload.get("app_id") or "default") + project_id = str(payload.get("project_id") or "default") + messages = payload.get("messages") or [] + buffer_loaded = next( + (e for e in construction_events or [] if e["phase"] == "buffer_loaded"), + None, + ) + buffer_persisted = next( + ( + e + for e in reversed(construction_events or []) + if e["phase"] == "buffer_persisted" + ), + None, + ) + if messages: + # Record the request's own messages first: an /add may + # already run boundary detection and extraction (writing + # episode markdown synchronously), and the + # entry -> memcell -> message links recorded by the file + # diff below need the message index populated. + await self._record_messages( + app_id, + project_id, + session_id, + messages, + defer_extraction=defer_extraction, + request_id=request_id, + buffer_loaded=buffer_loaded, + ) + # Diff the markdown tree; also catches background (OME) writes + # that landed since the previous request. A flush writes its + # episode markdown synchronously inside ``_memorize_locked``, so + # one diff after it observes everything. + await self._record_construction_events(construction_events, request_id) + if buffer_persisted is not None and not is_final: + await self._record_buffer_state(buffer_persisted, request_id=request_id) + await self._sync_files(trigger="flush" if is_final else "add") + if is_final: + # A flush is its own request-level event: record it even + # when the diff found nothing, so an empty flush stays + # distinguishable from "no request happened". + await self._record_flush( + app_id, + project_id, + session_id, + result=result, + request_id=request_id, + buffer_state=buffer_persisted + or ( + buffer_loaded + if buffer_loaded and not buffer_loaded["message_ids"] + else None + ), + ) + except Exception as exc: + logger.warning("memtrace_on_memorize_failed", error=str(exc)) + + async def on_memorize_error( + self, + payload: dict[str, Any], + *, + is_final: bool, + defer_extraction: bool, + error: BaseException, + request_id: str | None = None, + construction_events: Sequence[Mapping[str, Any]] | None = None, + ) -> None: + """Record a failed ``/add`` or ``/flush`` request. + + The business path re-raises after this hook; the graph keeps a + request-level op carrying ``status: "error"`` plus the exception + type/message, so failed extractions stay attributable. A best-effort + file diff runs first — the pipeline may have written partial + markdown before raising. + """ + if not self.enabled: + return + try: + session_id = str(payload.get("session_id", "")) + app_id = str(payload.get("app_id") or "default") + project_id = str(payload.get("project_id") or "default") + await self._record_construction_events(construction_events, request_id) + for event in construction_events or []: + if event["phase"] == "buffer_persisted": + await self._record_buffer_state(event, request_id=request_id) + await self._sync_files(trigger="flush" if is_final else "add") + error_metadata: dict[str, Any] = { + "session_id": session_id, + "is_final": is_final, + "defer_extraction": defer_extraction, + "status": "error", + "error_type": type(error).__name__, + "error_message": str(error)[:_MAX_ERROR_MESSAGE_CHARS], + "request_id": request_id, + } + if is_final: + op_name = f"memory_flush_{session_id}" + category = "extraction" + keys = self._flush_graph_keys(app_id, project_id, session_id) + else: + op_name = f"memory_add_{session_id}" + category = "initialization" + owners = { + str(m.get("sender_id") or "unknown") + for m in payload.get("messages", []) + } + keys = [ + (app_id, project_id, owner, session_id) + for owner in sorted(owners or {"unknown"}) + ] + for key in keys: + buffer = self._buffers.get(key) + + def record(buf: dict[str, Any] | None = buffer) -> None: + attempted = [ + comment_variable( + self._message_snapshot( + app_id, + project_id, + session_id, + str(message.get("sender_id") or "unknown"), + message, + idx, + ), + to_runtime=True, + id_strategy=_by_id, + encoding_fn=_encode, + category="message", + comment=( + "An input message submitted in a failed memory request." + ), + metadata={"acceptance": "attempted"}, + ) + for idx, message in enumerate(payload.get("messages") or []) + ] + comment_op( + op_name=op_name, + category=category, + comment=( + "The request failed; any partial markdown writes " + "were captured by the accompanying file diff." + ), + inputs=( + attempted + + ( + [(buf, dict(_BUFFER_INPUT_OPTIONS))] + if buf is not None + else [] + ) + ), + outputs=[], + metadata=self._op_metadata(error_metadata), + ) + + await self._update_graph( + key, + session_name=op_name, + session_category="memory_construction", + record=record, + ) + except Exception as exc: + logger.warning("memtrace_on_memorize_error_failed", error=str(exc)) + + async def on_search( + self, + req: SearchRequest, + resp: SearchResponse, + *, + stages: Sequence[SearchStageRecord] | None = None, + request_id: str | None = None, + ) -> None: + """Record one ``/search`` request: query -> pools -> hits -> context. + + Args: + req: The validated search request. + resp: The search response returned to the caller. + stages: Ordered per-stage candidate pools collected by + :func:`everos.memory.search.trace.collect_search_trace` + around the manager call; ``None``/empty keeps the legacy + ``query -> hits`` chain. + request_id: The propagated request id; forms the query node's + identity (``query-{owner}-{request_id}``). + """ + if not self.enabled: + return + try: + await self._sync_files(trigger="search") + await self._record_search(req, resp, stages=stages, request_id=request_id) + except Exception as exc: + logger.warning("memtrace_on_search_failed", error=str(exc)) + + async def on_search_error( + self, + req: SearchRequest, + *, + stages: Sequence[SearchStageRecord] | None = None, + error: BaseException, + request_id: str | None = None, + ) -> None: + """Record a failed ``/search`` request. + + The query node and whatever stage pools the collector gathered + before the failure (possibly none, possibly partial) are recorded + under a ``status: "error"`` retrieval op, so a failed query is + visible in the graph. The business path re-raises after this hook. + """ + if not self.enabled: + return + try: + await self._sync_files(trigger="search") + await self._record_search_error( + req, stages=stages, error=error, request_id=request_id + ) + except Exception as exc: + logger.warning("memtrace_on_search_error_failed", error=str(exc)) + + async def sync_now(self) -> None: + """Final sync for shutdown: one last diff plus a dirty-graph flush. + + Catches asynchronous writes (OME) that landed after the last + request and exports every graph dirtied since the previous flush. + Fail-safe like every other hook. + """ + if not self.enabled: + return + try: + await self._sync_files(trigger="shutdown") + await self._flush_dirty_graphs() + except Exception as exc: + logger.warning("memtrace_sync_now_failed", error=str(exc)) + + # ── QA recording (answer / evaluation) ───────────────────────────── + + async def on_answer( + self, + *, + app_id: str, + project_id: str, + owner: str, + request_id: str, + answer: str, + prompt: str | None = None, + answer_context: str | None = None, + bucket: str = "global", + query_full_node_id: str | None = None, + ) -> None: + """Record the answer stage of a previously recorded search. + + Appends the QA chain ``query (+ context + prompt) -> prediction`` + to the search's graph, using the native MemTraceBench vocabulary + (``llm_response`` / class ``prediction`` node, ``response`` + operation), so a retrieval-correct-but-answer-wrong failure stays + attributable (``ResponseError``). + + Args: + app_id: The app scope of the original search. + project_id: The project scope of the original search. + owner: The user the original search ran for. + request_id: The request id of the original search (the query + node identity is ``query-{owner}-{request_id}``). + answer: The answer text generated from the retrieved context. + prompt: The answer-generation prompt, when the caller has it. + bucket: The session bucket of the original search (``global`` + unless it ran with a ``session_id`` filter). + """ + if not self.enabled: + return + try: + key = (app_id, project_id, owner, bucket) + await self._update_graph( + key, + session_name=f"answer_generation_{owner}_{request_id}", + session_category="memory_retrieval", + record=lambda: self._record_answer( + key, + owner=owner, + request_id=request_id, + answer=answer, + prompt=prompt, + answer_context=answer_context, + query_full_node_id=query_full_node_id, + ), + ) + except Exception as exc: + logger.warning("memtrace_on_answer_failed", error=str(exc)) + + def _record_answer( + self, + key: GraphKey, + *, + owner: str, + request_id: str, + answer: str, + prompt: str | None, + answer_context: str | None = None, + query_full_node_id: str | None = None, + ) -> None: + """Record one ``answer_generation`` op inside the graph context.""" + graph = self._graphs[key] + resolved = resolve_query_node( + graph, + owner=owner, + request_id=request_id, + query_full_node_id=query_full_node_id, + ) + if resolved is None: + logger.warning( + "memtrace_qa_query_not_found", + owner=owner, + request_id=request_id, + bucket=key[3], + ) + return + query_id, query_handle = resolved + context_handle = _latest_handle(graph, f"context:context-{query_id}") + from .answer_context import record_answer_context + + context_handle = record_answer_context( + query_id=query_id, + query_handle=query_handle, + retrieved=context_handle, + answer_context=answer_context, + request_id=request_id, + ) + prompt_handle = ( + comment_variable( + _qa_prompt_snapshot(query_id, prompt), + to_runtime=True, + id_strategy=_by_id, + encoding_fn=_encode, + category="prompt", + comment="The answer-generation prompt for this query.", + ) + if prompt is not None + else None + ) + prediction_handle = comment_variable( + _qa_prediction_snapshot(query_id, answer), + to_runtime=True, + id_strategy=_by_id, + encoding_fn=_encode, + category="llm_response", + class_name="prediction", + comment="The answer generated from the retrieved memory context.", + ) + comment_op( + inputs=[ + handle + for handle in (query_handle, context_handle, prompt_handle) + if handle is not None + ], + outputs=[prediction_handle], + op_name=f"answer_generation_{query_id}", + category="response", + comment="Generate the final answer from the retrieved memory context.", + metadata=self._op_metadata( + {"request_id": request_id, "query_id": query_id} + ), + ) + + async def on_evaluation( + self, + *, + app_id: str, + project_id: str, + owner: str, + request_id: str, + golden_answers: Sequence[str], + judge_response: str | None = None, + judge_score: float | None = None, + bucket: str = "global", + query_full_node_id: str | None = None, + ) -> None: + """Record the evaluation stage of a previously recorded search. + + Appends ``query -> golden_answers`` (``inject_golden_answers``) + and, when a verdict is supplied, + ``prediction + golden_answers -> judge_response`` (``judge_answer``) + to the search's graph — the native MemTraceBench ``evaluation`` + operation vocabulary. + """ + if not self.enabled: + return + try: + key = (app_id, project_id, owner, bucket) + await self._update_graph( + key, + session_name=f"evaluation_{owner}_{request_id}", + session_category="memory_retrieval", + record=lambda: self._record_evaluation( + key, + owner=owner, + request_id=request_id, + golden_answers=golden_answers, + judge_response=judge_response, + judge_score=judge_score, + query_full_node_id=query_full_node_id, + ), + ) + except Exception as exc: + logger.warning("memtrace_on_evaluation_failed", error=str(exc)) + + def _record_evaluation( + self, + key: GraphKey, + *, + owner: str, + request_id: str, + golden_answers: Sequence[str], + judge_response: str | None, + judge_score: float | None, + query_full_node_id: str | None = None, + ) -> None: + """Record one ``inject_golden_answers`` / ``judge_answer`` pair.""" + graph = self._graphs[key] + resolved = resolve_query_node( + graph, + owner=owner, + request_id=request_id, + query_full_node_id=query_full_node_id, + ) + if resolved is None: + logger.warning( + "memtrace_qa_query_not_found", + owner=owner, + request_id=request_id, + bucket=key[3], + ) + return + query_id, query_handle = resolved + golden_handle = comment_variable( + _qa_golden_snapshot(query_id, golden_answers), + to_runtime=True, + id_strategy=_by_id, + encoding_fn=_encode, + category="golden_answers", + class_name="golden_answers", + comment="Reference answers injected by the evaluation batch.", + ) + comment_op( + inputs=[query_handle], + outputs=[golden_handle], + op_name=f"inject_golden_answers_{query_id}", + category="evaluation", + comment="Reference answers injected by the evaluation batch.", + metadata=self._op_metadata( + {"request_id": request_id, "query_id": query_id} + ), + ) + if judge_response is None and judge_score is None: + return + judge_handle = comment_variable( + _qa_judge_snapshot(query_id, judge_response, judge_score), + to_runtime=True, + id_strategy=_by_id, + encoding_fn=_encode, + category="judge_response", + class_name="judge_response", + comment="The judge verdict for this query's answer.", + ) + prediction_handle = _latest_handle(graph, f"prediction:prediction-{query_id}") + comment_op( + inputs=[ + handle + for handle in (prediction_handle, golden_handle, query_handle) + if handle is not None + ], + outputs=[judge_handle], + op_name=f"judge_answer_{query_id}", + category="evaluation", + comment="Judge the predicted answer against the reference answers.", + metadata=self._op_metadata( + {"request_id": request_id, "query_id": query_id} + ), + ) + + async def _record_construction_events( + self, + events: Sequence[Mapping[str, Any]] | None, + request_id: str | None, + ) -> None: + """Replay captured boundary inputs and actual extraction results. + + Event timestamps describe the actual boundary/extractor return, unlike + file observations. Background evolution still requires independent events. + """ + for event in events or []: + phase = event["phase"] + if phase == "extraction_attempt": + continue + if phase == "buffer_loaded": + await self._record_buffer_state(event, request_id=request_id) + continue + if phase == "buffer_persisted": + # Replay tails after their boundary/extraction inputs. Successful + # flushes use the request-level flush mutation for this step. + continue + if phase == "boundary": + await self._record_boundary_event(event, request_id) + continue + app, project, session = ( + str(event[field]) for field in ("app_id", "project_id", "session_id") + ) + for cell in [event]: + owners = cell.get("owners", []) + for owner in owners or ["unknown"]: + key = (app, project, owner, session) + mid = str(cell.get("id") or cell.get("memcell_id")) + metadata = { + "source": "construction_event", + "request_id": request_id, + "observed_at": event["observed_at"], + "phase": phase, + } + + def record( + cell: Mapping[str, Any] = cell, + key: GraphKey = key, + mid: str = mid, + phase: str = phase, + metadata: dict[str, Any] = metadata, + ) -> None: + graph = self._graphs[key] + result_id = f"extracted-{mid}-{key[2]}-{request_id or 'direct'}" + if phase == "persisted_episode": + result = _latest_handle(graph, result_id) + if result is not None: + identity = f"{key[2]}_{cell['entry_id']}" + self._entry_observations[(key[0], key[1], identity)] = { + **metadata, + "source_node": result.full_node_id, + } + elif phase == "extraction_result": + parent = _latest_handle(graph, f"cell-input-{mid}") + result = comment_variable( + { + "id": result_id, + "content": cell.get("content"), + "status": phase, + }, + to_runtime=True, + id_strategy=_by_id, + encoding_fn=_encode, + category="extraction_result", + comment=( + "The episode text extracted from the selected " + "conversation content." + ), + ) + comment_op( + inputs=[parent] if parent is not None else [], + outputs=[result], + op_name=f"{phase}_{mid}", + category="extraction", + comment=( + "Extract an episode from the selected " + "conversation content." + ), + metadata=self._op_metadata(metadata), + ) + + await self._update_graph( + key, + session_name=f"construction_{phase}", + session_category="memory_construction", + record=record, + export=False, + ) + + async def _record_boundary_event( + self, + event: Mapping[str, Any], + request_id: str | None, + ) -> None: + """Record the boundary decision and its message-dependent cell creation. + + Connect the consumed buffer through its structured boundary result to + each produced memcell. Model decisions stay on the result; deferred + requests retain a service outcome without implying a model call. + """ + app, project, session = ( + str(event[field]) for field in ("app_id", "project_id", "session_id") + ) + cells = list(event.get("cells", [])) + by_owner: dict[str, list[Mapping[str, Any]]] = {} + for cell in cells: + for sender in cell.get("sender_ids", []) or ["unknown"]: + by_owner.setdefault(str(sender), []).append(cell) + if not by_owner: + # A no-split detection has no cells to derive owners from; record + # it in every graph that tracks a buffer for this session. + by_owner = { + key[2]: [] for key in self._flush_graph_keys(app, project, session) + } + tag = request_id or uuid.uuid4().hex + deferred = event.get("reason") == "deferred" + detection = event.get("detection") or {} + for owner in sorted(by_owner): + key = (app, project, owner, session) + owner_cells = by_owner[owner] + + def record( + key: GraphKey = key, + owner: str = owner, + owner_cells: list[Mapping[str, Any]] = owner_cells, + ) -> None: + graph = self._graphs[key] + metadata: dict[str, Any] = { + "source": "construction_event", + "request_id": request_id, + "observed_at": event["observed_at"], + "phase": "boundary", + "status": event.get("status"), + "reason": event.get("reason"), + "detection_performed": event.get("detection_performed"), + } + message_ids = detection.get("message_ids") or list( + dict.fromkeys( + message_id + for cell in owner_cells + for message_id in cell.get("message_ids", []) + ) + ) + if not owner_cells: + current_buffer = _latest_handle(graph, f"buffer-{session}-{owner}") + if current_buffer is not None: + message_ids = list( + json.loads(current_buffer.raw_value)["message_ids"] + ) + result_identity = _boundary_result_identity(session, message_ids) + with comment_op_scope( + op_name=f"boundary_detection_{session}_{tag}", + category="boundary_detection", + comment=( + "Keep the session messages buffered because extraction " + "was deferred." + if deferred + else "Determine whether the buffered conversation can be " + "split into memory units." + ), + metadata=self._op_metadata(metadata), + ): + result = comment_variable( + { + "id": result_identity, + "session_id": session, + "request_id": request_id, + "status": event.get("status"), + "decision": ( + "deferred" + if deferred + else "split" + if owner_cells + else "no_split" + ), + "detection_performed": event.get("detection_performed"), + "cell_ids": [ + str(cell.get("id") or cell.get("memcell_id")) + for cell in owner_cells + ], + "message_ids": message_ids, + **( + { + "model_result": detection["model_result"], + "is_final": detection["is_final"], + "mode": detection["mode"], + } + if detection + else {} + ), + }, + to_runtime=True, + id_strategy=_by_id, + encoding_fn=_encode, + category=( + "llm_response" + if detection.get("model_result") is not None + else "boundary_outcome" + ), + class_name="boundary_detection_result", + comment=( + "The messages remain buffered until a later request " + "runs boundary detection." + if deferred + else "The model's boundary decision and the resulting " + "message groups, including any final flush closure." + if detection.get("model_result") is not None + else "The boundary stage outcome records whether " + "the conversation was split into memory units." + ), + ) + buffer_handle = next( + ( + handle + for handle in reversed( + graph.get_versions(f"buffer-{session}-{owner}") + ) + if message_ids + and set(message_ids).issubset( + json.loads(handle.raw_value)["message_ids"] + ) + ), + None, + ) + if buffer_handle is None and not message_ids: + buffer_handle = _latest_handle( + graph, f"buffer-{session}-{owner}" + ) + if buffer_handle is not None: + comment_op( + inputs=[buffer_handle], + outputs=[result], + reuse_op=True, + comment=( + "Record that boundary detection was deferred " + "for these buffered messages." + if deferred + else "Assess conversation boundaries for these " + "buffered session messages." + ), + metadata={"boundary_input": True}, + ) + else: + # Mirror the memcell fallback: link the analysed + # messages directly when no covering buffer version + # was recorded. + linked: set[str] = set() + for message_id in message_ids: + if message_id in linked: + continue + linked.add(message_id) + snapshot = self._messages.get((app, project, message_id)) + message_handle = comment_variable( + snapshot + if snapshot is not None + else {"id": message_id}, + to_runtime=True, + id_strategy=_by_id, + encoding_fn=_encode, + identity_only=snapshot is None, + category="message", + comment=( + "A session message analysed by boundary detection." + ), + ) + comment_link( + source=message_handle, + target=result, + comment=( + "Feed this buffered message into boundary " + "detection." + ), + ) + if not owner_cells: + marker = comment_variable( + { + "id": f"no-split-{session}-{tag}", + "reason": "deferred" if deferred else "no_split", + }, + to_runtime=True, + id_strategy=_by_id, + encoding_fn=_encode, + category="marker", + class_name="no_split_marker", + comment=( + "No memory unit was created, so the current " + "messages remain buffered." + ), + ) + comment_link( + source=result, + target=marker, + comment=( + "Retain the current messages for later processing " + "because no memory unit was created." + ), + ) + for cell in owner_cells: + mid = str(cell.get("id") or cell.get("memcell_id")) + entry = MemoryFileEntry( + entry_id=mid, + app_id=key[0], + project_id=key[1], + owner_id=key[2], + session_id=key[3], + timestamp=None, + parent_type="memcell", + parent_id=mid, + ) + parent = self._record_parent( + entry, + key[2], + message_ids=list(cell["message_ids"]), + sender_ids=list(cell["sender_ids"]), + observed_event=metadata, + boundary_result=result, + ) + self._record_cell_input( + key, + mid, + parent, + content=cell["content"], + metadata=self._op_metadata(metadata), + ) + + await self._update_graph( + key, + session_name="construction_boundary", + session_category="memory_construction", + record=record, + export=False, + ) + + def _record_cell_input( + self, + key: GraphKey, + memcell_id: str, + parent: Any, + *, + content: Any, + metadata: Mapping[str, Any], + ) -> Any: + """Reuse a cell's raw input across its independent memory extractors.""" + existing = _latest_handle(self._graphs[key], f"cell-input-{memcell_id}") + if existing is not None and ( + content is None or json.loads(existing.raw_value).get("content") == content + ): + return existing + value = comment_variable( + {"id": f"cell-input-{memcell_id}", "content": content}, + to_runtime=True, + id_strategy=_by_id, + encoding_fn=_encode, + category="construction_input", + comment=( + "The original conversation content supplied to memory extraction." + if content is not None + else "The original extraction input is unavailable for this memcell." + ), + metadata={"content_observed": content is not None}, + ) + comment_op( + inputs=[parent], + outputs=[value], + op_name=f"observe_cell_{memcell_id}", + category="boundary_detection", + comment="Record the conversation content selected for memory extraction.", + metadata=dict(metadata), + ) + return value + + # ── request recording ──────────────────────────────────────────────── + + async def _record_messages( + self, + app_id: str, + project_id: str, + session_id: str, + messages: list[dict[str, Any]], + *, + defer_extraction: bool = False, + request_id: str | None = None, + buffer_loaded: Mapping[str, Any] | None = None, + ) -> None: + """Record the complete add batch in each participating sender's graph. + + A session buffer contains the conversation, including assistant + replies. Owner partitioning must not drop other senders' inputs. + """ + senders: dict[str, None] = {} + snapshots: list[dict[str, Any]] = [] + for idx, message in enumerate(messages): + sender = str(message.get("sender_id") or "unknown") + snapshot = self._message_snapshot( + app_id, project_id, session_id, sender, message, idx + ) + scoped_id = (app_id, project_id, snapshot["id"]) + self._messages[scoped_id] = snapshot + known = self._session_messages.setdefault( + (app_id, project_id, session_id), [] + ) + if snapshot["id"] not in known: + known.append(snapshot["id"]) + if len(known) > _MAX_TRACKED_MESSAGES_PER_SESSION: + stale = known[:-_MAX_TRACKED_MESSAGES_PER_SESSION] + del known[:-_MAX_TRACKED_MESSAGES_PER_SESSION] + for stale_id in stale: + self._messages.pop((app_id, project_id, stale_id), None) + self._bound_messages.discard((app_id, project_id, stale_id)) + senders[sender] = None + snapshots.append(snapshot) + + for sender in senders: + key = (app_id, project_id, sender, session_id) + + def record( + snaps: list[dict[str, Any]] = snapshots, + graph_key: GraphKey = key, + ) -> None: + handles = [ + comment_variable( + snap, + to_runtime=True, + id_strategy=_by_id, + encoding_fn=_encode, + category="message", + comment=( + "An input message fed into the EverOS memory " + "pipeline via /memory/add." + ), + ) + for snap in snaps + ] + op_metadata: dict[str, Any] = { + "session_id": graph_key[3], + "message_count": len(snaps), + "request_id": request_id, + } + if defer_extraction: + op_metadata["defer_extraction"] = True + buffer = self._ensure_buffer( + graph_key, + initial_ids=list(buffer_loaded["before_message_ids"]) + if buffer_loaded + else None, + ) + with comment_mutation( + target=buffer, + inputs=handles, + id_strategy=_by_id, + encoding_fn=_encode, + category="message_buffer", + comment="The session messages held in the buffer at this point.", + mutation_name=f"memory_add_{graph_key[3]}", + mutation_category="initialization", + mutation_comment="Buffer input messages via /memory/add.", + mutation_metadata=self._op_metadata(op_metadata), + ): + buffer["message_ids"] = ( + list(buffer_loaded["message_ids"]) + if buffer_loaded + else list( + dict.fromkeys( + buffer["message_ids"] + [s["id"] for s in snaps] + ) + ) + ) + + await self._update_graph( + key, + session_name=f"memory_add_{session_id}", + session_category="memory_construction", + record=record, + export=False, + ) + + def _ensure_buffer( + self, + key: GraphKey, + *, + initial_ids: list[str] | None = None, + ) -> dict[str, Any]: + """Restore the latest buffer or register its real initial state.""" + buffer = self._buffers.get(key) + if buffer is None: + existing = _latest_handle(self._graphs[key], f"buffer-{key[3]}-{key[2]}") + if existing is not None: + buffer = json.loads(existing.raw_value) + else: + buffer = { + "id": f"buffer-{key[3]}-{key[2]}", + "app_id": key[0], + "project_id": key[1], + "session_id": key[3], + "owner_id": key[2], + "message_ids": list(initial_ids or []), + } + comment_variable( + buffer, + to_runtime=True, + id_strategy=_by_id, + encoding_fn=_encode, + category="message_buffer", + comment="The session messages held in the buffer at this point.", + ) + self._buffers[key] = buffer + return buffer + + async def _record_buffer_state( + self, + event: Mapping[str, Any], + *, + request_id: str | None, + ) -> None: + """Reconcile a real loaded buffer or record its persisted tail.""" + app, project, session = ( + str(event[field]) for field in ("app_id", "project_id", "session_id") + ) + owners = {key[2] for key in self._flush_graph_keys(app, project, session)} + owners.update(str(s or "unknown") for s in event.get("sender_ids", [])) + if len(owners) > 1: + owners.discard("unknown") + for owner in sorted(owners): + key = (app, project, owner, session) + + def record(key: GraphKey = key) -> None: + buffer = self._ensure_buffer( + key, + initial_ids=list(event.get("before_message_ids", [])), + ) + ids = list(event["message_ids"]) + if buffer["message_ids"] == ids: + return + with comment_mutation( + target=buffer, + id_strategy=_by_id, + encoding_fn=_encode, + category="message_buffer", + comment="The session messages held in the buffer at this point.", + mutation_name=f"{event['phase']}_{session}", + mutation_category="update", + mutation_comment="Record the real boundary-detection buffer state.", + mutation_metadata=self._op_metadata( + { + "source": "construction_event", + "request_id": request_id, + "observed_at": event["observed_at"], + } + ), + ): + buffer["message_ids"] = ids + + await self._update_graph( + key, + session_name=f"buffer_state_{session}", + session_category="memory_construction", + record=record, + export=False, + ) + + def _message_snapshot( + self, + app_id: str, + project_id: str, + session_id: str, + sender: str, + message: dict[str, Any], + idx: int, + ) -> dict[str, Any]: + """Build the deterministic snapshot dict for one input message. + + The identity replicates ``gen_message_id(session_id, ts_ms, idx)`` + from ``everos.memory.extract.ingest.id_gen`` — duplicated here + because the layered architecture forbids infra importing the memory + layer — so ``/add`` messages share the buffer-message nodes recorded + by the ``/search`` hook. ``idx`` is the message's position in the + request payload, matching ingest. Numeric timestamps auto-detect + seconds vs milliseconds and ISO-8601 strings are parsed, all + normalising onto the same millisecond identity. A message without a + parseable timestamp gets a stable fallback identity + (``m__invalid_``) flagged with ``timestamp_invalid`` + and the raw value, instead of being silently dropped and breaking + the memcell-membership chain. + """ + content = message.get("content") + if not isinstance(content, str): + content = json.dumps(content, ensure_ascii=False) + raw_timestamp = message.get("timestamp") + try: + moment = from_iso_format(raw_timestamp) + except (TypeError, ValueError): + logger.warning( + "memtrace_message_without_timestamp", + session_id=session_id, + idx=idx, + ) + return { + "id": f"m_{session_id}_invalid_{idx:03d}", + "app_id": app_id, + "project_id": project_id, + "content": content, + "name": sender, + "role": message.get("role", "user"), + "timestamp": None, + "timestamp_invalid": True, + "raw_timestamp": ( + raw_timestamp + if raw_timestamp is None + or isinstance(raw_timestamp, str | int | float | bool) + else str(raw_timestamp) + ), + } + timestamp_ms = int(moment.timestamp() * 1000) + return { + "id": f"m_{session_id}_{timestamp_ms}_{idx:03d}", + "app_id": app_id, + "project_id": project_id, + "content": content, + "name": sender, + "role": message.get("role", "user"), + "timestamp": moment.isoformat(), + } + + def _flush_graph_keys( + self, app_id: str, project_id: str, session_id: str + ) -> list[GraphKey]: + """Graph keys a flush of ``session_id`` should be recorded into. + + Every tracked sender buffer of the session gets the flush op; a + session with no known buffer (empty flush) falls back to the + ``unknown``-owner session graph so the event is still visible. + """ + keys = [ + key + for key in self._buffers + if key[0] == app_id and key[1] == project_id and key[3] == session_id + ] + return keys or [(app_id, project_id, "unknown", session_id)] + + async def _record_flush( + self, + app_id: str, + project_id: str, + session_id: str, + *, + result: Any, + request_id: str | None, + buffer_state: Mapping[str, Any] | None = None, + ) -> None: + """Record the request-level ``memory_flush`` op for one flush.""" + op_name = f"memory_flush_{session_id}" + op_metadata = { + "session_id": session_id, + "is_final": True, + "status": getattr(result, "status", None), + "message_count": getattr(result, "message_count", None), + "request_id": request_id, + } + for key in self._flush_graph_keys(app_id, project_id, session_id): + buffer = self._buffers.get(key) + + def record(buf: dict[str, Any] | None = buffer) -> None: + if buf is not None and buffer_state is not None: + # Even an empty flush gets its own transition/version. Never + # infer a drain from response.message_count (fresh rows only). + with comment_mutation( + target=buf, + id_strategy=_by_id, + encoding_fn=_encode, + category="message_buffer", + comment=( + "The session messages held in the buffer at this point." + ), + mutation_name=op_name, + mutation_category="extraction", + mutation_comment=( + "Flush the buffer and persist its actual tail." + ), + mutation_metadata=self._op_metadata( + { + **op_metadata, + "source": "construction_event", + "observed_at": buffer_state["observed_at"], + } + ), + ): + buf["message_ids"] = list(buffer_state["message_ids"]) + return + receipt = comment_variable( + { + "id": ( + f"flush-result-{session_id}-" + f"{request_id or uuid.uuid4().hex}" + ), + **op_metadata, + "buffer_state_observed": False, + }, + to_runtime=True, + id_strategy=_by_id, + encoding_fn=_encode, + category="request_result", + class_name="flush_result", + comment="Completion of one flush without a captured buffer state.", + ) + comment_op( + op_name=op_name, + category="extraction", + comment=( + "Flush the session buffer: boundary detection and " + "extraction ran over the buffered messages." + ), + inputs=( + [(buf, dict(_BUFFER_INPUT_OPTIONS))] if buf is not None else [] + ), + outputs=[receipt], + metadata=self._op_metadata(op_metadata), + ) + + await self._update_graph( + key, + session_name=op_name, + session_category="memory_construction", + record=record, + ) + + def _search_scope(self, req: SearchRequest) -> tuple[str, str, str, str, GraphKey]: + """Resolve the ``(owner, app, project, bucket, key)`` of one search.""" + owner = req.owner_id + app_id = req.app_id + project_id = req.project_id + bucket = "global" + if req.filters is not None: + extra = req.filters.model_extra or {} + session_id = extra.get("session_id") + if isinstance(session_id, str) and session_id: + bucket = session_id + return owner, app_id, project_id, bucket, (app_id, project_id, owner, bucket) + + def _next_query_identity( + self, key: GraphKey, owner: str, request_id: str | None + ) -> tuple[str, int]: + """Deterministic query identity: ``query-{owner}-{request_id}``. + + The request id keeps the identity reproducible across replays and + joinable with the request logs. A collision (the identity already + has a version in the live graph, e.g. a retried request) gets a + sequence suffix instead of a random component. Without a request id + (direct / CLI callers) the per-key sequence itself keeps the + identity unique within the process. + """ + seq = self._query_seq.get(key, 0) + 1 + self._query_seq[key] = seq + if request_id: + query_id = f"query-{owner}-{request_id}" + else: + query_id = f"query-{owner}-{seq:04d}" + graph = self._graphs[key] + base = query_id + if graph.get_versions(f"query:{query_id}"): + query_id = f"{base}-{seq:04d}" + while graph.get_versions(f"query:{query_id}"): + seq += 1 + query_id = f"{base}-{seq:04d}" + self._query_seq[key] = seq + return query_id, seq + + def _record_query_node( + self, + req: SearchRequest, + *, + owner: str, + query_id: str, + request_id: str, + ) -> Any: + """Record the ``query`` variable for one search and return its handle.""" + return comment_variable( + { + "id": query_id, + "query": req.query, + "user_id": owner, + "app_id": req.app_id, + "project_id": req.project_id, + "method": str(req.method), + "top_k": req.top_k, + "request_id": request_id, + }, + to_runtime=True, + id_strategy=_by_id, + encoding_fn=_encode, + category="message & query", + class_name="query", + comment="A query issued to the EverOS /memory/search endpoint.", + metadata={"request_id": request_id}, + ) + + def _record_stage_pools( + self, + stages: Sequence[SearchStageRecord] | None, + *, + query_id: str, + query_handle: Any, + seq: int, + request_id: str, + ) -> tuple[list[tuple[SearchStageRecord, Any]], dict[str, Any]]: + """Record every stage pool and its chain edges. + + Explicit input ids take precedence, including cross-kind dependencies. + Older collectors fall back to the previous pools of their kind. + Returns the + ``(stage, pool_handle)`` pairs (candidates are recorded later) and + the last pool per kind (the hits' source). + + Every stage is an explicit ``retrieval`` operation with real + inputs and outputs (not a bare link), mirroring the native + MemTraceBench graphs where each recall / fusion / rerank step is + its own operation; the resulting edge topology is unchanged. + """ + last_pool: dict[str, Any] = {} + stage_pools: list[tuple[SearchStageRecord, Any]] = [] + stage_handles: dict[str, Any] = {} + pending: dict[str, list[Any]] = {} + for stage in stages or []: + # Profile retrieval remains active; its graph branch is disabled. + if stage.kind == "profile": + continue + pool_handle = self._record_stage_pool(stage, query_id=query_id) + stage_pools.append((stage, pool_handle)) + if stage.input_stage_ids is not None: + sources = [stage_handles[sid] for sid in stage.input_stage_ids] + sources = sources or [query_handle] + pending[stage.kind] = [pool_handle] + elif stage.phase in _RECALL_PHASES: + sources = [query_handle] + pending.setdefault(stage.kind, []).append(pool_handle) + else: + sources = pending.get(stage.kind) or [query_handle] + pending[stage.kind] = [pool_handle] + comment_op( + inputs=sources, + outputs=[pool_handle], + op_name=f"{stage.phase}_{seq:04d}" + if stage.phase.startswith("_") + else f"{stage.kind}_{stage.phase}_{seq:04d}", + category="retrieval", + comment=stage_comments( + stage.phase, + stage.kind, + status=str(stage.metadata.get("status", "success")), + )[0], + metadata=self._op_metadata( + { + "phase": stage.phase, + "kind": stage.kind, + "request_id": request_id, + "query_id": query_id, + **{k: v for k, v in stage.metadata.items() if k != "items"}, + } + ), + ) + last_pool[stage.kind] = pool_handle + if stage.stage_id: + stage_handles[stage.stage_id] = pool_handle + return stage_pools, last_pool + + async def _record_search( + self, + req: SearchRequest, + resp: SearchResponse, + *, + stages: Sequence[SearchStageRecord] | None = None, + request_id: str | None = None, + ) -> None: + """Record one search request into the ``(owner, session)`` graph. + + With ``stages`` (the request's candidate-pool trace collected by + :func:`everos.memory.search.trace.collect_search_trace`) the + retrieval chain runs ``query -> recall pools -> fusion pools -> + last pool -> hits``, so a graph consumer can tell whether a piece + of evidence was recalled, survived fusion, and was returned. + Without stages the legacy ``query -> hits`` chain is recorded + unchanged. + """ + owner, app_id, project_id, bucket, key = self._search_scope(req) + original_request_id = request_id + request_id = request_id or "unknown" + + def record() -> None: + query_id, seq = self._next_query_identity(key, owner, original_request_id) + query_handle = self._record_query_node( + req, owner=owner, query_id=query_id, request_id=request_id + ) + # (kind, identity, score, text) per hit. + hits: list[tuple[str, str, float, str]] = [] + for episode in resp.data.episodes: + hits.append( + ( + "episode", + _hit_identity(owner, episode.id), + episode.score, + episode.episode, + ) + ) + for fact in episode.atomic_facts: + hits.append( + ( + "episode", + _hit_identity(owner, fact.id), + fact.score, + fact.content, + ) + ) + for case in resp.data.agent_cases: + hits.append( + ( + "agent_case", + _hit_identity(owner, case.id), + case.score, + case.approach, + ) + ) + for skill in resp.data.agent_skills: + hits.append( + ( + "agent_skill", + _hit_identity(owner, skill.id), + skill.score, + skill.content, + ) + ) + + hit_handles = [] + with comment_op_scope( + op_name=f"memory_search_{seq:04d}", + category="retrieval", + comment="Retrieve stored memories relevant to the query.", + metadata=self._op_metadata( + { + "session_id": bucket, + "hit_count": len(hits), + "request_id": request_id, + "query_id": query_id, + } + ), + ): + stage_pools, last_pool = self._record_stage_pools( + stages, + query_id=query_id, + query_handle=query_handle, + seq=seq, + request_id=request_id, + ) + terminal_stages = {stage.kind: stage for stage, _pool in stage_pools} + terminal_ids = { + kind: {_hit_identity(owner, c.id) for c in stage.candidates} + for kind, stage in terminal_stages.items() + } + linked_hits: set[tuple[str, str]] = set() + + for kind, identity, score, text in hits: + source_memory = self._memory_source(key, identity, text=text) + hit_handle = comment_variable( + { + "id": self._result_identity(query_id, kind, identity), + "memory_identity": identity, + "query_id": query_id, + "owner_id": owner, + "content": text, + "source": "search_response", + "source_revision": source_memory.full_node_id + if source_memory + else None, + }, + to_runtime=True, + id_strategy=_by_id, + encoding_fn=_encode, + category="retrieval_result", + class_name="retrieval_hit", + comment="The exact text returned by this search request.", + metadata={ + "score": score, + "request_id": request_id, + "revision_resolved": source_memory is not None, + }, + ) + if source_memory is not None: + comment_link( + source=source_memory, + target=hit_handle, + comment="Return the text of this stored memory revision.", + edge_metadata={"source_revision": True}, + ) + # Kinds without a recorded stage (or stage-less + # recording) keep the legacy query -> hit edge. + if (kind, identity) not in linked_hits: + source = last_pool.get(kind) + if source is None: + comment_link( + source=query_handle, + target=hit_handle, + comment="Return this memory as a match for the query.", + edge_metadata={"score": score}, + ) + elif identity not in terminal_ids[kind]: + # Response shaping can wrap atomic facts in an + # episode; a capped pool can also omit a hit. + # Keep that output connected without inventing + # another candidate in the actual pool snapshot. + comment_link( + source=source, + target=hit_handle, + comment="Include this returned memory in the results.", + edge_metadata={ + "score": score, + "phase": terminal_stages[kind].phase, + "kind": kind, + "membership": True, + "response_only": True, + }, + ) + # Listed hits receive their single membership edge + # below, after their rich snapshot has been recorded. + linked_hits.add((kind, identity)) + hit_handles.append(hit_handle) + + # Candidate stubs come last so a candidate that was also + # returned reuses the hit's richer snapshot (identity_only) + # instead of forking a stub-only version of the node. + for stage, pool_handle in stage_pools: + if stage.kind in {"profile", "unprocessed"}: + continue + if pool_handle.full_node_id != last_pool[stage.kind].full_node_id: + continue + self._record_stage_candidates( + stage, + owner=owner, + app_id=app_id, + project_id=project_id, + pool_handle=pool_handle, + query_id=query_id, + graph_key=key, + ) + + # Older callers may provide a response without collected stages. + if "unprocessed" not in last_pool and resp.data.unprocessed_messages: + messages = resp.data.unprocessed_messages + phase = "_load_unprocessed" + operation_comment, result_comment = stage_comments( + phase, "unprocessed" + ) + result = comment_variable( + { + "id": f"candidates_unprocessed_{phase}-{query_id}", + "query_id": query_id, + "phase": phase, + "kind": "unprocessed", + "count": len(messages), + "total_count": len(messages), + "ids": [m.id for m in messages], + "scores": [0.0] * len(messages), + "sources": [""] * len(messages), + "items": [m.model_dump(mode="json") for m in messages], + }, + to_runtime=True, + id_strategy=_by_id, + encoding_fn=_encode, + category="retrieval_result", + class_name="retrieval_results", + comment=result_comment, + metadata={"total_count": len(messages), "truncated": False}, + ) + comment_op( + inputs=[query_handle], + outputs=[result], + op_name=f"{phase}_{seq:04d}", + category="retrieval", + comment=operation_comment, + metadata=self._op_metadata( + {"query_id": query_id, "request_id": request_id} + ), + ) + last_pool["unprocessed"] = result + + context = { + "id": f"context-{query_id}", + "query": req.query, + "passages": [ + {"id": identity, "score": score, "text": text} + for _kind, identity, score, text in hits + ] + + [ + { + "id": f"profile-{owner}", + "score": profile.score or 0.0, + "text": json.dumps(profile.profile_data, ensure_ascii=False), + } + for profile in resp.data.profiles + ], + } + context["unprocessed_messages"] = [ + _unprocessed_message_snapshot(message) + for message in resp.data.unprocessed_messages + ] + context_handle = comment_variable( + context, + to_runtime=True, + id_strategy=_by_id, + encoding_fn=_encode, + category="memory_context", + class_name="context", + comment="The memory context assembled from the search hits.", + ) + with comment_op_scope( + op_name=f"context_assembly_{seq:04d}", + category="retrieval", + comment="Assemble the retrieved memory entries into a context.", + metadata=self._op_metadata( + {"request_id": request_id, "query_id": query_id} + ), + ): + if "unprocessed" in last_pool: + pending_status = next( + ( + stage.metadata.get("status", "success") + for stage, _pool in reversed(stage_pools) + if stage.kind == "unprocessed" + ), + "success", + ) + if resp.data.unprocessed_messages: + pending_comment = ( + "Include the pending session messages in the context." + ) + elif pending_status == "skipped": + pending_comment = ( + "Add no pending messages because no session was specified." + ) + elif pending_status == "error": + pending_comment = ( + "Add no pending messages because their retrieval failed." + ) + else: + pending_comment = ( + "Add no pending messages because the session buffer " + "is empty." + ) + comment_link( + source=last_pool["unprocessed"], + target=context_handle, + comment=pending_comment, + ) + for hit_handle in hit_handles: + comment_link( + source=hit_handle, + target=context_handle, + comment="Include this returned memory in the search context.", + ) + + await self._update_graph( + key, + session_name=f"memory_search_{bucket}_{request_id}", + session_category="memory_retrieval", + record=record, + ) + + async def _record_search_error( + self, + req: SearchRequest, + *, + stages: Sequence[SearchStageRecord] | None, + error: BaseException, + request_id: str | None, + ) -> None: + """Record a failed search: query node, partial pools, error op. + + The stage collector may hold a partially filled pool list at the + failure point; whatever was collected is recorded so the graph + shows how far the retrieval pipeline got. No hits / context are + recorded — the request never produced a response. + """ + owner, app_id, project_id, bucket, key = self._search_scope(req) + original_request_id = request_id + request_id = request_id or "unknown" + + def record() -> None: + query_id, seq = self._next_query_identity(key, owner, original_request_id) + query_handle = self._record_query_node( + req, owner=owner, query_id=query_id, request_id=request_id + ) + with comment_op_scope( + op_name=f"memory_search_{seq:04d}", + category="retrieval", + comment=(f"EverOS {req.method} search failed."), + metadata=self._op_metadata( + { + "session_id": bucket, + "status": "error", + "error_type": type(error).__name__, + "error_message": str(error)[:_MAX_ERROR_MESSAGE_CHARS], + "request_id": request_id, + "query_id": query_id, + } + ), + ): + stage_pools, last_pool = self._record_stage_pools( + stages, + query_id=query_id, + query_handle=query_handle, + seq=seq, + request_id=request_id, + ) + for stage, pool_handle in stage_pools: + if stage.kind in {"profile", "unprocessed"}: + continue + if pool_handle.full_node_id != last_pool[stage.kind].full_node_id: + continue + self._record_stage_candidates( + stage, + owner=owner, + app_id=app_id, + project_id=project_id, + pool_handle=pool_handle, + query_id=query_id, + graph_key=key, + ) + + await self._update_graph( + key, + session_name=f"memory_search_{bucket}_{request_id}", + session_category="memory_retrieval", + record=record, + ) + + def _record_stage_pool(self, stage: SearchStageRecord, *, query_id: str) -> Any: + """Record one search-stage candidate pool as a ``memory_context`` + variable and return its runtime handle. + + The pool identity is namespaced by the query so every request + records its own stage chain; the snapshot carries the capped + ``ids`` / ``scores`` / ``sources`` lists. + """ + snapshot = { + "id": f"candidates_{stage.kind}_{stage.phase}-{query_id}", + "query_id": query_id, + "phase": stage.phase, + "kind": stage.kind, + "count": len(stage.candidates), + "total_count": stage.total_count, + "ids": [candidate.id for candidate in stage.candidates], + "scores": [candidate.score for candidate in stage.candidates], + "sources": [candidate.source for candidate in stage.candidates], + } + if "items" in stage.metadata: + snapshot["items"] = stage.metadata["items"] + stage_metadata = { + key: value + for key, value in stage.metadata.items() + if isinstance(value, str | int | float | bool) + } + # Truncation markers: the pool snapshot is capped at + # ``STAGE_CANDIDATE_CAP``, so downstream attribution must know when + # it is looking at a partial recall set. + stage_metadata["total_count"] = stage.total_count + stage_metadata["truncated"] = stage.total_count > len(stage.candidates) + return comment_variable( + snapshot, + to_runtime=True, + id_strategy=_by_id, + encoding_fn=_encode, + category="retrieval_result" + if stage.kind == "unprocessed" + else "memory_context", + class_name=_POOL_CLASS_NAMES.get(stage.phase, "retrieval_results"), + comment=stage_comments( + stage.phase, + stage.kind, + status=str(stage.metadata.get("status", "success")), + )[1], + metadata=stage_metadata or None, + ) + + @staticmethod + def _result_identity(query_id: str, kind: str, identity: str) -> str: + digest = hashlib.sha256(_encode([kind, identity]).encode()).hexdigest()[:16] + return f"hit-{query_id}-{digest}" + + def _memory_source( + self, key: GraphKey, identity: str, *, text: str | None = None + ) -> Any: + """Copy a canonical revision without allocating a target-local version. + + Response text must match a recorded content revision. Unknown or stale + index values remain unresolved rather than borrowing the current disk value. + """ + target = self._graphs[key] + matches = [] + for source_key, graph in self._graphs.items(): + if source_key[:2] != key[:2]: + continue + for node in graph.get_versions(identity): + value = json.loads(node.value) + if ( + not isinstance(value, dict) + or "kind" not in value + or value.get("deleted") + ): + continue + if text is not None and value.get("content") != text: + continue + matches.append((node, graph)) + if not matches: + return None + node, source_graph = max( + matches, key=lambda pair: (pair[0].created_at, pair[0].version) + ) + existing = next( + ( + n + for n in target.get_versions(identity) + if n.full_node_id == node.full_node_id + ), + None, + ) + if existing is not None: + if existing.value != node.value: + raise ValueError( + "Conflicting legacy memory revisions; " + "collect into a fresh trace directory." + ) + return existing + if node.session_id not in { + session.session_id for session in target.get_all_sessions() + }: + target.add_session(source_graph.get_session(node.session_id)) + target.add_variable(node) + return target.get_variable(node.full_node_id) + + def _record_stage_candidates( + self, + stage: SearchStageRecord, + *, + owner: str, + app_id: str, + project_id: str, + pool_handle: Any, + query_id: str, + graph_key: GraphKey, + ) -> None: + """Record request-local candidate observations, never memory mutations.""" + seen: set[str] = set() + for candidate in stage.candidates: + identity = _hit_identity(owner, candidate.id) + if identity in seen: + continue + seen.add(identity) + candidate_handle = comment_variable( + { + "id": self._result_identity(query_id, stage.kind, identity), + "memory_identity": identity, + "query_id": query_id, + "source": "candidate_pool", + "identity_only": True, + }, + to_runtime=True, + id_strategy=_by_id, + encoding_fn=_encode, + identity_only=True, + category="retrieval_result", + class_name="retrieval_hit", + comment="A candidate reference with unobserved contents.", + metadata={"score": candidate.score, "phase": stage.phase}, + ) + comment_link( + source=pool_handle, + target=candidate_handle, + comment="Select this candidate from the retrieved memory pool.", + edge_metadata={ + "score": candidate.score, + "phase": stage.phase, + "kind": stage.kind, + "membership": True, + }, + ) + + # ── file tracking ──────────────────────────────────────────────────── + + async def _sync_files(self, *, trigger: str = "manual") -> None: + """Diff the memory-root markdown tree and record every change. + + ``_file_state`` and the entry/artifact mirrors are process-global, + so scan + apply run as one transaction under ``_sync_lock``. The + apply phase is split in two: snapshots are applied first (collecting + every entry identity seen this round), then deletions are decided + globally — an entry that moved files inside one diff round is a + move, not a delete + recreate. The first diff after process start + additionally reconciles downtime deletions against the exported + graphs. Every graph dirtied by the round is exported exactly once + at the end. Ops recorded by the diff carry ``source: "file_diff"`` + and the ``trigger`` (the hook that drove this diff) in metadata. + """ + async with self._sync_lock: + self._trigger = trigger + committed_state = dict(self._file_state) + try: + changed, deleted = await asyncio.to_thread(self._scan) + present: set[ScopedIdentity] = set() + present_by_file: dict[str, set[ScopedIdentity]] = {} + for path in deleted: + await self._apply_deleted_artifacts(path) + for snapshot in changed: + file_present = await self._apply_snapshot(snapshot) + present |= file_present + present_by_file[snapshot.path] = file_present + # Decide deletions across all touched files so moves survive. + touched = set(deleted) | present_by_file.keys() + for scoped_identity, path in list(self._entry_file.items()): + if path in touched and scoped_identity not in present: + await self._apply_deletion(scoped_identity) + if not self._first_scan_done: + await self._reconcile_after_restart(present, present_by_file) + await self._flush_dirty_graphs() + self._first_scan_done = True + except BaseException: + # Apply/export failures must retry even when files are unchanged. + self._file_state = committed_state + raise + + def _scan(self) -> tuple[list[MemoryFileSnapshot], list[str]]: + """Scan the memory root (runs in a worker thread). + + Returns: + `tuple[list[MemoryFileSnapshot], list[str]]`: + Parsed snapshots of new/changed files and the relative paths + of deleted files. + """ + changed: list[MemoryFileSnapshot] = [] + seen: set[str] = set() + for path in self._root.rglob("*.md"): + parts = set(path.relative_to(self._root).parts) + if parts & _SKIP_DIR_NAMES: + continue + if path.is_relative_to(self._out_dir): + continue + rel = str(path.relative_to(self._root)) + seen.add(rel) + stat = path.stat() + state = (stat.st_mtime_ns, stat.st_size) + if self._file_state.get(rel) == state: + continue + try: + snapshot = parse_memory_file(path, relative_to=self._root) + except Exception as exc: + logger.warning("memtrace_parse_failed", path=rel, error=str(exc)) + # Do not commit the new state: retry the same file at the + # next request boundary even when its mtime/size is unchanged. + continue + self._file_state[rel] = state + changed.append(snapshot) + deleted = [rel for rel in self._file_state if rel not in seen] + for rel in deleted: + del self._file_state[rel] + return changed, deleted + + async def _apply_snapshot( + self, snapshot: MemoryFileSnapshot + ) -> set[ScopedIdentity]: + """Route one parsed file's entries/artifact into their graphs. + + Returns the scoped identities of the entries present in the file + (empty for whole-file artifacts); ``_sync_files`` uses the union + per round to decide deletions globally. + """ + if snapshot.kind in _ENTRY_FILE_KINDS: + present: set[ScopedIdentity] = set() + for entry in snapshot.entries: + identity = self._entry_identity(entry) + scoped_identity = (entry.app_id, entry.project_id, identity) + present.add(scoped_identity) + await self._apply_entry(entry, identity, scoped_identity) + return present + await self._apply_artifact(snapshot) + return set() + + def _entry_identity(self, entry: MemoryFileEntry) -> str: + """Stable cross-graph identity for one markdown entry.""" + owner = entry.owner_id or "unknown" + return f"{owner}_{entry.entry_id}" + + async def _apply_entry( + self, + entry: MemoryFileEntry, + identity: str, + scoped_identity: ScopedIdentity, + ) -> None: + """Record a new entry or a content change of an existing entry.""" + owner = entry.owner_id or "unknown" + bucket = entry.session_id or "global" + key = (entry.app_id, entry.project_id, owner, bucket) + snapshot = { + "id": identity, + "entry_id": entry.entry_id, + "app_id": entry.app_id, + "project_id": entry.project_id, + "owner_id": owner, + "session_id": entry.session_id, + "timestamp": entry.timestamp, + "parent_type": entry.parent_type, + "parent_id": entry.parent_id, + "sender_ids": entry.sender_ids, + "subject": entry.subject, + "summary": entry.summary, + "content": entry.content, + "path": entry.path, + "kind": entry.kind, + } + previous = self._entries.get(scoped_identity) + if previous is None: + previous = await self._restored_snapshot(key, identity) + if previous is not None: + previous["path"] = entry.path + self._entries[scoped_identity] = previous + self._entry_file[scoped_identity] = entry.path + if previous is not None and _encode_without_path( + previous + ) == _encode_without_path(snapshot): + if previous.get("path") != entry.path: + # A pure move (log rotation, OME rewrite) is not an update: + # keep the node version, follow the entry to its new file. + previous["path"] = entry.path + self._entry_file[scoped_identity] = entry.path + return + + if previous is None: + message_ids, sender_ids, membership_status = await self._memcell_boundary( + entry + ) + cell_content = None + if entry.kind == "foresight" and entry.parent_type == "memcell": + graph = self._graphs[key] + cell_input = _latest_handle(graph, f"cell-input-{entry.parent_id}") + if ( + cell_input is None + or json.loads(cell_input.raw_value).get("content") is None + ): + cell_content = await self._memcell_payload(entry) + + def record() -> None: + parent_handle = self._record_parent( + entry, + owner, + message_ids=message_ids, + sender_ids=sender_ids, + membership_status=membership_status, + ) + if ( + entry.kind == "foresight" + and entry.parent_type == "memcell" + and parent_handle is not None + ): + parent_handle = self._record_cell_input( + key, + entry.parent_id, + parent_handle, + content=cell_content, + metadata=self._file_diff_metadata( + {"content_source": "memcell_archive"} + ), + ) + observation = self._entry_observations.get(scoped_identity) + if observation: + extracted = self._graphs[key].get_variable( + observation["source_node"] + ) + if ( + json.loads(extracted.value).get("content") + == snapshot["content"] + ): + parent_handle = extracted + else: + # A later disk rewrite must not masquerade as the actual + # extractor/persist output captured before it. + observation = None + with comment_op_scope( + op_name=f"{entry.kind}_extraction_{entry.entry_id}", + category="extraction", + comment=( + f"Record a new {entry.kind.replace('_', ' ')} memory " + "derived from this input." + ), + metadata=( + self._op_metadata(observation) + if observation + else self._file_diff_metadata({"path": entry.path}) + ), + ): + entry_handle = comment_variable( # + snapshot, + to_runtime=True, + id_strategy=_by_id, + encoding_fn=_encode, + category="memory_entry", + comment=_ENTRY_KIND_COMMENT.get( + entry.kind, "A memory entry parsed from markdown." + ), + ) + if parent_handle is not None: + comment_link(source=parent_handle, target=entry_handle) + + await self._update_graph( + key, + session_name=f"{entry.kind}_extraction_{entry.entry_id}", + session_category="memory_construction", + record=record, + export=False, + ) + self._entries[scoped_identity] = snapshot + self._entry_file[scoped_identity] = entry.path + self._entry_observations.pop(scoped_identity, None) + else: + + def record_update() -> None: + with comment_mutation( + target=previous, + id_strategy=_by_id, + encoding_fn=_encode, + category="memory_entry", + comment=_ENTRY_KIND_COMMENT.get( + entry.kind, "A memory entry parsed from markdown." + ), + mutation_name=f"update_{entry.entry_id}", + mutation_category="update", + mutation_comment=( + f"The {entry.kind} entry was rewritten in {entry.path}." + ), + mutation_metadata=self._file_diff_metadata({"path": entry.path}), + ): + previous.clear() + previous.update(snapshot) + + before = dict(previous) + try: + await self._update_graph( + key, + session_name=f"update_{entry.entry_id}", + session_category="memory_construction", + record=record_update, + export=False, + ) + except BaseException: + previous.clear() + previous.update(before) + raise + self._entry_file[scoped_identity] = entry.path + + async def _memcell_boundary( + self, entry: MemoryFileEntry + ) -> tuple[list[str] | None, list[str] | None, str]: + """Fetch the immutable boundary message and sender ids of a memcell. + + Boundary detection persists every memcell's exact message-id list in + SQLite (``Memcell.message_ids_json``) and the markdown entry's + ``parent_id`` is the memcell row's primary key, so the real + membership is recoverable even across restarts. + + Returns: + `tuple[list[str] | None, list[str] | None, str]`: + The exact message/sender lists (``None`` when unavailable) and the + membership status: ``exact`` (real boundary data), + ``row_missing`` (no matching memcell row), ``lookup_failed`` + (the SQLite read itself failed), or ``invalid_payload`` + (the row's ``message_ids_json`` is unparsable). + """ + if entry.parent_type != "memcell" or not entry.parent_id: + return None, None, "row_missing" + try: + if self._memcell_repo is None: + raise RuntimeError("Memcell repository is not configured") + rows = await self._memcell_repo.find_by_ids([entry.parent_id]) + except Exception as exc: + logger.warning( + "memtrace_memcell_lookup_failed", + memcell_id=entry.parent_id, + error=str(exc), + ) + return None, None, "lookup_failed" + row = rows[0] if rows else None + if ( + row is None + or row.app_id != entry.app_id + or row.project_id != entry.project_id + ): + return None, None, "row_missing" + try: + message_ids = json.loads(row.message_ids_json) + except (TypeError, ValueError): + return None, None, "invalid_payload" + if not isinstance(message_ids, list): + return None, None, "invalid_payload" + try: + sender_ids = json.loads(getattr(row, "sender_ids_json", "null")) + except (TypeError, ValueError): + sender_ids = None + if not isinstance(sender_ids, list): + sender_ids = None + return ( + [str(message_id) for message_id in message_ids], + [str(sender_id) for sender_id in sender_ids] + if sender_ids is not None + else None, + "exact", + ) + + async def _memcell_payload(self, entry: MemoryFileEntry) -> Any: + """Recover the archived raw input without borrowing another scope's cell.""" + try: + if self._memcell_repo is None: + raise RuntimeError("Memcell repository is not configured") + rows = await self._memcell_repo.find_by_ids([entry.parent_id]) + row = rows[0] if rows else None + if ( + row is None + or row.app_id != entry.app_id + or row.project_id != entry.project_id + or row.session_id != entry.session_id + ): + return None + payload = json.loads(row.payload_json) + return payload if isinstance(payload, dict) else None + except Exception as exc: + logger.warning( + "memtrace_memcell_payload_unavailable", + memcell_id=entry.parent_id, + error_type=type(exc).__name__, + ) + return None + + def _session_message_ids_heuristic(self, entry: MemoryFileEntry) -> list[str]: + """Approximate memcell membership from the session message index. + + Used only when the memcell's SQLite row is unavailable: prefer the + session's not-yet-bound messages, falling back to every indexed + session message when all of them are already bound. + """ + session_key = (entry.app_id, entry.project_id, entry.session_id or "") + indexed = [ + message_id + for message_id in self._session_messages.get(session_key, []) + if (entry.app_id, entry.project_id, message_id) in self._messages + ] + unbound = [ + message_id + for message_id in indexed + if (entry.app_id, entry.project_id, message_id) not in self._bound_messages + ] + return unbound or indexed + + def _record_parent( + self, + entry: MemoryFileEntry, + owner: str, + *, + message_ids: list[str] | None = None, + sender_ids: list[str] | None = None, + membership_status: str = "row_missing", + observed_event: Mapping[str, Any] | None = None, + boundary_result: Any = None, + ) -> Any: + """Record the parent chain of a new entry and return its handle. + + A ``memcell`` parent records its boundary once and reuses it for all + derived entries. Sender ids come from SQLite, not child-specific + Markdown metadata. Its input is the buffer version consumed by the + boundary. Message inputs are a fallback when that version is missing. + A later exact lookup can upgrade an + approximation; a failed lookup never downgrades an exact record. + Membership uses the exact id list persisted by boundary detection + (``membership: exact``), otherwise a session heuristic over the + process-local message index. The heuristic result is marked by how + the lookup failed: ``approximate`` for a missing / unparsable row, + ``lookup_failed`` when the SQLite read itself failed — a harder + warning than a mere approximation. A non-``exact`` node also + carries ``membership_detail`` with the raw status. Messages the + content index no longer covers (recorded before a restart) are + linked as identity-only stubs so they stitch onto their pre-restart + nodes. Any other parent kind is re-recorded as a lightweight + identity-only node. + + With ``boundary_result`` (the caller's event-level + ``boundary_detection`` scope is active) the memcell hangs off the + structured detection result, which already depends on the consumed + buffer. File-only observations use a recovered grouping result instead. + """ + if not entry.parent_id: + return None + if entry.parent_type == "memcell": + key = (entry.app_id, entry.project_id, owner, entry.session_id or "global") + graph = self._graphs[key] + existing = _latest_handle(graph, entry.parent_id) + previous = json.loads(existing.raw_value) if existing is not None else None + if ( + existing is not None + and existing.metadata.get("membership") == "exact" + and message_ids is None + ): + message_ids = previous["message_ids"] + sender_ids = previous["sender_ids"] + membership = "exact" + if message_ids is None: + membership = ( + "lookup_failed" + if membership_status == "lookup_failed" + else "approximate" + ) + message_ids = ( + previous["message_ids"] + if previous is not None + else self._session_message_ids_heuristic(entry) + ) + membership_metadata: dict[str, Any] = {"membership": membership} + if membership != "exact": + membership_metadata["membership_detail"] = membership_status + snapshots = [ + self._messages.get((entry.app_id, entry.project_id, message_id)) + for message_id in message_ids + ] + memcell = { + "id": entry.parent_id, + "app_id": entry.app_id, + "project_id": entry.project_id, + "session_id": entry.session_id, + "sender_ids": ( + sender_ids + if sender_ids is not None + else previous["sender_ids"] + if previous is not None + else entry.sender_ids + ), + "message_ids": message_ids, + } + for message_id in message_ids: + self._bound_messages.add((entry.app_id, entry.project_id, message_id)) + unchanged = ( + existing is not None + and previous == memcell + and existing.metadata.get("membership") == membership + ) + if unchanged and boundary_result is None: + return existing + if boundary_result is not None: + # The caller's event-level boundary_detection scope is active: + # group the memcell off the structured detection result. + if unchanged: + memcell_handle = existing + elif existing is None: + memcell_handle = comment_variable( + memcell, + to_runtime=True, + id_strategy=_by_id, + encoding_fn=_encode, + category="memory_entry", + comment="A memcell produced by boundary detection.", + metadata=membership_metadata, + ) + else: + with comment_mutation( + target=previous, + id_strategy=_by_id, + encoding_fn=_encode, + category="memory_entry", + comment="A memcell produced by boundary detection.", + metadata=membership_metadata, + reuse_op=True, + mutation_comment=( + "Update the message membership of this memcell." + ), + ) as mutation: + previous.clear() + previous.update(memcell) + memcell_handle = mutation.result + comment_op( + inputs=[boundary_result], + outputs=[memcell_handle], + reuse_op=True, + comment=( + "Based on the structured boundary decision, " + "the memory system groups these session messages into " + "a new memcell." + ), + metadata=( + self._op_metadata(observed_event) if observed_event else None + ), + ) + return memcell_handle + with comment_op_scope( + op_name=f"boundary_detection_{entry.parent_id}", + category="boundary_detection", + comment=( + "Boundary detection carved this memcell out of the " + "session messages." + ), + metadata=( + self._op_metadata(observed_event) + if observed_event + else self._file_diff_metadata( + {"session_id": entry.session_id or "", **membership_metadata} + ) + ), + ): + if existing is None: + memcell_handle = comment_variable( + memcell, + to_runtime=True, + id_strategy=_by_id, + encoding_fn=_encode, + category="memory_entry", + comment="A memcell produced by boundary detection.", + metadata=membership_metadata, + ) + else: + with comment_mutation( + target=previous, + id_strategy=_by_id, + encoding_fn=_encode, + category="memory_entry", + comment="A memcell produced by boundary detection.", + metadata=membership_metadata, + reuse_op=True, + mutation_comment=( + "Update the message membership of this memcell." + ), + ) as mutation: + previous.clear() + previous.update(memcell) + memcell_handle = mutation.result + buffer_handle = next( + ( + handle + for handle in reversed( + graph.get_versions(f"buffer-{entry.session_id}-{owner}") + ) + if message_ids + and set(message_ids).issubset( + json.loads(handle.raw_value)["message_ids"] + ) + ), + None, + ) + recovered_result = comment_variable( + { + "id": ( + f"boundary-observed-{entry.parent_id}" + f"-v{memcell_handle.version}" + ), + "session_id": entry.session_id, + "decision": "split", + "detection_performed": None, + "cell_ids": [entry.parent_id], + "message_ids": message_ids, + }, + to_runtime=True, + id_strategy=_by_id, + encoding_fn=_encode, + category="boundary_outcome", + class_name="boundary_detection_result", + comment=( + "The message grouping recovered for an existing memory unit." + ), + metadata={"observation_only": True, **membership_metadata}, + ) + comment_link( + source=recovered_result, + target=memcell_handle, + comment=( + "Associate the recovered message grouping " + "with this memory unit." + ), + ) + if buffer_handle is not None and message_ids: + comment_link( + source=buffer_handle, + target=recovered_result, + comment=( + "Identify the buffered messages belonging to " + "the recovered group." + ), + edge_metadata={"boundary_input": True}, + ) + return memcell_handle + linked: set[str] = set() + for message_id, snapshot in zip(message_ids, snapshots, strict=True): + if message_id in linked: + continue + linked.add(message_id) + message_handle = comment_variable( + snapshot if snapshot is not None else {"id": message_id}, + to_runtime=True, + id_strategy=_by_id, + encoding_fn=_encode, + identity_only=snapshot is None, + category="message", + comment=( + "A session message grouped into this memcell by " + "boundary detection." + ), + ) + comment_link( + source=message_handle, + target=recovered_result, + comment="Identify a message belonging to the recovered group.", + ) + return memcell_handle + parent_identity = f"{owner}_{entry.parent_id}" + return comment_variable( + {"id": parent_identity}, + to_runtime=True, + id_strategy=_by_id, + encoding_fn=_encode, + identity_only=True, + category="memory_entry", + comment="A lightweight reference to the parent memory entry.", + ) + + async def _apply_artifact(self, snapshot: MemoryFileSnapshot) -> None: + """Record a whole-file artifact (profile / agent record / skill).""" + owner = snapshot.owner_id or "unknown" + if snapshot.kind == "profile": + identity = f"profile-{owner}" + elif snapshot.kind == "agent_skill" and snapshot.frontmatter.get("name"): + # Search results use the LanceDB primary-key convention + # ``{owner}_{skill_name}``; keep the markdown-side identity equal + # so retrieval reuses the write-path node. + identity = f"{owner}_{snapshot.frontmatter['name']}" + else: + identity = f"artifact-{owner}-{snapshot.path}" + scoped_identity = (snapshot.app_id, snapshot.project_id, identity) + key = (snapshot.app_id, snapshot.project_id, owner, "global") + body = { + "id": identity, + "app_id": snapshot.app_id, + "project_id": snapshot.project_id, + "owner_id": owner, + "path": snapshot.path, + "kind": snapshot.kind, + "content": snapshot.body, + } + # A file whose semantic identity changed (for example a hand-edited + # skill name) deletes its old artifact before creating the new one. + for old_identity, path in list(self._artifact_file.items()): + if path == snapshot.path and old_identity != scoped_identity: + await self._apply_deletion(old_identity) + + previous = self._artifacts.get(scoped_identity) + if previous is None: + previous = await self._restored_snapshot(key, identity) + if previous is not None: + previous["path"] = snapshot.path + self._artifacts[scoped_identity] = previous + self._artifact_file[scoped_identity] = snapshot.path + if previous is not None and _encode(previous) == _encode(body): + return + if previous is None: + + def record() -> None: + value = comment_variable( + body, + to_runtime=True, + id_strategy=_by_id, + encoding_fn=_encode, + category="memory_entry", + comment=f"A {snapshot.kind} memory artifact ({snapshot.path}).", + ) + comment_op( + inputs=[], + outputs=[value], + op_name=f"observe_{snapshot.kind}_creation", + category="extraction", + comment="Record a newly observed memory artifact in the store.", + metadata=self._file_diff_metadata({"path": snapshot.path}), + ) + + await self._update_graph( + key, + session_name=f"artifact_{snapshot.kind}", + session_category="memory_construction", + record=record, + export=False, + ) + self._artifacts[scoped_identity] = body + self._artifact_file[scoped_identity] = snapshot.path + else: + + def record_update() -> None: + with comment_mutation( + target=previous, + id_strategy=_by_id, + encoding_fn=_encode, + category="memory_entry", + comment=f"A {snapshot.kind} memory artifact ({snapshot.path}).", + mutation_name=f"update_{snapshot.kind}", + mutation_category="update", + mutation_comment=(f"The {snapshot.kind} artifact was rewritten."), + mutation_metadata=self._file_diff_metadata({"path": snapshot.path}), + ): + previous.clear() + previous.update(body) + + before = dict(previous) + try: + await self._update_graph( + key, + session_name=f"update_{snapshot.kind}", + session_category="memory_construction", + record=record_update, + export=False, + ) + except BaseException: + previous.clear() + previous.update(before) + raise + + async def _apply_deleted_artifacts(self, path: str) -> None: + """Record deletions for the artifact of a removed whole-file. + + Entry deletions are decided globally in ``_sync_files`` instead: a + removed file's entries may have moved to another file inside the + same diff round, which is a move, not a deletion. + """ + for identity, artifact_path in list(self._artifact_file.items()): + if artifact_path == path: + await self._apply_deletion(identity) + + async def _apply_deletion(self, scoped_identity: ScopedIdentity) -> None: + """Record a deletion mutation for one entry/artifact identity.""" + target = self._entries.get(scoped_identity) + if target is None: + target = self._artifacts.get(scoped_identity) + if target is None: + return + app_id, project_id, identity = scoped_identity + owner = str(target.get("owner_id") or "unknown") + bucket = str(target.get("session_id") or "global") + key = (app_id, project_id, owner, bucket) + + def record() -> None: + with comment_mutation( + target=target, + id_strategy=_by_id, + encoding_fn=_encode, + category="memory_entry", + comment=_ENTRY_KIND_COMMENT.get( + str(target.get("kind") or ""), + f"A {target.get('kind')} memory artifact ({target.get('path')}).", + ), + mutation_name=f"delete_{identity}", + mutation_category="deletion", + mutation_comment=( + "The memory entry was deleted from the markdown store." + ), + mutation_metadata=self._file_diff_metadata(), + ): + target["deleted"] = True + + before = dict(target) + try: + await self._update_graph( + key, + session_name=f"delete_{identity}", + session_category="memory_construction", + record=record, + export=False, + ) + except BaseException: + target.clear() + target.update(before) + raise + self._entries.pop(scoped_identity, None) + self._entry_file.pop(scoped_identity, None) + self._artifacts.pop(scoped_identity, None) + self._artifact_file.pop(scoped_identity, None) + + # ── graph registry / export ────────────────────────────────────────── + + async def _restored_snapshot( + self, key: GraphKey, identity: str + ) -> dict[str, Any] | None: + """Recover the last write-path snapshot after a process restart. + + The identity is the join key; the caller adopts the file location + from the current scan (entries may have moved files — ``path`` + never participates in change detection). A snapshot whose latest + version is a deletion stays deleted: a reappearing entry starts a + fresh extraction record instead of mutating a deleted node. + """ + graph = await self._get_graph(key) + versions = graph.get_versions(identity) + if not versions: + return None + try: + restored = json.loads(versions[-1].raw_value) + except (TypeError, ValueError): + return None + if not isinstance(restored, dict) or restored.get("deleted"): + return None + return restored + + async def _reconcile_after_restart( + self, + present: set[ScopedIdentity], + present_by_file: dict[str, set[ScopedIdentity]], + ) -> None: + """Record deletions for entries/artifacts removed during downtime. + + Runs once, after the first post-start diff: that diff re-parses + every existing file (``_file_state`` is process-local), so a tracked + write-path snapshot whose file is gone — or whose entry no longer + appears in its file — was deleted while the process was down and + never got a deletion mutation. + """ + tracked = await asyncio.to_thread(self._collect_tracked_snapshots) + done: set[ScopedIdentity] = set() + for snapshot in tracked: + identity = str(snapshot.get("id") or "") + path = str(snapshot.get("path") or "") + if not identity or not path: + continue + scoped_identity = ( + str(snapshot.get("app_id") or "default"), + str(snapshot.get("project_id") or "default"), + identity, + ) + if scoped_identity in done: + continue + is_entry = "entry_id" in snapshot + if is_entry and scoped_identity in present: + continue # Still tracked — possibly moved files. + file_present = present_by_file.get(path) + if file_present is None: + missing = True # The whole file was removed during downtime. + elif is_entry: + missing = scoped_identity not in file_present + else: + missing = False # Whole-file artifact: the file exists. + if not missing: + continue + done.add(scoped_identity) + if is_entry: + self._entries.setdefault(scoped_identity, snapshot) + self._entry_file.setdefault(scoped_identity, path) + else: + self._artifacts.setdefault(scoped_identity, snapshot) + self._artifact_file.setdefault(scoped_identity, path) + await self._apply_deletion(scoped_identity) + + def _collect_tracked_snapshots(self) -> list[dict[str, Any]]: + """Read the latest live write-path snapshots from every exported graph. + + Runs in a worker thread during the first post-start diff. Only the + latest version of each ``memory_entry`` node is considered; nodes + without a ``path`` (candidate stubs, search-response hits, memcells) + and versions already marked ``deleted`` are skipped. + """ + collected: list[dict[str, Any]] = [] + if not self._out_dir.exists(): + return collected + for path in self._out_dir.glob("*.json"): + try: + data = json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError): + continue + latest: dict[str, dict[str, Any]] = {} + for node in data.get("data", {}).get("nodes") or []: + if node.get("category") != "memory_entry": + continue + name = node.get("name") + if not name: + continue + current = latest.get(name) + if current is not None and (current.get("version") or 0) >= ( + node.get("version") or 0 + ): + continue + latest[name] = node + for node in latest.values(): + try: + snapshot = json.loads(node.get("value") or "") + except (TypeError, ValueError): + continue + if ( + isinstance(snapshot, dict) + and snapshot.get("path") + and not snapshot.get("deleted") + ): + collected.append(snapshot) + return collected + + def _graph_path(self, key: GraphKey) -> Path: + """On-disk JSON path for one scoped owner/session graph. + + Every component is a ``{safe}-{digest}`` fragment (see + ``_scoped_name``): readable, short, and collision-proof. Renamed + after the first instrumented drop — pre-rename files are orphans + (the raw ids cannot be recovered from the old collision-prone + names); delete or ignore them, there is no migration. + """ + app_id, project_id, owner, bucket = key + scope = "" + if (app_id, project_id) != ("default", "default"): + scope = f"{_scoped_name(app_id)}__{_scoped_name(project_id)}__" + return self._out_dir / ( + f"{scope}{_scoped_name(owner)}__{_scoped_name(bucket)}.json" + ) + + async def _get_graph(self, key: GraphKey) -> ExecNetwork: + """Return the live graph for a key, restoring it from disk if needed.""" + if key in self._graphs: + return self._graphs[key] + lock = self._locks.setdefault(key, asyncio.Lock()) + async with lock: + return await self._get_graph_unlocked(key) + + async def _get_graph_unlocked(self, key: GraphKey) -> ExecNetwork: + """Get-or-create the graph for ``key``. + + The caller must hold the key's lock so concurrent first touches + cannot each create an instance and silently lose one side's + updates. + """ + if key in self._graphs: + return self._graphs[key] + path = self._graph_path(key) + if await asyncio.to_thread(path.exists): + graph = await asyncio.to_thread(self._load_graph, path) + else: + app_id, project_id, owner, bucket = key + with comment_graph( + graph_id=( + "everos-filetrace-" + f"{_scoped_name(app_id)}-{_scoped_name(project_id)}-" + f"{_scoped_name(owner)}-{_scoped_name(bucket)}" + ), + user_id=owner, + project_id=project_id, + storage_path=str(path), + metadata={ + "strategy": "file_tracking", + "app_id": app_id, + "project_id": project_id, + "trace_schema": 2, + "history_complete": False, + "session_bucket": bucket, + }, + ) as graph: + pass + self._graphs[key] = graph + return graph + + @staticmethod + def _load_graph(path: Path) -> ExecNetwork: + """Load one exported graph without blocking the event loop.""" + return ExecNetwork.import_graph(json.loads(path.read_text(encoding="utf-8"))) + + async def _update_graph( + self, + key: GraphKey, + *, + session_name: str, + session_category: str, + record: Callable[[], None], + export: bool = True, + ) -> None: + """Apply one recorded update to a graph. + + With ``export=False`` the on-disk write is deferred: the key is + marked dirty and ``_flush_dirty_graphs`` exports it once, so a diff + round dirtying the same graph for N entries costs one full + serialisation instead of N. + """ + lock = self._locks.setdefault(key, asyncio.Lock()) + async with lock: + graph = await self._get_graph_unlocked(key) + with ( + comment_graph(graph=graph), + comment_session( + session_name=session_name, + category=session_category, + ), + ): + try: + record() + finally: + # Preserve retryability even if recording or export fails. + self._dirty_keys.add(key) + if export: + await asyncio.to_thread(self._export, key, graph) + self._dirty_keys.discard(key) + + async def _flush_dirty_graphs(self) -> None: + """Export every graph dirtied since the last flush, once per graph.""" + while self._dirty_keys: + key = next(iter(self._dirty_keys)) + lock = self._locks.setdefault(key, asyncio.Lock()) + async with lock: + graph = self._graphs.get(key) + if graph is not None: + await asyncio.to_thread(self._export, key, graph) + self._dirty_keys.discard(key) + + def _export(self, key: GraphKey, graph: ExecNetwork) -> None: + """Export one graph as MemTraceBench-compatible JSON (atomic write). + + The whole read-annotations / write-tmp / replace sequence runs under + an inter-process ``portalocker`` lock (``.json.lock``) so + concurrent writers (e.g. multiple uvicorn workers pointing at the + same export dir) serialise instead of interleaving a read-modify- + write. The lock does not merge graphs — each process still exports + its own in-memory instance — so multi-writer deployments should + still prefer a single writer or per-worker export dirs. + """ + data = graph.export_graph() + describe_sentinels(data) + payload = data.get("data", {}) + # Op-only graphs are meaningful too: an empty flush or a failed + # request records a request-level op whose inputs/outputs collapse + # onto the NONE sentinel, leaving no variable nodes behind. + if not (payload.get("nodes") or payload.get("operations")): + return + path = self._graph_path(key) + self._out_dir.mkdir(parents=True, exist_ok=True) + lock_path = path.with_suffix(".json.lock") + with portalocker.Lock(str(lock_path), mode="w", timeout=30): + annotations: list[Any] = [] + if path.exists(): + try: + previous = json.loads(path.read_text(encoding="utf-8")) + annotations = previous.get("data", {}).get("annotations") or [] + except (OSError, json.JSONDecodeError): + annotations = [] + data.setdefault("data", {})["annotations"] = annotations + tmp_path = path.with_suffix(".json.tmp") + tmp_path.write_text( + json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8" + ) + tmp_path.replace(path) diff --git a/src/everos/infra/persistence/markdown/_readers/agent_skill_reader.py b/src/everos/infra/persistence/markdown/_readers/agent_skill_reader.py index fb4ce20af..debabcdea 100644 --- a/src/everos/infra/persistence/markdown/_readers/agent_skill_reader.py +++ b/src/everos/infra/persistence/markdown/_readers/agent_skill_reader.py @@ -17,7 +17,10 @@ the target is missing — readers do not raise on absence, since "skill not yet created" is a normal state for the upsert-style workflow. Callers that need to distinguish "missing" from "empty body" check for ``None`` -explicitly. +explicitly. A file removed between the existence check and the read is +missing too (``list_by_cluster`` skips it): an owner deletion moves the +agent's whole directory away under the owner's lock, which reads do not +take. ``reference_name`` / ``script_filename`` are appended after the skill directory, so ``skill_dir_name`` does not cover them; both go through @@ -193,11 +196,8 @@ async def read_reference( path = self._reference_path( agent_id, skill_name, reference_name, app_id, project_id ) - apath = anyio.Path(path) - if not await apath.is_file(): - return None - text = await MarkdownReader.read_text(apath) - return text.rstrip("\n") + text = await _read_text_if_present(path) + return text.rstrip("\n") if text is not None else None async def read_script( self, @@ -216,11 +216,8 @@ async def read_script( path = self._script_path( agent_id, skill_name, script_filename, app_id, project_id ) - apath = anyio.Path(path) - if not await apath.is_file(): - return None - text = await MarkdownReader.read_text(apath) - return text.rstrip("\n") + text = await _read_text_if_present(path) + return text.rstrip("\n") if text is not None else None # ── Internals — same shape as AgentSkillWriter ──────────────────────────── @@ -229,7 +226,8 @@ async def _read_path(self, path: Path, *, schema: type[T]) -> tuple[T, str] | No Shared by :meth:`read_main` (path derived from a caller-supplied ``skill_name``) and :meth:`list_by_cluster` (path taken directly - from a directory glob, never re-derived from a name). + from a directory glob, never re-derived from a name). ``None`` when + the file is not there, including when it went after the glob. Raises: ValidationError: the file's frontmatter violates *schema*. @@ -238,9 +236,10 @@ async def _read_path(self, path: Path, *, schema: type[T]) -> tuple[T, str] | No while ``list_by_cluster`` catches it per file so one bad file cannot starve the rest of the cluster. """ - if not await anyio.Path(path).is_file(): + text = await _read_text_if_present(path) + if text is None: return None - parsed = await MarkdownReader.read(path) + parsed = MarkdownReader.parse(text) frontmatter = schema.model_validate(parsed.frontmatter) body = parsed.body.rstrip("\n") return frontmatter, body @@ -294,3 +293,19 @@ def _script_path( / AgentSkillFrontmatter.SKILL_SCRIPTS_DIR_NAME / sanitize_dirname(script_filename, "script") ) + + +async def _read_text_if_present(path: Path) -> str | None: + """``path``'s text; ``None`` when it is not a file, or is removed before the read. + + The existence check answers fast for a missing path or a directory (which + on Windows would otherwise be retried as a sharing violation); the + ``FileNotFoundError`` catch covers the file going between that check and + the read. + """ + if not await anyio.Path(path).is_file(): + return None + try: + return await MarkdownReader.read_text(path) + except FileNotFoundError: + return None diff --git a/src/everos/infra/persistence/markdown/_readers/profile_reader.py b/src/everos/infra/persistence/markdown/_readers/profile_reader.py index 7118a21ee..c1d696af9 100644 --- a/src/everos/infra/persistence/markdown/_readers/profile_reader.py +++ b/src/everos/infra/persistence/markdown/_readers/profile_reader.py @@ -58,7 +58,12 @@ async def read( path = self._resolve_path(scope_id, schema, app_id, project_id) if not await anyio.Path(path).is_file(): return None - parsed = await MarkdownReader.read(path) + try: + parsed = await MarkdownReader.read(path) + except FileNotFoundError: + # A deletion can remove the file between the check and the read; + # "not yet written" and "just removed" are both absent. + return None frontmatter = schema.model_validate(parsed.frontmatter) body = parsed.body.rstrip("\n") return frontmatter, body diff --git a/src/everos/infra/persistence/sqlite/_repos/session_cut.py b/src/everos/infra/persistence/sqlite/_repos/session_cut.py index 6c17c19a3..6ea074011 100644 --- a/src/everos/infra/persistence/sqlite/_repos/session_cut.py +++ b/src/everos/infra/persistence/sqlite/_repos/session_cut.py @@ -13,7 +13,7 @@ import datetime as dt from collections.abc import Sequence -from sqlalchemy import delete, insert, update +from sqlalchemy import bindparam, delete, insert, text, update from sqlalchemy.ext.asyncio import AsyncSession from everos.core.utils.datetime import get_utc_now @@ -68,6 +68,38 @@ async def cut( await _replace_buffer(s, keys, tail) await s.commit() + async def already_cut( + self, + session_id: str, + track: str, + message_ids: Sequence[str], + *, + app_id: str, + project_id: str, + ) -> set[str]: + """Which of ``message_ids`` a memcell of the (session, track) holds. + + The memcells a cut inserts are its record of what it consumed, in the + same transaction, so a message is "already cut" exactly when one of + them lists it. + """ + if not message_ids: + return set() + # ponytail: scans the session's memcells; a (session, message_id) + # table if one session ever holds enough memcells for this to show. + stmt = text( + "SELECT DISTINCT j.value FROM memcell AS m, " + "json_each(m.message_ids_json) AS j " + "WHERE m.app_id = :app_id AND m.project_id = :project_id " + "AND m.session_id = :session_id AND m.track = :track " + "AND j.value IN :ids" + ).bindparams(bindparam("ids", expanding=True)) + params = _keys(app_id, project_id, session_id, track) | { + "ids": list(message_ids) + } + async with session_scope(self._factory) as s: + return set((await s.execute(stmt, params)).scalars()) + def _keys(app_id: str, project_id: str, session_id: str, track: str) -> dict[str, str]: return { diff --git a/src/everos/infra/persistence/sqlite/_repos/unprocessed_buffer.py b/src/everos/infra/persistence/sqlite/_repos/unprocessed_buffer.py index a7da474ea..3be0fe214 100644 --- a/src/everos/infra/persistence/sqlite/_repos/unprocessed_buffer.py +++ b/src/everos/infra/persistence/sqlite/_repos/unprocessed_buffer.py @@ -14,7 +14,7 @@ from __future__ import annotations -from sqlalchemy import delete, select, update +from sqlalchemy import delete, literal_column, select, update from sqlalchemy.dialects.sqlite import insert as sqlite_insert from everos.infra.persistence.sqlite._base.repository import RepoBase @@ -34,7 +34,11 @@ async def list_for_track( app_id: str = "default", project_id: str = "default", ) -> list[UnprocessedBuffer]: - """Return all rows of (app, project, session, track), ts asc.""" + """Return all rows of (app, project, session, track), ts asc. + + Rows sharing a timestamp come back in the order they were written + (``rowid``): the buffer is always rewritten whole, in merged order. + """ async with session_scope(self._factory) as s: stmt = ( select(UnprocessedBuffer) @@ -44,7 +48,7 @@ async def list_for_track( UnprocessedBuffer.session_id == session_id, UnprocessedBuffer.track == track, ) - .order_by(UnprocessedBuffer.timestamp.asc()) # type: ignore[union-attr] + .order_by(UnprocessedBuffer.timestamp.asc(), literal_column("rowid")) # type: ignore[union-attr] ) return list((await s.execute(stmt)).scalars().all()) diff --git a/src/everos/infra/persistence/sqlite/stores.py b/src/everos/infra/persistence/sqlite/stores.py index 81ef5109a..035f24d16 100644 --- a/src/everos/infra/persistence/sqlite/stores.py +++ b/src/everos/infra/persistence/sqlite/stores.py @@ -137,6 +137,17 @@ async def quarantine( project_id=session.project_id, ) + async def already_cut( + self, session: SessionKey, message_ids: Sequence[str] + ) -> set[str]: + return await self._cut.already_cut( + session.session_id, + _SESSION_TRACK, + message_ids, + app_id=session.app_id, + project_id=session.project_id, + ) + class SqliteMemcellStore: """Memcells over the ``memcell`` table. diff --git a/src/everos/memory/deps.py b/src/everos/memory/deps.py index 357a5ac8e..c290f009a 100644 --- a/src/everos/memory/deps.py +++ b/src/everos/memory/deps.py @@ -95,6 +95,7 @@ class LLMClients: Args: boundary: Cuts a session's messages into memcells. + language: Names each memcell's conversation language. episode: Extracts each memcell's episode. summary: Writes the episode's display summary. atomic_fact: Extracts atomic facts. @@ -108,6 +109,7 @@ class LLMClients: """ boundary: LLMClient + language: LLMClient episode: LLMClient summary: LLMClient atomic_fact: LLMClient diff --git a/src/everos/memory/events.py b/src/everos/memory/events.py index b6f91f47c..842b21b92 100644 --- a/src/everos/memory/events.py +++ b/src/everos/memory/events.py @@ -125,8 +125,9 @@ class EpisodeExtracted(Event): through to :class:`AtomicFactsExtracted` so the step that finishes the merge knows what to deprecate.""" language: str | None = None - """The episode's detected ``OutputLanguage`` value; the extractions this - event drives write in it. ``None`` lets each extractor infer its own.""" + """The episode's ``OutputLanguage`` value (as :attr:`Episode.language`); + the extractions this event drives write in it. ``None`` lets each + extractor infer its own.""" def owner_scope(self, copy: EpisodeCopy) -> Scope: """The user scope ``copy`` was written under.""" diff --git a/src/everos/memory/extract/boundary/detection.py b/src/everos/memory/extract/boundary/detection.py index 813c63c85..dfe4b88e2 100644 --- a/src/everos/memory/extract/boundary/detection.py +++ b/src/everos/memory/extract/boundary/detection.py @@ -29,17 +29,19 @@ import uuid from collections.abc import Sequence from datetime import UTC, tzinfo -from typing import Literal, NamedTuple, Protocol +from typing import Any, Literal, NamedTuple, Protocol from everalgo.boundary import Cuts from everalgo.llm import LLMOutputError from everalgo.types import ChatMessage, ConversationItem, MemCell from everos.config import BoundaryDetectionSettings +from everos.core.observability.logging import get_logger from everos.core.observability.tracing import memory_span from everos.core.utils.datetime import from_timestamp from everos.memory.custom_instructions import CustomInstructions from everos.memory.extract.llm_retry import retry_llm_output +from everos.memory.extract.trace import record_construction from everos.memory.models import CanonicalMessage, IngestResult, MemcellRecord from everos.memory.ports import SessionBufferStore, SessionKey @@ -54,6 +56,8 @@ ) from .quarantine import SessionQuarantine +logger = get_logger(__name__) + type Status = Literal["accumulated", "extracted", "skipped"] _RAW_TYPE_BY_MODE: dict[Mode, str] = { @@ -82,6 +86,7 @@ class BoundaryOutcome(NamedTuple): per_cell_all_senders: list[list[str]] status: Status message_count: int + detection: dict[str, Any] | None = None class BoundaryOperator(Protocol): @@ -158,7 +163,16 @@ async def buffer(self, ingested: IngestResult, *, mode: Mode) -> BoundaryOutcome if not fresh: return _empty_outcome("skipped", message_count=0) session = _session_of(ingested) - merged = merge_dedupe_sort(await self._session_buffer.list(session), fresh) + buffered = await self._session_buffer.list(session) + fresh = await self._not_yet_cut(session, fresh, buffered) + if not fresh: + # Every row was already cut; the buffer is unchanged. Still emit + # the authoritative snapshot so the tracer does not mistake the + # resent request messages for newly buffered input. + _record_buffer_loaded(ingested, buffered, buffered) + return _empty_outcome("skipped", message_count=0) + merged = merge_dedupe_sort(buffered, fresh) + _record_buffer_loaded(ingested, buffered, merged) await self._keep_buffered(session, merged) return _empty_outcome("accumulated", message_count=len(fresh)) @@ -191,22 +205,71 @@ async def detect( if not fresh and not is_final: return _empty_outcome("skipped", message_count=0) buffered = await self._session_buffer.list(session) + fresh = await self._not_yet_cut(session, fresh, buffered) + if not fresh and not is_final: + # Every row was already cut; the buffer is unchanged. Still emit + # the authoritative snapshot so the tracer does not mistake the + # resent request messages for newly buffered input. + _record_buffer_loaded(ingested, buffered, buffered) + return _empty_outcome("skipped", message_count=0) merged = merge_dedupe_sort(buffered, fresh) + _record_buffer_loaded(ingested, buffered, merged) + detection: dict[str, Any] = { + "message_ids": [m.message_id for m in merged], + "is_final": is_final, + "mode": mode, + "detection_performed": False, + } if not merged: - return _empty_outcome("accumulated", message_count=0) + return _empty_outcome("accumulated", message_count=0, detection=detection) if not is_final and not any(m.role == "user" for m in merged): # Episode extraction needs a user message; wait for one. await self._keep_buffered(session, merged) - return _empty_outcome("accumulated", message_count=len(fresh)) + return _empty_outcome( + "accumulated", message_count=len(fresh), detection=detection + ) result = await self._segment_or_quarantine( session, merged, buffered=buffered, mode=mode, is_final=is_final ) + detection["detection_performed"] = True + detection["model_result"] = { + "cell_message_ids": result.message_ids, + "tail_message_ids": [m.message_id for m in result.tail], + } if not result.cells: await self._keep_buffered(session, merged) - return _empty_outcome("accumulated", message_count=len(fresh)) + return _empty_outcome( + "accumulated", message_count=len(fresh), detection=detection + ) return await self._commit_cells( - session, result, mode=mode, message_count=len(fresh) + session, result, mode=mode, message_count=len(fresh), detection=detection + ) + + async def _not_yet_cut( + self, + session: SessionKey, + fresh: list[CanonicalMessage], + buffered: Sequence[CanonicalMessage], + ) -> list[CanonicalMessage]: + """``fresh`` without the messages a memcell of the session already holds. + + A client that resends a batch after a timeout sends messages the first + call may have cut already; those left the buffer, so the merge alone + would cut them a second time. A buffered message is kept: the tail + may share rows with the last cell. + """ + held = {m.message_id for m in buffered} + cut = await self._session_buffer.already_cut( + session, [m.message_id for m in fresh if m.message_id not in held] + ) + if not cut: + return fresh + logger.info( + "boundary_resent_messages_dropped", + session_id=session.session_id, + count=len(cut), ) + return [m for m in fresh if m.message_id not in cut] async def _segment_or_quarantine( self, @@ -332,6 +395,7 @@ async def _commit_cells( *, mode: Mode, message_count: int, + detection: dict[str, Any] | None = None, ) -> BoundaryOutcome: """Record one memcell row per cell and keep only the tail buffered, in one transaction: a failure leaves the buffer as it was.""" @@ -356,6 +420,7 @@ async def _commit_cells( tail=result.tail, last_memcell_ts=from_timestamp(last_cell_ts) if last_cell_ts else None, ) + _record_buffer_persisted(session, result.tail) return BoundaryOutcome( cells=result.cells, memcell_ids=memcell_ids, @@ -363,6 +428,7 @@ async def _commit_cells( per_cell_all_senders=senders, status="extracted", message_count=message_count, + detection=detection, ) async def _keep_buffered( @@ -371,6 +437,37 @@ async def _keep_buffered( await self._session_buffer.keep( session, merged, last_message_ts=max(m.timestamp for m in merged) ) + _record_buffer_persisted(session, merged) + + +def _record_buffer_loaded( + ingested: IngestResult, + buffered: Sequence[CanonicalMessage], + merged: Sequence[CanonicalMessage], +) -> None: + record_construction( + "buffer_loaded", + app_id=ingested.app_id, + project_id=ingested.project_id, + session_id=ingested.session_id, + snapshot_factory=lambda: { + "before_message_ids": [m.message_id for m in buffered], + "message_ids": [m.message_id for m in merged], + "sender_ids": list(dict.fromkeys(m.sender_id for m in merged)), + }, + ) + + +def _record_buffer_persisted( + session: SessionKey, rows: Sequence[CanonicalMessage] +) -> None: + record_construction( + "buffer_persisted", + app_id=session.app_id, + project_id=session.project_id, + session_id=session.session_id, + snapshot_factory=lambda: {"message_ids": [m.message_id for m in rows]}, + ) def _session_of(ingested: IngestResult) -> SessionKey: @@ -418,7 +515,9 @@ def _mint_memcell_id() -> str: return f"mc_{uuid.uuid4().hex[:12]}" -def _empty_outcome(status: Status, *, message_count: int) -> BoundaryOutcome: +def _empty_outcome( + status: Status, *, message_count: int, detection: dict[str, Any] | None = None +) -> BoundaryOutcome: return BoundaryOutcome( cells=[], memcell_ids=[], @@ -426,4 +525,5 @@ def _empty_outcome(status: Status, *, message_count: int) -> BoundaryOutcome: per_cell_all_senders=[], status=status, message_count=message_count, + detection=detection, ) diff --git a/src/everos/memory/extract/boundary/messages.py b/src/everos/memory/extract/boundary/messages.py index 53f74e61f..2e11ac3f2 100644 --- a/src/everos/memory/extract/boundary/messages.py +++ b/src/everos/memory/extract/boundary/messages.py @@ -52,11 +52,17 @@ def filter_for_mode( def merge_dedupe_sort( buffered: Sequence[CanonicalMessage], new: Sequence[CanonicalMessage] ) -> list[CanonicalMessage]: - """Union by ``message_id`` (a buffered row wins), sorted by ``(timestamp, id)``.""" + """Union by ``message_id`` (a buffered row wins), sorted by timestamp. + + The sort is stable: rows sharing a timestamp keep arrival order, buffered + rows (in buffer order) before this call's (in request order). Ids carry no + order of their own (``ingest.message_ids``), so a tool result never sorts + ahead of the call it answers on a tie. + """ seen: dict[str, CanonicalMessage] = {m.message_id: m for m in buffered} for m in new: seen.setdefault(m.message_id, m) - return sorted(seen.values(), key=lambda m: (m.timestamp, m.message_id)) + return sorted(seen.values(), key=lambda m: m.timestamp) class Segmentation(NamedTuple): diff --git a/src/everos/memory/extract/ingest/__init__.py b/src/everos/memory/extract/ingest/__init__.py index 149360bbe..2dd1da36d 100644 --- a/src/everos/memory/extract/ingest/__init__.py +++ b/src/everos/memory/extract/ingest/__init__.py @@ -1,17 +1,17 @@ """Ingest Gateway — normalise external input into canonical form. External usage: - from everos.memory.extract.ingest import process, gen_message_id + from everos.memory.extract.ingest import process, message_ids The current implementation only handles text content; non-text ``ContentItem`` entries are dropped with a warning. The parser hook (``memory/extract/parser/``) is reserved for future milestones. """ -from .id_gen import gen_message_id as gen_message_id +from .id_gen import message_ids as message_ids from .service import process as process __all__ = [ - "gen_message_id", + "message_ids", "process", ] diff --git a/src/everos/memory/extract/ingest/id_gen.py b/src/everos/memory/extract/ingest/id_gen.py index a88c91968..ac1b67db9 100644 --- a/src/everos/memory/extract/ingest/id_gen.py +++ b/src/everos/memory/extract/ingest/id_gen.py @@ -1,17 +1,49 @@ """Deterministic, human-readable ``message_id`` generation. -Format: ``m___``. +Format: ``m___``. -Human-readable so logs / debugging / md entries stay greppable. Deterministic -so caller retries (same payload) produce the same ids — pipeline merge -naturally dedupes via the message_id PK in ``unprocessed_buffer``. +``digest`` is 8 hex chars of SHA-256 over who said what (``sender_id``, ``role``, +``content``, ``tool_call_id``, ``tool_calls``). Nothing in the id depends on where +the message sits in its request, so a client that resends a batch -- whole, split +or regrouped -- produces the same ids, and the boundary stage drops what it +already buffered or cut. Two different messages in one millisecond get two ids. + +A message repeated verbatim within one request (same sender, words and +millisecond) is told apart by how many identical ones came before it in that +request; only then does the count enter the digest. Order among messages that +share a millisecond is not in the id: the boundary stage keeps arrival order. """ from __future__ import annotations -_IDX_PAD = 3 # caller batches are capped at 500 messages (DTO limit), 3 digits cover it +import hashlib +import json +from collections import Counter +from collections.abc import Mapping, Sequence +from typing import Any + +_IDENTITY_FIELDS = ("sender_id", "role", "content", "tool_call_id", "tool_calls") + + +def _digest(message: Mapping[str, Any], repeat: int) -> str: + basis: list[Any] = [message.get(field) for field in _IDENTITY_FIELDS] + if repeat: + basis.append(repeat) + raw = json.dumps(basis, sort_keys=True, ensure_ascii=False, default=str) + return hashlib.sha256(raw.encode("utf-8")).hexdigest()[:8] -def gen_message_id(session_id: str, timestamp_ms: int, idx: int) -> str: - """Return ``m___``.""" - return f"m_{session_id}_{timestamp_ms}_{idx:0{_IDX_PAD}d}" +def message_ids(session_id: str, messages: Sequence[Mapping[str, Any]]) -> list[str]: + """The id of each message of one request, in order.""" + seen: Counter[str] = Counter() + ids = [] + for message in messages: + ts_ms = int(message["timestamp"]) + first = f"m_{session_id}_{ts_ms}_{_digest(message, 0)}" + ids.append( + first + if not seen[first] + else f"m_{session_id}_{ts_ms}_{_digest(message, seen[first])}" + ) + seen[first] += 1 + return ids diff --git a/src/everos/memory/extract/ingest/service.py b/src/everos/memory/extract/ingest/service.py index acbfe5283..548e93534 100644 --- a/src/everos/memory/extract/ingest/service.py +++ b/src/everos/memory/extract/ingest/service.py @@ -35,7 +35,7 @@ require_multimodal, ) -from .id_gen import gen_message_id +from .id_gen import message_ids from .multimodal import coerce_items, derive_text from .sender_names import resolve_sender_names, sender_name_of @@ -75,7 +75,8 @@ async def process( canonical: list[CanonicalMessage] = [] non_text_total = 0 - for idx, m in enumerate(raw_messages): + ids = message_ids(session_id, raw_messages) + for m, message_id in zip(raw_messages, ids, strict=True): content_items = coerce_items(m["content"]) if has_unparsed_multimodal(content_items): require_multimodal() @@ -88,9 +89,7 @@ async def process( text, non_text = derive_text(content_items) non_text_total += non_text - ts_ms: int = int(m["timestamp"]) - message_id = gen_message_id(session_id, ts_ms, idx) - ts = from_timestamp(ts_ms) + ts = from_timestamp(int(m["timestamp"])) canonical.append( CanonicalMessage( diff --git a/src/everos/memory/extract/language.py b/src/everos/memory/extract/language.py new file mode 100644 index 000000000..51829d32a --- /dev/null +++ b/src/everos/memory/extract/language.py @@ -0,0 +1,73 @@ +"""The language a memcell's episode is written in, decided before it is written. + +everalgo's ``LanguageDetector`` names the language of the cell's chat messages +in one short call on the ``language`` task's model. The pipeline asks once per +memcell, before the episode extraction and outside its retries, so a retried +extraction neither asks again nor lands in another language. The episode is +written in the answer, which is then pinned on the episode and on +``EpisodeExtracted``, so the summary, the atomic facts and the profile follow +it. + +Never raises: a cell without chat text, or a failed call, gives ``None``, and +the episode is written as it was before the decision existed -- the episode +model picks the language and the pipeline reads it off the text. +""" + +from __future__ import annotations + +__all__ = ["decide_output_language"] + +from typing import TYPE_CHECKING + +from everos.core.observability.logging import get_logger +from everos.core.observability.tracing import memory_span + +if TYPE_CHECKING: + from everalgo.types import MemCell + from everalgo.user_memory import LanguageDetector, OutputLanguage + +logger = get_logger(__name__) + + +async def decide_output_language( + detector: LanguageDetector, cell: MemCell, *, memcell_id: str +) -> OutputLanguage | None: + """The language ``cell``'s episode is written in; ``None`` leaves it to the model. + + Args: + detector: Names the language of the cell's chat messages. + cell: The memcell about to be extracted. + memcell_id: The cell's id, for the log lines. + + Returns: + Chinese, Japanese or English (any other language comes back as + English); ``None`` when no chat message has text (no call is made) or + the call fails. + """ + with memory_span( + "everos.extract.language", + observation_type="generation", + metadata={"memcell_id": memcell_id}, + ): + try: + language = await detector.adetect(cell.items) + except Exception as exc: + # Undecided is the state every episode was written in before this + # call existed, so no failure of it may fail the write. + logger.warning( + "episode_language_undecided", + memcell_id=memcell_id, + reason="failed", + error_type=type(exc).__name__, + error=str(exc)[:200], + ) + return None + if language is None: + logger.info( + "episode_language_undecided", memcell_id=memcell_id, reason="no_chat" + ) + return None + logger.info( + "episode_language_decided", memcell_id=memcell_id, language=language.value + ) + return language diff --git a/src/everos/memory/extract/pipeline/user_memory.py b/src/everos/memory/extract/pipeline/user_memory.py index 083f90803..3d6c3438c 100644 --- a/src/everos/memory/extract/pipeline/user_memory.py +++ b/src/everos/memory/extract/pipeline/user_memory.py @@ -6,10 +6,14 @@ user-perspective output of one cell: Episode md, plus the ``EpisodeExtracted`` event that announces it. -Each cell costs one model call (``EpisodeExtractor.aextract``). Every copy -is written with :func:`~everos.memory.episode_summary.placeholder_summary` -as its summary; the ``summarize_episode`` strategy writes the model's preview -afterwards, from the episode text and in its language. +Each cell costs two model calls: the language decision +(:func:`~everos.memory.extract.language.decide_output_language`), then the +episode (``EpisodeExtractor.aextract``), written in the decided language. The +language stored on the episode and its event is the decided one, else the one +the episode's text is written in. Every copy is written with +:func:`~everos.memory.episode_summary.placeholder_summary` as its summary; the +``summarize_episode`` strategy writes the model's preview afterwards, from the +episode text and in its language. ``MemoryService.add`` runs it cell by cell alongside :class:`AgentMemoryPipeline` (the latter only in ``mode="agent"``) and @@ -23,20 +27,26 @@ from everalgo.types import Episode as AlgoEpisode from everalgo.types import MemCell as AlgoMemCell -from everalgo.user_memory import EpisodeExtractor +from everalgo.user_memory import EpisodeExtractor, LanguageDetector +from everos.core.observability.logging import get_logger from everos.core.observability.tracing import capture_output, memory_span from everos.core.utils.language import detect_output_language from everos.memory.custom_instructions import CustomInstructions from everos.memory.episode_summary import placeholder_summary from everos.memory.events import EpisodeCopy, EpisodeExtracted +from everos.memory.extract.language import decide_output_language from everos.memory.extract.llm_retry import retry_llm_output from everos.memory.extract.pipeline.base import CellOutcome, PreparedCell +from everos.memory.extract.trace import record_construction from everos.memory.models import Episode, IngestResult from everos.memory.ports import EpisodeStore, Event, MemcellStore, MemoryRef, Scope if TYPE_CHECKING: from everalgo.llm import LLMClient + from everalgo.user_memory import OutputLanguage + +logger = get_logger(__name__) class UserMemoryPipeline: @@ -47,6 +57,7 @@ class UserMemoryPipeline: memcell_store: Whether the cell still exists when its episodes are written (a session deletion removes it first). instructions: Custom instructions for the episode operator. + language_llm: LLM for the language decision. episode_llm: LLM for the episode extraction. tz: The zone message times are shown to the model in. """ @@ -57,9 +68,11 @@ def __init__( memcell_store: MemcellStore, instructions: CustomInstructions, *, + language_llm: LLMClient, episode_llm: LLMClient, tz: tzinfo = UTC, ) -> None: + self._language_detector = LanguageDetector(llm=language_llm) self._ep_ext = EpisodeExtractor(llm=episode_llm) self._episode_store = episode_store self._memcell_store = memcell_store @@ -79,10 +92,28 @@ async def run_cell( md_paths: list[str] = [] user_senders = _unique_user_senders(cell) if user_senders: - algo_ep = await self._extract_episode(ingested, prepared) - # The model writes in the conversation's language; what it chose - # pins every extraction downstream of this episode. - language = detect_output_language(algo_ep.episode) + record_construction( + "extraction_attempt", + app_id=ingested.app_id, + project_id=ingested.project_id, + session_id=ingested.session_id, + memcell_id=memcell_id, + owners=user_senders, + ) + decided = await decide_output_language( + self._language_detector, cell, memcell_id=memcell_id + ) + algo_ep = await self._extract_episode(ingested, prepared, decided) + record_construction( + "extraction_result", + app_id=ingested.app_id, + project_id=ingested.project_id, + session_id=ingested.session_id, + memcell_id=memcell_id, + owners=user_senders, + content=algo_ep.episode, + ) + language = _stored_language(decided, algo_ep.episode) written = await self._write_copies( ingested, prepared, algo_ep, senders=user_senders, language=language ) @@ -101,6 +132,13 @@ async def run_cell( language=language, ) ) + logger.info( + "episode_written", + memcell_id=memcell_id, + owners=len(written), + language=language, + language_from="decided" if decided else "text", + ) return CellOutcome( message_count=len(cell.items), events=events, @@ -108,13 +146,17 @@ async def run_cell( ) async def _extract_episode( - self, ingested: IngestResult, prepared: PreparedCell + self, + ingested: IngestResult, + prepared: PreparedCell, + language: OutputLanguage | None, ) -> AlgoEpisode: """One whole-cell episode, shared by every user sender of the cell. ``sender_id=None`` binds the episode to no user; the fan-out to one - copy per sender happens in markdown only, so a cell costs one model - call. An unusable reply is tried again by :func:`retry_llm_output`. + copy per sender happens in markdown only, so a cell costs one episode + call. It is written in ``language``; ``None`` leaves the language to + the model. An unusable reply is tried again by :func:`retry_llm_output`. """ extractor = self._ep_ext custom_instructions = self._instructions.load("episode_extract") @@ -124,6 +166,7 @@ async def attempt() -> AlgoEpisode: prepared.cell, sender_id=None, custom_instructions=custom_instructions, + output_language=language, tz=self._tz, ) @@ -216,6 +259,15 @@ async def memcell_alive() -> bool: ) if ref is None: return None + record_construction( + "persisted_episode", + app_id=ingested.app_id, + project_id=ingested.project_id, + session_id=ingested.session_id, + memcell_id=memcell_id, + owners=[ep.owner_id], + entry_id=ref.entry_id, + ) # Written .md path, memory-root-relative (only when # capture_content is on) — never the host absolute path. capture_output(persist_span, ref.md_path) @@ -225,6 +277,15 @@ async def memcell_alive() -> bool: # ── Helpers ─────────────────────────────────────────────────────────────── +def _stored_language(decided: OutputLanguage | None, episode: str) -> str | None: + """The language an episode is stored with: the decided one, else its text's. + + It pins every extraction downstream of the episode. Read off the text only + when nothing was decided, since then the model chose the language. + """ + return decided.value if decided else detect_output_language(episode) + + def _unique_user_senders(cell: AlgoMemCell) -> list[str]: """Distinct role=user sender_ids in a cell, preserving order. diff --git a/src/everos/memory/extract/trace.py b/src/everos/memory/extract/trace.py new file mode 100644 index 000000000..147e17653 --- /dev/null +++ b/src/everos/memory/extract/trace.py @@ -0,0 +1,50 @@ +"""Request-local construction evidence; no tracing or persistence dependency.""" + +from __future__ import annotations + +import copy +from collections.abc import Callable, Iterator +from contextlib import contextmanager +from contextvars import ContextVar +from typing import Any + +from everos.core.utils.datetime import get_utc_now + +_EVENTS: ContextVar[list[dict[str, Any]] | None] = ContextVar( + "everos_construction_events", default=None +) + + +def record_construction( + phase: str, + *, + snapshot_factory: Callable[[], dict[str, Any]] | None = None, + **values: Any, +) -> None: + """Snapshot a real boundary or extractor result, including empty results.""" + events = _EVENTS.get() + if events is None: + return + try: + if snapshot_factory is not None: + values.update(snapshot_factory()) + events.append( + { + "phase": phase, + "observed_at": get_utc_now().isoformat(), + **copy.deepcopy(values), + } + ) + except Exception: + return + + +@contextmanager +def collect_construction_trace() -> Iterator[list[dict[str, Any]]]: + """Isolate each request while allowing its pipeline tasks to share evidence.""" + events: list[dict[str, Any]] = [] + token = _EVENTS.set(events) + try: + yield events + finally: + _EVENTS.reset(token) diff --git a/src/everos/memory/models.py b/src/everos/memory/models.py index 9bac430d4..9a6717cba 100644 --- a/src/everos/memory/models.py +++ b/src/everos/memory/models.py @@ -123,9 +123,11 @@ class Episode(BaseModel): parent_id: str parent_type: EpisodeParentType = "memcell" language: str | None = None - """The ``OutputLanguage`` value the episode is written in, detected from - its text; downstream extractions are pinned to it. ``None`` when unknown - (an episode stored before it existed, or text with no letters).""" + """The ``OutputLanguage`` value the episode is written in; downstream + extractions are pinned to it. A pipeline episode stores the language + decided for its memcell, else the one read off its text; a merged episode + stores the one Reflection wrote it in. ``None`` when unknown (an episode + stored before it existed, or text with no letters).""" model_config = ConfigDict(extra="allow") diff --git a/src/everos/memory/ports/stores.py b/src/everos/memory/ports/stores.py index 8ee62e352..b6e33c893 100644 --- a/src/everos/memory/ports/stores.py +++ b/src/everos/memory/ports/stores.py @@ -359,6 +359,12 @@ async def quarantine( """Set the buffer (plus ``extra``) aside; return how many moved.""" ... + async def already_cut( + self, session: SessionKey, message_ids: Sequence[str] + ) -> set[str]: + """Which of ``message_ids`` a memcell of the session already holds.""" + ... + @runtime_checkable class MemcellStore(Protocol): diff --git a/src/everos/memory/reflection/_language.py b/src/everos/memory/reflection/_language.py new file mode 100644 index 000000000..8ccc473f8 --- /dev/null +++ b/src/everos/memory/reflection/_language.py @@ -0,0 +1,88 @@ +"""Which language a Reflection merge is written in. + +A merged episode spans many conversations of one owner, the way the profile +does, so it follows the owner's profile language (``Profile.primary_language``, +frozen once known). Before the owner has one, the members vote with the +languages they were stored with. A split vote names nothing: the reflector +picks the language and it is read off the merged text afterwards. The +language the merge is asked for and the one it is stored with are kept apart +so the log can say where the stored one came from. +""" + +from __future__ import annotations + +__all__ = ["LanguageChoice", "merged_language", "steer_language"] + +from collections import Counter +from collections.abc import Sequence +from typing import TYPE_CHECKING, Literal, NamedTuple + +from everos.core.utils.language import detect_output_language + +if TYPE_CHECKING: + from everos.memory.models import Episode + from everos.memory.ports import Stored + +_MAJORITY_SHARE = 0.6 +"""Share of the members the winning language must exceed (strictly). + +A 3-2 split lands on 0.6 and is refused: answered with its narrow winner, a +genuinely mixed cluster would be merged into a language the owner only half +uses. 2 of 2 and 2 of 3 decide, 1 of 2 does not.""" + + +class LanguageChoice(NamedTuple): + """A language and where it came from. + + Attributes: + value: The ``OutputLanguage`` value; ``None`` leaves it to the model. + source: ``"profile"`` (the owner's frozen language), ``"vote"`` (the + members' majority) or ``"text"`` (read off the merged episode). + """ + + value: str | None + source: Literal["profile", "vote", "text"] + + +def steer_language( + owner_language: str | None, members: Sequence[Stored[Episode]] +) -> LanguageChoice: + """The language the reflector is asked to write the merge in. + + Args: + owner_language: The owner's profile language; ``None`` without one. + members: The cluster's episodes sent to the merge. + """ + if owner_language: + return LanguageChoice(owner_language, "profile") + return LanguageChoice(_vote(members), "vote") + + +def merged_language(steer: LanguageChoice, merged_text: str) -> LanguageChoice: + """The language the merged episode is stored with. + + The steer when it named one; otherwise the reflector chose, and the + language is read off ``merged_text``. + """ + if steer.value is not None: + return steer + return LanguageChoice(detect_output_language(merged_text), "text") + + +def _vote(members: Sequence[Stored[Episode]]) -> str | None: + """The language a clear majority of ``members`` are written in, else ``None``. + + Each member votes with its stored ``language``; one stored without any (an + episode written before the field existed) votes with the one read off its + text. A member with no readable language abstains but still counts. + """ + if not members: + return None + readings = [ + m.item.language or detect_output_language(m.item.episode) for m in members + ] + counts = Counter(reading for reading in readings if reading is not None) + if not counts: + return None + language, hits = counts.most_common(1)[0] + return language if hits / len(readings) > _MAJORITY_SHARE else None diff --git a/src/everos/memory/reflection/orchestrator.py b/src/everos/memory/reflection/orchestrator.py index c12561e60..0575c79be 100644 --- a/src/everos/memory/reflection/orchestrator.py +++ b/src/everos/memory/reflection/orchestrator.py @@ -19,6 +19,10 @@ episode stays without facts and the originals stay live, which a later cycle detects as an orphan. +A merge is written in the owner's profile language, else the members' +majority language (:mod:`._language`); the merged episode and its event carry +the language it was written in, so its facts follow it. + See ``local/2026-06-14-reflection-everos-design.md`` for the full design. """ @@ -54,6 +58,7 @@ EpisodeStore, Filter, MemcellStore, + ProfileStore, ReflectionReportStore, Scope, SourceCheck, @@ -63,6 +68,11 @@ is_null, one_of, ) +from everos.memory.reflection._language import ( + LanguageChoice, + merged_language, + steer_language, +) logger = get_logger(__name__) @@ -89,6 +99,8 @@ class ReflectionOrchestrator: episode_index: Episode reads (members, orphans). memcell_store: Whether a source episode's memcell still exists. report_store: Reflection audit trail (which clusters were merged). + profile_store: The owner's profile, whose frozen language every merge + of the owner is written in. reflector: Algorithm-side EpisodeReflector (areflect). custom_instructions: Appended to the reflector's rules; ``None`` for none. """ @@ -101,6 +113,7 @@ def __init__( episode_index: EpisodeIndex, memcell_store: MemcellStore, report_store: ReflectionReportStore, + profile_store: ProfileStore, reflector: EpisodeReflector, custom_instructions: str | None = None, ) -> None: @@ -109,6 +122,7 @@ def __init__( self._episode_index = episode_index self._memcell_store = memcell_store self._report_store = report_store + self._profile_store = profile_store self._reflector = reflector self._custom_instructions = custom_instructions @@ -137,10 +151,11 @@ async def run( if not candidates: return [] + owner_language = await self._owner_language(scope) merged: list[EpisodeExtracted] = [] for cluster_id in candidates: event = await self._process_cluster_safely( - cluster_id=cluster_id, scope=scope + cluster_id=cluster_id, scope=scope, owner_language=owner_language ) if event is not None: merged.append(event) @@ -154,7 +169,7 @@ async def run( return merged async def _process_cluster_safely( - self, *, cluster_id: str, scope: Scope + self, *, cluster_id: str, scope: Scope, owner_language: str | None ) -> EpisodeExtracted | None: """Merge one cluster, catching errors to allow the cycle to continue. @@ -162,7 +177,9 @@ async def _process_cluster_safely( The merged episode's event on success, ``None`` on skip or error. """ try: - return await self._process_cluster(cluster_id=cluster_id, scope=scope) + return await self._process_cluster( + cluster_id=cluster_id, scope=scope, owner_language=owner_language + ) except AppError: logger.warning( "reflection_cluster_skipped", @@ -204,10 +221,15 @@ async def _select_candidates(self, *, scope: Scope, kind: ClusterKind) -> list[s # ── Per-cluster processing ──────────────────────────────────────────── async def _process_cluster( - self, *, cluster_id: str, scope: Scope + self, *, cluster_id: str, scope: Scope, owner_language: str | None ) -> EpisodeExtracted | None: """Merge one cluster and write the merged episode. + Args: + cluster_id: The cluster to merge. + scope: The owner scope it belongs to. + owner_language: The owner's profile language; ``None`` without one. + Returns: The merged episode's event, ``None`` on skip. """ @@ -230,11 +252,13 @@ async def _process_cluster( return None await self._detect_orphans(cluster_id, scope) + steer = steer_language(owner_language, episodes) mode, algo_result = await self._reflect_cluster( - episodes=episodes, owner_id=scope.owner_id + episodes=episodes, owner_id=scope.owner_id, output_language=steer.value ) if algo_result is None: return None + language = merged_language(steer, algo_result.episode) unchanged = await self._sources_alive(scope=scope, episodes=episodes) if unchanged is None: @@ -246,6 +270,7 @@ async def _process_cluster( scope=scope, algo_result=algo_result, last_ts=last_ts, + language=language, only_if=unchanged, ) if merged_entry_id is None: @@ -256,6 +281,8 @@ async def _process_cluster( mode=mode, source_count=len(members), merged_entry_id=merged_entry_id, + language=language.value, + language_from=language.source, ) return EpisodeExtracted( memcell_id=merged_entry_id, @@ -266,6 +293,7 @@ async def _process_cluster( app_id=scope.app_id, project_id=scope.project_id, source="reflection", + language=language.value, reflection=ReflectionContext( cluster_id=cluster_id, mode=mode, @@ -284,7 +312,11 @@ async def _process_cluster( ) async def _reflect_cluster( - self, *, episodes: list[StoredEpisode], owner_id: str + self, + *, + episodes: list[StoredEpisode], + owner_id: str, + output_language: str | None, ) -> tuple[ReflectionMode, AlgoEpisode | None]: """Determine reflection mode and call the algo reflector. @@ -302,6 +334,7 @@ async def _reflect_cluster( merged_entry_ids=merged_entry_ids, is_update=is_update, owner_id=owner_id, + output_language=output_language, ) return mode, algo_result @@ -329,6 +362,7 @@ async def _write_merged_episode( scope: Scope, algo_result: AlgoEpisode, last_ts: int, + language: LanguageChoice, only_if: SourceCheck, ) -> str | None: """Write the merged episode to markdown; return its entry id. @@ -344,6 +378,7 @@ async def _write_merged_episode( subject=algo_result.subject, parent_id=cluster_id, parent_type="cluster", + language=language.value, ) refs = await self._episode_store.append_many(scope, [merged], only_if=only_if) return refs[0].entry_id if refs else None @@ -384,6 +419,24 @@ async def unchanged() -> bool: # ── Helpers ─────────────────────────────────────────────────────────── + async def _owner_language(self, scope: Scope) -> str | None: + """The owner's frozen profile language; ``None`` without a readable one. + + An unreadable ``user.md`` (a broken hand edit) must not stop the + owner's merges, nor, through the cron run, every other owner's: they + fall back to the members' vote. + """ + try: + profile = await self._profile_store.read(scope) + except Exception: + logger.warning( + "reflection_profile_unreadable", + owner_id=scope.owner_id, + exc_info=True, + ) + return None + return profile.primary_language if profile is not None else None + async def _detect_orphans(self, cluster_id: str, scope: Scope) -> None: """Log warning if orphan merged episodes exist for this cluster.""" where = all_of( @@ -414,6 +467,7 @@ async def _call_reflector( merged_entry_ids: list[str], is_update: bool, owner_id: str, + output_language: str | None, ) -> AlgoEpisode | None: """Call the algo reflector (INIT or UPDATE mode). @@ -423,6 +477,8 @@ async def _call_reflector( (parent_type=cluster). Empty for INIT. is_update: Whether this is an UPDATE (vs INIT) reflection. owner_id: Owner for logging on failure. + output_language: The language to merge in; ``None`` lets the + reflector choose. Returns: An algo Episode result, or ``None`` on failure. @@ -440,9 +496,12 @@ async def _call_reflector( algo_episodes=algo_episodes, episodes=episodes, merged_entry_ids=merged_entry_ids, + output_language=output_language, ) return await self._reflector.areflect( - algo_episodes, custom_instructions=self._custom_instructions + algo_episodes, + custom_instructions=self._custom_instructions, + output_language=output_language, ) except AppError: logger.warning( @@ -465,6 +524,7 @@ async def _reflect_update( algo_episodes: list[AlgoEpisode], episodes: list[StoredEpisode], merged_entry_ids: list[str], + output_language: str | None, ) -> AlgoEpisode | None: """Run UPDATE-mode reflection by splitting old/new episodes. @@ -481,6 +541,7 @@ async def _reflect_update( new_algo_eps, old_episode=old_algo_eps[0], custom_instructions=self._custom_instructions, + output_language=output_language, ) diff --git a/src/everos/memory/search/manager.py b/src/everos/memory/search/manager.py index 2fb702ba3..fd8a83dd2 100644 --- a/src/everos/memory/search/manager.py +++ b/src/everos/memory/search/manager.py @@ -86,6 +86,7 @@ shape_episodes, ) from .skill_hybrid import search_agent_skills_hybrid +from .trace import record_branch, record_stage if TYPE_CHECKING: from everalgo.llm import LLMClient @@ -317,12 +318,34 @@ async def _load_unprocessed( """ session_id = _extract_top_level_session_id(req.filters) if session_id is None: + record_branch( + "_load_unprocessed", + "unprocessed", + [], + status="skipped", + skip_reason="no_session_filter", + ) return [] session = SessionKey( app_id=req.app_id, project_id=req.project_id, session_id=session_id ) - messages = await self._session_buffer.list(session) - return [_unprocessed_message_to_dto(m, session) for m in messages] + try: + messages = await self._session_buffer.list(session) + results = [_unprocessed_message_to_dto(m, session) for m in messages] + except Exception as exc: + record_branch( + "_load_unprocessed", + "unprocessed", + [], + status="error", + session_id=session_id, + error_type=type(exc).__name__, + ) + raise + record_branch( + "_load_unprocessed", "unprocessed", results, session_id=session_id + ) + return results # ── Agent partition ───────────────────────────────────────────── @@ -384,7 +407,7 @@ async def _search_episodes( decider: RoundDecider | None = None, ) -> list[SearchEpisodeItem]: if req.method == SearchMethod.AGENTIC: - return await search_episodes_agentic( + results = await search_episodes_agentic( req.query, owner_id=req.owner_id, where=where, @@ -400,9 +423,11 @@ async def _search_episodes( radius=_effective_radius(req), tz=self._tz, ) + record_stage("agentic", "episode", results) + return results if req.method == SearchMethod.LLM_MULTIROUND: - return await search_episodes_llm_multiround( + results = await search_episodes_llm_multiround( req.query, owner_id=req.owner_id, where=where, @@ -418,6 +443,8 @@ async def _search_episodes( tuning_source=self._tuning_source, trace_path_source=self._trace_path_source, ) + record_stage("agentic", "episode", results) + return results fusion_mode, _ = resolve_pipeline(req.method, "episode") top_k = self._top_k( @@ -440,6 +467,8 @@ async def _search_episodes( ) else: recalled = await self._maxsim_atomic_recall(req, where, top_k) + if req.method == SearchMethod.KEYWORD: + record_stage("single_route", "episode", recalled.candidates) # ``atomic_facts`` stays empty: facts come back only when the HYBRID # pipeline surfaces them with a score (see ``reshape_hybrid_output``). # Single-route recall has no per-fact score against the query, so @@ -451,6 +480,7 @@ async def _search_episodes( shaped = await self._search_episodes_hybrid(req, where, top_k) if req.min_score is not None: shaped = [s for s in shaped if s.score >= req.min_score] + record_stage("filtered", "episode", shaped) return shaped async def _search_episodes_hybrid( @@ -473,6 +503,16 @@ async def _search_episodes_hybrid( lanes.facts.candidates, top_k=top_k, ) + record_stage( + "rrf", + "episode", + kept, + inputs=[ + ("episode", "sparse"), + ("episode", "dense"), + ("episode", "maxsim_atomic"), + ], + ) facts = await self._fact.facts_for_episodes( build_ep_to_fact_parents(kept), where, @@ -487,6 +527,7 @@ async def _search_episodes_hybrid( dense=lanes.dense.candidates, fact_lane=lanes.facts.candidates, ) + record_stage("hierarchy", "episode", scored) return reshape_hybrid_output( scored, episodes_by_id=merge_stored(lanes.sparse, lanes.dense, lanes.facts), @@ -526,10 +567,15 @@ async def _hybrid_lanes( ), ) radius = _effective_radius(req) + dense = dense.within_radius(radius) + facts = facts.within_radius(radius) + record_stage("sparse", "episode", sparse.candidates) + record_stage("dense", "episode", dense.candidates) + record_stage("maxsim_atomic", "episode", facts.candidates) return _HybridLanes( sparse=sparse, - dense=dense.within_radius(radius), - facts=facts.within_radius(radius), + dense=dense, + facts=facts, vector=vector, ) @@ -539,7 +585,7 @@ async def _search_agent_cases( self, req: SearchRequest, where: Filter ) -> list[SearchAgentCaseItem]: if req.method == SearchMethod.AGENTIC: - return await search_agent_cases_agentic( + results = await search_agent_cases_agentic( req.query, where=where, case_recaller=self._case, @@ -550,6 +596,8 @@ async def _search_agent_cases( radius=_effective_radius(req), tz=self._tz, ) + record_stage("agentic", "agent_case", results) + return results fusion_mode, _ = resolve_pipeline(req.method, "agent_case") enable_rerank = _effective_llm_rerank(req) top_k = self._top_k(req.top_k, cap=_AGENT_TOP_K_CAP) @@ -583,6 +631,12 @@ async def _search_agent_cases( enable_rerank=enable_rerank, rerank_top_k=top_k, ) + record_stage( + "fusion", + "agent_case", + output.items, + metadata={"fusion_mode": fusion_mode, "enable_rerank": enable_rerank}, + ) return shape_agent_cases_ranked(output, merge_stored(sparse, dense)) # ── Agent skills ──────────────────────────────────────────────── @@ -600,7 +654,7 @@ async def _search_agent_skills( skill's ``source_case_ids`` holds the md-side entry ids. """ if req.method == SearchMethod.AGENTIC: - return await search_agent_skills_agentic( + results = await search_agent_skills_agentic( req.query, where=where, skill_recaller=self._skill, @@ -611,6 +665,8 @@ async def _search_agent_skills( radius=_effective_radius(req), tz=self._tz, ) + record_stage("agentic", "agent_skill", results) + return results fusion_mode, _ = resolve_pipeline(req.method, "agent_skill") top_k = self._top_k(req.top_k, cap=_AGENT_TOP_K_CAP) @@ -633,6 +689,12 @@ async def _search_agent_skills( case_scores, where, top_k=top_k ) dense = merge_by_id_max(dense, bridged) + bridge_inputs = [("agent_skill", "dense")] + if case_scores is not None: + bridge_inputs.append(("agent_case", "fusion")) + record_stage( + "bridged_dense", "agent_skill", dense.candidates, inputs=bridge_inputs + ) # Lane selection lives here so ``skill_hybrid`` stays single-purpose # (cross-encoder) and symmetry with the case path is preserved. @@ -659,13 +721,23 @@ async def _search_agent_skills( enable_rerank=True, rerank_top_k=top_k, ) + record_stage( + "fusion", + "agent_skill", + output.items, + metadata={"fusion_mode": "rrf", "enable_rerank": True}, + inputs=[ + ("agent_skill", "sparse"), + ("agent_skill", "bridged_dense"), + ], + ) return shape_agent_skills_ranked(output, merge_stored(sparse, dense)) # Cross-encoder lane (default): rrf + skill-shaped cross-encoder rerank. # The rank span is emitted inside build_skill_rerank_fn (callbacks), # so the cross-encoder rerank is covered uniformly with the agentic # path rather than double-wrapped here. - return await search_agent_skills_hybrid( + results = await search_agent_skills_hybrid( req.query, sparse=sparse, dense=dense, @@ -673,6 +745,14 @@ async def _search_agent_skills( top_k=top_k, rerank_pool=self._recall_limit(req.top_k, cap=_AGENT_HYBRID_LANE_CAP), ) + record_stage( + "fusion", + "agent_skill", + results, + metadata={"fusion_mode": "skill_hybrid", "enable_rerank": False}, + inputs=[("agent_skill", "sparse"), ("agent_skill", "bridged_dense")], + ) + return results # ── Profile ───────────────────────────────────────────────────── @@ -700,14 +780,17 @@ async def _single_route_recall( metadata={"phase": "single_route", "method": req.method.value}, ): if req.method == SearchMethod.KEYWORD: - return await recaller.sparse_recall( + recalled = await recaller.sparse_recall( req.query, where, limit=self._recall_limit(req.top_k, cap=cap) ) - vector = await self._embed_query(req.query) - recalled = await recaller.dense_recall( - vector, where, limit=self._recall_limit(req.top_k, cap=cap) - ) - return recalled.within_radius(_effective_radius(req)) + else: + vector = await self._embed_query(req.query) + recalled = await recaller.dense_recall( + vector, where, limit=self._recall_limit(req.top_k, cap=cap) + ) + recalled = recalled.within_radius(_effective_radius(req)) + record_stage("single_route", recaller.kind, recalled.candidates) + return recalled async def _recall_sparse_dense( self, @@ -735,7 +818,10 @@ async def _recall_sparse_dense( if vector else _no_recall(), ) - return sparse, dense.within_radius(_effective_radius(req)) + dense = dense.within_radius(_effective_radius(req)) + record_stage("sparse", recaller.kind, sparse.candidates) + record_stage("dense", recaller.kind, dense.candidates) + return sparse, dense async def _maxsim_atomic_recall( self, req: SearchRequest, where: Filter, top_k: int @@ -751,7 +837,9 @@ async def _maxsim_atomic_recall( fallback_limit=self._recall_limit(req.top_k), owner_id=req.owner_id, ) - return recalled.within_radius(_effective_radius(req)) + recalled = recalled.within_radius(_effective_radius(req)) + record_stage("maxsim_atomic", "episode", recalled.candidates) + return recalled async def _embed_query(self, query: str) -> list[float]: if self._embedding is None: diff --git a/src/everos/memory/search/trace.py b/src/everos/memory/search/trace.py new file mode 100644 index 000000000..125ce2748 --- /dev/null +++ b/src/everos/memory/search/trace.py @@ -0,0 +1,201 @@ +"""Request-level search-stage trace collector (MemTrace support). + +The MemTrace tracer (:mod:`everos.infra.memtrace`) records the candidate +pool at each stage of the search pipeline so the exported execution graph +can answer "was the evidence in the recall pool, did it survive fusion, +was it returned". To keep the memory layer free of any tracing +dependency, this module exposes a zero-dependency collection protocol: + +* :func:`record_stage` is called by the search manager at each pipeline + stage. Without an installed collector it is a no-op; it never raises, + so tracing can never break the search path. +* :func:`collect_search_trace` is entered once per ``/memory/search`` + request by the service layer and returns the ordered stage records. + +Isolation is by :class:`contextvars.ContextVar`: concurrent search +requests (each entering its own ``collect_search_trace``) never share a +collector, while the ``asyncio.gather`` fan-out inside one request +inherits it, so episode / agent-case / agent-skill stages of the same +request land in one list. + +Stage ``phase`` vocabulary: ``sparse`` / ``dense`` (per-route recall), +``single_route`` (KEYWORD / VECTOR one-route recall), ``maxsim_atomic`` +(VECTOR episode max-pool; also the atomic-fact lane of episode HYBRID), +``rrf`` / ``hierarchy`` / ``filtered`` +(episode HYBRID hierarchy pipeline), ``fusion`` (everalgo rank output), +``bridged_dense`` (case→skill bridge merged dense pool), ``agentic``. +``kind`` is the recaller business kind: ``episode`` / ``agent_case`` / +``agent_skill``. +""" + +from __future__ import annotations + +from collections.abc import Iterator, Mapping, Sequence +from contextlib import contextmanager +from contextvars import ContextVar +from dataclasses import dataclass, field +from typing import Any + +from everos.core.utils.datetime import get_utc_now + +# Per-stage candidate cap — mirrors the pool-size ceiling used by the +# EverOS-1 inline instrumentation; keeps the exported graph bounded when +# unlimited mode recalls pools of 100+ candidates. +STAGE_CANDIDATE_CAP = 50 + + +@dataclass(frozen=True) +class CandidateBrief: + """One candidate reduced to its identity triple (id, score, source).""" + + id: str + score: float + source: str + + +@dataclass(frozen=True) +class SearchStageRecord: + """The candidate pool observed at one stage of the search pipeline. + + ``total_count`` is the pool size before the ``STAGE_CANDIDATE_CAP`` + truncation (``-1`` when the source iterable exposed no length), so + consumers can tell a capped pool snapshot from a complete one. + """ + + phase: str + kind: str + candidates: tuple[CandidateBrief, ...] + total_count: int = 0 + metadata: Mapping[str, Any] = field(default_factory=dict) + stage_id: str = "" + input_stage_ids: tuple[str, ...] | None = None + + +_STAGE_COLLECTOR: ContextVar[list[SearchStageRecord] | None] = ContextVar( + "everos_search_stage_collector", default=None +) + + +def record_stage( + phase: str, + kind: str, + candidates: Sequence[Any], + *, + metadata: Mapping[str, Any] | None = None, + inputs: Sequence[tuple[str, str]] | None = None, +) -> None: + """Append one stage record to the active collector, if any. + + No-op when no collector is installed (the default outside a + ``collect_search_trace`` scope); never raises — a malformed candidate + or collector failure must not break search. + + Args: + phase (`str`): + Pipeline phase name (see module docstring for the vocabulary). + kind (`str`): + Business kind of the recalled candidates. + candidates (`Sequence[Any]`): + Candidates at this stage; each is reduced to its + ``id`` / ``score`` / ``source`` triple (attributes read + defensively) and capped at :data:`STAGE_CANDIDATE_CAP`. + metadata (`Mapping[str, Any] | None`, optional): + Stage annotations (e.g. ``fusion_mode``, ``enable_rerank``). + """ + collector = _STAGE_COLLECTOR.get() + if collector is None: + return + try: + try: + total_count = len(candidates) + except TypeError: + total_count = -1 # The iterable exposed no length. + briefs = tuple( + CandidateBrief( + id=str(getattr(candidate, "id", "")), + score=float(getattr(candidate, "score", 0.0) or 0.0), + source=str(getattr(candidate, "source", "") or ""), + ) + for candidate in candidates[:STAGE_CANDIDATE_CAP] + ) + stage_id = f"{kind}:{phase}:{len(collector)}" + resolved_inputs: list[str] = [] + if inputs is not None: + for input_kind, input_phase in inputs: + parent = next( + ( + s + for s in reversed(collector) + if s.kind == input_kind and s.phase == input_phase + ), + None, + ) + if parent is None: + raise ValueError("Missing input search stage.") + resolved_inputs.append(parent.stage_id) + collector.append( + SearchStageRecord( + phase=phase, + kind=kind, + candidates=briefs, + total_count=total_count, + metadata=dict(metadata) if metadata else {}, + stage_id=stage_id, + input_stage_ids=tuple(resolved_inputs) if inputs is not None else None, + ) + ) + except Exception: # tracing must never break the search path + return + + +def record_branch( + function: str, + kind: str, + results: Sequence[Any], + *, + status: str = "success", + **metadata: Any, +) -> None: + """Record an independent KV/buffer branch, including skips and empty reads. + + DTO snapshots are evaluated only with an active request collector. These + branches depend on the request, never on the episode ranking stages. + """ + if _STAGE_COLLECTOR.get() is None: + return + try: + record_stage( + function, + kind, + results, + inputs=[], + metadata={ + "function": function, + "status": status, + "observed_at": get_utc_now().isoformat(), + "items": [r.model_dump(mode="json") for r in results], + **metadata, + }, + ) + except Exception: + return + + +@contextmanager +def collect_search_trace() -> Iterator[list[SearchStageRecord]]: + """Install a fresh stage collector for one search request. + + Yields the list that :func:`record_stage` appends to; the collector + is uninstalled on exit, so nested or subsequent requests always start + from an empty record. + + Returns: + `Iterator[list[SearchStageRecord]]`: + The ordered stage records collected within the scope. + """ + stages: list[SearchStageRecord] = [] + token = _STAGE_COLLECTOR.set(stages) + try: + yield stages + finally: + _STAGE_COLLECTOR.reset(token) diff --git a/src/everos/memory/strategies/extract_atomic_facts.py b/src/everos/memory/strategies/extract_atomic_facts.py index 14ffed90a..f6e74c636 100644 --- a/src/everos/memory/strategies/extract_atomic_facts.py +++ b/src/everos/memory/strategies/extract_atomic_facts.py @@ -56,6 +56,7 @@ async def extract_atomic_facts( session_id=event.session_id, count=len(algo_facts), owners=len(event.copies), + language=event.language, ) return list(done) diff --git a/src/everos/memory/strategies/extract_user_profile.py b/src/everos/memory/strategies/extract_user_profile.py index 7fbb16e8b..3cbf3ec54 100644 --- a/src/everos/memory/strategies/extract_user_profile.py +++ b/src/everos/memory/strategies/extract_user_profile.py @@ -51,6 +51,7 @@ import asyncio from collections.abc import Collection +from typing import Literal from everalgo.types import Profile as AlgoProfile from everalgo.user_memory import ProfileExtractor @@ -107,7 +108,7 @@ async def _fold( existing = await deps.stores.profile.read(scope) waiting = await _waiting_episodes(scope, existing, event, deps) batch = [*own, *waiting] - language = _profile_language(existing, event) + language, language_from = _profile_language(existing, event) new_profile = await _extract( event, deps, episodes=batch, existing=existing, language=language ) @@ -123,6 +124,8 @@ async def _fold( episodes=len(batch), mode="UPDATE" if existing is not None else "INIT", written=new_profile is not None, + language=language, + language_from=language_from, ) @@ -201,16 +204,19 @@ async def _extract( def _profile_language( existing: Profile | None, event: EpisodeExtractedForOwner -) -> str | None: - """The language to write the profile in, frozen once known. +) -> tuple[str | None, Literal["frozen", "event"] | None]: + """The language to write the profile in, frozen once known, and its source. - A stored profile's ``primary_language`` wins and is never changed - automatically; changing it is a manual edit. Until one is stored, the - triggering episode's language is used and then frozen. + A stored profile's ``primary_language`` wins (``"frozen"``) and is never + changed automatically; changing it is a manual edit. Until one is stored, + the triggering episode's language is used (``"event"``) and then frozen. + ``(None, None)`` when neither has one: the model picks the language. """ if existing is not None and existing.primary_language: - return existing.primary_language - return event.language + return existing.primary_language, "frozen" + if event.language: + return event.language, "event" + return None, None EXTRACT_USER_PROFILE_SPEC = StrategySpec( diff --git a/src/everos/memory/strategies/reflect_episodes.py b/src/everos/memory/strategies/reflect_episodes.py index 7e5a776ea..c3e7f9411 100644 --- a/src/everos/memory/strategies/reflect_episodes.py +++ b/src/everos/memory/strategies/reflect_episodes.py @@ -59,6 +59,7 @@ async def reflect_episodes(event: CronTick, deps: MemoryDeps) -> list[Event]: episode_index=deps.indexes.episode, memcell_store=deps.stores.memcell, report_store=deps.stores.reflection_report, + profile_store=deps.stores.profile, reflector=EpisodeReflector(llm=deps.llms.reflection), custom_instructions=deps.instructions.load("reflect"), ) diff --git a/src/everos/service/bootstrap.py b/src/everos/service/bootstrap.py index 4013e1ccf..e15cdbde6 100644 --- a/src/everos/service/bootstrap.py +++ b/src/everos/service/bootstrap.py @@ -90,6 +90,7 @@ DeleteFence, FencedIndexEraser, ) +from everos.infra.memtrace import MemTraceTracker from everos.infra.ome import ( OfflineEngine, OMEConfig, @@ -97,7 +98,12 @@ OmeLock, to_ome_strategy, ) -from everos.infra.persistence import MemoryRoot, purge_scope +from everos.infra.persistence import ( + MemoryRoot, + app_dir_name, + project_dir_name, + purge_scope, +) from everos.infra.persistence.factories import ( build_derived_index, build_indexes, @@ -137,7 +143,7 @@ from everos.memory.strategies import STRATEGY_SPECS from everos.service._warmup import warm_token_counter from everos.service.knowledge import KnowledgeExtractor, KnowledgeService -from everos.service.memory import MemoryService +from everos.service.memory import InputLogWriter, MemoryService from everos.service.ops import BackfillDeps, Capabilities, OpsService from everos.service.purge import PurgeRunGate, PurgeService @@ -191,6 +197,9 @@ class Application: _admin: CascadeAdmin = dataclasses.field(repr=False) _engine: OfflineEngine = dataclasses.field(repr=False) _root_lock: OmeLock = dataclasses.field(repr=False) + _memtrace_tracker: MemTraceTracker | None = dataclasses.field( + default=None, repr=False + ) _stack: contextlib.AsyncExitStack = dataclasses.field( default_factory=contextlib.AsyncExitStack, repr=False ) @@ -226,6 +235,14 @@ async def start(self) -> None: raise async def _start_components(self) -> None: + tracker = self._memtrace_tracker + if tracker is not None: + logger.info( + "memtrace_tracker_status", + enabled=tracker.enabled, + out_dir=str(tracker.out_dir), + smartcomment_available=tracker.smartcomment_available, + ) scores = await init_score_sink(self._settings.observability) self._stack.push_async_callback(_shielded("score_sink", shutdown_score_sink)) logger.info("tracing_score_sink_ready", enabled=scores) @@ -290,6 +307,8 @@ async def aclose(self) -> None: async def _close_components(self) -> None: try: await self._stack.aclose() + if self._memtrace_tracker is not None: + await _shielded("memtrace", self._memtrace_tracker.sync_now)() await _shielded("index", self._admin.close_index)() await _shielded("sqlite", self._admin.dispose)() shutdown_tracing() @@ -361,6 +380,8 @@ def build_application( root = MemoryRoot(resolve_root()) database = SqliteDatabase(root, settings.sqlite) sqlite = SqliteRepos.over(database) + memtrace_tracker = MemTraceTracker() + memtrace_tracker.set_memcell_repo(sqlite.memcell) index = build_derived_index(settings, root) stores = build_stores(root, sqlite) indexes = build_indexes(index) @@ -398,7 +419,15 @@ def build_application( eraser = FencedIndexEraser(index.repositories, fence, sqlite.md_change_state) marks = MARKS.for_root(root.root) memory = _build_memory_service( - settings, providers, deps, tokenizer, OmeEventBus(engine), eraser, marks + settings, + providers, + deps, + tokenizer, + OmeEventBus(engine), + eraser, + marks, + root, + memtrace_tracker, ) engine.set_run_gate(PurgeRunGate(marks)) purge = PurgeService( @@ -453,6 +482,7 @@ def build_application( ), purge=purge, capabilities=capabilities, + _memtrace_tracker=memtrace_tracker, _settings=settings, _root=root, _admin=admin, @@ -614,12 +644,21 @@ def _build_memory_service( bus: EventBus, index_eraser: IndexEraser, purge_marks: PurgeMarks, + root: MemoryRoot, + memtrace_tracker: MemTraceTracker, ) -> MemoryService: stores, indexes = deps.stores, deps.indexes recaller_deps = RecallerDeps(tokenizer=tokenizer) return MemoryService( index_eraser=index_eraser, + memtrace_tracker=memtrace_tracker, purge_marks=purge_marks, + input_log=InputLogWriter( + root=root.root, + settings=settings.memorize.input_log, + app_dir=app_dir_name, + project_dir=project_dir_name, + ), raw_file_builder=partial(build_raw_file, settings_source=load_settings), settings=settings, boundary=BoundaryDetection( @@ -636,6 +675,7 @@ def _build_memory_service( episode_store=stores.episode, memcell_store=stores.memcell, instructions=deps.instructions, + language_llm=providers.llms.language, episode_llm=providers.llms.episode, tz=deps.tz, ), diff --git a/src/everos/service/memory/__init__.py b/src/everos/service/memory/__init__.py index 10d7ce7b4..672f1aeee 100644 --- a/src/everos/service/memory/__init__.py +++ b/src/everos/service/memory/__init__.py @@ -22,6 +22,7 @@ "DeleteResult", "ExtractionSupervisor", "FlushResult", + "InputLogWriter", "MemorizeResult", "MemoryService", "QueueHealth", @@ -33,15 +34,20 @@ import asyncio from collections.abc import Callable, Sequence +from contextlib import nullcontext from typing import TYPE_CHECKING, Any +from everos.core.context import resolve_request_id from everos.core.errors import PathTraversalError, SessionBusyError from everos.core.observability.logging import get_logger from everos.memory import DeviceLine, project_device_batch +from everos.memory.extract.trace import collect_construction_trace +from everos.memory.search.trace import collect_search_trace from ._delete import Deleter from ._delete import DeleteResult as DeleteResult from ._extraction import ExtractionSupervisor as ExtractionSupervisor +from ._input_log import InputLogWriter from ._memorize import Memorizer, flush_payload from ._models import FlushResult as FlushResult from ._models import MemorizeResult as MemorizeResult @@ -89,6 +95,7 @@ class MemoryService: get_manager: Answers :meth:`get`. raw_file_builder: Host file hydration capability for ingestion. index_eraser: Removes deleted memories' index rows (:meth:`delete`). + memtrace_tracker: Optional execution-graph recorder injected by bootstrap. purge_marks: The root's purge marks: the async queue drops rows a purge superseded; each delivery and each extraction is registered while it runs, so a purge can wait for it. ``None`` ignores purges. @@ -108,10 +115,14 @@ def __init__( get_manager: GetManager, raw_file_builder: RawFileBuilder, index_eraser: IndexEraser, + memtrace_tracker: Any = None, purge_marks: PurgeMarks | None = None, + input_log: InputLogWriter | None = None, ) -> None: + self._memtrace_tracker = memtrace_tracker self._search_manager = search_manager self._get_manager = get_manager + self._input_log = input_log self._extractions = ExtractionSupervisor() self._stores = stores self._deleter = Deleter( @@ -155,7 +166,21 @@ async def aclose(self) -> None: async def search(self, req: SearchRequest) -> SearchResponse: """Hybrid retrieval across the configured memory backends.""" - return await self._search_manager.search(req) + tracker = getattr(self, "_memtrace_tracker", None) + if tracker is None or not tracker.enabled: + return await self._search_manager.search(req) + + request_id = resolve_request_id() + with collect_search_trace() as stages: + try: + resp = await self._search_manager.search(req) + except Exception as exc: + await tracker.on_search_error( + req, stages=stages, error=exc, request_id=request_id + ) + raise + await tracker.on_search(req, resp, stages=stages, request_id=request_id) + return resp async def get(self, req: GetRequest) -> GetResponse: """Paginated listing over the requested ``memory_type``.""" @@ -289,6 +314,11 @@ async def queue_health(self) -> QueueHealth | None: # ── write use cases ──────────────────────────────────────────────────── + async def log_add(self, payload: dict[str, Any], *, request_id: str) -> None: + """Record one accepted ``/add`` before it enters the write path.""" + if self._input_log is not None: + await self._input_log.log_add(payload, request_id=request_id) + async def add( self, payload: dict[str, Any], @@ -430,6 +460,36 @@ async def _memorize( defer_extraction: Persist fresh messages to the unprocessed buffer but skip boundary detection and both extraction pipelines. """ - return await self._memorizer.run( - payload, is_final=is_final, defer_extraction=defer_extraction + request_id = resolve_request_id() + tracker = getattr(self, "_memtrace_tracker", None) + context = ( + collect_construction_trace() + if tracker is not None and getattr(tracker, "enabled", False) + else nullcontext([]) ) + with context as events: + try: + result = await self._memorizer.run( + payload, is_final=is_final, defer_extraction=defer_extraction + ) + except BaseException as exc: + if tracker is not None: + await tracker.on_memorize_error( + payload, + is_final=is_final, + defer_extraction=defer_extraction, + error=exc, + request_id=request_id, + **({"construction_events": events} if events else {}), + ) + raise + if tracker is not None: + await tracker.on_memorize( + payload, + is_final=is_final, + defer_extraction=defer_extraction, + result=result, + request_id=request_id, + **({"construction_events": events} if events else {}), + ) + return result diff --git a/src/everos/service/memory/_delete.py b/src/everos/service/memory/_delete.py index 3e6ad47db..55cab4656 100644 --- a/src/everos/service/memory/_delete.py +++ b/src/everos/service/memory/_delete.py @@ -53,7 +53,6 @@ _QUEUED = "queued work for this session; nothing was deleted, retry later" _LOCKED = "session is busy; nothing was deleted, retry later" _MEMORY_ID = re.compile(r"(?P.+)_(?Pep_\d{8}_\d+)") -_DETACH_ATTEMPTS = 3 _PREVIEW_CAP = 5 """A cluster's preview length, as everalgo clustering keeps it (``preview_cap`` default, everalgo-clustering 0.2.1 ``clustering/algorithm.py:41``).""" @@ -320,39 +319,38 @@ async def _delete_episodes(self, scope: Scope, targets: Sequence[str]) -> list[s return [ref.entry_id for ref in first] async def _detach_from_clusters(self, scope: Scope, gone: set[str]) -> None: - """Take ``gone`` out of their clusters (and members no longer in md). + """Take ``gone`` out of their clusters. - Members and their texts are read without the clustering lock; under - it the member list is read again and, if it moved, the round starts - over (at most three times, then the md is read under the lock). + The reverse lookup and the membership rewrite both happen under the + owner's clustering lock. A clustering pass may have checked that the + episode was alive before step 1 removed its markdown and may still be + waiting to commit a cluster; looking up outside the lock would miss + that cluster and leave the deleted episode in it. """ - clusters = self._stores.cluster - cluster_ids: set[str] = set() - for entry_id in sorted(gone): - found = await clusters.find_cluster_for_member(scope, "episode", entry_id) - if found is not None: - cluster_ids.add(found) - await self._prune_clusters(scope, cluster_ids, gone) + await self._prune_clusters(scope, set(), gone) async def _prune_clusters( self, scope: Scope, cluster_ids: set[str], gone: set[str] ) -> None: - """Reconcile membership with markdown, using the existing delete lock.""" + """Reconcile membership with markdown, under the owner's clustering lock. + + ``cluster_ids`` may carry clusters found by a caller's retry scan; + ``gone`` is re-resolved here so a cluster committed after that scan is + included. Every writer of one owner's clusters holds the same lock, so + the member list cannot move between the lookup and the rewrite. + """ clusters = self._stores.cluster - for cluster_id in sorted(cluster_ids): - for attempt in range(_DETACH_ATTEMPTS): + async with user_cluster_lock(scope.app_id, scope.project_id, scope.owner_id): + for entry_id in sorted(gone): + found = await clusters.find_cluster_for_member( + scope, "episode", entry_id + ) + if found is not None: + cluster_ids.add(found) + for cluster_id in sorted(cluster_ids): ids = [m for m, _ in await clusters.members(cluster_id)] alive = await self._alive(scope, ids) - async with user_cluster_lock( - scope.app_id, scope.project_id, scope.owner_id - ): - now = [m for m, _ in await clusters.members(cluster_id)] - if now != ids: - if attempt < _DETACH_ATTEMPTS - 1: - continue - ids, alive = now, await self._alive(scope, now) - await self._restamp(cluster_id, ids, alive, gone) - break + await self._restamp(cluster_id, ids, alive, gone) async def _alive(self, scope: Scope, ids: Sequence[str]) -> dict[str, Episode]: stored = await self._stores.episode.read_many(scope, ids) diff --git a/src/everos/service/memory/_input_log.py b/src/everos/service/memory/_input_log.py new file mode 100644 index 000000000..5b305a076 --- /dev/null +++ b/src/everos/service/memory/_input_log.py @@ -0,0 +1,126 @@ +"""Append-only JSONL log of accepted ``/add`` requests (issue #537). + +The log is deliberately independent of extraction: it records what the +client sent, before boundary detection can rewrite or drop anything. The +first PR ships it disabled; deletion/purge integration and the default-on +switch follow in a second PR. +""" + +from __future__ import annotations + +import asyncio +import datetime as dt +import hashlib +import json +from collections.abc import Callable +from pathlib import Path +from typing import Any + +from everos.config import InputLogSettings +from everos.core.observability.logging import get_logger +from everos.core.utils.datetime import get_now_with_timezone + +logger = get_logger(__name__) + +_LOG_DIR = ".input_log" + + +class InputLogWriter: + """One process-wide writer; appends one line per accepted ``/add``.""" + + def __init__( + self, + *, + root: Path, + settings: InputLogSettings, + app_dir: Callable[[str], str] = lambda value: value, + project_dir: Callable[[str], str] = lambda value: value, + ) -> None: + self._root = root + self._settings = settings + self._app_dir = app_dir + self._project_dir = project_dir + self._lock = asyncio.Lock() + + async def log_add(self, payload: dict[str, Any], *, request_id: str) -> None: + """Record one request; a failure is logged and never fails ``/add``.""" + if not self._settings.enabled: + return + try: + await self._write(payload, request_id=request_id) + except Exception as exc: # pragma: no cover - defensive boundary + logger.error( + "input_log_write_failed", + request_id=request_id, + error=f"{type(exc).__name__}: {exc}", + ) + + async def _write(self, payload: dict[str, Any], *, request_id: str) -> None: + now = get_now_with_timezone() + directory = self._directory(payload) + line = self._truncate( + { + **payload, + "request_id": request_id, + "received_at": now.isoformat(), + } + ) + async with self._lock: + await asyncio.to_thread(self._append_sync, directory, now, line) + + def _directory(self, payload: dict[str, Any]) -> Path: + app_id = str(payload.get("app_id", "default")) + project_id = str(payload.get("project_id", "default")) + return ( + self._root + / self._app_dir(app_id) + / self._project_dir(project_id) + / _LOG_DIR + ) + + def _truncate(self, line: dict[str, Any]) -> dict[str, Any]: + encoded = _encode(line) + if len(encoded) <= self._settings.max_inline_bytes: + return line + for message in line.get("messages", []): + content = message.get("content") + if not isinstance(content, list): + # The request schema also permits a plain string body. + continue + for item in content: + if not isinstance(item, dict): + continue + value = item.get("base64") + if not isinstance(value, str): + continue + extras = dict(item.get("extras") or {}) + extras["base64_sha256"] = hashlib.sha256( + value.encode("utf-8") + ).hexdigest() + extras["base64_bytes"] = len(value) + item["base64"] = None + item["extras"] = extras + return line + + def _append_sync( + self, directory: Path, now: dt.datetime, line: dict[str, Any] + ) -> None: + directory.mkdir(parents=True, exist_ok=True) + self._prune(directory, now.date()) + path = directory / f"{now.date().isoformat()}.jsonl" + with path.open("a", encoding="utf-8") as handle: + handle.write(_encode(line) + "\n") + + def _prune(self, directory: Path, today: dt.date) -> None: + cutoff = today - dt.timedelta(days=self._settings.retention_days) + for path in directory.glob("*.jsonl"): + try: + day = dt.date.fromisoformat(path.stem) + except ValueError: + continue + if day < cutoff: + path.unlink(missing_ok=True) + + +def _encode(line: dict[str, Any]) -> str: + return json.dumps(line, ensure_ascii=False, separators=(",", ":")) diff --git a/src/everos/service/memory/_memorize.py b/src/everos/service/memory/_memorize.py index 6f23e570d..82c5ccd95 100644 --- a/src/everos/service/memory/_memorize.py +++ b/src/everos/service/memory/_memorize.py @@ -23,13 +23,17 @@ import asyncio from typing import TYPE_CHECKING, Any, Literal +from everalgo.llm import LLMOutputError + from everos.core.context import resolve_request_id +from everos.core.errors import LLMServiceError from everos.core.locks import LOCKS, session_key from everos.core.observability.logging import get_logger from everos.core.observability.tracing import memory_span from everos.core.purge_marks import origin_or_now from everos.memory.extract.ingest import process as ingest_process from everos.memory.extract.pipeline import PipelineOutcome, PreparedCell +from everos.memory.extract.trace import record_construction from everos.service.memory._extraction import ExtractionSupervisor from everos.service.memory._models import MemorizeResult @@ -232,12 +236,50 @@ async def _cut( ) if defer_extraction and not is_final: buffered = await self._boundary.buffer(ingested, mode=mode) + record_construction( + "boundary", + app_id=ingested.app_id, + project_id=ingested.project_id, + session_id=ingested.session_id, + status=buffered.status, + reason="deferred", + detection_performed=False, + cells=[], + ) return MemorizeResult( message_count=len(payload.get("messages", [])), status=_merge_status(buffered.status, "skipped"), ) boundary = await self._boundary.detect(ingested, mode=mode, is_final=is_final) + record_construction( + "boundary", + app_id=ingested.app_id, + project_id=ingested.project_id, + session_id=ingested.session_id, + status=boundary.status, + detection_performed=(boundary.detection or {}).get( + "detection_performed", False + ), + detection=boundary.detection, + snapshot_factory=lambda: { + "cells": [ + { + "id": memcell_id, + "message_ids": message_ids, + "sender_ids": sender_ids, + "content": cell.model_dump(mode="json"), + } + for memcell_id, message_ids, sender_ids, cell in zip( + boundary.memcell_ids, + boundary.per_cell_message_ids, + boundary.per_cell_all_senders, + boundary.cells, + strict=True, + ) + ] + }, + ) if not boundary.cells: # Nothing went past the boundary stage — no pipelines to dispatch. @@ -264,7 +306,9 @@ async def _extract( cell has been tried, so the caller still sees the extraction failed. Raises: - Exception: The first pipeline failure, after all cells ran. + LLMServiceError: The first pipeline failure was an + ``LLMOutputError`` (no attempt got a usable reply). + Exception: Any other first pipeline failure, after all cells ran. """ pipelines: dict[str, Pipeline] = {"user_memory": self._user_pipeline} if mode == "agent": @@ -284,6 +328,12 @@ async def _extract( outcomes[track].append(result) await self._bus.publish(result.events) if first_error is not None: + if isinstance(first_error, LLMOutputError): + # Every attempt got a reply the operator rejected: the model + # is at fault and a later retry may succeed, so a 503. + raise LLMServiceError( + f"no usable LLM reply: {first_error}" + ) from first_error raise first_error user = PipelineOutcome.from_cells("user_memory", outcomes["user_memory"]) diff --git a/tests/acceptance/purge/seed.py b/tests/acceptance/purge/seed.py index ceecaf5fa..5f1abe45a 100644 --- a/tests/acceptance/purge/seed.py +++ b/tests/acceptance/purge/seed.py @@ -54,8 +54,15 @@ def _ok(resp: httpx.Response, *codes: int) -> dict[str, Any]: def agent_chat(user: str, token: str) -> list[dict[str, Any]]: """A user-agent exchange with three tool calls (an agent case needs at - least three tool rounds).""" - msgs = chat(user, token, assistant=AGENT, n=2) + least three tool rounds). + + The user is named ``Alice``, the person the fake episode narrative is + about: a profile builds only from episodes that name its owner. + """ + msgs = [ + m | {"sender_name": "Alice"} if m["sender_id"] == user else m + for m in chat(user, token, assistant=AGENT, n=2) + ] at = msgs[-1]["timestamp"] for i in range(3): call = { diff --git a/tests/acceptance/purge/test_inbox.py b/tests/acceptance/purge/test_inbox.py index c69043f51..bc494b4f3 100644 --- a/tests/acceptance/purge/test_inbox.py +++ b/tests/acceptance/purge/test_inbox.py @@ -9,7 +9,9 @@ from tests.acceptance.memory_delete.conftest import chat from tests.acceptance.memory_delete.proxy import Rule +from tests.fakes.llm import USER_TRACK_OPERATORS, boundary_reply +from .fake_upstream import Override from .journey import finish, purge from .observe import md_counts, release, rows, system_db from .seed import scope_token @@ -41,7 +43,7 @@ def _task(srv: Any, request_id: str) -> dict[str, Any]: def test_t8_1_queued_adds_split_by_when_they_came_in( - make_world: Any, purge_proxy: Any + make_world: Any, purge_proxy: Any, fake: Any ) -> None: """A8: the scope's adds queued before the purge fail as purge_in_progress; one in delivery is waited for (its data then purged with the rest); one @@ -50,6 +52,14 @@ def test_t8_1_queued_adds_split_by_when_they_came_in( world = make_world("T8.1", EVEROS_TEST_FAILPOINTS="purge.before_step8=pause") srv = world.srv s_token, o_token = scope_token("a1", "p1"), scope_token("a2", "p1") + # The other scope's adds cut on arrival, so their delivery shows as episodes. + fake.override( + Override( + pattern=o_token, + reply=boundary_reply([1]), + name=USER_TRACK_OPERATORS["boundary"], + ) + ) hold = purge_proxy.add(Rule(target="llm", pattern=f"{s_token}hold", mode="hold")) held_id = _async_add(srv, "queued", "a1", "p1", f"{s_token}hold") assert purge_proxy.wait_held("llm", timeout=60) diff --git a/tests/acceptance/purge/test_inflight.py b/tests/acceptance/purge/test_inflight.py index 9c6d95fe2..2eb131d1e 100644 --- a/tests/acceptance/purge/test_inflight.py +++ b/tests/acceptance/purge/test_inflight.py @@ -14,7 +14,9 @@ from tests.acceptance.memory_delete.conftest import chat from tests.acceptance.memory_delete.proxy import Rule from tests.acceptance.memory_delete.seed import write_episode +from tests.fakes.llm import USER_TRACK_OPERATORS, boundary_reply +from .fake_upstream import Override from .journey import finish, purge from .observe import ( INDEX_TABLES, @@ -28,6 +30,8 @@ ) from .seed import AGENT, scope_token +BOUNDARY_REPLY = USER_TRACK_OPERATORS["boundary"] + pytestmark = pytest.mark.acceptance S = {"scope": "project", "app_id": "a1", "project_id": "p1"} @@ -104,7 +108,7 @@ def test_t22_1_sync_add_in_flight_is_cleared(make_world: Any, purge_proxy: Any) srv, root = world.srv, world.srv.root word = f"{scope_token('a1', 'p1')}late" hold = purge_proxy.add( - Rule(target="llm", pattern=f'(?=.*"_BatchReply")(?=.*{word})', mode="hold") + Rule(target="llm", pattern=f'(?=.*"{BOUNDARY_REPLY}")(?=.*{word})', mode="hold") ) responses: dict[str, httpx.Response] = {} @@ -148,13 +152,18 @@ def add() -> None: def test_t22_2_extraction_handed_off_after_a_disconnect_is_waited_for( - make_world: Any, purge_proxy: Any + make_world: Any, purge_proxy: Any, fake: Any ) -> None: """A22 variant (T2): the request's client goes away after it handed its extraction off; the extraction carries on and the purge waits for it.""" world = make_world("T22.2") srv, root = world.srv, world.srv.root word = f"{scope_token('a1', 'p1')}gone" + # The add itself cuts (before the second exchange), so an episode + # extraction runs without a flush. + fake.override( + Override(pattern=word, reply=boundary_reply([2]), name=BOUNDARY_REPLY) + ) hold = purge_proxy.add( Rule(target="llm", pattern=f'(?=.*"_EpisodeReply")(?=.*{word})', mode="hold") ) diff --git a/tests/acceptance/purge/test_ome.py b/tests/acceptance/purge/test_ome.py index 5085b1eb5..cc3ab2723 100644 --- a/tests/acceptance/purge/test_ome.py +++ b/tests/acceptance/purge/test_ome.py @@ -5,6 +5,7 @@ import json import re import time +from collections.abc import Callable from datetime import datetime from pathlib import Path from typing import Any @@ -73,42 +74,84 @@ def _hold_facts(proxy: Any, token: str) -> Rule: ) +_BLOCKER = ("a2", "p1") + + +def _hold_case(proxy: Any, token: str) -> Rule: + """Hold the agent-case extraction of the scope ``token`` names.""" + return proxy.add( + Rule( + target="llm", + pattern=f'(?=.*"_CaseCompressReply")(?=.*{token})', + mode="hold", + ) + ) + + +def _running(srv: Any) -> list[tuple[str, tuple[str, str] | None]]: + return [ + (r["strategy_name"], _scope_of(r["event_payload"])) + for r in _runs(srv.root) + if r["status"] == "running" + ] + + +def _until_calm(srv: Any, ok: Callable[[], bool], what: str) -> None: + """Wait until ``ok()`` holds on two polls a second apart.""" + calm, deadline = 0, time.monotonic() + 60 + while time.monotonic() < deadline: + calm = calm + 1 if ok() else 0 + if calm >= 2: + return + time.sleep(1) + raise AssertionError(what, _running(srv)) + + def _backlog(world: Any, proxy: Any, app: str, project: str) -> None: - """A backlog of (app, project) the purge must drop, behind a held run of - (a2, p1) in the only OME slot (the purge does not wait for another - range, so it ends with the backlog still queued). + """A backlog of (app, project) the purge must drop, queued behind two held + runs of (a2, p1) that fill both OME slots (the world runs two); the purge + does not wait for another range, so it ends with the backlog still queued. The backlog is the part no source check covers: (app, project)'s agent case is extracted first (its memcell still there), and the event it emits -- which carries the case's content to the skill clustering -- - lands in the queue behind the held (a2, p1) run. First-stage events + lands in the queue behind the held (a2, p1) runs. First-stage events alone would prove nothing: their writes are skipped once the memcell - is gone, drop rule or not.""" + is gone, drop rule or not. + + No other run of (app, project) may have started when the purge comes: a + started run is in flight, and the purge waits for it. A strategy that + takes a partition lock (the profile, the clusterings) hands its slot back + while it takes the lock, so with every slot held it would stay started + and never finish. Hence two slots: the case is held in one while the rest + of the talk runs to its end in the other, and only then do both slots go + to (a2, p1).""" srv = world.srv token = scope_token(app, project) began = get_utc_now() cases = md_counts(srv.root, app, project)["md.agent_case"] - case = proxy.add( - Rule( - target="llm", - pattern=f'(?=.*"_CaseCompressReply")(?=.*{token})', - mode="hold", - ) - ) + case = _hold_case(proxy, token) talk(srv, "u1", "backlog", token, {"app_id": app, "project_id": project}) - assert proxy.wait_held("llm", timeout=60) # the case extraction, in the slot - blocker = scope_token("a2", "p1") + assert proxy.wait_held("llm", timeout=60) # the case extraction, in one slot + _until_calm( + srv, + lambda: _running(srv) == [("extract_agent_case", (app, project))], + "the rest of the talk never finished beside the held case", + ) + blocker = scope_token(*_BLOCKER) _hold_facts(proxy, blocker) + _hold_case(proxy, blocker) talk(srv, "u1", "blocker", blocker, {"app_id": "a2", "project_id": "p1"}) case.release.set() # the case lands; its follow-up queues behind a2's runs - deadline = time.monotonic() + 60 - while time.monotonic() < deadline: - running = [r for r in _runs(srv.root) if r["status"] == "running"] - if [_scope_of(r["event_payload"]) for r in running] == [("a2", "p1")]: - break - time.sleep(0.2) - assert [_scope_of(r["event_payload"]) for r in running] == [("a2", "p1")] - assert md_counts(srv.root, app, project)["md.agent_case"] > cases # it landed + _until_calm( + srv, + lambda: ( + proxy.held("llm") == 2 + and all(scope == _BLOCKER for _, scope in _running(srv)) + and md_counts(srv.root, app, project)["md.agent_case"] > cases + ), + "both slots never went to (a2, p1) with the case landed", + ) clustering = [ r for r in _after(_runs(srv.root), began) @@ -137,7 +180,7 @@ def _drain_and_check(world: Any, proxy: Any, job: dict[str, Any]) -> None: def test_t9_1_backlog_never_writes_back(make_world: Any, purge_proxy: Any) -> None: - world = make_world("T9.1", EVEROS_OME__MAX_CONCURRENT_RUNS="1") + world = make_world("T9.1", EVEROS_OME__MAX_CONCURRENT_RUNS="2") srv = world.srv _backlog(world, purge_proxy, "a1", "p1") job_id, _ = purge(srv, **S) @@ -147,7 +190,7 @@ def test_t9_1_backlog_never_writes_back(make_world: Any, purge_proxy: Any) -> No def test_t24_1_app_tombstone_covers_its_projects( make_world: Any, purge_proxy: Any ) -> None: - world = make_world("T24.1", EVEROS_OME__MAX_CONCURRENT_RUNS="1") + world = make_world("T24.1", EVEROS_OME__MAX_CONCURRENT_RUNS="2") srv = world.srv _backlog(world, purge_proxy, "a1", "p1") job_id, _ = purge(srv, scope="app", app_id="a1") @@ -155,7 +198,7 @@ def test_t24_1_app_tombstone_covers_its_projects( def test_t24_2_latest_purge_of_a_scope_wins(make_world: Any, purge_proxy: Any) -> None: - world = make_world("T24.2", EVEROS_OME__MAX_CONCURRENT_RUNS="1") + world = make_world("T24.2", EVEROS_OME__MAX_CONCURRENT_RUNS="2") srv = world.srv first, _ = purge(srv, **S) assert finish(srv, first)["status"] == "succeeded" diff --git a/tests/acceptance/purge/test_perf.py b/tests/acceptance/purge/test_perf.py index b45acadb7..397610c00 100644 --- a/tests/acceptance/purge/test_perf.py +++ b/tests/acceptance/purge/test_perf.py @@ -20,11 +20,14 @@ from tests.acceptance.memory_delete.conftest import chat from tests.acceptance.memory_delete.proxy import Rule from tests.acceptance.memory_delete.seed import write_episode +from tests.fakes.llm import USER_TRACK_OPERATORS from .journey import Evidence, evidence_base, finish, purge from .observe import system_db, wait_idle from .seed import AGENT, scope_token +BOUNDARY_REPLY = USER_TRACK_OPERATORS["boundary"] + pytestmark = pytest.mark.acceptance S = {"scope": "project", "app_id": "a1", "project_id": "p1"} @@ -128,7 +131,7 @@ def test_t35_1a_callers_are_not_slowed_while_the_purge_waits( base = _measure(srv) word = f"{scope_token('a1', 'p1')}slow" hold = purge_proxy.add( - Rule(target="llm", pattern=f'(?=.*"_BatchReply")(?=.*{word})', mode="hold") + Rule(target="llm", pattern=f'(?=.*"{BOUNDARY_REPLY}")(?=.*{word})', mode="hold") ) sent: dict[str, httpx.Response] = {} adder = threading.Thread( diff --git a/tests/fakes/application.py b/tests/fakes/application.py index 90cef1774..bd16ea385 100644 --- a/tests/fakes/application.py +++ b/tests/fakes/application.py @@ -123,6 +123,9 @@ def __init__(self, lifecycle: list[str] | None = None) -> None: self.delete = AsyncMock() self.delete_by_ids = AsyncMock(return_value=0) + async def log_add(self, payload: dict[str, Any], *, request_id: str) -> None: + return None + async def finish_interrupted_deletions(self, *, skip: Any = None) -> int: self.lifecycle.append("memory.finish_interrupted_deletions") return 0 diff --git a/tests/fakes/llm.py b/tests/fakes/llm.py index fa8ad6a1c..46056a20b 100644 --- a/tests/fakes/llm.py +++ b/tests/fakes/llm.py @@ -49,6 +49,7 @@ USER_TRACK_OPERATORS: Mapping[str, str] = { "boundary": "Reply", # everalgo-boundary names its batch reply model `Reply` + "language": "_LanguageReply", "episode": "_EpisodeReply", "episode_summary": "_SummaryReply", "atomic_facts": "_AtomicFactsReply", diff --git a/tests/fakes/llm_scripts/user_track/language.json b/tests/fakes/llm_scripts/user_track/language.json new file mode 100644 index 000000000..84f55d462 --- /dev/null +++ b/tests/fakes/llm_scripts/user_track/language.json @@ -0,0 +1 @@ +{"language": "English"} diff --git a/tests/fakes/llm_scripts/user_track/language_chinese.json b/tests/fakes/llm_scripts/user_track/language_chinese.json new file mode 100644 index 000000000..f646616c0 --- /dev/null +++ b/tests/fakes/llm_scripts/user_track/language_chinese.json @@ -0,0 +1 @@ +{"language": "Chinese"} diff --git a/tests/fakes/llm_scripts/user_track/language_unusable.json b/tests/fakes/llm_scripts/user_track/language_unusable.json new file mode 100644 index 000000000..7f8c66c66 --- /dev/null +++ b/tests/fakes/llm_scripts/user_track/language_unusable.json @@ -0,0 +1 @@ +this is not JSON diff --git a/tests/integration/test_memorize_agent_mode.py b/tests/integration/test_memorize_agent_mode.py index da4f6f783..78589c313 100644 --- a/tests/integration/test_memorize_agent_mode.py +++ b/tests/integration/test_memorize_agent_mode.py @@ -30,7 +30,7 @@ from everos.infra.ome.records import RunStatus from everos.infra.persistence import MemoryRoot -from everos.memory.extract.ingest.id_gen import gen_message_id +from everos.memory.extract.ingest import message_ids from everos.service import ( MemorizeResult, build_application, @@ -251,7 +251,7 @@ async def test_agent_mode_cut_files_each_tool_row_with_its_segment( ) assert result.status == "extracted" - ids = [gen_message_id(session, m["timestamp"], i) for i, m in enumerate(messages)] + ids = message_ids(session, messages) cells = [json.loads(row["message_ids_json"]) for row in _memcell_rows(tmp_path)] assert cells == [ids[:4], ids[4:]] diff --git a/tests/integration/test_memorize_window_segmentation.py b/tests/integration/test_memorize_window_segmentation.py index f680135b4..f4d833db9 100644 --- a/tests/integration/test_memorize_window_segmentation.py +++ b/tests/integration/test_memorize_window_segmentation.py @@ -45,6 +45,7 @@ from sqlalchemy import text from everos.infra.persistence import MemoryRoot +from everos.memory.extract.ingest import message_ids from everos.service import ( MemorizeResult, MemoryService, @@ -301,8 +302,7 @@ async def test_second_add_consumes_prior_buffer_and_replaces_tail( assert new_tail_id not in all_cell_msgs # Conservation: 6 distinct message ids covered across cells + buffer. - # (We avoid hard-coding id format here — gen_message_id encodes the - # per-batch index, not a global one.) + # (We avoid hard-coding the id format here; see ingest.message_ids.) covered = all_cell_msgs | {new_tail_id} assert len(covered) == 6, ( f"expected 6 distinct ids covered, got {len(covered)}: {covered}" @@ -386,3 +386,77 @@ async def test_three_sequential_adds_conservation_no_loss( ) # Disjoint assert not (in_cells & in_buffer) + + +# --------------------------------------------------------------------------- +# Resends (#274): a client that retries after a timeout resends messages the +# first call may already have cut; they must not be cut a second time. +# --------------------------------------------------------------------------- + + +async def test_resent_batch_is_not_cut_twice( + memorize_env_scripted: Callable[..., AsyncMock], storage: Storage +) -> None: + """[m0,m1,m2] cut after 2, then the identical request again.""" + await memorize_env_scripted(fake_llm=memorize_llm([[2], []])) + session = "s_resend" + batch = {"session_id": session, "messages": [_msg(i) for i in range(3)]} + + await memorize(batch) + await memorize(batch) + + cells = await _memcell_rows(storage, session) + assert [len(ids) for _, ids in cells] == [2], cells + assert [mid for mid, _ in await _buffer_rows(storage, session)] == [ + message_ids(session, [_msg(2)])[0] + ] + + +async def test_regrouped_resend_keeps_ids_and_drops_what_was_cut( + memorize_env_scripted: Callable[..., AsyncMock], storage: Storage +) -> None: + """The retry carries m1 at another position and one new message, m3.""" + await memorize_env_scripted(fake_llm=memorize_llm([[2], []])) + session = "s_regroup" + + await memorize({"session_id": session, "messages": [_msg(i) for i in range(3)]}) + await memorize({"session_id": session, "messages": [_msg(i) for i in (1, 2, 3)]}) + + cells = await _memcell_rows(storage, session) + assert len(cells) == 1, cells + buffered = [mid for mid, _ in await _buffer_rows(storage, session)] + assert buffered == [message_ids(session, [_msg(i)])[0] for i in (2, 3)] + + +async def test_one_millisecond_resent_in_parts_is_not_cut_twice( + memorize_env_scripted: Callable[..., AsyncMock], storage: Storage +) -> None: + """[A, B, C] share one millisecond and are cut after B; the retry carries B + alone. B keeps its id though its place in the request changed.""" + await memorize_env_scripted(fake_llm=memorize_llm([[2], []])) + session = "s_same_ms_parts" + batch = [_msg(0) | {"content": f"part-{i}"} for i in range(3)] + + await memorize({"session_id": session, "messages": batch}) + await memorize({"session_id": session, "messages": [batch[1]]}) + + cells = await _memcell_rows(storage, session) + assert [len(ids) for _, ids in cells] == [2], cells + assert [mid for mid, _ in await _buffer_rows(storage, session)] == message_ids( + session, [batch[2]] + ) + + +async def test_two_messages_with_one_millisecond_in_two_requests_both_stay( + memorize_env_scripted: Callable[..., AsyncMock], storage: Storage +) -> None: + """Different messages, same timestamp, each first in its request.""" + await memorize_env_scripted(fake_llm=memorize_llm([[], []])) + session = "s_same_ms" + first = _msg(0) + second = _msg(0) | {"content": "a different message"} + + await memorize({"session_id": session, "messages": [first]}) + await memorize({"session_id": session, "messages": [second]}) + + assert len(await _buffer_rows(storage, session)) == 2 diff --git a/tests/integration/test_reflection_integration.py b/tests/integration/test_reflection_integration.py index 9027a7756..1ec47397b 100644 --- a/tests/integration/test_reflection_integration.py +++ b/tests/integration/test_reflection_integration.py @@ -35,6 +35,7 @@ from everos.infra.persistence.markdown import ( MarkdownAtomicFactStore, MarkdownEpisodeStore, + MarkdownProfileStore, ) from everos.infra.persistence.sqlite import ( SqliteClusterStore, @@ -126,6 +127,7 @@ def __init__( episode_index=EpisodeIndexAdapter(storage.repos.episode), memcell_store=self.memcells, report_store=reports, + profile_store=MarkdownProfileStore(root), reflector=EpisodeReflector(llm=reflector_llm), ) self.finisher = ReflectionFinisher( diff --git a/tests/unit/test_component/test_llm/test_llm_task_resolution.py b/tests/unit/test_component/test_llm/test_llm_task_resolution.py index f0587a869..b9f6fae32 100644 --- a/tests/unit/test_component/test_llm/test_llm_task_resolution.py +++ b/tests/unit/test_component/test_llm/test_llm_task_resolution.py @@ -2,7 +2,7 @@ One rule: every field is taken from the first section that sets it -- the task's own section, then (decider only) the deprecated ``[decider]`` fields, then the -task's own defaults (decider only), then ``[llm]``. ``extra`` is one value, +task's own defaults (language and decider only), then ``[llm]``. ``extra`` is one value, replaced whole. The cases below pin that rule, the source each field reports, which tasks share a provider, and that ``temperature`` / ``max_tokens`` are defaults a call can still override -- read off the wire, because a provider that @@ -139,6 +139,33 @@ def _effective(settings: Settings, task: LLMTask) -> dict[str, Any]: "model": "base-model", }, ), + ( + "language keeps its own five defaults", + { + "timeout_seconds": 300.0, + "max_tokens": 8000, + "sdk_max_retries": 5, + "invalid_reply_retries": 4, + "temperature": 0.3, + "extra": {"extra_body": {"a": 1}}, + }, + LLMTask.LANGUAGE, + { + "temperature": 0.0, + "max_tokens": 64, + "timeout_seconds": 3.0, + "sdk_max_retries": 0, + "invalid_reply_retries": 0, + "extra": {"extra_body": {"a": 1}}, + "model": "base-model", + }, + ), + ( + "language section beats its defaults", + {"language": LLMTaskSettings(model="small", timeout_seconds=10.0)}, + LLMTask.LANGUAGE, + {"model": "small", "timeout_seconds": 10.0, "max_tokens": 64}, + ), ( "decider section beats its defaults", {"decider": LLMTaskSettings(timeout_seconds=20.0, max_tokens=64)}, @@ -294,11 +321,13 @@ def _providers(settings: Settings) -> dict[LLMTask, Any]: return build_llm_task_providers(configs) -def test_by_default_ten_tasks_share_one_provider_and_the_decider_has_its_own() -> None: +def test_by_default_the_tasks_share_one_provider_but_language_and_decider() -> None: + """The language task's own defaults make it a configuration of its own.""" providers = _providers(_settings()) - shared = {id(p) for task, p in providers.items() if task is not LLMTask.DECIDER} + own = {LLMTask.LANGUAGE, LLMTask.DECIDER} + shared = {id(p) for task, p in providers.items() if task not in own} assert len(shared) == 1 - assert id(providers[LLMTask.DECIDER]) not in shared + assert len({id(providers[task]) for task in own} | shared) == 3 def test_tasks_configured_alike_share_and_the_rest_split() -> None: @@ -306,7 +335,7 @@ def test_tasks_configured_alike_share_and_the_rest_split() -> None: providers = _providers(_settings({"boundary": nano, "summary": nano})) assert providers[LLMTask.BOUNDARY] is providers[LLMTask.SUMMARY] assert providers[LLMTask.BOUNDARY] is not providers[LLMTask.EPISODE] - assert len({id(p) for p in providers.values()}) == 3 + assert len({id(p) for p in providers.values()}) == 4 def test_the_decider_is_never_shared_even_when_configured_alike() -> None: @@ -382,13 +411,22 @@ async def test_unset_defaults_leave_both_out_of_the_request( ) -> None: """Only ``[llm]`` configured: each extraction request is what it was before.""" providers = _providers(_settings()) - for task in set(LLMTask) - {LLMTask.DECIDER}: + for task in set(LLMTask) - {LLMTask.LANGUAGE, LLMTask.DECIDER}: await _send(providers[task]) assert {tuple(sorted(body)) for body in wire} == { ("messages", "model", "response_format") } +async def test_the_language_task_sends_its_own_temperature_and_cap( + wire: list[dict[str, Any]], +) -> None: + """Only ``[llm]`` configured: the one-word language reply is still bounded.""" + await _send(_providers(_settings())[LLMTask.LANGUAGE]) + (body,) = wire + assert (body["temperature"], body["max_tokens"]) == (0.0, 64) + + async def test_the_decider_sends_its_reply_cap_and_extra( wire: list[dict[str, Any]], monkeypatch: pytest.MonkeyPatch ) -> None: diff --git a/tests/unit/test_component/test_llm/test_nvidia_endpoint.py b/tests/unit/test_component/test_llm/test_nvidia_endpoint.py new file mode 100644 index 000000000..1b3860ee2 --- /dev/null +++ b/tests/unit/test_component/test_llm/test_nvidia_endpoint.py @@ -0,0 +1,62 @@ +"""NVIDIA NIM -- an ``[llm]`` section pointed at NIM reaches the SDK client. + +NIM serves the OpenAI Chat Completions protocol, so it needs no provider of its +own: ``resolve_llm_config`` + ``build_llm_provider`` turn the section into an +``OpenAIProvider`` whose ``openai.AsyncOpenAI`` client carries NIM's base URL, +key, and model. No request is sent. +""" + +from __future__ import annotations + +from pydantic import SecretStr + +from everos.component.llm import ( + OpenAIProvider, + build_llm_provider, + observer_for, + resolve_llm_config, +) +from everos.config import Settings +from everos.config.settings import LLMSettings + +NVIDIA_BASE_URL = "https://integrate.api.nvidia.com/v1" +NVIDIA_MODEL = "nvidia/nemotron-3.5-super-vl-120b-a12b" + + +def _settings(base_url: str = NVIDIA_BASE_URL) -> Settings: + return Settings( + llm=LLMSettings( + model=NVIDIA_MODEL, + api_key=SecretStr("nvidia-test-key"), + base_url=base_url, + ) + ) + + +def test_nvidia_section_resolves_to_its_endpoint() -> None: + config = resolve_llm_config(_settings()) + + assert config.model == NVIDIA_MODEL + assert config.api_key == "nvidia-test-key" + assert config.base_url == NVIDIA_BASE_URL + + +def test_nvidia_endpoint_reaches_the_sdk_client() -> None: + settings = _settings() + + provider = build_llm_provider( + resolve_llm_config(settings), observer=observer_for(settings) + ) + + assert isinstance(provider, OpenAIProvider) + assert str(provider._client.base_url) == f"{NVIDIA_BASE_URL}/" + assert provider._client.api_key == "nvidia-test-key" + assert provider._model == NVIDIA_MODEL + + +def test_self_hosted_nim_base_url_is_kept() -> None: + provider = build_llm_provider( + resolve_llm_config(_settings(base_url="http://localhost:8000/v1")) + ) + + assert str(provider._client.base_url) == "http://localhost:8000/v1/" diff --git a/tests/unit/test_component/test_llm/test_openai_provider.py b/tests/unit/test_component/test_llm/test_openai_provider.py index be9f4c8dc..22dfdadbc 100644 --- a/tests/unit/test_component/test_llm/test_openai_provider.py +++ b/tests/unit/test_component/test_llm/test_openai_provider.py @@ -167,6 +167,54 @@ def test_negative_invalid_reply_retries_rejected() -> None: OpenAIProvider(model="m", api_key="k", invalid_reply_retries=-1) +# --------------------------------------------------------------------------- +# Trailing commas (#564) +# --------------------------------------------------------------------------- + + +class _Items(StrictOutputModel): + text: str + items: list[str] + + +@pytest.mark.parametrize( + ("reply", "repaired"), + [ + ('{"text": "ok", "items": [],}', '{"text": "ok", "items": []}'), + ( + '{\n"text": "ok",\n"items": ["a", "b",\n],\n}', + '{\n"text": "ok",\n"items": ["a", "b"\n]\n}', + ), + # A comma inside a string is the reply's content, not a trailing comma. + ('{"text": "a, } b,]", "items": [],}', '{"text": "a, } b,]", "items": []}'), + ( + '{"text": "say \\"x,\\"}", "items": ["y",]}', + '{"text": "say \\"x,\\"}", "items": ["y"]}', + ), + ], + ids=["object", "nested", "comma-in-string", "escaped-quote"], +) +async def test_trailing_commas_are_repaired_without_a_resend( + reply: str, repaired: str +) -> None: + upstream = _Upstream(_completion(reply)) + text = await _provider(upstream, invalid_reply_retries=0).achat( + _prompt(), response_format=_Items + ) + assert text == repaired + assert len(upstream.bodies) == 1 + + +async def test_repair_that_still_fails_validation_is_resent() -> None: + """Removing trailing commas does not excuse a missing field.""" + upstream = _Upstream(_completion('{"items": ["a",],}'), _completion()) + text = await _provider(upstream, invalid_reply_retries=1).achat( + _prompt(), response_format=_Reply + ) + assert text == _VALID + assert len(upstream.bodies) == 2 + + # --------------------------------------------------------------------------- # Observer # --------------------------------------------------------------------------- diff --git a/tests/unit/test_config/test_llm_task_settings.py b/tests/unit/test_config/test_llm_task_settings.py index c3c6aa0d2..c63507597 100644 --- a/tests/unit/test_config/test_llm_task_settings.py +++ b/tests/unit/test_config/test_llm_task_settings.py @@ -148,6 +148,7 @@ def test_the_task_names_are_stable() -> None: """Section names in users' configs: renaming one breaks every config using it.""" assert [task.value for task in LLMTask] == [ "boundary", + "language", "episode", "summary", "atomic_fact", diff --git a/tests/unit/test_entrypoints/test_tui/test_demo_app.py b/tests/unit/test_entrypoints/test_tui/test_demo_app.py index e6cec2797..3d3767829 100644 --- a/tests/unit/test_entrypoints/test_tui/test_demo_app.py +++ b/tests/unit/test_entrypoints/test_tui/test_demo_app.py @@ -2,6 +2,8 @@ from __future__ import annotations +from typing import TYPE_CHECKING + import pytest from everos.entrypoints.tui.demo.app import EverOSDemoApp @@ -30,6 +32,11 @@ ) from everos.entrypoints.tui.demo.widgets.sphere import SPHERE_STATES +if TYPE_CHECKING: + from collections.abc import Callable + + from textual.pilot import Pilot + _YELLOW = "#F9B91C" @@ -399,19 +406,17 @@ async def test_conversation_panel_scrolls_when_log_overflows() -> None: for i in range(8): app._record_line("you", f"memory {i}") app._record_line("everos", f"a long recalled answer for round {i}") - # Each _record_line defers its scroll_end past the layout refresh that - # Static.update() triggers; one pause is not always enough to drain 16 - # of them, and a late one landing after scroll_home re-pins the bottom. - await pilot.pause() - await pilot.pause() - panel = app.query_one("#conversation", VerticalScroll) - assert panel.max_scroll_y > 0 # content overflows and is scrollable - assert panel.scroll_y == panel.max_scroll_y # newest line auto-pinned + + def pinned_to_newest() -> bool: + return panel.max_scroll_y > 0 and panel.scroll_y == panel.max_scroll_y + + await _pause_until(pilot, pinned_to_newest) panel.scroll_home(animate=False) - await pilot.pause() - await pilot.pause() - assert panel.scroll_y == 0 # user can scroll back to the start + await _pause_until(pilot, lambda: panel.scroll_y == 0) + # A new turn brings a reader who scrolled up back to the newest line. + app._record_line("you", "one more memory") + await _pause_until(pilot, pinned_to_newest) async def test_slash_clear_wipes_the_conversation_log() -> None: @@ -591,3 +596,18 @@ def _css_block(css: str, selector: str) -> str: start = css.index(f"{selector} {{") end = css.index("}", start) return css[start:end] + + +async def _pause_until( + pilot: Pilot[None], condition: Callable[[], bool], *, max_pauses: int = 50 +) -> None: + """Pause the app until ``condition`` holds, failing after ``max_pauses``. + + Layout and deferred callbacks settle after a scheduling-dependent number of + message-pump turns, so a fixed pause count is flaky on slow runners. + """ + for _ in range(max_pauses): + if condition(): + return + await pilot.pause() + assert condition(), f"condition still false after {max_pauses} pauses" diff --git a/tests/unit/test_infra/test_markdown/test_readers/test_agent_skill_reader.py b/tests/unit/test_infra/test_markdown/test_readers/test_agent_skill_reader.py index c29c0063b..766d381bc 100644 --- a/tests/unit/test_infra/test_markdown/test_readers/test_agent_skill_reader.py +++ b/tests/unit/test_infra/test_markdown/test_readers/test_agent_skill_reader.py @@ -2,8 +2,10 @@ from __future__ import annotations +from collections.abc import Callable from pathlib import Path +import anyio import pytest from pydantic import ValidationError @@ -368,3 +370,81 @@ async def test_read_main_rederivation_from_raw_name_is_idempotent_safe( fm_out, body = out assert fm_out.name == space_name assert body == "The fix body." + + +# ── A file removed between the existence check and the read ────────────── + + +@pytest.fixture +def vanish_once_seen(monkeypatch: pytest.MonkeyPatch) -> Callable[[Path], None]: + """Make a path disappear right after a reader sees that it is a file. + + An owner deletion moves the agent's whole directory away under the owner's + lock, which reads do not take, so a file can go between ``is_file()`` and + the read that follows it. + """ + real_is_file = anyio.Path.is_file + doomed: set[Path] = set() + + async def is_file_then_gone(self: anyio.Path) -> bool: + present = await real_is_file(self) + if present and Path(str(self)) in doomed: + await self.unlink() + return present + + monkeypatch.setattr(anyio.Path, "is_file", is_file_then_gone) + return doomed.add + + +async def test_list_by_cluster_skips_a_skill_removed_while_listing( + writer: AgentSkillWriter, + reader: AgentSkillReader, + vanish_once_seen: Callable[[Path], None], +) -> None: + """A skill gone by the time it is read is absent, not an error.""" + for name in ("alpha", "beta"): + path = await writer.write_main( + "a1", + name, + frontmatter=_make_fm( + id=f"a1_{name}", agent_id="a1", name=name, cluster_id="cl1" + ), + body="b", + ) + if name == "alpha": + vanish_once_seen(path) + + results = await reader.list_by_cluster("a1", "cl1") + + assert [fm.name for fm, _body in results] == ["beta"] + + +async def test_read_main_is_none_for_a_skill_removed_before_the_read( + writer: AgentSkillWriter, + reader: AgentSkillReader, + vanish_once_seen: Callable[[Path], None], +) -> None: + path = await writer.write_main("a1", "alpha", frontmatter=_make_fm(), body="b") + vanish_once_seen(path) + + assert await reader.read_main("a1", "alpha", schema=AgentSkillFrontmatter) is None + + +async def test_read_reference_is_none_for_a_file_removed_before_the_read( + writer: AgentSkillWriter, + reader: AgentSkillReader, + vanish_once_seen: Callable[[Path], None], +) -> None: + vanish_once_seen(await writer.write_reference("a1", "alpha", "terms", "t")) + + assert await reader.read_reference("a1", "alpha", "terms") is None + + +async def test_read_script_is_none_for_a_file_removed_before_the_read( + writer: AgentSkillWriter, + reader: AgentSkillReader, + vanish_once_seen: Callable[[Path], None], +) -> None: + vanish_once_seen(await writer.write_script("a1", "alpha", "run.py", "pass\n")) + + assert await reader.read_script("a1", "alpha", "run.py") is None diff --git a/tests/unit/test_infra/test_markdown/test_readers/test_profile_reader.py b/tests/unit/test_infra/test_markdown/test_readers/test_profile_reader.py index 6cb01be1d..1c7897bdb 100644 --- a/tests/unit/test_infra/test_markdown/test_readers/test_profile_reader.py +++ b/tests/unit/test_infra/test_markdown/test_readers/test_profile_reader.py @@ -5,6 +5,7 @@ from pathlib import Path from typing import ClassVar, Literal +import anyio import pytest from pydantic import ValidationError @@ -63,6 +64,30 @@ async def test_read_returns_none_when_missing(reader: ProfileReader) -> None: assert await reader.read("u_ghost", schema=_UserProfileFM) is None +async def test_read_returns_none_when_file_vanishes_after_stat( + writer: ProfileWriter, reader: ProfileReader, monkeypatch: pytest.MonkeyPatch +) -> None: + """A deletion between the is_file check and the read is "not found".""" + await writer.write( + "u_jason", + frontmatter=_UserProfileFM( + id="demo_user_profile_u_jason", + type="demo_user_profile", + user_id="u_jason", + ), + body="b", + ) + original_is_file = anyio.Path.is_file + + async def is_file_then_delete(self: anyio.Path) -> bool: + result = await original_is_file(self) + await self.unlink() + return result + + monkeypatch.setattr(anyio.Path, "is_file", is_file_then_delete) + assert await reader.read("u_jason", schema=_UserProfileFM) is None + + async def test_read_round_trip_through_extra_fields( writer: ProfileWriter, reader: ProfileReader ) -> None: diff --git a/tests/unit/test_infra/test_memtrace_boundary_decision.py b/tests/unit/test_infra/test_memtrace_boundary_decision.py new file mode 100644 index 000000000..0cec75d8c --- /dev/null +++ b/tests/unit/test_infra/test_memtrace_boundary_decision.py @@ -0,0 +1,242 @@ +"""Preserve parsed boundary decisions from buffer input to memcell dependencies.""" + +from __future__ import annotations + +import json +from collections.abc import Sequence +from datetime import UTC, tzinfo +from pathlib import Path +from types import SimpleNamespace + +import pytest +from everalgo.boundary import Cuts +from everalgo.types import ConversationItem + +from everos.config import BoundaryDetectionSettings +from everos.core.utils.datetime import from_timestamp +from everos.infra.memtrace.tracker import MemTraceTracker +from everos.memory import CanonicalMessage +from everos.memory.extract.boundary import BoundaryDetection +from everos.memory.extract.trace import collect_construction_trace + +from .test_memtrace_tracker import _TS_MS, _message, _payload + + +class _ScriptedOperator: + def __init__(self, boundaries: list[int]) -> None: + self.boundaries = boundaries + + async def adetect_batch( + self, + items: Sequence[ConversationItem], + *, + is_final: bool, + custom_instructions: str | None, + tz: tzinfo, + hard_token_limit: int, + hard_message_limit: int, + ) -> Cuts: + ends = list(self.boundaries) + if is_final and (not ends or ends[-1] != len(items)): + ends.append(len(items)) + return Cuts(ends=ends, tail_start=ends[-1] if ends else 0) + + +class _Buffer: + async def list(self, session: object) -> list[CanonicalMessage]: + return [] + + async def keep(self, *args: object, **kwargs: object) -> None: + return None + + async def cut(self, *args: object, **kwargs: object) -> None: + return None + + async def already_cut(self, session: object, message_ids: object) -> set[str]: + return set() + + +@pytest.mark.parametrize("mode", ["chat", "agent"]) +@pytest.mark.parametrize( + ("boundaries", "is_final", "cell_count"), + [([2], False, 1), ([1, 2], True, 3), ([], False, 0), ([], True, 1)], +) +async def test_model_decision_to_memcell_dependencies( + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, + mode: str, + boundaries: list[int], + is_final: bool, + cell_count: int, +) -> None: + monkeypatch.setenv("EVEROS_MEMTRACE_DIR", str(tmp_path / "memtrace")) + messages = [ + CanonicalMessage( + message_id=f"m_sess_a_{_TS_MS + i}_000", + session_id="sess_a", + sender_id="alice", + role="user", + timestamp=from_timestamp((_TS_MS + i) / 1000), + text=f"Part {i}", + ) + for i in range(4) + ] + ingested = SimpleNamespace( + app_id="default", + project_id="default", + session_id="sess_a", + messages=messages, + ) + boundary = BoundaryDetection( + detector=_ScriptedOperator(boundaries), + instructions=SimpleNamespace(load=lambda _: "Messages: {messages}"), + session_buffer=_Buffer(), + settings=BoundaryDetectionSettings(strategy="batch"), + tz=UTC, + ) + + outcome = await boundary.detect(ingested, mode=mode, is_final=is_final) + + assert len(outcome.cells) == cell_count + detection = outcome.detection + assert detection is not None + assert detection["detection_performed"] is True + assert detection["model_result"]["cell_message_ids"] == ( + outcome.per_cell_message_ids + ) + assert detection["message_ids"] == [m.message_id for m in messages] + assert "raw_response" not in detection + + tracker = MemTraceTracker() + for i, message in enumerate(messages): + await tracker.on_memorize( + _payload(_message(message.text, _TS_MS + i)), + is_final=False, + defer_extraction=True, + result=None, + request_id=f"add-{i}", + ) + event_cells = [ + { + "id": memcell_id, + "message_ids": message_ids, + "sender_ids": sender_ids, + "content": cell.model_dump(mode="json"), + } + for memcell_id, message_ids, sender_ids, cell in zip( + outcome.memcell_ids, + outcome.per_cell_message_ids, + outcome.per_cell_all_senders, + outcome.cells, + strict=True, + ) + ] + await tracker.on_memorize( + _payload(), + is_final=is_final, + defer_extraction=False, + result=None, + request_id="detect", + construction_events=[ + { + "phase": "boundary", + "app_id": "default", + "project_id": "default", + "session_id": "sess_a", + "observed_at": "2026-01-01T00:00:00Z", + "detection_performed": True, + "detection": detection, + "cells": event_cells, + } + ], + ) + graph = tracker._graphs[("default", "default", "alice", "sess_a")] + result = graph.search_variables(class_name="boundary_detection_result")[0] + assert not graph.search_variables(class_name="raw_boundary_detection_response") + assert json.loads(result.raw_value)["model_result"] == detection["model_result"] + assert json.loads(result.raw_value)["message_ids"] == detection["message_ids"] + assert result.category == "llm_response" + edges = graph.get_all_edges() + + def parents(node_id: str) -> set[str]: + return { + e.source_full_node_id for e in edges if e.target_full_node_id == node_id + } + + (buffer_id,) = parents(result.full_node_id) + assert buffer_id == "buffer-sess_a-alice@5" + for cell in event_cells: + assert parents(cell["id"] + "@1") == {result.full_node_id} + assert parents("cell-input-" + cell["id"] + "@1") == {cell["id"] + "@1"} + if not outcome.cells: + marker = graph.search_variables(class_name="no_split_marker")[0] + assert parents(marker.full_node_id) == {result.full_node_id} + + +class _AllCutBuffer(_Buffer): + """Buffer whose memcells already hold every fresh id (timeout resend).""" + + def __init__(self, held: list[CanonicalMessage]) -> None: + self._held = held + + async def list(self, session: object) -> list[CanonicalMessage]: + return list(self._held) + + async def already_cut(self, session: object, message_ids: object) -> set[str]: + return set(message_ids) + + +@pytest.mark.parametrize("call", ["buffer", "detect"]) +async def test_fully_filtered_resend_records_unchanged_buffer( + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, + call: str, +) -> None: + """A resend whose rows were all cut already must trace the buffer as-is. + + Without the authoritative ``buffer_loaded`` snapshot the tracker falls + back to appending the resent request messages to the graph buffer, + although the real session buffer never changed. + """ + monkeypatch.setenv("EVEROS_MEMTRACE_DIR", str(tmp_path / "memtrace")) + held = CanonicalMessage( + message_id=f"m_sess_a_{_TS_MS}_000", + session_id="sess_a", + sender_id="alice", + role="user", + timestamp=from_timestamp(_TS_MS / 1000), + text="Kept tail", + ) + resent = CanonicalMessage( + message_id=f"m_sess_a_{_TS_MS + 1}_000", + session_id="sess_a", + sender_id="alice", + role="user", + timestamp=from_timestamp((_TS_MS + 1) / 1000), + text="Resent after a client timeout", + ) + ingested = SimpleNamespace( + app_id="default", + project_id="default", + session_id="sess_a", + messages=[resent], + ) + boundary = BoundaryDetection( + detector=_ScriptedOperator([]), + instructions=SimpleNamespace(load=lambda _: "Messages: {messages}"), + session_buffer=_AllCutBuffer([held]), + settings=BoundaryDetectionSettings(strategy="batch"), + tz=UTC, + ) + + with collect_construction_trace() as events: + if call == "buffer": + outcome = await boundary.buffer(ingested, mode="chat") + else: + outcome = await boundary.detect(ingested, mode="chat", is_final=False) + + assert outcome.status == "skipped" + loaded = [e for e in events if e["phase"] == "buffer_loaded"] + assert len(loaded) == 1 + assert loaded[0]["before_message_ids"] == [held.message_id] + assert loaded[0]["message_ids"] == [held.message_id] diff --git a/tests/unit/test_infra/test_memtrace_buffer_lifecycle.py b/tests/unit/test_infra/test_memtrace_buffer_lifecycle.py new file mode 100644 index 000000000..cdb2932e6 --- /dev/null +++ b/tests/unit/test_infra/test_memtrace_buffer_lifecycle.py @@ -0,0 +1,364 @@ +"""Pin buffer drains, historical boundary inputs and independent search branches.""" + +from __future__ import annotations + +import json +from pathlib import Path +from types import SimpleNamespace + +import pytest +from smartcomment.runtime import ExecNetwork + +from everos.infra.memtrace.tracker import ( + MemTraceTracker, + _boundary_result_identity, +) +from everos.memory.search.dto import SearchProfileItem, UnprocessedMessageDTO +from everos.memory.search.trace import collect_search_trace, record_branch + +from .test_memtrace_tracker import ( + _TS, + _TS_MS, + _load_export, + _message, + _payload, + _req, + _resp, +) + + +@pytest.fixture +def tracker(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> MemTraceTracker: + monkeypatch.setenv("EVEROS_MEMTRACE_DIR", str(tmp_path / "memtrace")) + return MemTraceTracker() + + +@pytest.mark.parametrize("restart", [False, True]) +async def test_two_flushes_drain_separate_buffer_versions( + tracker: MemTraceTracker, + restart: bool, +) -> None: + ids = [f"m_sess_a_{_TS_MS + i}_000" for i in range(3)] + common = { + "app_id": "default", + "project_id": "default", + "session_id": "sess_a", + "observed_at": _TS.isoformat(), + } + for i in range(2): + await tracker.on_memorize( + _payload(_message(str(i), _TS_MS + i)), + is_final=False, + defer_extraction=True, + result=None, + ) + for i in range(2): + consumed = ids[:2] if i == 0 else ids[2:] + await tracker.on_memorize( + _payload(), + is_final=True, + defer_extraction=False, + result=SimpleNamespace(status="extracted", message_count=0), + request_id=f"flush-{i}", + construction_events=[ + { + **common, + "phase": "buffer_loaded", + "before_message_ids": consumed, + "message_ids": consumed, + "sender_ids": ["alice"], + }, + {**common, "phase": "buffer_persisted", "message_ids": []}, + { + **common, + "phase": "boundary", + "cells": [ + { + "id": f"mc_{i}", + "message_ids": consumed, + "sender_ids": ["alice"], + "content": "real cell", + }, + ], + }, + ], + ) + if i == 0: + if restart: + tracker = MemTraceTracker() + await tracker.on_memorize( + _payload(_message("new", _TS_MS + 2)), + is_final=False, + defer_extraction=True, + result=None, + ) + payload = _load_export(tracker, ("default", "default", "alice", "sess_a")) + graph = ExecNetwork.import_graph(payload) + buffers = graph.get_versions("buffer-sess_a-alice") + assert all( + n.comment == "The session messages held in the buffer at this point." + for n in buffers + ) + assert [json.loads(n.raw_value)["message_ids"] for n in buffers] == [ + [], + ids[:1], + ids[:2], + [], + ids[2:], + [], + ] + for i, version in enumerate((3, 5)): + consumed = ids[:2] if i == 0 else ids[2:] + edges = [ + e for e in graph.get_all_edges() if e.target_full_node_id == f"mc_{i}@1" + ] + result_id = ( + "boundary_detection_result:" + f"{_boundary_result_identity('sess_a', consumed)}@1" + ) + assert [e.source_full_node_id for e in edges] == [result_id] + assert [ + e.source_full_node_id + for e in graph.get_all_edges() + if e.target_full_node_id == result_id + ] == [f"buffer-sess_a-alice@{version}"] + op = next( + o + for o in graph.get_all_operations() + if o.metadata.get("request_id") == f"flush-{i}" + and o.op_name == "memory_flush_sess_a" + ) + transitions = [e for e in graph.get_all_edges() if e.op_id == op.op_id] + assert [ + (e.source_full_node_id, e.target_full_node_id) for e in transitions + ] == [ + (f"buffer-sess_a-alice@{version}", f"buffer-sess_a-alice@{version + 1}"), + ] + assert not graph.get_versions("COMMENT:NONE") + + +async def test_deferred_outcome_and_flush_decision_share_one_node( + tracker: MemTraceTracker, +) -> None: + """A flush over the deferred messages versions the same outcome node.""" + ids = [f"m_sess_a_{_TS_MS}_000", f"m_sess_a_{_TS_MS + 1}_001"] + common = { + "app_id": "default", + "project_id": "default", + "session_id": "sess_a", + "observed_at": _TS.isoformat(), + } + await tracker.on_memorize( + _payload(_message("one", _TS_MS), _message("two", _TS_MS + 1)), + is_final=False, + defer_extraction=True, + result=None, + request_id="add-0", + construction_events=[ + { + **common, + "phase": "boundary", + "reason": "deferred", + "detection_performed": False, + "cells": [], + } + ], + ) + await tracker.on_memorize( + _payload(), + is_final=True, + defer_extraction=False, + result=SimpleNamespace(status="extracted", message_count=0), + request_id="flush-0", + construction_events=[ + { + **common, + "phase": "buffer_loaded", + "before_message_ids": ids, + "message_ids": ids, + "sender_ids": ["alice"], + }, + {**common, "phase": "buffer_persisted", "message_ids": []}, + { + **common, + "phase": "boundary", + "detection_performed": True, + "detection": { + "message_ids": ids, + "is_final": True, + "mode": "chat", + "model_result": { + "reasoning": "The topic closes.", + "boundaries": [2], + "should_wait": False, + }, + }, + "cells": [ + { + "id": "mc_0", + "message_ids": ids, + "sender_ids": ["alice"], + "content": "real cell", + } + ], + }, + ], + ) + payload = _load_export(tracker, ("default", "default", "alice", "sess_a")) + graph = ExecNetwork.import_graph(payload) + outcomes = graph.search_variables(class_name="boundary_detection_result") + identity = _boundary_result_identity("sess_a", ids) + assert {node.name for node in outcomes} == {identity} + deferred, split = sorted(outcomes, key=lambda node: node.version) + assert (deferred.version, split.version) == (1, 2) + deferred_value = json.loads(deferred.raw_value) + assert deferred_value["decision"] == "deferred" + assert deferred_value["detection_performed"] is False + assert deferred_value["request_id"] == "add-0" + assert deferred.category == "boundary_outcome" + split_value = json.loads(split.raw_value) + assert split_value["decision"] == "split" + assert split_value["request_id"] == "flush-0" + assert split_value["cell_ids"] == ["mc_0"] + assert split.category == "llm_response" + edges = graph.get_all_edges() + buffer_id = next( + e.source_full_node_id + for e in edges + if e.target_full_node_id == deferred.full_node_id + ) + assert buffer_id.startswith("buffer-sess_a-alice@") + assert any( + e.source_full_node_id == buffer_id + and e.target_full_node_id == split.full_node_id + for e in edges + ) + assert any( + e.source_full_node_id == split.full_node_id + and e.target_full_node_id == "mc_0@1" + for e in edges + ) + + +async def test_nonfinal_boundary_keeps_real_tail_and_empty_flush_is_versioned( + tracker: MemTraceTracker, +) -> None: + await tracker.on_memorize( + _payload(_message("one", _TS_MS), _message("tail", _TS_MS + 1)), + is_final=False, + defer_extraction=False, + result=None, + construction_events=[ + { + "phase": "buffer_persisted", + "app_id": "default", + "project_id": "default", + "session_id": "sess_a", + "observed_at": _TS.isoformat(), + "message_ids": [f"m_sess_a_{_TS_MS + 1}_001"], + } + ], + ) + assert tracker._buffers[("default", "default", "alice", "sess_a")][ + "message_ids" + ] == [f"m_sess_a_{_TS_MS + 1}_001"] + empty = { + "phase": "buffer_persisted", + "app_id": "default", + "project_id": "default", + "session_id": "sess_a", + "observed_at": _TS.isoformat(), + "message_ids": [], + } + for rid in ("drain", "empty-flush"): + await tracker.on_memorize( + _payload(), + is_final=True, + defer_extraction=False, + result=None, + request_id=rid, + construction_events=[empty], + ) + graph = tracker._graphs[("default", "default", "alice", "sess_a")] + versions = graph.get_versions("buffer-sess_a-alice") + assert [len(json.loads(n.raw_value)["message_ids"]) for n in versions] == [ + 0, + 2, + 1, + 0, + 0, + ] + + +async def test_profile_is_untraced_and_pending_messages_feed_context( + tracker: MemTraceTracker, +) -> None: + profile = SearchProfileItem( + id="profile_alice", + user_id="alice", + profile_data={"summary": "camping"}, + ) + message = UnprocessedMessageDTO( + id="m_sess_a_pending_000", + session_id="sess_a", + sender_id="alice", + role="user", + content="new trip", + timestamp=_TS, + ) + with collect_search_trace() as stages: + record_branch("_fetch_profile", "profile", [profile]) + record_branch( + "_load_unprocessed", "unprocessed", [message], session_id="sess_a" + ) + response = _resp(unprocessed=[message]) + response.data.profiles = [profile] + await tracker.on_search( + _req(include_profile=True), response, stages=stages, request_id="branches" + ) + payload = _load_export(tracker) + graph = ExecNetwork.import_graph(payload) + query = graph.search_variables(class_name="query")[0] + context = graph.search_variables(class_name="context")[0] + edge_pairs = { + (e.source_full_node_id, e.target_full_node_id) for e in graph.get_all_edges() + } + assert not graph.search_operations(name_pattern="^_fetch_profile_") + assert not graph.search_variables(class_name="retrieval_hit") + assert not graph.search_variables(category="message") + op = graph.search_operations(name_pattern="^_load_unprocessed_")[0] + assert op.metadata["status"] == "success" + edges = graph.filter_by_operation(op.op_id).edges + assert len(edges) == 1 and edges[0].source_full_node_id == query.full_node_id + result = graph.get_variable(edges[0].target_full_node_id) + assert json.loads(result.raw_value)["items"] == [message.model_dump(mode="json")] + assert result.category == "retrieval_result" + assert (result.full_node_id, context.full_node_id) in edge_pairs + passages = json.loads(context.raw_value)["passages"] + assert json.loads(passages[0]["text"]) == profile.profile_data + + +@pytest.mark.parametrize("include_profile", [False, True]) +async def test_empty_profile_branch_does_not_feed_context( + tracker: MemTraceTracker, + include_profile: bool, +) -> None: + status = "success" if include_profile else "skipped" + with collect_search_trace() as stages: + record_branch("_fetch_profile", "profile", [], status=status) + await tracker.on_search( + _req(include_profile=include_profile), + _resp(), + stages=stages, + request_id="empty-profile", + ) + graph = ExecNetwork.import_graph(_load_export(tracker)) + query = graph.search_variables(class_name="query")[0] + context = graph.search_variables(class_name="context")[0] + assert not graph.search_operations(name_pattern="^_fetch_profile_") + assert not graph.search_variables(class_name="retrieval_results") + assert not graph.search_variables(class_name="retrieval_hit") + edge_pairs = { + (e.source_full_node_id, e.target_full_node_id) for e in graph.get_all_edges() + } + assert (query.full_node_id, context.full_node_id) not in edge_pairs diff --git a/tests/unit/test_infra/test_memtrace_no_split.py b/tests/unit/test_infra/test_memtrace_no_split.py new file mode 100644 index 000000000..cc7777365 --- /dev/null +++ b/tests/unit/test_infra/test_memtrace_no_split.py @@ -0,0 +1,89 @@ +"""Keep deferred and empty boundary outcomes connected across repeated adds.""" + +from __future__ import annotations + +import importlib +import json +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import AsyncMock + +import pytest +from smartcomment.runtime import ExecNetwork + +from everos.infra.memtrace.tracker import MemTraceTracker +from everos.memory.extract.boundary import BoundaryOutcome +from everos.memory.extract.trace import collect_construction_trace + +from .test_memtrace_tracker import _TS_MS, _load_export, _message, _payload + +mm = importlib.import_module("everos.service.memory._memorize") + + +@pytest.mark.parametrize("deferred", [False, True]) +@pytest.mark.parametrize("restart", [False, True]) +async def test_each_add_without_cells_has_a_connected_outcome( + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, + deferred: bool, + restart: bool, +) -> None: + monkeypatch.setenv("EVEROS_MEMTRACE_DIR", str(tmp_path / "memtrace")) + tracker = MemTraceTracker() + ingested = SimpleNamespace( + app_id="default", project_id="default", session_id="sess_a" + ) + monkeypatch.setattr(mm, "ingest_process", AsyncMock(return_value=ingested)) + empty = BoundaryOutcome([], [], [], [], "accumulated", 1) + buffer = AsyncMock(return_value=empty) + detect = AsyncMock(return_value=empty) + memorizer = mm.Memorizer.__new__(mm.Memorizer) + memorizer._boundary = SimpleNamespace(buffer=buffer, detect=detect) + memorizer._multimodal_llm = None + memorizer._raw_file_builder = None + memorizer._sender_names = None + + for index in range(2): + if restart and index: + tracker = MemTraceTracker() + payload = _payload(_message(f"Conversation part {index}", _TS_MS + index)) + with collect_construction_trace() as events: + result = await memorizer._cut( + payload, + mode="chat", + is_final=False, + defer_extraction=deferred, + ) + assert len(events) == 1 and events[0]["phase"] == "boundary" + await tracker.on_memorize( + payload, + is_final=False, + defer_extraction=deferred, + result=result, + request_id=f"add-{index}", + construction_events=events, + ) + graph = ExecNetwork.import_graph( + _load_export(tracker, ("default", "default", "alice", "sess_a")) + ) + outcomes = graph.search_variables(class_name="boundary_detection_result") + assert len(outcomes) == 2 + assert len(graph.search_variables(class_name="no_split_marker")) == 2 + assert not graph.search_variables(category="construction_input") + for index, outcome in enumerate(outcomes): + value = json.loads(outcome.raw_value) + assert value["cell_ids"] == [] + assert value["decision"] == ("deferred" if deferred else "no_split") + assert len(value["message_ids"]) == index + 1 + if deferred: + assert value["detection_performed"] is False + edges = graph.get_all_edges() + incoming = [e for e in edges if e.target_full_node_id == outcome.full_node_id] + assert len(incoming) == 1 + assert incoming[0].source_full_node_id == f"buffer-sess_a-alice@{index + 2}" + outgoing = [e for e in edges if e.source_full_node_id == outcome.full_node_id] + assert len(outgoing) == 1 + assert graph.get_variable(outgoing[0].target_full_node_id).class_name == ( + "no_split_marker" + ) + assert (buffer.await_count, detect.await_count) == ((2, 0) if deferred else (0, 2)) diff --git a/tests/unit/test_infra/test_memtrace_qa.py b/tests/unit/test_infra/test_memtrace_qa.py new file mode 100644 index 000000000..32eb91cd2 --- /dev/null +++ b/tests/unit/test_infra/test_memtrace_qa.py @@ -0,0 +1,156 @@ +"""Unit tests for post-hoc QA injection into exported MemTrace graphs. + +Pins :func:`everos.infra.memtrace.qa.inject_qa_dir`: QA records are stitched +onto the recorded query node with the same identity / category / operation +vocabulary as the live tracker hooks (``prompt`` / ``prediction`` / +``golden_answers`` / ``judge_response`` nodes, ``response`` / ``evaluation`` +operations), the exported graph round-trips through ``ExecNetwork``, and +records whose query node cannot be resolved are skipped without failing the +batch. +""" + +from __future__ import annotations + +import datetime as _dt +import json +from pathlib import Path +from typing import Any + +import pytest +from smartcomment.runtime import ExecNetwork + +from everos.infra.memtrace.qa import inject_qa_dir +from everos.infra.memtrace.tracker import MemTraceTracker +from everos.memory.search.dto import ( + SearchData, + SearchEpisodeItem, + SearchMethod, + SearchRequest, + SearchResponse, +) + +_TS = _dt.datetime(2026, 1, 1, tzinfo=_dt.UTC) + + +@pytest.fixture +def tracker(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> MemTraceTracker: + """A tracker exporting into an isolated per-test directory.""" + monkeypatch.setenv("EVEROS_MEMTRACE_DIR", str(tmp_path / "memtrace")) + return MemTraceTracker() + + +def _req() -> SearchRequest: + return SearchRequest( + user_id="alice", + query="camping", + method=SearchMethod.HYBRID, + top_k=5, + ) + + +def _resp() -> SearchResponse: + return SearchResponse( + request_id="r" * 32, + data=SearchData( + episodes=[ + SearchEpisodeItem( + id="ep_1", + user_id="alice", + session_id="sess_a", + timestamp=_TS, + sender_ids=["alice"], + subject="s", + summary="s", + episode="body ep_1", + type="Conversation", + score=0.9, + ) + ], + ), + ) + + +def _record(**overrides: Any) -> dict[str, Any]: + record: dict[str, Any] = { + "user_id": "alice", + "request_id": "req-1", + "query": "camping", + "prompt": "answer prompt text", + "answer": "She went camping in July.", + "golden_answers": ["July"], + "judge_response": "VERDICT: 1 correct", + "judge_score": 1.0, + } + record.update(overrides) + return record + + +async def test_inject_qa_round_trip(tracker: MemTraceTracker, tmp_path: Path) -> None: + """Injection adds the full QA chain and the graph still imports cleanly.""" + await tracker.on_search(_req(), _resp(), request_id="req-1") + graph_dir = tmp_path / "memtrace" + + injected = inject_qa_dir(graph_dir, [_record()]) + + assert sum(injected.values()) == 1 + path = next(graph_dir.glob("*.json")) + data = json.loads(path.read_text(encoding="utf-8")) + nodes = {node["name"]: node for node in data["data"]["nodes"]} + query_id = "query-alice-req-1" + assert nodes[f"prompt-{query_id}"]["category"] == "prompt" + prediction = nodes[f"prediction-{query_id}"] + assert prediction["category"] == "llm_response" + assert prediction["class_name"] == "prediction" + golden = nodes[f"golden-{query_id}"] + assert golden["category"] == "golden_answers" + assert nodes[f"judge-{query_id}"]["class_name"] == "judge_response" + + ops = {op["op_name"]: op for op in data["data"]["operations"]} + assert ops[f"answer_generation_{query_id}"]["category"] == "response" + assert ops[f"inject_golden_answers_{query_id}"]["category"] == "evaluation" + assert ops[f"judge_answer_{query_id}"]["category"] == "evaluation" + assert ops[f"answer_generation_{query_id}"]["metadata"]["source"] == "qa_injection" + + # The injected graph still round-trips through the smartcomment importer. + ExecNetwork.import_graph(data) + + +async def test_inject_qa_skips_unknown_request( + tracker: MemTraceTracker, tmp_path: Path +) -> None: + """A record with no matching query node is skipped, not an error.""" + await tracker.on_search(_req(), _resp(), request_id="req-1") + graph_dir = tmp_path / "memtrace" + + injected = inject_qa_dir(graph_dir, [_record(request_id="req-nope")]) + + assert injected == {} + data = json.loads(next(graph_dir.glob("*.json")).read_text(encoding="utf-8")) + assert not any( + node["name"].startswith(("prediction-", "golden-", "judge-", "prompt-")) + for node in data["data"]["nodes"] + ) + + +async def test_inject_qa_without_golden_records_answer_only( + tracker: MemTraceTracker, tmp_path: Path +) -> None: + """Without golden answers only the answer stage is injected.""" + await tracker.on_search(_req(), _resp(), request_id="req-1") + graph_dir = tmp_path / "memtrace" + + injected = inject_qa_dir( + graph_dir, + [_record(golden_answers=[], judge_response=None, judge_score=None)], + ) + + assert sum(injected.values()) == 1 + data = json.loads(next(graph_dir.glob("*.json")).read_text(encoding="utf-8")) + names = {node["name"] for node in data["data"]["nodes"]} + query_id = "query-alice-req-1" + assert f"prediction-{query_id}" in names + assert f"golden-{query_id}" not in names + assert f"judge-{query_id}" not in names + ops = {op["op_name"] for op in data["data"]["operations"]} + assert f"answer_generation_{query_id}" in ops + assert f"inject_golden_answers_{query_id}" not in ops diff --git a/tests/unit/test_infra/test_memtrace_regressions.py b/tests/unit/test_infra/test_memtrace_regressions.py new file mode 100644 index 000000000..1288230c8 --- /dev/null +++ b/tests/unit/test_infra/test_memtrace_regressions.py @@ -0,0 +1,413 @@ +"""Pin actual revisions, request isolation, construction evidence and QA inputs.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from smartcomment.runtime import ExecNetwork + +from everos.infra.memtrace.qa import inject_qa_dir +from everos.infra.memtrace.tracker import MemTraceTracker, resolve_query_node +from everos.memory.search.trace import collect_search_trace, record_stage + +from .test_memtrace_tracker import ( + _EPISODE_MD, + _hit_node, + _load_export, + _req, + _resp, +) + + +@pytest.fixture +def tracker(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> MemTraceTracker: + monkeypatch.setenv("EVEROS_MEMTRACE_DIR", str(tmp_path / "memtrace")) + return MemTraceTracker() + + +def _path_exists(payload: dict, source: str, target: str) -> bool: + adjacency: dict[str, list[str]] = {} + for edge in payload["data"]["edges"]: + adjacency.setdefault(edge["source_full_node_id"], []).append( + edge["target_full_node_id"] + ) + pending, visited = [source], {source} + for node in pending: + for child in adjacency.get(node, []): + if child not in visited: + visited.add(child) + pending.append(child) + return target in visited + + +async def test_updated_revision_is_not_renumbered_in_search_graph( + tracker: MemTraceTracker, + tmp_path: Path, +) -> None: + from examples.memtrace.merge import merge_graphs + + path = tmp_path / "users/alice/episodes/2026-01-01.md" + path.parent.mkdir(parents=True) + path.write_text(_EPISODE_MD.replace("Alice went camping in July.", "Friday")) + await tracker._sync_files() + path.write_text(_EPISODE_MD.replace("Alice went camping in July.", "Monday")) + await tracker._sync_files() + response = _resp("ep_1") + response.data.episodes[0].episode = "Monday" + await tracker.on_search(_req(), response, request_id="after-update") + search = _load_export(tracker) + hit = _hit_node(search, "alice_ep_1") + assert json.loads(hit["value"])["source_revision"] == "alice_ep_1@2" + canonical = [n for n in search["data"]["nodes"] if n["name"] == "alice_ep_1"] + assert [n["version"] for n in canonical] == [2] + assert json.loads(canonical[0]["value"])["content"] == "Monday" + construction = _load_export(tracker, ("default", "default", "alice", "sess_a")) + merged = merge_graphs([construction, search]) + ExecNetwork.import_graph(merged) + memories = [n for n in merged["data"]["nodes"] if n["name"].endswith("/alice_ep_1")] + assert sorted(n["version"] for n in memories) == [1, 2] + merged_hit = _hit_node(merged, "alice_ep_1") + revision = json.loads(merged_hit["value"])["source_revision"] + assert revision in {n["full_node_id"] for n in memories} + assert revision.endswith("@2") + + +async def test_disk_state_does_not_replace_actual_stale_search_text( + tracker: MemTraceTracker, + tmp_path: Path, +) -> None: + path = tmp_path / "users/alice/episodes/2026-01-01.md" + path.parent.mkdir(parents=True) + path.write_text(_EPISODE_MD.replace("Alice went camping in July.", "Monday")) + response = _resp("ep_1") + response.data.episodes[0].episode = "Friday" + await tracker.on_search(_req(), response) + hit = _hit_node(_load_export(tracker), "alice_ep_1") + snapshot = json.loads(hit["value"]) + assert snapshot["content"] == "Friday" + assert snapshot["source_revision"] is None + assert hit["metadata"]["revision_resolved"] is False + + +async def test_shared_memory_does_not_connect_queries_to_other_contexts( + tracker: MemTraceTracker, + tmp_path: Path, +) -> None: + path = tmp_path / "users/alice/episodes/2026-01-01.md" + path.parent.mkdir(parents=True) + path.write_text(_EPISODE_MD.replace("Alice went camping in July.", "body ep_1")) + tracker._root = tmp_path + await tracker.on_search(_req(), _resp("ep_1"), request_id="first") + await tracker.on_search(_req(), _resp("ep_1"), request_id="second") + payload = _load_export(tracker) + assert _hit_node(payload, "alice_ep_1", "query-alice-first")["metadata"][ + "revision_resolved" + ] + assert _hit_node(payload, "alice_ep_1", "query-alice-second")["metadata"][ + "revision_resolved" + ] + assert not _path_exists( + payload, "query:query-alice-second@1", "context:context-query-alice-first@1" + ) + assert _path_exists( + payload, "query:query-alice-second@1", "context:context-query-alice-second@1" + ) + + +async def test_skill_bridge_inputs_match_actual_computation( + tracker: MemTraceTracker, +) -> None: + from types import SimpleNamespace + + candidates = [SimpleNamespace(id="skill", score=0.8, source="dense")] + with collect_search_trace() as stages: + record_stage("fusion", "agent_case", candidates) + record_stage("sparse", "agent_skill", candidates) + record_stage("dense", "agent_skill", candidates) + record_stage( + "bridged_dense", + "agent_skill", + candidates, + inputs=[("agent_skill", "dense"), ("agent_case", "fusion")], + ) + record_stage( + "fusion", + "agent_skill", + candidates, + inputs=[("agent_skill", "sparse"), ("agent_skill", "bridged_dense")], + ) + await tracker.on_search(_req(), _resp(), stages=stages, request_id="bridge") + graph = ExecNetwork.import_graph(_load_export(tracker)) + for phase, expected in ( + ("bridged_dense", {"agent_skill_dense", "agent_case_fusion"}), + ("fusion", {"agent_skill_sparse", "agent_skill_bridged_dense"}), + ): + op = graph.search_operations(name_pattern=f"^agent_skill_{phase}_")[0] + inputs = { + e.source_full_node_id for e in graph.filter_by_operation(op.op_id).edges + } + assert len(inputs) == 2 + assert all( + any(f"candidates_{name}-" in node for node in inputs) for name in expected + ) + + +async def test_restart_query_ids_and_explicit_qa_resolution( + tracker: MemTraceTracker, +) -> None: + await tracker.on_search(_req(), _resp(), request_id="repeat") + restarted = MemTraceTracker() + await restarted.on_search(_req(), _resp(), request_id="repeat") + graph = restarted._graphs[("default", "default", "alice", "global")] + assert len(graph.get_versions("query:query-alice-repeat")) == 1 + assert resolve_query_node(graph, owner="alice", request_id="repeat") is None + queries = graph.search_variables(class_name="query") + assert len(queries) == 2 + for query in queries: + resolved = resolve_query_node( + graph, + owner="alice", + request_id="repeat", + query_full_node_id=query.full_node_id, + ) + assert resolved is not None and resolved[1].full_node_id == query.full_node_id + + +async def test_failed_add_messages_reach_the_error_operation( + tracker: MemTraceTracker, +) -> None: + payload = { + "session_id": "s", + "messages": [ + { + "sender_id": "alice", + "content": "Friday", + "timestamp": "2026-01-01T00:00:00Z", + } + ], + } + await tracker.on_memorize_error( + payload, + is_final=False, + defer_extraction=False, + error=ValueError("invented"), + request_id="failed", + ) + graph = tracker._graphs[("default", "default", "alice", "s")] + message = graph.search_variables(category="message")[0] + op = graph.search_operations(name_pattern="^memory_add_")[0] + subgraph = graph.filter_by_operation(op.op_id) + assert message.full_node_id in {e.source_full_node_id for e in subgraph.edges} + assert op.metadata["status"] == "error" + assert message.metadata["acceptance"] == "attempted" + + +async def test_actual_construction_values_exist_without_markdown_outputs( + tracker: MemTraceTracker, +) -> None: + common = { + "app_id": "default", + "project_id": "default", + "session_id": "s", + "observed_at": "2026-01-01T00:00:00Z", + } + events = [ + { + **common, + "phase": "boundary", + "cells": [ + { + "id": "mc", + "message_ids": [], + "sender_ids": ["alice"], + "content": {"messages": ["Friday"]}, + } + ], + }, + { + **common, + "phase": "extraction_result", + "memcell_id": "mc", + "owners": ["alice"], + "content": "", + }, + ] + await tracker.on_memorize( + {"session_id": "s", "messages": []}, + is_final=False, + defer_extraction=False, + result=None, + construction_events=events, + ) + graph = tracker._graphs[("default", "default", "alice", "s")] + result = graph.search_variables(category="extraction_result")[0] + assert json.loads(result.value)["content"] == "" + op = graph.search_operations(name_pattern="^extraction_result_")[0] + assert op.metadata["source"] == "construction_event" + assert not op.metadata.get("observation_only") + assert "Friday" in graph.search_variables(category="construction_input")[0].value + + +async def test_qa_uses_actual_answer_context_and_injection_is_idempotent( + tracker: MemTraceTracker, + tmp_path: Path, +) -> None: + await tracker.on_search(_req(), _resp("ep_1"), request_id="qa") + record = { + "user_id": "alice", + "request_id": "qa", + "answer_context": "episode only", + "answer": "Unknown", + "golden_answers": ["Friday"], + "judge_response": "VERDICT: 0", + "judge_score": 0, + } + inject_qa_dir(tmp_path / "memtrace", [record]) + payload = _load_export(tracker) + inject_qa_dir(tmp_path / "memtrace", [record]) + second = _load_export(tracker) + assert len(payload["data"]["operations"]) == len(second["data"]["operations"]) + graph = ExecNetwork.import_graph(second) + answer = graph.search_operations(category="response")[0] + nodes = graph.filter_by_operation(answer.op_id).nodes + context = next(n for n in nodes if n.class_name == "answer_context") + assert json.loads(context.value)["content"] == "episode only" + assert not any(n.class_name == "context" for n in nodes) + + +@pytest.mark.parametrize("answer_only", [False, True]) +async def test_qa_injection_is_idempotent_for_partial_records( + tracker: MemTraceTracker, answer_only: bool +) -> None: + await tracker.on_search(_req(), _resp(), request_id="once") + record = {"user_id": "alice", "request_id": "once"} + if answer_only: + record.update(answer="Friday", answer_context="Friday") + else: + record.update(golden_answers=["Friday"]) + assert sum(inject_qa_dir(tracker.out_dir, [record]).values()) == 1 + path = next(tracker.out_dir.glob("*.json")) + before = path.read_bytes() + assert inject_qa_dir(tracker.out_dir, [record]) == {} + assert path.read_bytes() == before + + +async def test_qa_injection_requires_unique_tenant_scope( + tracker: MemTraceTracker, +) -> None: + for app in ("a", "b"): + await tracker.on_search( + _req().model_copy(update={"app_id": app}), _resp(), request_id="same" + ) + record = {"user_id": "alice", "request_id": "same", "answer": "Friday"} + assert inject_qa_dir(tracker.out_dir, [record]) == {} + assert ( + sum(inject_qa_dir(tracker.out_dir, [{**record, "app_id": "b"}]).values()) == 1 + ) + for path in tracker.out_dir.glob("*.json"): + graph = ExecNetwork.import_graph(json.loads(path.read_text())) + assert bool(graph.search_variables(class_name="prediction")) == ( + graph.metadata["app_id"] == "b" + ) + + +@pytest.mark.parametrize("stage", ["apply", "export"]) +async def test_failed_scan_application_retries_unchanged_files( + tracker: MemTraceTracker, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + stage: str, +) -> None: + path = tmp_path / "users/alice/episodes/2026-01-01.md" + path.parent.mkdir(parents=True) + path.write_text(_EPISODE_MD) + tracker._root = tmp_path + name = "_apply_snapshot" if stage == "apply" else "_export" + original = getattr(tracker, name) + calls = 0 + + def fail_once(*args: object, **kwargs: object) -> object: + nonlocal calls + calls += 1 + if calls == 1: + raise RuntimeError("injected failure") + return original(*args, **kwargs) + + monkeypatch.setattr(tracker, name, fail_once) + with pytest.raises(RuntimeError, match="injected failure"): + await tracker._sync_files() + assert not tracker._file_state + await tracker._sync_files() + data = _load_export(tracker, ("default", "default", "alice", "sess_a")) + revisions = [n for n in data["data"]["nodes"] if n["name"] == "alice_ep_1"] + assert len(revisions) == 1 + assert json.loads(revisions[0]["value"])["content"] == "Alice went camping in July." + + +@pytest.mark.parametrize("rewritten_before_scan", [False, True]) +async def test_persisted_episode_links_only_matching_actual_extractor_output( + tracker: MemTraceTracker, tmp_path: Path, rewritten_before_scan: bool +) -> None: + path = tmp_path / "users/alice/episodes/2026-01-01.md" + path.parent.mkdir(parents=True) + path.write_text( + _EPISODE_MD.replace("Alice went camping in July.", "Monday") + if rewritten_before_scan + else _EPISODE_MD + ) + tracker._root = tmp_path + common = { + "app_id": "default", + "project_id": "default", + "session_id": "sess_a", + "observed_at": "2026-01-01T00:00:00Z", + } + events = [ + { + **common, + "phase": "boundary", + "cells": [ + { + "id": "mc_1", + "message_ids": [], + "sender_ids": ["alice"], + "content": "Camping in July", + } + ], + }, + { + **common, + "phase": "extraction_result", + "memcell_id": "mc_1", + "owners": ["alice"], + "content": "Alice went camping in July.", + }, + { + **common, + "phase": "persisted_episode", + "memcell_id": "mc_1", + "owners": ["alice"], + "entry_id": "ep_1", + }, + ] + await tracker.on_memorize( + {"session_id": "sess_a", "messages": []}, + is_final=True, + defer_extraction=False, + result=None, + construction_events=events, + request_id="add", + ) + payload = _load_export(tracker, ("default", "default", "alice", "sess_a")) + graph = ExecNetwork.import_graph(payload) + extracted = graph.search_variables(category="extraction_result")[0] + assert _path_exists(payload, extracted.full_node_id, "alice_ep_1@1") is ( + not rewritten_before_scan + ) + op = graph.search_operations(name_pattern="^episode_extraction_ep_1$")[0] + assert op.metadata["source"] == ( + "file_diff" if rewritten_before_scan else "construction_event" + ) + assert bool(op.metadata.get("observation_only")) is rewritten_before_scan diff --git a/tests/unit/test_infra/test_memtrace_topology.py b/tests/unit/test_infra/test_memtrace_topology.py new file mode 100644 index 000000000..0fdd08864 --- /dev/null +++ b/tests/unit/test_infra/test_memtrace_topology.py @@ -0,0 +1,327 @@ +"""Pin shared extraction inputs, compact search branches and readable exports.""" + +from __future__ import annotations + +import json +from pathlib import Path +from types import SimpleNamespace + +import pytest +from smartcomment.runtime import ExecNetwork + +from everos.infra.memtrace.qa import inject_qa_dir +from everos.infra.memtrace.tracker import MemTraceTracker +from everos.memory.search.dto import SearchProfileItem, UnprocessedMessageDTO +from everos.memory.search.trace import collect_search_trace, record_branch + +from .test_memtrace_tracker import ( + _EPISODE_MD, + _TS, + _load_export, + _req, + _resp, +) + +_INPUT = {"items": [{"role": "user", "content": "Camping on Friday."}]} +_KEY = ("default", "default", "alice", "sess_a") + + +async def _empty_memcells(ids: list[str]) -> list[SimpleNamespace]: + return [] + + +memcell_repo = SimpleNamespace(find_by_ids=_empty_memcells) + + +@pytest.fixture(autouse=True) +def _inject_memcell_repo(monkeypatch: pytest.MonkeyPatch) -> None: + original_init = MemTraceTracker.__init__ + + def init(tracker: MemTraceTracker) -> None: + original_init(tracker) + tracker.set_memcell_repo(memcell_repo) + + monkeypatch.setattr(MemTraceTracker, "__init__", init) + + +@pytest.fixture +def tracker(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> MemTraceTracker: + monkeypatch.setenv("EVEROS_MEMTRACE_DIR", str(tmp_path / "memtrace")) + return MemTraceTracker() + + +def _write_foresights(root: Path) -> None: + path = root / "users/alice/.foresights/2026-01-01.md" + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text( + "---\nuser_id: alice\n---\n" + + "\n".join( + f"\n**owner_id**: alice\n" + "**session_id**: sess_a\n**parent_type**: memcell\n" + "**parent_id**: mc_1\n### Foresight\n" + f"Prepare for trip {i}.\n" + for i in range(2) + ) + ) + + +def _archive(**overrides: object) -> SimpleNamespace: + return SimpleNamespace( + **{ + "app_id": "default", + "project_id": "default", + "session_id": "sess_a", + "message_ids_json": "[]", + "sender_ids_json": '["alice"]', + "payload_json": json.dumps(_INPUT), + **overrides, + } + ) + + +def _assert_descriptions(payload: dict) -> None: + for collection in ("nodes", "operations", "edges"): + for record in payload["data"][collection]: + assert record.get("comment"), (collection, record) + assert "_load_unprocessed" not in record["comment"] + assert "_fetch_profile" not in record["comment"] + + +@pytest.mark.parametrize("restart", [False, True]) +async def test_episode_and_late_foresights_share_the_original_input( + tracker: MemTraceTracker, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + restart: bool, +) -> None: + async def archive(ids: list[str]) -> list[SimpleNamespace]: + return [_archive()] + + monkeypatch.setattr(memcell_repo, "find_by_ids", archive) + common = { + "app_id": "default", + "project_id": "default", + "session_id": "sess_a", + "observed_at": _TS.isoformat(), + } + events = [ + { + **common, + "phase": "boundary", + "cells": [ + { + "id": "mc_1", + "message_ids": [], + "sender_ids": ["alice"], + "content": _INPUT, + } + ], + }, + { + **common, + "phase": "extraction_attempt", + "memcell_id": "mc_1", + "owners": ["alice"], + }, + { + **common, + "phase": "extraction_result", + "memcell_id": "mc_1", + "owners": ["alice"], + "content": "Alice went camping in July.", + }, + { + **common, + "phase": "persisted_episode", + "memcell_id": "mc_1", + "owners": ["alice"], + "entry_id": "ep_1", + }, + ] + path = tmp_path / "users/alice/episodes/2026-01-01.md" + path.parent.mkdir(parents=True) + path.write_text(_EPISODE_MD) + await tracker.on_memorize( + {"session_id": "sess_a", "messages": []}, + is_final=True, + defer_extraction=False, + result=None, + request_id="build", + construction_events=events, + ) + if restart: + tracker = MemTraceTracker() + _write_foresights(tmp_path) + await tracker.sync_now() + payload = _load_export(tracker, _KEY) + graph = ExecNetwork.import_graph(payload) + cell = graph.get_versions("cell-input-mc_1") + assert len(cell) == 1 + assert json.loads(cell[0].raw_value)["content"] == _INPUT + assert not graph.search_variables(category="extraction_attempt") + assert not graph.search_operations(name_pattern="^extraction_attempt_") + result = graph.search_variables(category="extraction_result")[0] + pairs = [ + (e.source_full_node_id, e.target_full_node_id) for e in graph.get_all_edges() + ] + assert pairs.count(("mc_1@1", cell[0].full_node_id)) == 1 + assert (cell[0].full_node_id, result.full_node_id) in pairs + assert (result.full_node_id, "alice_ep_1@1") in pairs + for i in range(2): + assert pairs.count((cell[0].full_node_id, f"alice_fs_{i}@1")) == 1 + assert ("mc_1@1", f"alice_fs_{i}@1") not in pairs + _assert_descriptions(payload) + + +@pytest.mark.parametrize( + "source", + [ + "valid", + "missing", + "invalid", + "wrong_app", + "wrong_project", + "wrong_session", + "error", + ], +) +async def test_foresight_input_recovery_is_exact_or_explicitly_unknown( + tracker: MemTraceTracker, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + source: str, +) -> None: + async def archive(ids: list[str]) -> list[SimpleNamespace]: + if source == "missing": + return [] + if source == "error": + raise RuntimeError("database unavailable") + overrides = {} + if source.startswith("wrong_"): + overrides[f"{source.removeprefix('wrong_')}_id"] = "other" + if source == "invalid": + overrides["payload_json"] = "invalid JSON" + return [_archive(**overrides)] + + monkeypatch.setattr(memcell_repo, "find_by_ids", archive) + _write_foresights(tmp_path) + await tracker.sync_now() + payload = _load_export(tracker, _KEY) + graph = ExecNetwork.import_graph(payload) + cell = graph.get_versions("cell-input-mc_1") + assert len(cell) == 1 + assert json.loads(cell[0].raw_value)["content"] == ( + _INPUT if source == "valid" else None + ) + assert cell[0].metadata["content_observed"] is (source == "valid") + observe = graph.search_operations(name_pattern="^observe_cell_")[0] + assert observe.metadata["observation_only"] is True + _assert_descriptions(payload) + + +@pytest.mark.parametrize("scenario", ["success", "empty", "skipped", "error"]) +async def test_search_branches_have_one_described_result_without_profile_nodes( + tracker: MemTraceTracker, scenario: str +) -> None: + status = "success" if scenario == "empty" else scenario + messages = ( + [ + UnprocessedMessageDTO( + id=f"pending-{i}", + session_id="sess_a", + sender_id="alice", + role="user", + content=f"Trip detail {i}", + timestamp=_TS, + ) + for i in range(2) + ] + if scenario == "success" + else [] + ) + profile = SearchProfileItem( + id="profile_alice", user_id="alice", profile_data={"summary": "camping"} + ) + with collect_search_trace() as stages: + record_branch("_fetch_profile", "profile", [profile]) + record_branch("_load_unprocessed", "unprocessed", messages, status=status) + if status == "error": + await tracker.on_search_error( + _req(), stages=stages, error=RuntimeError("read failed"), request_id=status + ) + else: + response = _resp(unprocessed=messages) + response.data.profiles = [profile] + await tracker.on_search(_req(), response, stages=stages, request_id=status) + payload = _load_export(tracker) + graph = ExecNetwork.import_graph(payload) + assert not graph.search_operations(name_pattern="^_fetch_profile_") + assert not graph.search_variables(class_name="retrieval_hit") + assert not graph.search_variables(category="message") + result = graph.search_variables(class_name="retrieval_results") + assert len(result) == 1 and result[0].category == "retrieval_result" + assert result[0].metadata["status"] == status + assert json.loads(result[0].raw_value)["items"] == [ + m.model_dump(mode="json") for m in messages + ] + if status == "error": + assert not graph.search_variables(class_name="context") + else: + context = graph.search_variables(class_name="context")[0] + pairs = { + (e.source_full_node_id, e.target_full_node_id) + for e in graph.get_all_edges() + } + assert (result[0].full_node_id, context.full_node_id) in pairs + pending_edge = next( + e + for e in graph.get_all_edges() + if e.source_full_node_id == result[0].full_node_id + and e.target_full_node_id == context.full_node_id + ) + assert ( + pending_edge.comment + == { + "success": "Include the pending session messages in the context.", + "empty": "Add no pending messages because the session buffer is empty.", + "skipped": "Add no pending messages because no session was specified.", + }[scenario] + ) + assert json.loads(json.loads(context.raw_value)["passages"][0]["text"]) == ( + profile.profile_data + ) + _assert_descriptions(payload) + + +async def test_live_and_offline_qa_have_descriptions(tracker: MemTraceTracker) -> None: + for request_id in ("live", "offline"): + await tracker.on_search(_req(), _resp(), request_id=request_id) + await tracker.on_answer( + app_id="default", + project_id="default", + owner="alice", + request_id="live", + answer="Friday", + answer_context="Camping on Friday.", + ) + await tracker.on_evaluation( + app_id="default", + project_id="default", + owner="alice", + request_id="live", + golden_answers=["Friday"], + judge_score=1.0, + ) + inject_qa_dir( + tracker.out_dir, + [ + { + "user_id": "alice", + "request_id": "offline", + "answer": "Friday", + "golden_answers": ["Friday"], + "judge_score": 1.0, + } + ], + ) + _assert_descriptions(_load_export(tracker)) diff --git a/tests/unit/test_infra/test_memtrace_tracker.py b/tests/unit/test_infra/test_memtrace_tracker.py new file mode 100644 index 000000000..294809211 --- /dev/null +++ b/tests/unit/test_infra/test_memtrace_tracker.py @@ -0,0 +1,1802 @@ +"""Unit tests for the MemTrace tracker. + +Pins the MemTraceBench-compatible export produced by +:meth:`MemTraceTracker.on_search` / :meth:`MemTraceTracker.on_memorize`: + +* without stage records the legacy ``query -> hits -> context`` chain is + kept and no ``candidates_*`` pool nodes appear; +* with stage records each stage becomes a ``candidates_{kind}_{phase}`` + pool node, edges chain ``query -> recall pools -> fusion pools -> last + pool -> hits`` with only terminal pools expanding candidates and no + duplicate hit edges. Request-local hits reference canonical write-path + ``{owner}_{entry_id}`` revisions when the response content matches; +* ``unprocessed_messages`` share one retrieval result linked into the context; +* graph files are named with collision-proof ``{safe}-{digest}`` + fragments, one file per ``(app, project, owner, bucket)`` key, and + ``graph_id`` carries the same digest fragments; +* a diff round exports each dirtied graph exactly once, entry moves across + files produce no versions, downtime deletions are reconciled on the + first post-restart diff, and ``/add`` messages carry the ingest + ``m___`` identity (an unparseable timestamp falls + back to ``m__invalid_`` flagged ``timestamp_invalid``); +* flush requests record a request-level ``memory_flush`` op (including + empty flushes, in the ``unknown``-owner graph) and failed requests + record ``status: "error"`` ops (``on_memorize_error`` / + ``on_search_error``, the latter keeping the partial stage pools); +* operation metadata carries ``event_seq`` / ``observed_at`` (and + ``source`` / ``trigger`` on file-diff ops), stage pools carry + ``total_count`` / ``truncated``, query identities derive from the + request id with a sequence suffix on collision, memcell membership is + tri-state (``exact`` / ``approximate`` / ``lookup_failed``), and + ``sync_now`` flushes a final shutdown diff. + +The tracker resolves its root / export dir from ``EVEROS_ROOT`` / +``EVEROS_MEMTRACE_DIR`` at construction; the root conftest pins +``EVEROS_ROOT`` to ``tmp_path`` and the fixture below pins the export dir, +so every test exports into an isolated directory. +""" + +from __future__ import annotations + +import asyncio +import datetime as _dt +import importlib +import json +import re +from collections import Counter +from pathlib import Path +from types import SimpleNamespace +from typing import Any + +import pytest + +from everos.infra.memtrace.tracker import GraphKey, MemTraceTracker +from everos.memory.search.dto import ( + SearchAtomicFactItem, + SearchData, + SearchEpisodeItem, + SearchMethod, + SearchRequest, + SearchResponse, + UnprocessedMessageDTO, +) +from everos.memory.search.trace import ( + CandidateBrief, + SearchStageRecord, +) + + +async def _empty_memcells(ids: list[str]) -> list[Any]: + return [] + + +memcell_repo = SimpleNamespace(find_by_ids=_empty_memcells) + + +@pytest.fixture(autouse=True) +def _inject_memcell_repo(monkeypatch: pytest.MonkeyPatch) -> None: + original_init = MemTraceTracker.__init__ + + def init(tracker: MemTraceTracker) -> None: + original_init(tracker) + tracker.set_memcell_repo(memcell_repo) + + monkeypatch.setattr(MemTraceTracker, "__init__", init) + + +_TS = _dt.datetime(2026, 1, 1, tzinfo=_dt.UTC) +_TS_MS = 1767225600000 # 2026-01-01T00:00:00Z in unix milliseconds. + +# Minimal episode markdown with one entry block; picked up by the +# tracker's file diff as the write-path record of ``alice_ep_1``. +_EPISODE_MD = """--- +user_id: alice +--- + +**owner_id**: alice +**session_id**: sess_a +**timestamp**: 2026-01-01T00:00:00+00:00 +**parent_type**: memcell +**parent_id**: mc_1 +**sender_ids**: [alice] +### Subject +Camping +### Summary +Camping trip +### Content +Alice went camping in July. + +""" + +# Two entries carved out of two different memcells of the same session. +_TWO_MEMCELL_MD = """--- +user_id: alice +--- + +**owner_id**: alice +**session_id**: sess_a +**timestamp**: 2026-01-01T00:00:00+00:00 +**parent_type**: memcell +**parent_id**: mc_1 +**sender_ids**: [alice] +### Content +First cell. + + +**owner_id**: alice +**session_id**: sess_a +**timestamp**: 2026-01-01T00:05:00+00:00 +**parent_type**: memcell +**parent_id**: mc_2 +**sender_ids**: [alice] +### Content +Second cell. + +""" + +# Three parentless entries of one owner/session: same graph, one diff round. +_THREE_ENTRY_MD = """--- +user_id: alice +--- + +**owner_id**: alice +**session_id**: sess_a +**timestamp**: 2026-01-01T00:00:00+00:00 +**sender_ids**: [alice] +### Content +One. + + +**owner_id**: alice +**session_id**: sess_a +**timestamp**: 2026-01-01T00:01:00+00:00 +**sender_ids**: [alice] +### Content +Two. + + +**owner_id**: alice +**session_id**: sess_a +**timestamp**: 2026-01-01T00:02:00+00:00 +**sender_ids**: [alice] +### Content +Three. + +""" + + +@pytest.fixture +def tracker(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> MemTraceTracker: + """A tracker exporting into an isolated per-test directory.""" + monkeypatch.setenv("EVEROS_MEMTRACE_DIR", str(tmp_path / "memtrace")) + return MemTraceTracker() + + +def _req(**kwargs) -> SearchRequest: + options: dict[str, Any] = { + "user_id": "alice", + "query": "camping", + "method": SearchMethod.HYBRID, + "top_k": 5, + } + options.update(kwargs) + return SearchRequest(**options) + + +def _episode_item(eid: str, *, score: float = 0.9) -> SearchEpisodeItem: + return SearchEpisodeItem( + id=eid, + user_id="alice", + session_id="sess_a", + timestamp=_TS, + sender_ids=["alice"], + subject="s", + summary="s", + episode=f"body {eid}", + type="Conversation", + score=score, + atomic_facts=[ + SearchAtomicFactItem(id=f"{eid}_f1", content=f"fact {eid}", score=score) + ], + ) + + +def _resp( + *episode_ids: str, unprocessed: list[UnprocessedMessageDTO] | None = None +) -> SearchResponse: + return SearchResponse( + request_id="r" * 32, + data=SearchData( + episodes=[_episode_item(eid) for eid in episode_ids], + unprocessed_messages=unprocessed or [], + ), + ) + + +def _stages() -> list[SearchStageRecord]: + return [ + SearchStageRecord( + phase="sparse", + kind="episode", + candidates=( + CandidateBrief(id="ep_1", score=0.8, source="keyword"), + CandidateBrief(id="ep_2", score=0.7, source="keyword"), + ), + ), + SearchStageRecord( + phase="dense", + kind="episode", + candidates=(CandidateBrief(id="ep_1", score=0.9, source="vector"),), + ), + SearchStageRecord( + phase="fusion", + kind="episode", + candidates=(CandidateBrief(id="ep_1", score=0.95, source=""),), + metadata={"fusion_mode": "rrf", "enable_rerank": False}, + ), + ] + + +def _payload(*messages: dict[str, Any]) -> dict[str, Any]: + return { + "session_id": "sess_a", + "app_id": "default", + "project_id": "default", + "messages": list(messages), + } + + +def _message(content: str, timestamp: Any, *, sender: str = "alice") -> dict[str, Any]: + return { + "sender_id": sender, + "role": "user", + "content": content, + "timestamp": timestamp, + } + + +def _load_export( + tracker: MemTraceTracker, + key: GraphKey = ("default", "default", "alice", "global"), +) -> dict: + return json.loads(tracker._graph_path(key).read_text()) + + +def _nodes_by_name(data: dict) -> dict[str, list[dict]]: + by_name: dict[str, list[dict]] = {} + for node in data["data"]["nodes"]: + by_name.setdefault(node["name"], []).append(node) + return by_name + + +def _fnid(node: dict) -> str: + class_name = node.get("class_name") + full_name = f"{class_name}:{node['name']}" if class_name else node["name"] + return f"{full_name}@{node['version']}" + + +def _edge_pairs(data: dict) -> set[tuple[str, str]]: + return { + (e["source_full_node_id"], e["target_full_node_id"]) + for e in data["data"]["edges"] + } + + +def _hit_node(data: dict, identity: str, query_id: str | None = None) -> dict: + hits = [ + node + for node in data["data"]["nodes"] + if node.get("class_name") == "retrieval_hit" + and json.loads(node["value"]).get("memory_identity") == identity + and (query_id is None or json.loads(node["value"]).get("query_id") == query_id) + ] + assert len(hits) == 1 + return hits[0] + + +async def test_on_search_without_stages_keeps_legacy_chain( + tracker: MemTraceTracker, tmp_path: Path +) -> None: + await tracker.on_search(_req(), _resp("ep_1")) + data = _load_export(tracker) + nodes = _nodes_by_name(data) + assert not any(name.startswith("candidates_") for name in nodes) + query_ids = [name for name in nodes if name.startswith("query-alice-")] + assert len(query_ids) == 1 + query_fnid = _fnid(nodes[query_ids[0]][0]) + edges = _edge_pairs(data) + # Legacy query -> hit edges (episode + its nested atomic fact). + assert (query_fnid, _fnid(_hit_node(data, "alice_ep_1"))) in edges + assert (query_fnid, _fnid(_hit_node(data, "alice_ep_1_f1"))) in edges + # Hits feed the assembled context. + context_fnid = _fnid(nodes[f"context-{query_ids[0]}"][0]) + assert (_fnid(_hit_node(data, "alice_ep_1")), context_fnid) in edges + assert (_fnid(_hit_node(data, "alice_ep_1_f1")), context_fnid) in edges + + +async def test_on_search_with_stages_records_pools_and_chain( + tracker: MemTraceTracker, tmp_path: Path +) -> None: + await tracker.on_search(_req(), _resp("ep_1"), stages=_stages()) + data = _load_export(tracker) + nodes = _nodes_by_name(data) + query_id = next(name for name in nodes if name.startswith("query-alice-")) + query_fnid = _fnid(nodes[query_id][0]) + + # One pool node per recorded stage, carrying the capped triple lists. + for phase, count in (("sparse", 2), ("dense", 1), ("fusion", 1)): + pool = nodes[f"candidates_episode_{phase}-{query_id}"][0] + assert pool["category"] == "memory_context" + value = json.loads(pool["value"]) + assert value["phase"] == phase and value["kind"] == "episode" + assert value["count"] == count + assert len(value["ids"]) == len(value["scores"]) == len(value["sources"]) + fusion_pool = nodes[f"candidates_episode_fusion-{query_id}"][0] + assert fusion_pool["metadata"]["fusion_mode"] == "rrf" + assert fusion_pool["metadata"]["enable_rerank"] is False + + edges = _edge_pairs(data) + sparse_fnid = _fnid(nodes[f"candidates_episode_sparse-{query_id}"][0]) + dense_fnid = _fnid(nodes[f"candidates_episode_dense-{query_id}"][0]) + fusion_fnid = _fnid(fusion_pool) + # query -> recall pools; recall pools -> fusion pool. + assert (query_fnid, sparse_fnid) in edges + assert (query_fnid, dense_fnid) in edges + assert (sparse_fnid, fusion_fnid) in edges + assert (dense_fnid, fusion_fnid) in edges + # Intermediate pools retain their snapshots without expanding entries. + assert (sparse_fnid, _fnid(_hit_node(data, "alice_ep_1"))) not in edges + assert (sparse_fnid, "alice_ep_2@1") not in edges + assert (dense_fnid, _fnid(_hit_node(data, "alice_ep_1"))) not in edges + assert (fusion_fnid, _fnid(_hit_node(data, "alice_ep_1"))) in edges + # Last pool -> every hit; no direct query -> hit edge anymore. + hit_fnid = _fnid(_hit_node(data, "alice_ep_1")) + fact_fnid = _fnid(_hit_node(data, "alice_ep_1_f1")) + assert (fusion_fnid, hit_fnid) in edges + assert (fusion_fnid, fact_fnid) in edges + assert (query_fnid, hit_fnid) not in edges + + assert "alice_ep_2" not in nodes + terminal_edges = [ + edge + for edge in data["data"]["edges"] + if edge["source_full_node_id"] == fusion_fnid + ] + assert Counter(e["target_full_node_id"] for e in terminal_edges) == { + hit_fnid: 1, + fact_fnid: 1, + } + listed = next(e for e in terminal_edges if e["target_full_node_id"] == hit_fnid) + projected = next(e for e in terminal_edges if e["target_full_node_id"] == fact_fnid) + assert listed["metadata"]["membership"] is True + assert listed["metadata"]["score"] == 0.95 + assert "response_only" not in listed["metadata"] + assert projected["metadata"]["response_only"] is True + + +@pytest.mark.parametrize("failed", [False, True]) +async def test_only_terminal_pool_per_kind_expands_candidates( + tracker: MemTraceTracker, failed: bool +) -> None: + """Interleaved routes, including failures, expand only their last pools.""" + stages = [ + SearchStageRecord( + phase=phase, + kind=kind, + candidates=(CandidateBrief(id=eid, score=0.8, source=""),), + ) + for phase, kind, eid in ( + ("sparse", "episode", "ep_dropped"), + ("dense", "agent_case", "case_dropped"), + ("fusion", "episode", "ep_kept"), + ("fusion", "agent_case", "case_kept"), + ) + ] + if failed: + await tracker.on_search_error( + _req(), error=RuntimeError("failed"), stages=stages + ) + else: + await tracker.on_search(_req(), _resp(), stages=stages) + data = _load_export(tracker) + nodes = _nodes_by_name(data) + assert "alice_ep_dropped" not in nodes + assert "alice_case_dropped" not in nodes + for kind, eid in (("episode", "ep_kept"), ("agent_case", "case_kept")): + pool = next( + versions[0] + for name, versions in nodes.items() + if name.startswith(f"candidates_{kind}_fusion-") + ) + entry = _hit_node(data, f"alice_{eid}") + assert json.loads(entry["value"])["source"] == "candidate_pool" + assert (_fnid(pool), _fnid(entry)) in _edge_pairs(data) + + +async def test_hierarchy_response_episode_stays_connected_without_hit_edge( + tracker: MemTraceTracker, +) -> None: + """Fact-only hierarchy snapshots still connect their response episode.""" + stage = SearchStageRecord( + phase="hierarchy", + kind="episode", + candidates=(CandidateBrief(id="ep_1_f1", score=0.9, source=""),), + total_count=1, + ) + await tracker.on_search(_req(), _resp("ep_1"), stages=[stage]) + data = _load_export(tracker) + nodes = _nodes_by_name(data) + pool = next(v[0] for n, v in nodes.items() if n.startswith("candidates_")) + assert json.loads(pool["value"])["ids"] == ["ep_1_f1"] + outgoing = { + edge["target_full_node_id"]: edge["metadata"] + for edge in data["data"]["edges"] + if edge["source_full_node_id"] == _fnid(pool) + } + assert len(outgoing) == 2 + assert outgoing[_fnid(_hit_node(data, "alice_ep_1"))]["response_only"] is True + assert "response_only" not in outgoing[_fnid(_hit_node(data, "alice_ep_1_f1"))] + for name in ("alice_ep_1", "alice_ep_1_f1"): + hit = _hit_node(data, name) + assert hit["version"] == 1 + assert any( + edge["source_full_node_id"] == _fnid(hit) + and edge["target_full_node_id"].startswith("context:") + for edge in data["data"]["edges"] + ) + + +async def test_capped_terminal_pool_keeps_unlisted_returned_entries( + tracker: MemTraceTracker, +) -> None: + """Truncating the stage snapshot cannot disconnect an actual response.""" + stage = SearchStageRecord( + phase="fusion", + kind="episode", + candidates=(CandidateBrief(id="ep_1", score=0.8, source=""),), + total_count=120, + ) + await tracker.on_search(_req(), _resp("ep_2"), stages=[stage]) + data = _load_export(tracker) + nodes = _nodes_by_name(data) + pool = next(v[0] for n, v in nodes.items() if n.startswith("candidates_")) + assert pool["metadata"]["truncated"] is True + assert json.loads(pool["value"])["ids"] == ["ep_1"] + assert (_fnid(pool), _fnid(_hit_node(data, "alice_ep_1"))) in _edge_pairs(data) + assert (_fnid(pool), _fnid(_hit_node(data, "alice_ep_2"))) in _edge_pairs(data) + + +async def test_duplicate_candidates_and_hits_have_one_membership_edge( + tracker: MemTraceTracker, +) -> None: + """Repeated identities cannot reintroduce duplicate terminal edges.""" + candidate = CandidateBrief(id="ep_1", score=0.8, source="") + stage = SearchStageRecord( + phase="fusion", kind="episode", candidates=(candidate, candidate) + ) + await tracker.on_search(_req(), _resp("ep_1", "ep_1"), stages=[stage]) + data = _load_export(tracker) + counts = Counter( + edge["target_full_node_id"] + for edge in data["data"]["edges"] + if edge["source_full_node_id"].startswith("hybrid_retrieval_results:") + ) + assert counts == { + _fnid(_hit_node(data, "alice_ep_1")): 1, + _fnid(_hit_node(data, "alice_ep_1_f1")): 1, + } + + +async def test_candidate_stitches_onto_tracked_entry( + tracker: MemTraceTracker, tmp_path: Path +) -> None: + """A candidate known to the file index keeps its full write-path snapshot. + + The entry node shares the ``{owner}_{entry_id}`` identity across the + extraction graph (``alice`` / ``sess_a``) and the search graph + (``alice`` / ``global``). + """ + md_path = tmp_path / "users" / "alice" / "episodes" / "2026-01-01.md" + md_path.parent.mkdir(parents=True) + md_path.write_text(_EPISODE_MD, encoding="utf-8") + + response = _resp("ep_1") + response.data.episodes[0].episode = "Alice went camping in July." + await tracker.on_search(_req(), response, stages=_stages()) + + # The write-path diff recorded the extraction into the session graph. + extraction_nodes = _nodes_by_name( + _load_export(tracker, ("default", "default", "alice", "sess_a")) + ) + assert "alice_ep_1" in extraction_nodes + + search_nodes = _nodes_by_name(_load_export(tracker)) + entry = search_nodes["alice_ep_1"][0] + value = json.loads(entry["value"]) + # Full tracked snapshot, not the lightweight candidate stub. + assert value["content"] == "Alice went camping in July." + assert value["kind"] == "episode" + + +async def test_atomic_fact_entry_carries_fact_text( + tracker: MemTraceTracker, tmp_path: Path +) -> None: + """A kind-specific body section (``### Fact``) still reaches the graph. + + The AtomicFact writer emits ``### Fact`` instead of ``### Content``; the + entry snapshot must fold it into ``content`` so the exported graph keeps + the fact text for downstream attribution. + """ + md_path = tmp_path / "users" / "alice" / ".atomic_facts" / "af-2026-01-01.md" + md_path.parent.mkdir(parents=True) + md_path.write_text(_ATOMIC_FACT_MD, encoding="utf-8") + + await tracker.on_search(_req(), _resp("ep_1")) + + extraction_nodes = _nodes_by_name( + _load_export(tracker, ("default", "default", "alice", "sess_a")) + ) + assert "alice_af_1" in extraction_nodes + value = json.loads(extraction_nodes["alice_af_1"][0]["value"]) + assert value["content"] == "Alice went camping in July." + assert value["kind"] == "atomic_fact" + + +# Atomic-fact daily log with the kind-specific ``### Fact`` body section +# (the AtomicFact writer emits no ``### Content``). +_ATOMIC_FACT_MD = """--- +user_id: alice +--- + +**owner_id**: alice +**session_id**: sess_a +**timestamp**: 2026-01-01T00:00:00+00:00 +**parent_type**: memcell +**parent_id**: mc_1 +**sender_ids**: [alice] +### Fact +Alice went camping in July. + +""" + + +async def test_unprocessed_messages_link_into_context( + tracker: MemTraceTracker, tmp_path: Path +) -> None: + unprocessed = [ + UnprocessedMessageDTO( + id="m-1", + session_id="sess_a", + sender_id="alice", + sender_name="Alice", + role="user", + content="still buffering", + timestamp=_TS, + ) + ] + await tracker.on_search(_req(), _resp("ep_1", unprocessed=unprocessed)) + data = _load_export(tracker) + nodes = _nodes_by_name(data) + result = next( + versions[0] + for name, versions in nodes.items() + if name.startswith("candidates_unprocessed_") + ) + assert result["category"] == "retrieval_result" + assert result["class_name"] == "retrieval_results" + assert json.loads(result["value"])["items"][0]["content"] == "still buffering" + assert "m-1" not in nodes + query_id = next(name for name in nodes if name.startswith("query-alice-")) + context_fnid = _fnid(nodes[f"context-{query_id}"][0]) + assert (_fnid(result), context_fnid) in _edge_pairs(data) + + +async def test_disabled_tracker_writes_nothing( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + monkeypatch.setenv("EVEROS_MEMTRACE_ENABLED", "0") + monkeypatch.setenv("EVEROS_MEMTRACE_DIR", str(tmp_path / "memtrace")) + tracker = MemTraceTracker() + await tracker.on_search(_req(), _resp("ep_1"), stages=_stages()) + assert not (tmp_path / "memtrace").exists() + + +async def test_empty_daily_log_records_removed_entries_as_deletions( + tracker: MemTraceTracker, tmp_path: Path +) -> None: + md_path = tmp_path / "users" / "alice" / "episodes" / "2026-01-01.md" + md_path.parent.mkdir(parents=True) + md_path.write_text(_EPISODE_MD, encoding="utf-8") + await tracker.on_search(_req(), _resp()) + + md_path.write_text("---\nuser_id: alice\n---\n", encoding="utf-8") + await tracker.on_search(_req(), _resp()) + + nodes = _nodes_by_name( + _load_export(tracker, ("default", "default", "alice", "sess_a")) + ) + versions = sorted(nodes["alice_ep_1"], key=lambda node: node["version"]) + assert [node["version"] for node in versions] == [1, 2] + assert json.loads(versions[-1]["value"])["deleted"] is True + + +async def test_deleted_whole_file_artifact_is_recorded( + tracker: MemTraceTracker, tmp_path: Path +) -> None: + profile_path = tmp_path / "users" / "alice" / "user.md" + profile_path.parent.mkdir(parents=True) + profile_path.write_text( + "---\nuser_id: alice\n---\n# User profile\n", encoding="utf-8" + ) + await tracker.on_search(_req(), _resp()) + + profile_path.unlink() + await tracker.on_search(_req(), _resp()) + + nodes = _nodes_by_name(_load_export(tracker)) + versions = sorted(nodes["profile-alice"], key=lambda node: node["version"]) + assert [node["version"] for node in versions] == [1, 2] + assert json.loads(versions[-1]["value"])["deleted"] is True + + +def test_parse_failure_is_retried_without_a_file_change( + tracker: MemTraceTracker, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + md_path = tmp_path / "users" / "alice" / "episodes" / "2026-01-01.md" + md_path.parent.mkdir(parents=True) + md_path.write_text(_EPISODE_MD, encoding="utf-8") + tracker_mod = importlib.import_module("everos.infra.memtrace.tracker") + real_parse = tracker_mod.parse_memory_file + calls = 0 + + def _flaky_parse(*args, **kwargs): + nonlocal calls + calls += 1 + if calls == 1: + raise ValueError("transient partial write") + return real_parse(*args, **kwargs) + + monkeypatch.setattr(tracker_mod, "parse_memory_file", _flaky_parse) + + first_changed, _ = tracker._scan() + second_changed, _ = tracker._scan() + + assert first_changed == [] + assert len(second_changed) == 1 + assert calls == 2 + + +async def test_app_project_scopes_export_to_distinct_graphs( + tracker: MemTraceTracker, tmp_path: Path +) -> None: + for app_id, content in (("app_a", "A camping trip."), ("app_b", "B trip.")): + md_path = ( + tmp_path + / app_id + / "proj" + / "users" + / "alice" + / "episodes" + / "2026-01-01.md" + ) + md_path.parent.mkdir(parents=True) + md_path.write_text( + _EPISODE_MD.replace("Alice went camping in July.", content), + encoding="utf-8", + ) + + for app, text in (("app_a", "A camping trip."), ("app_b", "B trip.")): + response = _resp("ep_1") + response.data.episodes[0].episode = text + await tracker.on_search(_req(app_id=app, project_id="proj"), response) + + graph_a = _nodes_by_name( + _load_export(tracker, ("app_a", "proj", "alice", "global")) + ) + graph_b = _nodes_by_name( + _load_export(tracker, ("app_b", "proj", "alice", "global")) + ) + assert json.loads(graph_a["alice_ep_1"][0]["value"])["content"] == ( + "A camping trip." + ) + assert json.loads(graph_b["alice_ep_1"][0]["value"])["content"] == "B trip." + + +async def test_skill_main_file_uses_search_result_identity( + tracker: MemTraceTracker, tmp_path: Path +) -> None: + skill_path = ( + tmp_path + / "default_app" + / "default_project" + / "agents" + / "bot" + / "skills" + / "plan" + / "SKILL.md" + ) + skill_path.parent.mkdir(parents=True) + skill_path.write_text( + "---\nagent_id: bot\nname: plan\n---\n# Plan\n", encoding="utf-8" + ) + + await tracker._sync_files() + + nodes = _nodes_by_name( + _load_export(tracker, ("default", "default", "bot", "global")) + ) + assert "bot_plan" in nodes + assert ( + "artifact-bot-default_app/default_project/agents/bot/skills/plan/SKILL.md" + not in nodes + ) + + +async def test_skill_reference_is_not_recorded_as_an_independent_skill( + tracker: MemTraceTracker, tmp_path: Path +) -> None: + ref_path = ( + tmp_path + / "default_app/default_project/agents/bot/skills/skill_plan" + / "references/notes.md" + ) + ref_path.parent.mkdir(parents=True) + ref_path.write_text("Notes for the plan skill.\n", encoding="utf-8") + + await tracker._sync_files() + + nodes = _nodes_by_name( + _load_export(tracker, ("default", "default", "bot", "global")) + ) + artifact = next(iter(nodes.values()))[0] + assert json.loads(artifact["value"])["kind"] == "skill_reference" + + +async def test_restart_reuses_unchanged_entry_and_records_later_update( + tracker: MemTraceTracker, tmp_path: Path +) -> None: + md_path = tmp_path / "users" / "alice" / "episodes" / "2026-01-01.md" + md_path.parent.mkdir(parents=True) + md_path.write_text(_EPISODE_MD, encoding="utf-8") + await tracker._sync_files() + + restarted = MemTraceTracker() + await restarted._sync_files() + session_key = ("default", "default", "alice", "sess_a") + initial = _nodes_by_name(_load_export(restarted, session_key)) + assert len(initial["alice_ep_1"]) == 1 + + md_path.write_text( + _EPISODE_MD.replace("Alice went camping in July.", "Alice stayed home."), + encoding="utf-8", + ) + await restarted._sync_files() + updated = _nodes_by_name(_load_export(restarted, session_key)) + assert len(updated["alice_ep_1"]) == 2 + assert "Alice stayed home." in updated["alice_ep_1"][-1]["value"] + + +async def test_restart_continues_the_existing_message_buffer( + tracker: MemTraceTracker, tmp_path: Path +) -> None: + await tracker._record_messages( + "default", "default", "sess_a", [_message("first", 1)] + ) + await tracker._flush_dirty_graphs() + restarted = MemTraceTracker() + await restarted._record_messages( + "default", "default", "sess_a", [_message("second", 2)] + ) + await restarted._flush_dirty_graphs() + + nodes = _nodes_by_name( + _load_export(restarted, ("default", "default", "alice", "sess_a")) + ) + versions = sorted(nodes["buffer-sess_a-alice"], key=lambda n: n["version"]) + assert [node["version"] for node in versions] == [1, 2, 3] + assert json.loads(versions[0]["value"])["message_ids"] == [] + assert len(json.loads(versions[-1]["value"])["message_ids"]) == 2 + + +@pytest.mark.parametrize("restart", [False, True]) +async def test_both_chat_roles_feed_each_buffer_version( + tracker: MemTraceTracker, restart: bool +) -> None: + """Both user and assistant inputs reach initialization and mutation.""" + expected_ids = [] + for batch in range(2): + if batch and restart: + tracker = MemTraceTracker() + messages = [ + _message(f"user {batch}", _TS_MS + batch * 10), + { + **_message( + f"assistant {batch}", _TS_MS + batch * 10 + 1, sender="assistant" + ), + "role": "assistant", + }, + ] + await tracker.on_memorize( + _payload(*messages), + is_final=False, + defer_extraction=True, + result=None, + request_id=f"add-{batch}", + ) + batch_ids = [ + f"m_sess_a_{_TS_MS + batch * 10 + idx}_{idx:03d}" for idx in range(2) + ] + expected_ids.extend(batch_ids) + for owner in ("alice", "assistant"): + data = _load_export(tracker, ("default", "default", owner, "sess_a")) + nodes = _nodes_by_name(data) + buffer = max(nodes[f"buffer-sess_a-{owner}"], key=lambda n: n["version"]) + assert buffer["version"] == batch + 2 + assert json.loads(buffer["value"])["message_ids"] == expected_ids + for message_id in batch_ids: + assert (f"{message_id}@1", _fnid(buffer)) in _edge_pairs(data) + ops = _ops_by_name(data)["memory_add_sess_a"] + assert all(op["metadata"]["message_count"] == 2 for op in ops) + + +async def test_complete_message_batches_remain_scope_isolated( + tracker: MemTraceTracker, +) -> None: + """Full conversation buffers remain partitioned by app, project, session.""" + for idx, (app, project, session) in enumerate( + (("a", "p", "s"), ("b", "p", "s"), ("a", "q", "s"), ("a", "p", "t")) + ): + messages = [ + _message("user", _TS_MS + idx * 10), + { + **_message("reply", _TS_MS + idx * 10 + 1, sender="assistant"), + "role": "assistant", + }, + ] + await tracker.on_memorize( + { + "app_id": app, + "project_id": project, + "session_id": session, + "messages": messages, + }, + is_final=False, + defer_extraction=True, + result=None, + ) + data = _load_export(tracker, (app, project, "alice", session)) + nodes = _nodes_by_name(data) + buffer = json.loads(nodes[f"buffer-{session}-alice"][-1]["value"]) + assert buffer["message_ids"] == [ + f"m_{session}_{_TS_MS + idx * 10 + offset}_{offset:03d}" + for offset in range(2) + ] + + +async def test_shutdown_records_foresight_body_evidence_and_memcell( + tracker: MemTraceTracker, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """A late foresight write keeps its source chain and later file versions.""" + messages = [ + _message("I will go camping.", _TS_MS), + { + **_message("Pack warm clothes.", _TS_MS + 1, sender="assistant"), + "role": "assistant", + }, + ] + await tracker.on_memorize( + _payload(*messages), is_final=False, defer_extraction=True, result=None + ) + message_ids = [f"m_sess_a_{_TS_MS + idx}_{idx:03d}" for idx in range(2)] + + async def find_boundary(ids: list[str]) -> list[SimpleNamespace]: + assert ids == ["mc_1"] + return [ + SimpleNamespace( + app_id="default", + project_id="default", + message_ids_json=json.dumps(message_ids), + ) + ] + + monkeypatch.setattr(memcell_repo, "find_by_ids", find_boundary) + markdown = """--- +user_id: alice +--- + +**owner_id**: alice +**session_id**: sess_a +**timestamp**: 2026-01-01T00:00:00+00:00 +**parent_type**: memcell +**parent_id**: mc_1 +### Foresight +Alice may need warm clothes for camping. +### Evidence +Alice plans to camp in January. + +""" + path = tmp_path / "users" / "alice" / ".foresights" / "foresight-2026-01-01.md" + path.parent.mkdir(parents=True) + path.write_text(markdown, encoding="utf-8") + await tracker.sync_now() + key = ("default", "default", "alice", "sess_a") + data = _load_export(tracker, key) + nodes = _nodes_by_name(data) + value = json.loads(nodes["alice_fs_1"][0]["value"]) + assert value["kind"] == "foresight" + assert value["owner_id"] == "alice" and value["session_id"] == "sess_a" + assert value["content"] == ( + "Alice may need warm clothes for camping.\n\nAlice plans to camp in January." + ) + assert ("mc_1@1", "alice_fs_1@1") not in _edge_pairs(data) + assert ("mc_1@1", "cell-input-mc_1@1") in _edge_pairs(data) + assert ("cell-input-mc_1@1", "alice_fs_1@1") in _edge_pairs(data) + assert nodes["mc_1"][0]["metadata"]["membership"] == "exact" + for message_id in message_ids: + assert (f"{message_id}@1", "mc_1@1") not in _edge_pairs(data) + _assert_recovered_boundary(data, "buffer-sess_a-alice@2", "mc_1") + op = _ops_by_name(data)["foresight_extraction_fs_1"][0] + assert op["metadata"]["trigger"] == "shutdown" + path.write_text(markdown.replace("warm clothes", "a tent"), encoding="utf-8") + await tracker.sync_now() + path.unlink() + await tracker.sync_now() + versions = _nodes_by_name(_load_export(tracker, key))["alice_fs_1"] + assert [n["version"] for n in versions] == [1, 2, 3] + assert json.loads(versions[-1]["value"])["deleted"] is True + + +async def test_graph_file_names_are_collision_proof( + tracker: MemTraceTracker, tmp_path: Path +) -> None: + """Ids that ``_safe_name`` folds together still get distinct graph files.""" + owners = ("张三", "李四", "a@b", "a_b") + for owner in owners: + await tracker.on_search(_req(user_id=owner), _resp("ep_1")) + + expected = { + tracker._graph_path(("default", "default", owner, "global")) for owner in owners + } + assert len(expected) == 4 + assert set((tmp_path / "memtrace").glob("*.json")) == expected + # Each graph holds exactly its own owner's query. + for owner in owners: + path = tracker._graph_path(("default", "default", owner, "global")) + nodes = _nodes_by_name(json.loads(path.read_text())) + queries = [name for name in nodes if name.startswith("query-")] + assert len(queries) == 1 + assert queries[0].startswith(f"query-{owner}-") + + +async def test_sync_files_exports_each_graph_once( + tracker: MemTraceTracker, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """A diff round dirtying one graph for several entries exports it once.""" + exports: list[GraphKey] = [] + real_export = MemTraceTracker._export + + def counting_export(self: MemTraceTracker, key: GraphKey, graph: object) -> None: + exports.append(key) + real_export(self, key, graph) + + monkeypatch.setattr(MemTraceTracker, "_export", counting_export) + md_path = tmp_path / "users" / "alice" / "episodes" / "2026-01-01.md" + md_path.parent.mkdir(parents=True) + md_path.write_text(_THREE_ENTRY_MD, encoding="utf-8") + + await tracker._sync_files() + + assert exports == [("default", "default", "alice", "sess_a")] + + +def _assert_recovered_boundary(data: dict, buffer_id: str, cell_id: str) -> None: + """A recovered cell also has a result between its buffer and membership.""" + result_id = f"boundary_detection_result:boundary-observed-{cell_id}-v1@1" + edges = _edge_pairs(data) + assert (buffer_id, result_id) in edges + assert (result_id, cell_id + "@1") in edges + assert (buffer_id, cell_id + "@1") not in edges + assert {source for source, target in edges if target == cell_id + "@1"} == { + result_id + } + result = next(n for n in data["data"]["nodes"] if n["full_node_id"] == result_id) + assert result["metadata"]["observation_only"] is True + assert json.loads(result["value"])["detection_performed"] is None + + +async def test_memcell_membership_uses_recorded_boundary_data( + tracker: MemTraceTracker, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Two memcells extracted in one round each link only their own messages.""" + message_ids = [f"m_sess_a_{_TS_MS + idx}_{idx:03d}" for idx in range(4)] + boundary = {"mc_1": message_ids[:2], "mc_2": message_ids[2:]} + + async def fake_find_by_ids(ids: list[str]) -> list[SimpleNamespace]: + return [ + SimpleNamespace( + app_id="default", + project_id="default", + message_ids_json=json.dumps(boundary[memcell_id]), + ) + for memcell_id in ids + if memcell_id in boundary + ] + + monkeypatch.setattr(memcell_repo, "find_by_ids", fake_find_by_ids) + md_path = tmp_path / "users" / "alice" / "episodes" / "2026-01-01.md" + md_path.parent.mkdir(parents=True) + md_path.write_text(_TWO_MEMCELL_MD, encoding="utf-8") + + payload = _payload(*[_message(f"msg {idx}", _TS_MS + idx) for idx in range(4)]) + await tracker.on_memorize( + payload, is_final=False, defer_extraction=False, result=None + ) + + data = _load_export(tracker, ("default", "default", "alice", "sess_a")) + nodes = _nodes_by_name(data) + assert json.loads(nodes["mc_1"][0]["value"])["message_ids"] == message_ids[:2] + assert json.loads(nodes["mc_2"][0]["value"])["message_ids"] == message_ids[2:] + assert nodes["mc_1"][0]["metadata"]["membership"] == "exact" + edges = _edge_pairs(data) + assert (f"{message_ids[0]}@1", "mc_1@1") not in edges + assert (f"{message_ids[1]}@1", "mc_1@1") not in edges + assert (f"{message_ids[2]}@1", "mc_2@1") not in edges + assert (f"{message_ids[3]}@1", "mc_2@1") not in edges + # No cross-claiming: neither memcell links the other cell's messages. + assert (f"{message_ids[2]}@1", "mc_1@1") not in edges + assert (f"{message_ids[0]}@1", "mc_2@1") not in edges + _assert_recovered_boundary(data, "buffer-sess_a-alice@2", "mc_1") + _assert_recovered_boundary(data, "buffer-sess_a-alice@2", "mc_2") + + +@pytest.mark.parametrize("restart", [False, True]) +async def test_foresights_reuse_one_memcell_boundary( + tracker: MemTraceTracker, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + restart: bool, +) -> None: + """Derived entries cannot duplicate membership or invent sender-only versions.""" + messages = [ + _message("user", _TS_MS), + {**_message("reply", _TS_MS + 1, sender="assistant"), "role": "assistant"}, + ] + message_ids = [f"m_sess_a_{_TS_MS}_000", f"m_sess_a_{_TS_MS + 1}_001"] + + async def boundary(ids: list[str]) -> list[SimpleNamespace]: + return [ + SimpleNamespace( + app_id="default", + project_id="default", + message_ids_json=json.dumps(message_ids), + sender_ids_json=json.dumps(["alice", "assistant"]), + ) + ] + + monkeypatch.setattr(memcell_repo, "find_by_ids", boundary) + await tracker.on_memorize( + _payload(*messages), is_final=False, defer_extraction=True, result=None + ) + episode = tmp_path / "users/alice/episodes/2026-01-01.md" + episode.parent.mkdir(parents=True) + episode.write_text(_EPISODE_MD) + await tracker.sync_now() + if restart: + tracker = MemTraceTracker() + await tracker.on_memorize( + _payload(_message("later pending message", _TS_MS + 10)), + is_final=False, + defer_extraction=True, + result=None, + ) + foresights = tmp_path / "users/alice/.foresights/2026-01-01.md" + foresights.parent.mkdir(parents=True) + foresights.write_text( + "---\nuser_id: alice\n---\n" + + "\n".join( + f"\n" + "**owner_id**: alice\n**session_id**: sess_a\n" + "**parent_type**: memcell\n**parent_id**: mc_1\n" + f"### Foresight\nPrediction {index}.\n" + for index in range(5) + ) + ) + await tracker.sync_now() + data = _load_export(tracker, ("default", "default", "alice", "sess_a")) + nodes = _nodes_by_name(data) + assert len(nodes["mc_1"]) == 1 + assert json.loads(nodes["mc_1"][0]["value"])["sender_ids"] == ["alice", "assistant"] + assert len(_ops_by_name(data)["boundary_detection_mc_1"]) == 1 + counts = Counter( + (edge["source_full_node_id"], edge["target_full_node_id"]) + for edge in data["data"]["edges"] + ) + for message_id in message_ids: + assert counts[(message_id + "@1", "mc_1@1")] == 0 + _assert_recovered_boundary(data, "buffer-sess_a-alice@2", "mc_1") + assert counts[("buffer-sess_a-alice@3", "mc_1@1")] == 0 + assert counts[("buffer-sess_a-alice@2", "buffer-sess_a-alice@3")] == 1 + assert counts[("mc_1@1", "cell-input-mc_1@1")] == 1 + assert all( + counts[("cell-input-mc_1@1", f"alice_fs_{index}@1")] == 1 + and counts[("mc_1@1", f"alice_fs_{index}@1")] == 0 + for index in range(5) + ) + + +async def test_later_boundary_uses_the_buffer_after_the_next_add( + tracker: MemTraceTracker, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Two flush rounds attach different cells to the buffer each round consumed.""" + boundary = { + "mc_1": [f"m_sess_a_{_TS_MS}_000"], + "mc_2": [f"m_sess_a_{_TS_MS + 1}_000"], + } + + async def lookup(ids: list[str]) -> list[SimpleNamespace]: + return [ + SimpleNamespace( + app_id="default", + project_id="default", + message_ids_json=json.dumps(boundary[ids[0]]), + sender_ids_json='["alice"]', + ) + ] + + monkeypatch.setattr(memcell_repo, "find_by_ids", lookup) + episode = tmp_path / "users/alice/episodes/2026-01-01.md" + episode.parent.mkdir(parents=True) + await tracker.on_memorize( + _payload(_message("first", _TS_MS)), + is_final=False, + defer_extraction=True, + result=None, + ) + episode.write_text(_EPISODE_MD) + await tracker.sync_now() + await tracker.on_memorize( + _payload(_message("second", _TS_MS + 1)), + is_final=False, + defer_extraction=True, + result=None, + ) + episode.write_text(_TWO_MEMCELL_MD) + await tracker.sync_now() + data = _load_export(tracker, ("default", "default", "alice", "sess_a")) + edges = _edge_pairs(data) + _assert_recovered_boundary(data, "buffer-sess_a-alice@2", "mc_1") + _assert_recovered_boundary(data, "buffer-sess_a-alice@3", "mc_2") + assert ("buffer-sess_a-alice@3", "mc_1@1") not in edges + assert len(_ops_by_name(data)["boundary_detection_mc_1"]) == 1 + + +async def test_exact_memcell_boundary_is_not_downgraded_by_later_lookup_failure( + tracker: MemTraceTracker, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """An exact boundary upgrades the approximation once and survives read errors.""" + state = "missing" + + async def lookup(ids: list[str]) -> list[SimpleNamespace]: + if state == "missing": + return [] + if state == "failed": + raise RuntimeError("temporary read error") + return [ + SimpleNamespace( + app_id="default", + project_id="default", + message_ids_json=json.dumps([f"m_sess_a_{_TS_MS}_000"]), + sender_ids_json='["alice"]', + ) + ] + + monkeypatch.setattr(memcell_repo, "find_by_ids", lookup) + await tracker.on_memorize( + _payload(_message("first", _TS_MS)), + is_final=False, + defer_extraction=True, + result=None, + ) + episode = tmp_path / "users/alice/episodes/2026-01-01.md" + episode.parent.mkdir(parents=True) + episode.write_text(_EPISODE_MD) + await tracker.sync_now() + for index, next_state in enumerate(("exact", "failed"), 2): + state = next_state + episode.write_text( + _EPISODE_MD + + _EPISODE_MD.split("---\n", 2)[-1].replace("ep_1", f"ep_{index}") + ) + await tracker.sync_now() + data = _load_export(tracker, ("default", "default", "alice", "sess_a")) + nodes = _nodes_by_name(data) + assert len(nodes["mc_1"]) == 2 + assert nodes["mc_1"][-1]["metadata"]["membership"] == "exact" + assert len(_ops_by_name(data)["boundary_detection_mc_1"]) == 2 + + +async def test_memcell_membership_falls_back_with_approximate_flag( + tracker: MemTraceTracker, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Without a memcell row the session heuristic links unbound messages.""" + + async def no_rows(ids: list[str]) -> list[SimpleNamespace]: + return [] + + monkeypatch.setattr(memcell_repo, "find_by_ids", no_rows) + md_path = tmp_path / "users" / "alice" / "episodes" / "2026-01-01.md" + md_path.parent.mkdir(parents=True) + md_path.write_text(_EPISODE_MD, encoding="utf-8") + + payload = _payload(_message("first", _TS_MS), _message("second", _TS_MS + 1)) + await tracker.on_memorize( + payload, is_final=False, defer_extraction=False, result=None + ) + + nodes = _nodes_by_name( + _load_export(tracker, ("default", "default", "alice", "sess_a")) + ) + memcell = json.loads(nodes["mc_1"][0]["value"]) + assert memcell["message_ids"] == [ + f"m_sess_a_{_TS_MS}_000", + f"m_sess_a_{_TS_MS + 1}_001", + ] + assert nodes["mc_1"][0]["metadata"]["membership"] == "approximate" + + +async def test_restart_reconciles_downtime_deletion( + tracker: MemTraceTracker, tmp_path: Path +) -> None: + """A file deleted while the process was down gets a deletion version.""" + md_path = tmp_path / "users" / "alice" / "episodes" / "2026-01-01.md" + md_path.parent.mkdir(parents=True) + md_path.write_text(_EPISODE_MD, encoding="utf-8") + await tracker._sync_files() + + md_path.unlink() # Deleted during "downtime". + + restarted = MemTraceTracker() + await restarted._sync_files() + + nodes = _nodes_by_name( + _load_export(restarted, ("default", "default", "alice", "sess_a")) + ) + versions = sorted(nodes["alice_ep_1"], key=lambda node: node["version"]) + assert [node["version"] for node in versions] == [1, 2] + assert json.loads(versions[-1]["value"])["deleted"] is True + + +async def test_concurrent_search_requests_share_one_graph( + tracker: MemTraceTracker, tmp_path: Path +) -> None: + """Concurrent get-or-create for a fresh key must not lose updates.""" + await asyncio.gather( + tracker.on_search(_req(), _resp("ep_1"), request_id="r" * 31 + "1"), + tracker.on_search(_req(), _resp("ep_2"), request_id="r" * 31 + "2"), + ) + + nodes = _nodes_by_name(_load_export(tracker)) + query_ids = [name for name in nodes if name.startswith("query-alice-")] + assert len(query_ids) == 2 + data = _load_export(tracker) + assert _hit_node(data, "alice_ep_1") + assert _hit_node(data, "alice_ep_2") + + +async def test_entry_move_between_files_records_no_update( + tracker: MemTraceTracker, tmp_path: Path +) -> None: + """A pure cross-file move keeps the node version and updates the index.""" + first = tmp_path / "users" / "alice" / "episodes" / "2026-01-01.md" + second = tmp_path / "users" / "alice" / "episodes" / "2026-01-02.md" + first.parent.mkdir(parents=True) + first.write_text(_EPISODE_MD, encoding="utf-8") + await tracker._sync_files() + + first.unlink() + second.write_text(_EPISODE_MD, encoding="utf-8") + await tracker._sync_files() + + nodes = _nodes_by_name( + _load_export(tracker, ("default", "default", "alice", "sess_a")) + ) + assert [node["version"] for node in nodes["alice_ep_1"]] == [1] + scoped = ("default", "default", "alice_ep_1") + assert tracker._entry_file[scoped] == str(second.relative_to(tmp_path)) + + +async def test_later_hit_records_content_after_candidate_stub( + tracker: MemTraceTracker, +) -> None: + stages = [ + SearchStageRecord( + "sparse", "episode", (CandidateBrief("ep_9", 0.8, "keyword"),) + ) + ] + await tracker.on_search(_req(), _resp(), stages=stages, request_id="candidate") + await tracker.on_search(_req(), _resp("ep_9"), request_id="hit") + data = _load_export(tracker) + stub = _hit_node(data, "alice_ep_9", "query-alice-candidate") + hit = _hit_node(data, "alice_ep_9", "query-alice-hit") + assert json.loads(stub["value"])["source"] == "candidate_pool" + assert json.loads(hit["value"])["content"] == "body ep_9" + assert _fnid(stub) != _fnid(hit) + + +async def test_memorize_message_identity_matches_ingest_format( + tracker: MemTraceTracker, tmp_path: Path +) -> None: + """``/add`` messages carry the ingest ``m___`` id. + + Seconds / ISO-8601 inputs normalise onto the same millisecond identity; + a message without a usable timestamp gets a stable fallback identity + flagged ``timestamp_invalid`` instead of being dropped. + """ + payload = _payload( + _message("ms", _TS_MS), + _message("seconds", _TS_MS // 1000), + _message("iso", "2026-01-01T00:00:00+00:00"), + {"sender_id": "alice", "role": "user", "content": "kept"}, + ) + await tracker.on_memorize( + payload, is_final=False, defer_extraction=True, result=None + ) + + nodes = _nodes_by_name( + _load_export(tracker, ("default", "default", "alice", "sess_a")) + ) + base = f"m_sess_a_{_TS_MS}" + assert f"{base}_000" in nodes + assert f"{base}_001" in nodes + assert f"{base}_002" in nodes + fallback = json.loads(nodes["m_sess_a_invalid_003"][0]["value"]) + assert fallback["timestamp_invalid"] is True + assert fallback["raw_timestamp"] is None + assert fallback["content"] == "kept" + buffer = json.loads(nodes["buffer-sess_a-alice"][-1]["value"]) + assert buffer["message_ids"] == [ + f"{base}_000", + f"{base}_001", + f"{base}_002", + "m_sess_a_invalid_003", + ] + # Timestamps render as ISO strings that round-trip to the same instant. + value = json.loads(nodes[f"{base}_000"][0]["value"]) + moment = _dt.datetime.fromisoformat(value["timestamp"]) + assert int(moment.timestamp() * 1000) == _TS_MS + + +def _ops_by_name(data: dict) -> dict[str, list[dict]]: + by_name: dict[str, list[dict]] = {} + for op in data["data"]["operations"]: + by_name.setdefault(op["op_name"], []).append(op) + return by_name + + +async def test_flush_records_request_level_op( + tracker: MemTraceTracker, tmp_path: Path +) -> None: + """A flush gets its own ``memory_flush`` op wired to the session buffer.""" + payload = _payload(_message("first", _TS_MS)) + await tracker.on_memorize( + payload, is_final=False, defer_extraction=True, result=None + ) + result = SimpleNamespace(status="extracted", message_count=1) + await tracker.on_memorize( + _payload(), + is_final=True, + defer_extraction=False, + result=result, + request_id="req-flush", + ) + + data = _load_export(tracker, ("default", "default", "alice", "sess_a")) + flush_ops = _ops_by_name(data)["memory_flush_sess_a"] + assert len(flush_ops) == 1 + flush_op = flush_ops[0] + assert flush_op["category"] == "extraction" + metadata = flush_op["metadata"] + assert metadata["is_final"] is True + assert metadata["status"] == "extracted" + assert metadata["message_count"] == 1 + assert metadata["request_id"] == "req-flush" + assert metadata["event_seq"] >= 1 + assert "observed_at" in metadata + # A unique receipt marks completion when the real buffer state is unavailable. + edges = _edge_pairs(data) + assert any(source.startswith("buffer-sess_a-alice@") for source, _ in edges) + + +async def test_empty_flush_is_recorded_in_unknown_graph( + tracker: MemTraceTracker, tmp_path: Path +) -> None: + """A flush with no known buffer still leaves an input-less flush op.""" + result = SimpleNamespace(status="skipped", message_count=0) + await tracker.on_memorize( + _payload(), is_final=True, defer_extraction=False, result=result + ) + + data = _load_export(tracker, ("default", "default", "unknown", "sess_a")) + flush_op = _ops_by_name(data)["memory_flush_sess_a"][0] + assert flush_op["metadata"]["status"] == "skipped" + assert flush_op["metadata"]["message_count"] == 0 + + +async def test_on_memorize_error_records_error_op( + tracker: MemTraceTracker, tmp_path: Path +) -> None: + """A failed add leaves a ``status: error`` request-level op.""" + await tracker.on_memorize_error( + _payload(_message("x", _TS_MS)), + is_final=False, + defer_extraction=False, + error=ValueError("pipeline blew up"), + request_id="req-err", + ) + + data = _load_export(tracker, ("default", "default", "alice", "sess_a")) + error_op = _ops_by_name(data)["memory_add_sess_a"][0] + assert error_op["category"] == "initialization" + metadata = error_op["metadata"] + assert metadata["status"] == "error" + assert metadata["error_type"] == "ValueError" + assert metadata["error_message"] == "pipeline blew up" + assert metadata["request_id"] == "req-err" + assert metadata["is_final"] is False + + +async def test_on_memorize_error_flush_records_flush_op( + tracker: MemTraceTracker, tmp_path: Path +) -> None: + """A failed flush records a ``memory_flush`` error op, not an add op.""" + await tracker.on_memorize_error( + _payload(), + is_final=True, + defer_extraction=False, + error=RuntimeError("flush failed"), + ) + + data = _load_export(tracker, ("default", "default", "unknown", "sess_a")) + ops = _ops_by_name(data) + assert "memory_add_sess_a" not in ops + error_op = ops["memory_flush_sess_a"][0] + assert error_op["category"] == "extraction" + assert error_op["metadata"]["status"] == "error" + assert error_op["metadata"]["error_type"] == "RuntimeError" + + +async def test_on_search_error_records_query_pools_and_error_op( + tracker: MemTraceTracker, tmp_path: Path +) -> None: + """A failed search keeps the query node and the partial stage pools.""" + await tracker.on_search_error( + _req(), + stages=_stages(), + error=RuntimeError("search blew up"), + request_id="req-search-err", + ) + + data = _load_export(tracker) + nodes = _nodes_by_name(data) + query_id = "query-alice-req-search-err" + query = json.loads(nodes[query_id][0]["value"]) + assert query["request_id"] == "req-search-err" + assert nodes[query_id][0]["metadata"]["request_id"] == "req-search-err" + # The pools collected before the failure are recorded and chained. + assert f"candidates_episode_sparse-{query_id}" in nodes + query_fnid = _fnid(nodes[query_id][0]) + sparse_fnid = _fnid(nodes[f"candidates_episode_sparse-{query_id}"][0]) + assert (query_fnid, sparse_fnid) in _edge_pairs(data) + + error_op = _ops_by_name(data)["memory_search_0001"][0] + assert error_op["category"] == "retrieval" + metadata = error_op["metadata"] + assert metadata["status"] == "error" + assert metadata["error_type"] == "RuntimeError" + assert metadata["error_message"] == "search blew up" + assert metadata["request_id"] == "req-search-err" + + +async def test_stage_pool_records_truncation_metadata( + tracker: MemTraceTracker, tmp_path: Path +) -> None: + """A capped pool carries its pre-truncation size and the truncated flag.""" + stages = [ + SearchStageRecord( + phase="sparse", + kind="episode", + candidates=(CandidateBrief(id="ep_1", score=0.8, source="keyword"),), + total_count=120, + ) + ] + await tracker.on_search(_req(), _resp(), stages=stages, request_id="req-trunc") + + nodes = _nodes_by_name(_load_export(tracker)) + pool = nodes["candidates_episode_sparse-query-alice-req-trunc"][0] + assert pool["metadata"]["total_count"] == 120 + assert pool["metadata"]["truncated"] is True + value = json.loads(pool["value"]) + assert value["total_count"] == 120 + assert value["count"] == 1 + + +async def test_query_identity_uses_request_id_with_collision_suffix( + tracker: MemTraceTracker, tmp_path: Path +) -> None: + """Same request id twice: the second query gets a sequence suffix.""" + await tracker.on_search(_req(), _resp("ep_1"), request_id="req-1") + await tracker.on_search(_req(), _resp("ep_1"), request_id="req-1") + + nodes = _nodes_by_name(_load_export(tracker)) + assert "query-alice-req-1" in nodes + assert "query-alice-req-1-0002" in nodes + + +async def test_memcell_membership_marks_lookup_failed( + tracker: MemTraceTracker, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """A failing SQLite read is marked ``lookup_failed``, not ``approximate``.""" + + async def raising_find_by_ids(ids: list[str]) -> list[SimpleNamespace]: + raise RuntimeError("db down") + + monkeypatch.setattr(memcell_repo, "find_by_ids", raising_find_by_ids) + md_path = tmp_path / "users" / "alice" / "episodes" / "2026-01-01.md" + md_path.parent.mkdir(parents=True) + md_path.write_text(_EPISODE_MD, encoding="utf-8") + + payload = _payload(_message("first", _TS_MS)) + await tracker.on_memorize( + payload, is_final=False, defer_extraction=False, result=None + ) + + nodes = _nodes_by_name( + _load_export(tracker, ("default", "default", "alice", "sess_a")) + ) + metadata = nodes["mc_1"][0]["metadata"] + assert metadata["membership"] == "lookup_failed" + assert metadata["membership_detail"] == "lookup_failed" + # The heuristic still linked the session's unbound messages. + memcell = json.loads(nodes["mc_1"][0]["value"]) + assert memcell["message_ids"] == [f"m_sess_a_{_TS_MS}_000"] + + +async def test_memcell_membership_marks_invalid_payload( + tracker: MemTraceTracker, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """An unparsable memcell row falls back with ``invalid_payload`` detail.""" + + async def fake_find_by_ids(ids: list[str]) -> list[SimpleNamespace]: + return [ + SimpleNamespace( + app_id="default", project_id="default", message_ids_json="not-json" + ) + ] + + monkeypatch.setattr(memcell_repo, "find_by_ids", fake_find_by_ids) + md_path = tmp_path / "users" / "alice" / "episodes" / "2026-01-01.md" + md_path.parent.mkdir(parents=True) + md_path.write_text(_EPISODE_MD, encoding="utf-8") + + payload = _payload(_message("first", _TS_MS)) + await tracker.on_memorize( + payload, is_final=False, defer_extraction=False, result=None + ) + + nodes = _nodes_by_name( + _load_export(tracker, ("default", "default", "alice", "sess_a")) + ) + metadata = nodes["mc_1"][0]["metadata"] + assert metadata["membership"] == "approximate" + assert metadata["membership_detail"] == "invalid_payload" + + +async def test_graph_export_carries_digest_graph_id( + tracker: MemTraceTracker, tmp_path: Path +) -> None: + """``graph_id`` carries the same ``{safe}-{digest}`` fragments as the file.""" + await tracker.on_search(_req(user_id="a@b"), _resp("ep_1")) + data = _load_export(tracker, ("default", "default", "a@b", "global")) + # Every one of the four key-component fragments ends in an 8-char digest. + assert re.search(r"^everos-filetrace-(?:.+-[0-9a-f]{8}){4}$", data["graph_id"]) + assert "-7505d64a-" in data["graph_id"] # sha1("default")[:8] + + +async def test_sync_now_flushes_dirty_graphs( + tracker: MemTraceTracker, tmp_path: Path +) -> None: + """Shutdown sync diffs the tree and exports with ``trigger: shutdown``.""" + md_path = tmp_path / "users" / "alice" / "episodes" / "2026-01-01.md" + md_path.parent.mkdir(parents=True) + md_path.write_text(_EPISODE_MD, encoding="utf-8") + + await tracker.sync_now() + + data = _load_export(tracker, ("default", "default", "alice", "sess_a")) + assert "alice_ep_1" in _nodes_by_name(data) + extraction_op = _ops_by_name(data)["episode_extraction_ep_1"][0] + metadata = extraction_op["metadata"] + assert metadata["source"] == "file_diff" + assert metadata["trigger"] == "shutdown" + assert metadata["event_seq"] >= 1 + assert "observed_at" in metadata + + +async def test_stage_pools_are_explicit_retrieval_ops( + tracker: MemTraceTracker, tmp_path: Path +) -> None: + """Every stage pool is produced by its own retrieval op (native style).""" + await tracker.on_search( + _req(), _resp("ep_1"), stages=_stages(), request_id="req-ops" + ) + data = _load_export(tracker) + nodes = _nodes_by_name(data) + query_id = next(name for name in nodes if name.startswith("query-alice-")) + + ops = {op["op_name"]: op for op in data["data"]["operations"]} + edges_by_op: dict[str, set[tuple[str, str]]] = {} + for edge in data["data"]["edges"]: + edges_by_op.setdefault(edge["op_id"], set()).add( + (edge["source_full_node_id"], edge["target_full_node_id"]) + ) + + query_fnid = _fnid(nodes[query_id][0]) + sparse_fnid = _fnid(nodes[f"candidates_episode_sparse-{query_id}"][0]) + dense_fnid = _fnid(nodes[f"candidates_episode_dense-{query_id}"][0]) + fusion_fnid = _fnid(nodes[f"candidates_episode_fusion-{query_id}"][0]) + expected = { + "episode_sparse_0001": ( + {(query_fnid, sparse_fnid)}, + {"phase": "sparse", "kind": "episode"}, + ), + "episode_dense_0001": ( + {(query_fnid, dense_fnid)}, + {"phase": "dense", "kind": "episode"}, + ), + "episode_fusion_0001": ( + {(sparse_fnid, fusion_fnid), (dense_fnid, fusion_fnid)}, + {"phase": "fusion", "kind": "episode"}, + ), + } + for op_name, (edge_pairs, metadata) in expected.items(): + op = ops[op_name] + assert op["category"] == "retrieval" + assert edges_by_op[op["op_id"]] == edge_pairs + for key, value in metadata.items(): + assert op["metadata"][key] == value + assert op["metadata"]["event_seq"] >= 1 + assert op["metadata"]["request_id"] == "req-ops" + + +async def test_stage_pool_class_names_follow_native_vocabulary( + tracker: MemTraceTracker, tmp_path: Path +) -> None: + """Pool nodes keep ``memory_context`` but carry a native-style class.""" + await tracker.on_search(_req(), _resp("ep_1"), stages=_stages()) + nodes = _nodes_by_name(_load_export(tracker)) + query_id = next(name for name in nodes if name.startswith("query-alice-")) + expected = { + "sparse": "sparse_retrieval_results", + "dense": "dense_retrieval_results", + "fusion": "hybrid_retrieval_results", + } + for phase, class_name in expected.items(): + pool = nodes[f"candidates_episode_{phase}-{query_id}"][0] + assert pool["category"] == "memory_context" + assert pool["class_name"] == class_name + + +async def test_on_answer_and_evaluation_record_qa_chain( + tracker: MemTraceTracker, tmp_path: Path +) -> None: + """The QA hooks append the native prediction / evaluation chain.""" + await tracker.on_search( + _req(), _resp("ep_1"), stages=_stages(), request_id="req-qa" + ) + await tracker.on_answer( + app_id="default", + project_id="default", + owner="alice", + request_id="req-qa", + answer="She went camping in July.", + prompt="answer prompt text", + ) + await tracker.on_evaluation( + app_id="default", + project_id="default", + owner="alice", + request_id="req-qa", + golden_answers=["July"], + judge_response="VERDICT: 1 correct", + judge_score=1.0, + ) + + data = _load_export(tracker) + nodes = _nodes_by_name(data) + query_id = "query-alice-req-qa" + prompt_node = nodes[f"prompt-{query_id}"][0] + assert prompt_node["category"] == "prompt" + assert json.loads(prompt_node["value"])["prompt"] == "answer prompt text" + prediction = nodes[f"prediction-{query_id}"][0] + assert prediction["category"] == "llm_response" + assert prediction["class_name"] == "prediction" + assert json.loads(prediction["value"])["answer"] == "She went camping in July." + golden = nodes[f"golden-{query_id}"][0] + assert golden["category"] == "golden_answers" + assert golden["class_name"] == "golden_answers" + assert json.loads(golden["value"])["answers"] == ["July"] + judge = nodes[f"judge-{query_id}"][0] + assert judge["class_name"] == "judge_response" + assert json.loads(judge["value"])["score"] == 1.0 + + edges = _edge_pairs(data) + query_fnid = _fnid(nodes[query_id][0]) + context_fnid = _fnid(nodes[f"context-{query_id}"][0]) + prompt_fnid = _fnid(prompt_node) + prediction_fnid = _fnid(prediction) + golden_fnid = _fnid(golden) + judge_fnid = _fnid(judge) + assert (query_fnid, prediction_fnid) in edges + answer_context_fnid = _fnid(nodes[f"answer-context-{query_id}"][0]) + assert (context_fnid, answer_context_fnid) in edges + assert (answer_context_fnid, prediction_fnid) in edges + assert (context_fnid, prediction_fnid) not in edges + assert (prompt_fnid, prediction_fnid) in edges + assert (query_fnid, golden_fnid) in edges + assert (prediction_fnid, judge_fnid) in edges + assert (golden_fnid, judge_fnid) in edges + + ops = {op["op_name"]: op for op in data["data"]["operations"]} + assert ops[f"answer_generation_{query_id}"]["category"] == "response" + assert ops[f"inject_golden_answers_{query_id}"]["category"] == "evaluation" + assert ops[f"judge_answer_{query_id}"]["category"] == "evaluation" + + +async def test_qa_hooks_fail_safe_on_unknown_request( + tracker: MemTraceTracker, tmp_path: Path +) -> None: + """A QA record for an unrecorded search is a logged no-op, not an error.""" + await tracker.on_answer( + app_id="default", + project_id="default", + owner="alice", + request_id="req-missing", + answer="x", + ) + await tracker.on_evaluation( + app_id="default", + project_id="default", + owner="alice", + request_id="req-missing", + golden_answers=["y"], + ) + assert not tracker._graph_path(("default", "default", "alice", "global")).exists() + + +async def test_qa_hooks_resolve_collision_suffixed_query( + tracker: MemTraceTracker, tmp_path: Path +) -> None: + """A repeated request id resolves to the base query node deterministically.""" + await tracker.on_search(_req(), _resp("ep_1"), request_id="req-dup") + await tracker.on_search(_req(), _resp("ep_1"), request_id="req-dup") + await tracker.on_answer( + app_id="default", + project_id="default", + owner="alice", + request_id="req-dup", + answer="a", + ) + nodes = _nodes_by_name(_load_export(tracker)) + assert "query-alice-req-dup" in nodes + assert "query-alice-req-dup-0002" in nodes + assert "prediction-query-alice-req-dup" not in nodes + await tracker.on_answer( + app_id="default", + project_id="default", + owner="alice", + request_id="req-dup", + answer="a", + query_full_node_id="query:query-alice-req-dup-0002@1", + ) + nodes = _nodes_by_name(_load_export(tracker)) + assert "prediction-query-alice-req-dup-0002" in nodes diff --git a/tests/unit/test_infra/test_sqlite/test_stores.py b/tests/unit/test_infra/test_sqlite/test_stores.py index 8a701adfd..958d3d527 100644 --- a/tests/unit/test_infra/test_sqlite/test_stores.py +++ b/tests/unit/test_infra/test_sqlite/test_stores.py @@ -186,6 +186,15 @@ def _record(memcell_id: str, *messages: CanonicalMessage) -> MemcellRecord: ) +async def test_buffer_rows_of_one_timestamp_come_back_in_write_order( + stores: _Stores, +) -> None: + """Ids carry no order, so a tie must not fall back to the id's spelling.""" + call, result = _message("m_z", 1), _message("m_a", 1) + await stores.buffer.keep(_SESSION, [call, result], last_message_ts=call.timestamp) + assert [m.message_id for m in await stores.buffer.list(_SESSION)] == ["m_z", "m_a"] + + async def test_keep_buffers_messages_and_stamps_the_last_message( stores: _Stores, ) -> None: @@ -218,6 +227,23 @@ async def test_cut_records_the_cells_and_buffers_only_the_tail( assert status[1] is not None +async def test_already_cut_names_what_this_sessions_memcells_hold( + stores: _Stores, +) -> None: + m1, m2, m3 = _message("m1", 1), _message("m2", 2), _message("m3", 3) + other = SessionKey(app_id="app", project_id="proj", session_id="s2") + await stores.buffer.cut( + _SESSION, [_record("mc_1", m1, m2)], tail=[m3], last_memcell_ts=m2.timestamp + ) + await stores.buffer.cut( + other, [_record("mc_2", m3)], tail=[], last_memcell_ts=m3.timestamp + ) + + assert await stores.buffer.already_cut(_SESSION, ["m1", "m3", "m9"]) == {"m1"} + assert await stores.buffer.already_cut(other, ["m1", "m3"]) == {"m3"} + assert await stores.buffer.already_cut(_SESSION, []) == set() + + async def test_keep_leaves_the_last_memcell_stamp_alone(stores: _Stores) -> None: m1, m2 = _message("m1", 1), _message("m2", 2) await stores.buffer.keep(_SESSION, [m1], last_message_ts=m1.timestamp) diff --git a/tests/unit/test_memory/test_delete_model_replays.py b/tests/unit/test_memory/test_delete_model_replays.py index 3dd02dd4c..78e3bbfb9 100644 --- a/tests/unit/test_memory/test_delete_model_replays.py +++ b/tests/unit/test_memory/test_delete_model_replays.py @@ -207,6 +207,7 @@ async def _merge_once( episode_index=indexes.episode, memcell_store=stores.memcell, report_store=stores.reflection_report, + profile_store=stores.profile, reflector=reflector, ) return await orchestrator.run(scope=_USER) diff --git a/tests/unit/test_memory/test_extract/test_boundary/test_messages.py b/tests/unit/test_memory/test_extract/test_boundary/test_messages.py index 31e71c069..fa8058a7b 100644 --- a/tests/unit/test_memory/test_extract/test_boundary/test_messages.py +++ b/tests/unit/test_memory/test_extract/test_boundary/test_messages.py @@ -88,12 +88,15 @@ def test_merge_dedupe_sort_dedupes_by_message_id() -> None: assert m1.text == "hi" # original, not "overwritten?" -def test_merge_sorts_by_timestamp_then_id() -> None: - a = _msg("m_b", "user", ts_seconds=100) - b = _msg("m_a", "user", ts_seconds=100) - c = _msg("m_c", "user", ts_seconds=50) - merged = merge_dedupe_sort([], [a, b, c]) - assert [m.message_id for m in merged] == ["m_c", "m_a", "m_b"] +def test_merge_sorts_by_timestamp_and_keeps_arrival_order_on_a_tie() -> None: + """Ids carry no order (#274): a tie keeps the order rows arrived in, so a + tool result whose id happens to sort first still follows its call.""" + call = _msg("m_z", "assistant", ts_seconds=100) + result = _msg("m_a", "tool", ts_seconds=100) + earlier = _msg("m_c", "user", ts_seconds=50) + held = _msg("m_y", "user", ts_seconds=100) + merged = merge_dedupe_sort([held], [call, result, earlier]) + assert [m.message_id for m in merged] == ["m_c", "m_y", "m_z", "m_a"] # ── apply_cuts ─────────────────────────────────────────────────────────── diff --git a/tests/unit/test_memory/test_extract/test_boundary/test_quarantine.py b/tests/unit/test_memory/test_extract/test_boundary/test_quarantine.py index c2a7af088..4fd666443 100644 --- a/tests/unit/test_memory/test_extract/test_boundary/test_quarantine.py +++ b/tests/unit/test_memory/test_extract/test_boundary/test_quarantine.py @@ -43,6 +43,7 @@ ) from everos.memory.extract.boundary import BoundaryDetection, BoundaryOutcome from everos.memory.extract.boundary.quarantine import POISON_CALLS +from everos.memory.extract.ingest import message_ids from everos.memory.extract.ingest import service as ingest from everos.memory.extract.llm_retry import OUTPUT_ATTEMPTS from tests.fakes import ( @@ -119,17 +120,8 @@ async def add( async def add_orphan_tool_row(self, session: str, start: int) -> BoundaryOutcome: """An agent-mode add whose tool row answers no tool call.""" - payload = _payload(session, start) - payload["messages"].append( - { - "content": "tool output", - "timestamp": BASE_TS + start, - "sender_id": "tool", - "role": "tool", - } - ) ingested = await ingest.process( - payload, + _orphan_payload(session, start), multimodal_llm=None, raw_file_builder=unused_raw_file_builder, sender_names=InMemorySenderNameStore(), @@ -145,6 +137,24 @@ async def tracks(self, session: str) -> dict[str, list[str]]: } +def _orphan_payload(session: str, start: int) -> dict[str, Any]: + payload = _payload(session, start) + payload["messages"].append( + { + "content": "tool output", + "timestamp": BASE_TS + start, + "sender_id": "tool", + "role": "tool", + } + ) + return payload + + +def _ids(*payloads: dict[str, Any]) -> list[str]: + """The message ids ingest gives these payloads' messages.""" + return [i for p in payloads for i in message_ids(p["session_id"], p["messages"])] + + def _payload(session: str, start: int) -> dict[str, Any]: return { "session_id": session, @@ -175,15 +185,14 @@ async def test_third_consecutive_unusable_call_quarantines_the_buffer() -> None: assert tracks["memorize"] == [], "the session starts over" # The buffered poison and the quarantining call's own message are # kept; the two earlier calls' messages were never persisted. - assert sorted(tracks["quarantine"]) == [ - "m_s1_1700000000001_000", - "m_s1_1700000000004_000", - ] + assert sorted(tracks["quarantine"]) == sorted( + _ids(_payload("s1", 1), _payload("s1", 4)) + ) assert stage.llm.call_count == OUTPUT_ATTEMPTS * POISON_CALLS # The session goes on: a healthy flush cuts a cell from an empty buffer. outcome = await stage.add("s1", 5, final=True) assert outcome.status == "extracted" - assert outcome.per_cell_message_ids == [["m_s1_1700000000005_000"]] + assert outcome.per_cell_message_ids == [_ids(_payload("s1", 5))] assert (await stage.tracks("s1"))["memorize"] == [] assert len((await stage.tracks("s1"))["quarantine"]) == 2 @@ -235,7 +244,5 @@ async def test_an_orphan_tool_row_counts_without_reaching_the_model() -> None: assert stage.llm.call_count == 0, "never retried, never sent" tracks = await stage.tracks("s1") assert tracks["memorize"] == [] - assert sorted(tracks["quarantine"]) == [ - "m_s1_1700000000003_000", - "m_s1_1700000000003_001", - ] + # One timestamp, two different rows: two ids. + assert sorted(tracks["quarantine"]) == sorted(_ids(_orphan_payload("s1", 3))) diff --git a/tests/unit/test_memory/test_extract/test_ingest/test_id_gen.py b/tests/unit/test_memory/test_extract/test_ingest/test_id_gen.py new file mode 100644 index 000000000..e95c09833 --- /dev/null +++ b/tests/unit/test_memory/test_extract/test_ingest/test_id_gen.py @@ -0,0 +1,42 @@ +"""``message_ids``: what a resend keeps, what two messages never share.""" + +from __future__ import annotations + +from typing import Any + +from everos.memory.extract.ingest import message_ids + +_TS = 1_700_000_000_000 + + +def _m(text: str, ts: int = _TS, sender: str = "u1") -> dict[str, Any]: + return {"sender_id": sender, "role": "user", "timestamp": ts, "content": text} + + +def test_a_message_keeps_its_id_wherever_it_sits_in_the_request() -> None: + a, b = _m("a", _TS), _m("b", _TS + 1) + assert message_ids("s", [a, b])[1] == message_ids("s", [b])[0] + + +def test_one_millisecond_resent_in_parts_keeps_its_ids() -> None: + """[A, B] in one millisecond, then B alone: B is the same message.""" + a, b = _m("a"), _m("b") + first = message_ids("s", [a, b]) + assert message_ids("s", [b]) == [first[1]] + assert message_ids("s", [b, a]) == [first[1], first[0]] + + +def test_different_messages_in_one_millisecond_never_share_an_id() -> None: + assert message_ids("s", [_m("a")]) != message_ids("s", [_m("b")]) + assert message_ids("s", [_m("a")]) != message_ids("s", [_m("a", sender="u2")]) + + +def test_a_message_repeated_verbatim_in_one_request_is_kept_twice() -> None: + ids = message_ids("s", [_m("ok"), _m("ok")]) + assert len(set(ids)) == 2 + assert ids[0] == message_ids("s", [_m("ok")])[0] + + +def test_the_label_is_not_part_of_the_identity() -> None: + named = _m("a") | {"sender_name": "Alice"} + assert message_ids("s", [named]) == message_ids("s", [_m("a")]) diff --git a/tests/unit/test_memory/test_extract/test_language.py b/tests/unit/test_memory/test_extract/test_language.py new file mode 100644 index 000000000..e4378ddee --- /dev/null +++ b/tests/unit/test_memory/test_extract/test_language.py @@ -0,0 +1,126 @@ +"""``decide_output_language``: one detector call per memcell, never raising. + +The detector is everalgo's real ``LanguageDetector``; the model answers from +canned replies. What it names is returned as is (its "Other" comes back as +English), a cell without chat text costs no call, and a failed call -- an +error or an unusable reply -- gives ``None`` so the episode is written as +before. Every outcome logs one line naming the memcell. +""" + +from __future__ import annotations + +from typing import Any + +import pytest +import structlog +from everalgo.testing import FakeLLMClient +from everalgo.types import ChatMessage, MemCell +from everalgo.user_memory import LanguageDetector, OutputLanguage + +from everos.memory.extract.language import decide_output_language +from tests.fakes import UNUSABLE_REPLY + + +def _cell(*contents: str) -> MemCell: + return MemCell( + items=[ + ChatMessage( + id=f"m{index}", + role="user", + content=content, + timestamp=1_700_000_000_000, + sender_id="u1", + ) + for index, content in enumerate(contents) + ], + timestamp=1_700_000_000_000, + ) + + +def _answering(reply: str) -> FakeLLMClient: + return FakeLLMClient(handler=lambda *_args, **_kwargs: reply) + + +async def _decide(llm: FakeLLMClient, cell: MemCell) -> OutputLanguage | None: + return await decide_output_language( + LanguageDetector(llm=llm), cell, memcell_id="mc_a" + ) + + +@pytest.mark.parametrize( + ("label", "expected"), + [ + ("Chinese", OutputLanguage.CHINESE), + ("Japanese", OutputLanguage.JAPANESE), + ("English", OutputLanguage.ENGLISH), + ("Other", OutputLanguage.ENGLISH), + ], +) +async def test_the_named_language_is_returned_and_logged( + label: str, expected: OutputLanguage +) -> None: + llm = _answering(f'{{"language": "{label}"}}') + + with structlog.testing.capture_logs() as logs: + language = await _decide(llm, _cell("帮我订明天去杭州的票")) + + assert language is expected + assert llm.call_count == 1 + assert _lines(logs) == [ + { + "event": "episode_language_decided", + "log_level": "info", + "memcell_id": "mc_a", + "language": expected.value, + } + ] + + +async def test_a_cell_without_chat_text_costs_no_call() -> None: + llm = _answering('{"language": "Chinese"}') + + with structlog.testing.capture_logs() as logs: + language = await _decide(llm, _cell(" ")) + + assert language is None + assert llm.call_count == 0 + assert _lines(logs) == [ + { + "event": "episode_language_undecided", + "log_level": "info", + "memcell_id": "mc_a", + "reason": "no_chat", + } + ] + + +@pytest.mark.parametrize( + ("llm", "error_type"), + [ + (_answering(UNUSABLE_REPLY), "LLMOutputError"), + (_answering('{"language": "French"}'), "LLMOutputError"), + (FakeLLMClient(responses=[TimeoutError("deadline")]), "TimeoutError"), + ], + ids=["unusable reply", "label outside the set", "client error"], +) +async def test_a_failed_call_degrades_to_none( + llm: FakeLLMClient, error_type: str +) -> None: + """Undecided is how every episode was written before the call existed.""" + with structlog.testing.capture_logs() as logs: + language = await _decide(llm, _cell("hello there")) + + assert language is None + (line,) = _lines(logs) + assert {k: line[k] for k in ("event", "log_level", "memcell_id", "reason")} == { + "event": "episode_language_undecided", + "log_level": "warning", + "memcell_id": "mc_a", + "reason": "failed", + } + assert line["error_type"] == error_type + + +def _lines(logs: list[dict[str, Any]]) -> list[dict[str, Any]]: + """This module's lines; everalgo logs through the stdlib, not structlog.""" + return [line for line in logs if line["event"].startswith("episode_language")] diff --git a/tests/unit/test_memory/test_extract/test_pipeline/test_user_memory_emits.py b/tests/unit/test_memory/test_extract/test_pipeline/test_user_memory_emits.py index 21d4b0ce9..3651f6bd5 100644 --- a/tests/unit/test_memory/test_extract/test_pipeline/test_user_memory_emits.py +++ b/tests/unit/test_memory/test_extract/test_pipeline/test_user_memory_emits.py @@ -1,9 +1,10 @@ """``UserMemoryPipeline.run_cell``: one episode per cell, one copy per user sender. The episode operator is real (everalgo ``EpisodeExtractor``); the model answers -from the user-track canned scripts. A cell costs one model call: every copy is -written with the placeholder summary, and one ``EpisodeExtracted`` lists the -copies written. +from the user-track canned scripts. A cell costs two model calls: the language +decision, then the episode written in that language. Every copy is written with +the placeholder summary and the decided language (else the one read off the +episode text), and one ``EpisodeExtracted`` lists the copies written. """ from __future__ import annotations @@ -13,6 +14,7 @@ from unittest.mock import AsyncMock, MagicMock import pytest +import structlog from everalgo.llm import LLMOutputError from everalgo.testing import FakeLLMClient from everalgo.types import ChatMessage, MemCell @@ -22,6 +24,7 @@ from everos.memory.events import EpisodeCopy, EpisodeExtracted from everos.memory.extract.llm_retry import OUTPUT_ATTEMPTS from everos.memory.extract.pipeline import PreparedCell, UserMemoryPipeline +from everos.memory.extract.trace import collect_construction_trace from everos.memory.ports import MemoryRef from tests.fakes import ( bundled_instructions, @@ -74,6 +77,7 @@ def _pipeline( episode_store=episode_store, # type: ignore[arg-type] # recording double memcell_store=memcells, instructions=bundled_instructions(), + language_llm=llm, # type: ignore[arg-type] # FakeLLMClient episode_llm=llm, # type: ignore[arg-type] # FakeLLMClient ) @@ -105,10 +109,18 @@ async def test_emit_episode_extracted_after_md_write() -> None: episode_store = MagicMock() episode_store.append = AsyncMock(return_value=_REF) - outcome = await _pipeline(user_track_llm(), episode_store).run_cell( - _INGESTED, _prepared("u1") - ) + with collect_construction_trace() as events: + outcome = await _pipeline(user_track_llm(), episode_store).run_cell( + _INGESTED, _prepared("u1") + ) + assert [event["phase"] for event in events] == [ + "extraction_attempt", + "extraction_result", + "persisted_episode", + ] + assert events[1]["content"] == _EPISODE["content"] + assert events[2]["entry_id"] == _REF.entry_id assert outcome.md_paths == [_REF.md_path] (extracted,) = outcome.events assert isinstance(extracted, EpisodeExtracted) @@ -139,6 +151,33 @@ async def test_every_copy_is_written_with_the_placeholder_summary() -> None: assert [s.item.episode for s in episodes.records] == [_EPISODE["content"]] * 2 +async def test_the_decided_language_writes_the_episode_and_is_pinned() -> None: + """The episode is asked for in the decided language, and every copy and the + event carry it -- even over the language its text reads as.""" + llm = memorize_llm( + episode_content="The user booked a trip to Lisbon.", language="language_chinese" + ) + episode_store = _recording_store() + + with structlog.testing.capture_logs() as logs: + outcome = await _pipeline(llm, episode_store).run_cell( + _INGESTED, _prepared("u1", "u2") + ) + + (episode_call,) = _calls_for(llm, "_EpisodeReply") + assert f"Write every output field in Chinese{_NAMED}" in str(episode_call.messages) + (event,) = outcome.events + written = [call.args[1] for call in episode_store.append.await_args_list] + assert event.language == "Chinese" + assert [ep.language for ep in written] == ["Chinese", "Chinese"] + assert _written_log(logs) == { + "memcell_id": "mc_a", + "owners": 2, + "language": "Chinese", + "language_from": "decided", + } + + @pytest.mark.parametrize( ("content", "language"), [ @@ -147,25 +186,44 @@ async def test_every_copy_is_written_with_the_placeholder_summary() -> None: ("2026-05-17 12:00", None), ], ) -async def test_episode_and_event_carry_the_detected_language( +async def test_an_undecided_language_is_read_off_the_episode_text( content: str, language: str | None ) -> None: - """The episode's language is detected once and pinned on every copy.""" - episode_store = MagicMock() - episode_store.append = AsyncMock(return_value=_REF) - - outcome = await _pipeline( - memorize_llm(episode_content=content), episode_store - ).run_cell(_INGESTED, _prepared("u1", "u2")) + """A failed decision leaves the language to the model; what it wrote in is + detected once and pinned on every copy.""" + llm = memorize_llm(episode_content=content, language="language_unusable") + episode_store = _recording_store() + + with structlog.testing.capture_logs() as logs: + outcome = await _pipeline(llm, episode_store).run_cell( + _INGESTED, _prepared("u1", "u2") + ) - (event,) = [e for e in outcome.events if isinstance(e, EpisodeExtracted)] + (episode_call,) = _calls_for(llm, "_EpisodeReply") + assert _NAMED not in str(episode_call.messages) + (event,) = outcome.events written = [call.args[1] for call in episode_store.append.await_args_list] assert event.language == language assert [ep.language for ep in written] == [language, language] + assert _written_log(logs)["language_from"] == "text" + + +_NAMED = ", whatever language the input is in" +"""How everalgo's rule for a caller-named language continues past the name.""" -async def test_one_call_one_event_lists_every_user_sender() -> None: - """One model call per cell and one event naming each copy's own entry id.""" +def _calls_for(llm: FakeLLMClient, reply: str) -> list[object]: + return [call for call in llm.calls if call.response_format.__name__ == reply] + + +def _written_log(logs: list[dict[str, object]]) -> dict[str, object]: + (line,) = [entry for entry in logs if entry["event"] == "episode_written"] + return {k: line[k] for k in ("memcell_id", "owners", "language", "language_from")} + + +async def test_two_calls_one_event_lists_every_user_sender() -> None: + """The language decision, then one episode call per cell, and one event + naming each copy's own entry id.""" llm = user_track_llm() episodes = InMemoryEpisodeStore() @@ -177,7 +235,7 @@ async def test_one_call_one_event_lists_every_user_sender() -> None: ] assert [c.owner_id for c in event.copies] == ["u1", "u2"] assert outcome.md_paths == [s.ref.md_path for s in episodes.records] - assert _requested(llm) == ["_EpisodeReply"] + assert _requested(llm) == ["_LanguageReply", "_EpisodeReply"] async def test_a_copy_whose_write_was_skipped_is_not_listed() -> None: @@ -194,7 +252,10 @@ async def test_a_copy_whose_write_was_skipped_is_not_listed() -> None: async def test_a_blank_episode_is_tried_again_then_fails_the_cell() -> None: - """A blank reply is unusable: retried, then the cell fails, nothing written.""" + """A blank reply is unusable: retried, then the cell fails, nothing written. + + The language is decided once, before the attempts, not once per attempt. + """ llm = user_track_llm(episode="episode_blank") episode_store = MagicMock() episode_store.append = AsyncMock(return_value=_REF) @@ -202,6 +263,7 @@ async def test_a_blank_episode_is_tried_again_then_fails_the_cell() -> None: with pytest.raises(LLMOutputError): await _pipeline(llm, episode_store).run_cell(_INGESTED, _prepared("u1")) + assert _requested(llm).count("_LanguageReply") == 1 assert _requested(llm).count("_EpisodeReply") == OUTPUT_ATTEMPTS episode_store.append.assert_not_awaited() @@ -212,8 +274,9 @@ def _requested(llm: FakeLLMClient) -> list[str]: async def test_run_emits_extract_and_persist_spans() -> None: - """run_cell opens an everos.extract generation span (where LLM token - usage lands) and an everos.persist.markdown span around the md write.""" + """run_cell opens generation spans for the language decision and the + episode (where LLM token usage lands) and an everos.persist.markdown span + around the md write.""" from opentelemetry.sdk.trace.export import SimpleSpanProcessor from opentelemetry.sdk.trace.export.in_memory_span_exporter import ( InMemorySpanExporter, @@ -235,11 +298,9 @@ async def test_run_emits_extract_and_persist_spans() -> None: await _pipeline(user_track_llm()).run_cell(_INGESTED, _prepared("u1")) force_flush() spans = {s.name: s for s in exporter.get_finished_spans()} - assert "everos.extract" in spans assert "everos.persist.markdown" in spans - assert spans["everos.extract"].attributes["langfuse.observation.type"] == ( - "generation" - ) + for name in ("everos.extract.language", "everos.extract"): + assert spans[name].attributes["langfuse.observation.type"] == ("generation") finally: shutdown_tracing() @@ -318,6 +379,7 @@ async def test_the_episode_request_shows_times_in_the_configured_zone() -> None: episode_store=_recording_store(), memcell_store=_alive_memcells(), instructions=bundled_instructions(), + language_llm=user_track_llm(), episode_llm=llm, tz=timezone(timedelta(hours=8)), ) diff --git a/tests/unit/test_memory/test_extract/test_trace.py b/tests/unit/test_memory/test_extract/test_trace.py new file mode 100644 index 000000000..64e89492c --- /dev/null +++ b/tests/unit/test_memory/test_extract/test_trace.py @@ -0,0 +1,39 @@ +"""Construction snapshots never affect business execution and isolate requests.""" + +from __future__ import annotations + +import asyncio + +from everos.memory.extract.trace import collect_construction_trace, record_construction + + +def test_disabled_trace_skips_snapshot_serialization() -> None: + def fail() -> dict: + raise AssertionError("Serialization must not run without a collector.") + + record_construction("boundary", snapshot_factory=fail) + + +def test_snapshot_failure_is_isolated_and_results_are_immutable() -> None: + def fail() -> dict: + raise ValueError("bad snapshot") + + value = {"content": ["Friday"]} + with collect_construction_trace() as events: + record_construction("boundary", snapshot_factory=fail) + record_construction("extraction_result", result=value) + value["content"].append("Monday") + assert len(events) == 1 + assert events[0]["result"]["content"] == ["Friday"] + + +async def test_concurrent_construction_collectors_do_not_mix() -> None: + async def run(owner: str) -> list[dict]: + with collect_construction_trace() as events: + await asyncio.sleep(0) + record_construction("extraction_result", owner=owner, content="") + return events + + alice, bob = await asyncio.gather(run("alice"), run("bob")) + assert [event["owner"] for event in alice] == ["alice"] + assert [event["owner"] for event in bob] == ["bob"] diff --git a/tests/unit/test_memory/test_reflection/test_language.py b/tests/unit/test_memory/test_reflection/test_language.py new file mode 100644 index 000000000..c17a2f1ad --- /dev/null +++ b/tests/unit/test_memory/test_reflection/test_language.py @@ -0,0 +1,81 @@ +"""Which language a Reflection merge is asked for and stored with. + +The owner's profile language wins. Without one, the members vote with their +stored languages (a member stored without one votes with its text's), and the +winner must hold more than 60% of the members; a closer split names nothing, +and the stored language is then read off the merged text. +""" + +from __future__ import annotations + +import pytest + +from everos.memory.models import Episode +from everos.memory.ports import MemoryRef, Scope, Stored +from everos.memory.reflection._language import ( + LanguageChoice, + merged_language, + steer_language, +) + +_SCOPE = Scope(app_id="a", project_id="p", owner_id="u1", owner_type="user") + + +def _member(language: str | None, text: str = "plain text") -> Stored[Episode]: + return Stored( + ref=MemoryRef(id="u1_ep", entry_id="ep", md_path="e.md"), + scope=_SCOPE, + item=Episode( + owner_id="u1", + episode=text, + summary="", + timestamp=0, + subject="s", + parent_id="mc", + language=language, + ), + ) + + +def test_the_profile_language_wins_over_any_vote() -> None: + members = [_member("English"), _member("English")] + assert steer_language("Chinese", members) == LanguageChoice("Chinese", "profile") + + +@pytest.mark.parametrize( + ("languages", "expected"), + [ + (["English", "English"], "English"), + (["Chinese", "Chinese", "English"], "Chinese"), + (["Chinese", "English"], None), + (["Chinese", "Chinese", "Chinese", "English", "English"], None), + ([], None), + ], + ids=["2 of 2", "2 of 3", "1 of 2", "3 of 5 sits on the bar", "no members"], +) +def test_the_members_vote_needs_more_than_sixty_percent( + languages: list[str], expected: str | None +) -> None: + members = [_member(language) for language in languages] + assert steer_language(None, members) == LanguageChoice(expected, "vote") + + +def test_a_member_stored_without_a_language_votes_with_its_text() -> None: + members = [_member(None, "用户在讨论周末的行程。"), _member("Chinese")] + assert steer_language(None, members) == LanguageChoice("Chinese", "vote") + + +def test_an_unreadable_member_abstains_but_still_counts() -> None: + """One English vote of two members is no majority.""" + members = [_member(None, "2026-05-17 12:00"), _member("English")] + assert steer_language(None, members).value is None + + +def test_a_named_steer_is_what_the_merge_is_stored_with() -> None: + steer = LanguageChoice("Japanese", "vote") + assert merged_language(steer, "an English merged text") is steer + + +def test_without_a_steer_the_merged_text_decides() -> None: + steer = LanguageChoice(None, "vote") + assert merged_language(steer, "合并后的叙述") == LanguageChoice("Chinese", "text") diff --git a/tests/unit/test_memory/test_reflection/test_orchestrator.py b/tests/unit/test_memory/test_reflection/test_orchestrator.py index 6ac29dbc9..5ffc1749e 100644 --- a/tests/unit/test_memory/test_reflection/test_orchestrator.py +++ b/tests/unit/test_memory/test_reflection/test_orchestrator.py @@ -8,6 +8,8 @@ never in the index — the cascade carries it there - LLM failure skips cluster gracefully - empty candidates return empty list +- the merge language: the owner's profile language, else the members' vote, + else read off the merged text; pinned on the merged episode and its event """ from __future__ import annotations @@ -23,9 +25,10 @@ from everos.infra.persistence.lancedb import render_predicate from everos.memory._partition_locks import _reset_for_tests from everos.memory.events import EpisodeExtracted, ReflectedEpisode, ReflectionContext -from everos.memory.models import AtomicFact, Cluster, Episode +from everos.memory.models import AtomicFact, Cluster, Episode, Profile from everos.memory.ports import MemoryRef, Scope, SearchHit, Stored from everos.memory.reflection import ReflectionFinisher, ReflectionOrchestrator +from everos.memory.reflection._language import LanguageChoice from everos.memory.reflection.orchestrator import _MAX_CLUSTERS_PER_RUN _SCOPE = Scope( @@ -75,6 +78,7 @@ def _stored_episode( parent_type: str = "memcell", episode: str = "test episode text", md_path: str = "default_app/default_project/users/u_alice/episodes/e.md", + language: str | None = None, ) -> Stored[Episode]: return Stored( ref=MemoryRef(id=f"u_alice_{entry_id}", entry_id=entry_id, md_path=md_path), @@ -88,6 +92,7 @@ def _stored_episode( session_id="s_test", parent_id=parent_id, parent_type=parent_type, # type: ignore[arg-type] + language=language, ), ) @@ -124,6 +129,7 @@ class _Ports: reflector: MagicMock embedder: MagicMock memcell_store: MagicMock + profile_store: MagicMock def orchestrator(self) -> ReflectionOrchestrator: return ReflectionOrchestrator( @@ -132,6 +138,7 @@ def orchestrator(self) -> ReflectionOrchestrator: episode_index=self.episode_index, memcell_store=self.memcell_store, report_store=self.report_store, + profile_store=self.profile_store, reflector=self.reflector, ) @@ -148,7 +155,8 @@ def finisher(self) -> ReflectionFinisher: @pytest.fixture def ports() -> _Ports: - ports = _Ports(*(MagicMock() for _ in range(9))) + ports = _Ports(*(MagicMock() for _ in range(10))) + ports.profile_store.read = AsyncMock(return_value=None) # Nothing was deleted: every source is still in md, every memcell exists. ports.episode_store.exists = AsyncMock(side_effect=lambda _scope, ids: set(ids)) ports.memcell_store.find_by_ids = AsyncMock( @@ -319,6 +327,7 @@ async def test_merged_episode_is_written_with_a_cluster_parent(ports: _Ports) -> owner_id=None, episode="merged text", subject="topic", timestamp=0 ), last_ts=1_780_272_000_000, + language=LanguageChoice("Japanese", "profile"), only_if=_unchanged, ) @@ -333,6 +342,7 @@ async def test_merged_episode_is_written_with_a_cluster_parent(ports: _Ports) -> subject="topic", parent_id="cl_abc", parent_type="cluster", + language="Japanese", ) @@ -419,6 +429,106 @@ async def test_run_update_mode_uses_old_episode(ports: _Ports) -> None: assert merged.reflection.mode == "update" +# ── The merge language ──────────────────────────────────────────────────── + + +def _arm_two_members(ports: _Ports, *languages: str | None) -> None: + """One INIT-mergeable cluster whose two members stored ``languages``.""" + episodes = [ + _stored_episode( + entry_id=f"ep_20260601_000{i}", parent_id=f"mc_00{i}", language=language + ) + for i, language in enumerate(languages, 1) + ] + _arm_cluster_flow( + ports, + cluster_id="cl_lang", + members=[(ep.ref.entry_id, "episode") for ep in episodes], + episodes=episodes, + merged_entry_id="ep_20260614_0009", + ) + + +def _arm_profile(ports: _Ports, primary_language: str | None) -> None: + ports.profile_store.read = AsyncMock( + return_value=Profile( + owner_id="u_alice", + summary="s", + timestamp=0, + primary_language=primary_language, + ) + ) + + +@pytest.mark.parametrize( + ("profile_language", "member_languages", "asked", "stored", "source"), + [ + ("Chinese", ("English", "English"), "Chinese", "Chinese", "profile"), + (None, ("English", "English"), "English", "English", "vote"), + (None, ("Chinese", "English"), None, "English", "text"), + ], + ids=["profile wins", "members vote", "split vote reads the merged text"], +) +async def test_a_merge_is_written_and_pinned_in_one_language( + ports: _Ports, + profile_language: str | None, + member_languages: tuple[str, str], + asked: str | None, + stored: str, + source: str, +) -> None: + """The reflector is asked for the profile language, else the members' + majority; a split asks for none and the merged text decides. The merged + episode, its event (and so its facts) and the log carry the stored one.""" + _arm_two_members(ports, *member_languages) + _arm_profile(ports, profile_language) + + with structlog.testing.capture_logs() as logs: + (merged,) = await ports.orchestrator().run(scope=_SCOPE) + + assert ports.reflector.areflect.call_args.kwargs["output_language"] == asked + _, (written,) = ports.episode_store.append_many.await_args.args + assert (written.language, merged.language) == (stored, stored) + (line,) = [entry for entry in logs if entry["event"] == "reflection_merged"] + assert (line["language"], line["language_from"]) == (stored, source) + + +async def test_an_update_merge_is_asked_for_the_language_too(ports: _Ports) -> None: + old_merged = _stored_episode( + entry_id="ep_20260612_0001", parent_id="cl_update", parent_type="cluster" + ) + new_ep = _stored_episode(entry_id="ep_20260613_0001", parent_id="mc_004") + _arm_cluster_flow( + ports, + cluster_id="cl_update", + members=[("ep_20260612_0001", "episode"), ("ep_20260613_0001", "episode")], + episodes=[new_ep, old_merged], + merged_entry_id="ep_20260614_0002", + reflected={"cl_update"}, + ) + _arm_profile(ports, "Japanese") + + await ports.orchestrator().run(scope=_SCOPE) + + kwargs = ports.reflector.areflect.call_args.kwargs + assert ("old_episode" in kwargs, kwargs["output_language"]) == (True, "Japanese") + + +async def test_the_profile_is_read_once_per_owner_and_never_when_idle( + ports: _Ports, +) -> None: + _arm_two_members(ports, "English", "English") + await ports.orchestrator().run(scope=_SCOPE) + ports.profile_store.read.assert_awaited_once_with(_SCOPE) + + ports.profile_store.read.reset_mock() + ports.cluster_store.list_for_owner = AsyncMock( + return_value=_clusters(("cl_only_one", 1)) + ) + assert await ports.orchestrator().run(scope=_SCOPE) == [] + ports.profile_store.read.assert_not_awaited() + + @pytest.mark.parametrize("update", [False, True]) async def test_cluster_with_too_few_live_episodes_is_skipped( ports: _Ports, update: bool @@ -511,6 +621,7 @@ async def test_call_reflector_emits_consolidate_generation_span( merged_entry_ids=[], is_update=False, owner_id="u_alice", + output_language=None, ) force_flush() finally: @@ -708,3 +819,19 @@ async def exists(_scope: Scope, ids: Any) -> set[str]: ports.episode_store.deprecate.assert_awaited_once() ports.cluster_store.replace_members.assert_not_awaited() assert any(e["event"] == "reflection_finish_skipped_merged_gone" for e in logs) + + +async def test_an_unreadable_profile_falls_back_to_the_vote(ports: _Ports) -> None: + """A broken ``user.md`` must not fail the owner's run (nor, through the + cron run, every other owner's).""" + _arm_two_members(ports, "Japanese", "Japanese") + ports.profile_store.read = AsyncMock(side_effect=ValueError("bad frontmatter")) + + with structlog.testing.capture_logs() as logs: + (merged,) = await ports.orchestrator().run(scope=_SCOPE) + + assert merged.language == "Japanese" + assert ports.reflector.areflect.call_args.kwargs["output_language"] == "Japanese" + assert [e["event"] for e in logs if e["log_level"] == "warning"] == [ + "reflection_profile_unreadable" + ] diff --git a/tests/unit/test_memory/test_search/test_manager.py b/tests/unit/test_memory/test_search/test_manager.py index f817f36e6..284dd3909 100644 --- a/tests/unit/test_memory/test_search/test_manager.py +++ b/tests/unit/test_memory/test_search/test_manager.py @@ -32,7 +32,7 @@ from everos.core.errors import ProviderNotConfiguredError from everos.memory.models import CanonicalMessage, Cluster from everos.memory.ports import Scope, SearchHit, SessionKey -from everos.memory.search.dto import SearchMethod, SearchRequest +from everos.memory.search.dto import SearchMethod, SearchProfileItem, SearchRequest from everos.memory.search.manager import SearchManager from everos.memory.search.recall import ( AgentCaseRecaller, @@ -41,6 +41,7 @@ EpisodeRecaller, ) from everos.memory.search.recall.base import RecallerDeps +from everos.memory.search.trace import collect_search_trace from tests.fakes import static_trace_path, static_tuning, unscripted_llm from ._records import ( @@ -1099,7 +1100,8 @@ async def _fake_arank(rank_input: Any, **_: Any) -> RankOutput: skill_dense=[skill_direct], skill_by_case=[skill_bridged], ) - await mgr.search(_agent_req(method=SearchMethod.HYBRID, enable_llm_rerank=True)) + with collect_search_trace() as stages: + await mgr.search(_agent_req(method=SearchMethod.HYBRID, enable_llm_rerank=True)) dense_ids = {c.id for c in seen_skill_dense["dense"]} # Direct dense recall is preserved AND the case-bridged skill is unioned. @@ -1107,6 +1109,16 @@ async def _fake_arank(rank_input: Any, **_: Any) -> RankOutput: # The bridged skill inherits the matched case's score (0.85 from the case). by_id = {c.id: c for c in seen_skill_dense["dense"]} assert by_id["s_bridged"].score == pytest.approx(0.85) + by_phase = {(s.kind, s.phase): s for s in stages} + bridge = by_phase[("agent_skill", "bridged_dense")] + assert bridge.input_stage_ids == ( + by_phase[("agent_skill", "dense")].stage_id, + by_phase[("agent_case", "fusion")].stage_id, + ) + assert by_phase[("agent_skill", "fusion")].input_stage_ids == ( + by_phase[("agent_skill", "sparse")].stage_id, + bridge.stage_id, + ) async def test_search_emits_memory_search_span() -> None: @@ -1335,3 +1347,180 @@ async def test_search_omits_query_when_content_off(_search_spans: Any) -> None: await mgr.search(_user_req(method=SearchMethod.KEYWORD)) attrs = _span_index(_search_spans)["everos.memory.search"].attributes assert "langfuse.observation.input" not in attrs + + +# ── Stage trace hooks (MemTrace collector) ────────────────────────────── + + +async def test_keyword_user_records_single_route_stage() -> None: + mgr = _build_manager(episode_sparse=[_episode_row("ep_1")]) + with collect_search_trace() as stages: + await mgr.search(_user_req(method=SearchMethod.KEYWORD)) + branches = {s.phase: s for s in stages if s.phase.startswith("_")} + assert set(branches) == {"_load_unprocessed"} + assert all(s.metadata["status"] == "skipped" for s in branches.values()) + assert all(s.input_stage_ids == () for s in branches.values()) + assert [(s.phase, s.kind) for s in stages if s.kind == "episode"] == [ + ("single_route", "episode") + ] + stage = next(s for s in stages if s.kind == "episode") + assert [c.id for c in stage.candidates] == ["ep_1"] + assert stage.candidates[0].source == "keyword" + + +async def test_profile_fetch_returns_content_without_recording_a_branch() -> None: + profile = SearchProfileItem( + id="profile_alice", user_id="alice", profile_data={"summary": "camping"} + ) + + class ProfileRecaller: + async def fetch(self, owner_id: str, **kwargs: Any) -> list[SearchProfileItem]: + assert owner_id == "alice" + return [profile] + + mgr = _build_manager() + mgr._profile = ProfileRecaller() + with collect_search_trace() as stages: + response = await mgr.search( + _user_req(method=SearchMethod.KEYWORD, include_profile=True) + ) + assert response.data.profiles == [profile] + assert all(s.kind != "profile" for s in stages) + + +async def test_keyword_agent_records_single_route_per_kind() -> None: + mgr = _build_manager(case_sparse=[_case_row("c1")], skill_sparse=[_skill_row("s1")]) + with collect_search_trace() as stages: + await mgr.search(_agent_req(method=SearchMethod.KEYWORD)) + by_kind: dict[str, list[str]] = {} + for stage in stages: + if stage.kind != "unprocessed": + by_kind.setdefault(stage.kind, []).append(stage.phase) + assert by_kind == {"agent_case": ["single_route"], "agent_skill": ["single_route"]} + + +async def test_vector_user_records_maxsim_atomic_stage() -> None: + mgr = _build_manager( + episode_dense=[_episode_row("ep_dense")], + atomic_fact_dense=[_atomic_fact_row("f1", parent_id="ep_dense", score=0.85)], + embedding=_StubEmbedding(), + ) + with collect_search_trace() as stages: + await mgr.search(_user_req(method=SearchMethod.VECTOR)) + assert [(s.phase, s.kind) for s in stages if s.kind == "episode"] == [ + ("maxsim_atomic", "episode") + ] + stage = next(s for s in stages if s.kind == "episode") + assert [c.id for c in stage.candidates] == ["ep_dense"] + + +async def test_hybrid_user_records_hierarchy_stage_sequence() -> None: + ep1 = _episode_row("ep_1", score=0.8, memcell_id="mc_1") + mgr = _build_manager( + episode_sparse=[ep1], episode_dense=[ep1], embedding=_StubEmbedding() + ) + with collect_search_trace() as stages: + await mgr.search(_user_req(method=SearchMethod.HYBRID, top_k=10, min_score=0.0)) + assert [(s.phase, s.kind) for s in stages if s.kind == "episode"] == [ + ("sparse", "episode"), + ("dense", "episode"), + ("maxsim_atomic", "episode"), + ("rrf", "episode"), + ("hierarchy", "episode"), + ("filtered", "episode"), + ] + rrf = next(s for s in stages if s.phase == "rrf" and s.kind == "episode") + by_phase = {s.phase: s for s in stages if s.kind == "episode"} + assert rrf.input_stage_ids == ( + by_phase["sparse"].stage_id, + by_phase["dense"].stage_id, + by_phase["maxsim_atomic"].stage_id, + ) + + +async def test_hybrid_user_without_min_score_skips_filtered_stage() -> None: + ep1 = _episode_row("ep_1", score=0.8, memcell_id="mc_1") + mgr = _build_manager( + episode_sparse=[ep1], episode_dense=[ep1], embedding=_StubEmbedding() + ) + with collect_search_trace() as stages: + await mgr.search(_user_req(method=SearchMethod.HYBRID, top_k=10)) + assert [s.phase for s in stages if s.kind == "episode"] == [ + "sparse", + "dense", + "maxsim_atomic", + "rrf", + "hierarchy", + ] + + +async def test_hybrid_agent_records_fusion_stages_with_metadata() -> None: + mgr = _build_manager( + case_sparse=[_case_row("c1")], + skill_sparse=[_skill_row("s1")], + embedding=_StubEmbedding(), + reranker=_StubReranker(), + ) + with collect_search_trace() as stages: + await mgr.search(_agent_req(method=SearchMethod.HYBRID)) + by_kind: dict[str, list[str]] = {} + for stage in stages: + if stage.kind != "unprocessed": + by_kind.setdefault(stage.kind, []).append(stage.phase) + assert by_kind["agent_case"] == ["sparse", "dense", "fusion"] + assert by_kind["agent_skill"] == ["sparse", "dense", "bridged_dense", "fusion"] + case_fusion = next( + s for s in stages if s.kind == "agent_case" and s.phase == "fusion" + ) + assert case_fusion.metadata["enable_rerank"] is False + skill_fusion = next( + s for s in stages if s.kind == "agent_skill" and s.phase == "fusion" + ) + assert skill_fusion.metadata == { + "fusion_mode": "skill_hybrid", + "enable_rerank": False, + } + skill_dense = next( + s for s in stages if s.kind == "agent_skill" and s.phase == "dense" + ) + skill_sparse = next( + s for s in stages if s.kind == "agent_skill" and s.phase == "sparse" + ) + bridge = next(s for s in stages if s.phase == "bridged_dense") + assert bridge.input_stage_ids == (skill_dense.stage_id,) + assert skill_fusion.input_stage_ids == (skill_sparse.stage_id, bridge.stage_id) + + +async def test_agentic_records_final_stage_only( + monkeypatch: pytest.MonkeyPatch, +) -> None: + from everos.memory.search.dto import SearchEpisodeItem + + async def _fake_agentic(*args: Any, **kwargs: Any) -> list[SearchEpisodeItem]: + return [ + SearchEpisodeItem( + id="ep_1", + score=0.9, + session_id="s", + user_id="alice", + timestamp=_dt.datetime(2026, 1, 1, tzinfo=_dt.UTC), + sender_ids=["alice"], + subject="s", + summary="s", + episode="body", + type="Conversation", + atomic_facts=[], + ) + ] + + monkeypatch.setattr( + "everos.memory.search.manager.search_episodes_agentic", _fake_agentic + ) + mgr = _build_manager(embedding=_StubEmbedding(), reranker=_StubReranker()) + with collect_search_trace() as stages: + await mgr.search(_user_req(method=SearchMethod.AGENTIC)) + assert [(s.phase, s.kind) for s in stages if s.kind == "episode"] == [ + ("agentic", "episode") + ] + stage = next(s for s in stages if s.kind == "episode") + assert [c.id for c in stage.candidates] == ["ep_1"] diff --git a/tests/unit/test_memory/test_search/test_trace.py b/tests/unit/test_memory/test_search/test_trace.py new file mode 100644 index 000000000..4cc36990b --- /dev/null +++ b/tests/unit/test_memory/test_search/test_trace.py @@ -0,0 +1,179 @@ +"""Unit tests for the search-stage trace collector (``memory.search.trace``). + +Pins the collection protocol the MemTrace instrumentation relies on: + +* ``record_stage`` is a no-op outside a ``collect_search_trace`` scope and + never raises on malformed candidates; +* candidates are reduced to their ``(id, score, source)`` triple and each + stage is capped at ``STAGE_CANDIDATE_CAP``; the pre-truncation pool size + rides on ``total_count`` (``-1`` when the iterable has no length); +* concurrent search requests collect independently (``ContextVar`` + isolation), while the ``asyncio.gather`` fan-out inside one request + shares the request's collector. +""" + +from __future__ import annotations + +import asyncio +from dataclasses import dataclass + +from everos.memory.search.trace import ( + STAGE_CANDIDATE_CAP, + SearchStageRecord, + collect_search_trace, + record_stage, +) + + +@dataclass(frozen=True) +class _Candidate: + """Minimal stand-in for the everalgo ``Candidate`` triple.""" + + id: str + score: float + source: str + + +def _candidates(n: int, *, prefix: str = "c") -> list[_Candidate]: + return [ + _Candidate(id=f"{prefix}_{i}", score=0.5 + i * 0.01, source="keyword") + for i in range(n) + ] + + +def test_record_stage_is_noop_without_collector() -> None: + # No collect_search_trace scope installed — must silently do nothing. + record_stage("sparse", "episode", _candidates(3)) + + +def test_record_stage_never_raises_on_malformed_candidates() -> None: + with collect_search_trace() as stages: + record_stage("sparse", "episode", [object(), None]) + assert len(stages) == 1 + assert [(c.id, c.score, c.source) for c in stages[0].candidates] == [ + ("", 0.0, ""), + ("", 0.0, ""), + ] + + +def test_record_stage_swallows_candidate_attribute_errors() -> None: + """A candidate whose attribute access raises must not break search — + the whole stage record is dropped, the exception never propagates.""" + + class _Exploding: + @property + def id(self) -> str: + raise RuntimeError("boom") + + with collect_search_trace() as stages: + record_stage("sparse", "episode", [_Exploding()]) + assert stages == [] + + +def test_collect_search_trace_records_stages_in_order() -> None: + with collect_search_trace() as stages: + record_stage("sparse", "episode", _candidates(2)) + record_stage( + "fusion", + "episode", + _candidates(1, prefix="f"), + metadata={"fusion_mode": "rrf", "enable_rerank": False}, + ) + assert [s.phase for s in stages] == ["sparse", "fusion"] + assert all(s.kind == "episode" for s in stages) + assert [(c.id, c.score, c.source) for c in stages[0].candidates] == [ + ("c_0", 0.5, "keyword"), + ("c_1", 0.51, "keyword"), + ] + assert stages[1].metadata == {"fusion_mode": "rrf", "enable_rerank": False} + + +def test_record_stage_defaults_metadata_to_empty() -> None: + with collect_search_trace() as stages: + record_stage("sparse", "episode", _candidates(1)) + assert stages[0].metadata == {} + + +def test_candidates_capped_at_stage_cap() -> None: + with collect_search_trace() as stages: + record_stage("dense", "episode", _candidates(STAGE_CANDIDATE_CAP + 20)) + assert len(stages[0].candidates) == STAGE_CANDIDATE_CAP + # The first STAGE_CANDIDATE_CAP candidates (pool order) are kept. + assert stages[0].candidates[-1].id == f"c_{STAGE_CANDIDATE_CAP - 1}" + + +def test_total_count_reflects_the_pre_truncation_pool_size() -> None: + with collect_search_trace() as stages: + record_stage("dense", "episode", _candidates(STAGE_CANDIDATE_CAP + 20)) + record_stage("sparse", "episode", _candidates(3)) + assert stages[0].total_count == STAGE_CANDIDATE_CAP + 20 + assert stages[0].total_count > len(stages[0].candidates) + assert stages[1].total_count == 3 + assert stages[1].total_count == len(stages[1].candidates) + + +def test_total_count_is_unknown_when_candidates_expose_no_length() -> None: + class _SliceableOnly: + """Supports slicing but no ``len`` — the length stays unknown.""" + + def __init__(self, items: list[_Candidate]) -> None: + self._items = items + + def __getitem__(self, key: object) -> object: + return self._items[key] + + with collect_search_trace() as stages: + record_stage("sparse", "episode", _SliceableOnly(_candidates(2))) + assert stages[0].total_count == -1 + assert len(stages[0].candidates) == 2 + + +def test_stage_record_total_count_defaults_to_zero() -> None: + record = SearchStageRecord(phase="sparse", kind="episode", candidates=()) + assert record.total_count == 0 + + +def test_collector_uninstalled_on_scope_exit() -> None: + with collect_search_trace(): + record_stage("sparse", "episode", _candidates(1)) + record_stage("dense", "episode", _candidates(1)) # no-op again + with collect_search_trace() as stages: + pass + assert stages == [] + + +def test_nested_scopes_collect_independently() -> None: + with collect_search_trace() as outer: + record_stage("sparse", "episode", _candidates(1, prefix="o")) + with collect_search_trace() as inner: + record_stage("dense", "episode", _candidates(1, prefix="i")) + record_stage("fusion", "episode", _candidates(1, prefix="o")) + assert [c.id for s in outer for c in s.candidates] == ["o_0", "o_0"] + assert [s.phase for s in outer] == ["sparse", "fusion"] + assert [s.phase for s in inner] == ["dense"] + + +async def test_collectors_isolated_across_concurrent_tasks() -> None: + async def run(tag: str) -> list[SearchStageRecord]: + with collect_search_trace() as stages: + record_stage("sparse", "episode", _candidates(1, prefix=tag)) + await asyncio.sleep(0) # force interleaving + record_stage("fusion", "episode", _candidates(1, prefix=tag)) + return stages + + first, second = await asyncio.gather(run("a"), run("b")) + assert [s.phase for s in first] == ["sparse", "fusion"] + assert [s.phase for s in second] == ["sparse", "fusion"] + assert [c.id for c in first[0].candidates] == ["a_0"] + assert [c.id for c in second[0].candidates] == ["b_0"] + + +async def test_gather_children_share_the_request_collector() -> None: + """One request's ``asyncio.gather`` fan-out lands in one collector.""" + + async def child(kind: str) -> None: + record_stage("sparse", kind, _candidates(1)) + + with collect_search_trace() as stages: + await asyncio.gather(child("agent_case"), child("agent_skill")) + assert {s.kind for s in stages} == {"agent_case", "agent_skill"} diff --git a/tests/unit/test_memory/test_strategies/test_extract_atomic_facts.py b/tests/unit/test_memory/test_strategies/test_extract_atomic_facts.py index 9e8b1d5cb..e2dccbd1e 100644 --- a/tests/unit/test_memory/test_strategies/test_extract_atomic_facts.py +++ b/tests/unit/test_memory/test_strategies/test_extract_atomic_facts.py @@ -163,15 +163,20 @@ async def test_reflection_context_is_carried_through() -> None: async def test_facts_are_written_in_the_episode_language( language: str | None, ) -> None: - """The event's language is the extractor's output language; ``None`` lets - the extractor infer its own.""" + """The event's language is the extractor's output language, and the run's + log line names it; ``None`` lets the extractor infer its own.""" deps = make_deps() - with patch(_EXTRACTOR) as extractor_cls: + with ( + patch(_EXTRACTOR) as extractor_cls, + structlog.testing.capture_logs() as captured, + ): extractor_cls.return_value.aextract_from_text = AsyncMock(return_value=[]) await extract_atomic_facts(_event(language=language), deps) call = extractor_cls.return_value.aextract_from_text.call_args assert call.kwargs["output_language"] == language + record = next(e for e in captured if e.get("event") == "atomic_facts_extracted") + assert record["language"] == language async def test_reflection_fact_skips_memcell_check() -> None: diff --git a/tests/unit/test_memory/test_strategies/test_extract_user_profile.py b/tests/unit/test_memory/test_strategies/test_extract_user_profile.py index 5210a32c9..faad7dbcd 100644 --- a/tests/unit/test_memory/test_strategies/test_extract_user_profile.py +++ b/tests/unit/test_memory/test_strategies/test_extract_user_profile.py @@ -520,18 +520,26 @@ async def test_a_narrative_the_extractor_refuses_is_skipped() -> None: @pytest.mark.parametrize( - ("stored", "event_language", "expected"), + ("stored", "event_language", "expected", "source"), [ - pytest.param(None, "Chinese", "Chinese", id="no-profile-init-freezes"), - pytest.param("English", "Chinese", "English", id="frozen-wins-unchanged"), - pytest.param("", "Chinese", "Chinese", id="unfrozen-takes-event"), - pytest.param("", None, None, id="unknown-stays-unknown"), + pytest.param(None, "Chinese", "Chinese", "event", id="no-profile-init-freezes"), + pytest.param( + "English", "Chinese", "English", "frozen", id="frozen-wins-unchanged" + ), + pytest.param("", "Chinese", "Chinese", "event", id="unfrozen-takes-event"), + pytest.param("", None, None, None, id="unknown-stays-unknown"), ], ) async def test_profile_language_is_frozen_once_known( - stored: str | None, event_language: str | None, expected: str | None + stored: str | None, + event_language: str | None, + expected: str | None, + source: str | None, ) -> None: - """``stored``: ``None`` = no profile yet, ``""`` = one with no language.""" + """``stored``: ``None`` = no profile yet, ``""`` = one with no language. + + The run's log line says which language was used and where it came from. + """ deps = make_deps() _seed(deps, _scope()) if stored is not None: @@ -541,11 +549,16 @@ async def test_profile_language_is_frozen_once_known( timestamp=_TS - 1, primary_language=stored or None, ) - with _extractor(return_value=_algo_profile()) as extract: + with ( + _extractor(return_value=_algo_profile()) as extract, + structlog.testing.capture_logs() as logs, + ): await extract_user_profile(_event(language=event_language), deps) assert extract.call_args.kwargs["output_language"] == expected assert deps.stores.profile.profiles[_scope()].primary_language == expected + (line,) = [e for e in logs if e["event"] == "user_profile_extracted"] + assert (line["language"], line["language_from"]) == (expected, source) async def test_primary_language_does_not_reach_the_algo_profile() -> None: diff --git a/tests/unit/test_memtrace_example/__init__.py b/tests/unit/test_memtrace_example/__init__.py new file mode 100644 index 000000000..a55fb826b --- /dev/null +++ b/tests/unit/test_memtrace_example/__init__.py @@ -0,0 +1,3 @@ +"""Tests for standalone attribution examples.""" + +from __future__ import annotations diff --git a/tests/unit/test_memtrace_example/conftest.py b/tests/unit/test_memtrace_example/conftest.py new file mode 100644 index 000000000..d9e81b978 --- /dev/null +++ b/tests/unit/test_memtrace_example/conftest.py @@ -0,0 +1,117 @@ +"""Small invented QA graphs; no benchmark conversations or live credentials.""" + +from __future__ import annotations + +import json +from typing import Any + +import pytest +from smartcomment.runtime import ExecNetwork + + +def make_graph( + *, + score: Any = "0.0", + answers: Any = "['Friday']", + omit_prediction: bool = False, + mismatch: bool = False, +) -> ExecNetwork: + """An extraction -> retrieval -> response graph with an EverOS QA chain.""" + common = { + "filename": "invented.py", + "lineno": 1, + "graph_id": "test-graph", + "session_id": "test-session", + "created_at": "2026-01-01 00:00:00.000", + } + specs = [ + ("message", "message", None, {"content": "The adoption meeting was Friday."}), + ("memory", "memory_entry", None, {"content": "adoption meeting Friday"}), + ( + "query", + "message & query", + "query", + {"query": "When was the adoption meeting?"}, + ), + ("context", "memory_context", "context", {"content": "unrelated"}), + ("prediction", "llm_response", "prediction", {"answer": "Unknown"}), + ("golden", "golden_answers", "golden_answers", {"answers": answers}), + ( + "judge", + "judge_response", + "judge_response", + { + "query_id": "other" if mismatch else "query", + "score": score, + "response": "VERDICT: 0", + }, + ), + ] + nodes = [ + { + **common, + "name": name, + "version": 1, + "category": category, + "class_name": class_name, + "value": json.dumps(value), + } + for name, category, class_name, value in specs + ] + ids = { + name: f"{class_name + ':' if class_name else ''}{name}@1" + for name, _category, class_name, _value in specs + } + operations = [] + edges = [] + for op_id, name, category, inputs, output, seq in [ + ("extract-op", "extract", "extraction", ["message"], "memory", 1), + ("retrieve-op", "search", "retrieval", ["query", "memory"], "context", 2), + ("answer-op", "answer", "response", ["query", "context"], "prediction", 3), + ( + "judge-op", + "judge_answer_query", + "evaluation", + ["query", "golden"] + if omit_prediction + else ["query", "prediction", "golden"], + "judge", + None, + ), + ]: + operations.append( + { + **common, + "op_id": op_id, + "op_name": name, + "category": category, + "metadata": {"event_seq": seq} if seq else {}, + } + ) + for source in inputs: + edges.append( + { + **common, + "edge_id": f"{op_id}-{source}", + "op_id": op_id, + "source_full_node_id": ids[source], + "target_full_node_id": ids[output], + } + ) + return ExecNetwork.import_graph( + { + "graph_id": "test-graph", + "strict": False, + "data": { + "nodes": nodes, + "edges": edges, + "operations": operations, + "sessions": [{**common, "session_name": "synthetic-test"}], + }, + } + ) + + +@pytest.fixture +def graph() -> ExecNetwork: + return make_graph() diff --git a/tests/unit/test_memtrace_example/test_agent.py b/tests/unit/test_memtrace_example/test_agent.py new file mode 100644 index 000000000..c1e90579f --- /dev/null +++ b/tests/unit/test_memtrace_example/test_agent.py @@ -0,0 +1,269 @@ +"""Pin end-to-end tool calling, budget integrity, and honest failure reports.""" + +from __future__ import annotations + +import json +from typing import Any + +import pytest +from smartcomment.runtime import ExecNetwork + +from examples.memtrace.attribute import load_credentials +from examples.memtrace.graphtrace import ( + AttributionConfig, + attribute, + collect_failed_queries, +) +from examples.memtrace.graphtrace.agent import ContextBudgetError, trim_history + + +def call(name: str, **arguments: Any) -> dict[str, Any]: + return { + "id": "call-" + name, + "type": "function", + "function": { + "name": name, + "arguments": json.dumps(arguments), + }, + } + + +class ScriptedProvider: + def __init__(self, batches: list[list[dict[str, Any]]]) -> None: + self.batches = iter(batches) + self.requests: list[list[dict[str, Any]]] = [] + + async def complete( + self, messages: list[dict[str, Any]], tools: list[dict[str, Any]] + ) -> dict[str, Any]: + self.requests.append(messages) + return { + "message": { + "role": "assistant", + "content": None, + "tool_calls": next(self.batches), + }, + "usage": {"prompt_tokens": 7, "completion_tokens": 2, "total_tokens": 9}, + } + + +async def test_attribution_inspects_graph_and_corrects_invalid_submission( + graph: ExecNetwork, +) -> None: + provider = ScriptedProvider( + [ + [call("explore_graph_trace_node", include_variable_value=False)], + [call("view_node_value", full_node_id="message@1", pattern="Friday")], + [ + call( + "update_to_explore_nodes", + action="add", + full_node_id="memory@1", + discovered_by_op_id="extract-op", + ), + call("finish_node_exploration", outcome="Extraction preserved Friday."), + ], + [call("explore_graph_trace_node", include_variable_value=False)], + [call("view_node_value", full_node_id="context:context@1")], + [ + call( + "finish_graph_exploration", + outcome="Memory holds Friday; context omits it.", + ) + ], + [ + call( + "submit_attribution", + error_type="RetrievalError", + op_id="missing-op", + reason="Memory has Friday; final context does not.", + ) + ], + [ + call( + "submit_attribution", + error_type="RetrievalError", + op_id="retrieve-op", + reason=( + "memory@1 preserves Friday but context:context@1 omits it. " + "Extraction is correct; fixing retrieve-op supplies evidence " + "to response." + ), + ) + ], + ] + ) + original = graph.export_graph() + report = await attribute(graph, collect_failed_queries(graph)[0][0], provider) + assert report["status"] == "success" + assert report["attribution"]["op_id"] == "retrieve-op" + assert report["attribution"]["error_type"] == "RetrievalError" + assert report["iterations"] == 8 + assert report["usage"]["total_tokens"] == 72 + assert graph.export_graph() == original + errors = [ + event["message"]["content"] + for event in report["transcript"] + if event.get("message", {}).get("role") == "tool" + and event["message"]["content"].startswith("Tool error:") + ] + assert len(errors) == 1 and "does not exist" in errors[0] + for request in provider.requests: + assert sum(message["role"] == "system" for message in request) == 2 + assert "Memory holds Friday" in report["final_state"]["outcome"] + + +async def test_uninspected_operation_cannot_be_submitted(graph: ExecNetwork) -> None: + provider = ScriptedProvider( + [ + [call("finish_graph_exploration", outcome="No inspection")], + [ + call( + "submit_attribution", + error_type="RetrievalError", + op_id="retrieve-op", + reason="Guess", + ) + ], + ] + ) + report = await attribute( + graph, + collect_failed_queries(graph)[0][0], + provider, + AttributionConfig(max_iters=2), + ) + assert report["attribution"] is None + assert report["failure"]["type"] == "IterationLimit" + assert "Inspect the submitted operation" in json.dumps(report["transcript"]) + + +async def test_iteration_and_context_limits_preserve_state(graph: ExecNetwork) -> None: + case = collect_failed_queries(graph)[0][0] + report = await attribute( + graph, + case, + ScriptedProvider( + [ + [call("explore_graph_trace_node", include_variable_value=False)], + ] + ), + AttributionConfig(max_iters=1), + ) + assert report["failure"]["type"] == "IterationLimit" + assert report["attribution"] is None + assert report["final_state"]["exploring_node"]["full_node_id"] == "message@1" + provider = ScriptedProvider([]) + report = await attribute(graph, case, provider, AttributionConfig(context_chars=1)) + assert report["failure"]["type"] == "ContextBudgetError" + assert not provider.requests + assert report["final_state"] is not None + + +async def test_missing_source_evidence_ends_without_fabricated_attribution( + graph: ExecNetwork, +) -> None: + report = await attribute( + graph, + collect_failed_queries(graph)[0][0], + ScriptedProvider( + [ + [call("explore_graph_trace_node", include_variable_value=False)], + [ + call( + "finish_graph_exploration", + outcome="Source event is not recorded.", + insufficient_evidence=True, + ) + ], + ] + ), + ) + assert report["failure"] == { + "type": "InsufficientEvidence", + "message": "Source event is not recorded.", + } + assert report["attribution"] is None + assert report["final_state"]["finished_at"] + + +async def test_provider_errors_never_serialize_credentials(graph: ExecNetwork) -> None: + class FailingProvider: + async def complete(self, messages: list, tools: list) -> dict: + raise RuntimeError("sensitive-test-placeholder") + + report = await attribute( + graph, collect_failed_queries(graph)[0][0], FailingProvider() + ) + assert report["failure"]["type"] == "RuntimeError" + assert "sensitive-test-placeholder" not in json.dumps(report) + assert report["attribution"] is None + + +async def test_no_message_candidates_use_synthetic_root(graph: ExecNetwork) -> None: + payload = graph.export_graph() + for node in payload["data"]["nodes"]: + if node["category"] == "message": + node["category"] = "other" + graph = ExecNetwork.import_graph(payload) + report = await attribute( + graph, + collect_failed_queries(graph)[0][0], + ScriptedProvider( + [ + [call("explore_graph_trace_node", include_variable_value=False)], + ] + ), + AttributionConfig(max_iters=1), + ) + assert report["pseudo_evidence_nodes"] == [] + assert report["final_state"]["exploring_node"]["category"] == "synthetic_root" + + +def test_context_trimming_keeps_entire_multi_tool_batch() -> None: + history = [ + {"role": "system", "content": "instructions"}, + {"role": "user", "content": "task"}, + ] + for index, length in [(0, 3000), (1, 300)]: + calls = [call("a"), call("b")] + for c in calls: + c["id"] += str(index) + history += [ + {"role": "assistant", "content": None, "tool_calls": calls}, + *[ + {"role": "tool", "tool_call_id": c["id"], "content": "x" * length} + for c in calls + ], + ] + trimmed, removed = trim_history(history, "state", [], 1400) + assert removed == 1 + assert [m["role"] for m in trimmed] == [ + "system", + "user", + "assistant", + "tool", + "tool", + ] + ids = {c["id"] for c in trimmed[2]["tool_calls"]} + assert ids == {m["tool_call_id"] for m in trimmed[3:]} + with pytest.raises(ContextBudgetError): + trim_history(history, "state", [], 10) + + +def test_credentials_validate_pairs_and_environment( + tmp_path: Any, monkeypatch: Any +) -> None: + path = tmp_path / "config.json" + path.write_text( + json.dumps( + {"api_keys": ["fake-unit-key"], "base_urls": ["https://example.invalid/v1"]} + ) + ) + assert load_credentials(path) == ("fake-unit-key", "https://example.invalid/v1") + path.write_text(json.dumps({"api_keys": ["fake-unit-key"], "base_urls": []})) + with pytest.raises(ValueError): + load_credentials(path) + monkeypatch.setenv("OPENAI_API_KEY", "fake-env-key") + monkeypatch.setenv("OPENAI_BASE_URL", "https://example.invalid/v1") + assert load_credentials(None)[0] == "fake-env-key" diff --git a/tests/unit/test_memtrace_example/test_attribution_regressions.py b/tests/unit/test_memtrace_example/test_attribution_regressions.py new file mode 100644 index 000000000..3635732ec --- /dev/null +++ b/tests/unit/test_memtrace_example/test_attribution_regressions.py @@ -0,0 +1,327 @@ +"""Regression coverage for bounded exploration and mechanical evidence guards.""" + +from __future__ import annotations + +import copy +import json +import re + +import pytest +from smartcomment.runtime import ExecNetwork + +from examples.memtrace.graphtrace import ( + AttributionConfig, + GraphTraceNotebook, + attribute, + collect_failed_queries, +) +from examples.memtrace.graphtrace.retrieval import retrieve_starting_nodes +from examples.memtrace.merge import merge_graphs + +from .test_agent import ScriptedProvider, call + + +def _large_graph(graph: ExecNetwork, *, huge_value: bool = False) -> ExecNetwork: + payload = graph.export_graph() + if huge_value: + payload["data"]["nodes"][0]["value"] = "Friday " * 20_000 + else: + template = payload["data"]["operations"][0] + edge = payload["data"]["edges"][0] + for index in range(180): + op_id = f"extra-{index}" + payload["data"]["operations"].append({**template, "op_id": op_id}) + payload["data"]["edges"].append({**edge, "op_id": op_id, "edge_id": op_id}) + return ExecNetwork.import_graph(payload) + + +async def test_large_preview_leaves_room_for_the_next_model_call( + graph: ExecNetwork, +) -> None: + graph = _large_graph(graph) + provider = ScriptedProvider( + [ + [call("explore_graph_trace_node", include_variable_value=False)], + [ + call( + "finish_graph_exploration", + outcome="More pages are needed.", + insufficient_evidence=True, + ) + ], + ] + ) + report = await attribute(graph, collect_failed_queries(graph)[0][0], provider) + assert len(provider.requests) == 2 + preview = next( + event["message"]["content"] + for event in report["transcript"] + if event.get("tool_name") == "explore_graph_trace_node" + ) + assert len(preview) < 16_200 + assert "next offset=" in preview + assert report["failure"]["type"] == "InsufficientEvidence" + + +def test_single_large_operation_can_be_inspected_across_pages( + graph: ExecNetwork, +) -> None: + graph = _large_graph(graph, huge_value=True) + notebook = GraphTraceNotebook(graph) + notebook.initialize_execution_graph(["message@1"]) + offset = 1 + pages = 0 + while True: + page = notebook.explore_graph_trace_node(offset=offset, limit=4000) + pages += 1 + if "End of content." in page: + break + offset = int(re.search(r"next offset=(\d+)", page).group(1)) + assert pages > 2 + assert "extract-op" in notebook.inspected_operations + assert "message@1" in notebook.read_nodes + + +def test_forged_operation_header_in_a_value_is_not_inspection( + graph: ExecNetwork, +) -> None: + payload = graph.export_graph() + payload["data"]["nodes"][0]["value"] = "# Operation `judge-op`" + notebook = GraphTraceNotebook(ExecNetwork.import_graph(payload)) + notebook.initialize_execution_graph(["message@1"]) + notebook.explore_graph_trace_node() + assert "extract-op" in notebook.inspected_operations + assert "judge-op" not in notebook.inspected_operations + + +def test_completed_history_and_comments_have_bounded_hints(graph: ExecNetwork) -> None: + payload = graph.export_graph() + payload["data"]["nodes"][0]["comment"] = "long comment " * 20_000 + notebook = GraphTraceNotebook(ExecNetwork.import_graph(payload)) + notebook.initialize_execution_graph(["message@1"]) + notebook.explore_graph_trace_node(include_variable_value=False) + assert len(notebook.hint()) < 1200 + assert "long comment" in notebook.hint() + notebook.finish_node_exploration("large outcome " * 10_000) + record = notebook.state.exploration_history["message@1"] + for index in range(100): + node_id = f"history-{index}@1" + notebook.state.exploration_history[node_id] = record.model_copy( + update={"full_node_id": node_id} + ) + assert len(notebook.hint()) < 3000 + assert '"completed_count": 101' in notebook.hint() + + +@pytest.mark.parametrize( + ("op_id", "error_type", "reason", "observation", "expected"), + [ + ("judge-op", "DeletionError", "query:query@1", False, "not attributable"), + ("retrieve-op", "RetrievalError", "Guess", False, "Cite a relevant node"), + ("extract-op", "ExtractionError", "message@1", True, "File observations"), + ], +) +async def test_submission_rejects_invalid_evidence_and_operation_roles( + graph: ExecNetwork, + op_id: str, + error_type: str, + reason: str, + observation: bool, + expected: str, +) -> None: + payload = graph.export_graph() + if observation: + payload["data"]["operations"][0]["metadata"].update( + source="file_diff", observation_only=True + ) + graph = ExecNetwork.import_graph(payload) + provider = ScriptedProvider( + [ + [ + call("explore_graph_trace_node", include_variable_value=False), + call("view_node_value", full_node_id="query:query@1"), + call("view_node_value", full_node_id="message@1"), + ], + [call("finish_graph_exploration", outcome="Test guards")], + [ + call( + "submit_attribution", + error_type=error_type, + op_id=op_id, + reason=reason, + ) + ], + ] + ) + # One frontier slot selects the query; extraction uses the message instead. + config = AttributionConfig( + max_iters=3, max_trace_nodes=1 if not observation else 16 + ) + report = await attribute( + graph, collect_failed_queries(graph)[0][0], provider, config + ) + assert report["attribution"] is None + assert expected in json.dumps(report["transcript"]) + + +async def test_unobserved_answer_context_cannot_prove_response_error( + graph: ExecNetwork, +) -> None: + payload = graph.export_graph() + node = next(n for n in payload["data"]["nodes"] if n["name"] == "context") + node.update( + value=json.dumps({"content": None, "observed": False}), + class_name="answer_context", + name="actual", + full_name="answer_context:actual", + full_node_id="answer_context:actual@1", + ) + for edge in payload["data"]["edges"]: + for field in ("source_full_node_id", "target_full_node_id"): + if edge[field] == "context:context@1": + edge[field] = "answer_context:actual@1" + graph = ExecNetwork.import_graph(payload) + provider = ScriptedProvider( + [ + [call("explore_graph_trace_node")], + [call("finish_graph_exploration", outcome="Test unknown context")], + [ + call( + "submit_attribution", + error_type="ResponseError", + op_id="answer-op", + reason="answer_context:actual@1 lacks Friday", + ) + ], + ] + ) + report = await attribute( + graph, + collect_failed_queries(graph)[0][0], + provider, + AttributionConfig(max_iters=3, max_trace_nodes=1), + ) + assert report["attribution"] is None + assert "actual answer context is unrecorded" in json.dumps(report["transcript"]) + + +def test_safe_merge_keeps_tenants_separate_and_exploration_in_scope( + graph: ExecNetwork, +) -> None: + a, b = graph.export_graph(), copy.deepcopy(graph.export_graph()) + a["metadata"] = {"app_id": "a", "project_id": "p"} + b["metadata"] = {"app_id": "b", "project_id": "p"} + # UUIDs differ in real exports even if logical identities coincide. + for kind, field in ( + ("operations", "op_id"), + ("edges", "edge_id"), + ("sessions", "session_id"), + ): + for item in b["data"][kind]: + item[field] += "-b" + for node in b["data"]["nodes"]: + node["session_id"] += "-b" + for edge in b["data"]["edges"]: + edge["op_id"] += "-b" + merged = ExecNetwork.import_graph(merge_graphs([a, b])) + cases, errors = collect_failed_queries(merged) + assert len(cases) == 2 and not errors + case = cases[0] + query = merged.get_variable(case.query_full_node_id) + starting = retrieve_starting_nodes(merged, case) + assert len(starting) == 1 + assert ( + merged.get_variable(starting[0]).metadata["tenant_scope"] + == query.metadata["tenant_scope"] + ) + notebook = GraphTraceNotebook(merged, query_full_node_id=case.query_full_node_id) + notebook.initialize_execution_graph(starting) + other = next( + n + for n in merged.search_variables(class_name="query") + if n.full_node_id != case.query_full_node_id + ) + with pytest.raises(ValueError, match="another tenant"): + notebook.view_node_value(other.full_node_id) + for op in merged.search_operations(): + if op.metadata["tenant_scope"] != query.metadata["tenant_scope"]: + assert not notebook.operation_allowed(op) + + +def test_safe_merge_rejects_conflicting_immutable_revisions(graph: ExecNetwork) -> None: + a = graph.export_graph() + a["metadata"] = {"app_id": "a", "project_id": "p"} + b = copy.deepcopy(a) + b["data"]["nodes"][0]["value"] = json.dumps({"content": "Monday"}) + with pytest.raises(ValueError, match="Conflicting memory revision"): + merge_graphs([a, b]) + + +def test_case_scope_excludes_other_requests_and_future_construction( + graph: ExecNetwork, +) -> None: + payload = graph.export_graph() + query = next(n for n in payload["data"]["nodes"] if n["class_name"] == "query") + other_query = { + **query, + "name": "other-query", + "full_name": "query:other-query", + "full_node_id": "query:other-query@1", + } + payload["data"]["nodes"].append(other_query) + retrieval = next( + op for op in payload["data"]["operations"] if op["op_id"] == "retrieve-op" + ) + payload["data"]["operations"].extend( + [ + {**retrieval, "op_id": "other-request-op"}, + { + **retrieval, + "op_id": "future-extraction-op", + "category": "extraction", + "created_at": "2026-01-01 01:00:00.000", + }, + ] + ) + edge = next(e for e in payload["data"]["edges"] if e["op_id"] == "retrieve-op") + payload["data"]["edges"].extend( + [ + { + **edge, + "edge_id": "other-query-edge", + "op_id": "other-request-op", + "source_full_node_id": other_query["full_node_id"], + }, + { + **edge, + "edge_id": "future-edge", + "op_id": "future-extraction-op", + "source_full_node_id": "memory@1", + }, + ] + ) + graph = ExecNetwork.import_graph(payload) + notebook = GraphTraceNotebook(graph, query_full_node_id=query["full_node_id"]) + assert not notebook.operation_allowed(graph.get_operation("other-request-op")) + assert not notebook.operation_allowed(graph.get_operation("future-extraction-op")) + assert notebook.operation_allowed(graph.get_operation("retrieve-op")) + + +def test_reading_no_matches_or_beyond_value_does_not_count_as_evidence( + graph: ExecNetwork, +) -> None: + notebook = GraphTraceNotebook(graph) + notebook.initialize_execution_graph() + notebook.view_node_value("message@1", pattern="Tuesday") + notebook.view_node_value("message@1", offset=100_000) + assert "message@1" not in notebook.read_nodes + + +def test_notebook_supports_native_plain_text_queries(graph: ExecNetwork) -> None: + payload = graph.export_graph() + query = next(n for n in payload["data"]["nodes"] if n["class_name"] == "query") + query["value"] = "When was the meeting?" + graph = ExecNetwork.import_graph(payload) + notebook = GraphTraceNotebook(graph, query_full_node_id=query["full_node_id"]) + notebook.initialize_execution_graph([query["full_node_id"]]) + assert "answer-op" in notebook.explore_graph_trace_node() diff --git a/tests/unit/test_memtrace_example/test_cli.py b/tests/unit/test_memtrace_example/test_cli.py new file mode 100644 index 000000000..03aa91406 --- /dev/null +++ b/tests/unit/test_memtrace_example/test_cli.py @@ -0,0 +1,137 @@ +"""CLI listing is offline and reports never overwrite input data or credentials.""" + +from __future__ import annotations + +import json +import sys +from pathlib import Path +from typing import Any + +import pytest +from smartcomment.runtime import ExecNetwork + +from examples.memtrace import attribute as cli +from examples.memtrace.merge import merge_graphs + + +def _argv(monkeypatch: pytest.MonkeyPatch, path: Path, *args: str) -> None: + monkeypatch.setattr(sys, "argv", ["attribute.py", "--graph", str(path), *args]) + + +def test_listing_needs_no_credentials_or_client( + graph: ExecNetwork, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + path = tmp_path / "graph.json" + path.write_text(json.dumps(graph.export_graph())) + monkeypatch.delenv("OPENAI_API_KEY", raising=False) + _argv(monkeypatch, path, "--list-cases") + assert cli.main() == 0 + assert json.loads(capsys.readouterr().out)[0]["query"] == ( + "When was the adoption meeting?" + ) + + +@pytest.mark.parametrize("target", ["graph", "credentials"]) +def test_report_cannot_overwrite_input_or_credentials( + graph: ExecNetwork, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + target: str, +) -> None: + path = tmp_path / "graph.json" + path.write_text(json.dumps(graph.export_graph())) + credentials = tmp_path / "credentials.json" + credentials.write_text( + '{"api_keys": ["fake-key"], "base_urls": ["https://example.invalid"]}' + ) + output = path if target == "graph" else credentials + before = output.read_bytes() + _argv(monkeypatch, path, "--output", str(output), "--api-config", str(credentials)) + with pytest.raises(SystemExit) as exc: + cli.main() + assert exc.value.code == 2 + assert output.read_bytes() == before + + +@pytest.mark.parametrize("successful", [True, False]) +def test_cli_writes_report_and_returns_status( + graph: ExecNetwork, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + successful: bool, +) -> None: + path = tmp_path / "graph.json" + path.write_text(json.dumps(graph.export_graph())) + original = path.read_bytes() + output = tmp_path / "reports" / "report.json" + monkeypatch.setenv("OPENAI_API_KEY", "fake-unit-secret") + monkeypatch.setenv("OPENAI_MODEL", "unit-model") + + async def fake_run(*args: Any) -> dict[str, Any]: + return { + "status": "success" if successful else "failed", + "attribution": None, + "failure": None if successful else {"type": "InsufficientEvidence"}, + "iterations": 1, + "usage": {}, + } + + monkeypatch.setattr(cli, "_run", fake_run) + _argv(monkeypatch, path, "--query-id", "query", "--output", str(output)) + assert cli.main() == (0 if successful else 1) + report = json.loads(output.read_text()) + assert report["diagnostics"] == [] + assert "fake-unit-secret" not in output.read_text() + assert path.read_bytes() == original + + +def test_missing_graph_is_a_setup_failure( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + _argv(monkeypatch, tmp_path / "missing.json", "--list-cases") + assert cli.main() == 2 + + +def test_conflicting_legacy_merge_is_rejected_before_credentials( + graph: ExecNetwork, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + payload = graph.export_graph() + payload["metadata"] = {"merge_value_conflicts": ["memory@1"]} + path = tmp_path / "graph.json" + path.write_text(json.dumps(payload)) + _argv(monkeypatch, path, "--list-cases") + assert cli.main() == 2 + assert "unresolved revision conflicts" in capsys.readouterr().err + + +def test_safe_merged_query_can_be_selected_by_original_identity( + graph: ExecNetwork, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + payload = graph.export_graph() + payload["metadata"] = {"app_id": "a", "project_id": "p"} + path = tmp_path / "graph.json" + path.write_text(json.dumps(merge_graphs([payload]))) + output = tmp_path / "report.json" + monkeypatch.setenv("OPENAI_API_KEY", "fake-unit-key") + + async def fake_run(graph: ExecNetwork, case: Any, *args: Any) -> dict[str, Any]: + assert "/query@1" in case.query_full_node_id + return { + "status": "failed", + "iterations": 0, + "usage": {}, + "attribution": None, + "failure": {"type": "InsufficientEvidence"}, + } + + monkeypatch.setattr(cli, "_run", fake_run) + _argv(monkeypatch, path, "--query-id", "query", "--output", str(output)) + assert cli.main() == 1 diff --git a/tests/unit/test_memtrace_example/test_export_png.py b/tests/unit/test_memtrace_example/test_export_png.py new file mode 100644 index 000000000..c3da1b193 --- /dev/null +++ b/tests/unit/test_memtrace_example/test_export_png.py @@ -0,0 +1,149 @@ +"""Display truncation preserves returned evidence and owner-prefixed members.""" + +from __future__ import annotations + +import json + +import pytest +from smartcomment import ( + comment_graph, + comment_link, + comment_op_scope, + comment_session, + comment_variable, +) +from smartcomment.runtime import ExecNetwork + +from examples.memtrace.export_png import _display_payload + + +@pytest.mark.parametrize("selected_query", [None, "query-alice-first"]) +@pytest.mark.parametrize("request_local", [False, True]) +def test_display_preserves_all_returns_and_correct_candidate_prefix( + selected_query: str | None, + request_local: bool, +) -> None: + """Top-one display retains a listed non-hit and every returned fact/episode.""" + with comment_graph() as graph, comment_session(session_name="display"): + + def variable(name: str, value: dict, category: str, cls: str | None = None): + return comment_variable( + {"id": name, **value}, + to_runtime=True, + id_strategy=lambda snapshot: snapshot["id"], + encoding_fn=json.dumps, + category=category, + class_name=cls, + ) + + query = variable( + "query-alice-first", {"user_id": "alice"}, "message & query", "query" + ) + pool = variable( + "candidates_episode_hierarchy-query-alice-first", + { + "ids": ["af_shown", "af_returned", "af_hidden"], + "scores": [0.9, 0.8, 0.7], + "sources": ["", "", ""], + "total_count": 3, + "count": 3, + }, + "memory_context", + "reranked_results", + ) + recall = variable( + "candidates_episode_sparse-query-alice-first", + {"ids": ["ep_other_query"], "scores": [0.5], "sources": ["keyword"]}, + "memory_context", + "sparse_retrieval_results", + ) + # An earlier snapshot mentions evidence returned by another query; + # it must not appear as an isolated node in this query's diagram. + variable("alice_ep_other_query", {}, "memory_entry") + entries = { + eid: variable( + f"hit-query-alice-first-{eid}" if request_local else f"alice_{eid}", + {"memory_identity": f"alice_{eid}", "query_id": "query-alice-first"} + if request_local + else {}, + "retrieval_result" if request_local else "memory_entry", + "retrieval_hit" if request_local else None, + ) + for eid in ("af_shown", "af_returned", "af_hidden", "ep_wrapper") + } + context = variable("context-query-alice-first", {}, "memory_context", "context") + with comment_op_scope(op_name="retrieve", category="retrieval"): + comment_link(source=query, target=recall) + comment_link(source=recall, target=pool) + for entry in entries.values(): + comment_link( + source=pool, target=entry, edge_metadata={"membership": True} + ) + for eid in ("af_returned", "ep_wrapper"): + comment_link(source=entries[eid], target=context) + variable("query-alice-other", {"user_id": "alice"}, "message & query", "query") + + payload = graph.export_graph() + before = json.dumps(payload, sort_keys=True) + display = _display_payload(payload, 1, selected_query) + restored = ExecNetwork.import_graph(display) + names = {node.name for node in restored.get_all_nodes()} + assert { + entries[eid].name for eid in ("af_shown", "af_returned", "ep_wrapper") + } <= names + pairs = { + (edge["source_full_node_id"], edge["target_full_node_id"]) + for edge in display["data"]["edges"] + } + for eid in ("af_shown", "af_returned", "ep_wrapper"): + assert (pool.full_node_id, entries[eid].full_node_id) in pairs + assert (pool.full_node_id, entries["af_hidden"].full_node_id) not in pairs + if selected_query: + assert "query-alice-other" not in names + assert "alice_ep_other_query" not in names + pool_node = next(n for n in display["data"]["nodes"] if n["name"] == pool.name) + assert json.loads(pool_node["value"])["ids"] == ["af_shown"] + assert json.dumps(payload, sort_keys=True) == before + + +@pytest.mark.parametrize("candidate_count", [0, 3]) +def test_display_keeps_auxiliary_branch_to_context(candidate_count: int) -> None: + """Pool truncation must keep context assembly, including an empty read.""" + with comment_graph() as graph, comment_session(session_name="branches"): + query = comment_variable( + {"id": "query-alice-one", "user_id": "alice"}, + to_runtime=True, + id_strategy=lambda value: value["id"], + encoding_fn=json.dumps, + category="message & query", + class_name="query", + ) + pool = comment_variable( + { + "id": "candidates_unprocessed__load_unprocessed-query-alice-one", + "ids": [f"m_{i}" for i in range(candidate_count)], + "total_count": candidate_count, + }, + to_runtime=True, + id_strategy=lambda value: value["id"], + encoding_fn=json.dumps, + category="memory_context", + ) + context = comment_variable( + {"id": "context-query-alice-one"}, + to_runtime=True, + id_strategy=lambda value: value["id"], + encoding_fn=json.dumps, + category="memory_context", + class_name="context", + ) + with comment_op_scope(op_name="_load_unprocessed", category="retrieval"): + comment_link(source=query, target=pool) + with comment_op_scope(op_name="context_assembly", category="retrieval"): + comment_link(source=pool, target=context) + display = _display_payload(graph.export_graph(), 1, query.name) + ExecNetwork.import_graph(display) + assert (pool.full_node_id, context.full_node_id) in { + (edge["source_full_node_id"], edge["target_full_node_id"]) + for edge in display["data"]["edges"] + } diff --git a/tests/unit/test_memtrace_example/test_graphtrace.py b/tests/unit/test_memtrace_example/test_graphtrace.py new file mode 100644 index 000000000..044e272e5 --- /dev/null +++ b/tests/unit/test_memtrace_example/test_graphtrace.py @@ -0,0 +1,221 @@ +"""Pin graph-tool state, QA decoding and source-candidate ranking contracts.""" + +from __future__ import annotations + +import json + +import pytest +from smartcomment.runtime import ExecNetwork + +from examples.memtrace.graphtrace import ( + AttributionResult, + GraphTraceNotebook, + GraphTraceState, + collect_failed_queries, +) +from examples.memtrace.graphtrace.models import GraphTraceNodeRecord +from examples.memtrace.graphtrace.notebook import DUMMY_ROOT, paginate +from examples.memtrace.graphtrace.retrieval import bm25_scores, retrieve_starting_nodes + +from .conftest import make_graph + + +def test_qa_decodes_stringified_reference_list(graph: ExecNetwork) -> None: + cases, diagnostics = collect_failed_queries(graph) + assert diagnostics == [] + assert len(cases) == 1 + assert cases[0].query_full_node_id == "query:query@1" + assert cases[0].golden_answers == ["Friday"] + assert cases[0].prediction == "Unknown" + + +def test_native_judge_score_node_is_supported(graph: ExecNetwork) -> None: + payload = graph.export_graph() + for op in payload["data"]["operations"]: + if op["op_id"] == "judge-op": + op["op_name"] = "llm-judge" + judge = next( + node + for node in payload["data"]["nodes"] + if node["class_name"] == "judge_response" + ) + judge["value"] = "VERDICT: 0" + score = {**judge, "name": "score", "class_name": "judge_score", "value": "0.0"} + payload["data"]["nodes"].append(score) + edge = next( + edge for edge in payload["data"]["edges"] if edge["op_id"] == "judge-op" + ) + payload["data"]["edges"].append( + { + **edge, + "edge_id": "judge-score-edge", + "target_full_node_id": "judge_score:score@1", + } + ) + cases, diagnostics = collect_failed_queries(ExecNetwork.import_graph(payload)) + assert diagnostics == [] + assert cases[0].judge_response == "VERDICT: 0" + + +@pytest.mark.parametrize("score", [1, "1.0", 0.5]) +def test_successful_or_partial_judges_are_excluded(score: object) -> None: + assert collect_failed_queries(make_graph(score=score)) == ([], []) + + +@pytest.mark.parametrize( + "overrides", + [ + {"score": "nan"}, + {"score": None}, + {"score": "bad"}, + {"omit_prediction": True}, + {"answers": []}, + {"answers": [None]}, + {"mismatch": True}, + ], +) +def test_malformed_qa_chains_have_diagnostics(overrides: dict) -> None: + cases, diagnostics = collect_failed_queries(make_graph(**overrides)) + assert cases == [] + assert len(diagnostics) == 1 + assert "judge-op" in diagnostics[0] + + +def test_frontier_order_active_stability_and_capacity() -> None: + state = GraphTraceState() + for node_id, time in [("b@1", "02"), ("a@1", "02")]: + state.add(GraphTraceNodeRecord(full_node_id=node_id, created_at=time), 2) + assert state.start_next().full_node_id == "a@1" + state.add(GraphTraceNodeRecord(full_node_id="older@1", created_at="01"), 2) + assert state.start_next().full_node_id == "a@1" + with pytest.raises(ValueError, match="full"): + state.add(GraphTraceNodeRecord(full_node_id="extra@1", created_at="03"), 2) + with pytest.raises(ValueError, match="Only a queued"): + state.delete("a@1") + state.finish_node("locally correct") + assert state.start_next().full_node_id == "older@1" + with pytest.raises(ValueError, match="already"): + state.add(GraphTraceNodeRecord(full_node_id="a@1", created_at="02"), 2) + assert state.exploration_history["a@1"].outcome == "locally correct" + + +def test_initialize_is_atomic_and_restarts_without_mutating_graph( + graph: ExecNetwork, +) -> None: + original = graph.export_graph() + notebook = GraphTraceNotebook(graph, max_trace_nodes=1) + with pytest.raises(ValueError, match="full"): + notebook.initialize_execution_graph(["message@1", "query:query@1"]) + assert notebook.state is None + notebook.initialize_execution_graph() + assert notebook.state.start_next().full_node_id == DUMMY_ROOT + preview = notebook.explore_graph_trace_node(include_variable_value=False) + assert "message@1" in preview and "query:query@1" in preview + notebook.finish_graph_exploration("restart from query") + assert notebook.final_state.outcome == "restart from query" + notebook.initialize_execution_graph(["query:query@1"]) + notebook.explore_graph_trace_node(include_variable_value=False) + assert notebook.state.exploring_node.full_node_id == "query:query@1" + assert graph.export_graph() == original + + +def test_operation_preview_values_and_provenance(graph: ExecNetwork) -> None: + notebook = GraphTraceNotebook(graph) + notebook.initialize_execution_graph(["memory@1"]) + preview = notebook.explore_graph_trace_node( + include_variable_value=False, offset=1, limit=16000 + ) + assert preview.index("# Operation `extract-op`") < preview.index( + "# Operation `retrieve-op`" + ) + assert "Produced variables" in preview and "Direct successors" in preview + assert "Final output variables" in preview and "event_seq" in preview + assert "adoption meeting Friday" not in preview + notebook.update_to_explore_nodes("add", "context:context@1", "retrieve-op") + record = notebook.state.to_explore_nodes["context:context@1"] + assert record.discovered_from == "memory@1" + assert record.discovered_by_op_id == "retrieve-op" + with pytest.raises(ValueError, match="does not contain"): + notebook.update_to_explore_nodes("add", "judge@1", "retrieve-op") + with pytest.raises(ValueError): + notebook.update_to_explore_nodes("add", "missing@1") + assert "adoption meeting Friday" in notebook.view_node_value("memory@1") + + +def test_pagination_and_regex_search(graph: ExecNetwork) -> None: + assert "abc\n" in paginate("abcdef", 1, 3) + assert "next offset=4" in paginate("abcdef", 1, 3) + assert "def\n" in paginate("abcdef", 4, 3) + assert "No content" in paginate("abcdef", 100, 3) + with pytest.raises(ValueError): + paginate("a", 0, 1) + notebook = GraphTraceNotebook(graph) + notebook.initialize_execution_graph() + result = notebook.view_node_value( + "message@1", pattern="Friday", max_surrounding_chars=0 + ) + assert "Friday" in result and "Match at" in result + assert "No matches" in notebook.view_node_value("message@1", pattern="Tuesday") + with pytest.raises(ValueError, match="Invalid regex"): + notebook.view_node_value("message@1", pattern="[") + + +def test_regex_pagination_resumes_at_next_match(graph: ExecNetwork) -> None: + notebook = GraphTraceNotebook(graph) + notebook.initialize_execution_graph() + first = notebook.view_node_value( + "message@1", pattern=r"[A-Za-z]+", max_surrounding_chars=0, limit=25 + ) + assert "next offset=" in first + offset = int(first.split("next offset=")[1].split(".")[0]) + second = notebook.view_node_value( + "message@1", + pattern=r"[A-Za-z]+", + max_surrounding_chars=0, + limit=25, + offset=offset, + ) + assert first.splitlines()[0] != second.splitlines()[0] + + +def test_bm25_scores_and_candidates(graph: ExecNetwork) -> None: + scores = bm25_scores(["adoption meeting Friday", "meeting", "cycling"], "Friday") + assert scores[0] > scores[1] == scores[2] + assert bm25_scores(["", ""], "Friday") == [0, 0] + assert bm25_scores([], "Friday") == [] + case = collect_failed_queries(graph)[0][0] + assert retrieve_starting_nodes(graph, case, 1) == ["message@1"] + + +def test_node_and_attribution_validation() -> None: + with pytest.raises(ValueError): + GraphTraceNodeRecord(full_node_id="unversioned", created_at="00") + with pytest.raises(ValueError): + AttributionResult(error_type="RetrievalError", op_id="op", reason=" ") + + +def test_duplicate_event_sequences_fall_back_to_timestamp(graph: ExecNetwork) -> None: + payload = graph.export_graph() + for op in payload["data"]["operations"]: + if op["op_id"] == "extract-op": + op["metadata"]["event_seq"] = 2 + op["created_at"] = "2026-01-01 00:00:02.000" + notebook = GraphTraceNotebook(ExecNetwork.import_graph(payload)) + assert not notebook.unique_event_sequences + notebook.initialize_execution_graph(["memory@1"]) + preview = notebook.explore_graph_trace_node(include_variable_value=False) + assert preview.index("# Operation `retrieve-op`") < preview.index( + "# Operation `extract-op`" + ) + + +def test_completed_history_remains_in_fresh_hints(graph: ExecNetwork) -> None: + notebook = GraphTraceNotebook(graph) + notebook.initialize_execution_graph(["memory@1"]) + notebook.explore_graph_trace_node(include_variable_value=False) + notebook.finish_node_exploration("Evidence entered memory.") + assert "Evidence entered memory." in notebook.hint() + history = json.loads( + notebook.view_exploration_history().split("\n\nCharacters", 1)[0] + ) + assert history["memory@1"]["state"] == "explored" diff --git a/tests/unit/test_memtrace_example/test_repair_construction.py b/tests/unit/test_memtrace_example/test_repair_construction.py new file mode 100644 index 000000000..88fe44cbb --- /dev/null +++ b/tests/unit/test_memtrace_example/test_repair_construction.py @@ -0,0 +1,148 @@ +"""Offline repairs remove false boundary duplicates without rewriting history.""" + +from __future__ import annotations + +import copy +import json + +from smartcomment import ( + comment_graph, + comment_link, + comment_op_scope, + comment_session, + comment_variable, +) +from smartcomment.runtime import ExecNetwork + +from examples.memtrace.repair_construction import repair_payload + + +def _legacy_graph() -> tuple[dict, dict]: + """Model an episode and two foresights repeatedly observing one real boundary.""" + members = [f"m_session_{index}" for index in range(4)] + boundary = { + "app_id": "default", + "project_id": "default", + "session_id": "session", + "message_ids": members, + "sender_ids": ["alice", "assistant"], + } + with comment_graph(user_id="alice") as graph, comment_session(session_name="test"): + + def variable(value: dict, category: str): + return comment_variable( + value, + to_runtime=True, + id_strategy=lambda value: value["id"], + encoding_fn=lambda value: json.dumps(value, indent=2, sort_keys=True), + category=category, + ) + + messages = [variable({"id": name}, "message") for name in members] + buffer = {"id": "buffer-session-alice", **boundary, "owner_id": "alice"} + buffer["message_ids"] = members[:2] + first = variable(buffer, "message_buffer") + with comment_op_scope( + op_name="memory_add_session", + category="initialization", + metadata={"event_seq": 1}, + ): + for message in messages[:2]: + comment_link(source=message, target=first) + buffer["message_ids"] = members + second = variable(buffer, "message_buffer") + with comment_op_scope( + op_name="memory_add_session", + category="initialization", + metadata={"event_seq": 2}, + ): + comment_link(source=first, target=second) + for message in messages[2:]: + comment_link(source=message, target=second) + for index in range(3): + cell = { + "id": "mc_1", + **boundary, + "sender_ids": boundary["sender_ids"] if index == 0 else [], + } + with comment_op_scope( + op_name="boundary_detection_mc_1", + category="boundary_detection", + metadata={"event_seq": index + 3}, + ): + parent = comment_variable( + cell, + to_runtime=True, + id_strategy=lambda value: value["id"], + encoding_fn=lambda value: json.dumps( + value, indent=2, sort_keys=True + ), + category="memory_entry", + metadata={"membership": "exact"}, + ) + for message in messages: + comment_link(source=message, target=parent) + child = variable({"id": f"alice_entry_{index}"}, "memory_entry") + with comment_op_scope(op_name=f"entry_{index}", category="extraction"): + comment_link(source=parent, target=child) + # A later add must not replace the earlier consumed buffer in a repair. + buffer["message_ids"] = [*members, "later_message"] + third = variable(buffer, "message_buffer") + with comment_op_scope( + op_name="memory_add_session", + category="initialization", + metadata={"event_seq": 10}, + ): + comment_link(source=second, target=third) + return graph.export_graph(), {"mc_1": boundary} + + +def test_repair_merges_only_repeated_exact_boundaries() -> None: + """One edge per member, one real buffer input, and every child survive repair.""" + original, boundaries = _legacy_graph() + before = copy.deepcopy(original) + repaired, audit = repair_payload(original, boundaries) + assert original == before + graph = ExecNetwork.import_graph(repaired) + assert len(graph.get_versions("mc_1")) == 1 + assert json.loads(graph.get_latest_variable("mc_1").raw_value)["sender_ids"] == [ + "alice", + "assistant", + ] + inputs = [ + edge for edge in graph.get_all_edges() if edge.target_full_node_id == "mc_1@1" + ] + assert len(inputs) == 5 + assert {edge.source_full_node_id for edge in inputs} == { + *(f"m_session_{index}@1" for index in range(4)), + "buffer-session-alice@2", + } + assert len(graph.search_operations(category="boundary_detection")) == 1 + assert ( + len( + [ + edge + for edge in graph.get_all_edges() + if edge.source_full_node_id == "mc_1@1" + ] + ) + == 3 + ) + assert audit["removed_nodes"] == 1 and audit["added_buffer_edges"] == 1 + again, repeated = repair_payload(repaired, boundaries) + assert again == repaired + assert not repeated["cells"] + + +def test_repair_preserves_actual_membership_changes() -> None: + """A different message boundary is genuine history and cannot be collapsed.""" + original, boundaries = _legacy_graph() + changed = next( + node for node in original["data"]["nodes"] if node["full_node_id"] == "mc_1@2" + ) + value = json.loads(changed["value"]) + value["message_ids"] = value["message_ids"][:2] + changed["value"] = json.dumps(value, indent=2, sort_keys=True) + repaired, audit = repair_payload(original, boundaries) + assert repaired == original + assert not audit["cells"] diff --git a/tests/unit/test_properties/test_boundary_stateful.py b/tests/unit/test_properties/test_boundary_stateful.py index 6a378e164..270fb0edd 100644 --- a/tests/unit/test_properties/test_boundary_stateful.py +++ b/tests/unit/test_properties/test_boundary_stateful.py @@ -36,12 +36,10 @@ the ``quarantine`` track (nothing dropped, the session starts over), and the quarantine track holds exactly those ids. -Timestamps are unique per message, so ids are unique. ``gen_message_id`` is -deterministic in ``(session, timestamp_ms, index)`` by design (retries of -one payload dedupe through the buffer's primary key); two *different* -messages sent in separate calls with the same millisecond and index share -an id and the second is dropped as a duplicate -- a property of the id -scheme, outside this machine's domain and recorded separately. +Timestamps are unique per message, so ids are unique. ``message_ids`` is +deterministic in the session, the timestamp and what was said, so a resent +message keeps its id (the resend itself is pinned in +``tests/integration/test_memorize_resend.py``). A mid-call crash between the memcell insert and the buffer rewrite (the at-least-once case of #516) is not scripted either: the stage is not @@ -251,16 +249,23 @@ def _apply( def _fresh(self, session: str, msgs: list[tuple[str, str]]) -> list[dict[str, Any]]: out = [] - for idx, (role, text) in enumerate(msgs): + for role, text in msgs: self.next_ts += 1 ts = BASE_TS + self.next_ts + sender = "u" if role == "user" else "a" + request = { + "content": text, + "timestamp": ts, + "sender_id": sender, + "role": role, + } out.append( { - "id": ingest.gen_message_id(session, ts, idx), + "id": ingest.message_ids(session, [request])[0], "ts": ts, "role": role, "text": text, - "sender": "u" if role == "user" else "a", + "sender": sender, } ) return out diff --git a/tests/unit/test_properties/test_memorize_concurrency_jitter.py b/tests/unit/test_properties/test_memorize_concurrency_jitter.py index 947e87ad6..35bb9a38c 100644 --- a/tests/unit/test_properties/test_memorize_concurrency_jitter.py +++ b/tests/unit/test_properties/test_memorize_concurrency_jitter.py @@ -74,6 +74,7 @@ from everos.infra.persistence.sqlite._tables import Memcell from everos.memory.extract.boundary import BoundaryDetection from everos.memory.extract.boundary.quarantine import POISON_CALLS +from everos.memory.extract.ingest import message_ids from everos.memory.extract.pipeline import CellOutcome from tests.fakes import ( UNUSABLE_REPLY, @@ -219,8 +220,7 @@ async def _jittered( async def call(k: int, session: str, kind: str, n: int, pause: float) -> None: await asyncio.sleep(pause) msgs = [] - ids = [] - for idx in range(n if kind != "flush" else 0): + for _ in range(n if kind != "flush" else 0): next_ts[0] += 1 ts = BASE_TS + next_ts[0] msgs.append( @@ -231,10 +231,9 @@ async def call(k: int, session: str, kind: str, n: int, pause: float) -> None: "role": "user", } ) - mid = f"m_{session}_{ts}_{idx:03d}" - ids.append(mid) if next_ts[0] in run.poison_positions: run.poison_texts.add(f"m{next_ts[0]}") + ids = message_ids(session, msgs) payload = {"session_id": session, "messages": msgs} run.note(f"call#{k} {kind} {session} n={len(msgs)}") try: diff --git a/tests/unit/test_properties/test_memory_delete_jitter.py b/tests/unit/test_properties/test_memory_delete_jitter.py index 6064a3536..82db7e658 100644 --- a/tests/unit/test_properties/test_memory_delete_jitter.py +++ b/tests/unit/test_properties/test_memory_delete_jitter.py @@ -440,6 +440,7 @@ async def _add(world: _World, session: str, owners: tuple[str, ...]) -> None: episode_store=world.stores.episode, memcell_store=world.stores.memcell, instructions=bundled_instructions(), + language_llm=llm, episode_llm=llm, ) # The extraction model; sometimes slow enough for a whole session @@ -544,6 +545,7 @@ async def areflect(*args: Any, **kwargs: Any) -> AlgoEpisode: episode_index=_MdIndex(world), # type: ignore[arg-type] memcell_store=stores.memcell, report_store=stores.reflection_report, + profile_store=stores.profile, reflector=reflector, ) merged = await orchestrator.run(scope=_scope(owner)) @@ -932,6 +934,34 @@ async def _check(world: _World) -> None: crash=None, disk_full_at=None, ) +@example( # a skill listed, then removed by an agent deletion before it was read + first=[ + ("del_owner_session", "u1", "s1"), + ("skill",), + ("add", "s2", ("u2", "u3")), + ("reflect", "u3"), + ("del_session", "s1", False), + ("del_owner", "u3"), + ("skill",), + ("facts", "u3"), + ("facts", "u1"), + ("cluster", "u1"), + ("del_session", "s1", True), + ], + second=[ + ("cluster", "u3"), + ("del_owner", "u3"), + ("cluster", "u3"), + ("del_id", "u1"), + ("del_owner_session", "u1", "s2"), + ("cluster", "u1"), + ("skill",), + ("del_owner", "g1"), + ], + seed=257, + crash=None, + disk_full_at=2, +) def test_deletions_and_writers_keep_their_invariants( first: list[tuple[Any, ...]], second: list[tuple[Any, ...]], diff --git a/tests/unit/test_properties/test_merge_and_parse_laws.py b/tests/unit/test_properties/test_merge_and_parse_laws.py index 99df4e573..740b7190d 100644 --- a/tests/unit/test_properties/test_merge_and_parse_laws.py +++ b/tests/unit/test_properties/test_merge_and_parse_laws.py @@ -1,7 +1,9 @@ """Laws of the merge, rank and parse helpers on the memorize and search paths. 1. ``merge_dedupe_sort`` (boundary stage): the result is sorted by - ``(timestamp, message_id)``, holds each id once, its id set is the union + timestamp, rows sharing one keep arrival order (buffered first, in + buffer order, then new ones in request order -- ids carry no order since + #274), it holds each id once, its id set is the union of both inputs, a buffered message wins over a new one with the same id, and merging again changes nothing. ``buffered`` comes from a table keyed by ``message_id``, so it never holds an id twice; the law is stated on @@ -80,8 +82,12 @@ def test_merge_dedupe_sort_laws( buffered: list[CanonicalMessage], new: list[CanonicalMessage] ) -> None: merged = merge_dedupe_sort(buffered, new) - keys = [(m.timestamp, m.message_id) for m in merged] - assert keys == sorted(keys) + assert [m.timestamp for m in merged] == sorted(m.timestamp for m in merged) + arrival = {} + for m in [*buffered, *new]: + arrival.setdefault(m.message_id, len(arrival)) + keys = [(m.timestamp, arrival[m.message_id]) for m in merged] + assert keys == sorted(keys), "a tie keeps arrival order" ids = [m.message_id for m in merged] assert len(ids) == len(set(ids)) assert set(ids) == {m.message_id for m in buffered} | {m.message_id for m in new} diff --git a/tests/unit/test_service/test_build_providers.py b/tests/unit/test_service/test_build_providers.py index abcae0011..b411d8b36 100644 --- a/tests/unit/test_service/test_build_providers.py +++ b/tests/unit/test_service/test_build_providers.py @@ -91,13 +91,14 @@ def test_an_unconfigured_llm_fails_the_build(llm: LLMSettings) -> None: def test_every_task_is_built_from_llm_alone() -> None: - """One provider for the eleven extraction and search tasks, one for the decider.""" + """One provider for the extraction and search tasks; the language task and + the decider, which carry defaults of their own, get one each.""" llms = build_providers(_unconfigured()).llms clients = {f.name: getattr(llms, f.name) for f in dataclasses.fields(llms)} shared = {name for name, llm in clients.items() if llm is llms.boundary} - assert shared == set(clients) - {"decider"} - assert llms.decider is not llms.boundary + assert shared == set(clients) - {"language", "decider"} + assert len({id(llms.boundary), id(llms.language), id(llms.decider)}) == 3 def test_configured_optional_providers_are_built() -> None: diff --git a/tests/unit/test_service/test_delete_by_ids.py b/tests/unit/test_service/test_delete_by_ids.py index bd32a7432..5479f4fe8 100644 --- a/tests/unit/test_service/test_delete_by_ids.py +++ b/tests/unit/test_service/test_delete_by_ids.py @@ -3,6 +3,8 @@ from __future__ import annotations from collections.abc import AsyncIterator, Collection, Mapping, Sequence +from contextlib import AbstractAsyncContextManager +from types import TracebackType from typing import Any import pytest @@ -12,6 +14,7 @@ from everos.core.errors import DeletionIncompleteError from everos.infra.persistence.factories import build_stores from everos.infra.persistence.markdown import MarkdownEpisodeStore, MarkdownReader +from everos.memory import user_cluster_lock from everos.memory.deps import Stores from everos.memory.models import AtomicFact, Cluster, Episode from everos.memory.ports import NO_SOURCE_CHECK, MemoryRef, Scope @@ -241,6 +244,68 @@ async def test_dangling_member_detached_and_empty_cluster_deleted( assert await stores.cluster.get("cl_1") is None +class _ClusterLockProbe: + """The real owner lock, with a flag the fake cluster read can observe.""" + + def __init__(self) -> None: + self.inner: AbstractAsyncContextManager[None] | None = None + self.held = False + + async def __aenter__(self) -> _ClusterLockProbe: + assert self.inner is not None + await self.inner.__aenter__() + self.held = True + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + tb: TracebackType | None, + ) -> bool | None: + self.held = False + assert self.inner is not None + return await self.inner.__aexit__(exc_type, exc, tb) + + +async def test_cluster_committed_after_reverse_lookup_is_still_detached( + stores: Stores, monkeypatch: pytest.MonkeyPatch +) -> None: + """#597: a clustering pass can commit after the delete's reverse lookup. + + The lock probe makes the cluster visible only while the deletion holds the + owner's clustering lock, which is the state a racing clustering pass leaves + behind. The deletion must re-discover it there, or the deleted episode stays + a member forever. + """ + gone, keep = await _episodes(stores, _U1, "gone", "keep") + await _cluster(stores, [gone, keep]) + + probe = _ClusterLockProbe() + + def lock_factory(app_id: str, project_id: str, owner_id: str) -> _ClusterLockProbe: + probe.inner = user_cluster_lock(app_id, project_id, owner_id) + return probe + + monkeypatch.setattr("everos.service.memory._delete.user_cluster_lock", lock_factory) + find = stores.cluster.find_cluster_for_member + + async def find_after_lock( + scope: Scope, member_type: str, member_id: str + ) -> str | None: + if not probe.held: + return None + return await find(scope, member_type, member_id) + + monkeypatch.setattr(stores.cluster, "find_cluster_for_member", find_after_lock) + + await _by_ids(_deleter(stores), gone.id) + + cluster = await stores.cluster.get("cl_1") + assert cluster is not None + assert cluster.members == [keep.entry_id] + + async def test_unknown_ids_skipped_and_logged_without_note(stores: Stores) -> None: """B2 / B12: ids that match nothing are skipped; the log names hits and skips and never carries the note or any text.""" diff --git a/tests/unit/test_service/test_llm_task_wiring.py b/tests/unit/test_service/test_llm_task_wiring.py index 5703a2a0c..0edf43e40 100644 --- a/tests/unit/test_service/test_llm_task_wiring.py +++ b/tests/unit/test_service/test_llm_task_wiring.py @@ -1,8 +1,9 @@ """Every LLM consumer the bootstrap wires gets its own task's client. Each task is given a model of its own, then each consumer is asked which model -its client names: boundary detection, the episode and summary calls, agentic -search, the decider, the case gate, knowledge extraction, and the strategy +its client names: boundary detection, the language decision, the episode and +summary calls, agentic search, the decider, the case gate, knowledge +extraction, and the strategy dependencies (each strategy picking its own attribute is pinned beside it, in ``tests/unit/test_memory/test_strategies``). Startup logs where every task's settings came from, never the key, and warns when the deprecated ``[decider]`` @@ -70,6 +71,7 @@ def test_each_consumer_gets_its_own_tasks_client( build_application(settings) assert _model(boundary[0][-1]["llm"]) == "m-boundary" + assert _model(pipeline[0][-1]["language_llm"]) == "m-language" assert _model(pipeline[0][-1]["episode_llm"]) == "m-episode" assert _model(search[0][-1]["llm_client"]) == "m-search" assert _model(search[0][-1]["decider_client"]) == "m-decider" diff --git a/tests/unit/test_service/test_memorize_memtrace_hook.py b/tests/unit/test_service/test_memorize_memtrace_hook.py new file mode 100644 index 000000000..fb869f017 --- /dev/null +++ b/tests/unit/test_service/test_memorize_memtrace_hook.py @@ -0,0 +1,119 @@ +"""``MemoryService._memorize`` — MemTrace hook wiring on success and error.""" + +from __future__ import annotations + +import importlib +from collections.abc import Iterator +from types import SimpleNamespace +from typing import Any +from unittest.mock import AsyncMock + +import pytest + +from everos.memory.extract.trace import record_construction + +mm = importlib.import_module("everos.service.memory") + + +class _StubTracker: + def __init__(self) -> None: + self.enabled = False + self.calls: list[tuple[Any, ...]] = [] + self.error_calls: list[tuple[Any, ...]] = [] + self.events: list[dict[str, Any]] = [] + + async def on_memorize( + self, + payload: Any, + *, + is_final: bool, + defer_extraction: bool, + result: Any, + request_id: Any = None, + construction_events: Any = None, + ) -> None: + self.calls.append((payload, is_final, defer_extraction, result)) + self.events.extend(construction_events or []) + + async def on_memorize_error( + self, + payload: Any, + *, + is_final: bool, + defer_extraction: bool, + error: Any, + request_id: Any = None, + construction_events: Any = None, + ) -> None: + self.error_calls.append((payload, is_final, defer_extraction, error)) + self.events.extend(construction_events or []) + + +@pytest.fixture +def tracker(monkeypatch: pytest.MonkeyPatch) -> Iterator[_StubTracker]: + stub = _StubTracker() + monkeypatch.setattr(mm.MemoryService, "_memtrace_tracker", stub, raising=False) + monkeypatch.setattr(mm, "resolve_request_id", lambda: "request-1") + yield stub + + +def _service(run: Any) -> Any: + service = mm.MemoryService.__new__(mm.MemoryService) + service._memorizer = SimpleNamespace(run=run) + return service + + +async def test_success_calls_on_memorize_with_result( + tracker: _StubTracker, +) -> None: + result = mm.MemorizeResult(message_count=1, status="extracted") + service = _service(AsyncMock(return_value=result)) + + out = await service._memorize({"session_id": "s1", "messages": []}) + + assert out is result + assert tracker.error_calls == [] + assert len(tracker.calls) == 1 + _, is_final, defer_extraction, recorded = tracker.calls[0] + assert (is_final, defer_extraction) == (False, False) + assert recorded is result + + +async def test_failure_calls_on_memorize_error_and_reraises( + tracker: _StubTracker, +) -> None: + boom = RuntimeError("pipeline blew up") + service = _service(AsyncMock(side_effect=boom)) + + with pytest.raises(RuntimeError, match="pipeline blew up") as exc_info: + await service._memorize({"session_id": "s1", "messages": []}, is_final=True) + + assert exc_info.value is boom + assert tracker.calls == [] + assert len(tracker.error_calls) == 1 + _, is_final, defer_extraction, error = tracker.error_calls[0] + assert (is_final, defer_extraction) == (True, False) + assert error is boom + + +@pytest.mark.parametrize("fail", [False, True]) +async def test_actual_events_reach_both_hooks( + tracker: _StubTracker, fail: bool +) -> None: + tracker.enabled = True + + async def run(*args: Any, **kwargs: Any) -> Any: + record_construction("extraction_result", content="", owners=["alice"]) + if fail: + raise ValueError("write failed") + return mm.MemorizeResult(message_count=1, status="extracted") + + service = _service(run) + if fail: + with pytest.raises(ValueError, match="write failed"): + await service._memorize({"session_id": "s1", "messages": []}) + else: + await service._memorize({"session_id": "s1", "messages": []}) + assert len(tracker.events) == 1 + assert tracker.events[0]["content"] == "" + assert tracker.events[0]["phase"] == "extraction_result" diff --git a/tests/unit/test_service/test_memorize_unusable_reply.py b/tests/unit/test_service/test_memorize_unusable_reply.py new file mode 100644 index 000000000..0131851e9 --- /dev/null +++ b/tests/unit/test_service/test_memorize_unusable_reply.py @@ -0,0 +1,64 @@ +"""A cell whose extraction never got a usable LLM reply fails as an LLM error. + +An operator raises ``LLMOutputError`` when it rejects the model's reply, and +``retry_llm_output`` re-raises the last one. Leaving it as is turned +``/memory/flush`` into a 500 (#564); ``memorize`` re-raises it as an +``LLMServiceError``, which the API maps to a retryable 503. Any other +pipeline failure propagates unchanged. +""" + +from __future__ import annotations + +from typing import Any + +import pytest +from everalgo.llm import LLMOutputError + +from everos.core.errors import LLMServiceError +from everos.memory import IngestResult +from everos.memory.extract.boundary import BoundaryOutcome +from everos.memory.extract.pipeline import PreparedCell +from tests.fakes import make_memory_service + + +class _OneCellBoundary: + """A boundary stage that cuts one memcell on every call.""" + + async def detect(self, ingested: IngestResult, **_: Any) -> BoundaryOutcome: + return BoundaryOutcome( + cells=[object()], # type: ignore[list-item] + memcell_ids=["mc_1"], + per_cell_message_ids=[["m1"]], + per_cell_all_senders=[["u1"]], + status="extracted", + message_count=1, + ) + + +class _FailingPipeline: + def __init__(self, exc: Exception) -> None: + self._exc = exc + + async def run_cell(self, ingested: IngestResult, prepared: PreparedCell) -> Any: + raise self._exc + + +async def _flush(exc: Exception) -> None: + pipeline = _FailingPipeline(exc) + service = make_memory_service( + boundary=_OneCellBoundary(), user_pipeline=pipeline, agent_pipeline=pipeline + ) + await service._memorize({"session_id": "s1", "messages": []}, is_final=True) + + +async def test_unusable_reply_raises_llm_service_error() -> None: + reply_error = LLMOutputError("episode reply is not a valid _EpisodeReply") + with pytest.raises(LLMServiceError) as info: + await _flush(reply_error) + assert info.value.__cause__ is reply_error + assert "episode reply is not a valid _EpisodeReply" in str(info.value) + + +async def test_other_pipeline_failure_propagates_unchanged() -> None: + with pytest.raises(RuntimeError, match="disk full"): + await _flush(RuntimeError("disk full")) diff --git a/tests/unit/test_service/test_memory/test_input_log.py b/tests/unit/test_service/test_memory/test_input_log.py new file mode 100644 index 000000000..ff176269b --- /dev/null +++ b/tests/unit/test_service/test_memory/test_input_log.py @@ -0,0 +1,135 @@ +"""Input log writer for accepted /add requests (issue #537, first PR).""" + +from __future__ import annotations + +import hashlib +import json +from pathlib import Path + +from everos.config import InputLogSettings +from everos.infra.persistence import app_dir_name, project_dir_name +from everos.service.memory import InputLogWriter + + +def _payload(*, base64: str | None = None) -> dict: + content = [{"type": "text", "text": "hello"}] + if base64 is not None: + content.append({"type": "image", "base64": base64, "ext": "png"}) + return { + "app_id": "default", + "project_id": "default", + "session_id": "s1", + "messages": [ + {"role": "user", "sender_id": "u1", "timestamp": 1, "content": content} + ], + } + + +def _lines(root: Path) -> list[dict]: + files = list( + ( + root / app_dir_name("default") / project_dir_name("default") / ".input_log" + ).glob("*.jsonl") + ) + if not files: + return [] + return [json.loads(line) for line in files[0].read_text().splitlines()] + + +async def test_disabled_log_writes_nothing(tmp_path: Path) -> None: + writer = InputLogWriter( + root=tmp_path, + settings=InputLogSettings(enabled=False), + app_dir=app_dir_name, + project_dir=project_dir_name, + ) + await writer.log_add(_payload(), request_id="r1") + assert not ( + tmp_path / app_dir_name("default") / project_dir_name("default") / ".input_log" + ).exists() + + +async def test_enabled_log_appends_one_jsonl_line(tmp_path: Path) -> None: + writer = InputLogWriter( + root=tmp_path, + settings=InputLogSettings(enabled=True), + app_dir=app_dir_name, + project_dir=project_dir_name, + ) + await writer.log_add(_payload(), request_id="r1") + lines = _lines(tmp_path) + assert len(lines) == 1 + assert lines[0]["request_id"] == "r1" + assert lines[0]["session_id"] == "s1" + assert "received_at" in lines[0] + + +async def test_retention_sweeps_old_daily_files(tmp_path: Path) -> None: + directory = ( + tmp_path / app_dir_name("default") / project_dir_name("default") / ".input_log" + ) + directory.mkdir(parents=True) + old = directory / "2020-01-01.jsonl" + old.write_text("{}\n") + writer = InputLogWriter( + root=tmp_path, + settings=InputLogSettings(enabled=True, retention_days=1), + app_dir=app_dir_name, + project_dir=project_dir_name, + ) + await writer.log_add(_payload(), request_id="r1") + assert not old.exists() + assert len(_lines(tmp_path)) == 1 + + +async def test_large_attachment_is_replaced_by_length_and_sha(tmp_path: Path) -> None: + big = "A" * 5000 + writer = InputLogWriter( + root=tmp_path, + settings=InputLogSettings(enabled=True, max_inline_bytes=100), + app_dir=app_dir_name, + project_dir=project_dir_name, + ) + await writer.log_add(_payload(base64=big), request_id="r1") + + item = _lines(tmp_path)[0]["messages"][0]["content"][1] + assert item["base64"] is None + assert item["extras"]["base64_bytes"] == len(big) + assert item["extras"]["base64_sha256"] == hashlib.sha256(big.encode()).hexdigest() + + +async def test_large_string_content_is_retained(tmp_path: Path) -> None: + content = "x" * 500 + payload = _payload() + payload["messages"][0]["content"] = content + writer = InputLogWriter( + root=tmp_path, + settings=InputLogSettings(enabled=True, max_inline_bytes=100), + app_dir=app_dir_name, + project_dir=project_dir_name, + ) + await writer.log_add(payload, request_id="r1") + + lines = _lines(tmp_path) + assert len(lines) == 1 + assert lines[0]["messages"][0]["content"] == content + + +async def test_write_failure_does_not_escape(tmp_path: Path, monkeypatch) -> None: + writer = InputLogWriter( + root=tmp_path, + settings=InputLogSettings(enabled=True), + app_dir=app_dir_name, + project_dir=project_dir_name, + ) + + def _boom(*args: object, **kwargs: object) -> None: + raise OSError("disk full") + + monkeypatch.setattr(writer, "_append_sync", _boom) + await writer.log_add(_payload(), request_id="r1") # must not raise + + +def test_settings_default_is_disabled() -> None: + assert InputLogSettings().enabled is False + assert InputLogSettings().retention_days == 30 diff --git a/tests/unit/test_service/test_memtrace_lifecycle.py b/tests/unit/test_service/test_memtrace_lifecycle.py new file mode 100644 index 000000000..690ceac75 --- /dev/null +++ b/tests/unit/test_service/test_memtrace_lifecycle.py @@ -0,0 +1,38 @@ +"""Application shutdown performs the tracker's final markdown diff and export.""" + +from __future__ import annotations + +from types import SimpleNamespace +from unittest.mock import AsyncMock + +import pytest + +from everos.service import bootstrap + + +class _StubTracker: + def __init__(self) -> None: + self.sync_calls = 0 + + async def sync_now(self) -> None: + self.sync_calls += 1 + + +async def test_application_close_syncs_memtrace( + monkeypatch: pytest.MonkeyPatch, +) -> None: + tracker = _StubTracker() + monkeypatch.setattr(bootstrap, "shutdown_tracing", lambda: None) + app = bootstrap.Application.__new__(bootstrap.Application) + object.__setattr__(app, "_memtrace_tracker", tracker) + object.__setattr__(app, "_stack", SimpleNamespace(aclose=AsyncMock())) + object.__setattr__( + app, + "_admin", + SimpleNamespace(close_index=AsyncMock(), dispose=AsyncMock()), + ) + object.__setattr__(app, "_root_lock", SimpleNamespace(release=lambda: None)) + + await app._close_components() + + assert tracker.sync_calls == 1 diff --git a/tests/unit/test_service/test_search.py b/tests/unit/test_service/test_search.py new file mode 100644 index 000000000..5100caeb2 --- /dev/null +++ b/tests/unit/test_service/test_search.py @@ -0,0 +1,163 @@ +"""``MemoryService.search`` — MemTrace stage-trace wiring.""" + +from __future__ import annotations + +import importlib +from collections.abc import Callable +from dataclasses import dataclass +from typing import Any + +import pytest + +from everos.memory.search import SearchData, SearchMethod, SearchRequest, SearchResponse +from everos.memory.search.trace import record_stage + +search_mod = importlib.import_module("everos.service.memory") + + +@dataclass(frozen=True) +class _Candidate: + id: str + score: float + source: str + + +class _StubTracker: + def __init__(self, *, enabled: bool = True) -> None: + self.enabled = enabled + self.calls: list[tuple[Any, Any, Any]] = [] + self.error_calls: list[tuple[Any, Any, Any]] = [] + + async def on_search( + self, req: Any, resp: Any, *, stages: Any = None, request_id: Any = None + ) -> None: + self.calls.append((req, resp, stages)) + + async def on_search_error( + self, req: Any, *, stages: Any = None, error: Any = None, request_id: Any = None + ) -> None: + self.error_calls.append((req, stages, error)) + + +def _stub_manager( + resp: SearchResponse, record: Callable[[], None] | None = None +) -> Any: + class _StubManager: + async def search(self, req: Any) -> SearchResponse: + if record is not None: + record() + return resp + + return _StubManager() + + +def _service(manager: Any) -> Any: + service = search_mod.MemoryService.__new__(search_mod.MemoryService) + service._search_manager = manager + return service + + +def _req() -> SearchRequest: + return SearchRequest(user_id="alice", query="hi", method=SearchMethod.KEYWORD) + + +def _resp() -> SearchResponse: + return SearchResponse(request_id="r" * 32, data=SearchData()) + + +async def test_search_passes_collected_stages_to_tracker( + monkeypatch: pytest.MonkeyPatch, +) -> None: + resp = _resp() + tracker = _StubTracker() + service = _service( + _stub_manager( + resp, + record=lambda: record_stage( + "single_route", + "episode", + [_Candidate(id="ep_1", score=0.8, source="keyword")], + ), + ) + ) + monkeypatch.setattr( + search_mod.MemoryService, "_memtrace_tracker", tracker, raising=False + ) + monkeypatch.setattr(search_mod, "resolve_request_id", lambda: "request-1") + + out = await service.search(_req()) + + assert out is resp + assert len(tracker.calls) == 1 + _, _, stages = tracker.calls[0] + assert [(s.phase, s.kind) for s in stages] == [("single_route", "episode")] + assert [(c.id, c.score, c.source) for c in stages[0].candidates] == [ + ("ep_1", 0.8, "keyword") + ] + + +async def test_search_starts_from_a_fresh_collector_per_request( + monkeypatch: pytest.MonkeyPatch, +) -> None: + tracker = _StubTracker() + service = _service(_stub_manager(_resp())) + monkeypatch.setattr( + search_mod.MemoryService, "_memtrace_tracker", tracker, raising=False + ) + + record_stage("sparse", "episode", [_Candidate(id="x", score=0.1, source="keyword")]) + await service.search(_req()) + + assert len(tracker.calls) == 1 + assert tracker.calls[0][2] == [] + + +async def test_search_skips_collection_and_hook_when_tracker_disabled( + monkeypatch: pytest.MonkeyPatch, +) -> None: + tracker = _StubTracker(enabled=False) + + def _unexpected_collector() -> Any: + raise AssertionError("disabled tracing must not create a stage collector") + + service = _service(_stub_manager(_resp())) + monkeypatch.setattr( + search_mod.MemoryService, "_memtrace_tracker", tracker, raising=False + ) + monkeypatch.setattr(search_mod, "collect_search_trace", _unexpected_collector) + + out = await service.search(_req()) + + assert out is not None + assert tracker.calls == [] + + +async def test_search_error_invokes_error_hook_and_reraises( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A manager failure reaches ``on_search_error`` with the partial stages.""" + tracker = _StubTracker() + + class _FailingManager: + async def search(self, req: Any) -> SearchResponse: + record_stage( + "sparse", + "episode", + [_Candidate(id="ep_1", score=0.8, source="keyword")], + ) + raise RuntimeError("manager blew up") + + service = _service(_FailingManager()) + monkeypatch.setattr( + search_mod.MemoryService, "_memtrace_tracker", tracker, raising=False + ) + + with pytest.raises(RuntimeError, match="manager blew up"): + await service.search(_req()) + + assert tracker.calls == [] + assert len(tracker.error_calls) == 1 + req, stages, error = tracker.error_calls[0] + assert req.query == "hi" + assert isinstance(error, RuntimeError) + assert [(s.phase, s.kind) for s in stages] == [("sparse", "episode")] diff --git a/uv.lock b/uv.lock index 252b0fda8..501312f4b 100644 --- a/uv.lock +++ b/uv.lock @@ -575,7 +575,7 @@ wheels = [ [[package]] name = "everalgo-user-memory" -version = "0.9.0" +version = "0.10.1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "asgiref" }, @@ -583,14 +583,14 @@ dependencies = [ { name = "everalgo-core" }, { name = "pydantic" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/ff/a4/2caafdc04251aa5b3cb386c6dbc35ce052af6828ad836648d6e8d567e528/everalgo_user_memory-0.9.0.tar.gz", hash = "sha256:a77a251e4ea60aa646387fb8de15a08f98e75e0add354b810c25bf7f7d01a25d", size = 290132, upload-time = "2026-11-13T07:22:54.233Z" } +sdist = { url = "https://files.pythonhosted.org/packages/17/50/37988d354f3b2efe14b71c19a0f7f1e7839c77fe9411d4112e6a3619f963/everalgo_user_memory-0.10.1.tar.gz", hash = "sha256:75ad0e4ddc847cf0e08e2e32b5cfa54b71d9163a5a8a488e52e630d7bc2efd96", size = 298593, upload-time = "2026-11-20T06:47:52.516Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/63/9b/5e029f4d40122882f7801522c7098ba6f9f32f022aed89cc9e358f6774df/everalgo_user_memory-0.9.0-py3-none-any.whl", hash = "sha256:bde38fa94008c4d5b88c8284c368fba2dbef62e7fe269dd0a50b2efd4ae0b7d7", size = 137952, upload-time = "2026-11-13T07:22:53.074Z" }, + { url = "https://files.pythonhosted.org/packages/a8/a9/a723fd270f484a5a302c369d84ffe60e0b90433eac5df00cdbebb1ae3f49/everalgo_user_memory-0.10.1-py3-none-any.whl", hash = "sha256:e81b536a3c4356f9cca99714580bcf1ae61a902d0d1f7192b3465d0cec5d0d0a", size = 144409, upload-time = "2026-11-20T06:47:50.681Z" }, ] [[package]] name = "everos" -version = "1.7.0" +version = "1.7.1" source = { editable = "." } dependencies = [ { name = "aiosqlite" }, @@ -629,6 +629,9 @@ dependencies = [ ] [package.optional-dependencies] +memtrace = [ + { name = "smartcomment" }, +] milvus = [ { name = "pymilvus" }, ] @@ -659,6 +662,7 @@ dev = [ { name = "pytest-cov" }, { name = "pytest-rerunfailures" }, { name = "ruff" }, + { name = "smartcomment" }, ] [package.metadata] @@ -676,7 +680,7 @@ requires-dist = [ { name = "everalgo-parser", specifier = "==0.3.0" }, { name = "everalgo-parser", extras = ["svg"], marker = "extra == 'multimodal'", specifier = "==0.3.0" }, { name = "everalgo-rank", specifier = "==0.5.0" }, - { name = "everalgo-user-memory", specifier = "==0.9.0" }, + { name = "everalgo-user-memory", specifier = "==0.10.1" }, { name = "fastapi", specifier = ">=0.104.0" }, { name = "greenlet", specifier = ">=3.0" }, { name = "jieba", specifier = ">=0.42.1,<1.0" }, @@ -694,6 +698,7 @@ requires-dist = [ { name = "pymilvus", marker = "extra == 'milvus'", specifier = ">=3.0.0" }, { name = "python-multipart", specifier = ">=0.0.7" }, { name = "pyyaml", specifier = ">=6.0" }, + { name = "smartcomment", marker = "extra == 'memtrace'", specifier = ">=0.1.2" }, { name = "sqlmodel", specifier = ">=0.0.22" }, { name = "structlog", specifier = ">=24.0.0" }, { name = "textual", specifier = ">=8.2.7" }, @@ -702,7 +707,7 @@ requires-dist = [ { name = "watchdog", specifier = ">=4.0.2,<7" }, { name = "watchfiles", specifier = ">=0.21.0" }, ] -provides-extras = ["multimodal", "otel", "milvus", "nltk"] +provides-extras = ["multimodal", "memtrace", "otel", "milvus", "nltk"] [package.metadata.requires-dev] dev = [ @@ -720,6 +725,7 @@ dev = [ { name = "pytest-cov", specifier = ">=6.0.0" }, { name = "pytest-rerunfailures", specifier = ">=15.0" }, { name = "ruff", specifier = ">=0.8.0" }, + { name = "smartcomment", specifier = ">=0.1.2" }, ] [[package]] @@ -1344,6 +1350,19 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/b4/de/88b3be5c31b22333b3ca2f6ff1de4e863d8fe45aaea7485f591970ec1d3e/linkify_it_py-2.1.0-py3-none-any.whl", hash = "sha256:0d252c1594ecba2ecedc444053db5d3a9b7ec1b0dd929c8f1d74dce89f86c05e", size = 19878, upload-time = "2026-03-01T07:48:46.098Z" }, ] +[[package]] +name = "loguru" +version = "0.8.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "win32-setctime", marker = "sys_platform == 'win32'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/61/ce/b5bb93d4d9fc7a067f69140b3bb3782f6ad6360bc76e99b6e3d386cb1320/loguru-0.8.0.tar.gz", hash = "sha256:fb3e4623288e37700a0577f6e0ce776cc1860b5d95c657d67f07a2476b304867", size = 71232, upload-time = "2026-11-11T18:50:26.248Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c8/00/9ee7c8da7342b1a5524bca9d036f89e7d1d1e5a6345c9623763eeeac941f/loguru-0.8.0-py3-none-any.whl", hash = "sha256:e0fba09d6f76ba2d2f4bd1757122942f5a670c702e988b5efaeab99dacba0069", size = 69409, upload-time = "2026-11-11T18:50:24.148Z" }, +] + [[package]] name = "mako" version = "1.3.12" @@ -2527,6 +2546,19 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274", size = 11050, upload-time = "2024-12-04T17:35:26.475Z" }, ] +[[package]] +name = "smartcomment" +version = "0.1.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "loguru" }, + { name = "pydantic" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/0a/56/a101bfd9648f309e20145ef80110b9d0d77d14a3b3aca53fdd6b3b0816ba/smartcomment-0.1.2.tar.gz", hash = "sha256:3d745c06f849eccf759d895cbb295249b637ba8b86cbbe1df12fd0f18f751f08", size = 83041, upload-time = "2026-06-07T07:55:28.535Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/58/b7/d5cb57f675273313251684bea889aad53d300769e8eafc5ec48158a7270b/smartcomment-0.1.2-py3-none-any.whl", hash = "sha256:4585d83477d20074b8f4759c5a00f38c9475816ec34649ca6315625a4c095761", size = 66935, upload-time = "2026-06-07T07:55:26.806Z" }, +] + [[package]] name = "sniffio" version = "1.3.1" @@ -3060,3 +3092,12 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/9f/3e/28135a24e384493fa804216b79a6a6759a38cc4ff59118787b9fb693df93/websockets-16.0-cp314-cp314t-win_amd64.whl", hash = "sha256:b14dc141ed6d2dde437cddb216004bcac6a1df0935d79656387bd41632ba0bbd", size = 178531, upload-time = "2026-01-10T09:23:35.016Z" }, { url = "https://files.pythonhosted.org/packages/6f/28/258ebab549c2bf3e64d2b0217b973467394a9cea8c42f70418ca2c5d0d2e/websockets-16.0-py3-none-any.whl", hash = "sha256:1637db62fad1dc833276dded54215f2c7fa46912301a24bd94d45d46a011ceec", size = 171598, upload-time = "2026-01-10T09:23:45.395Z" }, ] + +[[package]] +name = "win32-setctime" +version = "1.2.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/1a/e4/f0f252c65f9bf7c4042b1f707ef338d49f799da582234e1d3e6e2cfca291/win32_setctime-1.2.1.tar.gz", hash = "sha256:077b35471bf1ff1d71e165c919ddc0cecf51b8e1802f5d820d33a96e2f6717dd", size = 4983, upload-time = "2026-10-25T18:21:32.318Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/bd/df/5593480bc1e932eeae28e4fa182ab68174edd0d77409ced3b6491d02d1d5/win32_setctime-1.2.1-py3-none-any.whl", hash = "sha256:a9edc685b35414bec69392c866ed82456ad125ac4a6a4b703ec1d8b462d4f477", size = 4215, upload-time = "2026-10-25T18:21:30.939Z" }, +]