Skip to content

Bound the in-memory proactive-notification cache so it cannot grow unbounded - #9795

Merged
kodjima33 merged 1 commit into
BasedHardware:mainfrom
ZachL111:zach/mem-db-proactive-noti-cap
Jul 15, 2026
Merged

kodjima33 merged 1 commit into
BasedHardware:mainfrom
ZachL111:zach/mem-db-proactive-noti-cap

Conversation

@ZachL111

@ZachL111 ZachL111 commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

What

database.mem_db keeps an in-memory cache of when a proactive notification was last sent:

proactive_noti_sent_at: dict[str, tuple[int, float]] = {}

def set_proactive_noti_sent_at(uid, *, app_id, ts, ttl=30):
    k = f'{uid}:{app_id}'
    proactive_noti_sent_at[k] = (ts, ttl + time.time())

def get_proactive_noti_sent_at(uid, app_id):
    ...
    ts, ex = proactive_noti_sent_at[k]
    if ex < time.time():
        del proactive_noti_sent_at[k]   # only place an entry is ever removed
        return None
    return ts

An expired entry is deleted only when its own key is read again. So a key for a user who churns, or an app that is uninstalled, is written once and never revisited, and it stays in the dict for the whole process lifetime. The map grows without bound. This is exactly the case the backend guide calls out (gotcha #11: "Module-level dicts: add TTL-based eviction or cap size - they grow forever otherwise").

Called from the proactive/mentor notification path (utils/app_integrations.py), so distinct {uid}:{app_id} keys accumulate over time.

Fix

Sweep expired entries and cap the map on write:

_MAX_PROACTIVE_NOTI_ENTRIES = 50000

def _prune_proactive_noti(now: float) -> None:
    for key in [k for k, (_ts, ex) in proactive_noti_sent_at.items() if ex < now]:
        del proactive_noti_sent_at[key]
    if len(proactive_noti_sent_at) > _MAX_PROACTIVE_NOTI_ENTRIES:
        overflow = len(proactive_noti_sent_at) - _MAX_PROACTIVE_NOTI_ENTRIES
        for key in sorted(proactive_noti_sent_at, key=lambda k: proactive_noti_sent_at[k][1])[:overflow]:
            del proactive_noti_sent_at[key]

def set_proactive_noti_sent_at(uid, *, app_id, ts, ttl=30):
    k = f'{uid}:{app_id}'
    now = time.time()
    proactive_noti_sent_at[k] = (ts, ttl + now)
    if len(proactive_noti_sent_at) > _MAX_PROACTIVE_NOTI_ENTRIES:
        _prune_proactive_noti(now)

The prune drops already-expired entries first (semantically gone -- get() already returns None for them), and only if still over the cap does it drop the entries nearest to expiry. It runs only when the map exceeds the cap, so the common path is a single dict write as before. The read path and the 30s TTL semantics are unchanged.

Tests

New tests/unit/test_mem_db_proactive_noti_cap.py (direct calls, no heavy import):

  • writing many already-expired entries past the cap sweeps them and keeps the map within the cap
  • the cap holds even when every entry is still live (nearest-to-expiry eviction)
  • get still returns a live value and None for an expired entry

Verification

cd backend && ENCRYPTION_SECRET=... python -m pytest tests/unit/test_mem_db_proactive_noti_cap.py -q
  -> 3 passed
black --line-length 120 --skip-string-normalization --check database/mem_db.py tests/unit/test_mem_db_proactive_noti_cap.py
  -> unchanged
python -m pyright -p pyrightconfig.json database/mem_db.py
  -> 0 errors
python scripts/check_module_stub_pollution.py
  -> Checked 661 test file(s); 0 violations

Product invariants affected

none

Review in cubic

…bounded

database.mem_db.proactive_noti_sent_at maps "<uid>:<app_id>" -> (sent_ts, expiry_ts). An expired
entry is deleted only when its own key is read again in get_proactive_noti_sent_at, so keys for
churned users or uninstalled apps are never revisited and accumulate for the whole process lifetime.
The repo's own guidance requires module-level dicts to add a TTL or size cap (backend gotcha BasedHardware#11).

set_proactive_noti_sent_at now sweeps already-expired entries (which get() already treats as gone)
and, if still over _MAX_PROACTIVE_NOTI_ENTRIES, drops the entries nearest to expiry, so the map stays
bounded. The sweep runs only when the map exceeds the cap, so the common path is unchanged.

tests/unit/test_mem_db_proactive_noti_cap.py: expired entries are swept when over the cap, the cap
holds even when all entries are live, and get still returns a live value and None for an expired one.
@Git-on-my-level

Copy link
Copy Markdown
Member

Thanks for tightening this cache — the failure mode is real: expired proactive-notification keys are only removed when the same key is read again, so churned users/apps can otherwise leave entries behind for the lifetime of the backend process.

I reviewed the diff and ran the new targeted regression test locally:

cd backend && python -m pytest tests/unit/test_mem_db_proactive_noti_cap.py -q
# 3 passed

The fix is narrowly scoped, keeps the cache bounded on writes, and includes coverage for both expired-entry sweeping and the all-live overflow case. I did not find a blocking code issue in this patch.

Leaving this as a positive maintainer signal rather than a formal approval: this touches a backend runtime cache/rate-limit path and the automation approval gate for this PR is still conservative, so a human maintainer should make the final merge decision.


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.

Qualifying bug fix (root cause stated, scoped, tested, CI green).

@kodjima33
kodjima33 merged commit afe5431 into BasedHardware:main Jul 15, 2026
22 of 25 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants