diff --git a/docs/cli-reference.md b/docs/cli-reference.md index 4aa0db4..c85c392 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -703,6 +703,12 @@ dw task-queue:resume orders --build-id build-2026.04.20-a3f dw task-queue:pause-activities orders --reason="payments vendor outage" dw task-queue:activity-dispatch orders dw task-queue:resume-activities orders + +# Inspect and retire an old worker build, or a whole queue (native Server 3.14.0+) +dw task-queue:retirement orders --build-id build-2026.04.20-a3f +dw task-queue:retire orders --build-id build-2026.04.20-a3f --expected-revision=sha256:... +dw task-queue:retirement orders +dw task-queue:retire orders ``` An activity dispatch pause holds every new activity lease on one task queue @@ -722,6 +728,34 @@ as published PHP Server 2.x, `dw` refuses with exit 8 before sending the request. `task-queue:describe` and `task-queue:list` show the activity dispatch state when the Server reports it, and print nothing new otherwise. +`task-queue:retirement` is a read-only inventory of everything that still +depends on one build (`--build-id` or `--unversioned`) or, without either, on +every cohort of the queue (Server #519): open runs pinned to it (including +waiting, continued and child runs), ready, leased and delayed tasks (activity +retries and timers), open activities, pending update validations, schedules +(queue scope only), and unattributed open runs, which make the inventory +incomplete. Each blocker has its exact count, up to 20 sample identities and a +recovery action. When `Retirable` is `yes`, the output prints the matching +`task-queue:retire` command bound to `observation.inventory_revision`. + +`task-queue:retire` sends one guarded retire request and never resends it. The +Server repeats the inventory inside the serialized transition and records +retirement only when it is empty: the build is never selected for new starts +again and its workers are marked draining; run pins, activity queues and +history are unchanged. A refusal is HTTP 409 and changes nothing; `dw` prints +the reason (`selected_for_new_starts`, `inventory_incomplete`, +`live_dependencies`, `inventory_changed`, `unknown_deployment` or +`unknown_task_queue`), each blocker with its sample and recovery, and the +Server's `expected_resolution`, and exits 2. `--expected-revision` refuses the +retire with `inventory_changed` if anything the inspection observed has +changed. `--json` returns the Server payload; a refusal keeps the usual error +envelope with the full body in `server_response`. + +Unlike `task-queue:drain`, which stops a build's polls immediately whether or +not work is still pinned to it, retirement waits for that work. Both commands +need a Server that advertises `capabilities.worker_build_retirement`; on any +other Server `dw` refuses with exit 8 before sending the request. + ### Worker Protocol Diagnostics ```bash diff --git a/rust/README.md b/rust/README.md index ce34640..8a89cd2 100644 --- a/rust/README.md +++ b/rust/README.md @@ -44,6 +44,7 @@ command is ported. | `--tls-verify=false` against HTTPS: no certificate or hostname checks, as in 2.x, plus a stderr warning on every such command (also with `--json` and `-q`) | Ported, intentional addition | | `batch:cancel`, `batch:signal`, `batch:update`, `batch:show`, `batch:resume`: resumable bulk operations with a private manifest and an optional `--deadline` ([runbook](../docs/batch-operations.md), cli#60). `parity/live_batch.py` runs them against the published Servers in CI | Rust-only, new | | `task-queue:pause-activities`, `task-queue:resume-activities`, `task-queue:activity-dispatch`: pause, resume and read activity dispatch on one task queue (Server #577), one request each after checking cluster info for `capabilities.task_queue_activity_dispatch_pause`; `task-queue:describe` and `task-queue:list` show the state when the Server reports it | Rust-only, new | +| `task-queue:retirement`, `task-queue:retire`: inspect what still depends on one worker build (`--build-id`, `--unversioned`) or a whole task queue, and retire it only when nothing does (Server #519), one request each after checking cluster info for `capabilities.worker_build_retirement`; `--expected-revision` binds the retire to an inspected inventory, and a 409 refusal (nothing changed) prints its blockers, recovery and expected resolution and exits 2 | Rust-only, new | | `workflow:update-outcome`: read an update's outcome later by its update ID (Server #1131, durable-workflow/.github#212), one GET after checking cluster info for `capabilities.update_outcome_reads`; pending, completed (including a null result), failed (exit 2), rejected and `update_not_found` (exit 5) are reported distinctly, and the update is never sent again. `workflow:update` points an unfinished update at it when the Server advertises the capability | Rust-only, new | Server calls go through the `durable-workflow` crate. The unreleased native diff --git a/rust/parity/catalog-additions.json b/rust/parity/catalog-additions.json index c0ebd29..ebbb706 100644 --- a/rust/parity/catalog-additions.json +++ b/rust/parity/catalog-additions.json @@ -1,5 +1,5 @@ { - "comment": "Rust-only commands appended to the 2.x catalog by update-catalog.sh: batch:* (cli#60), the task queue activity dispatch pause (task-queue:activity-dispatch, task-queue:pause-activities, task-queue:resume-activities; Server #577) and workflow:update-outcome (Server #1131, durable-workflow/.github#212). 2.x has no equivalent, so parity skips their help and strips them from listings.", + "comment": "Rust-only commands appended to the 2.x catalog by update-catalog.sh: batch:* (cli#60), the task queue activity dispatch pause (task-queue:activity-dispatch, task-queue:pause-activities, task-queue:resume-activities; Server #577), guarded worker build and task queue retirement (task-queue:retirement, task-queue:retire; Server #519) and workflow:update-outcome (Server #1131, durable-workflow/.github#212). 2.x has no equivalent, so parity skips their help and strips them from listings.", "commands": [ { "name": "batch:cancel", @@ -1528,6 +1528,365 @@ }, "rust_only": true }, + { + "name": "task-queue:retire", + "description": "Retire a worker build or task queue when nothing depends on it", + "synopsis": "task-queue:retire [-s|--server [SERVER]] [--namespace [NAMESPACE]] [--token [TOKEN]] [--tls-verify TLS-VERIFY] [--env ENV] [--output OUTPUT] [--build-id BUILD-ID] [--unversioned] [--expected-revision EXPECTED-REVISION] [--json] [--] ", + "aliases": [], + "hidden": false, + "help": "Retire one worker build (--build-id or --unversioned), or every\ncohort on the task queue, only when nothing depends on it. The Server\nrepeats the dw task-queue:retirement check inside the same serialized\ntransition that starts, continuations, retries and task creation take,\nand records retirement only when the inventory is empty.\n\nA retired build is never selected for new starts, cannot be promoted, and\nits workers are marked draining. When every cohort on a queue is retired\nand no active worker remains, new starts on the queue are refused until a\nnew worker cohort registers. Run pins, activity queues and history are\nunchanged.\n\nThe request is sent once and never resent. A refusal (HTTP 409) changes\nnothing: dw prints the reason (selected_for_new_starts,\ninventory_incomplete, live_dependencies, inventory_changed,\nunknown_deployment or unknown_task_queue), each blocker with its count,\nsample and recovery action, and exits 2. Promote the replacement build\nfirst with dw task-queue:promote.\n\nPass --expected-revision with the inventory_revision from an inspection\nto refuse if anything that inspection observed has changed.\n\nNeeds a Server that advertises the worker_build_retirement capability\n(native Server 3.14.0 or later). dw reads cluster info first and refuses\nwith exit 8, without sending the request, when it is missing.\n\nExamples:\n\n dw task-queue:retire orders --build-id build-2026.04.21-z9 --expected-revision sha256:...\n dw task-queue:retire orders --unversioned\n dw task-queue:retire orders --json", + "definition": { + "arguments": { + "task-queue": { + "name": "task-queue", + "is_required": true, + "is_array": false, + "description": "Task queue name, exactly as workers register it", + "default": null + } + }, + "options": { + "server": { + "name": "--server", + "shortcut": "-s", + "accept_value": true, + "is_value_required": false, + "is_multiple": false, + "description": "Server URL", + "default": null + }, + "namespace": { + "name": "--namespace", + "shortcut": "", + "accept_value": true, + "is_value_required": false, + "is_multiple": false, + "description": "Target namespace", + "default": null + }, + "token": { + "name": "--token", + "shortcut": "", + "accept_value": true, + "is_value_required": false, + "is_multiple": false, + "description": "Auth token", + "default": null + }, + "tls-verify": { + "name": "--tls-verify", + "shortcut": "", + "accept_value": true, + "is_value_required": true, + "is_multiple": false, + "description": "Verify TLS certificates (true/false). Defaults to $DURABLE_WORKFLOW_TLS_VERIFY, then the selected profile, then true.", + "default": null + }, + "env": { + "name": "--env", + "shortcut": "", + "accept_value": true, + "is_value_required": true, + "is_multiple": false, + "description": "Named dw environment to use (overrides $DW_ENV and any env set via `dw env:use`). Hard-fails when the profile does not exist.", + "default": null + }, + "output": { + "name": "--output", + "shortcut": "", + "accept_value": true, + "is_value_required": true, + "is_multiple": false, + "description": "Output format: table (human-readable), json (single JSON document), jsonl (one JSON object per line, for list commands)", + "default": "table" + }, + "build-id": { + "name": "--build-id", + "shortcut": "", + "accept_value": true, + "is_value_required": true, + "is_multiple": false, + "description": "Build ID of one cohort on the queue; omit it (and --unversioned) for the whole queue", + "default": null + }, + "unversioned": { + "name": "--unversioned", + "shortcut": "", + "accept_value": false, + "is_value_required": false, + "is_multiple": false, + "description": "Target the unversioned cohort (workers without a build_id)", + "default": false + }, + "expected-revision": { + "name": "--expected-revision", + "shortcut": "", + "accept_value": true, + "is_value_required": true, + "is_multiple": false, + "description": "observation.inventory_revision from dw task-queue:retirement; refuse if the inventory changed since", + "default": null + }, + "json": { + "name": "--json", + "shortcut": "", + "accept_value": false, + "is_value_required": false, + "is_multiple": false, + "description": "Output the command response as JSON (alias for --output=json)", + "default": false + }, + "help": { + "name": "--help", + "shortcut": "-h", + "accept_value": false, + "is_value_required": false, + "is_multiple": false, + "description": "Display help for the given command. When no command is given display help for the list command", + "default": false + }, + "silent": { + "name": "--silent", + "shortcut": "", + "accept_value": false, + "is_value_required": false, + "is_multiple": false, + "description": "Do not output any message", + "default": false + }, + "quiet": { + "name": "--quiet", + "shortcut": "-q", + "accept_value": false, + "is_value_required": false, + "is_multiple": false, + "description": "Only errors are displayed. All other output is suppressed", + "default": false + }, + "verbose": { + "name": "--verbose", + "shortcut": "-v|-vv|-vvv", + "accept_value": false, + "is_value_required": false, + "is_multiple": false, + "description": "Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug", + "default": false + }, + "version": { + "name": "--version", + "shortcut": "-V", + "accept_value": false, + "is_value_required": false, + "is_multiple": false, + "description": "Display this application version", + "default": false + }, + "ansi": { + "name": "--ansi", + "shortcut": "", + "accept_value": false, + "is_value_required": false, + "is_multiple": false, + "description": "Force (or disable --no-ansi) ANSI output", + "default": null + }, + "no-ansi": { + "name": "--no-ansi", + "shortcut": "", + "accept_value": false, + "is_value_required": false, + "is_multiple": false, + "description": "Negate the \"--ansi\" option", + "default": null + }, + "no-interaction": { + "name": "--no-interaction", + "shortcut": "-n", + "accept_value": false, + "is_value_required": false, + "is_multiple": false, + "description": "Do not ask any interactive question", + "default": false + } + } + }, + "rust_only": true + }, + { + "name": "task-queue:retirement", + "description": "Show what blocks retiring a worker build or task queue", + "synopsis": "task-queue:retirement [-s|--server [SERVER]] [--namespace [NAMESPACE]] [--token [TOKEN]] [--tls-verify TLS-VERIFY] [--env ENV] [--output OUTPUT] [--build-id BUILD-ID] [--unversioned] [--json] [--] ", + "aliases": [], + "hidden": false, + "help": "Show what still depends on one worker build, or on the whole task queue,\nin the selected namespace, and whether it can be retired safely. This is a\nread-only preview: nothing changes.\n\nWith --build-id (or --unversioned) the inventory covers runs pinned\nto that build on the queue; without either it covers every cohort on the\nqueue, including schedules that start runs on it. Each blocker gives its\nexact count, up to 20 sample identities and a recovery action:\n\n - open runs (waiting, continued and child runs keep their build pin);\n - ready, leased and delayed tasks (activity retries and timers);\n - open activities recorded on the queue;\n - pending update validations;\n - schedules (whole queue only);\n - unattributed open runs, which make the inventory incomplete and\n retirement unavailable.\n\nWhen it is retirable, pass its observation.inventory_revision to\ndw task-queue:retire --expected-revision so the retire is refused if\nanything changed in between.\n\nNeeds a Server that advertises the worker_build_retirement capability\n(native Server 3.14.0 or later). dw reads cluster info first and refuses\nwith exit 8, without sending the request, when it is missing.\n\nExamples:\n\n dw task-queue:retirement orders --build-id build-2026.04.21-z9\n dw task-queue:retirement orders --unversioned --json\n dw task-queue:retirement orders", + "definition": { + "arguments": { + "task-queue": { + "name": "task-queue", + "is_required": true, + "is_array": false, + "description": "Task queue name, exactly as workers register it", + "default": null + } + }, + "options": { + "server": { + "name": "--server", + "shortcut": "-s", + "accept_value": true, + "is_value_required": false, + "is_multiple": false, + "description": "Server URL", + "default": null + }, + "namespace": { + "name": "--namespace", + "shortcut": "", + "accept_value": true, + "is_value_required": false, + "is_multiple": false, + "description": "Target namespace", + "default": null + }, + "token": { + "name": "--token", + "shortcut": "", + "accept_value": true, + "is_value_required": false, + "is_multiple": false, + "description": "Auth token", + "default": null + }, + "tls-verify": { + "name": "--tls-verify", + "shortcut": "", + "accept_value": true, + "is_value_required": true, + "is_multiple": false, + "description": "Verify TLS certificates (true/false). Defaults to $DURABLE_WORKFLOW_TLS_VERIFY, then the selected profile, then true.", + "default": null + }, + "env": { + "name": "--env", + "shortcut": "", + "accept_value": true, + "is_value_required": true, + "is_multiple": false, + "description": "Named dw environment to use (overrides $DW_ENV and any env set via `dw env:use`). Hard-fails when the profile does not exist.", + "default": null + }, + "output": { + "name": "--output", + "shortcut": "", + "accept_value": true, + "is_value_required": true, + "is_multiple": false, + "description": "Output format: table (human-readable), json (single JSON document), jsonl (one JSON object per line, for list commands)", + "default": "table" + }, + "build-id": { + "name": "--build-id", + "shortcut": "", + "accept_value": true, + "is_value_required": true, + "is_multiple": false, + "description": "Build ID of one cohort on the queue; omit it (and --unversioned) for the whole queue", + "default": null + }, + "unversioned": { + "name": "--unversioned", + "shortcut": "", + "accept_value": false, + "is_value_required": false, + "is_multiple": false, + "description": "Target the unversioned cohort (workers without a build_id)", + "default": false + }, + "json": { + "name": "--json", + "shortcut": "", + "accept_value": false, + "is_value_required": false, + "is_multiple": false, + "description": "Output the command response as JSON (alias for --output=json)", + "default": false + }, + "help": { + "name": "--help", + "shortcut": "-h", + "accept_value": false, + "is_value_required": false, + "is_multiple": false, + "description": "Display help for the given command. When no command is given display help for the list command", + "default": false + }, + "silent": { + "name": "--silent", + "shortcut": "", + "accept_value": false, + "is_value_required": false, + "is_multiple": false, + "description": "Do not output any message", + "default": false + }, + "quiet": { + "name": "--quiet", + "shortcut": "-q", + "accept_value": false, + "is_value_required": false, + "is_multiple": false, + "description": "Only errors are displayed. All other output is suppressed", + "default": false + }, + "verbose": { + "name": "--verbose", + "shortcut": "-v|-vv|-vvv", + "accept_value": false, + "is_value_required": false, + "is_multiple": false, + "description": "Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug", + "default": false + }, + "version": { + "name": "--version", + "shortcut": "-V", + "accept_value": false, + "is_value_required": false, + "is_multiple": false, + "description": "Display this application version", + "default": false + }, + "ansi": { + "name": "--ansi", + "shortcut": "", + "accept_value": false, + "is_value_required": false, + "is_multiple": false, + "description": "Force (or disable --no-ansi) ANSI output", + "default": null + }, + "no-ansi": { + "name": "--no-ansi", + "shortcut": "", + "accept_value": false, + "is_value_required": false, + "is_multiple": false, + "description": "Negate the \"--ansi\" option", + "default": null + }, + "no-interaction": { + "name": "--no-interaction", + "shortcut": "-n", + "accept_value": false, + "is_value_required": false, + "is_multiple": false, + "description": "Do not ask any interactive question", + "default": false + } + } + }, + "rust_only": true + }, { "name": "workflow:update-outcome", "description": "Read an update's outcome later by its update ID", diff --git a/rust/parity/parity.py b/rust/parity/parity.py index 70a8771..a9c6a4f 100755 --- a/rust/parity/parity.py +++ b/rust/parity/parity.py @@ -498,7 +498,7 @@ def print_result(case, differences, reason, reference, candidate, verbose): def rust_only_commands(): """Catalog commands with no 2.x equivalent (cli#60, Server #577, - Server #1131), in catalog order.""" + Server #1131, Server #519), in catalog order.""" with open(os.path.join(CRATE, "src", "catalog.json"), encoding="utf-8") as handle: return [command["name"] for command in json.load(handle)["commands"] if command.get("rust_only")] diff --git a/rust/parity/test_parity.py b/rust/parity/test_parity.py index 7e87840..94c7d49 100644 --- a/rust/parity/test_parity.py +++ b/rust/parity/test_parity.py @@ -269,7 +269,8 @@ class RustOnlyCommandTest(unittest.TestCase): def test_the_catalog_marks_the_batch_activity_dispatch_and_update_outcome_commands_rust_only(self): self.assertEqual(["batch:cancel", "batch:resume", "batch:show", "batch:signal", "batch:update", "task-queue:activity-dispatch", "task-queue:pause-activities", - "task-queue:resume-activities", "workflow:update-outcome", "workflow:version-usage"], + "task-queue:resume-activities", "task-queue:retire", "task-queue:retirement", + "workflow:update-outcome", "workflow:version-usage"], parity.rust_only_commands()) def test_rust_only_help_is_skipped_but_2x_help_is_kept(self): diff --git a/rust/parity/update-catalog.sh b/rust/parity/update-catalog.sh index 1505676..c7a7a48 100755 --- a/rust/parity/update-catalog.sh +++ b/rust/parity/update-catalog.sh @@ -42,7 +42,7 @@ for command in listing["commands"]: if commands[-1][field] != update["reference"]: raise SystemExit("Reference catalog metadata changed: " + command["name"] + ":" + field) commands[-1][field] = update["candidate"] -# Rust-only commands (cli#60, Server #577, Server #1131) go into their namespace in name order. +# Rust-only commands (cli#60, Server #577, Server #1131, Server #519) go into their namespace in name order. with open(os.environ["DW_CATALOG_ADDITIONS"], encoding="utf-8") as handle: additions = json.load(handle)["commands"] for addition in additions: diff --git a/rust/src/catalog.json b/rust/src/catalog.json index b50852f..a0663af 100644 --- a/rust/src/catalog.json +++ b/rust/src/catalog.json @@ -11430,6 +11430,365 @@ }, "rust_only": true }, + { + "name": "task-queue:retire", + "description": "Retire a worker build or task queue when nothing depends on it", + "synopsis": "task-queue:retire [-s|--server [SERVER]] [--namespace [NAMESPACE]] [--token [TOKEN]] [--tls-verify TLS-VERIFY] [--env ENV] [--output OUTPUT] [--build-id BUILD-ID] [--unversioned] [--expected-revision EXPECTED-REVISION] [--json] [--] ", + "aliases": [], + "hidden": false, + "help": "Retire one worker build (--build-id or --unversioned), or every\ncohort on the task queue, only when nothing depends on it. The Server\nrepeats the dw task-queue:retirement check inside the same serialized\ntransition that starts, continuations, retries and task creation take,\nand records retirement only when the inventory is empty.\n\nA retired build is never selected for new starts, cannot be promoted, and\nits workers are marked draining. When every cohort on a queue is retired\nand no active worker remains, new starts on the queue are refused until a\nnew worker cohort registers. Run pins, activity queues and history are\nunchanged.\n\nThe request is sent once and never resent. A refusal (HTTP 409) changes\nnothing: dw prints the reason (selected_for_new_starts,\ninventory_incomplete, live_dependencies, inventory_changed,\nunknown_deployment or unknown_task_queue), each blocker with its count,\nsample and recovery action, and exits 2. Promote the replacement build\nfirst with dw task-queue:promote.\n\nPass --expected-revision with the inventory_revision from an inspection\nto refuse if anything that inspection observed has changed.\n\nNeeds a Server that advertises the worker_build_retirement capability\n(native Server 3.14.0 or later). dw reads cluster info first and refuses\nwith exit 8, without sending the request, when it is missing.\n\nExamples:\n\n dw task-queue:retire orders --build-id build-2026.04.21-z9 --expected-revision sha256:...\n dw task-queue:retire orders --unversioned\n dw task-queue:retire orders --json", + "definition": { + "arguments": { + "task-queue": { + "name": "task-queue", + "is_required": true, + "is_array": false, + "description": "Task queue name, exactly as workers register it", + "default": null + } + }, + "options": { + "server": { + "name": "--server", + "shortcut": "-s", + "accept_value": true, + "is_value_required": false, + "is_multiple": false, + "description": "Server URL", + "default": null + }, + "namespace": { + "name": "--namespace", + "shortcut": "", + "accept_value": true, + "is_value_required": false, + "is_multiple": false, + "description": "Target namespace", + "default": null + }, + "token": { + "name": "--token", + "shortcut": "", + "accept_value": true, + "is_value_required": false, + "is_multiple": false, + "description": "Auth token", + "default": null + }, + "tls-verify": { + "name": "--tls-verify", + "shortcut": "", + "accept_value": true, + "is_value_required": true, + "is_multiple": false, + "description": "Verify TLS certificates (true/false). Defaults to $DURABLE_WORKFLOW_TLS_VERIFY, then the selected profile, then true.", + "default": null + }, + "env": { + "name": "--env", + "shortcut": "", + "accept_value": true, + "is_value_required": true, + "is_multiple": false, + "description": "Named dw environment to use (overrides $DW_ENV and any env set via `dw env:use`). Hard-fails when the profile does not exist.", + "default": null + }, + "output": { + "name": "--output", + "shortcut": "", + "accept_value": true, + "is_value_required": true, + "is_multiple": false, + "description": "Output format: table (human-readable), json (single JSON document), jsonl (one JSON object per line, for list commands)", + "default": "table" + }, + "build-id": { + "name": "--build-id", + "shortcut": "", + "accept_value": true, + "is_value_required": true, + "is_multiple": false, + "description": "Build ID of one cohort on the queue; omit it (and --unversioned) for the whole queue", + "default": null + }, + "unversioned": { + "name": "--unversioned", + "shortcut": "", + "accept_value": false, + "is_value_required": false, + "is_multiple": false, + "description": "Target the unversioned cohort (workers without a build_id)", + "default": false + }, + "expected-revision": { + "name": "--expected-revision", + "shortcut": "", + "accept_value": true, + "is_value_required": true, + "is_multiple": false, + "description": "observation.inventory_revision from dw task-queue:retirement; refuse if the inventory changed since", + "default": null + }, + "json": { + "name": "--json", + "shortcut": "", + "accept_value": false, + "is_value_required": false, + "is_multiple": false, + "description": "Output the command response as JSON (alias for --output=json)", + "default": false + }, + "help": { + "name": "--help", + "shortcut": "-h", + "accept_value": false, + "is_value_required": false, + "is_multiple": false, + "description": "Display help for the given command. When no command is given display help for the list command", + "default": false + }, + "silent": { + "name": "--silent", + "shortcut": "", + "accept_value": false, + "is_value_required": false, + "is_multiple": false, + "description": "Do not output any message", + "default": false + }, + "quiet": { + "name": "--quiet", + "shortcut": "-q", + "accept_value": false, + "is_value_required": false, + "is_multiple": false, + "description": "Only errors are displayed. All other output is suppressed", + "default": false + }, + "verbose": { + "name": "--verbose", + "shortcut": "-v|-vv|-vvv", + "accept_value": false, + "is_value_required": false, + "is_multiple": false, + "description": "Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug", + "default": false + }, + "version": { + "name": "--version", + "shortcut": "-V", + "accept_value": false, + "is_value_required": false, + "is_multiple": false, + "description": "Display this application version", + "default": false + }, + "ansi": { + "name": "--ansi", + "shortcut": "", + "accept_value": false, + "is_value_required": false, + "is_multiple": false, + "description": "Force (or disable --no-ansi) ANSI output", + "default": null + }, + "no-ansi": { + "name": "--no-ansi", + "shortcut": "", + "accept_value": false, + "is_value_required": false, + "is_multiple": false, + "description": "Negate the \"--ansi\" option", + "default": null + }, + "no-interaction": { + "name": "--no-interaction", + "shortcut": "-n", + "accept_value": false, + "is_value_required": false, + "is_multiple": false, + "description": "Do not ask any interactive question", + "default": false + } + } + }, + "rust_only": true + }, + { + "name": "task-queue:retirement", + "description": "Show what blocks retiring a worker build or task queue", + "synopsis": "task-queue:retirement [-s|--server [SERVER]] [--namespace [NAMESPACE]] [--token [TOKEN]] [--tls-verify TLS-VERIFY] [--env ENV] [--output OUTPUT] [--build-id BUILD-ID] [--unversioned] [--json] [--] ", + "aliases": [], + "hidden": false, + "help": "Show what still depends on one worker build, or on the whole task queue,\nin the selected namespace, and whether it can be retired safely. This is a\nread-only preview: nothing changes.\n\nWith --build-id (or --unversioned) the inventory covers runs pinned\nto that build on the queue; without either it covers every cohort on the\nqueue, including schedules that start runs on it. Each blocker gives its\nexact count, up to 20 sample identities and a recovery action:\n\n - open runs (waiting, continued and child runs keep their build pin);\n - ready, leased and delayed tasks (activity retries and timers);\n - open activities recorded on the queue;\n - pending update validations;\n - schedules (whole queue only);\n - unattributed open runs, which make the inventory incomplete and\n retirement unavailable.\n\nWhen it is retirable, pass its observation.inventory_revision to\ndw task-queue:retire --expected-revision so the retire is refused if\nanything changed in between.\n\nNeeds a Server that advertises the worker_build_retirement capability\n(native Server 3.14.0 or later). dw reads cluster info first and refuses\nwith exit 8, without sending the request, when it is missing.\n\nExamples:\n\n dw task-queue:retirement orders --build-id build-2026.04.21-z9\n dw task-queue:retirement orders --unversioned --json\n dw task-queue:retirement orders", + "definition": { + "arguments": { + "task-queue": { + "name": "task-queue", + "is_required": true, + "is_array": false, + "description": "Task queue name, exactly as workers register it", + "default": null + } + }, + "options": { + "server": { + "name": "--server", + "shortcut": "-s", + "accept_value": true, + "is_value_required": false, + "is_multiple": false, + "description": "Server URL", + "default": null + }, + "namespace": { + "name": "--namespace", + "shortcut": "", + "accept_value": true, + "is_value_required": false, + "is_multiple": false, + "description": "Target namespace", + "default": null + }, + "token": { + "name": "--token", + "shortcut": "", + "accept_value": true, + "is_value_required": false, + "is_multiple": false, + "description": "Auth token", + "default": null + }, + "tls-verify": { + "name": "--tls-verify", + "shortcut": "", + "accept_value": true, + "is_value_required": true, + "is_multiple": false, + "description": "Verify TLS certificates (true/false). Defaults to $DURABLE_WORKFLOW_TLS_VERIFY, then the selected profile, then true.", + "default": null + }, + "env": { + "name": "--env", + "shortcut": "", + "accept_value": true, + "is_value_required": true, + "is_multiple": false, + "description": "Named dw environment to use (overrides $DW_ENV and any env set via `dw env:use`). Hard-fails when the profile does not exist.", + "default": null + }, + "output": { + "name": "--output", + "shortcut": "", + "accept_value": true, + "is_value_required": true, + "is_multiple": false, + "description": "Output format: table (human-readable), json (single JSON document), jsonl (one JSON object per line, for list commands)", + "default": "table" + }, + "build-id": { + "name": "--build-id", + "shortcut": "", + "accept_value": true, + "is_value_required": true, + "is_multiple": false, + "description": "Build ID of one cohort on the queue; omit it (and --unversioned) for the whole queue", + "default": null + }, + "unversioned": { + "name": "--unversioned", + "shortcut": "", + "accept_value": false, + "is_value_required": false, + "is_multiple": false, + "description": "Target the unversioned cohort (workers without a build_id)", + "default": false + }, + "json": { + "name": "--json", + "shortcut": "", + "accept_value": false, + "is_value_required": false, + "is_multiple": false, + "description": "Output the command response as JSON (alias for --output=json)", + "default": false + }, + "help": { + "name": "--help", + "shortcut": "-h", + "accept_value": false, + "is_value_required": false, + "is_multiple": false, + "description": "Display help for the given command. When no command is given display help for the list command", + "default": false + }, + "silent": { + "name": "--silent", + "shortcut": "", + "accept_value": false, + "is_value_required": false, + "is_multiple": false, + "description": "Do not output any message", + "default": false + }, + "quiet": { + "name": "--quiet", + "shortcut": "-q", + "accept_value": false, + "is_value_required": false, + "is_multiple": false, + "description": "Only errors are displayed. All other output is suppressed", + "default": false + }, + "verbose": { + "name": "--verbose", + "shortcut": "-v|-vv|-vvv", + "accept_value": false, + "is_value_required": false, + "is_multiple": false, + "description": "Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug", + "default": false + }, + "version": { + "name": "--version", + "shortcut": "-V", + "accept_value": false, + "is_value_required": false, + "is_multiple": false, + "description": "Display this application version", + "default": false + }, + "ansi": { + "name": "--ansi", + "shortcut": "", + "accept_value": false, + "is_value_required": false, + "is_multiple": false, + "description": "Force (or disable --no-ansi) ANSI output", + "default": null + }, + "no-ansi": { + "name": "--no-ansi", + "shortcut": "", + "accept_value": false, + "is_value_required": false, + "is_multiple": false, + "description": "Negate the \"--ansi\" option", + "default": null + }, + "no-interaction": { + "name": "--no-interaction", + "shortcut": "-n", + "accept_value": false, + "is_value_required": false, + "is_multiple": false, + "description": "Do not ask any interactive question", + "default": false + } + } + }, + "rust_only": true + }, { "name": "worker:deregister", "description": "Deregister a worker from the server", diff --git a/rust/src/commands/task_queue.rs b/rust/src/commands/task_queue.rs index 4499e2c..4dea964 100644 --- a/rust/src/commands/task_queue.rs +++ b/rust/src/commands/task_queue.rs @@ -912,3 +912,271 @@ fn principal_label(principal: &Value) -> Option { fn reported_dispatch(queue: &Value) -> Option<&Value> { php::get(queue, "activity_dispatch").filter(|value| value.is_object()) } + +/// Cluster info capability for the guarded build and queue retirement +/// routes (Server #519, native Server 3.14.0). +const WORKER_BUILD_RETIREMENT: &str = "worker_build_retirement"; + +const RETIREMENT_UNSUPPORTED: &str = "Guarded worker build and task queue retirement needs a native Durable Workflow Server 3.14.0 or later; published PHP Server 2.x has no such route."; + +const RETIREMENT_NEXT_STEP: &str = "Connect to a Server that advertises this capability. Without it, inspect the build with dw task-queue:build-ids and stop its workers only after its pinned runs close; dw task-queue:drain stops a build's polls immediately, whether or not work is still pinned to it."; + +/// `task-queue:retirement`: one read of the live dependencies that block +/// retiring one build (`--build-id`, `--unversioned`) or the whole queue. +pub fn retirement(context: &Context, input: &Input) -> Result { + retirement_request(context, input, false) +} + +/// `task-queue:retire`: one guarded retire request, never resent. A 409 +/// refusal changed nothing and is reported with its blockers. +pub fn retire(context: &Context, input: &Input) -> Result { + retirement_request(context, input, true) +} + +/// The cohort a retirement command names: `None` for the whole queue, +/// `Some(None)` for the unversioned cohort, `Some(Some(id))` for a build. +fn retirement_target(input: &Input) -> Result>, &'static str> { + let unversioned = input.flag("unversioned"); + let build_id = input.opt("build-id").flatten().filter(|id| !id.is_empty()); + match (unversioned, build_id) { + (true, Some(_)) => Err("--unversioned cannot be combined with --build-id. Choose one."), + (true, None) => Ok(Some(None)), + // The deployment name is `task_queue@build_id`, with `unversioned` + // naming the unversioned cohort: such a build id would address + // another cohort than the one given. + (false, Some(id)) if id.contains('@') => { + Err("A build_id containing \"@\" cannot be addressed by the deployment retirement route.") + } + (false, Some("unversioned")) => Err( + "The build_id \"unversioned\" names the unversioned cohort on this route. Pass --unversioned to target it.", + ), + (false, Some(id)) => Ok(Some(Some(id))), + (false, None) => Ok(None), + } +} + +fn retirement_request(context: &Context, input: &Input, retire: bool) -> Result { + let task_queue = input.arg("task-queue").unwrap_or_default(); + let target = match retirement_target(input) { + Ok(target) => target, + Err(message) => return Ok(crate::command_usage_error(&input.command, message)), + }; + let expected_revision = if retire { + input.opt_str("expected-revision") + } else { + None + }; + let info = context.preflight(false)?; + crate::compat::require_capability( + &info, + crate::build_info::version(), + WORKER_BUILD_RETIREMENT, + RETIREMENT_UNSUPPORTED, + RETIREMENT_NEXT_STEP, + ) + .map_err(CliError::Compatibility)?; + let action = if retire { "retire" } else { "retirement" }; + let namespace = context.connection.namespace.as_str(); + let segments: Vec = match target { + // `{namespace}/{task_queue}@{build_id}`; each part is one encoded + // path segment, so a queue name cannot select another route. + Some(build) => vec![ + "deployments".into(), + namespace.into(), + format!("{task_queue}@{}", build.unwrap_or("unversioned")), + action.into(), + ], + None => vec!["task-queues".into(), task_queue.into(), action.into()], + }; + let request = if retire { + let body = match expected_revision { + Some(revision) => json!({ "expected_inventory_revision": revision }), + None => json!({}), + }; + RawRequest::post(segments).json(body) + } else { + RawRequest::get(segments) + }; + let result = with_namespace( + context.resource_request(request)?, + &context.connection.namespace, + None, + ); + if context.mode.machine_readable() { + output::print_json(&result); + return Ok(0); + } + let shown_queue = match php::get(&result, "task_queue").filter(|value| !value.is_null()) { + Some(value) => text(Some(value)), + None => formatter::display_text(task_queue), + }; + let subject = match target { + Some(build) => format!( + "build_id {} on task queue {shown_queue}", + formatter::display_text(&build_id_label(build.map(|id| json!(id)).as_ref())) + ), + None => format!("task queue {shown_queue}"), + }; + if retire { + formatter::writeln_out(&format!("Retired {subject}.")); + } else { + formatter::writeln_out(&format!("Retirement inventory for {subject}")); + } + write_namespace_line(&result); + for line in retirement_lines(&result, !retire) { + formatter::writeln_out(&line); + } + let message = php::get(&result, "message").filter(|value| nonempty_scalar(Some(value))); + let mut closing = Vec::new(); + if let Some(message) = message { + closing.push(text(Some(message))); + } + if !retire { + if let Some(resolution) = + php::get(&result, "expected_resolution").filter(|value| nonempty_scalar(Some(value))) + { + closing.push(format!("Next: {}", text(Some(resolution)))); + } else if php::get(&result, "retirable") == Some(&Value::Bool(true)) { + let target_flag = match target { + Some(Some(id)) => format!(" --build-id={}", formatter::display_text(id)), + Some(None) => " --unversioned".into(), + None => String::new(), + }; + let revision = php::array_get(php::get(&result, "observation"), "inventory_revision") + .filter(|value| nonempty_scalar(Some(value))) + .map(|value| format!(" --expected-revision={}", text(Some(value)))) + .unwrap_or_default(); + closing.push(format!( + "Retire it with dw task-queue:retire {}{target_flag}{revision}; the Server repeats this check atomically and refuses if anything changed.", + formatter::display_text(task_queue) + )); + } + } + if !closing.is_empty() { + formatter::writeln_out(""); + for line in closing { + formatter::writeln_out(&line); + } + } + Ok(0) +} + +/// The inventory of a retirement inspection, retire receipt or 409 +/// refusal, as indented `Label: value` lines, then each blocker with its +/// count, details, recovery and sample. `verdict` adds whether it is +/// retirable and why not, which a receipt and a refusal already state. +pub(crate) fn retirement_lines(result: &Value, verdict: bool) -> Vec { + let field = |value: Option<&Value>| { + value + .filter(|value| nonempty_scalar(Some(value))) + .map(|value| text(Some(value))) + }; + let mut lines = Vec::new(); + if verdict { + let retirable = match php::get(result, "retirable") { + Some(Value::Bool(true)) => "yes", + Some(Value::Bool(false)) => "no", + _ => "-", + }; + lines.push(format!(" Retirable: {retirable}")); + if let Some(reason) = field(php::get(result, "reason")) { + lines.push(format!(" Reason: {reason}")); + } + } + if let Some(at) = field(php::get(result, "retired_at")) { + lines.push(format!(" Retired at: {at}")); + } + if let Some(by) = php::get(result, "retired_by").and_then(principal_label) { + lines.push(format!(" Retired by: {by}")); + } + let observation = php::get(result, "observation"); + for (label, key) in [ + ("Inventory", "status"), + ("Inventory revision", "inventory_revision"), + ("Observed at", "observed_at"), + ] { + if let Some(value) = field(php::array_get(observation, key)) { + lines.push(format!(" {label}: {value}")); + } + } + let build_ids = php::get(result, "build_ids") + .filter(|value| value.is_array()) + .map(|ids| { + php::values(ids) + .into_iter() + .map(|id| formatter::display_text(&build_id_label(Some(id)))) + .collect::>() + }) + .unwrap_or_default(); + if !build_ids.is_empty() { + lines.push(format!(" Build IDs: {}", build_ids.join(", "))); + } + let blockers = php::get(result, "blockers") + .filter(|value| value.is_array()) + .map(php::values) + .unwrap_or_default(); + if let Some(counts) = php::get(result, "counts").filter(|value| value.is_object()) { + let rows = counts + .as_object() + .into_iter() + .flatten() + .map(|(kind, count)| vec![formatter::display_text(kind), text_or(Some(count), "-")]) + .collect::>(); + if !rows.is_empty() { + lines.push(String::new()); + lines.push(output::render_table(&["Dependency", "Count"], &rows)); + } + } + if !blockers.is_empty() { + lines.push(String::new()); + lines.push("Blockers:".into()); + } + for blocker in blockers { + let kind = text_or(php::get(blocker, "kind"), "-"); + let count = text_or(php::get(blocker, "count"), "-"); + let details = blocker + .as_object() + .into_iter() + .flatten() + .filter(|(key, value)| { + !matches!( + key.as_str(), + "kind" | "count" | "sample" | "sample_truncated" | "recovery" + ) && php::is_scalar(Some(*value)) + }) + .map(|(key, value)| format!("{} {}", formatter::display_text(key), text(Some(value)))) + .collect::>(); + if details.is_empty() { + lines.push(format!(" {kind}: {count}")); + } else { + lines.push(format!(" {kind}: {count} ({})", details.join(", "))); + } + if let Some(recovery) = field(php::get(blocker, "recovery")) { + lines.push(format!(" Recovery: {recovery}")); + } + let samples = php::get(blocker, "sample") + .filter(|value| value.is_array()) + .map(php::values) + .unwrap_or_default(); + for sample in &samples { + lines.push(format!(" - {}", sample_label(sample))); + } + if truthy(php::get(blocker, "sample_truncated")) { + lines.push(format!(" (showing {} of {count})", samples.len())); + } + } + lines +} + +/// One sample identity as `key=value` pairs, in the Server's order. +fn sample_label(sample: &Value) -> String { + match sample.as_object() { + Some(fields) => fields + .iter() + .filter(|(_, value)| nonempty_scalar(Some(*value))) + .map(|(key, value)| format!("{}={}", formatter::display_text(key), text(Some(value)))) + .collect::>() + .join(", "), + None => text(Some(sample)), + } +} diff --git a/rust/src/error.rs b/rust/src/error.rs index fd3016d..0c7cd2e 100644 --- a/rust/src/error.rs +++ b/rust/src/error.rs @@ -263,6 +263,26 @@ fn conflict_lines(body: &Map) -> Vec { lines } +/// The 409 body of a guarded `task-queue:retire` the Server refused +/// (Server #519): `command_status: "rejected"` with its inventory. +fn retirement_refusal<'a>( + error: &'a CliError, + context: &ErrorContext, +) -> Option<&'a Map> { + match error { + CliError::Http { + status: 409, + body: Some(body), + .. + } if context.command == "task-queue:retire" + && body.get("command_status").and_then(Value::as_str) == Some("rejected") => + { + Some(body) + } + _ => None, + } +} + fn base_recommendations(error: &CliError, context: &ErrorContext) -> Vec { let item = |id: &str, message: &str, command: String| json!({"id": id, "severity": "error", "message": message, "command": command}); let help = format!("dw {} --help", context.command); @@ -302,6 +322,17 @@ fn base_recommendations(error: &CliError, context: &ErrorContext) -> Vec })]; } } + // A refused retirement changed nothing; the Server names what to do. + if let Some(refusal) = retirement_refusal(error, context) { + let resolution = scalar_text(refusal.get("expected_resolution")).unwrap_or_else(|| { + "Nothing was retired. Resolve the blockers, inspect again with dw task-queue:retirement, then retry.".into() + }); + return vec![json!({ + "id": "retirement.refused", + "severity": "error", + "message": resolution, + })]; + } // A failed update read later is final, not a request to fix and retry. if context.command == "workflow:update-outcome" && error @@ -655,6 +686,13 @@ pub fn human(error: &CliError, context: &ErrorContext) -> String { .map(|line| human_output_text(line)), ); } + if let Some(refusal) = retirement_refusal(error, context) { + // Already display text: the refusal's inventory and blockers. + lines.extend(crate::commands::task_queue::retirement_lines( + &Value::Object(refusal.clone()), + false, + )); + } } if let Some(errors) = error.validation_errors() { lines.extend( diff --git a/rust/src/main.rs b/rust/src/main.rs index 33717de..f20bbf2 100644 --- a/rust/src/main.rs +++ b/rust/src/main.rs @@ -104,6 +104,8 @@ fn handler(name: &str) -> Option { "task-queue:activity-dispatch" => Handler::Server(task_queue::activity_dispatch), "task-queue:pause-activities" => Handler::Server(task_queue::pause_activities), "task-queue:resume-activities" => Handler::Server(task_queue::resume_activities), + "task-queue:retire" => Handler::Server(task_queue::retire), + "task-queue:retirement" => Handler::Server(task_queue::retirement), "worker:list" => Handler::Server(worker::list), "worker:describe" => Handler::Server(worker::describe), "worker:register" => Handler::Server(worker::register), @@ -186,6 +188,8 @@ const NAMESPACE_SCOPED: &[&str] = &[ "task-queue:promote", "task-queue:resume", "task-queue:resume-activities", + "task-queue:retire", + "task-queue:retirement", "worker:deregister", "worker:describe", "worker:list", diff --git a/rust/tests/queues_workers.rs b/rust/tests/queues_workers.rs index f1f867c..c647973 100644 --- a/rust/tests/queues_workers.rs +++ b/rust/tests/queues_workers.rs @@ -890,3 +890,338 @@ fn list_adds_the_activity_dispatch_column_only_when_the_server_reports_it() { let stdout = stdout_text(&scratch.run(&server.url, &["task-queue:list"])); assert!(!stdout.contains("Activity Dispatch"), "{stdout}"); } + +/// Cluster info of a Server that advertises guarded retirement (native +/// Server 3.14.0, Server #519). +fn retirement_info() -> Value { + let mut info = info(); + info["capabilities"] = json!({"worker_build_retirement": true}); + info +} + +fn blocked_inventory() -> Value { + json!({ + "namespace": "orders", + "task_queue": "orders", + "build_id": "build-1", + "scope": "build", + "retirable": false, + "observation": { + "status": "complete", + "observed_at": "2026-11-25T10:00:00.000000Z", + "sample_limit": 20, + "inventory_revision": "sha256:blocked", + "atomic_with_action": false + }, + "counts": {"open_runs": 3, "ready_tasks": 0, "delayed_tasks": 1, "unattributed_runs": 0}, + "blockers": [ + { + "kind": "open_runs", "count": 3, "waiting_runs": 1, "continued_runs": 0, "child_runs": 0, + "sample": [{"workflow_id": "order-1", "run_id": "run-1", "workflow_type": "Order", "status": "waiting"}], + "sample_truncated": true, + "recovery": "Keep a worker for this cohort running until these runs close." + }, + { + "kind": "delayed_tasks", "count": 1, "activity_retries": 1, "timers": 0, + "sample": [{"task_id": "task-1", "run_id": "run-1"}], + "sample_truncated": false, + "recovery": "Keep a compatible worker available until these delayed retries come due." + } + ], + "build_ids": ["build-1"], + "deployment": null, + "reason": "live_dependencies", + "message": "At least one live dependency still needs this build.", + "expected_resolution": "Let the blocking work finish, or cancel or terminate it, then inspect again." + }) +} + +fn clear_inventory(scope: &str) -> Value { + json!({ + "namespace": "orders", + "task_queue": "orders", + "build_id": null, + "scope": scope, + "retirable": true, + "observation": { + "status": "complete", + "observed_at": "2026-11-25T10:00:00.000000Z", + "sample_limit": 20, + "inventory_revision": "sha256:clear", + "atomic_with_action": false + }, + "counts": {"open_runs": 0, "schedules": 0}, + "blockers": [], + "build_ids": [null, "build-1"], + "reason": null, + "message": "No live dependency was observed. The guarded retire action repeats this check atomically before it records retirement.", + "expected_resolution": null + }) +} + +#[test] +fn retirement_reads_one_build_inventory_and_reports_its_blockers() { + let scratch = Scratch::new(); + let server = Server::new(retirement_info(), vec![ok(blocked_inventory())]); + let stdout = stdout_text(&scratch.run( + &server.url, + &["task-queue:retirement", "orders", "--build-id=build-1"], + )); + assert_eq!( + server.request_lines(), + ["GET /prefix/api/deployments/orders/orders%40build-1/retirement HTTP/1.1"] + ); + for expected in [ + "Retirement inventory for build_id build-1 on task queue orders", + " Namespace: orders", + " Retirable: no", + " Reason: live_dependencies", + " Inventory: complete", + " Inventory revision: sha256:blocked", + " Build IDs: build-1", + "open_runs", + "Blockers:", + " open_runs: 3 (waiting_runs 1, continued_runs 0, child_runs 0)", + " Recovery: Keep a worker for this cohort running until these runs close.", + " - workflow_id=order-1, run_id=run-1, workflow_type=Order, status=waiting", + " (showing 1 of 3)", + " delayed_tasks: 1 (activity_retries 1, timers 0)", + "Next: Let the blocking work finish, or cancel or terminate it, then inspect again.", + ] { + assert!(stdout.contains(expected), "{expected}: {stdout}"); + } + assert!(!stdout.contains("dw task-queue:retire "), "{stdout}"); + + let server = Server::new(retirement_info(), vec![ok(blocked_inventory())]); + let output = scratch.run( + &server.url, + &[ + "task-queue:retirement", + "orders", + "--build-id=build-1", + "--json", + ], + ); + assert_eq!(json_stdout(&output), blocked_inventory()); +} + +#[test] +fn retirement_of_a_queue_or_the_unversioned_cohort_uses_its_own_route() { + let scratch = Scratch::new(); + let server = Server::new(retirement_info(), vec![ok(clear_inventory("task_queue"))]); + let stdout = stdout_text(&scratch.run(&server.url, &["task-queue:retirement", "a/b"])); + assert_eq!( + server.request_lines(), + ["GET /prefix/api/task-queues/a%2Fb/retirement HTTP/1.1"] + ); + for expected in [ + "Retirement inventory for task queue orders", + " Retirable: yes", + " Build IDs: (unversioned), build-1", + "dw task-queue:retire a/b --expected-revision=sha256:clear", + ] { + assert!(stdout.contains(expected), "{expected}: {stdout}"); + } + assert!(!stdout.contains("Blockers:"), "{stdout}"); + + let server = Server::new(retirement_info(), vec![ok(clear_inventory("build"))]); + let stdout = stdout_text(&scratch.run( + &server.url, + &["task-queue:retirement", "a/b", "--unversioned"], + )); + assert_eq!( + server.request_lines(), + ["GET /prefix/api/deployments/orders/a%2Fb%40unversioned/retirement HTTP/1.1"] + ); + assert!( + stdout.contains("dw task-queue:retire a/b --unversioned --expected-revision=sha256:clear"), + "{stdout}" + ); +} + +#[test] +fn retire_sends_one_guarded_request_bound_to_the_inspected_revision() { + let scratch = Scratch::new(); + let mut retired = clear_inventory("build"); + retired["build_id"] = json!("build-1"); + retired["build_ids"] = json!(["build-1"]); + retired["outcome"] = json!("retired"); + retired["command_status"] = json!("accepted"); + retired["changed"] = json!(true); + retired["retired_at"] = json!("2026-11-25T10:05:00.000000Z"); + retired["retired_by"] = + json!({"type": "auth:token", "id": "role:operator", "label": "Operator"}); + retired["message"] = json!("Retired: no live dependency was observed in the transition that recorded retirement. Its workers are marked draining and claim nothing."); + retired["observation"]["atomic_with_action"] = json!(true); + let server = Server::new(retirement_info(), vec![ok(retired.clone())]); + let stdout = stdout_text(&scratch.run( + &server.url, + &[ + "task-queue:retire", + "orders", + "--build-id=build-1", + "--expected-revision=sha256:clear", + ], + )); + assert_eq!( + server.request_lines(), + ["POST /prefix/api/deployments/orders/orders%40build-1/retire HTTP/1.1"] + ); + assert_eq!( + server.body(0), + json!({"expected_inventory_revision": "sha256:clear"}) + ); + for expected in [ + "Retired build_id build-1 on task queue orders.", + " Namespace: orders", + " Retired at: 2026-11-25T10:05:00.000000Z", + " Retired by: Operator (auth:token role:operator)", + " Inventory revision: sha256:clear", + "Its workers are marked draining and claim nothing.", + ] { + assert!(stdout.contains(expected), "{expected}: {stdout}"); + } + assert!(!stdout.contains("Retirable:"), "{stdout}"); + + let server = Server::new(retirement_info(), vec![ok(retired.clone())]); + let output = scratch.run(&server.url, &["task-queue:retire", "orders", "--json"]); + assert_eq!(json_stdout(&output), retired); + assert_eq!( + server.request_lines(), + ["POST /prefix/api/task-queues/orders/retire HTTP/1.1"] + ); + assert_eq!(server.body(0), json!({})); +} + +#[test] +fn a_refused_retire_changes_nothing_and_reports_the_blockers() { + let scratch = Scratch::new(); + let mut refused = blocked_inventory(); + refused["rejection_reason"] = json!("live_dependencies"); + refused["outcome"] = json!("rejected_live_dependencies"); + refused["command_status"] = json!("rejected"); + refused["changed"] = json!(false); + let reply = Reply { + status: 409, + headers: Vec::new(), + body: Some(refused.clone()), + }; + let server = Server::new(retirement_info(), vec![reply.clone()]); + let output = scratch.run( + &server.url, + &["task-queue:retire", "orders", "--build-id=build-1"], + ); + assert_eq!(output.status.code(), Some(2), "{output:?}"); + assert_eq!(server.requests().len(), 1); + let stderr = String::from_utf8(output.stderr).unwrap(); + for expected in [ + "At least one live dependency still needs this build.", + "Reason: live_dependencies", + " open_runs: 3 (waiting_runs 1, continued_runs 0, child_runs 0)", + " Recovery: Keep a worker for this cohort running until these runs close.", + " - workflow_id=order-1, run_id=run-1, workflow_type=Order, status=waiting", + " - Let the blocking work finish, or cancel or terminate it, then inspect again.", + ] { + assert!(stderr.contains(expected), "{expected}: {stderr}"); + } + assert!(!stderr.contains("Retirable:"), "{stderr}"); + + let server = Server::new(retirement_info(), vec![reply]); + let output = scratch.run( + &server.url, + &[ + "task-queue:retire", + "orders", + "--build-id=build-1", + "--json", + ], + ); + assert_eq!(output.status.code(), Some(2), "{output:?}"); + assert_eq!(server.requests().len(), 1); + let envelope: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(envelope["exit_code"], json!(2), "{envelope}"); + assert_eq!(envelope["status_code"], json!(409), "{envelope}"); + assert_eq!(envelope["reason"], json!("live_dependencies"), "{envelope}"); + assert_eq!( + envelope["outcome"], + json!("rejected_live_dependencies"), + "{envelope}" + ); + assert_eq!(envelope["server_response"], refused, "{envelope}"); + assert_eq!( + envelope["recommendations"][0]["id"], + json!("retirement.refused"), + "{envelope}" + ); +} + +#[test] +fn a_server_without_retirement_is_refused_before_any_request() { + let scratch = Scratch::new(); + let mut not_advertised = info(); + not_advertised["capabilities"] = json!({"worker_build_retirement": false}); + for info in [info(), not_advertised] { + for args in [ + vec!["task-queue:retirement", "orders", "--build-id=build-1"], + vec!["task-queue:retire", "orders"], + ] { + let server = Server::new(info.clone(), vec![ok(json!({}))]); + let output = scratch.run(&server.url, &args); + assert_eq!(output.status.code(), Some(8), "{args:?}: {output:?}"); + assert!(server.requests().is_empty(), "{args:?}"); + let stderr = String::from_utf8(output.stderr).unwrap(); + assert!( + stderr.contains("does not advertise capabilities.worker_build_retirement"), + "{stderr}" + ); + } + } +} + +#[test] +fn retirement_targets_are_checked_before_any_request() { + let scratch = Scratch::new(); + for (args, message) in [ + ( + vec![ + "task-queue:retire", + "orders", + "--build-id=b", + "--unversioned", + ], + "--unversioned cannot be combined with --build-id", + ), + ( + vec!["task-queue:retirement", "orders", "--build-id=a@b"], + "containing \"@\"", + ), + ( + vec!["task-queue:retire", "orders", "--build-id=unversioned"], + "names the unversioned cohort", + ), + ] { + let server = Server::new(retirement_info(), vec![ok(json!({}))]); + let output = scratch.run(&server.url, &args); + assert_eq!(output.status.code(), Some(1), "{args:?}: {output:?}"); + assert!(server.requests().is_empty(), "{args:?}"); + let stderr = String::from_utf8(output.stderr).unwrap(); + assert!(stderr.contains(message), "{message}: {stderr}"); + } +} + +#[test] +fn a_lost_retire_response_is_never_resent() { + let scratch = Scratch::new(); + let server = Server::new(retirement_info(), vec![lost()]); + let output = scratch.run( + &server.url, + &[ + "task-queue:retire", + "orders", + "--build-id=build-1", + "--json", + ], + ); + assert_eq!(output.status.code(), Some(3), "{output:?}"); + assert_eq!(server.requests().len(), 1); +}