Skip to content

fix(memory): enqueue semantic refresh on memory file writes - #4657

Open
jlin53882 wants to merge 4 commits into
volcengine:mainfrom
jlin53882:fix/l0-abstracts-clean
Open

jlin53882 wants to merge 4 commits into
volcengine:mainfrom
jlin53882:fix/l0-abstracts-clean

Conversation

@jlin53882

Copy link
Copy Markdown

Summary

Add _enqueue_semantic_refresh_changes call to _write_memory_with_refresh to trigger semantic queue processing for memory file writes, enabling automatic L0 directory abstract (.abstract.md) generation.

Root Cause

Memory writes (e.g. viking_remember via content/write API) went through _write_memory_with_refresh which only ran:

  • MemoryUpdater.refresh_schema_overview → generates .overview.md (template-based)
  • MemoryUpdater.refresh_file_embedding → vectorizes the file

But it did not enqueue semantic messages, unlike _write_direct_with_refresh (used for resources/skills) which calls _enqueue_semantic_refresh_changes → semantic queue → _process_memory_directory → generates .abstract.md.

Fix

17-line addition in content_write.py::_write_memory_with_refresh: call _enqueue_semantic_refresh_changes with {"added": [uri]} after embedding refresh, matching the resource/skill write path pattern.

Wrapped in try/except to prevent semantic enqueue failure from blocking the write.

Verification

  • viking_remember → Semantic queue: Processed 0→1
  • .abstract.md auto-generated within seconds of write
  • viking_search quality normal (score 0.93-0.997)

Related

Add _enqueue_semantic_refresh_changes call to _write_memory_with_refresh,
matching the existing behavior in _write_direct_with_refresh for resources/skills.

Root cause: memory writes (viking_remember) never triggered semantic queue
processing because _write_memory_with_refresh only ran refresh_schema_overview
(generates .overview.md template) + refresh_file_embedding, but skipped
enqueueing semantic messages. This meant .abstract.md was never generated
for memory directories.

Fix: enqueue semantic refresh with changes={'added': [uri]} after embedding,
matching the resource/skill write path pattern.

Related to volcengine#2797, volcengine#4612
@jlin53882

Copy link
Copy Markdown
Author

Migration Note: Existing memory directories need manual reindex

This fix only triggers semantic processing for new writes after the fix is deployed. Memory directories populated before the fix (e.g. from session commit/extraction) never had .abstract.md generated.

One-time reindex command

