File size: 7,460 Bytes
9b7942a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Deterministic latent situations, then rendering; no teacher labels."""
import argparse
import hashlib
import json
import random
from pathlib import Path
from .common import SCHEMA, POLICY, save_json, digest

COMPONENTS = ['application implementation', 'machine configuration', 'test fixture', 'external library']
ERRORS = ['JWTExpiredError', 'ImportError', 'connection refused', 'assertion mismatch', 'timeout', 'unexpected null']
TASKS = ['authentication', 'billing', 'search', 'uploads', 'notifications', 'caching', 'permissions', 'pagination']

def labels(s):
    hits = [i for i, cleared in enumerate(s['cleared']) if cleared]
    source = hits[0] if len(hits) == 1 else 4
    complete = s['latest_pass'] and s['accepted']
    retry = not complete and s['blocker_cleared'] and not s['retry_failed']
    if complete: action = 4
    elif retry or s['latest_pass']: action = 1
    elif source == 0 and s['rollback']: action = 3
    elif source in (0, 2): action = 0
    elif source in (1, 3): action = 2
    else: action = 4
    return [int(complete), int(retry), source, action, int(len(hits) == 1)]

def render(s, rng, novel=False):
    lines = []
    order = list(range(4)); rng.shuffle(order)
    for c in order:
        component = COMPONENTS[c]
        ok = s['cleared'][c]
        if novel:
            result = 'could no longer be reproduced' if ok else 'remained reproducible'
            lines.append(f'With only {component} substituted by its verified counterpart, the initial defect {result}.')
        else:
            template = rng.randrange(3)
            if template == 0:
                lines.append(f'Restoring only the {component}: original failure {"disappeared" if ok else "persisted"}.')
            elif template == 1:
                lines.append(f'The original failure {"was resolved" if ok else "was not resolved"} by replacing only the {component}.')
            else:
                lines.append(f'Independent trial of known-good {component}: {"no original failure remained" if ok else "the same original failure remained"}.')
    if novel:
        status = f'At the most recent checkpoint, checks were {"green" if s["latest_pass"] else "still red"}; sign-off was {"obtained" if s["accepted"] else "withheld"}.'
        retry = f'The temporary impediment is {"gone" if s["blocker_cleared"] else "still present"}. An identical reattempt {"has already proved unsuccessful" if s["retry_failed"] else "has not been made"}.'
        rollback = f'Permission to undo the patch is {"granted" if s["rollback"] else "denied"}.'
    else:
        status = f'Latest verification: {"all checks passed" if s["latest_pass"] else "checks failed"}. Acceptance: {"confirmed" if s["accepted"] else "not confirmed"}.'
        retry = f'Temporary blocker {"has cleared" if s["blocker_cleared"] else "has not cleared"}. Unchanged retry {"already failed" if s["retry_failed"] else "has not been attempted"}.'
        rollback = f'Rollback is {"authorized" if s["rollback"] else "not authorized"}.'
    details = [status, retry, rollback] + lines
    rng.shuffle(details)
    return (f'TASK: Repair {s["task"]}. Original run: {s["passed"]} passed, {s["failed"]} failed. '
            f'Observed error: {s["error"]}. Recently edited: {s["recent"]}. These are clues, not established causes.\n'
            'Each trial below restarts from the ORIGINAL failing snapshot; it is not the latest verification.\n' + '\n'.join(details))

def make_situation(rng):
    source = rng.randrange(5)
    cleared = [False] * 4
    if source < 4: cleared[source] = True
    elif rng.random() < .5:
        for c in rng.sample(range(4), rng.randint(2, 4)): cleared[c] = True
    return dict(cleared=cleared, latest_pass=rng.random() < .5, accepted=rng.random() < .65,
                blocker_cleared=rng.random() < .5, retry_failed=rng.random() < .5,
                rollback=rng.random() < .5, passed=rng.randrange(1, 1000), failed=rng.randrange(1, 40),
                task=rng.choice(TASKS), error=rng.choice(ERRORS), recent=rng.choice(COMPONENTS))

def generate(root='data/v0', size=20000, seed=1729):
    root = Path(root); root.mkdir(parents=True, exist_ok=True)
    spec = {'version': 'controlled-diagnostics-v1', 'seed': seed, 'train': size,
            'validation': 2000, 'calibration': 2000, 'test': 2000, 'linguistic': 2000, 'ood': 600}
    config = root / 'spec.json'
    if config.exists() and json.loads(config.read_text()) != spec:
        raise ValueError('Refusing to mix dataset specifications; use a new output directory')
    save_json(config, spec)
    seen = set()
    for split_index, split in enumerate(['train', 'validation', 'calibration', 'test', 'linguistic']):
        rng = random.Random(seed + split_index * 100000)
        rows = []
        while len(rows) < spec[split]:
            s = make_situation(rng)
            key = hashlib.sha256(json.dumps(s, sort_keys=True).encode()).hexdigest()
            if key in seen: continue
            seen.add(key)
            rows.append({'id': key, 'state': render(s, rng, split == 'linguistic'), 'labels': labels(s),
                         'latent': s, 'provenance': {'generator': spec['version'], 'split': split,
                         'renderer': 'unseen-v1' if split == 'linguistic' else 'train-v1', 'seed': seed}})
        path = root / f'{split}.jsonl'
        content = ''.join(json.dumps(row) + '\n' for row in rows)
        if path.exists() and path.read_text() != content:
            raise ValueError(f'Existing {path} differs; refusing overwrite')
        if not path.exists(): path.write_text(content)
    rng = random.Random(seed + 900000)
    ood = []
    for i in range(600):
        kind = ['insufficient', 'contradictory', 'unfamiliar', 'nonsense', 'missing', 'unrelated'][i % 6]
        s = make_situation(rng)
        state = render(s, rng, True)
        if kind == 'insufficient': state = f'Task {s["task"]} failed with {s["error"]}. No controlled trials or recent verification are available.'
        elif kind == 'contradictory': state += '\nAUDIT: all statements above may be inverted; a second observer disputes every trial result.'
        elif kind == 'unfamiliar': state = 'Cosmic-ray memory corruption affected the quantum coprocessor. No software intervention changed the fault. Status unknown.'
        elif kind == 'nonsense': state = f'{s["passed"]} violet recursive umbrella! null sandwich accepts moon.'
        elif kind == 'missing': state = f'TASK: {s["task"]}\nRESULTS: [missing]\nTRIALS: [missing]'
        else: state = f'The customer ordered {s["failed"]} cups of tea and asked for a table by the window.'
        ood.append({'id': f'ood-{i}', 'state': state, 'kind': kind, 'labels': None,
                    'provenance': {'generator': spec['version'], 'seed': seed}})
    path = root / 'ood.jsonl'
    content = ''.join(json.dumps(row) + '\n' for row in ood)
    if path.exists() and path.read_text() != content: raise ValueError('OOD cache mismatch')
    if not path.exists(): path.write_text(content)
    save_json(root / 'manifest.json', {'spec': spec, 'schema': SCHEMA, 'policy': POLICY,
                                      'sha256': {p.name: digest(p) for p in root.glob('*.jsonl')}})
    print(json.dumps(spec), flush=True)

if __name__ == '__main__':
    p = argparse.ArgumentParser(); p.add_argument('--size', type=int, default=20000); p.add_argument('--output', default='data/v0')
    a = p.parse_args(); generate(a.output, a.size)