#!/usr/bin/env python3 """Run Liquid d1 on Perch bug, security, and semantic lint method pairs.""" from __future__ import annotations import argparse import hashlib import importlib.util import json import math import sys import time from pathlib import Path from urllib.error import HTTPError, URLError from urllib.request import Request, urlopen BASE = Path(__file__).resolve().parent API = 'https://api.liquid.ai/decisions/v1/systemone' MODEL = 'd1:free' PROTOCOL = 'liquid-d1-perch-scan-pack-v1' LINT_PROTOCOL = 'liquid-d1-perch-semantic-ensure-v1' LINT_URL = 'https://huggingface.co/datasets/perchscan/perch-lint-bench-public/resolve/main/benchmark.jsonl' def module(path: Path, name: str): spec = importlib.util.spec_from_file_location(name, path) result = importlib.util.module_from_spec(spec) spec.loader.exec_module(result) return result core = module(BASE / 'benchmark.py', 'perch_benchmark') def semantic_question(ensure: str) -> dict: text = ' '.join(ensure.split()) return {'type': 'noul', 'instructions': 'Is `rule` true of the code below?', 'criteria': {'true': text, 'false': f'Not so: {text}'}} def load_data(domain: str, dataset: Path | None): if domain != 'lint': return core.load_pairs(domain, dataset) raw = dataset.read_bytes() if dataset else urlopen(LINT_URL, timeout=120).read() pairs = [json.loads(line) for line in raw.splitlines() if line] if not pairs or len({pair['pair_id'] for pair in pairs}) != len(pairs): raise ValueError('Empty or duplicate lint pairs') return pairs, hashlib.sha256(raw).hexdigest() def ask(key: str, state: dict, questions: dict, pair_id: str, role: str): payload = json.dumps({'model': MODEL, 'state': state, 'questions': questions}, ensure_ascii=False).encode() for attempt in range(8): request = Request(API, data=payload, method='POST', headers={'Authorization': 'Bearer ' + key, 'Content-Type': 'application/json'}) try: with urlopen(request, timeout=120) as response: result = json.load(response) break except HTTPError as exc: if exc.code not in (429, 500, 502, 503, 504) or attempt == 7: detail = exc.read(400).decode(errors='replace') raise RuntimeError(f'Liquid HTTP {exc.code} for {pair_id}:{role}: {detail}') from None delay = exc.headers.get('Retry-After') try: seconds = float(delay) except (TypeError, ValueError): seconds = min(60, 2 ** attempt) time.sleep(min(120, max(1, seconds))) except URLError: if attempt == 7: raise RuntimeError(f'Liquid network failure for {pair_id}:{role}') from None time.sleep(min(60, 2 ** attempt)) if result.get('model') != MODEL or set(result.get('answers', {})) != set(questions): raise ValueError(f'Liquid returned another model or incomplete answers for {pair_id}:{role}') return result['answers'], result.get('usage') or {} def predict(pair: dict, role: str, domain: str, pack: dict, key: str): if domain == 'lint': questions = {'semantic': semantic_question(pair['rule']['ensure'])} selected = None else: selected = core.scan_questions(pack, domain, pair['language']) questions = {q['name']: q['question'] for q in selected} answers, usage = ask(key, pair[role]['state'], questions, pair['pair_id'], role) if domain == 'lint': true_probability = core.probability(answers['semantic']['noul']) score = 1 - true_probability row = {'score': score, 'rule_true_probability': true_probability} protocol = LINT_PROTOCOL else: relevant = core.detection_questions(selected, domain) question_scores = {q['name']: core.raised_score(q, answers[q['name']]['noul']) for q in relevant} score, alert = core.scan_result(question_scores, selected, domain, .5) row = {'score': score, 'alert': alert, 'question_scores': question_scores, 'pack_sha256': pack['pack_sha256']} protocol = PROTOCOL row.update({'domain': domain, 'pair_id': pair['pair_id'], 'role': role, 'model_revision': MODEL, 'protocol_id': protocol, 'usage': usage}) return row def score_lint(pairs: list[dict], predictions: dict, digest: str): items = [(pair[role]['labels'][pair['domain']], predictions[pair['pair_id'], role]['score']) for pair in pairs for role in ('before', 'after')] tp = sum(y == 1 and s > .7 for y, s in items) fp = sum(y == 0 and s > .7 for y, s in items) fn = sum(y == 1 and s <= .7 for y, s in items) tn = sum(y == 0 and s <= .7 for y, s in items) eligible = [(predictions[p['pair_id'], 'before']['score'], predictions[p['pair_id'], 'after']['score']) for p in pairs if p['before']['labels'][p['domain']] == 1 and p['after']['labels'][p['domain']] == 0] return {'domain': 'lint', 'model_revision': MODEL, 'protocol_id': LINT_PROTOCOL, 'threshold': .7, 'alert_rule': 'rule violation score > 0.7', 'benchmark_sha256': digest, 'benchmark_pairs': len(pairs), 'benchmark_methods': len(items), 'average_precision': core.average_precision(items), 'precision': tp / (tp + fp) if tp + fp else 0, 'recall': tp / (tp + fn) if tp + fn else 0, 'f1': 2 * tp / (2 * tp + fp + fn) if 2 * tp + fp + fn else 0, 'confusion': {'tp': tp, 'fp': fp, 'tn': tn, 'fn': fn}, 'vulnerable_or_buggy_before_above_fixed_after': {'correct': sum(a > b for a, b in eligible), 'ties': sum(a == b for a, b in eligible), 'eligible': len(eligible)}} def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--domain', choices=('bug', 'security', 'lint'), required=True) parser.add_argument('--dataset', type=Path) parser.add_argument('--question-pack', type=Path, default=BASE / 'question-pack.json') parser.add_argument('--predictions', type=Path, required=True) parser.add_argument('--report', type=Path, required=True) parser.add_argument('--limit', type=int, default=0) parser.add_argument('--score-saved', action='store_true') parser.add_argument('--key-stdin', action='store_true') args = parser.parse_args() if args.limit < 0: parser.error('--limit must be nonnegative') pack = core.load_pack(args.question_pack) pairs, digest = load_data(args.domain, args.dataset) expected = {(p['pair_id'], role) for p in pairs for role in ('before', 'after')} predictions = {} if args.predictions.exists(): for line in args.predictions.read_text().splitlines(): if not line: continue row = json.loads(line) identity = row['pair_id'], row['role'] if identity not in expected or identity in predictions or row['domain'] != args.domain or row['model_revision'] != MODEL: raise ValueError(f'Unknown, duplicate, or wrong-model prediction: {identity}') predictions[identity] = row pending = [(p, role) for p in pairs for role in ('before', 'after') if (p['pair_id'], role) not in predictions] if args.score_saved and pending: raise ValueError(f'Incomplete: {len(pending)} method sides missing') if args.limit: pending = pending[:args.limit] if pending and not args.score_saved: if not args.key_stdin: raise ValueError('Use --key-stdin to provide the Liquid API key through standard input') key = sys.stdin.readline().strip() if not key: raise ValueError('Missing Liquid API key on standard input') args.predictions.parent.mkdir(parents=True, exist_ok=True) with args.predictions.open('a') as output: for index, (pair, role) in enumerate(pending, 1): row = predict(pair, role, args.domain, pack, key) predictions[pair['pair_id'], role] = row output.write(json.dumps(row, sort_keys=True) + '\n') output.flush() if index % 50 == 0 or index == len(pending): print(f'{args.domain}: {len(predictions)}/{len(expected)} method sides', file=sys.stderr, flush=True) if predictions.keys() != expected: print(f'{args.domain}: incomplete {len(predictions)}/{len(expected)}; rerun to resume', file=sys.stderr) return if args.domain == 'lint': report = score_lint(pairs, predictions, digest) else: report = core.report(pairs, predictions, args.domain, digest, MODEL, pack['protocol_id'], .5, pack) report['protocol_id'] = PROTOCOL report['input_tokens'] = sum((row.get('usage') or {}).get('input_tokens', 0) for row in predictions.values()) report['output_tokens'] = sum((row.get('usage') or {}).get('output_tokens', 0) for row in predictions.values()) report['api_calls'] = len(predictions) args.report.parent.mkdir(parents=True, exist_ok=True) args.report.write_text(json.dumps(report, indent=2, sort_keys=True) + '\n') print(json.dumps(report, sort_keys=True)) if __name__ == '__main__': main()