Repository navigation
feat(rpc): add submit-time named-predicate decision agent functions - #4323
gspencergoog wants to merge 14 commits into
Conversation
There was a problem hiding this comment.
Code Review
This pull request introduces experimental submit-time named-predicate decision agent functions, including NamedPredicateSpec, SessionRateLimiter, and build_predicate_agent_functions. These additions allow exposing server-owned boolean predicates as agent functions with built-in input validation, per-session sliding-window rate limiting, and backend error scrubbing. Comprehensive tests have also been added to verify these features. The review feedback suggests optimizing the argument validation in _extract_validated_value by replacing the strict key set comparison with a membership check, which avoids unnecessary set construction overhead and allows the schema validator to handle extra fields appropriately.
4dfd4b8 to
1ab25e6
Compare
1ab25e6 to
e0b8699
Compare
04414ba to
d14373e
Compare
d14373e to
5c4e5fa
Compare
Signed-off-by: Greg Spencer <gspencer@google.com>
Signed-off-by: Greg Spencer <gspencer@google.com>
| schema: dict[str, Any] = { | ||
| "type": "object", | ||
| "properties": { | ||
| "value": { |
There was a problem hiding this comment.
Defining value as a bare {"type": "string"} causes A2UI payload validation to reject every surface that passes user input via a data binding (such as {"@path": "/purpose"} or Express $purpose), because component validation checks function arguments before bindings resolve. Any real form trying to validate user-entered text with a named predicate fails immediately with A2uiValidationError.
Additional details
In A2UI v1.0, AgentFunction subclasses FunctionApi, whose schema describes function arguments as written in a component payload (before DataBinding or nested FunctionCall expressions resolve). PayloadValidator._validate_nested_call enforces this schema during component validation (validate_payload, RendererState.apply, A2uiRequestProcessor.parse_response, and strict MessageProcessor).
Empirically verified against BasicCatalog + validate_payload: a TextField with @checks calling {"@call": "check_purpose", "args": {"value": {"@path": "/purpose"}}} fails with:
A2uiValidationError: Validation failed for component 'TextField': components.root.@checks.0.condition.args.value: {'@path': '/purpose'} is not of type 'string'.
The existing round-trip test in test_decision_predicates.py missed this because it passed a hardcoded literal ("ada@acme.corp") and never validated the surface against agent_catalog.
Follow the constrained dynamic-string oneOf pattern used by openUrl in catalogs/basic/v1/catalog.json (lines 998–1009):
schema: dict[str, Any] = {
"type": "object",
"properties": {
"value": {
"oneOf": [
{
"type": "string",
"maxLength": spec.max_input_length,
},
{"$ref": "common_types.json#/$defs/DataBinding"},
{"$ref": "common_types.json#/$defs/FunctionCall"},
],
},
},
"required": ["value"],
"additionalProperties": False,
}Catalog.resolved_function_schema rewrites these $refs cleanly for both BasicCatalog and bare Catalog instances. Over callAgentFunction, PayloadValidator still rejects strings exceeding maxLength, non-strings, and extra properties, while _extract_validated_value rejects any unresolved {"@path": ...} or {"@call": ...} dict with INVALID_FUNCTION_CALL before acquiring rate-limit quota or calling the backend.
🤖 Agent-generated
| _GENERIC_PREDICATE_ERROR_MESSAGE, | ||
| code=RpcErrorCode.EXECUTION_ERROR, | ||
| ) | ||
| return bool(answers[0].yes >= _YES_PROBABILITY_THRESHOLD) |
There was a problem hiding this comment.
Reading answers[0].yes without verifying question_id, answer count, finiteness, or non-zero probability mass silently turns backend faults into a False decision instead of raising an EXECUTION_ERROR. Because JevHttpBackend maps omitted answer entries to {"yes": 0.0, "no": 0.0} and DecisionAnswer.yes defaults missing "yes" keys to 0.0, negatively phrased predicates (such as is_suspicious or is_policy_violation) silently fail open on backend glitches.
Additional details
Several malformed backend responses currently bypass error handling and evaluate cleanly as False (or an unrelated True):
JevHttpBackendconverts an omitted native answer entry into{"yes": 0.0, "no": 0.0}(backends.py:1066-1101,181-182).DecisionAnswer.yesreturnsself.distribution.probabilities.get("yes", 0.0)(models.py:479-481), so mismatched keys like{"Yes": 0.99}or{"true": 1.0}become0.0(False).DecisionDistribution.__post_init__acceptsfloat("nan")(models.py:373-377), andnan >= 0.5evaluates toFalse.- Positional indexing
answers[0]accepts multiple answers or an answer whosequestion_id != question.id(siblingdecision_binder/binder.py:951-958anddecision_cascade/router.py:812match byquestion_idand fail closed on omitted answers).
Validate the answer contract explicitly before thresholding:
answer = next(
(ans for ans in answers if ans.question_id == question.id), None
)
if len(answers) != 1 or answer is None:
logger.warning(
"Decision backend returned invalid answers for predicate '%s'.",
spec.name,
)
raise A2uiRpcError(
_GENERIC_PREDICATE_ERROR_MESSAGE,
code=RpcErrorCode.EXECUTION_ERROR,
)
probs = answer.distribution.probabilities
yes_prob = probs.get("yes")
total_mass = sum(p for p in probs.values() if math.isfinite(p) and p > 0.0)
if yes_prob is None or not math.isfinite(yes_prob) or total_mass <= 0.0:
logger.warning(
"Decision backend returned invalid boolean distribution for"
" predicate '%s'.",
spec.name,
)
raise A2uiRpcError(
_GENERIC_PREDICATE_ERROR_MESSAGE,
code=RpcErrorCode.EXECUTION_ERROR,
)
return yes_prob >= _YES_PROBABILITY_THRESHOLD🤖 Agent-generated
| """ | ||
| _validate_non_empty_str("session_id", session_id) | ||
| limiter: _SlidingWindowLimiter = ( | ||
| rate_limiter if rate_limiter is not None else _SlidingWindowLimiter() |
There was a problem hiding this comment.
Leaving rate_limiter unset creates a brand-new empty limiter on every build_predicate_agent_functions call, which silently turns off rate limiting whenever callers follow the normal per-request pattern (RendererToAgentMessageProcessor built per request with a verified session_id). A client can then invoke the decision backend indefinitely across requests without ever hitting the advertised per-session quota.
Additional details
Because session_id is a required argument on build_predicate_agent_functions and RendererToAgentMessageProcessor itself recommends building "one per request from the active catalogs" (python/a2ui_agent/src/a2ui/rpc/processor.py:126-127), callers naturally invoke build_predicate_agent_functions(backend, specs, session_id=sid) once per request. With rate_limiter: SessionRateLimiter | None = None defaulting to a throwaway _SlidingWindowLimiter(), every request resets the counter to zero—50 consecutive requests for the same session_id all succeed against the default max_calls=10.
Consider one of two safer designs:
- Preferred: Make
rate_limiter: SessionRateLimitera required keyword-only argument so callers must explicitly own and share the limiter's lifetime across requests. - Alternative: Fall back to a shared module-level default
SessionRateLimiterinstance across calls (and update the docstring accordingly) so the default configuration actually enforces per-session limits out of the box.
def build_predicate_agent_functions(
backend: DecisionBackend,
specs: Sequence[NamedPredicateSpec],
*,
session_id: str,
rate_limiter: SessionRateLimiter,
) -> list[AgentFunction]:🤖 Agent-generated
| ] | ||
| for sid in stale: | ||
| del self._buckets[sid] | ||
| while len(self._buckets) >= self._max_sessions: |
There was a problem hiding this comment.
When the limiter fills up with active sessions, evicting the least-recently-used entry discards that session's call history and resets its quota. Traffic cycling through more than max_sessions session IDs—or spikes from other active users—can reset active quotas and bypass per-session rate limiting.
Additional details
With max_calls=1 and max_sessions=2, cycling through sessions a, b, c lets 15/15 calls through inside the same window because each new session evicts an active bucket.
Once expired buckets have been swept, if len(self._buckets) >= self._max_sessions still holds, failing closed for new sessions (returning False / raising RATE_LIMITED) prevents quota-reset bypasses while still keeping memory bounded:
def _sweep_stale(self, cutoff: float) -> None:
stale = [
sid
for sid, bucket in self._buckets.items()
if not bucket or bucket[-1] <= cutoff
]
for sid in stale:
del self._buckets[sid]And in try_acquire when bucket is None:
if len(self._buckets) >= self._max_sessions:
self._sweep_stale(cutoff)
if len(self._buckets) >= self._max_sessions:
return FalseIf LRU eviction is intentionally preferred over failing closed under load, consider documenting that trade-off explicitly in SessionRateLimiter.
🤖 Agent-generated
| cutoff = now - self._window_seconds | ||
| bucket = self._buckets.get(session_id) | ||
| if bucket is None: | ||
| self._evict_stale_or_oldest(cutoff) |
There was a problem hiding this comment.
Calling _evict_stale_or_oldest(cutoff) unconditionally on every new session scans all tracked buckets while holding threading.Lock on the asyncio event loop thread, even when well below max_sessions, creating unnecessary now = float(self._clock()) is not checked for finiteness, so a NaN reading gets recorded in the bucket and never expires (NaN <= cutoff is always False), permanently locking out that session.
Additional details
Because _handle is async def, AgentFunctionRegistry._call_handler (python/a2ui_agent/src/a2ui/rpc/_agent_function_registry.py:263-264) runs limiter.acquire(session_id) directly on the event loop thread. Ramping up to max_sessions = 4_096 triggers a full dict scan on every new session (~8.4M iterations total) even though memory below max_sessions is already bounded by max_sessions * max_calls and existing sessions lazily prune expired timestamps on lines 191–192.
Guard the sweep behind if len(self._buckets) >= self._max_sessions: and reject non-finite clock readings:
now = float(self._clock())
if not math.isfinite(now):
raise ValueError(f"clock returned non-finite timestamp: {now!r}.")
cutoff = now - self._window_seconds
bucket = self._buckets.get(session_id)
if bucket is None:
if len(self._buckets) >= self._max_sessions:
self._evict_stale_or_oldest(cutoff)
bucket = deque()
self._buckets[session_id] = bucket🤖 Agent-generated
| f"NamedPredicateSpec.name {self.name!r} must be a valid" | ||
| " UAX #31 identifier." | ||
| ) | ||
| if self.name in _FORBIDDEN_GENERIC_NAMES: |
There was a problem hiding this comment.
Comparing self.name directly against _FORBIDDEN_GENERIC_NAMES only blocks exact lowercase ASCII names, so variants like "Judge", "JUDGE", or NFKC-equivalent Unicode identifiers such as fullwidth "judge" bypass the guard against registering generic prompt-proxy predicates.
Additional details
is_valid_uax31_identifier delegates to str.isidentifier() (python/a2ui_core/src/a2ui/core/common/uax31.py:29), which accepts uppercase and fullwidth Unicode letters ("judge".isidentifier() == True). Normalizing with NFKC and casefolding closes those variants:
import unicodedata| if self.name in _FORBIDDEN_GENERIC_NAMES: | |
| if unicodedata.normalize("NFKC", self.name).casefold() in _FORBIDDEN_GENERIC_NAMES: |
🤖 Agent-generated
| timeout=spec.timeout_seconds, | ||
| ) | ||
| except Exception as exc: | ||
| logger.warning( |
There was a problem hiding this comment.
Logging the raw session_id at WARNING level on every backend failure or timeout can leak sensitive session tokens or principal PII (such as user IDs or email addresses) into server logs.
Additional details
The docstring on line 330 describes session_id as a "session or principal identifier". In deployments where callers pass a session cookie/token or user email as session_id, emitting it verbatim in warning logs creates a log-injection / credential-leakage vector. Consider omitting session_id from the log message (as line 295 already does) or logging only a short non-reversible hash prefix.
🤖 Agent-generated
| SessionRateLimiter, | ||
| build_predicate_agent_functions, | ||
| ) | ||
| from a2ui.utils._experimental import SUPPRESS_ENV_VAR |
There was a problem hiding this comment.
This test imports the private module a2ui.utils._experimental (and also imports AgentFunctionResponseMessage from a2ui.core.schema.v1_0 on line 40 even though a2ui.rpc already re-exports it), which violates the repository's ban on deep/internal submodule imports in tests.
Additional details
AGENTS.md §8 and .agents/skills/coding-principles/subskills/python/coding-standards-and-verification.md prohibit deep internal submodule imports in tests as well as library code.
a2ui.utils._experimentalis a private module not exported ina2ui.utils.__all__; sibling tests (tests/decision/test_decision_kernel.py:233,tests/decision_binder/test_tool_pointer_binder.py:526) use the documented"A2UI_SUPPRESS_EXPERIMENTAL_FEATURE_WARNINGS"env var name directly.AgentFunctionResponseMessageis already re-exported from thea2ui.rpcfacade (python/a2ui_agent/src/a2ui/rpc/__init__.py:54), which is imported on line 49.
from a2ui.rpc import (
AgentFunctionResponseMessage,
RendererToAgentMessageProcessor,
)🤖 Agent-generated
| limiter.reset("s1") | ||
| assert limiter.try_acquire("s1") is True | ||
| assert limiter.try_acquire("s2") is True | ||
| # Adding s3 evicts LRU session s1 when max_sessions=2 is full. |
There was a problem hiding this comment.
This eviction test does not actually distinguish LRU from FIFO (since s1 is both the oldest inserted and the least recently used session) and never tests whether expired buckets are swept before eviction.
Additional details
To verify true eviction/expiry behavior:
- If keeping LRU eviction: touch
s1again after insertings2, inserts3, and verifys2(nots1) was evicted. - If switching to fail-closed behavior at capacity (see the limiter eviction comment): assert
s3is rejected whiles1ands2remain within the window, then advancenowpastwindow_secondsand verify expired buckets are swept sos3succeeds.
🤖 Agent-generated
| session_id="sess-err", | ||
| ) | ||
| with pytest.raises(A2uiRpcError) as exc_info: | ||
| await fns[0].invoke({"value": "hello"}, None) |
There was a problem hiding this comment.
Passing None as the second argument to fns[0].invoke(...) violates AgentFunction.invoke's non-optional AgentFunctionContext type signature and fails strict mypy checks when run directly on this test file.
Additional details
AgentFunction.invoke is typed as (self, args: dict[str, Any], context: AgentFunctionContext) -> Any (python/a2ui_core/src/a2ui/core/catalog/functions.py:334). Running uv run mypy python/a2ui_agent/tests/rpc/test_decision_predicates.py fails with:
error: Argument 2 to "invoke" of "AgentFunction" has incompatible type "None"; expected "AgentFunctionContext" [arg-type].
Pass an AgentFunctionContext as test_direct_invoke_enforces_argument_guards already does:
| await fns[0].invoke({"value": "hello"}, None) | |
| await fns[0].invoke({"value": "hello"}, AgentFunctionContext(catalog_id=CATALOG_ID, surface_id="s1", function_call_id="call-1")) |
🤖 Agent-generated
5c4e5fa to
4422c02
Compare
…ates # Conflicts: # python/a2ui_agent/CHANGELOG.md
Signed-off-by: Greg Spencer <gspencer@google.com>
|
Closing this PR in favor of the modularized replacement stack. @jacobsimionato: 🤖 Agent-generated |
Summary
Adds submit-time named-predicate agent functions (
a2ui.rpc.experimental.decision) on top of the shared decision kernel, allowing A2UI v1.0 clients to invoke server-defined boolean decision predicates viacallAgentFunctionwith strict input schemas, per-session rate limiting, and error scrubbing.Reviewer Focus
python/a2ui_agent/src/a2ui/rpc/experimental/decision/predicates.py:NamedPredicateSpecvalidation (rejecting genericjudge/classifynames), thread-safeSessionRateLimiter(clock read under lock), strict{value: str}schema withmaxLengthandadditionalProperties: False, fixed server-owned prompts, and full exception scrubbing (including Python 3.10asyncio.TimeoutError).python/a2ui_agent/tests/rpc/test_decision_predicates.py: schema enforcement, rate limiting, timeout/exception scrubbing, and barrel isolation.Changes
a2ui.rpc.experimentalnamespace anda2ui.rpc.experimental.decisionfacade exportingNamedPredicateSpec,SessionRateLimiter, andbuild_predicate_agent_functions.python/a2ui_agent/tests/rpc/test_decision_predicates.pyand updatedpython/a2ui_agent/CHANGELOG.md.Impact & Risks
a2ui.rpc.experimental.decisionand decorated with@experimental; importinga2ui.rpcora2ui.rpc.experimentaldoes not loada2ui.rpc.experimental.decision,a2ui.inference_formats.experimental, orhttpx.session_idrather than client-supplied context, and backend errors are logged server-side while returning a generic RPC error message to clients.Testing
uv run pyink --check python/a2ui_agentuv run mypy --follow-imports=silent python/a2ui_agent/src/a2ui/rpc/experimental/__init__.py python/a2ui_agent/src/a2ui/rpc/experimental/decision/*.pyA2UI_SUPPRESS_EXPERIMENTAL_FEATURE_WARNINGS=1 uv run pytest python/a2ui_agent/tests/rpc/test_decision_predicates.py python/a2ui_agent/tests/test_experimental_import_isolation.py -q