llm-bench

"""SQL (SQLite): a backup-monitoring DB. Views fold job history into an RPO verdict per host and a
maintenance view expands host/site windows into per-host suppression rows. v_maintenance_now
selects w.host_id, which is NULL for every row a site window expands to, so rpo_alert's
`NOT IN (SELECT host_id ...)` sees a NULL and the whole alert comes back empty. Patching the
alert (NOT EXISTS, or filtering NULLs out of the subquery) un-suppresses the site's hosts; the
fix is in the view."""
import re

ITEM_ID = "sql-backup-rpo"
LANG = "sql"
TOOL = "python3"

PROJECT = {
"schema.sql": '''-- Backup monitoring. All timestamps are UTC text 'YYYY-MM-DD HH:MM:SS'.
PRAGMA foreign_keys = ON;

CREATE TABLE sites (
    id    INTEGER PRIMARY KEY,
    code  TEXT NOT NULL UNIQUE,
    name  TEXT NOT NULL
);

CREATE TABLE hosts (
    id          INTEGER PRIMARY KEY,
    hostname    TEXT NOT NULL UNIQUE,
    site_id     INTEGER NOT NULL REFERENCES sites(id),
    tier        TEXT NOT NULL CHECK (tier IN ('gold', 'silver', 'bronze')),
    retired_at  TEXT            -- NULL while in service; retired hosts drop out of every report
);

-- Recovery point objective per tier: the newest good backup may be at most this old.
CREATE TABLE rpo_policy (
    tier           TEXT PRIMARY KEY,
    max_age_hours  INTEGER NOT NULL
);

-- One row per backup job as reported by the agents. 'warning' means the job completed but
-- skipped some files (open handles); it still counts as a good backup. 'running' jobs have no
-- finished_at yet.
CREATE TABLE backup_jobs (
    id             INTEGER PRIMARY KEY,
    host_id        INTEGER NOT NULL REFERENCES hosts(id),
    started_at     TEXT NOT NULL,
    finished_at    TEXT,
    status         TEXT NOT NULL CHECK (status IN ('running', 'success', 'warning', 'failed')),
    bytes_written  INTEGER
);

-- Planned work during which backup alerts are suppressed. A window targets exactly one host
-- (host_id set) or a whole site (site_id set). It is active while starts_at <= now < ends_at.
CREATE TABLE maintenance_windows (
    id         INTEGER PRIMARY KEY,
    host_id    INTEGER REFERENCES hosts(id),
    site_id    INTEGER REFERENCES sites(id),
    starts_at  TEXT NOT NULL,
    ends_at    TEXT NOT NULL,
    reason     TEXT NOT NULL,
    CHECK ((host_id IS NULL) <> (site_id IS NULL))
);

-- The instant every view and report is evaluated at (exactly one row). The nightly job sets it
-- to the run time; tests pin it.
CREATE TABLE report_clock (
    as_of  TEXT NOT NULL
);
''',

"views/10_job_runs.sql": '''-- v_job_runs: finished jobs, one row per job, outcome folded to good (1) / bad (0).
CREATE VIEW v_job_runs AS
SELECT
    j.id                                    AS job_id,
    j.host_id,
    j.started_at,
    j.finished_at,
    j.status,
    j.status IN ('success', 'warning')      AS good,
    COALESCE(j.bytes_written, 0)            AS bytes_written
FROM backup_jobs j
WHERE j.finished_at IS NOT NULL;

-- v_last_good: one row per in-service host with its newest good job; the job columns are NULL
-- when the host has never had a good backup. Ties on finished_at go to the higher job id.
CREATE VIEW v_last_good AS
SELECT
    h.id               AS host_id,
    r.job_id,
    r.finished_at      AS last_good_at,
    r.bytes_written    AS last_good_bytes
FROM hosts h
LEFT JOIN v_job_runs r
  ON r.job_id = (
       SELECT r2.job_id
       FROM v_job_runs r2
       WHERE r2.host_id = h.id AND r2.good
       ORDER BY r2.finished_at DESC, r2.job_id DESC
       LIMIT 1)
WHERE h.retired_at IS NULL;
''',

"views/20_host_state.sql": '''-- v_host_state: RPO verdict per in-service host as of report_clock.as_of.
--   never  no good backup on record
--   stale  newest good backup is older than the tier's max_age_hours
--   ok     otherwise
-- age_hours is NULL for 'never', otherwise rounded to one decimal.
CREATE VIEW v_host_state AS
SELECT
    h.id                AS host_id,
    h.hostname,
    h.site_id,
    s.code              AS site,
    h.tier,
    lg.last_good_at,
    lg.last_good_bytes,
    ROUND((julianday(c.as_of) - julianday(lg.last_good_at)) * 24, 1) AS age_hours,
    CASE
        WHEN lg.last_good_at IS NULL THEN 'never'
        WHEN (julianday(c.as_of) - julianday(lg.last_good_at)) * 24 > p.max_age_hours THEN 'stale'
        ELSE 'ok'
    END                 AS state
FROM v_last_good lg
JOIN hosts h       ON h.id = lg.host_id
JOIN sites s       ON s.id = h.site_id
JOIN rpo_policy p  ON p.tier = h.tier
CROSS JOIN report_clock c;
''',

"views/30_maintenance_now.sql": '''-- v_maintenance_now: alert suppression in effect at report_clock.as_of.
-- One row per (host, active window): a host window covers that host, a site window covers every
-- in-service host at the site. Consumers match on host_id.
CREATE VIEW v_maintenance_now AS
SELECT
    w.host_id      AS host_id,
    w.id           AS window_id,
    w.reason,
    w.ends_at
FROM maintenance_windows w
JOIN report_clock c
  ON w.starts_at <= c.as_of AND c.as_of < w.ends_at
LEFT JOIN hosts h
  ON h.site_id = w.site_id AND h.retired_at IS NULL;
''',

"queries/rpo_alert.sql": '''-- Nightly RPO alert: every in-service host whose state is not 'ok', except hosts under an active
-- maintenance window. 'never' first, then the oldest backup first, then by hostname.
SELECT hs.hostname, hs.site, hs.tier, hs.state, hs.age_hours
FROM v_host_state hs
WHERE hs.state <> 'ok'
  AND hs.host_id NOT IN (SELECT host_id FROM v_maintenance_now)
ORDER BY hs.state = 'never' DESC, hs.age_hours DESC, hs.hostname
''',

"queries/site_summary.sql": '''-- Weekly rollup per site. protected_gb is the sum of each host's newest good backup size.
SELECT
    s.code                                     AS site,
    COUNT(hs.host_id)                          AS hosts,
    COALESCE(SUM(hs.state = 'ok'), 0)          AS ok,
    COALESCE(SUM(hs.state = 'stale'), 0)       AS stale,
    COALESCE(SUM(hs.state = 'never'), 0)       AS never,
    ROUND(COALESCE(SUM(hs.last_good_bytes), 0) / 1e9, 1) AS protected_gb
FROM sites s
LEFT JOIN v_host_state hs ON hs.site_id = s.id
GROUP BY s.id
ORDER BY s.code
''',

"queries/maintenance_board.sql": '''-- NOC board: hosts whose backup alerts are suppressed right now, with the reason and when the
-- window closes. Soonest-closing first.
SELECT h.hostname, m.reason, m.ends_at
FROM v_maintenance_now m
JOIN hosts h ON h.id = m.host_id
ORDER BY m.ends_at, h.hostname
''',

"test_reports.py": '''import glob
import os
import sqlite3
import unittest

HERE = os.path.dirname(os.path.abspath(__file__))

FIXTURE = """
INSERT INTO sites (id, code, name) VALUES
  (1, 'HQ', 'Head office'), (2, 'BR', 'Eastside branch'), (3, 'COLO', 'Colocation rack');
INSERT INTO rpo_policy (tier, max_age_hours) VALUES ('gold', 26), ('silver', 50), ('bronze', 170);
INSERT INTO hosts (id, hostname, site_id, tier, retired_at) VALUES
  (1, 'dc01', 1, 'gold', NULL),
  (2, 'fs01', 1, 'silver', NULL),
  (3, 'sql01', 1, 'gold', NULL),
  (4, 'db02', 1, 'gold', NULL),
  (5, 'app03', 1, 'bronze', NULL),
  (6, 'br-fs01', 2, 'silver', NULL),
  (7, 'br-pos01', 2, 'bronze', NULL),
  (8, 'colo-web01', 3, 'silver', NULL),
  (9, 'colo-nas01', 3, 'bronze', NULL),
  (10, 'exch01', 1, 'gold', '2026-06-30 17:00:00');
INSERT INTO backup_jobs (host_id, started_at, finished_at, status, bytes_written) VALUES
  (1, '2026-10-11 01:00:00', '2026-10-11 01:40:00', 'success', 41000000000),
  (1, '2026-10-12 01:00:00', '2026-10-12 01:30:00', 'success', 42000000000),
  (2, '2026-10-09 22:00:00', '2026-10-09 23:00:00', 'warning', 610000000000),
  (2, '2026-10-10 22:00:00', '2026-10-10 22:20:00', 'failed', NULL),
  (2, '2026-10-11 22:00:00', NULL, 'running', NULL),
  (3, '2026-10-10 21:00:00', '2026-10-10 22:00:00', 'success', 150000000000),
  (3, '2026-10-11 21:00:00', '2026-10-11 22:00:00', 'failed', 3000000000),
  (4, '2026-10-11 02:00:00', '2026-10-11 02:05:00', 'failed', NULL),
  (5, '2026-10-06 02:00:00', '2026-10-06 03:00:00', 'success', 8000000000),
  (6, '2026-10-08 01:00:00', '2026-10-08 02:00:00', 'success', 220000000000),
  (6, '2026-10-11 01:00:00', '2026-10-11 01:10:00', 'failed', NULL),
  (7, '2026-10-11 01:00:00', '2026-10-11 01:02:00', 'failed', NULL),
  (8, '2026-10-11 19:00:00', '2026-10-11 20:00:00', 'success', 12000000000),
  (9, '2026-09-30 03:00:00', '2026-09-30 04:00:00', 'success', 900000000000),
  (10, '2026-06-29 01:00:00', '2026-06-29 02:00:00', 'success', 70000000000);
INSERT INTO maintenance_windows (host_id, site_id, starts_at, ends_at, reason) VALUES
  (2, NULL, '2026-10-11 18:00:00', '2026-10-13 18:00:00', 'disk replacement'),
  (NULL, 2, '2026-10-12 00:00:00', '2026-10-12 12:00:00', 'WAN cutover'),
  (3, NULL, '2026-10-10 00:00:00', '2026-10-11 00:00:00', 'patching'),
  (8, NULL, '2026-10-14 00:00:00', '2026-10-14 08:00:00', 'switch firmware');
"""


def read(rel):
    with open(os.path.join(HERE, rel)) as f:
        return f.read()


def open_db(as_of):
    db = sqlite3.connect(":memory:")
    db.executescript(read("schema.sql"))
    for path in sorted(glob.glob(os.path.join(HERE, "views", "*.sql"))):
        with open(path) as f:
            db.executescript(f.read())
    db.executescript(FIXTURE)
    db.execute("INSERT INTO report_clock (as_of) VALUES (?)", (as_of,))
    return db


def query(db, name):
    return db.execute(read(os.path.join("queries", name + ".sql"))).fetchall()


NIGHTLY = "2026-10-12 06:00:00"
TWO_DAYS_LATER = "2026-10-14 06:00:00"


class BackupReportTest(unittest.TestCase):
    def test_host_state_verdicts(self):
        db = open_db(NIGHTLY)
        got = {r[0]: (r[1], r[2]) for r in
               db.execute("SELECT hostname, state, age_hours FROM v_host_state")}
        self.assertEqual(got, {
            "dc01": ("ok", 4.5), "fs01": ("stale", 55.0), "sql01": ("stale", 32.0),
            "db02": ("never", None), "app03": ("ok", 147.0), "br-fs01": ("stale", 100.0),
            "br-pos01": ("never", None), "colo-web01": ("ok", 10.0),
            "colo-nas01": ("stale", 290.0)})

    def test_site_summary(self):
        db = open_db(NIGHTLY)
        self.assertEqual(query(db, "site_summary"), [
            ("BR", 2, 0, 1, 1, 220.0),
            ("COLO", 2, 1, 1, 0, 912.0),
            ("HQ", 5, 2, 2, 1, 810.0)])

    def test_rpo_alert_nightly(self):
        db = open_db(NIGHTLY)
        self.assertEqual(query(db, "rpo_alert"), [
            ("db02", "HQ", "gold", "never", None),
            ("colo-nas01", "COLO", "bronze", "stale", 290.0),
            ("sql01", "HQ", "gold", "stale", 32.0)])

    def test_site_window_covers_site_hosts(self):
        db = open_db(NIGHTLY)
        alerted = {r[0] for r in query(db, "rpo_alert")}
        self.assertEqual(alerted & {"br-fs01", "br-pos01"}, set())

    def test_rpo_alert_after_windows_close(self):
        db = open_db(TWO_DAYS_LATER)
        self.assertEqual([r[0] for r in query(db, "rpo_alert")], [
            "br-pos01", "db02", "colo-nas01", "app03", "br-fs01", "fs01", "sql01", "dc01"])

    def test_maintenance_board(self):
        db = open_db(TWO_DAYS_LATER)
        self.assertEqual(query(db, "maintenance_board"), [
            ("colo-web01", "switch firmware", "2026-10-14 08:00:00")])


if __name__ == "__main__":
    unittest.main()
''',
}

