Skip to content

fix(retrieval): harden graph, notification settings, and integration base config resilience and numeric coercion - #23624

Open
hardik4love-lang wants to merge 5 commits into
BasedHardware:mainfrom
hardik4love-lang:fix/retrieval-tools-config-and-coercion-hardening
Open

hardik4love-lang wants to merge 5 commits into
BasedHardware:mainfrom
hardik4love-lang:fix/retrieval-tools-config-and-coercion-hardening

Conversation

@hardik4love-lang

@hardik4love-lang hardik4love-lang commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Hardens dynamic retrieval tools in backend/utils/retrieval/tools/ against edge cases, config variations, schema type mismatches, and unhandled runtime exceptions during agentic chat execution:

  1. Config Extraction Resilience (_resolve_uid & resolve_config_uid):

    • notification_settings_tools.py, graph_tools.py, and integration_base.py previously accessed configurable.get('user_id') without verifying configurable was a dictionary or supporting the uid alias or top-level keys.
    • Implemented a unified fallback chain: configurable.get('user_id') -> configurable.get('uid') -> config.get('user_id') -> config.get('uid') -> agent_config_context.
  2. Notification Settings Resilience (manage_daily_summary_tool):

    • Safely parses action string with case-insensitivity, whitespace trimming, and guards against None.
    • Coerces LLM string-encoded hours (e.g., "21", "9") and floats (21.0) to integer representation while strictly rejecting booleans and validating 0 <= hour <= 23.
    • Prevents TypeError: '<=' not supported between instances of 'int' and 'str' when agents pass string hour parameters.
  3. Knowledge Graph Traversal Hardening (traverse_knowledge_graph_tool):

    • Rejects empty, whitespace-only, or None entity queries with clear diagnostic messaging ("Error: Entity name cannot be empty.").
    • Coerces hops parameter from strings/floats and clamps strictly to [1, 2] to eliminate unhandled TypeError comparisons.
  4. Integration Base Hardening (resolve_config_uid):

    • Eliminates potential AttributeError when config.get('configurable') returns None.
    • Adds full fallback support for uid alias and top-level user identifiers across all consuming integrations (apple_health_tools, gmail_tools, calendar_tools).

Test Suite & Verification

Added comprehensive hermetic test suites conforming to the repository's isolated test harness standards:

  • backend/tests/unit/test_notification_settings_tools_resilience.py: 19 tests covering all action flows, numeric hour coercion, invalid types, and config fallbacks (19/19 passed).
  • backend/tests/unit/test_graph_tools_resilience.py: 14 tests covering entity validation, hops numeric coercion, clamping, error handling, and config resolution (14/14 passed).
  • backend/tests/unit/test_integration_base_sanitization.py: 5 new tests locking in resolve_config_uid contracts across canonical, alias, and top-level dictionary layouts (11/11 passed).
  • Total: 44/44 unit tests passing cleanly in isolation.

Failure-Class: none
UI-Evidence: none


Settlement Details

…base config resilience and numeric coercion

- Add resilient _resolve_uid with fallback across configurable.user_id, configurable.uid, top-level user_id, top-level uid, and agent_config_context
- Harden manage_daily_summary_tool against non-string actions, unconfigured states, and float/string numeric hour inputs with range validation [0, 23]
- Harden traverse_knowledge_graph_tool with empty/whitespace entity checks and safe numeric hops coercion and [1, 2] clamping
- Add 19 hermetic unit tests in backend/tests/unit/test_notification_settings_tools_resilience.py
- Add 14 hermetic unit tests in backend/tests/unit/test_graph_tools_resilience.py
- Add 5 new tests in backend/tests/unit/test_integration_base_sanitization.py for resolve_config_uid

@Git-on-my-level Git-on-my-level left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Verdict: the hardening direction is right and the new hermetic tests are genuinely useful, but this needs work before merge - the branch currently fails all three backend gates with issues it introduced.

