Repository navigation
Studio: let the model leave itself a note that survives compaction - #10928
debojyoti-dev wants to merge 22 commits into
Conversation
The note is the model's own speculation promoted into the system turn, so the header marks it as possibly wrong and outranked by the user, and the note's own delimiters are defanged so it cannot escape its section. Co-Authored-By: Claude Haiku 4.5 <[email protected]>
Carries the model's note on the assistant message so the client re-sends it, keeping compaction stateless. Unknown-tag fallback means older clients degrade instead of 400ing. Co-Authored-By: Claude Opus 5 <[email protected]>
The note renders in its own section inside the block, never merged with the user's quoted instructions. Disabled renders byte-identical output. Co-Authored-By: Claude Sonnet 5 <[email protected]>
…tions _block_items scanned a captured <carried_forward> block for "- " bullets with no awareness that a <self_note> sub-region could be inside it, so a note containing markdown bullets was laundered into "the user's own earlier instructions, quoted verbatim" on the next reset. Excise the self_note region (terminated or not) from each captured body before the bullet walk. Co-Authored-By: Claude Sonnet 5 <[email protected]>
One bounded budget shared with the carried-forward items; the user's words are served first and the note takes what is left, trimmed rather than dropped. Co-Authored-By: Claude Sonnet 5 <[email protected]>
note[: room * 4] assumed ~4 chars/token, but the estimator it must agree with is len(json.dumps(...)) // 4, and JSON-escaping doubles the cost of `"` and `\`. A note quoting JSON or a Windows path could trim to a size that still estimated at roughly 2x its room. Trim now verifies against estimate_message_tokens and shrinks (bounded iterations) until it fits, falling back to no note when nothing does. Co-Authored-By: Claude Sonnet 5 <[email protected]>
Tells the model the <remember> tag exists and that the note is for its own future self rather than a summary for the user. Empty when disabled. Co-Authored-By: Claude Sonnet 5 <[email protected]>
Mirrors compactionHeadroomRatio. Both optional, so an existing client that omits them saves exactly as before. Co-Authored-By: Claude Sonnet 5 <[email protected]>
Clamps to the backend's ge/le so a slider value can never 400 the save. Co-Authored-By: Claude Sonnet 5 <[email protected]>
Injects the <remember> instruction when the feature is on, parses the note out of the finished reply, strips the tag from user-visible text, and emits the self_note part so the client can re-send it. Without this the render path had nothing to render. Limitation: streaming completions are not covered (documented in the task report) -- final-assembly extraction/strip is wired for the non-streaming GGUF and safetensors tool-loop completions only, since per-token buffering across 20+ streaming call sites in routes/inference.py was out of scope for this task. Co-Authored-By: Claude Sonnet 5 <[email protected]>
The Studio chat UI always streams, so Task 7.5's non-streaming-only wiring never fires for real users. Adds _SelfNoteStreamExtractor, following _ResponsesReasoningExtractor's holdback technique (reusing _responses_marker_holdback), wired into the GGUF tool-loop SSE generator: partial <remember> markers are held across token boundaries so no fragment of the tag or note body ever reaches the client, the note is captured via extract_note() on the full accumulated text at stream end, and emitted as a self_note _toolEvent chunk mirroring external_provider.py's compaction_block. Disabled stays byte-identical: the extractor is never constructed unless the feature is on. Co-Authored-By: Claude Sonnet 5 <[email protected]>
Builds the client leg of the stateless round-trip: the backend emits the note as a self_note tool event, the adapter now latches it onto the assistant message's final content (spliced in next to documentCitationParts, never rendered mid-stream), and re-sends it on the next request by promoting outbound assistant content to an array so latest_self_note() can read it back, mirroring the existing thought-signature round-trip. self_note is handled before the unconditional closeReasoningContent() call, alongside its other state-only siblings (container_ready, context_window_exceeded, etc.), since it opens no tool card and must not force-close an open reasoning block. Co-Authored-By: Claude Sonnet 5 <[email protected]>
`checkpoint._DELIMITERS` covered only `carried_forward`, while `self_note.py`
already covered both tags. So `_neutralise` let a USER's literal `<self_note>`
through verbatim into a rendered bullet, and `_SELF_NOTE_SECTION` --
unterminated-tolerant by design, since a block truncated mid-note has no closing
tag to anchor on -- then deleted from that bullet to the end of the block on the
NEXT compaction.
That is silent loss of the user's own standing instructions, and it fired with
the self-note feature DISABLED, which is the default:
_block_items(render_checkpoint(
["benign <self_note> opener", "SECOND REAL USER INSTRUCTION", "THIRD"]))
-> ['benign']
Widened `_DELIMITERS` to `</?(?:self_note|carried_forward)>`, mirroring
`self_note.py`. Only an Unsloth-rendered section can now contain a real
`<self_note>`, which is the same reasoning `_BLOCK` already documents for
claiming the HEADER rather than the bare tag.
Also anchored `_SELF_NOTE_SECTION` to line-start (MULTILINE) for defence in
depth: `render_self_note` always emits its opening tag at the start of a line,
so the anchor costs the real section nothing while a stray mid-line tag can no
longer trigger the greedy cut to end-of-body.
Tests: every existing escape test supplies the attack via `self_note=`, i.e.
they all assume the MODEL is the adversary; none supplied it via `items=`, the
user's own keyboard. That blind spot is what let this through. Added four tests
covering the user path, including an integration test driving TWO sequential
real compactions through `fit_checkpoint_context` with both tags in the user's
text, asserting the instructions survive both resets and no model text is
promoted into them.
Co-Authored-By: Claude Opus 5 <[email protected]>
Backend half of wiring the settings the issue asks for: the request can carry the toggle and the reserve, and they take precedence over the UNSLOTH_SELF_NOTE env default rather than the env var being the only control. Frontend store/UI threading is not done yet. Partial work recovered from an interrupted session; see .superpowers/sdd/2026-09-14-self-note-compaction/progress.md. Co-Authored-By: Claude Opus 5 <[email protected]>
…dapter selfNoteRequestFields existed but was never invoked outside its own definition file, so the self-note toggle/reserve settings never reached the backend. Thread selfNoteEnabled/selfNoteReserveTokens through the chat runtime store and into the adapter's request body, mirroring the compactionHeadroomRatio journey exactly (state field, setter, persisted scalar-setting key, and the adapter call site). Also extend PersistedChatSettings and its sanitizer so the two fields round-trip through /api/chat/settings like every other scalar setting. Default remains off; with the toggle off the request still carries only self_note_enabled: false, with no reserve. No backend file touched, and the existing sanitizers/selfNoteRequestFields/ggufCompactionRequestFields are unmodified. Co-Authored-By: Claude Sonnet 5 <[email protected]>
`self_note` is Unsloth's own extension, not an assistant-ui ThreadAssistantMessagePart variant, so splicing the literal into the yielded content widened the run-result type and broke `tsc -b` with two errors. Cast at the splice instead of widening the union: the part is inert for the renderer and only has to survive the round trip back to the backend. Verified against origin/main: baseline 0 errors, this branch was 2, now 0. Co-Authored-By: Claude Opus 5 <[email protected]>
|
@danielhanchen please review my PR |
|
Checked the compaction path in studio/backend/core/inference/checkpoint.py and the new self_note section plus SELF_NOTE_INSTRUCTION do land in the system turn, and the widened _DELIMITERS rewrites user text containing a literal self_note tag even with the feature off, so could you confirm the default-off prompt is unchanged for such a message? The direction is good, but this also carries frontend settings plumbing with no panel widget, so splitting it at the backend and frontend seam you named would make it much easier to review. |
Review asked whether the default-off prompt is really unchanged for a user message containing a literal self_note tag. It is not, and the existing "byte-identical" test could not have caught it: it compares render_checkpoint against itself on this branch, downstream of _neutralise, which runs during item selection. Pin the real scope instead of the claim. Identical to main for any message without a self_note tag; for one with it, exactly the "<" of that tag is rewritten, the instruction survives in full, and nothing is dropped. Co-Authored-By: Claude Opus 5 <[email protected]>
@danielhanchen You're right, and my description overclaimed. I checked rather than argued. The default-off prompt is not unchanged for that message
main: So "byte-identical when disabled" is not true as stated. It holds for every message The existing test could never have caught this. It asserts I've pushed The divergence is deliberate: it is the fix for the data-loss bug, where an un-defanged The system turn is gatedConfirmed. SplittingAgreed, and the numbers make your case better than my description did. The true diff from Three, in this order:
One caveat on sequencing, since it is the thing that made me bundle these in the first Your call whether that is better as three separate PRs or one stacked series — happy Your point about #3 is the sharpest of the three: plumbing a toggle end to end with |
…unner (#10952) * Take the wall clock out of two backend guards that fail on a loaded runner test_cache_does_not_bypass_expiry issued a key expiring in 600ms and asserted the first validate_api_key call still accepted it. That call runs PBKDF2, so on a busy runner the key is already expired when the first assertion reads it: assert None == 'unsloth'. Rewritten in the shape of its neighbour test_cache_does_not_bypass_revocation, warming the cache on a key valid for a day and then expiring the row, which also drops the 0.8s sleep. Verified it still fails when the expiry check is made conditional on a cache miss. The four ReDoS guards asserted a single wall-clock sample under 50ms. The tilde case measures about 11ms and was seen at 60.9ms on CI, which is preemption, not backtracking. They now take the fastest of five runs, since catastrophic backtracking costs seconds and every repeat pays it. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Measure the ReDoS guards on a CPU clock, not a wall clock perf_counter still counts the time this process spends off the CPU, so under sustained contention every one of the five samples carries it and the minimum can still cross the budget. The budget is about the regex's own CPU work, so process_time measures it directly. Best-of-five stays on top for the contention process_time cannot see. Same pairing as test_tool_loop_controller. * Stop the trickling-headers probe reading a busy runner as a broken fixture Third guard in the same family as the two already here. The fixture dribbles response headers from its own thread, and the test asserted `lines >= 3` immediately after the probe returned, which assumes 0.5s of probe bought that thread 0.5s of CPU. On a loaded runner it does not: seen on #10928 as AssertionError: fixture stopped trickling headers after 0 bytes on a probe that had timed out exactly as intended, so the assertion was reporting contention as a broken fixture. It now waits on an event the drip loop sets after its first byte instead of sampling a counter at an arbitrary moment. The companion `lines < 100` bound went the same way. It was a proxy for "the fixture is not sending whole header lines", measured through a byte count that a slow runner made small and a fast one made large. The property is about what the fixture writes, not how often it got to write it, so it is now asserted against the repeated chunk itself. Both directions mutation-checked: a fixture that never trickles fails the first, and a chunk carrying CRLF fails the second. * Prove the trickling fixture stayed inside the per-operation timeout The previous version waited for the fixture's first byte and accepted it. That is too weak, and in the direction that matters. urllib applies its own per-socket-operation timeout, so a peer that sends one byte and then goes quiet for longer than that trips it on its own, the probe returns "timeout" inside budget, and every assertion below passes against a build with no whole-request deadline at all. The old count-based check was reaching for this and could not express it, because a count cannot say when the bytes landed. The fixture now records the longest silence it ever left. While every gap stays under the socket timeout, and the last write lands within one timeout of the probe returning, no per-operation timeout can have fired, so a probe that returned anyway returned on the whole-request deadline. That is the distinction the test exists to make, asserted rather than assumed. A runner too contended to hold that has not produced a failure, it has produced no evidence, so the test skips with the measured numbers instead of passing on a broken build or going red on a busy machine. Mutation-checked both ways: a fixture that stalls after one byte now skips where it previously passed, and replacing worker.join(timeout) with worker.join() fails with the fixture still trickling. * Tighten the comments added by this PR --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Thank you so much for the PR and for the careful work here, @debojyoti-dev! The design was thoughtful: off by default, nothing stored server side, and the note kept clearly separate from the user's own instructions. We have decided not to merge it for now. Studio's compaction already works with RAG: turns that get compacted away are indexed, so the model can search the transcript and retrieve anything it needs, including approaches it already ruled out. That covers most of what a self-written note would carry, without asking the model to write a note on every turn or relying on it to choose well what to keep. If we find cases where retrieval is not enough, we may revisit this, and your PR would be a great starting point. Thanks again for contributing to Unsloth! |
Closes #10904.
What this does
When a chat overflows its context window, checkpoint compaction resets the epoch to
[system prompt + carried_forward] + [newest user turn]. The carried-forward block keeps the user's standing instructions, quoted verbatim. Nothing of the model's own working state survives, so a long stretch spent ruling an approach out gets re-derived after the reset.This adds an opt-in way for the model to carry a short note across that boundary. It writes
<remember>...</remember>at the end of a reply; the backend parses it out, strips it from what the user sees, and carries it on the assistant message. At the next compaction it renders inside the existing<carried_forward>block, in its own<self_note>section.Off by default. With the feature disabled,
render_checkpointoutput is byte-identical to today's — there is a test asserting exactly that.Why it is shaped this way
checkpoint.py's module docstring states two commitments this feature had to respect:Both still hold:
_select_items/_pick. When the feature is off, nothing about the block changes.self_notecontent part and the client re-sends it, exactly as the branch is already re-sent. No new table, no new lifetime.The note is model-authored text being promoted into the system role — the same authority-confusion risk the block's existing header already addresses for quoted user text, plus one more: the model is writing its own future input, so a wrong note is self-reinforcing. Two things bound that: the section header states the note is the model's own prior speculation, may be wrong, and is outranked by the user's newest message and by anything observable; and the note shares one bounded budget with the user's instructions and loses ties to them.
Scope
CONTRIBUTINGasks for focused PRs, and this spans backend, model layer, settings, and frontend. That is worth explaining rather than leaving for review to discover: the layers are interlocking, and a backend-only PR would be inert. In particular, the client re-send leg did not previously exist — outbound assistant content was always serialised as a plain string, while the backend only reads list-shaped content, so a note would have rendered once and then vanished. Splitting the PR would have shipped a feature that passes its tests and does nothing.Happy to split it if maintainers prefer; the natural seam is backend (
self_note.py+checkpoint.py+ capture wiring) versus frontend (adapter persistence + settings).Not included
self_notepart is dropped by the outbound per-provider allowlists inroutes/inference.py, which apply only to external providers — a local GGUF request has noprovider_typeand bypasses them. Checkpoint compaction is the local path, so the feature works where it is aimed. Anthropic and OpenAI do their own server-side compaction anyway (see the existingcompactioncontent part).<remember>block from the streamed reply and captures it. Safetensors and MLX chats are unchanged.UNSLOTH_SELF_NOTE/UNSLOTH_SELF_NOTE_MAX_TOKENSset the server default.Testing
test_checkpoint_compaction.pyare theconversation_archive.reachable()probe tests, which fail withoutsentence_transformersinstalled; they fail identically on a clean checkout and are unrelated to this work.tsc -b: 0 errors (matches themainbaseline).ruff check studio/backend: clean.81 tests were added (33 backend unit + 20 in
test_checkpoint_compaction.py+ 28 frontend). The ones worth pointing at:<self_note>keeps every instruction — this guards a data-loss bug found in review, where an unterminated-tolerant regex ate the rest of the block. It fires on the default-off path, so it is the test that matters most.<remember>tag split across streaming token boundaries (<reme+mber>) is still held back and still captured.<remember>(generation cut off) degrades to no note rather than leaking a half-note or hanging the stream.Known limitations
<remember>can lose up to 9 characters if generation stops exactly there — the same trade-off the existing<think>extractor already makes.generation-tool-recovery.tsdoes not recogniseself_note, so a note received just before a browser reload interrupts a stream is lost on recovery.fit_checkpoint_contextpath; the round-trip protections are covered at the_block_itemslevel.Settings: before and after
Settings > Chat on the merge base (left) and this branch (right), auto-compact on. The new row is turned on to show the note size choices (128, 256, 512, 1,024 tokens; default 256).