Repository navigation
fix(goals): guard qualitative goals against NoneType compare crashes and coerce suggestion floats - #22220
Conversation
…and coerce suggestion floats
…n qualitative goals
|
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:
Material dimensions:
Non-blocking nits: the new 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 |
|
Thanks for the thorough review @Git-on-my-level! All 18 unit tests in |
Git-on-my-level
left a comment
There was a problem hiding this comment.
Verdict: Strong defensive fix and excellent test coverage — one blocking API-contract issue to resolve before merge.
Blocking:
backend/utils/llm/goals.pyget_goal_advice: the newexcept ValueError: return 'Focus on the next small step toward your goal.'sits in the same function that still doesraise ValueError("Goal not found")for missing/inactive goals. The router forGET /v1/goals/{goal_id}/advicerelies 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_goalencodes 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 inget_goal_advicecorrectly covers all None/zero combinations including the ZeroDivisionError guard, and the bool-is-int trap handling in_safe_float/_safe_optional_floatis right.utils/llm/goals.pyextract_and_update_goal_progress: skipping purely qualitative goals from the prompt (token savings) plus the double-guard beforeupdate_goal_progressis a real improvement — LLM hallucination can no longer write numeric progress into a qualitative goal.models/goal.py: themode='before'validator is a sound self-healing schema (bool/NaN/Inf coercion, min/max swap when reversed).routers/goals.py: thenot 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.
…tract and dedup suggestion sanitizer
|
@Git-on-my-level Thanks for the thorough review and catch! Both points are addressed in commit 35ad2a5:
All 80 unit tests in the goals suite pass hermetically, and pyright reports 0 errors. |
Git-on-my-level
left a comment
There was a problem hiding this comment.
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.
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.
…e suggestion alias
|
Thanks for the quick re-review and the merge-ready verdict @Git-on-my-level! Addressed both nits in commit
All 25 unit tests across 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
left a comment
There was a problem hiding this comment.
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.
|
@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? |
|
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
left a comment
There was a problem hiding this comment.
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_fieldper-field coercion are intact, with this PR'ssanitize_goal_suggestionfinal pass layered after them. Theget_goal_advicenull-safety (qualitative / zero-target / one-sided-metric progress lines) and the qualitative-goal skip inextract_and_update_goal_progressare unchanged from the last head I reviewed. - backend/models/goal.py — byte-identical to the last head;
sanitize_suggestion_dict+ theGoalSuggestionResponsebefore-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_KEYliterals 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
left a comment
There was a problem hiding this comment.
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).
#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.
Summary
Hardens the goal tracking AI advice, suggestion, and extraction pipeline against runtime crashes (
TypeError,ZeroDivisionError, and FastAPIResponseValidationErrorHTTP 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 runtimeTypeErrorcrashes 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
Goal Advice Null-Safety & Qualitative Support (
utils/llm/goals.py&routers/goals.py):get_goal_advice: Whentarget_valueorcurrent_valueisNone(qualitative goals or cleared metrics), the previous code evaluatedif target_value > 0:and formatted{current_value:,.0f} / {target_value:,.0f}, raisingTypeError: '>' not supported between instances of 'NoneType' and 'int'and format stringTypeError._safe_optional_floatto safely parse metrics, guarding against the Pythonbool-is-inttrap (isinstance(True, int) == True).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.ZeroDivisionErrorwhentarget_value == 0.routers/goals.py: Inget_current_goal_advice, guards against goal documents lacking an'id'field.Self-Healing Goal Suggestions & Float Coercion (
models/goal.py&utils/llm/goals.py):@model_validator(mode="before")onGoalSuggestionResponseinmodels/goal.pyto make the Pydantic schema intrinsically self-healing againstnull, booleans, stringNaN/Infinity, and invertedmin > maxbounds across any caller.suggest_goal: Coercessuggested_target,suggested_min, andsuggested_maxto valid finitefloatvalues (suggested_min <= suggested_max) and normalizessuggested_typeto valid enum strings (scale,numeric,boolean), completely eliminating FastAPIResponseValidationError(HTTP 500) failures.Token Drain & Metric Corruption Prevention (
utils/llm/goals.py):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.Invariant Conformance
GoalSuggestionResponse,AdviceResponse).Verification
backend/tests/unit/test_goals_defensive.py(18/18 passing in 1.13s).bool-is-inttrap (_safe_float(True, 10.0) == 10.0).GoalSuggestionResponseself-healing model validator.UI Evidence
UI-Evidence: none (backend Python logic and hermetic test suite only)
Failure Class
Failure-Class: none
Bounty Payout Details