StructuredOutputHook fails to parse fenced JSON with CRLF line endings
Describe the bug
StructuredOutputHook removes an outer Markdown code fence before parsing an Agent's final reply as structured JSON.
The current code-fence pattern handles LF (\n) line endings, but does not recognize equivalent fences using CRLF (\r\n). As a result, the fence remains in the reply and JSON parsing fails.
During an Agent run, this consumes the configured correction retries and eventually stores None instead of the valid structured output.
Error message
The Agent's final reply could not be parsed as structured output after 2 retries: The reply is not valid JSON: Expecting value: line 1 column 1 (char 0)
To Reproduce
import json
from haystack.hooks.structured_output.hooks import _strip_code_fence
lf_reply = '```json\n{"city": "Paris"}\n```'
crlf_reply = '```json\r\n{"city": "Paris"}\r\n```'
lf_stripped = _strip_code_fence(lf_reply)
crlf_stripped = _strip_code_fence(crlf_reply)
print("LF:", repr(lf_stripped))
print("CRLF:", repr(crlf_stripped))
print(json.loads(lf_stripped))
print(json.loads(crlf_stripped))
Actual behavior
The LF fence is removed successfully:
LF: '{"city": "Paris"}'
The CRLF fence is returned unchanged:
CRLF: '```json\r\n{"city": "Paris"}\r\n```'
Calling json.loads() on the CRLF result raises:
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
I also reproduced the behavior through an offline Agent run using MockChatGenerator and StructuredOutputHook:
- The LF-formatted reply parsed successfully in one Agent step.
- The equivalent CRLF-formatted reply produced two correction messages.
- The Agent exhausted both configured retries.
- The resulting structured output was
None.
Expected behavior
When a Markdown code fence wraps the complete reply, StructuredOutputHook should remove the fence whether it uses LF or CRLF line endings.
For the CRLF example, _strip_code_fence() should return:
'{"city": "Paris"}'
The existing behavior for unfenced JSON and replies containing additional text outside the fence should remain unchanged.
Additional context
The current code-fence pattern explicitly requires \n:
_CODE_FENCE_PATTERN = re.compile(
r"^```[\w-]*[ \t]*\n(.*?)\n?[ \t]*```$",
re.DOTALL,
)
When the opening fence uses \r\n, the carriage-return character prevents the pattern from matching.
The same focused test file currently passes all existing tests, but its fenced-reply cases use LF exclusively. There is no CRLF regression coverage.
I reproduced this behavior against the current main commit shown below. I searched existing issues and pull requests and did not find an exact report or active implementation.
I would like to prepare a focused fix with regression tests if this behavior is confirmed as unintended.
System
- OS: Windows 11
- Python: 3.13.7
- Haystack commit:
0ad74747ffd7d9f9b092db97ba2e222080992c2e
I reproduced this against the current main branch at commit 0ad74747ff and would like to work on the fix. I plan to add focused CRLF regression coverage, preserve the existing LF behavior, and keep the change limited to StructuredOutputHook code-fence handling. Please assign this issue to me if it is suitable for an external contribution.
Hi! I'm interested in contributing to this issue.
I would like to work on a focused fix for CRLF handling in StructuredOutputHook, including regression tests for both LF and CRLF line endings while preserving existing behavior.
Could you please assign this issue to me, or let me know if I should proceed with a PR?
Thanks!
Hi, thanks for your interest. I have already reproduced this issue against current main and stated above that I am working on it. I have also prepared the focused CRLF regression tests and minimal fix locally.
To avoid duplicate work, I plan to open the linked PR shortly. I’ll leave the final assignment decision to the maintainers.
Heads-up: the fix is ready on a branch, but I could not open the PR from here (every POST /repos/deepset-ai/haystack/pulls with my fork's head returns 404, even though the compare view says "Able to merge"). So instead of leaving this open, here is what the change looks like — could someone open the PR from this branch, or tell me if I'm missing a step?
Branch: https://github.com/sunhouy/haystack/tree/fix/structured-output-crlf-fence (based on 0ad7474)
The two lines that matter, in haystack/hooks/structured_output/hooks.py:
-_CODE_FENCE_PATTERN = re.compile(r"^```[\w-]*[ \t]*\n(.*?)\n?[ \t]*```$", re.DOTALL)
+_CODE_FENCE_PATTERN = re.compile(r"^```[\w-]*[ \t]*\r?\n(.*?)\r?\n?[ \t]*```$", re.DOTALL)
match = _CODE_FENCE_PATTERN.match(text.strip())
- return match.group(1) if match else text
+ return match.group(1).rstrip("\r") if match else text
The lift from \n to \r?\n handles the opening fence; the rstrip("\r") is for the capture group, which otherwise keeps the \r that sits right before the closing fence and makes json.loads fail with Expecting value: line 1 column 1 even when the JSON is fine.
Tested with your repro plus two new parametrised cases in test/hooks/structured_output/test_hooks.py (json-fence-crlf, padded-fence-crlf, both model classes):
- on main: 4 failed, 38 passed (exactly the new cases)
- with the fix: 42 passed, full
test/hooks399 passed - the
MockChatGeneratorpath from your report now parses in one step instead of burning both retries
Unfenced replies and replies with text around the fence are untouched — checked those by hand as well. Also added a reno note. I'm happy to adjust anything if you'd rather handle this differently (e.g. normalising \r\n somewhere higher up instead of in the fence helper).
Thanks for sharing your investigation and test results. I have already opened PR #13617 for this issue with focused CRLF regression coverage and a release note.
My implementation handles the CRLF boundaries directly in the regex without applying rstrip("\r") to the captured payload. I’ll leave the implementation choice and any requested changes to the maintainers during review.