Skip to content

fix: speed up migrations #1018

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open

fix: speed up migrations #1018

wants to merge 4 commits into from

Conversation

gfyrag
Copy link
Collaborator

@gfyrag gfyrag commented Jul 19, 2025

No description provided.

@gfyrag gfyrag requested a review from a team as a code owner July 19, 2025 13:27
Copy link

coderabbitai bot commented Jul 19, 2025

Walkthrough

This update modifies several SQL migration scripts to create permanent tables (moves_view and txs_view) instead of temporary ones, adjusts column types to retain their originals, and adds foreign key constraints to improve hash join performance during updates. The update and control flow logic remain unchanged, with improved cleanup of temporary tables before exiting loops. Additionally, one migration increases batch size and changes pagination from OFFSET/LIMIT to range-based filtering.

Changes

Files (grouped) Change Summary
internal/storage/bucket/migrations/19-transactions-fill-pcv/up.sql
27-fix-invalid-pcv/up.sql
28-fix-pcv-missing-asset/up.sql
Created permanent moves_view tables, retained original transactions_seq column types, added foreign key constraints, and improved cleanup by dropping the table before early returns and loop exits.
internal/storage/bucket/migrations/31-fix-transaction-updated-at/up.sql Created permanent txs_view table, added foreign key constraint, simplified update join condition, and improved loop exit cleanup.
internal/storage/bucket/migrations/34-fix-memento-format/up.sql Increased batch size from 1000 to 10000 and changed batch selection from OFFSET/LIMIT pagination to range-based filtering on seq.

Sequence Diagram(s)

sequenceDiagram
    participant MigrationScript
    participant Database

    MigrationScript->>Database: Create permanent table (moves_view/txs_view)
    MigrationScript->>Database: Add foreign key constraint to transactions(seq)
    loop For each batch
        MigrationScript->>Database: Perform update using optimized join
        alt No rows found
            MigrationScript->>Database: Drop permanent table
            MigrationScript->>MigrationScript: Exit loop
        end
    end
Loading

Possibly related PRs

  • fix: invalid pcv #831: Modifies the same migration script involving the moves_view table, focusing on transactions_seq usage, foreign key constraints, and batch update logic improvements.
  • fix: invalid post commit volumes format #829: Also updates 19-transactions-fill-pcv/up.sql but changes JSON structure of aggregated data in moves_view, addressing different aspects of the same migration script.

Suggested labels

build-images

Suggested reviewers

  • Dav-14
  • paul-nicolas

Poem

In the warren of SQL, tables stand tall,
No longer fleeting, they’re permanent for all.
With columns restored and constraints now in place,
Hash joins leap swiftly in their optimized race.
A hop, a skip, migrations anew—
The bunny says, “Well done, code crew!” 🐇


📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 804e2f5 and 02e4533.

📒 Files selected for processing (2)
  • internal/storage/bucket/migrations/31-fix-transaction-updated-at/up.sql (2 hunks)
  • internal/storage/bucket/migrations/34-fix-memento-format/up.sql (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • internal/storage/bucket/migrations/31-fix-transaction-updated-at/up.sql
  • internal/storage/bucket/migrations/34-fix-memento-format/up.sql
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: Cursor BugBot
  • GitHub Check: Tests
  • GitHub Check: Dirty
✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/optimize-migrations

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai auto-generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

♻️ Duplicate comments (2)
internal/storage/bucket/migrations/27-fix-invalid-pcv/up.sql (1)

10-31: Same optimisation comments as migration 28

All remarks about using UNLOGGED tables and avoiding redundant indexes/FKs from migration 28 apply here verbatim.

internal/storage/bucket/migrations/19-transactions-fill-pcv/up.sql (1)

10-31: Same optimisation comments as migration 28

The UNLOGGED table suggestion and index/FK duplication concern equally apply to this migration.

🧹 Nitpick comments (4)
internal/storage/bucket/migrations/28-fix-pcv-missing-asset/up.sql (2)

10-10: Consider using UNLOGGED to avoid WAL overhead

moves_view exists only for the duration of the migration and is later dropped. Declaring it UNLOGGED can cut write-ahead-log traffic and speed the migration with zero durability concerns.

- create table moves_view as
+ create unlogged table moves_view as

29-31: Redundant index creation – let the FK reuse it

create index moves_view_idx on moves_view(transactions_seq); is immediately followed by a foreign-key constraint on the same column. Postgres will either:

  1. Reuse the existing index, or
  2. Create an identical one if it can’t reuse it (version-dependent).

Either way, you end up maintaining two indexes or one unnecessary DDL. Dropping the explicit index avoids ambiguity:

- create index moves_view_idx on moves_view(transactions_seq);
-- speed up hash join when updating rows later
 alter table moves_view add foreign key(transactions_seq) references transactions(seq);
internal/storage/bucket/migrations/31-fix-transaction-updated-at/up.sql (2)

10-10: UNLOGGED table can speed bulk updates

txs_view is a scratch table dropped at the end. Marking it UNLOGGED avoids WAL and often halves runtime on large ledgers.

- create table txs_view as
+ create unlogged table txs_view as

18-19: Potential duplicate index from FK + explicit index

The FK on seq will (re)use or recreate an index identical to the one already present on transactions.seq. Unless you rely on txs_view(seq) for other purposes, consider omitting the FK altogether and just keep the plain index to avoid catalog bloat and validation time.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 460f186 and 53f756f.

📒 Files selected for processing (4)
  • internal/storage/bucket/migrations/19-transactions-fill-pcv/up.sql (2 hunks)
  • internal/storage/bucket/migrations/27-fix-invalid-pcv/up.sql (2 hunks)
  • internal/storage/bucket/migrations/28-fix-pcv-missing-asset/up.sql (2 hunks)
  • internal/storage/bucket/migrations/31-fix-transaction-updated-at/up.sql (2 hunks)
🧰 Additional context used
🧠 Learnings (4)
internal/storage/bucket/migrations/28-fix-pcv-missing-asset/up.sql (1)
Learnt from: gfyrag
PR: formancehq/ledger#935
File: internal/controller/system/state_tracker.go:0-0
Timestamp: 2025-05-20T13:48:07.455Z
Learning: In the Formance ledger codebase, sequence reset queries with `select setval` don't require COALESCE around max(id) even for brand new ledgers, as the system handles this case properly.
internal/storage/bucket/migrations/19-transactions-fill-pcv/up.sql (1)
Learnt from: gfyrag
PR: formancehq/ledger#935
File: internal/controller/system/state_tracker.go:0-0
Timestamp: 2025-05-20T13:48:07.455Z
Learning: In the Formance ledger codebase, sequence reset queries with `select setval` don't require COALESCE around max(id) even for brand new ledgers, as the system handles this case properly.
internal/storage/bucket/migrations/27-fix-invalid-pcv/up.sql (1)
Learnt from: gfyrag
PR: formancehq/ledger#935
File: internal/controller/system/state_tracker.go:0-0
Timestamp: 2025-05-20T13:48:07.455Z
Learning: In the Formance ledger codebase, sequence reset queries with `select setval` don't require COALESCE around max(id) even for brand new ledgers, as the system handles this case properly.
internal/storage/bucket/migrations/31-fix-transaction-updated-at/up.sql (3)
Learnt from: gfyrag
PR: formancehq/ledger#935
File: internal/controller/system/state_tracker.go:0-0
Timestamp: 2025-05-20T13:48:07.455Z
Learning: In the Formance ledger codebase, sequence reset queries with `select setval` don't require COALESCE around max(id) even for brand new ledgers, as the system handles this case properly.
Learnt from: gfyrag
PR: formancehq/ledger#935
File: internal/controller/system/state_tracker.go:50-55
Timestamp: 2025-05-20T13:07:54.504Z
Learning: In the ledger codebase's `handleState` method, when updating ledger state from `StateInitializing` to `StateInUse`, it's intentional to proceed silently when `rowsAffected == 0`. This indicates another parallel transaction has already updated the ledger state and configured the sequences, so no error needs to be returned and no sequence updating is required.
Learnt from: gfyrag
PR: formancehq/ledger#892
File: internal/controller/ledger/controller_default.go:196-196
Timestamp: 2025-04-29T11:24:28.923Z
Learning: In the ledger Import function, it's critical to maintain proper log ID tracking by updating lastLogID with the current log.ID after each processed log, rather than setting it to nil. This ensures the system can properly validate the ordering of logs and prevent duplicate or out-of-order processing, which is essential for maintaining data integrity in the ledger.
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Cursor BugBot
  • GitHub Check: Tests
🔇 Additional comments (2)
internal/storage/bucket/migrations/28-fix-pcv-missing-asset/up.sql (1)

13-13: Double-check type compatibility after removing the numeric cast

transactions_seq is now taken as-is from moves.transactions_seq. Make sure this column’s type (likely bigint) exactly matches transactions.seq; otherwise the FK added below will fail.

internal/storage/bucket/migrations/31-fix-transaction-updated-at/up.sql (1)

34-34: Ledger-scoped uniqueness assumption – please confirm

The previous join filtered on both seq and ledger. Dropping the ledger predicate assumes seq is unique within the current schema. If multiple ledgers can share a schema, this may update rows across ledgers inadvertently.

cursor[bot]

This comment was marked as outdated.

Copy link

codecov bot commented Jul 19, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 80.78%. Comparing base (5221873) to head (02e4533).
Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1018      +/-   ##
==========================================
+ Coverage   80.51%   80.78%   +0.26%     
==========================================
  Files         186      186              
  Lines       10199    10199              
==========================================
+ Hits         8212     8239      +27     
+ Misses       1565     1544      -21     
+ Partials      422      416       -6     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🔭 Outside diff range comments (1)
internal/storage/bucket/migrations/34-fix-memento-format/up.sql (1)

90-90: COMMIT inside a DO block is invalid in PostgreSQL

DO $$ … $$; executes as a single anonymous code block inside its own transaction. Issuing COMMIT (or ROLLBACK) inside the block raises
ERROR: cannot commit while a subtransaction is active (PG ≥9.4).

Unless you are using a non-standard pl/pgsql variant that permits commits, this line should be removed. If chunked commits are required, convert the code into an external script that opens/commits transactions between calls to a stored procedure, rather than from inside the procedure itself.

🧹 Nitpick comments (2)
internal/storage/bucket/migrations/34-fix-memento-format/up.sql (2)

4-4: Large default batch size may pressure memory / WAL

Jumping from 1 000 to 10 000 rows per batch improves I/O efficiency but can spike memory usage and enlarge single-transaction WAL records, especially given the heavy json_build_object work per row. Consider making _batch_size configurable (e.g., via SET or a passed parameter) so operators can tune it for their environment.


93-93: DROP TABLE IF EXISTS txs_view; appears unrelated

txs_view is never created in this migration. While harmless, keeping unrelated cleanup logic obscures intent and can confuse readers. Recommend removing the line unless the view is guaranteed to exist from prior steps.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 53f756f and 804e2f5.

📒 Files selected for processing (5)
  • internal/storage/bucket/migrations/19-transactions-fill-pcv/up.sql (3 hunks)
  • internal/storage/bucket/migrations/27-fix-invalid-pcv/up.sql (3 hunks)
  • internal/storage/bucket/migrations/28-fix-pcv-missing-asset/up.sql (3 hunks)
  • internal/storage/bucket/migrations/31-fix-transaction-updated-at/up.sql (2 hunks)
  • internal/storage/bucket/migrations/34-fix-memento-format/up.sql (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • internal/storage/bucket/migrations/19-transactions-fill-pcv/up.sql
  • internal/storage/bucket/migrations/31-fix-transaction-updated-at/up.sql
  • internal/storage/bucket/migrations/27-fix-invalid-pcv/up.sql
  • internal/storage/bucket/migrations/28-fix-pcv-missing-asset/up.sql
🧰 Additional context used
🧠 Learnings (1)
internal/storage/bucket/migrations/34-fix-memento-format/up.sql (1)
Learnt from: gfyrag
PR: formancehq/ledger#935
File: internal/controller/system/state_tracker.go:0-0
Timestamp: 2025-05-20T13:48:07.455Z
Learning: In the Formance ledger codebase, sequence reset queries with `select setval` don't require COALESCE around max(id) even for brand new ledgers, as the system handles this case properly.
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: Dirty
  • GitHub Check: Tests
  • GitHub Check: Cursor BugBot

Comment on lines 15 to 20
with data as (
select *
from logs
where seq >= _offset and seq < _offset + _batch_size
order by seq
offset _offset
limit _batch_size
)
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Range-based pagination risks skipping rows with sparse seq values

Switching from OFFSET/LIMIT to

where seq >= _offset and seq < _offset + _batch_size

assumes that no gap in seq exceeds _batch_size.
If a gap larger than 10 000 exists (e.g., deleted rows or a sequence reset), the data CTE will return zero rows even though unprocessed rows still exist above the gap. Because exit when not found; triggers on the empty UPDATE, the loop terminates prematurely and leaves those rows un-migrated.

A safer pattern is to drive the loop by the last processed seq, not by a synthetic offset:

-        _offset integer := 0;
+        _last_seq integer := -1;

...
-            with data as (
-                select *
-                from logs
-                where seq >= _offset and seq < _offset + _batch_size
-                order by seq
-            )
+            with data as (
+                select *
+                from logs
+                where seq > _last_seq
+                order by seq
+                limit _batch_size
+            )
...
-            exit when not found;
-
-            _offset = _offset + _batch_size;
+            exit when not found;
+
+            -- advance to the highest seq we just touched
+            _last_seq = (select max(seq) from data);

This iterates until all rows are handled, independent of sparsity.

🤖 Prompt for AI Agents
In internal/storage/bucket/migrations/34-fix-memento-format/up.sql around lines
15 to 20, the current pagination uses a range condition on seq that assumes no
gaps larger than _batch_size, which can cause skipping rows if large gaps exist.
To fix this, refactor the loop to track the last processed seq value and use it
to fetch the next batch with a condition like seq > last_processed_seq ORDER BY
seq LIMIT _batch_size, ensuring all rows are processed regardless of gaps.

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