Skip to content

[codex] Extract user data services - #8393

Merged
Git-on-my-level merged 29 commits into
mainfrom
codex/techdebt-user-data-services
Jun 27, 2026
Merged

Git-on-my-level merged 29 commits into
mainfrom
codex/techdebt-user-data-services

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Jun 26, 2026 •

Copy link
Copy Markdown
Member

Summary

  • Extract account deletion orchestration from backend/routers/users.py into backend/services/users/account_deletion.py.
  • Extract GDPR/CCPA user export generation into backend/services/users/data_export.py while keeping router response headers unchanged.
  • Add focused service/router tests and retarget stale delete-account unit tests to the new service boundary.

Validation

  • python -m pytest -q backend/tests/services/users/test_account_deletion.py backend/tests/services/users/test_data_export.py backend/tests/routers/test_users.py
  • python -m pytest -q backend/tests/routers -k users
  • python -m pytest -q backend/tests/unit/test_delete_account_stripe_cancel.py backend/tests/unit/test_delete_account_purge_storage.py
  • python -m compileall backend/routers/users.py backend/services/users/account_deletion.py backend/services/users/data_export.py
  • black --line-length 120 --skip-string-normalization on changed Python files

Review in cubic

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

4 issues found across 10 files

Confidence score: 2/5

  • In backend/services/users/account_deletion.py, running deletion cleanup in a daemon thread means shutdown/redeploy can kill the wipe mid-flight, leaving accounts only partially deleted after users are told deletion began; move this to a durable non-daemon worker/job (or block until completion) before merging.
  • In backend/services/users/data_export.py, the hard 10,000-row cap for memories/action_items can produce incomplete GDPR/CCPA exports for heavy users, which is a clear user/compliance risk; remove the silent truncation and paginate/stream all records before merge.
  • In backend/services/users/data_export.py, doing large DB reads before the first yield defeats streaming and can spike latency/memory or trigger timeouts on large accounts; restructure to fetch in chunks and yield early to restore true streaming behavior.
  • In backend/tests/unit/test_delete_account_stripe_cancel.py, the free-user and Stripe-error tests don’t assert thread.start(), so regressions in launching cleanup could slip through; add explicit start() assertions in those paths before merging to lock in expected behavior.

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Comment thread backend/services/users/data_export.py Resolved
Comment thread backend/services/users/data_export.py Resolved
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Addressed the user-data service review feedback:

  • Export now yields the opening JSON chunk before DB reads, so the response starts streaming immediately.
  • Memories and standalone action items are exported page-by-page instead of being capped at 10,000 records.
  • Account deletion now submits the background wipe to the shared postprocess executor instead of a daemon thread.
  • Added assertions that paid, free, and Stripe-error deletion paths enqueue the wipe.
  • Added data export regression tests for early yield and pagination, and wired the data export test file into backend/test.sh.

Verification run locally:

uv run pytest tests/unit/test_delete_account_stripe_cancel.py tests/unit/test_delete_account_purge_storage.py tests/services/users/test_data_export.py -v
# 12 passed in 0.10s

uv run black --check services/users/data_export.py services/users/account_deletion.py tests/unit/test_delete_account_stripe_cancel.py tests/unit/test_delete_account_purge_storage.py tests/services/users/test_data_export.py
# 5 files would be left unchanged

git diff --check
# passed

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

2 issues found across 5 files (changes from recent commits).

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Comment thread backend/test.sh Resolved
Comment thread backend/services/users/data_export.py Resolved
@Git-on-my-level
Git-on-my-level force-pushed the codex/techdebt-user-data-services branch from df3d959 to 12cfdad Compare June 26, 2026 09:07
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Follow-up fixes for the second Cubic pass:

  • Added tests/services/users/test_account_deletion.py to backend/test.sh so the service-level account-deletion suite runs in the standard backend test runner.
  • Switched memory export pagination to get_non_filtered_memories(...) so the page length reflects the raw exported page and cannot terminate early because get_memories(...) filters after fetching.
  • Updated the service-level account-deletion tests to assert the postprocess-executor enqueue path instead of the old daemon-thread path.

Verification run locally:

uv run pytest tests/services/users/test_account_deletion.py tests/services/users/test_data_export.py tests/unit/test_delete_account_stripe_cancel.py tests/unit/test_delete_account_purge_storage.py -v
# 19 passed in 0.10s

uv run black --check services/users/data_export.py services/users/account_deletion.py tests/services/users/test_account_deletion.py tests/services/users/test_data_export.py tests/unit/test_delete_account_stripe_cancel.py tests/unit/test_delete_account_purge_storage.py
# 6 files would be left unchanged

git diff --check
# passed

@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 refactor: extract user data services (account deletion/export) — refactor, approve only

@Git-on-my-level

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 12cfdade2b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread backend/test.sh Resolved
Add the router-level delegation/error/header test to test.sh so it runs
in CI alongside the service-level tests it complements. Addresses Codex
review comment (P2): the new test file was added but never exercised by
the repository CI runner.
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Wired pytest tests/routers/test_users.py -v into backend/test.sh (grouped with the two tests/services/users/ entries), so the router-level delegation / 500 mapping / streaming-header coverage runs in CI.

Verification:

  • pytest tests/routers/test_users.py -v → 3 passed (0.32s) locally in the worktree venv (pylock.macos.toml, Python 3.11.15):
    • test_delete_account_delegates_to_service
    • test_delete_account_maps_unexpected_service_error_to_500
    • test_export_all_user_data_keeps_streaming_headers

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7af787a28d

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Add a dedicated bounded cleanup executor for long-running account deletion
wipes and enqueue background_wipe_user_data there instead of the shared
postprocess pool. This keeps bursts of account deletions from starving normal
conversation post-processing work.

Update account deletion tests to assert the wipe is enqueued on the cleanup
executor.
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Addressed the new Codex P2 about account deletion wipes consuming the shared postprocess pool.

What changed:

  • Added a dedicated bounded cleanup_executor in backend/utils/executors.py for long-running account-deletion cleanup work.
  • Changed start_account_deletion() to enqueue background_wipe_user_data on cleanup_executor instead of postprocess_executor.
  • Updated account-deletion service tests to assert the wipe is enqueued on the cleanup executor.

Verification passed locally:

  • .venv/bin/python -m pytest tests/services/users/test_account_deletion.py tests/routers/test_users.py -v → 10 passed
  • .venv/bin/python -m py_compile utils/executors.py services/users/account_deletion.py tests/services/users/test_account_deletion.py tests/routers/test_users.py → passed

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f7bb537995

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Codex review (discussion_r3482677110) flagged that the test asserts
users_service.postprocess_executor, which no longer exists on the module.
account_deletion.py imports and submits work with cleanup_executor (the
dedicated long-running account-deletion pool). Update all three
submit.assert_called_once_with assertions to reference cleanup_executor.

Verification: pytest tests/unit/test_delete_account_stripe_cancel.py (3 passed)
and tests/services/users/test_account_deletion.py (7 passed).
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Fixed in 3253151c1.

account_deletion.py imports and submits work with cleanup_executor (the dedicated long-running account-deletion pool from utils.executors), not postprocess_executor. The three submit.assert_called_once_with(...) assertions in test_delete_account_stripe_cancel.py were still referencing the old postprocess_executor name, which raised AttributeError and broke the test.

Updated all three assertions to reference users_service.cleanup_executor.

Verification:

  • pytest tests/unit/test_delete_account_stripe_cancel.py → 3 passed
  • pytest tests/services/users/test_account_deletion.py → 7 passed

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3253151c13

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread backend/utils/executors.py Resolved
Addresses P1 review feedback (Codex): the new cleanup_executor was
added to _ALL_EXECUTORS but test_get_executor_metrics_returns_all_pools
still asserted the old 7-element set. Update the expected set to include
'cleanup'.
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Fixed: include cleanup executor in metrics test

Review feedback addressed: discussion_r3482740809 (P1, @chatgpt-codex-connector)

What changed

  • Updated test_get_executor_metrics_returns_all_pools in backend/tests/unit/test_executors.py to include 'cleanup' in the expected executor set, matching the cleanup_executor now registered in _ALL_EXECUTORS.

Verification

  • Ran the 4 executor-metrics tests locally — all pass:
    python -m pytest tests/unit/test_executors.py::test_get_executor_metrics_returns_all_pools \
      tests/unit/test_executors.py::test_get_executor_metrics_fields \
      tests/unit/test_executors.py::test_get_executor_metrics_idle_utilization \
      tests/unit/test_executors.py::test_all_executors_are_monitored -v
    → 4 passed
    
  • Pre-commit formatting hook passed (no changes needed).
  • The expected set now matches get_executor_metrics() output exactly: {'critical', 'db', 'llm', 'stripe', 'sync', 'postprocess', 'cleanup', 'storage'}.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: c1ee3ac15e

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread backend/services/users/data_export.py Resolved
Comment thread backend/routers/users.py Resolved
Address P1 review feedback from chatgpt-codex-connector:

- test_llm_usage_endpoints.py: add get_people/get_user_profile to the
  database.users stub so services.users.data_export's module-level import
  succeeds when routers.users is imported under lightweight stubs.
- test_lock_bypass_fixes.py: re-point gdpr export test patches from
  routers.users.* to services.users.data_export.* and use
  get_non_filtered_memories (the actual helper the service calls).
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Addressed P1 review feedback

Fixed both P1 items raised by @chatgpt-codex-connector about the backend test runner breaking after the service extraction.

Thread 1 — database.users stub missing get_people/get_user_profile (r3482817433)

routers.users now imports services.users, which eagerly loads services/users/data_export.py. That module does from database.users import get_people, get_user_profile at module level. The test_llm_usage_endpoints.py test stubs database.users as a plain ModuleType with only transcription helpers, so the named import raised ImportError at collection time.

Fix: Added get_people and get_user_profile to the database.users stub in test_llm_usage_endpoints.py (consistent with the existing stub pattern for other DB helpers).

Thread 2 — GDPR export test patches pointing at wrong symbols (r3482817436)

test_gdpr_export_includes_locked patched routers.users.get_user_profile / get_people / get_standalone_action_items (old namespace) and database.memories.get_memories. After the extraction, these helpers live in services.users.data_export, and the service calls get_non_filtered_memories instead of get_memories. The patches had no effect, so the test consumed MagicMock-backed data and failed with TypeError: Type MagicMock not serializable.

Fix: Re-pointed the three patches to services.users.data_export.* and switched get_memories → get_non_filtered_memories.

Verification

  • test_llm_usage_endpoints.py: 2 passed (was failing at collection)
  • test_lock_bypass_fixes.py::test_gdpr_export_includes_locked: passed (was failing with TypeError)
  • New PR tests (test_data_export.py, test_account_deletion.py, test_users.py): 14 passed
  • black --check --line-length 120 --skip-string-normalization: clean

@chatgpt-codex-connector

Copy link
Copy Markdown

To use Codex here, create an environment for this repo.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d63a330822

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread backend/routers/users.py Resolved
…port to module scope

- P1 (account_deletion.py:106): persist wipe_status pending/completed markers
  in the account_deletions Firestore collection before enqueueing the wipe.
  A deploy/restart that cancels a queued cleanup_executor future no longer
  leaves the deletion silently incomplete — a reconciliation worker can query
  for wipe_status='pending' and re-enqueue. mark_user_deletion_wipe_started
  is written before enqueue; mark_user_deletion_wipe_completed in finally.
- P2 (routers/users.py:148): move start_account_deletion import to module
  scope per backend AGENTS.md Import Rules ('All imports at module top level').
- Update tests to assert wipe-status persistence and module-level import patching.

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Review feedback addressed

P1: Persist account-deletion wipes before returning OK (account_deletion.py:106)

Added persistent wipe-status markers in the existing account_deletions Firestore collection so a deploy/pod restart that cancels a queued cleanup_executor future no longer leaves the deletion silently incomplete.

What changed:

  • database/users.py: added mark_user_deletion_wipe_started(uid) and mark_user_deletion_wipe_completed(uid). Both write wipe_status to the top-level account_deletions document (same collection that already stores deletion feedback, survives the user-record wipe).
  • account_deletion.py: mark_user_deletion_wipe_started is called right before submit_with_context (line 117). mark_user_deletion_wipe_completed is called in a finally block at the end of background_wipe_user_data so it runs even when the wipe fails.
  • A reconciliation worker can query where wipe_status == 'pending' to find and re-enqueue wipes that were cancelled before they started. The marker write itself is best-effort (logged on failure, never blocks deletion).

This is a lighter-weight fix than a full durable queue + drain worker, which would be a separate infrastructure change. The pending marker gives the same reconciliation capability.

P2: Move account-deletion import to module scope (routers/users.py:148)

Moved from services.users.account_deletion import start_account_deletion to the module-level imports (line 25), alongside the existing from services.users.data_export import iter_user_data_export. Verified no circular dependency — account_deletion.py imports only from database/ and utils/, never from routers/.

Verification

  • tests/services/users/test_account_deletion.py: 7 passed — updated to assert wipe-status persistence ordering and finally-block behavior
  • tests/routers/test_users.py: 3 passed — updated to patch the module-level reference via patch.object instead of sys.modules injection
  • tests/unit/test_delete_account_* + test_executors.py: 32 passed
  • black --check --line-length 120: all files clean

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 630944cbb6

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Address Codex P1 review feedback: a crash or deploy after
auth.delete_account() succeeds but before the marker transitions to
'pending' left a 'deleting_auth' record outside the reconciler's
recovery query, permanently stranding the Firestore/GCS/vector wipe.

Changes:
- get_pending_deletion_wipes() now also fetches stale 'deleting_auth'
  records (age-gated in Python, same over-fetch pattern as 'pending')
- _claim_deletion_wipe_txn() handles 'deleting_auth' status with the
  same transactional age re-validation as 'pending'
- reconcile_pending_deletion_wipes() verifies the Firebase auth user is
  actually gone via _is_auth_user_gone() before recovering a
  'deleting_auth' record — fails safe on indeterminate errors so a
  transient Firebase outage cannot trigger a premature data wipe
- Updated docstrings/comments throughout to reflect the new recovery
  guarantee

Tests: 5 new tests covering recovery (user gone), skip (user exists),
skip (indeterminate error), and _is_auth_user_gone helper (both paths).
All 19 account_deletion tests + 9 claim_deletion_wipe_txn tests pass.
@Git-on-my-level

Copy link
Copy Markdown
Member Author

P1 fix: Recover stranded deleting_auth records after crash/deploy

Addressed Codex feedback — a crash/deploy after auth.delete_account() succeeds but before the marker transitions to pending permanently stranded the Firestore/GCS/vector wipe.

Root cause

The two-phase marker writes deleting_auth (non-actionable) in Phase 1, then transitions to pending (actionable) in Phase 2. The reconciler's get_pending_deletion_wipes() never queried deleting_auth, so a crash in that window left the wipe permanently unrecoverable.

Fix (3 files)

  • database/users.py — get_pending_deletion_wipes() now also fetches stale deleting_auth records (same age-gated over-fetch pattern as pending). _claim_deletion_wipe_txn() handles the deleting_auth status with the same transactional age re-validation.
  • services/users/account_deletion.py — Added _is_auth_user_gone(uid) helper that verifies the Firebase auth user is actually deleted before recovering. reconcile_pending_deletion_wipes() calls it for any deleting_auth record before claiming — fails safe on indeterminate errors so a transient Firebase outage cannot trigger a premature wipe.
  • Tests — 5 new tests:
    • test_reconcile_recovers_deleting_auth_when_user_gone — stale record + auth user deleted → recovered/enqueued
    • test_reconcile_skips_deleting_auth_when_user_exists — stale record + auth user exists → skipped (claim never called)
    • test_reconcile_skips_deleting_auth_on_indeterminate_error — stale record + Firebase internal error → skipped (fail safe)
    • test_is_auth_user_gone_returns_true_for_user_not_found — helper returns True for USER_NOT_FOUND
    • test_is_auth_user_gone_returns_false_for_indeterminate_error — helper returns False for non-USER_NOT_FOUND errors

Safety invariant preserved

A fresh deleting_auth record (intent just written, auth deletion in progress) is still never recovered — the stale age gate applies in both the query (Python) and the claim (transaction), and the auth-user-gone check adds a third layer.

Verification

  • pytest tests/services/users/test_account_deletion.py — 19 passed (14 existing + 5 new)
  • pytest tests/unit/test_claim_deletion_wipe_txn.py — 9 passed (existing transaction tests, unmodified)
  • pytest tests/unit/test_delete_account_stripe_cancel.py tests/unit/test_delete_account_purge_storage.py — 8 passed
  • black --check and ruff clean (pre-existing PlanLimits unused import in database/users.py is unrelated)

@Git-on-my-level

Copy link
Copy Markdown
Member Author

This is already handled in the squashed commit. The recovery path for stale deleting_auth records exists and is tested:

  1. get_pending_deletion_wipes() (backend/database/users.py:337-350) queries wipe_status == 'deleting_auth' docs and age-filters them (default 10 min stale cutoff).
  2. reconcile_pending_deletion_wipes() (backend/services/users/account_deletion.py:278-284) verifies _is_auth_user_gone(uid) returns True before claiming and re-enqueueing a deleting_auth record. If the auth user still exists or the Firebase check is indeterminate, the record is skipped.
  3. claim_deletion_wipe() re-validates the wipe_intent_at age inside the Firestore transaction (lines 383-391) so a fresh intent from an in-progress deletion can never be claimed prematurely.

