Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
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.
  • Loading branch information
AtharvaTilewale committed Nov 21, 2026
commit 392bc035244725edeaed327d8004382114add736
29 changes: 16 additions & 13 deletions packages/api/annotation_studio/gradio.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import json
import logging
import os
import secrets
import tempfile
import zipfile
from collections import OrderedDict
Expand Down Expand Up @@ -645,7 +646,10 @@ async def generate(
progress: gr.Progress = gr.Progress(), # noqa: B008
) -> tuple:
headers = identity_headers(request)
client = getattr(request, "session_hash", None)
# A browser tab is tracked by its Gradio session; a call without one (the exposed API used
# statelessly) gets its own key, so its results are still released when the bounded
# registry evicts it instead of waiting for Studio's global eviction.
client = getattr(request, "session_hash", None) or f"api-{secrets.token_hex(8)}"
opened: list[str] = [] # result sessions created in this call, for cleanup on failure
try:
progress(None, desc="Checking current edits…")
Expand All @@ -671,18 +675,17 @@ async def generate(
paths[result_id] = download.move_resource_to_block_cache(path)
Comment thread
Copilot marked this conversation as resolved.
Resolved
choices.append((f"Design {index}", result_id))
result_id = choices[1][1]
if client is not None:
previous = results_by_client.get(client, [])
# Keep the session generated from when it was one of this tab's tracked results,
# so a later generation from a different source still releases it.
retained = [session_id] if session_id in previous else []
stale = [key for key in previous if key not in opened and key not in retained]
results_by_client[client] = opened + retained
results_by_client.move_to_end(client)
while len(results_by_client) > MAX_TRACKED_CLIENTS:
_evicted, evicted_ids = results_by_client.popitem(last=False)
stale.extend(key for key in evicted_ids if key not in opened)
await handoff.close(stale, headers)
previous = results_by_client.get(client, [])
# Keep the session generated from when it was one of this tab's tracked results,
# so a later generation from a different source still releases it.
retained = [session_id] if session_id in previous else []
stale = [key for key in previous if key not in opened and key not in retained]
results_by_client[client] = opened + retained
results_by_client.move_to_end(client)
while len(results_by_client) > MAX_TRACKED_CLIENTS:
_evicted, evicted_ids = results_by_client.popitem(last=False)
stale.extend(key for key in evicted_ids if key not in opened)
await handoff.close(stale, headers)
warnings = "; ".join(issue["message"] for issue in snapshot["issues"])
message = f"Generated from input revision {snapshot['revision']}. {warnings}".strip()
designs = [
Expand Down
24 changes: 24 additions & 0 deletions tests/test_backend_review_fixes.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,3 +174,27 @@ async def run():
asyncio.run(run())
finally:
demo.close()


def test_stateless_api_generations_are_released_by_the_bounded_registry(monkeypatch) -> None:
"""Calls without a Gradio session (the exposed API used statelessly) are tracked too, so their
result sessions are released when the registry evicts them rather than leaking."""
import annotation_studio.gradio as gradio_module

monkeypatch.setattr(gradio_module, "MAX_TRACKED_CLIENTS", 2)
demo, callbacks = _demo_callbacks()

async def run():
http = TestClient(app)
src = http.post("/api/sessions", files={"file": ("input.cif", FIXTURE.read_bytes())}).json()["session_id"]
designs = []
for _ in range(3): # three stateless calls exceed the cap of two tracked entries
out = await callbacks["generate"](src, *_generate_values(1), request=None)
designs.append(next(key for key in out[2] if key != src))
assert http.get(f"/api/sessions/{designs[0]}").status_code == 404, "stateless results leaked"
assert all(http.get(f"/api/sessions/{d}").status_code == 200 for d in designs[1:])

try:
asyncio.run(run())
finally:
demo.close()
Loading