open-code-review icon indicating copy to clipboard operation
open-code-review copied to clipboard

Plan-phase system prompt renders tool parameters in nondeterministic order, so byte-identical requests defeat provider prefix caching

Open FeilixX opened this issue 3 months ago • 1 comments

OpenCodeReview Version

open-code-review v1.8.8 (6dc3eb067) darwin/arm64, built at 2026-08-04T13:09:52Z

Operating System

macOS (Apple Silicon)

Installation Method

npm (global)

LLM Provider

Other OpenAI-compatible endpoint (DeepSeek). The rendering defect itself is provider-independent; the cost effect applies to providers with prefix caching (e.g. DeepSeek and OpenAI cache automatically).

Bug Description

The plan-phase system prompt is not byte-stable: formatToolDefs renders each tool's parameter list by iterating a Go map without sorting, so the same tool config produces differently-ordered parameter bullets from one request to the next.

The chain, at 6dc3eb067:

  1. internal/config/template/prompts/plan_task_system.md:7 — the {{plan_tools}} placeholder sits near the top of the plan-task system message.
  2. internal/agent/agent.go:1471 (executePlanPhase) — the placeholder is resolved by calling formatToolDefs(a.args.PlanToolDefs) freshly on every per-file plan request.
  3. internal/agent/agent.go:1517 — parameters come from a JSON-decoded map[string]any (fn.Parameters["properties"]).
  4. internal/agent/agent.go:1527 — for name, p := range params iterates that map directly; Go randomizes map iteration order, so the bullet order varies per call:
for name, p := range params {
	suffix := ""
	if required[name] {
		suffix = " (required)"
	}
	...
}

For contrast, the API-level function-calling path is already deterministic — encoding/json sorts map keys when marshaling — so this is a small gap in the one hand-rolled text rendering, not a systemic issue.

Impact, kept in proportion:

  • No semantic impact. The model sees the same bullets in a different order.
  • Byte instability has two practical costs. First, on providers with automatic prefix caching, everything from the first reordered bullet to the end of the system prompt — byte-identical content — drops out of the shared prefix whenever two requests draw different orders (in the repro below that is ~1.6k chars of the 5k-char prompt; per-request cost is small but it recurs on every plan request for every caching provider). Second, prompts are not byte-reproducible across identical runs, which makes prompt-level debugging and cache-behavior analysis noisier than it needs to be. Related: #229 (session affinity only helps if the prompt bytes are stable) and #247 (one mechanical source of run-to-run variation that is free to remove).

Steps to Reproduce

Plan phase runs for files with >= 50 changed lines (PLAN_MODE_LINE_THRESHOLD, internal/config/template/task_template.json:33), so use files large enough to trigger it. Any configured provider works.

git init -q ocr-planprompt-repro && cd ocr-planprompt-repro
git commit -q --allow-empty -m init && git tag base
for name in alpha beta gamma; do
  { echo "pub struct ${name}Config {"; for i in $(seq 1 28); do echo "    pub field_$i: u32,"; done; echo "}";
    echo "impl ${name}Config {"; for i in $(seq 1 28); do echo "    pub fn get_$i(&self) -> u32 { self.field_$i }"; done; echo "}"; } > "$name.rs"
done
git add . && git commit -qm "three 60-line files"
ocr review --from base --to HEAD --audience agent

Then compare the plan-task system prompts recorded in the session JSONL:

python3 - <<'EOF'
import json, glob, os, hashlib
f = max(glob.glob(os.path.expanduser('~/.opencodereview/sessions/*ocr-planprompt-repro*/*.jsonl')), key=os.path.getmtime)
for line in open(f):
    e = json.loads(line)
    if e.get('type') == 'llm_request' and e.get('taskType') == 'plan_task':
        c = e['messages'][0]['content']
        print(e['filePath'], hashlib.md5(c.encode()).hexdigest()[:8], len(c))
EOF

Since the ordering is random, a single run usually suffices with 3 plan requests; occasionally all draws coincide — re-run once if so.

Expected Behavior

All plan-task system prompts within a run (and across runs, given unchanged tool config) are byte-identical: same content, same order.

Logs / Error Output

Observed in one run of the repro above — 3 plan requests, 2 distinct system prompts, identical length, diverging at char 3453:

gamma.rs   md5=fad066c6 len=5048
beta.rs    md5=3fb56faa len=5048
alpha.rs   md5=3fb56faa len=5048

Unified diff of the beta.rs vs gamma.rs system prompts — the entire difference is one relocated bullet:

   Parameters:
+  - case_sensitive: Whether to perform case-sensitive search. Defaults to false.
   - query_name: Filename keyword to search for, supports partial matching. (required)
-  - case_sensitive: Whether to perform case-sensitive search. Defaults to false.

Additional Context

Suggested fix: collect and sort the parameter names before iterating in formatToolDefs (alphabetical, or required-first-then-alphabetical) so the rendered text is a pure function of the tool config. One-line-ish change, no semantic effect on prompts.

Sibling report: #718 covers another instance of the same general family (a byte stream that feeds hashing/prompts not being deterministic), in an unrelated subsystem — the two are independent and neither fix covers the other.

FeilixX avatar Aug 04 '26 18:08 FeilixX

@FeilixX Hi, I’d like to work on this issue.

I plan to fix the nondeterministic prompt output by sorting tool parameter names before rendering them in formatToolDefs. This should keep the prompt semantically unchanged while making the generated system prompt byte-stable for cache friendliness.

I’ll also add a focused test to cover deterministic parameter ordering.

Anon2Tokyo avatar Aug 04 '26 19:08 Anon2Tokyo