Skip to content
Merged
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
159 changes: 159 additions & 0 deletions pkgs/atlas-search/eval/boundary-drift-6038.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
# Boundary-drift measurement — atlas span reuse (#6038)

**Question (issue #6038, parent #6028):** span reuse assumes a span's
stored vector stays valid when the span is reused in a new version.
But an embedding is a function of the chunk's exact text *including
its window neighbors*: the same paragraph embedded with different
surrounding text is a different vector, and its rank for a given
query can move. How much?

**Answer in one line:** a lot, at every perturbation size measured —
even a one-sentence boundary shift flips top-10 membership for
5.8% of query/target pairs, and replacing one neighbor paragraph
flips 10.3–17.8%. The reuse-safety rule this justifies is at the
bottom: **reuse only byte-identical windows; re-embed on any
context change.**

## Method

- **Corpus:** the real Atlas corpus (`~/atlas/v3/corpus.db`,
`messages` table; 114,165 messages scanned, 498,564 candidate
targets). Paragraphs are blank-line splits. A target is a
paragraph (200–2000 chars, ≥2 sentences) with a previous and a
next paragraph in the same message. Deterministic sample of 50
targets, seed 6038. Corpus text stays private: this report
carries numbers and methodology only — no excerpts, no message
ids, no query text.
- **Original window W0** = previous paragraph + target + next
paragraph (blank-line joined) — the production chunk shape.
- **Perturbations** (per target):
- `boundary_shift` — drop the first sentence of the *previous*
paragraph only (the target paragraph stays byte-identical and
the blank-line window shape is preserved); append the first
sentence of the paragraph after `next` to the end of `next`
when one exists (49 of 50 targets).
- `neighbor_replace_prev` / `neighbor_replace_next` — replace
that neighbor with the target paragraph of another sampled
message (deterministic donors, offsets +7 / +13).
- `target_alone` — the target paragraph with all context removed
(bounding case).
- **Embedder:** the production pipeline, replicated exactly from
`~/atlas/v3/embed_onnx.py` — pinned Snowflake
`snowflake-arctic-embed-m-v2.0` (HF snapshot
`95c2741480856aa9666782eb4afe11959938017f`), ONNX graph,
AutoTokenizer (`add_special_tokens=True`), right-pad 0 /
attention-mask 0, CLS pooling, L2 normalize. Documents embedded
prompt-free (production corpus mode); queries embedded with the
production `query: ` prompt (`atlas-core` `embed.rs`
`QUERY_PROMPT`). Embedding 270 windows + 20 queries took 357 s
on the laptop (16 threads).
- **Queries:** fixed set of 20 from the golden query set v3
(`~/atlas/v3/golden-queries-v3.json`, every 16th of 311) — the
same fixed set for every window variant.
- **Rank movement:** pool = the 50 original window vectors. For
each query, `rank0` is W0's rank in the pool; `rank_p` is the
perturbed vector's rank when it replaces W0 in the pool.
Reported over all 1,000 query/target pairs per perturbation.

Reproduce: `pkgs/atlas-search/eval/boundary_drift_6038.py`
(laptop only; needs `~/atlas/v3-venv` and the LD_LIBRARY_PATH in
the script's docstring). Raw results JSON is produced by the run;
the numbers below are its readback.

## Results — cosine drift (1 − cosine similarity vs W0, n = 50 targets)

| perturbation | median | p95 | mean | max |
|---|---|---|---|---|
| boundary_shift | 0.045 | 0.175 | 0.060 | 0.301 |
| neighbor_replace_prev | 0.292 | 0.554 | 0.306 | 0.745 |
| neighbor_replace_next | 0.121 | 0.360 | 0.147 | 0.438 |
| target_alone | 0.168 | 0.478 | 0.208 | 0.618 |

## Results — rank movement (pool of 50, 20 queries, 1,000 pairs per type)

| perturbation | median \|Δrank\| | p95 \|Δrank\| | max \|Δrank\| | top-10 flips |
|---|---|---|---|---|
| boundary_shift | 2 | 10 | 22 | 58 / 1000 (5.8%) |
| neighbor_replace_prev | 7 | 27 | 42 | 178 / 1000 (17.8%) |
| neighbor_replace_next | 4 | 21 | 36 | 103 / 1000 (10.3%) |
| target_alone | 5 | 19 | 39 | 119 / 1000 (11.9%) |

Notes on the shape of the numbers:

- **No perturbation is rank-stable.** The smallest change measured
— sliding the window boundary by one sentence — still has a p95
cosine drift of 0.175 and moves a target's rank by 10+ places
(in a pool of only 50) for 5% of query/target pairs.
- **The previous neighbor matters more than the next one**
(median drift 0.292 vs 0.121 for a full replacement). The window's
opening text is the larger context lever in this model; a design
that treats both neighbors as equally cheap to change is wrong.
- **Removing all context (`target_alone`) drifts less than
replacing the previous neighbor with foreign text** (median
0.168 vs 0.292): wrong context is worse than no context.
- Rank and top-10 flip figures are measured in, and scoped to,
this 50-window candidate pool; a flip rate is a property of the
pool it was measured in, not a portable constant. The production
pool (~100k chunks) is far denser near the top, so the production
flip rate for a perturbed window will differ (more near-neighbors
compete for the same ten slots); the figures here establish the
mechanism and its size at pool scale 50, and the reuse rule below
is written to hold regardless of the exact production rate.

## Reuse-safety rule (for the span-schema design, #6035)

> **A stored span vector may be reused only when the full window
> text that produced it — the span plus its recorded neighbors —
> is byte-identical in the new version. Any boundary shift or
> neighbor change, however small, invalidates the vector and the
> span must be re-embedded.** There is no measured "close enough"
> context change: the gentlest perturbation tested (one sentence
> of boundary shift) already flips top-10 membership ~1 time in
> 17 (at pool scale 50), and a single replaced neighbor flips it
> ~1 time in 6–10.
> Context identity — not span identity alone — is the reuse key:
> key stored vectors by the hash of the exact window text, and
> treat a context-class change (neighbor added / removed /
> replaced / boundary moved) as a re-embed trigger.

## Limitations

- 50 targets / 20 queries: distributions are indicative, not
tight; medians are stable at this size, p95s are coarse.
- Donor neighbors are real corpus paragraphs from *other*
messages — a harsher change than an edited version of the same
neighbor. An edit-in-place neighbor change would land between
`boundary_shift` and `neighbor_replace_*`; both endpoints of
that interval already break rank stability, so the rule does
not depend on where in the interval it falls.
- One model (the pinned production model), one corpus. The rule
is stated for this pipeline; another embedder would need its
own measurement before inheriting it.

## Corrections after Codex review (PR #7661)

The first version of this experiment had three defects, all caught
in Codex review of PR #7661 and fixed before merge:

1. `boundary_shift` originally split the *whole window* into
sentences and dropped the first one — when the previous
paragraph had no terminal punctuation its first "sentence"
merged into the target's first sentence, so the shift could eat
into the target, and the window was rebuilt space-joined,
losing the blank-line shape. The construction now drops only
the previous paragraph's first sentence, keeps the target
byte-identical, and preserves the window shape.
2. The model snapshot was selected as whichever HF cache snapshot
sorted last. It is now pinned to
`95c2741480856aa9666782eb4afe11959938017f` (the snapshot the
reported run used — verified the only snapshot in the cache),
and the script fails loudly if it is absent.
3. The top-10 flip rates were described as "the portable figure".
They are pool-relative; the text above now scopes them to the
measured 50-window pool.

The experiment was re-run end-to-end after the fixes. The
`boundary_shift` row above is the corrected run's output; every
other row reproduced the first run's numbers exactly (same seed,
same inputs, deterministic embedder), which is the regression
check that the fixes changed only what they were meant to change.
187 changes: 187 additions & 0 deletions pkgs/atlas-search/eval/boundary_drift_6038.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
#!/usr/bin/env python3
# lane-scratch: code-d /tmp/lane-d-20261108-0448 task 13010
"""Boundary-drift measurement for atlas span reuse (developing-today/code#6038).

Question: a span's stored vector is a function of its chunk's exact text
including window neighbors. When the same paragraph is embedded in a
perturbed window (shifted boundaries, changed neighbors), how much do
its vector (cosine drift) and its rank on a fixed query set move?

Method (numbers only — no corpus text, message ids, or query text are
printed or saved; the corpus is private):
- Corpus: ~/atlas/v3/corpus.db `messages` (the real Atlas corpus).
Paragraphs = blank-line splits. A target is a paragraph with both a
previous and a next paragraph in the same message (200..2000 chars).
Deterministic sample of 50 targets (seed 6038).
- Original window W0 = prev + target + next (blank-line joined), the
production chunk shape.
- Perturbations per target:
* boundary_shift — drop W0's first sentence; append the first
sentence of the paragraph after `next` when one exists.
* neighbor_replace_prev / neighbor_replace_next — replace that
neighbor with the target paragraph of another sampled message
(deterministic donor offsets +7 / +13).
* target_alone — the target paragraph with all context removed
(bounding case).
- Embedder: the production pipeline replicated exactly from
~/atlas/v3/embed_onnx.py — pinned Snowflake
snowflake-arctic-embed-m-v2.0 ONNX graph, AutoTokenizer
(add_special_tokens=True), right-pad 0 / attention-mask 0, CLS
pooling, L2 normalize. Documents prompt-free; queries embedded with
the production "query: " prompt (atlas-core embed.rs QUERY_PROMPT).
- Queries: fixed set of 20 from ~/atlas/v3/golden-queries-v3.json
(every 16th of 311).
- Rank movement: pool = the 50 original window vectors. For query q,
rank0 = rank of W0_i in the pool; rank_p = rank of the perturbed
vector when it replaces W0_i in the pool. Report |rank change|
distribution and top-10 membership flips.

Run (laptop only):
LD_LIBRARY_PATH=<gcc-lib>:<zlib-lib> ~/atlas/v3-venv/bin/python \
boundary_drift_6038.py --out results.json
"""
import argparse, json, pathlib, random, re, sqlite3, sys, time
import numpy as np

SEED = 6038
N_TARGETS = 50
TOPK = 10

def embed_all(sess, tok, texts, batch_tokens=32768):
enc = tok(texts, add_special_tokens=True)["input_ids"]
order = sorted(range(len(texts)), key=lambda i: -len(enc[i]))
out = [None] * len(texts)
input_names = [i.name for i in sess.get_inputs()]
cur, cur_max = [], 0
batches = []
for i in order:
l = len(enc[i]); nm = max(cur_max, l)
if cur and nm * (len(cur) + 1) > batch_tokens:
batches.append(cur); cur, cur_max = [i], l
else:
cur.append(i); cur_max = nm
if cur: batches.append(cur)
for b in batches:
ids = [enc[i] for i in b]; ml = max(len(x) for x in ids)
ii = np.zeros((len(b), ml), dtype=np.int64); am = np.zeros((len(b), ml), dtype=np.int64)
for j, x in enumerate(ids):
ii[j, :len(x)] = x; am[j, :len(x)] = 1
feed = {}
for n in input_names:
if n == "input_ids": feed[n] = ii
elif n == "attention_mask": feed[n] = am
elif n == "token_type_ids": feed[n] = np.zeros_like(ii)
h = sess.run(None, feed)[0]
v = h[:, 0, :].astype(np.float32)
v = v / np.linalg.norm(v, axis=1, keepdims=True)
for j, i in enumerate(b): out[i] = v[j]
return np.stack(out)

def sentences(text):
return [s for s in re.split(r"(?<=[.!?])\s+", text.strip()) if s]

def pct(a, q):
return float(np.percentile(np.asarray(a, dtype=np.float64), q))

def stats(a):
a = np.asarray(a, dtype=np.float64)
return {"n": int(a.size), "median": float(np.median(a)), "p95": pct(a, 95),
"mean": float(a.mean()), "max": float(a.max())}

def main():
ap = argparse.ArgumentParser()
ap.add_argument("--out", required=True)
ap.add_argument("--corpus", default="/home/user/atlas/v3/corpus.db")
ap.add_argument("--golden", default="/home/user/atlas/v3/golden-queries-v3.json")
args = ap.parse_args()
import onnxruntime as ort
from transformers import AutoTokenizer

# Pinned snapshot (Codex review, PR #7661): the exact revision the
# reported run used; fail loudly instead of silently selecting
# whichever snapshot happens to sort last in a future cache.
model_dir = "/home/user/.cache/huggingface/hub/models--Snowflake--snowflake-arctic-embed-m-v2.0/snapshots/95c2741480856aa9666782eb4afe11959938017f"
if not pathlib.Path(model_dir).is_dir():
sys.exit(f"pinned model snapshot missing: {model_dir}")
tok = AutoTokenizer.from_pretrained(model_dir)
so = ort.SessionOptions(); so.intra_op_num_threads = 16; so.inter_op_num_threads = 2
sess = ort.InferenceSession(model_dir + "/onnx/model.onnx", sess_options=so, providers=["CPUExecutionProvider"])

db = sqlite3.connect(f"file:{args.corpus}?mode=ro", uri=True)
rows = db.execute("SELECT id, text FROM messages WHERE text IS NOT NULL ORDER BY id").fetchall()
db.close()
cands = [] # (prev, target, next, after_next_or_None)
for _mid, text in rows:
paras = [p.strip() for p in text.split("\n\n") if p.strip()]
for i in range(1, len(paras) - 1):
t = paras[i]
if 200 <= len(t) <= 2000 and len(sentences(t)) >= 2:
after = paras[i + 2] if i + 2 < len(paras) else None
cands.append((paras[i - 1], t, paras[i + 1], after))
rng = random.Random(SEED)
sample = rng.sample(cands, N_TARGETS)
donors = [c[1] for c in sample]

W0, pert = [], {"boundary_shift": [], "neighbor_replace_prev": [], "neighbor_replace_next": [], "target_alone": []}
shift_extended = 0
for idx, (prev, tgt, nxt, after) in enumerate(sample):
w0 = prev + "\n\n" + tgt + "\n\n" + nxt
W0.append(w0)
prev_sents = sentences(prev)
shifted_prev = " ".join(prev_sents[1:])
next_part = nxt
if after:
next_part = nxt + " " + sentences(after)[0]; shift_extended += 1
shifted_parts = [q for q in (shifted_prev, tgt, next_part) if q]
pert["boundary_shift"].append("\n\n".join(shifted_parts))
pert["neighbor_replace_prev"].append(donors[(idx + 7) % N_TARGETS] + "\n\n" + tgt + "\n\n" + nxt)
pert["neighbor_replace_next"].append(prev + "\n\n" + tgt + "\n\n" + donors[(idx + 13) % N_TARGETS])
pert["target_alone"].append(tgt)

golden = json.load(open(args.golden))["queries"]
queries = [q["query"] for q in golden[::16][:20]]

t0 = time.time()
v0 = embed_all(sess, tok, W0)
vp = {k: embed_all(sess, tok, v) for k, v in pert.items()}
vq = embed_all(sess, tok, ["query: " + q for q in queries])
embed_seconds = time.time() - t0

S0 = vq @ v0.T # (Q, N)
order0 = np.argsort(-S0, axis=1)
rank0 = np.empty_like(order0)
for q in range(S0.shape[0]):
rank0[q, order0[q]] = np.arange(1, S0.shape[1] + 1)
top0 = [set(order0[q, :TOPK].tolist()) for q in range(S0.shape[0])]

result = {
"model_snapshot": model_dir.split("/")[-1],
"corpus_messages_scanned": len(rows),
"candidate_targets": len(cands),
"n_targets": N_TARGETS, "n_queries": len(queries), "seed": SEED,
"shift_extended_with_following_sentence": shift_extended,
"embed_seconds": round(embed_seconds, 1),
"per_type": {},
}
for name, V in vp.items():
cos = np.sum(v0 * V, axis=1)
drift = 1.0 - cos
sp = vq @ V.T
absdr, flips, pairs = [], 0, 0
for q in range(S0.shape[0]):
for i in range(N_TARGETS):
col = S0[q].copy(); col[i] = sp[q, i]
rp = int(np.sum(col > sp[q, i]) + 1)
absdr.append(abs(rp - int(rank0[q, i]))); pairs += 1
in0 = i in top0[q]; inp = rp <= TOPK
if in0 != inp: flips += 1
result["per_type"][name] = {
"cosine_drift": stats(drift), "cosine_similarity_median": float(np.median(cos)),
"abs_rank_change": stats(absdr), "top10_membership_flips": flips,
"top10_flip_rate": flips / pairs, "query_target_pairs": pairs,
}
json.dump(result, open(args.out, "w"), indent=1)
print(json.dumps(result, indent=1))

if __name__ == "__main__":
main()
Loading