Skip to content

Renumber migrations after the WIT default shift#89

Merged
leynos merged 5 commits into
mainfrom
fix-migration-ordering
Mar 30, 2026
Merged

Renumber migrations after the WIT default shift#89
leynos merged 5 commits into
mainfrom
fix-migration-ordering

Conversation

@leynos
Copy link
Copy Markdown
Owner

@leynos leynos commented Mar 29, 2026

Make V12__wasm_wit_default_0_3_0.sql the PostgreSQL migration that updates the default WIT version, then move the token-budget and redundant-index migrations to V13 and V14 so the sequence stays strictly ordered.

Align the libSQL incremental migration table and its tests with the new version numbers, and update the libSQL integration test to assert the renumbered migration marker.

Summary by Sourcery

Renumber libSQL incremental migrations to align the WIT default version shift and keep migration sequencing consistent across backends.

Enhancements:

  • Update libSQL incremental migration versions so the WIT default update migration is V12 and subsequent migrations are shifted to V13 and V14.
  • Adjust the non-transactional libSQL migration entry and SQL builder to use the renamed V12 WIT default migration.

Tests:

  • Update libSQL migration unit tests and the integration test to assert the new migration version numbers and markers.

Make `V12__wasm_wit_default_0_3_0.sql` the PostgreSQL migration that
updates the default WIT version, then move the token-budget and
redundant-index migrations to `V13` and `V14` so the sequence stays
strictly ordered.

Align the libSQL incremental migration table and its tests with the new
version numbers, and update the libSQL integration test to assert the
renumbered migration marker.
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Mar 29, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: d92d76a9-da38-4bf4-b330-3a170c8ebed7

📥 Commits

Reviewing files that changed from the base of the PR and between 736fef0 and d76f4dc.

📒 Files selected for processing (1)
  • tests/db_integration/libsql_wit_defaults.rs

Migration Sequencing Update for WIT Default Shift

Renumbers and realigns libSQL incremental migrations so the WebAssembly Interface Types (WIT) default version update runs as migration V12, with subsequent migrations shifted to V13 and V14. Updates migration runner logic, non-transactional handling, SQL builders, constants, and tests to assert the new ordering. References ExecPlan: docs/plans/2026-03-09-use-wit-v3-in-extensions.md.

Changes

  • src/db/libsql_migrations.rs

    • Moves the wasm_wit_default_0_3_0 incremental migration from version 10 → 12 in INCREMENTAL_MIGRATIONS and updates its embedded SQL generator marker to "-- generated by v12_wasm_wit_default_migration_sql()".
    • Shifts job_token_budget 12→13 and drop_redundant_wasm_tools_name_index 13→14, updating the embedded SQL include to V14 for the redundant-index migration.
    • Renames the SQL builder reference/usage to the v12 builder and special-cases non-transactional execution for version == 12 (it contains its own BEGIN/COMMIT and PRAGMAs).
    • Renames libSQL rebuild-related constants and copy-column constants from V10_* → V12_* to match the renumbered migration and ensure consistent wiring.
    • Documents why INCREMENTAL_MIGRATIONS intentionally jumps (some PG migrations are baked into libsql_schema.sql and must not be duplicated).
  • tests/db_integration/libsql_wit_defaults.rs and unit tests

    • Updates integration test to seed the legacy schema, run migrations, and verify that new inserts default to WIT "0.3.0".
    • Replaces previous single-version assertion with:
      • an assertion that _migrations has no row for version 10 (guard against regression), and
      • assertions that _migrations contains entries for versions 12, 13 and 14 with the expected names.
    • Applies the suggested refactor: extracts repeated test logic into five async free helper functions in the same test file (insert_test_wasm_tool, insert_test_wasm_channel, assert_wit_version, assert_migration_absent, assert_migration_entries) so the test body is orchestration-only.
    • Updates libSQL unit tests and integration test expectations to reference the renamed marker and version numbers.

Rationale / Context

Ensures strict, deterministic migration ordering so the WIT 0.3.0 default update runs as V12 and subsequent migrations remain ordered, aligning DB migration sequencing with the WIT 0.3.0 host contract and the ExecPlan document.

Impact

  • No exported/public API signature changes.
  • Migration runner non-transactional path moved to V12; constants, SQL builders, and tests updated to match renumbering.
  • Review effort: medium — focuses on renumbering, non-transactional handling, constants/SQL builder renames, and test refactor.

Walkthrough

Renumber the wasm WIT default incremental migration from 10 → 12, shift subsequent migrations to 13 and 14, rename the SQL builder function, update the runner special‑case to version 12, switch the embedded SQL include to V14, and update tests to assert the new versions.

Changes

Cohort / File(s) Summary
Migration Renumbering & Runner
src/db/libsql_migrations.rs
Renumber incremental migrations: wasm_wit_default_0_3_0 moved 10 → 12; job_token_budget → 13; drop_redundant_wasm_tools_name_index → 14. Move non‑transactional special case from version == 10 to version == 12. Rename SQL generator to v12_wasm_wit_default_migration_sql(). Update constants from V10_*V12_* and adjust subsequent version constants.
Embedded SQL Reference
src/db/.../V13__*, src/db/.../V14__*
Switch embedded include to the reindexed SQL file V14__... to match the shifted migration ordering.
Integration Tests
tests/db_integration/libsql_wit_defaults.rs
Refactor test to seed legacy schema, insert wasm_tools/wasm_channels rows, assert _migrations has no version = 10, and verify migration rows for versions 12 (wasm_wit_default_0_3_0), 13 (job_token_budget) and 14 (drop_redundant_wasm_tools_name_index). Add helper functions for insertion and assertions with clearer panic messages.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Client as "Test / Runner"
  participant Runner as "Migration Runner"
  participant Builder as "v12 SQL Builder"
  participant DB as "Database (_migrations & exec)"

  Client->>Runner: request run_incremental(version = 12)
  Runner->>DB: query `_migrations` for version 12
  DB-->>Runner: return migration entry / metadata
  Runner->>Builder: request non-transactional SQL for v12
  Builder-->>Runner: return SQL script (non-transactional)
  Runner->>DB: execute SQL (non-transactional)
  DB-->>Runner: return execution result
  Runner-->>Client: return success/failure
Loading

Poem

🔁 Migrations shifted, numbers realigned,
12 claims the WIT default, tidy and signed,
Runner altered, builder renamed with care,
Tests now seek versions in their rightful lair,
🎉 March the versions forward, steadfast and fair

🚥 Pre-merge checks | ✅ 3 | ❌ 4

