Skip to content

Studio: keep a chat's start date in the system prompt, note a new date on the latest user turn - #12096

Merged
danielhanchen merged 8 commits into
mainfrom
studio-date-note-user-turn
Sep 27, 2026
Merged

danielhanchen merged 8 commits into
mainfrom
studio-date-note-user-turn

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Sep 27, 2026 •

Copy link
Copy Markdown
Member

Follow-up to #8879.

#8879 puts The current date is YYYY-MM-DD. at the very start of the system prompt and recomputes it on every request. When a conversation crosses midnight (browser timezone), the first line of the prompt changes, so llama-server's prompt cache misses and the whole conversation is re-processed on the next turn.

What this changes

  • A Studio thread now keeps its start date in the system line. The date comes from the thread's created_at (following forkedFromThreadId to the root, so a fork keeps its parent's prefix), converted with the same browser timezone headers add a setting that tells the model the current date #8879 already uses. A creation day later than today (browser clock running ahead) is ignored.
  • When today differs from the start date, the newest user turn is led by [Current date: YYYY-MM-DD]. Earlier turns keep their own bytes.
  • Same-day requests are byte-identical to what main sends today.
  • No thread_id, an unknown thread, or a failed lookup falls back to the current behaviour (today's date in the system line, no note). API-key callers, internal workflows, Deep Research's stamped date, the Ollama no-synthetic-system-turn exemption and the verbatim passthroughs are unchanged.
  • The note is never added to a turn with no text (audio or image only), so the "Please transcribe this audio." / "Describe this image." defaults still apply. It skips tool results folded into user turns, and retrieval queries (RAG autoinject, conversation recall) strip it.
  • The note is kept through the paths that rebuild messages from the payload (multi-image, safetensors/MLX client tools, MLX token count).
  • Frontend: the context-usage count now sends thread_id even when tools are off (the completion always sends it), so counting and generation render the same prompt.

Prompt cache

Real llama-server (--jinja, one slot, prompt cache on), same GPU. An 8-turn conversation where turns 5 to 8 happen the day after turns 1 to 4. Requests are built with each tree's own date helpers. Values are timings.prompt_n (tokens re-evaluated), identical across 3 repeats.

Call Qwen3-0.6B main Qwen3-0.6B this PR Llama-3.2-1B main Llama-3.2-1B this PR
1 to 4 (day 1) 56, 60, 52, 48 56, 60, 52, 48 70, 19, 19, 16 70, 19, 19, 16
5 (first turn after midnight) 236 69 240 39
6 to 8 38, 48, 63 76, 78, 97 18, 17, 17 58, 73, 73
Day 2 total 385 320 292 243

The saving at midnight grows with the conversation's length. Each later turn costs the previous exchange once more, because the note moves to the newest turn; pinning it to the first turn of each day is a follow-up.

Answer quality

Where the note goes matters for small models. 40 prompts, greedy, an old chat continued today, compared with main's prompt for the same request ([facts correct of 60, date answered correctly of 3, replies that mention the date when main's did not, empty replies] across gemma-3-270m, Qwen3-0.6B, Llama-3.2-1B):

Note Facts Date Date bleed Empty
main 47 2 0 2
Trailing The current date is now ... 46 3 18 0
Leading [Current date: ...] (this PR) 48 3 4 0

A trailing sentence made small models answer about the date ("Since the current date is ..., three primary colors are"). The leading bracket keeps them on the question.

Tests

  • test_current_date_prompt_settings.py: 24 new tests covering start date in the browser zone, future creation days, deep and broken fork chains, lookup failures, midnight keeping the system turn, same-day byte identity, threadless fallback, media-only turns, text parts, folded and coalesced tool results, retrieval queries, idempotence, API-key callers and the disabled setting. With the new routing disabled, the behavioural tests fail.
  • Anthropic, OpenAI tool passthrough, Codex, hosted passthrough and MLX suites pass. test_openai_auto_switch.py plus test_chat_generation_supervisor.py: 731 passed, and the same 20 tests fail on main.
  • Frontend: tsc clean. current-date-context-usage, project-attachment-simulations and skills-token-count-discovery pass.
  • Studio regression switchboard (9 suites, base vs head): no functional regression.

@danielhanchen danielhanchen self-assigned this Sep 27, 2026
@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-09-27T07:26:06.562879Z 77d4152 PR opened
ℹ️ 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

chatgpt-codex-connector Bot commented Sep 27, 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-09-27T09:30:16.300639Z f1d0ee9 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 chatgpt-codex-connector Bot Sep 27, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security 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: a426d0489b

ℹ️ 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 +131 to +134
parent = get_chat_thread(parent_id)
if not parent:
break
thread = parent

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 Preserve the root date when a fork's source is deleted

When a user keeps a fork created on a later day but deletes its source chat, storage/studio_db.py::_reparent_surviving_forks deliberately leaves forkedFromThreadId pointing at the deleted root. This lookup then returns None, breaks the traversal, and uses the fork's own createdAt, so the next request changes the supposedly stable system date and invalidates the cached prefix. Persist or copy the original conversation-start date instead of silently falling back when an ancestor is missing.

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.

