Port barn (Java) to zag (Zig) #1

Closed
opened 2026-10-17 12:12:23 +00:00 by daniel · 8 comments
Owner

Plan: Port barn (Java) to zag (Zig)

Context

Barn is a ~11k-LOC Java 21 job daemon (one binary = CLI client + service, Unix-socket IPC, per-job state in /tmp/barn/jobs/<id>/). We are porting it to Zig 0.16 as zag (repo samson-media/zag, scaffold + README already pushed to develop) to get a small static native binary with no JVM/GraalVM.

Decisions (confirmed with user):

  • Fidelity: implement documented behaviour, fixing barn's bugs; keep CLI flags, JSON schemas and on-disk layout compatible.
  • Concurrency: one thread per running job (as barn).
  • Platforms, milestone 1: Linux + macOS. Windows deferred (needs a real ServiceMain, AF_UNIX/process-tree checks).
  • CI: Gitea Actions, single runner cross-compiling with zig build -Dtarget=....

Reference source: barn/src/main/java/com/samsonmedia/barn/. Port first: state/StateFiles, jobs/JobRepository, service/BarnService, execution/JobScheduler+JobRunner, config/ConfigLoader+TomlParser, ipc/IpcServer, cli/StatusCommand; specs in barn/docs/jobs.md, docs/config.md.

