Skip to content

Commit 392bc03

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 46bb37c commit 392bc03

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
@@ -5,6 +5,7 @@
55
import json
66
import logging
77
import os
8+
import secrets
89
import tempfile
910
import zipfile
1011
from collections import OrderedDict
@@ -645,7 +646,10 @@ async def generate(
645646
progress: gr.Progress = gr.Progress(), # noqa: B008
646647
) -> tuple:
647648
headers = identity_headers(request)
648-
client = getattr(request, "session_hash", None)
649+
# A browser tab is tracked by its Gradio session; a call without one (the exposed API used
650+
# statelessly) gets its own key, so its results are still released when the bounded
651+
# registry evicts it instead of waiting for Studio's global eviction.
652+
client = getattr(request, "session_hash", None) or f"api-{secrets.token_hex(8)}"
649653
opened: list[str] = [] # result sessions created in this call, for cleanup on failure
650654
try:
651655
progress(None, desc="Checking current edits…")
@@ -671,18 +675,17 @@ async def generate(
671675
paths[result_id] = download.move_resource_to_block_cache(path)
672676
choices.append((f"Design {index}", result_id))
673677
result_id = choices[1][1]
674-
if client is not None:
675-
previous = results_by_client.get(client, [])
676-
# Keep the session generated from when it was one of this tab's tracked results,
677-
# so a later generation from a different source still releases it.
678-
retained = [session_id] if session_id in previous else []
679-
stale = [key for key in previous if key not in opened and key not in retained]
680-
results_by_client[client] = opened + retained
681-
results_by_client.move_to_end(client)
682-
while len(results_by_client) > MAX_TRACKED_CLIENTS:
683-
_evicted, evicted_ids = results_by_client.popitem(last=False)
684-
stale.extend(key for key in evicted_ids if key not in opened)
685-
await handoff.close(stale, headers)
678+
previous = results_by_client.get(client, [])
679+
# Keep the session generated from when it was one of this tab's tracked results,
680+
# so a later generation from a different source still releases it.
681+
retained = [session_id] if session_id in previous else []
682+
stale = [key for key in previous if key not in opened and key not in retained]
683+
results_by_client[client] = opened + retained
684+
results_by_client.move_to_end(client)
685+
while len(results_by_client) > MAX_TRACKED_CLIENTS:
686+
_evicted, evicted_ids = results_by_client.popitem(last=False)
687+
stale.extend(key for key in evicted_ids if key not in opened)
688+
await handoff.close(stale, headers)
686689
warnings = "; ".join(issue["message"] for issue in snapshot["issues"])
687690
message = f"Generated from input revision {snapshot['revision']}. {warnings}".strip()
688691
designs = [

‎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)