Repository navigation
Feat/312 async hooks - #363
Conversation
Support running AlertEngine and SchemaValidator asynchronously off the span ingestion critical path when alerts.async_hooks is enabled in config. This avoids adding latency to span acknowledgment. CostEngine remains synchronous for immediate budget checks. Co-Authored-By: Gemini 3.5 Flash (High) <[email protected]>
Seed a fixed mid-month datetime (2026-06-15) and pass a mocked now_fn to the policy engine evaluation in cycle-spend unit tests. This prevents test failures caused by relative times crossing the billing cycle/month boundary when run at the start of a month in UTC. Co-Authored-By: Gemini 3.5 Flash (High) <[email protected]>
|
Thanks @tarun73 — this is a well-scoped take on #312 (CostEngine stays sync, error-tolerance preserved, default-off), and I appreciate you flagging the timezone test fix explicitly. A few things to resolve before it goes into the ingest path, since it's threading on a hot path: 1. Shutdown can drop queued alerts. The worker loop exits on 2. Concurrent DB writes. In async mode the worker thread writes alerts while the main thread writes spans/cost. Our per-thread-cursor setup (#124) is validated for concurrent reads; concurrent writes from two threads can hit DuckDB write-write conflicts under load, and since hooks swallow errors that'd silently drop alerts. Can you add a test that runs async hooks under concurrent ingest and confirm no conflicts? 3. Bound the queue. 4. CLAUDE.md. The ingest description still says hooks run synchronously — please document the async path + the Minor: the Good direction — just want the shutdown-drain, write-safety, and the bound solid before this lands on the write path. |
…abuilder-Labs#312) Addresses the four review blockers on the async-hooks path so it can merge. The async path stays default-OFF: a config without `[alerts] async_hooks` runs every hook inline on the ingest thread, byte-for-byte the historical synchronous behavior (covered by test_default_off_is_synchronous). 1. Shutdown no longer drops queued alerts. The worker loop stopped checking `_shutdown_event` at the top of each iteration; on shutdown it now drains the queue to empty (via a sentinel + an only-exit-on-empty-once-shutdown check) before the thread exits. `close()` now flushes first, and the `tj serve` lifespan calls `flush()` then `close()`. `flush()` is guarded so it returns immediately when no worker is alive rather than blocking forever on `queue.join()` with no consumer. 2. Concurrent DB writes are now safe. In async mode the worker thread writes alerts while the ingest thread writes spans/cost; DuckDB's optimistic concurrency can abort one with a write-write conflict, which the error-swallowing hook path would silently drop. `DuckDBBackend` now serializes all mutating methods through a re-entrant `write_lock`; the per-thread-cursor read path (Metabuilder-Labs#124) stays lock-free. New synthetic tests run async hooks under concurrent (and multi-producer) ingest and assert no lost writes and no conflict errors. 3. The hook queue is now bounded (`HOOK_QUEUE_MAXSIZE`) with an explicit drop-oldest overflow policy. Dropped spans are counted and logged at WARNING — never silently — so operators can see hooks shedding load. 4. CLAUDE.md now documents the async path accurately (was still described as synchronous): the `async_hooks` flag, cost-stays-sync, the write lock, and the lossless-shutdown contract. Also removes the now-unnecessary `hasattr(config, "alerts")` guards in `_run_hooks` (config.alerts is always present with a defaulted `async_hooks`). What's also in this PR (from the original author, unchanged by this commit): the budget-cap policy test's deterministic-clock fix was absorbed by the merge of main (`proxy/engine.py` already carries `now_fn` in production; no new production code was added for the test). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Co-Authored-By: tarun73 <[email protected]>
|
Pushed a follow-up commit ( Blockers addressed
Also removed the now-unnecessary Verification
|
…te_lock The two async-hooks concurrency tests only produced disjoint-table INSERTs (worker → alerts; producers → spans/sessions with fresh session_ids), which DuckDB never conflicts on. A concurrency review found that stubbing the write_lock with contextlib.nullcontext() left both tests PASSING — so the guard was decorative. DuckDB's only write-write conflict is same-row UPDATE overlap (TransactionException: Conflict on update!), which those tests never created. This adds test_async_hooks_same_row_update_contention: N threads each call increment_session_cost() on the SAME session row in a tight loop (a read- modify-write on one row) while the async hook worker also writes alerts. It asserts the final total is exact-to-the-penny (no lost increment) and no conflict was raised. Verified load-bearing: swapping self._write_lock for nullcontext() makes it FAIL with "Conflict on update!"; restoring the RLock makes it PASS. The existing disjoint-INSERT tests are kept with a one-line comment noting they exercise disjoint tables, not conflict. Also fixes the wrapped-body indentation the review flagged in db.py (upsert_session, recompute_session_totals_from_spans, upsert_agent, upsert_baseline): the with self._write_lock: wrapper left the SQL/params at the old indent — re-indented properly (ruff clean). Adds a CLAUDE.md caveat that direct db.conn writes from routes (alerts.py acknowledge, set_session_label) sit outside the write_lock — safe today on disjoint rows, but a future hot-row direct write to a worker-touched table needs care. Drops a stray blank line in test_budget_cap_policy.py. Co-Authored-By: tarun73 <[email protected]> Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
anilmurty
left a comment
There was a problem hiding this comment.
Approving. The async-hooks implementation is correct on every dimension that matters for a core storage change: default path is a true no-op (no thread/queue created), no lock-ordering deadlock (write_lock released before the non-blocking enqueue), provably lossless shutdown, bounded drop-oldest queue with logging. The write_lock covers every DuckDBBackend writer and the new same-row-UPDATE contention test is verified load-bearing (fails with the lock swapped for a no-op). Thanks @tarun73 for the original work. Merging for a clean board.
test_bounded_queue_drops_oldest_and_logs raced the producer against the
background hook worker: it flooded the bounded queue and asserted at least
one span was dropped, but when the worker drained fast enough the queue
never overflowed and the assert failed ("assert 0 > 0"). It passed on the
PR's own CI but failed under the release batch's different timing.
The drop-oldest overflow logic is correct and separately proven; only the
test's ability to *force* an overflow was unreliable. This makes the
overflow deterministic instead of raced:
- The blocking hook now signals `entered` once the worker has pulled the
first span and parked inside evaluate(); the test waits on it before
flooding, so the worker provably cannot drain concurrently.
- The hook's `release.wait()` drops its 10s timeout. That timeout was the
actual flake source: over a multi-second flood it could expire, waking
the worker to drain another span and re-park, quietly relieving queue
pressure so the drop count came out short (observed 2 instead of 5).
With no timeout the worker holds span Metabuilder-Labs#1 for the whole flood.
- The flood now enqueues via the real overflow entry point
(`_enqueue_hook`) rather than full `process()`. The drop-oldest policy
under test lives entirely in `_enqueue_hook`; routing 10k+ spans through
a real DuckDB write each added tens of seconds of unrelated I/O.
The assertion is now exact (`== overflow_by`) instead of a lower bound,
and still asserts the real behavior: drops happen, are counted, and are
logged at WARNING. Verified non-flaky over 20 consecutive runs; full
suite (tests/unit, tests/synthetic, tests/integration) green.
Co-Authored-By: tarun73 <[email protected]>
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
anilmurty
left a comment
There was a problem hiding this comment.
Re-approving on the deflaked commit — the bounded-queue drop test is now deterministic (worker held via an 'entered' Event during the flood, drops asserted exactly). CI green, 1901 tests pass. Merging — clean board.
|
@anilmurty thanks for completing this. |
Summary
This PR introduces an optional asynchronous path for post-ingest hooks (
AlertEngineandSchemaValidator) to run off the critical span ingestion path, avoiding span-acknowledgment latency overhead.CostEngineremainssynchronous for immediate budget checks.
NOTE: Additionally, this PR fixes a timezone/billing-cycle boundary test failure in
test_budget_cap_policy.py. (this is not directly related but this test fails since i am running it at late 30th June and the UTC date is in the next month (July 1st). If you think this should be handled separately we can do that too)Changes:
async_hooksboolean configuration flag (defaults tofalse)._hook_queue) and worker thread (TjHookWorker) to run Alert and Schema Validator hooks asynchronously.TjSpanExporterand FastAPI daemon serve lifespan to ensure no queued alerts are lost on exit.now_fn) and mid-month baseline datetime to resolve boundary failures on the 1st of the month UTC.Related issue
Closes #312
Checklist
pytest tests/unit/ tests/synthetic/ tests/agents/ tests/integration/)ruff check tokenjam/)mypy tokenjam/)tests/factories.py(not rawNormalizedSpan)@anilmurtyas reviewer (or @-mentioned him above)Other Testing evidence:
@anilmurty please review.
Feedback appreciated