File size: 13,373 Bytes
f2cf1f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f2ca97c
 
 
 
f2cf1f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5e5bb15
f2cf1f1
 
 
 
5e5bb15
 
f2cf1f1
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
#!/usr/bin/env python3
"""Run lexical, flat-UQ and SSEG on identical public FinGovBench inputs.

The benchmark labels are never loaded. GPT-OSS-20B supplies one shared set of local
component-risk measurements per case. Flat-UQ and SSEG consume exactly those saved
measurements; only SSEG retains workflow dependencies. Lexical is model-free.
"""

from __future__ import annotations

import argparse
import concurrent.futures
import json
import os
import re
import time
from collections import defaultdict, deque
from pathlib import Path

import httpx


ROOT = Path(__file__).resolve().parents[1]
MODEL = os.getenv("FINGOVBENCH_MODEL", "meta-llama/Llama-3.3-70B-Instruct-Turbo")
BASE_URL = os.getenv("TOGETHER_BASE_URL", "https://api.together.xyz/v1")
ACTIONS = {"release", "withhold", "escalate", "retry", "repair", "rollback", "scoped_revalidation", "restrict", "suspend"}
AUDITABLE = {"configuration", "evidence", "claim", "claim_evidence_relation", "model", "tool", "workflow_state", "decision", "action", "control", "governance"}
TOKEN = re.compile(r"[a-z0-9]+")
LEXICAL_THRESHOLD = 0.08


def read_rows() -> list[dict]:
    rows: list[dict] = []
    for split in ("development", "validation", "test"):
        path = ROOT / f"hf/closed_loop_inputs/{split}.jsonl"
        for line in path.read_text().splitlines():
            if not line.strip():
                continue
            row = json.loads(line)
            forbidden = {"gold", "telemetry", "post_action_observation", "graph", "ddas"} & row.keys()
            if forbidden:
                raise RuntimeError(f"public-input leakage in {row.get('case_id')}: {sorted(forbidden)}")
            rows.append(row)
    return sorted(rows, key=lambda row: row["case_id"])


def compact_case(row: dict) -> dict:
    components = []
    for node in row["workflow"]["components"]:
        item = {"component_id": node["node_id"], "type": node["node_type"]}
        if "value" in node:
            item["value"] = node["value"]
        components.append(item)
    return {
        "case_id": row["case_id"],
        "domain": row["domain"],
        "as_of": row["as_of"],
        "workflow_context": row["workflow_context"],
        # Benchmark-construction fields such as ``controlled_fault`` are excluded.
        "event": {
            key: row["event"][key]
            for key in ("event_id", "description", "observed_at", "trigger_category")
            if key in row["event"]
        },
        "assurance_claims": row.get("assurance_claims", []),
        "red_line_controls": row.get("red_line_controls", []),
        "components": components,
    }


def parse_json_object(text: str) -> dict:
    """Parse a JSON object even when the model surrounds it with prose or a fence."""
    text = text.strip()
    try:
        value = json.loads(text)
    except json.JSONDecodeError:
        start, end = text.find("{"), text.rfind("}")
        if start < 0 or end <= start:
            raise ValueError("model response contained no JSON object")
        value = json.loads(text[start : end + 1])
    if not isinstance(value, dict):
        raise ValueError("model response was not a JSON object")
    return value


def call_model(row: dict, client: httpx.Client, retries: int = 4) -> dict:
    system = (
        "You are an independent component-risk monitor for a financial AI workflow. "
        "Use only the supplied record. Do not infer a gold answer. Return JSON with keys "
        "component_risk (object mapping every component_id to a number from 0 to 1), "
        "terminal_risk (0 to 1), and rationale (maximum 30 words). A component has high "
        "risk when the observed event invalidates its declared local contract."
    )
    last: Exception | None = None
    for attempt in range(retries):
        try:
            payload = {
                "model": MODEL,
                "messages": [
                    {"role": "system", "content": system},
                    {"role": "user", "content": json.dumps(compact_case(row), sort_keys=True)},
                ],
                "temperature": 0,
                "max_tokens": 700,
            }
            if MODEL.startswith("openai/gpt-oss"):
                payload["reasoning_effort"] = "low"
            provider_response = client.post("/chat/completions", json=payload)
            provider_response.raise_for_status()
            body = provider_response.json()
            parsed = parse_json_object(body["choices"][0]["message"]["content"])
            allowed = {node["node_id"] for node in row["workflow"]["components"]}
            risks = {
                str(key): min(1.0, max(0.0, float(value)))
                for key, value in parsed.get("component_risk", {}).items()
                if str(key) in allowed
            }
            for component_id in allowed:
                risks.setdefault(component_id, 0.0)
            return {
                "case_id": row["case_id"],
                "model": str(body.get("model") or MODEL),
                "component_risk": risks,
                "terminal_risk": min(1.0, max(0.0, float(parsed.get("terminal_risk", 0.0)))),
                "rationale": str(parsed.get("rationale", ""))[:300],
                "usage": body.get("usage", {}),
            }
        except httpx.HTTPStatusError as exc:
            detail = exc.response.text.replace("\n", " ")[:500]
            last = RuntimeError(f"{exc}; provider_response={detail}")
            time.sleep(2 ** attempt)
        except (httpx.HTTPError, TimeoutError, KeyError, ValueError, json.JSONDecodeError) as exc:
            last = exc
            time.sleep(2 ** attempt)
    raise RuntimeError(f"{row['case_id']} failed after {retries} attempts: {last}")


def create_measurements(rows: list[dict], output: Path, workers: int) -> dict[str, dict]:
    existing = {}
    if output.exists():
        existing = {item["case_id"]: item for item in map(json.loads, output.read_text().splitlines()) if item}
    pending = [row for row in rows if row["case_id"] not in existing]
    api_key = os.getenv("TOGETHER_API_KEY", "").strip()
    if pending and not api_key:
        raise SystemExit("TOGETHER_API_KEY is required")
    client = httpx.Client(
        base_url=BASE_URL.rstrip("/"),
        headers={"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"},
        timeout=120,
    )
    with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as pool:
        futures = {pool.submit(call_model, row, client): row["case_id"] for row in pending}
        for index, future in enumerate(concurrent.futures.as_completed(futures), 1):
            item = future.result()
            existing[item["case_id"]] = item
            if index % 10 == 0 or index == len(pending):
                output.parent.mkdir(parents=True, exist_ok=True)
                output.write_text("".join(json.dumps(existing[key], sort_keys=True) + "\n" for key in sorted(existing)))
                print(f"checkpoint {len(existing)}/{len(rows)}", flush=True)
    return existing


def components(row: dict) -> list[dict]:
    return row["workflow"]["components"]


def auditable_ids(row: dict) -> list[str]:
    return [node["node_id"] for node in components(row) if node["node_type"] in AUDITABLE]


def descendants(row: dict, starts: list[str]) -> list[str]:
    adjacency: dict[str, list[str]] = defaultdict(list)
    for edge in row["workflow"]["dependencies"]:
        adjacency[edge["source"]].append(edge["target"])
    seen, queue = set(starts), deque(starts)
    while queue:
        for child in adjacency[queue.popleft()]:
            if child not in seen:
                seen.add(child)
                queue.append(child)
    allowed = set(auditable_ids(row))
    return sorted(seen & allowed)


def typed_governance_roots(row: dict, alarms: list[str]) -> list[str]:
    """Map local alarms to the contract nodes that require governance review.

    Superseded evidence is immutable historical evidence, not itself a repair
    target.  Its typed successor affects the claim--source relation; review and
    revalidation therefore begin at that relation and continue downstream.
    Other workflows retain the locally alarmed components as their roots.
    """
    dependencies = row["workflow"]["dependencies"]
    superseded_targets = {
        edge["target"] for edge in dependencies if edge.get("edge_type") == "superseded_by"
    }
    if superseded_targets:
        relation_roots = {
            edge["target"]
            for edge in dependencies
            if edge["source"] in superseded_targets
            and edge.get("edge_type") == "contradicts_or_qualifies"
        }
        if relation_roots:
            return sorted(relation_roots)
    return alarms


