Skip to content

fix(api): preserve refusal text in collected connection replies - #16435

Merged
danielhanchen merged 2 commits into
unslothai:mainfrom
hsusul:fix/connection-refusal
Nov 2, 2026
Merged

danielhanchen merged 2 commits into
unslothai:mainfrom
hsusul:fix/connection-refusal

Conversation

@hsusul

@hsusul hsusul commented Nov 1, 2026 •

Copy link
Copy Markdown
Contributor

Why

Nonstream clients of saved Chat Completions connections receive an empty assistant message when a provider sends refusal text. The stream collector discards delta.refusal even though the streaming route preserves it.

Closes #16434

What changed

  • Accumulate refusal fragments in _collect_chat_completion and include the completed refusal in the assistant message.
  • Add route tests through the real provider client and ASGI handler, plus mixed-field and empty-refusal controls.

Scope

  • Preserve Chat Completions refusal text for saved connections. Other provider protocols and scheduled-task refusal presentation are outside this change.

Blast Radius

The collector also serves scheduled provider calls. Existing connection and scheduler tests pass; absent, null and empty refusal deltas retain the existing message shape.

Verification

  • pytest studio/backend/tests/test_connection_refusal.py -q --tb=short reports 3 failed, 4 passed before the fix and 7 passed after it. The failures assert missing refusal text.
  • The new regression, test_connection_model_routes.py and test_scheduled_tasks.py report 270 passed, 1 warning. The existing Starlette/httpx deprecation warning remains.
  • A separate API reproduction preserves the complete refusal after the fix. Outbound provider HTTP is mocked; no live model call was made. Repository formatting, Ruff and git diff --check pass.

Studio UI regression check

Base 681111a2e vs head db348b580. Functional: NO_REGRESSION, UI coverage 88%, 4 visual change(s), 3 text-only change(s). Only steps whose screenshots differ are shown.

parallel/two_tabs_ui: masks cover 7% of the shot | reproduced on confirm (VISUAL_DIFF) | Sidebar thread title differs between concurrent tabs (fruits/animals); direction reverses on confirmation. Both tab replies and training/chat assertions pass. Interactive chat uses the unchanged streaming path.
parallel/two_tabs_ui

parallel/train_and_chat: masks cover 8% of the shot | reproduced on confirm (VISUAL_DIFF) | Sidebar thread title differs between concurrent tabs (fruits/animals); direction reverses on confirmation. Both tab replies and training/chat assertions pass. Interactive chat uses the unchanged streaming path.
parallel/train_and_chat

crawl/r_hub: masks cover 38% of the shot | reproduced on confirm (VISUAL_DIFF) | Catalog snapshot/focus varies; confirmation changes a different crawl interaction. Hub code is unchanged. No functional assertion failed.
crawl/r_hub

macos-15/crawl/r_export: macOS staging: the Images sidebar submenu is expanded on the after capture; export fields and disabled state match. The export and frontend code are unchanged. macOS coverage is 90.1%.
macos-15/crawl/r_export

Step Text / structure change
parallel/load_parallel {'removed': [], 'added': ['Estimated Memory Usage', 'GPU', '', 'Total', '', '#ctrl button:GPU: ', '#ctrl button:Total: ']}
parallel/stop_training {'removed': ['65/4.1k', 'Three fruits are named:', '#ctrl button:Name three fruits.', '#ctrl button:Context usage: 65 of 4.1k tokens'], 'added': ['Name three an
crawl/r_studio

@hsusul
hsusul requested a review from danielhanchen as a code owner November 1, 2026 23:33
danielhanchen added a commit to unslothai/unsloth-zoo that referenced this pull request Nov 2, 2026
…the legacy Qwen3-VL-MoE packing it loads silently wrong (#2357)

## Summary

On unslothai/unsloth CI, `Core zoo (HF=4.57.6 + TRL<1)` fails on current
main (`9e0658a4`). It is red on every unsloth PR that resolves it, for
example unslothai/unsloth#16435 and #16407. The cause is four cases of
`tests/test_moe_expert_lora_vanilla_load.py::test_unsloth_expert_lora_loads_in_vanilla_peft`,
which came in with #2343. The child scripts only fit transformers 5:

```
llama4:        TypeError: PeftAdapterMixin.load_adapter() got an unexpected keyword argument 'use_safetensors'
qwen3_vl_moe:  AttributeError: 'NoneType' object has no attribute 'get'   (config.rope_scaling.get("mrope_section", ...))
```

- 4.x `load_adapter` has no `use_safetensors` argument; PEFT's
`load_peft_weights` already falls back to the `.bin` there.
- The tiny Qwen3-VL-MoE text config passes only `rope_parameters`, while
4.x reads `rope_scaling` and `rope_theta`.

## What the fixed fixtures then show

With both fixed, three of the four cases pass on transformers 4.57.6.
The fourth is a real gap that the test was written to catch:
`qwen3_vl_moe` with the legacy `grouped_by_expert` lora_B packing.

- The test (and the `_legacy_grouped` docstring) say vanilla PEFT
refuses the legacy packing by shape, so it never loads with experts
mixed.
- On transformers 5 that holds: the save swaps the Qwen3-VL-MoE factors,
the shapes stop matching, and vanilla raises `size mismatch`.
- On 4.x those stacks are already hidden-first, so nothing is swapped.
`test_qwen3_vl_moe_swaps_factors_only_when_transformers_stores_another_layout`
pins that.
- So the shapes match and vanilla PEFT loads the adapter silently wrong:

| transformers | qwen3_vl_moe, grouped_by_expert, vanilla load |
|---|---|
| 5.22.1 | refuses: `size mismatch` |
| 4.57.6 | loads, logits off by 0.62 |

`rank_major` (the default) loads correctly on both: 2.7e-07. Llama-4 is
refused by shape on both, because its factors are always swapped.

This needs a product change in how a legacy-packed adapter is saved, so
it does not belong in a CI fix. I left it visible as a strict xfail for
that one case on transformers 4.x, with the reason. If the product
starts refusing or converting it, the strict xfail turns red and points
here.

## Change

`tests/test_moe_expert_lora_vanilla_load.py`:
- The child config sets `rope_scaling` and `rope_theta` on transformers
4.x.
- The `.bin` `load_adapter` call passes `use_safetensors = False` only
on transformers 5.
-
`test_unsloth_expert_lora_loads_in_vanilla_peft[qwen3_vl_moe-grouped_by_expert]`
is a strict xfail on transformers 4.x.
- Every other assertion and tolerance is unchanged.

## Testing

`tests/test_moe_expert_lora_vanilla_load.py`, torch 2.10 CPU:

| transformers | PEFT | main | this branch |
|---|---|---|---|
| 4.57.6 | 0.19.1 (the CI lane) | 4 failed, the two errors above | 10
passed, 1 xfailed |
| 4.57.6 | 0.21.2 | | 10 passed, 1 xfailed |
| 5.22.1 | 0.19.1 | | 11 passed |
| 5.22.1 | 0.21.2 | | 11 passed |
@danielhanchen danielhanchen self-assigned this Nov 2, 2026
@shimmyshimmer

Copy link
Copy Markdown
Member

Review record for #16435, carried over from the mirror it was reviewed on: danielhanchen/unsloth-staging-review#678.

Findings are quoted as posted and attributed to the account that posted them. The reactions shown are the triage recorded on the mirror; none were re-applied here. Commits are named as the mirror's, with this PR's equivalent where one was found.

Round 1: reviewed mirror dafb9dd7b0 (this PR's db348b580)

chatgpt-codex-connector[bot] (on the mirror)

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: dafb9dd7b0

No triage reaction was recorded on the mirror

Verdict

The round converged at mirror dafb9dd7b0 (this PR's db348b580).

This is the review as it stood at that commit. Anything pushed to this PR afterwards was not part of it.

danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 2, 2026
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Nov 2, 2026
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Nov 2, 2026
danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 2, 2026
@danielhanchen
danielhanchen merged commit 98f96f0 into unslothai:main Nov 2, 2026
danielhanchen added a commit that referenced this pull request Nov 2, 2026
…#16464)

## Summary

`Parity verdict, scored against the null` fails on unrelated PRs whose
base includes #16300 (`d56738f404`, the turn navigator at the chat's
left edge). In the last two hours it failed on #16458 (a backend-only
change) and on staging for #16463 and #16435, each time the same way:

```
matched:                    0
unstable actions differing: 32  (expected to vary; not a verdict)
NOTHING WAS COMPARED. ... This is not a pass.
```

In the null control (the same build on both arms), every action's thread
scaffold digest differs, even between two repetitions on the same arm,
while its length stays equal (`thread scaffolding outside any message
(24167->24167c)`). That is an instance id leaking into the structural
signature.

#16300 renders the navigator inside the thread root, outside every
message, as one button per turn with `data-turn-id={openerId}`.
`openerId` is the turn's opening message id (`thread-turns.ts` pushes
`message.id`). `scene/parity.js` already drops the values of
`data-message-id`, `data-thread-id` and the other id attributes it knew
about, but not this new one. Studio's message ids are short and random,
so `ID_RE` does not catch them in the value either.

The product is fine; the instrument fell behind the DOM.

## Change

- **`tests/studio/studiobench/scene/parity.js`:** an attribute is
volatile if it is in `VOLATILE_ATTRS`, or if its name matches
`data-*-id`. A volatile attribute keeps its presence in the signature
and loses only its value, as before.
- Every `data-*-id` in the frontend names an instance, e.g.
`data-turn-id`, `data-queue-item-id`, `data-bookmark-id`,
`data-entry-id`.
- So the next one added inside the thread cannot silently empty the
verdict the way this one did.
- Non-id data attributes (`data-turn`, `data-role`, `data-state`, ...)
still compare by value.
-
**`tests/studio/studiobench/fixture/selftest/test_studiobench_parity_digest.py`**
(these run the shipped `parity.js` under node):
- `test_every_data_id_attribute_is_volatile`: two different
`data-turn-id` values sign the same, a button with the attribute still
differs from one without it, and the same holds for
`data-queue-item-id`.
- `test_a_data_attribute_that_is_not_an_id_still_moves_the_signature`:
`data-turn="1"` against `"2"` still differs.

## Testing

- `tests/studio/studiobench/fixture/selftest`, `sweep/selftest` and
`analysis/selftest`: 606 passed.
- Sabotage: with main's `parity.js`,
`test_every_data_id_attribute_is_volatile` fails; the other new test
passes on both.
- Not proven here: I did not rerun the full parity sweep locally. The
PR's own parity job is the end-to-end check. On main's harness it should
report a non-zero `matched` count on this PR, as the runs before #16300
did (28 or 29).
oobabooga pushed a commit that referenced this pull request Nov 4, 2026
## What was broken

Importing an OpenAI chat drops assistant refusal replies. The imported
conversation shows two user turns in a row instead of the refusal
between them.

## Repro

1. Use main at `81dc73ac43b3bb487820752a4e749f6cf2c3f05f`.
2. Import this message JSONL:

```jsonl
{"role":"user","content":"A question"}
{"role":"assistant","content":null,"refusal":"I cannot help with that request."}
{"role":"user","content":"Another question"}
```

3. Only the two user turns appear. The same reply is also dropped when
represented as a `refusal` content part or imported inside a
training-style `messages` record.

## Fix

Read refusal text from either representation in [OpenAI's message
types](https://github.com/openai/openai-node/blob/master/src/resources/chat/completions/completions.ts).
Use the top-level `refusal` only when content produces no parts, so an
existing answer is not duplicated.

This is separate from #16435, which fixes saved-connection response
collection. Chat-file imports do not pass through that collector.

## Test

Tests cover both JSONL layouts and refusal formats, including empty
content. They also check message order, parent links, and that an
existing text answer takes precedence. The two refusal tests fail before
the fix; the precedence test already passes.

From `studio/frontend`, the final test counts are:

```text
$ node --experimental-strip-types --test --test-reporter=tap tests/message-jsonl-import.test.ts
# tests 18
# pass 18
# fail 0
```

The full frontend suite reports 14,786 passing tests, zero failures, and
one Windows-only skip on macOS. Locale parity, typecheck, build, bundle
budget, and all seven repository lint commands also exit successfully.
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.

[Bug] Nonstream saved-connection replies discard refusal text

3 participants