Skip to content

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

Closed
naviret wants to merge 3 commits into
aws:mainfrom
naviret:feat/runtime-warmup-hook
Closed

naviret wants to merge 3 commits into
aws:mainfrom
naviret:feat/runtime-warmup-hook

Conversation

@naviret

@naviret naviret commented Nov 18, 2026 •

Copy link
Copy Markdown

Closes #741

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")
Missing or invalid header 400
Unknown type, duplicate handler, or no warmup_hook ValueError when the decorator is applied
Hook path already served (e.g. POST /invocations) ValueError when the app is constructed
Invalid path ValueError when HookConfig is created
  • /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): 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.
  • runtime/app.py
    • BedrockAgentCoreApp(..., *, warmup_hook=None): a new keyword-only argument. None adds no route.
    • @app.warmup(type) registers a handler; _handle_warmup serves the route.
    • _add_route rejects a route whose (method, path) is already served.
    • _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.

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. The app serves the hook on its serving port, the same port as /ping. In the runtime's hooksConfiguration (CreateAgentRuntime / UpdateAgentRuntime), leave build.warmup.action.httpPost.port unset, so the platform uses the runtime's serving port, or set it to that same port. Serving a hook on a separate port is planned as a follow-up, which will add an optional HookConfig.port without breaking existing code.
  • 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. The README says so.

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.

Testing

Unit tests: TestWarmup (57 cases) in tests/bedrock_agentcore/runtime/test_app.py

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; 400 for a missing, empty, unknown or combined header; 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
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 (string, length, characters, canonical form); unknown port argument rejected; frozen

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

Integration test: 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, and an invalid type returns 400.

Results (on main at c629a24)

uv run pre-commit run --all-files                                   Passed
uv run --python 3.10 pytest tests/ --cov=src                        3876 passed, 10 skipped, 4 xpassed; coverage 91.35%
uv run --python 3.13 pytest tests/ --cov=src                        3876 passed, 10 skipped, 4 xpassed; coverage 91.35%
uv run pytest tests_integ/runtime/{simple,websocket,middleware,warmup}*  14 passed
uv build && uvx twine check dist/*                                  PASSED
  • The new code is fully covered.
  • test_runtime_passthrough.py wasn't run; it needs AWS credentials.
  • Mutation checks: removing the lock, sharing one lock, dropping the awaitable check, skipping the coroutine close(), dropping the conflict check, dropping the canonical-path check, and running sync handlers on the event loop each make a test fail.

End-to-end on deployed V2 runtimes

Run on 2026-11-19 against the public us-west-2 endpoints, with the agent image built from this branch's wheel (639971d).

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 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 hook (memory) succeeded, warmup hook (disk) succeeded; invoke {"memory_warmed": true, "disk_warmed": false}
M2 Memory handler only 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 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

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

client.create_agent_runtime(
    agentRuntimeName="sdk746e2e_M1_<suffix>",
    agentRuntimeArtifact={"containerConfiguration": {"containerUri": "<ecr-image-uri>"}},
    roleArn="<execution-role-arn>",
    networkConfiguration={"networkMode": "PUBLIC"},
    platformVersion="V2",
    environmentVariables={"WARMUP_PATH": "/warmup", "WARMUP_HANDLERS": "memory,disk"},
    hooksConfiguration={"build": {"warmup": {"action": {"httpPost": {"path": "/warmup"}}}}},
)
status=CREATING → status=READY (212 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.001s)", "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.659s)", "logger": "bedrock_agentcore.app"}
[LIFECYCLE-HOOK …] [LIFECYCLE] warmup hook (disk) succeeded in 0.7 s (119.3 s of the 120 s warmup budget left)
invoke → 200 {"memory_warmed": true, "disk_warmed": false}
M2: memory handler only
status=CREATING → status=READY (189 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.001s)", "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
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)
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
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
status=CREATING → status=CREATE_FAILED (95 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
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
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
status=CREATING → status=READY (185 s)
build logs: no [LIFECYCLE-HOOK] lines
invoke → 200 {"memory_warmed": false, "disk_warmed": false}
M9: M1 through UpdateAgentRuntime
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}

@github-actions github-actions Bot added the size/l PR size: L label Nov 18, 2026
@naviret
naviret force-pushed the feat/runtime-warmup-hook branch from c7133dc to 4feb80f Compare November 18, 2026 23:10
@github-actions github-actions Bot added size/l PR size: L and removed size/l PR size: L labels Nov 18, 2026
@naviret
naviret force-pushed the feat/runtime-warmup-hook branch from 4feb80f to 639971d Compare November 19, 2026 01:43
@github-actions github-actions Bot added size/l PR size: L and removed size/l PR size: L labels Nov 19, 2026
@codecov-commenter

codecov-commenter commented Nov 20, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
⚠️ Please upload report for BASE (main@8467c9a). Learn more about missing BASE report.

Additional details and impacted files
@@           Coverage Diff           @@
##             main     #746   +/-   ##
=======================================
  Coverage        ?   89.92%           
=======================================
  Files           ?      130           
  Lines           ?    11703           
  Branches        ?     1839           
=======================================
  Hits            ?    10524           
  Misses          ?      771           
  Partials        ?      408           
Flag Coverage Δ
unittests 89.92% <100.00%> (?)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

…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 aws#741
if warmup_type in handlers:
raise ValueError(f"A {warmup_type.value} warmup handler is already registered")

def register(func: Callable) -> Callable:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A generator or async-generator handler passes registration, then _dispatch_handler returns a generator that nobody iterates. The route reports completed and the handler body never runs. Can we reject generator functions here with a ValueError and add a test?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 40bbb06. @app.warmup raises ValueError for generator and async-generator functions, including ones wrapped in functools.partial or a callable object's __call__. A handler that returns a generator at call time gets a 500. Tests added.

Comment thread src/bedrock_agentcore/runtime/app.py Outdated
except ValueError:
self.logger.warning("Warmup request with invalid %s header: %r", WARMUP_TYPE_HEADER, raw_type)
return JSONResponse(
{"error": f"{WARMUP_TYPE_HEADER} must be 'memory' or 'disk', got {raw_type!r}"}, status_code=400

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we return 200 with result: skipped for an unknown but well-formed warmup type, and keep 400 only for a missing header? If the service adds a third type later, every deployed agent on this SDK version would fail the create.

@naviret naviret Nov 22, 2026 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 40bbb06. An unknown, well-formed type returns 200 {"result": "skipped"}; only a missing or empty header returns 400.

ValueError: If ``path`` doesn't meet the API constraints.
"""

path: str

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we add port to HookConfig, matching hooksConfiguration.<hook>.action.httpPost.port (8000-12000) and TS #330? When it differs from the serving port, serve the hook on its own listener. Customers who run their own server on 8080 need the hook on a separate port.

@naviret naviret Nov 22, 2026 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in e69da55. HookConfig.port (8000-12000) serves the hook on its own listener on 127.0.0.1, in the same process, opened by app.run() before the serving port and closed after it. A port equal to the serving port is served by the main app. The listener is started from the app's lifespan, so a separate port needs app.run(): app.run(lifespan="off") raises ValueError, and other launches (e.g. uvicorn agent:app) fail startup with a message saying so. End-to-end test results will be added to the description.

Comment thread src/bedrock_agentcore/runtime/app.py Outdated
middleware: Optional sequence of Starlette Middleware objects (or Middleware(...) entries)
warmup_hook: Where to serve the build warmup hook (``POST``), registered with ``@app.warmup``.
``warmup_hook.path`` must equal ``hooksConfiguration.build.warmup.action.httpPost.path``, which
the API requires. The hook is served on the serving port, so leave ``httpPost.port`` unset or

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Update this once port is supported: the hook is served on warmup_hook.port when set, otherwise on the serving port.

@naviret naviret Nov 22, 2026 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated in e69da55.

naviret added 2 commits November 21, 2026 12:54
…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 jariy17 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, all my comments are addressed.

@naviret

naviret commented Nov 23, 2026

Copy link
Copy Markdown
Author

Moved to aws/bedrock-agentcore-sdk-python-private#188 so the integration tests and the breaking-change check can run: PRs from forks don't get this repo's token or secrets. It's the same patch approved here, rebased onto that repo's main. Closing this one.

This branch had an error being deployed

1 failed deployment
manual-approval — e69da559 Deployed Nov 22, 2026 by naviret via Test (identity) #1733
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

3 participants