def policy_action(row: dict, iceberg: bool) -> str:
    if not iceberg:
        return "release"
    trigger = row["event"]["trigger_category"]
    tier = row["workflow_context"]["authority_tier"]
    failed_red_line = any(c.get("status") == "failed" and not c.get("compensable", True) for c in row.get("red_line_controls", []))
    if failed_red_line:
        return "suspend"
    if trigger == "tool_permission":
        return "restrict" if tier.startswith("C") else "scoped_revalidation"
    if trigger == "incident_near_miss":
        return "withhold"
    if trigger in {"performance_behaviour", "model_vendor"}:
        return "escalate"
    if trigger == "prompt_policy_orchestration":
        return "withhold"
    if trigger == "purpose_population":
        return "scoped_revalidation"
    if trigger == "memory_data":
        if tier.startswith("A"):
            return "rollback"
        return "withhold" if row["domain"] == "market_data" else "scoped_revalidation"
    return "escalate"


def prediction(row: dict, method: str, affected: list[str], reviewed: list[str], iceberg: bool) -> dict:
    action = policy_action(row, iceberg)
    return {
        "case_id": row["case_id"],
        "method": method,
        "model": MODEL if method != "lexical" else None,
        "iceberg_detected": iceberg,
        "governance_action": action,
        "affected_components": sorted(set(affected)),
        "revalidation_components": sorted(set(reviewed)),
        "reviewed_components": sorted(set(reviewed)),
        "release_permitted": action == "release",
    }


def lexical(row: dict) -> dict:
    event_terms = set(TOKEN.findall(row["event"]["description"].lower()))
    scores = []
    for node in components(row):
        node_terms = set(TOKEN.findall(json.dumps(node.get("value", "")).lower()))
        score = len(event_terms & node_terms) / max(1, len(event_terms | node_terms))
        scores.append((score, node["node_id"]))
    score, component_id = max(scores)
    # A deliberately simple, label-blind baseline: flag only when event language
    # overlaps a component above the prespecified threshold. It never reads case
    # origin, controlled-fault metadata, or benchmark labels.
    iceberg = score >= LEXICAL_THRESHOLD
    affected = [component_id] if iceberg else []
    return prediction(row, "lexical", affected, affected, iceberg)


def derive_predictions(rows: list[dict], measurements: dict[str, dict], threshold: float, output_dir: Path) -> None:
    outputs = {"lexical": [], "flat_uq": [], "sseg": []}
    for row in rows:
        outputs["lexical"].append(lexical(row))
        risks = measurements[row["case_id"]]["component_risk"]
        alarms = sorted(component_id for component_id, value in risks.items() if value >= threshold)
        if not alarms and measurements[row["case_id"]]["terminal_risk"] >= threshold:
            alarms = [max(risks, key=risks.get)]
        iceberg = bool(alarms)
        all_components = auditable_ids(row) if iceberg else []
        outputs["flat_uq"].append(prediction(row, "flat_uq", all_components, all_components, iceberg))
        roots = typed_governance_roots(row, alarms) if iceberg else []
        propagated = descendants(row, roots) if iceberg else []
        outputs["sseg"].append(prediction(row, "sseg", propagated, propagated, iceberg))
    output_dir.mkdir(parents=True, exist_ok=True)
    for method, records in outputs.items():
        (output_dir / f"{method}.jsonl").write_text("".join(json.dumps(record, sort_keys=True) + "\n" for record in records))


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--workers", type=int, default=8)
    parser.add_argument("--threshold", type=float, default=0.55)
    parser.add_argument("--limit", type=int)
    parser.add_argument("--case-origin", choices=("controlled", "genuine_revision"))
    parser.add_argument("--measurements", type=Path, default=ROOT / "results/gptoss20b_public_measurements.jsonl")
    parser.add_argument("--output-dir", type=Path, default=ROOT / "results/public_predictions")
    args = parser.parse_args()
    rows = read_rows()
    if args.case_origin:
        rows = [row for row in rows if row["case_origin"] == args.case_origin]
    if args.limit:
        rows = rows[: args.limit]
    measurements = create_measurements(rows, args.measurements, args.workers)
    derive_predictions(rows, measurements, args.threshold, args.output_dir)
    print(json.dumps({"cases": len(rows), "model": MODEL, "threshold": args.threshold, "methods": ["lexical", "flat_uq", "sseg"]}, indent=2))


if __name__ == "__main__":
    main()