Skip to content
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

Fix SQL Upgrade #471

Merged
merged 1 commit into from
Feb 10, 2025
Merged

Fix SQL Upgrade #471

merged 1 commit into from
Feb 10, 2025

Conversation

mkysel
Copy link
Collaborator

@mkysel mkysel commented Feb 10, 2025

The node does come up.

But I am not sure whether the code can handle a NULL column value.

Handing this partial solution over to @fbac .

Summary by CodeRabbit

  • New Features

    • Introduced additional configuration settings for blockchain interactions, enabling greater flexibility during runtime.
  • Chores

    • Updated the database schema to refine how blockchain data is managed, ensuring consistency while preserving existing functionality.

@mkysel mkysel requested a review from a team as a code owner February 10, 2025 16:43
Copy link

coderabbitai bot commented Feb 10, 2025

Walkthrough

This pull request introduces three new environment variable exports in the dev/run script to configure specific Ethereum contract addresses. In addition, it updates SQL migration files affecting the latest_block table: one migration removes the existing block_hash column, while another migration adds a block_hash BYTEA column—with its down migration ensuring the column is dropped if present. These changes adjust both the deployment configuration and the database schema.

Changes

File(s) Change Summary
dev/run Added three environment variable exports: XMTPD_CONTRACTS_NODES_ADDRESS, XMTPD_CONTRACTS_IDENTITY_UPDATES_ADDRESS, and XMTPD_CONTRACTS_MESSAGES_ADDRESS with specified Ethereum addresses.
pkg/migrations/00003_add-latest-block.up.sql Removed the block_hash BYTEA NOT NULL column from the latest_block table schema.
pkg/migrations/00004_add_blockchain_columns.up.sql, pkg/migrations/00004_add_blockchain_columns.down.sql Up migration adds a block_hash BYTEA column to the latest_block table; down migration includes a command to drop the block_hash column if it exists.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant S as dev/run Script
    participant A as Go Application
    
    U->>S: Execute dev/run script
    S->>S: Export XMTPD_CONTRACTS_NODES_ADDRESS
    S->>S: Export XMTPD_CONTRACTS_IDENTITY_UPDATES_ADDRESS
    S->>S: Export XMTPD_CONTRACTS_MESSAGES_ADDRESS
    S->>A: Run "go run" command
    A-->>U: Application started
Loading
sequenceDiagram
    participant MR as Migration Runner
    participant M03 as Migration 00003
    participant M04 as Migration 00004
    participant DB as Database

    MR->>M03: Apply migration (remove block_hash)
    M03->>DB: Remove block_hash column from latest_block
    MR->>M04: Apply migration up (add block_hash)
    M04->>DB: Add block_hash column to latest_block
    Note right of MR: For rollback:
    MR->>M04: Apply migration down (drop block_hash)
    M04->>DB: Execute ALTER TABLE DROP COLUMN IF EXISTS block_hash
Loading

Possibly related PRs


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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. (Beta)
  • @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.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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

🧹 Nitpick comments (4)
dev/run (1)

13-15: Document the purpose of contract addresses.

These appear to be development/test contract addresses. Consider adding comments to document:

  • The purpose of each contract
  • Whether these are test-only addresses
  • Any environment-specific variations (dev/staging/prod)
pkg/migrations/00004_add_blockchain_columns.down.sql (1)

1-8: Consider wrapping migrations in transactions.

While the migration follows proper order (index → table → column), consider wrapping it in a transaction to ensure atomicity.

+BEGIN;
 -- Drop index first
 DROP INDEX IF EXISTS idx_blockchain_messages_canonical;
 
 -- Then drop the table
 DROP TABLE IF EXISTS blockchain_messages;
 
 -- Drop newly added column
 ALTER TABLE latest_block DROP COLUMN IF EXISTS block_hash;
+COMMIT;
pkg/migrations/00004_add_blockchain_columns.up.sql (2)

1-11: Consider wrapping migrations in transactions.

Similar to the down migration, consider wrapping in a transaction for atomicity.

+BEGIN;
 CREATE TABLE blockchain_messages(
   block_number BIGINT NOT NULL,
   block_hash BYTEA NOT NULL,
   originator_node_id INT NOT NULL,
   originator_sequence_id BIGINT NOT NULL,
   is_canonical BOOLEAN NOT NULL DEFAULT TRUE,
   PRIMARY KEY (block_number, block_hash, originator_node_id, originator_sequence_id),
   FOREIGN KEY (originator_node_id, originator_sequence_id) REFERENCES gateway_envelopes(originator_node_id, originator_sequence_id)
 );
 CREATE INDEX idx_blockchain_messages_block_canonical ON blockchain_messages(block_number, is_canonical);
+COMMIT;

13-13: Clarify NULL handling strategy for block_hash.

The design choice to make block_hash nullable in latest_block but NOT NULL in blockchain_messages needs clarification:

  1. What scenarios lead to NULL block_hash in latest_block?
  2. How does the application handle the disparity between nullable and NOT NULL block_hash?
  3. Should we add a CHECK constraint to ensure data consistency with blockchain_messages?

This aligns with the PR objective's concern about NULL column handling.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8e4dada and efe38ea.

📒 Files selected for processing (4)
  • dev/run (1 hunks)
  • pkg/migrations/00003_add-latest-block.up.sql (1 hunks)
  • pkg/migrations/00004_add_blockchain_columns.down.sql (1 hunks)
  • pkg/migrations/00004_add_blockchain_columns.up.sql (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Test (Node)

Comment on lines 1 to 4
CREATE TABLE latest_block(
contract_address TEXT NOT NULL PRIMARY KEY,
block_number BIGINT NOT NULL,
block_hash BYTEA NOT NULL
block_number BIGINT NOT NULL
);
Copy link

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Verify data migration strategy for block_hash.

The removal of the NOT NULL block_hash column followed by its reintroduction as nullable in migration 00004 requires careful consideration:

  1. How is existing data handled during the transition?
  2. What is the strategy for handling NULL block_hash values in the application code?

Run this script to check for existing data handling:


🏁 Script executed:

#!/bin/bash
# Search for block_hash handling in the codebase
rg -A 5 "block_hash" --type go

Length of output: 2054


Action Required: Review and Adjust Nullable Block Hash Handling in Latest Block Updates

The migration sequence appears to rely on a two-step change:

  • Migration 00003 creates the latest_block table without a block_hash column.
  • Migration 00004 subsequently adds block_hash as a nullable column.

The SQL queries in pkg/db/queries/queries.sql.go show that the application inserts and updates records in latest_block using a statement that includes block_hash:

  • The INSERT ... ON CONFLICT DO UPDATE clause updates both block_number and block_hash and includes the condition
    WHERE $2 > latest_block.block_number AND $3 != latest_block.block_hash.

Because SQL’s standard inequality operator does not handle NULL well (e.g., both NULL != NULL and value != NULL evaluate to unknown), this raises two concerns:

  • Data Transition: How will existing rows migrated without a block_hash value (i.e. implicitly NULL) get updated when a valid block hash becomes available? The current condition may block the update if a new non‑NULL value is compared against a NULL stored value.
  • Application Handling: It is unclear if and how the application code ensures that block_hash is never NULL when an update is expected or if it’s intentionally designed to allow NULL values.

Recommendations:

  • Confirm the Migration Intent: Verify that migration 00004 aligns with the intended business logic. If updates should occur even when transitioning from a NULL value, consider revising the update condition.
  • Use Null-Safe Comparison: To reliably handle cases where either the new or stored block_hash might be NULL, consider replacing the condition $3 != latest_block.block_hash with a null-safe comparison like IS DISTINCT FROM (if supported by your SQL dialect).
    For example:
    ... AND $3 IS DISTINCT FROM latest_block.block_hash
  • Data Transition Strategy: Ensure that the migration plan accounts for existing rows without a block hash and defines how they should be updated once a non‑NULL value is available.

By addressing these points, you can ensure the migration sequence and subsequent data handling in the application are robust.

@fbac fbac merged commit 1261e2c into main Feb 10, 2025
8 checks passed
@fbac fbac deleted the mkysel/fix-sql-upgrade branch February 10, 2025 21:45
@fbac fbac mentioned this pull request Feb 11, 2025
fbac added a commit that referenced this pull request Feb 11, 2025
Introduced by mistake in #471
Remove them to use the ones defined in `local.env`

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

- **Chores**
- Streamlined internal configuration by removing outdated settings to
simplify environment management.
- These backend adjustments help maintain consistent performance without
affecting any visible features for users.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
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