Skip to content

feat(runtime): add @app.warmup decorator for build warmup lifecycle hooks - #754

Merged
jariy17 merged 3 commits into
mainfrom
feat/runtime-warmup-hook
Nov 25, 2026
Merged

jariy17 merged 3 commits into
mainfrom
feat/runtime-warmup-hook

Conversation

@jariy17

@jariy17 jariy17 commented Nov 25, 2026

Copy link
Copy Markdown
Contributor

Closes #741

Supersedes #746 (approved there). Opened from a branch in this repo so CI gets the repo's credentials, which fork PRs don't.

Description

Adds @app.warmup to BedrockAgentCoreApp for the AgentCore Runtime build warmup hook.

When a V2 runtime sets hooksConfiguration.build.warmup, AgentCore Runtime sends two POST requests to the agent before the runtime is READY: memory, then disk. The call type comes in the X-Amzn-Bedrock-AgentCore-Runtime-Warmup-Type header. Today each agent has to add the route, parse the header, keep /ping responsive and map errors to status codes itself. With this change:

from bedrock_agentcore import BedrockAgentCoreApp, HookConfig, WarmupType

app = BedrockAgentCoreApp(warmup_hook=HookConfig(path="/warmup"))  # same path as httpPost.path

@app.warmup(WarmupType.MEMORY)
def load_model():
    ...  # load what every session needs

@app.warmup(WarmupType.DISK)
def read_startup_files():
    ...  # read the files sessions read at start

Behavior

