Non-autoregressive System 1 decision engine. Typed choice, score and yes/no decisions over any text in a single forward pass, in 100+ languages, with a router that picks the right checkpoint per request.
Python calibrationclassificationdecision-modelhuggingfacejevmodernbertmultilingualnlppythonpytorchroutingtyped-decisionszero-shot
feat(router): a registry of checkpoints beside the built-ins, named like them
Alan de Freitas57d81b2fba1e
diff --git a/docs/routing.md b/docs/routing.mdindex 801abd30..3233acb7 100644--- a/docs/routing.md+++ b/docs/routing.md@@ -124,6 +124,22 @@ question wording, and adding unrelated question IDs prevents an exact match.router = Router(auto_task_detection=True)```+## Registering your own checkpoints++`Router(models=...)` and `Router.register(name, source, description=None)` accept any name beside the+three built-in ones. A source is a Hub repo id, a `(repo, subfolder)` pair or a local directory. A+registered checkpoint loads, is evicted and unloads like a built-in, and is named in `model=` or+`task=` like one. `Router.registered` lists the registered checkpoints and `Router.unregister(name)`+removes one.++```python+router = Router(models={"papers": "/models/laya-papers"})+router.register("tone", ("acme/laya-tone", None), description="tone of voice")+result = router.predict(state, questions, model="papers")+```++`normalise_name` still knows only the built-in names, while `Router.resolve` also knows the registry.+## Inspect routing without loading modelsUse `route()` to inspect one decision or `route_batch()` to inspect a sequence. Neither methoddiff --git a/examples/39_error_handling.py b/examples/39_error_handling.pyindex cfb36bdb..5e85e19d 100644--- a/examples/39_error_handling.py+++ b/examples/39_error_handling.py@@ -12,7 +12,7 @@ from laya.router import Routerbanner("39", "Error handling", """Five things a caller should be ready for:- 1. an unknown model name passed to `Router` -> ValueError, before anything loads;+ 1. a typo in `model=` on a `Router` -> ValueError, before anything loads;2. `laya.load` on a missing local path -> FileNotFoundError;3. a `choice` question with empty criteria -> ValueError naming it, before the model runs;4. a question whose options do not fit -> ValueError, but only once they overflow;@@ -24,13 +24,19 @@ banner("39", "Error handling", """TICKET = {"body": "I was charged twice and also my login is broken. Can someone look into it?"}-heading("1. Router with an unknown model name")+heading("1. A typo in `model=` on a Router")+# A name `Router(models=...)` does not know is not a typo: it registers a checkpoint of your own+# under that name -- a fine-tune in a local directory, a repo you pushed -- served beside the+# built-ins and loaded only when a request routes to it. The typo is in the request.+router = Router(models={"bogus": "/nowhere/at/all"})+print(" Router(models={'bogus': ...}) registered it beside the built-ins: %s" % sorted(router.registered))try:- Router(models={"bogus": "/nowhere/at/all"})+ router.route(TICKET, {"q": {"type": "noul", "instructions": "Is this about billing?"}}, model="bogsu")print(" no exception raised")except ValueError as e:print(" raised ValueError: %s" % e)-print(" -> the name is normalised in the constructor, so a typo fails before any weights load.")+print(" -> `model=` is resolved against the built-ins plus what you registered, so a typo fails")+print(" before any weights load; nothing is downloaded until a request routes to a name.")heading("2. laya.load on a path that does not exist")# `LOCAL_MODELS` is the directory each checkpoint would live in; `MODELS` is the `Router` spec,diff --git a/laya/router.py b/laya/router.pyindex 5138d918..fd1a6273 100644--- a/laya/router.py+++ b/laya/router.py@@ -32,6 +32,7 @@ import gcimport inspectimport jsonimport os+import reimport threadingimport timeimport warnings@@ -92,6 +93,22 @@ _TYPED_DECISION_WORKFLOWS = {"security_incidents": {"credential_compromise", "disposition", "severity", "true_positive", "urgency"},}+# What a caller may name a checkpoint of their own, once `canonical_name` has trimmed and+# lowercased it (so `Papers` is registered as `papers`): letters, digits, `.`, `_` and `-`, starting+# with a letter or digit. No `/`, because a Hub id or a path is a source, not a name.+_NAME_RE = re.compile(r"^[a-z0-9][a-z0-9._-]*$")+++def canonical_name(name: Any) -> str:+ """Trim, lowercase and resolve an alias, without asking whether the result names a checkpoint.++ The spelling half of :func:`normalise_name`. `Router.resolve` applies it and then checks the+ Router's own registry, which holds the built-in checkpoints plus any the caller registered;+ `normalise_name` applies it and checks the built-in table alone.+ """+ key = str(name).strip().lower()+ return _ALIASES.get(key, key)+class RouteDecision(dict):"""The routing outcome: which model, why, and what was detected.@@ -112,8 +129,14 @@ class RouteDecision(dict):def normalise_name(name: str) -> str:- key = str(name).strip().lower()- key = _ALIASES.get(key, key)+ """Canonical name of a built-in checkpoint, or ValueError.++ This is the registry of the checkpoints the package ships. A Router may know more -- the+ checkpoints registered on it with `Router(models=...)` or `Router.register` -- and resolves+ names through `Router.resolve`, which accepts those too. Code with no Router at hand (the CLI's+ `--model`, `laya.load`) keeps using this one.+ """+ key = canonical_name(name)if key not in DEFAULT_MODELS:raise ValueError("unknown model %r; choose one of %s (or an alias: %s)"% (name, sorted(DEFAULT_MODELS), sorted(_ALIASES)))@@ -346,7 +369,7 @@ def check_agent_kwargs(agent_kwargs: Dict[str, Any]) -> None:% (", ".join(repr(n) for n in unknown), sorted(accepted - _ROUTER_OWNED_AGENT_ARGS)))-def _digests_from_env(models: Dict[str, Any]) -> Dict[str, Optional[Dict[str, str]]]:+def _digests_from_env(models: Dict[str, Any], resolve=normalise_name) -> Dict[str, Optional[Dict[str, str]]]:"""Turn `LAYA_SHA256_DIGESTS` into per-checkpoint digest maps when it names models.The variable has two shapes, and the value types say which. A flat@@ -383,9 +406,9 @@ def _digests_from_env(models: Dict[str, Any]) -> Dict[str, Optional[Dict[str, straise ValueError("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" % sorted(data))- per_model = {normalise_name(k): dict(v) for k, v in data.items()}+ per_model = {resolve(k): dict(v) for k, v in data.items()}for name in models:- per_model.setdefault(normalise_name(name), {})+ per_model.setdefault(resolve(name), {})return per_model@@ -636,9 +659,16 @@ class Router(HookRegistry):self.hooks_timeout = None if hooks_timeout is None else validate_timeout(hooks_timeout)self._hooks_lock = threading.RLock() if not hooks_concurrent else Noneself._hooks_mutex = threading.Lock()- self.models = dict(STANDALONE_MODELS if standalone_repos else DEFAULT_MODELS)- if models:- self.models.update({normalise_name(k): v for k, v in models.items()})+ # The registry: built-in names first, then whatever the caller adds. A key that is a+ # built-in name re-points that checkpoint (a fine-tune standing in for `english`); any+ # other key registers a checkpoint of the caller's own, served beside the built-ins and+ # named in `model=` like one of them.+ self.models: Dict[str, Any] = dict(STANDALONE_MODELS if standalone_repos else DEFAULT_MODELS)+ # Free text per registered checkpoint, reported by `registered`; a public mutable attribute+ # like `sha256_digests`, filled by `register`.+ self.descriptions: Dict[str, str] = {}+ for k, v in (models or {}).items():+ self._add(k, v)self.device = deviceself.token = token or os.environ.get("HF_TOKEN")# Optional Hub revision (commit SHA/branch/tag) applied to every checkpoint load.@@ -646,7 +676,7 @@ class Router(HookRegistry):# reviewed commits differ.self.revision = revisionself.revisions: Dict[str, Optional[str]] = {- normalise_name(k): v for k, v in (revisions or {}).items()+ self.resolve(k): v for k, v in (revisions or {}).items()}# Options forwarded to every `Agent` this Router builds, checked now so a bad name fails on# this line rather than the first request that happens to load a checkpoint.@@ -657,11 +687,11 @@ class Router(HookRegistry):# overridden checkpoint by checkpoint by the argument. Keyed and normalised exactly like# `revisions`, so a misspelled model name fails here rather than leaving that checkpoint# unverified.- self.sha256_digests: Dict[str, Optional[Dict[str, str]]] = _digests_from_env(self.models)- argument = {normalise_name(k): v for k, v in (sha256_digests or {}).items()}+ self.sha256_digests: Dict[str, Optional[Dict[str, str]]] = _digests_from_env(self.models, self.resolve)+ argument = {self.resolve(k): v for k, v in (sha256_digests or {}).items()}self.sha256_digests.update(argument)self.max_loaded = max(1, int(max_loaded))- self.default = normalise_name(default)+ self.default = self.resolve(default)self.auto_task_detection = bool(auto_task_detection)# An opt-in language hint installed for every request: a code, or a callable taking the# state and returning one (or None to abstain). Checked before the built-in detection,@@ -688,13 +718,132 @@ class Router(HookRegistry):if preload:self.preload()+ # ------------------------------------------------------------------ registry+ def resolve(self, name: Any) -> str:+ """Canonical key of a checkpoint this Router knows: built-in, aliased, or registered.++ The instance counterpart of :func:`normalise_name`. Everything on the Router that takes a+ checkpoint name goes through here, so a checkpoint registered under `papers` is accepted+ wherever `english` is: `model=`, `task=`, `load`, `unload`, `preload`, `revisions`.+ """+ key = canonical_name(name)+ if key in self.models:+ return key+ raise ValueError("unknown model %r; choose one of %s (or an alias: %s)"+ % (name, sorted(self.models), sorted(_ALIASES)))++ def register(self, name: str, source: Any, description: Optional[str] = None) -> str:+ """Add a checkpoint under `name`, to be served beside the built-in ones.++ `source` is what `laya.load` accepts: a Hub repo id, a `(repo, subfolder)` pair, or a local+ directory holding `model.safetensors` and `rl_agent_config.json` -- a fine-tune exported by+ the training recipe, for instance. Nothing is downloaded or built here; the checkpoint loads+ on first use like the built-ins, is evicted and unloaded like them, and counts toward+ `max_loaded` like them.++ `description` is free text about the checkpoint for whoever reads `registered`.++ A nested `LAYA_SHA256_DIGESTS` entry for this name is picked up here; an entry for a name the+ constructor did not know still fails at construction, as before.++ Returns the canonical name. Registering an existing name replaces its source and unloads the+ resident Agent, so the next load builds from the new source.+ """+ with self._lock:+ key = canonical_name(name)+ missing = object() # a present None (an opted-out digest entry) is not an absent key+ before = (self.models.get(key, missing), self.sha256_digests.get(key, missing),+ self.descriptions.get(key, missing))+ try:+ key = self._add(name, source)+ if key not in self.sha256_digests:+ # A nested LAYA_SHA256_DIGESTS names no file of this checkpoint: the `{}` placeholder+ # the constructor gives every model keeps `verify_digests` off the nested map.+ from_env = _digests_from_env([key], canonical_name).get(key)+ if from_env is not None:+ self.sha256_digests[key] = from_env+ if description is not None:+ self.descriptions[key] = str(description)+ except BaseException: # a refused register() leaves the router as it was+ for table, old in ((self.models, before[0]), (self.sha256_digests, before[1]),+ (self.descriptions, before[2])):+ if old is missing:+ table.pop(key, None)+ else:+ table[key] = old+ raise+ replaced = before[0] is not missing and before[0] != self.models[key]+ if replaced:+ freed = self._unload_key(key) # outside the lock, waiting for a build of the old source+ if freed:+ self._dispatch_lifecycle("on_evict", freed)+ return key++ def unregister(self, name: str) -> None:+ """Remove a registered checkpoint: its source, description, revision and digest entries, and resident Agent.++ A built-in name is refused (re-point it with `register`, it cannot be removed), and so is a+ name the router does not know. A resident Agent is unloaded first, waiting for an in-flight+ build of it, so a request that already holds it finishes; a request that names it afterwards+ gets the usual unknown-model error.+ """+ key = self.resolve(name)+ if key in DEFAULT_MODELS:+ raise ValueError("%r is a built-in checkpoint and cannot be unregistered" % key)+ if key == self.default:+ raise ValueError("%r is this Router's default checkpoint; set another default before "+ "unregistering it" % key)+ with self._lock:+ self.models.pop(key, None) # first, so no new load can start a build of it+ freed = self._unload_key(key) # waits for a build that had already read its source+ with self._lock:+ for table in (self.descriptions, self.sha256_digests, self.revisions):+ table.pop(key, None)+ self._agents.pop(key, None)+ if key in self._order:+ self._order.remove(key)+ self._dispatch_lifecycle("on_evict", freed)++ @property+ def registered(self) -> Dict[str, Dict[str, Any]]:+ """The checkpoints registered beside the built-ins: name -> source and description.++ Serialisable as it is.+ """+ with self._lock:+ return {+ name: {+ "source": _repo_str(spec),+ "description": self.descriptions.get(name),+ }+ for name, spec in self.models.items() if name not in DEFAULT_MODELS+ }++ def _add(self, name: Any, source: Any) -> str:+ """`register` without the lock, for the constructor."""+ key = canonical_name(name)+ if key not in DEFAULT_MODELS:+ if not isinstance(name, str) or not _NAME_RE.match(key):+ raise ValueError("invalid checkpoint name %r: use lowercase letters, digits, '.', '_' or '-', "+ "starting with a letter or digit" % (name,))+ if key == "auto":+ raise ValueError("invalid checkpoint name %r: 'auto' means automatic routing in every "+ "model= argument" % (name,))+ if source is not None and not isinstance(source, (str, tuple, list)):+ raise TypeError("checkpoint source for %r must be a repo id, a local path or a (repo, subfolder) "+ "pair, got %s" % (name, type(source).__name__))+ if isinstance(source, str) and source.startswith("~"):+ source = os.path.expanduser(source) # a local path, never a Hub repo id+ self.models[key] = source+ return key+# ------------------------------------------------------------------ loadingdef load(self, name: str):"""Return the Agent for `name`, downloading and building it on first use.Concurrent callers share a single Agent instead of building duplicates."""- key = normalise_name(name)+ key = self.resolve(name)while True:with self._lock:if key in self._agents:@@ -754,6 +903,9 @@ class Router(HookRegistry):"""Construct the Agent for `key`: config is read under `_lock`, the build runs outside it."""from .agent import Agentwith self._lock:+ if self.models.get(key) is None:+ raise ValueError("checkpoint %r has no source to load from: it was attached as a built Agent "+ "and is no longer resident; attach it again, or register a path or repo" % key)repo, sub = _split(self.models[key])kwargs = {"device": self.device, "token": self.token, "subfolder": sub}# A None or blank entry in `revisions` is "no pin of its own", so the checkpoint@@ -823,9 +975,16 @@ class Router(HookRegistry):Useful when the process has a checkpoint loaded for other reasons: a demo that alreadybuilt `convaiinnovations/laya` can hand it to the router rather than pay for -- and holdin memory -- a duplicate 421M parameters.++ A name the Router does not know yet is registered on the spot, with no source: the agent+ serves under that name while resident, and loading it again after an unload needs+ `register(name, source)` first."""- key = normalise_name(name)with self._lock:+ try:+ key = self.resolve(name)+ except ValueError:+ key = self._add(name, None)self._agents[key] = agentself._touch(key)self.max_loaded = max(self.max_loaded, len(self._agents))@@ -839,7 +998,12 @@ class Router(HookRegistry):server or a demo. `max_loaded` is raised to fit both the requested checkpoints andall already-resident agents, so incremental preloading does not evict either."""- names = [normalise_name(n) for n in (list(self.models) if names is None else names)]+ if names is None:+ # Every checkpoint that has a source to build from; an `attach`ed agent registered+ # without one is resident already and would raise here once evicted.+ with self._lock:+ names = [n for n, source in self.models.items() if source is not None]+ names = [self.resolve(n) for n in names]with self._lock:self.max_loaded = max(self.max_loaded, len(set(names) | set(self._agents)))for n in names:@@ -850,6 +1014,33 @@ class Router(HookRegistry):self.load(n)return self+ def _unload_key(self, key: str) -> List[str]:+ """`unload` for a canonical key that may already be gone from `models`; returns what it freed."""+ freed: List[str] = []+ while True:+ with self._lock:+ inflight = self._loading.get(key)+ if inflight is None:+ agent = self._agents.pop(key, None)+ if key in self._order:+ self._order.remove(key)+ freed = [key] if agent is not None else []+ del agent+ gc.collect()+ try:+ import torch+ if torch.cuda.is_available():+ torch.cuda.empty_cache()+ if hasattr(torch, "xpu") and torch.xpu.is_available():+ torch.xpu.empty_cache()+ if hasattr(torch, "mps") and torch.backends.mps.is_available():+ torch.mps.empty_cache()+ except Exception:+ pass+ break+ inflight.done.wait()+ return freed+def unload(self, name: Optional[str] = None):"""Free one model, or all of them."""# When unloading a specific checkpoint, wait only for an in-flight build of THAT@@ -857,29 +1048,7 @@ class Router(HookRegistry):# When unloading all checkpoints (`name is None`), wait for all in-flight builds.freed: List[str] = []if name is not None:- key = normalise_name(name)- while True:- with self._lock:- inflight = self._loading.get(key)- if inflight is None:- agent = self._agents.pop(key, None)- if key in self._order:- self._order.remove(key)- freed = [key] if agent is not None else []- del agent- gc.collect()- try:- import torch- if torch.cuda.is_available():- torch.cuda.empty_cache()- if hasattr(torch, "xpu") and torch.xpu.is_available():- torch.xpu.empty_cache()- if hasattr(torch, "mps") and torch.backends.mps.is_available():- torch.mps.empty_cache()- except Exception:- pass- break- inflight.done.wait()+ freed = self._unload_key(self.resolve(name))else:while True:with self._lock:@@ -979,14 +1148,16 @@ class Router(HookRegistry):which lets a language-identification model abstain. Pass one here, or set`Router(lang_guess=...)` to apply it to every request."""+ # `.get`, not `[]`: a concurrent `unregister` can remove the name between `resolve` and this+ # lookup, and the decision then reports no repo rather than raising.if model is not None:- key = normalise_name(model)- return RouteDecision(model=key, repo=_repo_str(self.models[key]), reason="explicit model=%r" % model,+ key = self.resolve(model)+ return RouteDecision(model=key, repo=_repo_str(self.models.get(key)), reason="explicit model=%r" % model,detection=None, workflow=None)if task is not None:- key = normalise_name("typed-decisions" if str(task).lower().replace("-", "_") == "typed_decisions" else task)- return RouteDecision(model=key, repo=_repo_str(self.models[key]), reason="explicit task=%r" % task,+ key = self.resolve("typed-decisions" if str(task).lower().replace("-", "_") == "typed_decisions" else task)+ return RouteDecision(model=key, repo=_repo_str(self.models.get(key)), reason="explicit task=%r" % task,detection=None, workflow=None)workflow = match_typed_decisions_workflow(questions or {})@@ -1411,7 +1582,7 @@ class Router(HookRegistry):# Indexed, not `.model`: an on_route hook may replace the decision with a plain dict,# which `predict` accepts too. Normalised, because such a hook may name the checkpoint# by an alias ("ml"), and that request must share its checkpoint's forward pass.- groups.setdefault(normalise_name(decision["model"]), []).append(i)+ groups.setdefault(self.resolve(decision["model"]), []).append(i)# Counted rather than marked with None: an end hook may leave a None result, which# `predict` returns as it is.diff --git a/tests/test_hooks_api.py b/tests/test_hooks_api.pyindex 8d97c165..c1a0386d 100644--- a/tests/test_hooks_api.py+++ b/tests/test_hooks_api.py@@ -87,6 +87,9 @@ check_param("Router.__init__", Router.__init__, "revisions", None)check_param("Router.__init__", Router.__init__, "agent_kwargs", None)# ...and the per-checkpoint digests that `revisions` has always had a sibling need forcheck_param("Router.__init__", Router.__init__, "sha256_digests", None)+# ...and the checkpoints a caller registers beside the built-ins: `resolve` and `unregister` are the instance side+check_true("Router/resolve", callable(getattr(Router, "resolve", None)))+check_param("Router.unregister", Router.unregister, "name", inspect.Parameter.empty)# What the constructor does NOT raise over is part of its contract too: a shared# `agent_kwargs["expected_sha256"]` overlapping a per-checkpoint `sha256_digests` entry on one filediff --git a/tests/test_router.py b/tests/test_router.pyindex 7a25c759..a79a843a 100644--- a/tests/test_router.py+++ b/tests/test_router.py@@ -1608,6 +1608,334 @@ check("lang-code/agnostic primary wins over its subtag", _english_from_code("C.Ucheck("lang-code/posix with a modifier abstains", _english_from_code("POSIX-1"), None)+# --------------------------------------------------------------------- registered checkpoints+# A Router serves the checkpoints a caller registers beside the built-in three: named in `model=`+# or `task=` like them, and loaded, evicted and unloaded like them.+from laya.router import canonical_name # noqa: E402++check("registry/canonical lowercases and aliases", canonical_name(" ML "), "multilingual")+check("registry/canonical leaves an unknown name as typed", canonical_name("Papers"), "papers")++_SECTION_Q = {"section": {"type": "choice", "instructions": "Which section?", "criteria": {"a": "A", "b": "B"}}}+_CLAIM = "Transparency improved operator performance in 11 of 17 studies."+r = Router(models={"papers": "/tmp/laya-papers", "tone": ("acme/laya-tone", None)})+check("registry/registered names resolve", r.resolve("papers"), "papers")+check("registry/registered names resolve case-insensitively", r.resolve(" PAPERS "), "papers")+check("registry/built-ins still resolve", r.resolve("ml"), "multilingual")+check("registry/models holds built-ins plus registered", sorted(r.models),+ ["english", "multilingual", "papers", "tone", "typed-decisions"])+try:+ r.resolve("nope")+ check("registry/unknown name raises", False, True)+except ValueError as e:+ check("registry/unknown name lists the registered ones too", "'papers'" in str(e), True)+check("registry/normalise_name still knows only the built-ins", resolve_model_spec("papers"), None)++d = r.route(_CLAIM, _SECTION_Q, model="papers")+check("route/model= names a registered checkpoint", d.model, "papers")+check("route/repo is the registered source", d["repo"], "/tmp/laya-papers")+check("route/model= accepts a registered (repo, subfolder) pair", r.route(_CLAIM, _SECTION_Q, model="tone")["repo"],+ "acme/laya-tone")+check("route/task= names a registered checkpoint", r.route(_CLAIM, _SECTION_Q, task="tone").model, "tone")+check("route/a registered checkpoint is never chosen automatically", r.route(_CLAIM, _SECTION_Q).model, "english")+check("route/route_batch keeps the mix in order",+ [x.model for x in r.route_batch([{"state": _CLAIM, "questions": _SECTION_Q, "model": "papers"},+ {"state": _CLAIM, "questions": _SECTION_Q},+ {"state": _CLAIM, "questions": _SECTION_Q, "model": "tone"}])],+ ["papers", "english", "tone"])+check("registered/reports source and description", Router(models={"papers": "/tmp/laya-papers"}).registered,+ {"papers": {"source": "/tmp/laya-papers", "description": None}})+check("registered/built-ins are not listed", Router().registered, {})++# The built-in typed-decisions workflows are unchanged: opt-in, and still routed to the built-in.+_CS = {q: _SECTION_Q["section"] for q in ("action", "category", "churn_risk", "needs_human", "urgency")}+check("workflow/still needs auto_task_detection", r.route(_CLAIM, _CS).model, "english")+check("workflow/with auto_task_detection",+ Router(auto_task_detection=True).route(_CLAIM, _CS)["workflow"], "customer_service")++# a checkpoint registered after construction is not read as an artifact map of a nested env.+_old_env = os.environ.get("LAYA_SHA256_DIGESTS")+os.environ["LAYA_SHA256_DIGESTS"] = '{"english": {"model.safetensors": "%s"}}' % ("c" * 64)+try:+ _r_late = Router()+ _r_late.register("mine", "/tmp/laya-mine")+ check("register/nested LAYA_SHA256_DIGESTS gives a later checkpoint the empty placeholder",+ _r_late.sha256_digests["mine"], {})+finally:+ if _old_env is None:+ os.environ.pop("LAYA_SHA256_DIGESTS", None)+ else:+ os.environ["LAYA_SHA256_DIGESTS"] = _old_env++# a source starting with ~ is a local path.+check("register/~ in a source is expanded", Router(models={"mine": "~/laya-mine"}).models["mine"],+ os.path.expanduser("~/laya-mine"))++# `auto` is the routing word everywhere, so it cannot name a checkpoint.+try:+ Router().register("auto", "/tmp/laya-auto")+ check("register/auto is refused", True, False)+except ValueError as _e:+ check("register/auto is refused", "auto" in str(_e), True)++# an attach()ed agent with no source is not part of a whole-router preload.+with patch("laya.agent.Agent", side_effect=lambda repo, **kw: _Stub(repo)) as _build_att:+ _r_att = Router()+ _r_att.attach("mine", _Stub("mine"))+ _r_att.unload("mine")+ _r_att.preload()+ check("preload/skips a name with no source", sorted(_r_att.loaded),+ ["english", "multilingual", "typed-decisions"])++# register(): the same thing after construction.+r2 = Router()+check("register/returns the canonical name", r2.register("Tone", "acme/laya-tone", description="tone"), "tone")+check("register/description is reported", r2.registered["tone"], {"source": "acme/laya-tone", "description": "tone"})+check("register/a second call replaces the source", (r2.register("tone", "/tmp/tone-v2"), r2.models["tone"])[1], "/tmp/tone-v2")+check("register/replacing the source keeps the description", r2.registered["tone"]["description"], "tone")+check("register/a built-in name re-points that checkpoint",+ Router(models={"english": "/tmp/my-english"}).models["english"], "/tmp/my-english")+check("register/an alias re-points its built-in", Router(models={"en": "/tmp/mine"}).models["english"], "/tmp/mine")+for bad, why in (("Bad/Name", "slash"), ("", "empty"), ("-dash", "leading dash"), ("a b", "space")):+ try:+ Router().register(bad, "/tmp/x")+ check("register/refuses %s" % why, False, True)+ except ValueError:+ check("register/refuses %s" % why, True, True)+try:+ Router(models={"papers": 42})+ check("register/a source must be a path, repo or pair", False, True)+except TypeError:+ check("register/a source must be a path, repo or pair", True, True)++# Every name-taking option accepts a registered name, the way it accepts a built-in one.+r3 = Router(models={"papers": "/tmp/laya-papers"}, revisions={"papers": "abc123"}, default="papers",+ sha256_digests={"papers": {"model.safetensors": "a" * 64}})+check("register/default may be a registered name", r3.default, "papers")+check("register/revisions keyed by a registered name", r3.revisions, {"papers": "abc123"})+check("register/sha256_digests keyed by a registered name", r3.sha256_digests["papers"], {"model.safetensors": "a" * 64})+check("register/undecided text falls back to the registered default",+ r3.route("Quero cancelar", {"q": _SECTION_Q["section"]}).model, "papers")+_old_env = os.environ.get("LAYA_SHA256_DIGESTS")+os.environ["LAYA_SHA256_DIGESTS"] = '{"papers": {"model.safetensors": "%s"}}' % ("b" * 64)+try:+ check("register/LAYA_SHA256_DIGESTS may name a registered checkpoint",+ Router(models={"papers": "/tmp/laya-papers"}).sha256_digests["papers"], {"model.safetensors": "b" * 64})+finally:+ if _old_env is None:+ os.environ.pop("LAYA_SHA256_DIGESTS", None)+ else:+ os.environ["LAYA_SHA256_DIGESTS"] = _old_env++# attach() under a new name registers it with no source: resident now, not reloadable later.+r4 = Router()+r4.attach("adhoc", _Stub("adhoc"))+check("attach/new name becomes resident", "adhoc" in r4.loaded, True)+check("attach/new name is routable", r4.route(_CLAIM, _SECTION_Q, model="adhoc").model, "adhoc")+check("attach/new name has no source", r4.models["adhoc"], None)+r4.unload("adhoc")+try:+ r4.load("adhoc")+ check("attach/reload without a source is refused", False, True)+except ValueError as e:+ check("attach/reload without a source is refused", "no source" in str(e), True)++# load() hands a registered local path or repo to Agent as a source, not as a registry name.+import laya.agent as _agent_for_registry+_built = []+++class _RecordingAgent:+ def __init__(self, repo, **kwargs):+ _built.append((repo, kwargs.get("subfolder")))+++_prev_agent = _agent_for_registry.Agent+_agent_for_registry.Agent = _RecordingAgent+try:+ r5 = Router(models={"papers": "/tmp/laya-papers", "tone": ("acme/laya-tone", "v2")}, max_loaded=3)+ r5.load("papers")+ r5.load("tone")+ check("load/a registered path reaches Agent unchanged", _built[0], ("/tmp/laya-papers", None))+ check("load/a registered (repo, subfolder) pair reaches Agent", _built[1], ("acme/laya-tone", "v2"))+ check("load/registered checkpoints are resident like built-ins", r5.loaded, ["papers", "tone"])+ r5.preload(["papers", "english"])+ check("load/preload accepts registered names", "english" in r5.loaded and "papers" in r5.loaded, True)+ r5.unload("papers")+ check("load/unload accepts registered names", "papers" in r5.loaded, False)+finally:+ _agent_for_registry.Agent = _prev_agent+++# A refused register() leaves the router as it was.+_at = Router(models={"a": "/a", "b": "/b"})+try:+ _at.register("Bad/Name", "/x", description="x")+ _at_raised = False+except ValueError:+ _at_raised = True+check("register/refused call raises", _at_raised, True)+check("register/refused call leaves no checkpoint", ("bad/name" in _at.models, "bad/name" in _at.descriptions), (False, False))+_at2 = Router(models={"a": "/a"})+try:+ _at2.register("a", 42)+except TypeError:+ pass+check("register/refused call keeps the old source", _at2.registered["a"]["source"], "/a")++# An explicit `sha256_digests[name] = None` is a present entry that opts that checkpoint out of+# digest checks; a refused register() must restore it, not drop it (dropping it would hand the+# checkpoint back to the environment's digest map).+_at3 = Router(models={"a": "/a"}, sha256_digests={"a": None})+try:+ _at3.register("a", 42)+ check("register/refused call raises on a bad source", False, True)+except TypeError:+ check("register/refused call raises on a bad source", True, True)+check("register/refused call keeps an opted-out digest entry", ("a" in _at3.sha256_digests, _at3.sha256_digests.get("a", "gone")),+ (True, None))+check("register/refused call keeps the old source after a digest opt-out", _at3.models["a"], "/a")++# unregister() removes a registered name everywhere.+_rp = Router(models={"a": "/a", "b": "/b"})+_rp.descriptions["a"] = "A"+_rp.sha256_digests["a"] = None+_rp.revisions["a"] = "main"+_rp.attach("a", object())+_rp.unregister("a")+check("unregister/removes the name everywhere",+ ("a" in _rp.models, "a" in _rp.descriptions, "a" in _rp.sha256_digests,+ "a" in _rp.revisions, "a" in _rp.loaded, "a" in _rp.registered), (False,) * 6)+check("unregister/others are untouched", sorted(_rp.registered), ["b"])+for _bad in ("english", "ml", "never-registered"):+ try:+ _rp.unregister(_bad)+ check("unregister/%s refused" % _bad, False, True)+ except ValueError:+ check("unregister/%s refused" % _bad, True, True)+_rp.register("a", "/a")+check("unregister/the name can be registered again", "a" in _rp.registered, True)++# Routing while another thread re-registers and unregisters never fails or answers from a torn state.+_rc = Router(models={"a": "/a"})+_bad = []+++def _churn():+ for _ in range(40):+ _rc.register("a", "/a")+ _rc.register("c", "/c")+ _rc.unregister("c")+++def _route():+ for _ in range(200):+ try:+ _got = _rc.route(_CLAIM, model="a").model+ if _got != "a":+ _bad.append(_got)+ _rc.registered+ try:+ _rc.route(_CLAIM, model="c")+ except ValueError: # unregistered at that instant+ pass+ except Exception as exc: # noqa: BLE001+ _bad.append(exc)+++_th = [threading.Thread(target=_churn)] + [threading.Thread(target=_route) for _ in range(3)]+for _t in _th:+ _t.start()+for _t in _th[1:]:+ _t.join()+_th[0].join()+check("register+unregister while routing stay consistent", _bad[:3], [])+++def _swallow(fn, *args):+ try:+ fn(*args)+ except Exception: # noqa: BLE001+ pass+++def _test_unregister_during_build_leaves_no_zombie():+ """unregister waits for a build already in flight and leaves nothing under the dropped name."""+ import laya.agent as _agent_mod+ started, release = threading.Event(), threading.Event()++ class _Slow:+ def __init__(self, *args, **kwargs):+ started.set()+ release.wait(5)++ old = _agent_mod.Agent+ _agent_mod.Agent = _Slow+ try:+ r = Router(models={"tone": "/tone"})+ outcome = []++ def _load():+ try:+ outcome.append(r.load("tone"))+ except ValueError as e:+ outcome.append(e)++ loader = threading.Thread(target=_load, daemon=True)+ loader.start()+ started.wait(2)+ _timer = threading.Timer(0.3, release.set)+ _timer.start()+ t0 = _time.perf_counter()+ r.unregister("tone")+ waited = _time.perf_counter() - t0+ loader.join(2)+ _timer.cancel()+ return (waited >= 0.2, loader.is_alive(), len(outcome) == 1,+ "tone" in r.loaded, "tone" in r.models, "tone" in r._agents, "tone" in r._order,+ "tone" in r._loading)+ finally:+ release.set()+ _agent_mod.Agent = old+++check("unregister/a build in flight is waited for and leaves nothing behind",+ _test_unregister_during_build_leaves_no_zombie(),+ (True, False, True, False, False, False, False, False))++# The default checkpoint cannot be unregistered, and the router keeps routing.+_rd = Router(models={"papers": "/x"}, default="papers")+try:+ _rd.unregister("papers")+ check("unregister/the default is refused", False, True)+except ValueError as _e:+ check("unregister/the default is refused", "default" in str(_e), True)+check("unregister/a refused default still routes", _rd.route("12345").model, "papers")+++# Re-registering a name with a new source unloads the resident Agent; the same source does not.+class _EvictLog:+ def __init__(self):+ self.evicts = []++ def on_evict(self, ctx):+ self.evicts.append(ctx.model)+++_log = _EvictLog()+_rr = Router(hooks=[_log])+_rr.attach("papers", _Stub("papers"))+_rr.register("papers", "/y")+check("register/a new source unloads the resident agent", "papers" in _rr.loaded, False)+check("register/a new source fires on_evict", _log.evicts, ["papers"])+_rr.attach("papers", _Stub("papers"))+_rr.register("papers", "/y")+check("register/the same source keeps the resident agent", "papers" in _rr.loaded, True)+check("register/the same source fires no on_evict", _log.evicts, ["papers"])+_rr.register("fresh", "/z")+check("register/a new name unloads nothing", _log.evicts, ["papers"])++# --------------------------------------------------------------------- reportprint("\n%d passed, %d failed" % (len(PASS), len(FAIL)))for f in FAIL: