Skip to content

fix(logs): include the backend session log in the support diagnostics report - #8877

Merged
danielhanchen merged 12 commits into
unslothai:mainfrom
LeoBorcherding:fix-windows-rocm-vram-probe-isolation
Aug 25, 2026
Merged

danielhanchen merged 12 commits into
unslothai:mainfrom
LeoBorcherding:fix-windows-rocm-vram-probe-isolation

Conversation

@LeoBorcherding

Copy link
Copy Markdown
Collaborator

Context: the Windows ROCm / Strix Halo crash reported on Reddit (same host as #8853). This does not fix that crash — it makes the next report of it diagnosable.

Problem

The Python backend aims faulthandler at ~/.unsloth/studio/logs/server/ (studio/backend/run.py:1850), so when the GPU runtime aborts, the Python stack naming the call that died is written there and in no other file Studio keeps.

The support report's == Log tails == section collected tauri.log, tauri.log.1 and the phase logs, and never that directory. A hard native crash therefore arrives as exit code: 3 with nothing about what the process was doing, while the one file that answers it sits on the user's disk unasked-for. That is exactly how the linked report played out: seven minutes of healthy polling, the model dropdown's request fan-out all returning 200, then Backend stdout stream ended with status: exit code: 3 with no traceback and no [stderr] line.

Change

Tail the two newest server-*.log alongside the existing sections, labelled source=backend-session-log. Two files, so a crash and the restart that followed it both land in one report. An absent directory reports backend_session_logs=unavailable rather than erroring — a --no-torch host, or one with UNSLOTH_STUDIO_NO_FILE_LOG=1, simply has none.

They get a smaller budget than the other tails (64 KiB / 400 lines vs 200 KiB / 1000). enforce_report_limit truncates the end of the body, so bytes spent in a section inserted here come straight out of the phase logs below it. A faulthandler dump is a few KB at the end of the file, which is the half read_tail returns, so the smaller cap loses nothing that matters.

append_tail_section keeps its signature and delegates to a _capped variant; no existing call site changes behaviour.

Testing

Four new tests in diagnostics::report::tests:

  • newest-first ordering and the two-file cap
  • only server-*.log is collected (tauri.log, server-notes.txt ignored)
  • absent directory yields empty, no panic
  • the section stays inside its smaller budget while retaining the trailing faulthandler stack

Both behaviours mutation-tested: flipping the sort to ascending, and raising SERVER_LOG_TAIL_MAX_BYTES to TAIL_MAX_BYTES, each fail the suite.

cargo test --bins: 367 passed. cargo fmt --check is clean on the changed file (the tree has pre-existing diffs elsewhere, left alone).

Privacy: the new tails go through the same redact_text pass as every other section; report_redacts_footer_collection_warning_paths covers home-path masking.

…port

The Python backend aims faulthandler at ~/.unsloth/studio/logs/server/, so a
native abort in the GPU runtime writes its stack there and in no other file
Studio keeps. The report collected tauri.log and the phase logs but never that
directory, so a hard crash arrived as an exit code with nothing about the call
that died.

Tail the two newest server-*.log alongside the existing sections. Their budget is
smaller than the other tails on purpose: enforce_report_limit chops the end of
the body, so bytes spent here would come out of the phase logs, and a faulthandler
dump is a few KB at the end of the file, which is the half read_tail returns.
@LeoBorcherding LeoBorcherding self-assigned this Aug 18, 2026
@LeoBorcherding LeoBorcherding changed the title Studio: include the backend session log in the support diagnostics report fix(logs): include the backend session log in the support diagnostics report Aug 18, 2026
@danielhanchen

Copy link
Copy Markdown
Member

Confirmed the report path in studio/src-tauri/src/diagnostics/report.rs only tails the app and phase logs, so the server session log holding the faulthandler stack never made it in, and this covers it. Could you also take a look at the red Backend CI and the hf-stack package scan on this branch?

…ion-log slot

Only two backend session logs are collected, so an entry that matches
server-*.log by name but cannot be read has to be rejected during selection.
Rejecting it later in read_tail still costs a slot, and the slot it costs is
the one holding the faulthandler stack the report exists to carry. This is the
same reason scan_phase_logs_in_dir screens symlinks inline rather than at read
time.

Three cases, verified on Linux against the pre-change code:

- A FIFO. File::open on one blocks until a writer appears, and read_tail runs
  on the blocking pool behind collect_support_diagnostics, so this wedged a
  thread and the support report never returned. Measured: still blocked past
  5s. This is the one that matters, because it fails at the moment the user is
  already trying to report a crash.
- A directory. Reads back as EISDIR on Unix and ERROR_ACCESS_DENIED on
  Windows, so it degraded gracefully, but two of them took both slots and the
  real crash log did not make the report.
- A symlink. Same outcome, with read_tail's existing refusal noted only after
  the log it displaced was already gone.

Also:

- Say which directory was searched when there is nothing to collect. A backend
  the app adopted rather than spawned can resolve its own studio root from
  sys.prefix (utils/paths/storage_roots.py _infer_studio_home_from_venv), which
  the UNSLOTH_STUDIO_HOME scrub in process.rs cannot reach, so a bare
  "unavailable" cannot be told apart from "the backend logs somewhere else".
- Report a read_dir failure that is not NotFound. A missing directory is the
  ordinary case for an install that has never started a backend and stays
  silent; a permission wall did not.
- Skip a name carrying a control character or a backtick. The report is line
  oriented and fences tails with ```text, and both the header and the path are
  printed verbatim, so such a name forged key=value lines in the body.
- Correct the footer bounds line, which still advertised 1000 lines/200KiB for
  sections that are capped at 400/64KiB.
- Note in the tie-break comment that pidN is not zero padded, so the filename
  tiebreak is stable but not chronological.

Tests: one per rejected entry type, the FIFO one on a deadline since a
regression there hangs the suite rather than failing it; an ordering test whose
mtimes and filenames disagree, so it can only pass on mtime; and the budget
assertion tightened from 128KiB to 80KiB, which a mutation to 100KiB had been
slipping through.

cargo test --locked --no-fail-fast --bins: 372 passed. Each new assertion
mutation checked. cargo fmt --check is clean on this file.
@danielhanchen

Copy link
Copy Markdown
Member

Took this through a full pass. Short version: the problem is real, the fix is the right shape, the red checks were never yours, and I have pushed two things to the branch.

The red checks

Not caused by this PR, and nothing in report.rs needed to change for them. This is a Rust only diff, and every Rust job on it passed: Rust unit tests (windows), Rust unit tests (macos), Tauri Linux debug build.

Both failures were repo wide on the 2026-08-14 base this branch was cut from:

  • 18 of 18 sampled unrelated branches that day, and main itself, show the identical signature: pip scan-packages :: hf-stack failing while :: studio and :: extras pass, and (Python 3.13) plus Repo tests (CPU) failing.
  • Backend CI had 0 to 1 successes per day repo wide on 08-14, 08-15 and 08-16. Security audit had 0 on 08-14 and 08-15.
  • 135147814 (Fix CI on main: stale test doubles, a stale router stub, and two source defects #8956, 08-16) is the commit that fixed it, and says so in its own message: "main has been red since Aug 14 and every open PR inherits it". The same PR carries the hf-stack fix, removes 74 lines from scripts/scan_packages_baseline.json, and notes hf-stack "now exits 0 (was 1)".
  • First green main run: Security audit 2cf7a2888 (08-16), Backend CI a41f77853 (Run both ends of the interpreter matrix on a pull request, all four on main #9080, 08-17).

The mechanism is worth knowing for next time: pip scan-packages runs with --with-deps and SCAN_ENFORCE=1, so it resolves the transitive closure live from PyPI against a digest pinned baseline. An upstream release that touches a reviewed region reopens the finding on every open PR at once. 567b3b7f9 (#9252) documents a second instance of exactly that.

I used the "Update branch" button so CI now runs against current main instead. Merging was conflict free and the whole Rust suite is green on the merge locally (420 passed).

The premise checks out

I ran the writer for real rather than reading it. Extracted _setup_server_disk_logging and its helpers straight out of run.py by AST so it was the real function, pointed HOME at a scratch dir, and crashed the process with ctypes.string_at(0). The Current thread ... (most recent call first): block lands in server-<stamp>-pid<N>.log on disk, and the console gets only the pre crash marker. That is your claim, confirmed. Every filename the writer produces matches the reader's filter. Retention keeps exactly 20 and cannot reach outside the directory. Opt out creates nothing. An uncreatable log dir returns None without touching startup.

I also checked the thing that would have quietly sunk it on Windows: open(..., buffering=1) in text mode is fully supported there, TextIOWrapper flushes on newline, and CPython opens with _SH_DENYNO so Tauri can read the file while the backend still holds it open. No exclusive lock, no unflushed tail.

Two files is the right number, incidentally. start_backend is only ever called from a command, so there is no supervisor retry loop that could push a crash log out of a two file window.

What I pushed

bf8a41063, one commit. The selection took entries by name and let read_tail reject them afterwards, but only two files are collected, so a rejection after selection still costs a slot, and the slot it costs is the one holding the stack. Verified against your code as it stood:

  • A FIFO named server-*.log hung report generation. File::open on a FIFO blocks until a writer appears, path_has_symlink returns false for one and fs::metadata succeeds instantly, so nothing caught it. Measured: still blocked past 5s. read_tail runs on the blocking pool behind collect_support_diagnostics, so this wedges a thread and the command never returns, at the exact moment the user is already trying to report a crash. This is the one I would not have shipped.
  • Two directories named server-*.log took both slots and the real crash log did not make the report. Graceful (EISDIR on Unix, ERROR_ACCESS_DENIED on Windows) but the stack was gone.
  • Same for two symlinks. read_tail refused them correctly, after the log they displaced was already out.

The fix filters during selection and pushes a warning per rejection, which is what scan_phase_logs_in_dir already does in phase_log.rs for the same reason.

Four smaller things in the same commit:

  • Say which directory was searched when there is nothing to collect. _infer_studio_home_from_venv in utils/paths/storage_roots.py moves studio_root() purely from sys.prefix, with no env var involved, so the UNSLOTH_STUDIO_HOME scrub in process.rs does not reach it. I reproduced that with zero env vars set: an env mode install writes to <alt>/logs/server/ while the reader looks in ~/.unsloth/studio/logs/server. Managed spawns always agree, so this only bites an adopted backend, but a bare unavailable could not be told apart from "the backend logs somewhere else".
  • Report a read_dir failure that is not NotFound. A missing directory is the ordinary case and stays silent; a permission wall did not deserve to.
  • Skip names carrying a control character. A filename with a newline is legal on Unix and turned one header line into three, forging key=value lines inside a line oriented report.
  • The footer still advertised log sections <=1000 lines/200KiB each for sections capped at 400/64KiB.

Tests: one per rejected entry type, the FIFO one on a deadline since a regression there hangs the suite rather than failing it. Your ordering test could not say which key ordered the result because its names and mtimes agreed, so I added one where they disagree. And the budget assertion moved from 128KiB to 80KiB, because at 128KiB a mutation of SERVER_LOG_TAIL_MAX_BYTES to 100KiB passed unnoticed. I mutation checked all six assertions and each one fails when it should.

cargo test --locked --no-fail-fast --bins: 372 passed, three consecutive runs. cargo fmt --check clean on this file, and I left the pre existing diffs elsewhere alone. The new code and its cfg gating type check for x86_64-pc-windows-msvc and aarch64-apple-darwin.

Not this PR, but worth a look

  • _setup_server_disk_logging opens with "w", so a same second plus same pid restart truncates the previous session log. Negligible on Linux, less so on Windows where pids recycle aggressively, and crash then immediate restart is precisely when the truncated file is the one that mattered. "x" with a suffix retry would close it.
  • The tail survives a hard kill per line, not per byte. A trailing partial line with no newline is lost. Correct behaviour, just worth knowing when reading one of these.
  • Redaction holds up well on realistic session log content. Bearer tokens, hf_/sk- keys, JSON shaped keys, emails and home paths all get masked. What it cannot mask is free prompt or dataset text, which backend stdout does carry. That is a property of the source rather than of this change, but these tails are the first thing to put a lot of it in a report.

Nice find on the faulthandler directory. Approving once CI comes back on the new base.

Comment-only. Same prose, fewer lines: 65 comment lines down to 50, with the
code byte-identical after stripping comments.
The smaller cap on the backend session sections only makes sense because the
section sits above the phase logs and enforce_report_limit chops the END of the
body. Nothing asserted that placement, so a section moved below the phase logs
would still pass every existing test while quietly dropping the stack out of any
report that overflows the 1MiB clipboard budget.

Measured on the fixture: 1320788 bytes in, 1048576 out, stack retained.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Another round soon, please!

Reviewed commit: 4fc6cc3e00

ℹ️ 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".

Comment-only, one block. The opening pass covered the same code an hour earlier,
so there was little left: code is byte-identical with comments stripped.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

`entry.metadata()` is `stat`, which POSIX specifies needs no permission on the
file itself, only search permission on the path prefix. So a `server-*.log` the
desktop user cannot open passed every check in the selection loop, took one of
the two slots, and `read_tail` only reported the permission error afterwards,
by which time the readable crash log was already out of the report.

Reproduced before the fix: two mode-000 logs newer than a readable one took both
slots and the report carried no stack, only two `unavailable=Permission denied`
lines. Not hypothetical either way round: a backend once started under sudo, or
under a umask that strips the owner read bit, leaves exactly this behind.

Probing with `File::open` is safe at this point in the loop specifically because
the regular-file check runs first, so the probe can never be the FIFO whose open
blocks.

Regression test asserts the readable log wins and both rejections are reported;
removing the probe fails it. cargo test --locked --no-fail-fast --bins: 452 passed.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

Mode 000 does not deny root, or anyone holding CAP_DAC_OVERRIDE, so in a
root-based container the fixture cannot express its own precondition: both
locked files stay readable candidates and the assertions report the environment
rather than a defect.

Probe the fixture instead of testing the uid, since the capability can be held
without being root. Same reasoning as
studio/backend/tests/test_recommended_folders_permission.py, which skips itself
under root for exactly this.

Verified both directions: with the fixture left readable the test skips instead
of failing, and with the product-side File::open probe removed it still fails as
an unprivileged user, so the guard does not neuter the regression it exists for.
cargo test --locked --no-fail-fast --bins: 452 passed.
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: bf8c112fd5

ℹ️ 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".

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 24, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 24, 2026
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@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: 017a70fe59

ℹ️ 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".

Comment on lines +366 to +367
let server_log_dir = logs_dir().join("server");
let server_logs = newest_server_logs_in(&server_log_dir, SERVER_LOG_TAIL_FILES, warnings);

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 Search the adopted backend's actual log root

When the desktop adopts a backend whose studio_root() was inferred from an installer venv outside ~/.unsloth/studio (or otherwise uses a non-legacy root), _setup_server_disk_logging writes beneath that backend root, but this code searches only Tauri's fixed logs_dir(). The nearby comment acknowledges this case, yet the resulting report merely says unavailable and still omits the crash log this change is intended to capture; resolve or obtain the adopted backend's root and include its logs/server directory in the candidate search.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Real gap, but not one this PR can close, so leaving it out deliberately rather than by oversight.

Tauri has nothing today from which to derive an adopted backend's log directory. /api/health exposes studio_root_id, and main.py:272 documents that as a same-install discriminator that is empty when no installer token is present, not a path. Closing this means adding a session-log-path field to the health payload and bumping the desktop protocol so Tauri can consume it, which is a change to the backend API and the adoption path, not to the report collector.

It is also not a regression: before this PR nothing collected that directory for anyone, so an adopted backend is no worse off, and the searched= field added in bf8c112 means the report now names the directory it looked in rather than an ambiguous unavailable. Worth its own PR, and I would rather do it there than widen this one.

// that `read_tail` only refuses afterwards. A backend once started under sudo
// leaves exactly that behind. Safe to open now: non-regular files are already
// out, so this cannot be the FIFO that blocks.
if let Err(error) = File::open(&path) {

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 Keep the validated file handle for reading

When another same-user process can modify the server-log directory while diagnostics are collected, this validation is ineffective because the successfully opened handle is immediately discarded and append_tail_section_capped later reopens the pathname. A process can replace the entry after this check with a FIFO, causing File::open in read_tail to block indefinitely, or with a symlink to make the report read a different file despite the explicit guards; pass the validated open handle through to the tail reader (or reopen atomically with no-follow/nonblocking semantics) instead.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The race is real but it is not what the probe is for, and closing it properly is a bigger change than this one.

read_tail already resolves the path three times before it reads a byte: path_has_symlink at report.rs:584, fs::metadata at 587, File::open at 589. That shape predates this PR and covers tauri.log, tauri.log.1 and every phase log, so check-then-open is the module's existing contract, not something the probe introduced. Passing a handle through would mean changing read_tail's signature and the symlink-guard semantics for all of those callers, which belongs in a change about read_tail rather than one about which files reach it.

The distinction I am drawing against the FIFO fix in 6a96b5f: that one needed no attacker and no timing. A stale FIFO or a mode-000 file simply sitting in the directory wedged or displaced the crash log deterministically, every single collection. This needs a hostile same-user process hitting a microsecond window, and one that already has write access to the user's home directory. The probe is fully effective against the first and I am not claiming it defends the second.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: 4bfa6889ad

ℹ️ 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 b57ad59 into unslothai:main Aug 25, 2026
39 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants