capgo icon indicating copy to clipboard operation
capgo copied to clipboard

fix(backend): clean stuck manifest backlog

Open riderx opened this issue 6 months ago • 6 comments

Summary (AI generated)

  • Harden deleted bundle cleanup so missing app_versions_meta no longer blocks manifest row cleanup.
  • Add a bounded delete_old_deleted_versions() migration so hard-delete cascades run in 500-version batches.
  • Add admin:cleanup-stuck-manifest-backlog to audit and clear old stuck manifest rows, then vacuum analyze public.manifest.
  • Add unit and pgTAP coverage for metadata-missing cleanup, counter resets, bounded hard delete, and manifest cascade.

Motivation (AI generated)

public.manifest can grow when old soft-deleted bundle cleanup is blocked or backlogged. The database should keep the same retention policy while providing a bounded operational path to remove old stuck rows safely.

Business Impact (AI generated)

This reduces production database storage pressure and keeps bundle cleanup predictable without changing customer-facing bundle retention behavior. It also gives operators an auditable script to clean existing backlog after deployment.

Test Plan (AI generated)

  • [x] bun lint:backend
  • [x] bunx eslint --no-ignore scripts/cleanup_stuck_manifest_backlog.ts
  • [x] bunx vitest run tests/on-version-update-cleanup.unit.test.ts
  • [x] PGSSLMODE=disable bunx supabase test db supabase/tests/00-supabase_test_helpers.sql supabase/tests/16_test_retention.sql --db-url postgresql://postgres:[email protected]:54562/postgres
  • [x] bun test:backend
  • [x] bun run admin:cleanup-stuck-manifest-backlog --help
  • [x] Dry-run script audit against local Supabase DB

Generated with AI

Summary by CodeRabbit

  • New Features

    • Added an admin CLI to audit and optionally perform bounded cleanup of stuck/old manifest backlog.
    • Added a DB migration introducing a safe, bounded hard-delete helper for old soft-deleted versions with tightened permissions.
  • Bug Fixes

    • Improved orphan-detection for manifest assets and changed metadata-update failures to be logged rather than aborting deletes.
    • Ensures manifest counters are reset when manifest rows are removed.
  • Tests

    • Expanded tests to cover bounded-batch deletion and manifest cleanup behavior.
  • Documentation

    • Clarified inline comment about file-read behavior and error handling.

Review Change Stack

riderx avatar May 13 '26 00:05 riderx

[!NOTE]

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • [ ] ▶️ Resume reviews
  • [ ] 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds a bounded PL/pgSQL hard-delete function for old soft-deleted app_versions, an admin Bun/TypeScript script to audit and iteratively call that function, trigger adjustments to avoid throwing on meta-update errors, and SQL/unit tests validating bounded batching and manifest cascade.

Changes

Manifest Backlog Cleanup System

Layer / File(s) Summary
Database cleanup function and tests
supabase/migrations/20260513003104_manifest_cleanup_health.sql, supabase/tests/16_test_retention.sql
delete_old_deleted_versions() hard-deletes up to 500 soft-deleted app_versions older than 3 months (skips versions with channels), sets ownership/permissions, and is covered by SQL tests that verify bounded-batch behavior and manifest cascade deletions.
Admin CLI cleanup script
package.json, scripts/cleanup_stuck_manifest_backlog.ts
Adds admin:cleanup-stuck-manifest-backlog npm script and a Bun/TypeScript admin script that resolves DB URL from flags/env, prints pre-cleanup audits (table size, vacuum stats, bucket counts), optionally runs iterative delete_old_deleted_versions() batches with configurable pause and early-stop on stalled progress, optionally VACUUMs public.manifest, and prints post-cleanup audits.
Trigger cleanup integration and tests
supabase/functions/_backend/triggers/on_version_update.ts, tests/on-version-update-cleanup.unit.test.ts, supabase/functions/_backend/files/files.ts
deleteIt/trigger logic now includes s3_path when checking manifest references; stats/meta updates run only when metadata exists and meta-update failures are logged (not thrown). Unit tests expand Supabase/Postgres mocks to simulate manifest row deletions, verify deleteObject calls for bundle paths even when meta is missing, and assert SQL counter reset/decrement calls. A comment in files.ts was clarified about avoiding DB/R2 checks on file reads.

Sequence Diagram(s)

sequenceDiagram
  participant Script as Admin Script
  participant DB as Postgres
  participant Fn as delete_old_deleted_versions
  participant Manifest as public.manifest
  Script->>DB: pre-cleanup audit queries (size, vacuum, bucket counts)
  Script->>Fn: CALL public.delete_old_deleted_versions()
  Fn->>DB: DELETE bounded rows -> cascade deletes Manifest rows
  DB-->>Script: remaining eligible count
  Script->>DB: optional VACUUM (ANALYZE) public.manifest
  Script->>DB: post-cleanup audit queries

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 I hop through rows both old and gray,
Bounded batches whisk the backlog away.
Manifests fall and counters mend,
Tests confirm the careful end.
✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 6.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically summarizes the main change: a new bounded cleanup mechanism for stuck manifest backlog rows in the database.
Description check ✅ Passed The PR description covers summary, motivation, business impact, and a detailed test plan with checkboxes, fully complying with the required template structure.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • [ ] Create PR with unit tests
  • [ ] Commit unit tests in branch codex/manifest-cleanup-health

Comment @coderabbitai help to get the list of available commands and usage tips.

coderabbitai[bot] avatar May 13 '26 00:05 coderabbitai[bot]

Merging this PR will not alter performance

✅ 43 untouched benchmarks
⏩ 2 skipped benchmarks[^skipped]


Comparing codex/manifest-cleanup-health (4a3669f) with main (728e86b)

Open in CodSpeed

[^skipped]: 2 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports.

codspeed[bot] avatar May 13 '26 01:05 codspeed[bot]

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

There is still an object-lifecycle gap here: admin:cleanup-stuck-manifest-backlog --apply hard-deletes old app_versions by calling public.delete_old_deleted_versions(), and that removes manifest rows by FK cascade without deleting the corresponding R2 manifest objects.

That is fine only if the soft-delete trigger has already removed every manifest object. But this PR is explicitly for a stuck/backlogged cleanup path, and deleteIt() can leave manifest rows behind when prior cleanup was blocked. If any of those rows still point at live R2 keys, the admin script removes the last DB reference to those keys and future runs cannot discover them for object cleanup. The script's audit shows counts by manifest row/version, but it never lists or deletes the manifest.s3_path objects before the cascade.

I would either make the backlog script collect candidate manifest.s3_path values and delete those R2 objects before/while deleting the DB rows, or clearly split DB-only cleanup from storage cleanup and keep enough retry state for failed object deletes. A useful regression would seed an old deleted version with a manifest row, run the cleanup helper, and assert the storage-delete path is invoked or the manifest row remains available for a later object-cleanup pass.

digzrow-coder avatar May 13 '26 17:05 digzrow-coder