Closes#2909.
Omit the fewest eligible historical tool-argument payloads so oversized completed exchanges remain replayable, without touching signed/native provider rounds or durable history.
Long mastery sessions froze the event loop: every existence-only probe
(history_groups, context-builder guards) ran normalize_model_turn, which
deep-copies the whole request record via a JSON round-trip. A 121-message
session re-serialized megabytes per probe, holding the GIL long enough for
health checks to time out and the worker to be declared lost.
Extract the structural acceptance checks into _is_complete_model_turn and
add has_model_turn for existence-only sites. normalize_model_turn delegates
to the same predicate, then cleans and copies as before, so replay keeps its
full isolation. Stored records are normalize's own JSON-safe outputs, so the
predicate accepts exactly what normalize accepts on stored rows; a parity
corpus pins the shared rejections.
Fixes#2788
Co-authored-by: ZQR1101 <278034003+ZQR1101@users.noreply.github.com>
* fix(chat): isolate PDF attachment extraction
Run PDF-bearing chat attachment extraction outside the API process and reuse the single PDF image pass for both page markers and embedded attachments. Addresses the chat attachment reproduction in #2865.
* perf(pdf): skip decoding images after the count cap
Keep lookups for previously accepted image references ahead of the quota check so repeated pictures are still mapped to each page.
* perf(chat): reuse native PDF markdown for text-only parsing
Match the stored attachment bytes and preserve the configured parser path for other engines and incomplete native results.
* fix: keep sent runtime snapshots in mastery replay
Mastery replay dropped every runtime snapshot from history and the loop
re-appended them after it, so each follow-up request diverged from the
previous one at message 1 and only tools + system hit the prompt cache.
- project_mastery_replay(keep_snapshots=True) for the tutor request and
its token accounting; memory material still drops snapshots
- replay_group no longer blanks a tagged mastery_status_snapshot while
removing the legacy fused suffix
- status snapshot anchors are numbered from the start (occurrence), so a
later snapshot never changes how an earlier turn is projected
Refs #2922
* fix: keep runtime snapshots out of the mastery history budget
Replayed snapshots stay in the request so follow-up turns extend the cached prefix, but counting them made a large mastery_status snapshot push the history over its 20k budget after two turns; the next turn then paid a memory rewrite and a full prefix miss. The budget now measures the learning history only, as before. Refs #2922
* fix: bound the runtime snapshots kept in mastery history
Keeping sent snapshots out of the history budget entirely let many short
exchanges accumulate them without limit (80 quiz-style turns: 5.4k counted,
62k sent). Dialogue still keeps to the plan; dialogue plus snapshots keep to
twice the plan, and only as far as the model's window allows. Refs #2922
* fix: keep only this turn's state in the mastery status snapshot
Every mastery turn sends a fresh mastery_status snapshot and, since the
replay change, keeps earlier ones in history, so whatever a snapshot
carries is paid for once per turn and then kept. A full status read
repeats fixed guidance (open question, question group, working brief,
intake, teaching guidance and focus) and every default value of every
knowledge point.
The snapshot now drops empty and default values and the fixed guidance.
That guidance lives in named constants and is stated once in a new
mastery_status_guide system block, which also explains the omitted
defaults. Snapshots start with a one-line header; history sharing reads
both the header and the longer notice older sessions stored. An explicit
mastery_status call still returns the full payload.
Measured over 54 recorded snapshots: working briefs 1,454 -> 645 tokens
(median), full outline snapshots 6,352 -> 2,954. The guide adds 861
tokens (en) to the cached system prompt.
Refs #2922
* fix: size the exact tail the way the plan does, and share full reads with compact snapshots
Two gaps left by keeping snapshots in mastery replay (review on #2992):
- Recent-history selection counted kept snapshots in full while the plan
discounted them, so a session of short exchanges with large snapshots
archived most of them as soon as selection ran. ContextBuilder now sizes
the candidate tail through _recent_history_tokens(), and the mastery
builder answers with the same _plan_tokens() measure.
- Snapshots carry the compact form of map, learner_profile, learning_stages
and visual_requirements, so a later full mastery_status result never matched
them exactly. Sharing now also compares a full field's compact form and
marks such references with "defaults_omitted": true, which the state
reference notice explains.
Also: rename _next to _compact_next_step, and say in the status guide that
the omitted-default rules cover only what the snapshot includes.
Refs #2922
Images re-injected via chat_prior_image_reinject_max landed in the
current user message with no origin marker, so the model treated them
as fresh uploads of that message even when it was text-only. Mark the
collected prior images historical with their source message id and
insert a brief origin note before such images during multimodal
assembly; current-turn uploads keep their existing behavior.
Fixes#2632
Signed-off-by: evan188199-tech <238371241+evan188199-tech@users.noreply.github.com>
Practice notebook entries recorded in one session now share a single
sidebar row, titled by that session with its question count, expandable
to each question's own practice link. Entries without a session (and
sessions that produced one question) keep individual rows, and the
Question Bank, answers and review links are unchanged.
The learning index navigation read gains the existing session id and
title (no new persisted field); grouping happens in the projection.
Sidebar strings added to every locale.
Air review R1 blocker: stopping each caller at its first observation
lost the stability sampling the original windowed churn provided. Keep
the bounded readiness wait (barrier + per-caller observation), then have
every caller perform 50 further calls asserting each result is the very
same object as its first observation and never None; per-thread
mismatches are asserted empty after a bounded join. All prior invariants
kept: one shared instance ever, built exactly once, every caller saw it.
CI run 42532087495 failed on Python 3.11-3.14 for test-hermeticity
reasons, not contract violations:
- test_fifo/cold-cache: in a full-suite run, another test's
tiktoken.get_encoding leaves a resident cl100k_base in tiktoken's
in-process registry, and the acquisition correctly adopts it without
touching the filesystem -- so the FIFO/cold paths under test were
silently bypassed. Empty the registry via the existing
registry_free_tiktoken fixture so these tests always exercise the
paths their names claim.
- test_concurrent_warm_calls_yield_one_encoding: its fixed 0.5s
observation window conflated publish latency with sharing; on slower
runners nothing was observed in the window (CI: len(every_seen)==0).
Each caller now churns until it personally observes the encoding
(bounded deadline), and the assertions strengthen to require every
caller to see the same single instance.
- summarize-path tests: count boundaries were tuned for exact counts,
but #2522 keeps cold caches on the chars/4 heuristic, flipping the
rebuild/fold-in decision. Pin count_tokens on a deterministic exact
word counter (same idiom as the PR's own count_tokens tests) so the
budget-path logic stays deterministic on every machine; all original
assertions are unchanged.
No production changes: registry adoption, offline acquisition and
non-blocking callers are working as designed.
The deletion/replacement race tests previously skipped unless a real
cl100k_base cache fixture existed. They now build from a small synthetic
ranks blob whose hash is pinned for the test, against the real tiktoken
with every download-capable loader rigged to fail. Real-tokenizer parity
stays an explicitly optional test.
Add Hindi (hi, हिन्दी) to the reply-language contract, following step 4
of docs-for-dev/I18N.md and the earlier Malay change (550268e1):
- SUPPORTED_RESPONSE_LANGUAGES, the settings router's ResponseLanguage,
the prompt-language label and the settings-spec reply choices;
- "hindi", "हिन्दी" and "हिंदी" aliases in the backend and web
normalizers (hi-IN and hi_IN resolve through the base code);
- the web ResponseLanguage type, isResponseLanguage() and
RESPONSE_LANGUAGE_OPTIONS, which the partner picker shares;
- regenerated frontend contracts, and tests mirroring the Malay change.
The interface language is unchanged: no web catalog or picker entry.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
msvcrt's LK_LOCK gives up with EDEADLK after about ten seconds, and a
one-time upgrade of a large session database can hold the lock longer than
that. Retry on EDEADLK so the other workers wait, as flock does on POSIX;
any other lock error still propagates.
msvcrt's LK_LOCK gives up with EDEADLK after about ten seconds, and a worker
importing a large legacy store holds the lock longer than that. Retry on
EDEADLK so the other workers wait, as flock does on POSIX; any other lock
error still propagates.
LegacyChatSessionMigrator.migrate runs under _migration_lock because
every worker runs it at startup, but the lock used fcntl only and was a
no-op on Windows. Workers there copied, imported and archived the same
v1 sessions file at once: with 4 processes x 5 rounds, 17 of 20 runs
failed (LegacyMigrationError from colliding imports, WinError 32 on the
backup copy).
Take an msvcrt byte-range lock when fcntl is unavailable, in the same
shape as the other cross-process locks.
SQLiteSessionStore runs its WAL switch and schema creation under
_migration_lock, which serializes worker processes with fcntl.flock but
was a no-op on Windows. Processes opening the store together there
raced: on a fresh database 14 of 30 concurrent opens failed with
"database is locked" (PRAGMA journal_mode = WAL) or "trigger
practice_capture_update already exists".
Take an msvcrt byte-range lock when fcntl is unavailable, in the same
shape as the grants, cron and Codex-auth locks.
Return the detached thread ids from deleteMessage and have deleteTurn
notify the session-change bus, so useSessionThreads and the viewer refresh
immediately instead of keeping a stale marker.
ChatWorkspace clears only the tabs still pointing at one of the deleted
message rows; a newer passage selected but not yet sent survives the delete.
Persist a structured selection_source beside the assistant prompt, and use
the legacy sidebar prompt's containing message, role and selection to
disambiguate repeated text. Scan every user message for a quote, refuse to
guess between several, and make the backfill conditional so a concurrent move
or detach wins.
Serialize PocketBase preference merges with a lock that spans event loops,
not one asyncio lock per loop, and validate client-supplied anchors on turns
and organization updates. Detach threads when the message they point at is
deleted.
quoted_message_id now follows the create_target rule: the key's presence
is authoritative. A value moves the thread, an explicit null clears it,
and omitting the key leaves the stored anchor untouched. A new selection
moves the thread to the passage just asked about.
The message-level popover gains a detach action that clears the anchor
through the organization PATCH without deleting the conversation, and a
deliberate clear also stops the legacy backfill from re-attaching it.
Threads created before the attribution existed kept only the passage:
selection threads store it in tutor_selected_text, newer side chats as a
quote attachment. Match that passage against the parent transcript with
the Markdown projection selection grounding uses, and record the source
only when exactly one message contains it.
The scan is recorded per thread and runs when the thread list is read,
so it happens once; touch=false keeps the thread's place in the list.
Side chats are filed under the message their quoted passage came from:
the turn carries quoted_message_id, the backend stores it as
tutor_source_message_id, and the chat list shows "Little Tutor x N"
under that message with a popover to open or delete each thread.
Threads are read once per conversation and shared with the viewer, only
side-chat turns refresh the session lists, and a turn that omits the
field leaves the stored anchor untouched.
Refs #2118
The visual-coverage report and recovered usage reports are UTF-8 JSON
written by this codebase, but were read through the locale default.
Non-ASCII titles made coverage fall back to unverified and cost recovery
silently lose per-model details on Chinese Windows.
CommonMark only lets `**` close when it is right-flanking. A closing
marker right after a punctuation mark and right before a letter is not,
so a line like
つまり、**関連付けは「どの表を見るか」**です。
shows its asterisks instead of bold text. DeepTutor already repairs this
by inserting one space at the boundary, both for display
(`repairChineseEmphasis`, `appendWithEmphasisRepair`) and before an
answer is stored (`_repair_chinese_emphasis_for_persistence`). But all
three only ran when the reply language started with "zh". Japanese and
Korean set punctuation flush against the next word in the same way, so
replies in `ja` and `ko` hit the same rule and were left broken.
Run the existing repair for zh, ja and ko. The repair logic itself is
unchanged; its character classes already cover kana and hangul.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>