From 9f0ff8db34c305c310cf9bbe900e2526ae0ae0f5 Mon Sep 17 00:00:00 2001 From: Richard McDaniel <1130888+rmcdaniel@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:48:42 +0000 Subject: [PATCH] Add namespace:retention-plan and namespace:retention-apply (server#522) Native Server 3.30.0 previews a proposed namespace retention policy and applies it only while that plan still holds (durable-workflow/server#522, #1332, #1350). Expose it in the shipped Rust dw: - namespace:retention-plan [--retention=N] [--retention-mode=bounded|forever] [--scan-limit=N] [--hold-scan-limit=N]: one read-only POST of /namespaces/{name}/retention-plan. Human output shows the current and proposed policy with cutoffs, whether it is retroactive, complete, both revisions, a count for every change and exclusion ("at least N" when a count reached its bound), the incomplete fields, the hold inspection, example runs, the scope sentence and the exact apply command for the plan. --json returns the Server document unchanged. - namespace:retention-apply [--retention=N] [--retention-mode=...] --policy-revision=R --plan-revision=R [--confirm-retroactive-pruning] [--plan-file=plan.json]: one guarded POST of .../retention-plan/apply, never resent. --plan-file takes the resolved proposal and both revisions from a saved plan (namespace and schema checked) and cannot be combined with those four options. A stale (409), mismatched (409) or unconfirmed (422) apply changed nothing: dw prints the reason and the next step (re-plan, with the current policy_revision, for stale) and exits 2; --json keeps the error envelope with the full body. A 404 that is not namespace_not_found means the Server lacks the routes and points at native Server 3.30.0. Option names follow namespace:create/update (--retention for days). Invalid options are refused with exit 2 before any request. Server 3.30.0 advertises no capability for these routes, so there is no capability preflight. namespace:update is unchanged. Like the other native-only commands they are Rust-only catalog additions; the PHP 2.3.x maintenance line is unchanged. Docs: cli-reference, README, rust/README. Tests: 9 loopback-Server integration tests (tests/namespace_retention.rs). Co-Authored-By: Claude Opus 5.5 --- README.md | 19 + docs/cli-reference.md | 81 +++ rust/README.md | 1 + rust/parity/catalog-additions.json | 404 +++++++++++++++ rust/parity/parity.py | 2 +- rust/parity/test_parity.py | 1 + rust/parity/update-catalog.sh | 2 +- rust/src/catalog.json | 404 +++++++++++++++ rust/src/commands/mod.rs | 1 + rust/src/commands/retention_plan.rs | 449 +++++++++++++++++ rust/src/commands/task_queue.rs | 2 +- rust/src/error.rs | 58 +++ rust/src/main.rs | 9 +- rust/tests/namespace_retention.rs | 736 ++++++++++++++++++++++++++++ 14 files changed, 2163 insertions(+), 6 deletions(-) create mode 100644 rust/src/commands/retention_plan.rs create mode 100644 rust/tests/namespace_retention.rs diff --git a/README.md b/README.md index 009966c..f28464c 100644 --- a/README.md +++ b/README.md @@ -139,6 +139,25 @@ opaque `next_cursor` with the same query to continue. JSON and JSONL preserve th whole page, including counts. Drain or fence admissions and restart the query before making a branch-removal decision. +## Retention changes + +Before shortening a namespace's history retention, preview which closed runs +would become eligible for irreversible pruning, then apply the policy only +while that plan still holds (native Server 3.30.0+): + +```bash +dw namespace:retention-plan billing --retention=7 +dw namespace:retention-plan billing --retention=7 --json > plan.json +dw namespace:retention-apply billing --plan-file=plan.json --confirm-retroactive-pruning +``` + +The plan writes nothing. Counts that reach their scan limit are shown as +`at least N`. The apply refuses, changing nothing, if the namespace changed +since the plan, if the proposal differs from the planned one, or if a +retroactive policy is not confirmed. `namespace:update` still activates a +policy at once. See the +[retention plan reference](docs/cli-reference.md#retention-plan-and-guarded-apply). + ## Automation Contract All read and mutating commands support machine-readable output. Use diff --git a/docs/cli-reference.md b/docs/cli-reference.md index 7d29710..34bc4ae 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -711,6 +711,87 @@ dw namespace:update staging --retention=14 dw namespace:delete staging --json ``` +#### Retention plan and guarded apply + +`namespace:update --retention` activates the new policy at once, and the next +retention pass applies it to existing closed runs. To see what a change would +do first, preview it with `namespace:retention-plan`, then apply it with +`namespace:retention-apply` only while that plan still holds (native Server +3.30.0+, Server #522). Both need an admin token. + +```bash +# Preview shortening billing's retention to 7 days; nothing changes +dw namespace:retention-plan billing --retention=7 + +# Preview keeping terminal history until it is deleted or archived +dw namespace:retention-plan billing --retention-mode=forever + +# Apply the plan with its revisions; a retroactive policy needs the confirmation +dw namespace:retention-apply billing --retention=7 \ + --policy-revision=sha256:... --plan-revision=sha256:... --confirm-retroactive-pruning + +# Or save the plan and apply exactly what it planned +dw namespace:retention-plan billing --retention=7 --json > plan.json +dw namespace:retention-apply billing --plan-file=plan.json --confirm-retroactive-pruning +``` + +`namespace:retention-plan` takes the proposed `--retention` days, +`--retention-mode` (`bounded` or `forever`), or both. A field you leave out +keeps its current value. It shows the current and proposed policy with their +cutoffs and whether the proposal is retroactive, meaning it makes closed runs +eligible for pruning that the current policy keeps. It then counts closed, +unarchived runs in four groups: `newly_eligible`, `no_longer_eligible`, +`unchanged_eligible` and `unchanged_retained`. It also counts the runs a prune +would not delete: `archived`, `forever`, `not_terminal`, and eligible runs held +by `detached_activity_hold`, `external_payload_cleanup_unavailable` or +`backup_hold`. Each group lists up to five example runs, oldest first. + +`--scan-limit` (default 1000, at most 10000) bounds each count, and +`--hold-scan-limit` (default 100, at most 1000) bounds how many eligible runs +are checked for holds. A count that reaches its bound is shown as `at least N`. +The plan is then incomplete, and `Incomplete` names each such count. + +The output ends with the plan's scope and the exact `namespace:retention-apply` +command for it. That command repeats the resolved proposal and both revisions, +and adds `--confirm-retroactive-pruning` when the plan is retroactive. +`--json` returns the Server's `durable-workflow.v2.retention-plan.v1` document +unchanged. + +The plan writes nothing. It changes no policy, marks no row, fetches no payload +and prunes nothing. It describes one moment: runs can close, age past the +cutoff, be archived, or gain and lose holds, and the policy can change before +the next retention pass. It is not a list of what a later prune will delete. + +`namespace:retention-apply` sends the proposal with `--policy-revision` and +`--plan-revision` once and never resends it. Pass the same `--retention` and +`--retention-mode` you planned, or pass `--plan-file` with the plan's saved +`--json` output. That file supplies the proposal and both revisions, so it +cannot be combined with those four options. A retroactive proposal also needs +`--confirm-retroactive-pruning`, because pruning is irreversible. The Server +checks the revisions and updates the policy in one transaction. It refuses, and +changes nothing, in these cases. `dw` prints the reason and the next step, and +exits 2: + +| Status and reason | Cause | Next step | +| --- | --- | --- | +| `409 retention_policy_revision_stale` | The namespace changed after the plan. The refusal carries the current `policy_revision`. | Plan again, review it, and apply the new plan's revisions. | +| `409 retention_plan_revision_mismatch` | The proposal sent is not the one that was planned. | Apply the plan's exact proposal, or plan this one. | +| `422 retention_pruning_confirmation_required` | The proposal is retroactive and `--confirm-retroactive-pruning` was not passed. | Review `newly_eligible`, then repeat with the confirmation. | + +With `--json` a refusal keeps the usual error envelope, with `reason`, +`status_code` and the full body in `server_response`. + +An accepted apply shows the previous and new policy with their revisions, and +`--json` returns `durable-workflow.v2.retention-apply.v1`. The apply changes +only the namespace's policy and prunes nothing itself. Each later retention pass +prunes the closed, unarchived runs past the cutoff at that pass. That can +include runs that closed or aged after the plan, and it skips runs archived or +held at that time. + +A Server without these routes answers 404. `dw` exits 5 and says that native +Server 3.30.0 or later is needed. `namespace:update` is unchanged and still +activates a policy at once, with no plan or confirmation. + Configure external payload storage for a namespace: ```bash diff --git a/rust/README.md b/rust/README.md index 186492c..73dee55 100644 --- a/rust/README.md +++ b/rust/README.md @@ -46,6 +46,7 @@ command is ported. | `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:history-archive`, `workflow:history-archive-check`: a self-contained, verified archive of one closed run (Server #520). It holds the export, the exact bytes of every external payload it references, a manifest of their digests and a receipt. The copy runs under the external payload backup hold, resumes in the same directory and releases a crashed copy's hold; verification needs nothing but the directory and agrees with the Server's v1 conformance archive | Rust-only, new | +| `namespace:retention-plan`, `namespace:retention-apply`: preview a proposed retention policy (Server #522) with counts of the closed runs it makes eligible or ineligible for pruning, exclusions, examples and explicit `at least N` for incomplete counts, then apply it once, bound to the plan's `policy_revision` and `plan_revision` (or `--plan-file`), with `--confirm-retroactive-pruning` for a retroactive policy. A stale, mismatched or unconfirmed apply (409/422) changed nothing; dw prints the next step and exits 2. A Server without the routes (404) is reported as needing native Server 3.30.0 | 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 9506e43..ee516be 100644 --- a/rust/parity/catalog-additions.json +++ b/rust/parity/catalog-additions.json @@ -2560,6 +2560,410 @@ } }, "rust_only": true + }, + { + "name": "namespace:retention-apply", + "description": "Apply a planned retention policy only while the plan still holds", + "synopsis": "namespace:retention-apply [-s|--server [SERVER]] [--namespace [NAMESPACE]] [--token [TOKEN]] [--tls-verify TLS-VERIFY] [--env ENV] [--output OUTPUT] [--retention RETENTION] [--retention-mode RETENTION-MODE] [--policy-revision POLICY-REVISION] [--plan-revision PLAN-REVISION] [--confirm-retroactive-pruning] [--plan-file PLAN-FILE] [--json] [--] ", + "aliases": [], + "hidden": false, + "help": "Apply a retention policy previewed with dw namespace:retention-plan, only\nwhile that plan still holds. Pass the same proposal with the plan's\n--policy-revision and --plan-revision, or pass the plan's saved JSON with\n--plan-file.\n\nA retroactive proposal, one that makes closed runs eligible for pruning\nthat the current policy keeps (fewer days, or bounded replacing forever),\nalso needs --confirm-retroactive-pruning, because pruning is irreversible.\n\nThe request is sent once and never resent. The Server checks the revisions\nand updates the policy in one transaction. A refusal changes nothing, and\ndw prints what to do next and exits 2:\n\n retention_policy_revision_stale (409): the namespace changed after the\n plan. Plan again and apply the new plan's revisions.\n retention_plan_revision_mismatch (409): the proposal is not the one that\n was planned.\n retention_pruning_confirmation_required (422): the proposal is\n retroactive and --confirm-retroactive-pruning was not passed.\n\nThe apply changes only the namespace's policy. Each later retention pass\nprunes the closed, unarchived runs past the cutoff at that pass, which can\ninclude runs that closed or aged after the plan. dw namespace:update\nstill activates a policy at once, without a plan. Needs an admin token and\nnative Server 3.30.0 or later.\n\nExamples:\n\n dw namespace:retention-apply billing --retention=7 --policy-revision=sha256:... --plan-revision=sha256:... --confirm-retroactive-pruning\n dw namespace:retention-apply billing --plan-file=plan.json --confirm-retroactive-pruning", + "definition": { + "arguments": { + "name": { + "name": "name", + "is_required": true, + "is_array": false, + "description": "Namespace name", + "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" + }, + "retention": { + "name": "--retention", + "shortcut": "", + "accept_value": true, + "is_value_required": true, + "is_multiple": false, + "description": "Proposed retention period in days (1 to 365); omit it to keep the current days", + "default": null + }, + "retention-mode": { + "name": "--retention-mode", + "shortcut": "", + "accept_value": true, + "is_value_required": true, + "is_multiple": false, + "description": "Proposed retention mode: bounded or forever; omit it to keep the current mode", + "default": null + }, + "policy-revision": { + "name": "--policy-revision", + "shortcut": "", + "accept_value": true, + "is_value_required": true, + "is_multiple": false, + "description": "policy_revision from dw namespace:retention-plan; refuse if the namespace changed since", + "default": null + }, + "plan-revision": { + "name": "--plan-revision", + "shortcut": "", + "accept_value": true, + "is_value_required": true, + "is_multiple": false, + "description": "plan_revision from dw namespace:retention-plan; refuse if the proposal differs from the plan", + "default": null + }, + "confirm-retroactive-pruning": { + "name": "--confirm-retroactive-pruning", + "shortcut": "", + "accept_value": false, + "is_value_required": false, + "is_multiple": false, + "description": "Confirm that closed runs the current policy keeps may be pruned irreversibly", + "default": false + }, + "plan-file": { + "name": "--plan-file", + "shortcut": "", + "accept_value": true, + "is_value_required": true, + "is_multiple": false, + "description": "A plan saved with dw namespace:retention-plan --json; supplies the proposal and both revisions", + "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": "namespace:retention-plan", + "description": "Preview a proposed retention policy without applying it", + "synopsis": "namespace:retention-plan [-s|--server [SERVER]] [--namespace [NAMESPACE]] [--token [TOKEN]] [--tls-verify TLS-VERIFY] [--env ENV] [--output OUTPUT] [--retention RETENTION] [--retention-mode RETENTION-MODE] [--scan-limit SCAN-LIMIT] [--hold-scan-limit HOLD-SCAN-LIMIT] [--json] [--] ", + "aliases": [], + "hidden": false, + "help": "Preview what a proposed history-retention policy would do to a namespace,\nwithout applying it. Pass the proposed --retention days, --retention-mode, or\nboth; a field you leave out keeps its current value.\n\nThe plan counts closed, unarchived runs that become eligible for pruning\n(newly_eligible), stop being eligible (no_longer_eligible), stay eligible\nor stay retained, with up to five example runs each, oldest first. It also\ncounts runs a prune would not delete: archived runs past the proposed\ncutoff, runs a forever policy keeps, open runs, and eligible runs held by\nan open abandoned activity, an unsettled external payload reference or an\nactive backup hold. A count that reaches --scan-limit (default 1000, at\nmost 10000) or --hold-scan-limit (default 100, at most 1000) is shown as\n\"at least N\" and makes the plan incomplete.\n\nThe plan writes nothing: it changes no policy, marks no row and prunes\nnothing. It describes one moment. Runs can close, age, be archived or gain\nand lose holds, and the policy can change, before the next retention pass.\n\nApply the plan with dw namespace:retention-apply and its two revisions;\nthe human output prints the exact command. Needs an admin token and native\nServer 3.30.0 or later.\n\nExamples:\n\n dw namespace:retention-plan billing --retention=7\n dw namespace:retention-plan archive --retention-mode=forever\n dw namespace:retention-plan billing --retention=7 --json > plan.json", + "definition": { + "arguments": { + "name": { + "name": "name", + "is_required": true, + "is_array": false, + "description": "Namespace name", + "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" + }, + "retention": { + "name": "--retention", + "shortcut": "", + "accept_value": true, + "is_value_required": true, + "is_multiple": false, + "description": "Proposed retention period in days (1 to 365); omit it to keep the current days", + "default": null + }, + "retention-mode": { + "name": "--retention-mode", + "shortcut": "", + "accept_value": true, + "is_value_required": true, + "is_multiple": false, + "description": "Proposed retention mode: bounded or forever; omit it to keep the current mode", + "default": null + }, + "scan-limit": { + "name": "--scan-limit", + "shortcut": "", + "accept_value": true, + "is_value_required": true, + "is_multiple": false, + "description": "Most runs each count scans (default 1000, at most 10000)", + "default": null + }, + "hold-scan-limit": { + "name": "--hold-scan-limit", + "shortcut": "", + "accept_value": true, + "is_value_required": true, + "is_multiple": false, + "description": "Most eligible runs checked for holds (default 100, at most 1000)", + "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 } ] } diff --git a/rust/parity/parity.py b/rust/parity/parity.py index 73087ac..9dfe15d 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, Server #519, Server #520), in catalog order.""" + Server #1131, Server #519, Server #520, Server #522), 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 9d9e137..160522f 100644 --- a/rust/parity/test_parity.py +++ b/rust/parity/test_parity.py @@ -268,6 +268,7 @@ 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", + "namespace:retention-apply", "namespace:retention-plan", "task-queue:activity-dispatch", "task-queue:pause-activities", "task-queue:resume-activities", "task-queue:retire", "task-queue:retirement", "workflow:history-archive", "workflow:history-archive-check", diff --git a/rust/parity/update-catalog.sh b/rust/parity/update-catalog.sh index 0f955b7..d7e8e70 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, Server #519, Server #520) go into their namespace in name order. +# Rust-only commands (cli#60, Server #577, Server #1131, Server #519, Server #520, Server #522) 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 7ed99bc..46931b7 100644 --- a/rust/src/catalog.json +++ b/rust/src/catalog.json @@ -4383,6 +4383,410 @@ } } }, + { + "name": "namespace:retention-apply", + "description": "Apply a planned retention policy only while the plan still holds", + "synopsis": "namespace:retention-apply [-s|--server [SERVER]] [--namespace [NAMESPACE]] [--token [TOKEN]] [--tls-verify TLS-VERIFY] [--env ENV] [--output OUTPUT] [--retention RETENTION] [--retention-mode RETENTION-MODE] [--policy-revision POLICY-REVISION] [--plan-revision PLAN-REVISION] [--confirm-retroactive-pruning] [--plan-file PLAN-FILE] [--json] [--] ", + "aliases": [], + "hidden": false, + "help": "Apply a retention policy previewed with dw namespace:retention-plan, only\nwhile that plan still holds. Pass the same proposal with the plan's\n--policy-revision and --plan-revision, or pass the plan's saved JSON with\n--plan-file.\n\nA retroactive proposal, one that makes closed runs eligible for pruning\nthat the current policy keeps (fewer days, or bounded replacing forever),\nalso needs --confirm-retroactive-pruning, because pruning is irreversible.\n\nThe request is sent once and never resent. The Server checks the revisions\nand updates the policy in one transaction. A refusal changes nothing, and\ndw prints what to do next and exits 2:\n\n retention_policy_revision_stale (409): the namespace changed after the\n plan. Plan again and apply the new plan's revisions.\n retention_plan_revision_mismatch (409): the proposal is not the one that\n was planned.\n retention_pruning_confirmation_required (422): the proposal is\n retroactive and --confirm-retroactive-pruning was not passed.\n\nThe apply changes only the namespace's policy. Each later retention pass\nprunes the closed, unarchived runs past the cutoff at that pass, which can\ninclude runs that closed or aged after the plan. dw namespace:update\nstill activates a policy at once, without a plan. Needs an admin token and\nnative Server 3.30.0 or later.\n\nExamples:\n\n dw namespace:retention-apply billing --retention=7 --policy-revision=sha256:... --plan-revision=sha256:... --confirm-retroactive-pruning\n dw namespace:retention-apply billing --plan-file=plan.json --confirm-retroactive-pruning", + "definition": { + "arguments": { + "name": { + "name": "name", + "is_required": true, + "is_array": false, + "description": "Namespace name", + "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" + }, + "retention": { + "name": "--retention", + "shortcut": "", + "accept_value": true, + "is_value_required": true, + "is_multiple": false, + "description": "Proposed retention period in days (1 to 365); omit it to keep the current days", + "default": null + }, + "retention-mode": { + "name": "--retention-mode", + "shortcut": "", + "accept_value": true, + "is_value_required": true, + "is_multiple": false, + "description": "Proposed retention mode: bounded or forever; omit it to keep the current mode", + "default": null + }, + "policy-revision": { + "name": "--policy-revision", + "shortcut": "", + "accept_value": true, + "is_value_required": true, + "is_multiple": false, + "description": "policy_revision from dw namespace:retention-plan; refuse if the namespace changed since", + "default": null + }, + "plan-revision": { + "name": "--plan-revision", + "shortcut": "", + "accept_value": true, + "is_value_required": true, + "is_multiple": false, + "description": "plan_revision from dw namespace:retention-plan; refuse if the proposal differs from the plan", + "default": null + }, + "confirm-retroactive-pruning": { + "name": "--confirm-retroactive-pruning", + "shortcut": "", + "accept_value": false, + "is_value_required": false, + "is_multiple": false, + "description": "Confirm that closed runs the current policy keeps may be pruned irreversibly", + "default": false + }, + "plan-file": { + "name": "--plan-file", + "shortcut": "", + "accept_value": true, + "is_value_required": true, + "is_multiple": false, + "description": "A plan saved with dw namespace:retention-plan --json; supplies the proposal and both revisions", + "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": "namespace:retention-plan", + "description": "Preview a proposed retention policy without applying it", + "synopsis": "namespace:retention-plan [-s|--server [SERVER]] [--namespace [NAMESPACE]] [--token [TOKEN]] [--tls-verify TLS-VERIFY] [--env ENV] [--output OUTPUT] [--retention RETENTION] [--retention-mode RETENTION-MODE] [--scan-limit SCAN-LIMIT] [--hold-scan-limit HOLD-SCAN-LIMIT] [--json] [--] ", + "aliases": [], + "hidden": false, + "help": "Preview what a proposed history-retention policy would do to a namespace,\nwithout applying it. Pass the proposed --retention days, --retention-mode, or\nboth; a field you leave out keeps its current value.\n\nThe plan counts closed, unarchived runs that become eligible for pruning\n(newly_eligible), stop being eligible (no_longer_eligible), stay eligible\nor stay retained, with up to five example runs each, oldest first. It also\ncounts runs a prune would not delete: archived runs past the proposed\ncutoff, runs a forever policy keeps, open runs, and eligible runs held by\nan open abandoned activity, an unsettled external payload reference or an\nactive backup hold. A count that reaches --scan-limit (default 1000, at\nmost 10000) or --hold-scan-limit (default 100, at most 1000) is shown as\n\"at least N\" and makes the plan incomplete.\n\nThe plan writes nothing: it changes no policy, marks no row and prunes\nnothing. It describes one moment. Runs can close, age, be archived or gain\nand lose holds, and the policy can change, before the next retention pass.\n\nApply the plan with dw namespace:retention-apply and its two revisions;\nthe human output prints the exact command. Needs an admin token and native\nServer 3.30.0 or later.\n\nExamples:\n\n dw namespace:retention-plan billing --retention=7\n dw namespace:retention-plan archive --retention-mode=forever\n dw namespace:retention-plan billing --retention=7 --json > plan.json", + "definition": { + "arguments": { + "name": { + "name": "name", + "is_required": true, + "is_array": false, + "description": "Namespace name", + "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" + }, + "retention": { + "name": "--retention", + "shortcut": "", + "accept_value": true, + "is_value_required": true, + "is_multiple": false, + "description": "Proposed retention period in days (1 to 365); omit it to keep the current days", + "default": null + }, + "retention-mode": { + "name": "--retention-mode", + "shortcut": "", + "accept_value": true, + "is_value_required": true, + "is_multiple": false, + "description": "Proposed retention mode: bounded or forever; omit it to keep the current mode", + "default": null + }, + "scan-limit": { + "name": "--scan-limit", + "shortcut": "", + "accept_value": true, + "is_value_required": true, + "is_multiple": false, + "description": "Most runs each count scans (default 1000, at most 10000)", + "default": null + }, + "hold-scan-limit": { + "name": "--hold-scan-limit", + "shortcut": "", + "accept_value": true, + "is_value_required": true, + "is_multiple": false, + "description": "Most eligible runs checked for holds (default 100, at most 1000)", + "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": "namespace:set-storage-driver", "description": "Configure external payload storage for a namespace", diff --git a/rust/src/commands/mod.rs b/rust/src/commands/mod.rs index 136a8f9..197f24f 100644 --- a/rust/src/commands/mod.rs +++ b/rust/src/commands/mod.rs @@ -9,6 +9,7 @@ pub mod history_archive; pub mod info; pub mod namespace; mod operator_metrics; +pub mod retention_plan; pub mod runtime; pub mod schedule; pub mod schema; diff --git a/rust/src/commands/retention_plan.rs b/rust/src/commands/retention_plan.rs new file mode 100644 index 0000000..0277c4e --- /dev/null +++ b/rust/src/commands/retention_plan.rs @@ -0,0 +1,449 @@ +//! `namespace:retention-plan` and `namespace:retention-apply`: preview a +//! proposed history-retention policy, then apply it only while that plan +//! still holds (Server #522, native Server 3.30.0). +//! +//! The plan is one read-only POST. The apply is one guarded POST, never +//! resent; a refusal (409 or 422) changed nothing and is reported with what +//! to do next. `namespace:update` keeps activating a policy at once. + +use crate::cli::Input; +use crate::client::Context; +use crate::commands::schedule::{nonempty_scalar, text, text_or}; +use crate::commands::task_queue::sample_label; +use crate::error::CliError; +use crate::{formatter, output, php}; +use durable_workflow::RawRequest; +use serde_json::{json, Map, Value}; + +/// The schema of a plan answer, which `--plan-file` must carry. +pub const PLAN_SCHEMA: &str = "durable-workflow.v2.retention-plan.v1"; + +const MODES: [&str; 2] = ["bounded", "forever"]; + +/// `namespace:retention-plan`: one read-only plan of the proposed policy. +pub fn plan(context: &Context, input: &Input) -> Result { + let name = input.arg("name").unwrap_or_default(); + let mut body = proposal(input)?; + for option in ["scan-limit", "hold-scan-limit"] { + if let Some(limit) = positive_option(input, option)? { + body.insert(option.replace('-', "_"), json!(limit)); + } + } + context.preflight(false)?; + let result = context.resource_request( + RawRequest::post(["namespaces", name, "retention-plan"]).json(Value::Object(body)), + )?; + if context.mode.machine_readable() { + output::print_json(&result); + return Ok(0); + } + let namespace = shown_namespace(&result, name); + formatter::writeln_out(&format!( + "Retention plan for namespace {namespace}" + )); + let field = |key: &str| { + php::get(&result, key) + .filter(|value| nonempty_scalar(Some(value))) + .map(|value| text(Some(value))) + .unwrap_or_else(|| "-".into()) + }; + formatter::writeln_out(&format!(" Evaluated at: {}", field("evaluated_at"))); + formatter::writeln_out(&format!( + " Current policy: {}", + policy_label(php::get(&result, "current_policy")) + )); + formatter::writeln_out(&format!( + " Proposed policy: {}", + policy_label(php::get(&result, "proposed_policy")) + )); + formatter::writeln_out(&format!( + " Retroactive: {}", + yes_no(php::get(&result, "retroactive")) + )); + formatter::writeln_out(&format!( + " Complete: {}", + yes_no(php::get(&result, "complete")) + )); + formatter::writeln_out(&format!(" Policy revision: {}", field("policy_revision"))); + formatter::writeln_out(&format!(" Plan revision: {}", field("plan_revision"))); + + let changes = php::get(&result, "changes"); + let exclusions = php::get(&result, "exclusions"); + for (title, heading, section) in [ + ("Changes (closed, unarchived runs):", "Change", changes), + ( + "Exclusions (runs a prune would not delete):", + "Exclusion", + exclusions, + ), + ] { + let rows = entries(section) + .into_iter() + .map(|(key, entry)| vec![formatter::display_text(key), count_label(entry)]) + .collect::>(); + if !rows.is_empty() { + formatter::writeln_out(""); + formatter::writeln_out(title); + formatter::writeln_out(&output::render_table(&[heading, "Runs"], &rows)); + } + } + + let incomplete = php::get(&result, "incomplete") + .filter(|value| value.is_array()) + .map(php::values) + .unwrap_or_default(); + if !incomplete.is_empty() { + formatter::writeln_out(""); + formatter::writeln_out( + "Incomplete: these counts reached their scan limit and are minimums, not exact figures.", + ); + for item in incomplete { + let field = text_or(php::get(item, "field"), "-"); + match php::get(item, "reason").filter(|value| nonempty_scalar(Some(value))) { + Some(reason) => { + formatter::writeln_out(&format!(" {field}: {}", text(Some(reason)))) + } + None => formatter::writeln_out(&format!(" {field}")), + } + } + } + + let holds = php::get(&result, "hold_inspection").filter(|value| value.is_object()); + if let Some(holds) = holds { + formatter::writeln_out(""); + formatter::writeln_out(&format!( + "Hold inspection: {} eligible runs inspected, complete: {}, backup hold active: {}", + text_or(php::get(holds, "inspected"), "-"), + yes_no(php::get(holds, "complete")), + yes_no(php::get(holds, "backup_hold_active")), + )); + let skipped = php::get(holds, "not_evaluated") + .filter(|value| value.is_array()) + .map(|value| { + php::values(value) + .into_iter() + .map(|item| text(Some(item))) + .collect::>() + }) + .unwrap_or_default(); + if !skipped.is_empty() { + formatter::writeln_out(&format!(" Not evaluated: {}", skipped.join(", "))); + } + } + + let examples = [changes, exclusions] + .into_iter() + .flat_map(entries) + .filter_map(|(key, entry)| { + let runs = php::get(entry, "examples") + .filter(|value| value.is_array()) + .map(php::values) + .unwrap_or_default(); + (!runs.is_empty()).then_some((key, runs)) + }) + .collect::>(); + if !examples.is_empty() { + formatter::writeln_out(""); + formatter::writeln_out("Examples (oldest first):"); + for (key, runs) in examples { + formatter::writeln_out(&format!(" {}:", formatter::display_text(key))); + for run in runs { + formatter::writeln_out(&format!(" - {}", sample_label(run))); + } + } + } + + let mut closing = Vec::new(); + if let Some(scope) = php::get(&result, "scope").filter(|value| nonempty_scalar(Some(value))) { + closing.push(text(Some(scope))); + } + let retroactive = php::get(&result, "retroactive") == Some(&Value::Bool(true)); + if retroactive { + closing.push("This policy is retroactive: closed runs the current policy keeps become eligible for irreversible pruning at the next retention pass.".into()); + } + if let Some(command) = apply_command(&result, name, retroactive) { + closing.push(format!( + "Apply this plan with {command}; the Server refuses it if the namespace changed since this plan." + )); + } + if !closing.is_empty() { + formatter::writeln_out(""); + for line in closing { + formatter::writeln_out(&line); + } + } + Ok(0) +} + +/// `namespace:retention-apply`: one guarded apply, bound to a plan's +/// revisions and never resent. +pub fn apply(context: &Context, input: &Input) -> Result { + let name = input.arg("name").unwrap_or_default(); + let mut body = match input.opt_str("plan-file") { + Some(path) => { + if let Some(option) = [ + "retention", + "retention-mode", + "policy-revision", + "plan-revision", + ] + .into_iter() + .find(|option| input.opt_str(option).is_some()) + { + return Err(CliError::Invalid(format!( + "--plan-file cannot be combined with --{option}; the plan file supplies the proposal and both revisions." + ))); + } + plan_file_body(path, name)? + } + None => { + let mut body = proposal(input)?; + for option in ["policy-revision", "plan-revision"] { + let value = input + .opt_str(option) + .map(php::trim) + .filter(|value| !value.is_empty()) + .ok_or_else(|| { + CliError::Invalid(format!( + "--{option} is required. Take it from dw namespace:retention-plan, or pass --plan-file." + )) + })?; + body.insert(option.replace('-', "_"), json!(value)); + } + body + } + }; + body.insert( + "confirm_retroactive_pruning".into(), + json!(input.flag("confirm-retroactive-pruning")), + ); + context.preflight(false)?; + let result = context.resource_request( + RawRequest::post(["namespaces", name, "retention-plan", "apply"]).json(Value::Object(body)), + )?; + if context.mode.machine_readable() { + output::print_json(&result); + return Ok(0); + } + let namespace = shown_namespace(&result, name); + formatter::writeln_out(&format!( + "Retention policy applied to namespace {namespace}." + )); + let field = |key: &str| { + php::get(&result, key) + .filter(|value| nonempty_scalar(Some(value))) + .map(|value| text(Some(value))) + .unwrap_or_else(|| "-".into()) + }; + formatter::writeln_out(&format!(" Applied at: {}", field("applied_at"))); + formatter::writeln_out(&format!( + " Previous policy: {}", + policy_label(php::get(&result, "previous_policy")) + )); + formatter::writeln_out(&format!( + " Policy: {}", + policy_label(php::get(&result, "policy")) + )); + let retroactive = match ( + php::get(&result, "retroactive"), + php::get(&result, "confirmed_retroactive_pruning"), + ) { + (Some(Value::Bool(true)), Some(Value::Bool(true))) => "yes, pruning confirmed", + (Some(Value::Bool(true)), _) => "yes", + (Some(Value::Bool(false)), _) => "no", + _ => "-", + }; + formatter::writeln_out(&format!(" Retroactive: {retroactive}")); + formatter::writeln_out(&format!( + " Previous policy revision: {}", + field("previous_policy_revision") + )); + formatter::writeln_out(&format!(" Policy revision: {}", field("policy_revision"))); + if let Some(scope) = php::get(&result, "scope").filter(|value| nonempty_scalar(Some(value))) { + formatter::writeln_out(""); + formatter::writeln_out(&text(Some(scope))); + } + Ok(0) +} + +/// The proposed `retention_mode` and `retention_days` from the options; a +/// field left out keeps the namespace's current value on the Server. +fn proposal(input: &Input) -> Result, CliError> { + let mut body = Map::new(); + let mode = input.opt_str("retention-mode").map(php::trim); + if let Some(mode) = mode { + if !MODES.contains(&mode) { + return Err(CliError::Invalid( + "--retention-mode must be bounded or forever.".into(), + )); + } + body.insert("retention_mode".into(), json!(mode)); + } + if let Some(days) = positive_option(input, "retention")? { + if mode == Some("forever") { + return Err(CliError::Invalid( + "--retention cannot be combined with --retention-mode=forever; a forever policy has no days.".into(), + )); + } + body.insert("retention_days".into(), json!(days)); + } + Ok(body) +} + +/// A written option as a positive integer; the Server enforces its range. +fn positive_option(input: &Input, option: &str) -> Result, CliError> { + let Some(value) = input.opt(option).flatten().map(php::trim) else { + return Ok(None); + }; + match value.parse::() { + Ok(number) if number > 0 && php::ctype_digit(value) => Ok(Some(number)), + _ => Err(CliError::Invalid(format!( + "--{option} must be a positive integer." + ))), + } +} + +/// The apply body a saved plan (`namespace:retention-plan --json`) names: +/// its proposed policy, exactly as resolved, and both revisions. +fn plan_file_body(path: &str, name: &str) -> Result, CliError> { + let invalid = |detail: &str| { + CliError::Invalid(format!( + "--plan-file {path} is not a retention plan: {detail}. Save one with dw namespace:retention-plan ... --json." + )) + }; + let contents = std::fs::read_to_string(path).map_err(|error| { + CliError::Invalid(format!("Unable to read --plan-file {path}: {error}")) + })?; + let plan: Value = + serde_json::from_str(&contents).map_err(|_| invalid("it is not valid JSON"))?; + if plan.get("schema").and_then(Value::as_str) != Some(PLAN_SCHEMA) { + return Err(invalid(&format!("its schema is not {PLAN_SCHEMA}"))); + } + let planned = plan + .get("namespace") + .and_then(Value::as_str) + .unwrap_or_default(); + if !planned.eq_ignore_ascii_case(php::trim(name)) { + return Err(CliError::Invalid(format!( + "--plan-file {path} plans namespace {}, not {}.", + formatter::display_text(planned), + formatter::display_text(name) + ))); + } + let proposed = plan.get("proposed_policy"); + let mode = proposed + .and_then(|policy| policy.get("retention_mode")) + .and_then(Value::as_str) + .filter(|mode| MODES.contains(mode)) + .ok_or_else(|| invalid("proposed_policy.retention_mode is missing"))?; + let mut body = Map::new(); + body.insert("retention_mode".into(), json!(mode)); + if mode == "bounded" { + let days = proposed + .and_then(|policy| policy.get("retention_days")) + .and_then(Value::as_i64) + .ok_or_else(|| invalid("proposed_policy.retention_days is missing"))?; + body.insert("retention_days".into(), json!(days)); + } + for key in ["policy_revision", "plan_revision"] { + let revision = plan + .get(key) + .and_then(Value::as_str) + .filter(|value| !value.is_empty()) + .ok_or_else(|| invalid(&format!("{key} is missing")))?; + body.insert(key.into(), json!(revision)); + } + Ok(body) +} + +/// The `dw namespace:retention-apply` command that applies this plan: the +/// resolved proposal, so it matches the plan revision, and both revisions. +fn apply_command(result: &Value, name: &str, retroactive: bool) -> Option { + let revision = |key: &str| { + php::get(result, key) + .filter(|value| nonempty_scalar(Some(value))) + .map(|value| text(Some(value))) + }; + let (policy_revision, plan_revision) = + (revision("policy_revision")?, revision("plan_revision")?); + let proposed = php::get(result, "proposed_policy")?; + let mode = php::get(proposed, "retention_mode") + .and_then(Value::as_str) + .filter(|mode| MODES.contains(mode))?; + let mut command = format!( + "dw namespace:retention-apply {} --retention-mode={mode}", + formatter::display_text(name) + ); + if mode == "bounded" { + let days = php::get(proposed, "retention_days").and_then(Value::as_i64)?; + command.push_str(&format!(" --retention={days}")); + } + command.push_str(&format!( + " --policy-revision={policy_revision} --plan-revision={plan_revision}" + )); + if retroactive { + command.push_str(" --confirm-retroactive-pruning"); + } + Some(command) +} + +fn shown_namespace(result: &Value, name: &str) -> String { + match php::get(result, "namespace").filter(|value| nonempty_scalar(Some(value))) { + Some(value) => text(Some(value)), + None => formatter::display_text(name), + } +} + +/// `bounded, 7 days (cutoff ...)` or `forever (no cutoff)`. +fn policy_label(policy: Option<&Value>) -> String { + let Some(policy) = policy.filter(|value| value.is_object()) else { + return "-".into(); + }; + let mode = text_or(php::get(policy, "retention_mode"), "-"); + if mode == "forever" { + return "forever (no cutoff)".into(); + } + let mut label = mode; + if let Some(days) = + php::get(policy, "retention_days").filter(|value| nonempty_scalar(Some(value))) + { + label.push_str(&format!(", {} days", text(Some(days)))); + } + if let Some(cutoff) = php::get(policy, "cutoff").filter(|value| nonempty_scalar(Some(value))) { + label.push_str(&format!(" (cutoff {})", text(Some(cutoff)))); + } + label +} + +/// A plan section's categories, in the Server's order. +fn entries(section: Option<&Value>) -> Vec<(&String, &Value)> { + section + .and_then(Value::as_object) + .map(|fields| { + fields + .iter() + .filter(|(_, entry)| entry.is_object()) + .collect() + }) + .unwrap_or_default() +} + +/// An exact count, or `at least N` for a count that reached its bound. +fn count_label(entry: &Value) -> String { + let complete = php::get(entry, "complete") == Some(&Value::Bool(true)); + match php::get(entry, "count").filter(|value| value.is_number()) { + Some(count) if complete => text(Some(count)), + _ => match php::get(entry, "lower_bound").filter(|value| value.is_number()) { + Some(bound) => format!("at least {}", text(Some(bound))), + None => "-".into(), + }, + } +} + +fn yes_no(value: Option<&Value>) -> &'static str { + match value { + Some(Value::Bool(true)) => "yes", + Some(Value::Bool(false)) => "no", + _ => "-", + } +} diff --git a/rust/src/commands/task_queue.rs b/rust/src/commands/task_queue.rs index 4dea964..1a6a6c8 100644 --- a/rust/src/commands/task_queue.rs +++ b/rust/src/commands/task_queue.rs @@ -1169,7 +1169,7 @@ pub(crate) fn retirement_lines(result: &Value, verdict: bool) -> Vec { } /// One sample identity as `key=value` pairs, in the Server's order. -fn sample_label(sample: &Value) -> String { +pub(crate) fn sample_label(sample: &Value) -> String { match sample.as_object() { Some(fields) => fields .iter() diff --git a/rust/src/error.rs b/rust/src/error.rs index 0c7cd2e..afd17ff 100644 --- a/rust/src/error.rs +++ b/rust/src/error.rs @@ -283,6 +283,59 @@ fn retirement_refusal<'a>( } } +/// The two retention plan commands (Server #522, native Server 3.30.0). +const RETENTION_PLAN_COMMANDS: &[&str] = &["namespace:retention-plan", "namespace:retention-apply"]; + +/// The next step for a guarded retention apply the Server refused, which +/// changed nothing, or for a Server without the retention plan routes. +fn retention_plan_recommendation(error: &CliError, context: &ErrorContext) -> Option { + let CliError::Http { status, body, .. } = error else { + return None; + }; + if !RETENTION_PLAN_COMMANDS.contains(&context.command) { + return None; + } + let namespace = body + .as_ref() + .and_then(|body| scalar_text(body.get("namespace"))) + .unwrap_or_else(|| "".into()); + let plan = format!("dw namespace:retention-plan {namespace}"); + let reason = error.reason(); + match (*status, reason) { + (409, Some("retention_policy_revision_stale")) => { + let current = body + .as_ref() + .and_then(|body| scalar_text(body.get("policy_revision"))) + .map(|revision| format!(" Its current policy revision is {revision}.")) + .unwrap_or_default(); + Some(json!({ + "id": "retention_plan.stale", + "severity": "error", + "message": format!("Nothing was applied: the namespace changed after the plan.{current} Plan the policy again, review the new plan, then apply it with its revisions."), + "command": plan, + })) + } + (409, Some("retention_plan_revision_mismatch")) => Some(json!({ + "id": "retention_plan.mismatch", + "severity": "error", + "message": "Nothing was applied: the policy sent is not the policy that was planned. Apply with the plan's exact --retention and --retention-mode (or --plan-file), or plan this policy first.", + "command": plan, + })), + (422, Some("retention_pruning_confirmation_required")) => Some(json!({ + "id": "retention_plan.confirmation_required", + "severity": "error", + "message": "Nothing was applied: this policy makes closed runs eligible for pruning that the current policy keeps, and pruning is irreversible. Review the plan's newly_eligible runs, then repeat the command with --confirm-retroactive-pruning.", + })), + (404, reason) if reason != Some("namespace_not_found") => Some(json!({ + "id": "retention_plan.unsupported", + "severity": "error", + "message": "This Server has no retention plan route. Previewing a retention policy and the guarded apply need native Durable Workflow Server 3.30.0 or later; on an older Server, dw namespace:update activates a policy at once, without a plan.", + "command": "dw server:info", + })), + _ => 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); @@ -333,6 +386,9 @@ fn base_recommendations(error: &CliError, context: &ErrorContext) -> Vec "message": resolution, })]; } + if let Some(next) = retention_plan_recommendation(error, context) { + return vec![next]; + } // A failed update read later is final, not a request to fix and retry. if context.command == "workflow:update-outcome" && error @@ -639,6 +695,8 @@ pub fn human(error: &CliError, context: &ErrorContext) -> String { | "namespace:create" | "namespace:update" | "namespace:delete" + | "namespace:retention-plan" + | "namespace:retention-apply" ) || [ "batch:", "schedule:", diff --git a/rust/src/main.rs b/rust/src/main.rs index 39be655..4a3239e 100644 --- a/rust/src/main.rs +++ b/rust/src/main.rs @@ -37,9 +37,10 @@ enum Handler { /// reported as not yet available. fn handler(name: &str) -> Option { use commands::{ - activity_task, batch, completion, debug, doctor, env, history_archive, namespace, runtime, - schedule, schema, search_attribute, server, start_dev, system, task_queue, upgrade, - version_usage, worker, workflow, workflow_control, workflow_message, workflow_run, + activity_task, batch, completion, debug, doctor, env, history_archive, namespace, + retention_plan, runtime, schedule, schema, search_attribute, server, start_dev, system, + task_queue, upgrade, version_usage, worker, workflow, workflow_control, workflow_message, + workflow_run, }; Some(match name { "completion" => Handler::Local(completion::completion), @@ -65,6 +66,8 @@ fn handler(name: &str) -> Option { "namespace:create" => Handler::Server(namespace::create), "namespace:update" => Handler::Server(namespace::update), "namespace:delete" => Handler::Server(namespace::delete), + "namespace:retention-plan" => Handler::Server(retention_plan::plan), + "namespace:retention-apply" => Handler::Server(retention_plan::apply), "workflow:list-runs" => Handler::Server(workflow::list_runs), "workflow:describe" => Handler::Server(workflow_run::describe), "workflow:show-run" => Handler::Server(workflow_run::show_run), diff --git a/rust/tests/namespace_retention.rs b/rust/tests/namespace_retention.rs new file mode 100644 index 0000000..b21f9c0 --- /dev/null +++ b/rust/tests/namespace_retention.rs @@ -0,0 +1,736 @@ +//! namespace:retention-plan and namespace:retention-apply (Server #522) +//! against a loopback Server that answers each request from a queue, so +//! request counts, paths and bodies are observable. + +use serde_json::{json, Value}; +use std::collections::VecDeque; +use std::fs; +use std::io::{Read, Write}; +use std::net::TcpListener; +use std::path::PathBuf; +use std::process::{Command, Output}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex}; +use std::thread; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +struct Scratch(PathBuf); + +impl Scratch { + fn new() -> Self { + static NEXT: AtomicU64 = AtomicU64::new(0); + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos(); + let path = std::env::temp_dir().join(format!( + "dw-namespace-retention-{}-{now}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir(&path).unwrap(); + Self(path) + } + + fn run(&self, url: &str, args: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_dw")) + .args(args) + .args([ + "--server", + url, + "--namespace=orders", + "--token=fixture-token", + ]) + .env_clear() + .env("DW_CONFIG_HOME", &self.0) + .env("HOME", &self.0) + .output() + .unwrap() + } +} + +impl Drop for Scratch { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +/// A queued answer. `body: None` closes the connection without a response, +/// as a Server that crashed after receiving the request would. +#[derive(Clone)] +struct Reply { + status: u16, + headers: Vec<(&'static str, &'static str)>, + body: Option, +} + +fn ok(body: Value) -> Reply { + Reply { + status: 200, + headers: Vec::new(), + body: Some(body), + } +} + +fn lost() -> Reply { + Reply { + status: 200, + headers: Vec::new(), + body: None, + } +} + +/// Cluster info is the given document. Every other request takes the next +/// queued reply; the last one repeats. +struct Server { + url: String, + requests: Arc>>, +} + +impl Server { + fn new(info: Value, replies: Vec) -> Self { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let url = format!("http://{}/prefix", listener.local_addr().unwrap()); + let requests = Arc::new(Mutex::new(Vec::new())); + let observed = Arc::clone(&requests); + let queue = Arc::new(Mutex::new(VecDeque::from(replies))); + thread::spawn(move || { + for stream in listener.incoming() { + let Ok(mut stream) = stream else { continue }; + stream + .set_read_timeout(Some(Duration::from_secs(2))) + .unwrap(); + let request = read_request(&mut stream); + let reply = if request.starts_with("GET /prefix/api/cluster/info ") { + ok(info.clone()) + } else { + observed.lock().unwrap().push(request); + let mut queue = queue.lock().unwrap(); + if queue.len() > 1 { + queue.pop_front().unwrap() + } else { + queue.front().cloned().unwrap_or_else(|| ok(json!({}))) + } + }; + let Some(body) = reply.body else { + // Drop the connection: the request was received, the + // response is lost. + continue; + }; + let payload = serde_json::to_vec(&body).unwrap(); + let mut head = format!("HTTP/1.1 {} Test\r\n", reply.status); + for (name, value) in &reply.headers { + head.push_str(&format!("{name}: {value}\r\n")); + } + head.push_str(&format!( + "Content-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + payload.len() + )); + let _ = stream.write_all(head.as_bytes()); + let _ = stream.write_all(&payload); + } + }); + Self { url, requests } + } + + fn requests(&self) -> Vec { + self.requests.lock().unwrap().clone() + } + + fn request_lines(&self) -> Vec { + self.requests() + .iter() + .map(|request| request.lines().next().unwrap_or_default().to_owned()) + .collect() + } + + fn body(&self, index: usize) -> Value { + let request = &self.requests()[index]; + let body = request.split("\r\n\r\n").nth(1).unwrap_or_default(); + serde_json::from_str(body).unwrap() + } +} + +/// The request head, plus its body when Content-Length announces one. +fn read_request(stream: &mut std::net::TcpStream) -> String { + let mut bytes = Vec::new(); + let mut buffer = [0; 4096]; + loop { + if let Some(end) = bytes.windows(4).position(|part| part == b"\r\n\r\n") { + let head = String::from_utf8_lossy(&bytes[..end]).to_lowercase(); + let length = head + .lines() + .find_map(|line| line.strip_prefix("content-length:")) + .and_then(|value| value.trim().parse::().ok()) + .unwrap_or(0); + if bytes.len() >= end + 4 + length { + break; + } + } + match stream.read(&mut buffer) { + Ok(0) | Err(_) => break, + Ok(size) => bytes.extend_from_slice(&buffer[..size]), + } + } + String::from_utf8_lossy(&bytes).into_owned() +} + +fn info() -> Value { + serde_json::from_str(include_str!( + "../src/compat/fixtures/cluster-info-php-2.11.8.json" + )) + .unwrap() +} + +fn json_stdout(output: &Output) -> Value { + assert_eq!(output.status.code(), Some(0), "{output:?}"); + serde_json::from_slice(&output.stdout).unwrap() +} + +fn stdout_text(output: &Output) -> String { + assert_eq!(output.status.code(), Some(0), "{output:?}"); + String::from_utf8(output.stdout.clone()).unwrap() +} + +fn refusal(status: u16, body: Value) -> Reply { + Reply { + status, + headers: Vec::new(), + body: Some(body), + } +} + +fn examples(run: &str) -> Value { + json!([{ + "run_id": run, + "workflow_id": format!("order-{run}"), + "workflow_type": "orders.process", + "status": "completed", + "closed_at": "2026-11-01T10:00:00.000000Z" + }]) +} + +/// A native Server 3.30.0 plan that shortens 30 days to 7, with one count +/// at its scan bound and an incomplete hold inspection. +fn shortening_plan() -> Value { + json!({ + "schema": "durable-workflow.v2.retention-plan.v1", + "namespace": "billing", + "evaluated_at": "2026-11-26T10:00:00.000000Z", + "read_only": true, + "scope": "A point-in-time scan of one read snapshot, not an immutable deletion set.", + "policy_revision": "sha256:policy", + "plan_revision": "sha256:plan", + "retroactive": true, + "current_policy": { + "retention_mode": "bounded", + "retention_days": 30, + "cutoff": "2026-10-27T10:00:00+00:00", + "updated_at": "2026-11-01T09:00:00.000000Z" + }, + "proposed_policy": { + "retention_mode": "bounded", + "retention_days": 7, + "cutoff": "2026-11-19T10:00:00+00:00" + }, + "scan_limit": 1000, + "hold_scan_limit": 100, + "example_limit": 5, + "complete": false, + "incomplete": [ + {"field": "changes.newly_eligible", "reason": "scan_limit_reached"}, + {"field": "exclusions.backup_hold", "reason": "hold_scan_limit_reached"} + ], + "changes": { + "newly_eligible": {"count": null, "lower_bound": 1000, "complete": false, "examples": examples("run-1")}, + "no_longer_eligible": {"count": 0, "lower_bound": 0, "complete": true, "examples": []}, + "unchanged_eligible": {"count": 4, "lower_bound": 4, "complete": true, "examples": examples("run-0")}, + "unchanged_retained": {"count": 12, "lower_bound": 12, "complete": true, "examples": []} + }, + "exclusions": { + "archived": {"count": 3, "lower_bound": 3, "complete": true}, + "forever": {"count": 0, "lower_bound": 0, "complete": true}, + "not_terminal": {"count": 8, "lower_bound": 8, "complete": true}, + "detached_activity_hold": {"count": null, "lower_bound": 0, "complete": false, "examples": []}, + "external_payload_cleanup_unavailable": {"count": null, "lower_bound": 0, "complete": false, "examples": []}, + "backup_hold": {"count": null, "lower_bound": 2, "complete": false, "examples": examples("run-2")} + }, + "hold_inspection": { + "scope": "eligible_under_proposed_policy", + "inspected": 100, + "complete": false, + "backup_hold_active": true, + "not_evaluated": ["external_payload_storage_binding_unavailable"] + } + }) +} + +fn forever_plan() -> Value { + let mut plan = shortening_plan(); + plan["retroactive"] = json!(false); + plan["complete"] = json!(true); + plan["incomplete"] = json!([]); + plan["proposed_policy"] = + json!({"retention_mode": "forever", "retention_days": null, "cutoff": null}); + plan +} + +fn applied() -> Value { + json!({ + "schema": "durable-workflow.v2.retention-apply.v1", + "namespace": "billing", + "applied_at": "2026-11-26T10:05:00.000000Z", + "retroactive": true, + "confirmed_retroactive_pruning": true, + "previous_policy_revision": "sha256:policy", + "previous_policy": { + "retention_mode": "bounded", + "retention_days": 30, + "cutoff": "2026-10-27T10:05:00+00:00", + "updated_at": "2026-11-01T09:00:00.000000Z" + }, + "policy_revision": "sha256:applied", + "policy": { + "retention_mode": "bounded", + "retention_days": 7, + "cutoff": "2026-11-19T10:05:00+00:00", + "updated_at": "2026-11-26T10:05:00.000000Z" + }, + "scope": "The policy is active from applied_at. The plan's counts were a point-in-time scan, not the set that will be deleted." + }) +} + +const APPLY_ARGS: [&str; 5] = [ + "namespace:retention-apply", + "billing", + "--retention=7", + "--policy-revision=sha256:policy", + "--plan-revision=sha256:plan", +]; + +#[test] +fn a_plan_is_one_read_only_request_and_shows_every_count() { + let scratch = Scratch::new(); + let server = Server::new(info(), vec![ok(shortening_plan())]); + let stdout = stdout_text(&scratch.run( + &server.url, + &[ + "namespace:retention-plan", + "billing", + "--retention=7", + "--scan-limit=1000", + "--hold-scan-limit=100", + ], + )); + assert_eq!( + server.request_lines(), + ["POST /prefix/api/namespaces/billing/retention-plan HTTP/1.1"] + ); + assert_eq!( + server.body(0), + json!({"retention_days": 7, "scan_limit": 1000, "hold_scan_limit": 100}) + ); + assert!(server.requests()[0].contains("Bearer fixture-token")); + for expected in [ + "Retention plan for namespace billing", + " Evaluated at: 2026-11-26T10:00:00.000000Z", + " Current policy: bounded, 30 days (cutoff 2026-10-27T10:00:00+00:00)", + " Proposed policy: bounded, 7 days (cutoff 2026-11-19T10:00:00+00:00)", + " Retroactive: yes", + " Complete: no", + " Policy revision: sha256:policy", + " Plan revision: sha256:plan", + "Changes (closed, unarchived runs):", + "| newly_eligible | at least 1000 |", + "| no_longer_eligible | 0 |", + "| unchanged_retained | 12 |", + "Exclusions (runs a prune would not delete):", + "| archived | 3 |", + "| detached_activity_hold | at least 0 |", + "| backup_hold | at least 2 |", + "Incomplete: these counts reached their scan limit and are minimums, not exact figures.", + " changes.newly_eligible: scan_limit_reached", + " exclusions.backup_hold: hold_scan_limit_reached", + "Hold inspection: 100 eligible runs inspected, complete: no, backup hold active: yes", + " Not evaluated: external_payload_storage_binding_unavailable", + "Examples (oldest first):", + " newly_eligible:\n - run_id=run-1, workflow_id=order-run-1, workflow_type=orders.process, status=completed, closed_at=2026-11-01T10:00:00.000000Z", + " backup_hold:\n - run_id=run-2,", + "A point-in-time scan of one read snapshot, not an immutable deletion set.", + "This policy is retroactive: closed runs the current policy keeps become eligible for irreversible pruning", + "Apply this plan with dw namespace:retention-apply billing --retention-mode=bounded --retention=7 --policy-revision=sha256:policy --plan-revision=sha256:plan --confirm-retroactive-pruning;", + ] { + assert!(stdout.contains(expected), "{expected}: {stdout}"); + } + + let server = Server::new(info(), vec![ok(shortening_plan())]); + let output = scratch.run( + &server.url, + &[ + "namespace:retention-plan", + "billing", + "--retention=7", + "--json", + ], + ); + assert_eq!(json_stdout(&output), shortening_plan()); + assert_eq!(server.requests().len(), 1); +} + +#[test] +fn a_forever_plan_sends_only_the_mode_and_its_apply_needs_no_confirmation() { + let scratch = Scratch::new(); + let server = Server::new(info(), vec![ok(forever_plan())]); + let stdout = stdout_text(&scratch.run( + &server.url, + &[ + "namespace:retention-plan", + "billing", + "--retention-mode=forever", + ], + )); + assert_eq!(server.body(0), json!({"retention_mode": "forever"})); + for expected in [ + " Proposed policy: forever (no cutoff)", + " Retroactive: no", + " Complete: yes", + "Apply this plan with dw namespace:retention-apply billing --retention-mode=forever --policy-revision=sha256:policy --plan-revision=sha256:plan;", + ] { + assert!(stdout.contains(expected), "{expected}: {stdout}"); + } + assert!(!stdout.contains("Incomplete:"), "{stdout}"); + assert!( + !stdout.contains("--confirm-retroactive-pruning"), + "{stdout}" + ); + assert!(!stdout.contains("is retroactive"), "{stdout}"); + + // A plan with no proposal compares the current policy with itself. + let server = Server::new(info(), vec![ok(forever_plan())]); + stdout_text(&scratch.run(&server.url, &["namespace:retention-plan", "billing"])); + assert_eq!(server.body(0), json!({})); +} + +#[test] +fn apply_sends_one_guarded_request_bound_to_both_revisions() { + let scratch = Scratch::new(); + let server = Server::new(info(), vec![ok(applied())]); + let mut args = APPLY_ARGS.to_vec(); + args.push("--confirm-retroactive-pruning"); + let stdout = stdout_text(&scratch.run(&server.url, &args)); + assert_eq!( + server.request_lines(), + ["POST /prefix/api/namespaces/billing/retention-plan/apply HTTP/1.1"] + ); + assert_eq!( + server.body(0), + json!({ + "retention_days": 7, + "policy_revision": "sha256:policy", + "plan_revision": "sha256:plan", + "confirm_retroactive_pruning": true + }) + ); + for expected in [ + "Retention policy applied to namespace billing.", + " Applied at: 2026-11-26T10:05:00.000000Z", + " Previous policy: bounded, 30 days (cutoff 2026-10-27T10:05:00+00:00)", + " Policy: bounded, 7 days (cutoff 2026-11-19T10:05:00+00:00)", + " Retroactive: yes, pruning confirmed", + " Previous policy revision: sha256:policy", + " Policy revision: sha256:applied", + "The policy is active from applied_at.", + ] { + assert!(stdout.contains(expected), "{expected}: {stdout}"); + } + + let server = Server::new(info(), vec![ok(applied())]); + let mut args = APPLY_ARGS.to_vec(); + args.extend(["--retention-mode=bounded", "--json"]); + assert_eq!(json_stdout(&scratch.run(&server.url, &args)), applied()); + assert_eq!( + server.body(0), + json!({ + "retention_mode": "bounded", + "retention_days": 7, + "policy_revision": "sha256:policy", + "plan_revision": "sha256:plan", + "confirm_retroactive_pruning": false + }) + ); +} + +#[test] +fn apply_takes_the_proposal_and_revisions_from_a_saved_plan() { + let scratch = Scratch::new(); + for (plan, proposal) in [ + ( + shortening_plan(), + json!({"retention_mode": "bounded", "retention_days": 7}), + ), + (forever_plan(), json!({"retention_mode": "forever"})), + ] { + let path = scratch.0.join("plan.json"); + fs::write(&path, serde_json::to_vec_pretty(&plan).unwrap()).unwrap(); + let plan_file = format!("--plan-file={}", path.display()); + let server = Server::new(info(), vec![ok(applied())]); + stdout_text(&scratch.run( + &server.url, + &[ + "namespace:retention-apply", + "BILLING", + &plan_file, + "--confirm-retroactive-pruning", + ], + )); + let mut expected = proposal; + expected["policy_revision"] = json!("sha256:policy"); + expected["plan_revision"] = json!("sha256:plan"); + expected["confirm_retroactive_pruning"] = json!(true); + assert_eq!(server.body(0), expected); + } +} + +#[test] +fn each_refused_apply_changes_nothing_and_says_what_to_do_next() { + let scratch = Scratch::new(); + for (status, body, id, expected) in [ + ( + 409, + json!({ + "reason": "retention_policy_revision_stale", + "namespace": "billing", + "message": "The namespace changed after the plan. Request a new plan and apply its revisions.", + "policy_revision": "sha256:newer" + }), + "retention_plan.stale", + vec![ + "Server error: The namespace changed after the plan. Request a new plan and apply its revisions.", + "Reason: retention_policy_revision_stale", + "Nothing was applied: the namespace changed after the plan. Its current policy revision is sha256:newer.", + " Try: dw namespace:retention-plan billing", + ], + ), + ( + 409, + json!({ + "reason": "retention_plan_revision_mismatch", + "namespace": "billing", + "message": "The policy to apply is not the policy that was planned. Request a plan for this policy." + }), + "retention_plan.mismatch", + vec![ + "Reason: retention_plan_revision_mismatch", + "Nothing was applied: the policy sent is not the policy that was planned.", + " Try: dw namespace:retention-plan billing", + ], + ), + ( + 422, + json!({ + "reason": "retention_pruning_confirmation_required", + "namespace": "billing", + "retroactive": true, + "message": "This policy makes closed runs eligible for pruning that the current policy keeps, and pruning is irreversible. Set confirm_retroactive_pruning to true to apply it." + }), + "retention_plan.confirmation_required", + vec![ + "Reason: retention_pruning_confirmation_required", + "repeat the command with --confirm-retroactive-pruning.", + ], + ), + ] { + let server = Server::new(info(), vec![refusal(status, body.clone())]); + let output = scratch.run(&server.url, &APPLY_ARGS); + assert_eq!(output.status.code(), Some(2), "{id}: {output:?}"); + assert_eq!(server.requests().len(), 1, "{id}"); + assert_eq!(server.body(0)["confirm_retroactive_pruning"], json!(false)); + let stderr = String::from_utf8(output.stderr).unwrap(); + for line in expected { + assert!(stderr.contains(line), "{id}: {line}: {stderr}"); + } + + let server = Server::new(info(), vec![refusal(status, body.clone())]); + let mut args = APPLY_ARGS.to_vec(); + args.push("--json"); + let output = scratch.run(&server.url, &args); + assert_eq!(output.status.code(), Some(2), "{id}: {output:?}"); + assert_eq!(server.requests().len(), 1, "{id}"); + let envelope: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(envelope["exit_code"], json!(2), "{envelope}"); + assert_eq!(envelope["status_code"], json!(status), "{envelope}"); + assert_eq!(envelope["reason"], body["reason"], "{envelope}"); + assert_eq!(envelope["server_response"], body, "{envelope}"); + assert_eq!(envelope["recommendations"][0]["id"], json!(id), "{envelope}"); + } +} + +#[test] +fn a_server_without_the_plan_routes_points_at_server_3_30() { + let scratch = Scratch::new(); + for args in [ + vec!["namespace:retention-plan", "billing", "--retention=7"], + APPLY_ARGS.to_vec(), + ] { + let server = Server::new(info(), vec![refusal(404, json!({"message": "Not Found"}))]); + let mut json_args = args.clone(); + json_args.push("--json"); + let output = scratch.run(&server.url, &json_args); + assert_eq!(output.status.code(), Some(5), "{args:?}: {output:?}"); + let envelope: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!( + envelope["recommendations"][0]["id"], + json!("retention_plan.unsupported"), + "{envelope}" + ); + assert!(envelope["recommendations"][0]["message"] + .as_str() + .unwrap() + .contains("native Durable Workflow Server 3.30.0 or later")); + } + + // An unknown namespace on a Server that has the route is just not found. + let server = Server::new( + info(), + vec![refusal( + 404, + json!({"reason": "namespace_not_found", "namespace": "nope", "message": "Namespace [nope] not found."}), + )], + ); + let output = scratch.run(&server.url, &["namespace:retention-plan", "nope", "--json"]); + assert_eq!(output.status.code(), Some(5), "{output:?}"); + let envelope: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!( + envelope["recommendations"][0]["id"], + json!("resource.not_found"), + "{envelope}" + ); +} + +#[test] +fn invalid_options_and_plan_files_are_refused_before_any_request() { + let scratch = Scratch::new(); + let wrong_namespace = scratch.0.join("other.json"); + let mut other = shortening_plan(); + other["namespace"] = json!("orders"); + fs::write(&wrong_namespace, other.to_string()).unwrap(); + let not_a_plan = scratch.0.join("applied.json"); + fs::write(¬_a_plan, applied().to_string()).unwrap(); + let missing = scratch.0.join("missing.json"); + let file = |path: &PathBuf| format!("--plan-file={}", path.display()); + let (wrong_namespace, not_a_plan, missing) = + (file(&wrong_namespace), file(¬_a_plan), file(&missing)); + for (args, message) in [ + ( + vec!["namespace:retention-apply", "billing", "--retention=7"], + "--policy-revision is required.", + ), + ( + vec![ + "namespace:retention-apply", + "billing", + "--policy-revision=sha256:policy", + ], + "--plan-revision is required.", + ), + ( + vec!["namespace:retention-plan", "billing", "--retention=seven"], + "--retention must be a positive integer.", + ), + ( + vec!["namespace:retention-plan", "billing", "--retention=0"], + "--retention must be a positive integer.", + ), + ( + vec!["namespace:retention-plan", "billing", "--scan-limit=-1"], + "--scan-limit must be a positive integer.", + ), + ( + vec![ + "namespace:retention-plan", + "billing", + "--retention-mode=sometimes", + ], + "--retention-mode must be bounded or forever.", + ), + ( + vec![ + "namespace:retention-plan", + "billing", + "--retention-mode=forever", + "--retention=7", + ], + "a forever policy has no days", + ), + ( + vec![ + "namespace:retention-apply", + "billing", + &wrong_namespace, + "--retention=7", + ], + "--plan-file cannot be combined with --retention", + ), + ( + vec!["namespace:retention-apply", "billing", &wrong_namespace], + "plans namespace orders, not billing.", + ), + ( + vec!["namespace:retention-apply", "billing", ¬_a_plan], + "its schema is not durable-workflow.v2.retention-plan.v1", + ), + ( + vec!["namespace:retention-apply", "billing", &missing], + "Unable to read --plan-file", + ), + ] { + let server = Server::new(info(), vec![ok(json!({}))]); + let output = scratch.run(&server.url, &args); + assert_eq!(output.status.code(), Some(2), "{args:?}: {output:?}"); + assert!(server.requests().is_empty(), "{args:?}"); + let stderr = String::from_utf8(output.stderr).unwrap(); + assert!(stderr.contains(message), "{message}: {stderr}"); + } +} + +#[test] +fn names_are_one_encoded_segment_and_dot_names_are_refused() { + let scratch = Scratch::new(); + for (args, line) in [ + ( + vec!["namespace:retention-plan", "bill/ing?x", "--json"], + "POST /prefix/api/namespaces/bill%2Fing%3Fx/retention-plan HTTP/1.1", + ), + ( + vec![ + "namespace:retention-apply", + "bill/ing", + "--policy-revision=a", + "--plan-revision=b", + "--json", + ], + "POST /prefix/api/namespaces/bill%2Fing/retention-plan/apply HTTP/1.1", + ), + ] { + let server = Server::new(info(), vec![ok(json!({}))]); + json_stdout(&scratch.run(&server.url, &args)); + assert_eq!(server.request_lines(), [line], "{args:?}"); + } + for name in ["..", "."] { + let server = Server::new(info(), vec![ok(json!({}))]); + let output = scratch.run(&server.url, &["namespace:retention-plan", name, "--json"]); + assert_eq!(output.status.code(), Some(2), "{name}: {output:?}"); + assert!(server.requests().is_empty(), "{name}"); + } +} + +#[test] +fn a_lost_apply_response_is_never_resent() { + let scratch = Scratch::new(); + let server = Server::new(info(), vec![lost()]); + let mut args = APPLY_ARGS.to_vec(); + args.push("--json"); + let output = scratch.run(&server.url, &args); + assert_eq!(output.status.code(), Some(3), "{output:?}"); + assert_eq!(server.requests().len(), 1); +}