Repository navigation
feat(ts): port the Python hooks lifecycle to laya-ts - #308
Merged
Merged
Conversation
Agent and Router now take hooks / onPredictStart / onPredictEnd (installed or per-call) and fire onPredictStart, onPredictEnd, onRoute, onLoad, onEvict and onError with the same semantics as laya/hooks.py: start hooks may rewrite the state/questions or ctx.skip() a cached result, end hooks may rewrite results, onRoute may replace the routing decision, and hooksRaise=false warns instead of failing the request. HookRegistry adds addHook / removeHook / withHooks for scoped installs. Naming follows the rest of laya-ts (camelCase methods, withHooks instead of the Python context manager). Python's hooks_concurrent lock has no equivalent because dispatch is synchronous on one thread.
Owner
|
Thank you, hooks were the last Python subsystem with no TypeScript counterpart. All 59 tests pass, and answers are identical to before with no hooks set. Merging. |
NandhaKishorM
pushed a commit
that referenced
this pull request
Sep 24, 2026
…276) (#321) #276 landed after the TS hooks port (#308), leaving laya-ts a revision behind: no BaseHook, no process-wide defaults, no shared compose point. Port all three; Agent/Router predict and the router lifecycle events now resolve hooks via composeHooks (defaults, then installed, then per-call), read at call time like Python. No behavior change with no defaults set. Co-authored-by: NandhaKishorM <nandakishor@convaiinnovations.com>
baninaveen
pushed a commit
to baninaveen/laya
that referenced
this pull request
Sep 24, 2026
Agent and Router now take hooks / onPredictStart / onPredictEnd (installed or per-call) and fire onPredictStart, onPredictEnd, onRoute, onLoad, onEvict and onError with the same semantics as laya/hooks.py: start hooks may rewrite the state/questions or ctx.skip() a cached result, end hooks may rewrite results, onRoute may replace the routing decision, and hooksRaise=false warns instead of failing the request. HookRegistry adds addHook / removeHook / withHooks for scoped installs. Naming follows the rest of laya-ts (camelCase methods, withHooks instead of the Python context manager). Python's hooks_concurrent lock has no equivalent because dispatch is synchronous on one thread. Co-authored-by: NandhaKishorM <nandakishor@convaiinnovations.com>
baninaveen
pushed a commit
to baninaveen/laya
that referenced
this pull request
Sep 24, 2026
…andhaKishorM#276) (NandhaKishorM#321) NandhaKishorM#276 landed after the TS hooks port (NandhaKishorM#308), leaving laya-ts a revision behind: no BaseHook, no process-wide defaults, no shared compose point. Port all three; Agent/Router predict and the router lifecycle events now resolve hooks via composeHooks (defaults, then installed, then per-call), read at call time like Python. No behavior change with no defaults set. Co-authored-by: NandhaKishorM <nandakishor@convaiinnovations.com>
PerryLink
added a commit
to PerryLink/laya
that referenced
this pull request
Sep 25, 2026
The context manager restored the list by removing every entry matching a hook it had added, by identity. A hook object that an application had already installed therefore matched too, and was removed along with the block's own copy: ``` installed one hook before the block: 1 inside the block : 2 hook(s) after the block : 0 hook(s) <- the caller's hook is gone dispatches on the next call : 0 ``` `docs/hooks/api.md` and `docs/hooks/patterns.md` both say the block *"restores the previous list on exit, even if the block raises"*. An application that installs one audit or metrics hook at startup and later wraps a request in `hooks_installed` for a temporary one loses the audit hook for the rest of the process, silently. ## The snapshot fix was wrong in two other ways The first version of this fix saved `self.hooks` on entry and assigned it back on exit. The review caught two cases that breaks, and both are real: - **Two overlapping blocks.** The inner block installs its hook. The inner block exits and reinstates the snapshot taken *before* it, which is also before the outer block's hook was added — so the outer hook disappears while its `with` is still open. Worse, at the outer exit the outer snapshot is reinstated, so a hook that a *later* caller installed inside the window is removed for good. - **A hook added with `add_hook` inside the block** is not in the snapshot, so it is discarded on exit even though the block did not put it there. ## What it does now Removes **one occurrence per hook the block added**, the most recent match by identity, under the registry lock. `_extend_hooks` appends, so a hook that was already installed sits earlier in the list than the block's copy, which makes "most recent match" the block's own. Everything the block did not add is left alone. Deliberate choices tested: - **One occurrence per hook, not one per list entry.** A hook named twice in one `hooks_installed(...)` call is added twice and removed twice, so the block still leaves nothing behind — while a hook the caller installed once keeps its own copy. - **The lock is held for the read-modify-write.** The whole removal happens inside `_hooks_mutex_for_registry`, so a concurrent `add_hook` cannot be interleaved between the copy and the assignment. - **`_remove_hooks` is left alone.** Its predicate semantics are right for a caller who wants "remove every copy"; the bug was using it to implement a restore. - **The tests cover the arrangements the old ones could not.** The existing check installed a *temporary* hook that was registered nowhere else, which passes under any of the three implementations. The new ones install the hook first, nest two blocks, and add a hook inside a block — the only arrangements that distinguish them. ``` # with the snapshot version restored, the new tests fail: IndexError: list index out of range (f.hooks[0] after the block -- the hook added inside was discarded) $ python tests/test_hooks.py 176 passed, 0 failed (141 before) $ python tests/test_hooks_api.py all hook API tests passed $ python -m pytest tests/test_serve.py tests/test_system_one_lang.py -q 31 passed $ python -m ruff check laya/ --select=E9,F63,F7,F82,F401,F811 --line-length=120 All checks passed! $ python -m compileall -q laya/ tests/ ``` Verified against all four arrangements directly, with a weight-free fake agent: a hook installed before the block survives and still fires once; a hook added inside survives; an inner block's exit leaves the outer hook installed; and a hook named twice in one block leaves nothing behind. Known limitation: this is the Python side. `laya-ts/src/hooks.ts` carries the same remove-by-identity logic from PR NandhaKishorM#308, so the original defect is present in the port until that is addressed — the same one-occurrence-per-hook change applies there, in a separate PR so this diff stays one logical change.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Ports the Python
laya/hooks.pylifecycle to laya-ts — the last subsystem in the Python package with no TS counterpart. Hooks are opt-in and observe or shape every decision without forking:PredictContextwith the same fields (states,questions,runId,results,decision,model,usage,elapsedMs,error) andctx.skip(results)to short-circuit inference with a cached result.onPredictStart,onPredictEnd,onRoute,onLoad,onEvict,onError.AgentandRouteraccepthooks/onPredictStart/onPredictEndat construction and per call;hooksRaise: falsewarns and continues for telemetry that must not fail a request.HookRegistrywithaddHook/removeHook/withHooks(...)for scoped installs.hooksis a TypeError (which event would it bind to?), the same callable as both start and end is a TypeError, and a failingonErrorhook never masks the failure that triggered it.onLoadfires on first load only,onEvictfor LRU victims; cache-hit results still get aroutingkey, without overwriting one the cached payload already has.Deliberate naming differences from Python
onPredictStart, noton_predict_start), matching the rest of laya-ts (systemOne,langGuess).withHooks(hooks, fn)instead of thehooks_installedcontext manager — works for sync and async callbacks and always removes the hooks afterward.hooks_concurrent/ dispatch lock: TS hooks run synchronously on one thread, so there is nothing to serialise. Happy to add a note to that effect in docs/hooks if useful.Validation
npx vitest run— 59/59 (17 new tests intests/hooks.test.tscovering skip, state/question rewrite, result rewrite, per-call ordering, error paths, route replacement, load/evict lifecycle, and registry scoping)npx tsc --noEmitcleannpm run buildcleantests/test_hooks.pystill passes