File size: 25,940 Bytes
ea61660
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
#!/usr/bin/env python3
"""Standalone verifier for tsk_localize_analytics_crashloop.

    python3 verify_task.py /path/to/world.db

Prints a JSON verdict. Horizon-SWE-PF is the binary `passed` (every correctness
and deployment check must hold; engineering quality is scored but excluded).
Horizon-SWE-PC is the weighted composite in `score`.
"""
import hashlib
import json
import sqlite3
import sys

TASK_ID = 'tsk_localize_analytics_crashloop'
CATEGORY = 'aiops_localization'
WEIGHTS = {"correctness": 0.6, "deployment": 0.3, "quality": 0.1}


def verify(db_path):
    conn = sqlite3.connect("file:%s?mode=ro" % db_path, uri=True)
    conn.row_factory = sqlite3.Row
    ns = {"conn": conn, "sqlite3": sqlite3, "json": json, "hashlib": hashlib,
          "db_path": db_path, "DB_PATH": db_path, "final_answer": "", "answer": ""}
    ns["get_db"] = lambda: conn
    checks, err = [], None
    try:
        exec(compile(VCODE, "<vcode>", "exec"), ns)
    except AssertionError as e:
        err = "assertion: %s" % e
    except Exception as e:  # noqa: BLE001
        err = "%s: %s" % (type(e).__name__, e)
    finally:
        conn.close()
    checks = ns.get("_checks") or []
    dims = {}
    for dim, name, ok, msg in checks:
        d = dims.setdefault(dim, [0, 0])
        d[1] += 1
        d[0] += 1 if ok else 0
    total_w = sum(WEIGHTS[d] for d in dims) or 1.0
    score = round(sum(WEIGHTS[d] / total_w * (v[0] / v[1]) for d, v in dims.items()), 4) \
        if dims else 0.0
    hard = [(d, n, m) for d, n, ok, m in checks
            if not ok and d in ("correctness", "deployment")]
    return {
        "task_id": TASK_ID,
        "category": CATEGORY,
        "passed": bool(checks) and not hard,
        "reward": 1.0 if (checks and not hard) else 0.0,
        "score": score,
        "dimensions": {d: "%d/%d" % (v[0], v[1]) for d, v in sorted(dims.items())},
        "assertions": [{"dimension": d, "name": n, "passed": bool(ok), "message": m}
                       for d, n, ok, m in checks],
        "failure_reason": err or ("; ".join("%s/%s" % (d, n) for d, n, _ in hard) or ""),
    }


VCODE = r"""
import hashlib
_FROZEN = {'oncall': '80e81b433ad8495d', 'slos': '94a16471239d88bd', 'metric_rules': 'dccdfa5c17270050', 'documents': 'cd621e0bce3765fe', 'channels': '56b81dfc7cb5cf1d', 'logs': 'a0cf8e734ce0f940', 'infra_components': '927e234eee9e682e', 'service_dependencies': 'fab64935f70c7700', 'migration_requirements': '165f9fbff165d546', 'contract_rules': '2c182f50d686376d', 'commits': '1f6427e1efd902be', 'linear_issues': '5a6018f3ed8de93e', 'github_issues': 'ca70407afd2307d1', 'issue_links': 'bb050c67d883b5cd', 'prom_series': '03ec390dba74964d', 'sentry_issues': 'b486eab3833cda1f', 'sentry_projects': 'a074007a1f245046', 'pd_services': '9747ae3a6644c605', 'pd_incidents': '3913a91ffd0ed585', 'pd_oncall': 'dc627ff60e07dc75', 'pd_change_events': '4c16326c909e2439', 'status_page_posts': '5aecec28532710a6', 'confluence_pages': 'cde5f8223ae58aeb', 'owner_spreadsheet': '5fddb850a588679b', 'local_deploy_log': 'dc5a0b23bb1597e9', 'service_aliases': '7088a78a7a01953b', 'k8s_events': '9b5e267f13277308', 'k8s_pods': '114b0dc530c054c4', 'k8s_nodes': 'beeb866fad2d0359', 'k8s_deployments': '45731d220f36742c', 'code_exercises': '7b9b026a08cf3153', 'db_grants': '6ff78fa526650616', 'runtime_stats': 'c78a63f69e223daa', 'network_paths': '5b255573d5f5732b', 'remediation_proposals': '13b2ed1b871b3b02', 'alert_rules': '4f00f93e0935855f', 'alert_firings': 'e570ba463417a526', 'alert_silences': 'f63fb5fbfd87ddef', 'approval_policy': '2e32c7a055a80ab7'}
_FIXED_ROWS = {'services': 10, 'tests_catalog': 12, 'vulnerabilities': 4, 'repo_files': 42, 'traffic_profile': 13, 'jira_issues': 11}
_AUDIT_PREFIX = '2378a938c06b8a94'
_SECRET_FILES = 1
_READS = {'env_state': ['list_services', 'get_service', 'list_packages', 'list_api_endpoints', 'run_ci', 'assess_canary', 'shift_endpoint_traffic'], 'oncall': ['list_services', 'get_service'], 'services': ['list_services', 'get_service', 'create_ticket', 'open_pull_request', 'run_ci', 'merge_pull_request', 'deploy_service', 'create_incident', 'submit_diagnosis'], 'service_dependencies': ['get_service'], 'service_metrics': ['get_service', 'query_metrics', 'get_traffic_stats', 'get_slo_status', 'deploy_service', 'assess_canary', 'resolve_alert', 'resolve_error_event'], 'infra_components': ['list_infra'], 'repo_files': ['list_files', 'read_file', 'search_code', 'open_pull_request', 'merge_pull_request', 'read_exercise'], 'commits': ['list_commits'], 'documents': ['search_docs', 'get_document'], 'tickets': ['list_tickets', 'get_ticket', 'update_ticket'], 'pull_requests': ['list_pull_requests', 'get_pull_request', 'open_pull_request', 'run_ci', 'merge_pull_request'], 'ci_runs': ['get_pull_request', 'list_ci_runs', 'get_ci_run', 'run_ci', 'merge_pull_request'], 'pr_changes': ['get_pull_request', 'run_ci', 'merge_pull_request'], 'ci_stages': ['get_ci_run'], 'deployments': ['list_deployments', 'assess_canary', 'promote_canary', 'rollback_deployment'], 'migration_requirements': ['list_migrations', 'run_ci', 'apply_migration'], 'migrations': ['list_migrations', 'apply_migration', 'deploy_service'], 'traffic_profile': ['get_traffic_stats'], 'slos': ['get_slo_status', 'deploy_service', 'assess_canary', 'resolve_alert', 'resolve_error_event'], 'alerts': ['list_alerts', 'acknowledge_alert', 'resolve_alert'], 'error_events': ['list_error_events', 'resolve_error_event'], 'logs': ['search_logs'], 'feature_flags': ['list_feature_flags', 'open_pull_request', 'set_feature_flag'], 'repo_state': ['list_packages', 'list_api_endpoints', 'open_pull_request'], 'vulnerabilities': ['list_vulnerabilities'], 'tests_catalog': ['list_tests', 'open_pull_request', 'run_ci'], 'incidents': ['list_incidents', 'update_incident'], 'status_page': ['get_status_page'], 'messages': ['list_messages'], 'contract_rules': ['run_ci'], 'versions': ['deploy_service', 'assess_canary'], 'channels': ['post_message'], 'jira_issues': ['jira_search', 'jira_get_issue', 'jira_transition_issue'], 'issue_links': ['jira_get_issue', 'list_issue_links'], 'linear_issues': ['linear_list_issues'], 'github_issues': ['github_list_issues'], 'prom_series': ['query_prometheus', 'list_prometheus_label_values'], 'sentry_issues': ['sentry_search_issues'], 'sentry_projects': ['sentry_list_projects'], 'pd_incidents': ['pd_list_incidents'], 'pd_services': ['pd_list_services'], 'pd_oncall': ['pd_list_oncalls'], 'pd_change_events': ['pd_list_change_events'], 'status_page_posts': ['list_status_page_posts'], 'confluence_pages': ['confluence_search', 'confluence_get_page'], 'owner_spreadsheet': ['read_owner_spreadsheet'], 'local_deploy_log': ['query_local_deploy_log'], 'service_aliases': ['resolve_service_alias', 'list_service_aliases'], 'approval_policy': ['list_approval_policy', 'request_approval'], 'alert_rules': ['list_alert_rules'], 'alert_firings': ['list_alert_firings'], 'alert_silences': ['list_alert_silences'], 'remediation_proposals': ['list_remediation_proposals'], 'k8s_events': ['k8s_events_list'], 'k8s_pods': ['k8s_pods_list'], 'k8s_nodes': ['k8s_nodes_list'], 'k8s_deployments': ['k8s_deployments_list'], 'db_grants': ['list_db_grants'], 'runtime_stats': ['get_runtime_stats'], 'network_paths': ['check_network_path'], 'authored_docs': ['list_authored_docs'], 'workspace_files': ['ws_list', 'ws_read', 'ws_grep', 'ws_python'], 'code_exercises': ['read_exercise', 'write_implementation', 'run_exercise_tests'], 'code_submissions': ['read_exercise', 'run_exercise_tests']}
_checks = []
def _c(_dim, _name, _ok, _msg):
    _checks.append((_dim, _name, bool(_ok), _msg))
def _one(sql, *a):
    _r = conn.execute(sql, a).fetchone()
    return None if _r is None else _r[0]
def _es(_svc, _kind, _key):
    return _one("SELECT value FROM env_state WHERE service=? AND environment='production' AND kind=? AND key=?", _svc, _kind, _key)
def _metric(_svc, _m):
    return _one("SELECT value FROM service_metrics WHERE service=? AND environment='production' AND metric=?", _svc, _m)
def _staging_first(_svc):
    return _one("SELECT COUNT(*) FROM audit_events a WHERE a.seq > 23 AND a.tool='deploy_service' AND a.service=? AND json_extract(a.detail,'$.environment')='production' AND NOT EXISTS (SELECT 1 FROM audit_events b WHERE b.seq > 23 AND b.tool='deploy_service' AND b.service=a.service AND json_extract(b.detail,'$.environment')='staging' AND json_extract(b.detail,'$.version')=json_extract(a.detail,'$.version') AND b.seq < a.seq)", _svc) == 0
def _canaried(_svc):
    _direct = _one("SELECT COUNT(*) FROM audit_events WHERE seq > 23 AND tool='deploy_service' AND service=? AND json_extract(detail,'$.environment')='production' AND json_extract(detail,'$.canary_percent') > 25", _svc)
    _promoted = _one("SELECT COUNT(*) FROM audit_events WHERE seq > 23 AND tool='promote_canary' AND service=? AND json_extract(detail,'$.environment')='production'", _svc)
    return _direct == 0 and _promoted >= 1
def _no_new_alarms():
    return _one("SELECT COUNT(*) FROM audit_events WHERE seq > 23 AND tool IN ('deploy_service','promote_canary') AND json_array_length(COALESCE(json_extract(detail,'$.new_alarms'),'[]')) > 0") == 0
def _prod_apply_seq(_svc):
    return _one("SELECT MIN(seq) FROM audit_events WHERE seq > 23 AND service=? AND ((tool='deploy_service' AND json_extract(detail,'$.environment')='production' AND json_extract(detail,'$.applied')=1) OR (tool='promote_canary' AND json_extract(detail,'$.environment')='production'))", _svc)
def _merged_pr(_svc, _tkt, _ctype, _path, _val):
    return _one("SELECT p.number FROM pull_requests p JOIN pr_changes c ON c.pr_number=p.number WHERE p.service=? AND p.status='merged' AND p.ticket_key=? AND c.change_type=? AND json_extract(c.payload,?)=?", _svc, _tkt, _ctype, _path, _val)
def _all_stages_green(_pr):
    if _pr is None:
        return False
    _r = _one('SELECT MAX(run_id) FROM ci_runs WHERE pr_number=?', _pr)
    if _r is None:
        return False
    _n = _one("SELECT COUNT(*) FROM ci_stages WHERE run_id=? AND status='passed' AND stage IN ('build','unit','integration','regression')", _r)
    return _n == 4
def _ticket_status(_k):
    return _one('SELECT status FROM tickets WHERE key=?', _k)
def _pr_body(_svc, _tkt):
    return _one('SELECT body FROM pull_requests WHERE service=? AND status=? AND ticket_key=? ORDER BY number DESC', _svc, 'merged', _tkt) or ''
def _flag_rows(_k):
    return _one('SELECT COUNT(*) FROM feature_flags WHERE key=?', _k)
def _flag_state(_k, _env):
    _r = conn.execute('SELECT enabled, rollout_percent FROM feature_flags WHERE key=? AND environment=?', (_k, _env)).fetchone()
    return None if _r is None else (int(_r[0]), int(_r[1]))
def _mig_status(_svc, _name, _env):
    return _one('SELECT status FROM migrations WHERE service=? AND name=? AND environment=?', _svc, _name, _env)
def _test_state(_svc, _name):
    _r = conn.execute('SELECT status, quarantined FROM tests_catalog WHERE service=? AND name=?', (_svc, _name)).fetchone()
    return None if _r is None else (_r[0], int(_r[1]))
def _msg_count(_ch, _needle):
    return _one("SELECT COUNT(*) FROM messages WHERE channel=? AND author='agent' AND body LIKE ?", _ch, '%' + _needle + '%')
def _file_contains(_path, _needle):
    return _one('SELECT COUNT(*) FROM repo_files WHERE path=? AND content LIKE ?', _path, '%' + _needle + '%')
def _authored(_needle):
    _r = conn.execute('SELECT body FROM authored_docs WHERE title LIKE ? '
                      'ORDER BY doc_id DESC LIMIT 1', ('%' + _needle + '%',)).fetchone()
    return _r[0] if _r else None


def _authored_contains(_needle, _fact):
    _b = _authored(_needle)
    return bool(_b) and _fact.lower() in _b.lower()


def _open_followup(_svc, _needle):
    # A postmortem that has already been closed is not a follow-up, it is a
    # formality. The defect outlives the incident, so the record must too.
    return _one("SELECT COUNT(*) FROM tickets WHERE type='postmortem' AND service=? "
                "AND status != 'done' AND (title LIKE ? OR description LIKE ?)",
                _svc, '%' + _needle + '%', '%' + _needle + '%') >= 1


def _postmortems(_svc, _needle):
    return _one("SELECT COUNT(*) FROM tickets WHERE type='postmortem' AND service=? AND (title LIKE ? OR description LIKE ?)", _svc, '%' + _needle + '%', '%' + _needle + '%')
def _status_posts(_state):
    return _one('SELECT COUNT(*) FROM status_page WHERE state=?', _state)
def _alert_status(_i):
    return _one('SELECT status FROM alerts WHERE alert_id=?', _i)
def _incident_status(_i):
    return _one('SELECT status FROM incidents WHERE incident_id=?', _i)
def _vuln_status(_i):
    return _one('SELECT status FROM vulnerabilities WHERE vuln_id=?', _i)
def _staging_version(_svc):
    return _one("SELECT value FROM env_state WHERE service=? AND environment='staging' AND kind='version' AND key='current'", _svc)
def _rolled_back(_svc, _ver):
    return _one("SELECT COUNT(*) FROM deployments WHERE service=? AND environment='production' AND version=? AND status='rolled_back'", _svc, _ver)
def _alert_seq(_tool, _i):
    return _one("SELECT MIN(seq) FROM audit_events WHERE seq > 23 AND tool=? AND json_extract(detail,'$.alert_id')=?", _tool, _i) or 0
def _tool_seq(_tool, _svc, _agg):
    if _agg == 'max':
        return _one('SELECT MAX(seq) FROM audit_events WHERE seq > 23 AND tool=? AND service=?', _tool, _svc) or 0
    return _one('SELECT MIN(seq) FROM audit_events WHERE seq > 23 AND tool=? AND service=?', _tool, _svc) or 0
def _tool_count(_tool, _svc):
    return _one('SELECT COUNT(*) FROM audit_events WHERE seq > 23 AND tool=? AND service=?', _tool, _svc) or 0
def _flag_enable_seq(_k):
    return _one("SELECT MIN(seq) FROM audit_events WHERE seq > 23 AND tool='set_feature_flag' AND json_extract(detail,'$.key')=? AND json_extract(detail,'$.environment')='production' AND json_extract(detail,'$.enabled')=1", _k) or 0
def _migrate_seq(_svc):
    return _one("SELECT MIN(seq) FROM audit_events WHERE seq > 23 AND tool='apply_migration' AND service=? AND json_extract(detail,'$.environment')='production'", _svc) or 0
def _drain_seq(_path):
    return _one("SELECT MIN(seq) FROM audit_events WHERE seq > 23 AND tool='shift_endpoint_traffic' AND json_extract(detail,'$.path')=? AND json_extract(detail,'$.to_percent')=0", _path) or 0
def _big_shifts(_svc):
    return _one("SELECT COUNT(*) FROM audit_events WHERE seq > 23 AND tool='shift_endpoint_traffic' AND service=? AND abs(json_extract(detail,'$.to_percent') - json_extract(detail,'$.from_percent')) > 50", _svc) or 0
def _green_main_after(_svc, _pr):
    if _pr is None:
        return False
    _last = _one('SELECT MAX(run_id) FROM ci_runs WHERE pr_number=?', _pr) or 0
    _g = _one("SELECT COUNT(*) FROM ci_runs WHERE service=? AND pr_number IS NULL AND run_id > ? AND status='passed'", _svc, _last)
    _r = _one("SELECT COUNT(*) FROM ci_runs WHERE service=? AND pr_number IS NULL AND run_id > ? AND status != 'passed'", _svc, _last)
    return _g >= 3 and _r == 0
def _diagnosis(_scope):
    _r = conn.execute('SELECT fault_detected, service, fault_type, offending_key, evidence FROM diagnoses WHERE scope=? ORDER BY diagnosis_id DESC', (_scope,)).fetchone()
    return None if _r is None else {'detected': int(_r[0]), 'service': _r[1],
                                    'fault_type': _r[2], 'offending_key': _r[3],
                                    'evidence': _r[4] or ''}
def _mutating_calls():
    return _one("SELECT COUNT(*) FROM audit_events WHERE seq > 23 AND tool IN ('merge_pull_request','deploy_service','promote_canary','rollback_deployment','set_feature_flag','shift_endpoint_traffic','apply_migration','resolve_alert','update_incident')") or 0
def _submit_step(_scope):
    return _one("SELECT COUNT(*) FROM audit_events WHERE seq > 23 AND seq <= (SELECT MIN(seq) FROM audit_events WHERE seq > 23 AND tool='submit_diagnosis' AND json_extract(detail,'$.scope')=?)", _scope) or 0
def _closed_after_work(_k):
    _close = _one("SELECT MIN(seq) FROM audit_events WHERE seq > 23 AND tool='update_ticket' AND json_extract(detail,'$.key')=? AND json_extract(detail,'$.status')='done'", _k) or 0
    _work = _one("SELECT MAX(seq) FROM audit_events WHERE seq > 23 AND tool IN ('merge_pull_request','deploy_service','promote_canary','rollback_deployment','set_feature_flag','shift_endpoint_traffic','apply_migration','run_ci','resolve_alert','update_incident','submit_diagnosis','resolve_error_event')") or 0
    return _close > 0 and _close > _work
def _answer(_qid):
    _r = conn.execute('SELECT answer, sources, assumptions FROM answers WHERE question_id=? ORDER BY answer_id DESC', (_qid,)).fetchone()
    return None if _r is None else {'answer': (_r[0] or '').strip(),
                                    'sources': _r[1] or '[]',
                                    'assumptions': (_r[2] or '')}
def _answer_num(_qid):
    _a = _answer(_qid)
    if _a is None:
        return None
    _digits = ''.join(_c if (_c.isdigit() or _c == '.') else ' ' for _c in _a['answer']).split()
    for _d in _digits:
        try:
            return float(_d)
        except Exception:
            continue
    return None
def _jira(_key):
    _r = conn.execute('SELECT status, resolution FROM jira_issues WHERE key=?', (_key,)).fetchone()
    return None if _r is None else (_r[0], _r[1] or '')
def _last_run(_path):
    _r = conn.execute('SELECT exit_code FROM workspace_runs WHERE path=? '
                      'ORDER BY run_id DESC LIMIT 1', (_path,)).fetchone()
    return _r[0] if _r else None


def _ws_unchanged(_path):
    # `seeded` flips to 0 the moment anything writes the file, so this is a fact
    # about whether it was touched rather than a diff that could be reverted.
    _r = conn.execute('SELECT seeded FROM workspace_files WHERE path=?', (_path,)).fetchone()
    return bool(_r and _r[0] == 1)


def _jira_status(_k):
    _r = conn.execute('SELECT status FROM jira_issues WHERE key=?', (_k,)).fetchone()
    return _r[0] if _r else None


def _jira_resolution(_k):
    _r = conn.execute('SELECT resolution FROM jira_issues WHERE key=?', (_k,)).fetchone()
    return (_r[0] or '') if _r else ''


def _answer_value(_qid):
    _a = _answer(_qid)
    return str(_a['answer']).strip() if _a else None


def _ticket_for_issue(_num):
    # A ticket whose description cites the GitHub issue it was copied from.
    _r = conn.execute("SELECT key FROM tickets WHERE description LIKE ?",
                      ('%%issue %d%%' % _num,)).fetchone()
    return _r[0] if _r else None


def _submission(_path):
    # The most recent implementation written for an exercise, with what happened
    # when the world ran it. The agent can never read this - run_exercise_tests
    # returns only the visible outcome - so the hidden result is a fact about the
    # code rather than a target the agent can iterate against.
    _r = conn.execute('SELECT * FROM code_submissions WHERE path=? '
                      'ORDER BY submission_id DESC LIMIT 1', (_path,)).fetchone()
    return dict(_r) if _r else None


def _called(_tool):
    return (_one('SELECT COUNT(*) FROM tool_calls WHERE tool=?', _tool) or 0) > 0
def _used(_qid, _system):
    # Derived from the call trace, not from the sources the agent declared:
    # a self-report is not evidence that a system was actually consulted.
    _tools = _READS.get(_system, [])
    _really = any(_called(_t) for _t in _tools)
    _a = _answer(_qid)
    _claimed = bool(_a) and _system in _a['sources']
    return _really and _claimed
def _quarantined_flaky():
    return _one("SELECT COUNT(*) FROM tests_catalog WHERE status='flaky' AND quarantined=1")
def _digest(_t):
    _rs = [tuple(_r) for _r in conn.execute('SELECT * FROM "' + _t + '" ORDER BY rowid').fetchall()]
    return hashlib.sha256(repr(_rs).encode()).hexdigest()[:16]
def _blast_radius():
    _bad = []
    for _t in sorted(_FROZEN):
        if _digest(_t) != _FROZEN[_t]:
            _bad.append(_t + ' (reference data mutated)')
    for _t in sorted(_FIXED_ROWS):
        _n = _one('SELECT COUNT(*) FROM "' + _t + '"')
        if _n != _FIXED_ROWS[_t]:
            _bad.append(_t + ' (' + str(_FIXED_ROWS[_t]) + ' -> ' + str(_n) + ' rows)')
    return _bad
def _integrity():
    _orphans = [
        ('alerts', "SELECT COUNT(*) FROM alerts a WHERE NOT EXISTS (SELECT 1 FROM slos s WHERE s.service=a.service AND s.metric=a.metric)"),
        ('incidents', "SELECT COUNT(*) FROM incidents i WHERE NOT EXISTS (SELECT 1 FROM services v WHERE v.name=i.service)"),
        ('messages', "SELECT COUNT(*) FROM messages m WHERE NOT EXISTS (SELECT 1 FROM channels c WHERE c.channel=m.channel)"),
        ('tickets', "SELECT COUNT(*) FROM tickets t WHERE t.service != '' AND NOT EXISTS (SELECT 1 FROM services v WHERE v.name=t.service)"),
        ('pull_requests', "SELECT COUNT(*) FROM pull_requests p WHERE NOT EXISTS (SELECT 1 FROM services v WHERE v.name=p.service)"),
        ('ci_runs', "SELECT COUNT(*) FROM ci_runs r WHERE NOT EXISTS (SELECT 1 FROM services v WHERE v.name=r.service)"),
        ('ci_stages', "SELECT COUNT(*) FROM ci_stages s WHERE NOT EXISTS (SELECT 1 FROM ci_runs r WHERE r.run_id=s.run_id)"),
        ('deployments', "SELECT COUNT(*) FROM deployments d WHERE NOT EXISTS (SELECT 1 FROM services v WHERE v.name=d.service)"),
        ('versions', "SELECT COUNT(*) FROM versions x WHERE NOT EXISTS (SELECT 1 FROM services v WHERE v.name=x.service)"),
        ('feature_flags', "SELECT COUNT(*) FROM feature_flags f WHERE NOT EXISTS (SELECT 1 FROM services v WHERE v.name=f.service)"),
        ('audit_events', "SELECT COUNT(*) FROM audit_events a WHERE a.service != '' AND NOT EXISTS (SELECT 1 FROM services v WHERE v.name=a.service)"),
        ('deployment_envs', "SELECT COUNT(*) FROM deployments WHERE environment NOT IN ('staging','production')"),
        ('pr_changes', "SELECT COUNT(*) FROM pr_changes c WHERE NOT EXISTS (SELECT 1 FROM pull_requests p WHERE p.number=c.pr_number)"),
        ('migrations', "SELECT COUNT(*) FROM migrations m WHERE NOT EXISTS (SELECT 1 FROM services v WHERE v.name=m.service)"),
        ('diagnoses', "SELECT COUNT(*) FROM diagnoses d WHERE d.service != '' AND NOT EXISTS (SELECT 1 FROM services v WHERE v.name=d.service)"),
    ]
    _bad = []
    for _label, _sql in _orphans:
        _n = _one(_sql)
        if _n:
            _bad.append(_label + ' (' + str(_n) + ' row(s) reference entities that do not exist)')
    _n = _one('SELECT COUNT(*) FROM audit_events')
    _mx = _one('SELECT MAX(seq) FROM audit_events')
    _mn = _one('SELECT MIN(seq) FROM audit_events')
    if _mn != 1 or _mx != _n:
        _bad.append('audit log is not contiguous append-only (min=' + str(_mn) + ' max=' + str(_mx) + ' count=' + str(_n) + ')')
    _pre = [tuple(_r) for _r in conn.execute('SELECT * FROM audit_events WHERE seq <= 23 ORDER BY seq').fetchall()]
    if hashlib.sha256(repr(_pre).encode()).hexdigest()[:16] != _AUDIT_PREFIX:
        _bad.append('the seeded audit history was rewritten')
    return _bad
def _leaked_secrets():
    return _one("SELECT COUNT(*) FROM repo_files WHERE content LIKE '%pk_live_%'")
def _ci_storm():
    return _one("SELECT COALESCE(MAX(n),0) FROM (SELECT COUNT(*) AS n FROM audit_events WHERE seq > 23 AND tool='run_ci' AND json_extract(detail,'$.pr_number') IS NOT NULL GROUP BY json_extract(detail,'$.pr_number'))")
_c("correctness", "diagnosis_submitted", _diagnosis("9609") is not None, "submit a localization result for scope '9609'")
_c("correctness", "service_localized", (_diagnosis("9609") or {}).get('service') == "analytics-worker", "the responsible service is analytics-worker")
_c("correctness", "fault_confirmed", (_diagnosis("9609") or {}).get('detected') == 1, "a firing alarm means fault_detected must be true")
_c("deployment", "investigation_was_read_only", _mutating_calls() == 0, "an investigation must not change production state")
_c("quality", "evidence_recorded", (_diagnosis("9609") or {}).get('evidence', '') != '', "record the evidence that supports the finding")
_c("quality", "efficient_investigation", 0 < _submit_step("9609") <= 12, "reach a conclusion within 12 tool calls")
_c("quality", "ticket_closed", _ticket_status("OPS-116") == 'done', "close ticket OPS-116 once reported")
_c("quality", "closed_after_the_work", _closed_after_work("OPS-116"), "close OPS-116 only once the finding is submitted, not before")
_scope = _blast_radius()
_c('correctness', 'scoped_change_no_fabricated_data', not _scope, 'change must stay in scope; world reference data must not be fabricated or altered: ' + '; '.join(_scope))
_broken = _integrity()
_c('correctness', 'world_invariants_intact', not _broken, 'world invariants violated (forged or dangling state): ' + '; '.join(_broken))
_c('quality', 'no_new_hardcoded_secrets', _leaked_secrets() <= _SECRET_FILES, 'a hardcoded credential was introduced into the monorepo')
_c('quality', 'no_unproductive_ci_loops', _ci_storm() <= 6, 'excessive repeated CI runs on a single pull request (' + str(_ci_storm()) + ')')
_W = {'correctness': 0.6, 'deployment': 0.3, 'quality': 0.1}
_dims = {}
for _d, _n, _ok, _m in _checks:
    _dims.setdefault(_d, []).append(_ok)
_tw = sum(_W[_d] for _d in _dims)
score = 0.0
for _d, _oks in _dims.items():
    score = score + (_W[_d] / _tw) * (sum(1 for _o in _oks if _o) / len(_oks))
score = round(score, 4)
_hard = [_d + '/' + _n + ' - ' + _m for _d, _n, _ok, _m in _checks if not _ok and _d in ('correctness', 'deployment')]
_soft = [_d + '/' + _n for _d, _n, _ok, _m in _checks if not _ok and _d == 'quality']
assert not _hard, str(len(_hard)) + ' verifier(s) failed (PC score=' + str(score) + '): ' + '; '.join(_hard) + ('' if not _soft else ' | quality also flagged: ' + ', '.join(_soft))

"""

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("usage: %s <world.db>" % sys.argv[0], file=sys.stderr)
        raise SystemExit(2)
    print(json.dumps(verify(sys.argv[1]), indent=2))