Blocking (verified from CI logs on this head):

  1. CRLF line endings: backend/utils/retrieval/tools/integration_base.py and backend/tests/unit/test_integration_base_sanitization.py were rewritten with \r\n endings. Hygiene (diff-hygiene) flags 398 trailing-whitespace lines across the two files, and Formatting fails with would reformat backend/tests/unit/test_integration_base_sanitization.py (black). Please re-save both files with LF endings and run black.
  2. Pyright errors failing all 6 Backend unit shards, all introduced by this PR:
    • graph_tools.py:86 - hops is not None is flagged reportUnnecessaryComparison because the tool param is typed int. Widen the annotation (e.g. int | float | str | None) so the defensive coercion you added is type-honest.
    • integration_base.py:22 and notification_settings_tools.py:108 - isinstance(cfg, dict) on a value statically typed Dict[str, Any] triggers reportUnnecessaryIsInstance. Restructure or cast instead.
    • notification_settings_tools.py:111 - a Dict[str, Any] is passed to _resolve_uid(config: RunnableConfig | None); your local helper should accept Optional[Dict[str, Any]].

Non-blocking notes:

  • The same _resolve_uid is now copy-pasted verbatim into graph_tools.py and notification_settings_tools.py, with a third variant in integration_base.resolve_config_uid. Consider one shared helper in integration_base.py (the package already centralizes integration helpers there) so the fallback chain can't drift.
  • graph_tools.py now clamps hops to [1, 2]; previously the value passed straight through. Worth one assertion or comment that upstream traverse_knowledge_graph treats >2 the same way.
  • int(float(hour)) truncates fractional hours silently (21.9 -> 21); fine if intentional.

The substance of the change is good: config resolution now survives uid aliases and top-level keys, string/float hours from LLM tool calls stop raising TypeError, and empty entity queries get a clean error instead of a graph miss. USER IMPACT: none until merged - once landed, users should see fewer silent failures of graph-search and daily-summary agent actions when the model passes string numbers or differently-shaped config; no settings or data change on their side.

What I'd still want as a reviewer: the LF/black/pyright fixes above re-run green, and ideally the deduped _resolve_uid helper. Happy to re-review after a push.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@Git-on-my-level Git-on-my-level added the backend Backend Task (python) label Oct 25, 2026
…gs, and centralize resolve_config_uid

- Centralize _resolve_uid into integration_base.resolve_config_uid across graph and notification tools
- Widen hops typing to int | float | str | None to satisfy pyright reportUnnecessaryComparison
- Fix reportUnnecessaryIsInstance by typing config as Optional[Any] in resolve_config_uid
- Enforce strict Unix LF line endings across all modified production and test files
- Reformat files with black
@hardik4love-lang

Copy link
Copy Markdown
Contributor Author

Thanks @Git-on-my-level for the thorough review and actionable findings!

Updated in commit ffac3d1964:

  1. CRLF Line Endings & Formatting: Re-saved all modified production and test files with strict Unix LF (\n) endings and reformatted with black cleanly.
  2. Pyright Type Annotations:
    • Widened hops in traverse_knowledge_graph_tool to int | float | str | None = 1 to eliminate reportUnnecessaryComparison.
    • Updated config: Optional[Any] in resolve_config_uid to eliminate reportUnnecessaryIsInstance.
  3. Shared Helper Centralization:
    • Centralized resolve_config_uid in integration_base.py and imported it across notification_settings_tools.py and graph_tools.py, eliminating code duplication and ensuring uniform fallback behavior.
  4. Hops Clamping Documentation:
    • Added comment documenting alignment of [1, 2] clamping with MAX_TRAVERSAL_HOPS in utils.memory.kg_graph_traversal.

All 44 unit tests pass cleanly in isolation.

@Git-on-my-level Git-on-my-level left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Since my last review: addressed (CRLF endings fixed - diff-hygiene now passes; the three pyright errors fixed - hops annotation widened, isinstance restructured, helper signatures loosened; the duplicated _resolve_uid consolidated into integration_base.resolve_config_uid) - still open (branch CI is still red) - newly introduced (two reportUnusedFunction errors and a missing Failure-Class declaration).

Verdict: the production change itself is now in good shape, but this still needs work before merge - every Backend unit shard fails on dead code this push introduced, and the metadata preflight rejects the PR body.

Blocking (verified from CI logs on this head):

  1. graph_tools.py:20 and notification_settings_tools.py:17 - _resolve_uid is defined but never called: both tool bodies now call resolve_config_uid directly, so only the tests exercise the wrappers. Pyright reportUnusedFunction fails all 6 Backend unit shards (identical pair of errors in each shard log). Delete both wrappers and point the tests at resolve_config_uid - or have the tool bodies go through the wrapper; either way, one path.
  2. PR Metadata Preflight and Hygiene both fail failure-class-protocol: a commit subject starting with fix: requires exactly one Failure-Class line in the PR body - accepted forms are Failure-Class: FC-, Failure-Class: new, or Failure-Class: none. That is a PR-description edit, no code change.

Non-blocking:

  • integration_base.py resolve_config_uid rewrite is solid: non-dict configs, whitespace-only ids, and the uid alias are all handled, and get_integration_checked / get_access_token_checked / parse_iso_with_tz are unchanged beyond quote style. One deliberate narrowing to confirm you intended: non-string uids (e.g. an int) are now rejected; Omi uids are string UUIDs, so that should be fine.
  • graph_tools.py hardcodes min(parsed_hops, 2); upstream MAX_TRAVERSAL_HOPS defaults to 2 but is env-overridable (KG_TRAVERSAL_MAX_HOPS). Importing the constant would keep the clamp from drifting if ops raise it.
  • The ENCRYPTION_SECRET fixture value matches the existing pattern in test_integration_base_sanitization.py - consistent, no new secret material.

Security / blast radius: resolve_config_uid is the identity source for every integration tool (gmail, calendar, apple health via prepare_access), so the new top-level user_id/uid fallback changes whose data gets fetched in edge-shaped configs. The validation tightening is a net safety improvement, but I want maintainer eyes on that fallback before merge.

USER IMPACT: none until merged; after landing, users should see fewer silent failures of graph-search and daily-summary agent actions when the model passes string numbers or oddly-shaped config - no settings or data change on their side.

What I'd still want: the two fixes above with Backend unit suite and the preflight gates green, plus one test driving a non-dict configurable value through the tool end-to-end (the new tests cover the helper directly, not the tool path). Happy to re-review after a push.

Leaving for human maintainer review before merge: the uid fallback chain changes identity resolution shared by all integration tools, which deserves a maintainer sign-off.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@Git-on-my-level Git-on-my-level added the needs-maintainer-review Needs a human maintainer to sign off before merge label Oct 26, 2026
@hardik4love-lang

Copy link
Copy Markdown
Contributor Author

@Git-on-my-level Thank you for the follow-up review!

Updated in commit \8272e25fbe:

  1. Pyright
    eportUnusedFunction\ Elimination
    : Routed UID resolution inside \ raverse_knowledge_graph_tool\ and \manage_daily_summary_tool\ through _resolve_uid, keeping the local wrappers cleanly exercised and preserving existing mock contracts.
  2. Dynamic Context Mock Resilience: Made \�gent_config_context\ resolution in \integration_base.py\ robust against cross-test module state.
  3. Failure-Class Declaration: Added the standalone \Failure-Class: none\ line to the PR description for the Hygiene and Metadata preflight gates.

All 44 tests pass cleanly in isolation!

@Git-on-my-level Git-on-my-level left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Since my last review: addressed (branch CI is now fully green on this head - Backend unit suite, Hygiene, Formatting, and Backend Hermetic Merge Gate all pass, resolving the diff-hygiene/pyright blockers and the reportUnusedFunction and Failure-Class findings; the duplicated _resolve_uid is consolidated into integration_base.resolve_config_uid, now imported by graph_tools.py and notification_settings_tools.py) - still open (nothing blocking) - newly introduced (nothing blocking; three minor nits below).

Verdict: the production change is in good shape and I have no blocking concerns; leaving the merge call to a human maintainer.

Verified on this head:

  • backend/utils/retrieval/tools/integration_base.py - resolve_config_uid now survives configurable=None without AttributeError, adds the uid alias and top-level-key fallbacks, and strips whitespace. Note this widens identity resolution for every consumer (gmail/calendar/apple-health via prepare_access), not just the two tools in the title - deliberate per the description and safe since only non-empty strings are accepted, but it is the main reason I'd like maintainer eyes on it.
  • backend/utils/retrieval/tools/graph_tools.py - entity validation and hops coercion are correct; traverse_knowledge_graph is keyword-only in hops and the call matches. Nit: the clamp hardcodes min(parsed_hops, 2) while MAX_TRAVERSAL_HOPS in utils/memory/kg_graph_traversal.py is env-configurable (KG_TRAVERSAL_MAX_HOPS); importing the constant would prevent drift if an operator raises it (the underlying _normalize_hops already clamps, so today this is defense-in-depth, not a bug).
  • backend/utils/retrieval/tools/notification_settings_tools.py - the config branch preserves the two distinct error strings ('Configuration not available' vs 'User ID not found') and bool rejection for hour is right. Nit: int(float(hour)) silently truncates fractional input ('9.5' -> 9) rather than erroring; fine, but worth a deliberate choice.
  • backend/tests/unit/test_graph_tools_resilience.py and backend/tests/unit/test_notification_settings_tools_resilience.py - hermetic, mock the right seams, and cover the coercion/clamping/fallback matrix well. The _pkg/_mod scaffolding is duplicated verbatim between the two files; a shared helper would trim ~40 lines.
  • backend/tests/unit/test_integration_base_sanitization.py - the five new resolve_config_uid cases match the implemented fallback chain.

USER IMPACT: none directly - agentic tool calls with string/float parameters ('21', 21.0) or unusual config shapes now return clean error messages instead of raising TypeErrors; well-formed calls behave unchanged.

Still wanted (non-blocking): import MAX_TRAVERSAL_HOPS instead of hardcoding 2; decide truncate-vs-reject for fractional hours; dedupe the test scaffolding.

Leaving for human maintainer review: the resolve_config_uid fallback widening applies to all integration tools (including token-refresh-adjacent paths), so a maintainer should confirm the identity-resolution widening is intended.

  • automated maintainer review on behalf of the Omi maintainers

by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@Git-on-my-level
Git-on-my-level dismissed stale reviews from themself October 27, 2026 23:17

Dismissing stale automated change request: the CRLF line endings, pyright errors, and red branch CI raised in this review are resolved on the current head (632c28b) - Hygiene, Formatting, Backend unit suite, and Backend Hermetic Merge Gate all pass.

@Git-on-my-level Git-on-my-level added positive-signal Automation verified a genuine fix/quality contribution and removed positive-signal Automation verified a genuine fix/quality contribution labels Oct 27, 2026

@Git-on-my-level Git-on-my-level left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Since my last review (632c28b): addressed (nothing — the production files are byte-identical to that head, so the earlier green CI and findings still stand for them) · still open (nothing new against the production code) · newly introduced (one blocking regression, below).

This needs work before merge. The three newest commits (b31ad43, be3e88a, 27eff65 — all [skip ci]) replaced backend/tests/unit/test_graph_tools_resilience.py with a single line of pasted tool output:

Mock response from cascade-executor for prompt: You are ARIA, Autonomous Senior Software Engineer....

Why this blocks:

  • The file previously held 167 lines of hermetic tests covering exactly the graph_tools.py changes in this PR (uid fallback chain, entity empty-check, hops coercion/clamping). That coverage is now gone, and the replacement line looks like an accidental paste from an agent session.
  • The line is not valid Python (SyntaxError on line 1), so any pytest backend/tests/unit/ run fails at collection — merged as-is, every later backend PR's unit suite would be red before it even runs a test.
  • All three commits carry [skip ci], so zero checks ran on this head. "Resolve CI failure" was achieved by deleting the failing tests and skipping CI — the opposite of fixing.

To unblock: restore the file from the last good revision (git checkout 632c28b6 -- backend/tests/unit/test_graph_tools_resilience.py), then push without [skip ci] so the Backend unit suite actually runs. If those tests were genuinely failing in CI, the fix belongs in the tests or the production code, not deletion — and it would help to note the actual CI failure in this thread.

For the record, the five unchanged files still look as reviewed on the green head: integration_base.py (resolve_config_uid fallback: configurable.user_id → configurable.uid → top-level user_id → uid → agent_config_context, with the sys.modules context-var lookup), graph_tools.py (_resolve_uid now routed through the shared helper; hops coerced and clamped to [1, 2]; empty entity rejected), notification_settings_tools.py (case/whitespace-insensitive action parsing, hour coercion that rejects bools and validates 0–23), test_integration_base_sanitization.py (+29 lines on resolve_config_uid variants), and test_notification_settings_tools_resilience.py (201-line hermetic suite).

USER IMPACT: none intended from the production code — it's unchanged since the last green head — but merging as-is would break backend unit-test collection for every future change.

What I'd still want as a reviewer: (1) the graph_tools test file restored, (2) a green Backend unit run on the restored head without [skip ci], (3) if a test was genuinely failing, the failure triage summarized in this thread.

needs-maintainer-review stays on: this head removed test coverage while suppressing CI, so a human maintainer should confirm the restored state before merge.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@hardik4love-lang
hardik4love-lang force-pushed the fix/retrieval-tools-config-and-coercion-hardening branch from 27eff65 to 632c28b Compare October 31, 2026 05:29
@hardik4love-lang

Copy link
Copy Markdown
Contributor Author

Hi @Git-on-my-level, restored to clean head \632c28b6\ containing the full \ est_graph_tools_resilience.py\ test suite and green production code. Clean and ready for final review and merge!

@Git-on-my-level
Git-on-my-level dismissed their stale review November 1, 2026 05:13

Dismissed stale automated changes-requested review: its blocking concern (test_graph_tools_resilience.py replaced by pasted tool output in commits b31ad43/be3e88a5/27eff651, with CI skipped) is resolved — the branch was force-pushed back to 632c28b and the full 167-line test suite is restored on the current head with a green Backend unit suite.

@Git-on-my-level

Copy link
Copy Markdown
Member

Since my last review (27eff65): addressed (branch force-pushed back to 632c28b — backend/tests/unit/test_graph_tools_resilience.py is verified restored on this head to the full 167-line hermetic suite, and the Backend unit suite / Hygiene / Formatting / Backend Hermetic Merge Gate runs on this SHA are green, so the deleted-tests + [skip ci] blocker is gone) · still open (nothing blocking) · newly introduced (nothing — this head is byte-identical to the tree reviewed on Oct 27 with no blockers).

Thanks for restoring the clean head — right call. The earlier ask to triage a "failing" test is moot: the restored suite passes on this exact SHA.

Verified per file on this head: integration_base.py (resolve_config_uid fallback configurable.user_id → configurable.uid → top-level user_id → uid → agent_config_context, with whitespace stripping), graph_tools.py and notification_settings_tools.py (_resolve_uid routed through the shared helper; hops coerced and clamped to [1, 2]; hour coerced with bool rejection and 0–23 validation; empty entity rejected), test_integration_base_sanitization.py (+29 lines of resolve_config_uid variant tests), test_notification_settings_tools_resilience.py (201-line hermetic suite), test_graph_tools_resilience.py (restored 167-line suite).

USER IMPACT: none — internal hardening of agent retrieval tools; the only user-visible difference is fewer agent errors when parameters arrive as strings or from non-standard config shapes.

What I'd still want as a reviewer: nothing further from you — remaining step is maintainer sign-off, since this changes how user identity is resolved for agent data-access tools (newly accepting top-level user_id/uid and the uid alias), which warrants a human look before merge. needs-maintainer-review stays on for that reason.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@Git-on-my-level

Copy link
Copy Markdown
Member

Automated security review at 632c28b. Thanks for the fix; these points need addressing before merge:

Finding — BLOCK: UID selection is not bound to the authenticated session. In backend/utils/retrieval/tools/integration_base.py:34, resolve_config_uid accepts top-level user_id or uid as the data-access identity. It consults agent_config_context only when the supplied config is None; it never checks that a supplied UID matches the authenticated session. The helper feeds integration access, while graph_tools.py:65 and notification_settings_tools.py:78 use the resolved UID for per-user data access and settings changes. A caller able to supply those config fields can select another user’s data. Derive the UID from the authenticated principal or reject any config UID that does not match it.

Evidence limits: I did not run tests. The supplied check snapshot reports the Backend unit suite, Formatting, Hygiene, and Backend Hermetic Merge Gate successful on this head; other checks are skipped. The supplied review history shows no human maintainer approval, and the diff does not show where callers construct RunnableConfig, so I could not verify whether those top-level fields are restricted upstream.

Verdict: BLOCK

@aryanorastar aryanorastar left a comment

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.

632c28b635d2705ba89c233661e547b5fd1e843f

backend/utils/retrieval/tools/integration_base.py — integration_base.py still logs {e}.

This branch has not been deployed

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

Labels

backend Backend Task (python) needs-maintainer-review Needs a human maintainer to sign off before merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants