Skip to content

armgit / laya

Public Imported from GitHub
0

Non-autoregressive System 1 decision engine. Typed choice, score and yes/no decisions over any text in a single forward pass, in 100+ languages, with a router that picks the right checkpoint per request.

feat(router): warn when a registered name is one edit from a built-in

Cursor Agentd728d6f46c49
diff --git a/docs/routing.md b/docs/routing.md
index c5e527a8..2d31b4c3 100644
--- a/docs/routing.md
+++ b/docs/routing.md
@@ -131,7 +131,8 @@ router = Router(auto_task_detection=True)
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.
+removes one. A name one edit from a built-in, such as `englsh` for `english`, is still registered
+as its own checkpoint and a warning names the built-in, which is left unchanged.
```python
router = Router(models={"papers": "/models/laya-papers"})
diff --git a/laya/router.py b/laya/router.py
index 00bf193a..adc69d77 100644
--- a/laya/router.py
+++ b/laya/router.py
@@ -98,6 +98,52 @@ _TYPED_DECISION_WORKFLOWS = {
# 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._-]*$")
+# An adjacent transposition counts as one edit, so `enlgish` is one away from
+# `english`. Set this false for plain Levenshtein, where that pair costs two.
+_COUNT_ADJACENT_SWAP = True
+
+
+def _edit_distance(left: str, right: str) -> int:
+ """Edits that turn `left` into `right`: insert, delete, substitute, adjacent swap.
+
+ The swap is the only step that is not Levenshtein. It is gated by
+ `_COUNT_ADJACENT_SWAP`, so dropping that flag is the whole change.
+ """
+ if left == right:
+ return 0
+ n, m = len(left), len(right)
+ # `prev2` is the row two steps back, which is what an adjacent swap reads.
+ prev2: Optional[List[int]] = None
+ prev: List[int] = list(range(m + 1))
+ for i in range(1, n + 1):
+ cur = [i]
+ lc = left[i - 1]
+ for j in range(1, m + 1):
+ rc = right[j - 1]
+ cost = 0 if lc == rc else 1
+ best = min(cur[j - 1] + 1, prev[j] + 1, prev[j - 1] + cost)
+ if (_COUNT_ADJACENT_SWAP and prev2 is not None and j > 1
+ and lc == right[j - 2] and left[i - 2] == rc):
+ best = min(best, prev2[j - 2] + 1)
+ cur.append(best)
+ prev2 = prev
+ prev = cur
+ return prev[m]
+
+
+def _near_builtin(key: str) -> Optional[str]:
+ """Built-in name within one edit of `key`, or None.
+
+ Compared with the built-in names only, not their aliases. `en` and `ml` are
+ short enough that ordinary names sit one edit away from them.
+ """
+ for name in DEFAULT_MODELS:
+ if abs(len(key) - len(name)) > 1:
+ continue
+ if _edit_distance(key, name) == 1:
+ return name
+ return None
+
def canonical_name(name: Any) -> str:
"""Trim, lowercase and resolve an alias, without asking whether the result names a checkpoint.
@@ -753,6 +799,9 @@ class Router(HookRegistry):
`description` is free text about the checkpoint for whoever reads `registered`.
+ A name within one edit of a built-in is still registered, with a warning that names both
+ and leaves the built-in unchanged.
+
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.
@@ -844,6 +893,20 @@ class Router(HookRegistry):
"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
+ # After every check that can refuse the registration, and before the write. A filter
+ # that turns warnings into errors then raises with nothing stored, and `register`'s
+ # rollback still runs because the warning is inside its try. Built-in names and their
+ # aliases re-point that checkpoint, so they are not typos of themselves.
+ # 3, not 2: the frames from here are `_add` -> `register` / `Router.__init__` / `attach`
+ # -> the caller. 2 points inside this file, and the default once-per-location filter
+ # would then warn once for the process instead of once per call site.
+ if key not in DEFAULT_MODELS:
+ near = _near_builtin(key)
+ if near is not None:
+ warnings.warn(
+ "laya: checkpoint name %r is one edit from the built-in %r; it is registered "
+ "as a separate checkpoint and %r is unchanged." % (key, near, near),
+ RuntimeWarning, stacklevel=3)
self.models[key] = source
return key
diff --git a/tests/test_router.py b/tests/test_router.py
index acca020e..6e4efc84 100644
--- a/tests/test_router.py
+++ b/tests/test_router.py
@@ -1949,6 +1949,122 @@ _rr.register("fresh", "/z")
check("register/a new name unloads nothing", _log.evicts, ["papers"])
+# --------------------------------------------------------------------- near-typo names
+# A custom name one edit from a built-in is still registered. The call warns and names both,
+# so the typo is visible without taking the name away. An exact built-in, an alias, and a
+# clearly different name do not warn; neither does a registration refused for another reason.
+import inspect as _inspect
+import warnings as _warnings
+
+
+def _near_notes(caught):
+ return [w for w in caught if str(w.message).startswith("laya: checkpoint name")]
+
+
+def _near_text(name, built_in):
+ return ("laya: checkpoint name %r is one edit from the built-in %r; it is registered "
+ "as a separate checkpoint and %r is unchanged." % (name, built_in, built_in))
+
+
+def _warning_site(note):
+ """(basename, lineno) the warning was attributed to, without reading source."""
+ if note is None:
+ return None
+ return os.path.basename(note.filename), note.lineno
+
+
+with _warnings.catch_warnings(record=True) as _near_ctor_ws:
+ _warnings.simplefilter("always")
+ _near_ctor_line = _inspect.currentframe().f_lineno + 1 # the Router() call on the next line
+ _near_ctor = Router(models={"englsh": "/tmp/x"})
+_near_ctor_notes = _near_notes(_near_ctor_ws)
+_near_ctor_note = _near_ctor_notes[0] if _near_ctor_notes else None
+check("near-typo/constructor warns once", len(_near_ctor_notes), 1)
+check("near-typo/constructor names both",
+ None if _near_ctor_note is None else str(_near_ctor_note.message), _near_text("englsh", "english"))
+check("near-typo/constructor category",
+ None if _near_ctor_note is None else _near_ctor_note.category, RuntimeWarning)
+check("near-typo/constructor points at the caller", _warning_site(_near_ctor_note),
+ ("test_router.py", _near_ctor_line))
+check("near-typo/constructor still registers", _near_ctor.models.get("englsh"), "/tmp/x")
+check("near-typo/constructor leaves the built-in", _near_ctor.models["english"], DEFAULT_MODELS["english"])
+
+_near_reg_router = Router()
+with _warnings.catch_warnings(record=True) as _near_reg_ws:
+ _warnings.simplefilter("always")
+ _near_reg_line = _inspect.currentframe().f_lineno + 1 # the register() call on the next line
+ _near_reg = _near_reg_router.register("typed-decision", "/tmp/x")
+_near_reg_notes = _near_notes(_near_reg_ws)
+_near_reg_note = _near_reg_notes[0] if _near_reg_notes else None
+check("near-typo/register warns once", len(_near_reg_notes), 1)
+check("near-typo/register names both",
+ None if _near_reg_note is None else str(_near_reg_note.message),
+ _near_text("typed-decision", "typed-decisions"))
+check("near-typo/register points at the caller", _warning_site(_near_reg_note),
+ ("test_router.py", _near_reg_line))
+check("near-typo/register returns the name", _near_reg, "typed-decision")
+check("near-typo/register still registers", _near_reg_router.models.get("typed-decision"), "/tmp/x")
+check("near-typo/register leaves the built-in",
+ _near_reg_router.models["typed-decisions"], DEFAULT_MODELS["typed-decisions"])
+
+# An adjacent-letter swap is one edit (`enlgish`), not two substitutions.
+_near_swap_router = Router()
+with _warnings.catch_warnings(record=True) as _near_swap_ws:
+ _warnings.simplefilter("always")
+ _near_swap_router.register("enlgish", "/tmp/x")
+_near_swap_notes = _near_notes(_near_swap_ws)
+check("near-typo/adjacent swap warns once", len(_near_swap_notes), 1)
+check("near-typo/adjacent swap names both",
+ "" if not _near_swap_notes else str(_near_swap_notes[0].message), _near_text("enlgish", "english"))
+check("near-typo/adjacent swap still registers", _near_swap_router.models.get("enlgish"), "/tmp/x")
+
+with _warnings.catch_warnings(record=True) as _quiet_ws:
+ _warnings.simplefilter("always")
+ _quiet = Router(models={"papers": "/tmp/papers", "tone": "/tmp/tone", "english": "/tmp/my-english"})
+ _quiet.register("en", "/tmp/alias")
+ _quiet.register("ml", "/tmp/ml-alias")
+check("near-typo/distinct names and built-ins do not warn", _near_notes(_quiet_ws), [])
+check("near-typo/a built-in re-point still lands", _quiet.models["english"], "/tmp/alias")
+check("near-typo/an alias re-point still lands", _quiet.models["multilingual"], "/tmp/ml-alias")
+
+with _warnings.catch_warnings(record=True) as _bad_ws:
+ _warnings.simplefilter("always")
+ try:
+ Router().register("Bad/Name", "/tmp/x")
+ _bad_raised = None
+ except ValueError as _exc:
+ _bad_raised = _exc
+check("near-typo/invalid name raises", isinstance(_bad_raised, ValueError), True)
+check("near-typo/invalid name does not warn", _near_notes(_bad_ws), [])
+
+with _warnings.catch_warnings(record=True) as _src_ws:
+ _warnings.simplefilter("always")
+ try:
+ Router().register("englsh", 42)
+ _src_raised = None
+ except TypeError as _exc:
+ _src_raised = _exc
+check("near-typo/invalid source raises", isinstance(_src_raised, TypeError), True)
+check("near-typo/invalid source does not warn", _near_notes(_src_ws), [])
+
+# Promoting the warning to an error must not leave the name behind. The warning is raised
+# inside `register`'s try, so the existing rollback restores the router.
+_roll = Router(models={"papers": "/tmp/papers"})
+_roll_before = (dict(_roll.models), dict(_roll.descriptions), dict(_roll.sha256_digests))
+with _warnings.catch_warnings():
+ _warnings.simplefilter("error")
+ try:
+ _roll.register("englsh", "/tmp/x", description="typo")
+ _roll_raised = None
+ except RuntimeWarning as _exc:
+ _roll_raised = _exc
+check("near-typo/warnings-as-errors raises", isinstance(_roll_raised, RuntimeWarning), True)
+check("near-typo/warnings-as-errors names both",
+ _roll_raised is not None and "englsh" in str(_roll_raised) and "english" in str(_roll_raised), True)
+check("near-typo/warnings-as-errors leaves the router unchanged",
+ (dict(_roll.models), dict(_roll.descriptions), dict(_roll.sha256_digests)), _roll_before)
+
+
# --------------------------------------------------------------------- report
print("\n%d passed, %d failed" % (len(PASS), len(FAIL)))
for f in FAIL: