Skip to content

feat: migration 0014 — history drain state on channels (issue #70, database half) - #71

Merged
Bonobo791 merged 2 commits into
mainfrom
mt-history-state
Aug 4, 2026
Merged

feat: migration 0014 — history drain state on channels (issue #70, database half)#71
Bonobo791 merged 2 commits into
mainfrom
mt-history-state

Conversation

@Bonobo791

@Bonobo791 Bonobo791 commented Aug 4, 2026

Copy link
Copy Markdown
Owner

User description

What

The database half of #70 (live-first scanning during long history drains). Expand-only per I7 — no rebuild, nothing dropped:

  • drizzle/0014_channels_history_state.sql: channels gains nullable history_next_page_token (drain continuation) and history_boundary (ISO timestamp the drain started walking back from). A drain in flight at deploy time is backfilled (state copied from next_page_token/scan_cursor) so it keeps walking; the old columns are deliberately untouched — the backend switches reads over in its own PR (pipeline live/drain split).
  • schema.ts: the two columns with semantics comments.
  • src/lib/server/db/migration-0014.test.ts: behavior tests in the 0013 pattern (failing first, then green).
  • src/lib/server/testdb.ts: in-memory fixture gains the two columns (50 test files depend on it).

Behavior tests

  • columns added in declaration order, every pre-0014 row preserved exactly (distinct values per column, so a transposed copy can't slip through)
  • in-flight drain backfilled; live-only channels stay NULL; old columns untouched
  • tenancy contract still bites; new columns writable on legal shapes

Verification

  • npx vitest run src/lib/server/db/migration-0014.test.ts: 3/3 (watched ENOENT red → green)
  • Dev DB db applied + verified against the actual schema (0007-incident rule): 15 migrations in __drizzle_migrations, PRAGMA table_info(channels) shows 15 columns including both new ones, channels_org_requires_owner intact, no mid-drain channels (backfill vacuous on dev)
  • scripts/verify-tenancy.mjs against dev: ALL CHECKS PASSED (invariants are scan-state agnostic, as triaged)
  • npm run check 0/0, npm run test 50 files / 425 tests green, npm run build clean, codacy-analysis 0 issues on all changed files

Prod application: human per DEPLOY.md §1 after merge (npm run db:migrate with prod values sourced, then scripts/verify-tenancy.mjs must end ALL CHECKS PASSED).

Closes the database half of #70 (backend pipeline split remains with the backend agent).


CodeAnt-AI Description

Add separate database state for resumable channel history drains

What Changed

  • Channels now store history-drain continuation and boundary state separately from live scan progress
  • Deployments preserve in-progress drains by copying their resumable state into the new fields without changing existing scan values
  • Incomplete states without a scan boundary are left untouched instead of being treated as resumable
  • Test fixtures and migration tests cover row preservation, drain backfill, legal writes, and tenancy protection

Impact

✅ Resumable history drains after deployment
✅ Live scan state remains intact during migration
✅ Fewer corrupted or ambiguous drain states

💡 Usage Guide

Checking Your Pull Request

Every time you make a pull request, our system automatically looks through it. We check for security issues, mistakes in how you're setting up your infrastructure, and common code problems. We do this to make sure your changes are solid and won't cause any trouble later.

Talking to CodeAnt AI

Got a question or need a hand with something in your pull request? You can easily get in touch with CodeAnt AI right here. Just type the following in a comment on your pull request, and replace "Your question here" with whatever you want to ask:

@codeant-ai ask: Your question here

This lets you have a chat with CodeAnt AI about your pull request, making it easier to understand and improve your code.

Example

@codeant-ai ask: Can you suggest a safer alternative to storing this secret?

Preserve Org Learnings with CodeAnt

You can record team preferences so CodeAnt AI applies them in future reviews. Reply directly to the specific CodeAnt AI suggestion (in the same thread) and replace "Your feedback here" with your input:

@codeant-ai: Your feedback here

This helps CodeAnt AI learn and adapt to your team's coding style and standards.

Example

@codeant-ai: Do not flag unused imports.

Retrigger review

Ask CodeAnt AI to review the PR again, by typing:

@codeant-ai: review

Check Your Repository Health

To analyze the health of your code repository, visit our dashboard at https://app.codeant.ai. This tool helps you identify potential issues and areas for improvement in your codebase, ensuring your repository maintains high standards of code health.

@cla-bot cla-bot Bot added the cla-signed label Aug 4, 2026
@codeant-ai

codeant-ai Bot commented Aug 4, 2026

Copy link
Copy Markdown

🤖 CodeAnt AI — Review Status

Status Commit Started (UTC) Finished (UTC)
✅ Incremental review completed 4d0ab6b Aug 04, 2026 · 18:19 18:22
✅ Reviewed your PR a19ce8e Aug 04, 2026 · 18:06 18:09

@netlify

netlify Bot commented Aug 4, 2026

Copy link
Copy Markdown

Deploy Preview for moderaty ready!

Name Link
🔨 Latest commit 4d0ab6b
🔍 Latest deploy log https://app.netlify.com/projects/moderaty/deploys/6a722d1dd2f7490008087f12
😎 Deploy Preview https://deploy-preview-71--moderaty.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
Lighthouse
Lighthouse
1 paths audited
Performance: 91
Accessibility: 97
Best Practices: 100
SEO: 100
PWA: -
View the detailed breakdown and full score reports

To edit notification comments on pull requests, go to your Netlify project configuration.

@coderabbitai

coderabbitai Bot commented Aug 4, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Summary by CodeRabbit

  • New Features

    • Added support for tracking channel history pagination and its starting boundary independently.
    • Existing in-progress history states are preserved and automatically carried forward during migration.
  • Bug Fixes

    • Improved reliability when resuming channel history synchronization without changing existing continuation data.
  • Tests

    • Added coverage for migration behavior, data preservation, tenancy constraints, and updates to the new history state.

Walkthrough

Migration 0014 adds nullable history-drain columns to channels, backfills active rows, updates schema metadata and test schemas, and adds migration behavior tests.

Changes

Channel history state

Layer / File(s) Summary
Migration and schema metadata
drizzle/0014_channels_history_state.sql, drizzle/meta/0014_snapshot.json, drizzle/meta/_journal.json
The migration adds and backfills history_next_page_token and history_boundary. Drizzle metadata records the migration and updated schema snapshot.
Runtime channel schema
src/lib/server/db/schema.ts, src/lib/server/testdb.ts
The application and in-memory test schemas include the two nullable history fields.
Migration behavior tests
src/lib/server/db/migration-0014.test.ts
Tests verify column creation, row preservation, active-drain backfill, legacy-column preservation, tenancy constraints, and writes to history_boundary.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Possibly related PRs

🚥 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.
Title check ✅ Passed The title clearly identifies migration 0014 and the addition of channel history-drain state.
Description check ✅ Passed The description directly explains the migration, backfill behavior, schema updates, tests, and database scope.
✨ Finishing Touches 💡 1
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch mt-history-state

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.

@codeant-ai codeant-ai Bot added the size:XXL This PR changes 1000+ lines, ignoring generated files label Aug 4, 2026
@codeant-ai

codeant-ai Bot commented Aug 4, 2026

Copy link
Copy Markdown

Sequence Diagram

This PR adds nullable history-drain state to channels and backfills active drains from the existing scan state. The migration preserves existing columns and leaves live-only channels without drain state, enabling the later live and history scan split.

sequenceDiagram
    participant Deployment
    participant Database
    participant Channels

    Deployment->>Database: Apply migration 0014
    Database->>Channels: Add nullable history state columns
    Database->>Channels: Backfill active drain state
    Channels-->>Database: Preserve old scan state
    Database-->>Deployment: Migration complete with live-only state null
Loading

Generated by CodeAnt AI

@amazon-q-developer amazon-q-developer 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.

This migration is well-structured and properly implements the expand-only pattern for issue #70. The two new nullable columns (history_next_page_token and history_boundary) are correctly added to support independent history drain state while preserving the existing live scan functionality.

Key strengths:

  • Comprehensive test coverage validating column addition, backfill logic, row preservation, and constraint enforcement
  • Proper backfill strategy for in-flight drains using the WHERE clause to only copy state when next_page_token IS NOT NULL
  • Test DB fixture correctly updated to maintain test consistency across 50 test files
  • Schema definitions match the SQL migration exactly

The verification steps in the PR description demonstrate thorough validation. No blocking issues identified.


You can now have the agent implement changes and create commits directly on your pull request's source branch. Simply comment with /q followed by your request in natural language to ask the agent to make changes.

@codeant-ai

codeant-ai Bot commented Aug 4, 2026

Copy link
Copy Markdown

🏁 CodeAnt Quality Gate Results

Commit: 4d0ab6b0
Scan Time: 2026-08-04 18:33:29 UTC

✅ Overall Status: PASSED

Quality Gate Details

Quality Gate Status Details
Secrets ✅ PASSED 0 secrets found
Duplicate Code ✅ PASSED 0.0% duplicated
SAST ✅ PASSED No security issues
Bugs ✅ PASSED Rating S: No bugs
IAC ✅ PASSED Rating S: No issues

View Full Results

@codacy-production

codacy-production Bot commented Aug 4, 2026

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 9 complexity · 0 duplication

Metric Results
Complexity 9 (≤ 100 complexity)
Duplication 0 (≤ 1 duplication)

View in Codacy

NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer
TIP This summary will be updated as you push new changes.

@qodo-code-review

Copy link
Copy Markdown

PR Summary by Qodo

Migration 0014: add channels history-drain state columns (issue #70)

✨ Enhancement 🧪 Tests ⚙️ Configuration changes 🕐 40+ Minutes

Grey Divider

AI Description

• Add nullable channels columns for history-drain continuation and drain boundary timestamp
• Backfill new history columns for drains already in-flight at deploy time
• Add migration behavior tests and update shared in-memory test DB schema
Diagram

graph TD
  A["0014 migration SQL"] --> B["Drizzle migrator"] --> C[("channels table")]
  D["schema.ts (channels model)"] --> E["DB access layer"] --> C
  F["migration-0014.test.ts"] --> G[("in-memory SQLite")] --> B
  H["testdb.ts fixture"] --> G
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. SQLite trigger-based column mirroring (temporary)
  • ➕ Keeps old and new drain-state columns consistent during staged rollout
  • ➕ Reduces risk if a drain starts between DB-migration deploy and backend cutover
  • ➖ Adds non-obvious DB behavior and operational complexity
  • ➖ Triggers must be removed later; harder to reason about write paths
2. Backend dual-write + guarded read switch (in follow-up PR)
  • ➕ Keeps logic in application code (more visible, testable, versioned)
  • ➕ Allows controlled cutover (read-new when populated; otherwise fall back)
  • ➖ Requires careful deploy sequencing and extra code paths during transition
  • ➖ Needs explicit cleanup once old columns are retired

Recommendation: The PR’s expand-only approach (add nullable columns + one-time backfill) is the right default for safe migrations. The main thing to ensure is rollout safety for the window between this migration and the backend PR: either (a) deploy them back-to-back, or (b) have the backend PR dual-write and/or perform a second backfill-on-start so drains initiated after this migration don’t end up only in the legacy columns.

Files changed (6) +1095 / -0

Enhancement (2) +31 / -0
0014_channels_history_state.sqlAdd channels history-drain columns + backfill in-flight drains +29/-0

Add channels history-drain columns + backfill in-flight drains

• Adds nullable history_next_page_token and history_boundary columns to channels. Backfills those columns from next_page_token/scan_cursor for rows representing drains already in progress at deploy time, while leaving legacy columns untouched.

drizzle/0014_channels_history_state.sql

schema.tsExpose history-drain state columns on channels schema +2/-0

Expose history-drain state columns on channels schema

• Adds historyNextPageToken and historyBoundary to the channels sqliteTable definition, with comments clarifying drain-state semantics for the upcoming live/drain pipeline split.

src/lib/server/db/schema.ts

Tests (2) +158 / -0
migration-0014.test.tsAdd migration 0014 behavior tests (column order, backfill, tenancy) +156/-0

Add migration 0014 behavior tests (column order, backfill, tenancy)

• Introduces an in-memory SQLite behavior test suite that applies the 0014 migration against a pre-0014 schema. Verifies column declaration order, exact row preservation, correct backfill of in-flight drains, and that the tenancy CHECK constraint still rejects invalid rows.

src/lib/server/db/migration-0014.test.ts

testdb.tsExtend shared test DB channels table with new history columns +2/-0

Extend shared test DB channels table with new history columns

• Updates the in-memory test database schema so channels includes history_next_page_token and history_boundary, keeping downstream tests consistent with the migrated schema.

src/lib/server/testdb.ts

Other (2) +906 / -0
0014_snapshot.jsonRegenerate Drizzle snapshot for migration 0014 +899/-0

Regenerate Drizzle snapshot for migration 0014

• Updates Drizzle’s schema snapshot to reflect the two new channels columns and preserve existing constraints/indexes metadata.

drizzle/meta/0014_snapshot.json

_journal.jsonRegister migration 0014 in Drizzle journal +7/-0

Register migration 0014 in Drizzle journal

• Adds the 0014_channels_history_state entry to the migration journal with breakpoints enabled so the migration runner recognizes it.

drizzle/meta/_journal.json

@codeant-ai

codeant-ai Bot commented Aug 4, 2026

Copy link
Copy Markdown

PR Code Suggestions ✨

Latest suggestions up to commit a19ce8e
CategorySuggestion                                                                                                                                    SeverityGenerated at (UTC)
Incorrect variable usage
Copying the high-water cursor as the history boundary causes interrupted drains to resume from the wrong timestamp

The history boundary is copied from scan_cursor, but the existing pipeline uses
scan_cursor as the high-water timestamp of the current incomplete page and keeps the
requested drain boundary in cursor. For a drain interrupted after one or more pages,
this stores the newest page timestamp as history_boundary, causing the new drain
implementation to resume or eventually commit the wrong boundary. Copy cursor into
history_boundary for an in-flight drain.

drizzle/0014_channels_history_state.sql [27-28]

Why it matters? 🤔
  • ❌ Interrupted history analysis can stop at the wrong boundary.
  • ❌ Requested historical comments may remain unscanned.
  • ⚠️ User-selected history windows become incomplete after deployment.

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** drizzle/0014_channels_history_state.sql
**Line:** 27:28
**Comment:**
	*Incorrect Variable Usage: The history boundary is copied from `scan_cursor`, but the existing pipeline uses `scan_cursor` as the high-water timestamp of the current incomplete page and keeps the requested drain boundary in `cursor`. For a drain interrupted after one or more pages, this stores the newest page timestamp as `history_boundary`, causing the new drain implementation to resume or eventually commit the wrong boundary. Copy `cursor` into `history_boundary` for an in-flight drain.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
Major2026-08-04 18:08
State mismatch
Non-null continuation tokens do not uniquely identify history drains

The backfill classifies every channel with a non-null next_page_token as a history
drain, but the existing pipeline uses that column for ordinary live scans as well.
An incomplete live scan will therefore acquire history state and may later be
processed by the split backend as a history drain. Backfill only rows that can be
positively identified as history work, or preserve the distinction in the
pre-migration state before copying.

drizzle/0014_channels_history_state.sql [29]

Why it matters? 🤔
  • ❌ Incomplete live scans can be classified as history drains.
  • ⚠️ Future split workers may process the wrong continuation state.
  • ⚠️ Migration-time state classification becomes irreversible.

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** drizzle/0014_channels_history_state.sql
**Line:** 29:29
**Comment:**
	*State Mismatch: The backfill classifies every channel with a non-null `next_page_token` as a history drain, but the existing pipeline uses that column for ordinary live scans as well. An incomplete live scan will therefore acquire history state and may later be processed by the split backend as a history drain. Backfill only rows that can be positively identified as history work, or preserve the distinction in the pre-migration state before copying.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
Major2026-08-04 18:08

@Bonobo791

Copy link
Copy Markdown
Owner Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Aug 4, 2026

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

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

Warning

CodeRabbit couldn't request changes on this pull request because it doesn't have sufficient GitHub permissions.

Please grant CodeRabbit Pull requests: Read and write permission and re-run the review.

👉 Steps to fix this

Actionable comments posted: 1

🤖 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 `@drizzle/0014_channels_history_state.sql`:
- Around line 26-29: Restrict the UPDATE in
drizzle/0014_channels_history_state.sql to rows where both next_page_token and
scan_cursor are non-NULL, preserving the existing column assignments. In
src/lib/server/db/migration-0014.test.ts lines 122-143, seed a channel with
next_page_token set and scan_cursor NULL, then assert the intended values of
both history_next_page_token and history_boundary for that row.
🪄 Autofix

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: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 42a43b42-9c60-4424-bc0d-d10cecc51720

📥 Commits

Reviewing files that changed from the base of the PR and between 784bf16 and a19ce8e.

📒 Files selected for processing (6)
  • drizzle/0014_channels_history_state.sql
  • drizzle/meta/0014_snapshot.json
  • drizzle/meta/_journal.json
  • src/lib/server/db/migration-0014.test.ts
  • src/lib/server/db/schema.ts
  • src/lib/server/testdb.ts

Comment thread drizzle/0014_channels_history_state.sql Outdated
@qodo-code-review

qodo-code-review Bot commented Aug 4, 2026

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (1) 📜 Skill insights (0)

Grey Divider


Remediation recommended

1. Null boundary backfill ✓ Resolved 🐞 Bug ≡ Correctness
Description
Migration 0014 backfills history_boundary from scan_cursor for all rows with next_page_token,
but scan_cursor is nullable and can be derived from the nullable cursor, so this can produce
rows where history_next_page_token is set while history_boundary remains NULL. That creates an
incomplete “drain in flight” state in the new columns which future code may not be able to resume
deterministically.
Code

drizzle/0014_channels_history_state.sql[R26-29]

+UPDATE `channels`
+SET `history_next_page_token` = `next_page_token`,
+    `history_boundary` = `scan_cursor`
+WHERE `next_page_token` IS NOT NULL;
Relevance

●●● Strong

Team has accepted migration backfill correctness/idempotency fixes; inconsistent drain state treated
as real bug.

PR-#48

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The migration writes history_boundary = scan_cursor for all rows where next_page_token is set,
without ensuring scan_cursor is present. The codebase defines cursor as nullable and derives
scanCursor from a nullable fallback, so a NULL scan_cursor is a reachable database value; this
makes the migration capable of backfilling a NULL boundary alongside a non-NULL continuation token.

drizzle/0014_channels_history_state.sql[26-29]
src/lib/server/pipeline.ts[475-485]
src/lib/server/db/schema.ts[89-104]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Migration 0014 copies `next_page_token`/`scan_cursor` into the new history-drain columns whenever `next_page_token` is non-NULL, but it does not require `scan_cursor` to be non-NULL. Because `scan_cursor` is nullable (and can be derived from a nullable `cursor`), this backfill can create an inconsistent state where `history_next_page_token` is populated but `history_boundary` is NULL.

## Issue Context
- `channels.cursor` is explicitly nullable (legacy rows can be unbounded).
- The pipeline derives `scanCursor` from `channel.scanCursor ?? newest`, and `newest` can fall back to `channel.cursor`.
- The migration predicates only on `next_page_token IS NOT NULL`.

## Fix Focus Areas
- drizzle/0014_channels_history_state.sql[26-29]

### Suggested fix direction
Update the backfill to avoid creating partial drain state. Options:
1) Make the backfill conditional on `scan_cursor IS NOT NULL` (so you never set `history_next_page_token` without a boundary), or
2) Use an explicit fallback for the boundary (e.g., `history_boundary = COALESCE(scan_cursor, cursor)`), and consider also guarding against the case where both are NULL.

Pick the option that matches the intended invariants for a resumable drain (i.e., whether a drain is allowed to have a NULL boundary or must be treated as “no drain in flight”).

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Informational

2. Unclosed test DB clients ✓ Resolved 🐞 Bug ☼ Reliability
Description
The new migration-0014.test.ts creates and returns libSQL Client instances but never calls
client.close(), which is a test resource leak. As more migration tests are added, this can
accumulate open handles in some environments and make the test suite less robust.
Code

src/lib/server/db/migration-0014.test.ts[R70-73]

+	await client.executeMultiple(PRE_0014_DDL + seedSql);
+	for (const statement of statements) await client.execute(statement);
+	return client;
+}
Relevance

●●● Strong

Straightforward test reliability fix (close handles); low-risk and aligns with making tests robust.

PR-#3

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The new migration test helper returns a Client without any cleanup, and all tests call it. A
nearby migration test file explicitly calls client.close() in a finally block, showing the
intended lifecycle management for libSQL clients in tests.

src/lib/server/db/migration-0014.test.ts[67-73]
src/lib/server/db/migration.test.ts[25-73]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`src/lib/server/db/migration-0014.test.ts` creates libSQL clients but never closes them.

## Issue Context
Another migration test already demonstrates the preferred pattern: closing the client in a `finally` block.

## Fix Focus Areas
- src/lib/server/db/migration-0014.test.ts[67-73]

### Suggested fix direction
Wrap each test body in `try/finally` and call `client.close()` in the `finally`, or add a helper that registers cleanup (e.g., returning `{ client, close }`), so every created client is deterministically closed.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


3. Relative ./migrationTestUtils import 📘 Rule violation ⚙ Maintainability
Description
src/lib/server/db/migration-0014.test.ts imports a src/lib module via a relative path instead of
the $lib alias. This violates the project’s import-path standard and can lead to inconsistent
import styles across the codebase.
Code

src/lib/server/db/migration-0014.test.ts[22]

+import { migrationStatements } from './migrationTestUtils';
Relevance

● Weak

Similar $lib-alias import-style nits in test files were previously rejected; likely won’t enforce
here.

PR-#35
PR-#50

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
PR Compliance ID 2401155 requires that imports resolving into src/lib use the $lib alias. The
new test file imports migrationTestUtils (located under src/lib/server/db/) via a relative path
./migrationTestUtils, which violates that requirement.

Rule 2401155: Use $lib alias instead of relative paths for src/lib imports
src/lib/server/db/migration-0014.test.ts[19-23]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
A module located under `src/lib` is imported using a relative path (`./migrationTestUtils`) instead of the `$lib` alias.

## Issue Context
The repository uses SvelteKit’s `$lib` alias for imports targeting `src/lib`.

## Fix Focus Areas
- src/lib/server/db/migration-0014.test.ts[19-23]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Context used
✅ Compliance rules (platform): 78 rules

To customize comments, go to the Qodo configuration screen, or learn more in the docs.

Qodo Logo

Comment thread drizzle/0014_channels_history_state.sql Outdated
Comment thread src/lib/server/db/migration-0014.test.ts
@Bonobo791

Copy link
Copy Markdown
Owner Author

Triage — bot round 1 (commit pending)

  1. CodeRabbit + Qodo (same finding) — backfill with scan_cursor NULL creates an unresumable drain state: valid. A continuation token with no boundary has no defined end state, so the backfill now requires BOTH columns non-NULL (WHERE next_page_token IS NOT NULL AND scan_cursor IS NOT NULL); such rows are skipped, not backfilled into a shape future code cannot resume. New test a drain row without a scan boundary is NOT backfilled (watched red → green; mutation-checked: dropping the extra predicate fails the test, restored green). Note: dev db applied the earlier predicate, but the backfill was vacuous there (zero mid-drain channels), so no data consequence; prod gets the fixed SQL at apply time.
  2. Qodo (informational) — unclosed test clients: fixed — every client a test opens is registered and closed in afterEach, so even a mid-test assertion failure cannot leak a handle.
  3. Amazon Q — approving review, no findings. CodeAnt/Netlify green. CodeRabbit's request-changes permission warning is a repo-app permission note, not a code finding.

Gates: npm run check 0/0, npm run test 50 files / 426 tests green, npm run build clean, codacy-analysis 0 issues.

@codeant-ai codeant-ai Bot removed the size:XXL This PR changes 1000+ lines, ignoring generated files label Aug 4, 2026
@codeant-ai codeant-ai Bot added the size:XXL This PR changes 1000+ lines, ignoring generated files label Aug 4, 2026
@sonarqubecloud

sonarqubecloud Bot commented Aug 4, 2026

Copy link
Copy Markdown

@Bonobo791
Bonobo791 merged commit d663f56 into main Aug 4, 2026
16 of 19 checks passed
@Bonobo791
Bonobo791 deleted the mt-history-state branch August 4, 2026 18:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cla-signed size:XXL This PR changes 1000+ lines, ignoring generated files

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant