Skip to content

chore: clean up gathering invoice detailed lines - #3799

Merged
turip merged 2 commits into
mainfrom
chore/migrate-detailed-lines-pt2
Jul 16, 2026
Merged

turip merged 2 commits into
mainfrom
chore/migrate-detailed-lines-pt2

Conversation

@turip

@turip turip commented Jan 21, 2026 •

Copy link
Copy Markdown
Member

Overview

Remove invalid detailed rows attached to gathering invoice lines before the remaining standard invoices are migrated to billing schema level 2.

The code before the billing refactor in Jan 2026 have sometimes persisted detailed lines, for gathering invoices which is an invalid state.

This patch cleans it up as preparation for invoice schema 2 migration.

Changes

  • Find legacy and schema-level-2 detailed rows through the full invoice -> gathering line -> detailed line hierarchy.
  • Back up every row selected for deletion in om_migration_backup_20260716150455_gathering_details, including its source table, namespace, ID, and full JSON representation.
  • Delete discounts, detailed lines, and their line configs from leaf to parent.
  • Fail before deletion if an unexpected dependent row would be cascade-deleted or if a selected legacy detailed line is not a leaf.
  • Create only the helper indexes required by the cleanup and drop them before the transaction commits.
  • Exclude persistent migration backup tables from Atlas schema-drift checks.

The cleanup does not acquire billing customer locks because these invalid gathering details are not loaded or mutated by billing.

The migration is intentionally irreversible because the removed legacy data cannot be safely restored automatically. The persistent backup table remains available for manual recovery.

Validation

  • atlas migrate --env local lint --latest 2
  • atlas migrate --env local validate
  • atlas migrate --env local diff migrate-check
  • git diff --check

Summary by CodeRabbit

  • Data Maintenance

    • Added a controlled cleanup for obsolete gathering-related invoice details and configurations.
    • Preserves affected records in a backup table before removal.
    • Added safeguards to prevent unexpected cascading deletions and ensure only eligible records are removed.
  • Performance

    • Added supporting database indexes to improve cleanup and billing-detail lookups.
  • Migration Safety

    • Migration validation now excludes temporary backup tables.
    • Rollback documentation notes that deleted detail rows cannot be automatically restored.

Greptile Summary

This PR removes invalid detailed rows from gathering invoices before the remaining schema-level-2 migration. The main changes are:

  • Backs up selected rows with their source table and full JSON data.
  • Deletes discounts, detailed lines, and line configs from leaf to parent.
  • Adds guards against unexpected cascades and non-leaf deletions.
  • Creates and removes temporary indexes for the cleanup.
  • Excludes persistent migration backup tables from Atlas drift checks.

Confidence Score: 5/5

No additional blocking issue qualifies for this follow-up review.

  • No new incomplete or unsafe fix remains to report within the allowed follow-up scope.

Important Files Changed

Filename Overview
tools/migrate/migrations/20260716150455_cleanup_gathering_invoice_details.up.sql Backs up and deletes invalid gathering-invoice details with checks for dependent rows and non-leaf lines.
tools/migrate/migrations/20260716150455_cleanup_gathering_invoice_details.down.sql Documents that the data cleanup cannot be reversed automatically.
tools/migrate/migrations/20260716150454_create_gathering_detail_cleanup_indexes.up.sql Creates temporary indexes for the cleanup queries.
tools/migrate/migrations/20260716150456_drop_gathering_detail_cleanup_indexes.up.sql Removes the temporary cleanup indexes.
atlas.hcl Excludes persistent migration backup tables from schema-drift checks.

Reviews (5): Last reviewed commit: "fix: make gathering detail cleanup rerun..." | Re-trigger Greptile

Context used:

  • Context used - CLAUDE.md (source)
  • Context used - AGENTS.md (source)

@coderabbitai

coderabbitai Bot commented Jan 21, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The PR adds a transactional migration that backs up and removes gathering invoice details with dependency validation. It adds supporting indexes, excludes migration backup tables from Atlas checks, and documents the non-restorable rollback.

Changes

Gathering invoice cleanup

Layer / File(s) Summary
Cleanup index lifecycle
tools/migrate/migrations/20260716150454_create_gathering_detail_cleanup_indexes.*.sql, tools/migrate/migrations/20260716150456_drop_gathering_detail_cleanup_indexes.*.sql
Creates lookup indexes for cleanup queries and defines their rollback and removal operations.
Backup and capture invoice records
tools/migrate/migrations/20260716150455_cleanup_gathering_invoice_details.up.sql
Starts a transaction, creates a JSONB backup table, and captures gathering invoice, discount, configuration, and standard detail records.
Validated deletion and cleanup
tools/migrate/migrations/20260716150455_cleanup_gathering_invoice_details.up.sql
Checks prohibited cascades and leaf-line constraints, deletes selected records in order, and commits the transaction.
Migration exclusions and rollback handling
atlas.hcl, tools/migrate/migrations/20260716150455_cleanup_gathering_invoice_details.down.sql
Excludes migration backup tables from Atlas configuration and documents that deleted rows cannot be automatically restored.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Migration
  participant BillingTables
  participant BackupTable
  Migration->>BillingTables: select gathering invoice detail rows
  BillingTables-->>Migration: matching rows
  Migration->>BackupTable: store source rows as JSONB
  Migration->>BillingTables: validate delete dependencies
  BillingTables-->>Migration: dependency results
  Migration->>BillingTables: delete selected details, lines, and configs
  Migration->>Migration: commit transaction
Loading

Suggested labels: release-note/misc

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main change: cleaning up gathering invoice detailed lines.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch chore/migrate-detailed-lines-pt2

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@turip
turip changed the base branch from main to chore/migrate-detailed-lines-pt1 January 21, 2026 18:10
@turip
turip force-pushed the chore/migrate-detailed-lines-pt2 branch from 342754d to e42f796 Compare January 21, 2026 18:40
@turip turip added the release-note/misc Miscellaneous changes label Jan 21, 2026
Base automatically changed from chore/migrate-detailed-lines-pt1 to main January 22, 2026 14:07
@turip turip added the keep-open Exempt from stale processing; requires a concrete maintainer reason label Jul 13, 2026
@turip
turip force-pushed the chore/migrate-detailed-lines-pt2 branch from e42f796 to 69533c6 Compare July 16, 2026 12:33
@turip
turip force-pushed the chore/migrate-detailed-lines-pt2 branch from 6869774 to 73ed672 Compare July 16, 2026 15:07
@turip turip changed the title Chore/migrate detailed lines pt2 chore: clean up gathering invoice detailed lines Jul 16, 2026
@turip
turip marked this pull request as ready for review July 16, 2026 15:09
@turip
turip requested a review from a team as a code owner July 16, 2026 15:09
@turip turip added release-note/bug-fix Release note: Bug Fixes and removed release-note/misc Miscellaneous changes labels Jul 16, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@tools/migrate/migrations/20260716150455_cleanup_gathering_invoice_details.up.sql`:
- Around line 1-16: The cleanup migration currently creates temporary helper
indexes inside its transaction, unnecessarily holding write-blocking locks.
Remove the helper index creation and corresponding drops from this migration,
create and drop them in separate migrations using CREATE/DROP INDEX
CONCURRENTLY, and leave this file containing only the transactional cleanup.
- Around line 26-305: Materialize and lock the gathering-invoice deletion cohort
before the backup statements, using a temporary or equivalent cohort keyed by
invoice-line identity and namespace. Update every backup INSERT, cascade
validation DO block, and DELETE in this migration to join that single cohort
rather than independently re-scanning live invoice and line tables, preserving
the existing status/type predicates and ensuring the cohort is locked for the
migration’s full operation.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: e065455e-b887-4d32-99ca-03675459dd36

📥 Commits

Reviewing files that changed from the base of the PR and between 601784b and 73ed672.

⛔ Files ignored due to path filters (1)
  • tools/migrate/migrations/atlas.sum is excluded by !**/*.sum, !**/*.sum
📒 Files selected for processing (3)
  • atlas.hcl
  • tools/migrate/migrations/20260716150455_cleanup_gathering_invoice_details.down.sql
  • tools/migrate/migrations/20260716150455_cleanup_gathering_invoice_details.up.sql

@turip
turip force-pushed the chore/migrate-detailed-lines-pt2 branch from 73ed672 to c886c35 Compare July 16, 2026 15:32
@turip
turip enabled auto-merge (squash) July 16, 2026 15:33

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@tools/migrate/migrations/20260716150454_create_gathering_detail_cleanup_indexes.up.sql`:
- Around line 1-14: Update all four migration files to use concurrent index
operations: create indexes concurrently in
tools/migrate/migrations/20260716150454_create_gathering_detail_cleanup_indexes.up.sql
and
tools/migrate/migrations/20260716150456_drop_gathering_detail_cleanup_indexes.down.sql,
and use separate DROP INDEX CONCURRENTLY statements in
tools/migrate/migrations/20260716150454_create_gathering_detail_cleanup_indexes.down.sql
and
tools/migrate/migrations/20260716150456_drop_gathering_detail_cleanup_indexes.up.sql.
Mark these migrations for execution outside a transaction via the migration
runner’s transaction-mode directive, then regenerate them through Atlas and
verify the generated statements.

In
`@tools/migrate/migrations/20260716150455_cleanup_gathering_invoice_details.up.sql`:
- Around line 69-87: The config backup inserts must emit each (source_table,
namespace, id) only once. Update both config backup queries, including the
INSERT selecting from billing_invoice_flat_fee_line_configs, to deduplicate rows
using DISTINCT, DISTINCT ON, or an equivalent grouping while preserving the
existing filtering and selected backup data.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 964c5c6b-d5cf-4110-8930-58683904b88a

📥 Commits

Reviewing files that changed from the base of the PR and between 73ed672 and c886c35.

⛔ Files ignored due to path filters (1)
  • tools/migrate/migrations/atlas.sum is excluded by !**/*.sum, !**/*.sum
📒 Files selected for processing (7)
  • atlas.hcl
  • tools/migrate/migrations/20260716150454_create_gathering_detail_cleanup_indexes.down.sql
  • tools/migrate/migrations/20260716150454_create_gathering_detail_cleanup_indexes.up.sql
  • tools/migrate/migrations/20260716150455_cleanup_gathering_invoice_details.down.sql
  • tools/migrate/migrations/20260716150455_cleanup_gathering_invoice_details.up.sql
  • tools/migrate/migrations/20260716150456_drop_gathering_detail_cleanup_indexes.down.sql
  • tools/migrate/migrations/20260716150456_drop_gathering_detail_cleanup_indexes.up.sql
🚧 Files skipped from review as they are similar to previous changes (2)
  • tools/migrate/migrations/20260716150455_cleanup_gathering_invoice_details.down.sql
  • atlas.hcl

@turip
turip merged commit 8123cc6 into main Jul 16, 2026
25 checks passed
@turip
turip deleted the chore/migrate-detailed-lines-pt2 branch July 16, 2026 15:39
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

keep-open Exempt from stale processing; requires a concrete maintainer reason release-note/bug-fix Release note: Bug Fixes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants