Skip to content
Merged
157 changes: 125 additions & 32 deletions crates/core/src/rpc/surfnet_cheatcodes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1428,11 +1428,14 @@ pub trait SurfnetCheatcodes {
/// - `fetchBeforeUse`: If true, fetch fresh account data just before transaction execution (useful for price feeds, oracle updates, and dynamic balances)
/// - `account`: Account address (either `{ "pubkey": "..." }` or `{ "pda": { "programId": "...", "seeds": [...] } }`)
/// - `tags`: Array of tags for categorization
/// - `slot` (optional): The base slot from which relative slot offsets are calculated. If omitted, uses the current slot.
/// - `slot` (optional): The base slot from which relative slot offsets are calculated. If omitted, the next slot the surfnet produces. A base slot that is already produced is rejected with InvalidParams.
///
/// ## Returns
/// A `RpcResponse<()>` indicating whether the Scenario registration was successful.
///
/// Overrides are applied when the surfnet produces their slot; nothing is applied during this call.
/// `surfnet_timeTravel` produces only the next slot before it jumps, so overrides scheduled in the slots it skips are never applied; step one slot at a time.
///
/// ## Example Request (with slot)
/// ```json
/// {
Expand Down Expand Up @@ -1464,7 +1467,7 @@ pub trait SurfnetCheatcodes {
/// ],
/// "tags": ["defi", "price-feed"]
/// },
/// 355684457
/// 355684458
/// ]
/// }
/// ```
Expand Down Expand Up @@ -2517,37 +2520,14 @@ impl SurfnetCheatcodes for SurfnetCheatcodesRpc {
scenario: Scenario,
slot: Option<Slot>,
) -> BoxFuture<Result<RpcResponse<()>>> {
let SurfnetRpcContext {
svm_locker,
remote_ctx,
} = match meta.get_rpc_context(CommitmentConfig::confirmed()) {
Ok(res) => res,
Err(e) => return e.into(),
};
let SurfnetRpcContext { svm_locker, .. } =
match meta.get_rpc_context(CommitmentConfig::confirmed()) {
Ok(res) => res,
Err(e) => return e.into(),
};

Box::pin(async move {
// Get the base slot for registration (either provided or current)
let base_slot = slot.unwrap_or_else(|| svm_locker.get_latest_absolute_slot());

// Register the scenario with explicit base slot
svm_locker
.register_scenario(scenario, Some(base_slot))
.map_err(|e| jsonrpc_core::Error {
code: jsonrpc_core::ErrorCode::InternalError,
message: format!("Failed to register scenario: {}", e),
data: None,
})?;

// Immediately materialize overrides for the BASE slot (not current slot)
// This ensures slot 0's override is applied right away
svm_locker
.materialize_overrides_for_slot(&remote_ctx, base_slot)
.await
.map_err(|e| jsonrpc_core::Error {
code: jsonrpc_core::ErrorCode::InternalError,
message: format!("Failed to materialize initial overrides: {}", e),
data: None,
})?;
svm_locker.register_scenario(scenario, slot)?;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

The response only reports get_latest_absolute_slot(), so callers can't tell which base slot was chosen, and the docs tell them to wait for that slot. Return the base slot from register_scenario, e.g. SurfpoolResult<Slot>, and include it in the response (as the value or in the context). That spares SDK and Studio callers from assuming context.slot + 1, which a block produced between registration and response would make wrong.


Ok(cheatcode_response(
svm_locker.get_latest_absolute_slot(),
Expand Down Expand Up @@ -2583,7 +2563,8 @@ mod tests {

use super::*;
use crate::{
rpc::surfnet_cheatcodes::SurfnetCheatcodesRpc, tests::helpers::TestSetup,
rpc::surfnet_cheatcodes::SurfnetCheatcodesRpc,
tests::helpers::{TestSetup, UNHEALTHY_OFFSET, scheduled_override_fixture},
types::confidential_key_signature,
};

Expand Down Expand Up @@ -6196,4 +6177,116 @@ mod tests {
"the wrong aesKey should fail rather than decrypt"
);
}

#[tokio::test(flavor = "multi_thread")]
async fn test_register_scenario_applies_overrides_when_the_next_slot_is_produced() {
let client = TestSetup::new(SurfnetCheatcodesRpc::empty());
let (account_pubkey, instance) = client
.context
.svm_locker
.with_svm_writer(scheduled_override_fixture);
let account = || {
client.context.svm_locker.with_svm_reader(|svm_reader| {
svm_reader
.inner
.get_account(&account_pubkey)
.unwrap()
.unwrap()
})
};
let scheduled_slots = || {
client
.context
.svm_locker
.with_svm_reader(|svm_reader| svm_reader.scheduled_overrides.keys().unwrap())
};
let before = account();
let mut scenario = Scenario::new("next slot".to_string(), String::new());
scenario.add_override(instance);

let response = client
.rpc
.register_scenario(Some(client.context.clone()), scenario, None)
.await
.expect("registering without a slot should succeed");

assert_eq!(response.context.slot, 123);
assert_eq!(account(), before, "registering must not apply anything");
assert_eq!(scheduled_slots(), vec![124]);

client
.context
.svm_locker
.confirm_current_block(&None)
.await
.unwrap();

assert_eq!(
&account().data[UNHEALTHY_OFFSET..UNHEALTHY_OFFSET + 16],
&1_234u128.to_le_bytes(),
"producing slot 124 applies its override"
);
assert!(scheduled_slots().is_empty());
}

#[tokio::test(flavor = "multi_thread")]
async fn test_register_scenario_rejects_a_produced_base_slot() {
let client = TestSetup::new(SurfnetCheatcodesRpc::empty());
let (_, instance) = client
.context
.svm_locker
.with_svm_writer(scheduled_override_fixture);

for produced_slot in [123, 100] {
let mut scenario = Scenario::new("produced slot".to_string(), String::new());
scenario.add_override(instance.clone());

let error = client
.rpc
.register_scenario(Some(client.context.clone()), scenario, Some(produced_slot))
.await
.expect_err("a base slot that is already produced must be rejected");

assert_eq!(error.code, jsonrpc_core::ErrorCode::InvalidParams);
assert_eq!(
error.message,
format!("base slot {produced_slot} is already produced; the next slot is 124")
);
}
let scheduled_slots = client
.context
.svm_locker
.with_svm_reader(|svm_reader| svm_reader.scheduled_overrides.keys().unwrap());
assert!(scheduled_slots.is_empty());
}

#[tokio::test(flavor = "multi_thread")]
async fn test_register_scenario_rejects_a_relative_slot_that_overflows() {
let client = TestSetup::new(SurfnetCheatcodesRpc::empty());
let (_, instance) = client
.context
.svm_locker
.with_svm_writer(scheduled_override_fixture);
let mut scenario = Scenario::new("overflow".to_string(), String::new());
scenario.add_override(instance.clone());
let mut far = instance;
far.scenario_relative_slot = u64::MAX;
scenario.add_override(far);

let error = client
.rpc
.register_scenario(Some(client.context.clone()), scenario, None)
.await
.expect_err("a relative slot that overflows must be rejected");

assert_eq!(error.code, jsonrpc_core::ErrorCode::InvalidParams);
let scheduled_slots = client
.context
.svm_locker
.with_svm_reader(|svm_reader| svm_reader.scheduled_overrides.keys().unwrap());
assert!(
scheduled_slots.is_empty(),
"nothing may be scheduled when one override is rejected"
);
}
}
7 changes: 5 additions & 2 deletions crates/core/src/scenarios/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,11 @@ whole struct or array) also works, but it must be **complete** - every field of
padding included - because the account is re-encoded with Borsh. An out-of-range index or a
non-numeric segment on an array is a hard error, never a silent write elsewhere.

An override is applied once. Its resulting account state remains in later slots until a transaction
or another override writes that account again.
An override is applied once, when the surfnet produces its slot; nothing is applied during the
registration call. Its resulting account state remains in later slots until a transaction or another
override writes that account again.
`surfnet_timeTravel` produces only the next slot before it jumps, so overrides scheduled in the slots
it skips are never applied; step one slot at a time to play a scenario under a paused clock.

### Kamino integration tests

Expand Down
17 changes: 15 additions & 2 deletions crates/core/src/surfnet/locker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2855,13 +2855,26 @@ impl SurfnetSvmLocker {
self.with_svm_reader(Self::offline_account_owners)
}

/// Registers a scenario for execution
/// Schedules a scenario's overrides from `slot`, or from the next slot when omitted.
/// A base slot that is already produced is rejected: nothing would ever apply it.
pub fn register_scenario(
&self,
scenario: surfpool_types::Scenario,
slot: Option<Slot>,
) -> SurfpoolResult<()> {
self.with_svm_writer(move |svm_writer| svm_writer.register_scenario(scenario, slot))
self.with_svm_writer(move |svm_writer| {
let current_slot = svm_writer.get_latest_absolute_slot();
let next_slot = current_slot
.checked_add(1)
.ok_or_else(|| SurfpoolError::internal("the slot counter overflowed"))?;
let base_slot = slot.unwrap_or(next_slot);
if base_slot <= current_slot {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

This rejects slots that are already produced, but nothing guards against a slot the clock will skip. Time travel runs confirm_current_block once, which applies current+1, and then calls set_latest_absolute_slot(target). Anything scheduled in (current+1, target] is never applied and stays in scheduled_overrides. Since the first column now depends on slot production too, consider applying every pending slot <= new_slot during time travel, or document this limitation next to the rejection message.

return Err(SurfpoolError::invalid_params(format!(
"base slot {base_slot} is already produced; the next slot is {next_slot}"
)));
}
svm_writer.register_scenario(scenario, Some(base_slot))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

The base-slot check validates input up front, but svm.register_scenario still stores overrides one by one, and a later base + relative overflow fails with SurfpoolError::internal. When that happens:

  1. The scenario is left partly scheduled, because the overrides before the failing one are already stored.
  2. A bad caller input comes back as InternalError instead of InvalidParams.

Now that this function owns RPC validation, it's cheap to check every base_slot.checked_add(o.scenario_relative_slot) before calling into the SVM and return invalid_params on failure.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

The locker always passes Some(base_slot) here, but SurfnetSvm::register_scenario still defaults None to the current slot (svm.rs:4688), which is the old behaviour. Consider making the SVM parameter non-optional (base_slot: Slot) so the two layers can't drift apart. The pump and phoenix tests already pass explicit slots.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

SurfnetSvm::register_scenario (svm.rs:4989) still defaults None to the current slot. This locker always passes Some, so the RPC path is fine. But the two layers now have different defaults, and any direct SVM caller (like the pump tests) gets the old "already produced" behaviour without being told. Make the SVM method take a Slot instead of Option<Slot>, or give both layers the same default.

})
}

/// Materializes overrides for a specific slot (not necessarily the current slot)
Expand Down
78 changes: 18 additions & 60 deletions crates/core/src/surfnet/svm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4996,17 +4996,22 @@ impl SurfnetSvm {
base_slot
);

// Schedule overrides by adding base slot to their scenario-relative slots
// Every slot is checked before anything is stored, so a bad override leaves no partial plan.
let mut scheduled = Vec::with_capacity(scenario.overrides.len());
for override_instance in scenario.overrides {
let scenario_relative_slot = override_instance.scenario_relative_slot;
// Both operands are caller-supplied, so the sum has to be checked.
let absolute_slot = base_slot.checked_add(scenario_relative_slot).ok_or_else(|| {
SurfpoolError::internal(format!(
SurfpoolError::invalid_params(format!(
"Override {} cannot be scheduled: base slot {} plus relative slot {} overflows",
override_instance.id, base_slot, scenario_relative_slot
))
})?;
scheduled.push((absolute_slot, override_instance));
}

for (absolute_slot, override_instance) in scheduled {
let scenario_relative_slot = override_instance.scenario_relative_slot;
debug!(
"Scheduling override at absolute slot {} (base {} + relative {})",
absolute_slot, base_slot, scenario_relative_slot
Expand Down Expand Up @@ -5053,7 +5058,9 @@ mod tests {

use super::*;
use crate::{
storage::tests::TestType, surfnet::locker::SurfnetSvmLocker, tests::helpers::canned_rpc,
storage::tests::TestType,
surfnet::locker::SurfnetSvmLocker,
tests::helpers::{UNHEALTHY_OFFSET, canned_rpc, scheduled_override_fixture},
};

#[test]
Expand Down Expand Up @@ -8646,62 +8653,10 @@ mod tests {
assert_eq!(restored_account.lamports, 1_000_000);
}

/// `Obligation.unhealthy_borrow_value_sf` (u128), counting the discriminator.
const UNHEALTHY_OFFSET: usize = 2256;

/// A zeroed Kamino `Obligation` owned by klend. `SurfnetSvm::default()` already registers
/// the bundled template IDLs, so klend's is resolvable by owner program.
fn scheduled_override_fixture() -> (
SurfnetSvm,
Pubkey,
surfpool_types::OverrideInstance,
Receiver<GeyserEvent>,
) {
let (mut surfnet_svm, _simnet_events_rx, geyser_events_rx) = SurfnetSvm::default();

let klend = Pubkey::from_str_const("KLend2g3cP87fffoy8q1mQqGKjrxjC8boSyAYavgmjD");
let idl: Idl = serde_json::from_str(crate::scenarios::registry::KAMINO_V1_IDL_CONTENT)
.expect("kamino idl");
let obligation_disc = &idl
.accounts
.iter()
.find(|a| a.name == "Obligation")
.expect("Obligation account")
.discriminator;

let mut data = vec![0u8; 3344];
data[..8].copy_from_slice(obligation_disc);

let account_pubkey = Pubkey::new_unique();
surfnet_svm
.inner
.set_account(
account_pubkey,
Account {
lamports: 1_000_000,
data,
owner: klend,
executable: false,
rent_epoch: 0,
},
)
.expect("set obligation account");

let instance = surfpool_types::OverrideInstance::new(
"kamino-obligation-health".to_string(),
0,
surfpool_types::AccountAddress::Pubkey(account_pubkey.to_string()),
)
.with_values(HashMap::from([(
"unhealthy_borrow_value_sf".to_string(),
serde_json::json!(1_234u64),
)]));
(surfnet_svm, account_pubkey, instance, geyser_events_rx)
}

#[tokio::test]
async fn test_scenario_relative_slot_overflow_is_an_error_not_a_wrap() {
let (mut svm, account_pubkey, _instance, _geyser_events_rx) = scheduled_override_fixture();
let (mut svm, _simnet_events_rx, _geyser_events_rx) = SurfnetSvm::default();
let (account_pubkey, _instance) = scheduled_override_fixture(&mut svm);

let mut far = surfpool_types::OverrideInstance::new(
"kamino-obligation-health".to_string(),
Expand All @@ -8726,7 +8681,8 @@ mod tests {
#[tokio::test]
async fn forged_scenario_override_notifies_subscribers_and_geyser_once() {
const SLOT: u64 = 500;
let (mut svm, account_pubkey, instance, geyser_events_rx) = scheduled_override_fixture();
let (mut svm, _simnet_events_rx, geyser_events_rx) = SurfnetSvm::default();
let (account_pubkey, instance) = scheduled_override_fixture(&mut svm);
let account_updates = svm.subscribe_for_account_updates(&account_pubkey, None);
let program_updates = svm.subscribe_for_program_updates(
&Pubkey::from_str_const("KLend2g3cP87fffoy8q1mQqGKjrxjC8boSyAYavgmjD"),
Expand Down Expand Up @@ -8786,7 +8742,8 @@ mod tests {
// immediately precedes unhealthy_borrow_value_sf in the Obligation layout
const ALLOWED_OFFSET: usize = UNHEALTHY_OFFSET - 16;

let (mut svm, account_pubkey, first, _geyser_events_rx) = scheduled_override_fixture();
let (mut svm, _simnet_events_rx, _geyser_events_rx) = SurfnetSvm::default();
let (account_pubkey, first) = scheduled_override_fixture(&mut svm);
let mut first = first;
first.fetch_before_use = true;

Expand Down Expand Up @@ -9130,7 +9087,8 @@ mod tests {
#[tokio::test]
async fn an_idl_override_notifies_account_subscribers() {
const SLOT: u64 = 500;
let (mut svm, account_pubkey, instance, _geyser_events_rx) = scheduled_override_fixture();
let (mut svm, _simnet_events_rx, _geyser_events_rx) = SurfnetSvm::default();
let (account_pubkey, instance) = scheduled_override_fixture(&mut svm);
let updates =
svm.subscribe_for_account_updates(&account_pubkey, Some(UiAccountEncoding::Base64));
svm.scheduled_overrides.store(SLOT, vec![instance]).unwrap();
Expand Down
Loading
Loading