Complete M2 validation and lock the G1 evaluation protocol

Run and record both blind LLM validation passes and the external
cross-checks. Freeze the evaluation inputs, well splits, and reporting
scope with a SHA-256 checksum.

Use NPT definition b for DDR-code prediction with definition a as a
sensitivity analysis. Retain the class reporting thresholds and record
the empty set of eligible classes. Make T4 and OCR fidelity the headline
analyses and align the progress report and project documentation.

Co-authored-by: OpenAI Codex <noreply@openai.com>
This commit is contained in:
2026-11-18 04:13:13 +00:00
parent 5ffc8b3008
commit 2b59d635ce
24 changed files with 3305 additions and 338 deletions

View File

@@ -34,19 +34,8 @@ def out_dir() -> Path:
return paths.outputs_dir() / "audit" / "trial_100"
def load() -> pd.DataFrame:
d = paths.outputs_dir() / "labels"
x = pd.read_parquet(d / "t2_inputs.parquet")
lab = pd.read_parquet(d / "t2_labels.parquet")[["act_id", "npt_a", "npt_b", "cause_a", "cause_b"]]
ops = pd.read_parquet(d / "t1_activities.parquet")[["act_id", "op_class"]]
x = x.sort_values(["report_id", "seq"])
g = x.groupby("report_id")["comments"]
x["prev_comment"], x["next_comment"] = g.shift(1), g.shift(-1)
return x.merge(lab, on="act_id", validate="1:1").merge(ops, on="act_id", validate="1:1")
def sample() -> int:
x = load()
x = audit.load_activity_labels()
x["zone"] = audit.zone(x["npt_a"], x["npt_b"])
cls = x["cause_a"].where(x["zone"] == "a", x["cause_b"].where(x["zone"] == "b_only", x["op_class"]))
x["stratum"] = x["zone"] + "/" + cls

200
scripts/10_m2_agreement.py Normal file
View File

@@ -0,0 +1,200 @@
"""Score M2 agreement, abstentions and repeatability from completed blind ratings."""
from __future__ import annotations
import argparse
from datetime import datetime
from itertools import combinations
from statistics import median
import pandas as pd
import yaml
from volve_dia import audit, m2
def fleiss(labels: pd.DataFrame) -> dict:
complete = labels.dropna()
n, raters = complete.shape
if not n:
return {"n": 0, "kappa": None}
counts = complete.apply(lambda row: row.value_counts(), axis=1).fillna(0)
observed = float(((counts ** 2).sum(axis=1) - raters).mean() / (raters * (raters - 1)))
expected = float(((counts.sum(axis=0) / (n * raters)) ** 2).sum())
return {"n": n, "kappa": (observed - expected) / (1 - expected) if expected < 1 else None}
def load_panel(pass_number: int, sample: dict, config: dict, items: pd.Index) -> tuple[dict, dict]:
root = m2.directory() / "ratings"
ratings, provenance = {}, {}
families = set()
deadline_delta = m2.repeatability_gap() if pass_number == 2 else None
for name, model in config["raters"].items():
path = root / f"pass{pass_number}" / f"{name}.json"
state = m2.read_json(path)
if not state.get("completed_at") or set(state["responses"]) != set(items):
raise ValueError(f"Incomplete ratings: {path}")
source = state["provenance"]
if source["model"] != model or source["settings"]["spec_sha256"] != m2.digest(m2.VALIDATION):
raise ValueError(f"Rating model or specification changed: {path}")
for kind in ("activity", "section"):
for key in ("blind_sha256", "prompt_sha256"):
if source["blind"][kind][key] != sample[kind][key]:
raise ValueError(f"Rating input differs: {path}")
timing = {}
if deadline_delta is not None:
first = m2.read_json(root / "pass1" / path.name)
elapsed = datetime.fromisoformat(state["started_at"]) - datetime.fromisoformat(first["completed_at"])
if first["provenance"] != source or elapsed < deadline_delta:
raise ValueError(f"Second-pass settings or timing differ: {path}")
timing["elapsed_hours_after_pass1"] = elapsed.total_seconds() / 3600
ratings[name] = pd.DataFrame.from_dict(state["responses"], orient="index").reindex(items)
provenance[name] = {"ratings_sha256": m2.digest(path), "completed_at": state["completed_at"],
"started_at": state["started_at"], "model": model,
"weights_sha256": source["weights_sha256"], **timing}
families.add(model["family"])
if len(families) < 3:
raise ValueError("At least three distinct model families are required.")
return ratings, provenance
def rated_labels(r: pd.DataFrame, name: str) -> pd.Series:
if name.startswith("npt_"):
return r["npt"].map({"y": "yes", "n": "no"})
if name.startswith("cause_"):
return r["cause"].replace("none", "unspecified").where(r["npt"].eq("y"), "none").where(r["npt"].ne("?"))
return r[name].replace("?", None)
def metrics(reference: pd.Series, rating: pd.Series, weight: pd.Series) -> dict:
return {"raw": audit.agreement(rating, reference),
"weighted": audit.agreement(rating, reference, weight),
"weighted_kappa_full_precision": audit.cohen_kappa(rating, reference, weight),
"abstained": int(rating.isna().sum()),
"weighted_abstention_share": float(weight[rating.isna()].sum() / weight.sum())}
def class_metrics(reference: pd.Series, labels: pd.DataFrame, weight: pd.Series) -> dict:
result = {}
for category in sorted(reference.dropna().unique()):
positive = reference.eq(category)
cases = {}
for name, rating in labels.items():
valid = rating.notna()
matched = rating.eq(category).where(valid)
cases[name] = metrics(positive, matched, weight) | {"rated_code_positive": int((positive & valid).sum())}
kappas = [v["weighted_kappa_full_precision"] for v in cases.values()
if v["weighted_kappa_full_precision"] is not None]
majority = labels.notna().sum(axis=1).gt(len(labels.columns) / 2)
result[category] = {"sample_code_positive": int(positive.sum()),
"rated_items": int((positive & majority).sum()), "defined_raters": len(kappas),
"median_weighted_kappa": median(kappas) if kappas else None, "per_rater": cases}
return result
def score_target(reference: pd.Series, key: pd.DataFrame, labels: pd.DataFrame) -> dict:
weight = key["weight"]
per_rater = {name: metrics(reference, r, weight) for name, r in labels.items()}
kappas = [row["weighted_kappa_full_precision"] for row in per_rater.values()
if row["weighted_kappa_full_precision"] is not None]
return {
"items": len(key),
"median_weighted_kappa": median(kappas) if kappas else None,
"defined_raters": len(kappas),
"vs_code": per_rater,
"by_class": class_metrics(reference, labels, weight),
"by_well": {w: {name: metrics(reference.loc[ix], r.loc[ix], weight.loc[ix])
for name, r in labels.items()} for w, ix in key.groupby("well").groups.items()},
"pairwise": {f"{a}/{b}": {"raw": audit.agreement(labels[a], labels[b]),
"weighted": audit.agreement(labels[a], labels[b], weight)}
for a, b in combinations(labels, 2)},
"fleiss": fleiss(labels),
}
def reference_targets(activity: pd.DataFrame, section: pd.DataFrame) -> dict:
operations = activity.loc[activity["op_class"].ne("interruption")]
targets = {"operation": (operations, operations["op_class"]), "section": (section, section["section"])}
for definition in ("a", "b"):
targets[f"npt_{definition}"] = (activity, activity[f"npt_{definition}"].map({True: "yes", False: "no"}))
targets[f"cause_{definition}"] = (activity, activity[f"cause_{definition}"].fillna("none"))
return targets
def add_pooled_classes(target: str, reference: pd.Series, labels: pd.DataFrame, key: pd.DataFrame) -> dict:
draft = m2.PROTOCOL
preview = yaml.safe_load(draft.read_text(encoding="utf-8"))["class_evaluability"]["preview"]
rules = preview["t1_section"]["merges"] if target == "section" else preview["t2_cause"]["merges"]
pooled = {}
for parent, children in rules.items():
mapping = dict.fromkeys(children, parent)
pooled[parent] = class_metrics(reference.replace(mapping), labels.replace(mapping), key["weight"])[parent]
return pooled
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("pass_number", type=int, choices=(1, 2))
pass_number = parser.parse_args().pass_number
root = m2.directory()
sample = m2.read_json(root / "sample.json")
keys = {}
for kind in ("activity", "section"):
path = root / f"key_{kind}.csv"
if m2.digest(path) != sample[kind]["key_sha256"]:
raise ValueError(f"Frozen sample key changed: {path}")
keys[kind] = pd.read_csv(path, dtype={"section": str}).set_index("item")
activity, section = keys["activity"], keys["section"]
items = activity.index.append(section.index)
config = m2.spec()
raters, provenance = load_panel(pass_number, sample, config, items)
first_raters = load_panel(1, sample, config, items)[0] if pass_number == 2 else {}
wait = activity.loc[activity["op_class"].eq("wait")]
result = {"pass": pass_number, "provenance": provenance, "targets": {},
"wait_outside_interruption": {
"items": len(wait), "code_npt_b": int(wait["npt_b"].sum()),
"responses": {name: r.loc[wait.index, "npt"].value_counts().to_dict() for name, r in raters.items()},
}}
disagreements = []
for target, (key, reference) in reference_targets(activity, section).items():
labels = pd.DataFrame({name: rated_labels(r.loc[key.index], target) for name, r in raters.items()})
scored = score_target(reference, key, labels)
if target == "section" or target.startswith("cause_"):
scored["pooled_classes"] = add_pooled_classes(target, reference, labels, key)
if target == "section":
scored["by_source"] = {
src: score_target(reference.loc[ix], key.loc[ix], labels.loc[ix])
for src, ix in key.groupby("source").groups.items()
}
if first_raters:
scored["within_rater_vs_pass1"] = {
name: metrics(rated_labels(r.loc[key.index], target), labels[name], key["weight"])
for name, r in first_raters.items()
}
result["targets"][target] = scored
different = labels.isna().any(axis=1) | labels.ne(reference, axis=0).any(axis=1)
disagreements.append(key.loc[different].join(labels.loc[different]).assign(
target=target, code_label=reference.loc[different]).reset_index())
if pass_number == 1:
a, b = (result["targets"][f"npt_{d}"] for d in ("a", "b"))
if a["defined_raters"] == b["defined_raters"] == len(raters):
delta = b["median_weighted_kappa"] - a["median_weighted_kappa"]
result["npt_candidate"] = {"primary": "b" if delta >= 0.02 else "a", "delta_b_minus_a": delta}
else:
result["npt_candidate"] = None
else:
result["pass1_agreement_sha256"] = m2.digest(root / "agreement_pass1.json")
result["minimum_repeat_gap_days"] = m2.repeatability_gap().days
pd.concat(disagreements).to_csv(root / f"disagreements_pass{pass_number}.csv", index=False)
m2.write_json(root / f"agreement_pass{pass_number}.json", result)
for target, row in result["targets"].items():
print(f"{target}: median weighted kappa {row['median_weighted_kappa']}, Fleiss {row['fleiss']}")
if pass_number == 1:
print(f"First-pass NPT selection: {result['npt_candidate']}")
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,159 @@
"""Reproduce the DrillScribe, Anatoly5ms and TSPP checks on the M1 tables."""
from __future__ import annotations
import argparse
import re
from collections import Counter
from pathlib import Path
import pandas as pd
import yaml
from volve_dia import m2, paths
DRILLSCRIBE = "0abca0097b57823898b520b6fec491d408fa33e7"
ANATOLY5MS = "a0e16ed97f64d142ca99eb8e4d73a89c05e82eec"
TSPP = "1297d8b274042904fbd0fb95f2521a953eedbab6"
CELL_KEYS = ["wellbore", "cell"]
CAUSE_MAP = {"lost_circulation": "lost_circulation", "well_control": "well_control", "stuck_pipe": "stuck_fishing"}
CASES = {
"TSPP2": ("15/9-F-4", "2007-10-23 16:59"),
"TSPP3": ("15/9-F-9 A", "2009-07-04 07:28"),
"TSPP4": ("15/9-F-1", None),
}
def drillscribe_check(activities: pd.DataFrame, reports: pd.DataFrame, source: Path) -> dict:
columns = ["well", "raw_label", "t_start", "n_lines"]
external = pd.read_csv(source, usecols=columns + ["is_npt"])
external["t_start"] = pd.to_datetime(external["t_start"], utc=True)
src = activities.loc[activities["comments"].str.strip().fillna("").ne("")].copy()
src["t_start"] = pd.to_datetime(src["start_utc"], utc=True)
src["well"] = src["report_id"].map(reports.set_index("report_id")["nameWell"])
src = src.sort_values(["well", "t_start"], kind="stable")
ends = src["well"].ne(src["well"].shift()) | src["stateDetailActivity"].ne(src["stateDetailActivity"].shift())
ours = src.groupby(ends.cumsum()).agg(well=("well", "first"), raw_label=("stateDetailActivity", "first"),
t_start=("t_start", "min"), n_lines=("report_id", "size"))
expected, actual = (Counter(df[columns].itertuples(index=False, name=None)) for df in (external, ours))
return {"revision": DRILLSCRIBE, "source_sha256": m2.digest(source), "external_episodes": len(external),
"rebuilt_episodes": len(ours), "matched": sum((expected & actual).values()),
"external_only": sum((expected - actual).values()), "rebuilt_only": sum((actual - expected).values()),
"external_npt_episodes": int(external["is_npt"].sum()), "activities": len(src),
"wellbores": int(src["wellbore"].nunique()), "key": columns}
def text_strength(comments: pd.Series, rules: dict) -> pd.Series:
# Phrase-level matching adapted from Anatoly5ms, MIT. Upstream rules are read from its pinned local checkout.
expr = {name: [re.compile(pattern, re.IGNORECASE) for pattern in rules[name + "_patterns"]]
for name in ("strong", "weak", "exclude")}
def match(comment: str) -> str:
strengths = set()
for clause in re.split(r"[.;\n]+|,\s+", comment):
if any(pattern.search(clause) for pattern in expr["exclude"]):
continue
strengths.update(name for name in ("strong", "weak") if any(p.search(clause) for p in expr[name]))
return "strong" if "strong" in strengths else ("weak" if "weak" in strengths else "none")
return comments.fillna("").map(match)
def overlap(left: pd.Series, right: pd.Series) -> dict:
both, union = int((left & right).sum()), int((left | right).sum())
return {"n": len(left), "text_positive": int(left.sum()), "code_positive": int(right.sum()), "both": both,
"text_only": int((left & ~right).sum()), "code_only": int((~left & right).sum()),
"jaccard": both / union if union else None}
def cell_hits(frame: pd.DataFrame, mask: pd.Series, universe: pd.DataFrame) -> pd.Series:
keys = pd.MultiIndex.from_frame(frame.loc[mask & frame["cell"].notna(), CELL_KEYS])
return pd.Series(pd.MultiIndex.from_frame(universe[CELL_KEYS]).isin(keys), index=universe.index)
def anatoly_check(source: Path, activities: pd.DataFrame, labels: Path, witsml: Path, out: Path) -> dict:
rules = yaml.safe_load(source.read_text(encoding="utf-8"))["labeler"]["complication_rules"]
t3 = pd.read_parquet(labels / "t3_activities.parquet")
t2 = pd.read_parquet(labels / "t2_labels.parquet", columns=["act_id", "cause_a", "cause_b"])
cells = pd.read_parquet(labels / "t3_cells.parquet")
logs = pd.read_parquet(witsml / "wellbores.parquet")
eligible = logs.loc[logs["in_ddr"] & logs["n_time_logs"].gt(0), "wellbore"]
primary = cells["in_own_hole"] & cells["wellbore"].isin(eligible)
frame = t3.merge(t2, on="act_id", validate="one_to_one").merge(
activities[["report_id", "seq", "comments"]], on=["report_id", "seq"], validate="one_to_one")
matches = pd.DataFrame({name: text_strength(frame["comments"], rule) for name, rule in rules.items()})
counts = {name: matches[name].value_counts().to_dict() for name in matches}
result = {"revision": ANATOLY5MS, "source_sha256": m2.digest(source),
"scope": "Upstream comment regex only. The Volve-DIA activity MD and 10 m grid are shared.",
"strength_by_rule": counts, "thresholds": {}}
columns = ["act_id", "wellbore", "cell", "depth_class", "npt_a", "npt_b", "cause_a", "cause_b"]
evidence = frame[columns].join(matches)
evidence.loc[matches.ne("none").any(axis=1)].to_csv(out / "anatoly_text_hits.csv", index=False)
for threshold in ("strong", "strong_or_weak"):
positive = matches.eq("strong") if threshold == "strong" else matches.ne("none")
any_text = positive.any(axis=1)
by_definition = {}
for definition in ("a", "b"):
reference = frame[f"npt_{definition}"]
by_definition[definition] = {
"activity_all": overlap(any_text, reference),
"cells_all": overlap(cell_hits(frame, any_text, cells), cells[f"label_{definition}"]),
"cells_own_hole_with_witsml": overlap(cell_hits(frame, any_text, cells.loc[primary]),
cells.loc[primary, f"label_{definition}"]),
"matched_cause_activity": {
r: overlap(positive[r], frame[f"cause_{definition}"].eq(c)) for r, c in CAUSE_MAP.items()},
"matched_cause_cells_own_hole_with_witsml": {
r: overlap(cell_hits(frame, positive[r], cells.loc[primary]),
cell_hits(frame, frame[f"cause_{definition}"].eq(c), cells.loc[primary]))
for r, c in CAUSE_MAP.items()},
}
result["thresholds"][threshold] = by_definition
return result
def tspp_check(activities: pd.DataFrame, source: Path, out: Path) -> dict:
records = {}
for case, (wellbore, onset) in CASES.items():
file = source / f"{case}.csv"
times = pd.to_datetime(pd.read_csv(file, usecols=["date"])["date"], utc=True)
bounds = times.min() - pd.Timedelta(hours=3), times.max() + pd.Timedelta(hours=3)
rows = activities.loc[activities["wellbore"].eq(wellbore)
& (activities["end_utc"] > bounds[0]) & (activities["start_utc"] < bounds[1])]
keywords = r"stuck|jarr|pack.?off|overpull|over pull|tight"
hits = rows["comments"].str.contains(keywords, case=False, na=False)
records[case] = {"wellbore": wellbore, "source_sha256": m2.digest(file), "source_rows": len(times),
"reported_onset_timezone_unspecified": onset,
"window_utc_assumed": [t.isoformat() for t in bounds],
"ddr_rows": len(rows), "ddr_code_counts": rows["stateDetailActivity"].value_counts().to_dict(),
"ddr_keyword_rows": int(hits.sum())}
rows[["report_id", "seq", "start_utc", "end_utc", "md", "stateDetailActivity", "comments"]].to_csv(
out / f"{case}_ddr.csv", index=False)
return {"revision": TSPP, "cases": records, "purpose": "qualitative case-level checks"}
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--third-party", type=Path, default=paths.REPO_ROOT / "data" / "third_party")
third_party = parser.parse_args().third_party
ddr = paths.outputs_dir() / "ddr"
activities = pd.read_parquet(ddr / "activities.parquet")
reports = pd.read_parquet(ddr / "reports.parquet", columns=["report_id", "nameWell"])
out = m2.directory() / "cross_checks"
out.mkdir(parents=True, exist_ok=True)
result = {
"drillscribe": drillscribe_check(activities, reports, third_party / "drillscribe/repo/data/episodes.csv"),
"anatoly5ms": anatoly_check(third_party / "anatoly5ms_drilling_complication/repo/config/config.yaml",
activities, paths.outputs_dir() / "labels", paths.outputs_dir() / "witsml", out),
"tspp": tspp_check(activities, third_party / "tspp_stuck_pipe_cao2024/repo/TSPP/TSPP", out),
}
m2.write_json(out / "summary.json", result)
print(f"DrillScribe: {result['drillscribe']['matched']}/{result['drillscribe']['external_episodes']} episodes")
for mode, definitions in result["anatoly5ms"]["thresholds"].items():
for definition, bases in definitions.items():
print(f"Anatoly5ms {mode}, NPT {definition}: {bases['cells_own_hole_with_witsml']}")
for case, data in result["tspp"]["cases"].items():
print(f"{case}: {data['ddr_rows']} DDR rows, {data['ddr_code_counts'].get('stuck equipment', 0)} stuck codes")
if __name__ == "__main__":
main()

264
scripts/10_m2_protocol.py Normal file
View File

@@ -0,0 +1,264 @@
"""Recompute G1 inputs and split coverage, then freeze the evaluation protocol after both M2 passes."""
from __future__ import annotations
import argparse
import fcntl
from datetime import datetime
from pathlib import Path
import pandas as pd
import yaml
from volve_dia import m2, paths
PROTOCOL = m2.PROTOCOL
CHECKSUM = PROTOCOL.with_suffix(".yaml.sha256")
def targets(root: Path, draft: dict) -> dict[str, pd.DataFrame]:
reports = pd.read_parquet(root / "t1_reports.parquet")
reports = reports.loc[reports["scope"].eq("drilling_day")].copy()
reports["source"] = reports["filled_by"].eq("diaHole").map({True: "published", False: "filled"})
activity = pd.read_parquet(root / "t1_activities.parquet")
npt = pd.read_parquet(root / "t2_labels.parquet")
result = {"section": reports[["well", "section"]].rename(columns={"section": "label"}),
"section_published": reports.loc[reports["source"].eq("published"), ["well", "section"]]
.rename(columns={"section": "label"}),
"section_filled": reports.loc[reports["source"].eq("filled"), ["well", "section"]]
.rename(columns={"section": "label"}),
"operation": activity.loc[activity["op_class"].ne("interruption"), ["well", "op_class"]]
.rename(columns={"op_class": "label"})}
for definition in ("a", "b"):
result[f"npt_{definition}"] = npt[["well", f"npt_{definition}"]].rename(columns={f"npt_{definition}": "label"})
result[f"npt_{definition}"]["label"] = result[f"npt_{definition}"]["label"].map({True: "yes", False: "no"})
cause = f"cause_{definition}"
result[cause] = npt.loc[npt[f"npt_{definition}"], ["well", cause]].rename(columns={cause: "label"})
preview = draft["class_evaluability"]["preview"]
for target, rules in (("section", preview["t1_section"]), ("cause_a", preview["t2_cause"]),
("cause_b", preview["t2_cause"])):
mapping = {child: parent for parent, children in rules["merges"].items() for child in children}
for t in [target, "section_published", "section_filled"] if target == "section" else [target]:
result[f"{t}_pooled"] = result[t].assign(label=result[t]["label"].replace(mapping))
return result
def coverage(frame: pd.DataFrame, limits: dict) -> dict:
counts = frame.groupby(["label", "well"]).size()
return {label: {"n": int(n.sum()), "n_wells_min_items": int(n.ge(limits["min_items_per_well"]).sum()),
"evaluable": bool(n.ge(limits["min_items_per_well"]).sum() >= limits["min_wells"]),
"counts_by_well": n.droplevel("label").to_dict()}
for label, n in counts.groupby(level="label")}
def preflight(draft: dict) -> dict:
out = paths.outputs_dir()
source_hashes = {}
for name, record in draft["inputs"].items():
if isinstance(record, dict) and "file" in record:
source_hashes[name] = m2.digest(paths.REPO_ROOT / record["file"])
elif isinstance(record, dict) and "dir" in record:
source_hashes[name] = m2.digest(out / Path(record["dir"]).name / "summary.json")
if m2.read_json(out / "labels/summary.json")["labels_yaml"]["sha256"] != source_hashes["labels_config"]:
raise ValueError("The M1 labels were generated with a different labels.yaml.")
if m2.read_json(out / "t4/summary.json")["config"]["sha256"] != source_hashes["t4_templates"]:
raise ValueError("The M1 questions were generated with a different t4_templates.yaml.")
logs = pd.read_parquet(out / "witsml/wellbores.parquet")
cells = pd.read_parquet(out / "labels/t3_cells.parquet")
wellbores = sorted(logs.loc[logs["in_ddr"] & logs["n_time_logs"].gt(0), "wellbore"].unique())
relevant = cells.loc[cells["wellbore"].isin(wellbores) & cells["in_own_hole"]]
folds = {}
for well in sorted(relevant["well"].unique()):
train = relevant.loc[relevant["well"].ne(well)]
test = relevant.loc[relevant["well"].eq(well)]
folds[well] = {
"train_cells": len(train), "test_cells": len(test),
"train_positive": {d: int(train[f"label_{d}"].sum()) for d in ("a", "b")},
"test_positive": {d: int(test[f"label_{d}"].sum()) for d in ("a", "b")},
}
if not folds or any(any(n < 1 or n >= f["train_cells"] for n in f["train_positive"].values())
for f in folds.values()):
raise ValueError("At least one T3 training fold lacks positives or negatives.")
scopes = {name: coverage(frame, draft["class_evaluability"])
for name, frame in targets(out / "labels", draft).items()}
table_names = ("t1_activities", "t1_reports", "t2_labels", "t3_cells")
table_hashes = {name: m2.digest(out / "labels" / f"{name}.parquet") for name in table_names}
return {"input_hashes": source_hashes, "label_table_hashes": table_hashes, "class_coverage": scopes, "t3": {
"eligible_wellbores": wellbores, "eligible_wells": sorted(folds), "logo_folds": folds,
"cells": len(relevant), "wellbores_table_sha256": m2.digest(out / "witsml/wellbores.parquet"),
"cells_table_sha256": m2.digest(out / "labels/t3_cells.parquet"),
}}
def class_decisions(draft: dict, first: dict, pre: dict, definition: str) -> dict:
limits = draft["class_merging"]
coverage_table = pre["class_coverage"]
result = {}
for target in ("section", "operation", f"cause_{definition}", f"npt_{definition}"):
score = first["targets"][target]
names = coverage_table[target] | coverage_table.get(f"{target}_pooled", {})
pooled = score.get("pooled_classes", {})
preview = draft["class_evaluability"]["preview"]
merges = (preview["t1_section"]["merges"] if target == "section" else
preview["t2_cause"]["merges"] if target.startswith("cause_") else {})
members = {child: parent for parent, children in merges.items() for child in children}
eligible = {}
for name, cover in names.items():
s = (score["by_class"] | pooled).get(name, {})
kappa = s.get("median_weighted_kappa")
rated = s.get("rated_items", 0)
checks = {"well_support": cover["evaluable"], "rated": rated >= limits["min_audit_items"],
"agreement": kappa is not None and kappa >= limits["min_kappa"]}
eligible[name] = {"checks": checks, "rated_items": rated, "median_weighted_kappa": kappa,
"status": "keep" if all(checks.values()) else "drop"}
for child, parent in members.items():
if child in eligible:
eligible[child]["parent"] = parent
if eligible[parent]["status"] == "keep":
eligible[child]["within_parent_reportable"] = eligible[child]["status"] == "keep"
eligible[child]["status"] = "merge"
if target.startswith("cause_"):
for name in ("sidetrack", "hse"):
if name in eligible:
eligible[name]["status"] = "drop"
result[target] = eligible
return result
def check_panel(root: Path, pass_number: int, panel: dict, config: dict, sample: dict) -> None:
previous = root / "ratings" / "pass1"
names = set(config["raters"])
if panel["pass"] != pass_number or set(panel["provenance"]) != names:
raise ValueError(f"Incomplete agreement report for pass {pass_number}.")
minimum_gap = m2.repeatability_gap() if pass_number == 2 else None
for name, source in panel["provenance"].items():
file = root / "ratings" / f"pass{pass_number}" / f"{name}.json"
state = m2.read_json(file)
provenance = state["provenance"]
if (m2.digest(file) != source["ratings_sha256"] or not state.get("completed_at")
or len(state["responses"]) != sum(a["items"] for a in sample.values())
or provenance["settings"]["spec_sha256"] != m2.digest(m2.VALIDATION)
or provenance["model"] != config["raters"][name]):
raise ValueError(f"Rating is incomplete or has changed: {file}")
if minimum_gap is not None:
first = m2.read_json(previous / file.name)
if (first["provenance"] != provenance or
datetime.fromisoformat(state["started_at"]) < datetime.fromisoformat(first["completed_at"])
+ minimum_gap):
raise ValueError(f"Second-pass timing or provenance failed: {file}")
def freeze(draft: dict, pre: dict) -> None:
root = m2.directory()
sample = m2.read_json(root / "sample.json")
for kind, hashes in sample.items():
if (m2.digest(root / f"key_{kind}.csv") != hashes["key_sha256"]
or m2.digest(root / "blind" / f"{kind}.jsonl") != hashes["blind_sha256"]
or m2.digest(root / "blind" / f"{kind}_prompt.txt") != hashes["prompt_sha256"]):
raise ValueError(f"M2 sample or rubric was modified: {kind}")
first_file, second_file = (root / f"agreement_pass{n}.json" for n in (1, 2))
if not first_file.is_file() or not second_file.is_file():
raise ValueError("G1 requires completed agreement reports from both M2 passes.")
first, second = m2.read_json(first_file), m2.read_json(second_file)
config = m2.spec()
if second["pass1_agreement_sha256"] != m2.digest(first_file):
raise ValueError("First-pass agreement changed after the repeatability report.")
if second["minimum_repeat_gap_days"] != m2.repeatability_gap().days:
raise ValueError("The repeatability timing rule changed after the second pass was scored.")
for n, panel in enumerate((first, second), start=1):
check_panel(root, n, panel, config, sample)
cross_file = root / "cross_checks/summary.json"
if not first["npt_candidate"]:
raise ValueError("The first pass did not yield a defined NPT decision for the complete panel.")
definition = first["npt_candidate"]["primary"]
final = class_decisions(draft, first, pre, definition)
draft["status"] = "locked"
draft["locked_at_utc"] = m2.utc_now().isoformat()
draft["before_lock"] = []
for name, value in pre["input_hashes"].items():
record = draft["inputs"][name]
record["sha256" if "file" in record else "summary_sha256"] = value
draft["tasks"]["t2"]["npt_definition"]["primary"] = definition
draft["tasks"]["t3"]["wellbores"] = pre["t3"]["eligible_wellbores"]
draft["class_evaluability"]["final"] = pre["class_coverage"]
draft["class_merging"]["merges"] = final
draft["reporting"]["separate_class_scores"] = {
target: sorted(name for name, row in classes.items() if row["status"] == "keep")
for target, classes in final.items()
}
draft["inputs"]["label_tables"]["tables_sha256"] = pre["label_table_hashes"]
draft["validation"]["m2_evidence"] = {
"sample_sha256": m2.digest(root / "sample.json"),
"configuration_sha256": m2.digest(m2.VALIDATION),
"agreement_pass1_sha256": m2.digest(first_file), "agreement_pass2_sha256": m2.digest(second_file),
"cross_checks_sha256": m2.digest(cross_file), "npt_selection": first["npt_candidate"],
"t3_split": pre["t3"],
}
output = yaml.safe_dump(draft, sort_keys=False, width=110, allow_unicode=True)
candidate = root / "protocol_v1.candidate.yaml"
candidate.write_text(output, encoding="utf-8")
temp = PROTOCOL.with_suffix(".yaml.tmp")
temp.write_text(output, encoding="utf-8")
temp.replace(PROTOCOL)
write_checksum()
print(f"G1 locked: NPT definition {definition}; {CHECKSUM.relative_to(paths.REPO_ROOT)}")
def write_checksum() -> None:
line = f"{m2.digest(PROTOCOL)} {PROTOCOL.relative_to(paths.REPO_ROOT)}\n"
temp = CHECKSUM.with_suffix(".tmp")
temp.write_text(line, encoding="utf-8")
temp.replace(CHECKSUM)
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("action", choices=("preflight", "review", "lock"))
action = parser.parse_args().action
root = m2.directory()
root.mkdir(parents=True, exist_ok=True)
with (root / "protocol.lock").open("a") as lock:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
draft = yaml.safe_load(PROTOCOL.read_text(encoding="utf-8"))
if CHECKSUM.exists():
recorded = CHECKSUM.read_text(encoding="utf-8").split()[0]
if draft["status"] != "locked" or recorded != m2.digest(PROTOCOL):
raise ValueError("Existing G1 checksum does not match the locked protocol.")
print("G1 protocol checksum verified.")
elif draft["status"] == "locked":
candidate = root / "protocol_v1.candidate.yaml"
if action != "lock" or not candidate.is_file() or m2.digest(PROTOCOL) != m2.digest(candidate):
raise ValueError("The protocol says locked but its checksum is missing.")
write_checksum()
print("Recovered the checksum of the existing G1 candidate.")
else:
if draft["status"] != "draft":
raise ValueError(f"Unsupported protocol status: {draft['status']}")
pre = preflight(draft)
snapshot = root / "g1_preflight.json"
if action != "preflight" and (not snapshot.is_file() or m2.read_json(snapshot) != pre):
raise ValueError("G1 input tables differ from the preflight snapshot.")
if action == "preflight":
m2.write_json(snapshot, pre)
print(f"{len(pre['t3']['eligible_wellbores'])} T3 wellbores and "
f"{len(pre['t3']['eligible_wells'])} wells with both classes in every LOGO training fold")
if action == "review":
first_file = root / "agreement_pass1.json"
first = m2.read_json(first_file)
config = m2.spec()
check_panel(root, 1, first, config, m2.read_json(root / "sample.json"))
selection = first["npt_candidate"]
decisions = class_decisions(draft, first, pre, selection["primary"]) if selection else {}
m2.write_json(root / "g1_class_review_pass1.json", {
"agreement_sha256": m2.digest(first_file), "provisional_npt": selection,
"status": "provisional", "classes": decisions,
})
print(f"Provisional first-pass class decisions: {root / 'g1_class_review_pass1.json'}")
elif action == "lock":
freeze(draft, pre)
if __name__ == "__main__":
main()

163
scripts/10_m2_rate.py Normal file
View File

@@ -0,0 +1,163 @@
"""Run one fixed local LLM on each blinded item in a fresh conversation and checkpoint its responses."""
from __future__ import annotations
import argparse
import fcntl
import json
import socket
import subprocess
import time
from datetime import datetime
from pathlib import Path
import httpx
from volve_dia import audit, m2, paths
def blind_inputs(root: Path) -> tuple[dict, list]:
frozen = {}
entries = []
for kind in ("activity", "section"):
sample = root / f"{kind}.jsonl"
prompt = root / f"{kind}_prompt.txt"
frozen[kind] = {"blind_sha256": m2.digest(sample), "prompt_sha256": m2.digest(prompt)}
entries.extend((kind, prompt.read_text(encoding="utf-8"), row, json.loads(row)["item"])
for row in sample.read_text(encoding="utf-8").splitlines())
return frozen, entries
def schema(kind: str, sections: list[str]) -> dict:
enums = ({"section": [*sections, "?"]} if kind == "section" else
{"npt": ["y", "n", "?"], "cause": ["none", *audit.CAUSES, "hse"],
"operation": [*audit.OP_CLASSES, "?"]})
properties = {key: {"type": "string", "enum": choices} for key, choices in enums.items()}
properties["note"] = {"type": "string", "maxLength": 240}
return {"type": "object", "required": list(properties), "properties": properties, "additionalProperties": False}
def rate_item(client: httpx.Client, model: str, prompt: str, row: str, response_schema: dict,
seed: int, settings: dict) -> dict:
request = {"model": model, "temperature": settings["temperature"], "max_tokens": settings["max_tokens"],
"seed": seed, "messages": [{"role": "user", "content": f"{prompt.rstrip()}\n\nDDR record\n{row}"}],
"response_format": {"type": "json_schema", "json_schema": {"name": "rating", "schema": response_schema}}}
for attempt in range(3):
try:
response = client.post("/v1/chat/completions", json=request)
response.raise_for_status()
choice = response.json()["choices"][0]
if choice["finish_reason"] != "stop":
raise ValueError(f"Unexpected finish reason: {choice['finish_reason']}")
rating = json.loads(choice["message"]["content"])
if set(rating) != set(response_schema["required"]):
raise ValueError("Incomplete rating.")
for key, rule in response_schema["properties"].items():
if not isinstance(rating[key], str) or ("enum" in rule and rating[key] not in rule["enum"]):
raise ValueError(f"Invalid rating field: {key}")
return rating
except (ValueError, httpx.RequestError, httpx.HTTPStatusError) as error:
if attempt == 2:
raise RuntimeError(f"Rating failed after three attempts: {error}") from error
time.sleep(attempt + 1)
raise AssertionError("Unreachable rating retry state.")
def wait_ready(client: httpx.Client, server: subprocess.Popen) -> None:
deadline = time.monotonic() + 120
while server.poll() is None and time.monotonic() < deadline:
try:
if client.get("/health", timeout=2).is_success:
return
except httpx.TransportError:
pass
time.sleep(0.4)
raise RuntimeError(f"Local llama-server did not become healthy (exit code {server.poll()}).")
def run(args: argparse.Namespace, checkpoint: Path) -> None:
config = m2.spec()
model, settings = config["raters"][args.rater], config["rater_settings"]
first = None
if args.pass_number == 2:
first = m2.read_json(checkpoint.parent.parent / "pass1" / checkpoint.name)
ready = datetime.fromisoformat(first["completed_at"]) + m2.repeatability_gap()
if m2.utc_now() < ready:
raise ValueError(f"Second pass is eligible at {ready.isoformat()}.")
weights = (args.runtime / model["file"]).resolve()
server_bin = args.server.resolve()
frozen, items = blind_inputs(m2.directory() / "blind")
runtime_version = subprocess.run([server_bin, "--version"], capture_output=True, text=True, check=True)
if settings["engine"].split()[-1].removeprefix("b") not in runtime_version.stderr + runtime_version.stdout:
raise ValueError(f"Unexpected llama.cpp build: {runtime_version.stderr or runtime_version.stdout}")
settings = settings | {"spec_sha256": m2.digest(m2.VALIDATION), "gpu_layers": args.gpu_layers}
provenance = {"model": model, "weights_sha256": m2.digest(weights), "settings": settings,
"runtime_version": (runtime_version.stdout + runtime_version.stderr).strip(), "blind": frozen}
if first is not None and first["provenance"] != provenance:
raise ValueError("The second pass requires the frozen first-pass model, settings and inputs.")
if checkpoint.exists():
state = m2.read_json(checkpoint)
if state["provenance"] != provenance:
raise ValueError(f"Checkpoint provenance differs: {checkpoint}")
if state.get("completed_at"):
print(f"{args.rater}: pass {args.pass_number} already complete")
return
else:
state = {"provenance": provenance, "started_at": m2.utc_now().isoformat(), "responses": {}}
m2.write_json(checkpoint, state)
with socket.socket() as sock:
sock.bind(("127.0.0.1", 0))
port = sock.getsockname()[1]
command = [str(server_bin), "--model", str(weights), "--alias", args.rater, "--host", "127.0.0.1",
"--port", str(port), "--ctx-size", "8192", "--parallel", "1", "--threads", "4",
"--n-gpu-layers", args.gpu_layers, "--reasoning", "off", "--no-webui", "--no-context-shift",
"--verbosity", "1"]
schemas = {kind: schema(kind, config["section_sample"]["sections"]) for kind in ("activity", "section")}
with subprocess.Popen(command) as server, httpx.Client(
base_url=f"http://127.0.0.1:{port}", timeout=90, trust_env=False,
) as client:
try:
wait_ready(client, server)
for index, (kind, prompt, row, item) in enumerate(items):
if item in state["responses"]:
continue
seed = settings["seed_base"] + (args.pass_number - 1) * len(items) + index
try:
state["responses"][item] = rate_item(client, args.rater, prompt, row, schemas[kind], seed, settings)
except RuntimeError as error:
raise RuntimeError(f"{args.rater} item {item}: {error}") from error
m2.write_json(checkpoint, state)
if len(state["responses"]) % 50 == 0:
print(f"{args.rater}: {len(state['responses'])}/{len(items)} items")
finally:
server.terminate()
try:
server.wait(timeout=10)
except subprocess.TimeoutExpired:
server.kill()
state["completed_at"] = m2.utc_now().isoformat()
m2.write_json(checkpoint, state)
print(f"{args.rater}: pass {args.pass_number} complete, {len(state['responses'])} items")
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("rater", choices=list(m2.spec()["raters"]))
parser.add_argument("pass_number", type=int, choices=[1, 2])
parser.add_argument("--server", type=Path, required=True, help="Path to the pinned llama-server executable")
parser.add_argument("--runtime", type=Path, default=paths.outputs_dir() / "audit" / "m2_runtime")
parser.add_argument("--gpu-layers", default="all", help="Use 0 with the CPU build")
args = parser.parse_args()
out = m2.directory() / "ratings" / f"pass{args.pass_number}"
out.mkdir(parents=True, exist_ok=True)
with (out / f"{args.rater}.lock").open("a") as lock:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
run(args, out / f"{args.rater}.json")
if __name__ == "__main__":
main()

108
scripts/10_m2_sample.py Normal file
View File

@@ -0,0 +1,108 @@
"""Build independent, masked activity and report-day samples for M2."""
from __future__ import annotations
import hashlib
import json
from pathlib import Path
import pandas as pd
import yaml
from volve_dia import audit, paths
CONFIG = paths.REPO_ROOT / "configs"
ROOT = paths.outputs_dir() / "audit" / "m2_300"
def stratified(frame: pd.DataFrame, counts: dict, group: str, spec: dict) -> pd.DataFrame:
"""Draw by simple random sampling within each disjoint stratum with known inclusion probability."""
pieces = []
for category, n in counts.items():
pool = frame.loc[frame[group].eq(category)]
sizes = pool["stratum"].value_counts(sort=False).sort_index().to_dict()
allocation = audit.allocate(sizes, n, spec["min_per_stratum"])
for stratum, k in allocation.items():
f = pool.loc[pool["stratum"].eq(stratum)].sample(n=k, random_state=spec["seed"])
pieces.append(f.assign(n_stratum=sizes[stratum], k_stratum=k, weight=sizes[stratum] / k))
result = pd.concat(pieces).sample(frac=1, random_state=spec["seed"]).reset_index(drop=True)
if len(result) != sum(counts.values()):
raise ValueError("Sample quotas could not be filled.")
return result
def activity_sample(spec: dict) -> tuple[pd.DataFrame, pd.DataFrame, int]:
rows = audit.load_activity_labels().sort_values("act_id")
if spec["exclude_pilot"]:
pilot = pd.read_csv(ROOT.parent / "trial_100" / "key.csv", usecols=["act_id"])
rows = rows.loc[~rows["act_id"].isin(pilot["act_id"])].copy()
rows["zone"] = audit.zone(rows["npt_a"], rows["npt_b"])
category = rows["cause_a"].where(rows["zone"].eq("a"), rows["cause_b"])
category = category.where(rows["zone"].ne("none"), rows["op_class"])
rows["stratum"] = rows["zone"] + "/" + category + "/" + rows["well"]
s = stratified(rows, spec["zones"], "zone", spec)
s.insert(0, "item", [f"A{i:03d}" for i in range(1, len(s) + 1)])
s = s.rename(columns={"file_date": "report_date", "comments": "target_comment"})
for col in ("start_utc", "end_utc"):
s[col] = pd.to_datetime(s[col], utc=True).dt.strftime("%Y-%m-%dT%H:%MZ")
s["report_date"] = s["report_date"].astype(str)
sheet = s[["item", "wellbore", "report_date", "start_utc", "end_utc", "duration_h", "md", "rig_phase",
"prev_comment", "target_comment", "next_comment", "sum24Hr"]]
key = s[["item", "act_id", "well", "zone", "stratum", "n_stratum", "k_stratum", "weight",
"npt_a", "npt_b", "cause_a", "cause_b", "op_class"]]
return sheet, key, len(rows)
def section_sample(spec: dict) -> tuple[pd.DataFrame, pd.DataFrame, int]:
labels = paths.outputs_dir() / "labels"
ddr = paths.outputs_dir() / "ddr"
rows = pd.read_parquet(labels / "t1_reports.parquet")
rows = rows.loc[rows["scope"].eq("drilling_day"), ["report_id", "well", "section", "filled_by"]].copy()
rows["source"] = rows["filled_by"].eq("diaHole").map({True: "published", False: "filled"})
rows["stratum"] = rows["source"] + "/" + rows["section"]
s = stratified(rows.sort_values("report_id"), spec["source"], "source", spec)
s.insert(0, "item", [f"S{i:03d}" for i in range(1, len(s) + 1)])
reports = pd.read_parquet(ddr / "reports.parquet", columns=["report_id", "sum24Hr"])
act = pd.read_parquet(ddr / "activities.parquet", columns=["report_id", "seq", "comments"])
comments = act.sort_values("seq").groupby("report_id")["comments"].agg(list).rename("activity_comments")
view = s[["item", "report_id"]].merge(reports, on="report_id", validate="one_to_one")
view = view.join(comments, on="report_id", validate="one_to_one")
key = s[["item", "report_id", "well", "source", "section", "filled_by", "stratum",
"n_stratum", "k_stratum", "weight"]]
return view.drop(columns="report_id"), key, len(rows)
def encode(frame: pd.DataFrame) -> str:
return frame.to_json(orient="records", lines=True, force_ascii=False)
def write_frozen(path: Path, content: str) -> str:
raw = content.encode()
if path.exists() and path.read_bytes() != raw:
raise ValueError(f"Frozen M2 artifact differs: {path}")
if not path.exists():
path.write_bytes(raw)
return hashlib.sha256(raw).hexdigest()
def main() -> None:
spec = yaml.safe_load((CONFIG / "m2_validation.yaml").read_text())
ROOT.mkdir(parents=True, exist_ok=True)
blind = ROOT / "blind"
blind.mkdir(exist_ok=True)
manifest = {}
for kind, sample in (("activity", activity_sample), ("section", section_sample)):
sheet, key, population = sample(spec[f"{kind}_sample"])
manifest[kind] = {
"items": len(key), "population": population, "strata": int(key["stratum"].nunique()),
"wells": key["well"].value_counts().to_dict(),
"blind_sha256": write_frozen(blind / f"{kind}.jsonl", encode(sheet)),
"key_sha256": write_frozen(ROOT / f"key_{kind}.csv", key.to_csv(index=False)),
"prompt_sha256": write_frozen(blind / f"{kind}_prompt.txt", (CONFIG / f"m2_{kind}_prompt.txt").read_text()),
}
write_frozen(ROOT / "sample.json", json.dumps(manifest, indent=2) + "\n")
print(json.dumps(manifest, indent=2))
if __name__ == "__main__":
main()

30
scripts/run_m2.sh Executable file
View File

@@ -0,0 +1,30 @@
#!/usr/bin/env bash
# Run the reproducible M2 steps on existing M1 outputs.
set -euo pipefail
cd "$(dirname "$0")/.."
PY="${PY:-.venv/bin/python}"
export OMP_NUM_THREADS=4 MKL_NUM_THREADS=4 OPENBLAS_NUM_THREADS=4
[[ -n "${RUNLOG_DIR:-}" ]] || exec "$PY" -m volve_dia.runlog -n "m2_${1:-prepare}" -- bash scripts/run_m2.sh "$@"
step() { "$PY" -m volve_dia.runlog -- "$@"; }
case "${1:-prepare}" in
prepare)
step "$PY" scripts/10_m2_sample.py
step "$PY" scripts/10_m2_cross_checks.py
step "$PY" scripts/10_m2_protocol.py preflight
;;
pass1|pass2)
pass="${1#pass}"
shift
for rater in qwen gemma mistral; do
step "$PY" scripts/10_m2_rate.py "$rater" "$pass" "$@"
done
step "$PY" scripts/10_m2_agreement.py "$pass"
if [[ "$pass" == "1" ]]; then
step "$PY" scripts/10_m2_protocol.py review
fi
;;
*)
echo "Usage: scripts/run_m2.sh [prepare|pass1|pass2] [rater options]" >&2
exit 2
;;
esac