Skip to content

Commit 6bad979

Browse files
Release result sessions of stateless generate calls too
Addresses the second review on #21: a call to the exposed generate API without a Gradio session_hash skipped the registry, so its result sessions stayed in the store until Studio's global eviction. Such a call now gets its own key in the same bounded registry, so its results are released in order when the registry evicts it. The caller still receives the session ids it was returned.
1 parent 26cc563 commit 6bad979

2 files changed

Lines changed: 40 additions & 13 deletions

File tree

‎packages/api/annotation_studio/gradio.py‎

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import asyncio
44
import html
55
import logging
6+
import secrets
67
import tempfile
78
import zipfile
89
from collections import OrderedDict
@@ -192,7 +193,10 @@ async def generate(
192193
progress: gr.Progress = gr.Progress(), # noqa: B008
193194
) -> tuple:
194195
headers = identity_headers(request)
195-
client = getattr(request, "session_hash", None)
196+
# A browser tab is tracked by its Gradio session; a call without one (the exposed API used
197+
# statelessly) gets its own key, so its results are still released when the bounded
198+
# registry evicts it instead of waiting for Studio's global eviction.
199+
client = getattr(request, "session_hash", None) or f"api-{secrets.token_hex(8)}"
196200
opened: list[str] = [] # result sessions created in this call, for cleanup on failure
197201
try:
198202
progress(None, desc="Checking current edits…")
@@ -217,18 +221,17 @@ async def generate(
217221
paths[result_id] = download.move_resource_to_block_cache(path)
218222
choices.append((f"Design {index}", result_id))
219223
result_id = choices[1][1]
220-
if client is not None:
221-
previous = results_by_client.get(client, [])
222-
# Keep the session generated from when it was one of this tab's tracked results,
223-
# so a later generation from a different source still releases it.
224-
retained = [session_id] if session_id in previous else []
225-
stale = [key for key in previous if key not in opened and key not in retained]
226-
results_by_client[client] = opened + retained
227-
results_by_client.move_to_end(client)
228-
while len(results_by_client) > MAX_TRACKED_CLIENTS:
229-
_evicted, evicted_ids = results_by_client.popitem(last=False)
230-
stale.extend(key for key in evicted_ids if key not in opened)
231-
await handoff.close(stale, headers)
224+
previous = results_by_client.get(client, [])
225+
# Keep the session generated from when it was one of this tab's tracked results,
226+
# so a later generation from a different source still releases it.
227+
retained = [session_id] if session_id in previous else []
228+
stale = [key for key in previous if key not in opened and key not in retained]
229+
results_by_client[client] = opened + retained
230+
results_by_client.move_to_end(client)
231+
while len(results_by_client) > MAX_TRACKED_CLIENTS:
232+
_evicted, evicted_ids = results_by_client.popitem(last=False)
233+
stale.extend(key for key in evicted_ids if key not in opened)
234+
await handoff.close(stale, headers)
232235
warnings = "; ".join(issue["message"] for issue in snapshot["issues"])
233236
message = f"Generated from input revision {snapshot['revision']}. {warnings}".strip()
234237
return (

‎tests/test_backend_review_fixes.py‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -174,3 +174,27 @@ async def run():
174174
asyncio.run(run())
175175
finally:
176176
demo.close()
177+
178+
179+
def test_stateless_api_generations_are_released_by_the_bounded_registry(monkeypatch) -> None:
180+
"""Calls without a Gradio session (the exposed API used statelessly) are tracked too, so their
181+
result sessions are released when the registry evicts them rather than leaking."""
182+
import annotation_studio.gradio as gradio_module
183+
184+
monkeypatch.setattr(gradio_module, "MAX_TRACKED_CLIENTS", 2)
185+
demo, callbacks = _demo_callbacks()
186+
187+
async def run():
188+
http = TestClient(app)
189+
src = http.post("/api/sessions", files={"file": ("input.cif", FIXTURE.read_bytes())}).json()["session_id"]
190+
designs = []
191+
for _ in range(3): # three stateless calls exceed the cap of two tracked entries
192+
out = await callbacks["generate"](src, *_generate_values(1), request=None)
193+
designs.append(next(key for key in out[2] if key != src))
194+
assert http.get(f"/api/sessions/{designs[0]}").status_code == 404, "stateless results leaked"
195+
assert all(http.get(f"/api/sessions/{d}").status_code == 200 for d in designs[1:])
196+
197+
try:
198+
asyncio.run(run())
199+
finally:
200+
demo.close()

0 commit comments

Comments
 (0)