carlos / platform Public

host: cut log and error chunks at 16 MiB serialised (H5-M7 review 1)

Astra: escaping can turn 4096 pending 8 KiB lines into 192 MiB of JSONL,
one chunk the reader's 64 MiB bound would discard. EncodeJSONLChunks
cuts at 16 MiB of encoded JSONL or 4096 lines; logship and errship
write each run as its own chunk and hold from the first unwritten one.
Reader bounds unchanged. Census: applog, apperr, host envelopes.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev b9e4162df3a6d75d1330f3924391d2e60e7f7a7e parent ff961d5
8 files changed, +249 −36
  • docs/superpowers/notes/census-proposal-sec-console-dos.md +1 −1
  • internal/apperr/read.go +6 −0
  • internal/applog/chunk.go +66 −4
  • internal/applog/chunk_test.go +39 −0
  • internal/host/errship.go +22 −13
  • internal/host/logship.go +26 −16
  • internal/host/logship_test.go +85 −0
  • internal/provision/testdata/plan14-root-reads-sec-console-dos.tsv +4 −2

CI failed — run details

diff --git a/docs/superpowers/notes/census-proposal-sec-console-dos.md b/docs/superpowers/notes/census-proposal-sec-console-dos.md
index 4871c5edf..e8f4867e6 100644
--- a/docs/superpowers/notes/census-proposal-sec-console-dos.md
+++ b/docs/superpowers/notes/census-proposal-sec-console-dos.md
@@ -2,7 +2,7 @@
Ruling `census-ruling-sec-console-dos`. The independent reviewer approves or rejects every change below, 0 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
-Envelopes re-pinned: `internal/applog`.
+Envelopes re-pinned: `internal/apperr`, `internal/applog`, `internal/host`.
Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner.
diff --git a/internal/apperr/read.go b/internal/apperr/read.go
index 96aac7cfc..c99760d22 100644
--- a/internal/apperr/read.go
+++ b/internal/apperr/read.go
@@ -32,6 +32,12 @@ func HourOf(t time.Time) string { return applog.HourOf(t) }
// EncodeChunk renders records as gzipped JSONL.
func EncodeChunk(recs []Record) ([]byte, error) { return applog.EncodeJSONL(recs) }
+// EncodeChunks renders records as the chunks a shipper writes, cut where
+// applog.EncodeJSONLChunks cuts.
+func EncodeChunks(recs []Record) ([][]Record, [][]byte, error) {
+ return applog.EncodeJSONLChunks(recs)
+}
+
// DecodeChunk parses a chunk, skipping malformed lines.
func DecodeChunk(b []byte) ([]Record, error) { return applog.DecodeJSONL[Record](b) }
diff --git a/internal/applog/chunk.go b/internal/applog/chunk.go
index f24bd43fc..350826325 100644
--- a/internal/applog/chunk.go
+++ b/internal/applog/chunk.go
@@ -184,21 +184,79 @@ func EncodeJSONL[T any](recs []T) ([]byte, error) {
return buf.Bytes(), nil
}
+// WriteChunkBytes and WriteChunkLines are where a writer cuts a chunk
+// (EncodeJSONLChunks): its serialised JSONL, before gzip, stays at or under
+// WriteChunkBytes (one record over it alone excepted) and its lines at or
+// under WriteChunkLines, a quarter and a half of what DecodeJSONL will read.
+// The size is measured after JSON escaping, which is what the reader sees:
+// a raw byte can become six (a NUL is \u0000), so 4096 pending 8 KiB lines
+// can serialise to over 192 MiB, and only cutting on the encoded size keeps
+// every chunk a writer makes readable (H5-M7 review 1).
+const (
+ WriteChunkBytes = 16 << 20
+ WriteChunkLines = MaxChunkLines / 2
+)
+
+// EncodeJSONLChunks renders recs, in order, as one or more gzipped JSONL
+// chunks cut at WriteChunkBytes and WriteChunkLines, returning each chunk's
+// records with its body. A shipper writes each as its own chunk, keyed by
+// its first record.
+func EncodeJSONLChunks[T any](recs []T) (runs [][]T, bodies [][]byte, err error) {
+ var line, run bytes.Buffer
+ enc := json.NewEncoder(&line)
+ start, n := 0, 0
+ cut := func(end int) error {
+ var buf bytes.Buffer
+ zw := gzip.NewWriter(&buf)
+ if _, err := zw.Write(run.Bytes()); err != nil {
+ return err
+ }
+ if err := zw.Close(); err != nil {
+ return err
+ }
+ runs, bodies = append(runs, recs[start:end:end]), append(bodies, buf.Bytes())
+ run.Reset()
+ start, n = end, 0
+ return nil
+ }
+ for i, r := range recs {
+ line.Reset()
+ if err := enc.Encode(r); err != nil {
+ return nil, nil, err
+ }
+ if n > 0 && (run.Len()+line.Len() > WriteChunkBytes || n >= WriteChunkLines) {
+ if err := cut(i); err != nil {
+ return nil, nil, err
+ }
+ }
+ run.Write(line.Bytes())
+ n++
+ }
+ if n > 0 {
+ if err := cut(len(recs)); err != nil {
+ return nil, nil, err
+ }
+ }
+ return runs, bodies, nil
+}
+
// MaxChunkLines and MaxChunkBytes bound what DecodeJSONL will decode from
// one chunk (H5-M7). A chunk is written by a box, so the reader cannot
// trust its size: a few KiB of gzip can expand to hundreds of thousands of
// records, all decoded before any filter or collect cap could drop them.
// The bounds sit well above anything a shipper writes: host's logship and
-// errship put at most logshipMaxPending (4096) records in one chunk, and an
-// app line is at most execLogLineMax (8 KiB) before the tee truncates it,
-// so a genuine chunk is under 4096 lines and about 32 MiB decoded.
+// errship cut their chunks at WriteChunkBytes and WriteChunkLines
+// (EncodeJSONLChunks). A chunk written before that cut could serialise
+// past MaxChunkBytes only through pathological escaping (thousands of
+// pending lines of control characters, each byte six on the wire); such a
+// chunk is refused here and its read reports itself truncated (ReadChunks).
const (
MaxChunkLines = 8192
MaxChunkBytes = 64 << 20
)
// ErrChunkTooLarge is DecodeJSONL refusing a chunk past MaxChunkLines or
-// MaxChunkBytes. No shipper writes one, so it is not a log to show.
+// MaxChunkBytes. No current shipper writes one, so it is not a log to show.
var ErrChunkTooLarge = errors.New("applog: chunk decodes past its bound")
// DecodeJSONL parses a chunk, skipping malformed lines rather than failing
@@ -241,5 +299,9 @@ func DecodeJSONL[T any](b []byte) ([]T, error) {
// EncodeChunk renders log records: EncodeJSONL over Record.
func EncodeChunk(recs []Record) ([]byte, error) { return EncodeJSONL(recs) }
+// EncodeChunks renders log records as the chunks a shipper writes:
+// EncodeJSONLChunks over Record.
+func EncodeChunks(recs []Record) ([][]Record, [][]byte, error) { return EncodeJSONLChunks(recs) }
+
// DecodeChunk parses a log chunk: DecodeJSONL over Record.
func DecodeChunk(b []byte) ([]Record, error) { return DecodeJSONL[Record](b) }
diff --git a/internal/applog/chunk_test.go b/internal/applog/chunk_test.go
index a2b440526..8097cec5f 100644
--- a/internal/applog/chunk_test.go
+++ b/internal/applog/chunk_test.go
@@ -5,6 +5,7 @@ import (
"compress/gzip"
"errors"
"io"
+ "strings"
"testing"
"time"
)
@@ -214,3 +215,41 @@ func TestDecodeJSONLRefusesPastItsBounds(t *testing.T) {
t.Fatalf("chunk over MaxChunkBytes: %d records, %v; want ErrChunkTooLarge", len(recs), err)
}
}
+
+// EncodeJSONLChunks cuts on the serialised size the reader will see, escaping
+// included (H5-M7 review 1): every chunk decodes within WriteChunkBytes and
+// WriteChunkLines, and the runs are recs in order.
+func TestEncodeJSONLChunksCutsAtTheWriteBound(t *testing.T) {
+ msg := strings.Repeat("\x00", 8<<10) // 8 KiB on the tee, 48 KiB as JSON
+ var recs []Record
+ for i := 0; i < 1000; i++ {
+ recs = append(recs, Record{Seq: uint64(i), Msg: msg})
+ }
+ for i := 0; i < 2*WriteChunkLines; i++ { // tiny lines: the line cut
+ recs = append(recs, Record{Seq: uint64(1000 + i)})
+ }
+ runs, bodies, err := EncodeJSONLChunks(recs)
+ if err != nil || len(runs) != len(bodies) || len(runs) < 4 {
+ t.Fatalf("%d runs, %d bodies, %v", len(runs), len(bodies), err)
+ }
+ next := 0
+ for i, run := range runs {
+ raw := mustGunzip(t, bodies[i])
+ if len(raw) > WriteChunkBytes || len(run) > WriteChunkLines {
+ t.Fatalf("chunk %d: %d bytes, %d lines; want at most %d and %d", i, len(raw), len(run), WriteChunkBytes, WriteChunkLines)
+ }
+ got, err := DecodeChunk(bodies[i])
+ if err != nil || len(got) != len(run) {
+ t.Fatalf("chunk %d decodes to %d records, %v; want %d", i, len(got), err, len(run))
+ }
+ for _, r := range run {
+ if r.Seq != uint64(next) {
+ t.Fatalf("chunk %d holds seq %d, want %d", i, r.Seq, next)
+ }
+ next++
+ }
+ }
+ if next != len(recs) {
+ t.Fatalf("runs hold %d records, want %d", next, len(recs))
+ }
+}
diff --git a/internal/host/errship.go b/internal/host/errship.go
index d5adde012..c6e5ea76c 100644
--- a/internal/host/errship.go
+++ b/internal/host/errship.go
@@ -70,32 +70,41 @@ func errshipGather(sink *apperr.Sink, pending map[applog.AppKey][]apperr.Record)
}
}
-// errshipFlush writes one create-only chunk per pending app and forgets
-// what landed; a failed app keeps its records for the next round.
+// errshipFlush writes each pending app's records as create-only chunks, cut
+// as logshipFlush cuts them, and forgets what landed; a failed app keeps
+// the records from its first unwritten chunk on for the next round.
func errshipFlush(ctx context.Context, s release.Store, pending map[applog.AppKey][]apperr.Record, ledger *pruneLedger) {
for k, recs := range pending {
if len(recs) == 0 || strings.HasPrefix(k.App, demo.AppPrefix) {
delete(pending, k)
continue
}
- body, err := apperr.EncodeChunk(recs)
+ runs, bodies, err := apperr.EncodeChunks(recs)
if err != nil {
log.Printf("agent: errship encode %s/%s: %v (dropping %d records)", k.Acct, k.App, err, len(recs))
delete(pending, k)
continue
}
- key, err := apperr.ChunkKey(k.Acct, k.App, recs[0].Box, apperr.HourOf(recs[0].TS), recs[0].Seq, len(body))
- if err != nil {
- unshippable(applog.FamilyErrors, k, err)
- delete(pending, k)
- continue
+ done := 0
+ for i, run := range runs {
+ key, err := apperr.ChunkKey(k.Acct, k.App, run[0].Box, apperr.HourOf(run[0].TS), run[0].Seq, len(bodies[i]))
+ if err != nil {
+ unshippable(applog.FamilyErrors, k, err)
+ done = len(recs)
+ break
+ }
+ if _, err := s.Put(ctx, key, bodies[i], ""); err != nil {
+ log.Printf("agent: errship flush %s/%s: %v (%d records held)", k.Acct, k.App, err, len(recs)-done)
+ break
+ }
+ ledger.wrote(k, key, len(bodies[i]))
+ done += len(run)
}
- if _, err := s.Put(ctx, key, body, ""); err != nil {
- log.Printf("agent: errship flush %s/%s: %v (%d records held)", k.Acct, k.App, err, len(recs))
- continue
+ if done == len(recs) {
+ delete(pending, k)
+ } else {
+ pending[k] = recs[done:]
}
- ledger.wrote(k, key, len(body))
- delete(pending, k)
}
}
diff --git a/internal/host/logship.go b/internal/host/logship.go
index 4023cac68..89376b1b0 100644
--- a/internal/host/logship.go
+++ b/internal/host/logship.go
@@ -112,35 +112,45 @@ func logshipGather(sink *applog.Sink, pending map[applog.AppKey][]applog.Record)
}
}
-// logshipFlush writes one chunk per pending app — create-only, keyed by the
-// batch's first seq, so a retried batch can never overwrite a delivered one
-// — and forgets what landed, telling ledger what it wrote. A failed app
-// keeps its records for the next round; other apps' flushes proceed
-// regardless.
+// logshipFlush writes each pending app's records as chunks — create-only,
+// each keyed by its batch's first seq, so a retried batch can never
+// overwrite a delivered one — and forgets what landed, telling ledger what
+// it wrote. The batch is cut where applog.EncodeChunks cuts (16 MiB of
+// serialised JSONL), so every chunk stays readable by the console's
+// decoder (H5-M7). A failed app keeps the records from its first unwritten
+// chunk on for the next round; other apps' flushes proceed regardless.
func logshipFlush(ctx context.Context, s release.Store, pending map[applog.AppKey][]applog.Record, ledger *pruneLedger) {
for k, recs := range pending {
if len(recs) == 0 || strings.HasPrefix(k.App, demo.AppPrefix) {
delete(pending, k)
continue
}
- body, err := applog.EncodeChunk(recs)
+ runs, bodies, err := applog.EncodeChunks(recs)
if err != nil { // marshal of our own records — a bug, not a retry case
log.Printf("agent: logship encode %s/%s: %v (dropping %d records)", k.Acct, k.App, err, len(recs))
delete(pending, k)
continue
}
- key, err := applog.ChunkKey(k.Acct, k.App, recs[0].Box, applog.HourOf(recs[0].TS), recs[0].Seq, len(body))
- if err != nil {
- unshippable(applog.FamilyLogs, k, err)
- delete(pending, k)
- continue
+ done := 0
+ for i, run := range runs {
+ key, err := applog.ChunkKey(k.Acct, k.App, run[0].Box, applog.HourOf(run[0].TS), run[0].Seq, len(bodies[i]))
+ if err != nil {
+ unshippable(applog.FamilyLogs, k, err)
+ done = len(recs)
+ break
+ }
+ if _, err := s.Put(ctx, key, bodies[i], ""); err != nil {
+ log.Printf("agent: logship flush %s/%s: %v (%d records held)", k.Acct, k.App, err, len(recs)-done)
+ break
+ }
+ ledger.wrote(k, key, len(bodies[i]))
+ done += len(run)
}
- if _, err := s.Put(ctx, key, body, ""); err != nil {
- log.Printf("agent: logship flush %s/%s: %v (%d records held)", k.Acct, k.App, err, len(recs))
- continue
+ if done == len(recs) {
+ delete(pending, k)
+ } else {
+ pending[k] = recs[done:]
}
- ledger.wrote(k, key, len(body))
- delete(pending, k)
}
}
diff --git a/internal/host/logship_test.go b/internal/host/logship_test.go
index 2450259e4..b370321fa 100644
--- a/internal/host/logship_test.go
+++ b/internal/host/logship_test.go
@@ -167,3 +167,88 @@ func mustKey(t testing.TB) func(string, error) string {
return k
}
}
+
+// worstCaseRecords is logshipMaxPending records of 8 KiB app lines made of
+// NULs, each byte six on the wire (\u0000): about 192 MiB of JSONL.
+func worstCaseRecords() []applog.Record {
+ ts := time.Date(2026, 8, 10, 12, 0, 0, 0, time.UTC)
+ msg := strings.Repeat("\x00", 8<<10)
+ recs := make([]applog.Record, logshipMaxPending)
+ for i := range recs {
+ recs[i] = applog.Record{TS: ts, Box: "box1", Seq: uint64(1 + i), Stream: applog.StreamApp, Host: "h", Msg: msg}
+ }
+ return recs
+}
+
+// H5-M7 review 1: whatever the writer legitimately holds, every chunk it
+// writes is one the console's bounded decoder reads in full. A full pending
+// buffer of worst-case escaping goes out as several chunks, and the reader
+// gets every record back with nothing trimmed.
+func TestLogshipWorstCaseEscapingReadsBackWhole(t *testing.T) {
+ s := release.NewDirStore(t.TempDir())
+ app := applog.AppKey{Acct: "bde", App: "ledgerpay"}
+ recs := worstCaseRecords()
+ pending := map[applog.AppKey][]applog.Record{app: recs}
+ logshipFlush(context.Background(), s, pending, nil)
+ if len(pending) != 0 {
+ t.Fatalf("%d records still pending after a flush to a working bucket", len(pending[app]))
+ }
+ keys, err := s.List(context.Background(), mustKey(t)(applog.Prefix(app.Acct, app.App)))
+ if err != nil || len(keys) < 2 {
+ t.Fatalf("chunks %v (%v); want the batch cut into several", keys, err)
+ }
+ perBox, trimmed, err := applog.ReadChunks[applog.Record](context.Background(), s, mustKey(t)(applog.Prefix(app.Acct, app.App)),
+ time.Time{}, time.Time{}, func(applog.Record) bool { return true }, 2*logshipMaxPending)
+ if err != nil || trimmed {
+ t.Fatalf("read back: %v trimmed=%v; want every chunk readable", err, trimmed)
+ }
+ if len(perBox) != 1 || len(perBox[0]) != len(recs) {
+ t.Fatalf("read back %d boxes, %d records; want 1 box, %d", len(perBox), len(perBox[0]), len(recs))
+ }
+ for i, r := range perBox[0] {
+ if r.Seq != recs[i].Seq || r.Msg != recs[i].Msg {
+ t.Fatalf("record %d came back as seq %d with a %d-byte message", i, r.Seq, len(r.Msg))
+ }
+ }
+}
+
+// putOnce lets the first n Puts through and refuses the rest.
+type putOnce struct {
+ release.Store
+ n int
+}
+
+func (p *putOnce) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) {
+ if p.n == 0 {
+ return "", context.DeadlineExceeded
+ }
+ p.n--
+ return p.Store.Put(ctx, key, body, ifMatch)
+}
+
+// A flush that fails part-way keeps exactly the records from the first
+// unwritten chunk on; the next flush writes them under their own first seq.
+func TestLogshipFlushHoldsFromTheFirstUnwrittenChunk(t *testing.T) {
+ dir := release.NewDirStore(t.TempDir())
+ app := applog.AppKey{Acct: "bde", App: "ledgerpay"}
+ recs := worstCaseRecords()
+ runs, _, err := applog.EncodeChunks(recs)
+ if err != nil || len(runs) < 2 {
+ t.Fatalf("EncodeChunks: %d runs, %v", len(runs), err)
+ }
+ pending := map[applog.AppKey][]applog.Record{app: recs}
+ logshipFlush(context.Background(), &putOnce{Store: dir, n: 1}, pending, nil)
+ held := pending[app]
+ if len(held) != len(recs)-len(runs[0]) || held[0].Seq != runs[1][0].Seq {
+ t.Fatalf("held %d records from seq %d; want %d from seq %d", len(held), held[0].Seq, len(recs)-len(runs[0]), runs[1][0].Seq)
+ }
+ logshipFlush(context.Background(), dir, pending, nil)
+ if len(pending) != 0 {
+ t.Fatal("records still pending after the retry")
+ }
+ perBox, trimmed, err := applog.ReadChunks[applog.Record](context.Background(), dir, mustKey(t)(applog.Prefix(app.Acct, app.App)),
+ time.Time{}, time.Time{}, func(applog.Record) bool { return true }, 2*logshipMaxPending)
+ if err != nil || trimmed || len(perBox) != 1 || len(perBox[0]) != len(recs) {
+ t.Fatalf("read back after retry: %v trimmed=%v", err, trimmed)
+ }
+}
diff --git a/internal/provision/testdata/plan14-root-reads-sec-console-dos.tsv b/internal/provision/testdata/plan14-root-reads-sec-console-dos.tsv
index 22ff36464..0417731ec 100644
--- a/internal/provision/testdata/plan14-root-reads-sec-console-dos.tsv
+++ b/internal/provision/testdata/plan14-root-reads-sec-console-dos.tsv
@@ -1,3 +1,5 @@
# Census overlay sec-console-dos, written by census-propose (#369). census-ruling-sec-console-dos, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-sec-console-dos.md.
-# 0 body, 0 sites, 1 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
-@coverage internal/applog 174a18f85513dff5db6c0b7c3e5e41a72af3ba607abfb97550fe86cef476b2aa
+# 0 body, 0 sites, 3 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+@coverage internal/apperr eeed6e99fe5b8d2be14e07d3d4a96d4a3dd9995f9b99c80c09349f1b123d3ffa
+@coverage internal/applog bf04191fc816519559492f0d598d9d64ec5edd96660c95342e980429bcc43300
+@coverage internal/host d0ba8b6b2fa6b5d995f5bb9ee8669f97ceb13ed627f7cd1516fea7bc6f1e88b5