Repository navigation
Conversation
Per-user concurrency was a counter incremented on admission and decremented on completion; retries and races (finalizer replay, cancel vs completion, a lost DynamoDB reply, the stranded-task reconciler) could release a seat twice or never. - Each admitted task carries a concurrency_slot marker (held -> released). acquireTaskSlot / releaseTaskSlot (shared/task-concurrency.ts) change the marker and the counter in one transaction: acquire needs SUBMITTED with no marker and room under the cap; release needs a held marker on a terminal task. Lost replies are recovered from the marker; transaction conflicts retry with bounded jitter. - Admission, finalization (release in finally), failTask, the orchestrator's early-return paths and the stranded-task reconciler all release through the marker; no handler decrements active_count directly. confirm-uploads no longer reserves at submit; the orchestrator owns admission. - A held task can never be re-queued (SUBMITTED -> QUEUED and the admission queue require no marker). - An approval wait that outlives the poll window finalizes to FAILED. It used to attempt the invalid AWAITING_APPROVAL -> TIMED_OUT, leave the task active and still free its seat. A finalization that cannot reach a terminal state now throws and is retried, keeping the seat. - The concurrency reconciler reads counters, then strongly reads every reservation, repairs only under the observed reservation_version, and releases terminal reservations left by interrupted cleanup. Users with unmarked active tasks (admitted before this change) are skipped until they settle. - DynamoDB Local race suite (15 cases) runs when ABCA_DDB_LOCAL_ENDPOINT is set; ORCHESTRATOR.md documents the scheme and the upgrade/drain note.
1 of 7 tasks
5 tasks done
ClintEastman02
pushed a commit
to ClintEastman02/sample-autonomous-cloud-coding-agents
that referenced
this pull request
Nov 17, 2026
…s-samples#1048) * test(tooling): add the AWS Emulator integration tier (ADR-013 Tier 2a) ADR-013 marks Tier 2a (container integration tests between the unit build and remote CI) as "does not exist". This adds it in one narrow shape: ABCA's real handler, CLI and agent code runs in jest and pytest as usual, and only its AWS SDK calls go to a pinned AWS Emulator (https://github.com/aws/aws-emulator) on loopback. It needs Docker and no AWS account. It does not replace the real-AWS integ smoke: IAM, deployment and the AgentCore runtime are outside what an emulator can show. What is added: - scripts/aws-emulator/: a Dockerfile that pins the emulator version and verifies the package signature, a wrapper (up, down, run) that replaces the AWS environment with the emulator's, a jest configuration builder and global setup that refuse any other environment, and a Node preload that refuses connections leaving the machine. - cdk/test/emulator: the task API handlers, the concurrency reconciler and the orchestrator's admission and finalize functions on tables created from the CDK constructs. Four tests are test.failing witnesses of defects on main (#51 twice, #1003, and the reconciler's status list that PR #1009 rewrites). - cli/test/emulator: configure, login, token refresh and password change against a Cognito pool created through emulated CloudFormation. - agent/tests_emulator: progress events, trace upload, secrets, CloudWatch Logs, the tenant-scoped session, the approval transactions, and the trace round trip of #61 (agent upload, get-trace-url handler, bgagent trace download). - mise tasks emulator:up, emulator:down, emulator:run and test:integration. None is reachable from `mise run build`. The unit runs cannot pick these tests up, by naming and location: the jest files are *.emulator.ts, which the unit testMatch does not match, and the agent suite sits beside tests/, the only directory the unit run collects. knip.json names the tier's entry files (the two emulator jest configurations, the suites, the trace shim, the global setup and the Node preload), which the dead-code check cannot reach from the unit entry points. Verified at this commit as first made, on main c8fcdb08: - `mise run test:integration` from the repository root, in a login shell that exports a real AWS profile: 11 cdk, 5 cli and 42 agent tests pass in 29 s, emulator start and stop included. - `uvx ruff check tests_emulator` and `uvx ruff format --check tests_emulator` pass in agent/. - scripts/aws-emulator/emulator.sh is committed with mode 100755. After the rebase onto 8697c821 (main with #1035) the tier was run again at the head of the series, not at this commit. Refs #1041 * test(tooling): test the emulator guard's refusals The emulator tier keeps itself away from real AWS with a layered guard: the jest configuration and the pytest session refuse any AWS environment that is not the wrapper's, both confirm the endpoint before a test runs, and a Node preload and a Python audit hook refuse a connection that leaves the machine. None of these refusals had a test; they had only been tried by hand. The tier is an advisory check, so a guard that stops refusing has to fail the required build instead. Two unit suites now run the real guard files, each case in a child process whose environment is built from nothing: - cdk/test/scripts/aws-emulator-guard.test.ts (16 cases): the jest configuration, the global setup and the loopback-only preload. - agent/tests/test_emulator_guard.py (4 cases): the environment check, the audit hook and the session fixture of agent/tests_emulator/conftest.py. Every input is harmless if the guard under test is broken: loopback ports, 127.0.0.2, .invalid names answered by a stub resolver inside the child, no credentials. Each file's header lists the refusals it does not make happen. With them, three small corrections to the guard's own files, and the comments in mise.toml and emulator.sh that describe the tier: - emulator.sh says so when curl is missing (up and run). Without curl the health check failed silently and a running emulator was reported as unhealthy. - The audit hook's event list named socket.gethostbyname_ex, an event CPython does not raise (gethostbyname_ex raises socket.gethostbyname). The name is removed; the call is still refused. - Comments now say what the guard does not cover: a name that Node code resolves itself (node:dns), and a reverse lookup of an address in Python. Both can only produce a DNS question. Verified: - Both suites pass on macOS (jest 16, pytest 4), through a scrubbed environment and from a shell that exports a made-up AWS profile and access key. - Against copies of the guard files with one weakening each, the suites fail: 24 JavaScript and 22 Python weakenings each failed the expected cases before the last three cases were added, and the weakening behind each of those three fails it. - On Linux (arm64): before the last three cases were added, both suites passed in an Ubuntu 24.04 container as an unprivileged user, as root and with no network interface but loopback. The final pytest file passes in a Python 3.13 container without network, as root and as an unprivileged user. The jest cases added last have run under jest on macOS only. - `mise run build` runs both files; `mise run test:integration` does not. Refs #1041 * fix(cdk): add an index for a user's tasks by creation time (#51) The only index on the task table that is keyed by user sorts on status_created_at, which is `<status>#<time the status was entered>`. A descending read of it returns a user's tasks grouped by status, not newest first, which is half of #51. The issue recommends a second index, UserCreatedAtIndex (user_id, created_at); this adds it, with projection ALL, like UserStatusIndex and StatusIndex. ORCHESTRATOR.md lists it, with the two issue indexes its list had missed. Nothing reads the index yet. The next commit switches the task list to it, and covers the time a deployed stack takes to build the index. The index is declared last. Declared next to UserStatusIndex, CDK moves `created_at` ahead of `status` in the synthesized attribute definitions; declared last, the template of a deployed table differs by one appended index and nothing else. For a deployed stack: CloudFormation creates one index per update, so each index a stack has not yet created (JiraIssueIndex, LinearIssueIndex, this one) needs a deploy of its own. The index is the third that copies the full task row, written on every task write. Its cost was not measured. Verified: - cdk/test/constructs/task-table.test.ts passes (16 tests); with task-table.ts put back, two fail: the new test and the index-name constants test, which gained an assertion. - The synthesized table differs from main's by one appended GlobalSecondaryIndexes entry; attribute definitions and the five existing indexes are unchanged. - The existing grant already covers it: ListTasksFn's policy allows dynamodb:Query on the table's `index/*`. Refs #1041 Refs #51 * fix(api): list tasks newest first and fill filtered pages (#51) GET /v1/tasks read UserStatusIndex with the page size as DynamoDB `Limit`. Two defects followed, both in #51: - Order. The index sorts by status first, so the list came back grouped by status. The contract says newest first. - Filters. `Limit` bounds the rows read, not the rows matched, so a status or repo filter saw only the first page of rows. A user whose matching task was not among them got an empty page, with has_more true. The handler now reads UserCreatedAtIndex with the loop list-api-keys has used since #579: read one row more than the page, keep querying until the page is full or the index is exhausted, at most ten queries per request. The token is the key of the last task returned when the page was trimmed, and DynamoDB's own cursor when the ten-query cap stopped the read. A page can therefore still be short or empty while has_more is true; API_CONTRACT.md now says so. The status filter stays a FilterExpression on UserCreatedAtIndex. The key condition #51 proposes for it reads UserStatusIndex, whose order inside a status is the time the status was entered, not the creation time, and a filter on two statuses would need a query for each. ListTasksFn gets the construct's standard API-handler settings, 15 s and 256 MB, in place of Lambda's 3 s / 128 MB: task rows are large and a filtered list now makes up to ten queries of up to 1 MB each. The two emulator witnesses of #51 are now plain tests. The status filter one seeds one more task, so that the match lies beyond the first query and the loop runs against a real engine. Deployment: on a stack that is already deployed, CloudFormation updates this function without waiting for the new index, and DynamoDB does not allow a query on an index until it is ACTIVE. AWS documents both. Its API reference lists ResourceNotFoundException for a resource that is not ACTIVE and users report a ValidationException, so the handler does not wait for a refusal: it asks DescribeTable for the status of the index and reads UserStatusIndex, as it did before, until the answer is ACTIVE. Until then the list works and keeps its old order, with a warning in the log for each request that starts a list. An ACTIVE answer is remembered for the life of the execution environment. ListTasksFn's policy already allows the call (grantReadData); a construct test now pins that. A cursor is valid only on the index that issued it, so one that carries status_created_at keeps reading UserStatusIndex. A token issued before the deploy is such a cursor and is still accepted. DEPLOYMENT_GUIDE.md has the entry. The tier walks one table through that deploy: created without the index, the index added with UpdateTable, the index ACTIVE. The emulator reports the new index as CREATING for about three seconds and answers a query on it meanwhile, which AWS does not allow; the tier's README, added later in this series, lists that difference. Known limits: - `bgagent list` does not follow next_token, so a filter whose matches lie beyond ten queries prints an empty list with "(More results available)". - A cursor of UserCreatedAtIndex presented to an execution environment that has not been told the index is ACTIVE is answered 500. - An execution environment that remembers the index as ACTIVE answers 500 if the index is then removed, until it is replaced. The check could be repeated after a failure, but then any failed request would make a warm function depend on DescribeTable again. - The status check is needed for the deploy that adds the index only. Once every deployed stack has the index it can be removed. Verified: - cdk/test/handlers/list-tasks.test.ts passes (25 tests); with list-tasks.ts put back, 12 fail. The ListTasksFn settings test in cdk/test/constructs/task-api.test.ts fails without the construct change. - Emulator: cdk/test/emulator/task-api.emulator.ts passes (7 tests); with list-tasks.ts put back, the three #51 tests fail. - The handler weakened nine ways. The unit suite catches each and the emulator suite six: the index taken to be ACTIVE without asking, CREATING counted as ready, a cursor that no longer chooses its index, a trimmed page's cursor carrying the created_at value under status_created_at, the status asked for another table, and the loop cut to one query; unit only: ACTIVE not remembered, an index being updated or deleted counted as ready, and the warning removed. - On the emulator, with the real handlers: 120 tasks over 40 timestamps at six page sizes, with no filter, one and two statuses, a repository, and both, on a table with every index and on one without UserCreatedAtIndex; on the first table a 1,050-row list whose only match is its last row, tasks added and cancelled between pages, and rows of about 350 KB; on the second the index added between two pages. No task was repeated or skipped, and no query named UserCreatedAtIndex before DescribeTable had answered ACTIVE. - Not verified on AWS: the deploy itself, how long the index takes to become ACTIVE, and the latency of ten queries on Lambda. Refs #1041 Fixes #51 * fix(api): fill filtered pages of the webhook list GET /v1/webhooks has the defect that its twin, list-api-keys, has avoided since #579: it filters out revoked webhooks after `Limit`, so a user whose active webhooks sort behind a page of revoked ones got an empty page with has_more true. Revoked webhooks stay in the table for 30 days, and `bgagent webhook list` does not follow the token. The handler now uses the loop of the previous commit; the token is the key of the last webhook returned when the page was trimmed. ListWebhooksFn keeps Lambda's 3 s / 128 MB, as ListApiKeysFn has with this loop since #579: webhook rows are small. The latency of ten queries there was not measured. Verified: - cdk/test/handlers/list-webhooks.test.ts passes (10 tests); with list-webhooks.ts put back, 4 fail. The tests also fail for a cursor that is not advanced and for a next_token that is ignored. - On the emulator, with the real handler: two active webhooks behind three revoked ones at limit 2 came back empty before and both come back now; 83 webhooks at five page sizes, with and without revoked ones, none repeated or skipped. Refs #1041 * fix(api): pass the per-user concurrency cap to confirm-uploads confirm-uploads reads the per-user cap from MAX_CONCURRENT_TASKS_PER_USER, and the TaskApi construct never set that variable on its function, so the handler admitted against its fallback of 3 while every other path admits against 10. A user with three active tasks got 429 when confirming a task with attachments and was admitted everywhere else. The construct now sets the variable on ConfirmUploadsFn from the same value GetTaskFn gets, held in one const so that the constructor gains no branch. Two things this does not change: - Until #1009, a confirmed attachment task holds two seats (one taken by confirm-uploads, one by the orchestrator's admission), so the limit met on that path stays below the cap. - AgentStack passes its cap to the orchestrator and not to TaskApi, which uses its own default of 10. The two agree today; the prop's documentation says they must. Verified: - cdk/test/constructs/task-api.test.ts passes (54 tests); with task-api.ts put back, the two new tests fail ("10" and "5" expected, undefined received). - In the synthesized AgentStack every function that reads the variable now receives "10". Refs #1041 * fix(cli): recognise a GitHub token by its format `bgagent platform doctor` and `bgagent github set-token` decided that a token was configured when the secret held anything that did not start with `{`, on the assumption that CDK seeds a JSON placeholder. It does not: a secret declared without a value gets a generated 32-character password. On a fresh stack the doctor therefore passed the token check before any token existed, and the first `set-token` warned about overwriting one. isGithubTokenConfigured now accepts what a GitHub token looks like: one of the prefixes GitHub documents, or the 40 hex digits of the format that preceded them. The CDK side is left alone on purpose: changing how the secret is generated makes CloudFormation write a new version, which would replace a stored token on every existing stack. `bgagent github set-webhook-secret` used the same test to say whether a signing secret was already configured. A signing secret is chosen by the operator, so no rule can tell it from the generated password. The command now says, every time, that it replaces the stored secret, and no longer reads the secret first. Consequences worth knowing: - A stored value in a format the rule does not know reads as not configured: the doctor fails the check (its text now names that case), and `set-token` replaces the value without the overwrite warning. - QUICK_START said the stack creates an empty secret; it creates one with a generated placeholder. Verified: - cli/test/commands/github-token.test.ts and the new github.test.ts pass (29 tests); with github-token.ts and commands/github.ts put back, 4 fail. All six documented prefixes and both anchors of the pattern are pinned. No test pins the doctor's new text. - Emulator: the new cli/test/emulator/github-token-seed.emulator.ts creates a stack whose secret CloudFormation fills. It passes, and fails with github-token.ts put back. On 40 such stacks the old rule called every generated value configured and the new rule none. - `set-token` and `set-webhook-secret` run end to end on the emulator with piped input: no warning on first use, a warning on the second `set-token`, the notice on every `set-webhook-secret`. Refs #1041 * docs: replace admission_rejected and the failed-at-limit examples Since #441 a task over the per-user limit is queued, not failed. Some documentation still described the earlier behaviour: - SECURITY.md, OBSERVABILITY.md, INTERACTIVE_AGENTS.md and the agent-debugger plugin file named admission_rejected, an event #441 removed. They name admission_queued, and OBSERVABILITY.md also queue_pickup; neither carries user_id, so OBSERVABILITY.md no longer says that every event does. INTERACTIVE_AGENTS.md said as well that the orchestrator answers 429 over quota; it parks the task as QUEUED. - The failed-task examples in API_CONTRACT.md and cli/README.md showed "User concurrency limit reached", which no task has carried since #441. They show a pre-flight failure, with the classifier's own fields for that message. The category lists beside the two examples, and the one in ORCHESTRATOR.md, gain `blocked`, which the classifier defines. Verified: - Each sentence against the code it describes: where admission_queued and queue_pickup are emitted, the 24 hours of the queue, the pre-flight message and its classification (the classifier was run on the message), and the ten categories. - The mirrors are regenerated with `mise //docs:sync`; the Markdown lint and the link check pass. Refs #1041 * fix(cli): ops ages by time in status and shows the deployed cap Two defects in `bgagent ops`, and the documentation that repeated the second. stuck-tasks aged every row by its creation time. Since #441 the stranded-task reconciler it mirrors ages by time in the current status, so the command listed tasks the reconciler would leave alone: a task picked up from the admission queue a minute ago, or one paused for approval ten minutes ago, whatever its age. It now reads the timestamp inside status_created_at, falls back to created_at, and skips rows younger than the threshold, line for line as the reconciler does. `age_seconds` in `--output json` changes meaning accordingly: time in the current status, not time since creation. concurrency printed a default limit of 3. The stack deploys 10. The default is now 10, and a test reads the constant in cdk/src/stacks/agent.ts so that the two cannot drift again. The same number was stale in the documentation, and so was what happens at the limit (see the previous commit). - cli/README.md, USER_GUIDE, COST_MODEL, API_CONTRACT, ORCHESTRATOR and the troubleshoot skill say 10 where they said 3 or "3-5". cli/README.md also says what AGE(s) measures. - The user guide's task lifecycle has the QUEUED status, in the diagram and the table; its FAILED row and its event list no longer name a concurrency failure that does not happen. - API_CONTRACT describes the queue for the orchestrator's admission path and lists the events the code emits (admission_queued, queue_pickup). - The user guide no longer calls the cap configurable on the TaskOrchestrator construct: AgentStack sets it as a constant. It also says that a refused confirmation can be retried for 30 minutes only, after which the unconfirmed task is cancelled. Verified: - cli/test/commands/ops-queries.test.ts and ops.test.ts pass (22 tests); with ops-queries.ts put back, 3 fail. - On the emulator, beside the real reconciler on one table of 16 rows in the shapes the writers leave: the command listed exactly the nine tasks the reconciler then failed, with the same ages. - Each documentation sentence was checked against the code it describes; the mirrors are regenerated with `mise //docs:sync`. Refs #1041 * fix(agent): approval transitions maintain status_created_at status_created_at on a task row is `<status>#<time the status was entered>`. Twelve of the sixteen writers of `status` rewrite it. The agent's two approval transitions did not (nor did the two writers the next two commits fix), so a task paused for approval kept `RUNNING#<start of RUNNING>`. The stranded-task sweep ages a paused task by that timestamp. A task that had been running for two hours was therefore failed "Approval stranded" by the next sweep (every five minutes) after it opened a gate: the user's approval was refused with 409, and the agent went on to open a pull request for a task reported FAILED. Both transitions now write the attribute, in the format write_running uses: AWAITING_APPROVAL#<now> at the request, RUNNING#<now> at the resume. Nothing in the contract between the agent and the handlers changes; the attribute and its format already exist. Also here, because they follow from the same attribute: - The reconciler witness in the cdk emulator suite seeds what the agent now writes. - Two docstrings gave `bga list` ordering as the reason to keep the attribute in sync. The list no longer reads it; they name the readers that remain. For whoever merges second: #904 edits the resume expression on the same line (keep both attributes), and the TypeScript writer that #1013 adds for cloud workers needs the same attribute, or the defect returns for them. Verified: - agent/tests/test_task_state.py passes (66 tests); with task_state.py put back, the two new tests fail. - Emulator: tests_emulator/test_approval_transactions.py passes (7 tests); with task_state.py put back, 2 fail. - End to end on the emulator, with the agent's real hook and the real sweep run right after the gate opens: a task running for 7,500 s was failed before and is left alone now, its approval answers 202, and a gate that has been open for 7,300 s is still failed. Refs #1041 * fix(api): write completed_at and status_created_at on Slack cancel The Slack cancel button set `status` and `updated_at` only. A task cancelled from Slack kept the status_created_at of its previous status and had no completed_at, so the CLI's elapsed time for it kept growing. The one update now writes both, in the form cancel-task writes them. It still writes no ttl and no event and stops no compute. The button exists only on tasks the orchestrator is polling: the orchestrator supplies the ttl and the event when it finalizes the task, and the agent stops when it next checks for cancellation. Verified: - cdk/test/handlers/slack-interactions.test.ts passes (6 tests); with slack-interactions.ts put back, the cancel test fails. - On the emulator, with the real handler and a signed payload: the update is accepted for each of the seven cancellable statuses, the row moves to the CANCELLED group of UserStatusIndex, and a terminal row is left unchanged. Refs #1041 * fix(api): a task failed at presigning is written as a terminal row When generating the upload instructions fails, create-task moves the task from PENDING_UPLOADS to FAILED. That update wrote the status, the error and updated_at only: the row kept the status_created_at of PENDING_UPLOADS, had no completed_at, and had no ttl, so it never expired. The update now also writes completed_at, status_created_at (`FAILED#<now>`) and the retention ttl, as cancel-task, cleanup-pending-uploads and reconcile-admission-queue do. Verified: - cdk/test/handlers/shared/create-task-core-presign-failure.test.ts, new, is the first test to reach this branch; it fails with create-task-core.ts put back. - On the emulator, with the real createTaskCore and only the presign call failing: the update is accepted, the row reads back FAILED with the three attributes, and its ttl is 90 days ahead in epoch seconds. Refs #1041 * fix(api): set ttl on stranded tasks and completed_at on blocked ones Two more writers move a task to FAILED and leave out an attribute that a terminal row needs: - reconcile-stranded-tasks writes no `ttl`. The orchestrator stamps one when it finalizes a task, but a task stranded in SUBMITTED or HYDRATING has no orchestrator left to do that, so such a row was kept for ever. An approval-paused task usually still has an orchestrator, which stamps the ttl again a poll later; that moves the expiry by seconds. - confirm-uploads, when screening blocks an attachment, writes no `completed_at`, so a failed task had no completion time. Each write now sets the missing attribute. The sweep's ttl is the one it already gave the events it writes for the task; the construct's two comments on the retention setting now name both uses. Open PR #1009 changes both files and neither write. Verified: - cdk/test/handlers/reconcile-stranded-tasks.test.ts and cdk/test/handlers/confirm-uploads.test.ts pass (27 tests); with either handler put back, the test of its write fails. - On the emulator, with the real handlers: a task stranded in SUBMITTED is failed with a ttl 90 days ahead, equal to its events', and a fresh task is left alone; an attachment that fails screening leaves the task FAILED with completed_at equal to updated_at. Refs #1041 * fix(api): link handlers refuse a code whose ttl has passed slack-link, linear-link and jira-link accepted a pending link row when its status was `pending` and did not compare its `ttl` with the clock. DynamoDB deletes expired items lazily, so an expired code can still be in the table. Each handler's one condition now also refuses a row whose ttl is not a number or is before now, with the 404 it already returns for an unknown code. This is the check shared/linear-console.ts already makes for its own rows. The check sits before the dry-run branch, so the Linear and Jira preview is refused as well. Nothing else changes: the write order, the unconditional put and the response are as before. All three producers of pending rows have always written a numeric ttl in epoch seconds, so no code that is still within its lifetime is affected. A code that is already past its ttl and not yet deleted stops working at deploy. Verified: - The three handler test files pass (33 tests); with the handlers put back, 11 fail with "Expected: 404, Received: 200". - Each part of the condition is pinned: with the status check, the type check or the clock comparison removed from any of the three handlers, a test fails. - cdk/test/handlers/slack-command-processor.test.ts now pins that the Slack producer stores a numeric ttl at most 600 seconds ahead. Refs #1041 * fix(agent): assume the session role when the session is built Three comments say that a task fails closed when the per-task session role cannot be assumed. It did not. The role was assumed on the first signed request, where the refusal was one more error behind a best-effort writer, and the task carried on: it cloned, ran the agent loop and opened a pull request while nothing was written to the task or events tables, and the orchestrator reported "Agent session lost" minutes later. get_session() now resolves the credentials once, right after it builds the scoped session, and caches nothing until that succeeded. A role that cannot be assumed raises SessionScopingError from the first is_scoped() call in run_task, before RUNNING is written or the repository is cloned, and every later tenant-data call is refused the same way. No tenant data is written with the compute role, as before. It costs no extra STS call: the first tenant-data call would have made the same one. Runs with no session role configured are untouched, and botocore still re-assumes the role before expiry. What it gives up: the deferral was there so that an STS failure at start-up would not stop the agent. A failure that outlasts the SDK's five attempts at task start now fails the task, where before the task ran on and lost one best-effort write. A single throttled response is still absorbed by the SDK's retries. Read from #904's patch, not run: it gives the STS client one attempt on MicroVM, so with both merged a single failed AssumeRole at start aborts a MicroVM task. What it does not change: when the role can never be assumed, the agent has no credentials to record the reason on the task, so the user still reads "Agent session lost". The reason is in the application log group and /ping answers 503. Verified: - agent/tests/test_aws_session.py passes (23 tests); with aws_session.py put back, 2 fail: get_session() does not raise, and run_task does not stop. The second also fails when the is_scoped() call is taken out of run_task's scoping log line. - Emulator: tests_emulator/test_scoped_session.py passes (8 tests); with aws_session.py put back, 2 fail. - End to end on the emulator, with the real run_task (clone, agent loop and pull request stubbed) and a role that does not exist: before, the task reached the pull-request step with no event written; now run_task raises after 0.2 s with no stage reached. With an assumable role the run is unchanged. - With no compute credentials, or an unreachable STS endpoint, the result is SessionScopingError with nothing cached. Refs #1041 * fix(agent): retry trajectory log-stream creation The trajectory writer cached its CloudWatch Logs client before CreateLogStream had succeeded. When that first call failed after the SDK's own retries, the client was already cached, the stream was never asked for again, every write went to a stream that did not exist, and the writer disabled itself after three failures: the task's whole CloudWatch trajectory was lost. The client is now cached only once the stream exists, so a failed creation is tried again on the next write. The event whose write failed is still lost, and the limit of three failures is unchanged. Verified: - agent/tests/test_trace_upload.py passes (31 tests); with telemetry.py put back, the new test fails (one CreateLogStream call where two are expected). - Emulator: tests_emulator/test_cloudwatch_logs.py passes (6 tests); with telemetry.py put back, the new test fails: no stream exists after the log group is created. - On the emulator, with the first CreateLogStream throttled through all five SDK attempts: before, 0 of 5 events were written and the writer was disabled; now 4 of 5 are written. - One case is worse than before: a stream that already exists while CreateLogStream keeps failing with another error. The writer then spends its three failures on creation. Refs #1041 * test(agent): reset the blocker latch between unit tests hooks._LAST_BLOCKER_REASON is a module-level value. A clone-failure test in test_repo.py leaves it set, and a later test of the task's overall status then reports that leftover reason for an unrelated task. The default order happens to hide it; running test_repo.py together with TestResolveOverallTaskStatus fails 6 tests. The shared fixture that already clears the environment and the session cache now also resets the latch, and test_conftest_env_scrub.py proves it: a module-scoped fixture sets the latch just before the test that checks it is clear. Verified: - tests/test_conftest_env_scrub.py passes (3 tests); with conftest.py put back, the new test fails, alone and after tests/test_hooks.py. - tests/test_repo.py with the two TestResolveOverallTaskStatus classes: 6 of 61 fail without the reset, all pass with it. - The whole agent unit suite passes in the default order and in four random per-test orders; without the reset, three random orders each fail the new test. - The random-order runs were made before the rebase onto #1035, whose conftest did not reset the latch either. Refs #1041 * fix(cdk): say that the agent stores cost and duration as strings shared/numeric.ts explained the string values of cost_usd and duration_s by saying the AWS SDK Document client deserializes Number attributes as strings "in some code paths", and TaskRecord declared the fields as numbers. Neither is true. The agent writes cost_usd, duration_s and the turn counters as DynamoDB String attributes (write_terminal passes them through str()), and the Document client returns a String as a string and a Number as a number. No behaviour changes: every reader already coerces, and the emitted JavaScript of the changed files is identical. What changes: - The comments in numeric.ts, types.ts, github-comment.ts, orchestrator.ts and two of the three in fanout-task-events.ts say what is stored, and so do the comments of the five test files that repeated the old explanation. The third comment is in a block that open PR #991 moves; it is left as it is, so that #991 does not conflict there. - TaskRecord declares the four fields `number | string`, so calling .toFixed() or doing arithmetic on the raw field no longer compiles. formatDuration's parameter is widened to match the Number() it already applies. - docs/design/ORCHESTRATOR.md lists the two attributes as String. Verified: - `tsc --noEmit -p tsconfig.json` in cdk: no error. With the fields widened and formatDuration left as it was, the two calls in slack-blocks.ts fail to compile. - The stored types, from the serialized request of the unchanged write_terminal: cost_usd, duration_s and the turn counters are S. Through the handlers' own document client an S attribute comes back as a string and an N attribute as a number. - The types drift check passes; TaskRecord is server-only and no API response type changes. Refs #1041 * chore(cdk): correct the comments on the Linear webhook dedup Four comments and a test title say that Linear webhook deliveries are deduplicated on issue and action for 60 seconds. The handler keys the row on the delivery's data.id (an issue or a comment), its action and its webhookTimestamp, and keeps it for eight hours, because Linear retries after one minute, one hour and six hours; the comment above DEDUP_TTL_HOURS explains it. Comments and one test title only. No document states the window. Verified: - cdk/test/constructs/linear-integration.test.ts passes with the renamed test. Refs #1041 * ci: add the advisory emulator workflow Runs `mise run test:integration` on every pull request, in the merge queue and on demand. It references no secret and has `contents: read` only, so it runs unchanged for fork pull requests. Advisory means visible and not required: the job is not in the required checks of the `main` ruleset, so a red run shows on the pull request and does not block the merge. It is a separate workflow and not a job in build.yml because deploy.yml and integ.yml start from the build's conclusion and need it to be `success`. The file is the block in Appendix A of docs/research/aws-emulator-local-tests.md (added later in this series), byte for byte. It pins the mise release, as every workflow that installs mise has since #1035 (issue #890). Verified: - `zizmor --offline .github` reports no finding with the file, as without it; the pedantic persona and actionlint with shellcheck report nothing on the file. - Its command passed on Linux (arm64, Ubuntu 24.04 container with its own Docker daemon), four runs out of four, the first one building the image through the wrapper. That was before the rebase onto main with #1035 and before later changes to the tier, among them the emulator test that adds an index to a table; the final tree has run on macOS only. - 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 and both merged. - Not verified: the workflow has not run on GitHub, and no test process has run on x86_64. Refs #1041 * ci: run the integ task without cdk deploy arguments Since #567 the integ job's test step cannot get past argument parsing. That change replaced the bare `mise //cdk:integ` with a command that passes `cdk deploy` arguments after `--`: `--all --require-approval never` and six `-c` context values. mise appends what follows `--` to the task's last command, which is `integ-runner`, and integ-runner exits 1 on an option it does not declare. The job sits behind the `deploy` approval gate, so nobody saw it: the step last ran, and passed, on 2026-07-07, two days before #567. The step runs `mise //cdk:integ` with nothing after it again. The integ app never read the context values, and it takes the stack name from INTEG_STACK_NAME, which the step still exports. cdk/test/scripts/integ-workflow.test.ts reads the workflow and fails when the task is given an argument, or is run more than once, so that the next such command fails the unit build and not an approved run. The fix cannot be tried from this pull request: integ.yml starts from workflow_run and so runs main's copy of the file. An integ run approved before the merge still executes the old command and fails; the fix applies to runs created after the merge. Verified: - cdk/test/scripts/integ-workflow.test.ts passes; with integ.yml put back it fails, showing the seven lines of arguments. - With the arguments of the old command integ-runner exits 1 on "Unknown arguments: all, require-approval, requireApproval, c"; with none it lists an empty directory and exits 0. - actionlint with shellcheck reports the same one style note (SC2129, line 82) on the file before and after, and `zizmor --offline .github` reports no finding, as before. - Not verified: the job itself, which needs the `deploy` environment and an AWS account. The INTEG_STACK_NAME path, also from #567, has never run in CI. Refs #1041 * docs: document the emulator tier and record the investigation - scripts/aws-emulator/README.md is the maintained document for the tier: how to run it, the rules for tests in it, where a green run can be trusted, the known differences from AWS, the guard and what is outside it, and how to move the version pin. - AGENTS.md and the three package guides say where the emulator tests live and how to run them, and agent/README.md lists tests_emulator/. - ADR-013 is amended in place (status still `proposed`): phase 2a exists, on the AWS Emulator instead of LocalStack, as an advisory check. The estimate that it would eliminate "60%+ of CI-only failures" is replaced by what was measured, the graduation criteria the ADR asks for are added, and phase 2c is stated to need a real AWS account, because an emulator cannot show a missing permission. - docs/research/aws-emulator-local-tests.md is the investigation behind the tier: what was built and measured, what was not verified, and, under Outcome, what happened to each defect it lists. Its body describes the day it was handed over, when #1035 was still open; Outcome says what changed since. Verified: - The link check passes on the README, the four guides, the ADR and the report; the ADR's mirror is regenerated with `mise //docs:sync`. - The README's statements about the tree were checked against the scripts, the Dockerfile, the mise tasks and the tests. Its statements about the emulator's behaviour are carried from the investigation and were not checked again, except the row about a Query on an index that is being created, which was observed on 1.0.385 for this series. Refs #1041 * fix(agent): build the image with gh 2.103.3, Go 1.27.4 and uv 0.13.7 The weekly image scan fails (#1042) on 22 findings in two binaries of the agent image: gh and uv. gh is built from source at a version written in the Dockerfile, which nothing updates; Dependabot proposes only its Go image, and those pull requests were not merged (#963 had 1.27.3 from 2026-10-24). uv is copied from an image on a line that Dependabot's docker pull requests have never changed. - gh 2.93.0 -> 2.103.3, built with Go 1.27.4 where it was 1.27.1. That clears 16 of the 17 findings in gh: the four in the standard library and twelve of the thirteen in its modules. - uv 0.11.14 -> 0.13.7, the version the gates already run (mise.toml, agent/mise.toml). That clears the five in uv. A comment on the line says to bump it by hand, to the version of those two files; mise.toml and CONTRIBUTING.md now name the image as the third place to keep equal. - The finding that is left is CVE-2026-78661 in golang.org/x/net/html. No gh release requires the fixed x/net 0.62.0: 2.103.3 requires 0.60.0 and 2.104.0 requires 0.61.0. The advisory is about the HTML parser, and gh links only the tokenizer of that package: govulncheck finds no vulnerable symbol in the binary, and `go tool nm` shows none of the parser's functions. agent/.trivyignore accepts the finding until 2026-12-16 and says which bump removes the entry. Nothing warns before that date; the weekly scan fails from it. By gh's source at the two versions, the ten gh calls of agent/src take the same arguments and print the same output. Commands that the model runs itself can meet three changes listed in gh's release notes: `gh api`, for a response that is not JSON, and `gh pr diff`, when piped, refuse output that holds terminal escape sequences unless --allow-escape-sequences is given (2.97.0); `--comments` with `--json` is rejected (2.99.0); and the stubs of official extensions exit 1 where they exited 0, or install the extension without asking when CI is set (2.94.0). 2.97.0 also stops `gh auth status` from printing part of a token (GHSA-cg6r-mpgc-h9mm). The image's uv is also the one a target repository's build gets when it calls uv without pinning its own. uv's release notes between the two versions list changes that such a build can meet: a workspace member no longer gets the workspace root's default dependency groups (0.12.2), `uv run path/script.py` uses the script's own project and source distributions that are not .tar.gz are rejected (0.12.0), and Python 3.15 is the default download (0.13.0). The first can make a build that passed fail before the agent has changed anything. The task then notes "Initial build (...) FAILED before agent changes", and the default build gate does not count a later failure as a regression. 0.13.7 also has the fixes for two uv advisories that affect 0.11.14 and that the image scan does not report (GHSA-hq85-5cpj-mr62, GHSA-4gg8-gxpx-9rph). On 2026-11-16 gh 2.103.3 is 21 days old and uv 0.13.7 is 13. Go 1.27.4 is 6 days old, one short of the 7 days that mise.toml asks of the gate tools and that Dependabot waits; Dependabot's open #1038 proposes 1.27.3. With 1.27.3 the scan passes as well, but 1.27.3 has CVE-2026-97054 in net/http, fixed in 1.27.4, which the scanner's database lists without a severity yet. Verified: - The image built from nothing and scanned with the flags of `security:image` has no finding on linux/arm64, where the image built from main has the 22 of #1042. A linux/amd64 build, emulated on an arm64 machine, has none either. gh is compiled in the amd64 Go image there, and the scan reads v2.103.3 from the binary. The COPY of uv follows the build machine, not TARGETPLATFORM, so that build holds the arm64 uv; the amd64 uv binary was scanned on its own. - The arm64 image starts under opentelemetry-instrument with no network and answers /ping 200, /invocations with `{}` as its body 422 and an unknown path 404. - cdk/test/constructs/agent-image-pins.test.ts passes. - With the lock file as it is before the distro bump, `uv sync --frozen --no-dev` installs the same 117 packages under uv 0.11.14 and 0.13.7, on both platforms. - Not verified: a task run on a deployed stack. Refs #1042 * fix(deps): clear two OpenTelemetry advisories, renew two ignores Five osv-scanner ignores expire on 2026-11-28 and 2026-12-02 (#1042). From its date an ignore stops applying, and the required dependency scan then fails every pull request. Two of the five are fixed. aws-opentelemetry-distro pins the OpenTelemetry packages exactly, and its release 0.22.0 pins opentelemetry-api and opentelemetry-propagator-jaeger at 1.45.1, which has the fixes for GHSA-xcq7-p3pf-p88h and GHSA-f5m9-jfrj-jjj7. The agent moves from 0.18.0 to 0.22.0 and the two entries go. In uv.lock only OpenTelemetry packages change: 58 updated, 2 added, 3 removed. Dependabot's open #1028 proposes the same versions, among nine other updates. One is no longer needed. GitHub withdrew GHSA-gcqx-w48m-w2h4, the deepmerge advisory, on 2026-11-16; osv-scanner then reports its entry as unused, and the entry goes. Two are renewed until 2026-12-16, 30 days like the earlier ones, because neither can be removed today: - GHSA-mf5v-w3w3-f6cg needs opentelemetry-api 1.45.2, and no release of the distro allows it; upstream issue #975 asks for it. - GHSA-g3hv-75wg-m249, minimatch: the reason is rewritten, because three of its clauses were no longer true. Two affected copies are left, both in build tooling. The one bundled in aws-cdk-lib waits for a CDK release that has aws/aws-cdk#39595. The one under eslint-plugin-import-x could move with its release 4.18.0, but that release also changes import-x/order, which then fails on files of cdk and cli; the bump is left to the dependency update that re-sorts them. What the distro bump changes at run time. The list is what showed in the image and in runs of the agent's own code, without a deployed stack; it is not the whole changelog of four releases. - With the AWS distro and agent observability off, the ASGI instrumentation no longer emits `http send` and `http receive` spans. With it on, 0.18.0 already left them out. - The MCP client adds trace headers to every HTTP request: traceparent and baggage, which carries the session id, the user id and the repository, and x-amzn-trace-id as well under the AWS distro. They are added before the agent signs the request, so traceparent and baggage are inside its SigV4 signature. This matters only with the tool Gateway enabled. - Two declared changes on the path that agent observability uses: the CloudWatch Logs exporter retries only 429, 502, 503 and 504 (before: 408, 429 and every 5xx), and a failed first credential lookup no longer leaves every later export unsigned. - Neither the image nor the stack names a distro (OTEL_PYTHON_DISTRO). AgentCore Runtime adds OpenTelemetry variables of its own to a hosted agent (its documentation does not list them). Where nothing adds any, as in the Lambda MicroVM image or a local run, opentelemetry-instrument takes the first distro that Python lists. Listed from the same machine, that is the upstream distro in the image before the bump and the AWS distro after it. Verified: - `mise run security:deps` passes with the two osv-scanner.toml files, and osv-scanner reports no unused ignore. The expiry check of security.yml, run from the workflow file, reports no ignore within 21 days. - With uv 0.13.7, a plain `uv lock` on the previous lock and the new manifest gives the committed uv.lock. - The agent unit suite passes with the new packages, and the image with them starts and answers as before. - Not verified: traces and logs from a deployed stack with the new distro, and a call to a real tool Gateway, which is the test of that signature. Fixes #1042 * test(tooling): move the AWS Emulator pin to 1.0.481 The tier was pinned at 1.0.385. The pin moves to 1.0.481, the second release that upstream published after it. Upstream puts security fixes in its newest release only. A third release, 1.0.483, was published while this change was being verified. The three suites pass on it as well, but the README was probed on 1.0.481 and not on it, so the pin stops at 1.0.481. On 1.0.481 the cdk and agent suites pass unchanged. Two cli tests needed a change, both because release 1.0.471 changed Cognito: - RespondToAuthChallenge for NEW_PASSWORD_REQUIRED is implemented. The test of the first sign-in was a test.failing that waited for it. It is a plain test now, and it also asserts that the temporary password stops working and that the new one signs in. - The iss claim of a token names the emulator again, as it did before 1.0.382, and no longer the AWS host. The test asserts the new value and names the upstream record. The edited tests fail on 1.0.385 and pass on 1.0.481. The tier holds 62 tests, as before. The suites show only what a test asserts, so the README's table of differences and its lists of what does not work were probed again on both releases, and each reported change a second time, independently. What changed: - UpdateRegistryRecordStatus is implemented, and the four agent-registry answers that the JavaScript SDK refused now parse, so ABCA's registry code runs here for the first time. UpdateRegistry still answers 501. Two answers stop that code, and the list now names them; nobody has compared either with AWS. A second record under a name the registry holds is a ConflictException, and ABCA publishes each version of an asset under one name. DeleteRegistry is a ConflictException while the registry holds a record, where 1.0.385 accepted it, and the custom resource retries without deleting the records. - A write that changes nothing no longer emits a stream record. The row is removed. - Fewer malformed expressions are accepted: 10 of the 29 forms that were probed, where it was 13. Reversed BETWEEN bounds and contains(a, a) are refused now. - The package is 170 MB on arm64 and 191 MB on x86_64. - New row: a token verifier that derives the issuer from the pool id, as the one in the API's authorizer does, accepted an emulator token on 1.0.385 when given the pool's key set, and refuses every one on 1.0.481. - New sentences in what is outside the guard: the emulator opens ports for resource endpoints, which check no request signature. RunMicrovm opens one, which no test of the tier calls. Other containers on the same Docker engine reach it; on 1.0.385 it listened on loopback inside the container. The wrapper does not publish it. One more row, for a difference the probes found that is the same on both releases: a bucket holds at most 1,000 objects. Unchanged, each reproduced on both releases: the TTL deletion delay, the 3 second table and index transitions, index read consistency and the absence of TransactionConflict, the throttling limits, presigned POST, the window after a forced secret deletion, the ListSecrets page, RunTask overrides, the six operations that answer 501, ApplyGuardrail over HTTP/1.1 and the 15 minute signature window. Also seen on 1.0.481 and left out of the README, because no test and no statement depends on it. Among other things: a presigned URL is evaluated with the policies of its signer, a few more calls evaluate identity policies (ListTables and DescribeLimits among them), a Scan allowed under a ForAllValues condition on LeadingKeys returns every partition, DescribeSecret no longer returns RotationEnabled for a secret that never had rotation, and a software token is challenged at sign-in. The procedure for moving the pin now says that a statement no test asserts holds for the release that "Recorded on emulator" names, and that a move leaves an image and a stale tag behind. The report's Outcome records the move and the first run of the workflow on GitHub. Not verified: 1.0.481 has run on macOS (arm64) only. The workflow run of this commit is its first run on Linux and on x86_64. Refs #1041 --------- Co-authored-by: bgagent <bgagent@noreply.github.com>
This was referenced Nov 18, 2026
4 of 5 tasks
Contributor
Author
|
Superseded by #1086, which carries this change (its commits are kept as they were, followed by one commit that adapts the combined set to current main). Closing to keep one place for review. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #1003.
Each task now holds a reservation marker (
concurrency_slot: held → released, versioned). Taking and returning a seat is one DynamoDB transaction with the per-user counter, so a seat is released exactly once, under retries, finalizer replays, cancel/complete races and lost replies alike.Changes
shared/task-concurrency.ts:acquireTaskSlot/releaseTaskSlot, transactional with the counter, and conditioned on the task's own marker.orchestrator.ts:acquireTaskSlot;finalizeTaskreleases infinally;failTaskrethrows when the task isn't terminal;decrementConcurrencyis removed.orchestrate-task.ts: consistent reads, plus release steps on the early-return paths. Only new paths are added, so in-flight durable executions replay unchanged.reconcile-concurrency.ts,reconcile-stranded-tasks.tsand the admission queue: they repair drift through the marker and never release another task's seat.reconcile-stranded-tasksno longer decrements the counter directly.confirm-uploadsno longer reserves capacity at submit. The orchestrator owns admission, so an upload-confirmed task over the cap is queued like any other submission, instead of rejected with 429.ORCHESTRATOR.md: the new scheme, plus an upgrade note.Upgrade
Drain in-flight tasks before deploying. Tasks admitted before this change have no marker; they can't release another task's seat, and their user's count is treated as ambiguous until they finish.
Tests
task-concurrency-local.test.ts), run against the pinnedamazon/dynamodb-localimage: 15/15 pass. 7 of them fail when the release-marker condition is removed. In CI the suite skips until a DynamoDB Local service exists inbuild.yml; feat(compute): add Lambda MicroVM P3 approval lifecycle #904 adds that service.