Skip to content

Commit 31c030c

Browse files
committed
perf(plugin): scan past tagless wire leaders when deriving the tag floor
deriveTagLoadFloor scopes both hot-path tag scans (tagger initFromDb + the compartment trigger's token scans) to tag_number >= floor. It derived the floor from the leading wire message ids via getMinMessageTagNumberForRawId, which matches ONLY a message's :p/:file tags — never its tool tags (those key on the callId). After a compaction marker the wire head is frequently a run of tagless messages: the synthetic m[0]/m[1] leaders plus tool-only assistant turns. The old logic capped at the first 8 ID-BEARING probes and took their MIN, so a tagless head exhausted the budget on NULLs → Infinity → floor 0 → the full ~100k-tag scan the floor exists to avoid. Live-observed as an oscillating ~66ms compartmentTrigger that flipped to ~6ms only on passes whose head happened to start with a tagged message. Fix: keep probing PAST NULL leaders until 8 resolve (bounded by 64 probes so a fully-tagless head still falls back to floor 0 rather than scanning the wire), and widen the safety margin by 64 per leader skipped before the first hit — a skipped tool-only leader's tool tags sit just below the first :p tag we land on, so the wider margin keeps them inside the floor. The floor still only ever errs LOW (loads a few extra tags, never drops a live-wire tag), so the §N§ wire bytes and the trigger decision stay identical. Adds a one-line "tag floor: 0 (full-scan fallback)" health log so the fallback can't hide as silent latency.
1 parent aae1ab2 commit 31c030c

3 files changed

Lines changed: 93 additions & 15 deletions

File tree

packages/plugin/src/features/magic-context/storage-tags.ts

Lines changed: 45 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -928,37 +928,67 @@ export function getMinMessageTagNumberForRawId(
928928
return isMinTagNumberRow(row) && typeof row.m === "number" ? row.m : null;
929929
}
930930

931-
// Number of leading wire messages probed to derive the load-scoping floor, and
932-
// the margin subtracted from the resulting min tag number. A LOWER floor only
933-
// ever loads MORE tags (strictly safe — it can never exclude an in-wire tag);
934-
// the margin absorbs a tagged leading compaction-summary, near-boundary tool
935-
// straddles, and minor reordering at the wire head.
936-
export const TAGGER_FLOOR_SCAN_MESSAGES = 8;
931+
// Floor derivation tunables. A LOWER floor only ever loads MORE tags (strictly
932+
// safe — it can never exclude an in-wire tag); the margin absorbs a tagged
933+
// leading compaction-summary, near-boundary tool straddles, and reordering at
934+
// the wire head.
935+
// SCAN_HITS — stop once this many leading messages RESOLVE to a real tag
936+
// (we MIN across them to absorb head reordering).
937+
// MAX_PROBES — hard cap on probes so a fully-ghost/tool-only head can't make
938+
// us scan the whole wire; exhausting it → floor 0 (full scan).
939+
// SAFETY_MARGIN — base margin subtracted from the resolved min.
940+
// PER_SKIP_MARGIN — extra margin per LEADER SKIPPED before the first hit.
941+
export const TAGGER_FLOOR_SCAN_MESSAGES = 8; // SCAN_HITS
942+
export const TAGGER_FLOOR_MAX_PROBES = 64;
937943
export const TAGGER_FLOOR_SAFETY_MARGIN = 256;
944+
export const TAGGER_FLOOR_PER_SKIP_MARGIN = 64;
938945

939946
/**
940947
* Derive the tagger/scan load-scoping floor from the leading wire message ids:
941-
* the minimum message/file tag number across the first
942-
* `TAGGER_FLOOR_SCAN_MESSAGES` id-bearing ids, minus `TAGGER_FLOOR_SAFETY_MARGIN`
943-
* (clamped to 0). Shared by the tagger's `initFromDb` and the compartment
944-
* trigger's tag scans so both scope to the same live-wire range. Returns 0 when
945-
* nothing is tagged yet → callers fall back to the full-session scan.
948+
* roughly the minimum message/file tag number across the leading messages,
949+
* minus a safety margin (clamped to 0). Shared by the tagger's `initFromDb` and
950+
* the compartment trigger's tag scans so both scope to the same live-wire range.
951+
* Returns 0 when nothing resolves → callers fall back to the full-session scan.
952+
*
953+
* `getMinMessageTagNumberForRawId` matches ONLY a message's `:p`/`:file` tags,
954+
* never its tool tags (those key on the callId). So the wire head — which after
955+
* a compaction marker is frequently a run of tool-only assistant turns and/or
956+
* tagless ghost/synthetic leaders — returns all-NULL. The old code capped at the
957+
* first 8 ID-BEARING probes and took their MIN, so such a head exhausted the
958+
* budget on NULLs → Infinity → floor 0 → the full ~100k-tag scan we are trying
959+
* to avoid (the live ~66ms compartmentTrigger oscillation).
960+
*
961+
* Fix: keep probing PAST NULL leaders until SCAN_HITS messages resolve (bounded
962+
* by MAX_PROBES). A skipped tool-only leader's tool tags sit just BELOW the
963+
* first `:p` tag we land on, so we widen the margin by PER_SKIP_MARGIN for every
964+
* leader skipped before the first hit — the floor still only ever errs LOWER
965+
* (loads a few extra tags), never higher (never drops a live-wire tag).
946966
*/
947967
export function deriveTagLoadFloor(
948968
db: Database,
949969
sessionId: string,
950970
rawIds: Iterable<string | null | undefined>,
951971
): number {
952972
let min = Number.POSITIVE_INFINITY;
953-
let scanned = 0;
973+
let probes = 0;
974+
let hits = 0;
975+
let skippedBeforeFirstHit = 0;
954976
for (const rawId of rawIds) {
955977
if (typeof rawId !== "string" || rawId.length === 0) continue;
978+
if (probes >= TAGGER_FLOOR_MAX_PROBES) break;
979+
probes++;
956980
const m = getMinMessageTagNumberForRawId(db, sessionId, rawId);
957-
if (m !== null && m < min) min = m;
958-
if (++scanned >= TAGGER_FLOOR_SCAN_MESSAGES) break;
981+
if (m === null) {
982+
if (hits === 0) skippedBeforeFirstHit++;
983+
continue;
984+
}
985+
if (m < min) min = m;
986+
if (++hits >= TAGGER_FLOOR_SCAN_MESSAGES) break;
959987
}
960988
if (!Number.isFinite(min)) return 0;
961-
return Math.max(0, min - TAGGER_FLOOR_SAFETY_MARGIN);
989+
const margin =
990+
TAGGER_FLOOR_SAFETY_MARGIN + skippedBeforeFirstHit * TAGGER_FLOOR_PER_SKIP_MARGIN;
991+
return Math.max(0, min - margin);
962992
}
963993

964994
// Single source-of-truth column list for SELECTs that produce TagEntry.

packages/plugin/src/features/magic-context/tagger-scoped-load.test.ts

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -214,6 +214,43 @@ describe("deriveTagLoadFloor", () => {
214214
expect(deriveTagLoadFloor(db, s, [null, undefined, "", "msg_a"])).toBe(0);
215215
expect(deriveTagLoadFloor(db, s, ["msg_untagged"])).toBe(0);
216216
});
217+
218+
it("scans PAST tagless leaders (ghost/tool-only) to the first real :p tag", () => {
219+
// Reproduces the live regression: after a compaction marker the wire head
220+
// is a run of tool-only / tagless ghost messages with NO :p/:file tag, so
221+
// the old 8-id-probe MIN exhausted on NULLs → floor 0 → full scan.
222+
const s = "ses-1";
223+
// 3 tagless leaders (no message/file tag), then the first real one at 9000.
224+
insertMessageTag(db, s, "msg_real:p0", 9000);
225+
const floor = deriveTagLoadFloor(db, s, [
226+
"msg_ghost1",
227+
"msg_tool2",
228+
"msg_tool3",
229+
"msg_real",
230+
]);
231+
// Resolves (not 0). Base margin 256 + 3 skipped * 64 = 448 → 9000 - 448.
232+
expect(floor).toBe(9000 - (256 + 3 * 64));
233+
});
234+
235+
it("widens the margin per skipped leader so skipped tool tags stay included", () => {
236+
const s = "ses-1";
237+
// One skipped leader → margin 256 + 64 = 320.
238+
insertMessageTag(db, s, "msg_real:p0", 1000);
239+
expect(deriveTagLoadFloor(db, s, ["msg_ghost", "msg_real"])).toBe(1000 - 320);
240+
// Zero skipped (first id resolves) → base margin only.
241+
expect(deriveTagLoadFloor(db, s, ["msg_real"])).toBe(1000 - 256);
242+
});
243+
244+
it("stops at MAX_PROBES on a fully-tagless head → floor 0 (full-scan fallback)", () => {
245+
const s = "ses-1";
246+
// A real tag exists but only PAST the probe cap; 100 tagless leaders first.
247+
insertMessageTag(db, s, "msg_real:p0", 5000);
248+
const head: string[] = [];
249+
for (let i = 0; i < 100; i++) head.push(`msg_ghost${i}`);
250+
head.push("msg_real");
251+
// The first 64 probes are all NULL → break before reaching msg_real → 0.
252+
expect(deriveTagLoadFloor(db, s, head)).toBe(0);
253+
});
217254
});
218255

219256
describe("scoped tag-token scans (boundary + trigger pre-gate)", () => {

packages/plugin/src/hooks/magic-context/transform.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1063,6 +1063,17 @@ export function createTransform(deps: TransformDeps) {
10631063
// deriving it here keeps both tag scans scoped on every pass (those
10641064
// anchor-miss passes were the residual ~90ms full-scan regression).
10651065
const taggerFloor = deriveTaggerLoadFloor(messages, sessionId, db);
1066+
// floor 0 = no leading wire message resolved to a tag → BOTH tag scans
1067+
// (tagger initFromDb + the trigger's token scans) fall back to the full
1068+
// ~O(session) load. On a large session that's the ~70ms compartmentTrigger
1069+
// we are trying to avoid, so surface it as a one-line health signal rather
1070+
// than letting it hide as silent latency.
1071+
if (taggerFloor === 0 && messages.length > 0) {
1072+
sessionLog(
1073+
sessionId,
1074+
`tag floor: 0 (full-scan fallback) — no leading wire message resolved a tag across ${messages.length} msgs`,
1075+
);
1076+
}
10661077

10671078
let triggerBoundarySnapshot: ProtectedTailBoundarySnapshot | undefined;
10681079
if (fullFeatureMode && historianRunnable && !sessionMeta.compartmentInProgress) {

0 commit comments

Comments
 (0)