HIDDEN = ("test_reports.py",)
_VIEW = "views/30_maintenance_now.sql"
_ALERT = "queries/rpo_alert.sql"
FIX = {_VIEW: PROJECT[_VIEW]
       .replace("    w.host_id      AS host_id,", "    COALESCE(w.host_id, h.id) AS host_id,")
       .replace("  ON h.site_id = w.site_id AND h.retired_at IS NULL;",
                "  ON h.site_id = w.site_id AND h.retired_at IS NULL\n"
                "WHERE COALESCE(w.host_id, h.id) IS NOT NULL;")}
TEST_CMD = ["python3", "-B", "-m", "unittest", "-v"]
PASS_RE = r"^(test_\w+) \(.*\) \.\.\. ok$"
TESTS = tuple(re.findall(r"^    def (test_\w+)\(", PROJECT["test_reports.py"], re.M))
WRONG = [
    # NOT IN -> NOT EXISTS at the symptom: the NULL rows stop matching anything, so the alert
    # comes back, but the site window no longer suppresses br-fs01 / br-pos01.
    {_ALERT: PROJECT[_ALERT].replace(
        "  AND hs.host_id NOT IN (SELECT host_id FROM v_maintenance_now)",
        "  AND NOT EXISTS (SELECT 1 FROM v_maintenance_now m WHERE m.host_id = hs.host_id)")},
    # Filter the NULLs out of the subquery: same effect.
    {_ALERT: PROJECT[_ALERT].replace(
        "(SELECT host_id FROM v_maintenance_now)",
        "(SELECT host_id FROM v_maintenance_now WHERE host_id IS NOT NULL)")},
    # Select the joined host instead: site windows work, host windows now yield NULL.
    {_VIEW: PROJECT[_VIEW].replace("    w.host_id      AS host_id,", "    h.id           AS host_id,")},
]