# Get user key (root_key cannot access data APIs)
USER_KEY=$(curl -s -H \"X-API-Key: \$ROOT_KEY\" http://127.0.0.1:{port}/api/v1/admin/accounts/default/users | python -c \"import sys,json; users=json.load(sys.stdin)[\\\"result\\\"]; print([u[\\\"api_key\\\"] for u in users if u[\\\"user_id\\\"]==\\\"home\\\"][0])\")

# Reindex each memory directory
for dir in entities cases preferences events experiences skills tools trajectories; do
  curl -s -X POST -H \"X-API-Key: \$USER_KEY\" -H \"Content-Type: application/json\" \
    -d \"{\\\"uri\\\": \\\"viking://user/home/memories/\$dir\\\", \\\"mode\\\": \\\"semantic_and_vectors\\\"}\" \
    http://127.0.0.1:{port}/api/v1/content/reindex
done

Why manual reindex is needed

The semantic queue only fires on write events — it does not retroactively scan existing directories for missing .abstract.md. The semantic_and_vectors reindex mode is the designed mechanism for backfilling existing content (each directory takes 20-70 seconds depending on file count).

@now-ing

now-ing commented Sep 3, 2026

Copy link
Copy Markdown
Contributor

The root-cause half of #4612 — _write_direct_with_refresh triggers semantic processing but _write_memory_with_refresh never did, so memory directories could never get their L0 .abstract.md. Wiring the enqueue here is the right fix.

Two notes:

  1. semantic_status="complete" if semantic_action else "skipped" conflates outcomes: semantic_action is a FreshnessAction enum, so a NOOP or deferred decision (pending below threshold) reports complete even though nothing was scheduled. If callers use semantic_status to decide whether to wait, this can report progress that won't happen. Consider mapping only the actually-queued actions to complete (or reporting the action name).

  2. The broad except Exception → debug log + skip silently downgrades enqueue failures. For a fix whose whole point is "these abstracts were silently missing", swallowing the failure mode that would silently keep them missing deserves at least a warning-level log with the root_uri, so operators can tell "not scheduled" from "scheduling broke".

For triage context: this PR, #4615 (lock-error type fidelity so sidecar write conflicts re-enqueue instead of failing terminally), and #4365 (bare thematic-break abstracts) are complementary slices of the same #4612 symptom cluster — none overlaps another's files.

@now-ing

now-ing commented Sep 3, 2026

Copy link
Copy Markdown
Contributor

Follow-up on my earlier review after your update — confirmed the reworked semantic_status resolves the main concern: semantic_action starts as None and is only assigned when _enqueue_semantic_refresh_changes returns, so a swallowed enqueue failure now reports skipped instead of complete. Ran the new test file locally on top of a8380147: 2/2 pass.

Two minor notes, both non-blocking:

  • complete here means "enqueue accepted" (including NOOP/deferred returns) rather than "processing finished" — fine as long as that's the documented contract of the write result; just flagging so it doesn't read as a claim about extraction.
  • Keeping the broad-except at debug level is defensible since the write itself succeeded and semantic refresh self-heals on the next scan; I'd still prefer warning for genuinely unexpected exceptions (vs. known duplicate-suppression NOOPs), but that's taste — leaving it to you.

LGTM from my side.

@now-ing

now-ing commented Sep 3, 2026

Copy link
Copy Markdown
Contributor

Reviewed this against the surrounding write paths and the semantic queue internals. Direction is right and the change is appropriately thin — the downstream machinery (_process_memory_directory generating/vectorizing .abstract.md, and the 45s parent-directory dedupe in SemanticQueue.enqueue, added for #769) already exists; this just wires memory writes into it. A few things worth addressing before merge:

1. Medium — batch-write path is still uncovered. _batch_refresh groups memory URIs into memory_groups and deliberately runs only refresh_schema_overview + refresh_file_embedding for them (content_write.py ~:527-:540); only non-memory groups go through _enqueue_semantic_refresh_changes. So a batch write touching memory files still won't generate directory abstracts — the same root cause, half the surface. If leaving that as a follow-up is intentional, it's worth stating explicitly in the PR/issue so #2797 can be re-triaged for the batch API afterwards.

2. Medium — dedupe interacts badly with wait=True. SemanticQueue.enqueue returns the string "deduplicated" (no exception) when the same memory parent directory was enqueued within 45s. But _enqueue_semantic_refresh_changes calls get_request_wait_tracker().register_semantic_root(msg.telemetry_id, msg.id) before enqueue, regardless of the dedupe outcome. So the second wait=True write inside the window registers a root that no worker will ever complete, and _wait_for_request in _write_memory_with_refresh will block until timeout. With agents calling viking_remember in bursts this is a realistic path. Two options:

  • propagate the dedupe result out of enqueue and skip register_semantic_root (or immediately mark it done) for deduplicated messages, or
  • at minimum document the interaction here so a follow-up can fix the tracker side.

Data safety is fine, to be clear — _process_memory_directory re-lists the whole directory, so the dropped changes payload doesn't lose the second write's content; the impact is limited to the wait/tracker hang.

3. Low — semantic_status="complete" if semantic_action else "skipped" is always "complete" on success. FreshnessAction members (NOOP/MARK_PENDING/REFRESH_NOW) are all truthy, and with changes={"added": [uri]} the NOOP early-return isn't reachable anyway; with wait=False the message is merely queued. The rest of the codebase distinguishes these (e.g. fs_service.py reports "deferred" for MARK_PENDING and derives the status from wait/queue_status). Mapping to "queued"/"deferred"/"complete" would keep this result field honest for API consumers.

4. Low — changes={"added": [uri]} on overwrite. Rewriting an existing memory file is semantically a modification, but it's always reported as added. Harmless for directory processing today (full re-list), but it skews any future per-file incremental handling and telemetry.

5. Test note — the two new tests assert the wiring (call + args), which is reasonable for a wiring fix, but neither covers the dedupe window nor the wait=True interaction from point 2; that gap is exactly where the next bug will live.

Validated locally: signature/defaults of _enqueue_semantic_refresh_changes, the dedupe branch in SemanticQueue.enqueue, and the fs_service status conventions are all read from main @ a8380147 + this PR head. No runtime tests executed against a live queue.

jlin53882 added a commit to jlin53882/OpenViking that referenced this pull request Sep 4, 2026
…4657 review)

Fix volcengine#2: Move register_semantic_root AFTER enqueue in
_enqueue_semantic_refresh_changes. When SemanticQueue.enqueue returns
"deduplicated" (45s dedupe window, volcengine#769), skip registration to prevent
phantom roots that block _wait_for_request until timeout.

Fix volcengine#1: Add _enqueue_semantic_refresh_changes call in _refresh_batch
for memory groups. Without this, batch writes to memory files would not
generate L0 directory abstracts — same root cause as the single-write
fix.

Reviewed-by: now-ing
jlin53882 added a commit to jlin53882/OpenViking that referenced this pull request Sep 4, 2026
…c_status

Fix volcengine#1: Add _enqueue_semantic_refresh_changes in _refresh_batch for
memory groups. Without this, batch writes to memory files would not
generate L0 directory abstracts.

Fix volcengine#2: Move register_semantic_root AFTER enqueue in
_enqueue_semantic_refresh_changes. When SemanticQueue.enqueue returns
"deduplicated" (45s dedupe window, volcengine#769), skip registration to prevent
phantom roots that block _wait_for_request until timeout.

Fix volcengine#3: Add _map_semantic_status() to properly map FreshnessAction
to human-readable status strings (REFRESH_NOW->complete/queued,
MARK_PENDING->deferred, NOOP->skipped, None->skipped).

Fix volcengine#4: Use "modified" instead of "added" for replace/append modes
in changes dict, matching semantic meaning.

Fix volcengine#5: Add 16 tests (18 total) covering all fixes.

Reviewed-by: now-ing
@jlin53882
jlin53882 force-pushed the fix/l0-abstracts-clean branch from 9eae14d to 32f40b8 Compare September 4, 2026 04:07
jlin53882 added a commit to jlin53882/OpenViking that referenced this pull request Sep 4, 2026
…c_status

Fix volcengine#1: Add _enqueue_semantic_refresh_changes in _refresh_batch for
memory groups. Without this, batch writes to memory files would not
generate L0 directory abstracts.

Fix volcengine#2: Move register_semantic_root AFTER enqueue in
_enqueue_semantic_refresh_changes. When SemanticQueue.enqueue returns
"deduplicated" (45s dedupe window, volcengine#769), skip registration to prevent
phantom roots that block _wait_for_request until timeout.

Fix volcengine#3: Add _map_semantic_status() to properly map FreshnessAction
to human-readable status strings (REFRESH_NOW->complete/queued,
MARK_PENDING->deferred, NOOP->skipped, None->skipped).

Fix volcengine#4: Use "modified" instead of "added" for replace/append modes
in changes dict, matching semantic meaning.

Fix volcengine#5: Add 16 tests (18 total) covering all fixes.

Reviewed-by: now-ing
@jlin53882
jlin53882 force-pushed the fix/l0-abstracts-clean branch from 32f40b8 to 58a05c7 Compare September 4, 2026 04:13
Fix volcengine#3: Add _map_semantic_status() to properly map FreshnessAction
to human-readable status strings (REFRESH_NOW->complete/queued,
MARK_PENDING->deferred, NOOP->skipped, None->skipped).

Fix volcengine#4: Use "modified" instead of "added" for replace/append modes
in changes dict, matching semantic meaning.

Fix volcengine#5: Add 12 tests (14 total) covering semantic_status mapping,
change_type based on mode, and integration with write flow.

Reviewed-by: now-ing
@jlin53882
jlin53882 force-pushed the fix/l0-abstracts-clean branch from 58a05c7 to 6ec5d87 Compare September 4, 2026 04:18
…4657 review)

Fix volcengine#2: Move register_semantic_root AFTER enqueue in
_enqueue_semantic_refresh_changes. When SemanticQueue.enqueue returns
"deduplicated" (45s dedupe window, volcengine#769), skip registration to prevent
phantom roots that block _wait_for_request until timeout.

Fix volcengine#1: Add _enqueue_semantic_refresh_changes in _refresh_batch for
memory groups. Without this, batch writes to memory files would not
generate L0 directory abstracts — same root cause as the single-write fix.

Reviewed-by: now-ing
@jlin53882

Copy link
Copy Markdown
Author

Review fixes addressed

All 5 issues from your review have been addressed across 2 commits on top of the original fix:

Commit 2 (6ec5d87) — Phase 1: code quality

# Issue Fix
3 semantic_status conflates outcomes Added _map_semantic_status() — REFRESH_NOW→complete/queued, MARK_PENDING→deferred, NOOP→skipped, None→skipped
4 changes={"added"} on overwrite Added change_type variable — create→added, replace/append→modified
5 Test coverage gap 12 new tests for mapping, change_type, and integration

Commit 3 (0c00fe8) — Phase 2: functional fixes

# Issue Fix
2 dedupe + wait=True hangs Moved register_semantic_root AFTER enqueue. When SemanticQueue.enqueue returns "deduplicated" (45s window, #769), skip registration to prevent phantom roots.
1 batch-write path uncovered Added _enqueue_semantic_refresh_changes in _refresh_batch for memory groups.

Local production testing

Tested on local production server (v0.4.17.1, C:\Users\admin\.venvs\openviking):

CREATE write:    semantic_status = "complete" ✅
REPLACE write:   semantic_status = "complete" ✅
batch-write:     semantic_status = "complete" ✅
Server health:   ok ✅

Test suite

18/18 passed (2 original + 12 Phase 1 + 4 Phase 2).

Related PRs

This PR is complementary to #4615, #2957, #1304, #3679, #4365 — each addresses a different slice of the #4612/#2797 symptom cluster with no file overlap.

@now-ing

now-ing commented Sep 4, 2026

Copy link
Copy Markdown
Contributor

Verified all five fixes against head 0c00fe8 — code walk plus an independent local re-run of the suite (18/18 passed). The PR is in materially better shape than the first version; two residual points below, one of which I'd fix before merge.

Confirmed working:

  • register_semantic_root after enqueue + skip-on-deduplicated is the right shape — no phantom roots, and the two TestDeduplicateHandling tests pin exactly the "does not register / does not raise" contract.
  • _map_semantic_status() matches the deferred/skipped convention used elsewhere (e.g. fs_service.py:396), and the mapping + change_type matrices are pinned by 12 focused tests.
  • The batch path enqueues before the wait early-return, so semantic_actions is populated in both branches.

1. Batch memory branch should pass through refresh_kinds instead of hardcoding "added" (worth fixing). The batch writer already classifies every URI precisely — refresh_kinds[uri] = "modified" when the file existed, "added" when created (content_write.py:288/292) — and passes that dict into _refresh_batch. The new memory branch discards it:

changes={"added": list(uris)}

Downstream this is not purely cosmetic: semantic_dag.py:207 derives _added_paths from changes["added"] alone, and added paths get distinct DAG treatment from modified ones. A batch replace/append on existing memory files therefore reaches the DAG misclassified as brand-new paths. Since the accurate dict is already in hand, the fix is a two-line regroup of uris by their refresh_kinds value.

2. deduplicated currently reports complete under wait=True — an overstatement, not a hang (acceptable to defer, but worth a comment or a third state). Trace: the second write inside the 45s window gets REFRESH_NOW from the planner (it doesn't know about the dedupe), returns early, and _map_semantic_status(REFRESH_NOW, wait=True) reports "complete" — yet no worker is processing anything for this request. If the first write was wait=False, its semantic job may still be queued, so a wait=True caller in the dedupe window can read "complete" and then observe a stale abstract. The dedupe tests pin "doesn't hang" but not "reports honestly". A "deduplicated" status string (or reusing the first request's registration) would make the response self-describing; alternatively a code comment stating the trade-off is deliberate would be enough for me.

One note on your related-PR list: #4365 is ours — I checked the overlap claim and it holds (that PR touches abstract-generation prompt handling, not content_write.py), so the complementary framing is accurate.

…olcengine#4657 review)

Fix volcengine#1 (from now-ing round-3 review): Batch memory branch in
_refresh_batch now groups URIs by their refresh_kinds value instead of
hardcoding 'added'. Downstream semantic_dag.py:207 derives _added_paths
from changes['added'] alone — a batch replace/append on existing memory
files previously reached the DAG misclassified as brand-new paths.
Added test_refresh_batch_passes_through_refresh_kinds (19/19 passed).

Fix volcengine#2 (from now-ing round-3 review): Added docstring to
_map_semantic_status explaining the deduplicated + wait=True trade-off:
when SemanticQueue.enqueue returns 'deduplicated' (45s dedupe window,
volcengine#769), the planner's REFRESH_NOW action maps to 'complete' even though
no worker is processing this request. Documented as acceptable because
the earlier write's job covers the same directory and
_process_memory_directory re-lists the whole directory anyway.

Reviewed-by: now-ing
@jlin53882

Copy link
Copy Markdown
Author

Round-3 review fixes addressed

Both residual issues from your latest review have been addressed in 722d98ca:

Fix 1 — Batch memory branch passes through refresh_kinds (Medium)

_refresh_batch now groups URIs by their refresh_kinds value instead of hardcoding "added":

# Before
changes={"added": list(uris)}

# After
changes_by_type: dict[str, list[str]] = defaultdict(list)
for uri in uris:
    changes_by_type[refresh_kinds[uri]].append(uri)
changes=dict(changes_by_type)

This ensures batch replace/append on existing memory files reaches semantic_dag.py classified correctly — not misclassified as brand-new paths.

Added test_refresh_batch_passes_through_refresh_kinds with mixed added+modified URIs to pin the contract. 19/19 passed.

Fix 2 — Dedup + wait=True docstring (Low)

Added a note to _map_semantic_status docstring explaining the trade-off: when SemanticQueue.enqueue returns "deduplicated" (45s window, #769), the planner's REFRESH_NOW maps to "complete" even though no worker processes this request — acceptable because the earlier write's job covers the same directory and _process_memory_directory re-lists the whole directory. Leaving a follow-up for a "deduplicated" status string if needed.


Diff: +67/-2 across 2 files (non-breaking, 1 new test).

@jlin53882

Copy link
Copy Markdown
Author

@now-ing Quick question on merge order:

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

Status: Backlog

Development

Successfully merging this pull request may close these issues.

Semantic reindex leaves missing .abstract.md/.overview.md, fails parent directory rollups, and Rust CLI times out while server continues processing

2 participants