Skip to content

Commit 2a13c74

Browse files
fix(python): address hosted integration lifecycle review
1 parent 72f4435 commit 2a13c74

10 files changed

Lines changed: 103 additions & 188 deletions

File tree

‎python/samples/02-agents/harness/build_your_own_claw/claw_step04_production_ready/README.md‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -117,9 +117,11 @@ instances. Local hosts keep their original builder defaults.
117117
118118
Request-lifetime middleware releases only this agent's background-provider
119119
tasks for the active MAF session, in a `finally` path on success, failure or
120-
cancellation. Streaming teardown wraps **consumption**, not construction of a
121-
lazy stream. Outstanding research is cancelled and joined before the request's transports
122-
close, using the provider's finite **30-second** default. A child that ignores
120+
cancellation. An idempotent cleanup hook on the outer stream also handles a
121+
stream closed **before its first update**, while the iterator's `finally`
122+
handles partial consumption and run errors. Outstanding research is cancelled
123+
and joined before the request's transports close, using the provider's finite
124+
**30-second** default. A child that ignores
123125
cancellation is abandoned and logged when that bound expires, so it cannot
124126
hold transport teardown open indefinitely. Complete/collect research within a
125127
turn; unfinished runtime tasks cannot be resumed by a later factory-created

‎python/samples/02-agents/harness/build_your_own_claw/claw_step04_production_ready/hosted.py‎

Lines changed: 30 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -186,18 +186,39 @@ async def release_background() -> AsyncIterator[None]:
186186
raise
187187
inner = context.result
188188
if not isinstance(inner, ResponseStream):
189-
raise RuntimeError("The streaming hosted harness must return a ResponseStream.")
189+
async with release_background():
190+
raise RuntimeError("The streaming hosted harness must return a ResponseStream.")
190191

191-
async def updates() -> AsyncIterator[AgentResponseUpdate]:
192+
cleaned_up = False
193+
194+
async def cleanup() -> None:
195+
nonlocal cleaned_up
196+
if cleaned_up:
197+
return
198+
cleaned_up = True
192199
async with release_background():
193-
try:
194-
async for update in inner:
195-
yield update
196-
await inner.get_final_response()
197-
finally:
198-
await inner.close()
200+
await inner.close()
199201

200-
context.result = ResponseStream(updates(), finalizer=lambda _: inner.get_final_response())
202+
async def updates() -> AsyncIterator[AgentResponseUpdate]:
203+
run_failed = False
204+
try:
205+
async for update in inner:
206+
yield update
207+
await inner.get_final_response()
208+
except BaseException:
209+
run_failed = True
210+
raise
211+
finally:
212+
try:
213+
await cleanup()
214+
except BaseException as cleanup_error:
215+
logger.error("Failed to clean up the request stream (%s).", type(cleanup_error).__name__)
216+
if not run_failed:
217+
raise
218+
219+
context.result = ResponseStream(
220+
updates(), finalizer=lambda _: inner.get_final_response(), cleanup_hooks=[cleanup]
221+
)
201222
else:
202223
async with release_background():
203224
await call_next()

‎python/samples/04-hosting/foundry-hosted-agents/responses/custom_storage/README.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,15 @@ snapshot under a response ID and a conversation ID; each key has its own ETag.
2222
The snapshot's inner `session_id` is preserved when loading. Keys are not built
2323
from caller model options or an inner model-service session ID.
2424

25+
Cosmos items have a 2 MB service limit. Before a create or replacement, this
26+
sample checks the complete compact, escaped-JSON snapshot against a conservative
27+
**2,000,000-byte budget**, leaving room for service metadata. Oversized state
28+
fails explicitly before a backend write; a service 413 also becomes an
29+
actionable size error. Reduce the state or start a new conversation instead of
30+
retrying an oversized snapshot. This per-item check is not a retention policy
31+
or aggregate storage quota; those remain tracked in
32+
microsoft/agent-framework#8901.
33+
2534
**Existing unscoped data is not migrated.** The old `/user_id` container layout
2635
and connection-string configuration are intentionally replaced. Use a new
2736
container partitioned by `/scope_key` and start fresh conversations; do not fall

‎python/samples/04-hosting/foundry-hosted-agents/responses/custom_storage/main.py‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626

2727
import asyncio
2828
import hashlib
29+
import json
2930
import os
3031
import uuid
3132
from contextlib import AsyncExitStack
@@ -44,6 +45,10 @@
4445
from dotenv import load_dotenv
4546

4647
_CONFLICT = "Another request advanced this agent session; reload before writing."
48+
_MAX_COSMOS_ITEM_BYTES = 2_000_000
49+
_SESSION_TOO_LARGE = (
50+
"Agent session exceeds the 2,000,000-byte Cosmos snapshot budget; reduce session state or start a new conversation."
51+
)
4752

4853

4954
class CosmosSessionStore(SessionStore):
@@ -91,6 +96,8 @@ async def set(self, session_id: str, session: AgentSession) -> None:
9196
"scope_key": self._scope_key,
9297
"session": session.to_dict(),
9398
}
99+
if len(json.dumps(item, separators=(",", ":")).encode("utf-8")) > _MAX_COSMOS_ITEM_BYTES:
100+
raise ValueError(_SESSION_TOO_LARGE)
94101
try:
95102
etag = self._etags.get(session_id)
96103
if etag is None:
@@ -103,6 +110,8 @@ async def set(self, session_id: str, session: AgentSession) -> None:
103110
match_condition=MatchConditions.IfNotModified,
104111
)
105112
except CosmosHttpResponseError as exc:
113+
if exc.status_code == 413:
114+
raise ValueError(_SESSION_TOO_LARGE) from exc
106115
if exc.status_code not in (409, 412):
107116
raise
108117
raise RuntimeError(_CONFLICT) from exc

‎python/samples/04-hosting/foundry-hosted-agents/responses/files/README.md‎

Lines changed: 12 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,12 @@ The reader opens every directory component and the file without following
1010
symlinks, using directory descriptors rather than a check-then-open pathname.
1111
Replacing a directory or file with a symlink cannot redirect a read outside the
1212
upload directory. It rejects traversal, absolute paths, Windows-style paths,
13-
control characters, directory/file symlinks, non-regular files, invalid UTF-8 and
13+
control characters, directory/file symlinks, hard links, non-regular files, invalid UTF-8 and
1414
files larger than **1,000,000 bytes**. It checks size before reading, then uses a
1515
bounded read to catch growth during the read. POSIX descriptor-relative,
16-
`O_NOFOLLOW` and `O_DIRECTORY` support are required; unsupported platforms fail
17-
closed rather than falling back to an unsafe reader.
16+
`O_NOFOLLOW` and `O_DIRECTORY` support are required **inside the sandbox** and
17+
for local staging; unsupported platforms fail closed rather than falling back
18+
to an unsafe sandbox reader. The hosted-upload helper can run on Windows.
1819

1920
## Prerequisites and lifecycle
2021

@@ -49,8 +50,12 @@ curl -X POST http://localhost:8088/responses \
4950
-d '{"input":"Read contoso_q1_2026_report.txt and compare Q1 revenue."}'
5051
```
5152

52-
The helper applies the same bounded-read and symlink checks to the selected
53-
source and destination. `--local` never calls Azure. Local query/body session IDs
53+
The explicitly selected developer source is read portably: symlinked source
54+
directories are resolved, the opened file must be regular UTF-8, and the byte
55+
limit is checked before and after a bounded read. That source is operator-chosen,
56+
not a path supplied by the model. The `--local` destination retains the strict
57+
descriptor-relative, no-follow and hard-link checks. `--local` never calls Azure.
58+
Local query/body session IDs
5459
do **not** create separate filesystem sandboxes: a local server is a single-user
5560
development process. To simulate two sandboxes, run hosts with separate `HOME`
5661
directories and upload only to the first. The second must list no uploads and
@@ -74,7 +79,8 @@ SDK prerequisite for hosted-session file operations. The SDK uploads to
7479
`sample_files/contoso_q1_2026_report.txt`, relative to that
7580
sandbox's home directory. A portal/CLI upload to the home directory's root will
7681
not be visible to these tools; specify the `sample_files/` destination, or use
77-
this helper. No real upload is performed by the sample's offline tests.
82+
this helper. Live uploads require separately configured credentials and an
83+
explicitly selected agent/session.
7884

7985
Send the request to the deployed agent's Responses endpoint, routing to the same
8086
sandbox with the **request body** selector:
@@ -101,14 +107,3 @@ same prompt to a fresh sandbox B without uploading: its `list_files()` must be
101107
empty and the named read must fail. Upload separately to B if it needs the file.
102108
Do not claim this live check ran unless those resources and uploads were
103109
explicitly authorized.
104-
105-
## Offline checks
106-
107-
From `python/`, run:
108-
109-
```bash
110-
uv run pytest samples/04-hosting/foundry-hosted-agents/responses/files/tests -q
111-
```
112-
113-
The tests use temporary home directories, including descriptor-replacement
114-
checks. They require no Foundry project, credentials, deployment or real files.

‎python/samples/04-hosting/foundry-hosted-agents/responses/files/file_access.py‎

Lines changed: 26 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,8 @@ def _read_file(directory: int, filename: str) -> bytes:
6969
metadata = os.fstat(descriptor)
7070
if not stat.S_ISREG(metadata.st_mode):
7171
raise ValueError("Only regular uploaded files can be read.")
72+
if metadata.st_nlink != 1:
73+
raise ValueError("Uploaded files must not have hard links.")
7274
if metadata.st_size > MAX_FILE_BYTES:
7375
raise ValueError("Only UTF-8 files of at most 1,000,000 bytes can be read.")
7476
except BaseException:
@@ -91,7 +93,11 @@ def list_uploaded_files() -> list[str]:
9193
return []
9294
try:
9395
with os.scandir(directory) as entries:
94-
return sorted(entry.name for entry in entries if entry.is_file(follow_symlinks=False))
96+
return sorted(
97+
entry.name
98+
for entry in entries
99+
if entry.is_file(follow_symlinks=False) and entry.stat(follow_symlinks=False).st_nlink == 1
100+
)
95101
finally:
96102
os.close(directory)
97103

@@ -107,14 +113,22 @@ def read_uploaded_file(filename: str) -> str:
107113

108114

109115
def read_upload_source(source: Path) -> bytes:
110-
"""Read an explicitly selected local upload, with the same size and symlink checks."""
111-
source = source.expanduser().absolute()
116+
"""Read the operator-selected source portably; sandbox access remains descriptor-relative."""
112117
validate_filename(source.name)
113-
directory = _open_directory(source.parent)
114-
try:
115-
return _read_file(directory, source.name)
116-
finally:
117-
os.close(directory)
118+
source = source.expanduser().resolve(strict=True)
119+
if not source.is_file():
120+
raise ValueError("The upload source must be a regular UTF-8 file.")
121+
with source.open("rb") as file:
122+
metadata = os.fstat(file.fileno())
123+
if not stat.S_ISREG(metadata.st_mode):
124+
raise ValueError("The upload source must be a regular UTF-8 file.")
125+
if metadata.st_size > MAX_FILE_BYTES:
126+
raise ValueError("Only UTF-8 files of at most 1,000,000 bytes can be uploaded.")
127+
data = file.read(MAX_FILE_BYTES + 1)
128+
if len(data) > MAX_FILE_BYTES:
129+
raise ValueError("Only UTF-8 files of at most 1,000,000 bytes can be uploaded.")
130+
data.decode("utf-8")
131+
return data
118132

119133

120134
def write_local_upload(filename: str, data: bytes) -> None:
@@ -132,8 +146,11 @@ def write_local_upload(filename: str, data: bytes) -> None:
132146
dir_fd=directory,
133147
)
134148
try:
135-
if not stat.S_ISREG(os.fstat(descriptor).st_mode):
149+
metadata = os.fstat(descriptor)
150+
if not stat.S_ISREG(metadata.st_mode):
136151
raise ValueError("Only regular uploaded files can be written.")
152+
if metadata.st_nlink != 1:
153+
raise ValueError("Uploaded files must not have hard links.")
137154
except BaseException:
138155
os.close(descriptor)
139156
raise

‎python/samples/04-hosting/foundry-hosted-agents/responses/files/tests/test_file_access.py‎

Lines changed: 0 additions & 150 deletions
This file was deleted.

0 commit comments

Comments
 (0)