Skip to content

Comments

fix: MagicContext's data reset on restart#986

Open
taco-paco wants to merge 3 commits intomasterfrom
fix/magic-context-reset
Open

fix: MagicContext's data reset on restart#986
taco-paco wants to merge 3 commits intomasterfrom
fix/magic-context-reset

Conversation

@taco-paco
Copy link
Contributor

@taco-paco taco-paco commented Feb 19, 2026

Summary

Fixes MagicContext reset on restart.

Compatibility

  • No breaking changes
  • Config change (describe):
  • Migration needed (describe):

Testing

  • tests (or explain)

Checklist

Summary by CodeRabbit

  • Refactor
    • Preserve existing account data when funding; only create accounts when absent.
    • Improve initialization of the funding context and set its owner to ensure consistent behavior.
    • Result: fewer unintended data overwrites and more reliable account funding for end users.

@taco-paco taco-paco self-assigned this Feb 19, 2026
@github-actions
Copy link

github-actions bot commented Feb 19, 2026

Manual Deploy Available

You can trigger a manual deploy of this PR branch to testnet:

Deploy to Testnet 🚀

Alternative: Comment /deploy on this PR to trigger deployment directly.

⚠️ Note: Manual deploy requires authorization. Only authorized users can trigger deployments.

Comment updated automatically when the PR is synchronized.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 19, 2026

📝 Walkthrough

Walkthrough

The PR changes how the MAGIC_CONTEXT_PUBKEY account is funded and created in magicblock-api/src/fund_account.rs. fund_account_with_data now returns early if the target account already exists instead of overwriting it; when missing, it creates a new AccountSharedData. fund_magic_context introduces a CONTEXT_LAMPORTS constant (used instead of u64::MAX), replaces an unwrap with expect("magic context should have been created"), and explicitly sets the account owner on the created magic context. Function signatures are unchanged.

Assessment against linked issues

Objective Addressed Explanation
Prevent MagicContext from resetting on restart by preserving existing account state [#984]
✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/magic-context-reset

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 and usage tips.

Copy link
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.

Actionable comments posted: 1

Caution

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

⚠️ Outside diff range comments (1)
magicblock-api/src/fund_account.rs (1)

25-39: 🧹 Nitpick | 🔵 Trivial

fund_account_with_data unconditionally zeros existing account data — the root cause of issue #984.

This function's "exists" branch (line 33) resets data to zeroes even for pre-existing accounts. The PR correctly bypasses it for MagicContext, but any future caller relying on data preservation for a sized account will hit the same trap. Consider either renaming the function to clarify it always resets data, or adding a preserve_data flag / a separate fund_account_preserve_data helper to prevent repeat bugs.

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

In `@magicblock-api/src/fund_account.rs` around lines 25 - 39, The function
fund_account_with_data currently overwrites existing account data by calling
set_data(vec![0; size]) in the exists branch (accountsdb.get_account ->
acc.set_data), which causes unintended zeroing; update this function to either
(A) accept a preserve_data: bool parameter and only call acc.set_data when
preserve_data is false or when the existing data length differs from size, or
(B) split into two helpers (fund_account_with_zeroed_data and
fund_account_preserve_data) and move the zeroing behavior into the former;
ensure callers of fund_account_with_data (and any tests) are updated to use the
appropriate new API and keep the insert_account call (accountsdb.insert_account)
unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@magicblock-api/src/fund_account.rs`:
- Around line 85-89: The AccountSharedData creation for the MagicContext uses
the system program as owner; update the owner argument in the
AccountSharedData::new call that uses CONTEXT_LAMPORTS and MagicContext::SIZE to
pass &magic_program::id() (the magic program ID) instead of &Default::default()
so the account owner matches the tests and the ephemeral vault account.

---

Outside diff comments:
In `@magicblock-api/src/fund_account.rs`:
- Around line 25-39: The function fund_account_with_data currently overwrites
existing account data by calling set_data(vec![0; size]) in the exists branch
(accountsdb.get_account -> acc.set_data), which causes unintended zeroing;
update this function to either (A) accept a preserve_data: bool parameter and
only call acc.set_data when preserve_data is false or when the existing data
length differs from size, or (B) split into two helpers
(fund_account_with_zeroed_data and fund_account_preserve_data) and move the
zeroing behavior into the former; ensure callers of fund_account_with_data (and
any tests) are updated to use the appropriate new API and keep the
insert_account call (accountsdb.insert_account) unchanged.

@taco-paco taco-paco marked this pull request as ready for review February 20, 2026 06:24
Copy link
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.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@magicblock-api/src/fund_account.rs`:
- Line 82: The code currently calls .expect() in fund_magic_context which can
panic if insert_account failed (its Result was discarded with let _ = ...);
change fund_magic_context(accountsdb: &AccountsDb) to return ApiResult<()> (or
the crate's error type), stop discarding the Result from insert_account (use ?
to propagate errors), and replace the .expect("magic context should have been
created") retrieval with a fallible call that uses ? to return a proper error
instead of panicking; update callers to handle the ApiResult<()> accordingly
(references: function fund_magic_context, the earlier insert_account call, and
the retrieval after fund_account_with_data).

@GabrielePicco GabrielePicco added the P1 High priority label Feb 21, 2026
@@ -30,7 +30,6 @@ pub(crate) fn fund_account_with_data(
) {
let account = if let Some(mut acc) = accountsdb.get_account(pubkey) {
Copy link
Collaborator

@bmuddha bmuddha Feb 23, 2026

Choose a reason for hiding this comment

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

I meant performing an early return here, so that we don't modify existing account, for validator authority we ideally need a way to keep the balance intact, e.g. when an account is removed from accountsdb/closed the lamports should be refunded to validator keypair (as it acted as sponsor during account creation), but that's irrelevant to this task, and it's not like it's physically possible to exhaust u64::MAX lamports in any feasable amount of time.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Makes sense, done

Copy link
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)
magicblock-api/src/fund_account.rs (1)

78-85: ⚠️ Potential issue | 🟠 Major

.expect() in production code remains a MAJOR issue — changing from .unwrap() to .expect() is insufficient.

Although the .expect() is logically unreachable after the new fund_account_with_data (the account is guaranteed to exist), the panic is still a silent discard of any storage failure from insert_account on line 35. If that insert fails, get_account returns None and this panics at startup. The function should return ApiResult<()> and propagate errors.

As per coding guidelines: "Treat any usage of .unwrap() or .expect() in production Rust code as a MAJOR issue."

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

In `@magicblock-api/src/fund_account.rs` around lines 78 - 85, The code in
fund_account.rs panics via accountsdb.get_account(...).expect(...) which must be
replaced with proper error propagation: change the surrounding function (e.g.,
fund_account_with_data or its caller) to return ApiResult<()>, replace the
expect on accountsdb.get_account(&magic_program::MAGIC_CONTEXT_PUBKEY) with
pattern matching or .ok_or(...) to return a descriptive ApiError if the account
is missing, and handle the result of accountsdb.insert_account(...) by
propagating any insertion error instead of discarding it; update uses of
magic_context.set_delegated and set_owner accordingly after successful retrieval
and ensure failures return Err(...) rather than panicking.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@magicblock-api/src/fund_account.rs`:
- Around line 78-85: The code in fund_account.rs panics via
accountsdb.get_account(...).expect(...) which must be replaced with proper error
propagation: change the surrounding function (e.g., fund_account_with_data or
its caller) to return ApiResult<()>, replace the expect on
accountsdb.get_account(&magic_program::MAGIC_CONTEXT_PUBKEY) with pattern
matching or .ok_or(...) to return a descriptive ApiError if the account is
missing, and handle the result of accountsdb.insert_account(...) by propagating
any insertion error instead of discarding it; update uses of
magic_context.set_delegated and set_owner accordingly after successful retrieval
and ensure failures return Err(...) rather than panicking.

ℹ️ Review info

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c0fbbde and 8e85535.

📒 Files selected for processing (1)
  • magicblock-api/src/fund_account.rs

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P1 High priority

Projects

None yet

Development

Successfully merging this pull request may close these issues.

bug: MagicContext resets on restart

3 participants