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(serve): refuse the batch diagnostics out-parameter instead of filling and dropping it

Nandakishor9f7a6a61a0f1
diff --git a/laya/serve.py b/laya/serve.py
index acc095c9..12968bc7 100644
--- a/laya/serve.py
+++ b/laya/serve.py
@@ -171,6 +171,14 @@ BODY_REFUSALS = ("hooks", "on_predict_start", "on_predict_end", "hooks_raise", "
BATCH_BODY_CALL_CONTROLS = ("batch_size", "min_confidence", "sort_by_length")
BATCH_BODY_ITEM_CONTROLS = ("max_len", "head_max_len", "task", "lang", "lang_guess")
+# ``diagnostics`` is neither: it is an out-parameter. ``Router.predict_batch`` fills a dict the
+# caller already owns (#1111, so a shell can say which checkpoint groups actually reordered), and a
+# JSON body cannot own one -- whatever a request sent would be filled in and then dropped when the
+# handler returned. So the batch path refuses it, for the reason the list above exists: a control
+# the endpoint cannot honour is told, not ignored. It is listed separately from ``BODY_REFUSALS``
+# because that tuple is pinned against ``Router.predict``, which has no ``diagnostics``.
+BATCH_BODY_OUT_PARAMETERS = ("diagnostics",)
+
def _env_bool(name: str, default: bool) -> bool:
v = os.environ.get(name)
@@ -489,6 +497,26 @@ def _refuse_body_refusals(body: Dict[str, Any]) -> None:
"install them where laya-serve runs, or drop them" % ", ".join(given))
+def _refuse_out_parameters(body: Dict[str, Any]) -> None:
+ """Reject a batch request that sends one of ``BATCH_BODY_OUT_PARAMETERS`` (422).
+
+ ``Router.predict_batch``'s ``diagnostics`` is a dict the caller keeps a reference to and reads
+ after the call. An HTTP caller keeps no reference, so a value sent here could only be written
+ and discarded. Refusing says so instead of answering 200 to a request for a report that is
+ never delivered.
+ """
+ from fastapi import HTTPException
+
+ given = sorted(key for key in BATCH_BODY_OUT_PARAMETERS
+ if key in body and body[key] is not None)
+ if given:
+ raise HTTPException(
+ status_code=422,
+ detail="%s is filled in place for an in-process caller and cannot be returned over "
+ "HTTP; read the per-group report from the CLI or a local Router"
+ % ", ".join(given))
+
+
def _validate_language_param(body: Dict[str, Any], key: str) -> Optional[str]:
"""Return a ``lang`` / ``lang_guess`` value, requiring the code-string form (422).
@@ -1337,6 +1365,7 @@ def create_app(router: Optional[Any] = None):
# so without this call a batch body would silently hand a caller a shorter deadline for
# the operator's own hooks.
_refuse_body_refusals(body)
+ _refuse_out_parameters(body)
# The same guard `/v1/systemone` runs, for the same reason, and it has to walk the whole
# body rather than one state because that is what the batch carries: `predict_batch`
# tokenizes every state and every question here, so a lone `\udXXX` escape in any of them
diff --git a/tests/test_serve.py b/tests/test_serve.py
index a0d95359..1d331330 100644
--- a/tests/test_serve.py
+++ b/tests/test_serve.py
@@ -23,6 +23,7 @@ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
from laya.serve import ( # noqa: E402
BATCH_BODY_CALL_CONTROLS,
+ BATCH_BODY_OUT_PARAMETERS,
BATCH_BODY_ITEM_CONTROLS,
BODY_CONTROLS,
BODY_REFUSALS,
@@ -2671,15 +2672,18 @@ def test_batch_call_controls_are_exactly_predict_batch_kwargs_or_refusal():
"""A control added to ``Router.predict_batch`` must be placed on one side of the line.
Either serve forwards it (``BATCH_BODY_CALL_CONTROLS``) or it refuses it (``hooks_timeout``,
- the one hook-execution arg that ``predict_batch`` takes). Silently ignoring a new kwarg is the
- failure mode this pin exists to catch: the same reasoning that made ``/v1/systemone`` refuse
- ``hooks_timeout`` in #724 applies to the batch path -- a caller cannot shorten the deadline
- on which the operator's own hooks execute.
+ the one hook-execution arg that ``predict_batch`` takes, and ``diagnostics``, the out-parameter
+ HTTP cannot hand back). Silently ignoring a new kwarg is the failure mode this pin exists to
+ catch: the same reasoning that made ``/v1/systemone`` refuse ``hooks_timeout`` in #724 applies
+ to the batch path -- a caller cannot shorten the deadline on which the operator's own hooks
+ execute.
"""
from laya.router import Router
taken = set(inspect.signature(Router.predict_batch).parameters) - {"self", "requests"}
- declared = set(BATCH_BODY_CALL_CONTROLS) | set(BODY_REFUSALS)
+ declared = (set(BATCH_BODY_CALL_CONTROLS) | set(BODY_REFUSALS)
+ | set(BATCH_BODY_OUT_PARAMETERS))
+ assert not (set(BATCH_BODY_CALL_CONTROLS) & set(BATCH_BODY_OUT_PARAMETERS))
assert taken == declared, "predict_batch() takes %s; serve declares %s" % (
sorted(taken), sorted(declared))
@@ -2844,6 +2848,29 @@ def test_batch_hook_control_is_refused_not_dropped(monkeypatch, key):
assert not fake.batch_calls, "the refusal must come before inference"
[email protected]("key", BATCH_BODY_OUT_PARAMETERS)
+def test_batch_out_parameter_is_refused_not_filled_and_dropped(monkeypatch, key):
+ """``diagnostics`` is written into the caller's own dict, which an HTTP caller does not have.
+
+ ``Router.predict_batch`` takes it so a local caller -- the CLI, for #1111 -- can read which
+ checkpoint groups actually reordered. Over HTTP there is nothing to read it back from, so a
+ body that sent it would be answered 200 while the report it asked for was discarded with the
+ request. Refused instead, for the reason ``BODY_REFUSALS`` is: an unhonourable control is
+ reported, never ignored.
+ """
+ client, fake = _batch_client(monkeypatch)
+ r = client.post("/v1/systemone/batch", json={**BATCH_REQ, key: {}})
+ assert r.status_code == 422, r.text
+ detail = r.json()["detail"]
+ assert key in detail
+ assert "cannot be returned over HTTP" in detail
+ assert not fake.batch_calls, "the refusal must come before inference"
+ # An explicit null is "not asked for", the way every other control reads it.
+ ok = client.post("/v1/systemone/batch", json={**BATCH_REQ, key: None})
+ assert ok.status_code == 200, ok.text
+ assert key not in fake.batch_calls[0][1]
+
+
def test_batch_predict_fallback_forwards_every_control(monkeypatch):
"""When the attached Router has no ``predict_batch``, every control must reach ``predict()``.