Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ Versions follow the merge of a `*_release-v*` branch; CI publishes to npm on tag
- dsh 归因丢失协商回退(#4082/#3918/#2975):宿主重试/切模型/睡眠恢复的请求脱离 agent 执行链,归因为空时此前直接裸发上游(无压缩无护栏,且会话永久失守)。现在 shim 在归因正常时学习「车道 → 会话 + 边界指纹」(该次请求最后一条消息),归因丢失时若请求历史包含某已知边界且唯一命中,则由 takeover 门认领并原子补盖 x-bili-plugin-conversation(#3370 纪律),请求照常走插件车道;fork 从中间分叉不含边界 → 不认,行为与今天逐字节一致;无证据/多义 → 维持直发。每个 2xx 响应新增 x-bili-session 头(协议级,配合客户端可自持身份,见 PLUGIN.md);认领事件进 client 日志可见。
### 压缩

- **过小的陈旧 usage 样本不再冻结计量(#4383)**:同一会话 id 下的小而真实的 usage-grade 样本(标题生成/探测等侧车请求)被 settleUsageReport 无条件写进 lastUsageGradeTokens,所有输入基线读者(statusInputBaseline / effectiveTokenCount)原样信任——kernel 的 growth reference 是低水位标记(#1595)会跟到该值,growth ≡0、压力带失效,自动折叠整段停摆(复现:一次 4733-token 样本把 303k 上下文冻在 usage=1% 达 4h07m,154 次 nudge 全部 idle、零折叠;换模型前重启也不愈合)。现在两个共享读者都走同一个 stale-small 守卫:锚点低于当前出站 billing-caliber 本地估算(contextEstimateTokens)的 25%、且已被其后的一次主发送超越(contextTokensSource="estimate"——主发送逐次盖章、settle 翻回 "usage")时,降级为该估算值——即 #1595 书面承诺的"改用本地估算"兜底。新鲜度闸门区分"陈旧侧车样本"与"新鲜小样本"(后者保持权威,#1820 B 不变量有测试钉死);高于估算的锚点保持 #1839 优先(单向);无估算/无新鲜度戳的旧会话行为逐字节不变。preflight 本就自校正(max(baselineFloor, calibratedPayload)),不受影响;kernel 未动,无新增配置。
- **压缩区间跨越受保护消息时在边界截断,不再挖洞(#3953)**:此前模型选的区间如果中途扫过受保护消息(最近 N 条/最近一条用户消息),受保护消息会被从覆盖名单里挖掉、两侧照折——其回复(在受保护提问之后的消息)被摘要盖住,而摘要锚点落在提问之前,模型看到"答案摘要排在自己的问题上方"。现在区间在首个受保护消息处截断:从该位置起(受保护消息与其后的回复)全部保持可见,因果序不再被打穿。受保护消息恰在区间尾部的常规擦边(咨询式保护区原本设计的形状)行为逐字节不变;截断会清空区间或会劈开工具调用/结果对的形状退回原挖洞语义(吸收保护的吸收对不受影响)。
- **compress-from-store:被逐出的会话对着统一存储的原始视图折叠,不再永久拒收(#3982,根治 #3918 Phase 4)**:超过常驻池预算(默认 512 MiB)的大会话每次模型请求后都被逐出,活内存视图永不存活,`compress` 工具因此永久 REFUSED——而统一存储(#3911)本就每次保存把完整原始客户端视图镜像进 messages 表。现在 applyRanges 与外部摘要链在"有效视图为空"时先从统一正史恢复视图(只读、只窥探——绝不隐式建库;任一行不可解析维持诚实拒收),折叠落在持久化 state 上,与"下一轮模型请求后重试"路径完全同构。活视图在场时存储从不被咨询(零行为变化);无存储/legacy 模式拒收回执逐字节不变。

Expand Down
17 changes: 14 additions & 3 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ import { FORCE_TEXT_PROTOCOL } from "./server/inject.js";
export { isChatGptCodexUpstream, isCodexResponsesLite, resolvePromptCacheKey, shouldInjectPromptCacheKey } from "./server/prepare-responses.js";
import { reconcileFoldCoverage, noteSystemPromptFingerprint, resolveFoldReconcileMode } from "./fold-reconcile.js";
import { biliToolsDeclaredOnWire, countBiliToolUses, evaluateSelfHealRound, nudgeSuppressed, pluginLaneDegraded, pluginLaneRestore } from "./session-self-heal.js";
import { getSession, hasProcessedState, listSessions, peekSession, type PendingRetrieval, type Session, initSessions, markDirty, flushAllSessions, acquireInFlight, releaseInFlight, totalInFlight, snapshotMessages, ensureCanonicalId, storeEffectiveConfig, foldCoverage, postRebuildAnchorTokens, setPostRebuildAnchor, tickPostRebuildAnchor, splitSessionWarnings, RESPONSES_TURN_SEPARATOR_ID_PREFIX } from "./session.js";
import { getSession, hasProcessedState, listSessions, peekSession, type PendingRetrieval, type Session, initSessions, markDirty, flushAllSessions, acquireInFlight, releaseInFlight, totalInFlight, snapshotMessages, ensureCanonicalId, storeEffectiveConfig, foldCoverage, postRebuildAnchorTokens, setPostRebuildAnchor, tickPostRebuildAnchor, splitSessionWarnings, staleSmallAnchorFallback, RESPONSES_TURN_SEPARATOR_ID_PREFIX } from "./session.js";
import { detectStaleInstall } from "./update.js";
import { decideEaddrinuse, eaddrinuseExitCode, postBindCanLadder, UPGRADE_REPLACEMENT_ENV, type FailFastReason } from "./listen-policy.js";
import { getAdvisoryState, cannotResolveTarget } from "./advisory.js";
Expand Down Expand Up @@ -2329,7 +2329,11 @@ export function effectiveTokenCount(session: Session, msgs: CoreMessage[], inbou
// #1839: an overflow arm rides in here too — it is evidence, not billing,
// but it is bounded by the declared/stated window so it cannot produce
// the >100% ghost class, and the next real usage report overwrites it.
if (session.stats.lastInputTokens > 0 && (session.stats.lastInputTokensSource === "usage" || session.stats.lastInputTokensSource === "overflow-arm")) return { tokens: session.stats.lastInputTokens, source: "usage" };
// #4383: a stale-small trusted anchor (a sidecar/side-request sample under
// the same session id, superseded by later main sends) must not freeze the
// meter — fall through instead: the post-rebuild anchor below (if any) is
// the fresher measurement, otherwise the calibrated-estimate branches win.
if (session.stats.lastInputTokens > 0 && (session.stats.lastInputTokensSource === "usage" || session.stats.lastInputTokensSource === "overflow-arm") && staleSmallAnchorFallback(session.stats, session.stats.lastInputTokens) === null) return { tokens: session.stats.lastInputTokens, source: "usage" };
// #1820: right after a preflight rebuild the usage-grade baseline above is
// momentarily absent (the rebuild request's own report hasn't landed yet,
// or the upstream never reports), and every branch below sizes on the
Expand Down Expand Up @@ -2362,7 +2366,14 @@ export function effectiveTokenCount(session: Session, msgs: CoreMessage[], inbou
// upstreams (#553/#728) are unaffected: their anchor stays absent, so the
// fail-closed upper bounds below still apply.
const grade = session.stats.lastUsageGradeTokens;
if (grade !== undefined && grade > 0) return { tokens: grade, source: "usage" };
if (grade !== undefined && grade > 0) {
// #4383: stale-small retained anchor — the calibrated local estimate
// of the current outbound is strictly better than the char-count
// branches below (#1839 inflation), so it wins immediately.
const fallback = staleSmallAnchorFallback(session.stats, grade);
if (fallback !== null) return { tokens: fallback, source: "estimate" };
return { tokens: grade, source: "usage" };
}
// #553: zero-baseline ANCHOR-LESS anonymous sessions (prefix-affinity
// mints/forks/reloads) fall back to the raw-history upper bound — see the
// function header for why feeding 0 blinds them.
Expand Down
46 changes: 44 additions & 2 deletions src/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -689,6 +689,43 @@ export function effectiveConfig(session: Session | undefined, fallback: Config):
return classifier && !base.messagePathOf ? withDurableProtection(base, classifier) : base;
}

// #4383: a positive usage-grade anchor below this share of the billing-caliber
// estimate of the last main send (contextEstimateTokens) cannot describe the
// payload this conversation actually carries — it measured a different,
// smaller request under the same session id (title-gen/probe sidecar) or
// predates a growth burst. 0.25 sits just inside the estimator's own error
// band (uncalibrated chars/4 over-counts ASCII up to ~3.5× ⇒ a legitimate
// same-payload sample lands ≈0.29× the estimate and survives; sidecar samples
// are typically <10% and get caught), matching the k̂ clamp floor (0.25–4).
const STALE_ANCHOR_RATIO = 0.25;

/** #4383: stale-small usage-anchor guard shared by every input-baseline reader
* (statusInputBaseline, effectiveTokenCount). Returns the replacement reading
* — the calibrated local estimate itself (#1595's promised "ride local
* estimates until a usage-grade sample lands" fallback) — when BOTH hold:
* - `anchor` is below STALE_ANCHOR_RATIO × `stats.contextEstimateTokens`
* (magnitude-inconsistent with what this conversation actually sends);
* - `contextTokensSource === "estimate"`, i.e. a MAIN SEND has occurred
* since the last settled usage report (the relay chokepoint stamps it per
* send, settleUsageReport flips it back to "usage"). That freshness gate
* is what separates a STALE sidecar sample (superseded by later larger
* main sends) from a FRESH small one (the current send's own report,
* which keeps its #1820 authority over the post-rebuild anchor).
* One-directional by design: anchors ABOVE the estimate keep their #1839
* precedence (fail-closed direction); only too-small poison is demoted.
* Absent/non-positive estimate (legacy sessions, no main send yet) → null,
* byte-identical legacy behavior. */
export function staleSmallAnchorFallback(
stats: Pick<Session["stats"], "contextEstimateTokens" | "contextTokensSource">,
anchor: number,
): number | null {
const est = stats.contextEstimateTokens;
return stats.contextTokensSource === "estimate"
&& anchor > 0 && typeof est === "number" && Number.isFinite(est) && est > 0 && anchor < STALE_ANCHOR_RATIO * est
? est
: null;
}

/** #2029: provenance-aware baseline for STATUS readers — acp_status nudge
* recompute, plugin live nudge + panel, post-compress tail. Shared by every
* status surface so none of them can present an estimate-grade reading as a
Expand All @@ -710,12 +747,17 @@ export function effectiveConfig(session: Session | undefined, fallback: Config):
* sentinel. Never clamps: a REAL over-window usage report must still read
* >100%. The JSON observation contract (contextTokens/contextTokensSource,
* #2017) is deliberately separate — it expresses unknown explicitly rather
* than as 0. */
* than as 0. On top of all of that, the stale-small guard applies (#4383): an
* anchor below 25% of the billing-caliber local estimate of the current
* outbound AND superseded by a later main send is demoted to that estimate —
* it measured a different request under the same session id and must not
* blind the growth gate (see staleSmallAnchorFallback for the contract). */
export function statusInputBaseline(session: Session): number {
const stats = session.stats;
return stats.lastInputTokensSource === "usage" || stats.lastInputTokensSource === "overflow-arm"
const baseline = stats.lastInputTokensSource === "usage" || stats.lastInputTokensSource === "overflow-arm"
? stats.lastInputTokens
: stats.lastUsageGradeTokens ?? 0;
return staleSmallAnchorFallback(stats, baseline) ?? baseline;
}

/** #2117: the honest best reading of "how full is this context right now" for
Expand Down
Loading
Loading