Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
141 changes: 141 additions & 0 deletions .github/workflows/claude-review.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
name: Perform a code review when a pull request is created.
on:
pull_request:
types: [opened, synchronize, reopened, ready_for_review]

jobs:
claude:
# Skip drafts, and skip fork PRs: on `pull_request` they don't get the
# ANTHROPIC_API_KEY secret, so the review would only fail.
if: >-
!github.event.pull_request.draft &&
github.event.pull_request.head.repo.full_name == github.repository
runs-on: ubuntu-latest
permissions:
contents: read
outputs:
structured_output: ${{ steps.run_claude.outputs.structured_output }}
steps:
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
with:
# Explicitly check out the PR's merge commit.
ref: refs/pull/${{ github.event.pull_request.number }}/merge
persist-credentials: false

- name: Pre-fetch base and head refs for the PR
env:
PR_BASE_REF: ${{ github.event.pull_request.base.ref }}
PR_NUMBER: ${{ github.event.pull_request.number }}
run: |
# Pass GitHub expressions through env and quote shell expansions.
git fetch --no-tags origin \
"$PR_BASE_REF" \
"+refs/pull/$PR_NUMBER/head"

# If you want Claude to build and run code, install any dependencies that
# need to be downloaded before the "Run Claude" step, and add the commands
# it may run to --allowedTools below (e.g. "Bash(npm test:*)"). Any tool
# not listed there is denied.

- name: Run Claude
id: run_claude
uses: anthropics/claude-code-action@86d88e619d8e6caf07b5c3944dd14f441c533718 # v1.0.243
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
# Use this job's read-only token instead of the Claude GitHub App,
# which needs `id-token: write` and would get write access.
github_token: ${{ github.token }}
prompt: |
This is PR #${{ github.event.pull_request.number }} for ${{ github.repository }}.

Review ONLY the changes introduced by the PR, so consider:
git log --oneline ${{ github.event.pull_request.base.sha }}...${{ github.event.pull_request.head.sha }}
git diff ${{ github.event.pull_request.base.sha }}...${{ github.event.pull_request.head.sha }}

Suggest any improvements, potential bugs, or issues.
Be concise and specific in your feedback.

Return your review in two parts:
- `summary`: a short Markdown overview of the PR and your overall assessment.
- `comments`: one entry per specific issue, anchored to the line it concerns.
`path` is relative to the repository root. `line` is the line number in
the PR head version of the file (${{ github.event.pull_request.head.sha }}),
and must be a line shown in the diff above. The working tree is the merge
commit, so its line numbers can differ; check them with
`git show ${{ github.event.pull_request.head.sha }}:<path>`.
Put issues that don't belong to a single line in `summary` instead.

Pull request title and body:
----
${{ github.event.pull_request.title }}
${{ github.event.pull_request.body }}
claude_args: |
--allowedTools "Read,Grep,Glob,Bash(git log:*),Bash(git diff:*),Bash(git show:*)"
--json-schema '{
"type": "object",
"properties": {
"summary": {
"type": "string",
"description": "Overall review as Markdown, posted as the review body."
},
"comments": {
"type": "array",
"description": "Inline comments, each anchored to one line of the PR diff.",
"items": {
"type": "object",
"properties": {
"path": { "type": "string", "description": "File path relative to the repository root." },
"line": { "type": "integer", "minimum": 1, "description": "Line number in the PR head version of the file. Must be within the diff." },
"body": { "type": "string", "description": "The comment, as Markdown." }
},
"required": ["path", "line", "body"]
}
}
},
"required": ["summary", "comments"]
}'

post_feedback:
runs-on: ubuntu-latest
needs: claude
if: needs.claude.outputs.structured_output != ''
permissions:
issues: write
pull-requests: write
steps:
- name: Report Claude feedback
uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7.1.0
env:
CLAUDE_STRUCTURED_OUTPUT: ${{ needs.claude.outputs.structured_output }}
with:
github-token: ${{ github.token }}
script: |
const { summary = '', comments = [] } = JSON.parse(process.env.CLAUDE_STRUCTURED_OUTPUT);
const pr = context.payload.pull_request;
if (!summary.trim() && comments.length === 0) {
core.info('Claude returned an empty review; nothing to post.');
return;
}

