Skip to content

armgit / laya

Public Imported from GitHub
0

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.

fix(java): what reviewing 1acb2e9 found, including a regression it introduced

Adeshina Lasisi743fc47c892d
diff --git a/.github/workflows/java.yml b/.github/workflows/java.yml
index d1844b8b..b777fd0d 100644
--- a/.github/workflows/java.yml
+++ b/.github/workflows/java.yml
@@ -154,17 +154,17 @@ jobs:
# Without LAYA_CHECKPOINTS the checkpoint-backed factories abort by assumption and the rest
# run. `--min-tests` is what stops an aborted suite from looking like a pass.
#
- # Measured on the merged tree: 983 register here, 966 run, 17 abort on a checkpoint this
+ # Measured on the merged tree: 991 register here, 974 run, 17 abort on a checkpoint this
# lane does not have. Exact, not padded -- the floor stood at 680 long enough for the real
# figure to pass it by, which is how a floor stops being one. ONE below the JDK-matrix
# lane's floor on purpose: that lane passes `-PtestJavaVersion`, which is what makes
- # `TestJvmVersionTest` run instead of skip, so it executes 967. Same suite, one more test,
+ # `TestJvmVersionTest` run instead of skip, so it executes 975. Same suite, one more test,
# because the flag enables it. The step below is where the number is justified.
- name: Tests that need no model
working-directory: laya-java
run: ./gradlew --no-daemon test
- # Measured on the merged tree, Corretto 17, no checkpoints: 983 registered, 17 abort,
- # 966 RUN -- the floor counts what ran, so the aborted checkpoint-backed cases are not in
+ # Measured on the merged tree, Corretto 17, no checkpoints: 991 registered, 17 abort,
+ # 974 RUN -- the floor counts what ran, so the aborted checkpoint-backed cases are not in
# it. The floor is EXACT, with no margin, which is a change from the margin-of-4 this
# replaced. A margin only binds classes larger than itself, and three classes in this lane
# run exactly ONE test (`DecoderTest`, `TypedDecisionsParityTest`, `WindowPlanTest`), so no
@@ -179,7 +179,7 @@ jobs:
if: ${{ !cancelled() }}
run: >
python laya-java/scripts/check_test_results.py
- laya-java/laya-java/build/test-results/test --min-tests 966 --allow-aborted
+ laya-java/laya-java/build/test-results/test --min-tests 974 --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
@@ -335,7 +335,7 @@ jobs:
# dropped, Gradle exits 0 and the floor alone exits 0 on 488 tests, having run JDK 17 twice
# and reported it as two JDKs. With `--require-passed` it exits 1.
#
- # 967, not the build lane's 966, and the one is the point: this lane runs one test MORE
+ # 975, not the build lane's 974, and the one is the point: this lane runs one test MORE
# than that one, because `TestJvmVersionTest` is `@EnabledIfSystemProperty` and only
# enabled here. Both are EXACT, with no margin, for the reason the build lane gives --
# three classes here run exactly one test, so no positive margin can bind them.
@@ -356,7 +356,7 @@ jobs:
if: ${{ !cancelled() }}
run: >
python laya-java/scripts/check_test_results.py
- laya-java/laya-java/build/test-results/test --min-tests 967 --allow-aborted
+ laya-java/laya-java/build/test-results/test --min-tests 975 --allow-aborted
--require-passed TestJvmVersionTest
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
if: ${{ failure() }}
diff --git a/.github/workflows/release-java.yml b/.github/workflows/release-java.yml
index 4dd3d2fa..e90a85cc 100644
--- a/.github/workflows/release-java.yml
+++ b/.github/workflows/release-java.yml
@@ -67,7 +67,7 @@ jobs:
# that lane already covered.
- name: Model-free tests
run: ./gradlew --no-daemon test
- # 966 of the 983 registered tests run without a checkpoint. This floor has been raised
+ # 974 of the 991 registered tests run without a checkpoint. This floor has been raised
# as the model-free suite grew -- 440 left 191 of slack, 625 left 60 -- because a floor
# that does not bind is not a gate: under 625 the whole confidence-gate family of 26
# tests could have vanished from this lane with the gate still green.
@@ -83,7 +83,7 @@ jobs:
- name: The suite was not vacuous
run: >
python3 scripts/check_test_results.py laya-java/build/test-results/test
- --min-tests 966 --allow-aborted
+ --min-tests 974 --allow-aborted
- name: Build the jars
run: ./gradlew --no-daemon build -x test
diff --git a/laya-java/README.md b/laya-java/README.md
index dfa9e513..e3645e9c 100644
--- a/laya-java/README.md
+++ b/laya-java/README.md
@@ -488,11 +488,13 @@ events no agent can:
| event | when |
|---|---|
| `onRoute` | after a checkpoint is chosen, from every branch of `route` |
-| `onLoad` | after a checkpoint is built by `load`, `lease`, `predict` or `preload` — not on a cache hit |
+| `onLoad` | after a checkpoint is built by `load`, `lease`, `predict` or `preload`, or attached while that build ran — not on a cache hit |
| `onEvict` | after one is dropped, by `maxLoaded`, `unload` or `unloadAll` — before the `onLoad` that caused it, as in the reference |
-`Router.predict` also dispatches one `onPredictStart`/`onPredictEnd` pair for the whole
-route-and-answer call, with `onLoad` and `onEvict` landing inside it. The agent's own pair still
+`Router.predict` also dispatches one `onPredictStart`/`onPredictEnd` pair for the answer. As in the
+reference, routing and loading run first, so the order is `onRoute`, any `onEvict`/`onLoad`, then
+the pair, and `elapsedMs` does not include a cold load. A routing or loading failure still reaches
+`onError` and `onPredictEnd`, with no start event. The agent's own pair still
fires for the forward pass, so a router-level hook and an agent-level hook see different spans.
Hooks are dispatched outside the router's lock, so a hook may call back into the router —
@@ -518,7 +520,7 @@ router.hooks().addHook(new Hook() {
| a process-wide default hook sees **two** predict pairs per `Router.predict` | the router's and the agent's. A metric that sums `usage()` on `on_predict_end` double-counts. Install on `router.hooks()` or `agent.hooks()`, not `Hooks.setDefaultHooks`, unless you want both |
| a throwing `on_evict` hook fails `Router.close()` | and the remaining evictions are not dispatched. In try-with-resources that masks the body's own failure |
| calling back into the router from `on_evict` **during `close()`** | throws `this Router is closed`: `close()` marks the router closed before unloading |
-| `concurrent(false)` with an `AsyncHook` whose callback calls back into the router or agent | deadlocks. Serial dispatch holds a lock across the callback, and the callback is on another thread, so the inner dispatch cannot re-enter that lock. A callback that does not call back in is fine |
+| `concurrent(false)` with an `AsyncHook` whose callback dispatches a hook on the same registry | deadlocks with no deadline, and stalls until it with one. Serial dispatch holds a lock across the callback, and the callback is on another thread, so the inner dispatch cannot re-enter that lock. A callback that dispatches nothing — `loaded()`, a cached `load` — is fine |
| `ctx.maxLen` / `ctx.headMaxLen`, and states past the first | ignored on the router path. `Agent.predict` takes no budget arguments, and the router answers one state |
`on_route` carries its own context, not the predict pair's, so `runId` differs between them. Correlate
diff --git a/laya-java/laya-java/src/main/java/com/convaiinnovations/laya/Router.java b/laya-java/laya-java/src/main/java/com/convaiinnovations/laya/Router.java
index c12aef5c..6485ae55 100644
--- a/laya-java/laya-java/src/main/java/com/convaiinnovations/laya/Router.java
+++ b/laya-java/laya-java/src/main/java/com/convaiinnovations/laya/Router.java
@@ -23,6 +23,7 @@ import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.ReentrantLock;
+import java.util.function.Supplier;
/**
* Decides which laya checkpoint a request should go to. A port of {@code laya.router}.
@@ -912,16 +913,19 @@ public final class Router implements AutoCloseable, Predictor {
public Agent load(String name) {
Checkpoint checkpoint = normaliseName(name);
Outcome outcome = new Outcome();
+ Slot slot;
try {
- Slot slot = acquire(checkpoint, outcome);
+ slot = acquire(checkpoint, outcome);
release(slot);
- return slot.agent;
- } finally {
- // `finally`: a build that published and then threw while closing the evicted agent
- // still loaded and still evicted, so both events are owed. After `release`, so a hook
- // calling back in does not find this call holding a lease.
- dispatchOutcome(checkpoint, outcome);
+ } catch (RuntimeException | Error failure) {
+ // A build that published and then threw while closing the evicted agent still loaded
+ // and still evicted, so both events are owed.
+ dispatchOwed(checkpoint, outcome, failure);
+ throw failure;
}
+ // After `release`, so a hook calling back in does not find this call holding a lease.
+ dispatchOutcome(checkpoint, outcome);
+ return slot.agent;
}
/**
@@ -1059,6 +1063,9 @@ public final class Router implements AutoCloseable, Predictor {
attached.leases++;
built = attached;
duplicate = true;
+ if (outcome != null) {
+ outcome.built = true; // the reference fires on_load here too
+ }
} else {
built = new Slot(agent, true);
built.leases++;
@@ -1306,7 +1313,8 @@ public final class Router implements AutoCloseable, Predictor {
try {
release(acquire(checkpoint, preloaded));
} catch (RuntimeException | Error failure) {
- // maxLoaded was raised above, so only a concurrent load can make this evict.
+ // maxLoaded was raised above, so only another load in flight -- another
+ // thread's, or one an on_load hook starts -- can make this evict.
dispatchOwed(checkpoint, preloaded, failure);
throw failure;
}
@@ -1347,14 +1355,22 @@ public final class Router implements AutoCloseable, Predictor {
lock.unlock();
}
if (inflight == null) {
- // `finally`: the eviction happened whether or not closing the agent threw, so the
- // event is owed either way. `closeAll` rethrows the first failure.
try {
closeAll(toClose);
- } finally {
+ } catch (RuntimeException | Error failure) {
+ // The evictions happened whether or not a close threw, so every event is
+ // owed, and a hook failure is attached to the close failure, not swapped.
for (Checkpoint evicted : freed) {
- dispatchLifecycle(Hooks.Event.EVICT, evicted);
+ try {
+ dispatchLifecycle(Hooks.Event.EVICT, evicted);
+ } catch (RuntimeException | Error hookFailure) {
+ failure.addSuppressed(hookFailure);
+ }
}
+ throw failure;
+ }
+ for (Checkpoint evicted : freed) {
+ dispatchLifecycle(Hooks.Event.EVICT, evicted);
}
return freed;
}
@@ -1385,10 +1401,20 @@ public final class Router implements AutoCloseable, Predictor {
if (inflights.isEmpty()) {
try {
closeAll(toClose);
- } finally {
+ } catch (RuntimeException | Error failure) {
+ // The evictions happened whether or not a close threw, so every event is
+ // owed, and a hook failure is attached to the close failure, not swapped.
for (Checkpoint evicted : freed) {
- dispatchLifecycle(Hooks.Event.EVICT, evicted);
+ try {
+ dispatchLifecycle(Hooks.Event.EVICT, evicted);
+ } catch (RuntimeException | Error hookFailure) {
+ failure.addSuppressed(hookFailure);
+ }
}
+ throw failure;
+ }
+ for (Checkpoint evicted : freed) {
+ dispatchLifecycle(Hooks.Event.EVICT, evicted);
}
return freed;
}
@@ -1434,7 +1460,7 @@ public final class Router implements AutoCloseable, Predictor {
/** Route this state and answer its questions, with per-call routing arguments. */
public Prediction predict(Object state, Map<String, Question> questions,
RouteOptions options) {
- return predict(route(state, questions, options), state, questions,
+ return predictRouted(() -> route(state, questions, options), state, questions,
options == null ? null : options.lang());
}
@@ -1446,42 +1472,51 @@ public final class Router implements AutoCloseable, Predictor {
*/
public Prediction predict(RouteDecision decision, Object state,
Map<String, Question> questions) {
- return predict(decision, state, questions, null);
+ requireNonNull(decision, "decision");
+ return predictRouted(() -> decision, state, questions, null);
}
- private Prediction predict(RouteDecision decision, Object state,
+ /**
+ * Route, load, then answer -- in the reference's order: {@code on_route}, then any
+ * {@code on_evict}/{@code on_load}, then the predict pair, with {@code elapsedMs} starting
+ * after the load. A routing or loading failure reaches {@code on_error} and
+ * {@code on_predict_end}, as it does inside the reference's {@code try}.
+ */
+ private Prediction predictRouted(Supplier<RouteDecision> decide, Object state,
Map<String, Question> questions, String lang) {
- requireNonNull(decision, "decision");
- // The language the checkpoint is told is the caller's if they gave one, else whatever
- // routing detected -- which is the reference's rule, and it matters: the multilingual
- // checkpoint takes a language and the detected one is the best available answer.
- String language = lang;
- if (language == null && decision.detection() != null) {
- language = decision.detection().language();
- }
List<Hook> composed = hooks.composeFor(HookCall.none());
if (composed.isEmpty()) {
- try (Lease lease = lease(decision.model())) {
- return lease.agent().predict(state, questions, language); // unchanged fast path
+ RouteDecision decision = decide.get();
+ try (Lease lease = lease(decision.model())) { // unchanged fast path
+ return lease.agent().predict(state, questions, languageFor(decision, lang));
}
}
+ Hooks.Policy policy = hooks.policyFor(HookCall.none());
+ RouteDecision decision = null;
+ Lease lease;
+ try {
+ decision = decide.get();
+ lease = lease(decision.model());
+ } catch (RuntimeException | Error failure) {
+ PredictContext failed = new PredictContext(Collections.singletonList(state), questions,
+ decision == null ? null : decision.model().wireName(), this);
+ Hooks.failedBeforeStart(composed, failed, policy, failure);
+ throw failure;
+ }
// `Hooks.around` so ctx.skip, the error-before-end order, failure suppression and
- // elapsed/usage all behave as they do on an Agent. The lease is taken inside it, so
- // on_load and on_evict land between this call's start and end events.
+ // elapsed/usage all behave as they do on an Agent.
//
// ctx.maxLen/headMaxLen are NOT forwarded: Agent.predict takes no budget arguments, so a
// Router-level start hook that sets one is ignored here.
- PredictContext ctx = new PredictContext(Collections.singletonList(state), questions,
- decision.model().wireName(), this);
- String resolved = language;
- Checkpoint target = decision.model();
- List<Prediction> answered = Hooks.around(composed, ctx,
- hooks.policyFor(HookCall.none()),
- (states, asked, maxLen, headMaxLen) -> {
- try (Lease lease = lease(target)) {
- return List.of(lease.agent().predict(states.get(0), asked, resolved));
- }
- });
+ String resolved = languageFor(decision, lang);
+ List<Prediction> answered;
+ try (Lease held = lease) {
+ PredictContext ctx = new PredictContext(Collections.singletonList(state), questions,
+ decision.model().wireName(), this);
+ answered = Hooks.around(composed, ctx, policy,
+ (states, asked, maxLen, headMaxLen) ->
+ List.of(held.agent().predict(states.get(0), asked, resolved)));
+ }
if (answered == null || answered.isEmpty()) {
// Only a hook can cause this, by skipping with no result. Inventing one would report
// a decision the model never made.
@@ -1491,6 +1526,18 @@ public final class Router implements AutoCloseable, Predictor {
return answered.get(0);
}
+ /**
+ * The language the checkpoint is told: the caller's if they gave one, else whatever routing
+ * detected -- the reference's rule, and it matters, because the multilingual checkpoint takes
+ * a language and the detected one is the best available answer.
+ */
+ private static String languageFor(RouteDecision decision, String lang) {
+ if (lang == null && decision.detection() != null) {
+ return decision.detection().language();
+ }
+ return lang;
+ }
+
/**
* Close the router, freeing every checkpoint it built.
*
diff --git a/laya-java/laya-java/src/main/java/com/convaiinnovations/laya/hooks/AsyncHook.java b/laya-java/laya-java/src/main/java/com/convaiinnovations/laya/hooks/AsyncHook.java
index 0794d30d..0e1c3305 100644
--- a/laya-java/laya-java/src/main/java/com/convaiinnovations/laya/hooks/AsyncHook.java
+++ b/laya-java/laya-java/src/main/java/com/convaiinnovations/laya/hooks/AsyncHook.java
@@ -25,8 +25,10 @@ import java.util.function.Consumer;
* running on an executor, so an overrunning callback keeps going. It is {@link
* PredictContext#abandon abandoned} instead, as {@link Hooks} does for a hook that overruns
* {@code hooks_timeout}: anything it writes to the context afterwards is refused. Unlike that
- * case the thread is pooled, so the abandonment ends when the overrunning task returns, and a
- * later callback of the same call on that thread is accepted. It still occupies the executor's
+ * case the executor's thread is reused, so the abandonment ends when the overrunning task
+ * returns, and a later callback of the same call on that thread is accepted; an abandonment
+ * made by anything else on that thread stays in force. A callback that had not started by the
+ * deadline never runs. It still occupies the executor's
* thread until it returns, so a single-threaded executor has none left for the next callback --
* size the executor for the deadline, or leave the deadline off.
*/
@@ -99,21 +101,31 @@ public final class AsyncHook implements Hook {
// The executor picks the thread, so the task reports it back: abandoning the context needs
// the thread that will be writing to it.
AtomicReference<Thread> runner = new AtomicReference<>();
- // Guards abandon against the task finishing: abandoning a thread whose task has already
- // returned would refuse whatever that pooled thread runs for this call next.
+ // One gate decides start, expiry, abandon and release, so none of them races another: a
+ // task starting at the deadline does not run unabandoned, a task finishing at it does not
+ // stay abandoned, and only an abandonment made here is released here.
Object gate = new Object();
+ boolean[] gaveUp = new boolean[1];
boolean[] finished = new boolean[1];
+ boolean[] abandonedHere = new boolean[1];
CompletableFuture<Void> running;
try {
running = CompletableFuture.runAsync(() -> {
Thread self = Thread.currentThread();
- runner.set(self);
+ synchronized (gate) {
+ if (gaveUp[0]) {
+ return; // the call gave up before this started
+ }
+ runner.set(self);
+ }
try {
callback.accept(ctx);
} finally {
synchronized (gate) {
finished[0] = true;
- ctx.release(self);
+ if (abandonedHere[0]) {
+ ctx.release(self);
+ }
}
}
}, executor);
@@ -142,9 +154,11 @@ public final class AsyncHook implements Hook {
// cancel(true) cannot interrupt a task already running on an executor, so the callback
// is cut off from the call instead: whatever it writes from here on is refused.
synchronized (gate) {
+ gaveUp[0] = true;
Thread overrunning = runner.get();
if (overrunning != null && !finished[0]) {
ctx.abandon(overrunning);
+ abandonedHere[0] = true;
}
}
running.cancel(true);
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.java
index dd595718..6cb3011e 100644
--- 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.java
@@ -28,8 +28,9 @@ package com.convaiinnovations.laya.hooks;
* for a callback that must run on a particular thread. It is not a way to make a slow hook
* free: the prediction still waits, as the reference's does.
*
- * <p>A hook runs on the calling thread, or an {@code AsyncHook}'s executor while the caller
- * waits, so it is as thread-safe as the call around it. Install
+ * <p>A hook runs on the calling thread, on the thread a {@link Hooks.Policy#timeout()} runs it
+ * on, or on an {@code AsyncHook}'s executor, and in each case the caller waits for it until a
+ * deadline expires -- so until it overruns, 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.
*/
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.java
index 71955e07..e0bde893 100644
--- 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.java
@@ -766,4 +766,25 @@ public final class Hooks {
}
return ctx.results();
}
+
+ /**
+ * Reports a failure that happened before {@code on_predict_start} could fire -- routing or
+ * loading, which the reference runs inside its predict {@code try} -- as {@code on_error} and
+ * then {@code on_predict_end}. A hook failure is attached to {@code problem}, never substituted.
+ */
+ public static void failedBeforeStart(List<? extends Hook> hooks, PredictContext ctx,
+ Policy policy, Throwable problem) {
+ ctx.error(problem);
+ try {
+ dispatch(hooks, Event.ERROR, ctx, policy);
+ } catch (RuntimeException | Error hookFailure) {
+ problem.addSuppressed(hookFailure);
+ }
+ ctx.elapsedMs((System.nanoTime() - ctx.startedAt()) / 1_000_000.0);
+ try {
+ dispatch(hooks, Event.PREDICT_END, ctx, policy);
+ } catch (RuntimeException | Error hookFailure) {
+ problem.addSuppressed(hookFailure);
+ }
+ }
}
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.java
index a7342944..3fa12769 100644
--- 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.java
@@ -7,7 +7,6 @@ import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
-import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
@@ -66,7 +65,9 @@ public final class PredictContext {
* <p>Empty for every call that does not use {@link Hooks.Policy#timeout}, and at most one
* entry per overrun. A set rather than a flag because a chain can overrun more than once.
*/
- private final Set<Thread> abandoned = ConcurrentHashMap.newKeySet();
+ // A count, not a set: a hook abandoned by Hooks can call an AsyncHook that abandons and
+ // releases the same thread, and that release must not cancel the outer abandonment.
+ private final Map<Thread, Integer> abandoned = new ConcurrentHashMap<>();
/**
* A context for one call.
@@ -309,19 +310,20 @@ public final class PredictContext {
* call stops being able to wait for it. See {@link #states(List)}.
*/
void abandon(Thread runner) {
- abandoned.add(runner);
+ abandoned.merge(runner, 1, Integer::sum);
}
/**
- * Undoes {@link #abandon} once the overrunning task has returned, so a pooled thread that
- * runs this call's next callback is not refused for the previous one's overrun.
+ * Undoes one {@link #abandon} once the overrunning task has returned, so a pooled thread that
+ * runs this call's next callback is not refused for the previous one's overrun. Only the
+ * caller that abandoned may release, and abandonments of one thread nest.
*/
void release(Thread runner) {
- abandoned.remove(runner);
+ abandoned.computeIfPresent(runner, (thread, count) -> count == 1 ? null : count - 1);
}
private void refuseIfAbandoned(String what) {
- if (!abandoned.isEmpty() && abandoned.contains(Thread.currentThread())) {
+ if (!abandoned.isEmpty() && abandoned.containsKey(Thread.currentThread())) {
throw new IllegalStateException(String.format(
"laya: hook thread %s exceeded its deadline and was abandoned; this call has "
+ "moved on, so ctx.%s() is refused rather than applied to it",
diff --git a/laya-java/laya-java/src/test/java/com/convaiinnovations/laya/AsyncHookTest.java b/laya-java/laya-java/src/test/java/com/convaiinnovations/laya/AsyncHookTest.java
index 7edec9a8..73ff48b1 100644
--- a/laya-java/laya-java/src/test/java/com/convaiinnovations/laya/AsyncHookTest.java
+++ b/laya-java/laya-java/src/test/java/com/convaiinnovations/laya/AsyncHookTest.java
@@ -8,6 +8,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
import com.convaiinnovations.laya.hooks.AsyncHook;
import com.convaiinnovations.laya.hooks.Hook;
+import com.convaiinnovations.laya.hooks.Hooks;
import com.convaiinnovations.laya.hooks.PredictContext;
import java.time.Duration;
import java.util.ArrayList;
@@ -154,31 +155,87 @@ class AsyncHookTest {
// the release, that thread stayed abandoned for this context and the write was refused.
ExecutorService pool = Executors.newSingleThreadExecutor();
try {
- Hook slow = AsyncHook.of(new Hook() {
- @Override
- public void onPredictStart(PredictContext c) {
- try {
- Thread.sleep(300);
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- }
- }
- }, pool, Duration.ofMillis(50));
- Hook later = AsyncHook.of(new Hook() {
- @Override
- public void onPredictEnd(PredictContext c) {
- c.states(List.of("written by the next callback"));
- }
- }, pool);
- PredictContext ctx = ctx();
- assertThrows(IllegalStateException.class, () -> slow.onPredictStart(ctx));
- later.onPredictEnd(ctx); // queued behind the overrun, then runs
- assertEquals(List.of("written by the next callback"), ctx.states());
+ assertReleasedAfterOverrun(pool, false);
+ } finally {
+ pool.shutdownNow();
+ }
+ }
+
+ @Test
+ @DisplayName("the release also happens when the overrunning callback throws")
+ void aPooledThreadIsReleasedWhenTheOverrunThrows() {
+ ExecutorService pool = Executors.newSingleThreadExecutor();
+ try {
+ assertReleasedAfterOverrun(pool, true);
} finally {
pool.shutdownNow();
}
}
+ private static void assertReleasedAfterOverrun(ExecutorService pool, boolean overrunThrows) {
+ AtomicReference<Thread> overran = new AtomicReference<>();
+ AtomicReference<Thread> next = new AtomicReference<>();
+ Hook slow = AsyncHook.of(new Hook() {
+ @Override
+ public void onPredictStart(PredictContext c) {
+ overran.set(Thread.currentThread());
+ try {
+ Thread.sleep(300);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ if (overrunThrows) {
+ throw new IllegalStateException("the overrun failed as well");
+ }
+ }
+ }, pool, Duration.ofMillis(50));
+ Hook later = AsyncHook.of(new Hook() {
+ @Override
+ public void onPredictEnd(PredictContext c) {
+ next.set(Thread.currentThread());
+ c.states(List.of("written by the next callback"));
+ }
+ }, pool);
+ PredictContext ctx = ctx();
+ assertThrows(IllegalStateException.class, () -> slow.onPredictStart(ctx));
+ later.onPredictEnd(ctx); // queued behind the overrun, then runs
+ assertSame(overran.get(), next.get(), "the point is the SAME pooled thread");
+ assertEquals(List.of("written by the next callback"), ctx.states());
+ }
+
+ @Test
+ @DisplayName("an AsyncHook on an abandoned thread does not lift that abandonment")
+ void anOuterAbandonmentSurvivesAnInnerAsyncHook() throws Exception {
+ // Hooks abandons its timeout thread; that thread then runs an AsyncHook on a direct
+ // executor -- the same thread -- which must not release what it did not abandon.
+ CountDownLatch done = new CountDownLatch(1);
+ AtomicReference<String> outcome = new AtomicReference<>();
+ Hook inner = AsyncHook.of(new Hook() { }, Runnable::run);
+ Hook outer = new Hook() {
+ @Override
+ public void onPredictStart(PredictContext c) {
+ try {
+ Thread.sleep(200); // overruns the 50ms policy deadline
+ inner.onPredictEnd(c);
+ c.states(List.of("late write"));
+ outcome.set("accepted");
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ } catch (RuntimeException refused) {
+ outcome.set("refused");
+ } finally {
+ done.countDown();
+ }
+ }
+ };
+ PredictContext ctx = ctx();
+ assertThrows(RuntimeException.class, () -> Hooks.dispatch(List.of(outer),
+ Hooks.Event.PREDICT_START, ctx, Hooks.Policy.raising().timeout(Duration.ofMillis(50))));
+ assertTrue(done.await(3, TimeUnit.SECONDS));
+ assertEquals("refused", outcome.get());
+ assertEquals(List.of("state"), ctx.states());
+ }
+
@Test
@DisplayName("a non-positive timeout is refused rather than meaning 'never wait'")
void refusesANonPositiveTimeout() {
diff --git a/laya-java/laya-java/src/test/java/com/convaiinnovations/laya/RouterHooksTest.java b/laya-java/laya-java/src/test/java/com/convaiinnovations/laya/RouterHooksTest.java
index 79596efc..10f7603f 100644
--- a/laya-java/laya-java/src/test/java/com/convaiinnovations/laya/RouterHooksTest.java
+++ b/laya-java/laya-java/src/test/java/com/convaiinnovations/laya/RouterHooksTest.java
@@ -14,6 +14,7 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
@@ -57,6 +58,11 @@ class RouterHooksTest {
public void onPredictEnd(PredictContext ctx) {
note("end", ctx);
}
+
+ @Override
+ public void onError(PredictContext ctx) {
+ note("error", ctx);
+ }
}
private static final class StubAgents implements Router.AgentFactory {
@@ -149,11 +155,11 @@ class RouterHooksTest {
trace.events.toString());
assertEquals(1, trace.events.stream().filter(e -> e.startsWith("end:")).count(),
trace.events.toString());
- // on_route first, then on_load inside the predict pair -- the reference's order.
- // Derived from the trace, not hard-coded: which checkpoint answers is the default's
- // business, and this test is about the sequence.
+ // The reference's order: route and load run BEFORE on_predict_start, so elapsed_ms
+ // excludes the cold load. Derived from the trace, not hard-coded: which checkpoint
+ // answers is the default's business, and this test is about the sequence.
List<String> kinds = trace.events.stream().map(e -> e.split(":")[0]).toList();
- assertEquals(List.of("route", "start", "load", "end"), kinds,
+ assertEquals(List.of("route", "load", "start", "end"), kinds,
trace.events.toString());
}
}
@@ -282,6 +288,114 @@ class RouterHooksTest {
}
}
+ @Test
+ @DisplayName("a load failure in predict reaches on_error and on_predict_end, with no start")
+ void predictReportsALoadFailure(@TempDir Path root) throws IOException {
+ Trace trace = new Trace();
+ Router.AgentFactory broken = checkpoint -> {
+ throw new IllegalStateException("no weights here");
+ };
+ try (Router router = Router.builder().agents(broken).build()) {
+ router.hooks().addHook(trace);
+ IllegalStateException thrown = assertThrows(IllegalStateException.class,
+ () -> router.predict("hello", questions()));
+ assertEquals("no weights here", thrown.getMessage());
+ List<String> kinds = trace.events.stream().map(e -> e.split(":")[0]).toList();
+ assertEquals(List.of("route", "error", "end"), kinds, trace.events.toString());
+ }
+ }
+
+ @Test
+ @DisplayName("a routing failure in predict reaches on_error and on_predict_end, as in the reference")
+ void predictReportsARouteFailure(@TempDir Path root) throws IOException {
+ TinyCheckpoint.write(root, 64, 32);
+ Trace trace = new Trace();
+ try (Router router = Router.builder().agents(new StubAgents(root)).build()) {
+ router.hooks().addHook(trace);
+ assertThrows(RuntimeException.class, () -> router.predict("hello", questions(),
+ Router.RouteOptions.none().model("no-such-checkpoint")));
+ assertEquals(List.of("error:null", "end:null"), trace.events);
+ }
+ }
+
+ @Test
+ @DisplayName("load: a hook failing on the owed dispatch is attached to the close failure")
+ void loadDoesNotMaskTheCloseFailure(@TempDir Path root) throws IOException {
+ TinyCheckpoint.write(root, 64, 32);
+ try (Router router = Router.builder().agents(angryEnglish(root)).maxLoaded(1).build()) {
+ router.load("english");
+ router.hooks().addHook(throwsOnceOnEvict(new IllegalArgumentException("the sink refused it")));
+ IllegalStateException thrown =
+ assertThrows(IllegalStateException.class, () -> router.load("multilingual"));
+ assertEquals("a native close can fail", thrown.getMessage());
+ assertEquals(1, thrown.getSuppressed().length);
+ }
+ }
+
+ @Test
+ @DisplayName("unload: a hook failing on the owed dispatch is attached to the close failure")
+ void unloadDoesNotMaskTheCloseFailure(@TempDir Path root) throws IOException {
+ TinyCheckpoint.write(root, 64, 32);
+ try (Router router = Router.builder().agents(angryEnglish(root)).maxLoaded(2).build()) {
+ router.load("english");
+ router.hooks().addHook(throwsOnceOnEvict(new IllegalArgumentException("the sink refused it")));
+ IllegalStateException thrown =
+ assertThrows(IllegalStateException.class, () -> router.unload("english"));
+ assertEquals("a native close can fail", thrown.getMessage());
+ assertEquals(1, thrown.getSuppressed().length);
+ }
+ }
+
+ @Test
+ @DisplayName("an Error from a hook on the owed dispatch is attached too, not swapped in")
+ void anOwedHookErrorDoesNotMaskTheCloseFailure(@TempDir Path root) throws IOException {
+ TinyCheckpoint.write(root, 64, 32);
+ try (Router router = Router.builder().agents(angryEnglish(root)).maxLoaded(1).build()) {
+ router.load("english");
+ router.hooks().addHook(throwsOnceOnEvict(new AssertionError("an Error from a hook")));
+ IllegalStateException thrown =
+ assertThrows(IllegalStateException.class, () -> router.lease("multilingual"));
+ assertEquals("a native close can fail", thrown.getMessage());
+ assertTrue(thrown.getSuppressed()[0] instanceof AssertionError);
+ }
+ }
+
+ @Test
+ @DisplayName("on_load still fires when an attach wins the race with the build, as in the reference")
+ void loadDispatchesWhenAnAttachWinsTheRace(@TempDir Path root) throws IOException {
+ TinyCheckpoint.write(root, 64, 32);
+ Trace trace = new Trace();
+ AtomicReference<Router> self = new AtomicReference<>();
+ Router.AgentFactory racing = checkpoint -> {
+ // Attached while this build is in progress, so the build loses and is discarded.
+ self.get().attach("english",
+ TinyCheckpoint.agent(root, new TinyCheckpoint.RecordingSession()));
+ return TinyCheckpoint.agent(root, new TinyCheckpoint.RecordingSession());
+ };
+ try (Router router = Router.builder().agents(racing).maxLoaded(2).build()) {
+ self.set(router);
+ router.hooks().addHook(trace);
+ router.load("english");
+ assertEquals(List.of("load:english"), trace.events);
+ }
+ }
+
+ /** A hook whose first on_evict throws {@code failure}; later ones (from close()) do not. */
+ private static Hook throwsOnceOnEvict(Throwable failure) {
+ AtomicBoolean once = new AtomicBoolean();
+ return new Hook() {
+ @Override
+ public void onEvict(PredictContext ctx) {
+ if (once.compareAndSet(false, true)) {
+ if (failure instanceof Error error) {
+ throw error;
+ }
+ throw (RuntimeException) failure;
+ }
+ }
+ };
+ }
+
@Test
@DisplayName("a router with no hooks dispatches nothing and builds no context")
void noHooksNoDispatch(@TempDir Path root) throws IOException {