Skip to content

refactor(backend): centralize app notification dispatch - #12409

Merged
undivisible merged 7 commits into
BasedHardware:mainfrom
aryanorastar:codex/9518-notification-dispatch
Sep 19, 2026
Merged

undivisible merged 7 commits into
BasedHardware:mainfrom
aryanorastar:codex/9518-notification-dispatch

Conversation

@aryanorastar

@aryanorastar aryanorastar commented Aug 30, 2026 •

Copy link
Copy Markdown
Collaborator

What changed and why

Starts the backend notification-owner convergence requested by #9518 with a reviewable first production slice.

  • Adds a frozen, typed NotificationIntent and one NotificationDispatcher that returns explicit dispatched, suppressed, or failed outcomes.
  • Moves both external integration notification APIs (/v1/integrations/notification and /v2/integrations/{app_id}/notification) onto that owner.
  • Deletes the two router-local copies of the hourly rate-limit policy and uses the existing atomic Redis reservation primitive instead of read-then-increment races.
  • Moves internal and realtime app-integration push helpers through the same dispatcher while preserving their direct/no-external-quota policy.
  • Adds a shrink-only AST ratchet. Its guard list is derived from utils/notifications.py — every public function whose own body calls an FCM primitive — rather than hand-listed, so a sender added later is guarded the day it lands. The remaining 32 legacy direct calls across 18 files are recorded exactly; additions, alias escapes, hidden baseline growth, and stale baselines fail. Later refactor(backend): converge notification sending onto one dispatch owner (typed intents, single policy point) #9518 slices can only move this number down. Direct callers only: a wrapper delivering through another public function (send_credit_limit_notification → send_notification) is not itself counted.

This deliberately does not claim full closure of #9518. Other producer families, preference/quiet-hour policy, deduplication, cron, and the final zero baseline remain separate reviewable migrations.

Behavior and compatibility

  • External integrations still receive a 10-notification UTC-hour quota with the existing rate-limit response headers and 429 behavior.
  • The Redis reservation is now atomic under concurrent requests, and its TTL is bounded to the next UTC-hour boundary so the existing quota window is preserved.
  • App attribution (plugin_id) and app/main-chat navigation payloads are preserved.
  • Suppression and delivery failure are observable without logging notification content.
  • The new Redis namespace means one deployment can reset the in-progress integration quota once; no user data or notification is deleted.
  • No Flutter, iOS, Android, macOS client, or hardware path is changed.

Product invariants affected

None. This preserves the existing integration-notification contract while consolidating its backend owner.

How it was verified

  • backend/.venv/bin/python -m pytest -q backend/tests/unit/test_notification_dispatch.py backend/tests/unit/test_app_notification_plugin_id.py — 9 passed.
  • backend/.venv/bin/python -m pytest -q backend/tests/unit/test_integration_notification_validation.py — 1 passed.
  • App/realtime coordinator suites — 67 passed.
  • Mentor/proactive coordinator suite — 50 passed.
  • python3 .github/scripts/test_check_notification_dispatch_boundary.py — 5 mutation/ratchet tests passed.
  • python3 .github/scripts/check_notification_dispatch_boundary.py --base origin/main — 32 legacy direct calls, ratchet held.
  • python3 .github/scripts/test_run_checks.py — 47 manifest contract tests passed.
  • Black and git diff --check passed.

Tests

backend/tests/unit/test_notification_dispatch.py covers the shared contract and its error paths: full quota then suppression, app/user bucket isolation, UTC-hour expiry, direct-policy bypass, typed payload attribution/navigation, content-safe failure observability, and async transport delivery.

.github/scripts/test_check_notification_dispatch_boundary.py proves the guard resolves direct aliases and module-qualified calls, detects function escapes, rejects baseline-assisted growth, and accepts only exact downward ratchets.

Failure class (fixes)

Failure-Class: FC-split-mutation-authority

New guards

#9518 documents the live split authority: notification policy and low-level delivery are owned across routers and utility modules. The AST ratchet complements the shared dispatcher because Python cannot make a transport import private across packages; it turns the staged migration into an enforceable monotonic boundary rather than an honor-system convention.

Part of #9518.

Review in cubic

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@Git-on-my-level Git-on-my-level added backend Backend Task (python) workflow-review Needs maintainer review for workflow, automation, hooks, or CI behavior needs-maintainer-review Needs a human maintainer to sign off before merge labels Aug 30, 2026
@Git-on-my-level

Copy link
Copy Markdown
Member

Reviewed file-by-file against the #9518 dispatch-owner plan — this is a strong, well-scoped first slice. Findings below; nothing blocking from my side, but a couple of decisions deserve a human maintainer.

Verified sound

  • backend/utils/notification_dispatch.py — clean separation of intent (NotificationIntent), policy (EXTERNAL_APP_HOURLY vs DIRECT), and delivery, with injectable reserve/clock seams. Lazy _default_reserve/_default_*_delivery imports keep Redis/Firebase out of policy tests. Logging is structured and content-free (uid/kind/source/reason, never the body) — nice privacy touch.
  • Rate-limit parity: I compared _apply_policy + database.redis_db.reserve_rate_limit's Lua (remaining = max - current on admit, 0 on deny, TTL=window) against the deleted router check_rate_limit math — the header contract matches, the atomic reservation removes the real read-then-increment race, and window_seconds = 3600 - (ts % 3600) is in [1, 3600] so the TTL can never be zero. One actual improvement: Retry-After now equals the reset time on deny instead of always 0.
  • backend/routers/integration.py / backend/routers/notifications.py — the two duplicated ~55-line limiters collapse into one owner; 429 shape, plugin_id attribution, navigate_to, and the chat-message-before-dispatch ordering are preserved. In v1, moving target resolution before dispatch means suppressed requests no longer write chat messages (previously rate-limited requests skipped them too via the not allowed early-return, so behavior matches — worth a glance to confirm you agree that's the intended contract).
  • .github/scripts/check_notification_dispatch_boundary.py + baseline + tests — the ratchet counts alias imports, module-qualified calls, and bare pass/assignment of transport functions (ownership escapes), excludes the transport owner/dispatcher/tests, requires the baseline to exactly match observed counts, and rejects growth even when the baseline is edited to match. I spot-checked the baseline against the tree: app_integrations.py keeps exactly its 1 legacy call (proactive path) and routers/notifications.py its 1 (dev-key endpoint). The git show {base} shrink-only comparison follows the same pattern as the existing failure-class-guard-artifact-ratchet, and both new manifest entries satisfy the run_checks.py schema (triggers/lanes/reason).
  • Test updates are honest migrations: test_notification_dispatch.py covers full-quota-then-suppress, per-app/user isolation, UTC-hour window expiry, DIRECT bypass, plugin attribution, and failure observability; test_mentor_notifications.py/test_app_notification_plugin_id.py follow the new boundary; the deleted _FakeRedis regression test covered check_rate_limit, which no longer exists.

For the maintainer

  • New CI checks run repo-wide: both manifest entries trigger on backend/**/*.py, so every future backend PR runs the boundary ratchet. The check itself looks correct, but wiring new repo-wide enforcement is a workflow decision worth explicit sign-off.
  • One-time quota reset: the new rl:integration-notification:* key namespace means one deploy resets in-flight integration quotas (disclosed in the PR description). Operationally fine per the author; flagging so it's a conscious call.
  • v1 delivery-failure semantics: transport exceptions now yield 200 + logged failed outcome instead of propagating. This matches v2's existing behavior, but it is a behavior change on v1.
  • Later slices, not here: the daily proactive caps in app_integrations.py still live at call sites (callers now use the default DIRECT policy); ratchet alias detection is one level deep and skips any tests/ dir under backend/. Both fine for a staged migration — just make sure the refactor(backend): converge notification sending onto one dispatch owner (typed intents, single policy point) #9518 tracking captures them.

Labeled backend + workflow-review + needs-maintainer-review (the last two for the new repo-wide CI checks and the quota-key migration, which need maintainer sign-off). Thanks @aryanorastar — this is careful work.


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

@aryanorastar

Copy link
Copy Markdown
Collaborator Author

@undivisible @kodjima33 green and mergeable, reviewed two days ago with nothing blocking.

The review flagged three things as needing a human rather than more code: the new boundary ratchet triggers on backend/**/*.py so it runs on every future backend PR, one deploy resets in-flight integration quotas (new key namespace), and v1 transport failures now return 200 with a logged outcome instead of propagating — matching v2. All three are in the PR description; they need a yes, not a change.

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

Clean consolidation of notification dispatch with a shrink-only ratchet guard, but it's an explicit refactor (not a bug fix), so approve-only per policy.

@aryanorastar

Copy link
Copy Markdown
Collaborator Author

Answering the one item from the review that was addressed to me rather than to a maintainer — the v1 chat-message ordering. I had left it implicit; here it is checked against both trees.

Confirmed: the contract is preserved. A rate-limited v1 request writes no chat message, before or after.

main today:

check_rate_limit(...)
if not allowed:              -> 429, returns here
    ...
target = ...                 -> resolved inside the chat_messages_enabled branch
add_integration_chat_message(...)
send_app_notification(..., target=target)

This head:

target = ...                 -> resolved first, so the typed payload and the chat
                                message carry the same destination
outcome = dispatch_notification(intent)
if outcome.status == SUPPRESSED:   -> 429, returns here
add_integration_chat_message(...)

Both return 429 ahead of the write, so suppression skips the chat message on both. That is the behaviour you described, and yes — it is the intended contract. A quota rejection should not leave a chat row implying the notification went out.

The one real difference is that target resolution moved ahead of dispatch. It is a pure read of app.external_integration.chat_messages_target with no side effects, so nothing observable changes; it exists so the intent carries the same destination the chat message will use, instead of the two being derived independently.

No code change from this, so I am not pushing to an approved and clean head. The three items you routed to a maintainer — repo-wide ratchet triggers, the one-time quota-key reset, and v1 transport failures now returning 200 with a logged failed outcome to match v2 — are unchanged and still need a yes rather than a change.

Also carrying forward, for whoever picks up the next #9518 slice: the daily proactive caps in app_integrations.py still live at their call sites, and the ratchet's alias detection is one level deep and skips tests/ dirs. Both are deliberate for a staged migration and belong in the tracking issue rather than here.

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

Solid, well-tested backend refactor (dispatcher consolidation) from a trusted contributor, but it's a refactor not a bug fix, so per policy it stays approve-only rather than an auto-merge.

…on-dispatch

# Conflicts:
#	.github/checks-manifest.yaml
@aryanorastar

Copy link
Copy Markdown
Collaborator Author

Conflict resolved on 0645100. Merge of current main only — no change to this diff.

The conflict was in .github/checks-manifest.yaml, and it is the list-head shape rather than a disagreement: main added go-device-sdk-tests at the top of checks: while this branch adds notification-dispatch-boundary and its test entry in the same place. Neither side replaces the other, so the resolution is the union.

Verified by parsing rather than by eye, since a manifest that looks merged and has silently dropped an entry is exactly the failure this file cannot afford: 175 entries here against main's 173, the two added are this PR's, none dropped, no duplicate ids.

The ratchet still holds against the moved base, which was the thing worth checking — main advanced 1208 commits, and a new direct transport caller landing there would have shown up as growth:

notification dispatch boundary: 20 legacy direct calls (ratchet held)

Same count as the approved head, so main added no new bypass while this sat.

Verification on the merged head: boundary ratchet held at 20 against origin/main; its 5 mutation tests pass; test_run_checks.py 52 passed (main grew it from 47); both manifest entries execute green through run_checks.py --lane local; test_notification_dispatch.py + test_app_notification_plugin_id.py + test_integration_notification_validation.py 10 passed; test_mentor_notifications.py 50 passed. Pre-push gate passed.

Scope is unchanged: git diff origin/main...HEAD is the same 12 files, +791/−177, backend and .github only.

The three items routed to a maintainer are unchanged by this merge and still need a yes rather than a change: the boundary ratchet triggering on backend/**/*.py so it runs on every future backend PR, the one-time integration-quota reset from the new rl:integration-notification:* namespace, and v1 transport failures now returning 200 with a logged failed outcome to match v2.

@Git-on-my-level

Copy link
Copy Markdown
Member

Re-verified at the new head 06451005 (merge of main; conflict in .github/checks-manifest.yaml). This is the delta check on top of my earlier review of this PR, not a repeat of it.

Merge resolution is lossless. The manifest at head is exactly the parsed union of both parents' entries — 175 checks, no duplicates, nothing dropped from either side, both notification-dispatch-boundary entries intact with the same command/triggers/lanes/reason. All nine PR-authored files (backend/utils/notification_dispatch.py, the dispatch wiring in both routers, the ratchet scanner/baseline/self-tests, and the four touched test files) are byte-identical to the previously reviewed tree; on the two shared files (backend/routers/integration.py, backend/utils/app_integrations.py) the only residue versus main is this PR's own dispatch change set — main's incoming hunks (geolocation enrichment, integration redaction, proactive-notification rework) came through unchanged.

Ratchet still holds on the merged tree. Ran .github/scripts/check_notification_dispatch_boundary.py --base <merge-base> on a head checkout: 20 legacy direct calls (ratchet held), exit 0 — the baseline still matches the tree exactly after ~200 commits of main moving underneath it.

Tests re-run green at head with the repo venv: scanner self-tests 5/5; test_notification_dispatch.py + test_app_notification_plugin_id.py (9 passed); test_mentor_notifications.py + test_integration_notification_validation.py (51 passed). database.redis_db.reserve_rate_limit survived the merge with the exact signature the dispatcher calls.

Nothing new blocks from my side. One mechanical item: @kodjima33's approvals are attached to the pre-merge tree (they predate 06451005 by a few minutes), so the head needs a re-approval — given the byte-identical verification above, that should be a glance. The three substantive decisions from my earlier comment (repo-wide ratchet triggers on backend/**/*.py, the one-time rl:integration-notification:* quota-key reset on deploy, v1 delivery-failure now returning 200 + logged outcome) remain the open maintainer items, all disclosed in the PR description.

Thanks @aryanorastar — verifying the manifest merge by parsing rather than by eye was exactly the right instinct for that file.


by AI on behalf of David — re-approval of the head SHA by a maintainer is the remaining step; the substantive items above need a yes, not a change.

… point

The conflict was `.github/checks-manifest.yaml` for the second time in three
days, and both times for the same mechanical reason: main inserts new checks
just below the SDK block at the top of `checks:`, which is exactly where this
branch's two entries sit. Last merge it was go-device-sdk-tests; this one is
typescript-device-sdk-tests.

Resolved as the union again, but the two notification-dispatch entries now go
at the end of the list instead of the head, so the next check main adds does
not collide with them. Order carries no meaning here -- run_checks validates
by id and rejects duplicates, and nothing depends on position -- so this costs
nothing and stops a conflict that would otherwise recur on every new check.

Verified by parsing rather than by eye: 179 entries against main's 177, the
two added are this PR's, none dropped, no duplicate ids.

Co-Authored-By: Claude Opus 5 <[email protected]>
@aryanorastar

Copy link
Copy Markdown
Collaborator Author

Conflict resolved on acb844e — same file as three days ago, and this time I also removed the reason it keeps happening.

Why it recurred. Both conflicts are the same mechanical shape, not a disagreement: main inserts new checks just below the SDK block at the top of checks:, which is exactly where this branch's two entries sit. Last merge that was go-device-sdk-tests; this one is typescript-device-sdk-tests. Sitting at that position means every check main adds conflicts with this PR for as long as it is open.

So the two notification-dispatch-* entries now live at the end of the list rather than the head. Order carries no meaning in this file — run_checks validates by id and rejects duplicates, nothing reads position, and the two entries still execute green through run_checks.py --lane local. The relocation costs nothing and takes this branch out of main's insertion path.

Verified by parsing rather than by eye, same as last time: 179 entries against main's 177, the two added are this PR's, none dropped, no duplicate ids.

The ratchet held again on a base that moved another 171 commits:

notification dispatch boundary: 20 legacy direct calls (ratchet held)

Still the same count as the approved head, so no new direct transport caller has landed on main in the two weeks this has been open — which is the whole point of a shrink-only boundary on a staged migration.

Verification on the merged head: ratchet held at 20 against origin/main; its 5 mutation tests pass; test_run_checks.py 52 passed; both manifest entries execute green; test_notification_dispatch.py + test_app_notification_plugin_id.py + test_integration_notification_validation.py + test_mentor_notifications.py 60 passed. Pre-push gate passed. Scope unchanged at 12 files, +791/−177, backend and .github only.

The three items routed to a maintainer are untouched by this merge and still need a yes rather than a change: the boundary ratchet triggering on backend/**/*.py, the one-time integration-quota reset from the rl:integration-notification:* namespace, and v1 transport failures returning 200 with a logged failed outcome to match v2.

@aryanorastar

aryanorastar commented Sep 11, 2026 •

Copy link
Copy Markdown
Collaborator Author

The two red backend checks on acb844e are not from this diff. Triaged rather than assumed.

What fails: tests/unit/test_memories_archive_and_read_contracts.py::test_memory_item_to_memorydb_attaches_belief_view_only_when_flag_on, in shard 3/4:

>       assert on.currency_band == "fading"
E       AssertionError: assert 'history' == 'fading'

The Backend unit suite job failing after 3s is its aggregator, not a second failure.

Why it isn't this PR. The file is not in this diff — git diff origin/main...HEAD is the same 12 files, notification dispatch and .github only — and it is byte-identical to main. Nothing here touches backend/models/memories.py, belief views, or currency bands.

Reproduced on clean main. I checked out origin/main at 6cd3dd653c in a separate worktree and ran the single test there: it fails identically, same assertion, same 'history' == 'fading'. So the break is on main, and this PR's merge only pulled it in.

Root cause — corrected. My first read of this blamed d2826e6b and called the history/fading disagreement a memory-domain semantics question. That was wrong, and I'd rather fix it here than leave it standing. Both the band logic and the read path are correct. The test is a time bomb:

  • the fixture pins captured_at to 2026-07-13T12:00Z with half_life_days: 30;
  • memory_item_to_memorydb calls public_belief_overlay(item, now=datetime.now(timezone.utc)) (canonical_memory_adapter.py:410) and takes no now a test can inject;
  • compute_currency is 0.5 ** (days_since / half_life_days), and FADING_BAND_MIN is 0.25, i.e. fading requires currency >= 0.25.

So the assertion held for exactly two half-lives and then flipped:

captured_at  : 2026-07-13 12:00 UTC
flip         : 2026-09-11 12:00:00 UTC   (60 days = 2 half-lives, currency crosses 0.25)

Nothing changed in the code on Sep 11 — the clock crossed the band floor. After that instant the test fails permanently, on every backend PR, on main included.

Fixed on main. b5d425e (#13506) anchors captured_at to datetime.now(timezone.utc) - timedelta(days=30) so it is always exactly one half-life old. I had the same fix open as #13501 (45-day mid-band anchor); it was closed as superseded, which is the right call — one of them landing is what matters. Merging current main clears this red here.

This PR's own surface is unaffected and still green on the head: boundary ratchet held at 20 against origin/main, its 5 mutation tests pass, test_run_checks.py 52 passed, both manifest entries execute green, and the notification suites are 60 passed. Shards 1, 2 and 4 are green; only the shard carrying that memories file is red.

@Git-on-my-level

Copy link
Copy Markdown
Member

Verified the CI triage and it holds up. All four red checks trace to causes outside this diff: shard 3/4 fails on tests/unit/test_memories_archive_and_read_contracts.py::test_memory_item_to_memorydb_attaches_belief_view_only_when_flag_on (currency_band 'history' vs 'fading'), a clock-relative belief-view fixture fixed on main in b5d425e (#13506) at 16:46Z — after this run — with main's backend suite green again at 17:04Z; Backend unit suite is that failure's aggregator; both Desktop Swift failures are pull_request_target workflow-shape gates plus a SwiftPM test-step time budget, and this diff touches no desktop or workflow file beyond the checks manifest.

Also independently confirmed the merge resolution at acb844e is net-exactly the twelve PR files against merged main, with the checks-manifest union lossless.

Still leaving the three previously flagged decisions with a human maintainer before merge: the new dispatch-boundary ratchet runs on every future backend PR; the Redis key namespace change resets in-flight integration quotas once at deploy; and v1 now mirrors v2's 200-on-transport-failure contract. The code side looks in good shape.


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

… boundary ratchet

BasedHardware#13173 added `send_client_displayed_notification` and its async twin to
`utils/notifications.py`, and moved `utils/chat.py` off `send_notification`
onto them. Both new functions reach `_send_to_user{,_async}` directly, so
they are transport entry points like the ones already listed — but the
scanner did not know the names, so after merging main `chat.py` read as 0
direct calls and the checker demanded the baseline drop it.

That would have recorded a reduction that never happened and left two
unguarded ways to own transport. Adding the names restores `chat.py: 2`,
so the baseline is unchanged and the ratchet still holds at 20.

Failure-Class: none
@aryanorastar

aryanorastar commented Sep 11, 2026 •

Copy link
Copy Markdown
Collaborator Author

Merged current main on 3a38a4eb and fixed one thing the merge exposed. Both reds on the previous head are accounted for.

The backend red is gone. b5d425e (#13506) landed the clock anchor for the belief-band fixture, so test_memories_archive_and_read_contracts.py is 11 passed here now. I corrected my earlier triage comment above in place rather than stacking a reply on it — the failure was never d2826e6b or a memory-domain semantics question, it was a fixture pinning captured_at while the adapter reads datetime.now(timezone.utc), which crossed two half-lives at 2026-09-11T12:00:00Z.

The merge exposed a hole in this PR's own ratchet, and it would have failed open. #13173 added send_client_displayed_notification and send_client_displayed_notification_async to utils/notifications.py and moved utils/chat.py off send_notification onto them. Both new functions call _send_to_user{,_async} directly, so they are transport entry points exactly like the names the scanner already tracked — but the scanner did not know them, so after the merge chat.py scanned as 0 direct calls and the checker demanded I drop its 2 from the baseline:

baseline must exactly match current direct transport calls
observed={... no 'backend/utils/chat.py' ...}
baseline={... 'backend/utils/chat.py': 2 ...}

Taking that at face value would have recorded a reduction that never happened and left two unguarded ways to own transport. So I added the two names to TRANSPORT_CALLS instead. chat.py reads 2 again, the baseline file is unchanged, and the ratchet still holds at 20.

Checked it rather than assuming: with the names added, a fresh file calling send_client_displayed_notification is rejected (exit 1, the new path shows up in observed), and removing it passes again. Added one test that pins this directly, so the next transport entry point added to utils/notifications.py has a failing test to point at.

The desktop red on acb844e was not a test failure. 823 Swift suites ran, none failed, and the step failed a wall-clock budget: the Desktop Swift suite step took 2414s, over its 1800s regression budget.

I first read that as a cold SwiftPM cache and was wrong — green runs log the same skipping cache due to an error ... maintenance.lock doesn't exist warnings and restore the identical cache keys, and they finish in 780-873s. The real cause is one wedged batch:

swift test invocation [batch worker-2-0 x100] wall=1649s exit=143 (budget 1500s)

Exit 143 is the harness watchdog's SIGTERM at the 1500s per-invocation ceiling. Every other invocation in that run exited 0 in 16-94s, the machine was otherwise idle for 23 minutes, and the two halved re-runs of that same batch passed in 56s and 48s. So ~1500s of the 2414s is a single batch of 100 suites hanging in one SwiftPM process and then being killed — not build cost, and nothing this diff can reach.

This push re-runs the lane.

Verified on the new head: boundary ratchet 20 with the baseline untouched, its 6 tests pass, test_run_checks.py 52 passed, both manifest entries execute green as CI invokes them, notification suites 60 passed, and the diff against main is the same 12 files as before the merge.

@Git-on-my-level

Copy link
Copy Markdown
Member

Delta-verified at 3a38a4e and re-ran the verification at this head; one new finding on the ratchet that deserves a decision before merge.

Delta since the last reviewed head (acb844e)

The only PR-authored change is 3a38a4e, the two-line addition of send_client_displayed_notification{,_async} to TRANSPORT_CALLS in .github/scripts/check_notification_dispatch_boundary.py. The premise checks out against main: backend/utils/chat.py there now calls that pair directly, so without the fix the scanner would have read chat.py as 0 and demanded a phantom baseline reduction — the fix is correct and well-reasoned.

Re-verified at this head in a clean container: ratchet exit 0 ("20 legacy direct calls (ratchet held)"), scanner self-tests 6/6, and the four touched unit files green (test_notification_dispatch.py, test_app_notification_plugin_id.py, test_mentor_notifications.py, test_integration_notification_validation.py — 60/60). backend/utils/notification_dispatch.py, the router wiring in backend/routers/integration.py and backend/routers/notifications.py, and backend/utils/app_integrations.py are unchanged since the last review and still check out; .github/checks-manifest.yaml parses to 180 unique entries with both notification-dispatch-boundary entries present exactly once.

New finding: the ratchet guards 7 of the 16 public transport entry points, and the baseline locks that in at merge

backend/utils/notifications.py has 16 public functions that reach _send_to_user/_send_to_user_async/_send_messages. TRANSPORT_CALLS names 7. The other 9 (send_action_item_data_message, send_apple_reminders_sync_push{,_async}, send_merge_completed_message, send_important_conversation_message, send_action_item_update_message, send_action_item_deletion_message, send_action_items_batch_deletion_message, send_batch) are bypasses a new producer can use today without tripping the check — and 10 existing call sites in 7 files already do (routers/action_items.py, routers/developer.py, utils/task_sync.py, utils/conversations/merge_conversations.py, utils/conversations/process_conversation.py, utils/retrieval/tools/action_item_tools.py, utils/retrieval/tool_services/action_items.py). Scanning with the full public surface yields 32 direct calls across 18 files, so the recorded 20 understates the real transport ownership the manifest reason says this check prevents.

The part that makes this a now-or-never decision: validate_baseline requires the baseline to exactly match observed counts and rejects any per-file growth. I simulated a post-merge PR that widens TRANSPORT_CALLS honestly — it fails twice (exact-match: observed 32/18 files vs baseline 20/13; then growth: routers/action_items.py 1→5, routers/developer.py 0→2, …). So after merge, widening the guard requires migrating every newly visible call site to the dispatcher in the same PR, or weakening the check. Pre-merge it is a one-commit change. The PR description's "the remaining 20 legacy transport dependencies are recorded exactly" is exact only for the 7-name subset.

Three reasonable resolutions — maintainer's call, not necessarily more code:

The production slice itself is unaffected and still looks good. @kodjima33's approvals sit on 6ee10dc (an ancestor of this head; the only PR-authored delta since is the two-line fix), so the re-approval decision is a good place to weigh which ratchet resolution this PR should ship with.


by AI on behalf of David — the ratchet-coverage choice above needs a maintainer decision before merge.

aryanorastar and others added 2 commits September 14, 2026 09:39
…on-dispatch

# Conflicts:
#	.github/checks-manifest.yaml
The boundary ratchet guarded a hand-written list of seven names — two private, five public — and
utils/notifications.py has thirteen public functions that call an FCM
primitive directly. The other eight — send_action_item_data_message, the
action-item update/deletion/batch-deletion messages,
send_apple_reminders_sync_push{,_async}, send_important_conversation_message
and send_merge_completed_message — were bypasses a new producer could use
without tripping the check, and twelve existing call sites already did.

The recorded 20 was exact only for the subset. Against the module's real
surface the tree has 32 direct calls across 18 files.

Two properties make this worth fixing before merge rather than after. The
baseline must exactly match observed counts and may never grow per file, so
once it is on main, widening the guard means migrating every newly visible
call site in the same PR or weakening the check. And the list has already
drifted once: the first entry point added after it (BasedHardware#13173) went unguarded
until a merge happened to surface it.

So the list is gone. The checker reads the transport module and treats as an
entry point every public function whose own body calls _send_to_user,
_send_to_user_async or _send_messages. A sender added tomorrow is guarded the
day it lands, with no edit here. The baseline is regenerated at the honest 32;
there is no baseline on main yet, so this is the one moment that costs nothing.

Direct callers only, and that limit is stated in the checker and pinned by a
test: a wrapper delivering through another public function
(send_credit_limit_notification -> send_notification) is not itself counted.
A missing or unparseable transport module raises rather than deriving an empty
list that would pass as zero calls.

Mutation-checked: restoring a fixed list fails the new derivation test, and
the real tree's ratchet rejects a baseline that no longer matches; a fresh
producer calling send_merge_completed_message — previously unguarded — is now
counted and rejected.

Failure-Class: none

Co-Authored-By: Claude Opus 5 <[email protected]>
@aryanorastar

Copy link
Copy Markdown
Collaborator Author

Took option 1, plus the change that stops it recurring, on d8f7700d18. Merged current main on d598fa93b7 first.

The finding holds, with one count to correct. utils/notifications.py on main has thirteen public functions that call an FCM primitive directly, not sixteen — send_batch is a closure nested inside send_bulk_notification, not an importable entry point. The ratchet named five of the thirteen, so eight were unguarded: send_action_item_data_message, the action-item update / deletion / batch-deletion messages, send_apple_reminders_sync_push{,_async}, send_important_conversation_message and send_merge_completed_message. Your call-site total was right regardless: against the real surface the tree has 32 direct calls across 18 files, and the recorded 20 was exact only for the subset.

Why derive rather than extend the list. Extending it would have been the one-commit fix you described, and it would drift again — it already had: the first entry point added after the list was written (#13173) went unguarded until a merge surfaced it, which is what 3a38a4e was patching. So the list is gone. The checker reads the transport module and counts as an entry point every public function whose own body calls _send_to_user, _send_to_user_async or _send_messages. A sender added later is guarded the day it lands, with no edit to the checker. The baseline is regenerated at the honest 32; since there is no baseline on main yet, this is the moment it costs nothing — exactly your point about exact-match and no-growth locking in whatever merges.

Stated limit, pinned rather than implied. Direct callers only. A public wrapper that delivers through another public function (send_credit_limit_notification → send_notification) is not itself counted, so its producers are not either. Those wrappers each send one fixed, already-typed notification; widening to them is a later #9518 slice, and a test asserts the current boundary so it moves deliberately. A missing or unparseable transport module raises rather than deriving an empty list that would pass as zero calls.

Verified:

  • ratchet: 32 legacy direct calls (ratchet held) against origin/main;
  • mutation-checked: restoring a fixed name list fails the new derivation test, and the real tree then rejects the baseline; a fresh producer calling send_merge_completed_message — one of the eight previously unguarded — is now counted and rejected;
  • checker tests 9/9 (three new: a new sender guarded without editing the checker, wrappers excluded, missing module fails closed); test_run_checks.py 52 passed; notification suites 60 passed;
  • scope unchanged at 12 files, backend and .github only.

The manifest conflict recurred at the tail this time — main now appends there too, so the relocation three days ago only moved the collision. The two entries now sit mid-list after backend-datetime-sort-sentinel-ratchet, a neighbour untouched since Aug 21, which is the one position neither end of the list keeps growing into. Verified by parsing: 193 entries against main's 191, the two added are this PR's, none dropped, no duplicate ids.

PR description updated to the derived guard and the 32 count, including the direct-callers-only limit. The earlier maintainer items — the ratchet running on every backend PR, the one-time rl:integration-notification:* quota reset, and v1 returning 200 with a logged failed outcome — are unchanged and still need a yes rather than a change. The approval on 6ee10dc will need re-applying to this head.

@Git-on-my-level

Copy link
Copy Markdown
Member

Delta-verified at d8f7700d — the ratchet finding from the prior review is resolved, and resolved the right way.

What changed since the last reviewed head (3a38a4e)

One PR-authored commit: check_notification_dispatch_boundary.py no longer hand-lists transport entry points. transport_entry_points() now parses backend/utils/notifications.py and derives the guard list from the module itself — every public function whose own body calls _send_to_user, _send_to_user_async, or _send_messages — so the drift that motivated 3a38a4e (#13173 landing unguarded) can no longer happen: a new sender is counted the day it lands. The corrected count (13 public entry points, send_batch being a closure, not an entry point) checks out against the tree, and the baseline is regenerated at the honest 32 direct calls across 18 files.

Independently verified in a clean clone of this head

  • Ratchet: exit 0 against origin/main — 32 legacy direct calls (ratchet held); the baseline file does not exist on main, so initializing it here is free rather than a lock-in.
  • Derivation: transport_entry_points() on the real tree returns exactly the 13 public senders, matching the corrected inventory.
  • The guard bites where it previously didn't: a probe producer calling send_merge_completed_message (one of the eight previously unguarded names) is counted and fails the check with exit 1.
  • Checker self-tests 9/9, including the three new ones (new sender guarded without editing the checker; wrappers like send_credit_limit_notification → send_notification excluded as a stated, test-pinned limit; missing transport module raises instead of deriving an empty list).
  • Manifest merge is lossless: 193 unique entries at head vs 191 on main — only this PR's notification-dispatch-boundary{,-tests} added, nothing dropped or duplicated.
  • New unit tests (test_notification_dispatch.py, test_app_notification_plugin_id.py) pass; the removed check_rate_limit off-by-one regression test is superseded by test_external_app_policy_delivers_full_quota_then_suppresses, which asserts the full 10-of-10 quota through the new atomic reservation path.

The production slice is unchanged since prior reviews and still checks out, including reserve_rate_limit's TTL-on-deny semantics feeding Retry-After/X-RateLimit-Reset.

Still open before merge — the same three maintainer yes/no decisions from earlier in the thread, unchanged by this commit: (1) the ratchet triggers on backend/**/*.py, so it runs on every future backend PR; (2) the switch to the rl:integration-notification:* key namespace resets in-flight integration quotas once at deploy; (3) v1 returns 200 with a logged failed outcome when FCM delivery fails. None need code from where I stand — they need a maintainer ruling, plus re-approval at this head given the earlier approvals sit on 6ee10dc.


by AI on behalf of David — the ratchet-coverage fix is verified; the three queued decisions above need a maintainer ruling before merge.

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

Solid refactor (centralizes notification dispatch, atomic Redis reservation, AST ratchet guard) with good test coverage, but it's explicitly a refactor — confidence gate requires a bug/issue fix to merge, so approve-only.

@aryanorastar

Copy link
Copy Markdown
Collaborator Author

@Git-on-my-level need human response — kodjima approved d8f7700 as approve-only. The three items from the earlier review are unchanged and still need a yes or no, not more code:

  1. Repo-wide ratchet on backend/**/*.py (every future backend PR).
  2. One-time in-flight quota reset from rl:integration-notification:*.
  3. v1 transport failure now returns 200 + logged failed (match v2).

I am not merging on the GitHub APPROVED state. If any of those is a no, say which one and I will cut or close.

@undivisible

Copy link
Copy Markdown
Collaborator

Maintainer ruling on the three open items — this is the yes/no the thread has been waiting on:

  1. Repo-wide ratchet (backend/**/*.py triggers): YES. It only runs on backend-touching PRs, same trigger shape as the dead-code ratchet / async blockers / route-policy baseline. Deriving the guard list from utils/notifications.py (your d8f7700d fix) is exactly right.

  2. One-time rl:integration-notification:* quota reset: ACCEPTED, no migration. Old keys (notification_rate_limit:{app}:{uid}:{hour}, TTL 3600s) die within an hour anyway. Blast radius = external integration apps get at most one extra quota window at deploy. A migration script is permanent code for a one-hour blip.

  3. v1 200-on-transport-failure: SHIP AS-IS. I checked the wire contract on main: _send_to_user already swallows FCM exceptions (except → log → return 0, utils/notifications.py:287) and both v1 and v2 already return 200 {'status': 'Ok'} on failed delivery today. This PR changes zero wire behavior — it just makes the failure a typed, logged outcome instead of a silent return 0. Surfacing delivery outcomes to callers (e.g. an additive delivered field) is a separate follow-up slice under refactor(backend): converge notification sending onto one dispatch owner (typed intents, single policy point) #9518; it should not hold this PR.

Merge follows. Nice work — the delta-review trail on this one is genuinely excellent.

@undivisible
undivisible merged commit d54ad22 into BasedHardware:main Sep 19, 2026
39 checks passed
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 workflow-review Needs maintainer review for workflow, automation, hooks, or CI behavior

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants