"""Synthetic needle-in-a-haystack prompts built from fake service logs. Everything is procedurally generated from a fixed seed (no real data). Each haystack gets 5 needles ("The deploy key for service is <5 digits>") at 10/30/50/70/90% depth, and is trimmed to the target length counted with each model's own tokenizer, including the chat template (thinking disabled). Usage: python haystack.py [--models moe dense] [--out data/] Runs on CPU (only needs `transformers`), no network. """ import argparse import json import random import re from common import (BASE_SEED, DATA, MODELS, N_VARIANTS, NEEDLE_DEPTHS, snapshot_dir) FILLER_SERVICES = [f"{a}-{b}" for a in ["auth", "billing", "search", "ingest", "cart", "notify", "media", "geo", "ledger", "profile", "queue", "edge"] for b in ["api", "worker", "gw", "svc", "cron"]] NEEDLE_NAMES = ["orion", "lyra", "vega", "draco", "cygnus", "perseus", "aquila", "hydra", "pavo", "carina", "corvus", "lupus", "pictor", "tucana", "volans", "fornax"] LEVELS = ["INFO"] * 6 + ["DEBUG"] * 3 + ["WARN"] * 2 + ["ERROR"] TEMPLATES = [ "request {rid} completed status={status} latency_ms={ms} bytes={b}", "connection from 10.{o2}.{o3}.{o4}:{port} accepted, pool={pool}/64", "cache miss key=user:{rid} ttl={ttl}s shard={shard}", "retrying upstream call attempt={att} backoff_ms={ms} upstream={svc2}", "gc pause {ms}ms heap_mb={heap} goroutines={g}", "job {rid} enqueued priority={att} queue_depth={pool}", "health check ok cpu={cpu}% mem={heap}MB uptime_s={b}", "slow query table=t_{shard} rows={b} duration_ms={ms}", "token refresh for client c-{rid} expires_in={ttl}s", "config reload revision={rid} changed_keys={att}", ] QUESTION = ("The log above contains exactly five deploy keys, one each for the services {names}. " "List every one of these services with its deploy key, one per line, in the form " "`service: key`. Output only those five lines.") def log_line(rng: random.Random, t: int) -> str: hh, mm, ss = (t // 3600) % 24, (t // 60) % 60, t % 60 msg = rng.choice(TEMPLATES).format( rid=rng.randint(10000, 99999), status=rng.choice([200, 200, 200, 201, 204, 404, 500, 503]), ms=rng.randint(1, 2500), b=rng.randint(100, 900000), o2=rng.randint(0, 255), o3=rng.randint(0, 255), o4=rng.randint(1, 254), port=rng.randint(1024, 65535), pool=rng.randint(1, 64), ttl=rng.randint(30, 86400), shard=rng.randint(0, 31), att=rng.randint(1, 9), svc2=rng.choice(FILLER_SERVICES), heap=rng.randint(64, 8192), g=rng.randint(10, 5000), cpu=rng.randint(1, 99)) return (f"2026-03-14T{hh:02d}:{mm:02d}:{ss:02d}.{rng.randint(0, 999):03d}Z " f"{rng.choice(LEVELS):5s} [{rng.choice(FILLER_SERVICES)}] {msg}") def make_needles(rng: random.Random): names = rng.sample(NEEDLE_NAMES, len(NEEDLE_DEPTHS)) return [{"service": f"{n}-{rng.randint(10, 99)}", "value": str(rng.randint(10000, 99999)), "depth": d} for n, d in zip(names, NEEDLE_DEPTHS)] def needle_line(n, t): hh, mm, ss = (t // 3600) % 24, (t // 60) % 60, t % 60 return (f"2026-03-14T{hh:02d}:{mm:02d}:{ss:02d}.000Z NOTICE [secrets-vault] " f"The deploy key for service {n['service']} is {n['value']}.") def render(tok, filler, needles, order_rng_seed): """Insert needles at their depth (by line index) and wrap in the chat template.""" lines = list(filler) # insert from deepest to shallowest so earlier indices stay valid for n in sorted(needles, key=lambda n: -n["depth"]): idx = round(n["depth"] * len(filler)) lines.insert(idx, needle_line(n, 3600 + idx)) body = "\n".join(lines) names = [n["service"] for n in needles] random.Random(order_rng_seed).shuffle(names) user = f"\n{body}\n\n\n" + QUESTION.format(names=", ".join(names)) text = tok.apply_chat_template([{"role": "user", "content": user}], tokenize=False, add_generation_prompt=True, enable_thinking=False) return text, body def build_one(tok, target: int, seed: int): """Deterministic haystack whose full templated prompt is <= target tokens and within 48 tokens of it.""" rng = random.Random(seed) needles = make_needles(rng) pool = [log_line(rng, 3600 + i) for i in range(int(target / 18) + 400)] # > enough lines n = int(target / 32) # initial guess, refined below for _ in range(40): text, body = render(tok, pool[:n], needles, seed) ids = tok.encode(text, add_special_tokens=False) over = len(ids) - target if -48 < over <= 0: break step = max(1, abs(over) // 30) n += -step if over > 0 else step if n > len(pool): pool += [log_line(rng, 3600 + len(pool) + i) for i in range(500)] else: raise RuntimeError(f"could not fit haystack to {target} tokens") # actual needle depth as a fraction of body tokens body_ids = len(tok.encode(body, add_special_tokens=False)) for nd in needles: prefix = body.split(f"service {nd['service']} is")[0] nd["token_depth"] = round(len(tok.encode(prefix, add_special_tokens=False)) / body_ids, 4) return {"ids": ids, "n_tokens": len(ids), "needles": needles, "n_filler_lines": n, "seed": seed, "text": text} def score_recall(output: str, needles) -> dict: """Exact match: the first number after each service name must equal its key.""" found = {} for nd in needles: m = re.search(re.escape(nd["service"]) + r"\D{0,40}?(\d+)", output) found[nd["service"]] = (m.group(1) if m else None) == nd["value"] return {"correct": sum(found.values()), "per_needle": found} def load_tokenizer(repo): from transformers import AutoTokenizer return AutoTokenizer.from_pretrained(str(snapshot_dir(repo))) def build_model_set(key, tok=None, variants=N_VARIANTS, contexts=None): repo, ctxs, _ = MODELS[key] tok = tok or load_tokenizer(repo) prompts = [] for ctx in contexts or ctxs: for v in range(variants): p = build_one(tok, ctx, BASE_SEED + 1000 * (ctx // 1024) + v) p.update(model=key, context=ctx, variant=v) prompts.append(p) warm = build_one(tok, 1024, BASE_SEED + 99) warm.update(model=key, context=1024, variant=-1) return {"model": key, "repo": repo, "prompts": prompts, "warmup": warm} def main(): ap = argparse.ArgumentParser() ap.add_argument("--models", nargs="+", default=list(MODELS)) ap.add_argument("--out", default=str(DATA)) a = ap.parse_args() from pathlib import Path out = Path(a.out) out.mkdir(parents=True, exist_ok=True) for key in a.models: s = build_model_set(key) (out / f"prompts_{key}.json").write_text(json.dumps(s)) for p in s["prompts"]: print(f"{key} ctx={p['context']} v={p['variant']} tokens={p['n_tokens']} " f"depths={[n['token_depth'] for n in p['needles']]}") # one human-readable sample per model for the post / inspection (out / f"sample_{key}_8k_v0.txt").write_text(s["prompts"][0]["text"]) if __name__ == "__main__": main()