Intended behaviour fixes (vs barn's actual code)

  1. clean: same semantics offline and via service; no flags = nothing deleted; honour --all, --older-than, --include-failed, --dry-run, --job-id.
  2. kill: set state transition correctly (RUNNING→KILLED/CANCELED per docs) and make the runner tolerate an already-terminal job (no invalid-transition throw/race).
  3. Retries: schedule retries on job failure (barn only does so in crash recovery); honour per-job --max-retries/--retry-delay and retry_on_exit_codes; jitter 0.8–1.2 behind an injectable RNG for tests.
  4. Enforce default_timeout_seconds / --timeout.
  5. service reload: SIGHUP handler that re-reads config (never kills the daemon).
  6. Daemon and CLI both use the config search path (system → user → --config → env); storage.base_dir/ipc_socket honoured consistently; --barn-dir available on all commands.
  7. heartbeat_interval_seconds actually used (barn hard-codes 10s).
  8. Fix BARN_<SECTION>_<KEY> env mapping for load_levels.
  9. Socket created mode 0600; lock files not unlinked while held.
  10. Docs-only files (stage, progress.log, upload.log, max_disk_usage_gb, preserve_work_dir): out of scope for M1; document as not implemented.

Compatibility stays exact for: manifest.json (Jackson-style "key" : value pretty-print, field order), one-file-per-field state files (atomic .tmp+rename), IPC (NDJSON {type,payload} / {status,payload|error} over <base>/barn.sock→zag.sock), JSON/XML/human output field order, config defaults and .load whitelist files.

Milestones

M0 – Foundations (src/): ISO-8601 instant format/parse (0/3/6/9 fractional digits), atomic file writer, flock wrapper, Jackson-style JSON pretty-printer, mini-TOML parser ([section], key = value, flat arrays), duration parser (\d+[mhdwMHDW]), job-id generator (job- + 8 hex).
M1 – State & model: Job/JobManifest, state machine (QUEUED→RUNNING→SUCCEEDED/FAILED/CANCELED/KILLED; FAILED/KILLED→QUEUED), StateFiles, JobRepository, directories layout.
M2 – Config & load levels: config loader + defaults + env overrides + validation; .load classifier (basename / full path / dir-prefix matching), config show|validate|init|install with embedded default files (@embedFile).
M3 – Execution: scheduler (1s tick, oldest-first, per-level limits, retry_at), std.process.Child spawn with append-mode stdout/stderr logs, heartbeat thread, retry calculator, timeout, crash recovery on daemon start, usage sampling (/proc on Linux, proc_pidinfo/ps on macOS; usage.csv), cleanup scheduler.
M4 – IPC & daemon: Unix-socket server/client, request handlers (get_service_status, shutdown, reload, get_status, get_job, run_job, kill_job, clean_jobs), pid file, service start|stop|restart|reload|status|logs, --offline mode running the same code in-process.
M5 – CLI & output: hand-written arg parser (subcommands, --opt=val/--opt val, -- separator, global -o/--output, --config, --offline), human/JSON/XML formatters, --help, --version, bash/zsh completion, exit codes 0/1/2.
M6 – Service install: service install|uninstall for systemd and launchd (single shared unit/plist template, fixing the install.sh vs SystemdManager divergence); install.sh.
M7 – CI/release: Gitea Actions: zig build test on push; tag release cross-compiles linux-x64/arm64, macos-x64/arm64, generates SHA256SUMS, publishes release assets. Homebrew tap update later.
Later: Windows (ServiceMain, named/AF_UNIX transport check, install.ps1, Inno Setup).

Testing / verification

  • Unit tests per module via zig build test, ported from barn specs: JobStateMachineTest, RetryCalculatorTest, TomlParserTest, ConfigLoaderTest, CommandMatcherTest, LoadFileParserTest, StateFilesTest, DurationParserTest, formatter tests, CrashRecoveryTest, HeartbeatCheckerTest.
  • Compat harness (shell, zag/test/compat/): run barn once to produce golden outputs (run, status, describe, clean, service status, config show) with --offline --barn-dir <tmp>; diff against zag. Cross-check that zag can read a barn-written job dir and vice versa.
  • End-to-end: zag service start, zag run -- echo hi, zag status -o json, kill/retry/timeout/crash-recovery scenarios, zag service stop; run on Linux and macOS.
  • Early spikes before M3/M4: Zig 0.16 std.process.Child with append redirects and process-tree kill; std.net Unix sockets.

Housekeeping

  • Add zag/AGENTS.md + CLAUDE.md stub (matching other submodules) and decide whether to register zag as a submodule in the development mono repo (update AGENTS.md, Makefile, docs/submodules.md).
  • README: add install instructions/docs links only once those exist.
# Plan: Port barn (Java) to zag (Zig) ## Context Barn is a ~11k-LOC Java 21 job daemon (one binary = CLI client + service, Unix-socket IPC, per-job state in `/tmp/barn/jobs/<id>/`). We are porting it to Zig 0.16 as `zag` (repo `samson-media/zag`, scaffold + README already pushed to `develop`) to get a small static native binary with no JVM/GraalVM. Decisions (confirmed with user): - **Fidelity:** implement *documented* behaviour, fixing barn's bugs; keep CLI flags, JSON schemas and on-disk layout compatible. - **Concurrency:** one thread per running job (as barn). - **Platforms, milestone 1:** Linux + macOS. Windows deferred (needs a real `ServiceMain`, AF_UNIX/process-tree checks). - **CI:** Gitea Actions, single runner cross-compiling with `zig build -Dtarget=...`. Reference source: `barn/src/main/java/com/samsonmedia/barn/`. Port first: `state/StateFiles`, `jobs/JobRepository`, `service/BarnService`, `execution/JobScheduler`+`JobRunner`, `config/ConfigLoader`+`TomlParser`, `ipc/IpcServer`, `cli/StatusCommand`; specs in `barn/docs/jobs.md`, `docs/config.md`. ## Intended behaviour fixes (vs barn's actual code) 1. `clean`: same semantics offline and via service; no flags = nothing deleted; honour `--all`, `--older-than`, `--include-failed`, `--dry-run`, `--job-id`. 2. `kill`: set state transition correctly (RUNNING→KILLED/CANCELED per docs) and make the runner tolerate an already-terminal job (no invalid-transition throw/race). 3. Retries: schedule retries on job failure (barn only does so in crash recovery); honour per-job `--max-retries`/`--retry-delay` and `retry_on_exit_codes`; jitter 0.8–1.2 behind an injectable RNG for tests. 4. Enforce `default_timeout_seconds` / `--timeout`. 5. `service reload`: SIGHUP handler that re-reads config (never kills the daemon). 6. Daemon and CLI both use the config search path (system → user → `--config` → env); `storage.base_dir`/`ipc_socket` honoured consistently; `--barn-dir` available on all commands. 7. `heartbeat_interval_seconds` actually used (barn hard-codes 10s). 8. Fix `BARN_<SECTION>_<KEY>` env mapping for `load_levels`. 9. Socket created mode 0600; lock files not unlinked while held. 10. Docs-only files (`stage`, `progress.log`, `upload.log`, `max_disk_usage_gb`, `preserve_work_dir`): out of scope for M1; document as not implemented. Compatibility stays exact for: `manifest.json` (Jackson-style `"key" : value` pretty-print, field order), one-file-per-field state files (atomic `.tmp`+rename), IPC (NDJSON `{type,payload}` / `{status,payload|error}` over `<base>/barn.sock`→`zag.sock`), JSON/XML/human output field order, config defaults and `.load` whitelist files. ## Milestones **M0 – Foundations** (`src/`): ISO-8601 instant format/parse (0/3/6/9 fractional digits), atomic file writer, flock wrapper, Jackson-style JSON pretty-printer, mini-TOML parser (`[section]`, `key = value`, flat arrays), duration parser (`\d+[mhdwMHDW]`), job-id generator (`job-` + 8 hex). **M1 – State & model:** `Job`/`JobManifest`, state machine (QUEUED→RUNNING→SUCCEEDED/FAILED/CANCELED/KILLED; FAILED/KILLED→QUEUED), `StateFiles`, `JobRepository`, directories layout. **M2 – Config & load levels:** config loader + defaults + env overrides + validation; `.load` classifier (basename / full path / dir-prefix matching), `config show|validate|init|install` with embedded default files (`@embedFile`). **M3 – Execution:** scheduler (1s tick, oldest-first, per-level limits, `retry_at`), `std.process.Child` spawn with append-mode stdout/stderr logs, heartbeat thread, retry calculator, timeout, crash recovery on daemon start, usage sampling (`/proc` on Linux, `proc_pidinfo`/`ps` on macOS; `usage.csv`), cleanup scheduler. **M4 – IPC & daemon:** Unix-socket server/client, request handlers (`get_service_status`, `shutdown`, `reload`, `get_status`, `get_job`, `run_job`, `kill_job`, `clean_jobs`), pid file, `service start|stop|restart|reload|status|logs`, `--offline` mode running the same code in-process. **M5 – CLI & output:** hand-written arg parser (subcommands, `--opt=val`/`--opt val`, `--` separator, global `-o/--output`, `--config`, `--offline`), human/JSON/XML formatters, `--help`, `--version`, bash/zsh completion, exit codes 0/1/2. **M6 – Service install:** `service install|uninstall` for systemd and launchd (single shared unit/plist template, fixing the install.sh vs SystemdManager divergence); `install.sh`. **M7 – CI/release:** Gitea Actions: `zig build test` on push; tag release cross-compiles linux-x64/arm64, macos-x64/arm64, generates `SHA256SUMS`, publishes release assets. Homebrew tap update later. **Later:** Windows (ServiceMain, named/AF_UNIX transport check, `install.ps1`, Inno Setup). ## Testing / verification - Unit tests per module via `zig build test`, ported from barn specs: `JobStateMachineTest`, `RetryCalculatorTest`, `TomlParserTest`, `ConfigLoaderTest`, `CommandMatcherTest`, `LoadFileParserTest`, `StateFilesTest`, `DurationParserTest`, formatter tests, `CrashRecoveryTest`, `HeartbeatCheckerTest`. - Compat harness (shell, `zag/test/compat/`): run barn once to produce golden outputs (`run`, `status`, `describe`, `clean`, `service status`, `config show`) with `--offline --barn-dir <tmp>`; diff against zag. Cross-check that zag can read a barn-written job dir and vice versa. - End-to-end: `zag service start`, `zag run -- echo hi`, `zag status -o json`, kill/retry/timeout/crash-recovery scenarios, `zag service stop`; run on Linux and macOS. - Early spikes before M3/M4: Zig 0.16 `std.process.Child` with append redirects and process-tree kill; `std.net` Unix sockets. ## Housekeeping - Add `zag/AGENTS.md` + `CLAUDE.md` stub (matching other submodules) and decide whether to register `zag` as a submodule in the development mono repo (update `AGENTS.md`, `Makefile`, `docs/submodules.md`). - README: add install instructions/docs links only once those exist.
Author
Owner

M0 foundations done (commits 8cf4034 and the following): duration parser, ISO-8601 instants, job state machine, job ids, atomic file writes + FileLock, Jackson-style JSON writer, TOML subset parser. 31 tests passing. Next: M1 (job model, StateFiles, JobRepository).

M0 foundations done (commits 8cf4034 and the following): duration parser, ISO-8601 instants, job state machine, job ids, atomic file writes + FileLock, Jackson-style JSON writer, TOML subset parser. 31 tests passing. Next: M1 (job model, StateFiles, JobRepository).
Author
Owner

M1 done: Job/Manifest model, dirs layout, StateFiles, JobRepository (create/find/transitions/retry history). 48 tests passing.

M1 done: Job/Manifest model, dirs layout, StateFiles, JobRepository (create/find/transitions/retry history). 48 tests passing.
Author
Owner

M2 done (config loader/validation/env overrides, load-level classifier, embedded defaults). 63 tests passing. Starting M3 (execution).

M2 done (config loader/validation/env overrides, load-level classifier, embedded defaults). 63 tests passing. Starting M3 (execution).
Author
Owner

M3 done: retry policy, process spawning/log redirection/process-group kill, runner (heartbeat, timeout, kill, retry), crash recovery, per-level scheduler, usage sampling, cleanup policies. 101 tests passing. Starting M4 (IPC + daemon).

M3 done: retry policy, process spawning/log redirection/process-group kill, runner (heartbeat, timeout, kill, retry), crash recovery, per-level scheduler, usage sampling, cleanup policies. 101 tests passing. Starting M4 (IPC + daemon).
Author
Owner

M4 done at library level: Job JSON, NDJSON IPC server/client, daemon service (recovery, scheduler, handlers, cleanup timer, reload), pid-file/foreground/background/stop management. 123 tests passing. Starting M5 (CLI + output formats), which wires it all into the zag binary.

M4 done at library level: Job JSON, NDJSON IPC server/client, daemon service (recovery, scheduler, handlers, cleanup timer, reload), pid-file/foreground/background/stop management. 123 tests passing. Starting M5 (CLI + output formats), which wires it all into the zag binary.
Author
Owner

M4/M5 done: the zag binary now has run/status/describe/usage/kill/clean, service start/stop/restart/reload/status/logs, config show/validate/init/install, autocompletion; human/JSON/XML output; offline mode; per-job timeout; atomic job creation/deletion. 150 unit tests + test/e2e.sh (zig build e2e) passing. Next: M6 (systemd/launchd service install) and M7 (CI/release).

M4/M5 done: the zag binary now has run/status/describe/usage/kill/clean, service start/stop/restart/reload/status/logs, config show/validate/init/install, autocompletion; human/JSON/XML output; offline mode; per-job timeout; atomic job creation/deletion. 150 unit tests + test/e2e.sh (zig build e2e) passing. Next: M6 (systemd/launchd service install) and M7 (CI/release).
Author
Owner

All milestones M0-M7 are implemented on develop: 152 unit tests, test/e2e.sh (zig build e2e), cross-compiles for linux x64/arm64 (musl, static) and macOS x64/arm64, systemd/launchd service install, install.sh, Gitea Actions CI + tagged release workflows. Not done: Windows, barn-vs-zag golden-output compat harness, max_disk_usage_gb/preserve_work_dir, auto-update. CI runs are queued on the org runner (not verified there yet).

All milestones M0-M7 are implemented on develop: 152 unit tests, test/e2e.sh (zig build e2e), cross-compiles for linux x64/arm64 (musl, static) and macOS x64/arm64, systemd/launchd service install, install.sh, Gitea Actions CI + tagged release workflows. Not done: Windows, barn-vs-zag golden-output compat harness, max_disk_usage_gb/preserve_work_dir, auto-update. CI runs are queued on the org runner (not verified there yet).
Author
Owner

Decision: Windows support dropped (not needed). Building for a Windows target now fails early with a clear message; README/AGENTS updated.

Decision: Windows support dropped (not needed). Building for a Windows target now fails early with a clear message; README/AGENTS updated.
Sign in to join this conversation.
No labels
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: samson-media/zag#1