Not changing this. Deleting a fork's source is rare, and the effect is a one-time move of the system date to the fork's own creation day, so one cache miss rather than wrong output. It stays stable afterwards.

created = datetime.fromtimestamp(created_ms / 1000, timezone.utc)
except Exception:
return None
return _request_local_date(request, now = created)

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 Keep the start date independent of the current timezone

When the request timezone differs from the timezone used when the chat began—for example, after the user travels or changes the browser timezone—this reinterprets the original UTC creation instant in the new timezone. For chats created near midnight that can change the derived start date and therefore rewrite the system prompt, defeating the stable-prefix behavior. The creation-day value or its original timezone needs to be persisted rather than recalculated from each request's headers.

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.

Known and stated in the PR description. A timezone change can move a near-midnight start date by one day once, costing one cache miss. Persisting the start date needs a schema change that is out of scope here.

Comment on lines +6106 to +6108
copied = list(messages)
copied[index] = {**msg, "content": new_content}
return copied

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 Keep prior date notes stable across later requests

After midnight, the injected note exists only in this copied request and is not persisted with the user message. On the next turn, history therefore replays that prior user text without its note while this code adds the note only to the new latest user turn; the serialized prompt diverges before the prior assistant response, forcing the prompt cache to reprocess that response on every subsequent turn after rollover. Persist or deterministically reconstruct notes on earlier turns instead of moving the suffix from one user message to the next.

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.

This is the stated trade-off. Moving the note costs re-evaluating one prior exchange per turn instead of the whole conversation at midnight (measured in the PR description). Pinning the note to the first turn of each day needs message-level persistence and is planned as a follow-up.

Comment on lines 13649 to +13650
if isinstance(content, str):
return content.strip()
return strip_current_date_update_note(content).strip()

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 Strip date notes only when the server added them

This unconditionally removes any matching sentence from every caller's latest user text, even for API-key requests where Studio never injected a date note. A genuine query such as The current date is now 2026-08-16. becomes empty, causing RAG auto-injection and conversation recall to be skipped, while the same sentence at the end of a longer query is silently omitted from retrieval. The synthetic note needs provenance or an unambiguous marker before it can safely be stripped.

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.

Stripping only matches a user turn that ends with exactly this sentence and an ISO date. Real queries do not end that way, and the only effect is that one sentence is left out of a retrieval query.

Comment on lines 24328 to +24331
request,
include_api_key = run_studio_tool_loop,
provider_type = None if _external_nudge else provider_type,
thread_id = getattr(payload, "thread_id", 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 Send the thread ID for plain external-provider chats

For external models whose studio_tools capability is false or unknown, the external request builder in chat-adapter.ts only includes thread_id when externalUsesStudioTools is true. This new argument is therefore None for ordinary chats on providers such as Anthropic, so _current_date_parts continues using today's date in the system prompt and never emits the rollover note. Those chats still invalidate provider prompt caches at midnight; thread_id needs to be sent independently of tool support.

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.

Behaviour for these chats is unchanged from main: they keep today's date in the system line. Sending thread_id to providers without Studio tools would also turn on thread-scoped tool behaviour (conversation archive admission), so that belongs in its own change.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 27, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 27, 2026

@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: a426d0489b

ℹ️ 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 +126 to +134
while thread:
parent_id = thread.get("forkedFromThreadId")
if not parent_id or parent_id in seen:
break
seen.add(parent_id)
parent = get_chat_thread(parent_id)
if not parent:
break
thread = parent

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 Avoid opening a database connection for every fork ancestor

For a chat produced by repeatedly forking prior forks, this loop calls get_chat_thread once per ancestor; that function opens and closes a separate SQLite connection on every call. The traversal is synchronous inside the async inference and token-count handlers, has no depth bound, and is invoked multiple times while constructing a single request, so an imported or organically deep fork chain can block the event loop with hundreds or thousands of connection/query cycles. Resolve the root in one database operation, cache the result for the request, or impose a bounded traversal.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fork chains in practice are a few levels deep; a lookup measured about 0.6 ms including the connection, and it runs a handful of times per request, never per token.

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 9c9a8f0f9a

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

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 27, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 27, 2026
@danielhanchen
danielhanchen merged commit 7e80a43 into main Sep 27, 2026
63 of 64 checks passed
@danielhanchen
danielhanchen deleted the studio-date-note-user-turn branch September 27, 2026 10:31
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…e on the latest user turn (unslothai#12096)

* Keep a thread's start date in the system prompt and note a new date on the latest user turn

* Shorten date helper docstring

* Keep the date note through payload rebuilds, skip folded tool results, walk the whole fork chain

* Leave media-only turns and retrieval queries free of the date note

* Drop a restating docstring

* Lead the newest user turn with a bracketed date note instead of trailing it

* Never state a future start date; only skip turns that are wholly folded tool results

* Trim comments
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.

2 participants