from __future__ import annotations import argparse import concurrent.futures import json import random from pathlib import Path from awkweave.execution import run_awk from generate_data import Case, NAMES, STATUSES, WORDS, pair, render, rows def apache(rng: random.Random) -> list[str]: outputs = [] methods = ["GET", "POST", "PUT", "DELETE"] paths = ["/index.html", "/api/orders", "/api/items", "/health", "/missing", "/assets/app.js"] for _ in range(2): lines = [] for _ in range(rng.randint(7, 12)): ip = f"192.0.2.{rng.randint(1, 254)}" method = rng.choice(methods) path = rng.choice(paths) status = rng.choice([200, 200, 200, 201, 204, 400, 404, 500, 502, 503]) size = rng.randint(0, 5000) lines.append(f'{ip} - - [28/Nov/2026:10:00:00 +0000] "{method} {path} HTTP/1.1" {status} {size}') outputs.append("\n".join(lines) + "\n") return outputs def with_regions(rng: random.Random, kinds: list[str]) -> list[list[str]]: result = rows(rng, kinds) if "category" in kinds: index = kinds.index("category") for row in result: row[index] = rng.choice(["east", "west", "north", "south"]) return result def sales_pair(rng: random.Random) -> tuple[list[str], list[str]]: columns = [("order_id", "id"), ("region", "category"), ("amount", "smallint"), ("status", "status"), ("units", "smallint")] rng.shuffle(columns) headers = [name for name, _ in columns] kinds = [kind for _, kind in columns] old = STATUSES[:] STATUSES[:] = ["paid", "pending", "void", "paid"] try: inputs = [render(with_regions(rng, kinds), header=headers), render(with_regions(rng, kinds), header=headers)] finally: STATUSES[:] = old return headers, inputs def keyvalues(rng: random.Random) -> list[str]: outputs = [] services = ["web", "db", "api", "worker"] levels = ["info", "INFO", "warn", "ERROR", "error", "debug"] for _ in range(2): lines = [] for index in range(rng.randint(7, 11)): fields = [ f"level={rng.choice(levels)}", f"service={rng.choice(services)}", f"latency={rng.randint(1, 80)}", f"shard={rng.randint(1, 4)}", ] rng.shuffle(fields) lines.append(f"2026-11-28T09:{index:02d}:00Z " + " ".join(fields)) outputs.append("\n".join(lines) + "\n") return outputs def passwd(rng: random.Random) -> list[str]: outputs = [] shells = ["/bin/bash", "/bin/zsh", "/bin/sh", "/usr/sbin/nologin"] for _ in range(2): lines = [] for index, name in enumerate(rng.sample(NAMES, 8)): uid = rng.choice([0, 1, 999, 1000, 1001, 1002, 1003]) lines.append(f"{name}:x:{uid}:{uid}:{name}:/home/{name}:{rng.choice(shells)}") outputs.append("\n".join(lines) + "\n") return outputs def header_program(expression: str) -> str: return f'NR==1{{for(i=1;i<=NF;i++)h[$i]=i;next}}{expression}' def make_case(family: str, seed: int) -> Case: rng = random.Random(seed) if family == "http_status_class": low, high, label = rng.choice([(200, 299, "2xx"), (400, 499, "4xx"), (500, 599, "5xx")]) return Case(f"Count responses in the HTTP {label} status class and print 0 when none exist.", f'$9>={low}&&$9<={high}{{n++}}END{{print n+0}}', apache(rng), family, 2) if family == "http_bytes_total": return Case("Sum response bytes from the last field and print one total.", '{s+=$NF}END{print s+0}', apache(rng), family, 1) if family == "http_method": method = rng.choice(["GET", "POST", "PUT", "DELETE"]) return Case(f"Print complete request records using the {method} method.", f'$6=="\\"{method}"', apache(rng), family, 2) if family == "http_path": prefix = rng.choice(["/api/", "/assets/"]) escaped = prefix.replace("/", "\\/") return Case(f"Print request paths beginning with {prefix}.", f'$7 ~ /^{escaped}/{{print $7}}', apache(rng), family, 2) if family == "http_success_average": return Case("For HTTP 200 responses only, print mean response bytes to two decimal places.", '$9==200{s+=$10;n++}END{printf "%.2f\\n",s/n}', apache(rng), family, 2) if family == "http_unique_clients": return Case("Count distinct client IP addresses in these request logs.", '{if(!seen[$1]++)n++}END{print n+0}', apache(rng), family, 1) if family == "http_path_bytes": program = '{if(!($7 in sums))order[++n]=$7;sums[$7]+=$10}END{for(i=1;i<=n;i++)print order[i],sums[order[i]]}' return Case("Sum response bytes per request path in first-appearance order.", program, apache(rng), family, 2) if family == "http_error_rate": return Case("Print the percentage of 5xx responses to one decimal place, including the percent sign.", '$9>=500{n++}END{printf "%.1f%%\\n",100*n/NR}', apache(rng), family, 2) if family == "http_largest": program = '{if(NR==1||$NF>largest){largest=$NF;record=$0}}END{print record}' return Case("Print the complete response with the largest byte count; keep the earliest on ties.", program, apache(rng), family, 2) if family == "http_path_counts": program = '{if(!($7 in counts))order[++n]=$7;counts[$7]++}END{for(i=1;i<=n;i++)print order[i],counts[order[i]]}' return Case("Count requests per URL path and print groups in order of first appearance.", program, apache(rng), family, 2) if family == "header_average": headers, inputs = sales_pair(rng) expression = '{s+=$h["amount"];n++}END{printf "%.2f\\n",s/n}' return Case("Use the amount header and print the mean amount over data rows to two decimals.", header_program(expression), inputs, family, 2) if family == "header_sum_filter": headers, inputs = sales_pair(rng) expression = '$h["status"]=="paid"{s+=$h["amount"]}END{print s+0}' return Case("Find columns by name and print the total amount for paid records only.", header_program(expression), inputs, family, 2) if family == "header_group_average": headers, inputs = sales_pair(rng) expression = '{key=$h["region"];if(!(key in sums))order[++n]=key;sums[key]+=$h["amount"];counts[key]++}END{for(i=1;i<=n;i++)printf "%s %.2f\\n",order[i],sums[order[i]]/counts[order[i]]}' return Case("Print each region and its average amount to two decimals in first-appearance order.", header_program(expression), inputs, family, 3) if family == "header_group_units": headers, inputs = sales_pair(rng) expression = '{key=$h["region"];if(!(key in sums))order[++n]=key;sums[key]+=$h["units"]}END{for(i=1;i<=n;i++)print order[i],sums[order[i]]}' return Case("Use the headers to total units by region, preserving first-appearance order.", header_program(expression), inputs, family, 2) if family == "header_top_two": headers, inputs = sales_pair(rng) expression = '{n++;v[n]=$h["amount"]+0;line[n]=$0}END{for(i=2;i<=n;i++){x=v[i];s=line[i];j=i-1;while(j>=1&&v[j]{threshold})print $1}}}}' return Case(f"Print timestamps for records with latency greater than {threshold}.", program, keyvalues(rng), family, 2) if family == "kv_service_latency": program = '{service="";latency=0;for(i=1;i<=NF;i++){split($i,p,"=");if(p[1]=="service")service=p[2];if(p[1]=="latency")latency=p[2]}if(!(service in sums))order[++n]=service;sums[service]+=latency}END{for(i=1;i<=n;i++)print order[i],sums[order[i]]}' return Case("Total latency by service in first-appearance order, reading key=value fields.", program, keyvalues(rng), family, 3) if family == "kv_level_counts": program = '{level="";for(i=1;i<=NF;i++){split($i,p,"=");if(p[1]=="level")level=tolower(p[2])}if(!(level in counts))order[++n]=level;counts[level]++}END{for(i=1;i<=n;i++)print order[i],counts[order[i]]}' return Case("Count records per level in first-appearance order, normalizing level names to lowercase.", program, keyvalues(rng), family, 3) if family == "kv_service_average": program = '{service="";latency=0;for(i=1;i<=NF;i++){split($i,p,"=");if(p[1]=="service")service=p[2];if(p[1]=="latency")latency=p[2]}if(!(service in sums))order[++n]=service;sums[service]+=latency;counts[service]++}END{for(i=1;i<=n;i++)printf "%s %.1f\\n",order[i],sums[order[i]]/counts[order[i]]}' return Case("Print average latency per service to one decimal in first-appearance order.", program, keyvalues(rng), family, 3) if family == "passwd_shell": shell = rng.choice(["/bin/bash", "/bin/zsh", "/bin/sh"]) return Case(f"In this colon-delimited account data, print usernames using {shell}.", f'BEGIN{{FS=":"}}$7=="{shell}"{{print $1}}', passwd(rng), family, 1) if family == "passwd_uid": return Case("Using colon separators, print username and UID for UID values from 1000 through 1002 inclusive.", 'BEGIN{FS=":";OFS=":"}$3>=1000&&$3<=1002{print $1,$3}', passwd(rng), family, 2) if family == "passwd_shell_counts": program = 'BEGIN{FS=":"}{if(!($7 in counts))order[++n]=$7;counts[$7]++}END{for(i=1;i<=n;i++)print order[i],counts[order[i]]}' return Case("Count accounts per login shell in first-appearance order for colon-delimited records.", program, passwd(rng), family, 2) if family == "passwd_no_login": return Case("Print account names that cannot log in because their shell ends in nologin.", 'BEGIN{FS=":"}$7 ~ /nologin$/{print $1}', passwd(rng), family, 1) if family == "running_delta": program = '{change=$2-previous;if(NR==1)change=0;print $1,change;previous=$2}' return Case("For each record, print column 1 and the change in column 2 from the previous row, starting with 0.", program, pair(rng, ["category", "smallint", "word"]), family, 2) if family == "clamp_values": return Case("Clamp column 2 to the inclusive interval 8 through 18 while preserving every other field.", '{if($2<8)$2=8;else if($2>18)$2=18;print}', pair(rng, ["category", "smallint", "word"]), family, 2) if family == "group_maximum": program = '{if(!($1 in seen)){order[++n]=$1;seen[$1]=1;max[$1]=$2}if($2>max[$1])max[$1]=$2}END{for(i=1;i<=n;i++)print order[i],max[order[i]]}' return Case("Print each column-1 group with its maximum column-2 value in first-appearance order.", program, pair(rng, ["category", "smallint", "word"]), family, 2) if family == "first_last_group": program = '{if(!($1 in first)){first[$1]=$2;order[++n]=$1}last[$1]=$2}END{for(i=1;i<=n;i++)print order[i],first[order[i]],last[order[i]]}' return Case("For each column-1 group, print its first and last column-2 values in first-appearance order.", program, pair(rng, ["category", "smallint", "word"]), family, 2) if family == "consecutive_dedup": return Case("Suppress consecutive rows with the same column-1 group, printing one complete row per run.", '$1!=previous{print}{previous=$1}', pair(rng, ["category", "smallint", "word"]), family, 2) if family == "absolute_difference": return Case("Print column 1 and the absolute difference between columns 2 and 3 for every record.", '{d=$2-$3;if(d<0)d=-d;print $1,d}', pair(rng, ["category", "smallint", "smallint"]), family, 1) if family == "positive_ratio": return Case("Print column 1 and column 3 divided by column 2 as a percentage with one decimal; skip zero denominators.", '$2!=0{printf "%s %.1f%%\\n",$1,100*$3/$2}', pair(rng, ["category", "smallint", "smallint"]), family, 2) if family == "sorted_unique": program = '{seen[$1]=1}END{for(word in seen){value[++n]=word}for(i=2;i<=n;i++){x=value[i];j=i-1;while(j>=1&&value[j]>x){value[j+1]=value[j];j--}value[j+1]=x}for(i=1;i<=n;i++)print value[i]}' return Case("Print distinct column-1 values once each in ascending lexical order.", program, pair(rng, ["category", "smallint", "word"]), family, 3) if family == "blank_filter": inputs = pair(rng, ["word", "int"]) inputs = [text.replace("\n", "\n\n", 2) + " \n" for text in inputs] return Case("Remove blank and whitespace-only lines without changing other records.", '$0 ~ /[^[:space:]]/', inputs, family, 1) if family == "blank_count": inputs = pair(rng, ["word", "int"]) inputs = [text.replace("\n", "\n\n", 2) + " \n" for text in inputs] return Case("Count blank or whitespace-only input lines.", '$0 !~ /[^[:space:]]/{n++}END{print n+0}', inputs, family, 1) if family == "line_numbers": inputs = pair(rng, ["word", "int"]) inputs = [text.replace("\n", "\n\n", 1) for text in inputs] return Case("Prefix every non-empty line with its original line number, a colon, and a space.", '$0 ~ /[^[:space:]]/{print NR ": " $0}', inputs, family, 1) if family == "character_count": return Case("Print the total number of characters in the input, excluding newlines.", '{n+=length($0)}END{print n+0}', pair(rng, ["word", "int", "status"]), family, 1) if family == "comma_to_tab": return Case("Convert simple comma-separated input to tab-separated output without reordering fields.", 'BEGIN{FS=",";OFS="\\t"}{$1=$1;print}', pair(rng, ["name", "int", "word"], ","), family, 1) if family == "fixed_width": return Case("Right-align column 1 in a width of 8 and append column 2 immediately after the padding.", '{printf "%8s%s\\n",$1,$2}', pair(rng, ["category", "smallint", "word"]), family, 2) raise ValueError(family) FAMILIES = [ "http_status_class", "http_bytes_total", "http_method", "http_path", "http_success_average", "http_unique_clients", "http_path_bytes", "http_error_rate", "http_largest", "http_path_counts", "header_average", "header_sum_filter", "header_group_average", "header_group_units", "header_top_two", "header_percentage", "header_min_amount", "kv_service_errors", "kv_latency_threshold", "kv_service_latency", "kv_level_counts", "kv_service_average", "passwd_shell", "passwd_uid", "passwd_shell_counts", "passwd_no_login", "running_delta", "clamp_values", "group_maximum", "first_last_group", "consecutive_dedup", "absolute_difference", "positive_ratio", "sorted_unique", "blank_filter", "blank_count", "line_numbers", "character_count", "comma_to_tab", "fixed_width", ] def generate_row(index: int, seed: int) -> dict: family = FAMILIES[index % len(FAMILIES)] for attempt in range(100): case = make_case(family, seed + index * 1009 + attempt * 1_000_003) try: outputs = [run_awk(case.program, text) for text in case.inputs] except ValueError: continue if not outputs[0].strip(): continue return { "id": f"awkweave-real-{index:07d}", "request": case.request, "program": case.program, "input_text": case.inputs[0], "expected_output": outputs[0], "validation_input": case.inputs[1], "validation_output": outputs[1], "family": case.family, "difficulty": case.difficulty, "split": "train", "source": "realistic-grammar", "license": "CC-BY-4.0", } raise RuntimeError(f"Could not generate {family} at {index}") def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--count", type=int, default=40_000) parser.add_argument("--seed", type=int, default=20261129) parser.add_argument("--workers", type=int, default=8) parser.add_argument("--output", type=Path, default=Path("awkweave-realistic.jsonl")) args = parser.parse_args() with args.output.open("w", encoding="utf-8") as handle: with concurrent.futures.ProcessPoolExecutor(max_workers=args.workers) as executor: futures = {executor.submit(generate_row, index, args.seed): index for index in range(args.count)} completed = 0 for future in concurrent.futures.as_completed(futures): row = future.result() handle.write(json.dumps(row, ensure_ascii=False, separators=(",", ":")) + "\n") completed += 1 if completed % 1000 == 0: handle.flush() print(f"generated {completed}/{args.count}", flush=True) print(f"wrote {args.count} rows to {args.output}") if __name__ == "__main__": main()