oliver-zehentleitner / maity
performance, hub: plan the move to asyncio (async routes and async database access), plan only
tsk-v874y63b4z8p Open
Owner decision (Oliver, seq 97043): "ok, bauen wir mal mit python weiter und holen wir da raus was geht … machen wir die python implentierung mal ordentlich mit asyncio."
Today, on main: about 1144 synchronous route functions and 21 async def (the long-polls, login, joins, invitations, reports). Database access is synchronous SQLAlchemy 2 (create_engine) on psycopg 3 / PyMySQL / SQLite. Every synchronous request holds an anyio worker thread (default 40 per process) plus a pooled connection.
This card is the plan, not the code. Deliver a plan note on this card that lotse and the owner can decide on:
- Target design: SQLAlchemy
create_async_engine/AsyncConnection; drivers per backend (psycopg 3 async for PostgreSQL, which needs no new dependency; MariaDB: asyncmy or aiomysql; SQLite: aiosqlite or keep it sync for tests and small self-hosts); transactions,deps.py, the second-factor gate, and events.transaction. - Migration path in small PRs: which layer first (engine/deps, then hot routes: auth path, members, project, board, inbox, notifications), how sync and async code live side by side meanwhile, and what stays sync on purpose (worker threads, the probe, alembic).
- Measurement: before/after on the
statsline (busy/waiting worker threads, loop lag) and per-route ms, so every step shows a number. - Risks: race tests, MariaDB, the request-scoped tallies (Server-Timing #1542), background tasks, test suite time on the shared machine.
- Free-threaded Python (3.13t/3.14t, no GIL): does it help us, and when? A short answer is enough.
- Size estimate: number of PRs, order, and what can run in parallel with other cards.
Read first: hub/context/events.md (why the long-poll is already async), hub/context/serving.md (the stats line), hub/context/notifications.md (the thread-pool starvation test), hub/context/replicas.md. Use subagents for the code survey to save your context.
After #1540 is through. The plan goes to lotse; no code PR before the owner's go.
Notes
An agent · Nov 9, 2026, 09:29 UTC
Plan, part 1 of 3: today and the target design (zwhq, from a code survey of main 030542ae; no code yet)
Today:
- 318 routes are
defand 18 areasync def. The auth dependency is async, but it runsauthenticatein the thread pool (deps._resolve,run_in_threadpool(retrying, run)). So a sync route pays two thread hops: authentication, then the route itself. - All database access is Core with a sync
Connection: about 1,900 functions in 189 files takeconn: Connection. The size is 425 files, about 107k lines. - Engines:
- the serving engine (READ COMMITTED, LIFO QueuePool 16+16);
- a shared-counter engine;
- a LISTEN engine;
- a health engine.
- Background work is 20 daemon threads on the sync engine, plus a LISTEN thread (raw psycopg,
conn.notifies). One asyncio task,watch_load, feeds the stats line.
Target:
- Engine:
create_async_enginebeside the sync one, with the same URL rules and options (READ COMMITTED,options/application_name, thedo_connectDNS retry, pool share per replica).
- PostgreSQL:
postgresql+psycopg_async. psycopg 3.3 is already pinned, so no new driver;prepare_threshold=Nonefor PgBouncer carries over. - MariaDB: aiomysql. It is built on PyMySQL, so the error codes our retry and refusal code reads (1213, 1305) stay the same. asyncmy is faster but is its own implementation, so it means more to re-verify.
- SQLite: aiosqlite, so that tests and small self-hosts run the same code path (
BEGIN IMMEDIATEand the pragmas move to the async engine's sync events). - New dependencies: greenlet, aiomysql, aiosqlite.
- The bridge, not a rewrite:
AsyncConnection.run_sync(fn)hands today's syncConnectioncode a connection driven over greenlet. A route becomes:
async def→async with engine.begin() as aconn: return await aconn.run_sync(body)The body and every helper with
conn: Connectionstay as they are. That removes the thread hops without touching 1,900 functions. Native async helpers come only where a measurement asks for them.- The pieces that change:
- `deps._resolve`: awaits
run_syncdirectly; no thread pool. - `db.retrying`: an async twin that sleeps with
asyncio.sleepinstead oftime.sleep. - `events.transaction`: an async context manager with the same
conn.infokeys. The notifier's wake (call_soon_threadsafe) stays, because the workers still commit from threads. - The second-factor gate and `write_guard`: run inside
run_syncunchanged. The listeners go onasync_engine.sync_engine. - To verify in PR 1 with a test: that the
write_guardContextVar set in_resolveis visible insidebefore_cursor_executeunder greenlet. Today it relies onrun_in_threadpoolcopying the context.
- What stays sync on purpose:
- Alembic and
migrate, the 20 workers and the probe, on a sync engine with a smaller pool of their own. - The LISTEN thread (psycopg-specific, one per process) and the health engine.
- Rarely called routes (admin, settings): FastAPI mixes
defandasync def, so they can stay.
- 318 routes are
An agent · Nov 9, 2026, 09:29 UTC
Plan, part 2 of 3: path, measurement, risks
Migration path (small PRs, each through the three vendors, each with a number):
- Async infrastructure, no route changes:
- the async engine and dependencies;
- async
retryingandtransaction; - test fixtures for the async engine;
write_guardonsync_engine, plus a ContextVar test;count_statementsonsync_engine;- the connection budget split between the async pool and the workers' sync pool, updating replicas.md's per-process budget.
- Authentication path:
_resolvewithoutrun_in_threadpool. This removes one thread hop from every route. - Hot route families, one PR each, in this order:
- members;
- project;
- tasks/board;
- inbox (requests);
- notifications and events (already
async def: their reads move from the thread pool torun_sync); - chats.
- The rest, by router file, grouped about 3 to 5 files per PR, or stop where the numbers say enough.
- Cleanup: remove the unused sync paths, and revisit serving.md 68487d41 ("the hub leaves anyio's default limiter").
Measurement (before and after every PR):
- Stats line:
threads_busyandthreads_waiting_maxshould fall;loop_late_avg_ms/loop_late_max_msmust not rise: that is the price of work on the loop;pool_checked_out.- Per route: Server-Timing (#1542) on prod, plus the
hub-loadworkflow locally before and after. - Statement counts: unchanged, from the existing count tests.
- A new guard: loop lag under load (a hub-load run) with a limit agreed in PR 1.
Risks:
- Blocking on the loop. Inside
run_syncthe body runs on the event loop thread. CPU work (view building, JSON) and blocking calls then delay every other request and every long-poll wake. Calls to audit before each family is converted: time.sleepinretrying;- the
threading.Locks in ktw, images and others; - the password hashing semaphore;
- the avatar
subprocess.run; - outbound HTTP (forge, GitHub app, mail).
Each one either stays in a sync route or moves into
anyio.to_thread. The loop-lag guard catches what the audit misses.- Race tests (
tests/concurrency.py) use two sync connections and threads. They test database semantics and stay valid for the helpers. For async routes they need an async twin. - MariaDB: aiomysql runs only in CI (11.4, after main pushes). Each PR needs a MariaDB run on its head (jour fixe proposal t5.s2), or the risk lands on main.
- The request-scoped tallies (#1542): if they hang on
before_cursor_executeplus a ContextVar, they sharewrite_guard's question; the same test covers both. - Pool exhaustion moves. Without the thread cap of 40, more requests can wait on the pool at once (30 s, then 500, tsk-p80cre8r9355). PR 1 sets the pool timeout and the refusal on purpose.
- Test time on the shared machine: the sync TestClient still drives async routes. aiosqlite adds a little per statement. Measured in PR 1, and the parallel limit of
-n 2stays.
An agent · Nov 9, 2026, 09:29 UTC
Plan, part 3 of 3: free-threaded Python, size, order
Free-threaded Python (3.13t/3.14t, no GIL). Not now. It would let the thread pool run CPU work (view building) in parallel within one process. We already get that from several processes per pod (
MAITY_WORKERS) and replicas, and asyncio does not need it. The binary dependencies (psycopg-binary, pydantic-core, uvloop, httptools, greenlet) must support the free-threaded build, and the hub is on 3.12 (Dockerfile, CI).Revisit when two things hold: the Docker base is on 3.14, and every binary wheel we pin ships a free-threaded build. Then measure throughput per process against the workers we save. Whether each wheel supports it today is not checked here; that is part of the revisit.
Size estimate:
| step | PRs | can run beside other cards? |
|---|---|---|
| 1 infrastructure | 1 | no: first, alone |
| 2 auth path | 1 | after 1 |
| 3 hot families | 6 | one at a time per route file; after tsk-6srccd2r1h62 PRs 2–4, which touch the same files |
| 4 the rest | about 8 to 10 (3 to 5 router files each) | yes, file groups that no open PR touches |
| 5 cleanup | 1 | last |That is about 17 to 19 PRs. Steps 1 and 2 carry the risk and the most review effort. Steps 3 and 4 are mostly mechanical once the pattern stands, and each can stop early if its number shows no gain.
Expected effect (to be measured, not promised): every route loses the authentication thread hop. Converted routes lose the second hop and stop competing for the 40 threads. With many held long-polls and slow reads, waiting for a thread disappears (the 2026-10-26 incident class). Per-statement round trips stay: tsk-6srccd2r1h62 keeps cutting those, independently.
Decision needed from the owner:
- The drivers: aiomysql and aiosqlite (recommended), or asyncmy, or SQLite sync-only.
- The go for PR 1 (infrastructure) once #1540 is through.
An agent · Nov 9, 2026, 09:32 UTC
Decision (Oliver, req-hd5k9fprpxp7, 09:32Z, option 1; passed on by lotse in 97091/97093): the plan as written in nte-e33v7sxewqbp, nte-xgjn8z41szkp and nte-qskk62fxwne5.
- Drivers: psycopg 3 async (PostgreSQL), aiomysql (MariaDB) and aiosqlite (SQLite), plus greenlet. New dependencies are pinned with hashes in the lock.
- PR 1 (infrastructure, no route change) starts after #1540.
Rules for the series:
- One PR at a time, each through the reviewers via the review lead.
- PostgreSQL locally before every review request; MariaDB on main right after each merge.
- Stats-line numbers before and after in each PR body:
threads_busy,threads_waiting_max,loop_late_*,pool_checked_out, plus route times.
PR order:
- Infrastructure.
- The async engine beside the sync one, and the dependencies.
- Async
retryingandevents.transaction. - Test fixtures;
write_guardand the statement counts onsync_engine, with a ContextVar test. - The pool budget split between async and the workers' sync pool, in replicas.md.
- The loop-lag guard and its limit.
- Auth path:
deps._resolvewithoutrun_in_threadpool. - Hot families, one PR each: members, project, tasks/board, inbox (requests), notifications plus events, chats. These come after tsk-6srccd2r1h62 PRs 2–4, which touch the same files.
- The rest, by router file, 3 to 5 files per PR (about 8 to 10 PRs), or stop where the numbers say enough.
- Cleanup: remove the unused sync paths; revisit serving.md 68487d41.
About 17 to 19 PRs in all. Each one names its blocking-call audit (nte-xgjn8z41szkp) and its numbers.
An agent · Nov 11, 2026, 05:04 UTC
Side PR #1632 (head 788d54adf6c5b32823624f687e8e9271d27c5720, base 448332b9b45fe78a6355bb4956eb36174c1e784a): the loop-lag guard from #1626 measures against an idle reference loop instead of a fixed 250 ms. On GitHub runners an idle loop alone was 247–314 ms late; main has been red in hub-load since #1626. Runner (2 runs, green): apps at most 18 ms over the reference, average ≤ 8 ms. RED: a 400 ms block (366 against 89) and random 30–120 ms slices (average 35 ms). The card report stays on #1631 (PR 2): the hub allows one open PR per report.
An agent · Nov 18, 2026, 15:21 UTC
Handover on release (maity-coder-claude-005#e7y8, successor of zwhq, 2026-11-18; lotse seq 162857).
- Plan: in nte-e33v7sxewqbp, nte-xgjn8z41szkp and nte-qskk62fxwne5. Oliver decided it in nte-nsmypqtk30tp: aiomysql, aiosqlite, greenlet.
- Done so far:
- PR 1, infrastructure: #1626.
- PR 2, auth path: #1631, merged.
- Side PR #1632, the loop-lag guard against an idle reference loop. Per #1631 round 5 it landed before #1631.
- Next: step 3, hot route families, one PR each. It comes after tsk-6srccd2r1h62 PRs 2–4.
- Already moved off the loop on main: #1845 now runs some sync transactions off the event loop via
run_in_threadpool, enforced byhub/tests/test_no_sync_db_on_loop.py. Read that guard before converting a family. - Not checked by me: the state of tsk-6srccd2r1h62.