mirror of
https://github.com/router-for-me/CLIProxyAPI.git
synced 2026-12-02 15:12:55 +08:00
fix(executor): refresh replay cache snapshot after pairing-failure invalidation
- Add DeleteAntigravityReasoningReplayItemsIfUnchangedWithSnapshot in internal/cache to atomically return the newly written tombstone snapshot across local memory and Home KV modes. - Update scope.cacheSnapshot in prepareAntigravityGeminiReasoningReplayPayloadDocWithOptions when conditional invalidation succeeds so the next turn's Commit CAS persists instead of silently dropping replay state. - Add regression tests covering memory/KV commit recovery after pairing degradation and concurrent-write isolation. Closes: #7997
This commit is contained in:
@@ -282,7 +282,13 @@ func getAntigravityReasoningReplayItemsWithSnapshot(ctx context.Context, modelNa
|
||||
// per-key tombstone so eviction of an unrelated key cannot invalidate it.
|
||||
// antigravityReasoningReplayMu must be held by the caller.
|
||||
func reserveAntigravityReasoningReplayAbsentLocked(key string, now time.Time) AntigravityReasoningReplaySnapshot {
|
||||
if len(antigravityReasoningReplayEntries) >= AntigravityReasoningReplayCacheMaxEntries {
|
||||
return writeAntigravityReasoningReplayTombstoneLocked(key, now)
|
||||
}
|
||||
|
||||
func writeAntigravityReasoningReplayTombstoneLocked(key string, now time.Time) AntigravityReasoningReplaySnapshot {
|
||||
_, exists := antigravityReasoningReplayEntries[key]
|
||||
if (!exists && len(antigravityReasoningReplayEntries) >= AntigravityReasoningReplayCacheMaxEntries) ||
|
||||
len(antigravityReasoningReplayEntries) > AntigravityReasoningReplayCacheMaxEntries {
|
||||
evictOldestAntigravityReasoningReplayEntries(AntigravityReasoningReplayCacheEvictBatchSize)
|
||||
}
|
||||
antigravityReasoningReplayNextRevision++
|
||||
@@ -383,33 +389,47 @@ func ReplaceAntigravityReasoningReplayItemsIfUnchanged(ctx context.Context, mode
|
||||
// DeleteAntigravityReasoningReplayItemsIfUnchanged clears replay state only when
|
||||
// it still matches the state read for this request.
|
||||
func DeleteAntigravityReasoningReplayItemsIfUnchanged(ctx context.Context, modelName, sessionKey string, snapshot AntigravityReasoningReplaySnapshot) (bool, error) {
|
||||
_, deleted, errDelete := DeleteAntigravityReasoningReplayItemsIfUnchangedWithSnapshot(ctx, modelName, sessionKey, snapshot)
|
||||
return deleted, errDelete
|
||||
}
|
||||
|
||||
// DeleteAntigravityReasoningReplayItemsIfUnchangedWithSnapshot clears replay
|
||||
// state only when it still matches snapshot and returns the snapshot of the
|
||||
// newly written tombstone when the conditional delete succeeds.
|
||||
func DeleteAntigravityReasoningReplayItemsIfUnchangedWithSnapshot(ctx context.Context, modelName, sessionKey string, snapshot AntigravityReasoningReplaySnapshot) (AntigravityReasoningReplaySnapshot, bool, error) {
|
||||
key := antigravityReasoningReplayCacheKey(modelName, sessionKey)
|
||||
if key == "" {
|
||||
return false, nil
|
||||
return AntigravityReasoningReplaySnapshot{}, false, nil
|
||||
}
|
||||
if !snapshot.loaded {
|
||||
return true, DeleteAntigravityReasoningReplayItemRequired(ctx, modelName, sessionKey)
|
||||
return deleteAntigravityReasoningReplayItemWithSnapshot(ctx, modelName, sessionKey)
|
||||
}
|
||||
client, homeMode, errClient := currentAntigravityReasoningReplayKVClient()
|
||||
if homeMode {
|
||||
if errClient != nil {
|
||||
return false, errClient
|
||||
return AntigravityReasoningReplaySnapshot{}, false, errClient
|
||||
}
|
||||
return client.KVCompareAndSwap(ctx, antigravityReasoningReplayKVKey(modelName, sessionKey), snapshot.raw, snapshot.found, newAntigravityReasoningReplayTombstone(), AntigravityReasoningReplayCacheTTL)
|
||||
tombstone, branch := newAntigravityReasoningReplayTombstoneWithBranch()
|
||||
deleted, errCAS := client.KVCompareAndSwap(ctx, antigravityReasoningReplayKVKey(modelName, sessionKey), snapshot.raw, snapshot.found, tombstone, AntigravityReasoningReplayCacheTTL)
|
||||
if errCAS != nil || !deleted {
|
||||
return AntigravityReasoningReplaySnapshot{}, deleted, errCAS
|
||||
}
|
||||
return AntigravityReasoningReplaySnapshot{
|
||||
raw: append([]byte(nil), tombstone...),
|
||||
loaded: true,
|
||||
found: true,
|
||||
branch: branch,
|
||||
}, true, nil
|
||||
}
|
||||
cacheCleanupOnce.Do(startCacheCleanup)
|
||||
now := time.Now()
|
||||
antigravityReasoningReplayMu.Lock()
|
||||
defer antigravityReasoningReplayMu.Unlock()
|
||||
entry, found := antigravityReasoningReplayEntries[key]
|
||||
if found != snapshot.found || (found && entry.Revision != snapshot.revision) || (!found && snapshot.evictionEpoch != antigravityReasoningReplayEvictionEpoch) {
|
||||
return false, nil
|
||||
return AntigravityReasoningReplaySnapshot{}, false, nil
|
||||
}
|
||||
antigravityReasoningReplayNextRevision++
|
||||
antigravityReasoningReplayEntries[key] = antigravityReasoningReplayEntry{Timestamp: time.Now(), Revision: antigravityReasoningReplayNextRevision, Branch: newAntigravityReasoningReplayGeneration(), Deleted: true}
|
||||
if len(antigravityReasoningReplayEntries) > AntigravityReasoningReplayCacheMaxEntries {
|
||||
evictOldestAntigravityReasoningReplayEntries(AntigravityReasoningReplayCacheEvictBatchSize)
|
||||
}
|
||||
return true, nil
|
||||
return writeAntigravityReasoningReplayTombstoneLocked(key, now), true, nil
|
||||
}
|
||||
|
||||
// DeleteAntigravityReasoningReplayItem removes one replay item after upstream rejects
|
||||
@@ -422,27 +442,37 @@ func DeleteAntigravityReasoningReplayItem(modelName, sessionKey string) {
|
||||
|
||||
// DeleteAntigravityReasoningReplayItemRequired removes one replay item for request-time paths.
|
||||
func DeleteAntigravityReasoningReplayItemRequired(ctx context.Context, modelName, sessionKey string) error {
|
||||
_, _, errDelete := deleteAntigravityReasoningReplayItemWithSnapshot(ctx, modelName, sessionKey)
|
||||
return errDelete
|
||||
}
|
||||
|
||||
func deleteAntigravityReasoningReplayItemWithSnapshot(ctx context.Context, modelName, sessionKey string) (AntigravityReasoningReplaySnapshot, bool, error) {
|
||||
key := antigravityReasoningReplayCacheKey(modelName, sessionKey)
|
||||
if key == "" {
|
||||
return nil
|
||||
return AntigravityReasoningReplaySnapshot{}, false, nil
|
||||
}
|
||||
client, homeMode, errClient := currentAntigravityReasoningReplayKVClient()
|
||||
if homeMode {
|
||||
if errClient != nil {
|
||||
return errClient
|
||||
return AntigravityReasoningReplaySnapshot{}, false, errClient
|
||||
}
|
||||
_, errSet := client.KVSet(ctx, antigravityReasoningReplayKVKey(modelName, sessionKey), newAntigravityReasoningReplayTombstone(), homekv.KVSetOptions{EX: AntigravityReasoningReplayCacheTTL})
|
||||
return errSet
|
||||
tombstone, branch := newAntigravityReasoningReplayTombstoneWithBranch()
|
||||
written, errSet := client.KVSet(ctx, antigravityReasoningReplayKVKey(modelName, sessionKey), tombstone, homekv.KVSetOptions{EX: AntigravityReasoningReplayCacheTTL})
|
||||
if errSet != nil || !written {
|
||||
return AntigravityReasoningReplaySnapshot{}, written, errSet
|
||||
}
|
||||
return AntigravityReasoningReplaySnapshot{
|
||||
raw: append([]byte(nil), tombstone...),
|
||||
loaded: true,
|
||||
found: true,
|
||||
branch: branch,
|
||||
}, true, nil
|
||||
}
|
||||
cacheCleanupOnce.Do(startCacheCleanup)
|
||||
now := time.Now()
|
||||
antigravityReasoningReplayMu.Lock()
|
||||
antigravityReasoningReplayNextRevision++
|
||||
antigravityReasoningReplayEntries[key] = antigravityReasoningReplayEntry{Timestamp: time.Now(), Revision: antigravityReasoningReplayNextRevision, Branch: newAntigravityReasoningReplayGeneration(), Deleted: true}
|
||||
if len(antigravityReasoningReplayEntries) > AntigravityReasoningReplayCacheMaxEntries {
|
||||
evictOldestAntigravityReasoningReplayEntries(AntigravityReasoningReplayCacheEvictBatchSize)
|
||||
}
|
||||
antigravityReasoningReplayMu.Unlock()
|
||||
return nil
|
||||
defer antigravityReasoningReplayMu.Unlock()
|
||||
return writeAntigravityReasoningReplayTombstoneLocked(key, now), true, nil
|
||||
}
|
||||
|
||||
func newAntigravityReasoningReplayGeneration() string {
|
||||
@@ -538,12 +568,18 @@ func antigravityReasoningReplayItemsPrefix(prefix, items [][]byte) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func newAntigravityReasoningReplayTombstone() []byte {
|
||||
func newAntigravityReasoningReplayTombstoneWithBranch() ([]byte, string) {
|
||||
branch := newAntigravityReasoningReplayGeneration()
|
||||
doc := ojson.NewDocString(`{"type":"","generation":"","branch":"","deleted":true}`)
|
||||
_ = doc.Set("type", antigravityReasoningReplayGenerationItemType)
|
||||
_ = doc.Set("generation", newAntigravityReasoningReplayGeneration())
|
||||
_ = doc.Set("branch", newAntigravityReasoningReplayGeneration())
|
||||
_ = doc.Set("branch", branch)
|
||||
raw, _ := marshalReasoningReplayRawJSONArray([][]byte{doc.Bytes()})
|
||||
return raw, branch
|
||||
}
|
||||
|
||||
func newAntigravityReasoningReplayTombstone() []byte {
|
||||
raw, _ := newAntigravityReasoningReplayTombstoneWithBranch()
|
||||
return raw
|
||||
}
|
||||
|
||||
|
||||
@@ -554,3 +554,123 @@ func TestAntigravityReasoningReplayHomeReadNormalizesAndRejectsMixedInvalidChain
|
||||
t.Fatalf("invalid Home read refreshed TTL: count=%d", client.expireCount)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAntigravityReasoningReplayDeleteWithSnapshotAllowsSubsequentCASReplace(t *testing.T) {
|
||||
modes := []struct {
|
||||
name string
|
||||
homeMode bool
|
||||
}{
|
||||
{name: "local", homeMode: false},
|
||||
{name: "home", homeMode: true},
|
||||
}
|
||||
for _, mode := range modes {
|
||||
t.Run(mode.name, func(t *testing.T) {
|
||||
ClearAntigravityReasoningReplayCache()
|
||||
t.Cleanup(ClearAntigravityReasoningReplayCache)
|
||||
if mode.homeMode {
|
||||
client := newFakeAntigravityReasoningReplayKVClient()
|
||||
useFakeAntigravityReasoningReplayKVClient(t, client, true)
|
||||
}
|
||||
|
||||
const model = "gemini-3.6-flash-high"
|
||||
session := "delete-with-snapshot-" + mode.name
|
||||
badItem := antigravityReplayTestItem("bad-cached-signature-123456")
|
||||
freshItem := antigravityReplayTestItem("fresh-after-delete-signature-123456")
|
||||
staleItem := antigravityReplayTestItem("stale-pre-delete-signature-123456")
|
||||
|
||||
if !CacheAntigravityReasoningReplayItems(model, session, [][]byte{badItem}) {
|
||||
t.Fatal("initial cache write failed")
|
||||
}
|
||||
_, preDeleteSnapshot, found, errGet := GetAntigravityReasoningReplayItemsWithSnapshotRequired(context.Background(), model, session)
|
||||
if errGet != nil || !found {
|
||||
t.Fatalf("snapshot read = found %v, err %v", found, errGet)
|
||||
}
|
||||
|
||||
tombstoneSnapshot, deleted, errDelete := DeleteAntigravityReasoningReplayItemsIfUnchangedWithSnapshot(context.Background(), model, session, preDeleteSnapshot)
|
||||
if errDelete != nil || !deleted || !tombstoneSnapshot.loaded || !tombstoneSnapshot.found {
|
||||
t.Fatalf("DeleteAntigravityReasoningReplayItemsIfUnchangedWithSnapshot() = (snapshot=%+v, deleted=%v, err=%v), want loaded tombstone", tombstoneSnapshot, deleted, errDelete)
|
||||
}
|
||||
|
||||
// Pre-delete snapshot must no longer pass CAS against the tombstone.
|
||||
if swapped, errSwap := ReplaceAntigravityReasoningReplayItemsIfUnchanged(context.Background(), model, session, preDeleteSnapshot, [][]byte{staleItem}); errSwap != nil || swapped {
|
||||
t.Fatalf("pre-delete snapshot replace = (%v, %v), want (false, nil)", swapped, errSwap)
|
||||
}
|
||||
|
||||
// Returned tombstone snapshot must permit the next CAS replace.
|
||||
if swapped, errSwap := ReplaceAntigravityReasoningReplayItemsIfUnchanged(context.Background(), model, session, tombstoneSnapshot, [][]byte{freshItem}); errSwap != nil || !swapped {
|
||||
t.Fatalf("tombstone snapshot replace = (%v, %v), want (true, nil)", swapped, errSwap)
|
||||
}
|
||||
items, ok := GetAntigravityReasoningReplayItems(model, session)
|
||||
if !ok || len(items) != 1 || !bytes.Contains(items[0], []byte("fresh-after-delete-signature-123456")) {
|
||||
t.Fatalf("stored items = %q, found=%v", items, ok)
|
||||
}
|
||||
|
||||
// A stale pre-delete snapshot must also remain blocked after the fresh commit.
|
||||
if swapped, errSwap := ReplaceAntigravityReasoningReplayItemsIfUnchanged(context.Background(), model, session, preDeleteSnapshot, [][]byte{staleItem}); errSwap != nil || swapped {
|
||||
t.Fatalf("pre-delete snapshot replace after commit = (%v, %v), want (false, nil)", swapped, errSwap)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAntigravityReasoningReplayDeleteWithSnapshotPreservesConcurrentWrites(t *testing.T) {
|
||||
modes := []struct {
|
||||
name string
|
||||
homeMode bool
|
||||
}{
|
||||
{name: "local", homeMode: false},
|
||||
{name: "home", homeMode: true},
|
||||
}
|
||||
for _, mode := range modes {
|
||||
t.Run(mode.name, func(t *testing.T) {
|
||||
ClearAntigravityReasoningReplayCache()
|
||||
t.Cleanup(ClearAntigravityReasoningReplayCache)
|
||||
if mode.homeMode {
|
||||
client := newFakeAntigravityReasoningReplayKVClient()
|
||||
useFakeAntigravityReasoningReplayKVClient(t, client, true)
|
||||
}
|
||||
|
||||
const model = "gemini-3.6-flash-high"
|
||||
session := "delete-with-snapshot-race-" + mode.name
|
||||
badItem := antigravityReplayTestItem("race-bad-signature-123456")
|
||||
concurrentItem := antigravityReplayTestItem("race-concurrent-signature-123456")
|
||||
laterItem := antigravityReplayTestItem("race-later-signature-123456")
|
||||
|
||||
// Case 1: concurrent write before conditional delete causes CAS miss.
|
||||
if !CacheAntigravityReasoningReplayItems(model, session, [][]byte{badItem}) {
|
||||
t.Fatal("initial cache write failed")
|
||||
}
|
||||
_, staleSnapshot, found, errGet := GetAntigravityReasoningReplayItemsWithSnapshotRequired(context.Background(), model, session)
|
||||
if errGet != nil || !found {
|
||||
t.Fatalf("initial snapshot read = found %v, err %v", found, errGet)
|
||||
}
|
||||
if !CacheAntigravityReasoningReplayItems(model, session, [][]byte{concurrentItem}) {
|
||||
t.Fatal("concurrent write failed")
|
||||
}
|
||||
missedSnapshot, deleted, errDelete := DeleteAntigravityReasoningReplayItemsIfUnchangedWithSnapshot(context.Background(), model, session, staleSnapshot)
|
||||
if errDelete != nil || deleted || missedSnapshot.loaded {
|
||||
t.Fatalf("stale conditional delete = (snapshot=%+v, deleted=%v, err=%v), want (empty, false, nil)", missedSnapshot, deleted, errDelete)
|
||||
}
|
||||
|
||||
// Case 2: concurrent write after conditional delete blocks the returned tombstone snapshot.
|
||||
_, currentSnapshot, foundCurrent, errCurrent := GetAntigravityReasoningReplayItemsWithSnapshotRequired(context.Background(), model, session)
|
||||
if errCurrent != nil || !foundCurrent {
|
||||
t.Fatalf("current snapshot read = found %v, err %v", foundCurrent, errCurrent)
|
||||
}
|
||||
tombstoneSnapshot, deletedCurrent, errDeleteCurrent := DeleteAntigravityReasoningReplayItemsIfUnchangedWithSnapshot(context.Background(), model, session, currentSnapshot)
|
||||
if errDeleteCurrent != nil || !deletedCurrent {
|
||||
t.Fatalf("current conditional delete = (deleted=%v, err=%v), want (true, nil)", deletedCurrent, errDeleteCurrent)
|
||||
}
|
||||
if !CacheAntigravityReasoningReplayItems(model, session, [][]byte{concurrentItem}) {
|
||||
t.Fatal("post-delete concurrent write failed")
|
||||
}
|
||||
if swapped, errSwap := ReplaceAntigravityReasoningReplayItemsIfUnchanged(context.Background(), model, session, tombstoneSnapshot, [][]byte{laterItem}); errSwap != nil || swapped {
|
||||
t.Fatalf("superseded tombstone snapshot replace = (%v, %v), want (false, nil)", swapped, errSwap)
|
||||
}
|
||||
items, ok := GetAntigravityReasoningReplayItems(model, session)
|
||||
if !ok || len(items) != 1 || !bytes.Contains(items[0], []byte("race-concurrent-signature-123456")) {
|
||||
t.Fatalf("concurrent item was clobbered: %q, found=%v", items, ok)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -878,8 +878,10 @@ func prepareAntigravityGeminiReasoningReplayPayloadDocWithOptions(ctx context.Co
|
||||
}
|
||||
originalPairingValid := internalsignature.ValidateGeminiFunctionCallPairing(origWrapped) == nil
|
||||
if replayApplied && originalPairingValid && scope.valid() && reserveOnMiss {
|
||||
if _, errDelete := internalcache.DeleteAntigravityReasoningReplayItemsIfUnchanged(ctx, scope.modelName, scope.sessionKey, scope.cacheSnapshot); errDelete != nil {
|
||||
if nextSnapshot, deleted, errDelete := internalcache.DeleteAntigravityReasoningReplayItemsIfUnchangedWithSnapshot(ctx, scope.modelName, scope.sessionKey, scope.cacheSnapshot); errDelete != nil {
|
||||
logAntigravityReasoningReplayDegraded(scope, "invalidate", errDelete)
|
||||
} else if deleted {
|
||||
scope.cacheSnapshot = nextSnapshot
|
||||
}
|
||||
log.Warnf("antigravity executor: reasoning replay broke Gemini function call pairing (%v); degrading to original payload", errPairing)
|
||||
if originalContentsRaw != "" {
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
@@ -12,6 +13,7 @@ import (
|
||||
internalcache "github.com/router-for-me/CLIProxyAPI/v8/internal/cache"
|
||||
"github.com/router-for-me/CLIProxyAPI/v8/internal/config"
|
||||
homekv "github.com/router-for-me/CLIProxyAPI/v8/internal/home"
|
||||
"github.com/router-for-me/CLIProxyAPI/v8/internal/kvstore"
|
||||
"github.com/router-for-me/CLIProxyAPI/v8/internal/runtime/executor/helps"
|
||||
internalsignature "github.com/router-for-me/CLIProxyAPI/v8/internal/signature"
|
||||
"github.com/router-for-me/CLIProxyAPI/v8/internal/util"
|
||||
@@ -2257,6 +2259,174 @@ func TestPrepareAntigravityGeminiReasoningReplayDegradesWhenReplayBreaksPairing(
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrepareAntigravityGeminiReasoningReplayDegradesAndCommitsNextTurn(t *testing.T) {
|
||||
modes := []struct {
|
||||
name string
|
||||
useKV bool
|
||||
}{
|
||||
{name: "memory", useKV: false},
|
||||
{name: "kv", useKV: true},
|
||||
}
|
||||
|
||||
for _, mode := range modes {
|
||||
t.Run(mode.name, func(t *testing.T) {
|
||||
homekv.ClearCurrent()
|
||||
internalcache.ClearAntigravityReasoningReplayCache()
|
||||
if errShutdown := kvstore.ShutdownLocal(); errShutdown != nil {
|
||||
t.Fatalf("kvstore.ShutdownLocal() setup error = %v", errShutdown)
|
||||
}
|
||||
var dbPath string
|
||||
if mode.useKV {
|
||||
// Allocate TempDir before registering ShutdownLocal cleanup so LIFO
|
||||
// order closes bbolt before removing the directory (required on Windows).
|
||||
dbPath = filepath.Join(t.TempDir(), "issue7997-kv.db")
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
internalcache.ClearAntigravityReasoningReplayCache()
|
||||
homekv.ClearCurrent()
|
||||
if errShutdown := kvstore.ShutdownLocal(); errShutdown != nil {
|
||||
t.Errorf("kvstore.ShutdownLocal() cleanup error = %v", errShutdown)
|
||||
}
|
||||
})
|
||||
if mode.useKV {
|
||||
if errCfg := kvstore.ConfigureLocal(true, dbPath); errCfg != nil {
|
||||
t.Fatalf("kvstore.ConfigureLocal() error = %v", errCfg)
|
||||
}
|
||||
}
|
||||
|
||||
const model = "gemini-3.6-flash-high"
|
||||
const args = `{"file_path":"/tmp/a"}`
|
||||
payload := []byte(`{"sessionId":"sess-pairing-break-commit-` + mode.name + `","request":{"contents":[{"role":"model","parts":[{"thoughtSignature":"skip_thought_signature_validator","functionCall":{"name":"Read","args":` + args + `}}]},{"role":"user","parts":[{"functionResponse":{"name":"Read","response":{"result":"ok"}}}]}]}}`)
|
||||
payload = normalizeAntigravityGeminiFunctionResponseRoles(payload)
|
||||
if err := internalsignature.ValidateGeminiFunctionCallPairing(payload); err != nil {
|
||||
t.Fatalf("original payload pairing invalid: %v", err)
|
||||
}
|
||||
|
||||
badItem := []byte(`{"type":"function_call_part","contentIndex":0,"partIndex":0,"targetOccurrence":0,"call_id":"call_native_1","name":"Read","args":` + args + `,"thoughtSignature":"EsMTCsATARFNMg/XNVix5lDpkKaHR7Xg"}`)
|
||||
sessionKey := antigravityReasoningReplayScopeFromPayload(model, payload).sessionKey
|
||||
if !internalcache.CacheAntigravityReasoningReplayItems(model, sessionKey, [][]byte{badItem}) {
|
||||
t.Fatal("failed to cache bad replay item")
|
||||
}
|
||||
|
||||
opts := cliproxyexecutor.Options{
|
||||
SourceFormat: sdktranslator.FromString("claude"),
|
||||
OriginalRequest: []byte(`{"tools":[{"name":"Read","input_schema":{"type":"object","properties":{"file_path":{"type":"string"}}}}]}`),
|
||||
}
|
||||
out, scope, errPrepare := prepareAntigravityGeminiReasoningReplayPayload(
|
||||
context.Background(),
|
||||
model,
|
||||
cliproxyexecutor.Request{Model: model, Payload: payload},
|
||||
opts,
|
||||
payload,
|
||||
)
|
||||
if errPrepare != nil {
|
||||
t.Fatalf("prepareAntigravityGeminiReasoningReplayPayload error: %v, want graceful degradation", errPrepare)
|
||||
}
|
||||
if !bytes.Equal(out, payload) {
|
||||
t.Fatalf("out = %s, want original payload %s", out, payload)
|
||||
}
|
||||
if !scope.valid() {
|
||||
t.Fatalf("returned scope is invalid: %+v", scope)
|
||||
}
|
||||
|
||||
_, foundAfterDegrade, errPeekAfterDegrade := internalcache.PeekAntigravityReasoningReplayItemsRequired(context.Background(), model, sessionKey)
|
||||
if errPeekAfterDegrade != nil || foundAfterDegrade {
|
||||
t.Fatalf("cache after pairing degradation = (found=%v, err=%v), want (false, nil)", foundAfterDegrade, errPeekAfterDegrade)
|
||||
}
|
||||
|
||||
const newSig = "FreshSignatureAfterPairingDegradation1234567890"
|
||||
responseBody := []byte(`{"response":{"candidates":[{"content":{"role":"model","parts":[{"thought":true,"text":"checking next step"},{"thoughtSignature":"` + newSig + `","functionCall":{"name":"Grep","args":{"pattern":"foo"}}}]},"finishReason":"STOP"}]}}`)
|
||||
cacheAntigravityReasoningReplayFromResponse(context.Background(), scope, out, responseBody)
|
||||
|
||||
committedItems, foundAfterCommit, errPeekAfterCommit := internalcache.PeekAntigravityReasoningReplayItemsRequired(context.Background(), model, sessionKey)
|
||||
if errPeekAfterCommit != nil || !foundAfterCommit || len(committedItems) == 0 {
|
||||
t.Fatalf("cache after degraded turn commit = (len=%d, found=%v, err=%v), want committed replay items", len(committedItems), foundAfterCommit, errPeekAfterCommit)
|
||||
}
|
||||
hasNewSig := false
|
||||
for _, item := range committedItems {
|
||||
if ojson.GetBytesNoCopy(item, "thoughtSignature").String() == newSig {
|
||||
hasNewSig = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !hasNewSig {
|
||||
t.Fatalf("committed items missing %q: %q", newSig, committedItems)
|
||||
}
|
||||
|
||||
nextTurnPayload := []byte(`{"sessionId":"sess-pairing-break-commit-` + mode.name + `","request":{"contents":[{"role":"model","parts":[{"thoughtSignature":"skip_thought_signature_validator","functionCall":{"name":"Read","args":` + args + `}}]},{"role":"user","parts":[{"functionResponse":{"name":"Read","response":{"result":"ok"}}}]},{"role":"model","parts":[{"thoughtSignature":"skip_thought_signature_validator","functionCall":{"name":"Grep","args":{"pattern":"foo"}}}]},{"role":"user","parts":[{"functionResponse":{"name":"Grep","response":{"result":"match"}}}]}]}}`)
|
||||
nextTurnPayload = normalizeAntigravityGeminiFunctionResponseRoles(nextTurnPayload)
|
||||
replayedNext, _, errNext := prepareAntigravityGeminiReasoningReplayPayload(
|
||||
context.Background(),
|
||||
model,
|
||||
cliproxyexecutor.Request{Model: model, Payload: nextTurnPayload},
|
||||
opts,
|
||||
nextTurnPayload,
|
||||
)
|
||||
if errNext != nil {
|
||||
t.Fatalf("next turn prepare error: %v", errNext)
|
||||
}
|
||||
if gotSig := ojson.GetBytesNoCopy(replayedNext, "request.contents.2.parts.0.thoughtSignature").String(); gotSig != newSig {
|
||||
t.Fatalf("next turn replayed signature = %q, want %q", gotSig, newSig)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrepareAntigravityGeminiReasoningReplayDegradedCommitDoesNotClobberConcurrentWrite(t *testing.T) {
|
||||
homekv.ClearCurrent()
|
||||
internalcache.ClearAntigravityReasoningReplayCache()
|
||||
if errShutdown := kvstore.ShutdownLocal(); errShutdown != nil {
|
||||
t.Fatalf("kvstore.ShutdownLocal() setup error = %v", errShutdown)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
internalcache.ClearAntigravityReasoningReplayCache()
|
||||
homekv.ClearCurrent()
|
||||
if errShutdown := kvstore.ShutdownLocal(); errShutdown != nil {
|
||||
t.Errorf("kvstore.ShutdownLocal() cleanup error = %v", errShutdown)
|
||||
}
|
||||
})
|
||||
|
||||
const model = "gemini-3.6-flash-high"
|
||||
const args = `{"file_path":"/tmp/a"}`
|
||||
payload := []byte(`{"sessionId":"sess-pairing-break-concurrent","request":{"contents":[{"role":"model","parts":[{"thoughtSignature":"skip_thought_signature_validator","functionCall":{"name":"Read","args":` + args + `}}]},{"role":"user","parts":[{"functionResponse":{"name":"Read","response":{"result":"ok"}}}]}]}}`)
|
||||
payload = normalizeAntigravityGeminiFunctionResponseRoles(payload)
|
||||
|
||||
badItem := []byte(`{"type":"function_call_part","contentIndex":0,"partIndex":0,"targetOccurrence":0,"call_id":"call_native_1","name":"Read","args":` + args + `,"thoughtSignature":"EsMTCsATARFNMg/XNVix5lDpkKaHR7Xg"}`)
|
||||
sessionKey := antigravityReasoningReplayScopeFromPayload(model, payload).sessionKey
|
||||
if !internalcache.CacheAntigravityReasoningReplayItems(model, sessionKey, [][]byte{badItem}) {
|
||||
t.Fatal("failed to cache bad replay item")
|
||||
}
|
||||
|
||||
opts := cliproxyexecutor.Options{
|
||||
SourceFormat: sdktranslator.FromString("claude"),
|
||||
OriginalRequest: []byte(`{"tools":[{"name":"Read","input_schema":{"type":"object","properties":{"file_path":{"type":"string"}}}}]}`),
|
||||
}
|
||||
out, scope, errPrepare := prepareAntigravityGeminiReasoningReplayPayload(
|
||||
context.Background(),
|
||||
model,
|
||||
cliproxyexecutor.Request{Model: model, Payload: payload},
|
||||
opts,
|
||||
payload,
|
||||
)
|
||||
if errPrepare != nil {
|
||||
t.Fatalf("prepareAntigravityGeminiReasoningReplayPayload error: %v", errPrepare)
|
||||
}
|
||||
|
||||
const concurrentSig = "ConcurrentTurnSignatureMustSurvive1234567890"
|
||||
concurrentItem := []byte(`{"type":"thought_signature","contentIndex":0,"partIndex":0,"thoughtSignature":"` + concurrentSig + `"}`)
|
||||
if !internalcache.CacheAntigravityReasoningReplayItems(model, sessionKey, [][]byte{concurrentItem}) {
|
||||
t.Fatal("failed to cache concurrent replay item")
|
||||
}
|
||||
|
||||
responseBody := []byte(`{"response":{"candidates":[{"content":{"role":"model","parts":[{"thoughtSignature":"DegradedStaleSignatureShouldDrop1234567890","functionCall":{"name":"Grep","args":{"pattern":"foo"}}}]},"finishReason":"STOP"}]}}`)
|
||||
cacheAntigravityReasoningReplayFromResponse(context.Background(), scope, out, responseBody)
|
||||
|
||||
items, found, errPeek := internalcache.PeekAntigravityReasoningReplayItemsRequired(context.Background(), model, sessionKey)
|
||||
if errPeek != nil || !found || len(items) != 1 || ojson.GetBytesNoCopy(items[0], "thoughtSignature").String() != concurrentSig {
|
||||
t.Fatalf("concurrent replay item was clobbered: items=%q found=%v err=%v", items, found, errPeek)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAntigravityStreamChunksHaveTerminalCommitEvent(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
|
||||
Reference in New Issue
Block a user