Skip to content

studio: scope cancel-cleanup to in-flight tmp dirs; walk back tool_call_id - #5488

Merged
danielhanchen merged 5 commits into
mainfrom
studio-training-cleanup-and-toolcall
May 18, 2026
Merged

danielhanchen merged 5 commits into
mainfrom
studio-training-cleanup-and-toolcall

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

Two follow-ups to #5375 on the training-cancel path and chat tool-message handling.

Cancel-cleanup scope

_cleanup_cancelled_checkpoints in core/training/training.py previously rmtreed every checkpoint-<int>/ subdir on Cancel. The audit memo behind that change flagged ~67 MB of stale state after save_steps=20 + step-200 cancel; that residue is the HF Trainer atomic-rename partial (tmp-checkpoint-<step>/), not the completed checkpoint-<step>/ dirs the user expects to resume from.

The cleanup now:

  • targets only tmp-checkpoint-* subdirs
  • skips when output_dir itself is a symlink
  • skips symlinked children (so the realpath containment cannot be levered into deleting external content via a symlinked partial)
  • still refuses to touch anything whose realpath isn't under outputs_root()

tool_call_id walkback

ChatMessage._validate_role_shape stamped a random secrets.token_hex id when a role="tool" message arrived without tool_call_id. That id is uncorrelated with the prior assistant's tool_calls[].id, so strict passthrough backends (OpenAI, Anthropic) reject the request as orphaned and llama.cpp treats the tool result as "no preceding call" and hallucinates.

The synthesis moves up to ChatCompletionRequest.model_validator, where the whole conversation is visible. For each tool message without an id we walk back to the most recent earlier assistant turn that has tool_calls, prefer a function.name match against the tool message's name, otherwise take the first unconsumed tool_call. Crossing a role="user" turn breaks the lookup (a tool result must belong to the current turn). Random synth is the fallback only when no candidate assistant turn exists, which preserves the prior round-trip guarantee for orphaned messages.

ChatMessage._validate_role_shape no longer mutates tool_call_id; the per-message validator only enforces non-empty content for role="tool".

Test plan

  • tests/test_cleanup_cancelled_checkpoints.py (new): pins that completed checkpoint-<int>/ survive, in-flight tmp-checkpoint-* are removed, non-int suffixes (checkpoint-final, checkpoint-best) are left alone, output_dir outside outputs_root() is refused, symlinked output_dir and symlinked child are both skipped, missing output_dir is a no-op.
  • tests/test_inference_model_validation.py: 6 new walkback cases (name-match preference, first-unconsumed fallback, explicit id passthrough, multi-tool-result pairing, synth-on-no-parent, no-cross-user-turn invariant).
  • tests/test_openai_tool_passthrough.py: the two pre-existing ChatMessage-level synth-on-missing tests are rewritten to assert that the per-message validator now leaves tool_call_id untouched (resolution coverage lives in the request-level tests above).
  • Full pass: pytest tests/test_inference_model_validation.py tests/test_openai_tool_passthrough.py tests/test_anthropic_messages.py tests/test_responses_tool_passthrough.py tests/test_cleanup_cancelled_checkpoints.py -> 173 tests pass.

…ll_id

Two follow-ups to #5375's training and chat hardening.

_cleanup_cancelled_checkpoints used to rmtree every checkpoint-N
directory on Cancel. That is the opposite of what the user expects.
A user cancelling an 8h run with save_steps=2000 loses every
completed checkpoint they could have resumed from. The 67 MB residue
the audit memo flagged is the HF Trainer atomic-rename partial
(tmp-checkpoint-N), not the completed ones. The cleanup now targets
only tmp-checkpoint subdirs; completed checkpoint-N directories are
user-owned and stay. Symlinked output_dir and symlinked children are
skipped so the realpath containment cannot be levered into deleting
arbitrary content via a symlink trick.

ChatMessage._validate_role_shape stamped a random secrets.token_hex
id on tool messages with no tool_call_id. That id is uncorrelated
with the prior assistant tool_calls id, so strict passthrough
backends (OpenAI, Anthropic) reject the request as orphaned and
llama.cpp treats the tool result as "no preceding call" and
hallucinates. The synthesis moves up to ChatCompletionRequest, where
the whole conversation is visible: for each tool message missing an
id we walk back to the most recent assistant turn with tool_calls
(stopping at user turns), prefer a function.name match, otherwise
take the first unconsumed tool_call. Synthesis is the fallback when
no candidate assistant turn exists, preserving the prior round-trip
guarantee for orphaned tool messages.

Tests:
  - test_cleanup_cancelled_checkpoints.py (new): pins that completed
    checkpoint subdirs survive, tmp-checkpoint partials are removed,
    non-int suffixes (checkpoint-final, checkpoint-best) are left
    alone, output_dir outside outputs_root is refused, symlinked
    output_dir and symlinked child are both skipped, missing dir is
    a no-op.
  - test_inference_model_validation.py: 6 new walkback cases covering
    name-match preference, first-unconsumed fallback, explicit-id
    passthrough, multi-tool-result pairing, synth-on-no-parent, and
    no-cross-user-turn invariant.
  - test_openai_tool_passthrough.py: the two ChatMessage-level
    synth-on-missing tests are rewritten to assert that the per-
    message validator now leaves tool_call_id untouched; resolution
    coverage lives in the request-level tests above.

@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: 8c9e3f6f3c

ℹ️ 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 +634 to +635
if msg.role != "tool" or msg.tool_call_id:
continue

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 Mark explicit tool results as consumed before filling missing ids

When a tool result already has tool_call_id, this continue bypasses the consumed tracking, so mixed conversations can reuse the same assistant call id. For example, if an assistant emits call_a and call_b, the client sends the first tool result with explicit tool_call_id="call_a", and the second tool result omits the id, the walkback still treats call_a as unconsumed and assigns it again, leaving call_b unmatched; strict passthrough providers then reject the tool-result sequence.

Useful? React with 👍 / 👎.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request refines the training checkpoint cleanup logic to target only temporary directories, implements a request-level validator to resolve missing tool call IDs via conversation walkback, and adds corresponding unit tests. Feedback recommends optimizing the new validator by removing redundant type checks and moving an inline import outside of its loop to improve performance.

Comment thread studio/backend/models/inference.py Outdated
Comment on lines +649 to +656
tc_id = (tc or {}).get("id")
if not tc_id:
continue
if (
msg.name
and isinstance(tc, dict)
and (tc.get("function") or {}).get("name") == msg.name
):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

The isinstance(tc, dict) check and the (tc or {}) defensive wrapper are redundant here. Since this is an after model validator, prev.tool_calls has already been validated against the ChatMessage schema, which defines it as a list[dict]. Therefore, each element tc is guaranteed to be a dictionary. Removing these redundant checks improves efficiency.

                    tc_id = tc.get("id")
                    if not tc_id:
                        continue
                    if (
                        msg.name
                        and (tc.get("function") or {}).get("name") == msg.name
                    ):
References
  1. To improve efficiency, avoid redundant data iterations. Combine checks and transformations into a single loop and return computed values for callers to reuse.

consumed.add((a, t))
break
if picked is None:
import secrets as _secrets

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

The secrets module is imported inside the loop, which is inefficient as the import lookup occurs in every iteration. Move the import outside the loop. Ensure the placement (top of file vs. inline) adheres to existing file-level conventions (Rule 6) and avoid redundancy if already imported at the top (Rule 9).

References
  1. Imports should generally be at the top of the file (PEP 8), unless a specific inline pattern is established in the module. (link)
  2. To improve efficiency, avoid redundant data iterations. Combine checks and transformations into a single loop and return computed values for callers to reuse.
  3. Follow existing file-level conventions for imports, such as keeping certain imports (e.g., PIL) inline if that is the established pattern in the file.
  4. Avoid redundant inline imports if the module is already imported at the top of the file.

@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: 53308f7dc5

ℹ️ 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 +634 to +635
if msg.role != "tool" or msg.tool_call_id:
continue

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 Mark explicit tool results as consumed before walkback

When a tool result already includes tool_call_id, this continue skips adding the matching assistant tool_calls entry to consumed, so a later tool message with a missing id can reuse the same call id. In a mixed request such as assistant calls call_a/call_b, first tool result explicitly returns call_a, and second tool result omits its id, the second result is filled with call_a again and call_b remains unmatched, which strict passthrough providers reject.

Useful? React with 👍 / 👎.

…only

Reviewer follow-ups to the training-cleanup + tool_call_id walkback PR.

tool_call_id walkback: a mixed assistant turn with [call_a, call_b]
followed by a tool result that carried tool_call_id="call_a" and a
sibling tool result with no id resolved to ['call_a', 'call_a']
because the explicit id never reserved call_a in the consumed set.
Added a pre-pass over the message list that walks back from every
role="tool" message carrying an explicit id and marks the matching
(asst_idx, tc_idx) consumed, then the missing-id walkback runs against
that pre-populated set. The second result now resolves to call_b.

While here, also harden the function-shape check: if a provider
ships a malformed tool_call where `function` is a string rather than
a dict, the old `(tc.get("function") or {}).get("name")` raised
AttributeError on the string's .get; now isinstance-gated so the
walkback falls through to the fallback id without raising.

Cancel cleanup: `tmp-checkpoint-*` is too broad. HF Trainer's
in-flight partials are always `tmp-checkpoint-<integer-step>`, so
constrain the cleanup regex to `^tmp-checkpoint-\d+$`. A user folder
named `tmp-checkpoint-final`, `tmp-checkpoint-backup`, or
`tmp-checkpoint-user-notes` is now preserved.

ChatMessage docstring still pointed at the pre-PR contract that
required `tool_call_id` on every role="tool" message. Updated to say
missing ids are accepted at message scope and resolved at
ChatCompletionRequest scope. Inline comment above the cancel-cleanup
call now describes the actual behaviour (in-flight tmp partials,
completed checkpoints preserved).

Test:
  - python -m pytest studio/backend/tests/test_inference_model_validation.py
    studio/backend/tests/test_cleanup_cancelled_checkpoints.py
    studio/backend/tests/test_openai_tool_passthrough.py -q
    -> 76 passed (was 67 before this commit; +2 walkback regression
       tests, +1 numeric-suffix preservation test)
Move the HF tmp-checkpoint regex to module scope as a named constant.
Drop the multi-paragraph docstring on _cleanup_cancelled_checkpoints
and the inline call-site rationale; the function name + the test
class already cover the why.

Compress _resolve_missing_tool_call_ids docstring from a six-line
explanation to two. Same logic, fewer in-flow tutorials.

76 tests in cleanup + inference-model-validation + tool-passthrough pass.
@danielhanchen
danielhanchen merged commit d79fd92 into main May 18, 2026
32 checks passed
@danielhanchen
danielhanchen deleted the studio-training-cleanup-and-toolcall branch May 18, 2026 07:01
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