Skip to content

fix(goals): guard qualitative goals against NoneType compare crashes and coerce suggestion floats - #22220

Merged
kodjima33 merged 6 commits into
BasedHardware:mainfrom
Speedyzyzz:fix/goals-null-metric-advice-and-suggestions
Oct 25, 2026
Merged

kodjima33 merged 6 commits into
BasedHardware:mainfrom
Speedyzyzz:fix/goals-null-metric-advice-and-suggestions

Conversation

@Speedyzyzz

@Speedyzyzz Speedyzyzz commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Hardens the goal tracking AI advice, suggestion, and extraction pipeline against runtime crashes (TypeError, ZeroDivisionError, and FastAPI ResponseValidationError HTTP 500s) when handling qualitative goals, cleared metrics, or partial LLM suggestions.

Blast Radius & Production Impact: PATCH /v1/goals/{goal_id} with {"clear_metric": true} is a documented first-class API feature. Prior to this fix, 100% of users who cleared a metric or tracked a qualitative goal experienced runtime TypeError crashes and error log tracebacks whenever fetching AI advice. This PR restores genuine AI advice for qualitative goals, prevents token drain on conversational progress extraction, and eliminates HTTP 500s on AI suggestions.

Key Changes

  1. Goal Advice Null-Safety & Qualitative Support (utils/llm/goals.py & routers/goals.py):

    • In get_goal_advice: When target_value or current_value is None (qualitative goals or cleared metrics), the previous code evaluated if target_value > 0: and formatted {current_value:,.0f} / {target_value:,.0f}, raising TypeError: '>' not supported between instances of 'NoneType' and 'int' and format string TypeError.
    • Uses _safe_optional_float to safely parse metrics, guarding against the Python bool-is-int trap (isinstance(True, int) == True).
    • Cleanly formats PROGRESS: Qualitative goal (no numeric metric set) or numeric progress in the prompt, enabling users with qualitative goals to receive genuine AI advice instead of falling back on error.
    • Guards against ZeroDivisionError when target_value == 0.
    • In routers/goals.py: In get_current_goal_advice, guards against goal documents lacking an 'id' field.
  2. Self-Healing Goal Suggestions & Float Coercion (models/goal.py & utils/llm/goals.py):

    • Added a @model_validator(mode="before") on GoalSuggestionResponse in models/goal.py to make the Pydantic schema intrinsically self-healing against null, booleans, string NaN/Infinity, and inverted min > max bounds across any caller.
    • In suggest_goal: Coerces suggested_target, suggested_min, and suggested_max to valid finite float values (suggested_min <= suggested_max) and normalizes suggested_type to valid enum strings (scale, numeric, boolean), completely eliminating FastAPI ResponseValidationError (HTTP 500) failures.
  3. Token Drain & Metric Corruption Prevention (utils/llm/goals.py):

    • In extract_and_update_goal_progress: Purely qualitative goals (target_value is None, metric is None, current_value is None) are filtered out of prompt construction. If a user only has qualitative goals, extraction returns immediately, saving LLM tokens on every conversation.
    • Double-guards in the results loop to prevent hallucinated numeric extractions from resurrecting a half-numeric metric on cleared qualitative goals.

Invariant Conformance

  • INV-GOAL-1: Qualitative goals remain qualitative without forcing artificial numeric metrics.
  • INV-GOAL-2: Inactive, achieved, or missing goals continue to return safe fallback advice.
  • INV-GOAL-3: All endpoint payloads strictly satisfy Pydantic response models (GoalSuggestionResponse, AdviceResponse).

Verification

  • Added comprehensive hermetic unit test suite: backend/tests/unit/test_goals_defensive.py (18/18 passing in 1.13s).
    • Verifies qualitative advice, zero targets, non-finite values, and inactive goal fallbacks.
    • Verifies float parsing and the Python bool-is-int trap (_safe_float(True, 10.0) == 10.0).
    • Verifies GoalSuggestionResponse self-healing model validator.
    • Verifies qualitative goals bypass LLM extraction with 0 tokens burned.
  • Ran all combined goal regression suites: 147 passed, 0 failures.
  • Pyright type checker: 0 errors across all modified modules.

UI Evidence

UI-Evidence: none (backend Python logic and hermetic test suite only)

Failure Class

Failure-Class: none

Bounty Payout Details

Copilot AI balanced review requested due to automatic review settings October 18, 2026 19:41

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@Git-on-my-level

Copy link
Copy Markdown
Member

The production change here is correct and nicely scoped — this fixes real crashes in the goals AI pipeline (verified against the diff on 3296a7f); nits below are non-blocking.

Findings by file:

  • backend/utils/llm/goals.py: get_goal_advice previously crashed on qualitative/cleared-metric goals (target_value > 0 with None, and None format specs). The new _safe_optional_float parsing + progress_line branch ladder handles every None/zero/non-finite combination correctly, including the bool-is-int trap. suggest_goal now sanitizes LLM JSON through _sanitize_goal_suggestion, and extract_and_update_goal_progress skips purely qualitative goals (saves an LLM call's worth of tokens and prevents hallucinated numeric writes) and validates returned values through _safe_optional_float instead of raw float(). All good.
  • backend/models/goal.py: the model_validator(mode='before') on GoalSuggestionResponse makes the response schema self-healing, matching the manual sanitize in utils/llm/goals.py. Since /v1/goals/suggest declares response_model=GoalSuggestionResponse, null/boolean numerics from the LLM previously surfaced as ResponseValidationError 500s — this closes that at the schema layer too.
  • backend/routers/goals.py: not goal.get('id') guard in get_current_goal_advice prevents a KeyError on corrupt goal dicts. Minimal and correct.
  • backend/tests/unit/test_goals_defensive.py: 429 lines of well-structured defensive tests with stubbed Firestore/LLM — no network or real credentials (the env values at the top are the repo's established test fixtures). Good coverage of null, NaN/Inf, boolean, reversed-bounds, and malformed-JSON paths.

Material dimensions:

  • UX: users with qualitative goals or cleared metrics get real AI advice again instead of errors; suggestion endpoint stops returning 500s on partial LLM output.
  • Cost: skipping purely qualitative goals in progress extraction removes wasted LLM token spend per extraction call.
  • Security: no concerns — no secrets, no new dependencies, no auth-surface changes.
  • Blast radius: confined to the goals advice/suggestion/progress pipeline; worst-case regression is a canned fallback string, which is the pre-existing behavior.

Non-blocking nits: the new except ValueError in get_goal_advice returns the same string as the existing generic except Exception handler, so it's redundant; and the sanitize logic now lives in two places (model validator + _sanitize_goal_suggestion) — fine for now, but keep them in sync if the rules evolve. The safe_float = _safe_float module aliases exist only for test imports; an underscore import would be fine too.

USER IMPACT: Users with qualitative goals or cleared metrics will get working AI goal advice again, and goal suggestions will stop failing with errors when the AI returns incomplete numbers.

Remaining wants: no CI check runs have reported on this head yet — merge should wait for a green backend suite run. Leaving for human maintainer review of the 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.

@Git-on-my-level Git-on-my-level added positive-signal Automation verified a genuine fix/quality contribution backend Backend Task (python) labels Oct 19, 2026
@Speedyzyzz

Copy link
Copy Markdown
Contributor Author

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

All 18 unit tests in test_goals_defensive.py and the surrounding 147 goal regression tests pass completely clean locally with zero network dependencies. Ready for human maintainer review and workflow trigger whenever convenient!

@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: Strong defensive fix and excellent test coverage — one blocking API-contract issue to resolve before merge.

Blocking:

  • backend/utils/llm/goals.py get_goal_advice: the new except ValueError: return 'Focus on the next small step toward your goal.' sits in the same function that still does raise ValueError("Goal not found") for missing/inactive goals. The router for GET /v1/goals/{goal_id}/advice relies on that exception: except ValueError: raise HTTPException(404, 'Goal not found') (backend/routers/goals.py). Your handler makes the 404 unreachable — clients requesting advice for a nonexistent or inactive goal_id now get 200 with canned advice instead of 404, and they can no longer distinguish a bad ID from real advice. test_get_goal_advice_missing_or_inactive_goal encodes the new behavior, so it looks intentional — please either (a) drop the except-ValueError branch and let the 404 keep working, or (b) keep the 200-with-advice UX and remove the now-dead router 404 branch, whichever matches the intended client contract.

Non-blocking nit: the sanitization logic now exists twice — _sanitize_goal_suggestion in backend/utils/llm/goals.py and sanitize_suggestion in backend/models/goal.py — nearly line-for-line but with different default reasoning strings ('Start with a simple daily progress goal!' vs 'Start tracking your daily progress!'). Consider having one delegate to the other so the defaults can't drift.

What's good (verified):

  • utils/llm/goals.py: the progress-line rework in get_goal_advice correctly covers all None/zero combinations including the ZeroDivisionError guard, and the bool-is-int trap handling in _safe_float/_safe_optional_float is right.
  • utils/llm/goals.py extract_and_update_goal_progress: skipping purely qualitative goals from the prompt (token savings) plus the double-guard before update_goal_progress is a real improvement — LLM hallucination can no longer write numeric progress into a qualitative goal.
  • models/goal.py: the mode='before' validator is a sound self-healing schema (bool/NaN/Inf coercion, min/max swap when reversed).
  • routers/goals.py: the not goal.get('id') guard is correct and tested.
  • tests: hermetic stubs throughout, no network; the test constants match the repo's standard synthetic values.

Performance/cost: the qualitative-goal skip removes a wasted LLM call per extract-progress request for qualitative-only users — a token cost reduction, no new spend. Blast radius: goals advice/suggestion endpoints only; nothing else imports these helpers.

USER IMPACT: users with qualitative goals or cleared metrics will get real AI advice instead of errors, and the suggest-goal button will stop returning server errors — but a request for advice on a deleted/invalid goal ID would now return generic advice instead of a "not found" error until the item above is settled.

Still wanted as a reviewer: a test pinning whichever 404-vs-200 contract you choose for /v1/goals/{goal_id}/advice, and a CI run on the head commit (no check results were visible at review time).


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

@Speedyzyzz

Copy link
Copy Markdown
Contributor Author

@Git-on-my-level Thanks for the thorough review and catch! Both points are addressed in commit 35ad2a5:

  1. Restored 404 API Contract (Option a): In backend/utils/llm/goals.py, moved the goal lookup and active check outside try: and dropped the inner except ValueError: catch. Missing or inactive goals now propagate ValueError("Goal not found") straight up to backend/routers/goals.py line 292, which returns HTTPException(status_code=404, detail="Goal not found"). Active goals that encounter LLM / context retrieval failures continue to return the canned fallback advice with HTTP 200.

  2. Deduplicated Sanitizer Logic: Extracted sanitize_suggestion_dict in backend/models/goal.py and delegated _sanitize_goal_suggestion in backend/utils/llm/goals.py directly to it. Both files now share the exact same logic and standardized default reasoning ('Start tracking your daily progress!'), eliminating code drift.

  3. Test Coverage & Pinning:

    • Pinned the 404 contract at both the utility layer (test_get_goal_advice_missing_or_inactive_goal asserts ValueError) and the FastAPI router layer (test_get_goal_advice_router_raises_404_for_missing_goal asserts HTTPException(404)).
    • Added test_get_goal_advice_llm_failure_returns_fallback_advice to verify LLM failures still gracefully return 200 with fallback advice for active goals.
    • Added test_sanitize_suggestion_delegation_consistency to verify delegation and output equality.
    • Updated test_goals_any_active_goal.py to assert ValueError for inactive goals.

All 80 unit tests in the goals suite pass hermetically, and pyright reports 0 errors.

@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 (the blocking API-contract issue — in backend/utils/llm/goals.py get_goal_advice the goal lookup and raise ValueError("Goal not found") now sit outside the try, the broad except ValueError swallow is gone, and test_get_goal_advice_router_raises_404_for_missing_goal asserts the 404) · still open (nothing blocking) · newly introduced (nothing blocking; two nits below).

Verdict: the blocking issue from my earlier review is resolved — this looks merge-ready to me; leaving formal sign-off to a human maintainer.

Verified per file:

  • backend/utils/llm/goals.py — get_goal_advice now parses metrics via _safe_optional_float (bool/NaN/Inf guarded) and builds one of five PROGRESS prompt lines (numeric with %, numeric without %, current-only, target-only, qualitative), killing the NoneType-compare, format-string, and ZeroDivisionError crashes. extract_and_update_goal_progress skips purely qualitative goals both when building the prompt and as a write-path double-guard — a real token saving on every conversation with a qualitative goal. All suggest_goal paths route through the shared sanitizer.
  • backend/models/goal.py — sanitize_suggestion_dict is the single source of truth; the GoalSuggestionResponse model_validator(mode='before') delegates to it (nice dedup of the previously duplicated logic). Bounds swap when min > max and pad when equal; type allowlist {scale, numeric, boolean}; exported in all.
  • backend/routers/goals.py — get_current_goal_advice now returns the setup message for goal dicts lacking 'id' instead of raising KeyError. I checked get_user_goal: it only returns is_active goals with non-terminal status, so this path can't hit the ValueError re-raise in normal flow.
  • backend/tests/unit/test_goals_defensive.py — solid coverage: cleared metrics, zero targets, NaN/corrupt storage values, bool-hallucinated LLM JSON, reversed bounds, parse-failure fallback, router 404, and LLM-failure fallback, all with stubbed Firestore/LLM (no network).
  • backend/tests/unit/test_goals_any_active_goal.py — correctly flipped to expect the ValueError for the achieved-goal case, matching the restored contract.

Cost: qualitative goals no longer enter the extract-progress LLM call — fewer tokens per conversation. Security: no new surfaces; the ENCRYPTION_SECRET/OPENAI_API_KEY fixture pattern in the new test matches the existing repo-wide test convention. Blast radius: goals advice/suggestion/extract endpoints only; failure modes now degrade to fallbacks instead of 500s.

USER IMPACT: users with qualitative goals (no numeric metric) or cleared metrics now get real AI goal advice instead of an error, and goal suggestions can no longer 500 on malformed LLM output; requesting advice for a missing/inactive goal now correctly returns 404 instead of a canned 200 message.

Two nits, neither blocking: (1) if a goal flips to inactive between get_user_goal and get_goal_advice in GET /v1/goals/advice, the ValueError would surface as a 500 rather than 404 — a narrow race, but a try/except there would keep it consistent; (2) the _sanitize_goal_suggestion/sanitize_goal_suggestion alias pair in utils/llm/goals.py is redundant with the models.goal import — one alias would do.

Still wanted before merge: a green Backend Unit Tests run on this head (no check runs are currently reported on the branch).


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 their stale review October 22, 2026 12:10

Dismissing as resolved: the blocking concern (get_goal_advice's broad except ValueError swallowing the "Goal not found" raise, breaking the router's 404 contract) is fixed on the current head — the lookup and raise now sit outside the try, and test_get_goal_advice_router_raises_404_for_missing_goal asserts HTTP 404. Verified on commit 35ad2a5.

@Speedyzyzz

Speedyzyzz commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for the quick re-review and the merge-ready verdict @Git-on-my-level!

Addressed both nits in commit 473158e5bf:

  1. Inactive Goal Race Guard: In backend/routers/goals.py, wrapped get_current_goal_advice in a defensive try/except to ensure any inactive goal race condition surfaces as a clean 404 rather than bubbling up, pinned with a new unit test in test_goals_defensive.py.
  2. Consolidated Sanitizer Alias: Removed the redundant _sanitize_goal_suggestion alias in backend/utils/llm/goals.py and standardized all call sites on sanitize_goal_suggestion.

All 25 unit tests across test_goals_defensive.py and test_goals_any_active_goal.py pass clean locally with zero network dependencies.

On a personal note, I am a 3rd year student passionate about building voice AI and open source hardware. Diving deep into the Omi backend and LiveKit integrations has been an absolute blast. My dream is to join your team down the line, and until then, I am more than happy keeping the backend bulletproof one edge case at a time. Ready for human maintainer merge!

@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 (both nits — the inactive-goal race guard and the duplicate sanitizer alias, verified on the new head) · still open (a green Backend Unit Tests run on this head; no checks are reported on the branch) · newly introduced (nothing).

Verdict: both remaining nits from my last review are resolved and nothing new came in with 473158e — this still looks merge-ready to me; leaving formal sign-off to a human maintainer.

What the new commit changes (verified):

  • backend/routers/goals.py — get_current_goal_advice now wraps the get_goal_advice call in try/except ValueError -> HTTPException(404), so a goal that flips inactive between get_user_goal and the advice call returns 404 instead of an unhandled 500. This matches the {goal_id}/advice endpoint's contract.
  • backend/tests/unit/test_goals_defensive.py — the new test_get_current_goal_advice_raises_404_on_inactive_goal_race pins that behavior; the rest of the hermetic suite (cleared metrics, zero targets, NaN/corrupt storage, bool-hallucinated LLM JSON, reversed bounds, parse-failure fallback) is unchanged since my last pass.
  • backend/utils/llm/goals.py — the duplicate _sanitize_goal_suggestion alias is gone; every suggest_goal path now goes through the single sanitize_goal_suggestion alias delegating to models.goal.sanitize_suggestion_dict, so defaults cannot drift.
  • backend/models/goal.py and backend/tests/unit/test_goals_any_active_goal.py — unchanged since my last review (self-healing GoalSuggestionResponse validator; contract flip expecting ValueError for achieved goals).

USER IMPACT: none beyond the earlier fixes — users with qualitative goals keep getting real AI advice, and advice on a goal that was just completed or deleted now consistently returns "not found" instead of an occasional server error.

Still wanted before merge: a green Backend Unit Tests run on this head — no check runs are reported on the branch, so the suite has not been exercised by CI on this commit.


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

@Speedyzyzz

Copy link
Copy Markdown
Contributor Author

@Git-on-my-level need human response

Thanks for verifying that both nits are resolved and confirming the merge-ready verdict!

Since this PR is submitted from a fork, GitHub Actions requires a maintainer with write access to click the "Approve and run workflows" button on this PR to execute the Backend Unit Tests suite. Could you please trigger the workflow run and hit merge?

@Speedyzyzz

Copy link
Copy Markdown
Contributor Author

Resolved merge conflicts with upstream main cleanly in commit 45b32f6. All 32 goals defensive and regression unit tests pass with zero issues. Branch is completely mergeable and ready for maintainer sweep.

@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: the only new commit is a merge of upstream/main (45b32f6) · still open (a green Backend Unit Tests run on this head — the branch still reports no check runs) · newly introduced (nothing).

Verdict: still looks merge-ready to me; formal sign-off stays with a human maintainer.

The merge was the one risky step, because main recently landed its own goal-suggestion hardening (#23434) in the same file. Verified on the new head:

  • backend/utils/llm/goals.py — the merge keeps both sides: #23434's unlocked-memory filtering and _safe_float_field per-field coercion are intact, with this PR's sanitize_goal_suggestion final pass layered after them. The get_goal_advice null-safety (qualitative / zero-target / one-sided-metric progress lines) and the qualitative-goal skip in extract_and_update_goal_progress are unchanged from the last head I reviewed.
  • backend/models/goal.py — byte-identical to the last head; sanitize_suggestion_dict + the GoalSuggestionResponse before-validator are as previously reviewed.
  • backend/routers/goals.py and both test files — unchanged by the merge; the 404-on-missing/inactive-goal contract and the defensive suite carry over as-is.
  • backend/tests/unit/test_goals_defensive.py — the ENCRYPTION_SECRET / OPENAI_API_KEY literals match the dummies already used in backend/tests/unit/test_goals_any_active_goal.py on main; no new secret material.

USER IMPACT: users with qualitative goals or cleared metrics get real AI advice instead of an error fallback, and goal suggestions no longer 500 on malformed LLM output.

Still want before merge: one green Backend Unit Tests run on this head (none is reported on the branch), and a maintainer's look at the now-layered sanitization order (per-field coercion, then sanitize_suggestion_dict) to confirm it's the intended end state after #23434.


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

@kodjima33 kodjima33 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.

Backend bug fix: guards goal advice/suggestion pipeline against TypeError/ZeroDivisionError/ResponseValidationError for qualitative/cleared-metric goals. Scoped to goals subsystem, 18 new hermetic tests (147 passed), no abuse signals in diff, no linked issue so no self-bounty timing tell detectable. Confidence 4/5 (diff size only miss).

@kodjima33
kodjima33 merged commit 3486e8a into BasedHardware:main Oct 25, 2026
Git-on-my-level added a commit that referenced this pull request Oct 25, 2026
#23608)

#22220 added 'from models.goal import sanitize_suggestion_dict' to
utils/llm/goals.py, but the fixture in test_goals_wrapped_firmware_hardening.py
stubs 'models' as an empty package whose hand-listed fakes omitted
'models.goal'. In CI's per-file pytest processes (BACKEND_PYTEST_FILE_ISOLATION)
nothing pre-imports the real module, so the fresh goals.py exec hit
ModuleNotFoundError and all 7 tests errored on every run since 3486e8a
(deterministic main-red; shared local sessions hid it because a sibling test
file imports models.goal at module scope).

Load the real models.goal via load_module_fresh before the stub block and
register it in the fakes mapping: the fixture becomes self-contained (no import
ordering / shared sys.modules state) and the tests keep asserting the real
sanitize_suggestion_dict null-coercion behavior instead of a mock.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backend Backend Task (python) positive-signal Automation verified a genuine fix/quality contribution

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants