Skip to content
Hands-on IT IT Drills

Day 15: Competition – tool challenges against the clock

Goal: Build seven small ops tools from scratch under time pressure – with nothing but a specification and a test file – and prove that the patterns from 14 days have stuck · Duration: approx. 150 min · Prerequisite: Day 14

Briefing

  • Every round: read the specification, create the test file, start the stopwatch, write the module until pytest is green. Only then stop the clock.
  • The reference solution comes directly below. Cover it up and only read it once the time is over.
  • Allowed: Appendix A, --help, docs.python.org. Not allowed: AI assistants and copying from earlier days.
  • Scoring: all tests green within the time = full points, up to double the time = half points, after that 0. In addition, ruff check and mypy must be clean.
  • All tools live in one uv project, each as its own module with its own command.
tag15-wettkampf/
├── pyproject.toml          7 commands in [project.scripts]
├── src/wettkampf/          dupfind.py portwait.py jsonq.py envdiff.py
│                           cronnext.py secretscan.py summarize.py
├── tests/test_<tool>.py    given – do not change
└── lab/                    practice data per round

Warm-up: The competition ground

You build the ground before the start – it does not count toward the time.

cd ~/py-lab
uv init -q -p 3.14 --package --name wettkampf tag15-wettkampf
cd tag15-wettkampf
cat > pyproject.toml <<'EOF'
[project]
name = "wettkampf"
version = "0.1.0"
description = "Tag 15: kleine Tools auf Zeit"
readme = "README.md"
authors = [{ name = "Thomas Zachmann", email = "[email protected]" }]
requires-python = ">=3.14"
dependencies = []

[project.scripts]
dupfind = "wettkampf.dupfind:app"
portwait = "wettkampf.portwait:app"
jsonq = "wettkampf.jsonq:app"
envdiff = "wettkampf.envdiff:app"
cronnext = "wettkampf.cronnext:app"
secretscan = "wettkampf.secretscan:app"
llm-summarize = "wettkampf.summarize:app"

[build-system]
requires = ["uv_build>=0.9.26,<0.10.0"]
build-backend = "uv_build"

[tool.ruff.lint]
extend-select = ["E501", "B", "UP", "SIM", "I"]

[tool.mypy]
strict = true
files = ["src"]

[tool.pytest.ini_options]
testpaths = ["tests"]
EOF
uv add -q typer openai pydantic httpx
uv add -q --dev pytest ruff mypy
: > src/wettkampf/__init__.py
mkdir -p tests lab
uv run pytest -q; echo "exit=$?"

Expected:

no tests ran in 0.00s
exit=5
  • -p 3.14 pins the Python version, even if uv would otherwise choose an older one as the default.
  • A console script may point to a typer.Typer object (wettkampf.dupfind:app); typer apps are callable. Commands for modules that don’t exist yet only cause trouble when called.
  • : > datei (file) empties the __init__.py generated by uv; the package needs no main().
  • httpx is listed explicitly because the openai SDK no longer necessarily brings it along (Day 10).
  • pytest exit 5 means “no tests collected” – that will change shortly.

A stopwatch in the terminal, in case you don’t have one at hand:

start=$(date +%s)   # vor jeder Runde
echo "$(( ($(date +%s) - start) / 60 )) min"   # wenn pytest grün ist

Round 1: dupfind – duplicate files

Time limit: 15 min · Points: 10

Specification

  • dupfind DIR... searches the directories recursively and finds files with identical content (SHA-256).
  • Empty files and symlinks are ignored. Group by size first, and only hash files of equal size.
  • find_duplicates(roots) -> list[list[Path]]: groups with at least two paths, paths sorted, largest files first.
  • Output per group: <size> Bytes x <count>, with the paths indented below.
  • Exit 0: no duplicates, exit 1: duplicates found, exit 2: directory missing.

Tests

cat > tests/test_dupfind.py <<'EOF'
from pathlib import Path

from typer.testing import CliRunner

from wettkampf.dupfind import app, find_duplicates

runner = CliRunner()


def make(base: Path, files: dict[str, str]) -> None:
    for name, content in files.items():
        path = base / name
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_text(content, encoding="utf-8")


def test_findet_gruppen(tmp_path):
    make(tmp_path, {"a.txt": "x" * 10, "sub/b.txt": "x" * 10, "c.txt": "y" * 10})
    groups = find_duplicates([tmp_path])
    assert groups == [[tmp_path / "a.txt", tmp_path / "sub/b.txt"]]


def test_gleiche_groesse_anderer_inhalt(tmp_path):
    make(tmp_path, {"a": "abc", "b": "abd"})
    assert find_duplicates([tmp_path]) == []


def test_leere_dateien_und_symlinks_ignoriert(tmp_path):
    make(tmp_path, {"a": "", "b": "", "c": "inhalt"})
    (tmp_path / "link").symlink_to(tmp_path / "c")
    assert find_duplicates([tmp_path]) == []


def test_groesste_gruppe_zuerst(tmp_path):
    make(tmp_path, {"k1": "kurz", "k2": "kurz", "l1": "lang" * 50, "l2": "lang" * 50})
    groups = find_duplicates([tmp_path])
    assert [g[0].name for g in groups] == ["l1", "k1"]


def test_cli_exit_codes(tmp_path):
    make(tmp_path, {"a": "1", "b": "2"})
    assert runner.invoke(app, [str(tmp_path)]).exit_code == 0
    make(tmp_path, {"c": "1"})
    result = runner.invoke(app, [str(tmp_path)])
    assert result.exit_code == 1
    assert "1 Bytes x 2" in result.output
EOF

Reference solution

cat > src/wettkampf/dupfind.py <<'EOF'
"""dupfind – doppelte Dateien per SHA-256 finden."""

import hashlib
from collections import defaultdict
from pathlib import Path
from typing import Annotated

import typer

app = typer.Typer(add_completion=False)


def sha256(path: Path) -> str:
    with path.open("rb") as f:
        return hashlib.file_digest(f, "sha256").hexdigest()


def find_duplicates(roots: list[Path]) -> list[list[Path]]:
    """Gruppen gleicher Dateien; größte Dateien zuerst, Pfade sortiert."""
    by_size: defaultdict[int, list[Path]] = defaultdict(list)
    for root in roots:
        for path in root.rglob("*"):
            if path.is_file() and not path.is_symlink():
                size = path.stat().st_size
                if size:
                    by_size[size].append(path)
    groups: list[tuple[int, list[Path]]] = []
    for size, paths in by_size.items():
        if len(paths) < 2:
            continue  # einzigartige Größe: kein Hash nötig
        by_hash: defaultdict[str, list[Path]] = defaultdict(list)
        for path in paths:
            by_hash[sha256(path)].append(path)
        groups += [(size, sorted(g)) for g in by_hash.values() if len(g) > 1]
    groups.sort(key=lambda g: (-g[0], g[1]))
    return [paths for _, paths in groups]


@app.command()
def main(
    roots: Annotated[list[Path], typer.Argument(exists=True, file_okay=False)],
) -> None:
    """Listet Duplikate. Exit 0: keine, Exit 1: Duplikate gefunden."""
    groups = find_duplicates(roots)
    for paths in groups:
        typer.echo(f"{paths[0].stat().st_size} Bytes x {len(paths)}")
        for path in paths:
            typer.echo(f"  {path}")
    if groups:
        raise typer.Exit(1)
EOF
  • hashlib.file_digest (since 3.11) reads the file block by block – even 10 GB don’t fit into memory at once, and here they don’t have to.
  • The size is a free pre-filter: files with a unique size cannot be duplicates and are never read.
  • defaultdict(list) saves you the if key not in d; the sort key (-size, paths) puts large groups first and gives a stable order.

Check

uv run pytest -q tests/test_dupfind.py
mkdir -p lab/dup/a lab/dup/b
printf 'runbook v1\n' > lab/dup/a/runbook.md
cp lab/dup/a/runbook.md lab/dup/b/runbook-kopie.md
head -c 4096 /dev/zero > lab/dup/a/null.bin && cp lab/dup/a/null.bin lab/dup/b/null2.bin
printf 'anders\n' > lab/dup/b/notiz.txt
uv run dupfind lab/dup; echo "exit=$?"

Expected:

.....                                                                    [100%]
5 passed in 0.05s
4096 Bytes x 2
  lab/dup/a/null.bin
  lab/dup/b/null2.bin
11 Bytes x 2
  lab/dup/a/runbook.md
  lab/dup/b/runbook-kopie.md
exit=1

Save your progress? Sign up for free

Round 2: portwait – waiting for a port

Time limit: 15 min · Points: 10

Specification

  • portwait HOST:PORT [--timeout 30] [--interval 0.2] keeps trying a TCP connection until it succeeds or the timeout expires. A classic for init containers and CI (“wait until the database is there”).
  • parse_target("db:5432") -> ("db", 5432), also [::1]:8200. Missing or invalid port (not 1–65535): typer.BadParameter (exit 2).
  • wait_for(host, port, timeout, interval=0.2) -> float | None: seconds until success, or None. Every OSError (refused, DNS, timeout) means: try again later.
  • Success: HOST:PORT offen nach 1.4s (“open after”), exit 0. Timeout: message on stderr, exit 1.

Tests

cat > tests/test_portwait.py <<'EOF'
import socket

import pytest
import typer
from typer.testing import CliRunner

from wettkampf.portwait import app, parse_target, wait_for

runner = CliRunner()


@pytest.fixture
def open_port():
    with socket.create_server(("127.0.0.1", 0)) as server:
        yield server.getsockname()[1]


@pytest.fixture
def closed_port():
    with socket.create_server(("127.0.0.1", 0)) as server:
        port = server.getsockname()[1]
    return port  # Server ist zu: Verbindungen werden abgelehnt


def test_offener_port(open_port):
    waited = wait_for("127.0.0.1", open_port, timeout=2)
    assert waited is not None
    assert waited < 1


def test_timeout(closed_port):
    assert wait_for("127.0.0.1", closed_port, timeout=0.3, interval=0.05) is None


@pytest.mark.parametrize(
    ("target", "expected"),
    [("db:5432", ("db", 5432)), ("[::1]:8200", ("::1", 8200))],
)
def test_parse_target(target, expected):
    assert parse_target(target) == expected


@pytest.mark.parametrize("target", ["db", "db:http", "db:70000"])
def test_parse_target_fehler(target):
    with pytest.raises(typer.BadParameter):
        parse_target(target)


def test_cli(open_port, closed_port):
    ok = runner.invoke(app, [f"127.0.0.1:{open_port}"])
    assert ok.exit_code == 0
    assert "offen nach" in ok.output
    args = [f"127.0.0.1:{closed_port}", "--timeout", "0.2"]
    assert runner.invoke(app, args).exit_code == 1
    assert runner.invoke(app, ["kaputt"]).exit_code == 2
EOF

Reference solution

cat > src/wettkampf/portwait.py <<'EOF'
"""portwait – warten, bis ein TCP-Port Verbindungen annimmt."""

import socket
import time
from typing import Annotated

import typer

app = typer.Typer(add_completion=False)


def parse_target(target: str) -> tuple[str, int]:
    """'host:port' oder '[ipv6]:port' -> (host, port)."""
    host, sep, port = target.rpartition(":")
    if not sep or not port.isdigit() or not 0 < int(port) < 65536:
        raise typer.BadParameter(f"erwartet host:port, nicht {target!r}")
    return host.strip("[]"), int(port)


def wait_for(
    host: str, port: int, timeout: float, interval: float = 0.2
) -> float | None:
    """Sekunden bis zur ersten erfolgreichen Verbindung, None bei Timeout."""
    start = time.monotonic()
    deadline = start + timeout
    while True:
        left = deadline - time.monotonic()
        try:
            with socket.create_connection((host, port), timeout=max(left, 0.01)):
                return time.monotonic() - start
        except OSError:
            pass  # abgelehnt, DNS noch nicht da, Timeout: nochmal
        if time.monotonic() + interval > deadline:
            return None
        time.sleep(interval)


@app.command()
def main(
    target: Annotated[str, typer.Argument(help="host:port")],
    timeout: Annotated[float, typer.Option(help="Sekunden insgesamt")] = 30.0,
    interval: Annotated[float, typer.Option(help="Pause zwischen Versuchen")] = 0.2,
) -> None:
    """Exit 0, sobald der Port offen ist; Exit 1 nach Ablauf des Timeouts."""
    host, port = parse_target(target)
    waited = wait_for(host, port, timeout, interval)
    if waited is None:
        typer.echo(f"{host}:{port} nach {timeout}s nicht erreichbar", err=True)
        raise typer.Exit(1)
    typer.echo(f"{host}:{port} offen nach {waited:.1f}s")
EOF
  • time.monotonic() instead of time.time(): the monotonic clock never jumps, not even on NTP corrections.
  • The connection timeout is the remaining time – a hanging SYN cannot exceed the overall timeout.
  • The test fixtures bind port 0: the operating system assigns a free port, so collisions with running services are ruled out.

Check

uv run pytest -q tests/test_portwait.py
(sleep 1.5; uv run python -m http.server 8799 --bind 127.0.0.1 >/dev/null 2>&1) &
uv run portwait 127.0.0.1:8799 --timeout 10; echo "exit=$?"
pkill -f 'http.server 8799'
uv run portwait 127.0.0.1:8799 --timeout 1; echo "exit=$?"

Expected:

........                                                                 [100%]
8 passed in 0.42s
127.0.0.1:8799 offen nach 1.4s
exit=0
127.0.0.1:8799 nach 1.0s nicht erreichbar
exit=1

Save your progress? Sign up for free

Round 3: jsonq – a mini jq

Time limit: 25 min · Points: 20

Specification

  • jsonq EXPR [FILE] applies a path expression to JSON from FILE or stdin and prints each result as a JSON line; with -r, strings without quotes.
  • Expressions: . (everything), .key, ."key.mit.punkten" (key with dots), [n] (negative too), [] (iterate over a list or dict values). Freely combinable: .items[].ports[].
  • Missing keys and indexes yield null (like jq). .key on anything other than a dict/null, [n] on a non-list, and broken expressions: QueryError.
  • query(data, expr) -> list[Any]. Broken JSON or QueryError: message on stderr, exit 2.

Tests

cat > tests/test_jsonq.py <<'EOF'
import json

