diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml index 0073db9..e07b711 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/pull-request.yml @@ -29,6 +29,9 @@ jobs: go-version-file: go.mod - run: go build ./... - run: go test -race ./... + - name: Test the rollback rehearsal skill + if: runner.os == 'Linux' + run: python3 -m unittest discover -s tests/skills lint: runs-on: ubuntu-latest diff --git a/.gitignore b/.gitignore index 13bb2a3..5cf1b50 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,6 @@ /website/public/ /website/resources/ /website/.hugo_build.lock + +# Python bytecode generated by skill tests. +__pycache__/ diff --git a/README.md b/README.md index 6df6dc9..a4c8c56 100644 --- a/README.md +++ b/README.md @@ -99,6 +99,10 @@ Reading works against any Flagsmith instance. Changing flags — `flag update`, - `flagsmith auth token` — print the active Admin API credential for curl/scripts. - `flagsmith api ` — call any Flagsmith endpoint with the CLI's credentials applied (curl-like; `--sdk` for the SDK API, `-F`/`-f` fields). +## Agent skills + +[Rehearse a flag rollback](skills/rehearse-flag-rollback/SKILL.md) compares how different retirement policies affect new and in-flight work in a disposable environment. + ## Conventions - `--json` (or `FLAGSMITH_JSON_OUTPUT`) for machine-readable output; `--jq ` to filter it. diff --git a/skills/rehearse-flag-rollback/SKILL.md b/skills/rehearse-flag-rollback/SKILL.md new file mode 100644 index 0000000..55c351c --- /dev/null +++ b/skills/rehearse-flag-rollback/SKILL.md @@ -0,0 +1,15 @@ +--- +name: rehearse-flag-rollback +description: Use the Flagsmith CLI to rehearse a flag rollback against fresh and in-flight application work, compare rollback policies, and report which application invariants hold. +--- + +Use this when turning a flag off (or back on) could strand work started under its previous assignment. A successful flag write establishes configuration state. Only a probe of the application can establish what happens to that work. + +1. **Define the decision.** Identify the project, environment, flag, before/after assignment, audience, and candidate retirement policies. Ask what must stay true for a new visitor and for work already in progress. Phrase each check as something you can observe. Can the user reopen a saved draft? Does a retried job deliver exactly once? Agree on required checks before inspecting results. +2. **Find the application probe.** Look for an existing integration test or fixture. Adapt it to the [probe contract](references/probe.md) if needed. Confirm equivalent work completes before the rollback. Capture one piece of synthetic work and replay independent copies with the same dependencies and inputs under each candidate policy. Sample the actual application outcome, including side effects. If the necessary fixture or observation is unavailable, report the missing evidence. +3. **Confirm scope.** Identify both API origins and the numeric project ID with the operator. Establish permission to create and remove a disposable clone and to run the selected application fixture. Use staging dependencies and an authorized credential for that instance. Review the probe before running it. Flag isolation alone does not isolate queues, databases, payments or webhooks. +4. **Run the rehearsal.** Run the helper from the installed skill directory, using Flagsmith CLI v2, Flagsmith 2.263.0 or newer, Python 3 and an executable probe (the example uses a POSIX shebang). The helper reads the source, creates a uniquely named clone, checks the environment default and the SDK assignment before capture and after the change, then runs the named plans and verifies clone removal. The source receives no flag writes. Pass the application's own check names and policies. For an executable local example, see the [queue rehearsal](references/probe.md#try-the-queue-example). +5. **Report the decision.** Read the compact JSON receipt and exit code. Name the audience, failing or unobservable invariants, and cleanup status. Recommend a plan only after its required checks pass and cleanup is verified. A mixed comparison exits 1 even when one plan passed. If cleanup is unverified, resolve the run's generated name to its ID and verify ownership before removal. If interrupted by a hard kill, use the name printed before cloning. Never retry a mutation blindly. +6. **Hand off the release.** State which traffic, versions and dependencies were exercised. Report missing evidence or unverified cleanup before recommending any action. For additional audiences run separate rehearsals using synthetic identities and known traits. Cloning omits identity-specific state. Applying anything to a shared or production environment requires a separate decision. Present the proposed change, re-read current state and obtain explicit approval. A rehearsal does not establish production-wide safety. + +The helper changes the environment default's Boolean state. For a value, variant-weight or override rollback, rehearse that exact scope in a disposable environment with the CLI and evaluate the relevant identities and values. Do not substitute a Boolean toggle as evidence for a different change. diff --git a/skills/rehearse-flag-rollback/examples/queue_probe.py b/skills/rehearse-flag-rollback/examples/queue_probe.py new file mode 100755 index 0000000..1adb2f6 --- /dev/null +++ b/skills/rehearse-flag-rollback/examples/queue_probe.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python3 +"""A synthetic queue migration. Each replay starts with a fresh database.""" +import json +import os +import sqlite3 +import sys +from urllib.request import Request, urlopen +from uuid import uuid4 + + +def assignment(): + req = Request(os.environ["REHEARSAL_SDK_URL"] + "/api/v1/flags/", + headers={"X-Environment-Key": os.environ["REHEARSAL_SDK_KEY"]}) + with urlopen(req, timeout=5) as res: + flags = json.load(res) + return next(row["enabled"] for row in flags if row["feature"]["name"] == os.environ["REHEARSAL_FLAG"]) + + +def job(enabled): + return {"id": str(uuid4()), "payload": {"units": 7} if enabled else 7} + + +def replay(plan, pending, fresh): + if plan not in {"immediate", "drain"}: + raise ValueError("unknown schedule") + db = sqlite3.connect(":memory:") + db.execute("create table deliveries(job text primary key, units integer)") + + def deliver(item, v2_reader): + units = item["payload"] + if isinstance(units, dict): + if not v2_reader: + return + units = units["units"] + db.execute("insert or ignore into deliveries values (?, ?)", (item["id"], units)) + + deliver(fresh, False) + deliver(pending, plan == "drain") + deliver(pending, plan == "drain") # retry while the same reader is available + deliver(pending, False) # late retry after retirement + + def delivered_once(item): + return db.execute("select count(*), sum(units) from deliveries where job = ?", + (item["id"],)).fetchone() == (1, 7) + + checks = {"fresh_legacy_job": fresh["payload"] == 7 and delivered_once(fresh), + "inflight_delivered_once": delivered_once(pending)} + db.close() + return checks + + +if __name__ == "__main__": + request = json.load(sys.stdin) + if request["identity"] is not None or request["traits"]: + sys.exit("the example supports anonymous assignments only") + if sys.argv[1] == "capture": + if assignment() is not True: + raise ValueError("capture did not use the new writer") + result = job(True) + if not replay("drain", result, job(True))["inflight_delivered_once"]: + raise ValueError("the pending job could not complete before rollback") + else: + result = replay(request["plan"], request["snapshot"], job(assignment())) + print(json.dumps(result)) diff --git a/skills/rehearse-flag-rollback/references/probe.md b/skills/rehearse-flag-rollback/references/probe.md new file mode 100644 index 0000000..140c86a --- /dev/null +++ b/skills/rehearse-flag-rollback/references/probe.md @@ -0,0 +1,30 @@ +# Application probe + +Run the helper with explicit Admin and SDK origins, a numeric project ID, a source environment, and the flag name. Use the CLI's normal login or host-scoped credentials. Keep CLI output filtered; never print tokens, full environment documents, or raw sessions into the agent transcript. + +The probe is a trusted executable invoked without a shell. It gets the clone's client-side SDK key in `REHEARSAL_SDK_KEY`, its SDK origin in `REHEARSAL_SDK_URL`, and `REHEARSAL_FLAG`. The helper passes only those three variables plus PATH, LANG and SYSTEMROOT if set. The probe must bind its app to this clone and isolate its own resources. It owns cleanup of any application fixtures it creates. Use an isolated OS account or container for untrusted code; filtering environment variables is not a process sandbox. The probe exercises the retirement policies in its test environment. + +| Invocation | JSON on stdin | Required JSON on stdout | +| --- | --- | --- | +| `probe capture` | `identity`, `traits`, null `plan` and `snapshot` | One non-null JSON snapshot of in-flight work under the before assignment | +| `probe replay` | The selected `plan`, the original `snapshot`, the same identity and traits | Exactly the declared check names, each with a Boolean or null | + +Return true only when the application assertion was observed; false for an observed violation; null for missing evidence. Exit nonzero on infrastructure errors. Repeating a replay must start from the same captured input with clean application state. Before returning a capture, verify an equivalent item can finish on the original path. A snapshot may reference a fixture that the probe restores per plan. Use compact, synthetic JSON. Avoid live customer data. For asynchronous jobs use a bounded completion condition and check observable side effects after retries. + +## Try the queue example + +The example fetches the clone's assignment from the Flagsmith SDK endpoint and uses a fresh in-memory SQLite database per plan. It exercises the anonymous audience of a Boolean flag. It compares retiring a versioned queue reader immediately with allowing previously encoded jobs to complete. Use your own flag in an authorized test project. + +From the skill directory, set `ADMIN_ORIGIN`, `SDK_ORIGIN`, `PROJECT_ID`, `SOURCE_ENV` and `FLAG` to your authorized target. + +```sh +python3 scripts/rehearse.py \ + --api-url "$ADMIN_ORIGIN" --sdk-api-url "$SDK_ORIGIN" \ + --project "$PROJECT_ID" --source "$SOURCE_ENV" --flag "$FLAG" \ + --probe examples/queue_probe.py --plan immediate --plan drain \ + --check fresh_legacy_job --check inflight_delivered_once +``` + +The two plans share an immutable capture. The example expects the old reader to handle fresh work under both policies. The new-format job fails to deliver under immediate retirement and delivers seven units exactly once under the drain policy. Replace both the probe and its expectations for a different application. + +Exit 0 means every required observation passed in every plan. Exit 1 means the comparison completed and at least one check failed. Exit 2 means incomplete evidence, an unexpected SDK assignment, a failed command, or unverified cleanup. An inconclusive run can still contain observations from completed plans. The queue example captures work with the flag on. For an off-to-on rehearsal, use `--before off` with a probe that captures work under the off assignment. For targeted users supply `--identity` and repeated `--trait name=value`; implement that audience in the probe too. Targeted rehearsals stop before cloning if the active identity store cannot list overrides reliably or the flag has any identity overrides. Supply the full synthetic traits required by your probe; percentage-based assignments may vary by environment. The SDK convergence wait defaults to 90 seconds per switch; set `--convergence-timeout SECONDS` to match your cache lifetime. A flag hidden from the SDK when disabled cannot prove an explicit false assignment with this helper. diff --git a/skills/rehearse-flag-rollback/scripts/rehearse.py b/skills/rehearse-flag-rollback/scripts/rehearse.py new file mode 100755 index 0000000..4912321 --- /dev/null +++ b/skills/rehearse-flag-rollback/scripts/rehearse.py @@ -0,0 +1,211 @@ +#!/usr/bin/env python3 +"""Compare application rollback policies in a disposable Flagsmith environment.""" + +import argparse +import ipaddress +import json +import os +from pathlib import Path +import re +import secrets +import signal +import subprocess +import sys +import time +from urllib.parse import urlsplit + + +class Inconclusive(Exception): + pass + + +def origin(value): + try: + url = urlsplit(value) + port = url.port + except ValueError: + raise argparse.ArgumentTypeError("invalid API origin") from None + if url.hostname and url.path in ("", "/") and not ( + url.username is not None or url.password is not None or port == 0 or "?" in value or "#" in value + ): + if url.scheme == "https": + return value.rstrip("/") + try: + local = ipaddress.ip_address(url.hostname).is_loopback + except ValueError: + local = url.hostname == "localhost" + if local and url.scheme == "http": + return value.rstrip("/") + raise argparse.ArgumentTypeError("use an HTTPS origin or local loopback HTTP origin") + + +def label(value): + if not re.fullmatch(r"[a-zA-Z0-9][a-zA-Z0-9_.-]{0,127}", value): + raise argparse.ArgumentTypeError("expected a short identifier") + return value + + +def execute(args, env, phase, *, payload=None, timeout=30, read=True): + try: + result = subprocess.run(args, env=env, input=json.dumps(payload), text=True, + capture_output=True, timeout=timeout, check=True) + if read: + return json.loads(result.stdout) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Raw CLI diagnostics and application output can contain credentials or artifacts. + raise Inconclusive(f"{phase}: {type(exc).__name__}") from None + + +def rehearsal(opts): + name = "rehearsal-" + secrets.token_hex(10) + report = {"sandbox": name, "plans": {}, "cleanup": "not-created"} + admin = {k: v for k, v in os.environ.items() + if not k.upper().startswith("FLAGSMITH_ENVIRONMENT_KEY")} + base = ["flagsmith", "--no-input", "--api-url", opts.api_url, "--sdk-api-url", + opts.sdk_api_url, "--project", str(opts.project)] + key = None + + def cli(*args, query=None, phase, environment=None, timeout=30): + target = environment or key + command = base + (["--environment", target] if target else []) + list(args) + if query: + command += ["--jq", query] + return execute(command, admin, phase, read=bool(query), timeout=timeout) + + def switch(enabled): + action = "enable" if enabled else "disable" + cli("flag", action, opts.flag, "--yes", phase=f"flag {action}") + if cli("flag", "get", opts.flag, query=".enabled", phase="admin readback") is not enabled: + raise Inconclusive("unexpected environment default") + audience = ["--identity", opts.identity] if opts.identity else [] + for trait in opts.trait: + audience.extend(["--trait", trait]) + deadline = time.monotonic() + opts.convergence_timeout + delay = 0.5 + while True: + remaining = deadline - time.monotonic() + if remaining <= 0: + break + state = cli("evaluate", opts.flag, *audience, query=".enabled", phase="SDK evaluation", + timeout=min(30, remaining)) + remaining = deadline - time.monotonic() + if remaining <= 0: + break + if state is enabled: + return + time.sleep(min(delay, remaining)) + delay = min(delay * 2, 5) + raise Inconclusive("SDK assignment did not converge for this audience") + + def probe(phase, plan=None, snapshot=None): + # Pass an explicit environment to the trusted probe. The CLI admin credential + # and unrelated CI secrets are not needed by the application under test. + env = {k: os.environ[k] for k in ("PATH", "LANG", "SYSTEMROOT") if k in os.environ} + env.update(REHEARSAL_SDK_URL=opts.sdk_api_url, REHEARSAL_SDK_KEY=key, + REHEARSAL_FLAG=opts.flag) + return execute([opts.probe, phase], env, f"probe {phase}", timeout=opts.probe_timeout, + payload={"plan": plan, "snapshot": snapshot, "identity": opts.identity, + "traits": opts.trait}) + + def valid_environment(env): + return (isinstance(env, dict) and type(env.get("project")) is int + and env["project"] == opts.project and type(env.get("id")) is int + and env["id"] > 0 and isinstance(env.get("api_key"), str) + and bool(env["api_key"]) and not env["api_key"].startswith("-")) + + fields = "{id,name,project,api_key}" + try: + source = cli("environment", "get", opts.source, query=fields, phase="source lookup") + if not valid_environment(source): + raise Inconclusive("source environment identity unverified") + if opts.identity: + # Older Edge indexes and projects migrating between stores may omit overrides. + ready = cli("project", "get", str(opts.project), phase="check identity storage", + query="(.enable_dynamo_db == false and .use_edge_identities == false) or " + "(.enable_dynamo_db == true and .use_edge_identities == true and " + ".show_edge_identity_overrides_for_feature == true)") + if ready is not True: + raise Inconclusive("source identity storage cannot verify all overrides") + empty = cli("flag", "list", "--feature", opts.flag, "--identities", + environment=source["api_key"], phase="check source identity overrides", + query='type == "array" and length == 0') + if empty is not True: + raise Inconclusive("source identity overrides cannot be reproduced by cloning") + report["cleanup"] = "inspect-by-name" + print(f"Temporary environment: {name} (project {opts.project})", file=sys.stderr, flush=True) + clone = cli("environment", "clone", source["api_key"], name, query=fields, phase="clone") + if not (valid_environment(clone) and clone.get("name") == name + and clone["id"] != source["id"] and clone["api_key"] != source["api_key"]): + raise Inconclusive("clone identity unverified") + key = clone["api_key"] + switch(opts.before == "on") + snapshot = probe("capture") + if snapshot is None: + raise Inconclusive("missing capture") + switch(opts.before != "on") + for plan in opts.plan: + observed = probe("replay", plan, snapshot) + if (not isinstance(observed, dict) or set(observed) != set(opts.check) + or any(value is not None and type(value) is not bool for value in observed.values())): + raise Inconclusive(f"invalid observations for {plan}") + report["plans"][plan] = observed + except (Inconclusive, KeyboardInterrupt) as exc: + report["error"] = str(exc) or "interrupted" + finally: + if key: + try: + cli("environment", "delete", key, "--yes", phase="delete clone") + ids = cli("environment", "list", query="map(.id)", phase="verify deletion") + if (not isinstance(ids, list) or any(type(i) is not int for i in ids) + or clone["id"] in ids or source["id"] not in ids): + raise Inconclusive("clone deletion unverified") + report["cleanup"] = "verified" + except (Inconclusive, KeyboardInterrupt): + report["cleanup"] = "inspect-by-name" + checks = [value for results in report["plans"].values() for value in results.values()] + if "error" in report or report["cleanup"] != "verified" or None in checks: + return report, 2 + return report, 0 if all(checks) else 1 + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--api-url", required=True, type=origin) + parser.add_argument("--sdk-api-url", required=True, type=origin) + parser.add_argument("--project", required=True, type=int) + parser.add_argument("--source", required=True) + parser.add_argument("--flag", required=True, type=label) + parser.add_argument("--before", choices=["on", "off"], default="on") + parser.add_argument("--identity") + parser.add_argument("--trait", action="append", default=[]) + parser.add_argument("--probe", required=True, type=lambda s: str(Path(s).resolve())) + parser.add_argument("--probe-timeout", type=int, default=30) + parser.add_argument("--convergence-timeout", type=int, default=90, metavar="SECONDS") + parser.add_argument("--plan", type=label, action="append", required=True) + parser.add_argument("--check", type=label, action="append", required=True) + opts = parser.parse_args() + if opts.source.startswith("-") or not opts.source.strip() or opts.project < 1: + parser.error("supply a project ID and source environment name or key") + if opts.probe_timeout <= 0 or not os.access(opts.probe, os.X_OK) or not Path(opts.probe).is_file(): + parser.error("supply an executable probe and positive timeout") + if len(set(opts.plan)) != len(opts.plan) or len(set(opts.check)) != len(opts.check): + parser.error("duplicate plan or check") + if opts.convergence_timeout <= 0: + parser.error("supply a positive SDK convergence timeout") + if opts.identity is not None and not opts.identity.strip(): + parser.error("supply a non-empty synthetic identity") + if opts.trait and not opts.identity: + parser.error("traits require an identity") + + def interrupt(_signum, _frame): + raise KeyboardInterrupt + + signal.signal(signal.SIGTERM, interrupt) + report, code = rehearsal(opts) + report["verdict"] = ("pass", "fail", "inconclusive")[code] + print(json.dumps(report, separators=(",", ":"))) + return code + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/skills/test_rollback_rehearsal.py b/tests/skills/test_rollback_rehearsal.py new file mode 100644 index 0000000..d3ed4a9 --- /dev/null +++ b/tests/skills/test_rollback_rehearsal.py @@ -0,0 +1,297 @@ +import argparse +import contextlib +import io +from http.server import BaseHTTPRequestHandler, HTTPServer +import json +import os +from pathlib import Path +import subprocess +import sys +import threading +import unittest +from unittest.mock import patch + +SKILL = Path(__file__).resolve().parents[2] / "skills" / "rehearse-flag-rollback" +sys.path.insert(0, str(SKILL / "scripts")) +import rehearse + + +class RehearsalTests(unittest.TestCase): + def setUp(self): + self.opts = argparse.Namespace( + api_url="https://admin.example", sdk_api_url="https://sdk.example", + project=4, source="Staging", flag="reader", probe="probe", before="on", + identity=None, trait=[], plan=["first", "second"], check=["balance"], + probe_timeout=2, convergence_timeout=1, + ) + self.source = {"id": 1, "name": "Staging", "project": 4, "api_key": "src"} + self.calls = [] + self.evaluation_timeouts = [] + self.responses = {} + self.snapshot = {"balance": 17} + + def invoke(self, args, env, phase, *, payload=None, **kwargs): + self.calls.append(phase) + if phase == "SDK evaluation": + self.evaluation_timeouts.append(kwargs.get("timeout")) + if phase.startswith("probe "): + self.assertNotIn("FLAGSMITH_API_KEY", env) + self.assertEqual(env["REHEARSAL_SDK_KEY"], "copy") + self.assertEqual(payload["identity"], self.opts.identity) + self.assertEqual(payload["traits"], self.opts.trait) + else: + self.assertNotIn("FLAGSMITH_ENVIRONMENT_KEY", env) + if phase not in ("source lookup", "clone", "check identity storage", "check source identity overrides"): + self.assertEqual(args[args.index("--environment") + 1], "copy") + + if phase in self.responses: + result = self.responses[phase] + if isinstance(result, BaseException): + raise result + return result + if phase == "source lookup": + return self.source + if phase == "check identity storage": + return True + if phase == "check source identity overrides": + self.assertIn("--identities", args) + self.assertEqual(args[args.index("--feature") + 1], self.opts.flag) + self.assertEqual(args[args.index("--environment") + 1], "src") + return True + if phase == "clone": + self.assertEqual(args[args.index("clone") + 1], "src") + return dict(self.source, id=2, name=args[args.index("clone") + 2], api_key="copy") + if phase in ("flag enable", "flag disable"): + self.enabled = phase == "flag enable" + elif phase in ("SDK evaluation", "admin readback"): + return self.enabled + elif phase == "probe capture": + return self.snapshot + elif phase == "probe replay": + self.assertEqual(payload["snapshot"], self.snapshot) + return {"balance": payload["plan"] == "second"} + elif phase == "delete clone": + self.assertEqual(args[args.index("delete") + 1], "copy") + elif phase == "verify deletion": + return [1] + else: + self.fail(phase) + + def run_rehearsal(self): + with patch.object(rehearse, "execute", self.invoke), contextlib.redirect_stderr(io.StringIO()): + return rehearse.rehearsal(self.opts) + + def test_mixed_plans_replay_one_capture(self): + # Given + with patch.dict(os.environ, FLAGSMITH_ENVIRONMENT_KEY="other", FLAGSMITH_API_KEY="admin"): + # When + report, code = self.run_rehearsal() + + # Then + self.assertEqual(code, 1) + self.assertEqual(report["plans"], {"first": {"balance": False}, "second": {"balance": True}}) + self.assertEqual(report["cleanup"], "verified") + self.assertEqual(self.calls.count("probe capture"), 1) + + def test_reverse_change_with_synthetic_identity(self): + # Given + self.opts.before = "off" + self.opts.identity = "reader" + self.opts.trait = ["region=test"] + self.opts.plan = ["second"] + + # When + _, code = self.run_rehearsal() + + # Then + self.assertEqual(code, 0) + self.assertLess(self.calls.index("flag disable"), self.calls.index("flag enable")) + + def test_identity_overrides_stop_before_clone(self): + # Given + self.opts.identity = "reader" + self.responses["check source identity overrides"] = False + + # When + _, code = self.run_rehearsal() + + # Then + self.assertEqual(code, 2) + self.assertNotIn("clone", self.calls) + + def test_unavailable_identity_storage_stops_before_clone(self): + # Given + self.opts.identity = "reader" + for unknown in (False, None): + with self.subTest(storage=unknown): + self.responses["check identity storage"] = unknown + + # When + _, code = self.run_rehearsal() + + # Then + self.assertEqual(code, 2) + self.assertNotIn("check source identity overrides", self.calls) + self.assertNotIn("clone", self.calls) + + def test_origins_reject_trailing_query_and_fragment_delimiters(self): + # Given + for value in ("https://api.example?", "https://api.example/#"): + with self.subTest(value=value): + # When + with self.assertRaises(argparse.ArgumentTypeError) as error: + rehearse.origin(value) + + # Then + self.assertIn("origin", str(error.exception)) + + def test_invalid_source_or_clone_identity_prevents_writes(self): + # Given + for phase, response in (("source lookup", dict(self.source, id=None)), ("clone", self.source)): + with self.subTest(phase=phase): + self.responses = {phase: response} + self.calls.clear() + + # When + _, code = self.run_rehearsal() + + # Then + self.assertEqual(code, 2) + self.assertNotIn("flag enable", self.calls) + self.assertNotIn("delete clone", self.calls) + + def test_missing_or_malformed_observations(self): + # Given + for observed in ({"balance": None}, {}, {"balance": 1}, {"unrequested": True}): + with self.subTest(observed=observed): + self.responses["probe replay"] = observed + + # When + report, code = self.run_rehearsal() + + # Then + self.assertEqual((code, report["cleanup"]), (2, "verified")) + + def test_interrupted_capture_and_failed_readback_clean_up(self): + # Given + for phase, response in (("probe capture", KeyboardInterrupt()), ("admin readback", None), + ("probe replay", rehearse.Inconclusive("probe timeout"))): + with self.subTest(phase=phase): + self.responses = {phase: response} + + # When + report, code = self.run_rehearsal() + + # Then + self.assertEqual((code, report["cleanup"]), (2, "verified")) + + def test_sdk_polls_only_within_remaining_deadline(self): + # Given + self.responses["SDK evaluation"] = False + # One second total. The second poll begins with a quarter-second left. + with patch.object(rehearse.time, "monotonic", side_effect=[0, 0.125, 0.25, 0.75, 0.875, 1]), \ + patch.object(rehearse.time, "sleep") as sleep: + # When + report, code = self.run_rehearsal() + + # Then + self.assertEqual((code, report["cleanup"]), (2, "verified")) + self.assertNotIn("probe capture", self.calls) + self.assertEqual(self.evaluation_timeouts, [0.875, 0.25]) + self.assertEqual([call.args[0] for call in sleep.call_args_list], [0.5, 0.125]) + + def test_late_sdk_success_is_inconclusive(self): + # Given + self.responses["SDK evaluation"] = True + with patch.object(rehearse.time, "monotonic", side_effect=[0, 0.25, 1.125]): + # When + report, code = self.run_rehearsal() + + # Then + self.assertEqual((code, report["cleanup"]), (2, "verified")) + self.assertNotIn("probe capture", self.calls) + + def test_unverified_cleanup_overrides_pass(self): + # Given + self.opts.plan = ["second"] + for ids in ([1, 2], ["2"], [], None): + with self.subTest(ids=ids): + self.responses["verify deletion"] = ids + + # When + report, code = self.run_rehearsal() + + # Then + self.assertEqual((code, report["cleanup"]), (2, "inspect-by-name")) + + def test_command_errors_redact_arguments_and_raw_output(self): + # Given + command = [sys.executable, "-c", "print('private data')"] + + # When + with self.assertRaises(rehearse.Inconclusive) as error: + rehearse.execute(command, {}, "probe") + + # Then + self.assertEqual(str(error.exception), "probe: JSONDecodeError") + + def test_anonymous_queue_example_rejects_targeting(self): + # Given + request = {"identity": "reader", "traits": []} + + # When + run = subprocess.run( + [sys.executable, str(SKILL / "examples" / "queue_probe.py"), "capture"], + input=json.dumps(request), capture_output=True, text=True, + ) + + # Then + self.assertNotEqual(run.returncode, 0) + self.assertIn("anonymous", run.stderr) + + +class QueueExampleTests(unittest.TestCase): + def test_versioned_job_survives_only_with_reader_available(self): + # Given + class SDK(BaseHTTPRequestHandler): + def do_GET(self): + if self.path != "/api/v1/flags/" or self.headers.get("X-Environment-Key") != "copy": + self.send_error(404) + return + self.send_response(200) + self.end_headers() + flags = [{"feature": {"name": "reader"}, "enabled": self.server.enabled}] + self.wfile.write(json.dumps(flags).encode()) + + def log_message(self, *args): + pass + + with HTTPServer(("127.0.0.1", 0), SDK) as server: + worker = threading.Thread(target=server.serve_forever) + worker.start() + env = {**os.environ, "REHEARSAL_SDK_URL": f"http://127.0.0.1:{server.server_port}", + "REHEARSAL_SDK_KEY": "copy", "REHEARSAL_FLAG": "reader"} + + def probe(phase, plan=None, snapshot=None): + result = subprocess.run( + [sys.executable, str(SKILL / "examples" / "queue_probe.py"), phase], + input=json.dumps(dict(identity=None, traits=[], plan=plan, snapshot=snapshot)), + env=env, capture_output=True, check=True, text=True, timeout=5, + ) + return json.loads(result.stdout) + + try: + server.enabled = True + # When + snapshot = probe("capture") + server.enabled = False + outcomes = {plan: probe("replay", plan, snapshot) for plan in ("immediate", "drain")} + + # Then + for plan, observed in outcomes.items(): + with self.subTest(plan=plan): + self.assertEqual(observed, + {"fresh_legacy_job": True, "inflight_delivered_once": plan == "drain"}) + finally: + server.shutdown() + worker.join()