Repository navigation
feat(runtime): add @app.warmup decorator for build warmup lifecycle hooks - #754
Merged
Merged
Conversation
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.
jariy17
had a problem deploying
to
auto-approve
November 25, 2026 12:31 — with
GitHub Actions
Failure
jariy17
had a problem deploying
to
auto-approve
November 25, 2026 12:31 — with
GitHub Actions
Failure
Contributor
✅ No Breaking Changes DetectedNo public API breaking changes found in this PR. |
Contributor
|
Claude Security Review: no high-confidence findings. (run) |
nborges-aws
approved these changes
Nov 25, 2026
This was referenced Nov 25, 2026
This branch was previously deployed
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 #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.warmuptoBedrockAgentCoreAppfor the AgentCore Runtime build warmup hook.When a V2 runtime sets
hooksConfiguration.build.warmup, AgentCore Runtime sends twoPOSTrequests to the agent before the runtime isREADY:memory, thendisk. The call type comes in theX-Amzn-Bedrock-AgentCore-Runtime-Warmup-Typeheader. Today each agent has to add the route, parse the header, keep/pingresponsive and map errors to status codes itself. With this change:Behavior
200 {"status": "ok", "type": ..., "result": "completed"}200 {"status": "ok", "type": ..., "result": "skipped"}500 {"error": ..., "type": ...}, which fails the create or update500("declare it with async def")lambda: gen())500(mentionsyield); the generator is closed unstarted, so its body never runscpu)200 {"status": "ok", "type": <trimmed, lower-cased value>, "result": "skipped"}, logged asWarmup (<value>): unknown type, nothing to do400 {"error": "X-Amzn-Bedrock-AgentCore-Runtime-Warmup-Type header is missing or empty"}deforasync defwithyield, also viafunctools.partialor a callable's__call__)ValueErrorwhen the decorator is appliedwarmup_hookValueErrorwhen the decorator is appliedPOST /invocationson the serving port)ValueErrorwhen the app is constructed (or inapp.run()for a hook whose port equals the serving port)portoutside 8000–12000 (or not anint, or abool)ValueErrorwhenHookConfigis createdHookConfig.portset, started withapp.run()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 itHookConfig.portequal to the serving portHookConfig.portset,app.run(lifespan="off")ValueErrorHookConfig.portset, started another way (e.g.uvicorn agent:app)HookConfig.portset, lifespan skipped (uvicorn --lifespan off)503with the same message/pingstays responsive. Sync handlers run in a worker thread and async handlers on a separate event loop, the same as@app.entrypoint.asyncio.Lock.Changes
runtime/models.pyWarmupType(MEMORY,DISK) andWARMUP_TYPE_HEADER.HookConfig(path, port=None): a frozen dataclass.pathis 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.portmatcheshttpPost.port: an integer from 8000 to 12000,boolrejected;Nonemeans the serving port.WarmupTypedocstring: unknown types are answered withskipped.runtime/app.pyBedrockAgentCoreApp(..., *, warmup_hook=None): a new keyword-only argument.Noneadds no route.@app.warmup(type)registers a handler and rejects generator functions (_is_generator_callable);_handle_warmupserves the route, rejects a returned generator, skips unknown types and returns 400 only for a missing or empty header._add_routerejects a route whose(method, path)is already served, naming where (by the apporon port N)._hook_port_routes[port], checked per port.run(port=P)moves the hooks onPonto the main app, checked against the main routes.lifespan=(normalized with Starlette's ownRouter, nested inside ours). It binds each hook port itself on127.0.0.1, serves it with a small Starlette app on auvicorn.Serversubclass 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 plainuvicorn.run(self, ...).__call__answers503when a hook port is configured but the hook servers never started._Hookholds each hook's config, handlers and lock._invoke_handlerinto_dispatch_handler, so warmup handlers can be called with no arguments._invoke_handlerbehaves as before.__init__.py,runtime/__init__.py: exportWarmupTypeandHookConfig.README.md: a "Build Warmup Hook" section, including unknown types, generators andHookConfig.port.Design notes
httpPost.path, soHookConfigrequires 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.HookConfig.portmust equalbuild.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 on127.0.0.1only, the address the runtime calls, even when the app serves on0.0.0.0. The separate port needsapp.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.yieldwould return a generator that nobody iterates, so its body would never run; it's rejected at registration, and a returned generator fails the call.POST /pingandPOST /wsare allowed;POST /invocationsisn't.uvicorn --workers N) only one of them is warmed, and each would try to open the hook port. The README says so.-15, with or without a hook port (checked on uvicorn 0.34.2, 0.35.0 and 0.54.0).Backward compatible
Yes.
warmup_hookis a new keyword-only argument that defaults toNone, so existing apps get no new route and no behavior change.HookConfig.portdefaults toNone, and the extra lifespan is only installed when a hook has a port.Testing
Unit tests in
tests/bedrock_agentcore/runtime/test_app.pyTestWarmup(68 cases):lambda: gen(),lambda: async_gen()and anasync defreturning an async generator, with the generator body never run; 400 with the exact message for a missing, empty or blank header; 200skippedplus the info log forcpu,memory,diskandNetwork; the header matched case-insensitively and trimmed/pinganswersHealthyin < 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 lockdef+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 acceptedwarmup_hook/warmupthen 404s;POST /pingandPOST /wsallowed;POST /invocationsraises; nowarmup_hookmeans no route and the decorator raises; existing positional arguments unchangedHookConfigTestWarmupHookPort(46 cases):None, 8000, 9000, 12000 valid; 7999, 12001, 0, -1, 80,True,False,"8080",8080.0rejected with theHookConfig.portmessage; path checked first/pingor/invocations);/invocationsallowed on a hook port; conflicts checked per port; the lifespan is only replaced when a hook has a portrun()/invocationsraises, 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 throughapp.run()GET /ping,POST /invocationsandPOST /warmupget 503 with the message; no 503 without a hook port or after the merge; WebSocket unaffected/ping404s there,/warmup404s on the main app), then stops it and closes the port; nothing to start after a mergeCan'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 shutdown127.0.0.1when the app runs on0.0.0.0.tests/bedrock_agentcore/test_init.py:WarmupTypeandHookConfigadded to the pinned__all__.Integration tests
tests_integ/runtime/test_warmup_agent.pyruns a generated agent as a real local server. Its memory handler blocks for 2 s; it has no disk handler. The test asserts:completedonly after the work is done;/pings that started during the warmup all returnedHealthyin < 0.5 s;skipped, an unknown type (cpu) returns200 skipped, and a missing header returns400.tests_integ/runtime/test_warmup_hook_port.pyruns an agent withHookConfig(path="/warmup", port=<free port>)and the app on another free port:app.run(): the warmup completes on the hook port (2.0 s);/warmupis 404 on the serving port and/pingis 404 on the hook port; ≥ 5/pings during the blocking memory handler answerHealthyin < 0.5 s; one SIGTERM shuts both servers down gracefully (Application shutdown complete,Hook servers stopped) and closes both ports.uvicorn hook_port_agent:app: exits with code 3 and prints the "only served by app.run()" message; neither port opens.Results (on
3dc7508, on top ofmainatbfa07e5)runtime/app.pymisses only lines it missed before this change, andruntime/models.pyis at 100%.test_runtime_passthrough.py, which needs AWS credentials.test_warmup_hook_port.py:uvicorn module:app--lifespan off-15after graceful shutdown-15-15-15-15-15End-to-end on deployed V2 runtimes
Run against the public
us-west-2endpoints, with an agent image built from this branch's wheel:4ee3750, which differs from3dc7508only in unit tests and docstrings).639971d(the same change asc73a65f, before5fd10a6and3dc7508). Those add the generator check, the unknown-type skip andHookConfig.port; with no hook port, the route, dispatch andcompleted/skipped/500responses 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_warmedis alwaysfalse, 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./warmup(re-run on the previous port revision)CreateAgentRuntimewithplatformVersion="V2",hooksConfiguration.build.warmup.action.httpPost.path=/warmup, and both handlers enabled.2. Poll
GetAgentRuntimeuntil the status isREADYorCREATE_FAILED.3. Read the build logs: the
[LIFECYCLE-HOOK …]lines and the SDK'sWarmup (…)lines.4.
InvokeAgentRuntimewith a new session.5. Delete the runtime.
READYWarmup (disk) completed (0.550s);warmup hook (memory) succeeded,warmup hook (disk) succeeded; invoke{"memory_warmed": true, "disk_warmed": false}READYWarmup (disk): no handler registered, nothing to do;warmup hook (disk) succeeded; invoketrue/falseREADYWarmup (memory): no handler registered, nothing to do;warmup hook (disk) succeeded in 0.8 s; invokefalse/false/ping(the same path as the health check)httpPost.path=/pingandHookConfig(path="/ping"). The platform's ownGET /pinghealth checks run on the same path throughout.READYPOST /pingaccepted as the hook route; both calls succeeded while the health checks kept passing; invoketrue/falsehttpPost.path=/prepareandHookConfig(path="/warmup").CREATE_FAILED[ERROR] warmup hook (memory) failed: POST /prepare on port 8080 returned 404RuntimeError.CREATE_FAILEDWarmup (memory) failed(RuntimeError);[ERROR] warmup hook (memory) failed: POST /warmup on port 8080 returned 500RuntimeError.CREATE_FAILEDWarmup (disk) failed(RuntimeError);[ERROR] warmup hook (disk) failed: POST /warmup on port 8080 returned 500time.sleep(90), so the disk call gets the remaining budget.READYWarmup (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; invoketrue/falsehooksConfigurationhooksConfiguration.READY[LIFECYCLE-HOOK]lines; invoke{"memory_warmed": false, "disk_warmed": false}UpdateAgentRuntimeREADY.2.
UpdateAgentRuntimewith the same artifact, role, network, platform version, environment andhooksConfiguration(an update replaces the whole hook config, so it must be included).3. Poll until
READYorUPDATE_FAILED.4. Read the build logs and invoke, as in M1.
5. Delete the runtime.
READY(version 2)warmup hook (memory) succeededandwarmup hook (disk) succeeded; invoketrue/falseExcerpts 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):
M2: memory handler only (previous port revision)
M3: disk handler only (
639971d)M4: hook path
/ping(the same path as the health check) (639971d)M5: path mismatch (
639971d)M6a: memory handler raises (previous port revision)
M6b: disk handler raises (
639971d)M7: sync memory handler blocks for 90 s (
639971d)M8: decorator in the code, no
hooksConfiguration(639971d)M9: M1 through
UpdateAgentRuntime(639971d)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_PORTon the runtime setsHookConfig.port; unset meansHookConfig(path="/warmup"). The app serves on the default port 8080.HookConfig(path="/warmup", port=9000)andhttpPost.port=9000.READYHook 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}HookConfig(path="/warmup", port=8080)andhttpPost.port=8080.READYHook server listeningline (served on the serving port); both calls succeeded; invoketrue/falsehttpPost.portunsetHookConfig(path="/warmup", port=9000)and nohttpPost.port.CREATE_FAILEDHook server listening on http://127.0.0.1:9000 (POST /warmup);[ERROR] warmup hook (memory) failed: POST /warmup on port 8080 returned 404httpPost.portset, SDK port unsetHookConfig(path="/warmup")andhttpPost.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
P2: hook port equal to the serving port
P3: SDK port set,
httpPost.portunsetP4:
httpPost.portset, SDK port unset