diff --git a/docs/KANBAN.md b/docs/KANBAN.md index bf09211f..23290a22 100644 --- a/docs/KANBAN.md +++ b/docs/KANBAN.md @@ -25,7 +25,7 @@ Ruling landing: 1,472 rulings, 1,425 gold (test 277, val 164, train 984). Export ## In progress - [ ] **Raise test gold to 250 (G1), then 470 (G5).** Owner: Danny (rulings), Grok Bot (queues). Rows: export 274/250 met (recount 274; landing 277); G5 274/470; 37 test terms (roadmap >=150 open). Test-gap fill: 228 posts for 18/21 empty test terms; queues 2026-10-16c (54), 16d (42), 16e (33) ruled and applied. tlpur needs context. -- [ ] **PR #31: T026/T028 (windowed export context, R statuses non-gold, Jev use_mention).** Owner: Danny (merge yes). Opus review findings fixed; 42 tests pass. Not merged. +- [x] **PR #31: T026/T028 (windowed export context, R statuses non-gold, Jev use_mention).** Danny merge yes 2026-10-16 4:28 PM PT. ## Blocked - [x] **Freeze the held-out test manifest.** Done 2026-10-16 4:00 PM PT (Danny go 3:55 PM PT): 273 ids, sha256 a03c8619…; recorded in docs/v2/G5_PREREG_EVAL.md (PR #33), tag v2-test-freeze-2026-10-16. The 15 quarantined gold rows stay out of test. Readiness: READY (G1 273, 37/37 test terms; T2 318/300). Nothing runs on the Sparks until Danny says go. diff --git a/scripts/v2/export_splits.py b/scripts/v2/export_splits.py new file mode 100644 index 00000000..062651ce --- /dev/null +++ b/scripts/v2/export_splits.py @@ -0,0 +1,109 @@ +#!/usr/bin/env python3 +"""Export train/val/test JSONL from the PRIVATE local store, deduped on text hash. + +Dedup rules (deterministic): + 1. Within a split, keep one row per (content_sha256, term); prefer human-gold, then lowest record_id. + 2. Across splits, each text lives in ONE split, priority test > val > train (protects held-out). +Outputs (private, local_store/export/): {train,val,test}.jsonl (SFT rows), gold_test.jsonl +(prereg_eval.py format: record_id, gold, family), test_manifest.txt + sha256, export_report.json. +SFT row: record_id, split, term, term_family, lineage_family, context, label, label_source, slur_tagged. +""" +import json, os, hashlib, collections, sys +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) # 2026-10-16: current tracker ruling_queue, not the vi-data copy +from ruling_queue import split_for, window_excerpt, NON_GOLD_ROW_STATUS +ROOT = os.environ.get("HYPERLEX_LOCAL_STORE", "local_store") # private store; path set on the operator box +OUT = ROOT + "/export" +PRI = {"test": 0, "val": 1, "train": 2} + + +def gold(r): + h = r.get("human_ruling") or {} + if h.get("row_status") in NON_GOLD_ROW_STATUS: # spec 009 R = unusable evidence: never gold + return None + return h.get("sense") if str(h.get("source", "")).lower() == "human" and h.get("sense") in ("SLANG_SENSE", "OTHER_SENSE") else None + + +def context_of(r): + """T026: target-centred window (same width as the ruling queue) instead of the full post.""" + ctx, kind = window_excerpt(r.get("contextual_use") or "", r["term"]) + return ctx, kind + + +def text_key(r): + """Dedup key on the exported text itself (case/whitespace-normalised), not only the source post hash: + identical short excerpts from different posts were surviving as duplicates (readiness check 2026-10-16).""" + import hashlib as _h + t = " ".join(str(r.get("contextual_use") or "").lower().split()) + return _h.sha256(t.encode()).hexdigest() if t else r["content_sha256"] + + +def main(src=ROOT + "/curated_sense_observation.jsonl", out=OUT): + os.makedirs(out, exist_ok=True) + rows = [json.loads(l) for l in open(src) if l.strip()] + rep_ns = sum(1 for r in rows if (r.get("human_ruling") or {}).get("row_status") in NON_GOLD_ROW_STATUS) + for r in rows: + r["_split"] = (r.get("human_ruling") or {}).get("split") or split_for(r["term_family"]) + rep = {"input_rows": len(rows), "non_gold_row_status_rows": rep_ns} + # 1 within-split (text, term) + best = {} + for r in sorted(rows, key=lambda r: (gold(r) is None, r["record_id"])): + k = (r["_split"], text_key(r), r["term"].lower()) + best.setdefault(k, r) + rows1 = list(best.values()); rep["dropped_exact_dup"] = len(rows) - len(rows1) + # 2 cross-split + home = {} + for r in rows1: + s = home.get(text_key(r)) + if s is None or PRI[r["_split"]] < PRI[s]: + home[text_key(r)] = r["_split"] + rows2 = [r for r in rows1 if home[text_key(r)] == r["_split"]] + # Opus review PR #31: rows a human judged unusable (R) are not SFT rows either; counted, kept in the store + rows2_all = rows2 + rows2 = [r for r in rows2 if (r.get("human_ruling") or {}).get("row_status") not in NON_GOLD_ROW_STATUS] + rep["dropped_non_gold_row_status"] = len(rows2_all) - len(rows2) + rep["dropped_cross_split"] = len(rows1) - len(rows2) + by = collections.defaultdict(list) + for r in rows2: + g = gold(r) + ctx, kind = context_of(r) + h = r.get("human_ruling") or {} + by[r["_split"]].append({ + "record_id": r["record_id"], "split": r["_split"], "term": r["term"], "term_family": r["term_family"], + "lineage_family": (r.get("mutation_lineage") or {}).get("lineage_family"), + "context": ctx, "context_match": kind, "label": g or r["sense_candidate"], + "use_mention": h.get("use_mention"), "row_status": h.get("row_status"), + "excerpt_provenance": h.get("excerpt_provenance"), + "label_source": "human" if g else "model:" + str((r.get("model_proposal") or {}).get("model_or_rule")), + "slur_tagged": bool((r.get("sensitivity") or {}).get("slur_tagged")), "text_contains_slur": bool((r.get("sensitivity") or {}).get("text_contains_slur"))}) + for s in ("train", "val", "test"): + with open(f"{out}/{s}.jsonl", "w") as fh: + for x in sorted(by[s], key=lambda x: x["record_id"]): + fh.write(json.dumps(x, ensure_ascii=False) + "\n") + gt = sorted((x for x in by["test"] if x["label_source"] == "human"), key=lambda x: x["record_id"]) + with open(f"{out}/gold_test.jsonl", "w") as fh: + for x in gt: + fh.write(json.dumps({"record_id": x["record_id"], "gold": x["label"], "family": x["lineage_family"] or x["term_family"]}) + "\n") + man = "".join(x["record_id"] + "\n" for x in gt) + open(f"{out}/test_manifest.txt", "w").write(man) + rep["test_manifest_sha256"] = hashlib.sha256(man.encode()).hexdigest() + sha = {r["record_id"]: r["content_sha256"] for r in rows2} + texts = {s: {sha[x["record_id"]] for x in by[s]} for s in by} # whole-post hash, not the window + terms = {s: {x["term"].lower() for x in by[s]} for s in by} + rep.update({"rows": {s: len(by[s]) for s in by}, "gold_rows": {s: sum(x["label_source"] == "human" for x in by[s]) for s in by}, + "gold_test": len(gt), + "text_overlap": {"train_test": len(texts["train"] & texts["test"]), "val_test": len(texts["val"] & texts["test"]), "train_val": len(texts["train"] & texts["val"])}, + "term_overlap": {"train_test": len(terms["train"] & terms["test"]), "val_test": len(terms["val"] & terms["test"]), "train_val": len(terms["train"] & terms["val"])}, + "label_by_family": {str(k): dict(v) for k, v in _lab(rows2).items()}}) + json.dump(rep, open(f"{out}/export_report.json", "w"), indent=2) + print(json.dumps({k: v for k, v in rep.items() if k != "label_by_family"}, indent=2)) + + +def _lab(rows): + c = collections.defaultdict(collections.Counter) + for r in rows: + c[(r.get("mutation_lineage") or {}).get("lineage_family")][gold(r) or r["sense_candidate"]] += 1 + return c + + +if __name__ == "__main__": + main() diff --git a/scripts/v2/sense_labels.py b/scripts/v2/sense_labels.py new file mode 100644 index 00000000..be6b0e2f --- /dev/null +++ b/scripts/v2/sense_labels.py @@ -0,0 +1,248 @@ +#!/usr/bin/env python3 +# Mirror of the operator-box Jev sense labeller (spec 009 T028, 2026-10-16); paths generalized. +# PROVENANCE: NEW 2026-09-25 PT (Danny 10:50 PT). Additive: writes only table observation_sense_v1. +"""Per-observation sense labels (SLANG_SENSE | OTHER_SENSE | UNKNOWN) via Jev, batched per term. + +Only observations of tracked terms (observations.term_canonical = terms.canonical_form) that have no +label under the current sense contract version are sent (incremental: the daily export only labels +new observations). + +Usage: sense_labels.py [--backfill] [--dry-run] [--max-cost-usd 1.0] +""" +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import sqlite3 +import subprocess +from datetime import datetime, timezone +from pathlib import Path + +HERE = Path(__file__).resolve().parent +DB = Path(os.environ.get("VERN_DB", "data/vernacular.sqlite3")) +SENSE_CONTRACT = Path(os.environ.get("SENSE_CONTRACT", HERE / "jev_sense_contract.json")) # spec 009 T028: point at a rebuilt-sense-v2 contract to emit use_mention +JEV_CLIENT = Path(os.environ.get("JEV_CLIENT", str(HERE / "jev_client.mjs"))) +CACHE = HERE / "receipts" / "jev-cache" +PRICE = 0.042 # USD per 1M input tokens (TypeSafe jev-1.13), output free +LABELS = ("SLANG_SENSE", "OTHER_SENSE", "UNKNOWN") +UM_SUFFIX = "_um" # spec 009 T028: per-post use/mention question id suffix + + +def contract() -> dict: + return json.loads(SENSE_CONTRACT.read_text()) + + +def contract_sha() -> str: + return hashlib.sha256(SENSE_CONTRACT.read_bytes()).hexdigest() + + +def ensure_table(con) -> None: + con.execute("""CREATE TABLE IF NOT EXISTS observation_sense_v1 ( + observation_id TEXT PRIMARY KEY, term_id TEXT NOT NULL, label TEXT NOT NULL, prob REAL, + contract_version TEXT NOT NULL, computed_at TEXT NOT NULL)""") + cols = {r[1] for r in con.execute("PRAGMA table_info(observation_sense_v1)")} + if "use_mention" not in cols: # additive (spec 009 T028); NULL = not labelled (read as USE under v1.4) + con.execute("ALTER TABLE observation_sense_v1 ADD COLUMN use_mention TEXT") + + +def load_labels(db: Path = DB, version: str | None = None) -> dict: + """{observation_id: (label, prob)} for the current sense contract version ({} if table absent).""" + version = version or contract()["version"] + con = sqlite3.connect(f"file:{db}?mode=ro", uri=True, timeout=120) + try: + rows = con.execute("SELECT observation_id, label, prob FROM observation_sense_v1 WHERE contract_version=?", + (version,)).fetchall() + except sqlite3.OperationalError as e: + if "no such table" not in str(e): + raise # 11:33 PT fix: a lock (discovery lane writing) must fail loudly, never read as "no rows" + rows = [] + con.close() + return {r[0]: (r[1], r[2]) for r in rows} + + +def pending(db: Path = DB) -> dict: + """{term_id: {"cf", "p", "obs": [(observation_id, text)]}} of unlabeled tracked-term observations.""" + have = load_labels(db) + con = sqlite3.connect(f"file:{db}?mode=ro", uri=True, timeout=120) + terms = {cf: (tid, json.loads(pl)) for tid, cf, pl in con.execute("SELECT term_id, canonical_form, payload FROM terms")} + out = {} + for oid, cf, pl, created in con.execute( + "SELECT observation_id, term_canonical, payload, created_at FROM observations ORDER BY created_at, observation_id"): + if cf not in terms or oid in have: + continue + tid, p = terms[cf] + o = json.loads(pl) + out.setdefault(tid, {"cf": cf, "p": p, "obs": []})["obs"].append((oid, o.get("text") or o.get("raw_excerpt") or "")) + con.close() + return out + + +def build_request(cf: str, p: dict, batch: list, c: dict) -> dict: + posts = [{"id": f"p{i}", "text": (txt or "")[: c["max_post_chars"]]} for i, (_, txt) in enumerate(batch)] + qt = c["question_template"] + qs = {x["id"]: {"type": qt["type"], "instructions": qt["instructions"].format(pid=x["id"], term=cf), + "criteria": qt["criteria"]} for x in posts} + if c.get("closed_set_use_mention"): # rebuilt-sense-v2: one extra USE/MENTION choice per post + for x in posts: + qs[x["id"] + UM_SUFFIX] = {"type": "choice", + "instructions": f"Post {x['id']} in STATE.posts: does it USE the term '{cf}' to convey meaning, " + "or MENTION it (define, quote, ask what it means, comment on its form)? " + f"A definition embedded inside a genuine use is USE. Judge only post {x['id']}.", + "criteria": qt.get("criteria_use_mention") or {k: k for k in c["closed_set_use_mention"]}} + state = {"term": cf, "recorded_slang_meaning": p.get("current_summary") or "", + "possible_meanings": p.get("possible_meanings") or [], "posts": posts} + return {"state": state, "questions": qs, "model": c.get("model", "jev-latest")} + + +def estimate(req: dict) -> float: + return len(json.dumps(req)) / 4 * 2 * 2 * PRICE / 1e6 + + +def _tok(v) -> int: + if isinstance(v, dict): + v = v.get("total", v.get("noCache", 0)) + try: + return int(v or 0) + except (TypeError, ValueError): + return 0 + + +def call(req: dict, csha: str, dry_run: bool) -> tuple[dict, bool]: + h = hashlib.sha256(json.dumps(req, sort_keys=True, ensure_ascii=False).encode()).hexdigest() + cp = CACHE / f"sense_{csha[:12]}_{h}.json" + if cp.exists(): + try: + return json.loads(cp.read_text()), True + except Exception: + pass + try: + pr = subprocess.run(["node", str(JEV_CLIENT)], input=json.dumps(req), capture_output=True, text=True, timeout=180) + res = json.loads((pr.stdout.strip().splitlines() or ["{}"])[-1]) + except Exception as e: + return {"ok": False, "error_class": "jev_call_error", "error": type(e).__name__}, False + if res.get("ok") and (res.get("backend") != "typesafe" or res.get("dry_run") or res.get("emulated")): + return {"ok": False, "error_class": "not_real_jev", "error": f"backend={res.get('backend')}"}, False + if res.get("ok") and not dry_run: + CACHE.mkdir(parents=True, exist_ok=True) + cp.write_text(json.dumps(res)) + return res, False + + +def parse_answer(answers: dict, pid: str, c: dict) -> tuple: + """(label, prob, use_mention) for one post. Fail closed: missing/out-of-set/low-prob sense -> UNKNOWN; + missing/out-of-set use_mention -> None (unlabelled). Contract v2 rule: a MENTION is never SLANG_SENSE.""" + min_p = float(c["min_top_probability"]) + a = answers.get(pid) + lab, prob = "UNKNOWN", None + if isinstance(a, dict) and a.get("choice") in c["closed_set"]: + try: + prob = float((a.get("probabilities") or {}).get(a["choice"])) + except (TypeError, ValueError): + prob = None + lab = a["choice"] if prob is not None and prob >= min_p else "UNKNOWN" + um = None + if c.get("closed_set_use_mention"): + b = answers.get(pid + UM_SUFFIX) + if isinstance(b, dict) and b.get("choice") in c["closed_set_use_mention"]: + try: + up = float((b.get("probabilities") or {}).get(b["choice"])) + except (TypeError, ValueError): + up = None + um = b["choice"] if up is not None and up >= min_p else None + if lab == "SLANG_SENSE" and um != "USE": # v2: MENTION -> OTHER_SENSE; unresolved -> UNKNOWN (fail closed) + lab, prob = ("OTHER_SENSE", None) if um == "MENTION" else ("UNKNOWN", prob) + return lab, prob, um + + +def label_pending(db: Path = DB, max_cost_usd: float = 1.0, dry_run: bool = False, allow_live: bool = True, + only: set | None = None) -> dict: + """Label every pending observation (only the given canonical forms if `only`; export --only scoping, 2026-09-25 11:13 PT). + Returns stats incl. terms whose labeling is incomplete (fail closed).""" + c = contract(); csha = contract_sha(); ver = c["version"]; min_p = float(c["min_top_probability"]) + todo = pending(db) + if only: + todo = {k: v for k, v in todo.items() if v["cf"] in only} + stats = {"sense_contract_version": ver, "sense_contract_sha256": csha, "pending_posts": sum(len(v["obs"]) for v in todo.values()), + "pending_terms": len(todo), "batches": 0, "live_calls": 0, "cache_hits": 0, "labeled": 0, + "labels": {k: 0 for k in LABELS}, "incomplete_terms": [], "errors": [], "usage_input_tokens": 0, + "cost_usd_estimated_pre_call": 0.0} + if not todo: + return stats + con = None if dry_run else sqlite3.connect(db, timeout=30) + if con: + with con: + ensure_table(con) + now = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + for tid, v in todo.items(): + obs = v["obs"] + for i in range(0, len(obs), c["batch_size"]): + batch = obs[i:i + c["batch_size"]] + req = build_request(v["cf"], v["p"], batch, c) + est = estimate(req) + if not allow_live: + h = hashlib.sha256(json.dumps(req, sort_keys=True, ensure_ascii=False).encode()).hexdigest() + if not (CACHE / f"sense_{csha[:12]}_{h}.json").exists(): + stats["errors"].append({"term": v["cf"], "error_class": "live_disabled"}); stats["incomplete_terms"].append(v["cf"]); break + elif stats["cost_usd_estimated_pre_call"] + est > max_cost_usd: + stats["errors"].append({"term": v["cf"], "error_class": "spend_cap"}); stats["incomplete_terms"].append(v["cf"]); break + res, hit = call(req, csha, dry_run) + stats["batches"] += 1 + if hit: + stats["cache_hits"] += 1 + else: + stats["live_calls"] += 1; stats["cost_usd_estimated_pre_call"] += est + stats["usage_input_tokens"] += _tok((res.get("usage") or {}).get("inputTokens")) + if not res.get("ok"): + stats["errors"].append({"term": v["cf"], "error_class": res.get("error_class"), "error": str(res.get("error", ""))[:120]}) + stats["incomplete_terms"].append(v["cf"]); break + rows = [] + for j, (oid, _) in enumerate(batch): + lab, prob, um = parse_answer(res.get("answers") or {}, f"p{j}", c) + rows.append((oid, tid, lab, prob, ver, now, um)) + stats["labels"][lab] += 1 + if um: + stats.setdefault("use_mention", {}).setdefault(um, 0) + stats["use_mention"][um] += 1 + stats["labeled"] += len(rows) + if con: + with con: + con.executemany("INSERT INTO observation_sense_v1(observation_id, term_id, label, prob, contract_version, computed_at, use_mention) " + "VALUES (?,?,?,?,?,?,?) ON CONFLICT(observation_id) DO UPDATE SET term_id=excluded.term_id, " + "label=excluded.label, prob=excluded.prob, contract_version=excluded.contract_version, " + "computed_at=excluded.computed_at, use_mention=excluded.use_mention", rows) + if con: + con.close() + stats["cost_usd_actual_est"] = round(stats["usage_input_tokens"] * PRICE / 1e6, 6) + stats["cost_usd_estimated_pre_call"] = round(stats["cost_usd_estimated_pre_call"], 6) + stats["incomplete_terms"] = sorted(set(stats["incomplete_terms"])) + return stats + + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--backfill", action="store_true", help="one-time backfill of all unlabeled tracked-term observations") + ap.add_argument("--dry-run", action="store_true", help="count pending only; no Jev calls, no writes") + ap.add_argument("--max-cost-usd", type=float, default=1.0) + a = ap.parse_args() + if a.dry_run: + pd = pending() + reqs = [build_request(v["cf"], v["p"], v["obs"][i:i + contract()["batch_size"]], contract()) + for v in pd.values() for i in range(0, len(v["obs"]), contract()["batch_size"])] + print(json.dumps({"pending_posts": sum(len(v["obs"]) for v in pd.values()), "pending_terms": len(pd), + "batches": len(reqs), "cost_usd_estimated_pre_call": round(sum(map(estimate, reqs)), 6)})) + else: + cap = a.max_cost_usd if a.backfill else min(a.max_cost_usd, 1.0) + s = label_pending(max_cost_usd=cap) + s.setdefault("usage_input_tokens", 0) + s.setdefault("cost_usd_actual_est", 0.0) + run = datetime.now().strftime("%Y%m%d-%H%M%S") + (HERE / "receipts").mkdir(exist_ok=True) + (HERE / "receipts" / f"sense-{'backfill' if a.backfill else 'run'}-{run}.json").write_text(json.dumps(s, indent=2)) + with (HERE / "ledger.jsonl").open("a") as f: + f.write(json.dumps({"run_id": f"sense-{run}", "kind": "sense_backfill" if a.backfill else "sense_run", + "max_cost_usd": cap, **{k: s.get(k) for k in ("pending_posts", "batches", "live_calls", "labeled", + "labels", "incomplete_terms", "usage_input_tokens", "cost_usd_estimated_pre_call", "cost_usd_actual_est", + "sense_contract_sha256", "use_mention")}}) + "\n") + print(json.dumps(s, indent=1)) diff --git a/specs/009-ruling-label-taxonomy/contracts/jev_sense_contract.v2.json b/specs/009-ruling-label-taxonomy/contracts/jev_sense_contract.v2.json new file mode 100644 index 00000000..7014ce62 --- /dev/null +++ b/specs/009-ruling-label-taxonomy/contracts/jev_sense_contract.v2.json @@ -0,0 +1,62 @@ +{ + "_publication": { + "source_file": "jev_sense_contract.json", + "source_sha256": "ab20da884e08ffb79feec8bc9b8ab213b450294434d6fb803a2db7043b10ca8c", + "note": "Published copy for documentation. Sanitized on 2026-09-25 PT: local file paths, cache paths, account names and people's names were removed or generalized; the question text, closed sets, thresholds and fail-closed rules are unchanged. This contract embeds NO real posts, X post text, author handles, term example posts, holdout ids or database contents: the {term}/{pid}/STATE fields are template placeholders filled at run time. The illustrative state under 'synthetic_example' (where present) is invented and clearly synthetic. v2 adds use_mention (2026-10-16)." + }, + "contract_id": "vernacular-observation-sense", + "version": "rebuilt-sense-v2", + "provenance": "NEW 2026-09-25 10:53 PT (no original existed; rebuilt-series label for consistency). Per-post SLANG_SENSE vs OTHER_SENSE labels, used to compute sense_purity and to count evidence metrics on slang-sense posts only. General instructions; no term-specific hints. | v2 2026-10-16 (metrics-rule-v1.5, Danny 11:36 AM PT): adds use_mention; mentions are not SLANG_SENSE.", + "approved_by": "Danny, 2026-10-16 11:36 AM PT (spec 009 Q3)", + "model": "jev-latest", + "batch_size": 25, + "max_post_chars": 280, + "min_top_probability": 0.5, + "closed_set": [ + "SLANG_SENSE", + "OTHER_SENSE" + ], + "fail_closed_rules": [ + "Call-level Jev error/timeout/not-real-typesafe: no rows written for that batch; the term's observations stay unlabeled and the export fails the term closed (note untouched).", + "Per post: answer missing, outside closed_set, or top probability < min_top_probability -> stored as UNKNOWN (excluded from slang-sense metrics; counted in sense_unknown_share)." + ], + "question_template": { + "type": "choice", + "instructions": "Post {pid} in STATE.posts: is the term '{term}' used there in its slang sense (the recorded slang meaning in STATE, or a close slang variant/extension of it), or is it an unrelated same-spelling use (a name, school, team, company, product, ticker/token symbol, technical or scientific term, the literal ordinary word, part of another word, or another language)? Also answer use_mention: MENTION if the post draws attention to the word itself (defines, quotes, asks what it means, comments on its form) rather than using it to convey meaning; otherwise USE. A definition embedded inside a genuine use is USE. A MENTION is never SLANG_SENSE: label its sense OTHER_SENSE. Judge only post {pid}.", + "criteria": { + "SLANG_SENSE": "uses the term in its slang sense (USE only)", + "OTHER_SENSE": "unrelated same-spelling use (name, school, company, ticker, technical term, literal ordinary word, other language), not the slang sense; also any MENTION of the term" + }, + "criteria_use_mention": { + "USE": "the term conveys meaning in the post", + "MENTION": "the post is about the word itself (definition, quotation, question, form)" + } + }, + "related": "rebuilt-sense-anchored-v1: same question, but for terms with an operator definition the definition is passed as the anchor sense and a slang sense not in the definition counts as OTHER_SENSE (labels keyed by definition sha256).", + "synthetic_example": { + "_synthetic": true, + "STATE": { + "term": "zorblet", + "meaning": "SYNTHETIC: impressive", + "posts": { + "p1": "SYNTHETIC: that fit is zorblet", + "p2": "SYNTHETIC: Zorblet Inc. reports Q3 earnings", + "p3": "SYNTHETIC: what does \"zorblet\" even mean? it means impressive" + } + }, + "expected_labels": { + "p1": "SLANG_SENSE", + "p2": "OTHER_SENSE", + "p3": "OTHER_SENSE" + }, + "expected_use_mention": { + "p1": "USE", + "p2": "USE", + "p3": "MENTION" + } + }, + "closed_set_use_mention": [ + "USE", + "MENTION" + ] +} \ No newline at end of file diff --git a/specs/009-ruling-label-taxonomy/tasks.md b/specs/009-ruling-label-taxonomy/tasks.md index 97b74be9..672a0ebd 100644 --- a/specs/009-ruling-label-taxonomy/tasks.md +++ b/specs/009-ruling-label-taxonomy/tasks.md @@ -33,6 +33,6 @@ - [x] T026 Re-window excerpts for the 85 repair rows (50 TARGET_ABSENT + 3 review + 32 flagged), then re-queue (rulings/repair/2026-10-16-target-absent.txt on the operator box). - [ ] T027 (BLOCKED: remote scrimshawlife-ctrl/Hyperlex is archived/read-only, push 403; v1.5 lives in this spec) Push Hyperlex-archive metrics-rule-v1.5 commit (needs approval; that remote is public). -- [ ] T028 Implement use_mention in the Jev sense labelling runtime. +- [x] T028 Implement use_mention in the Jev sense labelling runtime. (2026-10-16: scripts/v2/sense_labels.py, PR #31; the live runtime emits it once pointed at the v2 contract) - T026 done 2026-10-16: queue excerpts are windowed around the target (`window_excerpt`, 500 chars); `ruling_queue.py repair` re-queues landed rows with original_text + previous_label kept. Repair queue 2026-10-16-repair: 85 rows (test 15, val 14, train 56) on the operator box. Re-ruling a TARGET_ABSENT row as non-R moves its status to status_history. diff --git a/tests/test_export_window_v2.py b/tests/test_export_window_v2.py new file mode 100644 index 00000000..b954d959 --- /dev/null +++ b/tests/test_export_window_v2.py @@ -0,0 +1,57 @@ +"""Spec 009 T026: export context is the target-centred window; R row statuses are never gold.""" +import json, os, sys, tempfile +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "scripts", "v2")) +import export_splits as ex +import ruling_queue as rq + + +def _row(rid, term, text, split="test", sense="SLANG_SENSE", **h): + hr = {"source": "human", "sense": sense, "split": split, **h} + return {"record_id": rid, "term": term, "term_family": "fam-a", "contextual_use": text, + "content_sha256": rid, "sense_candidate": "SLANG_SENSE", "human_ruling": hr, + "mutation_lineage": {"lineage_family": "general-slang"}, "model_proposal": {}, "sensitivity": {}} + + +def _run(rows): + d = tempfile.mkdtemp() + src = os.path.join(d, "in.jsonl") + with open(src, "w") as fh: + for r in rows: + fh.write(json.dumps(r) + "\n") + ex.main(src=src, out=d) + out = {} + for s in ("train", "val", "test"): + out.update({x["record_id"]: x for x in map(json.loads, open(os.path.join(d, s + ".jsonl")))}) + return out, json.load(open(os.path.join(d, "export_report.json"))), d + + +def test_context_is_target_window_not_head(): + text = "x" * 2000 + " zorbly " + "y" * 2000 + out, _, _ = _run([_row("r1", "zorbly", text)]) + ctx = out["r1"]["context"] + assert "zorbly" in ctx and len(ctx) <= rq.EXCERPT_CHARS + 2 + assert out["r1"]["context_match"] == "word" + + +def test_short_text_unchanged(): + out, _, _ = _run([_row("r1", "zorbly", "so zorbly")]) + assert out["r1"]["context"] == "so zorbly" + + +def test_non_gold_row_status_excluded(): + rows = [_row("ta", "zorbly", "a zorbly", row_status="TARGET_ABSENT"), + _row("ue", "zorbly", "b zorbly", row_status="UNUSABLE_EVIDENCE"), + _row("ok", "zorbly", "c zorbly", use_mention="USE")] + out, rep, d = _run(rows) + gold = {json.loads(l)["record_id"] for l in open(os.path.join(d, "gold_test.jsonl"))} + assert gold == {"ok"} + assert "ta" not in out and "ue" not in out + assert rep["dropped_non_gold_row_status"] == 2 + assert out["ok"]["use_mention"] == "USE" + assert rep["non_gold_row_status_rows"] == 2 + + +def test_gold_helper_matches_ruling_queue(): + for st in rq.NON_GOLD_ROW_STATUS: + assert ex.gold({"human_ruling": {"source": "human", "sense": "OTHER_SENSE", "row_status": st}}) is None + assert ex.gold({"human_ruling": {"source": "human", "sense": "OTHER_SENSE"}}) == "OTHER_SENSE" diff --git a/tests/test_sense_use_mention_v2.py b/tests/test_sense_use_mention_v2.py new file mode 100644 index 00000000..43377742 --- /dev/null +++ b/tests/test_sense_use_mention_v2.py @@ -0,0 +1,65 @@ +"""Spec 009 T028: the Jev sense labeller emits use_mention under rebuilt-sense-v2.""" +import json, os, sqlite3, sys, tempfile +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "scripts", "v2")) +import sense_labels as sl + +V2 = json.load(open(os.path.join(os.path.dirname(__file__), "..", "specs", "009-ruling-label-taxonomy", "contracts", "jev_sense_contract.v2.json"))) +V1 = {k: v for k, v in V2.items() if k not in ("closed_set_use_mention",)} +V1["version"] = "rebuilt-sense-v1" + + +def _a(choice, p): + return {"choice": choice, "probabilities": {choice: p}} + + +def test_v2_request_has_use_mention_question_per_post(): + req = sl.build_request("zorbly", {}, [("o1", "t1"), ("o2", "t2")], V2) + assert set(req["questions"]) == {"p0", "p1", "p0_um", "p1_um"} + assert set(req["questions"]["p0_um"]["criteria"]) == {"USE", "MENTION"} + + +def test_v1_request_unchanged(): + req = sl.build_request("zorbly", {}, [("o1", "t1")], V1) + assert set(req["questions"]) == {"p0"} + + +def test_parse_use(): + assert sl.parse_answer({"p0": _a("SLANG_SENSE", 0.9), "p0_um": _a("USE", 0.8)}, "p0", V2) == ("SLANG_SENSE", 0.9, "USE") + + +def test_mention_is_never_slang_sense(): + lab, _, um = sl.parse_answer({"p0": _a("SLANG_SENSE", 0.9), "p0_um": _a("MENTION", 0.9)}, "p0", V2) + assert (lab, um) == ("OTHER_SENSE", "MENTION") + + +def test_missing_or_low_use_mention_fails_closed_to_none(): + assert sl.parse_answer({"p0": _a("OTHER_SENSE", 0.9)}, "p0", V2)[2] is None + assert sl.parse_answer({"p0": _a("OTHER_SENSE", 0.9), "p0_um": _a("MENTION", 0.2)}, "p0", V2)[2] is None + assert sl.parse_answer({"p0": _a("OTHER_SENSE", 0.9), "p0_um": _a("BOTH", 0.9)}, "p0", V2)[2] is None + + +def test_v1_parse_has_no_use_mention(): + assert sl.parse_answer({"p0": _a("SLANG_SENSE", 0.9), "p0_um": _a("MENTION", 0.9)}, "p0", V1) == ("SLANG_SENSE", 0.9, None) + + +def test_low_sense_prob_is_unknown(): + assert sl.parse_answer({"p0": _a("SLANG_SENSE", 0.3)}, "p0", V2)[0] == "UNKNOWN" + + +def test_ensure_table_adds_column_additively(): + db = os.path.join(tempfile.mkdtemp(), "v.sqlite3") + con = sqlite3.connect(db) + con.execute("CREATE TABLE observation_sense_v1 (observation_id TEXT PRIMARY KEY, term_id TEXT NOT NULL, label TEXT NOT NULL, " + "prob REAL, contract_version TEXT NOT NULL, computed_at TEXT NOT NULL)") + con.execute("INSERT INTO observation_sense_v1 VALUES ('o1','t','SLANG_SENSE',1.0,'rebuilt-sense-v1','x')") + sl.ensure_table(con); sl.ensure_table(con) + assert con.execute("SELECT label, use_mention FROM observation_sense_v1").fetchall() == [("SLANG_SENSE", None)] + + +def test_slang_with_unresolved_use_mention_is_unknown(): + for um in ({}, {"p0_um": _a("BOTH", 0.9)}, {"p0_um": _a("MENTION", 0.3)}): + assert sl.parse_answer({"p0": _a("SLANG_SENSE", 0.9), **um}, "p0", V2)[0] == "UNKNOWN" + + +def test_mention_override_clears_prob(): + assert sl.parse_answer({"p0": _a("SLANG_SENSE", 0.9), "p0_um": _a("MENTION", 0.9)}, "p0", V2) == ("OTHER_SENSE", None, "MENTION")