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.

fix(agent): comprehensive input validation for questions, instructions, and state

Swatantra Yadav211de25b8804
diff --git a/laya/agent.py b/laya/agent.py
index 5ca3861c..abfe092a 100644
--- a/laya/agent.py
+++ b/laya/agent.py
@@ -624,14 +624,28 @@ class Agent(HookRegistry):
'NoneType' object has no attribute 'items'`, `KeyError: 'bool'`, or a `selected index k out
of range` raised inside the model for a question that ended up with no options at all.
"""
+ if qid is None:
+ raise ValueError("question id must not be None")
+ if not isinstance(qid, (str, int)) or (isinstance(qid, str) and not qid.strip()):
+ raise ValueError("question id must be a non-empty string, got %r" % (qid,))
if not isinstance(qdef, dict):
raise ValueError("question %r: definition must be a dict, got %s"
% (qid, type(qdef).__name__))
t = qdef.get("type")
- if t not in QTYPES:
+ if not isinstance(t, str) or t not in QTYPES:
raise ValueError("question %r: unknown type %r; use one of %s" % (qid, t, sorted(QTYPES)))
if "instructions" not in qdef:
raise ValueError("question %r: no 'instructions'; add the text the model should answer" % (qid,))
+ ins = qdef["instructions"]
+ if ins is None:
+ raise ValueError("question %r: 'instructions' must not be None; add the text the model should answer" % (qid,))
+ if isinstance(ins, str) and not ins.strip():
+ raise ValueError("question %r: 'instructions' must not be empty; add the text the model should answer" % (qid,))
+ if isinstance(ins, (list, dict)) and not ins:
+ raise ValueError("question %r: 'instructions' must not be empty; add the text the model should answer" % (qid,))
+ if not isinstance(ins, (str, dict, list, int, float)):
+ raise ValueError("question %r: 'instructions' must be a string, dict, or list, got %s"
+ % (qid, type(ins).__name__))
crit = qdef.get("criteria")
if t == "choice":
if not isinstance(crit, (dict, list)):
@@ -1158,6 +1172,11 @@ class Agent(HookRegistry):
left no states to score, before any window was read -- on either path, so a cached answer
never reads as a window the model read.
"""
+ if state is None:
+ raise TypeError("state must not be None; pass a string, dict, or list")
+ if not isinstance(questions, dict):
+ raise TypeError("questions must be a dict of question id -> definition, got %s"
+ % type(questions).__name__)
if aggregate != "auto":
raise ValueError("predict_long: only aggregate='auto' is supported")
hook_kwargs = {"hooks": hooks, "on_predict_start": on_predict_start,
diff --git a/laya/onnx_agent.py b/laya/onnx_agent.py
index c31778a9..1b1e0b6d 100644
--- a/laya/onnx_agent.py
+++ b/laya/onnx_agent.py
@@ -333,7 +333,16 @@ class ONNXAgent(HookRegistry):
raise TypeError(
"predict_batch expects a list of states; pass a single state to predict()/system_one()."
)
+ if not isinstance(questions, dict):
+ raise TypeError(
+ "questions must be a dict of question id -> definition, got %s"
+ % type(questions).__name__
+ )
states = list(states)
+ if any(state is None for state in states):
+ raise TypeError(
+ "state must not be None; pass a string, dict, or list"
+ )
if not states:
ctx.results = []
else:
@@ -424,6 +433,11 @@ class ONNXAgent(HookRegistry):
hook_kwargs = {"hooks": hooks, "on_predict_start": on_predict_start,
"on_predict_end": on_predict_end, "hooks_raise": hooks_raise,
"hooks_timeout": hooks_timeout}
+ if state is None:
+ raise TypeError("state must not be None; pass a string, dict, or list")
+ if not isinstance(questions, dict):
+ raise TypeError("questions must be a dict of question id -> definition, got %s"
+ % type(questions).__name__)
if aggregate != "auto":
raise ValueError("predict_long: only aggregate='auto' is supported")
max_len = self.cfg.get("max_len", 512)
diff --git a/laya/router.py b/laya/router.py
index 9a2f3cc8..36a0ec6d 100644
--- a/laya/router.py
+++ b/laya/router.py
@@ -607,6 +607,8 @@ class Router(HookRegistry):
checkpoint) and the replacement is what gets returned and used. `hooks` are per-call
hooks, appended after any installed on the Router.
"""
+ if questions is not None and not isinstance(questions, dict):
+ raise TypeError("questions must be a dict of question id -> definition, got %s" % type(questions).__name__)
decision = self._route(state, questions, model=model, task=task, lang=lang, lang_guess=lang_guess)
raise_errors = self.hooks_raise if hooks_raise is None else bool(hooks_raise)
active = compose_hooks(self.hooks, hooks)
@@ -733,6 +735,10 @@ class Router(HookRegistry):
and see `ctx.decision`; see `laya.hooks`. `max_len` / `head_max_len` override the agent
token budget for this call (a start hook may set `ctx.max_len` / `ctx.head_max_len`).
"""
+ if state is None:
+ raise TypeError("state must not be None; pass a string, dict, or list")
+ if not isinstance(questions, dict):
+ raise TypeError("questions must be a dict of question id -> definition, got %s" % type(questions).__name__)
mc = check_min_confidence(min_confidence) if min_confidence is not None else None
active = compose_hooks(self.hooks, hooks, on_predict_start, on_predict_end)
raise_errors = self.hooks_raise if hooks_raise is None else bool(hooks_raise)
diff --git a/tests/test_criteria.py b/tests/test_criteria.py
index 445f51c2..20ddd1ab 100644
--- a/tests/test_criteria.py
+++ b/tests/test_criteria.py
@@ -331,7 +331,15 @@ for label, qdef in [
"criteria": {"true": "y", "false": "n", "maybe": "?"}}),
("unknown type", {"type": "bool", "instructions": "Is it spam?"}),
("missing type", {"instructions": "Is it spam?"}),
+ ("list type", {"type": [], "instructions": "Is it spam?"}),
+ ("dict type", {"type": {}, "instructions": "Is it spam?"}),
("no instructions", {"type": "noul"}),
+ ("instructions is None", {"type": "noul", "instructions": None}),
+ ("instructions is empty string", {"type": "noul", "instructions": ""}),
+ ("instructions is whitespace", {"type": "noul", "instructions": " "}),
+ ("instructions is empty list", {"type": "noul", "instructions": []}),
+ ("instructions is empty dict", {"type": "noul", "instructions": {}}),
+ ("instructions is non-container object", {"type": "noul", "instructions": set()}),
# A criteria list is normalised to `{label: None}`, so its labels are the answer keys. Two
# entries that land on one key scored fewer options than the caller wrote and returned fewer
# probabilities than their list, without a word. Python collapses keys that compare equal, so
@@ -407,7 +415,13 @@ if _empty_label is not None:
# the same questions through the public entry point, not only the method under it
router = Router()
router.attach("english", agent)
-for label, qdef in (("choice without criteria", {"type": "choice", "instructions": "x"}),):
+for label, qdef in (
+ ("choice without criteria", {"type": "choice", "instructions": "x"}),
+ ("list type", {"type": [], "instructions": "Is it spam?"}),
+ ("dict type", {"type": {}, "instructions": "Is it spam?"}),
+ ("instructions is None", {"type": "noul", "instructions": None}),
+ ("instructions is empty string", {"type": "noul", "instructions": ""}),
+):
try:
router.predict(STATE, {"q": qdef}, model="english")
FAIL.append("rejected/router %s: no error raised" % label)
@@ -426,6 +440,17 @@ except ValueError as e:
except Exception as e:
FAIL.append("rejected/second question: %s instead of ValueError: %s" % (type(e).__name__, e))
+# every question id is validated (must be non-empty string)
+for bad_qid in (None, "", " "):
+ name = "rejected/question id %r" % (bad_qid,)
+ try:
+ agent.system_one(STATE, {bad_qid: {"type": "noul", "instructions": "Is it urgent?"}})
+ FAIL.append("%s: no error raised" % name)
+ except ValueError as e:
+ check_true("%s names question id" % name, "question id" in str(e), str(e))
+ except Exception as e:
+ FAIL.append("%s: %s instead of ValueError: %s" % (name, type(e).__name__, e))
+
# ...and the shapes that are valid still answer, so this is not validation-only coverage
GOOD = {
"choice": {"type": "choice", "instructions": "Which team?",
diff --git a/tests/test_onnx_batch.py b/tests/test_onnx_batch.py
index 77686ec6..ef80e508 100644
--- a/tests/test_onnx_batch.py
+++ b/tests/test_onnx_batch.py
@@ -175,6 +175,16 @@ check_raises("empty/bare dict rejected", TypeError,
lambda: _bare_onnx().predict_batch({"body": "x"}, QUESTIONS))
check_raises("empty/invalid question rejected before any run", ValueError,
lambda: _bare_onnx().predict_batch(STATES, {"bad": {"type": "nope", "instructions": "?"}}))
+for bad_type in ([], {}):
+ check_raises("invalid/question type %r rejected" % (bad_type,), ValueError,
+ lambda bt=bad_type: _bare_onnx().predict_batch(STATES, {"q": {"type": bt, "instructions": "?"}}))
+for bad_ins in (None, "", " ", []):
+ check_raises("invalid/instructions %r rejected" % (bad_ins,), ValueError,
+ lambda bi=bad_ins: _bare_onnx().predict_batch(STATES, {"q": {"type": "noul", "instructions": bi}}))
+check_raises("invalid/questions not a dict", TypeError,
+ lambda: _bare_onnx().predict_batch(STATES, ["not", "a", "dict"]))
+check_raises("invalid/state is None in batch", TypeError,
+ lambda: _bare_onnx().predict_batch([None], QUESTIONS))
check("budget/max_len and head_max_len forward through the batch path",
_bare_onnx().predict_batch(STATES, QUESTIONS, max_len=32, head_max_len=16),
[_bare_onnx().system_one(s, QUESTIONS, max_len=32, head_max_len=16) for s in STATES])
diff --git a/tests/test_serve.py b/tests/test_serve.py
index dab066ab..67a4a19f 100644
--- a/tests/test_serve.py
+++ b/tests/test_serve.py
@@ -684,6 +684,39 @@ class ValidatingRouter:
raise AssertionError("validation should have rejected this before predict()")
[email protected]("bad_type", [[], {}, "bogus", 123])
+def test_malformed_question_type_is_a_named_422(monkeypatch, bad_type):
+ monkeypatch.delenv("LAYA_API_KEY", raising=False)
+ client = TestClient(create_app(router=ValidatingRouter()), raise_server_exceptions=False)
+ body = dict(REQ)
+ body["questions"] = {"refund": {"type": bad_type, "instructions": "Is a refund requested?"}}
+ response = client.post("/v1/systemone", json=body)
+ assert response.status_code == 422, response.text
+ assert "unknown type" in response.text, response.text
+
+
[email protected]("bad_ins", [None, "", " ", []])
+def test_malformed_instructions_is_a_named_422(monkeypatch, bad_ins):
+ monkeypatch.delenv("LAYA_API_KEY", raising=False)
+ client = TestClient(create_app(router=ValidatingRouter()), raise_server_exceptions=False)
+ body = dict(REQ)
+ body["questions"] = {"refund": {"type": "noul", "instructions": bad_ins}}
+ response = client.post("/v1/systemone", json=body)
+ assert response.status_code == 422, response.text
+ assert "instructions" in response.text, response.text
+
+
[email protected]("bad_qid", ["", " "])
+def test_malformed_question_id_is_a_named_422(monkeypatch, bad_qid):
+ monkeypatch.delenv("LAYA_API_KEY", raising=False)
+ client = TestClient(create_app(router=ValidatingRouter()), raise_server_exceptions=False)
+ body = dict(REQ)
+ body["questions"] = {bad_qid: {"type": "noul", "instructions": "Is it urgent?"}}
+ response = client.post("/v1/systemone", json=body)
+ assert response.status_code == 422, response.text
+ assert "question id" in response.text, response.text
+
+
def test_a_nested_choice_label_is_a_caller_error_not_a_server_fault(monkeypatch):
"""A `criteria` list containing a list/dict label is the caller's mistake, so it must be 422.