Skip to content

Write a readable traceback under each JSON log record - #8585

Merged
danielhanchen merged 13 commits into
mainfrom
studio-readable-log-tracebacks
Aug 13, 2026
Merged

danielhanchen merged 13 commits into
mainfrom
studio-readable-log-tracebacks

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

~/.unsloth/studio/logs is a tee of stdout, and stdout is JSON, so every traceback reaches the person reading that file as one enormous line with its newlines escaped to \n. That is correct JSON and unreadable prose, and it is the state the log is in for every crash anyone is ever asked to send in. A reported Image Transform failure was tracked down that way, and arrived with, in the reporter's words, all its newlines mangled.

What changes

with_readable_traceback wraps the JSON renderer. The record is emitted unchanged, escaped exception field and all, so anything parsing the file record-by-record sees exactly what it saw before. The readable copy follows it on its own lines:

{"timestamp":"...","level":"error","event":"request_failed","exception":"Traceback (most recent call last):\n  File ..."}
Traceback (most recent call last):
  File "/studio/backend/core/inference/diffusion.py", line 5240, in generate
    image_latents = self.vae.encode(image)
RuntimeError: Input type (float) and bias type (c10::BFloat16) should be the same

That the file also carries non-JSON lines is not something this relies on by chance: faulthandler writes native stacks straight to the same handle, and uvicorn and third-party stderr land there too.

Safety

  • The echoed copy is event_dict["exception"] read after filter_sensitive_data and the truncation processor have rewritten it, so a secret cannot re-enter the log through the readable copy and a 2 MB traceback cannot be echoed at full length. Covered by a test.
  • Only the JSON renderer is wrapped. ConsoleRenderer (development) already prints tracebacks as tracebacks, and wrapping it would print each one twice.
  • Opt out with UNSLOTH_STUDIO_PLAIN_TRACEBACKS=0.

Tests

test_readable_traceback_logging.py, 6 cases: a record without an exception stays a single line, the JSON line stays parseable and keeps the escaped field while the readable copy follows, the env opt-out, blank and non-string exception values, ConsoleRenderer left unwrapped, and the redacted / truncated copy being the one echoed.

danielhanchen and others added 2 commits August 12, 2026 15:49
~/.unsloth/studio/logs is a tee of stdout and stdout is JSON, so every traceback reached the
person reading that file as one enormous line with its newlines escaped to \n. That is correct
JSON and unreadable prose, and it is the state the log is in for every crash anyone is ever
asked to send in. A reported Image Transform failure was found that way, with, in the
reporter's words, all its newlines mangled.

with_readable_traceback wraps the JSON renderer: the record is emitted unchanged, escaped
exception field and all, so anything parsing the file record-by-record is unaffected, and the
readable copy follows it on its own lines. The file already carries non-JSON lines by design:
faulthandler writes native stacks straight to the same handle.

The echoed copy is the one filter_sensitive_data and the truncation processor already
rewrote, so no secret re-enters the log through it and a 2 MB traceback is not echoed at full
length. ConsoleRenderer is left alone since it prints tracebacks as tracebacks already.
Opt out with UNSLOTH_STUDIO_PLAIN_TRACEBACKS=0.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 12, 2026
Codex is right that the echo alters the stdout stream. An exception message carries
request-derived text (the truncation cap in this file exists because a rejected upload
embedded a whole request body in one), so a message holding a newline plus a JSON object
would previously emit a line that json.loads accepts: a forged record, CWE-117.

Every echoed line now carries a "| " prefix. Not indentation: RFC 8259 lets a parser skip
leading whitespace, so json.loads('  {"event": ...}') succeeds and an indent would have
left the forgery intact. "| " cannot begin a JSON value, so no echoed line parses as a
record or can be confused for one, and a reader that wants records only can filter on the
prefix. splitlines/rejoin also normalises \r and the other separators a message could
smuggle in.

Kept on the same return value rather than moved to stderr: a processor runs before
PrintLogger prints, so a side-channel write would put the traceback ABOVE its record, and
the export worker reads stdout and stderr on separate pipes, which would let the two
reorder again in the dialog. One print under PrintLogger's lock keeps them adjacent.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

pre-commit-ci Bot and others added 2 commits August 12, 2026 16:13
Both of these were handled for free by the JSON renderer and became mine to handle when
the echo started emitting the text raw.

A lone surrogate reaches an exception message easily: json.loads('"\ud800"') yields one, so
a request body can carry it. JSONRenderer escaped it to ASCII; printing it raw raises
UnicodeEncodeError on a UTF-8 stdout, and inside an exception handler that loses the
traceback and replaces the original exception with the encoding error.

ESC sequences and backspaces were likewise escaped inside the JSON string. Emitted raw
they let request-derived text clear or rewrite what the reader sees, and a backspace run
can rub out the prefix in front of it, which is the one thing that prefix is there to
guarantee.

Both are escaped per line to their \uXXXX spellings. Ordinary non-ASCII text is untouched,
so a traceback quoting a non-English string still reads as that string, and tab is kept
since it shifts alignment but cannot move the cursor back or erase.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

pre-commit-ci Bot and others added 2 commits August 12, 2026 16:48
…ne cannot differ

Same regression as the terminal controls, one character class over. json.dumps escapes
these for free with ensure_ascii, so the JSON record always did; the echo emitted them raw
because they sit outside C0, C1 and the surrogate range.

The harm is not that the text looks jumbled. Measured through a UAX #9 implementation, an
echoed line reading "rejected upload <U+202E>gnp.eliforp/sdaolpu/" displays as "rejected
upload /uploads/profile.png": the reader sees a different, plausible, attacker-chosen
filename from the one that was logged, in any viewer applying the bidi algorithm. That is
Trojan Source (CVE-2021-42574) pointed at a log.

Exactly Unicode's Bidi_Control property, twelve characters, rather than all of category
Cf: ZWJ, ZWNJ, U+200B and the soft hyphen are Cf as well, carry orthographic or emoji
meaning in ordinary text, and reorder nothing. Escaping them would cost the readability
this function deliberately protects and buy nothing. A test pins the set so it can neither
widen to Cf nor narrow to the override alone.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 476798099a

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

and isinstance(line, str)
and _plain_tracebacks_enabled()
):
return f"{line}\n{_echoable(exception)}"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Serialize traceback writes across worker processes

When the server and a spawned inference or training worker log concurrently, they share the inherited stdout pipe but each process has its own PrintLogger lock (core/inference/orchestrator.py:378-390 and core/training/training.py:1693-1702). Returning the JSON record and echoed traceback as one string only guarantees thread-local ordering; once this combined write exceeds the pipe's PIPE_BUF—which an ordinary multi-kilobyte traceback can now do—the OS may interleave another process's output inside it. That can corrupt the JSON record or place unrelated lines between it and its traceback, defeating the adjacency and parseability this wrapper is intended to preserve; route writes through a shared inter-process serializer or the parent process instead.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The property is real, but it is not introduced here and the write was already over PIPE_BUF for exactly these events. truncate_exception caps the exception field at 16,384 characters by default, so a JSON record carrying a traceback has always been allowed to reach four times the 4,096-byte PIPE_BUF on Linux in a single print. Any interleaving hazard between the server and a spawned worker sharing the inherited stdout fd therefore predates this change and applies to the record alone.

What this PR adds is a second bounded copy on the same write, now capped after escaping in 27a1e55, so the exposure is the same in kind rather than newly created. Routing every log write through an inter-process serializer is a real change to how the workers log, well beyond a traceback echo, and I would rather not fold it in here. Worth noting the echo also degrades better than the record under interleaving: a torn | line is still recognisably not a record, whereas a torn JSON line has always been unparseable.

Comment thread studio/backend/loggers/config.py Outdated
Comment on lines +195 to +197
return "\n".join(
f"{_TRACEBACK_ECHO_PREFIX}{_escape_unprintable(part)}"
for part in exception.rstrip().splitlines()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Distinguish exception text from real traceback frames

When a request-derived exception message contains newlines, every injected line receives exactly the same prefix as genuine traceback frames, so a payload can append a plausible During handling of the above exception... section and fabricated stack frames that are indistinguishable in the human-facing log. The fresh evidence beyond the earlier JSON-record-forgery fix is that the prefix prevents json.loads() from accepting a line but does not identify which lines came from the exception message; preserve frame readability while escaping or otherwise marking newlines originating in the exception value.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This one I do not think is actionable at this layer, and it is not something the echo introduces.

CPython renders a multi-line exception message inline, unmarked, in the traceback itself. Raising ValueError("bad prompt\nDuring handling of the above exception, another exception occurred:\n\n File ...") produces exactly the fabricated section you describe from traceback.format_exc(), so it is already there in the unhandled-exception dump on the terminal, in the development ConsoleRenderer output, and in the JSON exception field this PR leaves untouched. The echo reproduces the string Python produced rather than assembling one.

Marking it in the processor is also not possible: structlog.processors.format_exc_info pops exc_info and leaves a single rendered string, so by the time with_readable_traceback runs there is no record of where the message ended and the frames resumed. Distinguishing them would have to happen at the point the traceback is rendered, which is upstream of this wrapper.

danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 12, 2026
truncate_exception bounds the exception field at UNSLOTH_STUDIO_MAX_EXCEPTION_CHARS,
but escaping then multiplies it: each control character becomes six, so a
control-heavy payload (a request body quoted into an exception message) turned
16 KiB of bounded field into 98 KiB of echo. The budget is now spent on the escaped
text, dropping whole lines from the middle and keeping the head and the tail. The
omission notice carries the same line prefix, so no line the echo emits can begin a
JSON value.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

A control-heavy exception message makes the final traceback line larger than the
tail budget on its own, and the tail loop dropped it whole, leaving the reader
every frame and no exception type or message. Cut it to what is left instead. The
notice says so rather than claiming zero lines went, since a cut line is kept.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Nice work!

Reviewed commit: 2dab38b1f3

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen
danielhanchen merged commit e005b1e into main Aug 13, 2026
37 of 43 checks passed
@danielhanchen
danielhanchen deleted the studio-readable-log-tracebacks branch August 13, 2026 00:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant