Skip to content

feat(rpc): add submit-time named-predicate decision agent functions - #4323

Closed
gspencergoog wants to merge 14 commits into
feat/decision-binder-adkfrom
feat/decision-rpc-predicates
Closed

gspencergoog wants to merge 14 commits into
feat/decision-binder-adkfrom
feat/decision-rpc-predicates

Conversation

@gspencergoog

Copy link
Copy Markdown
Collaborator

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 via callAgentFunction with strict input schemas, per-session rate limiting, and error scrubbing.

Reviewer Focus

  • python/a2ui_agent/src/a2ui/rpc/experimental/decision/predicates.py: NamedPredicateSpec validation (rejecting generic judge/classify names), thread-safe SessionRateLimiter (clock read under lock), strict {value: str} schema with maxLength and additionalProperties: False, fixed server-owned prompts, and full exception scrubbing (including Python 3.10 asyncio.TimeoutError).
  • python/a2ui_agent/tests/rpc/test_decision_predicates.py: schema enforcement, rate limiting, timeout/exception scrubbing, and barrel isolation.

Changes

  • Added a2ui.rpc.experimental namespace and a2ui.rpc.experimental.decision facade exporting NamedPredicateSpec, SessionRateLimiter, and build_predicate_agent_functions.
  • Added unit tests in python/a2ui_agent/tests/rpc/test_decision_predicates.py and updated python/a2ui_agent/CHANGELOG.md.

Impact & Risks

  • Isolated under a2ui.rpc.experimental.decision and decorated with @experimental; importing a2ui.rpc or a2ui.rpc.experimental does not load a2ui.rpc.experimental.decision, a2ui.inference_formats.experimental, or httpx.
  • Rate limiting keys strictly on transport-verified session_id rather 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_agent
  • uv run mypy --follow-imports=silent python/a2ui_agent/src/a2ui/rpc/experimental/__init__.py python/a2ui_agent/src/a2ui/rpc/experimental/decision/*.py
  • A2UI_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

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@gspencergoog
gspencergoog force-pushed the feat/decision-rpc-predicates branch from 4dfd4b8 to 1ab25e6 Compare November 20, 2026 01:47
@gspencergoog
gspencergoog changed the base branch from feat/decision-kernel-standalone to feat/decision-binder-adk November 20, 2026 01:47
@gspencergoog
gspencergoog added this pull request to stack #4324 November 20, 2026 01:47
@gspencergoog
gspencergoog force-pushed the feat/decision-rpc-predicates branch from 1ab25e6 to e0b8699 Compare November 20, 2026 01:52
@gspencergoog
gspencergoog force-pushed the feat/decision-rpc-predicates branch 2 times, most recently from 04414ba to d14373e Compare November 20, 2026 22:49
@gspencergoog
gspencergoog removed this pull request from stack #4324 November 20, 2026 22:51
@gspencergoog
gspencergoog added this pull request to stack #4343 November 20, 2026 22:51
@gspencergoog
gspencergoog removed this pull request from stack #4343 November 20, 2026 23:53
@gspencergoog
gspencergoog added this pull request to stack #4345 November 20, 2026 23:53
@gspencergoog
gspencergoog force-pushed the feat/decision-rpc-predicates branch from d14373e to 5c4e5fa Compare November 24, 2026 01:36
@gspencergoog
gspencergoog marked this pull request as ready for review November 24, 2026 01:48
Signed-off-by: Greg Spencer <gspencer@google.com>
Signed-off-by: Greg Spencer <gspencer@google.com>
schema: dict[str, Any] = {
"type": "object",
"properties": {
"value": {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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):

  • JevHttpBackend converts an omitted native answer entry into {"yes": 0.0, "no": 0.0} (backends.py:1066-1101, 181-182).
  • DecisionAnswer.yes returns self.distribution.probabilities.get("yes", 0.0) (models.py:479-481), so mismatched keys like {"Yes": 0.99} or {"true": 1.0} become 0.0 (False).
  • DecisionDistribution.__post_init__ accepts float("nan") (models.py:373-377), and nan >= 0.5 evaluates to False.
  • Positional indexing answers[0] accepts multiple answers or an answer whose question_id != question.id (sibling decision_binder/binder.py:951-958 and decision_cascade/router.py:812 match by question_id and 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()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. Preferred: Make rate_limiter: SessionRateLimiter a required keyword-only argument so callers must explicitly own and share the limiter's lifetime across requests.
  2. Alternative: Fall back to a shared module-level default SessionRateLimiter instance 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:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 False

If 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)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 $O(N^2)$ lock-hold work during ramp-up. In addition, 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:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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
Suggested change
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(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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._experimental is a private module not exported in a2ui.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.
  • AgentFunctionResponseMessage is already re-exported from the a2ui.rpc facade (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.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 s1 again after inserting s2, insert s3, and verify s2 (not s1) was evicted.
  • If switching to fail-closed behavior at capacity (see the limiter eviction comment): assert s3 is rejected while s1 and s2 remain within the window, then advance now past window_seconds and verify expired buckets are swept so s3 succeeds.

🤖 Agent-generated

session_id="sess-err",
)
with pytest.raises(A2uiRpcError) as exc_info:
await fns[0].invoke({"value": "hello"}, None)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

Suggested change
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

@gspencergoog
gspencergoog force-pushed the feat/decision-rpc-predicates branch from 5c4e5fa to 4422c02 Compare November 30, 2026 16:58
@gspencergoog

Copy link
Copy Markdown
Collaborator Author

Closing this PR in favor of the modularized replacement stack.

@jacobsimionato: a2ui.experimental.decision.rpc (submit-time named-predicate agent functions and per-session rate limiting) has been moved into #4474, with previous review comments incorporated.

🤖 Agent-generated

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants