OpenViking icon indicating copy to clipboard operation
OpenViking copied to clipboard

[Bug]: Python DSL parse_error — content-final quote collides with closing triple quote (""""), retry guidance cannot repair it, whole session memory extraction aborted

Open lqstc opened this issue 3 weeks ago • 2 comments

Python DSL parse_error: a content-final double quote collides with the closing triple quote (""""), the format retry cannot repair it, and the whole session's memory extraction is aborted

Summary

The Python extraction protocol parses the model's SDK program with ast.parse. When a natural-language argument wrapped in """...""" ends with a " immediately before the closing delimiter (or the model emits one surplus quote), the program contains four consecutive quotes (""""). Python closes the string at the first three quotes and treats the remaining " as a new, never-terminated literal:

SyntaxError: unterminated string literal

The single format retry re-prompts with quote guidance that says "rewrite every natural-language argument as a triple-quoted string" — but the failing program already used triple quotes. The guidance does not address the trailing-quote collision, so iteration 2 reproduces the same syntax error and the loop raises RuntimeError.

This occurred inside the streaming policy trainer's merge/extract loop. The exception propagates through train_from_extracted_cases and (with strict_extract_errors) aborts the entire Phase-2 long_term step: the whole streamed training batch is discarded and the session is marked extraction-failed — even though the user-memory extraction pass had already completed.

Environment

  • OpenViking v0.5.4.1 (uv tool install, Python 3.14)
  • extraction_output_format: python (default)
  • VLM: doubao-seed-2.1-lite via OpenAI-compatible gateway
  • Workload: normal live session commit; long CJK (Chinese) experience content (~100 lines of Markdown prose)

Evidence

Sanitized production log (paths and session id redacted):

ERROR | openviking.session.memory.extract_loop:run:451 - Failed to parse memory operations
  (iteration 2/2) failure_kind=parse_error
  error=Line 101: invalid Python syntax: unterminated string literal (detected at line 101)
  - <last line of a long Chinese experience body>""""
                                      ^
  response_preview='experiences_1.content.update("""## Situation - ...'

WARNING - [openviking-streaming-policy-trainer] background flush failed: Final response could not be
  parsed as operations after 2 iterations (failure_kind=parse_error)
ERROR - Phase 2 step long_term failed: Final response could not be parsed as operations after 2 iterations
ERROR - Memory extraction failed for session oc-ses_XXXXXXXX

Minimal reproduction (no server needed):

>>> import ast
>>> ast.parse('x.update("""some text"""")')
Traceback (most recent call last):
  ...
SyntaxError: unterminated string literal (detected at line 1)

The same failure occurs when the prose itself ends with " (e.g. a quoted term at the end of the last bullet) so that content-final quote + closing """ = """".

Root cause (source-level, v0.5.4.1)

  1. openviking/session/memory/extraction_output_protocol/python_protocol.py:646 — ast.parse(code, mode="exec"); on SyntaxError it reports Line N: invalid Python syntax: ... (lines 656–659). There is no tolerance/repair for the """" tail.
  2. openviking/session/memory/extract_loop.py:430–435 — exactly one format retry. render_format_retry (python_protocol.py:289–330) detects the error via _is_string_literal_syntax_error (line 1524, matches unterminated string literal) and advises: "a quote or newline inside prose likely ended the string early. Rewrite every natural-language argument ... as a triple-quoted string". This advice is correct for single-/double-quoted literals but inapplicable here: the program already used triple quotes; the collision is between a content-final (or surplus) " and the closing """. The model follows the advice and reproduces the same bug.
  3. extract_loop.py:465 raises RuntimeError → policy_trainer.submit_gradients → compressor_v3.py:491 train_from_extracted_cases → except Exception: if strict_extract_errors: raise (compressor_v3.py:532–534) → session Phase-2 long_term fails. The streaming batcher's flush fails as a whole, so all memory updates in that training batch are lost, not just the offending one.

Impact

  • Stochastic per-session failure; more likely with long, quote-heavy CJK Markdown content.
  • The one available retry is ineffective for this failure class (wrong guidance), so the failure is effectively terminal on first occurrence.
  • Blast radius is the whole session: the trainer batch is discarded and the session archive is marked failed, despite the user-memory extraction pass having completed before training started.

Suggested fixes

  1. Targeted retry guidance: when the error is unterminated string literal and the offending line ends with """", tell the model explicitly: "the content must not end with a double quote right before the closing \"\"\" — end the content with a newline or rephrase".
  2. Tolerant parsing: in this restricted DSL a string argument is always followed by ) or ,, so a """" (or """"") tail immediately before )/, is unambiguous — repair it to """ before ast.parse instead of failing.
  3. Structural: consider emitting operations as JSON (content as escaped JSON strings) instead of Python source — this eliminates the whole class of quote-collision syntax errors (cf. #5514, #6639 which are also DSL-surface failures).
  4. Failure isolation: a policy-trainer batch failure should not abort the session's entire long_term extraction. Catch trainer errors, log and skip (or persist the batch for later replay), and keep the already-extracted user memories.

Related

  • #5894 — size-driven parse_error on large sessions (different root cause, same terminal symptom)
  • #5514 — parse_error from fenced code block wrapping
  • #6639 — DSL emits dict/list for string-typed schema fields
  • #6235 — validator rejects forms the contract teaches

Filed by QoderCN (coding agent) on behalf of @lqstc. Log evidence sanitized; minimal reproduction verified locally on Python 3.14.

lqstc avatar Nov 11 '26 18:11 lqstc

Thanks for filing this detailed report with reproduction logs!

I verified the root cause locally:

  1. In ast.parse, four consecutive quotes ("""") caused by a content-final double quote immediately preceding the closing """ delimiter split into a closed triple-quoted literal followed by a dangling, unclosed quote (SyntaxError: unterminated string literal).
  2. render_format_retry() currently gives generic guidance advising the model to wrap arguments in """...""". Because the model already did so, iteration 2 reproduces the exact same syntax error and triggers the terminal RuntimeError.

I am preparing a surgical fix in openviking/session/memory/extraction_output_protocol/python_protocol.py that:

  • Automatically repairs trailing-quote collisions ("{4,} / '{4,} before argument delimiters ), ,, \n) during fallback compile so extraction succeeds on iteration 1.
  • Enhances render_format_retry() to provide targeted guidance if a trailing quote collision occurs.
  • Adds test cases to tests/session/memory/test_extraction_output_protocol.py.

I will raise a PR shortly!

mohitdixit02 avatar Nov 11 '26 18:11 mohitdixit02

Thanks for the report and the reproduction details. We've identified the trailing-quote issue in Python DSL memory extraction and expect to have a fix soon.

heaoxiang-ai avatar Nov 16 '26 08:11 heaoxiang-ai