diff --git a/.dockerignore b/.dockerignore index 5e535dbb7..563244a02 100644 --- a/.dockerignore +++ b/.dockerignore @@ -32,6 +32,10 @@ agent/**/*.pyc # Deployment profile (ADR-024): infrastructure selection only; editing it must not rebuild the image abca.deployment*.json +# Emulator test tooling: never part of the agent image, and bumping its pinned +# version must not change the image hash +scripts/aws-emulator/ + # Git and tooling .git/ .prek/ diff --git a/.github/workflows/emulator.yml b/.github/workflows/emulator.yml new file mode 100644 index 000000000..788e65d32 --- /dev/null +++ b/.github/workflows/emulator.yml @@ -0,0 +1,64 @@ +name: emulator +# ADR-013 Tier 2a: runs ABCA's real handler, CLI and agent code against the AWS Emulator +# (https://github.com/aws/aws-emulator) instead of module-level SDK mocks. No AWS account, +# role or secret is involved, so it runs unchanged for fork pull requests. +# +# Advisory: the job is not in the required status checks of the `main` ruleset, so a red run +# is visible on the pull request but does not block the merge. To make it required, add the +# job name ("Emulator integration tests") to the ruleset; it already runs on merge_group, +# which a required check must do or the merge queue deadlocks (#327). +# +# Kept out of build.yml on purpose: deploy.yml and integ.yml start from `workflow_run` on +# build and need its conclusion to be `success`. +on: + pull_request: {} + merge_group: {} + workflow_dispatch: {} + +permissions: + contents: read + +concurrency: + group: emulator-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + emulator: + name: Emulator integration tests + runs-on: ubuntu-latest + timeout-minutes: 15 + permissions: + contents: read + env: + CI: "true" + MISE_EXPERIMENTAL: "1" + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Install mise + uses: jdx/mise-action@b44d12e7d0d8ee7461bb893e1b1993500433185b # v5.2.7 + with: + version: 2026.10.25 # exact mise release for every workflow (#890); bump by PR + cache: true + + - name: Setup Node.js + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: 22.x + + - name: Install dependencies + run: mise run install + + # Builds the pinned, signature-verified emulator image, starts a fresh emulator on + # loopback, runs the cdk, cli and agent emulator suites, and stops it. + - name: Emulator integration tests + run: mise run test:integration + + - name: Emulator log (on failure) + if: failure() + run: | + docker ps -a --filter name=abca-aws-emulator --format '{{.Names}}' \ + | xargs -r -n1 docker logs --tail 200 || true diff --git a/.github/workflows/integ.yml b/.github/workflows/integ.yml index 8b7969638..9c190a0ef 100644 --- a/.github/workflows/integ.yml +++ b/.github/workflows/integ.yml @@ -272,13 +272,7 @@ jobs: set -euo pipefail export INTEG_STACK_NAME="int-${HEAD_SHA:0:12}-${RUN_NUMBER}" echo "Integ stack name: $INTEG_STACK_NAME" - mise //cdk:integ -- --all --require-approval never \ - -c stackName="integ-${{ github.run_id }}-${{ github.run_attempt }}" \ - -c github:sha="$(git rev-parse HEAD)" \ - -c github:ref="$(git branch --show-current || echo "detached")" \ - -c github:actor="${{ github.triggering_actor }}" \ - -c github:repository="$(gh repo view --json nameWithOwner --jq .nameWithOwner)" \ - -c github:clean="$([ -z "$(git status --porcelain)" ] && echo true || echo false)" + mise //cdk:integ # Post the final integ-smoke status back to the PR head so the check flips from # pending to success/failure. Skipped for workflow_dispatch (no PR to gate). diff --git a/AGENTS.md b/AGENTS.md index 4ba91e0e1..e9033584e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -20,6 +20,7 @@ mise run check:fast # lint + drift-prevention (drift and file-hygiene chec mise run security # secrets, deps, sast, grype, retire, gh-actions, agent mise run hooks:install # prek git hooks (also runs at end of install) mise run hooks:run # pre-commit + pre-push locally +mise run test:integration # emulator-backed tests of cdk, cli and agent (needs Docker, no AWS account; not part of build) ``` Security subtasks: `mise run security:secrets`, `security:sast`, `security:sast:range` (the same rule packs, reporting only the findings a branch adds: the per-PR check), `security:sast:masking`, `security:deps`, `security:retire`, `security:gh-actions`. The secret scans print the rule, file and line of each finding. A 12-digit number that reads as an AWS account id fails them, in tests and workflows too, unless it is an AWS-published placeholder (`123456789012`, `111122223333`, `444455556666`, `000000000000`) or, when it is not an account id, its line carries `gitleaks:allow -- `. Use that marker only on a line that holds no identifier, key or token: it exempts the whole line from every rule of the secret scan, not only the number. For `security:sast:masking` allowlist intentional fallbacks with an inline `nosemgrep: -- ` comment on the flagged `return` line (or the line immediately above) — the rule anchors on the `return`, so a token placed higher does not bind. @@ -56,6 +57,7 @@ Branch names: `(feat|fix|chore|docs)/-short-description` (e.g. `do | Operator web console | `web/src/`, `web/test/` | `web/src/core/api/types.ts` if API changes | [web/AGENTS.md](./web/AGENTS.md) | | Agent runtime | `agent/src/` | `agent/tests/`, `agent/README.md` | [agent/AGENTS.md](./agent/AGENTS.md) | | Progress events | `agent/src/progress_writer.py`, `agent/src/pipeline.py`, `agent/src/runner.py` | `agent/tests/test_progress_writer.py`; `cli/src/commands/watch.ts` | [agent/AGENTS.md](./agent/AGENTS.md), [cli/AGENTS.md](./cli/AGENTS.md) | +| Emulator-backed integration tests (ADR-013 Tier 2a) | `cdk/test/emulator/`, `cli/test/emulator/`, `agent/tests_emulator/`; tooling in `scripts/aws-emulator/` | [scripts/aws-emulator/README.md](./scripts/aws-emulator/README.md) when a rule or a known difference from AWS changes; run with `mise run test:integration` | [cdk/AGENTS.md](./cdk/AGENTS.md), [cli/AGENTS.md](./cli/AGENTS.md), [agent/AGENTS.md](./agent/AGENTS.md) | | User-facing / design prose | `docs/guides/`, `docs/design/` | `mise //docs:sync` | [docs/AGENTS.md](./docs/AGENTS.md) | | ADRs | `docs/decisions/` | `mise //docs:sync` | [docs/AGENTS.md](./docs/AGENTS.md) | | Deployment profiles / regional capabilities | `cdk/src/deployment/`, `contracts/deployment-capabilities.json` | **`cli/src/deployment-capabilities.ts`**, `cli/src/deployment-profile.ts`, `docs/guides/DEPLOYMENT_GUIDE.md#deployment-profiles` | [cdk/AGENTS.md](./cdk/AGENTS.md), [cli/AGENTS.md](./cli/AGENTS.md) | diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 1db3450fe..2a0026042 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -92,7 +92,7 @@ The `upgrade-main` GitHub workflow runs `mise run upgrade` daily and opens a PR PRs labeled `auto-approve` are approved automatically by the `auto-approve` workflow; only apply the label to automated PRs whose changes are gated by the full build (e.g. the dependency-upgrade PRs). -The tools that the gates run are not part of that upgrade. `prek`, `gitleaks`, `uv`, `semgrep`, `osv-scanner`, `grype` and `zizmor` are pinned to exact versions in the root `mise.toml` (`uv` and `trivy` in `agent/mise.toml`), and every workflow that installs mise pins the mise version (`version:` under `jdx/mise-action`). Nothing bumps these pins automatically: bump them by pull request, to a release that is at least 7 days old, and keep `uv` the same in both files. After pulling a change to a pin, run `mise install`. +The tools that the gates run are not part of that upgrade. `prek`, `gitleaks`, `uv`, `semgrep`, `osv-scanner`, `grype` and `zizmor` are pinned to exact versions in the root `mise.toml` (`uv` and `trivy` in `agent/mise.toml`), and every workflow that installs mise pins the mise version (`version:` under `jdx/mise-action`). Nothing bumps these pins automatically: bump them by pull request, to a release that is at least 7 days old, and keep `uv` the same in both files and in the `uv` image that `agent/Dockerfile` copies from. After pulling a change to a pin, run `mise install`. ### Git hooks diff --git a/agent/.trivyignore b/agent/.trivyignore index e69de29bb..6438574e0 100644 --- a/agent/.trivyignore +++ b/agent/.trivyignore @@ -0,0 +1,14 @@ +# Findings accepted temporarily in the agent image scan (`mise //agent:security:image`). +# An entry applies to the whole image. Each one expires (exp:YYYY-MM-DD is the first +# day, in UTC, on which it no longer applies) so that the scan fails again and the +# finding is re-reviewed. Nothing warns ahead of that day: the weekly expiry warning +# reads only the osv-scanner.toml files. Remove an entry as soon as a fixed release is +# available. + +# golang.org/x/net/html, quadratic text-node parsing (GO-2026-6860), reported for +# usr/local/bin/gh. On 2026-11-16 no gh release requires x/net >= 0.62.0, which has the +# fix: 2.103.3 requires 0.60.0, 2.104.0 requires 0.61.0, cli/cli trunk 0.62.0. The +# functions the advisory names (html.Parse and the parser behind it) are not linked into +# the binary: gh keeps only the tokenizer (`govulncheck -mode binary` and `go tool nm`). +# Remove this with the GH_VERSION bump in agent/Dockerfile that brings x/net 0.62.0. +CVE-2026-78661 exp:2026-12-16 diff --git a/agent/AGENTS.md b/agent/AGENTS.md index 95b3e8c74..9a741a609 100644 --- a/agent/AGENTS.md +++ b/agent/AGENTS.md @@ -48,6 +48,7 @@ Unit tests cannot reach AWS through botocore. `tests/conftest.py` removes the cr | `agent/src/prompts/` | WRITE | System prompts per workflow | | `agent/src/progress_writer.py` | WRITE | TaskEvents emission | | `agent/tests/` | WRITE | pytest suite | +| `agent/tests_emulator/` | WRITE | Emulator-backed tests: real agent code against a local AWS Emulator. The unit run does not collect them: `mise run test:integration` from the repository root (needs Docker). Rules and known differences from AWS: [scripts/aws-emulator/README.md](../scripts/aws-emulator/README.md). | | `agent/README.md` | WRITE | Env vars, PAT notes | | `cli/src/commands/watch.ts` | WRITE (if event schema changes) | Event consumer | diff --git a/agent/Dockerfile b/agent/Dockerfile index ff66faed0..25758d92c 100644 --- a/agent/Dockerfile +++ b/agent/Dockerfile @@ -1,5 +1,5 @@ ARG TARGETPLATFORM=linux/arm64 -ARG GH_VERSION=2.93.0 +ARG GH_VERSION=2.103.3 # Every external image is pinned by DIGEST, not by tag. # @@ -22,7 +22,7 @@ ARG GH_VERSION=2.93.0 FROM --platform=$TARGETPLATFORM jdxcode/mise:latest@sha256:df5adf538c92d86f9807e738c7c7a9b32a1ae06edf441ede141333e3fe6a2cd9 AS mise # Build gh with a patched Go toolchain; upstream packages can lag Go CVE fixes. -FROM --platform=$TARGETPLATFORM golang:1.27.1-bookworm@sha256:648f440f42a0958804efb24df176f806f9d353b41f1c0627f666428e40310f6b AS gh-builder +FROM --platform=$TARGETPLATFORM golang:1.27.4-bookworm@sha256:4fa7c968ba93f1635670522dbb01a2c78150443e1385746924566079f36570ea AS gh-builder ARG GH_VERSION RUN GOPROXY=direct GOBIN=/out go install "github.com/cli/cli/v2/cmd/gh@v${GH_VERSION}" @@ -99,7 +99,9 @@ RUN npm install -g npm@latest && \ # Install uv (fast Python package manager) — pinned by digest, not just version: # a published tag can be re-pushed, and this COPY sits above the dependency sync, # so a silent move here invalidates it. See the digest note at the top of the file. -COPY --from=ghcr.io/astral-sh/uv:0.11.14@sha256:1025398289b62de8269e70c45b91ffa37c373f38118d7da036fb8bb8efc85d97 /uv /usr/local/bin/uv +# Dependabot's docker updates have only ever changed the FROM lines of this file: +# bump this line by hand, to the `uv` version of mise.toml and agent/mise.toml. +COPY --from=ghcr.io/astral-sh/uv:0.13.7@sha256:96f40d3904aad8d0bd010539001d36c8e2188b981e1334471a90c4a1d93bb490 /uv /usr/local/bin/uv # Install Python dependencies via uv. Build context is repo root (set in # ``cdk/src/stacks/agent.ts``) so source paths are prefixed with ``agent/``. diff --git a/agent/README.md b/agent/README.md index 9386a46e7..fbfae525b 100644 --- a/agent/README.md +++ b/agent/README.md @@ -476,6 +476,7 @@ agent/ │ ├── test_pipeline.py Pipeline tests (cedar_policies injection, _resolve_overall_task_status, _chain_prior_agent_error) │ ├── test_shell.py Shell utility tests (slugify, redact_secrets, truncate, format_bytes) │ └── ... +├── tests_emulator/ Emulator-backed tests: real agent code against a local AWS Emulator (`mise run test:integration`; not collected by the unit run) ``` The container **CMD** runs the app under `opentelemetry-instrument` with **uvicorn** using the **asyncio** event loop (not uvloop), avoiding known subprocess issues with uvloop. diff --git a/agent/osv-scanner.toml b/agent/osv-scanner.toml index 2bd540d71..d72edb444 100644 --- a/agent/osv-scanner.toml +++ b/agent/osv-scanner.toml @@ -3,17 +3,7 @@ # the finding is re-reviewed; remove an entry once aws-opentelemetry-distro # allows the fixed OpenTelemetry versions. -[[IgnoredVulns]] -id = "GHSA-xcq7-p3pf-p88h" -ignoreUntil = 2026-11-28 -reason = "opentelemetry-api tracestate parsing DoS (fixed in 1.45.1). aws-opentelemetry-distro pins opentelemetry-api exactly; the latest release (0.21.0) still pins 1.44.0." - -[[IgnoredVulns]] -id = "GHSA-f5m9-jfrj-jjj7" -ignoreUntil = 2026-11-28 -reason = "opentelemetry-propagator-jaeger baggage allocation (fixed in 1.45.0). Pinned exactly by aws-opentelemetry-distro; only affects services that enable the optional Jaeger propagator." - [[IgnoredVulns]] id = "GHSA-mf5v-w3w3-f6cg" -ignoreUntil = 2026-11-28 -reason = "opentelemetry-api denial of service through quadratic-time traceparent parsing (fixed in 1.45.2). aws-opentelemetry-distro pins opentelemetry-api exactly; the latest release (0.22.0) pins 1.45.1, so no release of the distro allows the fix yet." +ignoreUntil = 2026-12-16 +reason = "opentelemetry-api denial of service through quadratic-time traceparent parsing (fixed in 1.45.2). aws-opentelemetry-distro pins opentelemetry-api exactly. On 2026-11-16 its latest release, 0.22.0 (the one locked), pins 1.45.1, so no release of the distro allows the fix yet (aws-observability/aws-otel-python-instrumentation#975 asks for it)." diff --git a/agent/pyproject.toml b/agent/pyproject.toml index beed12af7..c29788ae7 100644 --- a/agent/pyproject.toml +++ b/agent/pyproject.toml @@ -20,7 +20,7 @@ dependencies = [ "requests==2.34.2", #https://pypi.org/project/requests/ "fastapi==0.139.0", #https://pypi.org/project/fastapi/ "uvicorn==0.50.0", #https://pypi.org/project/uvicorn/ - "aws-opentelemetry-distro==0.18.0", #https://pypi.org/project/aws-opentelemetry-distro/ + "aws-opentelemetry-distro==0.22.0", #https://pypi.org/project/aws-opentelemetry-distro/ (0.22.0 clears GHSA-xcq7-p3pf-p88h and GHSA-f5m9-jfrj-jjj7) "mcp==1.30.0", #https://pypi.org/project/mcp/ (1.30.0 clears GHSA-84m7-p3x7-pcfv) # CEDAR ENGINE PARITY — DO NOT BUMP IN ISOLATION. # cedarpy (Python, agent runtime) and @cedar-policy/cedar-wasm (TypeScript, @@ -166,6 +166,7 @@ ignore = [ max-complexity = 15 [tool.ruff.lint.per-file-ignores] +"tests_emulator/**" = ["S101", "S106", "S108", "PLR2004", "ARG", "TID251"] # emulator-backed tests (mise run test:integration): assert; test tokens; /tmp paths; literal assertions; fixtures taken for their effect; their own boto3 session "src/entrypoint.py" = ["E402"] # re-export shim: importlib.reload() call must precede re-export from-imports # aws_session.py is the one module that builds boto3 clients, resources and sessions: # it attaches the solution User-Agent (#319). TID251 is one rule for the whole diff --git a/agent/src/aws_session.py b/agent/src/aws_session.py index 0f2e8f079..58f9dd548 100644 --- a/agent/src/aws_session.py +++ b/agent/src/aws_session.py @@ -96,8 +96,8 @@ def configure_session(user_id: str, repo: str, task_id: str) -> None: Called once at agent startup from the resolved ``TaskConfig``. Idempotent; safe to call before any tenant-data client is created. Does not itself - assume the role — assumption is deferred until the first client is built so - that a missing SessionRole never delays startup. Values are stored in a + assume the role — the first ``get_session()`` call does, with these tags, + so this must run first. Values are stored in a module global (not ``os.environ``) so tenant identifiers do not leak into spawned subprocesses. """ @@ -183,9 +183,9 @@ def _refresh() -> dict[str, str]: # propagates to every client AND resource derived from this session, so # all tenant-data calls carry it. (#319) botocore_session.user_agent_extra = ua.static_user_agent_extra() - # Deferred: the first assume_role happens on first credential use, not now, - # so a transient STS hiccup at startup doesn't crash the agent before it - # has even begun. + # No credentials yet: get_session() resolves them once, right after this + # returns, so a role that cannot be assumed fails closed there instead of + # on every later tenant-data call. botocore re-assumes before expiry. botocore_session._credentials = DeferredRefreshableCredentials( method="sts-assume-role-session-tags", refresh_using=_refresh, @@ -216,7 +216,13 @@ def get_session() -> Any: # reach every tenant's data (that is exactly what this control # prevents). try: - _session = _build_scoped_session(role_arn) + session = _build_scoped_session(role_arn) + # Assume the role now. Left to botocore it happens on the first + # signed request, where an STS refusal is one more error behind + # a best-effort wrapper and the task carries on. Cache nothing + # until it succeeded. + session.get_credentials().get_frozen_credentials() + _session = session _scoped = True except Exception as exc: from shell import log_error_cw diff --git a/agent/src/task_state.py b/agent/src/task_state.py index 5b3c5b2a4..b6ae2038f 100644 --- a/agent/src/task_state.py +++ b/agent/src/task_state.py @@ -189,9 +189,11 @@ def write_running(task_id: str) -> None: Updates ``status_created_at`` alongside ``status`` so the ``UserStatusIndex`` GSI sort key reflects the current status. Writers that transition the task (``create-task-core``, ``cancel-task``, - ``reconcile-stranded-tasks``) all rewrite this field; keeping Python - in sync is required for ``bga list`` to return tasks in the expected - order. + ``reconcile-stranded-tasks``) all rewrite this field, and Python must + too. Its readers take the prefix for the current status (the + queue-position lookup in ``get-task``) and the timestamp for when that + status was entered (the stranded-task sweep in + ``reconcile-stranded-tasks`` and ``bgagent ops stuck-tasks``). """ try: table = _get_table() @@ -703,7 +705,8 @@ def transact_write_approval_request( "TableName": task_table, "Key": {"task_id": {"S": task_id}}, "UpdateExpression": ( - "SET #s = :awaiting, awaiting_approval_request_id = :rid" + "SET #s = :awaiting, awaiting_approval_request_id = :rid, " + "status_created_at = :sca" ), "ConditionExpression": "#s = :running", "ExpressionAttributeNames": {"#s": "status"}, @@ -711,6 +714,7 @@ def transact_write_approval_request( ":awaiting": {"S": _STATUS_AWAITING_APPROVAL}, ":running": {"S": _STATUS_RUNNING}, ":rid": {"S": request_id}, + ":sca": {"S": f"{_STATUS_AWAITING_APPROVAL}#{_now_iso()}"}, }, } }, @@ -759,13 +763,15 @@ def transact_resume_from_approval( "TableName": task_table, "Key": {"task_id": {"S": task_id}}, "UpdateExpression": ( - "SET #s = :running REMOVE awaiting_approval_request_id" + "SET #s = :running, status_created_at = :sca " + "REMOVE awaiting_approval_request_id" ), "ConditionExpression": ( "#s = :awaiting AND awaiting_approval_request_id = :rid" ), "ExpressionAttributeNames": {"#s": "status"}, "ExpressionAttributeValues": { + ":sca": {"S": f"{_STATUS_RUNNING}#{_now_iso()}"}, ":running": {"S": _STATUS_RUNNING}, ":awaiting": {"S": _STATUS_AWAITING_APPROVAL}, ":rid": {"S": request_id}, diff --git a/agent/src/telemetry.py b/agent/src/telemetry.py index 560daa7b6..a9f16f465 100644 --- a/agent/src/telemetry.py +++ b/agent/src/telemetry.py @@ -167,11 +167,14 @@ def _ensure_client(self): from aws_session import platform_client region = os.environ.get("AWS_REGION") or os.environ.get("AWS_DEFAULT_REGION") - self._client = platform_client("logs", region_name=region) + client = platform_client("logs", region_name=region) log_stream = f"trajectory/{self._task_id}" - with contextlib.suppress(self._client.exceptions.ResourceAlreadyExistsException): - self._client.create_log_stream(logGroupName=self._log_group, logStreamName=log_stream) + with contextlib.suppress(client.exceptions.ResourceAlreadyExistsException): + client.create_log_stream(logGroupName=self._log_group, logStreamName=log_stream) + # Only now: a client cached before the stream exists is never asked to + # create it again. + self._client = client def _put_event(self, payload: dict) -> None: """Serialize *payload* to JSON, truncate if needed, and write.""" diff --git a/agent/tests/conftest.py b/agent/tests/conftest.py index c1a31b7e5..1a2d3a57e 100644 --- a/agent/tests/conftest.py +++ b/agent/tests/conftest.py @@ -355,3 +355,9 @@ def _clean_env(monkeypatch): from aws_session import reset_session_cache reset_session_cache() + + # The #251 blocker latch is a module-level scalar too: a clone-failure test + # in test_repo.py leaves it set for whichever test runs next. + from hooks import reset_blocker_reason + + reset_blocker_reason() diff --git a/agent/tests/test_aws_session.py b/agent/tests/test_aws_session.py index d058ad0ec..716493c48 100644 --- a/agent/tests/test_aws_session.py +++ b/agent/tests/test_aws_session.py @@ -84,8 +84,8 @@ def test_blank_role_arn_treated_as_unset(self, monkeypatch): # autouse fixture. This file's `_reset` fixture (above) itself does # `monkeypatch.delenv(SESSION_ROLE_ARN_ENV)`, which would MASK whether conftest's # `_clean_env` performs the scrub — a guard placed here passes even if the -# conftest line is deleted. Only a fixture-free module truly -# guards the fix. +# conftest line is deleted. Only a module without an autouse fixture +# of its own truly guards the fix. # --------------------------------------------------------------------------- @@ -94,6 +94,10 @@ def test_blank_role_arn_treated_as_unset(self, monkeypatch): class TestScopedSession: + """A test that sets the session role must script ``assume_role`` (or patch + ``_build_scoped_session``): a bare ``MagicMock`` client sends botocore's + expiry parsing into a loop that never returns.""" + def _arn(self, monkeypatch): monkeypatch.setenv("AWS_REGION", "us-east-1") monkeypatch.setenv(SESSION_ROLE_ARN_ENV, "arn:aws:iam::111122223333:role/abca-session") @@ -183,6 +187,91 @@ def test_build_failure_fails_closed_when_scoping_requested(self, monkeypatch): # The downgrade attempt was surfaced loudly before failing. assert any("SESSION_SCOPING_FAILED" in m for m in logged) + def test_role_that_cannot_be_assumed_fails_closed(self, monkeypatch): + """STS refusing the SessionRole must abort at the first get_session(), + not surface later as per-call errors behind best-effort wrappers, and + must leave nothing cached that a later call could take for unscoped.""" + from botocore.exceptions import ClientError + + from aws_session import SessionScopingError + + self._arn(monkeypatch) + configure_session(user_id="u-1", repo="owner/repo", task_id="t-abc") + sts = MagicMock(name="sts") + sts.assume_role.side_effect = ClientError( + {"Error": {"Code": "AccessDenied", "Message": "not authorized"}}, "AssumeRole" + ) + logged: list[str] = [] + + with ( + patch("boto3.client", return_value=sts), + patch("shell.log_error_cw", side_effect=lambda msg, **kw: logged.append(msg)), + pytest.raises(SessionScopingError), + ): + get_session() + + sts.assume_role.assert_called_once() + assert any("SESSION_SCOPING_FAILED" in m for m in logged) + assert aws_session._session is None + assert aws_session._scoped is None + + def test_role_that_cannot_be_assumed_stops_run_task(self, monkeypatch): + """An STS refusal must stop the task before it writes RUNNING or clones. + What stops it is the is_scoped() call in run_task's scoping log line; + the status and progress writes that follow are best-effort and would + carry on.""" + from botocore.exceptions import ClientError + + from aws_session import SessionScopingError + from pipeline import run_task + + self._arn(monkeypatch) + sts = MagicMock(name="sts") + sts.assume_role.side_effect = ClientError( + {"Error": {"Code": "AccessDenied", "Message": "not authorized"}}, "AssumeRole" + ) + + with ( + patch("boto3.client", return_value=sts), + patch("shell.log_error_cw"), + patch("pipeline.task_state") as task_state, + patch("repo.setup_repo") as setup_repo, + pytest.raises(SessionScopingError), + ): + run_task( + repo_url="owner/repo", + task_description="fix bug", + github_token="ghp_test", + aws_region="us-east-1", + task_id="test-id", + ) + + task_state.write_running.assert_not_called() + setup_repo.assert_not_called() + + def test_assumable_role_is_assumed_once(self, monkeypatch): + """The resolution in get_session() is the one AssumeRole the first + tenant-data call would have made anyway, not an extra one.""" + self._arn(monkeypatch) + configure_session(user_id="u-1", repo="owner/repo", task_id="t-abc") + sts = MagicMock(name="sts") + sts.assume_role.return_value = { + "Credentials": { + "AccessKeyId": "ASIAEXAMPLE", + "SecretAccessKey": "secret", + "SessionToken": "token", + "Expiration": datetime.datetime.now(datetime.UTC) + datetime.timedelta(hours=1), + } + } + + with patch("boto3.client", return_value=sts): + session = get_session() + frozen = session.get_credentials().get_frozen_credentials() + + assert is_scoped() is True + assert frozen.access_key == "ASIAEXAMPLE" + assert sts.assume_role.call_count == 1 + # --------------------------------------------------------------------------- # Refresh callback: re-assumes with session tags before the 1h chaining cap diff --git a/agent/tests/test_conftest_env_scrub.py b/agent/tests/test_conftest_env_scrub.py index 7391e4b6a..7741e246a 100644 --- a/agent/tests/test_conftest_env_scrub.py +++ b/agent/tests/test_conftest_env_scrub.py @@ -1,4 +1,4 @@ -"""Fixture-free regression guard for the ECS test-hang scrub (#615 / #616). +"""Regression guard for the ECS test-hang scrub (#615 / #616), without an autouse fixture. This module deliberately has NO local autouse fixture. It exists to prove that conftest's ``_clean_env`` autouse fixture strips ``AGENT_SESSION_ROLE_ARN`` from @@ -16,8 +16,8 @@ ``monkeypatch.setenv`` inside the test can't be scrubbed by them. Poisoning the process env at import time (before any fixture runs) means the conftest scrub is the only thing that can clear it by the time a test body reads it. Remove the -``AGENT_SESSION_ROLE_ARN`` line from conftest's ``_AGENT_ENV_VARS`` and BOTH tests -below fail — a true bidirectional guard. +``AGENT_SESSION_ROLE_ARN`` line from conftest's ``_AGENT_ENV_VARS`` and the first +two tests below fail — a true bidirectional guard. The bug this guards: with ``AGENT_SESSION_ROLE_ARN`` set, ``aws_session`` resolves a *scoped* session and ``tenant_client`` returns ``session.client(...)``, @@ -29,6 +29,9 @@ import os +import pytest + +import hooks from aws_session import SESSION_ROLE_ARN_ENV, is_scoped # Poison the process env at import time — BEFORE any fixture runs. The conftest @@ -48,3 +51,19 @@ def test_session_resolves_unscoped_when_scrubbed(): # bare get_session() must be unscoped — the path where boto3.client mocks # intercept, so no real S3 call is made and nothing hangs. assert is_scoped() is False + + +@pytest.fixture(scope="module") +def _latched_blocker(): + # The #251 blocker latch, as a clone-failure test in test_repo.py leaves it + # for whichever test runs next. Module scope, not autouse: pytest sets it up + # just before the function-scoped conftest `_clean_env` of the one test that + # requests it, so nothing else can have cleared it when the test body reads it. + hooks._record_blocker_reason("egress_denied", "left over from an earlier test", "github.com") + + +def test_conftest_clears_the_blocker_latch(_latched_blocker): + # Without the reset in conftest's _clean_env this is the leaked + # BLOCKED[egress_denied] reason, and pipeline._resolve_overall_task_status + # would report it for an unrelated task. + assert hooks.last_blocker_reason() is None diff --git a/agent/tests/test_emulator_guard.py b/agent/tests/test_emulator_guard.py new file mode 100644 index 000000000..e235580bb --- /dev/null +++ b/agent/tests/test_emulator_guard.py @@ -0,0 +1,206 @@ +"""Regression guards for the refusals of the emulator suite (``tests_emulator/conftest.py``). + +The emulator tests make real AWS SDK calls. Three things in their conftest stand +between them and a real account: ``_why_not_an_emulator`` (the environment), the +audit hook ``_refuse_non_loopback`` (anything that would leave the machine) and the +``emulator`` fixture, which every test depends on and which fails the test before +anything is created. A guard that stops refusing lets every emulator test pass, so +the refusals are made to happen here. Two of the fixture's are not: SDK clients that +resolve to another endpoint, and an STS answer from another account. Both need more +than a loopback port that nothing listens on. + +That conftest installs its audit hook when it is imported, and an audit hook cannot +be removed again, so it is never imported into this process: every case runs in a +fresh interpreter. Its whole environment is an empty home directory and what the +case names: the shell that started pytest may export a real profile. Nothing here +can leave the machine even if the guard under test is broken: there are no +credentials, the endpoint is a loopback port that nothing listens on, the one other +address is 127.0.0.2, and no resolver is asked about a name (``_NUMERIC_ONLY``). + +No emulator is needed, which is why this is part of the unit suite. The accepting +path is exercised by every ``mise run test:integration``. +""" + +import json +import re +import subprocess +import sys +from pathlib import Path + +AGENT_DIR = Path(__file__).resolve().parent.parent +# What scripts/aws-emulator/emulator.sh sets, and the only AWS variables the guard accepts. +# Nothing listens on port 1. +WRAPPER_ENVIRONMENT = { + "AWS_ENDPOINT_URL": "https://127.0.0.1:1", + "AWS_SHARED_CREDENTIALS_FILE": "/nonexistent/emulator_credentials", + "AWS_CONFIG_FILE": "/nonexistent/config", + "AWS_CA_BUNDLE": "/nonexistent/ca.pem", + "AWS_EC2_METADATA_DISABLED": "true", + "AWS_DISABLE_HOST_PREFIX_INJECTION": "true", + "AWS_REGION": "us-east-1", + "AWS_DEFAULT_REGION": "us-east-1", +} +REFUSED_ENDPOINTS = [ + "http://127.0.0.1:1", # not TLS + "https://localhost:1", # a name, not the address + "https://127.0.0.2:1", # another address + "https://127.0.0.1:1@outside.invalid", # only begins like the emulator's + "https://outside.invalid/https://127.0.0.1:1", # only ends like it +] +REFUSED_STRAYS = [ + "AWS_PROFILE", # a source of credentials + "AWS_ENDPOINT_URL_DYNAMODB", # begins like an accepted name, and sends one service elsewhere + "AWS_SDK_UA_APP_ID", # harmless in itself: whatever the wrapper does not set is refused +] + +# How every child starts: names are resolved numerically only. The audit event the hook +# listens for is raised all the same, but no resolver is asked, whatever the hook does. +_NUMERIC_ONLY = """ +import socket, sys + +_getaddrinfo = socket.getaddrinfo + + +def _numeric_only(host, port, family=0, type=0, proto=0, flags=0): + return _getaddrinfo(host, port, family, type, proto, flags | socket.AI_NUMERICHOST) + + +socket.getaddrinfo = _numeric_only +""" + +_PROBE = """ +import json, os + +import tests_emulator.conftest as guard # the import under test: it installs the audit hook + + +def reason(variables): + for name in [name for name in os.environ if name.startswith("AWS_")]: + del os.environ[name] + os.environ.update(variables) + return guard._why_not_an_emulator() + + +def outcome(attempt): + try: + attempt() + except PermissionError as exc: + return f"refused: {exc}" + except OSError as exc: + return f"not refused ({type(exc).__name__})" + return "not refused" + + +def connect(address): + with socket.socket() as tcp: + tcp.settimeout(1) + tcp.connect(address) + + +OTHER = ("127.0.0.2", 9) +with socket.socket() as listener, socket.socket(type=socket.SOCK_DGRAM) as udp: + listener.bind(("127.0.0.1", 0)) + listener.listen(1) + print(json.dumps({ + "reasons": [reason(variables) for variables in json.loads(sys.argv[1])], + "getaddrinfo": outcome(lambda: socket.getaddrinfo("outside.invalid", 443)), + "gethostbyname": outcome(lambda: socket.gethostbyname(OTHER[0])), + "connect": outcome(lambda: connect(OTHER)), + "sendto": outcome(lambda: udp.sendto(b"x", OTHER)), + "sendmsg": outcome(lambda: udp.sendmsg([b"x"], [], 0, OTHER)), + "loopback": outcome(lambda: connect(listener.getsockname())), + })) +""" + +_PYTEST = """ +import pytest + +sys.exit(pytest.main(sys.argv[1:])) +""" + +# In a child that starts with this, the conftest's call installs no audit hook. +_NO_AUDIT_HOOK = """ +sys.addaudithook = lambda hook: None +""" + + +def _run( + code: str, args: list[str], home: Path, variables: dict[str, str] +) -> subprocess.CompletedProcess[str]: + """Run ``code`` in a fresh interpreter in ``agent/``, with ``home`` and ``variables`` only.""" + return subprocess.run( + [sys.executable, "-c", _NUMERIC_ONLY + code, *args], + cwd=str(AGENT_DIR), + env={"HOME": str(home), **variables}, + capture_output=True, + text=True, + timeout=100, + check=False, + ) + + +def test_the_environment_check_and_the_audit_hook_refuse(tmp_path): + refused = [ + ({}, "(it is '')"), + *(({"AWS_ENDPOINT_URL": url}, f"(it is {url!r})") for url in REFUSED_ENDPOINTS), + *(({**WRAPPER_ENVIRONMENT, name: "x"}, f"environment: {name}") for name in REFUSED_STRAYS), + ] + environments = [WRAPPER_ENVIRONMENT, *(variables for variables, _ in refused)] + + proc = _run(_PROBE, [json.dumps(environments)], tmp_path, {}) + + assert proc.returncode == 0, proc.stderr + seen = json.loads(proc.stdout.splitlines()[-1]) + accepted, *reasons = seen["reasons"] + assert accepted is None, "the wrapper's own environment must be accepted" + for reason, (variables, expected) in zip(reasons, refused, strict=True): + assert expected in (reason or ""), f"must refuse {variables}" + leaves = "must not open a connection that leaves this machine, and this one tried to reach" + assert f"{leaves} 'outside.invalid'" in seen["getaddrinfo"] + for attempt in ("gethostbyname", "connect", "sendto", "sendmsg"): + assert f"{leaves} '127.0.0.2'" in seen[attempt], attempt + # Loopback stays open: that is where the emulator is. + assert seen["loopback"] == "not refused" + + +def test_no_emulator_test_runs_in_a_shell_without_the_emulator_environment(tmp_path): + # As `mise run test:integration` runs the suite; no cache, so that this run leaves no trace. + args = ["--no-cov", "-p", "no:cacheprovider", "-q", "tests_emulator"] + + proc = _run(_PYTEST, args, tmp_path, {}) + + assert proc.returncode == 1, proc.stdout + proc.stderr + assert "must be https://127.0.0.1: (it is '')" in proc.stdout, proc.stdout + # Errors only: no skip path, and no test that gets as far as its body. + summary = proc.stdout.splitlines()[-1] + assert not re.search(r" (passed|skipped|failed)", summary), summary + + +def _run_a_test_that_asks_for_no_fixture(home: Path, code: str) -> subprocess.CompletedProcess[str]: + """Run ``code``, which ends in ``_PYTEST``, on one test that asks for no fixture.""" + (home / "test_asks_for_nothing.py").write_text("def test_asks_for_nothing():\n pass\n") + # That file is outside tests_emulator/, so the conftest is loaded as a plugin, with the + # suite's own settings. --noconftest keeps out a conftest.py that happens to sit above + # the temporary directory. + args = ["-c", "pyproject.toml", "-p", "tests_emulator.conftest", "-p", "no:cacheprovider", "-q"] + # What a stopped emulator leaves behind: its variables, but no files and no listener. + return _run(code, [*args, "--noconftest", str(home)], home, WRAPPER_ENVIRONMENT) + + +def test_a_test_that_asks_for_no_fixture_is_stopped_when_the_emulator_does_not_answer(tmp_path): + proc = _run_a_test_that_asks_for_no_fixture(tmp_path, _PYTEST) + + assert proc.returncode == 1, proc.stdout + proc.stderr + # With the endpoint the conftest filled in: its own source, which pytest prints with an + # error the fixture did not expect, must not pass for the refusal. + assert "https://127.0.0.1:1 is set but did not answer STS" in proc.stdout, proc.stdout + + +def test_a_test_that_asks_for_no_fixture_is_stopped_when_the_audit_hook_is_not_in_force(tmp_path): + proc = _run_a_test_that_asks_for_no_fixture(tmp_path, _NO_AUDIT_HOOK + _PYTEST) + + assert proc.returncode == 1, proc.stdout + proc.stderr + # As a line of its own, which is how pytest reports the refusal: the conftest's source, + # which it prints with an error the fixture did not expect, has the same words. + refusal = "the loopback-only audit hook did not refuse a name lookup" + assert f"\n{refusal}\n" in proc.stdout, proc.stdout diff --git a/agent/tests/test_task_state.py b/agent/tests/test_task_state.py index b0eef03d9..feffb7cb8 100644 --- a/agent/tests/test_task_state.py +++ b/agent/tests/test_task_state.py @@ -176,8 +176,9 @@ def update_item(self, **kwargs): class TestWriteRunningMaintainsStatusCreatedAt: """Regression guard: ``write_running`` must rewrite ``status_created_at`` so the ``UserStatusIndex`` GSI sort key reflects the current status. - Without this, ``bga list`` sorts by the stale SUBMITTED prefix and newly - running / completed / cancelled tasks appear after stale SUBMITTED rows. + Its readers rely on that: the queue-position lookup in ``get-task`` + selects on the prefix, and the stranded-task sweep and + ``bgagent ops stuck-tasks`` age a task by the timestamp. """ def test_writes_status_created_at_with_running_prefix(self, monkeypatch): @@ -251,6 +252,36 @@ def update_item(self, **kwargs): assert sca_ts == completed_at +class TestApprovalTransitionsMaintainStatusCreatedAt: + """The stranded-approval sweep ages a paused task by the timestamp inside + ``status_created_at``. Both approval transitions must rewrite it, or the + sweep's two-hour limit runs from the start of RUNNING.""" + + def test_approval_request_stamps_awaiting_approval( + self, approval_tables_env, approval_row, monkeypatch + ): + monkeypatch.setattr(task_state, "_now_iso", lambda: "2026-11-15T03:30:00Z") + client = MagicMock() + + task_state.transact_write_approval_request("01KTASK", "01KREQ", approval_row, client=client) + + upd = client.transact_write_items.call_args.kwargs["TransactItems"][1]["Update"] + assert "status_created_at = :sca" in upd["UpdateExpression"] + assert upd["ExpressionAttributeValues"][":sca"] == { + "S": "AWAITING_APPROVAL#2026-11-15T03:30:00Z" + } + + def test_resume_stamps_running(self, approval_tables_env, monkeypatch): + monkeypatch.setattr(task_state, "_now_iso", lambda: "2026-11-15T03:35:00Z") + client = MagicMock() + + task_state.transact_resume_from_approval("01KTASK", "01KREQ", client=client) + + upd = client.transact_write_items.call_args.kwargs["TransactItems"][0]["Update"] + assert "status_created_at = :sca" in upd["UpdateExpression"] + assert upd["ExpressionAttributeValues"][":sca"] == {"S": "RUNNING#2026-11-15T03:35:00Z"} + + class TestWriteTerminalTraceS3Uri: """``write_terminal`` persists ``trace_s3_uri`` from the result dict so the ``get-trace-url`` handler (which reads the diff --git a/agent/tests/test_trace_upload.py b/agent/tests/test_trace_upload.py index bbb685942..e69891130 100644 --- a/agent/tests/test_trace_upload.py +++ b/agent/tests/test_trace_upload.py @@ -422,6 +422,32 @@ def test_captures_when_circuit_breaker_open(self): assert len(w._events) == 1 +class TestTrajectoryStreamCreation: + """A CreateLogStream that fails must be tried again on the next write. + A client cached before the stream exists is never asked to create it.""" + + def test_failed_stream_creation_is_retried_on_the_next_write(self, monkeypatch): + monkeypatch.setenv("LOG_GROUP_NAME", "/abca/application") + client = MagicMock() + # contextlib.suppress needs a real exception class here. + client.exceptions.ResourceAlreadyExistsException = type( + "ResourceAlreadyExistsException", (Exception,), {} + ) + client.create_log_stream.side_effect = [ + RuntimeError("still throttled after the SDK's own retries"), + None, + ] + + with patch("boto3.client", return_value=client): + w = _TrajectoryWriter("t-1") + w._put_event({"event": "A"}) # stream creation fails; this event is lost + w._put_event({"event": "B"}) # must create the stream, then write + + assert client.create_log_stream.call_count == 2 + assert client.put_log_events.call_count == 1 + assert (w._failure_count, w._disabled) == (1, False) + + class TestTruncationCallback: """Accumulator cap trips fire a one-shot callback so the pipeline can surface ``trace_truncated`` in diff --git a/agent/tests_emulator/__init__.py b/agent/tests_emulator/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/agent/tests_emulator/conftest.py b/agent/tests_emulator/conftest.py new file mode 100644 index 000000000..8b0aa0042 --- /dev/null +++ b/agent/tests_emulator/conftest.py @@ -0,0 +1,310 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: MIT-0 + +"""Fixtures for tests that run agent code against a local AWS Emulator (ADR-013 Tier 2a). + +Everything under ``tests_emulator/`` makes real AWS SDK calls. They go to an AWS +Emulator (https://github.com/aws/aws-emulator) on this machine, selected by the +environment ``scripts/aws-emulator/emulator.sh run`` builds:: + + AWS_ENDPOINT_URL=https://127.0.0.1: + AWS_SHARED_CREDENTIALS_FILE, AWS_CONFIG_FILE, AWS_CA_BUNDLE (written by the emulator) + NODE_EXTRA_CA_CERTS= (cross-language test only) + +This directory sits beside ``tests/``, not inside it: the unit run collects +``tests/`` only (``testpaths``), and the unit suite's conftest never applies +here. ``mise run test:integration`` runs it; for one file:: + + cd agent && ../scripts/aws-emulator/emulator.sh run uv run pytest --no-cov tests_emulator/ + +There is no skip path. Unless the AWS environment is exactly the emulator's, +every test fails before anything is created: with no endpoint these calls would +go to AWS with whatever credentials the shell holds. The session also refuses to +start unless STS, resolved the way agent code resolves it, reports the +emulator's fixed account id. And nothing in this process may connect anywhere +but loopback (``_refuse_non_loopback``): the environment only says where AWS SDK +calls go, and agent code also calls GitHub, Linear and Jira. + +The emulator keeps state in memory and has no reset call, so isolation comes from +names: one set of tables/bucket/log group per pytest session (unique run id), and +a fresh task id and user id per test. +""" + +from __future__ import annotations + +import os +import re +import socket +import sys +import uuid +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any + +import pytest + +if TYPE_CHECKING: + from task_state import ApprovalRow + +EMULATOR_ACCOUNT_ID = "000000000000" +# An IP address, not ``localhost``: with a host name the JavaScript SDK addresses +# S3 buckets as ``.localhost``, which the emulator's certificate does not cover. +_LOOPBACK_EMULATOR = re.compile(r"https://127\.0\.0\.1:\d+") +# What emulator.sh sets. Anything else in the AWS_* namespace (a profile, keys, a +# per-service endpoint, AWS_IGNORE_CONFIGURED_ENDPOINT_URLS) could send a call +# somewhere other than the emulator, or sign it with real credentials. +_EXPECTED_AWS_ENV = frozenset( + { + "AWS_ENDPOINT_URL", + "AWS_SHARED_CREDENTIALS_FILE", + "AWS_CONFIG_FILE", + "AWS_CA_BUNDLE", + "AWS_EC2_METADATA_DISABLED", + "AWS_DISABLE_HOST_PREFIX_INJECTION", + "AWS_REGION", + "AWS_DEFAULT_REGION", + } +) +_LOOPBACK_HOSTS = frozenset({"127.0.0.1", "localhost", "::1"}) + +_REGION = os.environ.get("AWS_REGION") or os.environ.get("AWS_DEFAULT_REGION") or "us-east-1" + + +def _refuse_non_loopback(event: str, args: tuple[Any, ...]) -> None: + """Audit hook: refuse a connection, datagram or name lookup that would leave this machine. + + It covers this process only; a child process does not inherit an audit hook. + A reverse lookup of an address (gethostbyaddr, getnameinfo) is not covered. + The refusal reaches the caller as an ordinary network error, so a test of + code that swallows network errors has to assert that no request was attempted. + When a test fails here, stub the call that tried to connect. Do not add hosts. + """ + if event in ("socket.connect", "socket.sendto", "socket.sendmsg"): + address = args[1] + host = address[0] if isinstance(address, tuple) else None # a str is a Unix socket path + elif event in ("socket.getaddrinfo", "socket.gethostbyname"): + host = args[0] + else: + return + if isinstance(host, bytes): + host = host.decode("ascii", "replace") + if host is not None and host not in _LOOPBACK_HOSTS: + raise PermissionError( + f"emulator tests must not open a connection that leaves this machine, " + f"and this one tried to reach {host!r}" + ) + + +# An audit hook cannot be removed again. That is fine here: this conftest is only +# loaded by a pytest process that was asked for tests_emulator. +sys.addaudithook(_refuse_non_loopback) + + +def _why_not_an_emulator() -> str | None: + """Reason the AWS environment could reach something other than a local emulator.""" + endpoint = os.environ.get("AWS_ENDPOINT_URL", "") + if not _LOOPBACK_EMULATOR.fullmatch(endpoint): + return ( + f"AWS_ENDPOINT_URL must be https://127.0.0.1: (it is {endpoint!r}); " + "run these tests with `mise run test:integration`" + ) + strays = sorted( + name for name in os.environ if name.startswith("AWS_") and name not in _EXPECTED_AWS_ENV + ) + if strays: + return f"unexpected AWS configuration in the environment: {', '.join(strays)}" + return None + + +@dataclass(frozen=True) +class Emulator: + """A verified emulator plus the resources this pytest session created in it.""" + + endpoint: str + region: str + ca_bundle: str + # Signed with the emulator's own key, which the emulator never denies: the + # tests use it to seed and to read back, independently of the code under test. + session: Any + task_table: str + task_events_table: str + task_approvals_table: str + trace_bucket: str + log_group: str + + def client(self, service_name: str, **kwargs: Any) -> Any: + return self.session.client(service_name, endpoint_url=self.endpoint, **kwargs) + + def table(self, name: str) -> Any: + return self.session.resource("dynamodb", endpoint_url=self.endpoint).Table(name) + + +# Key schemas of the tables these tests exercise. They mirror task-table.ts, +# task-events-table.ts and task-approvals-table.ts under cdk/src/constructs/; the +# agent uses none of their GSIs. +_TABLE_KEYS = { + "task_table": [("task_id", "HASH")], + "task_events_table": [("task_id", "HASH"), ("event_id", "RANGE")], + "task_approvals_table": [("task_id", "HASH"), ("request_id", "RANGE")], +} + + +def _create_tables(ddb: Any, names: dict[str, str]) -> None: + for field, name in names.items(): + keys = _TABLE_KEYS[field] + ddb.create_table( + TableName=name, + BillingMode="PAY_PER_REQUEST", + AttributeDefinitions=[{"AttributeName": k, "AttributeType": "S"} for k, _ in keys], + KeySchema=[{"AttributeName": k, "KeyType": kind} for k, kind in keys], + ) + # The emulator keeps a new table CREATING for three seconds, like AWS does for + # longer. Create them all first so the waits overlap. boto3's default is to + # poll every 20 seconds. + for name in names.values(): + ddb.get_waiter("table_exists").wait( + TableName=name, WaiterConfig={"Delay": 1, "MaxAttempts": 30} + ) + + +@pytest.fixture(scope="session") +def emulator() -> Any: + # Every test depends on this fixture (through ``_isolated_agent_state``), so + # failing here stops the whole run before anything below can reach AWS itself. + reason = _why_not_an_emulator() + if reason: + pytest.fail(reason, pytrace=False) + # The audit hook has to be in force before anything below runs. With it, the + # lookup is refused before a query is sent. + try: + socket.getaddrinfo("loopback-guard-check.invalid", 443) + except OSError as exc: + refused = isinstance(exc, PermissionError) + else: + refused = False + if not refused: + pytest.fail("the loopback-only audit hook did not refuse a name lookup", pytrace=False) + + import boto3 + from botocore.config import Config + from botocore.exceptions import BotoCoreError, ClientError + + endpoint = os.environ["AWS_ENDPOINT_URL"] + run_id = uuid.uuid4().hex[:8] + tables = { + "task_table": f"abca-emu-{run_id}-TaskTable", + "task_events_table": f"abca-emu-{run_id}-TaskEventsTable", + "task_approvals_table": f"abca-emu-{run_id}-TaskApprovalsTable", + } + emu = Emulator( + endpoint=endpoint, + region=_REGION, + ca_bundle=os.environ.get("AWS_CA_BUNDLE", ""), + session=boto3.Session(region_name=_REGION), + trace_bucket=f"abca-emu-{run_id}-traces", + log_group=f"/abca-emu/{run_id}/application", + **tables, + ) + + fail_fast = Config(connect_timeout=3, read_timeout=10, retries={"total_max_attempts": 1}) + # Built with no endpoint argument, the way agent code builds its clients: a + # setting in the shared config file can turn AWS_ENDPOINT_URL off, and this is + # where that shows. + sts = emu.session.client("sts", config=fail_fast) + problem = None + if sts.meta.endpoint_url != endpoint: + problem = f"SDK clients resolve to {sts.meta.endpoint_url}, not to {endpoint}" + else: + try: + account = sts.get_caller_identity()["Account"] + except (BotoCoreError, ClientError) as exc: + problem = f"AWS_ENDPOINT_URL={endpoint} is set but did not answer STS: {exc}" + else: + if account != EMULATOR_ACCOUNT_ID: + problem = ( + f"{endpoint} answered as account {account}, not the emulator's " + f"{EMULATOR_ACCOUNT_ID}; refusing to create test resources there" + ) + if problem: + pytest.fail(problem, pytrace=False) + + ddb, s3, logs = emu.client("dynamodb"), emu.client("s3"), emu.client("logs") + _create_tables(ddb, tables) + s3.create_bucket(Bucket=emu.trace_bucket) + logs.create_log_group(logGroupName=emu.log_group) + + yield emu + + for name in tables.values(): + ddb.delete_table(TableName=name) + for obj in s3.list_objects_v2(Bucket=emu.trace_bucket).get("Contents", []): + s3.delete_object(Bucket=emu.trace_bucket, Key=obj["Key"]) + s3.delete_bucket(Bucket=emu.trace_bucket) + logs.delete_log_group(logGroupName=emu.log_group) + + +def _reset_agent_module_state() -> None: + """Drop what agent modules cache at module level between calls. + + A client or table handle cached by one test would otherwise be reused by the + next one, with the previous test's table names and session. + """ + import aws_session + import progress_writer + import task_state + + aws_session.reset_session_cache() + progress_writer._reset_circuit_breakers() + task_state._table = None + + +@pytest.fixture(autouse=True) +def _isolated_agent_state(emulator: Emulator) -> Any: + """Give each test clean agent module state, and leave none behind.""" + _reset_agent_module_state() + yield + _reset_agent_module_state() + + +@pytest.fixture +def agent_env(emulator: Emulator, monkeypatch: pytest.MonkeyPatch) -> Emulator: + """The environment the stack gives the agent runtime (cdk/src/stacks/agent.ts).""" + monkeypatch.setenv("AWS_REGION", emulator.region) + monkeypatch.setenv("TASK_TABLE_NAME", emulator.task_table) + monkeypatch.setenv("TASK_EVENTS_TABLE_NAME", emulator.task_events_table) + monkeypatch.setenv("TASK_APPROVALS_TABLE_NAME", emulator.task_approvals_table) + monkeypatch.setenv("TRACE_ARTIFACTS_BUCKET_NAME", emulator.trace_bucket) + return emulator + + +def approval_row(task_id: str, request_id: str) -> ApprovalRow: + """A pending approval as the PreToolUse hook records it (design §10.1).""" + return { + "task_id": task_id, + "request_id": request_id, + "tool_name": "Bash", + "tool_input_preview": "git push --force", + "tool_input_sha256": "a" * 64, + "reason": "Soft-deny: force_push_any", + "severity": "high", + "matching_rule_ids": ["force_push_any"], + "status": "PENDING", + "created_at": "2026-05-07T00:00:00Z", + "timeout_s": 300, + "ttl": 1_800_000_000, + "user_id": "u-alice", + "repo": "owner/repo", + } + + +@pytest.fixture +def task_id() -> str: + """A task id shaped like production ones (ULID), unique per test.""" + from progress_writer import _generate_ulid + + return _generate_ulid() + + +@pytest.fixture +def user_id() -> str: + """A platform user id shaped like a Cognito ``sub``, unique per test.""" + return str(uuid.uuid4()) diff --git a/agent/tests_emulator/test_approval_transactions.py b/agent/tests_emulator/test_approval_transactions.py new file mode 100644 index 000000000..e2c75b6e8 --- /dev/null +++ b/agent/tests_emulator/test_approval_transactions.py @@ -0,0 +1,122 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: MIT-0 + +"""The approval-gate writes in ``task_state.py`` against real DynamoDB semantics. + +``tests/test_task_state.py`` hands these functions a MagicMock client, because (as +``_get_ddb_client`` notes) moto did not fully emulate ``TransactWriteItems`` with +conditions across two tables. Here the transactions run: the conditions are +evaluated by the service, a cancelled transaction really leaves nothing behind, +and the cancellation reasons are the ones the SDK reports. +""" + +from __future__ import annotations + +import pytest + +import task_state +from progress_writer import _generate_ulid + +from .conftest import approval_row + + +def _task(task_id: str) -> dict: + record = task_state.get_task(task_id) + assert record is not None + return record + + +@pytest.fixture +def running_task(agent_env, task_id) -> str: + """A task the orchestrator created and the agent already marked RUNNING.""" + agent_env.table(agent_env.task_table).put_item(Item={"task_id": task_id, "status": "RUNNING"}) + return task_id + + +@pytest.fixture +def pending_request(running_task) -> str: + """An approval the agent is waiting on for ``running_task``.""" + request_id = _generate_ulid() + task_state.transact_write_approval_request( + running_task, request_id, approval_row(running_task, request_id) + ) + return request_id + + +class TestApprovalRequest: + def test_pending_row_and_awaiting_status_are_written_together(self, running_task): + request_id = _generate_ulid() + row = approval_row(running_task, request_id) + + task_state.transact_write_approval_request(running_task, request_id, row) + + assert task_state.get_approval_row(running_task, request_id) == row + task = _task(running_task) + assert task["status"] == "AWAITING_APPROVAL" + assert task["awaiting_approval_request_id"] == request_id + # The stranded-approval sweep ages the task from this timestamp. + assert task["status_created_at"].startswith("AWAITING_APPROVAL#") + + def test_cancelled_task_gets_no_approval_row(self, agent_env, running_task): + agent_env.table(agent_env.task_table).put_item( + Item={"task_id": running_task, "status": "CANCELLED"} + ) + request_id = _generate_ulid() + + with pytest.raises(task_state.ApprovalWriteError) as raised: + task_state.transact_write_approval_request( + running_task, request_id, approval_row(running_task, request_id) + ) + + # The Put passed its own condition and was still undone with the Update. + codes = [reason["Code"] for reason in raised.value.cancellation_reasons] + assert codes == ["None", "ConditionalCheckFailed"] + assert task_state.get_approval_row(running_task, request_id) is None + assert _task(running_task)["status"] == "CANCELLED" + + def test_same_request_cannot_be_recorded_twice(self, running_task, pending_request): + with pytest.raises(task_state.ApprovalWriteError) as raised: + task_state.transact_write_approval_request( + running_task, pending_request, approval_row(running_task, pending_request) + ) + + codes = [reason["Code"] for reason in raised.value.cancellation_reasons] + assert codes == ["ConditionalCheckFailed", "ConditionalCheckFailed"] + + +class TestResumeAndTimeout: + def test_resume_returns_the_task_to_running(self, running_task, pending_request): + task_state.transact_resume_from_approval(running_task, pending_request) + + task = _task(running_task) + assert task["status"] == "RUNNING" + assert "awaiting_approval_request_id" not in task + assert task["status_created_at"].startswith("RUNNING#") + + def test_resume_for_a_different_request_is_refused(self, running_task, pending_request): + with pytest.raises(task_state.ApprovalResumeError): + task_state.transact_resume_from_approval(running_task, _generate_ulid()) + + assert _task(running_task)["status"] == "AWAITING_APPROVAL" + + def test_timeout_only_wins_while_the_request_is_still_pending( + self, running_task, pending_request + ): + timed_out = task_state.best_effort_update_approval_status( + running_task, pending_request, "TIMED_OUT" + ) + late_denial = task_state.best_effort_update_approval_status( + running_task, pending_request, "DENIED", reason="too late" + ) + + assert (timed_out, late_denial) == (True, False) + row = task_state.get_approval_row(running_task, pending_request) + assert row is not None + assert row["status"] == "TIMED_OUT" + assert "deny_reason" not in row + + def test_gate_counter_is_created_then_incremented(self, running_task): + assert task_state.increment_approval_gate_count_in_ddb(running_task) is True + assert task_state.increment_approval_gate_count_in_ddb(running_task) is True + + assert _task(running_task)["approval_gate_count"] == 2 diff --git a/agent/tests_emulator/test_cloudwatch_logs.py b/agent/tests_emulator/test_cloudwatch_logs.py new file mode 100644 index 000000000..18f34bf9c --- /dev/null +++ b/agent/tests_emulator/test_cloudwatch_logs.py @@ -0,0 +1,141 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: MIT-0 + +"""The agent's direct CloudWatch Logs writers against a real Logs API. + +Three writers put events into the application log group, each on its own stream +per task: the trajectory (``trajectory/``), the metrics report +(``metrics/``) and fatal errors (``agent_error/``). +""" + +from __future__ import annotations + +import json +import threading + +import pytest + +from shell import log_error_cw +from telemetry import _TrajectoryWriter, print_metrics + + +@pytest.fixture +def log_group(agent_env, monkeypatch) -> str: + monkeypatch.setenv("LOG_GROUP_NAME", agent_env.log_group) + return agent_env.log_group + + +def _messages(emulator, stream: str) -> list[str]: + events = emulator.client("logs").get_log_events( + logGroupName=emulator.log_group, logStreamName=stream, startFromHead=True + )["events"] + return [event["message"] for event in events] + + +class TestTrajectoryStream: + def test_turns_and_decisions_are_written_in_order(self, emulator, log_group, task_id): + writer = _TrajectoryWriter(task_id) + + writer.write_turn( + turn=1, model="claude", thinking="", text="hi", tool_calls=[], tool_results=[] + ) + writer.write_policy_decision("Bash", allowed=False, reason="hard deny", duration_ms=0.4) + + turn, decision = (json.loads(m) for m in _messages(emulator, f"trajectory/{task_id}")) + assert (turn["event"], turn["task_id"], turn["turn"]) == ("TRAJECTORY_TURN", task_id, 1) + assert decision == { + "event": "POLICY_DECISION", + "task_id": task_id, + "tool_name": "Bash", + "allowed": False, + "reason": "hard deny", + "duration_ms": 0.4, + } + + def test_second_writer_for_a_task_appends_to_the_existing_stream( + self, emulator, log_group, task_id + ): + _TrajectoryWriter(task_id).write_policy_decision("Read", True, "permit", 0.1) + second = _TrajectoryWriter(task_id) + + # The stream already exists: CreateLogStream answers + # ResourceAlreadyExistsException, which the writer must swallow. + second.write_policy_decision("Edit", True, "permit", 0.1) + + assert second._failure_count == 0 + tools = [json.loads(m)["tool_name"] for m in _messages(emulator, f"trajectory/{task_id}")] + assert tools == ["Read", "Edit"] + + def test_missing_log_group_disables_cloudwatch_but_not_the_trace_accumulator( + self, agent_env, task_id, monkeypatch, capsys + ): + monkeypatch.setenv("LOG_GROUP_NAME", f"{agent_env.log_group}-absent") + writer = _TrajectoryWriter(task_id, accumulate=True) + + for _ in range(4): + writer.write_policy_decision("Bash", True, "permit", 0.1) + + assert writer._disabled is True + assert writer._failure_count == writer._MAX_FAILURES + assert "ResourceNotFoundException" in capsys.readouterr().out + assert len(writer._events) == 4 + + def test_stream_is_created_once_the_log_group_exists( + self, emulator, agent_env, task_id, monkeypatch + ): + group = f"{agent_env.log_group}-late" + monkeypatch.setenv("LOG_GROUP_NAME", group) + logs = emulator.client("logs") + writer = _TrajectoryWriter(task_id) + + # No log group yet: CreateLogStream is refused and this event is lost. + writer.write_policy_decision("Read", True, "permit", 0.1) + logs.create_log_group(logGroupName=group) + try: + writer.write_policy_decision("Edit", True, "permit", 0.1) + streams = logs.describe_log_streams(logGroupName=group)["logStreams"] + events = [ + event + for stream in streams + for event in logs.get_log_events( + logGroupName=group, + logStreamName=stream["logStreamName"], + startFromHead=True, + )["events"] + ] + finally: + logs.delete_log_group(logGroupName=group) + + assert [s["logStreamName"] for s in streams] == [f"trajectory/{task_id}"] + assert [json.loads(e["message"])["tool_name"] for e in events] == ["Edit"] + assert (writer._failure_count, writer._disabled) == (1, False) + + +class TestMetricsAndErrorStreams: + def test_metrics_report_is_written_with_native_types(self, emulator, log_group, task_id): + print_metrics( + {"task_id": task_id, "status": "success", "turns": 3, "cost_usd": 0.25, "error": None} + ) + + (report,) = _messages(emulator, f"metrics/{task_id}") + assert json.loads(report) == { + "event": "METRICS_REPORT", + "task_id": task_id, + "status": "success", + "turns": 3, + "cost_usd": 0.25, + "error": None, + } + + def test_fatal_error_is_mirrored_to_the_application_log_group( + self, emulator, log_group, task_id + ): + log_error_cw("Agent failed: missing built-in hard-deny policies", task_id=task_id) + # The mirror runs on a daemon thread so it cannot block the failing path. + for thread in threading.enumerate(): + if thread.name == "agent-error-cw-write": + thread.join(timeout=30) + + assert _messages(emulator, f"agent_error/{task_id}") == [ + "[agent/error] Agent failed: missing built-in hard-deny policies" + ] diff --git a/agent/tests_emulator/test_progress_events.py b/agent/tests_emulator/test_progress_events.py new file mode 100644 index 000000000..aa29143d8 --- /dev/null +++ b/agent/tests_emulator/test_progress_events.py @@ -0,0 +1,128 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: MIT-0 + +"""``_ProgressWriter`` against a real DynamoDB API (the emulator's). + +``tests/test_progress_writer.py`` drives the writer with a MagicMock table and +hand-built ``ClientError``s. Here the same code talks to DynamoDB semantics: the +item has to survive the SDK's type marshalling and the service's validation, and +the errors the circuit breaker classifies are the ones the service really sends. +""" + +from __future__ import annotations + +import time +from decimal import Decimal + +from boto3.dynamodb.conditions import Key + +from progress_writer import _TTL_SECONDS, _ProgressWriter + + +def _events(emulator, task_id: str) -> list[dict]: + """All events for a task, oldest first. + + Ordered by the microsecond ``timestamp`` rather than by the table's sort key: + ``event_id`` only orders events to the millisecond, so two written within one + millisecond can come back from DynamoDB in either order. + """ + response = emulator.table(emulator.task_events_table).query( + KeyConditionExpression=Key("task_id").eq(task_id), ConsistentRead=True + ) + return sorted(response["Items"], key=lambda event: event["timestamp"]) + + +class TestProgressEventsReachDynamoDB: + def test_typed_events_round_trip_with_the_documented_item_shape(self, agent_env, task_id): + writer = _ProgressWriter(task_id, user_id="user-1", repo="owner/repo") + + writer.write_agent_milestone("clone_complete", "Repository cloned") + writer.write_agent_turn( + turn=1, model="claude", thinking="", text="Reading files", tool_calls_count=2 + ) + writer.write_agent_cost_update(cost_usd=0.1234, input_tokens=10, output_tokens=20, turn=1) + writer.write_approval_pre_approvals_loaded(count=2, scopes=["tool_type:Bash", "rule:r1"]) + + events = _events(agent_env, task_id) + assert [e["event_type"] for e in events] == [ + "agent_milestone", + "agent_turn", + "agent_cost_update", + "agent_milestone", + ] + milestone, turn, cost, approvals = events + assert milestone["metadata"] == { + "milestone": "clone_complete", + "details": "Repository cloned", + } + # Empty strings and nested lists are stored as given; numbers come back as + # DynamoDB numbers (the writer converts floats to Decimal for the SDK). + assert turn["metadata"]["thinking_preview"] == "" + assert turn["metadata"]["tool_calls_count"] == 2 + assert cost["metadata"]["cost_usd"] == Decimal("0.1234") + assert approvals["metadata"]["scopes"] == ["tool_type:Bash", "rule:r1"] + for event in events: + assert event["task_id"] == task_id + assert event["user_id"] == "user-1" + assert event["repo"] == "owner/repo" + assert len(event["event_id"]) == 26 + assert abs(int(event["ttl"]) - (time.time() + _TTL_SECONDS)) < 60 + # The sort key's time prefix follows emission order, which is what lets + # `bgagent watch` page through the table by event_id. + time_prefixes = [event["event_id"][:10] for event in events] + assert time_prefixes == sorted(time_prefixes) + + def test_unknown_cost_is_stored_as_null(self, agent_env, task_id): + _ProgressWriter(task_id).write_agent_cost_update( + cost_usd=None, input_tokens=1, output_tokens=2, turn=1 + ) + + (event,) = _events(agent_env, task_id) + assert event["metadata"]["cost_usd"] is None + assert "user_id" not in event + assert "repo" not in event + + def test_runner_and_pipeline_writers_share_one_stream(self, agent_env, task_id): + runner_writer = _ProgressWriter(task_id) + pipeline_writer = _ProgressWriter(task_id, trace=True) + + runner_writer.write_agent_tool_call("Bash", "ls", turn=1) + pipeline_writer.write_agent_milestone("pr_created", "x" * 5000) + + tool_call, milestone = _events(agent_env, task_id) + assert tool_call["metadata"]["tool_name"] == "Bash" + # trace=True raises the preview cap from 200 chars to 4 KB. + assert milestone["metadata"]["details"] == "x" * 4096 + "..." + + +class TestProgressWriterOnRealServiceErrors: + def test_item_over_400kb_is_dropped_without_tripping_the_breaker( + self, agent_env, task_id, capsys + ): + writer = _ProgressWriter(task_id) + + writer.write_approval_pre_approvals_loaded(count=500, scopes=["s" * 1000] * 500) + writer.write_agent_milestone("after_oversized", "still alive") + + assert "dropped event due to permanent DDB error" in capsys.readouterr().out + assert writer._disabled is False + assert writer._failure_count == 0 + assert [e["metadata"]["milestone"] for e in _events(agent_env, task_id)] == [ + "after_oversized" + ] + + def test_missing_table_opens_the_breaker_on_the_first_write( + self, agent_env, task_id, monkeypatch, capsys + ): + monkeypatch.setenv("TASK_EVENTS_TABLE_NAME", f"{agent_env.task_events_table}-absent") + writer = _ProgressWriter(task_id) + + writer.write_agent_milestone("first", "") + writer.write_agent_milestone("second", "") + + # One line for the first write; the second never reaches DynamoDB. + out = capsys.readouterr().out + assert out.count("disabling progress writer") == 1 + assert "ResourceNotFoundException" in out + assert writer._disabled is True + assert _ProgressWriter(task_id)._disabled is True diff --git a/agent/tests_emulator/test_scoped_session.py b/agent/tests_emulator/test_scoped_session.py new file mode 100644 index 000000000..5e7c8ca9d --- /dev/null +++ b/agent/tests_emulator/test_scoped_session.py @@ -0,0 +1,237 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: MIT-0 + +"""The per-task scoped session (``aws_session.py``) against real STS and IAM APIs. + +``tests/test_aws_session.py`` checks the arguments handed to a mocked +``assume_role``. Here the agent really assumes a SessionRole with its +``{user_id, repo, task_id}`` session tags and uses the credentials it gets back. + +What the emulator lets these tests establish, and what it does not: + +* STS validates the request (role exists, trust policy allows ``sts:AssumeRole`` + and ``sts:TagSession``, tag shape) and returns credentials that DynamoDB and S3 + accept. That part behaves like AWS. +* For a role created in the emulator, DynamoDB and S3 also evaluate the role's + identity policy, including ``dynamodb:LeadingKeys`` and + ``${aws:PrincipalTag/...}`` — so a cross-tenant call is denied here. AWS states + that this evaluation is not the same as the real one. The denial tests below + are therefore a tripwire for the agent's wiring (tags reach STS, tenant data + goes through the scoped session), never evidence that the policy is safe. +* The role policy below is a hand-written mirror of + ``cdk/src/constructs/agent-session-role.ts``, not the deployed policy. +""" + +from __future__ import annotations + +import json +import uuid + +import pytest +from boto3.dynamodb.conditions import Key +from botocore.exceptions import ClientError + +import task_state +from aws_session import SessionScopingError, configure_session, is_scoped, tenant_client +from progress_writer import _generate_ulid, _ProgressWriter +from telemetry import upload_trace_to_s3 + +from .conftest import EMULATOR_ACCOUNT_ID, approval_row + +_ASSUMABLE_BY_ACCOUNT = {"AWS": f"arn:aws:iam::{EMULATOR_ACCOUNT_ID}:root"} + +# AgentSessionRole.DDB_ITEM_ACTIONS (Scan is deliberately absent). +_DDB_ITEM_ACTIONS = [ + "dynamodb:GetItem", + "dynamodb:BatchGetItem", + "dynamodb:Query", + "dynamodb:PutItem", + "dynamodb:UpdateItem", + "dynamodb:DeleteItem", + "dynamodb:BatchWriteItem", + "dynamodb:ConditionCheckItem", +] + + +def _trust_policy(actions: list[str]) -> str: + statement = {"Effect": "Allow", "Principal": _ASSUMABLE_BY_ACCOUNT, "Action": actions} + return json.dumps({"Version": "2012-10-17", "Statement": [statement]}) + + +def _session_role_policy(emulator) -> str: + table_arn = f"arn:aws:dynamodb:{emulator.region}:{EMULATOR_ACCOUNT_ID}:table" + bucket_arn = f"arn:aws:s3:::{emulator.trace_bucket}" + statements = [ + { + "Effect": "Allow", + "Action": _DDB_ITEM_ACTIONS, + "Resource": f"{table_arn}/{table}", + "Condition": { + "ForAllValues:StringEquals": { + "dynamodb:LeadingKeys": ["${aws:PrincipalTag/task_id}"] + } + }, + } + for table in ( + emulator.task_table, + emulator.task_events_table, + emulator.task_approvals_table, + ) + ] + statements += [ + { + "Effect": "Allow", + "Action": "s3:PutObject", + "Resource": f"{bucket_arn}/{prefix}/${{aws:PrincipalTag/{tag}}}/*", + } + for prefix, tag in (("traces", "user_id"), ("artifacts", "task_id")) + ] + return json.dumps({"Version": "2012-10-17", "Statement": statements}) + + +@pytest.fixture(scope="module") +def roles(emulator): + """A SessionRole like the deployed one, and one whose trust omits TagSession.""" + iam = emulator.client("iam") + suffix = uuid.uuid4().hex[:8] + session_role = f"abca-emu-{suffix}-SessionRole" + untaggable_role = f"abca-emu-{suffix}-NoTagSession" + + arns = { + "session": iam.create_role( + RoleName=session_role, + AssumeRolePolicyDocument=_trust_policy(["sts:AssumeRole", "sts:TagSession"]), + )["Role"]["Arn"], + "untaggable": iam.create_role( + RoleName=untaggable_role, + AssumeRolePolicyDocument=_trust_policy(["sts:AssumeRole"]), + )["Role"]["Arn"], + "absent": f"arn:aws:iam::{EMULATOR_ACCOUNT_ID}:role/abca-emu-{suffix}-Absent", + } + iam.put_role_policy( + RoleName=session_role, PolicyName="tenant", PolicyDocument=_session_role_policy(emulator) + ) + + yield arns + + iam.delete_role_policy(RoleName=session_role, PolicyName="tenant") + iam.delete_role(RoleName=session_role) + iam.delete_role(RoleName=untaggable_role) + + +@pytest.fixture +def scoped(agent_env, roles, monkeypatch, task_id, user_id): + """The agent as the pipeline leaves it: SessionRole set, session tags configured.""" + monkeypatch.setenv("AGENT_SESSION_ROLE_ARN", roles["session"]) + configure_session(user_id=user_id, repo="owner/repo", task_id=task_id) + return agent_env + + +def _events(emulator, task_id: str) -> list[dict]: + return emulator.table(emulator.task_events_table).query( + KeyConditionExpression=Key("task_id").eq(task_id), ConsistentRead=True + )["Items"] + + +class TestScopedCredentials: + def test_tenant_clients_act_as_the_session_role_named_for_the_task( + self, scoped, roles, task_id + ): + identity = tenant_client("sts").get_caller_identity() + + assert is_scoped() is True + role_name = roles["session"].rsplit("/", 1)[1] + assert identity["Arn"] == ( + f"arn:aws:sts::{EMULATOR_ACCOUNT_ID}:assumed-role/{role_name}/abca-{task_id}" + ) + + def test_agent_writes_its_own_events_trace_and_task_record(self, scoped, task_id, user_id): + scoped.table(scoped.task_table).put_item( + Item={"task_id": task_id, "user_id": user_id, "status": "RUNNING"} + ) + + _ProgressWriter(task_id, user_id=user_id).write_agent_milestone("clone_complete", "") + uri = upload_trace_to_s3(task_id=task_id, user_id=user_id, body=b"\x1f\x8b trace") + task_state.write_terminal(task_id, "COMPLETED", {"trace_s3_uri": uri}) + + assert [e["metadata"]["milestone"] for e in _events(scoped, task_id)] == ["clone_complete"] + assert uri == f"s3://{scoped.trace_bucket}/traces/{user_id}/{task_id}.jsonl.gz" + record = task_state.get_task(task_id) + assert record is not None + assert (record["status"], record["trace_s3_uri"]) == ("COMPLETED", uri) + + def test_approval_gate_transaction_spans_both_of_the_tasks_tables(self, scoped, task_id): + scoped.table(scoped.task_table).put_item(Item={"task_id": task_id, "status": "RUNNING"}) + request_id = _generate_ulid() + row = approval_row(task_id, request_id) + + task_state.transact_write_approval_request(task_id, request_id, row) + task_state.transact_resume_from_approval(task_id, request_id) + + assert task_state.get_approval_row(task_id, request_id) == row + record = task_state.get_task(task_id) + assert record is not None + assert record["status"] == "RUNNING" + + +class TestOtherTenantsDataIsOutOfReach: + """Tripwire only — see the module docstring for what a denial here means.""" + + def test_event_for_another_task_is_denied_and_stops_the_writer(self, scoped, capsys): + other_task = _generate_ulid() + writer = _ProgressWriter(other_task) + + writer.write_agent_milestone("clone_complete", "") + + assert "AccessDeniedException" in capsys.readouterr().out + assert writer._disabled is True + assert _events(scoped, other_task) == [] + + def test_trace_under_another_users_prefix_is_denied(self, scoped, task_id, capsys): + other_user = str(uuid.uuid4()) + + uri = upload_trace_to_s3(task_id=task_id, user_id=other_user, body=b"\x1f\x8b trace") + + assert uri is None + assert "AccessDenied" in capsys.readouterr().out + listing = scoped.client("s3").list_objects_v2( + Bucket=scoped.trace_bucket, Prefix=f"traces/{other_user}/" + ) + assert listing["KeyCount"] == 0 + + def test_another_tasks_record_cannot_be_read(self, scoped): + other_task = _generate_ulid() + scoped.table(scoped.task_table).put_item(Item={"task_id": other_task, "status": "RUNNING"}) + + with pytest.raises(task_state.TaskFetchError, match="AccessDeniedException"): + task_state.get_task(other_task) + + +@pytest.mark.parametrize("role", ["absent", "untaggable"]) +class TestSessionRoleThatCannotBeAssumed: + @pytest.fixture + def unassumable(self, agent_env, roles, role, monkeypatch, task_id, user_id): + monkeypatch.setenv("AGENT_SESSION_ROLE_ARN", roles[role]) + configure_session(user_id=user_id, repo="owner/repo", task_id=task_id) + return agent_env + + def test_scoping_fails_closed_and_nothing_reaches_tenant_data( + self, unassumable, task_id, user_id + ): + # What pipeline.run_task calls first, before any work starts. + with pytest.raises(SessionScopingError) as raised: + is_scoped() + # Every later tenant-data call is refused the same way; none runs unscoped. + with pytest.raises(SessionScopingError): + tenant_client("sts") + uri = upload_trace_to_s3(task_id=task_id, user_id=user_id, body=b"\x1f\x8b trace") + + cause = raised.value.__cause__ + assert isinstance(cause, ClientError) + assert cause.operation_name == "AssumeRole" + assert cause.response["Error"]["Code"] == "AccessDenied" + assert uri is None + listing = unassumable.client("s3").list_objects_v2( + Bucket=unassumable.trace_bucket, Prefix=f"traces/{user_id}/" + ) + assert listing["KeyCount"] == 0 diff --git a/agent/tests_emulator/test_secrets.py b/agent/tests_emulator/test_secrets.py new file mode 100644 index 000000000..a6877e6ee --- /dev/null +++ b/agent/tests_emulator/test_secrets.py @@ -0,0 +1,118 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: MIT-0 + +"""Credential lookups in ``config.py`` against a real Secrets Manager API.""" + +from __future__ import annotations + +import json +import os +import uuid +from datetime import UTC, datetime, timedelta + +import pytest +from botocore.exceptions import ClientError + +from config import resolve_github_token, resolve_linear_api_token + + +@pytest.fixture +def create_secret(emulator): + """Create secrets in the emulator; delete them when the test ends.""" + client = emulator.client("secretsmanager") + arns: list[str] = [] + + def _create(value: str) -> str: + arn = client.create_secret(Name=f"abca-emu/{uuid.uuid4().hex}", SecretString=value)["ARN"] + arns.append(arn) + return arn + + yield _create + + for arn in arns: + client.delete_secret(SecretId=arn, ForceDeleteWithoutRecovery=True) + + +@pytest.fixture +def token_env(agent_env, monkeypatch): + """Both resolvers cache the token in ``os.environ``; undo that after the test. + + They assign ``os.environ[...]`` directly, which pytest only reverts for + variables ``monkeypatch`` already owns — so claim them here, set to empty + (which the resolvers treat as "not cached"). + """ + monkeypatch.setenv("GITHUB_TOKEN", "") + monkeypatch.setenv("LINEAR_API_TOKEN", "") + monkeypatch.delenv("LINEAR_VAULT_ENABLED", raising=False) + monkeypatch.delenv("LINEAR_OAUTH_SECRET_ARN", raising=False) + + +class TestGithubTokenFromSecretsManager: + def test_token_is_read_by_arn_and_cached_for_git(self, token_env, create_secret, monkeypatch): + monkeypatch.setenv("GITHUB_TOKEN_SECRET_ARN", create_secret("emulator-github-token")) + + assert resolve_github_token() == "emulator-github-token" + assert os.environ["GITHUB_TOKEN"] == "emulator-github-token" # noqa: S105 + + def test_cached_token_is_returned_without_another_lookup( + self, token_env, create_secret, monkeypatch, emulator + ): + arn = create_secret("first-value") + monkeypatch.setenv("GITHUB_TOKEN_SECRET_ARN", arn) + resolve_github_token() + emulator.client("secretsmanager").put_secret_value(SecretId=arn, SecretString="rotated") + + assert resolve_github_token() == "first-value" + + def test_missing_secret_raises_the_service_error(self, token_env, monkeypatch): + monkeypatch.setenv( + "GITHUB_TOKEN_SECRET_ARN", + f"arn:aws:secretsmanager:us-east-1:000000000000:secret:absent-{uuid.uuid4().hex}", + ) + + with pytest.raises(ClientError) as raised: + resolve_github_token() + + assert raised.value.response["Error"]["Code"] == "ResourceNotFoundException" + + +class TestLinearTokenFromSecretsManager: + @staticmethod + def _oauth_secret(**overrides) -> str: + # expires_at is far enough ahead that the resolver never attempts a + # refresh, which would call Linear's real OAuth endpoint. + expires_at = (datetime.now(UTC) + timedelta(days=1)).isoformat().replace("+00:00", "Z") + return json.dumps( + { + "access_token": "emulator-linear-access", + "refresh_token": "emulator-linear-refresh", + "expires_at": expires_at, + "scope": "read,write", + **overrides, + } + ) + + def test_unexpired_token_is_returned_from_the_workspace_secret(self, token_env, create_secret): + arn = create_secret(self._oauth_secret()) + + resolved = resolve_linear_api_token({"linear_oauth_secret_arn": arn}) + + assert resolved == "emulator-linear-access" + assert os.environ["LINEAR_API_TOKEN"] == "emulator-linear-access" # noqa: S105 + + # ``shell.log`` writes to fd 1 directly, so these two read it with ``capfd``. + def test_secret_that_is_not_json_yields_no_token(self, token_env, create_secret, capfd): + arn = create_secret("not json") + + assert resolve_linear_api_token({"linear_oauth_secret_arn": arn}) == "" + assert "is not valid JSON" in capfd.readouterr().out + + def test_missing_secret_is_logged_as_an_error_and_yields_no_token(self, token_env, capfd): + arn = f"arn:aws:secretsmanager:us-east-1:000000000000:secret:absent-{uuid.uuid4().hex}" + + assert resolve_linear_api_token({"linear_oauth_secret_arn": arn}) == "" + # The resolver escalates to ERROR only for the two "will not self-heal" + # codes, matching on the code string the service returns. + assert "ERROR resolve_linear_api_token failed: ResourceNotFoundException" in ( + capfd.readouterr().out + ) diff --git a/agent/tests_emulator/test_trace_round_trip.py b/agent/tests_emulator/test_trace_round_trip.py new file mode 100644 index 000000000..909c66be8 --- /dev/null +++ b/agent/tests_emulator/test_trace_round_trip.py @@ -0,0 +1,208 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: MIT-0 + +"""The ``--trace`` round trip across all three languages' halves (issue #61). + + agent (Python) writes the gzipped JSONL trace to S3 and records its + URI on the task telemetry / pipeline / task_state + API handler (TS) checks ownership, HEADs the object, presigns a GET + cdk/src/handlers/get-trace-url.ts + CLI (TS) asks the API, downloads through the URL, gunzips + cli/src/commands/trace.ts + +``test_trace_key_contract.py`` pins the key shape by reading the TypeScript as +text. Here the three halves run for real against one emulator: the Python side in +this process, the TypeScript sides in Node from source (``tsx``, a dev dependency +of ``@abca/cdk``). The only stand-ins are for what sits between them in a +deployment: ``cdk/test/emulator/trace-api-shim.ts`` for API Gateway and its +Cognito authorizer (so the CLI runs in API-key mode and its login path is not +exercised), and a ``put_item`` for the task record the orchestrator would have +created. +""" + +from __future__ import annotations + +import gzip +import json +import os +import subprocess +import threading +from pathlib import Path + +import pytest +import requests + +import task_state +from models import TaskConfig +from pipeline import _maybe_upload_trace +from progress_writer import _ProgressWriter +from telemetry import _TrajectoryWriter + +_REPO_ROOT = Path(__file__).resolve().parents[2] +_TSX = _REPO_ROOT / "node_modules" / ".bin" / "tsx" +_API_SHIM = _REPO_ROOT / "cdk" / "test" / "emulator" / "trace-api-shim.ts" +_CLI = _REPO_ROOT / "cli" / "src" / "bin" / "bgagent.ts" + + +@pytest.fixture(scope="module") +def trace_api(emulator): + """Base URL of the real get-trace-url handler, served over HTTP for this module.""" + if not _TSX.exists(): + pytest.fail("Node dependencies are not installed (run `mise run install`)", pytrace=False) + env = { + **os.environ, + "AWS_REGION": emulator.region, + "NODE_EXTRA_CA_CERTS": emulator.ca_bundle, + "TASK_TABLE_NAME": emulator.task_table, + "TRACE_ARTIFACTS_BUCKET_NAME": emulator.trace_bucket, + } + shim = subprocess.Popen([_TSX, _API_SHIM], env=env, stdout=subprocess.PIPE, text=True) + assert shim.stdout is not None + first_line = shim.stdout.readline() + try: + port = json.loads(first_line)["port"] + except (ValueError, KeyError, TypeError): + shim.kill() + shim.wait(timeout=30) + shim.stdout.close() + pytest.fail(f"trace API shim did not start: {first_line!r}") + # The handler logs to stdout; keep reading so a full pipe can never stall it. + drain = threading.Thread(target=shim.stdout.read, daemon=True) + drain.start() + + yield f"http://127.0.0.1:{port}" + + shim.terminate() + shim.wait(timeout=30) + drain.join(timeout=30) + shim.stdout.close() + + +@pytest.fixture +def bgagent(trace_api, emulator, tmp_path): + """Run the real CLI as ``user`` against the handler; returns the finished process.""" + config_dir = tmp_path / "bgagent-config" + config_dir.mkdir() + (config_dir / "config.json").write_text(json.dumps({"api_url": trace_api})) + + def _run(user: str, *args: str) -> subprocess.CompletedProcess[bytes]: + env = { + **os.environ, + "BGAGENT_CONFIG_DIR": str(config_dir), + # API-key mode skips the Cognito login; the shim reads it as the caller. + "BGAGENT_API_KEY": user, + "NODE_EXTRA_CA_CERTS": emulator.ca_bundle, + } + return subprocess.run( + [_TSX, _CLI, *args], env=env, capture_output=True, timeout=90, check=False + ) + + return _run + + +@pytest.fixture +def traced_task(agent_env, task_id, user_id) -> bytes: + """A finished ``--trace`` task, written by the agent's own code. Returns the artifact.""" + agent_env.table(agent_env.task_table).put_item( + Item={"task_id": task_id, "user_id": user_id, "status": "RUNNING"} + ) + trajectory = _TrajectoryWriter(task_id, accumulate=True) + trajectory.write_turn( + turn=1, + model="claude", + thinking="plan", + text="Reading the repo — ünïcödé", + tool_calls=[{"name": "Bash", "input": {"command": "ls"}}], + tool_results=[{"tool_use_id": "t1", "content": "README.md\n" * 200, "is_error": False}], + ) + trajectory.write_policy_decision("Bash", allowed=True, reason="permit", duration_ms=1.5) + artifact = trajectory.dump_gzipped_jsonl() + assert artifact is not None + + config = TaskConfig( + repo_url="owner/repo", + aws_region=agent_env.region, + task_id=task_id, + task_description="Do a thing", + user_id=user_id, + trace=True, + ) + uri = _maybe_upload_trace(config, trajectory, _ProgressWriter(task_id, trace=True)) + task_state.write_terminal(task_id, "COMPLETED", {"trace_s3_uri": uri}) + return artifact + + +def _trace_url(api: str, task_id: str, caller: str) -> requests.Response: + return requests.get(f"{api}/tasks/{task_id}/trace", headers={"X-API-Key": caller}, timeout=30) + + +class TestTraceRoundTrip: + def test_cli_prints_the_jsonl_the_agent_wrote(self, traced_task, bgagent, task_id, user_id): + result = bgagent(user_id, "trace", "download", task_id) + + assert result.returncode == 0, result.stderr.decode() + assert result.stdout == gzip.decompress(traced_task) + header, *events = [json.loads(line) for line in result.stdout.splitlines()] + assert header["event"] == "TRAJECTORY_ARTIFACT_HEADER" + assert [e["event"] for e in events] == ["TRAJECTORY_TURN", "POLICY_DECISION"] + + def test_cli_output_file_is_the_stored_artifact_byte_for_byte( + self, traced_task, bgagent, task_id, user_id, tmp_path + ): + target = tmp_path / "trace.jsonl.gz" + + result = bgagent(user_id, "trace", "download", task_id, "-o", str(target)) + + assert result.returncode == 0, result.stderr.decode() + assert target.read_bytes() == traced_task + + def test_presigned_url_works_for_any_https_client_that_trusts_the_emulator( + self, traced_task, trace_api, emulator, task_id, user_id + ): + issued = _trace_url(trace_api, task_id, user_id) + assert issued.status_code == 200, issued.text + + download = requests.get(issued.json()["data"]["url"], verify=emulator.ca_bundle, timeout=30) + + assert download.status_code == 200 + assert download.content == traced_task + assert download.headers["Content-Type"] == "application/gzip" + assert "Content-Encoding" not in download.headers + + +class TestTraceUrlIsRefused: + def test_for_a_caller_who_does_not_own_the_task(self, traced_task, trace_api, task_id): + response = _trace_url(trace_api, task_id, "someone-else") + + assert response.status_code == 403 + assert response.json()["error"]["code"] == "FORBIDDEN" + # The key-prefix guard further down answers with the same status and code; + # the message is what shows that the record-ownership check refused this. + assert response.json()["error"]["message"] == "You do not have access to this task." + + def test_until_the_agent_has_recorded_a_trace( + self, agent_env, bgagent, trace_api, task_id, user_id + ): + agent_env.table(agent_env.task_table).put_item( + Item={"task_id": task_id, "user_id": user_id, "status": "RUNNING"} + ) + + response = _trace_url(trace_api, task_id, user_id) + result = bgagent(user_id, "trace", "download", task_id) + + assert response.status_code == 404 + assert response.json()["error"]["code"] == "TRACE_NOT_AVAILABLE" + assert result.returncode != 0 + assert f"No trace artifact for task {task_id}" in result.stderr.decode() + + def test_when_the_recorded_object_is_gone_from_s3( + self, traced_task, trace_api, emulator, task_id, user_id + ): + emulator.client("s3").delete_object( + Bucket=emulator.trace_bucket, Key=f"traces/{user_id}/{task_id}.jsonl.gz" + ) + + response = _trace_url(trace_api, task_id, user_id) + + assert response.status_code == 404 + assert response.json()["error"]["code"] == "TRACE_NOT_AVAILABLE" diff --git a/agent/tests_emulator/test_trace_upload.py b/agent/tests_emulator/test_trace_upload.py new file mode 100644 index 000000000..b46cfd2f0 --- /dev/null +++ b/agent/tests_emulator/test_trace_upload.py @@ -0,0 +1,134 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: MIT-0 + +"""The ``--trace`` upload half (design §10.1) against a real S3 API. + +``tests/test_trace_upload.py`` asserts the ``put_object`` arguments on a mock. +Here the object is written to the emulator's S3 and read back, so the stored +bytes, key and content headers are what a downloader would actually receive. +""" + +from __future__ import annotations + +import gzip +import json + +from boto3.dynamodb.conditions import Key + +from models import TaskConfig +from pipeline import _maybe_upload_trace +from progress_writer import _ProgressWriter +from telemetry import _TrajectoryWriter, upload_trace_to_s3 + + +def _task_config(task_id: str, user_id: str, *, trace: bool) -> TaskConfig: + return TaskConfig( + repo_url="owner/repo", + aws_region="us-east-1", + task_id=task_id, + task_description="Do a thing", + user_id=user_id, + trace=trace, + ) + + +def _recorded_trajectory(task_id: str) -> _TrajectoryWriter: + """A trajectory with the events a short traced task accumulates.""" + trajectory = _TrajectoryWriter(task_id, accumulate=True) + trajectory.write_turn( + turn=1, + model="claude", + thinking="plan", + text="Reading the repo — ünïcödé", + tool_calls=[{"name": "Bash", "input": {"command": "ls"}}], + tool_results=[{"tool_use_id": "t1", "content": "README.md", "is_error": False}], + ) + trajectory.write_policy_decision("Bash", allowed=True, reason="permit", duration_ms=1.5) + trajectory.write_result( + subtype="success", + num_turns=1, + cost_usd=0.01, + duration_ms=1200, + duration_api_ms=900, + session_id="session-1", + usage=None, + ) + return trajectory + + +def _artifact(trajectory: _TrajectoryWriter) -> bytes: + artifact = trajectory.dump_gzipped_jsonl() + assert artifact is not None + return artifact + + +def _stored_trace(emulator, user_id: str, task_id: str) -> dict: + return emulator.client("s3").get_object( + Bucket=emulator.trace_bucket, Key=f"traces/{user_id}/{task_id}.jsonl.gz" + ) + + +class TestTraceUploadReachesS3: + def test_artifact_is_stored_byte_for_byte_under_the_callers_prefix( + self, agent_env, task_id, user_id + ): + artifact = _artifact(_recorded_trajectory(task_id)) + + uri = upload_trace_to_s3(task_id=task_id, user_id=user_id, body=artifact) + + assert uri == f"s3://{agent_env.trace_bucket}/traces/{user_id}/{task_id}.jsonl.gz" + stored = _stored_trace(agent_env, user_id, task_id) + assert stored["Body"].read() == artifact + # Described as gzip *content*, not as a gzip *encoding*: a client that saw + # Content-Encoding: gzip would decompress it behind the CLI's back. + assert stored["ContentType"] == "application/gzip" + assert "ContentEncoding" not in stored + + def test_stored_artifact_is_header_plus_events_as_jsonl(self, agent_env, task_id, user_id): + artifact = _artifact(_recorded_trajectory(task_id)) + upload_trace_to_s3(task_id=task_id, user_id=user_id, body=artifact) + + body = _stored_trace(agent_env, user_id, task_id)["Body"].read() + header, *events = [json.loads(line) for line in gzip.decompress(body).splitlines()] + assert header["event"] == "TRAJECTORY_ARTIFACT_HEADER" + assert header["task_id"] == task_id + assert header["accumulated_events"] == 3 + assert [e["event"] for e in events] == [ + "TRAJECTORY_TURN", + "POLICY_DECISION", + "TRAJECTORY_RESULT", + ] + assert events[0]["text"] == "Reading the repo — ünïcödé" + + def test_missing_bucket_fails_open(self, agent_env, task_id, user_id, monkeypatch, capsys): + monkeypatch.setenv("TRACE_ARTIFACTS_BUCKET_NAME", f"{agent_env.trace_bucket}-absent") + + uri = upload_trace_to_s3(task_id=task_id, user_id=user_id, body=b"\x1f\x8b") + + assert uri is None + assert "S3 put_object failed: NoSuchBucket" in capsys.readouterr().out + + +class TestPipelineTraceUpload: + def test_upload_announces_the_artifact_on_the_event_stream(self, agent_env, task_id, user_id): + config = _task_config(task_id, user_id, trace=True) + progress = _ProgressWriter(task_id, trace=True, user_id=user_id, repo=config.repo_url) + + uri = _maybe_upload_trace(config, _recorded_trajectory(task_id), progress) + + assert uri == f"s3://{agent_env.trace_bucket}/traces/{user_id}/{task_id}.jsonl.gz" + (event,) = agent_env.table(agent_env.task_events_table).query( + KeyConditionExpression=Key("task_id").eq(task_id), ConsistentRead=True + )["Items"] + assert event["metadata"] == {"milestone": "trajectory_uploaded", "details": uri} + + def test_task_without_trace_uploads_nothing(self, agent_env, task_id, user_id): + config = _task_config(task_id, user_id, trace=False) + + uri = _maybe_upload_trace(config, _recorded_trajectory(task_id), _ProgressWriter(task_id)) + + assert uri is None + listing = agent_env.client("s3").list_objects_v2( + Bucket=agent_env.trace_bucket, Prefix=f"traces/{user_id}/" + ) + assert listing["KeyCount"] == 0 diff --git a/agent/uv.lock b/agent/uv.lock index 1d024cbb6..e2634ee0a 100644 --- a/agent/uv.lock +++ b/agent/uv.lock @@ -64,10 +64,11 @@ wheels = [ [[package]] name = "aws-opentelemetry-distro" -version = "0.18.0" +version = "0.22.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "cachetools" }, + { name = "certifi" }, { name = "opentelemetry-api" }, { name = "opentelemetry-distro" }, { name = "opentelemetry-exporter-otlp-proto-common" }, @@ -88,7 +89,6 @@ dependencies = [ { name = "opentelemetry-instrumentation-confluent-kafka" }, { name = "opentelemetry-instrumentation-dbapi" }, { name = "opentelemetry-instrumentation-django" }, - { name = "opentelemetry-instrumentation-elasticsearch" }, { name = "opentelemetry-instrumentation-falcon" }, { name = "opentelemetry-instrumentation-fastapi" }, { name = "opentelemetry-instrumentation-flask" }, @@ -99,7 +99,6 @@ dependencies = [ { name = "opentelemetry-instrumentation-logging" }, { name = "opentelemetry-instrumentation-mysql" }, { name = "opentelemetry-instrumentation-mysqlclient" }, - { name = "opentelemetry-instrumentation-openai-agents-v2" }, { name = "opentelemetry-instrumentation-pika" }, { name = "opentelemetry-instrumentation-psycopg2" }, { name = "opentelemetry-instrumentation-pymemcache" }, @@ -129,11 +128,12 @@ dependencies = [ { name = "protobuf" }, { name = "python-dateutil" }, { name = "pyyaml" }, + { name = "requests" }, { name = "urllib3" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/da/6e/4674462032fee74bd51c6361056467e670af656c5b3fc49816aa97fbe14a/aws_opentelemetry_distro-0.18.0.tar.gz", hash = "sha256:4b1356e59c88ddfcdb9b1d7893868e3c7d66edad3ca5cf755d833877d1e8659b", size = 639010, upload-time = "2026-06-19T22:37:04.115Z" } +sdist = { url = "https://files.pythonhosted.org/packages/f3/d9/c892361084a79206f6983215e1f33dff3fe5cc5c6c97b64eb600a7260691/aws_opentelemetry_distro-0.22.0.tar.gz", hash = "sha256:e0972cf1abe04a5a10755089004a90a0b7e47aafbd1327c9fa2688a1792324ce", size = 663188, upload-time = "2026-10-30T22:54:05.903Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/c5/4d/5adde5c5ee4751f389cc2a7a44da878cd64b49a1c7a71d2da42ba9aff022/aws_opentelemetry_distro-0.18.0-py3-none-any.whl", hash = "sha256:9d0e077538b4638a023b7e5af72fde1ec03a2cc84406fe8e943df510010e0310", size = 394659, upload-time = "2026-06-19T22:37:02.095Z" }, + { url = "https://files.pythonhosted.org/packages/ef/67/6b7715fb39b0e8285aa653120470d27990fa8f1d307d10d61d27d4812fd4/aws_opentelemetry_distro-0.22.0-py3-none-any.whl", hash = "sha256:5a15658d83c17dd46d1a119620e6a8088cbf563548c8623f8eeb344748604610", size = 388831, upload-time = "2026-10-30T22:54:04.346Z" }, ] [[package]] @@ -168,7 +168,7 @@ dev = [ [package.metadata] requires-dist = [ - { name = "aws-opentelemetry-distro", specifier = "==0.18.0" }, + { name = "aws-opentelemetry-distro", specifier = "==0.22.0" }, { name = "bedrock-agentcore", specifier = "==1.18.1" }, { name = "boto3", specifier = "==1.43.78" }, { name = "cedarpy", specifier = "==4.12.2" }, @@ -767,81 +767,113 @@ wheels = [ [[package]] name = "opentelemetry-api" -version = "1.42.1" +version = "1.45.1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/b4/1c/125e1c936c0873796771b7f04f6c93b9f1bf5d424cea90fda94a99f61da8/opentelemetry_api-1.42.1.tar.gz", hash = "sha256:56c63bea9f77b62856be8c47600474acad853b2924b99b1687c4cb6297166716", size = 72296, upload-time = "2026-05-21T16:32:49.335Z" } +sdist = { url = "https://files.pythonhosted.org/packages/2e/02/6e0ae9cc61bd3169d401077b507b3ebc344745171e1051ab430be012dcd9/opentelemetry_api-1.45.1.tar.gz", hash = "sha256:aa38ed19bcc084ba42782a73255b3582283eced7ad6dddbd6695189e69adfb75", size = 72804, upload-time = "2026-10-06T17:32:58.133Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/a3/ca/9520cc1f3dfbbd03ac5903bbf55833e257bc64b1cf30fa8b0d6df374d821/opentelemetry_api-1.42.1-py3-none-any.whl", hash = "sha256:51a69edacadbc03a8950ace1c4c21099cacc538820ac2c9e36277e78cebba714", size = 61311, upload-time = "2026-05-21T16:32:28.822Z" }, + { url = "https://files.pythonhosted.org/packages/1e/41/f7dcf80b81ee8e71c1a2b59f14208bc723edbd89ed027a73b175abf6348e/opentelemetry_api-1.45.1-py3-none-any.whl", hash = "sha256:b31553efa588ae44bc306f863c785c5333a9ecc091248c6ee68b4b6c87fdedfb", size = 60256, upload-time = "2026-10-06T17:32:33.506Z" }, ] [[package]] name = "opentelemetry-distro" -version = "0.63b1" +version = "0.66b1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "opentelemetry-instrumentation" }, { name = "opentelemetry-sdk" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/c5/97/87080029d9309841dd97db34130f9410cda77162843f81d09ad257dce1ef/opentelemetry_distro-0.63b1.tar.gz", hash = "sha256:f435098abc7953f58226e8bf79e4c90bc6b32e50aa75d6fa074201db8243b577", size = 2333, upload-time = "2026-05-21T16:36:11.285Z" } +sdist = { url = "https://files.pythonhosted.org/packages/14/6b/65ad1c3ead547568fd9bb800eb78b8b440c3eaa13d8f0632f91e8e7af2aa/opentelemetry_distro-0.66b1.tar.gz", hash = "sha256:c2f679de6a0540fabef6d39fb43fce4c0ceb1a506e667c1fd7153abf362c0368", size = 2333, upload-time = "2026-10-06T17:36:08.419Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/09/27/1e05a169e5538b3c5c56ce3a27e230cf2227f2e4e2731291950517d67ddd/opentelemetry_distro-0.66b1-py3-none-any.whl", hash = "sha256:bf29f42ed11397c6fbea36c1e45481d9430a27ea116719c4902bdfbdeee54605", size = 2777, upload-time = "2026-10-06T17:35:07.705Z" }, +] + +[[package]] +name = "opentelemetry-exporter-http-transport" +version = "0.66b1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "opentelemetry-api" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/62/0c/e3ebdb4b507f66afcc905e6885a4946969bd75b45988492643356fbbdc63/opentelemetry_exporter_http_transport-0.66b1.tar.gz", hash = "sha256:443080203bf52586ce0b2ad901e8951c61833eab1aa539ae6f1f16fe9e8e7952", size = 11693, upload-time = "2026-10-06T17:32:59.65Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/35/97/16619e2e0e5192f2d1b8da2aaaefface05463cc1cfca6b81d3a3108ccedd/opentelemetry_distro-0.63b1-py3-none-any.whl", hash = "sha256:b405b04ad70e430390265eb38e82e067a84ca1f49a21429eaadb930c13330d66", size = 2777, upload-time = "2026-05-21T16:34:51.441Z" }, + { url = "https://files.pythonhosted.org/packages/04/69/6af86ff66492b481c6a4c05dcfd68beb47ed8ba046440a26a2aac76b95c7/opentelemetry_exporter_http_transport-0.66b1-py3-none-any.whl", hash = "sha256:2f95404bdee7f9d2d529c7de56c7bd86d014d774d8fbf137810e0167f8a492bf", size = 12155, upload-time = "2026-10-06T17:32:35.454Z" }, +] + +[package.optional-dependencies] +requests = [ + { name = "requests" }, +] + +[[package]] +name = "opentelemetry-exporter-otlp-common" +version = "0.66b1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "opentelemetry-sdk" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/cb/19/41de712173f43057e4532d42ece7d0c6d4210d353e5752433cb14987643f/opentelemetry_exporter_otlp_common-0.66b1.tar.gz", hash = "sha256:6b1403487a2185ac1feb45fd5546fdf8630ce71c36bcefaadf51e2130e9e23f9", size = 14325, upload-time = "2026-10-06T17:33:01.725Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fc/39/8c23d67665c762aa51840fa06f86e902e8f6f1693bc8d7e3d98cd6e2f753/opentelemetry_exporter_otlp_common-0.66b1-py3-none-any.whl", hash = "sha256:00ff8592c3a7cb729ff3fdc7ffa12372c243bdf2163e80c180994d0c7bd83ee9", size = 12385, upload-time = "2026-10-06T17:32:38.177Z" }, ] [[package]] name = "opentelemetry-exporter-otlp-proto-common" -version = "1.42.1" +version = "1.45.1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-proto" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/0e/9c/216acfeaedadf2e1937f4373929b20f73197c5c4a2546d4f584b7fa63813/opentelemetry_exporter_otlp_proto_common-1.42.1.tar.gz", hash = "sha256:04f1f01fb597c4249dfcd7f8b861c902c2102369d376d9d346ff38de4469a2ee", size = 21433, upload-time = "2026-05-21T16:32:55.526Z" } +sdist = { url = "https://files.pythonhosted.org/packages/c1/8e/65e85e5137991a3c493b11682151d198638a5bc1dd4b4c5f67e013c57d7c/opentelemetry_exporter_otlp_proto_common-1.45.1.tar.gz", hash = "sha256:2e4adcc3a67bcf57804fc49514f0ef64974ca7590aa3491da389852b4a0628f6", size = 18873, upload-time = "2026-10-06T17:33:04.471Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/d6/43/2375e7612e1121a4518c17603b6e0b03ad94f565aafad53f464dc5be2bf6/opentelemetry_exporter_otlp_proto_common-1.42.1-py3-none-any.whl", hash = "sha256:f48d395ab815b444da118868977e9798ea354c25737d5cf39578ae894011c140", size = 17327, upload-time = "2026-05-21T16:32:33.387Z" }, + { url = "https://files.pythonhosted.org/packages/84/aa/92f225d353904e7f70b8b3e3c1b02db0cf56f744c2e83c581dc372e78873/opentelemetry_exporter_otlp_proto_common-1.45.1-py3-none-any.whl", hash = "sha256:2f446183ae7047b036226f1d846c41a834b0e8755ad13b51a51dd38952eb466c", size = 15393, upload-time = "2026-10-06T17:32:41.911Z" }, ] [[package]] name = "opentelemetry-exporter-otlp-proto-grpc" -version = "1.42.1" +version = "1.45.1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "googleapis-common-protos" }, { name = "grpcio" }, { name = "opentelemetry-api" }, + { name = "opentelemetry-exporter-otlp-common" }, { name = "opentelemetry-exporter-otlp-proto-common" }, { name = "opentelemetry-proto" }, { name = "opentelemetry-sdk" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/87/87/ca7fc790dfdbcf4f9e9aab14a39ef1b7508ead13707e283de0b3131478d2/opentelemetry_exporter_otlp_proto_grpc-1.42.1.tar.gz", hash = "sha256:975c4461f167dd8ed8857d68d3b6b25f3d272eab896f6a9470d0f5b90e2faf15", size = 27140, upload-time = "2026-05-21T16:32:56.162Z" } +sdist = { url = "https://files.pythonhosted.org/packages/d6/00/a82af0be959dc58495740b169c6669a86e0811f6cd353a01eda34d255db3/opentelemetry_exporter_otlp_proto_grpc-1.45.1.tar.gz", hash = "sha256:3b3dcfbfdcb4e35149fcf309972282054b45228f5c10547d0095d6578510a9a0", size = 25997, upload-time = "2026-10-06T17:33:05.114Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/89/2b/28ba5b128f47fe8c3bab541000d6feb4b5a9bd26623ca013406f01c0fb60/opentelemetry_exporter_otlp_proto_grpc-1.42.1-py3-none-any.whl", hash = "sha256:0ae1177e2038b18a929b3098215243631ef91136cba26b7e2b12790ceb7e87cc", size = 19617, upload-time = "2026-05-21T16:32:34.278Z" }, + { url = "https://files.pythonhosted.org/packages/4d/46/2d1da202f1e17c81aae7efcf702898d524b46709e4d3e2bf1f7f8ca8fbc6/opentelemetry_exporter_otlp_proto_grpc-1.45.1-py3-none-any.whl", hash = "sha256:e42ecb789d2fc5d8145e3dadc3e2991c9f18cd166d7c7514e234702540274b76", size = 19492, upload-time = "2026-10-06T17:32:42.838Z" }, ] [[package]] name = "opentelemetry-exporter-otlp-proto-http" -version = "1.42.1" +version = "1.45.1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "googleapis-common-protos" }, { name = "opentelemetry-api" }, + { name = "opentelemetry-exporter-http-transport", extra = ["requests"] }, + { name = "opentelemetry-exporter-otlp-common" }, { name = "opentelemetry-exporter-otlp-proto-common" }, { name = "opentelemetry-proto" }, { name = "opentelemetry-sdk" }, { name = "requests" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/77/32/826bfa1d80ecea24f47808de03cd4a0d13c17ecc07712f45123f0f61e4ac/opentelemetry_exporter_otlp_proto_http-1.42.1.tar.gz", hash = "sha256:bf142a21035d7571ac3a09cb2e5639f49886f243972883cfe777ed3bf02b734d", size = 25406, upload-time = "2026-05-21T16:32:56.807Z" } +sdist = { url = "https://files.pythonhosted.org/packages/1b/17/26487707ea4caa97b17e6e4b5fa72133a53512ffa2f5cf7a49ef284b29cb/opentelemetry_exporter_otlp_proto_http-1.45.1.tar.gz", hash = "sha256:45c218405ce3fd879596924b1874bf9a8f6880206d61065c5a912c8e5c297fb7", size = 28839, upload-time = "2026-10-06T17:33:05.713Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/d3/96/82cb223a1502f0787d4bbff12907f5f8d870a50731febcd5818d93ef9555/opentelemetry_exporter_otlp_proto_http-1.42.1-py3-none-any.whl", hash = "sha256:00a16da1b312a1d6c7233d600d557c91df71125af73020f3b9a7765bd699d59d", size = 21793, upload-time = "2026-05-21T16:32:35.277Z" }, + { url = "https://files.pythonhosted.org/packages/aa/1f/517eaa0187ba106a9da97160ce2add3a371812681dc440930b267f714e42/opentelemetry_exporter_otlp_proto_http-1.45.1-py3-none-any.whl", hash = "sha256:24a97cf3753c7fb52fad44a696e452ff371686339e2acf3309e2eda3d0230700", size = 22180, upload-time = "2026-10-06T17:32:43.946Z" }, ] [[package]] name = "opentelemetry-instrumentation" -version = "0.63b1" +version = "0.66b1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -849,14 +881,14 @@ dependencies = [ { name = "packaging" }, { name = "wrapt" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/da/6d/4de72d97ff54db1ed270c7a59c9b904b917c0ac7af429c086c388b824ddb/opentelemetry_instrumentation-0.63b1.tar.gz", hash = "sha256:32368d6ae52c8de20aa790a6ad86b10a76f09956092337ae37d675773990e541", size = 41081, upload-time = "2026-05-21T16:36:14.206Z" } +sdist = { url = "https://files.pythonhosted.org/packages/a5/03/89e47ff8d52a4f83b343e6eb9ef1698ff45357216e5b6b2b21e0da5c5c7d/opentelemetry_instrumentation-0.66b1.tar.gz", hash = "sha256:e79a510f7d87c72d95e964ddb42193a0d9a75668c027d980eab032ea1322a5ce", size = 43308, upload-time = "2026-10-06T17:36:10.703Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/35/a1/9314e621c143e4d82a5bf7a43c2ff7a745d31023506336857607c8c543cc/opentelemetry_instrumentation-0.63b1-py3-none-any.whl", hash = "sha256:f1986716d52cc316ea5f60189098726a9071d8ecc0eee96c9ed110be08bade9c", size = 35577, upload-time = "2026-05-21T16:34:56.818Z" }, + { url = "https://files.pythonhosted.org/packages/da/b2/d1413681ff43e13ac9860df27e1226d3199ab0b97b352ceea41abcc660a5/opentelemetry_instrumentation-0.66b1-py3-none-any.whl", hash = "sha256:4c4aa14dc9a24a02325a9d4c42c4d0208dbb1374c2b1b8fe6c9392d59f3e1008", size = 36904, upload-time = "2026-10-06T17:35:11.663Z" }, ] [[package]] name = "opentelemetry-instrumentation-aio-pika" -version = "0.63b1" +version = "0.66b1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -864,14 +896,14 @@ dependencies = [ { name = "opentelemetry-semantic-conventions" }, { name = "wrapt" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/7a/32/277914f342efb52c64591c9c9b1333d1d7831a431c59122bf0cd67579e3f/opentelemetry_instrumentation_aio_pika-0.63b1.tar.gz", hash = "sha256:04ee2e556898828522ef9d2dd15bbcced85c32f558c362d00532d4231b321b78", size = 10190, upload-time = "2026-05-21T16:36:14.916Z" } +sdist = { url = "https://files.pythonhosted.org/packages/81/f0/9814836adbb2e3f0a61b192c3ad76a5518ff9902883f80ccd989be0f582e/opentelemetry_instrumentation_aio_pika-0.66b1.tar.gz", hash = "sha256:225c6fce4c6c341cddcec8342a5536c9f66927aa21968b233721673f465e520e", size = 10101, upload-time = "2026-10-06T17:36:11.404Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/17/a2/1a76234cfd6ec3958382696bf92740252e2e87efe4fe15a424d4ca91f423/opentelemetry_instrumentation_aio_pika-0.63b1-py3-none-any.whl", hash = "sha256:b8966aa46abc6f0d86d650502bafb479d0a03cb7d5b660a257d06020f1733c4a", size = 11679, upload-time = "2026-05-21T16:34:58.222Z" }, + { url = "https://files.pythonhosted.org/packages/f9/7a/d59e721f94743493030878ee30bbb6c4e7b405bc7cfd7a6a6bc57fe6ed86/opentelemetry_instrumentation_aio_pika-0.66b1-py3-none-any.whl", hash = "sha256:72ae37f1a579151b404635145efa92d97e24384505bc123f24532e98e400e764", size = 11645, upload-time = "2026-10-06T17:35:12.731Z" }, ] [[package]] name = "opentelemetry-instrumentation-aiohttp-client" -version = "0.63b1" +version = "0.66b1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -880,14 +912,14 @@ dependencies = [ { name = "opentelemetry-util-http" }, { name = "wrapt" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/47/6f/e7105760ec528b465238a06a05f8e6c358063e00ad53fed76fd625c6230c/opentelemetry_instrumentation_aiohttp_client-0.63b1.tar.gz", hash = "sha256:ec97399c02a7e278359efffdf16e93d59a7103b16f66790cda9b9496b171b136", size = 19041, upload-time = "2026-05-21T16:36:15.62Z" } +sdist = { url = "https://files.pythonhosted.org/packages/85/fe/634d77a0109df609eb290d172ab57e45fe35a1ef2c277f3e1908267acaa1/opentelemetry_instrumentation_aiohttp_client-0.66b1.tar.gz", hash = "sha256:6f853dadc53916fd6af41413bcb627b3e36c4a01b581e03b61b2f8eb6031d69f", size = 18849, upload-time = "2026-10-06T17:36:12.072Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/41/f8/f18666128e4b602601316ee73f35986c0a42ce44a615fd6b0f566c15e282/opentelemetry_instrumentation_aiohttp_client-0.63b1-py3-none-any.whl", hash = "sha256:5259c2c5103a5919941e0c45f2c95b055a50eb2ab39dc252f4b1e41ce6d984bb", size = 13675, upload-time = "2026-05-21T16:34:59.263Z" }, + { url = "https://files.pythonhosted.org/packages/7b/30/dd352a722a4b928b22363df249b38b6d173173d36b2eab6d04770fd7d348/opentelemetry_instrumentation_aiohttp_client-0.66b1-py3-none-any.whl", hash = "sha256:bb3d412ae30e83e0692c8e9b600c5990bdab736c7c048847461b4567d504078d", size = 13610, upload-time = "2026-10-06T17:35:13.651Z" }, ] [[package]] name = "opentelemetry-instrumentation-aiokafka" -version = "0.63b1" +version = "0.66b1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -895,14 +927,14 @@ dependencies = [ { name = "opentelemetry-semantic-conventions" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/fd/97/94d37d1e070f8f5dd64b0f5ef73abcafc0b6b22ea11469326c4cdd642ee9/opentelemetry_instrumentation_aiokafka-0.63b1.tar.gz", hash = "sha256:3c60f0f22a50780f84b6b61660e5e107f54f92c8ac2384f704f67bc00ff08c46", size = 14312, upload-time = "2026-05-21T16:36:17.023Z" } +sdist = { url = "https://files.pythonhosted.org/packages/23/72/f7060d236d5dd07bfe4788597d312b6946397af510ffda2823f365a889b7/opentelemetry_instrumentation_aiokafka-0.66b1.tar.gz", hash = "sha256:185e18196d52f13db75910bc5fa1900ff858dc3743c473e6bf4d57c712125448", size = 14193, upload-time = "2026-10-06T17:36:13.23Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/a7/e4/74b822a937e03ed4c4d6da6f9b041570d4ab0620bbd273b36a5460d06e5b/opentelemetry_instrumentation_aiokafka-0.63b1-py3-none-any.whl", hash = "sha256:730baf099753e591ab77cf2051b4b2043ecfbb69bb30e1da6a42e9f34dfa9752", size = 12727, upload-time = "2026-05-21T16:35:01.799Z" }, + { url = "https://files.pythonhosted.org/packages/e9/95/fc09ace9a2d7f0ea8c84c7863c31eb7a1c4dd53e87375674b6f0a070e739/opentelemetry_instrumentation_aiokafka-0.66b1-py3-none-any.whl", hash = "sha256:6a13ce65a2557b03989e0c096dfe02ee038ca16e5a191cb6b0b08de318bece6f", size = 12686, upload-time = "2026-10-06T17:35:15.644Z" }, ] [[package]] name = "opentelemetry-instrumentation-aiopg" -version = "0.63b1" +version = "0.66b1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -910,14 +942,14 @@ dependencies = [ { name = "opentelemetry-instrumentation-dbapi" }, { name = "wrapt" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/73/a2/5e873bd4a154847a7a07b02851a96ade063cad4b58aa130446acb4466c3a/opentelemetry_instrumentation_aiopg-0.63b1.tar.gz", hash = "sha256:c0422f67e1fa1302eeda3d4bacf2717b45bed7cf30983f97110de3fc934823db", size = 11713, upload-time = "2026-05-21T16:36:17.707Z" } +sdist = { url = "https://files.pythonhosted.org/packages/19/15/57b2416cea0ff0018e031843f317b90c3f330870af72897783c9058d1219/opentelemetry_instrumentation_aiopg-0.66b1.tar.gz", hash = "sha256:986d4e1d62e366d3da6d6ecf5ba19ddc172bd5467bc7973c1a0f8fba6d626235", size = 13409, upload-time = "2026-10-06T17:36:14.021Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/a5/c6/6e14818746f44d5463d5d2f307da767c522c908162eaf12678d9924e72a6/opentelemetry_instrumentation_aiopg-0.63b1-py3-none-any.whl", hash = "sha256:eb18261302a592d3dcfaa2f178e2b67c06c8692254d0fb2f5c9f51196da93aaf", size = 11407, upload-time = "2026-05-21T16:35:02.846Z" }, + { url = "https://files.pythonhosted.org/packages/ff/20/99be82fc9cd09e12bc35f50d0cb1a1570330c54322f7eefd39efd0d6bc32/opentelemetry_instrumentation_aiopg-0.66b1-py3-none-any.whl", hash = "sha256:aa4606515172b23c8c70c5afa3254e408ff1eace4862a7167f0e8b24d6a768e0", size = 11704, upload-time = "2026-10-06T17:35:16.602Z" }, ] [[package]] name = "opentelemetry-instrumentation-asgi" -version = "0.63b1" +version = "0.66b1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "asgiref" }, @@ -926,42 +958,42 @@ dependencies = [ { name = "opentelemetry-semantic-conventions" }, { name = "opentelemetry-util-http" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a0/b5/7ea3a9fd1b80e89786c14250bfaecf32a753c3fd08232690f4da8dc16e29/opentelemetry_instrumentation_asgi-0.63b1.tar.gz", hash = "sha256:267b422416d768f3c7f4054883b41d9c3a7c943d86d20032b738c99a3dbb5862", size = 26151, upload-time = "2026-05-21T16:36:18.368Z" } +sdist = { url = "https://files.pythonhosted.org/packages/5a/d9/ff522f5c3e340e9007554923b1a4d2ac451676f8757bafb3d0057f68b5c3/opentelemetry_instrumentation_asgi-0.66b1.tar.gz", hash = "sha256:78cdc5e45e897e16a8dac9d282e8d5bdf9af2d58e1313fa0bdd4a134c6f9dafc", size = 25992, upload-time = "2026-10-06T17:36:14.593Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/57/7e/83986f27b421de04fab1e1a84e892621dac42e6432a9c66779505f4d1381/opentelemetry_instrumentation_asgi-0.63b1-py3-none-any.whl", hash = "sha256:1a22453dfa965f14799b10a674b8acbcb897a8a75c79136060af54214cc7886e", size = 15906, upload-time = "2026-05-21T16:35:04.162Z" }, + { url = "https://files.pythonhosted.org/packages/67/ea/10ba99110bf3c9fb736af39c96ca8f3668b988cabb6b59309e058c44461c/opentelemetry_instrumentation_asgi-0.66b1-py3-none-any.whl", hash = "sha256:78b3f9bdf0fa38c65935a2ab46d59e0f9de873a51e0c95b0329f106e2ccb5274", size = 15812, upload-time = "2026-10-06T17:35:17.638Z" }, ] [[package]] name = "opentelemetry-instrumentation-asyncpg" -version = "0.63b1" +version = "0.66b1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "opentelemetry-instrumentation" }, { name = "opentelemetry-semantic-conventions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/ad/52/86a5d3e287fb67a6ff4d6dde7653f52b5c18ecd5429809508b507a0988a0/opentelemetry_instrumentation_asyncpg-0.63b1.tar.gz", hash = "sha256:8459cd11e3c114a0b823feb99dc8bac4c55a5374c4287211d0c2cc98787c38e0", size = 8745, upload-time = "2026-05-21T16:36:20.943Z" } +sdist = { url = "https://files.pythonhosted.org/packages/4d/af/283db299795441d914045e051c339767e781eae6dde9846659e949731806/opentelemetry_instrumentation_asyncpg-0.66b1.tar.gz", hash = "sha256:ac244bd5cb23363880a7937763d0810035815dc74a8389d2aa1f73d532ae47aa", size = 11413, upload-time = "2026-10-06T17:36:16.982Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/ef/09/62151650fe7bf76669130042fd2fc809e15b2c89489bfd4bb58d292a83f8/opentelemetry_instrumentation_asyncpg-0.63b1-py3-none-any.whl", hash = "sha256:ab3762e3d507e7a9bfab97a12fefa4c5b4048fcfbcbb3ae4887cf18bab364857", size = 9250, upload-time = "2026-05-21T16:35:08.22Z" }, + { url = "https://files.pythonhosted.org/packages/f3/59/f4c71b0023cef5cfb0c77fcd3d862cfe52892c4142797256ba1ffb036676/opentelemetry_instrumentation_asyncpg-0.66b1-py3-none-any.whl", hash = "sha256:7fe611aa899ac59f4a34b05e817a61f4011dc50d1545c4f48b77a4c62e663f05", size = 9750, upload-time = "2026-10-06T17:35:21.113Z" }, ] [[package]] name = "opentelemetry-instrumentation-aws-lambda" -version = "0.63b1" +version = "0.66b1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-instrumentation" }, { name = "opentelemetry-propagator-aws-xray" }, { name = "opentelemetry-semantic-conventions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/db/b3/5d7dc90186f8f64f6691c71904a8c6142532a056e469330e6ce7d345722b/opentelemetry_instrumentation_aws_lambda-0.63b1.tar.gz", hash = "sha256:1cb08d94ea3a9f543c90dc782358206546eb383140fb531066e050d8a4d87b59", size = 18550, upload-time = "2026-05-21T16:36:21.617Z" } +sdist = { url = "https://files.pythonhosted.org/packages/e9/a2/69e585e4d6d43649908d9fdfc92073499102f16a2487cd5a3709ad50e6bf/opentelemetry_instrumentation_aws_lambda-0.66b1.tar.gz", hash = "sha256:a270279181f7759a417535c6a90a92f22c6b6c6c551940e37e2cd5b50556b7d1", size = 22730, upload-time = "2026-10-06T17:36:17.541Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/f9/13/c16d9efd02013f0f1b728be111bd2261118bc092d57f7ac7655e40a11c98/opentelemetry_instrumentation_aws_lambda-0.63b1-py3-none-any.whl", hash = "sha256:df83558e2a294d0bd4b328d4ffae01881c795424602f8137d628f875f4d51724", size = 12078, upload-time = "2026-05-21T16:35:14.538Z" }, + { url = "https://files.pythonhosted.org/packages/ed/45/01d5303d03660b9d395b00da7c9c973605afda21883e6d05acbe92e98916/opentelemetry_instrumentation_aws_lambda-0.66b1-py3-none-any.whl", hash = "sha256:48a237c5418f5a00d366822f17bd271514be7e2cec18e28cbd4b0dfed88183a8", size = 13925, upload-time = "2026-10-06T17:35:22.017Z" }, ] [[package]] name = "opentelemetry-instrumentation-boto3sqs" -version = "0.63b1" +version = "0.66b1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -969,14 +1001,14 @@ dependencies = [ { name = "opentelemetry-semantic-conventions" }, { name = "wrapt" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/9d/96/995654768e0687157c19d29aaa7e39ed25e58337962181483a2d4951cd94/opentelemetry_instrumentation_boto3sqs-0.63b1.tar.gz", hash = "sha256:76064cc454ea46183dba8479819c69cf7cfb6304575e8ce33a3ee7b9f981feca", size = 11706, upload-time = "2026-05-21T16:36:22.328Z" } +sdist = { url = "https://files.pythonhosted.org/packages/60/d1/8728260955240c0fe16f6ce5cef7e90088ef54384f0594fb495d0b1eb051/opentelemetry_instrumentation_boto3sqs-0.66b1.tar.gz", hash = "sha256:71387b8f89d38d521f172b80473f858c879718fc58b24cca3fb5ed1afa2458b2", size = 11884, upload-time = "2026-10-06T17:36:18.138Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/d2/40/46a1ce83f93107064e3d2b6d6f5cb548a729022581fd5be67864a64e14f5/opentelemetry_instrumentation_boto3sqs-0.63b1-py3-none-any.whl", hash = "sha256:de2b93b47404bdc8572357abccadc72659c61b987c9212e451fd2d2f799f3e43", size = 10811, upload-time = "2026-05-21T16:35:15.92Z" }, + { url = "https://files.pythonhosted.org/packages/c9/96/956691648e27b7a621bdd2444a6938b79022abe60aa8ba4de43f65e40424/opentelemetry_instrumentation_boto3sqs-0.66b1-py3-none-any.whl", hash = "sha256:71cee26e1bd5d7fda6bf41afb427937d8d91115b7fb1699691a8c63857a14646", size = 10707, upload-time = "2026-10-06T17:35:23.041Z" }, ] [[package]] name = "opentelemetry-instrumentation-botocore" -version = "0.63b1" +version = "0.66b1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -985,14 +1017,14 @@ dependencies = [ { name = "opentelemetry-semantic-conventions" }, { name = "wrapt" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/f7/25/14c6be1107abad41ff326e16559467f170f6cc1227707be083e64f26e717/opentelemetry_instrumentation_botocore-0.63b1.tar.gz", hash = "sha256:ec141a0ef42682c484283c896d124e5fa975dcf5d8ffef7fd90ec7f83c094afb", size = 125068, upload-time = "2026-05-21T16:36:23.124Z" } +sdist = { url = "https://files.pythonhosted.org/packages/4d/f6/f648150c2bf30784b4ff448c15a6b5ad804ac41b91362ebe023ce14b88c3/opentelemetry_instrumentation_botocore-0.66b1.tar.gz", hash = "sha256:c601923e40aa008f4c0466b714c112fe47da07adb72ae6c69e2ac95992bcd66e", size = 129133, upload-time = "2026-10-06T17:36:18.898Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/b5/c2/ecca2a9ca7acff34c5ad97640105bdc2cd114ddca8a98fb7582934c4c0e6/opentelemetry_instrumentation_botocore-0.63b1-py3-none-any.whl", hash = "sha256:f05fd1f8b45fb5b12a940b68aad1e2329f440c6b678a3b9ba9fe5cc40223fb72", size = 36236, upload-time = "2026-05-21T16:35:17.007Z" }, + { url = "https://files.pythonhosted.org/packages/5d/6b/1f467c7e5725a8df6c2ed59446c5b9632bc480a525396a962ab67a4d7f28/opentelemetry_instrumentation_botocore-0.66b1-py3-none-any.whl", hash = "sha256:6352ceb4f204b13cd5b448f4df10de4a1a82f345fd0a81f8816a60e9ce3fdfc2", size = 36199, upload-time = "2026-10-06T17:35:23.976Z" }, ] [[package]] name = "opentelemetry-instrumentation-cassandra" -version = "0.63b1" +version = "0.66b1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -1000,28 +1032,28 @@ dependencies = [ { name = "opentelemetry-semantic-conventions" }, { name = "wrapt" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/b1/ae/1d83dc250c97fb7b48ec348ea2ea883d8d6c92b627ab6ba4d89389b37e32/opentelemetry_instrumentation_cassandra-0.63b1.tar.gz", hash = "sha256:79d18438b0ce1b50799ba7d79f05c769cb8e9b280d194741438ba14a1f4db90b", size = 8210, upload-time = "2026-05-21T16:36:24.351Z" } +sdist = { url = "https://files.pythonhosted.org/packages/9e/50/4bfb87450a6054bf5675b00a6c2c8cc469d7be47a9786931b87bc291c625/opentelemetry_instrumentation_cassandra-0.66b1.tar.gz", hash = "sha256:8c83b2644659c052cb5dbab21d2077e86569d6ef3e7412d03eb7f9cf6fa4f59d", size = 8906, upload-time = "2026-10-06T17:36:19.585Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/ae/3a/75be10de6fa7d02fcd43df6db67ab79a083fe8a5b718461869018a87fcf7/opentelemetry_instrumentation_cassandra-0.63b1-py3-none-any.whl", hash = "sha256:d4f73eda75a4a30956ba68050defab91f1c6a6f4059c4d797e35165726f88d19", size = 8298, upload-time = "2026-05-21T16:35:18.439Z" }, + { url = "https://files.pythonhosted.org/packages/62/f1/a5d515688d1dc596beab186c431995adb17af39920a068db21dac9146a59/opentelemetry_instrumentation_cassandra-0.66b1-py3-none-any.whl", hash = "sha256:c0138995fa99b6a37a6b66bfa714dcdae72ae5323d0dd17edae14135d7793578", size = 8435, upload-time = "2026-10-06T17:35:24.934Z" }, ] [[package]] name = "opentelemetry-instrumentation-celery" -version = "0.63b1" +version = "0.66b1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "opentelemetry-instrumentation" }, { name = "opentelemetry-semantic-conventions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/ec/23/3930fda593ff62c33649aa9cb90d8c48f0654f717715503bfbd4b3a4cb66/opentelemetry_instrumentation_celery-0.63b1.tar.gz", hash = "sha256:90d45267e7ad43fdc8643ec5f17f8f310adc301e2e075774efba18222ee7bad3", size = 15520, upload-time = "2026-05-21T16:36:25.017Z" } +sdist = { url = "https://files.pythonhosted.org/packages/d5/66/c2bbfbb7c90850dc52dee5d4968ab45a986093d2b77a631ff17e4107eefc/opentelemetry_instrumentation_celery-0.66b1.tar.gz", hash = "sha256:3b6c5539c8d4a060edbc0eb1f334ef909d0f9a5ecb7af545bdd73644e6e2e814", size = 15947, upload-time = "2026-10-06T17:36:20.175Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/23/8c/da3bdf3422feea847a4f19aebe8288bfa0b17b21b26cf0de444c6d2e9751/opentelemetry_instrumentation_celery-0.63b1-py3-none-any.whl", hash = "sha256:9e3888b3ed067196540ee1546155f69b757f0614dd1490930d86a5e021b28bd6", size = 13170, upload-time = "2026-05-21T16:35:19.56Z" }, + { url = "https://files.pythonhosted.org/packages/9e/73/b7597b2fede14cafe7122d1028bd6f648d9c1e049a61ab36481a4ed4f0df/opentelemetry_instrumentation_celery-0.66b1-py3-none-any.whl", hash = "sha256:145b5eece41331141edc8f454984238b05b107d7ead928b49e7a1916d5e48e99", size = 13480, upload-time = "2026-10-06T17:35:25.828Z" }, ] [[package]] name = "opentelemetry-instrumentation-confluent-kafka" -version = "0.63b1" +version = "0.66b1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -1029,14 +1061,14 @@ dependencies = [ { name = "opentelemetry-semantic-conventions" }, { name = "wrapt" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/bf/9e/c0fcc32ace111072d11d5c22f695ff0a27ecb3f30742703bc3b73e660138/opentelemetry_instrumentation_confluent_kafka-0.63b1.tar.gz", hash = "sha256:bd10c489380ea0ae227fa05cc5fc58ca20f3667d33ec550e1d809bffae2cc02d", size = 13073, upload-time = "2026-05-21T16:36:26.358Z" } +sdist = { url = "https://files.pythonhosted.org/packages/c6/db/0e65bffc09982f85a9de5f668ebdd3aadf491dd8f862dd7d97ff2758fe91/opentelemetry_instrumentation_confluent_kafka-0.66b1.tar.gz", hash = "sha256:834ae99cd024695946e7b72ce8f8060e0cc6b015c125b310f79ccd3069c585f4", size = 12978, upload-time = "2026-10-06T17:36:21.416Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/ac/d1/159e5869ce1cefdabb4d634590cd030d60bb0ede7a73b9deda7607cd4922/opentelemetry_instrumentation_confluent_kafka-0.63b1-py3-none-any.whl", hash = "sha256:d5acc47afb90f2e2cd3a35732acfde049963f5a22b16f0b5ea9e37dd694cdbae", size = 12841, upload-time = "2026-05-21T16:35:22.476Z" }, + { url = "https://files.pythonhosted.org/packages/aa/08/1ad195268ec09c4c320e0a12d37fa0d0b5eee46796a3b638c6bfe1c37dc1/opentelemetry_instrumentation_confluent_kafka-0.66b1-py3-none-any.whl", hash = "sha256:c3f067b0537817c1a8d311f8aeb0e510bceb2fdec98bc6223b4b7c9cea9d0608", size = 12775, upload-time = "2026-10-06T17:35:27.901Z" }, ] [[package]] name = "opentelemetry-instrumentation-dbapi" -version = "0.63b1" +version = "0.66b1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -1044,14 +1076,14 @@ dependencies = [ { name = "opentelemetry-semantic-conventions" }, { name = "wrapt" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/47/bf/2bb8048a3ba5686bb70e5d3d7dd2aa2b3d838ccd324e88557780f86b7635/opentelemetry_instrumentation_dbapi-0.63b1.tar.gz", hash = "sha256:406978ed56bcfc5fd246fd918e6b36d0f5de26fa396c78cf63326a7b530597c8", size = 19323, upload-time = "2026-05-21T16:36:27.036Z" } +sdist = { url = "https://files.pythonhosted.org/packages/23/b4/35c682a3a5762547cab6ac1d0f6e66a4e549cbbb852862903bb1523036fe/opentelemetry_instrumentation_dbapi-0.66b1.tar.gz", hash = "sha256:715be3080f644de2314d84388a73571acdbeca85bfbc7dc682f214c88cc18022", size = 19990, upload-time = "2026-10-06T17:36:22.281Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/d8/71/c7476e07d8bef5dfe5c301d1650f3ce15c4e3b7f4ffd4bbf6a0e3ebf3836/opentelemetry_instrumentation_dbapi-0.63b1-py3-none-any.whl", hash = "sha256:1bc842ddcacb7ec3622ef306ffdb3c584bf97df79d381e03604ea6eb23c63781", size = 14401, upload-time = "2026-05-21T16:35:23.941Z" }, + { url = "https://files.pythonhosted.org/packages/77/89/7f2ccd50975b66b2977a31bb489a2f0205b7fd033fc99046dcfa001c4252/opentelemetry_instrumentation_dbapi-0.66b1-py3-none-any.whl", hash = "sha256:a38043a8a907a321ae6b838f778ad19c8e78c0bfc2f336d6d30c5fdce112e88d", size = 14706, upload-time = "2026-10-06T17:35:28.831Z" }, ] [[package]] name = "opentelemetry-instrumentation-django" -version = "0.63b1" +version = "0.66b1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -1060,29 +1092,14 @@ dependencies = [ { name = "opentelemetry-semantic-conventions" }, { name = "opentelemetry-util-http" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/f7/37/90fd5f0dc4a2042dfdb609a9dbe42fde26b3690f9c33ece529b024251015/opentelemetry_instrumentation_django-0.63b1.tar.gz", hash = "sha256:f2071d2f92e4779c5a14dd452b0dfe426343599e6efa9d888304fb639a9f3101", size = 25565, upload-time = "2026-05-21T16:36:27.727Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/c8/14/3efdfb34393f6780ab3dc916dba9221e7be5f07eaa768c4575e14cea98fa/opentelemetry_instrumentation_django-0.63b1-py3-none-any.whl", hash = "sha256:909ea4afbb18f16eb811d7ac330ed0f6fda7765191d49bccb8cca38c4fbc005f", size = 19125, upload-time = "2026-05-21T16:35:25.29Z" }, -] - -[[package]] -name = "opentelemetry-instrumentation-elasticsearch" -version = "0.63b1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "opentelemetry-api" }, - { name = "opentelemetry-instrumentation" }, - { name = "opentelemetry-semantic-conventions" }, - { name = "wrapt" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/c0/05/80d0377b95f45f3276d8f43436c3e5addf5b0f6b8d7795257b22b8af1888/opentelemetry_instrumentation_elasticsearch-0.63b1.tar.gz", hash = "sha256:ef9cd756ca5635cd5212d8595f99dca17e61f72c305857468de17b385aa9e282", size = 14625, upload-time = "2026-05-21T16:36:29.031Z" } +sdist = { url = "https://files.pythonhosted.org/packages/e9/88/d0acbd7916aa3040a36486cedb60aa77c129c7029446fa6a00207345695c/opentelemetry_instrumentation_django-0.66b1.tar.gz", hash = "sha256:85b56193b6ce7b8db9c280c3ade4a4991601abc9ada4734c8911971423fd521f", size = 25233, upload-time = "2026-10-06T17:36:22.892Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/b9/08/c662c502ef1c08d13e55cf62f5fc25a410565018e8f04ec80835a6d84941/opentelemetry_instrumentation_elasticsearch-0.63b1-py3-none-any.whl", hash = "sha256:ed5b31ba284636ef3c91a1eb8d3e236b21e871612cb09306e98e08522be066d2", size = 11344, upload-time = "2026-05-21T16:35:26.407Z" }, + { url = "https://files.pythonhosted.org/packages/5b/c3/2739c248b60b2802b9e51d2a3373269f0ca3e16059ea4f1ca7370502118c/opentelemetry_instrumentation_django-0.66b1-py3-none-any.whl", hash = "sha256:23d1052940a025ae1dac70849b998cf9ba66731fa2b7e58254ab7dac5539a989", size = 18914, upload-time = "2026-10-06T17:35:30.052Z" }, ] [[package]] name = "opentelemetry-instrumentation-falcon" -version = "0.63b1" +version = "0.66b1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -1092,14 +1109,14 @@ dependencies = [ { name = "opentelemetry-util-http" }, { name = "packaging" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/4f/a2/743ee3159707e795390230d280b9d582cb854018331641b3aecd9915a9e3/opentelemetry_instrumentation_falcon-0.63b1.tar.gz", hash = "sha256:9563d71232de9a17aa95ba75666ac123a0bebc27383e1656ce13b52e07f2123f", size = 16828, upload-time = "2026-05-21T16:36:30.967Z" } +sdist = { url = "https://files.pythonhosted.org/packages/75/99/b875b6ee409fabb8e5ea770ebed465ba01719896f6487ce4715e5817eb22/opentelemetry_instrumentation_falcon-0.66b1.tar.gz", hash = "sha256:08a1304c2e7a50888e2161ea31f87df2455a763b1166b651540caff1d722cddc", size = 16634, upload-time = "2026-10-06T17:36:24.106Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/f1/c6/1616c45e4757e9930b14f7213512d8a3c7b32b9495cf5facc181ad62979b/opentelemetry_instrumentation_falcon-0.63b1-py3-none-any.whl", hash = "sha256:9079bb1721cb429ba8f03a8f9b522240d71cf03271d68096e898fd48e09b9553", size = 13293, upload-time = "2026-05-21T16:35:27.556Z" }, + { url = "https://files.pythonhosted.org/packages/20/34/ce53a58facd9b9ddc1f2db07c76649a8fcd0e8a92ece53f1e02258e06386/opentelemetry_instrumentation_falcon-0.66b1-py3-none-any.whl", hash = "sha256:8cb10d952e1897b0907a05a0d1efa8bce311614d244a62e7d6b10b02e3f64db5", size = 13226, upload-time = "2026-10-06T17:35:31.827Z" }, ] [[package]] name = "opentelemetry-instrumentation-fastapi" -version = "0.63b1" +version = "0.66b1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -1108,14 +1125,14 @@ dependencies = [ { name = "opentelemetry-semantic-conventions" }, { name = "opentelemetry-util-http" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/32/d6/0c128fac2e34b7d526a8d3c6edc45b875a97f8a987861b00511151b6337d/opentelemetry_instrumentation_fastapi-0.63b1.tar.gz", hash = "sha256:cc42dff56c96d0a2921510c4abab2a4c2e27fe64b26dc1254727fb550df100ba", size = 25387, upload-time = "2026-05-21T16:36:32.071Z" } +sdist = { url = "https://files.pythonhosted.org/packages/5d/2a/cd4125b7acbea2ed17f1d31b58c184cb0a79fcb5541ceb4de90ffc6d8c01/opentelemetry_instrumentation_fastapi-0.66b1.tar.gz", hash = "sha256:584cf9d2c4417ff8b2d6ff2bc606bfe13c8b3456018bf94f50f2cf658492505b", size = 26634, upload-time = "2026-10-06T17:36:25.157Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/b1/3d/2eae63f13f36d7a8ab5bf03d06ecaf169c2069b524547f24947be6d92094/opentelemetry_instrumentation_fastapi-0.63b1-py3-none-any.whl", hash = "sha256:52ee2cde9a2ac094bdd45d79f85860e03a972928a2553006071fe61d94cf7281", size = 12795, upload-time = "2026-05-21T16:35:28.68Z" }, + { url = "https://files.pythonhosted.org/packages/75/70/676928d537978acc7bff2ac8657bd0836ba608ffc8f65455238f1fa2bd0f/opentelemetry_instrumentation_fastapi-0.66b1-py3-none-any.whl", hash = "sha256:97f8ac8fd7537517f9e6988bd0aca04bfa5aad564bcd46c245530739e2be72d1", size = 14216, upload-time = "2026-10-06T17:35:32.827Z" }, ] [[package]] name = "opentelemetry-instrumentation-flask" -version = "0.63b1" +version = "0.66b1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -1125,14 +1142,14 @@ dependencies = [ { name = "opentelemetry-util-http" }, { name = "packaging" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/fd/8d/78ad1354ec4df8ec2817ff86fac16cf1c9f80cce9e17797e0f515bee1943/opentelemetry_instrumentation_flask-0.63b1.tar.gz", hash = "sha256:60dd3c54107fad5b2615f811a45a8600259a78e4105034f87741b092c2011f89", size = 23873, upload-time = "2026-05-21T16:36:32.857Z" } +sdist = { url = "https://files.pythonhosted.org/packages/c0/fc/c1a692ceb7ed56818f2f4f88044b5a0895b6666da954dbd566fdf265195b/opentelemetry_instrumentation_flask-0.66b1.tar.gz", hash = "sha256:10f788aff95236f0dbaaa066687283bf6345bb3c77bbb437f0fb67cb6222d5eb", size = 23876, upload-time = "2026-10-06T17:36:25.763Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/57/c1/84f17990829744c4d53d504f4d0623a4ad0cd9c11ca1052ff77d80d547c9/opentelemetry_instrumentation_flask-0.63b1-py3-none-any.whl", hash = "sha256:482f073083845f9f45200f2384de0018afab90fbe666c114ac71b7a3dc033264", size = 15071, upload-time = "2026-05-21T16:35:29.696Z" }, + { url = "https://files.pythonhosted.org/packages/52/65/7aa45ca677c51afb185bcd5e7ed121c84b07b2c566a72948a9e56fd16ae7/opentelemetry_instrumentation_flask-0.66b1-py3-none-any.whl", hash = "sha256:2933e71b94cc9e8e943e648d872fd3dead9cdb61295dc6deffd5d6fa8f27a39b", size = 14961, upload-time = "2026-10-06T17:35:34.002Z" }, ] [[package]] name = "opentelemetry-instrumentation-grpc" -version = "0.63b1" +version = "0.66b1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -1140,14 +1157,14 @@ dependencies = [ { name = "opentelemetry-semantic-conventions" }, { name = "wrapt" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/db/84/7c297486a6e9b99db041e5bd47f054aab29422be69659272908e292ed57a/opentelemetry_instrumentation_grpc-0.63b1.tar.gz", hash = "sha256:48d93e06872208a15ed720555ded9f366039924f41f3e16ea0da6ec937701e84", size = 31746, upload-time = "2026-05-21T16:36:33.561Z" } +sdist = { url = "https://files.pythonhosted.org/packages/d7/64/745e28d64fa07d3416fee6b31c2bffbb0e6a506f1d91886793310538306c/opentelemetry_instrumentation_grpc-0.66b1.tar.gz", hash = "sha256:2055c8584ea67cebe9e39a13dca000cbba17c52366aa2aa7c6655fe454ec13b4", size = 31922, upload-time = "2026-10-06T17:36:26.62Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/fd/2a/f4ad01d283550affaf3fa434671e3f6625095a4de90b9156bebaa4426aba/opentelemetry_instrumentation_grpc-0.63b1-py3-none-any.whl", hash = "sha256:40d30a2c5e97f90a28a8c4e688e368b4dcacc7654d358489cea92744311ff8d9", size = 24244, upload-time = "2026-05-21T16:35:31.098Z" }, + { url = "https://files.pythonhosted.org/packages/88/be/68be2da884ec05e42a0efefdfef373a7cfee55a58fb4fe3cae455d0fb61a/opentelemetry_instrumentation_grpc-0.66b1-py3-none-any.whl", hash = "sha256:8d0b0594bf86ece324367b4614c14c9a1893d65f0c7f2366a8131b45fc9ad474", size = 24261, upload-time = "2026-10-06T17:35:35.19Z" }, ] [[package]] name = "opentelemetry-instrumentation-httpx" -version = "0.63b1" +version = "0.66b1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -1156,99 +1173,84 @@ dependencies = [ { name = "opentelemetry-util-http" }, { name = "wrapt" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/02/27/c2b4335bca030e893acbe5ff2b4f434868773bf94508be7e6bf5af981b24/opentelemetry_instrumentation_httpx-0.63b1.tar.gz", hash = "sha256:f41ec82f25c3abcdada621052db3e5fd648e3b43d55eec4b9c0c5d3ecb7b4ff4", size = 23557, upload-time = "2026-05-21T16:36:34.583Z" } +sdist = { url = "https://files.pythonhosted.org/packages/de/50/41544799b043d14fdfa6fe62fa2518eaba22793fce03e9abde930b92e671/opentelemetry_instrumentation_httpx-0.66b1.tar.gz", hash = "sha256:5865a72c68098c85955a271ab8744b480a36e3ee492d35b8cadb93c7c4dbb618", size = 26637, upload-time = "2026-10-06T17:36:27.265Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/ba/b8/f536780996195c3b9f2354998554671e05a7a262df8c043f63fe9e5a6f0b/opentelemetry_instrumentation_httpx-0.63b1-py3-none-any.whl", hash = "sha256:14df6e99d81be9a8cd238f6639b6fa52404c4d3ce219058fcb5dc8c0f2211f86", size = 16336, upload-time = "2026-05-21T16:35:32.221Z" }, + { url = "https://files.pythonhosted.org/packages/4f/c6/e5682b1bfb320b32505e88255c34ae1e99fe9fb220cc465c244e91967eac/opentelemetry_instrumentation_httpx-0.66b1-py3-none-any.whl", hash = "sha256:0342a4002c6dbc6c4bf22cc7e698f50f5c8b77f63325c6f40c94ab87e016bf4d", size = 17723, upload-time = "2026-10-06T17:35:36.501Z" }, ] [[package]] name = "opentelemetry-instrumentation-jinja2" -version = "0.63b1" +version = "0.66b1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "opentelemetry-instrumentation" }, { name = "wrapt" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/02/ad/997b98d6894deec4f129961310a1ee904f502f7282c5cc7781f30d7ba708/opentelemetry_instrumentation_jinja2-0.63b1.tar.gz", hash = "sha256:5015c8fb1797f3d4c7097774734eb31e3c9e38fb3716a0c4a83a46d4fb63dd1a", size = 8350, upload-time = "2026-05-21T16:36:35.448Z" } +sdist = { url = "https://files.pythonhosted.org/packages/58/cd/0803b416d7650494ad4ea39086806588d095ffff984972696604dce37b55/opentelemetry_instrumentation_jinja2-0.66b1.tar.gz", hash = "sha256:f50a78d1a7542d2d150b11d2c507dd7e617e5d943baa06b4ed2d727784bcba82", size = 8307, upload-time = "2026-10-06T17:36:28.172Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/1d/cf/6f378b7a4c4a7b86fec8f5e06c0bffc05bf8d00330c11a44f04f54f4526e/opentelemetry_instrumentation_jinja2-0.63b1-py3-none-any.whl", hash = "sha256:7222883787ed85f174cfd46684b5f27c3d3b65b3bac77bb017a24a5f523e03b9", size = 8568, upload-time = "2026-05-21T16:35:33.378Z" }, + { url = "https://files.pythonhosted.org/packages/4d/de/8fa84e967770baaeb4a5d7ab574d0abe442e8b562a1fcc4e071e5d12f222/opentelemetry_instrumentation_jinja2-0.66b1-py3-none-any.whl", hash = "sha256:5b9a119a650dd91fa07ba0e0e7c60a872ea94babd9d2f88cddad3f9a80131f94", size = 8552, upload-time = "2026-10-06T17:35:37.8Z" }, ] [[package]] name = "opentelemetry-instrumentation-kafka-python" -version = "0.63b1" +version = "0.66b1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "opentelemetry-instrumentation" }, { name = "opentelemetry-semantic-conventions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/f1/33/260f8bdc56a069ebedd93f608b512d17acea28fb96c1493b669f4a523509/opentelemetry_instrumentation_kafka_python-0.63b1.tar.gz", hash = "sha256:b572bd9f02b5efe18292442190924bef9b86a51436c9d120745a950a584fe5f8", size = 10528, upload-time = "2026-05-21T16:36:36.6Z" } +sdist = { url = "https://files.pythonhosted.org/packages/66/b1/439e472e4af34450eab132e21e21678ed3993ba662a4ff33dbad7c5b8c12/opentelemetry_instrumentation_kafka_python-0.66b1.tar.gz", hash = "sha256:68574ccc6984be59b8856dea9546ad83d15cf6c2582a674d0e7bdd7d3952a1f4", size = 10708, upload-time = "2026-10-06T17:36:28.963Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/c9/da/185f6cd1c542516fd004e44d62e85d7ca25cbcac5abf14105092aed7c6e2/opentelemetry_instrumentation_kafka_python-0.63b1-py3-none-any.whl", hash = "sha256:786cf0416a04d9b502f96560ae2ad94a14b0c11e73bd779f9f3a0fe2b78a0346", size = 10732, upload-time = "2026-05-21T16:35:34.494Z" }, + { url = "https://files.pythonhosted.org/packages/65/e0/7d7f4fab109b3ace57b8a07eb87d9b5f11dd02275fcb2344850f9114920f/opentelemetry_instrumentation_kafka_python-0.66b1-py3-none-any.whl", hash = "sha256:4fec4441aad9116605f0523b656c694c3d38cf7704aca3a5fd26267a3cf10a91", size = 10323, upload-time = "2026-10-06T17:35:38.868Z" }, ] [[package]] name = "opentelemetry-instrumentation-logging" -version = "0.63b1" +version = "0.66b1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "opentelemetry-instrumentation" }, { name = "opentelemetry-semantic-conventions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/d1/cf/119381b1ae446fb07921a452e3a8e1887aa87f9856225f9829958dc20063/opentelemetry_instrumentation_logging-0.63b1.tar.gz", hash = "sha256:aa57d1bcb8931186b5dde565e9c17c572cf02412572d962da5b1a17ee5637d2c", size = 19823, upload-time = "2026-05-21T16:36:37.276Z" } +sdist = { url = "https://files.pythonhosted.org/packages/28/ca/0fcf525f238f4ab9df3a6d0423fb057085ea39a3e79ac912fef3d5fa16b8/opentelemetry_instrumentation_logging-0.66b1.tar.gz", hash = "sha256:2250240ecb1fce36939f64eafd988832338684564fb4c7b401c9b9af0ee11d46", size = 20353, upload-time = "2026-10-06T17:36:29.546Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/b6/71/1ba447311adf33023be14a1a309852c4cf74219f095d0055a54c1824d9ff/opentelemetry_instrumentation_logging-0.63b1-py3-none-any.whl", hash = "sha256:6b3aac8d18bc897468814d5ce4ed00f9d43588c583b4ba2288267e191b96d944", size = 15993, upload-time = "2026-05-21T16:35:35.851Z" }, + { url = "https://files.pythonhosted.org/packages/2e/7b/76bea1e80787848a9ac9882a598cbf1e761f16cebdb399d0e675221e34a0/opentelemetry_instrumentation_logging-0.66b1-py3-none-any.whl", hash = "sha256:f13761110c52eecae9d7debedb0f88b46acc248c20437e97c2a5b3a2b4f96a02", size = 15928, upload-time = "2026-10-06T17:35:39.915Z" }, ] [[package]] name = "opentelemetry-instrumentation-mysql" -version = "0.63b1" +version = "0.66b1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "opentelemetry-instrumentation" }, { name = "opentelemetry-instrumentation-dbapi" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/ef/5e/b07f70e94848e2514e4b0eaa5c40f5a72c37096d8267a029387ebe80a5eb/opentelemetry_instrumentation_mysql-0.63b1.tar.gz", hash = "sha256:cd3ef7a277e44093ca3d7df4a6fa4d0e588331ae1d908f5e6fc3084529f2c498", size = 10151, upload-time = "2026-05-21T16:36:37.966Z" } +sdist = { url = "https://files.pythonhosted.org/packages/70/8c/75263fcd424a129202b47aff33a561c58c181c0494ed6b9f426e926c506b/opentelemetry_instrumentation_mysql-0.66b1.tar.gz", hash = "sha256:5b7b20af1433269ca48b25a4e977e07a57f2db71c319a918cf68ba541ca65bfe", size = 10713, upload-time = "2026-10-06T17:36:30.164Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/76/60/e6d8c9ae85d994256a80850603b9aca157bcae43033097868c35be8bb0e6/opentelemetry_instrumentation_mysql-0.63b1-py3-none-any.whl", hash = "sha256:69e67e78c87b8d47b7575e79cb6872cef734b02783da37250566c86d934f9477", size = 9847, upload-time = "2026-05-21T16:35:37.295Z" }, + { url = "https://files.pythonhosted.org/packages/59/ee/ca535b3364dd33d1bfe15b2e2d247556fdcf7629715850c1c216310bfc64/opentelemetry_instrumentation_mysql-0.66b1-py3-none-any.whl", hash = "sha256:9f6ae7627812a15fddf035f3f2862c7c04fbcc23c98774a8a09d40c746a335d0", size = 9925, upload-time = "2026-10-06T17:35:40.886Z" }, ] [[package]] name = "opentelemetry-instrumentation-mysqlclient" -version = "0.63b1" +version = "0.66b1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "opentelemetry-instrumentation" }, { name = "opentelemetry-instrumentation-dbapi" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/ae/71/66741c53a7a67079dc85d19f399d18dae6acaa67603dc817aa8237710da8/opentelemetry_instrumentation_mysqlclient-0.63b1.tar.gz", hash = "sha256:4dc64ba88e4a2ab89e6b77d0f6f79153fb569ffc76f6c4cdb2d0dec643cb5bf0", size = 9779, upload-time = "2026-05-21T16:36:38.612Z" } +sdist = { url = "https://files.pythonhosted.org/packages/c2/2e/9825cfbc17fa4bef40ce464dfabff7cd79200a69bf0129441cb8564b39a2/opentelemetry_instrumentation_mysqlclient-0.66b1.tar.gz", hash = "sha256:283836cfa05c42450922ca54508b0b8762a207351d97958225fc728cf83ad9ba", size = 10430, upload-time = "2026-10-06T17:36:30.716Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/df/d1/7413e9df599d83d2d391d0acf05b3da090e8e5b6d4ee0212bd4677132d2c/opentelemetry_instrumentation_mysqlclient-0.63b1-py3-none-any.whl", hash = "sha256:24064533436841bef9272085e3fe2c20886373a82ed21d5a2a331535c368556a", size = 9737, upload-time = "2026-05-21T16:35:38.668Z" }, -] - -[[package]] -name = "opentelemetry-instrumentation-openai-agents-v2" -version = "0.1.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "opentelemetry-api" }, - { name = "opentelemetry-instrumentation" }, - { name = "opentelemetry-semantic-conventions" }, - { name = "opentelemetry-util-genai" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/00/15/b6a303454d2800d772cdebc490c1d598d06d0e541619db80195eb9ea85c6/opentelemetry_instrumentation_openai_agents_v2-0.1.0.tar.gz", hash = "sha256:1033f4b261ce07f65d197ac0e9c499302c805eae987a6cc4e7f99bb279363477", size = 22423, upload-time = "2025-10-15T19:04:59.912Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/cd/0a/b6f47734e1d7f936cbc52ef8e673d3e08d9c3c8a13d9549c03f978758076/opentelemetry_instrumentation_openai_agents_v2-0.1.0-py3-none-any.whl", hash = "sha256:e4e3dfba32bd6eeee0624eca9be54341ab7cc4f7a3bb895354f2f9d6f7afe2f3", size = 25002, upload-time = "2025-10-15T19:04:58.562Z" }, + { url = "https://files.pythonhosted.org/packages/df/f2/e36734ebdaf684205236dda70722441d8b91c5e06b7d6956e8953a294c18/opentelemetry_instrumentation_mysqlclient-0.66b1-py3-none-any.whl", hash = "sha256:a451dc08832bfc01aa53ba30007384ec7b47c8f09db24c414a5aa0da9479e252", size = 9735, upload-time = "2026-10-06T17:35:41.889Z" }, ] [[package]] name = "opentelemetry-instrumentation-pika" -version = "0.63b1" +version = "0.66b1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -1257,28 +1259,28 @@ dependencies = [ { name = "packaging" }, { name = "wrapt" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/be/eb/088c98cf73ba357f052cdf17dc5846f940fcd50c7dbe5d9958dfea364aeb/opentelemetry_instrumentation_pika-0.63b1.tar.gz", hash = "sha256:c74e23b2370283890d8094bc07686731ba6a7a4bb89a26dc3d6c86ae988fd8d0", size = 13247, upload-time = "2026-05-21T16:36:39.273Z" } +sdist = { url = "https://files.pythonhosted.org/packages/ec/e1/d0f21a8def168e8b45b90e4d31679aada2821fd69203a90dde2d1b4d4346/opentelemetry_instrumentation_pika-0.66b1.tar.gz", hash = "sha256:1a6f24e65db23dda8539bde273bcf190724e38f6b47ac16e10d3592356a3d404", size = 14023, upload-time = "2026-10-06T17:36:31.271Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/28/b3/57b63669cb47ec38575194e79dc3b3fc753646fd11e6cc925709aa9f81a9/opentelemetry_instrumentation_pika-0.63b1-py3-none-any.whl", hash = "sha256:14ab56ed06c0c8c922af72cf214eae6513da83be7b6987a17e4f10fa0820d7c2", size = 12681, upload-time = "2026-05-21T16:35:39.726Z" }, + { url = "https://files.pythonhosted.org/packages/e2/91/fa2f28441a86a8cb9f4c5eb37310197ef91190a3677fb59b73f23e8754dd/opentelemetry_instrumentation_pika-0.66b1-py3-none-any.whl", hash = "sha256:1a5ea62f37537deefbb6673a2804421e82017deaf967053260201463fa973b54", size = 12574, upload-time = "2026-10-06T17:35:42.853Z" }, ] [[package]] name = "opentelemetry-instrumentation-psycopg2" -version = "0.63b1" +version = "0.66b1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "opentelemetry-instrumentation" }, { name = "opentelemetry-instrumentation-dbapi" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/0d/26/0a771790d0a8241514cbf34c1aa478a03dd9bb6340b02b561fb9ceb80414/opentelemetry_instrumentation_psycopg2-0.63b1.tar.gz", hash = "sha256:060163f959415580baf87e73fe76c21380bdcb56af947fe5d7c8eeacfc30eb79", size = 12065, upload-time = "2026-05-21T16:36:40.634Z" } +sdist = { url = "https://files.pythonhosted.org/packages/fd/03/2b5babd54a905602097e37ce5fc0f20d99116625712363843ebf802410ef/opentelemetry_instrumentation_psycopg2-0.66b1.tar.gz", hash = "sha256:f7454114191930b854fa7a176d4009d727084ab2fb3bf4016c8ab0719ac89a6e", size = 12967, upload-time = "2026-10-06T17:36:32.591Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/40/51/acf4a31805240cf89272441c8a4f18a0d465f44a9a683eaa6c11a2997415/opentelemetry_instrumentation_psycopg2-0.63b1-py3-none-any.whl", hash = "sha256:2ddc692a593104dcfe408633ce56c1cfd7d519885de0864122e20c7743f09bbb", size = 10788, upload-time = "2026-05-21T16:35:41.784Z" }, + { url = "https://files.pythonhosted.org/packages/6f/7a/378b0f112d1219ff2ca04f0f491811923abcb832ccb71911c5ad12694c4a/opentelemetry_instrumentation_psycopg2-0.66b1-py3-none-any.whl", hash = "sha256:e69ef26a8e50d7ac2149a89b5e0f66c1fe5c06c3355a2068b845d83742139348", size = 11058, upload-time = "2026-10-06T17:35:44.612Z" }, ] [[package]] name = "opentelemetry-instrumentation-pymemcache" -version = "0.63b1" +version = "0.66b1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -1286,42 +1288,42 @@ dependencies = [ { name = "opentelemetry-semantic-conventions" }, { name = "wrapt" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/67/c7/3717e7ee5c983b6fa2e499dd520509ef96f651270fe32578bb353a581a5e/opentelemetry_instrumentation_pymemcache-0.63b1.tar.gz", hash = "sha256:cd577e9d5ffbbae9948eb4a7681d500aa8d64a30b316f0b54dcb9bbc1b397a84", size = 10590, upload-time = "2026-05-21T16:36:41.337Z" } +sdist = { url = "https://files.pythonhosted.org/packages/50/13/21cb0a84d78ca163f4b3ba5682009341ad462a50e4197bc9a72e1a28a61a/opentelemetry_instrumentation_pymemcache-0.66b1.tar.gz", hash = "sha256:62e91a2924ad6c4efded0a157c3c0d12c2d6a09b6a6f21bdaeafec0f12b83177", size = 11231, upload-time = "2026-10-06T17:36:33.205Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/ee/1f/257038a4a7eb54399c5ddad0891a4b11d89e70f77ce9a0380365065a3fd0/opentelemetry_instrumentation_pymemcache-0.63b1-py3-none-any.whl", hash = "sha256:b77428621e1ea2a48a772d35d9a53fb902bd525514679cad215c33d4310de4bf", size = 8854, upload-time = "2026-05-21T16:35:43.367Z" }, + { url = "https://files.pythonhosted.org/packages/8b/92/e5cc7ed34b5844885d34fdacd17e462f050351e2d5c928005dc3d3c80123/opentelemetry_instrumentation_pymemcache-0.66b1-py3-none-any.whl", hash = "sha256:56c211af460634e76bdf2eec98671f0283d8594ba0e59dfe1c84af8f9706489e", size = 9033, upload-time = "2026-10-06T17:35:45.56Z" }, ] [[package]] name = "opentelemetry-instrumentation-pymongo" -version = "0.63b1" +version = "0.66b1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "opentelemetry-instrumentation" }, { name = "opentelemetry-semantic-conventions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/06/b2/94c180359165abe62e829250bc6ac6b7daa2334b3c505bad64f1c64f18ab/opentelemetry_instrumentation_pymongo-0.63b1.tar.gz", hash = "sha256:8c0ae185b59dcb45c80bf90d4ffda5fcc6337dbba11de40306ffd69459e476fa", size = 10208, upload-time = "2026-05-21T16:36:41.961Z" } +sdist = { url = "https://files.pythonhosted.org/packages/59/6e/eb061804cbc160251ca234494529e4ef41ad4c4cdb8c12f9e262af8b2e3b/opentelemetry_instrumentation_pymongo-0.66b1.tar.gz", hash = "sha256:3317c1cf5e68e0896e361f3ed2eeddba3388836f2c64191257ec0e5e69b16a09", size = 11274, upload-time = "2026-10-06T17:36:33.78Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/04/b9/47b8d0f52d81d7661debebb11f4fdd1ab869d694089711c1ac8988456364/opentelemetry_instrumentation_pymongo-0.63b1-py3-none-any.whl", hash = "sha256:0d8dd55b2522eda4a7093da8b5f47fae9a3235fb2786bc14c161d5999a66320d", size = 10290, upload-time = "2026-05-21T16:35:44.634Z" }, + { url = "https://files.pythonhosted.org/packages/0c/86/fd19f36e78a65d10e4f9f2dd29137c7eb7f493eaabc198720b39326f67f1/opentelemetry_instrumentation_pymongo-0.66b1-py3-none-any.whl", hash = "sha256:a1b8ee770f769226b4b98c972d2ebfa770dbf81a230e7bbaa662c85e4a122ee0", size = 10626, upload-time = "2026-10-06T17:35:46.453Z" }, ] [[package]] name = "opentelemetry-instrumentation-pymysql" -version = "0.63b1" +version = "0.66b1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "opentelemetry-instrumentation" }, { name = "opentelemetry-instrumentation-dbapi" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/8b/b6/1f1d8ef1202c3c76592245b3d1b0c15c8b196d65887eb29e07958833f0b5/opentelemetry_instrumentation_pymysql-0.63b1.tar.gz", hash = "sha256:2cf6a24e136b5b0c3f6e59675fc44b42ad2b97474b075a82859f9868a9252648", size = 9735, upload-time = "2026-05-21T16:36:43.297Z" } +sdist = { url = "https://files.pythonhosted.org/packages/5f/27/7c99b258cc8cd278fb6e61972b3215bd7788d4d588141a0c6d64263eb5e0/opentelemetry_instrumentation_pymysql-0.66b1.tar.gz", hash = "sha256:c6cf3da2834d7ca545ccaf714d3b79d883fbe0057df7e3ac5b8096ff7232bf48", size = 10331, upload-time = "2026-10-06T17:36:35.092Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/e8/0f/42c1f519f061cef0d72171252cfd47e56f8d4ed0e77a0285ae8ecffb0822/opentelemetry_instrumentation_pymysql-0.63b1-py3-none-any.whl", hash = "sha256:6b54b83c86ac6c2e8dae642bbee4894e2283ceb5da23d571f1abb7060f7b62f4", size = 9719, upload-time = "2026-05-21T16:35:47.147Z" }, + { url = "https://files.pythonhosted.org/packages/80/57/3c8b1629036f94a8d025b492c881333a8b63e62d2ef5d43f31133fb47143/opentelemetry_instrumentation_pymysql-0.66b1-py3-none-any.whl", hash = "sha256:aa1d1e7d9a1a63341db24e990c5deb7554b3912f81c5e8ba80700d2c76517641", size = 9717, upload-time = "2026-10-06T17:35:48.505Z" }, ] [[package]] name = "opentelemetry-instrumentation-pyramid" -version = "0.63b1" +version = "0.66b1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -1331,14 +1333,14 @@ dependencies = [ { name = "opentelemetry-util-http" }, { name = "wrapt" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/5d/10/1a6708a065ce729eded5795b157a3802deada15715f51fc4632d26069ce0/opentelemetry_instrumentation_pyramid-0.63b1.tar.gz", hash = "sha256:7184b7b9f3def4cd60460539e9fbe0f1423319a32ce3998a132f743943a47109", size = 16719, upload-time = "2026-05-21T16:36:43.962Z" } +sdist = { url = "https://files.pythonhosted.org/packages/ac/da/d64573c187d32f6ba5c4b7ce1dc9929e1cf6ab5a28007170565c69756dd8/opentelemetry_instrumentation_pyramid-0.66b1.tar.gz", hash = "sha256:769092e65dfc9254272ce62e0c2e1f45289bb976c386ae2b7ed9c3d029404e82", size = 16857, upload-time = "2026-10-06T17:36:35.685Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/b0/cf/b4aa7ba996207ebccfdba9a97120a8d86f852d170865877909b91952af1e/opentelemetry_instrumentation_pyramid-0.63b1-py3-none-any.whl", hash = "sha256:70d74b5e798873ad3450e0c699c1013acbea5d8b2fe4c2096c674ebaf6d13fb9", size = 13603, upload-time = "2026-05-21T16:35:48.684Z" }, + { url = "https://files.pythonhosted.org/packages/b0/1c/ea115e73b7a08a5742358cc3d9a1c4edd90a7a5c4ba7870331c53be007fb/opentelemetry_instrumentation_pyramid-0.66b1-py3-none-any.whl", hash = "sha256:20f0ef859f96a95e15445d8fe695889a9aab926292e7503129e4f3133ca88356", size = 13605, upload-time = "2026-10-06T17:35:49.387Z" }, ] [[package]] name = "opentelemetry-instrumentation-redis" -version = "0.63b1" +version = "0.66b1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -1346,28 +1348,28 @@ dependencies = [ { name = "opentelemetry-semantic-conventions" }, { name = "wrapt" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/e6/58/2a91453c70943d6af4b5f9f1c232d69e6093800f95349ff5f1f8a89cf6ba/opentelemetry_instrumentation_redis-0.63b1.tar.gz", hash = "sha256:28d235159df43cc2bc8779af5c602afad1e08603fff75ac8ca34dd1bf30a9cb9", size = 16711, upload-time = "2026-05-21T16:36:44.662Z" } +sdist = { url = "https://files.pythonhosted.org/packages/39/f7/8a7f4d2178a79b4cca971836491d75884b8f2b3fcd0dc9a3d521ca65e7bd/opentelemetry_instrumentation_redis-0.66b1.tar.gz", hash = "sha256:d6cc6aa473e23692ae1be9011e2cb3ae5894376158533a71f9710e1fb0906dc7", size = 18060, upload-time = "2026-10-06T17:36:36.289Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/f5/17/33c21901325f6bf96939f355db174627c148c83211d0412622d4066f560d/opentelemetry_instrumentation_redis-0.63b1-py3-none-any.whl", hash = "sha256:f0e51c4006f68e340abbf28a7995feff004de78649697cbdf3bac0072cacd082", size = 14539, upload-time = "2026-05-21T16:35:49.995Z" }, + { url = "https://files.pythonhosted.org/packages/99/22/19286da994ae57c78ecc3f4bd692855ccedc54cd9b05ce56592ee28964c3/opentelemetry_instrumentation_redis-0.66b1-py3-none-any.whl", hash = "sha256:4e36651d553e63c8e8f4068d8a2362ae35ac5c9bbef53c27a0fcb96d9092dbb1", size = 14885, upload-time = "2026-10-06T17:35:50.394Z" }, ] [[package]] name = "opentelemetry-instrumentation-remoulade" -version = "0.63b1" +version = "0.66b1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "opentelemetry-instrumentation" }, { name = "opentelemetry-semantic-conventions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/47/f8/d19489aead7945f30ad125246c588c1de108d5261ca12834d972879af14a/opentelemetry_instrumentation_remoulade-0.63b1.tar.gz", hash = "sha256:99d694d0c013c36ecf4877bc6f99c93e009d881a7c1108ce25149482785e43c1", size = 8082, upload-time = "2026-05-21T16:36:45.367Z" } +sdist = { url = "https://files.pythonhosted.org/packages/39/23/c280c122d2181228ea7fabd2ea7a3228009b441138787d3d950d49024b88/opentelemetry_instrumentation_remoulade-0.66b1.tar.gz", hash = "sha256:e0a2d022f1ee2b6541a0f3707797d3f72b6d2c0c617eb490446f225155823a08", size = 8064, upload-time = "2026-10-06T17:36:36.902Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/87/67/9de2fc9c7d617f5327fe1f80fa8a94652f2ceb5bec5bdd071b4bd0eda125/opentelemetry_instrumentation_remoulade-0.63b1-py3-none-any.whl", hash = "sha256:80013f48757f38b89096f66a5bc983c241806421553fd41075faa72595008bcb", size = 8997, upload-time = "2026-05-21T16:35:51.136Z" }, + { url = "https://files.pythonhosted.org/packages/9b/2d/4fddb8dba6760cbafbc91a4c5d97f19477496d17a2c5d91fc8954ac08b5f/opentelemetry_instrumentation_remoulade-0.66b1-py3-none-any.whl", hash = "sha256:900eb6afe12f7c0add765529c2017b431238cb819b57c62fb268b0ea723cc00e", size = 8971, upload-time = "2026-10-06T17:35:51.452Z" }, ] [[package]] name = "opentelemetry-instrumentation-requests" -version = "0.63b1" +version = "0.66b1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -1375,14 +1377,14 @@ dependencies = [ { name = "opentelemetry-semantic-conventions" }, { name = "opentelemetry-util-http" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/7b/39/7b14ef15c7c74b0da7d32b449732795a5cf7495897b72fc0b48280b96f50/opentelemetry_instrumentation_requests-0.63b1.tar.gz", hash = "sha256:513fcaa3d93debbdb359c00ce1a137a34a89ee908c51ac43beb7e8c18ac2b3cd", size = 18098, upload-time = "2026-05-21T16:36:46.02Z" } +sdist = { url = "https://files.pythonhosted.org/packages/08/62/dcca0b7a2008675056040c61b70d37b5a24439613c7822068908ad3255ae/opentelemetry_instrumentation_requests-0.66b1.tar.gz", hash = "sha256:28578f72e68e3a5be3226c618ac9570ed360ef1dd22d5d6e0721c6905a4ccc67", size = 17985, upload-time = "2026-10-06T17:36:37.478Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/f8/18/a5e35fe8c9ad8041b71dd712658589de5d692aaa17d7cbce7f87a5cb0d0f/opentelemetry_instrumentation_requests-0.63b1-py3-none-any.whl", hash = "sha256:935c980a11e33bfd7ed969c741e4bd7c84077045651469f10e163534368d87f7", size = 13378, upload-time = "2026-05-21T16:35:52.166Z" }, + { url = "https://files.pythonhosted.org/packages/88/01/98e9bb7fef12784cd19811e454cf25bce4d774fd3e46b3f5fd2bce237075/opentelemetry_instrumentation_requests-0.66b1-py3-none-any.whl", hash = "sha256:7ba17d984a2bd876b88bf0aafcca27b5e3ff4c1821e0fe07641e380a3cf3a3a2", size = 13320, upload-time = "2026-10-06T17:35:52.477Z" }, ] [[package]] name = "opentelemetry-instrumentation-sqlalchemy" -version = "0.63b1" +version = "0.66b1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -1391,28 +1393,28 @@ dependencies = [ { name = "packaging" }, { name = "wrapt" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/cb/97/e5cb3ad027aebf7128faadeefe4d4cb0fc07ed32ef95e8fc9d828a077a85/opentelemetry_instrumentation_sqlalchemy-0.63b1.tar.gz", hash = "sha256:621f9eb800ea24a98b4eda968373e3909bfede0ff47f77b96f8b8a18bc2a2a1a", size = 18006, upload-time = "2026-05-21T16:36:46.855Z" } +sdist = { url = "https://files.pythonhosted.org/packages/d4/3e/d69fb08dacc4c248daedf7357732ddca7a0aaff7072a55e311d3da3ea51c/opentelemetry_instrumentation_sqlalchemy-0.66b1.tar.gz", hash = "sha256:a10043953fcba71911bf29a024f8cc337260c1ef0b4fc844b96cae0de0947baa", size = 18181, upload-time = "2026-10-06T17:36:38.111Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/3c/bc/c0984c4c51da64cc2c37ce031b4fb7fab61d223f2188a6bc6b5f18035ae3/opentelemetry_instrumentation_sqlalchemy-0.63b1-py3-none-any.whl", hash = "sha256:d417414f6517963e9c1ee91ec971b94938b46904499114d035a43937bd62b6a1", size = 14410, upload-time = "2026-05-21T16:35:53.342Z" }, + { url = "https://files.pythonhosted.org/packages/08/05/f8cff0c68a7f9ab8fab01904be5a49c5214435109c2a6b6d173a974c10d9/opentelemetry_instrumentation_sqlalchemy-0.66b1-py3-none-any.whl", hash = "sha256:aa30b10d880d7e91cf94b23a92ac85cec09ffddd8f0d40256d7c510e3dd33971", size = 14425, upload-time = "2026-10-06T17:35:53.436Z" }, ] [[package]] name = "opentelemetry-instrumentation-sqlite3" -version = "0.63b1" +version = "0.66b1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "opentelemetry-instrumentation" }, { name = "opentelemetry-instrumentation-dbapi" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/38/9c/b741eb1d9c6c74680913d0a4fd233c518e8f3f69a200a176121db795ccca/opentelemetry_instrumentation_sqlite3-0.63b1.tar.gz", hash = "sha256:3d61afda8358dc32135fabd27e5934bd25ea0eed68d64c34508f24ba8d723efc", size = 8420, upload-time = "2026-05-21T16:36:47.889Z" } +sdist = { url = "https://files.pythonhosted.org/packages/25/54/742ab70c78a1589c29f5513fd5097845b2c2fda58390bbff0f6e1af2601a/opentelemetry_instrumentation_sqlite3-0.66b1.tar.gz", hash = "sha256:e5d672a347deac385a71fb52d556ea443e2f3cc51eac05cac8f0a739cac0bb38", size = 9019, upload-time = "2026-10-06T17:36:38.74Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/65/b3/555c5c2f6d0ee5b5897f8b1d29096cb071ea1c15c77da6f60129b38e6f06/opentelemetry_instrumentation_sqlite3-0.63b1-py3-none-any.whl", hash = "sha256:cc11c68cccde061dc8bcc5f80fe00bb0105a0fbb11b390859a23ca91ccd4e3b6", size = 8528, upload-time = "2026-05-21T16:35:54.481Z" }, + { url = "https://files.pythonhosted.org/packages/3b/6a/c36552844c4e3545da7b2931213256c0717665c7d92246a4fe66e088fd9b/opentelemetry_instrumentation_sqlite3-0.66b1-py3-none-any.whl", hash = "sha256:f282b712f56186c36d592d4ab856d978bc7dd60f4b10500113da8c9eb45ff9bc", size = 8526, upload-time = "2026-10-06T17:35:54.362Z" }, ] [[package]] name = "opentelemetry-instrumentation-starlette" -version = "0.63b1" +version = "0.66b1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -1421,14 +1423,14 @@ dependencies = [ { name = "opentelemetry-semantic-conventions" }, { name = "opentelemetry-util-http" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/1e/22/3b1ba84543f7311b4a26b8735bbfa64e54eb2a0560976e703bc22cd7f3cd/opentelemetry_instrumentation_starlette-0.63b1.tar.gz", hash = "sha256:e6cc1798169362d2ef000905477d145b75798d45c955b181f07622a10d3d6c37", size = 14384, upload-time = "2026-05-21T16:36:48.539Z" } +sdist = { url = "https://files.pythonhosted.org/packages/9a/ea/f962c5b52ba6587ab25c49ed199e5dfe01d402e8d530c13ba99430668f23/opentelemetry_instrumentation_starlette-0.66b1.tar.gz", hash = "sha256:ef8274216c67856ac02f2d23daede0819c77a9b4b6cc3f4decb84663b7ac5693", size = 14319, upload-time = "2026-10-06T17:36:39.304Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/a3/b1/cbd8f3185186054b25a9f8ab2ee7ed70b950de15269c888dac4e3698de46/opentelemetry_instrumentation_starlette-0.63b1-py3-none-any.whl", hash = "sha256:824dbcc9039b89cee24df641d02aad6132cb09c9c67c2fd6ef55955ae90252c5", size = 11104, upload-time = "2026-05-21T16:35:55.906Z" }, + { url = "https://files.pythonhosted.org/packages/6c/89/4c8b2ed03712a802cb60a9d8d977c3340dc83a9be75b2fd0b9a011bf8371/opentelemetry_instrumentation_starlette-0.66b1-py3-none-any.whl", hash = "sha256:1ac11a70e345b57a4259f4a47311101b9eafa3b30d4133df25b36b2e6dfc2c88", size = 11094, upload-time = "2026-10-06T17:35:55.235Z" }, ] [[package]] name = "opentelemetry-instrumentation-system-metrics" -version = "0.63b1" +version = "0.66b1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -1436,28 +1438,28 @@ dependencies = [ { name = "opentelemetry-semantic-conventions" }, { name = "psutil" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/2b/a4/c91a0e085808724ad4cb3bdd76bf9dac872c8a8910b24767cf95ffde67a5/opentelemetry_instrumentation_system_metrics-0.63b1.tar.gz", hash = "sha256:d6d4d7a1a854be4165143cf6420ee5894188762eb367d7bf9da5be4a83a4b632", size = 17412, upload-time = "2026-05-21T16:36:49.276Z" } +sdist = { url = "https://files.pythonhosted.org/packages/d6/81/ab8cabaf45c5248fa88a0d0d3acea4483c105d76cd6c849654ebdab16f92/opentelemetry_instrumentation_system_metrics-0.66b1.tar.gz", hash = "sha256:b0fccbc1aecf35c182431a035ec4809b8f9607eec692243cf70f23b3bda51231", size = 17207, upload-time = "2026-10-06T17:36:40.518Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/29/37/b8bddfab16c0a36af1941ec041b5bc8fe3c3d802997b4e819037908a90d5/opentelemetry_instrumentation_system_metrics-0.63b1-py3-none-any.whl", hash = "sha256:995051f47876d79461aed8b7aa205d4584d90794ef864342cc748929c389bb42", size = 14006, upload-time = "2026-05-21T16:35:56.979Z" }, + { url = "https://files.pythonhosted.org/packages/a3/fd/ea072c512d65ba4054b02c8b7080cf1b362761d4727ee6c1f36dce53328d/opentelemetry_instrumentation_system_metrics-0.66b1-py3-none-any.whl", hash = "sha256:0654b41eb6db3c2f9ad9979487afcc6f461e5b35df282f0a11d0f465e906d967", size = 13913, upload-time = "2026-10-06T17:35:57.01Z" }, ] [[package]] name = "opentelemetry-instrumentation-threading" -version = "0.63b1" +version = "0.66b1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "opentelemetry-instrumentation" }, { name = "wrapt" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/d9/90/7b0279192fab614d57af3d57584ef7ac9e38fa3df0b1d412224f6f55a85b/opentelemetry_instrumentation_threading-0.63b1.tar.gz", hash = "sha256:afa8c2cada8ed136f07b04dc8739bc861a15e9a5edea1a65e4c5e1919c62946c", size = 9080, upload-time = "2026-05-21T16:36:49.977Z" } +sdist = { url = "https://files.pythonhosted.org/packages/55/4f/5fa05266cf24cae93fc32d557d0d2d2f605f81cca1df90614231bbad3cd1/opentelemetry_instrumentation_threading-0.66b1.tar.gz", hash = "sha256:2c217359439d09ca4a4be524db368c05a3cc7f218b85e8086f22664db0a03538", size = 9031, upload-time = "2026-10-06T17:36:41.147Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/c9/3d/3a991a4fcdf5ac82c04215e38cea4e73ad63713707014f9a70d1ab257f5f/opentelemetry_instrumentation_threading-0.63b1-py3-none-any.whl", hash = "sha256:33059298e68c94b13c38b562ad28799ec16a2fd06182ebfc762bb4e956e55d94", size = 8486, upload-time = "2026-05-21T16:35:58.084Z" }, + { url = "https://files.pythonhosted.org/packages/86/da/1cd52b8be7a521958ccdb9a1c4e5ae743aa2be295ba21ec0b620dc87842a/opentelemetry_instrumentation_threading-0.66b1-py3-none-any.whl", hash = "sha256:94039c60603060d26524e31aed1181a5d153e43f58462d110dbeb4830687d7d7", size = 8493, upload-time = "2026-10-06T17:35:57.958Z" }, ] [[package]] name = "opentelemetry-instrumentation-tornado" -version = "0.63b1" +version = "0.66b1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -1465,28 +1467,28 @@ dependencies = [ { name = "opentelemetry-semantic-conventions" }, { name = "opentelemetry-util-http" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/15/aa/24fa9520bbd98ae12d8936c2145ae7a4d5840571ce6233071a0adf52f643/opentelemetry_instrumentation_tornado-0.63b1.tar.gz", hash = "sha256:fa4f7b66bfa683424a96190123824391fc2b486f366200c42af3584bba880ecb", size = 23476, upload-time = "2026-05-21T16:36:50.624Z" } +sdist = { url = "https://files.pythonhosted.org/packages/83/61/2669253fac19c65917340eb138526530d8ef20a6094617590b0ddf7dfb7b/opentelemetry_instrumentation_tornado-0.66b1.tar.gz", hash = "sha256:d571e50cb4cf4b387e8496babbdafdaf8b11dcd93df8b9b7bb26c763da25263f", size = 24087, upload-time = "2026-10-06T17:36:41.768Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/0f/ee/68fdc32b3a76c79615ecc5b102a05e94ee07fe5e510f581266e3cea6e4f5/opentelemetry_instrumentation_tornado-0.63b1-py3-none-any.whl", hash = "sha256:6d1c33d0c109d696b16b45ea995c01d672750979bf41330c55051a327b7d6aa3", size = 17787, upload-time = "2026-05-21T16:35:59.13Z" }, + { url = "https://files.pythonhosted.org/packages/be/7f/f884abef8c7f8fc8dd23c3330f8ba8b86fada0c5eafb659f82d20c4e7e4c/opentelemetry_instrumentation_tornado-0.66b1-py3-none-any.whl", hash = "sha256:6601f13698e80a89de1fcbe00bad845368c053aec54819bcab1c5628b6fa4cc1", size = 17862, upload-time = "2026-10-06T17:35:58.877Z" }, ] [[package]] name = "opentelemetry-instrumentation-tortoiseorm" -version = "0.63b1" +version = "0.66b1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "opentelemetry-instrumentation" }, { name = "opentelemetry-semantic-conventions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/0b/62/59c3cc5e918950d1f9b3151854fb26faf924c1b57fe906132084957d341b/opentelemetry_instrumentation_tortoiseorm-0.63b1.tar.gz", hash = "sha256:37619762ec91208fdce4b95f4b46b4794589b1f166f5a5d195631c2b6f6d235c", size = 8755, upload-time = "2026-05-21T16:36:51.406Z" } +sdist = { url = "https://files.pythonhosted.org/packages/80/03/15775be3e318c78c7318996d9c09d82903777df74cabd09f0cdab01decad/opentelemetry_instrumentation_tortoiseorm-0.66b1.tar.gz", hash = "sha256:8aec043c62f3b2d852e78602cd53a0f4d9e481fce20df421cec39a2c9d4fbbdc", size = 9447, upload-time = "2026-10-06T17:36:42.358Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/12/6b/ab8362605c7df9896a4abdcc93fb860f8b184e8f37059930984f557fbab5/opentelemetry_instrumentation_tortoiseorm-0.63b1-py3-none-any.whl", hash = "sha256:a785fab2d25450e72d3779a2cfad8e2745a7746f09083acd1ba3e8ec0cbd2642", size = 9334, upload-time = "2026-05-21T16:36:00.277Z" }, + { url = "https://files.pythonhosted.org/packages/3c/78/32acfc1b4142c40e31c1b2570a88373d4a106d63543e69b57364aa2c6d50/opentelemetry_instrumentation_tortoiseorm-0.66b1-py3-none-any.whl", hash = "sha256:4a648a2387620645ae74efdb566e40a2bdb7db8a700416e2eb475b72f7e9385d", size = 9472, upload-time = "2026-10-06T17:36:00.038Z" }, ] [[package]] name = "opentelemetry-instrumentation-urllib" -version = "0.63b1" +version = "0.66b1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -1494,14 +1496,14 @@ dependencies = [ { name = "opentelemetry-semantic-conventions" }, { name = "opentelemetry-util-http" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/0e/2f/6b77bef02f06f312550251f9095e18189493d9a0a83f4608214c9be36da6/opentelemetry_instrumentation_urllib-0.63b1.tar.gz", hash = "sha256:500b959d7933408ef30a6f4bb2a0b6979f71129e62b945fc5615aa63df4ad9b8", size = 16668, upload-time = "2026-05-21T16:36:52.089Z" } +sdist = { url = "https://files.pythonhosted.org/packages/a2/21/626955d129e753d197217564f0688bef4ff62c05bbe9858b00112553604e/opentelemetry_instrumentation_urllib-0.66b1.tar.gz", hash = "sha256:f00daa25375fbdf88b7e1a425ef54c704674d8bef639c834de93df9b3f88d7f4", size = 16577, upload-time = "2026-10-06T17:36:42.918Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/a0/24/34df2aff5f2290deeeaf1b3bf040f48f53bb1cd4bb3ba7aa2ad51b80770f/opentelemetry_instrumentation_urllib-0.63b1-py3-none-any.whl", hash = "sha256:538e8c72515b48c69e03c2789a03d245ba6e1bf5c22c2052df1e872bb8274d96", size = 13138, upload-time = "2026-05-21T16:36:01.378Z" }, + { url = "https://files.pythonhosted.org/packages/3e/47/b661cb253be58118cb27067b41fb001784ed615b5e42b5c59a4e30388ee4/opentelemetry_instrumentation_urllib-0.66b1-py3-none-any.whl", hash = "sha256:6f679d785ebcb04b791a889d8a9c0e8edf897a85ab80a7a12b0139c461b14627", size = 13076, upload-time = "2026-10-06T17:36:01.281Z" }, ] [[package]] name = "opentelemetry-instrumentation-urllib3" -version = "0.63b1" +version = "0.66b1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -1510,14 +1512,14 @@ dependencies = [ { name = "opentelemetry-util-http" }, { name = "wrapt" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/c9/b9/acc5bd0add608cad1abebe9d65c0916bf48c8957c2a6b0b3985ead79830e/opentelemetry_instrumentation_urllib3-0.63b1.tar.gz", hash = "sha256:c4358358f49b7dc42550cd6efbcfbfce3d178b8bf09acf46b62993f5f3ba4a9c", size = 18945, upload-time = "2026-05-21T16:36:53.177Z" } +sdist = { url = "https://files.pythonhosted.org/packages/08/ab/2dd6b3a69df31ae12714bf24fcc2772956d7cb8f9082432c9e63a37e6930/opentelemetry_instrumentation_urllib3-0.66b1.tar.gz", hash = "sha256:31e84a2ccfa86ca1d4f1209ea66c1f709c335348d5c487477d3843172efcc408", size = 18826, upload-time = "2026-10-06T17:36:43.547Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/23/92/a9fac2daa2e4d843d6330263d56b18f32a5de43573e6c869da439e84ddf2/opentelemetry_instrumentation_urllib3-0.63b1-py3-none-any.whl", hash = "sha256:241d0a819e614e479ba89d32470dddd94191deb0cb49fa525fa5585022caddbe", size = 13512, upload-time = "2026-05-21T16:36:02.849Z" }, + { url = "https://files.pythonhosted.org/packages/be/7f/16f82bf359c28fb71ad4dc5ad386cce3483abbf1ce0ade087fe78c18daf3/opentelemetry_instrumentation_urllib3-0.66b1-py3-none-any.whl", hash = "sha256:e48b448fed4a127e54c584c37a443c91d80d34b9f9de324af9a00cead8b338b8", size = 13462, upload-time = "2026-10-06T17:36:02.242Z" }, ] [[package]] name = "opentelemetry-instrumentation-wsgi" -version = "0.63b1" +version = "0.66b1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -1525,23 +1527,23 @@ dependencies = [ { name = "opentelemetry-semantic-conventions" }, { name = "opentelemetry-util-http" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/0b/55/832f287fb153adc25c05bc2594d00ac4d1dbeca8b19388b2666d5154c912/opentelemetry_instrumentation_wsgi-0.63b1.tar.gz", hash = "sha256:03d61c4678ce82402e7f37b6a3dbd84cb97b85b3cb416a78c2e74c7c6d9451fa", size = 19667, upload-time = "2026-05-21T16:36:53.873Z" } +sdist = { url = "https://files.pythonhosted.org/packages/41/7a/a1ba86d95f849db8f41ffd03c7cb302559ef091d76cff78baddd4ad19205/opentelemetry_instrumentation_wsgi-0.66b1.tar.gz", hash = "sha256:ce803d8e828e75d7225c25a618b692cbd4687a11be64356308ed1feab0f70bab", size = 19527, upload-time = "2026-10-06T17:36:44.181Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/14/b6/0854591a78960f376c7f943a6927c2863e1f8b0c93003aafe03aa49c089b/opentelemetry_instrumentation_wsgi-0.63b1-py3-none-any.whl", hash = "sha256:86779715262227d3436bdfb16aabd1c524b0f236725a69e8754ceda76c6d79dc", size = 13786, upload-time = "2026-05-21T16:36:05.221Z" }, + { url = "https://files.pythonhosted.org/packages/a5/4f/17f06b0dc7c542c482b1d3f7f1d0925046f7e156fb39c255634b3c4f526a/opentelemetry_instrumentation_wsgi-0.66b1-py3-none-any.whl", hash = "sha256:8c86390c32fe8d0924b3541f292122d3a2ba6c3accc2bcbcc73ae985ee8e799e", size = 13752, upload-time = "2026-10-06T17:36:03.166Z" }, ] [[package]] name = "opentelemetry-processor-baggage" -version = "0.63b1" +version = "0.66b1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "opentelemetry-sdk" }, { name = "wrapt" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/7b/43/69a8dcb2a540809c02bfc31d01b2e8228b4dd28c363d6d59577bcf9f1361/opentelemetry_processor_baggage-0.63b1.tar.gz", hash = "sha256:334b77963ea5807efd6f05664a6064aa92fc6c03571edbf1f749b9dee370d567", size = 8834, upload-time = "2026-05-21T16:36:54.591Z" } +sdist = { url = "https://files.pythonhosted.org/packages/7d/e8/6b11138881f0b1870a16891311e34d2a74fb21c8a7637e71cb61757b810d/opentelemetry_processor_baggage-0.66b1.tar.gz", hash = "sha256:200c16de37b9afae685bdc368a261d1c091ac7ef4fb892ef93129e2be5036642", size = 8794, upload-time = "2026-10-06T17:36:44.807Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/23/44/3179fc05c69ca82657565d3223feb14d5208ede33e6838e42e7fe2dc01b8/opentelemetry_processor_baggage-0.63b1-py3-none-any.whl", hash = "sha256:b205c343720ce4d5e420204e09862a043917ee433b2304d87bb6f388084f3c15", size = 9488, upload-time = "2026-05-21T16:36:06.756Z" }, + { url = "https://files.pythonhosted.org/packages/b2/92/02b52c5ac72ffa4a54c496c83b99c6941090a4fd419b4666a73651222b8a/opentelemetry_processor_baggage-0.66b1-py3-none-any.whl", hash = "sha256:b43acdcb387d8934e04e8f265165b1d632ca62509c693941b31df69bf62d1fe5", size = 9467, upload-time = "2026-10-06T17:36:04.101Z" }, ] [[package]] @@ -1558,66 +1560,66 @@ wheels = [ [[package]] name = "opentelemetry-propagator-b3" -version = "1.42.1" +version = "1.45.1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/17/29/8919505640163f6038ddbfd2c93bc7c14339c81b6b52e220c33c072a8489/opentelemetry_propagator_b3-1.42.1.tar.gz", hash = "sha256:69e495870c05c115543b22a13635af24e5ac3f4cfcd40f2678dadf23725855c6", size = 9502, upload-time = "2026-05-21T16:33:02.781Z" } +sdist = { url = "https://files.pythonhosted.org/packages/d3/29/3a3e0ab089773324faaa4fe40c13cfc6a0a78410368578a30ee3453fc2a3/opentelemetry_propagator_b3-1.45.1.tar.gz", hash = "sha256:0f7d346b2cc2e9ec157c4e5c03f787d8631e61edc4b71978bb3bca2bb228db94", size = 9476, upload-time = "2026-10-06T17:33:10.358Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/52/95/8c3f5b0c0106a6eb008425b01da87a2a35614074200afe3d353272e12210/opentelemetry_propagator_b3-1.42.1-py3-none-any.whl", hash = "sha256:46b28494025d1752b244af5e02d4f98712fa90e57c57e5ef26b1a19e64fac1fa", size = 8345, upload-time = "2026-05-21T16:32:42.92Z" }, + { url = "https://files.pythonhosted.org/packages/6a/ed/425cf8b9b312bbe6d42d94283e19946d54f48963a1104c5ad65b51f8b332/opentelemetry_propagator_b3-1.45.1-py3-none-any.whl", hash = "sha256:cd811519968dced23dda1240f2adf488e579d1361340a666af8540cd8a1e17ac", size = 8333, upload-time = "2026-10-06T17:32:50.935Z" }, ] [[package]] name = "opentelemetry-propagator-jaeger" -version = "1.42.1" +version = "1.45.1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/44/8f/c169b074086a81bc651bfa7215454539dbec41320c21a5f186169dcc6373/opentelemetry_propagator_jaeger-1.42.1.tar.gz", hash = "sha256:650441e8373ef6de208010b7057580292f37ca54cdee07c068ae2e31fc5dc603", size = 8452, upload-time = "2026-05-21T16:33:03.326Z" } +sdist = { url = "https://files.pythonhosted.org/packages/ae/c1/c6fab5f87ddd0ad2950baf94297578291206b97fe413073ba2297e64d1e1/opentelemetry_propagator_jaeger-1.45.1.tar.gz", hash = "sha256:96b5a71ec3177715a2fad3653d93cbc05ac358f2cbe437681edf88a055674af6", size = 9958, upload-time = "2026-10-06T17:33:10.915Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/c6/51/14175e56deef14450d33bb8b9b8d7446ea1908858cf2e48d2bad7a48dca6/opentelemetry_propagator_jaeger-1.42.1-py3-none-any.whl", hash = "sha256:89fe37472e1b1d6cead25c0aad8081dfc1972b2f9bb63f9a971cb3336f3becd2", size = 8180, upload-time = "2026-05-21T16:32:44.011Z" }, + { url = "https://files.pythonhosted.org/packages/20/f8/f8698dca5e3cfe25733c8e2e3a8990611fd2099b8a4c345de0c6e47a04e6/opentelemetry_propagator_jaeger-1.45.1-py3-none-any.whl", hash = "sha256:008705ce03fb827244e2bc310272d6324073b20cb08939cac09752e22481938d", size = 8773, upload-time = "2026-10-06T17:32:52.049Z" }, ] [[package]] name = "opentelemetry-propagator-ot-trace" -version = "0.63b1" +version = "0.66b1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "opentelemetry-sdk" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/36/c2/68785003eb74567537cd62b3f75acf4bcb24059bb1f9f4d12553b0b197db/opentelemetry_propagator_ot_trace-0.63b1.tar.gz", hash = "sha256:d382f9b52110110411a4ad9e1f7d357ed2013e9ca044293101998c1b1277c276", size = 4771, upload-time = "2026-05-21T16:36:55.223Z" } +sdist = { url = "https://files.pythonhosted.org/packages/5b/ac/0cf788f364b01194315b87fe86a0dbfc2d962960083360294e88b130c02e/opentelemetry_propagator_ot_trace-0.66b1.tar.gz", hash = "sha256:d9891354966cf8941c85b90d483f52d6f79e5b9c27145eee2082c8767924f6eb", size = 6970, upload-time = "2026-10-06T17:36:45.381Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/be/96/178e05e480525118dc230fc96caf00af103398968597b77390c7fdb3d233/opentelemetry_propagator_ot_trace-0.63b1-py3-none-any.whl", hash = "sha256:eb931ecd0002ba6062f4ad1873ccf8d033caa911079dfc238a2b7346ae8d5a59", size = 4198, upload-time = "2026-05-21T16:36:07.706Z" }, + { url = "https://files.pythonhosted.org/packages/0c/9a/b66ac5db3ad3b4e7d2ee3e261210e59d663e483e2b9884052b7181910863/opentelemetry_propagator_ot_trace-0.66b1-py3-none-any.whl", hash = "sha256:0217b23e344f16b76cfcc9f0cea729e205ff4323d564a70d350f688f50c34370", size = 4792, upload-time = "2026-10-06T17:36:05.024Z" }, ] [[package]] name = "opentelemetry-proto" -version = "1.42.1" +version = "1.45.1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "protobuf" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/b4/55/63eac3e1089b768ba014091fdd2ae8a9a440c821ef5e2b786909c94c8836/opentelemetry_proto-1.42.1.tar.gz", hash = "sha256:c6a51e6b4f05ae63565f3a113217f3d2bfaec68f78c02d7a6c85f9010d1cfca6", size = 45839, upload-time = "2026-05-21T16:33:03.937Z" } +sdist = { url = "https://files.pythonhosted.org/packages/4b/7f/15f014fb195da6c2dbb6c71399b8e76824878718e94de6454038488eed28/opentelemetry_proto-1.45.1.tar.gz", hash = "sha256:79e0fb95e4616691a469439238aa9224d75779b3e108e895d1aa125ab29ca77c", size = 46488, upload-time = "2026-10-06T17:33:11.49Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/41/9d/171c02c84a76940b7e601805b3bb536985aded9168fbcc9ba52f0a730fa2/opentelemetry_proto-1.42.1-py3-none-any.whl", hash = "sha256:dedb74cba2886c59c7789b227a7a670613025a07489040050aedff6e5c0fb43c", size = 71782, upload-time = "2026-05-21T16:32:44.867Z" }, + { url = "https://files.pythonhosted.org/packages/ab/9a/42ec8180a769516ae757e893b69736826efceac7332553915b4528a91c6d/opentelemetry_proto-1.45.1-py3-none-any.whl", hash = "sha256:f38e2a8413053c180cd3d2637fbb279673ec2f6a6e09c995aafa2f452c52b46e", size = 72488, upload-time = "2026-10-06T17:32:53.057Z" }, ] [[package]] name = "opentelemetry-sdk" -version = "1.42.1" +version = "1.45.1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "opentelemetry-semantic-conventions" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/40/f7/b390bd9bfd703bf98a68fea1f27786c6872331fd617164a54b8a59bdc008/opentelemetry_sdk-1.42.1.tar.gz", hash = "sha256:8c834e8f8c9ba4171d4ec843d0cb8a67e4c7394d3f9e9297e582cbd9456ddbf7", size = 239262, upload-time = "2026-05-21T16:33:04.641Z" } +sdist = { url = "https://files.pythonhosted.org/packages/a1/79/7392e21a1c8f0c61d90b223e31c7e48cb9d452e91a6b820ad24cca5f23c4/opentelemetry_sdk-1.45.1.tar.gz", hash = "sha256:63d24a6ca645019a631e6a51999c73e93adcac1196ca640b8ae78a7cc4762bf3", size = 218324, upload-time = "2026-10-06T17:33:13.26Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/8f/6b/4287766cfbde577ae2272e8884abac325aeaac0d64f41c61d5b8cc595105/opentelemetry_sdk-1.42.1-py3-none-any.whl", hash = "sha256:083cd4bbfaa5aa7b5a9e552430d9951219967cfb27aa61feb13a77aba1fc839d", size = 170907, upload-time = "2026-05-21T16:32:45.894Z" }, + { url = "https://files.pythonhosted.org/packages/95/3c/87c42b4bd6dd297536f04cd9383d212ac557ecd49f2cbdcd46da1c9ef5c8/opentelemetry_sdk-1.45.1-py3-none-any.whl", hash = "sha256:c604c11dc429810812348989115fa44bd558772a3d7442afc43d024f2c250ca4", size = 140063, upload-time = "2026-10-06T17:32:55.04Z" }, ] [[package]] @@ -1634,38 +1636,24 @@ wheels = [ [[package]] name = "opentelemetry-semantic-conventions" -version = "0.63b1" +version = "0.66b1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/93/99/4d7dd6df64795951413ce6e815f8cf1eb191daf7196ae86574589643d5f3/opentelemetry_semantic_conventions-0.63b1.tar.gz", hash = "sha256:3daf963611334b365e98a57438183eb012d3bfb40b2d931a9af613476b8701a9", size = 148340, upload-time = "2026-05-21T16:33:05.455Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/cb/7a/7fe66f5f3682b1dd47d88cc4e11f1c6c0966b737de2d16671146e23c39a5/opentelemetry_semantic_conventions-0.63b1-py3-none-any.whl", hash = "sha256:dfe5ef4dee82586b746f522b818ceb298d00b3d59f660042bd79404bff8d0682", size = 203713, upload-time = "2026-05-21T16:32:47.016Z" }, -] - -[[package]] -name = "opentelemetry-util-genai" -version = "0.4b0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "opentelemetry-api" }, - { name = "opentelemetry-instrumentation" }, - { name = "opentelemetry-semantic-conventions" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/e8/54/545527aba649f6b8aba7b70c855db9089a2b8f234bd6c19beffa73a3163d/opentelemetry_util_genai-0.4b0.tar.gz", hash = "sha256:0235b03c5b3cb5efe5d3c16a5a68e82be34e6530d6707cf1cf122413578c2036", size = 47385, upload-time = "2026-05-01T17:29:17.055Z" } +sdist = { url = "https://files.pythonhosted.org/packages/46/e4/dbbfb2a010c4db2224a5114638acede6fe563d33cc20fb1752cebcbe6298/opentelemetry_semantic_conventions-0.66b1.tar.gz", hash = "sha256:497ca63bf383723411e8eaf60c8779e9877633c936bb641080adab59d0eb6ec8", size = 150250, upload-time = "2026-10-06T17:33:14.073Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/e8/50/0b86c4159a74802a917fcc2adf22f1af522f03805cc049415221207249e8/opentelemetry_util_genai-0.4b0-py3-none-any.whl", hash = "sha256:ac26db52ad1d86ce3e4ac183f204c37a6e66fdb6d86b71feee60468bcb32ef13", size = 42848, upload-time = "2026-05-01T17:29:15.839Z" }, + { url = "https://files.pythonhosted.org/packages/bc/14/67f8aa798857f8cf686f515bf93d9bb877ce952ddc8efae0fa25b45ce0d6/opentelemetry_semantic_conventions-0.66b1-py3-none-any.whl", hash = "sha256:d4cddeb4315490b35213f55e2bdc9ac54bb1e4d318927475bed62b35545e581b", size = 206279, upload-time = "2026-10-06T17:32:56.103Z" }, ] [[package]] name = "opentelemetry-util-http" -version = "0.63b1" +version = "0.66b1" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/6c/d8/7bf5e4cec0578ac3c28c18eb7b88f34279139cbc8c568d6aa02b9c5ae53e/opentelemetry_util_http-0.63b1.tar.gz", hash = "sha256:ba1268f00922ee522dba2ae38458060f99486e7385a8056985901ca9685adfff", size = 11102, upload-time = "2026-05-21T16:36:56.675Z" } +sdist = { url = "https://files.pythonhosted.org/packages/7c/b5/df4b61da899f6ebdffdbdf0c8b0f3189ee57151694ccd5b7d50ee2906241/opentelemetry_util_http-0.66b1.tar.gz", hash = "sha256:047dea1a628031f857a5a32261dc0e955bc162d39993ed1cffb8f2cff5ba8a62", size = 11586, upload-time = "2026-10-06T17:36:46.572Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/e5/f1/34e047e8f6a3c67e5220acf1af7b9f62868c25d77791bca74457bd2180a6/opentelemetry_util_http-0.63b1-py3-none-any.whl", hash = "sha256:6284194028c59cd439f8acfe388145069a6127f11dc077e1344a2094adacc3f8", size = 8205, upload-time = "2026-05-21T16:36:09.736Z" }, + { url = "https://files.pythonhosted.org/packages/eb/9b/c77ecaea79ba0de1a11e7f06a7f5eea7043ec23f1860dcf5f03536698e4c/opentelemetry_util_http-0.66b1-py3-none-any.whl", hash = "sha256:8f443d7abcaf29c4a07b373bbd31b5b39132c0ed3c27d015a59dc0323d5b1c58", size = 8387, upload-time = "2026-10-06T17:36:06.984Z" }, ] [[package]] diff --git a/cdk/AGENTS.md b/cdk/AGENTS.md index 5f27a89d9..3fb326e25 100644 --- a/cdk/AGENTS.md +++ b/cdk/AGENTS.md @@ -37,6 +37,8 @@ mise //cdk:destroy # destroy stack Construct tests: synthesize each distinct stack config once in `beforeAll`, assert against cached `Template` — do not re-synth per test. Bundling is disabled globally via `test/setup/disable-bundling.ts` (see Common mistakes). +Emulator-backed tests (`test/emulator/*.emulator.ts`) run real handlers against a local AWS Emulator. `mise //cdk:test` does not run them: use `mise run test:integration` from the repository root (needs Docker). Rules and known differences from AWS: [scripts/aws-emulator/README.md](../scripts/aws-emulator/README.md). + ## Primary locations | Path | Access | Purpose | diff --git a/cdk/jest.emulator.config.js b/cdk/jest.emulator.config.js new file mode 100644 index 000000000..fd9254d2b --- /dev/null +++ b/cdk/jest.emulator.config.js @@ -0,0 +1,2 @@ +// Emulator-backed handler tests (test/emulator/*.emulator.ts). Run with `mise run test:integration`. +module.exports = require('../scripts/aws-emulator/jest-config')(require('./package.json').jest); diff --git a/cdk/src/constructs/linear-integration.ts b/cdk/src/constructs/linear-integration.ts index 64b6c3e94..0211f4332 100644 --- a/cdk/src/constructs/linear-integration.ts +++ b/cdk/src/constructs/linear-integration.ts @@ -159,7 +159,7 @@ export interface LinearIntegrationProps { * provider name; Phase 2.0b OAuth migration). Webhook processor and * orchestrator use this to look up which credential provider holds the * workspace's OAuth token. - * - LinearWebhookDedupTable (60s TTL dedup for webhook retries) + * - LinearWebhookDedupTable (8h TTL dedup for webhook retries) * - Lambda handlers for the webhook receiver, async processor, and account linking * - API Gateway routes under /linear/* * - Two Secrets Manager secrets (webhook signing secret + personal API token) @@ -178,7 +178,7 @@ export class LinearIntegration extends Construct { */ public readonly workspaceRegistryTable: dynamodb.Table; - /** Webhook dedup table — (issue_id, action) keys with 60s TTL. */ + /** Webhook dedup table — delivery rows keyed on (data.id, action, webhookTimestamp), 8h TTL. */ public readonly webhookDedupTable: dynamodb.Table; /** Linear webhook signing secret (placeholder — populated by `bgagent linear setup`). */ @@ -207,7 +207,7 @@ export class LinearIntegration extends Construct { this.workspaceRegistryTable = workspaceRegistry.table; // Dedup table: linear webhook retries collapse to a single processor invoke - // within the 60s TTL window. Keyed on `{issue_id}#{action}`. + // within the 8h TTL window. Keyed on `{data.id}#{action}#{webhookTimestamp}`. this.webhookDedupTable = new dynamodb.Table(this, 'WebhookDedupTable', { partitionKey: { name: 'dedup_key', type: dynamodb.AttributeType.STRING }, billingMode: dynamodb.BillingMode.PAY_PER_REQUEST, diff --git a/cdk/src/constructs/stranded-task-reconciler.ts b/cdk/src/constructs/stranded-task-reconciler.ts index cb3dbdbc6..681564b79 100644 --- a/cdk/src/constructs/stranded-task-reconciler.ts +++ b/cdk/src/constructs/stranded-task-reconciler.ts @@ -33,7 +33,7 @@ const DEFAULT_STRANDED_TIMEOUT_SECONDS = 1200; /** Default approval-stranded timeout (seconds; 2 hours). */ const DEFAULT_APPROVAL_STRANDED_TIMEOUT_SECONDS = 7200; -/** Default task-record retention used for event TTL (days). */ +/** Default retention (days): the ttl of a task row the sweep fails and of the events it writes. */ const DEFAULT_TASK_RETENTION_DAYS = 90; /** Reconciler Lambda timeout (minutes). */ @@ -87,7 +87,7 @@ export interface StrandedTaskReconcilerProps { */ readonly approvalStrandedTimeoutSeconds?: number; - /** Forwarded to the handler for event TTL. @default 90 */ + /** Forwarded to the handler for the ttl of the task rows it fails and of its events. @default 90 */ readonly taskRetentionDays?: number; } diff --git a/cdk/src/constructs/task-api.ts b/cdk/src/constructs/task-api.ts index 0559278a2..bd079ed6c 100644 --- a/cdk/src/constructs/task-api.ts +++ b/cdk/src/constructs/task-api.ts @@ -155,7 +155,8 @@ export interface TaskApiProps { /** * Maximum concurrent tasks per user (#441). Threaded to the get-task * handler so the queue-wait ETA heuristic agrees with the - * orchestrator's admission cap. Must match + * orchestrator's admission cap, and to the confirm-uploads handler, + * which admits against it. Must match * ``TaskOrchestrator.maxConcurrentTasksPerUser``. * @default 10 */ @@ -566,6 +567,10 @@ export class TaskApi extends Construct { timeout: Duration.seconds(API_HANDLER_TIMEOUT_SECONDS), }); + // The per-user cap for the handlers here that read it. It has to match the + // orchestrator's (see the prop). + const maxConcurrentTasksPerUser = String(props.maxConcurrentTasksPerUser ?? 10); + const getTaskFn = new lambda.NodejsFunction(this, 'GetTaskFn', { entry: path.join(handlersDir, 'get-task.ts'), handler: 'handler', @@ -575,7 +580,7 @@ export class TaskApi extends Construct { ...commonEnv, // #441: queue-position ETA heuristic must agree with the // orchestrator's per-user admission cap. - MAX_CONCURRENT_TASKS_PER_USER: String(props.maxConcurrentTasksPerUser ?? 10), + MAX_CONCURRENT_TASKS_PER_USER: maxConcurrentTasksPerUser, }, bundling: commonBundling, }); @@ -591,6 +596,10 @@ export class TaskApi extends Construct { architecture: Architecture.ARM_64, environment: listTasksEnv, bundling: commonBundling, + // Task rows are large and a filtered list pages through up to 10 Queries of up to + // 1 MB each, so this gets the API-handler settings, not the 3s / 128MB defaults. + timeout: Duration.seconds(API_HANDLER_TIMEOUT_SECONDS), + memorySize: API_HANDLER_MEMORY_MB, }); const cancelTaskEnv: Record = { ...commonEnv }; @@ -752,6 +761,8 @@ export class TaskApi extends Construct { const confirmUploadsEnv: Record = { ...commonEnv }; confirmUploadsEnv.ATTACHMENTS_BUCKET_NAME = props.attachmentsBucket.bucketName; confirmUploadsEnv.USER_CONCURRENCY_TABLE_NAME = props.userConcurrencyTable.tableName; + // Without it the handler admits against its own fallback of 3. + confirmUploadsEnv.MAX_CONCURRENT_TASKS_PER_USER = maxConcurrentTasksPerUser; if (props.orchestratorFunctionArn) { confirmUploadsEnv.ORCHESTRATOR_FUNCTION_ARN = props.orchestratorFunctionArn; } diff --git a/cdk/src/constructs/task-table.ts b/cdk/src/constructs/task-table.ts index 188a7d687..65d3848a4 100644 --- a/cdk/src/constructs/task-table.ts +++ b/cdk/src/constructs/task-table.ts @@ -54,7 +54,9 @@ export interface TaskTableProps { * (queue processing), by idempotency key (dedup), and by Jira issue. * * GSIs: - * - UserStatusIndex (PK: user_id, SK: status_created_at) — "my tasks" queries + * - UserStatusIndex (PK: user_id, SK: status_created_at) — a user's tasks by + * status (queue position, active-task counts) + * - UserCreatedAtIndex (PK: user_id, SK: created_at) — the task list, newest first * - StatusIndex (PK: status, SK: created_at) — queue processing, monitoring * - IdempotencyIndex (PK: idempotency_key) — sparse index for dedup * - LinearIssueIndex (PK: linear_issue_id, SK: created_at) — sparse; resolve a @@ -70,6 +72,13 @@ export class TaskTable extends Construct { */ public static readonly USER_STATUS_INDEX = 'UserStatusIndex'; + /** + * GSI name for listing a user's tasks newest first (GET /tasks). + * PK: user_id, SK: created_at. UserStatusIndex cannot serve the list: its + * sort key begins with the status, so a read comes back grouped by status. + */ + public static readonly USER_CREATED_AT_INDEX = 'UserCreatedAtIndex'; + /** * GSI name for querying tasks by status. * PK: status, SK: created_at. @@ -182,5 +191,14 @@ export class TaskTable extends Construct { projectionType: dynamodb.ProjectionType.INCLUDE, nonKeyAttributes: ['pr_url', 'pr_number', 'status', 'repo', 'user_id', 'channel_metadata'], }); + + // GSI: list a user's tasks newest first (GET /tasks). Declared last so that a + // deployed table sees one index appended and no attribute definition moved. + this.table.addGlobalSecondaryIndex({ + indexName: TaskTable.USER_CREATED_AT_INDEX, + partitionKey: { name: 'user_id', type: dynamodb.AttributeType.STRING }, + sortKey: { name: 'created_at', type: dynamodb.AttributeType.STRING }, + projectionType: dynamodb.ProjectionType.ALL, + }); } } diff --git a/cdk/src/handlers/confirm-uploads.ts b/cdk/src/handlers/confirm-uploads.ts index f1b24ba9a..8a3b32dd9 100644 --- a/cdk/src/handlers/confirm-uploads.ts +++ b/cdk/src/handlers/confirm-uploads.ts @@ -565,7 +565,7 @@ async function failTaskOnScreening( await ddb.send(new UpdateCommand({ TableName: TABLE_NAME, Key: { task_id: taskId }, - UpdateExpression: 'SET #s = :failed, #sca = :status_created_at, error_message = :err, updated_at = :now, #ttl = :ttl', + UpdateExpression: 'SET #s = :failed, #sca = :status_created_at, error_message = :err, updated_at = :now, completed_at = :now, #ttl = :ttl', ConditionExpression: '#s = :pending_uploads', ExpressionAttributeNames: { '#s': 'status', diff --git a/cdk/src/handlers/fanout-task-events.ts b/cdk/src/handlers/fanout-task-events.ts index a6a9dd099..916cfa7eb 100644 --- a/cdk/src/handlers/fanout-task-events.ts +++ b/cdk/src/handlers/fanout-task-events.ts @@ -835,8 +835,8 @@ async function dispatchToGitHubComment(event: FanOutEvent): Promise { latestEventType: renderedEventType, latestEventAt: event.timestamp, prUrl: task.pr_url ?? null, - // DDB returns numeric attributes as strings at the Document-client - // boundary (see ``shared/numeric.ts``). Without coercion + // The agent stores these fields as DynamoDB strings (see + // ``shared/numeric.ts``). Without coercion // ``costUsd.toFixed(4)`` throws ``TypeError`` and the dispatcher // is rejected for every terminal event. durationS: coerceNumericOrNull( @@ -1645,8 +1645,8 @@ async function dispatchToJira(event: FanOutEvent): Promise { const paragraphs = renderJiraFinalStatusComment({ eventType: event.event_type, prUrl: task.pr_url ?? null, - // DDB returns numeric attributes as strings at the Document-client - // boundary; coerce so toFixed/comparisons work. Same pattern the + // The agent stores cost, duration and the turn counters as DynamoDB + // strings; coerce so toFixed/comparisons work. Same pattern the // GitHub + Linear dispatchers use. costUsd: coerceNumericOrNull( task.cost_usd, diff --git a/cdk/src/handlers/jira-link.ts b/cdk/src/handlers/jira-link.ts index d7b1a4173..45c3cf390 100644 --- a/cdk/src/handlers/jira-link.ts +++ b/cdk/src/handlers/jira-link.ts @@ -70,7 +70,9 @@ export async function handler(event: APIGatewayProxyEvent): Promise { diff --git a/cdk/src/handlers/list-tasks.ts b/cdk/src/handlers/list-tasks.ts index 560f6296b..bdfa7a794 100644 --- a/cdk/src/handlers/list-tasks.ts +++ b/cdk/src/handlers/list-tasks.ts @@ -17,6 +17,7 @@ * SOFTWARE. */ +import { DescribeTableCommand } from '@aws-sdk/client-dynamodb'; import { QueryCommand } from '@aws-sdk/lib-dynamodb'; import type { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda'; import { ulid } from 'ulid'; @@ -37,6 +38,45 @@ const DEFAULT_PAGE_LIMIT = 20; /** Hard page-size ceiling. */ const MAX_PAGE_LIMIT = 100; +/** + * Cap on DynamoDB `Query` round-trips per request. `Limit` is applied to items read, + * before `FilterExpression`, so a status or repo filter can leave a page short; we page + * until it is full. The cap bounds what one request reads; the token still advances. + */ +const MAX_QUERY_PAGES = 10; + +/** + * The indexes that can serve the list, each with the sort key its cursors carry. + * UserStatusIndex is the one the list read before #51; it groups tasks by status. + */ +const SORT_KEY_OF = { UserCreatedAtIndex: 'created_at', UserStatusIndex: 'status_created_at' } as const; + +/** + * True once DynamoDB has reported UserCreatedAtIndex as ACTIVE; kept for the life of this + * execution environment. The deploy that adds the index updates this function without + * waiting for DynamoDB to build it, and an index cannot be queried until it is ACTIVE. + * Only that deploy needs this: once every deployed stack has the index, the status check + * and the reading of UserStatusIndex can go. + */ +let createdAtIndexActive = false; + +/** + * The index to list from: UserCreatedAtIndex once it is ACTIVE, UserStatusIndex until then. + * @param requestId - for the warning logged while the list is read from UserStatusIndex. + * @returns the index name. + */ +async function listIndex(requestId: string): Promise { + if (!createdAtIndexActive) { + const { Table } = await ddb.send(new DescribeTableCommand({ TableName: TABLE_NAME })); + const status = Table?.GlobalSecondaryIndexes?.find((index) => index.IndexName === 'UserCreatedAtIndex')?.IndexStatus; + createdAtIndexActive = status === 'ACTIVE'; + if (!createdAtIndexActive) { + logger.warn('UserCreatedAtIndex is not ACTIVE; listing from UserStatusIndex', { index_status: status ?? 'missing', request_id: requestId }); + } + } + return createdAtIndexActive ? 'UserCreatedAtIndex' : 'UserStatusIndex'; +} + /** * GET /v1/tasks — List tasks for the authenticated user. */ @@ -67,7 +107,7 @@ export async function handler(event: APIGatewayProxyEvent): Promise = { - TableName: TABLE_NAME, - IndexName: 'UserStatusIndex', - KeyConditionExpression: 'user_id = :uid', - ExpressionAttributeValues: exprValues, - ScanIndexForward: false, - Limit: limit, - }; - - if (filterParts.length > 0) { - queryInput.FilterExpression = filterParts.join(' AND '); + // 4. Execute query. Accumulate until the page is full or the index is exhausted; + // over-fetch one so a full page can tell whether another task follows. A cursor is + // only valid on the index that issued it, and only UserStatusIndex cursors carry + // status_created_at. + const index = startKey?.status_created_at !== undefined ? 'UserStatusIndex' : await listIndex(requestId); + const items: TaskRecord[] = []; + for (let page = 0; page < MAX_QUERY_PAGES; page += 1) { + const result = await ddb.send(new QueryCommand({ + TableName: TABLE_NAME, + IndexName: index, + KeyConditionExpression: 'user_id = :uid', + ExpressionAttributeValues: exprValues, + ScanIndexForward: false, + Limit: limit + 1, + ...(filterParts.length > 0 && { + FilterExpression: filterParts.join(' AND '), + ExpressionAttributeNames: exprNames, + }), + ...(startKey && { ExclusiveStartKey: startKey }), + })); + items.push(...((result.Items ?? []) as TaskRecord[])); + startKey = result.LastEvaluatedKey as Record | undefined; + if (items.length > limit || !startKey) break; } - if (Object.keys(exprNames).length > 0) { - queryInput.ExpressionAttributeNames = exprNames; - } - if (startKey) { - queryInput.ExclusiveStartKey = startKey; - } - - // 4. Execute query - const result = await ddb.send(new QueryCommand(queryInput as any)); - const items = (result.Items ?? []) as TaskRecord[]; - const summaries = items.map(toTaskSummary); - - // 5. Encode pagination token - const nextToken = encodePaginationToken(result.LastEvaluatedKey as Record | undefined); - - return paginatedResponse(summaries, nextToken, requestId); + const pageItems = items.slice(0, limit); + + // 5. Encode pagination token. Trimmed: resume after the last task returned + // (LastEvaluatedKey lies past the over-fetched one). Otherwise the raw cursor, + // which is only set when the page cap stopped the loop. + const last = pageItems[pageItems.length - 1]; + const sortKey = SORT_KEY_OF[index]; + const nextToken = items.length > limit + ? encodePaginationToken({ task_id: last.task_id, user_id: last.user_id, [sortKey]: last[sortKey] }) + : encodePaginationToken(startKey); + + return paginatedResponse(pageItems.map(toTaskSummary), nextToken, requestId); } catch (err) { logger.error('Failed to list tasks', { error: String(err), request_id: requestId }); return errorResponse(500, ErrorCode.INTERNAL_ERROR, 'Internal server error.', requestId); diff --git a/cdk/src/handlers/list-webhooks.ts b/cdk/src/handlers/list-webhooks.ts index 9e179b374..0b83e9af2 100644 --- a/cdk/src/handlers/list-webhooks.ts +++ b/cdk/src/handlers/list-webhooks.ts @@ -36,6 +36,13 @@ const DEFAULT_PAGE_LIMIT = 20; /** Hard page-size ceiling. */ const MAX_PAGE_LIMIT = 100; +/** + * Cap on DynamoDB `Query` round-trips per request. `Limit` is applied to items read, + * before `FilterExpression`, so filtering out revoked webhooks can leave a page short; + * we page until it is full. The cap bounds what one request reads; the token still advances. + */ +const MAX_QUERY_PAGES = 10; + /** * GET /v1/webhooks — List webhooks for the authenticated user. */ @@ -49,7 +56,7 @@ export async function handler(event: APIGatewayProxyEvent): Promise | undefined; + if (items.length > limit || !startKey) break; + } + const pageItems = items.slice(0, limit); - const items = (result.Items ?? []) as WebhookRecord[]; - const nextToken = encodePaginationToken(result.LastEvaluatedKey as Record | undefined); + // Trimmed: resume after the last webhook returned (LastEvaluatedKey lies past the + // over-fetched one). Otherwise the raw cursor, which is only set when the page cap + // stopped the loop. + const last = pageItems[pageItems.length - 1]; + const nextToken = items.length > limit + ? encodePaginationToken({ webhook_id: last.webhook_id, user_id: last.user_id, created_at: last.created_at }) + : encodePaginationToken(startKey); - return paginatedResponse(items.map(toWebhookDetail), nextToken, requestId); + return paginatedResponse(pageItems.map(toWebhookDetail), nextToken, requestId); } catch (err) { logger.error('Failed to list webhooks', { error: String(err), request_id: requestId }); return errorResponse(500, ErrorCode.INTERNAL_ERROR, 'Internal server error.', requestId); diff --git a/cdk/src/handlers/reconcile-stranded-tasks.ts b/cdk/src/handlers/reconcile-stranded-tasks.ts index 4d5fa988f..ed03500ee 100644 --- a/cdk/src/handlers/reconcile-stranded-tasks.ts +++ b/cdk/src/handlers/reconcile-stranded-tasks.ts @@ -173,21 +173,26 @@ async function failStrandedTask(task: StrandedCandidate): Promise { + 'the runtime, or the agent container crashed during startup.'; // 1. Conditional status transition — only if still in the stranded state. + // The orchestrator that stamps the retention ttl at finalize may be gone + // or may never have started, so it is stamped here; a finalize that still + // comes overwrites it with its own. + const ttl = Math.floor(Date.now() / 1000) + TASK_RETENTION_DAYS * 24 * 3600; try { await ddb.send(new UpdateItemCommand({ TableName: TASK_TABLE, Key: { task_id: { S: task.task_id } }, UpdateExpression: 'SET #s = :failed, updated_at = :now, completed_at = :now, ' - + 'error_message = :err, status_created_at = :sca', + + 'error_message = :err, status_created_at = :sca, #ttl = :ttl', ConditionExpression: '#s = :expected', - ExpressionAttributeNames: { '#s': 'status' }, + ExpressionAttributeNames: { '#s': 'status', '#ttl': 'ttl' }, ExpressionAttributeValues: { ':failed': { S: 'FAILED' }, ':expected': { S: task.status }, ':now': { S: now }, ':err': { S: errorMessage }, ':sca': { S: `FAILED#${now}` }, + ':ttl': { N: String(ttl) }, }, })); } catch (err: unknown) { @@ -205,7 +210,6 @@ async function failStrandedTask(task: StrandedCandidate): Promise { // 2. Emit task_stranded + task_failed events. Best-effort — loss of an // event is acceptable; the task record is the source of truth. - const ttl = Math.floor(Date.now() / 1000) + TASK_RETENTION_DAYS * 24 * 3600; try { await ddb.send(new PutItemCommand({ TableName: EVENTS_TABLE, diff --git a/cdk/src/handlers/shared/create-task-core.ts b/cdk/src/handlers/shared/create-task-core.ts index f10d5b16b..82ae6ac0a 100644 --- a/cdk/src/handlers/shared/create-task-core.ts +++ b/cdk/src/handlers/shared/create-task-core.ts @@ -19,7 +19,8 @@ // HTTP create-task path: validation, persistence, orchestrator invoke. Related: orchestrator.ts, preflight.ts. // Idempotent replay: same user + same Idempotency-Key → 200 + TaskDetail (no duplicate write, no orchestrator re-invoke). -// Tests: cdk/test/handlers/shared/create-task-core.test.ts, cdk/test/handlers/create-task.test.ts +// Tests: cdk/test/handlers/shared/create-task-core.test.ts, cdk/test/handlers/shared/create-task-core-presign-failure.test.ts, +// cdk/test/handlers/create-task.test.ts import { BedrockRuntimeClient, ApplyGuardrailCommand } from '@aws-sdk/client-bedrock-runtime'; import { InvokeCommand, LambdaClient } from '@aws-sdk/client-lambda'; @@ -913,15 +914,18 @@ export async function createTaskCore( }); // Transition task to FAILED so it doesn't remain orphaned in PENDING_UPLOADS try { + const failedAt = new Date().toISOString(); await ddb.send(new UpdateCommand({ TableName: TABLE_NAME, Key: { task_id: taskId }, - UpdateExpression: 'SET #s = :failed, error_message = :err, updated_at = :now', - ExpressionAttributeNames: { '#s': 'status' }, + UpdateExpression: 'SET #s = :failed, error_message = :err, updated_at = :now, completed_at = :now, status_created_at = :sca, #ttl = :ttl', + ExpressionAttributeNames: { '#s': 'status', '#ttl': 'ttl' }, ExpressionAttributeValues: { ':failed': TaskStatus.FAILED, ':err': 'Failed to generate upload instructions. Please try again.', - ':now': new Date().toISOString(), + ':now': failedAt, + ':sca': `${TaskStatus.FAILED}#${failedAt}`, + ':ttl': computeTtlEpoch(TASK_RETENTION_DAYS), }, })); } catch (cleanupErr) { diff --git a/cdk/src/handlers/shared/github-comment.ts b/cdk/src/handlers/shared/github-comment.ts index 8af1cba66..25eeb38b8 100644 --- a/cdk/src/handlers/shared/github-comment.ts +++ b/cdk/src/handlers/shared/github-comment.ts @@ -340,8 +340,8 @@ function bgagentMarker(taskId: string): string { * accumulates the full history anyway. * * The numeric fields accept ``string`` alongside ``number | null`` to - * honestly model the DynamoDB Document-client boundary: ``Number`` - * attributes deserialize as JS ``string`` in some code paths (see + * honestly model what is stored: the agent writes ``duration_s`` and + * ``cost_usd`` as DynamoDB String attributes (see * ``shared/numeric.ts``). ``renderCommentBody`` coerces defensively so * a future caller that forgets to run the shared coercion helper at * its own boundary does not crash the way the fanout dispatcher did in diff --git a/cdk/src/handlers/shared/numeric.ts b/cdk/src/handlers/shared/numeric.ts index c7b242e83..c35ffd89a 100644 --- a/cdk/src/handlers/shared/numeric.ts +++ b/cdk/src/handlers/shared/numeric.ts @@ -20,19 +20,19 @@ /** * Numeric coercion helpers for the DynamoDB / Document-client boundary. * - * Rationale: the AWS SDK v3 Document client deserializes DynamoDB - * ``Number`` attributes as JavaScript ``string``s in some code paths - * (notably ``TaskRecord.{duration_s,cost_usd}`` from ``TaskTable``), - * even though our TypeScript types declare them as ``number | null``. - * Callers that go on to call ``.toFixed()`` / do arithmetic on those - * fields silently fail with ``TypeError: input.costUsd.toFixed is not - * a function`` (Scenario 7-extended deploy validation uncovered this - * in the GitHub fan-out dispatcher). + * Rationale: the Python agent stores ``cost_usd``, ``duration_s`` and the + * turn counters on the task row as DynamoDB String attributes + * (``agent/src/task_state.py::write_terminal`` passes them through + * ``str()``), and the Document client returns a String attribute as a + * JavaScript ``string``; only a Number attribute comes back as a ``number``. + * A caller that goes on to call ``.toFixed()`` on such a field fails + * with ``TypeError: input.costUsd.toFixed is not a function``, and + * ``+`` concatenates instead of adding (Scenario 7-extended deploy + * validation uncovered the first in the GitHub fan-out dispatcher). * * Use these helpers at any boundary that passes those fields on to - * numeric consumers. Adding a third call site is a signal that the - * underlying type declaration should be widened (``number | string | - * null``) at the DDB load boundary; for now, coerce locally. + * numeric consumers. ``TaskRecord`` declares them ``number | string``, + * so ``.toFixed()`` or arithmetic on the raw field does not compile. */ export interface CoerceContext { @@ -50,8 +50,8 @@ export interface CoerceLogger { /** * Coerce a value that should be a number but may arrive as a string - * (DynamoDB Document-client deserializes ``Number`` attributes as - * strings) into a finite ``number`` or ``null``. + * (the agent stores some task fields as DynamoDB String attributes) + * into a finite ``number`` or ``null``. * * Rules: * - ``null`` / ``undefined`` / empty-string → ``null`` (treated as diff --git a/cdk/src/handlers/shared/orchestrator.ts b/cdk/src/handlers/shared/orchestrator.ts index ec74f4aea..d8a47571e 100644 --- a/cdk/src/handlers/shared/orchestrator.ts +++ b/cdk/src/handlers/shared/orchestrator.ts @@ -1253,7 +1253,7 @@ export async function finalizeTask( log.info('Agent did not write memory — writing fallback episode'); try { // Coerce at the shared helper rather than ``Number(...)`` so a - // corrupt string ``cost_usd`` from the DDB Document client + // corrupt ``cost_usd`` (the agent stores it as a string) // collapses to ``undefined`` (and logs a warn) rather than // rendering ``Cost: $NaN.`` into the episode text — see // ``memory.ts::writeMinimalEpisode`` line 325 which calls diff --git a/cdk/src/handlers/shared/slack-format.ts b/cdk/src/handlers/shared/slack-format.ts index 0a86ae170..f9f065045 100644 --- a/cdk/src/handlers/shared/slack-format.ts +++ b/cdk/src/handlers/shared/slack-format.ts @@ -36,7 +36,7 @@ export function truncate(text: string, maxLen: number): string { * @param seconds - the duration in seconds. Non-numeric values are coerced with Number(). * @returns the formatted duration string. */ -export function formatDuration(seconds: number): string { +export function formatDuration(seconds: number | string): string { const s = Number(seconds); if (s < 60) return `${Math.round(s)}s`; const minutes = Math.floor(s / 60); diff --git a/cdk/src/handlers/shared/types.ts b/cdk/src/handlers/shared/types.ts index 36807c247..8d285cb70 100644 --- a/cdk/src/handlers/shared/types.ts +++ b/cdk/src/handlers/shared/types.ts @@ -227,8 +227,10 @@ export interface TaskRecord { readonly updated_at: string; readonly started_at?: string; readonly completed_at?: string; - readonly cost_usd?: number; - readonly duration_s?: number; + /** The agent stores these two and the turn counters below as DynamoDB + * Strings; read them through ``coerceNumericOrNull``. */ + readonly cost_usd?: number | string; + readonly duration_s?: number | string; readonly build_passed?: boolean; /** * A6/#299: whether a PR-iteration advanced the branch HEAD (a real commit) vs. @@ -278,10 +280,10 @@ export interface TaskRecord { readonly artifact_uri?: string; /** Rev-5 DATA-1: authoritative SDK counter including the attempt that * tripped any cap. Equals the legacy `turns` value. */ - readonly turns_attempted?: number; + readonly turns_attempted?: number | string; /** Rev-5 DATA-1: turns that actually completed (clamped to * `max_turns` when `agent_status='error_max_turns'`). */ - readonly turns_completed?: number; + readonly turns_completed?: number | string; readonly prompt_version?: string; readonly memory_written?: boolean; readonly compute_type?: ComputeType; @@ -930,12 +932,12 @@ export interface AgentAttachmentPayload { /** * Map a DynamoDB task record to the API detail response shape. * - * All numeric fields sourced from the DDB record are routed through - * ``coerceNumericOrNull`` — the Document-client deserializes DynamoDB - * ``Number`` attributes as JavaScript ``string``s in some code paths - * (see ``shared/numeric.ts`` for rationale), and any downstream caller - * doing arithmetic (``.toFixed``, comparison, math) on a string-typed - * "number" crashes at runtime. Coercing uniformly here means no caller + * The numeric fields that may be stored as strings are routed through + * ``coerceNumericOrNull`` — the agent stores some of them as DynamoDB + * String attributes, which arrive as JavaScript ``string``s + * (see ``shared/numeric.ts`` for rationale), and a downstream caller + * that calls ``.toFixed`` on a string-typed "number" crashes at + * runtime, while ``+`` concatenates. Coercing uniformly here means no caller * has to guess which TaskDetail numeric fields are safe — do not bypass * the helper when adding new numeric fields. * diff --git a/cdk/src/handlers/slack-interactions.ts b/cdk/src/handlers/slack-interactions.ts index 85a1e552e..26a468f2d 100644 --- a/cdk/src/handlers/slack-interactions.ts +++ b/cdk/src/handlers/slack-interactions.ts @@ -134,16 +134,20 @@ async function handleCancelAction(payload: SlackInteractionPayload, actionId: st // Attempt to cancel. QUEUED (#441) is cancellable — it removes the // task from the admission queue (no compute or concurrency to release). const CANCELLABLE_STATUSES = ['PENDING_UPLOADS', 'QUEUED', 'SUBMITTED', 'HYDRATING', 'RUNNING', 'AWAITING_APPROVAL', 'FINALIZING']; + // Terminal attributes as in cancel-task.ts, minus the ttl: the orchestrator + // stamps it when it finalizes the started task this button belongs to. + const now = new Date().toISOString(); try { await ddb.send(new UpdateCommand({ TableName: TASK_TABLE, Key: { task_id: taskId }, - UpdateExpression: 'SET #s = :cancelled, updated_at = :now', + UpdateExpression: 'SET #s = :cancelled, updated_at = :now, completed_at = :now, status_created_at = :sca', ConditionExpression: '#s IN (:s1, :s2, :s3, :s4, :s5, :s6, :s7)', ExpressionAttributeNames: { '#s': 'status' }, ExpressionAttributeValues: { ':cancelled': 'CANCELLED', - ':now': new Date().toISOString(), + ':now': now, + ':sca': `CANCELLED#${now}`, ':s1': CANCELLABLE_STATUSES[0], ':s2': CANCELLABLE_STATUSES[1], ':s3': CANCELLABLE_STATUSES[2], diff --git a/cdk/src/handlers/slack-link.ts b/cdk/src/handlers/slack-link.ts index 32f8d182c..3cf85cfc2 100644 --- a/cdk/src/handlers/slack-link.ts +++ b/cdk/src/handlers/slack-link.ts @@ -63,7 +63,9 @@ export async function handler(event: APIGatewayProxyEvent): Promise { expect(processors[0].Properties.Timeout).toBeGreaterThanOrEqual(120); }); - test('webhook dedup table has TTL attribute for 60s expiry', () => { + test('webhook dedup table has a TTL attribute', () => { template.hasResourceProperties('AWS::DynamoDB::Table', { KeySchema: [{ AttributeName: 'dedup_key', KeyType: 'HASH' }], TimeToLiveSpecification: { AttributeName: 'ttl', Enabled: true }, diff --git a/cdk/test/constructs/task-api.test.ts b/cdk/test/constructs/task-api.test.ts index be1be9304..dadd95b7c 100644 --- a/cdk/test/constructs/task-api.test.ts +++ b/cdk/test/constructs/task-api.test.ts @@ -96,6 +96,31 @@ function createStackWithBudget(): { stack: Stack; template: Template } { return { stack, template: Template.fromStack(stack) }; } +// Presigned-upload flow: the attachments bucket and the user-concurrency table +// together are what make TaskApi create the confirm-uploads Lambda. +function createStackWithAttachments(overrides?: Partial): { stack: Stack; template: Template } { + const app = new App(); + const stack = new Stack(app, 'TestStack'); + const taskTable = new dynamodb.Table(stack, 'TaskTable', { + partitionKey: { name: 'task_id', type: dynamodb.AttributeType.STRING }, + }); + const taskEventsTable = new dynamodb.Table(stack, 'TaskEventsTable', { + partitionKey: { name: 'task_id', type: dynamodb.AttributeType.STRING }, + sortKey: { name: 'event_id', type: dynamodb.AttributeType.STRING }, + }); + const userConcurrencyTable = new dynamodb.Table(stack, 'UserConcurrencyTable', { + partitionKey: { name: 'user_id', type: dynamodb.AttributeType.STRING }, + }); + new TaskApi(stack, 'TaskApi', { + taskTable, + taskEventsTable, + attachmentsBucket: new s3.Bucket(stack, 'AttachmentsBucket'), + userConcurrencyTable, + ...overrides, + }); + return { stack, template: Template.fromStack(stack) }; +} + // Full surface: webhookTable AND apiKeyTable both provided (all tables in the // same app/stack — CDK forbids cross-app resource references). function createStackWithWebhooksAndApiKeys(): { stack: Stack; template: Template } { @@ -242,6 +267,24 @@ describe('TaskApi construct', () => { expect(replayFn![1].Properties.MemorySize).toBe(512); }); + test('ListTasksFn gets raised timeout/memory, not the 3s/128MB defaults (#51)', () => { + // A filtered list pages until the page is full (up to 10 Queries). + const functions = baseTemplate.findResources('AWS::Lambda::Function'); + const listTasksFn = Object.entries(functions).find(([id]) => id.startsWith('TaskApiListTasksFn')); + expect(listTasksFn).toBeDefined(); + expect(listTasksFn![1].Properties.Timeout).toBe(15); + expect(listTasksFn![1].Properties.MemorySize).toBe(256); + }); + + test('ListTasksFn may describe the task table: it asks whether the list index is ACTIVE (#51)', () => { + const policies = baseTemplate.findResources('AWS::IAM::Policy'); + const listTasksPolicy = Object.entries(policies) + .find(([id]) => id.startsWith('TaskApiListTasksFnServiceRoleDefaultPolicy')); + const statements = (listTasksPolicy?.[1].Properties.PolicyDocument.Statement ?? []) as { Action: string[]; Resource: unknown }[]; + const taskTableRead = statements.find((statement) => JSON.stringify(statement.Resource).includes('"TaskTable')); + expect(taskTableRead?.Action).toEqual(expect.arrayContaining(['dynamodb:Query', 'dynamodb:DescribeTable'])); + }); + test('Lambda functions have correct environment variables', () => { const functions = baseTemplate.findResources('AWS::Lambda::Function'); @@ -652,6 +695,24 @@ describe('TaskApi construct with webhooks', () => { }); }); +describe('TaskApi construct — confirm-uploads admission cap', () => { + /** MAX_CONCURRENT_TASKS_PER_USER as the confirm-uploads Lambda receives it. */ + function confirmUploadsCap(template: Template): unknown { + const confirmUploadsFn = Object.entries(template.findResources('AWS::Lambda::Function')) + .find(([id]) => id.startsWith('TaskApiConfirmUploadsFn')); + expect(confirmUploadsFn).toBeDefined(); + return confirmUploadsFn![1].Properties.Environment.Variables.MAX_CONCURRENT_TASKS_PER_USER; + } + + test('ConfirmUploadsFn gets the per-user cap (default 10), not the handler fallback of 3', () => { + expect(confirmUploadsCap(createStackWithAttachments().template)).toBe('10'); + }); + + test('ConfirmUploadsFn respects custom maxConcurrentTasksPerUser', () => { + expect(confirmUploadsCap(createStackWithAttachments({ maxConcurrentTasksPerUser: 5 }).template)).toBe('5'); + }); +}); + describe('TaskApi construct — nudge endpoint (Phase 2)', () => { let nudgeTemplate: Template; diff --git a/cdk/test/constructs/task-table.test.ts b/cdk/test/constructs/task-table.test.ts index 0da53df26..1eceb958b 100644 --- a/cdk/test/constructs/task-table.test.ts +++ b/cdk/test/constructs/task-table.test.ts @@ -75,6 +75,21 @@ describe('TaskTable', () => { }); }); + test('creates UserCreatedAtIndex GSI', () => { + template.hasResourceProperties('AWS::DynamoDB::Table', { + GlobalSecondaryIndexes: Match.arrayWith([ + Match.objectLike({ + IndexName: 'UserCreatedAtIndex', + KeySchema: [ + { AttributeName: 'user_id', KeyType: 'HASH' }, + { AttributeName: 'created_at', KeyType: 'RANGE' }, + ], + Projection: { ProjectionType: 'ALL' }, + }), + ]), + }); + }); + test('creates StatusIndex GSI', () => { template.hasResourceProperties('AWS::DynamoDB::Table', { GlobalSecondaryIndexes: Match.arrayWith([ @@ -173,6 +188,7 @@ describe('TaskTable', () => { test('static index name constants match actual GSI names', () => { expect(TaskTable.USER_STATUS_INDEX).toBe('UserStatusIndex'); + expect(TaskTable.USER_CREATED_AT_INDEX).toBe('UserCreatedAtIndex'); expect(TaskTable.STATUS_INDEX).toBe('StatusIndex'); expect(TaskTable.IDEMPOTENCY_INDEX).toBe('IdempotencyIndex'); expect(TaskTable.LINEAR_ISSUE_INDEX).toBe('LinearIssueIndex'); diff --git a/cdk/test/emulator/concurrency-seats.emulator.ts b/cdk/test/emulator/concurrency-seats.emulator.ts new file mode 100644 index 000000000..3d5d02786 --- /dev/null +++ b/cdk/test/emulator/concurrency-seats.emulator.ts @@ -0,0 +1,191 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +/** + * Per-user concurrency seats against the AWS Emulator (ADR-013 Tier 2a). + * + * A seat is one unit of `active_count` in UserConcurrencyTable: admission takes + * it with a conditional increment and finalization gives it back. The durable + * `orchestrate-task` entry point needs the Lambda durable-execution service, so + * these tests call the functions its steps call (`shared/orchestrator.ts`), plus + * the real `create-task`, `get-task` and `reconcile-concurrency` handlers. + * + * Runs only through `jest.emulator.config.js` (see ./harness). + */ + +import { randomUUID } from 'node:crypto'; +import { GetCommand, UpdateCommand } from '@aws-sdk/lib-dynamodb'; +import { apiEvent, emulatorTables } from './harness'; +import { TaskEventsTable } from '../../src/constructs/task-events-table'; +import { TaskStatus } from '../../src/constructs/task-status'; +import { TaskTable } from '../../src/constructs/task-table'; +import { UserConcurrencyTable } from '../../src/constructs/user-concurrency-table'; + +const MAX_SEATS = 3; + +// Handlers read their configuration at module load, so the environment is set +// before any handler is imported. Names are unique to this file's run. +const run = randomUUID().slice(0, 8); +process.env.TASK_TABLE_NAME = `emu-${run}-tasks`; +process.env.TASK_EVENTS_TABLE_NAME = `emu-${run}-events`; +process.env.USER_CONCURRENCY_TABLE_NAME = `emu-${run}-seats`; +process.env.MAX_CONCURRENT_TASKS_PER_USER = String(MAX_SEATS); + +import { handler as createTask } from '../../src/handlers/create-task'; +import { handler as getTask } from '../../src/handlers/get-task'; +import { handler as reconcileConcurrency } from '../../src/handlers/reconcile-concurrency'; +import { admissionControl, finalizeTask, loadTask, queueTask, transitionTask } from '../../src/handlers/shared/orchestrator'; +import type { TaskRecord } from '../../src/handlers/shared/types'; +import { makeDocClient } from '../../src/handlers/shared/ua'; + +const ddb = makeDocClient(); + +/** A user no other test has written for, so tests need no cleanup between them. */ +const newUser = (): string => `user-${randomUUID()}`; + +/** Submit a repo-less task through the real create-task handler and load its record. */ +async function submitted(userId: string): Promise { + const result = await createTask(apiEvent(userId, { httpMethod: 'POST', body: JSON.stringify({ task_description: 'Summarize the open issues' }) })); + expect(result.statusCode).toBe(201); + return loadTask(JSON.parse(result.body).data.task_id); +} + +/** Take a submitted task as far as RUNNING the way the orchestrator's steps do: admit, hydrate, start. */ +async function running(userId: string): Promise { + const task = await submitted(userId); + expect(await admissionControl(task)).toBe(true); + await transitionTask(task.task_id, TaskStatus.SUBMITTED, TaskStatus.HYDRATING); + await transitionTask(task.task_id, TaskStatus.HYDRATING, TaskStatus.RUNNING); + return task.task_id; +} + +/** The agent's terminal write: RUNNING to COMPLETED. */ +async function complete(taskId: string): Promise { + await transitionTask(taskId, TaskStatus.RUNNING, TaskStatus.FINALIZING); + await transitionTask(taskId, TaskStatus.FINALIZING, TaskStatus.COMPLETED); +} + +/** Seats the user holds according to UserConcurrencyTable. */ +async function seats(userId: string): Promise { + const { Item } = await ddb.send(new GetCommand({ + TableName: process.env.USER_CONCURRENCY_TABLE_NAME, + Key: { user_id: userId }, + ConsistentRead: true, + })); + return Item?.active_count ?? 0; +} + +describe('concurrency seats against the AWS Emulator', () => { + emulatorTables((stack) => { + new TaskTable(stack, 'Tasks', { tableName: process.env.TASK_TABLE_NAME }); + new TaskEventsTable(stack, 'Events', { tableName: process.env.TASK_EVENTS_TABLE_NAME }); + new UserConcurrencyTable(stack, 'Seats', { tableName: process.env.USER_CONCURRENCY_TABLE_NAME }); + }); + + test('racing admissions never exceed the cap, and the losers queue in FIFO order', async () => { + const user = newUser(); + const tasks: TaskRecord[] = []; + for (let i = 0; i < MAX_SEATS + 2; i++) tasks.push(await submitted(user)); + + // eslint-disable-next-line @cdklabs/promiseall-no-unbounded-parallelism -- fixed-size fixture, not input-derived + const admitted = await Promise.all(tasks.map((task) => admissionControl(task))); + + expect(admitted.filter(Boolean)).toHaveLength(MAX_SEATS); + expect(await seats(user)).toBe(MAX_SEATS); + + // The orchestrator parks a task that lost admission; GET then ranks it among the user's queued tasks. + const losers = tasks.filter((_, i) => !admitted[i]); + for (const task of losers) expect(await queueTask(task)).toBe(true); + const positions: number[] = []; + for (const task of losers) { + const result = await getTask(apiEvent(user, { pathParameters: { task_id: task.task_id } })); + positions.push(JSON.parse(result.body).data.queue_position); + } + const fifo = losers.map((task) => `${task.created_at}#${task.task_id}`); + expect(positions).toEqual(fifo.map((key) => [...fifo].sort().indexOf(key) + 1)); + expect(await seats(user)).toBe(MAX_SEATS); + }); + + test('finalizing a completed task gives back exactly its own seat', async () => { + const user = newUser(); + const done = await running(user); + await running(user); + expect(await seats(user)).toBe(2); + + await complete(done); + await finalizeTask(done, { attempts: 1 }, user); + + expect(await seats(user)).toBe(1); + }); + + test('the concurrency reconciler repairs a leaked seat from the real index', async () => { + const user = newUser(); + await running(user); + // A seat with no live task behind it, as a finalize step that never ran leaves. + expect(await admissionControl({ user_id: user } as TaskRecord)).toBe(true); + expect(await seats(user)).toBe(2); + + await reconcileConcurrency(); + + expect(await seats(user)).toBe(1); + }); + + // KNOWN FAILURES: executable witnesses for two seat defects on main, reproduced + // here with real conditional writes rather than mocked `send` calls. Kept as + // `test.failing` so the suite stays green and flags the day the fix lands (open + // PR #1009 addresses both). Each was run once as a plain `test` to confirm it + // fails on its last assertion and not on setup; the passing tests above cover + // the same setup. + test.failing('#1003: a replayed finalize step does not release a second seat', async () => { + const user = newUser(); + const done = await running(user); + await running(user); + await complete(done); + + // Durable execution re-runs a step whose result it did not record. + await finalizeTask(done, { attempts: 1 }, user); + await finalizeTask(done, { attempts: 1 }, user); + + expect(await seats(user)).toBe(1); + }); + + // No issue reports this one: reconcile-concurrency counts four hard-coded + // statuses, while the design and ACTIVE_STATUSES say a task awaiting approval + // holds its seat. + test.failing('the concurrency reconciler keeps the seat of a task awaiting approval', async () => { + const user = newUser(); + const paused = await running(user); + // The Python agent is the only writer of this status; this writes the status + // attributes its approval-request transition writes. + await ddb.send(new UpdateCommand({ + TableName: process.env.TASK_TABLE_NAME, + Key: { task_id: paused }, + UpdateExpression: 'SET #status = :awaiting, status_created_at = :sca', + ExpressionAttributeNames: { '#status': 'status' }, + ExpressionAttributeValues: { + ':awaiting': TaskStatus.AWAITING_APPROVAL, + ':sca': `${TaskStatus.AWAITING_APPROVAL}#${new Date().toISOString()}`, + }, + })); + + await reconcileConcurrency(); + + expect(await seats(user)).toBe(1); + }); +}); diff --git a/cdk/test/emulator/harness.ts b/cdk/test/emulator/harness.ts new file mode 100644 index 000000000..c8a40e615 --- /dev/null +++ b/cdk/test/emulator/harness.ts @@ -0,0 +1,144 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +/** + * Shared setup for the emulator-backed handler tests (ADR-013 Tier 2a). + * + * These suites run real handler code in-process and let its AWS calls go over + * the wire to an AWS Emulator (https://github.com/aws/aws-emulator). Nothing + * here configures an endpoint: the SDK clients the handlers already build pick + * up AWS_ENDPOINT_URL, AWS_REGION and the emulator's credentials file from the + * environment, and Node trusts its certificate through NODE_EXTRA_CA_CERTS. + * + * The files are named `*.emulator.ts`, which the unit configuration does not + * match. They run only through `jest.emulator.config.js` + * (`mise run test:integration`), which refuses to start unless that + * environment is the emulator's and the emulator answers. + * + * The emulator keeps state in memory and has no reset route. Each test file + * therefore names its tables uniquely (so files can share one instance, run in + * parallel and be re-run without a restart), and each test writes under a user + * id of its own (so tests need no cleanup between them). + */ + +import { + type AttributeDefinition, CreateTableCommand, DeleteTableCommand, DynamoDBClient, type GlobalSecondaryIndex, + UpdateTableCommand, waitUntilTableExists, +} from '@aws-sdk/client-dynamodb'; +import { App, Stack } from 'aws-cdk-lib'; +import { Template } from 'aws-cdk-lib/assertions'; +import type { APIGatewayProxyEvent } from 'aws-lambda'; + +/** Timeout for table setup (ms). The emulator alone holds a new table in CREATING for 3 s; Jest's default is 5 s. */ +const SETUP_TIMEOUT_MS = 30_000; + +/** How long to wait for a new table to become ACTIVE (seconds). Shorter than the hook, so its own error is the one shown. */ +const TABLE_WAIT_SECONDS = 20; + +/** + * Give the enclosing `describe` the DynamoDB tables that `declare` adds to a + * stack: created on the emulator before its tests and deleted after them. + * + * The CreateTable inputs are read from the synthesized template, so key schema + * and indexes are the constructs' own. A handler that queries an index its + * construct no longer declares fails here instead of after a deploy. + * + * Streams and point-in-time recovery are not carried over. Neither is TTL, on + * purpose: the emulator deletes an expired item within a second where AWS takes + * up to days, so with TTL on, code that forgets to compare `ttl` with the clock + * looks correct here. + * @param declare - instantiates the table constructs under test, each with an explicit `tableName`. + * @param seed - writes the rows every test in the file needs, once the tables are ACTIVE. + * @param withoutIndexes - per table name, index names to leave out: the table as it was before a + * deploy added them. The table or another index must still use their key attributes. + * @returns a function that adds one of those indexes, as that deploy does, from the construct's definition. + */ +export function emulatorTables( + declare: (stack: Stack) => void, + seed?: () => Promise, + withoutIndexes: Record = {}, +): (tableName: string, indexName: string) => Promise { + let ddb: DynamoDBClient | undefined; + const created: string[] = []; + const declared: Record = {}; + + beforeAll(async () => { + const stack = new Stack(new App(), 'EmulatorTables'); + declare(stack); + ddb = new DynamoDBClient({}); + for (const [logicalId, { Properties: table }] of Object.entries(Template.fromStack(stack).findResources('AWS::DynamoDB::Table'))) { + if (typeof table.TableName !== 'string') { + throw new Error(`Table ${logicalId} has no literal tableName; pass one to its construct so the handler environment can name it.`); + } + declared[table.TableName] = table; + await ddb.send(new CreateTableCommand({ + TableName: table.TableName, + AttributeDefinitions: table.AttributeDefinitions, + KeySchema: table.KeySchema, + GlobalSecondaryIndexes: table.GlobalSecondaryIndexes + ?.filter((index: { IndexName: string }) => !withoutIndexes[table.TableName]?.includes(index.IndexName)), + BillingMode: table.BillingMode, + })); + created.push(table.TableName); + } + // Create them all before waiting: the CREATING window then costs one wait, not one per table. + for (const TableName of created) { + await waitUntilTableExists({ client: ddb, maxWaitTime: TABLE_WAIT_SECONDS, minDelay: 1 }, { TableName }); + } + await seed?.(); + }, SETUP_TIMEOUT_MS); + + afterAll(async () => { + for (const TableName of created) await ddb?.send(new DeleteTableCommand({ TableName })); + ddb?.destroy(); + }); + + return async (tableName, indexName) => { + const { AttributeDefinitions, GlobalSecondaryIndexes } = declared[tableName]; + const Create = GlobalSecondaryIndexes?.find((index) => index.IndexName === indexName); + await ddb?.send(new UpdateTableCommand({ TableName: tableName, AttributeDefinitions, GlobalSecondaryIndexUpdates: [{ Create }] })); + }; +} + +/** + * An API Gateway proxy event as the Cognito authorizer would deliver it. + * @param userId - the authenticated caller (`claims.sub`). + * @param overrides - request parts the call under test needs (body, headers, path or query parameters). + * @returns the event. + */ +export function apiEvent(userId: string, overrides: Partial = {}): APIGatewayProxyEvent { + return { + body: null, + headers: {}, + multiValueHeaders: {}, + httpMethod: 'GET', + isBase64Encoded: false, + path: '/v1/tasks', + pathParameters: null, + queryStringParameters: null, + multiValueQueryStringParameters: null, + stageVariables: null, + resource: '/tasks', + requestContext: { + authorizer: { claims: { sub: userId } }, + identity: { sourceIp: '127.0.0.1', userAgent: 'jest' }, + } as unknown as APIGatewayProxyEvent['requestContext'], + ...overrides, + }; +} diff --git a/cdk/test/emulator/task-api.emulator.ts b/cdk/test/emulator/task-api.emulator.ts new file mode 100644 index 000000000..cb94427f5 --- /dev/null +++ b/cdk/test/emulator/task-api.emulator.ts @@ -0,0 +1,249 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +/** + * Task API lifecycle against the AWS Emulator (ADR-013 Tier 2a). + * + * The real handler entry points run in-process; only their AWS calls leave the + * process, to an emulator whose tables are created from the CDK constructs. + * Nothing is mocked, so these tests see what `jest.mock('@aws-sdk/...')` tests + * cannot: index key order, `Limit` before `FilterExpression`, and the state a + * sequence of real conditional writes leaves behind. + * + * Runs only through `jest.emulator.config.js` (see ./harness). + */ + +import { randomUUID } from 'node:crypto'; +import { DescribeTableCommand } from '@aws-sdk/client-dynamodb'; +import { PutCommand } from '@aws-sdk/lib-dynamodb'; +import type { APIGatewayProxyResult } from 'aws-lambda'; +import { apiEvent, emulatorTables } from './harness'; +import { RepoTable } from '../../src/constructs/repo-table'; +import { TaskEventsTable } from '../../src/constructs/task-events-table'; +import { TaskTable } from '../../src/constructs/task-table'; + +// Handlers read their table names at module load, so the environment is set +// before any handler is imported. Names are unique to this file's run. +const run = randomUUID().slice(0, 8); +process.env.TASK_TABLE_NAME = `emu-${run}-tasks`; +process.env.TASK_EVENTS_TABLE_NAME = `emu-${run}-events`; +process.env.REPO_TABLE_NAME = `emu-${run}-repos`; +/** A task table as a stack has it before the deploy that adds UserCreatedAtIndex (#51). */ +const TASKS_BEFORE_51 = `emu-${run}-tasks-before-51`; + +import { handler as cancelTask } from '../../src/handlers/cancel-task'; +import { handler as createTask } from '../../src/handlers/create-task'; +import { handler as getTask } from '../../src/handlers/get-task'; +import { handler as getTaskEvents } from '../../src/handlers/get-task-events'; +import { handler as listTasks } from '../../src/handlers/list-tasks'; +import { makeDocClient } from '../../src/handlers/shared/ua'; + +const REPO = 'acme/widgets'; +const CONCURRENT_CANCELS = 8; + +/** A user no other test has written for, so tests need no cleanup between them. */ +const newUser = (): string => `user-${randomUUID()}`; +const data = (result: APIGatewayProxyResult) => JSON.parse(result.body).data; +const byId = (taskId: string) => ({ pathParameters: { task_id: taskId } }); +const pause = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); + +/** POST /v1/tasks through the real handler. Returns the HTTP result. */ +function submit(userId: string, idempotencyKey?: string): Promise { + return createTask(apiEvent(userId, { + httpMethod: 'POST', + headers: idempotencyKey ? { 'Idempotency-Key': idempotencyKey } : {}, + body: JSON.stringify({ repo: REPO, workflow_ref: 'coding/new-task-v1', task_description: 'Add a health check endpoint' }), + })); +} + +/** GET /v1/tasks through the real handler. Returns the parsed body. */ +async function list(userId: string, query?: Record, handler = listTasks) { + const result = await handler(apiEvent(userId, { queryStringParameters: query ?? null })); + expect(result.statusCode).toBe(200); + return JSON.parse(result.body) as { data: { task_id: string; status: string }[]; pagination: { next_token: string | null; has_more: boolean } }; +} + +describe('task API against the AWS Emulator', () => { + const addIndex = emulatorTables((stack) => { + new TaskTable(stack, 'Tasks', { tableName: process.env.TASK_TABLE_NAME }); + new TaskTable(stack, 'TasksBefore51', { tableName: TASKS_BEFORE_51 }); + new TaskEventsTable(stack, 'Events', { tableName: process.env.TASK_EVENTS_TABLE_NAME }); + new RepoTable(stack, 'Repos', { tableName: process.env.REPO_TABLE_NAME }); + }, () => { + // The row a Blueprint writes at deploy time; create-task gates on it. + const now = new Date().toISOString(); + return makeDocClient().send(new PutCommand({ + TableName: process.env.REPO_TABLE_NAME, + Item: { repo: REPO, status: 'active', onboarded_at: now, updated_at: now }, + })); + }, { [TASKS_BEFORE_51]: [TaskTable.USER_CREATED_AT_INDEX] }); + + test('create, get, list, cancel: one task through every handler', async () => { + const user = newUser(); + + const created = await submit(user); + expect(created.statusCode).toBe(201); + const taskId: string = data(created).task_id; + expect(data(created)).toMatchObject({ status: 'SUBMITTED', repo: REPO }); + + expect(data(await getTask(apiEvent(user, byId(taskId))))).toMatchObject({ task_id: taskId, status: 'SUBMITTED' }); + expect((await getTask(apiEvent(newUser(), byId(taskId)))).statusCode).toBe(403); + expect((await list(user)).data.map((t) => t.task_id)).toEqual([taskId]); + + const cancelled = await cancelTask(apiEvent(user, byId(taskId))); + expect(cancelled.statusCode).toBe(200); + expect((await cancelTask(apiEvent(user, byId(taskId)))).statusCode).toBe(409); + + // The cancel changed the status, so the task has moved between status filters. + expect(data(await getTask(apiEvent(user, byId(taskId)))).status).toBe('CANCELLED'); + expect((await list(user, { status: 'CANCELLED' })).data.map((t) => t.task_id)).toEqual([taskId]); + expect((await list(user, { status: 'SUBMITTED' })).data).toEqual([]); + + const events = data(await getTaskEvents(apiEvent(user, byId(taskId)))); + expect(events.map((e: { event_type: string }) => e.event_type)).toEqual(['task_created', 'task_cancelled']); + }); + + test('replaying an Idempotency-Key returns the original task and creates nothing', async () => { + const user = newUser(); + const key = `key-${randomUUID()}`; + + const first = await submit(user, key); + const replay = await submit(user, key); + + expect(first.statusCode).toBe(201); + expect(replay.statusCode).toBe(200); + expect(replay.headers).toMatchObject({ 'Idempotent-Replay': 'true' }); + expect(data(replay).task_id).toBe(data(first).task_id); + expect((await list(user)).data).toHaveLength(1); + + // The key is global, not per user: someone else reusing it is refused, not handed the task. + expect((await submit(newUser(), key)).statusCode).toBe(409); + }); + + // An outcome test: a loser is refused either by cancel-task's read of the task or + // by its conditional write, depending on timing, and this cannot tell which. The + // test that fails when a condition is missing is 'racing admissions' in + // concurrency-seats.emulator.ts. + test('concurrent cancels: one succeeds, the rest are refused, one event is recorded', async () => { + const user = newUser(); + const taskId: string = data(await submit(user)).task_id; + + // eslint-disable-next-line @cdklabs/promiseall-no-unbounded-parallelism -- fixed-size fixture, not input-derived + const results = await Promise.all(Array.from({ length: CONCURRENT_CANCELS }, () => cancelTask(apiEvent(user, byId(taskId))))); + + expect(results.map((r) => r.statusCode).sort()).toEqual([200, ...Array(CONCURRENT_CANCELS - 1).fill(409)]); + const events = data(await getTaskEvents(apiEvent(user, byId(taskId)))); + expect(events.filter((e: { event_type: string }) => e.event_type === 'task_cancelled')).toHaveLength(1); + }); + + test('list pages through the index without losing or repeating a task', async () => { + const user = newUser(); + const submitted: string[] = []; + for (let i = 0; i < 5; i++) submitted.push(data(await submit(user)).task_id); + + const seen: string[] = []; + let nextToken: string | null = null; + let pages = 0; + do { + const page = await list(user, { limit: '2', ...(nextToken && { next_token: nextToken }) }); + seen.push(...page.data.map((t) => t.task_id)); + nextToken = page.pagination.next_token; + pages++; + } while (nextToken); + + expect(pages).toBe(3); + expect([...seen].sort()).toEqual([...submitted].sort()); + }); + + test('#51: list returns the newest task first (API_CONTRACT.md: "ordered by created_at descending")', async () => { + const user = newUser(); + const older: string = data(await submit(user)).task_id; + await pause(5); + const newer: string = data(await submit(user)).task_id; + await cancelTask(apiEvent(user, byId(newer))); + + expect((await list(user)).data.map((t) => t.task_id)).toEqual([newer, older]); + }); + + test('#51: a status filter returns the matching task when it fits the page', async () => { + const user = newUser(); + const first: string = data(await submit(user)).task_id; + // Three newer tasks: the match lies beyond the first Query, which reads limit + 1 rows. + await submit(user); + await submit(user); + await submit(user); + await cancelTask(apiEvent(user, byId(first))); + + expect((await list(user, { status: 'CANCELLED', limit: '2' })).data.map((t) => t.task_id)).toEqual([first]); + }); + + // The deploy that adds UserCreatedAtIndex updates the handler while DynamoDB is still + // building the index, and an index cannot be queried until it is ACTIVE. This walks a + // table through that deploy: no such index, the index being created, the index ACTIVE. + test('#51: the list reads UserStatusIndex until UserCreatedAtIndex is ACTIVE, then lists newest first', async () => { + let listBefore51!: typeof listTasks; + jest.isolateModules(() => { + const current = process.env.TASK_TABLE_NAME; + process.env.TASK_TABLE_NAME = TASKS_BEFORE_51; + // eslint-disable-next-line @typescript-eslint/no-require-imports -- a second copy of the handler, bound to this table when it loads + listBefore51 = require('../../src/handlers/list-tasks').handler; + process.env.TASK_TABLE_NAME = current; + }); + const doc = makeDocClient(); + const indexStatus = async () => (await doc.send(new DescribeTableCommand({ TableName: TASKS_BEFORE_51 }))) + .Table?.GlobalSecondaryIndexes?.find((index) => index.IndexName === TaskTable.USER_CREATED_AT_INDEX)?.IndexStatus; + const ids = (page: { data: { task_id: string }[] }) => page.data.map((t) => t.task_id); + + // UserStatusIndex sorts by status before time, so its order is not newest first here. + const user = newUser(); + const tasks = [['oldest', 'RUNNING'], ['middle', 'COMPLETED'], ['newest', 'SUBMITTED']]; + for (const [day, [taskId, status]] of tasks.entries()) { + const createdAt = `2026-01-0${day + 1}T00:00:00.000Z`; + await doc.send(new PutCommand({ + TableName: TASKS_BEFORE_51, + Item: { task_id: taskId, user_id: user, status, repo: REPO, created_at: createdAt, status_created_at: `${status}#${createdAt}` }, + })); + } + const byStatus = ['newest', 'oldest', 'middle']; + + // 1. No such index: the list is read from UserStatusIndex, with cursors of that index. + const first = await list(user, { limit: '2' }, listBefore51); + const cursor = first.pagination.next_token ?? ''; + expect(Buffer.from(cursor, 'base64').toString('utf-8')).toContain('"status_created_at"'); + const second = await list(user, { limit: '2', next_token: cursor }, listBefore51); + expect([...ids(first), ...ids(second)]).toEqual(byStatus); + + try { + // 2. The index is being created (the emulator holds it in CREATING for about 3 seconds). + // The status only moves forward, so CREATING after the list means CREATING during it. + await addIndex(TASKS_BEFORE_51, TaskTable.USER_CREATED_AT_INDEX); + const whileCreating = await list(user, undefined, listBefore51); + expect(await indexStatus()).toBe('CREATING'); + expect(ids(whileCreating)).toEqual(byStatus); + + // 3. The index is ACTIVE: newest first, and a cursor issued earlier still finishes its list. + while (await indexStatus() !== 'ACTIVE') await pause(250); + expect(ids(await list(user, undefined, listBefore51))).toEqual(['newest', 'middle', 'oldest']); + expect(ids(await list(user, { limit: '2', next_token: cursor }, listBefore51))).toEqual(['middle']); + } finally { + // A table cannot be deleted while one of its indexes is being created. + while (await indexStatus() === 'CREATING') await pause(250); + } + }, 30_000); +}); diff --git a/cdk/test/emulator/trace-api-shim.ts b/cdk/test/emulator/trace-api-shim.ts new file mode 100644 index 000000000..23dd36ae4 --- /dev/null +++ b/cdk/test/emulator/trace-api-shim.ts @@ -0,0 +1,71 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +/** + * Stand-in for API Gateway in front of the real `get-trace-url` Lambda handler. + * + * Started by `agent/tests_emulator/test_trace_round_trip.py` (through `tsx`) so + * that pytest and the real `bgagent` CLI can reach the handler over HTTP. It + * only translates an HTTP request into the proxy event API Gateway would build + * and writes the handler's result back; every decision is the handler's own. + * + * API Gateway's Cognito authorizer would put the verified caller in + * `requestContext.authorizer.claims.sub`. Here the caller is whoever the + * `X-API-Key` header names — the header the CLI sends for `BGAGENT_API_KEY`. + * + * Prints `{"port": }` on stdout once it is listening. + */ + +import { createServer } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import { handler } from '../../src/handlers/get-trace-url'; + +// The handler makes real SDK calls and trusts whatever caller the header names, +// so this serves it only when those calls are bound for an emulator on loopback. +if (!/^https:\/\/127\.0\.0\.1:\d+$/.test(process.env.AWS_ENDPOINT_URL ?? '')) { + throw new Error('trace-api-shim serves only against an AWS Emulator (AWS_ENDPOINT_URL=https://127.0.0.1:).'); +} + +const TRACE_ROUTE = /^\/tasks\/([^/]+)\/trace$/; + +const server = createServer((req, res) => { + const match = TRACE_ROUTE.exec(new URL(req.url ?? '/', 'http://shim').pathname); + if (req.method !== 'GET' || !match) { + res.writeHead(404).end(); + return; + } + const caller = req.headers['x-api-key']; + const event = { + httpMethod: 'GET', + path: req.url, + headers: req.headers, + pathParameters: { task_id: decodeURIComponent(match[1]) }, + requestContext: { + authorizer: typeof caller === 'string' ? { claims: { sub: caller } } : undefined, + }, + }; + handler(event as never).then( + (result) => res.writeHead(result.statusCode, result.headers as Record).end(result.body), + (err: unknown) => res.writeHead(500).end(String(err)), + ); +}); + +server.listen(0, '127.0.0.1', () => { + process.stdout.write(`${JSON.stringify({ port: (server.address() as AddressInfo).port })}\n`); +}); diff --git a/cdk/test/handlers/confirm-uploads.test.ts b/cdk/test/handlers/confirm-uploads.test.ts index dfa211fc6..14399dab4 100644 --- a/cdk/test/handlers/confirm-uploads.test.ts +++ b/cdk/test/handlers/confirm-uploads.test.ts @@ -309,6 +309,9 @@ describe('confirm-uploads handler', () => { expect(result.statusCode).toBe(400); const body = JSON.parse(result.body); expect(body.error.code).toBe('ATTACHMENT_BLOCKED'); + // The task is failed as a complete terminal row. + const failing = ddbSend.mock.calls.find((call: any[]) => call[0]?.input?.ExpressionAttributeValues?.[':failed']); + expect(failing?.[0].input.UpdateExpression).toContain('completed_at = :now'); }); test('skips S3 cleanup when failTaskOnScreening loses the race (ConditionalCheckFailedException)', async () => { diff --git a/cdk/test/handlers/fanout-task-events.test.ts b/cdk/test/handlers/fanout-task-events.test.ts index 78125b2bf..2f72c24a2 100644 --- a/cdk/test/handlers/fanout-task-events.test.ts +++ b/cdk/test/handlers/fanout-task-events.test.ts @@ -1231,8 +1231,8 @@ describe('fanout-task-events: GitHub dispatcher (Chunk J)', () => { // ---- Number-coercion regression (found in deploy validation) ---- test('TaskRecord with string-typed cost_usd/duration_s renders without throwing (DDB Number coercion)', async () => { - // Regression: the DynamoDB Document-client returns Number - // attributes as strings. ``renderCommentBody`` calls + // Regression: the agent stores cost and duration as DynamoDB + // strings. ``renderCommentBody`` calls // ``costUsd.toFixed(4)`` which throws TypeError on a string, // causing every terminal event on a pr_iteration task to be // rejected by the dispatcher. The fan-out boundary must coerce. diff --git a/cdk/test/handlers/jira-link.test.ts b/cdk/test/handlers/jira-link.test.ts index c784e7ce0..84ed73a3a 100644 --- a/cdk/test/handlers/jira-link.test.ts +++ b/cdk/test/handlers/jira-link.test.ts @@ -34,6 +34,9 @@ process.env.JIRA_USER_MAPPING_TABLE_NAME = 'JiraMap'; import { handler } from '../../src/handlers/jira-link'; +// The handler refuses a pending row whose ttl has passed, so live fixtures carry a future one. +const FUTURE_TTL = Math.floor(Date.now() / 1000) + 600; + function makeEvent(body: unknown, userId?: string): APIGatewayProxyEvent { return { body: body === null ? null : JSON.stringify(body), @@ -75,17 +78,48 @@ describe('jira-link handler', () => { }); test('404s when code exists but status is not pending', async () => { - ddbSend.mockResolvedValueOnce({ Item: { jira_identity: 'pending#XYZ', status: 'consumed' } }); + ddbSend.mockResolvedValueOnce({ Item: { jira_identity: 'pending#XYZ', status: 'consumed', ttl: FUTURE_TTL } }); const result = await handler(makeEvent({ code: 'XYZ123' }, 'cognito-user-1')); expect(result.statusCode).toBe(404); }); + test.each([false, true])('404s when the code is past its ttl (dry_run: %s)', async (dryRun) => { + ddbSend.mockResolvedValueOnce({ + Item: { + jira_identity: 'pending#link-3f8b4a2c', + status: 'pending', + ttl: Math.floor(Date.now() / 1000) - 1, + jira_cloud_id: 'cloud-1', + jira_account_id: 'acc-1', + }, + }); + const result = await handler(makeEvent({ code: 'link-3f8b4a2c', dry_run: dryRun }, 'cognito-user-1')); + expect(result.statusCode).toBe(404); + expect(ddbSend).toHaveBeenCalledTimes(1); // the Get only: nothing written or deleted + }); + + test.each([['absent', undefined], ['a string', String(FUTURE_TTL)]])('404s when the pending row has no numeric ttl (%s)', async (_shape, ttl) => { + ddbSend.mockResolvedValueOnce({ + Item: { + jira_identity: 'pending#link-3f8b4a2c', + status: 'pending', + ttl, + jira_cloud_id: 'cloud-1', + jira_account_id: 'acc-1', + }, + }); + const result = await handler(makeEvent({ code: 'link-3f8b4a2c' }, 'cognito-user-1')); + expect(result.statusCode).toBe(404); + expect(ddbSend).toHaveBeenCalledTimes(1); + }); + test('writes confirmed mapping and deletes pending record on success', async () => { ddbSend .mockResolvedValueOnce({ Item: { jira_identity: 'pending#link-3f8b4a2c', status: 'pending', + ttl: FUTURE_TTL, jira_cloud_id: 'cloud-1', jira_account_id: 'acc-1', }, @@ -113,6 +147,7 @@ describe('jira-link handler', () => { Item: { jira_identity: 'pending#link-3f8b4a2c', status: 'pending', + ttl: FUTURE_TTL, jira_cloud_id: 'cloud-1', jira_site_url: 'https://acme.atlassian.net', jira_account_id: 'acc-1', @@ -155,6 +190,7 @@ describe('jira-link handler', () => { Item: { jira_identity: 'pending#link-3f8b4a2c', status: 'pending', + ttl: FUTURE_TTL, jira_cloud_id: 'c', jira_account_id: 'a', }, diff --git a/cdk/test/handlers/linear-link.test.ts b/cdk/test/handlers/linear-link.test.ts index c66ec0a5c..9b1288764 100644 --- a/cdk/test/handlers/linear-link.test.ts +++ b/cdk/test/handlers/linear-link.test.ts @@ -34,6 +34,9 @@ process.env.LINEAR_USER_MAPPING_TABLE_NAME = 'LinearMap'; import { handler } from '../../src/handlers/linear-link'; +// The handler refuses a pending row whose ttl has passed, so live fixtures carry a future one. +const FUTURE_TTL = Math.floor(Date.now() / 1000) + 600; + function makeEvent(body: unknown, userId?: string): APIGatewayProxyEvent { return { body: body === null ? null : JSON.stringify(body), @@ -75,17 +78,48 @@ describe('linear-link handler', () => { }); test('404s when code exists but status is not pending', async () => { - ddbSend.mockResolvedValueOnce({ Item: { linear_identity: 'pending#XYZ', status: 'consumed' } }); + ddbSend.mockResolvedValueOnce({ Item: { linear_identity: 'pending#XYZ', status: 'consumed', ttl: FUTURE_TTL } }); const result = await handler(makeEvent({ code: 'XYZ123' }, 'cognito-user-1')); expect(result.statusCode).toBe(404); }); + test.each([false, true])('404s when the code is past its ttl (dry_run: %s)', async (dryRun) => { + ddbSend.mockResolvedValueOnce({ + Item: { + linear_identity: 'pending#link-3f8b4a2c', + status: 'pending', + ttl: Math.floor(Date.now() / 1000) - 1, + linear_workspace_id: 'workspace-uuid-1', + linear_user_id: 'user-uuid-1', + }, + }); + const result = await handler(makeEvent({ code: 'link-3f8b4a2c', dry_run: dryRun }, 'cognito-user-1')); + expect(result.statusCode).toBe(404); + expect(ddbSend).toHaveBeenCalledTimes(1); // the Get only: nothing written or deleted + }); + + test.each([['absent', undefined], ['a string', String(FUTURE_TTL)]])('404s when the pending row has no numeric ttl (%s)', async (_shape, ttl) => { + ddbSend.mockResolvedValueOnce({ + Item: { + linear_identity: 'pending#link-3f8b4a2c', + status: 'pending', + ttl, + linear_workspace_id: 'workspace-uuid-1', + linear_user_id: 'user-uuid-1', + }, + }); + const result = await handler(makeEvent({ code: 'link-3f8b4a2c' }, 'cognito-user-1')); + expect(result.statusCode).toBe(404); + expect(ddbSend).toHaveBeenCalledTimes(1); + }); + test('writes confirmed mapping and deletes pending record on success', async () => { ddbSend .mockResolvedValueOnce({ Item: { linear_identity: 'pending#link-3f8b4a2c', status: 'pending', + ttl: FUTURE_TTL, linear_workspace_id: 'workspace-uuid-1', linear_user_id: 'user-uuid-1', }, @@ -115,6 +149,7 @@ describe('linear-link handler', () => { Item: { linear_identity: 'pending#link-3f8b4a2c', status: 'pending', + ttl: FUTURE_TTL, linear_workspace_id: 'workspace-uuid-1', linear_workspace_slug: 'acme', linear_user_id: 'user-uuid-1', @@ -164,6 +199,7 @@ describe('linear-link handler', () => { Item: { linear_identity: 'pending#link-3f8b4a2c', status: 'pending', + ttl: FUTURE_TTL, linear_workspace_id: 'w', linear_user_id: 'u', }, diff --git a/cdk/test/handlers/list-tasks.test.ts b/cdk/test/handlers/list-tasks.test.ts index 0225be651..5e435b17e 100644 --- a/cdk/test/handlers/list-tasks.test.ts +++ b/cdk/test/handlers/list-tasks.test.ts @@ -22,9 +22,18 @@ import type { APIGatewayProxyEvent } from 'aws-lambda'; // --- Mocks --- const mockSend = jest.fn(); -jest.mock('@aws-sdk/client-dynamodb', () => ({ DynamoDBClient: jest.fn(() => ({})) })); +/** Answers DescribeTable, so that `mockSend` sees the data-plane calls only. */ +const mockDescribeTable = jest.fn(); +jest.mock('@aws-sdk/client-dynamodb', () => ({ + DynamoDBClient: jest.fn(() => ({})), + DescribeTableCommand: jest.fn((input: unknown) => ({ _type: 'DescribeTable', input })), +})); jest.mock('@aws-sdk/lib-dynamodb', () => ({ - DynamoDBDocumentClient: { from: jest.fn(() => ({ send: mockSend })) }, + DynamoDBDocumentClient: { + from: jest.fn(() => ({ + send: (command: { _type: string }) => (command._type === 'DescribeTable' ? mockDescribeTable(command) : mockSend(command)), + })), + }, BatchGetCommand: jest.fn((input: unknown) => ({ _type: 'BatchGet', input })), QueryCommand: jest.fn((input: unknown) => ({ _type: 'Query', input })), })); @@ -113,9 +122,20 @@ function makeEvent(overrides: Partial = {}): APIGatewayPro }; } +/** A DescribeTable answer in which UserCreatedAtIndex has the given status, or is missing. */ +const describedWith = (IndexStatus?: string) => ({ + Table: { + GlobalSecondaryIndexes: [ + { IndexName: 'UserStatusIndex', IndexStatus: 'ACTIVE' }, + ...(IndexStatus ? [{ IndexName: 'UserCreatedAtIndex', IndexStatus }] : []), + ], + }, +}); + beforeEach(() => { jest.clearAllMocks(); mockSend.mockResolvedValue({ Items: TASK_ITEMS }); + mockDescribeTable.mockResolvedValue(describedWith('ACTIVE')); }); describe('list-tasks handler', () => { @@ -194,19 +214,6 @@ describe('list-tasks handler', () => { expect(body.data[0]).toMatchObject({ cost_usd: null, completed_at: null, channel_source: 'api' }); }); - test('returns pagination token when more results exist', async () => { - mockSend.mockResolvedValueOnce({ - Items: [TASK_ITEMS[0]], - LastEvaluatedKey: { task_id: { S: 'task-1' }, user_id: { S: 'user-123' } }, - }); - - const result = await handler(makeEvent()); - const body = JSON.parse(result.body); - - expect(body.pagination.has_more).toBe(true); - expect(body.pagination.next_token).toBeTruthy(); - }); - test('returns 400 for an unknown view instead of returning tasks', async () => { const result = await handler(makeEvent({ queryStringParameters: { view: 'budgets' }, @@ -254,7 +261,8 @@ describe('list-tasks handler', () => { await handler(event); const queryInput = MockQueryCommand.mock.calls[0][0]; - expect(queryInput.Limit).toBe(5); + // limit + 1: the extra row tells a full page whether another task follows. + expect(queryInput.Limit).toBe(6); }); test('returns 400 for invalid status filter', async () => { @@ -289,4 +297,137 @@ describe('list-tasks handler', () => { expect(result.statusCode).toBe(500); }); + + describe('pagination (#51: Limit is applied before the status and repo filters)', () => { + test('queries UserCreatedAtIndex newest first', async () => { + await handler(makeEvent()); + + const queryInput = MockQueryCommand.mock.calls[0][0]; + expect(queryInput.IndexName).toBe('UserCreatedAtIndex'); + expect(queryInput.ScanIndexForward).toBe(false); + }); + + test('keeps querying past filtered-out pages until the page is full', async () => { + // Page 1: every row read was filtered out, but a cursor remains. Page 2 is the + // default reply: enough tasks to fill limit=1 plus one extra. + const cursor = { task_id: 'task-0', user_id: 'user-123', created_at: '2025-03-16T09:00:00Z' }; + mockSend.mockResolvedValueOnce({ Items: [], LastEvaluatedKey: cursor }); + + const result = await handler(makeEvent({ queryStringParameters: { status: 'RUNNING,COMPLETED', limit: '1' } })); + const body = JSON.parse(result.body); + + expect(mockSend).toHaveBeenCalledTimes(2); + expect(MockQueryCommand.mock.calls[1][0].ExclusiveStartKey).toEqual(cursor); + expect(body.data.map((t: { task_id: string }) => t.task_id)).toEqual(['task-1']); + expect(body.pagination.has_more).toBe(true); + expect(body.pagination.next_token).not.toBeNull(); + }); + + test('next_token resumes from the last task returned, not the scan boundary', async () => { + mockSend.mockResolvedValueOnce({ Items: TASK_ITEMS, LastEvaluatedKey: { task_id: 'task-scanned-past' } }); + + const result = await handler(makeEvent({ queryStringParameters: { limit: '1' } })); + const body = JSON.parse(result.body); + + const decoded = JSON.parse(Buffer.from(body.pagination.next_token, 'base64').toString('utf-8')); + // Boundary is the last task actually returned (task-1), so task-2 is not skipped. + expect(decoded).toEqual({ task_id: 'task-1', user_id: 'user-123', created_at: TASK_ITEMS[0].created_at }); + }); + + test('stops after the page cap and hands back the raw cursor', async () => { + // Every page filters to nothing but keeps returning a cursor. + mockSend.mockResolvedValue({ Items: [], LastEvaluatedKey: { task_id: 'task-x' } }); + + const result = await handler(makeEvent({ queryStringParameters: { status: 'FAILED' } })); + const body = JSON.parse(result.body); + + expect(mockSend).toHaveBeenCalledTimes(10); // MAX_QUERY_PAGES + expect(body.data).toHaveLength(0); + // The read is not finished, so the list must not be reported as complete. + expect(body.pagination.has_more).toBe(true); + const decoded = JSON.parse(Buffer.from(body.pagination.next_token, 'base64').toString('utf-8')); + expect(decoded).toEqual({ task_id: 'task-x' }); + }); + }); + + describe('choice of index (UserCreatedAtIndex is being built on the deploy that adds it)', () => { + // The handler remembers that the index is ACTIVE, so each test loads a copy of its own. + // That copy has its own command mocks, so these tests read the commands `mockSend` got. + let listTasks: typeof handler; + const indexesRead = () => mockSend.mock.calls.map(([command]) => command.input.IndexName); + + beforeEach(() => { + jest.isolateModules(() => { + // eslint-disable-next-line @typescript-eslint/no-require-imports -- a fresh copy of the handler and its cached index status + listTasks = require('../../src/handlers/list-tasks').handler; + }); + }); + + test.each([ + ['CREATING', 'CREATING'], ['UPDATING', 'UPDATING'], ['DELETING', 'DELETING'], ['missing', undefined], + ])('lists from UserStatusIndex while UserCreatedAtIndex is %s', async (_state, status) => { + mockDescribeTable.mockResolvedValue(describedWith(status)); + const stdout = jest.spyOn(process.stdout, 'write').mockImplementation(() => true); + + const result = await listTasks(makeEvent({ queryStringParameters: { limit: '1' } })); + const logged = stdout.mock.calls.join(''); + stdout.mockRestore(); + const body = JSON.parse(result.body); + + expect(result.statusCode).toBe(200); + expect(mockDescribeTable.mock.calls.map(([command]) => command.input)).toEqual([{ TableName: 'Tasks' }]); + expect(indexesRead()).toEqual(['UserStatusIndex']); + expect(body.data.map((t: { task_id: string }) => t.task_id)).toEqual(['task-1']); + // The cursor is one of the index that was read. + const decoded = JSON.parse(Buffer.from(body.pagination.next_token, 'base64').toString('utf-8')); + expect(decoded).toEqual({ task_id: 'task-1', user_id: 'user-123', status_created_at: TASK_ITEMS[0].status_created_at }); + // The deployment guide tells operators to look for this line. + expect(logged).toContain('UserCreatedAtIndex is not ACTIVE'); + }); + + test('asks again on each request until the index is ACTIVE, and never after', async () => { + mockDescribeTable.mockResolvedValueOnce(describedWith('CREATING')); + + await listTasks(makeEvent()); + await listTasks(makeEvent()); + await listTasks(makeEvent()); + + expect(indexesRead()).toEqual(['UserStatusIndex', 'UserCreatedAtIndex', 'UserCreatedAtIndex']); + expect(mockDescribeTable).toHaveBeenCalledTimes(2); + }); + + const token = (key: Record) => Buffer.from(JSON.stringify(key)).toString('base64'); + const createdAtKey = { task_id: 'task-1', user_id: 'user-123', created_at: TASK_ITEMS[0].created_at }; + + test('a status_created_at cursor is read from UserStatusIndex without a status check', async () => { + const key = { task_id: 'task-1', user_id: 'user-123', status_created_at: TASK_ITEMS[0].status_created_at }; + + await listTasks(makeEvent({ queryStringParameters: { next_token: token(key) } })); + + expect(mockDescribeTable).not.toHaveBeenCalled(); + expect(mockSend.mock.calls[0][0].input).toMatchObject({ IndexName: 'UserStatusIndex', ExclusiveStartKey: key }); + }); + + test.each([ + ['ACTIVE', 'UserCreatedAtIndex'], + // UserCreatedAtIndex is not read before it is ACTIVE; DynamoDB refuses this key on + // UserStatusIndex, so the request is a 500. + ['CREATING', 'UserStatusIndex'], + ])('a created_at cursor follows the status check: %s reads %s', async (status, index) => { + mockDescribeTable.mockResolvedValue(describedWith(status)); + + await listTasks(makeEvent({ queryStringParameters: { next_token: token(createdAtKey) } })); + + expect(mockSend.mock.calls.map(([command]) => command.input)).toMatchObject([{ IndexName: index, ExclusiveStartKey: createdAtKey }]); + }); + + test('a status check that fails is a 500, and no index is read', async () => { + mockDescribeTable.mockRejectedValueOnce(new Error('AccessDeniedException')); + + const result = await listTasks(makeEvent()); + + expect(result.statusCode).toBe(500); + expect(mockSend).not.toHaveBeenCalled(); + }); + }); }); diff --git a/cdk/test/handlers/list-webhooks.test.ts b/cdk/test/handlers/list-webhooks.test.ts index bc9846c8d..cef3074ab 100644 --- a/cdk/test/handlers/list-webhooks.test.ts +++ b/cdk/test/handlers/list-webhooks.test.ts @@ -79,6 +79,17 @@ function makeEvent(overrides: Partial = {}): APIGatewayPro }; } +function makeRecord(n: number) { + return { + webhook_id: `wh-${n}`, + user_id: 'user-123', + name: `ci-${n}`, + status: 'active', + created_at: `2026-01-01T00:00:${String(n).padStart(2, '0')}Z`, + updated_at: '2026-01-01T00:00:00Z', + }; +} + beforeEach(() => { jest.clearAllMocks(); mockSend.mockResolvedValue({ Items: [], LastEvaluatedKey: undefined }); @@ -109,18 +120,6 @@ describe('list-webhooks handler', () => { expect(body.data[0].name).toBe('CI'); }); - test('supports pagination', async () => { - mockSend.mockResolvedValueOnce({ - Items: [{ webhook_id: 'wh-1', user_id: 'user-123', name: 'CI', status: 'active', created_at: '2025-01-01', updated_at: '2025-01-01' }], - LastEvaluatedKey: { webhook_id: 'wh-1', user_id: 'user-123', created_at: '2025-01-01' }, - }); - - const result = await handler(makeEvent()); - const body = JSON.parse(result.body); - expect(body.pagination.has_more).toBe(true); - expect(body.pagination.next_token).toBeDefined(); - }); - test('returns 401 when not authenticated', async () => { const event = makeEvent(); event.requestContext.authorizer = null; @@ -133,4 +132,79 @@ describe('list-webhooks handler', () => { const result = await handler(makeEvent()); expect(result.statusCode).toBe(500); }); + + describe('pagination (Limit is applied before the revoked filter)', () => { + test('over-fetches limit+1 so a full page can prove another webhook exists', async () => { + await handler(makeEvent({ queryStringParameters: { limit: '20' } })); + const q = mockSend.mock.calls[0][0].input; + expect(q.Limit).toBe(21); + }); + + test('passes next_token as ExclusiveStartKey', async () => { + const key = { webhook_id: 'wh-1' }; + const token = Buffer.from(JSON.stringify(key)).toString('base64'); + + await handler(makeEvent({ queryStringParameters: { next_token: token } })); + + expect(mockSend.mock.calls[0][0].input.ExclusiveStartKey).toEqual(key); + }); + + test('a single page short of the limit reports has_more=false with no token', async () => { + // Fewer active webhooks than requested, index exhausted (no LastEvaluatedKey). + mockSend.mockResolvedValueOnce({ Items: [makeRecord(2), makeRecord(1)] }); + const result = await handler(makeEvent({ queryStringParameters: { limit: '20' } })); + const body = JSON.parse(result.body); + expect(body.data).toHaveLength(2); + expect(body.pagination.has_more).toBe(false); + expect(body.pagination.next_token).toBeNull(); + expect(mockSend).toHaveBeenCalledTimes(1); + }); + + test('keeps querying past filtered-out pages until the page is full', async () => { + // Page 1: Limit applied before the filter yields no active webhook, but a cursor remains. + mockSend.mockResolvedValueOnce({ Items: [], LastEvaluatedKey: { webhook_id: 'wh-0' } }); + // Page 2: enough active webhooks to fill limit=2 plus one extra. + mockSend.mockResolvedValue({ + Items: [makeRecord(3), makeRecord(2), makeRecord(1)], + LastEvaluatedKey: { webhook_id: 'wh-1' }, + }); + + const result = await handler(makeEvent({ queryStringParameters: { limit: '2' } })); + const body = JSON.parse(result.body); + + expect(mockSend).toHaveBeenCalledTimes(2); + expect(mockSend.mock.calls[1][0].input.ExclusiveStartKey).toEqual({ webhook_id: 'wh-0' }); + expect(body.data.map((w: { webhook_id: string }) => w.webhook_id)).toEqual(['wh-3', 'wh-2']); + expect(body.pagination.has_more).toBe(true); + expect(body.pagination.next_token).not.toBeNull(); + }); + + test('next_token resumes from the last returned webhook, not the scan boundary', async () => { + mockSend.mockResolvedValueOnce({ + Items: [makeRecord(3), makeRecord(2), makeRecord(1)], + LastEvaluatedKey: { webhook_id: 'wh-scanned-past' }, + }); + const result = await handler(makeEvent({ queryStringParameters: { limit: '2' } })); + const body = JSON.parse(result.body); + + const decoded = JSON.parse(Buffer.from(body.pagination.next_token, 'base64').toString('utf-8')); + // Boundary is the last webhook actually returned (wh-2), so wh-1 is not skipped. + expect(decoded).toEqual({ webhook_id: 'wh-2', user_id: 'user-123', created_at: makeRecord(2).created_at }); + }); + + test('stops after the page cap and still advances the raw cursor', async () => { + // Every page filters to nothing but keeps returning a cursor. + mockSend.mockResolvedValue({ Items: [], LastEvaluatedKey: { webhook_id: 'wh-x' } }); + const result = await handler(makeEvent({ queryStringParameters: { limit: '20' } })); + const body = JSON.parse(result.body); + + expect(mockSend).toHaveBeenCalledTimes(10); // MAX_QUERY_PAGES + expect(body.data).toHaveLength(0); + // The cap stopped the read with a cursor still pending, so hand it back + // rather than report the list as complete. + expect(body.pagination.has_more).toBe(true); + const decoded = JSON.parse(Buffer.from(body.pagination.next_token, 'base64').toString('utf-8')); + expect(decoded).toEqual({ webhook_id: 'wh-x' }); + }); + }); }); diff --git a/cdk/test/handlers/reconcile-stranded-tasks.test.ts b/cdk/test/handlers/reconcile-stranded-tasks.test.ts index 8c2346c5c..8f2477388 100644 --- a/cdk/test/handlers/reconcile-stranded-tasks.test.ts +++ b/cdk/test/handlers/reconcile-stranded-tasks.test.ts @@ -116,11 +116,15 @@ describe('reconcile-stranded-tasks', () => { expect(transitionCall).toBeDefined(); const input = transitionCall![0].input as { Key: { task_id: { S: string } }; - ExpressionAttributeValues: Record; + UpdateExpression: string; + ExpressionAttributeValues: Record; }; expect(input.Key.task_id.S).toBe('t-stranded'); expect(input.ExpressionAttributeValues[':failed'].S).toBe('FAILED'); expect(input.ExpressionAttributeValues[':expected'].S).toBe('SUBMITTED'); + // No orchestrator may be left to finalize this task, so the sweep stamps the retention ttl (90 days here). + expect(input.UpdateExpression).toContain('#ttl = :ttl'); + expect(Number(input.ExpressionAttributeValues[':ttl'].N)).toBeGreaterThan(Date.now() / 1000 + 89 * 86400); // Events written. const putCalls = (mockDdbSend.mock.calls as [{ _type: string; input: Record }][]) @@ -131,6 +135,8 @@ describe('reconcile-stranded-tasks', () => { return item.event_type.S; }); expect(eventTypes).toEqual(expect.arrayContaining(['task_stranded', 'task_failed'])); + // The task row expires with its events. + expect(input.ExpressionAttributeValues[':ttl'].N).toBe((putCalls[0][0].input as { Item: { ttl: { N: string } } }).Item.ttl.N); // Concurrency decrement. const decrementCall = (mockDdbSend.mock.calls as [{ _type: string; input: Record }][]) diff --git a/cdk/test/handlers/shared/create-task-core-presign-failure.test.ts b/cdk/test/handlers/shared/create-task-core-presign-failure.test.ts new file mode 100644 index 000000000..77e7b4ab3 --- /dev/null +++ b/cdk/test/handlers/shared/create-task-core-presign-failure.test.ts @@ -0,0 +1,71 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +// create-task-core reads ATTACHMENTS_BUCKET_NAME when it loads, and create-task-core.test.ts +// loads it without a bucket, so the presigned-upload branch needs a file of its own. + +const mockSend = jest.fn(); +jest.mock('@aws-sdk/client-dynamodb', () => ({ DynamoDBClient: jest.fn(() => ({})) })); +jest.mock('@aws-sdk/lib-dynamodb', () => ({ + DynamoDBDocumentClient: { from: jest.fn(() => ({ send: mockSend })) }, + PutCommand: jest.fn((input: unknown) => ({ _type: 'Put', input })), + UpdateCommand: jest.fn((input: unknown) => ({ _type: 'Update', input })), +})); + +jest.mock('@aws-sdk/client-bedrock-runtime', () => ({ + BedrockRuntimeClient: jest.fn(() => ({ send: jest.fn(() => Promise.resolve({ action: 'NONE' })) })), + ApplyGuardrailCommand: jest.fn(), +})); + +jest.mock('@aws-sdk/client-s3', () => ({ S3Client: jest.fn(() => ({})) })); +jest.mock('@aws-sdk/s3-presigned-post', () => ({ + createPresignedPost: jest.fn(() => Promise.reject(new Error('presign failed'))), +})); + +process.env.GUARDRAIL_ID = 'test-guardrail-id'; +process.env.GUARDRAIL_VERSION = '1'; +process.env.ATTACHMENTS_BUCKET_NAME = 'attachments-bucket'; + +import { createTaskCore } from '../../../src/handlers/shared/create-task-core'; + +describe('createTaskCore when presigning an upload fails', () => { + test('fails the task with completed_at, a matching status_created_at and a ttl', async () => { + const result = await createTaskCore( + { + task_description: 'Summarise the attached notes', + attachments: [{ type: 'file', content_type: 'text/plain', filename: 'notes.txt', expected_size_bytes: 10 }], + }, + { userId: 'user-123', channelSource: 'api', channelMetadata: {} }, + 'req-1', + ); + + expect(result.statusCode).toBe(500); + const update = mockSend.mock.calls.map(([cmd]) => cmd).find(cmd => cmd._type === 'Update'); + const { UpdateExpression, ExpressionAttributeNames: names, ExpressionAttributeValues: values } = update.input; + expect(UpdateExpression).toContain('completed_at = :now'); + expect(UpdateExpression).toContain('status_created_at = :sca'); + expect(UpdateExpression).toContain('#ttl = :ttl'); + expect(values[':sca']).toBe(`FAILED#${values[':now']}`); + expect(names['#ttl']).toBe('ttl'); + // Epoch seconds, a retention period ahead: a value in milliseconds would never expire. + const nowSeconds = Date.now() / 1000; + expect(values[':ttl']).toBeGreaterThan(nowSeconds); + expect(values[':ttl']).toBeLessThan(nowSeconds + 91 * 86_400); + }); +}); diff --git a/cdk/test/handlers/shared/error-classifier.test.ts b/cdk/test/handlers/shared/error-classifier.test.ts index e42a69886..c4ea0aa78 100644 --- a/cdk/test/handlers/shared/error-classifier.test.ts +++ b/cdk/test/handlers/shared/error-classifier.test.ts @@ -1033,11 +1033,12 @@ describe('classifyError', () => { }); // Regression: all numeric fields coerce through ``coerceNumericOrNull`` - // so the DDB Document-client's string-typed Number deserialization - // cannot leak into downstream consumers (same bug class as the + // so that a string in one of them (the agent stores cost, duration + // and the turn counters as strings) cannot leak into downstream + // consumers (same bug class as the // ``costUsd.toFixed`` crash fixed in commit ``c09bfd7``). The cast - // to ``unknown as TaskRecord`` simulates a record produced by the - // Document client where ``Number`` attributes came back as strings. + // to ``unknown as TaskRecord`` simulates such a record as the + // Document client returns it. test('coerces string-typed numeric DDB fields to numbers on output', () => { const record = { ...baseRecord, diff --git a/cdk/test/handlers/shared/github-comment.test.ts b/cdk/test/handlers/shared/github-comment.test.ts index a9eacd060..4da2c1ab7 100644 --- a/cdk/test/handlers/shared/github-comment.test.ts +++ b/cdk/test/handlers/shared/github-comment.test.ts @@ -499,7 +499,7 @@ describe('github-comment: renderCommentBody numeric self-defense (finding #9)', latestEventType: 'task_completed', latestEventAt: '2026-05-05T00:00:00Z', prUrl: null, - // DynamoDB Document-client deserialization: Number → string. + // As the agent stores them: DynamoDB strings (see shared/numeric.ts). durationS: '96.0' as unknown as number, costUsd: '0.20939010000000002' as unknown as number, }); diff --git a/cdk/test/handlers/shared/numeric.test.ts b/cdk/test/handlers/shared/numeric.test.ts index d51abc12c..143514380 100644 --- a/cdk/test/handlers/shared/numeric.test.ts +++ b/cdk/test/handlers/shared/numeric.test.ts @@ -36,7 +36,7 @@ describe('coerceNumericOrNull', () => { expect(warnCalls).toHaveLength(0); }); - test('parses numeric strings (DDB Document-client shape)', () => { + test('parses numeric strings (the shape the agent stores)', () => { // The actual shape observed in Scenario 7-extended deploy // validation: ``duration_s: "96.0"`` and // ``cost_usd: "0.20939010000000002"``. diff --git a/cdk/test/handlers/shared/slack-format.test.ts b/cdk/test/handlers/shared/slack-format.test.ts index 4b747084c..a7c00053d 100644 --- a/cdk/test/handlers/shared/slack-format.test.ts +++ b/cdk/test/handlers/shared/slack-format.test.ts @@ -53,7 +53,7 @@ describe('formatDuration', () => { }); test('coerces DynamoDB numeric strings via Number()', () => { - // DynamoDB may round-trip numeric attributes as strings; Number() coerces them. + // The agent stores these as DynamoDB strings; Number() coerces them. expect(formatDuration('90' as unknown as number)).toBe('1m 30s'); expect(formatDuration('3600' as unknown as number)).toBe('1h'); }); diff --git a/cdk/test/handlers/slack-command-processor.test.ts b/cdk/test/handlers/slack-command-processor.test.ts index f803171b6..fcbc55968 100644 --- a/cdk/test/handlers/slack-command-processor.test.ts +++ b/cdk/test/handlers/slack-command-processor.test.ts @@ -258,6 +258,10 @@ describe('slack-command-processor handler', () => { expect(putCall).toBeTruthy(); expect(putCall![0].input.Item.slack_identity).toMatch(/^pending#/); expect(putCall![0].input.Item.status).toBe('pending'); + // slack-link refuses a pending row whose ttl is not a number of seconds in the future. + const nowSeconds = Math.floor(Date.now() / 1000); + expect(putCall![0].input.Item.ttl).toBeGreaterThan(nowSeconds); + expect(putCall![0].input.Item.ttl).toBeLessThanOrEqual(nowSeconds + 600); const posted = fetchMock.mock.calls.find( ([_url, opts]) => String((opts as { body: string }).body).includes('bgagent slack link'), ); diff --git a/cdk/test/handlers/slack-interactions.test.ts b/cdk/test/handlers/slack-interactions.test.ts index 9d1356022..5b29762a0 100644 --- a/cdk/test/handlers/slack-interactions.test.ts +++ b/cdk/test/handlers/slack-interactions.test.ts @@ -137,6 +137,11 @@ describe('slack-interactions handler', () => { const updateCall = ddbSend.mock.calls.find(([cmd]) => cmd._type === 'Update'); expect(updateCall).toBeTruthy(); expect(updateCall![0].input.ExpressionAttributeValues[':cancelled']).toBe('CANCELLED'); + // The row is terminal: it carries completed_at and a status_created_at that matches its status. + const { UpdateExpression, ExpressionAttributeValues: values } = updateCall![0].input; + expect(UpdateExpression).toContain('completed_at = :now'); + expect(UpdateExpression).toContain('status_created_at = :sca'); + expect(values[':sca']).toBe(`CANCELLED#${values[':now']}`); }); test('cancel_task rejects when caller is not task owner', async () => { diff --git a/cdk/test/handlers/slack-link.test.ts b/cdk/test/handlers/slack-link.test.ts index 1acd1c45e..93ec59bed 100644 --- a/cdk/test/handlers/slack-link.test.ts +++ b/cdk/test/handlers/slack-link.test.ts @@ -34,6 +34,9 @@ process.env.SLACK_USER_MAPPING_TABLE_NAME = 'SlackMap'; import { handler } from '../../src/handlers/slack-link'; +// The handler refuses a pending row whose ttl has passed, so live fixtures carry a future one. +const FUTURE_TTL = Math.floor(Date.now() / 1000) + 600; + function makeEvent(body: unknown, userId?: string): APIGatewayProxyEvent { return { body: body === null ? null : JSON.stringify(body), @@ -75,17 +78,42 @@ describe('slack-link handler', () => { }); test('404s when code exists but status is not pending', async () => { - ddbSend.mockResolvedValueOnce({ Item: { slack_identity: 'pending#XYZ', status: 'consumed' } }); + ddbSend.mockResolvedValueOnce({ Item: { slack_identity: 'pending#XYZ', status: 'consumed', ttl: FUTURE_TTL } }); const result = await handler(makeEvent({ code: 'XYZ123' }, 'cognito-user-1')); expect(result.statusCode).toBe(404); }); + test('404s when the code is past its ttl', async () => { + ddbSend.mockResolvedValueOnce({ + Item: { + slack_identity: 'pending#ABC123', + status: 'pending', + ttl: Math.floor(Date.now() / 1000) - 1, + slack_team_id: 'T1', + slack_user_id: 'U_slack', + }, + }); + const result = await handler(makeEvent({ code: 'ABC123' }, 'cognito-user-1')); + expect(result.statusCode).toBe(404); + expect(ddbSend).toHaveBeenCalledTimes(1); // the Get only: nothing written or deleted + }); + + test.each([['absent', undefined], ['a string', String(FUTURE_TTL)]])('404s when the pending row has no numeric ttl (%s)', async (_shape, ttl) => { + ddbSend.mockResolvedValueOnce({ + Item: { slack_identity: 'pending#ABC123', status: 'pending', ttl, slack_team_id: 'T1', slack_user_id: 'U_slack' }, + }); + const result = await handler(makeEvent({ code: 'ABC123' }, 'cognito-user-1')); + expect(result.statusCode).toBe(404); + expect(ddbSend).toHaveBeenCalledTimes(1); + }); + test('writes confirmed mapping and deletes pending record on success', async () => { ddbSend .mockResolvedValueOnce({ Item: { slack_identity: 'pending#ABC123', status: 'pending', + ttl: FUTURE_TTL, slack_team_id: 'T1', slack_user_id: 'U_slack', }, @@ -108,7 +136,7 @@ describe('slack-link handler', () => { test('normalizes the code (uppercase, trimmed)', async () => { ddbSend .mockResolvedValueOnce({ - Item: { slack_identity: 'pending#ABC123', status: 'pending', slack_team_id: 'T1', slack_user_id: 'U1' }, + Item: { slack_identity: 'pending#ABC123', status: 'pending', ttl: FUTURE_TTL, slack_team_id: 'T1', slack_user_id: 'U1' }, }) .mockResolvedValueOnce({}) .mockResolvedValueOnce({}); diff --git a/cdk/test/scripts/aws-emulator-guard.test.ts b/cdk/test/scripts/aws-emulator-guard.test.ts new file mode 100644 index 000000000..2d303f41c --- /dev/null +++ b/cdk/test/scripts/aws-emulator-guard.test.ts @@ -0,0 +1,225 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +/** + * Tests for the guard of the emulator-backed tests (`scripts/aws-emulator/`). + * + * Those tests make real AWS SDK calls, so three files stand between them and a real + * account: `jest-config.js` refuses an AWS environment that is not the emulator's, + * `jest-global-setup.js` refuses a preload that is missing or refuses nothing and an + * endpoint that is not an emulator, and `loopback-only.cjs` refuses a connection that + * leaves the machine. A guard that stops refusing lets every emulator test pass, so the + * refusals are made to happen here. Three of `jest-global-setup.js` are not: a certificate + * it does not trust and a wrong answer on the health route, which need a TLS listener, and + * an endpoint that never answers, which takes three seconds. + * + * Every case runs the real file in a child `node` whose whole environment is what the + * case names: the shell that starts jest may export a real AWS profile. No case can + * send anything off the machine even when the guard under test is broken: there are no + * credentials, the endpoints are loopback ports, and the hosts are 127.0.0.2 or + * `.invalid` names that no resolver is asked about. + * + * Neither an emulator nor Docker is needed, so this runs with the unit suite (same + * placement rationale as `check-constants-sync.test.ts`). The accepting path, a real + * emulator answering its health route, is exercised by every `mise run test:integration`. + */ + +import { spawnSync } from 'node:child_process'; +import * as path from 'node:path'; + +const REPO_ROOT = path.resolve(__dirname, '../../..'); +const GUARD = path.join(REPO_ROOT, 'scripts/aws-emulator'); +const JEST_CONFIG = path.join(GUARD, 'jest-config.js'); +const GLOBAL_SETUP = path.join(GUARD, 'jest-global-setup.js'); +const PRELOAD = path.join(GUARD, 'loopback-only.cjs'); + +/** The AWS variables `emulator.sh run` sets, and the only ones the guard accepts. Nothing listens on port 1. */ +const WRAPPER_ENVIRONMENT = { + AWS_ENDPOINT_URL: 'https://127.0.0.1:1', + AWS_SHARED_CREDENTIALS_FILE: '/nonexistent/emulator_credentials', + AWS_CONFIG_FILE: '/nonexistent/config', + AWS_CA_BUNDLE: '/nonexistent/ca.pem', + AWS_EC2_METADATA_DISABLED: 'true', + AWS_DISABLE_HOST_PREFIX_INJECTION: 'true', + AWS_REGION: 'us-east-1', + AWS_DEFAULT_REGION: 'us-east-1', +}; + +/** Run `node` with `args`. `env` is its whole environment: nothing is inherited. */ +function node(args: string[], env: Record = {}) { + return spawnSync(process.execPath, args, { env, encoding: 'utf-8', timeout: 30_000 }); +} + +describe('emulator test guard', () => { + // One `node` start per test, about 50 ms each. + jest.setTimeout(60_000); + + describe('jest-config.js', () => { + /** The global setup of the emulator configuration, built from a unit configuration that has one of its own. */ + const BUILD = `require(${JSON.stringify(JEST_CONFIG)})({ globalSetup: 'unit-setup' }).globalSetup`; + + test('accepts what the wrapper sets, and puts its own global setup in place of the unit one', () => { + const result = node(['-p', BUILD], WRAPPER_ENVIRONMENT); + + expect(result).toMatchObject({ status: 0, stdout: `${GLOBAL_SETUP}\n`, stderr: '' }); + }); + + test.each([ + 'http://127.0.0.1:1', // not TLS + 'https://localhost:1', // a name, not the address + 'https://127.0.0.2:1', // another address + 'https://127.0.0.1:1@outside.invalid', // only begins like the emulator's: the host is outside.invalid + 'https://outside.invalid/https://127.0.0.1:1', // only ends like it + ])('refuses the endpoint %s', (endpoint) => { + const result = node(['-p', BUILD], { ...WRAPPER_ENVIRONMENT, AWS_ENDPOINT_URL: endpoint }); + + expect(result.status).toBe(1); + expect(result.stderr).toContain(`(AWS_ENDPOINT_URL='${endpoint}')`); + }); + + test.each([ + 'AWS_PROFILE', // a source of credentials + 'AWS_ENDPOINT_URL_DYNAMODB', // begins like an accepted name, and sends one service elsewhere + 'AWS_SDK_UA_APP_ID', // harmless in itself: whatever the wrapper does not set is refused + ])('refuses %s beside what the wrapper sets', (stray) => { + const result = node(['-p', BUILD], { ...WRAPPER_ENVIRONMENT, [stray]: 'anything' }); + + expect(result.status).toBe(1); + expect(result.stderr).toContain(`unexpected: ${stray})`); + }); + + test.each(['cdk', 'cli'])('%s/jest.emulator.config.js refuses a shell without the emulator environment', (workspace) => { + const result = node([path.join(REPO_ROOT, workspace, 'jest.emulator.config.js')]); + + expect(result.status).toBe(1); + expect(result.stderr).toContain("(AWS_ENDPOINT_URL=''). Run them with: mise run test:integration"); + }); + }); + + describe('jest-global-setup.js refuses to start a run', () => { + /** + * Runs the setup, as jest does, against a listener that answers the health route with the + * emulator's own body and is not the emulator: it does not speak TLS, let alone with the + * certificate of this run. The system resolver is taken out first, so that it is not asked + * even if the preload under test lets the setup's own probe through. + */ + const START = ` + const impostor = require('node:http').createServer((_request, response) => response.end('ok')).unref(); + impostor.listen(0, '127.0.0.1', async () => { + require('node:dns').lookup = (_host, _options, callback) => callback(new Error('no name resolution here')); + process.env.AWS_ENDPOINT_URL = 'https://127.0.0.1:' + impostor.address().port; + await require(${JSON.stringify(GLOBAL_SETUP)})(); + console.log('accepted'); + });`; + + test('without the loopback-only preload', () => { + const result = node(['-e', START], WRAPPER_ENVIRONMENT); + + expect(result.status).toBe(1); + expect(result.stderr).toContain('Error: Emulator tests need the loopback-only preload'); + }); + + test('with a preload that refuses nothing', () => { + // The name the setup looks for, on a connect that lets everything through. + const nameOnly = ` + const net = require('node:net'); + const connect = net.Socket.prototype.connect; + net.Socket.prototype.connect = function loopbackOnlyConnect(...args) { return connect.apply(this, args); };`; + + const result = node(['-e', nameOnly + START], WRAPPER_ENVIRONMENT); + + expect(result.status).toBe(1); + expect(result.stderr).toContain('Error: Emulator tests need the loopback-only preload'); + }); + + test('with a guard that is not the preload', () => { + // Refuses the probe, under another name. + const otherName = ` + const net = require('node:net'); + const connect = net.Socket.prototype.connect; + net.Socket.prototype.connect = function someOtherGuard(...args) { + if (typeof args[1] === 'string' && args[1] !== '127.0.0.1') throw new Error('refused by another guard'); + return connect.apply(this, args); + };`; + + const result = node(['-e', otherName + START], WRAPPER_ENVIRONMENT); + + expect(result.status).toBe(1); + expect(result.stderr).toContain('Error: Emulator tests need the loopback-only preload'); + }); + + test('on an endpoint that is some other local service', () => { + const result = node(['--require', PRELOAD, '-e', START], WRAPPER_ENVIRONMENT); + + expect(result.status).toBe(1); + expect(result.stderr).toMatch(/Error: No AWS Emulator at https:\/\/127\.0\.0\.1:\d+ \(/); + }); + }); + + describe('loopback-only.cjs', () => { + /** + * Tries each way out and reports how it ended. A refusal throws before the name is resolved, + * so the resolver, which is replaced first by one that only counts, is never asked. Without + * the guard an attempt ends in that resolver's error or at 127.0.0.2, and is abandoned at once. + */ + const ATTEMPTS = ` + const net = require('node:net'); + const http = require('node:http'); + const tls = require('node:tls'); + const server = http.createServer((_request, response) => response.end('ok')); + server.listen(0, '127.0.0.1', async () => { + const report = { lookups: 0 }; + require('node:dns').lookup = (_host, _options, callback) => { report.lookups += 1; callback(new Error('no name resolution here')); }; + const attempt = (name, open) => { + try { + open().on('error', () => undefined).destroy(); + report[name] = 'not refused'; + } catch (error) { + report[name] = error.message; + } + }; + attempt('net.connect', () => net.connect({ host: 'outside.invalid', port: 443 })); + attempt('http.get', () => http.get({ host: 'outside.invalid' })); + attempt('tls.connect', () => tls.connect({ host: 'outside.invalid', port: 443 })); + attempt('socket.connect', () => new net.Socket().connect(80, '127.0.0.2')); + report.fetch = await fetch('http://outside.invalid/').then(() => 'not refused', (error) => String(error.cause?.message)); + report.loopback = await (await fetch('http://127.0.0.1:' + server.address().port)).text(); + server.close(); + console.log(JSON.stringify(report)); + });`; + + test('refuses every host but loopback, before the name is resolved', () => { + const refused = (host: string) => expect.stringContaining(`and this one tried to reach ${host}.`); + + const result = node(['--require', PRELOAD, '-e', ATTEMPTS]); + + expect(result).toMatchObject({ status: 0, stderr: '' }); + expect(JSON.parse(result.stdout)).toEqual({ + 'net.connect': refused('outside.invalid'), + 'http.get': refused('outside.invalid'), + 'tls.connect': refused('outside.invalid'), + 'socket.connect': refused('127.0.0.2'), + 'fetch': refused('outside.invalid'), + 'lookups': 0, + // Loopback stays open: that is where the emulator is. + 'loopback': 'ok', + }); + }); + }); +}); diff --git a/cdk/test/scripts/integ-workflow.test.ts b/cdk/test/scripts/integ-workflow.test.ts new file mode 100644 index 000000000..527040ead --- /dev/null +++ b/cdk/test/scripts/integ-workflow.test.ts @@ -0,0 +1,46 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +/** + * Test for the command the `integ` job in `.github/workflows/integ.yml` runs. + * + * mise appends whatever follows `mise //cdk:integ --` to the task's last command, + * `integ-runner`, which exits 1 on an option it does not declare. The job sits + * behind the `deploy` approval gate, so a command that cannot start goes unseen + * until someone approves a run. This test fails, without AWS access, as soon as + * the workflow gives the task anything or runs it a second time; an option that + * is meant to be passed has to be allowed here first. + * + * Same placement rationale as `check-constants-sync.test.ts`: `cdk/test/` is the + * Jest tree that can reach the repository root. + */ + +import * as fs from 'node:fs'; +import * as path from 'node:path'; + +const WORKFLOW = fs.readFileSync(path.resolve(__dirname, '../../../.github/workflows/integ.yml'), 'utf-8'); + +/** What each invocation writes after the task name, continuation lines included. */ +const AFTER_TASK = [...WORKFLOW.matchAll(/^[^#\n]*mise \/\/cdk:integ((?:.*\\\n)*.*)$/gm)].map((match) => match[1]); + +describe('integ workflow', () => { + test('runs the integ task once, with nothing after it', () => { + expect(AFTER_TASK).toEqual(['']); + }); +}); diff --git a/cli/AGENTS.md b/cli/AGENTS.md index e1ce0cb3e..d779a31e5 100644 --- a/cli/AGENTS.md +++ b/cli/AGENTS.md @@ -42,6 +42,7 @@ The suite is sealed off from the machine it runs on (`test/setup/`): | `cli/src/auth.ts` | WRITE | Cognito login, token cache (`~/.bgagent/credentials.json`) | | `cli/src/types.ts` | WRITE | API types (mirror of `cdk/.../types.ts`) | | `cli/test/` | WRITE | Jest tests | +| `cli/test/emulator/` | WRITE | Emulator-backed tests (`*.emulator.ts`): real CLI code against a local AWS Emulator. Not part of the unit run: `mise run test:integration` from the repository root (needs Docker). Rules and known differences from AWS: [scripts/aws-emulator/README.md](../scripts/aws-emulator/README.md). | ## Code style diff --git a/cli/README.md b/cli/README.md index e995b9174..a86bc4147 100644 --- a/cli/README.md +++ b/cli/README.md @@ -304,7 +304,7 @@ bgagent runtime status \ ### `bgagent ops stuck-tasks` -List tasks in `SUBMITTED`, `HYDRATING`, or `AWAITING_APPROVAL` older than the stranded-task reconciler thresholds (defaults: 1200s / 7200s). Text output includes Cognito email plus username UUID. +List tasks that have been in `SUBMITTED`, `HYDRATING`, or `AWAITING_APPROVAL` longer than the stranded-task reconciler thresholds (defaults: 1200s / 7200s). Text output includes Cognito email plus username UUID. `AGE(s)` / `age_seconds` is the time in the current status; rows are listed oldest-created first. ``` bgagent ops stuck-tasks \ @@ -319,7 +319,7 @@ Compare `UserConcurrencyTable` counters with live active task counts per user. R ``` bgagent ops concurrency \ - --limit Per-user limit (default: 3) \ + --limit Per-user limit (default: 10) \ --output ``` @@ -423,14 +423,14 @@ bgagent admin reset-password \ For failed tasks, the error display is structured when a classification is available: ``` -Error: [CONCURRENCY] Concurrency limit reached - The maximum number of concurrent tasks for this user has been reached. - Remedy: Wait for an active task to complete, cancel a running task, or ask an admin to increase the limit. - Retryable: yes - Detail: User concurrency limit reached +Error: [AUTH] Repository not found or inaccessible + The GitHub token cannot access the target repository. It may not exist or the token lacks visibility. + Remedy: Check that the repository name is correct and the configured PAT has access to it. + Retryable: no + Detail: Pre-flight check failed: REPO_NOT_FOUND_OR_NO_ACCESS — GitHub API returned HTTP 404 for acme/widgets ``` -The classifier covers 9 error categories: `auth`, `network`, `concurrency`, `compute`, `agent`, `guardrail`, `config`, `timeout`, and `unknown`. When no classification is available, the raw error message is shown. +The classifier covers 10 error categories: `auth`, `network`, `concurrency`, `compute`, `agent`, `guardrail`, `config`, `timeout`, `blocked`, and `unknown`. When no classification is available, the raw error message is shown. **JSON mode** (`--output json`) prints the raw API response as pretty-printed JSON, suitable for piping to `jq` or other tools. diff --git a/cli/jest.emulator.config.js b/cli/jest.emulator.config.js new file mode 100644 index 000000000..4bc710f1d --- /dev/null +++ b/cli/jest.emulator.config.js @@ -0,0 +1,2 @@ +// Emulator-backed CLI tests (test/emulator/*.emulator.ts). Run with `mise run test:integration`. +module.exports = require('../scripts/aws-emulator/jest-config')(require('./package.json').jest); diff --git a/cli/src/commands/github.ts b/cli/src/commands/github.ts index a72a36c43..5dff817e7 100644 --- a/cli/src/commands/github.ts +++ b/cli/src/commands/github.ts @@ -18,7 +18,6 @@ */ import { - GetSecretValueCommand, PutSecretValueCommand, SecretsManagerClient, } from '@aws-sdk/client-secrets-manager'; @@ -127,29 +126,12 @@ export function makeGithubCommand(): Command { const sm = makeClient(SecretsManagerClient, { region }); - // Show whether a secret is already configured so the operator - // doesn't accidentally rotate it without realising. Linear's - // signing secrets start with `lin_wh_` — GitHub's are - // free-form (operator-chosen), so we can't pattern-match. - // Just check whether *anything* is there. - let alreadyConfigured = false; - try { - const cur = await sm.send(new GetSecretValueCommand({ SecretId: webhookSecretArn })); - if (cur.SecretString && cur.SecretString.length > 0 && !cur.SecretString.startsWith('{')) { - // CDK seeds a JSON-blob placeholder; a real GitHub secret - // wouldn't start with `{`. Crude but good enough. - alreadyConfigured = true; - } - } catch (err) { - if ((err as { name?: string }).name !== 'ResourceNotFoundException') { - throw err; - } - } - if (alreadyConfigured) { - console.log(' ⚠ A signing secret is already configured. This command will OVERWRITE it.'); - console.log(' Make sure the new value matches what you pasted into GitHub.'); - console.log(); - } + // A GitHub signing secret is operator-chosen, and CloudFormation creates + // this secret with a random password, so a stored secret cannot be told + // from one nobody has set. Say what the command does instead of guessing. + console.log(' This replaces the signing secret stored for the stack.'); + console.log(' Make sure the new value matches what you pasted into GitHub.'); + console.log(); const secret = (await promptSecret('GitHub webhook signing secret: ')).trim(); if (!secret) { diff --git a/cli/src/commands/ops.ts b/cli/src/commands/ops.ts index c9462456e..29331c55f 100644 --- a/cli/src/commands/ops.ts +++ b/cli/src/commands/ops.ts @@ -110,7 +110,7 @@ export function makeOpsCommand(): Command { .description('Show per-user active task counts vs admission limit (UserConcurrencyTable)') .option('--region ', 'AWS region (defaults to configured region or AWS_REGION)') .option('--stack-name ', 'CloudFormation stack name', DEFAULT_STACK_NAME) - .option('--limit ', 'Per-user concurrency limit (default: 3)', parseInt) + .option('--limit ', 'Per-user concurrency limit (default: 10)', parseInt) .option('--output ', 'Output format: text or json', 'text') .action(async (opts) => { const { region, stackName } = resolveOperatorContext(opts); diff --git a/cli/src/github-token.ts b/cli/src/github-token.ts index 60b7c36d7..a66ee3ea7 100644 --- a/cli/src/github-token.ts +++ b/cli/src/github-token.ts @@ -101,7 +101,17 @@ export async function resolveGithubTokenSecretArn( }; } -/** True when the secret already holds a non-placeholder PAT/token string. */ +/** + * How a GitHub token starts: one of the type prefixes GitHub documents at + * https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/about-authentication-to-github#githubs-token-formats + * or, for a token issued before GitHub introduced prefixes in 2021, 40 hex digits and nothing else. + */ +const GITHUB_TOKEN_SHAPE = /^(gh[pousr]_|github_pat_|[0-9a-f]{40}$)/; + +/** + * True when the secret holds a GitHub token. Presence is not enough: a secret + * nobody has set holds the 32-character password CloudFormation generated for it. + */ export async function isGithubTokenConfigured( region: string, secretArn: string, @@ -109,14 +119,7 @@ export async function isGithubTokenConfigured( const sm = makeClient(SecretsManagerClient, { region }); try { const cur = await sm.send(new GetSecretValueCommand({ SecretId: secretArn })); - if (!cur.SecretString || cur.SecretString.length === 0) { - return false; - } - // CDK seeds an empty JSON placeholder on first deploy; a real PAT would not. - if (cur.SecretString.startsWith('{')) { - return false; - } - return true; + return GITHUB_TOKEN_SHAPE.test(cur.SecretString ?? ''); } catch (err) { if ((err as { name?: string }).name === 'ResourceNotFoundException') { return false; diff --git a/cli/src/ops-queries.ts b/cli/src/ops-queries.ts index b6d8dda87..4c3e06c36 100644 --- a/cli/src/ops-queries.ts +++ b/cli/src/ops-queries.ts @@ -27,7 +27,8 @@ import { documentClient, lowLevelClient } from './dynamo-clients'; /** Align with ``reconcile-stranded-tasks.ts`` defaults. */ export const DEFAULT_STRANDED_TIMEOUT_SECONDS = 1200; export const DEFAULT_APPROVAL_STRANDED_TIMEOUT_SECONDS = 7200; -export const DEFAULT_MAX_CONCURRENT_TASKS_PER_USER = 3; +/** The per-user cap the stack deploys (``maxConcurrentTasksPerUser`` in ``cdk/src/stacks/agent.ts``). */ +export const DEFAULT_MAX_CONCURRENT_TASKS_PER_USER = 10; export type StuckTaskStatus = 'SUBMITTED' | 'HYDRATING' | 'AWAITING_APPROVAL'; @@ -90,13 +91,19 @@ async function queryStuckByStatus( const userId = item.user_id?.S; const createdAt = item.created_at?.S; if (!taskId || !userId || !createdAt) continue; + // Age by time in the current status, as the reconciler does (#441): + // status_created_at is `#`, and created_at is the fallback + // for a row without a readable one. + const enteredAt = item.status_created_at?.S?.split('#')[1]; + const age = ageSeconds(enteredAt && !Number.isNaN(Date.parse(enteredAt)) ? enteredAt : createdAt); + if (age < thresholdSeconds) continue; rows.push({ task_id: taskId, user_id: userId, status, repo: item.repo?.S, created_at: createdAt, - age_seconds: ageSeconds(createdAt), + age_seconds: age, threshold_seconds: thresholdSeconds, }); } diff --git a/cli/src/platform-doctor.ts b/cli/src/platform-doctor.ts index 844857814..e76a462a0 100644 --- a/cli/src/platform-doctor.ts +++ b/cli/src/platform-doctor.ts @@ -565,7 +565,7 @@ async function checkGithubToken( id, label, status: 'fail', - detail: 'GitHub token secret is empty or still the CDK placeholder. Run `bgagent github set-token`.', + detail: 'GitHub token secret is empty, still the CDK placeholder, or not in a GitHub token format. Run `bgagent github set-token`.', }; } diff --git a/cli/test/commands/github-token.test.ts b/cli/test/commands/github-token.test.ts index 37a857811..122f07cb8 100644 --- a/cli/test/commands/github-token.test.ts +++ b/cli/test/commands/github-token.test.ts @@ -214,13 +214,45 @@ describe('isGithubTokenConfigured', () => { smSend.mockReset(); }); - test('returns true for a non-placeholder secret string', async () => { - smSend.mockResolvedValueOnce({ SecretString: 'ghp_abc123' }); + test('returns false for a string that is not a GitHub token', async () => { + smSend.mockResolvedValueOnce({ SecretString: '{}' }); + await expect(isGithubTokenConfigured('us-east-1', 'arn:secret')).resolves.toBe(false); + }); + + // What a deployed stack holds until someone stores a token: CDK creates the + // secret with CloudFormation's generated password (32 characters, at least one + // upper-case letter, lower-case letter, digit and punctuation character). + test('returns false for the generated password of a secret nobody has set', async () => { + smSend.mockResolvedValueOnce({ SecretString: 'Aa1!'.repeat(8) }); + await expect(isGithubTokenConfigured('us-east-1', 'arn:secret')).resolves.toBe(false); + }); + + // Built with repeat() so that no token-shaped literal sits in the source. + test.each([ + ['classic personal access token', `ghp_${'a1B2'.repeat(9)}`], + ['fine-grained personal access token', `github_pat_${'a1B2'.repeat(5)}aa_${'c3D4'.repeat(14)}ccc`], + ['OAuth token', `gho_${'a1B2'.repeat(9)}`], + ['GitHub App user access token', `ghu_${'a1B2'.repeat(9)}`], + ['GitHub App installation access token', `ghs_${'a1B2'.repeat(9)}`], + ['GitHub App refresh token', `ghr_${'a1B2'.repeat(9)}`], + ['token in the format issued before 2021', 'a1b2c3d4e5'.repeat(4)], + ])('returns true for a %s', async (_format, token) => { + smSend.mockResolvedValueOnce({ SecretString: token }); await expect(isGithubTokenConfigured('us-east-1', 'arn:secret')).resolves.toBe(true); }); - test('returns false for empty or JSON placeholder secrets', async () => { - smSend.mockResolvedValueOnce({ SecretString: '{}' }); + // One row per anchor of the pattern: the value has to start with the token, + // and the format without a prefix is 40 hex digits and no more. + test.each([ + ['value that only contains a token', JSON.stringify({ token: `ghp_${'a1B2'.repeat(9)}` })], + ['string of 41 hex digits', `${'a1b2c3d4e5'.repeat(4)}f`], + ])('returns false for a %s', async (_case, value) => { + smSend.mockResolvedValueOnce({ SecretString: value }); + await expect(isGithubTokenConfigured('us-east-1', 'arn:secret')).resolves.toBe(false); + }); + + test('returns false when the secret has no string value', async () => { + smSend.mockResolvedValueOnce({}); await expect(isGithubTokenConfigured('us-east-1', 'arn:secret')).resolves.toBe(false); }); diff --git a/cli/test/commands/github.test.ts b/cli/test/commands/github.test.ts new file mode 100644 index 000000000..403a5b1fd --- /dev/null +++ b/cli/test/commands/github.test.ts @@ -0,0 +1,102 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +import { GetSecretValueCommand, PutSecretValueCommand } from '@aws-sdk/client-secrets-manager'; +import { makeGithubCommand } from '../../src/commands/github'; +import { promptSecret } from '../../src/prompt-secret'; +import { getStackOutput } from '../../src/stack-outputs'; + +const smSend = jest.fn(); +jest.mock('@aws-sdk/client-secrets-manager', () => { + const actual = jest.requireActual('@aws-sdk/client-secrets-manager'); + return { ...actual, SecretsManagerClient: jest.fn(() => ({ send: smSend })) }; +}); +jest.mock('../../src/stack-outputs', () => ({ getStackOutput: jest.fn() })); +jest.mock('../../src/prompt-secret', () => ({ promptSecret: jest.fn() })); +jest.mock('../../src/config', () => ({ + loadConfig: () => ({ region: 'us-east-1' }), + tryLoadConfig: () => null, +})); + +/** + * What a deployed stack holds in a secret nobody has set: CDK creates it with + * CloudFormation's generated password (32 characters, at least one upper-case + * letter, lower-case letter, digit and punctuation character). + */ +const GENERATED_PASSWORD = 'Aa1!'.repeat(8); + +describe('github command', () => { + let consoleSpy: jest.SpiedFunction; + const output = (): string => consoleSpy.mock.calls.map((call) => String(call[0] ?? '')).join('\n'); + const run = (...args: string[]): Promise => + makeGithubCommand().parseAsync(['node', 'github', ...args, '--region', 'us-east-1']); + + /** The secret currently holds `stored`; writes succeed. */ + function secretHolds(stored: string): void { + smSend.mockImplementation(async (command: unknown) => + (command instanceof GetSecretValueCommand ? { SecretString: stored } : {})); + } + + /** Every value the command wrote, in order. */ + const written = (): unknown[] => smSend.mock.calls + .map((call) => call[0] as unknown) + .filter((command): command is PutSecretValueCommand => command instanceof PutSecretValueCommand) + .map((command) => command.input); + + beforeEach(() => { + consoleSpy = jest.spyOn(console, 'log').mockImplementation(); + smSend.mockReset(); + (getStackOutput as jest.Mock).mockImplementation(async (_region: string, _stack: string, key: string) => + (key.endsWith('SecretArn') ? `arn:${key}` : null)); + (promptSecret as jest.Mock).mockResolvedValue('value-typed-by-the-operator'); + }); + + afterEach(() => { + consoleSpy.mockRestore(); + }); + + test('set-token on a fresh stack stores the token without an overwrite warning', async () => { + secretHolds(GENERATED_PASSWORD); + + await run('set-token'); + + expect(output()).not.toContain('OVERWRITE'); + expect(written()).toEqual([{ SecretId: 'arn:GitHubTokenSecretArn', SecretString: 'value-typed-by-the-operator' }]); + }); + + test('set-token warns before replacing a stored token', async () => { + // Built with repeat() so that no token-shaped literal sits in the source. + secretHolds(`ghp_${'a1B2'.repeat(9)}`); + + await run('set-token'); + + expect(output()).toContain('A GitHub token is already configured in this secret. This command will OVERWRITE it.'); + }); + + test('set-webhook-secret does not claim a signing secret is configured on a fresh stack', async () => { + secretHolds(GENERATED_PASSWORD); + + await run('set-webhook-secret'); + + expect(output()).not.toContain('already configured'); + // What it says instead, whatever the secret holds. + expect(output()).toContain('This replaces the signing secret stored for the stack.'); + expect(written()).toEqual([{ SecretId: 'arn:GitHubWebhookSecretArn', SecretString: 'value-typed-by-the-operator' }]); + }); +}); diff --git a/cli/test/commands/ops-queries.test.ts b/cli/test/commands/ops-queries.test.ts index 3192bdb6a..cd45c1999 100644 --- a/cli/test/commands/ops-queries.test.ts +++ b/cli/test/commands/ops-queries.test.ts @@ -17,9 +17,16 @@ * SOFTWARE. */ +import * as fs from 'fs'; +import * as path from 'path'; import { QueryCommand } from '@aws-sdk/client-dynamodb'; import { QueryCommand as DocQueryCommand, ScanCommand } from '@aws-sdk/lib-dynamodb'; -import { findStuckTasks, buildConcurrencyReport, countActiveTasksForUser } from '../../src/ops-queries'; +import { + findStuckTasks, + buildConcurrencyReport, + countActiveTasksForUser, + DEFAULT_MAX_CONCURRENT_TASKS_PER_USER, +} from '../../src/ops-queries'; const lowLevelSend = jest.fn(); const docSend = jest.fn(); @@ -49,7 +56,8 @@ describe('ops-queries', () => { }); test('findStuckTasks parses each status query into a distinct, status-tagged row', async () => { - const oldCreated = new Date(Date.now() - 3600_000).toISOString(); + // Older than both thresholds, as rows the index query returns always are. + const oldCreated = new Date(Date.now() - 3 * 3600_000).toISOString(); // One distinct task per status query (Promise.all fires three queries). lowLevelSend .mockResolvedValueOnce({ @@ -124,6 +132,84 @@ describe('ops-queries', () => { expect(tasks[0]?.repo).toBeUndefined(); }); + test('findStuckTasks ages a task by the time it entered its status, not by its creation', async () => { + const ago = (seconds: number) => new Date(Date.now() - seconds * 1000).toISOString(); + lowLevelSend + // SUBMITTED: waited in the admission queue for three hours, picked up a minute ago. + .mockResolvedValueOnce({ + Items: [{ + task_id: { S: 'picked-up-just-now' }, + user_id: { S: 'user-1' }, + created_at: { S: ago(3 * 3600) }, + status_created_at: { S: `SUBMITTED#${ago(60)}` }, + }], + }) + .mockResolvedValueOnce({ Items: [] }) + // AWAITING_APPROVAL: all created long ago; two paused ten minutes ago, one three hours ago. + .mockResolvedValueOnce({ + Items: [{ + task_id: { S: 'paused-just-now' }, + user_id: { S: 'user-1' }, + created_at: { S: ago(5 * 3600) }, + status_created_at: { S: `AWAITING_APPROVAL#${ago(600)}` }, + }, { + // A row that still carries the entry time of an earlier status is aged + // from that time all the same, as the reconciler ages it. + task_id: { S: 'paused-just-now-earlier-entry' }, + user_id: { S: 'user-1' }, + created_at: { S: ago(5 * 3600) }, + status_created_at: { S: `RUNNING#${ago(600)}` }, + }, { + task_id: { S: 'paused-too-long' }, + user_id: { S: 'user-1' }, + created_at: { S: ago(5 * 3600) }, + status_created_at: { S: `AWAITING_APPROVAL#${ago(3 * 3600)}` }, + }], + }); + + const tasks = await findStuckTasks('us-east-1', 'TaskTable'); + + expect(tasks.map((t) => t.task_id)).toEqual(['paused-too-long']); + expect(tasks[0].age_seconds).toBeGreaterThanOrEqual(3 * 3600); + expect(tasks[0].age_seconds).toBeLessThan(3 * 3600 + 60); + }); + + test('findStuckTasks falls back to created_at when status_created_at is missing or unreadable', async () => { + const created = new Date(Date.now() - 3 * 3600_000).toISOString(); + lowLevelSend + .mockResolvedValueOnce({ + Items: [{ task_id: { S: 'no-status-time' }, user_id: { S: 'user-1' }, created_at: { S: created } }], + }) + .mockResolvedValueOnce({ + Items: [{ + task_id: { S: 'bad-status-time' }, + user_id: { S: 'user-1' }, + created_at: { S: created }, + status_created_at: { S: 'HYDRATING#not-a-date' }, + }], + }) + .mockResolvedValueOnce({ Items: [] }); + + const tasks = await findStuckTasks('us-east-1', 'TaskTable'); + + expect(tasks.map((t) => t.task_id).sort()).toEqual(['bad-status-time', 'no-status-time']); + for (const task of tasks) { + expect(task.age_seconds).toBeGreaterThanOrEqual(3 * 3600); + } + }); + + // The stack does not publish its cap, so the CLI carries a copy. Read as text: + // the CLI must not import the CDK package (same technique as model-id.test.ts). + test('the default per-user limit is the cap the stack deploys', () => { + const stack = fs.readFileSync( + path.join(__dirname, '..', '..', '..', 'cdk', 'src', 'stacks', 'agent.ts'), + 'utf-8', + ); + const deployed = /const maxConcurrentTasksPerUser = (\d+);/.exec(stack)?.[1]; + expect(deployed).toBeDefined(); + expect(DEFAULT_MAX_CONCURRENT_TASKS_PER_USER).toBe(Number(deployed)); + }); + test('countActiveTasksForUser paginates UserStatusIndex', async () => { docSend .mockResolvedValueOnce({ diff --git a/cli/test/commands/ops.test.ts b/cli/test/commands/ops.test.ts index 2bfced229..224ecd694 100644 --- a/cli/test/commands/ops.test.ts +++ b/cli/test/commands/ops.test.ts @@ -180,6 +180,6 @@ describe('ops command', () => { const payload = JSON.parse(consoleSpy.mock.calls[0][0] as string); expect(payload.concurrency).toHaveLength(1); expect(payload.concurrency[0].user_email).toBe('you@example.com'); - expect(payload.limit_per_user).toBe(3); + expect(payload.limit_per_user).toBe(10); }); }); diff --git a/cli/test/emulator/cognito-sign-in.emulator.ts b/cli/test/emulator/cognito-sign-in.emulator.ts new file mode 100644 index 000000000..df1102466 --- /dev/null +++ b/cli/test/emulator/cognito-sign-in.emulator.ts @@ -0,0 +1,243 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +/** + * The CLI's real sign-in path against an AWS Emulator + * (https://github.com/aws/aws-emulator) instead of a mocked SDK (ADR-013 + * Tier 2a). + * + * Nothing here is mocked. `bgagent configure --stack-name` reads a real + * CloudFormation stack's outputs, and `login` / `getAuthToken` / + * `changePassword` talk to the Cognito user pool that stack created, so the + * assertions are about what the service answers (JWT claims, error names, the + * pool's password policy) rather than about what a mock was told to return. + * + * Named `*.emulator.ts`, which the unit configuration does not match. It runs + * only through `jest.emulator.config.js` (`mise run test:integration`), which + * refuses to start unless the AWS environment is the emulator's and the + * emulator answers. + */ + +import * as fs from 'fs'; +import * as os from 'os'; +import * as path from 'path'; +import { + CloudFormationClient, + CreateStackCommand, + DeleteStackCommand, + DescribeStacksCommand, + type Stack, +} from '@aws-sdk/client-cloudformation'; +import { changePassword, getAuthToken, login } from '../../src/auth'; +import { adminInviteUser, adminResetPassword, resolveCognitoAdminContext } from '../../src/cognito-admin'; +import { makeConfigureCommand } from '../../src/commands/configure'; +import { loadConfig, loadCredentials, saveCredentials } from '../../src/config'; +import { makeClient } from '../../src/ua'; + +const REGION = process.env.AWS_REGION ?? 'us-east-1'; +const SETUP_TIMEOUT_MS = 30_000; +/** Shorter than the hook, so a stack that never settles reports itself instead of a bare hook timeout. */ +const STACK_WAIT_MS = 20_000; +const POLL_INTERVAL_MS = 50; + +const TEMP_PASSWORD = 'T3mp$trongPass!'; +const PASSWORD = 'N3w$trongPass!'; +const NEXT_PASSWORD = 'An0ther$trongPass!'; + +/** + * The two resources the sign-in path needs, shaped like the ones + * `cdk/src/constructs/task-api.ts` synthesizes (email as the username, the + * 12-character policy, password + refresh auth flows, no client secret), with + * the outputs `bgagent configure --stack-name` reads. + */ +const STACK_TEMPLATE = { + AWSTemplateFormatVersion: '2010-09-09', + Resources: { + UserPool: { + Type: 'AWS::Cognito::UserPool', + Properties: { + UsernameAttributes: ['email'], + AutoVerifiedAttributes: ['email'], + AdminCreateUserConfig: { AllowAdminCreateUserOnly: true }, + Policies: { + PasswordPolicy: { + MinimumLength: 12, + RequireLowercase: true, + RequireUppercase: true, + RequireNumbers: true, + RequireSymbols: true, + }, + }, + }, + }, + AppClient: { + Type: 'AWS::Cognito::UserPoolClient', + Properties: { + UserPoolId: { Ref: 'UserPool' }, + ExplicitAuthFlows: ['ALLOW_USER_PASSWORD_AUTH', 'ALLOW_USER_SRP_AUTH', 'ALLOW_REFRESH_TOKEN_AUTH'], + GenerateSecret: false, + }, + }, + }, + Outputs: { + ApiUrl: { Value: 'https://api.invalid/v1/' }, + UserPoolId: { Value: { Ref: 'UserPool' } }, + AppClientId: { Value: { Ref: 'AppClient' } }, + }, +}; + +/** Claims of an ID token; the signature is not checked (the CLI never checks it either). */ +function idTokenClaims(idToken: string): Record { + const [, payload] = idToken.split('.'); + return JSON.parse(Buffer.from(payload, 'base64url').toString('utf-8')) as Record; +} + +async function settledStack(cloudFormation: CloudFormationClient, stackName: string): Promise { + const deadline = Date.now() + STACK_WAIT_MS; + while (Date.now() < deadline) { + const stack = (await cloudFormation.send(new DescribeStacksCommand({ StackName: stackName }))).Stacks?.[0]; + if (stack?.StackStatus && !stack.StackStatus.endsWith('_IN_PROGRESS')) return stack; + await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS)); + } + throw new Error(`Fixture stack ${stackName} was still in progress after ${STACK_WAIT_MS} ms`); +} + +describe('bgagent sign-in against an AWS Emulator', () => { + const stackName = `bgagent-cli-emulator-${Date.now().toString(36)}`; + let cloudFormation: CloudFormationClient; + let stackOutputs: Map; + let configDir: string; + let userCount = 0; + + /** A fresh user in FORCE_CHANGE_PASSWORD, as `bgagent admin invite-user` leaves it. */ + async function invitedUser(): Promise { + userCount += 1; + const email = `user-${userCount}@example.com`; + await adminInviteUser(await resolveCognitoAdminContext({ region: REGION, stackName }), email, TEMP_PASSWORD); + return email; + } + + /** A fresh user with a permanent password, as `bgagent admin reset-password` leaves it. */ + async function confirmedUser(): Promise { + const email = await invitedUser(); + await adminResetPassword(await resolveCognitoAdminContext({ region: REGION, stackName }), email, PASSWORD); + return email; + } + + beforeAll(async () => { + // First, before any CLI code runs: the CLI keeps its config and tokens under + // ~/.bgagent, and this suite must never read or replace the developer's own. + configDir = fs.mkdtempSync(path.join(os.tmpdir(), 'bgagent-emulator-')); + process.env.BGAGENT_CONFIG_DIR = configDir; + + cloudFormation = makeClient(CloudFormationClient, { region: REGION }); + await cloudFormation.send(new CreateStackCommand({ StackName: stackName, TemplateBody: JSON.stringify(STACK_TEMPLATE) })); + const stack = await settledStack(cloudFormation, stackName); + if (stack.StackStatus !== 'CREATE_COMPLETE') { + throw new Error(`Fixture stack ${stackName} ended in ${stack.StackStatus}: ${stack.StackStatusReason ?? 'no reason given'}`); + } + stackOutputs = new Map((stack.Outputs ?? []).map((output) => [output.OutputKey, output.OutputValue])); + + const log = jest.spyOn(console, 'log').mockImplementation(() => undefined); + try { + await makeConfigureCommand().parseAsync(['node', 'configure', '--stack-name', stackName, '--region', REGION]); + } finally { + log.mockRestore(); + } + }, SETUP_TIMEOUT_MS); + + afterAll(async () => { + if (configDir) fs.rmSync(configDir, { recursive: true, force: true }); + await cloudFormation?.send(new DeleteStackCommand({ StackName: stackName })); + }, SETUP_TIMEOUT_MS); + + /** Token cache inside the suite's own directory (never derived from the CLI's default). */ + const credentialsFile = (): string => path.join(configDir, 'credentials.json'); + + beforeEach(() => { + fs.rmSync(credentialsFile(), { force: true }); + }); + + test('configure --stack-name stores the pool and client the stack created', () => { + expect(stackOutputs.get('UserPoolId')).toMatch(new RegExp(`^${REGION}_`)); + expect(loadConfig()).toEqual({ + api_url: 'https://api.invalid/v1/', + region: REGION, + user_pool_id: stackOutputs.get('UserPoolId'), + client_id: stackOutputs.get('AppClientId'), + stack_name: stackName, + }); + }); + + test('an invited user is challenged for a new password and nothing is cached', async () => { + const email = await invitedUser(); + + await expect(login(email, TEMP_PASSWORD)).rejects.toThrow(/requires a new password on first login/); + + expect(loadCredentials()).toBeNull(); + }); + + test('first sign-in rotates the temporary password', async () => { + const email = await invitedUser(); + + await login(email, TEMP_PASSWORD, () => Promise.resolve(PASSWORD)); + + expect(loadCredentials()).not.toBeNull(); + await expect(login(email, TEMP_PASSWORD)).rejects.toThrow(/incorrect password/); + await expect(login(email, PASSWORD)).resolves.toBeUndefined(); + }); + + test('login caches an ID token for the user, and an expired cache is refreshed', async () => { + const email = await confirmedUser(); + + await login(email, PASSWORD); + + const cached = loadCredentials(); + expect(fs.statSync(credentialsFile()).mode % 0o1000).toBe(0o600); + const claims = idTokenClaims(cached!.id_token); + expect(claims).toMatchObject({ email, token_use: 'id', aud: loadConfig().client_id }); + // For a pool that a stack creates, the emulator names its own endpoint as + // the issuer, where AWS names + // https://cognito-idp..amazonaws.com/ (upstream: + // aws/aws-emulator issues/things-that-do-not-work/ + // 20261115T035031Z-cognito-identity-cognito-idp-the-cognito-id-token.md). + expect(claims.iss).toBe(`${process.env.AWS_ENDPOINT_URL}/${loadConfig().user_pool_id}`); + await expect(getAuthToken()).resolves.toBe(cached!.id_token); + + saveCredentials({ ...cached!, token_expiry: new Date(0).toISOString() }); + const refreshed = idTokenClaims(await getAuthToken()); + + expect(refreshed).toMatchObject({ email, sub: claims.sub }); + expect(loadCredentials()!.refresh_token).toBe(cached!.refresh_token); + expect(Date.parse(loadCredentials()!.token_expiry)).toBeGreaterThan(Date.now()); + }); + + test('change-password verifies the current password, applies the pool policy, then rotates', async () => { + const email = await confirmedUser(); + await login(email, PASSWORD); + + await expect(changePassword('Wr0ng$trongPass!', NEXT_PASSWORD)).rejects.toThrow('Current password is incorrect.'); + // The CLI's own prefix; what follows is the service's wording, which is not asserted. + await expect(changePassword(PASSWORD, 'weak')).rejects.toThrow(/^New password rejected: /); + await changePassword(PASSWORD, NEXT_PASSWORD); + + await expect(login(email, PASSWORD)).rejects.toThrow(/incorrect password/); + await expect(login(email, NEXT_PASSWORD)).resolves.toBeUndefined(); + }); +}); diff --git a/cli/test/emulator/github-token-seed.emulator.ts b/cli/test/emulator/github-token-seed.emulator.ts new file mode 100644 index 000000000..b24cf133a --- /dev/null +++ b/cli/test/emulator/github-token-seed.emulator.ts @@ -0,0 +1,104 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +/** + * What the CLI concludes about the platform GitHub token secret of a stack + * where nobody has stored a token, against an AWS Emulator (ADR-013 Tier 2a). + * + * A mocked test decides for itself what such a secret holds. Here the value is + * the one CloudFormation generates: the secret is declared the way `aws-cdk-lib` + * synthesizes `new secretsmanager.Secret(this, 'GitHubTokenSecret', { description })` + * in `cdk/src/stacks/agent.ts`, with `GenerateSecretString: {}`, which yields a + * random password and not a placeholder the CLI could recognize. + * + * Named `*.emulator.ts`; runs only through `jest.emulator.config.js` + * (`mise run test:integration`). + */ + +import { + CloudFormationClient, + CreateStackCommand, + DeleteStackCommand, + DescribeStacksCommand, + type Stack, +} from '@aws-sdk/client-cloudformation'; +import { isGithubTokenConfigured, putGithubToken, resolveGithubTokenSecretArn } from '../../src/github-token'; +import { makeClient } from '../../src/ua'; + +const REGION = process.env.AWS_REGION ?? 'us-east-1'; +const SETUP_TIMEOUT_MS = 30_000; +/** Shorter than the hook, so a stack that never settles reports itself instead of a bare hook timeout. */ +const STACK_WAIT_MS = 20_000; +const POLL_INTERVAL_MS = 50; + +const STACK_TEMPLATE = { + AWSTemplateFormatVersion: '2010-09-09', + Resources: { + GitHubTokenSecret: { + Type: 'AWS::SecretsManager::Secret', + Properties: { + Description: 'GitHub personal access token for the background agent', + GenerateSecretString: {}, + }, + }, + }, + Outputs: { GitHubTokenSecretArn: { Value: { Ref: 'GitHubTokenSecret' } } }, +}; + +async function settledStack(cloudFormation: CloudFormationClient, stackName: string): Promise { + const deadline = Date.now() + STACK_WAIT_MS; + while (Date.now() < deadline) { + const stack = (await cloudFormation.send(new DescribeStacksCommand({ StackName: stackName }))).Stacks?.[0]; + if (stack?.StackStatus && !stack.StackStatus.endsWith('_IN_PROGRESS')) return stack; + await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS)); + } + throw new Error(`Fixture stack ${stackName} was still in progress after ${STACK_WAIT_MS} ms`); +} + +describe('the platform GitHub token secret of a new stack', () => { + const stackName = `bgagent-cli-emulator-token-${Date.now().toString(36)}`; + let cloudFormation: CloudFormationClient; + let secretArn: string; + + beforeAll(async () => { + cloudFormation = makeClient(CloudFormationClient, { region: REGION }); + await cloudFormation.send(new CreateStackCommand({ StackName: stackName, TemplateBody: JSON.stringify(STACK_TEMPLATE) })); + const stack = await settledStack(cloudFormation, stackName); + if (stack.StackStatus !== 'CREATE_COMPLETE') { + throw new Error(`Fixture stack ${stackName} ended in ${stack.StackStatus}: ${stack.StackStatusReason ?? 'no reason given'}`); + } + // The secret `bgagent github set-token` writes to when no flag is given. + ({ secretArn } = await resolveGithubTokenSecretArn({ region: REGION, stackName })); + }, SETUP_TIMEOUT_MS); + + afterAll(async () => { + await cloudFormation?.send(new DeleteStackCommand({ StackName: stackName })); + }, SETUP_TIMEOUT_MS); + + test('a secret nobody has set is not a configured token', async () => { + await expect(isGithubTokenConfigured(REGION, secretArn)).resolves.toBe(false); + }); + + test('it is configured once a token is stored', async () => { + // Built with repeat() so that no token-shaped literal sits in the source. + await putGithubToken(REGION, secretArn, `ghp_${'a1B2'.repeat(9)}`); + + await expect(isGithubTokenConfigured(REGION, secretArn)).resolves.toBe(true); + }); +}); diff --git a/docs/abca-plugin/agents/agent-debugger.md b/docs/abca-plugin/agents/agent-debugger.md index 3c7ca07bf..5f3d0a6ed 100644 --- a/docs/abca-plugin/agents/agent-debugger.md +++ b/docs/abca-plugin/agents/agent-debugger.md @@ -50,7 +50,7 @@ You are a debugging specialist for the ABCA agent runtime. You diagnose task exe 2. **Check event types** for clues: - `preflight_failed` — GitHub access issue (PAT permissions, repo existence) - `guardrail_blocked` — Content screening rejected the prompt - - `admission_rejected` — Concurrency limit or validation failure + - `admission_queued` — Concurrency limit reached: the task waits for a free slot, and fails (`task_failed`, reason `queue_timeout`) after 24 hours in the queue - `task_failed` — Agent runtime error - `task_timed_out` — 9-hour limit exceeded diff --git a/docs/abca-plugin/skills/troubleshoot/SKILL.md b/docs/abca-plugin/skills/troubleshoot/SKILL.md index 0e3eaf18f..f42ecfa66 100644 --- a/docs/abca-plugin/skills/troubleshoot/SKILL.md +++ b/docs/abca-plugin/skills/troubleshoot/SKILL.md @@ -162,7 +162,7 @@ node cli/lib/bin/bgagent.js events --output json - Check if the agent is stuck in a loop (review logs) **Concurrency limit:** -- Default: 3 concurrent tasks per user +- Default: 10 concurrent tasks per user - Wait for running tasks to complete or cancel them ## Local Agent Testing Issues diff --git a/docs/decisions/ADR-013-tiered-validation-pyramid.md b/docs/decisions/ADR-013-tiered-validation-pyramid.md index f68640218..1817d8464 100644 --- a/docs/decisions/ADR-013-tiered-validation-pyramid.md +++ b/docs/decisions/ADR-013-tiered-validation-pyramid.md @@ -2,6 +2,7 @@ **Status:** proposed **Date:** 2026-05-19 +**Last-updated:** 2026-11-15 ## Context @@ -24,7 +25,7 @@ For a human, this is annoying. For an autonomous agent, this is catastrophic: - **Cascade failures** — in a stacked PR chain (ADR-001), a CI failure on PR 1 blocks PRs 2–N, multiplying the wait - **Cost amplification** — each round-trip costs inference tokens for the agent to re-read the failure, re-analyze, and re-attempt -The root cause: there is no **Tier 2** — a local, fast, high-fidelity validation layer that catches integration-level issues *before* pushing to remote. +The root cause: there is no **Tier 2** — a local, fast, high-fidelity validation layer that catches integration-level issues *before* pushing to remote. (Phase 2a of it now exists; see the table below.) ### What exists today @@ -33,7 +34,7 @@ The root cause: there is no **Tier 2** — a local, fast, high-fidelity validati | Pre-commit (Tier 0) | No fixed budget: by what is staged (measured times under Tier 0 below) | Formatting, secrets, lint and drift checks of the staged files | None — works well | | mise build (Tier 1) | 30–90s | Compile, unit tests, CDK synth, docs sync, linting | Wired as a pre-push gate (prek `pre-push` hooks run tests + security); the `mise run build` superset is available on demand | | Remote CI (Tier 3) | 5–20 min | Full matrix, security, E2E, deploy | Authoritative but slow | -| **Local integration (Tier 2)** | — | **Does not exist** | Integration-level validation without remote round-trip | +| **Local integration (Tier 2)** | About half a minute for phase 2a, on a laptop | Phase 2a only: how real handler, CLI and agent code behaves against emulated DynamoDB, S3, Secrets Manager, Cognito, STS and CloudWatch Logs | Phase 2a is an advisory check, not a required one; phases 2b–2d do not exist | ### Agentic-first motivation @@ -100,23 +101,23 @@ Status: **Implemented as a pre-push gate.** `.pre-commit-config.yaml` sets `defa **Tier 2 — Local sandbox (1–5 min, on-demand before PR)** -This tier does not exist today. It should provide: +Phase 2a exists; the rest of this tier does not. It should provide: -- Container-based integration tests against mocked AWS services (LocalStack or moto) -- CDK deploy to a local/ephemeral sandbox (validate IAM, resource creation without real cloud) +- Container-based integration tests against emulated AWS services (phase 2a uses the AWS Emulator; LocalStack and moto were the candidates when this ADR was written) +- CDK deploy to an ephemeral sandbox (validate IAM and resource creation). This part needs a real AWS account: the emulator does not evaluate IAM the way AWS does, and a missing `Allow` never fails a deployment there - Agent runtime smoke test (run the agent pipeline against a test repo in a local container) - Cross-package integration (API → handler → agent contract verification) - Policy validation (Cedar policy evaluation against test fixtures) -Status: **Gap — does not exist.** This is the primary investment needed. +Status: **Phase 2a implemented as an advisory check; phases 2b–2d are a gap.** `mise run test:integration` starts a pinned AWS Emulator in a container and runs ABCA's real handler, CLI and agent code against it, with no AWS account. The `emulator` workflow runs it on every pull request and is not a required check. ABCA's own agents cannot run it inside their container yet: the agent image has no Docker. What a green run shows and does not show, and the rules for tests in this tier, are in `scripts/aws-emulator/README.md`. Progressive build-out: | Phase | Capability | Mechanism | Catches | |-------|-----------|-----------|---------| -| 2a | Container integration tests | `mise run test:integration` → Docker Compose + LocalStack | AWS API call failures, DynamoDB schema issues, SQS message format | +| 2a | Container integration tests | `mise run test:integration` → the AWS Emulator in a container, version pinned in `scripts/aws-emulator/Dockerfile` | DynamoDB conditions, update expressions, transactions, index keys and `Limit` applied before a filter; S3 object and presigned GET behavior; Secrets Manager, Cognito sign-in, STS `AssumeRole` and CloudWatch Logs behavior; state shared between the Python agent and the TypeScript handlers. Not permissions, deployment or the AgentCore runtime | | 2b | Agent pipeline smoke | `mise run test:agent-smoke` → build agent container, run against fixture repo | Agent crashes, tool failures, prompt regressions | -| 2c | Ephemeral stack deploy | `mise run deploy:ephemeral` → CDK deploy to a disposable environment with auto-destroy | IAM permission gaps (ADR-002 preflight), resource wiring, real API behavior | +| 2c | Ephemeral stack deploy | `mise run deploy:ephemeral` → CDK deploy to a disposable environment in a real AWS account, with auto-destroy (not the emulator, which cannot show a missing permission) | IAM permission gaps (ADR-002 preflight), resource wiring, real API behavior | | 2d | Full local sandbox | `mise run sandbox` → MicroVM matching prod topology | End-to-end flow in production-equivalent isolation | **Tier 3 — Remote CI (5–20 min, authoritative, gates merge)** @@ -158,7 +159,7 @@ Residual risk after these mitigations (a malicious fork PR that passes maintaine ### Agent interaction model -Agents interact with validation tiers through skills (depends on ADR-012 for the skill model). The `validate-locally` skill and the two `mise` tasks it runs in the flow below are proposed here and do not exist yet: +Agents interact with validation tiers through skills (depends on ADR-012 for the skill model). The `validate-locally` skill and `mise run check:full` in the flow below are proposed here and do not exist yet; `mise run test:integration` exists (phase 2a): ``` Agent completes implementation @@ -180,16 +181,16 @@ The gap analysis dictates priority: | Priority | Investment | Impact | |----------|-----------|--------| | P0 | ~~Enforce Tier 1 as pre-push gate~~ **(largely done)** — test + security push gate is wired (prek `pre-push` hooks); remaining work is folding synth/docs-sync/drift into the gate | Eliminates "pushed without building" class of CI failures | -| P1 | `mise run test:integration` (Tier 2a — LocalStack) | Eliminates 60%+ of CI-only failures (AWS API contract mismatches) | +| P1 | ~~`mise run test:integration` (Tier 2a)~~ **(done as an advisory check)** — built on the AWS Emulator; remaining work is graduation to a required check (criteria under Design constraints) | Catches data-plane defects and defects in state shared between the agent and the handlers without a deployment: about one in twelve (10 of 120) of the recorded defects that passed unit tests and were found on a deployed stack. More than half of those 120 need real AWS and still do. It does not reduce CI-only failures: `build.yml` makes no AWS call | | P2 | Agent smoke test (Tier 2b) | Catches agent runtime regressions before PR | | P3 | Ephemeral stack deploy (Tier 2c) | Catches IAM/wiring issues that only surface in real deployment | | P4 | Full local sandbox (Tier 2d) | Production-equivalent local validation (long-term target) | ### Design constraints -- **Tier 2 must not require cloud credentials for basic operation** — agents running in isolation (MicroVM, CI runner) need to validate without AWS access. LocalStack/moto fills this. -- **Tier 2 must be optional until stable** — a failing Tier 2 should warn, not block, during build-out. Once stable, it becomes a gate. -- **Tier 2 must be cacheable** — container images, LocalStack state, and fixture repos should be cached between runs. An agent shouldn't rebuild the world every time. +- **Tier 2 must not require cloud credentials for basic operation** — agents running in isolation (MicroVM, CI runner) need to validate without AWS access. For phase 2a the AWS Emulator fills this: it needs Docker and no AWS account. Phase 2c is the exception and needs a real account. +- **Tier 2 must be optional until stable** — a failing Tier 2 should warn, not block, during build-out. Once stable, it becomes a gate. For phase 2a, stable means, measured over 30 days: every red run triaged; none of the last 100 pull-request and merge-queue runs red because of the emulator or the runner; p95 job duration under 5 minutes; at least one test per service in scope; the emulator pin never more than 14 days behind upstream. Then the job is added to the required checks of the `main` ruleset. +- **Tier 2 must be cacheable** — container images and fixture repos should be cached between runs (emulated state is in memory and is discarded on purpose). An agent shouldn't rebuild the world every time. - **No tier should duplicate work from a lower tier** — if Tier 0 checks formatting, Tier 1 does not re-check it. If Tier 1 runs unit tests, Tier 3 does not re-run them (it may run *additional* tests but not the same ones). ### Escape hatches @@ -217,14 +218,21 @@ Escape hatches must be explicit (noted in PR description, not silent). - (-) Pre-push gate adds 30–90s to every push (proposed mitigation: `mise run check:fast` alone for safe paths) - (!) LocalStack fidelity gaps must be documented — when Tier 2 passes but Tier 3 fails, document the divergence and add it to Tier 2's scope - (!) Tier 2 "optional until stable" phase must have a defined graduation criteria, or it stays optional forever +- (!) Phase 2a was built on the AWS Emulator, not LocalStack: the three LocalStack consequences above apply to it as written. Its known differences from AWS are kept in `scripts/aws-emulator/README.md`, and the graduation criteria asked for above are under Design constraints ## References - Issue #149 — implementation tracking for this ADR -- ADR-002 — bootstrap policies (Tier 2c validates IAM preflight locally) +- ADR-002 — bootstrap policies (Tier 2c validates the IAM preflight before a pull request, in a real AWS account) - ADR-008 — definition of done (tier requirements per DoD level) - ADR-012 (prerequisite) — operational knowledge stack; this ADR depends on 012's skill model for agent interaction with validation tiers - Current hooks: `.pre-commit-config.yaml` — the config file keeps the `pre-commit` name, but the runner is **prek** (pinned in `mise.toml` `[tools]`; `prek install --prepare-hooks` wires both `pre-commit` and `pre-push` stages). Implements Tier 0 (`pre-commit` stage) and the Tier 1 push gate (`pre-push` stage). - Current build: `mise.toml` root + package-level configs (Tier 1 implementation) -- LocalStack: https://localstack.cloud (candidate for Tier 2a) +- AWS Emulator: https://github.com/aws/aws-emulator (adopted for Tier 2a; the version is pinned in `scripts/aws-emulator/Dockerfile`) +- LocalStack: https://localstack.cloud (the candidate for Tier 2a when this ADR was written; not adopted, and not evaluated in depth) +- `docs/research/aws-emulator-local-tests.md` — the investigation behind phase 2a: what was built and measured, and what was not verified - Firecracker MicroVMs: https://firecracker-microvm.github.io (candidate for Tier 2d) + +## Changelog + +- 2026-11-15 — Phase 2a is implemented, on the AWS Emulator instead of LocalStack, as an advisory check (`mise run test:integration` and the `emulator` workflow). Replaced the estimate that it would eliminate "60%+ of CI-only failures" with what was measured, added the graduation criteria this ADR asks for, and stated that phase 2c needs a real AWS account because the emulator cannot show a missing permission (decision otherwise unchanged). diff --git a/docs/design/API_CONTRACT.md b/docs/design/API_CONTRACT.md index fe0e8a4e3..702097c18 100644 --- a/docs/design/API_CONTRACT.md +++ b/docs/design/API_CONTRACT.md @@ -263,7 +263,7 @@ Returns full details of a task. Users can only access their own tasks. | Field | Type | Description | |---|---|---| -| `category` | String | One of: `auth`, `network`, `concurrency`, `compute`, `agent`, `guardrail`, `config`, `timeout`, `unknown` | +| `category` | String | One of: `auth`, `network`, `concurrency`, `compute`, `agent`, `guardrail`, `config`, `timeout`, `blocked`, `unknown` | | `title` | String | Human-readable error title | | `description` | String | Detailed explanation of what went wrong | | `remedy` | String | Suggested action to resolve the error | @@ -273,13 +273,13 @@ Example for a failed task: ```json { - "error_message": "User concurrency limit reached", + "error_message": "Pre-flight check failed: REPO_NOT_FOUND_OR_NO_ACCESS — GitHub API returned HTTP 404 for acme/widgets", "error_classification": { - "category": "concurrency", - "title": "Concurrency limit reached", - "description": "The maximum number of concurrent tasks for this user has been reached.", - "remedy": "Wait for an active task to complete, cancel a running task, or ask an admin to increase the limit.", - "retryable": true + "category": "auth", + "title": "Repository not found or inaccessible", + "description": "The GitHub token cannot access the target repository. It may not exist or the token lacks visibility.", + "remedy": "Check that the repository name is correct and the configured PAT has access to it.", + "retryable": false } } ``` @@ -356,7 +356,7 @@ Returns the audit trail for a task: state transitions, hydration events, session **Query parameters:** `limit` (default 50, max 100), `next_token`. -**Event types:** `task_created`, `uploads_confirmed`, `attachment_blocked`, `admission_rejected`, `preflight_failed`, `hydration_started`, `hydration_complete`, `session_started`, `pr_created`, `task_completed`, `task_failed`, `task_cancelled`, `task_timed_out`. Custom blueprint steps emit `{step_name}_started`, `{step_name}_completed`, `{step_name}_failed`. (There is no `admission_passed` or `session_ended` event — admission success is implicit in the subsequent `hydration_started`, and session end is captured by the terminal event.) +**Event types:** `task_created`, `uploads_confirmed`, `attachment_blocked`, `admission_queued`, `queue_pickup`, `preflight_failed`, `hydration_started`, `hydration_complete`, `session_started`, `pr_created`, `task_completed`, `task_failed`, `task_cancelled`, `task_timed_out`. Custom blueprint steps emit `{step_name}_started`, `{step_name}_completed`, `{step_name}_failed`. (There is no `admission_passed` or `session_ended` event — admission success is implicit in the subsequent `hydration_started`, and session end is captured by the terminal event.) **Correlation envelope (#245):** each event optionally carries top-level `user_id`, `repo`, and `trace_id` (the agent's OTEL trace id) so the event stream joins to structured logs and X-Ray. Each field is present only when the event's source stamped it — `task_created` predates the envelope and carries none; events from `hydration_started` onward carry `user_id`/`repo`, and agent-emitted events additionally carry `trace_id`. Fields are omitted (not `null`) when absent. See [OBSERVABILITY.md](./OBSERVABILITY.md#correlation-envelope). @@ -571,10 +571,10 @@ There is no per-user request-rate or "tasks-per-hour" limiter on task creation. | Per-task nudge limit | Default 10/min | Per task (`POST /tasks/{id}/nudge`) | `429 RATE_LIMIT_EXCEEDED` | | Application rate limiter (`shared/rate-limit`) | Per-endpoint | Used by `approve`, `deny`, `pending`, `nudge`, `policies` and Linear webhook/fan-out paths — **not** task creation | `429 RATE_LIMIT_EXCEEDED` | -**Concurrency (not a rate limit).** Per-user concurrent task count is bounded (configurable, default 3-5). This is enforced by admission control, not by the create-task endpoint: +**Concurrency (not a rate limit).** Per-user concurrent task count is bounded (configurable, default 10). This is enforced by admission control, not by the create-task endpoint: - `POST /v1/tasks/{task_id}/confirm-uploads` rejects with `429 RATE_LIMIT_EXCEEDED` when the user is already at their concurrency limit. -- For the orchestrator admission path (the `SUBMITTED → HYDRATING` transition), exceeding the limit does not return an HTTP error — the task is already created. The orchestrator drives the task to `FAILED` with `error_message` "User concurrency limit reached" and emits an `admission_rejected` event. +- For the orchestrator admission path (the `SUBMITTED → HYDRATING` transition), exceeding the limit does not return an HTTP error — the task is already created. The orchestrator parks the task as `QUEUED` and emits an `admission_queued` event. The task is admitted, oldest first, as the user's slots free up (`queue_pickup`), and fails if it is still queued 24 hours after submission. **Monthly budget admission.** Task creation checks the current UTC-month estimated spend for the authenticated user and every Cognito group captured as a team. A configured hard-stop scope at or above 100% returns `429 BUDGET_EXCEEDED` before creating a new task. Alerts-only scopes continue. Same-user idempotent replays return their existing task before this check. @@ -624,3 +624,4 @@ List endpoints use token-based pagination (consistent with DynamoDB's `Exclusive - Pass `next_token` as query parameter for the next page - Tokens are short-lived and should not be stored - Results ordered by `created_at` descending (newest first) +- A page can hold fewer items than `limit`, or none, while `has_more` is `true`: a list that filters (tasks by `status` or `repo`, webhooks and API keys without the revoked ones) reads a bounded number of rows per request. Follow `next_token` until `has_more` is `false` diff --git a/docs/design/COST_MODEL.md b/docs/design/COST_MODEL.md index 501d3f2df..23dd1f20a 100644 --- a/docs/design/COST_MODEL.md +++ b/docs/design/COST_MODEL.md @@ -105,7 +105,7 @@ For **AWS-native** chargeback of Bedrock spend (Cost Explorer / CUR 2.0 by `user | Monthly user/team warning | Estimated terminal-task cost rollup | CloudWatch/SNS at 80% and 100% | | Monthly user/team hard stop | Admission check at 100% | Disabled per scope unless `--hard-stop` is set | | Session timeout | Orchestrator timeout | 9 hours | -| Concurrency limit | Per-user atomic counter | 3 concurrent tasks | +| Concurrency limit | Per-user atomic counter | 10 concurrent tasks | | System concurrency | System-wide counter | Account-level AgentCore quota | Monthly budgets use UTC calendar months and the same estimated `cost_usd` stored on terminal tasks. The TaskTable stream consumer transactionally increments the user and captured Cognito-team rollups and writes a task marker so duplicate stream delivery cannot double count. Admission checks every configured applicable scope; any scope at 100% with hard stop enabled rejects a new task. In-flight tasks continue and can overshoot because their final cost is unknown until termination. diff --git a/docs/design/INTERACTIVE_AGENTS.md b/docs/design/INTERACTIVE_AGENTS.md index a76fab596..31642b1d2 100644 --- a/docs/design/INTERACTIVE_AGENTS.md +++ b/docs/design/INTERACTIVE_AGENTS.md @@ -174,7 +174,7 @@ A single AgentCore Runtime, invoked via `bedrock-agentcore:InvokeAgentRuntime` w Durable-execution Lambda that owns the task lifecycle from submission to terminal state. Responsibilities: -- **Admission control** — atomic DDB conditional update on `UserConcurrencyTable` (`active_count < max`); reject with 429 if over quota. +- **Admission control** — atomic DDB conditional update on `UserConcurrencyTable` (`active_count < max`); a task over the limit is parked as `QUEUED` (#441). - **State transition** `SUBMITTED → HYDRATING → RUNNING → FINALIZING → terminal`. - **Invocation** — calls `InvokeAgentRuntime` with SigV4. - **Poll loop** — waits for the agent to land a terminal status in `TaskTable`; enforces heartbeat watchdog; transitions to `FAILED` if the container dies. @@ -197,7 +197,7 @@ The durable event spine. PK = `task_id`, SK = `event_id` (ULID), TTL enabled, ** Writers: - `ProgressWriter` (inside the agent container) — per tool call, per turn, per milestone, cost updates, errors. -- `OrchestratorFn` — `task_created`, `hydration_*`, `session_started`, `task_*`, `preflight_*`, `admission_rejected`, `guardrail_blocked`. +- `OrchestratorFn` — `task_created`, `hydration_*`, `session_started`, `task_*`, `preflight_*`, `admission_queued`, `guardrail_blocked`. - Cancel/reconciler handlers — `task_cancelled`, `task_stranded`. Readers: diff --git a/docs/design/OBSERVABILITY.md b/docs/design/OBSERVABILITY.md index 0d67bccde..b7e70cd84 100644 --- a/docs/design/OBSERVABILITY.md +++ b/docs/design/OBSERVABILITY.md @@ -92,11 +92,11 @@ The platform tracks four categories of signals, each serving different consumers Every task emits structured events at each state transition, stored in the TaskEvents table: -- State transitions: `task_created`, `admission_rejected`, `uploads_confirmed`, `hydration_started`, `hydration_complete`, `session_started`, `pr_created`, `task_completed`, `task_failed`, `task_cancelled`, `task_timed_out` +- State transitions: `task_created`, `admission_queued`, `queue_pickup`, `uploads_confirmed`, `hydration_started`, `hydration_complete`, `session_started`, `pr_created`, `task_completed`, `task_failed`, `task_cancelled`, `task_timed_out` - Blueprint custom step events: `{step_name}_started`, `{step_name}_completed`, `{step_name}_failed` - Guardrail events: `guardrail_blocked` (content blocked during hydration) -All events carry `task_id` and `user_id` for filtering. +All events carry `task_id` for filtering; the events the orchestrator and the agent write from `hydration_started` onward also carry `user_id` (see the coverage notes above). ### Agent execution diff --git a/docs/design/ORCHESTRATOR.md b/docs/design/ORCHESTRATOR.md index c66858c72..23a8965c1 100644 --- a/docs/design/ORCHESTRATOR.md +++ b/docs/design/ORCHESTRATOR.md @@ -338,7 +338,7 @@ Each task runs in its own isolated compute session with no shared mutable state |---|---|---| | `invoke_agent_runtime` TPS | 25 per agent/account | AgentCore quota (adjustable) | | Concurrent sessions | Account-level limit | AgentCore quota | -| Per-user concurrency | Configurable (default 3-5) | Platform config | +| Per-user concurrency | Configurable (default 10) | Platform config | | System-wide max tasks | Configurable | Bounded by selected-backend quotas | ### Counter management @@ -425,14 +425,14 @@ Three DynamoDB tables back the orchestrator: one for task state, one for the aud | `model_id` | String? | Foundation model ID | | `prompt_version` | String | System prompt hash for evaluation correlation | | `blueprint_config` | Map? | Snapshot of `RepoConfig` at task creation | -| `cost_usd` | Number? | Agent cost from SDK | -| `duration_s` | Number? | Total duration | +| `cost_usd` | String? | Agent cost from SDK, written by the agent as a string | +| `duration_s` | String? | Total duration in seconds, written by the agent as a string | | `ttl` | Number? | DynamoDB TTL (default: created_at + 90 days) | | `created_at` / `updated_at` | String | ISO 8601 timestamps | -> **Derived field:** `error_classification` is not stored in DynamoDB. It is computed at API response time by passing `error_message` through the runtime error classifier (`error-classifier.ts`). This returns a structured object with `category` (auth/network/concurrency/compute/agent/guardrail/config/timeout/unknown), `title`, `description`, `remedy`, and `retryable` flag. The derived-field pattern means classifier updates take effect immediately for all existing tasks without data migration. +> **Derived field:** `error_classification` is not stored in DynamoDB. It is computed at API response time by passing `error_message` through the runtime error classifier (`error-classifier.ts`). This returns a structured object with `category` (auth/network/concurrency/compute/agent/guardrail/config/timeout/blocked/unknown), `title`, `description`, `remedy`, and `retryable` flag. The derived-field pattern means classifier updates take effect immediately for all existing tasks without data migration. -**GSIs:** `UserStatusIndex` (PK: `user_id`, SK: `status#created_at`), `StatusIndex` (PK: `status`, SK: `created_at`), `IdempotencyIndex` (PK: `idempotency_key`, sparse). +**GSIs:** `UserStatusIndex` (PK: `user_id`, SK: `status#created_at`), `UserCreatedAtIndex` (PK: `user_id`, SK: `created_at`; the task list, newest first), `StatusIndex` (PK: `status`, SK: `created_at`), `IdempotencyIndex` (PK: `idempotency_key`, sparse), `LinearIssueIndex` (PK: `linear_issue_id`, SK: `created_at`, sparse), `JiraIssueIndex` (PK: `jira_issue_identity`, SK: `created_at`, sparse). ### TaskEvents table diff --git a/docs/design/SECURITY.md b/docs/design/SECURITY.md index 7bf67d4e5..55e7a1959 100644 --- a/docs/design/SECURITY.md +++ b/docs/design/SECURITY.md @@ -151,7 +151,7 @@ flowchart LR | Submission | Input validation | `validation.ts`, `create-task-core.ts` | HTTP error only | | Submission | Repo onboarding gate | `repo-config.ts` | HTTP error only | | Submission | Guardrail screening | `create-task-core.ts` | HTTP error only | -| Admission | Concurrency limit | `orchestrator.ts` | `admission_rejected` event | +| Admission | Concurrency limit | `orchestrator.ts` | `admission_queued` event | | Pre-flight | GitHub access, PAT permissions, PR access | `preflight.ts` | `preflight_failed` event | | Hydration | Guardrail prompt screening | `context-hydration.ts` | `guardrail_blocked` event | | Hydration | Budget/quota resolution | `orchestrator.ts` | Persisted on task record | diff --git a/docs/guides/DEPLOYMENT_GUIDE.md b/docs/guides/DEPLOYMENT_GUIDE.md index ad69ce770..8b0d3e5fe 100644 --- a/docs/guides/DEPLOYMENT_GUIDE.md +++ b/docs/guides/DEPLOYMENT_GUIDE.md @@ -453,6 +453,28 @@ STACK_NAME= mise //cdk:preflight:log-delivery -- --check-only A bare `cdk deploy` (no mise, no pipeline) does **not** run the preflight. On that path, or after the rollback above, run the check command shown under *Affects* and then follow the manual steps in [Observability — AgentCore log delivery](../design/OBSERVABILITY.md#agentcore-log-delivery). +### Task list keeps its old order while a new index is built (#51) + +**Affects:** an existing stack on its first deploy of a version that adds `UserCreatedAtIndex` to the task table. A fresh stack is not affected. + +**Symptom:** For a while after the deploy, `GET /v1/tasks` (`bgagent list`, the console's task list) still returns tasks grouped by status instead of newest first, and the `ListTasksFn` log has a `UserCreatedAtIndex is not ACTIVE` warning for each request that starts a list. + +**Root cause:** CloudFormation starts creating the index and continues with the update without waiting for it, and DynamoDB does not allow a query on an index until it is `ACTIVE`. The list handler therefore asks DynamoDB for the status of the index, and reads `UserStatusIndex`, as it did before, until the answer is `ACTIVE`. This has been tested against an emulated DynamoDB and not observed on a deployed stack; how long the build takes on a given table has not been measured. + +**Resolution:** None needed. The list is newest first once the index is `ACTIVE`: + +```bash +aws dynamodb describe-table --table-name \ + --query "Table.GlobalSecondaryIndexes[?IndexName=='UserCreatedAtIndex'].IndexStatus" +``` + +Two CloudFormation limits apply to the same update. It creates one index per update, so each index a stack has not yet created (`JiraIssueIndex`, `LinearIssueIndex`, this one) needs a deploy of its own, in the order the versions added them, each once the index of the deploy before it is `ACTIVE`. And AWS recommends that an update which adds an index changes nothing else, which this version cannot follow: if the update rolls back while the index is being created, CloudFormation leaves the index in place. Delete it, wait until the status command above prints `[]`, then deploy again. DynamoDB refuses the delete in the first phase of the build; if it does, try again after a minute: + +```bash +aws dynamodb update-table --table-name \ + --global-secondary-index-updates '[{"Delete": {"IndexName": "UserCreatedAtIndex"}}]' +``` + ### AgentCore unsupported Availability Zones **Affects:** Fresh deploys in accounts whose default Availability Zones don't line up with the zones AgentCore supports for the region. diff --git a/docs/guides/QUICK_START.mdx b/docs/guides/QUICK_START.mdx index 47d09d67d..a32fb3a11 100644 --- a/docs/guides/QUICK_START.mdx +++ b/docs/guides/QUICK_START.mdx @@ -194,7 +194,7 @@ If a task fails immediately with text like the model is **not available on your ## Step 4 - Store the GitHub token -The agent reads the GitHub PAT from **AWS Secrets Manager** at runtime. The CDK stack created an empty secret for you - now you need to put your token value in it. Replace `ghp_your_token_here` with the actual token from Step 2. Make sure `REGION` matches where you deployed - if it is empty, the AWS CLI builds a malformed endpoint URL and fails silently. +The agent reads the GitHub PAT from **AWS Secrets Manager** at runtime. The CDK stack created a secret with a generated placeholder value for you - now you need to put your token value in it. Replace `ghp_your_token_here` with the actual token from Step 2. Make sure `REGION` matches where you deployed - if it is empty, the AWS CLI builds a malformed endpoint URL and fails silently. diff --git a/docs/guides/USER_GUIDE.md b/docs/guides/USER_GUIDE.md index 1c2c72a60..1e77c70a2 100644 --- a/docs/guides/USER_GUIDE.md +++ b/docs/guides/USER_GUIDE.md @@ -1065,6 +1065,9 @@ flowchart LR H --> X S --> F S --> X + S <--> Q[QUEUED] + Q --> F + Q --> X ``` The orchestrator uses Lambda Durable Functions to manage the lifecycle durably - long-running tasks (up to 9 hours) survive transient failures and Lambda timeouts. The agent commits work regularly, so partial progress is never lost. @@ -1073,12 +1076,13 @@ The orchestrator uses Lambda Durable Functions to manage the lifecycle durably - |---|---| | `PENDING_UPLOADS` | Initial state while presigned attachment uploads are pending confirmation | | `SUBMITTED` | Task accepted; orchestrator invoked asynchronously | +| `QUEUED` | You are at your concurrency limit; the task waits for a free slot and starts automatically. See [Concurrency limits](#concurrency-limits). | | `HYDRATING` | Orchestrator passed admission control; assembling the agent payload | | `RUNNING` | Agent session started and actively working on the task | | `AWAITING_APPROVAL` | Agent paused at a Cedar HITL gate; waiting for your `approve` or `deny` decision. See [Approval gates](#approval-gates-cedar-hitl). | | `FINALIZING` | Agent session ended; task is wrapping up (post-session hooks / PR finalization) before reaching a terminal state | | `COMPLETED` | Agent finished and created a PR (or determined no changes were needed) | -| `FAILED` | Something went wrong - pre-flight check failed, concurrency limit reached, guardrail blocked the content, or the agent encountered an error | +| `FAILED` | Something went wrong - pre-flight check failed, guardrail blocked the content, the task stayed queued for more than 24 hours, or the agent encountered an error | | `CANCELLED` | Task was cancelled by the user | | `TIMED_OUT` | Task exceeded the maximum allowed duration (~8 hours, the AgentCore max session duration; the orchestrator safety-net timer is slightly longer) | @@ -1088,7 +1092,7 @@ Task records in terminal states are automatically deleted after 90 days (configu ### Concurrency limits -Each user can run up to 3 tasks concurrently by default (configurable via `maxConcurrentTasksPerUser` on the `TaskOrchestrator` CDK construct). If you exceed the limit, the task fails with a concurrency message. Wait for an active task to complete, or cancel one, then retry. +Each user can run up to 10 tasks concurrently. If you exceed the limit, the task is queued (`QUEUED`) instead of failing: it starts automatically, oldest first, as your active tasks finish or are cancelled, and fails only if it is still queued 24 hours after submission. A task with a file attachment over 500 KB is checked when you confirm its uploads: if your slots are all in use at that moment, the confirmation is refused with `429 RATE_LIMIT_EXCEEDED`. Through the API, confirm again once a slot is free, within 30 minutes of submitting; after that the unconfirmed task is cancelled. `bgagent submit` does not retry the confirmation: submit the task again. There is no system-wide cap - the theoretical maximum is `number_of_users * per_user_limit`. The hard ceiling is the AgentCore concurrent sessions quota for your AWS account (check the [AWS Service Quotas console](https://console.aws.amazon.com/servicequotas/) for Bedrock AgentCore in your region). @@ -1103,7 +1107,7 @@ curl "$API_URL/tasks//events" -H "Authorization: $TOKEN" Available events: - **Lifecycle** - `task_created`, `session_started`, `task_completed`, `task_failed`, `task_cancelled`, `task_timed_out` -- **Orchestration** - `admission_rejected`, `hydration_started`, `hydration_complete` +- **Orchestration** - `admission_queued`, `queue_pickup`, `hydration_started`, `hydration_complete` - **Checks** - `preflight_failed`, `guardrail_blocked` - **Interactive** - `nudge_acknowledged`, `agent_milestone` - **Approvals (Cedar HITL)** - `approval_requested`, `approval_recorded`, `approval_timed_out` @@ -1211,4 +1215,4 @@ Every task consumes model tokens, compute time, and GitHub API calls. Setting li - **Content screening** - Task descriptions and PR context are screened by Bedrock Guardrails for prompt injection. If your task is unexpectedly blocked, check the task events for a `guardrail_blocked` entry and revise your description. - **Idempotency** - If you're creating tasks via the API and might retry on network errors, include an `Idempotency-Key` header to prevent duplicate tasks. -- **Concurrency** - You share a per-user concurrency limit (default: 3 tasks). If you hit the limit, wait for a task to finish or cancel one you no longer need before submitting more. +- **Concurrency** - You share a per-user concurrency limit (default: 10 tasks). If you hit the limit, new tasks are queued and start as active ones finish; cancel one you no longer need to free a slot. diff --git a/docs/research/aws-emulator-local-tests.md b/docs/research/aws-emulator-local-tests.md new file mode 100644 index 000000000..33643ebd8 --- /dev/null +++ b/docs/research/aws-emulator-local-tests.md @@ -0,0 +1,487 @@ +# AWS Emulator for local and CI tests + +**Status:** adopted as an advisory check. This is the investigation as it was handed over on 2026-11-15: unless a sentence says otherwise, it describes the proof of concept (then uncommitted, in a worktree of this branch) and `main` (`c8fcdb08`) as they stood that day. What was decided and done afterwards is in [Outcome](#outcome). The rules for tests in the tier and the list of known differences from AWS are maintained in [`scripts/aws-emulator/README.md`](../../scripts/aws-emulator/README.md), not here. +**Date:** 2026-11-15 +**Emulator version examined:** 1.0.385 (`aws/aws-emulator`, commit `813af48`) + +## Summary + +Adopt the [AWS Emulator](https://github.com/aws/aws-emulator) as ADR-013's Tier 2a (container integration tests, between the local unit build and remote CI), which the ADR marks "does not exist". Use it in one way: ABCA's real handler, CLI and agent code runs in its normal test runner, and only its AWS SDK calls go to an emulator on loopback. Run it with `mise run test:integration` and as an advisory check on every pull request. + +What the investigation established: + +| Question | Answer | +|---|---| +| Does ABCA code run against it? | Yes, with no change to product code. The proof of concept has 58 tests across `cdk`, `cli` and `agent` and runs in about 24 seconds on a laptop, emulator start and stop included. | +| Does it find things the mocked suites cannot? | Yes. It reproduced open issues #51 and #1003, and execution on it confirmed three defects around approval gates that no issue tracks (see [Defects found](#defects-found-during-the-investigation)). | +| How much of ABCA's defect history would it have caught? | About one in twelve of the 120 recorded defects that passed unit tests and were found on a live stack (10 on a second reader's count, 13 on the first). More than half needed real AWS and still would. | +| Can it replace the real-AWS integ smoke? | No. IAM, deployment of the full platform, and the AgentCore runtime are outside what it can show. | +| What does it cost? | Docker wherever the tier runs, a 1.08 GB image built once per version in 16 seconds, about 390 lines of tooling (the proof of concept adds about 2,200 lines of tests and harness), an estimated 3 minutes per pull request in CI, and a pinned version that someone has to move. | +| What is not verified? | The workflow has never run on GitHub, the suites have run on macOS only, and nothing was compared with real AWS (see [Costs and risks](#costs-and-risks)). | + +Three things this proposal does not recommend: deploying stacks to the emulator as a test tier, making the check required from day one, and running handlers inside the emulator's own Lambda. The reasons are in [Deploying to the emulator](#deploying-to-the-emulator) and [Rollout](#rollout). + +## Outcome + +The owner read this report on 2026-11-15 and decided: adopt the tier as an advisory check, implement it on one branch for one pull request, fix the defects below that no open pull request already addresses, and add the workflow of Appendix A. + +The main things that pull request adds to the proof of concept described in the rest of this document: + +- `.github/workflows/emulator.yml`, exactly as in [Appendix A](#appendix-a-workflow). +- Tests of the guard's refusals in the unit suites, so that a guard that stops refusing fails the required build: `cdk/test/scripts/aws-emulator-guard.test.ts` and `agent/tests/test_emulator_guard.py`. +- `scripts/aws-emulator/README.md` (how to run the tier, its rules, the known differences), which also covers what the README criterion of issue #61 asks for, at another path; lines in the four `AGENTS.md` guides; and the amendment of ADR-013. +- The fixes in the two tables below. Each fix that changes behaviour has a unit test that fails without it (the one about numbers stored as strings changes comments and types only, and is checked by the compiler), and where an emulator test witnessed the defect it is now a plain test. The emulator suites then hold 12 `cdk` tests (2 still `test.failing`, both waiting for PR #1009), 7 `cli` tests (1 `test.failing`, an emulator gap, until the pin moved: see the end of this section) and 43 agent tests. + +| Defect (details under [Defects found](#defects-found-during-the-investigation)) | Outcome | +|---|---| +| The stranded-approval sweep measures from the start of `RUNNING` | Fixed: the agent's two approval transitions write `status_created_at`. The TypeScript writer that open PR #1013 adds needs the same attribute | +| A task resumed after a long approval wait is failed as "Agent session lost" | Left to open PR #904 | +| The concurrency reconciler counts four statuses; #1003 | Left to open PR #1009 | +| A never-configured GitHub token secret is reported as configured | Fixed in the CLI: a token is recognised by GitHub's formats, and `github set-webhook-secret` no longer guesses whether a secret is set | +| A session role that cannot be assumed does not abort the task | Fixed: the role is assumed when the session is first built, so the task stops before any work. The price is that an STS failure at task start that outlasts the SDK's retries now fails the task. When the role can never be assumed the user still reads "Agent session lost", because the agent has no credentials to record the reason | +| The trajectory writer never retries stream creation | Fixed | +| #51: list order and the empty filtered page | Fixed: a new index `UserCreatedAtIndex` on the task table, read until the page is full. The next deployment creates and backfills the index; on an existing stack the handler asks DynamoDB for the status of the new index and reads the old one, in its old order, until that status is `ACTIVE` (see "Known deployment issues" in the deployment guide) | +| `integ.yml` is blocked by its own concurrency group | Fixed on `main`: #1035 moved the group from the workflow to the `integ` job, and #1047 keyed it by pull request, so that runs of different pull requests no longer cancel each other (#1046). `integ.yml` and ADR-013 now also say that `integ-smoke` is not a required check. Whether `integ-smoke` becomes required is a ruleset setting and is open | +| `upgrade-main` has failed since 2026-08-19 | Not a defect of a tracked file: the token in the repository secret `AUTOMATION_GITHUB_TOKEN` stopped being accepted. Open; it needs a new token | +| The Slack cancel button writes less than `cancel-task` | Fixed: it writes `completed_at` and `status_created_at` | +| `task_cancelled` is recorded twice | Left: both writers are needed and every consumer tolerates the repeat | +| `bgagent ops stuck-tasks` ages tasks by creation time | Fixed: it ages by time in the current status, as the reconciler does | +| Numbers stored as strings while the comments blame the SDK | Fixed: `numeric.ts`, `TaskRecord` and the comments that cite them say what is stored, in the handlers and in their tests. One comment in `fanout-task-events.ts` is left as it is: it sits in a block that open PR #991 moves, and changing it here would make that pull request conflict there | +| The agent unit suite depends on test order | Fixed | + +Found while fixing, and not listed further down: + +| Defect | Outcome | +|---|---| +| `GET /v1/webhooks` applies its filter after `Limit`, as #51 did | Fixed | +| The confirm-uploads Lambda never receives the per-user cap, and admits against a fallback of 3 where the stack sets 10 | Fixed. Until open PR #1009, a confirmed attachment task still holds two seats, so the limit met on that path stays below the cap | +| The presign-failure path of `create-task` fails a task without `completed_at`, a matching `status_created_at` or a `ttl` | Fixed | +| `bgagent ops concurrency` prints a default limit of 3 where the stack deploys 10, and six documents said 3 or "3-5" | Fixed. The user guide and the API contract also said that a task over the limit fails; since #441 it is queued, and they now say so. Four more documents named the event that #441 removed (`admission_rejected`), and two examples showed a task failed at the limit; they are corrected too | +| The `integ` job's command has been unrunnable since #567: it passes `cdk deploy` arguments to `integ-runner`, which exits 1 | Fixed: the job runs `mise //cdk:integ` with nothing after it, and a unit test fails when the workflow passes the task an argument. The job has not run with the fix: it needs the `deploy` approval, and until this merges an approved run still uses `main`'s copy of the workflow | +| `auto-approve` cannot approve the pull requests `upgrade-main` opens, because one token does both | Open | +| `upgrade-main.yml` reports a patch that `git apply` refuses as "Empty patch. Skipping.", and the run ends green | Open | +| `GET /v1/pending` lists an approval request whose window has passed until DynamoDB deletes the row | Open, tracked as #1043; PR #904 changes how the wait works | +| Comments and a test title describe the Linear webhook dedup as 60 seconds on issue and action; the handler keeps eight hours on the delivery's id (an issue or a comment), action and timestamp | Fixed (comments only) | +| A task that times out in the admission queue is shown as "Unexpected error": its message says "concurrency slot" and the classifier looks for "concurrency limit" | Open. Whether it should be classed as a concurrency error, which is retryable, is a product decision | +| `AgentStack` passes its per-user cap to the orchestrator and the reconcilers but not to `TaskApi` or `AdmissionQueuePickup`, which use a default of their own | Open, tracked as #1044. No effect while the constant and both defaults are 10 | +| Two more writers of a terminal status omit an attribute: `reconcile-stranded-tasks.ts` writes no `ttl`, `confirm-uploads.ts` no `completed_at` | Fixed: each write sets the missing attribute. Open PR #1009 changes both files, but neither write | + +PR #1035 merged on 2026-11-16 (UTC), after the hand-over, and the pull request was rebased onto it. Where the rest of this document calls #1035 open, or describes `dead-code-pr.yml`, it describes the day of the hand-over: #1035 replaced that workflow with a zero-tolerance dead-code check in the build. The pull request carries the seven `knip.json` entries that [Fit with pull request #1035](#fit-with-pull-request-1035) found it would need, and the mise version that every workflow which installs mise now pins, in `emulator.yml` and in Appendix A. + +What [Costs and risks](#costs-and-risks) lists as not verified still was when the pull request was opened, with three exceptions: + +- The tier has since run on Linux. On arm64, in an Ubuntu 24.04 container with its own Docker daemon, `mise run test:integration` built the image through `emulator.sh up`, passed the three suites and stopped the emulator, four runs out of four, and the two guard suites passed there as well. These runs were made before the rebase onto #1035; the rebased tree had then run on macOS only. The `linux/amd64` package was built into an image, and the three suites passed against that emulator under emulation. No test process had run on x86_64, and the workflow had not run on GitHub. +- The pull request is rebased onto #1035, and `mise run build` passes there with the gates #1035 added, which this investigation had only simulated one by one. +- A red check that is not required does not hold the merge queue: `dead-code-pr` failed on the merge groups of #664 and #665 on 2026-08-12, and both merged. + +After the pull request was opened: + +- Its workflow ran on GitHub for the first time and passed: a GitHub-hosted x86_64 runner built the image and ran the 62 tests, in three minutes for the job. That is the first test process on x86_64 and the first run of the workflow. +- The pin moved from 1.0.385 to 1.0.481, the second release published after it. The suites showed two changes, both in Cognito and both made by release 1.0.471: `RespondToAuthChallenge` for `NEW_PASSWORD_REQUIRED` is implemented, so the `cli` test of the first sign-in is a plain test and no `test.failing` waits for an emulator gap; and the `iss` claim of a token names the emulator again, as it did on 1.0.367. The README's table of differences and its lists of what does not work were then probed again on both releases. More had changed with no test to show it: `UpdateRegistryRecordStatus` is implemented, the four agent-registry answers parse in the JavaScript SDK, `DeleteRegistry` refuses a registry that holds records, a write that changes nothing emits no stream record, fewer malformed expressions are accepted, and other containers can reach the ports the emulator opens for resource endpoints. That table and those lists are current for 1.0.481; where this document describes the emulator, it describes 1.0.385. When the pin moved, 1.0.481 had run on macOS only. + +## What the emulator is + +An AWS-published local emulator of the AWS APIs: one Rust process that serves every service on a single HTTPS endpoint. The points that matter for this proposal: + +- **Distribution.** Signed `.deb` and `.rpm` packages for Linux on x86_64 and aarch64. AWS publishes no container image; on macOS it runs in Docker from a short Dockerfile. +- **Wire contract.** HTTPS on loopback with a certificate created at each start, and SigV4 signatures required with credentials created at each start. Both SDKs ABCA uses reach it through environment variables alone (`AWS_ENDPOINT_URL`, a credentials file, a CA bundle). +- **State.** In memory. There is no reset call; restarting is the reset. Start to healthy takes under a second and an idle instance uses about 180 MiB. +- **Unimplemented operations are explicit.** They answer HTTP 501 `NotImplemented` instead of an empty success. Two other kinds of gap are silent: four agent-registry operations return bodies the JavaScript SDK cannot parse, and four CloudFormation resource types report `CREATE_COMPLETE` and create nothing (see [Deploying to the emulator](#deploying-to-the-emulator)). +- **Maturity.** Very young. Its first GitHub release is dated 2026-11-07 and its first issue 2026-11-11; three days after that it had 417 open issues. There were 30 releases between 2026-11-07 and 2026-11-14, nine of them on the last day. +- **Stated limits.** AWS says not to use it to test security, that one instance is one account and one Region, and that fidelity is strongest for control-plane APIs. + +The alternatives ADR-013 names were not evaluated in depth. LocalStack's documentation says an auth token is mandatory to start its container, which means a CI secret and no runs for fork pull requests. moto has a standalone server mode that a Node process can also use and is the mature community option. DynamoDB Local, which the repository already uses for local agent runs, covers DynamoDB only. + +## What was built and measured + +The proof of concept is in the worktree and runs with one command. Every suite uses real product code and no SDK mock. + +| Suite | What runs for real | Tests | Time | +|---|---|---|---| +| `cdk/test/emulator` | The `create-task`, `get-task`, `list-tasks`, `cancel-task`, `get-task-events` and `reconcile-concurrency` handlers and the orchestrator's admission and finalize functions, on tables created from the CDK table constructs | 11, of which 4 are known-defect witnesses (jest `test.failing`: the test states the correct behavior and is green only while it still fails) | 5 s | +| `cli/test/emulator` | `configure --stack-name`, login, token refresh and change-password against a Cognito pool created through emulated CloudFormation. The fixture stack is written by hand to match the `TaskApi` construct as it is today | 5, of which 1 is a `test.failing` that marks an emulator gap | 2 s | +| `agent/tests_emulator` | Progress events, trace upload, secret resolution, CloudWatch Logs writes, the tenant-scoped session (a real `AssumeRole` with session tags), the approval transactions, and the round trip issue #61 asks for: the Python agent uploads a trace, the TypeScript `get-trace-url` handler presigns it, the real `bgagent trace download` fetches and gunzips it. The CLI runs in API-key mode against a stand-in for API Gateway and its authorizer, so its login path is not part of the round trip | 42 | 12 s | + +How this was checked. The investigation was run by AI agents in three rounds: investigators built the suites and the probes, verifiers repeated each claim with scripts of their own, and reviewers checked the final tree and this document. Everywhere else in this document, "agent" means ABCA's coding agent. Verifiers ran the first version of each suite between 16 and 23 times on fresh instances, serially, in parallel, in random order and with three sessions sharing one emulator, with no failure. The suites were then restructured twice in response to verifier and reviewer findings (see [Fit with pull request #1035](#fit-with-pull-request-1035) and [Keeping the tier away from real AWS](#keeping-the-tier-away-from-real-aws)). On the final version `mise run test:integration` passed five times in a row (21.6 to 25.2 seconds each) with a scratch state directory, and again with no overrides from a login shell that exports a real AWS profile. Each `test.failing` was run once as a plain `test`: the four `cdk` ones fail on their final assertion, and the `cli` one fails at the 501 it documents. The numbers that shape the design: + +- A new DynamoDB table is unusable for a fixed 3.0 seconds (a constant in the emulator, not configurable). Tables created together share one wait, so the cost is 3 seconds per test file, which is about 70% of a file's run time. +- One DynamoDB call from jest to the emulator in Docker on macOS takes about 2 ms. +- The round trip for issue #61 takes 6.8 seconds for six tests. A change to the handler alone (adding `ResponseContentEncoding: 'gzip'` to the presigned request) passes the handler's 25 unit tests and the agent's trace tests and fails three round-trip tests. + +Known limits of the proof of concept itself: + +- The agent suite's table key schemas and session-role policy are copied by hand from the CDK constructs. They match today for what the tests use: the three key schemas, and the DynamoDB, trace and artifact statements of the session role. The construct's attachment-read and Bedrock statements are not mirrored, and the test role trusts the account root where the construct trusts the compute role. Nothing fails if a construct changes. +- Rule 1 below (rows come from the real writer) is not followed everywhere. Besides those copies and the CLI's hand-written fixture stack, three kinds of row are written by the tests themselves: the repo row `create-task` gates on (`task-api.emulator.ts`), the `AWAITING_APPROVAL` status in the reconciler witness (`concurrency-seats.emulator.ts`), and every task row in the agent suite. +- `concurrent cancels` in `task-api.emulator.ts` is an outcome test. Depending on timing a losing cancel is refused by the handler's read or by its conditional write, and the test passes either way, so it cannot detect a missing condition. `racing admissions` in `concurrency-seats.emulator.ts` can. +- The agent test of the approval transition passes over two of the defects listed below, because its task row has two attributes and its tables have no indexes. +- The agent suite inherits agent variables from the calling shell. With `AGENT_SESSION_ROLE_ARN` exported, tests that expect the unscoped path fail (seen on an earlier version of the suite); the unit conftest clears 19 such variables and this suite clears none. + +## What it is worth + +### Against ABCA's own history + +One investigator built a ledger of 120 defects whose own record (commit body, issue or pull request) says they passed unit tests and were found on a deployed stack. A second reader independently re-classified 48 of them, including every one counted in favor of the emulator, and agreed on 42. The table gives the second reader's tally; the first counted 13 in the top row. + +| Where the defect could have been caught | Count | Share | +|---|---|---| +| An emulator-backed test (data-plane behavior, or state shared between the Python agent and the TypeScript handlers) | 10 | 8% | +| A deployment to the emulator | 2 | 2% | +| Only real AWS: IAM and bootstrap policies (21), Lambda, AgentCore and MicroVM runtime behavior (22), CloudFormation deployment, model behavior, service quirks | 62 | 52% | +| Only a real third party or the real container image | 9 | 8% | +| A unit or synth test | 37 | 31% | + +Three cautions. The most generous reading of the same ledger gives 18 of 120. The 120 are a selection, not a census: six of the source commits contain at least twelve more live-found defects that are not in the ledger, none of them catchable on an emulator, so the true share is somewhat lower. And "would have caught" assumes someone had written the test that drives the real code path. + +The catchable defects share a profile: they are silent, and they recur. A filter applied after `Limit` appeared five times between April and November (#51, still open; #579; #681; #831; #987). Approval gates that denied everything, a workspace reported as not onboarded, and webhooks that answered 401 forever are in the same group. + +### Against the CI record + +ADR-013 (status: proposed) says a Tier 2a would eliminate "60%+ of CI-only failures (AWS API contract mismatches)". The record does not support that sentence. `build.yml` has no credentials and makes no AWS call. Of the 62 failed build logs that were read (all 50 human-authored ones still available, and 12 Dependabot ones), none shows a request to AWS; the failures are unit tests, type checks and lint. Thirty-one of them do show agent unit tests reaching the boto3 CloudWatch Logs client and stopping at `NoRegionError`: the build makes no AWS call because the runner has no Region or credentials, not because the unit suite is hermetic. + +The comparison that matters is with the real-AWS integ smoke, and the record there is this: its test step has executed once in CI, on 2026-07-07, and passed. Since then `integ.yml` has been blocked by its own workflow-level concurrency group: a run waiting for `deploy` environment approval holds the group, and each newer run is cancelled in the queue. Between 2026-07-07 and 2026-11-15 the group was held by an approval wait for 122 of 130 days and 1,194 of 1,241 runs were cancelled, all but one before any job started, so not even the green "skipped" status is posted. One pull request that changes `cdk/` and `agent/` (#909) merged with no `integ-smoke` status on its head, and `integ-smoke` is not among the required status checks. In practice the emulator tier would not run before the integ tests; it would be the only automated check of AWS behavior on a pull request. + +### Demand that already exists in the repository + +- Three open pull requests (#1009, #1013, #904) each add a suite that needs a real conditional-write engine, gated on a DynamoDB Local endpoint. On `main` nothing provides one, so they skip or fail in CI. #904 itself adds a pinned `amazon/dynamodb-local` service container to the `build` job and hands its endpoint to the build step, and #1009's description relies on that. +- Hand-written in-memory DynamoDB fakes, about 300 lines in `cdk/test/integration` (two files) and one handler test. They match conditions by substring, ignore `Limit` and filters, and return whole items from every index. One of them, in `orchestration-e2e.test.ts`, drops the conditional claim write (`child_status = :releasing`) that the child-release path in `orchestration-release.ts` relies on to release a child once, so in the fake a second releaser also passes. (This is the orchestration release already on `main`, not the seat release of PR #1009.) +- The source contains at least 46 distinct `ConditionExpression` forms and 64 `UpdateExpression` forms. Only one of them, the `attribute_not_exists(task_id)` put in `create-task`, is ever evaluated by a real DynamoDB engine before production, in the real-AWS integ smoke; no update expression and no query is. + +## Where a green run can be trusted + +The investigation ran 353 checks shaped like ABCA's real calls against the emulator; 302 behaved as AWS documents, and the differences that set the scope below were probed again independently. + +| Trust a green run for | Do not use the tier for | +|---|---| +| DynamoDB: conditions, update expressions, transactions with per-item cancellation reasons, index keys and projections, `Limit` before filter, pagination including the 1 MB page, reserved words | Permissions of any kind. A missing grant is invisible; identity policies are evaluated in some paths and not others | +| S3 objects: put, get, head, delete, versions, presigned GET | Presigned POST policy enforcement (see below) | +| Secrets Manager: version stages, delete then restore, the error names and the one message text ABCA matches | Deployment correctness of the platform stack | +| Cognito: admin user operations, password login, refresh, change password, token claims | First-login password rotation, the hosted UI, MFA | +| STS: `AssumeRole` with session tags returning usable credentials | The AgentCore runtime, identity vault and registry; ECS and MicroVM task lifecycles | +| CloudWatch Logs: stream creation and writes | Anything that depends on eventual consistency, `TransactionConflict` or TTL timing | + +The two columns are separate lists; rows do not pair. + +The agent suite does contain five tests that expect a denial: three cross-tenant calls refused under the session role's policy, and two roles that cannot be assumed. They are a tripwire for the agent's wiring (the session tags reach STS, and tenant data goes through the scoped session). AWS says the emulator does not evaluate policies the way IAM does, so a pass is not evidence that the deployed policy is safe, and these are the tests most likely to change with an emulator release. + +Twelve operations ABCA calls do not work and stay on mocks. Eight answer 501: `InvokeAgentRuntime`, `StopRuntimeSession`, `RetrieveMemoryRecords`, `GetResourceOauth2Token`, `CompleteResourceTokenAuth`, `UpdateRegistry`, `UpdateRegistryRecordStatus`, and `RespondToAuthChallenge` for `NEW_PASSWORD_REQUIRED`. Four agent-registry operations answer with timestamps the JavaScript SDK refuses: three reads, and `SubmitRegistryRecordForApproval`, which takes effect on the server and then fails in the client. ABCA catches the error from three of the eight and continues, so a test of those paths is green while exercising only the fallback. `ApplyGuardrail` needs a test-side HTTP/1.1 request handler, because the bedrock-runtime client negotiates HTTP/2 and the emulator offers only HTTP/1.1. + +### Known differences from AWS + +| Difference | Consequence | +|---|---| +| With TTL enabled, an expired item is deleted 0.5 to 1.0 seconds after expiry; AWS says typically within a few days | Code that relies on TTL deletion instead of comparing `ttl` with the clock looks correct. The `cdk` harness therefore leaves TTL off | +| Index reads always reflect the preceding write, and a transaction is never cancelled with `TransactionConflict` | A read-after-write through a GSI can never miss here, and the retry for a conflicting transaction cannot be reached | +| Throttling and partial batches occur only at the limits the emulator models, which are AWS's documented ones: a provisioned table past its units, one partition key written past 1,000 write units in a second (three puts of about 390 KB), a `BatchGetItem` past 16 MB | ABCA's on-demand tables with ordinary rows do not reach them (300 small writes to one key, none refused). A test with large rows on one key can be throttled, and those branches can be exercised on purpose | +| About a dozen malformed expression forms are accepted, and a condition comparing an attribute with itself lets the write through | A typo of that kind passes here and is refused by AWS | +| Presigned POST: the policy and the signature are not enforced the way S3 enforces them | A test that the bucket refuses an upload outside the policy cannot be written here | +| A stream emits a `MODIFY` record for a write that changes nothing | Never assert on record or invocation counts | +| A force-deleted secret keeps its name blocked for about 0.5 seconds | Remove-then-recreate in one test needs a retry | +| `ListSecrets` returns more than 100 results in one page; ECS `RunTask` accepts overrides over 8,192 characters | Two historical ABCA defects would have passed | + +### Rules for tests in this tier + +1. Rows come from the real writer and schemas from the CDK constructs. +2. Assert on stored state and on error names. Never assert on AWS message text, stream record counts or invocation counts. +3. Never wait for TTL expiry. To test expiry logic, write a row with a past `ttl` and assert what the handler decides. +4. Age the data, not the clock: the emulator rejects requests signed more than 15 minutes from its own time, so fake timers break signing. +5. One set of uniquely named tables per test file (jest) or per session (pytest), created together; a fresh user or task id per test. +6. When code swallows an error from an operation the emulator does not implement, assert which branch ran. +7. Every expected failure or emulator-specific branch names the upstream record it waits for. +8. Nothing but the emulator and loopback. Stub every endpoint that is not an AWS SDK call, and never follow a URL the emulator returns. The tooling enforces this for the Node processes the wrapper starts and for the pytest process. + +## Proposed integration + +### How it runs + +``` +mise run test:integration + emulator.sh up build the pinned image if missing, start a fresh emulator on 127.0.0.1 + emulator.sh run jest (cdk/jest.emulator.config.js) real handlers in process + emulator.sh run jest (cli/jest.emulator.config.js) real CLI code in process + emulator.sh run pytest tests_emulator real agent code in process + emulator.sh down stop it; all state is discarded +``` + +The mise tasks are root tasks: run them from the repository root. + +Handlers are not run inside the emulator's Lambda. That runtime is QuickJS with generated stand-ins for the AWS SDK, not Node, so a handler that passes there has not been tested against the real SDK, and most of ABCA's do not run there at all (see [Deploying to the emulator](#deploying-to-the-emulator)). + +### Files + +| File | Purpose | Lines | +|---|---|---| +| `scripts/aws-emulator/Dockerfile` | Pinned emulator version, base image pinned by digest, package verified against the AWS publishing key by fingerprint, telemetry off | 62 | +| `scripts/aws-emulator/emulator.sh` | `up`, `down`, and `run ` with the AWS environment replaced | 133 | +| `scripts/aws-emulator/jest-config.js` | Builds a package's emulator jest configuration from its unit configuration; refuses unless the AWS environment is the wrapper's | 45 | +| `scripts/aws-emulator/jest-global-setup.js` | Before any test file loads, confirms that the loopback guard is in force and that the endpoint is the emulator | 54 | +| `scripts/aws-emulator/loopback-only.cjs` | Node preload that refuses any TCP connection leaving the machine | 47 | +| `cdk/jest.emulator.config.js`, `cli/jest.emulator.config.js` | Two lines each | 4 | +| `mise.toml` | Tasks `test:integration`, `emulator:up`, `emulator:down`, `emulator:run`; none is reachable from `mise run build` | +38 | +| `agent/pyproject.toml` | Ruff exceptions for `tests_emulator/**`: the list PR #1035 gives `tests/**`, which also passes on `main` | +1 | +| `.dockerignore` | The tooling directory stays out of the agent image context, so a version bump does not change the image hash | +4 | + +The tier itself changes no other tracked file. The unit runs cannot pick the emulator tests up, by naming and location and not by ignore lists: the jest files are `*.emulator.ts`, which the unit `testMatch` does not match, and the agent suite is in `agent/tests_emulator`, beside `tests/`, which is the only directory the unit run collects. + +The emulator's per-run credentials and certificate are written under the user cache directory, outside the repository, because the agent image asset fingerprints the repository root. + +### Keeping the tier away from real AWS + +The same tests with no endpoint set would call AWS with whatever credentials the shell holds, and product code also makes calls that are not AWS SDK calls at all. The guard is layered: + +1. **The wrapper replaces the AWS environment.** `emulator.sh run` removes every `AWS_*` variable, not a list of known ones, then sets the endpoint, the emulator's credentials file and its certificate. A leftover `AWS_ENDPOINT_URL_` or `AWS_IGNORE_CONFIGURED_ENDPOINT_URLS` would otherwise route calls to real endpoints. It also removes `GITHUB_TOKEN`, `GH_TOKEN` and `BGAGENT_API_KEY`, points `BGAGENT_CONFIG_DIR` away from `~/.bgagent`, and refuses to run anything unless the emulator answers its health route. Everything else in the caller's environment is inherited, other tokens included. One exception to the removal: a mise shim re-applies a mise `[env]` after the wrapper has run, and inside `mise run`, `yarn` can be a shim. `AWS_*` variables that come back are refused by layer 2. The three tokens are not checked again, so a token kept in a mise `[env]` is present in the jest processes, where layer 4 keeps it on the machine. +2. **The test configurations refuse a foreign environment.** The jest configurations and the pytest session require `AWS_ENDPOINT_URL` to be `https://127.0.0.1:` and no `AWS_*` variable other than the ones the wrapper sets. There is no skip path, so a run cannot be green having tested nothing. +3. **The endpoint is confirmed before any test.** The jest global setup requires the emulator's health route to answer over the certificate of this run. The pytest session requires STS, with a client built the way agent code builds one, to answer as account `000000000000`; a setting in the shared config file that turns `AWS_ENDPOINT_URL` off shows up there. The jest check confirms the address in the variable, not where SDK clients resolve. Such a setting cannot occur through the wrapper, which replaces the config file, and layer 4 covers it otherwise. +4. **Nothing may connect anywhere but loopback.** The environment only says where AWS SDK calls go. Product code also calls GitHub, Slack, Linear and Jira; the API-key authorizer's token verifier fetches its key set from the real `cognito-idp` host; `shared/agentcore-browser.ts` opens a hand-signed WebSocket. The wrapper preloads a module into every Node process it starts (jest and its workers, `tsx`, the CLI) that refuses a non-loopback TCP connection; child Node processes get it through the inherited `NODE_OPTIONS`. The agent suite installs the same rule as a Python audit hook in the pytest process, where it also covers datagrams and the lookup of a name. Both check themselves on every run: before any test, the jest global setup and the pytest session try to reach a `.invalid` host and stop the run unless that is refused, so jest does not start without the preload. Nothing else is covered: a Python subprocess, a Node process started with an environment that drops `NODE_OPTIONS`, UDP from Node, programs that are neither (`git`, `gh`, `uv`), a name that Node code resolves itself (`node:dns`), and a reverse lookup of an address in Python. No emulator test starts or reaches one of those. A refused connection reaches the caller as an ordinary network error, so a test of code that swallows network errors has to assert that no request was attempted. +5. **Only emulator-issued keys exist in that environment.** AWS does not recognize them. This is the one layer that could not be tested without calling AWS. + +For boto3 the certificate bundle is a further guard: it replaces the trust store, so a call that did go to an AWS host fails at the TLS handshake. (Node only adds the emulator's certificate to its own, which is why layer 4 exists.) It was needed once during the investigation. AWS CLI v1 forces a real endpoint for `sqs`, `rds`, `docdb`, `neptune` and `health` whatever `AWS_ENDPOINT_URL` says, and one `aws sqs` command dialed `queue.amazonaws.com`; the handshake failed before any request was sent. The tier uses SDKs only, and `emulator:run` is not for that CLI. + +What reviewers tried and could not break. Before the loopback guards existed, with every Node and Python process recording connections, the three suites made 181 connections, all to `127.0.0.1`; a shell polluted with 23 fake `AWS_*` variables left only the wrapper's; a home directory with canary `~/.aws` and `~/.bgagent` files was neither used nor modified; the emulator container opened no outbound connection. With the guards in place, a recorder under the Node preload saw 60 connection attempts in 8 Node processes during a whole run: 52 to `127.0.0.1`, 8 to local pipes, none refused. Each refusal described above was then tried on purpose, by a reviewer or in the final check, and behaved as written; the two self-checks were tried with the preload removed and with a copy of the agent suite whose hook was not installed. + +What is outside the guard: + +- `emulator:up` runs the container engine with the caller's environment. If Docker is configured to use the ECR credential helper for `public.ecr.aws`, an image build would ask ECR Public for a token with real credentials when it pulls the base image (a read-only call; reasoned from the tooling, not observed). +- The port is published on the host's loopback interface only, but other containers on the same Docker engine can reach it. They still need the per-run key, except for the routes the emulator serves unsigned. +- After a failed `test:integration` the emulator stays up for inspection, with its per-run credentials on disk (mode 0600), until `emulator:down`, the next `emulator:up`, or, per the emulator's CLI reference, an hour without an API call (not tested). + +### Fit with pull request #1035 + +PR #1035 isolates the unit suites: the CLI's jest `globalSetup` deletes every `AWS_*` variable and a setup file restricts sockets to loopback, and the agent's `conftest.py` deletes them, refuses every botocore request and fails CI when any test is skipped. Its `pyproject.toml` makes pytest warnings errors and adds ruff rules, its coverage contract pins the jest blocks of `cdk` and `cli`, and its dead-code check is zero-tolerance over `test/` and `scripts/`. An emulator test that sits inside those harnesses and skips itself when no emulator is present cannot work once that merges, which is why the tier is separate by naming and location. + +Checked by taking #1035's files from git (head `9525c2d8`), not by merging: + +| #1035 gate | Result on this worktree | +|---|---| +| Coverage contract over the jest blocks | No drift: neither `package.json` is edited | +| ESLint with its `cdk` and `cli` configurations, `--max-warnings 0` | Clean | +| Ruff 0.17.3 with its `agent/pyproject.toml`, which adds the `ARG` rules and a `TID251` banned-API table | Clean. The `tests_emulator/**` line carries the exception list #1035 gives `tests/**`; with the list `main` uses for `tests/**` there are 17 findings | +| `cli` emulator suite under a #1035-style unit configuration | 5 passed. The emulator configuration replaces the unit `globalSetup` and inherits the loopback-only setup file | +| Agent emulator suite with `strict = true` and warnings as errors | 42 passed, three runs. The unit conftest never applies to `tests_emulator` | +| Dead-code check with its `knip.json` | Eight of the new files are reported as unused until seven entry lines are added, after which nothing is: `jest.emulator.config.js` and `test/emulator/*.emulator.ts` in the `cdk` and `cli` workspaces, `test/emulator/trace-api-shim.ts` in `cdk`, and `scripts/aws-emulator/jest-global-setup.js` and `loopback-only.cjs` in the root workspace | + +If #1035 merges first, each slice of the rollout carries its own `knip.json` entries (four, one and two lines). `agent/pyproject.toml` is the one file where the two change sets conflict textually (adjacent lines); `mise.toml` and `.dockerignore` merge cleanly. + +### CI + +A separate workflow, not a job in `build.yml`: `deploy.yml` and `integ.yml` start from `workflow_run` on `build` and need its conclusion to be `success`, so an advisory failure there would stop both. The workflow in [Appendix A](#appendix-a-workflow) uses no secret and `contents: read` only, so it runs unchanged for fork pull requests. It adds no finding to the repository's own `zizmor` gate and passes `actionlint`. + +It has not run on GitHub, and the three suites have run on macOS only. On Linux, an earlier version of the wrapper was exercised as an unprivileged user against a Linux Docker daemon on arm64 (`up` with the image copied in, a signed STS call through `run`, `down`), and the `linux/amd64` image was built and started under emulation on a Mac. Still to run on Linux: the image build through `emulator.sh up`, the wrapper as it is now, and jest and pytest under the loopback guards. The first run on a GitHub-hosted runner covers all of these. + +The parts measured so far add up to 2.1 to 2.3 minutes: 83 to 89 seconds of overhead for a comparable job (`dead-code-pr`, checkout through `mise run install`), a 16 to 24 second image build and the 24 second tier, the last two on a laptop. The estimate of 2.5 to 3.5 minutes allows for a slower hosted runner. + +Advisory here means visible and not required: the job is left out of the ruleset's required checks and a failure shows as a red check. The repository's one existing advisory gate, `dead-code-pr.yml`, masks failures with `continue-on-error` instead; a red check keeps the history measurable for the graduation criteria below. That a red check which is not required does not hold up the merge queue is taken from GitHub's documentation, not observed. + +### Version pin + +One pin, the `ARG AWS_EMULATOR_VERSION` line in the Dockerfile. To move it, run `ABCA_EMULATOR_VERSION= mise run test:integration` and then edit the line. The image tag carries the version and a checksum of the Dockerfile, so either change is rebuilt. The override was run once, with v1.0.367, before the tag carried the checksum. The wrapper does not remove old images; after a bump, delete the previous tag (`docker image rm abca-aws-emulator:`, about 1 GB each). Upstream ships several releases a day and puts security fixes only in the newest one, but the exposure is small by construction: published on host loopback only, no real credentials or data, a CI job with no secret. + +Pinning is not optional. The user guide says passing fidelity tests do not regress; the published scores say otherwise. On an unchanged test set (v1.0.336 to v1.0.385, 2.2 days), up to 23 tests on the six core services went from pass to fail because of the emulator. None is a happy-path test of an operation ABCA calls on DynamoDB, S3 objects or Secrets Manager. The one that matters to ABCA is Cognito: v1.0.382 changed the token `iss` claim, and running this tier on v1.0.367 fails exactly one test, on that claim. ABCA's own suite on the candidate version is the gate for a bump; the release notes are the second check. + +### Relation to what exists + +| Existing piece | Proposal | +|---|---| +| DynamoDB Local suites in open PRs #1009, #1013, #904 | Leave them on DynamoDB Local. #904 adds it as a service container in the required `build` job, which is where these suites would run, and it is the more mature DynamoDB engine. Porting them to the emulator has not been tried. It would need the files moved to `test/emulator/*.emulator.ts`, their `http://127.0.0.1` guard and own endpoint variable replaced by the wrapper's environment, and their injected dummy credentials removed; it would move them out of the required build into the advisory workflow; and the `TransactionConflict` retry in #1009 cannot be exercised on the emulator. The emulator does a different job: it is the only option that also covers S3, Secrets Manager, Cognito, STS and Logs behind one endpoint | +| `agent/run.sh --local-events` with DynamoDB Local | Keep. That flow uses real credentials for Bedrock and redirects only DynamoDB; the emulator rejects keys it did not issue | +| Hand-written DynamoDB fakes | Replace later, after measuring what they contribute to the coverage thresholds | +| Issue #61 | `agent/tests_emulator/test_trace_round_trip.py` meets its end-to-end and under-10-seconds criteria. Its opt-in marker criterion is met differently (a separate directory and run, not a marker) and its README criterion is not met | +| ADR-013 | Replace the LocalStack wording with the emulator; replace the "60%+" sentence with the measured statement in [What it is worth](#what-it-is-worth); add the graduation criteria below; state that Tier 2c (the ephemeral stack deploy, which the ADR expects to catch IAM gaps) stays on real AWS | +| Real-AWS integ smoke | Keep as the authority for IAM, deployment and API Gateway wiring, and unblock it; the emulator tier does not stand in for it | + +## Deploying to the emulator + +Not recommended as a tier now. The boundary was measured and is narrower than a green deployment suggests. + +What works: the existing integ app (`cdk/test/integ/integ.task-api-smoke.ts`) deploys unmodified with `cdk bootstrap` and `cdk deploy`, 53 resources of 18 types, in about 52 seconds for a full cycle including synth and destroy. All 53 were read back from their owning services with the declared properties. Requests through the deployed REST API pass the Cognito authorizer and reach the handlers, provided the client sends a non-loopback `Host` header and a `User-Agent`, because the emulator evaluates the stack's WAF managed rules. Emulated CloudFormation also rejects template mistakes that type checking and template assertions accept, such as a GSI key missing from the attribute definitions. + +What does not: + +- **integ-runner's assertions cannot complete.** They are Lambda-backed custom resources with Node providers, and the emulated Node runtime has no HTTP client to answer CloudFormation with. A Python provider does complete. +- **Handlers mostly do not run there.** Through the deployed API the six Task API routes answer 200, 200, 500, 502, 502 and 502. A package file over 8 MiB is truncated, sometimes without any error. +- **A stack status is not proof.** Four resource types, including the AgentCore runtime and memory, reach `CREATE_COMPLETE` and create nothing. +- **The full platform is refused.** The minimal profile has 318 resources. Six of its resource types are unknown to the emulator, and the template is refused until the resources of those types are removed. With those and the six custom resources removed and three resources patched, 302 reach `CREATE_COMPLETE`. Leaving out the three patched ones and four that create nothing, 295 of the 318 deploy unmodified and exist (an investigator's measurement that no verifier re-ran). +- **Bootstrap policy gaps stay invisible.** A missing `Allow` never fails a deployment; only an explicit `Deny` or a broken trust policy does, and ABCA's execution policies contain no `Deny`. + +Of the 120 historical defects, two would have been caught by a deployment to the emulator. Revisit when the emulated Lambda runtime is real Node (`aws/aws-emulator#28` and `#325`). + +## Rollout + +The proposal at hand-over was three pull requests, one per suite, each with its own issue. The owner chose one branch and one pull request instead, with the workflow and the fixes in it (see [Outcome](#outcome)). That pull request touches paths the admin team owns in CODEOWNERS (`mise.toml`, `.github`, the `AGENTS.md` files). + +Left for later from the three-slice plan: + +- Take the agent suite's table schemas and its session-role policy from the synthesized template instead of copying them by hand, and derive the CLI's fixture stacks from the constructs. +- Declare `tsx` in `cli`. The trace round trip runs CLI source with it and only `@abca/cdk` declares it; a new dependency there needs agreement first. +- Tests of the `bgagent setup` AWS adapters, which no test executes today. The last of the five (`setBootstrapComputeTypes`) can only be reached by exporting `defaultDeps` from `cli/src/commands/setup.ts`, a small product-code change. + +First tests to add, by expected value: + +1. The approval lifecycle across the agent, the handlers and both reconcilers, with the agent's real transition writing the rows. It covers the three approval defects found here. +2. Every handler that combines `Limit` with a filter or reads one page, seeded with more than a page of non-matching rows first (#51 and its four relatives). +3. Approve and deny as real transactions, replacing `approval-concurrency.test.ts`, whose mock scripts the outcome it asserts. +4. One invariant over all writers of a task's `status`: `status_created_at` follows the status, and a terminal row has `completed_at` and `ttl`. +5. The attachment upload path, asserting the handlers' decisions and not S3's enforcement. + +Graduation to a required check, measured over 30 days: every red run triaged; none of the last 100 pull-request and merge-queue runs red because of the emulator or the runner; p95 job duration under 5 minutes; at least one test per service in scope; the pin never more than 14 days behind. Then add the job name to the ruleset, and have CI install the pinned `.deb` on the runner from a cache instead of building the image, so that a required check does not depend on two download hosts (`public.ecr.aws` for the base image, `downloads.aws.com` for the package) on every run. + +## Costs and risks + +- **A young dependency.** 417 open issues days after its first release, behavior changing daily. The pin contains it; the list of differences has to be kept. +- **False confidence.** Emulator-green is not AWS-green. The table of differences above is the minimum that contributors need to know, and it will grow. +- **Docker.** The wrapper runs the emulator in a container on every platform, CI included; the native Linux package is not used. Docker is already needed for CDK asset bundling. +- **License.** The source repository is CC0-1.0 with Apache-2.0 vendored code. The package's own `THIRD_PARTY_LICENSES` file lists four crates under LGPL-3.0-only among 961. ABCA downloads the package from AWS at use time and never redistributes it. Committing the package, publishing a prebuilt image, or baking it into an image ABCA distributes would change that and needs a license review first. +- **Telemetry.** On by default upstream; the image turns it off in two places. +- **Invisible to scanners.** The package is one statically linked binary with no audit metadata; `grype` catalogs zero packages in it. Its vulnerability management is the bump cadence. +- **Not verified.** The workflow has not run on GitHub, so its duration, its behavior for fork pull requests and the assumption about the merge queue are untested. The suites have run on macOS only. The worktree has not been merged with #1035; that pull request's gates were simulated one by one. The DynamoDB Local suites of #1009, #1013 and #904 have not been run on the emulator. The full-platform deployment figures were not re-run. Nothing in this investigation was compared with real AWS: every statement about AWS behavior is from AWS documentation, the published fidelity suite, or ABCA's own commit history. + +## Not built, and when to add it + +| Left out | Add it when | +|---|---| +| A scheduled run that tries the newest upstream release | Manual bumps become a chore, or the tier is headed for required status | +| One table set shared by all jest test files (the agent suite already shares one per session) | The 3 second wait per file starts to dominate the run | +| Reading each handler's environment from its construct | A variable-name drift reaches a deployed stack | +| A stream driver (read real stream records, apply the construct's filter, call the consumer) | The first test of the orchestration reconciler or fan-out is written | +| Request timeouts on the harness clients | A stalled emulator is seen in practice. Today the health probe before the run and the job timeout bound it | +| A check that the downloaded package is the pinned release, beyond who signed it | The download host is not trusted to serve the file its URL names | +| A deploy-to-emulator check | The emulated Lambda runtime is real Node | +| Letting ABCA's own agents run the tier inside their container before they open a pull request (the self-validation ADR-013 is written for) | The check is required, so that an agent's pull request is not judged by a check the agent could not run. Today the agent image has no Docker, AgentCore caps images at 2 GB, and the egress allowlist lacks `downloads.aws.com`. The agent suite would also have to clear the agent variables it inherits | + +## Defects found during the investigation + +Code references are to `main` at `c8fcdb08`. Unless a row says otherwise, the defect was found by one investigator and confirmed by an independent verifier: the product defects by running the real code against the emulator, the two CI rows from the GitHub API. One row has a single execution behind it: the heartbeat defect was found and run in real time by a verifier (a later reviewer read the code path and found it consistent). The concurrency-group mechanism was established by a verifier and confirmed live by a later reviewer. + +| Defect | Where | What was observed | Tracking | +|---|---|---|---| +| The stranded-approval sweep measures from the start of `RUNNING`, not from the approval request | `agent/src/task_state.py:706-708,762-764`; `cdk/src/handlers/reconcile-stranded-tasks.ts:108-142` | With the agent's real hook and the real reconciler, a task that had been `RUNNING` for 2 h 5 min was failed "Approval stranded" 0.3 s after it opened its gate. The user's approval was refused with 409, the gated call was denied when the agent's own wait ended, and the agent went on to open a pull request for a task reported `FAILED`. Tasks are exposed when they open a gate after about 1 h 55 min of running | None. Open PR #1013 adds a TypeScript writer with the same omission | +| A task resumed after an approval wait longer than 240 s can be failed as "Agent session lost" | `agent/src/task_state.py:106-127,762-764`; `cdk/src/handlers/shared/orchestrator.ts:1113-1137` | Heartbeats are not written while a task awaits approval and the resume does not refresh one. With both timers on their own cadence, a 275 s wait ended `FAILED` 25 s after the user approved; a 205 s wait survived. AgentCore and Lambda MicroVM backends | None. Fixed in passing inside open PR #904 | +| The concurrency reconciler counts four statuses where `ACTIVE_STATUSES` lists five | `cdk/src/handlers/reconcile-concurrency.ts:40-48` against `cdk/src/constructs/task-status.ts:95-101` | Reproduced with the real handler and the agent's real transition. One verifier also saw the same handler count a `SUBMITTED` task that holds no seat | None. Open PR #1009 rewrites the handler on `ACTIVE_STATUSES` and tests it | +| A never-configured GitHub token secret is reported as configured | `cli/src/github-token.ts:115-118`; `cdk/src/stacks/agent.ts:305-308` | CDK seeds the secret with a random 32-character string; the CLI assumes a JSON placeholder. On a fresh stack `platform doctor` passes the token check and the first `github set-token` warns about overwriting a token. `github set-webhook-secret` uses the same test (read, not run) | None. Same root cause as closed #368, fixed there for the Jira webhook secret only | +| A session role that cannot be assumed does not abort the task, although three comments say it does | `agent/src/aws_session.py:35-41,186-192`; `agent/src/pipeline.py:906-909`; `agent/src/server.py:974-975` | `AssumeRole` is deferred by design. The agent completed the clone, agent loop and pull-request steps with nothing written to the task or events tables; gated tool calls were denied. On AgentCore and MicroVM the orchestrator reports "Agent session lost" about six minutes later. A task with attachments does abort, at the download. No tenant data was read or written with the unscoped credentials. In a CDK-managed deployment this probably needs drift or an SCP (inferred) | None | +| The trajectory writer never retries stream creation | `agent/src/telemetry.py:157-174` | A first `CreateLogStream` that fails after the SDK's retries loses the task's whole CloudWatch trajectory | None | +| #51: list order and the empty filtered page | `cdk/src/handlers/list-tasks.ts:83-110` | Reproduced with the unmodified handler. Fixing it with a key condition on `status_created_at` would hide approval-paused tasks under `AWAITING_APPROVAL` (shown by a direct index query) and Slack-cancelled tasks under `CANCELLED` (inferred from the stored row), because neither writer maintains that attribute; design the two together | #51 | +| #1003: a replayed finalize step releases a second seat | `cdk/src/handlers/shared/orchestrator.ts:1235-1297` | Reproduced | #1003, PR #1009 | +| `integ.yml` is blocked by its own concurrency group; `integ-smoke` is not a required check | `.github/workflows/integ.yml:45-47,198` | See [Against the CI record](#against-the-ci-record) | Open PR #1035 moves the group to the deploy job (its commit `6eb6662f`). Open #400 proposes relaxing the same group for another reason | +| `upgrade-main` has failed on every scheduled run since 2026-08-19 | The repository secret `AUTOMATION_GITHUB_TOKEN`, which `.github/workflows/upgrade-main.yml` uses | 89 consecutive failures in the Create Pull Request job: GitHub refuses the fetch and the push made with that token. The workflow file is the one that succeeded the day before, and the secret has not been updated since 2026-06-11. The last pull request the job opened is #590 on 2026-07-11 | None | + +Smaller observations: the Slack cancel button writes less than `cancel-task` (a stale `status_created_at` and no `completed_at`); cancelling a running task through the API records `task_cancelled` twice; `bgagent ops stuck-tasks` ages tasks by creation time, so an approval-paused task created long ago is listed as stuck; the agent stores `cost_usd`, `duration_s` and turn counters as DynamoDB strings while `numeric.ts` blames the SDK and `TaskRecord` declares numbers (every current reader coerces); the agent unit suite depends on test order through `hooks._LAST_BLOCKER_REASON`. + +Also confirmed, and already fixed with a regression test in open PR #1035: eleven Lambda bundles contain all of `aws-cdk-lib`. + +## Open decisions + +Decided on 2026-11-15 (see [Outcome](#outcome)): 1 (yes), 2 (a red check that is not required), 8 (the tables in Outcome) and 9 (one branch and one pull request, with its issue). The others are open; for 4, 5 and 6 the pull request follows what this document proposes. + +1. Adopt the tier as advisory, in the shape above? +2. Advisory as a red check that is not required (proposed), or masked with `continue-on-error` as `dead-code-pr.yml` does? +3. One local backend or two? #904 adds DynamoDB Local as a service container in the required `build` job, where the suites of #1009, #1013 and #904 would run. Proposed: keep them there and use the emulator for what DynamoDB Local cannot reach. Porting them (not tried) gives one backend, but moves them into the advisory workflow and gives up the `TransactionConflict` retry. +4. Do known-defect witnesses (`test.failing`) ship, or only passing tests? A `test.failing` passes on any throw, so each has to be run once as a plain test; the alternative is a test that asserts today's wrong value and fails when it is fixed. The repository already ships one such witness (`cdk/test/integration/orchestration-e2e.test.ts:402-412`). +5. Keep the five agent tests that expect an emulator-evaluated denial, knowing they can break with an emulator release? +6. Directory names: `test/emulator` and `tests_emulator` (what the tests need) or `integration` (what ADR-013 and issue #61 call the tier). `cdk/test/integration` already holds fake-backed tests that run in the unit tier. +7. `integ.yml`: unblock it (open #400 proposes relaxing the same concurrency group), and should `integ-smoke` be a required check? `integ.yml` and ADR-013 call it required; the ruleset does not list it. +8. Which of the defects marked "None" to file, and in what order. The #51 fix and the status writers are one design, and the approval-sweep fix has to land in whichever writer is current when #1013 merges. +9. The issues the tier needs before any branch (ADR-003): one per slice. #61 is open and not labeled `approved`. +10. Which upstream reports to file (Appendix B). + +## Appendix A: workflow + +`.github/workflows/emulator.yml`. The committed file is this block, byte for byte. + +```yaml +name: emulator +# ADR-013 Tier 2a: runs ABCA's real handler, CLI and agent code against the AWS Emulator +# (https://github.com/aws/aws-emulator) instead of module-level SDK mocks. No AWS account, +# role or secret is involved, so it runs unchanged for fork pull requests. +# +# Advisory: the job is not in the required status checks of the `main` ruleset, so a red run +# is visible on the pull request but does not block the merge. To make it required, add the +# job name ("Emulator integration tests") to the ruleset; it already runs on merge_group, +# which a required check must do or the merge queue deadlocks (#327). +# +# Kept out of build.yml on purpose: deploy.yml and integ.yml start from `workflow_run` on +# build and need its conclusion to be `success`. +on: + pull_request: {} + merge_group: {} + workflow_dispatch: {} + +permissions: + contents: read + +concurrency: + group: emulator-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + emulator: + name: Emulator integration tests + runs-on: ubuntu-latest + timeout-minutes: 15 + permissions: + contents: read + env: + CI: "true" + MISE_EXPERIMENTAL: "1" + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Install mise + uses: jdx/mise-action@b44d12e7d0d8ee7461bb893e1b1993500433185b # v5.2.7 + with: + version: 2026.10.25 # exact mise release for every workflow (#890); bump by PR + cache: true + + - name: Setup Node.js + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: 22.x + + - name: Install dependencies + run: mise run install + + # Builds the pinned, signature-verified emulator image, starts a fresh emulator on + # loopback, runs the cdk, cli and agent emulator suites, and stops it. + - name: Emulator integration tests + run: mise run test:integration + + - name: Emulator log (on failure) + if: failure() + run: | + docker ps -a --filter name=abca-aws-emulator --format '{{.Names}}' \ + | xargs -r -n1 docker logs --tail 200 || true +``` + +The emulator logs its start-up and table creation only, so the last step shows whether the emulator started, not why a test failed. + +## Appendix B: upstream reports worth filing + +Nothing was filed. None of the five is in the emulator's in-repository issue log at the commit examined (the last three by keyword search only), and searches of its GitHub tracker on 2026-11-15 found no report of them. + +| Report | Evidence | +|---|---| +| The `lib-dynamodb` stand-in inside emulated Lambda throws on `ExclusiveStartKey: undefined`; the real SDK skips undefined values | The same query from host Node with the real SDK succeeds against the same table | +| A Lambda package file over 8 MiB is truncated, and runs without error when the cut falls on a statement boundary | A file 35 bytes over the cap returned the handler defined before the cut | +| `ListSecrets` returns more than 100 results without `MaxResults` | 103 secrets came back in one page | +| ECS `RunTask` accepts container overrides longer than 8,192 characters | A 12,000-character override was accepted | +| Four agent-registry operations (`GetRegistry`, `GetRegistryRecord`, `ListRegistryRecords`, `SubmitRegistryRecordForApproval`) return `createdAt` and `updatedAt` as epoch numbers, which the AWS SDK for JavaScript refuses | boto3 accepts the same responses; the JavaScript client throws on each | + +Already recorded upstream and worth a comment, not a duplicate: `RespondToAuthChallenge` for `NEW_PASSWORD_REQUIRED`, Node custom-resource providers, AgentCore resources that are declared but not created, a write condition that compares an attribute with itself being accepted, `CreateOauth2CredentialProvider` answering a duplicate name with `ConflictException` where ABCA's history records `ValidationException` from AWS, the `gpg --import` step of the user guide that fails in the guide's own base image (`aws/aws-emulator#313`), the four-part version in `versions.json` that package URLs reject (`#434`), the fixed 3 second table transition (`#436`), and the missing HTTP/2 listener (`#31`). + +## Appendix C: running the proof of concept + +From the repository root: + +```bash +mise run test:integration # everything, on a fresh emulator +mise run emulator:up # or keep one running while iterating +mise run emulator:run -- yarn --cwd cdk jest --config jest.emulator.config.js task-api +(cd agent && ../scripts/aws-emulator/emulator.sh run uv run pytest --no-cov tests_emulator/test_secrets.py) +mise run emulator:down +``` + +The first `emulator:up` builds the image (about 16 seconds, a 161 MB download on arm64 and 182 MB on x86_64). Two worktrees can run the tier at the same time; the port is derived from the checkout path. + +A green run prints about 45 INFO lines from the handlers during the `cdk` step, among them "Drift detected" from the concurrency reconciler. They are the product's own logs, not failures. Tests marked `test.failing` are counted and listed as passed. diff --git a/docs/src/content/docs/architecture/Api-contract.md b/docs/src/content/docs/architecture/Api-contract.md index 55035d0fe..29b5098d0 100644 --- a/docs/src/content/docs/architecture/Api-contract.md +++ b/docs/src/content/docs/architecture/Api-contract.md @@ -265,7 +265,7 @@ Returns full details of a task. Users can only access their own tasks. | Field | Type | Description | |---|---|---| -| `category` | String | One of: `auth`, `network`, `concurrency`, `compute`, `agent`, `guardrail`, `config`, `timeout`, `unknown` | +| `category` | String | One of: `auth`, `network`, `concurrency`, `compute`, `agent`, `guardrail`, `config`, `timeout`, `blocked`, `unknown` | | `title` | String | Human-readable error title | | `description` | String | Detailed explanation of what went wrong | | `remedy` | String | Suggested action to resolve the error | @@ -275,13 +275,13 @@ Example for a failed task: ```json { - "error_message": "User concurrency limit reached", + "error_message": "Pre-flight check failed: REPO_NOT_FOUND_OR_NO_ACCESS — GitHub API returned HTTP 404 for acme/widgets", "error_classification": { - "category": "concurrency", - "title": "Concurrency limit reached", - "description": "The maximum number of concurrent tasks for this user has been reached.", - "remedy": "Wait for an active task to complete, cancel a running task, or ask an admin to increase the limit.", - "retryable": true + "category": "auth", + "title": "Repository not found or inaccessible", + "description": "The GitHub token cannot access the target repository. It may not exist or the token lacks visibility.", + "remedy": "Check that the repository name is correct and the configured PAT has access to it.", + "retryable": false } } ``` @@ -358,7 +358,7 @@ Returns the audit trail for a task: state transitions, hydration events, session **Query parameters:** `limit` (default 50, max 100), `next_token`. -**Event types:** `task_created`, `uploads_confirmed`, `attachment_blocked`, `admission_rejected`, `preflight_failed`, `hydration_started`, `hydration_complete`, `session_started`, `pr_created`, `task_completed`, `task_failed`, `task_cancelled`, `task_timed_out`. Custom blueprint steps emit `{step_name}_started`, `{step_name}_completed`, `{step_name}_failed`. (There is no `admission_passed` or `session_ended` event — admission success is implicit in the subsequent `hydration_started`, and session end is captured by the terminal event.) +**Event types:** `task_created`, `uploads_confirmed`, `attachment_blocked`, `admission_queued`, `queue_pickup`, `preflight_failed`, `hydration_started`, `hydration_complete`, `session_started`, `pr_created`, `task_completed`, `task_failed`, `task_cancelled`, `task_timed_out`. Custom blueprint steps emit `{step_name}_started`, `{step_name}_completed`, `{step_name}_failed`. (There is no `admission_passed` or `session_ended` event — admission success is implicit in the subsequent `hydration_started`, and session end is captured by the terminal event.) **Correlation envelope (#245):** each event optionally carries top-level `user_id`, `repo`, and `trace_id` (the agent's OTEL trace id) so the event stream joins to structured logs and X-Ray. Each field is present only when the event's source stamped it — `task_created` predates the envelope and carries none; events from `hydration_started` onward carry `user_id`/`repo`, and agent-emitted events additionally carry `trace_id`. Fields are omitted (not `null`) when absent. See [OBSERVABILITY.md](/sample-autonomous-cloud-coding-agents/architecture/observability#correlation-envelope). @@ -573,10 +573,10 @@ There is no per-user request-rate or "tasks-per-hour" limiter on task creation. | Per-task nudge limit | Default 10/min | Per task (`POST /tasks/{id}/nudge`) | `429 RATE_LIMIT_EXCEEDED` | | Application rate limiter (`shared/rate-limit`) | Per-endpoint | Used by `approve`, `deny`, `pending`, `nudge`, `policies` and Linear webhook/fan-out paths — **not** task creation | `429 RATE_LIMIT_EXCEEDED` | -**Concurrency (not a rate limit).** Per-user concurrent task count is bounded (configurable, default 3-5). This is enforced by admission control, not by the create-task endpoint: +**Concurrency (not a rate limit).** Per-user concurrent task count is bounded (configurable, default 10). This is enforced by admission control, not by the create-task endpoint: - `POST /v1/tasks/{task_id}/confirm-uploads` rejects with `429 RATE_LIMIT_EXCEEDED` when the user is already at their concurrency limit. -- For the orchestrator admission path (the `SUBMITTED → HYDRATING` transition), exceeding the limit does not return an HTTP error — the task is already created. The orchestrator drives the task to `FAILED` with `error_message` "User concurrency limit reached" and emits an `admission_rejected` event. +- For the orchestrator admission path (the `SUBMITTED → HYDRATING` transition), exceeding the limit does not return an HTTP error — the task is already created. The orchestrator parks the task as `QUEUED` and emits an `admission_queued` event. The task is admitted, oldest first, as the user's slots free up (`queue_pickup`), and fails if it is still queued 24 hours after submission. **Monthly budget admission.** Task creation checks the current UTC-month estimated spend for the authenticated user and every Cognito group captured as a team. A configured hard-stop scope at or above 100% returns `429 BUDGET_EXCEEDED` before creating a new task. Alerts-only scopes continue. Same-user idempotent replays return their existing task before this check. @@ -626,3 +626,4 @@ List endpoints use token-based pagination (consistent with DynamoDB's `Exclusive - Pass `next_token` as query parameter for the next page - Tokens are short-lived and should not be stored - Results ordered by `created_at` descending (newest first) +- A page can hold fewer items than `limit`, or none, while `has_more` is `true`: a list that filters (tasks by `status` or `repo`, webhooks and API keys without the revoked ones) reads a bounded number of rows per request. Follow `next_token` until `has_more` is `false` diff --git a/docs/src/content/docs/architecture/Cost-model.md b/docs/src/content/docs/architecture/Cost-model.md index e9ed6a45d..96b86fd04 100644 --- a/docs/src/content/docs/architecture/Cost-model.md +++ b/docs/src/content/docs/architecture/Cost-model.md @@ -107,7 +107,7 @@ For **AWS-native** chargeback of Bedrock spend (Cost Explorer / CUR 2.0 by `user | Monthly user/team warning | Estimated terminal-task cost rollup | CloudWatch/SNS at 80% and 100% | | Monthly user/team hard stop | Admission check at 100% | Disabled per scope unless `--hard-stop` is set | | Session timeout | Orchestrator timeout | 9 hours | -| Concurrency limit | Per-user atomic counter | 3 concurrent tasks | +| Concurrency limit | Per-user atomic counter | 10 concurrent tasks | | System concurrency | System-wide counter | Account-level AgentCore quota | Monthly budgets use UTC calendar months and the same estimated `cost_usd` stored on terminal tasks. The TaskTable stream consumer transactionally increments the user and captured Cognito-team rollups and writes a task marker so duplicate stream delivery cannot double count. Admission checks every configured applicable scope; any scope at 100% with hard stop enabled rejects a new task. In-flight tasks continue and can overshoot because their final cost is unknown until termination. diff --git a/docs/src/content/docs/architecture/Interactive-agents.md b/docs/src/content/docs/architecture/Interactive-agents.md index 36ffd2844..c35d9383b 100644 --- a/docs/src/content/docs/architecture/Interactive-agents.md +++ b/docs/src/content/docs/architecture/Interactive-agents.md @@ -176,7 +176,7 @@ A single AgentCore Runtime, invoked via `bedrock-agentcore:InvokeAgentRuntime` w Durable-execution Lambda that owns the task lifecycle from submission to terminal state. Responsibilities: -- **Admission control** — atomic DDB conditional update on `UserConcurrencyTable` (`active_count < max`); reject with 429 if over quota. +- **Admission control** — atomic DDB conditional update on `UserConcurrencyTable` (`active_count < max`); a task over the limit is parked as `QUEUED` (#441). - **State transition** `SUBMITTED → HYDRATING → RUNNING → FINALIZING → terminal`. - **Invocation** — calls `InvokeAgentRuntime` with SigV4. - **Poll loop** — waits for the agent to land a terminal status in `TaskTable`; enforces heartbeat watchdog; transitions to `FAILED` if the container dies. @@ -199,7 +199,7 @@ The durable event spine. PK = `task_id`, SK = `event_id` (ULID), TTL enabled, ** Writers: - `ProgressWriter` (inside the agent container) — per tool call, per turn, per milestone, cost updates, errors. -- `OrchestratorFn` — `task_created`, `hydration_*`, `session_started`, `task_*`, `preflight_*`, `admission_rejected`, `guardrail_blocked`. +- `OrchestratorFn` — `task_created`, `hydration_*`, `session_started`, `task_*`, `preflight_*`, `admission_queued`, `guardrail_blocked`. - Cancel/reconciler handlers — `task_cancelled`, `task_stranded`. Readers: diff --git a/docs/src/content/docs/architecture/Observability.md b/docs/src/content/docs/architecture/Observability.md index 6758365b5..c9603713c 100644 --- a/docs/src/content/docs/architecture/Observability.md +++ b/docs/src/content/docs/architecture/Observability.md @@ -94,11 +94,11 @@ The platform tracks four categories of signals, each serving different consumers Every task emits structured events at each state transition, stored in the TaskEvents table: -- State transitions: `task_created`, `admission_rejected`, `uploads_confirmed`, `hydration_started`, `hydration_complete`, `session_started`, `pr_created`, `task_completed`, `task_failed`, `task_cancelled`, `task_timed_out` +- State transitions: `task_created`, `admission_queued`, `queue_pickup`, `uploads_confirmed`, `hydration_started`, `hydration_complete`, `session_started`, `pr_created`, `task_completed`, `task_failed`, `task_cancelled`, `task_timed_out` - Blueprint custom step events: `{step_name}_started`, `{step_name}_completed`, `{step_name}_failed` - Guardrail events: `guardrail_blocked` (content blocked during hydration) -All events carry `task_id` and `user_id` for filtering. +All events carry `task_id` for filtering; the events the orchestrator and the agent write from `hydration_started` onward also carry `user_id` (see the coverage notes above). ### Agent execution diff --git a/docs/src/content/docs/architecture/Orchestrator.md b/docs/src/content/docs/architecture/Orchestrator.md index bfef87138..06798cc39 100644 --- a/docs/src/content/docs/architecture/Orchestrator.md +++ b/docs/src/content/docs/architecture/Orchestrator.md @@ -340,7 +340,7 @@ Each task runs in its own isolated compute session with no shared mutable state |---|---|---| | `invoke_agent_runtime` TPS | 25 per agent/account | AgentCore quota (adjustable) | | Concurrent sessions | Account-level limit | AgentCore quota | -| Per-user concurrency | Configurable (default 3-5) | Platform config | +| Per-user concurrency | Configurable (default 10) | Platform config | | System-wide max tasks | Configurable | Bounded by selected-backend quotas | ### Counter management @@ -427,14 +427,14 @@ Three DynamoDB tables back the orchestrator: one for task state, one for the aud | `model_id` | String? | Foundation model ID | | `prompt_version` | String | System prompt hash for evaluation correlation | | `blueprint_config` | Map? | Snapshot of `RepoConfig` at task creation | -| `cost_usd` | Number? | Agent cost from SDK | -| `duration_s` | Number? | Total duration | +| `cost_usd` | String? | Agent cost from SDK, written by the agent as a string | +| `duration_s` | String? | Total duration in seconds, written by the agent as a string | | `ttl` | Number? | DynamoDB TTL (default: created_at + 90 days) | | `created_at` / `updated_at` | String | ISO 8601 timestamps | -> **Derived field:** `error_classification` is not stored in DynamoDB. It is computed at API response time by passing `error_message` through the runtime error classifier (`error-classifier.ts`). This returns a structured object with `category` (auth/network/concurrency/compute/agent/guardrail/config/timeout/unknown), `title`, `description`, `remedy`, and `retryable` flag. The derived-field pattern means classifier updates take effect immediately for all existing tasks without data migration. +> **Derived field:** `error_classification` is not stored in DynamoDB. It is computed at API response time by passing `error_message` through the runtime error classifier (`error-classifier.ts`). This returns a structured object with `category` (auth/network/concurrency/compute/agent/guardrail/config/timeout/blocked/unknown), `title`, `description`, `remedy`, and `retryable` flag. The derived-field pattern means classifier updates take effect immediately for all existing tasks without data migration. -**GSIs:** `UserStatusIndex` (PK: `user_id`, SK: `status#created_at`), `StatusIndex` (PK: `status`, SK: `created_at`), `IdempotencyIndex` (PK: `idempotency_key`, sparse). +**GSIs:** `UserStatusIndex` (PK: `user_id`, SK: `status#created_at`), `UserCreatedAtIndex` (PK: `user_id`, SK: `created_at`; the task list, newest first), `StatusIndex` (PK: `status`, SK: `created_at`), `IdempotencyIndex` (PK: `idempotency_key`, sparse), `LinearIssueIndex` (PK: `linear_issue_id`, SK: `created_at`, sparse), `JiraIssueIndex` (PK: `jira_issue_identity`, SK: `created_at`, sparse). ### TaskEvents table diff --git a/docs/src/content/docs/architecture/Security.md b/docs/src/content/docs/architecture/Security.md index 8918d1ee0..906f08d71 100644 --- a/docs/src/content/docs/architecture/Security.md +++ b/docs/src/content/docs/architecture/Security.md @@ -153,7 +153,7 @@ flowchart LR | Submission | Input validation | `validation.ts`, `create-task-core.ts` | HTTP error only | | Submission | Repo onboarding gate | `repo-config.ts` | HTTP error only | | Submission | Guardrail screening | `create-task-core.ts` | HTTP error only | -| Admission | Concurrency limit | `orchestrator.ts` | `admission_rejected` event | +| Admission | Concurrency limit | `orchestrator.ts` | `admission_queued` event | | Pre-flight | GitHub access, PAT permissions, PR access | `preflight.ts` | `preflight_failed` event | | Hydration | Guardrail prompt screening | `context-hydration.ts` | `guardrail_blocked` event | | Hydration | Budget/quota resolution | `orchestrator.ts` | Persisted on task record | diff --git a/docs/src/content/docs/decisions/Adr-013-tiered-validation-pyramid.md b/docs/src/content/docs/decisions/Adr-013-tiered-validation-pyramid.md index 2d83fb6e7..3b2ea79f1 100644 --- a/docs/src/content/docs/decisions/Adr-013-tiered-validation-pyramid.md +++ b/docs/src/content/docs/decisions/Adr-013-tiered-validation-pyramid.md @@ -4,6 +4,7 @@ title: "ADR-013: Tiered validation pyramid for agentic-first development" **Status:** proposed **Date:** 2026-05-19 +**Last-updated:** 2026-11-15 ## Context @@ -26,7 +27,7 @@ For a human, this is annoying. For an autonomous agent, this is catastrophic: - **Cascade failures** — in a stacked PR chain (ADR-001), a CI failure on PR 1 blocks PRs 2–N, multiplying the wait - **Cost amplification** — each round-trip costs inference tokens for the agent to re-read the failure, re-analyze, and re-attempt -The root cause: there is no **Tier 2** — a local, fast, high-fidelity validation layer that catches integration-level issues *before* pushing to remote. +The root cause: there is no **Tier 2** — a local, fast, high-fidelity validation layer that catches integration-level issues *before* pushing to remote. (Phase 2a of it now exists; see the table below.) ### What exists today @@ -35,7 +36,7 @@ The root cause: there is no **Tier 2** — a local, fast, high-fidelity validati | Pre-commit (Tier 0) | No fixed budget: by what is staged (measured times under Tier 0 below) | Formatting, secrets, lint and drift checks of the staged files | None — works well | | mise build (Tier 1) | 30–90s | Compile, unit tests, CDK synth, docs sync, linting | Wired as a pre-push gate (prek `pre-push` hooks run tests + security); the `mise run build` superset is available on demand | | Remote CI (Tier 3) | 5–20 min | Full matrix, security, E2E, deploy | Authoritative but slow | -| **Local integration (Tier 2)** | — | **Does not exist** | Integration-level validation without remote round-trip | +| **Local integration (Tier 2)** | About half a minute for phase 2a, on a laptop | Phase 2a only: how real handler, CLI and agent code behaves against emulated DynamoDB, S3, Secrets Manager, Cognito, STS and CloudWatch Logs | Phase 2a is an advisory check, not a required one; phases 2b–2d do not exist | ### Agentic-first motivation @@ -102,23 +103,23 @@ Status: **Implemented as a pre-push gate.** `.pre-commit-config.yaml` sets `defa **Tier 2 — Local sandbox (1–5 min, on-demand before PR)** -This tier does not exist today. It should provide: +Phase 2a exists; the rest of this tier does not. It should provide: -- Container-based integration tests against mocked AWS services (LocalStack or moto) -- CDK deploy to a local/ephemeral sandbox (validate IAM, resource creation without real cloud) +- Container-based integration tests against emulated AWS services (phase 2a uses the AWS Emulator; LocalStack and moto were the candidates when this ADR was written) +- CDK deploy to an ephemeral sandbox (validate IAM and resource creation). This part needs a real AWS account: the emulator does not evaluate IAM the way AWS does, and a missing `Allow` never fails a deployment there - Agent runtime smoke test (run the agent pipeline against a test repo in a local container) - Cross-package integration (API → handler → agent contract verification) - Policy validation (Cedar policy evaluation against test fixtures) -Status: **Gap — does not exist.** This is the primary investment needed. +Status: **Phase 2a implemented as an advisory check; phases 2b–2d are a gap.** `mise run test:integration` starts a pinned AWS Emulator in a container and runs ABCA's real handler, CLI and agent code against it, with no AWS account. The `emulator` workflow runs it on every pull request and is not a required check. ABCA's own agents cannot run it inside their container yet: the agent image has no Docker. What a green run shows and does not show, and the rules for tests in this tier, are in `scripts/aws-emulator/README.md`. Progressive build-out: | Phase | Capability | Mechanism | Catches | |-------|-----------|-----------|---------| -| 2a | Container integration tests | `mise run test:integration` → Docker Compose + LocalStack | AWS API call failures, DynamoDB schema issues, SQS message format | +| 2a | Container integration tests | `mise run test:integration` → the AWS Emulator in a container, version pinned in `scripts/aws-emulator/Dockerfile` | DynamoDB conditions, update expressions, transactions, index keys and `Limit` applied before a filter; S3 object and presigned GET behavior; Secrets Manager, Cognito sign-in, STS `AssumeRole` and CloudWatch Logs behavior; state shared between the Python agent and the TypeScript handlers. Not permissions, deployment or the AgentCore runtime | | 2b | Agent pipeline smoke | `mise run test:agent-smoke` → build agent container, run against fixture repo | Agent crashes, tool failures, prompt regressions | -| 2c | Ephemeral stack deploy | `mise run deploy:ephemeral` → CDK deploy to a disposable environment with auto-destroy | IAM permission gaps (ADR-002 preflight), resource wiring, real API behavior | +| 2c | Ephemeral stack deploy | `mise run deploy:ephemeral` → CDK deploy to a disposable environment in a real AWS account, with auto-destroy (not the emulator, which cannot show a missing permission) | IAM permission gaps (ADR-002 preflight), resource wiring, real API behavior | | 2d | Full local sandbox | `mise run sandbox` → MicroVM matching prod topology | End-to-end flow in production-equivalent isolation | **Tier 3 — Remote CI (5–20 min, authoritative, gates merge)** @@ -160,7 +161,7 @@ Residual risk after these mitigations (a malicious fork PR that passes maintaine ### Agent interaction model -Agents interact with validation tiers through skills (depends on ADR-012 for the skill model). The `validate-locally` skill and the two `mise` tasks it runs in the flow below are proposed here and do not exist yet: +Agents interact with validation tiers through skills (depends on ADR-012 for the skill model). The `validate-locally` skill and `mise run check:full` in the flow below are proposed here and do not exist yet; `mise run test:integration` exists (phase 2a): ``` Agent completes implementation @@ -182,16 +183,16 @@ The gap analysis dictates priority: | Priority | Investment | Impact | |----------|-----------|--------| | P0 | ~~Enforce Tier 1 as pre-push gate~~ **(largely done)** — test + security push gate is wired (prek `pre-push` hooks); remaining work is folding synth/docs-sync/drift into the gate | Eliminates "pushed without building" class of CI failures | -| P1 | `mise run test:integration` (Tier 2a — LocalStack) | Eliminates 60%+ of CI-only failures (AWS API contract mismatches) | +| P1 | ~~`mise run test:integration` (Tier 2a)~~ **(done as an advisory check)** — built on the AWS Emulator; remaining work is graduation to a required check (criteria under Design constraints) | Catches data-plane defects and defects in state shared between the agent and the handlers without a deployment: about one in twelve (10 of 120) of the recorded defects that passed unit tests and were found on a deployed stack. More than half of those 120 need real AWS and still do. It does not reduce CI-only failures: `build.yml` makes no AWS call | | P2 | Agent smoke test (Tier 2b) | Catches agent runtime regressions before PR | | P3 | Ephemeral stack deploy (Tier 2c) | Catches IAM/wiring issues that only surface in real deployment | | P4 | Full local sandbox (Tier 2d) | Production-equivalent local validation (long-term target) | ### Design constraints -- **Tier 2 must not require cloud credentials for basic operation** — agents running in isolation (MicroVM, CI runner) need to validate without AWS access. LocalStack/moto fills this. -- **Tier 2 must be optional until stable** — a failing Tier 2 should warn, not block, during build-out. Once stable, it becomes a gate. -- **Tier 2 must be cacheable** — container images, LocalStack state, and fixture repos should be cached between runs. An agent shouldn't rebuild the world every time. +- **Tier 2 must not require cloud credentials for basic operation** — agents running in isolation (MicroVM, CI runner) need to validate without AWS access. For phase 2a the AWS Emulator fills this: it needs Docker and no AWS account. Phase 2c is the exception and needs a real account. +- **Tier 2 must be optional until stable** — a failing Tier 2 should warn, not block, during build-out. Once stable, it becomes a gate. For phase 2a, stable means, measured over 30 days: every red run triaged; none of the last 100 pull-request and merge-queue runs red because of the emulator or the runner; p95 job duration under 5 minutes; at least one test per service in scope; the emulator pin never more than 14 days behind upstream. Then the job is added to the required checks of the `main` ruleset. +- **Tier 2 must be cacheable** — container images and fixture repos should be cached between runs (emulated state is in memory and is discarded on purpose). An agent shouldn't rebuild the world every time. - **No tier should duplicate work from a lower tier** — if Tier 0 checks formatting, Tier 1 does not re-check it. If Tier 1 runs unit tests, Tier 3 does not re-run them (it may run *additional* tests but not the same ones). ### Escape hatches @@ -219,14 +220,21 @@ Escape hatches must be explicit (noted in PR description, not silent). - (-) Pre-push gate adds 30–90s to every push (proposed mitigation: `mise run check:fast` alone for safe paths) - (!) LocalStack fidelity gaps must be documented — when Tier 2 passes but Tier 3 fails, document the divergence and add it to Tier 2's scope - (!) Tier 2 "optional until stable" phase must have a defined graduation criteria, or it stays optional forever +- (!) Phase 2a was built on the AWS Emulator, not LocalStack: the three LocalStack consequences above apply to it as written. Its known differences from AWS are kept in `scripts/aws-emulator/README.md`, and the graduation criteria asked for above are under Design constraints ## References - Issue #149 — implementation tracking for this ADR -- ADR-002 — bootstrap policies (Tier 2c validates IAM preflight locally) +- ADR-002 — bootstrap policies (Tier 2c validates the IAM preflight before a pull request, in a real AWS account) - ADR-008 — definition of done (tier requirements per DoD level) - ADR-012 (prerequisite) — operational knowledge stack; this ADR depends on 012's skill model for agent interaction with validation tiers - Current hooks: `.pre-commit-config.yaml` — the config file keeps the `pre-commit` name, but the runner is **prek** (pinned in `mise.toml` `[tools]`; `prek install --prepare-hooks` wires both `pre-commit` and `pre-push` stages). Implements Tier 0 (`pre-commit` stage) and the Tier 1 push gate (`pre-push` stage). - Current build: `mise.toml` root + package-level configs (Tier 1 implementation) -- LocalStack: https://localstack.cloud (candidate for Tier 2a) +- AWS Emulator: https://github.com/aws/aws-emulator (adopted for Tier 2a; the version is pinned in `scripts/aws-emulator/Dockerfile`) +- LocalStack: https://localstack.cloud (the candidate for Tier 2a when this ADR was written; not adopted, and not evaluated in depth) +- `docs/research/aws-emulator-local-tests.md` — the investigation behind phase 2a: what was built and measured, and what was not verified - Firecracker MicroVMs: https://firecracker-microvm.github.io (candidate for Tier 2d) + +## Changelog + +- 2026-11-15 — Phase 2a is implemented, on the AWS Emulator instead of LocalStack, as an advisory check (`mise run test:integration` and the `emulator` workflow). Replaced the estimate that it would eliminate "60%+ of CI-only failures" with what was measured, added the graduation criteria this ADR asks for, and stated that phase 2c needs a real AWS account because the emulator cannot show a missing permission (decision otherwise unchanged). diff --git a/docs/src/content/docs/developer-guide/Contributing.md b/docs/src/content/docs/developer-guide/Contributing.md index 2e15fca6f..fc39bf2a9 100644 --- a/docs/src/content/docs/developer-guide/Contributing.md +++ b/docs/src/content/docs/developer-guide/Contributing.md @@ -94,7 +94,7 @@ The `upgrade-main` GitHub workflow runs `mise run upgrade` daily and opens a PR PRs labeled `auto-approve` are approved automatically by the `auto-approve` workflow; only apply the label to automated PRs whose changes are gated by the full build (e.g. the dependency-upgrade PRs). -The tools that the gates run are not part of that upgrade. `prek`, `gitleaks`, `uv`, `semgrep`, `osv-scanner`, `grype` and `zizmor` are pinned to exact versions in the root `mise.toml` (`uv` and `trivy` in `agent/mise.toml`), and every workflow that installs mise pins the mise version (`version:` under `jdx/mise-action`). Nothing bumps these pins automatically: bump them by pull request, to a release that is at least 7 days old, and keep `uv` the same in both files. After pulling a change to a pin, run `mise install`. +The tools that the gates run are not part of that upgrade. `prek`, `gitleaks`, `uv`, `semgrep`, `osv-scanner`, `grype` and `zizmor` are pinned to exact versions in the root `mise.toml` (`uv` and `trivy` in `agent/mise.toml`), and every workflow that installs mise pins the mise version (`version:` under `jdx/mise-action`). Nothing bumps these pins automatically: bump them by pull request, to a release that is at least 7 days old, and keep `uv` the same in both files and in the `uv` image that `agent/Dockerfile` copies from. After pulling a change to a pin, run `mise install`. ### Git hooks diff --git a/docs/src/content/docs/getting-started/Deployment-guide.md b/docs/src/content/docs/getting-started/Deployment-guide.md index b418bfced..45ea26aab 100644 --- a/docs/src/content/docs/getting-started/Deployment-guide.md +++ b/docs/src/content/docs/getting-started/Deployment-guide.md @@ -455,6 +455,28 @@ STACK_NAME= mise //cdk:preflight:log-delivery -- --check-only A bare `cdk deploy` (no mise, no pipeline) does **not** run the preflight. On that path, or after the rollback above, run the check command shown under *Affects* and then follow the manual steps in [Observability — AgentCore log delivery](/sample-autonomous-cloud-coding-agents/architecture/observability#agentcore-log-delivery). +### Task list keeps its old order while a new index is built (#51) + +**Affects:** an existing stack on its first deploy of a version that adds `UserCreatedAtIndex` to the task table. A fresh stack is not affected. + +**Symptom:** For a while after the deploy, `GET /v1/tasks` (`bgagent list`, the console's task list) still returns tasks grouped by status instead of newest first, and the `ListTasksFn` log has a `UserCreatedAtIndex is not ACTIVE` warning for each request that starts a list. + +**Root cause:** CloudFormation starts creating the index and continues with the update without waiting for it, and DynamoDB does not allow a query on an index until it is `ACTIVE`. The list handler therefore asks DynamoDB for the status of the index, and reads `UserStatusIndex`, as it did before, until the answer is `ACTIVE`. This has been tested against an emulated DynamoDB and not observed on a deployed stack; how long the build takes on a given table has not been measured. + +**Resolution:** None needed. The list is newest first once the index is `ACTIVE`: + +```bash +aws dynamodb describe-table --table-name \ + --query "Table.GlobalSecondaryIndexes[?IndexName=='UserCreatedAtIndex'].IndexStatus" +``` + +Two CloudFormation limits apply to the same update. It creates one index per update, so each index a stack has not yet created (`JiraIssueIndex`, `LinearIssueIndex`, this one) needs a deploy of its own, in the order the versions added them, each once the index of the deploy before it is `ACTIVE`. And AWS recommends that an update which adds an index changes nothing else, which this version cannot follow: if the update rolls back while the index is being created, CloudFormation leaves the index in place. Delete it, wait until the status command above prints `[]`, then deploy again. DynamoDB refuses the delete in the first phase of the build; if it does, try again after a minute: + +```bash +aws dynamodb update-table --table-name \ + --global-secondary-index-updates '[{"Delete": {"IndexName": "UserCreatedAtIndex"}}]' +``` + ### AgentCore unsupported Availability Zones **Affects:** Fresh deploys in accounts whose default Availability Zones don't line up with the zones AgentCore supports for the region. diff --git a/docs/src/content/docs/getting-started/Quick-start.mdx b/docs/src/content/docs/getting-started/Quick-start.mdx index 6b2d22621..577335a69 100644 --- a/docs/src/content/docs/getting-started/Quick-start.mdx +++ b/docs/src/content/docs/getting-started/Quick-start.mdx @@ -194,7 +194,7 @@ If a task fails immediately with text like the model is **not available on your ## Step 4 - Store the GitHub token -The agent reads the GitHub PAT from **AWS Secrets Manager** at runtime. The CDK stack created an empty secret for you - now you need to put your token value in it. Replace `ghp_your_token_here` with the actual token from Step 2. Make sure `REGION` matches where you deployed - if it is empty, the AWS CLI builds a malformed endpoint URL and fails silently. +The agent reads the GitHub PAT from **AWS Secrets Manager** at runtime. The CDK stack created a secret with a generated placeholder value for you - now you need to put your token value in it. Replace `ghp_your_token_here` with the actual token from Step 2. Make sure `REGION` matches where you deployed - if it is empty, the AWS CLI builds a malformed endpoint URL and fails silently. diff --git a/docs/src/content/docs/using/Task-lifecycle.md b/docs/src/content/docs/using/Task-lifecycle.md index 96e49f5c0..58481756d 100644 --- a/docs/src/content/docs/using/Task-lifecycle.md +++ b/docs/src/content/docs/using/Task-lifecycle.md @@ -18,6 +18,9 @@ flowchart LR H --> X S --> F S --> X + S <--> Q[QUEUED] + Q --> F + Q --> X ``` The orchestrator uses Lambda Durable Functions to manage the lifecycle durably - long-running tasks (up to 9 hours) survive transient failures and Lambda timeouts. The agent commits work regularly, so partial progress is never lost. @@ -26,12 +29,13 @@ The orchestrator uses Lambda Durable Functions to manage the lifecycle durably - |---|---| | `PENDING_UPLOADS` | Initial state while presigned attachment uploads are pending confirmation | | `SUBMITTED` | Task accepted; orchestrator invoked asynchronously | +| `QUEUED` | You are at your concurrency limit; the task waits for a free slot and starts automatically. See [Concurrency limits](#concurrency-limits). | | `HYDRATING` | Orchestrator passed admission control; assembling the agent payload | | `RUNNING` | Agent session started and actively working on the task | | `AWAITING_APPROVAL` | Agent paused at a Cedar HITL gate; waiting for your `approve` or `deny` decision. See [Approval gates](/sample-autonomous-cloud-coding-agents/using/approval-gates-cedar-hitl). | | `FINALIZING` | Agent session ended; task is wrapping up (post-session hooks / PR finalization) before reaching a terminal state | | `COMPLETED` | Agent finished and created a PR (or determined no changes were needed) | -| `FAILED` | Something went wrong - pre-flight check failed, concurrency limit reached, guardrail blocked the content, or the agent encountered an error | +| `FAILED` | Something went wrong - pre-flight check failed, guardrail blocked the content, the task stayed queued for more than 24 hours, or the agent encountered an error | | `CANCELLED` | Task was cancelled by the user | | `TIMED_OUT` | Task exceeded the maximum allowed duration (~8 hours, the AgentCore max session duration; the orchestrator safety-net timer is slightly longer) | @@ -41,7 +45,7 @@ Task records in terminal states are automatically deleted after 90 days (configu ### Concurrency limits -Each user can run up to 3 tasks concurrently by default (configurable via `maxConcurrentTasksPerUser` on the `TaskOrchestrator` CDK construct). If you exceed the limit, the task fails with a concurrency message. Wait for an active task to complete, or cancel one, then retry. +Each user can run up to 10 tasks concurrently. If you exceed the limit, the task is queued (`QUEUED`) instead of failing: it starts automatically, oldest first, as your active tasks finish or are cancelled, and fails only if it is still queued 24 hours after submission. A task with a file attachment over 500 KB is checked when you confirm its uploads: if your slots are all in use at that moment, the confirmation is refused with `429 RATE_LIMIT_EXCEEDED`. Through the API, confirm again once a slot is free, within 30 minutes of submitting; after that the unconfirmed task is cancelled. `bgagent submit` does not retry the confirmation: submit the task again. There is no system-wide cap - the theoretical maximum is `number_of_users * per_user_limit`. The hard ceiling is the AgentCore concurrent sessions quota for your AWS account (check the [AWS Service Quotas console](https://console.aws.amazon.com/servicequotas/) for Bedrock AgentCore in your region). @@ -56,7 +60,7 @@ curl "$API_URL/tasks//events" -H "Authorization: $TOKEN" Available events: - **Lifecycle** - `task_created`, `session_started`, `task_completed`, `task_failed`, `task_cancelled`, `task_timed_out` -- **Orchestration** - `admission_rejected`, `hydration_started`, `hydration_complete` +- **Orchestration** - `admission_queued`, `queue_pickup`, `hydration_started`, `hydration_complete` - **Checks** - `preflight_failed`, `guardrail_blocked` - **Interactive** - `nudge_acknowledged`, `agent_milestone` - **Approvals (Cedar HITL)** - `approval_requested`, `approval_recorded`, `approval_timed_out` diff --git a/docs/src/content/docs/using/Tips-for-being-a-good-citizen.md b/docs/src/content/docs/using/Tips-for-being-a-good-citizen.md index cd832c169..475241563 100644 --- a/docs/src/content/docs/using/Tips-for-being-a-good-citizen.md +++ b/docs/src/content/docs/using/Tips-for-being-a-good-citizen.md @@ -33,4 +33,4 @@ Every task consumes model tokens, compute time, and GitHub API calls. Setting li - **Content screening** - Task descriptions and PR context are screened by Bedrock Guardrails for prompt injection. If your task is unexpectedly blocked, check the task events for a `guardrail_blocked` entry and revise your description. - **Idempotency** - If you're creating tasks via the API and might retry on network errors, include an `Idempotency-Key` header to prevent duplicate tasks. -- **Concurrency** - You share a per-user concurrency limit (default: 3 tasks). If you hit the limit, wait for a task to finish or cancel one you no longer need before submitting more. \ No newline at end of file +- **Concurrency** - You share a per-user concurrency limit (default: 10 tasks). If you hit the limit, new tasks are queued and start as active ones finish; cancel one you no longer need to free a slot. \ No newline at end of file diff --git a/knip.json b/knip.json index b4293f900..313e9ab9f 100644 --- a/knip.json +++ b/knip.json @@ -13,14 +13,18 @@ }, "workspaces": { ".": { - "entry": ["scripts/*.{js,mjs,ts}"] + "entry": ["scripts/*.{js,mjs,ts}", "scripts/aws-emulator/jest-global-setup.js", "scripts/aws-emulator/loopback-only.cjs"] }, "cdk": { - "entry": ["src/main.ts!", "src/handlers/*.ts!", "scripts/*.ts", "test/integ/integ.*.ts"], + "entry": [ + "src/main.ts!", "src/handlers/*.ts!", "scripts/*.ts", "test/integ/integ.*.ts", + "jest.emulator.config.js", "test/emulator/*.emulator.ts", "test/emulator/trace-api-shim.ts" + ], "project": ["src/**/*.ts!", "scripts/**/*.ts", "test/**/*.ts"], "ignoreDependencies": ["tsx", "@aws-cdk/integ-runner"] }, "cli": { + "entry": ["jest.emulator.config.js", "test/emulator/*.emulator.ts"], "project": ["src/**/*.ts!", "test/**/*.ts"] }, "docs": { diff --git a/mise.toml b/mise.toml index fd101a42f..f654b9465 100644 --- a/mise.toml +++ b/mise.toml @@ -27,7 +27,8 @@ node = "22.23.4" # Gate tools are pinned to exact versions so that a required check changes only # with a commit (#722, #540). Nothing bumps these automatically (Dependabot has # no mise ecosystem): bump by PR to a release at least 7 days old (the cooldown -# in .github/dependabot.yml) and keep `uv` equal to agent/mise.toml. +# in .github/dependabot.yml) and keep `uv` equal to agent/mise.toml and to the +# uv image in agent/Dockerfile. prek = "0.5.9" gitleaks = "8.30.1" # uv must be declared so it is on PATH before semgrep installs: mise's @@ -205,6 +206,46 @@ run = [ description = "Fast tier without a test run: the `lint` and `drift-prevention` tasks. Not check-only: drift-prevention fixes trailing whitespace and missing final newlines (and then fails) and regenerates the command stubs" depends = [":lint", ":drift-prevention"] +################## +#### EMULATOR #### +################## + +# Emulator-backed integration tests (ADR-013 Tier 2a): ABCA's real handler, CLI and agent code +# against a local AWS Emulator (https://github.com/aws/aws-emulator). Needs Docker and no AWS +# account. `mise run build` runs none of these tasks, only the unit tests of the guard's refusals. +# The emulator version is pinned once, in scripts/aws-emulator/Dockerfile. See +# scripts/aws-emulator/README.md for the rules and the known differences from AWS, and +# docs/research/aws-emulator-local-tests.md for the investigation behind the tier. + +[tasks."emulator:up"] +description = "Start a fresh AWS Emulator on 127.0.0.1 (builds the pinned, signature-verified image on first use)" +run = "scripts/aws-emulator/emulator.sh up" + +[tasks."emulator:down"] +description = "Stop the AWS Emulator (emulated state is in memory and is discarded)" +run = "scripts/aws-emulator/emulator.sh down" + +# Arguments after `--` are the command, for one file while iterating. Run from the repository +# root (these are root tasks); the parentheses keep the shell there: +# mise run emulator:run -- yarn --cwd cdk jest --config jest.emulator.config.js task-api +# (cd agent && ../scripts/aws-emulator/emulator.sh run uv run pytest --no-cov tests_emulator/test_secrets.py) +# For programs that use an AWS SDK. Not for AWS CLI v1, which ignores the endpoint for some services. +[tasks."emulator:run"] +description = "Run a command against the running emulator with the AWS environment replaced by the emulator's (pass it after --)" +run = "scripts/aws-emulator/emulator.sh run" + +# On failure the list stops and the emulator stays up for inspection (`docker logs`); the next +# `emulator:up` replaces it, and it is started with an idle timeout of one hour. +[tasks."test:integration"] +description = "Tier 2a: emulator-backed integration tests (cdk, cli, agent) against a fresh AWS Emulator" +run = [ + { task = "emulator:up" }, + "scripts/aws-emulator/emulator.sh run yarn --cwd cdk jest --config jest.emulator.config.js", + "scripts/aws-emulator/emulator.sh run yarn --cwd cli jest --config jest.emulator.config.js", + "cd agent && ../scripts/aws-emulator/emulator.sh run uv run pytest --no-cov tests_emulator", + { task = "emulator:down" }, +] + ################## #### SECURITY #### ################## diff --git a/osv-scanner.toml b/osv-scanner.toml index 72c04d9ac..cd7490131 100644 --- a/osv-scanner.toml +++ b/osv-scanner.toml @@ -2,12 +2,7 @@ # lockfiles in this directory. Each entry expires so the scan fails again and the # finding is re-reviewed; remove an entry as soon as a fixed release is available. -[[IgnoredVulns]] -id = "GHSA-gcqx-w48m-w2h4" -ignoreUntil = 2026-11-28 -reason = "deepmerge 4.3.1 prototype poisoning: no fixed release exists. Reached only via jest-config (test tooling), never deployed." - [[IgnoredVulns]] id = "GHSA-g3hv-75wg-m249" -ignoreUntil = 2026-12-02 -reason = "minimatch globparts DoS (fixed in 11.0.1). Every copy that works with 11.x is resolved to it; three cannot move. 10.2.5 is bundled inside aws-cdk-lib (bundleDependencies, which resolutions cannot replace; 2.275.0, the latest, still bundles ^10.2.6) and matches only repository-controlled patterns at synth time. eslint-plugin-import-x (lint-time only) imports makeRe, which minimatch 11 removed; 4.17.1, the latest, still requires ^9 || ^10. 3.1.5 is required by test-exclude 6 (jest coverage, test tooling only), which calls the CommonJS default export that minimatch dropped in 9.0." +ignoreUntil = 2026-12-16 +reason = "minimatch globparts DoS (7.0.0 and later, fixed in 11.0.1). Two affected copies are left, both in build tooling and never deployed. 10.2.5 is bundled inside aws-cdk-lib 2.261.0 (bundleDependencies, which resolutions cannot replace) and matches only patterns from CDK code and the cdk command line, at synth time. On 2026-11-16 no aws-cdk-lib release had the fix: 2.277.0 bundles 10.2.6, and the bump to 11.0.8 (aws/aws-cdk#39595, merged 2026-11-13) is not in it. 10.2.6 serves eslint-plugin-import-x 4.17.1 (lint only, patterns from the eslint configs), which imports makeRe, removed in minimatch 11. 4.18.0, the first release that accepts minimatch 11, also sorts parent imports before sibling imports in import-x/order, which fails lint on existing files; that bump is left to the dependency update that re-sorts them." diff --git a/scripts/aws-emulator/Dockerfile b/scripts/aws-emulator/Dockerfile new file mode 100644 index 000000000..b2df492c3 --- /dev/null +++ b/scripts/aws-emulator/Dockerfile @@ -0,0 +1,62 @@ +# AWS Emulator (https://github.com/aws/aws-emulator) for the local/CI integration tier (ADR-013 Tier 2a). +# Test tooling only: never part of a deployed stack or of the agent image. +# +# AWS publishes no prebuilt image, so this installs the signed Linux package. It differs from the +# user guide's five-line Dockerfile in three ways: +# - the version is pinned (the guide installs `latest`), +# - the package is verified against its detached signature and the AWS publishing key, pinned by +# fingerprint, before it is installed (the guide's `rpm -i` verifies nothing), +# - telemetry is off in the image itself, so no caller can forget to disable it. +# +# AWS_EMULATOR_VERSION is the ONE pin for the repository: scripts/aws-emulator/emulator.sh reads it +# from this line, and CI builds this same file. Bump it here and nowhere else. +# Use the three-part version from https://github.com/aws/aws-emulator/releases (versions.json lists +# a fourth component, e.g. 1.0.385.1, that the package file names do not carry). +ARG AWS_EMULATOR_VERSION=1.0.481 + +# Pinned by digest like every other external image in this repository (see agent/Dockerfile). +# The digest is a multi-platform index (linux/amd64 + linux/arm64). To bump: +# docker buildx imagetools inspect public.ecr.aws/amazonlinux/amazonlinux:2023-minimal +FROM public.ecr.aws/amazonlinux/amazonlinux:2023-minimal@sha256:158a9044f9dc0777f098b76c8b54346f6ed4560b9a6a416dec7a5ba3bc483af4 AS base + +FROM base AS verified +ARG AWS_EMULATOR_VERSION +ARG TARGETARCH +# Signature check, fail-closed. +# +# This base image ships gnupg2-minimal (no gpg-agent, no gpgv), so `gpg --import` as written in the +# user guide fails here. Dearmor the key into a keyring file and verify against that instead. +# +# VALIDSIG's last field is the primary-key fingerprint of the key that made the signature, so the +# grep asserts both "the signature is good" and "it was made by the key we pinned", whatever else +# current.asc may contain after a key rotation. A rotation therefore fails the build until the +# fingerprint is updated from the user guide ("To verify the package before you install it"). +RUN set -eu; \ + case "$TARGETARCH" in \ + amd64) arch=x86_64 ;; \ + arm64) arch=aarch64 ;; \ + *) echo "unsupported architecture: $TARGETARCH" >&2; exit 1 ;; \ + esac; \ + url="https://downloads.aws.com/aws-emulator/packages/aws-emulator/LTS/aws-emulator-${AWS_EMULATOR_VERSION}-1-${arch}.rpm"; \ + curl -fsSL --retry 3 -o /tmp/aws-emulator.rpm "$url"; \ + curl -fsSL --retry 3 -o /tmp/aws-emulator.rpm.sig "$url.sig"; \ + curl -fsSL --retry 3 -o /tmp/aws-publishing.asc https://downloads.aws.com/keys/gpg/current.asc; \ + export GNUPGHOME=/tmp/gnupg; mkdir -m 700 "$GNUPGHOME"; \ + gpg --batch --no-autostart --dearmor < /tmp/aws-publishing.asc > /tmp/aws-publishing.gpg; \ + gpg --batch --no-autostart --no-default-keyring --keyring /tmp/aws-publishing.gpg \ + --status-fd 1 --verify /tmp/aws-emulator.rpm.sig /tmp/aws-emulator.rpm \ + > /tmp/verify.status 2> /tmp/verify.log \ + || { cat /tmp/verify.log /tmp/verify.status >&2; exit 1; }; \ + grep -Eq '^\[GNUPG:\] VALIDSIG .* 98BCF336A3BE53B734E967C52E5BF49BD940F624$' /tmp/verify.status \ + || { echo "package is not signed by the pinned AWS publishing key" >&2; cat /tmp/verify.status >&2; exit 1; } + +FROM base +# Bind-mount the verified package instead of ADD/COPY so the archive (well over 100 MB) is not kept as a layer. +RUN --mount=type=bind,from=verified,source=/tmp/aws-emulator.rpm,target=/tmp/aws-emulator.rpm \ + rpm -i /tmp/aws-emulator.rpm && mkdir -p /home/emulator && chown 1000 /home/emulator +USER 1000 +ENV HOME=/home/emulator \ + EMULATOR_TELEMETRY=off +EXPOSE 9297 +# -b 0.0.0.0 so Docker can forward the port; emulator.sh publishes it on 127.0.0.1 only. +ENTRYPOINT ["aws-emulator", "-b", "0.0.0.0", "--telemetry", "off"] diff --git a/scripts/aws-emulator/README.md b/scripts/aws-emulator/README.md new file mode 100644 index 000000000..a6da2c2ce --- /dev/null +++ b/scripts/aws-emulator/README.md @@ -0,0 +1,114 @@ +# Emulator-backed integration tests + +This tier (ADR-013 Tier 2a) runs ABCA's real handler, CLI and agent code in the normal test runners, jest and pytest, with no SDK mock: the AWS SDK calls go to an [AWS Emulator](https://github.com/aws/aws-emulator) on loopback. It needs Docker and `curl`, and no AWS account. + +It is an advisory check: the [`emulator` workflow](../../.github/workflows/emulator.yml) runs it on every pull request and is not a required check. [ADR-013](../../docs/decisions/ADR-013-tiered-validation-pyramid.md) has the criteria for making it one. It does not replace the real-AWS integ smoke (`mise //cdk:integ`), which stays the authority for IAM, deployment and API Gateway wiring. The investigation behind the tier, with what was measured and what was not verified, is in [docs/research/aws-emulator-local-tests.md](../../docs/research/aws-emulator-local-tests.md). + +## Run it + +From the repository root, after `mise run install` (the mise tasks are root tasks): + +```bash +mise run test:integration # everything, on a fresh emulator: about half a minute +mise run emulator:up # or keep one running while iterating +mise run emulator:run -- yarn --cwd cdk jest --config jest.emulator.config.js task-api +(cd agent && ../scripts/aws-emulator/emulator.sh run uv run pytest --no-cov tests_emulator/test_secrets.py) +mise run emulator:down +``` + +- The suites are `cdk/test/emulator/*.emulator.ts`, `cli/test/emulator/*.emulator.ts` and `agent/tests_emulator/`. The unit runs cannot pick them up: the unit `testMatch` does not match `*.emulator.ts`, and the agent's unit run collects `tests/` only. +- The first `emulator:up` builds the image (about 1 GB) from the [Dockerfile](Dockerfile), once per version: it downloads the signed package, about 170 to 190 MB, and verifies it. +- Emulated state is in memory and there is no reset call. `emulator:up` always starts a fresh emulator, and `emulator:down` discards everything. +- The port is derived from the checkout path, so two worktrees can run the tier at the same time. The header of [emulator.sh](emulator.sh), the wrapper behind these tasks, lists the variables that override the port, the state directory, the version and the container engine. +- After a failed `test:integration` the emulator stays up for inspection (`docker logs abca-aws-emulator-`) until `emulator:down` or the next `emulator:up`. Its per-run credentials stay on disk (mode 0600) under the user cache directory, and it is started with an idle timeout of one hour. +- The `cdk` step prints the handlers' own INFO logs, among them "Drift detected" from the concurrency reconciler. They are not failures. A `test.failing` case is reported as passed for as long as the defect or emulator gap it records exists. + +## Rules for tests in this tier + +1. Rows come from the real writer and schemas from the CDK constructs. +2. Assert on stored state and on error names. Never assert on AWS message text, stream record counts or invocation counts. +3. Never wait for TTL expiry. To test expiry logic, write a row with a past `ttl` and assert what the handler decides. +4. Age the data, not the clock: the emulator rejects requests signed more than 15 minutes from its own time, so fake timers break signing. +5. One set of uniquely named tables per test file (jest) or per session (pytest), created together; a fresh user or task id per test. A new table is unusable for 3 seconds, and tables created together share that wait. +6. When code swallows an error from an operation the emulator does not implement, assert which branch ran. +7. Every expected failure or emulator-specific branch names the record it waits for: an ABCA issue or pull request for a product defect, the upstream record for an emulator gap. +8. Nothing but the emulator and loopback. Stub every endpoint that is not an AWS SDK call, and never follow a URL the emulator returns. The tooling enforces this for the Node processes the wrapper starts and for the pytest process. + +Rule 1 is not met everywhere yet. The agent suite copies its table key schemas and its session-role policy by hand from the constructs, the two `cli` fixture stacks are written by hand to match the `TaskApi` construct and the stack's GitHub token secret, and some rows are seeded by the tests. Nothing fails there when a construct changes. + +## Where a green run can be trusted + +A green run says how the code behaves against the emulator, not against AWS. Nothing in the tier is compared with real AWS, and the emulator's behavior changes between releases. + +| Trust a green run for | Do not use the tier for | +|---|---| +| DynamoDB: conditions, update expressions, transactions with per-item cancellation reasons, index keys and projections, `Limit` before filter, pagination including the 1 MB page, reserved words | Permissions of any kind. A missing grant is invisible; identity policies are evaluated in some paths and not others | +| S3 objects: put, get, head, delete, versions, presigned GET | Presigned POST policy enforcement (see the differences below) | +| Secrets Manager: version stages, delete then restore, the error names and the one message text ABCA matches | Deployment correctness of the platform stack | +| Cognito: admin user operations, password login, first-login password rotation, refresh, change password, token claims other than `iss` | The hosted UI, MFA | +| STS: `AssumeRole` with session tags returning usable credentials | The AgentCore runtime, identity vault and registry; ECS and MicroVM task lifecycles | +| CloudWatch Logs: stream creation and writes | Anything that depends on eventual consistency, `TransactionConflict` or TTL timing | + +The two columns are separate lists; rows do not pair. + +The agent suite contains tests that expect a denial: cross-tenant calls refused under the session role's policy, and roles that cannot be assumed. They are a tripwire for the agent's wiring (the session tags reach STS, and tenant data goes through the scoped session). AWS says the emulator does not evaluate policies the way IAM does, so a pass is not evidence that the deployed policy is safe, and these are the tests most likely to change with an emulator release. + +Some operations ABCA calls do not work on the emulator and stay on mocks: + +- Answered with 501 `NotImplemented`: `InvokeAgentRuntime`, `StopRuntimeSession`, `RetrieveMemoryRecords`, `GetResourceOauth2Token`, `CompleteResourceTokenAuth` and `UpdateRegistry`. ABCA catches the error from `StopRuntimeSession`, `RetrieveMemoryRecords` and `GetResourceOauth2Token` and continues, so a test of those paths is green while exercising only the fallback (rule 6). +- In the agent registry two answers stop ABCA's code, and neither has been compared with AWS. A second record under a name the registry already holds is answered with `ConflictException`, whatever its `recordVersion` (the AWS SDK documents record names as unique within a registry); ABCA publishes each version of an asset under the same name, so only the first can be published. `DeleteRegistry` is answered with `ConflictException` while the registry holds a record (the AWS SDK documents that the records are removed with the registry); the registry custom resource retries it and deletes no record, so its Delete does not complete while a record exists. +- `ApplyGuardrail` needs a test-side HTTP/1.1 request handler: the bedrock-runtime client negotiates HTTP/2 and the emulator offers only HTTP/1.1. + +## Known differences from AWS + +Recorded on emulator 1.0.481. Keep this table and the lists above current when the version pin moves or a test finds another difference. + +| Difference | Consequence | +|---|---| +| With TTL enabled, an expired item is deleted 0.5 to 1.0 seconds after expiry; AWS says typically within a few days | Code that relies on TTL deletion instead of comparing `ttl` with the clock looks correct. The `cdk` harness therefore leaves TTL off | +| A `Query` on an index that `UpdateTable` is still creating is answered; AWS does not allow it until the index is `ACTIVE`. The emulator does report the index as `CREATING`, for about 3 seconds | Code that queries an index before it is `ACTIVE` passes here and fails on AWS. Code that asks for the index status first, as the task list does, can be tested | +| Index reads always reflect the preceding write, and a transaction is never cancelled with `TransactionConflict` | A read-after-write through a GSI can never miss here, and the retry for a conflicting transaction cannot be reached | +| Throttling and partial batches occur only at the limits the emulator models, which are AWS's documented ones: a provisioned table past its units, one partition key written past 1,000 write units in a second (three puts of about 390 KB), a `BatchGetItem` past 16 MB | ABCA's on-demand tables with ordinary rows do not reach them. A test with large rows on one key can be throttled, and those branches can be exercised on purpose | +| About ten malformed expression forms are accepted, and a condition comparing an attribute with itself lets the write through | A typo of that kind passes here and is refused by AWS | +| Presigned POST: the policy and the signature are not enforced the way S3 enforces them | A test that the bucket refuses an upload outside the policy cannot be written here | +| A bucket holds at most 1,000 objects, counting every version and delete marker; a write that adds one more is refused with `ValidationException` | A listing at the default page size never has a second page, so the second page of the upload cleanup loop cannot be reached here | +| A force-deleted secret keeps its name blocked for about 0.5 seconds | Remove-then-recreate in one test needs a retry | +| `ListSecrets` returns more than 100 results in one page; ECS `RunTask` accepts overrides over 8,192 characters | Two historical ABCA defects would have passed | +| The `iss` claim of a Cognito token names the emulator, `https://127.0.0.1:/` in the tier; AWS issues `https://cognito-idp..amazonaws.com/` | A verifier that derives the issuer from the pool id, as the one in the API's authorizer does, refuses every token the emulator issues | + +## Keeping the tier away from real AWS + +The same tests with no endpoint set would call AWS with whatever credentials the shell holds, and product code also makes calls that are not AWS SDK calls. The guard is layered: + +1. **The wrapper replaces the AWS environment.** `emulator.sh run` removes every `AWS_*` variable, then sets the endpoint, the emulator's credentials file and its certificate. It also removes `GITHUB_TOKEN`, `GH_TOKEN` and `BGAGENT_API_KEY`, points `BGAGENT_CONFIG_DIR` away from `~/.bgagent`, and refuses to run anything unless the emulator answers its health route. Everything else in the caller's environment is inherited. +2. **The test configurations refuse a foreign environment.** The jest configurations (`jest-config.js`) and the pytest session (`agent/tests_emulator/conftest.py`) require `AWS_ENDPOINT_URL` to be `https://127.0.0.1:` and no `AWS_*` variable other than the ones the wrapper sets. There is no skip path, so a run cannot be green having tested nothing. +3. **The endpoint is confirmed before any test.** The jest global setup (`jest-global-setup.js`) requires the emulator's health route to answer over the certificate of this run. The pytest session requires STS, with a client built the way agent code builds one, to answer as account `000000000000`. +4. **Nothing may connect anywhere but loopback.** Product code also calls GitHub, Slack, Linear and Jira, and none of that follows `AWS_ENDPOINT_URL`. The wrapper preloads `loopback-only.cjs` into every Node process it starts, which refuses a TCP connection that leaves the machine. The agent suite installs the same rule as a Python audit hook, where it also covers datagrams and the lookup of a name. Both check themselves before any test runs. +5. **Only emulator-issued keys exist in that environment.** AWS does not recognize them. + +Most refusals of layers 2 to 4 are tested without an emulator in the unit suites, so a guard that stops making them fails the required build: `cdk/test/scripts/aws-emulator-guard.test.ts` and `agent/tests/test_emulator_guard.py`. The header of each file lists the refusals it does not cover. + +What a test author has to know: + +- A refused connection reaches the caller as an ordinary network error, so a test of code that swallows network errors has to assert that no request was attempted. When a test fails on the loopback rule, stub the call that tried to connect. Do not add hosts to the list. +- `emulator:run` is for programs that use an AWS SDK. AWS CLI v1 forces a real endpoint for `sqs`, `rds`, `docdb`, `neptune` and `health` whatever `AWS_ENDPOINT_URL` says. + +What is outside the guard: + +- Layer 4 does not cover a Python subprocess, a Node process started with an environment that drops `NODE_OPTIONS`, UDP from Node, or programs that are neither (`git`, `gh`, `uv`). No emulator test starts one of those. +- Layer 4 refuses connections, not every DNS question. In Node, code that resolves a host itself before it connects (`node:dns`, as the URL and Linear attachment downloads do) still sends a DNS query; in Python, a reverse lookup of an address does. A test that reaches such code has to stub the lookup. +- When a command the wrapper starts resolves to a mise shim, as `yarn` can inside `mise run`, mise applies its `[env]` again after the wrapper has removed the variables. An `AWS_*` variable that comes back is refused by layer 2. A token is not checked again and stays in the jest processes, where layer 4 keeps it on the machine. +- `emulator:up` runs the container engine with the caller's environment. If Docker uses the ECR credential helper for `public.ecr.aws`, an image build asks ECR Public for a token with real credentials when it pulls the base image (a read-only call; reasoned from the tooling, not observed). +- The port is published on the host's loopback interface only, but other containers on the same Docker engine can reach it. They can also reach the ports that the emulator opens for resource endpoints, which check no request signature; the wrapper does not publish them. `RunMicrovm` opens one, also when the call is refused, and no test of the tier calls it. + +## Moving the version pin + +There is one pin, the `ARG AWS_EMULATOR_VERSION` line in the [Dockerfile](Dockerfile). The wrapper reads it from there, and CI builds the same file. + +1. Run `ABCA_EMULATOR_VERSION= mise run test:integration`, with the three-part version from the emulator's [releases](https://github.com/aws/aws-emulator/releases). ABCA's own suites on the candidate version are the gate for a bump; the release notes are the second check. +2. Edit the `ARG` line, and bring the tables and lists above up to date with what changed. The suites show only what a test asserts. The other statements hold for the release that "Recorded on emulator" names: probe them again and move that line, or leave it. +3. Remove what the move leaves behind with `docker image rm abca-aws-emulator:`: the previous pin's image, and the candidate's tag from step 1, which carries the checksum of the Dockerfile before the edit. The wrapper does not remove old images. + +The image tag carries the version and a checksum of the Dockerfile, so a change to either is rebuilt. The package is verified against the AWS publishing key, pinned by fingerprint: a key rotation fails the build until the fingerprint is updated from the emulator's user guide. + +Pinning is not optional. Upstream ships several releases a day and behavior changes between them: release 1.0.382 changed the `iss` claim of Cognito tokens, which the `cli` suite asserts, and release 1.0.471 changed it back. Security fixes go into the newest release only. The exposure is small by construction: the emulator is published on host loopback only, holds no real credentials or data, and the CI job has no AWS credential and no repository secret, only the job's read-only `GITHUB_TOKEN`. diff --git a/scripts/aws-emulator/emulator.sh b/scripts/aws-emulator/emulator.sh new file mode 100755 index 000000000..ed921c5c5 --- /dev/null +++ b/scripts/aws-emulator/emulator.sh @@ -0,0 +1,142 @@ +#!/usr/bin/env bash +# AWS Emulator lifecycle and guarded command runner for the local/CI integration tier +# (ADR-013 Tier 2a). Driven by the mise tasks emulator:up, emulator:down, emulator:run and +# test:integration. `mise run build` never runs this script, only the unit tests of the other guard files. +# +# emulator.sh up build the pinned image if missing, start a FRESH emulator, wait for health +# emulator.sh down stop it (all emulated state is in memory, so this is also "reset") +# emulator.sh run run with the AWS environment replaced by the emulator's +# +# `run` is for programs that use an AWS SDK. Do not use it with AWS CLI v1: that CLI forces a real +# AWS endpoint for sqs, rds, docdb, neptune and health whatever AWS_ENDPOINT_URL says. +# +# Needs a container engine (see CDK_DOCKER below) and curl, which the health check uses. +# +# Environment: +# ABCA_EMULATOR_PORT port on 127.0.0.1. Default: derived from the checkout path, so two worktrees +# can run the tier at the same time without stopping each other's emulator. +# ABCA_EMULATOR_HOME where the emulator keeps its per-run credentials and certificate. Default is +# under the user cache directory. It is deliberately OUTSIDE the repository: the +# agent image asset fingerprints the repository root, and these files change on +# every start. +# ABCA_EMULATOR_VERSION try another emulator release for this invocation only (default: the pin). +# CDK_DOCKER container engine (default docker), same convention as cdk/mise.toml. +set -euo pipefail + +HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +ROOT=$(cd "$HERE/../.." && pwd) +ENGINE=${CDK_DOCKER:-docker} + +# The single version pin lives in the Dockerfile (ARG AWS_EMULATOR_VERSION=...). +# ABCA_EMULATOR_VERSION overrides it for one invocation, which is how a newer upstream release is +# tried before the pin is moved: ABCA_EMULATOR_VERSION= mise run test:integration +VERSION=${ABCA_EMULATOR_VERSION:-$(sed -n 's/^ARG AWS_EMULATOR_VERSION=//p' "$HERE/Dockerfile")} +[[ "$VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || { echo "emulator: bad or missing emulator version '$VERSION' (pin: $HERE/Dockerfile)" >&2; exit 1; } + +derive_port() { echo $((20000 + $(printf '%s' "$ROOT" | cksum | cut -d' ' -f1) % 10000)); } +PORT=${ABCA_EMULATOR_PORT:-$(derive_port)} +[[ "$PORT" =~ ^[0-9]+$ ]] || { echo "emulator: ABCA_EMULATOR_PORT must be a number (got '$PORT')" >&2; exit 1; } + +STATE=${ABCA_EMULATOR_HOME:-${XDG_CACHE_HOME:-$HOME/.cache}/abca-aws-emulator} +FILES=$STATE/.aws/emulator/$PORT +# The tag carries the Dockerfile's checksum as well as the version, so a change to the Dockerfile +# that keeps the version (a base-image bump, the key fingerprint) is built, not silently skipped. +IMAGE=abca-aws-emulator:$VERSION-$(cksum < "$HERE/Dockerfile" | cut -d' ' -f1) +NAME=abca-aws-emulator-$PORT +ENDPOINT=https://127.0.0.1:$PORT + +# --noproxy: a proxy configured in the shell must not be asked for a loopback address. +healthy() { curl -sf --max-time 2 --noproxy '*' --cacert "$FILES/ca.pem" "$ENDPOINT/__admin/health" >/dev/null 2>&1; } + +up() { + # Listed, not inspected: while Docker Desktop's engine sleeps (Resource Saver) it answers + # `image inspect` with "No such image", which would re-run the build after every pause. + if [ -z "$("$ENGINE" images -q "$IMAGE" 2>/dev/null)" ]; then + echo "emulator: building $IMAGE (once per version; downloads and verifies the signed package)" + # Dockerfile on stdin: no build context is sent. + "$ENGINE" build --build-arg AWS_EMULATOR_VERSION="$VERSION" -t "$IMAGE" - < "$HERE/Dockerfile" + fi + # Pre-create the shared directory; otherwise Docker on Linux creates it root-owned and the emulator, + # which runs as the caller, cannot write its files there. + mkdir -p "$STATE/.aws/emulator" + "$ENGINE" rm -f "$NAME" >/dev/null 2>&1 || true + # On Linux the files must belong to the caller; Docker Desktop (macOS) maps ownership itself. + local user=() + if [ "$(uname -s)" = Linux ]; then user=(--user "$(id -u):$(id -g)"); fi + # -e HOME makes the emulator write the same paths inside the container as on the host. + # 127.0.0.1 on the publish side keeps the emulator off the host's network interfaces (it binds + # 0.0.0.0 in the container). Other containers on the same engine can still reach it. + # ${user[@]+...}: an empty array is "unbound" under `set -u` on the bash 3.2 that macOS ships. + "$ENGINE" run -d --name "$NAME" ${user[@]+"${user[@]}"} --memory=2g --memory-swap=2g \ + -p "127.0.0.1:$PORT:$PORT" -e HOME="$STATE" \ + -v "$STATE/.aws/emulator:$STATE/.aws/emulator" \ + "$IMAGE" -p "$PORT" --idle-timeout 3600 >/dev/null + for _ in $(seq 120); do + if healthy; then echo "emulator: $VERSION ready on $ENDPOINT"; return 0; fi + sleep 0.25 + done + echo "emulator: did not become healthy on $ENDPOINT" >&2 + "$ENGINE" logs "$NAME" 2>&1 | tail -20 >&2 + exit 1 +} + +down() { + # SIGTERM first so the emulator deletes its credentials and certificate; then remove the container. + "$ENGINE" stop -t 5 "$NAME" >/dev/null 2>&1 || true + "$ENGINE" rm -f "$NAME" >/dev/null 2>&1 || true + echo "emulator: stopped ($NAME)" +} + +# Replace the AWS environment of this shell with the emulator's. EVERY AWS_* variable goes, not a +# hand-picked list: that also covers AWS_ENDPOINT_URL_, AWS_IGNORE_CONFIGURED_ENDPOINT_URLS, +# AWS_ROLE_ARN / AWS_WEB_IDENTITY_TOKEN_FILE and the container-credential variables an agent runtime +# sets. Everything outside that namespace is inherited, apart from the tokens removed below. +emulator_env() { + local name + while IFS= read -r name; do unset "$name"; done < <(compgen -e | grep -E '^AWS_' || true) + # Real credentials for other services have no business in a run that only talks to loopback. + unset GITHUB_TOKEN GH_TOKEN BGAGENT_API_KEY + export AWS_ENDPOINT_URL=$ENDPOINT + export AWS_SHARED_CREDENTIALS_FILE=$FILES/emulator_credentials + export AWS_CONFIG_FILE=$FILES/config + export AWS_CA_BUNDLE=$FILES/ca.pem + export NODE_EXTRA_CA_CERTS=$FILES/ca.pem + export AWS_EC2_METADATA_DISABLED=true + export AWS_DISABLE_HOST_PREFIX_INJECTION=true + export AWS_REGION=us-east-1 AWS_DEFAULT_REGION=us-east-1 + # A proxy configured in the shell must not be asked for a loopback address. + export NO_PROXY="127.0.0.1,localhost${NO_PROXY:+,$NO_PROXY}" + export no_proxy="127.0.0.1,localhost${no_proxy:+,$no_proxy}" + # Not an AWS variable, but the same hazard: without this the CLI reads ~/.bgagent, which holds + # the API URL and tokens of the developer's REAL deployment. + export BGAGENT_CONFIG_DIR=$STATE/bgagent + # The variables above only say where AWS SDK calls go. This makes every Node process started + # from here refuse any connection that would leave the machine (see loopback-only.cjs); the + # Python suite installs the same rule itself (agent/tests_emulator/conftest.py). + export NODE_OPTIONS="--require \"$HERE/loopback-only.cjs\"${NODE_OPTIONS:+ $NODE_OPTIONS}" +} + +# Refuse to run anything unless an emulator started by `up` is answering on this port. +guard() { + { [ -r "$AWS_SHARED_CREDENTIALS_FILE" ] && healthy; } \ + || { echo "emulator: refusing to run: no healthy emulator on $ENDPOINT (run: mise run emulator:up)" >&2; exit 1; } +} + +# Without curl the health check fails silently and a running emulator is reported as unhealthy. +need_curl() { + command -v curl >/dev/null || { echo "emulator: curl is required (the health check uses it)" >&2; exit 1; } +} + +case "${1:-}" in + up) need_curl; up ;; + down) down ;; + run) + shift + [ $# -gt 0 ] || { echo "usage: emulator.sh run " >&2; exit 2; } + need_curl + emulator_env + guard + exec "$@" + ;; + *) echo "usage: emulator.sh up | down | run " >&2; exit 2 ;; +esac diff --git a/scripts/aws-emulator/jest-config.js b/scripts/aws-emulator/jest-config.js new file mode 100644 index 000000000..2c84f3f23 --- /dev/null +++ b/scripts/aws-emulator/jest-config.js @@ -0,0 +1,45 @@ +// Builds the jest configuration for a package's emulator-backed tests (ADR-013 Tier 2a) from that +// package's own unit-test configuration. Used by cdk/jest.emulator.config.js and +// cli/jest.emulator.config.js; run through `mise run test:integration`. +// +// The tests are named *.emulator.ts, which the unit configurations' testMatch does not match, so +// a unit run cannot pick them up. They make real AWS SDK calls: with no endpoint set they would +// call AWS with whatever credentials the shell holds. So this refuses to produce a configuration +// unless the AWS environment is the one scripts/aws-emulator/emulator.sh builds, and the +// configuration it produces confirms, before any test file loads, that the loopback-only preload +// is in force and that the endpoint is that emulator (jest-global-setup.js). + +const path = require('node:path'); + +const LOOPBACK_EMULATOR = /^https:\/\/127\.0\.0\.1:\d+$/; +// What emulator.sh sets. Anything else in the AWS_* namespace (a profile, keys, a per-service +// endpoint, AWS_IGNORE_CONFIGURED_ENDPOINT_URLS) could send a call somewhere other than the +// emulator, or sign it with real credentials. +const EXPECTED = new Set([ + 'AWS_ENDPOINT_URL', 'AWS_SHARED_CREDENTIALS_FILE', 'AWS_CONFIG_FILE', 'AWS_CA_BUNDLE', + 'AWS_EC2_METADATA_DISABLED', 'AWS_DISABLE_HOST_PREFIX_INJECTION', 'AWS_REGION', 'AWS_DEFAULT_REGION', +]); + +module.exports = function emulatorConfig(unitConfig) { + const endpoint = process.env.AWS_ENDPOINT_URL ?? ''; + const strays = Object.keys(process.env).filter((name) => name.startsWith('AWS_') && !EXPECTED.has(name)); + if (!LOOPBACK_EMULATOR.test(endpoint) || strays.length > 0) { + throw new Error( + `Emulator tests need AWS_ENDPOINT_URL=https://127.0.0.1: and no other AWS configuration ` + + `(AWS_ENDPOINT_URL='${endpoint}'${strays.length > 0 ? `; unexpected: ${strays.join(', ')}` : ''}). ` + + 'Run them with: mise run test:integration', + ); + } + // A unit configuration may carry a globalSetup that strips the AWS environment so that unit + // tests cannot reach AWS (the CLI's does, from #1035 on). That environment is what these tests + // run on, so it is replaced; everything else is inherited. + return { + ...unitConfig, + testMatch: ['/test/emulator/**/*.emulator.ts'], + globalSetup: path.join(__dirname, 'jest-global-setup.js'), + // Coverage thresholds are a property of the unit suite; a handful of files cannot meet them. + collectCoverage: false, + // The unit run's JUnit report lives in the same directory; do not overwrite it. + reporters: ['default'], + }; +}; diff --git a/scripts/aws-emulator/jest-global-setup.js b/scripts/aws-emulator/jest-global-setup.js new file mode 100644 index 000000000..2e8eaf61d --- /dev/null +++ b/scripts/aws-emulator/jest-global-setup.js @@ -0,0 +1,54 @@ +// Jest globalSetup for the emulator-backed tests: runs once, before any test file is loaded, and +// stops the run unless two things hold. +// +// 1. loopback-only.cjs is preloaded and refuses a connection that leaves this machine. The +// environment only says where AWS SDK calls go; that preload is what keeps everything else +// (and an SDK client a profile setting has pointed back at AWS) on this machine. +// 2. The endpoint really is the AWS Emulator this environment belongs to. Only an emulator answers +// `ok` on /__admin/health, and only the one that wrote the certificate named by +// NODE_EXTRA_CA_CERTS passes the TLS handshake. A loopback address that is some other local +// service fails here instead of receiving a suite's CreateTable calls. +// +// Deliberately free of dependencies: this file belongs to no package. + +const https = require('node:https'); +const net = require('node:net'); + +/** True when the preload is in force. Sends nothing either way: with the preload, connect throws before the name is resolved. */ +function loopbackOnly() { + if (net.Socket.prototype.connect.name !== 'loopbackOnlyConnect') return false; + const probe = new net.Socket(); + try { + probe.connect(443, 'loopback-guard-check.invalid'); + return false; + } catch { + return true; + } finally { + probe.destroy(); + } +} + +module.exports = function requireEmulator() { + if (!loopbackOnly()) { + throw new Error( + 'Emulator tests need the loopback-only preload (scripts/aws-emulator/loopback-only.cjs), and it is not in force. ' + + 'Run them with: mise run test:integration', + ); + } + const endpoint = process.env.AWS_ENDPOINT_URL; + const refuse = (why) => new Error(`No AWS Emulator at ${endpoint} (${why}). Start one with: mise run emulator:up`); + return new Promise((resolve, reject) => { + const request = https.get(`${endpoint}/__admin/health`, { timeout: 3000 }, (response) => { + let body = ''; + response.setEncoding('utf8'); + response.on('data', (chunk) => { body += chunk; }); + response.on('end', () => { + if (response.statusCode === 200 && body.trim() === 'ok') resolve(); + else reject(refuse(`its health route answered ${response.statusCode}`)); + }); + }); + // An endpoint that accepts and never answers fails in seconds, not at a test's timeout. + request.on('timeout', () => request.destroy(new Error('no answer within 3 s'))); + request.on('error', (error) => reject(refuse(error.message))); + }); +}; diff --git a/scripts/aws-emulator/loopback-only.cjs b/scripts/aws-emulator/loopback-only.cjs new file mode 100644 index 000000000..b3f7dc48f --- /dev/null +++ b/scripts/aws-emulator/loopback-only.cjs @@ -0,0 +1,49 @@ +// Preloaded into every Node process that emulator.sh starts (NODE_OPTIONS=--require): jest and +// its workers, tsx, the bgagent CLI. A child process gets it through the inherited NODE_OPTIONS, +// so one started with an environment of its own does not. +// +// The emulator tests make real network calls, and the only place they may go is this machine. +// The environment points the AWS SDK at the emulator; it does not govern anything else. Product +// code also calls GitHub, Slack, Linear and Jira, fetches a token-verification key set from the +// real Cognito host, and opens a hand-signed WebSocket, none of which follow AWS_ENDPOINT_URL. +// Every TCP connection out of a Node process (http, https, http2, fetch, WebSocket, the AWS SDK) +// goes through net.Socket.connect, so that is where one that would leave the machine is refused, +// before a name is resolved or a packet is sent. Pipes are untouched. UDP (node:dgram) does not +// pass through here and is not covered; no ABCA code uses it. Nor does a name that code resolves +// itself (node:dns): the URL and Linear attachment downloads do that before they connect, so a +// test that reaches them has to stub the lookup. +// +// The refusal reaches the caller as an ordinary network error. A test of code that swallows +// network errors therefore has to assert that no request was attempted. +// +// When a test fails here, stub the call that tried to connect. Do not add hosts to the list. +// jest-global-setup.js checks, by this function's name and by a refused probe, that this is loaded. +'use strict'; + +const net = require('node:net'); + +const LOOPBACK = new Set(['localhost', '127.0.0.1', '::1', '::ffff:127.0.0.1']); + +/** The TCP host a connect call targets, or undefined for a pipe. */ +function tcpHost(args) { + // net.connect() hands over one normalized [options, listener] array, socket.connect() the caller's arguments. + const [first, second] = Array.isArray(args[0]) ? args[0] : args; + if (typeof first === 'object' && first !== null) { + // http's agent passes `path: null` for TCP; like node, only a non-empty path means a pipe. + return first.path ? undefined : first.host || 'localhost'; + } + if (typeof first === 'string' && Number.isNaN(Number(first))) return undefined; + return typeof second === 'string' && second ? second : 'localhost'; +} + +const connect = net.Socket.prototype.connect; +net.Socket.prototype.connect = function loopbackOnlyConnect(...args) { + const host = tcpHost(args); + if (host !== undefined && !LOOPBACK.has(host)) { + throw new Error( + `Emulator tests must not open a connection that leaves this machine, and this one tried to reach ${host}. ` + + 'Stub the call that sends the request (see scripts/aws-emulator/loopback-only.cjs).', + ); + } + return connect.apply(this, args); +};