[Bug]: strip_line_numbers() is not idempotent — line-number prefixes accumulate in merged memories
Issue Origin
Observed or reproduced in a real environment
Bug Description
strip_line_numbers() removes only one line-number prefix per line, while add_line_numbers() can be applied to content that already carries one. On the patch-merge path this makes prefixes accumulate in stored memory content: a card merged N times ends up as 1\t1\t1\t## Title.
every_line_has_line_numbers() uses the same single-prefix regex, so it reports True on content that still carries prefixes — the "aggressive stripping fallback" is therefore not reached.
Steps to Reproduce
from openviking.session.memory.utils.line_numbers import (
add_line_numbers, strip_line_numbers, every_line_has_line_numbers)
c = "## Title\n- fact one"
twice = add_line_numbers(add_line_numbers(c)) # '1\t1\t## Title'
s = strip_line_numbers(twice) # '1\t## Title' <-- one remains
every_line_has_line_numbers(s) # True
Expected Behavior
strip_line_numbers() is idempotent with respect to add_line_numbers(): stripping returns content with no line-number prefix, regardless of how many were applied.
Actual Behavior
One prefix survives per call. In stored memories this accumulates with each merge until the content becomes unreadable.
Minimal Reproducible Example
Observed on real stored memories (v0.4.16, entities schema, merge_op: patch). The number of surviving prefixes tracked the card version: version 1 → 0 prefixes, version 4 → 3, version 5 → 2. Cards never merged were always clean, and the session transcripts contained no numbered lines — confirming the prefixes are introduced by the merge path, not by the conversation.
Stored card after four merges:
1 1 1 ## Point Roadmap avec Steven
2 2 2 - Point avec Steven sur la roadmap
Error Logs
None — the corruption is silent.
OpenViking Version
v0.4.16
Python Version
3.13.15
Additional Context
Root cause: _LINE_NUMBER_PREFIX_RE = re.compile(r"^(\d+)\t") is anchored on ^, so re.sub matches at most once per line.
A minimal fix would be a separate repeated pattern used only by strip_line_numbers (leaving extract_start_line_number's capture group untouched):
_LINE_NUMBER_PREFIXES_RE = re.compile(r"^(?:\d+\t)+")
_LINE_NUMBER_PREFIXES_WITH_LEADING_SPACE_RE = re.compile(r"^(?:\s*\d+\t)+")
⚠️ One caveat we could not resolve from the outside: stripping all prefixes would also strip legitimate leading TSV columns (e.g. a stored table whose first cells are digits). Guarding add_line_numbers() against already-numbered input may be the safer place to fix this. We deliberately leave that design choice to you.
Workaround in the meantime: stripping all levels once is stable — after cleaning, two further merges and a fresh write produced zero prefixes.
Thanks for the report. The examples already show that the numbered prefixes are introduced by the merge path, not by the session transcript.
The key missing detail is the first merge where a clean stored card became prefixed with 1\t....
Could you share the raw patch operation from that merge, especially the search and replace fields before applying the patch?
From the code path, the first stored prefix would usually mean the content being written already had line-number prefixes before it was persisted.Seeing the first bad patch would let us confirm whether the prefix entered before patch application or was introduced during patch application, which determines the right place to fix it. If we can see whether that happens during create or update, we can fix the correct write boundary instead of only stripping already-polluted files.
Follow-up with the data you asked for. It partly contradicts your hypothesis, and it corrects two claims in my original report.
First, the bad news on the artifact you asked for. memory_diff.json does not carry search/replace. An operation only has uri, memory_type, before, after, deleted_content. So I cannot hand you the raw patch op from outside the server — only the exact before/after around each write. Over 3.5 days of real use (v0.4.16, entities + preferences + events, merge_op: patch) that is 52 writes that introduce prefixes.
1. It is not only the merge path. Four cards created on 2026-08-27 13:07 as adds, with no prior version at all, were persisted with two prefix levels already:
entities/développement/alec_henry.md adds 0 -> 3 numbered lines, level 0 -> 2
entities/développement/nicola_courtin.md adds 0 -> 3 numbered lines, level 0 -> 2
entities/développement/oussama_ammar.md adds 0 -> 3 numbered lines, level 0 -> 2
entities/développement/steven_poirier.md adds 0 -> 3 numbered lines, level 0 -> 2
A create cannot have gone through a patch merge, so at least one prefix is applied on the write path itself.
2. before is clean in 14 of the 52. The clearest one, entities/développement/point_roadmap_steven.md:
before (clean, 4 lines)
## Point Roadmap avec Steven
- Point avec Steven sur la roadmap
- Sujets à aborder : Search Console, Wix, Canva, archi mémoire, multitâche
- Priorité n°1 pour demain
after
1 ## Point Roadmap avec Steven
2 - Point avec Steven sur la roadmap
3 - Sujets à aborder : Search Console, Wix, Canva, archi mémoire, multitâche
4 - Priorité n°1 pour demain
5 - Ton WhatsApp pour Steven :
...
11 À tester très vite
1
Note the trailing bare 1 on the last line. The same card then went level 1 -> 2 -> 3 on the following merges.
3. It reproduces on a card that was clean. I stripped all levels from the stored cards once. Cards whose before is clean come back numbered on their very next write — the most recent occurrence is 2026-08-29 13:52, on preferences/noam/communication_style.md. So please disregard the "stripping all levels once is stable" workaround at the end of my original report: it was measured over too short a window and it is wrong.
4. Correction to my original report. I wrote that "cards never merged were always clean". Point 1 shows that is false. The version-to-prefix correlation I reported still holds for merged cards, but it is not the whole mechanism.
Taken together — prefixes on adds, a clean before yielding a numbered after, and that orphan 1 — this points at the write boundary rather than at patch application: the content handed to the persist step already carries numbers. That matches the direction you suggested, guarding add_line_numbers() against already-numbered input, rather than only making strip_line_numbers() idempotent. Both may be needed, since the accumulation on merged cards is real too.
I can dump the full 52-row before/after table, or the raw memory_diff.json files for any of the cards above, if that helps pin down the exact call site.
Could a maintainer weigh in on which fix for this should be pursued? There are currently two open PRs approaching it from different angles, neither with a review.
- #4424 (
3daa673a5): scoped to the accumulation mechanism: makesstrip_line_numbers()remove repeated prefixes. Small and self-contained, 7 lines plus a test. - #4618 (
a4e618f80): starts from the same idempotency fix, then covers the write paths as well. Prefixes are stripped only when the SEARCH block is itself fully numbered, which is the one available evidence that the content was copied from a numbered read view. Every other path stores verbatim.
They overlap rather than conflict: #4424 is roughly the first commit of #4618.
Both authors have been responsive and both branches are in good shape, but
v0.4.18, v0.4.19 and v0.4.20 have each shipped with strip_line_numbers() still
in its original single-pass form. Anyone on a release build is still
accumulating prefixes.
Two things I can offer, having tested both branches in an isolated container against the v0.4.17.1 and v0.4.18 runtimes:
Shape-based detection of "is this a numbered view?" is not viable on the write
path. An intermediate commit on #4618 tried it and deleted real data:
'2024\t17\n2025\t19' became '17\n19'. Requiring the run to start at 1
doesn't help, since a quarter index is consecutive and 1-based. That's what
pushed #4618 toward the SEARCH-evidence rule.
Whichever lands, existing damage needs a separate cleanup. Neither PR rewrites already-stored cards, and under the #4618 rule the paths that were incidentally cleaning them stop doing so, so a store that looks like it is self-healing today will stop once the fix lands. A one-time pass or a release note would save people the surprise.
Happy to re-test whichever direction is preferred.
Independent reproduction on v0.4.23 — via ov compile --skill memory, not session extraction
Adding a data point on a release build, because the discussion above has focused on the session-extraction path and the maintainer asked specifically for the first bad write.
Environment: self-hosted ghcr.io/volcengine/openviking:v0.4.23, single Linux host, Docker, local vectordb, extraction_output_format: json, output_language_override: zh-CN. No source patches — official image only.
The trigger that has not been reported yet: ov compile --skill memory
I ran the v0.4.23 in-place memory consolidation on one memory type:
ov compile --to viking://user/<user>/memories/entities --skill memory
Task completed in 67s: total_adds: 0, total_updates: 5, total_deletes: 0, errors: [].
All 5 updated files came back fully line-numbered, written straight to durable storage:
$ head -2 'memories/entities/apriso operation/nms_reworkrepair_126_oprsequencce.add.md' | cat -A
1^I# NMS_ReworkRepair_126_Oprsequencce.ADD$
2^I$
Hex confirmation of the first bytes (1 \t #):
0000000 1 \t # N M S _ R e w o r k R e
So this is not only reachable from session commit / patch merge — --skill memory consolidation reaches it too, on a build released after v0.4.18/19/20 that still ships the single-pass strip_line_numbers().
What I can confirm about the mechanism
The exact-match fast path in patch_handler.py is the gate I can see firing. Around openviking/session/memory/merge_op/patch_handler.py:471:
has_line_numbers = (
every_line_has_line_numbers(search_content)
and every_line_has_line_numbers(replace_content)
) or (every_line_has_line_numbers(search_content) and replace_content.strip() == "")
if has_line_numbers:
search_content = strip_line_numbers(search_content)
replace_content = strip_line_numbers(replace_content)
When the model numbers only one side of the pair, the conjunction is false, the branch is skipped, and the numbered text is stored verbatim. In my 5 files the surviving prefix count was 1 on every line — consistent with the "one side numbered" case rather than repeated accumulation.
This is the same asymmetry @Backroads4Me describes from the other direction: with only one side numbered there is no evidence rule to consult, so nothing is stripped.
Supporting evidence from my store
- 30 files were already polluted before I ran anything (found by scanning for
^\d+\t), accumulated silently across September. Only 5 were added by my--skill memoryrun, so the write path had been leaking for weeks on this deployment. - Pollution is still live. After I cleaned all 26 affected files to zero, 6 new files appeared numbered within the next 45 minutes (mtime
09:47:08) with noov compileinvoked by me — plain ongoing extraction. - Consistent with @nono-proW6's correction #4: I also saw files whose
beforestate was clean come back numbered, and I saw numbering introduced on newly written files, not just merged ones.
Cleanup note relevant to whatever fix lands
@Backroads4Me's closing point matches what I observed in practice: cleaning stored cards is a separate, one-time operation. I stripped prefixes on 26 files by rewriting storage directly (the content/write API round-trip is not usable for this — see below), and the store does not stay clean on its own.
One operational hazard worth recording for anyone doing the same cleanup — POST /api/v1/content/write with mode: "replace" on a memory URI is not a safe read-modify-write primitive:
GET /api/v1/content/read?raw=truereturns the body plus theMEMORY_FIELDStrailer, and it linkifiesviking://URIs inside JSON string values ("resource_uri": "viking://..."came back as["resource_uri": "](viking://...)).- Writing that straight back duplicates the
MEMORY_FIELDSblock (I reproduced 2 blocks on 20 files; the second block was a re-serialization of the first) and persists the linkified URIs. - Also, a URI containing a space is normalized on write (
agent skill→agent_skill), silently creating a duplicate directory instead of updating the original.
None of that is this bug, and I mention it only because "clean up the polluted cards with the public write API" is the obvious move and it corrupts files. I have not filed it separately; happy to if it is wanted.
Version
- OpenViking
v0.4.23(Docker, official image; release tag SHAdf32bf6e50a40843438f9491a26069ca4bd08f1f) - Python
3.13.15(bundled in image) - Model backend: OpenAI-compatible
Expected
Per the existing analysis: strip_line_numbers() idempotent plus evidence-based cleanup on the remaining write paths, with the one-numbered-side case covered. Since --skill memory exercises the same write boundary, it should be covered by the same fix — I am not proposing a separate path.
I am not attaching my memory contents; the excerpts above are synthetic-safe and the paths are generic. I still have the before/after of the 26 cleaned files plus the 20 duplicated-trailer files if a maintainer wants the raw artifacts — including the orphan-trailing-1 pattern @nono-proW6 described, which I also saw.