try {
await github.rest.pulls.createReview({
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: pr.number,
commit_id: pr.head.sha,
event: 'COMMENT',
body: summary.trim() || 'See inline comments.',
comments: comments.map(({ path, line, body }) => ({ path, line, side: 'RIGHT', body })),
});
} catch (error) {
// GitHub rejects the whole review if any comment points outside the
// diff. Fall back to a single PR comment so no feedback is lost.
core.warning(`Could not post inline review (${error.message}); posting a plain comment instead.`);
const details = comments.map(({ path, line, body }) => `**\`${path}:${line}\`**\n\n${body}`);
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: pr.number,
body: [summary.trim(), ...details].filter(Boolean).join('\n\n---\n\n'),
});
}
7 changes: 7 additions & 0 deletions crates/core/src/scenarios/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,13 @@ never takes effect. An account not yet in the surfnet is fetched from the remote
or its owner with its owned accounts, is marked offline. Keep-alive is kept in memory only: after a restart on a persistent database it stops
until an importing override plays again.

An override can turn keep-alive off for the account it writes with `"keepAlive": []`, as `keep_alive: []`
does for a template. From that override's slot on, nothing rewrites the account, including keep-alive
that earlier overrides started, so its fields age as the clock moves on, for example to test a stale
price. The override must write a value for this to take effect. Without the field, the template's
keep-alive applies as usual. To keep fresh an account a transaction reads but no scenario names, give
it an override of its own.

### Override Templates
Directly using the `surfnet_registerScenario` endpoint requires building out a map of account keys that are specific to the schema of the account that is being written to.
This is a cumbersome process in most cases.
Expand Down
2 changes: 2 additions & 0 deletions crates/core/src/scenarios/keep_alive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ pub struct KeepAliveSource {
pub address: Pubkey,
/// The override's values, which input and PDA addresses resolve against.
pub values: HashMap<String, serde_json::Value>,
/// The override set `keepAlive: []`: keep-alive stops rewriting `address`.
pub off: bool,
}

/// Binds a template's keep-alive import to the account it rewrites every slot, resolved when an
Expand Down
60 changes: 57 additions & 3 deletions crates/core/src/surfnet/svm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3530,15 +3530,22 @@ impl SurfnetSvm {

// Joins keep-alive only once its write succeeds: a failed override leaves the account as
// if no scenario had touched it.
let keep_alive_off = override_instance
.keep_alive
.as_ref()
.is_some_and(Vec::is_empty);
let mut keep_alive_source = None;
if scheduled
&& let Some(template) = template_registry().get(&override_instance.template_id)
&& !template.keep_alive.is_empty()
&& (keep_alive_off
|| template_registry()
.get(&override_instance.template_id)
.is_some_and(|template| !template.keep_alive.is_empty()))
{
keep_alive_source = Some(KeepAliveSource {
template: template.id.clone(),
template: override_instance.template_id.clone(),
address: account_pubkey,
values: override_instance.values.clone(),
off: keep_alive_off,
});
}

Expand Down Expand Up @@ -3919,6 +3926,12 @@ impl SurfnetSvm {
/// Adds the accounts that `touched` makes keep-alive imports rewrite.
fn enroll_keep_alive(&mut self, touched: Vec<KeepAliveSource>) {
for source in touched {
if source.off {
self.keep_alive_bindings
.retain(|binding| binding.address != source.address);
info!("Keep-alive stops rewriting {}", source.address);
continue;
}
let Some(template) = template_registry().get(&source.template) else {
continue;
};
Expand Down Expand Up @@ -9748,4 +9761,45 @@ mod tests {
.expect("the override must notify the account's subscribers");
assert_eq!(update.data.decode(), Some(account.data));
}

#[tokio::test]
async fn an_empty_keep_alive_list_stops_keep_alive_on_the_account_it_writes() {
let (mut svm, _simnet_events_rx, _geyser_events_rx) = SurfnetSvm::default();
let (account_pubkey, instance) = scheduled_override_fixture(&mut svm);
let other = Pubkey::new_unique();
for address in [account_pubkey, other] {
svm.keep_alive_bindings.insert(KeepAliveBinding {
template: "an-earlier-override".to_string(),
import: 0,
address,
});
}
let mut play = async |slot: u64, keep_alive: serde_json::Value, values| {
let mut instance = instance.clone().with_values(values);
instance.keep_alive = serde_json::from_value(keep_alive).unwrap();
svm.scheduled_overrides.store(slot, vec![instance]).unwrap();
svm.materialize_overrides_for_slot(&None, slot)
.await
.unwrap();
svm.keep_alive_bindings
.iter()
.map(|binding| binding.address)
.collect::<Vec<Pubkey>>()
};
let mut both = vec![account_pubkey, other];
both.sort();

let failed = HashMap::from([("nope".to_string(), serde_json::json!(1))]);
assert_eq!(play(500, serde_json::json!([]), failed).await, both);
assert_eq!(
play(501, serde_json::json!([{}]), instance.values.clone()).await,
both,
"a failed write and a non-empty list stop nothing"
);
assert_eq!(
play(502, serde_json::json!([]), instance.values.clone()).await,
vec![other],
"only the written account stops"
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,11 @@ enabled: boolean,
* Whether to fetch fresh account data just before transaction execution
*/
fetchBeforeUse?: boolean,
/**
* Keep-alive for the account this override writes. Absent, the template's keep-alive applies;
* `[]` turns it off. Only `[]` is supported.
*/
keepAlive?: Array<unknown>,
/**
* Account address to override - use pubkey for known addresses or pda for derived addresses
*/
Expand Down
1 change: 1 addition & 0 deletions crates/types/src/rpc_endpoints.json
Original file line number Diff line number Diff line change
Expand Up @@ -861,6 +861,7 @@
"label": "Option<String> (An optional label for this override instance)",
"enabled": "bool (Indicates whether this override instance is enabled)",
"fetchBeforeUse": "bool (Indicates whether to fetch the latest on-chain account data before applying overrides)",
"keepAlive": "Option<[]> (Optional. Omit it to keep the template's keep-alive. [] turns keep-alive off for the account this override writes, from this slot on, including keep-alive that earlier overrides started. Only [] is supported)",
"account": "AccountAddress (The account this override targets, as {\"pubkey\": \"<base-58 address>\"} or {\"pda\": {\"programId\": \"<base-58 program>\", \"seeds\": [ ... ]}})"
}
}
Expand Down
36 changes: 36 additions & 0 deletions crates/types/src/scenarios.rs
Original file line number Diff line number Diff line change
Expand Up @@ -592,6 +592,14 @@ pub struct OverrideInstance {
#[serde(default)]
#[cfg_attr(feature = "ts-bindings", ts(as = "Option<bool>", optional))]
pub fetch_before_use: bool,
/// Keep-alive for the account this override writes. Absent, the template's keep-alive applies;
/// `[]` turns it off. Only `[]` is supported.
#[schemars(
description = "Optional. Omit it to keep the template's keep-alive. [] turns keep-alive off for the account this override writes, from this slot on, including keep-alive that earlier overrides started. Only [] is supported"
)]
#[serde(default, skip_serializing_if = "Option::is_none")]
#[cfg_attr(feature = "ts-bindings", ts(type = "Array<unknown>", optional))]
pub keep_alive: Option<Vec<serde_json::Value>>,
/// Account address to override - use pubkey for known addresses or pda for derived addresses
#[schemars(
description = "Account address: either {\"pubkey\": \"base58_address\"} or {\"pda\": {\"programId\": \"...\", \"seeds\": [...]}}"
Expand All @@ -609,6 +617,7 @@ impl OverrideInstance {
label: None,
enabled: true,
fetch_before_use: false,
keep_alive: None,
account,
}
}
Expand Down Expand Up @@ -2496,4 +2505,31 @@ templates:
);
}
}

#[test]
fn keep_alive_is_absent_unless_given() {
let instance = |keep_alive: Option<serde_json::Value>| {
let mut value = json!({
"id": "o", "templateId": "t", "values": {}, "scenarioRelativeSlot": 0,
"enabled": true, "account": { "pubkey": "11111111111111111111111111111111" }
});
if let Some(keep_alive) = keep_alive {
value["keepAlive"] = keep_alive;
}
serde_json::from_value::<super::OverrideInstance>(value).unwrap()
};

let absent = instance(None);
assert_eq!(absent.keep_alive, None);
assert!(
serde_json::to_value(&absent)
.unwrap()
.get("keepAlive")
.is_none()
);

let off = instance(Some(json!([])));
assert_eq!(off.keep_alive, Some(vec![]));
assert_eq!(serde_json::to_value(&off).unwrap()["keepAlive"], json!([]));
}
}
Loading