"""Gold-labelled data for the router instrument's JUDGE and RERANK sets.
JUDGE (32 items) measures a small model acting as a judge of computing work.
24 "verdict" items: does `candidate` meet `task`? gold "pass" | "fail" (12 / 12).
8 "pairwise" items: which of `a` / `b` better meets `task`? gold "a" | "b" (4 / 4); the
harness also runs each with a/b swapped to cancel position bias.
Categories: code (Python, Go, Rust), shell, sql, logs (is this summary faithful to the
lines?), config (nginx, systemd, sshd, YAML) and answer (factual sysadmin answers).
Fails are near-misses (negative-slice off-by-one, `$` matching before a trailing newline,
in-place delete while ranging, integer division, `-mtime -7`, `grep -c` under errexit,
COUNT(bool), a join missing its key, an invented count/event, proxy_pass without a URI,
cron's day-of-month OR day-of-week rule, a .255 that isn't a broadcast address). Passes
include terse or unusual-but-correct solutions, so surface pattern matching loses.
RERANK (16 items) measures a small model acting as a reranker: order `candidates` by
relevance to `query`. `relevance` grades 0-3 (omitted ids are 0) with exactly one id at the
top grade. Every item carries lexical hard negatives (share the query's keywords, don't
answer it) and at least one relevant candidate with low keyword overlap.
How the gold labels were verified (2026-10-12, recorded per item in "why"):
- Every code/shell/SQL verdict and pairwise item was executed from this module's exact
text in a fresh temp dir with tiny fixtures: Python with python3 3.9, Go with go 1.27,
Rust with rustc 1.96, shell with macOS bash 3.2 + BSD userland AND bash 5 + GNU
userland (Debian python:3.12-slim container), SQL with sqlite3 AND PostgreSQL 16.
- Config: the nginx item ran in nginx:1.27-alpine against an echo backend; the sshd item
via `sshd -T` plus a throwaway loopback sshd (offered auth methods); YAML via PyYAML 6.
The systemd item follows systemd.service(5) (not run: no systemd on the Mac).
- Log summaries were checked claim-by-claim against the quoted lines; answers against
crontab(5), ssh(1)/ssh_config(5), Python's ipaddress module and shell semantics.
- Rerank grades are hand-assigned; candidates' factual content was checked against the
relevant man pages / language docs.
Scoring is deterministic: no model judges another.
"""
JUDGE = [
# ============================================================ verdict: code
{"id": "j-py-chunks", "cat": "code", "kind": "verdict",
"task": "Python: write `chunks(xs, n)` that splits the list `xs` into consecutive sub-lists of "
"length `n` (n >= 1) and returns them as a list of lists; the last sub-list may be "
"shorter. Examples: chunks([1, 2, 3, 4, 5], 2) == [[1, 2], [3, 4], [5]] and "
"chunks([], 3) == [].",
"candidate": """from itertools import islice
def chunks(xs, n):
it = iter(xs)
return list(iter(lambda: list(islice(it, n)), []))
""",
"gold": "pass",
"why": "iter(callable, sentinel) pulls n-item slices until an empty list; executed: matches a "
"reference on all lists of length 0-12 for n=1-6, incl. both examples."},
{"id": "j-py-tail", "cat": "code", "kind": "verdict",
"task": "Python: write `tail(path, n)` that returns the last `n` lines of a text file as a "
"list of strings without their newline characters, like `tail -n`. n >= 1. If the "
"file has fewer than n lines, return all of its lines.",
"candidate": """def tail(path, n):
with open(path) as f:
lines = f.read().splitlines()
return lines[len(lines) - n:]
""",
"gold": "fail",
"why": "when n > len(lines) the start index goes negative and slices from the end; executed: "
"3-line file with n=5 returns 2 lines, not 3."},
{"id": "j-py-ipv4", "cat": "code", "kind": "verdict",
"task": "Python: write `is_ipv4(s)` that returns True only if the string `s` is exactly a "
"dotted-quad IPv4 address (four decimal numbers 0-255 separated by dots) and False "
"for anything else, including strings with leading or trailing whitespace or "
"newlines. Leading zeros in an octet may be accepted.",
"candidate": r"""import re
def is_ipv4(s):
if not re.match(r"^\d{1,3}(\.\d{1,3}){3}$", s):
return False
return all(int(p) <= 255 for p in s.split("."))
""",
"gold": "fail",
"why": "`$` also matches just before a trailing newline and int() strips it; executed: "
"is_ipv4('10.0.0.1\\n') is True (other cases like 256.1.1.1 / 1.2.3 are right)."},
{"id": "j-go-lowerbound", "cat": "code", "kind": "verdict",
"task": "Go: write `func LowerBound(a []int, x int) int` that, for a slice `a` sorted in "
"ascending order (duplicates allowed), returns the index of the first element >= x, "
"or len(a) if there is none. It must run in O(log n). Don't use the sort or slices "
"packages.",
"candidate": """func LowerBound(a []int, x int) int {
lo, n := 0, len(a)
for n > 0 {
half := n / 2
if a[lo+half] < x {
lo += half + 1
n -= half + 1
} else {
n = half
}
}
return lo
}
""",
"gold": "pass",
"why": "count-based (std::lower_bound-style) binary search; executed: matches a linear scan "
"for every sorted slice over {0..3} of length 0-7 and every x in -1..4."},
{"id": "j-go-dropempty", "cat": "code", "kind": "verdict",
"task": "Go: write `func DropEmpty(xs []string) []string` that returns the elements of xs that "
"are not the empty string, in their original order. Reusing xs's backing array is "
"fine.",
"candidate": """func DropEmpty(xs []string) []string {
for i, s := range xs {
if s == "" {
xs = append(xs[:i], xs[i+1:]...)
}
}
return xs
}
""",
"gold": "fail",
"why": "deleting while ranging skips the element shifted into slot i; executed: "
"[a \"\" \"\" b] -> [a \"\" b], and [\"\" \"\" \"\"] panics (slice bounds out of range)."},
{"id": "j-rs-median", "cat": "code", "kind": "verdict",
"task": "Rust: write `fn median(v: &mut Vec<i64>) -> Option<f64>` that returns None for an "
"empty vector and otherwise the median. For an even number of elements the median is "
"the mean of the two middle values, so [1, 2] gives 1.5. Sorting v in place is "
"allowed.",
"candidate": """fn median(v: &mut Vec<i64>) -> Option<f64> {
if v.is_empty() {
return None;
}
v.sort_unstable();
let n = v.len();
if n % 2 == 1 {
Some(v[n / 2] as f64)
} else {
Some(((v[n / 2 - 1] + v[n / 2]) / 2) as f64)
}
}
""",
"gold": "fail",
"why": "the even case divides as i64 before converting; executed (rustc): median([1, 2]) = "
"1.0, median([3, 1, 4, 2]) = 2.0 instead of 1.5 / 2.5."},
{"id": "j-rs-wordfreq", "cat": "code", "kind": "verdict",
"task": "Rust: write `fn word_freq(text: &str) -> HashMap<String, usize>` that counts words, "
"where words are separated by any whitespace and counted case-insensitively (keys "
"are lowercase). Example: \"The cat\\tthe\\n\" gives {\"the\": 2, \"cat\": 1}. Assume "
"`use std::collections::HashMap;` is in scope.",
"candidate": """fn word_freq(text: &str) -> HashMap<String, usize> {
text.split_whitespace()
.map(str::to_lowercase)
.fold(HashMap::new(), |mut m, w| {
*m.entry(w).or_default() += 1;
m
})
}
""",
"gold": "pass",
"why": "fold over split_whitespace with lowercase keys; executed (rustc): the example, empty "
"input -> {}, and mixed tabs/newlines/repeated spaces all correct."},
# ============================================================ verdict: shell
{"id": "j-sh-find-mtime", "cat": "shell", "kind": "verdict",
"task": "Shell (GNU findutils): delete the regular files under /var/log/app whose names end in "
".log and that were last modified more than 7 days ago. Stay on that filesystem and "
"touch nothing else.",
"candidate": "find /var/log/app -xdev -type f -name '*.log' -mtime -7 -delete",
"gold": "fail",
"why": "-mtime -7 selects files modified LESS than 7 days ago (needs +7); executed (BSD and GNU "
"find): deletes the 1- and 3-day-old logs, keeps the 10- and 30-day-old ones."},
{"id": "j-sh-rm-r", "cat": "shell", "kind": "verdict",
"task": "Bash, in a CI script that runs under `set -e`: remove the directory named in "
"$BUILD_DIR and everything below it. It must never prompt (not even for read-only "
"files) and must not abort the script when the directory doesn't exist yet.",
"candidate": "rm -r -- \"$BUILD_DIR\"",
"gold": "fail",
"why": "without -f, a missing dir is an error (exit 1) that set -e turns into an abort, and rm "
"prompts for write-protected files on a tty; executed: script stops before its next line."},
{"id": "j-sh-top-ips", "cat": "shell", "kind": "verdict",
"task": "Shell: access.log is in nginx's default combined format (the client IP is the first "
"space-separated field). Print the 3 client IPs with the most requests, highest "
"first, one per line as '<count> <ip>'.",
"candidate": "awk '{n[$1]++} END {for (ip in n) print n[ip], ip}' access.log | sort -rn | head -n 3",
"gold": "pass",
"why": "awk tally instead of the usual sort|uniq -c; executed on a 6-IP fixture (BSD and GNU "
"userland): prints '7 ...', '5 ...', '3 ...' in the right order."},
{"id": "j-sh-grep-n", "cat": "shell", "kind": "verdict",
"task": "Shell: print every line of hosts.txt prefixed with its 1-based line number and a "
"colon, e.g. '1:alpha'. Blank lines must be numbered too, and the file's last line "
"may lack a trailing newline but must still be printed.",
"candidate": "grep -n '' hosts.txt",
"gold": "pass",
"why": "the empty pattern matches every line, incl. blank ones and an unterminated last line; "
"executed (BSD and GNU grep): '1:alpha','2:','3:gamma' for a file ending without \\n."},
{"id": "j-sh-grep-c-errexit", "cat": "shell", "kind": "verdict",
"task": "Bash script running under `set -euo pipefail`: store the number of lines in app.log "
"that contain ERROR in a variable `count`, print 'errors: <count>', and carry on with "
"the rest of the script. app.log may contain no ERROR lines at all, in which case it "
"must print 'errors: 0' and continue.",
"candidate": """count=$(grep -c ERROR app.log)
echo "errors: $count"
""",
"gold": "fail",
"why": "grep -c prints 0 but exits 1 on no match, and the assignment takes that status, so "
"errexit kills the script; executed (bash 3.2 and 5.2): nothing printed, exit 1."},
# ============================================================ verdict: sql
{"id": "j-sql-count-bool", "cat": "sql", "kind": "verdict",
"task": "SQL (SQLite or PostgreSQL). Tables: customers(id INTEGER PRIMARY KEY, name TEXT) and "
"orders(id INTEGER PRIMARY KEY, customer_id INTEGER, status TEXT). For every customer "
"who has at least 2 orders with status 'paid', return their id, their name and the "
"number of their paid orders as paid_orders.",
"candidate": """SELECT c.id, c.name, COUNT(o.status = 'paid') AS paid_orders
FROM customers c
JOIN orders o ON o.customer_id = c.id
GROUP BY c.id, c.name
HAVING COUNT(o.status = 'paid') >= 2;
""",
"gold": "fail",
"why": "COUNT counts non-NULL values and false/0 is non-NULL, so it counts all orders; "
"executed (sqlite3 and Postgres 16): a customer with 1 paid + 2 refunded shows up as 3."},
{"id": "j-sql-never-ordered", "cat": "sql", "kind": "verdict",
"task": "SQL (SQLite or PostgreSQL). Tables: customers(id INTEGER PRIMARY KEY, name TEXT) and "
"orders(id INTEGER PRIMARY KEY, customer_id INTEGER NULL, total NUMERIC); "
"customer_id is NULL for guest checkouts, and two customers can share a name. Return "
"the id and name of every customer who has never placed an order.",
"candidate": """SELECT c.id, c.name
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.id, c.name
HAVING COUNT(o.id) = 0;
""",
"gold": "pass",
"why": "anti-join via LEFT JOIN + COUNT of the nullable side; executed (sqlite3 and Postgres "
"16) with guest orders and a duplicate name: returns exactly the 2 order-less customers."},
{"id": "j-sql-latest", "cat": "sql", "kind": "verdict",
"task": "SQL (SQLite or PostgreSQL). Table readings(sensor_id INTEGER, ts TEXT, value REAL); ts "
"is an ISO-8601 'YYYY-MM-DD HH:MM:SS' string and is unique per sensor, but all "
"sensors report on the same schedule, so the same ts appears for many sensors. Return "
"one row per sensor: sensor_id and the value of its most recent reading.",
"candidate": """SELECT r.sensor_id, r.value
FROM readings r
WHERE NOT EXISTS (
SELECT 1 FROM readings newer
WHERE newer.sensor_id = r.sensor_id AND newer.ts > r.ts
);
""",
"gold": "pass",
"why": "correlated NOT EXISTS keeps each sensor's newest row; executed (sqlite3 and Postgres "
"16) on shared timestamps and a sensor with one reading: one correct row per sensor."},
# ============================================================ verdict: logs
{"id": "j-log-ssh-count", "cat": "logs", "kind": "verdict",
"task": "Summarize this /var/log/auth.log excerpt in one or two sentences for the on-call "
"channel. The summary must be faithful: every claim supported by the lines, no "
"invented counts or events.\n\n"
"Oct 11 02:14:03 web1 sshd[30411]: Failed password for root from 203.0.113.7 port 51022 ssh2\n"
"Oct 11 02:14:07 web1 sshd[30411]: Failed password for root from 203.0.113.7 port 51022 ssh2\n"
"Oct 11 02:14:12 web1 sshd[30413]: Failed password for invalid user admin from 203.0.113.7 port 51040 ssh2\n"
"Oct 11 02:14:15 web1 sshd[30415]: Failed password for root from 198.51.100.23 port 40112 ssh2\n"
"Oct 11 02:14:20 web1 sshd[30413]: Connection closed by invalid user admin 203.0.113.7 port 51040 [preauth]\n"
"Oct 11 02:15:41 web1 sshd[30420]: Accepted publickey for deploy from 192.0.2.10 port 60218 ssh2: ED25519 SHA256:kq3VbR0x7Lw2mJbW0mS9a6YtD4c2r1Hk8EzQ5uN1pTo\n"
"Oct 11 02:15:41 web1 sshd[30420]: pam_unix(sshd:session): session opened for user deploy(uid=1001) by (uid=0)",
"candidate": "Between 02:14:03 and 02:14:15, 203.0.113.7 made 4 failed password attempts "
"(against root and the nonexistent user admin) and 198.51.100.23 failed once "
"against root; at 02:15:41 deploy logged in with a public key from 192.0.2.10.",
"gold": "fail",
"why": "203.0.113.7 has 3 failed attempts (2 root + 1 admin), not 4; 4 is the total across both "
"IPs. Everything else is supported."},
{"id": "j-log-oom", "cat": "logs", "kind": "verdict",
"task": "Summarize these journal lines from db1 in one or two sentences for an incident "
"ticket. The summary must be faithful: every claim supported by the lines, no "
"invented counts or events.\n\n"
"Oct 11 03:12:05 db1 kernel: postgres invoked oom-killer: gfp_mask=0x140cca(GFP_HIGHUSER_MOVABLE|__GFP_COMP), order=0, oom_score_adj=0\n"
"Oct 11 03:12:05 db1 kernel: Out of memory: Killed process 2211 (postgres) total-vm:9123456kB, anon-rss:6801232kB, file-rss:0kB, shmem-rss:131072kB, UID:113 pgtables:14212kB oom_score_adj:0\n"
"Oct 11 03:12:05 db1 postgres[2190]: LOG: server process (PID 2211) was terminated by signal 9: Killed\n"
"Oct 11 03:12:05 db1 postgres[2190]: LOG: terminating any other active server processes\n"
"Oct 11 03:12:06 db1 postgres[2190]: LOG: all server processes terminated; reinitializing\n"
"Oct 11 03:12:06 db1 postgres[2230]: LOG: database system was interrupted; last known up at 2026-10-11 03:07:44 UTC\n"
"Oct 11 03:12:07 db1 postgres[2230]: LOG: database system was not properly shut down; automatic recovery in progress\n"
"Oct 11 03:12:09 db1 postgres[2230]: LOG: redo done at 0/5A1C3F8\n"
"Oct 11 03:12:10 db1 postgres[2190]: LOG: database system is ready to accept connections",
"candidate": "03:12:05: the kernel OOM killer SIGKILLed one PostgreSQL backend (PID 2211). The "
"postmaster (PID 2190) stayed up, terminated the other sessions, ran crash "
"recovery and was accepting connections again at 03:12:10, roughly 5 s of outage.",
"gold": "pass",
"why": "each claim maps to a line: OOM kill of 2211 + signal 9, 2190 logs throughout, "
"'terminating any other active server processes', recovery/redo, ready at 03:12:10."},
{"id": "j-log-raid", "cat": "logs", "kind": "verdict",
"task": "Summarize these kernel lines from nas1 in one or two sentences for the hardware log. "
"The summary must be faithful: every claim supported by the lines, no invented "
"counts or events.\n\n"
"Oct 10 04:10:31 nas1 kernel: ata3.00: exception Emask 0x0 SAct 0x40000 SErr 0x0 action 0x0\n"
"Oct 10 04:10:31 nas1 kernel: ata3.00: failed command: READ FPDMA QUEUED\n"
"Oct 10 04:10:31 nas1 kernel: blk_update_request: I/O error, dev sdb, sector 1953520 op 0x0:(READ) flags 0x0 phys_seg 1 prio class 0\n"
"Oct 10 04:10:32 nas1 kernel: md/raid1:md0: Disk failure on sdb1, disabling device.\n"
"Oct 10 04:10:32 nas1 kernel: md/raid1:md0: Operation continuing on 1 devices.\n"
"Oct 10 04:10:40 nas1 kernel: ata3: hard resetting link\n"
"Oct 10 04:10:45 nas1 kernel: ata3: SATA link up 6.0 Gbps (SStatus 133 SControl 300)",
"candidate": "At 04:10:31 a read from sdb failed with an I/O error; a second later md disabled "
"sdb1, leaving the RAID1 array md0 running on one device. The ata3 link was "
"hard-reset and came back up at 04:10:45, but nothing shows sdb1 being re-added "
"or resynced.",
"gold": "pass",
"why": "every claim is in the lines (read I/O error on sdb, md0 disabling sdb1 and continuing "
"on 1 device, ata3 reset/link up); it doesn't claim a rebuild."},
# ============================================================ verdict: config
{"id": "j-cfg-nginx-prefix", "cat": "config", "kind": "verdict",
"task": "nginx: inside an existing server block, add a location that proxies every request "
"under /api/ to the backend at 127.0.0.1:8080 with the /api prefix stripped: a "
"request for /api/users?id=3 must reach the backend as /users?id=3.",
"candidate": """location /api/ {
proxy_pass http://127.0.0.1:8080;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
""",
"gold": "fail",
"why": "proxy_pass without a URI part forwards the original URI unchanged (needs a trailing "
"'/'); executed in nginx 1.27: backend sees /api/users?id=3."},
{"id": "j-cfg-systemd", "cat": "config", "kind": "verdict",
"task": "systemd: write a unit for the long-running program /opt/app/worker. It must start at "
"boot once the network is actually online, be restarted whenever it exits for any "
"reason (including a clean exit with status 0), and wait 5 seconds before each "
"restart.",
"candidate": """[Unit]
Description=app worker
Wants=network-online.target
After=network-online.target
[Service]
ExecStart=/opt/app/worker
Restart=always
RestartSec=5
[Install]
WantedBy=multi-user.target
""",
"gold": "pass",
"why": "per systemd.service(5)/systemd.special(7): Restart=always covers clean exits, "
"RestartSec=5, Wants+After network-online.target, WantedBy for boot (not executed)."},
{"id": "j-cfg-sshd-authmethods", "cat": "config", "kind": "verdict",
"task": "OpenSSH sshd_config: nobody may log in with a password (including keyboard-"
"interactive / PAM password prompts), root may not log in at all by any method, and "
"every other user must still be able to log in with an SSH key. Give the directives "
"to add.",
"candidate": """PermitRootLogin no
AuthenticationMethods publickey
""",
"gold": "pass",
"why": "AuthenticationMethods publickey makes publickey the only method that can complete auth "
"(sshd_config(5)); `sshd -T` parses it, and a loopback sshd with it offers only "
"'(publickey)' vs '(publickey,password,keyboard-interactive)' without it."},
# ============================================================ verdict: answer
{"id": "j-ans-cron-dow", "cat": "answer", "kind": "verdict",
"task": "Answer correctly: on what schedule does the crontab line "
"`30 2 1-7 * 1 /usr/local/sbin/patch-reboot` run with standard Vixie cron / cronie?",
"candidate": "At 02:30 on the first Monday of every month: day-of-month 1-7 restricted to "
"day-of-week 1 (Monday) picks the Monday that falls in the first seven days.",
"gold": "fail",
"why": "crontab(5): when both day fields are restricted the job runs when EITHER matches, i.e. "
"02:30 on days 1-7 of every month AND every Monday."},
{"id": "j-ans-ssh-L", "cat": "answer", "kind": "verdict",
"task": "Answer correctly: what does `ssh -N -L 15432:db.internal:5432 admin@bastion` do?",
"candidate": "It logs in to bastion as admin without running a remote command (-N) and listens "
"on local port 15432 (loopback only, by default). Each connection to that port is "
"carried through the SSH session, and bastion opens a TCP connection to "
"db.internal:5432 (db.internal is resolved by bastion, not by your machine). So "
"`psql -h localhost -p 15432` reaches the database.",
"gold": "pass",
"why": "matches ssh(1) -L/-N and ssh_config(5) GatewayPorts=no default; the forward target is "
"resolved and connected from the server side."},
{"id": "j-ans-cidr", "cat": "answer", "kind": "verdict",
"task": "Answer correctly: in the subnet 10.0.12.0/22, can the address 10.0.13.255 be assigned "
"to a host?",
"candidate": "No. 10.0.13.255 ends in .255, and a .255 address is always the broadcast address "
"of its network, so it can't be given to a host.",
"gold": "fail",
"why": "the /22 spans 10.0.12.0-10.0.15.255; its broadcast is 10.0.15.255 and 10.0.13.255 is an "
"ordinary host (checked with Python ipaddress)."},
# ============================================================ pairwise
{"id": "j-pw-py-intervals", "cat": "code", "kind": "pairwise",
"task": "Python: write `merge(intervals)` that takes a list of [start, end] integer pairs "
"(inclusive, start <= end, in any order) and returns the merged list sorted by start, "
"combining intervals that overlap or share an endpoint: "
"merge([[5, 6], [1, 3], [3, 4]]) == [[1, 4], [5, 6]].",
"a": """def merge(intervals):
out = []
for s, e in sorted(intervals):
if out and s <= out[-1][1]:
out[-1][1] = max(out[-1][1], e)
else:
out.append([s, e])
return out
""",
"b": """def merge(intervals):
out = []
for s, e in sorted(intervals):
if out and s <= out[-1][1]:
out[-1][1] = e
else:
out.append([s, e])
return out
""",
"gold": "a",
"why": "b overwrites the end instead of taking the max; executed: b turns [[1, 10], [2, 3]] "
"into [[1, 3]]; a matches a brute-force reference on 3000 random inputs."},
{"id": "j-pw-go-countlines", "cat": "code", "kind": "pairwise",
"task": "Go: write `func CountLines(path string) (int, error)` that returns the number of lines "
"in a text file, where a final line without a trailing newline still counts. Some "
"lines in these files are over 1 MB long. Return an error if reading fails.",
"a": """func CountLines(path string) (int, error) {
f, err := os.Open(path)
if err != nil {
return 0, err
}
defer f.Close()
sc := bufio.NewScanner(f)
n := 0
for sc.Scan() {
n++
}
return n, nil
}
""",
"b": """func CountLines(path string) (int, error) {
f, err := os.Open(path)
if err != nil {
return 0, err
}
defer f.Close()
r := bufio.NewReader(f)
n := 0
for {
line, err := r.ReadString('\\n')
if len(line) > 0 {
n++
}
if err == io.EOF {
return n, nil
}
if err != nil {
return n, err
}
}
}
""",
"gold": "b",
"why": "Scanner's default 64 KiB token limit stops at the long line and a never checks "
"sc.Err(); executed: 3 lines with a 2 MB middle line -> a returns (1, nil), b returns 3."},
{"id": "j-pw-sh-ssh-loop", "cat": "shell", "kind": "pairwise",
"task": "Bash: hosts.txt lists one hostname per line (every line ends with a newline). For each "
"host, run `uptime` on it over SSH (key auth is already set up) and print the "
"result, so you get one uptime line per host.",
"a": """while read -r host; do
printf '%s: ' "$host"
ssh "$host" uptime
done < hosts.txt
""",
"b": """while read -r host; do
printf '%s: ' "$host"
ssh -n "$host" uptime
done < hosts.txt
""",
"gold": "b",
"why": "without -n ssh reads (and forwards) the loop's stdin, eating the remaining hostnames "
"(BashFAQ 89, ssh(1) -n); reproduced with a stdin-reading ssh stub: a does 1 host, b all 3."},
{"id": "j-pw-sh-distinct", "cat": "shell", "kind": "pairwise",
"task": "Bash: data.tsv is tab-separated, has no header, and its rows are in no particular "
"order. Print each distinct value of the third column exactly once.",
"a": "sort -t$'\\t' -k3,3 -u data.tsv | cut -f3",
"b": "awk -F'\\t' '{print $3}' data.tsv | uniq",
"gold": "a",
"why": "uniq only collapses ADJACENT duplicates; a's sort -u on key 3 keeps one row per key. "
"Executed (BSD and GNU): b repeats values from unsorted rows, a prints each once."},
{"id": "j-pw-sql-join-key", "cat": "sql", "kind": "pairwise",
"task": "SQL (SQLite or PostgreSQL). Table deployments(service TEXT, deployed_at TEXT, "
"version TEXT). Deployments go out in batches, so many services share the same "
"deployed_at value; deployed_at is unique per service. Return each service with the "
"version it is currently running (the version from its most recent deployment).",
"a": """SELECT d.service, d.version
FROM deployments d
JOIN (SELECT service, MAX(deployed_at) AS latest
FROM deployments GROUP BY service) m
ON d.deployed_at = m.latest;
""",
"b": """SELECT d.service, d.version
FROM deployments d
JOIN (SELECT service, MAX(deployed_at) AS latest
FROM deployments GROUP BY service) m
ON d.service = m.service AND d.deployed_at = m.latest;
""",
"gold": "b",
"why": "a's join lacks the service key, so a service's older row matches another service's "
"latest timestamp; executed (sqlite3 and Postgres 16): a returns 6 rows incl. a stale "
"version and duplicates, b the correct 3."},
{"id": "j-pw-log-backup", "cat": "logs", "kind": "pairwise",
"task": "Summarize these lines from backup1 for the morning report in two sentences or fewer. "
"Be faithful: every claim supported by the lines, no invented events.\n\n"
"Oct 12 02:00:01 backup1 CRON[8812]: (root) CMD (/usr/local/sbin/nightly-backup.sh)\n"
"Oct 12 02:00:02 backup1 nightly-backup[8813]: starting dump of 3 databases to /var/backups/db\n"
"Oct 12 02:04:47 backup1 nightly-backup[8813]: dumped crm (2.1G)\n"
"Oct 12 02:05:13 backup1 nightly-backup[8813]: pg_dump: error: could not write to output file: No space left on device\n"
"Oct 12 02:05:13 backup1 nightly-backup[8813]: FAILED dumping billing; aborting run (exit 1)\n"
"Oct 12 02:30:00 backup1 CRON[9120]: (root) CMD (/usr/local/sbin/prune-old-backups.sh --keep 7)\n"
"Oct 12 02:30:04 backup1 prune-old-backups[9121]: removed 4 archives, freed 11.3G on /var/backups",
"a": "The 02:00 nightly backup dumped crm (2.1G), then aborted at 02:05 when the billing dump "
"hit 'No space left on device', so the third database was never dumped. The 02:30 prune "
"freed 11.3G on /var/backups, but nothing shows the backup being re-run.",
"b": "The 02:00 nightly backup dumped crm (2.1G) and then failed on billing at 02:05 with 'No "
"space left on device'. After the 02:30 prune freed 11.3G on /var/backups, the backup was "
"re-run and completed successfully.",
"gold": "a",
"why": "b invents a re-run and success; no line after 02:30:04 mentions the backup. a's claims "
"(incl. third DB never dumped: 3 planned, 1 done, run aborted) are all supported."},
{"id": "j-pw-cfg-yaml-versions", "cat": "config", "kind": "pairwise",
"task": "YAML for a CI config that is read with a YAML 1.1 loader (e.g. PyYAML). The job matrix "
"must list the Python versions 3.9, 3.10 and 3.11, and the CI tool needs each version "
"as a string with exactly those characters.",
"a": """matrix:
python: [3.9, 3.10, 3.11]
""",
"b": """matrix:
python: ["3.9", "3.10", "3.11"]
""",
"gold": "b",
"why": "unquoted versions load as floats and 3.10 becomes 3.1; executed with PyYAML 6: a -> "
"[3.9, 3.1, 3.11] (floats), b -> ['3.9', '3.10', '3.11']."},
{"id": "j-pw-ans-sudo-redirect", "cat": "answer", "kind": "pairwise",
"task": "Answer correctly: why does `sudo echo 'nameserver 10.0.0.53' > /etc/resolv.conf` fail "
"with 'Permission denied' when run by a normal user, and what is a working one-line "
"replacement?",
"a": "The `>` redirection is set up by your own unprivileged shell before sudo even runs, so "
"the file is opened as you. Let a root process open it instead: "
"`echo 'nameserver 10.0.0.53' | sudo tee /etc/resolv.conf >/dev/null`.",
"b": "echo is a shell builtin, and sudo can't elevate builtins, so the write runs without root. "
"Call the external binary instead: "
"`sudo /bin/echo 'nameserver 10.0.0.53' > /etc/resolv.conf`.",
"gold": "a",
"why": "b's fix still redirects in the user's shell, so it fails identically (and sudo already "
"runs /bin/echo). Shown: `nosuchcmd > f` creates f before the command runs."},
]
RERANK = [
# ============================================================ code
{"id": "k-code-backoff", "cat": "code",
"query": "Python helper that retries a flaky network call, waiting longer after each failure "
"(exponential backoff)",
"candidates": {
"c1": """def ewma(values, alpha=0.3):
\"\"\"Exponentially weighted moving average of request latencies.\"\"\"
avg = None
for v in values:
avg = v if avg is None else alpha * v + (1 - alpha) * avg
return avg""",
"c2": """def retry(fn, attempts=3, delay=2.0):
for i in range(attempts):
try:
return fn()
except (ConnectionError, TimeoutError):
if i == attempts - 1:
raise
time.sleep(delay)""",
"c3": """def fetch_json(url, timeout=10):
\"\"\"Network call to the inventory API. Raises on HTTP failure.\"\"\"
req = urllib.request.Request(url, headers={"Accept": "application/json"})
with urllib.request.urlopen(req, timeout=timeout) as resp:
return json.load(resp)""",
"c4": """def call_patiently(op, tries=6, base=0.5, cap=30.0):
for n in range(tries):
try:
return op()
except OSError:
if n == tries - 1:
raise
time.sleep(min(cap, base * 2 ** n) * random.uniform(0.5, 1.0))""",
"c5": """def backoff_delays(base=1.0, factor=2.0, limit=5):
\"\"\"Delay schedule [1, 2, 4, 8, 16] used by the job-runner config.\"\"\"
return [base * factor ** i for i in range(limit)]""",
"c6": """def record_failure(stats, host):
\"\"\"Count consecutive failed calls per host; reset on success.\"\"\"
stats[host] = stats.get(host, 0) + 1
if stats[host] >= 5:
log.warning("host %s failing repeatedly (%d)", host, stats[host])""",
"c7": """class TokenBucket:
def __init__(self, rate, burst):
self.rate, self.tokens, self.burst = rate, burst, burst
self.t = time.monotonic()
def take(self):
now = time.monotonic()
self.tokens = min(self.burst, self.tokens + (now - self.t) * self.rate)
self.t = now
if self.tokens >= 1:
self.tokens -= 1
return True
return False""",
},
"relevance": {"c4": 3, "c2": 2, "c5": 1},
"why": "c4 retries on OSError (covers connection/timeout errors) with capped, jittered "
"base*2**n sleeps, without saying 'retry' or 'backoff'; c2 retries at a fixed delay."},
{"id": "k-code-duration", "cat": "code",
"query": "Python function that parses a duration string like '1h30m' or '45s' into a number of "
"seconds",
"candidates": {
"c1": """def humanize(seconds):
h, rem = divmod(int(seconds), 3600)
m, s = divmod(rem, 60)
return "".join(f"{v}{u}" for v, u in ((h, "h"), (m, "m"), (s, "s")) if v) or "0s\"""",
"c2": """def parse_ts(s):
\"\"\"Parse an ISO-8601 timestamp string like '2026-10-12T08:30:00Z'.\"\"\"
return datetime.strptime(s, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc)""",
"c3": """def clock_to_seconds(text):
\"\"\"'01:30:00' -> 5400. Accepts MM:SS too.\"\"\"
total = 0
for p in text.split(":"):
total = total * 60 + int(p)
return total""",
"c4": """@dataclass
class JobDuration:
\"\"\"Duration of a finished job, in seconds, as stored in the results table.\"\"\"
job_id: str
seconds: float
def __str__(self):
return f"{self.job_id}: {self.seconds:.1f}s\"""",
"c5": r"""_UNIT = {"d": 86400, "h": 3600, "m": 60, "s": 1}
def to_secs(spec):
total, pos = 0, 0
for m in re.finditer(r"(\d+)([dhms])", spec):
if m.start() != pos:
raise ValueError(f"bad spec: {spec!r}")
total += int(m.group(1)) * _UNIT[m.group(2)]
pos = m.end()
if not spec or pos != len(spec):
raise ValueError(f"bad spec: {spec!r}")
return total""",
"c6": """def sleep_seconds(n):
\"\"\"Sleep for n seconds, logging the wait.\"\"\"
log.debug("sleeping %ss", n)
time.sleep(n)""",
"c7": """parser.add_argument("--timeout", type=int, default=30,
help="request timeout in seconds, e.g. 45")""",
},
"relevance": {"c5": 3, "c3": 2, "c1": 1},
"why": "c5 parses '1h30m'-style specs (d/h/m/s units) into seconds; c3 parses clock-style "
"durations; c1 is the inverse formatter; c2/c4/c6/c7 only share words."},
{"id": "k-code-go-cancel", "cat": "code",
"query": "Go HTTP handler: stop the expensive work as soon as the client disconnects",
"candidates": {
"c1": """var client = &http.Client{
Timeout: 10 * time.Second,
Transport: &http.Transport{MaxIdleConnsPerHost: 16},
}""",
"c2": """func report(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
rows, err := db.QueryContext(ctx, heavyReportSQL)
if err != nil {
if errors.Is(err, context.Canceled) {
return // caller went away
}
http.Error(w, err.Error(), 500)
return
}
defer rows.Close()
for rows.Next() {
if ctx.Err() != nil {
return
}
// ... aggregate row
}
}""",
"c3": """sig := make(chan os.Signal, 1)
signal.Notify(sig, os.Interrupt, syscall.SIGTERM)
<-sig
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
srv.Shutdown(ctx)""",
"c4": """func logClient(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("client %s %s %s", r.RemoteAddr, r.Method, r.URL.Path)
next.ServeHTTP(w, r)
})
}""",
"c5": """ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
req, _ := http.NewRequestWithContext(ctx, "GET", upstreamURL, nil)
resp, err := http.DefaultClient.Do(req)""",
"c6": """func worker(jobs <-chan Job, done <-chan struct{}) {
for {
select {
case <-done:
return
case j := <-jobs:
process(j)
}
}
}""",
"c7": """srv := &http.Server{
Addr: ":8080",
ReadTimeout: 5 * time.Second,
WriteTimeout: 30 * time.Second,
Handler: mux,
}""",
},
"relevance": {"c2": 3, "c6": 2, "c5": 1},
"why": "c2 threads r.Context() (canceled when the client goes away) into the query and the row "
"loop; c6 is the generic done-channel pattern; c5 uses a context only for a timeout."},
{"id": "k-code-rust-from", "cat": "code",
"query": "Rust: make `?` convert std::io::Error into my own error enum automatically",
"candidates": {
"c1": """impl fmt::Display for AppError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
AppError::Io(e) => write!(f, "io error: {e}"),
AppError::Config(msg) => write!(f, "bad config: {msg}"),
}
}
}""",
"c2": """let text = fs::read_to_string(&path).map_err(AppError::Io)?;""",
"c3": """impl From<io::Error> for AppError {
fn from(e: io::Error) -> Self {
AppError::Io(e)
}
}""",
"c4": """match fs::remove_file(&lock) {
Ok(()) => {}
Err(e) if e.kind() == io::ErrorKind::NotFound => {}
Err(e) => return Err(e),
}""",
"c5": """let cfg = fs::read_to_string("app.toml")
.unwrap_or_else(|e| panic!("cannot read app.toml: {e}"));""",
"c6": """#[derive(Debug, thiserror::Error)]
enum ParseError {
#[error("bad number: {0}")]
Num(#[from] std::num::ParseIntError),
}""",
"c7": """fn main() -> Result<(), Box<dyn std::error::Error>> {
let cfg = std::fs::read_to_string("app.toml")?;
run(&cfg)?;
Ok(())
}""",
},
"relevance": {"c3": 3, "c2": 2, "c6": 1, "c7": 1},
"why": "`?` calls From::from on the error, so c3's impl is exactly what makes it automatic; c2 "
"converts by hand per call site; c6 shows #[from] for a different error type."},
# ============================================================ logs
{"id": "k-log-ssh-accept", "cat": "logs",
"query": "the auth.log line showing that user deploy successfully logged in over SSH",
"candidates": {
"c1": "Oct 12 07:58:12 web1 sshd[4410]: Failed password for deploy from 198.51.100.4 port 52101 ssh2",
"c2": "Oct 12 07:58:20 web1 sshd[4412]: pam_unix(sshd:session): session opened for user deploy(uid=1001) by (uid=0)",
"c3": "Oct 12 07:58:19 web1 sshd[4412]: Accepted publickey for deploy from 198.51.100.4 port 52114 ssh2: ED25519 SHA256:3fV0kq1oZ7c9TQ8xg2Lw1mJbW0mS9a6YtD4c2r1Hk8E",
"c4": "Oct 12 08:02:44 web1 sshd[4460]: Accepted publickey for backup from 10.0.0.12 port 41980 ssh2: RSA SHA256:Qm9vZ2xlTm90QVJlYWxLZXlKdXN0RmFrZURhdGExMjM",
"c5": "Oct 12 07:58:20 web1 systemd-logind[612]: New session 17 of user deploy.",
"c6": "Oct 12 07:57:03 web1 sshd[4398]: Invalid user deplo from 203.0.113.50 port 40022",
"c7": "Oct 12 07:58:12 web1 sshd[4410]: Connection closed by authenticating user deploy 198.51.100.4 port 52101 [preauth]",
"c8": "Oct 12 08:41:55 web1 sshd[4412]: pam_unix(sshd:session): session closed for user deploy",
},
"relevance": {"c3": 3, "c2": 2, "c5": 2, "c8": 1},
"why": "sshd's 'Accepted publickey for deploy' is the authentication success itself; the PAM / "
"logind session lines follow from it; c4 is a success for a different user."},
{"id": "k-log-oom", "cat": "logs",
"query": "why was the postgres process killed at 03:12?",
"candidates": {
"c1": "Oct 11 03:12:05 db1 postgres[2190]: LOG: server process (PID 2211) was terminated by signal 9: Killed",
"c2": "Oct 11 03:12:05 db1 kernel: Out of memory: Killed process 2211 (postgres) total-vm:9123456kB, anon-rss:6801232kB, file-rss:0kB, shmem-rss:131072kB, UID:113 pgtables:14212kB oom_score_adj:0",
"c3": "Oct 10 22:15:00 db1 sudo: user : TTY=pts/1 ; PWD=/home/user ; USER=root ; COMMAND=/usr/bin/kill -TERM 1874",
"c4": "Oct 11 03:12:05 db1 kernel: postgres invoked oom-killer: gfp_mask=0x140cca(GFP_HIGHUSER_MOVABLE|__GFP_COMP), order=0, oom_score_adj=0",
"c5": "Oct 11 03:12:10 db1 postgres[2190]: LOG: database system is ready to accept connections",
"c6": "Oct 11 01:00:00 db1 postgres[2190]: LOG: checkpoint complete: wrote 1832 buffers (11.2%); 0 WAL file(s) added, 0 removed, 1 recycled",
"c7": "Oct 11 03:11:58 db1 kernel: nvme0n1: I/O 912 QID 4 timeout, completion polled",
"c8": "Oct 11 03:12:05 db1 postgres[2190]: LOG: terminating any other active server processes",
},
"relevance": {"c2": 3, "c1": 2, "c4": 2, "c8": 1},
"why": "c2 names the killer and the reason (kernel OOM, ~6.5 GiB anon RSS, PID 2211); c1 shows "
"only the signal; c4 shows the OOM killer starting, not who it killed."},
{"id": "k-log-tls", "cat": "logs",
"query": "why are the billing service's outbound API calls failing since this morning?",
"candidates": {
"c1": "2026-10-12T06:00:03Z billing INFO scheduler: starting invoice run batch=2026-10-12",
"c2": "2026-10-12T02:14:51Z certbot INFO renewed certificate for billing.internal.example (expires 2027-01-10)",
"c3": "2026-10-12T06:00:04Z billing WARN payments: retrying POST /v2/charges (attempt 2/5) in 2s",
"c4": "2026-10-11T23:41:10Z gateway ERROR upstream billing: connect() failed (111: Connection refused) while connecting to upstream",
"c5": "2026-10-12T06:00:04Z billing ERROR payments: POST https://api.payments.example/v2/charges failed: x509: certificate has expired or is not yet valid: current time 2026-10-12T06:00:04Z is after 2026-10-12T00:00:00Z",
"c6": "2026-10-11T09:12:30Z billing WARN payments: server certificate for api.payments.example expires at 2026-10-12T00:00:00Z (in 14h47m)",
"c7": "2026-10-12T06:00:31Z billing ERROR invoices: 214 invoices not charged; will retry next run",
"c8": "2026-10-12T06:00:04Z billing DEBUG http: dial tcp 10.0.4.17:443 ok (12ms)",
},
"relevance": {"c5": 3, "c6": 2, "c3": 1, "c7": 1, "c8": 1},
"why": "c5 is the failing outbound call with its cause (the payment API's cert expired at "
"midnight); c6 predicted it; c2 is our own cert renewing fine; c4 is inbound, yesterday."},
# ============================================================ docs
{"id": "k-doc-rsync-mirror", "cat": "docs",
"query": "rsync option to make the destination an exact mirror, removing files there that no "
"longer exist in the source",
"candidates": {
"c1": "--remove-source-files After a file has been transferred successfully, delete it from "
"the sending side (directories are left in place). Useful for moving files rather than "
"copying them.",
"c2": "--existing Skip creating files on the receiver that do not already exist there; only "
"update files the destination already has.",
"c3": "--delete Delete extraneous files from the receiving side, i.e. files that are not "
"present on the sending side, but only in directories being synchronized. Use with "
"-r/-a, and try --dry-run first: it removes data at the destination.",
"c4": "--delete-before, --delete-during, --delete-delay, --delete-after Choose when "
"receiver-side deletions happen relative to the transfer (before it, incrementally, or "
"at the end). They change timing and memory use, not which files get deleted.",
"c5": "--ignore-existing Skip updating files that already exist on the destination; new "
"files are still created.",
"c6": "-a, --archive Archive mode: recurse into directories and preserve symlinks, "
"permissions, modification times, group, owner and device files; equivalent to "
"-rlptgoD. It does not delete anything on the receiver.",
"c7": "--backup When a destination file would be replaced or deleted, rename the old copy "
"with a ~ suffix (see --suffix, --backup-dir) instead of discarding it.",
"c8": "--max-delete=NUM Do not delete more than NUM files or directories in one run; a "
"safety cap for transfers that delete.",
},
"relevance": {"c3": 3, "c4": 2, "c6": 1, "c8": 1},
"why": "--delete is the option that removes receiver files absent from the source; c4 only "
"tunes its timing; c1 removes from the SOURCE (lexical trap)."},
{"id": "k-doc-git-uncommit", "cat": "docs",
"query": "undo my last git commit but keep its changes in my working files",
"candidates": {
"c1": "git restore [--staged] <pathspec> Restore specified paths in the working tree from a "
"restore source (the index by default). With --staged, restore the index instead.",
"c2": "git revert <commit> Create a new commit that reverses the changes introduced by "
"<commit>. The original commit stays in history; requires a clean working tree.",
"c3": "git reset --hard <commit> Resets the index and working tree. Any changes to tracked "
"files in the working tree since <commit> are discarded.",
"c4": "git commit --amend Replace the tip of the current branch with a new commit built from "
"the current index; use it to fix the last commit's message or add forgotten files.",
"c5": "git stash push Save your local modifications to a new stash entry and roll the working "
"tree and index back to HEAD.",
"c6": "git reset [<commit>] (default --mixed mode) Resets the index to <commit> but not the "
"working tree: changed files are preserved but not marked for commit.",
"c7": "git reset --soft HEAD~1 Moves the branch back one commit without touching the index "
"or the working tree, so the undone commit's changes stay staged and ready to commit "
"again. (--mixed, the default, also keeps the files but unstages them.)",
"c8": "git reflog Shows where HEAD and branch tips have pointed recently, so commits that "
"were reset away can be found and recovered.",
},
"relevance": {"c7": 3, "c6": 2, "c2": 1, "c4": 1, "c8": 1},
"why": "c7 is exactly 'drop the last commit, keep its changes'; c6 is the general mixed reset "
"without the HEAD~1 target; c3 shares 'reset'/'working tree' but discards the changes."},
{"id": "k-doc-systemd-env", "cat": "docs",
"query": "set an environment variable for one systemd service without editing the unit file "
"that the package shipped",
"candidates": {
"c1": "/etc/environment Read by pam_env at login for user sessions; KEY=value lines. It "
"affects login shells and desktop sessions.",
"c2": "Environment= Sets environment variables for executed processes. Takes a space-"
"separated list of assignments, e.g. Environment=\"ONE=one\" \"TWO=two two\". May be "
"given more than once.",
"c3": "systemctl set-environment VAR=value Sets a variable in the service manager's own "
"environment; it is inherited by units started afterwards and is lost on reboot.",
"c4": "systemctl edit UNIT Opens an editor on a drop-in /etc/systemd/system/UNIT.d/"
"override.conf. Settings there are merged over the vendor unit, survive package "
"upgrades, and the manager reloads on save. Put [Service] and Environment=LOG_LEVEL="
"debug in it, then restart UNIT.",
"c5": "export VAR=value in ~/.bashrc Makes VAR available to interactive shells started by "
"that user.",
"c6": "EnvironmentFile= Like Environment=, but reads the variables from a text file; a "
"leading '-' on the path makes a missing file non-fatal.",
"c7": "systemctl daemon-reload Reload the systemd manager configuration: rerun generators "
"and reload all unit files.",
"c8": "systemctl show -p Environment UNIT Print the environment variables currently "
"configured for UNIT.",
},
"relevance": {"c4": 3, "c2": 2, "c6": 2, "c3": 1, "c7": 1, "c8": 1},
"why": "a drop-in via systemctl edit is the per-service, upgrade-safe way; c2/c6 are the "
"directives but not where to put them; c1/c5 never reach services."},
# ============================================================ commands
{"id": "k-cmd-port", "cat": "commands",
"query": "which process is listening on TCP port 8080 on this Linux box",
"candidates": {
"c1": "curl -sI http://127.0.0.1:8080/",
"c2": "sudo ss -ltnp 'sport = :8080'",
"c3": "sudo lsof -i :8080",
"c4": "nc -l 8080",
"c5": "grep -i ':1F90 ' /proc/net/tcp",
"c6": "sudo netstat -tlnp | grep 8080",
"c7": "sudo iptables -A INPUT -p tcp --dport 8080 -j ACCEPT",
"c8": "ss -s",
},
"relevance": {"c2": 3, "c3": 2, "c6": 2, "c5": 1},
"why": "c2 filters listening TCP sockets on exactly port 8080 and shows the owning process; c3 "
"also lists clients/UDP; c6's grep can hit 18080; c5 shows the socket but no process."},
{"id": "k-cmd-bigdirs", "cat": "commands",
"query": "find which directories under /var are using the most space",
"candidates": {
"c1": "df -h /var",
"c2": "sudo find /var -xdev -type f -size +500M -exec ls -lh {} +",
"c3": "du -sh /var",
"c4": "ls -lS /var",
"c5": "sudo du -xh --max-depth=2 /var 2>/dev/null | sort -rh | head -n 20",
"c6": "sudo du -sh /var/*",
"c7": "sudo lsof +L1",
"c8": "journalctl --disk-usage",
},
"relevance": {"c5": 3, "c6": 2, "c2": 1, "c3": 1, "c8": 1},
"why": "c5 sizes directories two levels down and sorts them largest first; c6 is unsorted, "
"top level only; c1 and c4 share 'size' semantics but say nothing per directory."},
{"id": "k-cmd-tar-list", "cat": "commands",
"query": "see the list of files inside backup.tar.gz without unpacking it",
"candidates": {
"c1": "tar -tzvf backup.tar.gz",
"c2": "tar -xzvf backup.tar.gz",
"c3": "gzip -l backup.tar.gz",
"c4": "tar -tzf backup.tar.gz | grep '^etc/'",
"c5": "zcat backup.tar.gz | head -c 512",
"c6": "tar -czf backup.tar.gz /etc",
"c7": "mkdir /tmp/peek && tar -xzf backup.tar.gz -C /tmp/peek && ls -R /tmp/peek",
"c8": "unzip -l backup.tar.gz",
},
"relevance": {"c1": 3, "c4": 2, "c7": 1},
"why": "-t lists the archive without extracting; c4 lists only etc/; c7 gets a listing by "
"unpacking; c3 'lists' only gzip sizes, c2 extracts, c6 overwrites the archive."},
# ============================================================ errors
{"id": "k-err-modnotfound", "cat": "errors",
"query": "ModuleNotFoundError: No module named 'yaml' when I run my script with python3",
"candidates": {
"c1": "yaml.scanner.ScannerError: mapping values are not allowed here. That's a YAML syntax "
"problem: usually a missing space after a colon or bad indentation in the .yml file.",
"c2": "The importable module is called yaml but the PyPI distribution is PyYAML. Install it "
"into the interpreter that runs the script: `python3 -m pip install PyYAML` (or the "
"distro package python3-yaml).",
"c3": "ImportError: attempted relative import with no known parent package. Run it as "
"`python -m package.module` from the project root instead of executing the file "
"directly.",
"c4": "ModuleNotFoundError just means the import system searched every entry of sys.path "
"and found nothing; print sys.path to see where it looked.",
"c5": "You probably installed it into a different interpreter or virtualenv. Compare `which "
"python3` with the interpreter pip belongs to (`pip --version`) and activate the right "
"venv.",
"c6": "AttributeError: module 'yaml' has no attribute 'FullLoader'. Your PyYAML predates 5.1; "
"upgrade it.",
"c7": "To read YAML in Go, add gopkg.in/yaml.v3 to go.mod and call yaml.Unmarshal.",
},
"relevance": {"c2": 3, "c5": 2, "c4": 1},
"why": "the module 'yaml' ships in the PyYAML distribution, installed via the same python3; c5 "
"covers the wrong-interpreter case; c1/c6/c7 share 'yaml' but are other problems."},
{"id": "k-err-nilmap", "cat": "errors",
"query": "Go program crashes with: panic: assignment to entry in nil map",
"candidates": {
"c1": "fatal error: concurrent map writes. Two goroutines wrote the same map at once; guard "
"it with a sync.Mutex or use sync.Map.",
"c2": "panic: runtime error: invalid memory address or nil pointer dereference. You "
"dereferenced a nil pointer; check for nil before using it.",
"c3": "Struct fields of map type start out nil. If your type has `counts map[string]int`, "
"give it a constructor that sets `counts: make(map[string]int)` before anything writes "
"to it.",
"c4": "panic: runtime error: index out of range [3] with length 3. A slice index is past the "
"end; check len() first.",
"c5": "A map declared with `var m map[string]int` is nil: reading from it returns zero values, "
"but writing to it panics. Allocate it first with `m = make(map[string]int)` or a "
"literal `map[string]int{}`.",
"c6": "The zero value of a map type is nil; len() of a nil map is 0 and ranging over it does "
"nothing.",
"c7": "invalid operation: cannot index m (variable of type *map[string]int). You're indexing "
"a pointer to a map; dereference it with (*m)[k].",
},
"relevance": {"c5": 3, "c3": 2, "c6": 1},
"why": "c5 explains the panic (writing to a nil map) and the fix (make/literal); c3 is the same "
"fix for struct fields only; c1/c2 share 'map'/'nil'/'panic' but are other errors."},
{"id": "k-err-502-refused", "cat": "errors",
"query": "nginx error.log says 'connect() failed (111: Connection refused) while connecting to "
"upstream' and clients get 502 Bad Gateway",
"candidates": {
"c1": "upstream timed out (110: Connection timed out) while reading response header from "
"upstream: the backend accepted the connection but answered too slowly; raise "
"proxy_read_timeout or fix the slow endpoint.",
"c2": "connect() to 127.0.0.1:8000 failed (13: Permission denied) while connecting to "
"upstream: on SELinux hosts nginx may not open network connections; run `setsebool -P "
"httpd_can_network_connect 1`.",
"c3": "A 502 Bad Gateway means nginx could not get a valid response from the upstream; the "
"specific reason is in nginx's error.log.",
"c4": "client intended to send too large body: raise client_max_body_size (default 1m); "
"clients get 413.",
"c5": "Check that the app's service is actually running (`systemctl status app`); if it "
"crashed on start, nginx has nothing to connect to.",
"c6": "Errno 111 means nothing accepted the connection at the upstream address nginx was "
"given: the app is down, crashed on start, or listens on another port or address (e.g. "
"::1 vs 127.0.0.1). Compare the proxy_pass target with `ss -ltnp`, then read the app's "
"own logs.",
"c7": "no live upstreams while connecting to upstream: every server in the upstream block is "
"currently marked failed; see max_fails and fail_timeout.",
"c8": "If the backend listens on a Unix socket, proxy_pass must name it (proxy_pass "
"http://unix:/run/app.sock;) and the path must match the socket the app creates.",
},
"relevance": {"c6": 3, "c5": 2, "c3": 1, "c7": 1, "c8": 1},
"why": "c6 explains errno 111 and how to find which cause applies; c5 covers one cause; c1/c2 "
"share 'connect()'/'upstream' but are errno 110/13 with different fixes."},
]