Skip to content

Studio: let the model leave itself a note that survives compaction - #10928

Closed
debojyoti-dev wants to merge 22 commits into
unslothai:mainfrom
debojyoti-dev:feat/self-note-before-compaction
Closed

debojyoti-dev wants to merge 22 commits into
unslothai:mainfrom
debojyoti-dev:feat/self-note-before-compaction

Conversation

@debojyoti-dev

@debojyoti-dev debojyoti-dev commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

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_checkpoint output 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:

X is a bounded verbatim record of the user's standing instructions from the dropped turns, built deterministically so there is no summariser to fail.

NOTHING IS STORED: the client re-sends the whole branch, so X is recomputed each request.

Both still hold:

  • The deterministic path is untouched. The note renders in a separate section, never merged with the user's quoted bullets, and never enters _select_items/_pick. When the feature is off, nothing about the block changes.
  • Nothing is stored. The note rides on the assistant message as a self_note content 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

CONTRIBUTING asks 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

  • External providers. The self_note part is dropped by the outbound per-provider allowlists in routes/inference.py, which apply only to external providers — a local GGUF request has no provider_type and 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 existing compaction content part).
  • GGUF tool chats only. The instruction to write a note is added only on the local GGUF tool-loop path, the one path that hides the <remember> block from the streamed reply and captures it. Safetensors and MLX chats are unchanged.
  • Settings. Chat settings has a "Keep a model note across compaction" switch (shown when auto-compact is on) with a note size of 128 to 1024 tokens. UNSLOTH_SELF_NOTE / UNSLOTH_SELF_NOTE_MAX_TOKENS set the server default.

Testing

  • Backend: 279 passed. Three pre-existing failures in test_checkpoint_compaction.py are the conversation_archive.reachable() probe tests, which fail without sentence_transformers installed; they fail identically on a clean checkout and are unrelated to this work.
  • Frontend: 7494/7494 passed.
  • tsc -b: 0 errors (matches the main baseline).
  • 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:

  • The disabled path renders byte-identically.
  • A note containing markdown bullets cannot be laundered into the user's quoted instructions on a second compaction.
  • A user whose own text contains a literal <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.
  • A <remember> tag split across streaming token boundaries (<reme + mber>) is still held back and still captured.
  • An unterminated <remember> (generation cut off) degrades to no note rather than leaking a half-note or hanging the stream.

Known limitations

  • A reply ending in text that coincidentally prefixes <remember> can lose up to 9 characters if generation stops exactly there — the same trade-off the existing <think> extractor already makes.
  • A note trimmed to fit its budget can be cut mid-sentence, which can invert its meaning. The section header tells the model the note may be wrong and to prefer what it can observe.
  • generation-tool-recovery.ts does not recognise self_note, so a note received just before a browser reload interrupts a stream is lost on recovery.
  • No integration test drives two sequential compactions through the full fit_checkpoint_context path; the round-trip protections are covered at the _block_items level.

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).

Settings > Chat before and after

debojyoti-dev and others added 16 commits September 14, 2026 19:20
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]>
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@debojyoti-dev

Copy link
Copy Markdown
Contributor Author

@danielhanchen please review my PR

@danielhanchen

Copy link
Copy Markdown
Member

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]>
@debojyoti-dev

debojyoti-dev commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor Author

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.

@danielhanchen You're right, and my description overclaimed. I checked rather than argued.

The default-off prompt is not unchanged for that message

_DELIMITERS went from </?carried_forward> to </?(?:self_note|carried_forward)>, and
_neutralise is called from _entry during item selection. So for a user message
containing a literal <self_note>, the quoted bullet differs from main with the feature
off:

main: Never write <self_note> in my docs.
branch: Never write ‹self_note> in my docs.

So "byte-identical when disabled" is not true as stated. It holds for every message
that does not contain a self_note tag, and not for one that does.

The existing test could never have caught this. It asserts
render_checkpoint(items, self_note = "") == render_checkpoint(items) — both on this
branch, and items are already neutralised by the time render_checkpoint sees them. It
compares the branch against itself, downstream of where the change actually happens.

I've pushed 163e703a1, which pins the real scope against a local copy of main's regex:
identical output for benign text, and for a typed tag exactly the < changes —
len(ours) == len(typed), the instruction preserved either side of the tag, and an
end-to-end check that both user instructions still come back from _block_items.

The divergence is deliberate: it is the fix for the data-loss bug, where an un-defanged
literal tag let _SELF_NOTE_SECTION (unterminated-tolerant by design) delete from that
bullet to the end of the block on the next compaction. One character defanged, versus
losing the rest of the user's standing instructions. But it is a behaviour change on the
default-off path and should have been stated as one rather than filed under "unchanged".
I'll correct the description.

The system turn is gated

Confirmed. note_instruction() returns "" unless enabled(), and
_apply_self_note_nudge returns the nudge untouched when it does. Verified at runtime:
default enabled() is False and the instruction is ''; with UNSLOTH_SELF_NOTE=1 it
is 473 characters. The section and SELF_NOTE_INSTRUCTION land only when the feature is
on.

Splitting

Agreed, and the numbers make your case better than my description did. The true diff from
the merge base is 2241 insertions across 17 files — backend 10 files / 1570, frontend
7 files / 671. The settings plumbing you flagged as widget-less is a clean 261 lines
across 5 files (chat-settings-api.ts, chat-settings-storage.ts,
chat-runtime-store.ts, and their two test files).

Three, in this order:

# Scope Size
1 Backend — self_note.py, checkpoint.py, capture wiring, backend tests ~1570
2 Frontend round-trip — chat-adapter.ts, auto-compaction.ts, chat-self-note-part.test.ts ~410
3 Settings plumbing — the 261 above, landing with the panel widget rather than before it ~261

One caveat on sequencing, since it is the thing that made me bundle these in the first
place: #1 alone is inert, not merely unused. Outbound assistant content was serialised as
a plain string while the backend only reads list-shaped content, so without #2's
collectAssistantSelfNote the note renders once and then vanishes. #1 is reviewable and
testable on its own, but should not be called done until #2 lands.

Your call whether that is better as three separate PRs or one stacked series — happy
either way, and I would rather do it than have you review 2241 lines at once.

Your point about #3 is the sharpest of the three: plumbing a toggle end to end with
nothing rendering it is exactly the kind of thing that should wait for its widget.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen added a commit that referenced this pull request Sep 15, 2026
…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>
@danielhanchen danielhanchen self-assigned this Oct 12, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 12, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 12, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 12, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 12, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 12, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 12, 2026 •

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-12T11:26:24.427189Z 98043a7 New commits
ℹ️ 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 Summary

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

Review Status Commit Review trigger
📝 Code Review 🔄 Running since 2026-10-12T11:26:20.940674Z 98043a7 New commits
ℹ️ 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.

@unslothai unslothai deleted a comment from debojyoti-dev Oct 12, 2026
danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 12, 2026
@danielhanchen

Copy link
Copy Markdown
Member

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!

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.

[Feature] Allow Model to "Leave a Self Note" Before Compacting.

2 participants