[Bug] Memory extraction fails with failure_kind=parse_error when the model wraps operations in a fenced code block
Issue Origin
Observed in a real local deployment (OpenViking v0.4.22, macOS), 2026-09-30 ~20:35 CST, during session_commit.
Bug Description
The commit fails with:
Phase 2 step long_term failed: Final response could not be parsed as operations after 2 iterations (failure_kind=parse_error)
with the underlying parse error:
Failed to parse memory operations (iteration 2/2) failure_kind=parse_error
error=Line 44: invalid Python syntax: …
Observation from the captured response_preview: the model wrapped its operations in a Markdown fenced block starting with ```python (i.e. ```python <op>(...) ``` instead of bare ops). The DSL parser then reports an invalid-syntax error at the corresponding line.
Notes:
- After #5171 this is correctly surfaced as a failure (previously it would have been silently swallowed as a successful zero-memory commit) — good change; reporting so the parse edge can be handled.
- Similar family: #1541 (open, “LLM returns plain text instead of JSON structure”), #4580 / #4486 / #5163 (closed).
- Retrying the same session reproduced parse_error again (not transient).
Ask
- Should the extractor normalize/strip code fences before parsing (defensive), or is the intended fix prompt-side only?
- Is
Line 44: invalid Python syntaxthe expected error shape for a fenced block, or is there a better diagnostic to include (e.g., first offending line snippet)?
Environment
OpenViking v0.4.22 local (vlm doubao-seed-2.1-lite via Ark plan gateway). Session content redacted; can share a sanitized raw response if needed.
On current main (1394d476), a single ```python block is already supported: parse() extracts the code before compiling it. I ran the existing fence/syntax-error regressions on that checkout: 10 passed (pytest tests/session/memory/test_extraction_output_protocol.py -k 'fence or syntax_error' -q -o addopts=). This includes a normal fenced program, surrounding explanation, recoverable missing closing fence, and rejection of truncated Python. No live Ark call was tested.
Line 44: invalid Python syntax comes from parsing the extracted program, so the opening fence in response_preview alone does not establish the cause. The current diagnostic also includes the offending source line and a caret; line numbers refer to the extracted code. Could you share a fully sanitized response that still reproduces the error, plus the complete parser error? Replace memory text/identifiers and remove credentials, while preserving quotes, newlines and fence boundaries. That would let us distinguish malformed code inside the block from a fence-extraction edge before changing normalization or the prompt.
I saw errors like those recently and solved it (temporarily) with "extraction_output_format": "json"
I didn't dig into it deeper, nor do I want to, but I suspect my model (Qwen3.8-Flash-Next) is simply not smart enough to know the right expected syntax, or it doesn't understand it from the prompt (I didn'see one, just "Use Pythonic DSL syntax" or something like that - and I don't know what that is).
Before this change, it failed most of the time, now I only saw one, maybe two failure with long (150K) prompts.
I hope this is not an indication of skewing towards larger models, the exact reason why I abandoned hindsight :)
Update — a third, distinct cause: CJK full-width punctuation inside the model's DSL output.
Environment: v0.4.22, macOS, VLM via Ark (doubao), sessions in Chinese (zh-CN).
Verbatim (server.log, 2026-10-02 18:27:06 CST):
2026-10-02 18:27:06.965 | ERROR | openviking.session.memory.extract_loop:run:421 - Failed to parse memory operations (iteration 4/4) failure_kind=parse_error error=Line 10: invalid Python syntax: invalid character ')' (U+FF09)
2026-10-02 18:27:06,969 - openviking.session.session - ERROR - Phase 2 step long_term failed: Final response could not be parsed as operations after 4 iterations (failure_kind=parse_error)
This is not the fenced-block wrapping case already discussed above, and not the schema/field-name case in #5527: the emitted operations are otherwise conforming, and the parse dies on a single full-width right parenthesis ) (U+FF09) in the DSL line.
Two further commits carry the same summary line, but their iteration-level detail was no longer in the retained log window, so I am not claiming their cause: 2026-09-30 20:20:38 (resource 20260929_185026_3cabc8) and 2026-10-01 18:05:55 (resource cc-c2641326-cb3f-419e-96ed-57c787726435).
Impact on this side: 3 commits lost their long-term extraction to parse_error over three days; retries are useless here (all 4 iterations fail on the same character), and the failure archive is terminal until #4295 lands.
Workaround: none applied yet on this deployment — next step here is to try extraction_output_format: json (as mentioned above) and re-measure.
If it helps, the payload is one character wide off conforming, so normalising CJK full-width punctuation before compile (or extending the existing python-dict path) looks like the smallest change; I have not tested that, so treat it as a suggestion only.
Correction + evidence — my previous comment got the mechanism wrong, and the full diagnostic (source line + caret + response_preview) changes the picture.
Correction first: I wrote that "the emitted operations are otherwise conforming, and the parse dies on a single full-width right parenthesis". That is incomplete. The retained diagnostic includes the offending source line and a caret, which point at something else.
Full retained diagnostic (server.log, 2026-10-02 18:27:06 CST — three lines, verbatim apart from redaction):
2026-10-02 18:27:06.965 | ERROR | openviking.session.memory.extract_loop:run:421 - Failed to parse memory operations (iteration 4/4) failure_kind=parse_error error=Line 10: invalid Python syntax: invalid character ')' (U+FF09)
- <redacted> heredoc typo (`''",` written as `""",`), parse failed, file was not written, redo
^ response_preview='```python sidecar_wiring = sdk.create_entities( peer_id=\'<redacted>\', category=\'<redacted>\', name=\'<redacted>\', content="""# <redacted> ...'
2026-10-02 18:27:06,969 - openviking.session.session - ERROR - Phase 2 step long_term failed: Final response could not be parsed as operations after 4 iterations (failure_kind=parse_error)
What that says (answering the specific question above — malformed code inside the block vs. fence-extraction edge):
- It is neither. The fence boundary looks fine (
response_previewopens with ```python). - The model emits the memory body inlined into a
content="""…"""literal, and the body itself contains a markdown code span holding a literal""",— i.e. a"""sequence inside the payload. That terminates thecontentliteral early, so the remaining prose gets parsed as code, and it dies on a CJK full-width parenthesis. - So the failure class is: the DSL's own string delimiters are not escaped against payload content. The CJK character is where it surfaces, not the cause — my earlier "normalise full-width punctuation" suggestion would only mask it.
Reproducer, honestly scoped: I cannot hand you a full sanitized response that still reproduces — the log retains only a ~120-character response_preview, so the remaining lines of that response are gone. That itself is a small actionable point: if the preview were, say, full-response-on-parse-error, this class would be reproducible from a user's log directly.
What I can give, with fences/quotes/newlines preserved and identifiers redacted:
sidecar_wiring = sdk.create_entities(
peer_id='<redacted>',
category='<redacted>',
name='<redacted>',
content="""# <redacted>
<redacted prose>
- <redacted> heredoc typo (`''",` written as `""",`), parse failed, file was not written, redo
<redacted prose, containing (full-width parens) …>""")
The """, inside the body is the payload element that closes the literal early; the reported Line 10 is the line where the following prose is then parsed as code.
Impact: 3 commits lost their long-term extraction to parse_error over three days on this deployment (2026-09-30/10-01/10-02); retries are useless (all 4 iterations hit the same defect).
This is also consistent with the extraction_output_format: json workaround mentioned above — JSON-encoding the payload removes the injection surface, which is what I would expect if the above mechanism is right.
I reproduced the delimiter failure with a synthetic payload on current main (e8a197c3), through PythonExtractionOutputProtocol.parse(): an unescaped """, inside content="""…""" closes the literal early, and the parser then reports the full-width parenthesis in the following prose. This supports the mechanism in your correction; it cannot recover or establish the exact contents of the missing response.
With the same payload, escaping backslashes and the embedded triple quotes preserves the entire content, including the CJK punctuation and a C:\temp\notes path. The JSON protocol also preserves it when supplied correctly JSON-encoded content. Normalizing punctuation would change the memory and leave the broken delimiter intact.
The initial Python contract already says to escape literal triple quotes and backslashes. The format-retry message only repeats “use triple-quoted strings”, so repeating that escape rule there may help this particular failure. This is a prompt improvement to evaluate, not evidence that a model will obey it or that failed archives can already be retried.
Validation: three successful encoding controls plus the expected malformed-Python rejection; existing fence/syntax/string-retry tests: 11 passed. No live model call or server commit was run. memory.extraction_output_format: "json" is a reasonable scoped workaround for subsequent long-term extraction, but it still requires valid model output and does not repair an already-failed archive. I would keep full responses out of ordinary logs: they can contain sensitive memory content.
Config-level finding: the python extraction output protocol is what mandates triple quotes.
Following up on the delimiter mechanism you confirmed: the output protocol is selectable, and the default is the fragile one.
MemoryConfig.extraction_output_format is Literal["json", "python"] and defaults to "python". Its own field description reads: "'python' uses the restricted internal memory SDK DSL (default); 'json' preserves the legacy structured JSON protocol."
The python protocol's own contract instructs the model to use triple quotes for natural-language arguments — i.e. the triple-quoted form is protocol-mandated, not a model-specific quirk. That is consistent with the delimiter failure being reachable on any sufficiently capable model, not just weaker ones.
Switching to memory.extraction_output_format = "json" selects JsonExtractionOutputProtocol, which per its docstring "preserve[s] the existing JSON prompt and tolerant parsing behavior" and renders its contract from model_json_schema().
Note this key appears to be undocumented: 0 hits across the zh/en configuration, extraction and FAQ pages. That is likely why deployments stay on the python default without realising the protocol is switchable — and why the workaround shared earlier in this thread works.
Related reports worth cross-referencing:
- #5527 — flash-tier models intermittently mis-emit during extraction
- #5632 — non-schema JSON treated as a successful empty result (silent loss rather than a visible failure; this one may hide failures that never surface as a non-200)
- #5565 — Working Memory v2 update branch forces a specific
tool_choice
Environment: v0.4.23, macOS, VLM doubao-seed-2.1-lite via the Ark plan endpoint, sessions in Chinese. Observed locally: ~20% of session_commit tasks failing over a 24h window after the account-quota issue cleared — 51% read-timeout, 39% the 'list' object has no attribute 'strip' path, 9% failure_kind=parse_error.