diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..fcfe796 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,180 @@ +# CLAUDE.md — rules for all agents working on dsflow_tui + +dsflow_tui is a single-file curses TUI for the `dsflow` DesignSync check-in +flow: it lists a designer's changes and locks, runs sanity in a detached +runner that locks the files while it runs, and checks in or tags the result. +Read `README.md` for usage and `TODO.md` for the backlog before doing +anything. `files.zip` holds the original `dsflow` plan (bash `dsflow`, +`dsflow_ci`, `dsflow.conf`) this tool must stay compatible with. + +## Hard invariants (never break these) + +1. **Never leave a lock behind.** Every lock the runner takes is released + on pass, fail, cancel and runner error, and the TUI's lost-runner + cleanup (`x`) releases the rest. Locks the designer held before the run + are never released by it. +2. **Never check in untested content.** A check-in happens only after a + pass on every `SANITY_CONFIGS` entry, with the file contents unchanged + since the run started (sha1), nothing stale on Trunk, and the pass + younger than `MAX_STAMP_AGE`. When in doubt, refuse and say why. +3. **Never lose local edits.** No command the TUI issues may overwrite a + modified local copy. `ds_lock` takes the vault lock only; it never + fetches. +4. **All DesignSync access goes through the `ds_*` helpers** in + `dsflow.conf` or `BASH_DEFAULTS`. No `dssc` flags or output parsing in + Python. Site differences are fixed in the conf, not in the script. +5. **Stay compatible with bash `dsflow`.** Shared state keeps its format: + `.dsflow/new_files`, `.dsflow/sanity.stamp` (the hash must equal + `dsflow`'s `content_hash`), and the `CHECKIN_LOG` line format. +6. **The CI working tag is never moved by hand.** Only `dsflow_ci` moves + `WORKING_TAG`; the TUI filters it out of every tag list. +7. **The terminal status is written last.** Readers treat a terminal + `status` in `tui_job.json` as "locks are settled", so the runner saves it + only after lock release. History: the first version saved it before + releasing locks; the test suite caught the race (2026-09-23). + +## Simplicity first + +- Prefer the boring, obvious implementation. If you're building an + abstraction for a second user that doesn't exist yet, stop. +- **Standard library only, Python 3.6 floor.** Designers copy one file + onto locked-down EDA hosts with no pip. No third-party imports in + `dsflow_tui.py`; `vermin -t=3.6-` must stay clean. Test tooling may use + more, but the tests themselves stay on `unittest`. +- **Bash snippets run on bash 3.2** (macOS dev machines): no `mapfile`, + no associative arrays, no `${var,,}`. +- Small functions, descriptive names, shallow nesting. Code should be + readable top-to-bottom without jumping around. +- Match the style of the surrounding code (comment density, naming, + section layout). + +## File and function size + +The tool ships as **one file on purpose**: one file is what gets copied +onto EDA hosts. So the unit a reader navigates is the **section**, the +banner-commented block (`# ---- Flow: ...`), not the file. + +- **Sections: target 300–600 production lines.** A section has to be + describable in one sentence. Several "and" clauses mean it wants to be + two sections. +- **Functions: 10–50 lines.** Investigate anything over 80; anything over + 150 needs a reason in a comment. +- Looser for declarative tables and embedded fixtures (`COLOR_SPEC`, + `FAKE_DSSC`, `DEMO_CONF`). +- A split is a **pure move**: behaviour and screen output identical, the + test count does not drop, all tests green. +- If the file itself becomes the problem, splitting into a package is a + lead decision: it breaks the "copy one file" deployment and needs a + zipapp or install story first. + +Measured 2026-09-23 (non-blank, non-comment lines): file 2 219. Sections: +the app (`App`) 883, demo sandbox 238, Flow 228, Runner 304, form 164, +look & feel 158, the rest under 70. **`App` is over the mark**: split it +into views (drawing) and actions (dialogs and background work) before +adding a feature to it. Functions over 80: `Runner.execute` 99 and +`App.draw_files` 90, both candidates for the next pure move. + +## Python standards + +Before declaring any work finished: + +- `python3 -m py_compile dsflow_tui.py` clean +- `vermin --no-tips -t=3.6- --violations dsflow_tui.py` clean + (`pip install vermin` into a dev venv; never a runtime dependency) +- `tools/guard.py -- python3 -m unittest discover -s tests -v` green +- `./dsflow_tui.py --demo --demo-reset` opened and driven by hand across + every tab you touched + +Code rules: + +- No bare `except:`. A broad `except Exception` needs a `# noqa` comment + that says why; the runner's is there so locks are always released. +- Curses calls happen only on the main thread. Background threads change + plain attributes, and the next frame draws them. +- Every `subprocess` that can run long gets `start_new_session=True` so + it can be killed as a process group. +- Public classes and non-obvious functions get a one-line docstring that + says what/why, not how. + +## Document-based development + +Every feature lives in `docs/features//README.md`. That +README is the single source of truth for the feature and must contain +these sections: + +```markdown +# +## Goal — one paragraph, what and why +## Assumptions — everything you assumed that isn't enforced by code + (dssc behaviour above all: flags, output, lock rules) +## Handshakes — contracts with dsflow.conf, bash dsflow, dsflow_ci + and the job file: what you consume, what you promise +## Status / TODO — checklist; keep current as you work +## Work log — dated entries by the dev agent: what was done, key + decisions, deviations from plan +## QA log — dated entries by the QA agent: what was verified, + how, and findings +## Review — reserved for the lead; do not write here +``` + +Rules: + +- **Dev agents**: create/update the feature README *as you work*, not at + the end. Finished TODOs get checked off in the same README. If you + change a handshake (a `ds_*` helper, the job-file schema, shared + `.dsflow/` state), say so explicitly in Handshakes and in the work log. +- **QA agents**: you verify, you don't redesign. Run the checks, try to + break the feature, record everything in the QA log. File concrete + findings (file:line, reproduction), not opinions. Small unambiguous + fixes (typos, a missing test assertion) you may fix directly and note. +- **Review section** is written only by the lead agent after examining + the work. Respond to review comments by fixing and logging in the work + log, not by editing the Review section. + +## Workflow + +- Do **not** run `git commit` or `git push`. The lead reviews and commits + all work. +- Do not touch files outside your feature's stated scope. If you need a + change elsewhere, write it as a request in your README's Handshakes + section and stop. +- New behavior needs tests in the same change. Anything touching the + runner, locking or check-in gets a `tests/test_runner.py` case that + proves invariants 1–3 still hold for it. +- Update `TODO.md`: check items your feature completes (leave the item + text intact). + +## Never touch a real vault; never leave processes behind + +The runner starts detached processes that outlive the command that +spawned them, and every `dssc` call can change shared vault state. + +- **Dev and QA work only against the demo sandbox** (`--demo`, or + `setup_demo()` in tests, in a temp or scratch directory). Running + against a real DesignSync workspace is a lead decision, made with a + designer, for the verification items in `TODO.md`. +- **Every test run and every scripted TUI drive goes through + `tools/guard.py [-t SECONDS] -- `**: it kills the command's + process group after the limit (default 600 s) and exits non-zero if a + runner or `dsflow-tui` bash helper is still alive afterwards. +- A guard kill or a leak is a finding: report the command and what it + hit. Do not raise the limit or add sleeps to make it pass. + +## The dev loop + +Work runs **serially, one feature at a time, in one tree**: + +1. **The lead plans**: writes the feature's section in `TODO.md` (each item + naming the functions or sections it touches) and a brief with the file + scope. +2. **One dev (Opus)** implements it, keeping the feature README current, + and stops when the Python standards above are met. +3. **One QA (Sonnet)** then verifies in the same tree: reruns every check, + tries to break the invariants (kill the runner mid-run, cancel during + lock, edit a file during sanity, stale a file on Trunk), and records + the QA log. Rework goes back to step 2 and to the same QA afterwards. +4. **The lead reviews**, writes the Review section, reruns the full checks + and commits. + +Never two agents in the tree at once, and the next feature starts only +after the lead commits the previous one. diff --git a/README.md b/README.md new file mode 100644 index 0000000..d970df7 --- /dev/null +++ b/README.md @@ -0,0 +1,160 @@ +# dsflow_tui + +A terminal UI for the `dsflow` DesignSync check-in flow. It lets a designer +see their changes and locks, fire a sanity regression that locks the files +while it runs, and check in or tag the result without typing `dssc`. + +One file, Python 3.6+ standard library only (curses), plus bash. Copy +`dsflow_tui.py` next to `dsflow` and it runs; there is nothing to install. + +``` + ◆ dsflow │ ws ~/ws/wifi_mac │ lucio │ Trunk:Latest │ green tag: working updated 12:03:11 (1.5s) + 1 Changes 5 2 Locks 1 3 Checked-out 4 4 Sanity run ⠹ 5 Logs +──────────────────────────────────────────────────────────────────────────────────────────────── + St File Base → Latest Lock Flags + ◉ M rtl/rx/rx_fsm.sv 1.4 latest you IN-RUN + ◉ M rtl/top/wifi_mac_top.sv 1.12 latest you HOT IN-RUN + ○ M rtl/tx/tx_ctrl.sv 1.7 → 1.8 — STALE + ○ A rtl/rx/rx_agg.sv new file — +──────────────────────────────────────────────────────────────────────────────────────────────── + ⠹ SANITY Sanity kibo_2x2 ████████░░░░░░░░ 0/2 cfg │ 3m10s │ 1 locked by run 2 selected + spc mark a all s sanity c check in t tag n add new m rebase r refresh +``` + +## Try it (demo) + +The demo builds a sandbox workspace driven by a fake `dssc`, so you can try +every action without a DesignSync vault: + +```bash +./dsflow_tui.py --demo --demo-reset +``` + +It has modified, stale, new, hot and locked-by-someone-else files. Useful +knobs, all environment variables: + +```bash +DEMO_FAIL=jaguar_1x1 ./dsflow_tui.py --demo # make one config fail +DEMO_STEP_SECS=0.2 ./dsflow_tui.py --demo # faster fake sanity +``` + +`--demo-reset` rebuilds the sandbox from scratch; without it the sandbox +keeps its state between runs. `--demo-dir DIR` puts it somewhere else. + +## Usage + +Run from the workspace root, the same place you run `dsflow`: + +```bash +dsflow_tui.py # interactive TUI +dsflow_tui.py status # progress of the current sanity run, then exit +dsflow_tui.py status --json # the same, for scripts +dsflow_tui.py --sanity-cmd 'sim/regress.sh --cfg {cfg}' +``` + +| Option | Meaning | +|---|---| +| `--ws DIR` | workspace root (default: current directory) | +| `--conf FILE` | `dsflow.conf` (default: `$DSFLOW_CONF`, else `/flow/dsflow.conf`) | +| `--sanity-cmd CMD` | external sanity command; `{cfg}` and `{ws}` are substituted | +| `--tags T1,T2` | tags offered for batch tagging (default: `DSFLOW_TAGS`) | +| `--auto-refresh SEC` | re-query DesignSync every SEC seconds (default: only on `r` and after actions) | + +### Tabs + +1. **Changes**: locally modified and newly added files, with base/latest + version, lock holder and flags (`HOT`, `STALE`, `IN-RUN`, `MISSING`). +2. **Locks**: your locks, plus every hot file and who holds it. +3. **Checked-out**: writable copies you have not locked. +4. **Sanity run**: each step of the current or last run, progress bars and a + live log tail. +5. **Logs**: full sanity logs per config, the runner log, and this session's + activity. + +### Keys + +| Key | Action | +|---|---| +| `space` / `a` / `esc` | mark a file / mark all in the tab / clear marks. With nothing marked, the cursor row is used. | +| `s` | run sanity on the marked changes | +| `c` | check in marked files that a passing run already covers | +| `t` | batch-tag the marked files with a tag from `DSFLOW_TAGS` | +| `l` / `u` | lock / release a lock | +| `n` | register brand-new files for check-in (same as `dsflow add`) | +| `m` | rebase stale files onto `Trunk:Latest` (same as `dsflow rebase`) | +| `x` | cancel the running sanity, or clean up after a lost runner | +| `1`-`5`, `tab` | switch tabs | +| `r` / `?` / `q` | refresh / help / quit | + +## How a sanity run works + +`s` asks for the configs, what to do on pass (check in, or unlock only), +a comment and an optional tag, then starts a detached runner: + +1. check the files are not stale on Trunk and not locked by someone else +2. lock them (files you already held are left as they are) +3. refresh unmodified files to `Trunk:Latest` (optional) +4. run sanity on every config, one after another, stopping at the first failure +5. on pass: confirm the files did not change during the run, check in, tag; + or just stop there in unlock-only mode +6. release every lock the run took, whatever happened + +The runner does not depend on the TUI. Quit, lose the SSH session, reopen +later: the run carries on and `status` shows where it is. If the runner +itself dies, the TUI notices after 60 s without a heartbeat and `x` stops the +leftover simulation and releases the locks. + +A later `c` checks in only if a passing run on all configs covers exactly +the current file contents and is younger than `MAX_STAMP_AGE`. + +Sanity runs on the whole workspace. If you mark only some of your changed +files, the unmarked ones are tested too but not checked in; the run dialog +warns about this. + +## Configuration + +Everything comes from `dsflow.conf`, the file the bash `dsflow` already uses. +Optional additions: + +```bash +DSFLOW_TAGS="wmac_working wmac_rx_drop" # tags offered by batch tag +SANITY_SCRIPT='$WS_ROOT/sim/run_sanity.sh {cfg}' # instead of run_sanity() +``` + +All DesignSync access goes through `ds_*` helpers. The TUI adds defaults for +the ones `dsflow.conf` does not define; **verify these against your `dssc` +version before rollout** and override any of them in `dsflow.conf`: + +| Helper | Default | Check | +|---|---|---| +| `ds_lock` | `dssc lock` | must take the vault lock without touching the local copy | +| `ds_list_managed` | `dssc ls -rec -report N .` | one workspace-relative path per line | +| `ds_list_writable` | managed files that are writable, plus their holder | assumes files are fetched read-only unless checked out | +| `ds_tag` | `dssc tag -replace` | moves an existing tag | +| `ds_checkin`, `ds_checkin_new` | `dssc ci`, `dssc ci -new` | whether `ci` releases the lock | +| `ds_refresh`, `ds_rebase` | `dssc pop` as in `dsflow` | | + +## Files it writes + +In `/.dsflow/`, next to the bash `dsflow` state it shares (`new_files`, +`sanity.stamp`): + +| File | Contents | +|---|---| +| `tui_job.json` | state of the current or last run | +| `tui_runner.log` | what the runner did, step by step | +| `sanity_.log` | sanity output per config | +| `tui_history.json` | last passing duration per config, for progress estimates | + +A run that covered all your changes on all configs also writes a +`sanity.stamp` that `dsflow checkin` accepts. + +## Development + +```bash +python3 -m unittest discover -s tests -v +``` + +The tests run the runner end to end against the demo sandbox. See +`CLAUDE.md` for the rules and the dev loop. `files.zip` holds the original +`dsflow` plan scripts this tool builds on. diff --git a/TODO.md b/TODO.md new file mode 100644 index 0000000..4ee2094 --- /dev/null +++ b/TODO.md @@ -0,0 +1,24 @@ +# TODO + +## §1 Verify against a real DesignSync (lead + a designer, real workspace) + +Each item is an assumption in `docs/features/dsflow-tui/README.md`. Fix any +mismatch in `dsflow.conf`, not in the script. + +- [ ] `ds_lock` (`dssc lock`) takes the vault lock without fetching or touching a modified local copy +- [ ] `ds_list_managed` (`dssc ls -rec -report N .`) prints one workspace-relative path per line +- [ ] files are fetched read-only unless checked out (the Checked-out tab depends on it) +- [ ] `ds_tag` (`dssc tag -replace`) moves an existing tag on the listed files +- [ ] `dssc ci` releases the lock after check-in (the run's unlock step tolerates either) +- [ ] a stamp written by a full-coverage TUI run is accepted by `dsflow checkin` on the Linux host +- [ ] runner survives logout on the EDA host (`start_new_session`, no SIGHUP from the batch system) + +## §2 Structure (pure moves, see CLAUDE.md "File and function size") + +- [ ] split the `App` section (883 lines) into views and actions +- [ ] shorten `Runner.execute` (99 lines): one method per step +- [ ] shorten `App.draw_files` (90 lines): one cell renderer per tab + +## §3 Tests + +- [ ] pty-driven TUI smoke test (open, mark, start a run, cancel), guarded, no third-party deps diff --git a/docs/features/dsflow-tui/README.md b/docs/features/dsflow-tui/README.md new file mode 100644 index 0000000..865a9c0 --- /dev/null +++ b/docs/features/dsflow-tui/README.md @@ -0,0 +1,72 @@ +# dsflow-tui + +## Goal + +Give designers one screen for the `dsflow` check-in flow: see local changes, +locks and checked-out copies; run sanity on chosen files with those files +locked for the duration; then check in, tag, or just unlock. This replaces +typing `dsflow precheckin` / `checkin` / `claim` / `release` by hand and +makes "I forgot to release the lock" impossible. + +## Assumptions + +- `ds_lock` = `dssc lock` takes the vault lock without touching the local + copy. **Unverified**: TODO §1. +- `dssc ls -rec -report N .` lists managed files, one relative path each. + **Unverified**. +- DesignSync fetches read-only copies unless a file is checked out, so + "writable and unlocked" means "checked out without a lock". **Unverified**. +- `dssc tag -replace` moves an existing tag. **Unverified**. +- `dssc ci` releases the lock. The runner does not rely on it: it checks + the holder and unlocks what the run took either way. +- Sanity runs on the whole workspace, so unmarked local changes are tested + too. The run dialog warns; it does not stop the run. +- The runner and TUI may be on different hosts sharing the workspace over + NFS, so liveness is a heartbeat in the job file, not a pid check. + +## Handshakes + +Consumes from `dsflow.conf`: `TRUNK_SEL`, `WORKING_TAG`, `SANITY_CONFIGS`, +`MAX_STAMP_AGE`, `HOT_FILES`, `CHECKIN_LOG`, `run_sanity`, and the +`ds_list_modified` / `ds_base_version` / `ds_latest_version` / +`ds_lock_holder` / `ds_unlock` helpers. Optional: `DSFLOW_TAGS`, +`SANITY_SCRIPT`, and overrides of every `BASH_DEFAULTS` helper. + +Promises to bash `dsflow`: `.dsflow/new_files` stays a sorted path list; +`.dsflow/sanity.stamp` is written only by a run that covered exactly +`all_changes` on exactly `SANITY_CONFIGS`, with `dsflow`'s `content_hash`; +`CHECKIN_LOG` lines are `timeuserhashfiles`. + +Promises to `dsflow_ci`: never moves `WORKING_TAG`. + +Job file (`.dsflow/tui_job.json`): written by the runner, read by the TUI +and `status`. A terminal `status` (`passed`, `failed`, `cancelled`, +`error`) means lock release has finished. `heartbeat` is refreshed every +5 s; 60 s without one means the runner is gone. + +## Status / TODO + +- [x] Changes, Locks (with hot-file board), Checked-out, Sanity run, Logs tabs +- [x] detached runner: validate, lock, refresh, sanity per config, verify, check in, tag, unlock +- [x] cancel, lost-runner cleanup, later check-in with `c`, batch tag, add new, rebase +- [x] `status` / `status --json`, `--sanity-cmd`, `SANITY_SCRIPT` +- [x] `--demo` sandbox with a fake `dssc`; `tests/test_runner.py` +- [ ] real-DesignSync verification: TODO §1 + +## Work log + +- 2026-09-23: first version built on the `dsflow` plan in `files.zip`. + Choices: curses over Textual (no pip on EDA hosts); the runner is a + separate detached process so a closed terminal can't strand locks; + cancel is a file (`tui_job.cancel`) rather than a signal so it works + across hosts. Tested in the demo through a pty with pass, fail, cancel, + unlock-only then `c`, kill -9 of the runner, stale guard, ASCII locale. +- 2026-09-23: writing the test suite found two bugs, both fixed. The fake + `dssc` computed wrong paths when the demo lived under a symlinked + directory (macOS `/var`), which broke the default `--demo` on a Mac. The + runner saved the terminal status before releasing locks (CLAUDE.md + invariant 7). + +## QA log + +## Review diff --git a/dsflow_tui.py b/dsflow_tui.py index 3dd43b4..40fe7ac 100755 --- a/dsflow_tui.py +++ b/dsflow_tui.py @@ -593,21 +593,19 @@ class Runner(object): self.save() threading.Thread(target=self._heartbeat, daemon=True).start() + # The terminal status is saved last: readers treat it as "locks are settled". + final = "error" try: self.execute() - self.job["status"] = "passed" + final = "passed" except Cancelled: - self.job["status"] = "cancelled" - self.job["summary"] = "cancelled by user" + final, self.job["summary"] = "cancelled", "cancelled by user" except StepFailed as e: - self.job["status"] = "failed" - self.job["summary"] = str(e) + final, self.job["summary"] = "failed", str(e) except Exception as e: # noqa - the runner must always release locks - self.job["status"] = "error" self.job["summary"] = "runner error: %s" % e self.log(traceback.format_exc()) finally: - final = self.job["status"] with self.lk: for s in self.job["steps"]: if s["status"] == "running": @@ -619,14 +617,15 @@ class Runner(object): s["status"] = "skipped" self.job["finished"] = time.time() self.job["phase"] = "finished" + self.job["status"] = final self.done = True - self.log("finished: %s - %s" % (self.job["status"], self.job.get("summary", ""))) + self.log("finished: %s - %s" % (final, self.job.get("summary", ""))) self.save() try: os.remove(self.flow.path(JOB_CANCEL)) except OSError: pass - return 0 if self.job["status"] == "passed" else 1 + return 0 if final == "passed" else 1 def execute(self): j, flow = self.job, self.flow @@ -2188,7 +2187,7 @@ FAKE_DSSC = r'''#!/usr/bin/env python3 """Fake dssc for the dsflow_tui demo. Vault state lives in $DSSC_FAKE_VAULT.""" import hashlib, json, os, sys, time, getpass VAULT = os.environ["DSSC_FAKE_VAULT"] -ROOT = os.path.dirname(VAULT) +ROOT = os.path.dirname(os.path.realpath(VAULT)) ME = os.environ.get("USER") or getpass.getuser() time.sleep(0.03) @@ -2230,7 +2229,7 @@ def parse(argv, valued): def targets(v, pos): out = [] for p in pos or ["."]: - r = os.path.relpath(os.path.abspath(p), ROOT) + r = os.path.relpath(os.path.realpath(p), ROOT) if r == ".": out += sorted(v["files"]) elif r in v["files"]: @@ -2289,7 +2288,7 @@ elif cmd == "ci": fl, vals, pos = parse(argv, {"-comment"}) if "-new" in fl: for p in pos: - f = os.path.relpath(os.path.abspath(p), ROOT) + f = os.path.relpath(os.path.realpath(p), ROOT) if f in v["files"]: die("%s is already managed" % f) v["files"][f] = dict(base="1.1", latest="1.1", hash=sha(f), locker="", tags={}, author=ME) @@ -2371,7 +2370,7 @@ ds_unlock() { dssc unlock "$@"; } def setup_demo(base, reset): - base = os.path.abspath(base) + base = os.path.realpath(base) # macOS: /var -> /private/var would skew relative paths ws, bindir, share = os.path.join(base, "ws"), os.path.join(base, "bin"), os.path.join(base, "share") vault = os.path.join(ws, ".fakevault.json") if reset and os.path.isdir(base): diff --git a/tests/test_runner.py b/tests/test_runner.py new file mode 100644 index 0000000..92b81fc --- /dev/null +++ b/tests/test_runner.py @@ -0,0 +1,132 @@ +"""Runner and Flow tests against the --demo sandbox (fake dssc, no real vault). + + python3 -m unittest discover -s tests -v +""" +import os +import shutil +import subprocess +import sys +import tempfile +import time +import unittest + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")) +import dsflow_tui as d # noqa: E402 + +RUN_TIMEOUT = 60 + + +class DemoCase(unittest.TestCase): + """Fresh demo workspace per test; sanity steps are shortened to keep runs fast.""" + + def setUp(self): + self.base = tempfile.mkdtemp(prefix="dsflow_tui_test-") + self.env = dict(os.environ) + os.environ.update(DEMO_STEP_SECS="0.05", DEMO_SANITY_TESTS="3") + os.environ.pop("DEMO_FAIL", None) + ws, conf = d.setup_demo(self.base, True) + self.flow = d.Flow(ws, conf) + self.flow.load_vars() + + def tearDown(self): + os.environ.clear() + os.environ.update(self.env) + for root, dirs, files in os.walk(self.base): + for n in dirs + files: + os.chmod(os.path.join(root, n), 0o755) + shutil.rmtree(self.base) + + def start(self, mods, news=(), mode="checkin", tag=""): + job = d.new_job(self.flow, list(mods), list(news), self.flow.configs, mode, "test", tag, True) + d.spawn_runner(self.flow, job) + + def wait(self, until_state="done"): + deadline = time.time() + RUN_TIMEOUT + while time.time() < deadline: + job = d.read_json(self.flow.path(d.JOB_FILE)) + if d.job_state(job) == until_state: + return job + time.sleep(0.2) + self.fail("runner did not reach '%s' within %ds" % (until_state, RUN_TIMEOUT)) + + def steps(self, job): + return dict((s["key"], s["status"]) for s in job["steps"]) + + +class SnapshotTest(DemoCase): + def test_lists_changes_locks_and_checkouts(self): + snap = self.flow.snapshot() + self.assertIsNone(snap.err) + kinds = dict((r["path"], r["kind"]) for r in snap.changes) + self.assertEqual(kinds["rtl/rx/rx_agg.sv"], "A") + self.assertEqual(kinds["rtl/rx/rx_fsm.sv"], "M") + stale = [r["path"] for r in snap.changes if r["stale"]] + self.assertEqual(stale, ["rtl/tx/tx_ctrl.sv"]) + holders = dict((r["path"], r["holder"]) for r in snap.locks) + self.assertEqual(holders["rtl/regs/mac_regs.sv"], "alice") + self.assertEqual(holders["rtl/top/wifi_mac_top.sv"], d.ME) + self.assertIn("rtl/tx/tx_crc.sv", [r["path"] for r in snap.checkout]) + + +class RunnerTest(DemoCase): + def test_pass_checks_in_tags_and_releases_locks(self): + mods = ["rtl/rx/rx_fsm.sv", "rtl/tx/tx_fifo.sv"] + self.start(mods, ["rtl/rx/rx_agg.sv"], tag="wmac_working") + job = self.wait() + self.assertEqual(job["status"], "passed", job.get("summary")) + self.assertTrue(job["checked_in"]) + self.assertEqual(set(self.steps(job).values()), {"done"}) + self.assertEqual(self.flow.holders(mods), dict((f, "") for f in mods)) + self.assertEqual(self.flow.new_files(), []) + with open(self.flow.vars["CHECKIN_LOG"]) as fh: + self.assertIn("rtl/rx/rx_agg.sv", fh.read()) + + def test_failure_releases_run_locks_but_keeps_preheld(self): + os.environ["DEMO_FAIL"] = "jaguar_1x1" + hot, plain = "rtl/top/wifi_mac_top.sv", "rtl/rx/rx_fsm.sv" + self.start([hot, plain]) + job = self.wait() + self.assertEqual(job["status"], "failed") + self.assertEqual(job["locked_by_job"], [plain]) + self.assertEqual(self.steps(job)["checkin"], "skipped") + self.assertEqual(self.flow.holders([hot, plain]), {hot: d.ME, plain: ""}) + + def test_cancel_stops_sanity_and_releases_locks(self): + os.environ.update(DEMO_STEP_SECS="2", DEMO_SANITY_TESTS="30") + mods = ["rtl/rx/rx_fsm.sv"] + self.start(mods, mode="unlock") + deadline = time.time() + RUN_TIMEOUT + while self.steps(d.read_json(self.flow.path(d.JOB_FILE))).get("sanity:kibo_2x2") != "running": + self.assertLess(time.time(), deadline) + time.sleep(0.2) + open(self.flow.path(d.JOB_CANCEL), "w").close() + job = self.wait() + self.assertEqual(job["status"], "cancelled") + self.assertEqual(self.flow.holders(mods), {mods[0]: ""}) + self.assertNotIn("child_pid", job) + + def test_stale_file_is_rejected_before_locking(self): + self.start(["rtl/tx/tx_ctrl.sv"]) + job = self.wait() + self.assertEqual(job["status"], "failed") + self.assertEqual(self.steps(job)["validate"], "failed") + self.assertEqual(job["locked_by_job"], []) + + def test_full_coverage_run_writes_stamp_dsflow_accepts(self): + self.assertEqual(self.flow.act("ds_rebase", "rtl/tx/tx_ctrl.sv")[0], 0) + snap = self.flow.snapshot() + mods = [r["path"] for r in snap.changes if r["kind"] == "M"] + news = [r["path"] for r in snap.changes if r["kind"] == "A"] + self.start(mods, news, mode="unlock") + self.assertEqual(self.wait()["status"], "passed") + with open(self.flow.path("sanity.stamp")) as fh: + stamp = dict(l.split("=", 1) for l in fh.read().splitlines()) + # dsflow's content_hash, transcribed so it also runs on bash 3.2 + bash_hash = subprocess.check_output(self.flow.argv( + 'fs=$(%s); sha1sum $fs | sha1sum | cut -d" " -f1' % d.ALL_CHANGES_SH), + cwd=self.flow.ws, env=self.flow.env(), universal_newlines=True).strip() + self.assertEqual(stamp["stamp_hash"], bash_hash) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/guard.py b/tools/guard.py new file mode 100755 index 0000000..cbd9f36 --- /dev/null +++ b/tools/guard.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +"""Run a command with a wall-clock limit, then fail if it leaked runner processes. + + tools/guard.py [-t SECONDS] -- [args...] + +Kills the command's whole process group when it exceeds the limit (default +600 s). Afterwards, any process still matching the dsflow_tui runner or its +bash helpers is reported and the guard exits non-zero: a leak is a finding. +""" +import argparse +import os +import signal +import subprocess +import sys +import time + +LEAK_PATTERN = "_runjob|dsflow-tui" + + +def leftovers(): + out = subprocess.run(["pgrep", "-fl", LEAK_PATTERN], stdout=subprocess.PIPE, + universal_newlines=True).stdout + return [l for l in out.splitlines() if "guard.py" not in l] + + +def main(): + ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + ap.add_argument("-t", type=int, default=600, metavar="SECONDS") + ap.add_argument("command", nargs=argparse.REMAINDER) + args = ap.parse_args() + cmd = args.command[1:] if args.command[:1] == ["--"] else args.command + if not cmd: + ap.error("no command given") + + p = subprocess.Popen(cmd, start_new_session=True) + try: + rc = p.wait(timeout=args.t) + except subprocess.TimeoutExpired: + os.killpg(p.pid, signal.SIGKILL) + p.wait() + print("guard: killed after %ds: %s" % (args.t, " ".join(cmd)), file=sys.stderr) + rc = 124 + + time.sleep(1) # let detached runners finish their own cleanup + leaked = leftovers() + if leaked: + print("guard: leftover processes (a finding - report the command):", file=sys.stderr) + for line in leaked: + print(" " + line, file=sys.stderr) + return rc or 3 + return rc + + +if __name__ == "__main__": + sys.exit(main())