Skip to content

Feat/312 async hooks - #363

Merged
anilmurty merged 7 commits into
Metabuilder-Labs:mainfrom
tarun73:feat/312-async-hooks
Jul 3, 2026
Merged

anilmurty merged 7 commits into
Metabuilder-Labs:mainfrom
tarun73:feat/312-async-hooks

Conversation

@tarun73

@tarun73 tarun73 commented Jul 1, 2026

Copy link
Copy Markdown
Contributor

Summary

This PR introduces an optional asynchronous path for post-ingest hooks (AlertEngine and SchemaValidator) to run off the critical span ingestion path, avoiding span-acknowledgment latency overhead. CostEngine remains
synchronous 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:

  • AlertsConfig: Added async_hooks boolean configuration flag (defaults to false).
  • IngestPipeline: Added background thread-safe queue (_hook_queue) and worker thread (TjHookWorker) to run Alert and Schema Validator hooks asynchronously.
  • Graceful Shutdown: Added flush and close hooks to OTel TjSpanExporter and FastAPI daemon serve lifespan to ensure no queued alerts are lost on exit.
  • Budget Cap Policy Tests: Injected a deterministic clock (now_fn) and mid-month baseline datetime to resolve boundary failures on the 1st of the month UTC.

Related issue

Closes #312

Checklist

  • Tests pass (pytest tests/unit/ tests/synthetic/ tests/agents/ tests/integration/)
  • Lint clean (ruff check tokenjam/)
  • Type check clean (mypy tokenjam/)
  • CLAUDE.md updated (if architecture changed)
  • Test spans use tests/factories.py (not raw NormalizedSpan)
  • Requested @anilmurty as reviewer (or @-mentioned him above)

Other Testing evidence:

  1. Ran couple of more testing to check real life examples and it works as expected.

@anilmurty please review.

Feedback appreciated

Tarun Reddy Yadama and others added 2 commits June 30, 2026 23:13
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]>
@tarun73
tarun73 requested a review from anilmurty as a code owner July 1, 2026 03:25
@anilmurty

Copy link
Copy Markdown
Contributor

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 _shutdown_event at the top of each iteration, so once close() sets the event it stops without draining the queue — and cmd_serve.py's lifespan calls close() without flush() first. Net: queued alerts are lost on shutdown, which is the opposite of the goal. Could you have the worker drain to empty on shutdown, and make every shutdown path flush() then close()? Also guard flush() so it can't hang if the worker already exited (queue.join() with no consumer blocks forever).

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. queue.Queue() has no maxsize; under a slow hook + high volume (the case this targets) memory grows unbounded. Please bound it with an explicit overflow policy, and log if anything is ever dropped.

4. CLAUDE.md. The ingest description still says hooks run synchronously — please document the async path + the async_hooks flag (the checklist box is ticked but the file isn't in the diff).

Minor: the hasattr(config, "alerts") guards are unnecessary now; and since the budget-cap fix adds a now_fn to production code, note it under "What's also in this PR" or split it.

Good direction — just want the shutdown-drain, write-safety, and the bound solid before this lands on the write path.

@anilmurty anilmurty left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

as noted above

anilmurty and others added 2 commits July 2, 2026 21:29
…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]>
@anilmurty

Copy link
Copy Markdown
Contributor

Pushed a follow-up commit (f0cf652) addressing the four review blockers, plus merged main (the branch was behind). Original authorship preserved via Co-Authored-By.

Blockers addressed

  1. Shutdown dropped queued alerts. The worker no longer bails at the top of the loop on _shutdown_event; on shutdown it drains the queue to empty (sentinel + only-exit-on-empty-once-shutdown). close() now flushes first, and the tj serve lifespan does flush() then close(). flush() is guarded so it returns immediately when no worker is alive rather than blocking forever on queue.join().
  2. Concurrent DB writes. In async mode the worker writes alerts while the ingest thread writes spans/cost; DuckDB's optimistic concurrency can abort one with a write-write conflict that 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 ([follow-up] Make the daemon DB layer safe for concurrent API requests #124) stays lock-free. Added tests/synthetic/test_async_hooks_concurrency.py running async hooks under concurrent (and multi-producer) ingest, asserting no lost writes / no conflict errors.
  3. Unbounded queue. Now bounded (HOOK_QUEUE_MAXSIZE = 10_000) with an explicit drop-oldest overflow policy; drops are counted and logged at WARNING — never silent.
  4. CLAUDE.md. Updated to document 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 removed the now-unnecessary hasattr(config, "alerts") guards. The budget-cap test's clock fix was absorbed by the main merge (proxy/engine.py already carries now_fn in production — no new production code for the test).

Verification

  • ruff check tokenjam/ clean; mypy tokenjam/core/ingest.py tokenjam/core/db.py clean.
  • pytest tests/unit/ tests/synthetic/ tests/integration/ — 1817 passed, incl. the new concurrency/shutdown/overflow tests.
  • Default-OFF confirmed by test_default_off_is_synchronous: a config without async_hooks runs hooks inline with no worker thread.

anilmurty and others added 2 commits July 2, 2026 21:56
…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
anilmurty previously approved these changes Jul 3, 2026

@anilmurty anilmurty left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 anilmurty left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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
anilmurty merged commit e751fd0 into Metabuilder-Labs:main Jul 3, 2026
4 checks passed
@tarun73

tarun73 commented Jul 6, 2026

Copy link
Copy Markdown
Contributor Author

@anilmurty thanks for completing this.

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.

[enhancement] Make heavy post-ingest hooks asynchronous so they don't block span-ack

2 participants