diff --git a/seaweed-block/core/frontend/chunkstore/layout/list_page.go b/seaweed-block/core/frontend/chunkstore/layout/list_page.go new file mode 100644 index 0000000000..24b23e8b75 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/list_page.go @@ -0,0 +1,243 @@ +package layout + +import ( + "bytes" + "encoding/json" + "fmt" + "strings" +) + +// These are format ceilings, not work timeouts. Reading one page never +// requires materializing its chain. A producer must stop before exceeding +// them; it may not truncate a list or omit required candidates. +const ( + ListPageVersion = 1 + ListDir = "lists" + MaxListPageBytes = 1 << 20 + MaxListPageEntries = 4096 + MaxListPages = 4096 + MaxListProducerBytes = 256 +) + +type ListKind string + +const ( + ListDrop ListKind = "drop" + ListUploadIntent ListKind = "upload-intent" + ListSnapshotDeleteIntent ListKind = "snapshot-delete-intent" +) + +// ListRef binds the exact bytes and remaining page count. Pages decreases +// strictly along Next, so a reader never follows an unbounded/cyclic chain. +type ListRef struct { + Hash string `json:"hash"` + Pages uint32 `json:"pages"` +} + +func (r ListRef) check() error { + h, err := parseHash(r.Hash) + if err != nil || h.String() != r.Hash || r.Pages == 0 || r.Pages > MaxListPages { + return fmt.Errorf("%w: invalid list reference", ErrMalformed) + } + return nil +} +func (r ListRef) Path() (string, error) { + if err := r.check(); err != nil { + return "", err + } + return ListDir + "/" + r.Hash, nil +} + +// SnapshotTarget is an admitted snapshot incarnation, never a resolution +// of the name made again by a later executor. VolumeID is on its page. +type SnapshotTarget struct { + Name string `json:"name"` + Gen uint64 `json:"gen"` +} + +// ListPage is immutable metadata. Its presence grants no delete/upload +// authority. A writer publishes its reference through HEAD only after the +// page is durable; producer and consumer wiring is a separate transition. +type ListPage struct { + VolumeID VolumeID + Kind ListKind + Producer string + Generation uint64 + Pages uint32 + Next *ListRef + Target *SnapshotTarget + Entries []string +} + +type listPageDoc struct { + Version int `json:"version"` + VolumeID string `json:"volume_id"` + Kind ListKind `json:"kind"` + Producer string `json:"producer"` + Generation uint64 `json:"generation"` + Pages uint32 `json:"pages"` + Next *ListRef `json:"next,omitempty"` + Target *SnapshotTarget `json:"target,omitempty"` + Entries []string `json:"entries"` +} + +func (p ListPage) check() error { + if p.VolumeID.IsZero() || p.Generation == 0 || p.Pages == 0 || p.Pages > MaxListPages { + return fmt.Errorf("%w: list page identity or page count", ErrMalformed) + } + if p.Producer == "" || len(p.Producer) > MaxListProducerBytes { + return fmt.Errorf("%w: list page producer", ErrMalformed) + } + if err := validName("list producer", p.Producer); err != nil { + return err + } + switch p.Kind { + case ListDrop: + case ListUploadIntent: + if p.Target != nil { + return fmt.Errorf("%w: upload intent has a snapshot target", ErrMalformed) + } + case ListSnapshotDeleteIntent: + if p.Target == nil { + return fmt.Errorf("%w: snapshot-delete intent needs its captured target", ErrMalformed) + } + default: + return fmt.Errorf("%w: unknown list kind %q", ErrMalformed, p.Kind) + } + if p.Target != nil { + if p.Target.Gen == 0 { + return fmt.Errorf("%w: list snapshot target generation zero", ErrMalformed) + } + if err := CheckSnapshot(p.Target.Name, SnapshotMeta{}); err != nil { + return err + } + } + if p.Next == nil { + if p.Pages != 1 { + return fmt.Errorf("%w: list chain ends before its declared count", ErrMalformed) + } + } else { + if err := p.Next.check(); err != nil { + return err + } + if p.Pages != p.Next.Pages+1 { + return fmt.Errorf("%w: list page count does not decrease by one", ErrMalformed) + } + } + if len(p.Entries) == 0 || len(p.Entries) > MaxListPageEntries { + return fmt.Errorf("%w: list page entry count", ErrMalformed) + } + for i, rel := range p.Entries { + if i > 0 && p.Entries[i-1] >= rel { + return fmt.Errorf("%w: list names not sorted and unique", ErrMalformed) + } + if err := checkListObjectPath(rel); err != nil { + return err + } + } + return nil +} + +// checkListObjectPath accepts canonical content-named data objects only. +// HEAD, VOLUME, another list, arbitrary paths and foreign directories are +// never candidates merely because a page contains a string naming them. +func checkListObjectPath(rel string) error { + parts := strings.Split(rel, "/") + if len(parts) == 2 { + switch parts[0] { + case RootDir: + n, err := ParseRootName(parts[1]) + if err == nil && n.Path() == rel { + return nil + } + case SegDir: + n, err := ParseSegName(parts[1]) + if err == nil && n.Path() == rel { + return nil + } + } + } + if len(parts) == 3 && parts[0] == PoolDir { + n, err := ParseChunkName(parts[2]) + if err == nil && n.Path() == rel { + return nil + } + } + return fmt.Errorf("%w: list candidate %q is not a canonical object path", ErrMalformed, rel) +} + +func (p ListPage) Encode() ([]byte, error) { + if err := p.check(); err != nil { + return nil, err + } + d := listPageDoc{Version: ListPageVersion, VolumeID: p.VolumeID.String(), Kind: p.Kind, Producer: p.Producer, Generation: p.Generation, Pages: p.Pages, Next: p.Next, Target: p.Target, Entries: p.Entries} + b, err := json.Marshal(d) + if err == nil && len(b) > MaxListPageBytes { + return nil, fmt.Errorf("%w: list page exceeds byte limit", ErrMalformed) + } + return b, err +} + +func listPageHash(raw []byte) string { + return Sum(append([]byte("swblock:list-page:v1\x00"), raw...)).String() +} +func (p ListPage) Ref() (ListRef, error) { + raw, err := p.Encode() + if err != nil { + return ListRef{}, err + } + return ListRef{Hash: listPageHash(raw), Pages: p.Pages}, nil +} + +var ErrListPageNewerVersion = fmt.Errorf("%w: list page written by a newer version: use a newer binary", ErrMalformed) + +// DecodeListPage checks one bounded page against the reference and full +// volume identity before any consumer can interpret its candidates. +func DecodeListPage(raw []byte, ref ListRef, volume VolumeID) (ListPage, error) { + if len(raw) > MaxListPageBytes { + return ListPage{}, fmt.Errorf("%w: list page exceeds byte limit", ErrMalformed) + } + if err := ref.check(); err != nil { + return ListPage{}, err + } + if listPageHash(raw) != ref.Hash { + return ListPage{}, fmt.Errorf("%w: list page content hash mismatch", ErrCorrupt) + } + var probe struct { + Version int `json:"version"` + } + if err := json.Unmarshal(raw, &probe); err != nil { + return ListPage{}, fmt.Errorf("%w: list page: %v", ErrMalformed, err) + } + if probe.Version > ListPageVersion { + return ListPage{}, ErrListPageNewerVersion + } + if probe.Version != ListPageVersion { + return ListPage{}, fmt.Errorf("%w: list page version %d", ErrMalformed, probe.Version) + } + var d listPageDoc + dec := json.NewDecoder(bytes.NewReader(raw)) + dec.DisallowUnknownFields() + if err := dec.Decode(&d); err != nil { + return ListPage{}, fmt.Errorf("%w: list page: %v", ErrMalformed, err) + } + id, err := ParseVolumeID(d.VolumeID) + if err != nil { + return ListPage{}, err + } + if volume.IsZero() || id != volume { + return ListPage{}, ErrIdentity + } + p := ListPage{VolumeID: id, Kind: d.Kind, Producer: d.Producer, Generation: d.Generation, Pages: d.Pages, Next: d.Next, Target: d.Target, Entries: d.Entries} + if p.Pages != ref.Pages { + return ListPage{}, fmt.Errorf("%w: list reference page count mismatch", ErrMalformed) + } + canon, err := p.Encode() + if err != nil { + return ListPage{}, err + } + if !bytes.Equal(canon, raw) { + return ListPage{}, fmt.Errorf("%w: list page is not canonical", ErrMalformed) + } + return p, nil +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/list_page_test.go b/seaweed-block/core/frontend/chunkstore/layout/list_page_test.go new file mode 100644 index 0000000000..6e026f0287 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/list_page_test.go @@ -0,0 +1,171 @@ +package layout + +import ( + "bytes" + "errors" + "fmt" + "os" + "sort" + "strings" + "testing" +) + +const dropPageGolden = `{"version":1,"volume_id":"00000000000000000000000000000001","kind":"drop","producer":"cut-a","generation":42,"pages":1,"entries":["root/0000000000000000000000000000000000000000000000000000000000000000"]}` + +func TestListPageGoldenAndContentBinding(t *testing.T) { + id, err := ParseVolumeID("00000000000000000000000000000001") + if err != nil { + t.Fatal(err) + } + // Fixed expected bytes are independent of the encoder under test. + p := ListPage{VolumeID: id, Kind: ListDrop, Producer: "cut-a", Generation: 42, Pages: 1, Entries: []string{"root/" + strings.Repeat("0", 64)}} + raw, err := p.Encode() + if err != nil { + t.Fatal(err) + } + if string(raw) != dropPageGolden { + t.Fatalf("format changed: %s", raw) + } + ref, err := p.Ref() + if err != nil { + t.Fatal(err) + } + decoded, err := DecodeListPage([]byte(dropPageGolden), ref, id) + if err != nil { + t.Fatal(err) + } + again, err := decoded.Encode() + if err != nil || !bytes.Equal(raw, again) { + t.Fatalf("round trip: %s %v", again, err) + } + corrupted := bytes.Replace(raw, []byte(`"cut-a"`), []byte(`"cut-b"`), 1) + if _, err := DecodeListPage(corrupted, ref, id); err == nil { + t.Fatal("content-name corruption accepted") + } + other := idFor("other") + if _, err := DecodeListPage(raw, ref, other); err == nil { + t.Fatal("cross-volume page accepted") + } +} + +func TestListPageGoldenVectors(t *testing.T) { + id, _ := ParseVolumeID("00000000000000000000000000000001") + for _, tc := range []struct { + name, hash string + pages uint32 + }{ + {"drop", "c63e99b5835669e4e46b4efb780e0a4fd4f55a088d78f9fb871d4caa0ed49294", 1}, + {"upload-intent", "d4ad26a9e72cfd6533188e130584ff12a45f3d402f4907a934e7ada0ad909db8", 1}, + {"delete-tail", "d30f6462321c2b060f6d3972bb01c8b70c978d3b46c1cd3752f393b429b0b548", 1}, + {"delete-head", "b6ad6d5f8d8f47fd9dd7c17b0184ae684949f7cf1f0bc13001b777e6b9b9c23a", 2}, + } { + t.Run(tc.name, func(t *testing.T) { + raw, err := os.ReadFile("testdata/list-page-v1/" + tc.name + ".json") + if err != nil { + t.Fatal(err) + } + ref := ListRef{Hash: tc.hash, Pages: tc.pages} + p, err := DecodeListPage(raw, ref, id) + if err != nil { + t.Fatal(err) + } + encoded, err := p.Encode() + if err != nil || !bytes.Equal(encoded, raw) { + t.Fatalf("golden encoding changed: %s %v", encoded, err) + } + got, err := p.Ref() + if err != nil || got != ref { + t.Fatalf("golden content name: %+v %v", got, err) + } + }) + } +} + +// Give each deliberately invalid document its own correct hash, so schema +// validation, not an unrelated hash mismatch, is what rejects it. +func TestListPageRefusesMalformedDocuments(t *testing.T) { + id, _ := ParseVolumeID("00000000000000000000000000000001") + z := strings.Repeat("0", 64) + for name, raw := range map[string]string{ + "truncated": dropPageGolden[:len(dropPageGolden)-1], + "unknown field": strings.Replace(dropPageGolden, `"version":1,`, `"version":1,"unexpected":1,`, 1), + "duplicate field": strings.Replace(dropPageGolden, `"version":1,`, `"version":1,"version":1,`, 1), + "whitespace": dropPageGolden + "\n", + "unknown kind": strings.Replace(dropPageGolden, `"kind":"drop"`, `"kind":"other"`, 1), + "zero generation": strings.Replace(dropPageGolden, `"generation":42`, `"generation":0`, 1), + "zero pages": strings.Replace(dropPageGolden, `"pages":1`, `"pages":0`, 1), + "too many pages": strings.Replace(dropPageGolden, `"pages":1`, `"pages":4097`, 1), + "early tail": strings.Replace(dropPageGolden, `"pages":1`, `"pages":2`, 1), + "bad next count": strings.Replace(dropPageGolden, `"entries":`, `"next":{"hash":"`+z+`","pages":1},"entries":`, 1), + "unbound delete": strings.Replace(dropPageGolden, `"kind":"drop"`, `"kind":"snapshot-delete-intent"`, 1), + "HEAD candidate": strings.Replace(dropPageGolden, "root/"+z, "HEAD", 1), + "list candidate": strings.Replace(dropPageGolden, "root/"+z, "lists/"+z, 1), + "wrong shard": strings.Replace(dropPageGolden, "root/"+z, "pool/1/0-"+z, 1), + "parent traversal": strings.Replace(dropPageGolden, "root/"+z, "root/../HEAD", 1), + "duplicate name": strings.Replace(dropPageGolden, `"root/`+z+`"`, `"root/`+z+`","root/`+z+`"`, 1), + "unsorted names": strings.Replace(dropPageGolden, `"root/`+z+`"`, `"root/`+strings.Repeat("1", 64)+`","root/`+z+`"`, 1), + } { + t.Run(name, func(t *testing.T) { + b := []byte(raw) + ref := ListRef{Hash: Sum(append([]byte("swblock:list-page:v1\x00"), b...)).String(), Pages: 1} + if _, err := DecodeListPage(b, ref, id); err == nil { + t.Fatal("invalid page accepted") + } + }) + } +} + +func TestListPageLimitsAndKinds(t *testing.T) { + id, _ := ParseVolumeID("00000000000000000000000000000001") + p := ListPage{VolumeID: id, Kind: ListDrop, Producer: "cut-a", Generation: 42, Pages: 1} + for i := 0; i < MaxListPageEntries; i++ { + p.Entries = append(p.Entries, fmt.Sprintf("pool/0/%d-%s", i, strings.Repeat("0", 64))) + } + // Codec requires lexical order, independent of numeric chunk order. + sort.Strings(p.Entries) + if _, err := p.Encode(); err != nil { + t.Fatalf("entry ceiling refused: %v", err) + } + p.Entries = append(p.Entries, "root/"+strings.Repeat("0", 64)) + if _, err := p.Encode(); err == nil { + t.Fatal("entry ceiling bypassed") + } + if _, err := DecodeListPage(bytes.Repeat([]byte("x"), MaxListPageBytes+1), ListRef{}, id); err == nil { + t.Fatal("oversized input accepted") + } + newer := bytes.Replace([]byte(dropPageGolden), []byte(`"version":1`), []byte(`"version":2`), 1) + r := ListRef{Hash: Sum(append([]byte("swblock:list-page:v1\x00"), newer...)).String(), Pages: 1} + if _, err := DecodeListPage(newer, r, id); !errors.Is(err, ErrListPageNewerVersion) { + t.Fatalf("newer format not named: %v", err) + } + p = ListPage{VolumeID: id, Kind: ListSnapshotDeleteIntent, Producer: "delete-a", Generation: 42, Pages: 1, Target: &SnapshotTarget{Name: "daily", Gen: 8}, Entries: []string{"root/" + strings.Repeat("0", 64)}} + if _, err := p.Encode(); err != nil { + t.Fatal(err) + } + p.Target.Gen = 0 + if _, err := p.Encode(); err == nil { + t.Fatal("legacy zero snapshot target accepted") + } + p.Target.Gen = 8 + p.Kind = ListUploadIntent + if _, err := p.Encode(); err == nil { + t.Fatal("upload intent confused with snapshot delete") + } +} + +func TestListReferenceCannotEscapeItsDirectory(t *testing.T) { + if _, err := (ListRef{Hash: "../HEAD", Pages: 1}).Path(); err == nil { + t.Fatal("unvalidated reference became a path") + } + r := ListRef{Hash: "c63e99b5835669e4e46b4efb780e0a4fd4f55a088d78f9fb871d4caa0ed49294", Pages: 1} + p, err := r.Path() + if err != nil || p != "lists/c63e99b5835669e4e46b4efb780e0a4fd4f55a088d78f9fb871d4caa0ed49294" { + t.Fatalf("path: %q %v", p, err) + } + raw := []byte(dropPageGolden) + id, _ := ParseVolumeID("00000000000000000000000000000001") + r.Pages = 2 + if _, err := DecodeListPage(raw, r, id); err == nil { + t.Fatal("HEAD page-count binding ignored") + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/testdata/list-page-v1/delete-head.json b/seaweed-block/core/frontend/chunkstore/layout/testdata/list-page-v1/delete-head.json new file mode 100644 index 0000000000..e2aa4b3e51 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/testdata/list-page-v1/delete-head.json @@ -0,0 +1 @@ +{"version":1,"volume_id":"00000000000000000000000000000001","kind":"snapshot-delete-intent","producer":"delete-a","generation":44,"pages":2,"next":{"hash":"d30f6462321c2b060f6d3972bb01c8b70c978d3b46c1cd3752f393b429b0b548","pages":1},"target":{"name":"daily","gen":42},"entries":["pool/0/0-0000000000000000000000000000000000000000000000000000000000000000"]} \ No newline at end of file diff --git a/seaweed-block/core/frontend/chunkstore/layout/testdata/list-page-v1/delete-tail.json b/seaweed-block/core/frontend/chunkstore/layout/testdata/list-page-v1/delete-tail.json new file mode 100644 index 0000000000..f3977830f0 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/testdata/list-page-v1/delete-tail.json @@ -0,0 +1 @@ +{"version":1,"volume_id":"00000000000000000000000000000001","kind":"snapshot-delete-intent","producer":"delete-a","generation":44,"pages":1,"target":{"name":"daily","gen":42},"entries":["root/0000000000000000000000000000000000000000000000000000000000000000"]} \ No newline at end of file diff --git a/seaweed-block/core/frontend/chunkstore/layout/testdata/list-page-v1/drop.json b/seaweed-block/core/frontend/chunkstore/layout/testdata/list-page-v1/drop.json new file mode 100644 index 0000000000..c41d586e55 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/testdata/list-page-v1/drop.json @@ -0,0 +1 @@ +{"version":1,"volume_id":"00000000000000000000000000000001","kind":"drop","producer":"cut-a","generation":42,"pages":1,"entries":["root/0000000000000000000000000000000000000000000000000000000000000000"]} \ No newline at end of file diff --git a/seaweed-block/core/frontend/chunkstore/layout/testdata/list-page-v1/upload-intent.json b/seaweed-block/core/frontend/chunkstore/layout/testdata/list-page-v1/upload-intent.json new file mode 100644 index 0000000000..cc829cf38a --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/testdata/list-page-v1/upload-intent.json @@ -0,0 +1 @@ +{"version":1,"volume_id":"00000000000000000000000000000001","kind":"upload-intent","producer":"cut-b","generation":43,"pages":1,"entries":["pool/0/0-0000000000000000000000000000000000000000000000000000000000000000"]} \ No newline at end of file diff --git a/seaweed-block/docs/design/immutable-list-pages.md b/seaweed-block/docs/design/immutable-list-pages.md new file mode 100644 index 0000000000..39e3577061 --- /dev/null +++ b/seaweed-block/docs/design/immutable-list-pages.md @@ -0,0 +1,43 @@ +# Immutable cleaning and intent list pages + +This Draft codec prepares persisted metadata; it has no storage writer, +HEAD publication, retirement or cleaner caller. Those transitions require +the page-chain crash refinement before integration. + +Version 1 is compact canonical JSON with keys in this order: +`version, volume_id, kind, producer, generation, pages, next?, target?, entries`. +Each reference is `{hash, pages}`. A snapshot target is `{name, gen}`. +Kinds are `drop`, `upload-intent`, and `snapshot-delete-intent`; the last +requires a captured nonzero snapshot incarnation. The enclosing full volume +ID binds it to its volume. The producer is an opaque identifier, not authority. + +The object name is SHA-256 of `swblock:list-page:v1` followed by a NUL and +the exact canonical bytes, stored under `lists/`. +The decoder checks the reference hash, full volume ID and remaining-page +count. Entries are strictly sorted unique canonical owned root/segment/chunk +paths, not HEAD, VOLUME, another list or arbitrary paths. Consumers must still +check live roots and retain the existing Stat/HEAD/conditional Mark/Delete +ordering; listing a name gives no right to remove it. + +Format ceilings (not time limits): 1 MiB per encoded page, 4,096 entries per +page, 4,096 pages per chain, 256 producer bytes. A tail has pages=1 and no next; +a non-tail has pages=next.pages+1. One read/encode allocates one bounded page, +not a volume-sized chain. A producer reaching a ceiling must refuse before +its effect, never truncate or omit required work. These explicit ceilings +are proposed for format review and must be confirmed before declaration. + +A chain reader also validates producer/kind/target/generation consistency +across pages; this codec checks one page only. The future consumer may +advance progress only after completing its effects. An unread continuation +must remain reachable until retirement is authorized. Neither an absent page +nor malformed metadata may mean empty/completed work. + +Fixed files in `layout/testdata/list-page-v1` cover a drop page, upload intent, +and a two-page snapshot-delete intent. Their independent SHA-256 names are +pinned in tests. Negative controls exercise truncation, unknown/duplicate +fields, kind confusion, identity/hash mismatch, counts, canonical ordering, +forbidden paths and size/entry limits. Unknown newer versions are refused. + +The fallback cleaner stays a full mark/sweep until a separately reviewed +switch, made safe for reachable list/intent objects. Nothing in this codec +starts that switch or weakens existing reclamation protections. \ No newline at end of file