Skip to content

Commit 9eda615

Browse files
donislawdevclaude
andcommitted
A tar.gz one byte over its cut frame's floor keeps the uncut layout
One byte of spare goes to the comment, as a space behind the label. Without a label no part of the frame takes it, and planning ended in an internal defect - 9757 B with no label, cut half way. Such a size now keeps the layout of an archive nothing cuts, as sizes below the floor do, and a new guard writes the first sizes from the smallest with a label and without. The reader of maps stops on a deflate stream that ends inside a code, where the bits past the end read as zeros and a code of zeros decoded for ever, and on a tar header with a size below zero, which held the walk in place. The map guard hands it one of each. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 237d11e commit 9eda615

5 files changed

Lines changed: 167 additions & 17 deletions

File tree

‎internal/format/targz/cut.go‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -162,7 +162,9 @@ func layOut(m memo, label string, content, target int64) (frame, bool, error) {
162162
head := gzipHead + commentCost(label)
163163
dirs := fewestBlocks(dirsLength(m)).length()
164164
spare := target - (head + dirs + content + tailFloor + gzipTrailer)
165-
if spare < 0 {
165+
if spare < 0 || spare == 1 && label == "" {
166+
// One byte over the frame's floor can go only to the comment, as a
167+
// space behind the label, so without a label it does not fit either.
166168
return frame{}, false, nil
167169
}
168170
want := min(max(format.PaddingInFront(head+dirs, content, m.cutAt, target), 0), spare)
@@ -345,6 +347,8 @@ func writeForACut(ctx context.Context, w io.Writer, m memo) error {
345347
}
346348
var trailer [gzipTrailer]byte
347349
binary.LittleEndian.PutUint32(trailer[:4], sum.crc.Sum32())
350+
// ISIZE is the length modulo 2^32 (RFC 1952 section 2.3.1), so the
351+
// conversion drops what it should.
348352
binary.LittleEndian.PutUint32(trailer[4:], uint32(sum.n))
349353
_, err := w.Write(trailer[:])
350354
return err

‎internal/guard/filemap_test.go‎

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package guard
22

33
import (
4+
"bytes"
5+
"compress/gzip"
46
"errors"
57
"fmt"
68
"io"
@@ -191,6 +193,7 @@ func TestEveryFormatsMapIsTheOneItsStructureReadsBack(t *testing.T) {
191193
t.Errorf("canary: a file with no padding behind its content passed for the layout due at the first byte")
192194
}
193195
askTheLastEndCanaries(t, dir)
196+
askTheReaderOfMapsToStop(t, dir)
194197
t.Logf("%d files, %d with padding, %d of them on both sides of the content, %d cut at the ends of a split", len(files), padded, split, ends)
195198
}
196199

@@ -293,6 +296,71 @@ func askTheLastEndCanaries(t *testing.T, dir string) {
293296
}
294297
}
295298

299+
// askTheReaderOfMapsToStop hands the reader of maps two tar.gz files it must
300+
// refuse rather than read for ever: a squeezed one cut half way, whose last
301+
// Huffman code runs off the end, where the bits read as zeros and a code of
302+
// zeros for a byte decoded again and again, and one whose tar header gives a
303+
// size below zero, which held the walk through the tar in place
304+
// (docs/REVIEW-240-2026-11-13.md). A loop comes back as the guard's time
305+
// running out, a refusal of another kind as the words it gives.
306+
func askTheReaderOfMapsToStop(t *testing.T, dir string) {
307+
t.Helper()
308+
// Letters drawn unevenly and without a period, so the stream codes mostly
309+
// single bytes in a block of its own codes.
310+
var text bytes.Buffer
311+
x := uint32(1)
312+
for range 4000 {
313+
x = x*1103515245 + 12345
314+
text.WriteByte("aaaaaaaabbbcd"[x>>16%13])
315+
}
316+
squeezed := gzipped(t, text.Bytes(), gzip.BestCompression)
317+
header := make([]byte, 512)
318+
copy(header, "a.txt")
319+
copy(header[124:], "-0000001000")
320+
cases := []struct {
321+
name, says string
322+
data []byte
323+
setting map[string]string
324+
}{
325+
{"cut", "runs off the end of the file at bit", squeezed[:len(squeezed)/2], map[string]string{"compression": "best"}},
326+
{"below-zero", "gives a size below zero", gzipped(t, append(header, make([]byte, 1024)...), gzip.NoCompression), nil},
327+
}
328+
reqs := make([]oracle.LayoutRequest, len(cases))
329+
for i, c := range cases {
330+
path := filepath.Join(dir, "canary-"+c.name+".targz")
331+
if err := os.WriteFile(path, c.data, 0o600); err != nil {
332+
t.Fatal(err)
333+
}
334+
reqs[i] = oracle.LayoutRequest{Format: "targz", Path: path, Settings: c.setting}
335+
}
336+
got, _, err := oracle.LayoutBatch(t.Context(), reqs)
337+
if err != nil {
338+
t.Fatalf("canary: reading the maps back: %v", err)
339+
}
340+
for i, c := range cases {
341+
if !strings.Contains(got[i].Error, c.says) {
342+
t.Errorf("canary: the reader of maps answered a tar.gz %s with %q, where %q was due", c.name, got[i].Error, c.says)
343+
}
344+
}
345+
}
346+
347+
// gzipped is data in one gzip member, at level.
348+
func gzipped(t *testing.T, data []byte, level int) []byte {
349+
t.Helper()
350+
var out bytes.Buffer
351+
zw, err := gzip.NewWriterLevel(&out, level)
352+
if err != nil {
353+
t.Fatal(err)
354+
}
355+
if _, err := zw.Write(data); err != nil {
356+
t.Fatal(err)
357+
}
358+
if err := zw.Close(); err != nil {
359+
t.Fatal(err)
360+
}
361+
return out.Bytes()
362+
}
363+
296364
// writeMapped writes one healthy file of f through a map recorder, laid out
297365
// for a cut at cutAt when that is not zero.
298366
func writeMapped(t *testing.T, dir string, f format.Descriptor, name string, setting map[string]string, size, cutAt int64) mappedFile {

‎internal/guard/mutationcoverage_test.go‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,9 @@ var provenByProbe = map[string]string{
159159
"fixed codes, must inflate to its bytes and read as those runs - its reach check, every frame of the marker met - and red on " +
160160
"2026-11-13 for a frame a byte short (the plan refuses at 65541 B) and for an empty block's BTYPE bit one place off " +
161161
"(compress/flate refuses at 65537 B), where the first passed the share and the map guards.",
162+
"TestATarGzCutNearItsSmallestComesToEverySize": "its reach check - the frame met, and without a label the size after its floor " +
163+
"that keeps the layout of an archive nothing cuts, which with a label is due never - and red on 2026-11-13 without the " +
164+
"case of one byte over the floor (an internal defect at 9757 B) and with that case taken for a label too (label true).",
162165
"TestACutAtTheSmallestSizeSaysHowLongTheContentWas": "its own canaries - a cut that does not state the content's length, and one stating a " +
163166
"byte less than the map runs, must not pass - its reach check - the ZIP packages at their smallest have no padding in front and are cut " +
164167
"in the content - and red on 2026-11-13 before the Office packages marked their parts with a length without a padding part in front: " +

‎internal/guard/targzcut_test.go‎

Lines changed: 75 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -72,26 +72,91 @@ func TestATarGzLaidOutForACutComesToEverySizeAndReads(t *testing.T) {
7272
}
7373
}
7474

75+
// A tar.gz a damage cuts comes to every size from its smallest, with a label
76+
// and without.
77+
//
78+
// The frame for a cut costs a few bytes more than the smallest archive, so
79+
// near the smallest size an archive keeps the layout of one nothing cuts until
80+
// the frame fits. One byte over the frame's floor goes to the comment, as a
81+
// space behind the label. Without a label no field takes it, and that size
82+
// stopped the run with an internal defect (docs/REVIEW-240-2026-11-13.md). So
83+
// this writes the first sizes from the smallest, cut half way and not, holds
84+
// each to its size and to compress/gzip and archive/tar, and asserts that it
85+
// met the frame - and, only without a label, the size after its floor that
86+
// keeps the layout of an archive nothing cuts.
87+
func TestATarGzCutNearItsSmallestComesToEverySize(t *testing.T) {
88+
desc, err := format.Get("targz")
89+
if err != nil {
90+
t.Fatal(err)
91+
}
92+
for _, label := range []bool{false, true} {
93+
smallest := desc.SmallestAccepted(format.Request{Label: label})
94+
framed, plainAfter := false, false
95+
for size := smallest; size < smallest+16; size++ {
96+
req := format.Request{Bytes: size, Label: label, Seed: 7}
97+
if _, err := desc.Generator.Plan(req); err != nil {
98+
// The one size in the gap just above the smallest archive.
99+
continue
100+
}
101+
plain := writeRequest(t, desc, req)
102+
req.CutAt = size / 2
103+
cut := writeRequest(t, desc, req)
104+
if int64(len(cut)) != size {
105+
t.Errorf("label %v, %d B: a cut half way came to %d B", label, size, len(cut))
106+
continue
107+
}
108+
if _, err := entriesRead(cut); err != nil {
109+
t.Errorf("label %v, %d B: %v", label, size, err)
110+
}
111+
laid := !bytes.Equal(cut, plain)
112+
plainAfter = plainAfter || framed && !laid
113+
framed = framed || laid
114+
}
115+
if !framed {
116+
t.Errorf("label %v: none of the 16 sizes from %d B was laid out for a cut", label, smallest)
117+
}
118+
if plainAfter != !label {
119+
t.Errorf("label %v: a size after the frame's floor kept the layout of an archive nothing cuts: %v - due only without a label", label, plainAfter)
120+
}
121+
}
122+
}
123+
75124
// writeWhole writes a tar.gz of size bytes laid out for a cut half way, whole.
76125
func writeWhole(t *testing.T, desc format.Descriptor, size int64) []byte {
77126
t.Helper()
78-
p, err := desc.Generator.Plan(format.Request{Bytes: size, Label: true, Seed: 7, CutAt: size / 2})
127+
return writeRequest(t, desc, format.Request{Bytes: size, Label: true, Seed: 7, CutAt: size / 2})
128+
}
129+
130+
// writeRequest plans and writes req, whole.
131+
func writeRequest(t *testing.T, desc format.Descriptor, req format.Request) []byte {
132+
t.Helper()
133+
p, err := desc.Generator.Plan(req)
79134
if err != nil {
80-
t.Fatalf("%d B: planning: %v", size, err)
135+
t.Fatalf("%d B: planning: %v", req.Bytes, err)
81136
}
82137
var out bytes.Buffer
83138
if err := desc.Generator.Write(t.Context(), &out, p); err != nil {
84-
t.Fatalf("%d B: writing: %v", size, err)
139+
t.Fatalf("%d B: writing: %v", req.Bytes, err)
85140
}
86141
return out.Bytes()
87142
}
88143

89-
// readsEveryEntry reads every entry of a tar.gz to its end, through
90-
// compress/gzip, which checks the trailer, and archive/tar.
144+
// readsEveryEntry reads every entry of a tar.gz laid out for a cut to its end,
145+
// and holds it to a file and padding beside it.
91146
func readsEveryEntry(data []byte) error {
147+
files, err := entriesRead(data)
148+
if err == nil && files < 2 {
149+
err = fmt.Errorf("%d entries, where a file and padding beside it were due", files)
150+
}
151+
return err
152+
}
153+
154+
// entriesRead reads every entry of a tar.gz to its end, through
155+
// compress/gzip, which checks the trailer, and archive/tar, and counts them.
156+
func entriesRead(data []byte) (int, error) {
92157
zr, err := gzip.NewReader(bytes.NewReader(data))
93158
if err != nil {
94-
return err
159+
return 0, err
95160
}
96161
tr := tar.NewReader(zr)
97162
files := 0
@@ -101,20 +166,17 @@ func readsEveryEntry(data []byte) error {
101166
break
102167
}
103168
if err != nil {
104-
return err
169+
return files, err
105170
}
106171
if _, err := io.Copy(io.Discard, tr); err != nil {
107-
return fmt.Errorf("%s: %w", h.Name, err)
172+
return files, fmt.Errorf("%s: %w", h.Name, err)
108173
}
109174
files++
110175
}
111176
if _, err := io.Copy(io.Discard, zr); err != nil {
112-
return fmt.Errorf("after the tar: %w", err)
113-
}
114-
if files < 2 {
115-
return fmt.Errorf("%d entries, where a file and padding beside it were due", files)
177+
return files, fmt.Errorf("after the tar: %w", err)
116178
}
117-
return nil
179+
return files, nil
118180
}
119181

120182
// gzipStreamStart is where the deflate stream of a gzip member starts: after

‎internal/oracle/layout.py‎

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -324,12 +324,22 @@ def __init__(self, data, pos):
324324
self.data, self.at = data, pos * 8
325325

326326
def peek(self, n):
327+
"""The next n bits, as zeros past the end of the data, so a short code
328+
at the very end still decodes."""
327329
i = self.at >> 3
328330
return (int.from_bytes(self.data[i:i + 4], "little") >> (self.at & 7)) & ((1 << n) - 1)
329331

332+
def skip(self, n):
333+
"""Moves past n bits, and stops a stream that runs off the end of the
334+
data: there peek reads zeros, and a code of zeros for a byte would
335+
otherwise decode for ever."""
336+
self.at += n
337+
if self.at > len(self.data) * 8:
338+
raise NoMap(f"the deflate stream runs off the end of the file at bit {self.at - n}")
339+
330340
def take(self, n):
331341
value = self.peek(n)
332-
self.at += n
342+
self.skip(n)
333343
return value
334344

335345

@@ -361,7 +371,7 @@ def decode(bits, code):
361371
symbol, n = table[bits.peek(maxbits)]
362372
if symbol is None:
363373
raise NoMap(f"no Huffman code opens the bits at {bits.at}")
364-
bits.at += n
374+
bits.skip(n)
365375
return symbol
366376

367377

@@ -412,7 +422,7 @@ def inflated_length(bits, literals, distances):
412422
distance = decode(bits, distances)
413423
if distance > 29:
414424
raise NoMap(f"the distance code {distance} at {bits.at} is not one")
415-
bits.at += DISTANCE_EXTRA[distance]
425+
bits.skip(DISTANCE_EXTRA[distance])
416426

417427

418428
def deflate_blocks(data, pos):
@@ -476,6 +486,9 @@ def add(role, at):
476486
return parts
477487
name = head[:100].rstrip(b"\x00")
478488
size = int(head[124:136].rstrip(b"\x00 ") or b"0", 8)
489+
if size < 0:
490+
# int() takes a sign, and a size below zero would hold t in place.
491+
raise NoMap(f"the tar header at {t} gives a size below zero")
479492
kind = head[156:157]
480493
if name in (b"tfg-padding.bin", b"tfg-padding-end.bin"):
481494
role = PADDING

0 commit comments

Comments
 (0)