Non-autoregressive System 1 decision engine. Typed choice, score and yes/no decisions over any text in a single forward pass, in 100+ languages, with a router that picks the right checkpoint per request.
Python calibrationclassificationdecision-modelhuggingfacejevmodernbertmultilingualnlppythonpytorchroutingtyped-decisionszero-shot
feat(java): hooks, and the one scan that must not run them
Adeshina Lasisicca997007192
diff --git a/.github/workflows/java.yml b/.github/workflows/java.ymlindex b8a8ac0c..4018d945 100644--- a/.github/workflows/java.yml+++ b/.github/workflows/java.yml@@ -156,11 +156,18 @@ jobs:- name: Tests that need no modelworking-directory: laya-javarun: ./gradlew --no-daemon test+ # Measured locally: 812 registered, 798 RUN -- the floor counts what ran, so the 14+ # checkpoint-backed cases this lane aborts are not in it. The margin is 4, the same shape+ # as the 685/680 it replaces, and for the reason the `tokenizer` parity cell gives: a+ # floor below the total minus the SMALLEST class does not bind that class. `AgentHooksTest`+ # is 8 tests, so at the old 680 the whole of it could be deleted with this step still+ # green. Verified both ways: with `AgentHooksTest` dropped 790 run and this exits 1; with+ # `HooksTest` dropped 693 run and it exits 1.- name: Model-free suite was not vacuousif: ${{ !cancelled() }}run: >python laya-java/scripts/check_test_results.py- laya-java/laya-java/build/test-results/test --min-tests 680 --allow-aborted+ laya-java/laya-java/build/test-results/test --min-tests 794 --allow-aborted# The samples are single-file source programs, deliberately NOT a Gradle module: a# `samples` subproject would inherit the root build's MavenPublication and@@ -319,7 +326,7 @@ jobs:if: ${{ !cancelled() }}run: >python laya-java/scripts/check_test_results.py- laya-java/laya-java/build/test-results/test --min-tests 680 --allow-aborted+ laya-java/laya-java/build/test-results/test --min-tests 794 --allow-aborted--require-passed TestJvmVersionTest- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2if: ${{ failure() }}diff --git a/laya-java/CHANGELOG.md b/laya-java/CHANGELOG.mdindex ef9dba65..54a360ff 100644--- a/laya-java/CHANGELOG.md+++ b/laya-java/CHANGELOG.md@@ -44,6 +44,25 @@ see [Installing](README.md#installing).span said it did. `Budget` carries the reference's `RuntimeWarning` text as data as well aslogging it, since every clamp here is a decision the caller cannot otherwise see — their windowshrinks, their stride shrinks with it, and the forward-pass count can triple.+- `hooks`: the opt-in lifecycle, ported from `laya.hooks`. `Hook` is one interface with six+ default no-op methods — the reference's structural `Hook` protocol and its concrete `BaseHook`+ are the same thing once an interface can carry defaults. `PredictContext` is the per-call,+ mutable state every hook of one call shares: a start hook may rewrite the states, the+ questions and the token budget, or answer the call outright with `ctx.skip(...)`, in which+ case the model never runs; an end hook may replace the results and sees the call's totalled+ `usage` and `elapsedMs`. `HookRegistry` is the per-agent list — `agent.hooks()` — editable+ while the agent is alive and snapshotted per call, with `hooksInstalled` scoping hooks to a+ block. `HookCall` carries per-call hooks and policy overrides. `Hooks` composes the chain —+ **process-wide defaults, then installed, then per-call**, which is a contract and not an+ implementation detail — dispatches it, bounds each hook with an optional deadline, serialises+ it behind a lock when asked, and totals usage. `Agent.predict` and `Agent.predictBatch` run+ it; `Agent.predictLong` deliberately does not, for the reason under *Known limitations*.+ Everything above is recorded from the reference in `fixtures/hooks.json`, including what a+ start hook sees, what `skip` does to inference, and what a throwing hook does under each+ policy.+- `Agent.using(tokenizer, config, session, modelName)` and `Agent.modelName()`: the checkpoint+ name a hook reads off `PredictContext.model()`. `Agent.open` takes it from the model+ directory's own name, since `rl_agent_config.json` does not carry one.- `Tokenizer.decode(int[])` and `decode(int[], boolean skipSpecialTokens)`: ids back to text,matching the `tokenizers` crate's `ByteLevel`, `Replace`, `ByteFallback`, `Fuse`, `Strip` and`Sequence` decoders. Byte-exact against the reference over both shipped checkpoints, including@@ -87,8 +106,25 @@ see [Installing](README.md#installing).### Known limitations-- Not implemented: hooks, `predictLong`, structured `decide`, the `laya-java-client` HTTP module,- Android.+- Not implemented: structured `decide`, the `laya-java-client` HTTP module, Android.+- `AsyncHook` is not ported, and will not be. It exists in the reference to finish a coroutine+ from synchronous code; a JVM method call is already synchronous, so a hook that wants+ asynchronous work composes it and blocks on it in one line. Porting the wrapper would mean+ choosing a future type for every caller and owning a thread pool to await on.+- Hooks run on `predict` and `predictBatch` only. `Router` does not dispatch them — so+ `PredictContext` has no `router`/`decision` pair, rather than two fields that are always null+ — and `predictLong` deliberately does not either. The reference's `predict_long` survives+ hooks only by way of a start probe, a post-chain budget check and two separate "a hook+ answered the document" paths, none of which this port has; without them a hook that adds one+ option silently re-truncates every window, and a hook that answers the call leaves `windows`+ claiming a scan that never ran. Running hooks there without that machinery would be worse+ than not running them.+- `Hooks.withoutDefaultHooks` is a `ThreadLocal` where the reference's `_SKIP_DEFAULTS` is a+ `contextvars.ContextVar`. A `ContextVar` is copied into an asyncio task; a `ThreadLocal` is+ not inherited by a thread started inside the scope. Nothing here dispatches hooks off the+ calling thread, so there is nowhere for it to bite today.+- A timed-out hook keeps running, on both runtimes: neither Java nor Python can interrupt a+ thread that will not cooperate, so the deadline bounds the request and not the process.- `typed-decisions` is routable — `Router` knows it and resolves its aliases — but has no recordedend-to-end fixtures. The routing decision is tested; a forward pass against that checkpoint isnot.@@ -125,5 +161,10 @@ Recorded here because each one was a defect first and a lesson second.does not merely misreport a score, it changes which labels survive the cut.- `%.0f` and `round()` are half-to-**even** in CPython; `String.format` and `Math.round` arehalf-up.+- A Java `finally` that throws **replaces** the pending exception, where Python's re-raises the+ original. The reference's hook wrapper goes out of its way to stop a failing end hook masking+ the failure it was observing, so the end-hook stage here is written out longhand rather than+ put in a `finally`, and the hook's failure is attached with `addSuppressed` where the+ reference chains it onto `__context__`.[0.1.0]: https://github.com/NandhaKishorM/layadiff --git a/laya-java/README.md b/laya-java/README.mdindex 3337f767..1495b71e 100644--- a/laya-java/README.md+++ b/laya-java/README.md@@ -13,12 +13,14 @@ four questions about a document cost one batched encode rather than four round tImplemented: tokenizer, sequence builder, config, ONNX inference (fused or split graph), answerdecoding, `predict`, `predictBatch`, usage and truncation reporting, script and language detection(`lang.LanguageDetection`), the question presets (`Presets`), the checkpoint `Router` with its-load-and-evict lifecycle, the embedding `Shortlist` with its LRU cache, and the email cleaner-and state builder (`LayaEmail`).+load-and-evict lifecycle, the embedding `Shortlist` with its LRU cache, the email cleaner and+state builder (`LayaEmail`), the long-state scan (`predictLong`), the abstention gate+(`ConfidenceGate`), and the prediction hooks (`hooks`).-Not implemented yet: hooks, `predictLong`, structured `decide`, the-`laya-java-client` HTTP module, Android. **Not published to Maven Central** — see-[Installing](#installing).+Not implemented yet: structured `decide`, the `laya-java-client` HTTP module, Android. Hooks run+on `predict` and `predictBatch`; `Router` and `predictLong` do not dispatch them, and there is no+`AsyncHook` — see [Watching and shaping a call](#watching-and-shaping-a-call). **Not published to+Maven Central** — see [Installing](#installing).## Where to go next@@ -351,6 +353,60 @@ every window of a long document tokenize differently from the reference, so theholds them, or to drive the batching and usage accounting through a stub`infer.InferenceSession` instead of a 1.2 GB graph.+## Watching and shaping a call++```java+agent.hooks().addHook(new Hook() {+ @Override public void onPredictEnd(PredictContext ctx) {+ metrics.record(ctx.model(), ctx.usage().inputTokens(), ctx.elapsedMs());+ }+});++// Per call: answer from a cache without the model running at all.+agent.predictBatch(states, questions, null, 0, false,+ HookCall.of(Hooks.onPredictStart(ctx -> cache.lookup(ctx.states())+ .ifPresent(ctx::skip))));+```++A hook is the one place your code runs **inside** a prediction. Implement any of the six methods+on `Hook` — the rest default to doing nothing — and install it on the agent, on a single call, or+process-wide with `Hooks.setDefaultHooks`.++`PredictContext` is the call, and it is mutable on purpose. A start hook may rewrite+`ctx.states(...)` or `ctx.questions(...)`, move the token budget with `ctx.maxLen(...)` /+`ctx.headMaxLen(...)`, or answer outright with `ctx.skip(results)` — which skips inference while+still running the end hooks. An end hook may replace `ctx.results(...)`, and sees `ctx.usage()`+totalled over the call plus `ctx.elapsedMs()`. Every hook of one call gets the **same** context,+so `ctx.runId()` pairs a start with its end without state of your own.++The order is a contract: **process-wide defaults, then installed, then per-call**, and within a+per-call `HookCall`, hook objects before the `onStart`/`onEnd` callbacks. A tracer installed to+watch what a per-call hook did only sees it if it runs after it.++`agent.hooks()` also carries the policy. `raiseErrors(false)` reports a throwing hook and carries+on, which is what a telemetry hook needs — it must not be able to fail a request.+`concurrent(false)` serialises hooks that are not re-entrant. `timeout(Duration)` bounds each hook+call; an overrunning hook fails the request, though it **keeps running** in the background, since+neither runtime can interrupt a thread that will not cooperate. A `HookCall` can override+`raiseErrors` and `timeout` for one call without touching the others.++Scope hooks to a block with `try (var scope = agent.hooks().hooksInstalled(tracer)) { ... }`. It+removes one copy of each hook it added — not every copy by identity, which would take one the+application had installed before the block, and not a snapshot, which would undo an overlapping+block and discard anything added inside this one.++`predictLong` runs **no** hooks — not per-call, not installed, not process-wide. A scan is sized+before any hook could run, and the reference only lets hooks into `predict_long` by way of a start+probe, a post-chain budget check and two separate "a hook answered the document" paths. None of+those are ported, and without them a hook that adds one option silently re-truncates every window.+Window the state yourself and hand the windows to `predictBatch` if you need hooks over a long+document.++There is no `AsyncHook`. It exists in the reference to finish a coroutine from synchronous code,+and a JVM method call is already synchronous: a hook that wants asynchronous work composes it and+blocks on it — `ship(ctx.results()).toCompletableFuture().join()` — bounded however your runtime+wants, or by `timeout(Duration)`.+## Threads`Agent.open(model, graph)` leaves the thread count to ONNX Runtime, which is what the Pythondiff --git a/laya-java/fixtures/hooks.json b/laya-java/fixtures/hooks.jsonnew file mode 100644index 00000000..a874b341--- /dev/null+++ b/laya-java/fixtures/hooks.json@@ -0,0 +1,3064 @@+{+ "events": [+ "on_predict_start",+ "on_predict_end",+ "on_route",+ "on_load",+ "on_evict",+ "on_error"+ ],+ "composition": [+ {+ "case": "nothing-installed",+ "defaults": [],+ "installed": [],+ "hooks": [],+ "on_predict_start": [],+ "on_predict_end": [],+ "skip_defaults": false,+ "order": []+ },+ {+ "case": "defaults-only",+ "defaults": [+ "d1",+ "d2"+ ],+ "installed": [],+ "hooks": [],+ "on_predict_start": [],+ "on_predict_end": [],+ "skip_defaults": false,+ "order": [+ "d1",+ "d2"+ ]+ },+ {+ "case": "installed-only",+ "defaults": [],+ "installed": [+ "i1",+ "i2"+ ],+ "hooks": [],+ "on_predict_start": [],+ "on_predict_end": [],+ "skip_defaults": false,+ "order": [+ "i1",+ "i2"+ ]+ },+ {+ "case": "per-call-only",+ "defaults": [],+ "installed": [],+ "hooks": [+ "p1",+ "p2"+ ],+ "on_predict_start": [],+ "on_predict_end": [],+ "skip_defaults": false,+ "order": [+ "p1",+ "p2"+ ]+ },+ {+ "case": "defaults-then-installed-then-per-call",+ "defaults": [+ "d1"+ ],+ "installed": [+ "i1"+ ],+ "hooks": [+ "p1"+ ],+ "on_predict_start": [],+ "on_predict_end": [],+ "skip_defaults": false,+ "order": [+ "d1",+ "i1",+ "p1"+ ]+ },+ {+ "case": "callables-come-after-hook-objects",+ "defaults": [+ "d1"+ ],+ "installed": [+ "i1"+ ],+ "hooks": [+ "p1"+ ],+ "on_predict_start": [+ "s1"+ ],+ "on_predict_end": [+ "e1"+ ],+ "skip_defaults": false,+ "order": [+ "d1",+ "i1",+ "p1",+ "start:s1",+ "end:e1"+ ]+ },+ {+ "case": "several-start-callables-keep-their-order",+ "defaults": [],+ "installed": [],+ "hooks": [],+ "on_predict_start": [+ "s1",+ "s2",+ "s3"+ ],+ "on_predict_end": [],+ "skip_defaults": false,+ "order": [+ "start:s1",+ "start:s2",+ "start:s3"+ ]+ },+ {+ "case": "start-callables-before-end-callables",+ "defaults": [],+ "installed": [],+ "hooks": [],+ "on_predict_start": [+ "s1"+ ],+ "on_predict_end": [+ "e1"+ ],+ "skip_defaults": false,+ "order": [+ "start:s1",+ "end:e1"+ ]+ },+ {+ "case": "skip-defaults-drops-only-the-defaults",+ "defaults": [+ "d1",+ "d2"+ ],+ "installed": [+ "i1"+ ],+ "hooks": [+ "p1"+ ],+ "on_predict_start": [],+ "on_predict_end": [],+ "skip_defaults": true,+ "order": [+ "i1",+ "p1"+ ]+ },+ {+ "case": "skip-defaults-with-nothing-else",+ "defaults": [+ "d1"+ ],+ "installed": [],+ "hooks": [],+ "on_predict_start": [],+ "on_predict_end": [],+ "skip_defaults": true,+ "order": []+ }+ ],+ "default_hooks_api": {+ "after_set": [+ "probe"+ ],+ "mutating_the_returned_list_changes_nothing": [+ "probe"+ ],+ "after_add": [+ "probe",+ "added"+ ],+ "after_clear": []+ },+ "normalise_refusals": [+ {+ "input": "a class rather than an instance",+ "error": "hooks entries must be instances, not classes; got _NotAHook. Instantiate it first."+ },+ {+ "input": "an object implementing no event",+ "error": "hooks entries must implement at least one of on_predict_start, on_predict_end, on_route, on_load, on_evict, on_error; got _NotAHook. Pass a plain callable as on_predict_start=/on_predict_end= instead."+ },+ {+ "input": "an event attribute that is not callable",+ "error": "hooks entry _NotCallable.on_predict_start must be callable, got str"+ },+ {+ "input": "a plain object",+ "error": "hooks entries must implement at least one of on_predict_start, on_predict_end, on_route, on_load, on_evict, on_error; got object. Pass a plain callable as on_predict_start=/on_predict_end= instead."+ },+ {+ "input": "a non-callable on_predict_start",+ "error": "on_predict_start must be callable, got int"+ },+ {+ "input": "a non-callable on_predict_end",+ "error": "on_predict_end must be callable, got str"+ }+ ],+ "as_sequence": [+ {+ "input": "none",+ "length": 0+ },+ {+ "input": "one",+ "length": 1+ },+ {+ "input": "list-of-two",+ "length": 2+ },+ {+ "input": "tuple-of-three",+ "length": 3+ },+ {+ "input": "empty-list",+ "length": 0+ }+ ],+ "dispatch": [+ {+ "case": "every-hook-in-order",+ "event": "on_predict_start",+ "raise_errors": true,+ "chain": [+ {+ "name": "a",+ "events": [+ "on_predict_start"+ ],+ "behaviour": null+ },+ {+ "name": "b",+ "events": [+ "on_predict_start"+ ],+ "behaviour": null+ },+ {+ "name": "c",+ "events": [+ "on_predict_start"+ ],+ "behaviour": null+ }+ ],+ "calls": [+ "a.on_predict_start",+ "b.on_predict_start",+ "c.on_predict_start"+ ],+ "raised": null,+ "warnings": [],+ "results": null+ },+ {+ "case": "a-hook-that-does-not-implement-the-event-is-skipped",+ "event": "on_predict_start",+ "raise_errors": true,+ "chain": [+ {+ "name": "a",+ "events": [+ "on_predict_start"+ ],+ "behaviour": null+ },+ {+ "name": "b",+ "events": [+ "on_predict_end"+ ],+ "behaviour": null+ },+ {+ "name": "c",+ "events": [+ "on_predict_start"+ ],+ "behaviour": null+ }+ ],+ "calls": [+ "a.on_predict_start",+ "c.on_predict_start"+ ],+ "raised": null,+ "warnings": [],+ "results": null+ },+ {+ "case": "no-hook-implements-the-event",+ "event": "on_route",+ "raise_errors": true,+ "chain": [+ {+ "name": "a",+ "events": [+ "on_predict_end"+ ],+ "behaviour": null+ }+ ],+ "calls": [],+ "raised": null,+ "warnings": [],+ "results": null+ },+ {+ "case": "raising-stops-the-chain",+ "event": "on_predict_start",+ "raise_errors": true,+ "chain": [+ {+ "name": "a",+ "events": [+ "on_predict_start"+ ],+ "behaviour": null+ },+ {+ "name": "b",+ "events": [+ "on_predict_start"+ ],+ "behaviour": "raise"+ },+ {+ "name": "c",+ "events": [+ "on_predict_start"+ ],+ "behaviour": null+ }+ ],+ "calls": [+ "a.on_predict_start",+ "b.on_predict_start"+ ],+ "raised": {+ "type": "ValueError",+ "message": "boom from b"+ },+ "warnings": [],+ "results": null+ },+ {+ "case": "raise-errors-false-warns-and-continues",+ "event": "on_predict_start",+ "raise_errors": false,+ "chain": [+ {+ "name": "a",+ "events": [+ "on_predict_start"+ ],+ "behaviour": null+ },+ {+ "name": "b",+ "events": [+ "on_predict_start"+ ],+ "behaviour": "raise"+ },+ {+ "name": "c",+ "events": [+ "on_predict_start"+ ],+ "behaviour": null+ }+ ],+ "calls": [+ "a.on_predict_start",+ "b.on_predict_start",+ "c.on_predict_start"+ ],+ "raised": null,+ "warnings": [+ "laya: hook StubHook.on_predict_start failed: boom from b"+ ],+ "results": null+ },+ {+ "case": "raise-errors-false-with-every-hook-failing",+ "event": "on_predict_start",+ "raise_errors": false,+ "chain": [+ {+ "name": "a",+ "events": [+ "on_predict_start"+ ],+ "behaviour": "raise"+ },+ {+ "name": "b",+ "events": [+ "on_predict_start"+ ],+ "behaviour": "raise"+ }+ ],+ "calls": [+ "a.on_predict_start",+ "b.on_predict_start"+ ],+ "raised": null,+ "warnings": [+ "laya: hook StubHook.on_predict_start failed: boom from a",+ "laya: hook StubHook.on_predict_start failed: boom from b"+ ],+ "results": null+ },+ {+ "case": "skip-does-not-stop-the-chain",+ "event": "on_predict_start",+ "raise_errors": true,+ "chain": [+ {+ "name": "a",+ "events": [+ "on_predict_start"+ ],+ "behaviour": "skip:1"+ },+ {+ "name": "b",+ "events": [+ "on_predict_start"+ ],+ "behaviour": null+ }+ ],+ "calls": [+ "a.on_predict_start",+ "b.on_predict_start"+ ],+ "raised": null,+ "warnings": [],+ "results": 1+ },+ {+ "case": "the-other-four-events-dispatch-the-same-way",+ "event": "on_route",+ "raise_errors": true,+ "chain": [+ {+ "name": "a",+ "events": [+ "on_route",+ "on_load",+ "on_evict",+ "on_error"+ ],+ "behaviour": null+ },+ {+ "name": "b",+ "events": [+ "on_route"+ ],+ "behaviour": null+ }+ ],+ "calls": [+ "a.on_route",+ "b.on_route"+ ],+ "raised": null,+ "warnings": [],+ "results": null+ },+ {+ "case": "on-error-dispatches-over-the-same-chain",+ "event": "on_error",+ "raise_errors": false,+ "chain": [+ {+ "name": "a",+ "events": [+ "on_error"+ ],+ "behaviour": null+ },+ {+ "name": "b",+ "events": [+ "on_error"+ ],+ "behaviour": "raise"+ }+ ],+ "calls": [+ "a.on_error",+ "b.on_error"+ ],+ "raised": null,+ "warnings": [+ "laya: hook StubHook.on_error failed: boom from b"+ ],+ "results": null+ },+ {+ "case": "on-predict-end-dispatches-over-the-same-chain",+ "event": "on_predict_end",+ "raise_errors": true,+ "chain": [+ {+ "name": "a",+ "events": [+ "on_predict_end"+ ],+ "behaviour": null+ },+ {+ "name": "b",+ "events": [+ "on_predict_end"+ ],+ "behaviour": null+ }+ ],+ "calls": [+ "a.on_predict_end",+ "b.on_predict_end"+ ],+ "raised": null,+ "warnings": [],+ "results": null+ }+ ],+ "skip": [+ {+ "case": "one-result-per-state",+ "states": 3,+ "results": 3,+ "accepted": true,+ "error": null,+ "assigned": [+ 10,+ 11,+ 12+ ]+ },+ {+ "case": "one-result-for-the-whole-call",+ "states": 3,+ "results": 1,+ "accepted": true,+ "error": null,+ "assigned": [+ 10+ ]+ },+ {+ "case": "one-state-one-result",+ "states": 1,+ "results": 1,+ "accepted": true,+ "error": null,+ "assigned": [+ 10+ ]+ },+ {+ "case": "two-results-for-one-state",+ "states": 1,+ "results": 2,+ "accepted": false,+ "error": "ctx.skip() takes one result for the whole call or one per state in ctx.states (1); got 2",+ "assigned": null+ },+ {+ "case": "too-few-results",+ "states": 3,+ "results": 2,+ "accepted": false,+ "error": "ctx.skip() takes one result for the whole call or one per state in ctx.states (3); got 2",+ "assigned": null+ },+ {+ "case": "no-results-at-all",+ "states": 3,+ "results": 0,+ "accepted": false,+ "error": "ctx.skip() takes one result for the whole call or one per state in ctx.states (3); got 0",+ "assigned": null+ },+ {+ "case": "too-many-results",+ "states": 2,+ "results": 5,+ "accepted": false,+ "error": "ctx.skip() takes one result for the whole call or one per state in ctx.states (2); got 5",+ "assigned": null+ },+ {+ "case": "no-states-no-results",+ "states": 0,+ "results": 0,+ "accepted": true,+ "error": null,+ "assigned": []+ },+ {+ "case": "no-states-one-result",+ "states": 0,+ "results": 1,+ "accepted": true,+ "error": null,+ "assigned": [+ 10+ ]+ },+ {+ "case": "no-states-two-results",+ "states": 0,+ "results": 2,+ "accepted": false,+ "error": "ctx.skip() takes one result for the whole call or one per state in ctx.states (0); got 2",+ "assigned": null+ }+ ],+ "usage": [+ {+ "case": "one-result",+ "results": [+ {+ "input_tokens": 11,+ "output_tokens": 0+ }+ ],+ "total": {+ "input_tokens": 11,+ "output_tokens": 0+ }+ },+ {+ "case": "several-results-sum",+ "results": [+ {+ "input_tokens": 11,+ "output_tokens": 1+ },+ {+ "input_tokens": 22,+ "output_tokens": 2+ },+ {+ "input_tokens": 33,+ "output_tokens": 3+ }+ ],+ "total": {+ "input_tokens": 66,+ "output_tokens": 6+ }+ },+ {+ "case": "no-results-at-all",+ "results": [],+ "total": {+ "input_tokens": 0,+ "output_tokens": 0+ }+ },+ {+ "case": "zeroes",+ "results": [+ {+ "input_tokens": 0,+ "output_tokens": 0+ }+ ],+ "total": {+ "input_tokens": 0,+ "output_tokens": 0+ }+ },+ {+ "case": "a-missing-usage-block",+ "results": [+ {}+ ],+ "total": {+ "input_tokens": 0,+ "output_tokens": 0+ }+ },+ {+ "case": "a-null-usage-block",+ "results": [+ {+ "__usage_is_none__": true+ }+ ],+ "total": {+ "input_tokens": 0,+ "output_tokens": 0+ }+ },+ {+ "case": "a-missing-key",+ "results": [+ {+ "input_tokens": 7+ }+ ],+ "total": {+ "input_tokens": 7,+ "output_tokens": 0+ }+ },+ {+ "case": "a-null-value",+ "results": [+ {+ "input_tokens": 7,+ "output_tokens": null+ }+ ],+ "total": {+ "input_tokens": 7,+ "output_tokens": 0+ }+ },+ {+ "case": "a-float-is-truncated",+ "results": [+ {+ "input_tokens": 7.9,+ "output_tokens": 0+ }+ ],+ "total": {+ "input_tokens": 7,+ "output_tokens": 0+ }+ }+ ],+ "timeouts": [+ {+ "input": "None",+ "accepted": true,+ "value": null,+ "error": null+ },+ {+ "input": "1",+ "accepted": true,+ "value": 1.0,+ "error": null+ },+ {+ "input": "1.5",+ "accepted": true,+ "value": 1.5,+ "error": null+ },+ {+ "input": "0.05",+ "accepted": true,+ "value": 0.05,+ "error": null+ },+ {+ "input": "'0.5'",+ "accepted": true,+ "value": 0.5,+ "error": null+ },+ {+ "input": "0",+ "accepted": false,+ "value": null,+ "error": "hooks_timeout must be a positive finite number or None; got 0"+ },+ {+ "input": "0.0",+ "accepted": false,+ "value": null,+ "error": "hooks_timeout must be a positive finite number or None; got 0.0"+ },+ {+ "input": "-1",+ "accepted": false,+ "value": null,+ "error": "hooks_timeout must be a positive finite number or None; got -1"+ },+ {+ "input": "-0.5",+ "accepted": false,+ "value": null,+ "error": "hooks_timeout must be a positive finite number or None; got -0.5"+ },+ {+ "input": "nan",+ "accepted": false,+ "value": null,+ "error": "hooks_timeout must be a positive finite number or None; got nan"+ },+ {+ "input": "inf",+ "accepted": false,+ "value": null,+ "error": "hooks_timeout must be a positive finite number or None; got inf"+ },+ {+ "input": "-inf",+ "accepted": false,+ "value": null,+ "error": "hooks_timeout must be a positive finite number or None; got -inf"+ }+ ],+ "registry": [+ {+ "case": "add-keeps-insertion-order",+ "script": [+ "add:a",+ "add:b",+ "add:c"+ ],+ "steps": [+ {+ "op": "add:a",+ "returned": null,+ "hooks": [+ "a"+ ]+ },+ {+ "op": "add:b",+ "returned": null,+ "hooks": [+ "a",+ "b"+ ]+ },+ {+ "op": "add:c",+ "returned": null,+ "hooks": [+ "a",+ "b",+ "c"+ ]+ }+ ],+ "final": [+ "a",+ "b",+ "c"+ ]+ },+ {+ "case": "add-a-sequence-at-once",+ "script": [+ "add:[a,b]",+ "add:c"+ ],+ "steps": [+ {+ "op": "add:[a,b]",+ "returned": null,+ "hooks": [+ "a",+ "b"+ ]+ },+ {+ "op": "add:c",+ "returned": null,+ "hooks": [+ "a",+ "b",+ "c"+ ]+ }+ ],+ "final": [+ "a",+ "b",+ "c"+ ]+ },+ {+ "case": "the-same-hook-twice",+ "script": [+ "add:a",+ "add:a"+ ],+ "steps": [+ {+ "op": "add:a",+ "returned": null,+ "hooks": [+ "a"+ ]+ },+ {+ "op": "add:a",+ "returned": null,+ "hooks": [+ "a",+ "a"+ ]+ }+ ],+ "final": [+ "a",+ "a"+ ]+ },+ {+ "case": "remove-by-identity",+ "script": [+ "add:a",+ "add:b",+ "remove:a"+ ],+ "steps": [+ {+ "op": "add:a",+ "returned": null,+ "hooks": [+ "a"+ ]+ },+ {+ "op": "add:b",+ "returned": null,+ "hooks": [+ "a",+ "b"+ ]+ },+ {+ "op": "remove:a",+ "returned": true,+ "hooks": [+ "b"+ ]+ }+ ],+ "final": [+ "b"+ ]+ },+ {+ "case": "remove-takes-every-copy",+ "script": [+ "add:a",+ "add:a",+ "add:b",+ "remove:a"+ ],+ "steps": [+ {+ "op": "add:a",+ "returned": null,+ "hooks": [+ "a"+ ]+ },+ {+ "op": "add:a",+ "returned": null,+ "hooks": [+ "a",+ "a"+ ]+ },+ {+ "op": "add:b",+ "returned": null,+ "hooks": [+ "a",+ "a",+ "b"+ ]+ },+ {+ "op": "remove:a",+ "returned": true,+ "hooks": [+ "b"+ ]+ }+ ],+ "final": [+ "b"+ ]+ },+ {+ "case": "remove-something-never-installed",+ "script": [+ "add:a",+ "remove:b"+ ],+ "steps": [+ {+ "op": "add:a",+ "returned": null,+ "hooks": [+ "a"+ ]+ },+ {+ "op": "remove:b",+ "returned": false,+ "hooks": [+ "a"+ ]+ }+ ],+ "final": [+ "a"+ ]+ },+ {+ "case": "a-block-installs-and-restores",+ "script": [+ "enter:1:[t]",+ "exit:1"+ ],+ "steps": [+ {+ "op": "enter:1:[t]",+ "returned": null,+ "hooks": [+ "t"+ ]+ },+ {+ "op": "exit:1",+ "returned": null,+ "hooks": []+ }+ ],+ "final": []+ },+ {+ "case": "a-block-over-an-already-installed-hook",+ "script": [+ "add:a",+ "enter:1:[a]",+ "exit:1"+ ],+ "steps": [+ {+ "op": "add:a",+ "returned": null,+ "hooks": [+ "a"+ ]+ },+ {+ "op": "enter:1:[a]",+ "returned": null,+ "hooks": [+ "a",+ "a"+ ]+ },+ {+ "op": "exit:1",+ "returned": null,+ "hooks": [+ "a"+ ]+ }+ ],+ "final": [+ "a"+ ]+ },+ {+ "case": "overlapping-blocks",+ "script": [+ "enter:1:[x]",+ "enter:2:[y]",+ "exit:2",+ "exit:1"+ ],+ "steps": [+ {+ "op": "enter:1:[x]",+ "returned": null,+ "hooks": [+ "x"+ ]+ },+ {+ "op": "enter:2:[y]",+ "returned": null,+ "hooks": [+ "x",+ "y"+ ]+ },+ {+ "op": "exit:2",+ "returned": null,+ "hooks": [+ "x"+ ]+ },+ {+ "op": "exit:1",+ "returned": null,+ "hooks": []+ }+ ],+ "final": []+ },+ {+ "case": "overlapping-blocks-exited-outermost-first",+ "script": [+ "enter:1:[x]",+ "enter:2:[y]",+ "exit:1",+ "exit:2"+ ],+ "steps": [+ {+ "op": "enter:1:[x]",+ "returned": null,+ "hooks": [+ "x"+ ]+ },+ {+ "op": "enter:2:[y]",+ "returned": null,+ "hooks": [+ "x",+ "y"+ ]+ },+ {+ "op": "exit:1",+ "returned": null,+ "hooks": [+ "y"+ ]+ },+ {+ "op": "exit:2",+ "returned": null,+ "hooks": []+ }+ ],+ "final": []+ },+ {+ "case": "add-inside-a-block-survives-the-exit",+ "script": [+ "enter:1:[t]",+ "add:d",+ "exit:1"+ ],+ "steps": [+ {+ "op": "enter:1:[t]",+ "returned": null,+ "hooks": [+ "t"+ ]+ },+ {+ "op": "add:d",+ "returned": null,+ "hooks": [+ "t",+ "d"+ ]+ },+ {+ "op": "exit:1",+ "returned": null,+ "hooks": [+ "d"+ ]+ }+ ],+ "final": [+ "d"+ ]+ },+ {+ "case": "a-block-with-several-arguments",+ "script": [+ "enter:1:[x],[y,z]",+ "exit:1"+ ],+ "steps": [+ {+ "op": "enter:1:[x],[y,z]",+ "returned": null,+ "hooks": [+ "x",+ "y",+ "z"+ ]+ },+ {+ "op": "exit:1",+ "returned": null,+ "hooks": []+ }+ ],+ "final": []+ },+ {+ "case": "a-block-with-nothing-in-it",+ "script": [+ "enter:1:",+ "exit:1"+ ],+ "steps": [+ {+ "op": "enter:1:",+ "returned": null,+ "hooks": []+ },+ {+ "op": "exit:1",+ "returned": null,+ "hooks": []+ }+ ],+ "final": []+ }+ ],+ "predict_batch": [+ {+ "case": "no-hooks",+ "defaults": [],+ "installed": [],+ "hooks": [],+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "hooks_raise": true,+ "inference_raises": false,+ "inference": {+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "overrides": {}+ },+ "calls": [],+ "result": [+ 110+ ],+ "raised": null,+ "warnings": [],+ "one_run_id_per_call": true,+ "run_id_hex_length": null+ },+ {+ "case": "a-start-hook-sees-the-call",+ "defaults": [],+ "installed": [],+ "hooks": [+ {+ "name": "p",+ "behaviour": {}+ }+ ],+ "states": [+ "s0",+ "s1"+ ],+ "questions": [+ "urgent",+ "intent"+ ],+ "hooks_raise": true,+ "inference_raises": false,+ "inference": {+ "states": [+ "s0",+ "s1"+ ],+ "questions": [+ "urgent",+ "intent"+ ],+ "overrides": {}+ },+ "calls": [+ {+ "call": "p.on_predict_start",+ "states": [+ "s0",+ "s1"+ ],+ "questions": [+ "urgent",+ "intent"+ ],+ "model": "stub-checkpoint",+ "max_len": null,+ "head_max_len": null,+ "results": null,+ "usage": null,+ "error": null,+ "elapsed_ms_set": false+ },+ {+ "call": "p.on_predict_end",+ "states": [+ "s0",+ "s1"+ ],+ "questions": [+ "urgent",+ "intent"+ ],+ "model": "stub-checkpoint",+ "max_len": null,+ "head_max_len": null,+ "results": [+ 110,+ 111+ ],+ "usage": {+ "input_tokens": 221,+ "output_tokens": 201+ },+ "error": null,+ "elapsed_ms_set": true+ }+ ],+ "result": [+ 110,+ 111+ ],+ "raised": null,+ "warnings": [],+ "one_run_id_per_call": true,+ "run_id_hex_length": 32+ },+ {+ "case": "default-installed-and-per-call-all-fire",+ "defaults": [+ {+ "name": "d",+ "behaviour": {}+ }+ ],+ "installed": [+ {+ "name": "i",+ "behaviour": {}+ }+ ],+ "hooks": [+ {+ "name": "p",+ "behaviour": {}+ }+ ],+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "hooks_raise": true,+ "inference_raises": false,+ "inference": {+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "overrides": {}+ },+ "calls": [+ {+ "call": "d.on_predict_start",+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "model": "stub-checkpoint",+ "max_len": null,+ "head_max_len": null,+ "results": null,+ "usage": null,+ "error": null,+ "elapsed_ms_set": false+ },+ {+ "call": "i.on_predict_start",+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "model": "stub-checkpoint",+ "max_len": null,+ "head_max_len": null,+ "results": null,+ "usage": null,+ "error": null,+ "elapsed_ms_set": false+ },+ {+ "call": "p.on_predict_start",+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "model": "stub-checkpoint",+ "max_len": null,+ "head_max_len": null,+ "results": null,+ "usage": null,+ "error": null,+ "elapsed_ms_set": false+ },+ {+ "call": "d.on_predict_end",+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "model": "stub-checkpoint",+ "max_len": null,+ "head_max_len": null,+ "results": [+ 110+ ],+ "usage": {+ "input_tokens": 110,+ "output_tokens": 100+ },+ "error": null,+ "elapsed_ms_set": true+ },+ {+ "call": "i.on_predict_end",+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "model": "stub-checkpoint",+ "max_len": null,+ "head_max_len": null,+ "results": [+ 110+ ],+ "usage": {+ "input_tokens": 110,+ "output_tokens": 100+ },+ "error": null,+ "elapsed_ms_set": true+ },+ {+ "call": "p.on_predict_end",+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "model": "stub-checkpoint",+ "max_len": null,+ "head_max_len": null,+ "results": [+ 110+ ],+ "usage": {+ "input_tokens": 110,+ "output_tokens": 100+ },+ "error": null,+ "elapsed_ms_set": true+ }+ ],+ "result": [+ 110+ ],+ "raised": null,+ "warnings": [],+ "one_run_id_per_call": true,+ "run_id_hex_length": 32+ },+ {+ "case": "a-start-hook-rewrites-the-states",+ "defaults": [],+ "installed": [],+ "hooks": [+ {+ "name": "p",+ "behaviour": {+ "on_predict_start": "states:x,y,z"+ }+ }+ ],+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "hooks_raise": true,+ "inference_raises": false,+ "inference": {+ "states": [+ "x",+ "y",+ "z"+ ],+ "questions": [+ "q"+ ],+ "overrides": {}+ },+ "calls": [+ {+ "call": "p.on_predict_start",+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "model": "stub-checkpoint",+ "max_len": null,+ "head_max_len": null,+ "results": null,+ "usage": null,+ "error": null,+ "elapsed_ms_set": false+ },+ {+ "call": "p.on_predict_end",+ "states": [+ "x",+ "y",+ "z"+ ],+ "questions": [+ "q"+ ],+ "model": "stub-checkpoint",+ "max_len": null,+ "head_max_len": null,+ "results": [+ 110,+ 111,+ 112+ ],+ "usage": {+ "input_tokens": 333,+ "output_tokens": 303+ },+ "error": null,+ "elapsed_ms_set": true+ }+ ],+ "result": [+ 110,+ 111,+ 112+ ],+ "raised": null,+ "warnings": [],+ "one_run_id_per_call": true,+ "run_id_hex_length": 32+ },+ {+ "case": "a-start-hook-rewrites-the-questions",+ "defaults": [],+ "installed": [],+ "hooks": [+ {+ "name": "p",+ "behaviour": {+ "on_predict_start": "questions:urgent,intent"+ }+ }+ ],+ "states": [+ "s0"+ ],+ "questions": [+ "q",+ "r"+ ],+ "hooks_raise": true,+ "inference_raises": false,+ "inference": {+ "states": [+ "s0"+ ],+ "questions": [+ "urgent",+ "intent"+ ],+ "overrides": {}+ },+ "calls": [+ {+ "call": "p.on_predict_start",+ "states": [+ "s0"+ ],+ "questions": [+ "q",+ "r"+ ],+ "model": "stub-checkpoint",+ "max_len": null,+ "head_max_len": null,+ "results": null,+ "usage": null,+ "error": null,+ "elapsed_ms_set": false+ },+ {+ "call": "p.on_predict_end",+ "states": [+ "s0"+ ],+ "questions": [+ "urgent",+ "intent"+ ],+ "model": "stub-checkpoint",+ "max_len": null,+ "head_max_len": null,+ "results": [+ 110+ ],+ "usage": {+ "input_tokens": 110,+ "output_tokens": 100+ },+ "error": null,+ "elapsed_ms_set": true+ }+ ],+ "result": [+ 110+ ],+ "raised": null,+ "warnings": [],+ "one_run_id_per_call": true,+ "run_id_hex_length": 32+ },+ {+ "case": "a-start-hook-sets-the-token-budget",+ "defaults": [],+ "installed": [],+ "hooks": [+ {+ "name": "p",+ "behaviour": {+ "on_predict_start": "max_len:128"+ }+ }+ ],+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "hooks_raise": true,+ "inference_raises": false,+ "inference": {+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "overrides": {+ "max_len": 128+ }+ },+ "calls": [+ {+ "call": "p.on_predict_start",+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "model": "stub-checkpoint",+ "max_len": null,+ "head_max_len": null,+ "results": null,+ "usage": null,+ "error": null,+ "elapsed_ms_set": false+ },+ {+ "call": "p.on_predict_end",+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "model": "stub-checkpoint",+ "max_len": 128,+ "head_max_len": null,+ "results": [+ 110+ ],+ "usage": {+ "input_tokens": 110,+ "output_tokens": 100+ },+ "error": null,+ "elapsed_ms_set": true+ }+ ],+ "result": [+ 110+ ],+ "raised": null,+ "warnings": [],+ "one_run_id_per_call": true,+ "run_id_hex_length": 32+ },+ {+ "case": "a-start-hook-sets-the-head-budget",+ "defaults": [],+ "installed": [],+ "hooks": [+ {+ "name": "p",+ "behaviour": {+ "on_predict_start": "head_max_len:64"+ }+ }+ ],+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "hooks_raise": true,+ "inference_raises": false,+ "inference": {+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "overrides": {+ "head_max_len": 64+ }+ },+ "calls": [+ {+ "call": "p.on_predict_start",+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "model": "stub-checkpoint",+ "max_len": null,+ "head_max_len": null,+ "results": null,+ "usage": null,+ "error": null,+ "elapsed_ms_set": false+ },+ {+ "call": "p.on_predict_end",+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "model": "stub-checkpoint",+ "max_len": null,+ "head_max_len": 64,+ "results": [+ 110+ ],+ "usage": {+ "input_tokens": 110,+ "output_tokens": 100+ },+ "error": null,+ "elapsed_ms_set": true+ }+ ],+ "result": [+ 110+ ],+ "raised": null,+ "warnings": [],+ "one_run_id_per_call": true,+ "run_id_hex_length": 32+ },+ {+ "case": "skip-answers-the-call",+ "defaults": [],+ "installed": [],+ "hooks": [+ {+ "name": "p",+ "behaviour": {+ "on_predict_start": "skip:1"+ }+ }+ ],+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "hooks_raise": true,+ "inference_raises": false,+ "inference": null,+ "calls": [+ {+ "call": "p.on_predict_start",+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "model": "stub-checkpoint",+ "max_len": null,+ "head_max_len": null,+ "results": null,+ "usage": null,+ "error": null,+ "elapsed_ms_set": false+ },+ {+ "call": "p.on_predict_end",+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "model": "stub-checkpoint",+ "max_len": null,+ "head_max_len": null,+ "results": [+ 10+ ],+ "usage": {+ "input_tokens": 10,+ "output_tokens": 0+ },+ "error": null,+ "elapsed_ms_set": true+ }+ ],+ "result": [+ 10+ ],+ "raised": null,+ "warnings": [],+ "one_run_id_per_call": true,+ "run_id_hex_length": 32+ },+ {+ "case": "skip-one-per-state",+ "defaults": [],+ "installed": [],+ "hooks": [+ {+ "name": "p",+ "behaviour": {+ "on_predict_start": "skip:2"+ }+ }+ ],+ "states": [+ "s0",+ "s1"+ ],+ "questions": [+ "q"+ ],+ "hooks_raise": true,+ "inference_raises": false,+ "inference": null,+ "calls": [+ {+ "call": "p.on_predict_start",+ "states": [+ "s0",+ "s1"+ ],+ "questions": [+ "q"+ ],+ "model": "stub-checkpoint",+ "max_len": null,+ "head_max_len": null,+ "results": null,+ "usage": null,+ "error": null,+ "elapsed_ms_set": false+ },+ {+ "call": "p.on_predict_end",+ "states": [+ "s0",+ "s1"+ ],+ "questions": [+ "q"+ ],+ "model": "stub-checkpoint",+ "max_len": null,+ "head_max_len": null,+ "results": [+ 10,+ 11+ ],+ "usage": {+ "input_tokens": 21,+ "output_tokens": 1+ },+ "error": null,+ "elapsed_ms_set": true+ }+ ],+ "result": [+ 10,+ 11+ ],+ "raised": null,+ "warnings": [],+ "one_run_id_per_call": true,+ "run_id_hex_length": 32+ },+ {+ "case": "skip-one-for-the-whole-call",+ "defaults": [],+ "installed": [],+ "hooks": [+ {+ "name": "p",+ "behaviour": {+ "on_predict_start": "skip:1"+ }+ }+ ],+ "states": [+ "s0",+ "s1"+ ],+ "questions": [+ "q"+ ],+ "hooks_raise": true,+ "inference_raises": false,+ "inference": null,+ "calls": [+ {+ "call": "p.on_predict_start",+ "states": [+ "s0",+ "s1"+ ],+ "questions": [+ "q"+ ],+ "model": "stub-checkpoint",+ "max_len": null,+ "head_max_len": null,+ "results": null,+ "usage": null,+ "error": null,+ "elapsed_ms_set": false+ },+ {+ "call": "p.on_predict_end",+ "states": [+ "s0",+ "s1"+ ],+ "questions": [+ "q"+ ],+ "model": "stub-checkpoint",+ "max_len": null,+ "head_max_len": null,+ "results": [+ 10+ ],+ "usage": {+ "input_tokens": 10,+ "output_tokens": 0+ },+ "error": null,+ "elapsed_ms_set": true+ }+ ],+ "result": [+ 10+ ],+ "raised": null,+ "warnings": [],+ "one_run_id_per_call": true,+ "run_id_hex_length": 32+ },+ {+ "case": "skip-with-a-count-that-fits-nothing",+ "defaults": [],+ "installed": [],+ "hooks": [+ {+ "name": "p",+ "behaviour": {+ "on_predict_start": "skip:3"+ }+ }+ ],+ "states": [+ "s0",+ "s1"+ ],+ "questions": [+ "q"+ ],+ "hooks_raise": true,+ "inference_raises": false,+ "inference": null,+ "calls": [+ {+ "call": "p.on_predict_start",+ "states": [+ "s0",+ "s1"+ ],+ "questions": [+ "q"+ ],+ "model": "stub-checkpoint",+ "max_len": null,+ "head_max_len": null,+ "results": null,+ "usage": null,+ "error": null,+ "elapsed_ms_set": false+ },+ {+ "call": "p.on_error",+ "states": [+ "s0",+ "s1"+ ],+ "questions": [+ "q"+ ],+ "model": "stub-checkpoint",+ "max_len": null,+ "head_max_len": null,+ "results": null,+ "usage": null,+ "error": "ctx.skip() takes one result for the whole call or one per state in ctx.states (2); got 3",+ "elapsed_ms_set": false+ },+ {+ "call": "p.on_predict_end",+ "states": [+ "s0",+ "s1"+ ],+ "questions": [+ "q"+ ],+ "model": "stub-checkpoint",+ "max_len": null,+ "head_max_len": null,+ "results": null,+ "usage": null,+ "error": "ctx.skip() takes one result for the whole call or one per state in ctx.states (2); got 3",+ "elapsed_ms_set": true+ }+ ],+ "result": null,+ "raised": {+ "type": "ValueError",+ "message": "ctx.skip() takes one result for the whole call or one per state in ctx.states (2); got 3",+ "context": null+ },+ "warnings": [],+ "one_run_id_per_call": true,+ "run_id_hex_length": 32+ },+ {+ "case": "the-last-skip-wins",+ "defaults": [],+ "installed": [],+ "hooks": [+ {+ "name": "p",+ "behaviour": {+ "on_predict_start": "skip:1"+ }+ },+ {+ "name": "p2",+ "behaviour": {+ "on_predict_start": "skip:2"+ }+ }+ ],+ "states": [+ "s0",+ "s1"+ ],+ "questions": [+ "q"+ ],+ "hooks_raise": true,+ "inference_raises": false,+ "inference": null,+ "calls": [+ {+ "call": "p.on_predict_start",+ "states": [+ "s0",+ "s1"+ ],+ "questions": [+ "q"+ ],+ "model": "stub-checkpoint",+ "max_len": null,+ "head_max_len": null,+ "results": null,+ "usage": null,+ "error": null,+ "elapsed_ms_set": false+ },+ {+ "call": "p2.on_predict_start",+ "states": [+ "s0",+ "s1"+ ],+ "questions": [+ "q"+ ],+ "model": "stub-checkpoint",+ "max_len": null,+ "head_max_len": null,+ "results": [+ 10+ ],+ "usage": null,+ "error": null,+ "elapsed_ms_set": false+ },+ {+ "call": "p.on_predict_end",+ "states": [+ "s0",+ "s1"+ ],+ "questions": [+ "q"+ ],+ "model": "stub-checkpoint",+ "max_len": null,+ "head_max_len": null,+ "results": [+ 10,+ 11+ ],+ "usage": {+ "input_tokens": 21,+ "output_tokens": 1+ },+ "error": null,+ "elapsed_ms_set": true+ },+ {+ "call": "p2.on_predict_end",+ "states": [+ "s0",+ "s1"+ ],+ "questions": [+ "q"+ ],+ "model": "stub-checkpoint",+ "max_len": null,+ "head_max_len": null,+ "results": [+ 10,+ 11+ ],+ "usage": {+ "input_tokens": 21,+ "output_tokens": 1+ },+ "error": null,+ "elapsed_ms_set": true+ }+ ],+ "result": [+ 10,+ 11+ ],+ "raised": null,+ "warnings": [],+ "one_run_id_per_call": true,+ "run_id_hex_length": 32+ },+ {+ "case": "an-end-hook-rewrites-the-results",+ "defaults": [],+ "installed": [],+ "hooks": [+ {+ "name": "p",+ "behaviour": {+ "on_predict_end": "results:1"+ }+ }+ ],+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "hooks_raise": true,+ "inference_raises": false,+ "inference": {+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "overrides": {}+ },+ "calls": [+ {+ "call": "p.on_predict_start",+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "model": "stub-checkpoint",+ "max_len": null,+ "head_max_len": null,+ "results": null,+ "usage": null,+ "error": null,+ "elapsed_ms_set": false+ },+ {+ "call": "p.on_predict_end",+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "model": "stub-checkpoint",+ "max_len": null,+ "head_max_len": null,+ "results": [+ 110+ ],+ "usage": {+ "input_tokens": 110,+ "output_tokens": 100+ },+ "error": null,+ "elapsed_ms_set": true+ }+ ],+ "result": [+ 510+ ],+ "raised": null,+ "warnings": [],+ "one_run_id_per_call": true,+ "run_id_hex_length": 32+ },+ {+ "case": "a-raising-start-hook-fails-the-call",+ "defaults": [],+ "installed": [],+ "hooks": [+ {+ "name": "p",+ "behaviour": {+ "on_predict_start": "raise"+ }+ },+ {+ "name": "p2",+ "behaviour": {}+ }+ ],+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "hooks_raise": true,+ "inference_raises": false,+ "inference": null,+ "calls": [+ {+ "call": "p.on_predict_start",+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "model": "stub-checkpoint",+ "max_len": null,+ "head_max_len": null,+ "results": null,+ "usage": null,+ "error": null,+ "elapsed_ms_set": false+ },+ {+ "call": "p.on_error",+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "model": "stub-checkpoint",+ "max_len": null,+ "head_max_len": null,+ "results": null,+ "usage": null,+ "error": "boom from p",+ "elapsed_ms_set": false+ },+ {+ "call": "p2.on_error",+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "model": "stub-checkpoint",+ "max_len": null,+ "head_max_len": null,+ "results": null,+ "usage": null,+ "error": "boom from p",+ "elapsed_ms_set": false+ },+ {+ "call": "p.on_predict_end",+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "model": "stub-checkpoint",+ "max_len": null,+ "head_max_len": null,+ "results": null,+ "usage": null,+ "error": "boom from p",+ "elapsed_ms_set": true+ },+ {+ "call": "p2.on_predict_end",+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "model": "stub-checkpoint",+ "max_len": null,+ "head_max_len": null,+ "results": null,+ "usage": null,+ "error": "boom from p",+ "elapsed_ms_set": true+ }+ ],+ "result": null,+ "raised": {+ "type": "ValueError",+ "message": "boom from p",+ "context": null+ },+ "warnings": [],+ "one_run_id_per_call": true,+ "run_id_hex_length": 32+ },+ {+ "case": "a-raising-start-hook-is-only-a-warning",+ "defaults": [],+ "installed": [],+ "hooks": [+ {+ "name": "p",+ "behaviour": {+ "on_predict_start": "raise"+ }+ },+ {+ "name": "p2",+ "behaviour": {}+ }+ ],+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "hooks_raise": false,+ "inference_raises": false,+ "inference": {+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "overrides": {}+ },+ "calls": [+ {+ "call": "p.on_predict_start",+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "model": "stub-checkpoint",+ "max_len": null,+ "head_max_len": null,+ "results": null,+ "usage": null,+ "error": null,+ "elapsed_ms_set": false+ },+ {+ "call": "p2.on_predict_start",+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "model": "stub-checkpoint",+ "max_len": null,+ "head_max_len": null,+ "results": null,+ "usage": null,+ "error": null,+ "elapsed_ms_set": false+ },+ {+ "call": "p.on_predict_end",+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "model": "stub-checkpoint",+ "max_len": null,+ "head_max_len": null,+ "results": [+ 110+ ],+ "usage": {+ "input_tokens": 110,+ "output_tokens": 100+ },+ "error": null,+ "elapsed_ms_set": true+ },+ {+ "call": "p2.on_predict_end",+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "model": "stub-checkpoint",+ "max_len": null,+ "head_max_len": null,+ "results": [+ 110+ ],+ "usage": {+ "input_tokens": 110,+ "output_tokens": 100+ },+ "error": null,+ "elapsed_ms_set": true+ }+ ],+ "result": [+ 110+ ],+ "raised": null,+ "warnings": [+ "laya: hook StubHook.on_predict_start failed: boom from p"+ ],+ "one_run_id_per_call": true,+ "run_id_hex_length": 32+ },+ {+ "case": "a-raising-end-hook-fails-the-call",+ "defaults": [],+ "installed": [],+ "hooks": [+ {+ "name": "p",+ "behaviour": {+ "on_predict_end": "raise"+ }+ }+ ],+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "hooks_raise": true,+ "inference_raises": false,+ "inference": {+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "overrides": {}+ },+ "calls": [+ {+ "call": "p.on_predict_start",+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "model": "stub-checkpoint",+ "max_len": null,+ "head_max_len": null,+ "results": null,+ "usage": null,+ "error": null,+ "elapsed_ms_set": false+ },+ {+ "call": "p.on_predict_end",+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "model": "stub-checkpoint",+ "max_len": null,+ "head_max_len": null,+ "results": [+ 110+ ],+ "usage": {+ "input_tokens": 110,+ "output_tokens": 100+ },+ "error": null,+ "elapsed_ms_set": true+ }+ ],+ "result": null,+ "raised": {+ "type": "ValueError",+ "message": "boom from p",+ "context": null+ },+ "warnings": [],+ "one_run_id_per_call": true,+ "run_id_hex_length": 32+ },+ {+ "case": "a-raising-end-hook-is-only-a-warning",+ "defaults": [],+ "installed": [],+ "hooks": [+ {+ "name": "p",+ "behaviour": {+ "on_predict_end": "raise"+ }+ }+ ],+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "hooks_raise": false,+ "inference_raises": false,+ "inference": {+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "overrides": {}+ },+ "calls": [+ {+ "call": "p.on_predict_start",+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "model": "stub-checkpoint",+ "max_len": null,+ "head_max_len": null,+ "results": null,+ "usage": null,+ "error": null,+ "elapsed_ms_set": false+ },+ {+ "call": "p.on_predict_end",+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "model": "stub-checkpoint",+ "max_len": null,+ "head_max_len": null,+ "results": [+ 110+ ],+ "usage": {+ "input_tokens": 110,+ "output_tokens": 100+ },+ "error": null,+ "elapsed_ms_set": true+ }+ ],+ "result": [+ 110+ ],+ "raised": null,+ "warnings": [+ "laya: hook StubHook.on_predict_end failed: boom from p"+ ],+ "one_run_id_per_call": true,+ "run_id_hex_length": 32+ },+ {+ "case": "inference-fails",+ "defaults": [],+ "installed": [],+ "hooks": [+ {+ "name": "p",+ "behaviour": {}+ }+ ],+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "hooks_raise": true,+ "inference_raises": true,+ "inference": {+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "overrides": {}+ },+ "calls": [+ {+ "call": "p.on_predict_start",+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "model": "stub-checkpoint",+ "max_len": null,+ "head_max_len": null,+ "results": null,+ "usage": null,+ "error": null,+ "elapsed_ms_set": false+ },+ {+ "call": "p.on_error",+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "model": "stub-checkpoint",+ "max_len": null,+ "head_max_len": null,+ "results": null,+ "usage": null,+ "error": "the graph refused this batch",+ "elapsed_ms_set": false+ },+ {+ "call": "p.on_predict_end",+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "model": "stub-checkpoint",+ "max_len": null,+ "head_max_len": null,+ "results": null,+ "usage": null,+ "error": "the graph refused this batch",+ "elapsed_ms_set": true+ }+ ],+ "result": null,+ "raised": {+ "type": "RuntimeError",+ "message": "the graph refused this batch",+ "context": null+ },+ "warnings": [],+ "one_run_id_per_call": true,+ "run_id_hex_length": 32+ },+ {+ "case": "inference-fails-with-a-raising-error-hook",+ "defaults": [],+ "installed": [],+ "hooks": [+ {+ "name": "p",+ "behaviour": {+ "on_error": "raise"+ }+ }+ ],+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "hooks_raise": true,+ "inference_raises": true,+ "inference": {+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "overrides": {}+ },+ "calls": [+ {+ "call": "p.on_predict_start",+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "model": "stub-checkpoint",+ "max_len": null,+ "head_max_len": null,+ "results": null,+ "usage": null,+ "error": null,+ "elapsed_ms_set": false+ },+ {+ "call": "p.on_error",+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "model": "stub-checkpoint",+ "max_len": null,+ "head_max_len": null,+ "results": null,+ "usage": null,+ "error": "the graph refused this batch",+ "elapsed_ms_set": false+ },+ {+ "call": "p.on_predict_end",+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "model": "stub-checkpoint",+ "max_len": null,+ "head_max_len": null,+ "results": null,+ "usage": null,+ "error": "the graph refused this batch",+ "elapsed_ms_set": true+ }+ ],+ "result": null,+ "raised": {+ "type": "RuntimeError",+ "message": "the graph refused this batch",+ "context": "ValueError"+ },+ "warnings": [],+ "one_run_id_per_call": true,+ "run_id_hex_length": 32+ },+ {+ "case": "inference-fails-with-a-raising-end-hook",+ "defaults": [],+ "installed": [],+ "hooks": [+ {+ "name": "p",+ "behaviour": {+ "on_predict_end": "raise"+ }+ }+ ],+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "hooks_raise": true,+ "inference_raises": true,+ "inference": {+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "overrides": {}+ },+ "calls": [+ {+ "call": "p.on_predict_start",+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "model": "stub-checkpoint",+ "max_len": null,+ "head_max_len": null,+ "results": null,+ "usage": null,+ "error": null,+ "elapsed_ms_set": false+ },+ {+ "call": "p.on_error",+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "model": "stub-checkpoint",+ "max_len": null,+ "head_max_len": null,+ "results": null,+ "usage": null,+ "error": "the graph refused this batch",+ "elapsed_ms_set": false+ },+ {+ "call": "p.on_predict_end",+ "states": [+ "s0"+ ],+ "questions": [+ "q"+ ],+ "model": "stub-checkpoint",+ "max_len": null,+ "head_max_len": null,+ "results": null,+ "usage": null,+ "error": "the graph refused this batch",+ "elapsed_ms_set": true+ }+ ],+ "result": null,+ "raised": {+ "type": "RuntimeError",+ "message": "the graph refused this batch",+ "context": "ValueError"+ },+ "warnings": [],+ "one_run_id_per_call": true,+ "run_id_hex_length": 32+ },+ {+ "case": "no-states",+ "defaults": [],+ "installed": [],+ "hooks": [+ {+ "name": "p",+ "behaviour": {}+ }+ ],+ "states": [],+ "questions": [+ "q"+ ],+ "hooks_raise": true,+ "inference_raises": false,+ "inference": null,+ "calls": [+ {+ "call": "p.on_predict_start",+ "states": [],+ "questions": [+ "q"+ ],+ "model": "stub-checkpoint",+ "max_len": null,+ "head_max_len": null,+ "results": null,+ "usage": null,+ "error": null,+ "elapsed_ms_set": false+ },+ {+ "call": "p.on_predict_end",+ "states": [],+ "questions": [+ "q"+ ],+ "model": "stub-checkpoint",+ "max_len": null,+ "head_max_len": null,+ "results": [],+ "usage": {+ "input_tokens": 0,+ "output_tokens": 0+ },+ "error": null,+ "elapsed_ms_set": true+ }+ ],+ "result": [],+ "raised": null,+ "warnings": [],+ "one_run_id_per_call": true,+ "run_id_hex_length": 32+ }+ ]+}diff --git a/laya-java/laya-java/src/main/java/com/convaiinnovations/laya/Agent.java b/laya-java/laya-java/src/main/java/com/convaiinnovations/laya/Agent.javaindex 13778d99..3873b486 100644--- a/laya-java/laya-java/src/main/java/com/convaiinnovations/laya/Agent.java+++ b/laya-java/laya-java/src/main/java/com/convaiinnovations/laya/Agent.java@@ -2,6 +2,10 @@ package com.convaiinnovations.laya;import com.convaiinnovations.laya.config.AgentConfig;import com.convaiinnovations.laya.decode.Decoder;+import com.convaiinnovations.laya.hooks.HookCall;+import com.convaiinnovations.laya.hooks.HookRegistry;+import com.convaiinnovations.laya.hooks.Hooks;+import com.convaiinnovations.laya.hooks.PredictContext;import com.convaiinnovations.laya.infer.InferenceSession;import com.convaiinnovations.laya.onnx.LayaSession;import com.convaiinnovations.laya.sequence.Collator;@@ -47,6 +51,16 @@ public final class Agent implements AutoCloseable, Predictor {private final AgentConfig config;private final InferenceSession session;private final int padId;+ private final String modelName;+ /**+ * This agent's hooks, which a caller may edit at any point in its life.+ *+ * <p>Final and never replaced: a call takes a snapshot of the list, so installing a hook+ * mid-flight cannot disturb one, and handing out the registry rather than copying hook+ * methods onto {@code Agent} keeps six lifecycle names off the surface of a class whose+ * subject is prediction.+ */+ private final HookRegistry hooks = new HookRegistry();/*** This agent's own lifecycle, not the session's.*@@ -57,11 +71,13 @@ public final class Agent implements AutoCloseable, Predictor {*/private volatile boolean closed;- private Agent(Tokenizer tokenizer, AgentConfig config, InferenceSession session, int padId) {+ private Agent(Tokenizer tokenizer, AgentConfig config, InferenceSession session, int padId,+ String modelName) {this.tokenizer = tokenizer;this.config = config;this.session = session;this.padId = padId;+ this.modelName = modelName;}/**@@ -79,9 +95,11 @@ public final class Agent implements AutoCloseable, Predictor {/** Opens a checkpoint with an explicit intra-op thread count. */public static Agent open(Path modelDirectory, Path graphDirectory, int threads)throws IOException {+ Path name = modelDirectory.getFileName();return using(Tokenizer.fromModelDirectory(modelDirectory),AgentConfig.fromModelDirectory(modelDirectory),- LayaSession.open(graphDirectory, threads));+ LayaSession.open(graphDirectory, threads),+ name == null ? null : name.toString());}/**@@ -90,6 +108,19 @@ public final class Agent implements AutoCloseable, Predictor {* stub {@link InferenceSession} instead of a 1.2 GB graph.*/public static Agent using(Tokenizer tokenizer, AgentConfig config, InferenceSession session) {+ return using(tokenizer, config, session, null);+ }++ /**+ * Assembles an agent from parts, naming the checkpoint.+ *+ * @param modelName what {@link PredictContext#model()} reports to a hook, or null. A router+ * serving several checkpoints through one tokenizer is the caller that needs it: without+ * a name, a hook watching every prediction in a process cannot say which checkpoint+ * answered+ */+ public static Agent using(Tokenizer tokenizer, AgentConfig config, InferenceSession session,+ String modelName) {// Padding is masked out of attention but still embedded, so it has to be a real id.// No silent fallback to the SEP id. The reference hands `tok.pad_token_id` straight to// the collator, so a checkpoint naming no pad_token fails the request outright -- and a@@ -99,7 +130,29 @@ public final class Agent implements AutoCloseable, Predictor {int padId = tokenizer.padId().orElseThrow(() -> new IllegalStateException("this checkpoint names no pad_token, so a batch cannot be padded; the reference "+ "refuses the same checkpoint"));- return new Agent(tokenizer, config, session, padId);+ return new Agent(tokenizer, config, session, padId, modelName);+ }++ /**+ * The checkpoint name a hook sees, or null when the agent was assembled without one.+ *+ * <p>{@link #open} takes it from the model directory's own name; that is the only thing a+ * checkpoint on disk is identified by here, since {@code rl_agent_config.json} does not+ * carry one.+ */+ public String modelName() {+ return modelName;+ }++ /**+ * This agent's hooks: install, remove, and the policy for a throwing or slow one.+ *+ * <pre>{@code+ * agent.hooks().addHook(tracer).raiseErrors(false);+ * }</pre>+ */+ public HookRegistry hooks() {+ return hooks;}/** The checkpoint's tokenizer, for callers that want to measure a state's token cost. */@@ -156,10 +209,54 @@ public final class Agent implements AutoCloseable, Predictor {*/public List<Prediction> predictBatch(List<?> states, Map<String, Question> questions,String language, int batchSize, boolean sortByLength) {+ return predictBatch(states, questions, language, batchSize, sortByLength, HookCall.none());+ }++ /**+ * Asks every question about every state, with hooks around the call.+ *+ * <p>The hooks are this agent's installed ones, after any process-wide defaults, with+ * {@code call}'s own appended last — see {@link Hooks#compose}. A start hook may rewrite the+ * states, the questions or the token budget, or answer the call outright with+ * {@link PredictContext#skip}, in which case the model is never reached. An end hook may+ * replace the results, and what it leaves is what this returns.+ *+ * <p>The checks on the states and the questions happen AFTER the start hooks, deliberately,+ * and that is the reference's order too: only the value that survives the hooks is+ * validated, so a hook that normalises a caller's loose input is allowed to do its job.+ *+ * @param call per-call hooks and policy overrides, or {@link HookCall#none()}+ */+ public List<Prediction> predictBatch(List<?> states, Map<String, Question> questions,+ String language, int batchSize, boolean sortByLength,+ HookCall call) {+ // Before any hook: a closed agent cannot answer, and dispatching a start hook that then+ // watched the call fail would report a prediction that was never going to happen.if (closed) {throw new IllegalStateException("this agent is closed; open a new one rather than reusing it");}+ PredictContext ctx = new PredictContext(states, questions, modelName, this);+ return Hooks.around(hooks.composeFor(call), ctx, hooks.policyFor(call),+ (hooked, asked, maxLen, headMaxLen) ->+ infer(hooked, asked, language, batchSize, sortByLength, maxLen,+ headMaxLen));+ }++ /**+ * The forward passes, over whatever the start hooks left to ask.+ *+ * <p>The reference's {@code _infer_batch}: everything a hook cannot change once it has run.+ * Separate from {@link #predictBatch} so that {@link #predictLong} can reach it without+ * dispatching a hook chain — see that method for why it must not — and so the hook wrapper+ * itself is one shared, tested piece rather than a sequence repeated per entry point.+ *+ * @param maxLen the per-call token budget a hook set, or null for the checkpoint's+ * @param headMaxLen the per-call head budget a hook set, or null for the checkpoint's+ */+ private List<Prediction> infer(List<?> states, Map<String, Question> questions,+ String language, int batchSize, boolean sortByLength,+ Integer maxLen, Integer headMaxLen) {for (int i = 0; i < states.size(); i++) {// Refused, as both Python backends refuse it: `serialize_state(None)` is// `json.dumps(None)`, so a missing state would otherwise be answered as a decision@@ -195,6 +292,8 @@ public final class Agent implements AutoCloseable, Predictor {throw new IllegalArgumentException("question " + entry.getKey() + " is null");}}+ int tokenBudget = maxLen == null ? config.maxLen() : maxLen;+ int headBudget = headMaxLen == null ? config.headMaxLen() : headMaxLen;List<String> questionIds = new ArrayList<>(asked.keySet());int chunk = batchSize > 0 ? batchSize : states.size();// Sorting only pays off when it can actually reorder across more than one call, which@@ -210,7 +309,8 @@ public final class Agent implements AutoCloseable, Predictor {int end = Math.min(states.size(), start + window);List<List<SequenceBuilder.Sequence>> encoded = new ArrayList<>(end - start);for (int i = start; i < end; i++) {- encoded.add(encodeState(states.get(i), questionIds, asked));+ encoded.add(encodeState(states.get(i), questionIds, asked, tokenBudget,+ headBudget));}List<Integer> order = new ArrayList<>(encoded.size());for (int i = 0; i < encoded.size(); i++) {@@ -269,8 +369,28 @@ public final class Agent implements AutoCloseable, Predictor {* does. The returned probability and confidence are the deciding window's, not a calibrated* number for the document; {@link LongPrediction.Window} says which window that was.*- * <p>A state that already fits one window is passed straight to {@link #predict}, with no- * window attribution and {@code windows == 1}.+ * <p>A state that already fits one window is answered in one call, with no window+ * attribution and {@code windows == 1}.+ *+ * <p><b>No hook runs here.</b> Not the per-call ones — there is no {@link HookCall}+ * parameter — and not the installed or process-wide ones either: the scan reaches the+ * forward passes through the same private path {@link #predictBatch} wraps, rather than+ * through {@code predictBatch} itself. That is a decision, not an omission.+ *+ * <p>A hook's whole power is to rewrite what is asked, and a scan is SIZED before any hook+ * could run. The reference lets hooks into {@code predict_long} and then spends four pieces+ * of machinery keeping them honest: a probe appended after the caller's own start hooks to+ * record what inference was actually handed, a budget check run after the chain to catch a+ * hook that added options the windows were not sized for, and two separate reporting paths+ * for a hook that answered the document outright and one that rewrote the states it was+ * scanned over. Without those, a hook that adds one option silently re-truncates every+ * window — the tail of each reaches no model while the reported span says it did — and a+ * hook that answers the call leaves {@code windows} claiming a scan that never happened.+ *+ * <p>Running hooks here without that machinery would be worse than not running them, so+ * this does not. Nothing is silently dropped: {@link #predictBatch} takes a {@link HookCall},+ * and a caller who needs hooks over a long state can window it themselves and hand the+ * windows to that.** @param window state tokens per window, or null for the per-question budget. Capped at* the room the questions leave -- see {@link WindowPlan}@@ -311,7 +431,8 @@ public final class Agent implements AutoCloseable, Predictor {if (stateIds.length <= plan.window()) {// Identical to a plain call, with no windowing overhead and no window attribution --// nothing decided between windows because there was only one.- Prediction single = predict(state, questions, language);+ Prediction single = infer(Collections.singletonList(state), questions, language, 0,+ false, null, null).get(0);Map<String, LongPrediction.Windowed> answers = new LinkedHashMap<>();for (Map.Entry<String, Answer> entry : single.answers().entrySet()) {answers.put(entry.getKey(),@@ -344,8 +465,8 @@ public final class Agent implements AutoCloseable, Predictor {Integer cap = WindowPlan.batchCap(scanned.size(), plan.window(),Math.max(64, maxLen - headMaxLen - 8), batchSize > 0 ? batchSize : null);- List<Prediction> results = predictBatch(scanned, questions, language,- cap == null ? 0 : cap, false);+ List<Prediction> results = infer(scanned, questions, language,+ cap == null ? 0 : cap, false, null, null);if (results.size() != scanned.size()) {throw new IllegalStateException(String.format("the state was split into %d windows and the batch returned %d results",@@ -445,9 +566,13 @@ public final class Agent implements AutoCloseable, Predictor {** <p>Once, not once per question: that is what {@code build_sequence}'s pre-tokenized state* parameter exists for, and a document is usually far longer than the question asked about it.+ *+ * @param maxLen the budget in force for this call, the checkpoint's unless a hook moved it+ * @param headMaxLen the head budget in force for this call, likewise*/private List<SequenceBuilder.Sequence> encodeState(Object state, List<String> questionIds,- Map<String, Question> questions) {+ Map<String, Question> questions,+ int maxLen, int headMaxLen) {int[] stateIds = tokenizer.encode(SequenceBuilder.serializeState(state).replace(maskToken(), " "), -1);List<SequenceBuilder.Sequence> built = new ArrayList<>(questionIds.size());@@ -462,7 +587,7 @@ public final class Agent implements AutoCloseable, Predictor {// byte-identical, so nothing a caller can read revealed it.boolean truncateLeft = state instanceof List;SequenceBuilder.Sequence sequence = SequenceBuilder.build(tokenizer, state, question,- config.maxLen(), config.headMaxLen(), null, truncateLeft, stateIds);+ maxLen, headMaxLen, null, truncateLeft, stateIds);int defined = question.renderOptions().size();if (sequence.markers().length != defined) {// Markers sit at absolute positions and the sequence is then cut to `max_len`, so@@ -475,8 +600,7 @@ public final class Agent implements AutoCloseable, Predictor {"question %s: only %d of its %d option markers fit in max_len=%d with "+ "head_max_len=%d spent on the question; lower head_max_len, raise "+ "max_len, or use fewer options",- id, sequence.markers().length, defined, config.maxLen(),- config.headMaxLen()));+ id, sequence.markers().length, defined, maxLen, headMaxLen));}built.add(sequence);}diff --git a/laya-java/laya-java/src/main/java/com/convaiinnovations/laya/hooks/Hook.java b/laya-java/laya-java/src/main/java/com/convaiinnovations/laya/hooks/Hook.javanew file mode 100644index 00000000..377ac8b1--- /dev/null+++ b/laya-java/laya-java/src/main/java/com/convaiinnovations/laya/hooks/Hook.java@@ -0,0 +1,91 @@+package com.convaiinnovations.laya.hooks;++/**+ * The one place a caller's own code runs inside a prediction.+ *+ * <p>Override only the events you need; the rest are no-ops. A hook may watch a call, rewrite+ * what it is about to ask, or answer it outright with {@link PredictContext#skip}.+ *+ * <pre>{@code+ * final class Tracer implements Hook {+ * @Override public void onPredictEnd(PredictContext ctx) {+ * span.record(ctx.usage().inputTokens(), ctx.elapsedMs());+ * }+ * }+ * agent.hooks().addHook(new Tracer());+ * }</pre>+ *+ * <p>This is ONE type where the reference has two. {@code laya.hooks.Hook} is a structural+ * {@code Protocol} — a hook is anything with at least one of the six methods — and+ * {@code BaseHook} is the concrete no-op class to subclass when you would rather not implement+ * by shape. An interface with default methods is both at once, so there is nothing for a second+ * type to be. The consequence is that the reference's "missing methods are skipped" becomes "the+ * default does nothing", which is the same behaviour from the outside: {@link Hooks#dispatch}+ * calling a default no-op and the reference finding no attribute to call both leave the context+ * untouched and nothing in the log.+ *+ * <p>Nothing here mirrors the reference's {@code AsyncHook}, deliberately. That class exists to+ * solve a problem the JVM does not have: in Python an {@code async def} hook returns a coroutine+ * that only an event loop can finish, so a synchronous caller needs+ * {@code run_coroutine_sync} — and a background loop thread when it is already inside one — to+ * get a value back. A JVM method call is already synchronous, so a hook that wants to do+ * asynchronous work composes it and blocks on the result itself:+ *+ * <pre>{@code+ * @Override public void onPredictEnd(PredictContext ctx) {+ * ship(ctx.results()).toCompletableFuture().join(); // or orTimeout(...), or ignore it+ * }+ * }</pre>+ *+ * <p>Porting {@code AsyncHook} would mean choosing a future type for every caller and owning a+ * thread pool to await it on, to wrap a {@code join} the caller can write in one line and bound+ * however their own runtime wants. Half-porting it — accepting a {@code CompletionStage} and+ * blocking on it with no deadline — would be worse: {@link Hooks.Policy#timeout()} already+ * bounds a slow hook, and a second, invisible wait inside one would make a hook that never+ * returns look like a hook that never started.+ *+ * <p>A hook runs on the calling thread, so it is as thread-safe as the call around it. Install+ * one that is not, and set {@link HookRegistry#concurrent(boolean)} to false to have dispatch+ * serialise it.+ */+public interface Hook {++ /**+ * Before inference, with the states and questions the call was made with.+ *+ * <p>Rewriting {@link PredictContext#states} or {@link PredictContext#questions} changes what+ * is asked; {@link PredictContext#skip} answers the call without the model running at all.+ */+ default void onPredictStart(PredictContext ctx) {+ }++ /**+ * After inference, on the success path and the failure path alike.+ *+ * <p>{@link PredictContext#results} is the answer and may be replaced; on a failure it is+ * null and {@link PredictContext#error} says why.+ */+ default void onPredictEnd(PredictContext ctx) {+ }++ /** After a router has chosen a checkpoint, before it is asked anything. */+ default void onRoute(PredictContext ctx) {+ }++ /** After a checkpoint has been loaded. */+ default void onLoad(PredictContext ctx) {+ }++ /** After a checkpoint has been evicted. */+ default void onEvict(PredictContext ctx) {+ }++ /**+ * When the call failed, before {@link #onPredictEnd}.+ *+ * <p>Throwing from here does not replace the failure that triggered it: see+ * {@link Hooks#around}.+ */+ default void onError(PredictContext ctx) {+ }+}diff --git a/laya-java/laya-java/src/main/java/com/convaiinnovations/laya/hooks/HookCall.java b/laya-java/laya-java/src/main/java/com/convaiinnovations/laya/hooks/HookCall.javanew file mode 100644index 00000000..b290cd99--- /dev/null+++ b/laya-java/laya-java/src/main/java/com/convaiinnovations/laya/hooks/HookCall.java@@ -0,0 +1,91 @@+package com.convaiinnovations.laya.hooks;++import java.time.Duration;+import java.util.ArrayList;+import java.util.List;+import java.util.function.Consumer;++/**+ * The hooks and policy overrides for ONE call, appended after whatever the agent already has.+ *+ * <pre>{@code+ * agent.predictBatch(states, questions, null, 0, false,+ * HookCall.of(Hooks.onPredictStart(ctx -> ctx.maxLen(256)))+ * .raiseErrors(false));+ * }</pre>+ *+ * <p>One type rather than five parameters, because the reference's five — {@code hooks},+ * {@code on_predict_start}, {@code on_predict_end}, {@code hooks_raise} and+ * {@code hooks_timeout} — would otherwise be five overloads of every predicting method, and a+ * caller who wants only the third of them should not have to name the other four.+ *+ * <p>{@code raiseErrors} and {@code timeout} are boxed because null means "do not override, use+ * the agent's", which is a third state a {@code boolean} and a bare {@link Duration} default+ * cannot carry.+ */+public record HookCall(List<Hook> hooks, List<Consumer<PredictContext>> onPredictStart,+ List<Consumer<PredictContext>> onPredictEnd, Boolean raiseErrors,+ Duration timeout) {++ private static final HookCall NONE =+ new HookCall(List.of(), List.of(), List.of(), null, null);++ public HookCall {+ hooks = List.copyOf(hooks);+ onPredictStart = List.copyOf(onPredictStart);+ onPredictEnd = List.copyOf(onPredictEnd);+ timeout = Hooks.validateTimeout(timeout);+ }++ /** No per-call hooks and no overrides: the agent's own configuration, unchanged. */+ public static HookCall none() {+ return NONE;+ }++ /** One hook, for this call only. */+ public static HookCall of(Hook hook) {+ return NONE.andThen(hook);+ }++ /** Several hooks, for this call only, in the given order. */+ public static HookCall of(List<? extends Hook> hooks) {+ return new HookCall(List.copyOf(hooks), List.of(), List.of(), null, null);+ }++ /** This call with one more hook appended. */+ public HookCall andThen(Hook hook) {+ List<Hook> grown = new ArrayList<>(hooks);+ grown.add(hook);+ return new HookCall(grown, onPredictStart, onPredictEnd, raiseErrors, timeout);+ }++ /** This call with one more start callback, which runs after every hook object. */+ public HookCall onStart(Consumer<PredictContext> callback) {+ List<Consumer<PredictContext>> grown = new ArrayList<>(onPredictStart);+ grown.add(callback);+ return new HookCall(hooks, grown, onPredictEnd, raiseErrors, timeout);+ }++ /** This call with one more end callback, which runs after every start callback. */+ public HookCall onEnd(Consumer<PredictContext> callback) {+ List<Consumer<PredictContext>> grown = new ArrayList<>(onPredictEnd);+ grown.add(callback);+ return new HookCall(hooks, onPredictStart, grown, raiseErrors, timeout);+ }++ /** This call overriding the agent's {@code raiseErrors}. */+ public HookCall raiseErrors(boolean value) {+ return new HookCall(hooks, onPredictStart, onPredictEnd, value, timeout);+ }++ /** This call overriding the agent's per-hook timeout. Null means "no override", not "no limit". */+ public HookCall timeout(Duration value) {+ return new HookCall(hooks, onPredictStart, onPredictEnd, raiseErrors, value);+ }++ /** Whether this adds nothing to the agent's own hooks and policy. */+ public boolean isEmpty() {+ return hooks.isEmpty() && onPredictStart.isEmpty() && onPredictEnd.isEmpty()+ && raiseErrors == null && timeout == null;+ }+}diff --git a/laya-java/laya-java/src/main/java/com/convaiinnovations/laya/hooks/HookRegistry.java b/laya-java/laya-java/src/main/java/com/convaiinnovations/laya/hooks/HookRegistry.javanew file mode 100644index 00000000..9ee8519c--- /dev/null+++ b/laya-java/laya-java/src/main/java/com/convaiinnovations/laya/hooks/HookRegistry.java@@ -0,0 +1,204 @@+package com.convaiinnovations.laya.hooks;++import java.time.Duration;+import java.util.ArrayList;+import java.util.List;+import java.util.concurrent.locks.ReentrantLock;++/**+ * The hooks installed on one agent, and what dispatch does with them.+ *+ * <p>A list that can be edited while the agent is alive, so a tracer can be attached to a+ * long-lived agent without rebuilding it. A call takes a SNAPSHOT — {@link Hooks#compose} copies+ * — so adding or removing a hook never disturbs a call already in flight.+ *+ * <p>In the reference this is a mixin that {@code Agent}, {@code Router} and {@code ONNXAgent}+ * inherit. {@link com.convaiinnovations.laya.Agent} is final and already implements two+ * interfaces, and single inheritance makes a mixin the wrong shape here anyway: the registry is+ * reached through {@code agent.hooks()} instead, which also keeps six hook methods off the+ * surface of a class whose subject is prediction.+ */+public final class HookRegistry {++ private final Object mutex = new Object();+ private final ReentrantLock serial = new ReentrantLock();++ private volatile List<Hook> installed = List.of();+ private volatile boolean raiseErrors = true;+ private volatile boolean concurrent = true;+ private volatile Duration timeout;++ /** The installed hooks, in order, as a snapshot. */+ public List<Hook> hooks() {+ return installed;+ }++ /** Installs one hook. Returns this, for chaining. */+ public HookRegistry addHook(Hook hook) {+ return addHooks(List.of(hook));+ }++ /** Installs several hooks, in order. Returns this, for chaining. */+ public HookRegistry addHooks(List<? extends Hook> hooks) {+ List<Hook> normalised = Hooks.normalise(hooks, null, null);+ if (normalised.isEmpty()) {+ return this;+ }+ synchronized (mutex) {+ List<Hook> grown = new ArrayList<>(installed);+ grown.addAll(normalised);+ installed = List.copyOf(grown);+ }+ return this;+ }++ /**+ * Removes a hook by identity, every copy of it.+ *+ * @return whether it was installed at all+ */+ public boolean removeHook(Hook hook) {+ synchronized (mutex) {+ List<Hook> remaining = new ArrayList<>(installed.size());+ for (Hook candidate : installed) {+ if (candidate != hook) {+ remaining.add(candidate);+ }+ }+ if (remaining.size() == installed.size()) {+ return false;+ }+ installed = List.copyOf(remaining);+ return true;+ }+ }++ /**+ * Installs hooks for the duration of a block, then removes them.+ *+ * <pre>{@code+ * try (var ignored = agent.hooks().hooksInstalled(tracer)) {+ * agent.predict(state, questions);+ * }+ * }</pre>+ *+ * <p>A build with {@code -Xlint:try -Werror} needs {@code @SuppressWarnings("try")} on the+ * enclosing method: javac reports an unreferenced resource for every try-with-resources+ * whose value is only a scope, which is what this is.+ */+ public Scope hooksInstalled(Hook... hooks) {+ return hooksInstalled(List.of(hooks));+ }++ /** Installs hooks for the duration of a block, then removes them. */+ public Scope hooksInstalled(List<? extends Hook> hooks) {+ List<Hook> added = Hooks.normalise(hooks, null, null);+ addHooks(added);+ return new Scope(added);+ }++ /** What {@link HookRegistry#hooksInstalled(Hook...)} hands back; closing it removes what it added. */+ public final class Scope implements AutoCloseable {++ private final List<Hook> added;+ private boolean closed;++ private Scope(List<Hook> added) {+ this.added = added;+ }++ /**+ * Removes ONE occurrence of each hook this scope added, the most recent match.+ *+ * <p>Not "every copy by identity", and not "restore a snapshot". Both are wrong, and+ * the reference carries the scars of each. Removing by identity alone took a hook the+ * application had installed before the block along with the block's own, and it stayed+ * gone — while the contract is that a block restores the previous list. Restoring a+ * snapshot is wrong in two other ways: with two overlapping scopes the first exit+ * reinstates its snapshot and so removes the second scope's hook, and a hook added+ * inside the block is discarded because it is not in the snapshot either. Taking one+ * occurrence per hook the scope added leaves everything else in place.+ *+ * <p>The scan runs BACKWARDS, taking the most recent match, because installation+ * appends and a hook that was already there sits earlier than this scope's copy of it.+ * That direction is fidelity to the reference and nothing more: the copies are the same+ * object, so the list left behind is identical either way and no test can tell the two+ * apart. Measured, not assumed — reversing the loop survives the whole suite. What IS+ * observable, and is pinned, is that only ONE copy goes.+ *+ * <p>Idempotent, as {@link AutoCloseable} asks: closing twice would otherwise take a+ * second copy that belongs to someone else.+ */+ @Override+ public void close() {+ synchronized (mutex) {+ if (closed) {+ return;+ }+ closed = true;+ List<Hook> current = new ArrayList<>(installed);+ for (Hook hook : added) {+ for (int at = current.size() - 1; at >= 0; at--) {+ if (current.get(at) == hook) {+ current.remove(at);+ break;+ }+ }+ }+ installed = List.copyOf(current);+ }+ }+ }++ /** Whether a throwing hook fails the call. True by default, as the reference. */+ public boolean raiseErrors() {+ return raiseErrors;+ }++ /** Sets whether a throwing hook fails the call, or is reported and stepped over. */+ public HookRegistry raiseErrors(boolean value) {+ this.raiseErrors = value;+ return this;+ }++ /** Whether hooks may run unguarded. True by default. */+ public boolean concurrent() {+ return concurrent;+ }++ /**+ * Sets whether hooks may run unguarded.+ *+ * <p>False serialises every dispatch on this agent behind one re-entrant lock, for a hook+ * that is not safe to run from two calls at once. It does not make a hook atomic with the+ * inference around it.+ */+ public HookRegistry concurrent(boolean value) {+ this.concurrent = value;+ return this;+ }++ /** The per-hook deadline, or null for no limit. */+ public Duration timeout() {+ return timeout;+ }++ /** Sets the per-hook deadline. Null removes it. */+ public HookRegistry timeout(Duration value) {+ this.timeout = Hooks.validateTimeout(value);+ return this;+ }++ /** The effective hook list for one call: defaults, then these, then the call's own. */+ public List<Hook> composeFor(HookCall call) {+ return Hooks.compose(installed, call);+ }++ /** The effective policy for one call, with the call's overrides applied over this agent's. */+ public Hooks.Policy policyFor(HookCall call) {+ HookCall perCall = call == null ? HookCall.none() : call;+ boolean raising = perCall.raiseErrors() == null ? raiseErrors : perCall.raiseErrors();+ Duration deadline = perCall.timeout() == null ? timeout : perCall.timeout();+ return new Hooks.Policy(raising, concurrent ? null : serial, deadline, Hooks.reporting());+ }+}diff --git a/laya-java/laya-java/src/main/java/com/convaiinnovations/laya/hooks/Hooks.java b/laya-java/laya-java/src/main/java/com/convaiinnovations/laya/hooks/Hooks.javanew file mode 100644index 00000000..68baa981--- /dev/null+++ b/laya-java/laya-java/src/main/java/com/convaiinnovations/laya/hooks/Hooks.java@@ -0,0 +1,566 @@+package com.convaiinnovations.laya.hooks;++import com.convaiinnovations.laya.Prediction;+import com.convaiinnovations.laya.Question;+import java.time.Duration;+import java.util.ArrayList;+import java.util.List;+import java.util.Map;+import java.util.concurrent.locks.Lock;+import java.util.function.Consumer;++/**+ * Composing, dispatching and bounding hooks — the parts of {@code laya.hooks} that are not a type.+ *+ * <p>Three things here are contracts rather than implementation details, and each is pinned by+ * {@code fixtures/hooks.json}:+ *+ * <ul>+ * <li><b>Order.</b> {@link #compose} is process-wide defaults, then the hooks installed on the+ * agent, then the per-call ones; {@link #dispatch} calls them in that order. A port that+ * composes the other way round still runs every hook and fails nothing — except that the+ * tracer a caller installed to watch what their per-call hook did now runs first and sees+ * nothing.</li>+ * <li><b>{@link PredictContext#skip} does not stop the chain.</b> It assigns the results; it is+ * {@link #around} reading them afterwards that skips inference. Every later start hook+ * still runs, and can overwrite the answer.</li>+ * <li><b>{@link Policy#raiseErrors}.</b> True fails the request at the first throwing hook and+ * the rest of the chain never runs. False reports and continues, which is what a telemetry+ * hook needs — it must not be able to fail a request.</li>+ * </ul>+ */+public final class Hooks {++ private static final System.Logger LOG =+ System.getLogger(Hooks.class.getPackage().getName());++ private static final Object DEFAULTS_MUTEX = new Object();+ private static List<Hook> defaults = List.of();+ private static final ThreadLocal<Boolean> SKIP_DEFAULTS = ThreadLocal.withInitial(() -> false);++ private Hooks() {+ }++ /**+ * The six lifecycle events, in the reference's own order.+ *+ * <p>The order is data, not presentation: {@code HOOK_EVENTS} is what the reference's+ * refusal messages enumerate, and a port that reorders it describes a different API.+ */+ public enum Event {+ /** Before inference. */+ PREDICT_START("on_predict_start"),+ /** After inference, success or failure. */+ PREDICT_END("on_predict_end"),+ /** After a router chose a checkpoint. */+ ROUTE("on_route"),+ /** After a checkpoint was loaded. */+ LOAD("on_load"),+ /** After a checkpoint was evicted. */+ EVICT("on_evict"),+ /** When the call failed, before {@link #PREDICT_END}. */+ ERROR("on_error");++ private final String wireName;++ Event(String wireName) {+ this.wireName = wireName;+ }++ /** The name the reference calls this event, which is what a cross-language caller reads. */+ public String wireName() {+ return wireName;+ }++ void callOn(Hook hook, PredictContext ctx) {+ switch (this) {+ case PREDICT_START -> hook.onPredictStart(ctx);+ case PREDICT_END -> hook.onPredictEnd(ctx);+ case ROUTE -> hook.onRoute(ctx);+ case LOAD -> hook.onLoad(ctx);+ case EVICT -> hook.onEvict(ctx);+ case ERROR -> hook.onError(ctx);+ }+ }+ }++ /**+ * One call's totalled token usage, as a hook sees it.+ *+ * <p>Not {@link com.convaiinnovations.laya.Usage}: that describes ONE state, including what+ * its budget dropped and which question was blamed. This is the sum over the call, which is+ * the only number a hook can report without re-deriving per-state attribution the reference+ * does not give it either.+ */+ public record Totals(int inputTokens, int outputTokens) {+ }++ /**+ * What dispatch does with a hook that throws, one that overruns, and one that is not+ * re-entrant.+ *+ * @param raiseErrors true fails the call at the first throwing hook; false reports through+ * {@code onFailure} and runs the rest of the chain+ * @param lock held across each hook call, for hooks that are not safe to run+ * concurrently, or null to run them unguarded+ * @param timeout bounds EACH hook call, or null for no limit. A hook that overruns+ * raises — see {@link #dispatch} for what that does and does not protect+ * @param onFailure where a swallowed failure is reported when {@code raiseErrors} is+ * false. Never null; {@link #reporting()} is the default and logs at WARNING+ */+ public record Policy(boolean raiseErrors, Lock lock, Duration timeout,+ Consumer<String> onFailure) {++ public Policy {+ timeout = validateTimeout(timeout);+ if (onFailure == null) {+ throw new IllegalArgumentException(+ "a policy needs somewhere to report a swallowed hook failure; pass "+ + "Hooks.reporting() for the default");+ }+ }++ /** Fail the call on a throwing hook, no lock, no timeout. The reference's defaults. */+ public static Policy raising() {+ return new Policy(true, null, null, reporting());+ }++ /** This policy with {@code raiseErrors} replaced. */+ public Policy raiseErrors(boolean value) {+ return new Policy(value, lock, timeout, onFailure);+ }++ /** This policy with the serialising lock replaced. */+ public Policy lock(Lock value) {+ return new Policy(raiseErrors, value, timeout, onFailure);+ }++ /** This policy with the per-hook timeout replaced. */+ public Policy timeout(Duration value) {+ return new Policy(raiseErrors, lock, value, onFailure);+ }++ /** This policy reporting swallowed failures somewhere else — a test, or a metric. */+ public Policy onFailure(Consumer<String> value) {+ return new Policy(raiseErrors, lock, timeout, value);+ }+ }++ /** The default failure sink: one WARNING line per swallowed hook failure. */+ public static Consumer<String> reporting() {+ return message -> LOG.log(System.Logger.Level.WARNING, message);+ }++ /** What inference {@link #around} runs when no hook has answered the call. */+ @FunctionalInterface+ public interface Inference {++ /**+ * Answers the call.+ *+ * @param states the states the start hooks left on the context, never empty+ * @param questions the questions they left, never empty of meaning+ * @param maxLen a per-call token budget, or null for the checkpoint's own+ * @param headMaxLen a per-call head budget, or null for the checkpoint's own+ */+ List<Prediction> run(List<Object> states, Map<String, Question> questions,+ Integer maxLen, Integer headMaxLen);+ }++ /**+ * Wraps a hook object around a plain {@code onPredictStart} callback.+ *+ * <p>{@link Hook} has six methods, so it is not a functional interface and a lambda cannot+ * be one. This is the reference's {@code on_predict_start=} parameter: the common case is a+ * caller who wants one event, and making them write an anonymous class for it is the kind of+ * friction that stops a tracer being added at all.+ */+ public static Hook onPredictStart(Consumer<PredictContext> callback) {+ requireCallback(callback, "onPredictStart");+ return new Hook() {+ @Override+ public void onPredictStart(PredictContext ctx) {+ callback.accept(ctx);+ }++ @Override+ public String toString() {+ return "onPredictStart(" + callback + ")";+ }+ };+ }++ /** Wraps a hook object around a plain {@code onPredictEnd} callback. */+ public static Hook onPredictEnd(Consumer<PredictContext> callback) {+ requireCallback(callback, "onPredictEnd");+ return new Hook() {+ @Override+ public void onPredictEnd(PredictContext ctx) {+ callback.accept(ctx);+ }++ @Override+ public String toString() {+ return "onPredictEnd(" + callback + ")";+ }+ };+ }++ private static void requireCallback(Consumer<PredictContext> callback, String name) {+ if (callback == null) {+ throw new IllegalArgumentException(name + " must not be null");+ }+ }++ /**+ * One ordered list from a hook list and the two convenience callbacks.+ *+ * <p>Hooks first, in their own order, then the start callbacks, then the end callbacks —+ * so a {@code onPredictEnd} callback never runs before a hook object's own end method.+ *+ * <p>Three of the reference's refusals have no counterpart here and are not omissions: a+ * class rather than an instance, an object implementing none of the six events, and an+ * event attribute that is not callable are all unrepresentable once {@link Hook} is a type.+ * The fixture records them anyway, so that a reference that stopped refusing them would be+ * caught rather than quietly leaving this paragraph wrong. A null entry IS representable,+ * and is refused here.+ */+ public static List<Hook> normalise(List<? extends Hook> hooks,+ List<? extends Consumer<PredictContext>> onPredictStart,+ List<? extends Consumer<PredictContext>> onPredictEnd) {+ List<Hook> out = new ArrayList<>();+ if (hooks != null) {+ for (Hook hook : hooks) {+ if (hook == null) {+ throw new IllegalArgumentException("a hooks entry must not be null");+ }+ out.add(hook);+ }+ }+ if (onPredictStart != null) {+ for (Consumer<PredictContext> callback : onPredictStart) {+ out.add(onPredictStart(callback));+ }+ }+ if (onPredictEnd != null) {+ for (Consumer<PredictContext> callback : onPredictEnd) {+ out.add(onPredictEnd(callback));+ }+ }+ return List.copyOf(out);+ }++ /**+ * The effective hook list for one call: defaults, then installed, then per-call.+ *+ * <p>The defaults are read HERE, at call time rather than at construction, so a hook set+ * after an agent was built still applies to it.+ */+ public static List<Hook> compose(List<? extends Hook> installed, HookCall call) {+ HookCall perCall = call == null ? HookCall.none() : call;+ List<Hook> out = new ArrayList<>(SKIP_DEFAULTS.get() ? List.of() : defaultHooks());+ if (installed != null) {+ out.addAll(installed);+ }+ out.addAll(normalise(perCall.hooks(), perCall.onPredictStart(), perCall.onPredictEnd()));+ return List.copyOf(out);+ }++ /**+ * The process-wide hooks, in order. Empty unless {@link #setDefaultHooks} was called.+ *+ * <p>A mutable COPY, as the reference returns: editing it is editing a list of your own, not+ * the process-wide one. {@link #withoutDefaultHooks} does not affect this — it suppresses the+ * defaults for a call, and a read that lied about what is installed would make a scope+ * impossible to debug from inside.+ */+ public static List<Hook> defaultHooks() {+ synchronized (DEFAULTS_MUTEX) {+ return new ArrayList<>(defaults);+ }+ }++ /**+ * Replaces the process-wide default hooks.+ *+ * <p>Defaults run before installed and per-call hooks for every agent in the process, so a+ * tracer or a metrics hook does not have to be threaded through every construction.+ */+ public static void setDefaultHooks(List<? extends Hook> hooks) {+ List<Hook> normalised = normalise(hooks, null, null);+ synchronized (DEFAULTS_MUTEX) {+ defaults = normalised;+ }+ }++ /** Appends one hook to the process-wide defaults. */+ public static void addDefaultHook(Hook hook) {+ List<Hook> normalised = normalise(List.of(hook), null, null);+ synchronized (DEFAULTS_MUTEX) {+ List<Hook> grown = new ArrayList<>(defaults);+ grown.addAll(normalised);+ defaults = List.copyOf(grown);+ }+ }++ /** Removes every process-wide default hook. */+ public static void clearDefaultHooks() {+ synchronized (DEFAULTS_MUTEX) {+ defaults = List.of();+ }+ }++ /**+ * Switches the process-wide defaults off for this thread, until the scope is closed.+ *+ * <pre>{@code+ * try (var ignored = Hooks.withoutDefaultHooks()) {+ * agent.predict(state, questions); // installed and per-call hooks only+ * }+ * }</pre>+ *+ * <p>Javac's {@code -Xlint:try} reports an unreferenced resource, so a build with+ * {@code -Werror} needs {@code @SuppressWarnings("try")} on the enclosing method. That is a+ * known javac wart about the idiom, not about this method.+ *+ * <p>This is the reference's {@code _SKIP_DEFAULTS}, which a router enters so that a scan+ * made of many internal predictions fires a process-wide hook once for the scan rather than+ * once per forward pass. There it is a {@code contextvars.ContextVar} and here it is a+ * {@link ThreadLocal}, and the difference is real: a {@code ContextVar} is copied into an+ * asyncio task, while a {@code ThreadLocal} is not inherited by a thread the scope starts.+ * Work handed to another thread inside the scope therefore sees the defaults again. Nothing+ * in this port dispatches hooks off the calling thread, so there is nowhere for that to bite+ * today — it is written down because the first code that does will be surprised otherwise.+ */+ public static DefaultsScope withoutDefaultHooks() {+ boolean previous = SKIP_DEFAULTS.get();+ SKIP_DEFAULTS.set(true);+ return () -> SKIP_DEFAULTS.set(previous);+ }++ /**+ * What {@link #withoutDefaultHooks} hands back.+ *+ * <p>Its own type rather than {@link AutoCloseable} so that {@code close} declares no+ * checked exception: restoring a thread-local cannot fail, and a {@code throws Exception}+ * on the resource would push a {@code catch} into every caller for a failure that does not+ * exist.+ */+ @FunctionalInterface+ public interface DefaultsScope extends AutoCloseable {+ @Override+ void close();+ }++ /**+ * Returns a positive timeout, or null for no limit.+ *+ * <p>A non-positive timeout is refused here rather than left to the wait: a zero or negative+ * deadline returns before the hook has started, so the outcome of a fast hook under one is a+ * race. The reference also refuses a NaN and an infinity, which a {@link Duration} cannot+ * hold — those two refusals are unreachable here rather than unimplemented.+ */+ public static Duration validateTimeout(Duration value) {+ if (value == null) {+ return null;+ }+ if (value.isZero() || value.isNegative()) {+ throw new IllegalArgumentException(+ "a hook timeout must be a positive duration or null; got " + value);+ }+ return value;+ }++ /**+ * Sums the per-state usage so a hook sees one total for the call.+ *+ * <p>The reference coerces as it goes — a missing usage block, a null one, a missing key, a+ * null value and a float all become an int — because a result there is a plain dict a hook+ * may have rewritten. Here a {@link Prediction} carries a {@link com.convaiinnovations.laya.Usage}+ * whose fields are primitive ints, so every one of those coercions is unreachable. They are+ * still pinned by the fixture, which records what each degenerate shape totals to, because+ * the Java side has to produce the same number from the representable equivalent.+ */+ public static Totals aggregateUsage(List<Prediction> results) {+ int input = 0;+ int output = 0;+ for (Prediction result : results) {+ input += result.usage().inputTokens();+ output += result.usage().outputTokens();+ }+ return new Totals(input, output);+ }++ /**+ * Calls {@code event} on every hook, in order.+ *+ * <p>{@code policy.raiseErrors()} false reports through {@link Policy#onFailure} and+ * continues. {@code policy.lock()} serialises dispatch for hooks that are not re-entrant.+ * {@code policy.timeout()} bounds each hook call: an overrunning hook raises, or reports+ * when {@code raiseErrors} is false.+ *+ * <p>A timed-out hook KEEPS RUNNING. Neither Java nor Python can interrupt a thread that+ * will not cooperate, so the deadline protects the request and not the process — a hook that+ * blocks forever leaks a thread per call. That is the reference's behaviour too, and it is+ * the reason the timeout is opt-in.+ *+ * <p>{@code raiseErrors} governs a {@link RuntimeException} and nothing else. An+ * {@link Error} is rethrown whatever the policy says, which is the reference's rule in Java+ * terms: it catches {@code Exception} and deliberately not {@code BaseException}, so a+ * {@code KeyboardInterrupt} or a {@code SystemExit} is never swallowed by a telemetry hook.+ * An {@link OutOfMemoryError} reported as a line of text and then carried on from is the+ * same mistake.+ */+ public static void dispatch(List<? extends Hook> hooks, Event event, PredictContext ctx,+ Policy policy) {+ for (Hook hook : hooks) {+ try {+ if (policy.lock() == null) {+ call(hook, event, ctx, policy.timeout());+ } else {+ policy.lock().lock();+ try {+ call(hook, event, ctx, policy.timeout());+ } finally {+ policy.lock().unlock();+ }+ }+ } catch (RuntimeException problem) {+ if (policy.raiseErrors()) {+ throw problem;+ }+ policy.onFailure().accept(String.format("laya: hook %s.%s failed: %s",+ hook.getClass().getSimpleName(), event.wireName(), problem.getMessage()));+ }+ }+ }++ private static void call(Hook hook, Event event, PredictContext ctx, Duration timeout) {+ if (timeout == null) {+ event.callOn(hook, ctx);+ return;+ }+ Throwable[] box = new Throwable[1];+ Thread runner = new Thread(() -> {+ try {+ event.callOn(hook, ctx);+ } catch (RuntimeException | Error problem) {+ box[0] = problem;+ }+ }, "laya-hook-timeout");+ runner.setDaemon(true);+ runner.start();+ try {+ runner.join(timeout.toMillis(), timeout.toNanosPart() % 1_000_000);+ } catch (InterruptedException interrupted) {+ Thread.currentThread().interrupt();+ throw new IllegalStateException("interrupted while waiting for hook "+ + hook.getClass().getSimpleName() + "." + event.wireName(), interrupted);+ }+ if (runner.isAlive()) {+ // Seconds, not `Duration.toString`'s "PT0.05S". The reference names the hook as+ // `<class>.<method>` and the deadline in seconds, and a caller grepping their logs+ // across the two runtimes should find the same line.+ throw new HookTimeoutException(String.format("laya: hook %s.%s exceeded %ss",+ hook.getClass().getSimpleName(), event.wireName(),+ timeout.toNanos() / 1e9));+ }+ if (box[0] instanceof RuntimeException problem) {+ throw problem;+ }+ if (box[0] instanceof Error problem) {+ throw problem;+ }+ }++ /** A hook that outran {@link Policy#timeout}. Unchecked, so the usual policy governs it. */+ public static final class HookTimeoutException extends RuntimeException {++ private static final long serialVersionUID = 1L;++ HookTimeoutException(String message) {+ super(message);+ }+ }++ /**+ * Runs one call with its hooks around it: start, inference or a hook's answer, then error and+ * end.+ *+ * <p>Extracted rather than written inline in {@code Agent}, because the sequence below is the+ * whole observable contract of a hooked call and it is the same for anything that answers+ * questions. Keeping it in one place is also what lets it be tested against the reference+ * with a stub inference, which is how the fixture records it: whether the model ran at all is+ * then an observable rather than something inferred from the payload.+ *+ * <p>What happens, in order:+ *+ * <ol>+ * <li>{@link Event#PREDICT_START} over every hook.</li>+ * <li>If no hook assigned results, inference runs over whatever the hooks left on the+ * context — the states, the questions and the two budget overrides. An EMPTY state list+ * answers with an empty list without reaching inference, since there is nothing to+ * collate.</li>+ * <li>On a failure, {@link Event#ERROR} runs with the failure on the context. A hook that+ * throws here is ATTACHED to the real failure as a suppressed exception, never+ * substituted for it: the thing that broke the request must be what the caller+ * catches.</li>+ * <li>{@link Event#PREDICT_END} runs either way, after {@code elapsedMs} and — when there+ * are results — the totalled {@code usage} are on the context. A hook that throws here+ * fails the call if nothing else had, and is attached to the existing failure if+ * something had.</li>+ * </ol>+ *+ * <p>The last two steps are written out rather than put in a {@code finally} block, and that+ * is not style: a Java {@code finally} that throws REPLACES the pending exception, which is+ * precisely the masking the reference goes out of its way to prevent.+ *+ * @return the results on the context, which is the hooks' last word on the call+ */+ public static List<Prediction> around(List<? extends Hook> hooks, PredictContext ctx,+ Policy policy, Inference inference) {+ Throwable raised = null;+ try {+ dispatch(hooks, Event.PREDICT_START, ctx, policy);+ if (ctx.results() == null) {+ if (ctx.states().isEmpty()) {+ ctx.results(List.of());+ } else {+ ctx.results(inference.run(ctx.states(), ctx.questions(), ctx.maxLen(),+ ctx.headMaxLen()));+ }+ }+ } catch (RuntimeException | Error problem) {+ raised = problem;+ ctx.error(problem);+ try {+ dispatch(hooks, Event.ERROR, ctx, policy);+ } catch (RuntimeException | Error hookFailure) {+ // Attached, never substituted: the thing that broke the request is what the+ // caller has to catch, and a failing observer must not be able to hide it.+ problem.addSuppressed(hookFailure);+ }+ }++ ctx.elapsedMs((System.nanoTime() - ctx.startedAt()) / 1_000_000.0);+ if (ctx.results() != null) {+ ctx.usage(aggregateUsage(ctx.results()));+ }+ try {+ dispatch(hooks, Event.PREDICT_END, ctx, policy);+ } catch (RuntimeException | Error hookFailure) {+ if (raised == null) {+ throw hookFailure;+ }+ raised.addSuppressed(hookFailure);+ }++ if (raised instanceof RuntimeException problem) {+ throw problem;+ }+ if (raised instanceof Error problem) {+ throw problem;+ }+ return ctx.results();+ }+}diff --git a/laya-java/laya-java/src/main/java/com/convaiinnovations/laya/hooks/PredictContext.java b/laya-java/laya-java/src/main/java/com/convaiinnovations/laya/hooks/PredictContext.javanew file mode 100644index 00000000..404657ca--- /dev/null+++ b/laya-java/laya-java/src/main/java/com/convaiinnovations/laya/hooks/PredictContext.java@@ -0,0 +1,217 @@+package com.convaiinnovations.laya.hooks;++import com.convaiinnovations.laya.Prediction;+import com.convaiinnovations.laya.Predictor;+import com.convaiinnovations.laya.Question;+import java.util.ArrayList;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;+import java.util.UUID;++/**+ * One call, as every hook of that call sees it — and as a hook may change it.+ *+ * <p>Mutable, which nothing else in this port is. That is the point: a hook that could only read+ * would be a logger, and the reference's contract is that a start hook may rewrite the states,+ * the questions and the token budget, and that an end hook may rewrite the results. A record+ * cannot express any of that.+ *+ * <p>One context exists per call and is shared by every event of it, so {@link #runId} is what+ * lets a tracer pair a start with its end without threading state of its own. Identity is+ * identity: the reference declares {@code eq=False} so two contexts are never equal and one can+ * sit in a set keyed by the call rather than by its contents, which is what a Java object does+ * by default — so there is no {@code equals} or {@code hashCode} here, on purpose.+ *+ * <p>Not thread-safe, and not meant to be: hooks run on the calling thread, in order.+ *+ * <p>Two of the reference's fields are absent. {@code router} and {@code decision} carry a+ * {@code RouteDecision} to an {@code on_route} hook, and nothing in this port dispatches that+ * event yet — {@link com.convaiinnovations.laya.Router} does its own selection without hooks. A+ * field that is always null is not a port of a field, it is a promise the caller cannot tell+ * from a bug. What the reference splits across {@code agent} and {@code router} is one field+ * here, {@link #predictor}, because both are a {@link Predictor}.+ */+public final class PredictContext {++ private final String runId = UUID.randomUUID().toString().replace("-", "");+ private final long startedAt = System.nanoTime();+ private final String model;+ private final Predictor predictor;++ private List<Object> states;+ private Map<String, Question> questions;+ private List<Prediction> results;+ private Integer maxLen;+ private Integer headMaxLen;+ private Hooks.Totals usage;+ private Double elapsedMs;+ private Throwable error;++ /**+ * A context for one call.+ *+ * @param model the resolved checkpoint name, or null when the caller named none+ * @param predictor the agent or router answering this call, or null+ * @param maxLen a per-call token budget, or null for the checkpoint's own+ * @param headMaxLen a per-call head budget, or null for the checkpoint's own+ */+ public PredictContext(List<?> states, Map<String, Question> questions, String model,+ Predictor predictor, Integer maxLen, Integer headMaxLen) {+ this.states = new ArrayList<>(states);+ this.questions = new LinkedHashMap<>(questions);+ this.model = model;+ this.predictor = predictor;+ this.maxLen = maxLen;+ this.headMaxLen = headMaxLen;+ }++ /** A context with no budget overrides. */+ public PredictContext(List<?> states, Map<String, Question> questions, String model,+ Predictor predictor) {+ this(states, questions, model, predictor, null, null);+ }++ /** Shared by every hook of one call, 32 hex characters, as the reference's {@code uuid4().hex}. */+ public String runId() {+ return runId;+ }++ /** The resolved checkpoint name, or null. */+ public String model() {+ return model;+ }++ /** The agent or router answering this call, or null. */+ public Predictor predictor() {+ return predictor;+ }++ /** The states this call will be answered over. */+ public List<Object> states() {+ return states;+ }++ /** Replaces the states. Inference is handed what the LAST start hook left here. */+ public void states(List<?> replacement) {+ this.states = new ArrayList<>(replacement);+ }++ /** The questions this call will ask. */+ public Map<String, Question> questions() {+ return questions;+ }++ /** Replaces the questions, keeping the given iteration order — a choice's options are positional. */+ public void questions(Map<String, Question> replacement) {+ this.questions = new LinkedHashMap<>(replacement);+ }++ /**+ * The answers, or null when the model has not run.+ *+ * <p>Null and empty are different states of a call: "inference has not happened" against+ * "inference returned nothing". A start hook reads this to tell whether an earlier hook has+ * already answered, and {@link Hooks#around} reads it to decide whether to run the model at+ * all, so collapsing the two would make an empty batch skip inference forever.+ */+ public List<Prediction> results() {+ return results;+ }++ /** Replaces the results. From an end hook this is what the caller receives. */+ public void results(List<Prediction> replacement) {+ this.results = replacement;+ }++ /** A per-call token budget, or null for the checkpoint's own. */+ public Integer maxLen() {+ return maxLen;+ }++ /** Overrides the token budget for this call. */+ public void maxLen(Integer replacement) {+ this.maxLen = replacement;+ }++ /** A per-call head budget, or null for the checkpoint's own. */+ public Integer headMaxLen() {+ return headMaxLen;+ }++ /** Overrides the head budget for this call. */+ public void headMaxLen(Integer replacement) {+ this.headMaxLen = replacement;+ }++ /** The call's totalled usage, set before the end hooks run, or null when it failed. */+ public Hooks.Totals usage() {+ return usage;+ }++ /** Set by {@link Hooks#around} once the results are known. */+ void usage(Hooks.Totals totals) {+ this.usage = totals;+ }++ /** Wall time for the whole call, set before the end hooks run. */+ public Double elapsedMs() {+ return elapsedMs;+ }++ /** {@link System#nanoTime} at construction, for a hook measuring its own slice of the call. */+ public long startedAt() {+ return startedAt;+ }++ /** Set by {@link Hooks#around} once the call is over, failed or not. */+ void elapsedMs(double value) {+ this.elapsedMs = value;+ }++ /** What the call failed with, or null. Set before the error and end hooks run. */+ public Throwable error() {+ return error;+ }++ /** Set by {@link Hooks#around} before the error hooks run. */+ void error(Throwable failure) {+ this.error = failure;+ }++ /**+ * Answers the call from a start hook: inference is skipped and the end hooks still run.+ *+ * <p>{@code results} replaces the WHOLE call, so it carries one entry per state in+ * {@link #states}, in that order — the shape {@code predictBatch} returns. A hook fires once+ * per call and a call can carry many states. The one other accepted shape is a single entry+ * for the whole call.+ *+ * <p>The count is checked HERE, against that contract, so a wrong one fails inside the hook+ * under the caller's own {@link Hooks.Policy#raiseErrors} rather than downstream. In the+ * reference, downstream was where it surfaced: a router indexed {@code results[0]} of an+ * empty list, which the server mapped to a 500, and a batch returned a shorter list than it+ * was given states — quietly dropping rows the caller was about to zip against.+ *+ * <p>Zero results for zero states is accepted, because zero is both "one per state" and+ * "nothing", and an empty call has nothing to answer.+ *+ * @throws IllegalArgumentException when the count is neither 1 nor one per state+ */+ public void skip(List<Prediction> results) {+ if (results.size() != 1 && results.size() != states.size()) {+ throw new IllegalArgumentException(String.format(+ "ctx.skip() takes one result for the whole call or one per state in "+ + "ctx.states (%d); got %d", states.size(), results.size()));+ }+ this.results = results;+ }++ @Override+ public String toString() {+ return "PredictContext[runId=" + runId + ", states=" + states.size()+ + ", questions=" + questions.size()+ + ", results=" + (results == null ? "none" : String.valueOf(results.size()))+ + ", model=" + model + "]";+ }+}diff --git a/laya-java/laya-java/src/test/java/com/convaiinnovations/laya/AgentHooksTest.java b/laya-java/laya-java/src/test/java/com/convaiinnovations/laya/AgentHooksTest.javanew file mode 100644index 00000000..6b291c7c--- /dev/null+++ b/laya-java/laya-java/src/test/java/com/convaiinnovations/laya/AgentHooksTest.java@@ -0,0 +1,256 @@+package com.convaiinnovations.laya;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertNotNull;+import static org.junit.jupiter.api.Assertions.assertSame;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;++import com.convaiinnovations.laya.hooks.Hook;+import com.convaiinnovations.laya.hooks.HookCall;+import com.convaiinnovations.laya.hooks.HookRegistry;+import com.convaiinnovations.laya.hooks.Hooks;+import com.convaiinnovations.laya.hooks.PredictContext;+import java.io.IOException;+import java.nio.file.Path;+import java.util.ArrayList;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;+import org.junit.jupiter.api.AfterEach;+import org.junit.jupiter.api.DisplayName;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.io.TempDir;++/**+ * Hooks as an {@link Agent} actually runs them, over a synthetic checkpoint.+ *+ * <p>{@link HooksTest} pins the hook model itself against the reference, driving+ * {@link Hooks#around} with a stub inference — which is what lets "the model did not run" be an+ * observable. This covers the other half: that {@code Agent} is wired to that model at all, and+ * that a hook's edits reach the tokenizer rather than being recorded and dropped. None of it can+ * come from the fixture, because the reference's inference is a different implementation.+ *+ * <p>The sharpest test here is the last one. {@link Agent#predictLong} deliberately runs NO+ * hooks — not per-call, not installed, not process-wide — because the reference's+ * {@code predict_long} only survives contact with them by way of a start probe, a post-chain+ * budget check and two separate "a hook answered the document" paths, none of which this port+ * has. A silent regression there would be a hook firing once per WINDOW instead of once per+ * document, with a scan whose windows were sized before the hook could change anything.+ */+final class AgentHooksTest {++ private static Map<String, Question> twoQuestions() {+ Map<String, Question> questions = new LinkedHashMap<>();+ questions.put("intent", Question.choice("What next?",+ TinyCheckpoint.ordered("refund", "money back", "escalate", "a human")));+ questions.put("urgent", Question.noul("Needs a human."));+ return questions;+ }++ @AfterEach+ void noDefaultsLeakIntoTheNextTest() {+ Hooks.clearDefaultHooks();+ }++ /** Records every context it is handed, so a test can read what a hook actually saw. */+ private static final class Watcher implements Hook {++ final List<String> events = new ArrayList<>();+ PredictContext start;+ PredictContext end;++ @Override+ public void onPredictStart(PredictContext ctx) {+ events.add("start");+ start = ctx;+ }++ @Override+ public void onPredictEnd(PredictContext ctx) {+ events.add("end");+ end = ctx;+ }+ }++ @Test+ @DisplayName("a start hook sees the agent's own states, questions and checkpoint name")+ void aStartHookSeesTheCall(@TempDir Path root) throws IOException {+ TinyCheckpoint.write(root, 128, 48);+ try (TinyCheckpoint.RecordingSession session = new TinyCheckpoint.RecordingSession();+ Agent agent = Agent.using(+ com.convaiinnovations.laya.tokenizer.Tokenizer.fromModelDirectory(root),+ com.convaiinnovations.laya.config.AgentConfig.fromModelDirectory(root),+ session, "tiny")) {+ Watcher watcher = new Watcher();+ agent.hooks().addHook(watcher);+ agent.predictBatch(List.of("alpha", "beta"), twoQuestions());++ assertEquals(List.of("start", "end"), watcher.events);+ assertEquals(List.of("alpha", "beta"), watcher.start.states());+ assertEquals(List.of("intent", "urgent"),+ new ArrayList<>(watcher.start.questions().keySet()));+ assertEquals("tiny", watcher.start.model());+ assertSame(agent, watcher.start.predictor());+ assertSame(watcher.start, watcher.end, "one context per call, not one per event");+ assertNotNull(watcher.end.usage());+ assertEquals(2, watcher.end.results().size());+ assertTrue(watcher.end.elapsedMs() >= 0.0);+ }+ }++ @Test+ @DisplayName("ctx.skip answers the call without the graph running at all")+ void skipShortCircuitsInference(@TempDir Path root) throws IOException {+ TinyCheckpoint.write(root, 128, 48);+ Prediction cached = new Prediction(Prediction.MODEL, Map.of(),+ new Usage(7, 0, 7, 0, false, List.of(), Map.of()));+ try (TinyCheckpoint.RecordingSession session = new TinyCheckpoint.RecordingSession();+ Agent agent = TinyCheckpoint.agent(root, session)) {+ List<Prediction> got = agent.predictBatch(List.of("alpha"), twoQuestions(), null, 0,+ false, HookCall.of(Hooks.onPredictStart(ctx -> ctx.skip(List.of(cached)))));++ assertEquals(List.of(cached), got, "the hook's payload, not the model's");+ assertTrue(session.batches.isEmpty(),+ "the graph ran anyway, so skip is recorded rather than honoured");+ }+ }++ @Test+ @DisplayName("a start hook's token budget reaches the tokenizer, not just the context")+ void aBudgetOverrideReachesTheSequenceBuilder(@TempDir Path root) throws IOException {+ TinyCheckpoint.write(root, 256, 48);+ String state = "x".repeat(400);+ Map<String, Question> questions = Map.of("urgent", Question.noul("Needs a human."));+ try (TinyCheckpoint.RecordingSession session = new TinyCheckpoint.RecordingSession();+ Agent agent = TinyCheckpoint.agent(root, session)) {+ Usage wide = agent.predict(state, questions).usage();+ Usage narrow = agent.predictBatch(List.of(state), questions, null, 0, false,+ HookCall.of(Hooks.onPredictStart(ctx -> ctx.maxLen(96))))+ .get(0).usage();++ assertTrue(narrow.stateTokensDropped() > wide.stateTokensDropped(),+ "a smaller budget must drop more of the state: " + wide + " vs " + narrow);+ assertEquals(wide.stateTokens(), narrow.stateTokens(),+ "the state itself did not change, only the room for it");++ // The head budget is the OTHER half of the same arithmetic: spending more of+ // max_len on the question leaves less for the state. Asserted separately because a+ // port that threads one override and drops the other passes the check above.+ Usage wideHead = agent.predictBatch(List.of(state), questions, null, 0, false,+ HookCall.of(Hooks.onPredictStart(ctx -> ctx.headMaxLen(200))))+ .get(0).usage();+ assertTrue(wideHead.stateTokensDropped() > wide.stateTokensDropped(),+ "a bigger head budget must leave less room for the state: " + wide + " vs "+ + wideHead);+ }+ }++ @Test+ @DisplayName("an end hook replaces what the caller receives")+ void anEndHookRewritesTheResults(@TempDir Path root) throws IOException {+ TinyCheckpoint.write(root, 128, 48);+ Prediction replacement = new Prediction(Prediction.MODEL, Map.of(),+ new Usage(1, 0, 1, 0, false, List.of(), Map.of()));+ try (TinyCheckpoint.RecordingSession session = new TinyCheckpoint.RecordingSession();+ Agent agent = TinyCheckpoint.agent(root, session)) {+ List<Prediction> got = agent.predictBatch(List.of("alpha"), twoQuestions(), null, 0,+ false,+ HookCall.of(Hooks.onPredictEnd(ctx -> ctx.results(List.of(replacement)))));++ assertEquals(List.of(replacement), got);+ assertFalse(session.batches.isEmpty(), "inference still ran; only the answer changed");+ }+ }++ @Test+ @DisplayName("predict runs the chain too, and a failing hook fails the call")+ void predictIsHookedAndRespectsThePolicy(@TempDir Path root) throws IOException {+ TinyCheckpoint.write(root, 128, 48);+ try (TinyCheckpoint.RecordingSession session = new TinyCheckpoint.RecordingSession();+ Agent agent = TinyCheckpoint.agent(root, session)) {+ Watcher watcher = new Watcher();+ agent.hooks().addHook(watcher);+ agent.predict("alpha", twoQuestions());+ assertEquals(List.of("start", "end"), watcher.events,+ "a single-state predict is a batch of one, hooks and all");++ agent.hooks().addHook(new Hook() {+ @Override+ public void onPredictStart(PredictContext ctx) {+ throw new IllegalStateException("no");+ }+ });+ assertThrows(IllegalStateException.class, () -> agent.predict("beta", twoQuestions()));++ agent.hooks().raiseErrors(false);+ assertNotNull(agent.predict("gamma", twoQuestions()),+ "with raiseErrors off a broken hook must not be able to fail a request");+ }+ }++ @Test+ @DisplayName("a scoped hook is installed for the block and gone after it")+ @SuppressWarnings("try") // javac reports the unreferenced scope; see hooksInstalled+ void scopedHooks(@TempDir Path root) throws IOException {+ TinyCheckpoint.write(root, 128, 48);+ try (TinyCheckpoint.RecordingSession session = new TinyCheckpoint.RecordingSession();+ Agent agent = TinyCheckpoint.agent(root, session)) {+ Watcher watcher = new Watcher();+ try (HookRegistry.Scope ignored = agent.hooks().hooksInstalled(watcher)) {+ agent.predict("alpha", twoQuestions());+ }+ agent.predict("beta", twoQuestions());+ assertEquals(List.of("start", "end"), watcher.events,+ "the hook saw the call inside the block and nothing after it");+ }+ }++ @Test+ @DisplayName("a closed agent refuses before any hook can watch a call that will not happen")+ void aClosedAgentDispatchesNothing(@TempDir Path root) throws IOException {+ TinyCheckpoint.write(root, 128, 48);+ TinyCheckpoint.RecordingSession session = new TinyCheckpoint.RecordingSession();+ Agent agent = TinyCheckpoint.agent(root, session);+ Watcher watcher = new Watcher();+ agent.hooks().addHook(watcher);+ agent.close();+ assertThrows(IllegalStateException.class, () -> agent.predict("alpha", twoQuestions()));+ assertEquals(List.of(), watcher.events);+ }++ @Test+ @DisplayName("predictLong runs no hook: not per-call, not installed, not process-wide")+ void predictLongIsDeliberatelyUnhooked(@TempDir Path root) throws IOException {+ TinyCheckpoint.write(root, 128, 48);+ Map<String, Question> questions = Map.of("urgent", Question.noul("Needs a human."));+ try (TinyCheckpoint.RecordingSession session = new TinyCheckpoint.RecordingSession();+ Agent agent = TinyCheckpoint.agent(root, session)) {+ Watcher installed = new Watcher();+ Watcher processWide = new Watcher();+ agent.hooks().addHook(installed);+ Hooks.setDefaultHooks(List.of(processWide));++ // Long enough to need several windows, which is the case where a hook firing per+ // call rather than per document would be visible.+ LongPrediction scanned = agent.predictLong("y".repeat(600), questions);+ assertTrue(scanned.usage().windows() > 1, "the state has to actually be scanned");+ // ...and short enough to be answered in one call, which takes the other branch.+ LongPrediction single = agent.predictLong("short", questions);+ assertEquals(1, single.usage().windows());++ assertEquals(List.of(), installed.events,+ "a scan dispatched the installed hooks; see predictLong's javadoc for why "+ + "it must not until the reference's start probe and budget check are ported");+ assertEquals(List.of(), processWide.events,+ "a scan dispatched the process-wide defaults, so a tracer installed for the "+ + "whole process would see one event per window and call it a prediction");++ // The ordinary path still dispatches, so the assertion above is about predictLong+ // and not about the hooks having been switched off entirely.+ agent.predict("alpha", questions);+ assertEquals(List.of("start", "end"), installed.events);+ }+ }+}diff --git a/laya-java/laya-java/src/test/java/com/convaiinnovations/laya/HookStubs.java b/laya-java/laya-java/src/test/java/com/convaiinnovations/laya/HookStubs.javanew file mode 100644index 00000000..0161724c--- /dev/null+++ b/laya-java/laya-java/src/test/java/com/convaiinnovations/laya/HookStubs.java@@ -0,0 +1,211 @@+package com.convaiinnovations.laya;++import com.convaiinnovations.laya.hooks.Hook;+import com.convaiinnovations.laya.hooks.PredictContext;+import java.util.ArrayList;+import java.util.LinkedHashMap;+import java.util.LinkedHashSet;+import java.util.List;+import java.util.Map;+import java.util.Set;++/**+ * The hook chain {@code fixtures/hooks.json} was recorded over, rebuilt on this side.+ *+ * <p>The fixture does not record closures, it records a NAME, a set of events and a behaviour+ * string per event — so the same chain can be built in either language from the same data. This+ * is the Java half of that contract.+ *+ * <p>The class is called {@code StubHook} because the reference's stub is, and+ * {@link com.convaiinnovations.laya.hooks.Hooks#dispatch} quotes the hook's class name in the+ * line it reports when a failure is swallowed. The recorded text is part of what the fixture+ * pins, so the name is data rather than taste.+ */+final class HookStubs {++ private HookStubs() {+ }++ /** One result in the shape a prediction has, identified by its input-token count. */+ static Prediction result(int i) {+ return new Prediction(Prediction.MODEL, Map.of(),+ new Usage(10 + i, i, 7, 0, false, List.of(), Map.of()));+ }++ /** The questions a case asks: one noul each, which is all these cases need asked. */+ static Map<String, Question> questions(List<String> ids) {+ Map<String, Question> out = new LinkedHashMap<>();+ for (String id : ids) {+ out.put(id, Question.noul("is this " + id));+ }+ return out;+ }++ /** A hook named {@code name}, implementing {@code events}, doing {@code behaviour}. */+ static StubHook hook(List<Object> log, String name, List<String> events,+ Map<String, String> behaviour, boolean observe) {+ return new StubHook(log, name, events, behaviour, observe);+ }++ /** A hook that only records, implementing every event. */+ static StubHook hook(List<Object> log, String name) {+ return new StubHook(log, name, Hooks0.EVENTS, Map.of(), false);+ }++ /** The six wire names, as the fixture spells them. */+ static final class Hooks0 {+ static final List<String> EVENTS = List.of("on_predict_start", "on_predict_end",+ "on_route", "on_load", "on_evict", "on_error");++ private Hooks0() {+ }+ }++ /** What one hook saw, keyed exactly as the fixture records it. */+ static Map<String, Object> observation(String name, String event, PredictContext ctx) {+ Map<String, Object> seen = new LinkedHashMap<>();+ seen.put("call", name + "." + event);+ seen.put("states", new ArrayList<>(ctx.states()));+ seen.put("questions", new ArrayList<>(ctx.questions().keySet()));+ seen.put("model", ctx.model());+ seen.put("max_len", ctx.maxLen());+ seen.put("head_max_len", ctx.headMaxLen());+ if (ctx.results() == null) {+ seen.put("results", null);+ } else {+ List<Object> tokens = new ArrayList<>();+ for (Prediction prediction : ctx.results()) {+ tokens.add(prediction.usage().inputTokens());+ }+ seen.put("results", tokens);+ }+ if (ctx.usage() == null) {+ seen.put("usage", null);+ } else {+ seen.put("usage", Map.of("input_tokens", ctx.usage().inputTokens(),+ "output_tokens", ctx.usage().outputTokens()));+ }+ seen.put("error", ctx.error() == null ? null : ctx.error().getMessage());+ seen.put("elapsed_ms_set", ctx.elapsedMs() != null);+ seen.put("run_id", ctx.runId());+ return seen;+ }++ /**+ * A recorded hook.+ *+ * <p>Every one of the six methods is overridden and then filtered on {@code events}, rather+ * than only overriding the ones a case names: the reference's stub has only the named+ * methods and {@code dispatch} skips what is absent, and the observable it produces — the+ * hook logs nothing for an event it does not implement — is the same either way. This is+ * where the port's "a default no-op is an absent method" claim is actually exercised.+ */+ static final class StubHook implements Hook {++ private final List<Object> log;+ private final String name;+ private final Set<String> events;+ private final Map<String, String> behaviour;+ private final boolean observe;++ private StubHook(List<Object> log, String name, List<String> events,+ Map<String, String> behaviour, boolean observe) {+ this.log = log;+ this.name = name;+ this.events = new LinkedHashSet<>(events);+ this.behaviour = behaviour;+ this.observe = observe;+ }++ String name() {+ return name;+ }++ @Override+ public void onPredictStart(PredictContext ctx) {+ fire("on_predict_start", ctx);+ }++ @Override+ public void onPredictEnd(PredictContext ctx) {+ fire("on_predict_end", ctx);+ }++ @Override+ public void onRoute(PredictContext ctx) {+ fire("on_route", ctx);+ }++ @Override+ public void onLoad(PredictContext ctx) {+ fire("on_load", ctx);+ }++ @Override+ public void onEvict(PredictContext ctx) {+ fire("on_evict", ctx);+ }++ @Override+ public void onError(PredictContext ctx) {+ fire("on_error", ctx);+ }++ private void fire(String event, PredictContext ctx) {+ if (!events.contains(event)) {+ return;+ }+ log.add(observe ? observation(name, event, ctx) : name + "." + event);+ apply(behaviour.get(event), ctx);+ }++ /** The behaviour language the fixture writes, read back. */+ private void apply(String spec, PredictContext ctx) {+ if (spec == null || "record".equals(spec)) {+ return;+ }+ int colon = spec.indexOf(':');+ String verb = colon < 0 ? spec : spec.substring(0, colon);+ String argument = colon < 0 ? "" : spec.substring(colon + 1);+ switch (verb) {+ case "raise" ->+ // The reference raises a ValueError; this is its Java counterpart, and+ // the MESSAGE is what the fixture compares.+ throw new IllegalArgumentException("boom from " + name);+ case "skip" -> ctx.skip(results(0, Integer.parseInt(argument)));+ case "states" -> ctx.states(split(argument));+ case "questions" -> ctx.questions(questions(split(argument)));+ case "results" -> ctx.results(results(500, Integer.parseInt(argument)));+ case "max_len" -> ctx.maxLen(Integer.parseInt(argument));+ case "head_max_len" -> ctx.headMaxLen(Integer.parseInt(argument));+ case "sleep" -> sleep(Double.parseDouble(argument));+ default -> throw new AssertionError("unknown hook behaviour " + spec);+ }+ }++ private static void sleep(double seconds) {+ try {+ Thread.sleep((long) (seconds * 1000.0));+ } catch (InterruptedException interrupted) {+ Thread.currentThread().interrupt();+ }+ }++ private static List<String> split(String csv) {+ return csv.isEmpty() ? List.of() : List.of(csv.split(","));+ }++ private static List<Prediction> results(int base, int count) {+ List<Prediction> out = new ArrayList<>(count);+ for (int i = 0; i < count; i++) {+ out.add(result(base + i));+ }+ return out;+ }++ @Override+ public String toString() {+ return name;+ }+ }+}diff --git a/laya-java/laya-java/src/test/java/com/convaiinnovations/laya/HooksTest.java b/laya-java/laya-java/src/test/java/com/convaiinnovations/laya/HooksTest.javanew file mode 100644index 00000000..1485e3e4--- /dev/null+++ b/laya-java/laya-java/src/test/java/com/convaiinnovations/laya/HooksTest.java@@ -0,0 +1,861 @@+package com.convaiinnovations.laya;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertNotNull;+import static org.junit.jupiter.api.Assertions.assertNull;+import static org.junit.jupiter.api.Assertions.assertSame;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;+import static org.junit.jupiter.api.DynamicTest.dynamicTest;++import com.convaiinnovations.laya.hooks.Hook;+import com.convaiinnovations.laya.hooks.HookCall;+import com.convaiinnovations.laya.hooks.HookRegistry;+import com.convaiinnovations.laya.hooks.Hooks;+import com.convaiinnovations.laya.hooks.PredictContext;+import java.time.Duration;+import java.util.ArrayList;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;+import java.util.concurrent.atomic.AtomicInteger;+import java.util.function.Consumer;+import org.junit.jupiter.api.AfterEach;+import org.junit.jupiter.api.DisplayName;+import org.junit.jupiter.api.DynamicTest;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.TestFactory;++/**+ * The hook model against {@code fixtures/hooks.json}, recorded from {@code laya.hooks}.+ *+ * <p>Hooks are the one place a caller's own code runs inside a prediction, so almost everything+ * about them is observable and almost none of it is derivable from the answers. The fixture+ * records the chain as DATA — a name, the events it implements, and a behaviour string per event+ * — so the identical chain is rebuilt here rather than described twice; see {@link HookStubs}.+ *+ * <p>What a port gets wrong by default, and what each section therefore pins:+ *+ * <ul>+ * <li>ORDER. Defaults, then installed, then per-call, with the two convenience callbacks after+ * the hook objects. Every order runs every hook, so nothing fails — except that a tracer+ * installed to watch what a per-call hook did now runs first and sees nothing.</li>+ * <li>{@code skip} does not stop the chain. A port that returns early from dispatch passes+ * every single-hook case and loses the contract that a later hook can overrule.</li>+ * <li>A failing hook is ATTACHED to the failure it observed, never substituted for it. On the+ * JVM that is {@code addSuppressed} where the reference uses {@code __context__}, and the+ * thing that must not change is which exception the caller catches.</li>+ * <li>Where a {@code finally} would be wrong. Java's replaces the pending exception, so the+ * end-hook stage is written out longhand; the two "inference failed AND a hook failed"+ * cases are what prove it.</li>+ * </ul>+ *+ * <p>Three of the reference's refusals are unrepresentable once {@link Hook} is a type — a class+ * rather than an instance, an object implementing none of the events, and an event attribute+ * that is not callable. They are asserted to still be refusals ON THE PYTHON SIDE rather than+ * skipped, so that a reference which stopped refusing them would be caught here instead of+ * leaving the port's javadoc quietly wrong.+ */+final class HooksTest {++ @SuppressWarnings("unchecked")+ private static Map<String, Object> family() {+ return (Map<String, Object>) (Map<?, ?>) Fixtures.load("hooks.json");+ }++ @SuppressWarnings("unchecked")+ private static List<Object> section(String name) {+ return (List<Object>) family().get(name);+ }++ @SuppressWarnings("unchecked")+ private static Map<String, Object> map(Object value) {+ return (Map<String, Object>) value;+ }++ @SuppressWarnings("unchecked")+ private static List<Object> list(Object value) {+ return (List<Object>) value;+ }++ private static List<String> strings(Object value) {+ List<String> out = new ArrayList<>();+ if (value != null) {+ for (Object item : list(value)) {+ out.add((String) item);+ }+ }+ return out;+ }++ private static Integer integer(Object value) {+ return value == null ? null : ((Number) value).intValue();+ }++ @AfterEach+ void noDefaultsLeakIntoTheNextTest() {+ // Process-wide state, so a case that set it and failed must not take the next one with+ // it. Clearing in teardown rather than only in each case is the difference between one+ // red test and a cascade nobody can attribute.+ Hooks.clearDefaultHooks();+ }++ // -- the events ---------------------------------------------------------++ @Test+ @DisplayName("the six events, and their order, are the reference's")+ void eventsMatch() {+ List<String> recorded = strings(family().get("events"));+ List<String> ported = new ArrayList<>();+ for (Hooks.Event event : Hooks.Event.values()) {+ ported.add(event.wireName());+ }+ assertEquals(recorded, ported,+ "the enum's declaration order is the reference's HOOK_EVENTS order");+ }++ // -- composition --------------------------------------------------------++ /**+ * The label the fixture gives one entry of a composed list.+ *+ * <p>A hook object is its name. A convenience callback has been wrapped by+ * {@link Hooks#onPredictStart}, which is opaque by design, so it is identified by the+ * {@code toString} that method documents.+ */+ private static String label(Hook hook) {+ if (hook instanceof HookStubs.StubHook stub) {+ return stub.name();+ }+ String text = hook.toString();+ if (text.startsWith("onPredictStart(")) {+ return "start:" + text.substring("onPredictStart(".length(), text.length() - 1);+ }+ if (text.startsWith("onPredictEnd(")) {+ return "end:" + text.substring("onPredictEnd(".length(), text.length() - 1);+ }+ return text;+ }++ /** A callback whose {@code toString} is its name, so a composed adapter can be identified. */+ private static Consumer<PredictContext> callback(String name) {+ return new Consumer<>() {+ @Override+ public void accept(PredictContext ctx) {+ // Composition order is the subject here; what the callback does is not.+ }++ @Override+ public String toString() {+ return name;+ }+ };+ }++ @TestFactory+ @DisplayName("defaults, then installed, then per-call, with callbacks last")+ @SuppressWarnings("try") // javac reports the unreferenced resource; see withoutDefaultHooks+ List<DynamicTest> compositionOrderMatches() {+ List<DynamicTest> tests = new ArrayList<>();+ for (Object raw : section("composition")) {+ Map<String, Object> one = map(raw);+ tests.add(dynamicTest((String) one.get("case"), () -> {+ List<Object> log = new ArrayList<>();+ try {+ List<Hook> defaults = new ArrayList<>();+ for (String name : strings(one.get("defaults"))) {+ defaults.add(HookStubs.hook(log, name));+ }+ Hooks.setDefaultHooks(defaults);++ List<Hook> installed = new ArrayList<>();+ for (String name : strings(one.get("installed"))) {+ installed.add(HookStubs.hook(log, name));+ }+ HookCall call = HookCall.none();+ for (String name : strings(one.get("hooks"))) {+ call = call.andThen(HookStubs.hook(log, name));+ }+ for (String name : strings(one.get("on_predict_start"))) {+ call = call.onStart(callback(name));+ }+ for (String name : strings(one.get("on_predict_end"))) {+ call = call.onEnd(callback(name));+ }++ List<Hook> composed;+ if (Boolean.TRUE.equals(one.get("skip_defaults"))) {+ try (Hooks.DefaultsScope ignored = Hooks.withoutDefaultHooks()) {+ composed = Hooks.compose(installed, call);+ }+ } else {+ composed = Hooks.compose(installed, call);+ }+ List<String> order = new ArrayList<>();+ for (Hook hook : composed) {+ order.add(label(hook));+ }+ assertEquals(strings(one.get("order")), order, "composition order");+ } finally {+ Hooks.clearDefaultHooks();+ }+ }));+ }+ return tests;+ }++ @Test+ @DisplayName("the process-wide defaults are set, added to, read as a copy and cleared")+ void defaultHooksApiMatches() {+ Map<String, Object> recorded = map(family().get("default_hooks_api"));+ List<Object> log = new ArrayList<>();+ Hooks.setDefaultHooks(List.of(HookStubs.hook(log, "probe")));+ assertEquals(strings(recorded.get("after_set")), labels(Hooks.defaultHooks()));++ List<Hook> borrowed = Hooks.defaultHooks();+ borrowed.add(HookStubs.hook(log, "intruder"));+ assertEquals(strings(recorded.get("mutating_the_returned_list_changes_nothing")),+ labels(Hooks.defaultHooks()),+ "the read hands back a copy, so editing it edits a list of your own");++ Hooks.addDefaultHook(HookStubs.hook(log, "added"));+ assertEquals(strings(recorded.get("after_add")), labels(Hooks.defaultHooks()));++ Hooks.clearDefaultHooks();+ assertEquals(strings(recorded.get("after_clear")), labels(Hooks.defaultHooks()));+ }++ private static List<String> labels(List<Hook> hooks) {+ List<String> out = new ArrayList<>();+ for (Hook hook : hooks) {+ out.add(label(hook));+ }+ return out;+ }++ @Test+ @DisplayName("withoutDefaultHooks suppresses the defaults for a call without unsetting them")+ @SuppressWarnings("try")+ void withoutDefaultHooksIsAScopeNotAnEdit() {+ List<Object> log = new ArrayList<>();+ Hook probe = HookStubs.hook(log, "probe");+ Hooks.setDefaultHooks(List.of(probe));+ try (Hooks.DefaultsScope ignored = Hooks.withoutDefaultHooks()) {+ assertEquals(List.of(), Hooks.compose(List.of(), HookCall.none()),+ "the scope suppresses them for a call");+ assertEquals(List.of(probe), Hooks.defaultHooks(),+ "...and a read still says what is installed, or the scope cannot be debugged");+ }+ assertEquals(List.of(probe), Hooks.compose(List.of(), HookCall.none()),+ "and they are back afterwards");+ }++ // -- normalise ----------------------------------------------------------++ @TestFactory+ @DisplayName("what the reference refuses to accept as a hook, it still refuses")+ List<DynamicTest> normaliseRefusalsStillRefuse() {+ List<DynamicTest> tests = new ArrayList<>();+ for (Object raw : section("normalise_refusals")) {+ Map<String, Object> one = map(raw);+ tests.add(dynamicTest((String) one.get("input"), () ->+ // Unrepresentable on this side -- a class is not a Hook, an object with no+ // event methods is not a Hook, and an event that is not callable cannot+ // exist once the events are methods. Asserting the reference still refuses+ // them is what keeps that claim true: if it stopped, this port's javadoc+ // would be wrong and nothing else here would notice.+ assertNotNull(one.get("error"),+ "the reference no longer refuses this, so the type-system argument "+ + "in Hooks.normalise is out of date")));+ }+ return tests;+ }++ @Test+ @DisplayName("a null entry is representable, so it is refused here")+ void normaliseRefusesNull() {+ List<Hook> withNull = new ArrayList<>();+ withNull.add(null);+ assertThrows(IllegalArgumentException.class, () -> Hooks.normalise(withNull, null, null));+ assertThrows(IllegalArgumentException.class, () -> Hooks.onPredictStart(null));+ assertThrows(IllegalArgumentException.class, () -> Hooks.onPredictEnd(null));+ }++ @TestFactory+ @DisplayName("one hook, several, or none all flatten the same way")+ List<DynamicTest> flatteningMatches() {+ List<DynamicTest> tests = new ArrayList<>();+ List<Object> log = new ArrayList<>();+ Hook one = HookStubs.hook(log, "one");+ Map<String, List<Hook>> inputs = new LinkedHashMap<>();+ inputs.put("none", null);+ inputs.put("one", List.of(one));+ inputs.put("list-of-two", List.of(one, one));+ inputs.put("tuple-of-three", List.of(one, one, one));+ inputs.put("empty-list", List.of());+ for (Object raw : section("as_sequence")) {+ Map<String, Object> entry = map(raw);+ String name = (String) entry.get("input");+ tests.add(dynamicTest(name, () -> {+ assertTrue(inputs.containsKey(name), "unrecorded flattening case " + name);+ assertEquals(integer(entry.get("length")).intValue(),+ Hooks.normalise(inputs.get(name), null, null).size());+ }));+ }+ return tests;+ }++ // -- dispatch -----------------------------------------------------------++ @TestFactory+ @DisplayName("every dispatch calls what the reference called, in order, and fails where it did")+ List<DynamicTest> dispatchMatches() {+ List<DynamicTest> tests = new ArrayList<>();+ for (Object raw : section("dispatch")) {+ Map<String, Object> one = map(raw);+ tests.add(dynamicTest((String) one.get("case"), () -> {+ List<Object> log = new ArrayList<>();+ List<Hook> chain = new ArrayList<>();+ for (Object link : list(one.get("chain"))) {+ Map<String, Object> spec = map(link);+ chain.add(HookStubs.hook(log, (String) spec.get("name"),+ strings(spec.get("events")), behaviourOf(spec.get("behaviour")),+ false));+ }+ PredictContext ctx = new PredictContext(List.of("s0"),+ HookStubs.questions(List.of("q")), null, null);+ List<String> warnings = new ArrayList<>();+ Hooks.Policy policy = new Hooks.Policy((Boolean) one.get("raise_errors"), null,+ null, warnings::add);+ Hooks.Event event = eventOf((String) one.get("event"));++ Map<String, Object> raised = one.get("raised") == null ? null+ : map(one.get("raised"));+ if (raised == null) {+ Hooks.dispatch(chain, event, ctx, policy);+ } else {+ RuntimeException problem = assertThrows(RuntimeException.class,+ () -> Hooks.dispatch(chain, event, ctx, policy));+ assertEquals(raised.get("message"), problem.getMessage());+ assertEquals(javaTypeFor((String) raised.get("type")),+ problem.getClass().getSimpleName());+ }+ assertEquals(strings(one.get("calls")), log, "which hooks ran, in order");+ assertEquals(strings(one.get("warnings")), warnings,+ "what a swallowed failure reported");+ assertEquals(integer(one.get("results")),+ ctx.results() == null ? null : ctx.results().size(),+ "a skip assigns results without stopping the chain");+ }));+ }+ return tests;+ }++ private static Map<String, String> behaviourOf(Object recorded) {+ Map<String, String> out = new LinkedHashMap<>();+ if (recorded instanceof String single) {+ for (Hooks.Event event : Hooks.Event.values()) {+ out.put(event.wireName(), single);+ }+ } else if (recorded instanceof Map<?, ?> perEvent) {+ perEvent.forEach((key, value) -> out.put((String) key, (String) value));+ }+ return out;+ }++ private static Hooks.Event eventOf(String wireName) {+ for (Hooks.Event event : Hooks.Event.values()) {+ if (event.wireName().equals(wireName)) {+ return event;+ }+ }+ throw new AssertionError("no event called " + wireName);+ }++ /** The exception the reference raises, as this port spells it. */+ private static String javaTypeFor(String pythonType) {+ return switch (pythonType) {+ case "ValueError" -> "IllegalArgumentException";+ case "RuntimeError" -> "RuntimeException";+ case "TypeError" -> "IllegalArgumentException";+ default -> throw new AssertionError("unmapped reference exception " + pythonType);+ };+ }++ // -- ctx.skip -----------------------------------------------------------++ @TestFactory+ @DisplayName("skip takes one result per state, or one for the call, and nothing else")+ List<DynamicTest> skipMatches() {+ List<DynamicTest> tests = new ArrayList<>();+ for (Object raw : section("skip")) {+ Map<String, Object> one = map(raw);+ tests.add(dynamicTest((String) one.get("case"), () -> {+ int states = integer(one.get("states"));+ int count = integer(one.get("results"));+ List<Object> given = new ArrayList<>();+ for (int i = 0; i < states; i++) {+ given.add("s" + i);+ }+ List<Prediction> answers = new ArrayList<>();+ for (int i = 0; i < count; i++) {+ answers.add(HookStubs.result(i));+ }+ PredictContext ctx = new PredictContext(given,+ HookStubs.questions(List.of("q")), null, null);+ if (Boolean.TRUE.equals(one.get("accepted"))) {+ ctx.skip(answers);+ List<Object> assigned = new ArrayList<>();+ for (Prediction prediction : ctx.results()) {+ assigned.add(prediction.usage().inputTokens());+ }+ assertEquals(list(one.get("assigned")).stream().map(HooksTest::integer)+ .toList(), assigned);+ } else {+ IllegalArgumentException problem = assertThrows(+ IllegalArgumentException.class, () -> ctx.skip(answers));+ assertEquals(one.get("error"), problem.getMessage());+ assertNull(ctx.results(), "a refused skip leaves the call unanswered");+ }+ }));+ }+ return tests;+ }++ // -- aggregate_usage ----------------------------------------------------++ @TestFactory+ @DisplayName("usage totals over the call, including the shapes a record cannot hold")+ List<DynamicTest> usageMatches() {+ List<DynamicTest> tests = new ArrayList<>();+ for (Object raw : section("usage")) {+ Map<String, Object> one = map(raw);+ tests.add(dynamicTest((String) one.get("case"), () -> {+ List<Prediction> results = new ArrayList<>();+ for (Object block : list(one.get("results"))) {+ Map<String, Object> usage = map(block);+ // A missing block, a null block, a missing key and a null value are all+ // "no number" in the reference, which coerces them to zero because a result+ // there is a plain dict a hook may have rewritten. A Usage record holds+ // primitive ints, so the representable equivalent of every one of them is+ // the same: zero. A float truncates, which `int()` and a Java cast agree on.+ results.add(new Prediction(Prediction.MODEL, Map.of(),+ new Usage(truncate(usage.get("input_tokens")),+ truncate(usage.get("output_tokens")), 0, 0, false,+ List.of(), Map.of())));+ }+ Map<String, Object> total = map(one.get("total"));+ Hooks.Totals got = Hooks.aggregateUsage(results);+ assertEquals(integer(total.get("input_tokens")).intValue(), got.inputTokens());+ assertEquals(integer(total.get("output_tokens")).intValue(), got.outputTokens());+ }));+ }+ return tests;+ }++ private static int truncate(Object value) {+ return value instanceof Number number ? (int) number.doubleValue() : 0;+ }++ // -- validate_timeout ---------------------------------------------------++ @TestFactory+ @DisplayName("a timeout is a positive duration, and the non-positive ones are refused")+ List<DynamicTest> timeoutsMatch() {+ List<DynamicTest> tests = new ArrayList<>();+ for (Object raw : section("timeouts")) {+ Map<String, Object> one = map(raw);+ String input = (String) one.get("input");+ Duration candidate = durationFor(input);+ if (candidate == null && !"None".equals(input)) {+ // nan, inf and -inf have no Duration, and '0.5' is a string the reference+ // coerces where Java has no such value to be handed. Unreachable, not skipped:+ // the refusal is still asserted on the reference's side.+ tests.add(dynamicTest(input + " (unrepresentable as a Duration)", () -> {+ if (Boolean.FALSE.equals(one.get("accepted"))) {+ assertNotNull(one.get("error"));+ } else {+ assertNotNull(one.get("value"));+ }+ }));+ continue;+ }+ tests.add(dynamicTest(input, () -> {+ if (Boolean.TRUE.equals(one.get("accepted"))) {+ assertEquals(candidate, Hooks.validateTimeout(candidate));+ } else {+ assertThrows(IllegalArgumentException.class,+ () -> Hooks.validateTimeout(candidate));+ }+ }));+ }+ return tests;+ }++ private static Duration durationFor(String recorded) {+ return switch (recorded) {+ case "None" -> null;+ case "1" -> Duration.ofSeconds(1);+ case "1.5" -> Duration.ofMillis(1500);+ case "0.05" -> Duration.ofMillis(50);+ case "0", "0.0" -> Duration.ZERO;+ case "-1" -> Duration.ofSeconds(-1);+ case "-0.5" -> Duration.ofMillis(-500);+ default -> null;+ };+ }++ // -- the registry -------------------------------------------------------++ @TestFactory+ @DisplayName("installing, removing and scoping hooks leaves the list the reference leaves")+ List<DynamicTest> registryMatches() {+ List<DynamicTest> tests = new ArrayList<>();+ for (Object raw : section("registry")) {+ Map<String, Object> one = map(raw);+ tests.add(dynamicTest((String) one.get("case"), () -> {+ HookRegistry registry = new HookRegistry();+ List<Object> log = new ArrayList<>();+ Map<String, Hook> pool = new LinkedHashMap<>();+ Map<String, HookRegistry.Scope> blocks = new LinkedHashMap<>();+ for (Object rawStep : list(one.get("steps"))) {+ Map<String, Object> step = map(rawStep);+ String op = (String) step.get("op");+ int colon = op.indexOf(':');+ String verb = colon < 0 ? op : op.substring(0, colon);+ String rest = colon < 0 ? "" : op.substring(colon + 1);+ Object returned = null;+ switch (verb) {+ case "add" -> {+ if (rest.startsWith("[")) {+ registry.addHooks(named(pool, log, rest));+ } else {+ registry.addHook(named(pool, log, rest).get(0));+ }+ }+ case "remove" ->+ returned = registry.removeHook(named(pool, log, rest).get(0));+ case "enter" -> {+ int second = rest.indexOf(':');+ String block = rest.substring(0, second);+ // The reference takes several arguments, each a hook or a sequence,+ // and flattens them in order into one list -- so one list here is+ // the same thing, which is what the several-argument case asserts.+ blocks.put(block, registry.hooksInstalled(+ named(pool, log, rest.substring(second + 1))));+ }+ case "exit" -> blocks.remove(rest).close();+ default -> throw new AssertionError("unknown registry op " + op);+ }+ assertEquals(step.get("returned"), returned, "what " + op + " reported");+ assertEquals(strings(step.get("hooks")), labels(registry.hooks()),+ "the installed list after " + op);+ }+ assertEquals(strings(one.get("final")), labels(registry.hooks()));+ }));+ }+ return tests;+ }++ /** The hooks a scripted op names, one instance per name so identity is stable. */+ private static List<Hook> named(Map<String, Hook> pool, List<Object> log, String spec) {+ List<Hook> out = new ArrayList<>();+ for (String name : spec.replace("[", "").replace("]", "").split(",")) {+ if (!name.isEmpty()) {+ out.add(pool.computeIfAbsent(name, key -> HookStubs.hook(log, key)));+ }+ }+ return out;+ }++ @Test+ @DisplayName("a scope closed twice does not take someone else's copy")+ void closingAScopeTwiceIsIdempotent() {+ HookRegistry registry = new HookRegistry();+ List<Object> log = new ArrayList<>();+ Hook tracer = HookStubs.hook(log, "tracer");+ registry.addHook(tracer);+ HookRegistry.Scope scope = registry.hooksInstalled(tracer);+ assertEquals(List.of("tracer", "tracer"), labels(registry.hooks()));+ scope.close();+ scope.close();+ assertEquals(List.of("tracer"), labels(registry.hooks()),+ "the second close must not remove the copy the application installed");+ }++ // -- the whole call -----------------------------------------------------++ @TestFactory+ @DisplayName("a hooked call does what the reference's predict_batch did, end to end")+ List<DynamicTest> aroundMatches() {+ List<DynamicTest> tests = new ArrayList<>();+ for (Object raw : section("predict_batch")) {+ Map<String, Object> one = map(raw);+ tests.add(dynamicTest((String) one.get("case"), () -> runPredictCase(one)));+ }+ return tests;+ }++ private void runPredictCase(Map<String, Object> one) {+ List<Object> log = new ArrayList<>();+ try {+ Hooks.setDefaultHooks(stubs(log, one.get("defaults")));+ List<Hook> installed = stubs(log, one.get("installed"));+ HookCall call = HookCall.of(stubs(log, one.get("hooks")));++ List<Object> states = new ArrayList<>(strings(one.get("states")));+ Map<String, Question> questions = HookStubs.questions(strings(one.get("questions")));+ boolean inferenceRaises = Boolean.TRUE.equals(one.get("inference_raises"));+ Map<String, Object>[] inferenceSaw = asArray();++ Hooks.Inference inference = (hookedStates, asked, maxLen, headMaxLen) -> {+ Map<String, Object> seen = new LinkedHashMap<>();+ seen.put("states", new ArrayList<>(hookedStates));+ seen.put("questions", new ArrayList<>(asked.keySet()));+ Map<String, Object> overrides = new LinkedHashMap<>();+ if (maxLen != null) {+ overrides.put("max_len", maxLen);+ }+ if (headMaxLen != null) {+ overrides.put("head_max_len", headMaxLen);+ }+ seen.put("overrides", overrides);+ inferenceSaw[0] = seen;+ if (inferenceRaises) {+ throw new RuntimeException("the graph refused this batch");+ }+ List<Prediction> out = new ArrayList<>();+ for (int i = 0; i < hookedStates.size(); i++) {+ out.add(HookStubs.result(100 + i));+ }+ return out;+ };++ List<String> warnings = new ArrayList<>();+ Hooks.Policy policy = new Hooks.Policy((Boolean) one.get("hooks_raise"), null, null,+ warnings::add);+ PredictContext ctx = new PredictContext(states, questions, "stub-checkpoint", null);+ List<Hook> active = Hooks.compose(installed, call);++ Map<String, Object> raised = one.get("raised") == null ? null : map(one.get("raised"));+ List<Prediction> results = null;+ if (raised == null) {+ results = Hooks.around(active, ctx, policy, inference);+ } else {+ RuntimeException problem = assertThrows(RuntimeException.class,+ () -> Hooks.around(active, ctx, policy, inference));+ assertEquals(raised.get("message"), problem.getMessage(), "what the caller sees");+ assertEquals(javaTypeFor((String) raised.get("type")),+ problem.getClass().getSimpleName());+ Object context = raised.get("context");+ if (context == null) {+ assertEquals(0, problem.getSuppressed().length,+ "nothing else failed, so nothing is attached");+ } else {+ // The reference chains a failing error/end hook onto the real failure with+ // `__context__`; the JVM's equivalent is a suppressed exception. What must+ // not change is which one the caller catches.+ assertEquals(1, problem.getSuppressed().length,+ "a failing hook is attached to the failure it observed");+ assertEquals(javaTypeFor((String) context),+ problem.getSuppressed()[0].getClass().getSimpleName());+ }+ }++ assertEquals(describeInference(one.get("inference")), describe(inferenceSaw[0]),+ "what inference was handed, or that it never ran");+ assertEquals(strings(one.get("warnings")), warnings);+ assertEquals(tokensOf(one.get("result")),+ results == null ? null : tokens(results), "what the caller receives");+ assertObservations(list(one.get("calls")), log);+ } finally {+ Hooks.clearDefaultHooks();+ }+ }++ @SuppressWarnings("unchecked")+ private static Map<String, Object>[] asArray() {+ // A one-slot holder so the inference lambda can report what it was handed.+ return (Map<String, Object>[]) new Map<?, ?>[1];+ }++ private static List<Hook> stubs(List<Object> log, Object recorded) {+ List<Hook> out = new ArrayList<>();+ if (recorded != null) {+ for (Object raw : list(recorded)) {+ Map<String, Object> spec = map(raw);+ out.add(HookStubs.hook(log, (String) spec.get("name"), HookStubs.Hooks0.EVENTS,+ behaviourOf(spec.get("behaviour")), true));+ }+ }+ return out;+ }++ private static List<Object> tokens(List<Prediction> results) {+ List<Object> out = new ArrayList<>();+ for (Prediction prediction : results) {+ out.add(prediction.usage().inputTokens());+ }+ return out;+ }++ private static List<Object> tokensOf(Object recorded) {+ if (recorded == null) {+ return null;+ }+ List<Object> out = new ArrayList<>();+ for (Object item : list(recorded)) {+ out.add(integer(item));+ }+ return out;+ }++ private static String describeInference(Object recorded) {+ return recorded == null ? "never ran" : describeSeen(map(recorded));+ }++ private static String describe(Map<String, Object> seen) {+ return seen == null ? "never ran" : describeSeen(seen);+ }++ private static String describeSeen(Map<String, Object> seen) {+ Map<String, Object> overrides = map(seen.get("overrides"));+ Map<String, Object> normalised = new LinkedHashMap<>();+ overrides.forEach((key, value) -> normalised.put(key, integer(value)));+ return seen.get("states") + " " + seen.get("questions") + " " + normalised;+ }++ /** Each hook invocation, field by field, so a mismatch names the field rather than the blob. */+ private void assertObservations(List<Object> recorded, List<Object> got) {+ assertEquals(recorded.size(), got.size(), "how many hook invocations happened");+ for (int at = 0; at < recorded.size(); at++) {+ Map<String, Object> want = map(recorded.get(at));+ Map<String, Object> have = map(got.get(at));+ String where = "invocation " + at + " (" + want.get("call") + ")";+ assertEquals(want.get("call"), have.get("call"), where);+ assertEquals(strings(want.get("states")), have.get("states"), where + " states");+ assertEquals(strings(want.get("questions")), have.get("questions"),+ where + " questions");+ assertEquals(want.get("model"), have.get("model"), where + " model");+ assertEquals(integer(want.get("max_len")), have.get("max_len"), where + " max_len");+ assertEquals(integer(want.get("head_max_len")), have.get("head_max_len"),+ where + " head_max_len");+ assertEquals(tokensOf(want.get("results")), have.get("results"), where + " results");+ assertEquals(usageOf(want.get("usage")), have.get("usage"), where + " usage");+ assertEquals(want.get("error"), have.get("error"), where + " error");+ assertEquals(want.get("elapsed_ms_set"), have.get("elapsed_ms_set"),+ where + " elapsed");+ assertEquals(32, ((String) have.get("run_id")).length(), where + " run id length");+ assertEquals(map(got.get(0)).get("run_id"), have.get("run_id"),+ where + ": one run id per call, or a tracer cannot pair a start with its end");+ }+ }++ private static Map<String, Object> usageOf(Object recorded) {+ if (recorded == null) {+ return null;+ }+ Map<String, Object> want = map(recorded);+ return Map.of("input_tokens", integer(want.get("input_tokens")),+ "output_tokens", integer(want.get("output_tokens")));+ }++ // -- the parts the reference cannot record ------------------------------++ @Test+ @DisplayName("a hook that overruns its deadline fails the call rather than holding it")+ void aSlowHookTimesOut() {+ List<Object> log = new ArrayList<>();+ Hook slow = HookStubs.hook(log, "slow", HookStubs.Hooks0.EVENTS,+ Map.of("on_predict_start", "sleep:5"), false);+ PredictContext ctx = new PredictContext(List.of("s0"),+ HookStubs.questions(List.of("q")), null, null);+ Hooks.Policy policy = Hooks.Policy.raising().timeout(Duration.ofMillis(50));+ long began = System.nanoTime();+ Hooks.HookTimeoutException problem = assertThrows(Hooks.HookTimeoutException.class,+ () -> Hooks.dispatch(List.of(slow), Hooks.Event.PREDICT_START, ctx, policy));+ double waited = (System.nanoTime() - began) / 1_000_000.0;+ assertTrue(waited < 4000.0, "the deadline bounded the call, not the hook: waited " + waited);+ // The hook is named by its CLASS and event, as the reference's `__qualname__` names it,+ // and the deadline is in seconds -- so the line a caller greps for is the same text on+ // both runtimes.+ assertEquals("laya: hook StubHook.on_predict_start exceeded 0.05s", problem.getMessage());+ }++ @Test+ @DisplayName("a hook under a timeout still reports its own failure, not a timeout")+ void aFailingHookUnderATimeoutStillFails() {+ List<Object> log = new ArrayList<>();+ Hook angry = HookStubs.hook(log, "angry", HookStubs.Hooks0.EVENTS,+ Map.of("on_predict_start", "raise"), false);+ PredictContext ctx = new PredictContext(List.of("s0"),+ HookStubs.questions(List.of("q")), null, null);+ IllegalArgumentException problem = assertThrows(IllegalArgumentException.class,+ () -> Hooks.dispatch(List.of(angry), Hooks.Event.PREDICT_START, ctx,+ Hooks.Policy.raising().timeout(Duration.ofSeconds(5))));+ assertEquals("boom from angry", problem.getMessage(),+ "the hook's failure crosses back from the thread it ran on");+ }++ @Test+ @DisplayName("a non-concurrent registry serialises its hooks behind one lock")+ void serialisedHooksDoNotOverlap() throws Exception {+ HookRegistry registry = new HookRegistry().concurrent(false);+ AtomicInteger inside = new AtomicInteger();+ AtomicInteger overlaps = new AtomicInteger();+ Hook counting = new Hook() {+ @Override+ public void onPredictStart(PredictContext ctx) {+ if (inside.incrementAndGet() > 1) {+ overlaps.incrementAndGet();+ }+ try {+ Thread.sleep(2);+ } catch (InterruptedException interrupted) {+ Thread.currentThread().interrupt();+ } finally {+ inside.decrementAndGet();+ }+ }+ };+ registry.addHook(counting);+ Hooks.Policy policy = registry.policyFor(HookCall.none());+ assertNotNull(policy.lock(), "concurrent(false) is what installs the lock");+ List<Thread> workers = new ArrayList<>();+ for (int i = 0; i < 8; i++) {+ Thread worker = new Thread(() -> Hooks.dispatch(registry.hooks(),+ Hooks.Event.PREDICT_START,+ new PredictContext(List.of("s"), HookStubs.questions(List.of("q")), null,+ null),+ policy));+ workers.add(worker);+ worker.start();+ }+ for (Thread worker : workers) {+ worker.join();+ }+ assertEquals(0, overlaps.get(), "two calls ran the same hook at once");+ }++ @Test+ @DisplayName("the per-call policy overrides the agent's, and only where it says so")+ void perCallPolicyOverrides() {+ HookRegistry registry = new HookRegistry().raiseErrors(false)+ .timeout(Duration.ofSeconds(3));+ assertFalse(registry.policyFor(HookCall.none()).raiseErrors());+ assertEquals(Duration.ofSeconds(3), registry.policyFor(HookCall.none()).timeout());++ HookCall call = HookCall.none().raiseErrors(true);+ assertTrue(registry.policyFor(call).raiseErrors());+ assertEquals(Duration.ofSeconds(3), registry.policyFor(call).timeout(),+ "a call that overrides one knob must not reset the other");+ assertEquals(Duration.ofMillis(10),+ registry.policyFor(HookCall.none().timeout(Duration.ofMillis(10))).timeout());+ assertThrows(IllegalArgumentException.class,+ () -> HookCall.none().timeout(Duration.ZERO));+ assertSame(HookCall.none(), HookCall.none(), "the empty call is a constant");+ assertTrue(HookCall.none().isEmpty());+ assertFalse(HookCall.none().raiseErrors(true).isEmpty());+ }+}diff --git a/laya-java/scripts/gen_fixtures.py b/laya-java/scripts/gen_fixtures.pyindex 1b335cb9..5762344f 100644--- a/laya-java/scripts/gen_fixtures.py+++ b/laya-java/scripts/gen_fixtures.py@@ -3069,6 +3069,712 @@ def confidence_gate():" the three states and the no-op" % (gated, len(GATE_STATES)))return {"states": list(GATE_STATES), "cases": cases, "refusals": refusals}+# ---------------------------------------------------------------------------+# laya.hooks: composition order, what a hook sees, and what it can change.+# ---------------------------------------------------------------------------++#: Results carry a usage block only, so a case's provenance is readable from one number:+#: inference returns 110+, a start hook's `ctx.skip()` returns 10+, an end hook's rewrite 510+.+def _hook_result(i):+ """One result dict in the shape `predict_batch` returns, with a usage block to aggregate."""+ return {"model": "laya-rl-agent-onnx", "answers": {},+ "usage": {"input_tokens": 10 + i, "output_tokens": i, "state_tokens": 7,+ "state_tokens_dropped": 0, "truncated": False,+ "truncated_questions": []}}+++def _hook_questions(ids):+ """A question mapping with those ids: one noul each, which is all these cases need asked."""+ return {qid: {"noul": "is this %s" % qid} for qid in ids}+++def _apply_hook_behaviour(spec, ctx, name):+ """The one behaviour a stub hook performs, named by a string the port reconstructs.++ A behaviour is data rather than a closure so the Java side can build the same chain from the+ fixture. Anything a hook is allowed to do to a call is one of these.+ """+ if spec is None or spec == "record":+ return+ verb, _, argument = spec.partition(":")+ if verb == "raise":+ raise ValueError("boom from %s" % name)+ if verb == "skip":+ ctx.skip([_hook_result(i) for i in range(int(argument))])+ return+ if verb == "states":+ ctx.states = argument.split(",") if argument else []+ return+ if verb == "questions":+ ctx.questions = _hook_questions(argument.split(",") if argument else [])+ return+ if verb == "results":+ ctx.results = [_hook_result(500 + i) for i in range(int(argument))]+ return+ if verb == "max_len":+ ctx.max_len = int(argument)+ return+ if verb == "head_max_len":+ ctx.head_max_len = int(argument)+ return+ if verb == "sleep":+ import time as _time+ _time.sleep(float(argument))+ return+ raise AssertionError("unknown hook behaviour %r" % (spec,))+++def _stub_hook(log, name, events, behaviour=None, observe=False):+ """A hook implementing exactly `events`, appending to `log` and then doing `behaviour`.++ The class is called `StubHook` whatever the instance is named, because `dispatch`'s+ `raise_errors=False` warning quotes `type(hook).__name__` and that text is part of what this+ family pins -- so the port's stub has to be able to produce the same string.+ """+ def make(event):+ def method(self, ctx):+ if observe:+ log.append(_observation(name, event, ctx))+ else:+ log.append("%s.%s" % (name, event))+ spec = behaviour.get(event) if isinstance(behaviour, dict) else behaviour+ _apply_hook_behaviour(spec, ctx, name)+ method.__name__ = event+ method.__qualname__ = "StubHook.%s" % event+ return method++ namespace = {event: make(event) for event in events}+ namespace["stub_name"] = name+ return type("StubHook", (object,), namespace)()+++def _observation(name, event, ctx):+ """Everything one hook can read off the context, as the fixture records it."""+ states = ctx.states+ if isinstance(states, (list, tuple)):+ states = list(states)+ questions = ctx.questions+ return {+ "call": "%s.%s" % (name, event),+ "states": states,+ "questions": list(questions) if isinstance(questions, dict) else questions,+ "model": ctx.model,+ "max_len": ctx.max_len,+ "head_max_len": ctx.head_max_len,+ # `None` is not `[]`: "inference has not run" and "inference returned nothing" are+ # different states of the call, and a start hook distinguishes them to decide whether an+ # earlier hook has already answered.+ "results": None if ctx.results is None else [r["usage"]["input_tokens"]+ for r in ctx.results],+ "usage": ctx.usage,+ "error": None if ctx.error is None else str(ctx.error),+ # Popped before the fixture is written -- it is a fresh uuid4 per call, so recording+ # the value would make the file differ on every run. What IS recorded is that one call's+ # hooks all saw the SAME one, and how long it is.+ "run_id": ctx.run_id,+ "elapsed_ms_set": ctx.elapsed_ms is not None,+ }+++#: (case, default hook names, installed names, per-call `hooks=` names, `on_predict_start=`+#: names, `on_predict_end=` names, whether the call runs under `_SKIP_DEFAULTS`).+HOOK_COMPOSITION_CASES = [+ ("nothing-installed", [], [], [], [], [], False),+ ("defaults-only", ["d1", "d2"], [], [], [], [], False),+ ("installed-only", [], ["i1", "i2"], [], [], [], False),+ ("per-call-only", [], [], ["p1", "p2"], [], [], False),+ # THE order contract: defaults, then installed, then per-call.+ ("defaults-then-installed-then-per-call", ["d1"], ["i1"], ["p1"], [], [], False),+ # The two convenience callables are appended AFTER the per-call hook objects, starts before+ # ends, so a `on_predict_end=` callable never runs before a `hooks=` entry's end method.+ ("callables-come-after-hook-objects", ["d1"], ["i1"], ["p1"], ["s1"], ["e1"], False),+ ("several-start-callables-keep-their-order", [], [], [], ["s1", "s2", "s3"], [], False),+ ("start-callables-before-end-callables", [], [], [], ["s1"], ["e1"], False),+ # Defaults are read at CALL time, and a scope can switch them off without unsetting them.+ ("skip-defaults-drops-only-the-defaults", ["d1", "d2"], ["i1"], ["p1"], [], [], True),+ ("skip-defaults-with-nothing-else", ["d1"], [], [], [], [], True),+]+++#: (case, chain of (name, implemented events, behaviour), event dispatched, raise_errors).+HOOK_DISPATCH_CASES = [+ ("every-hook-in-order", [("a", ["on_predict_start"], None), ("b", ["on_predict_start"], None),+ ("c", ["on_predict_start"], None)], "on_predict_start", True),+ # A hook implementing a different subset is SKIPPED for this event, not an error.+ ("a-hook-that-does-not-implement-the-event-is-skipped",+ [("a", ["on_predict_start"], None), ("b", ["on_predict_end"], None),+ ("c", ["on_predict_start"], None)], "on_predict_start", True),+ ("no-hook-implements-the-event",+ [("a", ["on_predict_end"], None)], "on_route", True),+ # Under `raise_errors` the chain STOPS at the first failure; the hooks after it never run.+ ("raising-stops-the-chain",+ [("a", ["on_predict_start"], None), ("b", ["on_predict_start"], "raise"),+ ("c", ["on_predict_start"], None)], "on_predict_start", True),+ # With it off the failure is a warning and the rest of the chain still runs, which is what a+ # telemetry hook needs: it must not be able to fail the request.+ ("raise-errors-false-warns-and-continues",+ [("a", ["on_predict_start"], None), ("b", ["on_predict_start"], "raise"),+ ("c", ["on_predict_start"], None)], "on_predict_start", False),+ ("raise-errors-false-with-every-hook-failing",+ [("a", ["on_predict_start"], "raise"), ("b", ["on_predict_start"], "raise")],+ "on_predict_start", False),+ # `ctx.skip()` does NOT short-circuit the chain. It assigns `ctx.results`, and it is+ # `predict_batch` that reads it afterwards -- so every later start hook still runs and can+ # see, and overwrite, what the earlier one answered.+ ("skip-does-not-stop-the-chain",+ [("a", ["on_predict_start"], "skip:1"), ("b", ["on_predict_start"], None)],+ "on_predict_start", True),+ ("the-other-four-events-dispatch-the-same-way",+ [("a", ["on_route", "on_load", "on_evict", "on_error"], None),+ ("b", ["on_route"], None)], "on_route", True),+ ("on-error-dispatches-over-the-same-chain",+ [("a", ["on_error"], None), ("b", ["on_error"], "raise")], "on_error", False),+ ("on-predict-end-dispatches-over-the-same-chain",+ [("a", ["on_predict_end"], None), ("b", ["on_predict_end"], None)], "on_predict_end", True),+]+++#: (case, state count, result count handed to `ctx.skip`).+HOOK_SKIP_CASES = [+ ("one-result-per-state", 3, 3),+ ("one-result-for-the-whole-call", 3, 1),+ ("one-state-one-result", 1, 1),+ # Two results for one state is neither shape, and it is the shape that silently dropped rows+ # the caller was about to zip against.+ ("two-results-for-one-state", 1, 2),+ ("too-few-results", 3, 2),+ ("no-results-at-all", 3, 0),+ ("too-many-results", 2, 5),+ # An empty call: zero is both "one per state" and "none", so it is accepted.+ ("no-states-no-results", 0, 0),+ ("no-states-one-result", 0, 1),+ ("no-states-two-results", 0, 2),+]+++#: (case, per-result usage blocks).+HOOK_USAGE_CASES = [+ ("one-result", [{"input_tokens": 11, "output_tokens": 0}]),+ ("several-results-sum", [{"input_tokens": 11, "output_tokens": 1},+ {"input_tokens": 22, "output_tokens": 2},+ {"input_tokens": 33, "output_tokens": 3}]),+ ("no-results-at-all", []),+ ("zeroes", [{"input_tokens": 0, "output_tokens": 0}]),+ # The reference coerces, because a result dict is a plain dict a hook may have rewritten.+ ("a-missing-usage-block", [{}]),+ ("a-null-usage-block", [{"__usage_is_none__": True}]),+ ("a-missing-key", [{"input_tokens": 7}]),+ ("a-null-value", [{"input_tokens": 7, "output_tokens": None}]),+ ("a-float-is-truncated", [{"input_tokens": 7.9, "output_tokens": 0}]),+]+++#: Values offered to `validate_timeout`.+HOOK_TIMEOUT_VALUES = [None, 1, 1.5, 0.05, "0.5", 0, 0.0, -1, -0.5,+ float("nan"), float("inf"), float("-inf")]+++#: (case, scripted registry operations). `enter`/`exit` bracket a `hooks_installed` block.+HOOK_REGISTRY_CASES = [+ ("add-keeps-insertion-order", ["add:a", "add:b", "add:c"]),+ ("add-a-sequence-at-once", ["add:[a,b]", "add:c"]),+ # The same instance twice is two installations, and removing by identity takes both.+ ("the-same-hook-twice", ["add:a", "add:a"]),+ ("remove-by-identity", ["add:a", "add:b", "remove:a"]),+ ("remove-takes-every-copy", ["add:a", "add:a", "add:b", "remove:a"]),+ ("remove-something-never-installed", ["add:a", "remove:b"]),+ ("a-block-installs-and-restores", ["enter:1:[t]", "exit:1"]),+ # The rule `_remove_instances` exists for: the application had already installed `a`, so the+ # block's exit must take ONE copy -- its own, the most recent -- and leave the other.+ ("a-block-over-an-already-installed-hook", ["add:a", "enter:1:[a]", "exit:1"]),+ # Two overlapping blocks. Restoring a snapshot would make the first exit remove the second+ # block's hook; taking one occurrence each does not.+ ("overlapping-blocks", ["enter:1:[x]", "enter:2:[y]", "exit:2", "exit:1"]),+ ("overlapping-blocks-exited-outermost-first",+ ["enter:1:[x]", "enter:2:[y]", "exit:1", "exit:2"]),+ # A hook added with add_hook INSIDE a block is not in any snapshot and must survive the exit.+ ("add-inside-a-block-survives-the-exit", ["enter:1:[t]", "add:d", "exit:1"]),+ ("a-block-with-several-arguments", ["enter:1:[x],[y,z]", "exit:1"]),+ ("a-block-with-nothing-in-it", ["enter:1:", "exit:1"]),+]+++#: (case, default hooks, installed hooks, per-call hooks, states, question ids, hooks_raise,+#: whether the stubbed inference itself raises). Each hook is `(name, {event: behaviour})` and+#: implements EVERY event, so the log says exactly which events fired and in which order --+#: which event a hook implements is the dispatch section's subject, not this one's.+HOOK_PREDICT_CASES = [+ ("no-hooks", [], [], [], ["s0"], ["q"], True, False),+ # Question ids that are NOT in alphabetical order, deliberately: a choice's options are+ # positional and a question map is iterated, so a port that re-sorts the mapping on the way+ # into the context asks a different question than the caller wrote -- and with ids like+ # "q", "r" it would still compare clean.+ ("a-start-hook-sees-the-call", [], [], [("p", {})], ["s0", "s1"], ["urgent", "intent"],+ True, False),+ # Order end to end: a default, an installed and a per-call hook all fire, in that order, for+ # both events -- and `compose_hooks` reads the defaults at CALL time, not at construction.+ ("default-installed-and-per-call-all-fire", [("d", {})], [("i", {})], [("p", {})], ["s0"],+ ["q"], True, False),+ # A start hook rewrites the call, and it is the REWRITTEN value inference is handed.+ ("a-start-hook-rewrites-the-states", [], [], [("p", {"on_predict_start": "states:x,y,z"})],+ ["s0"], ["q"], True, False),+ # Two ids, out of alphabetical order, so a port that re-sorts the rewritten mapping on the+ # way back onto the context differs here rather than passing on a one-question rewrite.+ ("a-start-hook-rewrites-the-questions", [], [],+ [("p", {"on_predict_start": "questions:urgent,intent"})], ["s0"], ["q", "r"], True, False),+ ("a-start-hook-sets-the-token-budget", [], [], [("p", {"on_predict_start": "max_len:128"})],+ ["s0"], ["q"], True, False),+ ("a-start-hook-sets-the-head-budget", [], [],+ [("p", {"on_predict_start": "head_max_len:64"})], ["s0"], ["q"], True, False),+ # `ctx.skip()` short-circuits inference: the stub is never called and the hook's own payload+ # is what comes back.+ ("skip-answers-the-call", [], [], [("p", {"on_predict_start": "skip:1"})], ["s0"], ["q"],+ True, False),+ ("skip-one-per-state", [], [], [("p", {"on_predict_start": "skip:2"})], ["s0", "s1"], ["q"],+ True, False),+ ("skip-one-for-the-whole-call", [], [], [("p", {"on_predict_start": "skip:1"})],+ ["s0", "s1"], ["q"], True, False),+ ("skip-with-a-count-that-fits-nothing", [], [], [("p", {"on_predict_start": "skip:3"})],+ ["s0", "s1"], ["q"], True, False),+ # A later start hook can overwrite what an earlier one answered, because `ctx.skip` assigns+ # and dispatch does not stop.+ ("the-last-skip-wins", [], [], [("p", {"on_predict_start": "skip:1"}),+ ("p2", {"on_predict_start": "skip:2"})],+ ["s0", "s1"], ["q"], True, False),+ # An end hook may replace the whole result list, and that is the return value.+ ("an-end-hook-rewrites-the-results", [], [], [("p", {"on_predict_end": "results:1"})],+ ["s0"], ["q"], True, False),+ # A throwing hook, under each policy and at each end of the call.+ ("a-raising-start-hook-fails-the-call", [], [], [("p", {"on_predict_start": "raise"}),+ ("p2", {})], ["s0"], ["q"], True, False),+ ("a-raising-start-hook-is-only-a-warning", [], [], [("p", {"on_predict_start": "raise"}),+ ("p2", {})], ["s0"], ["q"], False, False),+ ("a-raising-end-hook-fails-the-call", [], [], [("p", {"on_predict_end": "raise"})], ["s0"],+ ["q"], True, False),+ ("a-raising-end-hook-is-only-a-warning", [], [], [("p", {"on_predict_end": "raise"})],+ ["s0"], ["q"], False, False),+ # Inference itself fails: on_error runs, then on_predict_end runs ANYWAY, with the error on+ # the context and `ctx.results` still None.+ ("inference-fails", [], [], [("p", {})], ["s0"], ["q"], True, True),+ # A failing on_error hook must not replace the failure that triggered it.+ ("inference-fails-with-a-raising-error-hook", [], [], [("p", {"on_error": "raise"})], ["s0"],+ ["q"], True, True),+ # A failing end hook on the FAILURE path must not mask the real error either.+ ("inference-fails-with-a-raising-end-hook", [], [], [("p", {"on_predict_end": "raise"})],+ ["s0"], ["q"], True, True),+ # The empty call: no inference, an empty result list, and the end hook still sees it.+ ("no-states", [], [], [("p", {})], [], ["q"], True, False),+]+++#: The lifecycle event names, in the reference's own order, asserted against `HOOK_EVENTS` rather+#: than imported: the ORDER is what a port's enum has to agree with, and importing it would make+#: a reordering invisible here.+HOOK_EVENT_NAMES = ["on_predict_start", "on_predict_end", "on_route", "on_load", "on_evict",+ "on_error"]+++def _hook_name_of(entry):+ """The label the fixture gives one entry of a composed hook list."""+ kind = type(entry).__name__+ if kind in ("_StartAdapter", "_EndAdapter"):+ return ("start:" if kind == "_StartAdapter" else "end:") + entry.fn.laya_stub_name+ return getattr(entry, "stub_name", kind)+++def _named_callable(name):+ """A plain `on_predict_start=` / `on_predict_end=` callable, labelled for the fixture."""+ def fn(ctx):+ return None+ fn.laya_stub_name = name+ return fn+++def hook_dispatch():+ """`laya.hooks`: what runs, in what order, and what each hook is allowed to change.++ Hooks are the one place a caller's own code runs inside a prediction, so every observable+ here is a contract a port has to reproduce exactly. The sections below are chosen so a port+ that gets any of them wrong differs somewhere:++ * ORDER. `compose_hooks` is defaults, then installed, then per-call, and `dispatch` calls+ them in that order. A port that composes the other way round still runs every hook, so+ nothing fails -- except that the tracer a caller installed to see what the per-call hook+ did now runs first and sees nothing.+ * `ctx.skip()` assigns `ctx.results` and does NOT stop the chain. The short-circuit is+ `predict_batch` reading `ctx.results` afterwards, so a later start hook still runs and+ can overwrite the answer. A port that returns early from dispatch loses that.+ * `hooks_raise`. True fails the request at the first throwing hook and the rest of the+ chain never runs; False warns, with a message quoting the hook's class and event, and+ continues. Both ends of the call, and the failure path, are recorded.+ * what a hook SEES. The states, the questions, the model, the token-budget overrides, the+ run id shared across one call's hooks, and -- at the end -- the aggregated usage, the+ elapsed time and the error. A port that builds the context late, or rebuilds it per+ event, breaks the identity those depend on.+ * `ctx.skip()`'s count check. One result for the whole call or one per state, nothing else,+ refused INSIDE the hook under the caller's own `hooks_raise` rather than downstream --+ where it had been an `IndexError` the server mapped to a 500, and a short list+ `predict_batch` returned while the caller zipped it against their states.++ Inference is stubbed, so this family needs no checkpoint and no graph: `ONNXAgent.predict_batch`+ is driven unbound over a stub that carries only what it touches. That is also what makes the+ "skip answers the call" cases legible -- whether the model ran is recorded, not inferred.+ """+ import threading+ import warnings++ from laya.hooks import (+ HOOK_EVENTS, HookRegistry, PredictContext, _as_sequence, add_default_hook,+ aggregate_usage, clear_default_hooks, compose_hooks, default_hooks, dispatch,+ normalise_hooks, set_default_hooks, validate_timeout,+ )+ from laya.hooks import _SKIP_DEFAULTS++ assert list(HOOK_EVENTS) == HOOK_EVENT_NAMES, (+ "the lifecycle events moved: %r" % (HOOK_EVENTS,))++ # -- composition order ---------------------------------------------------+ composition = []+ for (cid, defaults, installed, per_call, starts, ends, skip_defaults) in \+ HOOK_COMPOSITION_CASES:+ log = []+ clear_default_hooks()+ set_default_hooks([_stub_hook(log, n, HOOK_EVENT_NAMES) for n in defaults])+ token = _SKIP_DEFAULTS.set(True) if skip_defaults else None+ try:+ active = compose_hooks(+ [_stub_hook(log, n, HOOK_EVENT_NAMES) for n in installed],+ [_stub_hook(log, n, HOOK_EVENT_NAMES) for n in per_call],+ [_named_callable(n) for n in starts],+ [_named_callable(n) for n in ends])+ finally:+ if token is not None:+ _SKIP_DEFAULTS.reset(token)+ clear_default_hooks()+ composition.append({+ "case": cid, "defaults": defaults, "installed": installed, "hooks": per_call,+ "on_predict_start": starts, "on_predict_end": ends,+ "skip_defaults": skip_defaults,+ "order": [_hook_name_of(entry) for entry in active],+ })++ # `default_hooks()` hands back a COPY: a caller that mutates it must not be editing the+ # process-wide list, which is the difference between a read and a handle.+ clear_default_hooks()+ probe = _stub_hook([], "probe", HOOK_EVENT_NAMES)+ set_default_hooks([probe])+ defaults_api = {"after_set": [_hook_name_of(h) for h in default_hooks()]}+ borrowed = default_hooks()+ borrowed.append(_stub_hook([], "intruder", HOOK_EVENT_NAMES))+ defaults_api["mutating_the_returned_list_changes_nothing"] = [+ _hook_name_of(h) for h in default_hooks()]+ add_default_hook(_stub_hook([], "added", HOOK_EVENT_NAMES))+ defaults_api["after_add"] = [_hook_name_of(h) for h in default_hooks()]+ clear_default_hooks()+ defaults_api["after_clear"] = [_hook_name_of(h) for h in default_hooks()]++ # -- what normalise_hooks refuses ---------------------------------------+ class _NotAHook(object):+ pass++ class _NotCallable(object):+ on_predict_start = "not a function"++ refusals = []+ for label, argument in (("a class rather than an instance", _NotAHook),+ ("an object implementing no event", _NotAHook()),+ ("an event attribute that is not callable", _NotCallable()),+ ("a plain object", object())):+ try:+ normalise_hooks(argument)+ refusals.append({"input": label, "error": None})+ except TypeError as problem:+ refusals.append({"input": label, "error": str(problem)})+ for label, argument in (("a non-callable on_predict_start", 7),+ ("a non-callable on_predict_end", "nope")):+ try:+ if "start" in label:+ normalise_hooks(None, argument, None)+ else:+ normalise_hooks(None, None, argument)+ refusals.append({"input": label, "error": None})+ except TypeError as problem:+ refusals.append({"input": label, "error": str(problem)})++ # `_as_sequence`: one hook, a list of them, or nothing, flattened the same way.+ as_sequence = [+ {"input": "none", "length": len(_as_sequence(None))},+ {"input": "one", "length": len(_as_sequence(probe))},+ {"input": "list-of-two", "length": len(_as_sequence([probe, probe]))},+ {"input": "tuple-of-three", "length": len(_as_sequence((probe, probe, probe)))},+ {"input": "empty-list", "length": len(_as_sequence([]))},+ ]++ # -- dispatch ------------------------------------------------------------+ dispatched = []+ for cid, chain, event, raise_errors in HOOK_DISPATCH_CASES:+ log = []+ hooks = [_stub_hook(log, name, events, behaviour) for name, events, behaviour in chain]+ ctx = PredictContext(states=["s0"], questions=_hook_questions(["q"]))+ raised = None+ with warnings.catch_warnings(record=True) as caught:+ warnings.simplefilter("always")+ try:+ dispatch(hooks, event, ctx, raise_errors=raise_errors)+ except BaseException as problem:+ raised = {"type": type(problem).__name__, "message": str(problem)}+ dispatched.append({+ "case": cid, "event": event, "raise_errors": raise_errors,+ "chain": [{"name": name, "events": events, "behaviour": behaviour}+ for name, events, behaviour in chain],+ "calls": log, "raised": raised,+ "warnings": [str(w.message) for w in caught],+ "results": None if ctx.results is None else len(ctx.results),+ })++ # -- ctx.skip() ----------------------------------------------------------+ skips = []+ for cid, n_states, n_results in HOOK_SKIP_CASES:+ ctx = PredictContext(states=["s%d" % i for i in range(n_states)],+ questions=_hook_questions(["q"]))+ try:+ ctx.skip([_hook_result(i) for i in range(n_results)])+ skips.append({"case": cid, "states": n_states, "results": n_results,+ "accepted": True, "error": None,+ "assigned": [r["usage"]["input_tokens"] for r in ctx.results]})+ except ValueError as problem:+ skips.append({"case": cid, "states": n_states, "results": n_results,+ "accepted": False, "error": str(problem),+ "assigned": None})++ # -- aggregate_usage -----------------------------------------------------+ usages = []+ for cid, blocks in HOOK_USAGE_CASES:+ results = []+ for block in blocks:+ if block.get("__usage_is_none__"):+ results.append({"usage": None})+ elif block:+ results.append({"usage": dict(block)})+ else:+ results.append({})+ usages.append({"case": cid, "results": blocks, "total": aggregate_usage(results)})++ # -- validate_timeout ----------------------------------------------------+ timeouts = []+ for value in HOOK_TIMEOUT_VALUES:+ entry = {"input": repr(value)}+ try:+ accepted = validate_timeout(value)+ entry["accepted"] = True+ entry["value"] = accepted+ entry["error"] = None+ except (ValueError, OverflowError) as problem:+ entry["accepted"] = False+ entry["value"] = None+ entry["error"] = str(problem)+ timeouts.append(entry)++ # -- HookRegistry --------------------------------------------------------+ registries = []+ for cid, script in HOOK_REGISTRY_CASES:+ class _Registry(HookRegistry):+ def __init__(self):+ self.hooks = ()+ self._hooks_mutex = threading.Lock()++ registry = _Registry()+ pool = {}++ def named(label):+ if label not in pool:+ pool[label] = _stub_hook([], label, HOOK_EVENT_NAMES)+ return pool[label]++ blocks = {}+ steps = []+ for op in script:+ verb, _, rest = op.partition(":")+ returned = None+ if verb == "add":+ if rest.startswith("["):+ registry.add_hook([named(x) for x in rest[1:-1].split(",") if x])+ else:+ registry.add_hook(named(rest))+ elif verb == "remove":+ returned = registry.remove_hook(named(rest))+ elif verb == "enter":+ block, _, arguments = rest.partition(":")+ groups = []+ for group in ([] if not arguments else arguments.split("],[")):+ labels = [x for x in group.strip("[]").split(",") if x]+ groups.append([named(x) for x in labels])+ manager = registry.hooks_installed(*groups)+ blocks[block] = manager+ manager.__enter__()+ elif verb == "exit":+ blocks.pop(rest).__exit__(None, None, None)+ else:+ raise AssertionError("unknown registry op %r" % (op,))+ steps.append({"op": op, "returned": returned,+ "hooks": [_hook_name_of(h) for h in registry.hooks]})+ for leftover in list(blocks.values()):+ leftover.__exit__(None, None, None)+ registries.append({"case": cid, "script": list(script), "steps": steps,+ "final": [_hook_name_of(h) for h in registry.hooks]})++ predicted = _hook_predict_cases()++ # The branches have to be REACHED. Every case below compares clean against a port that never+ # runs a hook at all, so a case list that stopped constructing a short-circuit, a refusal or+ # a failure would still be green -- which is the one outcome this family must not produce.+ reached = {+ "three-tier order": sum(1 for c in composition+ if c["defaults"] and c["installed"] and c["hooks"]+ and c["order"][:len(c["defaults"])] == c["defaults"]),+ "defaults skipped": sum(1 for c in composition if c["skip_defaults"] and c["defaults"]+ and not set(c["defaults"]) & set(c["order"])),+ "dispatch stopped early": sum(1 for c in dispatched if c["raised"]),+ "dispatch warned and continued": sum(1 for c in dispatched+ if c["warnings"] and not c["raised"]),+ "dispatch skipped a hook": sum(1 for c in dispatched+ if len(c["calls"]) < len(c["chain"])+ and not c["raised"]),+ "skip refused": sum(1 for c in skips if not c["accepted"]),+ "skip accepted": sum(1 for c in skips if c["accepted"]),+ "timeout refused": sum(1 for t in timeouts if not t["accepted"]),+ "block left a hook behind": sum(1 for r in registries if r["final"]),+ "block restored": sum(1 for r in registries if not r["final"]),+ "inference short-circuited": sum(1 for c in predicted if c["inference"] is None+ and c["raised"] is None),+ "inference saw a rewrite": sum(1 for c in predicted if c["inference"]+ and (c["inference"]["states"] != c["states"]+ or c["inference"]["questions"] != c["questions"]+ or c["inference"]["overrides"])),+ "call failed": sum(1 for c in predicted if c["raised"]),+ "call warned": sum(1 for c in predicted if c["warnings"]),+ "on_error fired": sum(1 for c in predicted+ if any(e["call"].endswith(".on_error") for e in c["calls"])),+ "a hook failure was attached, not substituted": sum(+ 1 for c in predicted if c["raised"] and c["raised"]["context"]),+ "an end hook saw the aggregated usage": sum(+ 1 for c in predicted+ if any(e["call"].endswith(".on_predict_end") and e["usage"] for e in c["calls"])),+ }+ thin = {name: count for name, count in reached.items() if count < 1}+ if thin or reached["skip refused"] < 4 or reached["inference short-circuited"] < 3:+ raise AssertionError(+ "the hook cases do not reach every branch this family exists to pin: %s"+ % ", ".join("%s=%d" % pair for pair in sorted(reached.items())))++ return {+ "events": HOOK_EVENT_NAMES,+ "composition": composition,+ "default_hooks_api": defaults_api,+ "normalise_refusals": refusals,+ "as_sequence": as_sequence,+ "dispatch": dispatched,+ "skip": skips,+ "usage": usages,+ "timeouts": timeouts,+ "registry": registries,+ "predict_batch": predicted,+ }+++def _hook_predict_cases():+ """`ONNXAgent.predict_batch` driven over a stubbed inference, one case per contract.++ Unbound over a stub that carries only what the method touches -- the hook list, the three+ policy fields, the model id and `_infer_batch` -- so this needs no checkpoint and no graph,+ and so the fixture can record whether the model was reached at all. That last part is the+ point of the `skip` cases: "inference did not run" is the observable, and inferring it from+ the payload would not distinguish a short-circuit from a model that happened to agree.+ """+ import warnings++ from laya.hooks import clear_default_hooks, set_default_hooks++ from laya.onnx_agent import ONNXAgent++ cases = []+ for (cid, defaults, installed, per_call, states, qids, hooks_raise,+ inference_raises) in HOOK_PREDICT_CASES:+ log = []+ seen = {}++ class Stub(object):+ """Everything `predict_batch` touches on `self`, and nothing else."""++ model_id = "stub-checkpoint"+ hooks_concurrent = True+ _hooks_lock = None++ def __init__(self):+ self.hooks = [_stub_hook(log, n, HOOK_EVENT_NAMES, b, observe=True)+ for n, b in installed]+ self.hooks_raise = hooks_raise+ self.hooks_timeout = None++ def _infer_batch(self, inner_states, inner_questions, lang=None, batch_size=None,+ sort_by_length=False, **overrides):+ seen["states"] = list(inner_states)+ seen["questions"] = list(inner_questions)+ seen["overrides"] = dict(overrides)+ if inference_raises:+ raise RuntimeError("the graph refused this batch")+ return [_hook_result(100 + i) for i in range(len(inner_states))]++ clear_default_hooks()+ if defaults:+ set_default_hooks([_stub_hook(log, n, HOOK_EVENT_NAMES, b, observe=True)+ for n, b in defaults])+ questions = _hook_questions(qids)+ raised = None+ results = None+ try:+ with warnings.catch_warnings(record=True) as caught:+ warnings.simplefilter("always")+ results = ONNXAgent.predict_batch(+ Stub(), list(states), questions,+ hooks=[_stub_hook(log, n, HOOK_EVENT_NAMES, b, observe=True)+ for n, b in per_call])+ except BaseException as problem:+ raised = {"type": type(problem).__name__, "message": str(problem),+ # The reference attaches a failing end/error hook to the real failure+ # rather than letting it replace it, so the original is still what the+ # caller catches and the hook's is reachable underneath.+ "context": None if problem.__context__ is None+ else type(problem.__context__).__name__}+ finally:+ clear_default_hooks()++ run_ids = {entry["run_id"] for entry in log}+ for entry in log:+ del entry["run_id"]+ cases.append({+ "case": cid,+ "defaults": [{"name": n, "behaviour": b} for n, b in defaults],+ "installed": [{"name": n, "behaviour": b} for n, b in installed],+ "hooks": [{"name": n, "behaviour": b} for n, b in per_call],+ "states": list(states), "questions": qids, "hooks_raise": hooks_raise,+ "inference_raises": inference_raises,+ # What the model was handed, or null when a hook answered before it ran.+ "inference": None if "states" not in seen else {+ "states": seen["states"], "questions": seen["questions"],+ "overrides": seen["overrides"]},+ "calls": log,+ "result": None if results is None else [r["usage"]["input_tokens"] for r in results],+ "raised": raised,+ "warnings": [str(w.message) for w in caught],+ # One context per call, shared by every hook of it: that is what lets a tracer+ # correlate a start with its end without threading state of its own.+ "one_run_id_per_call": len(run_ids) <= 1,+ "run_id_hex_length": len(next(iter(run_ids))) if run_ids else None,+ })+ return cases++def _decoder_shape(tokenizer_json):"""The decoder section's type chain, flattened, so the fixture says what it was recorded on."""import io@@ -3091,6 +3797,7 @@ def _decoder_shape(tokenizer_json):FAMILIES = {"confidence_gate.json": confidence_gate,+ "hooks.json": hook_dispatch,"predict_long.json": predict_long_scan,"window_plan.json": window_plan,"lang_tables.json": lang_tables,