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
laya-go: router on_route hooks and hook registry
Adeshina Lasisi6373196508d0
diff --git a/laya-go/README.md b/laya-go/README.mdindex 8fe31dec..38351681 100644--- a/laya-go/README.md+++ b/laya-go/README.md@@ -5,7 +5,7 @@ modules. Running the model needs the nested `onnx` module, which uses cgo.The foundation (language detection, questions, sequences, the tokenizer) and the predict path(`infer`, `agent`) are here, and the `onnx` module runs the graph. The router's pure routing half-(`router`) is here; loading, hooks and routed inference come in later changes.+(`router`) and its `on_route` hooks are here; loading and routed inference come in later changes.| Package | What it is || --- | --- |@@ -13,7 +13,7 @@ The foundation (language detection, questions, sequences, the tokenizer) and the| `schema` | Questions (`Choice`, `ChoiceOf`, `Score`, `Noul`, `NoulWith`, `Questions`) and results (`Answer`, `Prediction`, `Usage`) every other package shares. Questions are refused with laya's own wording and read or written in the Python wire form. || `sequence` | `build_sequence`, `build_head`, `state_room`, `window_budget` and `window_batch_cap`: `EncodeState`, `Build`, `StateRoom`, `PlanWindows`, `BatchCap`. || `infer` | The seam to a model runtime: `Batch` (the graph's five inputs), `Output` (its two), `Session`, and the shape checks `Batch.Validate` and `Output.Check`. |-| `router` | Which checkpoint reads a request, the port of the routing half of `laya/router.py`: `New`, `Route`, `RouteBatch`, `NormaliseName`, `EnglishFromCode`, `MatchTypedDecisionsWorkflow`, `QuestionSchema`. Decisions carry laya's reason strings. Loads nothing. |+| `router` | Which checkpoint reads a request, the port of the routing half of `laya/router.py`: `New`, `Route`, `RouteBatch`, `NormaliseName`, `EnglishFromCode`, `MatchTypedDecisionsWorkflow`, `QuestionSchema`. Decisions carry laya's reason strings. `OnRoute` hooks (`AddHook`, `WithInstalledHooks`, `ForHooks`) may observe or replace a decision, under the agent's hook dispatcher. Loads nothing. || `agent` | `ONNXAgent.predict` and `predict_batch` over an `infer.Session`: `Open`, `Predict`, `PredictBatch`, `LoadConfig`, with batch size, sort-by-length and context cancellation between runs. || `onnx` | A nested module (cgo, its own `go.mod`): `onnx.Open` runs a fused `laya.onnx` on ONNX Runtime and implements `infer.Session`, for `agent.Open`. Needs an ONNX Runtime 1.29+ shared library; `CGO_ENABLED=0` builds and `Open` returns `ErrNoCGO`. || `tokenizer` | A reader and runner for Hugging Face `tokenizer.json` (BPE): normalizer, pre-tokenizer, added tokens, byte fallback, decoder. |diff --git a/laya-go/router/doc.go b/laya-go/router/doc.goindex 0b2ac910..0d6d1330 100644--- a/laya-go/router/doc.go+++ b/laya-go/router/doc.go@@ -1,7 +1,8 @@// Package router decides which Laya checkpoint should read a request. It is the routing half of// laya/router.py: Route and RouteBatch look at the state, the questions and the caller's hints and-// name a checkpoint and the reason, without loading or running anything. Loading, hooks and-// routed inference are separate changes.+// name a checkpoint and the reason, without loading or running anything. OnRoute hooks (see+// hooks.go) may observe or replace the decision. Loading and routed inference are separate+// changes.//// The checkpoints are English, Multilingual and TypedDecisions. The order of the evidence is// fixed, first match wins:@@ -16,12 +17,15 @@// Reason strings are part of the contract. They quote with Python's repr, round percentages half// to even and cut at 60 code points, so a decision here reads exactly as the Python router's.//-// A Router is immutable once built and safe for concurrent use.+// A Router is safe for concurrent use. Its routing is fixed once built; only its hook list changes+// (AddHook, RemoveHook, InstallHooks).//// # Differences from Python//// A name is a string: Python's str(name) of a non-string has no counterpart. Router.register and// the custom checkpoints are not ported, so the Router knows the three built-in names. A hint// callable is a LangHint returning "" to abstain. explain=True is not ported: lang.Analysis has no-// diagnostic field. Hooks (on_route) and the model lifecycle belong to later changes.+// diagnostic field. The model lifecycle (on_load,+// on_evict) belongs to a later change. Hooks run one at a time unless WithConcurrentHooks is given+// (Python's Router defaults to concurrent), and a hook failure names the hook's Go type.package routerdiff --git a/laya-go/router/example_test.go b/laya-go/router/example_test.goindex 46acb988..42e652ab 100644--- a/laya-go/router/example_test.go+++ b/laya-go/router/example_test.go@@ -66,3 +66,19 @@ func ExampleNormaliseName() {// typed-decisions// unknown model 'gpt'; choose one of ['english', 'multilingual', 'typed-decisions'] (or an alias: ['decisions', 'default', 'en', 'laya', 'laya-multilingual', 'laya-typed-decisions', 'ml', 'multi', 'typed', 'typed_decisions'])}++func ExampleRouter_AddHook() {+ r, _ := router.New()+ // A hook may replace the decision; Route returns the replacement.+ _ = r.AddHook(&router.HookFuncs{OnRouteFunc: func(c *router.RouteContext) {+ fmt.Println("saw", c.Decision.Model)+ if c.Decision.Model == router.English {+ c.Decision = router.Decision{Model: router.Multilingual, Repo: c.Decision.Repo, Reason: "pinned by policy"}+ }+ }})+ d, _ := r.Route("Please refund the duplicate charge from March.", schema.Questions{})+ fmt.Println(d.Model, "|", d.Reason)+ // Output:+ // saw english+ // multilingual | pinned by policy+}diff --git a/laya-go/router/hooks.go b/laya-go/router/hooks.gonew file mode 100644index 00000000..7d81ddce--- /dev/null+++ b/laya-go/router/hooks.go@@ -0,0 +1,298 @@+package router++// Hooks are laya/hooks.py for the one event a pure Router raises, on_route (on_load and on_evict+// arrive with loading). A hook is any value with an OnRoute method; the same value may also be an+// agent.Hook, as in Python, where one object implements several events. Each call of Route+// dispatches over: the process-wide agent.DefaultHooks (which take only an agent.Hook, so a+// hook that is both embeds agent.BaseHook), the Router's installed hooks, then the+// call's ForHooks, and a hook without OnRoute is skipped.+//+// The dispatch is agent.HookRun, the one the agent uses, so ordering, WithHookErrors,+// WithHookTimeout and panic recovery behave as there. Unlike Python's Router, whose hooks run+// concurrently unless hooks_concurrent=False, hooks run one at a time across all goroutines+// unless WithConcurrentHooks is given, as on the agent. A hook must not call Route on the+// Router that is running it while hooks are serial: Python's lock is re-entrant, this one is not.+//+// A hook may replace ctx.Decision; the replacement is what Route returns. Route does not check+// it: a Model that names no checkpoint is the hook's business, and the caller that loads it+// sees the error. A hook that overruns WithHookTimeout is abandoned, not stopped (see+// agent/hooks.go).++import (+ "context"+ "crypto/rand"+ "encoding/hex"+ "fmt"+ "log"+ "reflect"+ "sync"+ "time"++ "github.com/NandhaKishorM/laya/laya-go/agent"+ "github.com/NandhaKishorM/laya/laya-go/schema"+)++// RouteHook is a hook that sees the routing decision.+type RouteHook interface {+ // OnRoute runs after the Router has decided. It may replace ctx.Decision.+ OnRoute(ctx *RouteContext)+}++// RouteContext is what an OnRoute hook sees of one Route call. The hooks of a call share it and+// run one after another, so a replacement made by one is seen by the next.+type RouteContext struct {+ // States holds the one state being routed; rewriting it changes nothing.+ States []any+ // Questions are the questions asked, as passed to Route.+ Questions schema.Questions+ // RunID is 32 hex characters, shared by every hook of the call. It is not the prediction's.+ RunID string+ // Decision is the routing decision; assign to replace it.+ Decision Decision+ // Router is the Router that is routing.+ Router *Router+}++// BaseHook implements RouteHook with a no-op, for embedding.+type BaseHook struct{}++// OnRoute does nothing.+func (BaseHook) OnRoute(*RouteContext) {}++// HookFuncs is a RouteHook made of a function; nil is a no-op. Use it as *HookFuncs: a value+// holds a func, which cannot be compared, so RemoveHook could never find it.+type HookFuncs struct {+ OnRouteFunc func(*RouteContext)+}++// OnRoute calls OnRouteFunc.+func (f *HookFuncs) OnRoute(c *RouteContext) {+ if f.OnRouteFunc != nil {+ f.OnRouteFunc(c)+ }+}++// hookState is the Router's hook registry and dispatch settings.+type hookState struct {+ mu sync.RWMutex+ installed []any+ timeout time.Duration+ raise bool+ lock *agent.HookLock+ warn func(string)+}++type hookConfig struct {+ installed []any+ timeout time.Duration+ raise bool+ concurrent bool+ warn func(string)+}++func newHookState(c hookConfig) *hookState {+ h := &hookState{installed: append([]any(nil), c.installed...), timeout: c.timeout, raise: c.raise, warn: c.warn}+ if h.warn == nil {+ h.warn = func(msg string) { log.Print(msg) }+ }+ if !c.concurrent {+ h.lock = agent.NewHookLock()+ }+ return h+}++// checkHooks refuses a nil hook and one that implements no event, Python's "hooks entries must+// implement at least one of ...".+func checkHooks(hooks []any) error {+ for i, h := range hooks {+ if isNil(h) {+ return fmt.Errorf("router: hook %d is nil", i)+ }+ _, route := h.(RouteHook)+ _, predict := h.(agent.Hook)+ if !route && !predict {+ return fmt.Errorf("router: hook %d (%T) implements neither OnRoute nor agent.Hook", i, h)+ }+ }+ return nil+}++func isNil(v any) bool {+ if v == nil {+ return true+ }+ switch rv := reflect.ValueOf(v); rv.Kind() {+ case reflect.Pointer, reflect.Interface, reflect.Map, reflect.Slice, reflect.Func, reflect.Chan:+ return rv.IsNil()+ }+ return false+}++// WithInstalledHooks installs hooks on the Router, as AddHook does after New.+func WithInstalledHooks(hooks ...any) Option {+ return func(c *config) error {+ if err := checkHooks(hooks); err != nil {+ return err+ }+ c.hooks.installed = append(c.hooks.installed, hooks...)+ return nil+ }+}++// WithHookTimeout bounds the wait for each hook. d must be positive; leave the option out for no+// limit.+func WithHookTimeout(d time.Duration) Option {+ return func(c *config) error {+ if err := agent.ValidateHookTimeout(d); err != nil {+ return err+ }+ c.hooks.timeout = d+ return nil+ }+}++// WithHookErrors chooses what a failing hook does: raise true (the default) makes Route return+// its error, false warns and goes on.+func WithHookErrors(raise bool) Option {+ return func(c *config) error { c.hooks.raise = raise; return nil }+}++// WithConcurrentHooks lets hooks of concurrent calls run at the same time; the default runs one+// at a time.+func WithConcurrentHooks() Option {+ return func(c *config) error { c.hooks.concurrent = true; return nil }+}++// WithHookWarnings sets where a hook failure that does not fail the call is reported; the+// default is the log package.+func WithHookWarnings(sink func(msg string)) Option {+ return func(c *config) error { c.hooks.warn = sink; return nil }+}++// AddHook installs hooks after those already there. A hook added twice runs twice.+func (r *Router) AddHook(hooks ...any) error {+ if err := checkHooks(hooks); err != nil {+ return err+ }+ r.hk.mu.Lock()+ r.hk.installed = append(r.hk.installed, hooks...)+ r.hk.mu.Unlock()+ return nil+}++// RemoveHook removes every installed copy of hook, compared by identity, and reports whether+// there was one. A hook whose dynamic type cannot be compared is never found; pass a pointer.+func (r *Router) RemoveHook(hook any) bool {+ r.hk.mu.Lock()+ defer r.hk.mu.Unlock()+ kept := r.hk.installed[:0:0]+ for _, h := range r.hk.installed {+ if !agent.SameHook(h, hook) {+ kept = append(kept, h)+ }+ }+ removed := len(kept) != len(r.hk.installed)+ r.hk.installed = kept+ return removed+}++// InstallHooks installs hooks until the returned function is called, which removes one copy of+// each (the most recent) and leaves everything else, including what was added meanwhile.+// Overlapping installs may be undone in either order.+func (r *Router) InstallHooks(hooks ...any) (undo func(), err error) {+ if err := r.AddHook(hooks...); err != nil {+ return nil, err+ }+ var once sync.Once+ return func() {+ once.Do(func() {+ r.hk.mu.Lock()+ defer r.hk.mu.Unlock()+ for _, h := range hooks {+ for i := len(r.hk.installed) - 1; i >= 0; i-- {+ if agent.SameHook(r.hk.installed[i], h) {+ r.hk.installed = append(r.hk.installed[:i:i], r.hk.installed[i+1:]...)+ break+ }+ }+ }+ })+ }, nil+}++// Hooks returns a copy of the installed hooks.+func (r *Router) Hooks() []any {+ r.hk.mu.RLock()+ defer r.hk.mu.RUnlock()+ return append([]any(nil), r.hk.installed...)+}++// composeHooks is the hooks of one call, in order: defaults, installed, the call's.+func (r *Router) composeHooks(c call) []any {+ var hooks []any+ for _, h := range agent.DefaultHooks() {+ hooks = append(hooks, h)+ }+ r.hk.mu.RLock()+ hooks = append(hooks, r.hk.installed...)+ r.hk.mu.RUnlock()+ return append(hooks, c.hooks...)+}++// ForHooks adds hooks to one request, after the defaults and the installed ones.+func ForHooks(hooks ...any) CallOption {+ return func(c *call) {+ if err := checkHooks(hooks); err != nil && c.err == nil {+ c.err = err+ }+ c.hooks = append(c.hooks, hooks...)+ }+}++// ForHookErrors overrides WithHookErrors for this request.+func ForHookErrors(raise bool) CallOption {+ return func(c *call) { c.raise = &raise }+}++// ForHookTimeout overrides WithHookTimeout for this request; d must be positive.+func ForHookTimeout(d time.Duration) CallOption {+ return func(c *call) { c.timeout = &d }+}++func newRunID() string {+ var b [16]byte+ _, _ = rand.Read(b[:])+ return hex.EncodeToString(b[:])+}++// dispatchRoute runs OnRoute over the hooks of c and returns the decision they leave.+func (r *Router) dispatchRoute(state any, qs schema.Questions, d Decision, c call) (Decision, error) {+ policy := agent.HookPolicy{Timeout: r.hk.timeout, Raise: r.hk.raise, Warn: r.hk.warn}+ if c.raise != nil {+ policy.Raise = *c.raise+ }+ if c.timeout != nil {+ if err := agent.ValidateHookTimeout(*c.timeout); err != nil {+ return d, err+ }+ policy.Timeout = *c.timeout+ }+ var hooks []RouteHook+ var all []any+ for _, h := range r.composeHooks(c) {+ if rh, ok := h.(RouteHook); ok {+ hooks, all = append(hooks, rh), append(all, h)+ }+ }+ if len(hooks) == 0 {+ return d, nil+ }+ rc := &RouteContext{States: []any{state}, Questions: qs, RunID: newRunID(), Decision: d, Router: r}+ run := agent.HookRun{Lock: r.hk.lock, Policy: policy}+ err := run.Dispatch(context.Background(), "on_route", len(hooks),+ func(i int) string { return agent.HookName(all[i]) }, func(i int) { hooks[i].OnRoute(rc) })+ if err != nil {+ return d, err+ }+ return rc.Decision, nil+}diff --git a/laya-go/router/hooks_golden_test.go b/laya-go/router/hooks_golden_test.gonew file mode 100644index 00000000..165d28f6--- /dev/null+++ b/laya-go/router/hooks_golden_test.go@@ -0,0 +1,334 @@+package router_test++import (+ "fmt"+ "regexp"+ "strconv"+ "strings"+ "sync"+ "testing"+ "time"++ "github.com/NandhaKishorM/laya/laya-go/agent"+ "github.com/NandhaKishorM/laya/laya-go/internal/fixtures"+ "github.com/NandhaKishorM/laya/laya-go/lang"+ "github.com/NandhaKishorM/laya/laya-go/router"+)++// hookRecorder collects what the hooks saw, in order, and the warnings the Router reported.+type hookRecorder struct {+ mu sync.Mutex+ calls []hookSeen+ runIDs []string+ warns []string+}++type hookSeen struct {+ hook, model, reason string+ states, questions []string+ runIDLen int+ runIDShared bool+ routerIsSelf bool+}++func (r *hookRecorder) warn(msg string) {+ r.mu.Lock()+ r.warns = append(r.warns, msg)+ r.mu.Unlock()+}++// routeStub is the golden's hook: it records what it sees, then acts out its behaviour. Hooks that+// the golden gives no on_route are otherStub, which has no OnRoute method at all.+type routeStub struct {+ agent.BaseHook // a process-wide default must be an agent.Hook+ name, behaviour string+ rec *hookRecorder+ r **router.Router+}++func (h *routeStub) OnRoute(c *router.RouteContext) {+ seen := hookSeen{hook: h.name, model: string(c.Decision.Model), reason: c.Decision.Reason,+ runIDLen: len(c.RunID), routerIsSelf: c.Router == *h.r}+ for _, s := range c.States {+ switch v := s.(type) {+ case string:+ seen.states = append(seen.states, v)+ case lang.Object:+ seen.states = append(seen.states, "<dict>")+ case []any:+ seen.states = append(seen.states, "<list>")+ default:+ seen.states = append(seen.states, fmt.Sprintf("<%T>", s))+ }+ }+ seen.questions = c.Questions.IDs()+ h.rec.mu.Lock()+ h.rec.runIDs = append(h.rec.runIDs, c.RunID)+ seen.runIDShared = c.RunID == h.rec.runIDs[0]+ h.rec.calls = append(h.rec.calls, seen)+ h.rec.mu.Unlock()+ kind, arg, _ := strings.Cut(h.behaviour, ":")+ switch kind {+ case "replace", "replace_raise":+ spec, _ := c.Router.Spec(router.Checkpoint(arg))+ c.Decision = router.Decision{Model: router.Checkpoint(arg), Repo: spec.String(), Reason: "replaced by " + h.name}+ case "suffix":+ c.Decision.Reason += "|" + h.name+ }+ switch kind {+ case "raise", "replace_raise":+ panic(fmt.Errorf("boom from %s", h.name))+ case "sleep":+ secs, _ := strconv.ParseFloat(arg, 64)+ time.Sleep(time.Duration(secs * float64(time.Second)))+ }+}++type otherStub struct {+ agent.BaseHook+ name string+ rec *hookRecorder+}++func (h *otherStub) OnPredictEnd(*agent.PredictContext) {+ h.rec.mu.Lock()+ h.rec.calls = append(h.rec.calls, hookSeen{hook: h.name + ":other"})+ h.rec.mu.Unlock()+}++// timeoutName rewrites Python's "laya: hook X.on_route exceeded" to Go's, which names the hook's+// type and not the bound method.+var (+ timeoutName = regexp.MustCompile(`laya: hook \w+\.on_route exceeded`)+ failedName = regexp.MustCompile(`laya: hook \w+\.on_route failed`)+)++func goText(s string) string {+ s = timeoutName.ReplaceAllString(s, "laya: hook routeStub exceeded")+ return failedName.ReplaceAllString(s, "laya: hook routeStub.on_route failed")+}++type hookCase struct {+ r *router.Router+ rec *hookRecorder+ opts []router.CallOption+}++func (hc *hookCase) snapshot() ([]hookSeen, []string) {+ hc.rec.mu.Lock()+ defer hc.rec.mu.Unlock()+ return append([]hookSeen(nil), hc.rec.calls...), append([]string(nil), hc.rec.warns...)+}++// buildHooked makes the Router and the call options for one golden record; the defaults are left+// installed for the caller to clear. ok is false when New refused the router.+func buildHooked(t *testing.T, rec fixtures.Object) (hc *hookCase, newErr error) {+ t.Helper()+ hc = &hookCase{rec: &hookRecorder{}}+ var ptr *router.Router+ var installed, call, defaults []any+ for _, hv := range fixtures.List(t, rec.Must("chain")) {+ h := fixtures.Obj(t, hv)+ name := str(t, h, "name")+ var hook any = &otherStub{name: name, rec: hc.rec}+ for _, e := range fixtures.Strings(t, h.Must("events")) {+ if e == "on_route" {+ hook = &routeStub{name: name, behaviour: str(t, h, "behaviour"), rec: hc.rec, r: &ptr}+ }+ }+ switch str(t, h, "where") {+ case "default":+ defaults = append(defaults, hook)+ case "installed":+ installed = append(installed, hook)+ default:+ call = append(call, hook)+ }+ }+ opts := []router.Option{router.WithInstalledHooks(installed...), router.WithHookWarnings(hc.rec.warn)}+ concurrent := true // Python's default+ for _, m := range fixtures.Obj(t, rec.Must("router")) {+ switch m.Key {+ case "hooks_raise":+ opts = append(opts, router.WithHookErrors(fixtures.Bool(t, m.Value)))+ case "hooks_timeout":+ opts = append(opts, router.WithHookTimeout(seconds(t, m.Value)))+ case "hooks_concurrent":+ concurrent = fixtures.Bool(t, m.Value)+ case "auto_task_detection":+ opts = append(opts, router.WithAutoTaskDetection(fixtures.Bool(t, m.Value)))+ default:+ t.Fatalf("unhandled router kwarg %q", m.Key)+ }+ }+ if concurrent {+ opts = append(opts, router.WithConcurrentHooks())+ }+ var err error+ hc.r, err = router.New(opts...)+ ptr = hc.r+ if err != nil {+ return nil, err+ }+ if len(call) > 0 {+ hc.opts = append(hc.opts, router.ForHooks(call...))+ }+ for _, m := range fixtures.Obj(t, rec.Must("call")) {+ switch m.Key {+ case "hooks_raise":+ hc.opts = append(hc.opts, router.ForHookErrors(fixtures.Bool(t, m.Value)))+ case "hooks_timeout":+ hc.opts = append(hc.opts, router.ForHookTimeout(seconds(t, m.Value)))+ default:+ t.Fatalf("unhandled call kwarg %q", m.Key)+ }+ }+ agent.ClearDefaultHooks()+ t.Cleanup(agent.ClearDefaultHooks)+ for _, d := range defaults {+ if err := agent.AddDefaultHook(d.(agent.Hook)); err != nil {+ t.Fatal(err)+ }+ }+ return hc, nil+}++func seconds(t *testing.T, v any) time.Duration {+ t.Helper()+ return time.Duration(fixtures.Float(t, v) * float64(time.Second))+}++func checkCalls(t *testing.T, got []hookSeen, want []any) {+ t.Helper()+ if len(got) != len(want) {+ t.Fatalf("%d hook calls, want %d: %+v", len(got), len(want), got)+ }+ for i, wv := range want {+ w := fixtures.Obj(t, wv)+ g := got[i]+ if g.hook != str(t, w, "hook") || g.model != str(t, w, "model") || g.reason != str(t, w, "reason") ||+ strings.Join(g.states, "\x00") != strings.Join(fixtures.Strings(t, w.Must("states")), "\x00") ||+ strings.Join(g.questions, ",") != strings.Join(fixtures.Strings(t, w.Must("questions")), ",") ||+ g.runIDLen != fixtures.Int(t, w.Must("run_id_len")) || g.runIDShared != fixtures.Bool(t, w.Must("run_id_shared")) ||+ g.routerIsSelf != fixtures.Bool(t, w.Must("router_is_self")) {+ t.Errorf("call %d\n got %+v\nwant %v", i, g, w)+ }+ }+}++func checkWarnings(t *testing.T, got []string, want []any) {+ t.Helper()+ var w []string+ for _, v := range want {+ w = append(w, goText(fixtures.Str(t, v)))+ }+ if strings.Join(got, "|") != strings.Join(w, "|") {+ t.Errorf("warnings\n got %q\nwant %q", got, w)+ }+}++func TestRouteHooksGolden(t *testing.T) {+ cases := family(t, "hooks")+ if len(cases) != 337 {+ t.Fatalf("%d cases", len(cases))+ }+ var decided, failed, refusedRouters, warned, replaced, timedOut int+ for i, c := range cases {+ rec := fixtures.Obj(t, c)+ t.Run(fmt.Sprintf("%d-%s", i, str(t, rec, "case")), func(t *testing.T) {+ hc, err := buildHooked(t, rec)+ if want, bad := rec.Get("router_error"); bad {+ refusedRouters+++ if err == nil || err.Error() != fixtures.Str(t, want) {+ t.Fatalf("New error = %v, want %q", err, want)+ }+ return+ }+ if err != nil {+ t.Fatal(err)+ }+ state, qs, opts := callOptions(t, fixtures.Obj(t, rec.Must("route")))+ got, err := hc.r.Route(state, qs, append(opts, hc.opts...)...)+ calls, warns := hc.snapshot()+ checkCalls(t, calls, fixtures.List(t, rec.Must("calls")))+ if len(warns) > 0 {+ warned+++ }+ checkWarnings(t, warns, fixtures.List(t, rec.Must("warnings")))+ if want, bad := rec.Get("error"); bad && want != nil {+ failed+++ msg := fixtures.Str(t, fixtures.Obj(t, want).Must("message"))+ if strings.Contains(msg, "exceeded") {+ timedOut+++ }+ if err == nil || err.Error() != goText(msg) {+ t.Fatalf("Route error = %v, want %q", err, goText(msg))+ }+ return+ }+ if err != nil {+ t.Fatal(err)+ }+ decided+++ want := fixtures.Obj(t, rec.Must("decision"))+ if strings.HasPrefix(got.Reason, "replaced by") {+ replaced+++ }+ checkDecision(t, got, want)+ })+ }+ t.Logf("%d decided, %d failed (%d timeouts), %d routers refused, %d warned, %d replaced", decided, failed, timedOut, refusedRouters, warned, replaced)+ if decided < 150 || failed < 100 || timedOut < 15 || refusedRouters < 2 || warned < 25 || replaced < 25 {+ t.Fatalf("the golden stopped covering every outcome")+ }+}++func TestRouteBatchHooksGolden(t *testing.T) {+ cases := family(t, "hook_batches")+ if len(cases) != 42 {+ t.Fatalf("%d cases", len(cases))+ }+ var failed, hooked int+ for i, c := range cases {+ rec := fixtures.Obj(t, c)+ t.Run(fmt.Sprintf("%d-%s", i, str(t, rec, "case")), func(t *testing.T) {+ hc, err := buildHooked(t, rec)+ if err != nil {+ t.Fatal(err)+ }+ var reqs []router.Request+ for _, item := range fixtures.List(t, rec.Must("requests")) {+ state, qs, opts := callOptions(t, fixtures.Obj(t, item))+ reqs = append(reqs, router.Request{State: state, Questions: qs, Options: opts})+ }+ got, err := hc.r.RouteBatch(reqs, hc.opts...)+ calls, warns := hc.snapshot()+ checkCalls(t, calls, fixtures.List(t, rec.Must("calls")))+ checkWarnings(t, warns, fixtures.List(t, rec.Must("warnings")))+ if want, bad := rec.Get("error"); bad && want != nil {+ failed+++ msg := goText(fixtures.Str(t, fixtures.Obj(t, want).Must("message")))+ if err == nil || err.Error() != msg {+ t.Fatalf("RouteBatch error = %v, want %q", err, msg)+ }+ return+ }+ if err != nil {+ t.Fatal(err)+ }+ want := fixtures.List(t, rec.Must("decisions"))+ if len(got) != len(want) {+ t.Fatalf("%d decisions, want %d", len(got), len(want))+ }+ if len(calls) > 0 {+ hooked+++ }+ for j := range got {+ checkDecision(t, got[j], fixtures.Obj(t, want[j]))+ }+ })+ }+ if failed < 3 || hooked < 15 {+ t.Fatalf("the golden stopped covering both outcomes: %d failed, %d hooked", failed, hooked)+ }+}diff --git a/laya-go/router/hooks_test.go b/laya-go/router/hooks_test.gonew file mode 100644index 00000000..f6734b73--- /dev/null+++ b/laya-go/router/hooks_test.go@@ -0,0 +1,320 @@+package router_test++import (+ "errors"+ "strings"+ "sync"+ "sync/atomic"+ "testing"+ "time"++ "github.com/NandhaKishorM/laya/laya-go/agent"+ "github.com/NandhaKishorM/laya/laya-go/router"+)++type fn = func(*router.RouteContext)++func hook(f fn) *router.HookFuncs { return &router.HookFuncs{OnRouteFunc: f} }++func TestHookSeesTheContext(t *testing.T) {+ var seen *router.RouteContext+ var copyOf router.RouteContext+ r := mustNew(t)+ _ = r.AddHook(hook(func(c *router.RouteContext) { seen, copyOf = c, *c }))+ qs := noul(t, "urgency")+ d, err := r.Route(englishText, qs)+ if err != nil {+ t.Fatal(err)+ }+ if seen == nil || copyOf.Router != r || len(copyOf.States) != 1 || copyOf.States[0] != englishText ||+ strings.Join(copyOf.Questions.IDs(), ",") != "urgency" || len(copyOf.RunID) != 32 {+ t.Fatalf("context %+v", copyOf)+ }+ if copyOf.Decision.Model != router.English || d.Model != router.English || copyOf.Decision.Reason != d.Reason {+ t.Fatalf("hook saw %+v, Route returned %+v", copyOf.Decision, d)+ }+}++func TestHookReplacementIsReturnedAsIs(t *testing.T) {+ r := mustNew(t)+ _ = r.AddHook(hook(func(c *router.RouteContext) { c.Decision = router.Decision{Model: "nonsense", Reason: "r"} }))+ d, err := r.Route(englishText, none)+ if err != nil || d.Model != "nonsense" || d.Reason != "r" {+ t.Fatalf("%+v, %v", d, err)+ }+}++func TestRunIDDiffersPerCallAndIsSharedWithinOne(t *testing.T) {+ var ids []string+ r := mustNew(t)+ h := hook(func(c *router.RouteContext) { ids = append(ids, c.RunID) })+ _ = r.AddHook(h, h)+ for i := 0; i < 2; i++ {+ if _, err := r.Route("x", none); err != nil {+ t.Fatal(err)+ }+ }+ if len(ids) != 4 || ids[0] != ids[1] || ids[2] != ids[3] || ids[0] == ids[2] {+ t.Fatalf("run ids %v", ids)+ }+}++func TestRegistry(t *testing.T) {+ var order []string+ mk := func(n string) *router.HookFuncs { return hook(func(*router.RouteContext) { order = append(order, n) }) }+ a, b, c := mk("a"), mk("b"), mk("c")+ r := mustNew(t, router.WithInstalledHooks(a))+ run := func() string {+ order = nil+ if _, err := r.Route("x", none); err != nil {+ t.Fatal(err)+ }+ return strings.Join(order, "")+ }+ _ = r.AddHook(b, a)+ if got := run(); got != "aba" {+ t.Fatalf("add order %q", got)+ }+ undo, err := r.InstallHooks(c, a)+ if err != nil {+ t.Fatal(err)+ }+ if got := run(); got != "abaca" {+ t.Fatalf("installed %q", got)+ }+ _ = r.AddHook(c) // added while installed: must survive the undo+ undo()+ undo() // idempotent+ if got := run(); got != "abac" {+ t.Fatalf("after undo %q (the most recent copy of a goes, the earlier ones stay)", got)+ }+ if !r.RemoveHook(a) || r.RemoveHook(a) {+ t.Fatal("RemoveHook should find a once")+ }+ if got := run(); got != "bc" {+ t.Fatalf("after remove %q", got)+ }+ if n := len(r.Hooks()); n != 2 {+ t.Fatalf("%d hooks", n)+ }+ r.Hooks()[0] = nil // a copy+ if r.Hooks()[0] == nil {+ t.Fatal("Hooks returned the live slice")+ }+}++func TestHookValidation(t *testing.T) {+ r := mustNew(t)+ var nilHook *router.HookFuncs+ for name, bad := range map[string]any{"nil": nil, "typed nil": nilHook, "no event": struct{}{}, "a func": func() {}} {+ if err := r.AddHook(bad); err == nil {+ t.Errorf("%s accepted", name)+ }+ if _, err := router.New(router.WithInstalledHooks(bad)); err == nil {+ t.Errorf("%s accepted by New", name)+ }+ if _, err := r.Route("x", none, router.ForHooks(bad)); err == nil {+ t.Errorf("%s accepted by ForHooks", name)+ }+ }+ if _, err := r.InstallHooks(nil); err == nil {+ t.Error("InstallHooks accepted nil")+ }+ if len(r.Hooks()) != 0 {+ t.Fatal("a refused hook was installed")+ }+ // An agent.Hook alone is a valid entry: it has no OnRoute and is skipped.+ if err := r.AddHook(agent.BaseHook{}); err != nil {+ t.Fatal(err)+ }+ if _, err := r.Route("x", none); err != nil {+ t.Fatal(err)+ }+}++func TestRouteErrorBeatsHookErrorsAndRunsNoHook(t *testing.T) {+ var ran bool+ r := mustNew(t)+ _ = r.AddHook(hook(func(*router.RouteContext) { ran = true }))+ _, err := r.Route("x", none, router.ForModel("nope"), router.ForHookTimeout(0), router.ForHooks(nil))+ var ue *router.UnknownModelError+ if !errors.As(err, &ue) || ran {+ t.Fatalf("%v, ran=%v", err, ran)+ }+}++func TestPerCallTimeoutIsValidatedEvenWithNoHooks(t *testing.T) {+ r := mustNew(t)+ for _, d := range []time.Duration{0, -time.Second} {+ _, err := r.Route("x", none, router.ForHookTimeout(d))+ if err == nil || !strings.HasPrefix(err.Error(), "hooks_timeout must be a positive finite number or None; got ") {+ t.Errorf("%v: %v", d, err)+ }+ }+ if _, err := router.New(router.WithHookTimeout(0)); err == nil {+ t.Error("New accepted a zero timeout")+ }+}++func TestPanicIsAFailedHookAndGoexitToo(t *testing.T) {+ r := mustNew(t)+ _ = r.AddHook(hook(func(*router.RouteContext) { panic("plain string") }))+ if _, err := r.Route("x", none); err == nil || err.Error() != "plain string" {+ t.Fatalf("%v", err)+ }+ var warns []string+ r = mustNew(t, router.WithHookErrors(false), router.WithHookWarnings(func(m string) { warns = append(warns, m) }))+ var after bool+ _ = r.AddHook(hook(func(*router.RouteContext) { panic(errors.New("x")) }), hook(func(*router.RouteContext) { after = true }))+ if _, err := r.Route("x", none); err != nil || !after || len(warns) != 1 ||+ warns[0] != "laya: hook HookFuncs.on_route failed: x" {+ t.Fatalf("err=%v after=%v warns=%q", err, after, warns)+ }+}++func TestTimeoutAbandonsTheHookButNotTheRouter(t *testing.T) {+ release := make(chan struct{})+ t.Cleanup(func() { close(release) })+ r := mustNew(t, router.WithHookTimeout(30*time.Millisecond))+ _ = r.AddHook(hook(func(*router.RouteContext) { <-release }))+ start := time.Now()+ _, err := r.Route("x", none)+ if err == nil || err.Error() != "laya: hook HookFuncs exceeded 0.03s" || time.Since(start) > 2*time.Second {+ t.Fatalf("%v after %v", err, time.Since(start))+ }+ // The slow hook no longer holds the serial lock: a call without it goes through.+ r.RemoveHook(r.Hooks()[0])+ if _, err := r.Route("x", none); err != nil {+ t.Fatal(err)+ }+}++// Serial hooks never overlap across goroutines; WithConcurrentHooks lets them.+func TestSerialHooksDoNotOverlapAndConcurrentOnesCan(t *testing.T) {+ overlap := func(opts ...router.Option) int32 {+ var inside, worst int32+ r := mustNew(t, opts...)+ _ = r.AddHook(hook(func(*router.RouteContext) {+ n := atomic.AddInt32(&inside, 1)+ for {+ w := atomic.LoadInt32(&worst)+ if n <= w || atomic.CompareAndSwapInt32(&worst, w, n) {+ break+ }+ }+ time.Sleep(5 * time.Millisecond)+ atomic.AddInt32(&inside, -1)+ }))+ var wg sync.WaitGroup+ for i := 0; i < 8; i++ {+ wg.Add(1)+ go func() {+ defer wg.Done()+ if _, err := r.Route(englishText, none); err != nil {+ t.Error(err)+ }+ }()+ }+ wg.Wait()+ return worst+ }+ if w := overlap(); w != 1 {+ t.Errorf("serial hooks overlapped %d deep", w)+ }+ if w := overlap(router.WithConcurrentHooks()); w < 2 {+ t.Errorf("concurrent hooks never overlapped (%d)", w)+ }+}++// Hooks added, removed and run from many goroutines: the race detector is the assertion, plus+// every call returning one of the two decisions a hook can leave.+func TestConcurrentRegistryAndRoutes(t *testing.T) {+ r := mustNew(t, router.WithConcurrentHooks())+ pin := hook(func(c *router.RouteContext) {+ c.Decision = router.Decision{Model: router.Multilingual, Reason: "pin"}+ })+ var wg sync.WaitGroup+ for i := 0; i < 6; i++ {+ wg.Add(2)+ go func() {+ defer wg.Done()+ for j := 0; j < 50; j++ {+ undo, err := r.InstallHooks(pin)+ if err != nil {+ t.Error(err)+ return+ }+ r.Hooks()+ undo()+ _ = r.AddHook(pin)+ r.RemoveHook(pin)+ }+ }()+ go func() {+ defer wg.Done()+ for j := 0; j < 50; j++ {+ d, err := r.Route(englishText, none)+ if err != nil || (d.Model != router.English && d.Reason != "pin") {+ t.Errorf("%+v, %v", d, err)+ return+ }+ }+ }()+ }+ wg.Wait()+}++func TestDefaultHooksRunFirstAndAreSkippedWithoutOnRoute(t *testing.T) {+ agent.ClearDefaultHooks()+ t.Cleanup(agent.ClearDefaultHooks)+ var order []string+ d := &routeAndAgentHook{fn: func(*router.RouteContext) { order = append(order, "default") }}+ if err := agent.AddDefaultHook(d, agent.BaseHook{}); err != nil {+ t.Fatal(err)+ }+ r := mustNew(t, router.WithInstalledHooks(hook(func(*router.RouteContext) { order = append(order, "installed") })))+ if _, err := r.Route("x", none, router.ForHooks(hook(func(*router.RouteContext) { order = append(order, "call") }))); err != nil {+ t.Fatal(err)+ }+ if got := strings.Join(order, ","); got != "default,installed,call" {+ t.Fatalf("%q", got)+ }+}++type routeAndAgentHook struct {+ agent.BaseHook+ fn fn+}++func (h *routeAndAgentHook) OnRoute(c *router.RouteContext) { h.fn(c) }++func TestRouteBatchAppliesBatchHookOptionsToEveryRequestAndStopsAtFirstFailure(t *testing.T) {+ var seen []string+ r := mustNew(t)+ _ = r.AddHook(hook(func(c *router.RouteContext) {+ seen = append(seen, c.States[0].(string))+ if c.States[0] == "bad" {+ panic("no")+ }+ }))+ reqs := []router.Request{{State: "a"}, {State: "bad"}, {State: "c"}}+ if _, err := r.RouteBatch(reqs); err == nil || err.Error() != "no" || strings.Join(seen, ",") != "a,bad" {+ t.Fatalf("%v %v", err, seen)+ }+ seen = nil+ ds, err := r.RouteBatch(reqs, router.ForHookErrors(false))+ if err != nil || len(ds) != 3 || strings.Join(seen, ",") != "a,bad,c" {+ t.Fatalf("%v %v %v", ds, err, seen)+ }+ if _, err := r.RouteBatch(reqs[:1], router.ForHookTimeout(0)); err == nil {+ t.Fatal("batch timeout not validated")+ }+}++func TestBaseHookIsANoOp(t *testing.T) {+ type embed struct{ router.BaseHook }+ r := mustNew(t, router.WithInstalledHooks(&embed{}))+ if d, err := r.Route(englishText, none); err != nil || d.Model != router.English {+ t.Fatal(d, err)+ }+}diff --git a/laya-go/router/router.go b/laya-go/router/router.goindex 9fc06226..f01f7464 100644--- a/laya-go/router/router.go+++ b/laya-go/router/router.go@@ -5,6 +5,7 @@ import ("os""os/user""strings"+ "time""github.com/NandhaKishorM/laya/laya-go/internal/pyjson""github.com/NandhaKishorM/laya/laya-go/internal/unicodedata"@@ -49,12 +50,14 @@ type Router struct {def Checkpointauto boolhint LangHint+ hk *hookState}// Option configures New.type Option func(*config) errortype config struct {+ hooks hookConfigstandalone booldef stringauto bool@@ -112,7 +115,7 @@ func WithSourceIn(name, repo, subfolder string) Option {// New builds a Router. A default or source name that is neither a checkpoint nor an alias is an// *UnknownModelError. Sources are applied in the order given, the last one for a name winning.func New(opts ...Option) (*Router, error) {- c := config{def: string(Multilingual)}+ c := config{def: string(Multilingual), hooks: hookConfig{raise: true}}for _, o := range opts {if err := o(&c); err != nil {return nil, err@@ -122,7 +125,7 @@ func New(opts ...Option) (*Router, error) {if c.standalone {base = standalone}- r := &Router{models: make(map[Checkpoint]ModelSpec, len(base)), auto: c.auto, hint: c.hint}+ r := &Router{models: make(map[Checkpoint]ModelSpec, len(base)), auto: c.auto, hint: c.hint, hk: newHookState(c.hooks)}for k, v := range base {r.models[k] = v}@@ -193,6 +196,10 @@ type CallOption func(*call)type call struct {model, task, lang *stringhint LangHint+ hooks []any+ raise *bool+ timeout *time.Duration+ err error}// ForModel routes to the named checkpoint or alias, ahead of every other signal.@@ -212,13 +219,29 @@ func ForLangGuess(h LangHint) CallOption { return func(c *call) { c.hint = h } }// Route decides which checkpoint reads state, without loading or running anything. qs is only// looked at for its ids, to recognise a typed-decisions workflow; the zero value is fine.//-// The error is an *UnknownModelError for a model or task that names no checkpoint.+// Hooks with an OnRoute method then see the decision and may replace it; the replacement is+// returned (see hooks.go).+//+// The error is an *UnknownModelError for a model or task that names no checkpoint, or a hook's+// failure under WithHookErrors(true).func (r *Router) Route(state any, qs schema.Questions, opts ...CallOption) (Decision, error) {var c callfor _, o := range opts {o(&c)}- return r.route(state, qs, c)+ return r.routeHooked(state, qs, c)+}++// routeHooked is route followed by the OnRoute hooks, Python's Router.route.+func (r *Router) routeHooked(state any, qs schema.Questions, c call) (Decision, error) {+ d, err := r.route(state, qs, c)+ if err != nil {+ return Decision{}, err+ }+ if c.err != nil {+ return Decision{}, c.err+ }+ return r.dispatchRoute(state, qs, d, c)}func (r *Router) decision(key Checkpoint, reason string, det *lang.Analysis, wf string) Decision {@@ -332,13 +355,17 @@ type Request struct {// RouteBatch routes a heterogeneous batch without loading anything. The decisions keep the// order of reqs. A nil State is refused with laya's text; the first failing request ends the// batch.-func (r *Router) RouteBatch(reqs []Request) ([]Decision, error) {+//+// opts apply to every request, before the request's own Options; they are meant for the hook+// options (ForHooks, ForHookErrors, ForHookTimeout), as route_batch's hooks, hooks_raise and+// hooks_timeout are.+func (r *Router) RouteBatch(reqs []Request, opts ...CallOption) ([]Decision, error) {out := make([]Decision, 0, len(reqs))for i, req := range reqs {if req.State == nil {return nil, fmt.Errorf("request %d 'state' must not be None; pass a string, dict, or list", i)}- d, err := r.Route(req.State, req.Questions, req.Options...)+ d, err := r.Route(req.State, req.Questions, append(append([]CallOption(nil), opts...), req.Options...)...)if err != nil {return nil, err}