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(hooks): add OptionStabilityHook for metamorphic reliability signal (#635)
Swatantra Yadav6bfb1c3b3a74
diff --git a/docs/hooks/api.md b/docs/hooks/api.mdindex 0f49a913..3bf910d9 100644--- a/docs/hooks/api.md+++ b/docs/hooks/api.md@@ -4,12 +4,13 @@ Everything on this page is importable from `laya` (the common names) or `laya.howhole surface).```python-from laya import PredictContext, PredictHook, Hook+from laya import PredictContext, PredictHook, Hook, OptionStabilityHookfrom laya.hooks import HOOK_EVENTS, normalise_hooks, dispatch, aggregate_usage```- [PredictContext](#predictcontext)- [Hook protocol](#hook-protocol)+- [OptionStabilityHook](#optionstabilityhook)- [Convenience types](#convenience-types)- [Configuration surface](#configuration-surface)- [Event payloads](#event-payloads)@@ -143,6 +144,34 @@ class Audit(BaseHook):`Hook` is best when you want structural typing (any object with the right methods); `BaseHook` isbest when you want an explicit base to subclass and call `super()` on.+## OptionStabilityHook++`OptionStabilityHook` evaluates prediction reliability across meaning-preserving option permutations and letter renamings (addressing issue #635). It executes variants in the same single-forward-pass batch without multiple network calls or serial invocations.++Layout-aware (#635, #951): on checkpoints using parallel option layouts (`option_layout="parallel"`), options cannot attend to each other so reordering cannot move decisions by construction. The hook automatically detects layout from the agent config, executing rename-only probes on parallel checkpoints while running both rename and reorder probes on sequential checkpoints.++```python+from laya import OptionStabilityHook++# Required accept and escalate thresholds; pass None to disable categorical triage:+stability_hook = OptionStabilityHook(accept=0.85, escalate=0.60, variants="fast")+agent = laya.load("convaiinnovations/laya", hooks=[stability_hook])+```++Thresholds `accept` and `escalate` are required keyword arguments: categorical gating decisions (`ACCEPT`, `VERIFY`, `ESCALATE`) depend directly on application error tolerance, option count, and temperature calibration (Issue #1245). Pass `accept=None, escalate=None` to evaluate continuous stability signals without applying categorical gating.+++It attaches a `reliability` diagnostic block to each choice question's answer:+- `probes`: List of probe kinds that executed (e.g. `["rename"]`, `["reorder", "rename"]`, or `[]`).+- `option_layout`: Checkpoint layout (`"parallel"` or `"sequential"`).+- `soft_stability`: Mean probability assigned to the chosen option across all evaluated variants (`None` if unprobed).+- `stability`: Fraction of variants whose argmax choice agrees with the original decision (`None` if unprobed).+- `rename_stability`: Stability across rename variants (`None` if no rename probe ran).+- `reorder_stability`: Stability across reorder variants (`None` if no reorder probe ran).+- `decision`: Categorical classification (`ACCEPT`, `VERIFY`, or `ESCALATE`, or `None` if unprobed).+- `variant_choices`: Mapping of variant name to decoded choice.+- `variant_support`: Mapping of variant name to probability mass on the primary choice.+## Convenience types```pythondiff --git a/laya/__init__.py b/laya/__init__.pyindex e067f6cc..59372e8f 100644--- a/laya/__init__.py+++ b/laya/__init__.py@@ -22,7 +22,7 @@ import os as _os_os.environ.setdefault("USE_TF", "0")from .email import clean_email_body, email_state-from .hooks import AsyncHook, BaseHook, Hook, PredictContext, PredictHook+from .hooks import AsyncHook, BaseHook, Hook, OptionStabilityHook, PredictContext, PredictHookfrom .lang import analyse as detect_languagefrom .lang import detect_script, is_englishfrom .presets import (@@ -151,6 +151,7 @@ __all__ = ["Hook","BaseHook","AsyncHook",+ "OptionStabilityHook","decide","decide_batch","DecisionResult",diff --git a/laya/hooks.py b/laya/hooks.pyindex b680808c..a603b500 100644--- a/laya/hooks.py+++ b/laya/hooks.py@@ -12,13 +12,16 @@ import asyncioimport contextvarsimport inspectimport math+import random+import stringimport threadingimport timeimport uuidimport warnings+import zlibfrom contextlib import contextmanagerfrom dataclasses import dataclass, field-from typing import Any, Awaitable, Callable, Dict, List, Optional, Protocol, Sequence, Union+from typing import Any, Awaitable, Callable, Dict, List, Optional, Protocol, Sequence, Tuple, Union@dataclass(eq=False)@@ -545,3 +548,472 @@ def dispatch(RuntimeWarning,stacklevel=2,)+++_SEP = "::rel"++ALL_VARIANTS = (+ "reversed",+ "shuffle1",+ "shuffle2",+ "shuffle3",+ "letters",+ "letters_reversed",+ "letters_shuffle",+)++VARIANT_PRESETS = {+ "full": None,+ "fast": ("reversed", "letters_reversed"),+}+++def make_variants(+ labels: Sequence[str],+ seed_key: str,+ n_shuffles: int = 3,+ relabel: bool = True,+ include: Optional[Sequence[str]] = None,+ reorder: bool = True,+) -> List[Tuple[str, List[str], bool]]:+ """Meaning-preserving rewrites of choice option order and labels (#635).++ The first variant is always the original question. Shuffles are seeded using a+ zlib CRC32 hash of `seed_key` so variant selection is reproducible across identical+ inputs. Note: this provides reproducible variant generation, not a model-level+ determinism guarantee. Duplicates are dropped because evaluating an identical+ sequence twice would artificially inflate stability.+ """+ labels_list = list(labels)+ rng = random.Random(zlib.crc32(seed_key.encode("utf-8")))+ cands: List[Tuple[str, List[str], bool]] = [+ ("original", labels_list, False),+ ]+ if reorder:+ cands.append(("reversed", labels_list[::-1], False))+ for i in range(n_shuffles):+ order = labels_list[:]+ rng.shuffle(order)+ cands.append((f"shuffle{i + 1}", order, False))+ if relabel and len(labels_list) <= 26:+ cands.append(("letters", labels_list, True))+ cands.append(("letters_reversed", labels_list[::-1], True))+ order = labels_list[:]+ rng.shuffle(order)+ cands.append(("letters_shuffle", order, True))++ if include is not None:+ wanted = set(include)+ cands = [c for c in cands if c[0] == "original" or c[0] in wanted]++ seen = set()+ out = []+ for name, order, rel in cands:+ key = (tuple(order), rel)+ if key not in seen:+ seen.add(key)+ out.append((name, order, rel))+ return out+++def decide_reliability(+ soft_stability: float,+ accept: Optional[float],+ escalate: Optional[float] = None,+) -> Optional[str]:+ """Classify soft stability into 'ACCEPT', 'VERIFY', or 'ESCALATE'.++ If `accept` is None, returns None (fail-closed uncalibrated signal).+ """+ if accept is None:+ return None+ if soft_stability >= accept:+ return "ACCEPT"+ if escalate is not None and soft_stability < escalate:+ return "ESCALATE"+ return "VERIFY"+++def calibrate_reliability(+ soft_scores: Sequence[float],+ correct: Sequence[bool],+ target_accuracy: float = 0.90,+ max_escalate_accuracy: float = 1 / 3,+) -> Tuple[float, float]:+ """Pick (accept, escalate) thresholds from labelled evaluation examples (#635).++ accept = lowest cutoff where answers at or above it reach `target_accuracy`.+ escalate = highest cutoff below `accept` where answers below it are at most+ `max_escalate_accuracy` accurate.+ If no cutoff reaches `target_accuracy`, accept is returned as 1.01 (accept nothing).+ """+ pairs = sorted(zip(soft_scores, correct))+ if not pairs:+ raise ValueError("cannot calibrate reliability on empty scores/correct pairs")+ cuts = sorted({round(s, 4) for s, _ in pairs})++ accept = 1.01+ for t in cuts:+ kept = [c for s, c in pairs if s >= t]+ if kept and sum(kept) / len(kept) >= target_accuracy:+ accept = t+ break++ escalate = 0.0+ for t in cuts:+ if t >= accept:+ break+ below = [c for s, c in pairs if s < t]+ if below and sum(below) / len(below) <= max_escalate_accuracy:+ escalate = t+ return accept, escalate+++def _seed_of(state: Any) -> str:+ return state if isinstance(state, str) else repr(state)+++class OptionStabilityHook(BaseHook):+ """Opt-in reliability signal via metamorphic option reordering and renaming (#635).++ Generates variant permutations of choice options at `on_predict_start`, scores them+ in the same batch forward pass, and adds a `reliability` dict to each choice answer+ at `on_predict_end`.++ Thresholds `accept` and `escalate` are required keyword-only arguments. A defaulted+ threshold reads as an engine recommendation, but optimal cutoffs depend on domain+ error tolerance, option count, and calibration temperatures (Issue #1245). Pass+ `accept=None, escalate=None` to compute continuous stability metrics without categorical+ triage decisions.++ Layout-aware (#635, #951):+ On parallel option layouts (`option_layout="parallel"`), options cannot attend to each+ other so reordering yields 100% agreement by construction. The hook detects the+ checkpoint's layout from `ctx.agent.config` and runs rename-only probes on parallel+ checkpoints, while running both rename and reorder probes on sequential checkpoints.+ The returned `reliability["probes"]` explicitly names which probes actually ran,+ returning `None` for stability signals when no probe could run.+ """++ def __init__(+ self,+ *,+ accept: Optional[float],+ escalate: Optional[float],+ probes: Optional[Union[str, Sequence[str]]] = None,+ n_shuffles: int = 3,+ relabel: bool = True,+ rename_max_options: int = 20,+ variants: Union[str, Sequence[str], None] = "full",+ seed: Optional[str] = None,+ ):+ if probes is not None:+ if isinstance(probes, str):+ if probes == "auto":+ self.probes = None+ elif probes in ("reorder", "rename"):+ self.probes = (probes,)+ elif probes == "all":+ self.probes = ("reorder", "rename")+ else:+ raise ValueError("unknown probe type %r; choose from 'auto', 'reorder', 'rename', 'all'" % (probes,))+ elif isinstance(probes, (list, tuple, set)):+ probes_list = list(probes)+ if not probes_list:+ raise ValueError("probes list must not be empty; choose from 'reorder', 'rename'")+ bad = [p for p in probes_list if p not in ("reorder", "rename")]+ if bad:+ raise ValueError("unknown probe types %r; choose from 'reorder', 'rename'" % (bad,))+ self.probes = tuple(dict.fromkeys(probes_list))+ else:+ raise TypeError("probes must be a string or sequence of probe names, got %s" % type(probes).__name__)+ else:+ self.probes = None++ if isinstance(n_shuffles, bool) or not isinstance(n_shuffles, int) or n_shuffles < 0:+ raise ValueError("n_shuffles must be a non-negative integer, got %r" % (n_shuffles,))+ if not isinstance(relabel, bool):+ raise TypeError("relabel must be a bool, got %r" % (relabel,))+ if isinstance(rename_max_options, bool) or not isinstance(rename_max_options, int) or rename_max_options < 2:+ raise ValueError("rename_max_options must be an integer >= 2, got %r" % (rename_max_options,))++ self.n_shuffles = n_shuffles+ self.relabel = relabel+ self.rename_max_options = rename_max_options+ self.variants = variants+ self._include = self._resolve_variants(variants)++ if accept is not None:+ if (isinstance(accept, bool) or not isinstance(accept, (int, float))+ or not math.isfinite(accept) or not (0.0 <= accept <= 1.01)):+ raise ValueError("accept must be a float in [0.0, 1.01], got %r" % (accept,))+ self.accept = float(accept)+ else:+ self.accept = None++ if escalate is not None:+ if (isinstance(escalate, bool) or not isinstance(escalate, (int, float))+ or not math.isfinite(escalate) or not (0.0 <= escalate <= 1.0)):+ raise ValueError("escalate must be a float in [0.0, 1.0], got %r" % (escalate,))+ self.escalate = float(escalate)+ else:+ self.escalate = None++ if self.accept is not None and self.escalate is not None and self.escalate > self.accept:+ raise ValueError("escalate (%r) must not be greater than accept (%r)" % (escalate, accept))++ self.seed = str(seed) if seed is not None else None++ self._plans: Dict[str, Any] = {}+ self._lock = threading.Lock()++ @staticmethod+ def _resolve_variants(variants: Union[str, Sequence[str], None]) -> Optional[List[str]]:+ if variants is None:+ return None+ if isinstance(variants, str):+ if variants not in VARIANT_PRESETS:+ raise ValueError(+ "unknown variants preset %r; use one of %s or a sequence from %s"+ % (variants, sorted(VARIANT_PRESETS), list(ALL_VARIANTS))+ )+ preset = VARIANT_PRESETS[variants]+ return list(preset) if preset is not None else None+ if isinstance(variants, (list, tuple, set)):+ names = list(variants)+ bad = [n for n in names if n not in ALL_VARIANTS]+ if bad:+ raise ValueError("unknown variant names %r; choose from %s" % (bad, list(ALL_VARIANTS)))+ if not names:+ raise ValueError("variants list is empty: nothing to compare the original against")+ return names+ raise TypeError("variants must be a string preset or sequence of names, got %s" % type(variants).__name__)++ @staticmethod+ def _detect_layout(ctx: PredictContext) -> str:+ agent = getattr(ctx, "agent", None)+ if agent is not None:+ cfg = getattr(agent, "config", None)+ if isinstance(cfg, dict):+ raw = cfg.get("option_layout")+ if isinstance(raw, str):+ val = raw.strip().lower()+ if val in ("parallel", "sequential"):+ return val+ warnings.warn(+ "laya: unknown option_layout %r in agent config; defaulting to 'sequential'" % (raw,),+ RuntimeWarning,+ stacklevel=2,+ )+ return "sequential"++ @staticmethod+ def _variant_question(q: Dict[str, Any], order: List[str], relabel: bool) -> Tuple[Dict[str, Any], Dict[str, str]]:+ shown = list(string.ascii_uppercase[: len(order)]) if relabel else list(order)+ new_q = dict(q)+ crit = q.get("criteria")+ if isinstance(crit, dict):+ new_q["criteria"] = {s: crit[orig] for s, orig in zip(shown, order)}+ elif isinstance(crit, (list, tuple)):+ if relabel:+ new_q["criteria"] = {s: orig for s, orig in zip(shown, order)}+ else:+ new_q["criteria"] = list(order)+ return new_q, dict(zip(shown, order))++ def on_predict_start(self, ctx: PredictContext) -> None:+ if not ctx.questions:+ return++ for qid in ctx.questions:+ if _SEP in qid:+ raise ValueError("question id %r must not contain %r" % (qid, _SEP))++ layout = self._detect_layout(ctx)+ if self.probes is not None:+ configured_probes = set(self.probes)+ else:+ # Layout-aware probe selection (#635, #951):+ # Parallel layout makes reordering structurally invariant (100% agreement by construction).+ # Therefore reorder probes are pure cost and skipped; rename probes remain informative.+ if layout == "parallel":+ configured_probes = {"rename"} if self.relabel else set()+ else:+ configured_probes = {"reorder"}+ if self.relabel:+ configured_probes.add("rename")++ base_seed = self.seed if self.seed is not None else (+ _seed_of(ctx.states[0]) if (ctx.states and len(ctx.states) == 1) else "batch"+ )++ plan: Dict[str, Dict[str, Any]] = {}+ new_questions = dict(ctx.questions)++ for qid, q in ctx.questions.items():+ if not isinstance(q, dict) or q.get("type") != "choice":+ continue+ crit = q.get("criteria")+ if isinstance(crit, dict):+ labels = list(crit.keys())+ elif isinstance(crit, (list, tuple)):+ labels = list(crit)+ else:+ continue+ if len(labels) < 2:+ # Questions with < 2 options cannot be probed+ plan[qid] = {+ "layout": layout,+ "variants": [("original", qid, {k: k for k in labels}, False)],+ "probes_ran": [],+ }+ continue++ can_reorder = "reorder" in configured_probes+ can_rename = ("rename" in configured_probes) and (len(labels) <= self.rename_max_options)++ if not can_reorder and not can_rename:+ plan[qid] = {+ "layout": layout,+ "variants": [("original", qid, {k: k for k in labels}, False)],+ "probes_ran": [],+ }+ continue++ seed_key = f"{base_seed}|{qid}"+ variants = make_variants(+ labels,+ seed_key,+ self.n_shuffles,+ relabel=can_rename,+ include=self._include,+ reorder=can_reorder,+ )++ q_variants = [("original", qid, {k: k for k in labels}, False)]+ probes_ran = []+ if any(not rel and name != "original" for name, _, rel in variants[1:]):+ probes_ran.append("reorder")+ if any(rel for _, _, rel in variants[1:]):+ probes_ran.append("rename")++ for i, (name, order, rel) in enumerate(variants[1:], 1):+ vq, back = self._variant_question(q, order, rel)+ key = f"{qid}{_SEP}{i}"+ new_questions[key] = vq+ q_variants.append((name, key, back, rel))++ plan[qid] = {+ "layout": layout,+ "variants": q_variants,+ "probes_ran": probes_ran,+ }++ if plan:+ ctx.questions = new_questions+ with self._lock:+ self._plans[ctx.run_id] = plan++ def on_predict_end(self, ctx: PredictContext) -> None:+ with self._lock:+ plan = self._plans.pop(ctx.run_id, None)+ if not plan or not ctx.results:+ return++ for res in ctx.results:+ if not isinstance(res, dict):+ continue+ answers = res.get("answers")+ if not isinstance(answers, dict):+ continue++ all_variant_keys = set()+ for qid, q_plan in plan.items():+ variants = q_plan["variants"]+ layout = q_plan["layout"]+ probes_ran = q_plan["probes_ran"]++ for _, key, _, _ in variants[1:]:+ all_variant_keys.add(key)++ if qid not in answers:+ continue+ ans = answers[qid]+ if not isinstance(ans, dict) or ans.get("type") != "choice":+ continue++ choice = ans.get("choice")+ seen = []+ all_present = all(key in answers for _, key, _, _ in variants)+ if not all_present:+ continue++ for name, key, back, rel in variants:+ a = answers[key]+ raw_probs = a.get("probabilities") or {}+ probs = {back.get(k, k): v for k, v in raw_probs.items()}+ v_choice = a.get("choice")+ mapped_choice = back.get(v_choice, v_choice)+ seen.append((name, mapped_choice, probs, rel))++ others = seen[1:]+ if not others or not probes_ran:+ # No probes ran for this question: return None signals so caller+ # does not gate on an unprobed question (#635).+ ans["reliability"] = {+ "probes": [],+ "option_layout": layout,+ "decision": None,+ "soft_stability": None,+ "stability": None,+ "rename_stability": None,+ "reorder_stability": None,+ "n_variants": len(seen),+ "distinct_choices": sorted({c for _, c, _, _ in seen if c is not None}),+ "variant_choices": {name: c for name, c, _, _ in seen},+ "variant_support": {name: round(p.get(choice, 0.0), 4) for name, _, p, _ in seen},+ }+ continue++ reorder_items = [+ (name, c, p) for name, c, p, rel in others+ if not rel+ ]+ rename_items = [+ (name, c, p) for name, c, p, rel in others+ if rel+ ]++ stability = (sum(c == choice for _, c, _, _ in others) / len(others)) if others else None+ soft = (sum(p.get(choice, 0.0) for _, _, p, _ in seen) / len(seen)) if seen else None+ reorder_stab = (sum(c == choice for _, c, _ in reorder_items) / len(reorder_items)) if reorder_items else None+ rename_stab = (sum(c == choice for _, c, _ in rename_items) / len(rename_items)) if rename_items else None++ ans["reliability"] = {+ "probes": list(probes_ran),+ "option_layout": layout,+ "decision": decide_reliability(soft, self.accept, self.escalate) if soft is not None else None,+ "soft_stability": round(soft, 4) if soft is not None else None,+ "stability": round(stability, 4) if stability is not None else None,+ "rename_stability": round(rename_stab, 4) if rename_stab is not None else None,+ "reorder_stability": round(reorder_stab, 4) if reorder_stab is not None else None,+ "n_variants": len(seen),+ "distinct_choices": sorted({c for _, c, _, _ in seen if c is not None}),+ "variant_choices": {name: c for name, c, _, _ in seen},+ "variant_support": {name: round(p.get(choice, 0.0), 4) for name, _, p, _ in seen},+ }++ for key in all_variant_keys:+ answers.pop(key, None)++ usage = res.get("usage")+ if isinstance(usage, dict):+ if "truncated_questions" in usage and isinstance(usage["truncated_questions"], list):+ usage["truncated_questions"] = [q for q in usage["truncated_questions"] if _SEP not in q]+ if "options" in usage and isinstance(usage["options"], dict):+ usage["options"] = {k: v for k, v in usage["options"].items() if _SEP not in k}++ def on_error(self, ctx: PredictContext) -> None:+ with self._lock:+ self._plans.pop(ctx.run_id, None)+diff --git a/scripts/test_suites.py b/scripts/test_suites.pyindex 7687cce9..446e06e3 100644--- a/scripts/test_suites.py+++ b/scripts/test_suites.py@@ -41,6 +41,7 @@ SCRIPT_SUITES = ["tests/test_state_budget.py","tests/test_hooks.py","tests/test_hooks_api.py",+ "tests/test_option_stability.py","tests/test_structured.py","tests/test_structured_api.py","tests/test_structured_docs.py",diff --git a/tests/test_hooks.py b/tests/test_hooks.pyindex d04015db..be5e0ebf 100644--- a/tests/test_hooks.py+++ b/tests/test_hooks.py@@ -20,7 +20,7 @@ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))import laya.agent as _agent_mod # noqa: E402from laya.agent import Agent # noqa: E402-from laya.hooks import normalise_hooks # noqa: E402+from laya.hooks import OptionStabilityHook, normalise_hooks # noqa: E402from laya.router import RouteDecision, Router # noqa: E402PASS, FAIL = [], []@@ -1966,6 +1966,46 @@ check_raises("router_batch/route_batch rejects positional hooks", TypeError,check_raises("router_batch/predict_batch rejects positional hooks", TypeError,lambda: r_pos.predict_batch([req("pos2")], 8, 1.0, None, False, [PerCallTrace()]))+# --------------------------------------------------------------- OptionStabilityHook (issue #635)+check_raises("stability/missing accept and escalate", TypeError, lambda: OptionStabilityHook())+check_raises("stability/negative n_shuffles", ValueError, lambda: OptionStabilityHook(accept=0.8, escalate=0.6, n_shuffles=-1))+check_raises("stability/bool n_shuffles", ValueError, lambda: OptionStabilityHook(accept=0.8, escalate=0.6, n_shuffles=True))+check_raises("stability/unknown variants", ValueError, lambda: OptionStabilityHook(accept=0.8, escalate=0.6, variants="invalid"))+check_raises("stability/empty variants", ValueError, lambda: OptionStabilityHook(accept=0.8, escalate=0.6, variants=[]))+check_raises("stability/escalate > accept", ValueError, lambda: OptionStabilityHook(accept=0.5, escalate=0.8))++stab_hook = OptionStabilityHook(accept=0.77, escalate=0.61, seed="test-seed")+stab_q = {"choice_q": {"type": "choice", "instructions": "Pick?", "criteria": {"a": "opt 1", "b": "opt 2"}}}+stab_ctx = PredictContext(states=["state 1"], questions=dict(stab_q))+stab_hook.on_predict_start(stab_ctx)+check_true("stability/injects variant questions", any(k.startswith("choice_q::rel") for k in stab_ctx.questions))++sim_answers = {}+for k, q_def in stab_ctx.questions.items():+ crit = q_def["criteria"]+ target = [name for name, desc in crit.items() if desc == "opt 1"][0]+ sim_answers[k] = {+ "type": "choice",+ "choice": target,+ "probabilities": {name: (0.9 if name == target else 0.1) for name in crit},+ "answer_confidence": 0.9,+ }++stab_ctx.results = [{+ "model": "fake",+ "answers": sim_answers,+ "usage": {"truncated_questions": ["choice_q::rel1"]},+}]+stab_hook.on_predict_end(stab_ctx)+stab_ans = stab_ctx.results[0]["answers"]+check_true("stability/cleans variant keys", not any("::rel" in k for k in stab_ans))+check("stability/keeps choice", stab_ans["choice_q"]["choice"], "a")+check_true("stability/adds reliability", "reliability" in stab_ans["choice_q"])+check("stability/accept decision", stab_ans["choice_q"]["reliability"]["decision"], "ACCEPT")+check("stability/stability 1.0", stab_ans["choice_q"]["reliability"]["stability"], 1.0)+check("stability/probes list", stab_ans["choice_q"]["reliability"]["probes"], ["reorder", "rename"])+check("stability/cleans usage", stab_ctx.results[0]["usage"]["truncated_questions"], [])+# --------------------------------------------------------------- docs prose for plain callables# `docs/hooks/index.md` and the `laya/hooks.py` module docstring used to say a plain callablediff --git a/tests/test_hooks_api.py b/tests/test_hooks_api.pyindex bd72e347..96c97fef 100644--- a/tests/test_hooks_api.py+++ b/tests/test_hooks_api.py@@ -23,7 +23,7 @@ import syssys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))import laya # noqa: E402-from laya import Agent, BaseHook, PredictContext, PredictHook, Router, load # noqa: E402+from laya import Agent, AsyncHook, BaseHook, OptionStabilityHook, PredictContext, PredictHook, Router, load # noqa: E402from laya.hooks import HOOK_EVENTS, Hook # noqa: E402from laya.onnx_agent import ONNXAgent # noqa: E402from laya.router import _question_schema # noqa: E402@@ -82,6 +82,17 @@ for label, fn in (("Agent.__init__", Agent.__init__), ("load", load)):# Python and TypeScript share the 0.4.0 fallback for unidentified text.check_param("Router.__init__", Router.__init__, "default", "multilingual")++# OptionStabilityHook parameters (#635)+check_param("OptionStabilityHook.__init__", OptionStabilityHook.__init__, "accept", inspect.Parameter.empty, inspect.Parameter.KEYWORD_ONLY)+check_param("OptionStabilityHook.__init__", OptionStabilityHook.__init__, "escalate", inspect.Parameter.empty, inspect.Parameter.KEYWORD_ONLY)+check_param("OptionStabilityHook.__init__", OptionStabilityHook.__init__, "probes", None, inspect.Parameter.KEYWORD_ONLY)+check_param("OptionStabilityHook.__init__", OptionStabilityHook.__init__, "n_shuffles", 3, inspect.Parameter.KEYWORD_ONLY)+check_param("OptionStabilityHook.__init__", OptionStabilityHook.__init__, "relabel", True, inspect.Parameter.KEYWORD_ONLY)+check_param("OptionStabilityHook.__init__", OptionStabilityHook.__init__, "rename_max_options", 20, inspect.Parameter.KEYWORD_ONLY)+check_param("OptionStabilityHook.__init__", OptionStabilityHook.__init__, "variants", "full", inspect.Parameter.KEYWORD_ONLY)+check_param("OptionStabilityHook.__init__", OptionStabilityHook.__init__, "seed", None, inspect.Parameter.KEYWORD_ONLY)+# Router keeps lang_guess and explicit per-model revisions toocheck_param("Router.__init__", Router.__init__, "lang_guess", None)check_param("Router.__init__", Router.__init__, "revisions", None)@@ -152,6 +163,12 @@ check_true("Agent.backend_object is a property", isinstance(Agent.backend_object# ONNXAgent downloads the same Hub artifacts as Agent, so it authenticates the same waycheck_param("ONNXAgent.__init__", ONNXAgent.__init__, "token", None)+# AsyncHook wraps async hooks with an optional loop+check_param("AsyncHook.__init__", AsyncHook.__init__, "loop", None)++# OptionStabilityHook (issue #635)+check_true("OptionStabilityHook is a BaseHook", issubclass(OptionStabilityHook, BaseHook))+# --------------------------------------------------------------- predict surfacesfrom laya.mcp.remote import RemoteRouter # noqa: E402diff --git a/tests/test_option_stability.py b/tests/test_option_stability.pynew file mode 100644index 00000000..784a14a6--- /dev/null+++ b/tests/test_option_stability.py@@ -0,0 +1,384 @@+"""Tests for OptionStabilityHook and metamorphic reliability signal (#635).++Pure Python tests: runs offline without torch or checkpoint downloads.++Run: python tests/test_option_stability.py+"""+import os+import sys++sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))++from laya.hooks import ( # noqa: E402+ ALL_VARIANTS,+ OptionStabilityHook,+ PredictContext,+ VARIANT_PRESETS,+ calibrate_reliability,+ decide_reliability,+ make_variants,+)++PASS, FAIL = [], []+++def check(name, got, want):+ if got == want:+ PASS.append(name)+ else:+ FAIL.append("%s: got %r, want %r" % (name, got, want))+++def check_true(name, cond, detail=""):+ if cond:+ PASS.append(name)+ else:+ FAIL.append("%s%s" % (name, ": " + detail if detail else ""))+++def check_raises(name, exc, fn):+ try:+ fn()+ except exc:+ PASS.append(name)+ return+ except BaseException as other: # noqa: BLE001+ FAIL.append("%s: raised %r, want %r" % (name, other, exc))+ return+ FAIL.append("%s: did not raise %r" % (name, exc))+++# --------------------------------------------------------------- constants & presets+check("constants/ALL_VARIANTS count", len(ALL_VARIANTS), 7)+check("constants/VARIANT_PRESETS keys", sorted(VARIANT_PRESETS.keys()), ["fast", "full"])+++# --------------------------------------------------------------- make_variants+v1 = make_variants(["a", "b", "c"], "seed")+v2 = make_variants(["a", "b", "c"], "seed")+check("make_variants/deterministic", v1, v2)+check("make_variants/original is first", v1[0], ("original", ["a", "b", "c"], False))+check("make_variants/no duplicates", len({(tuple(o), r) for _, o, r in v1}), len(v1))++# 2 options: original + reversed + letters + letters_reversed = at most 4 variants+check_true("make_variants/two options capped at 4", len(make_variants(["x", "y"], "s", n_shuffles=10)) <= 4)++# Presets+fast = make_variants(["a", "b", "c"], "s", include=VARIANT_PRESETS["fast"])+check("make_variants/fast preset has 3 rows", [name for name, _, _ in fast], ["original", "reversed", "letters_reversed"])++# Relabel flag disabled+no_rel = make_variants(["a", "b", "c"], "s", relabel=False)+check_true("make_variants/no relabel has no letters variants", all(not r for _, _, r in no_rel))+++# --------------------------------------------------------------- validation+check_raises("validation/missing required accept and escalate", TypeError, lambda: OptionStabilityHook())+check_raises("validation/negative n_shuffles", ValueError, lambda: OptionStabilityHook(accept=0.8, escalate=0.6, n_shuffles=-1))+check_raises("validation/bool n_shuffles", ValueError, lambda: OptionStabilityHook(accept=0.8, escalate=0.6, n_shuffles=True))+check_raises("validation/bool relabel", TypeError, lambda: OptionStabilityHook(accept=0.8, escalate=0.6, relabel="yes"))+check_raises("validation/unknown preset", ValueError, lambda: OptionStabilityHook(accept=0.8, escalate=0.6, variants="invalid"))+check_raises("validation/empty variants list", ValueError, lambda: OptionStabilityHook(accept=0.8, escalate=0.6, variants=[]))+check_raises("validation/unknown variant name", ValueError, lambda: OptionStabilityHook(accept=0.8, escalate=0.6, variants=["reversed", "nope"]))+check_raises("validation/invalid accept float", ValueError, lambda: OptionStabilityHook(accept=1.5, escalate=0.5))+check_raises("validation/negative accept", ValueError, lambda: OptionStabilityHook(accept=-0.1, escalate=0.0))+check_raises("validation/invalid escalate float", ValueError, lambda: OptionStabilityHook(accept=0.9, escalate=1.1))+check_raises("validation/escalate greater than accept", ValueError, lambda: OptionStabilityHook(accept=0.5, escalate=0.8))+++# --------------------------------------------------------------- decide & calibrate+check("decide/accept", decide_reliability(0.95, accept=0.77, escalate=0.61), "ACCEPT")+check("decide/verify", decide_reliability(0.70, accept=0.77, escalate=0.61), "VERIFY")+check("decide/escalate", decide_reliability(0.30, accept=0.77, escalate=0.61), "ESCALATE")+check_raises("decide/missing accept", TypeError, lambda: decide_reliability(0.95))+check_raises("calibrate/empty pairs", ValueError, lambda: calibrate_reliability([], []))++scores = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.85, 0.9, 0.95, 0.99]+correct = [False, False, False, True, False, True, False, True, True, True, True, True]+acc, esc = calibrate_reliability(scores, correct, target_accuracy=0.90)+check_true("calibrate/escalate <= accept", esc <= acc)+kept = [c for s, c in zip(scores, correct) if s >= acc]+check_true("calibrate/target accuracy reached", sum(kept) / len(kept) >= 0.90)+++# --------------------------------------------------------------- hook lifecycle: single state+hook = OptionStabilityHook(accept=0.77, escalate=0.61, seed="fixed-seed")+q_choice = {+ "ask": {+ "type": "choice",+ "instructions": "Which team?",+ "criteria": {"refund": "money back", "tech": "bug fix", "sales": "pricing"},+ },+ "score_q": {"type": "score", "instructions": "Rate?", "criteria": ["low", "high"]},+ "noul_q": {"type": "noul", "instructions": "Yes or no?"},+}++ctx = PredictContext(states=["I want my money back."], questions=dict(q_choice))+hook.on_predict_start(ctx)++# Check variants added+check_true("start/original questions preserved", "ask" in ctx.questions)+check_true("start/non-choice unchanged", "score_q" in ctx.questions and "noul_q" in ctx.questions)+variant_keys = [k for k in ctx.questions if k.startswith("ask::rel")]+check_true("start/variants added for choice", len(variant_keys) >= 2)++# Check reserved separator rejected in caller question ids+bad_ctx = PredictContext(states=["test"], questions={"bad::rel1": q_choice["ask"]})+check_raises("start/rejects reserved separator", ValueError, lambda: hook.on_predict_start(bad_ctx))++# Simulate model execution where "refund" wins across all variants (stable agent)+simulated_answers = {}+for qk, qv in ctx.questions.items():+ if qk == "score_q":+ simulated_answers[qk] = {"type": "score", "score": 1.0, "confidence": 0.9, "answer_confidence": 0.9}+ elif qk == "noul_q":+ simulated_answers[qk] = {"type": "noul", "noul": 0.8, "confidence": 0.8, "answer_confidence": 0.8}+ else:+ # Choice question (original or variant)+ crit = qv["criteria"]+ # Find which key holds description "money back"+ target_key = [k for k, desc in crit.items() if desc == "money back"][0]+ other_keys = [k for k in crit if k != target_key]+ probs = {target_key: 0.85}+ for ok in other_keys:+ probs[ok] = round(0.15 / len(other_keys), 4)+ simulated_answers[qk] = {+ "type": "choice",+ "choice": target_key,+ "probabilities": probs,+ "confidence": 0.7,+ "answer_confidence": 0.85,+ }++ctx.results = [{+ "model": "fake",+ "answers": simulated_answers,+ "usage": {+ "input_tokens": 100,+ "output_tokens": 0,+ "truncated_questions": ["ask::rel1"],+ "options": {"ask": {"total": 3, "distinct": 3}, "ask::rel1": {"total": 3, "distinct": 3}},+ },+}]++hook.on_predict_end(ctx)++# Verify results after on_predict_end+res = ctx.results[0]+ans = res["answers"]+check_true("end/variant keys removed from answers", not any(k.startswith("ask::rel") for k in ans))+check("end/original choice question retained", ans["ask"]["choice"], "refund")+check_true("end/reliability added to choice", "reliability" in ans["ask"])+rel = ans["ask"]["reliability"]+check("end/stable answer accepted", rel["decision"], "ACCEPT")+check("end/stability is 1.0", rel["stability"], 1.0)+check_true("end/soft_stability is ~0.85", abs(rel["soft_stability"] - 0.85) < 1e-3)+check("end/distinct_choices is single refund", rel["distinct_choices"], ["refund"])+check_true("end/non-choice has no reliability", "reliability" not in ans["score_q"])+check_true("end/usage truncated_questions cleaned", "ask::rel1" not in res["usage"]["truncated_questions"])+check_true("end/usage options cleaned", "ask::rel1" not in res["usage"]["options"])+check_true("end/internal plan cleaned", ctx.run_id not in hook._plans)+++# --------------------------------------------------------------- fragile agent (picks first option)+ctx_fragile = PredictContext(states=["test"], questions={"ask": dict(q_choice["ask"])})+hook_fragile = OptionStabilityHook(accept=0.77, escalate=0.61, seed="fixed-seed")+hook_fragile.on_predict_start(ctx_fragile)++sim_fragile = {}+for qk, qv in ctx_fragile.questions.items():+ crit = qv["criteria"]+ keys = list(crit.keys())+ probs = {keys[0]: 0.9}+ for ok in keys[1:]:+ probs[ok] = round(0.1 / (len(keys) - 1), 4)+ sim_fragile[qk] = {+ "type": "choice",+ "choice": keys[0],+ "probabilities": probs,+ "confidence": 0.8,+ "answer_confidence": 0.9,+ }++ctx_fragile.results = [{"model": "fake", "answers": sim_fragile, "usage": {}}]+hook_fragile.on_predict_end(ctx_fragile)++rel_f = ctx_fragile.results[0]["answers"]["ask"]["reliability"]+check_true("fragile/stability is low", rel_f["stability"] < 0.5)+check_true("fragile/decision is not ACCEPT", rel_f["decision"] in ("VERIFY", "ESCALATE"))+check_true("fragile/multiple distinct choices", len(rel_f["distinct_choices"]) > 1)+++# --------------------------------------------------------------- batch execution+ctx_batch = PredictContext(states=["s1", "s2"], questions={"ask": dict(q_choice["ask"])})+hook_batch = OptionStabilityHook(accept=0.77, escalate=0.61, seed="batch-test")+hook_batch.on_predict_start(ctx_batch)++# Simulate 2 states in results+results_batch = []+for state in ("s1", "s2"):+ sim_b = {}+ for qk, qv in ctx_batch.questions.items():+ crit = qv["criteria"]+ target = [k for k, desc in crit.items() if desc == "money back"][0]+ probs = {k: (0.9 if k == target else 0.05) for k in crit}+ sim_b[qk] = {"type": "choice", "choice": target, "probabilities": probs, "answer_confidence": 0.9}+ results_batch.append({"model": "fake", "answers": sim_b, "usage": {}})++ctx_batch.results = results_batch+hook_batch.on_predict_end(ctx_batch)++check("batch/len results is 2", len(ctx_batch.results), 2)+for i, r in enumerate(ctx_batch.results):+ a = r["answers"]["ask"]+ check("batch/%d variant keys cleaned" % i, [k for k in r["answers"] if "::rel" in k], [])+ check("batch/%d decision" % i, a["reliability"]["decision"], "ACCEPT")+++# --------------------------------------------------------------- error handling cleanup+ctx_err = PredictContext(states=["err"], questions={"ask": dict(q_choice["ask"])})+hook_err = OptionStabilityHook(accept=0.77, escalate=0.61)+hook_err.on_predict_start(ctx_err)+check_true("error/plan exists before error", ctx_err.run_id in hook_err._plans)+hook_err.on_error(ctx_err)+check_true("error/plan cleared on error", ctx_err.run_id not in hook_err._plans)+++# --------------------------------------------------------------- uncalibrated / accept=None+check("decide/uncalibrated returns None", decide_reliability(0.99, accept=None), None)+hook_uncal = OptionStabilityHook(accept=None, escalate=None, seed="fixed-seed")+check("hook/uncalibrated accept is None", hook_uncal.accept, None)+check("hook/uncalibrated escalate is None", hook_uncal.escalate, None)+ctx_uncal = PredictContext(states=["I want my money back."], questions={"ask": dict(q_choice["ask"])})+hook_uncal.on_predict_start(ctx_uncal)+sim_uncal = {}+for qk, qv in ctx_uncal.questions.items():+ crit = qv["criteria"]+ target_key = [k for k, desc in crit.items() if desc == "money back"][0]+ sim_uncal[qk] = {+ "type": "choice",+ "choice": target_key,+ "probabilities": {target_key: 0.85},+ "confidence": 0.85,+ "answer_confidence": 0.85,+ }+ctx_uncal.results = [{"answers": sim_uncal, "usage": {}}]+hook_uncal.on_predict_end(ctx_uncal)+check("hook/uncalibrated decision is None", ctx_uncal.results[0]["answers"]["ask"]["reliability"]["decision"], None)+++# --------------------------------------------------------------- layout-aware probe selection (#635, #951)+class MockAgent:+ def __init__(self, option_layout="sequential"):+ self.config = {"option_layout": option_layout}++# 1. Parallel layout: auto-probes run rename-only+parallel_agent = MockAgent(option_layout="parallel")+ctx_par = PredictContext(states=["test parallel"], questions={"ask": dict(q_choice["ask"])}, agent=parallel_agent)+hook_par = OptionStabilityHook(accept=0.77, escalate=0.61, seed="fixed-seed")+hook_par.on_predict_start(ctx_par)++# Only rename variants should be injected (no reversed or shuffle)+par_variant_names = [k for k in ctx_par.questions.keys() if k != "ask"]+check_true("parallel/injects variants", len(par_variant_names) > 0)+check("parallel/plan probes_ran is rename only", hook_par._plans[ctx_par.run_id]["ask"]["probes_ran"], ["rename"])+check("parallel/plan layout is parallel", hook_par._plans[ctx_par.run_id]["ask"]["layout"], "parallel")++sim_par = {}+for qk, qv in ctx_par.questions.items():+ crit = qv["criteria"]+ target_key = [k for k, desc in crit.items() if desc == "money back"][0]+ sim_par[qk] = {+ "type": "choice",+ "choice": target_key,+ "probabilities": {target_key: 0.90},+ "confidence": 0.90,+ "answer_confidence": 0.90,+ }+ctx_par.results = [{"answers": sim_par, "usage": {}}]+hook_par.on_predict_end(ctx_par)++par_rel = ctx_par.results[0]["answers"]["ask"]["reliability"]+check("parallel/reliability probes is ['rename']", par_rel["probes"], ["rename"])+check("parallel/reliability layout is parallel", par_rel["option_layout"], "parallel")+check_true("parallel/rename_stability is not None", par_rel["rename_stability"] is not None)+check("parallel/reorder_stability is None", par_rel["reorder_stability"], None)++# 2. Sequential layout: auto-probes run both reorder and rename+seq_agent = MockAgent(option_layout="sequential")+ctx_seq = PredictContext(states=["test sequential"], questions={"ask": dict(q_choice["ask"])}, agent=seq_agent)+hook_seq = OptionStabilityHook(accept=0.77, escalate=0.61, seed="fixed-seed")+hook_seq.on_predict_start(ctx_seq)+check("sequential/plan probes_ran is ['reorder', 'rename']", hook_seq._plans[ctx_seq.run_id]["ask"]["probes_ran"], ["reorder", "rename"])++sim_seq = {}+for qk, qv in ctx_seq.questions.items():+ crit = qv["criteria"]+ target_key = [k for k, desc in crit.items() if desc == "money back"][0]+ sim_seq[qk] = {+ "type": "choice",+ "choice": target_key,+ "probabilities": {target_key: 0.90},+ "confidence": 0.90,+ "answer_confidence": 0.90,+ }+ctx_seq.results = [{"answers": sim_seq, "usage": {}}]+hook_seq.on_predict_end(ctx_seq)++seq_rel = ctx_seq.results[0]["answers"]["ask"]["reliability"]+check("sequential/reliability probes is ['reorder', 'rename']", seq_rel["probes"], ["reorder", "rename"])+check_true("sequential/rename_stability is not None", seq_rel["rename_stability"] is not None)+check_true("sequential/reorder_stability is not None", seq_rel["reorder_stability"] is not None)++# 3. Explicit probe override: probes="reorder" on parallel checkpoint overrides auto+ctx_forced = PredictContext(states=["test forced"], questions={"ask": dict(q_choice["ask"])}, agent=parallel_agent)+hook_forced = OptionStabilityHook(accept=0.77, escalate=0.61, probes="reorder", seed="fixed-seed")+hook_forced.on_predict_start(ctx_forced)+check("override/plan probes_ran is reorder", hook_forced._plans[ctx_forced.run_id]["ask"]["probes_ran"], ["reorder"])++# 4. Unprobed single-option question: returns None signals and probes=[]+single_q = {"single": {"type": "choice", "instructions": "only one", "criteria": {"a": "only"}}}+ctx_single = PredictContext(states=["test single"], questions=single_q, agent=seq_agent)+hook_single = OptionStabilityHook(accept=0.77, escalate=0.61)+hook_single.on_predict_start(ctx_single)+check("single_option/no variants injected", len(ctx_single.questions), 1)+ctx_single.results = [{"answers": {"single": {"type": "choice", "choice": "a", "probabilities": {"a": 1.0}}}, "usage": {}}]+hook_single.on_predict_end(ctx_single)+single_rel = ctx_single.results[0]["answers"]["single"]["reliability"]+check("single_option/probes is empty", single_rel["probes"], [])+check("single_option/stability is None", single_rel["stability"], None)+check("single_option/soft_stability is None", single_rel["soft_stability"], None)+check("single_option/decision is None", single_rel["decision"], None)++# 5. Validation of new parameters+check_raises("validation/invalid probe string", ValueError, lambda: OptionStabilityHook(accept=0.8, escalate=0.6, probes="nonsense"))+check_raises("validation/empty probe list", ValueError, lambda: OptionStabilityHook(accept=0.8, escalate=0.6, probes=[]))+check_raises("validation/invalid probe list item", ValueError, lambda: OptionStabilityHook(accept=0.8, escalate=0.6, probes=["reorder", "bad"]))+check_raises("validation/invalid rename_max_options", ValueError, lambda: OptionStabilityHook(accept=0.8, escalate=0.6, rename_max_options=1))+check_raises("validation/bool rename_max_options", ValueError, lambda: OptionStabilityHook(accept=0.8, escalate=0.6, rename_max_options=True))++# 6. Layout normalization and warning fallback+title_par_agent = MockAgent(option_layout=" Parallel ")+ctx_title_par = PredictContext(states=["test case normalization"], questions={"ask": dict(q_choice["ask"])}, agent=title_par_agent)+hook_norm = OptionStabilityHook(accept=0.77, escalate=0.61, seed="fixed-seed")+hook_norm.on_predict_start(ctx_title_par)+check("normalization/Parallel maps to parallel layout", hook_norm._plans[ctx_title_par.run_id]["ask"]["layout"], "parallel")++import warnings as _test_warnings+with _test_warnings.catch_warnings(record=True) as _warn_records:+ _test_warnings.simplefilter("always")+ bogus_agent = MockAgent(option_layout="unsupported_layout")+ ctx_bogus = PredictContext(states=["test bogus layout"], questions={"ask": dict(q_choice["ask"])}, agent=bogus_agent)+ hook_bogus = OptionStabilityHook(accept=0.77, escalate=0.61, seed="fixed-seed")+ hook_bogus.on_predict_start(ctx_bogus)+ check("normalization/bogus falls back to sequential", hook_bogus._plans[ctx_bogus.run_id]["ask"]["layout"], "sequential")+ check_true("normalization/bogus emits warning", any("unknown option_layout" in str(w.message) for w in _warn_records))+++# --------------------------------------------------------------- report+print("\n%d passed, %d failed" % (len(PASS), len(FAIL)))+for f in FAIL:+ print(" FAIL", f)+if not FAIL:+ print("all option stability tests passed")+sys.exit(1 if FAIL else 0)