Skip fallback needs complete, empty evidence; capture lists over-budget changes
The server skip fallback for stages with a skipped edge now applies only when every earlier visit recorded a complete file-change capture with no changed files and no image artifact. Any change (no repo-specific UI path or extension list), any partial/unavailable/missing capture, a human decision or a checkpoint-retry prefix runs the model. auto_skip=false opts a stage out. The fallback verdict names the server fallback. Capture compares over-budget text by hash and, in Git, lists paths it could not compare when their git status changes, marked no_patch, so a large workspace no longer records files: [] for a real edit. Run detail gains a warnings list for partial/unavailable captures, also printed by inspect on stderr.
This commit is contained in:
+191
-37
@@ -14,6 +14,7 @@ import (
|
||||
"os/exec"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"syscall"
|
||||
"unicode/utf8"
|
||||
|
||||
@@ -28,13 +29,37 @@ const (
|
||||
maxPatchBytes = 128 << 10
|
||||
maxFilePatchBytes = 64 << 10
|
||||
maxLines = 5000
|
||||
binarySniffBytes = 8 << 10
|
||||
)
|
||||
|
||||
// maxHashBytes bounds one hash-only file; larger files are skipped (and, in a
|
||||
// Git working tree, listed only when their Git status changes). It is a
|
||||
// variable so package tests can exercise that path without huge files.
|
||||
var maxHashBytes int64 = 256 << 20
|
||||
|
||||
// snapshotBudget is the retained text bytes per snapshot. Files beyond it (or
|
||||
// beyond the per-file limit) are still compared by content hash and listed
|
||||
// without a patch, so an over-budget workspace never hides which files changed.
|
||||
var snapshotBudget atomic.Int64
|
||||
|
||||
func init() { snapshotBudget.Store(maxSnapshotBytes) }
|
||||
|
||||
// SetSnapshotBudgetForTesting lowers the retained-text budget so tests can
|
||||
// exercise an over-budget workspace without writing tens of megabytes. It
|
||||
// returns a function restoring the previous budget. Production never calls it.
|
||||
func SetSnapshotBudgetForTesting(n int64) (restore func()) {
|
||||
previous := snapshotBudget.Swap(n)
|
||||
return func() { snapshotBudget.Store(previous) }
|
||||
}
|
||||
|
||||
type file struct {
|
||||
data []byte
|
||||
hash [32]byte
|
||||
mode fs.FileMode
|
||||
binary bool
|
||||
// hashOnly marks a text file compared by content hash only: it exceeded the
|
||||
// per-file or per-snapshot text budget, so no patch can be produced.
|
||||
hashOnly bool
|
||||
}
|
||||
|
||||
type Snapshot struct {
|
||||
@@ -44,6 +69,63 @@ type Snapshot struct {
|
||||
available bool
|
||||
diagnostic string
|
||||
scope string
|
||||
// gitStatus maps run-relative paths to their porcelain XY status code when
|
||||
// the run directory is a Git working tree and the status read succeeded
|
||||
// (gitOK). Compare uses it to list changed paths the content snapshot could
|
||||
// not compare (time/file limit, unreadable); it never reads HEAD/index content.
|
||||
gitStatus map[string]string
|
||||
gitOK bool
|
||||
}
|
||||
|
||||
// readGitStatus reads `git status --porcelain=v1 -z` for the run directory and
|
||||
// returns its paths relative to that directory. It only reads: optional locks
|
||||
// are disabled so the index is never refreshed or rewritten.
|
||||
func readGitStatus(ctx context.Context, directory string) (map[string]string, bool) {
|
||||
prefixOut, err := exec.CommandContext(ctx, "git", "-c", "core.fsmonitor=false", "-C", directory, "rev-parse", "--show-prefix").Output()
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
prefix := strings.TrimSpace(string(prefixOut))
|
||||
cmd := exec.CommandContext(ctx, "git", "--no-optional-locks", "-c", "core.fsmonitor=false", "-C", directory, "status", "--porcelain=v1", "-z", "--no-renames", "--untracked-files=all", "--", ".")
|
||||
out := &boundedOutput{limit: 4 << 20}
|
||||
cmd.Stdout = out
|
||||
if err := cmd.Run(); err != nil {
|
||||
return nil, false
|
||||
}
|
||||
status := map[string]string{}
|
||||
for _, entry := range strings.Split(out.String(), "\x00") {
|
||||
if len(entry) < 4 || entry[2] != ' ' {
|
||||
continue
|
||||
}
|
||||
name, ok := strings.CutPrefix(entry[3:], prefix)
|
||||
if !ok || name == "" {
|
||||
continue // outside the run directory
|
||||
}
|
||||
status[name] = entry[:2]
|
||||
}
|
||||
return status, true
|
||||
}
|
||||
|
||||
// hashFile streams f from its start into a content hash without retaining it.
|
||||
// It returns ok=false when the file exceeds maxHashBytes or cannot be read.
|
||||
func hashFile(f *os.File) (hash [32]byte, binary bool, ok bool) {
|
||||
if _, err := f.Seek(0, io.SeekStart); err != nil {
|
||||
return hash, false, false
|
||||
}
|
||||
h := sha256.New()
|
||||
head := make([]byte, binarySniffBytes)
|
||||
n, err := io.ReadFull(f, head)
|
||||
if err != nil && !errors.Is(err, io.ErrUnexpectedEOF) && !errors.Is(err, io.EOF) {
|
||||
return hash, false, false
|
||||
}
|
||||
head = head[:n]
|
||||
h.Write(head)
|
||||
copied, err := io.Copy(h, io.LimitReader(f, maxHashBytes+1-int64(n)))
|
||||
if err != nil || int64(n)+copied > maxHashBytes {
|
||||
return hash, false, false
|
||||
}
|
||||
copy(hash[:], h.Sum(nil))
|
||||
return hash, bytes.IndexByte(head, 0) >= 0, true
|
||||
}
|
||||
|
||||
func protected(name string) bool {
|
||||
@@ -130,6 +212,9 @@ func Capture(ctx context.Context, directory string, previous ...*Snapshot) *Snap
|
||||
s.partial = true
|
||||
s.diagnostic = "Workspace inventory incomplete."
|
||||
}
|
||||
if git {
|
||||
s.gitStatus, s.gitOK = readGitStatus(ctx, directory)
|
||||
}
|
||||
// Keep pre-stage paths even if a stage changes .gitignore/the index.
|
||||
known := map[string]bool{}
|
||||
for _, name := range names {
|
||||
@@ -179,7 +264,7 @@ func Capture(ctx context.Context, directory string, previous ...*Snapshot) *Snap
|
||||
continue
|
||||
}
|
||||
info, err := root.Lstat(name)
|
||||
if err != nil || !info.Mode().IsRegular() || info.Size() > maxFileBytes {
|
||||
if err != nil || !info.Mode().IsRegular() || info.Size() > maxHashBytes {
|
||||
s.skipped[name] = true
|
||||
continue
|
||||
}
|
||||
@@ -194,28 +279,43 @@ func Capture(ctx context.Context, directory string, previous ...*Snapshot) *Snap
|
||||
s.skipped[name] = true
|
||||
continue
|
||||
}
|
||||
data, readErr := io.ReadAll(io.LimitReader(f, maxFileBytes+1))
|
||||
if opened.Size() <= maxFileBytes {
|
||||
data, readErr := io.ReadAll(io.LimitReader(f, maxFileBytes+1))
|
||||
if readErr != nil {
|
||||
f.Close()
|
||||
s.skipped[name] = true
|
||||
continue
|
||||
}
|
||||
if len(data) <= maxFileBytes {
|
||||
f.Close()
|
||||
binary := bytes.IndexByte(data, 0) >= 0 || !utf8.Valid(data)
|
||||
hash := sha256.Sum256(data)
|
||||
hashOnly := false
|
||||
// Binary changes need only metadata and a hash, never retained patch bytes.
|
||||
// Counting screenshots against the retained-text budget can otherwise
|
||||
// exhaust it before any source files are reached in sorted inventory order.
|
||||
// Text beyond the budget keeps only its hash, so a change to it is still
|
||||
// listed (without a patch) instead of being skipped unseen.
|
||||
if binary {
|
||||
data = nil
|
||||
} else if int64(used+len(data)) > snapshotBudget.Load() {
|
||||
data = nil
|
||||
hashOnly = true
|
||||
} else {
|
||||
used += len(data)
|
||||
}
|
||||
s.files[name] = file{data: data, hash: hash, mode: opened.Mode().Perm(), binary: binary, hashOnly: hashOnly}
|
||||
continue
|
||||
}
|
||||
// The file grew past the per-file limit while being read: hash it.
|
||||
}
|
||||
hash, binary, ok := hashFile(f)
|
||||
f.Close()
|
||||
if readErr != nil || len(data) > maxFileBytes {
|
||||
if !ok {
|
||||
s.skipped[name] = true
|
||||
continue
|
||||
}
|
||||
binary := bytes.IndexByte(data, 0) >= 0 || !utf8.Valid(data)
|
||||
hash := sha256.Sum256(data)
|
||||
// Binary changes need only metadata and a hash, never retained patch bytes.
|
||||
// Counting screenshots against the retained-text budget can otherwise
|
||||
// exhaust it before any source files are reached in sorted inventory order.
|
||||
if binary {
|
||||
data = nil
|
||||
} else {
|
||||
if used+len(data) > maxSnapshotBytes {
|
||||
s.skipped[name] = true
|
||||
s.partial = true
|
||||
continue
|
||||
}
|
||||
used += len(data)
|
||||
}
|
||||
s.files[name] = file{data: data, hash: hash, mode: opened.Mode().Perm(), binary: binary}
|
||||
s.files[name] = file{hash: hash, mode: opened.Mode().Perm(), binary: binary, hashOnly: !binary}
|
||||
}
|
||||
return s
|
||||
}
|
||||
@@ -258,6 +358,35 @@ func Compare(before, after *Snapshot) *protocol.StageFileChanges {
|
||||
sort.Strings(names)
|
||||
remaining := maxPatchBytes
|
||||
retained := 0
|
||||
add := func(change protocol.FileChange) {
|
||||
if change.Truncated {
|
||||
result.Status = "partial"
|
||||
if !change.NoPatch {
|
||||
result.Diagnostic = "Some patches were omitted/truncated by capture limits."
|
||||
}
|
||||
}
|
||||
encoded, _ := json.Marshal(change)
|
||||
if retained+len(encoded)+1 > maxPatchBytes {
|
||||
change.Patch = ""
|
||||
change.Truncated = true
|
||||
encoded, _ = json.Marshal(change)
|
||||
}
|
||||
if retained+len(encoded)+1 > maxPatchBytes {
|
||||
result.Omitted++
|
||||
result.Status = "partial"
|
||||
result.Diagnostic = "Additional file changes omitted by the retained evidence size limit."
|
||||
return
|
||||
}
|
||||
if change.Truncated {
|
||||
result.Status = "partial"
|
||||
}
|
||||
retained += len(encoded) + 1
|
||||
result.Files = append(result.Files, change)
|
||||
}
|
||||
listed := 0
|
||||
// decided records every path the content comparison settled (changed or
|
||||
// not), so the Git-status pass below only speaks for the rest.
|
||||
decided := map[string]bool{}
|
||||
for _, name := range names {
|
||||
if skipped[name] {
|
||||
continue
|
||||
@@ -268,6 +397,7 @@ func Compare(before, after *Snapshot) *protocol.StageFileChanges {
|
||||
if !aOK && before.partial || !bOK && after.partial {
|
||||
continue
|
||||
}
|
||||
decided[name] = true
|
||||
if aOK && bOK && a.hash == b.hash && a.mode == b.mode {
|
||||
continue
|
||||
}
|
||||
@@ -285,7 +415,12 @@ func Compare(before, after *Snapshot) *protocol.StageFileChanges {
|
||||
if bOK {
|
||||
change.AfterMode = fmt.Sprintf("%04o", b.mode)
|
||||
}
|
||||
if !change.Binary && a.hash != b.hash {
|
||||
if !change.Binary && a.hash != b.hash && (a.hashOnly || b.hashOnly) {
|
||||
// Over-budget content was compared by hash: list it, without a patch.
|
||||
change.Truncated = true
|
||||
change.NoPatch = true
|
||||
listed++
|
||||
} else if !change.Binary && a.hash != b.hash {
|
||||
if remaining == 0 || bytes.Count(a.data, []byte("\n"))+bytes.Count(b.data, []byte("\n")) > maxLines {
|
||||
change.Truncated = true
|
||||
} else {
|
||||
@@ -314,27 +449,46 @@ func Compare(before, after *Snapshot) *protocol.StageFileChanges {
|
||||
}
|
||||
}
|
||||
}
|
||||
if change.Truncated {
|
||||
result.Status = "partial"
|
||||
result.Diagnostic = "Some patches were omitted/truncated by capture limits."
|
||||
add(change)
|
||||
}
|
||||
// In a Git working tree, paths the content snapshot could not settle
|
||||
// (skipped as unreadable/oversized, or beyond the time/file limit) are still
|
||||
// listed when their Git status changed during the visit. A path dirty with
|
||||
// the same status before and after cannot be proven changed and stays
|
||||
// counted as skipped. Protected paths are never listed.
|
||||
if before.gitOK && after.gitOK {
|
||||
gitNames := map[string]bool{}
|
||||
for name := range before.gitStatus {
|
||||
gitNames[name] = true
|
||||
}
|
||||
encoded, _ := json.Marshal(change)
|
||||
if retained+len(encoded)+1 > maxPatchBytes {
|
||||
change.Patch = ""
|
||||
change.Truncated = true
|
||||
encoded, _ = json.Marshal(change)
|
||||
for name := range after.gitStatus {
|
||||
gitNames[name] = true
|
||||
}
|
||||
if retained+len(encoded)+1 > maxPatchBytes {
|
||||
result.Omitted++
|
||||
result.Status = "partial"
|
||||
result.Diagnostic = "Additional file changes omitted by the retained evidence size limit."
|
||||
continue
|
||||
ordered := make([]string, 0, len(gitNames))
|
||||
for name := range gitNames {
|
||||
if !decided[name] && fs.ValidPath(name) && !protected(name) {
|
||||
ordered = append(ordered, name)
|
||||
}
|
||||
}
|
||||
if change.Truncated {
|
||||
result.Status = "partial"
|
||||
sort.Strings(ordered)
|
||||
for _, name := range ordered {
|
||||
was, now := before.gitStatus[name], after.gitStatus[name]
|
||||
if was == now {
|
||||
continue
|
||||
}
|
||||
kind := "modified"
|
||||
switch {
|
||||
case now == "" && was == "??", strings.Contains(now, "D"):
|
||||
kind = "deleted"
|
||||
case was == "" && (now == "??" || strings.HasPrefix(now, "A")):
|
||||
kind = "added"
|
||||
}
|
||||
add(protocol.FileChange{Path: name, Kind: kind, Truncated: true, NoPatch: true})
|
||||
listed++
|
||||
}
|
||||
retained += len(encoded) + 1
|
||||
result.Files = append(result.Files, change)
|
||||
}
|
||||
if listed > 0 && result.Status == "partial" && result.Omitted == 0 {
|
||||
result.Diagnostic = "Some changed files exceeded capture limits and are listed without patches; this is not a complete workspace diff."
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
@@ -132,9 +132,14 @@ func TestProtectedSymlinkAndLimits(t *testing.T) {
|
||||
put(t, dir, "large", "small now")
|
||||
put(t, dir, "normal", "safe\n")
|
||||
changes := Compare(before, Capture(ctx, dir, before))
|
||||
if changes.Status != "partial" || len(changes.Files) != 1 || changes.Files[0].Path != "normal" {
|
||||
// The oversized file is compared by hash and listed without a patch; the
|
||||
// protected file and the symlink stay excluded.
|
||||
if changes.Status != "partial" || len(changes.Files) != 2 || changes.Files[0].Path != "large" || changes.Files[1].Path != "normal" {
|
||||
t.Fatal(changes)
|
||||
}
|
||||
if large := changes.Files[0]; !large.NoPatch || !large.Truncated || large.Patch != "" || large.Kind != "modified" {
|
||||
t.Fatalf("oversized file not listed without patch: %+v", large)
|
||||
}
|
||||
for _, f := range changes.Files {
|
||||
if strings.Contains(f.Patch, "secret") {
|
||||
t.Fatal("secret retained")
|
||||
@@ -189,3 +194,92 @@ func TestBinaryFilesDoNotStarveSourceDiffs(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func gitRepo(t *testing.T) (string, func(...string)) {
|
||||
t.Helper()
|
||||
if _, err := exec.LookPath("git"); err != nil {
|
||||
t.Skip("git unavailable")
|
||||
}
|
||||
dir := t.TempDir()
|
||||
run := func(args ...string) {
|
||||
t.Helper()
|
||||
cmd := exec.Command("git", append([]string{"-C", dir, "-c", "user.email=t@example.invalid", "-c", "user.name=t", "-c", "commit.gpgsign=false"}, args...)...)
|
||||
if data, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("%v: %v %s", args, err, data)
|
||||
}
|
||||
}
|
||||
run("init", "-q")
|
||||
return dir, run
|
||||
}
|
||||
|
||||
// TestOverBudgetChangeIsListedWithoutPatch is the run-236 regression: a
|
||||
// workspace whose text exceeds the snapshot budget must still list the one
|
||||
// changed file (sorted last, after the budget is exhausted) instead of
|
||||
// returning files: [] with every late path skipped.
|
||||
func TestOverBudgetChangeIsListedWithoutPatch(t *testing.T) {
|
||||
restore := SetSnapshotBudgetForTesting(64)
|
||||
defer restore()
|
||||
dir, git := gitRepo(t)
|
||||
if err := os.MkdirAll(filepath.Join(dir, "web/src"), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for i := 0; i < 20; i++ {
|
||||
put(t, dir, fmt.Sprintf("a-%02d.txt", i), strings.Repeat("filler\n", 4))
|
||||
}
|
||||
put(t, dir, "web/src/Inbox.test.tsx", "it('works')\n")
|
||||
git("add", ".")
|
||||
git("commit", "-qm", "init")
|
||||
ctx := context.Background()
|
||||
before := Capture(ctx, dir)
|
||||
put(t, dir, "web/src/Inbox.test.tsx", "it('works')\nit('more')\n")
|
||||
changes := Compare(before, Capture(ctx, dir, before))
|
||||
if len(changes.Files) != 1 || changes.Files[0].Path != "web/src/Inbox.test.tsx" {
|
||||
t.Fatalf("over-budget change not listed: %+v", changes)
|
||||
}
|
||||
if f := changes.Files[0]; f.Kind != "modified" || !f.NoPatch || f.Patch != "" {
|
||||
t.Fatalf("over-budget change should be listed without patch: %+v", f)
|
||||
}
|
||||
if changes.Status != "partial" || changes.Skipped != 0 {
|
||||
t.Fatalf("status/skipped = %q/%d, want partial/0", changes.Status, changes.Skipped)
|
||||
}
|
||||
// Unchanged over-budget files are compared by hash, so a visit that edits
|
||||
// nothing is a complete, empty capture rather than a partial one.
|
||||
again := Capture(ctx, dir)
|
||||
if empty := Compare(again, Capture(ctx, dir, again)); empty.Status != "complete" || len(empty.Files) != 0 {
|
||||
t.Fatalf("no-op over-budget visit = %+v, want complete and empty", empty)
|
||||
}
|
||||
}
|
||||
|
||||
// TestGitStatusListsUncomparableChanges proves a file the content snapshot
|
||||
// skips (here: above the hash bound) is still listed when its Git status
|
||||
// changes during the visit, while a protected path never is.
|
||||
func TestGitStatusListsUncomparableChanges(t *testing.T) {
|
||||
previous := maxHashBytes
|
||||
maxHashBytes = 16
|
||||
defer func() { maxHashBytes = previous }()
|
||||
dir, git := gitRepo(t)
|
||||
put(t, dir, "big.bin", strings.Repeat("x", 64))
|
||||
put(t, dir, ".env", "A=1\n")
|
||||
put(t, dir, "small.txt", "one\n")
|
||||
git("add", "big.bin", "small.txt")
|
||||
git("commit", "-qm", "init")
|
||||
ctx := context.Background()
|
||||
before := Capture(ctx, dir)
|
||||
put(t, dir, "big.bin", strings.Repeat("y", 64))
|
||||
put(t, dir, "fresh.bin", strings.Repeat("z", 64))
|
||||
put(t, dir, ".env", "A=2\n")
|
||||
changes := Compare(before, Capture(ctx, dir, before))
|
||||
got := map[string]string{}
|
||||
for _, f := range changes.Files {
|
||||
if !f.NoPatch {
|
||||
t.Fatalf("git-listed change carries a patch: %+v", f)
|
||||
}
|
||||
got[f.Path] = f.Kind
|
||||
}
|
||||
if len(got) != 2 || got["big.bin"] != "modified" || got["fresh.bin"] != "added" {
|
||||
t.Fatalf("git status listing = %v (%+v)", got, changes)
|
||||
}
|
||||
if changes.Status != "partial" || !strings.Contains(changes.Diagnostic, "without patches") {
|
||||
t.Fatalf("status/diagnostic = %q/%q", changes.Status, changes.Diagnostic)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user