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
router: per-checkpoint SHA-256 pins (WithSHA256Digests, nested LAYA_SHA256_DIGESTS, ExpectedSHA256)
Adeshina Lasisi90122ff04007
diff --git a/laya-go/README.md b/laya-go/README.mdindex 9f3d3082..48c9e404 100644--- a/laya-go/README.md+++ b/laya-go/README.md@@ -18,7 +18,7 @@ The foundation (language detection, questions, sequences, the tokenizer) and the| `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`. || `agent` | `ONNXAgent.predict` and `predict_batch` over an `infer.Session`: `Open`, `Predict`, `PredictBatch`, `LoadConfig`, `WithCalibration` (installs a `calibrate` payload at `Open`) and `CalibrationPayload` (writes one), with batch size, sort-by-length and context cancellation between runs. |-| `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. With `WithAgentFactory` it also loads: `Load`, `Lease` (an evicted agent closes after its last lease), `Attach`, `Preload`, `Unload`, `UnloadAll`, `Close`, LRU `WithMaxLoaded`, single-flight builds, `OnLoad`/`OnEvict` hooks. |+| `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. With `WithAgentFactory` it also loads: `Load`, `Lease` (an evicted agent closes after its last lease), `Attach`, `Preload`, `Unload`, `UnloadAll`, `Close`, LRU `WithMaxLoaded`, single-flight builds, `OnLoad`/`OnEvict` hooks. `WithSHA256Digests`, a nested `LAYA_SHA256_DIGESTS` and `ExpectedSHA256` give each checkpoint its own digest pins. || `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. || `internal/unicodedata` | The character predicates `laya/lang.py` leans on, recorded from CPython. |diff --git a/laya-go/router/digests.go b/laya-go/router/digests.gonew file mode 100644index 00000000..e4d2b8ce--- /dev/null+++ b/laya-go/router/digests.go@@ -0,0 +1,175 @@+package router++// Per-checkpoint SHA-256 pins: laya/router.py's sha256_digests argument, its LAYA_SHA256_DIGESTS+// layering (_digests_from_env) and the merge of the channels that pin one checkpoint+// (_merge_expected_digests). The Router only holds and merges the maps; the AgentFactory passes+// the result to agent.WithExpectedSHA256, which does the checking.++import (+ "encoding/json"+ "fmt"+ "os"+ "sort"++ "github.com/NandhaKishorM/laya/laya-go/internal/digest"+ "github.com/NandhaKishorM/laya/laya-go/internal/unicodedata"+ "github.com/NandhaKishorM/laya/laya-go/lang"+)++// WithSHA256Digests pins checkpoints to the SHA-256 of their files, one map of slash path -> hex+// digest per checkpoint, as laya's Router(sha256_digests=...) does. Names are normalised as every+// Router name is, so "en" pins English, and a name the Router does not know is an+// *UnknownModelError from New. A nil map is an explicit "pin nothing": it masks a flat+// LAYA_SHA256_DIGESTS for that checkpoint. A pin given here replaces the whole entry the+// environment seeded for that checkpoint; a later call replaces an earlier one per name.+//+// The Router does not verify anything. ExpectedSHA256 says what to hand agent.WithExpectedSHA256.+func WithSHA256Digests(digests map[string]map[string]string) Option {+ digests = copyTable(digests) // later edits by the caller must not reach the Router+ return func(c *config) error {+ names := make([]string, 0, len(digests))+ for name := range digests {+ names = append(names, name)+ }+ sort.Strings(names) // two spellings of one checkpoint ("en", "english") resolve in name order+ for _, name := range names {+ c.digests = append(c.digests, digestPin{name, digests[name]})+ }+ return nil+ }+}++type digestPin struct {+ name string+ files map[string]string+}++// digestTable is the per-checkpoint pins: a missing key has no entry at all, and a nil value is an+// entry that names no files.+type digestTable map[Checkpoint]map[string]string++// digestsFromEnv is _digests_from_env. A flat {artifact: digest} map, an unset, blank or+// unparseable variable and anything that is not a non-empty object name nothing here: the agent+// reads those itself. A nested {model: {artifact: digest}} map seeds every checkpoint the Router+// knows, the ones it does not name with an empty entry.+func digestsFromEnv(models map[Checkpoint]ModelSpec) (digestTable, error) {+ raw := unicodedata.Strip(os.Getenv(digest.Env))+ if raw == "" {+ return digestTable{}, nil+ }+ var data lang.Object+ if err := json.Unmarshal([]byte(raw), &data); err != nil || len(data) == 0 {+ return digestTable{}, nil // not JSON, not an object, or {}: laya.revisions' to report+ }+ strs, objs := 0, 0+ for _, m := range data {+ switch m.Value.(type) {+ case string:+ strs+++ case lang.Object:+ objs+++ }+ }+ if strs == len(data) {+ return digestTable{}, nil // flat: the agent applies it+ }+ if objs != len(data) {+ keys := make([]string, len(data))+ for i, m := range data {+ keys[i] = m.Key+ }+ return nil, fmt.Errorf("LAYA_SHA256_DIGESTS must be either {artifact: digest} for every "++ "checkpoint or {model: {artifact: digest}} per checkpoint; %s mixes the two or holds a "++ "value that is neither", pyList(keys))+ }+ table := make(digestTable, len(models))+ for _, m := range data {+ key, err := NormaliseName(m.Key)+ if err != nil {+ return nil, err+ }+ files := map[string]string{}+ for _, f := range m.Value.(lang.Object) {+ s, ok := f.Value.(string)+ if !ok {+ return nil, fmt.Errorf("LAYA_SHA256_DIGESTS: the digest of %q in %q must be a string, got %T",+ f.Key, m.Key, f.Value)+ }+ files[f.Key] = s+ }+ table[key] = files+ }+ for name := range models {+ if _, ok := table[name]; !ok {+ table[name] = map[string]string{}+ }+ }+ return table, nil+}++// SHA256Digests is a copy of the per-checkpoint pins the Router holds: the environment's, then+// WithSHA256Digests on top. A checkpoint with no entry is absent; one that pins nothing has a nil+// or empty map.+func (r *Router) SHA256Digests() map[Checkpoint]map[string]string { return copyTable(r.digests) }++// copyTable deep-copies a table, keeping a nil entry nil and an empty one empty.+func copyTable[K comparable](t map[K]map[string]string) map[K]map[string]string {+ out := make(map[K]map[string]string, len(t))+ for k, v := range t {+ if v == nil {+ out[k] = nil+ continue+ }+ cp := make(map[string]string, len(v))+ for f, d := range v {+ cp[f] = d+ }+ out[k] = cp+ }+ return out+}++// ExpectedSHA256 is the map to build checkpoint c with, out of the two channels that pin it:+// shared, which reaches every checkpoint (a pin the factory holds itself), and the Router's own+// entry for c. The files of both count, and for a file both name the Router's entry wins, because+// shared reaches checkpoints whose "model.safetensors" are different files.+//+// A nil result means neither channel says anything, and the factory must then pass no+// agent.WithExpectedSHA256, so the agent keeps its own LAYA_SHA256_DIGESTS fallback. An empty+// non-nil result is not the same: it must still be passed, because it masks that fallback, which a+// nested variable would otherwise have read as an artifact map. The result is a fresh map. A name+// the Router does not know is an *UnknownModelError.+func (r *Router) ExpectedSHA256(name string, shared map[string]string) (map[string]string, error) {+ key, err := NormaliseName(name)+ if err != nil {+ return nil, err+ }+ return mergeExpectedDigests(shared, r.digests.entry(key)), nil+}++// entry is _digest_entry: nil when c has no entry, an empty map for one that names no files.+func (t digestTable) entry(c Checkpoint) map[string]string {+ files, ok := t[c]+ if !ok {+ return nil+ }+ if files == nil {+ return map[string]string{}+ }+ return files+}++// mergeExpectedDigests is _merge_expected_digests; nil is None and an empty map is {}.+func mergeExpectedDigests(shared, perModel map[string]string) map[string]string {+ if shared == nil && perModel == nil {+ return nil+ }+ merged := make(map[string]string, len(shared)+len(perModel))+ for k, v := range shared {+ merged[k] = v+ }+ for k, v := range perModel {+ merged[k] = v+ }+ return merged+}diff --git a/laya-go/router/digests_golden_test.go b/laya-go/router/digests_golden_test.gonew file mode 100644index 00000000..06d0b059--- /dev/null+++ b/laya-go/router/digests_golden_test.go@@ -0,0 +1,101 @@+package router_test++import (+ "os"+ "reflect"+ "strconv"+ "testing"++ "github.com/NandhaKishorM/laya/laya-go/internal/fixtures"+ "github.com/NandhaKishorM/laya/laya-go/router"+)++// files reads a golden {path: digest} object; JSON null is a nil map, {} an empty one.+func files(t *testing.T, v any) map[string]string {+ t.Helper()+ if v == nil {+ return nil+ }+ out := map[string]string{}+ for _, m := range fixtures.Obj(t, v) {+ out[m.Key] = fixtures.Str(t, m.Value)+ }+ return out+}++func perModel(t *testing.T, v any) map[string]map[string]string {+ t.Helper()+ if v == nil {+ return nil+ }+ out := map[string]map[string]string{}+ for _, m := range fixtures.Obj(t, v) {+ out[m.Key] = files(t, m.Value)+ }+ return out+}++func setEnv(t *testing.T, v any) {+ t.Helper()+ t.Setenv("LAYA_SHA256_DIGESTS", "")+ if v == nil {+ os.Unsetenv("LAYA_SHA256_DIGESTS")+ return+ }+ os.Setenv("LAYA_SHA256_DIGESTS", fixtures.Str(t, v))+}++func TestRouterDigestsGolden(t *testing.T) {+ root := fixtures.Load(t, "go_extra.json")+ rows := fixtures.List(t, root.Must("router_digests"))+ if len(rows) != 1125 {+ t.Fatalf("%d rows", len(rows))+ }+ errs := 0+ for i, rv := range rows {+ row := fixtures.Obj(t, rv)+ t.Run(strconv.Itoa(i), func(t *testing.T) {+ setEnv(t, row.Must("env"))+ var opts []router.Option+ if arg := perModel(t, row.Must("argument")); arg != nil {+ opts = append(opts, router.WithSHA256Digests(arg))+ }+ r, err := router.New(opts...)+ if want, bad := row.Get("error"); bad {+ errs+++ if err == nil || err.Error() != fixtures.Str(t, want) {+ t.Fatalf("New error = %v, want %q", err, want)+ }+ return+ }+ if err != nil {+ t.Fatalf("New: %v", err)+ }+ table := map[router.Checkpoint]map[string]string{}+ for k, v := range perModel(t, row.Must("table")) {+ table[router.Checkpoint(k)] = v+ }+ got := r.SHA256Digests()+ if len(got) != len(table) {+ t.Fatalf("table = %v, want %v", got, table)+ }+ for k, want := range table {+ g, ok := got[k]+ if !ok || (g == nil) != (want == nil) || (want != nil && !reflect.DeepEqual(g, want)) {+ t.Fatalf("table[%s] = %#v, want %#v", k, g, want)+ }+ }+ shared := files(t, row.Must("shared"))+ for _, m := range fixtures.Obj(t, row.Must("expected")) {+ want := files(t, m.Value)+ got, err := r.ExpectedSHA256(m.Key, shared)+ if err != nil || (got == nil) != (want == nil) || (want != nil && !reflect.DeepEqual(got, want)) {+ t.Fatalf("ExpectedSHA256(%s) = %#v, %v, want %#v", m.Key, got, err, want)+ }+ }+ })+ }+ if errs != 445 {+ t.Fatalf("%d error rows, want 445", errs)+ }+}diff --git a/laya-go/router/digests_test.go b/laya-go/router/digests_test.gonew file mode 100644index 00000000..2f22a43a--- /dev/null+++ b/laya-go/router/digests_test.go@@ -0,0 +1,277 @@+package router_test++import (+ "context"+ "crypto/sha256"+ "encoding/hex"+ "errors"+ "reflect"+ "strings"+ "sync"+ "testing"++ "github.com/NandhaKishorM/laya/laya-go/agent"+ "github.com/NandhaKishorM/laya/laya-go/router"+)++func hexOf(s string) string { h := sha256.Sum256([]byte(s)); return hex.EncodeToString(h[:]) }++const cfgFile = "rl_agent_config.json"++func newDigestRouter(t *testing.T, env string, opts ...router.Option) *router.Router {+ t.Helper()+ t.Setenv("LAYA_SHA256_DIGESTS", env)+ r, err := router.New(opts...)+ if err != nil {+ t.Fatal(err)+ }+ return r+}++// digestFactory builds the toy checkpoint with what ExpectedSHA256 says, as a real factory does.+func digestFactory(rp **router.Router, shared map[string]string) router.AgentFactory {+ return func(_ context.Context, c router.Checkpoint) (*agent.Agent, error) {+ var opts []agent.Option+ exp, err := (*rp).ExpectedSHA256(string(c), shared)+ if err != nil {+ return nil, err+ }+ if exp != nil {+ opts = append(opts, agent.WithExpectedSHA256(exp))+ }+ return agent.Open(toyCheckpoint(), &probeSession{}, opts...)+ }+}++func loadVia(t *testing.T, env string, shared map[string]string, name string, opts ...router.Option) error {+ t.Helper()+ var r *router.Router+ t.Setenv("LAYA_SHA256_DIGESTS", env)+ r, err := router.New(append(opts, router.WithAgentFactory(digestFactory(&r, shared)))...)+ if err != nil {+ t.Fatal(err)+ }+ defer r.Close()+ a, err := r.Load(context.Background(), name)+ if err == nil && a == nil {+ t.Fatal("nil agent")+ }+ return err+}++func TestDigestsEnvLayering(t *testing.T) {+ good, bad := hexOf(`{}`), hexOf("x")+ flat := `{"` + cfgFile + `":"` + bad + `"}`+ nested := `{"english":{"` + cfgFile + `":"` + bad + `"},"multilingual":{"` + cfgFile + `":"` + good + `"}}`++ t.Run("flat is left to the agent", func(t *testing.T) {+ r := newDigestRouter(t, flat)+ if n := len(r.SHA256Digests()); n != 0 {+ t.Fatalf("table = %v", r.SHA256Digests())+ }+ if err := loadVia(t, flat, nil, "english"); !errors.Is(err, agent.ErrDigestMismatch) {+ t.Fatalf("flat env must still reach the agent: %v", err)+ }+ })+ t.Run("nested is split per checkpoint", func(t *testing.T) {+ if err := loadVia(t, nested, nil, "english"); !errors.Is(err, agent.ErrDigestMismatch) {+ t.Fatalf("english = %v", err)+ }+ if err := loadVia(t, nested, nil, "multilingual"); err != nil {+ t.Fatalf("multilingual = %v", err)+ }+ })+ t.Run("a checkpoint the nested map omits is masked, not read as an artifact map", func(t *testing.T) {+ if err := loadVia(t, nested, nil, "typed-decisions"); err != nil {+ t.Fatalf("typed-decisions = %v", err)+ }+ r := newDigestRouter(t, nested)+ got := r.SHA256Digests()+ if len(got) != 3 || got["typed-decisions"] == nil || len(got["typed-decisions"]) != 0 {+ t.Fatalf("placeholder = %#v", got)+ }+ })+ t.Run("keys are normalised", func(t *testing.T) {+ r := newDigestRouter(t, `{"EN ":{"a":"b"}}`)+ if got := r.SHA256Digests()["english"]; !reflect.DeepEqual(got, map[string]string{"a": "b"}) {+ t.Fatalf("english = %v", got)+ }+ })+ t.Run("a later spelling of one checkpoint wins", func(t *testing.T) {+ r := newDigestRouter(t, `{"english":{"a":"1"},"en":{"a":"2"}}`)+ if got := r.SHA256Digests()["english"]["a"]; got != "2" {+ t.Fatalf("a = %q", got)+ }+ })+ t.Run("unparseable or empty is not this layer's error", func(t *testing.T) {+ for _, v := range []string{"", " ", "{not json", "[]", `"d"`, "{}", "null", "7"} {+ if n := len(newDigestRouter(t, v).SHA256Digests()); n != 0 {+ t.Errorf("%q: table has %d entries", v, n)+ }+ }+ })+}++func TestDigestsEnvErrors(t *testing.T) {+ for _, c := range []struct{ env, want string }{+ {`{"engligh":{"a":"b"}}`, "unknown model 'engligh'"},+ {`{"model.safetensors":"x","english":{"a":"b"}}`, "LAYA_SHA256_DIGESTS must be either {artifact: digest} for every checkpoint or {model: {artifact: digest}} per checkpoint; ['english', 'model.safetensors'] mixes the two or holds a value that is neither"},+ {`{"english":{"a":"b"},"x":1}`, "mixes the two"},+ {`{"english":null}`, "mixes the two"},+ {`{"english":{"a":1}}`, `the digest of "a" in "english" must be a string`},+ } {+ t.Setenv("LAYA_SHA256_DIGESTS", c.env)+ _, err := router.New()+ if err == nil || !strings.Contains(err.Error(), c.want) {+ t.Errorf("%s: err = %v", c.env, err)+ }+ }+ t.Setenv("LAYA_SHA256_DIGESTS", `{"engligh":{}}`)+ var ue *router.UnknownModelError+ if _, err := router.New(); !errors.As(err, &ue) {+ t.Errorf("an unknown name is an *UnknownModelError: %v", err)+ }+}++func TestDigestsArgument(t *testing.T) {+ a, b := map[string]string{"model.safetensors": "a"}, map[string]string{"model.safetensors": "b"}+ t.Run("keys are normalised", func(t *testing.T) {+ r := newDigestRouter(t, "", router.WithSHA256Digests(map[string]map[string]string{"ml": a, "typed": nil}))+ got := r.SHA256Digests()+ if len(got) != 2 || !reflect.DeepEqual(got["multilingual"], a) {+ t.Fatalf("table = %v", got)+ }+ if v, ok := got["typed-decisions"]; !ok || v != nil {+ t.Fatalf("explicit nil must stay an entry: %v", got)+ }+ if n := len(newDigestRouter(t, "").SHA256Digests()); n != 0 {+ t.Fatalf("no pins, no entries: %d", n)+ }+ })+ t.Run("a misspelled name fails New", func(t *testing.T) {+ t.Setenv("LAYA_SHA256_DIGESTS", "")+ var ue *router.UnknownModelError+ _, err := router.New(router.WithSHA256Digests(map[string]map[string]string{"engligh": a}))+ if !errors.As(err, &ue) {+ t.Fatalf("err = %v", err)+ }+ })+ t.Run("the argument replaces the environment's entry whole", func(t *testing.T) {+ env := `{"english":{"x":"1","y":"2"},"multilingual":{"model.safetensors":"b"}}`+ r := newDigestRouter(t, env, router.WithSHA256Digests(map[string]map[string]string{"english": a}))+ got := r.SHA256Digests()+ if !reflect.DeepEqual(got["english"], a) || !reflect.DeepEqual(got["multilingual"], b) {+ t.Fatalf("table = %v", got)+ }+ })+ t.Run("an explicit nil masks a flat environment map for that checkpoint only", func(t *testing.T) {+ flat := `{"` + cfgFile + `":"` + hexOf("x") + `"}`+ opt := router.WithSHA256Digests(map[string]map[string]string{"english": nil})+ if err := loadVia(t, flat, nil, "english", opt); err != nil {+ t.Fatalf("english = %v", err)+ }+ if err := loadVia(t, flat, nil, "multilingual", opt); !errors.Is(err, agent.ErrDigestMismatch) {+ t.Fatalf("multilingual keeps the environment: %v", err)+ }+ })+ t.Run("a later option replaces an earlier one per name", func(t *testing.T) {+ r := newDigestRouter(t, "",+ router.WithSHA256Digests(map[string]map[string]string{"english": a, "multilingual": a}),+ router.WithSHA256Digests(map[string]map[string]string{"english": b}))+ got := r.SHA256Digests()+ if !reflect.DeepEqual(got["english"], b) || !reflect.DeepEqual(got["multilingual"], a) {+ t.Fatalf("table = %v", got)+ }+ })+ t.Run("the caller's map is copied", func(t *testing.T) {+ in := map[string]string{"f": "1"}+ r := newDigestRouter(t, "", router.WithSHA256Digests(map[string]map[string]string{"english": in}))+ in["f"] = "2"+ r.SHA256Digests()["english"]["f"] = "3"+ if got := r.SHA256Digests()["english"]["f"]; got != "1" {+ t.Fatalf("f = %q", got)+ }+ })+}++func TestExpectedSHA256Merge(t *testing.T) {+ shared := map[string]string{"tokenizer.json": "d", "model.safetensors": "c"}+ per := map[string]string{"model.safetensors": "b"}+ r := newDigestRouter(t, "", router.WithSHA256Digests(map[string]map[string]string{"english": per, "multilingual": nil}))+ cases := []struct {+ name string+ shared map[string]string+ want map[string]string+ }{+ {"english", nil, per},+ {"english", shared, map[string]string{"tokenizer.json": "d", "model.safetensors": "b"}}, // per-checkpoint wins+ {"multilingual", shared, shared}, // nil entry is {} and keeps shared+ {"multilingual", nil, map[string]string{}}, // nil entry still masks+ {"typed-decisions", nil, nil}, // nothing says anything+ {"typed-decisions", map[string]string{}, map[string]string{}},+ {"typed-decisions", shared, shared},+ }+ for _, c := range cases {+ got, err := r.ExpectedSHA256(c.name, c.shared)+ if err != nil || (got == nil) != (c.want == nil) || !reflect.DeepEqual(got, c.want) {+ t.Errorf("%s %v = %#v, %v, want %#v", c.name, c.shared, got, err, c.want)+ }+ }+ got, _ := r.ExpectedSHA256("english", shared)+ got["x"] = "y"+ if _, leaked := shared["x"]; leaked {+ t.Fatal("the result must be a fresh map")+ }+ if again, _ := r.ExpectedSHA256("english", nil); again["x"] != "" {+ t.Fatal("the result must not alias the table")+ }+ var ue *router.UnknownModelError+ if _, err := r.ExpectedSHA256("nope", nil); !errors.As(err, &ue) {+ t.Fatalf("unknown name: %v", err)+ }+ if got, err := r.ExpectedSHA256(" EN ", nil); err != nil || !reflect.DeepEqual(got, per) {+ t.Fatalf("alias: %v %v", got, err)+ }+}++func TestSharedAndPerCheckpointPinsBothVerify(t *testing.T) {+ good, bad := hexOf(`{}`), hexOf("x")+ // shared pins the config wrongly, the per-checkpoint entry corrects it: loads+ opt := router.WithSHA256Digests(map[string]map[string]string{"english": {cfgFile: good}})+ if err := loadVia(t, "", map[string]string{cfgFile: bad}, "english", opt); err != nil {+ t.Fatalf("override: %v", err)+ }+ // no per-checkpoint entry: shared alone is verified+ if err := loadVia(t, "", map[string]string{cfgFile: bad}, "multilingual", opt); !errors.Is(err, agent.ErrDigestMismatch) {+ t.Fatalf("shared alone: %v", err)+ }+ // a file only the per-checkpoint entry names is verified too+ opt = router.WithSHA256Digests(map[string]map[string]string{"english": {cfgFile: bad}})+ if err := loadVia(t, "", map[string]string{"tokenizer/tokenizer.json": hexOf("whatever")}, "english", opt); !errors.Is(err, agent.ErrDigestMismatch) {+ t.Fatalf("per-checkpoint file: %v", err)+ }+}++func TestDigestsConcurrentUse(t *testing.T) {+ r := newDigestRouter(t, `{"english":{"a":"1"}}`)+ var wg sync.WaitGroup+ for i := 0; i < 16; i++ {+ wg.Add(1)+ go func() {+ defer wg.Done()+ for j := 0; j < 200; j++ {+ got, err := r.ExpectedSHA256("english", map[string]string{"s": "t"})+ if err != nil || got["a"] != "1" || got["s"] != "t" {+ t.Errorf("got %v, %v", got, err)+ return+ }+ got["a"] = "mutated"+ r.SHA256Digests()["english"]["a"] = "mutated"+ }+ }()+ }+ wg.Wait()+ if got := r.SHA256Digests()["english"]["a"]; got != "1" {+ t.Fatalf("a = %q", got)+ }+}diff --git a/laya-go/router/doc.go b/laya-go/router/doc.goindex 7bd1efe6..cba4d981 100644--- a/laya-go/router/doc.go+++ b/laya-go/router/doc.go@@ -27,6 +27,14 @@// 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.//+// # Digests+//+// WithSHA256Digests pins checkpoints to the SHA-256 of their files, and a nested+// LAYA_SHA256_DIGESTS ({model: {artifact: digest}}) does the same from the environment, read by New;+// a flat one is left to the agent. ExpectedSHA256 merges those with a pin the factory holds for+// every checkpoint and returns the map for agent.WithExpectedSHA256, nil meaning pass none. The+// Router verifies nothing itself.+//// A Router is safe for concurrent use. Its routing is fixed once built; only its hook list changes// (AddHook, RemoveHook, InstallHooks).//@@ -40,5 +48,11 @@// where Python registers it. Load returns an agent that closes on eviction; Lease keeps it open.// Attach and Preload raise MaxLoaded as in Python. Hooks run concurrently as in Python; WithSerialHooks// runs one at a time (and then a hook must not call Route on its own Router). A hook failure-// names the hook's Go type.+// names the hook's Go type. Digests: SHA256Digests is a copy, where Python's sha256_digests is a+// public dict that can be edited after construction; a non-string digest in a nested+// LAYA_SHA256_DIGESTS is an error from New, where Python hands it to the agent; two spellings of one+// checkpoint in WithSHA256Digests resolve in name order, where Python uses the dict's order. Not+// ported, because the factory owns them: agent_kwargs and its reserved-name check (a factory passes+// typed agent options), revision and revisions (no hub download), preload=True (New has no context,+// call Preload), per-checkpoint lang_temperatures (a factory passes agent.WithLangTemperatures).package routerdiff --git a/laya-go/router/example_test.go b/laya-go/router/example_test.goindex 97416cf6..b2c50fbc 100644--- a/laya-go/router/example_test.go+++ b/laya-go/router/example_test.go@@ -101,3 +101,24 @@ func ExampleRouter_Lease() {// router: cannot load the english checkpoint: no weights for english in this example// [] 1}++func ExampleRouter_ExpectedSHA256() {+ t := "model.safetensors"+ r, _ := router.New(router.WithSHA256Digests(map[string]map[string]string{+ "english": {t: "aaaa"},+ "multilingual": nil, // pin nothing, even where LAYA_SHA256_DIGESTS names files+ }))+ // A factory asks for each checkpoint's map and hands a non-nil one to agent.WithExpectedSHA256.+ shared := map[string]string{"tokenizer/tokenizer.json": "dddd", t: "cccc"}+ for _, name := range []string{"english", "multilingual", "typed-decisions"} {+ m, _ := r.ExpectedSHA256(name, shared)+ fmt.Println(name, m)+ }+ m, _ := r.ExpectedSHA256("typed-decisions", nil)+ fmt.Println(m == nil)+ // Output:+ // english map[model.safetensors:aaaa tokenizer/tokenizer.json:dddd]+ // multilingual map[model.safetensors:cccc tokenizer/tokenizer.json:dddd]+ // typed-decisions map[model.safetensors:cccc tokenizer/tokenizer.json:dddd]+ // true+}diff --git a/laya-go/router/router.go b/laya-go/router/router.goindex dd757546..53021711 100644--- a/laya-go/router/router.go+++ b/laya-go/router/router.go@@ -46,12 +46,13 @@ func LangCode(code string) LangHint { return func(any) string { return code } }// Router routes requests. Build one with New.type Router struct {- models map[Checkpoint]ModelSpec- def Checkpoint- auto bool- hint LangHint- hk *hookState- lc lifecycle+ models map[Checkpoint]ModelSpec+ def Checkpoint+ auto bool+ hint LangHint+ hk *hookState+ lc lifecycle+ digests digestTable}// Option configures New.@@ -66,6 +67,7 @@ type config struct {sources []sourcefactory AgentFactorymaxLoaded int+ digests []digestPin}type source struct {@@ -133,8 +135,10 @@ func New(opts ...Option) (*Router, error) {for k, v := range base {r.models[k] = v}+ var err errorfor _, s := range c.sources {- key, err := NormaliseName(s.name)+ var key Checkpoint+ key, err = NormaliseName(s.name)if err != nil {return nil, err}@@ -143,6 +147,20 @@ func New(opts ...Option) (*Router, error) {}r.models[key] = s.spec}+ if r.digests, err = digestsFromEnv(r.models); err != nil {+ return nil, err+ }+ pins := make(digestTable, len(c.digests))+ for _, p := range c.digests {+ key, err := NormaliseName(p.name)+ if err != nil {+ return nil, err+ }+ pins[key] = p.files+ }+ for k, v := range pins {+ r.digests[k] = v+ }def, err := NormaliseName(c.def)if err != nil {return nil, err