genkit icon indicating copy to clipboard operation
genkit copied to clipboard

[JS] Restartable interrupts: a tool cannot tell a duplicated restart from a new call (pass it the tool request's `ref`)

Open FurkhanShaikh opened this issue 1 week ago • 5 comments

Is your feature request related to a problem? Please describe.

The restartable tool on the interrupts page ("Tools with restartable interrupts", transferMoney) performs the transfer when it is restarted with { status: 'APPROVED' }. If the same restart is sent twice (a client retrying after a timeout, an approval submitted twice, a redelivered queue message), the tool runs twice and the transfer happens twice.

The usual defence is an idempotency key derived from the call, so the payment provider can drop the second request. Genkit already has such a value: the tool request's ref (the model's tool-call id). It is on the interrupt (interrupt.toolRequest.ref) and on the restart part, and it is the same for both restarts. But it is not passed to the tool function. The tool's second argument carries abortSignal, context, inputStream, interrupt, metadata, registry, resumed, sendChunk, streamingRequested and trace, and none of them contains the ref. The input alone cannot tell a duplicated restart from a second, intended transfer of the same amount to the same account.

Reproduction on genkit 1.44.0, using genkit/beta as the page does. It needs no API key and makes no network calls: the model is a local fake that asks for one transferMoney call with ref call_1. The script is below. Output:

interrupted call ref: call_1
restart 1: Done. | restart 2: Done.
restart part ref: call_1
transfers executed: 2
  transfer 1: {"input":{"toAccountId":"ABC123","amount":100000},"optionKeys":["abortSignal","context","inputStream","interrupt","metadata","registry","resumed","sendChunk","streamingRequested","trace"],"carriesRef":false}
  transfer 2: {"input":{"toAccountId":"ABC123","amount":100000},"optionKeys":["abortSignal","context","inputStream","interrupt","metadata","registry","resumed","sendChunk","streamingRequested","trace"],"carriesRef":false}

We first saw this on 1.42.0 with @genkit-ai/compat-oai against a local OpenAI-compatible server. There, the ref was the model's tool-call id and came back unchanged in the resumed messages. A restart resent after the process was killed with the transfer committed also paid twice.

Describe the solution you'd like

Pass the tool request's ref to the tool function, for example as options.toolRequest (name, ref) or options.ref, both on first execution and on restart. A tool could then derive a key such as <conversation id>:<ref> and send it to the provider. Where a model plugin supplies no ref, Genkit could assign one when it records the request, so that the restart carries it.

A sentence on the interrupts page would also help: a restart runs the tool body again, so a side-effecting restartable tool should be idempotent, and it should say which value to key on.

Describe alternatives you've considered

  • Keying on the input cannot tell a duplicated restart from a second identical transfer.
  • The trace ids identify an execution, not the call. In this run, with no telemetry configured, every execution got all-zero ids.
  • A generate middleware. Its tool hook is typed to receive the ToolRequestPart, ref included (tool?: (req: ToolRequestPart, ctx, next) in @genkit-ai/ai 1.44.0), so an application could probably pass the ref into context itself. We have not tried this. The page's example does not do it, and every application with a side-effecting restartable tool would have to.

Additional context

  • Runtime: Windows 11; Node v22.23.1; genkit 1.44.0 (@genkit-ai/ai 1.44.0).
  • Scope: we tested only the JS SDK. The Go section of the page (DefineResumableTool, call.Restart) describes the same restart.
  • Duplicates: we searched the issues for ref, restart, interrupt, idempotency and tool-call id, and found no existing report of this.
repro.mjs
// A restartable tool, as on genkit.dev/docs/interrupts ("Tools with restartable interrupts"), restarted
// twice with the same approval: a duplicated resume request (a client retry after a timeout, a double
// click, a redelivered queue message). Does the tool get anything that tells the two restarts apart from
// two different transfers?
//
// npm install [email protected], then node repro.mjs. No API key, no network: the model is a local fake that
// asks for one transferMoney call with ref "call_1" (the model's tool-call id) and then answers "Done.".
import { genkit, z } from 'genkit/beta';

const ai = genkit({});

ai.defineModel({ name: 'fake/model' }, async (req) => {
  const last = req.messages[req.messages.length - 1];
  if (last.content.some((p) => p.toolResponse)) {
    return { message: { role: 'model', content: [{ text: 'Done.' }] }, finishReason: 'stop' };
  }
  return {
    message: {
      role: 'model',
      content: [{ toolRequest: { name: 'transferMoney', ref: 'call_1', input: { toAccountId: 'ABC123', amount: 100000 } } }],
    },
    finishReason: 'stop',
  };
});

const transfers = [];
const transferMoney = ai.defineTool(
  {
    name: 'transferMoney',
    description: 'Transfers money between accounts.',
    inputSchema: z.object({ toAccountId: z.string(), amount: z.number() }),
    outputSchema: z.object({ status: z.string(), message: z.string().optional() }),
  },
  async (input, options) => {
    const { interrupt, resumed } = options;
    if (resumed?.status === 'REJECTED') return { status: 'REJECTED' };
    if (resumed?.status !== 'APPROVED' && input.amount > 10000) {
      interrupt({ message: 'Please confirm sending an amount > $100.' });
    }
    // what the tool can see on the paying pass: does any value in its options carry the call's ref?
    const seen = JSON.stringify(options, (k, v) => (typeof v === 'function' || k === 'registry' ? undefined : v));
    transfers.push({ input, optionKeys: Object.keys(options).sort(), carriesRef: seen.includes('call_1') });
    return { status: 'OK' };
  },
);

const MODEL = 'fake/model';
const first = await ai.generate({ model: MODEL, prompt: 'Transfer $1000 to account ABC123', tools: [transferMoney] });
const intr = first.interrupts[0];
console.log('interrupted call ref:', intr.toolRequest.ref);

const restart = () =>
  ai.generate({
    model: MODEL,
    tools: [transferMoney],
    messages: first.messages,
    resume: { restart: [transferMoney.restart(intr, { status: 'APPROVED' })] },
  });

const r1 = await restart(); // the approval
const r2 = await restart(); // the same approval, sent again
console.log('restart 1:', r1.text, '| restart 2:', r2.text);
console.log('restart part ref:', transferMoney.restart(intr, { status: 'APPROVED' }).toolRequest.ref);
console.log('transfers executed:', transfers.length);
transfers.forEach((t, i) => console.log(`  transfer ${i + 1}:`, JSON.stringify(t)));

FurkhanShaikh avatar Nov 19 '26 23:11 FurkhanShaikh

Triage: P2 · S · stop: needs design decision

Area: js

Root cause: toRunOptions in js/ai/src/generate/resolve-tool-requests.ts and ToolRunOptions in js/ai/src/tool.ts only pass metadata, resumed, and abortSignal from a ToolRequestPart to the tool implementation, omitting part.toolRequest.ref (and not assigning a ref when a model omits one). However, exposing the tool request ref on the public tool options interface requires a design decision on the exact API contract and cross-SDK parity.

Options:

  • Option 1 (Recommended): Add ref?: string to ToolRunOptions (and ToolContext / tool package in Go if parity is desired). Populate out.ref = part.toolRequest.ref in toRunOptions in js/ai/src/generate/resolve-tool-requests.ts, and decide whether Genkit should auto-generate a ref when the model does not provide one.
  • Option 2: Add toolRequest?: { name: string; ref?: string } to ToolRunOptions. Pass the request descriptor on the options object so future request-level properties do not collide with top-level ActionRunOptions fields.
  • Option 3: Keep ToolRunOptions unchanged and document using a generate middleware tool hook. Middleware already receives the full ToolRequestPart (including toolRequest.ref) and can forward it via context.
Details
  • In js/ai/src/tool.ts, ToolRunOptions extends ActionRunOptions with resumed?: boolean | Record<string, any> and metadata?: Record<string, any>.
  • In js/ai/src/generate/resolve-tool-requests.ts, toRunOptions(part, options) constructs ToolRunOptions from part.metadata, part.metadata?.resumed, and options?.abortSignal, and executeTool calls tool(req.toolRequest.input, ctx as ToolRunOptions). req.toolRequest.ref is only used when building the toolResponse after execution.
  • In Go (go/ai/tools.go and go/ai/tool/tool.go), ToolContext and ResumableToolFunc also do not currently expose ToolRequest.Ref to the tool body.

Run f2114a43-3089-4a40-bcc5-59026c33c496 · Cloud Run logs

genkit-bot avatar Nov 20 '26 15:11 genkit-bot

@genkit-bot implement Option 2, scoped to JS only (js/ai).

  • Add toolRequest?: { name: string; ref?: string } to ToolRunOptions in js/ai/src/tool.ts.
  • Populate toolRequest in toRunOptions in js/ai/src/generate/resolve-tool-requests.ts so both initial tool runs and restarts receive { name, ref } (omitting ref when undefined).
  • Pass through part.toolRequest.ref as supplied by the model without auto-generating synthetic refs. In JS, google-genai serializes toolRequest.ref as functionCall.id, so fallback ID generation for providers that omit it is out of scope here.
  • Add unit tests covering initial execution, restartable interrupts, and missing ref.

Go parity and the interrupts docs update are out of scope and will be tracked separately.

ssbushi avatar Nov 20 '26 18:11 ssbushi

Opened #7278 (run aa54768d-56c5-4ad9-a869-2efb1b88f67f, Cloud Run logs)

genkit-bot avatar Nov 20 '26 18:11 genkit-bot

With the linked PR the tool gets the ref, which covers the case shown. Two notes for the docs follow-up, since the transferMoney example on the interrupts page is what people will copy.

The ref identifies this tool call, not the transfer. A duplicated restart reuses it, which is what you want. If the model later proposes the same transfer in a new turn, it gets a new ref. That is also right, since only the user can say whether it is a second transfer.

The ref alone does not make the tool safe. The tool still has to store ref plus result before it answers, return the stored result on a repeat, and treat "started, no result" as unknown, not as free to retry. And where a provider sends no ref, the tool has no key at all, so the example should say what to do then.

gioherazo avatar Nov 24 '26 17:11 gioherazo

For recorded executions, a duplicate destination triggers an independent review before another transferMoney call.

pip install panel-firewall
usepanel proxy --policy panel-policy.yaml -- YOUR_MCP_SERVER_COMMAND
mode: approval
actions:
  transferMoney: {risk: write, duplicate_guard: {field: toAccountId, within_seconds: 600}}

A second transfer to the same account within 10 minutes is held for human approval. This is broader than a request-ref key, so two legitimate transfers to the same account also need review. https://github.com/tenthlook/panel-firewall

axiom-csc avatar Nov 28 '26 02:11 axiom-csc