Skip to content

fix: speed up migration 19 #1017

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

Merged
merged 4 commits into from
Jul 19, 2025
Merged

Conversation

gfyrag
Copy link
Collaborator

@gfyrag gfyrag commented Jul 18, 2025

No description provided.

@gfyrag gfyrag requested a review from a team as a code owner July 18, 2025 21:29
Copy link

coderabbitai bot commented Jul 18, 2025

Walkthrough

The migration scripts were updated to create permanent tables (moves_view or txs_view) instead of temporary ones, revert the transactions_seq column type from numeric to its original type, add foreign key constraints referencing transactions(seq) to optimize hash join performance, and improve control flow by explicitly dropping these tables before early exits in batch update loops. Additionally, one script changed batch processing from offset-based pagination to range-based selection.

Changes

File(s) Change Summary
internal/storage/bucket/migrations/19-transactions-fill-pcv/up.sql Created permanent moves_view table, reverted transactions_seq type from numeric, added index and foreign key constraint, improved cleanup and loop exit control flow
internal/storage/bucket/migrations/27-fix-invalid-pcv/up.sql Same as above: permanent moves_view table, transactions_seq type reverted, foreign key constraint added, enhanced cleanup and exit logic
internal/storage/bucket/migrations/28-fix-pcv-missing-asset/up.sql Same as above: permanent moves_view table, transactions_seq type reverted, foreign key constraint added, explicit cleanup before exit
internal/storage/bucket/migrations/31-fix-transaction-updated-at/up.sql Created permanent txs_view table, added foreign key constraint, simplified update join condition, explicit table drop before loop exit
internal/storage/bucket/migrations/34-fix-memento-format/up.sql Increased batch size from 1000 to 10000; replaced offset-based pagination with range-based selection on seq column for batch processing

Possibly related PRs

  • fix: invalid pcv #831: Modifies the same migration scripts to change moves_view from temporary to permanent and adds foreign key constraints, closely related at the code level.
  • fix: memento format #926: Updates batch processing logic and control flow in 34-fix-memento-format/up.sql, sharing changes to batch update approach.
  • fix: invalid post commit volumes format #829: Modifies the same migration script 19-transactions-fill-pcv/up.sql but focuses on JSON aggregation changes, different aspect of the same migration.

Suggested reviewers

  • Dav-14
  • paul-nicolas

Poem

A table once fleeting, now here to stay,
With columns aligned in a permanent way.
An index for speed, a constraint for the link,
Transactions and moves, now closer in sync.
🐇 With hops of migration, the schema’s anew—
All thanks to the work of the diligent 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 72b661a and f919d69.

📒 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: GoReleaser
  • GitHub Check: Cursor BugBot
  • GitHub Check: Tests
✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch hotfix/v2.2/speedup-migration-19

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.

cursor[bot]

This comment was marked as outdated.

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

🔭 Outside diff range comments (1)
internal/storage/bucket/migrations/19-transactions-fill-pcv/up.sql (1)

56-58: COMMIT inside a DO $$ … $$ block is illegal – the migration will fail at runtime

COMMIT/ROLLBACK are only allowed in top-level scripts and CREATE PROCEDURE bodies (PostgreSQL ≥ 11).
A DO block executes as an anonymous function and cannot manage transactions. When this script runs, PostgreSQL will raise ERROR: cannot commit while a subtransaction is active, aborting the whole migration.

Suggested fix – simplest: keep everything in one transaction and just drop the commit;:

-            perform pg_notify('migrations-{{ .Schema }}', 'continue: ' || _batch_size);
-
-            commit;
+            perform pg_notify('migrations-{{ .Schema }}', 'continue: ' || _batch_size);

If you really need batch commits, wrap the logic in a CREATE PROCEDURE + CALL instead of a DO block, or split the migration into multiple statements executed from psql/goose outside an explicit transaction.

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

30-31: Foreign-key adds validation overhead but brings no join-time benefit

The FK from moves_view.transactions_seqtransactions(seq):

  1. Forces an immediate full-table validation scan (could be large) and adds triggers on moves_view, yet
  2. Provides zero planning benefit for the upcoming UPDATE … JOIN – the optimiser only needs the b-tree you already created (moves_view_idx).

Since moves_view is dropped a few lines later, the FK’s cost outweighs any integrity value.

Consider dropping the FK altogether:

--- speed up hash join when updating rows later
-alter table moves_view add foreign key(transactions_seq) references transactions(seq);

If you want extra safety without the upfront cost, add the constraint NOT VALID then VALIDATE CONSTRAINT after the update completes.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 05e590c and 50a025b.

📒 Files selected for processing (1)
  • internal/storage/bucket/migrations/19-transactions-fill-pcv/up.sql (2 hunks)
🧰 Additional context used
🧠 Learnings (1)
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.
⏰ 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

cursor[bot]

This comment was marked as outdated.

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: 2

♻️ Duplicate comments (2)
internal/storage/bucket/migrations/28-fix-pcv-missing-asset/up.sql (2)

10-27: Same optimisation as migration 27 – make moves_view UNLOGGED

The reasoning and benefits are identical to those described for migration 27.


30-31: Defer FK validation to avoid full-table scans

See detailed rationale in migration 27 review.

🧹 Nitpick comments (2)
internal/storage/bucket/migrations/27-fix-invalid-pcv/up.sql (1)

10-27: Consider making moves_view UNLOGGED for faster bulk processing

CREATE TABLE moves_view AS … materialises ~1 K rows per batch into a regular, WAL-logged table.
Because the table is dropped at the end of the block and never survives the migration, logging its changes is wasted I/O.

- create table moves_view as
+ create unlogged table moves_view as

Using UNLOGGED speeds up the migration and still preserves crash-safety for the main data because the source tables are fully logged.
(If logical-replication support is required, keep it regular.)

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

10-13: Copying all columns is unnecessary and bloats the working set

txs_view is only used as a driver table for seq. Copying the entire transactions row (SELECT *) doubles storage and I/O.

-create table txs_view as
-select *
-from transactions
-where updated_at is null;
+create unlogged table txs_view as
+select seq
+from transactions
+where updated_at is null;

Lean materialisation speeds up both the CREATE TABLE and the subsequent JOIN.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 50a025b and 17ffbef.

📒 Files selected for processing (3)
  • 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)
📓 Common learnings
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: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#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#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.
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/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.
⏰ 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: Tests
  • GitHub Check: Dirty
  • GitHub Check: Cursor BugBot

@gfyrag gfyrag force-pushed the hotfix/v2.2/speedup-migration-19 branch from 17ffbef to fa628d0 Compare July 19, 2025 13:27
cursor[bot]

This comment was marked as outdated.

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-91: COMMIT inside a DO $$ … $$ block will raise cannot COMMIT inside a function
DO executes in a single implicit transaction; explicit COMMIT is prohibited (unless this is a procedure, which it isn’t). This statement will abort the migration at runtime.
Drop the commit; or convert the block into a proper CREATE PROCEDURE … LANGUAGE plpgsql and CALL it.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between fa628d0 and 72b661a.

📒 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/31-fix-transaction-updated-at/up.sql
  • internal/storage/bucket/migrations/28-fix-pcv-missing-asset/up.sql
  • internal/storage/bucket/migrations/19-transactions-fill-pcv/up.sql
  • internal/storage/bucket/migrations/27-fix-invalid-pcv/up.sql
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
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/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). (2)
  • GitHub Check: Cursor BugBot
  • GitHub Check: Tests
🔇 Additional comments (1)
internal/storage/bucket/migrations/34-fix-memento-format/up.sql (1)

4-4: 10 k batch-size is fine, but confirm RAM/lock impact on large ledgers
Jumping from 1 000 to 10 000 multiplies in-memory row materialisation and lock duration by ×10. On busy instances this can noticeably increase lock contention and shared-buffers churn. Please benchmark on a production-sized dataset to make sure the gain outweighs the extra pressure.

@gfyrag gfyrag merged commit e8dca16 into release/v2.2 Jul 19, 2025
9 checks passed
@gfyrag gfyrag deleted the hotfix/v2.2/speedup-migration-19 branch July 19, 2025 18:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants