Skip to content

Studio: keep one corrupt session file from aborting the import - #17550

Merged
danielhanchen merged 8 commits into
unslothai:mainfrom
DimitriChrysafis:studio-import-corrupt-session
Nov 19, 2026
Merged

danielhanchen merged 8 commits into
unslothai:mainfrom
DimitriChrysafis:studio-import-corrupt-session

Conversation

@DimitriChrysafis

@DimitriChrysafis DimitriChrysafis commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Problem

_import_session catches OSError and ImportError around read_transcript.
Any other exception from one file, such as a malformed record ({"message": null}
reaches claude.py's record.get("message", {}).get(...) as None.get, an
AttributeError), a torn .jsonl.zst, a crash inside _pending_messages,
propagates out of run_import, surfaces in the route as a 500, and every
session still waiting in project.sessions is silently skipped while the ones
already done stay imported.

A cyclic parentId chain is worse than an exception: the ancestor walk in
_pending_messages never terminates, so the import hangs outright.

Fix

The claude.py reader now drops a record whose message is not an object before
it becomes a turn (the Cursor reader already does this). It keeps its place in the
ancestry chain but never touches the streamed-reply bookkeeping, so a malformed
record costs only itself and the rest of that session imports on the same branch.

As a backstop for failures the readers cannot absorb (a torn .jsonl.zst, a
crash inside _pending_messages), move the per-file guard up to _import_project: each session runs inside
try, and a file-level failure becomes a warnings entry ("<name>: could not be imported") that the route already returns in the summary. Sessions that were
half-imported before the failure are covered by the existing "shell thread, no
mark" recovery on the next run.

SQLite errors still propagate after the existing transaction rolls back. A failed
checkpoint write or database operation must not be reported as a corrupt session file.

The ancestor walk gets the seen bound claude.py already uses for the
same climb: a cyclic chain roots the turn (there is no surviving ancestor to
hang it off, and a missing parent orphans the row) instead of looping, and the
other member of the cycle then attaches to it normally.

Tests

tests/test_external_import.py gains four cases: a {"message": null} record
ahead of real turns (the session imports, no warning), one inside a streamed
parallel-tool-call reply (the answer keeps the second call's branch), a reader that raises on one
session file sorted ahead of a healthy one (the healthy chat still imports and the
bad file lands in warnings), and a re-import whose new turns
form a two-node parentId cycle (the run terminates, both rows land, no
dangling parents). On the old code the first test raises AttributeError out
of run_import and the second hangs; all 34 pre-existing tests still pass.

tests/test_external_import_atomic.py also checks that OperationalError and
ProgrammingError from checkpoint writes propagate after messages and the
checkpoint roll back, and that a retry succeeds. The four existing checkpoint
failure tests keep their original raise/rollback assertions.

Validation on Python 3.12 after merging current main: 60 passed across test_external_import.py,
test_external_import_atomic.py, and test_external_import_single_read.py.
The pinned Ruff checks and formatter pass for the changed files.

_import_session caught OSError and ImportError around read_transcript,
so a record the parser chokes on ({"message": null} -> AttributeError),
a torn .jsonl.zst, or a cyclic parent chain escaped per-file handling.
The exception surfaced in the route as a 500 and every session still
waiting in project.sessions was skipped, with the files already done
left imported. Catch per session instead and report the file in
warnings; bound the ancestor walk in _pending_messages so a cyclic
chain roots the turn instead of hanging the import.
@danielhanchen

Copy link
Copy Markdown
Member

(Python 3.13, a-f) fails four tests in studio/backend/tests/test_external_import_atomic.py, all with the same shape:

tests/test_external_import_atomic.py:89: in test_first_import_rolls_back_messages_when_checkpoint_fails
    pytest.raises(sqlite3.IntegrityError, match = "checkpoint write failed"),
E   Failed: DID NOT RAISE IntegrityError

The other three are test_incremental_import_rolls_back_and_preserves_studio_changes, test_recreated_chat_drops_its_deleted_incarnations_checkpoint and test_checkpoint_only_failure_keeps_existing_import_intact.

Those tests inject a failing checkpoint write in _record_external_import_mark and expect the import to raise after the messages are rolled back. With the new per-session handling, that IntegrityError is now caught and the import finishes (external_import_finished ... "chats": 0), so nothing reaches pytest.raises. These pass on main.

If skipping a broken session is the intended behaviour for these cases too, the atomic tests should assert the rollback (no messages, no checkpoint) and the skipped count instead of the raise. If not, a database error like this probably should not be treated the same as a corrupt session file.

@DimitriChrysafis

Copy link
Copy Markdown
Contributor Author

Fixed in 37c35de. SQLite errors now propagate after rollback instead of being treated as corrupt session files. The four existing atomic tests pass unchanged, and I added coverage for OperationalError and ProgrammingError too. All 45 import tests pass locally on Python 3.13; CI is running.

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-19T06:47:12.786370Z 6ad86af Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: 8211708644

ℹ️ 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 added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 18, 2026
danielhanchen added a commit that referenced this pull request Nov 18, 2026
)

## Record the NPU detector's file load in the risky-loader baseline

The risky-loader lint in `Source lint` fails on `main` since #18049. It
shows up on unrelated PRs, for example #17550:

```
1 risky loader call site(s) not in the baseline:
  unsloth_cli/_npu.py:88  [dynamic-import] spec_from_file_location
```

### Cause

#18049 added `npu_detected()` to `unsloth_cli/_npu.py`. The CLI uses it
to reuse Studio's stdlib-only NPU detector without importing the Studio
backend. It loads the file through
`importlib.util.spec_from_file_location`, which
`scripts/lint_risky_loaders.py` flags until the call site is reviewed
and recorded.

### Why it is safe

The path is fixed: `Path(__file__).resolve().parents[1] /
"studio/backend/utils/hardware/npu.py"`. That is a file shipped in the
same package, and no user, network or checkpoint input chooses it. Any
failure, including a missing file, is caught and returns `False`.

So the lint's own guidance applies: record the call site with a reason
rather than change the code.

### Fix

One new entry in `scripts/risky_loaders_baseline.json`, generated with
`python scripts/lint_risky_loaders.py --update`. The generated `REVIEW
ME` placeholder is replaced with the reason above. No other entry moves,
and no code changes.

### Verification

- `python scripts/lint_risky_loaders.py`: fails on `main` on this call
site and passes with this change. `--self-test` passes too.
- The repo's risky-loader tests pass: 46 passed.
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@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: 27673067c5

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

for index, (record, node, parent_node) in enumerate(records):
uuid = str(record.get("uuid") or "")
reply = record.get("message", {}).get("id") if record["type"] == "assistant" else None
reply = _message(record).get("id") if record["type"] == "assistant" else None

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 Skip malformed records before updating reply state

When an assistant record with message: null falls between two streamed blocks sharing the same message.id, normalizing it to {} still runs the reply bookkeeping below and clears active_blocks. In a parallel-tool-call sequence a1 -> a1b, where the next answer follows a tool-result record parented to a1, this freezes tail_of[a1] at a1: the answer is incorrectly parented to a1 instead of a1b, excluding the second valid tool call from the selected conversation branch. I reproduced this through run_import; it reports no warning and checkpoints the incorrect graph, so re-import does not repair it. Skip malformed records before updating reply state, while preserving their ancestry links.

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.

Fixed in 6ad86af: records whose message is not an object are dropped in the first pass, so they keep their ancestry link but never touch reply state; added a regression test for the a1 -> null -> a1b case.

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🎉

Reviewed commit: 6ad86afab0

ℹ️ 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 added a commit that referenced this pull request Nov 19, 2026
## Summary

Two gloo tests started failing in the CPU tensor-parallel shards on
several unrelated PRs (#18290, #17550):

```
tests/test_tp_kv_replicated_gloo.py::test_kv_heads_below_tp_are_replicated_per_rank
E   assert (0, 16) == (0, 128)

tests/test_tp_native_gloo.py::test_tp2_tied_norm_weight_is_summed_once
E   Max absolute difference: 7.361173629760742e-06   (tolerance 3.4e-06)
```

On a host with a cold Hugging Face cache, both fail every time,
including on commits from before any recent tensor-parallel change.

## Cause

Not a code change. The gloo tensor and pipeline parallel builders
(`build()` in `tests/test_tp_native_oracle.py` and
`tests/test_pp_native_gloo.py`) read a tiny Hub repo's `config.json` at
its latest revision and build random weights from it.
`trl-internal-testing/tiny-Qwen3ForCausalLM` was re-uploaded upstream on
2026-11-19 (commit `92ee0a3c80`), and its config changed `head_dim` from
128 to 16:

| revision | hidden_size | heads / KV heads | head_dim |
|---|---|---|---|
| `25bb9b8963` (previous) | 8 | 4 / 2 | 128 |
| `92ee0a3c80` (current) | 8 | 4 / 2 | 16 |

- `test_kv_heads_below_tp_are_replicated_per_rank` hardcoded 128 for the
expected per-rank KV row slice.
- `test_tp2_tied_norm_weight_is_summed_once` compares parity values that
the new shapes move just past their tolerance.

Runners that still have the old config cached pass and fresh fetches
fail. That is why the same base, with the same package versions
(transformers 5.18.0, torch 2.10.0), was green on some PRs and red on
others. `trl-internal-testing/tiny-Qwen3MoeForCausalLM` was re-uploaded
the same day.

The tensor-parallel code is correct. It slices by the config's
`head_dim`.

## Fix

Test-only:

- `tests/_tiny_fixture_revisions.py` pins a full commit id for every
tiny repo the two builders use:
  - Qwen3 and Qwen3-MoE at the revision before the re-upload;
  - the rest at their current revision, the one CI has been green on.
- Both builders load the config with `AutoConfig.from_pretrained(repo,
revision = revision(repo))`. Moving a fixture is now a deliberate edit
to the pin table.
- `tests/test_tiny_fixture_revisions_pinned.py` fails if either builder
module names a tiny repo without a pin, if a pin is not a full commit
id, or if a builder stops loading at the pin.
- `test_kv_heads_below_tp_are_replicated_per_rank` also pins `head_dim`
in its own overrides and derives the expected rows from it, so it states
the shape it checks.

## Verification

| | result |
|---|---|
| `test_tp_kv_replicated_gloo.py`, main | 1 failed, 10 passed |
| `test_tp_kv_replicated_gloo.py`, this branch | 11 passed |
| `test_tp_native_gloo.py` (`tied_norm`), main | 1 failed |
| `test_tp_native_gloo.py`, this branch | 57 passed |
| `test_pp_native_gloo.py`, this branch | 24 passed |
| `test_tiny_fixture_revisions_pinned.py` | 3 passed |
| `tp_native.py` sabotaged to give every rank KV head 0 | the KV test
fails on ranks 2 and 3 (`(0, 16)`) |

So the per-rank KV head check still catches wrong slicing. ruff is
clean.
@danielhanchen
danielhanchen merged commit 9ac6b30 into unslothai:main Nov 19, 2026

@LeoBorcherding LeoBorcherding left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for the fix, @DimitriChrysafis. Posting the results for the record now that it has merged.

Tested at 27673067 against base 9150fd9 on a Colab L4 (Python 3.13). I called the real POST /api/import/{source} on a booted Unsloth Studio, using fake ~/.claude and ~/.codex homes.

case base this PR
Claude import with 8 sessions (one {"message": null}, one bad image source, one empty, one non-UTF-8) 500, 2 chats, and a retry gives 500 again 200: 6 chats, 1 skipped, 1 warning; a rerun adds nothing
Codex: a torn .jsonl.zst 200, skipped silently 200, skipped silently
Codex: a garbage-byte .jsonl.zst 500, ZstdError 500, ZstdError
backend tests (own files) 54 passed 59 passed

Run against base, two of the new tests fail and the third one hangs. The DB-errors test passes on base too, so it's a regression guard rather than a repro.

The Claude side is fixed. The Codex case still returns 500: zstandard.ZstdError isn't an OSError, and _meta only catches (OSError, ImportError) (codex.py:41). It escapes from list_projects (init.py:405) before the new per-session guard runs (:385-391). So one bad file in ~/.codex blocks the whole Codex import. Catching Exception there would close it. It would also cover Python 3.14, where the stdlib compression.zstd raises EOFError on a torn file; I checked that by calling the function locally, not through the route.

A smaller thing that isn't a regression: a torn .zst is counted as skipped with no warning. A small single-block file decodes to 0 records even when 95% of it is there. A 3000-line file torn the same way recovers 2372 records.

Not tested: the warning toast in the UI, the Cursor import.

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.

3 participants