Request or registration Result
Call for a type with a handler Runs the handler, then 200 {"status": "ok", "type": ..., "result": "completed"}
Call for a type without a handler 200 {"status": "ok", "type": ..., "result": "skipped"}
Handler raises 500 {"error": ..., "type": ...}, which fails the create or update
Sync handler returns an awaitable 500 ("declare it with async def")
Handler returns a generator (e.g. lambda: gen()) 500 (mentions yield); the generator is closed unstarted, so its body never runs
Call for a type this SDK version doesn't know (e.g. cpu) 200 {"status": "ok", "type": <trimmed, lower-cased value>, "result": "skipped"}, logged as Warmup (<value>): unknown type, nothing to do
Missing or empty header 400 {"error": "X-Amzn-Bedrock-AgentCore-Runtime-Warmup-Type header is missing or empty"}
Generator handler (def or async def with yield, also via functools.partial or a callable's __call__) ValueError when the decorator is applied
Unknown type, duplicate handler, or no warmup_hook ValueError when the decorator is applied
Hook path already served on its port (e.g. POST /invocations on the serving port) ValueError when the app is constructed (or in app.run() for a hook whose port equals the serving port)
Invalid path, or port outside 8000–12000 (or not an int, or a bool) ValueError when HookConfig is created
HookConfig.port set, started with app.run() Hook served on that port only, on 127.0.0.1 (where the runtime calls it) whatever host the app serves on, by a second listener in the same process that opens before the serving port and closes after it
HookConfig.port equal to the serving port Served on the serving port, as if unset
HookConfig.port set, app.run(lifespan="off") ValueError
HookConfig.port set, started another way (e.g. uvicorn agent:app) Startup fails with "Hook ports are only served by app.run(); …", uvicorn exits with code 3
HookConfig.port set, lifespan skipped (uvicorn --lifespan off) Every HTTP request gets 503 with the same message
Hook port already taken Startup fails with an error naming the port, before the serving port opens (exit code 3)
  • /ping stays responsive. Sync handlers run in a worker thread and async handlers on a separate event loop, the same as @app.entrypoint.
  • Calls never overlap. Each hook has its own asyncio.Lock.

Changes

  • runtime/models.py
    • WarmupType (MEMORY, DISK) and WARMUP_TYPE_HEADER.
    • HookConfig(path, port=None): a frozen dataclass. path is validated against the public API rules: 1–32 characters, A-Z a-z 0-9 . _ ~ / -, starts with /, canonical form. Each rule raises its own message. port matches httpPost.port: an integer from 8000 to 12000, bool rejected; None means the serving port.
    • WarmupType docstring: unknown types are answered with skipped.
  • runtime/app.py
    • BedrockAgentCoreApp(..., *, warmup_hook=None): a new keyword-only argument. None adds no route.
    • @app.warmup(type) registers a handler and rejects generator functions (_is_generator_callable); _handle_warmup serves the route, rejects a returned generator, skips unknown types and returns 400 only for a missing or empty header.
    • _add_route rejects a route whose (method, path) is already served, naming where (by the app or on port N).
    • Hook routes are stored like the TypeScript SDK: no port → the main app's routes; a port → _hook_port_routes[port], checked per port. run(port=P) moves the hooks on P onto the main app, checked against the main routes.
    • When a hook has a port, the constructor composes the app's lifespan with the user's lifespan= (normalized with Starlette's own Router, nested inside ours). It binds each hook port itself on 127.0.0.1, serves it with a small Starlette app on a uvicorn.Server subclass that leaves signals to the main server, waits until each hook server has started, and stops them on shutdown. The main server still starts with plain uvicorn.run(self, ...).
    • __call__ answers 503 when a hook port is configured but the hook servers never started.
    • _Hook holds each hook's config, handlers and lock.
    • Dispatch moved from _invoke_handler into _dispatch_handler, so warmup handlers can be called with no arguments. _invoke_handler behaves as before.
  • __init__.py, runtime/__init__.py: export WarmupType and HookConfig.
  • README.md: a "Build Warmup Hook" section, including unknown types, generators and HookConfig.port.

Design notes

  • No SDK default path. The API requires httpPost.path, so HookConfig requires it too. The path is then written out in both places, which makes a mismatch easy to spot, and apps that don't use the hook get no new route.
  • Port. HookConfig.port must equal build.warmup.action.httpPost.port. Omit both and the hook is served on the serving port, next to /ping. Set both (8000–12000) and the hook is served on that port only, for example when the agent runs its own server on 8080. That port listens on 127.0.0.1 only, the address the runtime calls, even when the app serves on 0.0.0.0. The separate port needs app.run(): its listener is started from the app's lifespan, on the same event loop as the main server, before the serving port opens, and stopped after the main server drains. Started any other way, the app refuses to start (or answers 503 if the lifespan is skipped) instead of silently not serving the hook.
  • Unknown types are skipped, not rejected. If the service adds a third warmup type later, agents built with this version still pass the create or update.
  • Generators are rejected. A handler with yield would return a generator that nobody iterates, so its body would never run; it's rejected at registration, and a returned generator fails the call.
  • Route conflicts compare method and path, as the platform does. POST /ping and POST /ws are allowed; POST /invocations isn't.
  • One server process. The warmup call reaches one process, so with several worker processes (uvicorn --workers N) only one of them is warmed, and each would try to open the hook port. The README says so.
  • SIGTERM exit status. uvicorn re-raises the signal it handled after a graceful shutdown, so the process ends with -15, with or without a hook port (checked on uvicorn 0.34.2, 0.35.0 and 0.54.0).

Backward compatible

Yes. warmup_hook is a new keyword-only argument that defaults to None, so existing apps get no new route and no behavior change. HookConfig.port defaults to None, and the extra lifespan is only installed when a hook has a port.

Testing

Unit tests in tests/bedrock_agentcore/runtime/test_app.py

TestWarmup (68 cases):

Area What's covered
Results completed and skipped per type; both handlers each run for their own type; 500 for sync and async handlers that raise; 500 for a sync handler that returns a coroutine (which is closed, so it doesn't warn) or another awaitable; 500 for lambda: gen(), lambda: async_gen() and an async def returning an async generator, with the generator body never run; 400 with the exact message for a missing, empty or blank header; 200 skipped plus the info log for cpu, memory,disk and Network; the header matched case-insensitively and trimmed
Dispatch sync handlers in a worker thread, async handlers on a separate loop; a concurrent /ping answers Healthy in < 0.5 s while a sync handler blocks for 1.5 s; three overlapping warmup calls run one at a time; each hook has its own lock
Decorator returns the function unchanged; duplicate and unknown types raise; string forms accepted; def+yield, async def+yield, a partial and a nested partial of a generator, and callable classes with a generator or async generator __call__ rejected; non-generator partials and callables accepted
warmup_hook custom path works and /warmup then 404s; POST /ping and POST /ws allowed; POST /invocations raises; no warmup_hook means no route and the decorator raises; existing positional arguments unchanged
HookConfig 6 valid and 13 invalid paths, each asserting the message of the check that fires; frozen

TestWarmupHookPort (46 cases):

Area What's covered
Validation None, 8000, 9000, 12000 valid; 7999, 12001, 0, -1, 80, True, False, "8080", 8080.0 rejected with the HookConfig.port message; path checked first
Routes no port → main app; a port → its own routes only (not on the main app, and the hook app serves no /ping or /invocations); /invocations allowed on a hook port; conflicts checked per port; the lifespan is only replaced when a hook has a port
run() a hook on the serving port is merged onto the main app and served; the merge is conflict-checked (/invocations raises, uvicorn not started); a hook on another port stays off the main app; lifespan="off" rejected with a port (including one equal to the serving port), allowed without one; lifespan="on" passed through
Without app.run() the lifespan fails startup with the message; with no lifespan, GET /ping, POST /invocations and POST /warmup get 503 with the message; no 503 without a hook port or after the merge; WebSocket unaffected
Lifespan starts a real hook server on a free port (warmup completes there, /ping 404s there, /warmup 404s on the main app), then stops it and closes the port; nothing to start after a merge
User lifespan an async context manager runs nested (hook port already listening at its startup and still listening at its shutdown) and its state reaches the request; a generator lifespan runs through Starlette's conversion; a failing user lifespan stops the hook servers
Failures a taken port fails with Can't serve the hook on HookConfig.port N: binding 127.0.0.1:N failed; a taken second port closes the first socket; a hook server that stops during startup fails startup; a crashed hook server is logged on shutdown
  • Hook servers leave the SIGINT/SIGTERM handlers to the main server (checked with the hook server started on the main thread, where uvicorn would install them).
  • The hook port binds 127.0.0.1 when the app runs on 0.0.0.0.

tests/bedrock_agentcore/test_init.py: WarmupType and HookConfig added to the pinned __all__.

Integration tests

tests_integ/runtime/test_warmup_agent.py runs a generated agent as a real local server. Its memory handler blocks for 2 s; it has no disk handler. The test asserts:

  • the invocation shows the unwarmed state before the warmup and the warmed state after;
  • the memory call returns completed only after the work is done;
  • at least 5 /pings that started during the warmup all returned Healthy in < 0.5 s;
  • disk returns skipped, an unknown type (cpu) returns 200 skipped, and a missing header returns 400.

tests_integ/runtime/test_warmup_hook_port.py runs an agent with HookConfig(path="/warmup", port=<free port>) and the app on another free port:

  1. app.run(): the warmup completes on the hook port (2.0 s); /warmup is 404 on the serving port and /ping is 404 on the hook port; ≥ 5 /pings during the blocking memory handler answer Healthy in < 0.5 s; one SIGTERM shuts both servers down gracefully (Application shutdown complete, Hook servers stopped) and closes both ports.
  2. uvicorn hook_port_agent:app: exits with code 3 and prints the "only served by app.run()" message; neither port opens.
  3. Hook port taken: the process exits with code 3, printing the error that names the port, and the serving port never opens.

Results (on 3dc7508, on top of main at bfa07e5)

uv run pre-commit run --all-files                     Passed
uv run --python 3.10 pytest tests/ --cov=src --cov-branch   3941 passed, 10 skipped, 4 xpassed; coverage 91%
uv run --python 3.13 pytest tests/ --cov=src --cov-branch   3941 passed, 10 skipped, 4 xpassed; coverage 91%
uv run pytest tests_integ/runtime                     20 passed, 7 skipped
  • The new code is fully covered; runtime/app.py misses only lines it missed before this change, and runtime/models.py is at 100%.
  • The 7 skipped are test_runtime_passthrough.py, which needs AWS credentials.
  • uvicorn versions (throwaway venvs, Python 3.13, Starlette 1.10.0), test_warmup_hook_port.py:
uvicorn Own port, SIGTERM uvicorn module:app Taken hook port --lifespan off No hook port, SIGTERM (baseline)
0.34.2 (minimum) pass; exit -15 after graceful shutdown exit 3 + message exit 3, serving port never opened 503 + message exit -15
0.35.0 (locked) pass; exit -15 exit 3 + message exit 3 503 + message exit -15
0.54.0 (latest) pass; exit -15 exit 3 + message exit 3 503 + message exit -15

End-to-end on deployed V2 runtimes

Run against the public us-west-2 endpoints, with an agent image built from this branch's wheel:

  • P1–P4 ran on 2026-11-21 on the current code (built from 4ee3750, which differs from 3dc7508 only in unit tests and docstrings).
  • M1, M2 and M6a ran on 2026-11-21 on the previous revision of the port commit, which differs from the current code only in the hook-port bind host, refactors and tests; cases without a hook port don't touch that code.
  • M3–M5 and M7–M9 ran on 2026-11-19 on 639971d (the same change as c73a65f, before 5fd10a6 and 3dc7508). Those add the generator check, the unknown-type skip and HookConfig.port; with no hook port, the route, dispatch and completed / skipped / 500 responses these cases exercise are unchanged, and M1, M2 and M6a gave the same results on that revision.

Test agent: one image. Environment variables on the runtime pick which handlers are registered, which one raises, and how long the memory handler blocks. The memory handler sets an in-process flag, the disk handler reads a few-MB file, and the entrypoint returns both flags.

disk_warmed is always false, as expected. Per the docs, only what the memory call loads is what each new instance starts with. The disk call warms file access, so its success shows in the build logs, not in the invoke response.

# Case Steps Result Evidence
M1 Memory and disk handlers, path /warmup (re-run on the previous port revision) 1. CreateAgentRuntime with platformVersion="V2", hooksConfiguration.build.warmup.action.httpPost.path=/warmup, and both handlers enabled.
2. Poll GetAgentRuntime until the status is READY or CREATE_FAILED.
3. Read the build logs: the [LIFECYCLE-HOOK …] lines and the SDK's Warmup (…) lines.
4. InvokeAgentRuntime with a new session.
5. Delete the runtime.
✅ READY Warmup (disk) completed (0.550s); warmup hook (memory) succeeded, warmup hook (disk) succeeded; invoke {"memory_warmed": true, "disk_warmed": false}
M2 Memory handler only (re-run on the previous port revision) As M1, with only the memory handler enabled. ✅ READY Warmup (disk): no handler registered, nothing to do; warmup hook (disk) succeeded; invoke true/false
M3 Disk handler only As M1, with only the disk handler enabled. ✅ READY Warmup (memory): no handler registered, nothing to do; warmup hook (disk) succeeded in 0.8 s; invoke false/false
M4 Hook path /ping (the same path as the health check) As M1, with httpPost.path=/ping and HookConfig(path="/ping"). The platform's own GET /ping health checks run on the same path throughout. ✅ READY POST /ping accepted as the hook route; both calls succeeded while the health checks kept passing; invoke true/false
M5 Path mismatch As M1, with httpPost.path=/prepare and HookConfig(path="/warmup"). ✅ CREATE_FAILED [ERROR] warmup hook (memory) failed: POST /prepare on port 8080 returned 404
M6a Memory handler raises (re-run on the previous port revision) As M1, with the memory handler raising RuntimeError. ✅ CREATE_FAILED Warmup (memory) failed (RuntimeError); [ERROR] warmup hook (memory) failed: POST /warmup on port 8080 returned 500
M6b Disk handler raises As M1, with the disk handler raising RuntimeError. ✅ CREATE_FAILED memory succeeded; Warmup (disk) failed (RuntimeError); [ERROR] warmup hook (disk) failed: POST /warmup on port 8080 returned 500
M7 Sync memory handler blocks for 90 s As M1, with the memory handler calling time.sleep(90), so the disk call gets the remaining budget. ✅ READY Warmup (memory) completed (90.000s); warmup hook (memory) succeeded in 90.0 s (30.0 s of the 120 s warmup budget left); no health-check failures; invoke true/false
M8 Decorator in the code, no hooksConfiguration As M1, without hooksConfiguration. ✅ READY no [LIFECYCLE-HOOK] lines; invoke {"memory_warmed": false, "disk_warmed": false}
M9 M1 through UpdateAgentRuntime 1. Create the M1 runtime and wait for READY.
2. UpdateAgentRuntime with the same artifact, role, network, platform version, environment and hooksConfiguration (an update replaces the whole hook config, so it must be included).
3. Poll until READY or UPDATE_FAILED.
4. Read the build logs and invoke, as in M1.
5. Delete the runtime.
✅ READY (version 2) a second build shows warmup hook (memory) succeeded and warmup hook (disk) succeeded; invoke true/false

Excerpts per case (from the build logs and invoke responses; IDs replaced with placeholders):

M1: memory and disk handlers, path /warmup (previous port revision)

Create request (parameters; the other cases differ only as noted in the Steps column):

client.create_agent_runtime(
    agentRuntimeName="sdk746e2e2_M1_<suffix>",
    agentRuntimeArtifact={"containerConfiguration": {"containerUri": "<ecr-image-uri>"}},
    roleArn="<execution-role-arn>",
    networkConfiguration={"networkMode": "PUBLIC"},
    platformVersion="V2",
    environmentVariables={"WARMUP_HANDLERS": "memory,disk"},  # P cases add "WARMUP_PORT"
    hooksConfiguration={"build": {"warmup": {"action": {"httpPost": {"path": "/warmup"}}}}},
)
status=CREATING → status=READY (198 s)
[agent] warmup_hook=HookConfig(path='/warmup', port=None)
[LIFECYCLE-HOOK …] [LIFECYCLE] warmup hook (memory) started with 120.0 s of the 120 s warmup budget left
{"level": "INFO", "message": "Warmup (memory) completed (0.000s)", "logger": "bedrock_agentcore.app"}
[LIFECYCLE-HOOK …] [LIFECYCLE] warmup hook (memory) succeeded in 0.0 s (120.0 s of the 120 s warmup budget left)
[LIFECYCLE-HOOK …] [LIFECYCLE] warmup hook (disk) started with 120.0 s of the 120 s warmup budget left
{"level": "INFO", "message": "Warmup (disk) completed (0.550s)", "logger": "bedrock_agentcore.app"}
[LIFECYCLE-HOOK …] [LIFECYCLE] warmup hook (disk) succeeded in 0.6 s (119.4 s of the 120 s warmup budget left)
invoke → 200 {"memory_warmed": true, "disk_warmed": false}
M2: memory handler only (previous port revision)
status=CREATING → status=READY (198 s)
[LIFECYCLE-HOOK …] [LIFECYCLE] warmup hook (memory) started with 120.0 s of the 120 s warmup budget left
{"level": "INFO", "message": "Warmup (memory) completed (0.000s)", "logger": "bedrock_agentcore.app"}
[LIFECYCLE-HOOK …] [LIFECYCLE] warmup hook (memory) succeeded in 0.0 s (120.0 s of the 120 s warmup budget left)
[LIFECYCLE-HOOK …] [LIFECYCLE] warmup hook (disk) started with 120.0 s of the 120 s warmup budget left
{"level": "INFO", "message": "Warmup (disk): no handler registered, nothing to do", "logger": "bedrock_agentcore.app"}
[LIFECYCLE-HOOK …] [LIFECYCLE] warmup hook (disk) succeeded in 0.0 s (120.0 s of the 120 s warmup budget left)
invoke → 200 {"memory_warmed": true, "disk_warmed": false}
M3: disk handler only (639971d)
status=CREATING → status=READY (205 s)
[LIFECYCLE-HOOK …] [LIFECYCLE] warmup hook (memory) started with 120.0 s of the 120 s warmup budget left
{"level": "INFO", "message": "Warmup (memory): no handler registered, nothing to do", "logger": "bedrock_agentcore.app"}
[LIFECYCLE-HOOK …] [LIFECYCLE] warmup hook (memory) succeeded in 0.0 s (120.0 s of the 120 s warmup budget left)
[LIFECYCLE-HOOK …] [LIFECYCLE] warmup hook (disk) started with 120.0 s of the 120 s warmup budget left
[LIFECYCLE-HOOK …] [LIFECYCLE] warmup hook (disk) succeeded in 0.8 s (119.2 s of the 120 s warmup budget left)
invoke → 200 {"memory_warmed": false, "disk_warmed": false}
M4: hook path /ping (the same path as the health check) (639971d)
status=CREATING → status=READY (207 s)
[agent] startup WARMUP_PATH=/ping WARMUP_HANDLERS=['memory', 'disk']
[LIFECYCLE-HOOK …] [LIFECYCLE] warmup hook (memory) started with 120.0 s of the 120 s warmup budget left
[LIFECYCLE-HOOK …] [LIFECYCLE] warmup hook (memory) succeeded in 0.0 s (120.0 s of the 120 s warmup budget left)
[LIFECYCLE-HOOK …] [LIFECYCLE] warmup hook (disk) started with 120.0 s of the 120 s warmup budget left
[LIFECYCLE-HOOK …] [LIFECYCLE] warmup hook (disk) succeeded in 0.0 s (120.0 s of the 120 s warmup budget left)
invoke → 200 {"memory_warmed": true, "disk_warmed": false}
M5: path mismatch (639971d)
status=CREATING → status=CREATE_FAILED (111 s)
failureReason: A lifecycle hook failed. Check your runtime's logs for which hook failed and why. ...
[LIFECYCLE-HOOK …] [LIFECYCLE] warmup hook (memory) started with 120.0 s of the 120 s warmup budget left
[LIFECYCLE-HOOK …] [ERROR] warmup hook (memory) failed: POST /prepare on port 8080 returned 404 after 0.0 s
M6a: memory handler raises (previous port revision)
status=CREATING → status=CREATE_FAILED (122 s)
failureReason: A lifecycle hook failed. Check your runtime's logs for which hook failed and why. ...
[LIFECYCLE-HOOK …] [LIFECYCLE] warmup hook (memory) started with 120.0 s of the 120 s warmup budget left
{"level": "ERROR", "message": "Warmup (memory) failed (0.000s)", "logger": "bedrock_agentcore.app", "errorType": "RuntimeError", "errorMessage": "memory warmup failed on purpose"}
[LIFECYCLE-HOOK …] [ERROR] warmup hook (memory) failed: POST /warmup on port 8080 returned 500 after 0.0 s
M6b: disk handler raises (639971d)
status=CREATING → status=CREATE_FAILED (203 s)
[LIFECYCLE-HOOK …] [LIFECYCLE] warmup hook (memory) started with 120.0 s of the 120 s warmup budget left
{"level": "INFO", "message": "Warmup (memory) completed (0.000s)", "logger": "bedrock_agentcore.app"}
[LIFECYCLE-HOOK …] [LIFECYCLE] warmup hook (memory) succeeded in 0.0 s (120.0 s of the 120 s warmup budget left)
[LIFECYCLE-HOOK …] [LIFECYCLE] warmup hook (disk) started with 120.0 s of the 120 s warmup budget left
{"level": "ERROR", "message": "Warmup (disk) failed (0.017s)", "logger": "bedrock_agentcore.app", "errorType": "RuntimeError", "errorMessage": "disk warmup failed on purpose"}
[LIFECYCLE-HOOK …] [ERROR] warmup hook (disk) failed: POST /warmup on port 8080 returned 500 after 0.3 s
M7: sync memory handler blocks for 90 s (639971d)
status=CREATING → status=READY (295 s)
[LIFECYCLE-HOOK …] [LIFECYCLE] warmup hook (memory) started with 120.0 s of the 120 s warmup budget left
{"level": "INFO", "message": "Warmup (memory) completed (90.000s)", "logger": "bedrock_agentcore.app"}
[LIFECYCLE-HOOK …] [LIFECYCLE] warmup hook (memory) succeeded in 90.0 s (30.0 s of the 120 s warmup budget left)
[LIFECYCLE-HOOK …] [LIFECYCLE] warmup hook (disk) started with 30.0 s of the 120 s warmup budget left
{"level": "INFO", "message": "Warmup (disk) completed (0.861s)", "logger": "bedrock_agentcore.app"}
[LIFECYCLE-HOOK …] [LIFECYCLE] warmup hook (disk) succeeded in 0.9 s (29.1 s of the 120 s warmup budget left)
invoke → 200 {"memory_warmed": true, "disk_warmed": false}
M8: decorator in the code, no hooksConfiguration (639971d)
status=CREATING → status=READY (185 s)
build logs: no [LIFECYCLE-HOOK] lines
invoke → 200 {"memory_warmed": false, "disk_warmed": false}
M9: M1 through UpdateAgentRuntime (639971d)
create:  status=CREATING → status=READY (185 s), version 1
[LIFECYCLE-HOOK …] [LIFECYCLE] warmup hook (memory) started with 120.0 s of the 120 s warmup budget left
[LIFECYCLE-HOOK …] [LIFECYCLE] warmup hook (memory) succeeded in 0.0 s (120.0 s of the 120 s warmup budget left)
[LIFECYCLE-HOOK …] [LIFECYCLE] warmup hook (disk) started with 120.0 s of the 120 s warmup budget left
[LIFECYCLE-HOOK …] [LIFECYCLE] warmup hook (disk) succeeded in 0.6 s (119.4 s of the 120 s warmup budget left)
update:  UpdateAgentRuntime (same hooksConfiguration) → status=UPDATING, version 2 → status=READY, version 2
second build:
[LIFECYCLE-HOOK …] [LIFECYCLE] warmup hook (memory) started with 120.0 s of the 120 s warmup budget left
{"level": "INFO", "message": "Warmup (memory) completed (0.000s)", "logger": "bedrock_agentcore.app"}
[LIFECYCLE-HOOK …] [LIFECYCLE] warmup hook (memory) succeeded in 0.0 s (120.0 s of the 120 s warmup budget left)
[LIFECYCLE-HOOK …] [LIFECYCLE] warmup hook (disk) started with 120.0 s of the 120 s warmup budget left
{"level": "INFO", "message": "Warmup (disk) completed (0.546s)", "logger": "bedrock_agentcore.app"}
[LIFECYCLE-HOOK …] [LIFECYCLE] warmup hook (disk) succeeded in 0.5 s (119.5 s of the 120 s warmup budget left)
invoke → 200 {"memory_warmed": true, "disk_warmed": false}

End-to-end: hook ports

Run on 2026-11-21 on the current code (see above), with the same agent and steps as M1 (both handlers enabled). WARMUP_PORT on the runtime sets HookConfig.port; unset means HookConfig(path="/warmup"). The app serves on the default port 8080.

# Case Steps Result Evidence
P1 Hook on its own port As M1, with HookConfig(path="/warmup", port=9000) and httpPost.port=9000. ✅ READY Hook server listening on http://127.0.0.1:9000 (POST /warmup); warmup hook (memory) succeeded, warmup hook (disk) succeeded; invoke on 8080 {"memory_warmed": true, "disk_warmed": false}
P2 Hook port equal to the serving port As M1, with HookConfig(path="/warmup", port=8080) and httpPost.port=8080. ✅ READY no Hook server listening line (served on the serving port); both calls succeeded; invoke true/false
P3 SDK port set, httpPost.port unset As M1, with HookConfig(path="/warmup", port=9000) and no httpPost.port. ✅ CREATE_FAILED Hook server listening on http://127.0.0.1:9000 (POST /warmup); [ERROR] warmup hook (memory) failed: POST /warmup on port 8080 returned 404
P4 httpPost.port set, SDK port unset As M1, with HookConfig(path="/warmup") and httpPost.port=9000. ✅ CREATE_FAILED [ERROR] warmup hook (memory) failed: POST /warmup on port 9000: error sending request for url (http://127.0.0.1:9000/warmup)
P1: hook on its own port
hooksConfiguration={"build": {"warmup": {"action": {"httpPost": {"path": "/warmup", "port": 9000}}}}}
environmentVariables={"WARMUP_HANDLERS": "memory,disk", "WARMUP_PORT": "9000"}

status=CREATING → status=READY (198 s)
[agent] warmup_hook=HookConfig(path='/warmup', port=9000)
{"level": "INFO", "message": "Hook server listening on http://127.0.0.1:9000 (POST /warmup)", "logger": "bedrock_agentcore.app"}
[LIFECYCLE-HOOK …] [LIFECYCLE] warmup hook (memory) started with 120.0 s of the 120 s warmup budget left
{"level": "INFO", "message": "Warmup (memory) completed (0.000s)", "logger": "bedrock_agentcore.app"}
[LIFECYCLE-HOOK …] [LIFECYCLE] warmup hook (memory) succeeded in 0.0 s (120.0 s of the 120 s warmup budget left)
[LIFECYCLE-HOOK …] [LIFECYCLE] warmup hook (disk) started with 120.0 s of the 120 s warmup budget left
{"level": "INFO", "message": "Warmup (disk) completed (0.092s)", "logger": "bedrock_agentcore.app"}
[LIFECYCLE-HOOK …] [LIFECYCLE] warmup hook (disk) succeeded in 0.1 s (119.9 s of the 120 s warmup budget left)
invoke (port 8080) → 200 {"memory_warmed": true, "disk_warmed": false}
P2: hook port equal to the serving port
hooksConfiguration={"build": {"warmup": {"action": {"httpPost": {"path": "/warmup", "port": 8080}}}}}
environmentVariables={"WARMUP_HANDLERS": "memory,disk", "WARMUP_PORT": "8080"}

status=CREATING → status=READY (213 s)
[agent] warmup_hook=HookConfig(path='/warmup', port=8080)
build logs: no "Hook server listening" line
[LIFECYCLE-HOOK …] [LIFECYCLE] warmup hook (memory) started with 120.0 s of the 120 s warmup budget left
{"level": "INFO", "message": "Warmup (memory) completed (0.000s)", "logger": "bedrock_agentcore.app"}
[LIFECYCLE-HOOK …] [LIFECYCLE] warmup hook (memory) succeeded in 0.0 s (120.0 s of the 120 s warmup budget left)
[LIFECYCLE-HOOK …] [LIFECYCLE] warmup hook (disk) started with 120.0 s of the 120 s warmup budget left
{"level": "INFO", "message": "Warmup (disk) completed (0.516s)", "logger": "bedrock_agentcore.app"}
[LIFECYCLE-HOOK …] [LIFECYCLE] warmup hook (disk) succeeded in 0.5 s (119.5 s of the 120 s warmup budget left)
invoke → 200 {"memory_warmed": true, "disk_warmed": false}
P3: SDK port set, httpPost.port unset
hooksConfiguration={"build": {"warmup": {"action": {"httpPost": {"path": "/warmup"}}}}}
environmentVariables={"WARMUP_HANDLERS": "memory,disk", "WARMUP_PORT": "9000"}

status=CREATING → status=CREATE_FAILED (107 s)
failureReason: A lifecycle hook failed. Check your runtime's logs for which hook failed and why. ...
[agent] warmup_hook=HookConfig(path='/warmup', port=9000)
{"level": "INFO", "message": "Hook server listening on http://127.0.0.1:9000 (POST /warmup)", "logger": "bedrock_agentcore.app"}
[LIFECYCLE-HOOK …] [LIFECYCLE] warmup hook (memory) started with 120.0 s of the 120 s warmup budget left
[LIFECYCLE-HOOK …] [ERROR] warmup hook (memory) failed: POST /warmup on port 8080 returned 404 after 0.0 s
P4: httpPost.port set, SDK port unset
hooksConfiguration={"build": {"warmup": {"action": {"httpPost": {"path": "/warmup", "port": 9000}}}}}
environmentVariables={"WARMUP_HANDLERS": "memory,disk"}

status=CREATING → status=CREATE_FAILED (122 s)
failureReason: A lifecycle hook failed. Check your runtime's logs for which hook failed and why. ...
[agent] warmup_hook=HookConfig(path='/warmup', port=None)
[LIFECYCLE-HOOK …] [LIFECYCLE] warmup hook (memory) started with 120.0 s of the 120 s warmup budget left
[LIFECYCLE-HOOK …] [ERROR] warmup hook (memory) failed: POST /warmup on port 9000: error sending request for url (http://127.0.0.1:9000/warmup)

naviret added 3 commits November 25, 2026 12:26
…ooks

Add BedrockAgentCoreApp.warmup(WarmupType.MEMORY | WarmupType.DISK) to
register build warmup handlers, and a keyword-only
warmup_hook=HookConfig(path=...) constructor argument that serves them at
POST <path>. The path must equal
hooksConfiguration.build.warmup.action.httpPost.path; the SDK has no
default, and without warmup_hook no route is added and @app.warmup raises.

HookConfig validates the path against the public API constraints
(HttpPostLifecycleHookAction): 1-32 characters, an allowed character set,
and canonical form. The hook is served on the app's serving port, so
httpPost.port must be unset or equal to it. A warmup path that clashes
with an existing route on a shared HTTP method (such as POST
/invocations) raises at construction; POST /ping and POST /ws are
allowed.

The route reads X-Amzn-Bedrock-AgentCore-Runtime-Warmup-Type: a
registered type runs its handler (200 completed; 500 on exception or when
a sync handler returns an awaitable), a type with no handler returns 200
skipped, and a missing or invalid header returns 400. Sync handlers run in
a worker thread and async handlers on a separate event loop, so /ping
keeps answering; an asyncio.Lock keeps warmup handlers from running
concurrently. The dispatch logic moves from _invoke_handler into a shared
_dispatch_handler; _invoke_handler's behavior is unchanged.

Export WarmupType and HookConfig from bedrock_agentcore and
bedrock_agentcore.runtime.

Closes #741
…ypes

A generator or async generator warmup handler passed registration, and
_dispatch_handler then returned a generator nobody iterated: the route
reported completed and the handler body never ran.

- @app.warmup now raises ValueError for a generator function (def or
  async def with yield), also through functools.partial and a callable
  object's __call__. The new _is_generator_callable sits next to
  _is_async_gen_callable.
- _handle_warmup also checks the result at call time: a generator or an
  async generator (including the sync generator _dispatch_handler wraps
  an async generator in) is closed unstarted and the call returns 500
  with a TypeError that mentions yield.

Only a missing or empty (after trimming) warmup type header now returns
400 ({"error": "<header> header is missing or empty"}). Any other unknown
type returns 200 {"status": "ok", "type": <trimmed lower-cased value>,
"result": "skipped"} and logs "Warmup (<value>): unknown type, nothing to
do", so a type the service adds later can't fail the create or update of
agents on this SDK version. WarmupType stays MEMORY and DISK.

README and docstrings describe both behaviors; the integration test now
expects 200 skipped for "cpu" and 400 for a missing header.
…ort)

Add HookConfig.port, matching hooksConfiguration.<hook>.action.httpPost.port:
an integer from 8000 to 12000 (bool rejected), validated with its own
"HookConfig.port ..." ValueError. None, the default, serves the hook on
the serving port as before.

Routes follow the shape of the TypeScript SDK:
- a hook without a port goes on the main app's routes, conflict-checked
  by _add_route as before;
- a hook with a port goes in _hook_port_routes[port], conflict-checked
  against the other hooks on that port;
- app.run(port=P) moves the hooks on P onto the main app, checked against
  the main routes, since only run() knows the serving port.

The main server still starts with plain uvicorn.run(self, ...). When some
hook has a port, the constructor composes the app's lifespan with the
user's lifespan= (any style Starlette accepts, normalized with Starlette's
own Router; the user's lifespan runs nested inside). On startup it binds
each hook port's socket itself on 127.0.0.1, where the runtime calls
hooks (SO_REUSEADDR, inheritable), so a taken port fails with an error
naming the port, then serves each port with a
small Starlette app on a uvicorn.Server subclass whose capture_signals()
is a no-op, as a task on the main loop. It waits until every hook server
has started, so hook ports listen before the serving port opens. On
shutdown it stops the hook servers and waits for them, after the main
server has drained.

Hook ports need app.run():
- run() rejects lifespan="off" when a hook has a port;
- if the lifespan runs without run() (e.g. uvicorn agent:app), startup
  fails with "Hook ports are only served by app.run(); ...", and uvicorn
  exits with code 3;
- if the lifespan is skipped (uvicorn --lifespan off), every HTTP request
  gets 503 with the same message.

Docs: the constructor and HookConfig docstrings and the README say the
hook is served on warmup_hook.port when set, otherwise on the serving
port; the port must equal httpPost.port (omit both for the serving
port); a separate port needs app.run() and one server process.

Tests: port validation; routes and conflicts per port; merge onto the
main app; lifespan="off" rejected; the 503 path; the lifespan starting
and stopping hook servers around the user's lifespan; taken ports;
hook ports bound to loopback; signal handlers left to the main server. The
new integration test covers the hook on its own port (warmup on the hook
port, 404 for /warmup on the serving port, /ping Healthy during a
blocking handler, one SIGTERM closing both ports), the uvicorn CLI launch
exiting with code 3, and a taken hook port exiting before the serving
port opens.
@github-actions

Copy link
Copy Markdown
Contributor

✅ No Breaking Changes Detected

No public API breaking changes found in this PR.

@agentcore-devx-automation agentcore-devx-automation Bot added the claude-security-reviewing Claude Code /security-review in progress label Nov 25, 2026
@agentcore-devx-automation

Copy link
Copy Markdown
Contributor

Claude Security Review: no high-confidence findings. (run)

@agentcore-devx-automation agentcore-devx-automation Bot removed the claude-security-reviewing Claude Code /security-review in progress label Nov 25, 2026
@jariy17
jariy17 merged commit 62f8fc6 into main Nov 25, 2026
49 of 57 checks passed

This branch was previously deployed

1 inactive deployment
auto-approve — dd38a6fe Deployed Nov 25, 2026 by jariy17 via Test (gateway) #1736
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size/xl PR size: XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Feature request: @app.warmup decorator for AgentCore Runtime build-warmup lifecycle hooks

2 participants