WeKnora/internal/agent/compaction/compactor.go

337 lines
11 KiB
Go
Raw Normal View History

package compaction
import (
"context"
"errors"
"fmt"
"strings"
"time"
agenttoken "github.com/Tencent/WeKnora/internal/agent/token"
"github.com/Tencent/WeKnora/internal/models/chat"
"github.com/Tencent/WeKnora/internal/types"
)
const (
// maxSummarizationAttempts bounds the retries for one compaction. Each
// attempt is a full LLM round-trip, and a compaction that keeps failing is
// better served by the raw archive than by stalling the turn.
maxSummarizationAttempts = 2
// llmCallLabel identifies compaction traffic in tracing and usage
// accounting, separating it from the agent's own reasoning rounds.
llmCallLabel = "agent_context_compaction"
)
// Reason records what asked for a compaction, for logging and for the UI.
type Reason string
const (
// ReasonThreshold is the routine case: context crossed the budget.
ReasonThreshold Reason = "threshold"
// ReasonOverflow is repair after the provider rejected or truncated a
// request because the window was full.
ReasonOverflow Reason = "overflow"
)
// ErrNothingToCompact means the context cannot be made smaller: everything
// outside the keep-recent budget is already gone. Callers must treat this as a
// stop signal rather than retrying, or they reproduce the every-round
// summarization loop this package exists to prevent.
var ErrNothingToCompact = errors.New("compaction: nothing outside the keep-recent budget")
// Result describes what one compaction did.
type Result struct {
Messages []chat.Message
Summary string
Reason Reason
TokensBefore int
TokensAfter int
MessagesBefore int
MessagesAfter int
// Degraded reports that at least one summary came from the raw archive
// because the summarizer failed. The context still shrank; its memory is
// just coarser.
Degraded bool
// SplitTurn reports that the cut divided a single turn, so a turn-prefix
// summary was generated alongside the history summary.
SplitTurn bool
feat(agent): persist compaction checkpoints across turns (#3407) * feat(agent): persist compaction checkpoints across turns Agent compaction only lived inside the turn that ran it: the summary was discarded at turn end and LoadAgentHistory rebuilt raw history from the messages table, so every later turn past the threshold paid for another summarization of nearly the same history. A compaction whose history summary ends exactly on a stored turn is now written onto that turn's assistant message (messages.context_checkpoint). LoadAgentHistory starts from the newest checkpoint: the summary replaces that turn and everything before it, and later turns are replayed verbatim. The compactor already treats a leading summary as the previous summary, so checkpoints fold forward incrementally. History messages carry their turn's assistant message ID (chat.Message TurnID, engine-internal) so compaction can tell whether its cut lands on a stored-turn boundary. Nothing is persisted when the cut ends inside a stored turn, covers only the live turn, or the history summary degraded to a raw archive; a split turn's prefix summary is never persisted because that turn is replayed whole next time. Writes are column-scoped and best-effort, and a failed lookup falls back to history without a checkpoint. Storing the checkpoint on the covered turn keeps the boundary implicit, so session forks copy it with the turn and deleting the turn drops it. The HistoryTurns cap still applies, now to the turns after the checkpoint. * test(skill): wait for the background install in the name-conflict test InstallSkill queues the install on a goroutine, and the fixture row already starts at installing, so reading the status right after the call raced the mock install and failed whenever it landed on ready first. Wait for the run to finish on the reused row instead, as the other install tests do. * feat(agent): size agent history by tokens instead of turn count Agent history was capped at history_turns (default 5) because every turn used to rebuild raw history and compaction could not persist. With compaction checkpoints persisted, the cap is no longer what keeps a session inside the window, and it threw away context that would have fit. LoadAgentHistory now loads the newest checkpoint summary plus the newest turns after it that fit a token budget: the run's compaction threshold (agent.HistoryTokenBudget, the window less the reply reserve). History that large already triggers the first round's compaction, which persists a new checkpoint, so compaction rather than a turn count bounds the session. Loading more would only hand that compaction a summarizer input larger than the model can read. Rows are paged backwards by (created_at, id) and the read stops at the checkpoint or once the budget is full, so a long session is never read whole. Kept turns stay contiguous, the newest turn is kept even when it alone exceeds the budget (compaction splits it), and a turn cut by the read is left out rather than replayed without its original question. Agent mode no longer reads history_turns: AgentConfig.HistoryTurns is removed, the editor hides the input in smart-reasoning mode and explains the automatic behavior, and the smart-reasoning builtins drop the setting. Quick-answer (KnowledgeQA) keeps its turn cap since it has no compaction. * Revert "feat(agent): size agent history by tokens instead of turn count" This reverts commit d05fb6e5f1f161813a88e9127609f7a059f38f12. Loading history up to the compaction threshold lets the loader drop the oldest turns before compaction can trigger: whenever a single turn's replay is larger than the system prompt plus the new question, the trimmed history stays under the threshold, nothing is summarized, and the session degrades into a large sliding window that never gets a checkpoint. A turn-by-turn simulation of LoadAgentHistory with the real compactor showed zero compactions over 60 turns in those cases. Keep the persisted checkpoints with the HistoryTurns cap for now; token budgeted history returns in a separate change with a budget that leaves the overflow to compaction.
2026-09-18 12:38:56 +00:00
// Checkpoint is the part of this compaction a later turn can start from,
// or nil when there is none (see Preparation.checkpoint).
Checkpoint *Checkpoint
feat(agent): size agent history by the window and calibrate token estimates (#3413) * feat(agent): size agent history by the window and calibrate token estimates Agent history was capped at history_turns (default 5) because compaction could not survive a turn. With checkpoints persisted, load history by tokens instead, and let compaction bound the session. Budget. The loader drops the oldest turns that do not fit, and what it drops is lost: neither replayed nor summarized. A budget equal to the compaction threshold (the earlier attempt, since reverted) let the loader trim first, so whenever one turn was larger than the system prompt plus the new question the request never crossed the threshold; nothing was summarized and the session became a sliding window with no checkpoint. agent.HistoryTokenBudget is now the whole window: overflow reaches the first round's compaction, which summarizes it into a new checkpoint. A turn-by-turn regression test drives the real loader, budget and compactor and fails as soon as a stored turn after the checkpoint is missing from the loaded history; restoring the old budget fails it. Summarizer input. History can now reach the window, so the part being summarized can outgrow one request. An overflowing request degrades to a raw archive that is never persisted, so every later turn would fail the same way. Prepare keeps the newest messages that fit, the prompt states how many were left out, and file paths still come from all of them. Calibration. cl100k counts Chinese at about a token a character where Qwen and DeepSeek spend about 0.6. The estimator now carries a scale (clamped to 0.5-1.5, text only), learned from consecutive requests in a turn: they share tools, system prompt and earlier messages, so the provider's growth between them prices exactly the appended messages, without mixing in how a provider renders tool schemas. The turn's scale is stored on its usage (context_token_scale); the next turn's loader prices history with it and hands it to the engine. Loading, the first compaction check and compaction itself share one estimator, so they agree; calibrating only the trigger would let the loader drop turns again, which the regression test covers. Also: history is priced as the engine sends it (redacted KB/Wiki results cost one line); a checkpoint older than the rows read is matched by the assistant rows' (created_at, id) order; a read ending on a turn's question keeps that turn; a compaction discarded for freeing under 5% still persists its checkpoint; a checkpoint write matching no row is an error; a partial index backs the newest-checkpoint lookup. Agent mode no longer reads history_turns: the field leaves AgentConfig, the editor hides it in smart-reasoning mode, and quick-answer keeps its turn cap. * fix(agent): address review of window-sized history loading Summarization. The summarizer call had a fixed 60s total timeout. With history loaded up to the window, a request could carry ~175k tokens and be cut off while prefilling or writing normally; the degraded result left no checkpoint, so the next turn reloaded the same history and failed the same way. Summarization now streams and is cancelled only after no output for the engine's stall timeout (120s by default, LLMCallTimeout overrides), with the overall ceiling left to the transport, as for the engine's own rounds and as in Codex and Pi. A stopped turn is not retried. When the summarizer still fails, the raw archive is persisted as a checkpoint marked degraded so the loop is broken, and the next compaction refines it as the previous summary. The archive is held to the summary budget, newest messages first, so a degraded compaction always frees room. Loading. The loader priced turns as sent but returned and held them as stored, so wiki pages stored in full and sent as one line could pile up in memory. It now returns the as-sent history and releases each turn's stored rows once replayed, keeping about a page of rows at a time. Index. The partial checkpoint index is replaced by a composite (session_id, created_at DESC, id DESC) index serving the backwards page, the newest-checkpoint lookup and the recent-messages reads. It is built with CREATE INDEX CONCURRENTLY so writes to messages are not blocked; the migration holds that single statement, since a multi-statement query runs as an implicit transaction. A PostgreSQL integration test, skipped without WEKNORA_MIGRATION_TEST_POSTGRES_DSN, applies the chain, runs 000106 down and up through golang-migrate, and checks both queries use the index without a sort; the SQLite migration test checks the same plans. Calibration. It no longer waits for a total token count, and a usage with only a scale is persisted. A turn that measures nothing carries forward the scale it started from, so the newest turn always has the latest one.
2026-09-18 14:51:31 +00:00
// Omitted counts the oldest messages left out of the summarization
// requests because they did not fit (see fitSummarizerInput).
Omitted int
feat(agent): persist compaction checkpoints across turns (#3407) * feat(agent): persist compaction checkpoints across turns Agent compaction only lived inside the turn that ran it: the summary was discarded at turn end and LoadAgentHistory rebuilt raw history from the messages table, so every later turn past the threshold paid for another summarization of nearly the same history. A compaction whose history summary ends exactly on a stored turn is now written onto that turn's assistant message (messages.context_checkpoint). LoadAgentHistory starts from the newest checkpoint: the summary replaces that turn and everything before it, and later turns are replayed verbatim. The compactor already treats a leading summary as the previous summary, so checkpoints fold forward incrementally. History messages carry their turn's assistant message ID (chat.Message TurnID, engine-internal) so compaction can tell whether its cut lands on a stored-turn boundary. Nothing is persisted when the cut ends inside a stored turn, covers only the live turn, or the history summary degraded to a raw archive; a split turn's prefix summary is never persisted because that turn is replayed whole next time. Writes are column-scoped and best-effort, and a failed lookup falls back to history without a checkpoint. Storing the checkpoint on the covered turn keeps the boundary implicit, so session forks copy it with the turn and deleting the turn drops it. The HistoryTurns cap still applies, now to the turns after the checkpoint. * test(skill): wait for the background install in the name-conflict test InstallSkill queues the install on a goroutine, and the fixture row already starts at installing, so reading the status right after the call raced the mock install and failed whenever it landed on ready first. Wait for the run to finish on the reused row instead, as the other install tests do. * feat(agent): size agent history by tokens instead of turn count Agent history was capped at history_turns (default 5) because every turn used to rebuild raw history and compaction could not persist. With compaction checkpoints persisted, the cap is no longer what keeps a session inside the window, and it threw away context that would have fit. LoadAgentHistory now loads the newest checkpoint summary plus the newest turns after it that fit a token budget: the run's compaction threshold (agent.HistoryTokenBudget, the window less the reply reserve). History that large already triggers the first round's compaction, which persists a new checkpoint, so compaction rather than a turn count bounds the session. Loading more would only hand that compaction a summarizer input larger than the model can read. Rows are paged backwards by (created_at, id) and the read stops at the checkpoint or once the budget is full, so a long session is never read whole. Kept turns stay contiguous, the newest turn is kept even when it alone exceeds the budget (compaction splits it), and a turn cut by the read is left out rather than replayed without its original question. Agent mode no longer reads history_turns: AgentConfig.HistoryTurns is removed, the editor hides the input in smart-reasoning mode and explains the automatic behavior, and the smart-reasoning builtins drop the setting. Quick-answer (KnowledgeQA) keeps its turn cap since it has no compaction. * Revert "feat(agent): size agent history by tokens instead of turn count" This reverts commit d05fb6e5f1f161813a88e9127609f7a059f38f12. Loading history up to the compaction threshold lets the loader drop the oldest turns before compaction can trigger: whenever a single turn's replay is larger than the system prompt plus the new question, the trimmed history stays under the threshold, nothing is summarized, and the session degrades into a large sliding window that never gets a checkpoint. A turn-by-turn simulation of LoadAgentHistory with the real compactor showed zero compactions over 60 turns in those cases. Keep the persisted checkpoints with the HistoryTurns cap for now; token budgeted history returns in a separate change with a budget that leaves the overflow to compaction.
2026-09-18 12:38:56 +00:00
}
// Checkpoint is a summary that ends exactly on a stored turn. Persisted onto
// that turn, it lets the next turn load the summary in place of everything up
// to and including the turn, instead of summarizing the same history again.
type Checkpoint struct {
// TurnID is the stored turn the summary covers through, inclusive.
TurnID string
Summary string
feat(agent): size agent history by the window and calibrate token estimates (#3413) * feat(agent): size agent history by the window and calibrate token estimates Agent history was capped at history_turns (default 5) because compaction could not survive a turn. With checkpoints persisted, load history by tokens instead, and let compaction bound the session. Budget. The loader drops the oldest turns that do not fit, and what it drops is lost: neither replayed nor summarized. A budget equal to the compaction threshold (the earlier attempt, since reverted) let the loader trim first, so whenever one turn was larger than the system prompt plus the new question the request never crossed the threshold; nothing was summarized and the session became a sliding window with no checkpoint. agent.HistoryTokenBudget is now the whole window: overflow reaches the first round's compaction, which summarizes it into a new checkpoint. A turn-by-turn regression test drives the real loader, budget and compactor and fails as soon as a stored turn after the checkpoint is missing from the loaded history; restoring the old budget fails it. Summarizer input. History can now reach the window, so the part being summarized can outgrow one request. An overflowing request degrades to a raw archive that is never persisted, so every later turn would fail the same way. Prepare keeps the newest messages that fit, the prompt states how many were left out, and file paths still come from all of them. Calibration. cl100k counts Chinese at about a token a character where Qwen and DeepSeek spend about 0.6. The estimator now carries a scale (clamped to 0.5-1.5, text only), learned from consecutive requests in a turn: they share tools, system prompt and earlier messages, so the provider's growth between them prices exactly the appended messages, without mixing in how a provider renders tool schemas. The turn's scale is stored on its usage (context_token_scale); the next turn's loader prices history with it and hands it to the engine. Loading, the first compaction check and compaction itself share one estimator, so they agree; calibrating only the trigger would let the loader drop turns again, which the regression test covers. Also: history is priced as the engine sends it (redacted KB/Wiki results cost one line); a checkpoint older than the rows read is matched by the assistant rows' (created_at, id) order; a read ending on a turn's question keeps that turn; a compaction discarded for freeing under 5% still persists its checkpoint; a checkpoint write matching no row is an error; a partial index backs the newest-checkpoint lookup. Agent mode no longer reads history_turns: the field leaves AgentConfig, the editor hides it in smart-reasoning mode, and quick-answer keeps its turn cap. * fix(agent): address review of window-sized history loading Summarization. The summarizer call had a fixed 60s total timeout. With history loaded up to the window, a request could carry ~175k tokens and be cut off while prefilling or writing normally; the degraded result left no checkpoint, so the next turn reloaded the same history and failed the same way. Summarization now streams and is cancelled only after no output for the engine's stall timeout (120s by default, LLMCallTimeout overrides), with the overall ceiling left to the transport, as for the engine's own rounds and as in Codex and Pi. A stopped turn is not retried. When the summarizer still fails, the raw archive is persisted as a checkpoint marked degraded so the loop is broken, and the next compaction refines it as the previous summary. The archive is held to the summary budget, newest messages first, so a degraded compaction always frees room. Loading. The loader priced turns as sent but returned and held them as stored, so wiki pages stored in full and sent as one line could pile up in memory. It now returns the as-sent history and releases each turn's stored rows once replayed, keeping about a page of rows at a time. Index. The partial checkpoint index is replaced by a composite (session_id, created_at DESC, id DESC) index serving the backwards page, the newest-checkpoint lookup and the recent-messages reads. It is built with CREATE INDEX CONCURRENTLY so writes to messages are not blocked; the migration holds that single statement, since a multi-statement query runs as an implicit transaction. A PostgreSQL integration test, skipped without WEKNORA_MIGRATION_TEST_POSTGRES_DSN, applies the chain, runs 000106 down and up through golang-migrate, and checks both queries use the index without a sort; the SQLite migration test checks the same plans. Calibration. It no longer waits for a total token count, and a usage with only a scale is persisted. A turn that measures nothing carries forward the scale it started from, so the newest turn always has the latest one.
2026-09-18 14:51:31 +00:00
// Degraded reports that Summary holds a raw archive because the
// summarizer failed. It is still a checkpoint: the next compaction
// folds it in as the previous summary.
Degraded bool
}
// Freed is how much room the compaction actually recovered. A non-positive
// value means the summary cost as much as the history it replaced.
func (r *Result) Freed() int {
return r.TokensBefore - r.TokensAfter
}
// Compactor summarizes conversation history into a checkpoint.
type Compactor struct {
chatModel chat.Chat
estimator *agenttoken.Estimator
settings Settings
}
// New builds a compactor. It returns nil when compaction cannot run, so the
// caller can treat a nil compactor as "feature off" without a second flag.
func New(chatModel chat.Chat, estimator *agenttoken.Estimator, settings Settings) *Compactor {
if chatModel == nil || estimator == nil || settings.MaxContextTokens <= 0 {
return nil
}
return &Compactor{chatModel: chatModel, estimator: estimator, settings: settings.Normalize()}
}
// Settings returns the normalized settings, including the derived threshold.
func (c *Compactor) Settings() Settings {
if c == nil {
return Settings{}
}
return c.settings
}
// Compact replaces history older than the keep-recent budget with a summary.
// It returns ErrNothingToCompact when no such history exists.
func (c *Compactor) Compact(
ctx context.Context, messages []chat.Message, reason Reason,
) (*Result, error) {
if c == nil {
return nil, ErrNothingToCompact
}
prep := Prepare(messages, c.settings, c.estimator)
if prep == nil {
return nil, ErrNothingToCompact
}
feat(agent): persist compaction checkpoints across turns (#3407) * feat(agent): persist compaction checkpoints across turns Agent compaction only lived inside the turn that ran it: the summary was discarded at turn end and LoadAgentHistory rebuilt raw history from the messages table, so every later turn past the threshold paid for another summarization of nearly the same history. A compaction whose history summary ends exactly on a stored turn is now written onto that turn's assistant message (messages.context_checkpoint). LoadAgentHistory starts from the newest checkpoint: the summary replaces that turn and everything before it, and later turns are replayed verbatim. The compactor already treats a leading summary as the previous summary, so checkpoints fold forward incrementally. History messages carry their turn's assistant message ID (chat.Message TurnID, engine-internal) so compaction can tell whether its cut lands on a stored-turn boundary. Nothing is persisted when the cut ends inside a stored turn, covers only the live turn, or the history summary degraded to a raw archive; a split turn's prefix summary is never persisted because that turn is replayed whole next time. Writes are column-scoped and best-effort, and a failed lookup falls back to history without a checkpoint. Storing the checkpoint on the covered turn keeps the boundary implicit, so session forks copy it with the turn and deleting the turn drops it. The HistoryTurns cap still applies, now to the turns after the checkpoint. * test(skill): wait for the background install in the name-conflict test InstallSkill queues the install on a goroutine, and the fixture row already starts at installing, so reading the status right after the call raced the mock install and failed whenever it landed on ready first. Wait for the run to finish on the reused row instead, as the other install tests do. * feat(agent): size agent history by tokens instead of turn count Agent history was capped at history_turns (default 5) because every turn used to rebuild raw history and compaction could not persist. With compaction checkpoints persisted, the cap is no longer what keeps a session inside the window, and it threw away context that would have fit. LoadAgentHistory now loads the newest checkpoint summary plus the newest turns after it that fit a token budget: the run's compaction threshold (agent.HistoryTokenBudget, the window less the reply reserve). History that large already triggers the first round's compaction, which persists a new checkpoint, so compaction rather than a turn count bounds the session. Loading more would only hand that compaction a summarizer input larger than the model can read. Rows are paged backwards by (created_at, id) and the read stops at the checkpoint or once the budget is full, so a long session is never read whole. Kept turns stay contiguous, the newest turn is kept even when it alone exceeds the budget (compaction splits it), and a turn cut by the read is left out rather than replayed without its original question. Agent mode no longer reads history_turns: AgentConfig.HistoryTurns is removed, the editor hides the input in smart-reasoning mode and explains the automatic behavior, and the smart-reasoning builtins drop the setting. Quick-answer (KnowledgeQA) keeps its turn cap since it has no compaction. * Revert "feat(agent): size agent history by tokens instead of turn count" This reverts commit d05fb6e5f1f161813a88e9127609f7a059f38f12. Loading history up to the compaction threshold lets the loader drop the oldest turns before compaction can trigger: whenever a single turn's replay is larger than the system prompt plus the new question, the trimmed history stays under the threshold, nothing is summarized, and the session degrades into a large sliding window that never gets a checkpoint. A turn-by-turn simulation of LoadAgentHistory with the real compactor showed zero compactions over 60 turns in those cases. Keep the persisted checkpoints with the HistoryTurns cap for now; token budgeted history returns in a separate change with a budget that leaves the overflow to compaction.
2026-09-18 12:38:56 +00:00
history, historyDegraded := c.summarizeHistory(ctx, prep)
summary, prefixDegraded := c.appendTurnPrefix(ctx, prep, history)
summary += prep.fileOps.format()
compacted := Apply(messages, prep, summary)
return &Result{
Messages: compacted,
Summary: summary,
Reason: reason,
TokensBefore: prep.TokensBefore,
TokensAfter: c.estimator.EstimateMessages(compacted),
MessagesBefore: len(messages),
MessagesAfter: len(compacted),
feat(agent): persist compaction checkpoints across turns (#3407) * feat(agent): persist compaction checkpoints across turns Agent compaction only lived inside the turn that ran it: the summary was discarded at turn end and LoadAgentHistory rebuilt raw history from the messages table, so every later turn past the threshold paid for another summarization of nearly the same history. A compaction whose history summary ends exactly on a stored turn is now written onto that turn's assistant message (messages.context_checkpoint). LoadAgentHistory starts from the newest checkpoint: the summary replaces that turn and everything before it, and later turns are replayed verbatim. The compactor already treats a leading summary as the previous summary, so checkpoints fold forward incrementally. History messages carry their turn's assistant message ID (chat.Message TurnID, engine-internal) so compaction can tell whether its cut lands on a stored-turn boundary. Nothing is persisted when the cut ends inside a stored turn, covers only the live turn, or the history summary degraded to a raw archive; a split turn's prefix summary is never persisted because that turn is replayed whole next time. Writes are column-scoped and best-effort, and a failed lookup falls back to history without a checkpoint. Storing the checkpoint on the covered turn keeps the boundary implicit, so session forks copy it with the turn and deleting the turn drops it. The HistoryTurns cap still applies, now to the turns after the checkpoint. * test(skill): wait for the background install in the name-conflict test InstallSkill queues the install on a goroutine, and the fixture row already starts at installing, so reading the status right after the call raced the mock install and failed whenever it landed on ready first. Wait for the run to finish on the reused row instead, as the other install tests do. * feat(agent): size agent history by tokens instead of turn count Agent history was capped at history_turns (default 5) because every turn used to rebuild raw history and compaction could not persist. With compaction checkpoints persisted, the cap is no longer what keeps a session inside the window, and it threw away context that would have fit. LoadAgentHistory now loads the newest checkpoint summary plus the newest turns after it that fit a token budget: the run's compaction threshold (agent.HistoryTokenBudget, the window less the reply reserve). History that large already triggers the first round's compaction, which persists a new checkpoint, so compaction rather than a turn count bounds the session. Loading more would only hand that compaction a summarizer input larger than the model can read. Rows are paged backwards by (created_at, id) and the read stops at the checkpoint or once the budget is full, so a long session is never read whole. Kept turns stay contiguous, the newest turn is kept even when it alone exceeds the budget (compaction splits it), and a turn cut by the read is left out rather than replayed without its original question. Agent mode no longer reads history_turns: AgentConfig.HistoryTurns is removed, the editor hides the input in smart-reasoning mode and explains the automatic behavior, and the smart-reasoning builtins drop the setting. Quick-answer (KnowledgeQA) keeps its turn cap since it has no compaction. * Revert "feat(agent): size agent history by tokens instead of turn count" This reverts commit d05fb6e5f1f161813a88e9127609f7a059f38f12. Loading history up to the compaction threshold lets the loader drop the oldest turns before compaction can trigger: whenever a single turn's replay is larger than the system prompt plus the new question, the trimmed history stays under the threshold, nothing is summarized, and the session degrades into a large sliding window that never gets a checkpoint. A turn-by-turn simulation of LoadAgentHistory with the real compactor showed zero compactions over 60 turns in those cases. Keep the persisted checkpoints with the HistoryTurns cap for now; token budgeted history returns in a separate change with a budget that leaves the overflow to compaction.
2026-09-18 12:38:56 +00:00
Degraded: historyDegraded || prefixDegraded,
SplitTurn: prep.IsSplitTurn,
feat(agent): persist compaction checkpoints across turns (#3407) * feat(agent): persist compaction checkpoints across turns Agent compaction only lived inside the turn that ran it: the summary was discarded at turn end and LoadAgentHistory rebuilt raw history from the messages table, so every later turn past the threshold paid for another summarization of nearly the same history. A compaction whose history summary ends exactly on a stored turn is now written onto that turn's assistant message (messages.context_checkpoint). LoadAgentHistory starts from the newest checkpoint: the summary replaces that turn and everything before it, and later turns are replayed verbatim. The compactor already treats a leading summary as the previous summary, so checkpoints fold forward incrementally. History messages carry their turn's assistant message ID (chat.Message TurnID, engine-internal) so compaction can tell whether its cut lands on a stored-turn boundary. Nothing is persisted when the cut ends inside a stored turn, covers only the live turn, or the history summary degraded to a raw archive; a split turn's prefix summary is never persisted because that turn is replayed whole next time. Writes are column-scoped and best-effort, and a failed lookup falls back to history without a checkpoint. Storing the checkpoint on the covered turn keeps the boundary implicit, so session forks copy it with the turn and deleting the turn drops it. The HistoryTurns cap still applies, now to the turns after the checkpoint. * test(skill): wait for the background install in the name-conflict test InstallSkill queues the install on a goroutine, and the fixture row already starts at installing, so reading the status right after the call raced the mock install and failed whenever it landed on ready first. Wait for the run to finish on the reused row instead, as the other install tests do. * feat(agent): size agent history by tokens instead of turn count Agent history was capped at history_turns (default 5) because every turn used to rebuild raw history and compaction could not persist. With compaction checkpoints persisted, the cap is no longer what keeps a session inside the window, and it threw away context that would have fit. LoadAgentHistory now loads the newest checkpoint summary plus the newest turns after it that fit a token budget: the run's compaction threshold (agent.HistoryTokenBudget, the window less the reply reserve). History that large already triggers the first round's compaction, which persists a new checkpoint, so compaction rather than a turn count bounds the session. Loading more would only hand that compaction a summarizer input larger than the model can read. Rows are paged backwards by (created_at, id) and the read stops at the checkpoint or once the budget is full, so a long session is never read whole. Kept turns stay contiguous, the newest turn is kept even when it alone exceeds the budget (compaction splits it), and a turn cut by the read is left out rather than replayed without its original question. Agent mode no longer reads history_turns: AgentConfig.HistoryTurns is removed, the editor hides the input in smart-reasoning mode and explains the automatic behavior, and the smart-reasoning builtins drop the setting. Quick-answer (KnowledgeQA) keeps its turn cap since it has no compaction. * Revert "feat(agent): size agent history by tokens instead of turn count" This reverts commit d05fb6e5f1f161813a88e9127609f7a059f38f12. Loading history up to the compaction threshold lets the loader drop the oldest turns before compaction can trigger: whenever a single turn's replay is larger than the system prompt plus the new question, the trimmed history stays under the threshold, nothing is summarized, and the session degrades into a large sliding window that never gets a checkpoint. A turn-by-turn simulation of LoadAgentHistory with the real compactor showed zero compactions over 60 turns in those cases. Keep the persisted checkpoints with the HistoryTurns cap for now; token budgeted history returns in a separate change with a budget that leaves the overflow to compaction.
2026-09-18 12:38:56 +00:00
Checkpoint: prep.checkpoint(history, historyDegraded),
feat(agent): size agent history by the window and calibrate token estimates (#3413) * feat(agent): size agent history by the window and calibrate token estimates Agent history was capped at history_turns (default 5) because compaction could not survive a turn. With checkpoints persisted, load history by tokens instead, and let compaction bound the session. Budget. The loader drops the oldest turns that do not fit, and what it drops is lost: neither replayed nor summarized. A budget equal to the compaction threshold (the earlier attempt, since reverted) let the loader trim first, so whenever one turn was larger than the system prompt plus the new question the request never crossed the threshold; nothing was summarized and the session became a sliding window with no checkpoint. agent.HistoryTokenBudget is now the whole window: overflow reaches the first round's compaction, which summarizes it into a new checkpoint. A turn-by-turn regression test drives the real loader, budget and compactor and fails as soon as a stored turn after the checkpoint is missing from the loaded history; restoring the old budget fails it. Summarizer input. History can now reach the window, so the part being summarized can outgrow one request. An overflowing request degrades to a raw archive that is never persisted, so every later turn would fail the same way. Prepare keeps the newest messages that fit, the prompt states how many were left out, and file paths still come from all of them. Calibration. cl100k counts Chinese at about a token a character where Qwen and DeepSeek spend about 0.6. The estimator now carries a scale (clamped to 0.5-1.5, text only), learned from consecutive requests in a turn: they share tools, system prompt and earlier messages, so the provider's growth between them prices exactly the appended messages, without mixing in how a provider renders tool schemas. The turn's scale is stored on its usage (context_token_scale); the next turn's loader prices history with it and hands it to the engine. Loading, the first compaction check and compaction itself share one estimator, so they agree; calibrating only the trigger would let the loader drop turns again, which the regression test covers. Also: history is priced as the engine sends it (redacted KB/Wiki results cost one line); a checkpoint older than the rows read is matched by the assistant rows' (created_at, id) order; a read ending on a turn's question keeps that turn; a compaction discarded for freeing under 5% still persists its checkpoint; a checkpoint write matching no row is an error; a partial index backs the newest-checkpoint lookup. Agent mode no longer reads history_turns: the field leaves AgentConfig, the editor hides it in smart-reasoning mode, and quick-answer keeps its turn cap. * fix(agent): address review of window-sized history loading Summarization. The summarizer call had a fixed 60s total timeout. With history loaded up to the window, a request could carry ~175k tokens and be cut off while prefilling or writing normally; the degraded result left no checkpoint, so the next turn reloaded the same history and failed the same way. Summarization now streams and is cancelled only after no output for the engine's stall timeout (120s by default, LLMCallTimeout overrides), with the overall ceiling left to the transport, as for the engine's own rounds and as in Codex and Pi. A stopped turn is not retried. When the summarizer still fails, the raw archive is persisted as a checkpoint marked degraded so the loop is broken, and the next compaction refines it as the previous summary. The archive is held to the summary budget, newest messages first, so a degraded compaction always frees room. Loading. The loader priced turns as sent but returned and held them as stored, so wiki pages stored in full and sent as one line could pile up in memory. It now returns the as-sent history and releases each turn's stored rows once replayed, keeping about a page of rows at a time. Index. The partial checkpoint index is replaced by a composite (session_id, created_at DESC, id DESC) index serving the backwards page, the newest-checkpoint lookup and the recent-messages reads. It is built with CREATE INDEX CONCURRENTLY so writes to messages are not blocked; the migration holds that single statement, since a multi-statement query runs as an implicit transaction. A PostgreSQL integration test, skipped without WEKNORA_MIGRATION_TEST_POSTGRES_DSN, applies the chain, runs 000106 down and up through golang-migrate, and checks both queries use the index without a sort; the SQLite migration test checks the same plans. Calibration. It no longer waits for a total token count, and a usage with only a scale is persisted. A turn that measures nothing carries forward the scale it started from, so the newest turn always has the latest one.
2026-09-18 14:51:31 +00:00
Omitted: prep.OmittedHistory + prep.OmittedTurnPrefix,
}, nil
}
feat(agent): persist compaction checkpoints across turns (#3407) * feat(agent): persist compaction checkpoints across turns Agent compaction only lived inside the turn that ran it: the summary was discarded at turn end and LoadAgentHistory rebuilt raw history from the messages table, so every later turn past the threshold paid for another summarization of nearly the same history. A compaction whose history summary ends exactly on a stored turn is now written onto that turn's assistant message (messages.context_checkpoint). LoadAgentHistory starts from the newest checkpoint: the summary replaces that turn and everything before it, and later turns are replayed verbatim. The compactor already treats a leading summary as the previous summary, so checkpoints fold forward incrementally. History messages carry their turn's assistant message ID (chat.Message TurnID, engine-internal) so compaction can tell whether its cut lands on a stored-turn boundary. Nothing is persisted when the cut ends inside a stored turn, covers only the live turn, or the history summary degraded to a raw archive; a split turn's prefix summary is never persisted because that turn is replayed whole next time. Writes are column-scoped and best-effort, and a failed lookup falls back to history without a checkpoint. Storing the checkpoint on the covered turn keeps the boundary implicit, so session forks copy it with the turn and deleting the turn drops it. The HistoryTurns cap still applies, now to the turns after the checkpoint. * test(skill): wait for the background install in the name-conflict test InstallSkill queues the install on a goroutine, and the fixture row already starts at installing, so reading the status right after the call raced the mock install and failed whenever it landed on ready first. Wait for the run to finish on the reused row instead, as the other install tests do. * feat(agent): size agent history by tokens instead of turn count Agent history was capped at history_turns (default 5) because every turn used to rebuild raw history and compaction could not persist. With compaction checkpoints persisted, the cap is no longer what keeps a session inside the window, and it threw away context that would have fit. LoadAgentHistory now loads the newest checkpoint summary plus the newest turns after it that fit a token budget: the run's compaction threshold (agent.HistoryTokenBudget, the window less the reply reserve). History that large already triggers the first round's compaction, which persists a new checkpoint, so compaction rather than a turn count bounds the session. Loading more would only hand that compaction a summarizer input larger than the model can read. Rows are paged backwards by (created_at, id) and the read stops at the checkpoint or once the budget is full, so a long session is never read whole. Kept turns stay contiguous, the newest turn is kept even when it alone exceeds the budget (compaction splits it), and a turn cut by the read is left out rather than replayed without its original question. Agent mode no longer reads history_turns: AgentConfig.HistoryTurns is removed, the editor hides the input in smart-reasoning mode and explains the automatic behavior, and the smart-reasoning builtins drop the setting. Quick-answer (KnowledgeQA) keeps its turn cap since it has no compaction. * Revert "feat(agent): size agent history by tokens instead of turn count" This reverts commit d05fb6e5f1f161813a88e9127609f7a059f38f12. Loading history up to the compaction threshold lets the loader drop the oldest turns before compaction can trigger: whenever a single turn's replay is larger than the system prompt plus the new question, the trimmed history stays under the threshold, nothing is summarized, and the session degrades into a large sliding window that never gets a checkpoint. A turn-by-turn simulation of LoadAgentHistory with the real compactor showed zero compactions over 60 turns in those cases. Keep the persisted checkpoints with the HistoryTurns cap for now; token budgeted history returns in a separate change with a budget that leaves the overflow to compaction.
2026-09-18 12:38:56 +00:00
// summarizeHistory folds the complete turns being dropped into the previous
// summary, falling back to a raw archive when the summarizer fails.
func (c *Compactor) summarizeHistory(ctx context.Context, p *Preparation) (string, bool) {
if len(p.MessagesToSummarize) == 0 {
return p.PreviousSummary, false
}
feat(agent): persist compaction checkpoints across turns (#3407) * feat(agent): persist compaction checkpoints across turns Agent compaction only lived inside the turn that ran it: the summary was discarded at turn end and LoadAgentHistory rebuilt raw history from the messages table, so every later turn past the threshold paid for another summarization of nearly the same history. A compaction whose history summary ends exactly on a stored turn is now written onto that turn's assistant message (messages.context_checkpoint). LoadAgentHistory starts from the newest checkpoint: the summary replaces that turn and everything before it, and later turns are replayed verbatim. The compactor already treats a leading summary as the previous summary, so checkpoints fold forward incrementally. History messages carry their turn's assistant message ID (chat.Message TurnID, engine-internal) so compaction can tell whether its cut lands on a stored-turn boundary. Nothing is persisted when the cut ends inside a stored turn, covers only the live turn, or the history summary degraded to a raw archive; a split turn's prefix summary is never persisted because that turn is replayed whole next time. Writes are column-scoped and best-effort, and a failed lookup falls back to history without a checkpoint. Storing the checkpoint on the covered turn keeps the boundary implicit, so session forks copy it with the turn and deleting the turn drops it. The HistoryTurns cap still applies, now to the turns after the checkpoint. * test(skill): wait for the background install in the name-conflict test InstallSkill queues the install on a goroutine, and the fixture row already starts at installing, so reading the status right after the call raced the mock install and failed whenever it landed on ready first. Wait for the run to finish on the reused row instead, as the other install tests do. * feat(agent): size agent history by tokens instead of turn count Agent history was capped at history_turns (default 5) because every turn used to rebuild raw history and compaction could not persist. With compaction checkpoints persisted, the cap is no longer what keeps a session inside the window, and it threw away context that would have fit. LoadAgentHistory now loads the newest checkpoint summary plus the newest turns after it that fit a token budget: the run's compaction threshold (agent.HistoryTokenBudget, the window less the reply reserve). History that large already triggers the first round's compaction, which persists a new checkpoint, so compaction rather than a turn count bounds the session. Loading more would only hand that compaction a summarizer input larger than the model can read. Rows are paged backwards by (created_at, id) and the read stops at the checkpoint or once the budget is full, so a long session is never read whole. Kept turns stay contiguous, the newest turn is kept even when it alone exceeds the budget (compaction splits it), and a turn cut by the read is left out rather than replayed without its original question. Agent mode no longer reads history_turns: AgentConfig.HistoryTurns is removed, the editor hides the input in smart-reasoning mode and explains the automatic behavior, and the smart-reasoning builtins drop the setting. Quick-answer (KnowledgeQA) keeps its turn cap since it has no compaction. * Revert "feat(agent): size agent history by tokens instead of turn count" This reverts commit d05fb6e5f1f161813a88e9127609f7a059f38f12. Loading history up to the compaction threshold lets the loader drop the oldest turns before compaction can trigger: whenever a single turn's replay is larger than the system prompt plus the new question, the trimmed history stays under the threshold, nothing is summarized, and the session degrades into a large sliding window that never gets a checkpoint. A turn-by-turn simulation of LoadAgentHistory with the real compactor showed zero compactions over 60 turns in those cases. Keep the persisted checkpoints with the HistoryTurns cap for now; token budgeted history returns in a separate change with a budget that leaves the overflow to compaction.
2026-09-18 12:38:56 +00:00
instructions := initialSummarizationInstructions
if p.PreviousSummary != "" {
instructions = updateSummarizationInstructions
}
text, err := c.summarize(
feat(agent): size agent history by the window and calibrate token estimates (#3413) * feat(agent): size agent history by the window and calibrate token estimates Agent history was capped at history_turns (default 5) because compaction could not survive a turn. With checkpoints persisted, load history by tokens instead, and let compaction bound the session. Budget. The loader drops the oldest turns that do not fit, and what it drops is lost: neither replayed nor summarized. A budget equal to the compaction threshold (the earlier attempt, since reverted) let the loader trim first, so whenever one turn was larger than the system prompt plus the new question the request never crossed the threshold; nothing was summarized and the session became a sliding window with no checkpoint. agent.HistoryTokenBudget is now the whole window: overflow reaches the first round's compaction, which summarizes it into a new checkpoint. A turn-by-turn regression test drives the real loader, budget and compactor and fails as soon as a stored turn after the checkpoint is missing from the loaded history; restoring the old budget fails it. Summarizer input. History can now reach the window, so the part being summarized can outgrow one request. An overflowing request degrades to a raw archive that is never persisted, so every later turn would fail the same way. Prepare keeps the newest messages that fit, the prompt states how many were left out, and file paths still come from all of them. Calibration. cl100k counts Chinese at about a token a character where Qwen and DeepSeek spend about 0.6. The estimator now carries a scale (clamped to 0.5-1.5, text only), learned from consecutive requests in a turn: they share tools, system prompt and earlier messages, so the provider's growth between them prices exactly the appended messages, without mixing in how a provider renders tool schemas. The turn's scale is stored on its usage (context_token_scale); the next turn's loader prices history with it and hands it to the engine. Loading, the first compaction check and compaction itself share one estimator, so they agree; calibrating only the trigger would let the loader drop turns again, which the regression test covers. Also: history is priced as the engine sends it (redacted KB/Wiki results cost one line); a checkpoint older than the rows read is matched by the assistant rows' (created_at, id) order; a read ending on a turn's question keeps that turn; a compaction discarded for freeing under 5% still persists its checkpoint; a checkpoint write matching no row is an error; a partial index backs the newest-checkpoint lookup. Agent mode no longer reads history_turns: the field leaves AgentConfig, the editor hides it in smart-reasoning mode, and quick-answer keeps its turn cap. * fix(agent): address review of window-sized history loading Summarization. The summarizer call had a fixed 60s total timeout. With history loaded up to the window, a request could carry ~175k tokens and be cut off while prefilling or writing normally; the degraded result left no checkpoint, so the next turn reloaded the same history and failed the same way. Summarization now streams and is cancelled only after no output for the engine's stall timeout (120s by default, LLMCallTimeout overrides), with the overall ceiling left to the transport, as for the engine's own rounds and as in Codex and Pi. A stopped turn is not retried. When the summarizer still fails, the raw archive is persisted as a checkpoint marked degraded so the loop is broken, and the next compaction refines it as the previous summary. The archive is held to the summary budget, newest messages first, so a degraded compaction always frees room. Loading. The loader priced turns as sent but returned and held them as stored, so wiki pages stored in full and sent as one line could pile up in memory. It now returns the as-sent history and releases each turn's stored rows once replayed, keeping about a page of rows at a time. Index. The partial checkpoint index is replaced by a composite (session_id, created_at DESC, id DESC) index serving the backwards page, the newest-checkpoint lookup and the recent-messages reads. It is built with CREATE INDEX CONCURRENTLY so writes to messages are not blocked; the migration holds that single statement, since a multi-statement query runs as an implicit transaction. A PostgreSQL integration test, skipped without WEKNORA_MIGRATION_TEST_POSTGRES_DSN, applies the chain, runs 000106 down and up through golang-migrate, and checks both queries use the index without a sort; the SQLite migration test checks the same plans. Calibration. It no longer waits for a total token count, and a usage with only a scale is persisted. A turn that measures nothing carries forward the scale it started from, so the newest turn always has the latest one.
2026-09-18 14:51:31 +00:00
ctx, p.MessagesToSummarize, p.OmittedHistory, p.PreviousSummary, instructions, c.settings.summaryBudget(),
feat(agent): persist compaction checkpoints across turns (#3407) * feat(agent): persist compaction checkpoints across turns Agent compaction only lived inside the turn that ran it: the summary was discarded at turn end and LoadAgentHistory rebuilt raw history from the messages table, so every later turn past the threshold paid for another summarization of nearly the same history. A compaction whose history summary ends exactly on a stored turn is now written onto that turn's assistant message (messages.context_checkpoint). LoadAgentHistory starts from the newest checkpoint: the summary replaces that turn and everything before it, and later turns are replayed verbatim. The compactor already treats a leading summary as the previous summary, so checkpoints fold forward incrementally. History messages carry their turn's assistant message ID (chat.Message TurnID, engine-internal) so compaction can tell whether its cut lands on a stored-turn boundary. Nothing is persisted when the cut ends inside a stored turn, covers only the live turn, or the history summary degraded to a raw archive; a split turn's prefix summary is never persisted because that turn is replayed whole next time. Writes are column-scoped and best-effort, and a failed lookup falls back to history without a checkpoint. Storing the checkpoint on the covered turn keeps the boundary implicit, so session forks copy it with the turn and deleting the turn drops it. The HistoryTurns cap still applies, now to the turns after the checkpoint. * test(skill): wait for the background install in the name-conflict test InstallSkill queues the install on a goroutine, and the fixture row already starts at installing, so reading the status right after the call raced the mock install and failed whenever it landed on ready first. Wait for the run to finish on the reused row instead, as the other install tests do. * feat(agent): size agent history by tokens instead of turn count Agent history was capped at history_turns (default 5) because every turn used to rebuild raw history and compaction could not persist. With compaction checkpoints persisted, the cap is no longer what keeps a session inside the window, and it threw away context that would have fit. LoadAgentHistory now loads the newest checkpoint summary plus the newest turns after it that fit a token budget: the run's compaction threshold (agent.HistoryTokenBudget, the window less the reply reserve). History that large already triggers the first round's compaction, which persists a new checkpoint, so compaction rather than a turn count bounds the session. Loading more would only hand that compaction a summarizer input larger than the model can read. Rows are paged backwards by (created_at, id) and the read stops at the checkpoint or once the budget is full, so a long session is never read whole. Kept turns stay contiguous, the newest turn is kept even when it alone exceeds the budget (compaction splits it), and a turn cut by the read is left out rather than replayed without its original question. Agent mode no longer reads history_turns: AgentConfig.HistoryTurns is removed, the editor hides the input in smart-reasoning mode and explains the automatic behavior, and the smart-reasoning builtins drop the setting. Quick-answer (KnowledgeQA) keeps its turn cap since it has no compaction. * Revert "feat(agent): size agent history by tokens instead of turn count" This reverts commit d05fb6e5f1f161813a88e9127609f7a059f38f12. Loading history up to the compaction threshold lets the loader drop the oldest turns before compaction can trigger: whenever a single turn's replay is larger than the system prompt plus the new question, the trimmed history stays under the threshold, nothing is summarized, and the session degrades into a large sliding window that never gets a checkpoint. A turn-by-turn simulation of LoadAgentHistory with the real compactor showed zero compactions over 60 turns in those cases. Keep the persisted checkpoints with the HistoryTurns cap for now; token budgeted history returns in a separate change with a budget that leaves the overflow to compaction.
2026-09-18 12:38:56 +00:00
)
if err != nil {
// The previous summary is still the best record of everything
// before this span, so the archive is appended to it rather than
// replacing it.
feat(agent): size agent history by the window and calibrate token estimates (#3413) * feat(agent): size agent history by the window and calibrate token estimates Agent history was capped at history_turns (default 5) because compaction could not survive a turn. With checkpoints persisted, load history by tokens instead, and let compaction bound the session. Budget. The loader drops the oldest turns that do not fit, and what it drops is lost: neither replayed nor summarized. A budget equal to the compaction threshold (the earlier attempt, since reverted) let the loader trim first, so whenever one turn was larger than the system prompt plus the new question the request never crossed the threshold; nothing was summarized and the session became a sliding window with no checkpoint. agent.HistoryTokenBudget is now the whole window: overflow reaches the first round's compaction, which summarizes it into a new checkpoint. A turn-by-turn regression test drives the real loader, budget and compactor and fails as soon as a stored turn after the checkpoint is missing from the loaded history; restoring the old budget fails it. Summarizer input. History can now reach the window, so the part being summarized can outgrow one request. An overflowing request degrades to a raw archive that is never persisted, so every later turn would fail the same way. Prepare keeps the newest messages that fit, the prompt states how many were left out, and file paths still come from all of them. Calibration. cl100k counts Chinese at about a token a character where Qwen and DeepSeek spend about 0.6. The estimator now carries a scale (clamped to 0.5-1.5, text only), learned from consecutive requests in a turn: they share tools, system prompt and earlier messages, so the provider's growth between them prices exactly the appended messages, without mixing in how a provider renders tool schemas. The turn's scale is stored on its usage (context_token_scale); the next turn's loader prices history with it and hands it to the engine. Loading, the first compaction check and compaction itself share one estimator, so they agree; calibrating only the trigger would let the loader drop turns again, which the regression test covers. Also: history is priced as the engine sends it (redacted KB/Wiki results cost one line); a checkpoint older than the rows read is matched by the assistant rows' (created_at, id) order; a read ending on a turn's question keeps that turn; a compaction discarded for freeing under 5% still persists its checkpoint; a checkpoint write matching no row is an error; a partial index backs the newest-checkpoint lookup. Agent mode no longer reads history_turns: the field leaves AgentConfig, the editor hides it in smart-reasoning mode, and quick-answer keeps its turn cap. * fix(agent): address review of window-sized history loading Summarization. The summarizer call had a fixed 60s total timeout. With history loaded up to the window, a request could carry ~175k tokens and be cut off while prefilling or writing normally; the degraded result left no checkpoint, so the next turn reloaded the same history and failed the same way. Summarization now streams and is cancelled only after no output for the engine's stall timeout (120s by default, LLMCallTimeout overrides), with the overall ceiling left to the transport, as for the engine's own rounds and as in Codex and Pi. A stopped turn is not retried. When the summarizer still fails, the raw archive is persisted as a checkpoint marked degraded so the loop is broken, and the next compaction refines it as the previous summary. The archive is held to the summary budget, newest messages first, so a degraded compaction always frees room. Loading. The loader priced turns as sent but returned and held them as stored, so wiki pages stored in full and sent as one line could pile up in memory. It now returns the as-sent history and releases each turn's stored rows once replayed, keeping about a page of rows at a time. Index. The partial checkpoint index is replaced by a composite (session_id, created_at DESC, id DESC) index serving the backwards page, the newest-checkpoint lookup and the recent-messages reads. It is built with CREATE INDEX CONCURRENTLY so writes to messages are not blocked; the migration holds that single statement, since a multi-statement query runs as an implicit transaction. A PostgreSQL integration test, skipped without WEKNORA_MIGRATION_TEST_POSTGRES_DSN, applies the chain, runs 000106 down and up through golang-migrate, and checks both queries use the index without a sort; the SQLite migration test checks the same plans. Calibration. It no longer waits for a total token count, and a usage with only a scale is persisted. A turn that measures nothing carries forward the scale it started from, so the newest turn always has the latest one.
2026-09-18 14:51:31 +00:00
return joinNonEmpty(p.PreviousSummary,
rawArchive(p.MessagesToSummarize, c.settings.summaryBudget(), c.estimator)), true
}
feat(agent): persist compaction checkpoints across turns (#3407) * feat(agent): persist compaction checkpoints across turns Agent compaction only lived inside the turn that ran it: the summary was discarded at turn end and LoadAgentHistory rebuilt raw history from the messages table, so every later turn past the threshold paid for another summarization of nearly the same history. A compaction whose history summary ends exactly on a stored turn is now written onto that turn's assistant message (messages.context_checkpoint). LoadAgentHistory starts from the newest checkpoint: the summary replaces that turn and everything before it, and later turns are replayed verbatim. The compactor already treats a leading summary as the previous summary, so checkpoints fold forward incrementally. History messages carry their turn's assistant message ID (chat.Message TurnID, engine-internal) so compaction can tell whether its cut lands on a stored-turn boundary. Nothing is persisted when the cut ends inside a stored turn, covers only the live turn, or the history summary degraded to a raw archive; a split turn's prefix summary is never persisted because that turn is replayed whole next time. Writes are column-scoped and best-effort, and a failed lookup falls back to history without a checkpoint. Storing the checkpoint on the covered turn keeps the boundary implicit, so session forks copy it with the turn and deleting the turn drops it. The HistoryTurns cap still applies, now to the turns after the checkpoint. * test(skill): wait for the background install in the name-conflict test InstallSkill queues the install on a goroutine, and the fixture row already starts at installing, so reading the status right after the call raced the mock install and failed whenever it landed on ready first. Wait for the run to finish on the reused row instead, as the other install tests do. * feat(agent): size agent history by tokens instead of turn count Agent history was capped at history_turns (default 5) because every turn used to rebuild raw history and compaction could not persist. With compaction checkpoints persisted, the cap is no longer what keeps a session inside the window, and it threw away context that would have fit. LoadAgentHistory now loads the newest checkpoint summary plus the newest turns after it that fit a token budget: the run's compaction threshold (agent.HistoryTokenBudget, the window less the reply reserve). History that large already triggers the first round's compaction, which persists a new checkpoint, so compaction rather than a turn count bounds the session. Loading more would only hand that compaction a summarizer input larger than the model can read. Rows are paged backwards by (created_at, id) and the read stops at the checkpoint or once the budget is full, so a long session is never read whole. Kept turns stay contiguous, the newest turn is kept even when it alone exceeds the budget (compaction splits it), and a turn cut by the read is left out rather than replayed without its original question. Agent mode no longer reads history_turns: AgentConfig.HistoryTurns is removed, the editor hides the input in smart-reasoning mode and explains the automatic behavior, and the smart-reasoning builtins drop the setting. Quick-answer (KnowledgeQA) keeps its turn cap since it has no compaction. * Revert "feat(agent): size agent history by tokens instead of turn count" This reverts commit d05fb6e5f1f161813a88e9127609f7a059f38f12. Loading history up to the compaction threshold lets the loader drop the oldest turns before compaction can trigger: whenever a single turn's replay is larger than the system prompt plus the new question, the trimmed history stays under the threshold, nothing is summarized, and the session degrades into a large sliding window that never gets a checkpoint. A turn-by-turn simulation of LoadAgentHistory with the real compactor showed zero compactions over 60 turns in those cases. Keep the persisted checkpoints with the HistoryTurns cap for now; token budgeted history returns in a separate change with a budget that leaves the overflow to compaction.
2026-09-18 12:38:56 +00:00
return text, false
}
feat(agent): persist compaction checkpoints across turns (#3407) * feat(agent): persist compaction checkpoints across turns Agent compaction only lived inside the turn that ran it: the summary was discarded at turn end and LoadAgentHistory rebuilt raw history from the messages table, so every later turn past the threshold paid for another summarization of nearly the same history. A compaction whose history summary ends exactly on a stored turn is now written onto that turn's assistant message (messages.context_checkpoint). LoadAgentHistory starts from the newest checkpoint: the summary replaces that turn and everything before it, and later turns are replayed verbatim. The compactor already treats a leading summary as the previous summary, so checkpoints fold forward incrementally. History messages carry their turn's assistant message ID (chat.Message TurnID, engine-internal) so compaction can tell whether its cut lands on a stored-turn boundary. Nothing is persisted when the cut ends inside a stored turn, covers only the live turn, or the history summary degraded to a raw archive; a split turn's prefix summary is never persisted because that turn is replayed whole next time. Writes are column-scoped and best-effort, and a failed lookup falls back to history without a checkpoint. Storing the checkpoint on the covered turn keeps the boundary implicit, so session forks copy it with the turn and deleting the turn drops it. The HistoryTurns cap still applies, now to the turns after the checkpoint. * test(skill): wait for the background install in the name-conflict test InstallSkill queues the install on a goroutine, and the fixture row already starts at installing, so reading the status right after the call raced the mock install and failed whenever it landed on ready first. Wait for the run to finish on the reused row instead, as the other install tests do. * feat(agent): size agent history by tokens instead of turn count Agent history was capped at history_turns (default 5) because every turn used to rebuild raw history and compaction could not persist. With compaction checkpoints persisted, the cap is no longer what keeps a session inside the window, and it threw away context that would have fit. LoadAgentHistory now loads the newest checkpoint summary plus the newest turns after it that fit a token budget: the run's compaction threshold (agent.HistoryTokenBudget, the window less the reply reserve). History that large already triggers the first round's compaction, which persists a new checkpoint, so compaction rather than a turn count bounds the session. Loading more would only hand that compaction a summarizer input larger than the model can read. Rows are paged backwards by (created_at, id) and the read stops at the checkpoint or once the budget is full, so a long session is never read whole. Kept turns stay contiguous, the newest turn is kept even when it alone exceeds the budget (compaction splits it), and a turn cut by the read is left out rather than replayed without its original question. Agent mode no longer reads history_turns: AgentConfig.HistoryTurns is removed, the editor hides the input in smart-reasoning mode and explains the automatic behavior, and the smart-reasoning builtins drop the setting. Quick-answer (KnowledgeQA) keeps its turn cap since it has no compaction. * Revert "feat(agent): size agent history by tokens instead of turn count" This reverts commit d05fb6e5f1f161813a88e9127609f7a059f38f12. Loading history up to the compaction threshold lets the loader drop the oldest turns before compaction can trigger: whenever a single turn's replay is larger than the system prompt plus the new question, the trimmed history stays under the threshold, nothing is summarized, and the session degrades into a large sliding window that never gets a checkpoint. A turn-by-turn simulation of LoadAgentHistory with the real compactor showed zero compactions over 60 turns in those cases. Keep the persisted checkpoints with the HistoryTurns cap for now; token budgeted history returns in a separate change with a budget that leaves the overflow to compaction.
2026-09-18 12:38:56 +00:00
// appendTurnPrefix adds the summary of a split turn's discarded head, so the
// retained tail still has its originating request.
func (c *Compactor) appendTurnPrefix(ctx context.Context, p *Preparation, history string) (string, bool) {
if !p.IsSplitTurn || len(p.TurnPrefixMessages) == 0 {
return history, false
}
degraded := false
prefix, err := c.summarize(
feat(agent): size agent history by the window and calibrate token estimates (#3413) * feat(agent): size agent history by the window and calibrate token estimates Agent history was capped at history_turns (default 5) because compaction could not survive a turn. With checkpoints persisted, load history by tokens instead, and let compaction bound the session. Budget. The loader drops the oldest turns that do not fit, and what it drops is lost: neither replayed nor summarized. A budget equal to the compaction threshold (the earlier attempt, since reverted) let the loader trim first, so whenever one turn was larger than the system prompt plus the new question the request never crossed the threshold; nothing was summarized and the session became a sliding window with no checkpoint. agent.HistoryTokenBudget is now the whole window: overflow reaches the first round's compaction, which summarizes it into a new checkpoint. A turn-by-turn regression test drives the real loader, budget and compactor and fails as soon as a stored turn after the checkpoint is missing from the loaded history; restoring the old budget fails it. Summarizer input. History can now reach the window, so the part being summarized can outgrow one request. An overflowing request degrades to a raw archive that is never persisted, so every later turn would fail the same way. Prepare keeps the newest messages that fit, the prompt states how many were left out, and file paths still come from all of them. Calibration. cl100k counts Chinese at about a token a character where Qwen and DeepSeek spend about 0.6. The estimator now carries a scale (clamped to 0.5-1.5, text only), learned from consecutive requests in a turn: they share tools, system prompt and earlier messages, so the provider's growth between them prices exactly the appended messages, without mixing in how a provider renders tool schemas. The turn's scale is stored on its usage (context_token_scale); the next turn's loader prices history with it and hands it to the engine. Loading, the first compaction check and compaction itself share one estimator, so they agree; calibrating only the trigger would let the loader drop turns again, which the regression test covers. Also: history is priced as the engine sends it (redacted KB/Wiki results cost one line); a checkpoint older than the rows read is matched by the assistant rows' (created_at, id) order; a read ending on a turn's question keeps that turn; a compaction discarded for freeing under 5% still persists its checkpoint; a checkpoint write matching no row is an error; a partial index backs the newest-checkpoint lookup. Agent mode no longer reads history_turns: the field leaves AgentConfig, the editor hides it in smart-reasoning mode, and quick-answer keeps its turn cap. * fix(agent): address review of window-sized history loading Summarization. The summarizer call had a fixed 60s total timeout. With history loaded up to the window, a request could carry ~175k tokens and be cut off while prefilling or writing normally; the degraded result left no checkpoint, so the next turn reloaded the same history and failed the same way. Summarization now streams and is cancelled only after no output for the engine's stall timeout (120s by default, LLMCallTimeout overrides), with the overall ceiling left to the transport, as for the engine's own rounds and as in Codex and Pi. A stopped turn is not retried. When the summarizer still fails, the raw archive is persisted as a checkpoint marked degraded so the loop is broken, and the next compaction refines it as the previous summary. The archive is held to the summary budget, newest messages first, so a degraded compaction always frees room. Loading. The loader priced turns as sent but returned and held them as stored, so wiki pages stored in full and sent as one line could pile up in memory. It now returns the as-sent history and releases each turn's stored rows once replayed, keeping about a page of rows at a time. Index. The partial checkpoint index is replaced by a composite (session_id, created_at DESC, id DESC) index serving the backwards page, the newest-checkpoint lookup and the recent-messages reads. It is built with CREATE INDEX CONCURRENTLY so writes to messages are not blocked; the migration holds that single statement, since a multi-statement query runs as an implicit transaction. A PostgreSQL integration test, skipped without WEKNORA_MIGRATION_TEST_POSTGRES_DSN, applies the chain, runs 000106 down and up through golang-migrate, and checks both queries use the index without a sort; the SQLite migration test checks the same plans. Calibration. It no longer waits for a total token count, and a usage with only a scale is persisted. A turn that measures nothing carries forward the scale it started from, so the newest turn always has the latest one.
2026-09-18 14:51:31 +00:00
ctx, p.TurnPrefixMessages, p.OmittedTurnPrefix, "", turnPrefixInstructions, c.settings.turnPrefixBudget(),
feat(agent): persist compaction checkpoints across turns (#3407) * feat(agent): persist compaction checkpoints across turns Agent compaction only lived inside the turn that ran it: the summary was discarded at turn end and LoadAgentHistory rebuilt raw history from the messages table, so every later turn past the threshold paid for another summarization of nearly the same history. A compaction whose history summary ends exactly on a stored turn is now written onto that turn's assistant message (messages.context_checkpoint). LoadAgentHistory starts from the newest checkpoint: the summary replaces that turn and everything before it, and later turns are replayed verbatim. The compactor already treats a leading summary as the previous summary, so checkpoints fold forward incrementally. History messages carry their turn's assistant message ID (chat.Message TurnID, engine-internal) so compaction can tell whether its cut lands on a stored-turn boundary. Nothing is persisted when the cut ends inside a stored turn, covers only the live turn, or the history summary degraded to a raw archive; a split turn's prefix summary is never persisted because that turn is replayed whole next time. Writes are column-scoped and best-effort, and a failed lookup falls back to history without a checkpoint. Storing the checkpoint on the covered turn keeps the boundary implicit, so session forks copy it with the turn and deleting the turn drops it. The HistoryTurns cap still applies, now to the turns after the checkpoint. * test(skill): wait for the background install in the name-conflict test InstallSkill queues the install on a goroutine, and the fixture row already starts at installing, so reading the status right after the call raced the mock install and failed whenever it landed on ready first. Wait for the run to finish on the reused row instead, as the other install tests do. * feat(agent): size agent history by tokens instead of turn count Agent history was capped at history_turns (default 5) because every turn used to rebuild raw history and compaction could not persist. With compaction checkpoints persisted, the cap is no longer what keeps a session inside the window, and it threw away context that would have fit. LoadAgentHistory now loads the newest checkpoint summary plus the newest turns after it that fit a token budget: the run's compaction threshold (agent.HistoryTokenBudget, the window less the reply reserve). History that large already triggers the first round's compaction, which persists a new checkpoint, so compaction rather than a turn count bounds the session. Loading more would only hand that compaction a summarizer input larger than the model can read. Rows are paged backwards by (created_at, id) and the read stops at the checkpoint or once the budget is full, so a long session is never read whole. Kept turns stay contiguous, the newest turn is kept even when it alone exceeds the budget (compaction splits it), and a turn cut by the read is left out rather than replayed without its original question. Agent mode no longer reads history_turns: AgentConfig.HistoryTurns is removed, the editor hides the input in smart-reasoning mode and explains the automatic behavior, and the smart-reasoning builtins drop the setting. Quick-answer (KnowledgeQA) keeps its turn cap since it has no compaction. * Revert "feat(agent): size agent history by tokens instead of turn count" This reverts commit d05fb6e5f1f161813a88e9127609f7a059f38f12. Loading history up to the compaction threshold lets the loader drop the oldest turns before compaction can trigger: whenever a single turn's replay is larger than the system prompt plus the new question, the trimmed history stays under the threshold, nothing is summarized, and the session degrades into a large sliding window that never gets a checkpoint. A turn-by-turn simulation of LoadAgentHistory with the real compactor showed zero compactions over 60 turns in those cases. Keep the persisted checkpoints with the HistoryTurns cap for now; token budgeted history returns in a separate change with a budget that leaves the overflow to compaction.
2026-09-18 12:38:56 +00:00
)
if err != nil {
degraded = true
feat(agent): size agent history by the window and calibrate token estimates (#3413) * feat(agent): size agent history by the window and calibrate token estimates Agent history was capped at history_turns (default 5) because compaction could not survive a turn. With checkpoints persisted, load history by tokens instead, and let compaction bound the session. Budget. The loader drops the oldest turns that do not fit, and what it drops is lost: neither replayed nor summarized. A budget equal to the compaction threshold (the earlier attempt, since reverted) let the loader trim first, so whenever one turn was larger than the system prompt plus the new question the request never crossed the threshold; nothing was summarized and the session became a sliding window with no checkpoint. agent.HistoryTokenBudget is now the whole window: overflow reaches the first round's compaction, which summarizes it into a new checkpoint. A turn-by-turn regression test drives the real loader, budget and compactor and fails as soon as a stored turn after the checkpoint is missing from the loaded history; restoring the old budget fails it. Summarizer input. History can now reach the window, so the part being summarized can outgrow one request. An overflowing request degrades to a raw archive that is never persisted, so every later turn would fail the same way. Prepare keeps the newest messages that fit, the prompt states how many were left out, and file paths still come from all of them. Calibration. cl100k counts Chinese at about a token a character where Qwen and DeepSeek spend about 0.6. The estimator now carries a scale (clamped to 0.5-1.5, text only), learned from consecutive requests in a turn: they share tools, system prompt and earlier messages, so the provider's growth between them prices exactly the appended messages, without mixing in how a provider renders tool schemas. The turn's scale is stored on its usage (context_token_scale); the next turn's loader prices history with it and hands it to the engine. Loading, the first compaction check and compaction itself share one estimator, so they agree; calibrating only the trigger would let the loader drop turns again, which the regression test covers. Also: history is priced as the engine sends it (redacted KB/Wiki results cost one line); a checkpoint older than the rows read is matched by the assistant rows' (created_at, id) order; a read ending on a turn's question keeps that turn; a compaction discarded for freeing under 5% still persists its checkpoint; a checkpoint write matching no row is an error; a partial index backs the newest-checkpoint lookup. Agent mode no longer reads history_turns: the field leaves AgentConfig, the editor hides it in smart-reasoning mode, and quick-answer keeps its turn cap. * fix(agent): address review of window-sized history loading Summarization. The summarizer call had a fixed 60s total timeout. With history loaded up to the window, a request could carry ~175k tokens and be cut off while prefilling or writing normally; the degraded result left no checkpoint, so the next turn reloaded the same history and failed the same way. Summarization now streams and is cancelled only after no output for the engine's stall timeout (120s by default, LLMCallTimeout overrides), with the overall ceiling left to the transport, as for the engine's own rounds and as in Codex and Pi. A stopped turn is not retried. When the summarizer still fails, the raw archive is persisted as a checkpoint marked degraded so the loop is broken, and the next compaction refines it as the previous summary. The archive is held to the summary budget, newest messages first, so a degraded compaction always frees room. Loading. The loader priced turns as sent but returned and held them as stored, so wiki pages stored in full and sent as one line could pile up in memory. It now returns the as-sent history and releases each turn's stored rows once replayed, keeping about a page of rows at a time. Index. The partial checkpoint index is replaced by a composite (session_id, created_at DESC, id DESC) index serving the backwards page, the newest-checkpoint lookup and the recent-messages reads. It is built with CREATE INDEX CONCURRENTLY so writes to messages are not blocked; the migration holds that single statement, since a multi-statement query runs as an implicit transaction. A PostgreSQL integration test, skipped without WEKNORA_MIGRATION_TEST_POSTGRES_DSN, applies the chain, runs 000106 down and up through golang-migrate, and checks both queries use the index without a sort; the SQLite migration test checks the same plans. Calibration. It no longer waits for a total token count, and a usage with only a scale is persisted. A turn that measures nothing carries forward the scale it started from, so the newest turn always has the latest one.
2026-09-18 14:51:31 +00:00
prefix = rawArchive(p.TurnPrefixMessages, c.settings.turnPrefixBudget(), c.estimator)
feat(agent): persist compaction checkpoints across turns (#3407) * feat(agent): persist compaction checkpoints across turns Agent compaction only lived inside the turn that ran it: the summary was discarded at turn end and LoadAgentHistory rebuilt raw history from the messages table, so every later turn past the threshold paid for another summarization of nearly the same history. A compaction whose history summary ends exactly on a stored turn is now written onto that turn's assistant message (messages.context_checkpoint). LoadAgentHistory starts from the newest checkpoint: the summary replaces that turn and everything before it, and later turns are replayed verbatim. The compactor already treats a leading summary as the previous summary, so checkpoints fold forward incrementally. History messages carry their turn's assistant message ID (chat.Message TurnID, engine-internal) so compaction can tell whether its cut lands on a stored-turn boundary. Nothing is persisted when the cut ends inside a stored turn, covers only the live turn, or the history summary degraded to a raw archive; a split turn's prefix summary is never persisted because that turn is replayed whole next time. Writes are column-scoped and best-effort, and a failed lookup falls back to history without a checkpoint. Storing the checkpoint on the covered turn keeps the boundary implicit, so session forks copy it with the turn and deleting the turn drops it. The HistoryTurns cap still applies, now to the turns after the checkpoint. * test(skill): wait for the background install in the name-conflict test InstallSkill queues the install on a goroutine, and the fixture row already starts at installing, so reading the status right after the call raced the mock install and failed whenever it landed on ready first. Wait for the run to finish on the reused row instead, as the other install tests do. * feat(agent): size agent history by tokens instead of turn count Agent history was capped at history_turns (default 5) because every turn used to rebuild raw history and compaction could not persist. With compaction checkpoints persisted, the cap is no longer what keeps a session inside the window, and it threw away context that would have fit. LoadAgentHistory now loads the newest checkpoint summary plus the newest turns after it that fit a token budget: the run's compaction threshold (agent.HistoryTokenBudget, the window less the reply reserve). History that large already triggers the first round's compaction, which persists a new checkpoint, so compaction rather than a turn count bounds the session. Loading more would only hand that compaction a summarizer input larger than the model can read. Rows are paged backwards by (created_at, id) and the read stops at the checkpoint or once the budget is full, so a long session is never read whole. Kept turns stay contiguous, the newest turn is kept even when it alone exceeds the budget (compaction splits it), and a turn cut by the read is left out rather than replayed without its original question. Agent mode no longer reads history_turns: AgentConfig.HistoryTurns is removed, the editor hides the input in smart-reasoning mode and explains the automatic behavior, and the smart-reasoning builtins drop the setting. Quick-answer (KnowledgeQA) keeps its turn cap since it has no compaction. * Revert "feat(agent): size agent history by tokens instead of turn count" This reverts commit d05fb6e5f1f161813a88e9127609f7a059f38f12. Loading history up to the compaction threshold lets the loader drop the oldest turns before compaction can trigger: whenever a single turn's replay is larger than the system prompt plus the new question, the trimmed history stays under the threshold, nothing is summarized, and the session degrades into a large sliding window that never gets a checkpoint. A turn-by-turn simulation of LoadAgentHistory with the real compactor showed zero compactions over 60 turns in those cases. Keep the persisted checkpoints with the HistoryTurns cap for now; token budgeted history returns in a separate change with a budget that leaves the overflow to compaction.
2026-09-18 12:38:56 +00:00
}
if history == "" {
history = "No prior history."
}
return history + splitTurnSeparator + prefix, degraded
}
// summarize runs one summarization call with retries.
feat(agent): size agent history by the window and calibrate token estimates (#3413) * feat(agent): size agent history by the window and calibrate token estimates Agent history was capped at history_turns (default 5) because compaction could not survive a turn. With checkpoints persisted, load history by tokens instead, and let compaction bound the session. Budget. The loader drops the oldest turns that do not fit, and what it drops is lost: neither replayed nor summarized. A budget equal to the compaction threshold (the earlier attempt, since reverted) let the loader trim first, so whenever one turn was larger than the system prompt plus the new question the request never crossed the threshold; nothing was summarized and the session became a sliding window with no checkpoint. agent.HistoryTokenBudget is now the whole window: overflow reaches the first round's compaction, which summarizes it into a new checkpoint. A turn-by-turn regression test drives the real loader, budget and compactor and fails as soon as a stored turn after the checkpoint is missing from the loaded history; restoring the old budget fails it. Summarizer input. History can now reach the window, so the part being summarized can outgrow one request. An overflowing request degrades to a raw archive that is never persisted, so every later turn would fail the same way. Prepare keeps the newest messages that fit, the prompt states how many were left out, and file paths still come from all of them. Calibration. cl100k counts Chinese at about a token a character where Qwen and DeepSeek spend about 0.6. The estimator now carries a scale (clamped to 0.5-1.5, text only), learned from consecutive requests in a turn: they share tools, system prompt and earlier messages, so the provider's growth between them prices exactly the appended messages, without mixing in how a provider renders tool schemas. The turn's scale is stored on its usage (context_token_scale); the next turn's loader prices history with it and hands it to the engine. Loading, the first compaction check and compaction itself share one estimator, so they agree; calibrating only the trigger would let the loader drop turns again, which the regression test covers. Also: history is priced as the engine sends it (redacted KB/Wiki results cost one line); a checkpoint older than the rows read is matched by the assistant rows' (created_at, id) order; a read ending on a turn's question keeps that turn; a compaction discarded for freeing under 5% still persists its checkpoint; a checkpoint write matching no row is an error; a partial index backs the newest-checkpoint lookup. Agent mode no longer reads history_turns: the field leaves AgentConfig, the editor hides it in smart-reasoning mode, and quick-answer keeps its turn cap. * fix(agent): address review of window-sized history loading Summarization. The summarizer call had a fixed 60s total timeout. With history loaded up to the window, a request could carry ~175k tokens and be cut off while prefilling or writing normally; the degraded result left no checkpoint, so the next turn reloaded the same history and failed the same way. Summarization now streams and is cancelled only after no output for the engine's stall timeout (120s by default, LLMCallTimeout overrides), with the overall ceiling left to the transport, as for the engine's own rounds and as in Codex and Pi. A stopped turn is not retried. When the summarizer still fails, the raw archive is persisted as a checkpoint marked degraded so the loop is broken, and the next compaction refines it as the previous summary. The archive is held to the summary budget, newest messages first, so a degraded compaction always frees room. Loading. The loader priced turns as sent but returned and held them as stored, so wiki pages stored in full and sent as one line could pile up in memory. It now returns the as-sent history and releases each turn's stored rows once replayed, keeping about a page of rows at a time. Index. The partial checkpoint index is replaced by a composite (session_id, created_at DESC, id DESC) index serving the backwards page, the newest-checkpoint lookup and the recent-messages reads. It is built with CREATE INDEX CONCURRENTLY so writes to messages are not blocked; the migration holds that single statement, since a multi-statement query runs as an implicit transaction. A PostgreSQL integration test, skipped without WEKNORA_MIGRATION_TEST_POSTGRES_DSN, applies the chain, runs 000106 down and up through golang-migrate, and checks both queries use the index without a sort; the SQLite migration test checks the same plans. Calibration. It no longer waits for a total token count, and a usage with only a scale is persisted. A turn that measures nothing carries forward the scale it started from, so the newest turn always has the latest one.
2026-09-18 14:51:31 +00:00
//
// The call streams and is cancelled only when it stops producing output for
// the stall timeout, the rule the engine applies to its own rounds. A fixed
// total budget was wrong for exactly the calls that matter: the history being
// summarized can be most of the window, and a request that was prefilling and
// writing normally was cut off at 60 seconds, degraded, and started over on
// the next turn. The overall ceiling belongs to the provider transport.
func (c *Compactor) summarize(
ctx context.Context,
messages []chat.Message,
feat(agent): size agent history by the window and calibrate token estimates (#3413) * feat(agent): size agent history by the window and calibrate token estimates Agent history was capped at history_turns (default 5) because compaction could not survive a turn. With checkpoints persisted, load history by tokens instead, and let compaction bound the session. Budget. The loader drops the oldest turns that do not fit, and what it drops is lost: neither replayed nor summarized. A budget equal to the compaction threshold (the earlier attempt, since reverted) let the loader trim first, so whenever one turn was larger than the system prompt plus the new question the request never crossed the threshold; nothing was summarized and the session became a sliding window with no checkpoint. agent.HistoryTokenBudget is now the whole window: overflow reaches the first round's compaction, which summarizes it into a new checkpoint. A turn-by-turn regression test drives the real loader, budget and compactor and fails as soon as a stored turn after the checkpoint is missing from the loaded history; restoring the old budget fails it. Summarizer input. History can now reach the window, so the part being summarized can outgrow one request. An overflowing request degrades to a raw archive that is never persisted, so every later turn would fail the same way. Prepare keeps the newest messages that fit, the prompt states how many were left out, and file paths still come from all of them. Calibration. cl100k counts Chinese at about a token a character where Qwen and DeepSeek spend about 0.6. The estimator now carries a scale (clamped to 0.5-1.5, text only), learned from consecutive requests in a turn: they share tools, system prompt and earlier messages, so the provider's growth between them prices exactly the appended messages, without mixing in how a provider renders tool schemas. The turn's scale is stored on its usage (context_token_scale); the next turn's loader prices history with it and hands it to the engine. Loading, the first compaction check and compaction itself share one estimator, so they agree; calibrating only the trigger would let the loader drop turns again, which the regression test covers. Also: history is priced as the engine sends it (redacted KB/Wiki results cost one line); a checkpoint older than the rows read is matched by the assistant rows' (created_at, id) order; a read ending on a turn's question keeps that turn; a compaction discarded for freeing under 5% still persists its checkpoint; a checkpoint write matching no row is an error; a partial index backs the newest-checkpoint lookup. Agent mode no longer reads history_turns: the field leaves AgentConfig, the editor hides it in smart-reasoning mode, and quick-answer keeps its turn cap. * fix(agent): address review of window-sized history loading Summarization. The summarizer call had a fixed 60s total timeout. With history loaded up to the window, a request could carry ~175k tokens and be cut off while prefilling or writing normally; the degraded result left no checkpoint, so the next turn reloaded the same history and failed the same way. Summarization now streams and is cancelled only after no output for the engine's stall timeout (120s by default, LLMCallTimeout overrides), with the overall ceiling left to the transport, as for the engine's own rounds and as in Codex and Pi. A stopped turn is not retried. When the summarizer still fails, the raw archive is persisted as a checkpoint marked degraded so the loop is broken, and the next compaction refines it as the previous summary. The archive is held to the summary budget, newest messages first, so a degraded compaction always frees room. Loading. The loader priced turns as sent but returned and held them as stored, so wiki pages stored in full and sent as one line could pile up in memory. It now returns the as-sent history and releases each turn's stored rows once replayed, keeping about a page of rows at a time. Index. The partial checkpoint index is replaced by a composite (session_id, created_at DESC, id DESC) index serving the backwards page, the newest-checkpoint lookup and the recent-messages reads. It is built with CREATE INDEX CONCURRENTLY so writes to messages are not blocked; the migration holds that single statement, since a multi-statement query runs as an implicit transaction. A PostgreSQL integration test, skipped without WEKNORA_MIGRATION_TEST_POSTGRES_DSN, applies the chain, runs 000106 down and up through golang-migrate, and checks both queries use the index without a sort; the SQLite migration test checks the same plans. Calibration. It no longer waits for a total token count, and a usage with only a scale is persisted. A turn that measures nothing carries forward the scale it started from, so the newest turn always has the latest one.
2026-09-18 14:51:31 +00:00
omitted int,
previousSummary, instructions string,
maxTokens int,
) (string, error) {
feat(agent): size agent history by the window and calibrate token estimates (#3413) * feat(agent): size agent history by the window and calibrate token estimates Agent history was capped at history_turns (default 5) because compaction could not survive a turn. With checkpoints persisted, load history by tokens instead, and let compaction bound the session. Budget. The loader drops the oldest turns that do not fit, and what it drops is lost: neither replayed nor summarized. A budget equal to the compaction threshold (the earlier attempt, since reverted) let the loader trim first, so whenever one turn was larger than the system prompt plus the new question the request never crossed the threshold; nothing was summarized and the session became a sliding window with no checkpoint. agent.HistoryTokenBudget is now the whole window: overflow reaches the first round's compaction, which summarizes it into a new checkpoint. A turn-by-turn regression test drives the real loader, budget and compactor and fails as soon as a stored turn after the checkpoint is missing from the loaded history; restoring the old budget fails it. Summarizer input. History can now reach the window, so the part being summarized can outgrow one request. An overflowing request degrades to a raw archive that is never persisted, so every later turn would fail the same way. Prepare keeps the newest messages that fit, the prompt states how many were left out, and file paths still come from all of them. Calibration. cl100k counts Chinese at about a token a character where Qwen and DeepSeek spend about 0.6. The estimator now carries a scale (clamped to 0.5-1.5, text only), learned from consecutive requests in a turn: they share tools, system prompt and earlier messages, so the provider's growth between them prices exactly the appended messages, without mixing in how a provider renders tool schemas. The turn's scale is stored on its usage (context_token_scale); the next turn's loader prices history with it and hands it to the engine. Loading, the first compaction check and compaction itself share one estimator, so they agree; calibrating only the trigger would let the loader drop turns again, which the regression test covers. Also: history is priced as the engine sends it (redacted KB/Wiki results cost one line); a checkpoint older than the rows read is matched by the assistant rows' (created_at, id) order; a read ending on a turn's question keeps that turn; a compaction discarded for freeing under 5% still persists its checkpoint; a checkpoint write matching no row is an error; a partial index backs the newest-checkpoint lookup. Agent mode no longer reads history_turns: the field leaves AgentConfig, the editor hides it in smart-reasoning mode, and quick-answer keeps its turn cap. * fix(agent): address review of window-sized history loading Summarization. The summarizer call had a fixed 60s total timeout. With history loaded up to the window, a request could carry ~175k tokens and be cut off while prefilling or writing normally; the degraded result left no checkpoint, so the next turn reloaded the same history and failed the same way. Summarization now streams and is cancelled only after no output for the engine's stall timeout (120s by default, LLMCallTimeout overrides), with the overall ceiling left to the transport, as for the engine's own rounds and as in Codex and Pi. A stopped turn is not retried. When the summarizer still fails, the raw archive is persisted as a checkpoint marked degraded so the loop is broken, and the next compaction refines it as the previous summary. The archive is held to the summary budget, newest messages first, so a degraded compaction always frees room. Loading. The loader priced turns as sent but returned and held them as stored, so wiki pages stored in full and sent as one line could pile up in memory. It now returns the as-sent history and releases each turn's stored rows once replayed, keeping about a page of rows at a time. Index. The partial checkpoint index is replaced by a composite (session_id, created_at DESC, id DESC) index serving the backwards page, the newest-checkpoint lookup and the recent-messages reads. It is built with CREATE INDEX CONCURRENTLY so writes to messages are not blocked; the migration holds that single statement, since a multi-statement query runs as an implicit transaction. A PostgreSQL integration test, skipped without WEKNORA_MIGRATION_TEST_POSTGRES_DSN, applies the chain, runs 000106 down and up through golang-migrate, and checks both queries use the index without a sort; the SQLite migration test checks the same plans. Calibration. It no longer waits for a total token count, and a usage with only a scale is persisted. A turn that measures nothing carries forward the scale it started from, so the newest turn always has the latest one.
2026-09-18 14:51:31 +00:00
request := []chat.Message{
{Role: "system", Content: summarizationSystemPrompt},
{Role: "user", Content: buildSummarizationPrompt(messages, omitted, previousSummary, instructions)},
}
opts := &chat.ChatOptions{
Temperature: 0.3, // low temperature for factual summarization
MaxTokens: maxTokens,
CacheRetention: chat.CacheRetentionNone,
}
var lastErr error
for attempt := 1; attempt <= maxSummarizationAttempts; attempt++ {
feat(agent): size agent history by the window and calibrate token estimates (#3413) * feat(agent): size agent history by the window and calibrate token estimates Agent history was capped at history_turns (default 5) because compaction could not survive a turn. With checkpoints persisted, load history by tokens instead, and let compaction bound the session. Budget. The loader drops the oldest turns that do not fit, and what it drops is lost: neither replayed nor summarized. A budget equal to the compaction threshold (the earlier attempt, since reverted) let the loader trim first, so whenever one turn was larger than the system prompt plus the new question the request never crossed the threshold; nothing was summarized and the session became a sliding window with no checkpoint. agent.HistoryTokenBudget is now the whole window: overflow reaches the first round's compaction, which summarizes it into a new checkpoint. A turn-by-turn regression test drives the real loader, budget and compactor and fails as soon as a stored turn after the checkpoint is missing from the loaded history; restoring the old budget fails it. Summarizer input. History can now reach the window, so the part being summarized can outgrow one request. An overflowing request degrades to a raw archive that is never persisted, so every later turn would fail the same way. Prepare keeps the newest messages that fit, the prompt states how many were left out, and file paths still come from all of them. Calibration. cl100k counts Chinese at about a token a character where Qwen and DeepSeek spend about 0.6. The estimator now carries a scale (clamped to 0.5-1.5, text only), learned from consecutive requests in a turn: they share tools, system prompt and earlier messages, so the provider's growth between them prices exactly the appended messages, without mixing in how a provider renders tool schemas. The turn's scale is stored on its usage (context_token_scale); the next turn's loader prices history with it and hands it to the engine. Loading, the first compaction check and compaction itself share one estimator, so they agree; calibrating only the trigger would let the loader drop turns again, which the regression test covers. Also: history is priced as the engine sends it (redacted KB/Wiki results cost one line); a checkpoint older than the rows read is matched by the assistant rows' (created_at, id) order; a read ending on a turn's question keeps that turn; a compaction discarded for freeing under 5% still persists its checkpoint; a checkpoint write matching no row is an error; a partial index backs the newest-checkpoint lookup. Agent mode no longer reads history_turns: the field leaves AgentConfig, the editor hides it in smart-reasoning mode, and quick-answer keeps its turn cap. * fix(agent): address review of window-sized history loading Summarization. The summarizer call had a fixed 60s total timeout. With history loaded up to the window, a request could carry ~175k tokens and be cut off while prefilling or writing normally; the degraded result left no checkpoint, so the next turn reloaded the same history and failed the same way. Summarization now streams and is cancelled only after no output for the engine's stall timeout (120s by default, LLMCallTimeout overrides), with the overall ceiling left to the transport, as for the engine's own rounds and as in Codex and Pi. A stopped turn is not retried. When the summarizer still fails, the raw archive is persisted as a checkpoint marked degraded so the loop is broken, and the next compaction refines it as the previous summary. The archive is held to the summary budget, newest messages first, so a degraded compaction always frees room. Loading. The loader priced turns as sent but returned and held them as stored, so wiki pages stored in full and sent as one line could pile up in memory. It now returns the as-sent history and releases each turn's stored rows once replayed, keeping about a page of rows at a time. Index. The partial checkpoint index is replaced by a composite (session_id, created_at DESC, id DESC) index serving the backwards page, the newest-checkpoint lookup and the recent-messages reads. It is built with CREATE INDEX CONCURRENTLY so writes to messages are not blocked; the migration holds that single statement, since a multi-statement query runs as an implicit transaction. A PostgreSQL integration test, skipped without WEKNORA_MIGRATION_TEST_POSTGRES_DSN, applies the chain, runs 000106 down and up through golang-migrate, and checks both queries use the index without a sort; the SQLite migration test checks the same plans. Calibration. It no longer waits for a total token count, and a usage with only a scale is persisted. A turn that measures nothing carries forward the scale it started from, so the newest turn always has the latest one.
2026-09-18 14:51:31 +00:00
content, finishReason, err := c.streamSummary(ctx, request, opts)
if err == nil {
err = validateSummary(content, finishReason)
}
if err == nil {
return strings.TrimSpace(content), nil
}
feat(agent): size agent history by the window and calibrate token estimates (#3413) * feat(agent): size agent history by the window and calibrate token estimates Agent history was capped at history_turns (default 5) because compaction could not survive a turn. With checkpoints persisted, load history by tokens instead, and let compaction bound the session. Budget. The loader drops the oldest turns that do not fit, and what it drops is lost: neither replayed nor summarized. A budget equal to the compaction threshold (the earlier attempt, since reverted) let the loader trim first, so whenever one turn was larger than the system prompt plus the new question the request never crossed the threshold; nothing was summarized and the session became a sliding window with no checkpoint. agent.HistoryTokenBudget is now the whole window: overflow reaches the first round's compaction, which summarizes it into a new checkpoint. A turn-by-turn regression test drives the real loader, budget and compactor and fails as soon as a stored turn after the checkpoint is missing from the loaded history; restoring the old budget fails it. Summarizer input. History can now reach the window, so the part being summarized can outgrow one request. An overflowing request degrades to a raw archive that is never persisted, so every later turn would fail the same way. Prepare keeps the newest messages that fit, the prompt states how many were left out, and file paths still come from all of them. Calibration. cl100k counts Chinese at about a token a character where Qwen and DeepSeek spend about 0.6. The estimator now carries a scale (clamped to 0.5-1.5, text only), learned from consecutive requests in a turn: they share tools, system prompt and earlier messages, so the provider's growth between them prices exactly the appended messages, without mixing in how a provider renders tool schemas. The turn's scale is stored on its usage (context_token_scale); the next turn's loader prices history with it and hands it to the engine. Loading, the first compaction check and compaction itself share one estimator, so they agree; calibrating only the trigger would let the loader drop turns again, which the regression test covers. Also: history is priced as the engine sends it (redacted KB/Wiki results cost one line); a checkpoint older than the rows read is matched by the assistant rows' (created_at, id) order; a read ending on a turn's question keeps that turn; a compaction discarded for freeing under 5% still persists its checkpoint; a checkpoint write matching no row is an error; a partial index backs the newest-checkpoint lookup. Agent mode no longer reads history_turns: the field leaves AgentConfig, the editor hides it in smart-reasoning mode, and quick-answer keeps its turn cap. * fix(agent): address review of window-sized history loading Summarization. The summarizer call had a fixed 60s total timeout. With history loaded up to the window, a request could carry ~175k tokens and be cut off while prefilling or writing normally; the degraded result left no checkpoint, so the next turn reloaded the same history and failed the same way. Summarization now streams and is cancelled only after no output for the engine's stall timeout (120s by default, LLMCallTimeout overrides), with the overall ceiling left to the transport, as for the engine's own rounds and as in Codex and Pi. A stopped turn is not retried. When the summarizer still fails, the raw archive is persisted as a checkpoint marked degraded so the loop is broken, and the next compaction refines it as the previous summary. The archive is held to the summary budget, newest messages first, so a degraded compaction always frees room. Loading. The loader priced turns as sent but returned and held them as stored, so wiki pages stored in full and sent as one line could pile up in memory. It now returns the as-sent history and releases each turn's stored rows once replayed, keeping about a page of rows at a time. Index. The partial checkpoint index is replaced by a composite (session_id, created_at DESC, id DESC) index serving the backwards page, the newest-checkpoint lookup and the recent-messages reads. It is built with CREATE INDEX CONCURRENTLY so writes to messages are not blocked; the migration holds that single statement, since a multi-statement query runs as an implicit transaction. A PostgreSQL integration test, skipped without WEKNORA_MIGRATION_TEST_POSTGRES_DSN, applies the chain, runs 000106 down and up through golang-migrate, and checks both queries use the index without a sort; the SQLite migration test checks the same plans. Calibration. It no longer waits for a total token count, and a usage with only a scale is persisted. A turn that measures nothing carries forward the scale it started from, so the newest turn always has the latest one.
2026-09-18 14:51:31 +00:00
lastErr = err
if ctx.Err() != nil {
break // the turn itself was stopped; another attempt cannot help
}
}
return "", fmt.Errorf("summarization failed after %d attempts: %w",
maxSummarizationAttempts, lastErr)
}
feat(agent): size agent history by the window and calibrate token estimates (#3413) * feat(agent): size agent history by the window and calibrate token estimates Agent history was capped at history_turns (default 5) because compaction could not survive a turn. With checkpoints persisted, load history by tokens instead, and let compaction bound the session. Budget. The loader drops the oldest turns that do not fit, and what it drops is lost: neither replayed nor summarized. A budget equal to the compaction threshold (the earlier attempt, since reverted) let the loader trim first, so whenever one turn was larger than the system prompt plus the new question the request never crossed the threshold; nothing was summarized and the session became a sliding window with no checkpoint. agent.HistoryTokenBudget is now the whole window: overflow reaches the first round's compaction, which summarizes it into a new checkpoint. A turn-by-turn regression test drives the real loader, budget and compactor and fails as soon as a stored turn after the checkpoint is missing from the loaded history; restoring the old budget fails it. Summarizer input. History can now reach the window, so the part being summarized can outgrow one request. An overflowing request degrades to a raw archive that is never persisted, so every later turn would fail the same way. Prepare keeps the newest messages that fit, the prompt states how many were left out, and file paths still come from all of them. Calibration. cl100k counts Chinese at about a token a character where Qwen and DeepSeek spend about 0.6. The estimator now carries a scale (clamped to 0.5-1.5, text only), learned from consecutive requests in a turn: they share tools, system prompt and earlier messages, so the provider's growth between them prices exactly the appended messages, without mixing in how a provider renders tool schemas. The turn's scale is stored on its usage (context_token_scale); the next turn's loader prices history with it and hands it to the engine. Loading, the first compaction check and compaction itself share one estimator, so they agree; calibrating only the trigger would let the loader drop turns again, which the regression test covers. Also: history is priced as the engine sends it (redacted KB/Wiki results cost one line); a checkpoint older than the rows read is matched by the assistant rows' (created_at, id) order; a read ending on a turn's question keeps that turn; a compaction discarded for freeing under 5% still persists its checkpoint; a checkpoint write matching no row is an error; a partial index backs the newest-checkpoint lookup. Agent mode no longer reads history_turns: the field leaves AgentConfig, the editor hides it in smart-reasoning mode, and quick-answer keeps its turn cap. * fix(agent): address review of window-sized history loading Summarization. The summarizer call had a fixed 60s total timeout. With history loaded up to the window, a request could carry ~175k tokens and be cut off while prefilling or writing normally; the degraded result left no checkpoint, so the next turn reloaded the same history and failed the same way. Summarization now streams and is cancelled only after no output for the engine's stall timeout (120s by default, LLMCallTimeout overrides), with the overall ceiling left to the transport, as for the engine's own rounds and as in Codex and Pi. A stopped turn is not retried. When the summarizer still fails, the raw archive is persisted as a checkpoint marked degraded so the loop is broken, and the next compaction refines it as the previous summary. The archive is held to the summary budget, newest messages first, so a degraded compaction always frees room. Loading. The loader priced turns as sent but returned and held them as stored, so wiki pages stored in full and sent as one line could pile up in memory. It now returns the as-sent history and releases each turn's stored rows once replayed, keeping about a page of rows at a time. Index. The partial checkpoint index is replaced by a composite (session_id, created_at DESC, id DESC) index serving the backwards page, the newest-checkpoint lookup and the recent-messages reads. It is built with CREATE INDEX CONCURRENTLY so writes to messages are not blocked; the migration holds that single statement, since a multi-statement query runs as an implicit transaction. A PostgreSQL integration test, skipped without WEKNORA_MIGRATION_TEST_POSTGRES_DSN, applies the chain, runs 000106 down and up through golang-migrate, and checks both queries use the index without a sort; the SQLite migration test checks the same plans. Calibration. It no longer waits for a total token count, and a usage with only a scale is persisted. A turn that measures nothing carries forward the scale it started from, so the newest turn always has the latest one.
2026-09-18 14:51:31 +00:00
// streamSummary collects one summarization stream. Output of any kind, the
// model's reasoning included, counts as progress and resets the stall timer.
func (c *Compactor) streamSummary(
ctx context.Context, messages []chat.Message, opts *chat.ChatOptions,
) (content, finishReason string, err error) {
callCtx, cancel := context.WithCancel(types.WithLLMCallMetadata(ctx, llmCallLabel, ""))
defer cancel()
stream, err := c.chatModel.ChatStream(callCtx, messages, opts)
if err != nil {
return "", "", err
}
if stream == nil {
return "", "", errors.New("summarization stream was not opened")
}
// Anything the provider still sends after this returns is discarded, so
// its goroutine can finish once the cancelled context closes the stream.
defer func() {
go func() {
for {
if _, ok := <-stream; !ok {
return
}
}
}()
}()
timeout := c.settings.stallTimeout()
stall := time.NewTimer(timeout)
defer stall.Stop()
var sb strings.Builder
streamErr := ""
for {
select {
case <-ctx.Done():
return "", "", ctx.Err()
case <-stall.C:
return "", "", fmt.Errorf("summarization stalled: no output for %s", timeout)
case chunk, ok := <-stream:
if !ok {
if streamErr != "" {
return "", finishReason, fmt.Errorf("summarization stream error: %s", streamErr)
}
return sb.String(), finishReason, nil
}
stall.Reset(timeout)
if chunk.FinishReason != "" {
finishReason = chunk.FinishReason
}
switch chunk.ResponseType {
case types.ResponseTypeError:
streamErr = chunk.Content
case types.ResponseTypeThinking:
// progress, but not part of the summary
default:
sb.WriteString(chunk.Content)
}
}
}
}
// validateSummary rejects responses that cannot serve as a checkpoint.
//
// The length stop is the one worth spelling out: a summary cut off by the token
// cap reads like a valid summary but silently ends mid-section, and every later
// round inherits that truncation as its only memory of the dropped history.
// A partial summary is a failure: it cannot serve as a checkpoint.
feat(agent): size agent history by the window and calibrate token estimates (#3413) * feat(agent): size agent history by the window and calibrate token estimates Agent history was capped at history_turns (default 5) because compaction could not survive a turn. With checkpoints persisted, load history by tokens instead, and let compaction bound the session. Budget. The loader drops the oldest turns that do not fit, and what it drops is lost: neither replayed nor summarized. A budget equal to the compaction threshold (the earlier attempt, since reverted) let the loader trim first, so whenever one turn was larger than the system prompt plus the new question the request never crossed the threshold; nothing was summarized and the session became a sliding window with no checkpoint. agent.HistoryTokenBudget is now the whole window: overflow reaches the first round's compaction, which summarizes it into a new checkpoint. A turn-by-turn regression test drives the real loader, budget and compactor and fails as soon as a stored turn after the checkpoint is missing from the loaded history; restoring the old budget fails it. Summarizer input. History can now reach the window, so the part being summarized can outgrow one request. An overflowing request degrades to a raw archive that is never persisted, so every later turn would fail the same way. Prepare keeps the newest messages that fit, the prompt states how many were left out, and file paths still come from all of them. Calibration. cl100k counts Chinese at about a token a character where Qwen and DeepSeek spend about 0.6. The estimator now carries a scale (clamped to 0.5-1.5, text only), learned from consecutive requests in a turn: they share tools, system prompt and earlier messages, so the provider's growth between them prices exactly the appended messages, without mixing in how a provider renders tool schemas. The turn's scale is stored on its usage (context_token_scale); the next turn's loader prices history with it and hands it to the engine. Loading, the first compaction check and compaction itself share one estimator, so they agree; calibrating only the trigger would let the loader drop turns again, which the regression test covers. Also: history is priced as the engine sends it (redacted KB/Wiki results cost one line); a checkpoint older than the rows read is matched by the assistant rows' (created_at, id) order; a read ending on a turn's question keeps that turn; a compaction discarded for freeing under 5% still persists its checkpoint; a checkpoint write matching no row is an error; a partial index backs the newest-checkpoint lookup. Agent mode no longer reads history_turns: the field leaves AgentConfig, the editor hides it in smart-reasoning mode, and quick-answer keeps its turn cap. * fix(agent): address review of window-sized history loading Summarization. The summarizer call had a fixed 60s total timeout. With history loaded up to the window, a request could carry ~175k tokens and be cut off while prefilling or writing normally; the degraded result left no checkpoint, so the next turn reloaded the same history and failed the same way. Summarization now streams and is cancelled only after no output for the engine's stall timeout (120s by default, LLMCallTimeout overrides), with the overall ceiling left to the transport, as for the engine's own rounds and as in Codex and Pi. A stopped turn is not retried. When the summarizer still fails, the raw archive is persisted as a checkpoint marked degraded so the loop is broken, and the next compaction refines it as the previous summary. The archive is held to the summary budget, newest messages first, so a degraded compaction always frees room. Loading. The loader priced turns as sent but returned and held them as stored, so wiki pages stored in full and sent as one line could pile up in memory. It now returns the as-sent history and releases each turn's stored rows once replayed, keeping about a page of rows at a time. Index. The partial checkpoint index is replaced by a composite (session_id, created_at DESC, id DESC) index serving the backwards page, the newest-checkpoint lookup and the recent-messages reads. It is built with CREATE INDEX CONCURRENTLY so writes to messages are not blocked; the migration holds that single statement, since a multi-statement query runs as an implicit transaction. A PostgreSQL integration test, skipped without WEKNORA_MIGRATION_TEST_POSTGRES_DSN, applies the chain, runs 000106 down and up through golang-migrate, and checks both queries use the index without a sort; the SQLite migration test checks the same plans. Calibration. It no longer waits for a total token count, and a usage with only a scale is persisted. A turn that measures nothing carries forward the scale it started from, so the newest turn always has the latest one.
2026-09-18 14:51:31 +00:00
func validateSummary(content, finishReason string) error {
if strings.TrimSpace(content) == "" {
return errors.New("empty response from LLM")
}
feat(agent): size agent history by the window and calibrate token estimates (#3413) * feat(agent): size agent history by the window and calibrate token estimates Agent history was capped at history_turns (default 5) because compaction could not survive a turn. With checkpoints persisted, load history by tokens instead, and let compaction bound the session. Budget. The loader drops the oldest turns that do not fit, and what it drops is lost: neither replayed nor summarized. A budget equal to the compaction threshold (the earlier attempt, since reverted) let the loader trim first, so whenever one turn was larger than the system prompt plus the new question the request never crossed the threshold; nothing was summarized and the session became a sliding window with no checkpoint. agent.HistoryTokenBudget is now the whole window: overflow reaches the first round's compaction, which summarizes it into a new checkpoint. A turn-by-turn regression test drives the real loader, budget and compactor and fails as soon as a stored turn after the checkpoint is missing from the loaded history; restoring the old budget fails it. Summarizer input. History can now reach the window, so the part being summarized can outgrow one request. An overflowing request degrades to a raw archive that is never persisted, so every later turn would fail the same way. Prepare keeps the newest messages that fit, the prompt states how many were left out, and file paths still come from all of them. Calibration. cl100k counts Chinese at about a token a character where Qwen and DeepSeek spend about 0.6. The estimator now carries a scale (clamped to 0.5-1.5, text only), learned from consecutive requests in a turn: they share tools, system prompt and earlier messages, so the provider's growth between them prices exactly the appended messages, without mixing in how a provider renders tool schemas. The turn's scale is stored on its usage (context_token_scale); the next turn's loader prices history with it and hands it to the engine. Loading, the first compaction check and compaction itself share one estimator, so they agree; calibrating only the trigger would let the loader drop turns again, which the regression test covers. Also: history is priced as the engine sends it (redacted KB/Wiki results cost one line); a checkpoint older than the rows read is matched by the assistant rows' (created_at, id) order; a read ending on a turn's question keeps that turn; a compaction discarded for freeing under 5% still persists its checkpoint; a checkpoint write matching no row is an error; a partial index backs the newest-checkpoint lookup. Agent mode no longer reads history_turns: the field leaves AgentConfig, the editor hides it in smart-reasoning mode, and quick-answer keeps its turn cap. * fix(agent): address review of window-sized history loading Summarization. The summarizer call had a fixed 60s total timeout. With history loaded up to the window, a request could carry ~175k tokens and be cut off while prefilling or writing normally; the degraded result left no checkpoint, so the next turn reloaded the same history and failed the same way. Summarization now streams and is cancelled only after no output for the engine's stall timeout (120s by default, LLMCallTimeout overrides), with the overall ceiling left to the transport, as for the engine's own rounds and as in Codex and Pi. A stopped turn is not retried. When the summarizer still fails, the raw archive is persisted as a checkpoint marked degraded so the loop is broken, and the next compaction refines it as the previous summary. The archive is held to the summary budget, newest messages first, so a degraded compaction always frees room. Loading. The loader priced turns as sent but returned and held them as stored, so wiki pages stored in full and sent as one line could pile up in memory. It now returns the as-sent history and releases each turn's stored rows once replayed, keeping about a page of rows at a time. Index. The partial checkpoint index is replaced by a composite (session_id, created_at DESC, id DESC) index serving the backwards page, the newest-checkpoint lookup and the recent-messages reads. It is built with CREATE INDEX CONCURRENTLY so writes to messages are not blocked; the migration holds that single statement, since a multi-statement query runs as an implicit transaction. A PostgreSQL integration test, skipped without WEKNORA_MIGRATION_TEST_POSTGRES_DSN, applies the chain, runs 000106 down and up through golang-migrate, and checks both queries use the index without a sort; the SQLite migration test checks the same plans. Calibration. It no longer waits for a total token count, and a usage with only a scale is persisted. A turn that measures nothing carries forward the scale it started from, so the newest turn always has the latest one.
2026-09-18 14:51:31 +00:00
switch strings.ToLower(strings.TrimSpace(finishReason)) {
case "length", "max_tokens", "max_output_tokens":
return errors.New("generation hit the token cap and the summary is incomplete")
}
return nil
}
// buildSummarizationPrompt wraps the transcript in a tag and puts the
// instructions last, so the summarizer cannot mistake conversation text for
// its own instructions.
feat(agent): size agent history by the window and calibrate token estimates (#3413) * feat(agent): size agent history by the window and calibrate token estimates Agent history was capped at history_turns (default 5) because compaction could not survive a turn. With checkpoints persisted, load history by tokens instead, and let compaction bound the session. Budget. The loader drops the oldest turns that do not fit, and what it drops is lost: neither replayed nor summarized. A budget equal to the compaction threshold (the earlier attempt, since reverted) let the loader trim first, so whenever one turn was larger than the system prompt plus the new question the request never crossed the threshold; nothing was summarized and the session became a sliding window with no checkpoint. agent.HistoryTokenBudget is now the whole window: overflow reaches the first round's compaction, which summarizes it into a new checkpoint. A turn-by-turn regression test drives the real loader, budget and compactor and fails as soon as a stored turn after the checkpoint is missing from the loaded history; restoring the old budget fails it. Summarizer input. History can now reach the window, so the part being summarized can outgrow one request. An overflowing request degrades to a raw archive that is never persisted, so every later turn would fail the same way. Prepare keeps the newest messages that fit, the prompt states how many were left out, and file paths still come from all of them. Calibration. cl100k counts Chinese at about a token a character where Qwen and DeepSeek spend about 0.6. The estimator now carries a scale (clamped to 0.5-1.5, text only), learned from consecutive requests in a turn: they share tools, system prompt and earlier messages, so the provider's growth between them prices exactly the appended messages, without mixing in how a provider renders tool schemas. The turn's scale is stored on its usage (context_token_scale); the next turn's loader prices history with it and hands it to the engine. Loading, the first compaction check and compaction itself share one estimator, so they agree; calibrating only the trigger would let the loader drop turns again, which the regression test covers. Also: history is priced as the engine sends it (redacted KB/Wiki results cost one line); a checkpoint older than the rows read is matched by the assistant rows' (created_at, id) order; a read ending on a turn's question keeps that turn; a compaction discarded for freeing under 5% still persists its checkpoint; a checkpoint write matching no row is an error; a partial index backs the newest-checkpoint lookup. Agent mode no longer reads history_turns: the field leaves AgentConfig, the editor hides it in smart-reasoning mode, and quick-answer keeps its turn cap. * fix(agent): address review of window-sized history loading Summarization. The summarizer call had a fixed 60s total timeout. With history loaded up to the window, a request could carry ~175k tokens and be cut off while prefilling or writing normally; the degraded result left no checkpoint, so the next turn reloaded the same history and failed the same way. Summarization now streams and is cancelled only after no output for the engine's stall timeout (120s by default, LLMCallTimeout overrides), with the overall ceiling left to the transport, as for the engine's own rounds and as in Codex and Pi. A stopped turn is not retried. When the summarizer still fails, the raw archive is persisted as a checkpoint marked degraded so the loop is broken, and the next compaction refines it as the previous summary. The archive is held to the summary budget, newest messages first, so a degraded compaction always frees room. Loading. The loader priced turns as sent but returned and held them as stored, so wiki pages stored in full and sent as one line could pile up in memory. It now returns the as-sent history and releases each turn's stored rows once replayed, keeping about a page of rows at a time. Index. The partial checkpoint index is replaced by a composite (session_id, created_at DESC, id DESC) index serving the backwards page, the newest-checkpoint lookup and the recent-messages reads. It is built with CREATE INDEX CONCURRENTLY so writes to messages are not blocked; the migration holds that single statement, since a multi-statement query runs as an implicit transaction. A PostgreSQL integration test, skipped without WEKNORA_MIGRATION_TEST_POSTGRES_DSN, applies the chain, runs 000106 down and up through golang-migrate, and checks both queries use the index without a sort; the SQLite migration test checks the same plans. Calibration. It no longer waits for a total token count, and a usage with only a scale is persisted. A turn that measures nothing carries forward the scale it started from, so the newest turn always has the latest one.
2026-09-18 14:51:31 +00:00
func buildSummarizationPrompt(messages []chat.Message, omitted int, previousSummary, instructions string) string {
var sb strings.Builder
sb.WriteString("<conversation>\n")
feat(agent): size agent history by the window and calibrate token estimates (#3413) * feat(agent): size agent history by the window and calibrate token estimates Agent history was capped at history_turns (default 5) because compaction could not survive a turn. With checkpoints persisted, load history by tokens instead, and let compaction bound the session. Budget. The loader drops the oldest turns that do not fit, and what it drops is lost: neither replayed nor summarized. A budget equal to the compaction threshold (the earlier attempt, since reverted) let the loader trim first, so whenever one turn was larger than the system prompt plus the new question the request never crossed the threshold; nothing was summarized and the session became a sliding window with no checkpoint. agent.HistoryTokenBudget is now the whole window: overflow reaches the first round's compaction, which summarizes it into a new checkpoint. A turn-by-turn regression test drives the real loader, budget and compactor and fails as soon as a stored turn after the checkpoint is missing from the loaded history; restoring the old budget fails it. Summarizer input. History can now reach the window, so the part being summarized can outgrow one request. An overflowing request degrades to a raw archive that is never persisted, so every later turn would fail the same way. Prepare keeps the newest messages that fit, the prompt states how many were left out, and file paths still come from all of them. Calibration. cl100k counts Chinese at about a token a character where Qwen and DeepSeek spend about 0.6. The estimator now carries a scale (clamped to 0.5-1.5, text only), learned from consecutive requests in a turn: they share tools, system prompt and earlier messages, so the provider's growth between them prices exactly the appended messages, without mixing in how a provider renders tool schemas. The turn's scale is stored on its usage (context_token_scale); the next turn's loader prices history with it and hands it to the engine. Loading, the first compaction check and compaction itself share one estimator, so they agree; calibrating only the trigger would let the loader drop turns again, which the regression test covers. Also: history is priced as the engine sends it (redacted KB/Wiki results cost one line); a checkpoint older than the rows read is matched by the assistant rows' (created_at, id) order; a read ending on a turn's question keeps that turn; a compaction discarded for freeing under 5% still persists its checkpoint; a checkpoint write matching no row is an error; a partial index backs the newest-checkpoint lookup. Agent mode no longer reads history_turns: the field leaves AgentConfig, the editor hides it in smart-reasoning mode, and quick-answer keeps its turn cap. * fix(agent): address review of window-sized history loading Summarization. The summarizer call had a fixed 60s total timeout. With history loaded up to the window, a request could carry ~175k tokens and be cut off while prefilling or writing normally; the degraded result left no checkpoint, so the next turn reloaded the same history and failed the same way. Summarization now streams and is cancelled only after no output for the engine's stall timeout (120s by default, LLMCallTimeout overrides), with the overall ceiling left to the transport, as for the engine's own rounds and as in Codex and Pi. A stopped turn is not retried. When the summarizer still fails, the raw archive is persisted as a checkpoint marked degraded so the loop is broken, and the next compaction refines it as the previous summary. The archive is held to the summary budget, newest messages first, so a degraded compaction always frees room. Loading. The loader priced turns as sent but returned and held them as stored, so wiki pages stored in full and sent as one line could pile up in memory. It now returns the as-sent history and releases each turn's stored rows once replayed, keeping about a page of rows at a time. Index. The partial checkpoint index is replaced by a composite (session_id, created_at DESC, id DESC) index serving the backwards page, the newest-checkpoint lookup and the recent-messages reads. It is built with CREATE INDEX CONCURRENTLY so writes to messages are not blocked; the migration holds that single statement, since a multi-statement query runs as an implicit transaction. A PostgreSQL integration test, skipped without WEKNORA_MIGRATION_TEST_POSTGRES_DSN, applies the chain, runs 000106 down and up through golang-migrate, and checks both queries use the index without a sort; the SQLite migration test checks the same plans. Calibration. It no longer waits for a total token count, and a usage with only a scale is persisted. A turn that measures nothing carries forward the scale it started from, so the newest turn always has the latest one.
2026-09-18 14:51:31 +00:00
if omitted > 0 {
fmt.Fprintf(&sb, "[%d earlier messages are not shown: they did not fit in one summarization "+
"request, and no previous summary covers them. Do not guess at what they said.]\n\n", omitted)
}
sb.WriteString(serializeConversation(messages))
sb.WriteString("\n</conversation>\n\n")
if previousSummary != "" {
sb.WriteString("<previous-summary>\n")
sb.WriteString(previousSummary)
sb.WriteString("\n</previous-summary>\n\n")
}
sb.WriteString(instructions)
return sb.String()
}
func joinNonEmpty(parts ...string) string {
kept := make([]string, 0, len(parts))
for _, p := range parts {
if strings.TrimSpace(p) != "" {
kept = append(kept, p)
}
}
return strings.Join(kept, "\n\n")
}