import pytest
from typer.testing import CliRunner

from wettkampf.jsonq import QueryError, app, query

runner = CliRunner()
DATA = {
    "kind": "List",
    "items": [
        {"name": "web", "ports": [80, 443], "labels": {"app.kubernetes.io/name": "w"}},
        {"name": "db", "ports": [5432]},
    ],
}


@pytest.mark.parametrize(
    ("expr", "expected"),
    [
        (".", [DATA]),
        (".kind", ["List"]),
        (".items[1].name", ["db"]),
        (".items[-1].ports[0]", [5432]),
        (".items[].name", ["web", "db"]),
        (".items[].ports[]", [80, 443, 5432]),
        (".items[1].labels", [None]),
        ('.items[0].labels."app.kubernetes.io/name"', ["w"]),
        (".fehlt.auch", [None]),
    ],
)
def test_query(expr, expected):
    assert query(DATA, expr) == expected


@pytest.mark.parametrize("expr", ["kind", ".items[x]", ".items[0", ".kind[0]"])
def test_query_fehler(expr):
    with pytest.raises(QueryError):
        query(DATA, expr)


def test_cli_stdin_und_raw():
    data = json.dumps(DATA)
    result = runner.invoke(app, [".items[].name"], input=data)
    assert result.output.splitlines() == ['"web"', '"db"']
    result = runner.invoke(app, ["-r", ".items[].name"], input=data)
    assert result.output.splitlines() == ["web", "db"]


def test_cli_fehler(tmp_path):
    bad = tmp_path / "bad.json"
    bad.write_text("{kaputt", encoding="utf-8")
    assert runner.invoke(app, [".", str(bad)]).exit_code == 2
    assert runner.invoke(app, ["kind"], input="{}").exit_code == 2
EOF

Reference solution

cat > src/wettkampf/jsonq.py <<'EOF'
"""jsonq – ein Mini-jq: .key, ."key.mit.punkt", [n], [] auf JSON anwenden."""

import json
import re
import sys
from pathlib import Path
from typing import Annotated, Any

import typer

app = typer.Typer(add_completion=False)
TOKEN = re.compile(r'\.(?:([A-Za-z_][\w-]*)|"([^"]+)")|\[(-?\d+)\]|\[\]|\.')


class QueryError(ValueError):
    """Ausdruck ungültig oder passt nicht zu den Daten."""


def step(value: Any, m: re.Match[str]) -> list[Any]:
    key = m[1] or m[2]
    if key is not None:
        if value is not None and not isinstance(value, dict):
            raise QueryError(f"kann {type(value).__name__} nicht mit .{key} lesen")
        return [None if value is None else value.get(key)]
    if m[3] is not None:
        if value is None:
            return [None]
        if not isinstance(value, list):
            raise QueryError(f"kann {type(value).__name__} nicht indizieren")
        i = int(m[3])
        return [value[i] if -len(value) <= i < len(value) else None]
    if m[0] == "[]":
        if not isinstance(value, list | dict):
            raise QueryError(f"kann {type(value).__name__} nicht iterieren")
        return list(value.values() if isinstance(value, dict) else value)
    return [value]  # "." allein


def query(data: Any, expr: str) -> list[Any]:
    if not expr.startswith("."):
        raise QueryError(f"Ausdruck muss mit '.' beginnen: {expr!r}")
    results, pos = [data], 0
    while pos < len(expr):
        m = TOKEN.match(expr, pos)
        if m is None:
            raise QueryError(f"unerwartet bei Position {pos}: {expr[pos:]!r}")
        results = [out for value in results for out in step(value, m)]
        pos = m.end()
    return results


@app.command()
def main(
    expr: str,
    file: Annotated[Path | None, typer.Argument(exists=True, dir_okay=False)] = None,
    raw: Annotated[
        bool, typer.Option("--raw", "-r", help="Strings ohne Quotes")
    ] = False,
) -> None:
    """Wendet EXPR auf FILE oder stdin an. Exit 2 bei kaputtem JSON/Ausdruck."""
    try:
        text = file.read_text(encoding="utf-8") if file else sys.stdin.read()
        results = query(json.loads(text), expr)
    except (json.JSONDecodeError, QueryError) as err:
        typer.echo(f"jsonq: {err}", err=True)
        raise typer.Exit(2) from err
    for value in results:
        if raw and isinstance(value, str):
            typer.echo(value)
        else:
            typer.echo(json.dumps(value, ensure_ascii=False))
EOF
  • A regex with alternatives is a full-fledged tokenizer: TOKEN.match(expr, pos) reads exactly one token starting at position pos, and the groups tell you which one.
  • The result list grows through [] and is processed in full by every further step – the nested comprehension is the entire “interpreter”.
  • isinstance(value, list | dict): since 3.10, isinstance also accepts union types.

Check

uv run pytest -q tests/test_jsonq.py
cat > lab/pods.json <<'EOF'
{"kind": "List", "items": [
  {"metadata": {"name": "web-1", "labels": {"app.kubernetes.io/name": "web"}},
   "status": {"phase": "Running", "containerStatuses": [{"restartCount": 0}]}},
  {"metadata": {"name": "db-0", "labels": {"app.kubernetes.io/name": "db"}},
   "status": {"phase": "CrashLoopBackOff", "containerStatuses": [{"restartCount": 7}]}}
]}
EOF
uv run jsonq '.items[].metadata.name' lab/pods.json
uv run jsonq -r '.items[1].status.phase' lab/pods.json
cat lab/pods.json | uv run jsonq '.items[].status.containerStatuses[].restartCount'
uv run jsonq '.items[0].metadata.labels."app.kubernetes.io/name"' lab/pods.json
uv run jsonq '.items[0].metadata.name[0]' lab/pods.json; echo "exit=$?"

Expected:

...............                                                          [100%]
15 passed in 0.02s
"web-1"
"db-0"
CrashLoopBackOff
0
7
"web"
jsonq: kann str nicht indizieren
exit=2

Save your progress? Sign up for free

Round 4: envdiff – comparing .env files

Time limit: 15 min · Points: 10

Specification

  • envdiff A B [--show-values] compares two .env files and prints one line per key: - KEY only in A, + KEY only in B, ~ KEY value differs; sorted by key.
  • Values appear only with --show-values (~ KEY: alt -> neu, i.e. old -> new; missing ones as <fehlt>, “missing”). .env files contain secrets; a diff quickly ends up in a ticket.
  • parse_env(text) -> dict[str, str]: KEY=VALUE, optional export, spaces around =, values in '…' or "…" (content stays literal, including #), otherwise # starts a comment. Ignore comment lines, blank lines and broken lines.
  • Exit 0: equal, exit 1: differences.

Tests

cat > tests/test_envdiff.py <<'EOF'
from typer.testing import CliRunner

from wettkampf.envdiff import app, diff, parse_env

runner = CliRunner()
A = """# Lab-Werte
DB_HOST=db.lab
DB_PASS='lab-geheim-1'
export API_URL="https://api.lab"
DEBUG=true
"""
B = """DB_HOST=db.lab
DB_PASS=lab-geheim-2
API_URL=https://api.lab   # Kommentar am Ende
TIMEOUT=30
"""


def test_parse_env():
    env = parse_env(A)
    assert env == {
        "DB_HOST": "db.lab",
        "DB_PASS": "lab-geheim-1",
        "API_URL": "https://api.lab",
        "DEBUG": "true",
    }


def test_parse_env_sonderfaelle():
    env = parse_env("X='a # b'\nY=\nkaputt\n Z = 1 \n")
    assert env == {"X": "a # b", "Y": "", "Z": "1"}


def test_diff():
    assert diff(parse_env(A), parse_env(B)) == [
        ("~", "DB_PASS"),
        ("-", "DEBUG"),
        ("+", "TIMEOUT"),
    ]


def test_cli_maskiert_werte(tmp_path):
    a, b = tmp_path / "a.env", tmp_path / "b.env"
    a.write_text(A, encoding="utf-8")
    b.write_text(B, encoding="utf-8")
    result = runner.invoke(app, [str(a), str(b)])
    assert result.exit_code == 1
    assert "~ DB_PASS" in result.output
    assert "geheim" not in result.output
    shown = runner.invoke(app, [str(a), str(b), "--show-values"])
    assert "lab-geheim-1 -> lab-geheim-2" in shown.output
    assert runner.invoke(app, [str(a), str(a)]).exit_code == 0
EOF

Reference solution

cat > src/wettkampf/envdiff.py <<'EOF'
"""envdiff – zwei .env-Dateien vergleichen, ohne Werte zu verraten."""

import re
from pathlib import Path
from typing import Annotated

import typer

app = typer.Typer(add_completion=False)
LINE = re.compile(r"^\s*(?:export\s+)?([A-Za-z_]\w*)\s*=\s*(.*?)\s*$")
EnvFile = Annotated[Path, typer.Argument(exists=True, dir_okay=False)]


def parse_value(raw: str) -> str:
    if raw[:1] in ("'", '"'):
        quote = raw[0]
        end = raw.find(quote, 1)
        return raw[1:end] if end > 0 else raw[1:]
    return raw.split(" #", 1)[0].strip()


def parse_env(text: str) -> dict[str, str]:
    """KEY=VALUE pro Zeile; Kommentare, Leerzeilen und Kaputtes ignorieren."""
    env = {}
    for line in text.splitlines():
        if line.lstrip().startswith("#"):
            continue
        m = LINE.match(line)
        if m:
            env[m[1]] = parse_value(m[2])
    return env


def diff(a: dict[str, str], b: dict[str, str]) -> list[tuple[str, str]]:
    """(-, KEY) nur in a, (+, KEY) nur in b, (~, KEY) verschieden – nach KEY."""
    out = [("-", k) for k in a.keys() - b.keys()]
    out += [("+", k) for k in b.keys() - a.keys()]
    out += [("~", k) for k in a.keys() & b.keys() if a[k] != b[k]]
    return sorted(out, key=lambda item: item[1])


@app.command()
def main(
    a: EnvFile,
    b: EnvFile,
    show_values: Annotated[bool, typer.Option(help="Werte anzeigen")] = False,
) -> None:
    """Exit 0: gleich, Exit 1: Unterschiede. Werte nur mit --show-values."""
    env_a = parse_env(a.read_text(encoding="utf-8"))
    env_b = parse_env(b.read_text(encoding="utf-8"))
    changes = diff(env_a, env_b)
    for sign, key in changes:
        line = f"{sign} {key}"
        if show_values:
            old, new = env_a.get(key, "<fehlt>"), env_b.get(key, "<fehlt>")
            line += f": {old} -> {new}"
        typer.echo(line)
    if changes:
        raise typer.Exit(1)
EOF
  • Dict views behave like sets: a.keys() - b.keys(), a.keys() & b.keys() – no detour via set().
  • sorted(..., key=lambda item: item[1]) sorts by key only; the order of -/+/~ doesn’t matter.
  • A type alias with Annotated (EnvFile) keeps two arguments of the same kind lean (Day 3).

Check

uv run pytest -q tests/test_envdiff.py
cat > lab/staging.env <<'EOF'
# Lab-Werte
DB_HOST=db.lab
DB_PASS=lab-pw-alt
export API_URL="https://api.lab"
DEBUG=true
EOF
cat > lab/prod.env <<'EOF'
DB_HOST=db.lab
DB_PASS=lab-pw-neu
API_URL=https://api.lab  # gleich
TIMEOUT=30
EOF
uv run envdiff lab/staging.env lab/prod.env; echo "exit=$?"
uv run envdiff lab/staging.env lab/prod.env --show-values

Expected:

....                                                                     [100%]
4 passed in 0.01s
~ DB_PASS
- DEBUG
+ TIMEOUT
exit=1
~ DB_PASS: lab-pw-alt -> lab-pw-neu
- DEBUG: true -> <fehlt>
+ TIMEOUT: <fehlt> -> 30

Save your progress? Sign up for free

Round 5: cronnext – when does the job run?

Time limit: 25 min · Points: 20

Specification

  • cronnext EXPR [-n 5] [--from 2026-10-10T08:07] prints the next N points in time after --from (default: now): 2026-10-12 09:00 Mo (German weekday abbreviation).
  • Five fields: minute (0–59), hour (0–23), day (1–31), month (1–12), weekday (0–7, 0 and 7 = Sunday). Per field: *, 5, lists 1,3, ranges 1-5, steps */15 and 10-20/5.
  • parse_field(field, lo, hi) -> set[int]; values out of range, reversed ranges, step 0 or nonsense: CronError (exit 2 in the CLI).
  • Classic cron rule: if day and weekday are both restricted, it is enough for either one to match (0 0 13 * 5 = every 13th and every Friday).
  • next_runs(expr, start, count) -> list[datetime], naive local time, seconds 0, strictly after start.

Tests

cat > tests/test_cronnext.py <<'EOF'
from datetime import datetime

import pytest
from typer.testing import CliRunner

from wettkampf.cronnext import CronError, app, next_runs, parse_field

runner = CliRunner()
START = datetime(2026, 10, 10, 8, 7)  # Samstag


@pytest.mark.parametrize(
    ("field", "lo", "hi", "expected"),
    [
        ("*", 0, 6, set(range(7))),
        ("5", 0, 59, {5}),
        ("1,3-5", 0, 59, {1, 3, 4, 5}),
        ("*/15", 0, 59, {0, 15, 30, 45}),
        ("10-20/5", 0, 59, {10, 15, 20}),
    ],
)
def test_parse_field(field, lo, hi, expected):
    assert parse_field(field, lo, hi) == expected


@pytest.mark.parametrize("field", ["60", "5-1", "*/0", "x", ""])
def test_parse_field_fehler(field):
    with pytest.raises(CronError):
        parse_field(field, 0, 59)


def test_alle_15_minuten():
    runs = next_runs("*/15 * * * *", START, 3)
    assert [r.strftime("%H:%M") for r in runs] == ["08:15", "08:30", "08:45"]


def test_werktags_9_uhr_ueberspringt_wochenende():
    assert next_runs("0 9 * * 1-5", START, 1) == [datetime(2026, 10, 12, 9, 0)]


def test_sonntag_als_0_und_7():
    sunday = [datetime(2026, 10, 11, 0, 0)]
    assert next_runs("0 0 * * 0", START, 1) == sunday
    assert next_runs("0 0 * * 7", START, 1) == sunday


def test_tag_oder_wochentag():
    # Both restricted: the 13th OR a Monday (classic cron rule)
    runs = next_runs("0 0 13 * 1", START, 2)
    assert runs == [datetime(2026, 10, 12), datetime(2026, 10, 13)]


def test_29_februar():
    assert next_runs("0 0 29 2 *", START, 1) == [datetime(2028, 2, 29)]


def test_cli():
    args = ["*/15 9-17 * * 1-5", "-n", "2", "--from", "2026-10-10T08:07"]
    result = runner.invoke(app, args)
    assert result.output.splitlines() == ["2026-10-12 09:00 Mo", "2026-10-12 09:15 Mo"]
    assert runner.invoke(app, ["* * *"]).exit_code == 2
EOF

Reference solution

cat > src/wettkampf/cronnext.py <<'EOF'
"""cronnext – die nächsten Läufe eines cron-Ausdrucks berechnen."""

from datetime import datetime, timedelta
from typing import Annotated

import typer

app = typer.Typer(add_completion=False)
FIELDS = [(0, 59), (0, 23), (1, 31), (1, 12), (0, 7)]  # min std tag monat wtag
DAYS = ["Mo", "Di", "Mi", "Do", "Fr", "Sa", "So"]


class CronError(ValueError):
    """Ungültiger cron-Ausdruck."""


def parse_field(field: str, lo: int, hi: int) -> set[int]:
    """'*', '5', '1,3-5', '*/15', '10-20/5' -> Menge erlaubter Werte."""
    values: set[int] = set()
    for part in field.split(","):
        rng, _, step_s = part.partition("/")
        try:
            step = int(step_s) if step_s else 1
            if rng == "*":
                start, end = lo, hi
            else:
                a, _, b = rng.partition("-")
                start, end = int(a), int(b or a)
        except ValueError as err:
            raise CronError(f"ungültig: {part!r}") from err
        if step < 1 or not lo <= start <= end <= hi:
            raise CronError(f"außerhalb {lo}-{hi} oder Schritt < 1: {part!r}")
        values |= set(range(start, end + 1, step))
    return values


def next_runs(expr: str, start: datetime, count: int) -> list[datetime]:
    fields = expr.split()
    if len(fields) != 5:
        raise CronError(f"5 Felder erwartet, {len(fields)} bekommen")
    minute, hour, dom, month, dow = (
        parse_field(f, lo, hi) for f, (lo, hi) in zip(fields, FIELDS, strict=True)
    )
    dow = {d % 7 for d in dow}  # 7 ist auch Sonntag
    dom_any, dow_any = fields[2] == "*", fields[4] == "*"
    t = start.replace(second=0, microsecond=0) + timedelta(minutes=1)
    runs: list[datetime] = []
    limit = start + timedelta(days=366 * 5)
    while len(runs) < count and t < limit:
        cron_dow = (t.weekday() + 1) % 7  # Python: Mo=0, cron: So=0
        day_ok = (t.day in dom) if dow_any else (cron_dow in dow)
        if not dom_any and not dow_any:
            day_ok = t.day in dom or cron_dow in dow
        if t.month not in month or not day_ok:
            t = t.replace(hour=0, minute=0) + timedelta(days=1)
        elif t.hour not in hour:
            t = t.replace(minute=0) + timedelta(hours=1)
        elif t.minute not in minute:
            t += timedelta(minutes=1)
        else:
            runs.append(t)
            t += timedelta(minutes=1)
    return runs


@app.command()
def main(
    expr: Annotated[str, typer.Argument(help='z. B. "*/15 9-17 * * 1-5"')],
    n: Annotated[int, typer.Option("-n", help="Anzahl Läufe")] = 5,
    start: Annotated[
        datetime | None,
        typer.Option("--from", formats=["%Y-%m-%dT%H:%M"], help="Default: jetzt"),
    ] = None,
) -> None:
    """Gibt die nächsten N Zeitpunkte aus (lokale Zeit, ohne Zeitzone)."""
    try:
        runs = next_runs(expr, start or datetime.now(), n)
    except CronError as err:
        raise typer.BadParameter(str(err)) from err
    for run in runs:
        typer.echo(f"{run:%Y-%m-%d %H:%M} {DAYS[run.weekday()]}")
EOF
  • Walking minute by minute through a year would mean 525,600 steps per hit. That’s why the loop jumps: if the day doesn’t match, to the next day; if the hour doesn’t match, to the next hour.
  • (t.weekday() + 1) % 7 translates Python’s Monday=0 into cron’s Sunday=0 – the most common source of errors in this round.
  • limit (five years) ends impossible expressions like 0 0 31 2 * with an empty list instead of an endless loop.
  • formats=[...] teaches typer to read 2026-10-10T08:07 without seconds as a datetime.

Check

uv run pytest -q tests/test_cronnext.py
uv run cronnext "*/15 9-17 * * 1-5" -n 3 --from 2026-10-10T08:07
uv run cronnext "0 0 13 * 5" -n 3 --from 2026-10-10T08:07
uv run cronnext "61 * * * *"; echo "exit=$?"

Expected (abridged):

................                                                         [100%]
16 passed in 0.04s
2026-10-12 09:00 Mo
2026-10-12 09:15 Mo
2026-10-12 09:30 Mo
2026-10-13 00:00 Di
2026-10-16 00:00 Fr
2026-10-23 00:00 Fr
│ Invalid value: außerhalb 0-59 oder Schritt < 1: '61'                         │
exit=2

The second expression was probably meant as “Friday the 13th” – but cron runs on the 13th or on every Friday. Surprises like this are exactly what a cronnext finds before deployment.

Save your progress? Sign up for free

Round 6: secretscan – finding secrets in the repo

Time limit: 20 min · Points: 15

Specification

  • secretscan [DIR] (default .) searches all text files recursively using four rules: aws-access-key (AKIA/ASIA + 16 characters), github-token (ghp_ and others + at least 36 characters), private-key (PEM header), password-assignment (password, passwd, secret, api_key with = or : and a quoted value of 8 or more characters).
  • Skipped: .git, .venv, node_modules, __pycache__, symlinks, files > 1 MB, binary files (NUL byte in the first 1024 bytes) and lines containing secretscan: ignore.
  • scan(root) -> list[Finding] with path, line, rule, secret; sorted by path and line.
  • Output pfad:zeile: regel maske (path:line: rule mask), then N Funde (“N findings”). The secret never appears in plain text: mask() shows at most the first 4 characters (if there are more than 8), the rest *.
  • Exit 0: nothing found, exit 1: findings.

Tests

cat > tests/test_secretscan.py <<'EOF'
from pathlib import Path

from typer.testing import CliRunner

from wettkampf.secretscan import app, mask, scan

runner = CliRunner()
# Assemble test values at runtime: that way no scanner flags this file.
AWS = "AKIA" + "IOSFODNN7EXAMPLE"  # Beispielschlüssel aus der AWS-Doku
GHP = "ghp_" + "lab" * 12
PEM = "-----BEGIN " + "OPENSSH PRIVATE KEY-----"


def repo(tmp_path: Path) -> Path:
    (tmp_path / "src").mkdir()
    (tmp_path / ".git").mkdir()
    (tmp_path / "src/config.py").write_text(
        f'aws_key = "{AWS}"\npassword = "lab-pw-123456"\nok = 1\n', encoding="utf-8"
    )
    (tmp_path / "deploy.sh").write_text(f"export GH={GHP}\n", encoding="utf-8")
    (tmp_path / "id_lab").write_text(f"{PEM}\nabc\n", encoding="utf-8")
    (tmp_path / ".git/config").write_text(f"token = '{GHP}'\n", encoding="utf-8")
    (tmp_path / "bild.png").write_bytes(b"\x89PNG\x00" + AWS.encode())
    (tmp_path / "test.env").write_text(
        f"KEY={AWS}  # secretscan: ignore\n", encoding="utf-8"
    )
    return tmp_path


def test_scan_findet_alle_regeln(tmp_path):
    found = [(f.path.name, f.line, f.rule) for f in scan(repo(tmp_path))]
    assert found == [
        ("deploy.sh", 1, "github-token"),
        ("id_lab", 1, "private-key"),
        ("config.py", 1, "aws-access-key"),
        ("config.py", 2, "password-assignment"),
    ]


def test_mask():
    assert mask(AWS) == "AKIA****************"
    assert mask("kurz") == "****"


def test_cli_zeigt_nie_den_klartext(tmp_path):
    result = runner.invoke(app, [str(repo(tmp_path))])
    assert result.exit_code == 1
    assert "4 Funde" in result.output
    assert AWS not in result.output
    assert GHP not in result.output


def test_cli_sauber(tmp_path):
    (tmp_path / "a.py").write_text("print('hallo')\n", encoding="utf-8")
    result = runner.invoke(app, [str(tmp_path)])
    assert result.exit_code == 0
    assert "0 Funde" in result.output
EOF

The test file assembles its fake secrets at runtime. If AKIA… appeared in one piece in the source code, every scanner – yours included – would report the test file itself.

Reference solution

cat > src/wettkampf/secretscan.py <<'EOF'
"""secretscan – Secrets in einem Verzeichnisbaum finden (Ausgabe maskiert)."""

import re
from collections.abc import Iterator
from dataclasses import dataclass
from pathlib import Path
from typing import Annotated

import typer

app = typer.Typer(add_completion=False)
RULES = {
    "aws-access-key": re.compile(r"\b(?:AKIA|ASIA)[0-9A-Z]{16}\b"),
    "github-token": re.compile(r"\bgh[pousr]_[A-Za-z0-9]{36,}\b"),
    "private-key": re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----"),
    "password-assignment": re.compile(
        r"(?i)\b(?:password|passwd|secret|api_key)\s*[:=]\s*['\"]([^'\"]{8,})['\"]"
    ),
}
SKIP_DIRS = {".git", ".venv", "node_modules", "__pycache__"}
MAX_BYTES = 1_000_000
IGNORE = "secretscan: ignore"


@dataclass(frozen=True)
class Finding:
    path: Path
    line: int
    rule: str
    secret: str


def mask(secret: str) -> str:
    keep = 4 if len(secret) > 8 else 0
    return secret[:keep] + "*" * (len(secret) - keep)


def files(root: Path) -> Iterator[Path]:
    """Alle Textdateien unter root, ohne SKIP_DIRS, große und binäre Dateien."""
    for path in sorted(root.rglob("*")):
        rel = path.relative_to(root)
        if SKIP_DIRS.intersection(rel.parts) or not path.is_file():
            continue
        if path.is_symlink() or path.stat().st_size > MAX_BYTES:
            continue
        with path.open("rb") as f:
            if b"\x00" in f.read(1024):
                continue  # binär
        yield path


def scan(root: Path) -> list[Finding]:
    found = []
    for path in files(root):
        text = path.read_text(encoding="utf-8", errors="replace")
        for no, line in enumerate(text.splitlines(), 1):
            if IGNORE in line:
                continue
            for rule, rx in RULES.items():
                for m in rx.finditer(line):
                    found.append(Finding(path, no, rule, m[m.lastindex or 0]))
    return found


@app.command()
def main(
    root: Annotated[Path, typer.Argument(exists=True, file_okay=False)] = Path("."),
) -> None:
    """Exit 0: nichts gefunden, Exit 1: Funde. Secrets werden nie ausgegeben."""
    found = scan(root)
    for f in found:
        typer.echo(f"{f.path.relative_to(root)}:{f.line}: {f.rule} {mask(f.secret)}")
    typer.echo(f"{len(found)} Funde")
    if found:
        raise typer.Exit(1)
EOF
  • m[m.lastindex or 0]: if the rule has a group (the value after password=), only that group is reported, otherwise the whole match.
  • SKIP_DIRS.intersection(rel.parts) checks all path parts at once – .git is skipped at any depth.
  • errors="replace" instead of crashing on broken UTF-8; binary files are caught beforehand by the NUL test.

Check

uv run pytest -q tests/test_secretscan.py
mkdir -p lab/leak
cat > lab/leak/app.py <<'EOF'
AWS_KEY = "AKIAIOSFODNN7EXAMPLE"
password = "lab-pw-123456"  # secretscan: ignore
EOF
cat > lab/leak/values.yaml <<'EOF'
db:
  password: "lab-pw-abcdefgh"
EOF
uv run secretscan lab/leak; echo "exit=$?"
uv run secretscan src; echo "exit=$?"

Expected:

....                                                                     [100%]
4 passed in 0.02s
app.py:1: aws-access-key AKIA****************
values.yaml:2: password-assignment lab-***********
2 Funde
exit=1
0 Funde
exit=0

AKIAIOSFODNN7EXAMPLE is the official example key from the AWS documentation – a lab value that works nowhere.

Save your progress? Sign up for free

Round 7: llm-summarize – having an LLM assess a log

Time limit: 20 min · Points: 15

Specification

  • llm-summarize LOG [--top 20] [--dry-run] condenses a log and has a local LLM assess it. Configuration as on Day 10 via SUMMARIZE_BASE_URL (default Ollama), SUMMARIZE_MODEL (ministral-3:3b), SUMMARIZE_API_KEY.
  • normalize(line): remove the leading timestamp, replace secrets (rules from secretscan) with <secret>, IPv4 addresses with <ip>, remaining numbers with #.
  • digest(lines, top): first line N Zeilen, M Muster (“N lines, M patterns”), then the most frequent patterns as <n>x <pattern>. Only this digest goes to the model – never the raw log.
  • summarize(client, text) -> Report (pydantic: headline, severity ∈ ok/warn/crit, findings), structured output with temperature=0.
  • --dry-run only shows the digest, without the LLM. Otherwise the output is [SEVERITY] headline plus - finding. Exit 0 for ok, 1 for warn/crit, 2 if the LLM is unreachable.

Tests

cat > tests/test_summarize.py <<'EOF'
from types import SimpleNamespace as NS
from unittest.mock import MagicMock

from typer.testing import CliRunner

from wettkampf import summarize as sm

runner = CliRunner()
PW = "lab-pw-" + "123456"  # Lab-Wert, zur Laufzeit zusammengesetzt
LOG = f"""2026-10-10T08:00:01Z INFO api ok path=/api/orders ms=12
2026-10-10T08:00:02Z ERROR db connection refused host=10.0.2.15 retry=1
2026-10-10T08:00:03Z ERROR db connection refused host=10.0.2.16 retry=2
2026-10-10T08:00:04Z WARN login failed user=bob password="{PW}"
"""


def test_normalize_entfernt_zeit_ip_zahlen_und_secrets():
    lines = LOG.splitlines()
    assert sm.normalize(lines[1]) == "ERROR db connection refused host=<ip> retry=#"
    expected = 'WARN login failed user=bob password="<secret>"'  # secretscan: ignore
    assert sm.normalize(lines[3]) == expected


def test_digest_zaehlt_muster():
    d = sm.digest(LOG.splitlines(), top=2)
    assert d.splitlines() == [
        "4 Zeilen, 3 Muster",
        "2x ERROR db connection refused host=<ip> retry=#",
        "1x INFO api ok path=/api/orders ms=#",
    ]


def test_summarize_fragt_strukturiert():
    report = sm.Report(headline="DB weg", severity="crit", findings=["refused"])
    client = MagicMock()
    client.chat.completions.parse.return_value = NS(
        choices=[NS(message=NS(parsed=report))]
    )
    assert sm.summarize(client, "2x ERROR ...") == report
    kwargs = client.chat.completions.parse.call_args.kwargs
    assert kwargs["response_format"] is sm.Report
    assert kwargs["temperature"] == 0


def test_cli_dry_run_ohne_llm(tmp_path, monkeypatch):
    log = tmp_path / "app.log"
    log.write_text(LOG, encoding="utf-8")
    monkeypatch.setattr(sm, "make_client", MagicMock(side_effect=AssertionError))
    result = runner.invoke(sm.app, [str(log), "--dry-run"])
    assert result.exit_code == 0
    assert "2x ERROR db connection refused" in result.output
    assert "10.0.2.15" not in result.output
    assert "lab-pw" not in result.output


def test_cli_exit_code_nach_schwere(tmp_path, monkeypatch):
    log = tmp_path / "app.log"
    log.write_text(LOG, encoding="utf-8")
    report = sm.Report(headline="DB weg", severity="crit", findings=["a", "b"])
    monkeypatch.setattr(sm, "make_client", MagicMock())
    monkeypatch.setattr(sm, "summarize", lambda client, text: report)
    result = runner.invoke(sm.app, [str(log)])
    assert result.exit_code == 1
    assert result.output.splitlines()[0] == "[CRIT] DB weg"
EOF

Reference solution

cat > src/wettkampf/summarize.py <<'EOF'
"""llm-summarize – ein Log verdichten und von einem lokalen LLM bewerten lassen."""

import os
import re
from collections import Counter
from pathlib import Path
from typing import Annotated, Literal

import openai
import typer
from openai import OpenAI
from pydantic import BaseModel

from wettkampf.secretscan import RULES

app = typer.Typer(add_completion=False)
BASE_URL = os.environ.get("SUMMARIZE_BASE_URL", "http://127.0.0.1:11434/v1")
MODEL = os.environ.get("SUMMARIZE_MODEL", "ministral-3:3b")
SYSTEM = (
    "Du bist SRE. Du bekommst eine verdichtete Logdatei: Muster mit Häufigkeit. "
    "Antworte auf Deutsch. headline: ein Satz. severity: ok, warn oder crit. "
    "findings: höchstens 3 konkrete Auffälligkeiten."
)
STAMP = re.compile(r"^\S*\d{4}-\d{2}-\d{2}\S*\s+")
IP = re.compile(r"\b\d{1,3}(?:\.\d{1,3}){3}\b")
NUMBER = re.compile(r"\b\d+\b")


class Report(BaseModel):
    headline: str
    severity: Literal["ok", "warn", "crit"]
    findings: list[str]


def normalize(line: str) -> str:
    """Zeitstempel weg, IPs und Secrets schwärzen, Zahlen zu '#'."""
    line = STAMP.sub("", line.strip())
    for rx in RULES.values():
        line = rx.sub(lambda m: m[0].replace(m[m.lastindex or 0], "<secret>"), line)
    return NUMBER.sub("#", IP.sub("<ip>", line))


def digest(lines: list[str], top: int = 20) -> str:
    """Kompakter, geschwärzter Text statt des ganzen Logs."""
    patterns = Counter(normalize(line) for line in lines if line.strip())
    out = [f"{sum(patterns.values())} Zeilen, {len(patterns)} Muster"]
    out += [f"{n}x {p}" for p, n in patterns.most_common(top)]
    return "\n".join(out)


def make_client() -> OpenAI:
    key = os.environ.get("SUMMARIZE_API_KEY", "ollama")
    return OpenAI(base_url=BASE_URL, api_key=key, timeout=120, max_retries=1)


def summarize(client: OpenAI, text: str) -> Report:
    resp = client.chat.completions.parse(
        model=MODEL,
        messages=[
            {"role": "system", "content": SYSTEM},
            {"role": "user", "content": text},
        ],
        response_format=Report,
        temperature=0,
    )
    parsed = resp.choices[0].message.parsed
    if parsed is None:
        raise ValueError("Modell lieferte kein gültiges JSON")
    return parsed


@app.command()
def main(
    logfile: Annotated[Path, typer.Argument(exists=True, dir_okay=False)],
    top: Annotated[int, typer.Option(help="Anzahl Muster für das LLM")] = 20,
    dry_run: Annotated[
        bool, typer.Option(help="nur zeigen, was gesendet würde")
    ] = False,
) -> None:
    """Exit 0: ok, 1: warn/crit, 2: LLM nicht erreichbar."""
    lines = logfile.read_text(encoding="utf-8", errors="replace").splitlines()
    text = digest(lines, top)
    if dry_run:
        typer.echo(text)
        return
    try:
        report = summarize(make_client(), text)
    except openai.APIConnectionError as err:
        typer.echo("LLM nicht erreichbar (läuft Ollama?)", err=True)
        raise typer.Exit(2) from err
    typer.echo(f"[{report.severity.upper()}] {report.headline}")
    for finding in report.findings:
        typer.echo(f"  - {finding}")
    if report.severity != "ok":
        raise typer.Exit(1)
EOF
  • Condensing before sending saves tokens (500 lines become 5) and is privacy protection at the same time: IPs and secrets never leave the machine, even if a cloud API sits behind it later.
  • The secret rules come from Round 6 – one module, two tools.
  • rx.sub with a function replaces only the group (the value); the key password= stays readable for the model.

Check

A lab log with an incident at the end:

uv run pytest -q tests/test_summarize.py
uv run python - <<'EOF'
import random
from datetime import UTC, datetime, timedelta

rng = random.Random(15)
t = datetime(2026, 10, 10, 8, 0, tzinfo=UTC)
with open("lab/app.log", "w", encoding="utf-8") as f:
    for i in range(500):
        t += timedelta(seconds=rng.randint(1, 5))
        stamp = t.strftime("%Y-%m-%dT%H:%M:%SZ")
        if i > 400 and rng.random() < 0.6:
            host = f"10.0.2.{rng.randint(10, 20)}"
            msg = f"ERROR db connection refused host={host} retry={rng.randint(1, 5)}"
        elif rng.random() < 0.05:
            msg = f"WARN slow query ms={rng.randint(900, 3000)} table=orders"
        else:
            path = rng.choice(["/api/orders", "/api/users"])
            msg = f"INFO api ok path={path} ms={rng.randint(5, 80)}"
        print(f"{stamp} {msg}", file=f)
EOF
uv run llm-summarize lab/app.log --dry-run
uv run llm-summarize lab/app.log; echo "exit=$?"

Expected (LLM text varies, abridged):

.....                                                                    [100%]
5 passed in 0.26s
500 Zeilen, 4 Muster
218x INFO api ok path=/api/users ms=#
196x INFO api ok path=/api/orders ms=#
60x ERROR db connection refused host=<ip> retry=#
26x WARN slow query ms=# table=orders
[WARN] API- und Datenbankverkehr läuft stabil, aber langsame Abfragen in der
`orders`-Tabelle auffällig.
  - Häufige Datenbankverbindungsfehler (60x) mit `host=<ip>` – potenzielles
    Netzwerk- oder Konfigurationsproblem.
  - Lange Abfragezeiten in der `orders`-Tabelle (26x) ...
exit=1

Read critically: 60 refused DB connections are more crit than warn, and the model cannot know that they all fall within the last few minutes – the digest has no time axis. The tool pre-sorts; a human has to decide.

Save your progress? Sign up for free

Scoring

Round Time limit Points achieved
1 dupfind 15 min 10 [ ]
2 portwait 15 min 10 [ ]
3 jsonq 25 min 20 [ ]
4 envdiff 15 min 10 [ ]
5 cronnext 25 min 20 [ ]
6 secretscan 20 min 15 [ ]
7 llm-summarize 20 min 15 [ ]
Total 135 min 100
Points Rating
85–100 Pro: you build ops tools faster than you can search for them
65–84 Solid: the patterns have stuck; keep practicing the details (time, edge cases)
below 65 Repeat rounds with 0 points the next day without the reference solution

For every missed round, note the reason in one sentence (“forgot the weekday mapping”, “didn’t know the typer date format”). This list is your personal cheat sheet.

Checkpoint

#!/usr/bin/env bash
check() { if eval "$2" >/dev/null 2>&1; then echo "✔ $1"; else echo "✘ $1"; fi; }
cd ~/py-lab/tag15-wettkampf
for t in dupfind portwait jsonq envdiff cronnext secretscan summarize; do
  check "Tests $t" "uv run pytest -q tests/test_$t.py"
done
check "ruff sauber" "uv run ruff check && uv run ruff format --check"
check "mypy --strict sauber" "uv run mypy"
check "dupfind meldet Duplikate (Exit 1)" "uv run dupfind lab/dup; test \$? -eq 1"
check "portwait Timeout (Exit 1)" \
  "uv run portwait 127.0.0.1:9 --timeout 0.5; test \$? -eq 1"
check "jsonq liest stdin" "echo '{\"a\": [1, 2]}' | uv run jsonq '.a[1]' | grep -qx 2"
check "envdiff verrät keine Werte" \
  "! uv run envdiff lab/staging.env lab/prod.env | grep -q lab-pw"
check "cronnext überspringt das Wochenende" "uv run cronnext '0 9 * * 1-5' -n 1 \
  --from 2026-10-10T08:00 | grep -q '2026-10-12 09:00 Mo'"
check "secretscan findet das Lab-Leak" "uv run secretscan lab/leak; test \$? -eq 1"
check "eigener Code ohne Secrets" "uv run secretscan src && uv run secretscan tests"
check "llm-summarize schwärzt IPs" \
  "! uv run llm-summarize lab/app.log --dry-run | grep -q '10\.0\.2'"

Expected:

✔ Tests dupfind
✔ Tests portwait
✔ Tests jsonq
✔ Tests envdiff
✔ Tests cronnext
✔ Tests secretscan
✔ Tests summarize
✔ ruff sauber
✔ mypy --strict sauber
✔ dupfind meldet Duplikate (Exit 1)
✔ portwait Timeout (Exit 1)
✔ jsonq liest stdin
✔ envdiff verrät keine Werte
✔ cronnext überspringt das Wochenende
✔ secretscan findet das Lab-Leak
✔ eigener Code ohne Secrets
✔ llm-summarize schwärzt IPs

Port 9 (discard) is closed on a normal Mac – ideal for the timeout test.

Challenge

Bonus round (10 min, 5 bonus points): today, dupfind hashes every file of equal size completely. With many large ISO images of the same size, that is expensive. Add a stage in between: first compare the first 4 KiB, and compute the full SHA-256 only for files with the same beginning. A test proves that files with different beginnings are never hashed completely.

Hint: With monkeypatch.setattr(dupfind, "sha256", ...) you replace the hash function in the test with a version that records which files it sees.

Solution

In src/wettkampf/dupfind.py, insert before find_duplicates:

def head(path: Path, size: int = 4096) -> bytes:
    with path.open("rb") as f:
        return f.read(size)

In find_duplicates, replace the block starting at by_hash (inside the size loop):

        by_head: defaultdict[bytes, list[Path]] = defaultdict(list)
        for path in paths:
            by_head[head(path)].append(path)
        for same_head in by_head.values():
            if len(same_head) < 2:
                continue  # Anfang unterscheidet sich: kein voller Hash nötig
            by_hash: defaultdict[str, list[Path]] = defaultdict(list)
            for path in same_head:
                by_hash[sha256(path)].append(path)
            groups += [(size, sorted(g)) for g in by_hash.values() if len(g) > 1]

In tests/test_dupfind.py, add from wettkampf import dupfind at the top and append:

def test_voller_hash_nur_bei_gleichem_anfang(tmp_path, monkeypatch):
    make(tmp_path, {"a": "A" + "x" * 9999, "b": "B" + "x" * 9999})
    make(tmp_path, {"c": "A" + "x" * 9999})
    hashed = []
    original = dupfind.sha256

    def counting(path):
        hashed.append(path.name)
        return original(path)

    monkeypatch.setattr(dupfind, "sha256", counting)
    assert find_duplicates([tmp_path]) == [[tmp_path / "a", tmp_path / "c"]]
    assert sorted(hashed) == ["a", "c"]
uv run pytest -q tests/test_dupfind.py && uv run mypy

Expected:

......                                                                   [100%]
6 passed in 0.06s
Success: no issues found in 8 source files

monkeypatch works because find_duplicates looks up the name sha256 in the module at runtime. The same staged idea – pre-filter cheaply, check only the rest expensively – is what made logsum fast on Day 14.

Save your progress? Sign up for free

Enterprise Note

  • For each of these tools there are mature role models: fdupes/rmlint, wait-for-it, jq, dotenv-linter, gitleaks/trufflehog. Building your own pays off when you need exactly one rule specific to your team or work in an environment without installation rights.
  • Secret scanning belongs in pre-commit (Day 5) and in CI. A finding means: rotate the secret, don’t just delete the line – Git history forgets nothing.
  • Always use portwait in init containers with a timeout; Kubernetes probes and depends_on: condition: service_healthy often replace it entirely.
  • Check cron expressions before rollout and document time zones; Kubernetes CronJobs have spec.timeZone for that.
  • LLM summaries are pre-sorting, not diagnosis: send a digest instead of the raw log, remove secrets and personal data beforehand, and label the assessment as a suggestion.