File size: 11,291 Bytes
bd27cf3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Long-context families: states of ~800-4000 tokens (big logs, wide JSON
arrays, multi-clause policy docs, dense incident reports). Exercises the
state encoder's long-range extraction — current families are all <400 tok.
"""
import json
import random

from .genbase import generate, emit, q_choice, q_noul, q_score, validate_row

rng = random.Random()

SERVICES = ["auth", "billing", "gateway", "worker", "search", "notify",
            "ledger", "cache", "queue", "frontend", "reporting", "inventory"]
LEVELS = ["INFO", "DEBUG", "WARN", "ERROR"]
COMPANIES = ["Acme Corp", "BluePeak", "Corebridge", "Datamint", "Everline",
             "Ferrous Ltd", "GreenDesk", "Heliotrope", "IronOak", "Jetstone"]
SKUS = ["SKU-{:04d}".format(i) for i in range(200)]


def _ts(m):
    return f"2026-09-{rng.randint(1,28):02d}T{rng.randint(0,23):02d}:{rng.randint(0,59):02d}:{rng.randint(0,59):02d}Z"


def gen_long_log():
    """60-160 log lines across 4-8 services; one service is the culprit."""
    n_lines = rng.randint(60, 160)
    svcs = rng.sample(SERVICES, rng.randint(4, 8))
    culprit = rng.choice(svcs)
    culprit_idx = rng.randint(15, n_lines - 5)
    lines, first_err, err_counts = [], None, {s: 0 for s in svcs}
    for i in range(n_lines):
        s = rng.choice(svcs)
        lvl = "INFO" if rng.random() < 0.6 else rng.choice(
            ["DEBUG", "WARN", "ERROR"])
        if i >= culprit_idx and s == culprit:
            lvl = "ERROR" if rng.random() < 0.8 else "WARN"
        if lvl == "ERROR":
            err_counts[s] += 1
            if first_err is None:
                first_err = s
        msg = rng.choice(["request handled", "retrying upstream",
                          "connection reset", "timeout waiting on lock",
                          "cache miss", "batch flushed", "heartbeat ok",
                          "null pointer in handler", "disk threshold hit",
                          "consumer lag rising"])
        lines.append(f"{_ts(i)} [{lvl}] {s}: {msg}")
    state = "\n".join(lines)
    qv = [float(s == culprit) for s in svcs]
    qs = [q_choice("culprit",
                   "Which service is responsible for the incident?",
                   svcs, qv)]
    if rng.random() < 0.6:
        n_err = sum(1 for ln in lines if "[ERROR]" in ln)
        qs.append(q_regress_count(n_err,
                                  "How many ERROR-level lines are in the log?",
                                  "lines"))
    p_err = sum(v for s, v in err_counts.items() if s == culprit) / max(
        1, sum(err_counts.values()))
    qs.append(q_noul("culprit_majority",
                     f"Did {culprit} produce the majority of ERROR lines?",
                     float(p_err > 0.5)))
    return state, qs


def q_regress_count(n, instr, unit):
    from .genbase import q_regress
    return q_regress("count", instr, [float(n)] * 19, unit=unit)


def gen_big_json():
    """JSON array of 60-140 product records; exact aggregate questions."""
    n = rng.randint(60, 140)
    recs = []
    for i in range(n):
        recs.append({"sku": rng.choice(SKUS), "cat": rng.choice(
            ["tool", "part", "consumable", "equipment"]),
            "price": round(rng.uniform(1, 500), 2),
            "stock": rng.randint(0, 300),
            "supplier": rng.choice(COMPANIES)})
    state = json.dumps({"warehouse_inventory": recs})
    priciest = max(recs, key=lambda r: r["price"])
    n_stock0 = sum(1 for r in recs if r["stock"] == 0)
    cats = sorted({r["cat"] for r in recs})
    cat_share = {c: sum(1 for r in recs if r["cat"] == c) / n for c in cats}
    # dominant category: exact argmax, ties -> uniform over tied cats
    mx = max(cat_share.values())
    tied = [c for c in cats if cat_share[c] == mx]
    qv = [1.0 / len(tied) if c in tied else 0.0 for c in cats]
    qs = [
        q_noul("pricey_tool",
               "Is the most expensive record a 'tool' item?",
               float(priciest["cat"] == "tool")),
        q_noul("stockout10", "Are more than 10 records out of stock?",
               float(n_stock0 > 10)),
        q_choice("dominant_cat", "Which category has the most records?",
                 cats, qv),
        q_regress_count(n_stock0, "How many records have stock == 0?",
                        "records"),
    ]
    return state, qs


def gen_policy_doc():
    """Multi-clause policy document (30-80 clauses); ask which clause governs."""
    n_clauses = rng.randint(30, 80)
    domains = ["refunds", "travel", "expenses", "security", "hiring",
               "procurement", "data retention", "vendor onboarding"]
    domain = rng.choice(domains)
    clauses = []
    target_idx = rng.randint(0, n_clauses - 1)
    target_amt = rng.choice([50, 100, 250, 500, 1000, 2500, 5000])
    for i in range(n_clauses):
        c = f"Clause {i+1}: "
        if i == target_idx:
            c += (f"Any {domain} request exceeding ${target_amt} requires "
                  f"sign-off from the regional director.")
        else:
            amt = rng.choice([10, 25, 75, 15000, 25000])
            c += rng.choice([
                f"{domain} requests under ${amt} may be auto-approved by "
                f"the system.",
                f"All {domain} documentation must be retained for "
                f"{rng.randint(1,10)} years.",
                f"{domain} submissions on weekends route to the on-call "
                f"manager.",
                f"Duplicate {domain} submissions within "
                f"{rng.randint(2,30)} days are merged automatically."])
        clauses.append(c)
    state = (f"POLICY MANUAL — {domain.upper()} (v{rng.randint(2,9)}."
             f"{rng.randint(0,9)})\n\n" + "\n".join(clauses))
    amt = target_amt + rng.choice([1, 10, 100, 500])
    qs = [q_noul("needs_director",
                 f"A {domain} request for ${amt} just arrived. Does it "
                 f"require regional director sign-off?", 1.0),
          q_choice("which_clause",
                   f"Which clause governs a ${amt} {domain} request?",
                   [f"Clause {i+1}" for i in range(n_clauses)]
                   if n_clauses <= 30 else None or
                   [f"Clause {i+1}" for i in
                    sorted(set([target_idx] +
                               rng.sample(range(n_clauses),
                                          min(9, n_clauses - 1))))],
                   None)]
    # fix the choice target: one-hot on the true clause, restricted option set
    opts = [f"Clause {i+1}" for i in
            sorted(set([target_idx] + rng.sample(range(n_clauses),
                                                 min(9, n_clauses - 1))))]
    qs[1] = q_choice("which_clause",
                     f"Which clause governs a ${amt} {domain} request?",
                     opts, [float(o == f"Clause {target_idx+1}") for o in opts])
    return state, qs


def gen_incident_report():
    """Dense prose incident report with embedded facts; reading comprehension."""
    svc = rng.choice(SERVICES)
    n_users = rng.choice([120, 350, 800, 2400, 5600, 12000])
    dur = rng.choice([12, 27, 45, 90, 150])
    sev = rng.choice(["SEV1", "SEV2", "SEV3"])
    cause = rng.choice(["bad deploy", "certificate expiry", "DNS misconfig",
                        "db failover loop", "cache stampede"])
    day = rng.randint(1, 28)
    resolution = rng.choice(['rolled back the deploy',
                             'rotated the certificate', 'repointed DNS',
                             'killed the failover loop', 'warmed the cache'])
    detected_via = rng.choice(['pager alert', 'customer report',
                               'dashboard review'])
    paras = [
        f"Incident INC-{rng.randint(1000,9999)} occurred on 2026-09-{day:02d}. "
        f"The {svc} service began returning elevated error rates at "
        f"{rng.randint(0,23):02d}:{rng.randint(0,59):02d} UTC after a "
        f"{cause}. On-call was paged {rng.randint(2,15)} minutes later.",
        f"Impact assessment: approximately {n_users} users were affected "
        f"over a {dur}-minute window. Retry storms amplified load on "
        f"{rng.choice(SERVICES)} but did not cause secondary failure. "
        f"Customer support received {rng.randint(5,80)} related tickets.",
        f"Resolution: the on-call engineer {resolution} and error rates "
        f"returned to baseline. Severity classification: {sev}. Postmortem "
        f"scheduled within {rng.randint(2,7)} days. Action items: "
        f"{rng.randint(3,9)} filed.",
    ]
    if rng.random() < 0.5:
        paras.insert(1, f"Timeline detail: detection via {detected_via}; "
                     f"the incident channel had {rng.randint(4,40)} "
                     f"participants.")
    state = "\n\n".join(paras)
    qs = [
        q_choice("service", "Which service was primarily affected?",
                 SERVICES, [float(s == svc) for s in SERVICES]),
        q_noul("sev12", "Was the incident SEV1 or SEV2?",
               float(sev in ("SEV1", "SEV2"))),
        q_noul("big_impact", "Did the incident affect more than 1000 users?",
               float(n_users > 1000)),
        q_choice("cause", "What caused the incident?",
                 ["bad deploy", "certificate expiry", "DNS misconfig",
                  "db failover loop", "cache stampede"],
                 [float(c == cause) for c in
                  ["bad deploy", "certificate expiry", "DNS misconfig",
                   "db failover loop", "cache stampede"]]),
    ]
    return state, qs


def gen_sensor_grid():
    """Many sensors, one report; spatial aggregation questions."""
    rows = rng.randint(8, 20)
    cols = rng.randint(8, 20)
    n_sensors = rows * cols
    fail_rate = rng.choice([0.02, 0.05, 0.1])
    grid, n_fail = [], 0
    fail_cells = []
    for r in range(rows):
        row = []
        for c in range(cols):
            bad = rng.random() < fail_rate
            row.append("X" if bad else ".")
            if bad:
                n_fail += 1
                fail_cells.append((r, c))
        grid.append("".join(row))
    state = (f"Sensor grid {rows}x{cols} ({n_sensors} sensors). "
             f"'X' = sensor reporting fault, '.' = healthy.\n" +
             "\n".join(grid))
    qs = [
        q_noul("critical", f"Is the grid in a critical state (>{int(fail_rate*1.5*100)}% faults)?",
               float(n_fail / n_sensors > fail_rate * 1.5)),
        q_noul("any_fault", "Are there any faults?", float(n_fail > 0)),
    ]
    if fail_cells:
        r0 = min(r for r, _ in fail_cells)
        qs.append(q_noul("top_fault",
                         "Is there a fault in the top half of the grid?",
                         float(r0 < rows // 2)))
    return state, qs


FAMILIES = {"long_log": gen_long_log, "big_json": gen_big_json,
            "policy_doc": gen_policy_doc, "incident_report": gen_incident_report,
            "sensor_grid": gen_sensor_grid}
WEIGHTS = {"long_log": 0.22, "big_json": 0.22, "policy_doc": 0.18,
           "incident_report": 0.20, "sensor_grid": 0.18}


def make_rows(n, seed):
    return generate(FAMILIES, WEIGHTS, n, seed, rng)


if __name__ == "__main__":
    rows = make_rows(8, 0)
    for r in rows:
        validate_row(r)
        print(r["id"], "| state chars:", len(r["state"]))
    print(f"{len(rows)} rows OK")