Skip to content

Studio: fewer GC passes while the backend imports, RSA key generated alongside startup - #15586

Merged
danielhanchen merged 5 commits into
mainfrom
studio-backend-startup
Oct 28, 2026
Merged

danielhanchen merged 5 commits into
mainfrom
studio-backend-startup

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 27, 2026 •

Copy link
Copy Markdown
Member

Two pieces of work sit on the Studio backend's startup path that do not need to: the cyclic GC repeatedly scans a heap that only grows while run.py imports the backend, and the API key RSA pair is generated inline in the lifespan before the server is ready.

What changes

  • studio/backend/run.py: around from main import app, ..., the generation 0 GC threshold is raised to max(current, 100_000) and restored in a finally, even if the import fails. A threshold of 0 (automatic GC turned off by an embedder) is left alone.
  • core/inference/key_exchange.py + main.py: the lifespan starts RSA key generation on a thread first and installs the key at the same point as before, before the watchdog and before yield. A generation error is re-raised there, so a failure still fails startup; init_key_pair() with no argument behaves as before. Key generation releases the GIL (the main thread kept 91% of its speed while it ran).

Results

GC threshold, paired measurement of the backend import (n=6):

main this PR
Collections during the import (gen 0 / 1 / 2) 248 / 23 / 2 6 / 0 / 0
Time inside the GC (median) 518 ms 149 ms
Import CPU (median) 5300 ms 4796 ms (-9.5%)

RSA key: generated inline it took 24 to 77 ms on the lifespan path (median about 39 ms); here the lifespan waits 0.15 to 0.34 ms for it (n=6).

Tests

  • New studio/backend/tests/test_backend_import_gc_threshold.py (2: main is imported inside a try whose finally restores the threshold, and the threshold is raised before the import and only when automatic GC is on) and test_key_pair_startup_overlap.py (4: the key generated off thread is the one installed, a generation error is re-raised at install, init_key_pair() still generates synchronously, and the lifespan starts generation first and installs it before serving). Both fail on main and pass here.
  • Full studio/backend/tests on both sides (-n 12): the same failures on both (environment-specific); the tests that differed on one side were timing under load and pass on both sides when rerun at -n 4 (513 passed, 1 skipped each).
  • Staging CI on ubuntu-latest, windows-latest and macos-15 (Apple Silicon): the startup tests ran and passed on each (6 passed per OS).

Not covered

  • Time to first /api/health on a real server moved by less than the 5 to 7 s run-to-run spread on the test host, so I am not claiming a wall-clock number.
  • gc.freeze() after warm-up was measured and not kept: once warm the backend heap stops growing, so it added one forced full collection and saved none.

danielhanchen added a commit that referenced this pull request Oct 28, 2026
…, and name any test that still does (#15626)

## Summary

Backend CI (`(Python 3.13, a-f)`) and `Repo tests (CPU, rest)` have been
failing intermittently with dozens of errors like

```
AttributeError: torch._dynamo.config.recompile_limit does not exist
AttributeError: torch._dynamo.config.suppress_errors does not exist
AttributeError: torch._inductor.config.emulate_precision_casts does not exist
```

Seen on #15586, #15589, #15590, #15592, #15593, #15596 and #15601.
Locally, on pytest 9.1.1, it never reproduced.

### Root cause

CI resolves pytest 9.2.0, which changed `MonkeyPatch.setattr`
(pytest-dev/pytest#10644).
- For a non-class target it now records the old value from the instance
`__dict__`. Before, it used `getattr`.
- A torch `ConfigModule` (`torch._dynamo.config`,
`torch._inductor.config`, and its `SubConfigProxy` children such as
`torch._inductor.config.triton`) serves its entries from `__getattr__`.
They are never in `__dict__`, so pytest records "not set".
- On undo it therefore calls `delattr`. `ConfigModule.__delattr__` marks
the entry hidden, and every later read in that process raises `... does
not exist`.

So every `monkeypatch.setattr(torch._dynamo.config, ...)` in the suite
now deletes the entry it patched. Which shard fails depends on which
xdist worker such a test lands on.

Minimal reproduction:

```python
def test_patch(monkeypatch):
    monkeypatch.setattr(torch._dynamo.config, "suppress_errors", True)

def test_after():
    assert torch._dynamo.config.suppress_errors is False
```

On pytest 9.1.1 both pass. On 9.2.0 `test_after` fails with
`torch._dynamo.config.suppress_errors does not exist`.

## Change

`tests/_shared/torch_config_guard.py`, installed from
`tests/conftest.py` and `studio/backend/tests/conftest.py`:
- **`install_monkeypatch_fix()`:** wraps `pytest.MonkeyPatch.setattr`.
When the target is a torch `ConfigModule` or `SubConfigProxy`, including
the dotted-string form, it records the real value that was replaced, so
`undo()` restores it with `setattr` instead of deleting the entry. Every
other target goes through pytest unchanged. The fix is a no-op until
torch is imported, and it never imports torch itself.
- **`_no_deleted_torch_config_entries` autouse fixture:** any test that
still leaves a config entry deleted, by any route, errors at its own
teardown with the stack of the delete. The entry is then restored with
its previous value, so the rest of the worker is not poisoned. Cost is
about 24 us per test.

The guard is what found the cause. On the first push (guard only),
staging CI named 15 deletes, and every recorded stack ended in
`_pytest/monkeypatch.py, line 437, in undo: delattr(obj, name)`.

## Testing

**Under pytest 9.2.0** (CI's version):
- `tests/test_torch_config_guard.py`: 10 passed. Two tests pin the fix:
- `test_monkeypatch_undo_restores_a_config_entry_instead_of_deleting_it`
covers `torch._dynamo.config`, `torch._inductor.config` and
`torch._inductor.config.triton`.
- `test_monkeypatch_undo_restores_a_config_entry_named_by_import_path`
covers the dotted-string form.
- **Sabotage:** with `install_monkeypatch_fix` turned into a no-op,
those 4 cases fail and the guard errors at teardown.
- `tests/test_block_compile.py`: 13 failed on main (`suppress_errors` /
`recompile_limit does not exist`, the CI signature), 42 passed with this
change.

**Under pytest 9.1.1:**
- `tests/test_torch_config_guard.py`: 10 passed, and
`tests/test_block_compile.py`: 42 passed, on both trees.
- `studio/backend/tests/test_diffusion_*.py` (about 17,400 tests, run in
parallel with main on one loaded host): the guard fired 0 times. The
branch had 67 failed / 14 errors against 79 / 26 on main. The 3 failures
seen only on the branch pass when rerun alone, so they are load flakes.
- Meta-tests that read conftests and `tests/_shared`, plus
`test_ci_backend_pytest_shards.py`: 604 passed.
@danielhanchen danielhanchen self-assigned this Oct 28, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 28, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-28T09:29:41.432554Z
We couldn’t complete this review. Comment @codex review to try again.
5d5bef0 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: e74c7c85b8

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen
danielhanchen marked this pull request as ready for review October 28, 2026 09:29
@danielhanchen
danielhanchen merged commit 7362fbc into main Oct 28, 2026
5 of 52 checks passed
@danielhanchen
danielhanchen deleted the studio-backend-startup branch October 28, 2026 11:58
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant