Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
feat(agentcore): add runtime version history and endpoint pinning (#1911)
Lisandro Pintos21966f2ff7aa
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7131340e..71195749 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,8 @@ Versioning follows [Semantic Versioning](https://semver.org/).### Changed+- **Bedrock AgentCore — runtime version history and endpoint pinning** — runtime updates now retain version snapshots, `GetAgentRuntime` retrieves a selected version, and `ListAgentRuntimeVersions` paginates the history. `DEFAULT` advances with the latest version while named endpoints stay pinned until updated; invocations use the selected snapshot, with containers isolated by version. Contributed by @pingedbrain.+- **CloudFormation — `AWS::Lambda::Version` updates `FunctionScalingConfig` in place** — a stack update re-ran the create, which published a new version for every change; a `FunctionScalingConfig` change now keeps the version, also when the update rolls back. Contributed by @iot-rocket.- **botocore 1.43.106** — the service models MiniStack reads move from 1.43.63 to 1.43.106; the images keep `awscli` 1.45.63, installed on the same botocore instead of its pinned one.### Fixeddiff --git a/ministack/services/bedrock_agentcore.py b/ministack/services/bedrock_agentcore.pyindex eb7a457c..7301167f 100644--- a/ministack/services/bedrock_agentcore.py+++ b/ministack/services/bedrock_agentcore.py@@ -23,6 +23,7 @@ against botocore ``bedrock-agentcore-control`` / ``bedrock-agentcore``service-2.json."""import asyncio+import base64import copyimport datetimeimport json@@ -58,7 +59,7 @@ logger = logging.getLogger("bedrock_agentcore")_runtimes = AccountRegionScopedDict() # agentRuntimeId -> runtime record_endpoints = AccountRegionScopedDict() # agentRuntimeId -> {endpointName -> endpoint record}_resource_policies = AccountRegionScopedDict() # resource ARN -> policy string-_containers = {} # (account, region, runtime id) -> Docker container+_containers = {} # (account, region, runtime id, version) -> Docker container_container_lock = threading.RLock()# AgentRuntimeName / EndpointName: start with a letter, then letters/digits/_,@@ -88,6 +89,12 @@ def _restore_state(data):_endpoints.update(data.get("endpoints", {}))_resource_policies.update(data.get("resourcePolicies", {}))_migrate_legacy_arns()+ # Backfill one snapshot for state written before version history existed.+ for runtime in _runtimes._data.values():+ if not runtime.get("_versions"):+ runtime["_versions"] = {+ runtime.get("agentRuntimeVersion", "1"): _version_snapshot(runtime)+ }def _migrate_legacy_arns():@@ -291,6 +298,67 @@ def _parse_body(body) -> dict:return {}+def _query_value(query_params, key, default=None):+ value = (query_params or {}).get(key, default)+ if isinstance(value, list):+ return value[0] if value else default+ return value+++def _version_snapshot(runtime):+ return {key: copy.deepcopy(value) for key, value in runtime.items()+ if not key.startswith("_")}+++def _runtime_versions(runtime):+ versions = runtime.get("_versions")+ if versions:+ return versions+ current = runtime.get("agentRuntimeVersion", "1")+ return {current: _version_snapshot(runtime)}+++def _version_summary(runtime, version):+ snapshot = _runtime_versions(runtime)[version]+ return {+ "agentRuntimeArn": runtime["agentRuntimeArn"],+ "agentRuntimeId": runtime["agentRuntimeId"],+ "agentRuntimeVersion": version,+ "agentRuntimeName": snapshot["agentRuntimeName"],+ "description": snapshot.get("description", ""),+ "lastUpdatedAt": _iso(snapshot["lastUpdatedAt"]),+ "status": snapshot["status"],+ }+++def _paginate(items, query_params):+ raw_limit = _query_value(query_params, "maxResults", "10")+ try:+ limit = int(raw_limit)+ except (TypeError, ValueError):+ return None, _validation("maxResults must be an integer from 1 to 100")+ if not 1 <= limit <= 100:+ return None, _validation("maxResults must be an integer from 1 to 100")++ token = _query_value(query_params, "nextToken")+ offset = 0+ if token:+ try:+ padded = token + "=" * (-len(token) % 4)+ offset = int(base64.urlsafe_b64decode(padded.encode()).decode())+ if offset < 0:+ raise ValueError+ except (ValueError, TypeError, base64.binascii.Error):+ return None, _validation("nextToken is invalid")++ result = {"items": items[offset:offset + limit]}+ if offset + limit < len(items):+ result["nextToken"] = base64.urlsafe_b64encode(+ str(offset + limit).encode()+ ).decode().rstrip("=")+ return result, None++# ---------------------------------------------------------------------------# Control plane — AgentRuntime# ---------------------------------------------------------------------------@@ -330,6 +398,7 @@ def _create_agent_runtime(body):"filesystemConfigurations"):if opt in data:record[opt] = data[opt]+ record["_versions"] = {version: _version_snapshot(record)}_runtimes[runtime_id] = record# AWS creates the DEFAULT endpoint with the runtime, pointing at the latest version._endpoints[runtime_id] = {"DEFAULT": _endpoint_record(record, "DEFAULT", version)}@@ -345,11 +414,21 @@ def _create_agent_runtime(body):})-def _get_agent_runtime(runtime_id):+def _get_agent_runtime(runtime_id, query_params=None):record = _runtimes.get(runtime_id)if record is None:return _not_found(f"Agent runtime {runtime_id} not found")- out = {k: v for k, v in record.items() if not k.startswith("_")}+ version = _query_value(query_params, "version")+ if version is None:+ selected = record+ else:+ selected = _runtime_versions(record).get(str(version))+ if selected is None:+ return _not_found(+ f"Agent runtime version {version} for runtime {runtime_id} not found"+ )+ out = {key: value for key, value in selected.items()+ if not key.startswith("_")}return json_response(out)@@ -368,20 +447,21 @@ def _list_agent_runtimes(body):return json_response({"agentRuntimes": summaries})-def _list_agent_runtime_versions(runtime_id, body):+def _list_agent_runtime_versions(runtime_id, query_params):record = _runtimes.get(runtime_id)if record is None:return _not_found(f"Agent runtime {runtime_id} not found")- summary = {- "agentRuntimeArn": record["agentRuntimeArn"],- "agentRuntimeId": record["agentRuntimeId"],- "agentRuntimeVersion": record["agentRuntimeVersion"],- "agentRuntimeName": record["agentRuntimeName"],- "description": record.get("description", ""),- "lastUpdatedAt": _iso(record["lastUpdatedAt"]),- "status": record["status"],- }- return json_response({"agentRuntimes": [summary]})+ items = [+ _version_summary(record, version)+ for version in sorted(_runtime_versions(record), key=int, reverse=True)+ ]+ page, error = _paginate(items, query_params)+ if error:+ return error+ return json_response({+ "agentRuntimes": page["items"],+ **({"nextToken": page["nextToken"]} if "nextToken" in page else {}),+ })def _update_agent_runtime(runtime_id, body):@@ -392,13 +472,18 @@ def _update_agent_runtime(runtime_id, body):for field in ("agentRuntimeArtifact", "roleArn", "networkConfiguration"):if not data.get(field):return _validation(f"{field} is required")++ versions = record.get("_versions")+ if not versions:+ versions = {+ record.get("agentRuntimeVersion", "1"): _version_snapshot(record)+ }+ record["_versions"] = versions+_stop_container(runtime_id)now = now_iso()new_version = str(int(record["agentRuntimeVersion"]) + 1)record["agentRuntimeVersion"] = new_version- default = (_endpoints.get(runtime_id) or {}).get("DEFAULT")- if default:- default.update(targetVersion=new_version, liveVersion=new_version, lastUpdatedAt=now)record["lastUpdatedAt"] = nowrecord["status"] = "READY"for field in ("agentRuntimeArtifact", "roleArn", "networkConfiguration"):@@ -409,6 +494,11 @@ def _update_agent_runtime(runtime_id, body):"filesystemConfigurations"):if opt in data:record[opt] = data[opt]++ versions[new_version] = _version_snapshot(record)+ default = (_endpoints.get(runtime_id) or {}).get("DEFAULT")+ if default:+ default.update(targetVersion=new_version, liveVersion=new_version, lastUpdatedAt=now)return json_response({"agentRuntimeArn": record["agentRuntimeArn"],"agentRuntimeId": runtime_id,@@ -445,10 +535,13 @@ def _create_agent_runtime_endpoint(runtime_id, body):name = data.get("name")if not name or not _NAME_RE.match(name):return _validation("name must match ^[a-zA-Z][a-zA-Z0-9_]{0,47}$")- endpoints = _endpoints.setdefault(runtime_id, {})+ endpoints = _endpoints.get(runtime_id) or {}if name in endpoints:return _conflict(f"Endpoint {name} already exists")- target_version = data.get("agentRuntimeVersion") or runtime["agentRuntimeVersion"]+ target_version = str(data.get("agentRuntimeVersion") or runtime["agentRuntimeVersion"])+ if target_version not in _runtime_versions(runtime):+ return _validation(f"Agent runtime version {target_version} does not exist")+ endpoints = _endpoints.setdefault(runtime_id, {})record = _endpoint_record(runtime, name, target_version, data.get("description", ""))now = record["createdAt"]endpoints[name] = record@@ -510,12 +603,15 @@ def _update_agent_runtime_endpoint(runtime_id, endpoint_name, body):if record is None:return _not_found(f"Endpoint {endpoint_name} not found")data = _parse_body(body)- now = now_iso()- if data.get("agentRuntimeVersion"):- record["targetVersion"] = data["agentRuntimeVersion"]- record["liveVersion"] = data["agentRuntimeVersion"]+ if data.get("agentRuntimeVersion") is not None:+ version = str(data["agentRuntimeVersion"])+ if version not in _runtime_versions(runtime):+ return _validation(f"Agent runtime version {version} does not exist")+ record["targetVersion"] = version+ record["liveVersion"] = versionif "description" in data:record["description"] = data["description"]+ now = now_iso()record["lastUpdatedAt"] = nowrecord["status"] = "READY"return json_response({@@ -693,12 +789,14 @@ def _invoke_agent_runtime(runtime_arn, headers, body, query_params=None):if runtime is None:return _not_found(f"Agent runtime {runtime_arn} not found")- qualifier = query_params.get("qualifier") if query_params else None- if isinstance(qualifier, list):- qualifier = qualifier[0] if qualifier else None+ qualifier = _query_value(query_params, "qualifier")endpoint = _endpoint_for_qualifier(runtime, owner_account, owner_region, qualifier)if qualifier and endpoint is None:return _not_found(f"Agent runtime endpoint {qualifier} not found")+ version = (endpoint or {}).get("liveVersion") or runtime["agentRuntimeVersion"]+ selected = _runtime_versions(runtime).get(str(version))+ if selected is None:+ return _not_found(f"Agent runtime version {version} for runtime {runtime['agentRuntimeId']} not found")from ministack.app import AUTHfrom ministack.core.iam_evaluator import caller_arn, pin_request_caller@@ -714,7 +812,7 @@ def _invoke_agent_runtime(runtime_arn, headers, body, query_params=None):)with request_scope(owner_account, owner_region):- return _invoke_agent_runtime_in_owner(runtime, headers, body)+ return _invoke_agent_runtime_in_owner(selected, headers, body)def _invoke_agent_runtime_in_owner(runtime, headers, body):@@ -782,8 +880,8 @@ def _docker_client():return _docker-def _container_key(runtime_id):- return get_account_id(), get_region(), runtime_id+def _container_key(runtime_id, version):+ return get_account_id(), get_region(), runtime_id, str(version)def _remove_container(container):@@ -808,9 +906,9 @@ def _remove_orphan_containers(client, labels):def _stop_container(runtime_id):with _container_lock:- container = _containers.pop(_container_key(runtime_id), None)- if container is not None:- _remove_container(container)+ prefix = _container_key(runtime_id, "")[:3]+ for key in [key for key in _containers if key[:3] == prefix]:+ _remove_container(_containers.pop(key))def _container_invocations_url(runtime):@@ -819,7 +917,7 @@ def _container_invocations_url(runtime):image = artifact.get("containerUri")if not isinstance(image, str) or not image:raise ValueError("Agent runtime has no containerConfiguration.containerUri")- key = _container_key(runtime["agentRuntimeId"])+ key = _container_key(runtime["agentRuntimeId"], runtime["agentRuntimeVersion"])with _container_lock:container = _containers.get(key)if container is not None:@@ -837,6 +935,7 @@ def _container_invocations_url(runtime):labels = own_labels("agentcore", **{"ministack.agentcore.runtime": runtime["agentRuntimeId"],+ "ministack.agentcore.runtime-version": runtime["agentRuntimeVersion"],"ministack.agentcore.account": key[0],"ministack.agentcore.region": key[1]})try:@@ -984,7 +1083,7 @@ async def handle_request(method, path, headers, body, query_params):elif n == 2:runtime_id = unquote(parts[1])if method == "GET":- return _get_agent_runtime(runtime_id)+ return _get_agent_runtime(runtime_id, query_params)if method == "PUT":return _update_agent_runtime(runtime_id, body)if method == "DELETE":@@ -997,7 +1096,7 @@ async def handle_request(method, path, headers, body, query_params):)runtime_id = unquote(parts[1])if seg == "versions" and method == "POST":- return _list_agent_runtime_versions(runtime_id, body)+ return _list_agent_runtime_versions(runtime_id, query_params)if seg == "runtime-endpoints":if method == "PUT":return _create_agent_runtime_endpoint(runtime_id, body)diff --git a/tests/test_bedrock_agentcore.py b/tests/test_bedrock_agentcore.pyindex 22c59069..a078d709 100644--- a/tests/test_bedrock_agentcore.py+++ b/tests/test_bedrock_agentcore.py@@ -72,7 +72,7 @@ def test_agentcore_runtime_lifecycle():assert rid in idsupdated = ctl.update_agent_runtime(- agentRuntimeId=rid, agentRuntimeArtifact=_ARTIFACT,+ agentRuntimeId=rid, agentRuntimeArtifact=_CODE_ARTIFACT,roleArn=_ROLE, networkConfiguration=_NET,)assert updated["agentRuntimeVersion"] == "2"@@ -81,9 +81,21 @@ def test_agentcore_runtime_lifecycle():default = ctl.get_agent_runtime_endpoint(agentRuntimeId=rid, endpointName="DEFAULT")assert (default["liveVersion"], default["targetVersion"]) == ("2", "2")assert ctl.get_agent_runtime(agentRuntimeId=rid)["agentRuntimeVersion"] == "2"-- versions = ctl.list_agent_runtime_versions(agentRuntimeId=rid)["agentRuntimes"]- assert versions and versions[0]["agentRuntimeId"] == rid+ assert ctl.get_agent_runtime(agentRuntimeId=rid, agentRuntimeVersion="1")[+ "agentRuntimeArtifact"+ ] == _ARTIFACT+ assert ctl.get_agent_runtime(agentRuntimeId=rid, agentRuntimeVersion="2")[+ "agentRuntimeArtifact"+ ] == _CODE_ARTIFACT++ first_page = ctl.list_agent_runtime_versions(+ agentRuntimeId=rid, maxResults=1+ )+ assert first_page["agentRuntimes"][0]["agentRuntimeVersion"] == "2"+ second_page = ctl.list_agent_runtime_versions(+ agentRuntimeId=rid, maxResults=1, nextToken=first_page["nextToken"]+ )+ assert second_page["agentRuntimes"][0]["agentRuntimeVersion"] == "1"finally:deleted = ctl.delete_agent_runtime(agentRuntimeId=rid)assert deleted["status"] == "DELETING"@@ -93,12 +105,142 @@ def test_agentcore_runtime_lifecycle():assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"+def test_agentcore_invocation_uses_endpoint_version(monkeypatch):+ runtime_id = None+ observed_runtimes = []++ def capture(runtime, headers, body):+ observed_runtimes.append(runtime)+ return 200, {"Content-Type": "application/json"}, b"{}"++ monkeypatch.setattr(agentcore, "_invoke_agent_runtime_in_owner", capture)+ monkeypatch.setattr(agentcore, "_resource_policy_allows_invocation", lambda *args: True)++ with agentcore.request_scope("000000000000", "us-east-1"):+ status, _, payload = agentcore._create_agent_runtime(json.dumps({+ "agentRuntimeName": f"version_{_uuid_mod.uuid4().hex[:8]}",+ "agentRuntimeArtifact": _CODE_ARTIFACT,+ "roleArn": _ROLE,+ "networkConfiguration": _NET,+ }).encode())+ assert status == 200+ runtime = json.loads(payload)+ runtime_id = runtime["agentRuntimeId"]+ arn = runtime["agentRuntimeArn"]+ try:+ status, _, _ = agentcore._create_agent_runtime_endpoint(+ runtime_id, json.dumps({"name": "prod", "agentRuntimeVersion": "1"}).encode()+ )+ assert status == 200+ status, _, _ = agentcore._update_agent_runtime(runtime_id, json.dumps({+ "agentRuntimeArtifact": _ARTIFACT,+ "roleArn": _ROLE,+ "networkConfiguration": _NET,+ }).encode())+ assert status == 200++ status, _, v1_payload = asyncio.run(agentcore.handle_request(+ "GET", f"/runtimes/{runtime_id}", {}, b"", {"version": ["1"]}+ ))+ assert status == 200+ assert json.loads(v1_payload)["agentRuntimeArtifact"] == _CODE_ARTIFACT++ status, _, first_payload = asyncio.run(agentcore.handle_request(+ "POST", f"/runtimes/{runtime_id}/versions", {}, b"",+ {"maxResults": ["1"]},+ ))+ first_page = json.loads(first_payload)+ assert status == 200+ assert first_page["agentRuntimes"][0]["agentRuntimeVersion"] == "2"+ status, _, second_payload = asyncio.run(agentcore.handle_request(+ "POST", f"/runtimes/{runtime_id}/versions", {}, b"",+ {"maxResults": ["1"], "nextToken": [first_page["nextToken"]]},+ ))+ second_page = json.loads(second_payload)+ assert status == 200+ assert second_page["agentRuntimes"][0]["agentRuntimeVersion"] == "1"++ agentcore._invoke_agent_runtime(arn, {}, b"{}", {"qualifier": ["prod"]})+ agentcore._invoke_agent_runtime(arn, {}, b"{}", {})+ assert [item["agentRuntimeVersion"] for item in observed_runtimes] == ["1", "2"]+ assert observed_runtimes[0]["agentRuntimeArtifact"] == _CODE_ARTIFACT+ assert observed_runtimes[1]["agentRuntimeArtifact"] == _ARTIFACT++ status, _, _ = agentcore._update_agent_runtime_endpoint(+ runtime_id, "prod", json.dumps({"agentRuntimeVersion": "2"}).encode()+ )+ assert status == 200+ agentcore._invoke_agent_runtime(arn, {}, b"{}", {"qualifier": ["prod"]})+ assert [item["agentRuntimeVersion"] for item in observed_runtimes] == ["1", "2", "2"]+ assert observed_runtimes[-1]["agentRuntimeArtifact"] == _ARTIFACT+ finally:+ agentcore._delete_agent_runtime(runtime_id)+++def test_agentcore_version_errors_and_state_restore():+ original_state = agentcore.get_state()+ runtime_id = None+ try:+ with agentcore.request_scope("000000000000", "us-east-1"):+ status, _, payload = agentcore._create_agent_runtime(json.dumps({+ "agentRuntimeName": f"restore_{_uuid_mod.uuid4().hex[:8]}",+ "agentRuntimeArtifact": _CODE_ARTIFACT,+ "roleArn": _ROLE,+ "networkConfiguration": _NET,+ }).encode())+ assert status == 200+ runtime_id = json.loads(payload)["agentRuntimeId"]+ status, _, _ = agentcore._update_agent_runtime(runtime_id, json.dumps({+ "agentRuntimeArtifact": _ARTIFACT,+ "roleArn": _ROLE,+ "networkConfiguration": _NET,+ }).encode())+ assert status == 200++ saved_state = agentcore.get_state()+ agentcore.load_persisted_state(saved_state)+ status, _, versions_payload = agentcore._list_agent_runtime_versions(runtime_id, {})+ assert status == 200+ assert [item["agentRuntimeVersion"] for item in json.loads(versions_payload)[+ "agentRuntimes"+ ]] == ["2", "1"]++ legacy_state = agentcore.get_state()+ legacy_runtime = legacy_state["runtimes"].get_scoped(+ "000000000000", "us-east-1", runtime_id+ )+ legacy_runtime.pop("_versions")+ agentcore.load_persisted_state(legacy_state)+ status, _, versions_payload = agentcore._list_agent_runtime_versions(runtime_id, {})+ assert status == 200+ versions = json.loads(versions_payload)["agentRuntimes"]+ assert [item["agentRuntimeVersion"] for item in versions] == ["2"]++ status, _, _ = agentcore._get_agent_runtime(runtime_id, {"version": ["99"]})+ assert status == 404+ status, _, _ = agentcore._create_agent_runtime_endpoint(+ runtime_id, json.dumps({"name": "missing", "agentRuntimeVersion": "99"}).encode()+ )+ assert status == 400+ _, error = agentcore._paginate([], {"maxResults": ["101"]})+ assert error[0] == 400+ _, error = agentcore._paginate([], {"nextToken": ["invalid!"]})+ assert error[0] == 400+ finally:+ if runtime_id is not None:+ with agentcore.request_scope("000000000000", "us-east-1"):+ agentcore._delete_agent_runtime(runtime_id)+ agentcore.load_persisted_state(original_state)++def test_agentcore_endpoint_lifecycle():ctl = _client("bedrock-agentcore-control")name = f"rt_{_uuid_mod.uuid4().hex[:8]}"rid = _create(ctl, name)["agentRuntimeId"]try:- ep = ctl.create_agent_runtime_endpoint(agentRuntimeId=rid, name="prod")+ ep = ctl.create_agent_runtime_endpoint(+ agentRuntimeId=rid, name="prod", agentRuntimeVersion="1"+ )assert ep["endpointName"] == "prod"assert ep["status"] == "CREATING"assert ep["agentRuntimeEndpointArn"] == (@@ -107,14 +249,25 @@ def test_agentcore_endpoint_lifecycle():got = ctl.get_agent_runtime_endpoint(agentRuntimeId=rid, endpointName="prod")assert got["status"] == "READY"assert got["name"] == "prod"+ assert got["liveVersion"] == got["targetVersion"] == "1"names = [e["name"] for e inctl.list_agent_runtime_endpoints(agentRuntimeId=rid)["runtimeEndpoints"]]assert sorted(names) == ["DEFAULT", "prod"]+ ctl.update_agent_runtime(+ agentRuntimeId=rid, agentRuntimeArtifact=_CODE_ARTIFACT,+ roleArn=_ROLE, networkConfiguration=_NET,+ )+ got = ctl.get_agent_runtime_endpoint(agentRuntimeId=rid, endpointName="prod")+ assert got["liveVersion"] == got["targetVersion"] == "1"+upd = ctl.update_agent_runtime_endpoint(- agentRuntimeId=rid, endpointName="prod", description="live")+ agentRuntimeId=rid, endpointName="prod",+ agentRuntimeVersion="2", description="live",+ )assert upd["status"] == "UPDATING"+ assert (upd["liveVersion"], upd["targetVersion"]) == ("2", "2")assert ctl.delete_agent_runtime_endpoint(agentRuntimeId=rid, endpointName="prod")["status"] == "DELETING"@@ -574,12 +727,18 @@ def test_container_image_invoked_and_removed(monkeypatch):_, _, second_body = _invoke(runtime["agentRuntimeArn"])asyncio.run(second_body.runner(_discard, None))assert len(started) == 1+ version_two = dict(agentcore._runtimes[runtime["agentRuntimeId"]])+ version_two["agentRuntimeVersion"] = "2"+ agentcore._container_invocations_url(version_two)+ assert len(started) == 2+ assert [item[1]["labels"]["ministack.agentcore.runtime-version"]+ for item in started] == ["1", "2"]finally:agentcore._delete_agent_runtime(runtime["agentRuntimeId"])server.shutdown()server.server_close()thread.join()- assert removed == [True]+ assert removed == [True, True]def test_container_joins_ministack_network(monkeypatch):