So the crash scenario described — backend dies after auth.delete_account(uid) succeeds but before _persist_wipe_marker_with_retry transitions to 'pending' — is recovered: the stale 'deleting_auth' marker ages out, the reconciler verifies the Firebase user is gone, and re-enqueues the Firestore/GCS/vector wipe.

Verified by running pytest tests/services/users/test_account_deletion.py — 19 passed. The recovery path is specifically covered by:

  • test_reconcile_recovers_deleting_auth_when_user_gone (stale + user gone → recovered)
  • test_reconcile_skips_deleting_auth_when_user_exists (stale + user exists → skipped)
  • test_reconcile_skips_deleting_auth_on_indeterminate_error (indeterminate → skipped, fail safe)
  • test_is_auth_user_gone_returns_true_for_user_not_found / test_is_auth_user_gone_returns_false_for_indeterminate_error

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 9d2a902e60

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Addresses chatgpt-codex-connector P2: the stubbed database.users module
stayed cached in sys.modules after import against the fake _client.db,
leaking into later unit tests in a multi-file pytest run. Record its
prior sys.modules entry alongside the transitive stubs so the autouse
fixture restores/removes it after this module's tests finish.
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Addressed P2: Remove the stubbed database.users module after import in commit 998710b.

What changed
database.users is imported against the fake database._client.db and mocked cache helpers, so after import it stayed cached in sys.modules as a half-stubbed module. The _STUB_PRIORS dict only tracked the transitive stubs (database._client, database.firestore_cache, database.redis_db, utils.subscription), not database.users itself. In a multi-file pytest run, a later module importing database.users would reuse this half-stubbed version, making results depend on collection order.

Fix: record database.users's prior sys.modules entry in _STUB_PRIORS immediately before importing it, so the existing module-scoped _restore_sys_modules autouse fixture restores (or removes) it after this module's tests finish.

Verification
Ran the module's full suite locally:

python -m pytest tests/unit/test_claim_deletion_wipe_txn.py -v

9 passed, 0 failed.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 998710be1a

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread backend/database/users.py Resolved
Addresses chatgpt-codex-connector P2 (discussion_r3484122470): the
imported services.users.account_deletion and services.users.data_export
modules stayed cached in sys.modules with MagicMock globals
(users_db, stripe_utils, cleanup_executor, etc.) after being loaded via
the _StubFinder. In a multi-file pytest run, a later test importing the
real service would reuse this mock-backed copy instead of reloading
production dependencies.

Both test files now pop the service module and its parent packages from
sys.modules in the finally block, alongside the existing stub cleanup.
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Two fixes pushed (commit ec8323c) plus a design assessment for the third comment.


Fixed — P2: Remove stubbed service modules after import (test_account_deletion.py)

The imported services.users.account_deletion module stayed cached in sys.modules with MagicMock globals (users_db, cleanup_executor, stripe_utils, etc.) after being loaded via the _StubFinder. The cleanup popped the dependency stubs but left the service module itself. In a multi-file pytest run, a later test importing the real service would reuse this mock-backed copy.

Fix: pop services.users.account_deletion and its parent packages (services.users, services) in the finally block alongside the existing stub cleanup. Applied the same fix to test_data_export.py which has the identical pattern.

Verification: 32 tests pass across all three affected test modules:

python -m pytest tests/services/users/test_account_deletion.py tests/services/users/test_data_export.py tests/unit/test_claim_deletion_wipe_txn.py -v

32 passed, 0 failed.


Assessment — P2: Don't reclaim pending wipes solely by age (database/users.py:335)

This is a valid robustness observation but not a correctness bug in the current design. Walking through the concurrent-double-enqueue scenario:

  1. The reconciler's _claim_deletion_wipe_txn atomically transitions pending → retrying inside a Firestore transaction (lines 392-401). So when the reconciler re-claims a slow worker's aged-out pending marker, the record becomes retrying — it is not left as pending for a third claim.

  2. The wipe operations themselves (delete_user_data, purge_derived_user_data, vector deletes) are idempotent: deleting already-deleted Firestore subcollections, vector records, and GCS recordings is a no-op. A concurrent double-enqueue wastes work but does not corrupt data.

  3. The "duplicate failure overwrites successful completion" scenario: if worker A completes (→ completed) and worker B then fails (→ failed), the reconciler re-runs the wipe. Since the account is already wiped, this is a benign no-op that eventually settles to completed.

The concern would become a real bug if the wipe operations were non-idempotent or if the stale_after window were shorter than realistic wipe durations. The current stale_after=10min is conservative for the operations involved (Firestore collection deletes + vector DB batch deletes). Adding a heartbeat/claimed state (pending → running with periodic wipe_claimed_at updates) would reduce duplicate work, but it's an optimization, not a safety fix. I'd suggest tracking it as a follow-up enhancement rather than expanding this PR's scope.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ec8323ccb3

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Address review feedback (chatgpt-codex-connector P2): the reconciler
previously reclaimed 'pending' wipe markers solely by age, which meant a
slow but live wipe (queued behind other cleanup jobs) could be
duplicate-claimed after the short 10-min stale window, and a later
duplicate failure could overwrite a successful completion.

Introduce a 'running' state that background_wipe_user_data transitions
to at the start of execution. The reconciler now distinguishes:
- stale 'pending' (queued but never started → genuinely orphaned →
  reclaim after 10 min)
- 'running' (actively executing → only reclaim after 30 min to account
  for legitimately slow wipes that sit behind other jobs)

Added mark_user_deletion_wipe_running(), updated get_pending_deletion_wipes
and _claim_deletion_wipe_txn to handle 'running' with its own stale
window, and added 6 new tests covering the running-state behavior.
The running-state fix in the prior commit (b742b47) uses
mark_user_deletion_wipe_running() directly in the worker and guards
concurrent execution via _claim_deletion_wipe_txn(). The
_claim_running_wipe_txn/claim_running_wipe helpers were an unused
alternative approach — remove them.
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Review feedback addressed

Comment Status
#3484183349 — Don't reclaim pending wipes solely by age (P2, chatgpt-codex-connector) ✅ Fixed

Running state prevents duplicate wipe reclaim (#3484183349)

The core concern was that a slow but live wipe could be reclaimed as orphaned after the 10-minute stale_after window and re-enqueued concurrently, with a later duplicate failure overwriting a successful completion.

Fix: Introduced a running wipe_status so the reconciler can distinguish:

  • pending — queued in the executor backlog but not yet started. Safe to re-enqueue after the short stale_after (10 min).
  • running — worker started executing. Only recovered after a much longer running_stale_after (30 min), indicating a crashed/killed worker.

Changes:

  1. mark_user_deletion_wipe_running() — new function called at the top of background_wipe_user_data to transition pending → running.
  2. get_pending_deletion_wipes() — queries stale running records with a separate running_stale_after window (default 30 min), keeping fresh running records excluded.
  3. _claim_deletion_wipe_txn() — refuses fresh/moderately-recent running markers (worker is live); only claims running markers stale beyond running_stale_after.
  4. claim_deletion_wipe() — signature gains running_stale_after parameter.
  5. The running marker write is non-fatal: if it fails, the wipe still proceeds (logged as warning).

Verification

tests/services/users/test_account_deletion.py — 20 passed
tests/unit/test_claim_deletion_wipe_txn.py — 13 passed
33 passed in 0.13s

New tests added:

  • test_claim_txn_skips_fresh_running_marker — 12-min-old running marker NOT claimed (core fix)
  • test_claim_txn_claims_stale_running_marker — 45-min-old running marker IS claimed
  • test_claim_txn_skips_running_marker_near_stale_boundary — 29-min marker NOT claimed
  • test_get_pending_deletion_wipes_includes_stale_running — stale running recovered, fresh running excluded
  • test_background_wipe_continues_when_running_marker_persist_fails — non-fatal marker write

@Git-on-my-level

Copy link
Copy Markdown
Member Author

Fixed: Don't reclaim pending wipes solely by age

Addressed the P2 feedback from chatgpt-codex-connector about the reconciler reclaiming pending wipe markers solely by age.

What changed

Introduced a 'running' state that background_wipe_user_data transitions to at the start of execution. The reconciler now distinguishes:

  • Stale pending (queued but never started → genuinely orphaned → reclaim after 10 min stale_after)
  • running (actively executing → only reclaim after 30 min running_stale_after to account for legitimately slow wipes that sit behind other cleanup jobs)

This prevents a slow but live wipe from being duplicate-claimed after the short 10-min pending stale window, which was the core race condition: a later duplicate failure could overwrite a successful completion with failed and keep retrying an already-deleted account.

Files changed

  • database/users.py: Added mark_user_deletion_wipe_running(), updated get_pending_deletion_wipes() and _claim_deletion_wipe_txn() to handle 'running' with its own longer stale window (30 min default).
  • services/users/account_deletion.py: background_wipe_user_data now calls mark_user_deletion_wipe_running(uid) at the start of execution.

Verification

  • 33 tests pass (test_claim_deletion_wipe_txn.py + test_account_deletion.py), including 6 new tests:
    • test_claim_txn_skips_fresh_running_marker — 12 min running marker NOT claimed
    • test_claim_txn_claims_stale_running_marker — 45 min running marker IS claimed
    • test_claim_txn_skips_running_marker_near_stale_boundary — 29 min marker NOT claimed
    • test_get_pending_deletion_wipes_includes_stale_running — stale running recovered, fresh running excluded
    • test_background_wipe_continues_when_running_marker_persist_fails — wipe proceeds even if marker write fails
    • Updated test_background_wipe_user_data_preserves_order to verify running is first call
  • black --check --line-length 120 clean on all changed files

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7d78f6fd7b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread backend/database/users.py Resolved
Comment thread backend/tests/routers/test_users.py Resolved

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

2 issues found across 4 files (changes from recent commits).

Tip: Review your code locally with the cubic CLI to iterate faster.

Re-trigger cubic

… restore router

Address 3 review threads from chatgpt-codex-connector:

P1 — set_user_deletion_feedback() used a non-merge set() on
account_deletions/{uid}, which could erase a durable wipe marker
(pending/failed/retrying) on a retried delete request. Now uses
merge=True so existing wipe_status fields are preserved.

P2 — retrying claims were reclaimed using the short stale_after (10 min)
window. If the executor backlog was full, a queued retrying future could
be re-claimed before it started running. Now uses running_stale_after
(30 min) for both get_pending_deletion_wipes and _claim_deletion_wipe_txn.

P2 — tests/routers/test_users.py leaked the stub-loaded routers.users
module into sys.modules. Now pops routers.users and service modules after
collection, and restores in the module-scope fixture.
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Round 2: Fixed 3 review threads

P1 — Preserve wipe state when storing deletion feedback

database/users.py: set_user_deletion_feedback() used a non-merge set() on account_deletions/{uid}, which could erase a durable wipe marker (pending/failed/retrying) if a delete request was retried after a previous attempt already wrote a marker. Now uses merge=True so existing wipe_status fields are preserved.

P2 — Avoid reclaiming queued retrying wipes

database/users.py: retrying claims were reclaimed using the short stale_after (10 min) window. If all cleanup workers were occupied, a queued retrying future could be re-claimed before it started running, causing duplicate wipes to race. Now uses running_stale_after (30 min) for both get_pending_deletion_wipes and _claim_deletion_wipe_txn, matching the running state's behavior.

P2 — Restore the stub-loaded users router

tests/routers/test_users.py: The stub-loaded routers.users module was leaking into sys.modules after test collection. Now pops routers.users and its service modules (services.users, services.users.account_deletion) after collection, and restores them in the module-scope fixture.

Verification

  • 34 tests pass: test_claim_deletion_wipe_txn.py (14) + test_account_deletion.py (20), including 2 new tests:
    • test_claim_txn_skips_queued_retrying_claim — 15-min retrying claim NOT re-claimed
    • Updated test_claim_txn_reclaims_stale_retrying_claim — 45-min retrying claim IS re-claimed
  • black --check --line-length 120 clean on all changed files

@Git-on-my-level

Copy link
Copy Markdown
Member Author

Round 3: Fixed typo + note on retrying claim

  • Fixed typo in test docstring: "non-fial" → "non-fatal"
  • The P1 about retrying claims being reclaimed while queued was already fixed in commit 9e2079b70 — retrying claims now use running_stale_after (30 min) instead of stale_after (10 min), both in get_pending_deletion_wipes and _claim_deletion_wipe_txn.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a17947d7fc

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread backend/tests/routers/test_users.py Resolved

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

2 issues found across 4 files (changes from recent commits).

Tip: Review your code locally with the cubic CLI to iterate faster.

Re-trigger cubic

Comment thread backend/tests/routers/test_users.py Resolved
Comment thread backend/tests/routers/test_users.py Resolved
Addresses review feedback from Codex (P2) and Cubic (P1/P2):

test_users.py:
- Capture _prior_routers_users and service module priors BEFORE stubbed
  import runs, so teardown restores the real modules instead of the
  stub-loaded versions
- Add services.users.data_export to the cleanup pop loop (was missing)
- Clear parent package attributes (routers.users, services.users.*) so
  from-imports don't resolve to stub-loaded modules via attr lookup

test_claim_deletion_wipe_txn.py:
- Clear database.users attribute on the parent database package during
  teardown so from database import users doesn't resolve to the
  half-stubbed module via attribute lookup

All 17 tests across both files pass.
@Git-on-my-level

Copy link
Copy Markdown
Member Author

sys.modules cleanup — addressed all 4 review threads

All four unresolved threads flagged incomplete sys.modules / parent-package-attribute cleanup in the two stub-based test modules. Root cause in each case: the prior module entry was captured after the stubbed import had already populated sys.modules, so teardown restored the stub-loaded version instead of the real module, and parent package attributes (e.g. database.users, routers.users) retained references to stub-loaded modules.

Changes

backend/tests/routers/test_users.py (Threads 1, 3, 4):

  • _prior_routers_users and _prior_service_modules are now captured before the stubbed from routers import users import runs (was captured after → restored the mock-backed router).
  • Added services.users.data_export to the cleanup pop loop (Thread 3 / P1 — was missing alongside account_deletion).
  • Added services.users, services.users.account_deletion, services.users.data_export to the module-scoped teardown restore.
  • Clear parent package attributes (routers.users, services.users.*) after popping so from routers import users / from services.users import ... re-import the real modules rather than resolving via attribute lookup on already-imported package objects.

backend/tests/unit/test_claim_deletion_wipe_txn.py (Thread 2):

  • Teardown now clears the users attribute on the parent database package (delattr(database, 'users')) so from database import users doesn't resolve to the half-stubbed module via attribute lookup.

Verification

  • All 17 tests across both files pass:
    pytest tests/routers/test_users.py tests/unit/test_claim_deletion_wipe_txn.py -v
    → 17 passed in 0.29s
    
  • Both files compile cleanly (py_compile).
  • Pre-commit hook passed (no formatting changes needed).

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7edbf9b0c1

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

pytest collects later test modules before any module-scoped fixture
teardown runs, so restoring sys.modules in fixture teardown leaves
half-stubbed entries (database._client, database.redis_db, utils.subscription,
utils.other.endpoints) in sys.modules while later tests are imported.

Move all sys.modules restoration to module level, immediately after
capturing the needed references. This eliminates cross-module stub leakage:
running test_users.py + test_claim_deletion_wipe_txn.py +
test_rate_limiting.py together now passes all 70 tests (previously 9
test_rate_limiting tests failed due to leaked stubs).
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Re: "Restore stubs before collection continues" — fixed

Valid concern. Module-scoped fixture teardown runs after pytest has already collected (imported) later test modules, so the half-stubbed database._client, database.redis_db, utils.subscription, and utils.other.endpoints entries remained in sys.modules during collection of subsequent test files.

Fix

Moved all sys.modules restoration from fixture teardown to module level, immediately after capturing the needed references (users_db / users_router). The module-level variables hold direct references to the already-imported module objects, so tests continue to work with their MagicMock-backed helpers even after the sys.modules entries are restored.

This was applied to both stub-based test files:

  • test_claim_deletion_wipe_txn.py: removed the _restore_sys_modules fixture entirely; restore happens right after from database import users as users_db. Removed unused import pytest.
  • test_users.py: removed the _restore_endpoints_shim fixture; utils.other.endpoints restoration now happens at module level alongside the existing routers/services cleanup.

Verification

Running all three files together now passes with zero leakage:

pytest tests/routers/test_users.py tests/unit/test_claim_deletion_wipe_txn.py tests/unit/test_rate_limiting.py -v
→ 70 passed in 0.25s

Previously this combination had 9 failures in test_rate_limiting.py caused exactly by the leaked stubs this comment identified.

@Git-on-my-level
Git-on-my-level merged commit d7e8950 into main Jun 27, 2026
3 checks passed
@Git-on-my-level
Git-on-my-level deleted the codex/techdebt-user-data-services branch June 27, 2026 00:16
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.

2 participants