Add files using upload-large-folder tool
Browse filesFiles changed (50)
- faisi/W2-02-checker-synthesizer/src/checkers/synthesize_and_gate.pyAdded+283
- faisi/W3-01-guided-rl/config/agent.yamlAdded+2
- faisi/W3-01-guided-rl/logs/train.logAdded
- faisi/W3-01-guided-rl/reports/w3_01_guided_rl_report.jsonAdded
- faisi/W3-01-guided-rl/src/rl_env/__init__.pyAdded+4
- faisi/W3-01-guided-rl/src/rl_env/advantages.pyAdded+31
- faisi/W3-01-guided-rl/src/rl_env/consistency_scorer.pyAdded+148
- faisi/W3-01-guided-rl/src/rl_env/guided_loop.pyAdded+41
- faisi/W3-01-guided-rl/src/rl_env/guided_report.pyAdded+304
- faisi/W3-01-guided-rl/src/rl_env/guided_services.pyAdded+220
- faisi/W3-01-guided-rl/src/rl_env/guided_trainer.pyAdded+84
- faisi/W3-01-guided-rl/src/rl_env/prepare_guided.pyAdded+68
- faisi/W3-01-guided-rl/src/rl_env/reuse_step_zero.pyAdded+36
- faisi/W3-01-guided-rl/tests/test_guided.pyAdded+108
- faisi/W3-02-scaling-coevolution/config/agent.yamlAdded+2
- faisi/W3-02-scaling-coevolution/reports/w3_02_checker_v2_report.jsonAdded+2231
- faisi/W3-02-scaling-coevolution/reports/w3_02_scaling_and_r2_report.jsonAdded
- faisi/W3-02-scaling-coevolution/src/checker_v2/__init__.pyAdded
- faisi/W3-02-scaling-coevolution/src/checker_v2/gate.pyAdded+212
- faisi/W3-02-scaling-coevolution/src/checker_v2/mine_residual_conflicts.pyAdded+144
- faisi/W3-02-scaling-coevolution/src/checker_v2/saturation.pyAdded+64
- faisi/W3-02-scaling-coevolution/src/checker_v2/synthesize.pyAdded+212
- faisi/W3-02-scaling-coevolution/src/rl_env/__init__.pyAdded+4
- faisi/W3-02-scaling-coevolution/src/rl_env/advantages_v2.pyAdded+21
- faisi/W3-02-scaling-coevolution/src/rl_env/consistency_scorer_v2.pyAdded+45
- faisi/W3-02-scaling-coevolution/src/rl_env/export_hf.pyAdded+47
- faisi/W3-02-scaling-coevolution/src/rl_env/label_resamples.pyAdded+67
- faisi/W3-02-scaling-coevolution/src/rl_env/prepare_sample.pyAdded+61
- faisi/W3-02-scaling-coevolution/src/rl_env/prepare_scaling.pyAdded+62
- faisi/W3-02-scaling-coevolution/src/rl_env/resample.pyAdded+144
- faisi/W3-02-scaling-coevolution/src/rl_env/scaling_loop.pyAdded+6
- faisi/W3-02-scaling-coevolution/src/rl_env/scaling_report.pyAdded+242
- faisi/W3-02-scaling-coevolution/src/rl_env/scaling_services.pyAdded+24
- faisi/W3-02-scaling-coevolution/src/rl_env/scaling_trainer.pyAdded+91
- faisi/W3-02-scaling-coevolution/tests/test_scaling_v2.pyAdded+76
- faisi/W3-02-scaling-coevolution/verified_checkers_v2/check_rule_01.pyAdded+11
- faisi/W3-02-scaling-coevolution/verified_checkers_v2/check_rule_02.pyAdded+8
- faisi/W3-02-scaling-coevolution/verified_checkers_v2/check_rule_03.pyAdded+15
- faisi/W3-02-scaling-coevolution/verified_checkers_v2/check_rule_04.pyAdded+11
- faisi/W3-02-scaling-coevolution/verified_checkers_v2/check_rule_05.pyAdded+8
- faisi/W3-02-scaling-coevolution/verified_checkers_v2/check_rule_06.pyAdded+7
- faisi/W3-02-scaling-coevolution/verified_checkers_v2/check_rule_07.pyAdded+10
- faisi/W3-02-scaling-coevolution/verified_checkers_v2/check_rule_08.pyAdded+7
- faisi/W3-02-scaling-coevolution/verified_checkers_v2/check_rule_09.pyAdded+8
- faisi/W3-02-scaling-coevolution/verified_checkers_v2/check_rule_10.pyAdded+9
- faisi/W3-02-scaling-coevolution/verified_checkers_v2/check_rule_11.pyAdded+7
- faisi/W3-02-scaling-coevolution/verified_checkers_v2/check_rule_12.pyAdded+10
- faisi/W3-02-scaling-coevolution/verified_checkers_v2/manifest.jsonAdded+14
- faisi/W4-01-external-baselines/config/agent.yamlAdded+2
- faisi/W4-01-external-baselines/prompts/playbook_p1.txtAdded+1
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283"""Execute the full-corpus gate and publish the independently contributing checker library."""import argparseimport asynciofrom collections import Counter, defaultdictfrom contextlib import contextmanagerfrom dataclasses import dataclassimport jsonimport osfrom pathlib import Pathimport signalfrom statistics import fmean
from checkers.engine import Checker, CheckerTimeout, DATASET_WORD, UnsafeCheckerfrom checkers.generation import CODER, generatefrom checkers.inventory import ALLOWLIST_SHA256, DATASETS, train_allowlistfrom checkers.mine_conflicts import load_training, minefrom checkers.normalize_draft import normalize
MIN_CHECKERS, MAX_CHECKERS = 8, 20MAX_FPR = 0.05MIN_TPR = 0.15MIN_DELTA = 0.03MAX_UNION_FPR = 0.15MIN_UNION_TPR = 0.45MAX_MEAN_MS = 2.0
def bitmask(indices): return sum(1 << index for index in indices)
def timeout_handler(_signum, _frame): raise CheckerTimeout("checker_watchdog_timeout")
@contextmanagerdef watchdog(): previous = signal.signal(signal.SIGALRM, timeout_handler) try: yield finally: signal.setitimer(signal.ITIMER_REAL, 0) signal.signal(signal.SIGALRM, previous)
@dataclass(frozen=True, slots=True)class Trial: candidate: dict checker: Checker anchors: int negatives: int metrics: dict
def evaluate_candidates(paths, mined): anchor_mask, negative_mask = bitmask(mined.anchors), bitmask(mined.negatives) anchor_n, negative_n = len(mined.anchors), len(mined.negatives) stats, eligible, fingerprints = [], [], set() with watchdog(): for path in paths: candidate = json.loads(path.read_text()) result = {name: candidate[name] for name in ("index", "theme", "model", "seed")} if "revision" in candidate: result["revision"] = candidate["revision"] result["previous_rejection"] = candidate["previous_rejection"] stats.append(result) if "error" in candidate or candidate["model"] != CODER or candidate["finish_reason"] != "stop": result["rejected"] = "incomplete_generation" continue try: source, changed = normalize(candidate) if changed: result["normalized_schema_or_scope"] = True checker = Checker.compile(source) except (UnsafeChecker, SyntaxError, RecursionError) as exc: result["rejected"] = str(exc) continue rejected, elapsed, errors, reasons = [], [], Counter(), Counter() for index, row in enumerate(mined.rows): try: signal.setitimer(signal.ITIMER_REAL, 0.010) (passed, reason), nanos = checker.timed(row.ctx) except Exception as exc: errors[type(exc).__name__] += 1 else: elapsed.append(nanos) if not passed: rejected.append(index) reasons[reason] += 1 finally: signal.setitimer(signal.ITIMER_REAL, 0) flags = bitmask(rejected) anchors, negatives = flags & anchor_mask, flags & negative_mask fpr, tpr = anchors.bit_count() / anchor_n, negatives.bit_count() / negative_n ordered = sorted(elapsed) mean_ms = fmean(elapsed) / 1e6 if elapsed else None result.update({ "fpr": fpr, "tpr": tpr, "anchors_rejected": anchors.bit_count(), "conflicts_rejected": negatives.bit_count(), "mean_ms": mean_ms, "p99_ms": ordered[int(0.99 * (len(ordered) - 1))] / 1e6 if ordered else None, "max_ms": ordered[-1] / 1e6 if ordered else None, "evaluated_trajectories": len(mined.rows), "errors": sum(errors.values()), "error_types": dict(errors), "failure_reason_counts": dict(reasons), }) if errors: result["rejected"] = "execution_errors_or_timeout" elif mean_ms is None or mean_ms >= MAX_MEAN_MS: result["rejected"] = "latency" elif fpr > MAX_FPR or tpr < MIN_TPR: result["rejected"] = "individual_fpr_or_tpr" elif checker.source in fingerprints: result["rejected"] = "duplicate_source" elif DATASET_WORD.search(candidate["description"]) or len(candidate["description"]) > 400: result["rejected"] = "invalid_description" else: eligible.append(Trial(candidate, checker, anchors, negatives, result)) fingerprints.add(checker.source) return eligible, stats
@dataclass(frozen=True, slots=True)class State: order: tuple anchors: int negatives: int
def select(eligible, anchor_n, negative_n): """Deterministic beam search over orders. Keep coverage diversity within each depth.""" beam = [State((), 0, 0)] best = beam[0] for _ in range(min(len(eligible), MAX_CHECKERS)): options = {} buckets = defaultdict(list) for state in beam: for index, trial in enumerate(eligible): new_hits = (trial.negatives & ~state.negatives).bit_count() if new_hits / negative_n < MIN_DELTA: continue anchors = state.anchors | trial.anchors if anchors.bit_count() / anchor_n > MAX_UNION_FPR: continue negatives = state.negatives | trial.negatives key = anchors, negatives options.setdefault(key, State(state.order + (index,), anchors, negatives)) if not options: break ranked = sorted(options.values(), key=lambda state: ( -state.negatives.bit_count(), state.anchors.bit_count(), state.order )) best = ranked[0] if len(best.order) >= MIN_CHECKERS and best.negatives.bit_count() / negative_n >= MIN_UNION_TPR: break # Preserve low-overlap opportunities as well as large early unions. for state in ranked: bin_index = state.negatives.bit_count() * 40 // negative_n if len(eligible) <= 18 or len(buckets[bin_index]) < 64: buckets[bin_index].append(state) beam = [state for values in buckets.values() for state in values] return best
def publish(args, mined, records, trials, state): audit = json.loads(args.audit.read_bytes()) if (audit["allowlisted_train_cases"] != mined.summary()["train_cases"] or sum(audit["trajectory_counts_by_model"].values()) != len(mined.rows) or any(audit[name] != 0 for name in ( "test_payloads_read", "out_of_scope_trajectory_payloads_decoded", "ground_truth_vault_files_opened", "causal_path_files_opened", ))): raise ValueError("input_audit_failed") isolated = os.getenv("W202_ISOLATED") == "1" if isolated and any(Path(path).exists() for path in ( "/proc/1/root", "/input/vault", "/data", "/mnt/workspace/.local/faisi/w2-00", "/cpfs01/zijian.pan4/faisi/ground_truth_vault", )): raise ValueError("unexpected_analysis_inputs_visible") audit["filesystem_and_network_isolated_final_gate"] = isolated anchors, negatives = len(mined.anchors), len(mined.negatives) accepted = [] mask = 0 args.verified.mkdir(parents=True, exist_ok=True) for j, selected in enumerate(state.order, 1): trial = trials[selected] name = f"check_rule_{j:02d}" checker = Checker.compile(trial.checker.source, name) delta = (trial.negatives & ~mask).bit_count() / negatives mask |= trial.negatives other_hits = 0 for other in state.order: if other != selected: other_hits |= trials[other].negatives (args.verified / f"{name}.py").write_text(checker.source, encoding="utf-8") accepted.append({ "function": name, "candidate_index": trial.candidate["index"], "theme": trial.candidate["theme"], "description": trial.candidate["description"], "delta_tpr": delta, "exclusive_tpr_in_final_library": (trial.negatives & ~other_hits).bit_count() / negatives, **{key: trial.metrics[key] for key in ( "fpr", "tpr", "mean_ms", "p99_ms", "max_ms", "evaluated_trajectories", "errors", "failure_reason_counts", )}, }) for old_path in args.verified.glob("check_rule_*.py"): if old_path.stem not in {item["function"] for item in accepted}: old_path.unlink() union_fpr = state.anchors.bit_count() / anchors union_tpr = state.negatives.bit_count() / negatives breakdown = {} for dataset in DATASETS: eligible_anchors = {i for i in mined.anchors if mined.rows[i].case[0] == dataset} eligible_conflicts = {i for i in mined.negatives if mined.rows[i].case[0] == dataset} breakdown[dataset] = { "anchor_count": len(eligible_anchors), "conflict_count": len(eligible_conflicts), "joint_fpr": (state.anchors & bitmask(eligible_anchors)).bit_count() / len(eligible_anchors) if eligible_anchors else None, "joint_tpr": (state.negatives & bitmask(eligible_conflicts)).bit_count() / len(eligible_conflicts) if eligible_conflicts else None, } report = { "overall_pass": MIN_CHECKERS <= len(accepted) <= MAX_CHECKERS and union_fpr <= MAX_UNION_FPR and union_tpr >= MIN_UNION_TPR, "generator": {"model": CODER, "tensor_parallel_size": 4, "seed_base": 42000}, "allowlist_sha256": ALLOWLIST_SHA256, "input_isolation": audit, "mining": mined.summary(), "gate_thresholds": { "trajectory_timeout_ms": 10, "max_mean_ms": MAX_MEAN_MS, "max_error_rate": 0, "max_individual_fpr": MAX_FPR, "min_individual_tpr": MIN_TPR, "min_delta_tpr": MIN_DELTA, "max_joint_fpr": MAX_UNION_FPR, "min_joint_tpr": MIN_UNION_TPR, }, "total_candidates": len(records), "syntactically_and_statistically_eligible": len(trials), "revised_candidates": sum("revision" in record for record in records), "model_draft_revisions": sum(record.get("revision", 0) for record in records), "selected_rule_count": len(accepted), "selected_rules": accepted, "joint_fpr": union_fpr, "joint_tpr": union_tpr, "joint_anchor_rejections": state.anchors.bit_count(), "joint_conflict_rejections": state.negatives.bit_count(), "joint_metrics_by_dataset": breakdown, "candidate_results": records, } args.report.parent.mkdir(parents=True, exist_ok=True) temporary = args.report.with_suffix(".tmp") temporary.write_text(json.dumps(report, ensure_ascii=False, indent=2, allow_nan=False) + "\n") temporary.replace(args.report) print(json.dumps({ "overall_pass": report["overall_pass"], "total_candidates": len(records), "selected_rule_count": len(accepted), "joint_fpr": union_fpr, "joint_tpr": union_tpr, }), flush=True)
def main(args): mined = mine(load_training(args.training, train_allowlist(args.allowlist))) paths = sorted(args.candidates.glob("candidate_*.json")) if not paths: asyncio.run(generate(mined, args.candidates, args.endpoint, 0, 40)) paths = sorted(args.candidates.glob("candidate_*.json")) trials, records = evaluate_candidates(paths, mined) state = select(trials, len(mined.anchors), len(mined.negatives)) print(json.dumps({"first_round_candidates": len(records), "first_round_eligible": len(trials), "first_round_selected": len(state.order), "first_round_joint_tpr": state.negatives.bit_count() / len(mined.negatives)}), flush=True) if args.expand and len(paths) < 60 and ( len(state.order) < MIN_CHECKERS or state.negatives.bit_count() / len(mined.negatives) < MIN_UNION_TPR ): remaining = {index for index in mined.negatives if not (state.negatives >> index) & 1} previous = [trials[index].candidate["theme"] for index in state.order] first = len(paths) asyncio.run(generate(mined, args.candidates, args.endpoint, first, 60 - first, remaining, previous)) new_paths = [path for path in sorted(args.candidates.glob("candidate_*.json")) if path not in paths] added_trials, added_records = evaluate_candidates(new_paths, mined) trials.extend(added_trials) records.extend(added_records) state = select(trials, len(mined.anchors), len(mined.negatives)) publish(args, mined, records, trials, state)
if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) for option in ("allowlist", "training", "audit", "candidates", "verified", "report"): parser.add_argument("--" + option, type=Path, required=True) parser.add_argument("--endpoint", default="http://127.0.0.1:19202") parser.add_argument("--expand", action="store_true") main(parser.parse_args())12- name: w201_sandbox _target_: rl_env.guided_loop.GuidedAgentLoop1234"""W3-01 extensions in front of the shared W2-01 runtime."""from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)12345678910111213141516171819202122232425262728293031"""W2-01 GRPO with a lower bound on the per-group reward scale."""from collections import defaultdict
import torch
MIN_SPREAD = 1e-4STD_FLOOR = 0.15
def group_can_update(rewards): return max(rewards) - min(rewards) >= MIN_SPREAD
@torch.no_grad()def guided_grpo(token_level_rewards, response_mask, index, epsilon=1e-6, norm_adv_by_std_in_grpo=True, config=None): scores = token_level_rewards.sum(dim=-1) groups = defaultdict(list) for offset, group in enumerate(index): groups[group].append(offset) centered = torch.zeros_like(scores) for positions in groups.values(): values = scores[positions] if len(positions) == 1 or float(values.max() - values.min()) < MIN_SPREAD: continue difference = values - values.mean() if norm_adv_by_std_in_grpo: difference = difference / values.std().clamp_min(STD_FLOOR) centered[positions] = difference advantages = centered.unsqueeze(-1) * response_mask return advantages, advantages123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148"""Outcome-guided reward from authorized root verdicts and anonymous evidence."""from dataclasses import dataclassfrom functools import lru_cacheimport hashlibimport jsonimport loggingfrom pathlib import Pathimport time
from checkers.context_api import TrajectoryContextfrom checkers.engine import Checker, CheckerTimeout, load_library
RULE_COUNT = 8MAX_BLOCKS = 2GUARD_HINT = "Inspect the missing neighbor/edge or root telemetry and resubmit a supported propagation chain."RELATIONS = ("upstream", "downstream", "services", "instances", "hosts")LOGGER = logging.getLogger(__name__)
@dataclass(frozen=True)class RuntimeRule: checker: Checker
@property def name(self): return self.checker.name
def run(self, ctx): # The AST forbids blocking I/O. Budget its computation independently # of CPU descheduling inside concurrent rollout and evaluator workers. for attempt in range(3): try: return self.checker.run(ctx, clock=time.thread_time_ns) except CheckerTimeout as error: if str(error) != "checker_time_limit" or attempt == 2: raise LOGGER.warning("retry_checker_cpu_budget rule=%s attempt=%d", self.name, attempt + 1)
def guard_phase(phase): return phase.startswith("guard_")
@lru_cache(maxsize=1)def rule_library(root="/verified"): directory = Path(root) declared = json.loads((directory / "manifest.json").read_bytes()) names = [f"check_rule_{index:02d}.py" for index in range(1, RULE_COUNT + 1)] actual = {name: hashlib.sha256((directory / name).read_bytes()).hexdigest() for name in names} if actual != declared: raise ValueError("w202_checker_digest_mismatch") library = load_library(directory) if len(library) != RULE_COUNT: raise ValueError("w202_checker_count_mismatch") return tuple(RuntimeRule(checker) for checker in library)
def ordered_link(left, right): return (left, right) if left <= right else (right, left)
@dataclass(frozen=True)class TopologySupport: observed_links: frozenset observed_owner_links: frozenset
@classmethod def from_context(cls, ctx): pairs = {ordered_link(a, b) for a, b in ctx.observed_edges} for entity, neighbors in ctx.observed_topology.items(): for relation in RELATIONS: pairs.update(ordered_link(entity, other) for other in neighbors[relation]) service_pairs = { ordered_link(ctx.owner_service(a), ctx.owner_service(b)) for a, b in pairs } return cls(frozenset(pairs), frozenset(service_pairs))
def supports(self, ctx, left, right): return ( ordered_link(left, right) in self.observed_links or ordered_link(ctx.owner_service(left), ctx.owner_service(right)) in self.observed_owner_links )
def fraction(self, ctx): if not ctx.submitted_path: return float(ctx.distinct_observed_anomalous_services() < 2) return sum(self.supports(ctx, a, b) for a, b in ctx.submitted_path) / len(ctx.submitted_path)
def exploration(ctx): owners = {ctx.owner_service(entity) for entity in ctx.queried_entities} owners = {owner for owner in owners if ctx.entity_layer(owner) == "service"} multi = ctx.distinct_observed_anomalous_services() >= 2 explored_services = len(owners) >= 2 if multi else bool(ctx.observed_metrics and ctx.queried_topology_entities) co_located = {other for entry in ctx.observed_topology.values() for other in entry["co_located_entities"]} advanced = bool(ctx.queried_edges) or any( ctx.entity_layer(entity) == "host" or entity in co_located for entity in ctx.observed_metrics ) return round(0.03 * sum(( bool(ctx.queried_entities), bool(ctx.queried_topology_entities), explored_services, advanced, )), 6)
@dataclass(frozen=True)class ObservationScores: phi_lib: float all_pass: float phi_topo: float b_exp: float
def observation_scores(ctx, rules): passed = sum(rule.run(ctx)[0] for rule in rules) if len(rules) != RULE_COUNT: raise ValueError("w202_checker_count_mismatch") return ObservationScores(passed / RULE_COUNT, float(passed == RULE_COUNT), TopologySupport.from_context(ctx).fraction(ctx), exploration(ctx))
def guided_reward(observations, root_hit): if observations is None: return -0.1 if not root_hit: return round(observations.b_exp, 6) return round(0.35 + 0.30 * observations.phi_lib + 0.20 * observations.all_pass + 0.15 * observations.phi_topo, 6)
def blocked_results(steps): return sum(call["result"].get("status") == "verification_needed" for step in steps for call in step["tool_calls"])
def guard_feedback(initial, steps, submission, forced, rules): if forced or blocked_results(steps) >= MAX_BLOCKS: return None ctx = TrajectoryContext.from_trace({ "initial_observation": initial, "turns": steps, "num_turns": len(steps), "submission": submission, }) checks = [(rule.name, *rule.run(ctx)) for rule in rules] support = TopologySupport.from_context(ctx) links_supported = all(support.supports(ctx, a, b) for a, b in ctx.inter_service_edges_in_submission()) rejected = next(((name, reason) for name, passed, reason in checks if not passed), None) if rejected is None and not links_supported: rejected = ("observed_topology", "unsupported_cross_service_edge") if rejected is not None: return {"status": "verification_needed", "rule": rejected[0], "reason": rejected[1], "hint": GUARD_HINT} return None1234567891011121314151617181920212223242526272829303132333435363738394041"""Reuse W2-01 sampling, adding terminal traces and opt-in evaluation feedback."""import asyncioimport jsonimport mathimport time
from rl_env.common import SOCKET_LIMIT, json_bytesfrom rl_env.consistency_scorer import guard_feedback, guard_phase, rule_libraryfrom rl_env.sandbox_env import SandboxAgentLoop
class GuidedAgentLoop(SandboxAgentLoop): def handle_tool_result(self, key, initial, steps, name, args, result, forced): if guard_phase(key["phase"]) and name == "submit_diagnosis" and result.get("status") == "accepted": return guard_feedback(initial, steps, args, forced, rule_library()) or result return result
async def score_episode(self, key, step, trace): train = key["phase"] == "train" path = "/ipc/score.sock" if train else "/ipc/eval.sock" began = time.monotonic_ns() body = json_bytes(key | {"step": step, "trace": trace}) encode_ns = time.monotonic_ns() - began reader, writer = await asyncio.open_unix_connection(path, limit=SOCKET_LIMIT) try: # Separate serialization, socket delivery, and scorer work in the ledger. sent_ns = time.monotonic_ns() header = f'{{"sent_ns":{sent_ns},"encode_ns":{encode_ns},'.encode() writer.write(header + body[1:]) await writer.drain() line = await asyncio.wait_for(reader.readline(), 120) result = json.loads(line) score = result.get("score") if type(score) not in (float, int) or not math.isfinite(score) or not ( score == -0.1 or 0 <= score <= 1 ): raise RuntimeError("invalid_isolated_score") return score finally: writer.close() await writer.wait_closed()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304"""Validate the complete experiment and summarize matched W2-01 comparisons."""import argparsefrom collections import Counter, defaultdictimport hashlibimport jsonimport mathfrom pathlib import Pathfrom statistics import fmean
import numpy as npimport yaml
from rl_env.consistency_scorer import ObservationScores, guided_rewardfrom rl_env.curve import load_rows, metrics, runtime_metrics, training_stats
COHORTS = ("id_test", "ood_test", "ood_all")PHASES = ("id_test", "ood_test", "ood_extra")COMPARED = ("canonical_service_ac_at_1", "canonical_path_edge_f1", "canonical_grounded_ac_at_1", "canonical_ungrounded_hit_ratio", "avg_turns", "invalid_submit_rate")
def valid_reward(row): if row["invalid"]: return row["score"] == -0.1 and not row["root_hit"] scores = ObservationScores(*(row[field] for field in ("phi_lib", "all_pass", "phi_topo", "b_exp"))) return ( scores.phi_lib in {i / 8 for i in range(9)} and scores.all_pass == float(scores.phi_lib == 1) and 0 <= scores.phi_topo <= 1 and scores.b_exp in {round(i * .03, 6) for i in range(5)} and row["score"] == guided_reward(scores, row["root_hit"]) )
def timing_report(values): ordered = sorted(values) return {"mean": fmean(ordered), "p50": float(np.quantile(ordered, .5)), "p99": float(np.quantile(ordered, .99)), "max": ordered[-1]}
def reward_diagnostics(root, train): rewards = list(load_rows(root / "judge/rewards.jsonl")) groups = defaultdict(list) for row in rewards: groups[row["step"], row["dataset"], row["case_id"]].append(row) active = {} per_step = defaultdict(Counter) for group, rows in groups.items(): spread = max(row["score"] for row in rows) - min(row["score"] for row in rows) active[group] = spread >= 1e-4 summary = per_step[group[0]] summary["scored_groups"] += 1 summary["active_groups"] += active[group] if not any(row["root_hit"] for row in rows): summary["all_miss_groups"] += 1 summary["active_all_miss_groups"] += active[group] summary["root_hits"] += sum(row["root_hit"] for row in rows) summary["invalid"] += sum(row["invalid"] for row in rows) for step in train["steps"]: counts = per_step[step["step"]] if (step["outcome/active_groups"] != counts["active_groups"] or step["outcome/groups"] != counts["scored_groups"]): raise ValueError("reward_group_spread_disagrees_with_optimizer") step["guided_group_diagnostics"] = dict(counts) valid = [row for row in rewards if not row["invalid"]] serialization = [r["serialization_ms"] for r in rewards if "serialization_ms" in r] return { "active_group_fraction": sum(active.values()) / len(active), "optimizer_steps": sum(row["outcome/active_groups"] > 0 for row in train["steps"]), "all_miss_groups": sum(row["all_miss_groups"] for row in per_step.values()), "active_all_miss_groups": sum(row["active_all_miss_groups"] for row in per_step.values()), "terminal_score_components_mean": { key: fmean(row[key] for row in valid) for key in ("phi_lib", "phi_topo", "all_pass", "b_exp") }, "training_root_hit_rate": fmean(row["root_hit"] for row in rewards), "invalid_submission_rate": fmean(row["invalid"] for row in rewards), "message_bytes": timing_report([r["message_bytes"] for r in rewards]), "serialization_ms": timing_report(serialization) if serialization else None, "ipc_one_way_receive_ms": timing_report([r["receive_ms"] for r in rewards]), "score_service_ms": timing_report([r["score_service_ms"] for r in rewards]), }
def scope_allowlists(root): path = root / "data/allowlists.json" allowed = {key: {tuple(case) for case in values} for key, values in json.loads(path.read_bytes()).items()} allowed["ood_extra"] = allowed["ood_all"] - allowed["ood_test"] return allowed
def collect(path, allowed, direct_steps, guard_steps=()): values = defaultdict(dict) for row in load_rows(path): phase = row["phase"] is_guard = phase.startswith("guard_") mode = "guard" if is_guard else "direct" phase = phase.removeprefix("guard_") key = row["dataset"], row["case_id"] step = row["step"] target = values[mode, step, phase] if (phase not in PHASES or key not in allowed[phase] or key in target or row["seed"] != 42 or step not in (guard_steps if is_guard else direct_steps)): raise ValueError("evaluation_inventory_mismatch") if not 0 <= row.get("guard_blocks", 0) <= (2 if is_guard else 0): raise ValueError("guard_block_budget") target[key] = row for mode, steps in (("direct", direct_steps), ("guard", guard_steps)): for step in steps: for phase in PHASES: if set(values[mode, step, phase]) != allowed[phase]: raise ValueError(f"incomplete_evaluation:{mode}:{step}:{phase}") return values
def cohort(values, mode, step, name): data = values[mode, step, "ood_test" if name == "ood_all" else name] return data | values[mode, step, "ood_extra"] if name == "ood_all" else data
def summarize(rows): result = metrics(rows) result["canonical_ungrounded_hit_ratio"] = result.pop("ungrounded_hit_ratio") result["checker_all_pass_rate"] = fmean(row["checker_all_pass"] for row in rows) result["guard_interventions"] = sum(row["guard_blocks"] for row in rows) result["sessions_with_guard_feedback"] = sum(bool(row["guard_blocks"]) for row in rows) support = [row["phi_topo"] for row in rows if row["phi_topo"] is not None] result["mean_phi_topo"] = fmean(support) if support else None return result
def curve(root, values, mode, steps, total): points = [] for step in steps: checkpoint = root / "trainhome/checkpoints" / f"global_step_{step}" for rank in range(4): if not (checkpoint / "actor" / f"model_world_size_4_rank_{rank}.pt").is_file(): raise ValueError(f"checkpoint_incomplete:{step}") if not (checkpoint / "data.pt").is_file(): raise ValueError(f"checkpoint_loader_state_missing:{step}") node = {name: summarize(list(cohort(values, mode, step, name).values())) for name in COHORTS} node["ood_by_system"] = { name: {system: summarize([row for case, row in cohort(values, mode, step, name).items() if case[0] == dataset]) for system, dataset in (("Market", "openrca_v1"), ("hs", "openrca_v2"))} for name in ("ood_test", "ood_all") } points.append({"step": step, "progress_pct": int(step * 100 / total), "mode": mode, "checkpoint": f"checkpoints/global_step_{step}", **node}) return points
def differences(treatment, control): prior = control | {"canonical_ungrounded_hit_ratio": control.get("canonical_ungrounded_hit_ratio", control.get("ungrounded_hit_ratio"))} return {key: None if treatment.get(key) is None or prior.get(key) is None else treatment[key] - prior[key] for key in COMPARED}
def paired_evidence(now, before): if now.keys() != before.keys(): raise ValueError("paired_comparison_case_mismatch") fields = ("root_hit", "path_edge_f1", "grounded", "turns") summary = {} for field in fields: pairs = [(now[key][field], before[key][field]) for key in sorted(now)] if any((a is None) != (b is None) for a, b in pairs): raise ValueError("paired_annotation_inventory_changed") observed = [(a, b) for a, b in pairs if a is not None] if not observed: summary[field] = None continue d = np.array([float(a) - float(b) for a, b in observed]) rng = np.random.default_rng(42) draws = np.concatenate([d[rng.integers(0, len(d), size=(500, len(d)))].mean(1) for _ in range(20)]) lo, hi = np.quantile(draws, (.025, .975)) result = {"pairs": len(observed), "mean_change": float(d.mean()), "paired_bootstrap_ci95": [float(lo), float(hi)]} if field in ("root_hit", "grounded"): up = sum(a and not b for a, b in observed) down = sum(b and not a for a, b in observed) discordant = up + down result.update({"improved": up, "regressed": down, "one_sided_mcnemar_p": ( sum(math.comb(discordant, k) / 2**discordant for k in range(up, discordant + 1)) if discordant else 1.0)}) summary[field] = result return summary
def verify_control(values, published): for point in published: for name in COHORTS: outcomes = list(cohort(values, "direct", point["step"], name).values()) original = metrics(outcomes) if original != point[name]: raise ValueError(f"w201_baseline_ledger_differs_from_report:{point['step']}:{name}")
def verify_trainer_config(current_path, baseline_path): current = yaml.safe_load(current_path.read_bytes()) baseline = yaml.safe_load(baseline_path.read_bytes()) administrative = ("project_name", "experiment_name") scopes = ( ("trainer", current["trainer"], baseline["trainer"]), ("actor_rollout_ref.rollout.trace", current["actor_rollout_ref"]["rollout"]["trace"], baseline["actor_rollout_ref"]["rollout"]["trace"]), ) changed = [] for section, current_scope, baseline_scope in scopes: for key in administrative: if current_scope.pop(key) != baseline_scope.pop(key): changed.append(f"{section}.{key}") if current != baseline: raise ValueError("formal_w201_hyperparameters_changed") return {"matches_w201": True, "reporting_fields_changed": changed}
def build(root, baseline_report, baseline_ledger): config = json.loads((root / "trainhome/run.json").read_bytes()) allowed = scope_allowlists(root) split = json.loads((root / "data/split_summary.json").read_bytes()) audit = json.loads((root / "isolation_audit.json").read_bytes()) original = json.loads(baseline_report.read_bytes()) source_points = original["checkpoint_evaluation_curve"] baseline_active = original["training_logs_summary"]["active_groups"] / original["training_logs_summary"]["full_groups"] train = training_stats(root, config, valid_reward=valid_reward) train.update(reward_diagnostics(root, train)) runtime = runtime_metrics(root) ledger = collect(root / "judge/evaluations.jsonl", allowed, config["milestones"], config["runtime_guard_steps"]) direct = curve(root, ledger, "direct", config["milestones"], config["steps"]) guard = curve(root, ledger, "guard", config["runtime_guard_steps"], config["steps"]) comparison, criteria = [], {} config_check = None if not config["smoke"]: config_check = verify_trainer_config(root / "trainhome/config.yaml", baseline_ledger.parent.parent / "trainhome/config.yaml") control = collect(baseline_ledger, allowed, config["milestones"]) verify_control(control, source_points) source_by_step = {node["step"]: node for node in source_points} for point in direct + guard: mode, step = point["mode"], point["step"] comparator = source_by_step[step] now, prior = (cohort(ledger, mode, step, "id_test"), cohort(control, "direct", step, "id_test")) info = { "mode": mode, "step": step, "delta_vs_w201": {key: differences(point[key], comparator[key]) for key in COHORTS}, "paired_id_vs_w201": paired_evidence(now, prior), } if mode == "guard": direct_match = next(node for node in direct if node["step"] == step) info["delta_vs_w301_direct"] = {key: differences(point[key], direct_match[key]) for key in COHORTS} comparison.append(info) for mode in ("direct", "guard"): final = next(info for info in comparison if info["step"] == config["steps"] and info["mode"] == mode) delta, paired = final["delta_vs_w201"], final["paired_id_vs_w201"] criteria[mode] = { "id_root_at_least_w201_final": delta["id_test"]["canonical_service_ac_at_1"] >= 0, "id_avg_turns_above_w201_final": delta["id_test"]["avg_turns"] > 0, "id_path_f1_positive_paired_ci": paired["path_edge_f1"]["paired_bootstrap_ci95"][0] > 0, "id_grounded_at_1_positive_paired_p_lt_05": ( paired["grounded"]["mean_change"] > 0 and paired["grounded"]["one_sided_mcnemar_p"] < .05 ), "ood_test_and_all_root_at_least_w201_final": all( delta[key]["canonical_service_ac_at_1"] >= 0 for key in ("ood_test", "ood_all") ), } no_oom = runtime["explicit_oom_log_matches"] == 0 active_gain = train["active_group_fraction"] - baseline_active return { "overall_pass": (not config["smoke"] and no_oom and active_gain > 0 and all(all(mode.values()) for mode in criteria.values())), "run_kind": "smoke" if config["smoke"] else "full", "training_hyperparameters": config, "effective_hydra_config_comparison": config_check, "split_inventory": split, "input_isolation": audit, "training_logs_summary": train, "checkpoint_evaluation_curve": direct, "runtime_guard_evaluation_curve": guard, "comparison_vs_w2_01": comparison, "w3_01_step0_to_final": { mode: {name: differences(nodes[-1][name], nodes[0][name]) for name in COHORTS} for mode, nodes in (("direct", direct), ("guard", guard)) }, "runtime": runtime, "w2_01_baseline_sha256": hashlib.sha256(baseline_report.read_bytes()).hexdigest(), "acceptance": {"completed_steps": len(train["steps"]), "no_oom": no_oom, "w201_active_group_fraction": baseline_active, "active_group_fraction_gain": active_gain, "id_exploration_comparison": "step 52 versus W2-01 step 52 mean turns", "ood_comparison": "both Test and All canonical root hit rate at least W2-01 final", "id_paired_tests": "two-sided bootstrap 95% interval for path F1; one-sided McNemar for grounded", "outcomes_by_mode": criteria}, }
if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("run", type=Path) parser.add_argument("report", type=Path) parser.add_argument("--baseline-report", type=Path, required=True) parser.add_argument("--baseline-ledger", type=Path, required=True) args = parser.parse_args() report = build(args.run, args.baseline_report, args.baseline_ledger) tmp = args.report.with_suffix(".tmp") tmp.write_text(json.dumps(report, ensure_ascii=False, indent=2, allow_nan=False) + "\n") tmp.replace(args.report) print(json.dumps({"overall_pass": report["overall_pass"], **report["acceptance"]}), flush=True)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220"""Separate anonymous query, root-only training reward, and evaluation services."""import argparseimport asynciofrom concurrent.futures import ThreadPoolExecutorfrom dataclasses import asdictimport jsonimport osfrom pathlib import Pathimport reimport time
from checkers.context_api import TrajectoryContextfrom rl_env.common import SOCKET_LIMITfrom rl_env.consistency_scorer import ( blocked_results, guard_feedback, guard_phase, guided_reward, observation_scores, rule_library,)from rl_env.service import Cases, OutcomeJudge, ToolServer, writefrom sandbox.evaluator import decode_diagnosis
EVAL_PHASES = ("id_test", "ood_test", "ood_extra")CASE_PREFIX = re.compile(rb'\{"case_id":\s*"(case-[0-9a-f]{24})"')
class GuidedCases(Cases): def check(self, row): return super().check(row | {"phase": row["phase"].removeprefix("guard_")})
class GuidedTools(ToolServer): def close_after_submit(self, key): # In guard sessions the agent only closes after accepting the validated result. return not guard_phase(key["phase"])
def load_eval_answers(vault, allowed): result = {} keys = set().union(*(allowed[phase] for phase in EVAL_PHASES)) for dataset in {dataset for dataset, _ in keys}: path = vault / f"{dataset}.jsonl" if path.stat().st_mode & 0o777 != 0o444: raise ValueError("eval_vault_not_readonly") table = result[dataset] = {} with path.open("rb") as stream: for line in stream: match = CASE_PREFIX.match(line) if match is None: raise ValueError("invalid_vault_header") case = match[1].decode() if (dataset, case) in keys: table[case] = json.loads(line) if {(dataset, case) for dataset, table in result.items() for case in table} != keys: raise ValueError("evaluation_inventory_mismatch") return result
def replay_guard(trace, session, rules): """Recompute verification feedback before using the original W2-00 replay.""" prior, steps = [], [] for step in trace["turns"]: calls = [] for call in step["tool_calls"]: if call["name"] == "submit_diagnosis" and isinstance(call["arguments"], dict): base = session.call(call["name"], call["arguments"]) if base.get("status") == "accepted": requested = guard_feedback(trace["initial_observation"], prior, call["arguments"], step["forced"], rules) if call["result"] != (requested or base): raise ValueError("guard_feedback_replay_mismatch") if requested: # Preserve turn history and W2-00's direct evidence extraction. calls.append({"name": None, "arguments": None, "result": {"error": "tool_call_required"}}) continue if call["result"].get("status") == "verification_needed": raise ValueError("unmatched_guard_feedback") calls.append(call) prior.append(step) steps.append(step | {"tool_calls": calls}) return trace | {"turns": steps}
class ScoreService: def __init__(self, cases, filename): self.cases = cases self.pool = ThreadPoolExecutor(max_workers=32) self.rules = rule_library() self.stream = (Path("/state/judge") / filename).open("a", buffering=1)
def setup_session(self, row): if type(row.get("trace")) is not dict or row["trace"].get("schema_version") != 2: raise ValueError("terminal_schema_v2_trace_required") dataset, case = self.cases.check(row) trace = row["trace"] snapshot = self.cases.snapshot(dataset, case) session = self.cases.open(row) submission = trace["submission"] decoded = None if submission is not None: try: decoded = decode_diagnosis(session, submission) except (ValueError, TypeError, KeyError): pass key = {field: row[field] for field in ("phase", "step", "dataset", "case_id", "seed")} return key, trace, snapshot, session, decoded
async def handle(self, reader, writer): line = await asyncio.wait_for(reader.readline(), 600) delivered = time.monotonic_ns() row = json.loads(line) started = time.perf_counter_ns() score, entry = await asyncio.get_running_loop().run_in_executor(self.pool, self.compute, row) entry.update({"message_bytes": len(line), "receive_ms": (delivered - row["sent_ns"]) / 1e6, "serialization_ms": row.get("encode_ns", 0) / 1e6, "score_service_ms": (time.perf_counter_ns() - started) / 1e6}) self.stream.write(json.dumps(entry, separators=(",", ":"), allow_nan=False) + "\n") await write(writer, {"score": score})
class GuidedJudge(ScoreService): def __init__(self, cases): assert not Path("/data/vault").exists() assert not Path("/code/eval_only/evaluate_trajectories.py").exists() assert not Path("/proc/1/root").exists() self.roots = json.loads(Path("/data/train_roots.json").read_bytes()) if not cases.allowed["train"] <= {(d, c) for d, table in self.roots.items() for c in table}: raise ValueError("training_root_inventory") super().__init__(cases, "rewards.jsonl")
def compute(self, row): from eval_only.entity_projection import service_key
if row["phase"] != "train": raise ValueError("training_reward_phase_only") key, trace, snapshot, _, decoded = self.setup_session(row) observations = None hit = False if decoded is not None: targets = {service_key(root, snapshot.entities) for root in self.roots[key["dataset"]][key["case_id"]]} targets.discard(None) hit = service_key(decoded["root_entity_id"], snapshot.entities) in targets observations = observation_scores(TrajectoryContext.from_trace(trace), self.rules) score = guided_reward(observations, hit) return score, key | {"score": score, "root_hit": hit, "invalid": decoded is None, "turns": trace["num_turns"], **(asdict(observations) if observations else {})}
class GuidedEvaluator(ScoreService): projection = OutcomeJudge.projection
def __init__(self, cases): assert os.statvfs("/data/vault").f_flag & os.ST_RDONLY assert not Path("/data/train_roots.json").exists() assert not Path("/proc/1/root").exists() self.answers = load_eval_answers(Path("/data/vault"), cases.allowed) super().__init__(cases, "evaluations.jsonl")
def compute(self, row): from eval_only.evaluate_trajectories import canonical_score, replay
phase = row["phase"] if phase.removeprefix("guard_") not in EVAL_PHASES: raise ValueError("evaluation_phase_only") if row["seed"] != 42: raise ValueError("eval_seed_changed") key, trace, snapshot, session, decoded = self.setup_session(row) is_guard = guard_phase(phase) guard_blocks = blocked_results(trace["turns"]) if not is_guard and guard_blocks: raise ValueError("guard_used_in_direct_evaluation") replayed, _, rejected, queried = replay(replay_guard(trace, session, self.rules) if is_guard else trace, session) if replayed != decoded: raise ValueError("evaluation_replay_disagrees_with_reward") observations = observation_scores(TrajectoryContext.from_trace(trace), self.rules) if decoded else None metric = canonical_score(snapshot.entities, self.projection(key["dataset"], key["case_id"]), decoded, queried) reward = float(metric["canonical_root_hit"]) if decoded else -0.1 return reward, key | { "root_hit": metric["canonical_root_hit"], "grounded": metric["canonical_grounded"], "path_edge_f1": metric["canonical_path_edge_f1"], "turns": trace["num_turns"], "invalid": decoded is None, "rejected_submissions": rejected, "checker_all_pass": bool(observations and observations.all_pass), "phi_lib": observations.phi_lib if observations else None, "phi_topo": observations.phi_topo if observations else None, "guard_blocks": guard_blocks, }
async def run(role): classes = {"tools": GuidedTools, "judge": GuidedJudge, "eval": GuidedEvaluator} sockets = {"tools": "tools", "judge": "score", "eval": "eval"} if role == "tools": assert not Path("/data/vault").exists() and not Path("/data/train_roots.json").exists() service = classes[role](GuidedCases())
async def handle(reader, writer): try: await service.handle(reader, writer) except (BrokenPipeError, ConnectionResetError, asyncio.TimeoutError): pass except Exception as exc: print(json.dumps({"role": role, "error": type(exc).__name__, "detail": str(exc)[:160]}), flush=True) try: await write(writer, {"error": "invalid_session_request"}) except (BrokenPipeError, ConnectionResetError): pass finally: writer.close() try: await writer.wait_closed() except (BrokenPipeError, ConnectionResetError): pass
server = await asyncio.start_unix_server(handle, f"/ipc/{sockets[role]}.sock", limit=SOCKET_LIMIT, backlog=512) print(f"{role}_ready", flush=True) async with server: await server.serve_forever()
if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("role", choices=("tools", "judge", "eval")) asyncio.run(run(parser.parse_args().role))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384"""Keep W2-01's native verl config and add the W3-01 comparison hooks."""import argparseimport json
import rayfrom omegaconf import OmegaConffrom verl.trainer.main_ppo import run_ppofrom verl.trainer.ppo import core_algos
from rl_env.advantages import STD_FLOOR, MIN_SPREAD, group_can_update, guided_grpofrom rl_env.train import STATE, OutcomeTrainer, make_config, run_trainer
class GuardView: def __init__(self, loader): self.loader = loader
def __iter__(self): for batch in self.loader: yield batch | { "extra_info": [row | {"phase": "guard_" + row["phase"]} for row in batch["extra_info"]], "data_source": ["guard_" + source for source in batch["data_source"]], }
class GuidedTrainer(OutcomeTrainer): def group_can_update(self, rewards): return group_can_update(rewards)
def _compute_advantage(self, batch, metrics): # The native wrapper still handles grouping, masking, IS and TransferQueue. original = core_algos.compute_grpo_outcome_advantage core_algos.compute_grpo_outcome_advantage = guided_grpo try: return super()._compute_advantage(batch, metrics) finally: core_algos.compute_grpo_outcome_advantage = original
def _validate(self): cached_baseline = STATE / "verified_step0_metrics.json" if self.global_steps == 0 and cached_baseline.is_file(): return json.loads(cached_baseline.read_bytes()) metrics = super()._validate() if self.global_steps in (0, self.total_training_steps): loader = self.val_dataloader self.val_dataloader = GuardView(loader) try: guard = super()._validate() metrics.update({f"runtime_guard/{key}": value for key, value in guard.items()}) finally: self.val_dataloader = loader return metrics
@ray.remote(num_cpus=1)class GuidedTaskRunner: def run(self, config): return run_trainer(config, GuidedTrainer)
def guided_config(smoke=False): config = make_config(smoke) # The W2 parquet rows explicitly select this agent name. The role mounts # W3's agent config at the same path so the four dataset files stay exact. config.trainer.project_name = "faisi-w3-01" config.trainer.experiment_name = "guided-grpo-smoke" if smoke else "guided-grpo" (STATE / "config.yaml").write_text(OmegaConf.to_yaml(config, resolve=True)) path = STATE / "run.json" run = json.loads(path.read_bytes()) run.update({"reward": "w301_observation_guided", "grpo_std_floor": STD_FLOOR, "checker_budget_clock": "thread_cpu_time_ns", "min_group_reward_spread": MIN_SPREAD, "runtime_guard_steps": [0, run["steps"]]}) path.write_text(json.dumps(run) + "\n") return config
if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--smoke", action="store_true") args = parser.parse_args() try: run_ppo(guided_config(args.smoke), task_runner_class=GuidedTaskRunner) finally: ray.shutdown()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768"""Copy the exact baseline inventory and prepare sealed, root-only inputs."""import argparsefrom collections import defaultdictimport hashlibimport jsonfrom pathlib import Pathimport shutil
from checkers.inventory import ALLOWLIST_SHA256, train_allowlistfrom checkers.prepare_training import authorized_roots
NAMES = ("allowlists.json", "split_summary.json", "train.parquet", "val.parquet")
def sha(path): return hashlib.sha256(path.read_bytes()).hexdigest()
def main(args): inventory = train_allowlist(args.baseline / "data/allowlists.json") source = args.smoke_data if args.smoke_data else args.baseline / "data" keys = json.loads((source / "allowlists.json").read_bytes()) active = {tuple(key) for key in keys["train"]} if not (active <= inventory if args.smoke_data else active == inventory): raise ValueError("w201_train_inventory_changed") if any(tuple(key) in inventory for cohort in ("id_test", "ood_all") for key in keys[cohort]): raise ValueError("training_and_evaluation_overlap") for name in ("data", "roots", "verified"): (args.run / name).mkdir(parents=True, exist_ok=True, mode=0o700) hashes = {} for name in NAMES: shutil.copyfile(source / name, args.run / "data" / name) hashes[name] = sha(source / name) targets = defaultdict(dict) for (dataset, case), roots in authorized_roots(args.raw_root, active).items(): targets[dataset][case] = roots root_file = args.run / "roots/train_roots.json" root_file.write_text(json.dumps(targets, separators=(",", ":"))) root_file.chmod(0o444)
report_path = args.checkers / "reports/w2_02_checker_gate_report.json" policy = json.loads(report_path.read_bytes()) if policy["overall_pass"] is not True or policy["selected_rule_count"] != 8: raise ValueError("w202_validation_required") manifest = {} for entry in policy["selected_rules"]: name = entry["function"] + ".py" chosen = args.checkers / "verified_checkers" / name if sha(chosen) != entry["source_sha256"]: raise ValueError("w202_source_hash_mismatch") shutil.copyfile(chosen, args.run / "verified" / name) manifest[name] = entry["source_sha256"] (args.run / "verified/manifest.json").write_text(json.dumps(manifest)) audit = { "formal_w201_allowlist_sha256": ALLOWLIST_SHA256, "copied_w201_data_sha256": hashes, "train_roots": len(active), "train_root_fields_only": True, "train_vault_mounted_in_judge": False, "train_causal_paths_read": 0, "w202_report_sha256": sha(report_path), "w202_source_sha256": manifest, } (args.run / "isolation_audit.json").write_text(json.dumps(audit, indent=2) + "\n") print(json.dumps(audit), flush=True)
if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) for name in ("run", "raw_root", "checkers", "baseline"): parser.add_argument("--" + name.replace("_", "-"), type=Path, required=True) parser.add_argument("--smoke-data", type=Path) main(parser.parse_args())123456789101112131415161718192021222324252627282930313233343536"""Verify a complete baseline ledger before restarting updates from checkpoint 0."""import argparseimport jsonfrom pathlib import Path
from rl_env.guided_report import COHORTS, collect, curve, scope_allowlists
def verify(root): checkpoint_tracker = root / "trainhome/checkpoints/latest_checkpointed_iteration.txt" if checkpoint_tracker.read_text().strip() != "0": raise ValueError("reuse_requires_step_zero_checkpoint") if any((root / path).exists() for path in ("trainhome/steps.jsonl", "trainhome/consumed.jsonl", "judge/rewards.jsonl")): raise ValueError("archive_update_ledgers_before_reuse") allowed = scope_allowlists(root) records = collect(root / "judge/evaluations.jsonl", allowed, (0,), (0,)) nodes = [curve(root, records, mode, (0,), 52)[0] for mode in ("direct", "guard")] values = {f"verified_step0/{node['mode']}/{cohort}/canonical_service_ac_at_1": node[cohort]["canonical_service_ac_at_1"] for node in nodes for cohort in COHORTS} marker = root / "trainhome/verified_step0_metrics.json" marker.write_text(json.dumps(values, indent=2) + "\n") path = root / "isolation_audit.json" audit = json.loads(path.read_bytes()) audit["verified_step0_reused_after_restart"] = { "checkpoint_step": 0, "complete_direct_cases": nodes[0]["id_test"]["cases"] + nodes[0]["ood_all"]["cases"], "complete_guard_cases": nodes[1]["id_test"]["cases"] + nodes[1]["ood_all"]["cases"], } path.write_text(json.dumps(audit, indent=2) + "\n") print(json.dumps(audit["verified_step0_reused_after_restart"]), flush=True)
if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("run", type=Path) args = parser.parse_args() verify(args.run)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108from dataclasses import replacefrom types import SimpleNamespaceimport time
import pytestimport torch
from checkers.context_api import METRIC_FIELDS, NEIGHBOR_GROUPS, OVERVIEW_FIELDS, TrajectoryContextfrom checkers.engine import CheckerTimeoutfrom rl_env.advantages import group_can_update, guided_grpofrom rl_env.consistency_scorer import ( ObservationScores, RuntimeRule, TopologySupport, exploration, guard_feedback, guided_reward,)
INITIAL = {"result": { "fields": OVERVIEW_FIELDS, "anomalies": [ ["SVC_01", "service", 0.4, 0.5, False, "cpu_usage", 7], ["SVC_02", "service", 0.4, 0.5, False, "error_rate", 8], ],}}SUBMIT = {"root_entity_id": "INST_01", "propagation_path": [["INST_01", "INST_02"]], "key_evidence_ids": []}
def tool(name, entity, result): return {"tool_calls": [{"name": name, "arguments": {"entity_id": entity}, "result": result | {"entity_id": entity}}]}
def topology(entity, **groups): return tool("get_topology_neighbors", entity, { **dict.fromkeys(NEIGHBOR_GROUPS, []), **groups, "structure": {}, "hop": 1, })
def metrics(entity): return tool("query_entity_metrics", entity, {"fields": METRIC_FIELDS, "slots": {}})
def make_context(turns, submission=SUBMIT): return TrajectoryContext.from_trace({"initial_observation": INITIAL, "turns": turns, "num_turns": len(turns), "submission": submission})
def test_reward_bounds_and_exact_weights(): assert guided_reward(None, False) == -.1 confident = ObservationScores(1, 1, 1, .12) assert guided_reward(confident, False) == .12 assert guided_reward(confident, True) == 1 assert guided_reward(replace(confident, phi_topo=0), True) == .85 assert guided_reward(ObservationScores(.125, 0, 0, .12), True) == .3875
def test_topology_support_uses_observed_owners_and_unordered_links(): left = topology("INST_01", services=[["SVC_01", 8]]) right = topology("INST_02", services=[["SVC_02", 8]]) related = topology("SVC_02", downstream=[["SVC_01", 8]]) ctx = make_context([left, right]) assert TopologySupport.from_context(ctx).fraction(ctx) == 0 ctx = make_context([left, right, related]) assert TopologySupport.from_context(ctx).fraction(ctx) == 1 ctx = make_context([related], SUBMIT | {"propagation_path": []}) assert TopologySupport.from_context(ctx).fraction(ctx) == 0 solitary = replace(ctx, overview_anomalies={"SVC_01": ctx.overview_anomalies["SVC_01"]}) assert TopologySupport.from_context(solitary).fraction(solitary) == 1
def test_exploration_counts_distinct_evidence_not_repeated_calls(): own = topology("SVC_01", instances=[["INST_01", 8]], co_located_entities=[["INST_03", 5]]) assert exploration(make_context([metrics("SVC_01")] * 3)) == .03 assert exploration(make_context([own, metrics("INST_01"), metrics("SVC_01")])) == .06 assert exploration(make_context([own, metrics("INST_01"), metrics("SVC_02"), metrics("INST_03")])) == .12
def test_guard_block_budget_cross_edges_and_forced_acceptance(): rules = [SimpleNamespace(name=f"check_rule_{i}", run=lambda _ctx: (True, "ok")) for i in range(8)] first = guard_feedback(INITIAL, [], SUBMIT, False, rules) assert first["rule"] == "observed_topology" blocked = [{"tool_calls": [{"result": first}]}] assert guard_feedback(INITIAL, [], SUBMIT, True, rules) is None assert guard_feedback(INITIAL, blocked * 2, SUBMIT, False, rules) is None assert guard_feedback(INITIAL, [], SUBMIT | {"propagation_path": []}, False, rules) is None
def test_advantage_floor_and_zero_spread_mask(): rewards = torch.tensor([[.03, 0], [.06, 0], [.5, 0], [.50009, 0], [0., 0], [1., 0]]) mask = torch.tensor([[1, 0]] * 6) adv, ret = guided_grpo(rewards, mask, ["a", "a", "b", "b", "c", "c"]) assert adv[:, 0].tolist() == pytest.approx([-.1, .1, 0., 0., -.70710678, .70710678]) assert (adv[:, 1] == 0).all() and torch.equal(adv, ret) assert not group_can_update([0.5, .50009]) assert group_can_update([.03, .06])
def test_runtime_budget_uses_thread_cpu_clock(): attempts = [] def checked(_ctx, *, clock): assert clock is time.thread_time_ns attempts.append(clock) if len(attempts) == 1: raise CheckerTimeout("checker_time_limit") return True, "ok"
checker = RuntimeRule(SimpleNamespace(name="check_rule_01", run=checked)) assert checker.name == "check_rule_01" assert checker.run(make_context([])) == (True, "ok") assert len(attempts) == 212- name: w201_sandbox _target_: rl_env.scaling_loop.ScalingAgentLoop12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231{ "phase": "r1_policy_residual_gate", "overall_pass": true, "train_only_isolation": { "source_allowlist_sha256": "34709abed3cf336ab21ee9c2bf7c24e08b037ca0936d16ebd74985199eb278b4", "train_snapshot_count": 621, "eval_snapshots_in_view": 0, "vault_mounted": false, "train_roots_only": true, "eval_data_mounted_in_gate": false, "root_names_mounted_in_gate": false, "ground_truth_vault_reads": 0 }, "r1_resample_statistics_h1": { "training_cases": 621, "trajectories": 4968, "valid_submissions": 4968, "root_hits": 1267, "root_hit_rate": 0.25503220611916266, "library_passes": 4427, "library_all_pass_rate": 0.8911030595813204, "wrong_root_and_library_passes": 3227, "wrong_root_and_library_pass_rate_all_trajectories": 0.6495571658615137, "library_pass_rate_among_valid_wrong_roots": 0.8719265063496352, "anchor_pos_count": 1119, "residual_fp_count": 78, "cases_with_anchors": 166, "residual_fp_cases": 36, "same_case_positive_path_disagreement_pairs": 2392 }, "old_anchor_count": 1499, "model_draft_revisions": 52, "gating": { "overall_pass": true, "candidates": 60, "eligible_before_incremental_gate": 5, "admitted_rules": [ { "index": 14, "theme": "root_overview_rank", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 56014, "revised_from_seed": 55014, "fpr_r2_anchor": 0.03753351206434316, "fpr_w202_anchor": 0.030687124749833223, "tpr_residual": 0.5512820512820513, "mean_thread_cpu_ms": 0.025930479202102986, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "description": "Flags a root-owner anomaly peak below half the strongest rival when two other owner families were directly queried.", "function": "check_rule_09", "delta_tpr": 0.5512820512820513, "sha256": "5175489a612d2d049e207a82f7c60fdd5feb735137f5edaca784b035d4220548" }, { "index": 39, "theme": "unverified_colocated_origin", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 56039, "revised_from_seed": 55039, "fpr_r2_anchor": 0.03485254691689008, "fpr_w202_anchor": 0.038692461641094064, "tpr_residual": 0.08974358974358974, "mean_thread_cpu_ms": 0.022787283902891604, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "description": "Requests a call-edge check of the root owner when at least two other owner families were queried and at least half of the observed co-located entities are anomalous.", "function": "check_rule_10", "delta_tpr": 0.08974358974358974, "sha256": "a968b7a3f191a0937298b48bba6ede47376dc5002c38ee9b4583b376b770bf75" }, { "index": 21, "theme": "unexamined_root_topology", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 56021, "revised_from_seed": 55021, "fpr_r2_anchor": 0.0071492403932082215, "fpr_w202_anchor": 0.038692461641094064, "tpr_residual": 0.34615384615384615, "mean_thread_cpu_ms": 0.003409702798824803, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "description": "Requests local topology for the proposed root or its owner when a call edge has already been queried.", "function": "check_rule_11", "delta_tpr": 0.07692307692307693, "sha256": "b439686603e2810ce6cddbeb7d2e7bd720f2658e0c48a7a9b03265f0a94b9997" }, { "index": 0, "theme": "root_owner_late_onset", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 56000, "revised_from_seed": 55000, "normalized_feedback_reason": "root_later_than_observed_peer", "fpr_r2_anchor": 0.01161751563896336, "fpr_w202_anchor": 0.018679119412941963, "tpr_residual": 0.10256410256410256, "mean_thread_cpu_ms": 0.0317841283438998, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "description": "Flags a measured root-family onset at least 60 seconds after an observed competing anomaly.", "function": "check_rule_12", "delta_tpr": 0.0641025641025641, "sha256": "987e362199f0b229f019dc5028d453493f2fc00f6ab671be746240ae8d517794" } ], "new_rule_count": 4, "joint_fpr_anchor": 0.08668453976764968, "joint_tpr_residual": 0.782051282051282, "anchor_rejections": 97, "residual_rejections": 61, "candidate_metrics": [ { "index": 0, "theme": "root_owner_late_onset", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 56000, "revised_from_seed": 55000, "normalized_feedback_reason": "root_later_than_observed_peer", "fpr_r2_anchor": 0.01161751563896336, "fpr_w202_anchor": 0.018679119412941963, "tpr_residual": 0.10256410256410256, "mean_thread_cpu_ms": 0.0317841283438998, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "description": "Flags a measured root-family onset at least 60 seconds after an observed competing anomaly." }, { "index": 1, "theme": "earliest_reversal", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 53001, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.004669779853235491, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.007335311736508427, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "insufficient_residual_coverage" }, { "index": 2, "theme": "early_competing_path", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54002, "revised_from_seed": 53002, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.0, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.008362732951909695, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "insufficient_residual_coverage" }, { "index": 3, "theme": "overlooked_downstream", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54003, "revised_from_seed": 53003, "fpr_r2_anchor": 0.21090259159964253, "fpr_w202_anchor": 0.12408272181454302, "tpr_residual": 0.19230769230769232, "mean_thread_cpu_ms": 0.008051894541518478, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "soundness" }, { "index": 4, "theme": "dominant_neighbor", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54004, "revised_from_seed": 53004, "exclusion": "rejected_ast", "validator": "denied_dictionary_unpack" }, { "index": 5, "theme": "root_weak_measured", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54005, "revised_from_seed": 53005, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.0, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.005494772705430081, "runtime_errors": { "TypeError": 224 }, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "runtime" }, { "index": 6, "theme": "root_weak_same_scope", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54006, "revised_from_seed": 53006, "exclusion": "rejected_ast", "validator": "denied_call" }, { "index": 7, "theme": "caller_latency_gap", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54007, "revised_from_seed": 53007, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.0, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.012389277717643421, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "insufficient_residual_coverage" }, { "index": 8, "theme": "callee_internal_latency", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 53008, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.0, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.0067581714860058765, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "insufficient_residual_coverage" }, { "index": 9, "theme": "colocated_interference", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54009, "revised_from_seed": 53009, "fpr_r2_anchor": 0.8811438784629133, "fpr_w202_anchor": 0.61974649766511, "tpr_residual": 0.2692307692307692, "mean_thread_cpu_ms": 0.015147985310035564, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "soundness" }, { "index": 10, "theme": "early_owner", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54010, "revised_from_seed": 53010, "fpr_r2_anchor": 0.004468275245755138, "fpr_w202_anchor": 0.00600400266844563, "tpr_residual": 0.01282051282051282, "mean_thread_cpu_ms": 0.009203695840420596, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "insufficient_residual_coverage" }, { "index": 11, "theme": "earliest_reversal", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54011, "revised_from_seed": 53011, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.0, "tpr_residual": 0.0, "mean_thread_cpu_ms": null, "runtime_errors": { "TypeError": 6467 }, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "runtime" }, { "index": 12, "theme": "early_competing_path", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54012, "revised_from_seed": 53012, "exclusion": "rejected_ast", "validator": "denied_call" }, { "index": 13, "theme": "overlooked_downstream", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54013, "revised_from_seed": 53013, "fpr_r2_anchor": 0.6925826630920465, "fpr_w202_anchor": 0.5910607071380921, "tpr_residual": 0.3717948717948718, "mean_thread_cpu_ms": 0.006664972939539199, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "soundness" }, { "index": 14, "theme": "root_overview_rank", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 56014, "revised_from_seed": 55014, "fpr_r2_anchor": 0.03753351206434316, "fpr_w202_anchor": 0.030687124749833223, "tpr_residual": 0.5512820512820513, "mean_thread_cpu_ms": 0.025930479202102986, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "description": "Flags a root-owner anomaly peak below half the strongest rival when two other owner families were directly queried." }, { "index": 15, "theme": "root_weak_measured", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54015, "revised_from_seed": 53015, "exclusion": "rejected_ast", "validator": "denied_attribute" }, { "index": 16, "theme": "root_weak_same_scope", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54016, "revised_from_seed": 53016, "exclusion": "rejected_ast", "validator": "denied_call" }, { "index": 17, "theme": "caller_latency_gap", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54017, "revised_from_seed": 53017, "exclusion": "rejected_ast", "validator": "denied_string_literal" }, { "index": 18, "theme": "callee_internal_latency", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 53018, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.0, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.006728019947425391, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "insufficient_residual_coverage" }, { "index": 19, "theme": "colocated_interference", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54019, "revised_from_seed": 53019, "exclusion": "rejected_ast", "validator": "denied_call" }, { "index": 20, "theme": "early_owner", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54020, "revised_from_seed": 53020, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.0, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.0037430135135135133, "runtime_errors": { "TypeError": 6245 }, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "runtime" }, { "index": 21, "theme": "unexamined_root_topology", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 56021, "revised_from_seed": 55021, "fpr_r2_anchor": 0.0071492403932082215, "fpr_w202_anchor": 0.038692461641094064, "tpr_residual": 0.34615384615384615, "mean_thread_cpu_ms": 0.003409702798824803, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "description": "Requests local topology for the proposed root or its owner when a call edge has already been queried." }, { "index": 22, "theme": "early_competing_path", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 53022, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.00066711140760507, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.004454036183701871, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "insufficient_residual_coverage" }, { "index": 23, "theme": "overlooked_downstream", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54023, "revised_from_seed": 53023, "exclusion": "rejected_ast", "validator": "invalid_return_shape" }, { "index": 24, "theme": "dominant_neighbor", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54024, "revised_from_seed": 53024, "fpr_r2_anchor": 0.0035746201966041107, "fpr_w202_anchor": 0.00133422281521014, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.008723806710994278, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "insufficient_residual_coverage" }, { "index": 25, "theme": "root_weak_measured", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 53025, "fpr_r2_anchor": 0.008936550491510277, "fpr_w202_anchor": 0.10740493662441628, "tpr_residual": 0.02564102564102564, "mean_thread_cpu_ms": 0.005371018091850936, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "soundness" }, { "index": 26, "theme": "root_weak_same_scope", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54026, "revised_from_seed": 53026, "exclusion": "rejected_ast", "validator": "invalid_return_shape" }, { "index": 27, "theme": "caller_latency_gap", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54027, "revised_from_seed": 53027, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.0, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.005206475645585279, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "insufficient_residual_coverage" }, { "index": 28, "theme": "callee_internal_latency", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 53028, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.0, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.009661358280501004, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "insufficient_residual_coverage" }, { "index": 29, "theme": "colocated_interference", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54029, "revised_from_seed": 53029, "fpr_r2_anchor": 0.8811438784629133, "fpr_w202_anchor": 0.6204136090727151, "tpr_residual": 0.2692307692307692, "mean_thread_cpu_ms": 0.008673825266738829, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "soundness" }, { "index": 30, "theme": "early_owner", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54030, "revised_from_seed": 53030, "fpr_r2_anchor": 0.004468275245755138, "fpr_w202_anchor": 0.00600400266844563, "tpr_residual": 0.01282051282051282, "mean_thread_cpu_ms": 0.008563272769444873, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "insufficient_residual_coverage" }, { "index": 31, "theme": "earliest_reversal", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54031, "revised_from_seed": 53031, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.0, "tpr_residual": 0.0, "mean_thread_cpu_ms": null, "runtime_errors": { "TypeError": 6467 }, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "runtime" }, { "index": 32, "theme": "early_competing_path", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 53032, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.0, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.005317004793567342, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "insufficient_residual_coverage" }, { "index": 33, "theme": "overlooked_downstream", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 53033, "fpr_r2_anchor": 0.6407506702412868, "fpr_w202_anchor": 0.561707805203469, "tpr_residual": 0.3717948717948718, "mean_thread_cpu_ms": 0.006448587134683779, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "soundness" }, { "index": 34, "theme": "dominant_neighbor", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54034, "revised_from_seed": 53034, "exclusion": "rejected_ast", "validator": "denied_dictionary_unpack" }, { "index": 35, "theme": "root_weak_measured", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54035, "revised_from_seed": 53035, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.0, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.0070791286240589465, "runtime_errors": { "TypeError": 224 }, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "runtime" }, { "index": 36, "theme": "root_weak_same_scope", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54036, "revised_from_seed": 53036, "exclusion": "rejected_ast", "validator": "denied_call" }, { "index": 37, "theme": "caller_latency_gap", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 53037, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.0, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.00786958481521571, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "insufficient_residual_coverage" }, { "index": 38, "theme": "callee_internal_latency", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54038, "revised_from_seed": 53038, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.0, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.023292657681349988, "runtime_errors": { "AttributeError": 1904 }, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "runtime" }, { "index": 39, "theme": "unverified_colocated_origin", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 56039, "revised_from_seed": 55039, "fpr_r2_anchor": 0.03485254691689008, "fpr_w202_anchor": 0.038692461641094064, "tpr_residual": 0.08974358974358974, "mean_thread_cpu_ms": 0.022787283902891604, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "description": "Requests a call-edge check of the root owner when at least two other owner families were queried and at least half of the observed co-located entities are anomalous." }, { "index": 40, "theme": "early_owner", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54040, "revised_from_seed": 53040, "exclusion": "rejected_ast", "validator": "denied_dictionary_unpack" }, { "index": 41, "theme": "earliest_reversal", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54041, "revised_from_seed": 53041, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.0, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.0037292972972972974, "runtime_errors": { "TypeError": 6245 }, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "runtime" }, { "index": 42, "theme": "early_competing_path", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 53042, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.0, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.005075790474717798, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "insufficient_residual_coverage" }, { "index": 43, "theme": "overlooked_downstream", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 53043, "fpr_r2_anchor": 0.6407506702412868, "fpr_w202_anchor": 0.561707805203469, "tpr_residual": 0.3717948717948718, "mean_thread_cpu_ms": 0.008884576310499458, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "soundness" }, { "index": 44, "theme": "dominant_neighbor", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54044, "revised_from_seed": 53044, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.0, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.005311831785345718, "runtime_errors": { "AttributeError": 653 }, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "runtime" }, { "index": 45, "theme": "root_weak_measured", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 53045, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.0, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.010266335858976341, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "insufficient_residual_coverage" }, { "index": 46, "theme": "root_infra_anomaly_contrast", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 56046, "revised_from_seed": 55046, "fpr_r2_anchor": 0.050044682752457555, "fpr_w202_anchor": 0.05870580386924616, "tpr_residual": 0.38461538461538464, "mean_thread_cpu_ms": 0.1231315238905211, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "soundness" }, { "index": 47, "theme": "caller_latency_gap", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54047, "revised_from_seed": 53047, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.0, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.012119673109633524, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "insufficient_residual_coverage" }, { "index": 48, "theme": "callee_internal_latency", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54048, "revised_from_seed": 53048, "exclusion": "rejected_ast", "validator": "invalid_return_shape" }, { "index": 49, "theme": "colocated_interference", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54049, "revised_from_seed": 53049, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.0, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.008525205814133293, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "insufficient_residual_coverage" }, { "index": 50, "theme": "unsupported_cross_owner_branches", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 56050, "revised_from_seed": 55050, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.05203468979319546, "tpr_residual": 0.19230769230769232, "mean_thread_cpu_ms": 0.08356176588835627, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "description": "Check for missing bidirectional inter-service edges and their corresponding owner pairs." }, { "index": 51, "theme": "unverified_root_branch", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 53051, "exclusion": "rejected_ast", "validator": "denied_call" }, { "index": 52, "theme": "early_cross_edge", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 53052, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.00066711140760507, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.013198567032627185, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "insufficient_residual_coverage" }, { "index": 53, "theme": "early_outgoing_rival", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 53053, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.0, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.010637304661389622, "runtime_errors": { "TypeError": 782 }, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "runtime" }, { "index": 54, "theme": "dominant_neighbor_unchecked", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 53054, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.0, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.009920301652892562, "runtime_errors": { "TypeError": 5412, "AttributeError": 813 }, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "runtime" }, { "index": 55, "theme": "root_weak_positive_error", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 53055, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.0, "tpr_residual": 0.0, "mean_thread_cpu_ms": null, "runtime_errors": { "TypeError": 6467 }, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "runtime" }, { "index": 56, "theme": "callee_observed_gap", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 53056, "exclusion": "rejected_ast", "validator": "denied_string_literal" }, { "index": 57, "theme": "colocated_multi_service", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 53057, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.0, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.008403863769908766, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "insufficient_residual_coverage" }, { "index": 58, "theme": "absent_direct_root_contrast", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 56058, "revised_from_seed": 55058, "fpr_r2_anchor": 0.0017873100983020554, "fpr_w202_anchor": 0.00266844563042028, "tpr_residual": 0.01282051282051282, "mean_thread_cpu_ms": 0.025910254059069122, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "insufficient_residual_coverage" }, { "index": 59, "theme": "early_root_rival_on_path", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 53059, "fpr_r2_anchor": 0.004468275245755138, "fpr_w202_anchor": 0.00600400266844563, "tpr_residual": 0.01282051282051282, "mean_thread_cpu_ms": 0.025212546930570588, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "insufficient_residual_coverage" } ], "source_manifest": { "check_rule_01.py": "71ccd9040b8fdb857c3895e7996ae56ffbd43f3962e34e9a9821102ac3a6b4be", "check_rule_02.py": "c395ca2bf73f7176b456de30af2b091e2defafdf84695e380a9e6cfd6b78d47b", "check_rule_03.py": "0429f6867a6f5edbf2b1753547dcb1a923a40d23c165434d2a96c7b2387f731b", "check_rule_04.py": "50d946c853c789e9be63fb0382a076186e8356d379c7feae73e634983c61b86a", "check_rule_05.py": "096927d37039b519480f17b8a388144afcc0e136cde27e8a13867a52de2d9f87", "check_rule_06.py": "3a7e3c0f78a5e4e70209709b4e8322f59bd1b716b60c6d72a28df90424ea3bd8", "check_rule_07.py": "3edc9391152495412b969e89d449a50e8bef256917d01ae14ad9f198db6427bd", "check_rule_08.py": "ed207ed766a36b49e8799ef9e031db10c1b1339d1b0540f392a2e5b24def9bdd", "check_rule_09.py": "5175489a612d2d049e207a82f7c60fdd5feb735137f5edaca784b035d4220548", "check_rule_10.py": "a968b7a3f191a0937298b48bba6ede47376dc5002c38ee9b4583b376b770bf75", "check_rule_11.py": "b439686603e2810ce6cddbeb7d2e7bd720f2658e0c48a7a9b03265f0a94b9997", "check_rule_12.py": "987e362199f0b229f019dc5028d453493f2fc00f6ab671be746240ae8d517794" } }, "matched_training_cohort_progression": [ { "checkpoint": "w200_base", "h1": { "training_cases": 621, "trajectories": 4968, "valid_submissions": 4968, "root_hits": 1168, "root_hit_rate": 0.23510466988727857, "library_passes": 3312, "library_all_pass_rate": 0.6666666666666666, "wrong_root_and_library_passes": 2359, "wrong_root_and_library_pass_rate_all_trajectories": 0.4748389694041868, "library_pass_rate_among_valid_wrong_roots": 0.6207894736842106, "anchor_pos_count": 796, "residual_fp_count": 96, "cases_with_anchors": 163, "residual_fp_cases": 41, "same_case_positive_path_disagreement_pairs": 0 }, "v2": { "training_cases": 621, "trajectories": 4968, "valid_submissions": 4968, "root_hits": 1168, "root_hit_rate": 0.23510466988727857, "library_passes": 3159, "library_all_pass_rate": 0.6358695652173914, "wrong_root_and_library_passes": 2229, "wrong_root_and_library_pass_rate_all_trajectories": 0.44867149758454106, "library_pass_rate_among_valid_wrong_roots": 0.5865789473684211, "anchor_pos_count": 782, "residual_fp_count": 52, "cases_with_anchors": 159, "residual_fp_cases": 23, "same_case_positive_path_disagreement_pairs": 0 } }, { "checkpoint": "w301_r1_step52", "h1": { "training_cases": 621, "trajectories": 4968, "valid_submissions": 4968, "root_hits": 1267, "root_hit_rate": 0.25503220611916266, "library_passes": 4427, "library_all_pass_rate": 0.8911030595813204, "wrong_root_and_library_passes": 3227, "wrong_root_and_library_pass_rate_all_trajectories": 0.6495571658615137, "library_pass_rate_among_valid_wrong_roots": 0.8719265063496352, "anchor_pos_count": 1119, "residual_fp_count": 78, "cases_with_anchors": 166, "residual_fp_cases": 36, "same_case_positive_path_disagreement_pairs": 2392 }, "v2": { "training_cases": 621, "trajectories": 4968, "valid_submissions": 4968, "root_hits": 1267, "root_hit_rate": 0.25503220611916266, "library_passes": 3243, "library_all_pass_rate": 0.6527777777777778, "wrong_root_and_library_passes": 2185, "wrong_root_and_library_pass_rate_all_trajectories": 0.4398148148148148, "library_pass_rate_among_valid_wrong_roots": 0.5903809781140232, "anchor_pos_count": 1022, "residual_fp_count": 3, "cases_with_anchors": 152, "residual_fp_cases": 1, "same_case_positive_path_disagreement_pairs": 2150 } }, { "checkpoint": "w302_r2_step26", "h1": { "training_cases": 621, "trajectories": 4968, "valid_submissions": 4968, "root_hits": 1278, "root_hit_rate": 0.2572463768115942, "library_passes": 4571, "library_all_pass_rate": 0.9200885668276972, "wrong_root_and_library_passes": 3332, "wrong_root_and_library_pass_rate_all_trajectories": 0.6706924315619968, "library_pass_rate_among_valid_wrong_roots": 0.9029810298102982, "anchor_pos_count": 1202, "residual_fp_count": 86, "cases_with_anchors": 169, "residual_fp_cases": 35, "same_case_positive_path_disagreement_pairs": 2322 }, "v2": { "training_cases": 621, "trajectories": 4968, "valid_submissions": 4968, "root_hits": 1278, "root_hit_rate": 0.2572463768115942, "library_passes": 3514, "library_all_pass_rate": 0.7073268921095008, "wrong_root_and_library_passes": 2380, "wrong_root_and_library_pass_rate_all_trajectories": 0.47906602254428343, "library_pass_rate_among_valid_wrong_roots": 0.6449864498644986, "anchor_pos_count": 1122, "residual_fp_count": 15, "cases_with_anchors": 155, "residual_fp_cases": 6, "same_case_positive_path_disagreement_pairs": 2176 } } ], "round3_saturation_audit": { "overall_pass": false, "candidates": 76, "eligible_before_incremental_gate": 0, "admitted_rules": [], "new_rule_count": 0, "joint_fpr_anchor": 0.0, "joint_tpr_residual": 0.0, "anchor_rejections": 0, "residual_rejections": 0, "candidate_metrics": [ { "index": 1, "theme": "earliest_reversal", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 53001, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.004669779853235491, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.007163393691046853, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "insufficient_residual_coverage" }, { "index": 2, "theme": "early_competing_path", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54002, "revised_from_seed": 53002, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.0, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.008332878923766817, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "insufficient_residual_coverage" }, { "index": 3, "theme": "overlooked_downstream", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54003, "revised_from_seed": 53003, "fpr_r2_anchor": 0.18627450980392157, "fpr_w202_anchor": 0.12408272181454302, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.007506867481057678, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "soundness" }, { "index": 4, "theme": "dominant_neighbor", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54004, "revised_from_seed": 53004, "exclusion": "rejected_ast", "validator": "denied_dictionary_unpack" }, { "index": 5, "theme": "root_weak_measured", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54005, "revised_from_seed": 53005, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.0, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.0051891899904367225, "runtime_errors": { "TypeError": 193 }, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "runtime" }, { "index": 6, "theme": "root_weak_same_scope", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54006, "revised_from_seed": 53006, "exclusion": "rejected_ast", "validator": "denied_call" }, { "index": 7, "theme": "caller_latency_gap", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54007, "revised_from_seed": 53007, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.0, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.01166131854028143, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "insufficient_residual_coverage" }, { "index": 8, "theme": "callee_internal_latency", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 53008, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.0, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.0061214815215710535, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "insufficient_residual_coverage" }, { "index": 9, "theme": "colocated_interference", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54009, "revised_from_seed": 53009, "fpr_r2_anchor": 0.9233511586452763, "fpr_w202_anchor": 0.61974649766511, "tpr_residual": 0.9333333333333333, "mean_thread_cpu_ms": 0.014932356734188959, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "soundness" }, { "index": 10, "theme": "early_owner", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54010, "revised_from_seed": 53010, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.00600400266844563, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.008448981134993042, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "insufficient_residual_coverage" }, { "index": 11, "theme": "earliest_reversal", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54011, "revised_from_seed": 53011, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.0, "tpr_residual": 0.0, "mean_thread_cpu_ms": null, "runtime_errors": { "TypeError": 6467 }, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "runtime" }, { "index": 12, "theme": "early_competing_path", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54012, "revised_from_seed": 53012, "exclusion": "rejected_ast", "validator": "denied_call" }, { "index": 13, "theme": "overlooked_downstream", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54013, "revised_from_seed": 53013, "fpr_r2_anchor": 0.7103386809269162, "fpr_w202_anchor": 0.5910607071380921, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.006145539508272769, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "soundness" }, { "index": 15, "theme": "root_weak_measured", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54015, "revised_from_seed": 53015, "exclusion": "rejected_ast", "validator": "denied_attribute" }, { "index": 16, "theme": "root_weak_same_scope", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54016, "revised_from_seed": 53016, "exclusion": "rejected_ast", "validator": "denied_call" }, { "index": 17, "theme": "caller_latency_gap", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54017, "revised_from_seed": 53017, "exclusion": "rejected_ast", "validator": "denied_string_literal" }, { "index": 18, "theme": "callee_internal_latency", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 53018, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.0, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.006230759393845678, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "insufficient_residual_coverage" }, { "index": 19, "theme": "colocated_interference", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54019, "revised_from_seed": 53019, "exclusion": "rejected_ast", "validator": "denied_call" }, { "index": 20, "theme": "early_owner", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54020, "revised_from_seed": 53020, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.0, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.0034692393617021277, "runtime_errors": { "TypeError": 6279 }, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "runtime" }, { "index": 22, "theme": "early_competing_path", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 53022, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.00066711140760507, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.004299316375444565, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "insufficient_residual_coverage" }, { "index": 23, "theme": "overlooked_downstream", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54023, "revised_from_seed": 53023, "exclusion": "rejected_ast", "validator": "invalid_return_shape" }, { "index": 24, "theme": "dominant_neighbor", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54024, "revised_from_seed": 53024, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.00133422281521014, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.008272868563476109, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "insufficient_residual_coverage" }, { "index": 25, "theme": "root_weak_measured", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 53025, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.10740493662441628, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.005964698005257461, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "soundness" }, { "index": 26, "theme": "root_weak_same_scope", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54026, "revised_from_seed": 53026, "exclusion": "rejected_ast", "validator": "invalid_return_shape" }, { "index": 27, "theme": "caller_latency_gap", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54027, "revised_from_seed": 53027, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.0, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.004892734962115355, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "insufficient_residual_coverage" }, { "index": 28, "theme": "callee_internal_latency", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 53028, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.0, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.009956194680686562, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "insufficient_residual_coverage" }, { "index": 29, "theme": "colocated_interference", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54029, "revised_from_seed": 53029, "fpr_r2_anchor": 0.9233511586452763, "fpr_w202_anchor": 0.6204136090727151, "tpr_residual": 0.9333333333333333, "mean_thread_cpu_ms": 0.008567378537188804, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "soundness" }, { "index": 30, "theme": "early_owner", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54030, "revised_from_seed": 53030, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.00600400266844563, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.0077155760012370496, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "insufficient_residual_coverage" }, { "index": 31, "theme": "earliest_reversal", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54031, "revised_from_seed": 53031, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.0, "tpr_residual": 0.0, "mean_thread_cpu_ms": null, "runtime_errors": { "TypeError": 6467 }, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "runtime" }, { "index": 32, "theme": "early_competing_path", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 53032, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.0, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.005069385340961806, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "insufficient_residual_coverage" }, { "index": 33, "theme": "overlooked_downstream", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 53033, "fpr_r2_anchor": 0.661319073083779, "fpr_w202_anchor": 0.561707805203469, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.005902962424617288, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "soundness" }, { "index": 34, "theme": "dominant_neighbor", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54034, "revised_from_seed": 53034, "exclusion": "rejected_ast", "validator": "denied_dictionary_unpack" }, { "index": 35, "theme": "root_weak_measured", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54035, "revised_from_seed": 53035, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.0, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.00497917708001275, "runtime_errors": { "TypeError": 193 }, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "runtime" }, { "index": 36, "theme": "root_weak_same_scope", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54036, "revised_from_seed": 53036, "exclusion": "rejected_ast", "validator": "denied_call" }, { "index": 37, "theme": "caller_latency_gap", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 53037, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.0, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.004501673109633524, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "insufficient_residual_coverage" }, { "index": 38, "theme": "callee_internal_latency", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54038, "revised_from_seed": 53038, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.0, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.005601494353826851, "runtime_errors": { "AttributeError": 1685 }, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "runtime" }, { "index": 40, "theme": "early_owner", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54040, "revised_from_seed": 53040, "exclusion": "rejected_ast", "validator": "denied_dictionary_unpack" }, { "index": 41, "theme": "earliest_reversal", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54041, "revised_from_seed": 53041, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.0, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.0031822393617021274, "runtime_errors": { "TypeError": 6279 }, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "runtime" }, { "index": 42, "theme": "early_competing_path", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 53042, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.0, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.004416984536879542, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "insufficient_residual_coverage" }, { "index": 43, "theme": "overlooked_downstream", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 53043, "fpr_r2_anchor": 0.661319073083779, "fpr_w202_anchor": 0.561707805203469, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.006587708829441782, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "soundness" }, { "index": 44, "theme": "dominant_neighbor", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54044, "revised_from_seed": 53044, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.0, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.002639548600508906, "runtime_errors": { "AttributeError": 572 }, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "runtime" }, { "index": 45, "theme": "root_weak_measured", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 53045, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.0, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.0052025070357198085, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "insufficient_residual_coverage" }, { "index": 46, "theme": "root_infra_anomaly_contrast", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 56046, "revised_from_seed": 55046, "fpr_r2_anchor": 0.0338680926916221, "fpr_w202_anchor": 0.05870580386924616, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.1196576146590382, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "insufficient_residual_coverage" }, { "index": 47, "theme": "caller_latency_gap", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54047, "revised_from_seed": 53047, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.0, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.011257342817380547, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "insufficient_residual_coverage" }, { "index": 48, "theme": "callee_internal_latency", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54048, "revised_from_seed": 53048, "exclusion": "rejected_ast", "validator": "invalid_return_shape" }, { "index": 49, "theme": "colocated_interference", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 54049, "revised_from_seed": 53049, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.0, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.008244537961960723, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "insufficient_residual_coverage" }, { "index": 50, "theme": "unsupported_cross_owner_branches", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 56050, "revised_from_seed": 55050, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.05203468979319546, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.08034308226380084, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "insufficient_residual_coverage" }, { "index": 51, "theme": "unverified_root_branch", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 53051, "exclusion": "rejected_ast", "validator": "denied_call" }, { "index": 52, "theme": "early_cross_edge", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 53052, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.00066711140760507, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.006861599195917736, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "insufficient_residual_coverage" }, { "index": 53, "theme": "early_outgoing_rival", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 53053, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.0, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.00737716539396043, "runtime_errors": { "TypeError": 705 }, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "runtime" }, { "index": 54, "theme": "dominant_neighbor_unchecked", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 53054, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.0, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.0076748274336283185, "runtime_errors": { "TypeError": 5569, "AttributeError": 672 }, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "runtime" }, { "index": 55, "theme": "root_weak_positive_error", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 53055, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.0, "tpr_residual": 0.0, "mean_thread_cpu_ms": null, "runtime_errors": { "TypeError": 6467 }, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "runtime" }, { "index": 56, "theme": "callee_observed_gap", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 53056, "exclusion": "rejected_ast", "validator": "denied_string_literal" }, { "index": 57, "theme": "colocated_multi_service", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 53057, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.0, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.00794181150456162, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "insufficient_residual_coverage" }, { "index": 58, "theme": "absent_direct_root_contrast", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 56058, "revised_from_seed": 55058, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.00266844563042028, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.020743574454925005, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "insufficient_residual_coverage" }, { "index": 59, "theme": "early_root_rival_on_path", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 53059, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.00600400266844563, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.02520798623782279, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "insufficient_residual_coverage" }, { "index": 100, "theme": "unverified_root_edge", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 53100, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.0, "tpr_residual": 0.0, "mean_thread_cpu_ms": null, "runtime_errors": { "TypeError": 6467 }, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "runtime" }, { "index": 101, "theme": "unverified_root_branch", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 53102, "revised_from_seed": 53101, "exclusion": "rejected_ast", "validator": "denied_call" }, { "index": 102, "theme": "early_cross_edge", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 53103, "revised_from_seed": 53102, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.0, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.007917922408441962, "runtime_errors": { "AttributeError": 23 }, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "runtime" }, { "index": 103, "theme": "early_outgoing_rival", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 53104, "revised_from_seed": 53103, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.00066711140760507, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.008333457862996753, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "insufficient_residual_coverage" }, { "index": 104, "theme": "dominant_neighbor_unchecked", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 53105, "revised_from_seed": 53104, "exclusion": "rejected_ast", "validator": "denied_call" }, { "index": 105, "theme": "root_weak_positive_error", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 53105, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.0, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.008530430851063829, "runtime_errors": { "AttributeError": 6279 }, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "runtime" }, { "index": 106, "theme": "callee_observed_gap", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 53107, "revised_from_seed": 53106, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.0, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.007558492498066512, "runtime_errors": { "TypeError": 2 }, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "runtime" }, { "index": 107, "theme": "colocated_multi_service", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 53108, "revised_from_seed": 53107, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.0, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.0036155091363423396, "runtime_errors": { "KeyError": 64 }, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "runtime" }, { "index": 108, "theme": "root_weak_no_events_rival", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 53108, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.0, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.004920441085271318, "runtime_errors": { "AttributeError": 5177 }, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "runtime" }, { "index": 109, "theme": "early_root_rival_on_path", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 53109, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.0, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.020870640482449358, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "insufficient_residual_coverage" }, { "index": 110, "theme": "unverified_root_edge", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 53111, "revised_from_seed": 53110, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.03602401601067378, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.005588382712231329, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "insufficient_residual_coverage" }, { "index": 111, "theme": "unverified_root_branch", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 53112, "revised_from_seed": 53111, "exclusion": "rejected_ast", "validator": "denied_call" }, { "index": 112, "theme": "early_cross_edge", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 53113, "revised_from_seed": 53112, "fpr_r2_anchor": 0.0035650623885918, "fpr_w202_anchor": 0.016010673782521682, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.007691838874284831, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "insufficient_residual_coverage" }, { "index": 113, "theme": "early_outgoing_rival", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 53114, "revised_from_seed": 53113, "exclusion": "rejected_ast", "validator": "denied_call" }, { "index": 114, "theme": "dominant_neighbor_unchecked", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 53115, "revised_from_seed": 53114, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.0, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.014771489361702129, "runtime_errors": { "AttributeError": 6279 }, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "runtime" }, { "index": 115, "theme": "root_weak_positive_error", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 53115, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.0, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.0222859644106151, "runtime_errors": { "KeyError": 898, "AttributeError": 708 }, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "runtime" }, { "index": 116, "theme": "callee_observed_gap", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 53117, "revised_from_seed": 53116, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.0, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.004373241843203959, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "insufficient_residual_coverage" }, { "index": 117, "theme": "colocated_multi_service", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 53118, "revised_from_seed": 53117, "exclusion": "rejected_ast", "validator": "denied_call" }, { "index": 118, "theme": "root_weak_no_events_rival", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 53119, "revised_from_seed": 53118, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.0, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.005264020102056594, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "insufficient_residual_coverage" }, { "index": 119, "theme": "early_root_rival_on_path", "model": "Qwen2.5-Coder-32B-Instruct", "seed": 53119, "fpr_r2_anchor": 0.0, "fpr_w202_anchor": 0.0, "tpr_residual": 0.0, "mean_thread_cpu_ms": 0.007313657801144271, "runtime_errors": {}, "trajectories_checked": 4968, "older_anchors_checked": 1499, "syntax_normalized": false, "exclusion": "insufficient_residual_coverage" } ], "source_manifest": null, "candidate_pool": { "unused_r1_candidates": 56, "fresh_r3_candidates": 20, "fresh_r3_draft_retries": 14, "fresh_r3_incomplete_generation": 0 }, "baseline_library_size": 12, "marginal_delta_tpr": [], "note": "The dry-run never updates the released v2 library." }, "comparability": { "same_621_cases": true, "trajectories_per_case_each_stage": 8, "base_sampling_source": "Original W2-00 7B rollouts, seeds 1000\u20131007", "r1_r2_sampling_source": "Exported policies, seeds 2000\u20132007, equal W3-01 interaction protocol", "base_path_disagreement_pairs_available": false, "causal_truth_paths_read": 0 }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212"""Score bounded candidate programs and greedily admit measured residual gains."""import argparsefrom collections import Counterfrom dataclasses import dataclassimport hashlibimport jsonfrom pathlib import Pathfrom statistics import fmeanimport time
from checker_v2.mine_residual_conflicts import allowed_inventory, load_resample, mine, write_pairsfrom checkers.engine import Checker, UnsafeCheckerfrom checkers.mine_conflicts import load_training, mine as mine_w202from checkers.normalize_draft import normalizefrom rl_env.consistency_scorer import rule_library
MAX_FPR = .05MAX_OLD_FPR = .06MIN_DELTA = .02MAX_JOINT_FPR = .15MIN_JOINT_TPR = .15
REVIEWED_DESCRIPTIONS = { "root_overview_rank": "Flags a root-owner anomaly peak below half the strongest rival when two other owner families were directly queried.", "unverified_colocated_origin": "Requests a call-edge check of the root owner when at least two other owner families were queried and at least half of the observed co-located entities are anomalous.", "unexamined_root_topology": "Requests local topology for the proposed root or its owner when a call edge has already been queried.", "root_owner_late_onset": "Flags a measured root-family onset at least 60 seconds after an observed competing anomaly.",}
@dataclass(frozen=True, slots=True)class Candidate: checker: Checker result: dict anchor_rejections: frozenset residual_rejections: frozenset
def old_anchor_contexts(path, allowed): mined = mine_w202(load_training(path, allowed)) if len(mined.anchors) != 1499: raise ValueError("w202_anchor_inventory_changed") return tuple(mined.rows[i].ctx for i in sorted(mined.anchors))
def evaluate(paths, mined, old_anchors): eligible, ledger = [], [] if not mined.anchors or not mined.residual: return eligible, ledger for path in sorted(paths): draft = json.loads(path.read_bytes()) result = {key: draft[key] for key in ("index", "theme", "model", "seed")} if "revised_from_seed" in draft: result["revised_from_seed"] = draft["revised_from_seed"] ledger.append(result) if "error" in draft or draft["model"] != "Qwen2.5-Coder-32B-Instruct" or draft["finish_reason"] != "stop": result["exclusion"] = "incomplete_generation" continue source, changed = normalize(draft) if draft["theme"] == "root_owner_late_onset" and "root_earlier_than_peer" in source: source = source.replace("'root_earlier_than_peer'", "'root_later_than_observed_peer'") result["normalized_feedback_reason"] = "root_later_than_observed_peer" try: checker = Checker.compile(source) except (UnsafeChecker, SyntaxError, ValueError, RecursionError) as error: result["exclusion"] = "rejected_ast" result["validator"] = str(error) continue denied, errors, elapsed = set(), Counter(), [] old_denied = 0 for index, sample in enumerate(mined.samples): try: outcome, ns = checker.timed(sample.context, clock=time.thread_time_ns) except Exception as error: errors[type(error).__name__] += 1 continue elapsed.append(ns) if not outcome[0]: denied.add(index) for ctx in old_anchors: try: outcome, ns = checker.timed(ctx, clock=time.thread_time_ns) except Exception as error: errors[type(error).__name__] += 1 continue elapsed.append(ns) old_denied += not outcome[0] new_anchors = frozenset(denied & mined.anchors) residual = frozenset(denied & mined.residual) fpr = len(new_anchors) / len(mined.anchors) old_fpr = old_denied / len(old_anchors) tpr = len(residual) / len(mined.residual) average_ms = fmean(elapsed) / 1e6 if elapsed else None result.update({"fpr_r2_anchor": fpr, "fpr_w202_anchor": old_fpr, "tpr_residual": tpr, "mean_thread_cpu_ms": average_ms, "runtime_errors": dict(errors), "trajectories_checked": len(mined.samples), "older_anchors_checked": len(old_anchors), "syntax_normalized": changed}) if errors or average_ms is None or average_ms >= 2: result["exclusion"] = "runtime" elif fpr > MAX_FPR or old_fpr > MAX_OLD_FPR: result["exclusion"] = "soundness" elif tpr < MIN_DELTA: result["exclusion"] = "insufficient_residual_coverage" else: result["description"] = REVIEWED_DESCRIPTIONS.get(draft["theme"], str(draft["description"])[:300]) eligible.append(Candidate(checker, result, new_anchors, residual)) return eligible, ledger
def choose(candidates, anchor_count, residual_count, maximum=8): if not anchor_count or not residual_count: return [], set(), set() accepted, rejected_anchors, covered = [], set(), set() remaining = list(candidates) while remaining and len(accepted) < maximum: compatible = [candidate for candidate in remaining if len(candidate.residual_rejections - covered) / residual_count >= MIN_DELTA and len(candidate.anchor_rejections | rejected_anchors) / anchor_count <= MAX_JOINT_FPR] if not compatible: break best = min(compatible, key=lambda item: ( -len(item.residual_rejections - covered), len(item.anchor_rejections - rejected_anchors), item.result["fpr_w202_anchor"], item.result["index"], )) delta = len(best.residual_rejections - covered) / residual_count accepted.append((best, delta)) rejected_anchors.update(best.anchor_rejections) covered.update(best.residual_rejections) remaining.remove(best) return accepted, rejected_anchors, covered
def publish_library(source, target, selected): target.mkdir(parents=True, exist_ok=True) manifest = json.loads((source / "manifest.json").read_bytes()) for name, digest in manifest.items(): preserved = (source / name).read_bytes() if hashlib.sha256(preserved).hexdigest() != digest: raise ValueError("source_h1_digest_mismatch") (target / name).write_bytes(preserved) accepted = [] for index, (candidate, delta) in enumerate(selected, start=9): name = f"check_rule_{index:02d}" source_bytes = Checker.compile(candidate.checker.source, name).source.encode() file = name + ".py" (target / file).write_bytes(source_bytes) manifest[file] = hashlib.sha256(source_bytes).hexdigest() accepted.append(candidate.result | {"function": name, "delta_tpr": delta, "sha256": manifest[file]}) for file in target.glob("check_rule_*.py"): if file.name not in manifest: file.unlink() (target / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n") return accepted, manifest
def execute(mined, baseline_anchors, candidates, library=None, output=None): eligible, items = evaluate(candidates, mined, baseline_anchors) accepted, anchors, covered = choose(eligible, len(mined.anchors), len(mined.residual)) fpr = len(anchors) / len(mined.anchors) if mined.anchors else None tpr = len(covered) / len(mined.residual) if mined.residual else None passed = 3 <= len(accepted) <= 8 and fpr is not None and fpr <= MAX_JOINT_FPR and tpr >= MIN_JOINT_TPR accepted_rows = [item.result | {"delta_tpr": delta} for item, delta in accepted] manifest = None if library is not None and output is not None: accepted_rows, manifest = publish_library(library, output, accepted) return { "overall_pass": passed, "candidates": len(items), "eligible_before_incremental_gate": len(eligible), "admitted_rules": accepted_rows, "new_rule_count": len(accepted_rows), "joint_fpr_anchor": fpr, "joint_tpr_residual": tpr, "anchor_rejections": len(anchors), "residual_rejections": len(covered), "candidate_metrics": items, "source_manifest": manifest, }
def restricted_fs(): if any(Path(name).exists() for name in ( "/data/vault", "/data/train_roots.json", "/data/snapshots", "/proc/1/root", "/cpfs01/zijian.pan4/faisi/ground_truth_vault", )): raise RuntimeError("offline_checker_mount_isolation_required")
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--output", type=Path, default=Path("/output")) args = parser.parse_args() restricted_fs() allowed = allowed_inventory("/input/plan.json", "/input/isolation.json") samples = load_resample("/input/samples.jsonl", "/input/labels.jsonl", allowed) initial = Path("/input/h1") mined = mine(samples, rule_library(str(initial))) write_pairs(args.output / "residual_pairs.jsonl", mined) original = old_anchor_contexts("/input/w202_training.jsonl", allowed) paths = list((args.output / "candidates").glob("candidate_*.json")) result = execute(mined, original, paths, initial, args.output / "verified_checkers_v2") report = { "phase": "r1_policy_residual_gate", "overall_pass": result["overall_pass"], "train_only_isolation": json.loads(Path("/input/isolation.json").read_bytes()) | { "eval_data_mounted_in_gate": False, "root_names_mounted_in_gate": False, "ground_truth_vault_reads": 0, }, "r1_resample_statistics_h1": mined.report(), "old_anchor_count": len(original), "model_draft_revisions": len(list((args.output / "draft_revisions").glob("*.json"))), "gating": result, } (args.output / "w3_02_checker_v2_report.json").write_text(json.dumps(report, indent=2, allow_nan=False) + "\n") print(json.dumps({"overall_pass": result["overall_pass"], "mining": mined.report(), "new_rules": result["new_rule_count"], "joint_tpr": result["joint_tpr_residual"], "joint_fpr": result["joint_fpr_anchor"]}), flush=True)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144"""Residual mining with a pinned training inventory and isolated root verdicts."""import argparsefrom collections import defaultdictfrom dataclasses import dataclassfrom itertools import combinationsimport jsonfrom pathlib import Path
from checkers.context_api import TrajectoryContextfrom checkers.inventory import ALLOWLIST_SHA256from rl_env.consistency_scorer import TopologySupport, rule_library
@dataclass(frozen=True, slots=True)class Sample: case: tuple[str, str] sample_idx: int context: TrajectoryContext root_hit: bool valid: bool aligned_path: frozenset
@dataclass(frozen=True, slots=True)class Mining: samples: tuple anchors: frozenset residual: frozenset pairs: tuple divergent: tuple library_passes: tuple topology_support: tuple
def report(self): n = len(self.samples) valid = sum(item.valid for item in self.samples) hits = sum(item.root_hit for item in self.samples) passes = sum(self.library_passes) misses_passing = sum(not row.root_hit and ok for row, ok in zip(self.samples, self.library_passes)) return { "training_cases": len({row.case for row in self.samples}), "trajectories": n, "valid_submissions": valid, "root_hits": hits, "root_hit_rate": hits / n, "library_passes": passes, "library_all_pass_rate": passes / n, "wrong_root_and_library_passes": misses_passing, "wrong_root_and_library_pass_rate_all_trajectories": misses_passing / n, "library_pass_rate_among_valid_wrong_roots": ( misses_passing / (valid - hits) if valid > hits else None ), "anchor_pos_count": len(self.anchors), "residual_fp_count": len(self.residual), "cases_with_anchors": len({self.samples[i].case for i in self.anchors}), "residual_fp_cases": len({self.samples[i].case for i in self.residual}), "same_case_positive_path_disagreement_pairs": len(self.divergent), }
def allowed_inventory(plan, audit): proof = json.loads(Path(audit).read_bytes()) data = json.loads(Path(plan).read_bytes()) cases = {tuple(case) for case in data["train"]} if (proof["source_allowlist_sha256"] != ALLOWLIST_SHA256 or proof["eval_snapshots_in_view"] != 0 or proof["vault_mounted"] or proof["train_snapshot_count"] != 621 or len(cases) != len(data["train"]) or len(cases) != 621 or any(data[cohort] for cohort in ("id_test", "ood_test", "ood_all"))): raise ValueError("unapproved_training_view") return frozenset(cases)
def load_resample(traces, labels, allowed): def index(path): result = {} with Path(path).open(encoding="utf-8") as stream: for line in stream: row = json.loads(line) key = row["dataset"], row["case_id"], row["sample_idx"] if (key[:2] not in allowed or type(key[2]) is not int or not 0 <= key[2] < 8 or row["session_seed"] != 2000 + key[2] or key in result or not line.endswith("\n")): raise ValueError("unauthorized_or_duplicate_train_sample") result[key] = row if len(result) != len(allowed) * 8: raise ValueError("incomplete_resampling") return result
histories = index(traces) verdicts = index(labels) samples = [] for key in sorted(histories): row = histories[key] label = verdicts[key] if (type(label["root_hit"]) is not bool or type(label["valid"]) is not bool or label["valid"] != (row["submission"] is not None) or row["schema_version"] != 2 or label["root_hit"] and not label["valid"]): raise ValueError("root_verdict_malformed") samples.append(Sample( key[:2], key[2], TrajectoryContext.from_trace(row), label["root_hit"], label["valid"], frozenset(tuple(pair) for pair in (label["aligned_path"] or ())), )) return tuple(samples)
def mine(samples, rules): anchors_by_case = defaultdict(list) flag, topo = [], [] for index, sample in enumerate(samples): passed = sample.valid and all(rule.run(sample.context)[0] for rule in rules) supported = TopologySupport.from_context(sample.context).fraction(sample.context) if sample.valid else 0. flag.append(passed) topo.append(supported) if passed and sample.root_hit and supported == 1.: anchors_by_case[sample.case].append(index) residual, pairs, divergent = set(), [], [] for index, sample in enumerate(samples): if flag[index] and not sample.root_hit and sample.case in anchors_by_case: residual.add(index) pairs.append((index, anchors_by_case[sample.case][index % len(anchors_by_case[sample.case])])) for indexes in anchors_by_case.values(): for left, right in combinations(indexes, 2): if samples[left].aligned_path != samples[right].aligned_path: divergent.append((left, right)) return Mining(samples, frozenset(i for ids in anchors_by_case.values() for i in ids), frozenset(residual), tuple(pairs), tuple(divergent), tuple(flag), tuple(topo))
def write_pairs(path, mined): tmp = path.with_suffix(".tmp") with tmp.open("w", encoding="utf-8") as stream: for kind, pairs in (("residual_fp", mined.pairs), ("positive_path_divergence", mined.divergent)): for left, right in pairs: a, b = mined.samples[left], mined.samples[right] dataset, case = a.case stream.write(json.dumps({ "kind": kind, "dataset": dataset, "case_id": case, "sample_indices": [a.sample_idx, b.sample_idx], }, separators=(",", ":")) + "\n") tmp.replace(path)
if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) for field in ("plan", "audit", "traces", "labels", "h1"): parser.add_argument("--" + field, required=True, type=Path) args = parser.parse_args() samples = load_resample(args.traces, args.labels, allowed_inventory(args.plan, args.audit)) result = mine(samples, rule_library(str(args.h1))) print(json.dumps(result.report(), indent=2))12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364"""Recheck unused rule candidates against the continued policy's residuals."""import jsonfrom pathlib import Path
from checker_v2.gate import execute, old_anchor_contexts, restricted_fsfrom checker_v2.mine_residual_conflicts import Sample, allowed_inventory, load_resample, minefrom checkers.mine_conflicts import load_trainingfrom rl_env.consistency_scorer import rule_libraryfrom rl_env.consistency_scorer_v2 import rule_library_v2
def main(): restricted_fs() output = Path("/output") path = output / "w3_02_checker_v2_report.json" report = json.loads(path.read_bytes()) if not report["overall_pass"]: raise ValueError("accepted_v2_gate_required") allowed = allowed_inventory("/input/plan.json", "/input/isolation.json") base = tuple(Sample(row.case, row.sample_idx, row.ctx, row.hit, True, frozenset()) for row in load_training("/input/w202_training.jsonl", allowed) if row.model == "Qwen2.5-7B-Instruct") r1 = load_resample("/input/r1_samples.jsonl", "/input/r1_labels.jsonl", allowed) r2 = load_resample("/input/samples.jsonl", "/input/labels.jsonl", allowed) h1, v2 = rule_library("/input/h1"), rule_library_v2(str(output / "verified_checkers_v2")) report["matched_training_cohort_progression"] = [] for name, rows in (("w200_base", base), ("w301_r1_step52", r1), ("w302_r2_step26", r2)): plain, extended = mine(rows, h1), mine(rows, v2) report["matched_training_cohort_progression"].append( {"checkpoint": name, "h1": plain.report(), "v2": extended.report()}) final = mine(r2, v2) admitted = {r["index"] for r in report["gating"]["admitted_rules"]} available = [item for item in (output / "candidates").glob("candidate_*.json") if json.loads(item.read_bytes())["index"] not in admitted] additional = list((output / "r3_candidates").glob("candidate_*.json")) dry = execute(final, old_anchor_contexts("/input/w202_training.jsonl", allowed), available + additional) dry["candidate_pool"] = { "unused_r1_candidates": len(available), "fresh_r3_candidates": len(additional), "fresh_r3_draft_retries": len(list((output / "r3_draft_retries").glob("*.json"))), "fresh_r3_incomplete_generation": sum( row.get("exclusion") == "incomplete_generation" and row["index"] >= 100 for row in dry["candidate_metrics"] ), } dry["baseline_library_size"] = len(v2) dry["marginal_delta_tpr"] = [rule["delta_tpr"] for rule in dry["admitted_rules"]] dry["note"] = "The dry-run never updates the released v2 library." report["round3_saturation_audit"] = dry report["comparability"] = { "same_621_cases": True, "trajectories_per_case_each_stage": 8, "base_sampling_source": "Original W2-00 7B rollouts, seeds 1000–1007", "r1_r2_sampling_source": "Exported policies, seeds 2000–2007, equal W3-01 interaction protocol", "base_path_disagreement_pairs_available": False, "causal_truth_paths_read": 0, } tmp = path.with_suffix(".tmp") tmp.write_text(json.dumps(report, indent=2, allow_nan=False) + "\n") tmp.replace(path) print(json.dumps({"r2_residual": final.report(), "r3_admissions": dry["new_rule_count"], "r3_joint_tpr": dry["joint_tpr_residual"], "r3_delta_tpr": dry["marginal_delta_tpr"]}), flush=True)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212"""Generate second-order checker candidates using isolated contrast summaries."""import argparseimport asyncioimport jsonfrom pathlib import Pathimport random
import httpx
from checker_v2.gate import restricted_fsfrom checker_v2.mine_residual_conflicts import allowed_inventory, load_resample, minefrom checkers.generation import CODER, SCHEMA, SYSTEM, completion, synopsisfrom rl_env.consistency_scorer import rule_libraryfrom rl_env.consistency_scorer_v2 import rule_library_v2
THEMES = ( ("early_owner", "Choose a suspect only if a directly measured different owner in the root's known neighborhood starts earlier than the root, and has stronger direct anomalies. onset_diff(a,b)=onset(b)-onset(a)."), ("earliest_reversal", "A submitted sink cannot explain a nearby across-owner anomaly that is strongly measured and began much earlier. Check early symptoms only where both offsets are known."), ("early_competing_path", "Check directed paths whose root owner is contradicted by earlier measured alternative owners along the path. Prefer a meaningful offset and a corroborating severity gap."), ("overlooked_downstream", "A weaker root with an uninspected anomalous downstream of a different owner. Use observed_topology[root]['downstream'] and severity by observed neighbor; missing numeric values must abstain."), ("dominant_neighbor", "A strongly anomalous observed neighbor was never directly queried and the inspected root and owner both have low anomalies. Distinguish root versus neighbor using observed robust_z only."), ("root_weak_measured", "The queried root/owner lacks direct anomaly and events, while a directly measured related service has strong positive robust_z. Only use measured two-sided evidence."), ("root_weak_same_scope", "Compare directly measured supporting evidence for the predicted root family (same owner) with other inspected owner families. Reject only when the root is demonstrably weak."), ("caller_latency_gap", "Avoid attributing a large call wait gap to the caller when a related callee has stronger and earlier measured anomalies. Use explicit involvement of root owner and compare measured durations."), ("callee_internal_latency", "A submitted callee has low observed internal latency and no abnormal direct metrics while its caller has a stronger direct slowdown and higher errors. Require known measured evidence."), ("colocated_interference", "A seed node and other owners co-located on a host show anomalous metrics but no host was searched; protect anchors via a corroborating weakness or earlier co-located anomaly."),)REFINEMENTS = ( ("unverified_root_edge", "Reject a claimed cross-owner edge leaving the root only when both endpoint families were inspected but neighbors, ownership, hosting, and queried edges still provide no direct or projected link. Check either orientation. Account for instance ownership."), ("unverified_root_branch", "Require coherent evidence for a multi-branch root claim in which every submitted path begins with a queried root. If none of its cross-owner branches connect via a link actually observed around either owner, reject only when at least two distinct branches were asserted."), ("early_cross_edge", "Check a directly queried inter-service path edge for a measured onset reversal of at least one minute. Also require the affected endpoint to have clearly stronger direct anomalies. Use only pairs with both offsets and reliable direct metrics."), ("early_outgoing_rival", "Test a wrong-direction claim where the earliest directly observed anomalous service is an inspected neighbor of the root family. Compare with the earliest onset observed on any member of the root family."), ("dominant_neighbor_unchecked", "Look for multiple unqueried neighboring owners with very strong signals while the directly measured root family has only negative or quiet robust_z. Count distinct owners across upstream and downstream."), ("root_weak_positive_error", "Look for a clearly abnormal error-rate or latency slot on a measured neighbor, while measured root-family error-rate and latency values are quiet and no root-family events corroborate the claim. Use strict numeric knownness checks."), ("callee_observed_gap", "If a measured calling relation shows a large slowdown and error rise, check for an earlier directly measured, clearly abnormal callee and a quiet caller. Apply only when the submitted root maps to that caller."), ("colocated_multi_service", "Use measured co-location and shared-host facts to require a host check when several different owners are anomalous, the selected instance root is quiet, and the host is marked multi-tenant. Corroborate with directly queried values."), ("root_weak_no_events_rival", "Find a measured neighbor owner with both an earlier onset and stronger direct telemetry when every examined root-family entity lacks anomalous metrics or corroborating events. Do not infer normality without at least one actual measurement."), ("early_root_rival_on_path", "Compare directly measured competing services already in the submitted graph. Reject a notable earlier onset opposed to the proposed root only if the earlier service has strong measured errors or latency and observed topology supports the competing local direction."),)API_HINT = """The examples are summaries, not the actual schema. Here are valid access patterns:neighbors = ctx.observed_topology.get(e, {}).get("downstream", {})for peer, z in neighbors.items(): # neighbor map values are float or None if z is None: continueown = ctx.owner_service(e) # a single ID, possibly the same as efor slot in ctx.observed_metrics.get(e, {}).values(): if slot is None: continue z = slot.get("robust_z") # take a numeric field, never sum slot mappings if z is None: continueif ctx.distinct_observed_anomalous_services() >= 2: # returns an integer passfor peer in ctx.uninspected_anomalous_downstream(e): # set of IDs passif ctx.observed_events.get(e): passUse .get() for possibly unqueried root, owner, host, or neighbor. Use explicit None checkson every numeric field. Call min/max only after a nonempty list check. Do not combinemapping values with list concatenation. A path must remain permissible when observationsneeded to check the rule are unavailable. Return a literal tuple in every branch.Build collections in one expression with comprehensions or set(generator). Never callappend(), add(), update(), extend(), or use +=, mutation, or subtraction of sets."""CALIBRATED = { 0: ("root_owner_late_onset", "Set root=ctx.submitted_root and own=ctx.owner_service(root). Use root_ids={root, own} | {e for e in ctx.queried_entities if ctx.owner_service(e) == own}. Use peer_ids={e for e in ctx.queried_entities if ctx.owner_service(e) != own and ctx.has_direct_anomaly(e)}. For each set build a comprehension of ctx.earliest_anomaly_offset(e) values, keeping only values that are not None. When both collections are nonempty and min(root_offsets)-min(peer_offsets)>=60, reject. Do not inspect submitted_path."), 14: ("root_overview_rank", "Set own=ctx.owner_service(ctx.submitted_root). Use competing={ctx.owner_service(e) for e in ctx.queried_entities if ctx.owner_service(e) != own}. Use roots=[row['robust_z'] for e,row in ctx.overview_anomalies.items() if ctx.owner_service(e)==own and row.get('robust_z') is not None]. Use peers with the same comprehension but owner != own. Reject when len(competing)>=2, both lists are nonempty and max(roots)*2 < max(peers)."), 21: ("unexamined_root_topology", "If a call edge has been queried, a proposed root should have had its local topology checked. Reject exactly when ctx.queried_edges is nonempty AND neither submitted_root nor owner_service(submitted_root) is a key in ctx.observed_topology. Abstain if no edge was attempted. Give a reason about missing verification of the proposed source's topology."), 39: ("unverified_colocated_origin", "Set own=ctx.owner_service(root) and peers={ctx.owner_service(e) for e in ctx.queried_entities if ctx.owner_service(e) != own}. Set linked=any(own in (ctx.owner_service(a),ctx.owner_service(b)) for a,b in ctx.observed_edges). Reject exactly when len(peers)>=2, ratio=ctx.co_located_anomaly_ratio(root) is not None and ratio>=0.5, and linked is false. Do not use distinct_observed_anomalous_services or compare the two edge endpoints' owners to each other."), 46: ("root_infra_anomaly_contrast", "Write each collection as a comprehension: root_zs=[slot['robust_z'] for e in ctx.queried_entities if ctx.owner_service(e)==own for key,slot in ctx.observed_metrics.get(e,{}).items() if key in ('cpu_usage','mem_usage','io_usage','network_usage') and slot is not None and slot.get('robust_z') is not None]. Use the identical peer_zs comprehension with !=own. Reject if both nonempty and sum(peer_zs)/len(peer_zs) - sum(root_zs)/len(root_zs) >= 30. Make own the owner_service of the submitted root."), 50: ("unsupported_cross_owner_branches", "Use links=set(ctx.observed_edges) | {(ent,peer) for ent,topo in ctx.observed_topology.items() for group in ('upstream','downstream','services','instances','hosts') for peer in topo.get(group,{})}. Set owners={(ctx.owner_service(a),ctx.owner_service(b)) for a,b in links}. Loop over inter_service_edges_in_submission() and increment missing with missing = missing + 1 only if (u,v) and (v,u) are absent in links AND both directions of the corresponding owner pair are absent in owners. Reject as soon as missing >=2. Do not update any set or list."), 58: ("absent_direct_root_contrast", "Let own=ctx.owner_service(ctx.submitted_root), roots=[e for e in ctx.queried_entities if ctx.owner_service(e)==own], peers=[e for e in ctx.queried_entities if ctx.owner_service(e)!=own]. Reject only if any root entity has a measured metric mapping, none of roots has has_direct_anomaly(e) or ctx.observed_events.get(e), and at least one peer has has_direct_anomaly(e). These are lists of distinct entities, not owner IDs."),}
def relevance(theme, ctx): root = ctx.submitted_root owner = ctx.owner_service(root) peers = {e for e in ctx.queried_entities if ctx.owner_service(e) != owner} if theme.startswith("early"): found = [ctx.onset_diff(e, root) for e in peers] return max((value for value in found if value is not None), default=0) if theme in ("dominant_neighbor", "overlooked_downstream"): return len(ctx.uninspected_anomalous_downstream(root)) if theme.startswith("root_weak"): return sum(ctx.has_direct_anomaly(e) for e in peers) if not ctx.has_direct_anomaly(root) else 0 if theme.startswith(("caller_", "callee_")): return max((r.get("span_gap_ms") or 0 for edge, r in ctx.observed_edges.items() if owner in {ctx.owner_service(e) for e in edge}), default=0) return ctx.co_located_anomaly_ratio(root) or 0
def examples(mined, theme, index, limit=3): rng = random.Random(53000 + index) pairs = list(mined.pairs) rng.shuffle(pairs) pairs.sort(key=lambda pair: -relevance(theme, mined.samples[pair[0]].context)) cases, output = set(), [] for wrong, correct in pairs: negative, positive = mined.samples[wrong], mined.samples[correct] if negative.case not in cases: cases.add(negative.case) output.append({"residual_wrong": synopsis(negative.context), "anchor": synopsis(positive.context)}) if len(output) == limit: break return output
async def synthesize(mined, directory, count, start=0, round3=False, repair=False, calibrated=False): directory.mkdir(exist_ok=True, parents=True) revisions = {} if repair: report = json.loads((directory.parent / "w3_02_checker_v2_report.json").read_bytes()) revisions = {row["index"]: row for row in report["gating"]["candidate_metrics"] if row.get("exclusion") in ("runtime", "rejected_ast")} (directory.parent / "draft_revisions").mkdir(exist_ok=True) if calibrated: (directory.parent / "draft_revisions").mkdir(exist_ok=True) transport = httpx.AsyncHTTPTransport(uds="/coder.sock") async with httpx.AsyncClient(transport=transport, base_url="http://local", timeout=150) as client: if CODER not in {row["id"] for row in (await client.get("/v1/models")).raise_for_status().json()["data"]}: raise RuntimeError("unexpected_codegen_model") sem = asyncio.Semaphore(16)
async def job(index): output = directory / f"candidate_{index:03d}.json" prior = None if calibrated and index not in CALIBRATED: return if output.is_file() and index not in revisions and not calibrated: existing = json.loads(output.read_bytes()) if not round3 or existing.get("finish_reason") == "stop": return prior = existing family = REFINEMENTS if round3 or index >= 50 else THEMES theme, rule = CALIBRATED[index] if calibrated else family[index % len(family)] accepted = "Both existing generations of checks" if round3 else "First-order checks" prompt = ( f"{accepted} already accepted all of these; missing cross-service path alone cannot help. " "Identify a conflict in root attribution using numeric evidence and complete observations. " "Use the theme below and independently tune plausible, interpretable thresholds. " "Reject only on evidence; use None guards; avoid exact sample numbers or names. " "Do not treat missing values as normal. The description should identify the evidence conflict.\n" + rule + "\n" + API_HINT + "\nPaired summaries (summary keys are illustrative, not API accessors):\n" + json.dumps(examples(mined, theme, index, limit=2 if round3 else 3), separators=(",", ":")) ) if index in revisions: prior = json.loads(output.read_bytes()) prompt = ( "Repair this draft's interface or Python subset errors. Preserve its evidence predicate " "and abstain when a measurement needed by the predicate is missing. " "Return the corrected description and one complete function.\n" + API_HINT + "\nGate failure: " + json.dumps({k: revisions[index].get(k) for k in ("exclusion", "validator", "runtime_errors")}) + "\nDraft:\n" + prior["code"] ) if calibrated: prior = json.loads(output.read_bytes()) prompt = ( "Implement this pre-specified monitoring evidence check. Follow the predicate and thresholds " "exactly and avoid extra prerequisites. Return the complete checker and a short description.\n" + rule + "\n" + API_HINT ) async with sem: seed = 53000 + index if calibrated: seed = max(55000 + index, prior["seed"] + 1000) elif prior is not None: seed = prior["seed"] + 1 if round3 else 54000 + index draft = await completion(client, { "model": CODER, "messages": [{"role": "system", "content": SYSTEM}, {"role": "user", "content": prompt}], "temperature": .15 if calibrated else .46 + .07 * ((index // len(THEMES)) % 4), "max_tokens": 1000 if round3 else 1200, "top_p": .93, "seed": seed, "response_format": SCHEMA, }, {"index": index, "theme": theme, "model": CODER, "seed": seed}) if prior is not None: if "error" in draft or draft["finish_reason"] != "stop": return revisions_dir = directory.parent / ("r3_draft_retries" if round3 else "draft_revisions") revisions_dir.mkdir(exist_ok=True) archive = revisions_dir / (output.stem + f"-{prior['seed']}.json") archive.write_text(json.dumps(prior) + "\n") draft["revised_from_seed"] = prior["seed"] tmp = output.with_suffix(".tmp") tmp.write_text(json.dumps(draft) + "\n") tmp.replace(output) print(json.dumps({"candidate": index, "theme": theme, "ok": "error" not in draft}), flush=True)
await asyncio.gather(*(job(index) for index in range(start, start + count)))
if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--count", type=int, default=50) parser.add_argument("--start", type=int, default=0) parser.add_argument("--round3", action="store_true") parser.add_argument("--repair", action="store_true") parser.add_argument("--calibrated", action="store_true") args = parser.parse_args() if sum((args.round3, args.repair, args.calibrated)) > 1: parser.error("select only one of --round3, --repair and --calibrated") restricted_fs() allowed = allowed_inventory("/input/plan.json", "/input/isolation.json") histories = load_resample("/input/samples.jsonl", "/input/labels.jsonl", allowed) initial = mine(histories, rule_library_v2("/output/verified_checkers_v2") if args.round3 else rule_library("/input/h1")) if not initial.pairs and not args.round3: raise ValueError("no_same_case_contrasts_for_generation") if initial.pairs: target = Path("/output/r3_candidates" if args.round3 else "/output/candidates") asyncio.run(synthesize(initial, target, args.count, args.start, args.round3, args.repair, args.calibrated))1234"""W3-02 extensions layered over the earlier FAISI training runtime."""from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)123456789101112131415161718192021"""Skip every GRPO group with no correct root, even if a submission was invalid."""from rl_env.advantages import MIN_SPREAD, guided_grpofrom rl_env.consistency_scorer_v2 import ROOT_HIT_FLOOR
def group_has_reward_variance(rewards): # Recover the six-place rewards after transport through float32 tensors. scale = 1_000_000 top = round(max(rewards) * scale) bottom = round(min(rewards) * scale) return top - bottom >= round(MIN_SPREAD * scale)
def group_can_update_v2(rewards): return round(max(rewards), 6) >= ROOT_HIT_FLOOR and group_has_reward_variance(rewards)
def guided_grpo_v2(token_level_rewards, response_mask, index, epsilon=1e-6, norm_adv_by_std_in_grpo=True, config=None): return guided_grpo(token_level_rewards, response_mask, index, epsilon, norm_adv_by_std_in_grpo, config, accept_group=group_can_update_v2)123456789101112131415161718192021222324252627282930313233343536373839404142434445"""Root-anchored score using a digest-locked extension of the vetted library."""from dataclasses import dataclassfrom functools import lru_cacheimport hashlibimport jsonfrom pathlib import Path
from checkers.engine import load_libraryfrom rl_env.consistency_scorer import RuntimeRule, TopologySupport
ROOT_HIT_FLOOR = .40
@lru_cache(maxsize=2)def rule_library_v2(root="/verified"): root = Path(root) digest = json.loads((root / "manifest.json").read_bytes()) files = sorted(root.glob("check_rule_*.py")) if not 11 <= len(files) <= 16 or sorted(digest) != [f"check_rule_{num:02d}.py" for num in range(1, len(files) + 1)]: raise ValueError("unexpected_v2_library_inventory") if {p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in files} != digest: raise ValueError("v2_library_digest_mismatch") return tuple(RuntimeRule(rule) for rule in load_library(root))
@dataclass(frozen=True, slots=True)class ObservationScoresV2: phi_lib: float all_pass: float phi_topo: float
def observation_scores_v2(ctx, rules): passed = sum(rule.run(ctx)[0] for rule in rules) return ObservationScoresV2(passed / len(rules), float(passed == len(rules)), TopologySupport.from_context(ctx).fraction(ctx))
def guided_reward_v2(observations, root_hit): if observations is None: return -.1 if not root_hit: return 0. return round(ROOT_HIT_FLOOR + .30 * observations.phi_lib + .15 * observations.all_pass + .15 * observations.phi_topo, 6)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647"""Export a trusted local verl FSDP2 actor without editing its checkpoint."""import argparseimport jsonfrom pathlib import Pathimport shutilimport subprocessimport sysfrom tempfile import TemporaryDirectory
def export(actor, output, tokenizer_from): if output.exists(): raise FileExistsError(output) output.parent.mkdir(parents=True, exist_ok=True) with TemporaryDirectory(dir=output.parent, prefix=".fsdp-export-") as scratch: stage = Path(scratch) overlay = stage / "actor" overlay.mkdir() shutil.copytree(actor / "huggingface", overlay / "huggingface") for file in [actor / "fsdp_config.json", *sorted(actor.glob("model_world_size_*_rank_*.pt"))]: (overlay / file.name).symlink_to(file.resolve(strict=True)) config = overlay / "huggingface" / "config.json" data = json.loads(config.read_bytes()) data.pop("attn_implementation", None) config.write_text(json.dumps(data)) weights = stage / "merged" subprocess.run([ sys.executable, "-m", "verl.model_merger", "merge", "--backend", "fsdp", "--local_dir", str(overlay), "--target_dir", str(weights), ], check=True) for name in ("tokenizer.json", "tokenizer_config.json", "vocab.json", "merges.txt"): if not (weights / name).is_file() and (tokenizer_from / name).is_file(): shutil.copyfile(tokenizer_from / name, weights / name) if not list(weights.glob("*.safetensors")) or not (weights / "tokenizer.json").is_file(): raise RuntimeError("incomplete_huggingface_export") for file in weights.iterdir(): file.chmod(0o444) weights.rename(output)
if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--actor", type=Path, required=True) parser.add_argument("--output", type=Path, required=True) parser.add_argument("--tokenizer-from", type=Path, required=True) args = parser.parse_args() export(args.actor, args.output, args.tokenizer_from)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667"""Label terminal submissions in the train-root-only namespace."""from collections import defaultdictfrom concurrent.futures import ThreadPoolExecutorfrom hashlib import blake2simport jsonfrom pathlib import Path
from eval_only.entity_projection import service_keyfrom rl_env.service import Casesfrom sandbox.evaluator import decode_diagnosisfrom sandbox.query_tools import SandboxSession
def score_case(entry, cases, train_roots): (dataset, case), rows = entry snapshot = cases.snapshot(dataset, case) targets = {service_key(name, snapshot.entities) for name in train_roots[dataset][case]} targets.discard(None) result = [] for row in rows: seed = row["session_seed"] submission = row["submission"] hit = False aligned = None valid = submission is not None if valid: session = SandboxSession(snapshot, seed, cases.budget) decoded = decode_diagnosis(session, submission) hit = service_key(decoded["root_entity_id"], snapshot.entities) in targets def opaque(entity): return blake2s(f"{case}/{entity}".encode(), digest_size=12).hexdigest() compared = {(service_key(a, snapshot.entities), service_key(b, snapshot.entities)) for a, b in decoded["propagation_path"]} aligned = sorted((opaque(a), opaque(b)) for a, b in compared if a is not None and b is not None and a != b) result.append({"dataset": dataset, "case_id": case, "sample_idx": row["sample_idx"], "session_seed": seed, "root_hit": hit, "valid": valid, "aligned_path": aligned}) return result
def main(): if any(Path(path).exists() for path in ("/data/vault", "/proc/1/root", "/code/eval_only/evaluate_trajectories.py")): raise RuntimeError("root_scoring_isolation_required") cases = Cases() rows = defaultdict(list) with Path("/data/samples.jsonl").open() as stream: for line in stream: row = json.loads(line) key = cases.check(row | {"phase": "train", "seed": row["session_seed"]}) rows[key].append(row) if rows.keys() != cases.allowed["train"] or any( len(group) != 8 or {row["sample_idx"] for row in group} != set(range(8)) or any(row["session_seed"] != 2000 + row["sample_idx"] for row in group) for group in rows.values() ): raise ValueError("resampled_inventory_incomplete") roots = json.loads(Path("/data/train_roots.json").read_bytes()) count = hits = 0 with ThreadPoolExecutor(max_workers=12) as pool, Path("/state/judge/rewards.jsonl").open("w") as out: for scores in pool.map(lambda entry: score_case(entry, cases, roots), rows.items()): for record in scores: count += 1 hits += record["root_hit"] out.write(json.dumps(record, separators=(",", ":")) + "\n") print(json.dumps({"scored": count, "canonical_root_hits": hits, "vault_opened": False}), flush=True)
if __name__ == "__main__": main()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061"""Materialize a read-only, train-only snapshot view for standalone resampling."""import argparseimport jsonimport osfrom pathlib import Pathimport shutil
from checkers.inventory import ALLOWLIST_SHA256, train_allowlistfrom sandbox.snapshot import FILES
def prepare(run, w301, snapshots, window_index): allowed = train_allowlist(w301 / "data/allowlists.json") windows = json.loads(window_index.read_bytes()) train_windows = {} source_roots = w301 / "roots/train_roots.json" roots = json.loads(source_roots.read_bytes()) if {(dataset, case) for dataset, group in roots.items() for case in group} != allowed: raise ValueError("unexpected_train_roots") snapshots = snapshots.resolve(strict=True) for dataset, case in sorted(allowed): origin = snapshots / dataset / case if origin.is_symlink() or set(item.name for item in origin.iterdir()) != FILES: raise ValueError("invalid_snapshot_layout") target = run / "snapshots" / dataset / case target.mkdir(parents=True, exist_ok=True) for name in FILES: source = origin / name if source.is_symlink() or not source.is_file(): raise ValueError("invalid_snapshot_file") out = target / name if not out.exists(): os.link(source, out) elif not os.path.samefile(source, out): raise ValueError("snapshot_view_content_changed") train_windows.setdefault(dataset, {})[case] = windows["windows"][dataset][case] present = {(path.parent.name, path.name) for path in (run / "snapshots").glob("*/*") if path.is_dir()} if present != allowed: raise ValueError("unexpected_snapshot_view_inventory") (run / "data").mkdir(exist_ok=True) (run / "roots").mkdir(exist_ok=True) (run / "verified").mkdir(exist_ok=True) roles = {"train": sorted(allowed), "id_test": [], "ood_test": [], "ood_all": []} (run / "data/allowlists.json").write_text(json.dumps(roles, separators=(",", ":"))) (run / "data/windows.json").write_text(json.dumps({"version": 1, "windows": train_windows})) shutil.copyfile(source_roots, run / "roots/train_roots.json") (run / "roots/train_roots.json").chmod(0o444) for file in (w301 / "verified").iterdir(): shutil.copyfile(file, run / "verified" / file.name) (run / "input_audit.json").write_text(json.dumps({ "source_allowlist_sha256": ALLOWLIST_SHA256, "train_snapshot_count": len(present), "eval_snapshots_in_view": 0, "vault_mounted": False, "train_roots_only": True, }, indent=2) + "\n")
if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) for option in ("run", "w301", "snapshots", "window-index"): parser.add_argument("--" + option, required=True, type=Path) args = parser.parse_args() prepare(args.run, args.w301, args.snapshots, args.window_index)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162"""Prepare byte-identical splits, root-only labels, and the admitted v2 library."""import argparseimport hashlibimport jsonfrom pathlib import Pathimport shutil
from checkers.inventory import ALLOWLIST_SHA256, train_allowlist
DATA_FILES = ("allowlists.json", "train.parquet", "val.parquet", "split_summary.json")
def digest(path): return hashlib.sha256(path.read_bytes()).hexdigest()
def prepare(run, source, gate_dir, pilot): inventory = train_allowlist(source / "data/allowlists.json") roots = json.loads((source / "roots/train_roots.json").read_bytes()) if {(dataset, case) for dataset, cases in roots.items() for case in cases} != inventory: raise ValueError("sealed_roots_changed") inputs = pilot or source / "data" selection = {tuple(entry) for entry in json.loads((inputs / "allowlists.json").read_bytes())["train"]} if not selection <= inventory or (not pilot and selection != inventory): raise ValueError("scaling_training_scope_changed") for sub in ("data", "verified", "roots"): (run / sub).mkdir(parents=True, exist_ok=True) for name in DATA_FILES: shutil.copyfile(inputs / name, run / "data" / name) pure_roots = {ds: {case: names for case, names in cases.items() if (ds, case) in selection} for ds, cases in roots.items()} root_path = run / "roots/train_roots.json" root_path.write_text(json.dumps(pure_roots, separators=(",", ":"))) root_path.chmod(0o444) report = json.loads((gate_dir / "w3_02_checker_v2_report.json").read_bytes()) if report["overall_pass"] is not True: raise ValueError("v2_gate_not_accepted") verified = gate_dir / "verified_checkers_v2" inventory_v2 = json.loads((verified / "manifest.json").read_bytes()) previous = json.loads((source / "verified/manifest.json").read_bytes()) if any(inventory_v2.get(name) != sha for name, sha in previous.items()) or not 11 <= len(inventory_v2) <= 16: raise ValueError("v2_library_must_preserve_h1") for name, sha in inventory_v2.items(): if digest(verified / name) != sha: raise ValueError("v2_source_digest_mismatch") shutil.copyfile(verified / name, run / "verified" / name) shutil.copyfile(verified / "manifest.json", run / "verified/manifest.json") (run / "isolation_audit.json").write_text(json.dumps({ "formal_allowlist_sha256": ALLOWLIST_SHA256, "data_sha256": {name: digest(run / "data" / name) for name in DATA_FILES}, "train_roots_count": len(selection), "train_vault_mounted": False, "source_manifest": inventory_v2, }, indent=2) + "\n")
if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) for name in ("run", "source", "gate-dir"): parser.add_argument("--" + name, required=True, type=Path) parser.add_argument("--pilot", type=Path) args = parser.parse_args() prepare(args.run, args.source, args.gate_dir, args.pilot)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144"""Re-sample an exported 7B policy with the W3-01 prompt and a sealed train-only plan."""import argparseimport asyncioimport jsonfrom pathlib import Pathimport randomfrom types import SimpleNamespace
import httpxfrom transformers import AutoTokenizer
from rl_env.common import SOCKET_LIMIT, json_bytesfrom rl_env.sandbox_env import SandboxAgentLoop
SEED_BASE = 2000GROUP_SIZE = 8ENTRY = Path("/state/train/samples.jsonl")PLAN = Path("/state/data/allowlists.json")
class LocalGeneration: def __init__(self, client, model_name): self.client = client self.model_name = model_name
async def generate(self, request_id, prompt_ids, sampling_params): decode = {key: sampling_params[key] for key in ("seed", "temperature", "top_p", "max_tokens")} response = await self.client.post("/v1/completions", json={ "model": self.model_name, "prompt": prompt_ids, **decode, "return_token_ids": True, "structured_outputs": {"json": sampling_params["structured_outputs"].json}, }) response.raise_for_status() tokens = response.json()["choices"][0]["token_ids"] return SimpleNamespace(token_ids=tokens, log_probs=[0.0] * len(tokens), extra_fields={})
class Collector(SandboxAgentLoop): def __init__(self, server, tokenizer, sink): self.server_manager = server self.tokenizer = tokenizer self.rollout_config = SimpleNamespace(response_length=10240) self.sink = sink
async def ct_build_initial_tokens(self, messages, tools=None): rendered = self.tokenizer.apply_chat_template(messages, tools=tools, tokenize=False, add_generation_prompt=True) tokens = self.tokenizer.encode(rendered, add_special_tokens=False) if len(tokens) > 2048: raise ValueError("initial_prompt_over_budget") return tokens
async def score_episode(self, key, step, trace): self.sink.write(json_bytes({"dataset": key["dataset"], "case_id": key["case_id"], "sample_idx": key["seed"] - SEED_BASE, "session_seed": key["seed"], **trace})) self.sink.flush() return 0.0
async def collect(self, dataset, case, sample): key = {"dataset": dataset, "case_id": case, "phase": "train", "seed": SEED_BASE + sample} reader, writer = await asyncio.open_unix_connection("/ipc/tools.sock", limit=SOCKET_LIMIT) try: writer.write(json_bytes(key)) await writer.drain() overview = json.loads(await asyncio.wait_for(reader.readline(), 120)) if "error" in overview: raise RuntimeError("isolated_overview_failed") await self.interact(reader, writer, key, overview, 0, {"temperature": .7, "top_p": .95}, {"uid": f"{dataset}-{case}-{sample}", "session_id": sample}) finally: writer.close() await writer.wait_closed()
def selection(): plan = json.loads(PLAN.read_bytes()) if set(plan) != {"train", "id_test", "ood_test", "ood_all"} or any(plan[name] for name in plan if name != "train"): raise ValueError("sampling_requires_train_only_allowlist") cases = sorted(map(tuple, plan["train"])) if len(cases) != 621 or len(set(cases)) != 621: raise ValueError("bad_training_case_inventory") random.Random(42).shuffle(cases) return [(dataset, case, sample) for dataset, case in cases for sample in range(GROUP_SIZE)]
def existing(path, expected): if not path.exists(): return set() seen = set() with path.open("rb+") as stream: for line in iter(stream.readline, b""): if not line.endswith(b"\n"): stream.truncate(stream.tell() - len(line)) break row = json.loads(line) key = row["dataset"], row["case_id"], row["sample_idx"] if key in seen or key not in expected or row["session_seed"] != SEED_BASE + key[2]: raise ValueError("invalid_resume_trajectories") seen.add(key) return seen
async def run(model_name, concurrency): if Path("/data/vault").exists() or Path("/data/train_roots.json").exists() or Path("/data/snapshots").exists(): raise RuntimeError("sampler_mounts_unexpected_data") planned = selection() seen = existing(ENTRY, set(planned)) todo = iter(key for key in planned if key not in seen) tokenizer = AutoTokenizer.from_pretrained("/model", local_files_only=True) transport = httpx.AsyncHTTPTransport(uds="/tmp/generate.sock", limits=httpx.Limits(max_connections=concurrency, max_keepalive_connections=concurrency)) async with httpx.AsyncClient(transport=transport, base_url="http://local", timeout=180) as client: models = (await client.get("/v1/models")).raise_for_status().json() if model_name not in {row["id"] for row in models["data"]}: raise ValueError("unexpected_sampling_model") with ENTRY.open("ab") as stream: collector = Collector(LocalGeneration(client, model_name), tokenizer, stream)
async def worker(): for key in todo: for attempt in range(3): try: await collector.collect(*key) break except httpx.TransportError: if attempt == 2: raise await asyncio.sleep(attempt + 1) seen.add(key) if len(seen) % 128 == 0: print(json.dumps({"completed": len(seen), "planned": len(planned)}), flush=True)
await asyncio.gather(*(worker() for _ in range(concurrency))) if len(seen) != len(planned): raise RuntimeError("incomplete_resampling") print(json.dumps({"completed": len(seen), "planned": len(planned)}), flush=True)
if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--model-name", required=True) parser.add_argument("--concurrency", type=int, default=96) args = parser.parse_args() if not 1 <= args.concurrency <= 128: parser.error("concurrency must be between 1 and 128") asyncio.run(run(args.model_name, args.concurrency))123456from rl_env.consistency_scorer_v2 import rule_library_v2from rl_env.guided_loop import GuidedAgentLoop
class ScalingAgentLoop(GuidedAgentLoop): load_rules = staticmethod(rule_library_v2)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242"""Report exact grouping, checkpoints and paired cross-policy comparisons."""import argparsefrom collections import Counter, defaultdictimport jsonfrom pathlib import Pathfrom statistics import fmean
from rl_env.advantages_v2 import group_can_update_v2, group_has_reward_variancefrom rl_env.consistency_scorer_v2 import ObservationScoresV2, guided_reward_v2from rl_env.curve import load_rows, runtime_metrics, training_statsfrom rl_env.guided_report import COHORTS, cohort, collect, curve, differences, paired_evidence, scope_allowlists, timing_report
ROOT = "canonical_service_ac_at_1"PATH_F1 = "canonical_path_edge_f1"GROUNDED = "canonical_grounded_ac_at_1"
def valid_reward(row): if row["invalid"]: return row["score"] == -.1 and not row["root_hit"] value = ObservationScoresV2(row["phi_lib"], row["all_pass"], row["phi_topo"]) return (0 <= value.phi_lib <= 1 and value.all_pass == float(value.phi_lib == 1) and 0 <= value.phi_topo <= 1 and row["score"] == guided_reward_v2(value, row["root_hit"]))
def verify_updates(root, train): rows = list(load_rows(root / "judge/rewards.jsonl")) grouped = defaultdict(list) for row in rows: grouped[row["step"], row["dataset"], row["case_id"]].append(row) counts = defaultdict(Counter) for (step, _, _), rewards in grouped.items(): root_hits = sum(row["root_hit"] for row in rewards) scores = [row["score"] for row in rewards] active = group_can_update_v2(scores) counts[step]["groups"] += 1 counts[step]["active"] += active counts[step]["all_miss"] += root_hits == 0 counts[step]["active_all_miss"] += active and root_hits == 0 counts[step]["root_hits"] += root_hits counts[step]["below_min_spread"] += not group_has_reward_variance(scores) for step in train["steps"]: stage = counts[step["step"]] if (step["outcome/active_groups"] != stage["active"] or step["outcome/groups"] != stage["groups"] or stage["active_all_miss"]): raise ValueError("root_anchored_update_ledger_disagreement") step["root_anchored_group_diagnostics"] = {key: stage[key] for key in ( "groups", "active", "all_miss", "active_all_miss", "root_hits", "below_min_spread", )} return { "active_group_fraction": train["active_groups"] / train["full_groups"], "zero_variance_group_ratio": sum(s["below_min_spread"] for s in counts.values()) / train["full_groups"], "all_miss_groups": sum(s["all_miss"] for s in counts.values()), "active_all_miss_groups": sum(s["active_all_miss"] for s in counts.values()), "optimizer_steps": sum(step["outcome/active_groups"] > 0 for step in train["steps"]), "total_training_root_hit_rate": fmean(row["root_hit"] for row in rows), "invalid_submission_rate": fmean(row["invalid"] for row in rows), "ipc_one_way_receive_ms": timing_report([row["receive_ms"] for row in rows]), "mean_trace_message_bytes": fmean(row["message_bytes"] for row in rows), }
def summarize_run(root): config = json.loads((root / "trainhome/run.json").read_bytes()) split = json.loads((root / "data/split_summary.json").read_bytes()) audit = json.loads((root / "isolation_audit.json").read_bytes()) sealed = scope_allowlists(root) rows = collect(root / "judge/evaluations.jsonl", sealed, config["milestones"], config["runtime_guard_steps"]) train = training_stats(root, config, valid_reward=valid_reward) train.update(verify_updates(root, train)) model_shards = config.get("checkpoint_model_shards_saved", True) summary = { "training_hyperparameters": config, "split_inventory": split, "input_isolation": audit, "training_logs_summary": train, "runtime": runtime_metrics(root), "checkpoint_evaluation_curve": curve(root, rows, "direct", config["milestones"], config["steps"], model_shards), "runtime_guard_evaluation_curve": curve(root, rows, "guard", config["runtime_guard_steps"], config["steps"], model_shards), } return summary, rows
def read_prior(run, report_path, allowed, direct, guard=()): observations = collect(run / "judge/evaluations.jsonl", allowed, direct, guard) json_report = json.loads(report_path.read_bytes()) final = {"direct": json_report["checkpoint_evaluation_curve"][-1]} if guard: final["guard"] = json_report["runtime_guard_evaluation_curve"][-1] return final, observations
def key_to_curve(mode): return "checkpoint_evaluation_curve" if mode == "direct" else "runtime_guard_evaluation_curve"
def compare_run(result, evaluation_rows, control): results = [] for mode in ("direct", "guard"): nodes = result[key_to_curve(mode)] comparison = {"mode": mode, "step": nodes[-1]["step"], "comparisons": {}} policies = dict(control) policies["own_step_0"] = ({mode: nodes[0]}, evaluation_rows) for name, (prior, prior_rows) in policies.items(): selected = mode if mode in prior else "direct" old = prior[selected] new = nodes[-1] comparison["comparisons"][name] = { "baseline_mode": selected, "baseline_step": old["step"], "difference_by_cohort": {k: differences(new[k], old[k]) for k in COHORTS}, "paired_by_cohort": { k: paired_evidence(cohort(evaluation_rows, mode, new["step"], k), cohort(prior_rows, selected, old["step"], k)) for k in COHORTS }, } results.append(comparison) return results
def scoped_best(comparators): fields = (("id_test", ROOT), ("id_test", PATH_F1), ("id_test", GROUNDED), ("ood_all", ROOT)) return {f"{cohort_name}/{field}": max(node[cohort_name][field] for node in comparators) for cohort_name, field in fields}
def compare_totals(r2, large, repo, smoke=None): a, ra = summarize_run(r2) b, rb = summarize_run(large) sealed = scope_allowlists(r2) if sealed != scope_allowlists(large) or a["training_hyperparameters"]["smoke"] or b["training_hyperparameters"]["smoke"]: raise ValueError("formal_scope_comparison_required") anchored = Path("/mnt/workspace/.local/faisi") p1 = repo / "W2-01-outcome-rl/reports/w2_01_outcome_rl_curve.json" p3 = repo / "W3-01-guided-rl/reports/w3_01_guided_rl_report.json" w201 = read_prior(anchored / "w2-01/full", p1, sealed, (0, 13, 26, 39, 52)) w301 = read_prior(anchored / "w3-01/full", p3, sealed, (0, 13, 26, 39, 52), (0, 52)) prior = {"w2_01_final": w201, "w3_01_final": w301} a["paired_comparisons"] = compare_run(a, ra, prior) r2_final = {mode: a[key_to_curve(mode)][-1] for mode in ("direct", "guard")} b["paired_comparisons"] = compare_run(b, rb, prior | {"w3_02_7b_r2_final": (r2_final, ra)}) a["initial_checkpoint_alignment_w3_01_step52_direct"] = { name: { "difference": differences(a["checkpoint_evaluation_curve"][0][name], w301[0]["direct"][name]), "paired": paired_evidence(cohort(ra, "direct", 0, name), cohort(w301[1], "direct", 52, name)), } for name in COHORTS } if smoke is not None: pilot, _ = summarize_run(smoke) if pilot["training_hyperparameters"]["experiment"] != "guided_14b" or not pilot["training_hyperparameters"]["smoke"]: raise ValueError("14b_smoke_required") b["single_step_smoke"] = { "runtime": pilot["runtime"], "optimizer_steps": pilot["training_logs_summary"]["optimizer_steps"], "training_steps": pilot["training_logs_summary"]["steps"], } root_w2 = w201[0]["direct"]["id_test"][ROOT] root_r1 = w301[0]["direct"]["id_test"][ROOT] r2_modes = {} for review in a["paired_comparisons"]: mode = review["mode"] current = a[key_to_curve(mode)][-1] delta = review["comparisons"]["w2_01_final"]["difference_by_cohort"] r2_modes[mode] = { "root_above_r1_direct_and_at_least_w201": current["id_test"][ROOT] > root_r1 and current["id_test"][ROOT] >= root_w2, "id_path_f1_above_w201": delta["id_test"][PATH_F1] > 0, "id_grounded_above_w201": delta["id_test"][GROUNDED] > 0, "ood_test_at_least_w201": delta["ood_test"][ROOT] >= 0, "ood_all_above_w201": delta["ood_all"][ROOT] > 0, } previous_nodes = [] for file in (p1, p3): report = json.loads(file.read_bytes()) previous_nodes.extend(report["checkpoint_evaluation_curve"] + report.get("runtime_guard_evaluation_curve", [])) previous_nodes.extend(a["checkpoint_evaluation_curve"] + a["runtime_guard_evaluation_curve"]) comparable_highs = scoped_best(previous_nodes) modes14 = {} for review in b["paired_comparisons"]: mode = review["mode"] delta = review["comparisons"]["own_step_0"]["difference_by_cohort"] current = b[key_to_curve(mode)][-1] modes14[mode] = { "id_root_positive": delta["id_test"][ROOT] > 0, "id_path_f1_positive": delta["id_test"][PATH_F1] > 0, "id_grounded_positive": delta["id_test"][GROUNDED] > 0, "ood_all_root_positive": delta["ood_all"][ROOT] > 0, "deltas_vs_comparable_existing_best": { key: current[key.split("/", 1)[0]][key.split("/", 1)[1]] - high for key, high in comparable_highs.items() }, } clear_best = any(all(v >= 0 for v in mode["deltas_vs_comparable_existing_best"].values()) and any(v > 0 for v in mode["deltas_vs_comparable_existing_best"].values()) for mode in modes14.values()) r2_ok = a["runtime"]["explicit_oom_log_matches"] == 0 and any(all(entry.values()) for entry in r2_modes.values()) large_ok = b["runtime"]["explicit_oom_log_matches"] == 0 and clear_best and all( all(value for key, value in mode.items() if key != "deltas_vs_comparable_existing_best") for mode in modes14.values() ) return { "overall_pass": r2_ok and large_ok, "experiments": {"7b_r2": a, "14b_guided": b}, "acceptance": { "7b_r2_pass": r2_ok, "7b_r2_per_mode": r2_modes, "14b_guided_pass": large_ok, "14b_guided_per_mode": modes14, "comparable_existing_componentwise_best": comparable_highs, "14b_clear_comprehensive_best": clear_best, "comprehensive_best_definition": ( "Pareto comparison to component-wise maxima across the matched W2-01, W3-01 and 7B-R2 " "ID and OOD-All cohorts. No scalar ordering of the metrics was assumed." ), }, }
def write(path, report): path.parent.mkdir(parents=True, exist_ok=True) tmp = path.with_suffix(".tmp") tmp.write_text(json.dumps(report, indent=2, allow_nan=False) + "\n") tmp.replace(path)
if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) sub = parser.add_subparsers(dest="mode", required=True) single = sub.add_parser("single") single.add_argument("run", type=Path) full = sub.add_parser("combine") for arg in ("r2", "large", "repo", "output"): full.add_argument("--" + arg, type=Path, required=True) full.add_argument("--smoke", type=Path) args = parser.parse_args() if args.mode == "single": report, _ = summarize_run(args.run) write(args.run / "training_report.json", report) print(json.dumps({"run": report["training_hyperparameters"]["experiment"], "oom": report["runtime"]["explicit_oom_log_matches"], "active_all_miss_groups": report["training_logs_summary"]["active_all_miss_groups"]})) else: report = compare_totals(args.r2, args.large, args.repo, args.smoke) write(args.output, report) print(json.dumps(report["acceptance"]))123456789101112131415161718192021222324"""Use the existing isolated score/guard protocol with the v2 observation score."""import argparseimport asyncio
from rl_env.consistency_scorer_v2 import guided_reward_v2, observation_scores_v2, rule_library_v2from rl_env.guided_services import GuidedEvaluator, GuidedJudge, GuidedTools, run
class V2Judge(GuidedJudge): load_rules = staticmethod(rule_library_v2) observe = staticmethod(observation_scores_v2) reward = staticmethod(guided_reward_v2)
class V2Evaluator(GuidedEvaluator): load_rules = staticmethod(rule_library_v2) observe = staticmethod(observation_scores_v2)
if __name__ == "__main__": roles = {"tools": GuidedTools, "judge": V2Judge, "eval": V2Evaluator} parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("role", choices=roles) asyncio.run(run(parser.parse_args().role, roles))12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091"""Run the 7B continuation and the native-offload 14B full experiment."""import argparseimport json
import rayfrom omegaconf import OmegaConffrom verl.trainer.main_ppo import run_ppo
from rl_env.advantages import MIN_SPREAD, STD_FLOORfrom rl_env.advantages_v2 import group_can_update_v2, guided_grpo_v2from rl_env.consistency_scorer_v2 import ROOT_HIT_FLOORfrom rl_env.guided_trainer import GuidedTrainerfrom rl_env.train import STATE, make_config, run_trainer
EXPERIMENTS = { "r2_7b": {"steps": 26, "epochs": 1, "lr": 5e-7, "tp": 2, "model": "W3-01-step-52"}, "guided_14b": {"steps": 52, "epochs": 2, "lr": 8e-7, "tp": 4, "model": "Qwen2.5-14B-Instruct"},}
class ScalingTrainer(GuidedTrainer): advantage_function = staticmethod(guided_grpo_v2)
def group_can_update(self, rewards): return group_can_update_v2(rewards)
@ray.remote(num_cpus=1)class ScalingTaskRunner: def run(self, config): return run_trainer(config, ScalingTrainer)
def scaling_config(experiment, smoke=False): config = make_config(smoke) design = dict(EXPERIMENTS[experiment]) steps = 1 if smoke else design["steps"] epochs = 1 if smoke else design["epochs"] freq = 1 if smoke else 13 if experiment == "r2_7b" else 26 config.trainer.total_epochs = epochs config.trainer.total_training_steps = steps config.trainer.save_freq = config.trainer.test_freq = freq config.trainer.project_name = "faisi-w3-02" config.trainer.experiment_name = experiment + ("-smoke" if smoke else "") config.actor_rollout_ref.actor.optim.lr = design["lr"] config.actor_rollout_ref.rollout.tensor_model_parallel_size = design["tp"] # The pod has a shared thread budget across Ray, vLLM and the tool services. config.actor_rollout_ref.rollout.agent.num_workers = 4 native_offload = experiment == "guided_14b" if native_offload: config.actor_rollout_ref.rollout.gpu_memory_utilization = .76 config.actor_rollout_ref.rollout.enforce_eager = True config.actor_rollout_ref.actor.fsdp_config.offload_policy = True config.actor_rollout_ref.ref.fsdp_config.offload_policy = True # Bound packed microbatches by the existing per-GPU token limit. This # amortizes CPU gradient offload across multiple short trajectories. config.actor_rollout_ref.actor.use_dynamic_bsz = True if smoke: config.actor_rollout_ref.actor.checkpoint.save_contents = ["extra"] (STATE / "config.yaml").write_text(OmegaConf.to_yaml(config, resolve=True)) marker = STATE / "run.json" info = json.loads(marker.read_bytes()) info.update(design | { "smoke": smoke, "steps": steps, "epochs": epochs, "experiment": experiment, "milestones": list(range(0, steps + 1, freq)), "runtime_guard_steps": [0, steps], "rollout_tensor_parallel": design["tp"], "reward": "w302_root_anchored_v2", "grpo_std_floor": STD_FLOOR, "min_group_reward_spread": MIN_SPREAD, "root_hit_score_floor": ROOT_HIT_FLOOR, "fsdp2_cpu_offload_policy": native_offload, "activation_cpu_offload": config.actor_rollout_ref.model.enable_activation_offload, "dynamic_microbatching": config.actor_rollout_ref.actor.use_dynamic_bsz, "actor_tokens_per_gpu_limit": config.actor_rollout_ref.actor.ppo_max_token_len_per_gpu, "checkpoint_model_shards_saved": not smoke, "agent_workers": config.actor_rollout_ref.rollout.agent.num_workers, "rollout_enforce_eager": config.actor_rollout_ref.rollout.enforce_eager, "rollout_gpu_memory_utilization": config.actor_rollout_ref.rollout.gpu_memory_utilization, "actor_ref_gpu_count": config.trainer.n_gpus_per_node, "rollout_gpu_count": config.actor_rollout_ref.rollout.n_gpus_per_node, }) marker.write_text(json.dumps(info, indent=2) + "\n") return config
if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("experiment", choices=EXPERIMENTS) parser.add_argument("--smoke", action="store_true") args = parser.parse_args() try: run_ppo(scaling_config(args.experiment, args.smoke), task_runner_class=ScalingTaskRunner) finally: ray.shutdown()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576from types import SimpleNamespace
import pytestimport torch
from checker_v2.gate import Candidate, choosefrom checker_v2.mine_residual_conflicts import Sample, minefrom checkers.context_api import OVERVIEW_FIELDS, TrajectoryContextfrom rl_env.advantages_v2 import group_can_update_v2, guided_grpo_v2from rl_env.consistency_scorer_v2 import ObservationScoresV2, guided_reward_v2
def test_v2_reward_distinguishes_invalid_misses_and_supported_hits(): all_pass = ObservationScoresV2(1, 1, 1) assert guided_reward_v2(None, False) == -.1 assert guided_reward_v2(all_pass, False) == 0 assert guided_reward_v2(all_pass, True) == 1 assert guided_reward_v2(ObservationScoresV2(1, 1, 0), True) == .85 assert guided_reward_v2(ObservationScoresV2(.5, 0, .5), True) == .625 assert guided_reward_v2(ObservationScoresV2(0, 0, 0), True) == .40
def test_v2_skips_every_all_miss_group_and_preserves_advantage_floor(): assert not group_can_update_v2([-.1, 0.] * 4) assert not group_can_update_v2([.03, .12] * 4) assert not group_can_update_v2([.4] * 7 + [.40009]) assert group_can_update_v2([.4] * 7 + [.4001]) assert group_can_update_v2([0.] * 7 + [.4]) rewards = torch.tensor([[value, 0.] for value in [-.1, 0.] * 4 + [.4, .43] * 4]) mask = torch.tensor([[1, 0]] * len(rewards)) advantages, returns = guided_grpo_v2(rewards, mask, ["miss"] * 8 + ["hit"] * 8) assert advantages[:8, 0].tolist() == [0.] * 8 assert advantages[8:, 0].tolist() == pytest.approx([-.1, .1] * 4, abs=1e-6) assert not advantages[:, 1].any() assert torch.equal(advantages, returns)
def test_residuals_require_a_valid_miss_and_a_supported_anchored_case(): def sample(case, slot, hit, valid=True, root="SVC_01", projected=None): ctx = TrajectoryContext.from_trace({ "initial_observation": {"result": {"fields": OVERVIEW_FIELDS, "anomalies": []}}, "turns": [], "num_turns": 0, "submission": {"root_entity_id": root, "propagation_path": []} if valid else None, }) return Sample(("synthetic", case), slot, ctx, hit, valid, frozenset(projected or ()))
rule = SimpleNamespace(run=lambda ctx: (ctx.submitted_root != "SVC_03", "test")) rows = ( sample("a", 0, True), sample("a", 1, False), sample("a", 2, False, valid=False), sample("a", 3, False, root="SVC_03"), sample("a", 4, True, projected=[("a", "b")]), sample("b", 0, False), ) result = mine(rows, [rule]) assert result.anchors == {0, 4} assert result.residual == {1} assert result.divergent == ((0, 4),) assert result.report()["wrong_root_and_library_passes"] == 2
def test_gate_requires_unique_coverage_within_joint_anchor_budget(): def candidate(index, false_positives, true_positives): return Candidate(None, {"index": index, "fpr_w202_anchor": .01}, frozenset(false_positives), frozenset(true_positives))
c1 = candidate(1, range(0, 3), range(0, 10)) duplicate = candidate(2, range(0, 3), range(0, 10)) c3 = candidate(3, range(2, 5), range(10, 17)) c4 = candidate(4, range(6, 9), range(17, 23)) c5 = candidate(5, range(0, 3), [17]) winners, rejected, covered = choose([c5, c4, c3, duplicate, c1], 40, 100) assert [(rule.result["index"], delta) for rule, delta in winners] == [(1, .10), (3, .07)] assert len(rejected) == 5 assert len(covered) == 171234567891011def check_rule_01(ctx: 'TrajectoryContext') -> tuple[bool, str]: if ctx.distinct_observed_anomalous_services() < 2: return (True, 'ok') if ctx.distinct_observed_anomalous_services() >= 2: root = ctx.submitted_root if root in ctx.observed_metrics and (not ctx.inter_service_edges_in_submission()): root_owner = ctx.owner_service(root) if not ctx.observed_events.get(root): if all((ctx.owner_service(entity) == root_owner for entity in ctx.observed_metrics if entity != root)): return (False, 'multi_service_isolation_no_new_evidence') return (True, 'ok')12345678def check_rule_02(ctx: 'TrajectoryContext') -> tuple[bool, str]: if ctx.distinct_observed_anomalous_services() < 2: return (True, 'ok') owners = set((ctx.owner_service(e) for e in ctx.queried_entities)) if len(owners) == 1: if not ctx.inter_service_edges_in_submission(): return (False, 'missing_inter_service_path') return (True, 'ok')123456789101112131415def check_rule_03(ctx: 'TrajectoryContext') -> tuple[bool, str]: if ctx.distinct_observed_anomalous_services() < 2: return (True, 'ok') if not ctx.submitted_path: return (True, 'ok') root = ctx.submitted_root if ctx.entity_layer(root) != 'instance': return (True, 'ok') if ctx.distinct_anomalous_services_in_overview() <= 1: return (True, 'ok') if any((ctx.owner_service(caller) != ctx.owner_service(callee) for (caller, callee) in ctx.inter_service_edges_in_submission())): return (True, 'ok') if root in ctx.queried_topology_entities: return (True, 'ok') return (False, 'uninspected_instance_root')1234567891011def check_rule_04(ctx: 'TrajectoryContext') -> tuple[bool, str]: if ctx.distinct_observed_anomalous_services() < 2: return (True, 'ok') if ctx.entity_layer(ctx.submitted_root) != 'instance': return (True, 'ok') services = ctx.distinct_observed_anomalous_services() if services < 2: return (True, 'ok') if ctx.inter_service_edges_in_submission(): return (True, 'ok') return (False, 'unsupported_instance_service_boundary')12345678def check_rule_05(ctx: 'TrajectoryContext') -> tuple[bool, str]: if ctx.distinct_observed_anomalous_services() < 2: return (True, 'ok') if not ctx.submitted_path or all((ctx.owner_service(c) == ctx.owner_service(a) for (c, a) in ctx.submitted_path)): cross_owner_edges = any((ctx.owner_service(caller) != ctx.owner_service(callee) for (caller, callee) in ctx.observed_edges)) if not cross_owner_edges: return (False, 'unsupported_multi_service_isolation') return (True, 'ok')1234567def check_rule_06(ctx: 'TrajectoryContext') -> tuple[bool, str]: if ctx.distinct_observed_anomalous_services() < 2: return (True, 'ok') inter_service_edges = ctx.inter_service_edges_in_submission() if not inter_service_edges: return (False, 'missing_cross_service_edges') return (True, 'ok')12345678910def check_rule_07(ctx: 'TrajectoryContext') -> tuple[bool, str]: for (cause, affected) in ctx.submitted_path: if ctx.owner_service(cause) != ctx.owner_service(affected): onset_diff = ctx.onset_diff(cause, affected) if onset_diff is not None and onset_diff < 0: return (False, 'negative_onset_diff_cross_owner') anomalous_services_count = ctx.distinct_observed_anomalous_services() if anomalous_services_count >= 2 and (not ctx.inter_service_edges_in_submission()) and (ctx.earliest_anomaly_offset(ctx.submitted_root) is not None): return (False, 'unexplained_multi_service_anomalies') return (True, 'ok')1234567def check_rule_08(ctx: 'TrajectoryContext') -> tuple[bool, str]: root = ctx.submitted_root if not any((ctx.owner_service(e) == ctx.owner_service(root) for e in ctx.queried_entities)): return (False, 'uninspected_diagnosis_family') if ctx.distinct_observed_anomalous_services() >= 2 and root in ctx.observed_metrics and (root not in ctx.queried_topology_entities) and (not ctx.inter_service_edges_in_submission()): return (False, 'multi_service_missing_cross_owner_path') return (True, 'ok')12345678def check_rule_09(ctx: 'TrajectoryContext') -> tuple[bool, str]: own = ctx.owner_service(ctx.submitted_root) competing = {ctx.owner_service(e) for e in ctx.queried_entities if ctx.owner_service(e) != own} roots = [row['robust_z'] for (e, row) in ctx.overview_anomalies.items() if ctx.owner_service(e) == own and row.get('robust_z') is not None] peers = [row['robust_z'] for (e, row) in ctx.overview_anomalies.items() if ctx.owner_service(e) != own and row.get('robust_z') is not None] if len(competing) >= 2 and roots and peers and (max(roots) * 2 < max(peers)): return (False, 'competing_services_more_severe') return (True, 'ok')123456789def check_rule_10(ctx: 'TrajectoryContext') -> tuple[bool, str]: own = ctx.owner_service(ctx.submitted_root) peers = {ctx.owner_service(e) for e in ctx.queried_entities if ctx.owner_service(e) != own} linked = any((own in (ctx.owner_service(a), ctx.owner_service(b)) for (a, b) in ctx.observed_edges)) if len(peers) >= 2: ratio = ctx.co_located_anomaly_ratio(ctx.submitted_root) if ratio is not None and ratio >= 0.5 and (not linked): return (False, 'inconsistent_peer_and_colocation') return (True, 'ok')1234567def check_rule_11(ctx: 'TrajectoryContext') -> tuple[bool, str]: if ctx.queried_edges: root = ctx.submitted_root owner = ctx.owner_service(root) if not ctx.observed_topology.get(root) and (not ctx.observed_topology.get(owner)): return (False, 'missing_root_topology_verification') return (True, 'ok')12345678910def check_rule_12(ctx: 'TrajectoryContext') -> tuple[bool, str]: root = ctx.submitted_root own = ctx.owner_service(root) root_ids = {root, own} | {e for e in ctx.queried_entities if ctx.owner_service(e) == own} peer_ids = {e for e in ctx.queried_entities if ctx.owner_service(e) != own and ctx.has_direct_anomaly(e)} root_offsets = [ctx.earliest_anomaly_offset(e) for e in root_ids if ctx.earliest_anomaly_offset(e) is not None] peer_offsets = [ctx.earliest_anomaly_offset(e) for e in peer_ids if ctx.earliest_anomaly_offset(e) is not None] if root_offsets and peer_offsets and (min(root_offsets) - min(peer_offsets) >= 60): return (False, 'root_later_than_observed_peer') return (True, 'ok')1234567891011121314{ "check_rule_01.py": "71ccd9040b8fdb857c3895e7996ae56ffbd43f3962e34e9a9821102ac3a6b4be", "check_rule_02.py": "c395ca2bf73f7176b456de30af2b091e2defafdf84695e380a9e6cfd6b78d47b", "check_rule_03.py": "0429f6867a6f5edbf2b1753547dcb1a923a40d23c165434d2a96c7b2387f731b", "check_rule_04.py": "50d946c853c789e9be63fb0382a076186e8356d379c7feae73e634983c61b86a", "check_rule_05.py": "096927d37039b519480f17b8a388144afcc0e136cde27e8a13867a52de2d9f87", "check_rule_06.py": "3a7e3c0f78a5e4e70209709b4e8322f59bd1b716b60c6d72a28df90424ea3bd8", "check_rule_07.py": "3edc9391152495412b969e89d449a50e8bef256917d01ae14ad9f198db6427bd", "check_rule_08.py": "ed207ed766a36b49e8799ef9e031db10c1b1339d1b0540f392a2e5b24def9bdd", "check_rule_09.py": "5175489a612d2d049e207a82f7c60fdd5feb735137f5edaca784b035d4220548", "check_rule_10.py": "a968b7a3f191a0937298b48bba6ede47376dc5002c38ee9b4583b376b770bf75", "check_rule_11.py": "b439686603e2810ce6cddbeb7d2e7bd720f2658e0c48a7a9b03265f0a94b9997", "check_rule_12.py": "987e362199f0b229f019dc5028d453493f2fc00f6ab671be746240ae8d517794"}12- name: w201_sandbox _target_: baselines.coop_prompt_outcome_rl.PlaybookLoop1Initiate diagnosis on the root service. Query its metrics for anomalies. Use Topology to map upstream and downstream services. Focus on downstream if severe alert is observed there. Analyze io_usage, mem_usage, and network_usage for spikes. Compare Z-scores of metrics against baseline. Identify onset order of metric changes. Examine call graphs for error patterns. Look for cross-edge anomalies indicating shared issues. Check co-located instances for resource contention. Prioritize services with high multi-service anomaly counts. Use NetFlow for network traffic analysis if relevant. If no clear cause, narrow scope by querying direct neighbors. Conclude with a rooted acyclic chain linking root to suspected cause.faisi/W2-02-checker-synthesizer/src/checkers/synthesize_and_gate.pyAdded+283
faisi/W3-01-guided-rl/config/agent.yamlAdded+2
faisi/W3-01-guided-rl/logs/train.logAdded
faisi/W3-01-guided-rl/reports/w3_01_guided_rl_report.jsonAdded
faisi/W3-01-guided-rl/src/rl_env/__init__.pyAdded+4
faisi/W3-01-guided-rl/src/rl_env/advantages.pyAdded+31
faisi/W3-01-guided-rl/src/rl_env/consistency_scorer.pyAdded+148
faisi/W3-01-guided-rl/src/rl_env/guided_loop.pyAdded+41
faisi/W3-01-guided-rl/src/rl_env/guided_report.pyAdded+304
faisi/W3-01-guided-rl/src/rl_env/guided_services.pyAdded+220
faisi/W3-01-guided-rl/src/rl_env/guided_trainer.pyAdded+84
faisi/W3-01-guided-rl/src/rl_env/prepare_guided.pyAdded+68
faisi/W3-01-guided-rl/src/rl_env/reuse_step_zero.pyAdded+36
faisi/W3-01-guided-rl/tests/test_guided.pyAdded+108
faisi/W3-02-scaling-coevolution/config/agent.yamlAdded+2
faisi/W3-02-scaling-coevolution/reports/w3_02_checker_v2_report.jsonAdded+2231
faisi/W3-02-scaling-coevolution/reports/w3_02_scaling_and_r2_report.jsonAdded
faisi/W3-02-scaling-coevolution/src/checker_v2/__init__.pyAdded
faisi/W3-02-scaling-coevolution/src/checker_v2/gate.pyAdded+212
faisi/W3-02-scaling-coevolution/src/checker_v2/mine_residual_conflicts.pyAdded+144
faisi/W3-02-scaling-coevolution/src/checker_v2/saturation.pyAdded+64
faisi/W3-02-scaling-coevolution/src/checker_v2/synthesize.pyAdded+212
faisi/W3-02-scaling-coevolution/src/rl_env/__init__.pyAdded+4
faisi/W3-02-scaling-coevolution/src/rl_env/advantages_v2.pyAdded+21
faisi/W3-02-scaling-coevolution/src/rl_env/consistency_scorer_v2.pyAdded+45
faisi/W3-02-scaling-coevolution/src/rl_env/export_hf.pyAdded+47
faisi/W3-02-scaling-coevolution/src/rl_env/label_resamples.pyAdded+67
faisi/W3-02-scaling-coevolution/src/rl_env/prepare_sample.pyAdded+61
faisi/W3-02-scaling-coevolution/src/rl_env/prepare_scaling.pyAdded+62
faisi/W3-02-scaling-coevolution/src/rl_env/resample.pyAdded+144
faisi/W3-02-scaling-coevolution/src/rl_env/scaling_loop.pyAdded+6
faisi/W3-02-scaling-coevolution/src/rl_env/scaling_report.pyAdded+242
faisi/W3-02-scaling-coevolution/src/rl_env/scaling_services.pyAdded+24
faisi/W3-02-scaling-coevolution/src/rl_env/scaling_trainer.pyAdded+91
faisi/W3-02-scaling-coevolution/tests/test_scaling_v2.pyAdded+76
faisi/W3-02-scaling-coevolution/verified_checkers_v2/check_rule_01.pyAdded+11
faisi/W3-02-scaling-coevolution/verified_checkers_v2/check_rule_02.pyAdded+8
faisi/W3-02-scaling-coevolution/verified_checkers_v2/check_rule_03.pyAdded+15
faisi/W3-02-scaling-coevolution/verified_checkers_v2/check_rule_04.pyAdded+11
faisi/W3-02-scaling-coevolution/verified_checkers_v2/check_rule_05.pyAdded+8
faisi/W3-02-scaling-coevolution/verified_checkers_v2/check_rule_06.pyAdded+7
faisi/W3-02-scaling-coevolution/verified_checkers_v2/check_rule_07.pyAdded+10
faisi/W3-02-scaling-coevolution/verified_checkers_v2/check_rule_08.pyAdded+7
faisi/W3-02-scaling-coevolution/verified_checkers_v2/check_rule_09.pyAdded+8
faisi/W3-02-scaling-coevolution/verified_checkers_v2/check_rule_10.pyAdded+9
faisi/W3-02-scaling-coevolution/verified_checkers_v2/check_rule_11.pyAdded+7
faisi/W3-02-scaling-coevolution/verified_checkers_v2/check_rule_12.pyAdded+10
faisi/W3-02-scaling-coevolution/verified_checkers_v2/manifest.jsonAdded+14
faisi/W4-01-external-baselines/config/agent.yamlAdded+2
faisi/W4-01-external-baselines/prompts/playbook_p1.txtAdded+1