Skip to content

refactor: removed dead code identified in issue - #848

Open
Arowolokehinde wants to merge 1 commit into
MostroP2P:mainfrom
Arowolokehinde:fix/dead-code-818
Open

refactor: removed dead code identified in issue #848
Arowolokehinde wants to merge 1 commit into
MostroP2P:mainfrom
Arowolokehinde:fix/dead-code-818

Conversation

@Arowolokehinde

@Arowolokehinde Arowolokehinde commented Jul 30, 2026

Copy link
Copy Markdown
  • restore_session: drop unreachable hex-validity guards on PublicKey values; nostr_sdk::PublicKey always serializes to 64-char hex so the guards could never trigger

  • admin_take_dispute: drop is_solver == 0 recheck after find_solver_pubkey; the SQL already filters WHERE is_solver == true so the Ok arm is structurally guaranteed non-zero

  • db: remove rebuild_disputes_table_without_tokens and the SQLite version-fallback branch inside migrate_remove_token_columns; DROP COLUMN is supported on all deployment targets (SQLite >= 3.35 everywhere: Ubuntu 24.04 = 3.45, Debian Bookworm = 3.40, Alpine = 3.43+)

  • dispute: propagate setup_dispute error with map_err(MostroCantDo)? instead of silently swallowing it; the old if .is_ok() pattern skipped order.update() on failure but kept running, leaving the order flags unset while still creating the dispute row

Closes #818

Summary by CodeRabbit

  • Bug Fixes
    • Dispute actions now stop and clearly report setup failures instead of continuing with incomplete processing.
    • Solver authorization handling has been updated for more consistent dispute resolution.
    • Session restoration now proceeds through the restoration workflow without unnecessary early rejection.
    • Legacy dispute data upgrades are more reliable, preserve existing records, and remove obsolete fields safely.

@coderabbitai

coderabbitai Bot commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 5dd42faa-0d0a-4e77-a6c6-c83c6869b919

📥 Commits

Reviewing files that changed from the base of the PR and between 9fc0299 and 69542b3.

📒 Files selected for processing (4)
  • src/app/admin_take_dispute.rs
  • src/app/dispute.rs
  • src/app/restore_session.rs
  • src/db.rs
🚧 Files skipped from review as they are similar to previous changes (4)
  • src/app/admin_take_dispute.rs
  • src/app/dispute.rs
  • src/app/restore_session.rs
  • src/db.rs

Included review availability: Your plan includes up to 2 reviews per rolling hour; 1 remains after this review.


Walkthrough

The pull request removes obsolete validation and fallback branches, propagates dispute setup failures, and replaces disputes-table rebuilding with transactional removal of legacy token columns.

Changes

Application and database cleanup

Layer / File(s) Summary
Solver permission gate
src/app/admin_take_dispute.rs
Solver lookup failures reject access without an additional is_solver check.
Restore session entry flow
src/app/restore_session.rs
Restore processing proceeds without local key-format validation.
Dispute setup error propagation
src/app/dispute.rs
setup_dispute failures return before the order update.
Dispute token-column migration
src/db.rs
Existing legacy token columns are dropped in one transaction. The obsolete table-rebuild test is removed.

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

Merge Risk: ⚪ Minimal · up to 69542

The current changes are merge-ready after normal checks and review; no actionable merge-blocking risk remains.

Poem

A rabbit cleared branches from the trail,
Setup errors now can’t fail.
Old token columns hop away,
Restore flows start clean today.
Squeak, squeak—less code to weigh!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly identifies the primary change: removal of dead code described in the linked issue.
Linked Issues check ✅ Passed The changes implement all four objectives in issue #818, including dead-code removal and setup error propagation.
Out of Scope Changes check ✅ Passed All reviewed changes relate directly to the dead-code cleanup and error-handling objectives in issue #818.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

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

🧹 Nitpick comments (1)
src/db.rs (1)

3410-3416: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a positive-path migration test.

With rebuild_disputes_table_preserves_rows gone, the only remaining coverage is the no-op branch — the actual drop path (and row preservation) is untested. A test that adds the legacy columns back, inserts a row, runs the migration, and asserts both columns are gone while the row survives would keep coverage on the reachable logic this PR is consolidating onto.

🧪 Sketch of the missing test
#[tokio::test]
async fn migrate_remove_token_columns_drops_legacy_columns_and_preserves_rows() {
    let pool = migrated_pool().await;
    sqlx::query("ALTER TABLE disputes ADD COLUMN buyer_token INTEGER")
        .execute(&pool)
        .await
        .unwrap();
    sqlx::query("ALTER TABLE disputes ADD COLUMN seller_token INTEGER")
        .execute(&pool)
        .await
        .unwrap();
    // insert a dispute row here, then:
    migrate_remove_token_columns(&pool).await.unwrap();
    assert!(!table_column_exists(&pool, "disputes", "buyer_token").await.unwrap());
    assert!(!table_column_exists(&pool, "disputes", "seller_token").await.unwrap());
    // assert the inserted row is still present
}
🤖 Prompt for 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.

In `@src/db.rs` around lines 3410 - 3416, Add a positive-path test alongside
migrate_remove_token_columns_is_noop_without_token_columns that restores both
legacy token columns, inserts a disputes row, runs migrate_remove_token_columns,
and verifies buyer_token and seller_token are removed while the inserted row
remains.
🤖 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.

Nitpick comments:
In `@src/db.rs`:
- Around line 3410-3416: Add a positive-path test alongside
migrate_remove_token_columns_is_noop_without_token_columns that restores both
legacy token columns, inserts a disputes row, runs migrate_remove_token_columns,
and verifies buyer_token and seller_token are removed while the inserted row
remains.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 46a3b8f6-0bd3-4fdf-b711-402423c284ff

📥 Commits

Reviewing files that changed from the base of the PR and between 94e736a and 9fc0299.

📒 Files selected for processing (4)
  • src/app/admin_take_dispute.rs
  • src/app/dispute.rs
  • src/app/restore_session.rs
  • src/db.rs
💤 Files with no reviewable changes (1)
  • src/app/restore_session.rs

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

Reviewed the four changes against main. The substance is correct — both dead-code claims hold up under checking — but I found three things worth surfacing before merge.

Verified as genuinely unreachable (both claims correct):

  • restore_session.rs — the hex/length guards were dead. master_key and trade_key come from event.identity / event.sender, which are already nostr_sdk::PublicKey; to_string() on those can only ever produce 64-char hex, so neither guard could fire. The PublicKey::from_hex calls further down in send_restore_session_response / send_restore_session_timeout still validate the string form where it actually matters, and their tests still cover the invalid-key path.
  • admin_take_dispute.rs — the is_solver == 0 recheck was structurally unreachable: find_solver_pubkey queries WHERE pubkey == ?1 AND is_solver == true via fetch_one, so an Ok arm necessarily carries is_solver == true.

Three findings:

1. The branch is 32 commits behind upstream/main and needs a rebase before merge. Side effect while reviewing: the suite here runs 1045 tests vs 1187 on current main, which initially looked like deleted test coverage and isn't — it's just the older base. Worth rebasing so a reviewer doesn't have to rule that out.

2. The SQLite justification reaches the right conclusion from the wrong premise. The commit message argues DROP COLUMN is safe by enumerating distro versions (Ubuntu 24.04 = 3.45, Bookworm = 3.40, Alpine 3.43+). But mostrod never uses the host's SQLite: libsqlite3-sys 0.37.0 compiles the bundled amalgamation (cargo:rerun-if-changed=sqlite3/sqlite3.c) and links it statically (cargo:rustc-link-lib=static=sqlite3), pinning SQLite 3.51.3 at compile time. So removing the fallback is safer than argued — it cannot depend on the deployment environment at all. Only flagging because that reasoning will be the record for whoever revisits this: the distro-version framing implies a host dependency that doesn't exist, and would send someone re-adding a fallback for a machine with old system SQLite.

3. The dispute.rs change is a behavior fix, not dead-code removal — you do say so in the description, so this is context for @grunch rather than a correction. Tracing it: setup_dispute returns Err(CantDoReason::DisputeCreationError) only when the disputing party's flag was already set. Old code skipped order.update() but kept going and still created the dispute row; new code returns early. Returning early is right.

The nuance: dispute_action already guards at the top with find_dispute_by_order_id(...).is_ok()DisputeAlreadyExists, so the normal double-dispute path never reaches setup_dispute twice. That means the Err branch is only reachable from an inconsistent DB state (order flag set with no dispute row), where the old code silently self-healed and the new code hard-fails with DisputeCreationError — leaving that user unable to open a dispute until the state is fixed. I think failing loudly on a violated precondition is the correct call, and it's a state that shouldn't arise. Just worth a maintainer knowing it's the trade-off being made rather than discovering it from a report later.

Checks on the branch as-is: 1045 passed / 0 failed, cargo clippy --all-targets -- -D warnings clean, cargo fmt --check clean. The three migrate_remove_token_columns tests (no-op, both-columns, single-column) survive the rewrite, so the migration keeps its coverage.

Nothing here is a blocker on the code itself — my only actual ask is the rebase, plus optionally correcting the SQLite rationale so it doesn't mislead later. Contributor, not a maintainer, so this is a technical second opinion rather than a merge signal.

- restore_session: drop unreachable hex-validity guards on PublicKey
  values; nostr_sdk::PublicKey always serializes to 64-char hex so the
  guards could never trigger

- admin_take_dispute: drop is_solver == 0 recheck after
  find_solver_pubkey; the SQL already filters WHERE is_solver == true
  so the Ok arm is structurally guaranteed non-zero

- db: remove rebuild_disputes_table_without_tokens and the SQLite
  version-fallback branch inside migrate_remove_token_columns; DROP
  COLUMN is safe unconditionally - mostrod links libsqlite3-sys with \
  the bundled SQLite source (3.51.3 compiled statically into the binary),\
  so runtime behavior is independent of any host SQLite version

- dispute: propagate setup_dispute error with map_err(MostroCantDo)?
  instead of silently swallowing it; the old if .is_ok() pattern
  skipped order.update() on failure but kept running, leaving the
  order flags unset while still creating the dispute row
@Arowolokehinde

Copy link
Copy Markdown
Author

Thank you for the feedback @ToRyVand
i just rebased onto upstream/main - 1209 tests passing, cargo fmt --check and cargo clippy clean.

Also corrected the SQLite rationale in the commit message. The distro-version framing was wrong — mostrod links libsqlite3-sys 0.37.0 which compiles and statically links the bundled SQLite source (3.51.3) at build time, so the fallback removal is independent of any host SQLite version. Updated the message to reflect that.

@ToRyVand

Copy link
Copy Markdown
Contributor

Verified independently against 69542b3: cargo test --all → 1209 passed, 3 ignored; cargo fmt --check and cargo clippy --all-targets -- -D warnings both clean. Confirmed libsqlite3-sys 0.37.0 in Cargo.lock statically links the bundled SQLite source, so the corrected commit message rationale checks out.

One note: rebase was onto main@2f2b813 — 3 commits have landed since, including #888 which also touches src/db.rs. Rebased locally against current main and it applies clean, no conflicts, just flagging in case this sits a while longer before merge.

ToRyVand added a commit to ToRyVand/mostro that referenced this pull request Aug 19, 2026
cargo mutants left the `60 * 60` timeout computation untestable inline.
Extract it as RESTORE_SESSION_TIMEOUT_SECS with a test that pins the value.

The hex-validation extraction this commit originally carried is dropped:
its only two call sites are the guards MostroP2P#848 removes as unreachable
(`identity`/`sender` are `PublicKey`, so `.to_string()` is always 64 hex),
and the two invalid-key tests it added already exist on main from MostroP2P#803.
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.

[LOW] Dead code: unreachable hex guards, is_solver==0 recheck, SQLite rebuild fallback, swallowed setup_dispute error

2 participants