Commit 25724b7
committed
perf(session): cache messages across prompt loop to preserve prompt cache byte-identity
OpenCode updates tool part states in-place (pending → completed + output)
between consecutive API calls in the tool-execution loop. When the next
API call serializes the conversation, the previous assistant message has
different bytes (completed state + output vs pending/error placeholder),
breaking Anthropic's prompt cache from that point forward.
On real sessions this causes ~20% of turns to re-write the entire context
at the cache-write price (12.5× cache-read). On April 21st alone, this
cost $2,264 in cache writes vs $1,234 in cache reads.
Fix: cache the conversation array across prompt loop iterations. On tool-
call continuation steps, only append genuinely NEW messages instead of
reloading all messages from the DB. Existing messages retain their
original part states (as the API last saw them), preserving byte-identity
for the prompt cache.
Full reloads still happen after compaction, subtask handling, and overflow
recovery — these operations structurally change the conversation.1 parent 276d162 commit 25724b7
2 files changed
Lines changed: 31 additions & 1 deletion
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
16 | 16 | | |
17 | 17 | | |
18 | 18 | | |
| 19 | + | |
19 | 20 | | |
20 | 21 | | |
21 | 22 | | |
| |||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1279 | 1279 | | |
1280 | 1280 | | |
1281 | 1281 | | |
| 1282 | + | |
| 1283 | + | |
| 1284 | + | |
| 1285 | + | |
| 1286 | + | |
| 1287 | + | |
| 1288 | + | |
| 1289 | + | |
1282 | 1290 | | |
1283 | 1291 | | |
1284 | 1292 | | |
1285 | 1293 | | |
1286 | | - | |
| 1294 | + | |
| 1295 | + | |
| 1296 | + | |
| 1297 | + | |
1287 | 1298 | | |
1288 | 1299 | | |
1289 | 1300 | | |
| |||
1335 | 1346 | | |
1336 | 1347 | | |
1337 | 1348 | | |
| 1349 | + | |
1338 | 1350 | | |
1339 | 1351 | | |
1340 | 1352 | | |
| |||
1347 | 1359 | | |
1348 | 1360 | | |
1349 | 1361 | | |
| 1362 | + | |
1350 | 1363 | | |
1351 | 1364 | | |
1352 | 1365 | | |
| |||
1356 | 1369 | | |
1357 | 1370 | | |
1358 | 1371 | | |
| 1372 | + | |
1359 | 1373 | | |
1360 | 1374 | | |
1361 | 1375 | | |
| |||
1489 | 1503 | | |
1490 | 1504 | | |
1491 | 1505 | | |
| 1506 | + | |
| 1507 | + | |
| 1508 | + | |
| 1509 | + | |
| 1510 | + | |
| 1511 | + | |
| 1512 | + | |
| 1513 | + | |
| 1514 | + | |
| 1515 | + | |
| 1516 | + | |
| 1517 | + | |
| 1518 | + | |
| 1519 | + | |
| 1520 | + | |
1492 | 1521 | | |
1493 | 1522 | | |
1494 | 1523 | | |
| |||
0 commit comments