❌ Failed checks (4 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is well-structured with clear objectives, but the template's required validation and security sections are incomplete or missing. Complete the template by checking validation steps (cargo fmt, clippy, test results), marking the change type, specifying the review track (likely Track C given database impact), and confirming security/rollback details.
Docstring Coverage ⚠️ Warning Docstring coverage is 63.64% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Testing ⚠️ Warning PR lacks essential test coverage for non-transactional migration error paths, idempotency verification, SQL snapshot testing, and PostgreSQL-specific migrations. Add error path testing for apply_non_transactional_migration(), idempotency tests running migrations twice, snapshot tests for generated SQL, and PostgreSQL backend migration tests.
User-Facing Documentation ⚠️ Warning PR renumbers libSQL migrations (V10→V12, V12→V13, V13→V14) but docs/database-integrations.md section 4.3 retains outdated version numbers, creating inaccuracy for operator-facing documentation. Update docs/database-integrations.md section 4.3 to reflect new migration versions: V12 for WIT-version rebuilds, V13 for token-budget columns, V14 for drop-redundant-index.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and directly summarises the main change: renumbering migrations following the WIT default version shift from V10 to V12.
Developer Documentation ✅ Passed PR contains only internal implementation changes to libSQL migration version numbering and internal helper function names with no new or changed public APIs.
Module-Level Documentation ✅ Passed Both modified files carry appropriate module-level docstrings using the //! format, clearly explaining their purpose and utility.

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

✨ 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 fix-migration-ordering

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

@github-actions github-actions Bot added scope: db/postgres PostgreSQL backend scope: db/libsql libSQL / Turso backend size: S 10-49 changed lines risk: medium Business logic, config, or moderate-risk modules contributor: core 20+ merged PRs labels Mar 29, 2026
@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai Bot commented Mar 29, 2026

Reviewer's guide (collapsed on small PRs)

Reviewer's Guide

Renumbers the libSQL incremental migrations so that the WIT default-update migration is version 12, shifts subsequent migrations to versions 13 and 14, and updates the non-transactional migration helper plus tests and integration checks to match the new numbering and SQL marker strings.

Class diagram for libSQL migration helper function renumbering

classDiagram
    class LibsqlMigrationsModule {
        +INCREMENTAL_MIGRATIONS : Vec~(i64, &str, &str)~
        +SCHEMA : &str
        +run_incremental(conn : libsql_Connection) Result
        -append_table_rebuild_sql(sql : String, table_name : &str, columns_sql : &str) String
        -v12_wasm_wit_default_migration_sql() String
    }

    class libsql_Connection

    LibsqlMigrationsModule --> libsql_Connection : uses
Loading

File-Level Changes

Change Details Files
Renumber libSQL incremental migrations and wire the WIT default migration as version 12 with updated SQL marker and helper function name.
  • Updated INCREMENTAL_MIGRATIONS entries so the wasm WIT default migration is version 12, job token budget is version 13, and the redundant index drop is version 14
  • Adjusted the include path for the redundant index migration to reference V14 instead of V13
  • Changed the special-case non-transactional migration branch to trigger on version 12 instead of 10
  • Renamed the helper function for building the WIT default migration SQL from v10_wasm_wit_default_migration_sql to v12_wasm_wit_default_migration_sql
src/db/libsql_migrations.rs
Align unit tests and integration tests with the new migration version numbers and SQL marker strings.
  • Updated tests to look up version 12 instead of 10 in INCREMENTAL_MIGRATIONS and to expect the new SQL marker string referencing v12_wasm_wit_default_migration_sql
  • Adjusted test assertions to mention V12 instead of V10 in error messages and expectations for WIT default behavior
  • Changed the libSQL integration test to query the _migrations table for version 12 instead of 10
src/db/libsql_migrations.rs
tests/db_integration/libsql_wit_defaults.rs

Possibly linked issues

  • Front end documentation #7: PR renumbers migrations to make the WIT change V12 and shifts others, resolving the duplicate V12 issue.

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

codescene-delta-analysis[bot]

This comment was marked as outdated.

@leynos leynos marked this pull request as ready for review March 29, 2026 22:03
Copy link
Copy Markdown
Contributor

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

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

Hey - I've found 1 issue, and left some high level feedback:

  • Consider renaming v12_wasm_wit_default_migration_sql to a version-agnostic name (e.g., wit_default_migration_sql) so future renumbering doesn’t require touching function names and all their call sites.
  • Some test assertion messages and strings embed the migration version number (e.g., "expected a V12 libSQL migration..."); you could reduce future churn by asserting on the name/marker and making messages less version-specific where possible.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- Consider renaming `v12_wasm_wit_default_migration_sql` to a version-agnostic name (e.g., `wit_default_migration_sql`) so future renumbering doesn’t require touching function names and all their call sites.
- Some test assertion messages and strings embed the migration version number (e.g., "expected a V12 libSQL migration..."); you could reduce future churn by asserting on the name/marker and making messages less version-specific where possible.

## Individual Comments

### Comment 1
<location path="tests/db_integration/libsql_wit_defaults.rs" line_range="137" />
<code_context>
     let mut migration_rows = conn
         .query(
             "SELECT name FROM _migrations WHERE version = ?1",
-            libsql::params![10],
</code_context>
<issue_to_address>
**suggestion (testing):** Strengthen the integration test by validating the full migration state, not just the presence of version 12

The test now checks for version 12 instead of 10, which matches the renumbered migrations. To make it a stronger regression guard around this renumbering, you could also:

- Assert that there is no `_migrations` row for version 10.
- Optionally assert that versions 13 and 14 exist with the expected names, so the test fails if libSQL and PostgreSQL migration sequences diverge again.

Suggested implementation:

```rust
    // First, assert that there is no migration entry for the old version 10.
    let mut migration_rows = conn
        .query(
            "SELECT name FROM _migrations WHERE version = ?1",
            libsql::params![10],
        )
        .await
        .expect("query migration marker for version 10");
    assert!(
        migration_rows
            .next()
            .await
            .expect("read migration row for version 10")
            .is_none(),
        "unexpected _migrations row for version 10; migration numbering has regressed"
    );

    // Then, assert that the renumbered migrations (12, 13, 14) all exist.
    for version in [12_i64, 13, 14] {
        let mut rows = conn
            .query(
                "SELECT name FROM _migrations WHERE version = ?1",
                libsql::params![version],
            )
            .await
            .expect("query migration marker");
        let row = rows
            .next()
            .await
            .expect("read migration row for expected version");
        assert!(
            row.is_some(),
            "expected _migrations row for version {}; migration sequences may have diverged",
            version
        );
    }

    // Preserve the original query for version 12 in case later assertions depend on it.
    let mut migration_rows = conn
        .query(
            "SELECT name FROM _migrations WHERE version = ?1",
            libsql::params![12],
        )
        .await
        .expect("query migration marker");

```

If you want to assert specific migration names for versions 12, 13, and 14 (not just their presence), you can extend the loop body to extract the `name` column from `row` using whatever accessor your `libsql` row type provides (e.g., `row.unwrap().get::<_, String>(0)?`) and compare it to the expected migration filenames. That part depends on the exact APIs and naming conventions used elsewhere in your test suite.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread tests/db_integration/libsql_wit_defaults.rs
Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 6ebcf8deff

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/db/libsql_migrations.rs
Copy link
Copy Markdown
Contributor

@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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/db/libsql_migrations.rs (1)

68-157: ⚠️ Potential issue | 🟡 Minor

Document the intentional libSQL migration version gap (9 → 12) in the code.

V10 (wasm_versioning) and V11 (conversation_unique_indexes) changes are embedded directly in libsql_schema.sql, whereas PostgreSQL applies them as incremental migrations. The INCREMENTAL_MIGRATIONS array correctly skips these versions because libSQL's bootstrap schema already includes those schema updates. Add a comment above the array explaining this backend-specific design to prevent future confusion.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/db/libsql_migrations.rs` around lines 68 - 157, The
INCREMENTAL_MIGRATIONS array currently jumps from version 9 to 12 which looks
like a bug; add a short explanatory comment immediately above the
INCREMENTAL_MIGRATIONS definition stating that the v10 (wasm_versioning) and v11
(conversation_unique_indexes) migrations are intentionally omitted for libSQL
because those schema changes are already baked into the libSQL bootstrap schema
(libsql_schema.sql) rather than applied incrementally, and that this gap is
backend-specific to prevent future confusion when editing INCREMENTAL_MIGRATIONS
or adding new versions; reference the symbols INCREMENTAL_MIGRATIONS, the
numeric versions 9→12, and the migration names (wasm_versioning,
conversation_unique_indexes) in the comment so maintainers can quickly
understand the rationale.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@src/db/libsql_migrations.rs`:
- Around line 68-157: The INCREMENTAL_MIGRATIONS array currently jumps from
version 9 to 12 which looks like a bug; add a short explanatory comment
immediately above the INCREMENTAL_MIGRATIONS definition stating that the v10
(wasm_versioning) and v11 (conversation_unique_indexes) migrations are
intentionally omitted for libSQL because those schema changes are already baked
into the libSQL bootstrap schema (libsql_schema.sql) rather than applied
incrementally, and that this gap is backend-specific to prevent future confusion
when editing INCREMENTAL_MIGRATIONS or adding new versions; reference the
symbols INCREMENTAL_MIGRATIONS, the numeric versions 9→12, and the migration
names (wasm_versioning, conversation_unique_indexes) in the comment so
maintainers can quickly understand the rationale.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: f8875d58-8b43-49ad-8b29-4a68cbc7d85b

📥 Commits

Reviewing files that changed from the base of the PR and between 209cb73 and 6ebcf8d.

📒 Files selected for processing (5)
  • migrations/V12__wasm_wit_default_0_3_0.sql
  • migrations/V13__job_token_budget.sql
  • migrations/V14__drop_redundant_wasm_tools_name_index.sql
  • src/db/libsql_migrations.rs
  • tests/db_integration/libsql_wit_defaults.rs

Expand the libSQL WIT-default integration test so it asserts the old
`V10` migration marker is absent and the renumbered `V12`, `V13`, and
`V14` markers all exist with the expected names.

Keep the renumbering fix covered by a stronger regression check so a
future divergence between PostgreSQL and libSQL migration sequences
fails loudly.
@github-actions github-actions Bot added size: M 50-199 changed lines and removed size: S 10-49 changed lines labels Mar 29, 2026
codescene-delta-analysis[bot]

This comment was marked as outdated.

Copy link
Copy Markdown
Contributor

@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.

♻️ Duplicate comments (1)
tests/db_integration/libsql_wit_defaults.rs (1)

54-175: 🧹 Nitpick | 🔵 Trivial

Function length exceeds recommended threshold.

Static analysis flags this function at 115 lines against a 70-line threshold. Extract helper functions to reduce cognitive load:

♻️ Suggested helper extractions
async fn assert_migration_absent(conn: &libsql::Connection, version: i64) {
    let mut rows = conn
        .query(
            "SELECT name FROM _migrations WHERE version = ?1",
            libsql::params![version],
        )
        .await
        .expect("query migration marker");
    assert!(
        rows.next().await.expect("read migration row").is_none(),
        "unexpected _migrations row for version {version}; migration numbering regressed"
    );
}

async fn assert_migration_present(conn: &libsql::Connection, version: i64, expected_name: &str) {
    let mut rows = conn
        .query(
            "SELECT name FROM _migrations WHERE version = ?1",
            libsql::params![version],
        )
        .await
        .expect("query migration marker");
    let row = rows
        .next()
        .await
        .expect("read migration row")
        .unwrap_or_else(|| {
            panic!("expected _migrations row for version {version}; migration sequences diverged")
        });
    let name: String = row.get(0).expect("migration name");
    assert_eq!(name, expected_name);
}

Then the test body becomes:

assert_migration_absent(&conn, 10).await;

for (version, expected_name) in [
    (12_i64, "wasm_wit_default_0_3_0"),
    (13_i64, "job_token_budget"),
    (14_i64, "drop_redundant_wasm_tools_name_index"),
] {
    assert_migration_present(&conn, version, expected_name).await;
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/db_integration/libsql_wit_defaults.rs` around lines 54 - 175, The test
function libsql_run_migrations_upgrades_legacy_wasm_wit_defaults is too long;
extract two small async helpers (e.g., assert_migration_absent(conn:
&libsql::Connection, version: i64) and assert_migration_present(conn:
&libsql::Connection, version: i64, expected_name: &str)) that encapsulate the
repeated _migrations query/validation logic currently using
conn.query(...).await, then call assert_migration_absent(&conn, 10).await and
replace the loop body with calls to assert_migration_present(&conn, version,
expected_name).await for each (version, expected_name) tuple to shorten and
clarify the main test function while preserving behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@tests/db_integration/libsql_wit_defaults.rs`:
- Around line 54-175: The test function
libsql_run_migrations_upgrades_legacy_wasm_wit_defaults is too long; extract two
small async helpers (e.g., assert_migration_absent(conn: &libsql::Connection,
version: i64) and assert_migration_present(conn: &libsql::Connection, version:
i64, expected_name: &str)) that encapsulate the repeated _migrations
query/validation logic currently using conn.query(...).await, then call
assert_migration_absent(&conn, 10).await and replace the loop body with calls to
assert_migration_present(&conn, version, expected_name).await for each (version,
expected_name) tuple to shorten and clarify the main test function while
preserving behavior.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 353482ab-cb5c-4e8f-823f-ed97ab3de285

📥 Commits

Reviewing files that changed from the base of the PR and between 6ebcf8d and a29a3d2.

📒 Files selected for processing (1)
  • tests/db_integration/libsql_wit_defaults.rs

Document why `INCREMENTAL_MIGRATIONS` jumps from `9` to `12` in the
libSQL backend.

Explain that `wasm_versioning` and
`conversation_unique_indexes` are already baked into
`libsql_schema.sql`, so maintainers do not try to add backend-specific
placeholder entries when extending the migration sequence.
codescene-delta-analysis[bot]

This comment was marked as outdated.

Copy link
Copy Markdown
Contributor

@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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/db/libsql_migrations.rs (1)

24-62: 🧹 Nitpick | 🔵 Trivial

Rename these constants to reflect V12 usage.

V10_WASM_TOOLS_COLUMNS, V10_WASM_TOOLS_COPY_COLUMNS, V10_WASM_TOOLS_POST_REBUILD_SQL, V10_WASM_CHANNELS_COLUMNS, and V10_WASM_CHANNELS_COPY_COLUMNS are now used exclusively by v12_wasm_wit_default_migration_sql(), yet retain the V10_ prefix. This creates a naming inconsistency that could confuse maintainers.

Rename these constants to V12_* or drop the version prefix entirely (e.g., WASM_WIT_DEFAULT_TOOLS_COLUMNS) to match their actual usage context.

♻️ Proposed rename
-const V10_WASM_TOOLS_COLUMNS: &str = r#"    id TEXT PRIMARY KEY,
+const V12_WASM_TOOLS_COLUMNS: &str = r#"    id TEXT PRIMARY KEY,
     user_id TEXT NOT NULL,
     ...
     UNIQUE (user_id, name, version)"#;

-const V10_WASM_TOOLS_COPY_COLUMNS: &str = r#"id, user_id, name, version, wit_version, description, wasm_binary, binary_hash,
+const V12_WASM_TOOLS_COPY_COLUMNS: &str = r#"id, user_id, name, version, wit_version, description, wasm_binary, binary_hash,
     parameters_schema, source_url, trust_level, status, created_at, updated_at"#;

-const V10_WASM_TOOLS_POST_REBUILD_SQL: &str = r#"CREATE INDEX IF NOT EXISTS idx_wasm_tools_user ON wasm_tools(user_id);
+const V12_WASM_TOOLS_POST_REBUILD_SQL: &str = r#"CREATE INDEX IF NOT EXISTS idx_wasm_tools_user ON wasm_tools(user_id);
 CREATE INDEX IF NOT EXISTS idx_wasm_tools_status ON wasm_tools(status);
 CREATE INDEX IF NOT EXISTS idx_wasm_tools_trust ON wasm_tools(trust_level);"#;

-const V10_WASM_CHANNELS_COLUMNS: &str = r#"    id TEXT PRIMARY KEY,
+const V12_WASM_CHANNELS_COLUMNS: &str = r#"    id TEXT PRIMARY KEY,
     user_id TEXT NOT NULL,
     ...
     UNIQUE (user_id, name)"#;

-const V10_WASM_CHANNELS_COPY_COLUMNS: &str = r#"id, user_id, name, version, wit_version, description, wasm_binary, binary_hash,
+const V12_WASM_CHANNELS_COPY_COLUMNS: &str = r#"id, user_id, name, version, wit_version, description, wasm_binary, binary_hash,
     capabilities_json, status, created_at, updated_at"#;

Then update the references in v12_wasm_wit_default_migration_sql() at lines 317–329 accordingly.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/db/libsql_migrations.rs` around lines 24 - 62, Constants with a V10_
prefix (V10_WASM_TOOLS_COLUMNS, V10_WASM_TOOLS_COPY_COLUMNS,
V10_WASM_TOOLS_POST_REBUILD_SQL, V10_WASM_CHANNELS_COLUMNS,
V10_WASM_CHANNELS_COPY_COLUMNS) are actually used by
v12_wasm_wit_default_migration_sql() and should be renamed to reflect V12 usage
(or a neutral name) to avoid confusion; rename each constant (e.g.,
V12_WASM_TOOLS_COLUMNS, V12_WASM_TOOLS_COPY_COLUMNS,
V12_WASM_TOOLS_POST_REBUILD_SQL, V12_WASM_CHANNELS_COLUMNS,
V12_WASM_CHANNELS_COPY_COLUMNS or drop the version prefix) and update every
reference inside v12_wasm_wit_default_migration_sql() to the new names so the
code compiles and the names match their usage.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@src/db/libsql_migrations.rs`:
- Around line 24-62: Constants with a V10_ prefix (V10_WASM_TOOLS_COLUMNS,
V10_WASM_TOOLS_COPY_COLUMNS, V10_WASM_TOOLS_POST_REBUILD_SQL,
V10_WASM_CHANNELS_COLUMNS, V10_WASM_CHANNELS_COPY_COLUMNS) are actually used by
v12_wasm_wit_default_migration_sql() and should be renamed to reflect V12 usage
(or a neutral name) to avoid confusion; rename each constant (e.g.,
V12_WASM_TOOLS_COLUMNS, V12_WASM_TOOLS_COPY_COLUMNS,
V12_WASM_TOOLS_POST_REBUILD_SQL, V12_WASM_CHANNELS_COLUMNS,
V12_WASM_CHANNELS_COPY_COLUMNS or drop the version prefix) and update every
reference inside v12_wasm_wit_default_migration_sql() to the new names so the
code compiles and the names match their usage.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: eb6656c8-29dd-46b4-ab28-ac3c532d9fb9

📥 Commits

Reviewing files that changed from the base of the PR and between a29a3d2 and df3e514.

📒 Files selected for processing (1)
  • src/db/libsql_migrations.rs

@leynos
Copy link
Copy Markdown
Owner Author

leynos commented Mar 29, 2026

@coderabbitai Please suggest a fix for this issue and supply a prompt for an AI coding agent to enable it to apply the fix. Include the file and symbol names indicated in the issue at the head of your response.

Large Method

tests/db_integration/libsql_wit_defaults.rs: libsql_run_migrations_upgrades_legacy_wasm_wit_defaults

What lead to degradation?

libsql_run_migrations_upgrades_legacy_wasm_wit_defaults increases from 90 to 115 lines of code, threshold = 70

Why does this problem occur?

Overly long functions make the code harder to read. The recommended maximum function length for the Rust language is 70 lines of code. Severity: Brain Method - Complex Method - Long Method.

How to fix it?

We recommend to be careful here -- just splitting long functions don't necessarily make the code easier to read. Instead, look for natural chunks inside the functions that expresses a specific task or concern. Often, such concerns are indicated by a Code Comment followed by an if-statement. Use the EXTRACT FUNCTION refactoring to encapsulate that concern.

@coderabbitai

This comment was marked as resolved.

Rename the libSQL rebuild SQL constants that feed
v12_wasm_wit_default_migration_sql so their names match the
migration version that still uses them.

This removes stale V10-prefixed identifiers that were left behind after
migration renumbering and makes the v12 migration wiring easier to follow.
codescene-delta-analysis[bot]

This comment was marked as outdated.

@coderabbitai coderabbitai Bot added the Roadmap label Mar 29, 2026
Extract the repeated insert and assertion steps from
`libsql_run_migrations_upgrades_legacy_wasm_wit_defaults` into
free async helpers in the same integration test file.

This keeps the legacy schema fixture unchanged while shrinking the test
body down to setup, migration execution, and the expected helper calls.
@coderabbitai coderabbitai Bot removed the Roadmap label Mar 29, 2026
@leynos
Copy link
Copy Markdown
Owner Author

leynos commented Mar 29, 2026

@coderabbitai Have the following now been resolved?

<location path="tests/db_integration/libsql_wit_defaults.rs" line_range="137" />
<code_context>
     let mut migration_rows = conn
         .query(
             "SELECT name FROM _migrations WHERE version = ?1",
-            libsql::params![10],
</code_context>
<issue_to_address>
**suggestion (testing):** Strengthen the integration test by validating the full migration state, not just the presence of version 12

The test now checks for version 12 instead of 10, which matches the renumbered migrations. To make it a stronger regression guard around this renumbering, you could also:

- Assert that there is no `_migrations` row for version 10.
- Optionally assert that versions 13 and 14 exist with the expected names, so the test fails if libSQL and PostgreSQL migration sequences diverge again.

Suggested implementation:

```rust
    // First, assert that there is no migration entry for the old version 10.
    let mut migration_rows = conn
        .query(
            "SELECT name FROM _migrations WHERE version = ?1",
            libsql::params![10],
        )
        .await
        .expect("query migration marker for version 10");
    assert!(
        migration_rows
            .next()
            .await
            .expect("read migration row for version 10")
            .is_none(),
        "unexpected _migrations row for version 10; migration numbering has regressed"
    );

    // Then, assert that the renumbered migrations (12, 13, 14) all exist.
    for version in [12_i64, 13, 14] {
        let mut rows = conn
            .query(
                "SELECT name FROM _migrations WHERE version = ?1",
                libsql::params![version],
            )
            .await
            .expect("query migration marker");
        let row = rows
            .next()
            .await
            .expect("read migration row for expected version");
        assert!(
            row.is_some(),
            "expected _migrations row for version {}; migration sequences may have diverged",
            version
        );
    }

    // Preserve the original query for version 12 in case later assertions depend on it.
    let mut migration_rows = conn
        .query(
            "SELECT name FROM _migrations WHERE version = ?1",
            libsql::params![12],
        )
        .await
        .expect("query migration marker");

```

If you want to assert specific migration names for versions 12, 13, and 14 (not just their presence), you can extend the loop body to extract the `name` column from `row` using whatever accessor your `libsql` row type provides (e.g., `row.unwrap().get::<_, String>(0)?`) and compare it to the expected migration filenames. That part depends on the exact APIs and naming conventions used elsewhere in your test suite.
</issue_to_address>

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Mar 29, 2026

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
fd 'libsql_wit_defaults.rs' --exec cat {}

Length of output: 6442


@leynos: Yes, both points from the original suggestion are fully addressed in the current file:

  • No version-10 row: assert_migration_absent(&conn, 10) asserts that no _migrations row exists for version 10, guarding against numbering regression.
  • Versions 12, 13, and 14 with exact names: assert_migration_entries iterates over all three renumbered migrations and asserts not just their presence but also their exact name values (wasm_wit_default_0_3_0, job_token_budget, drop_redundant_wasm_tools_name_index), which is stronger than the original suggestion of presence-only checks.

The test is now a proper regression guard for the full renumbering.

@leynos leynos merged commit 2a612b2 into main Mar 30, 2026
25 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

contributor: core 20+ merged PRs risk: medium Business logic, config, or moderate-risk modules scope: db/libsql libSQL / Turso backend scope: db/postgres PostgreSQL backend size: M 50-199 changed lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant