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
Next Next commit
Make hosted Gradio sessions identity-aware and restart-safe
- Forward the proxy-authenticated identity header on in-process Studio
  hand-off calls. In ANNOTATION_STUDIO_IDENTITY_HEADER mode every hand-off was
  a 401, so generation could not run, and results are now owned by the user
  whose iframe opens them.
- Release hand-off sessions: generate_cif deletes its temporary input session,
  and a browser tab's earlier designs are deleted when it generates again
  (the session it generated from is kept). Unreleased sessions filled the
  64-slot store and evicted other users' live sessions.
- Persist the document revision in session snapshots so a client's stale
  expected_revision cannot match a different state after a restart. Undo
  history is still memory-only.
  • Loading branch information
AtharvaTilewale committed Nov 21, 2026
commit 444ff456cb26940c455f422a5abf4b651e0cef0e
58 changes: 49 additions & 9 deletions packages/api/annotation_studio/gradio.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,21 +141,45 @@ def validate_refold(self, options: dict) -> dict: ...
}"""


def identity_headers(request: gr.Request | None) -> dict[str, str]:
"""Forward the proxy-authenticated user to Studio for in-process hand-off calls.

In identity mode Studio rejects requests without the configured header, and sessions are
owned by that user. The Gradio request came through the same trusted proxy, so its header
is as trustworthy as the browser's own Studio requests and keeps results openable in the iframe.
"""
from annotation_studio import main as studio_main

header = studio_main.IDENTITY_HEADER
if not header or request is None:
return {}
value = request.headers.get(header)
return {header: value} if value else {}


class StudioHandoff:
"""Use Studio's versioned HTTP contract without sharing document internals."""

def __init__(self, studio: FastAPI, editor_path: str = "/"):
self.editor_path = editor_path
self.transport = httpx.ASGITransport(app=studio)

async def open(self, name: str, cif: str) -> tuple[str, str]:
async with httpx.AsyncClient(transport=self.transport, base_url="http://studio") as client:
async def open(self, name: str, cif: str, headers: dict[str, str] | None = None) -> tuple[str, str]:
async with httpx.AsyncClient(transport=self.transport, base_url="http://studio", headers=headers) as client:
response = await client.post("/api/v1/sessions", files={"file": (name, cif.encode())})
response.raise_for_status()
session = response.json()
session_id = session["session_id"]
return session_id, self.frame(session_id)

async def close(self, session_ids: list[str], headers: dict[str, str] | None = None) -> None:
"""Release hand-off sessions; Studio's bounded store would otherwise evict live user sessions."""
async with httpx.AsyncClient(transport=self.transport, base_url="http://studio", headers=headers) as client:
for session_id in session_ids:
response = await client.delete(f"/api/v1/sessions/{quote(session_id, safe='')}")
if response.status_code not in (204, 404):
response.raise_for_status()

def frame(self, session_id: str | None = None, *, example: str | None = None, card: bool = False) -> str:
"""The editor's frame. With `card` (design-card mode), Studio draws the card in its sidebar and the frame takes
the window's height, as the page does."""
Expand All @@ -173,11 +197,13 @@ def frame(self, session_id: str | None = None, *, example: str | None = None, ca
'allow="clipboard-write; fullscreen; webgpu"></iframe>'
)

async def export(self, session_id: str, warning_checks: frozenset[str]) -> dict:
async def export(
self, session_id: str, warning_checks: frozenset[str], headers: dict[str, str] | None = None
) -> dict:
if not session_id:
raise gr.Error("Open a structure in Studio first")
session_id = quote(session_id, safe="")
async with httpx.AsyncClient(transport=self.transport, base_url="http://studio") as client:
async with httpx.AsyncClient(transport=self.transport, base_url="http://studio", headers=headers) as client:
response = await client.post(f"/api/v1/sessions/{session_id}/export")
response.raise_for_status()
snapshot = response.json()
Expand Down Expand Up @@ -536,6 +562,8 @@ def create_demo(
refold_models=refold_models,
refold_limits=refold_limits,
)
# Result sessions each browser tab created, released when that tab generates again.
results_by_client: dict[str, list[str]] = {}
Comment thread
Copilot marked this conversation as resolved.
Resolved
with gr.Blocks(delete_cache=(3600, 3600)) as demo:
gr.Markdown(f"# {provider.title}")
session = gr.Textbox(visible=False)
Expand Down Expand Up @@ -588,11 +616,15 @@ def check_input(snapshot: dict, options: dict) -> None:
async def run_cifs(cif: str, options: dict) -> list[str]:
return await _run_cifs(generate_fn, cif, options)

async def generate_cif(cif: str, options: dict) -> dict:
async def generate_cif(cif: str, options: dict, request: gr.Request = None) -> dict:
"""Generate from an annotated CIF through the same Studio validation and model path."""
validated = provider.validate(options or {})
session_id, _ = await handoff.open("input.cif", cif)
snapshot = await handoff.export(session_id, provider.warning_checks)
headers = identity_headers(request)
session_id, _ = await handoff.open("input.cif", cif, headers)
try:
snapshot = await handoff.export(session_id, provider.warning_checks, headers)
finally:
await handoff.close([session_id], headers)
check_input(snapshot, validated)
return {
"designs": await run_cifs(snapshot["cif"], validated),
Expand All @@ -602,12 +634,15 @@ async def generate_cif(cif: str, options: dict) -> dict:
async def generate(
session_id: str,
*values,
request: gr.Request = None,
progress: gr.Progress = gr.Progress(), # noqa: B008
) -> tuple:
headers = identity_headers(request)
client = getattr(request, "session_hash", None)
Comment thread
AtharvaTilewale marked this conversation as resolved.
Resolved
try:
progress(None, desc="Checking current edits…")
options = provider.validate(dict(zip(controls, values, strict=True)))
snapshot = await handoff.export(session_id, provider.warning_checks)
snapshot = await handoff.export(session_id, provider.warning_checks, headers)
check_input(snapshot, options)
with tempfile.TemporaryDirectory(prefix="studio-generation-") as directory:
progress(None, desc="Generating design (including any GPU wait)…")
Expand All @@ -623,10 +658,15 @@ async def generate(
for index, cif in enumerate(results, start=1):
path = Path(directory) / f"design-{index}.cif"
path.write_text(cif)
result_id, _ = await handoff.open(path.name, cif)
result_id, _ = await handoff.open(path.name, cif, headers)
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:
# Keep the session generated from (it may itself be an earlier design).
previous = [key for key in results_by_client.get(client, []) if key != session_id]
results_by_client[client] = [key for _, key in choices[1:]]
Comment thread
Copilot marked this conversation as resolved.
Resolved
await handoff.close(previous, headers)
warnings = "; ".join(issue["message"] for issue in snapshot["issues"])
message = f"Generated from input revision {snapshot['revision']}. {warnings}".strip()
designs = [
Expand Down
13 changes: 11 additions & 2 deletions packages/api/annotation_studio/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,8 +120,16 @@ def _persist(self, session_id: str, document: StudioDocument) -> None:
path = self._session_file(session_id)
if path is None:
return
# The revision is what clients send back as expected_revision; restarting it at 0 on reload
# would let a stale confirmation match a different document state. Undo history is not
# persisted (it would cost one CIF per entry on every edit) and starts empty after a reload.
metadata = json.dumps(
{"name": document.name, "owner_id": current_owner(), "design": document.export_design_state()},
{
"name": document.name,
"owner_id": current_owner(),
"revision": document.revision,
"design": document.export_design_state(),
},
separators=(",", ":"),
)
temporary = path.with_name(f".{path.name}.{os.getpid()}.tmp")
Expand All @@ -147,8 +155,9 @@ def _load(self, session_id: str) -> tuple[str, StudioDocument] | None:
)
# What the document remembers beside its atoms: each chain as loaded and what new residues replaced.
document.restore_design_state(metadata.get("design"))
document.revision = int(metadata.get("revision", 0))
return str(metadata.get("owner_id", "local")), document
except (IndexError, KeyError, OSError, ValueError):
except (IndexError, KeyError, OSError, TypeError, ValueError):
path.unlink(missing_ok=True)
return None

Expand Down
99 changes: 99 additions & 0 deletions tests/test_backend_review_fixes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
"""Regressions for hosted-mode session handling: identity hand-off, session release, restart safety."""

import asyncio
from pathlib import Path
from types import SimpleNamespace

import pytest
from annotation_studio import main as studio_main
from annotation_studio.main import DocumentStore, app
from atomworks_studio_editing.document import StudioDocument
from fastapi.testclient import TestClient

FIXTURE = Path(__file__).parent / "fixtures" / "inverse_folding_2kl8.cif"
HEADER = "X-Forwarded-User"


def test_persistent_store_keeps_the_revision_across_reloads(tmp_path) -> None:
store = DocumentStore(tmp_path)
session_id = store.add(StudioDocument.from_cif(FIXTURE.read_text(), "input"))
for value in (1, 0):
store.call(session_id, lambda document, value=value: document.set_charge([0], value=value), persist=True)
assert store.get(session_id).revision == 2

reloaded = DocumentStore(tmp_path).get(session_id)
# Restarting at 0 would let a client's stale expected_revision match a different document.
assert reloaded.revision == 2
assert reloaded.to_cif() == store.get(session_id).to_cif()


class _SamplesProvider:
"""Minimal GenerationProvider: the hand-off is under test, not a model's controls."""

title = "Hand-off test"
default_example = None
warning_checks = frozenset({"missing_atoms"}) # as the RFD4 provider: incomplete residues warn

def controls(self):
import gradio as gr

return {"samples": gr.Number(value=1, precision=0)}

def validate(self, options):
return {"samples": int(options.get("samples") or 1)}

def validate_input(self, snapshot, options):
return None

def example_options(self, example):
return {}


def _demo_callbacks():
pytest.importorskip("gradio")
from annotation_studio.gradio import create_demo

def generate(cif, options):
return [cif] * options["samples"]

demo = create_demo(app, provider=_SamplesProvider(), generate_fn=generate)
return demo, {event.fn.__name__: event.fn for event in demo.fns.values() if event.fn}


def test_gradio_hand_off_works_in_identity_mode_and_releases_sessions(monkeypatch) -> None:
monkeypatch.setattr(studio_main, "IDENTITY_HEADER", HEADER)
demo, callbacks = _demo_callbacks()
alice = SimpleNamespace(headers={HEADER: "alice"}, session_hash="alice-tab")
client = TestClient(app)

def status(session_id: str, user: str) -> int:
return client.get(f"/api/v1/sessions/{session_id}", headers={HEADER: user}).status_code

async def run():
cif = FIXTURE.read_text()
sessions_before = len(studio_main.store._documents)
# Without forwarding the proxy identity, every in-process hand-off call was a 401.
direct = await callbacks["generate_cif"](cif, {"samples": 1}, alice)
assert len(direct["designs"]) == 1
# The temporary API session is released instead of occupying one of the 64 store slots.
assert len(studio_main.store._documents) == sessions_before

source = client.post("/api/v1/sessions", files={"file": ("input.cif", cif.encode())}, headers={HEADER: "alice"})
source_id = source.json()["session_id"]
values = (2,)
first = await callbacks["generate"](source_id, *values, request=alice)
first_results = [key for key in first[2] if key != source_id]
assert len(first_results) == 2
# Results belong to the authenticated user, so the iframe can open them and others cannot.
assert all(status(key, "alice") == 200 for key in first_results)
assert all(status(key, "bob") == 404 for key in first_results)

second = await callbacks["generate"](source_id, *values, request=alice)
assert all(status(key, "alice") == 404 for key in first_results), "earlier designs must be released"
assert all(status(key, "alice") == 200 for key in second[2])
assert status(source_id, "alice") == 200, "the input session must survive"

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