From ddc660ed2c18c6a32f3e806a532ee0d983116429 Mon Sep 17 00:00:00 2001 From: Matthias Linhuber Date: Fri, 21 Aug 2026 15:05:50 +0200 Subject: [PATCH 1/8] Stop redelivering long-running jobs while they are still executing The JetStream job consumer created its consumers without an explicit AckWait or MaxDeliver, so the client defaults applied: a 30s ack timeout and unlimited redeliveries. Because processJob acks only after processing(job) returns, and the Docker executor's ScheduleJob blocks for the entire job, every Docker-mode job longer than 30 seconds was redelivered and executed again while the first copy was still running - repeating every 30 seconds for as long as the job took. Both copies mount the same shared- volume, so they corrupt each other's workspace. The worker now signals InProgress on a ticker for as long as the job runs, which keeps resetting the ack timer, so job duration no longer drives redelivery. AckWait and MaxDeliver are set explicitly and are configurable via NATS_ACK_WAIT (default 1m) and NATS_MAX_DELIVER (default 3). The last allowed delivery is not executed: it publishes a terminal Failed status and terminates the message, so a job that keeps killing its worker neither loops forever nor vanishes without a status. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01Dmsq9AGYZWikY4BqjR3CLw --- .env.example | 2 + AGENTS.md | 1 + HadesScheduler/HadesOperator/go.sum | 41 +++++ HadesScheduler/Readme.md | 8 +- HadesScheduler/go.sum | 21 +++ HadesScheduler/main.go | 10 +- docs/configuration.md | 6 +- shared/go.mod | 46 +++++- shared/go.sum | 113 +++++++++++++- shared/nats/ackprogress_test.go | 97 ++++++++++++ shared/nats/consumer.go | 179 +++++++++++++++++++++- shared/nats/consumer_redelivery_test.go | 192 ++++++++++++++++++++++++ shared/nats/publisher.go | 12 +- website/docs/reference/configuration.md | 2 + 14 files changed, 706 insertions(+), 24 deletions(-) create mode 100644 shared/nats/ackprogress_test.go create mode 100644 shared/nats/consumer_redelivery_test.go diff --git a/.env.example b/.env.example index d45c5824..3ee6774c 100644 --- a/.env.example +++ b/.env.example @@ -36,6 +36,8 @@ HADES_EXECUTOR="docker" # Executor to use for running jobs (options: docker, k8s ### HadesScheduler Options ### CONCURRENCY=1 # Number of jobs to run concurrently (default: 1) +NATS_ACK_WAIT=1m # How long JetStream waits for an ack before redelivering a job to another worker; a liveness backstop, not a job-duration budget (default: 1m) +NATS_MAX_DELIVER=3 # Max deliveries per job; the last one publishes a terminal Failed status instead of running the job again (default: 3) ### HadesOperator Options ### WATCH_NAMESPACE="hades" diff --git a/AGENTS.md b/AGENTS.md index 3dd2b9f0..32dfe5e0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -25,6 +25,7 @@ Go workspace (`go.work`, Go 1.26) with five modules: - **Queue subjects:** `hades.jobs.{high,medium,low}` (priority-bucketed JetStream subjects). - **Status subjects:** `hades.jobstatus.{Queued,Running,Succeeded,Failed,Stopped}` (payload = job ID string). `HadesAPI` publishes `Queued` on enqueue; the scheduler/operator publish `Running`/`Succeeded`/`Failed`. `HadesLogManager` and the dashboard subscribe to the whole `hades.jobstatus.*` lifecycle. - **Log subjects:** see `shared/buildlogs/buildlog_stream.go`. +- **Job leases:** the scheduler acks a job only after the executor returns, and the Docker executor blocks for the whole job. `shared/nats/consumer.go` therefore heartbeats `msg.InProgress()` on a ticker while a job runs so the `NATS_ACK_WAIT` (default 1m) timer keeps resetting - job duration must never determine AckWait. `NATS_MAX_DELIVER` (default 3) caps redeliveries; the last delivery is not executed but publishes a terminal `Failed` status and terminates the message. - **Job DTO:** `shared/payload/payload.go` (`QueuePayload` with ordered `Step`s). Job-level: `timeout_seconds` (whole-job timeout). Each step has `image`, optional `script`, `metadata` env vars, `cpu_limit` (whole cores), `memory_limit`, and the Docker-only limits `network`, `memory_swap`, `pids_limit`. - **Executor parity:** `timeout_seconds`, env (`metadata`), `cpu_limit`, `memory_limit` are enforced on both executors (Kubernetes: per-container resources + Job `activeDeadlineSeconds`). `network`, `memory_swap`, `pids_limit` are enforced on the **Docker executor only**; the operator accepts them for schema parity but does not apply them (pod containers share a network namespace; no per-container swap/PID field). - **CRD:** `BuildJob` in `HadesScheduler/HadesOperator/api/v1/buildjob_types.go`. **Important:** if you change `BuildJobSpec`, run `make -C HadesScheduler/HadesOperator manifests generate` and commit `helm/hades/crds/build.hades.tum.de_buildjobs.yaml` and `zz_generated.deepcopy.go` - the `verify-crd.yml` GitHub workflow will fail otherwise. The `BuildJobSpec` is intentionally duplicated from `shared/payload`; keep them in sync manually. diff --git a/HadesScheduler/HadesOperator/go.sum b/HadesScheduler/HadesOperator/go.sum index 631291a0..25b61186 100644 --- a/HadesScheduler/HadesOperator/go.sum +++ b/HadesScheduler/HadesOperator/go.sum @@ -1,29 +1,45 @@ +dario.cat/mergo v1.0.2 h1:85+piFYR1tMbRrLcDwR18y4UKJ3aH1Tbzi24VRW1TK8= +github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c h1:udKWzYgxTojEKWjV8V+WSxDXJ4NFATAsZjh8iIbsQIg= github.com/Masterminds/semver/v3 v3.4.0 h1:Zog+i5UMtVoCU8oKka5P7i9q9HgrJeGzI9SA1Xbatp0= github.com/Masterminds/semver/v3 v3.4.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM= +github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/caarlos0/env/v11 v11.4.1 h1:fYwH0sWEsBSMPG7t4e/PEfTFzrWrpjyygXyUnWiSwEw= github.com/caarlos0/env/v11 v11.4.1/go.mod h1:qupehSf/Y0TUTsxKywqRt/vJjN5nz6vauiYEUUr8P4U= +github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/containerd/errdefs v1.0.0 h1:tg5yIfIlQIrxYtu9ajqY42W3lpS19XqdxRQeEwYG8PI= +github.com/containerd/errdefs/pkg v0.3.0 h1:9IKJ06FvyNlexW690DXuQNx2KA2cUJXx151Xdx3ZPPE= +github.com/containerd/log v0.1.0 h1:TCJt7ioM2cr/tfR8GPbGf9/VRAX8D2B4PjzCpfX540I= +github.com/containerd/platforms v0.2.1 h1:zvwtM3rz2YHPQsF2CHYM8+KtB5dvhISiXh5ZpSBQv6A= +github.com/cpuguy83/dockercfg v0.3.2 h1:DlJTyZGBDlXqUZ2Dk2Q3xHs/FtnooJJVaad2S9GKorA= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk= +github.com/docker/go-connections v0.8.1 h1:JibmG5hULs5qXSr/cp/w3Pw5fZuStt4MOHMUExb29/M= +github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4= +github.com/ebitengine/purego v0.10.1 h1:dewVBCBT2GaMu1SrNTYxQhgQBethzfhiwvZiLGP/qyY= github.com/emicklei/go-restful/v3 v3.13.0 h1:C4Bl2xDndpU6nJ4bc1jXd+uTmYPVUwkD6bFY/oTyCes= github.com/emicklei/go-restful/v3 v3.13.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= github.com/evanphx/json-patch v0.5.2 h1:xVCHIVMUu1wtM/VkR9jVZ45N3FhZfYMMYGorLCR8P3k= github.com/evanphx/json-patch v0.5.2/go.mod h1:ZWS5hhDbVDyob71nXKNL0+PWn6ToqBHMikGIFbs31qQ= github.com/evanphx/json-patch/v5 v5.9.11 h1:/8HVnzMq13/3x9TPvjG08wUGqBTmZBsCWzjTM0wiaDU= github.com/evanphx/json-patch/v5 v5.9.11/go.mod h1:3j+LviiESTElxA4p3EMKAB9HXj3/XEtnUf6OZxqIQTM= +github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc= github.com/fsnotify/fsnotify v1.10.1 h1:b0/UzAf9yR5rhf3RPm9gf3ehBPpf0oZKIjtpKrx59Ho= github.com/fsnotify/fsnotify v1.10.1/go.mod h1:TLheqan6HD6GBK6PrDWyDPBaEV8LspOxvPSjC+bVfgo= github.com/fxamacker/cbor/v2 v2.9.2 h1:X4Ksno9+x3cz0TZv69ec1hxP/+tymuR8PXQJyDwfh78= github.com/fxamacker/cbor/v2 v2.9.2/go.mod h1:vM4b+DJCtHn+zz7h3FFp/hDAI9WNWCsZj23V5ytsSxQ= github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8= github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-logr/zapr v1.3.0 h1:XGdV8XW8zdwFiwOA2Dryh1gj2KRQyOOoNmBy4EplIcQ= github.com/go-logr/zapr v1.3.0/go.mod h1:YKepepNBd1u/oyhd/yQmtjVXmm9uML4IXUgMOwR8/Gg= +github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE= github.com/go-openapi/jsonpointer v1.0.0 h1:kR9tHqY0CtZaOPVFm622dPVNhrvYpwr4uCxgL3h1H8s= github.com/go-openapi/jsonpointer v1.0.0/go.mod h1:Z3rw7dWu1p9IgitXCFamSlA5lmDiklEB6vkaxcNZW5Y= github.com/go-openapi/jsonreference v1.0.0 h1:jlmTr6torcd1YgDQvSfNmRtKzYDO4FGBkrAdlAVWnpY= @@ -79,6 +95,17 @@ github.com/klauspost/compress v1.19.1 h1:VsB4HPswih7mmZ8WleSFQ75c/Ui1M4trX5oAsJn github.com/klauspost/compress v1.19.1/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ= github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= +github.com/lufia/plan9stats v0.0.0-20260330125221-c963978e514e h1:Q6MvJtQK/iRcRtzAscm/zF23XxJlbECiGPyRicsX+Ak= +github.com/magiconair/properties v1.8.10 h1:s31yESBquKXCV9a/ScB3ESkOjUYYv+X0rg8SYxI99mE= +github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0= +github.com/moby/go-archive v0.2.0 h1:zg5QDUM2mi0JIM9fdQZWC7U8+2ZfixfTYoHL7rWUcP8= +github.com/moby/moby/api v1.55.0 h1:2/sexvQyqIWS8pRSCFddBfpW2qE7vR7FCL+vN8pxwMc= +github.com/moby/moby/client v0.5.1 h1:tYNaJno4c0HXz12y5BiqEDy0rVTYkWzI26lGvnTMiJw= +github.com/moby/patternmatcher v0.6.1 h1:qlhtafmr6kgMIJjKJMDmMWq7WLkKIo23hsrpR3x084U= +github.com/moby/sys/sequential v0.7.0 h1:ASQNGNROJSuOO6LL6bPHbKvuZu6NU8P4ldPWk31zj/8= +github.com/moby/sys/user v0.4.0 h1:jhcMKit7SA80hivmFJcbB1vqmw//wU61Zdui2eQXuMs= +github.com/moby/sys/userns v0.1.0 h1:tVLXkFOxVu9A64/yh59slHVv9ahO9UIev4JZusOLG/g= +github.com/moby/term v0.5.2 h1:6qk3FJAFDs6i/q3W/pQ97SX192qKfZgGjCQqfCJkgzQ= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= @@ -97,11 +124,14 @@ github.com/onsi/ginkgo/v2 v2.27.4 h1:fcEcQW/A++6aZAZQNUmNjvA9PSOzefMJBerHJ4t8v8Y github.com/onsi/ginkgo/v2 v2.27.4/go.mod h1:ArE1D/XhNXBXCBkKOLkbsb2c81dQHCRcF5zwn/ykDRo= github.com/onsi/gomega v1.39.0 h1:y2ROC3hKFmQZJNFeGAMeHZKkjBL65mIZcvrLQBF9k6Q= github.com/onsi/gomega v1.39.0/go.mod h1:ZCU1pkQcXDO5Sl9/VVEGlDyp+zm0m1cmeG5TOzLgdh4= +github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U= +github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJwooC2xJA040= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 h1:o4JXh1EVt9k/+g42oCprj/FisM4qX9L3sZB3upGN2ZU= github.com/prometheus/client_golang v1.24.1 h1:JnJkREXzWxUdCuPFpIWZiPispT9xVV59uiuyR2bPlnU= github.com/prometheus/client_golang v1.24.1/go.mod h1:F+oSRECHg4sse5ucfYpYDeIv/hu68Zo0uoHKetWnzcE= github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk= @@ -110,6 +140,8 @@ github.com/prometheus/common v0.70.1 h1:1HvjP4D5oL3t8RsPlwxA9onvvStjtIHYE5XuuwOi github.com/prometheus/common v0.70.1/go.mod h1:VdFUQDMZK3VLkurFUVhia6uys/0suUp86TJz5qbJRhc= github.com/prometheus/procfs v0.21.1 h1:GljZCt+zSTS+NZq88cyQ1LjZ+RCHp3uVuabBWA5+OJI= github.com/prometheus/procfs v0.21.1/go.mod h1:aB55Cww9pdSJVHk0hUf0inxWyyjPogFIjmHKYgMKmtY= +github.com/shirou/gopsutil/v4 v4.26.6 h1:Mzr/npDtQC/xpeEuQKHZt8Zo9CmPvhTj8nkR8w5TLDs= +github.com/sirupsen/logrus v1.9.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w= github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk= github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= @@ -118,8 +150,17 @@ github.com/stretchr/objx v0.5.3/go.mod h1:rDQraq+vQZU7Fde9LOZLr8Tax6zZvy4kuNKF+Q github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/testcontainers/testcontainers-go v0.44.0 h1:/Fwh6HY1mIikhnm9e7HwoxGycx0lzRAE0f5VQpjFxzI= +github.com/tklauser/go-sysconf v0.4.0 h1:7H0uAN+7RkwWRaxhYXDLqa5V3LPrJeV8wmD9dRUgPQU= +github.com/tklauser/numcpus v0.12.0 h1:NR85qdvHA9pFse3x3weVZ0r0ST8R6l5RHbZrlRaqob4= github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM= github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg= +github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0= +go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0 h1:8tvICD4vSTOOsNrsI4Ljf6C+6UKvpTEH5XY3JMoyPoo= +go.opentelemetry.io/otel v1.44.0 h1:JjwHmHpA4iZ3wBxluu2fbbE7j4kqlE8jXyAyPXH7HqU= +go.opentelemetry.io/otel/metric v1.44.0 h1:1w0gILTcHdr3YI+ixLyjemwrVnsMURbTZFrSYCdDdmc= +go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/6gtIk= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= diff --git a/HadesScheduler/Readme.md b/HadesScheduler/Readme.md index d09e5499..0dea63bf 100644 --- a/HadesScheduler/Readme.md +++ b/HadesScheduler/Readme.md @@ -10,6 +10,12 @@ The scheduler subscribes to the priority-bucketed job subjects (`hades.jobs.{hig NATS (hades.jobs.*) ──► HadesScheduler ──► executor ──► containers (one per step) ``` +### Job leases and redelivery + +A pulled job stays leased until it is acknowledged. Because the Docker executor blocks for the whole job, the worker signals `InProgress` to JetStream every few seconds while the job runs, which keeps resetting the `NATS_ACK_WAIT` timer. A job is therefore only redelivered when the worker itself stops responding (crash, OOM kill, pod eviction, network partition) - never because it runs for a long time, including a job running all the way to its `timeout_seconds`. + +`NATS_MAX_DELIVER` (default `3`) bounds how often a job that keeps taking down its worker is retried. The last delivery is not executed: it publishes a terminal `Failed` status (with a reason explaining the redeliveries) and drops the job, so a poisonous job neither loops forever nor disappears without a status. + ## Executors ### Docker (`HADES_EXECUTOR=docker`) - local development @@ -22,7 +28,7 @@ The scheduler creates a `BuildJob` custom resource; the [HadesOperator](HadesOpe ## Configuration -Common variables: `HADES_EXECUTOR` (default `docker`), `CONCURRENCY` (default `1`), `NATS_URL`, and the executor-specific `DOCKER_*` or `K8S_*` variables. See [docs/configuration.md](../docs/configuration.md) for the complete list. +Common variables: `HADES_EXECUTOR` (default `docker`), `CONCURRENCY` (default `1`), `NATS_URL`, `NATS_ACK_WAIT` (default `1m`), `NATS_MAX_DELIVER` (default `3`), and the executor-specific `DOCKER_*` or `K8S_*` variables. See [docs/configuration.md](../docs/configuration.md) for the complete list. ## Run locally diff --git a/HadesScheduler/go.sum b/HadesScheduler/go.sum index 1defe5b6..3e32e6b7 100644 --- a/HadesScheduler/go.sum +++ b/HadesScheduler/go.sum @@ -1,15 +1,20 @@ +dario.cat/mergo v1.0.2 h1:85+piFYR1tMbRrLcDwR18y4UKJ3aH1Tbzi24VRW1TK8= github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c h1:udKWzYgxTojEKWjV8V+WSxDXJ4NFATAsZjh8iIbsQIg= github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY= github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU= github.com/caarlos0/env/v11 v11.4.1 h1:fYwH0sWEsBSMPG7t4e/PEfTFzrWrpjyygXyUnWiSwEw= github.com/caarlos0/env/v11 v11.4.1/go.mod h1:qupehSf/Y0TUTsxKywqRt/vJjN5nz6vauiYEUUr8P4U= +github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/containerd/errdefs v1.0.0 h1:tg5yIfIlQIrxYtu9ajqY42W3lpS19XqdxRQeEwYG8PI= github.com/containerd/errdefs v1.0.0/go.mod h1:+YBYIdtsnF4Iw6nWZhJcqGSg/dwvV7tyJ/kCkyJ2k+M= github.com/containerd/errdefs/pkg v0.3.0 h1:9IKJ06FvyNlexW690DXuQNx2KA2cUJXx151Xdx3ZPPE= github.com/containerd/errdefs/pkg v0.3.0/go.mod h1:NJw6s9HwNuRhnjJhM7pylWwMyAkmCQvQ4GpJHEqRLVk= +github.com/containerd/log v0.1.0 h1:TCJt7ioM2cr/tfR8GPbGf9/VRAX8D2B4PjzCpfX540I= +github.com/containerd/platforms v0.2.1 h1:zvwtM3rz2YHPQsF2CHYM8+KtB5dvhISiXh5ZpSBQv6A= +github.com/cpuguy83/dockercfg v0.3.2 h1:DlJTyZGBDlXqUZ2Dk2Q3xHs/FtnooJJVaad2S9GKorA= github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s= github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -22,6 +27,7 @@ github.com/docker/go-connections v0.8.1 h1:JibmG5hULs5qXSr/cp/w3Pw5fZuStt4MOHMUE github.com/docker/go-connections v0.8.1/go.mod h1:no1qkHdjq7kLMGUXYAduOhYPSJxxvgWBh7ogVvptn3Q= github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4= github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= +github.com/ebitengine/purego v0.10.1 h1:dewVBCBT2GaMu1SrNTYxQhgQBethzfhiwvZiLGP/qyY= github.com/emicklei/go-restful/v3 v3.13.0 h1:C4Bl2xDndpU6nJ4bc1jXd+uTmYPVUwkD6bFY/oTyCes= github.com/emicklei/go-restful/v3 v3.13.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc= @@ -33,6 +39,7 @@ github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8= github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= +github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE= github.com/go-openapi/jsonpointer v1.0.0 h1:kR9tHqY0CtZaOPVFm622dPVNhrvYpwr4uCxgL3h1H8s= github.com/go-openapi/jsonpointer v1.0.0/go.mod h1:Z3rw7dWu1p9IgitXCFamSlA5lmDiklEB6vkaxcNZW5Y= github.com/go-openapi/jsonreference v1.0.0 h1:jlmTr6torcd1YgDQvSfNmRtKzYDO4FGBkrAdlAVWnpY= @@ -84,12 +91,19 @@ github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/lufia/plan9stats v0.0.0-20260330125221-c963978e514e h1:Q6MvJtQK/iRcRtzAscm/zF23XxJlbECiGPyRicsX+Ak= +github.com/magiconair/properties v1.8.10 h1:s31yESBquKXCV9a/ScB3ESkOjUYYv+X0rg8SYxI99mE= github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0= github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo= +github.com/moby/go-archive v0.2.0 h1:zg5QDUM2mi0JIM9fdQZWC7U8+2ZfixfTYoHL7rWUcP8= github.com/moby/moby/api v1.55.0 h1:2/sexvQyqIWS8pRSCFddBfpW2qE7vR7FCL+vN8pxwMc= github.com/moby/moby/api v1.55.0/go.mod h1:+RQ6wluLwtYaTd1WnPLykIDPekkuyD/ROWQClE83pzs= github.com/moby/moby/client v0.5.1 h1:tYNaJno4c0HXz12y5BiqEDy0rVTYkWzI26lGvnTMiJw= github.com/moby/moby/client v0.5.1/go.mod h1:odLstlZ6uSnfvAgVxMpvgmb8SUdd+siH2T0GBuxVAlM= +github.com/moby/patternmatcher v0.6.1 h1:qlhtafmr6kgMIJjKJMDmMWq7WLkKIo23hsrpR3x084U= +github.com/moby/sys/sequential v0.7.0 h1:ASQNGNROJSuOO6LL6bPHbKvuZu6NU8P4ldPWk31zj/8= +github.com/moby/sys/user v0.4.0 h1:jhcMKit7SA80hivmFJcbB1vqmw//wU61Zdui2eQXuMs= +github.com/moby/sys/userns v0.1.0 h1:tVLXkFOxVu9A64/yh59slHVv9ahO9UIev4JZusOLG/g= github.com/moby/term v0.5.2 h1:6qk3FJAFDs6i/q3W/pQ97SX192qKfZgGjCQqfCJkgzQ= github.com/moby/term v0.5.2/go.mod h1:d3djjFCrjnB+fl8NJux+EJzu0msscUP+f8it8hPkFLc= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= @@ -113,8 +127,11 @@ github.com/opencontainers/image-spec v1.1.1/go.mod h1:qpqAh3Dmcf36wStyyWU+kCeDgr github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 h1:o4JXh1EVt9k/+g42oCprj/FisM4qX9L3sZB3upGN2ZU= github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= +github.com/shirou/gopsutil/v4 v4.26.6 h1:Mzr/npDtQC/xpeEuQKHZt8Zo9CmPvhTj8nkR8w5TLDs= +github.com/sirupsen/logrus v1.9.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w= github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk= github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= @@ -123,8 +140,12 @@ github.com/stretchr/objx v0.5.3/go.mod h1:rDQraq+vQZU7Fde9LOZLr8Tax6zZvy4kuNKF+Q github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/testcontainers/testcontainers-go v0.44.0 h1:/Fwh6HY1mIikhnm9e7HwoxGycx0lzRAE0f5VQpjFxzI= +github.com/tklauser/go-sysconf v0.4.0 h1:7H0uAN+7RkwWRaxhYXDLqa5V3LPrJeV8wmD9dRUgPQU= +github.com/tklauser/numcpus v0.12.0 h1:NR85qdvHA9pFse3x3weVZ0r0ST8R6l5RHbZrlRaqob4= github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM= github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg= +github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0= go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0 h1:8tvICD4vSTOOsNrsI4Ljf6C+6UKvpTEH5XY3JMoyPoo= diff --git a/HadesScheduler/main.go b/HadesScheduler/main.go index e31f9411..d43a619b 100644 --- a/HadesScheduler/main.go +++ b/HadesScheduler/main.go @@ -19,8 +19,8 @@ import ( // HadesSchedulerConfig holds the scheduler's runtime configuration. The // executor is selected separately via utils.ExecutorConfig (HADES_EXECUTOR). type HadesSchedulerConfig struct { - Concurrency uint `env:"CONCURRENCY" envDefault:"1"` - NatsConfig hadesnats.ConnectionConfig + ConsumerConfig hadesnats.ConsumerConfig + NatsConfig hadesnats.ConnectionConfig } func main() { @@ -40,9 +40,11 @@ func main() { slog.Info("HadesScheduler configuration", "executor", executorCfg.Executor, - "concurrency", cfg.Concurrency, + "concurrency", cfg.ConsumerConfig.Concurrency, "nats_url", cfg.NatsConfig.URL, "nats_tls", cfg.NatsConfig.TLS, + "nats_ack_wait", cfg.ConsumerConfig.AckWait, + "nats_max_deliver", cfg.ConsumerConfig.MaxDeliver, ) natsConn, err := hadesnats.SetupDefaultNatsConnection(cfg.NatsConfig) @@ -52,7 +54,7 @@ func main() { } defer natsConn.Close() - consumer, err := hadesnats.NewHadesConsumer(natsConn, cfg.Concurrency) + consumer, err := hadesnats.NewHadesConsumer(natsConn, cfg.ConsumerConfig) if err != nil { slog.Error("Failed to create Hades consumer", "error", err) os.Exit(1) diff --git a/docs/configuration.md b/docs/configuration.md index 92c8bfee..87eb8c76 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -32,7 +32,7 @@ Every component connects to NATS with the same `ConnectionConfig`. Plus the [NATS](#nats-connection-all-components) and [global](#global-all-components) variables. -> **Reserved (not yet implemented):** `PROMETHEUS_ADDRESS`, `RETENTION_IN_MIN`, `MAX_RETRIES`, and `TIMEOUT_IN_MIN` appear in `.env.example` and some compose files but are **not read by any component today**. They are placeholders for planned features and currently have no effect. (Note: a per-job timeout *is* supported, but it is set on the job payload as `timeout_seconds`, not via this env var - see [API: `Step`/`QueuePayload`](./api.md#queuepayload).) +> **Reserved (not yet implemented):** `PROMETHEUS_ADDRESS`, `RETENTION_IN_MIN`, `MAX_RETRIES`, and `TIMEOUT_IN_MIN` appear in `.env.example` and some compose files but are **not read by any component today**. They are placeholders for planned features and currently have no effect. (Note: a per-job timeout *is* supported, but it is set on the job payload as `timeout_seconds`, not via this env var - see [API: `Step`/`QueuePayload`](./api.md#queuepayload). How often a job is retried after its worker died is bounded by the scheduler's `NATS_MAX_DELIVER`, not by `MAX_RETRIES`.) > > **Per-job/per-step resource controls** are set on the job payload, not via environment variables: `timeout_seconds` (job), and per-step `cpu_limit`, `memory_limit`, `network`, `memory_swap`, `pids_limit`. Timeout, CPU, memory and environment variables are enforced on both executors; `network`, `memory_swap` and `pids_limit` are Docker-executor only (Kubernetes has no per-container swap/PID field, and a pod's containers share one network namespace). See [api.md](./api.md#step). @@ -40,7 +40,9 @@ Plus the [NATS](#nats-connection-all-components) and [global](#global-all-compon | Variable | Default | Description | Source | | -------- | ------- | ----------- | ------ | -| `CONCURRENCY` | `1` | Number of jobs processed concurrently. | `HadesScheduler/main.go` (`HadesSchedulerConfig`) | +| `CONCURRENCY` | `1` | Number of jobs processed concurrently. | `shared/nats/consumer.go` (`ConsumerConfig`) | +| `NATS_ACK_WAIT` | `1m` | How long JetStream waits for an ack before redelivering a job to another worker. This is a liveness backstop, **not** a job-duration budget: a worker signals progress every few seconds while a job runs, so jobs of any length (including ones running to their `timeout_seconds`) are never redelivered while the worker is alive. Lower it for faster recovery after a scheduler crash, raise it if the network is flaky. | `shared/nats/consumer.go` (`ConsumerConfig`) | +| `NATS_MAX_DELIVER` | `3` | Maximum number of times a single job is delivered. The last delivery is not executed: it is used to publish a terminal `Failed` status and drop the job, so the default allows two execution attempts before Hades gives up on a job that keeps crashing or stalling its worker. | `shared/nats/consumer.go` (`ConsumerConfig`) | | `HADES_EXECUTOR` | `docker` | Execution platform: `docker` or `k8s`. | `shared/utils/config.go` (`ExecutorConfig`) | Plus the [NATS](#nats-connection-all-components) and [global](#global-all-components) variables, and - depending on `HADES_EXECUTOR` - the Docker or Kubernetes variables below. diff --git a/shared/go.mod b/shared/go.mod index de490994..159d1a16 100644 --- a/shared/go.mod +++ b/shared/go.mod @@ -8,18 +8,58 @@ require ( github.com/joho/godotenv v1.5.1 github.com/nats-io/nats.go v1.52.0 github.com/stretchr/testify v1.11.1 + github.com/testcontainers/testcontainers-go v0.44.0 ) require ( + dario.cat/mergo v1.0.2 // indirect + github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c // indirect + github.com/Microsoft/go-winio v0.6.2 // indirect + github.com/cenkalti/backoff/v4 v4.3.0 // indirect + github.com/cespare/xxhash/v2 v2.3.0 // indirect + github.com/containerd/errdefs v1.0.0 // indirect + github.com/containerd/errdefs/pkg v0.3.0 // indirect + github.com/containerd/log v0.1.0 // indirect + github.com/containerd/platforms v0.2.1 // indirect + github.com/cpuguy83/dockercfg v0.3.2 // indirect github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect + github.com/distribution/reference v0.6.0 // indirect + github.com/docker/go-connections v0.8.1 // indirect + github.com/docker/go-units v0.5.0 // indirect + github.com/ebitengine/purego v0.10.1 // indirect + github.com/felixge/httpsnoop v1.1.0 // indirect + github.com/go-logr/logr v1.4.4 // indirect + github.com/go-logr/stdr v1.2.2 // indirect + github.com/go-ole/go-ole v1.3.0 // indirect github.com/klauspost/compress v1.19.1 // indirect - github.com/kr/pretty v0.3.1 // indirect + github.com/lufia/plan9stats v0.0.0-20260330125221-c963978e514e // indirect + github.com/magiconair/properties v1.8.10 // indirect + github.com/moby/docker-image-spec v1.3.1 // indirect + github.com/moby/go-archive v0.2.0 // indirect + github.com/moby/moby/api v1.55.0 // indirect + github.com/moby/moby/client v0.5.1 // indirect + github.com/moby/patternmatcher v0.6.1 // indirect + github.com/moby/sys/sequential v0.7.0 // indirect + github.com/moby/sys/user v0.4.0 // indirect + github.com/moby/sys/userns v0.1.0 // indirect + github.com/moby/term v0.5.2 // indirect github.com/nats-io/nkeys v0.4.16 // indirect github.com/nats-io/nuid v1.0.1 // indirect + github.com/opencontainers/go-digest v1.0.0 // indirect + github.com/opencontainers/image-spec v1.1.1 // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect - github.com/rogpeppe/go-internal v1.14.1 // indirect + github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect + github.com/shirou/gopsutil/v4 v4.26.6 // indirect + github.com/sirupsen/logrus v1.9.4 // indirect + github.com/tklauser/go-sysconf v0.4.0 // indirect + github.com/tklauser/numcpus v0.12.0 // indirect + github.com/yusufpapurcu/wmi v1.2.4 // indirect + go.opentelemetry.io/auto/sdk v1.2.1 // indirect + go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0 // indirect + go.opentelemetry.io/otel v1.44.0 // indirect + go.opentelemetry.io/otel/metric v1.44.0 // indirect + go.opentelemetry.io/otel/trace v1.44.0 // indirect golang.org/x/crypto v0.54.0 // indirect golang.org/x/sys v0.47.0 // indirect - gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/shared/go.sum b/shared/go.sum index dc4849e8..bd7413a1 100644 --- a/shared/go.sum +++ b/shared/go.sum @@ -1,41 +1,142 @@ +dario.cat/mergo v1.0.2 h1:85+piFYR1tMbRrLcDwR18y4UKJ3aH1Tbzi24VRW1TK8= +dario.cat/mergo v1.0.2/go.mod h1:E/hbnu0NxMFBjpMIE34DRGLWqDy0g5FuKDhCb31ngxA= +github.com/AdaLogics/go-fuzz-headers v0.0.0-20240806141605-e8a1dd7889d6 h1:He8afgbRMd7mFxO99hRNu+6tazq8nFF9lIwo9JFroBk= +github.com/AdaLogics/go-fuzz-headers v0.0.0-20240806141605-e8a1dd7889d6/go.mod h1:8o94RPi1/7XTJvwPpRSzSUedZrtlirdB3r9Z20bi2f8= +github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c h1:udKWzYgxTojEKWjV8V+WSxDXJ4NFATAsZjh8iIbsQIg= +github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= +github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY= +github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU= github.com/caarlos0/env/v11 v11.4.1 h1:fYwH0sWEsBSMPG7t4e/PEfTFzrWrpjyygXyUnWiSwEw= github.com/caarlos0/env/v11 v11.4.1/go.mod h1:qupehSf/Y0TUTsxKywqRt/vJjN5nz6vauiYEUUr8P4U= -github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= +github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8= +github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE= +github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= +github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/containerd/errdefs v1.0.0 h1:tg5yIfIlQIrxYtu9ajqY42W3lpS19XqdxRQeEwYG8PI= +github.com/containerd/errdefs v1.0.0/go.mod h1:+YBYIdtsnF4Iw6nWZhJcqGSg/dwvV7tyJ/kCkyJ2k+M= +github.com/containerd/errdefs/pkg v0.3.0 h1:9IKJ06FvyNlexW690DXuQNx2KA2cUJXx151Xdx3ZPPE= +github.com/containerd/errdefs/pkg v0.3.0/go.mod h1:NJw6s9HwNuRhnjJhM7pylWwMyAkmCQvQ4GpJHEqRLVk= +github.com/containerd/log v0.1.0 h1:TCJt7ioM2cr/tfR8GPbGf9/VRAX8D2B4PjzCpfX540I= +github.com/containerd/log v0.1.0/go.mod h1:VRRf09a7mHDIRezVKTRCrOq78v577GXq3bSa3EhrzVo= +github.com/containerd/platforms v0.2.1 h1:zvwtM3rz2YHPQsF2CHYM8+KtB5dvhISiXh5ZpSBQv6A= +github.com/containerd/platforms v0.2.1/go.mod h1:XHCb+2/hzowdiut9rkudds9bE5yJ7npe7dG/wG+uFPw= +github.com/cpuguy83/dockercfg v0.3.2 h1:DlJTyZGBDlXqUZ2Dk2Q3xHs/FtnooJJVaad2S9GKorA= +github.com/cpuguy83/dockercfg v0.3.2/go.mod h1:sugsbF4//dDlL/i+S+rtpIWp+5h0BHJHfjj5/jFyUJc= +github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s= +github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk= +github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E= +github.com/docker/go-connections v0.8.1 h1:JibmG5hULs5qXSr/cp/w3Pw5fZuStt4MOHMUExb29/M= +github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4= +github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= +github.com/ebitengine/purego v0.10.1 h1:dewVBCBT2GaMu1SrNTYxQhgQBethzfhiwvZiLGP/qyY= +github.com/ebitengine/purego v0.10.1/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ= +github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc= +github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE= +github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= +github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8= +github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= +github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= +github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0= +github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE= +github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78= +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= github.com/klauspost/compress v1.19.1 h1:VsB4HPswih7mmZ8WleSFQ75c/Ui1M4trX5oAsJnhSlk= github.com/klauspost/compress v1.19.1/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ= -github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= -github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= -github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/lufia/plan9stats v0.0.0-20260330125221-c963978e514e h1:Q6MvJtQK/iRcRtzAscm/zF23XxJlbECiGPyRicsX+Ak= +github.com/lufia/plan9stats v0.0.0-20260330125221-c963978e514e/go.mod h1:autxFIvghDt3jPTLoqZ9OZ7s9qTGNAWmYCjVFWPX/zg= +github.com/magiconair/properties v1.8.10 h1:s31yESBquKXCV9a/ScB3ESkOjUYYv+X0rg8SYxI99mE= +github.com/magiconair/properties v1.8.10/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0= +github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0= +github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo= +github.com/moby/go-archive v0.2.0 h1:zg5QDUM2mi0JIM9fdQZWC7U8+2ZfixfTYoHL7rWUcP8= +github.com/moby/go-archive v0.2.0/go.mod h1:mNeivT14o8xU+5q1YnNrkQVpK+dnNe/K6fHqnTg4qPU= +github.com/moby/moby/api v1.55.0 h1:2/sexvQyqIWS8pRSCFddBfpW2qE7vR7FCL+vN8pxwMc= +github.com/moby/moby/api v1.55.0/go.mod h1:+RQ6wluLwtYaTd1WnPLykIDPekkuyD/ROWQClE83pzs= +github.com/moby/moby/client v0.5.1 h1:tYNaJno4c0HXz12y5BiqEDy0rVTYkWzI26lGvnTMiJw= +github.com/moby/patternmatcher v0.6.1 h1:qlhtafmr6kgMIJjKJMDmMWq7WLkKIo23hsrpR3x084U= +github.com/moby/patternmatcher v0.6.1/go.mod h1:hDPoyOpDY7OrrMDLaYoY3hf52gNCR/YOUYxkhApJIxc= +github.com/moby/sys/sequential v0.7.0 h1:ASQNGNROJSuOO6LL6bPHbKvuZu6NU8P4ldPWk31zj/8= +github.com/moby/sys/sequential v0.7.0/go.mod h1:NfSTAp6V3fw4tmkD62PEcOKeZKquXT8VKCkf7aVR79o= +github.com/moby/sys/user v0.4.0 h1:jhcMKit7SA80hivmFJcbB1vqmw//wU61Zdui2eQXuMs= +github.com/moby/sys/user v0.4.0/go.mod h1:bG+tYYYJgaMtRKgEmuueC0hJEAZWwtIbZTB+85uoHjs= +github.com/moby/sys/userns v0.1.0 h1:tVLXkFOxVu9A64/yh59slHVv9ahO9UIev4JZusOLG/g= +github.com/moby/sys/userns v0.1.0/go.mod h1:IHUYgu/kao6N8YZlp9Cf444ySSvCmDlmzUcYfDHOl28= +github.com/moby/term v0.5.2 h1:6qk3FJAFDs6i/q3W/pQ97SX192qKfZgGjCQqfCJkgzQ= +github.com/moby/term v0.5.2/go.mod h1:d3djjFCrjnB+fl8NJux+EJzu0msscUP+f8it8hPkFLc= github.com/nats-io/nats.go v1.52.0 h1:n3avV4VBsCgsdwh71TppsTwtv+QdPs7ntSKM8qJLGsc= github.com/nats-io/nats.go v1.52.0/go.mod h1:26HypzazeOkyO3/mqd1zZd53STJN0EjCYF9Uy2ZOBno= github.com/nats-io/nkeys v0.4.16 h1:rd5oAuLOb8mnAycB0xleuEBNS1pVVnN0fv/FF34Eypg= github.com/nats-io/nkeys v0.4.16/go.mod h1:llLgWoI0o4z/Q57q2R1kHfmocyhGV6VG/U18Glg1Afs= github.com/nats-io/nuid v1.0.1 h1:5iA8DT8V7q8WK2EScv2padNa/rTESc1KdnPw4TC2paw= github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c= -github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= +github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U= +github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= +github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJwooC2xJA040= +github.com/opencontainers/image-spec v1.1.1/go.mod h1:qpqAh3Dmcf36wStyyWU+kCeDgrGnAve2nCC8+7h8Q0M= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= +github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 h1:o4JXh1EVt9k/+g42oCprj/FisM4qX9L3sZB3upGN2ZU= +github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE= github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= +github.com/shirou/gopsutil/v4 v4.26.6 h1:Mzr/npDtQC/xpeEuQKHZt8Zo9CmPvhTj8nkR8w5TLDs= +github.com/shirou/gopsutil/v4 v4.26.6/go.mod h1:LZ6ewCSkBqUpvSOf+LsTGnRinC6iaNUNMGBtDkJBaLQ= +github.com/sirupsen/logrus v1.9.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w= +github.com/sirupsen/logrus v1.9.4/go.mod h1:ftWc9WdOfJ0a92nsE2jF5u5ZwH8Bv2zdeOC42RjbV2g= +github.com/stretchr/objx v0.5.3 h1:jmXUvGomnU1o3W/V5h2VEradbpJDwGrzugQQvL0POH4= +github.com/stretchr/objx v0.5.3/go.mod h1:rDQraq+vQZU7Fde9LOZLr8Tax6zZvy4kuNKF+QYS+U0= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/testcontainers/testcontainers-go v0.44.0 h1:/Fwh6HY1mIikhnm9e7HwoxGycx0lzRAE0f5VQpjFxzI= +github.com/testcontainers/testcontainers-go v0.44.0/go.mod h1:IcnwQrYTO86xHXu5bvMaBH7ATlbS3Qn1M1QWW3c66rE= +github.com/tklauser/go-sysconf v0.4.0 h1:7H0uAN+7RkwWRaxhYXDLqa5V3LPrJeV8wmD9dRUgPQU= +github.com/tklauser/go-sysconf v0.4.0/go.mod h1:8mTNWyog7H+MpKijp4VmKJAd2bbYQ2zuUwkYRbUArPI= +github.com/tklauser/numcpus v0.12.0 h1:NR85qdvHA9pFse3x3weVZ0r0ST8R6l5RHbZrlRaqob4= +github.com/tklauser/numcpus v0.12.0/go.mod h1:ABHeXzJnr/qqwguhClkZKT1/8VABcYrsyUiUGobwWJg= +github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0= +github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0= +go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= +go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0 h1:8tvICD4vSTOOsNrsI4Ljf6C+6UKvpTEH5XY3JMoyPoo= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0/go.mod h1:z9+yiacE0IHRqM4qFfkbt/JYlmYXgss8GY/jXoNuPJI= +go.opentelemetry.io/otel v1.44.0 h1:JjwHmHpA4iZ3wBxluu2fbbE7j4kqlE8jXyAyPXH7HqU= +go.opentelemetry.io/otel v1.44.0/go.mod h1:BMgjTHL9WPRlRjL2oZCBTL4whCGtXch2H4BhOPIAyYc= +go.opentelemetry.io/otel/metric v1.44.0 h1:1w0gILTcHdr3YI+ixLyjemwrVnsMURbTZFrSYCdDdmc= +go.opentelemetry.io/otel/metric v1.44.0/go.mod h1:8O7hanEPBNgEMmybD3s2VBKcgWOCsA6tzHBPODAiquo= +go.opentelemetry.io/otel/sdk v1.44.0 h1:nHYwb9lK+fJPU/dnT6s7W7Z8itMWyqrnVfbheVYrZ58= +go.opentelemetry.io/otel/sdk v1.44.0/go.mod h1:Osuydd3Se74nqjAKxid74N5eC+jfEqfTegHRnq58oK0= +go.opentelemetry.io/otel/sdk/metric v1.44.0 h1:3LlKgI+VjbVsjNRFZJZAJ30WjXC5VkNRks6si09iEfI= +go.opentelemetry.io/otel/sdk/metric v1.44.0/go.mod h1:5B5pMARnXxKhltooO4xUuCBorl65a4EpnTalObqOigA= +go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/6gtIk= +go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE= golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw= golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk= +golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs= golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/term v0.45.0 h1:NwWyBmoJCbfTHpxrWoZ9C6/VxOf7ic219I8xZZFdrf0= +golang.org/x/term v0.45.0/go.mod h1:9aqxs0blBcrm/n0L9QW0aRVD+ktan8ssZromtqJC43w= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gotest.tools/v3 v3.5.2 h1:7koQfIKdy+I8UTetycgUqXWSDwpgv193Ka+qRsmBY8Q= +gotest.tools/v3 v3.5.2/go.mod h1:LtdLGcnqToBH83WByAAi/wiwSFCArdFIUV/xxN4pcjA= +pgregory.net/rapid v1.2.0 h1:keKAYRcjm+e1F0oAuU5F5+YPAWcyxNNRK2wud503Gnk= +pgregory.net/rapid v1.2.0/go.mod h1:PY5XlDGj0+V1FCq0o192FdRhpKHGTRIWBgqjDBTrq04= diff --git a/shared/nats/ackprogress_test.go b/shared/nats/ackprogress_test.go new file mode 100644 index 00000000..2aa8637e --- /dev/null +++ b/shared/nats/ackprogress_test.go @@ -0,0 +1,97 @@ +package nats + +import ( + "errors" + "sync/atomic" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestAckProgressInterval(t *testing.T) { + tests := []struct { + name string + ackWait time.Duration + want time.Duration + }{ + {"default ack wait is capped", DefaultAckWait, maxAckProgressInterval}, + {"long ack wait is capped", 1 * time.Hour, maxAckProgressInterval}, + {"short ack wait scales down", 3 * time.Second, 1 * time.Second}, + {"tiny ack wait hits the floor", 10 * time.Millisecond, minAckProgressInterval}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equal(t, tt.want, ackProgressInterval(tt.ackWait)) + // The heartbeat must always be well below AckWait, otherwise it + // cannot reset the ack timer in time. + if tt.ackWait > minAckProgressInterval { + assert.Less(t, ackProgressInterval(tt.ackWait), tt.ackWait) + } + }) + } +} + +func TestConsumerConfigWithDefaults(t *testing.T) { + cfg := ConsumerConfig{}.withDefaults() + assert.Equal(t, uint(1), cfg.Concurrency) + assert.Equal(t, DefaultAckWait, cfg.AckWait) + assert.Equal(t, DefaultMaxDeliver, cfg.MaxDeliver) + + // MaxDeliver must never end up unlimited (0), which is the JetStream default. + assert.Positive(t, ConsumerConfig{MaxDeliver: -1}.withDefaults().MaxDeliver) + + // Explicit values are kept. + custom := ConsumerConfig{Concurrency: 4, AckWait: 5 * time.Second, MaxDeliver: 2}.withDefaults() + assert.Equal(t, ConsumerConfig{Concurrency: 4, AckWait: 5 * time.Second, MaxDeliver: 2}, custom) +} + +func TestStartAckProgressSignalsRepeatedly(t *testing.T) { + var calls atomic.Int64 + stop := startAckProgress(func() error { + calls.Add(1) + return nil + }, 10*time.Millisecond, "job-1") + + assert.Eventually(t, func() bool { return calls.Load() >= 3 }, 2*time.Second, 5*time.Millisecond, + "expected repeated in-progress signals while the job is running") + + stop() +} + +// TestStartAckProgressStopIsFinalAndIdempotent guards the two failure modes of +// the heartbeat goroutine: leaking past the job, and signalling in-progress on a +// message that has already been acked or naked. +func TestStartAckProgressStopIsFinalAndIdempotent(t *testing.T) { + var calls atomic.Int64 + stop := startAckProgress(func() error { + calls.Add(1) + return nil + }, time.Millisecond, "job-1") + + assert.Eventually(t, func() bool { return calls.Load() > 0 }, 2*time.Second, time.Millisecond) + + stop() + after := calls.Load() + + // Calling stop twice (defer plus explicit call in processJob) must not panic + // on a closed channel or block. + require.NotPanics(t, stop) + + time.Sleep(50 * time.Millisecond) + assert.Equal(t, after, calls.Load(), "in-progress must not be signalled after stop returns") +} + +func TestStartAckProgressSurvivesSignalErrors(t *testing.T) { + var calls atomic.Int64 + stop := startAckProgress(func() error { + calls.Add(1) + return errors.New("connection closed") + }, time.Millisecond, "job-1") + defer stop() + + // A failed heartbeat is logged, not fatal: the next tick tries again. + assert.Eventually(t, func() bool { return calls.Load() >= 3 }, 2*time.Second, time.Millisecond) +} diff --git a/shared/nats/consumer.go b/shared/nats/consumer.go index 7e5863fd..b1cc4003 100644 --- a/shared/nats/consumer.go +++ b/shared/nats/consumer.go @@ -12,6 +12,7 @@ import ( "github.com/google/uuid" hades "github.com/hades-scheduler/hades/shared" + "github.com/hades-scheduler/hades/shared/buildstatus" "github.com/hades-scheduler/hades/shared/payload" "github.com/nats-io/nats.go" "github.com/nats-io/nats.go/jetstream" @@ -19,17 +20,92 @@ import ( var _ hades.JobConsumer = (*HadesNATSConsumer)(nil) +const ( + // DefaultAckWait is how long JetStream waits for an ack (or an in-progress + // signal) before it redelivers a job to another worker. It is deliberately + // unrelated to how long a job runs: while a job is being processed the + // worker resets this timer every ackProgressInterval (see startAckProgress), + // so AckWait only bounds how long an *unresponsive* worker keeps a job + // hostage. One minute means a crashed or partitioned scheduler releases its + // in-flight jobs quickly, while still tolerating six consecutive lost + // heartbeats before a healthy worker's job is handed to someone else. + DefaultAckWait = 1 * time.Minute + + // DefaultMaxDeliver bounds how often a single job may be delivered. Without + // it JetStream retries forever, so a job that reliably kills its worker + // loops for the stream's whole 24h retention. The last delivery is not + // executed: it is used to report the terminal failure and terminate the + // message (see processJob), so the default allows two execution attempts. + DefaultMaxDeliver = 3 + + // maxAckProgressInterval caps the in-progress heartbeat so a long AckWait + // does not lead to a needlessly coarse heartbeat. + maxAckProgressInterval = 10 * time.Second + + // minAckProgressInterval keeps the heartbeat from becoming a busy loop when + // a very small AckWait is configured (mainly in tests). + minAckProgressInterval = 100 * time.Millisecond +) + +// ConsumerConfig holds the tunables of the JetStream job consumer. +// Zero values fall back to the defaults above. +type ConsumerConfig struct { + // Concurrency is the maximum number of jobs processed simultaneously by a + // single scheduler instance. + Concurrency uint `env:"CONCURRENCY" envDefault:"1"` + // AckWait is the JetStream ack timeout for an in-flight job. See + // DefaultAckWait: it is a liveness backstop, not a job-duration budget. + AckWait time.Duration `env:"NATS_ACK_WAIT" envDefault:"1m"` + // MaxDeliver is the maximum number of times a single job is delivered. See + // DefaultMaxDeliver. + MaxDeliver int `env:"NATS_MAX_DELIVER" envDefault:"3"` +} + +// withDefaults returns the config with non-positive values replaced by the +// package defaults. +func (c ConsumerConfig) withDefaults() ConsumerConfig { + if c.Concurrency == 0 { + c.Concurrency = 1 + } + if c.AckWait <= 0 { + c.AckWait = DefaultAckWait + } + if c.MaxDeliver <= 0 { + c.MaxDeliver = DefaultMaxDeliver + } + return c +} + +// ackProgressInterval returns how often an in-flight job signals progress for +// the given AckWait. It stays well below AckWait so several lost heartbeats do +// not trigger a redelivery. +func ackProgressInterval(ackWait time.Duration) time.Duration { + interval := ackWait / 3 + if interval > maxAckProgressInterval { + interval = maxAckProgressInterval + } + if interval < minAckProgressInterval { + interval = minAckProgressInterval + } + return interval +} + // HadesNATSConsumer manages job consumption from the NATS queue system with priority handling. type HadesNATSConsumer struct { natsConnection *nats.Conn concurrency uint + ackWait time.Duration + maxDeliver int consumers map[hades.Priority]jetstream.Consumer kv jetstream.KeyValue } // NewHadesConsumer creates a new job consumer with priority queue support. -// The concurrency parameter controls the maximum number of jobs processed simultaneously. -func NewHadesConsumer(nc *nats.Conn, concurrency uint) (*HadesNATSConsumer, error) { +// The config controls how many jobs are processed simultaneously and how +// JetStream redelivers jobs whose worker stops responding. +func NewHadesConsumer(nc *nats.Conn, cfg ConsumerConfig) (*HadesNATSConsumer, error) { + cfg = cfg.withDefaults() + ctx := context.Background() js, err := jetstream.New(nc) if err != nil { @@ -46,17 +122,23 @@ func NewHadesConsumer(nc *nats.Conn, concurrency uint) (*HadesNATSConsumer, erro Durable: consumerName, AckPolicy: jetstream.AckExplicitPolicy, FilterSubject: prioritySubject(priority), + // Set both explicitly instead of inheriting the client defaults + // (AckWait 30s, MaxDeliver unlimited): a 30s ack timeout redelivered + // every job that ran longer than half a minute, and an unlimited + // MaxDeliver turned any job that kills its worker into an endless + // loop. + AckWait: cfg.AckWait, + MaxDeliver: cfg.MaxDeliver, }) if err != nil { slog.Error("Failed to create JetStream consumer", "error", err, "priority", priority) return nil, err } consumers[priority] = cons - slog.Info("Created JetStream consumer", "consumer", consumerName, "priority", prioritySubject(priority)) + slog.Info("Created JetStream consumer", "consumer", consumerName, "priority", prioritySubject(priority), + "ack_wait", cfg.AckWait, "max_deliver", cfg.MaxDeliver) } - slog.Info("Created JetStream consumer", "consumers", consumers) - kv, err := js.CreateOrUpdateKeyValue(ctx, jetstream.KeyValueConfig{ Bucket: "HADES_JOBS", }) @@ -67,7 +149,9 @@ func NewHadesConsumer(nc *nats.Conn, concurrency uint) (*HadesNATSConsumer, erro return &HadesNATSConsumer{ natsConnection: nc, consumers: consumers, - concurrency: concurrency, + concurrency: cfg.Concurrency, + ackWait: cfg.AckWait, + maxDeliver: cfg.MaxDeliver, kv: kv, }, nil } @@ -160,6 +244,27 @@ func (hc *HadesNATSConsumer) processJob( priority hades.Priority, processing hades.PayloadHandler, ) { + // A job that reaches its last allowed delivery has already stalled or + // crashed a worker on every previous attempt. Running it once more would + // only burn another AckWait and then be dropped silently by JetStream, so + // the final delivery is spent reporting the terminal failure instead - the + // same Failed status the executors publish for any other job failure. + if numDelivered := deliveryCount(msg, job.ID.String()); numDelivered >= uint64(hc.maxDeliver) { + reason := fmt.Sprintf("job was delivered %d times without completing (max_deliver=%d); giving up", numDelivered, hc.maxDeliver) + slog.Error("Giving up on job after repeated redeliveries", + "workerID", workerID, + "jobID", job.ID.String(), + "priority", priority, + "numDelivered", numDelivered) + if err := publishJobStatus(hc.natsConnection, buildstatus.StatusFailed, job.ID.String(), reason); err != nil { + slog.Error("Failed to publish terminal failure status", "error", err, "jobID", job.ID.String()) + } + if err := msg.Term(); err != nil { + slog.Error("Failed to terminate exhausted message", "error", err, "jobID", job.ID.String()) + } + return + } + defer func() { if r := recover(); r != nil { slog.Error("Job processing panic", @@ -179,8 +284,24 @@ func (hc *HadesNATSConsumer) processJob( "jobID", job.ID.String(), "priority", priority) + // processing(job) blocks for the whole job on the Docker executor (it waits + // on every step's container). Without a heartbeat, any job longer than + // AckWait is redelivered and executed a second time while the first copy is + // still running - both copies then share the same shared- volume. + // Signalling in-progress resets the ack timer for as long as the job runs, + // however long that legitimately is. + // + // The stop function is registered as a defer so a panic in processing also + // stops it; it runs before the recover defer above (defers are LIFO) and so + // before the NAK. It is also called explicitly below so no heartbeat can + // race with the Ack. + stopAckProgress := startAckProgress(msg.InProgress, ackProgressInterval(hc.ackWait), job.ID.String()) + defer stopAckProgress() + processing(job) + stopAckProgress() + slog.Info("Worker finished job", "workerID", workerID, "jobID", job.ID.String(), @@ -194,6 +315,52 @@ func (hc *HadesNATSConsumer) processJob( } } +// deliveryCount reports how many times msg has been delivered, starting at 1 +// for the first delivery. It returns 0 if the metadata is unreadable, which +// keeps an unexpected message shape from being terminated as poisonous. +func deliveryCount(msg jetstream.Msg, jobID string) uint64 { + meta, err := msg.Metadata() + if err != nil { + slog.Warn("Failed to read message metadata", "error", err, "jobID", jobID) + return 0 + } + return meta.NumDelivered +} + +// startAckProgress repeatedly calls inProgress (jetstream.Msg.InProgress) every +// interval until the returned stop function is called, resetting the message's +// AckWait timer while the job runs. +// +// The returned stop function is idempotent and waits for the goroutine to exit, +// so once it returns, inProgress is guaranteed not to be called again - an +// in-progress signal sent after Ack/Nak would be an error on a terminated +// message. +func startAckProgress(inProgress func() error, interval time.Duration, jobID string) func() { + done := make(chan struct{}) + stopped := make(chan struct{}) + + go func() { + defer close(stopped) + ticker := time.NewTicker(interval) + defer ticker.Stop() + for { + select { + case <-done: + return + case <-ticker.C: + if err := inProgress(); err != nil { + slog.Warn("Failed to signal job progress to JetStream", "error", err, "jobID", jobID) + } + } + } + }() + + return sync.OnceFunc(func() { + close(done) + <-stopped + }) +} + // parseMessage handles message parsing and validation func (hc *HadesNATSConsumer) parseMessage(ctx context.Context, msg jetstream.Msg) (payload.QueuePayload, error) { var job payload.QueuePayload diff --git a/shared/nats/consumer_redelivery_test.go b/shared/nats/consumer_redelivery_test.go new file mode 100644 index 00000000..49a37043 --- /dev/null +++ b/shared/nats/consumer_redelivery_test.go @@ -0,0 +1,192 @@ +package nats + +import ( + "context" + "sync/atomic" + "testing" + "time" + + "github.com/google/uuid" + hades "github.com/hades-scheduler/hades/shared" + "github.com/hades-scheduler/hades/shared/buildstatus" + "github.com/hades-scheduler/hades/shared/payload" + "github.com/nats-io/nats.go" + "github.com/nats-io/nats.go/jetstream" + "github.com/stretchr/testify/suite" + "github.com/testcontainers/testcontainers-go" + "github.com/testcontainers/testcontainers-go/wait" +) + +const natsImage = "nats:2.11.4" + +// testAckWait is deliberately tiny so a "long-running" job in these tests only +// has to outlive a couple of seconds instead of the production AckWait. +const testAckWait = 2 * time.Second + +// ConsumerRedeliverySuite exercises the JetStream redelivery behaviour of +// HadesNATSConsumer against a real NATS server. +type ConsumerRedeliverySuite struct { + suite.Suite + natsC testcontainers.Container + conn *nats.Conn + publisher *HadesNATSPublisher +} + +func TestConsumerRedeliverySuite(t *testing.T) { + suite.Run(t, new(ConsumerRedeliverySuite)) +} + +func (s *ConsumerRedeliverySuite) SetupSuite() { + ctx := context.Background() + container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{ + ContainerRequest: testcontainers.ContainerRequest{ + Image: natsImage, + ExposedPorts: []string{"4222/tcp", "8222/tcp"}, + Cmd: []string{"-js", "-m", "8222"}, + WaitingFor: wait.ForHTTP("/healthz").WithPort("8222/tcp"), + }, + Started: true, + }) + s.Require().NoError(err) + s.natsC = container + + endpoint, err := container.Endpoint(ctx, "") + s.Require().NoError(err) + + s.conn, err = SetupDefaultNatsConnection(ConnectionConfig{URL: "nats://" + endpoint}) + s.Require().NoError(err) + + s.publisher, err = NewHadesPublisher(s.conn) + s.Require().NoError(err) +} + +func (s *ConsumerRedeliverySuite) TearDownSuite() { + if s.conn != nil { + s.conn.Close() + } + if s.natsC != nil { + s.Require().NoError(testcontainers.TerminateContainer(s.natsC)) + } +} + +// runConsumer starts the consumer's dequeue loop in the background and returns a +// function that stops it and waits for the workers to exit. +func (s *ConsumerRedeliverySuite) runConsumer(cfg ConsumerConfig, handler hades.PayloadHandler) func() { + consumer, err := NewHadesConsumer(s.conn, cfg) + s.Require().NoError(err) + + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + go func() { + defer close(done) + consumer.DequeueJob(ctx, handler) + }() + + return func() { + cancel() + <-done + } +} + +func newTestJob(name string) payload.QueuePayload { + return payload.QueuePayload{ + ID: uuid.New(), + Name: name, + Timestamp: time.Now(), + Steps: []payload.Step{{ID: 1, Name: "step", Image: "alpine:latest"}}, + } +} + +// TestLongRunningJobIsExecutedExactlyOnce is the regression test for the +// redelivery bug: the consumer used to ack only after the handler returned, so +// with the library's 30s AckWait every Docker-mode job longer than half a minute +// was redelivered and executed a second time while the first copy was still +// running - both copies sharing the same shared- volume. +// +// The handler here blocks for several multiples of AckWait. With the in-progress +// heartbeat the job stays leased for as long as it runs, so it must be handed to +// a handler exactly once. +func (s *ConsumerRedeliverySuite) TestLongRunningJobIsExecutedExactlyOnce() { + var started atomic.Int64 + finished := make(chan struct{}) + + // Runs for 3x AckWait: without a heartbeat JetStream would have redelivered + // the job twice by the time the handler returns. + jobDuration := 3 * testAckWait + + stop := s.runConsumer(ConsumerConfig{Concurrency: 2, AckWait: testAckWait, MaxDeliver: DefaultMaxDeliver}, + func(job payload.QueuePayload) { + if started.Add(1) == 1 { + time.Sleep(jobDuration) + close(finished) + } + }) + defer stop() + + job := newTestJob("long-running-job") + s.Require().NoError(s.publisher.EnqueueHighJob(context.Background(), job)) + + select { + case <-finished: + case <-time.After(jobDuration + 15*time.Second): + s.FailNow("job handler never finished") + } + + // Give JetStream more than a full AckWait to redeliver if the ack timer was + // not being reset, plus time for a redelivered copy to reach the handler. + time.Sleep(2 * testAckWait) + + s.Equal(int64(1), started.Load(), "a job running longer than AckWait must be executed exactly once") +} + +// TestPoisonJobIsTerminatedAndReportedFailed covers the MaxDeliver backstop: a +// job that keeps killing its worker must stop being redelivered and must surface +// as Failed rather than disappearing silently. +func (s *ConsumerRedeliverySuite) TestPoisonJobIsTerminatedAndReportedFailed() { + const maxDeliver = 2 + + failures := make(chan *nats.Msg, 4) + sub, err := s.conn.ChanSubscribe(buildstatus.StatusSubject(buildstatus.StatusFailed), failures) + s.Require().NoError(err) + defer func() { _ = sub.Unsubscribe() }() + + var attempts atomic.Int64 + stop := s.runConsumer(ConsumerConfig{Concurrency: 1, AckWait: testAckWait, MaxDeliver: maxDeliver}, + func(job payload.QueuePayload) { + attempts.Add(1) + panic("executor exploded") + }) + defer stop() + + job := newTestJob("poison-job") + s.Require().NoError(s.publisher.EnqueueHighJob(context.Background(), job)) + + // Delivery 1 panics and is naked with a 5s delay; delivery 2 is the last + // allowed one and is spent reporting the failure instead of running again. + var failure *nats.Msg + select { + case failure = <-failures: + case <-time.After(30 * time.Second): + s.FailNow("no terminal Failed status was published for the poison job") + } + + s.Equal(job.ID.String(), string(failure.Data)) + s.NotEmpty(failure.Header.Get(buildstatus.ReasonHeader), "the terminal failure must explain itself") + s.Equal(int64(maxDeliver-1), attempts.Load(), "the final delivery must not execute the job again") + + // The message is terminated, so it must not come back. + time.Sleep(3 * testAckWait) + s.Equal(int64(maxDeliver-1), attempts.Load(), "a terminated job must not be redelivered") + s.Empty(failures, "the terminal failure must be reported once") +} + +// TearDownTest drops any job left over from a failed test so the next one starts +// from an empty work queue. +func (s *ConsumerRedeliverySuite) TearDownTest() { + ctx := context.Background() + js, err := jetstream.New(s.conn) + s.Require().NoError(err) + stream, err := js.Stream(ctx, "HADES_JOBS") + s.Require().NoError(err) + s.Require().NoError(stream.Purge(ctx)) +} diff --git a/shared/nats/publisher.go b/shared/nats/publisher.go index 0bfe8b16..03cd1e28 100644 --- a/shared/nats/publisher.go +++ b/shared/nats/publisher.go @@ -106,7 +106,15 @@ func (hp *HadesNATSPublisher) EnqueueJobWithPriority(ctx context.Context, queueP // subject "hades.jobstatus.{status}". Subscribers such as HadesLogManager use // these events to track a job's lifecycle. Nothing publishes the Queued status // today except the API on enqueue, so this completes the lifecycle feed. -func (hp *HadesNATSPublisher) PublishJobStatus(ctx context.Context, jobStatus buildstatus.JobStatus, jobID string, reason ...string) error { +func (hp *HadesNATSPublisher) PublishJobStatus(_ context.Context, jobStatus buildstatus.JobStatus, jobID string, reason ...string) error { + return publishJobStatus(hp.natsConnection, jobStatus, jobID, reason...) +} + +// publishJobStatus publishes a status transition on the core-NATS status +// subject "hades.jobstatus.{status}". It backs HadesNATSPublisher's +// StatusPublisher implementation and is also used by the consumer to report a +// job it gives up on, so both report failures the same way. +func publishJobStatus(nc *nats.Conn, jobStatus buildstatus.JobStatus, jobID string, reason ...string) error { if jobID == "" { return fmt.Errorf("empty job ID") } @@ -120,7 +128,7 @@ func (hp *HadesNATSPublisher) PublishJobStatus(ctx context.Context, jobStatus bu if r := buildstatus.FirstReason(reason...); r != "" { msg.Header = nats.Header{buildstatus.ReasonHeader: []string{r}} } - if err := hp.natsConnection.PublishMsg(msg); err != nil { + if err := nc.PublishMsg(msg); err != nil { return fmt.Errorf("publishing job status %s for job %s: %w", jobStatus, jobID, err) } slog.Debug("Published job status", "job_id", jobID, "status", jobStatus, "subject", subject) diff --git a/website/docs/reference/configuration.md b/website/docs/reference/configuration.md index 2ab75d84..15ec512f 100644 --- a/website/docs/reference/configuration.md +++ b/website/docs/reference/configuration.md @@ -42,6 +42,8 @@ Hades is configured entirely through environment variables (loaded via `caarlos0 | Variable | Default | Description | | -------- | ------- | ----------- | | `CONCURRENCY` | `1` | Number of jobs processed concurrently. | +| `NATS_ACK_WAIT` | `1m` | How long JetStream waits for an ack before redelivering a job to another worker. A liveness backstop, not a job-duration budget: a worker signals progress while a job runs, so long jobs are never redelivered while the worker is alive. | +| `NATS_MAX_DELIVER` | `3` | Maximum number of deliveries per job. The last delivery is spent publishing a terminal `Failed` status and dropping the job, so the default allows two execution attempts. | | `HADES_EXECUTOR` | `docker` | Execution platform: `docker` or `k8s`. | Depending on `HADES_EXECUTOR`, the Docker or Kubernetes variables below also apply. From 9c302f3cd0fe266ce47a1cef970ad06464e851aa Mon Sep 17 00:00:00 2001 From: Matthias Linhuber Date: Fri, 21 Aug 2026 15:50:18 +0200 Subject: [PATCH 2/8] Reject a MaxDeliver that would never execute a job The last allowed delivery is spent publishing the terminal Failed status instead of running the job, so NATS_MAX_DELIVER=1 made the very first delivery count as exhausted and no job would ever have been executed - a single misconfigured value silently disabling the whole scheduler. NewHadesConsumer now rejects anything below 2 at startup. Zero and negative still mean "unset" and fall back to the default of 3. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01Dmsq9AGYZWikY4BqjR3CLw --- .env.example | 2 +- docs/configuration.md | 2 +- shared/nats/ackprogress_test.go | 19 ++++++++++++++++++- shared/nats/consumer.go | 22 ++++++++++++++++++++++ shared/nats/consumer_redelivery_test.go | 2 +- website/docs/reference/configuration.md | 2 +- 6 files changed, 44 insertions(+), 5 deletions(-) diff --git a/.env.example b/.env.example index 3ee6774c..72aa599c 100644 --- a/.env.example +++ b/.env.example @@ -37,7 +37,7 @@ HADES_EXECUTOR="docker" # Executor to use for running jobs (options: docker, k8s ### HadesScheduler Options ### CONCURRENCY=1 # Number of jobs to run concurrently (default: 1) NATS_ACK_WAIT=1m # How long JetStream waits for an ack before redelivering a job to another worker; a liveness backstop, not a job-duration budget (default: 1m) -NATS_MAX_DELIVER=3 # Max deliveries per job; the last one publishes a terminal Failed status instead of running the job again (default: 3) +NATS_MAX_DELIVER=3 # Max deliveries per job; the last one publishes a terminal Failed status instead of running the job again (minimum: 2, default: 3) ### HadesOperator Options ### WATCH_NAMESPACE="hades" diff --git a/docs/configuration.md b/docs/configuration.md index 87eb8c76..d77d5337 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -42,7 +42,7 @@ Plus the [NATS](#nats-connection-all-components) and [global](#global-all-compon | -------- | ------- | ----------- | ------ | | `CONCURRENCY` | `1` | Number of jobs processed concurrently. | `shared/nats/consumer.go` (`ConsumerConfig`) | | `NATS_ACK_WAIT` | `1m` | How long JetStream waits for an ack before redelivering a job to another worker. This is a liveness backstop, **not** a job-duration budget: a worker signals progress every few seconds while a job runs, so jobs of any length (including ones running to their `timeout_seconds`) are never redelivered while the worker is alive. Lower it for faster recovery after a scheduler crash, raise it if the network is flaky. | `shared/nats/consumer.go` (`ConsumerConfig`) | -| `NATS_MAX_DELIVER` | `3` | Maximum number of times a single job is delivered. The last delivery is not executed: it is used to publish a terminal `Failed` status and drop the job, so the default allows two execution attempts before Hades gives up on a job that keeps crashing or stalling its worker. | `shared/nats/consumer.go` (`ConsumerConfig`) | +| `NATS_MAX_DELIVER` | `3` | Maximum number of times a single job is delivered. The last delivery is not executed: it is used to publish a terminal `Failed` status and drop the job, so the default allows two execution attempts before Hades gives up on a job that keeps crashing or stalling its worker. Must be at least `2`; the scheduler refuses to start otherwise, because `1` would spend the only delivery on the failure report and never execute a job. | `shared/nats/consumer.go` (`ConsumerConfig`) | | `HADES_EXECUTOR` | `docker` | Execution platform: `docker` or `k8s`. | `shared/utils/config.go` (`ExecutorConfig`) | Plus the [NATS](#nats-connection-all-components) and [global](#global-all-components) variables, and - depending on `HADES_EXECUTOR` - the Docker or Kubernetes variables below. diff --git a/shared/nats/ackprogress_test.go b/shared/nats/ackprogress_test.go index 2aa8637e..6083f4b9 100644 --- a/shared/nats/ackprogress_test.go +++ b/shared/nats/ackprogress_test.go @@ -48,6 +48,23 @@ func TestConsumerConfigWithDefaults(t *testing.T) { assert.Equal(t, ConsumerConfig{Concurrency: 4, AckWait: 5 * time.Second, MaxDeliver: 2}, custom) } +// TestConsumerConfigValidate pins the MaxDeliver lower bound: because the last +// allowed delivery reports the terminal failure instead of running the job, +// MaxDeliver = 1 would silently stop the scheduler from ever executing a job. +// That must fail loudly at startup instead. +func TestConsumerConfigValidate(t *testing.T) { + err := ConsumerConfig{MaxDeliver: 1}.withDefaults().validate() + require.Error(t, err) + assert.Contains(t, err.Error(), "NATS_MAX_DELIVER") + + // Unset (zero/negative) means "use the default", not "one delivery". + assert.NoError(t, ConsumerConfig{}.withDefaults().validate()) + assert.NoError(t, ConsumerConfig{MaxDeliver: -1}.withDefaults().validate()) + + // The smallest usable value still allows one execution attempt. + assert.NoError(t, ConsumerConfig{MaxDeliver: minMaxDeliver}.withDefaults().validate()) +} + func TestStartAckProgressSignalsRepeatedly(t *testing.T) { var calls atomic.Int64 stop := startAckProgress(func() error { @@ -63,7 +80,7 @@ func TestStartAckProgressSignalsRepeatedly(t *testing.T) { // TestStartAckProgressStopIsFinalAndIdempotent guards the two failure modes of // the heartbeat goroutine: leaking past the job, and signalling in-progress on a -// message that has already been acked or naked. +// message that has already been ACKed or NAKed. func TestStartAckProgressStopIsFinalAndIdempotent(t *testing.T) { var calls atomic.Int64 stop := startAckProgress(func() error { diff --git a/shared/nats/consumer.go b/shared/nats/consumer.go index b1cc4003..552bf542 100644 --- a/shared/nats/consumer.go +++ b/shared/nats/consumer.go @@ -76,6 +76,24 @@ func (c ConsumerConfig) withDefaults() ConsumerConfig { return c } +// minMaxDeliver is the smallest MaxDeliver that still lets a job run. The last +// allowed delivery is spent reporting the terminal failure instead of executing +// the job (see processJob), so MaxDeliver = 1 would mean the very first delivery +// is already the last one and no job would ever be executed. +const minMaxDeliver = 2 + +// validate rejects a configuration that would silently stop all job execution. +// It runs after withDefaults, so a zero or negative MaxDeliver has already been +// replaced by DefaultMaxDeliver and only an explicit, unusable value is left. +func (c ConsumerConfig) validate() error { + if c.MaxDeliver < minMaxDeliver { + return fmt.Errorf( + "NATS_MAX_DELIVER must be at least %d, got %d: the last allowed delivery reports the terminal failure instead of running the job, so a lower value would never execute any job", + minMaxDeliver, c.MaxDeliver) + } + return nil +} + // ackProgressInterval returns how often an in-flight job signals progress for // the given AckWait. It stays well below AckWait so several lost heartbeats do // not trigger a redelivery. @@ -105,6 +123,10 @@ type HadesNATSConsumer struct { // JetStream redelivers jobs whose worker stops responding. func NewHadesConsumer(nc *nats.Conn, cfg ConsumerConfig) (*HadesNATSConsumer, error) { cfg = cfg.withDefaults() + if err := cfg.validate(); err != nil { + slog.Error("Invalid consumer configuration", "error", err) + return nil, err + } ctx := context.Background() js, err := jetstream.New(nc) diff --git a/shared/nats/consumer_redelivery_test.go b/shared/nats/consumer_redelivery_test.go index 49a37043..e72e1d30 100644 --- a/shared/nats/consumer_redelivery_test.go +++ b/shared/nats/consumer_redelivery_test.go @@ -161,7 +161,7 @@ func (s *ConsumerRedeliverySuite) TestPoisonJobIsTerminatedAndReportedFailed() { job := newTestJob("poison-job") s.Require().NoError(s.publisher.EnqueueHighJob(context.Background(), job)) - // Delivery 1 panics and is naked with a 5s delay; delivery 2 is the last + // Delivery 1 panics and is NAKed with a 5s delay; delivery 2 is the last // allowed one and is spent reporting the failure instead of running again. var failure *nats.Msg select { diff --git a/website/docs/reference/configuration.md b/website/docs/reference/configuration.md index 15ec512f..02a97373 100644 --- a/website/docs/reference/configuration.md +++ b/website/docs/reference/configuration.md @@ -43,7 +43,7 @@ Hades is configured entirely through environment variables (loaded via `caarlos0 | -------- | ------- | ----------- | | `CONCURRENCY` | `1` | Number of jobs processed concurrently. | | `NATS_ACK_WAIT` | `1m` | How long JetStream waits for an ack before redelivering a job to another worker. A liveness backstop, not a job-duration budget: a worker signals progress while a job runs, so long jobs are never redelivered while the worker is alive. | -| `NATS_MAX_DELIVER` | `3` | Maximum number of deliveries per job. The last delivery is spent publishing a terminal `Failed` status and dropping the job, so the default allows two execution attempts. | +| `NATS_MAX_DELIVER` | `3` | Maximum number of deliveries per job. The last delivery is spent publishing a terminal `Failed` status and dropping the job, so the default allows two execution attempts. Must be at least `2` - the scheduler refuses to start otherwise. | | `HADES_EXECUTOR` | `docker` | Execution platform: `docker` or `k8s`. | Depending on `HADES_EXECUTOR`, the Docker or Kubernetes variables below also apply. From 49dd2c5d72e3c8823b674cb9621399b765576be7 Mon Sep 17 00:00:00 2001 From: Matthias Linhuber Date: Fri, 21 Aug 2026 20:40:07 +0200 Subject: [PATCH 3/8] Reject an AckWait shorter than the progress heartbeat CodeRabbit caught a config value that silently reintroduces the bug this PR fixes. ackProgressInterval derives the heartbeat from AckWait/3 but clamps it up to minAckProgressInterval (100ms). Below 3*minAckProgressInterval the clamp wins, so with NATS_ACK_WAIT=10ms the first InProgress call lands at 100ms - long after AckWait has elapsed. JetStream redelivers a job that is still running, and the duplicate execution is back. validate() now rejects anything under 300ms, alongside the existing MaxDeliver bound. Zero and negative still mean "use the default", so only an explicit, unusable value fails. TestConsumerConfigValidateAckWait pins the bound and asserts that at exactly minAckWait the heartbeat equals minAckProgressInterval, which is what makes 300ms the correct floor rather than an arbitrary one. Documented the minimum in docs/configuration.md, the website reference, and .env.example. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01Dmsq9AGYZWikY4BqjR3CLw --- .env.example | 2 +- docs/configuration.md | 2 +- shared/nats/ackprogress_test.go | 23 +++++++++++++++++++++++ shared/nats/consumer.go | 19 ++++++++++++++++--- website/docs/reference/configuration.md | 2 +- 5 files changed, 42 insertions(+), 6 deletions(-) diff --git a/.env.example b/.env.example index 72aa599c..f5b316f6 100644 --- a/.env.example +++ b/.env.example @@ -36,7 +36,7 @@ HADES_EXECUTOR="docker" # Executor to use for running jobs (options: docker, k8s ### HadesScheduler Options ### CONCURRENCY=1 # Number of jobs to run concurrently (default: 1) -NATS_ACK_WAIT=1m # How long JetStream waits for an ack before redelivering a job to another worker; a liveness backstop, not a job-duration budget (default: 1m) +NATS_ACK_WAIT=1m # How long JetStream waits for an ack before redelivering a job to another worker; a liveness backstop, not a job-duration budget (default: 1m, minimum: 300ms) NATS_MAX_DELIVER=3 # Max deliveries per job; the last one publishes a terminal Failed status instead of running the job again (minimum: 2, default: 3) ### HadesOperator Options ### diff --git a/docs/configuration.md b/docs/configuration.md index d77d5337..187efc82 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -41,7 +41,7 @@ Plus the [NATS](#nats-connection-all-components) and [global](#global-all-compon | Variable | Default | Description | Source | | -------- | ------- | ----------- | ------ | | `CONCURRENCY` | `1` | Number of jobs processed concurrently. | `shared/nats/consumer.go` (`ConsumerConfig`) | -| `NATS_ACK_WAIT` | `1m` | How long JetStream waits for an ack before redelivering a job to another worker. This is a liveness backstop, **not** a job-duration budget: a worker signals progress every few seconds while a job runs, so jobs of any length (including ones running to their `timeout_seconds`) are never redelivered while the worker is alive. Lower it for faster recovery after a scheduler crash, raise it if the network is flaky. | `shared/nats/consumer.go` (`ConsumerConfig`) | +| `NATS_ACK_WAIT` | `1m` | How long JetStream waits for an ack before redelivering a job to another worker. This is a liveness backstop, **not** a job-duration budget: a worker signals progress every few seconds while a job runs, so jobs of any length (including ones running to their `timeout_seconds`) are never redelivered while the worker is alive. Lower it for faster recovery after a scheduler crash, raise it if the network is flaky. Minimum `300ms`: the progress heartbeat is clamped to `100ms`, so a shorter `AckWait` would expire before the first heartbeat and redeliver a running job. | `shared/nats/consumer.go` (`ConsumerConfig`) | | `NATS_MAX_DELIVER` | `3` | Maximum number of times a single job is delivered. The last delivery is not executed: it is used to publish a terminal `Failed` status and drop the job, so the default allows two execution attempts before Hades gives up on a job that keeps crashing or stalling its worker. Must be at least `2`; the scheduler refuses to start otherwise, because `1` would spend the only delivery on the failure report and never execute a job. | `shared/nats/consumer.go` (`ConsumerConfig`) | | `HADES_EXECUTOR` | `docker` | Execution platform: `docker` or `k8s`. | `shared/utils/config.go` (`ExecutorConfig`) | diff --git a/shared/nats/ackprogress_test.go b/shared/nats/ackprogress_test.go index 6083f4b9..9ce36b54 100644 --- a/shared/nats/ackprogress_test.go +++ b/shared/nats/ackprogress_test.go @@ -65,6 +65,29 @@ func TestConsumerConfigValidate(t *testing.T) { assert.NoError(t, ConsumerConfig{MaxDeliver: minMaxDeliver}.withDefaults().validate()) } +// TestConsumerConfigValidateAckWait pins the AckWait lower bound. The heartbeat +// interval is AckWait/3 but clamped up to minAckProgressInterval, so below +// 3*minAckProgressInterval the clamp wins and the first heartbeat lands after +// AckWait has already elapsed. JetStream would then redeliver a job that is +// still running, which is the duplicate execution this consumer prevents. +func TestConsumerConfigValidateAckWait(t *testing.T) { + err := ConsumerConfig{AckWait: 10 * time.Millisecond}.withDefaults().validate() + require.Error(t, err) + assert.Contains(t, err.Error(), "NATS_ACK_WAIT") + + // Unset (zero/negative) means "use the default", not "expire immediately". + assert.NoError(t, ConsumerConfig{}.withDefaults().validate()) + assert.NoError(t, ConsumerConfig{AckWait: -1}.withDefaults().validate()) + + // At the bound the heartbeat is exactly minAckProgressInterval, which still + // leaves two further heartbeats before AckWait elapses. + assert.NoError(t, ConsumerConfig{AckWait: minAckWait}.withDefaults().validate()) + assert.Equal(t, minAckProgressInterval, ackProgressInterval(minAckWait)) + + // Just below it, the clamp would push the heartbeat past AckWait/3. + assert.Error(t, ConsumerConfig{AckWait: minAckWait - time.Millisecond}.withDefaults().validate()) +} + func TestStartAckProgressSignalsRepeatedly(t *testing.T) { var calls atomic.Int64 stop := startAckProgress(func() error { diff --git a/shared/nats/consumer.go b/shared/nats/consumer.go index 552bf542..bcaf6dbf 100644 --- a/shared/nats/consumer.go +++ b/shared/nats/consumer.go @@ -82,10 +82,23 @@ func (c ConsumerConfig) withDefaults() ConsumerConfig { // is already the last one and no job would ever be executed. const minMaxDeliver = 2 -// validate rejects a configuration that would silently stop all job execution. -// It runs after withDefaults, so a zero or negative MaxDeliver has already been -// replaced by DefaultMaxDeliver and only an explicit, unusable value is left. +// minAckWait is the smallest AckWait for which the heartbeat can still keep a +// job alive. ackProgressInterval derives the heartbeat from AckWait/3 but clamps +// it up to minAckProgressInterval, so below this bound the clamp wins and the +// first InProgress call would land after AckWait had already elapsed. JetStream +// would redeliver a job that is still running - exactly the duplicate execution +// this consumer exists to prevent. +const minAckWait = 3 * minAckProgressInterval + +// validate rejects a configuration that would silently break job execution. +// It runs after withDefaults, so a zero or negative value has already been +// replaced by its default and only an explicit, unusable one is left. func (c ConsumerConfig) validate() error { + if c.AckWait < minAckWait { + return fmt.Errorf( + "NATS_ACK_WAIT must be at least %s, got %s: the in-progress heartbeat is clamped to %s, so a shorter AckWait would expire before the first heartbeat and redeliver a job that is still running", + minAckWait, c.AckWait, minAckProgressInterval) + } if c.MaxDeliver < minMaxDeliver { return fmt.Errorf( "NATS_MAX_DELIVER must be at least %d, got %d: the last allowed delivery reports the terminal failure instead of running the job, so a lower value would never execute any job", diff --git a/website/docs/reference/configuration.md b/website/docs/reference/configuration.md index 02a97373..0ba3df5b 100644 --- a/website/docs/reference/configuration.md +++ b/website/docs/reference/configuration.md @@ -42,7 +42,7 @@ Hades is configured entirely through environment variables (loaded via `caarlos0 | Variable | Default | Description | | -------- | ------- | ----------- | | `CONCURRENCY` | `1` | Number of jobs processed concurrently. | -| `NATS_ACK_WAIT` | `1m` | How long JetStream waits for an ack before redelivering a job to another worker. A liveness backstop, not a job-duration budget: a worker signals progress while a job runs, so long jobs are never redelivered while the worker is alive. | +| `NATS_ACK_WAIT` | `1m` | How long JetStream waits for an ack before redelivering a job to another worker. A liveness backstop, not a job-duration budget: a worker signals progress while a job runs, so long jobs are never redelivered while the worker is alive. Minimum `300ms`, because the progress heartbeat is clamped to `100ms`. | | `NATS_MAX_DELIVER` | `3` | Maximum number of deliveries per job. The last delivery is spent publishing a terminal `Failed` status and dropping the job, so the default allows two execution attempts. Must be at least `2` - the scheduler refuses to start otherwise. | | `HADES_EXECUTOR` | `docker` | Execution platform: `docker` or `k8s`. | From 856b4a5306d23675208f77646db9ea80d3f065de Mon Sep 17 00:00:00 2001 From: Matthias Linhuber Date: Fri, 21 Aug 2026 20:52:05 +0200 Subject: [PATCH 4/8] Describe the real reason for the AckWait minimum Copilot was right that the previous wording overstated the failure mode. For an AckWait between 100ms and 300ms the first heartbeat does still arrive before the ack window closes, so "AckWait would expire before the first heartbeat" is only true below 100ms. The actual reason for the bound: the heartbeat targets AckWait/3, which puts three ticks inside every ack window so a delayed or dropped one is harmless. The minAckProgressInterval clamp holds the interval at 100ms, so under 300ms the window carries fewer than three ticks and that margin erodes - and under 100ms it is gone entirely and the original failure applies. Reworded in all four places the claim appeared: the constant's doc comment, the validation error operators actually see, the test rationale, and both config references. No behaviour change; the 300ms bound and its test are unchanged. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01Dmsq9AGYZWikY4BqjR3CLw --- docs/configuration.md | 2 +- shared/nats/ackprogress_test.go | 12 +++++++----- shared/nats/consumer.go | 15 ++++++++------- website/docs/reference/configuration.md | 2 +- 4 files changed, 17 insertions(+), 14 deletions(-) diff --git a/docs/configuration.md b/docs/configuration.md index 187efc82..4c12b94c 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -41,7 +41,7 @@ Plus the [NATS](#nats-connection-all-components) and [global](#global-all-compon | Variable | Default | Description | Source | | -------- | ------- | ----------- | ------ | | `CONCURRENCY` | `1` | Number of jobs processed concurrently. | `shared/nats/consumer.go` (`ConsumerConfig`) | -| `NATS_ACK_WAIT` | `1m` | How long JetStream waits for an ack before redelivering a job to another worker. This is a liveness backstop, **not** a job-duration budget: a worker signals progress every few seconds while a job runs, so jobs of any length (including ones running to their `timeout_seconds`) are never redelivered while the worker is alive. Lower it for faster recovery after a scheduler crash, raise it if the network is flaky. Minimum `300ms`: the progress heartbeat is clamped to `100ms`, so a shorter `AckWait` would expire before the first heartbeat and redeliver a running job. | `shared/nats/consumer.go` (`ConsumerConfig`) | +| `NATS_ACK_WAIT` | `1m` | How long JetStream waits for an ack before redelivering a job to another worker. This is a liveness backstop, **not** a job-duration budget: a worker signals progress every few seconds while a job runs, so jobs of any length (including ones running to their `timeout_seconds`) are never redelivered while the worker is alive. Lower it for faster recovery after a scheduler crash, raise it if the network is flaky. Minimum `300ms`: the heartbeat targets `AckWait/3` so three ticks fall inside each ack window, but it is clamped to a `100ms` floor. Below `300ms` that clamp leaves fewer than three ticks per window and erodes the margin that absorbs a delayed or dropped heartbeat; below `100ms` the first heartbeat arrives after `AckWait` has elapsed and a running job is redelivered. | `shared/nats/consumer.go` (`ConsumerConfig`) | | `NATS_MAX_DELIVER` | `3` | Maximum number of times a single job is delivered. The last delivery is not executed: it is used to publish a terminal `Failed` status and drop the job, so the default allows two execution attempts before Hades gives up on a job that keeps crashing or stalling its worker. Must be at least `2`; the scheduler refuses to start otherwise, because `1` would spend the only delivery on the failure report and never execute a job. | `shared/nats/consumer.go` (`ConsumerConfig`) | | `HADES_EXECUTOR` | `docker` | Execution platform: `docker` or `k8s`. | `shared/utils/config.go` (`ExecutorConfig`) | diff --git a/shared/nats/ackprogress_test.go b/shared/nats/ackprogress_test.go index 9ce36b54..9f82252d 100644 --- a/shared/nats/ackprogress_test.go +++ b/shared/nats/ackprogress_test.go @@ -66,10 +66,11 @@ func TestConsumerConfigValidate(t *testing.T) { } // TestConsumerConfigValidateAckWait pins the AckWait lower bound. The heartbeat -// interval is AckWait/3 but clamped up to minAckProgressInterval, so below -// 3*minAckProgressInterval the clamp wins and the first heartbeat lands after -// AckWait has already elapsed. JetStream would then redeliver a job that is -// still running, which is the duplicate execution this consumer prevents. +// targets AckWait/3, giving three ticks per ack window so a delayed or dropped +// one is harmless. Below 3*minAckProgressInterval the clamp wins and that +// margin collapses towards a single tick; under minAckProgressInterval it is +// gone altogether and the first heartbeat lands after AckWait has elapsed, +// redelivering a job that is still running. func TestConsumerConfigValidateAckWait(t *testing.T) { err := ConsumerConfig{AckWait: 10 * time.Millisecond}.withDefaults().validate() require.Error(t, err) @@ -84,7 +85,8 @@ func TestConsumerConfigValidateAckWait(t *testing.T) { assert.NoError(t, ConsumerConfig{AckWait: minAckWait}.withDefaults().validate()) assert.Equal(t, minAckProgressInterval, ackProgressInterval(minAckWait)) - // Just below it, the clamp would push the heartbeat past AckWait/3. + // Just below it, the clamp holds the interval above AckWait/3 and the + // three-ticks-per-window margin starts to erode. assert.Error(t, ConsumerConfig{AckWait: minAckWait - time.Millisecond}.withDefaults().validate()) } diff --git a/shared/nats/consumer.go b/shared/nats/consumer.go index bcaf6dbf..5cdb3d38 100644 --- a/shared/nats/consumer.go +++ b/shared/nats/consumer.go @@ -82,12 +82,13 @@ func (c ConsumerConfig) withDefaults() ConsumerConfig { // is already the last one and no job would ever be executed. const minMaxDeliver = 2 -// minAckWait is the smallest AckWait for which the heartbeat can still keep a -// job alive. ackProgressInterval derives the heartbeat from AckWait/3 but clamps -// it up to minAckProgressInterval, so below this bound the clamp wins and the -// first InProgress call would land after AckWait had already elapsed. JetStream -// would redeliver a job that is still running - exactly the duplicate execution -// this consumer exists to prevent. +// minAckWait is the smallest AckWait that preserves the heartbeat's safety +// margin. ackProgressInterval targets AckWait/3 so at least three heartbeats +// fall inside every ack window and a couple of delayed or lost ticks still +// cannot trigger a redelivery. Below this bound the minAckProgressInterval +// clamp wins, that margin shrinks towards a single tick, and under 100ms it +// disappears entirely: the first InProgress call would land after AckWait had +// already elapsed and JetStream would redeliver a job that is still running. const minAckWait = 3 * minAckProgressInterval // validate rejects a configuration that would silently break job execution. @@ -96,7 +97,7 @@ const minAckWait = 3 * minAckProgressInterval func (c ConsumerConfig) validate() error { if c.AckWait < minAckWait { return fmt.Errorf( - "NATS_ACK_WAIT must be at least %s, got %s: the in-progress heartbeat is clamped to %s, so a shorter AckWait would expire before the first heartbeat and redeliver a job that is still running", + "NATS_ACK_WAIT must be at least %s, got %s: the in-progress heartbeat is clamped to a %s floor, so a shorter AckWait leaves fewer than three heartbeats per ack window and loses the margin that keeps a delayed or dropped tick from redelivering a job that is still running", minAckWait, c.AckWait, minAckProgressInterval) } if c.MaxDeliver < minMaxDeliver { diff --git a/website/docs/reference/configuration.md b/website/docs/reference/configuration.md index 0ba3df5b..76832153 100644 --- a/website/docs/reference/configuration.md +++ b/website/docs/reference/configuration.md @@ -42,7 +42,7 @@ Hades is configured entirely through environment variables (loaded via `caarlos0 | Variable | Default | Description | | -------- | ------- | ----------- | | `CONCURRENCY` | `1` | Number of jobs processed concurrently. | -| `NATS_ACK_WAIT` | `1m` | How long JetStream waits for an ack before redelivering a job to another worker. A liveness backstop, not a job-duration budget: a worker signals progress while a job runs, so long jobs are never redelivered while the worker is alive. Minimum `300ms`, because the progress heartbeat is clamped to `100ms`. | +| `NATS_ACK_WAIT` | `1m` | How long JetStream waits for an ack before redelivering a job to another worker. A liveness backstop, not a job-duration budget: a worker signals progress while a job runs, so long jobs are never redelivered while the worker is alive. Minimum `300ms`: the heartbeat targets `AckWait/3` but is clamped to a `100ms` floor, so shorter values leave fewer than three ticks per ack window and lose the margin that absorbs a delayed or dropped heartbeat. | | `NATS_MAX_DELIVER` | `3` | Maximum number of deliveries per job. The last delivery is spent publishing a terminal `Failed` status and dropping the job, so the default allows two execution attempts. Must be at least `2` - the scheduler refuses to start otherwise. | | `HADES_EXECUTOR` | `docker` | Execution platform: `docker` or `k8s`. | From 2573287b6a6b3d56e4fbddd1f836a0c4ca91b24f Mon Sep 17 00:00:00 2001 From: Matthias Linhuber Date: Mon, 24 Aug 2026 21:38:20 +0200 Subject: [PATCH 5/8] Potential fix for pull request finding Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- shared/nats/consumer.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/shared/nats/consumer.go b/shared/nats/consumer.go index 5cdb3d38..979ff0ff 100644 --- a/shared/nats/consumer.go +++ b/shared/nats/consumer.go @@ -52,13 +52,13 @@ const ( type ConsumerConfig struct { // Concurrency is the maximum number of jobs processed simultaneously by a // single scheduler instance. - Concurrency uint `env:"CONCURRENCY" envDefault:"1"` + Concurrency uint `env:"CONCURRENCY"` // AckWait is the JetStream ack timeout for an in-flight job. See // DefaultAckWait: it is a liveness backstop, not a job-duration budget. - AckWait time.Duration `env:"NATS_ACK_WAIT" envDefault:"1m"` + AckWait time.Duration `env:"NATS_ACK_WAIT"` // MaxDeliver is the maximum number of times a single job is delivered. See // DefaultMaxDeliver. - MaxDeliver int `env:"NATS_MAX_DELIVER" envDefault:"3"` + MaxDeliver int `env:"NATS_MAX_DELIVER"` } // withDefaults returns the config with non-positive values replaced by the From 75dbc905078258e1df2b68f7c782695eff908f6f Mon Sep 17 00:00:00 2001 From: Matthias Linhuber Date: Mon, 24 Aug 2026 21:44:28 +0200 Subject: [PATCH 6/8] Pin that the nested ConsumerConfig env defaults are loaded This PR moved Concurrency off HadesSchedulerConfig into the nested ConsumerConfig, so the startup log now depends on the loader traversing nested structs and applying their envDefault tags. If that ever stopped holding, withDefaults() would keep the consumer running correctly while the log reported 0 / 0s / 0 - a config log disagreeing with the effective config. The test clears the variables rather than setting them empty, since an explicit empty value is not an absent one. --- HadesScheduler/main_test.go | 47 +++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 HadesScheduler/main_test.go diff --git a/HadesScheduler/main_test.go b/HadesScheduler/main_test.go new file mode 100644 index 00000000..65e27987 --- /dev/null +++ b/HadesScheduler/main_test.go @@ -0,0 +1,47 @@ +package main + +import ( + "os" + "testing" + "time" + + "github.com/hades-scheduler/hades/shared/utils" +) + +// TestConsumerConfigDefaultsAreLoaded pins that the envDefault tags on the +// nested ConsumerConfig actually apply when the environment sets nothing. +// +// This matters because Concurrency lives in a nested struct rather than on +// HadesSchedulerConfig directly. If nested traversal ever stopped working - +// for instance by making the field a pointer, or by switching config loader - +// the fields would silently stay at their zero values. NewHadesConsumer's +// withDefaults() would still run the consumer correctly, so nothing would +// break at runtime; the damage would be confined to the startup log reporting +// 0 / 0s / 0 while the consumer actually used 1 / 1m / 3. A configuration log +// that disagrees with the effective configuration is worse than no log. +func TestConsumerConfigDefaultsAreLoaded(t *testing.T) { + // Clear rather than set: t.Setenv with an empty string is still a set + // variable, and an explicit empty value is not the same as an absent one. + // Restored by t.Cleanup so the test does not leak into its neighbours. + for _, key := range []string{"CONCURRENCY", "NATS_ACK_WAIT", "NATS_MAX_DELIVER"} { + if old, ok := os.LookupEnv(key); ok { + t.Cleanup(func() { os.Setenv(key, old) }) + os.Unsetenv(key) + } + } + + var cfg HadesSchedulerConfig + if err := utils.LoadConfig(&cfg); err != nil { + t.Fatalf("LoadConfig: %v", err) + } + + if got := cfg.ConsumerConfig.Concurrency; got != 1 { + t.Errorf("Concurrency = %d, want 1", got) + } + if got := cfg.ConsumerConfig.AckWait; got != time.Minute { + t.Errorf("AckWait = %v, want 1m", got) + } + if got := cfg.ConsumerConfig.MaxDeliver; got != 3 { + t.Errorf("MaxDeliver = %d, want 3", got) + } +} From c7495c7699a11e4c19bab54125c0f023c87535dc Mon Sep 17 00:00:00 2001 From: Matthias Linhuber Date: Mon, 24 Aug 2026 23:32:24 +0200 Subject: [PATCH 7/8] Declare the ConsumerConfig defaults so the parsed config is not zeros The struct carried env tags but no envDefault, so a scheduler started without CONCURRENCY/NATS_ACK_WAIT/NATS_MAX_DELIVER parsed all three as zero. withDefaults() inside NewHadesConsumer meant the consumer still RAN at 1/1m/3, so nothing misbehaved - but the startup log reported 0/0s/0, disagreeing with the effective configuration. The values now exist as constants and as tag literals, because struct tags cannot reference constants. A test in shared/nats pins the two together so they cannot drift silently, and the scheduler test asserts against the constants rather than magic numbers. The earlier version of that test passed only because it set the variables to the empty string, which is not the same as leaving them unset; it is now cleared properly and passes in a clean environment. --- HadesScheduler/main_test.go | 14 +++--- shared/nats/consumer.go | 29 +++++++++-- shared/nats/consumerconfig_test.go | 78 ++++++++++++++++++++++++++++++ 3 files changed, 109 insertions(+), 12 deletions(-) create mode 100644 shared/nats/consumerconfig_test.go diff --git a/HadesScheduler/main_test.go b/HadesScheduler/main_test.go index 65e27987..1a2e1216 100644 --- a/HadesScheduler/main_test.go +++ b/HadesScheduler/main_test.go @@ -3,8 +3,8 @@ package main import ( "os" "testing" - "time" + hadesnats "github.com/hades-scheduler/hades/shared/nats" "github.com/hades-scheduler/hades/shared/utils" ) @@ -35,13 +35,13 @@ func TestConsumerConfigDefaultsAreLoaded(t *testing.T) { t.Fatalf("LoadConfig: %v", err) } - if got := cfg.ConsumerConfig.Concurrency; got != 1 { - t.Errorf("Concurrency = %d, want 1", got) + if got := cfg.ConsumerConfig.Concurrency; got != hadesnats.DefaultConcurrency { + t.Errorf("Concurrency = %d, want %d", got, hadesnats.DefaultConcurrency) } - if got := cfg.ConsumerConfig.AckWait; got != time.Minute { - t.Errorf("AckWait = %v, want 1m", got) + if got := cfg.ConsumerConfig.AckWait; got != hadesnats.DefaultAckWait { + t.Errorf("AckWait = %v, want %v", got, hadesnats.DefaultAckWait) } - if got := cfg.ConsumerConfig.MaxDeliver; got != 3 { - t.Errorf("MaxDeliver = %d, want 3", got) + if got := cfg.ConsumerConfig.MaxDeliver; got != hadesnats.DefaultMaxDeliver { + t.Errorf("MaxDeliver = %d, want %d", got, hadesnats.DefaultMaxDeliver) } } diff --git a/shared/nats/consumer.go b/shared/nats/consumer.go index 979ff0ff..9697a0b4 100644 --- a/shared/nats/consumer.go +++ b/shared/nats/consumer.go @@ -38,6 +38,11 @@ const ( // message (see processJob), so the default allows two execution attempts. DefaultMaxDeliver = 3 + // DefaultConcurrency is how many jobs one scheduler instance processes at + // once. Named rather than inlined so the envDefault tag below, withDefaults + // and the documentation all point at one value. + DefaultConcurrency = 1 + // maxAckProgressInterval caps the in-progress heartbeat so a long AckWait // does not lead to a needlessly coarse heartbeat. maxAckProgressInterval = 10 * time.Second @@ -49,23 +54,37 @@ const ( // ConsumerConfig holds the tunables of the JetStream job consumer. // Zero values fall back to the defaults above. +// +// The envDefault tags matter beyond convenience. withDefaults() below is +// applied inside NewHadesConsumer, so the consumer always RUNS with the right +// values - but without these tags a config parsed from an environment that sets +// none of them stays at zero, and anything inspecting it (notably the +// scheduler's startup log) reports 0/0s/0 while the consumer actually uses +// 1/1m/3. A configuration log that disagrees with the effective configuration +// is worse than no log, so the defaults are declared here as well. +// +// The tag literals must stay in step with the constants above; the values are +// duplicated because struct tags cannot reference Go constants. +// TestConsumerConfigEnvDefaultsMatchConstants pins them together. type ConsumerConfig struct { // Concurrency is the maximum number of jobs processed simultaneously by a // single scheduler instance. - Concurrency uint `env:"CONCURRENCY"` + Concurrency uint `env:"CONCURRENCY" envDefault:"1"` // AckWait is the JetStream ack timeout for an in-flight job. See // DefaultAckWait: it is a liveness backstop, not a job-duration budget. - AckWait time.Duration `env:"NATS_ACK_WAIT"` + AckWait time.Duration `env:"NATS_ACK_WAIT" envDefault:"1m"` // MaxDeliver is the maximum number of times a single job is delivered. See // DefaultMaxDeliver. - MaxDeliver int `env:"NATS_MAX_DELIVER"` + MaxDeliver int `env:"NATS_MAX_DELIVER" envDefault:"3"` } // withDefaults returns the config with non-positive values replaced by the -// package defaults. +// package defaults. Still required despite the envDefault tags above: a +// ConsumerConfig built programmatically (tests, direct struct literals) never +// goes through env.Parse and would otherwise reach JetStream as zeros. func (c ConsumerConfig) withDefaults() ConsumerConfig { if c.Concurrency == 0 { - c.Concurrency = 1 + c.Concurrency = DefaultConcurrency } if c.AckWait <= 0 { c.AckWait = DefaultAckWait diff --git a/shared/nats/consumerconfig_test.go b/shared/nats/consumerconfig_test.go new file mode 100644 index 00000000..90e994e6 --- /dev/null +++ b/shared/nats/consumerconfig_test.go @@ -0,0 +1,78 @@ +package nats + +import ( + "os" + "reflect" + "testing" + "time" + + "github.com/caarlos0/env/v11" +) + +// TestConsumerConfigEnvDefaultsMatchConstants pins the envDefault tag literals +// to the exported constants they mirror. +// +// Struct tags cannot reference Go constants, so the default values exist twice: +// once as DefaultConcurrency/DefaultAckWait/DefaultMaxDeliver and once as tag +// literals. Nothing but this test stops the two from drifting, and drift would +// be quiet - withDefaults() would keep the consumer running correctly while the +// parsed config, and therefore the scheduler's startup log, reported something +// else. +func TestConsumerConfigEnvDefaultsMatchConstants(t *testing.T) { + ty := reflect.TypeOf(ConsumerConfig{}) + for _, tc := range []struct { + field string + want string + }{ + {"Concurrency", "1"}, + {"AckWait", "1m"}, + {"MaxDeliver", "3"}, + } { + f, ok := ty.FieldByName(tc.field) + if !ok { + t.Fatalf("ConsumerConfig has no field %s", tc.field) + } + if got := f.Tag.Get("envDefault"); got != tc.want { + t.Errorf("%s envDefault = %q, want %q", tc.field, got, tc.want) + } + } + + // The literals above are only meaningful if they parse to the constants. + if d, err := time.ParseDuration("1m"); err != nil || d != DefaultAckWait { + t.Errorf("AckWait tag %q does not equal DefaultAckWait (%v)", "1m", DefaultAckWait) + } + if DefaultMaxDeliver != 3 { + t.Errorf("DefaultMaxDeliver = %d, but the envDefault tag says 3", DefaultMaxDeliver) + } + if DefaultConcurrency != 1 { + t.Errorf("DefaultConcurrency = %d, but the envDefault tag says 1", DefaultConcurrency) + } +} + +// TestConsumerConfigParsesDefaultsFromEmptyEnv is the behavioural half: with none +// of the variables set, a parsed config must already carry the documented +// defaults rather than zeros. +func TestConsumerConfigParsesDefaultsFromEmptyEnv(t *testing.T) { + // Clear rather than set: t.Setenv with an empty string still leaves the + // variable defined, and an explicit empty value is not an absent one. + for _, key := range []string{"CONCURRENCY", "NATS_ACK_WAIT", "NATS_MAX_DELIVER"} { + if old, ok := os.LookupEnv(key); ok { + t.Cleanup(func() { os.Setenv(key, old) }) + os.Unsetenv(key) + } + } + + var cfg ConsumerConfig + if err := env.Parse(&cfg); err != nil { + t.Fatalf("env.Parse: %v", err) + } + if cfg.Concurrency != DefaultConcurrency { + t.Errorf("Concurrency = %d, want %d", cfg.Concurrency, DefaultConcurrency) + } + if cfg.AckWait != DefaultAckWait { + t.Errorf("AckWait = %v, want %v", cfg.AckWait, DefaultAckWait) + } + if cfg.MaxDeliver != DefaultMaxDeliver { + t.Errorf("MaxDeliver = %d, want %d", cfg.MaxDeliver, DefaultMaxDeliver) + } +} From 2f6c0cc731e8e5d4669a5ffb02c0f8391110e3a8 Mon Sep 17 00:00:00 2001 From: Matthias Linhuber Date: Mon, 24 Aug 2026 23:36:29 +0200 Subject: [PATCH 8/8] Check the errors when saving and restoring test environment os.Setenv and os.Unsetenv both return errors. A failed restore would leave a variable cleared for every later test in the package, and the failure would be invisible. --- HadesScheduler/main_test.go | 10 ++++++++-- shared/nats/consumerconfig_test.go | 10 ++++++++-- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/HadesScheduler/main_test.go b/HadesScheduler/main_test.go index 1a2e1216..271a241e 100644 --- a/HadesScheduler/main_test.go +++ b/HadesScheduler/main_test.go @@ -25,8 +25,14 @@ func TestConsumerConfigDefaultsAreLoaded(t *testing.T) { // Restored by t.Cleanup so the test does not leak into its neighbours. for _, key := range []string{"CONCURRENCY", "NATS_ACK_WAIT", "NATS_MAX_DELIVER"} { if old, ok := os.LookupEnv(key); ok { - t.Cleanup(func() { os.Setenv(key, old) }) - os.Unsetenv(key) + t.Cleanup(func() { + if err := os.Setenv(key, old); err != nil { + t.Errorf("restoring %s: %v", key, err) + } + }) + } + if err := os.Unsetenv(key); err != nil { + t.Fatalf("unsetting %s: %v", key, err) } } diff --git a/shared/nats/consumerconfig_test.go b/shared/nats/consumerconfig_test.go index 90e994e6..301c418b 100644 --- a/shared/nats/consumerconfig_test.go +++ b/shared/nats/consumerconfig_test.go @@ -57,8 +57,14 @@ func TestConsumerConfigParsesDefaultsFromEmptyEnv(t *testing.T) { // variable defined, and an explicit empty value is not an absent one. for _, key := range []string{"CONCURRENCY", "NATS_ACK_WAIT", "NATS_MAX_DELIVER"} { if old, ok := os.LookupEnv(key); ok { - t.Cleanup(func() { os.Setenv(key, old) }) - os.Unsetenv(key) + t.Cleanup(func() { + if err := os.Setenv(key, old); err != nil { + t.Errorf("restoring %s: %v", key, err) + } + }) + } + if err := os.Unsetenv(key); err != nil { + t.Fatalf("unsetting %s: %v", key, err) } }