Skip to content

feat(memtrace): add smartcomment execution tracing - #612

Open
gdshjzm wants to merge 15 commits into
EverMind-AI:mainfrom
gdshjzm:feat/memtrace-smartcomment
Open

gdshjzm wants to merge 15 commits into
EverMind-AI:mainfrom
gdshjzm:feat/memtrace-smartcomment

Conversation

@gdshjzm

@gdshjzm gdshjzm commented Nov 19, 2026

Copy link
Copy Markdown

feat(memtrace): add smartcomment execution tracing

Summary

This PR adds optional MemTrace-compatible execution-graph tracing to EverOS using smartcomment.

It instruments the add, flush, and search paths to capture memory construction and retrieval behavior, including request failures, boundary decisions, extraction evidence, message-buffer changes, per-stage retrieval candidate pools, and answer/evaluation chains.

The tracker is integrated through application-scoped dependency injection, without introducing a process-wide singleton or changing the default memory-path behavior when tracing is unavailable.

Changes

Execution-graph tracing

  • Add everos.infra.memtrace, backed by the optional smartcomment dependency.
  • Export MemTraceBench-compatible JSON execution graphs.
  • Record variables, operations, versions, mutations, and dependency edges.
  • Preserve graph state across restarts and reconcile file changes that occur while the process is stopped.
  • Record answer generation and evaluation chains for downstream attribution.

Request and lifecycle integration

  • Instrument /memory/add, /memory/flush, and /memory/search.
  • Capture failed requests with request-level error operations and propagated request IDs.
  • Inject the tracker through application bootstrap rather than importing infra from service use cases.
  • Log tracker status during startup and perform a final markdown diff and graph export during shutdown.

Construction and retrieval evidence

  • Record buffer loading and persistence events.
  • Preserve parsed boundary decisions and exact memcell/message relationships.
  • Capture episode extraction attempts, results, and persisted entry IDs.
  • Add request-local collectors for construction and search-stage evidence.
  • Record sparse, dense, single-route, MaxSim, hierarchy, fusion, bridged-skill, and agentic retrieval stages.
  • Include candidate-pool truncation metadata and explicit stage dependencies.

Dependencies, examples, and documentation

  • Add the memtrace optional dependency:
    memtrace = ["smartcomment>=0.1.2"]
  • Update uv.lock.
  • Add MemTrace examples for graph export, merging, QA injection, attribution, repair, and visualization.
  • Add instrumentation and attribution documentation.
  • Add comprehensive unit coverage for tracing behavior and graph topology.

Configuration

Install the optional dependency:

uv sync --extra memtrace

Configuration is environment-based:

  • EVEROS_MEMTRACE_ENABLED=1 enables tracing; this is the default.
  • EVEROS_MEMTRACE_ENABLED=0 disables tracing.
  • EVEROS_MEMTRACE_DIR overrides the graph export directory.

When smartcomment is unavailable or tracing is disabled, the hooks are no-ops. Tracing failures are logged and do not interrupt memory operations.

For multi-worker deployments, use a single writer or assign each worker a separate EVEROS_MEMTRACE_DIR, since processes maintain independent in-memory graph instances.

Validation

  • make lint — passed, including all 14 architecture contracts.
  • make docs-check — passed.
  • make package — passed, including wheel and sdist smoke tests.
  • MemTrace-focused tests — 255 passed.
  • Bootstrap, queue, and API tests — 309 passed.
  • make integration — 229 passed, 9 skipped.
  • Private-key, merge-conflict, large-file, whitespace, and EOF checks — passed.

Unrelated upstream test issue

The full unit run completed with 4265 passed, 4 skipped, and 1 failure in:

tests/unit/test_properties/test_memory_delete_jitter.py::
test_deletions_and_writers_keep_their_invariants

The same failure was reproduced on unmodified origin/main using the same locked dependencies and Hypothesis seed:

146452175139249657157320773885722710309

This confirms that the concurrency-deletion failure is pre-existing and unrelated to the MemTrace changes.

@gloryfromca gloryfromca left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Blocking: the default required unit-test environment cannot collect the new MemTrace tests.

I found one blocker inline. With the memtrace extra installed, all 255 changed test modules pass. In the default frozen environment used by the required Linux, Windows, and Python 3.13 unit jobs, collection fails because SmartComment is absent.

Covered: CLAUDE.md and all repository rule files; the complete diff and production callers; the branch's one-commit history; backward compatibility and optional-disabled behavior; whether existing tests were weakened; and architecture constraints. git diff --check, Ruff, format checking, all 14 import-linter contracts, datetime discipline, and singleton checks pass.

Comment thread pyproject.toml Resolved
Kendrick-Song and others added 12 commits November 20, 2026 10:16
* docs(benchmarks): add LoCoMo results page with model configs

Move LoCoMo's detailed results out of benchmarks/README into
benchmarks/locomo.md and its Chinese mirror: accuracy and search time
by retrieval method, batch against step boundary detection, and
accuracy and write / search latency across models per stage, with
every run's scores and the latency detail in an appendix.

The benchmarks README keeps the results table, links LoCoMo from it
and lists the detail page under "More results". The top-level README,
docs/configuration.md and docs/index.md point to the new page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(benchmarks): lead the LoCoMo page with a model x method table

Open benchmarks/locomo.md with one table of accuracy for every
retrieval method across seven model configurations. hybrid, vector and
keyword call no LLM, so they share one search time pooled over every
configuration; agentic's search time follows its model and sits next
to each score.

Under the table: what each column runs, what each retrieval method
does, how scores and times were taken, and the differences a corrected
paired bootstrap supports. The published configuration's write time is
given per message, as step detection makes one boundary call per
message, apart from the batch configurations. Times measured while
qwen3-235b answered slowly carry a footnote next to them. The appendix
uses the first table's column names and order, and adds hybrid runs
and write and search latency for the gpt-5.4-mini per-stage
configuration.

Links to the page point at the new table, and the decider link at
Batch or step.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(benchmarks): state needed keys per retrieval method

The prerequisites tied the DeepInfra key to benchmarks (LoCoMo needs
both models, the other three only embedding), but what a run needs
follows from its retrieval methods. List them by method, as
preflight.py checks them: vector, hybrid and llm_multiround need the
embedding model, agentic also the reranker, keyword neither. Name the
default models, drop the benchmark tags from the method table and the
rerank variable row, and note that every method needs the LLMs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs: show benchmark results first and on the front page

The benchmarks README opened with setup and kept its results as step 6,
near the end. Lead with them instead, as Results, and retitle the page
Benchmarks; the numbered steps keep their order. Every link to the old
anchor points at the new one.

The front page README had no benchmark numbers. Add a Benchmarks
section after Why EverOS, in both languages, with the four headline
scores and their answer models, and link LoCoMo's detail page and the
reproduction guide.

docs/configuration.md repeated LoCoMo's batch and step scores; keep its
trade-off table and point to benchmarks/locomo.md for the scores, so
they live in one place.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(tui): pin demo conversation to newest line with anchor()

_record_line kept the newest line in view with scroll_end(), which
defers the scroll until after a screen refresh. Static.update() only
marks the log for layout; the Layout message reaches the screen when
the Static's own message pump goes idle. When the screen ran the
deferred callbacks first, they read the stale max_scroll_y (0), so the
panel stayed at the top for good. Slowing the log's message dispatch
by 5ms reproduces this every time; it is the Windows unit job failure
"assert 0.0 == 13".

Re-anchor the panel on every line instead: an anchored container is
pinned to the bottom inside the layout pass that sizes the new line,
and re-anchoring brings back a reader who scrolled up, as before.

The test now waits for the outcome with a bounded pause loop instead
of a fixed pause count, and also checks that a new line re-pins a
panel the reader scrolled up.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(config): say what rerank's provider picks, list dashscope

Every model section names its service by base_url, and the LLM,
multimodal and embedding endpoints all speak the OpenAI-compatible
protocol. Rerank endpoints share no request format, which is why
[rerank] alone also takes provider. Say so in docs/configuration.md
and default.toml, and list all three values with the request each one
sends: the docs and the template comment named deepinfra and vllm but
not dashscope, which the factory has accepted since it was added.

The rerank api_key is required except for a self-hosted vllm server,
as the factory checks; the field table now says so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(benchmarks): narrow the LoCoMo appendix to what it lists

The appendix said it held every number behind the tables above, but the
batch side of the Batch or step comparison is summarized there only.
Say what it does hold: the numbers behind the results table and the
latency sections.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(changelog): note the demo conversation fix

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
…Mind-AI#615)

* feat!: decide each memcell's episode language before writing it

A memcell with a user sender first asks everalgo's LanguageDetector
(everalgo-user-memory 0.10.0), on the new `language` LLM task, which
language its conversation is carried on in: Chinese, Japanese or
English, any other language as English. The episode is extracted in
that language and stores it, so its summary, atomic facts and a first
profile follow it. The decision is made once per memcell, outside the
episode retries, and never fails the write: no chat text, a timeout or
an unusable reply leaves the language to the episode model, and the
stored language is read off the episode text as before.

[llm.language] defaults to temperature 0, 64 output tokens, a 3-second
timeout and no retries, so a synchronous add waits at most 3 seconds
longer per memcell.

Reflection writes a merge in the owner's frozen profile language, else
in the language more than 60% of the merged episodes stored, else in
the one read off the merged text; the merged episode stores it and its
facts follow it. An unreadable user.md falls back to the vote instead
of failing every owner's run.

The episode, atomic-fact, profile and reflection log lines name the
language used and where it came from.

BREAKING CHANGE: UserMemoryPipeline takes language_llm and
ReflectionOrchestrator takes profile_store.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: read an agent skill file removed mid-read as absent

AgentSkillReader checked that a file exists, then read it. An owner
deletion moves the agent's whole directory away under the owner's lock,
which reads do not take, so a file could go between the two steps and
the read raised FileNotFoundError, failing the extract_agent_skill run.
read_main, list_by_cluster, read_reference and read_script now share one
read that returns None when the file is gone at either step, as the
other markdown readers already treat a file that vanished; the existence
check stays as the fast path for a missing path or a directory.

The delete-jitter property test keeps the interleaving that exposed it
(seed 257) as an example.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* build: bump everalgo-user-memory to 0.10.1

0.10.1 changes only LanguageDetector's prompt: a few words of another
language (names, places, brands, terms, short phrases) no longer decide
a conversation's language, with a worked example of an English exchange
carrying two Chinese words. The API is unchanged. The CHANGELOG entry
and docs/how-memory-works.md describe the rule.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
…verMind-AI#580)

Some OpenAI-compatible models (DeepSeek in JSON mode, for one) end an
object or array with a trailing comma. Strict validation rejects it, and
resending the identical request tends to get the same reply back.
OpenAIProvider now validates such a reply once more with the trailing
commas removed (string contents untouched) and returns the repaired text.

When an operator still rejects every reply, memorize re-raised the bare
LLMOutputError, which no API error rule maps, so /memory/flush answered
500. It is now re-raised as LLMServiceError, the existing retryable 503.

Fixes EverMind-AI#564

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
…d-AI#614)

ProfileReader checked is_file() and then read the file. A deletion can
remove it between the two calls; the reader then raised FileNotFoundError
into profile extraction instead of returning the normal "not yet written"
result. Catch only that missing-file race and return None.

The deterministic test removes the file from the is_file() hook, so it
fails on the previous code and pins the fix.

Refs EverMind-AI#597.
The log is independent of extraction: one JSONL line per accepted /add,
written in the route before the sync/async split, at
<root>/<app>/<project>/.input_log/YYYY-MM-DD.jsonl (outside .index).

It is disabled by default. When enabled it applies retention_days, keeps
text verbatim while replacing large base64 attachments with length +
SHA-256, and logs write failures without failing /add. Deletion and purge
integration, plus the default-on switch, follow in the second PR.

Refs EverMind-AI#537.
…#613)

The cascade section described a 500 ms debounce that the watcher does
not have, and LSN-based crash recovery that the ledger does not implement.
Watcher events enqueue directly; recovery resets orphaned processing rows
and lets the scanner reconcile the tree.

Refs EverMind-AI#542.
)

* test(purge): fix seed profiles and stale boundary holds

The purge acceptance suite had drifted from main since the everalgo
2026-11 line (EverMind-AI#595) and the per-owner profile split (EverMind-AI#600):

- The seed failed its own P0 check: the profile builds only from
  episodes that name their owner, and the fake narrative is about
  "Alice" while the seeded users had no name. The seeded user is now
  called Alice. This unblocks every case, T15.1 included.
- T22.1 and T35.1a held the boundary call by its old reply model name
  `_BatchReply`, renamed `Reply`; they now take it from
  USER_TRACK_OPERATORS.
- T22.2 and T8.1 relied on an add without a flush cutting a memcell;
  the fake boundary no longer cuts by default, so each test scripts a
  cut for its own messages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(purge): keep the backlog cases' in-scope runs off the blocker

T9.1, T24.1 and T24.2 held one (a2, p1) run in the only OME slot until
the purge of (a1, p1) had succeeded. With profiles seeded, the backlog
talk also starts an extract_user_profile run of (a1, p1); a strategy
that takes a partition lock hands its slot back while it takes the lock,
so that run stayed started behind the held blocker, and the purge,
which waits for every started in-scope run, timed out in its drain.

The cases now run two slots: the (a1, p1) case extraction is held in one
while the rest of its talk finishes in the other, and only then are two
(a2, p1) extractions held, so both slots are (a2, p1)'s and the case's
follow-up waits in the queue unstarted, as the cases intend.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: zhanghui <23442919+gloryfromca@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
…I#599)

The by-id deletion resolved clusters before acquiring the owner clustering lock. A clustering pass that had already checked its source could commit between that lookup and the lock, leaving the deleted episode in the new cluster.

Move discovery and reconciliation under the same lock, and add a deterministic regression test that makes the cluster visible only while the lock is held.
…-AI#609)

* fix(memorize): drop resent messages a memcell already holds

A client that retries /memory/add after a timeout resends messages the
first call may have cut into a memcell. Deduplication only looked at the
session buffer, which a cut empties, so the retry cut them again: a
second memcell and episode with the same messages (EverMind-AI#274).

The boundary stage now drops fresh messages that a memcell of the
session already lists. The memcell rows are the record: the cut inserts
them in the same transaction that empties the buffer, and a session
delete removes them, so no new table or extra write is needed.

Message ids no longer depend on where a message sits in its request:
m_<session>_<ts>_<n>_<digest>, n counting the request's messages that
share the timestamp (so they keep their order) and digest covering
sender_id, role, content, tool_call_id and tool_calls. A regrouped
resend keeps its ids, and two different messages sent in separate
requests with one timestamp no longer share an id (the second used to
be dropped).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(memorize): derive the jitter test's message ids

The concurrency jitter property test built message ids by hand in the
old m_<session>_<ts>_<idx> format; it now asks ingest.message_ids.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(memorize): keep message ids stable across split resends

The id carried the message's position among same-millisecond messages of
its request, so resending [A, B] as [B] gave B a new id and it could be
cut into a second memcell. The id is now session + timestamp + a digest
of who said what; a verbatim repeat within one request adds its repeat
count to the digest. Order among same-millisecond messages is kept by a
stable timestamp sort and by reading buffered rows in write order.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: zhanghui <23442919+gloryfromca@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

@gloryfromca gloryfromca left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

No blockers; this can merge as far as I am concerned.

The new commit fixes the prior required-CI collection failure by adding SmartComment to the default dev dependency group while preserving it as an optional runtime extra. uv sync --frozen and all 255 changed tests pass without selecting --extra memtrace; git diff --check also passes. I reviewed the two-file delta against the full change and relevant CI/dependency callers, and rechecked the repository rules, backward compatibility, test strength, history, and architecture constraints covered in the first round. My prior thread is resolved.

# Conflicts:
#	src/everos/memory/extract/boundary/detection.py
#	src/everos/memory/extract/pipeline/user_memory.py
#	src/everos/memory/search/manager.py
#	src/everos/service/bootstrap.py
#	src/everos/service/memory/__init__.py

@gloryfromca gloryfromca left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Blocking: resend filtering and three-lane HYBRID must preserve truthful MemTrace provenance.

The merge onto current main resolves the five code conflicts cleanly for business behavior, but two ordinary new-main paths now export execution graphs that contradict what actually happened; both are marked inline. I reproduced each mismatch directly.

Validation: all 267 changed tests pass; the two resend integration tests pass; git diff --check, Ruff, format checking, and all 14 import-layer contracts pass. Covered this round: repository guidance; the full branch diff against refreshed origin/main; conflict-resolution callers and merge history; backward compatibility and the prior dependency fix; test-strength changes; and architecture constraints.

Comment thread src/everos/memory/search/manager.py Resolved
Address review on the merge onto current main:

- detection: emit the authoritative buffer_loaded snapshot when
  _not_yet_cut filters every fresh row (timeout resend). Without it the
  tracer fell back to appending the resent request messages to the graph
  buffer although the session buffer never changed.
- search: record the atomic-fact HYBRID lane (maxsim_atomic) and wire it
  into the rrf stage inputs, so every fused candidate has a recorded
  input lane.

@gloryfromca gloryfromca left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

No blockers; this can merge as far as I am concerned.

Revision 607dc25 fixes both provenance defects: fully filtered resends now supply an unchanged authoritative buffer snapshot, and episode HYBRID records the atomic-fact lane as an explicit input to rrf. I reran both original reproductions and confirmed the exported behavior, not only the new assertions.

Validation: all 269 changed tests and both resend integration tests pass; git diff --check, Ruff, format checking, and all 14 import-layer contracts pass. I reviewed the focused delta, its callers and history, repository guidance, backward compatibility, test strength, and architecture constraints. All threads I opened are resolved.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants