diff --git a/.golangci.yml b/.golangci.yml index 4150af83..382031bd 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -156,6 +156,10 @@ linters-settings: require-explanation: true issues: max-same-issues: 0 + # Trimmed copy of the klauspost/compress zstd encoder. Kept as upstream wrote + # it so it stays diffable against the release it came from. + exclude-dirs: + - llo/internal/zstdenc exclude-rules: - path: test text: "^G404:" diff --git a/go.mod b/go.mod index ad571b94..6478fa3e 100644 --- a/go.mod +++ b/go.mod @@ -3,6 +3,7 @@ module github.com/smartcontractkit/chainlink-data-streams go 1.27.1 require ( + github.com/cespare/xxhash/v2 v2.3.0 github.com/esote/minmaxheap v1.0.0 github.com/ethereum/go-ethereum v1.17.4 github.com/expr-lang/expr v1.17.8 @@ -11,12 +12,13 @@ require ( github.com/hashicorp/go-plugin v1.8.0 github.com/jmoiron/sqlx v1.4.0 github.com/jpillora/backoff v1.0.0 - github.com/klauspost/compress v1.18.6 + github.com/klauspost/compress v1.20.3 github.com/leanovate/gopter v0.2.11 github.com/lib/pq v1.12.3 github.com/pelletier/go-toml/v2 v2.3.1 github.com/pkg/errors v0.9.1 github.com/prometheus/client_golang v1.23.2 + github.com/prometheus/client_model v0.6.2 github.com/shopspring/decimal v1.4.0 github.com/smartcontractkit/chainlink-common v0.11.2-0.20260918171610-2b348aaadc86 github.com/smartcontractkit/chainlink-common/keystore v1.1.0 @@ -45,7 +47,6 @@ require ( github.com/buger/jsonparser v1.2.0 // indirect github.com/cenkalti/backoff v2.2.1+incompatible // indirect github.com/cenkalti/backoff/v5 v5.0.3 // indirect - github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/cloudevents/sdk-go/binding/format/protobuf/v2 v2.16.2 // indirect github.com/cloudevents/sdk-go/v2 v2.16.2 // indirect github.com/cockroachdb/errors v1.11.3 // indirect @@ -132,7 +133,6 @@ require ( github.com/pion/logging v0.2.4 // indirect github.com/pion/stun/v3 v3.1.5 // indirect github.com/pion/transport/v4 v4.0.2 // indirect - github.com/prometheus/client_model v0.6.2 // indirect github.com/prometheus/common v0.67.5 // indirect github.com/prometheus/procfs v0.20.1 // indirect github.com/rogpeppe/go-internal v1.14.1 // indirect diff --git a/go.sum b/go.sum index 23c02df1..14e989ec 100644 --- a/go.sum +++ b/go.sum @@ -388,8 +388,8 @@ github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/X github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= -github.com/klauspost/compress v1.18.6 h1:2jupLlAwFm95+YDR+NwD2MEfFO9d4z4Prjl1XXDjuao= -github.com/klauspost/compress v1.18.6/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ= +github.com/klauspost/compress v1.20.3 h1:zWNoFqq/lSuYQRim3dUXlXeA0IqwuZGicdG5ZTfY5j4= +github.com/klauspost/compress v1.20.3/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y= github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg= diff --git a/llo/dev/v31/blobcompress.go b/llo/dev/v31/blobcompress.go deleted file mode 100644 index d626cd53..00000000 --- a/llo/dev/v31/blobcompress.go +++ /dev/null @@ -1,163 +0,0 @@ -package llo - -import ( - "fmt" - "sync" - - "github.com/klauspost/compress/zstd" - - "github.com/smartcontractkit/libocr/offchainreporting2plus/ocr3_1types" - - protocol "github.com/smartcontractkit/chainlink-data-streams/llo/protocol" -) - -// Blob payload codec identifiers. The first byte of a blob payload names the -// codec used for the remaining bytes, so a reader never has to guess and the -// writer stays free to fall back to raw when compression does not pay off. -const ( - blobCodecRaw byte = 0 - blobCodecZstd byte = 1 -) - -// maxDecompressedBlobPayloadBytes bounds the size of a blob payload after -// decompression. A blob is a stream-values-only observation proto, so the same -// bound the v30 observation codec uses applies here: it is generously above any -// honest payload while keeping a malicious peer from turning a small blob into -// a huge allocation (zstd bomb). -const maxDecompressedBlobPayloadBytes = protocol.MaxDecompressedObservationLength - -// MaxBlobPayloadBytes is the size of a broadcast blob payload libocr accepts, -// and is the value the factory declares as MaxBlobPayloadBytes. It bounds the -// payload as framed for broadcast (codec byte plus body), which is a different -// quantity from maxDecompressedBlobPayloadBytes: the latter is the anti-bomb -// bound applied to the decompressed bytes on the read side, and is deliberately -// looser. Enforcing this one on the write side is what stops the pump from -// broadcasting a blob every peer's libocr would reject. -const MaxBlobPayloadBytes = ocr3_1types.MaxMaxBlobPayloadBytes - -// zstd Encoder/Decoder are safe for concurrent use via EncodeAll/DecodeAll and -// are expensive to build, so a single pair is shared process-wide. Built lazily -// so a construction failure surfaces at the call site rather than in init. -var ( - blobZstd blobCompressor - blobZstdOnce sync.Once - blobZstdErr error -) - -type blobCompressor struct { - encoder *zstd.Encoder - decoder *zstd.Decoder -} - -func getBlobCompressor() (blobCompressor, error) { - blobZstdOnce.Do(func() { - encoder, err := zstd.NewWriter(nil) - if err != nil { - blobZstdErr = fmt.Errorf("new zstd encoder: %w", err) - return - } - // WithDecoderMaxMemory bounds the decompressed size to a safe limit. - // WithDecodeAllCapLimit bounds each DecodeAll call to the capacity of - // its destination, which decodeBlobPayload sizes to the call's budget. - decoder, err := zstd.NewReader(nil, - zstd.WithDecoderConcurrency(0), - zstd.WithDecoderMaxMemory(maxDecompressedBlobPayloadBytes), - zstd.WithDecodeAllCapLimit(true), - ) - if err != nil { - blobZstdErr = fmt.Errorf("new zstd decoder: %w", err) - return - } - blobZstd = blobCompressor{encoder: encoder, decoder: decoder} - }) - return blobZstd, blobZstdErr -} - -// encodeBlobPayload frames raw proto bytes for broadcast, compressing them when -// that actually shrinks the payload. The codec choice is made here and recorded -// in the leading byte; readers never re-derive it, so nodes are free to disagree -// on whether compression paid off without affecting the decoded result. -func encodeBlobPayload(raw []byte) ([]byte, error) { - if len(raw) > maxDecompressedBlobPayloadBytes { - // Refuse to emit a blob every peer would reject on decompression; - // fail loudly here instead. - return nil, fmt.Errorf("blob payload too large: %d > %d bytes", len(raw), maxDecompressedBlobPayloadBytes) - } - c, err := getBlobCompressor() - if err != nil { - return nil, err - } - compressed := c.encoder.EncodeAll(raw, []byte{blobCodecZstd}) - out := compressed - if len(compressed) >= len(raw)+1 { - out = make([]byte, 0, len(raw)+1) - out = append(out, blobCodecRaw) - out = append(out, raw...) - } - // The framed payload is what is broadcast, has to fit the declared limit. - // A payload that compresses poorly can pass the check above and still land over it. - if len(out) > MaxBlobPayloadBytes { - return nil, fmt.Errorf("framed blob payload too large: %d > %d bytes", len(out), MaxBlobPayloadBytes) - } - return out, nil -} - -// decodeBlobPayload reverses encodeBlobPayload. The payload is untrusted, so -// the decompressed size is bounded by maxOut: cheaply up front via the zstd -// frame header when it declares a content size, and during decompression via -// the capacity of the destination buffer in case it does not. maxOut is a -// caller-supplied budget (see decodeObservation) and is clamped to -// maxDecompressedBlobPayloadBytes. -func decodeBlobPayload(payload []byte, maxOut int) ([]byte, error) { - if len(payload) == 0 { - return nil, fmt.Errorf("empty blob payload") - } - if maxOut <= 0 { - return nil, fmt.Errorf("blob payload budget exhausted") - } - if maxOut > maxDecompressedBlobPayloadBytes { - maxOut = maxDecompressedBlobPayloadBytes - } - codec, body := payload[0], payload[1:] - switch codec { - case blobCodecRaw: - if len(body) > maxOut { - return nil, fmt.Errorf("blob payload too large: %d > %d bytes", len(body), maxOut) - } - return body, nil - case blobCodecZstd: - c, err := getBlobCompressor() - if err != nil { - return nil, err - } - // Reject an oversized frame before spending decompression work on it. - // A hostile peer can omit or understate the declared size, so this is - // an optimization, not the enforcement point. - var hdr zstd.Header - if err := hdr.Decode(body); err != nil { - return nil, fmt.Errorf("decode blob payload header: %w", err) - } - if hdr.HasFCS && hdr.FrameContentSize > uint64(maxOut) { - return nil, fmt.Errorf("declared decompressed blob payload too large: %d > %d bytes", hdr.FrameContentSize, maxOut) - } - // The decoder stops once the output outgrows the destination capacity, - // so the per-call budget holds while decompressing, not only after. - // encodeBlobPayload always declares the content size, so an honest - // payload allocates exactly its size here. - capacity := maxOut - if hdr.HasFCS { - capacity = int(hdr.FrameContentSize) //nolint:gosec // bounded by maxOut above - } - out, err := c.decoder.DecodeAll(body, make([]byte, 0, capacity)) - if err != nil { - return nil, fmt.Errorf("decompress blob payload: %w", err) - } - // The cap limit is checked per block, so a block can overshoot it. - if len(out) > maxOut { - return nil, fmt.Errorf("decompressed blob payload too large: %d > %d bytes", len(out), maxOut) - } - return out, nil - default: - return nil, fmt.Errorf("unknown blob payload codec %d", codec) - } -} diff --git a/llo/dev/v31/blobmemo.go b/llo/dev/v31/blobmemo.go index 92b54624..a8a1031a 100644 --- a/llo/dev/v31/blobmemo.go +++ b/llo/dev/v31/blobmemo.go @@ -46,7 +46,7 @@ const maxMemoizedPayloads = ocrtypes.MaxOracles * maxObservationBlobHandles // while StateTransition still runs, each round call discards the other's // entries and the superseded handle misses on every get and drops every put. // That degrades to running without the memo and bound in the observation -// decompression budget in decodeObservation, not the memo. +// decompression budget in fetchBlobsAndDecodeObservation, not the memo. type blobPayloadCache struct { mu sync.Mutex seqNr uint64 @@ -64,6 +64,8 @@ type blobPayloadCache struct { type blobPayloadEntry struct { values protocol.StreamValues size int + // cycleStartSeqNr is the blob's own, see LLOBlobPayloadProto. + cycleStartSeqNr uint64 } func newBlobPayloadCache() *blobPayloadCache { diff --git a/llo/dev/v31/blobmemo_test.go b/llo/dev/v31/blobmemo_test.go index b6e000e9..60a8e15e 100644 --- a/llo/dev/v31/blobmemo_test.go +++ b/llo/dev/v31/blobmemo_test.go @@ -20,13 +20,13 @@ import ( // referencing the resulting handle. func blobObservation(t *testing.T, bc *llotest.BlobBroadcastFetcher, sv protocol.StreamValues) ocrtypes.Observation { t.Helper() - payload, err := marshalStreamValues(sv) + payload, err := marshalStreamValues(sv, 1) require.NoError(t, err) handle, err := bc.BroadcastBlob(tests.Context(t), payload, ocr3_1types.BlobExpirationHintSequenceNumber{SeqNr: 100}) require.NoError(t, err) handleBytes, err := handle.MarshalBinary() require.NoError(t, err) - enc, err := encodeObservation(Observation{UnixTimestampNanoseconds: 1}, [][]byte{handleBytes}) + enc, err := encodeObservation(Observation{ObservationTimestampNanoseconds: 1}, [][]byte{handleBytes}) require.NoError(t, err) return enc } @@ -49,11 +49,11 @@ func Test_BlobPayloadCache_SkipsSecondFetch(t *testing.T) { cache := newBlobPayloadCache() - first, err := decodeObservation(ctx, enc, bc, cache.round(7)) + first, err := fetchBlobsAndDecodeObservation(ctx, enc, bc, cache.round(7)) require.NoError(t, err) require.Equal(t, 1, bc.Fetches()) - second, err := decodeObservation(ctx, enc, bc, cache.round(7)) + second, err := fetchBlobsAndDecodeObservation(ctx, enc, bc, cache.round(7)) require.NoError(t, err) require.Equal(t, 1, bc.Fetches(), "the second decode of the round must be served from the memo") @@ -65,7 +65,7 @@ func Test_BlobPayloadCache_SkipsSecondFetch(t *testing.T) { } // Without a memo the fetch happens again, which is what the memo replaces. - _, err = decodeObservation(ctx, enc, bc, nil) + _, err = fetchBlobsAndDecodeObservation(ctx, enc, bc, nil) require.NoError(t, err) require.Equal(t, 2, bc.Fetches()) } @@ -79,11 +79,11 @@ func Test_BlobPayloadCache_ScopedToSeqNr(t *testing.T) { enc := blobObservation(t, bc, testStreamValues(10)) cache := newBlobPayloadCache() - _, err := decodeObservation(ctx, enc, bc, cache.round(7)) + _, err := fetchBlobsAndDecodeObservation(ctx, enc, bc, cache.round(7)) require.NoError(t, err) require.Equal(t, 1, bc.Fetches()) - _, err = decodeObservation(ctx, enc, bc, cache.round(8)) + _, err = fetchBlobsAndDecodeObservation(ctx, enc, bc, cache.round(8)) require.NoError(t, err) require.Equal(t, 2, bc.Fetches(), "a later round must not be served the previous round's payload") @@ -108,11 +108,11 @@ func Test_BlobPayloadCache_FailuresNotMemoized(t *testing.T) { // No fetcher: a reference that could not be resolved must not be cached as // an absence, so a later decode in the same round still fetches. - _, err := decodeObservation(ctx, enc, nil, cache.round(7)) + _, err := fetchBlobsAndDecodeObservation(ctx, enc, nil, cache.round(7)) var bfErr *blobFetchError require.ErrorAs(t, err, &bfErr) - _, err = decodeObservation(ctx, enc, bc, cache.round(7)) + _, err = fetchBlobsAndDecodeObservation(ctx, enc, bc, cache.round(7)) require.NoError(t, err) require.Equal(t, 1, bc.Fetches()) } @@ -124,7 +124,7 @@ func Test_BlobPayloadCache_BudgetChargedOnHit(t *testing.T) { ctx := tests.Context(t) bc := newFakeBroadcaster() sv := testStreamValues(20) - payload, err := marshalStreamValues(sv) + payload, err := marshalStreamValues(sv, 1) require.NoError(t, err) handle, err := bc.BroadcastBlob(ctx, payload, ocr3_1types.BlobExpirationHintSequenceNumber{SeqNr: 100}) require.NoError(t, err) @@ -132,12 +132,12 @@ func Test_BlobPayloadCache_BudgetChargedOnHit(t *testing.T) { require.NoError(t, err) // The same handle four times, so the budget is charged four times. - enc, err := encodeObservation(Observation{UnixTimestampNanoseconds: 1}, [][]byte{handleBytes, handleBytes, handleBytes, handleBytes}) + enc, err := encodeObservation(Observation{ObservationTimestampNanoseconds: 1}, [][]byte{handleBytes, handleBytes, handleBytes, handleBytes}) require.NoError(t, err) - withMemo, memoErr := decodeObservation(ctx, enc, bc, newBlobPayloadCache().round(7)) + withMemo, memoErr := fetchBlobsAndDecodeObservation(ctx, enc, bc, newBlobPayloadCache().round(7)) require.Equal(t, 1, bc.Fetches(), "repeats within one observation are memo hits") - withoutMemo, plainErr := decodeObservation(ctx, enc, bc, nil) + withoutMemo, plainErr := fetchBlobsAndDecodeObservation(ctx, enc, bc, nil) // Whatever the budget verdict is, it must be the same with and without the // memo; the payloads here are small, so both are expected to succeed. diff --git a/llo/dev/v31/blobpump.go b/llo/dev/v31/blobpump.go index bd77944b..97949d90 100644 --- a/llo/dev/v31/blobpump.go +++ b/llo/dev/v31/blobpump.go @@ -4,10 +4,14 @@ import ( "context" "fmt" "runtime/debug" + "strconv" "sync" "sync/atomic" "time" + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/promauto" + "github.com/smartcontractkit/chainlink-common/pkg/logger" llotypes "github.com/smartcontractkit/chainlink-common/pkg/types/llo" @@ -20,53 +24,30 @@ import ( // Defaults for the blob pump. See PluginFactoryParams for the overrides. const ( - // DefaultMaxSnapshotRounds bounds freshness and is enforced LOCALLY, by this - // node's Take: it decides how stale the parked stream values may be when this - // oracle references them in an observation. It has no effect on the blob - // transport. Shortening it makes this node discard its own snapshot sooner, - // it does not make the blob unfetchable for anyone. A snapshot gathered for - // seqNr N is usable through N+MaxSnapshotRounds-1; the default of 2 means - // consume at N+1, tolerating one skipped round. Tune against the report - // format's staleness budget. - DefaultMaxSnapshotRounds = 2 - // DefaultBlobLifetimeRounds bounds fetchability and is enforced REMOTELY, by - // libocr's blob transport: it is the expiration hint passed to BroadcastBlob, - // after which peers can no longer fetch the blob and the handle in an - // observation resolves to nothing. It does not bound staleness: a node's own - // freshness gate is DefaultMaxSnapshotRounds. Tune against network fetch - // latency and reaping lag, not against data freshness. - DefaultBlobLifetimeRounds = 4 - // BlobFetchMarginRounds couples the two: the number of rounds that must remain - // between the last seqNr at which this node may reference a snapshot (local, - // MaxSnapshotRounds) and the seqNr at which its blob expires for peers - // (remote, BlobLifetimeRounds). Guarantees a handle that is still locally - // usable is still remotely fetchable, with slack for slow or lagging peers. + // BlobFetchMarginRounds is how many rounds a blob must stay fetchable past + // the round that references it, so slow or lagging peers can still fetch + // it. Take offers a snapshot only while its blob expires at least this many + // rounds after the current one. BlobFetchMarginRounds = 3 + // DefaultBlobLifetimeRounds is the expiration hint passed to BroadcastBlob, + // in rounds after the cycle that produced the blob started. After it peers + // can no longer fetch the blob and the handle in an observation resolves to + // nothing. A snapshot can be offered for BlobLifetimeRounds minus + // BlobFetchMarginRounds rounds, so the default leaves room for + // SnapshotReuseRounds. It does not bound staleness: the state transition + // does, from replicated data (see freshness.go). + DefaultBlobLifetimeRounds = BlobFetchMarginRounds + SnapshotReuseRounds + // MinBlobLifetimeRounds is the smallest lifetime that lets a snapshot be + // offered for one round. + MinBlobLifetimeRounds = BlobFetchMarginRounds + 1 // DefaultBlobObservationDurationMultiplier scales MaxDurationObservation // into the pump's per-cycle budget. The pump runs off the OCR critical // path, so it can afford to wait longer than a synchronous observation. DefaultBlobObservationDurationMultiplier = 2 - // SnapshotAgeSlack scales the measured round period into the wall-clock age - // at which a parked snapshot is discarded. The bound is derived from the - // observed round period rather than from MaxDurationObservation, which is - // unrelated to the round cadence: a bound shorter than one round period - // would reject every snapshot and silently stop the node contributing - // stream values. Slack makes this a jitter guard, not a second freshness - // gate, since staleness in rounds is already bounded by MaxSnapshotRounds. - SnapshotAgeSlack = 2 - // DefaultMaxRoundPeriod is the ceiling on the measured round period. The - // measurement is wall clock, so a stall or a pause folds a gap far wider - // than the protocol ever schedules and inflates the derived age bound for - // several rounds after. Not using DeltaRound which can be a valid zero - DefaultMaxRoundPeriod = 2 * time.Second // MaxBlobLifetimeRounds bounds BlobLifetimeRounds. The pump broadcasts // roughly one blob per round, so the unexpired-blob budget declared to // libocr grows with the lifetime; this keeps that budget sane. MaxBlobLifetimeRounds = 64 - // MinMaxSnapshotRounds bounds MaxSnapshotRounds from below. A cycle gathers - // the snapshot for the round that kicked it, and the snapshot is first taken - // by the next round, so a window of one round discards every snapshot. - MinMaxSnapshotRounds = 2 // BlobBroadcastAttempts is how many times one cycle tries to broadcast the // payload it gathered. BlobBroadcastAttempts = 3 @@ -102,32 +83,21 @@ func perOracleUnexpiredBlobCount(blobLifetimeRounds uint64) int { return max(n, MinPerOracleUnexpiredBlobCount) } -// ResolveBlobRounds applies the defaults to the snapshot and blob lifetime -// knobs and checks the resulting pair leaves BlobFetchMarginRounds of fetch -// margin. Shared with plugin config validation so a job spec is rejected at -// create time rather than at plugin startup. -func ResolveBlobRounds(maxSnapshotRounds, blobLifetimeRounds uint64) (uint64, uint64, error) { - if maxSnapshotRounds == 0 { - maxSnapshotRounds = DefaultMaxSnapshotRounds - } +// ResolveBlobLifetimeRounds applies the default to the blob lifetime knob and +// bounds it to [MinBlobLifetimeRounds, MaxBlobLifetimeRounds]. Shared with +// plugin config validation so a job spec is rejected at create time rather +// than at plugin startup. +func ResolveBlobLifetimeRounds(blobLifetimeRounds uint64) (uint64, error) { if blobLifetimeRounds == 0 { blobLifetimeRounds = DefaultBlobLifetimeRounds } - if maxSnapshotRounds < MinMaxSnapshotRounds { - return 0, 0, fmt.Errorf("MaxSnapshotRounds (%d) is below MinMaxSnapshotRounds (%d)", maxSnapshotRounds, MinMaxSnapshotRounds) + if blobLifetimeRounds < MinBlobLifetimeRounds { + return 0, fmt.Errorf("BlobLifetimeRounds (%d) is below MinBlobLifetimeRounds (%d): a snapshot could never be offered with %d rounds of fetch margin", blobLifetimeRounds, MinBlobLifetimeRounds, BlobFetchMarginRounds) } if blobLifetimeRounds > MaxBlobLifetimeRounds { - return 0, 0, fmt.Errorf("BlobLifetimeRounds (%d) exceeds MaxBlobLifetimeRounds (%d)", blobLifetimeRounds, MaxBlobLifetimeRounds) + return 0, fmt.Errorf("BlobLifetimeRounds (%d) exceeds MaxBlobLifetimeRounds (%d)", blobLifetimeRounds, MaxBlobLifetimeRounds) } - // A snapshot is last referenced at forSeqNr+maxSnapshotRounds-1 and its blob - // expires at forSeqNr+blobLifetimeRounds, so this is the fetch margin. - // Subtract from the already bounded lifetime rather than adding to - // maxSnapshotRounds, whose sum would wrap and pass the check, leaving the - // pump to overflow usableBefore and call every snapshot stale. - if blobLifetimeRounds+1 < BlobFetchMarginRounds || maxSnapshotRounds > blobLifetimeRounds+1-BlobFetchMarginRounds { - return 0, 0, fmt.Errorf("BlobLifetimeRounds (%d) leaves less than %d rounds of fetch margin past MaxSnapshotRounds (%d)", blobLifetimeRounds, BlobFetchMarginRounds, maxSnapshotRounds) - } - return maxSnapshotRounds, blobLifetimeRounds, nil + return blobLifetimeRounds, nil } // pumpInput is the round context the pump needs, published by Observation. @@ -148,19 +118,20 @@ func (in pumpInput) observable() bool { // broadcast as a blob, and reduced to the marshaled handle that goes on the // wire. type blobSnapshot struct { - handleBytes []byte - observedAt time.Time - // forSeqNr is the sequence number known when the cycle started. - forSeqNr uint64 - // usableBefore is the local freshness gate: this node must not reference the - // snapshot at or beyond this sequence number. Purely local, not on the wire. - usableBefore uint64 - // expiresAt is the expiration hint given to the blob transport: peers cannot - // fetch the blob at or beyond this sequence number. Always greater than - // usableBefore by at least BlobFetchMarginRounds. - expiresAt uint64 - // streamCount is the number of streams the cycle observed (for logging). - streamCount int + blobHandleBytes []byte + // cycleStartSeqNr is the sequence number known when the cycle started. It + // travels in the blob payload, where the state transition reads it to + // judge the values' age. + cycleStartSeqNr uint64 + // blobExpirationHintSeqNr is the expiration hint given to the blob + // transport: peers cannot fetch the blob at or beyond this sequence number. + // Not derivable from cycleStartSeqNr, since a broadcast retry recomputes + // the hint from the round current at that attempt. + blobExpirationHintSeqNr uint64 + // requestedStreams and observedStreams are how many streams the cycle was + // asked for and how many the blob carries a value for (for logging). + requestedStreams int + observedStreams int } // blobPump gathers stream observations off the OCR critical path and broadcasts @@ -170,9 +141,20 @@ type blobSnapshot struct { // (or discards) a snapshot, so the pump rate tracks the round rate without // needing to know deltaRound, and no blob is broadcast that no round asked for. // Cycles are serial, so there is never more than one DataSource.Observe in -// flight. There is deliberately no idle watchdog: a snapshot's usability is +// flight. There is deliberately no idle watchdog: a snapshot's fetchability is // bounded by sequence number, so refreshing while no rounds are running would -// produce snapshots that are already too old to use. +// only pile up blobs. +// +// The latest parked snapshot is kept until a newer one parks, and may be +// referenced by several rounds: a cycle that runs longer than a round costs +// nothing as long as the previous values are still fetchable, instead of a +// round with no stream values. A newly parked snapshot always replaces the +// previous one, taken or not. +// +// The pump does not judge whether a snapshot's values are still fresh. That +// decision is the state transition's, taken from replicated data so every +// oracle keeps the same values (see freshness.go). Take checks one thing only: +// that peers will still be able to fetch the blob. type blobPump struct { blobPumpParams lggr logger.Logger @@ -184,21 +166,18 @@ type blobPump struct { closeTimeout time.Duration inFlight atomic.Bool - misses atomic.Uint64 - cycles atomic.Uint64 missStreak atomic.Uint64 - - // ready holds the latest parked snapshot. - ready chan *blobSnapshot + metrics blobPumpMetrics mu sync.Mutex input pumpInput - // lastTakeAt, lastTakeSeqNr and roundPeriod estimate the round cadence from - // the interval between Take calls for consecutive sequence numbers. The - // estimate is bounded by maxRoundPeriod. - lastTakeAt time.Time - lastTakeSeqNr uint64 - roundPeriod time.Duration + // latest is the newest parked snapshot, nil until the first cycle parks. + // referenced records whether a round has already taken it. + latest *blobSnapshot + referenced bool + // cycleEnded is closed when the in-flight cycle ends, parked or not, and + // replaced for the next one. Take waits on it. + cycleEnded chan struct{} } // blobPumpParams is the pump's configuration, resolved by the factory. @@ -206,17 +185,10 @@ type blobPumpParams struct { bbf ocr3_1types.BlobBroadcastFetcher ds DataSource configDigest ocrtypes.ConfigDigest + donID uint32 verboseLogging bool observationTimeout time.Duration - // maxSnapshotAge is the wall-clock jitter guard. Positive pins it to an - // explicit duration, zero derives it from the measured round period, and - // negative disables it, leaving maxSnapshotRounds as the only bound. - maxSnapshotAge time.Duration - // maxSnapshotRounds is the local freshness gate. See DefaultMaxSnapshotRounds. - maxSnapshotRounds uint64 - // maxRoundPeriod caps the measured round period. See DefaultMaxRoundPeriod. - maxRoundPeriod time.Duration - // blobLifetimeRounds is the remote fetchability bound. See DefaultBlobLifetimeRounds. + // blobLifetimeRounds is the fetchability bound. See DefaultBlobLifetimeRounds. blobLifetimeRounds uint64 // inFlightWait bounds how long Take waits for an in-flight cycle to park. inFlightWait time.Duration @@ -228,9 +200,10 @@ func newBlobPump(lggr logger.Logger, params blobPumpParams) *blobPump { blobPumpParams: params, lggr: logger.Sugared(lggr).Named("BlobPump"), trigger: make(chan struct{}, 1), - ready: make(chan *blobSnapshot, 1), + cycleEnded: make(chan struct{}), ctx: ctx, cancel: cancel, + metrics: newBlobPumpMetrics(params.donID), closeTimeout: max(params.observationTimeout*closeTimeoutSlackMultiplier, minCloseTimeout), } } @@ -284,30 +257,26 @@ func (p *blobPump) SetInput(in pumpInput) { p.mu.Unlock() } -// Take returns the parked snapshot if it is still usable at seqNr, and always -// kicks the next cycle: kicking on a discard as well as on a hit is what stops -// a single unusable snapshot from stalling the pump forever. The second return -// value is the reason a snapshot was not returned, for logging. +// Take returns the latest parked snapshot if peers can still fetch its blob at +// seqNr, and always kicks the next cycle: kicking on a discard as well as on a +// hit is what stops a single unusable snapshot from stalling the pump forever. +// The second return value is the reason a snapshot was not returned, for +// logging. // -// A round that finds nothing parked while a cycle is running waits up to -// inFlightWait for the cycle to park, or until ctx is done. +// A snapshot stays offered until a newer one parks, so a round may take what +// an earlier round already took. A round that finds nothing new while a cycle +// is running waits up to inFlightWait for the cycle to end, or until ctx is +// done, and then falls back to what is parked. func (p *blobPump) Take(ctx context.Context, seqNr uint64) (*blobSnapshot, string) { if !p.enabled() { return nil, "blob pump disabled" } - p.mu.Lock() - p.recordRoundLocked(time.Now(), seqNr) - ageLimit := p.snapshotAgeLimitLocked() - in := p.input - p.mu.Unlock() - defer p.kick() - snap, waited := p.takeReady(ctx, p.inFlightWait) + snap, reused, waited := p.take(ctx, seqNr, p.inFlightWait) - now := time.Now() switch { - case snap == nil && !in.observable(): + case snap == nil && !p.observable(): return nil, "nothing to observe this round" case snap == nil: p.miss() @@ -315,105 +284,179 @@ func (p *blobPump) Take(ctx context.Context, seqNr uint64) (*blobSnapshot, strin return nil, "cycle in flight" } return nil, "no snapshot parked" - case seqNr >= snap.usableBefore: + case !snap.isFetchableAtSeqNr(seqNr): p.miss() - return nil, fmt.Sprintf("snapshot too stale (forSeqNr=%d usableBefore=%d expiresAt=%d)", snap.forSeqNr, snap.usableBefore, snap.expiresAt) - case ageLimit > 0 && now.Sub(snap.observedAt) > ageLimit: + return nil, fmt.Sprintf("snapshot blob expires too soon for peers to fetch (cycleStartSeqNr=%d blobExpirationHintSeqNr=%d seqNr=%d margin=%d)", snap.cycleStartSeqNr, snap.blobExpirationHintSeqNr, seqNr, BlobFetchMarginRounds) + case !snap.isWithinRoundAgeAtSeqNr(seqNr): p.miss() - return nil, fmt.Sprintf("snapshot too old (age=%s max=%s)", now.Sub(snap.observedAt), ageLimit) + return nil, fmt.Sprintf("snapshot is past the stream value age bound (cycleStartSeqNr=%d seqNr=%d maxAgeRounds=%d)", snap.cycleStartSeqNr, seqNr, MaxStreamValueAgeRounds) default: p.missStreak.Store(0) + if reused { + p.metrics.reuses.Inc() + } return snap, "" } } -// takeReady detaches the parked snapshot, waiting up to timeout for an -// in-flight cycle to park one. The wait ends early when ctx is done or the -// pump shuts down. -func (p *blobPump) takeReady(ctx context.Context, timeout time.Duration) (*blobSnapshot, bool) { - waited := false - if timeout > 0 && p.inFlight.Load() { +// observable reports whether the published input can produce a snapshot. +func (p *blobPump) observable() bool { + p.mu.Lock() + defer p.mu.Unlock() + return p.input.observable() +} + +// take returns the latest usable snapshot and marks it referenced, reporting +// whether an earlier round had already referenced it. When nothing new is +// parked and a cycle is in flight it first waits up to timeout for that cycle +// to end, early if ctx is done or the pump shuts down. A snapshot no round can +// reference any more counts as nothing new, so the wait also covers the +// handover from an expiring snapshot to the one in flight. +func (p *blobPump) take(ctx context.Context, seqNr uint64, timeout time.Duration) (snap *blobSnapshot, reused, waited bool) { + p.mu.Lock() + defer p.mu.Unlock() + + nothingNew := p.latest == nil || p.referenced || !p.latest.isUsableAtSeqNr(seqNr) + if timeout > 0 && nothingNew && p.inFlight.Load() { waited = true + ended := p.cycleEnded + p.mu.Unlock() waitCtx, cancel := context.WithTimeout(ctx, timeout) - defer cancel() select { - case snap := <-p.ready: - return snap, waited + case <-ended: case <-waitCtx.Done(): case <-p.ctx.Done(): } + cancel() + p.mu.Lock() } - select { - case snap := <-p.ready: - return snap, waited - default: - return nil, waited + if p.latest == nil { + return nil, false, waited } + reused = p.referenced + p.referenced = true + return p.latest, reused, waited +} + +// isFetchableAtSeqNr reports whether a round at seqNr may reference the +// snapshot: its blob must stay fetchable for BlobFetchMarginRounds more +// rounds. libocr expires a blob once the committed seqNr reaches the hint, so +// a round at seqNr can fetch a blob while seqNr <= hint. The margin covers +// peers that fetch late. +func (s *blobSnapshot) isFetchableAtSeqNr(seqNr uint64) bool { + return seqNr <= s.blobExpirationHintSeqNr && s.blobExpirationHintSeqNr-seqNr >= BlobFetchMarginRounds } -// park makes a snapshot available to take, replacing if we have a snap -// that no round has taken. The newest snapshot has a higher priority. +// isWithinRoundAgeAtSeqNr reports whether a round at seqNr would still pass the +// state transition's round age bound for the snapshot. +func (s *blobSnapshot) isWithinRoundAgeAtSeqNr(seqNr uint64) bool { + return seqNr >= s.cycleStartSeqNr && seqNr-s.cycleStartSeqNr <= MaxStreamValueAgeRounds +} + +// isUsableAtSeqNr reports whether a round at seqNr may reference the snapshot. +func (s *blobSnapshot) isUsableAtSeqNr(seqNr uint64) bool { + return s.isFetchableAtSeqNr(seqNr) && s.isWithinRoundAgeAtSeqNr(seqNr) +} + +// park makes a snapshot the one Take offers. The newest snapshot always wins, +// whether or not a round took the previous one. func (p *blobPump) park(snap *blobSnapshot) { - p.takeReady(context.Background(), 0) - p.ready <- snap + p.mu.Lock() + p.latest = snap + p.referenced = false + p.mu.Unlock() +} + +// beginCycle marks a cycle in flight. endCycle clears it and releases every +// Take waiting on it. Both run under mu so a Take never captures the channel of +// a cycle that has already ended. +func (p *blobPump) beginCycle() { + p.mu.Lock() + p.inFlight.Store(true) + p.mu.Unlock() +} + +func (p *blobPump) endCycle() { + p.mu.Lock() + p.inFlight.Store(false) + close(p.cycleEnded) + p.cycleEnded = make(chan struct{}) + p.mu.Unlock() } // miss records a round that found no usable snapshot when one was expected. // Sustained misses means this node is not contributing at all. Record misses // and log when above MissStreakLogThreshold. func (p *blobPump) miss() { - p.misses.Add(1) + p.metrics.misses.Inc() if streak := p.missStreak.Add(1); streak >= MissStreakLogThreshold && streak%MissStreakLogThreshold == 0 { p.lggr.Errorw("Blob pump has found no usable snapshot for consecutive rounds; this node is contributing no stream values", - "missStreak", streak, "misses", p.misses.Load(), "cycles", p.cycles.Load(), "maxSnapshotAge", p.maxSnapshotAge, "maxSnapshotRounds", p.maxSnapshotRounds) - } -} - -// recordRoundLocked builds the interval since the previous Take into the round -// period estimate, but only for subsequent rounds. -// Gaps are capped at maxRoundPeriod, so a stall cannot overestimate. -func (p *blobPump) recordRoundLocked(now time.Time, seqNr uint64) { - if !p.lastTakeAt.IsZero() && seqNr == p.lastTakeSeqNr+1 { - gap := now.Sub(p.lastTakeAt) - if p.maxRoundPeriod > 0 && gap > p.maxRoundPeriod { - gap = p.maxRoundPeriod - } - if p.roundPeriod == 0 { - p.roundPeriod = gap - } else { - p.roundPeriod = (3*p.roundPeriod + gap) / 4 - } - } - p.lastTakeAt = now - p.lastTakeSeqNr = seqNr -} - -// snapshotAgeLimitLocked resolves the wall-clock bound for this round. Zero -// means no bound at all, and is the fallback whenever the cadence is unknown: -// an unmeasured round period falls back to maxSnapshotRounds as the only -// staleness bound rather than to an invented duration. Rejecting every snapshot -// is the worse failure, because it stops the node contributing stream values -// while every round still succeeds, so it shows up as a counter and nothing -// else. -func (p *blobPump) snapshotAgeLimitLocked() time.Duration { - switch { - case p.maxSnapshotAge < 0: - return 0 - case p.maxSnapshotAge > 0: - return p.maxSnapshotAge - case p.roundPeriod > 0: - return time.Duration(p.maxSnapshotRounds) * p.roundPeriod * SnapshotAgeSlack - default: - return 0 + "missStreak", streak, "misses", p.Misses(), "cycles", p.Cycles(), "blobLifetimeRounds", p.blobLifetimeRounds) } } // Misses reports how many rounds found no usable snapshot. -func (p *blobPump) Misses() uint64 { return p.misses.Load() } +func (p *blobPump) Misses() uint64 { return p.metrics.misses.Load() } // Cycles reports how many snapshots the pump has successfully parked. -func (p *blobPump) Cycles() uint64 { return p.cycles.Load() } +func (p *blobPump) Cycles() uint64 { return p.metrics.cycles.Load() } + +// Reuses reports how many rounds took a snapshot an earlier round had already +// taken. +func (p *blobPump) Reuses() uint64 { return p.metrics.reuses.Load() } + +// Blob pump metrics. Node-local: they describe this node's contribution, not +// consensus. Misses climbing on one node is that node failing to contribute. +// Reuses climbing on every node is the data source lagging the round rate. +var ( + blobPumpCyclesMetric = promauto.NewCounterVec(prometheus.CounterOpts{ + Namespace: "llo", + Subsystem: "blob_pump", + Name: "cycles_total", + Help: "Blob pump cycles that parked a snapshot.", + }, []string{"donID"}) + blobPumpMissesMetric = promauto.NewCounterVec(prometheus.CounterOpts{ + Namespace: "llo", + Subsystem: "blob_pump", + Name: "misses_total", + Help: "Rounds that found no usable snapshot and observed no stream values.", + }, []string{"donID"}) + blobPumpReusesMetric = promauto.NewCounterVec(prometheus.CounterOpts{ + Namespace: "llo", + Subsystem: "blob_pump", + Name: "reuses_total", + Help: "Rounds that referenced a snapshot an earlier round had already referenced.", + }, []string{"donID"}) +) + +// pumpCounter is one pump counter kept readable in process: the prometheus +// child is per DON and shared across pump instances, so the pump's own count +// for logs and tests lives in the atomic. One Inc moves both. +type pumpCounter struct { + n atomic.Uint64 + prom prometheus.Counter +} + +func (c *pumpCounter) Inc() { + c.n.Add(1) + c.prom.Inc() +} + +func (c *pumpCounter) Load() uint64 { return c.n.Load() } + +type blobPumpMetrics struct { + cycles, misses, reuses pumpCounter +} + +func newBlobPumpMetrics(donID uint32) blobPumpMetrics { + don := strconv.FormatUint(uint64(donID), 10) + return blobPumpMetrics{ + cycles: pumpCounter{prom: blobPumpCyclesMetric.WithLabelValues(don)}, + misses: pumpCounter{prom: blobPumpMissesMetric.WithLabelValues(don)}, + reuses: pumpCounter{prom: blobPumpReusesMetric.WithLabelValues(don)}, + } +} func (p *blobPump) kick() { select { @@ -447,8 +490,9 @@ func (p *blobPump) safeCycle() { p.cycle() } -// cycle runs one observation and parks the result. A failed cycle parks nothing: -// the round that finds no snapshot emits an observation without stream values. +// cycle runs one observation and parks the result. A failed cycle parks +// nothing: the previous snapshot stays offered while fetchable, and a round +// that finds none emits an observation without stream values. func (p *blobPump) cycle() { p.mu.Lock() in := p.input @@ -458,24 +502,24 @@ func (p *blobPump) cycle() { return } - p.inFlight.Store(true) - defer p.inFlight.Store(false) + p.beginCycle() + defer p.endCycle() - snap, err := p.observe(in) + snap, err := p.observeStreamValuesAndBroadcastBlob(in) if err != nil { p.lggr.Warnw("Blob pump cycle failed; round will observe no stream values", "err", err, "seqNr", in.seqNr, "streams", len(in.streams)) return } - p.cycles.Add(1) + p.metrics.cycles.Inc() p.park(snap) if p.verboseLogging { - p.lggr.Debugw("Blob pump parked snapshot", "seqNr", in.seqNr, "usableBefore", snap.usableBefore, "expiresAt", snap.expiresAt, "streams", snap.streamCount, "handleBytes", len(snap.handleBytes)) + p.lggr.Debugw("Blob pump parked snapshot", "seqNr", in.seqNr, "cycleStartSeqNr", snap.cycleStartSeqNr, "blobExpirationHintSeqNr", snap.blobExpirationHintSeqNr, "requestedStreams", snap.requestedStreams, "observedStreams", snap.observedStreams, "handleBytes", len(snap.blobHandleBytes)) } } -func (p *blobPump) observe(in pumpInput) (*blobSnapshot, error) { +func (p *blobPump) observeStreamValuesAndBroadcastBlob(in pumpInput) (*blobSnapshot, error) { sv := make(protocol.StreamValues, len(in.streams)) for _, sid := range in.streams { sv[sid] = nil @@ -501,8 +545,14 @@ func (p *blobPump) observe(in pumpInput) (*blobSnapshot, error) { sv = requested } dropUnobservable(sv, p.lggr, in.seqNr) + observed := 0 + for _, v := range sv { + if v != nil { + observed++ + } + } - payload, err := marshalStreamValues(sv) + payload, err := marshalStreamValues(sv, in.seqNr) if err != nil { return nil, err } @@ -510,8 +560,7 @@ func (p *blobPump) observe(in pumpInput) (*blobSnapshot, error) { return nil, fmt.Errorf("no stream values observed for %d streams", len(in.streams)) } - usableBefore := in.seqNr + p.maxSnapshotRounds - handle, expiresAt, err := p.broadcast(ctx, payload, in.seqNr) + handle, expirationHintSeqNr, err := p.broadcast(ctx, payload, in.seqNr) if err != nil { return nil, err } @@ -521,12 +570,11 @@ func (p *blobPump) observe(in pumpInput) (*blobSnapshot, error) { } return &blobSnapshot{ - handleBytes: handleBytes, - observedAt: observedAt, - forSeqNr: in.seqNr, - usableBefore: usableBefore, - expiresAt: expiresAt, - streamCount: len(sv), + blobHandleBytes: handleBytes, + cycleStartSeqNr: in.seqNr, + blobExpirationHintSeqNr: expirationHintSeqNr, + requestedStreams: len(in.streams), + observedStreams: observed, }, nil } @@ -534,20 +582,21 @@ func (p *blobPump) observe(in pumpInput) (*blobSnapshot, error) { // broadcast within the cycle's own timeout, and returns the handle together // with the expiration hint it was broadcast under. // -// forSeqNr is the round the values were gathered for. The expiration hint is +// cycleStartSeqNr is the round the values were gathered for. The expiration hint is // recomputed per attempt from the latest round published by Observation, so a // retry that lands rounds later does not hand peers a blob that expires as of // a sequence number already behind them. The hint only moves forward, and it // bounds fetchability, not staleness: how stale the values themselves may be is -// still decided locally by usableBefore. -func (p *blobPump) broadcast(ctx context.Context, payload []byte, forSeqNr uint64) (ocr3_1types.BlobHandle, uint64, error) { +// decided by the state transition from cycleStartSeqNr, which a retry does not +// change. +func (p *blobPump) broadcast(ctx context.Context, payload []byte, cycleStartSeqNr uint64) (ocr3_1types.BlobHandle, uint64, error) { var lastErr error for attempt := 1; attempt <= BlobBroadcastAttempts; attempt++ { - expiresAt := max(forSeqNr, p.latestSeqNr()) + p.blobLifetimeRounds + expiresAt := max(cycleStartSeqNr, p.latestSeqNr()) + p.blobLifetimeRounds handle, err := p.bbf.BroadcastBlob(ctx, payload, ocr3_1types.BlobExpirationHintSequenceNumber{SeqNr: expiresAt}) if err == nil { if attempt > 1 { - p.lggr.Infow("Blob broadcast succeeded after retry", "attempt", attempt, "forSeqNr", forSeqNr, "expiresAt", expiresAt) + p.lggr.Infow("Blob broadcast succeeded after retry", "attempt", attempt, "cycleStartSeqNr", cycleStartSeqNr, "expiresAt", expiresAt) } return handle, expiresAt, nil } @@ -556,7 +605,7 @@ func (p *blobPump) broadcast(ctx context.Context, payload []byte, forSeqNr uint6 break } backoff := BlobBroadcastRetryBackoff << (attempt - 1) - p.lggr.Warnw("Blob broadcast failed; retrying within this cycle", "attempt", attempt, "attempts", BlobBroadcastAttempts, "backoff", backoff, "forSeqNr", forSeqNr, "err", err) + p.lggr.Warnw("Blob broadcast failed; retrying within this cycle", "attempt", attempt, "attempts", BlobBroadcastAttempts, "backoff", backoff, "cycleStartSeqNr", cycleStartSeqNr, "err", err) select { case <-ctx.Done(): return ocr3_1types.BlobHandle{}, 0, fmt.Errorf("BroadcastBlob error: %w (last attempt: %w)", ctx.Err(), lastErr) @@ -595,11 +644,11 @@ func dropUnobservable(sv protocol.StreamValues, lggr logger.Logger, seqNr uint64 } } -// marshalStreamValues serializes stream values into the stream-values-only -// proto that is carried by a blob, framed by encodeBlobPayload (which -// compresses it when that shrinks the payload). Returns nil when nothing was -// observed. -func marshalStreamValues(sv protocol.StreamValues) ([]byte, error) { +// marshalStreamValues serializes stream values and the seqNr the cycle that +// gathered them started in into the blob payload proto, framed by +// encodeBlobPayload (which compresses it when that shrinks the payload). +// Returns nil when nothing was observed. +func marshalStreamValues(sv protocol.StreamValues, cycleStartSeqNr uint64) ([]byte, error) { pb, err := streamValuesToProto(sv) if err != nil { return nil, err @@ -608,7 +657,7 @@ func marshalStreamValues(sv protocol.StreamValues) ([]byte, error) { return nil, nil } - raw, err := deterministicMarshal.Marshal(&protocol.LLOObservationProto{StreamValues: pb}) + raw, err := deterministicMarshal.Marshal(&protocol.LLOBlobPayloadProto{CycleStartSeqNr: cycleStartSeqNr, StreamValues: pb}) if err != nil { return nil, fmt.Errorf("marshal stream values: %w", err) } diff --git a/llo/dev/v31/blobpump_test.go b/llo/dev/v31/blobpump_test.go index 7c0ed55b..f5b5a9c5 100644 --- a/llo/dev/v31/blobpump_test.go +++ b/llo/dev/v31/blobpump_test.go @@ -3,7 +3,6 @@ package llo import ( "context" "errors" - "math" "math/big" "sync" "sync/atomic" @@ -26,7 +25,7 @@ import ( ocrtypes "github.com/smartcontractkit/libocr/offchainreporting2plus/types" ) -func testPump(t *testing.T, ds DataSource, bbf ocr3_1types.BlobBroadcastFetcher, maxAge time.Duration) *blobPump { +func testPump(t *testing.T, ds DataSource, bbf ocr3_1types.BlobBroadcastFetcher) *blobPump { t.Helper() p := newBlobPump(logger.Test(t), blobPumpParams{ bbf: bbf, @@ -34,8 +33,6 @@ func testPump(t *testing.T, ds DataSource, bbf ocr3_1types.BlobBroadcastFetcher, configDigest: ocrtypes.ConfigDigest{1}, verboseLogging: true, observationTimeout: tests.WaitTimeout(t), - maxSnapshotAge: maxAge, - maxSnapshotRounds: DefaultMaxSnapshotRounds, blobLifetimeRounds: DefaultBlobLifetimeRounds, }) p.Start() @@ -57,7 +54,7 @@ func mockDS() *mockDataSource { func Test_blobPump_TakeKicksNextCycle(t *testing.T) { ds := mockDS() bc := newFakeBroadcaster() - p := testPump(t, ds, bc, time.Minute) + p := testPump(t, ds, bc) p.SetInput(pumpInputFor(2)) snap, reason := p.Take(t.Context(), 2) @@ -69,23 +66,22 @@ func Test_blobPump_TakeKicksNextCycle(t *testing.T) { p.SetInput(pumpInputFor(3)) snap, reason = p.Take(t.Context(), 3) require.NotNil(t, snap, "reason: %s", reason) - require.Equal(t, uint64(2), snap.forSeqNr) - require.Equal(t, uint64(2+DefaultMaxSnapshotRounds), snap.usableBefore) - require.Equal(t, uint64(2+DefaultBlobLifetimeRounds), snap.expiresAt) - require.NotEmpty(t, snap.handleBytes) + require.Equal(t, uint64(2), snap.cycleStartSeqNr) + require.Equal(t, uint64(2+DefaultBlobLifetimeRounds), snap.blobExpirationHintSeqNr) + require.NotEmpty(t, snap.blobHandleBytes) require.Equal(t, uint64(1), p.Misses()) - // The blob was hinted to expire at forSeqNr + lifetime. Assert on the first + // The blob was hinted to expire at cycleStartSeqNr + lifetime. Assert on the first // broadcast: later cycles re-broadcast an identical payload, which is // content-addressed to the same handle, so only the ordered hint log // distinguishes them. hints := bc.Hints() require.NotEmpty(t, hints) - require.Equal(t, ocr3_1types.BlobExpirationHintSequenceNumber{SeqNr: snap.expiresAt}, hints[0]) + require.Equal(t, ocr3_1types.BlobExpirationHintSequenceNumber{SeqNr: snap.blobExpirationHintSeqNr}, hints[0]) // The snapshot's handle fetches back the payload the pump broadcast. var handle ocr3_1types.BlobHandle - require.NoError(t, handle.UnmarshalBinary(snap.handleBytes)) + require.NoError(t, handle.UnmarshalBinary(snap.blobHandleBytes)) payload, err := bc.FetchBlob(tests.Context(t), handle) require.NoError(t, err) require.NotEmpty(t, payload) @@ -97,7 +93,7 @@ func Test_blobPump_TakeKicksNextCycle(t *testing.T) { func Test_blobPump_DropsUnrequestedStreams(t *testing.T) { ds := mockDS() ds.vals[999] = protocol.ToDecimal(decimal.NewFromInt(9)) - p := testPump(t, ds, newFakeBroadcaster(), time.Minute) + p := testPump(t, ds, newFakeBroadcaster()) p.SetInput(pumpInputFor(2)) p.Take(t.Context(), 2) @@ -106,7 +102,8 @@ func Test_blobPump_DropsUnrequestedStreams(t *testing.T) { p.SetInput(pumpInputFor(3)) snap, reason := p.Take(t.Context(), 3) require.NotNil(t, snap, "reason: %s", reason) - require.Equal(t, 1, snap.streamCount) + require.Equal(t, 1, snap.requestedStreams) + require.Equal(t, 1, snap.observedStreams) } func Test_dropUnobservable(t *testing.T) { @@ -122,92 +119,135 @@ func Test_dropUnobservable(t *testing.T) { assert.Nil(t, sv[3]) // What is left decodes on the receiving side. - payload, err := marshalStreamValues(sv) + payload, err := marshalStreamValues(sv, 1) require.NoError(t, err) raw, err := decodeBlobPayload(payload, maxDecompressedBlobPayloadBytes) require.NoError(t, err) - chunk := &protocol.LLOObservationProto{} + chunk := &protocol.LLOBlobPayloadProto{} require.NoError(t, proto.Unmarshal(raw, chunk)) require.Len(t, chunk.StreamValues, 1) _, err = streamValueFromProtoAllowNil(chunk.StreamValues[1]) require.NoError(t, err) } -// Test_blobPump_TakeIsSingleUse guards against two rounds referencing the same -// blob handle. -func Test_blobPump_TakeIsSingleUse(t *testing.T) { - p := testPump(t, mockDS(), newFakeBroadcaster(), time.Minute) +// Test_blobPump_ReusesSnapshotUntilNewerParks covers reuse: the parked +// snapshot serves every round until a newer one replaces it, taken or not. The +// data source never returns, so only the snapshots parked by hand are offered. +func Test_blobPump_ReusesSnapshotUntilNewerParks(t *testing.T) { + ds := &gatedDataSource{release: make(chan struct{}), entered: make(chan struct{})} + defer close(ds.release) + p := testPump(t, ds, newFakeBroadcaster()) p.SetInput(pumpInputFor(2)) - require.Eventually(t, func() bool { - _, _ = p.Take(t.Context(), 2) - return p.Cycles() >= 1 - }, tests.WaitTimeout(t), 10*time.Millisecond) - require.Eventually(t, func() bool { - snap, _ := p.Take(t.Context(), 2) - return snap != nil - }, tests.WaitTimeout(t), 10*time.Millisecond) + first := &blobSnapshot{blobHandleBytes: []byte{1}, cycleStartSeqNr: 2, blobExpirationHintSeqNr: 2 + DefaultBlobLifetimeRounds} + p.park(first) + for seqNr := uint64(3); seqNr <= 2+SnapshotReuseRounds; seqNr++ { + snap, reason := p.Take(t.Context(), seqNr) + require.Same(t, first, snap, "seqNr %d: %s", seqNr, reason) + } + require.Equal(t, uint64(SnapshotReuseRounds-1), p.Reuses()) + require.Zero(t, p.Misses()) - // The pump may have parked a fresh snapshot by now, so assert on the parked - // slot directly rather than on a second Take. - p.takeReady(t.Context(), 0) - snap, reason := p.Take(t.Context(), 2) + // Past the fetch margin the old snapshot is withheld, not replaced. + snap, reason := p.Take(t.Context(), 3+SnapshotReuseRounds) require.Nil(t, snap) - require.NotEmpty(t, reason) -} + require.Contains(t, reason, "expires too soon") + require.Equal(t, uint64(1), p.Misses()) -func Test_blobPump_RejectsStaleSnapshots(t *testing.T) { - // The local freshness gate is usableBefore, which falls well short of the - // blob's own expiry: the snapshot stops being referenceable while the blob - // is still fetchable by peers. - t.Run("too stale by sequence number", func(t *testing.T) { - p := testPump(t, mockDS(), newFakeBroadcaster(), time.Minute) - p.park(&blobSnapshot{handleBytes: []byte{1}, observedAt: time.Now(), forSeqNr: 2, usableBefore: 4, expiresAt: 6}) + // A newer snapshot replaces the previous one whether or not it was taken. + second := &blobSnapshot{blobHandleBytes: []byte{2}, cycleStartSeqNr: 6, blobExpirationHintSeqNr: 6 + DefaultBlobLifetimeRounds} + p.park(second) + third := &blobSnapshot{blobHandleBytes: []byte{3}, cycleStartSeqNr: 7, blobExpirationHintSeqNr: 7 + DefaultBlobLifetimeRounds} + p.park(third) + snap, reason = p.Take(t.Context(), 8) + require.Same(t, third, snap, reason) + require.Equal(t, uint64(SnapshotReuseRounds-1), p.Reuses(), "first take of a new snapshot is not a reuse") +} - snap, reason := p.Take(t.Context(), 4) - require.Nil(t, snap) - require.Contains(t, reason, "too stale") - require.Equal(t, uint64(1), p.Misses()) - }) +// Test_blobPump_TakeWaitsForNewerWhenReferenced asserts a round that already +// has the parked snapshot on the wire waits for the in-flight cycle, so a +// newer snapshot is preferred to a reuse whenever one lands in time. +func Test_blobPump_TakeWaitsForNewerWhenReferenced(t *testing.T) { + ds := &gatedDataSource{release: make(chan struct{}), entered: make(chan struct{})} + p := testPump(t, ds, newFakeBroadcaster()) + p.inFlightWait = tests.WaitTimeout(t) + p.SetInput(pumpInputFor(2)) - t.Run("expired by wall clock", func(t *testing.T) { - p := testPump(t, mockDS(), newFakeBroadcaster(), time.Nanosecond) - p.park(&blobSnapshot{handleBytes: []byte{1}, observedAt: time.Now().Add(-time.Hour), forSeqNr: 2, usableBefore: 100, expiresAt: 100}) + old := &blobSnapshot{blobHandleBytes: []byte{1}, cycleStartSeqNr: 2, blobExpirationHintSeqNr: 2 + DefaultBlobLifetimeRounds} + p.park(old) + snap, _ := p.Take(t.Context(), 3) + require.Same(t, old, snap) + select { + case <-ds.entered: + case <-time.After(tests.WaitTimeout(t)): + t.Fatal("DataSource.Observe was never called") + } - snap, reason := p.Take(t.Context(), 3) - require.Nil(t, snap) - require.Contains(t, reason, "too old") - }) + go func() { + time.Sleep(50 * time.Millisecond) + close(ds.release) + }() + snap, reason := p.Take(t.Context(), 4) + require.NotNil(t, snap, reason) + require.NotSame(t, old, snap, "Take reused the old snapshot instead of waiting for the cycle") + require.Zero(t, p.Reuses()) +} - t.Run("age check disabled", func(t *testing.T) { - p := testPump(t, mockDS(), newFakeBroadcaster(), -1) - p.park(&blobSnapshot{handleBytes: []byte{1}, observedAt: time.Now().Add(-time.Hour), forSeqNr: 2, usableBefore: 100, expiresAt: 100}) +func Test_blobPump_OffersSnapshotWhileFetchable(t *testing.T) { + // The only local gate: the blob must stay fetchable for + // BlobFetchMarginRounds past the round that references it. Freshness is + // the state transition's call. + park := func(p *blobPump, hint uint64) { + p.park(&blobSnapshot{blobHandleBytes: []byte{1}, cycleStartSeqNr: 2, blobExpirationHintSeqNr: hint}) + } - snap, _ := p.Take(t.Context(), 3) - require.NotNil(t, snap, "with the age check disabled only maxSnapshotRounds bounds staleness") + t.Run("offered up to the margin", func(t *testing.T) { + p := testPump(t, mockDS(), newFakeBroadcaster()) + for seqNr := uint64(3); seqNr+BlobFetchMarginRounds <= 2+DefaultBlobLifetimeRounds; seqNr++ { + park(p, 2+DefaultBlobLifetimeRounds) + snap, reason := p.Take(t.Context(), seqNr) + require.NotNil(t, snap, "seqNr %d: %s", seqNr, reason) + } + require.Zero(t, p.Misses()) }) - // With no explicit age the bound is derived from the measured round period, - // so a pump that has seen no rounds yet must not reject on age: guessing a - // cadence would silently stop the node contributing stream values. - t.Run("derived age check is inert until a round period is measured", func(t *testing.T) { - p := testPump(t, mockDS(), newFakeBroadcaster(), 0) - p.park(&blobSnapshot{handleBytes: []byte{1}, observedAt: time.Now().Add(-time.Hour), forSeqNr: 2, usableBefore: 100, expiresAt: 100}) - - snap, reason := p.Take(t.Context(), 3) - require.NotNil(t, snap, "reason: %s", reason) + t.Run("withheld inside the margin", func(t *testing.T) { + p := testPump(t, mockDS(), newFakeBroadcaster()) + park(p, 2+DefaultBlobLifetimeRounds) + snap, reason := p.Take(t.Context(), 2+DefaultBlobLifetimeRounds-BlobFetchMarginRounds+1) + require.Nil(t, snap) + require.Contains(t, reason, "expires too soon") + require.Equal(t, uint64(1), p.Misses()) }) - t.Run("derived age check rejects once the round period is known", func(t *testing.T) { - p := testPump(t, mockDS(), newFakeBroadcaster(), 0) - p.mu.Lock() - p.roundPeriod = time.Millisecond - p.mu.Unlock() - p.park(&blobSnapshot{handleBytes: []byte{1}, observedAt: time.Now().Add(-time.Hour), forSeqNr: 2, usableBefore: 100, expiresAt: 100}) + t.Run("withheld past expiry", func(t *testing.T) { + p := testPump(t, mockDS(), newFakeBroadcaster()) + park(p, 6) + snap, reason := p.Take(t.Context(), 7) + require.Nil(t, snap) + require.Contains(t, reason, "expires too soon") + }) - snap, reason := p.Take(t.Context(), 3) + t.Run("withheld past the round age bound even while fetchable", func(t *testing.T) { + // A long lifetime, or a broadcast retry that landed rounds late, keeps + // the blob fetchable past the age bound the state transition applies. + p := testPump(t, mockDS(), newFakeBroadcaster()) + park(p, 2+MaxBlobLifetimeRounds) + snap, reason := p.Take(t.Context(), 2+MaxStreamValueAgeRounds) + require.NotNil(t, snap, reason) + park(p, 2+MaxBlobLifetimeRounds) + snap, reason = p.Take(t.Context(), 2+MaxStreamValueAgeRounds+1) require.Nil(t, snap) - require.Contains(t, reason, "too old") + require.Contains(t, reason, "past the stream value age bound") + require.Equal(t, uint64(1), p.Misses()) + }) + + t.Run("the default lifetime covers the reuse horizon", func(t *testing.T) { + // A snapshot gathered during round N is first offered at N+1 and must + // still be offered at N+SnapshotReuseRounds. + snap := &blobSnapshot{cycleStartSeqNr: 2, blobExpirationHintSeqNr: 2 + DefaultBlobLifetimeRounds} + require.True(t, snap.isFetchableAtSeqNr(2+SnapshotReuseRounds)) + require.False(t, snap.isFetchableAtSeqNr(2+SnapshotReuseRounds+1)) }) } @@ -218,7 +258,7 @@ func Test_blobPump_ParksNothingOnFailure(t *testing.T) { t.Run("data source error", func(t *testing.T) { ds := mockDS() ds.err = errors.New("bridge down") - p := testPump(t, ds, newFakeBroadcaster(), time.Minute) + p := testPump(t, ds, newFakeBroadcaster()) p.SetInput(pumpInputFor(2)) _, _ = p.Take(t.Context(), 2) @@ -234,7 +274,7 @@ func Test_blobPump_ParksNothingOnFailure(t *testing.T) { bc.SetBroadcastError(errors.New("broadcast unavailable")) return bc }() - p := testPump(t, mockDS(), bc, time.Minute) + p := testPump(t, mockDS(), bc) p.SetInput(pumpInputFor(2)) _, _ = p.Take(t.Context(), 2) @@ -256,7 +296,7 @@ func Test_blobPump_SkipsIdleInput(t *testing.T) { t.Run(name, func(t *testing.T) { ds := mockDS() bc := newFakeBroadcaster() - p := testPump(t, ds, bc, time.Minute) + p := testPump(t, ds, bc) p.SetInput(in) for i := 0; i < 3; i++ { _, _ = p.Take(t.Context(), 2) @@ -273,7 +313,7 @@ func Test_blobPump_SkipsIdleInput(t *testing.T) { func Test_blobPump_SingleFlight(t *testing.T) { release := make(chan struct{}) ds := &blockingDataSource{release: release} - p := testPump(t, ds, newFakeBroadcaster(), time.Minute) + p := testPump(t, ds, newFakeBroadcaster()) p.SetInput(pumpInputFor(2)) for i := 0; i < 10; i++ { @@ -316,7 +356,7 @@ func (g *gatedDataSource) Observe(ctx context.Context, sv protocol.StreamValues, // the wait. func Test_blobPump_TakeWaitsForInFlightCycle(t *testing.T) { ds := &gatedDataSource{release: make(chan struct{}), entered: make(chan struct{})} - p := testPump(t, ds, newFakeBroadcaster(), time.Minute) + p := testPump(t, ds, newFakeBroadcaster()) p.inFlightWait = tests.WaitTimeout(t) // The first Take only kicks the cycle: nothing is in flight yet, so there is @@ -350,7 +390,7 @@ func Test_blobPump_TakeWaitFallsThroughOnTimeout(t *testing.T) { ds := &gatedDataSource{release: make(chan struct{}), entered: make(chan struct{})} defer close(ds.release) - p := testPump(t, ds, newFakeBroadcaster(), time.Minute) + p := testPump(t, ds, newFakeBroadcaster()) p.inFlightWait = 50 * time.Millisecond p.SetInput(pumpInputFor(2)) @@ -374,44 +414,6 @@ func Test_blobPump_TakeWaitFallsThroughOnTimeout(t *testing.T) { // estimate to gaps that really are one round wide: rounds that observe no // streams skip Take, and folding the wider gap they leave would inflate the // derived age bound. -func Test_blobPump_RoundPeriodOnlyMeasuresConsecutiveRounds(t *testing.T) { - p := testPump(t, mockDS(), newFakeBroadcaster(), time.Minute) - - base := time.Now() - p.recordRoundLocked(base, 2) - require.Zero(t, p.roundPeriod, "first round has nothing to measure against") - - // Round 5 skips rounds 3 and 4, so its gap spans three round periods. - p.recordRoundLocked(base.Add(300*time.Millisecond), 5) - require.Zero(t, p.roundPeriod, "gap across skipped rounds was folded in") - - p.recordRoundLocked(base.Add(400*time.Millisecond), 6) - require.Equal(t, 100*time.Millisecond, p.roundPeriod) - - // A repeated sequence number is not a new round either. - p.recordRoundLocked(base.Add(900*time.Millisecond), 6) - require.Equal(t, 100*time.Millisecond, p.roundPeriod) -} - -// Test_blobPump_RoundPeriodIsCapped covers a stalled round: the gap is wall -// clock, so without the cap one stall would inflate the derived age bound for -// several rounds after it. -func Test_blobPump_RoundPeriodIsCapped(t *testing.T) { - p := testPump(t, mockDS(), newFakeBroadcaster(), time.Minute) - p.maxRoundPeriod = 400 * time.Millisecond - - base := time.Now() - p.recordRoundLocked(base, 2) - p.recordRoundLocked(base.Add(time.Hour), 3) - require.Equal(t, p.maxRoundPeriod, p.roundPeriod, "a stalled round was folded in uncapped") - - // Uncapped, the estimate stays free to follow a slow DON. - cap := p.maxRoundPeriod - p.maxRoundPeriod = 0 - p.recordRoundLocked(base.Add(2*time.Hour), 4) - require.Greater(t, p.roundPeriod, cap) -} - // Test_blobPump_ExpectedMissesAreNotCounted covers the rounds that lose their // stream values by design: a pump with no transport wired, and a round whose // input gives a cycle nothing to do. Neither is a miss, so the counters stay @@ -419,7 +421,7 @@ func Test_blobPump_RoundPeriodIsCapped(t *testing.T) { // producing and is not. func Test_blobPump_ExpectedMissesAreNotCounted(t *testing.T) { t.Run("disabled pump", func(t *testing.T) { - p := testPump(t, nil, nil, time.Minute) + p := testPump(t, nil, nil) for i := 0; i < 2*MissStreakLogThreshold; i++ { snap, reason := p.Take(t.Context(), 2) @@ -431,7 +433,7 @@ func Test_blobPump_ExpectedMissesAreNotCounted(t *testing.T) { }) t.Run("nothing to observe", func(t *testing.T) { - p := testPump(t, mockDS(), newFakeBroadcaster(), time.Minute) + p := testPump(t, mockDS(), newFakeBroadcaster()) p.SetInput(pumpInput{streams: nil, seqNr: 2, lifeCycleStage: protocol.LifeCycleStageProduction}) snap, reason := p.Take(t.Context(), 2) @@ -442,7 +444,7 @@ func Test_blobPump_ExpectedMissesAreNotCounted(t *testing.T) { }) t.Run("retired", func(t *testing.T) { - p := testPump(t, mockDS(), newFakeBroadcaster(), time.Minute) + p := testPump(t, mockDS(), newFakeBroadcaster()) p.SetInput(pumpInput{streams: []llotypes.StreamID{100}, seqNr: 2, lifeCycleStage: protocol.LifeCycleStageRetired}) snap, reason := p.Take(t.Context(), 2) @@ -460,7 +462,7 @@ func Test_blobPump_TakeWaitHonoursContext(t *testing.T) { ds := &gatedDataSource{release: make(chan struct{}), entered: make(chan struct{})} defer close(ds.release) - p := testPump(t, ds, newFakeBroadcaster(), time.Minute) + p := testPump(t, ds, newFakeBroadcaster()) p.inFlightWait = tests.WaitTimeout(t) p.SetInput(pumpInputFor(2)) @@ -488,7 +490,7 @@ func Test_blobPump_TakeWaitHonoursContext(t *testing.T) { // cycle rather than to an absent snapshot. func Test_blobPump_TakeWaitReportsCycleAfterItEnds(t *testing.T) { ds := &gatedDataSource{release: make(chan struct{}), entered: make(chan struct{}), err: errors.New("boom")} - p := testPump(t, ds, newFakeBroadcaster(), time.Minute) + p := testPump(t, ds, newFakeBroadcaster()) p.inFlightWait = 500 * time.Millisecond p.SetInput(pumpInputFor(2)) @@ -537,7 +539,7 @@ func Test_observableStreams(t *testing.T) { func Test_blobPump_DisabledIsInert(t *testing.T) { t.Run("nil broadcaster", func(t *testing.T) { ds := mockDS() - p := testPump(t, ds, nil, time.Minute) + p := testPump(t, ds, nil) p.SetInput(pumpInputFor(2)) for i := 0; i < 3; i++ { snap, reason := p.Take(t.Context(), 2) @@ -550,7 +552,7 @@ func Test_blobPump_DisabledIsInert(t *testing.T) { t.Run("nil data source", func(t *testing.T) { bc := newFakeBroadcaster() - p := testPump(t, nil, bc, time.Minute) + p := testPump(t, nil, bc) p.SetInput(pumpInputFor(2)) snap, reason := p.Take(t.Context(), 2) require.Nil(t, snap) @@ -571,7 +573,7 @@ func (p *panicDataSource) Observe(ctx context.Context, sv protocol.StreamValues, // nothing and later cycles still run. func Test_blobPump_SurvivesDataSourcePanic(t *testing.T) { ds := &panicDataSource{} - p := testPump(t, ds, newFakeBroadcaster(), time.Minute) + p := testPump(t, ds, newFakeBroadcaster()) p.SetInput(pumpInputFor(2)) _, _ = p.Take(t.Context(), 2) @@ -614,7 +616,6 @@ func Test_blobPump_CloseDoesNotHangOnStuckDataSource(t *testing.T) { bbf: newFakeBroadcaster(), ds: ds, observationTimeout: time.Minute, - maxSnapshotRounds: DefaultMaxSnapshotRounds, blobLifetimeRounds: DefaultBlobLifetimeRounds, }) require.Equal(t, closeTimeoutSlackMultiplier*time.Minute, p.closeTimeout, "closeTimeout must derive from the observation timeout") @@ -668,7 +669,7 @@ func Test_blobPump_RetriesFailedBroadcast(t *testing.T) { bc := &flakyBroadcaster{BlobBroadcastFetcher: newFakeBroadcaster()} bc.failures.Store(1) - p := testPump(t, ds, bc, time.Minute) + p := testPump(t, ds, bc) p.SetInput(pumpInputFor(2)) _, _ = p.Take(t.Context(), 2) @@ -677,7 +678,7 @@ func Test_blobPump_RetriesFailedBroadcast(t *testing.T) { snap, reason := p.Take(t.Context(), 3) require.NotNil(t, snap, reason) - require.EqualValues(t, 2, snap.forSeqNr, "the retry does not change the round the values were gathered for") + require.EqualValues(t, 2, snap.cycleStartSeqNr, "the retry does not change the round the values were gathered for") } // Test_blobPump_BroadcastRetryRefreshesExpiry asserts a retry that lands after @@ -696,7 +697,7 @@ func Test_blobPump_BroadcastRetryRefreshesExpiry(t *testing.T) { p.SetInput(pumpInputFor(5)) } } - p = testPump(t, ds, bc, time.Minute) + p = testPump(t, ds, bc) p.SetInput(pumpInputFor(2)) _, _ = p.Take(t.Context(), 2) @@ -705,11 +706,11 @@ func Test_blobPump_BroadcastRetryRefreshesExpiry(t *testing.T) { require.Len(t, hints, 1) require.Equal(t, ocr3_1types.BlobExpirationHintSequenceNumber{SeqNr: 5 + DefaultBlobLifetimeRounds}, hints[0]) - // Fetchability moved forward; local freshness did not. + // Fetchability moved forward. The cycle the values belong to did not. snap, reason := p.Take(t.Context(), 3) require.NotNil(t, snap, reason) - require.EqualValues(t, 2+DefaultMaxSnapshotRounds, snap.usableBefore) - require.EqualValues(t, 5+DefaultBlobLifetimeRounds, snap.expiresAt) + require.EqualValues(t, 2, snap.cycleStartSeqNr) + require.EqualValues(t, 5+DefaultBlobLifetimeRounds, snap.blobExpirationHintSeqNr) } // Test_blobPump_BroadcastRetriesAreBounded asserts a transport that stays down @@ -719,7 +720,7 @@ func Test_blobPump_BroadcastRetriesAreBounded(t *testing.T) { bc := &flakyBroadcaster{BlobBroadcastFetcher: newFakeBroadcaster()} bc.failures.Store(1 << 30) - p := testPump(t, ds, bc, time.Minute) + p := testPump(t, ds, bc) p.SetInput(pumpInputFor(2)) _, _ = p.Take(t.Context(), 2) @@ -729,47 +730,32 @@ func Test_blobPump_BroadcastRetriesAreBounded(t *testing.T) { require.Nil(t, snap) } -func Test_ResolveBlobRounds(t *testing.T) { - t.Run("applies the defaults", func(t *testing.T) { - snap, life, err := ResolveBlobRounds(0, 0) +func Test_ResolveBlobLifetimeRounds(t *testing.T) { + t.Run("applies the default", func(t *testing.T) { + life, err := ResolveBlobLifetimeRounds(0) require.NoError(t, err) - assert.Equal(t, uint64(DefaultMaxSnapshotRounds), snap) assert.Equal(t, uint64(DefaultBlobLifetimeRounds), life) }) - t.Run("rejects a snapshot window below the minimum", func(t *testing.T) { - _, _, err := ResolveBlobRounds(1, 0) - require.ErrorContains(t, err, "below MinMaxSnapshotRounds") + t.Run("rejects a lifetime below the minimum", func(t *testing.T) { + _, err := ResolveBlobLifetimeRounds(MinBlobLifetimeRounds - 1) + require.ErrorContains(t, err, "below MinBlobLifetimeRounds") }) t.Run("rejects a lifetime past the maximum", func(t *testing.T) { - _, _, err := ResolveBlobRounds(0, MaxBlobLifetimeRounds+1) + _, err := ResolveBlobLifetimeRounds(MaxBlobLifetimeRounds + 1) require.ErrorContains(t, err, "exceeds MaxBlobLifetimeRounds") }) - t.Run("rejects too little fetch margin", func(t *testing.T) { - _, _, err := ResolveBlobRounds(8, 8) - require.ErrorContains(t, err, "rounds of fetch margin") - }) - - t.Run("rejects a lifetime shorter than the margin", func(t *testing.T) { - _, _, err := ResolveBlobRounds(MinMaxSnapshotRounds, 1) - require.ErrorContains(t, err, "rounds of fetch margin") - }) - - t.Run("rejects a snapshot window that would wrap the margin sum", func(t *testing.T) { - // maxSnapshotRounds+BlobFetchMarginRounds wraps to a small number, so - // comparing the sum would accept this and overflow usableBefore. - _, _, err := ResolveBlobRounds(math.MaxUint64, 0) - require.ErrorContains(t, err, "rounds of fetch margin") - _, _, err = ResolveBlobRounds(math.MaxUint64-BlobFetchMarginRounds+1, 0) - require.ErrorContains(t, err, "rounds of fetch margin") + t.Run("accepts the bounds", func(t *testing.T) { + for _, v := range []uint64{MinBlobLifetimeRounds, MaxBlobLifetimeRounds} { + life, err := ResolveBlobLifetimeRounds(v) + require.NoError(t, err) + assert.Equal(t, v, life) + } }) - t.Run("accepts the margin boundary", func(t *testing.T) { - snap, life, err := ResolveBlobRounds(MaxBlobLifetimeRounds+1-BlobFetchMarginRounds, MaxBlobLifetimeRounds) - require.NoError(t, err) - assert.Equal(t, uint64(MaxBlobLifetimeRounds+1-BlobFetchMarginRounds), snap) - assert.Equal(t, uint64(MaxBlobLifetimeRounds), life) + t.Run("the default leaves room for reuse", func(t *testing.T) { + require.GreaterOrEqual(t, DefaultBlobLifetimeRounds-BlobFetchMarginRounds, SnapshotReuseRounds) }) } diff --git a/llo/dev/v31/concurrency_test.go b/llo/dev/v31/concurrency_test.go index 7e8c8177..e1245ead 100644 --- a/llo/dev/v31/concurrency_test.go +++ b/llo/dev/v31/concurrency_test.go @@ -61,9 +61,9 @@ func Test_Reports_StateTransition_Concurrent_OptsIsolation(t *testing.T) { // so the channel is reportable once it is in effect. obsRound := func(ts uint64, defs llotypes.ChannelDefinitions) []ocrtypes.AttributedObservation { obs := Observation{ - UnixTimestampNanoseconds: ts, - UpdateChannelDefinitions: defs, - StreamValues: protocol.StreamValues{100: protocol.ToDecimal(decimal.NewFromInt(5))}, + ObservationTimestampNanoseconds: ts, + UpdateChannelDefinitions: defs, + StreamValues: protocol.StreamValues{100: protocol.ToDecimal(decimal.NewFromInt(5))}, } aos := make([]ocrtypes.AttributedObservation, 0, 4) for i := 0; i < 4; i++ { @@ -81,7 +81,7 @@ func Test_Reports_StateTransition_Concurrent_OptsIsolation(t *testing.T) { p.ReportCodecs = map[llotypes.ReportFormat]protocol.ReportCodec{llotypes.ReportFormatJSON: optsEchoCodec{}} kv := newMemKV() - _, err := p.StateTransition(ctx, 1, ocrtypes.AttributedQuery{}, obsRound(1_000, nil), kv, testBlobs) + _, err := p.StateTransition(ctx, 1, ocrtypes.AttributedQuery{}, emptyRound(), kv, testBlobs) require.NoError(t, err) _, err = p.StateTransition(ctx, 2, ocrtypes.AttributedQuery{}, obsRound(2_000, llotypes.ChannelDefinitions{1: withOpts(1)}), kv, testBlobs) require.NoError(t, err) @@ -163,9 +163,9 @@ func Test_Reports_RebuildsEvictedGeneration(t *testing.T) { } obsRound := func(ts uint64, defs llotypes.ChannelDefinitions) []ocrtypes.AttributedObservation { obs := Observation{ - UnixTimestampNanoseconds: ts, - UpdateChannelDefinitions: defs, - StreamValues: protocol.StreamValues{100: protocol.ToDecimal(decimal.NewFromInt(5))}, + ObservationTimestampNanoseconds: ts, + UpdateChannelDefinitions: defs, + StreamValues: protocol.StreamValues{100: protocol.ToDecimal(decimal.NewFromInt(5))}, } aos := make([]ocrtypes.AttributedObservation, 0, 4) for i := 0; i < 4; i++ { @@ -178,7 +178,7 @@ func Test_Reports_RebuildsEvictedGeneration(t *testing.T) { p.ReportCodecs = map[llotypes.ReportFormat]protocol.ReportCodec{llotypes.ReportFormatJSON: optsEchoCodec{}} kv := newMemKV() - _, err := p.StateTransition(ctx, 1, ocrtypes.AttributedQuery{}, obsRound(1_000, nil), kv, testBlobs) + _, err := p.StateTransition(ctx, 1, ocrtypes.AttributedQuery{}, emptyRound(), kv, testBlobs) require.NoError(t, err) // Round 2 agrees the channel; it takes effect in round 3, which seeds its // watermark, and round 4 is the first that reports it. No round after 2 @@ -219,8 +219,8 @@ func Test_Reports_RebuildsEvictedGeneration(t *testing.T) { // seqNr, without inserting one: Load only calls build on a miss, and a build // that fails stores nothing. func cachedGeneration(c *protocol.ChannelCache, seqNr uint64) bool { - _, err := c.Load(seqNr, func() (llotypes.ChannelDefinitions, error) { + _, err := c.Load(seqNr, func() ([]byte, error) { return nil, errors.New("not cached") - }) + }, decodeChannelState) return err == nil } diff --git a/llo/dev/v31/decode_fuzz_test.go b/llo/dev/v31/decode_fuzz_test.go index 2232bce2..e9de989e 100644 --- a/llo/dev/v31/decode_fuzz_test.go +++ b/llo/dev/v31/decode_fuzz_test.go @@ -23,7 +23,7 @@ import ( // enforces. // payloadFetcher returns the same payload for every handle, so a fuzzer can -// drive the blob path of decodeObservation with arbitrary bytes. +// drive the blob path of fetchBlobsAndDecodeObservation with arbitrary bytes. type payloadFetcher struct{ payload []byte } func (f payloadFetcher) FetchBlob(context.Context, ocr3_1types.BlobHandle) ([]byte, error) { @@ -37,12 +37,12 @@ var _ ocr3_1types.BlobFetcher = payloadFetcher{} // byzantine peer picks these bytes, and every other oracle decodes them. func FuzzDecodeObservation(f *testing.F) { obs := Observation{ - AttestedPredecessorRetirement: []byte("retirement"), - ShouldRetire: true, - UnixTimestampNanoseconds: 1_700_000_000_000_000_000, - RemoveChannelIDs: map[llotypes.ChannelID]struct{}{7: {}}, - UpdateChannelDefinitions: llotypes.ChannelDefinitions{1: jsonChannel()}, - SupportedReportFormats: formatSet(llotypes.ReportFormatJSON, llotypes.ReportFormatEVMPremiumLegacy), + AttestedPredecessorRetirement: []byte("retirement"), + ShouldRetire: true, + ObservationTimestampNanoseconds: 1_700_000_000_000_000_000, + RemoveChannelIDs: map[llotypes.ChannelID]struct{}{7: {}}, + UpdateChannelDefinitions: llotypes.ChannelDefinitions{1: jsonChannel()}, + SupportedReportFormats: formatSet(llotypes.ReportFormatJSON, llotypes.ReportFormatEVMPremiumLegacy), } encoded, err := encodeObservation(obs, nil) if err != nil { @@ -55,7 +55,7 @@ func FuzzDecodeObservation(f *testing.F) { f.Fatal(err) } - payload, err := marshalStreamValues(protocol.StreamValues{100: protocol.ToDecimal(decimal.NewFromInt(123))}) + payload, err := marshalStreamValues(protocol.StreamValues{100: protocol.ToDecimal(decimal.NewFromInt(123))}, 1) if err != nil { f.Fatal(err) } @@ -68,7 +68,7 @@ func FuzzDecodeObservation(f *testing.F) { f.Add([]byte("not an observation"), []byte("not a payload")) f.Fuzz(func(t *testing.T, raw, payload []byte) { - decoded, err := decodeObservation(context.Background(), ocrtypes.Observation(raw), payloadFetcher{payload: payload}, nil) + decoded, err := fetchBlobsAndDecodeObservation(context.Background(), ocrtypes.Observation(raw), payloadFetcher{payload: payload}, nil) if err != nil { return } @@ -108,8 +108,17 @@ func FuzzDecodePrecursor(f *testing.F) { if err != nil { f.Fatal(err) } + c, err := getPayloadCompressor() + if err != nil { + f.Fatal(err) + } + // A zstd frame that declares more than the precursor bound. + bomb := c.encoder.EncodeAll(make([]byte, maxDecompressedPrecursorBytes+1), []byte{payloadCodecZstd}) f.Add([]byte(full)) f.Add([]byte(empty)) + f.Add(bomb) + f.Add([]byte{payloadCodecRaw, 0x0a, 0x00}) + f.Add([]byte{payloadCodecZstd, 0xde, 0xad, 0xbe, 0xef}) f.Add([]byte{0x0a, 0x00}) f.Add([]byte("not a precursor")) f.Add([]byte{}) @@ -153,7 +162,7 @@ func FuzzLoadKVState(f *testing.F) { f.Add([]byte("production"), seeded.m[string(keyChannelState)], beU64(9), []byte(nil)) f.Add([]byte{}, []byte{}, []byte{}, []byte{}) f.Add([]byte("staging"), []byte("not a proto"), []byte{0x01}, []byte{0x01, 0x02}) - f.Add([]byte(nil), []byte{0x0a, 0x02, 0x08, 0x01}, beU64(1), append(beU32(100), beU32(1)...)) + f.Add([]byte(nil), []byte{payloadCodecRaw, 0x0a, 0x02, 0x08, 0x01}, beU64(1), []byte{payloadCodecZstd, 0x01, 0x02}) f.Fuzz(func(t *testing.T, lifecycle, channelState, seqNr, hotState []byte) { kv := newMemKV() @@ -195,6 +204,7 @@ func FuzzLoadKVState(f *testing.F) { func FuzzDecodeHistoryRecords(f *testing.F) { f.Add(append(beU32(100), beU32(1)...), []byte(nil), []byte(nil)) f.Add([]byte{0x01}, []byte("not a proto"), []byte("not a proto")) + f.Add([]byte{}, []byte{payloadCodecRaw, 0x08, 0x01}, []byte{payloadCodecZstd, 0x28, 0xb5, 0x2f, 0xfd}) f.Add([]byte{}, []byte{}, []byte{}) f.Fuzz(func(t *testing.T, index, header, chunk []byte) { diff --git a/llo/dev/v31/doc.go b/llo/dev/v31/doc.go index 3e764ab0..5e1f9ebc 100644 --- a/llo/dev/v31/doc.go +++ b/llo/dev/v31/doc.go @@ -46,6 +46,14 @@ // proto maps — or fixed-width big-endian integers) because the store is // replicated across oracles and any divergence halts the protocol. // +// The proto records (c/defs, c/codecs, r/agg and the history header and chunks) +// are then framed like blobs and the precursor, zstd-compressed whenever that +// shrinks them. libocr builds the state root from the framed bytes, so the +// same rule as for the precursor applies: Test_Golden_KVRecords and +// Test_Golden_KVHistoryChunkCompressed freeze them, and a dependency bump that +// changes them must roll out to the whole DON at once. Admission bounds the raw +// records under the per-key limit, so compression is headroom only. +// // # Deferred channel definitions // // Channel definition changes agreed in a round take effect in the NEXT round. @@ -81,7 +89,7 @@ // Stream values are always disseminated as a blob, never inline: an observation // carries only votes, the retirement report, its timestamp, and the handle of a // blob holding the round's stream values. See observation.go for the framing. -// The blob payload itself is framed by blobcompress.go: a leading codec byte +// The blob payload itself is framed by payloadcodec.go: a leading codec byte // followed by the stream-values proto, zstd-compressed whenever that shrinks // it. The codec is chosen by the writer and read from the byte, so nodes need // not agree on whether compression paid off. @@ -94,25 +102,39 @@ // discards a snapshot, so the pump rate tracks the round rate without knowing // deltaRound, and cycles are serial so only one Observe is ever in flight. // -// A snapshot is therefore gathered one round before it is used. Two separate -// bounds apply to it. MaxSnapshotRounds is local: it decides how stale the -// values may be when this node references them (forSeqNr + MaxSnapshotRounds), -// and is what a report format's staleness budget should be tuned against. -// BlobLifetimeRounds is remote: it is the expiration hint given to the blob -// transport (forSeqNr + BlobLifetimeRounds), deciding how long peers can still -// fetch the blob, and sits BlobFetchMarginRounds beyond the last seqNr at which -// the handle can be referenced. A broadcast that the transport refuses is +// A snapshot is therefore gathered one round before it is used, and stays +// offered until a newer one parks: a cycle that runs longer than a round, or +// fails, costs no round its stream values while the previous snapshot is still +// fetchable. The pump applies one bound to it, fetchability. BlobLifetimeRounds +// is the expiration hint given to the blob transport (cycleStartSeqNr + +// BlobLifetimeRounds), after which peers can no longer fetch the blob, and +// Take offers a snapshot only while its blob stays fetchable for +// BlobFetchMarginRounds more rounds, so slow or lagging peers can still fetch +// it. With the default lifetime that lets one snapshot serve +// SnapshotReuseRounds rounds. A broadcast that the transport refuses is // retried inside the cycle (BlobBroadcastAttempts), which is what keeps the // round trip off the OCR critical path; a retry recomputes the hint from the -// round current at that attempt, so the values stay bounded by MaxSnapshotRounds -// while the blob stays fetchable for the round that will reference it. A wall-clock age check derived from the -// measured round period guards against jitter on top. A round that finds -// nothing usable — cold start, a failed cycle, or a stale snapshot — emits an -// observation with no stream values. That is not a halt: quorum counts -// observations, not values. The cost lands in aggregation, which needs >F values -// per stream, so streams miss the round only if more than F nodes miss together. -// The pump counts misses and cycles (Misses / Cycles) so correlated misses show -// up as more than an unexplained report gap. +// round current at that attempt, so the blob stays fetchable for the round +// that will reference it. A round that finds nothing usable, on cold start or +// once the blob is about to expire, emits an observation with no stream +// values. That is not a halt: quorum counts observations, not values. The cost +// lands in aggregation, which needs >F values per stream, so streams miss the +// round only if more than F nodes miss together. The pump counts misses, +// cycles and reuses (Misses / Cycles / Reuses, exported as the +// llo_blob_pump_* counters) so correlated misses show up as more than an +// unexplained report gap. +// +// The pump does not judge whether its values are still fresh. A decision taken +// on one node, from its own clock, is invisible to its peers and withholds the +// node's values with no trace in consensus. The state transition judges +// instead, from replicated data only, so every oracle keeps the same values. +// The blob carries the seqNr its cycle started in (LLOBlobPayloadProto), the +// hot state carries the agreed timestamps of the last few rounds, and each +// contribution is held to a round age and a time age derived from those +// (freshness.go). A stream whose fresh contributions cannot reach the +// contribution floor aggregates every contribution instead, which is the +// behaviour without the rule, so a bound that proves too tight for a DON costs +// freshness, never liveness. The fallback is counted (llo_freshness metrics). // // # Parity status (vs v30) // @@ -141,6 +163,13 @@ // those channels report. Reports emits exactly those channels, so emission and // the validAfter advance read the same decision. // +// The precursor uses the same framing as blobs. Unlike a blob, its bytes must +// match on every oracle, because libocr digests and signs them. The choice of +// codec depends only on the raw bytes, and zstd output is stable for one +// library version with pinned options, so this holds within a version. +// Test_Golden_Precursor freezes the compressed bytes. A dependency bump that +// changes them must roll out to the whole DON at once. +// // Cross-round timestamped-aggregate carry-forward (in the r/agg record, // newer-wins monotonicity) and best-effort outcome/report telemetry are also // implemented. diff --git a/llo/dev/v31/factory.go b/llo/dev/v31/factory.go index 0bf27e32..4e1a91c2 100644 --- a/llo/dev/v31/factory.go +++ b/llo/dev/v31/factory.go @@ -45,16 +45,11 @@ type PluginFactoryParams struct { AttributedObservationTelemetryCh chan<- *protocol.LLOAttributedObservationTelemetry // DonID is optional and used only for telemetry and logging. DonID uint32 - // MaxSnapshotRounds overrides DefaultMaxSnapshotRounds if non-zero. Bounds - // how stale this node's own stream values may be when it references them, - // and nothing else; it does not affect what peers can fetch. Must be at - // least MinMaxSnapshotRounds, since a snapshot gathered for one sequence - // number is consumed by a later one, and must leave BlobFetchMarginRounds - // below BlobLifetimeRounds. - MaxSnapshotRounds uint64 // BlobLifetimeRounds overrides DefaultBlobLifetimeRounds if non-zero. Bounds - // how long peers can still fetch a broadcast blob, and nothing else; it does - // not bound staleness, MaxSnapshotRounds does. + // how long peers can still fetch a broadcast blob, and so for how many + // rounds past BlobFetchMarginRounds a snapshot can be offered. It does not + // bound staleness, the state transition does. Must be within + // [MinBlobLifetimeRounds, MaxBlobLifetimeRounds]. BlobLifetimeRounds uint64 // MaxDurationBlobObservation overrides the pump's per-cycle observation // budget (default: DefaultBlobObservationDurationMultiplier * @@ -65,17 +60,6 @@ type PluginFactoryParams struct { // a cycle already in flight to park, so a larger factor waits less. Must // be >0. BlobInFlightWaitFactor uint64 - // MaxBlobSnapshotAge pins the wall-clock age at which a parked snapshot is - // discarded. Left at zero the pump derives it from the round period it - // measures, which is the only safe default: any bound derived from - // MaxDurationObservation is unrelated to the round cadence and can reject - // every snapshot. A negative value disables the check, leaving - // MaxSnapshotRounds as the only staleness bound. - MaxBlobSnapshotAge time.Duration - // MaxRoundPeriod overrides DefaultMaxRoundPeriod if non-zero. Bounds the - // round period the pump measures, so a stalled round cannot inflate the - // derived snapshot age bound. Must be set above the DON real round cadence. - MaxRoundPeriod time.Duration } func NewPluginFactory(p PluginFactoryParams) *PluginFactory { @@ -102,7 +86,7 @@ func (f *PluginFactory) NewReportingPlugin(ctx context.Context, cfg ocr3types.Re // Initialize the memory ballast protocol.InitMemoryBallast() - maxSnapshotRounds, blobLifetimeRounds, err := ResolveBlobRounds(f.MaxSnapshotRounds, f.BlobLifetimeRounds) + blobLifetimeRounds, err := ResolveBlobLifetimeRounds(f.BlobLifetimeRounds) if err != nil { return nil, nil, err } @@ -150,17 +134,14 @@ func (f *PluginFactory) NewReportingPlugin(ctx context.Context, cfg ocr3types.Re blobInFlightWaitFactor = defaultBlobInFlightWaitFactor } - maxRoundPeriod := f.MaxRoundPeriod - if maxRoundPeriod <= 0 { - maxRoundPeriod = DefaultMaxRoundPeriod - } - blobObservationTimeout := f.MaxDurationBlobObservation if blobObservationTimeout <= 0 { blobObservationTimeout = DefaultBlobObservationDurationMultiplier * cfg.MaxDurationObservation } p := &Plugin{ + freshnessMetrics: newFreshnessMetrics(f.DonID), + precursorMetrics: newPrecursorMetrics(f.DonID), Config: f.Config, PredecessorConfigDigest: onchainConfig.PredecessorConfigDigest, ConfigDigest: cfg.ConfigDigest, @@ -180,6 +161,10 @@ func (f *PluginFactory) NewReportingPlugin(ctx context.Context, cfg ocr3types.Re ProtocolVersion: offchainConfig.ProtocolVersion, DefaultMinReportIntervalNanoseconds: offchainConfig.DefaultMinReportIntervalNanoseconds, AggregationFaultTolerance: aggregationFaultTolerance, + // libocr fills EstimatedRoundInterval from the shared config's + // DeltaRound, a lower bound on the round interval, so it is the same + // on every oracle. + MinRoundInterval: cfg.EstimatedRoundInterval, } // Definitions and the opts decoded from them are cached together, as one @@ -194,12 +179,10 @@ func (f *PluginFactory) NewReportingPlugin(ctx context.Context, cfg ocr3types.Re bbf: bbf, ds: f.DataSource, configDigest: cfg.ConfigDigest, + donID: f.DonID, verboseLogging: f.Config.VerboseLogging, observationTimeout: blobObservationTimeout, inFlightWait: cfg.MaxDurationObservation / time.Duration(blobInFlightWaitFactor), - maxSnapshotAge: f.MaxBlobSnapshotAge, - maxSnapshotRounds: maxSnapshotRounds, - maxRoundPeriod: maxRoundPeriod, blobLifetimeRounds: blobLifetimeRounds, }) p.pump.Start() @@ -229,6 +212,8 @@ func (f *PluginFactory) NewReportingPlugin(ctx context.Context, cfg ocr3types.Re // decimal coefficient is bounded on // observation decode, and a calculated one // where it is written into the aggregates. + // These bounds hold for the raw proto, so + // zstd framing is headroom, not what fits it. // MaxKeyValueModifiedKeys* the per-round write set is c/defs plus r/agg // plus the history windows, and history is // bounded by protocol.MaxHistoryPairs, which diff --git a/llo/dev/v31/flow_test.go b/llo/dev/v31/flow_test.go index cf1e7545..1e42d7f0 100644 --- a/llo/dev/v31/flow_test.go +++ b/llo/dev/v31/flow_test.go @@ -188,9 +188,9 @@ func (m *mockPredecessorRetirementReportCache) VerifyAttestedRetirementReport(_ // signer set so the DON can agree on it and verify the report against it. func promotionObs(tsNanoseconds uint64) Observation { return Observation{ - UnixTimestampNanoseconds: tsNanoseconds, - AttestedPredecessorRetirement: []byte("attested"), - PredecessorSigners: testPredecessorSigners, + ObservationTimestampNanoseconds: tsNanoseconds, + AttestedPredecessorRetirement: []byte("attested"), + PredecessorSigners: testPredecessorSigners, } } @@ -200,7 +200,7 @@ func jsonChannel() llotypes.ChannelDefinition { // addChannelRound feeds 4 identical observations voting to add the given channel. func addChannelRound(t *testing.T, ts uint64, cid llotypes.ChannelID, cd llotypes.ChannelDefinition) []ocrtypes.AttributedObservation { - obs := Observation{UnixTimestampNanoseconds: ts, UpdateChannelDefinitions: llotypes.ChannelDefinitions{cid: cd}} + obs := Observation{ObservationTimestampNanoseconds: ts, UpdateChannelDefinitions: llotypes.ChannelDefinitions{cid: cd}} aos := make([]ocrtypes.AttributedObservation, 0, 4) for i := 0; i < 4; i++ { aos = append(aos, ao(i, mustEncodeObs(t, obs))) @@ -355,30 +355,6 @@ func Test_Factory_NewReportingPlugin_maxDurationObservation(t *testing.T) { }) } -func Test_Factory_MaxRoundPeriod(t *testing.T) { - ctx := tests.Context(t) - base := ocr3types.ReportingPluginConfig{N: 4, F: 1, ConfigDigest: ocrtypes.ConfigDigest{9}, OffchainConfig: mustEncodeOffchainConfig(t, 1), MaxDurationObservation: time.Second} - - newPump := func(t *testing.T, params PluginFactoryParams, cfg ocr3types.ReportingPluginConfig) *blobPump { - t.Helper() - params.OnchainConfigCodec = mockOnchainConfigCodec{} - params.Logger = logger.Test(t) - p, _, err := NewPluginFactory(params).NewReportingPlugin(ctx, cfg, nil) - require.NoError(t, err) - t.Cleanup(func() { require.NoError(t, p.Close()) }) - return p.(*Plugin).pump - } - - t.Run("defaulted", func(t *testing.T) { - require.Equal(t, DefaultMaxRoundPeriod, newPump(t, PluginFactoryParams{}, base).maxRoundPeriod) - }) - - t.Run("override wins", func(t *testing.T) { - pump := newPump(t, PluginFactoryParams{MaxRoundPeriod: time.Second}, base) - require.Equal(t, time.Second, pump.maxRoundPeriod) - }) -} - func Test_Factory_NewReportingPlugin(t *testing.T) { ctx := tests.Context(t) f := NewPluginFactory(PluginFactoryParams{ @@ -400,9 +376,7 @@ func Test_Factory_NewReportingPlugin(t *testing.T) { require.Equal(t, 3, pl.minContributions()) require.NotNil(t, pl.ChannelCache) require.NotNil(t, pl.pump) - require.Equal(t, uint64(DefaultMaxSnapshotRounds), pl.pump.maxSnapshotRounds) require.Equal(t, uint64(DefaultBlobLifetimeRounds), pl.pump.blobLifetimeRounds) - require.Equal(t, DefaultMaxRoundPeriod, pl.pump.maxRoundPeriod) require.NoError(t, pl.Close()) } @@ -441,7 +415,7 @@ func Test_Observation_And_Validate_Flow(t *testing.T) { first, err := p.Observation(ctx, 3, ocrtypes.AttributedQuery{}, kv, nil) require.NoError(t, err) require.NotEmpty(t, first) - decodedFirst, err := decodeObservation(ctx, first, bc, nil) + decodedFirst, err := fetchBlobsAndDecodeObservation(ctx, first, bc, nil) require.NoError(t, err) require.Empty(t, decodedFirst.StreamValues) @@ -452,7 +426,7 @@ func Test_Observation_And_Validate_Flow(t *testing.T) { obsBytes, err := p.Observation(ctx, 4, ocrtypes.AttributedQuery{}, kv, nil) require.NoError(t, err) require.NotEmpty(t, obsBytes) - decoded, err := decodeObservation(ctx, obsBytes, bc, nil) + decoded, err := fetchBlobsAndDecodeObservation(ctx, obsBytes, bc, nil) require.NoError(t, err) require.Contains(t, decoded.StreamValues, llotypes.StreamID(100)) @@ -479,7 +453,7 @@ func Test_StateTransition_ChannelRemoval(t *testing.T) { require.Contains(t, kvChannelDefs(t, kv), llotypes.ChannelID(1)) // Round 3: four oracles vote to remove channel 1. - removeObs := Observation{UnixTimestampNanoseconds: 2000, RemoveChannelIDs: map[llotypes.ChannelID]struct{}{1: {}}} + removeObs := Observation{ObservationTimestampNanoseconds: 2000, RemoveChannelIDs: map[llotypes.ChannelID]struct{}{1: {}}} removeAOs := make([]ocrtypes.AttributedObservation, 0, 4) for i := 0; i < 4; i++ { removeAOs = append(removeAOs, ao(i, mustEncodeObs(t, removeObs))) @@ -494,7 +468,7 @@ func Test_StateTransition_ChannelRemoval(t *testing.T) { require.Contains(t, kvHotState(t, kv).validAfterNanoseconds, llotypes.ChannelID(1)) // Round 4: the removal takes effect and the channel's state is dropped. - nextObs := Observation{UnixTimestampNanoseconds: 3000} + nextObs := Observation{ObservationTimestampNanoseconds: 3000} nextAOs := make([]ocrtypes.AttributedObservation, 0, 4) for i := 0; i < 4; i++ { nextAOs = append(nextAOs, ao(i, mustEncodeObs(t, nextObs))) @@ -601,7 +575,7 @@ func Test_StateTransition_Promotion_StagingOnlyChannelTreatedAsNew(t *testing.T) require.NotContains(t, kvHotState(t, kv).validAfterNanoseconds, llotypes.ChannelID(2)) // Round 3 (ts=2000): channel 2 is now in effect and gets its first watermark. - seedObs := Observation{UnixTimestampNanoseconds: 2000} + seedObs := Observation{ObservationTimestampNanoseconds: 2000} seedAOs := make([]ocrtypes.AttributedObservation, 0, 4) for i := 0; i < 4; i++ { seedAOs = append(seedAOs, ao(i, mustEncodeObs(t, seedObs))) @@ -633,7 +607,7 @@ func Test_ValidateObservation_Errors(t *testing.T) { kv := newMemKV() // AttestedPredecessorRetirement present but no predecessor -> error. - o1 := Observation{UnixTimestampNanoseconds: 1, AttestedPredecessorRetirement: []byte("x")} + o1 := Observation{ObservationTimestampNanoseconds: 1, AttestedPredecessorRetirement: []byte("x")} require.Error(t, p.ValidateObservation(ctx, 2, ocrtypes.AttributedQuery{}, ao(0, mustEncodeObs(t, o1)), kv, nil)) // Too many channel-definition updates -> error. @@ -641,11 +615,11 @@ func Test_ValidateObservation_Errors(t *testing.T) { for i := uint32(1); i <= 6; i++ { defs[llotypes.ChannelID(i)] = jsonChannel() } - o2 := Observation{UnixTimestampNanoseconds: 1, UpdateChannelDefinitions: defs} + o2 := Observation{ObservationTimestampNanoseconds: 1, UpdateChannelDefinitions: defs} require.Error(t, p.ValidateObservation(ctx, 2, ocrtypes.AttributedQuery{}, ao(0, mustEncodeObs(t, o2)), kv, nil)) // A TimestampedStreamValue whose nested value is not a Decimal -> error. - o3 := Observation{UnixTimestampNanoseconds: 1, StreamValues: protocol.StreamValues{ + o3 := Observation{ObservationTimestampNanoseconds: 1, StreamValues: protocol.StreamValues{ 1: &protocol.TimestampedStreamValue{StreamValue: &protocol.TimestampedStreamValue{StreamValue: protocol.ToDecimal(decimal.NewFromInt(1))}}, }} require.Error(t, p.ValidateObservation(ctx, 2, ocrtypes.AttributedQuery{}, ao(0, mustEncodeObs(t, o3)), kv, nil)) @@ -663,7 +637,7 @@ func Test_StateTransition_Retirement(t *testing.T) { require.NoError(t, err) // Round 3: four oracles vote to retire. - retireObs := Observation{UnixTimestampNanoseconds: 2000, ShouldRetire: true} + retireObs := Observation{ObservationTimestampNanoseconds: 2000, ShouldRetire: true} retireAOs := make([]ocrtypes.AttributedObservation, 0, 4) for i := 0; i < 4; i++ { retireAOs = append(retireAOs, ao(i, mustEncodeObs(t, retireObs))) @@ -691,7 +665,7 @@ func Test_StateTransition_RetirementThreshold(t *testing.T) { retireRound := func(t *testing.T, votes int) []ocrtypes.AttributedObservation { aos := make([]ocrtypes.AttributedObservation, 0, 3) for i := 0; i < 3; i++ { - obs := Observation{UnixTimestampNanoseconds: 2000, ShouldRetire: i < votes} + obs := Observation{ObservationTimestampNanoseconds: 2000, ShouldRetire: i < votes} aos = append(aos, ao(i, mustEncodeObs(t, obs))) } return aos @@ -759,16 +733,16 @@ func Test_ValidateObservation_RemoveAddSwapAtBudget(t *testing.T) { // it replaces, so the resulting set is back on the budget, not over it. replacement := llotypes.ChannelDefinitions{3: streamRangeChannel(llotypes.StreamID(2*half)+1, half)} swap := Observation{ - UnixTimestampNanoseconds: 1_000, - RemoveChannelIDs: map[llotypes.ChannelID]struct{}{2: {}}, - UpdateChannelDefinitions: replacement, + ObservationTimestampNanoseconds: 1_000, + RemoveChannelIDs: map[llotypes.ChannelID]struct{}{2: {}}, + UpdateChannelDefinitions: replacement, } require.NoError(t, p.ValidateObservation(ctx, 2, ocrtypes.AttributedQuery{}, ao(0, mustEncodeObs(t, swap)), kv, testBlobs)) // The same update without the removal vote does exceed the budget, which is // what makes the assertion above about the removals and not about slack in // the limit. - addOnly := Observation{UnixTimestampNanoseconds: 1_000, UpdateChannelDefinitions: replacement} + addOnly := Observation{ObservationTimestampNanoseconds: 1_000, UpdateChannelDefinitions: replacement} require.Error(t, p.ValidateObservation(ctx, 2, ocrtypes.AttributedQuery{}, ao(0, mustEncodeObs(t, addOnly)), kv, testBlobs)) } @@ -877,13 +851,15 @@ func Test_StateTransition_PredecessorConfigNeedsQuorum(t *testing.T) { // set of its own and attest a handover that never happened. func Test_StateTransition_PredecessorConfigAgreementIsPerRound(t *testing.T) { ctx := tests.Context(t) - p, kv := stagedPlugin(t, &mockPredecessorRetirementReportCache{report: protocol.RetirementReport{}}) + p, kv := stagedPlugin(t, &mockPredecessorRetirementReportCache{verifyErr: errors.New("Verify failed; not enough valid signatures")}) - // Round 2 reaches quorum on the real signer set but carries no retirement - // report, so the instance stays in staging and the agreement is discarded. + // Round 2 reaches quorum on the real signer set but its retirement report + // fails verification, so the instance stays in staging and the agreement is + // discarded. A signer set is only valid alongside a report, so the vote + // cannot be cast on its own. votesOnly := make([]ocrtypes.AttributedObservation, 0, 4) - for i := 0; i < 4; i++ { - votesOnly = append(votesOnly, ao(i, mustEncodeObs(t, Observation{UnixTimestampNanoseconds: 1000, PredecessorSigners: testPredecessorSigners}))) + for i := range 4 { + votesOnly = append(votesOnly, ao(i, mustEncodeObs(t, Observation{ObservationTimestampNanoseconds: 1000, AttestedPredecessorRetirement: []byte("attested"), PredecessorSigners: testPredecessorSigners}))) } _, err := p.StateTransition(ctx, 2, ocrtypes.AttributedQuery{}, votesOnly, kv, testBlobs) require.NoError(t, err) @@ -895,7 +871,7 @@ func Test_StateTransition_PredecessorConfigAgreementIsPerRound(t *testing.T) { attacker := [][]byte{{0xFF}, {0xFE}} forged := make([]ocrtypes.AttributedObservation, 0, 4) for i := 0; i < 4; i++ { - obs := Observation{UnixTimestampNanoseconds: 2000} + obs := Observation{ObservationTimestampNanoseconds: 2000} if i == 0 { obs.AttestedPredecessorRetirement = []byte("attested") obs.PredecessorSigners = attacker @@ -949,7 +925,7 @@ func Test_Observation_PredecessorConfigVote(t *testing.T) { t.Helper() obsBytes, err := p.Observation(ctx, 2, ocrtypes.AttributedQuery{}, kv, nil) require.NoError(t, err) - obs, err := decodeObservation(ctx, obsBytes, testBlobs, nil) + obs, err := fetchBlobsAndDecodeObservation(ctx, obsBytes, testBlobs, nil) require.NoError(t, err) return obs } @@ -1003,11 +979,11 @@ func Test_Observation_PredecessorConfigVote(t *testing.T) { // Nothing compares observation bytes today and this keeps a future path that does from being silently wrong. func Test_EncodeObservation_IsDeterministic(t *testing.T) { obs := Observation{ - UnixTimestampNanoseconds: 1234, - AttestedPredecessorRetirement: []byte("attested"), - PredecessorSigners: testPredecessorSigners, - PredecessorF: 1, - RemoveChannelIDs: map[llotypes.ChannelID]struct{}{7: {}, 1: {}, 4: {}, 2: {}, 9: {}}, + ObservationTimestampNanoseconds: 1234, + AttestedPredecessorRetirement: []byte("attested"), + PredecessorSigners: testPredecessorSigners, + PredecessorF: 1, + RemoveChannelIDs: map[llotypes.ChannelID]struct{}{7: {}, 1: {}, 4: {}, 2: {}, 9: {}}, UpdateChannelDefinitions: llotypes.ChannelDefinitions{ 5: jsonChannel(), 3: jsonChannel(), 8: jsonChannel(), 1: jsonChannel(), }, @@ -1032,11 +1008,11 @@ func Test_MarshalStreamValues_IsDeterministic(t *testing.T) { sv[id] = protocol.ToDecimal(decimal.NewFromInt(int64(id))) } - want, err := marshalStreamValues(sv) + want, err := marshalStreamValues(sv, 1) require.NoError(t, err) require.NotEmpty(t, want) for range 64 { - got, err := marshalStreamValues(sv) + got, err := marshalStreamValues(sv, 1) require.NoError(t, err) require.Equal(t, want, got, "the same stream values must marshal to the same payload") } @@ -1067,7 +1043,7 @@ func Test_Observation_RemovesOnlyTombstones(t *testing.T) { require.NoError(t, err) agree := make([]ocrtypes.AttributedObservation, 0, 4) for i := 0; i < 4; i++ { - agree = append(agree, ao(i, mustEncodeObs(t, Observation{UnixTimestampNanoseconds: 1000, UpdateChannelDefinitions: defs}))) + agree = append(agree, ao(i, mustEncodeObs(t, Observation{ObservationTimestampNanoseconds: 1000, UpdateChannelDefinitions: defs}))) } _, err = p.StateTransition(ctx, 2, ocrtypes.AttributedQuery{}, agree, kv, testBlobs) require.NoError(t, err) @@ -1076,7 +1052,7 @@ func Test_Observation_RemovesOnlyTombstones(t *testing.T) { cdc.defs = desired obsBytes, err := p.Observation(ctx, 3, ocrtypes.AttributedQuery{}, kv, nil) require.NoError(t, err) - obs, err := decodeObservation(ctx, obsBytes, testBlobs, nil) + obs, err := fetchBlobsAndDecodeObservation(ctx, obsBytes, testBlobs, nil) require.NoError(t, err) return obs.RemoveChannelIDs } @@ -1206,9 +1182,7 @@ func Test_IsReportable_MinReportIntervalDoesNotOverflow(t *testing.T) { }, } support := map[llotypes.ReportFormat]int{llotypes.ReportFormatJSON: 4} - gen, err := protocol.NewChannelCache().Load(1, func() (llotypes.ChannelDefinitions, error) { - return out.ChannelDefinitions, nil - }) + gen, err := loadDefinitions(protocol.NewChannelCache(), 1, out.ChannelDefinitions) require.NoError(t, err) optsCache := gen.Opts() @@ -1261,7 +1235,7 @@ func Test_ValidateObservation_DoesNotEvictChannelAnalysisCache(t *testing.T) { for i := 0; i < updates; i++ { cd := jsonChannel() cd.Streams[0].StreamID = llotypes.StreamID(200 + i) //nolint:gosec // small test constant - obs := Observation{UnixTimestampNanoseconds: 1_000, UpdateChannelDefinitions: llotypes.ChannelDefinitions{1: cd}} + obs := Observation{ObservationTimestampNanoseconds: 1_000, UpdateChannelDefinitions: llotypes.ChannelDefinitions{1: cd}} require.NoError(t, p.ValidateObservation(ctx, 2, ocrtypes.AttributedQuery{}, ao(i%4, mustEncodeObs(t, obs)), kv, testBlobs)) } } diff --git a/llo/dev/v31/freshness.go b/llo/dev/v31/freshness.go new file mode 100644 index 00000000..d543cf07 --- /dev/null +++ b/llo/dev/v31/freshness.go @@ -0,0 +1,269 @@ +package llo + +import ( + "math" + "sort" + "strconv" + "time" + + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/promauto" + + llotypes "github.com/smartcontractkit/chainlink-common/pkg/types/llo" + + protocol "github.com/smartcontractkit/chainlink-data-streams/llo/protocol" +) + +// Stream value freshness. +// +// Every stream value reaches the state transition through a blob gathered by +// the sender's blob pump some rounds earlier. The pump cannot judge on its own +// whether those values are still fresh: a decision taken on one node, from that +// node's clock, is invisible to its peers and withholds the node's values with +// no trace in consensus. The state transition judges instead, from replicated +// data only, so every oracle keeps the same contributions. +// +// A contribution carries the seqNr its cycle started in (CycleStartSeqNr). Two +// ages are derived from it, both from consensus data: +// +// - round age: seqNr - cycleStartSeqNr, bounded by MaxStreamValueAgeRounds. +// This is the bound the pump's local round gate used to enforce, now +// visible to every oracle. +// - time age: roundTs - agreedTs[cycleStartSeqNr], bounded by +// MaxStreamValueAgeRounds round intervals. The agreed timestamp of the +// cycle's round is a lower bound on when the values were gathered, since +// the cycle started after the previous round committed. It catches a stall: +// seqNr stands still while time passes, so round age alone would call +// values gathered before the stall one round old. It is skipped while the +// round interval is unknown, during the first rounds after a fresh state. +// +// A per stream fallback keeps liveness: when the fresh contributions cannot +// reach minContributions, the ones stale by rounds are aggregated too, as +// before this rule existed. Contributions stale by time never come back: after +// a DON wide stall every contribution is old, and re-admitting them would +// report pre-stall values under the post-stall timestamp. The stream has no +// aggregate that round instead, as it had when the pump withheld the snapshot. +// There is no persisted freshness state and no mode. +// +// The agreed timestamps come from a window the hot state carries, one entry +// per recent round. The same window yields a replicated estimate of the round +// interval, so the time bound tracks the DON's real cadence. The configured +// DeltaRound is only a floor: libocr documents it as a lower bound on the +// round interval, and it may be zero. +const ( + // SnapshotReuseRounds is how many consecutive rounds may reference one + // blob pump snapshot: gathered during round N, referenced at N+1 through + // N+SnapshotReuseRounds. The pump enforces it indirectly, through the blob + // fetch margin (see DefaultBlobLifetimeRounds). The constant sizes the + // freshness bounds to match. + SnapshotReuseRounds = 4 + // MaxStreamValueAgeRounds bounds, in rounds and in round intervals, how old + // a contribution's values may be at the round that aggregates them. A + // snapshot referenced on its last reuse round is SnapshotReuseRounds old + // before DataSource.Observe time and the window's one interval of + // imprecision are added, so two intervals of slack are left for those. + MaxStreamValueAgeRounds = SnapshotReuseRounds + 2 + // agreedTimestampWindow is how many recent agreed timestamps the hot state + // keeps. It must cover every cycleStartSeqNr a fresh contribution may carry. + agreedTimestampWindow = MaxStreamValueAgeRounds + 1 +) + +// streamContribution is one oracle's value for one stream, kept apart from the +// other oracles' values until freshness is decided. +type streamContribution struct { + value protocol.StreamValue + cycleStartSeqNr uint64 +} + +// freshnessStats is what one round's selection did, for logs and telemetry. +type freshnessStats struct { + // streamsFiltered is how many streams aggregated fresh contributions only, + // leaving at least one stale contribution out. + streamsFiltered int + // streamsFallenBack is how many streams re-admitted contributions stale by + // rounds because the fresh ones missed minContributions. + streamsFallenBack int + // contributionsStale is how many contributions were judged stale, whether + // or not the fallback let them in. + contributionsStale int + // staleByRounds, staleByTime and staleBeforeWindow split contributionsStale + // by the bound that rejected first. + staleByRounds int + staleByTime int + staleBeforeWindow int + maxStreamValueAge time.Duration + roundInterval time.Duration +} + +func (s freshnessStats) any() bool { + return s.streamsFiltered > 0 || s.streamsFallenBack > 0 || s.contributionsStale > 0 +} + +// appendAgreedTimestamp returns the window for a round whose agreed timestamp +// is ts, given the previous round's window: ts appended, oldest entries +// dropped beyond agreedTimestampWindow. The result never aliases prev. +func appendAgreedTimestamp(prev []uint64, ts uint64) []uint64 { + n := min(len(prev)+1, agreedTimestampWindow) + window := make([]uint64, 0, n) + window = append(window, prev[max(0, len(prev)+1-n):]...) + return append(window, ts) +} + +// agreedTimestampAt returns the agreed timestamp of round at from a window +// whose last entry belongs to round seqNr. ok is false when at is outside the +// window. +func agreedTimestampAt(window []uint64, seqNr, at uint64) (uint64, bool) { + if at > seqNr || seqNr-at >= uint64(len(window)) { + return 0, false + } + return window[len(window)-1-int(seqNr-at)], true +} + +// roundIntervalEstimate is the median of the nonzero intervals between the +// consecutive agreed timestamps of the window, floored at the configured +// DeltaRound. The median absorbs the one wide gap a stall leaves. Zero when +// fewer than two timestamps are known or every interval is zero, which happens +// while the agreed timestamp is held against a regressing median: the cadence +// is unknown and no time bound applies. +func roundIntervalEstimate(window []uint64, configured time.Duration) time.Duration { + intervals := make([]uint64, 0, len(window)) + for i := 1; i < len(window); i++ { + if window[i] > window[i-1] { + intervals = append(intervals, window[i]-window[i-1]) + } + } + if len(intervals) == 0 { + return 0 + } + sort.Slice(intervals, func(i, j int) bool { return intervals[i] < intervals[j] }) + median := time.Duration(min(intervals[len(intervals)/2], uint64(math.MaxInt64))) //nolint:gosec // G115 clamped + return max(median, configured) +} + +// selectFreshContributions decides, per stream, which contributions this round +// aggregates. A contribution is fresh when its round age and its time age are +// both within bound. A roundInterval of zero disables the time bound. See the +// package comment above. The fresh set is used when +// it reaches minContributions, otherwise the contributions stale by rounds are +// re-admitted. Values keep their input order, so the result does not depend on +// how the split went. +// +// Every input is replicated: seqNr, the agreed timestamps, the configured +// interval from the shared OCR config, and a cycle start seqNr the sender can +// only choose within the window. The result is therefore the same on every +// oracle. +func selectFreshContributions( + byStream map[llotypes.StreamID][]streamContribution, + seqNr uint64, + roundTs uint64, + window []uint64, + roundInterval time.Duration, + minContributions int, +) (map[llotypes.StreamID][]protocol.StreamValue, freshnessStats) { + maxAge := uint64(MaxStreamValueAgeRounds * roundInterval) //nolint:gosec // G115 positive duration + stats := freshnessStats{maxStreamValueAge: time.Duration(maxAge), roundInterval: roundInterval} //nolint:gosec // G115 bounded above + out := make(map[llotypes.StreamID][]protocol.StreamValue, len(byStream)) + + for sid, contributions := range byStream { + fresh := make([]protocol.StreamValue, 0, len(contributions)) + // fallback is every contribution the fallback may re-admit: the fresh + // ones and those stale by rounds only. Stale by time never comes back. + fallback := make([]protocol.StreamValue, 0, len(contributions)) + stale := 0 + for _, c := range contributions { + switch { + case c.cycleStartSeqNr > seqNr || seqNr-c.cycleStartSeqNr > MaxStreamValueAgeRounds: + stats.staleByRounds++ + fallback = append(fallback, c.value) + default: + cycleTs, ok := agreedTimestampAt(window, seqNr, c.cycleStartSeqNr) + if !ok { + stats.staleBeforeWindow++ + fallback = append(fallback, c.value) + } else if maxAge > 0 && roundTs > cycleTs && roundTs-cycleTs > maxAge { + stats.staleByTime++ + } else { + fresh = append(fresh, c.value) + fallback = append(fallback, c.value) + continue + } + } + stale++ + } + stats.contributionsStale += stale + switch { + case stale == 0: + out[sid] = fresh + case len(fresh) >= minContributions || len(fallback) == len(fresh): + stats.streamsFiltered++ + out[sid] = fresh + default: + stats.streamsFallenBack++ + out[sid] = fallback + } + } + return out, stats +} + +// Freshness metrics. Node-local observations with no effect on consensus. The +// fallback counter is the signal that the bounds are too tight for a DON: +// streams falling back every round aggregate stale values with no other trace. +var ( + freshnessStaleContributionsMetric = promauto.NewCounterVec(prometheus.CounterOpts{ + Namespace: "llo", + Subsystem: "freshness", + Name: "stale_contributions_total", + Help: "Stream value contributions judged stale by the state transition.", + }, []string{"donID", "reason"}) + freshnessFallbackStreamsMetric = promauto.NewCounterVec(prometheus.CounterOpts{ + Namespace: "llo", + Subsystem: "freshness", + Name: "fallback_streams_total", + Help: "Streams that re-admitted contributions stale by rounds because the fresh ones could not reach min contributions.", + }, []string{"donID"}) + freshnessRoundIntervalMetric = promauto.NewGaugeVec(prometheus.GaugeOpts{ + Namespace: "llo", + Subsystem: "freshness", + Name: "round_interval_seconds", + Help: "Round interval estimated from the agreed timestamps of recent rounds, as used for the stream value age bound.", + }, []string{"donID"}) +) + +// freshnessMetrics holds the label children for one DON, resolved once at +// plugin construction so the state transition does no label lookup per round. +type freshnessMetrics struct { + staleByRounds, staleByTime, staleBeforeWindow, fallbackStreams prometheus.Counter + roundInterval prometheus.Gauge +} + +func newFreshnessMetrics(donID uint32) *freshnessMetrics { + don := strconv.FormatUint(uint64(donID), 10) + return &freshnessMetrics{ + staleByRounds: freshnessStaleContributionsMetric.WithLabelValues(don, "rounds"), + staleByTime: freshnessStaleContributionsMetric.WithLabelValues(don, "time"), + staleBeforeWindow: freshnessStaleContributionsMetric.WithLabelValues(don, "window"), + fallbackStreams: freshnessFallbackStreamsMetric.WithLabelValues(don), + roundInterval: freshnessRoundIntervalMetric.WithLabelValues(don), + } +} + +// record exports one round's stats. A nil receiver records nothing, for +// plugins built without the factory. +func (m *freshnessMetrics) record(s freshnessStats) { + if m == nil { + return + } + if s.staleByRounds > 0 { + m.staleByRounds.Add(float64(s.staleByRounds)) + } + if s.staleByTime > 0 { + m.staleByTime.Add(float64(s.staleByTime)) + } + if s.staleBeforeWindow > 0 { + m.staleBeforeWindow.Add(float64(s.staleBeforeWindow)) + } + if s.streamsFallenBack > 0 { + m.fallbackStreams.Add(float64(s.streamsFallenBack)) + } + m.roundInterval.Set(s.roundInterval.Seconds()) +} diff --git a/llo/dev/v31/freshness_test.go b/llo/dev/v31/freshness_test.go new file mode 100644 index 00000000..3ff982da --- /dev/null +++ b/llo/dev/v31/freshness_test.go @@ -0,0 +1,345 @@ +package llo + +import ( + "testing" + "time" + + "github.com/shopspring/decimal" + "github.com/stretchr/testify/require" + + llotypes "github.com/smartcontractkit/chainlink-common/pkg/types/llo" + + "github.com/smartcontractkit/chainlink-data-streams/llo/protocol" + + "github.com/smartcontractkit/libocr/offchainreporting2plus/ocr3_1types" + ocrtypes "github.com/smartcontractkit/libocr/offchainreporting2plus/types" +) + +func Test_Freshness_Constants(t *testing.T) { + require.Greater(t, MaxStreamValueAgeRounds, SnapshotReuseRounds, "the last reuse round must still be fresh") + require.Greater(t, agreedTimestampWindow, MaxStreamValueAgeRounds, "every fresh cycle start must resolve in the window") +} + +func Test_appendAgreedTimestamp(t *testing.T) { + var window []uint64 + for ts := uint64(1); ts <= agreedTimestampWindow+2; ts++ { + prev := append([]uint64(nil), window...) + window = appendAgreedTimestamp(window, ts) + require.Equal(t, prev, prev[:len(prev):len(prev)], "the previous window is not modified") + require.LessOrEqual(t, len(window), agreedTimestampWindow) + require.Equal(t, ts, window[len(window)-1], "the newest entry is last") + for i := 1; i < len(window); i++ { + require.Equal(t, window[i-1]+1, window[i], "entries are consecutive") + } + } + require.Len(t, window, agreedTimestampWindow) +} + +func Test_agreedTimestampAt(t *testing.T) { + // Window written by round 10: rounds 8, 9, 10. + window := []uint64{800, 900, 1000} + for at, want := range map[uint64]uint64{10: 1000, 9: 900, 8: 800} { + got, ok := agreedTimestampAt(window, 10, at) + require.True(t, ok, "round %d", at) + require.Equal(t, want, got, "round %d", at) + } + _, ok := agreedTimestampAt(window, 10, 7) + require.False(t, ok, "before the window") + _, ok = agreedTimestampAt(window, 10, 11) + require.False(t, ok, "after the window") + _, ok = agreedTimestampAt(nil, 10, 10) + require.False(t, ok, "empty window") +} + +func Test_roundIntervalEstimate(t *testing.T) { + sec := uint64(time.Second) + t.Run("median of the intervals", func(t *testing.T) { + window := []uint64{0, sec, 2 * sec, 2*sec + sec/2, 4 * sec} + require.Equal(t, time.Second, roundIntervalEstimate(window, time.Second)) + }) + t.Run("zero intervals are skipped", func(t *testing.T) { + window := []uint64{sec, sec, sec, 3 * sec} + require.Equal(t, 2*time.Second, roundIntervalEstimate(window, 0)) + }) + t.Run("floored at the configured interval", func(t *testing.T) { + window := []uint64{0, sec / 4, sec / 2} + require.Equal(t, time.Second, roundIntervalEstimate(window, time.Second)) + }) + t.Run("not capped by the configured interval", func(t *testing.T) { + // DeltaRound is a lower bound on the round interval, not its cadence. + window := []uint64{0, 5 * sec, 10 * sec} + require.Equal(t, 5*time.Second, roundIntervalEstimate(window, 250*time.Millisecond)) + }) + t.Run("a stall does not move the median", func(t *testing.T) { + window := []uint64{0, sec, 2 * sec, 3 * sec, 63 * sec} + require.Equal(t, time.Second, roundIntervalEstimate(window, 0)) + }) + t.Run("unknown while fewer than two timestamps advance", func(t *testing.T) { + require.Equal(t, time.Duration(0), roundIntervalEstimate(nil, 0)) + require.Equal(t, time.Duration(0), roundIntervalEstimate([]uint64{sec}, 0)) + require.Equal(t, time.Duration(0), roundIntervalEstimate([]uint64{sec, sec, sec}, 0)) + require.Equal(t, time.Duration(0), roundIntervalEstimate(nil, time.Second), "the floor applies to a measurement only") + }) +} + +func Test_selectFreshContributions(t *testing.T) { + val := func(i int64) protocol.StreamValue { return protocol.ToDecimal(decimal.NewFromInt(i)) } + contribution := func(i int64, cycleStart uint64) streamContribution { + return streamContribution{value: val(i), cycleStartSeqNr: cycleStart} + } + values := func(in []protocol.StreamValue) []int64 { + out := make([]int64, 0, len(in)) + for _, sv := range in { + out = append(out, sv.(*protocol.Decimal).Decimal().IntPart()) + } + return out + } + + const seqNr = uint64(20) + const interval = time.Second + sec := uint64(time.Second) + // Window written by round 20, one second apart: rounds 13 to 20. + window := make([]uint64, 0, agreedTimestampWindow) + for i := range agreedTimestampWindow { + window = append(window, uint64(100+i)*sec) + } + roundTs := window[len(window)-1] + require.Len(t, window, agreedTimestampWindow) + + t.Run("all fresh", func(t *testing.T) { + in := map[llotypes.StreamID][]streamContribution{1: {contribution(3, 20), contribution(1, 19), contribution(2, 20-MaxStreamValueAgeRounds)}} + out, stats := selectFreshContributions(in, seqNr, roundTs, window, interval, 3) + require.Equal(t, []int64{3, 1, 2}, values(out[1]), "input order is kept") + require.False(t, stats.any()) + }) + + t.Run("stale by rounds is left out when enough are fresh", func(t *testing.T) { + in := map[llotypes.StreamID][]streamContribution{1: {contribution(1, 20), contribution(9, 20-MaxStreamValueAgeRounds-1), contribution(2, 20), contribution(3, 19)}} + out, stats := selectFreshContributions(in, seqNr, roundTs, window, interval, 3) + require.Equal(t, []int64{1, 2, 3}, values(out[1])) + require.Equal(t, 1, stats.streamsFiltered) + require.Equal(t, 0, stats.streamsFallenBack) + require.Equal(t, 1, stats.contributionsStale) + require.Equal(t, 1, stats.staleByRounds) + }) + + t.Run("stale by time", func(t *testing.T) { + // The cycle's round is in the window and recent in rounds, but this + // round's agreed timestamp jumped far ahead of it: a stall. The window + // ends with this round's timestamp. + stalled := roundTs + uint64(MaxStreamValueAgeRounds)*sec + 1 + stalledWindow := append(append([]uint64(nil), window[:len(window)-1]...), stalled) + in := map[llotypes.StreamID][]streamContribution{1: {contribution(1, 20), contribution(2, 20), contribution(3, 20), contribution(9, 19)}} + out, stats := selectFreshContributions(in, seqNr, stalled, stalledWindow, interval, 3) + require.Equal(t, []int64{1, 2, 3}, values(out[1]), "this round's own cycle has age zero and stays") + require.Equal(t, 1, stats.staleByTime) + }) + + t.Run("no time bound while the interval is unknown", func(t *testing.T) { + stalled := roundTs + uint64(MaxStreamValueAgeRounds)*sec + 1 + stalledWindow := append(append([]uint64(nil), window[:len(window)-1]...), stalled) + in := map[llotypes.StreamID][]streamContribution{1: {contribution(1, 20), contribution(2, 20), contribution(3, 20), contribution(9, 19)}} + _, stats := selectFreshContributions(in, seqNr, stalled, stalledWindow, 0, 3) + require.False(t, stats.any()) + }) + + t.Run("exactly at the bound is fresh", func(t *testing.T) { + atBound := roundTs + uint64(MaxStreamValueAgeRounds)*sec + in := map[llotypes.StreamID][]streamContribution{1: {contribution(1, 20), contribution(2, 20), contribution(3, 20), contribution(9, 20)}} + _, stats := selectFreshContributions(in, seqNr, atBound, window, interval, 3) + require.False(t, stats.any()) + }) + + t.Run("before the window", func(t *testing.T) { + short := window[len(window)-2:] // rounds 19 and 20 only + in := map[llotypes.StreamID][]streamContribution{1: {contribution(1, 20), contribution(2, 20), contribution(3, 20), contribution(9, 18)}} + out, stats := selectFreshContributions(in, seqNr, roundTs, short, interval, 3) + require.Equal(t, []int64{1, 2, 3}, values(out[1])) + require.Equal(t, 1, stats.staleBeforeWindow) + }) + + t.Run("future cycle start is stale", func(t *testing.T) { + in := map[llotypes.StreamID][]streamContribution{1: {contribution(1, 20), contribution(2, 20), contribution(3, 20), contribution(9, 21)}} + out, stats := selectFreshContributions(in, seqNr, roundTs, window, interval, 3) + require.Equal(t, []int64{1, 2, 3}, values(out[1])) + require.Equal(t, 1, stats.staleByRounds) + }) + + t.Run("falls back to contributions stale by rounds below min contributions", func(t *testing.T) { + in := map[llotypes.StreamID][]streamContribution{1: {contribution(1, 20), contribution(9, 1), contribution(2, 20)}} + out, stats := selectFreshContributions(in, seqNr, roundTs, window, interval, 3) + require.Equal(t, []int64{1, 9, 2}, values(out[1]), "every contribution, in input order") + require.Equal(t, 0, stats.streamsFiltered) + require.Equal(t, 1, stats.streamsFallenBack) + require.Equal(t, 1, stats.contributionsStale) + }) + + t.Run("stale by time is never re-admitted", func(t *testing.T) { + // A stall: every contribution comes from before the timestamp jump. + stalled := roundTs + uint64(MaxStreamValueAgeRounds)*sec + 1 + stalledWindow := append(append([]uint64(nil), window[:len(window)-1]...), stalled) + in := map[llotypes.StreamID][]streamContribution{1: {contribution(1, 19), contribution(2, 19), contribution(3, 19), contribution(4, 18)}} + out, stats := selectFreshContributions(in, seqNr, stalled, stalledWindow, interval, 3) + require.Empty(t, out[1], "no fresh contribution and nothing to fall back to") + require.Equal(t, 1, stats.streamsFiltered) + require.Equal(t, 0, stats.streamsFallenBack) + require.Equal(t, 4, stats.staleByTime) + }) + + t.Run("per stream", func(t *testing.T) { + in := map[llotypes.StreamID][]streamContribution{ + 1: {contribution(1, 20), contribution(2, 20), contribution(3, 20), contribution(9, 1)}, + 2: {contribution(1, 20), contribution(9, 1), contribution(8, 1)}, + 3: {contribution(1, 20), contribution(2, 20)}, + } + out, stats := selectFreshContributions(in, seqNr, roundTs, window, interval, 3) + require.Equal(t, []int64{1, 2, 3}, values(out[1])) + require.Equal(t, []int64{1, 9, 8}, values(out[2])) + require.Equal(t, []int64{1, 2}, values(out[3])) + require.Equal(t, 1, stats.streamsFiltered) + require.Equal(t, 1, stats.streamsFallenBack) + require.Equal(t, 3, stats.contributionsStale) + }) +} + +// Test_fetchBlobsAndDecodeObservation_CycleStartSeqNr covers the deterministic blob checks: +// a payload without a cycle start, handles from different cycles, and a cycle +// start ahead of the round. +func Test_fetchBlobsAndDecodeObservation_CycleStartSeqNr(t *testing.T) { + ctx := t.Context() + bc := newFakeBroadcaster() + sv := protocol.StreamValues{100: protocol.ToDecimal(decimal.NewFromInt(1))} + handleFor := func(cycleStart uint64) []byte { + payload, err := marshalStreamValues(sv, cycleStart) + require.NoError(t, err) + handle, err := bc.BroadcastBlob(ctx, payload, ocr3_1types.BlobExpirationHintSequenceNumber{SeqNr: 100}) + require.NoError(t, err) + handleBytes, err := handle.MarshalBinary() + require.NoError(t, err) + return handleBytes + } + + t.Run("round trip", func(t *testing.T) { + enc, err := encodeObservation(Observation{ObservationTimestampNanoseconds: 1}, [][]byte{handleFor(7)}) + require.NoError(t, err) + memo := newBlobPayloadCache().round(9) + decoded, err := fetchBlobsAndDecodeObservation(ctx, enc, bc, memo) + require.NoError(t, err) + require.EqualValues(t, 7, decoded.CycleStartSeqNr) + // A memo hit carries the same cycle start. + decoded, err = fetchBlobsAndDecodeObservation(ctx, enc, bc, memo) + require.NoError(t, err) + require.EqualValues(t, 7, decoded.CycleStartSeqNr) + }) + + t.Run("no stream values no cycle start", func(t *testing.T) { + enc, err := encodeObservation(Observation{ObservationTimestampNanoseconds: 1}, nil) + require.NoError(t, err) + decoded, err := fetchBlobsAndDecodeObservation(ctx, enc, bc, nil) + require.NoError(t, err) + require.Zero(t, decoded.CycleStartSeqNr) + }) + + t.Run("zero cycle start is malformed", func(t *testing.T) { + enc, err := encodeObservation(Observation{ObservationTimestampNanoseconds: 1}, [][]byte{handleFor(0)}) + require.NoError(t, err) + _, err = fetchBlobsAndDecodeObservation(ctx, enc, bc, nil) + require.ErrorContains(t, err, "carries no cycle start seqNr") + }) + + t.Run("handles from different cycles", func(t *testing.T) { + enc, err := encodeObservation(Observation{ObservationTimestampNanoseconds: 1}, [][]byte{handleFor(7), handleFor(8)}) + require.NoError(t, err) + _, err = fetchBlobsAndDecodeObservation(ctx, enc, bc, nil) + require.ErrorContains(t, err, "blobs from different cycles") + }) + + t.Run("cycle start ahead of the round", func(t *testing.T) { + p := testPlugin(t) + enc, err := encodeObservation(Observation{ObservationTimestampNanoseconds: 1, SupportedReportFormats: testSupportedReportFormats}, [][]byte{handleFor(7)}) + require.NoError(t, err) + _, err = p.fetchBlobsDecodeAndValidateObservation(ctx, 6, ao(0, enc), bc) + require.ErrorContains(t, err, "gathered for a future round") + _, err = p.fetchBlobsDecodeAndValidateObservation(ctx, 7, ao(0, enc), bc) + require.NoError(t, err) + }) +} + +// Test_StateTransition_Freshness drives the rule through whole rounds: a +// lagging oracle's values are left out while enough fresh ones remain, every +// contribution is aggregated when they do not, and a stall rejects the values +// gathered before it for one round. +func Test_StateTransition_Freshness(t *testing.T) { + ctx := t.Context() + p := testPlugin(t) + p.MinRoundInterval = time.Second + kv := newMemKV() + + const sec = uint64(time.Second) + median := func(t *testing.T, precBytes ocr3_1types.ReportsPlusPrecursor) int64 { + t.Helper() + prec, err := decodePrecursor(precBytes) + require.NoError(t, err) + agg, ok := prec.StreamAggregates[100][llotypes.AggregatorMedian] + require.True(t, ok, "stream 100 must aggregate") + return agg.(*protocol.Decimal).Decimal().IntPart() + } + obs := func(i int, ts uint64, value int64, cycleStart uint64) ocrtypes.AttributedObservation { + return ao(i, mustEncodeObs(t, Observation{ + ObservationTimestampNanoseconds: ts, + StreamValues: protocol.StreamValues{100: protocol.ToDecimal(decimal.NewFromInt(value))}, + CycleStartSeqNr: cycleStart, + })) + } + + // Rounds 1 to 3: bootstrap and install the channel, one second apart. + _, err := p.StateTransition(ctx, 1, ocrtypes.AttributedQuery{}, emptyRound(), kv, testBlobs) + require.NoError(t, err) + _, err = p.StateTransition(ctx, 2, ocrtypes.AttributedQuery{}, addChannelRound(t, 2*sec, 1, jsonChannel()), kv, testBlobs) + require.NoError(t, err) + _, err = p.StateTransition(ctx, 3, ocrtypes.AttributedQuery{}, addChannelRound(t, 3*sec, 1, jsonChannel()), kv, testBlobs) + require.NoError(t, err) + + // Round 4: three fresh contributions and one from a cycle that started + // before the window. Without the rule the median of {10, 12, 14, 1000} is + // 14. With it, the median of the fresh three is 12. + prec, err := p.StateTransition(ctx, 4, ocrtypes.AttributedQuery{}, []ocrtypes.AttributedObservation{ + obs(0, 4*sec, 10, 4), obs(1, 4*sec, 12, 3), obs(2, 4*sec, 14, 4), obs(3, 4*sec, 1000, 1), + }, kv, testBlobs) + require.NoError(t, err) + require.EqualValues(t, 12, median(t, prec)) + + // Round 5: only two fresh contributions, below the floor of three, so + // every contribution is aggregated: the median of {10, 14, 1000} is 14. + prec, err = p.StateTransition(ctx, 5, ocrtypes.AttributedQuery{}, []ocrtypes.AttributedObservation{ + obs(0, 5*sec, 10, 5), obs(1, 5*sec, 14, 5), obs(3, 5*sec, 1000, 1), + }, kv, testBlobs) + require.NoError(t, err) + require.EqualValues(t, 14, median(t, prec)) + + // Round 6 after a stall: the agreed timestamp jumps a minute, and every + // contribution comes from a cycle started in round 5, before the stall. + // All are stale by time and none is re-admitted: the stream has no + // aggregate this round. + prec, err = p.StateTransition(ctx, 6, ocrtypes.AttributedQuery{}, []ocrtypes.AttributedObservation{ + obs(0, 65*sec, 10, 5), obs(1, 65*sec, 12, 5), obs(2, 65*sec, 1000, 5), obs(3, 65*sec, 1000, 5), + }, kv, testBlobs) + require.NoError(t, err) + prec6, err := decodePrecursor(prec) + require.NoError(t, err) + _, aggregated := prec6.StreamAggregates[100][llotypes.AggregatorMedian] + require.False(t, aggregated, "pre-stall values must not be reported under the post-stall timestamp") + + // Round 7: cycles started after the stall are fresh again, and the one + // still carrying round 5 is left out. + prec, err = p.StateTransition(ctx, 7, ocrtypes.AttributedQuery{}, []ocrtypes.AttributedObservation{ + obs(0, 66*sec, 10, 7), obs(1, 66*sec, 12, 6), obs(2, 66*sec, 14, 7), obs(3, 66*sec, 1000, 5), + }, kv, testBlobs) + require.NoError(t, err) + require.EqualValues(t, 12, median(t, prec)) + + // The window persisted with the round. + state, err := loadKVState(kv, p.ChannelCache, p.Logger) + require.NoError(t, err) + require.Equal(t, []uint64{2 * sec, 3 * sec, 4 * sec, 5 * sec, 65 * sec, 66 * sec}, state.recentAgreedTimestamps) +} diff --git a/llo/dev/v31/golden_test.go b/llo/dev/v31/golden_test.go index 9084cd32..d237ec5f 100644 --- a/llo/dev/v31/golden_test.go +++ b/llo/dev/v31/golden_test.go @@ -81,13 +81,18 @@ func Test_Golden_Precursor(t *testing.T) { for _, tc := range []struct { name string p precursor + + codec byte }{ - {"precursor_empty.bin", precursor{}}, - {"precursor_full.bin", goldenPrecursor()}, + {"precursor_empty.bin", precursor{}, payloadCodecRaw}, + // Also freezes the zstd bitstream: a compress library bump that changes + // it would split oracles on the precursor digest. + {"precursor_full.bin", goldenPrecursor(), payloadCodecZstd}, } { t.Run(tc.name, func(t *testing.T) { b, err := encodePrecursor(tc.p) require.NoError(t, err) + require.Equal(t, tc.codec, b[0]) goldenBytes(t, tc.name, b) // The golden bytes must also decode back to the same projection, so @@ -95,16 +100,20 @@ func Test_Golden_Precursor(t *testing.T) { // regenerated file. want, err := os.ReadFile(filepath.Join(goldenDir, tc.name)) require.NoError(t, err) - got, err := decodePrecursor(want) - require.NoError(t, err) - require.Equal(t, normalizePrecursor(tc.p), got) + require.Equal(t, normalizePrecursor(t, tc.p), decodeResolvedPrecursor(t, want)) }) } } // normalizePrecursor fills in the empty maps decodePrecursor always returns, so // that a nil-map input compares equal to its decoded form. -func normalizePrecursor(p precursor) precursor { +func normalizePrecursor(t *testing.T, p precursor) precursor { + t.Helper() + if p.ChannelState == nil && len(p.ChannelDefinitions) > 0 { + b, err := encodeChannelState(p.ChannelDefinitions) + require.NoError(t, err) + p.ChannelState = b + } if p.ChannelDefinitions == nil { p.ChannelDefinitions = llotypes.ChannelDefinitions{} } @@ -117,6 +126,17 @@ func normalizePrecursor(p precursor) precursor { return p } +// decodeResolvedPrecursor decodes b and resolves its channel definitions with +// a fresh cache, giving the precursor Reports works from. +func decodeResolvedPrecursor(t *testing.T, b []byte) precursor { + t.Helper() + p, err := decodePrecursor(b) + require.NoError(t, err) + _, err = p.definitions(protocol.NewChannelCache()) + require.NoError(t, err) + return p +} + func Test_Golden_KVRecords(t *testing.T) { p := goldenPrecursor() kv := newMemKV() @@ -135,6 +155,7 @@ func Test_Golden_KVRecords(t *testing.T) { }}}, 100: {llotypes.AggregatorMedian: {ObservedAtNanoseconds: 1, StreamValue: protocol.ToDecimal(decimal.NewFromInt(123))}}, }, + nil, logger.Test(t), )) // Out-of-order oracles and formats, so the sorting the writer does is part @@ -247,6 +268,45 @@ func Test_Golden_KVHistoryRecords(t *testing.T) { require.Len(t, chunk.Records(), 3) } +// Test_Golden_KVHistoryChunkCompressed freezes a full ring slot of realistic +// prices. Unlike the smaller golden records it compresses, so it is what +// catches a zstd bump that changes the bitstream of KV records. +func Test_Golden_KVHistoryChunkCompressed(t *testing.T) { + const ( + sid = llotypes.StreamID(100) + agg = llotypes.AggregatorMedian + ) + + kv := newMemKV() + var set protocol.RingWriteSet + for i := range protocol.MaxHistoryChunkRecords { + w := readHistory(t, kv, sid, agg) + if w == nil { + w = protocol.NewRingWindow(nil) + } + _, err := w.SetRequiredCount(protocol.MaxHistoryChunkRecords) + require.NoError(t, err) + price := decimal.RequireFromString("3412.57").Add(decimal.New(int64(i%7), -2)) + appended, err := w.Append(1_700_000_000_000_000_000+uint64(i)*1_000_000_000, protocol.ToDecimal(price)) + require.NoError(t, err) + require.True(t, appended) + + set = w.WriteSet() + _, err = writeHistoryHeader(kv, sid, agg, set.Header) + require.NoError(t, err) + _, err = writeHistoryChunk(kv, sid, agg, set.Chunk) + require.NoError(t, err) + } + + b := kv.m[string(historyChunkKey(sid, agg, set.Chunk.Slot()))] + require.Equal(t, payloadCodecZstd, b[0], "a full chunk must compress, or this golden freezes nothing") + goldenBytes(t, "kv_history_chunk_full.bin", b) + + chunk, err := readHistoryChunk(kv, sid, agg, set.Chunk.Slot()) + require.NoError(t, err) + require.Len(t, chunk.Records(), protocol.MaxHistoryChunkRecords) +} + // Test_Golden_KVKeys freezes the key layout. Keys are part of the replicated // schema too: renaming one silently orphans the stored value on every node. func Test_Golden_KVKeys(t *testing.T) { diff --git a/llo/dev/v31/handover_test.go b/llo/dev/v31/handover_test.go index e122b93b..0a210848 100644 --- a/llo/dev/v31/handover_test.go +++ b/llo/dev/v31/handover_test.go @@ -412,13 +412,13 @@ func Test_Handover_V30ToV31(t *testing.T) { stagingTS := ts stagingTS += handoverTickNanos newInst.round(Observation{ - UnixTimestampNanoseconds: stagingTS, - UpdateChannelDefinitions: llotypes.ChannelDefinitions{handoverChannelID: handoverChannel()}, - StreamValues: handoverStreamValues(), + ObservationTimestampNanoseconds: stagingTS, + UpdateChannelDefinitions: llotypes.ChannelDefinitions{handoverChannelID: handoverChannel()}, + StreamValues: handoverStreamValues(), }) for range 2 { stagingTS += handoverTickNanos - newInst.round(Observation{UnixTimestampNanoseconds: stagingTS, StreamValues: handoverStreamValues()}) + newInst.round(Observation{ObservationTimestampNanoseconds: stagingTS, StreamValues: handoverStreamValues()}) } for _, r := range newInst.reports { require.True(t, r.specimen, "staging instance must only emit specimen reports") @@ -451,11 +451,11 @@ func Test_Handover_V30ToV31(t *testing.T) { stagingTS += handoverTickNanos newInst.round(Observation{ - UnixTimestampNanoseconds: stagingTS, - AttestedPredecessorRetirement: attestedBytes, - PredecessorSigners: handoverPredecessorSigners, - PredecessorF: 1, - StreamValues: handoverStreamValues(), + ObservationTimestampNanoseconds: stagingTS, + AttestedPredecessorRetirement: attestedBytes, + PredecessorSigners: handoverPredecessorSigners, + PredecessorF: 1, + StreamValues: handoverStreamValues(), }) require.Equal(t, protocol.LifeCycleStageProduction, newInst.lifeCycleStage()) @@ -466,7 +466,7 @@ func Test_Handover_V30ToV31(t *testing.T) { // predecessor's last observation timestamp. for range 3 { stagingTS += handoverTickNanos - newInst.round(Observation{UnixTimestampNanoseconds: stagingTS, StreamValues: handoverStreamValues()}) + newInst.round(Observation{ObservationTimestampNanoseconds: stagingTS, StreamValues: handoverStreamValues()}) } all := append(append([]emittedReport{}, old.reports...), newInst.reports...) @@ -489,13 +489,13 @@ func Test_Handover_V31ToV30(t *testing.T) { ts += handoverTickNanos old.round(Observation{ - UnixTimestampNanoseconds: ts, - UpdateChannelDefinitions: llotypes.ChannelDefinitions{handoverChannelID: handoverChannel()}, - StreamValues: handoverStreamValues(), + ObservationTimestampNanoseconds: ts, + UpdateChannelDefinitions: llotypes.ChannelDefinitions{handoverChannelID: handoverChannel()}, + StreamValues: handoverStreamValues(), }) for range 3 { ts += handoverTickNanos - old.round(Observation{UnixTimestampNanoseconds: ts, StreamValues: handoverStreamValues()}) + old.round(Observation{ObservationTimestampNanoseconds: ts, StreamValues: handoverStreamValues()}) } require.NotEmpty(t, old.reports, "v3.1 must be emitting reports before the handover") for _, r := range old.reports { @@ -526,7 +526,7 @@ func Test_Handover_V31ToV30(t *testing.T) { // --- retire v3.1 --- old.p.ShouldRetireCache = &mockShouldRetireCache{retire: true} ts += handoverTickNanos - old.round(Observation{UnixTimestampNanoseconds: ts, ShouldRetire: true, StreamValues: handoverStreamValues()}) + old.round(Observation{ObservationTimestampNanoseconds: ts, ShouldRetire: true, StreamValues: handoverStreamValues()}) require.Equal(t, protocol.LifeCycleStageRetired, old.lifeCycleStage()) require.NotEmpty(t, old.retirementRR, "retired v3.1 instance must emit a retirement report") @@ -622,8 +622,8 @@ func Test_Handover_V30ToV31_RejectsBadSignatures(t *testing.T) { newInst.round(Observation{}) require.Equal(t, protocol.LifeCycleStageStaging, newInst.lifeCycleStage()) - bad := Observation{UnixTimestampNanoseconds: handoverTickNanos, AttestedPredecessorRetirement: tc.attested, PredecessorSigners: handoverPredecessorSigners, PredecessorF: 1} - clean := Observation{UnixTimestampNanoseconds: handoverTickNanos} + bad := Observation{ObservationTimestampNanoseconds: handoverTickNanos, AttestedPredecessorRetirement: tc.attested, PredecessorSigners: handoverPredecessorSigners, PredecessorF: 1} + clean := Observation{ObservationTimestampNanoseconds: handoverTickNanos} require.NoError(t, newInst.tryRound(bad, bad, clean, clean)) require.Equal(t, protocol.LifeCycleStageStaging, newInst.lifeCycleStage(), @@ -657,11 +657,11 @@ func Test_Handover_BadRetirementDoesNotStallRound(t *testing.T) { // The round completes and the rest of the observation still counts: the // channel vote carried alongside the unverifiable report takes effect. bad := Observation{ - UnixTimestampNanoseconds: handoverTickNanos, - AttestedPredecessorRetirement: attest(t, raw), - PredecessorSigners: handoverPredecessorSigners, - PredecessorF: 1, - UpdateChannelDefinitions: llotypes.ChannelDefinitions{handoverChannelID: handoverChannel()}, + ObservationTimestampNanoseconds: handoverTickNanos, + AttestedPredecessorRetirement: attest(t, raw), + PredecessorSigners: handoverPredecessorSigners, + PredecessorF: 1, + UpdateChannelDefinitions: llotypes.ChannelDefinitions{handoverChannelID: handoverChannel()}, } require.NoError(t, newInst.tryRound(bad, bad, bad, bad)) require.Equal(t, protocol.LifeCycleStageStaging, newInst.lifeCycleStage()) @@ -671,10 +671,10 @@ func Test_Handover_BadRetirementDoesNotStallRound(t *testing.T) { // Once the report verifies, the very next round promotes. newInst.p.PredecessorRetirementReportCache = newPredecessorCache(t, attest(t, raw), true) newInst.round(Observation{ - UnixTimestampNanoseconds: 2 * handoverTickNanos, - AttestedPredecessorRetirement: attest(t, raw), - PredecessorSigners: handoverPredecessorSigners, - PredecessorF: 1, + ObservationTimestampNanoseconds: 2 * handoverTickNanos, + AttestedPredecessorRetirement: attest(t, raw), + PredecessorSigners: handoverPredecessorSigners, + PredecessorF: 1, }) require.Equal(t, protocol.LifeCycleStageProduction, newInst.lifeCycleStage()) require.Equal(t, uint64(500), newInst.validAfter()[handoverChannelID]) @@ -697,7 +697,7 @@ func Test_Handover_RejectsIncompatibleProtocolVersion(t *testing.T) { newInst.round(Observation{}) require.Equal(t, protocol.LifeCycleStageStaging, newInst.lifeCycleStage()) - obs := Observation{UnixTimestampNanoseconds: handoverTickNanos, AttestedPredecessorRetirement: attest(t, raw), PredecessorSigners: handoverPredecessorSigners, PredecessorF: 1} + obs := Observation{ObservationTimestampNanoseconds: handoverTickNanos, AttestedPredecessorRetirement: attest(t, raw), PredecessorSigners: handoverPredecessorSigners, PredecessorF: 1} require.NoError(t, newInst.tryRound(obs, obs, obs, obs)) require.Equal(t, protocol.LifeCycleStageStaging, newInst.lifeCycleStage(), "instance must stay in staging on a retirement report from an unsupported protocol version") @@ -771,32 +771,32 @@ func Test_Handover_RetirementReportFrozenAfterRetirement(t *testing.T) { old := newV31Instance(t, ocrtypes.ConfigDigest{0x31}, nil, nil) old.round(Observation{}) // bootstrap -> production ts := handoverTickNanos * 10 - old.round(Observation{UnixTimestampNanoseconds: ts, UpdateChannelDefinitions: handoverBackfillDefs(), StreamValues: handoverStreamValues()}) + old.round(Observation{ObservationTimestampNanoseconds: ts, UpdateChannelDefinitions: handoverBackfillDefs(), StreamValues: handoverStreamValues()}) for range 2 { ts += handoverTickNanos - old.round(Observation{UnixTimestampNanoseconds: ts, StreamValues: handoverStreamValues()}) + old.round(Observation{ObservationTimestampNanoseconds: ts, StreamValues: handoverStreamValues()}) } // Agreed in the round before retiring, so it takes effect on the // retiring round itself. ts += handoverTickNanos old.round(Observation{ - UnixTimestampNanoseconds: ts, - UpdateChannelDefinitions: llotypes.ChannelDefinitions{pendingChannelID: handoverChannel()}, - StreamValues: handoverStreamValues(), + ObservationTimestampNanoseconds: ts, + UpdateChannelDefinitions: llotypes.ChannelDefinitions{pendingChannelID: handoverChannel()}, + StreamValues: handoverStreamValues(), }) ts += handoverTickNanos - old.round(Observation{UnixTimestampNanoseconds: ts, ShouldRetire: true, StreamValues: handoverStreamValues()}) + old.round(Observation{ObservationTimestampNanoseconds: ts, ShouldRetire: true, StreamValues: handoverStreamValues()}) require.Equal(t, protocol.LifeCycleStageRetired, old.lifeCycleStage()) requireFrozen(t, old.retirementRR, func() []byte { ts += handoverTickNanos old.retirementRR = nil old.round(Observation{ - UnixTimestampNanoseconds: ts, - ShouldRetire: true, - UpdateChannelDefinitions: retiredUpdate, - RemoveChannelIDs: retiredRemove, - StreamValues: handoverStreamValues(), + ObservationTimestampNanoseconds: ts, + ShouldRetire: true, + UpdateChannelDefinitions: retiredUpdate, + RemoveChannelIDs: retiredRemove, + StreamValues: handoverStreamValues(), }) return old.retirementRR }) @@ -819,7 +819,7 @@ func Test_Handover_DivergentRetirementsRefusePromotion(t *testing.T) { return raw } withRetirement := func(attested []byte) Observation { - return Observation{UnixTimestampNanoseconds: handoverTickNanos, AttestedPredecessorRetirement: attested, PredecessorSigners: handoverPredecessorSigners, PredecessorF: 1} + return Observation{ObservationTimestampNanoseconds: handoverTickNanos, AttestedPredecessorRetirement: attested, PredecessorSigners: handoverPredecessorSigners, PredecessorF: 1} } t.Run("different watermarks", func(t *testing.T) { @@ -889,15 +889,15 @@ func Test_Handover_StagingSkipsBackfill(t *testing.T) { inst.round(Observation{}) // bootstrap ts := handoverTickNanos * 10 inst.round(Observation{ - UnixTimestampNanoseconds: ts, - UpdateChannelDefinitions: handoverBackfillDefs(), - StreamValues: handoverStreamValues(), + ObservationTimestampNanoseconds: ts, + UpdateChannelDefinitions: handoverBackfillDefs(), + StreamValues: handoverStreamValues(), }) // Definitions are deferred one round, so give it several rounds in // effect: enough for the backfill to emit all three observations. for range 5 { ts += handoverTickNanos - inst.round(Observation{UnixTimestampNanoseconds: ts, StreamValues: handoverStreamValues()}) + inst.round(Observation{ObservationTimestampNanoseconds: ts, StreamValues: handoverStreamValues()}) } return inst } @@ -971,13 +971,13 @@ func Test_Handover_PromotionResumesBackfillAtPredecessorWatermark(t *testing.T) stagingTS := ts stagingTS += handoverTickNanos newInst.round(Observation{ - UnixTimestampNanoseconds: stagingTS, - UpdateChannelDefinitions: handoverBackfillDefs(), - StreamValues: handoverStreamValues(), + ObservationTimestampNanoseconds: stagingTS, + UpdateChannelDefinitions: handoverBackfillDefs(), + StreamValues: handoverStreamValues(), }) for range 3 { stagingTS += handoverTickNanos - newInst.round(Observation{UnixTimestampNanoseconds: stagingTS, StreamValues: handoverStreamValues()}) + newInst.round(Observation{ObservationTimestampNanoseconds: stagingTS, StreamValues: handoverStreamValues()}) } require.Equal(t, uint64(0), newInst.validAfter()[handoverBackfillChannelID], "the staging instance must not have advanced the backfill watermark") @@ -989,11 +989,11 @@ func Test_Handover_PromotionResumesBackfillAtPredecessorWatermark(t *testing.T) stagingTS += handoverTickNanos newInst.round(Observation{ - UnixTimestampNanoseconds: stagingTS, - AttestedPredecessorRetirement: attestedBytes, - PredecessorSigners: handoverPredecessorSigners, - PredecessorF: 1, - StreamValues: handoverStreamValues(), + ObservationTimestampNanoseconds: stagingTS, + AttestedPredecessorRetirement: attestedBytes, + PredecessorSigners: handoverPredecessorSigners, + PredecessorF: 1, + StreamValues: handoverStreamValues(), }) require.Equal(t, protocol.LifeCycleStageProduction, newInst.lifeCycleStage()) @@ -1036,12 +1036,12 @@ func Test_Handover_BackfillAbsentFromRetirementReportStartsAtZero(t *testing.T) newInst.round(Observation{}) stagingTS := ts + handoverTickNanos newInst.round(Observation{ - UnixTimestampNanoseconds: stagingTS, - UpdateChannelDefinitions: handoverBackfillDefs(), - StreamValues: handoverStreamValues(), + ObservationTimestampNanoseconds: stagingTS, + UpdateChannelDefinitions: handoverBackfillDefs(), + StreamValues: handoverStreamValues(), }) stagingTS += handoverTickNanos - newInst.round(Observation{UnixTimestampNanoseconds: stagingTS, StreamValues: handoverStreamValues()}) + newInst.round(Observation{ObservationTimestampNanoseconds: stagingTS, StreamValues: handoverStreamValues()}) promoted := newPredecessorCache(t, attest(t, old.retirementRR), true) newInst.p.PredecessorRetirementReportCache = promoted @@ -1050,11 +1050,11 @@ func Test_Handover_BackfillAbsentFromRetirementReportStartsAtZero(t *testing.T) stagingTS += handoverTickNanos newInst.round(Observation{ - UnixTimestampNanoseconds: stagingTS, - AttestedPredecessorRetirement: attestedBytes, - PredecessorSigners: handoverPredecessorSigners, - PredecessorF: 1, - StreamValues: handoverStreamValues(), + ObservationTimestampNanoseconds: stagingTS, + AttestedPredecessorRetirement: attestedBytes, + PredecessorSigners: handoverPredecessorSigners, + PredecessorF: 1, + StreamValues: handoverStreamValues(), }) require.Equal(t, protocol.LifeCycleStageProduction, newInst.lifeCycleStage()) diff --git a/llo/dev/v31/history_flow_test.go b/llo/dev/v31/history_flow_test.go index 133d21a0..706420a9 100644 --- a/llo/dev/v31/history_flow_test.go +++ b/llo/dev/v31/history_flow_test.go @@ -32,8 +32,8 @@ func historyExprChannel(expression string) llotypes.ChannelDefinition { func valueRound(t *testing.T, ts uint64, value int64) []ocrtypes.AttributedObservation { t.Helper() obs := Observation{ - UnixTimestampNanoseconds: ts, - StreamValues: protocol.StreamValues{100: protocol.ToDecimal(decimal.NewFromInt(value))}, + ObservationTimestampNanoseconds: ts, + StreamValues: protocol.StreamValues{100: protocol.ToDecimal(decimal.NewFromInt(value))}, } aos := make([]ocrtypes.AttributedObservation, 0, 4) for i := range 4 { @@ -182,7 +182,7 @@ func Test_History_ReclaimedOnChannelRemoval(t *testing.T) { require.NotEmpty(t, kv.m[string(keyHistoryIndex)]) // Vote the channel away. - removeObs := Observation{UnixTimestampNanoseconds: 20_000, RemoveChannelIDs: map[llotypes.ChannelID]struct{}{1: {}}} + removeObs := Observation{ObservationTimestampNanoseconds: 20_000, RemoveChannelIDs: map[llotypes.ChannelID]struct{}{1: {}}} removeAOs := make([]ocrtypes.AttributedObservation, 0, 4) for i := range 4 { removeAOs = append(removeAOs, ao(i, mustEncodeObs(t, removeObs))) diff --git a/llo/dev/v31/kv.go b/llo/dev/v31/kv.go index a233cc53..1933d18a 100644 --- a/llo/dev/v31/kv.go +++ b/llo/dev/v31/kv.go @@ -36,6 +36,11 @@ import ( // sorted (the history index) // hv -> 1 byte: history layout version // +// The proto records (c/defs, c/codecs, r/agg, hh/, hc/) are framed like blobs +// and the precursor: a codec byte followed by the proto, zstd-compressed +// whenever that shrinks it (see payloadcodec.go). The remaining keys hold a few +// fixed-width bytes that compression cannot shrink, so they stay raw. +// // c/seqnr lets readers cache the decoded c/defs in memory across rounds and // re-read it only when the stored sequence number differs from the cached one // (see protocol.ChannelCache). @@ -85,6 +90,28 @@ func beU32(v uint32) []byte { return b } +// writeKVRecord frames a marshaled proto record and writes it under key. +func writeKVRecord(w ocr3_1types.KeyValueStateReadWriter, key, raw []byte, what string) error { + b, err := encodeKVRecord(raw, what) + if err != nil { + return err + } + return w.Write(key, b) +} + +// readKVRecord reads and unframes the proto record under key. It returns nil +// when the key is absent. +func readKVRecord(r ocr3_1types.KeyValueStateReader, key []byte, what string) ([]byte, error) { + b, err := r.Read(key) + if err != nil { + return nil, fmt.Errorf("read %s: %w", what, err) + } + if len(b) == 0 { + return nil, nil + } + return decodeKVRecord(b, what) +} + func historyHeaderKey(streamID llotypes.StreamID, agg llotypes.Aggregator) []byte { k := append([]byte{}, prefixHistoryHead...) k = append(k, beU32(streamID)...) @@ -113,6 +140,9 @@ type kvState struct { // concurrently-running round from swapping decoded opts out from under this // one; always read opts from here rather than from plugin-wide state. opts *protocol.OptsCache + // channelState is the encoded c/defs record channelDefinitions were decoded + // from, owned by the same generation. The precursor carries it as is. + channelState []byte // codecSupport[oracleID] is the report formats that oracle last advertised // a codec for. See writeCodecSupport for why it is remembered per oracle // instead of being counted per round. @@ -130,6 +160,10 @@ type kvState struct { // (newer-wins monotonicity). Regular aggregates are recomputed fresh every // round and are never persisted. carryForward map[llotypes.StreamID]map[llotypes.Aggregator]*protocol.TimestampedStreamValue + // recentAgreedTimestamps holds the agreed observation timestamps of the + // rounds up to and including the one that wrote the record, oldest first. + // See appendAgreedTimestamp. + recentAgreedTimestamps []uint64 } // loadKVState reconstructs the full state from the replicated store, including @@ -180,14 +214,15 @@ func loadColdKVState(r ocr3_1types.KeyValueStateReader, cache *protocol.ChannelC s.channelStateSeqNr = binary.BigEndian.Uint64(seqNrBytes) } - gen, err := cache.Load(s.channelStateSeqNr, func() (llotypes.ChannelDefinitions, error) { - return readChannelState(r) - }) + gen, err := cache.Load(s.channelStateSeqNr, func() ([]byte, error) { + return readKVRecord(r, keyChannelState, "channel state") + }, decodeChannelState) if err != nil { return nil, err } s.channelDefinitions = gen.Definitions() s.opts = gen.Opts() + s.channelState = gen.Record() support, err := readCodecSupport(r) if err != nil { @@ -201,11 +236,11 @@ func loadColdKVState(r ocr3_1types.KeyValueStateReader, cache *protocol.ChannelC // readCodecSupport reads and decodes the c/codecs record. func readCodecSupport(r ocr3_1types.KeyValueStateReader) (map[commontypes.OracleID]map[llotypes.ReportFormat]struct{}, error) { support := map[commontypes.OracleID]map[llotypes.ReportFormat]struct{}{} - b, err := r.Read(keyCodecSupport) + b, err := readKVRecord(r, keyCodecSupport, "codec support") if err != nil { - return nil, fmt.Errorf("read codec support: %w", err) + return nil, err } - if len(b) == 0 { + if b == nil { return support, nil } pb := &protocol.LLOCodecSupportProto{} @@ -232,9 +267,9 @@ func readCodecSupport(r ocr3_1types.KeyValueStateReader) (map[commontypes.Oracle // codec for. // // Support is remembered per oracle rather than counted per round because the -// observation quorum is 2f+1. A count taken from one round can never exceed -// 2f+1, so the supporter threshold reportability would demand that every observation -// in a minimal quorum advertise the format. +// observation quorum can be as small as 2f+1. A count taken from one such round +// can never exceed 2f+1, so the supporter threshold reportability would demand +// that every observation in a minimal quorum advertise the format. func writeCodecSupport(w ocr3_1types.KeyValueStateReadWriter, support map[commontypes.OracleID]map[llotypes.ReportFormat]struct{}) error { pb := &protocol.LLOCodecSupportProto{ Oracles: make([]*protocol.LLOOracleCodecSupportProto, 0, len(support)), @@ -255,7 +290,7 @@ func writeCodecSupport(w ocr3_1types.KeyValueStateReadWriter, support map[common if err != nil { return fmt.Errorf("marshal codec support: %w", err) } - return w.Write(keyCodecSupport, b) + return writeKVRecord(w, keyCodecSupport, b, "codec support") } // readChannelState reads and decodes the c/defs record. @@ -267,12 +302,19 @@ func writeCodecSupport(w ocr3_1types.KeyValueStateReadWriter, support map[common // decode can allocate. A peer cannot inject records, and every oracle reads // the same bytes. func readChannelState(r ocr3_1types.KeyValueStateReader) (llotypes.ChannelDefinitions, error) { - b, err := r.Read(keyChannelState) + b, err := readKVRecord(r, keyChannelState, "channel state") if err != nil { - return nil, fmt.Errorf("read channel state: %w", err) + return nil, err } + return decodeChannelState(b) +} + +// decodeChannelState decodes an encoded c/defs record. The KeyValueState read +// and Reports both decode through it, so a record decodes the same wherever it +// comes from. +func decodeChannelState(b []byte) (llotypes.ChannelDefinitions, error) { defs := llotypes.ChannelDefinitions{} - if len(b) == 0 { + if b == nil { return defs, nil } pb := &protocol.LLOChannelStateProto{} @@ -293,11 +335,11 @@ func readChannelState(r ocr3_1types.KeyValueStateReader) (llotypes.ChannelDefini // aggregates to MaxPersistedAggregates, channels are capped by verification, // and the record is bounded in bytes. func readHotState(r ocr3_1types.KeyValueStateReader, s *kvState, lggr logger.Logger) error { - b, err := r.Read(keyHotState) + b, err := readKVRecord(r, keyHotState, "hot state") if err != nil { - return fmt.Errorf("read hot state: %w", err) + return err } - if len(b) == 0 { + if b == nil { return nil } pb := &protocol.LLOHotStateProto{} @@ -305,6 +347,7 @@ func readHotState(r ocr3_1types.KeyValueStateReader, s *kvState, lggr logger.Log return fmt.Errorf("unmarshal hot state: %w", err) } s.observationTimestampNs = pb.ObservationTimestampNanoseconds + s.recentAgreedTimestamps = pb.RecentAgreedTimestampsNanoseconds for _, va := range pb.ValidAfterNanoseconds { s.validAfterNanoseconds[va.ChannelID] = va.ValidAfterNanoseconds } @@ -346,6 +389,18 @@ func writeLifecycle(w ocr3_1types.KeyValueStateReadWriter, stage llotypes.LifeCy // sequence number of this write. Call it only when the definitions actually // changed, so that readers can keep serving their in-memory copy. func writeChannelState(w ocr3_1types.KeyValueStateReadWriter, seqNr uint64, defs llotypes.ChannelDefinitions) error { + b, err := encodeChannelState(defs) + if err != nil { + return err + } + if err := writeKVRecord(w, keyChannelState, b, "channel state"); err != nil { + return err + } + return w.Write(keyChannelSeqNr, beU64(seqNr)) +} + +// encodeChannelState encodes the definitions as a c/defs record. +func encodeChannelState(defs llotypes.ChannelDefinitions) ([]byte, error) { pb := &protocol.LLOChannelStateProto{ ChannelDefinitions: make([]*protocol.LLOChannelIDAndDefinitionProto, 0, len(defs)), } @@ -360,27 +415,26 @@ func writeChannelState(w ocr3_1types.KeyValueStateReadWriter, seqNr uint64, defs }) b, err := deterministicMarshal.Marshal(pb) if err != nil { - return fmt.Errorf("marshal channel state: %w", err) - } - if err := w.Write(keyChannelState, b); err != nil { - return err + return nil, fmt.Errorf("marshal channel state: %w", err) } - return w.Write(keyChannelSeqNr, beU64(seqNr)) + return b, nil } // writeHotState persists the per-round state: observation timestamp, validAfter -// watermarks, reportability decisions, and carry-forward timestamped -// aggregates. It is written every round. +// watermarks, reportability decisions, carry-forward timestamped aggregates +// and the recent agreed timestamps window. It is written every round. func writeHotState( w ocr3_1types.KeyValueStateReadWriter, observationTimestampNs uint64, validAfterNanoseconds map[llotypes.ChannelID]uint64, reportable map[llotypes.ChannelID]bool, carryForward map[llotypes.StreamID]map[llotypes.Aggregator]*protocol.TimestampedStreamValue, + recentAgreedTimestamps []uint64, lggr logger.Logger, ) error { pb := &protocol.LLOHotStateProto{ - ObservationTimestampNanoseconds: observationTimestampNs, + ObservationTimestampNanoseconds: observationTimestampNs, + RecentAgreedTimestampsNanoseconds: recentAgreedTimestamps, } pb.ValidAfterNanoseconds = make([]*protocol.LLOChannelIDAndValidAfterNanosecondsProto, 0, len(validAfterNanoseconds)) @@ -440,7 +494,7 @@ func writeHotState( if err != nil { return fmt.Errorf("marshal hot state: %w", err) } - return w.Write(keyHotState, b) + return writeKVRecord(w, keyHotState, b, "hot state") } // histKey identifies one history window. The aggregator is part of the identity @@ -465,7 +519,11 @@ func readHistoryHeader(r ocr3_1types.KeyValueStateReader, sid llotypes.StreamID, if len(b) == 0 { return nil, nil } - header, err := protocol.UnmarshalStreamHistoryHeader(b) + raw, err := decodeKVRecord(b, "history header") + if err != nil { + return nil, fmt.Errorf("read history header for stream %d aggregator %d: %w: %w", sid, agg, protocol.ErrCorruptStreamHistory, err) + } + header, err := protocol.UnmarshalStreamHistoryHeader(raw) if err != nil { return nil, fmt.Errorf("read history header for stream %d aggregator %d: %w", sid, agg, err) } @@ -473,12 +531,15 @@ func readHistoryHeader(r ocr3_1types.KeyValueStateReader, sid llotypes.StreamID, } // writeHistoryHeader persists a history header deterministically, returning the -// number of bytes written for telemetry. +// number of framed bytes written for telemetry. func writeHistoryHeader(w ocr3_1types.KeyValueStateReadWriter, sid llotypes.StreamID, agg llotypes.Aggregator, header *protocol.StreamHistoryHeader) (int, error) { b, err := header.MarshalBinary() if err != nil { return 0, fmt.Errorf("marshal history header for stream %d aggregator %d: %w", sid, agg, err) } + if b, err = encodeKVRecord(b, "history header"); err != nil { + return 0, err + } return len(b), w.Write(historyHeaderKey(sid, agg), b) } @@ -502,7 +563,11 @@ func readHistoryChunk(r ocr3_1types.KeyValueStateReader, sid llotypes.StreamID, if len(b) == 0 { return nil, nil } - chunk, err := protocol.UnmarshalStreamHistoryChunk(b) + raw, err := decodeKVRecord(b, "history chunk") + if err != nil { + return nil, fmt.Errorf("read history chunk for stream %d aggregator %d slot %d: %w: %w", sid, agg, slot, protocol.ErrCorruptStreamHistory, err) + } + chunk, err := protocol.UnmarshalStreamHistoryChunk(raw) if err != nil { return nil, fmt.Errorf("read history chunk for stream %d aggregator %d slot %d: %w", sid, agg, slot, err) } @@ -510,12 +575,15 @@ func readHistoryChunk(r ocr3_1types.KeyValueStateReader, sid llotypes.StreamID, } // writeHistoryChunk persists one ring slot deterministically, returning the -// number of bytes written for telemetry. +// number of framed bytes written for telemetry. func writeHistoryChunk(w ocr3_1types.KeyValueStateReadWriter, sid llotypes.StreamID, agg llotypes.Aggregator, chunk *protocol.StreamHistoryChunk) (int, error) { b, err := chunk.MarshalBinary() if err != nil { return 0, fmt.Errorf("marshal history chunk for stream %d aggregator %d slot %d: %w", sid, agg, chunk.Slot(), err) } + if b, err = encodeKVRecord(b, "history chunk"); err != nil { + return 0, err + } return len(b), w.Write(historyChunkKey(sid, agg, chunk.Slot()), b) } diff --git a/llo/dev/v31/kv_test.go b/llo/dev/v31/kv_test.go index 05580408..86d89be6 100644 --- a/llo/dev/v31/kv_test.go +++ b/llo/dev/v31/kv_test.go @@ -2,6 +2,7 @@ package llo import ( "encoding/binary" + "errors" "testing" "github.com/shopspring/decimal" @@ -30,7 +31,7 @@ func Test_ChannelCache_ReadsDefsOnlyWhenSeqNrChanges(t *testing.T) { require.NoError(t, err) // Round 3 still re-reads once, because round 2 changed the definitions. - noopObs := Observation{UnixTimestampNanoseconds: 2_000} + noopObs := Observation{ObservationTimestampNanoseconds: 2_000} aos := make([]ocrtypes.AttributedObservation, 0, 4) for i := 0; i < 4; i++ { aos = append(aos, ao(i, mustEncodeObs(t, noopObs))) @@ -61,7 +62,7 @@ func Test_ChannelCache_StaleSeqNrForcesReload(t *testing.T) { kv := newMemKV() defs := llotypes.ChannelDefinitions{1: jsonChannel()} require.NoError(t, writeChannelState(kv, 5, defs)) - require.NoError(t, writeHotState(kv, 0, nil, nil, nil, logger.Test(t))) + require.NoError(t, writeHotState(kv, 0, nil, nil, nil, nil, logger.Test(t))) cache := protocol.NewChannelCache() s, err := loadKVState(kv, cache, logger.Test(t)) @@ -97,7 +98,7 @@ func Test_HotState_DropsOrphanedCarryForward(t *testing.T) { // Round 3: the channel is now in effect; observe a timestamped value so it // gets carried forward. - obs := Observation{UnixTimestampNanoseconds: 2_000, StreamValues: protocol.StreamValues{100: tsv}} + obs := Observation{ObservationTimestampNanoseconds: 2_000, StreamValues: protocol.StreamValues{100: tsv}} aos := make([]ocrtypes.AttributedObservation, 0, 4) for i := 0; i < 4; i++ { aos = append(aos, ao(i, mustEncodeObs(t, obs))) @@ -108,7 +109,7 @@ func Test_HotState_DropsOrphanedCarryForward(t *testing.T) { // Round 4: vote to remove the only channel referencing the pair. The removal // is deferred, so the channel is still in effect and the value is retained. - removeObs := Observation{UnixTimestampNanoseconds: 3_000, RemoveChannelIDs: map[llotypes.ChannelID]struct{}{1: {}}} + removeObs := Observation{ObservationTimestampNanoseconds: 3_000, RemoveChannelIDs: map[llotypes.ChannelID]struct{}{1: {}}} removeAOs := make([]ocrtypes.AttributedObservation, 0, 4) for i := 0; i < 4; i++ { removeAOs = append(removeAOs, ao(i, mustEncodeObs(t, removeObs))) @@ -119,7 +120,7 @@ func Test_HotState_DropsOrphanedCarryForward(t *testing.T) { // Round 5: the removal takes effect and the carry-forward value is reclaimed // by not being written into the new hot record. - nextObs := Observation{UnixTimestampNanoseconds: 4_000} + nextObs := Observation{ObservationTimestampNanoseconds: 4_000} nextAOs := make([]ocrtypes.AttributedObservation, 0, 4) for i := 0; i < 4; i++ { nextAOs = append(nextAOs, ao(i, mustEncodeObs(t, nextObs))) @@ -148,7 +149,7 @@ func Test_KVRecords_DeterministicAndRoundTrip(t *testing.T) { for i := 0; i < 8; i++ { kv := newMemKV() require.NoError(t, writeChannelState(kv, 9, defs)) - require.NoError(t, writeHotState(kv, 1_234, validAfter, reportable, carry, logger.Test(t))) + require.NoError(t, writeHotState(kv, 1_234, validAfter, reportable, carry, nil, logger.Test(t))) if i == 0 { channelBytes, hotBytes = kv.m[string(keyChannelState)], kv.m[string(keyHotState)] continue @@ -159,7 +160,7 @@ func Test_KVRecords_DeterministicAndRoundTrip(t *testing.T) { kv := newMemKV() require.NoError(t, writeChannelState(kv, 9, defs)) - require.NoError(t, writeHotState(kv, 1_234, validAfter, reportable, carry, logger.Test(t))) + require.NoError(t, writeHotState(kv, 1_234, validAfter, reportable, carry, nil, logger.Test(t))) require.Equal(t, uint64(9), binary.BigEndian.Uint64(kv.m[string(keyChannelSeqNr)])) s, err := loadKVState(kv, nil, logger.Test(t)) @@ -189,6 +190,8 @@ func Test_HotState_DiscardsNonTimestampedCarryForward(t *testing.T) { }, }) require.NoError(t, err) + b, err = encodeKVRecord(b, "hot state") + require.NoError(t, err) kv := newMemKV() require.NoError(t, kv.Write(keyHotState, b)) @@ -209,6 +212,38 @@ func Test_HotState_DiscardsNonTimestampedCarryForward(t *testing.T) { // definition change is persisted immediately but is not in effect until the // following round, so the round that agreed it still aggregates, reports and // caches opts against the definitions Observation actually read. +// Test_KVRecords_BadFrame covers a framed record that does not decode. The +// round state records fail the load, as an undecodable proto does. History is +// corruption, which the store discards and re-warms. +func Test_KVRecords_BadFrame(t *testing.T) { + bad := []byte{payloadCodecZstd, 0x01, 0x02, 0x03} + + for name, key := range map[string][]byte{ + "channel state": keyChannelState, + "codec support": keyCodecSupport, + "hot state": keyHotState, + } { + t.Run(name, func(t *testing.T) { + kv := newMemKV() + require.NoError(t, kv.Write(key, bad)) + _, err := loadKVState(kv, nil, logger.Test(t)) + require.ErrorContains(t, err, name) + }) + } + + t.Run("history", func(t *testing.T) { + const sid, agg = llotypes.StreamID(1), llotypes.AggregatorMedian + kv := newMemKV() + require.NoError(t, kv.Write(historyHeaderKey(sid, agg), bad)) + require.NoError(t, kv.Write(historyChunkKey(sid, agg, 0), bad)) + + _, err := readHistoryHeader(kv, sid, agg) + require.True(t, errors.Is(err, protocol.ErrCorruptStreamHistory), "got %v", err) + _, err = readHistoryChunk(kv, sid, agg, 0) + require.True(t, errors.Is(err, protocol.ErrCorruptStreamHistory), "got %v", err) + }) +} + func Test_DeferredDefinitions_TakeEffectNextRound(t *testing.T) { ctx := tests.Context(t) p := testPlugin(t) @@ -226,7 +261,7 @@ func Test_DeferredDefinitions_TakeEffectNextRound(t *testing.T) { } round := func(seqNr, ts uint64, defs llotypes.ChannelDefinitions) precursor { - o := Observation{UnixTimestampNanoseconds: ts, StreamValues: protocol.StreamValues{100: protocol.ToDecimal(decimal.NewFromInt(1))}} + o := Observation{ObservationTimestampNanoseconds: ts, StreamValues: protocol.StreamValues{100: protocol.ToDecimal(decimal.NewFromInt(1))}} if defs != nil { o.UpdateChannelDefinitions = defs } @@ -236,9 +271,7 @@ func Test_DeferredDefinitions_TakeEffectNextRound(t *testing.T) { } raw, err := p.StateTransition(ctx, seqNr, ocrtypes.AttributedQuery{}, aos, kv, testBlobs) require.NoError(t, err) - prec, err := decodePrecursor(raw) - require.NoError(t, err) - return prec + return decodeResolvedPrecursor(t, raw) } _, err := p.StateTransition(ctx, 1, ocrtypes.AttributedQuery{}, []ocrtypes.AttributedObservation{ao(0, nil), ao(1, nil), ao(2, nil)}, kv, testBlobs) @@ -294,7 +327,7 @@ func Test_ChannelGeneration_BindsOptsToDefinitions(t *testing.T) { return o.V } round := func(seqNr, ts uint64, defs llotypes.ChannelDefinitions) { - o := Observation{UnixTimestampNanoseconds: ts} + o := Observation{ObservationTimestampNanoseconds: ts} if defs != nil { o.UpdateChannelDefinitions = defs } diff --git a/llo/dev/v31/limits_test.go b/llo/dev/v31/limits_test.go index e2209c61..e216165b 100644 --- a/llo/dev/v31/limits_test.go +++ b/llo/dev/v31/limits_test.go @@ -118,14 +118,26 @@ func TestLimits_HotStateWorstCaseFitsPerKeyLimit(t *testing.T) { reportable[cid] = true } + // A full window of maximal agreed timestamps. + window := make([]uint64, agreedTimestampWindow) + for i := range window { + window[i] = maxTimestamp + } + + // The write refuses a raw record over the per-key limit, so succeeding here + // is what proves admission keeps it under on its own: compression is + // headroom, not what makes it fit. kv := newMemKV() - require.NoError(t, writeHotState(kv, maxTimestamp, validAfter, reportable, carry, logger.Test(t))) + require.NoError(t, writeHotState(kv, maxTimestamp, validAfter, reportable, carry, window, logger.Test(t))) record, err := kv.Read(keyHotState) require.NoError(t, err) require.LessOrEqual(t, len(record), ocr3_1types.MaxMaxKeyValueValueBytes, "worst-case r/agg record (%d bytes) exceeds the per-key limit", len(record)) - t.Logf("worst-case r/agg record: %d bytes of %d", len(record), ocr3_1types.MaxMaxKeyValueValueBytes) + raw, err := decodeKVRecord(record, "hot state") + require.NoError(t, err) + t.Logf("worst-case r/agg record: %d bytes raw, %d framed (%.2fx), of %d", + len(raw), len(record), float64(len(raw))/float64(len(record)), ocr3_1types.MaxMaxKeyValueValueBytes) } // TestLimits_HotStateTruncatesAboveCap covers the cap itself: above it, pairs @@ -145,7 +157,7 @@ func TestLimits_HotStateTruncatesAboveCap(t *testing.T) { } kv := newMemKV() - require.NoError(t, writeHotState(kv, 1, nil, nil, carry, logger.Test(t))) + require.NoError(t, writeHotState(kv, 1, nil, nil, carry, nil, logger.Test(t))) state := &kvState{ channelDefinitions: llotypes.ChannelDefinitions{}, @@ -337,14 +349,17 @@ func TestLimits_ChannelStateWorstCaseFitsPerKeyLimit(t *testing.T) { require.Greater(t, channels*optsEach, protocol.MaxTotalOptsBytes-channels) require.LessOrEqual(t, optsEach, protocol.MaxChannelOptsBytes) + // As for r/agg, the write itself refuses a raw record over the limit. kv := newMemKV() require.NoError(t, writeChannelState(kv, 1, defs)) record, err := kv.Read(keyChannelState) require.NoError(t, err) require.LessOrEqual(t, len(record), ocr3_1types.MaxMaxKeyValueValueBytes, "worst-case c/defs record (%d bytes) exceeds the per-key limit", len(record)) - t.Logf("worst-case c/defs record: %d bytes of the %d per-key limit", - len(record), ocr3_1types.MaxMaxKeyValueValueBytes) + raw, err := decodeKVRecord(record, "channel state") + require.NoError(t, err) + t.Logf("worst-case c/defs record: %d bytes raw, %d framed (%.2fx), of the %d per-key limit", + len(raw), len(record), float64(len(raw))/float64(len(record)), ocr3_1types.MaxMaxKeyValueValueBytes) } // Observation decode rejects an oversized coefficient (see @@ -454,14 +469,14 @@ func TestLimits_ObservationWorstCaseFitsDeclared(t *testing.T) { } obs := Observation{ - AttestedPredecessorRetirement: attestedBytes, - ShouldRetire: true, - UnixTimestampNanoseconds: math.MaxUint64, - RemoveChannelIDs: removals, - UpdateChannelDefinitions: updates, - SupportedReportFormats: formats, - PredecessorSigners: signers, - PredecessorF: math.MaxUint8, + AttestedPredecessorRetirement: attestedBytes, + ShouldRetire: true, + ObservationTimestampNanoseconds: math.MaxUint64, + RemoveChannelIDs: removals, + UpdateChannelDefinitions: updates, + SupportedReportFormats: formats, + PredecessorSigners: signers, + PredecessorF: math.MaxUint8, } // The encoder references one blob. A handle carries at most one // availability signature per oracle, well under 4 KiB. @@ -508,7 +523,7 @@ func TestLimits_PrecursorWorstCaseFitsDeclared(t *testing.T) { // Every channel reportable, under the largest IDs. reportable := slices.Sorted(maps.Keys(defs)) - encoded, err := encodePrecursor(precursor{ + raw, err := marshalPrecursor(precursor{ LifeCycleStage: llotypes.LifeCycleStage(strings.Repeat("x", 32)), ObservationTimestampNanoseconds: math.MaxUint64, ChannelDefinitions: defs, @@ -518,8 +533,14 @@ func TestLimits_PrecursorWorstCaseFitsDeclared(t *testing.T) { ReportableChannelIDs: reportable, }) require.NoError(t, err) - require.LessOrEqual(t, len(encoded), ocr3_1types.MaxMaxReportsPlusPrecursorBytes, - "worst-case precursor (%d bytes) exceeds the declared limit", len(encoded)) - t.Logf("worst-case precursor: %d bytes of the %d limit", - len(encoded), ocr3_1types.MaxMaxReportsPlusPrecursorBytes) + // Admission must keep the raw precursor under the limit on its own: + // compression is headroom, not what makes it fit. + require.LessOrEqual(t, len(raw), maxDecompressedPrecursorBytes, + "worst-case raw precursor (%d bytes) exceeds the decompression bound", len(raw)) + framed, err := framePrecursor(raw) + require.NoError(t, err) + require.LessOrEqual(t, len(framed), ocr3_1types.MaxMaxReportsPlusPrecursorBytes, + "worst-case framed precursor (%d bytes) exceeds the declared limit", len(framed)) + t.Logf("worst-case precursor: %d bytes raw, %d framed (%.2fx), of the %d limit", + len(raw), len(framed), float64(len(raw))/float64(len(framed)), ocr3_1types.MaxMaxReportsPlusPrecursorBytes) } diff --git a/llo/dev/v31/observation.go b/llo/dev/v31/observation.go index 632cc6ed..5af49988 100644 --- a/llo/dev/v31/observation.go +++ b/llo/dev/v31/observation.go @@ -3,6 +3,7 @@ package llo import ( "context" "encoding/binary" + "errors" "fmt" "sort" @@ -19,12 +20,12 @@ import ( // Observation, but is disseminated using the v31 wire framing (which supports // offloading the bulk stream-value payload to a blob). type Observation struct { - AttestedPredecessorRetirement []byte - ShouldRetire bool - UnixTimestampNanoseconds uint64 - RemoveChannelIDs map[llotypes.ChannelID]struct{} - UpdateChannelDefinitions llotypes.ChannelDefinitions - StreamValues protocol.StreamValues + AttestedPredecessorRetirement []byte + ShouldRetire bool + ObservationTimestampNanoseconds uint64 + RemoveChannelIDs map[llotypes.ChannelID]struct{} + UpdateChannelDefinitions llotypes.ChannelDefinitions + StreamValues protocol.StreamValues // SupportedReportFormats are the report formats this oracle has a report // codec for. Encoding is node-local state that the state transition cannot // read without forking; advertising it here turns it into a replicated fact @@ -39,6 +40,11 @@ type Observation struct { // Signer order is significant: a signature names its signer by index. PredecessorSigners [][]byte PredecessorF uint8 + // CycleStartSeqNr is the sequence number the sender's blob pump saw when + // the cycle that gathered StreamValues started, read from the blob. Zero + // when the observation carries no stream values. The state transition + // measures the values' age from it. See selectFreshContributions. + CycleStartSeqNr uint64 } // observationWireVersion is the leading byte of the v31 observation framing. @@ -75,7 +81,7 @@ func encodeObservation(obs Observation, handles [][]byte) (ocrtypes.Observation, main := &protocol.LLOObservationProto{ AttestedPredecessorRetirement: obs.AttestedPredecessorRetirement, ShouldRetire: obs.ShouldRetire, - UnixTimestampNanoseconds: obs.UnixTimestampNanoseconds, + UnixTimestampNanoseconds: obs.ObservationTimestampNanoseconds, PredecessorSigners: obs.PredecessorSigners, PredecessorF: uint32(obs.PredecessorF), } @@ -140,14 +146,14 @@ type blobFetchError struct{ err error } func (e *blobFetchError) Error() string { return e.err.Error() } func (e *blobFetchError) Unwrap() error { return e.err } -// decodeObservation reverses encodeObservation, fetching any referenced blobs. +// fetchBlobsAndDecodeObservation reverses encodeObservation, fetching any referenced blobs. // Observations carrying inline stream values are rejected: v31 disseminates // values exclusively via blobs. // // memo, when non-nil, memoizes decoded blob payloads for the round so the same // handle is fetched and decompressed once instead of once per plugin phase. It // changes cost only: an observation decodes identically on a hit and on a miss. -func decodeObservation(ctx context.Context, raw ocrtypes.Observation, bf ocr3_1types.BlobFetcher, memo *roundBlobPayloads) (Observation, error) { +func fetchBlobsAndDecodeObservation(ctx context.Context, raw ocrtypes.Observation, bf ocr3_1types.BlobFetcher, memo *roundBlobPayloads) (Observation, error) { if len(raw) == 0 { return Observation{}, nil } @@ -228,10 +234,13 @@ func decodeObservation(ctx context.Context, raw ocrtypes.Observation, bf ocr3_1t if err != nil { return Observation{}, err } - chunk := &protocol.LLOObservationProto{} + chunk := &protocol.LLOBlobPayloadProto{} if err := proto.Unmarshal(raw, chunk); err != nil { return Observation{}, fmt.Errorf("unmarshal blob payload: %w", err) } + if chunk.CycleStartSeqNr == 0 { + return Observation{}, errors.New("blob payload carries no cycle start seqNr") + } values := make(protocol.StreamValues, len(chunk.StreamValues)) for id, pbSv := range chunk.StreamValues { sv, err := streamValueFromProtoAllowNil(pbSv) @@ -243,11 +252,19 @@ func decodeObservation(ctx context.Context, raw ocrtypes.Observation, bf ocr3_1t // Only a payload that decoded cleanly is memoized. A fetch failure is // node-local and transient, and a decode failure is deterministic and // recomputed for free, so neither is worth remembering. - entry = blobPayloadEntry{values: values, size: len(raw)} + entry = blobPayloadEntry{values: values, size: len(raw), cycleStartSeqNr: chunk.CycleStartSeqNr} memo.put(h.key, entry) } budget -= entry.size + // One observation is one cycle's values, so every blob it names must + // come from the same cycle. Deterministic: every oracle reads the same + // payloads. + if obs.CycleStartSeqNr == 0 { + obs.CycleStartSeqNr = entry.cycleStartSeqNr + } else if obs.CycleStartSeqNr != entry.cycleStartSeqNr { + return Observation{}, fmt.Errorf("observation references blobs from different cycles: seqNr %d and %d", obs.CycleStartSeqNr, entry.cycleStartSeqNr) + } if obs.StreamValues == nil { obs.StreamValues = make(protocol.StreamValues, len(entry.values)) } @@ -260,7 +277,7 @@ func decodeObservation(ctx context.Context, raw ocrtypes.Observation, bf ocr3_1t } func observationFromProto(main *protocol.LLOObservationProto) (Observation, error) { - // Bound the channel votes before copying them, and before decodeObservation + // Bound the channel votes before copying them, and before fetchBlobsAndDecodeObservation // fetches any blob, so an oversized observation costs no fetch. if len(main.RemoveChannelIDs) > protocol.MaxObservationRemoveChannelIDsLength { return Observation{}, fmt.Errorf("observation removes too many channels: %d (max %d)", len(main.RemoveChannelIDs), protocol.MaxObservationRemoveChannelIDsLength) @@ -269,9 +286,9 @@ func observationFromProto(main *protocol.LLOObservationProto) (Observation, erro return Observation{}, fmt.Errorf("observation updates too many channels: %d (max %d)", len(main.UpdateChannelDefinitions), protocol.MaxObservationUpdateChannelDefinitionsLength) } obs := Observation{ - AttestedPredecessorRetirement: main.AttestedPredecessorRetirement, - ShouldRetire: main.ShouldRetire, - UnixTimestampNanoseconds: main.UnixTimestampNanoseconds, + AttestedPredecessorRetirement: main.AttestedPredecessorRetirement, + ShouldRetire: main.ShouldRetire, + ObservationTimestampNanoseconds: main.UnixTimestampNanoseconds, } if len(main.RemoveChannelIDs) > 0 { obs.RemoveChannelIDs = make(map[llotypes.ChannelID]struct{}, len(main.RemoveChannelIDs)) diff --git a/llo/dev/v31/observation_coefficient_test.go b/llo/dev/v31/observation_coefficient_test.go index 75444184..55849513 100644 --- a/llo/dev/v31/observation_coefficient_test.go +++ b/llo/dev/v31/observation_coefficient_test.go @@ -15,14 +15,14 @@ import ( ocrtypes "github.com/smartcontractkit/libocr/offchainreporting2plus/types" ) -// Test_decodeObservation_CoefficientBound covers the blob-carried path, which is +// Test_fetchBlobsAndDecodeObservation_CoefficientBound covers the blob-carried path, which is // how v31 observations carry stream values at all: a value over the coefficient // bound must be rejected there, not merely in the protocol-level decoder. // // The rejection is a plain error rather than a blobFetchError, which is what -// makes it deterministic across oracles and therefore safe for -// decodeObservations to drop this observation alone instead of failing the round. -func Test_decodeObservation_CoefficientBound(t *testing.T) { +// makes it deterministic across oracles, so every oracle fails the round on it +// the same way in fetchBlobsDecodeValidateAndTallyObservations. +func Test_fetchBlobsAndDecodeObservation_CoefficientBound(t *testing.T) { ctx := tests.Context(t) overSized := decimal.NewFromBigInt(new(big.Int).Lsh(big.NewInt(1), protocol.MaxDecimalCoefficientBits), -2) @@ -30,16 +30,16 @@ func Test_decodeObservation_CoefficientBound(t *testing.T) { encode := func(t *testing.T, d decimal.Decimal) []byte { return mustEncodeObs(t, Observation{ - UnixTimestampNanoseconds: 1, - StreamValues: protocol.StreamValues{1: protocol.ToDecimal(d)}, + ObservationTimestampNanoseconds: 1, + StreamValues: protocol.StreamValues{1: protocol.ToDecimal(d)}, }) } - obs, err := decodeObservation(ctx, encode(t, atLimit), testBlobs, nil) + obs, err := fetchBlobsAndDecodeObservation(ctx, encode(t, atLimit), testBlobs, nil) require.NoError(t, err) require.Len(t, obs.StreamValues, 1) - _, err = decodeObservation(ctx, encode(t, overSized), testBlobs, nil) + _, err = fetchBlobsAndDecodeObservation(ctx, encode(t, overSized), testBlobs, nil) require.ErrorIs(t, err, protocol.ErrDecimalCoefficientOutOfRange) var bfErr *blobFetchError @@ -51,7 +51,7 @@ func Test_decodeObservation_CoefficientBound(t *testing.T) { // that matters: an oracle sending an unbounded value costs its own observation // and nothing else. The round completes and the remaining observations still // aggregate, which is why this bound is safe to enforce on the consensus path. -func Test_StateTransition_DropsObservationOverCoefficientBound(t *testing.T) { +func Test_StateTransition_RejectsObservationOverCoefficientBound(t *testing.T) { ctx := tests.Context(t) p := testPlugin(t) kv := newMemKV() @@ -74,8 +74,8 @@ func Test_StateTransition_DropsObservationOverCoefficientBound(t *testing.T) { obsWith := func(d decimal.Decimal) []byte { return mustEncodeObs(t, Observation{ - UnixTimestampNanoseconds: 3_000, - StreamValues: protocol.StreamValues{1: protocol.ToDecimal(d)}, + ObservationTimestampNanoseconds: 3_000, + StreamValues: protocol.StreamValues{1: protocol.ToDecimal(d)}, }) } // Three honest observations and one unbounded, which is f=1 for this plugin. @@ -86,9 +86,16 @@ func Test_StateTransition_DropsObservationOverCoefficientBound(t *testing.T) { ao(3, obsWith(overSized)), } - precBytes, err := p.StateTransition(ctx, 4, ocrtypes.AttributedQuery{}, aos, kv, testBlobs) - require.NoError(t, err, "one unbounded observation must not fail the round") + // ValidateObservation rejects the unbounded observation, so a leader that + // proposes it anyway runs a different validation from this oracle. + require.Error(t, p.ValidateObservation(ctx, 4, ocrtypes.AttributedQuery{}, ao(3, obsWith(overSized)), kv, testBlobs)) + _, err = p.StateTransition(ctx, 4, ocrtypes.AttributedQuery{}, aos, kv, testBlobs) + require.ErrorContains(t, err, "invariant violation") + require.ErrorContains(t, err, "decimal coefficient out of range") + // Without it the honest observations aggregate. + precBytes, err := p.StateTransition(ctx, 4, ocrtypes.AttributedQuery{}, aos[:3], kv, testBlobs) + require.NoError(t, err) prec, err := decodePrecursor(precBytes) require.NoError(t, err) aggregated, ok := prec.StreamAggregates[1][llotypes.AggregatorMedian] diff --git a/llo/dev/v31/payloadcodec.go b/llo/dev/v31/payloadcodec.go new file mode 100644 index 00000000..45a237dd --- /dev/null +++ b/llo/dev/v31/payloadcodec.go @@ -0,0 +1,212 @@ +package llo + +import ( + "fmt" + "sync" + + "github.com/klauspost/compress/zstd" + + "github.com/smartcontractkit/libocr/offchainreporting2plus/ocr3_1types" + + zstdenc "github.com/smartcontractkit/chainlink-data-streams/llo/internal/zstdenc/zstd" + protocol "github.com/smartcontractkit/chainlink-data-streams/llo/protocol" +) + +// Payload codec identifiers. The first byte of a framed payload (a blob, the +// precursor or a KV record) names the codec used for the remaining bytes, so a reader never +// has to guess and the writer stays free to fall back to raw when compression +// does not pay off. +const ( + payloadCodecRaw byte = 0 + payloadCodecZstd byte = 1 +) + +// maxDecompressedBlobPayloadBytes bounds the size of a blob payload after +// decompression. A blob is a stream-values-only observation proto, so the same +// bound the v30 observation codec uses applies here: it is generously above any +// honest payload while keeping a malicious peer from turning a small blob into +// a huge allocation (zstd bomb). +const maxDecompressedBlobPayloadBytes = protocol.MaxDecompressedObservationLength + +// MaxBlobPayloadBytes is the size of a broadcast blob payload libocr accepts, +// and is the value the factory declares as MaxBlobPayloadBytes. It bounds the +// payload as framed for broadcast (codec byte plus body), which is a different +// quantity from maxDecompressedBlobPayloadBytes: the latter is the anti-bomb +// bound applied to the decompressed bytes on the read side, and is deliberately +// looser. Enforcing this one on the write side is what stops the pump from +// broadcasting a blob every peer's libocr would reject. +const MaxBlobPayloadBytes = ocr3_1types.MaxMaxBlobPayloadBytes + +// maxDecompressedPrecursorBytes bounds the raw precursor proto. It equals the +// declared libocr limit on purpose: admission keeps the raw precursor under it +// (see TestLimits_PrecursorWorstCaseFitsDeclared), so compression is headroom +// and never what makes a precursor fit. +const maxDecompressedPrecursorBytes = ocr3_1types.MaxMaxReportsPlusPrecursorBytes + +// maxKVRecordBytes bounds a framed KV record both raw and framed. libocr +// rejects a value over MaxMaxKeyValueValueBytes, and the limits tests keep the +// raw worst case of every framed record under it, so compression is headroom +// here too. +const maxKVRecordBytes = ocr3_1types.MaxMaxKeyValueValueBytes + +// zstd Encoder/Decoder are safe for concurrent use via EncodeAll/DecodeAll and +// are expensive to build, so a single pair is shared process-wide. Built lazily +// so a construction failure surfaces at the call site rather than in init. +var ( + payloadZstd payloadCompressor + payloadZstdOnce sync.Once + payloadZstdErr error +) + +type payloadCompressor struct { + encoder *zstdenc.Encoder + decoder *zstd.Decoder +} + +func getPayloadCompressor() (payloadCompressor, error) { + payloadZstdOnce.Do(func() { + // The precursor is digested and signed, and KV records feed the state + // root, so every oracle must produce the same bytes. zstd output is + // stable only for one encoder version and one set of options, so encode + // with the frozen copy in llo/internal/zstdenc, which a dependency bump + // cannot move, and pin the options that shape the output. + // Test_Golden_Precursor and Test_Golden_KVRecords catch any change. + // Decoding stays on the upstream module: any conforming decoder reads + // these frames, and it keeps receiving fixes for untrusted input. + encoder, err := zstdenc.NewWriter(nil, + zstdenc.WithEncoderLevel(zstdenc.SpeedDefault), + zstdenc.WithEncoderCRC(true), + zstdenc.WithZeroFrames(false), + // Declare the content size in every frame. Without it zstd omits + // the size from frames under 256 bytes, and decodeFramedPayload + // rejects a frame that does not declare it. + zstdenc.WithSingleSegment(true), + ) + if err != nil { + payloadZstdErr = fmt.Errorf("new zstd encoder: %w", err) + return + } + // WithDecoderMaxMemory bounds the decompressed size to a safe limit. + // WithDecodeAllCapLimit bounds each DecodeAll call to the capacity of + // its destination, which decodeFramedPayload sizes to the call's budget. + decoder, err := zstd.NewReader(nil, + zstd.WithDecoderConcurrency(0), + zstd.WithDecoderMaxMemory(max(maxDecompressedBlobPayloadBytes, maxDecompressedPrecursorBytes, maxKVRecordBytes)), + zstd.WithDecodeAllCapLimit(true), + ) + if err != nil { + payloadZstdErr = fmt.Errorf("new zstd decoder: %w", err) + return + } + payloadZstd = payloadCompressor{encoder: encoder, decoder: decoder} + }) + return payloadZstd, payloadZstdErr +} + +// encodeFramedPayload frames raw bytes behind a codec byte, compressing them +// when that actually shrinks the payload. The choice depends only on raw, so +// two encoders built from the same library version always agree on it. maxRaw +// bounds raw so a reader with the same bound can decode it, and maxFramed is +// the size libocr accepts. what names the payload in errors. +func encodeFramedPayload(raw []byte, maxRaw, maxFramed int, what string) ([]byte, error) { + if len(raw) > maxRaw { + // Refuse to emit a payload every peer would reject on decompression; + // fail loudly here instead. + return nil, fmt.Errorf("%s too large: %d > %d bytes", what, len(raw), maxRaw) + } + c, err := getPayloadCompressor() + if err != nil { + return nil, err + } + out := c.encoder.EncodeAll(raw, []byte{payloadCodecZstd}) + if len(out) >= len(raw)+1 { + out = make([]byte, 0, len(raw)+1) + out = append(out, payloadCodecRaw) + out = append(out, raw...) + } + // A payload that compresses poorly can pass the raw check and still land + // over the framed limit. + if len(out) > maxFramed { + return nil, fmt.Errorf("framed %s too large: %d > %d bytes", what, len(out), maxFramed) + } + return out, nil +} + +// decodeFramedPayload reverses encodeFramedPayload. The payload is untrusted, +// so the decompressed size is bounded by maxOut up front via the content size +// the zstd frame header declares, and during decompression via the capacity of +// the destination buffer, which is that declared size. +func decodeFramedPayload(payload []byte, maxOut int, what string) ([]byte, error) { + if len(payload) == 0 { + return nil, fmt.Errorf("empty %s", what) + } + if maxOut <= 0 { + return nil, fmt.Errorf("%s budget exhausted", what) + } + codec, body := payload[0], payload[1:] + switch codec { + case payloadCodecRaw: + if len(body) > maxOut { + return nil, fmt.Errorf("%s too large: %d > %d bytes", what, len(body), maxOut) + } + return body, nil + case payloadCodecZstd: + c, err := getPayloadCompressor() + if err != nil { + return nil, err + } + // encodeFramedPayload always declares the content size. Require it, so + // a tiny frame cannot make every decode allocate the whole budget, and + // reject an oversized frame before spending decompression work on it. + var hdr zstd.Header + if err := hdr.Decode(body); err != nil { + return nil, fmt.Errorf("decode %s header: %w", what, err) + } + if !hdr.HasFCS { + return nil, fmt.Errorf("%s frame does not declare its content size", what) + } + if hdr.FrameContentSize > uint64(maxOut) { + return nil, fmt.Errorf("declared decompressed %s too large: %d > %d bytes", what, hdr.FrameContentSize, maxOut) + } + // A hostile peer can understate the declared size. The decoder stops + // once the output outgrows the destination capacity, so the declared + // size holds while decompressing, not only after. + out, err := c.decoder.DecodeAll(body, make([]byte, 0, int(hdr.FrameContentSize))) //nolint:gosec // bounded by maxOut above + if err != nil { + return nil, fmt.Errorf("decompress %s: %w", what, err) + } + // The cap limit is checked per block, so a block can overshoot it. + if len(out) > maxOut { + return nil, fmt.Errorf("decompressed %s too large: %d > %d bytes", what, len(out), maxOut) + } + return out, nil + default: + return nil, fmt.Errorf("unknown %s codec %d", what, codec) + } +} + +// encodeBlobPayload frames raw proto bytes for broadcast. Unlike the +// precursor, nodes need not agree on these bytes: each blob is fetched and +// decoded on its own. +func encodeBlobPayload(raw []byte) ([]byte, error) { + return encodeFramedPayload(raw, maxDecompressedBlobPayloadBytes, MaxBlobPayloadBytes, "blob payload") +} + +// decodeBlobPayload reverses encodeBlobPayload. maxOut is a caller-supplied +// budget (see fetchBlobsAndDecodeObservation) and is clamped to +// maxDecompressedBlobPayloadBytes. +func decodeBlobPayload(payload []byte, maxOut int) ([]byte, error) { + return decodeFramedPayload(payload, min(maxOut, maxDecompressedBlobPayloadBytes), "blob payload") +} + +// encodeKVRecord frames a marshaled KV record for writing. libocr builds the +// state root from these bytes, so they must match on every oracle, as for the +// precursor. +func encodeKVRecord(raw []byte, what string) ([]byte, error) { + return encodeFramedPayload(raw, maxKVRecordBytes, maxKVRecordBytes, what) +} + +// decodeKVRecord reverses encodeKVRecord. +func decodeKVRecord(b []byte, what string) ([]byte, error) { + return decodeFramedPayload(b, maxKVRecordBytes, what) +} diff --git a/llo/dev/v31/blobcompress_fuzz_test.go b/llo/dev/v31/payloadcodec_fuzz_test.go similarity index 91% rename from llo/dev/v31/blobcompress_fuzz_test.go rename to llo/dev/v31/payloadcodec_fuzz_test.go index 42f3c9b7..82640e9a 100644 --- a/llo/dev/v31/blobcompress_fuzz_test.go +++ b/llo/dev/v31/payloadcodec_fuzz_test.go @@ -15,8 +15,8 @@ func FuzzDecodeBlobPayload(f *testing.F) { f.Fatal(err) } f.Add(framed) - f.Add(append([]byte{blobCodecRaw}, raw...)) - f.Add([]byte{blobCodecZstd}) + f.Add(append([]byte{payloadCodecRaw}, raw...)) + f.Add([]byte{payloadCodecZstd}) f.Add([]byte{}) f.Fuzz(func(t *testing.T, payload []byte) { diff --git a/llo/dev/v31/blobcompress_test.go b/llo/dev/v31/payloadcodec_test.go similarity index 52% rename from llo/dev/v31/blobcompress_test.go rename to llo/dev/v31/payloadcodec_test.go index 9f9d48f8..84c06633 100644 --- a/llo/dev/v31/blobcompress_test.go +++ b/llo/dev/v31/payloadcodec_test.go @@ -3,6 +3,7 @@ package llo import ( "bytes" "strings" + "sync" "testing" "github.com/klauspost/compress/zstd" @@ -19,7 +20,7 @@ func Test_BlobPayload_RoundTrip(t *testing.T) { raw := []byte(strings.Repeat("stream-values-are-repetitive", 200)) framed, err := encodeBlobPayload(raw) require.NoError(t, err) - require.Equal(t, blobCodecZstd, framed[0]) + require.Equal(t, payloadCodecZstd, framed[0]) assert.Less(t, len(framed), len(raw)) got, err := decodeBlobPayload(framed, maxDecompressedBlobPayloadBytes) @@ -33,7 +34,7 @@ func Test_BlobPayload_RoundTrip(t *testing.T) { raw := []byte{0x9f, 0x1c, 0x00, 0xd3, 0x7a} framed, err := encodeBlobPayload(raw) require.NoError(t, err) - require.Equal(t, blobCodecRaw, framed[0]) + require.Equal(t, payloadCodecRaw, framed[0]) assert.Equal(t, len(raw)+1, len(framed)) got, err := decodeBlobPayload(framed, maxDecompressedBlobPayloadBytes) @@ -55,13 +56,13 @@ func Test_BlobPayload_MarshalStreamValuesRoundTrip(t *testing.T) { for i := uint32(0); i < 500; i++ { sv[i] = protocol.ToDecimal(decimal.NewFromInt(int64(i))) } - payload, err := marshalStreamValues(sv) + payload, err := marshalStreamValues(sv, 1) require.NoError(t, err) - require.Equal(t, blobCodecZstd, payload[0]) + require.Equal(t, payloadCodecZstd, payload[0]) raw, err := decodeBlobPayload(payload, maxDecompressedBlobPayloadBytes) require.NoError(t, err) - chunk := &protocol.LLOObservationProto{} + chunk := &protocol.LLOBlobPayloadProto{} require.NoError(t, proto.Unmarshal(raw, chunk)) assert.Len(t, chunk.StreamValues, 500) } @@ -78,14 +79,14 @@ func Test_decodeBlobPayload_Errors(t *testing.T) { }) t.Run("corrupt zstd body", func(t *testing.T) { - _, err := decodeBlobPayload([]byte{blobCodecZstd, 0xde, 0xad, 0xbe, 0xef}, maxDecompressedBlobPayloadBytes) + _, err := decodeBlobPayload([]byte{payloadCodecZstd, 0xde, 0xad, 0xbe, 0xef}, maxDecompressedBlobPayloadBytes) require.ErrorContains(t, err, "blob payload header") }) t.Run("zstd bomb is rejected without allocating", func(t *testing.T) { enc, err := zstd.NewWriter(nil) require.NoError(t, err) - bomb := enc.EncodeAll(make([]byte, maxDecompressedBlobPayloadBytes+1), []byte{blobCodecZstd}) + bomb := enc.EncodeAll(make([]byte, maxDecompressedBlobPayloadBytes+1), []byte{payloadCodecZstd}) require.Less(t, len(bomb), 1<<20, "bomb should be tiny on the wire") _, err = decodeBlobPayload(bomb, maxDecompressedBlobPayloadBytes) @@ -109,11 +110,11 @@ func Test_decodeBlobPayload_Errors(t *testing.T) { }) } -func Test_decodeBlobPayload_UndeclaredSize(t *testing.T) { +func Test_decodeBlobPayload_RejectsUndeclaredSize(t *testing.T) { // A streaming encoder does not know the content size up front, so the frame - // omits it and the header check cannot reject the payload. + // omits it. Decoding it would need a buffer sized to the whole budget. var buf bytes.Buffer - buf.WriteByte(blobCodecZstd) + buf.WriteByte(payloadCodecZstd) enc, err := zstd.NewWriter(&buf) require.NoError(t, err) _, err = enc.Write(make([]byte, 1<<20)) @@ -124,26 +125,94 @@ func Test_decodeBlobPayload_UndeclaredSize(t *testing.T) { require.NoError(t, hdr.Decode(buf.Bytes()[1:])) require.False(t, hdr.HasFCS) - // Stopped by the decoder, not by the length check after it. - _, err = decodeBlobPayload(buf.Bytes(), 4096) - require.ErrorIs(t, err, zstd.ErrDecoderSizeExceeded) - - got, err := decodeBlobPayload(buf.Bytes(), 1<<20) - require.NoError(t, err) - assert.Len(t, got, 1<<20) + _, err = decodeBlobPayload(buf.Bytes(), 1<<20) + require.ErrorContains(t, err, "frame does not declare its content size") } -func Test_encodeBlobPayload_DeclaresContentSize(t *testing.T) { +func Test_decodeBlobPayload_RejectsUnderstatedSize(t *testing.T) { framed, err := encodeBlobPayload(make([]byte, 4096)) require.NoError(t, err) - require.Equal(t, blobCodecZstd, framed[0]) - var hdr zstd.Header + require.Equal(t, payloadCodecZstd, framed[0]) + + // Rewrite the declared size to 1024 without touching the blocks. + hostile, err := zstd.NewWriter(nil, zstd.WithEncoderCRC(true), zstd.WithSingleSegment(true)) + require.NoError(t, err) + small := hostile.EncodeAll(make([]byte, 1024), nil) + var smallHdr, hdr zstd.Header + require.NoError(t, smallHdr.Decode(small)) require.NoError(t, hdr.Decode(framed[1:])) - require.True(t, hdr.HasFCS) - assert.Equal(t, uint64(4096), hdr.FrameContentSize) + require.Equal(t, smallHdr.HeaderSize, hdr.HeaderSize) + understated := append([]byte{payloadCodecZstd}, small[:smallHdr.HeaderSize]...) + understated = append(understated, framed[1+hdr.HeaderSize:]...) + + // Stopped while decompressing, not by the length check after it. A single + // segment frame sizes its window to the declared size, so the window check + // fires before the capacity limit. + _, err = decodeBlobPayload(understated, 1<<20) + require.ErrorContains(t, err, "decompress blob payload") +} + +func Test_encodeBlobPayload_DeclaresContentSize(t *testing.T) { + // zstd omits the size from frames under 256 bytes unless they are single + // segment, so cover both sides of that boundary. + for _, n := range []int{64, 255, 256, 4096} { + framed, err := encodeBlobPayload(make([]byte, n)) + require.NoError(t, err) + require.Equal(t, payloadCodecZstd, framed[0], "n=%d", n) + var hdr zstd.Header + require.NoError(t, hdr.Decode(framed[1:])) + require.True(t, hdr.HasFCS, "n=%d", n) + assert.Equal(t, uint64(n), hdr.FrameContentSize, "n=%d", n) + } } func Test_encodeBlobPayload_RejectsOversized(t *testing.T) { _, err := encodeBlobPayload(make([]byte, maxDecompressedBlobPayloadBytes+1)) require.ErrorContains(t, err, "blob payload too large") } + +func Test_encodePrecursor_DeterministicAcrossGoroutines(t *testing.T) { + // libocr digests the framed precursor, so every encode of the same value + // must produce the same bytes, including encodes that share the encoder. + want, err := encodePrecursor(goldenPrecursor()) + require.NoError(t, err) + require.Equal(t, payloadCodecZstd, want[0]) + + var wg sync.WaitGroup + got := make([][]byte, 16) + for i := range got { + wg.Go(func() { + b, err := encodePrecursor(goldenPrecursor()) + assert.NoError(t, err) + got[i] = b + }) + } + wg.Wait() + for _, b := range got { + require.Equal(t, []byte(want), b) + } +} + +func Test_decodePrecursor_Framing(t *testing.T) { + raw, err := marshalPrecursor(goldenPrecursor()) + require.NoError(t, err) + + t.Run("unframed proto is rejected", func(t *testing.T) { + _, err := decodePrecursor(raw) + require.ErrorContains(t, err, "unknown precursor codec") + }) + t.Run("raw codec decodes", func(t *testing.T) { + require.Equal(t, normalizePrecursor(t, goldenPrecursor()), decodeResolvedPrecursor(t, append([]byte{payloadCodecRaw}, raw...))) + }) + t.Run("declared size above the bound is rejected", func(t *testing.T) { + c, err := getPayloadCompressor() + require.NoError(t, err) + bomb := c.encoder.EncodeAll(make([]byte, maxDecompressedPrecursorBytes+1), []byte{payloadCodecZstd}) + _, err = decodePrecursor(bomb) + require.ErrorContains(t, err, "declared decompressed precursor too large") + }) + t.Run("raw above the bound is not encoded", func(t *testing.T) { + _, err := framePrecursor(make([]byte, maxDecompressedPrecursorBytes+1)) + require.ErrorContains(t, err, "precursor too large") + }) +} diff --git a/llo/dev/v31/plugin.go b/llo/dev/v31/plugin.go index 181e6760..f82f1cb4 100644 --- a/llo/dev/v31/plugin.go +++ b/llo/dev/v31/plugin.go @@ -53,6 +53,10 @@ type Plugin struct { // keys the facts derived from them by definition alone. ReportCodecs map[llotypes.ReportFormat]protocol.ReportCodec DonID uint32 + // freshnessMetrics is set by the factory. Nil records nothing. + freshnessMetrics *freshnessMetrics + // precursorMetrics is set by the factory. Nil records nothing. + precursorMetrics *precursorMetrics // ChannelCache memoizes the channel definitions record, together with the // opts decoded from it, across rounds so it is re-read only when its // sequence number changes. May be nil, in which case a fresh generation is @@ -103,6 +107,11 @@ type Plugin struct { // aggregation tolerates. It sets the contribution floor, see // minContributions. AggregationFaultTolerance int + + // MinRoundInterval is the configured DeltaRound, from the shared OCR config. + // It floors the round interval the state transition measures from agreed + // timestamps. See roundIntervalEstimate. + MinRoundInterval time.Duration } // minContributions is the contribution floor: the fewest contributions a stream @@ -212,9 +221,9 @@ func (p *Plugin) Observation(ctx context.Context, seqNr uint64, _ ocrtypes.Attri var reason string if snap, reason = p.pump.Take(ctx, seqNr); snap != nil { - handles = append(handles, snap.handleBytes) + handles = append(handles, snap.blobHandleBytes) } else { - p.Logger.Debugw("No usable stream-value snapshot for this round", "stage", "Observation", "seqNr", seqNr, "reason", reason, "misses", p.pump.Misses(), "cycles", p.pump.Cycles()) + p.Logger.Debugw("No usable stream-value snapshot for this round", "stage", "Observation", "seqNr", seqNr, "reason", reason, "misses", p.pump.Misses(), "cycles", p.pump.Cycles(), "reuses", p.pump.Reuses()) } } @@ -222,7 +231,7 @@ func (p *Plugin) Observation(ctx context.Context, seqNr uint64, _ ocrtypes.Attri if obsTSNanos < 0 { return nil, fmt.Errorf("negative observation timestamps are not supported, got: %d", obsTSNanos) } - obs.UnixTimestampNanoseconds = uint64(obsTSNanos) + obs.ObservationTimestampNanoseconds = uint64(obsTSNanos) // Advertised every round, including when retired: a statement about this // binary, not about the round or about what this node wants admitted. @@ -468,21 +477,9 @@ func (p *Plugin) ValidateObservation(ctx context.Context, seqNr uint64, _ ocrtyp return nil } - observation, err := decodeObservation(ctx, ao.Observation, bf, p.BlobPayloads.round(seqNr)) + observation, err := p.fetchBlobsDecodeAndValidateObservation(ctx, seqNr, ao, bf) if err != nil { - return fmt.Errorf("observation decode error: %w", err) - } - - if p.PredecessorConfigDigest == nil && len(observation.AttestedPredecessorRetirement) != 0 { - return errors.New("AttestedPredecessorRetirement is not empty even though this instance has no predecessor") - } - if p.PredecessorConfigDigest == nil && len(observation.PredecessorSigners) != 0 { - return errors.New("PredecessorSigners is not empty even though this instance has no predecessor") - } - // The signer set is only ever needed to verify a report carried alongside - // it, so a set without one is dead weight on the wire. - if len(observation.PredecessorSigners) != 0 && len(observation.AttestedPredecessorRetirement) == 0 { - return errors.New("PredecessorSigners is not empty even though this observation carries no AttestedPredecessorRetirement") + return err } // Only the baseline checks run here. A definition is installed on more than @@ -527,23 +524,67 @@ func (p *Plugin) ValidateObservation(ctx context.Context, seqNr uint64, _ ocrtyp return fmt.Errorf("UpdateChannelDefinitions is invalid: %w", err) } + return nil +} + +// fetchBlobsDecodeAndValidateObservation runs every observation check that +// needs no KV state: framing, blob fetch and decode, size limits, value types +// and the predecessor fields. ValidateObservation and StateTransition both +// call it, so the two cannot drift apart. The channel definition checks read +// KV state and stay in ValidateObservation. +// +// A blob fetch failure is returned wrapped in blobFetchError, so the caller +// can tell a node-local failure from a malformed observation. +func (p *Plugin) fetchBlobsDecodeAndValidateObservation(ctx context.Context, seqNr uint64, ao ocrtypes.AttributedObservation, bf ocr3_1types.BlobFetcher) (Observation, error) { + observation, err := fetchBlobsAndDecodeObservation(ctx, ao.Observation, bf, p.BlobPayloads.round(seqNr)) + if err != nil { + return Observation{}, fmt.Errorf("observation decode error: %w", err) + } + + if p.PredecessorConfigDigest == nil && len(observation.AttestedPredecessorRetirement) != 0 { + return Observation{}, errors.New("AttestedPredecessorRetirement is not empty even though this instance has no predecessor") + } + if p.PredecessorConfigDigest == nil && len(observation.PredecessorSigners) != 0 { + return Observation{}, errors.New("PredecessorSigners is not empty even though this instance has no predecessor") + } + // The signer set is only ever needed to verify a report carried alongside + // it, so a set without one is dead weight on the wire. + if len(observation.PredecessorSigners) != 0 && len(observation.AttestedPredecessorRetirement) == 0 { + return Observation{}, errors.New("PredecessorSigners is not empty even though this observation carries no AttestedPredecessorRetirement") + } + + // A cycle cannot have started in a round that has not happened yet. The + // lower bound is not checked: an old cycle is a stale contribution, which + // is the state transition's call, not an invalid observation. + if observation.CycleStartSeqNr > seqNr { + return Observation{}, fmt.Errorf("stream values gathered for a future round: cycle start seqNr %d > %d", observation.CycleStartSeqNr, seqNr) + } if len(observation.StreamValues) > protocol.MaxObservationStreamValuesLength { - return fmt.Errorf("StreamValues is too long: %v vs %v", len(observation.StreamValues), protocol.MaxObservationStreamValuesLength) + return Observation{}, fmt.Errorf("StreamValues is too long: %v vs %v", len(observation.StreamValues), protocol.MaxObservationStreamValuesLength) } for _, streamValue := range observation.StreamValues { if v, ok := streamValue.(*protocol.TimestampedStreamValue); ok { if v.StreamValue.Type() != protocol.LLOStreamValue_Decimal { - return fmt.Errorf("nested stream value on TimestampedStreamValue must be a Decimal, got: %v", v.StreamValue.Type()) + return Observation{}, fmt.Errorf("nested stream value on TimestampedStreamValue must be a Decimal, got: %v", v.StreamValue.Type()) } } } - return nil + return observation, nil } -// ObservationQuorum uses the standard 2f+1 quorum. +// ObservationQuorum uses the Byzantine quorum: at least 2f+1 observations, +// equal to it when n = 3f+1, and never more than n-f, so the honest oracles +// alone always reach it. For n > 3f+1 a round waits for more observations than +// 2f+1, so each stream gets more contributions. func (p *Plugin) ObservationQuorum(ctx context.Context, seqNr uint64, _ ocrtypes.AttributedQuery, aos []ocrtypes.AttributedObservation, _ ocr3_1types.KeyValueStateReader, _ ocr3_1types.BlobFetcher) (bool, error) { - return quorumhelper.ObservationCountReachesObservationQuorum(quorumhelper.QuorumTwoFPlusOne, p.N, p.F, aos), nil + return p.hasObservationQuorum(aos), nil +} + +// hasObservationQuorum is the one quorum rule, shared by ObservationQuorum and +// the StateTransition invariant. +func (p *Plugin) hasObservationQuorum(aos []ocrtypes.AttributedObservation) bool { + return quorumhelper.ObservationCountReachesObservationQuorum(quorumhelper.QuorumByzQuorum, p.N, p.F, aos) } // Committed is a no-op: LLO has no on-commit side effects, and Committed is not diff --git a/llo/dev/v31/plugin_test.go b/llo/dev/v31/plugin_test.go index 8199a678..46a3c18b 100644 --- a/llo/dev/v31/plugin_test.go +++ b/llo/dev/v31/plugin_test.go @@ -4,6 +4,7 @@ import ( "context" "encoding/binary" "errors" + "fmt" "math" "strconv" "sync" @@ -132,8 +133,6 @@ func attachPump(t *testing.T, p *Plugin, ds DataSource, bbf ocr3_1types.BlobBroa configDigest: p.ConfigDigest, verboseLogging: true, observationTimeout: tests.WaitTimeout(t), - maxSnapshotAge: time.Minute, - maxSnapshotRounds: DefaultMaxSnapshotRounds, blobLifetimeRounds: DefaultBlobLifetimeRounds, }) p.pump.Start() @@ -145,6 +144,11 @@ func ao(observer int, obsBytes []byte) ocrtypes.AttributedObservation { return ocrtypes.AttributedObservation{Observer: commontypes.OracleID(observer), Observation: obsBytes} } +// emptyRound is a quorum of empty observations, the only kind round 1 accepts. +func emptyRound() []ocrtypes.AttributedObservation { + return []ocrtypes.AttributedObservation{ao(0, nil), ao(1, nil), ao(2, nil), ao(3, nil)} +} + // testSupportedReportFormats is the codec coverage a fixture oracle advertises // by default: every format the tests in this package build channels for. var testSupportedReportFormats = formatSet( @@ -185,7 +189,14 @@ func mustEncodeObs(t *testing.T, obs Observation) []byte { require.NoError(t, err) return b } - payload, err := marshalStreamValues(obs.StreamValues) + // A cycle start of 1 is valid for every round and stale after + // MaxStreamValueAgeRounds, where the fallback aggregates every + // contribution anyway. Tests of the freshness rule set it explicitly. + cycleStartSeqNr := obs.CycleStartSeqNr + if cycleStartSeqNr == 0 { + cycleStartSeqNr = 1 + } + payload, err := marshalStreamValues(obs.StreamValues, cycleStartSeqNr) require.NoError(t, err) handle, err := testBlobs.BroadcastBlob(tests.Context(t), payload, ocr3_1types.BlobExpirationHintSequenceNumber{SeqNr: 0}) require.NoError(t, err) @@ -201,9 +212,9 @@ func mustEncodeObs(t *testing.T, obs Observation) []byte { func Test_Observation_WireRoundTrip(t *testing.T) { ctx := tests.Context(t) obs := Observation{ - ShouldRetire: true, - UnixTimestampNanoseconds: 123456789, - RemoveChannelIDs: map[llotypes.ChannelID]struct{}{7: {}}, + ShouldRetire: true, + ObservationTimestampNanoseconds: 123456789, + RemoveChannelIDs: map[llotypes.ChannelID]struct{}{7: {}}, UpdateChannelDefinitions: llotypes.ChannelDefinitions{ 1: {ReportFormat: llotypes.ReportFormatJSON, Streams: []llotypes.Stream{{StreamID: 100, Aggregator: llotypes.AggregatorMedian}}}, }, @@ -211,11 +222,11 @@ func Test_Observation_WireRoundTrip(t *testing.T) { enc, err := encodeObservation(obs, nil) require.NoError(t, err) - got, err := decodeObservation(ctx, enc, nil, nil) + got, err := fetchBlobsAndDecodeObservation(ctx, enc, nil, nil) require.NoError(t, err) assert.Equal(t, obs.ShouldRetire, got.ShouldRetire) - assert.Equal(t, obs.UnixTimestampNanoseconds, got.UnixTimestampNanoseconds) + assert.Equal(t, obs.ObservationTimestampNanoseconds, got.ObservationTimestampNanoseconds) assert.Equal(t, obs.RemoveChannelIDs, got.RemoveChannelIDs) require.Contains(t, got.UpdateChannelDefinitions, llotypes.ChannelID(1)) require.Empty(t, got.StreamValues) @@ -227,13 +238,13 @@ func Test_Observation_WireRoundTrip(t *testing.T) { func Test_Observation_StreamValuesNeverInline(t *testing.T) { ctx := tests.Context(t) obs := Observation{ - UnixTimestampNanoseconds: 1, - StreamValues: protocol.StreamValues{100: protocol.ToDecimal(decimal.NewFromInt(42))}, + ObservationTimestampNanoseconds: 1, + StreamValues: protocol.StreamValues{100: protocol.ToDecimal(decimal.NewFromInt(42))}, } enc, err := encodeObservation(obs, nil) require.NoError(t, err) - got, err := decodeObservation(ctx, enc, nil, nil) + got, err := fetchBlobsAndDecodeObservation(ctx, enc, nil, nil) require.NoError(t, err) require.Empty(t, got.StreamValues, "stream values must travel in a blob, never inline") } @@ -247,7 +258,7 @@ func Test_Observation_BlobRoundTrip(t *testing.T) { for i := 0; i < 500; i++ { sv[llotypes.StreamID(i)] = protocol.ToDecimal(decimal.NewFromInt(int64(i))) } - payload, err := marshalStreamValues(sv) + payload, err := marshalStreamValues(sv, 1) require.NoError(t, err) bc := newFakeBroadcaster() @@ -256,17 +267,17 @@ func Test_Observation_BlobRoundTrip(t *testing.T) { handleBytes, err := handle.MarshalBinary() require.NoError(t, err) - enc, err := encodeObservation(Observation{UnixTimestampNanoseconds: 1}, [][]byte{handleBytes}) + enc, err := encodeObservation(Observation{ObservationTimestampNanoseconds: 1}, [][]byte{handleBytes}) require.NoError(t, err) - got, err := decodeObservation(ctx, enc, bc, nil) + got, err := fetchBlobsAndDecodeObservation(ctx, enc, bc, nil) require.NoError(t, err) require.Len(t, got.StreamValues, len(sv)) require.True(t, equalStreamValue(sv[100], got.StreamValues[100])) // Without a fetcher the reference is unusable, and that must be classified // as a node-local blob-fetch failure rather than a malformed observation. - _, err = decodeObservation(ctx, enc, nil, nil) + _, err = fetchBlobsAndDecodeObservation(ctx, enc, nil, nil) var bfErr *blobFetchError require.ErrorAs(t, err, &bfErr) } @@ -309,8 +320,8 @@ func Test_FullRound_AddChannelThenReport(t *testing.T) { // Round 2 (seqNr=2): four oracles vote to add channel 1. addObs := Observation{ - UnixTimestampNanoseconds: 1_000, - UpdateChannelDefinitions: llotypes.ChannelDefinitions{1: channelDef}, + ObservationTimestampNanoseconds: 1_000, + UpdateChannelDefinitions: llotypes.ChannelDefinitions{1: channelDef}, } addAOs := []ocrtypes.AttributedObservation{} for i := 0; i < 4; i++ { @@ -328,8 +339,8 @@ func Test_FullRound_AddChannelThenReport(t *testing.T) { valObs := func(ts uint64) []ocrtypes.AttributedObservation { obs := Observation{ - UnixTimestampNanoseconds: ts, - StreamValues: protocol.StreamValues{100: protocol.ToDecimal(decimal.NewFromInt(42))}, + ObservationTimestampNanoseconds: ts, + StreamValues: protocol.StreamValues{100: protocol.ToDecimal(decimal.NewFromInt(42))}, } aos := []ocrtypes.AttributedObservation{} for i := 0; i < 4; i++ { @@ -371,8 +382,8 @@ func Test_StateTransition_ContributionFloor(t *testing.T) { addAOs := []ocrtypes.AttributedObservation{} for i := 0; i < 4; i++ { addAOs = append(addAOs, ao(i, mustEncodeObs(t, Observation{ - UnixTimestampNanoseconds: 1_000, - UpdateChannelDefinitions: llotypes.ChannelDefinitions{1: channelDef}, + ObservationTimestampNanoseconds: 1_000, + UpdateChannelDefinitions: llotypes.ChannelDefinitions{1: channelDef}, }))) } _, err = p.StateTransition(ctx, 2, ocrtypes.AttributedQuery{}, addAOs, kv, testBlobs) @@ -384,7 +395,7 @@ func Test_StateTransition_ContributionFloor(t *testing.T) { valObs := func(ts uint64, contributors int) []ocrtypes.AttributedObservation { aos := []ocrtypes.AttributedObservation{} for i := 0; i < 4; i++ { - obs := Observation{UnixTimestampNanoseconds: ts} + obs := Observation{ObservationTimestampNanoseconds: ts} if i < contributors { obs.StreamValues = protocol.StreamValues{100: protocol.ToDecimal(decimal.NewFromInt(42))} } @@ -445,8 +456,7 @@ func Test_Precursor_RoundTrip_And_Determinism(t *testing.T) { require.NoError(t, err) require.Equal(t, b1, b2, "precursor encoding must be deterministic") - got, err := decodePrecursor(b1) - require.NoError(t, err) + got := decodeResolvedPrecursor(t, b1) assert.Equal(t, p.LifeCycleStage, got.LifeCycleStage) assert.Equal(t, p.ObservationTimestampNanoseconds, got.ObservationTimestampNanoseconds) assert.Equal(t, p.ValidAfterNanoseconds, got.ValidAfterNanoseconds) @@ -463,9 +473,9 @@ func Test_StateTransition_Determinism_ShuffledObservations(t *testing.T) { } obs := func(observer int, ts uint64, val int64) ocrtypes.AttributedObservation { return ao(observer, mustEncodeObs(t, Observation{ - UnixTimestampNanoseconds: ts, - UpdateChannelDefinitions: llotypes.ChannelDefinitions{1: channelDef}, - StreamValues: protocol.StreamValues{100: protocol.ToDecimal(decimal.NewFromInt(val))}, + ObservationTimestampNanoseconds: ts, + UpdateChannelDefinitions: llotypes.ChannelDefinitions{1: channelDef}, + StreamValues: protocol.StreamValues{100: protocol.ToDecimal(decimal.NewFromInt(val))}, })) } @@ -491,14 +501,14 @@ func Test_StateTransition_Determinism_ShuffledObservations(t *testing.T) { require.Equal(t, kvA.m, kvB.m, "KV write-set must be identical regardless of observation order") } -func Test_decodeObservation_RejectsHugeHandleCount(t *testing.T) { +func Test_fetchBlobsAndDecodeObservation_RejectsHugeHandleCount(t *testing.T) { ctx := tests.Context(t) // version byte + a uvarint encoding a huge handle count. buf := []byte{observationWireVersion} var tmp [binary.MaxVarintLen64]byte n := binary.PutUvarint(tmp[:], ^uint64(0)) // max uint64 buf = append(buf, tmp[:n]...) - _, err := decodeObservation(ctx, buf, nil, nil) + _, err := fetchBlobsAndDecodeObservation(ctx, buf, nil, nil) require.Error(t, err, "must reject an oversized handle count instead of allocating") require.Contains(t, err.Error(), "too many blobs") } @@ -993,7 +1003,7 @@ func Test_Telemetry(t *testing.T) { channelDef := llotypes.ChannelDefinition{ReportFormat: llotypes.ReportFormatJSON, Streams: []llotypes.Stream{{StreamID: 100, Aggregator: llotypes.AggregatorMedian}}} obs := func(ts uint64, withVal bool) []ocrtypes.AttributedObservation { - o := Observation{UnixTimestampNanoseconds: ts, UpdateChannelDefinitions: llotypes.ChannelDefinitions{1: channelDef}} + o := Observation{ObservationTimestampNanoseconds: ts, UpdateChannelDefinitions: llotypes.ChannelDefinitions{1: channelDef}} if withVal { o.StreamValues = protocol.StreamValues{100: protocol.ToDecimal(decimal.NewFromInt(42))} } @@ -1044,9 +1054,7 @@ func Test_CalculatedStreams(t *testing.T) { }} channelCache := protocol.NewChannelCache() - generation, err := channelCache.Load(1, func() (llotypes.ChannelDefinitions, error) { - return definitions, nil - }) + generation, err := loadDefinitions(channelCache, 1, definitions) require.NoError(t, err) prec := precursor{ @@ -1142,7 +1150,7 @@ func Test_HistoryBackfill(t *testing.T) { // validBlobHandleBytes returns the wire encoding of a syntactically valid handle // for a blob nobody broadcast. It lets a test build an observation that -// *references* a blob (so decodeObservation reaches the fetch path) while the +// *references* a blob (so fetchBlobsAndDecodeObservation reaches the fetch path) while the // fetch is guaranteed to fail. func validBlobHandleBytes() []byte { handle, err := llotest.NewBlobHandle([]byte("never broadcast")) @@ -1156,11 +1164,11 @@ func validBlobHandleBytes() []byte { return b } -// Test_decodeObservation_BlobFetchErrorIsClassified verifies that a failure to +// Test_fetchBlobsAndDecodeObservation_BlobFetchErrorIsClassified verifies that a failure to // fetch a referenced blob surfaces as a *blobFetchError, so StateTransition can // propagate it (uniform retry) instead of silently dropping the observation on // only some oracles (Finding 2). -func Test_decodeObservation_BlobFetchErrorIsClassified(t *testing.T) { +func Test_fetchBlobsAndDecodeObservation_BlobFetchErrorIsClassified(t *testing.T) { ctx := tests.Context(t) mainBytes, err := proto.Marshal(&protocol.LLOObservationProto{UnixTimestampNanoseconds: 42}) require.NoError(t, err) @@ -1169,32 +1177,32 @@ func Test_decodeObservation_BlobFetchErrorIsClassified(t *testing.T) { var bfErr *blobFetchError // A failing fetcher -> node-local error, must be a *blobFetchError. - _, err = decodeObservation(ctx, frame, &errBroadcaster{}, nil) + _, err = fetchBlobsAndDecodeObservation(ctx, frame, &errBroadcaster{}, nil) require.Error(t, err) require.True(t, errors.As(err, &bfErr), "fetch failure must be a blobFetchError so StateTransition propagates it") // A nil fetcher (blob referenced but unfetchable) -> also a *blobFetchError. - _, err = decodeObservation(ctx, frame, nil, nil) + _, err = fetchBlobsAndDecodeObservation(ctx, frame, nil, nil) require.Error(t, err) require.True(t, errors.As(err, &bfErr)) } -// Test_decodeObservation_MalformedIsNotBlobFetchError verifies that +// Test_fetchBlobsAndDecodeObservation_MalformedIsNotBlobFetchError verifies that // deterministic decode failures (same bytes on every oracle) are NOT classified // as blobFetchError, so StateTransition still drops just that observation rather // than aborting the whole round (Finding 2, the other side of the boundary). -func Test_decodeObservation_MalformedIsNotBlobFetchError(t *testing.T) { +func Test_fetchBlobsAndDecodeObservation_MalformedIsNotBlobFetchError(t *testing.T) { ctx := tests.Context(t) var bfErr *blobFetchError // Unknown wire version. - _, err := decodeObservation(ctx, []byte{0x02, 0x00}, &errBroadcaster{}, nil) + _, err := fetchBlobsAndDecodeObservation(ctx, []byte{0x02, 0x00}, &errBroadcaster{}, nil) require.Error(t, err) require.False(t, errors.As(err, &bfErr), "malformed framing must stay droppable, not a blobFetchError") // Well-framed but garbage handle bytes: UnmarshalBinary fails deterministically. frame := frameObservation([][]byte{{0xFF}}, nil) - _, err = decodeObservation(ctx, frame, &errBroadcaster{}, nil) + _, err = fetchBlobsAndDecodeObservation(ctx, frame, &errBroadcaster{}, nil) require.Error(t, err) require.False(t, errors.As(err, &bfErr)) } @@ -1225,38 +1233,92 @@ func Test_StateTransition_PropagatesBlobFetchFailure(t *testing.T) { require.Contains(t, err.Error(), "fetch blob") } -// Test_StateTransition_RequiresQuorumAfterDecode checks that observations -// dropped on decode cannot shrink the sample below 2f+1, where f byzantine -// timestamps could control the median. -func Test_StateTransition_RequiresQuorumAfterDecode(t *testing.T) { +// Test_StateTransition_FailsOnInvalidObservation checks that an observation +// failing the checks ValidateObservation runs fails the round instead of being +// dropped, so a sample can never shrink below the quorum it was accepted on +// and a divergent validation cannot fork the state. +func Test_StateTransition_FailsOnInvalidObservation(t *testing.T) { ctx := tests.Context(t) p := testPlugin(t) kv := newMemKV() + t.Run("non-empty observation in round 1", func(t *testing.T) { + aos := []ocrtypes.AttributedObservation{ao(0, nil), ao(1, nil), ao(2, []byte{0x7f})} + _, err := p.StateTransition(ctx, 1, ocrtypes.AttributedQuery{}, aos, kv, testBlobs) + require.ErrorContains(t, err, "invariant violation: non-empty observation from oracle 2 in round 1") + }) + // Bootstrap. _, err := p.StateTransition(ctx, 1, ocrtypes.AttributedQuery{}, []ocrtypes.AttributedObservation{ao(0, nil), ao(1, nil), ao(2, nil)}, kv, testBlobs) require.NoError(t, err) valid := func(i int) ocrtypes.AttributedObservation { - return ao(i, mustEncodeObs(t, Observation{UnixTimestampNanoseconds: 1000})) - } - invalid := func(i int) ocrtypes.AttributedObservation { - return ao(i, []byte{0x7f}) + return ao(i, mustEncodeObs(t, Observation{ObservationTimestampNanoseconds: 1000})) } - t.Run("2f+1 decoded observations proceed", func(t *testing.T) { - aos := []ocrtypes.AttributedObservation{valid(0), valid(1), valid(2), invalid(3)} + t.Run("malformed framing", func(t *testing.T) { + aos := []ocrtypes.AttributedObservation{valid(0), valid(1), valid(2), ao(3, []byte{0x7f})} _, err := p.StateTransition(ctx, 2, ocrtypes.AttributedQuery{}, aos, kv, testBlobs) - require.NoError(t, err) + require.ErrorContains(t, err, "invariant violation: observation from oracle 3 accepted by the leader fails validation on this oracle") + require.ErrorContains(t, err, "observation decode error") + }) + + t.Run("predecessor field without a predecessor", func(t *testing.T) { + stray := ao(3, mustEncodeObs(t, Observation{ObservationTimestampNanoseconds: 1000, AttestedPredecessorRetirement: []byte{1}})) + aos := []ocrtypes.AttributedObservation{valid(0), valid(1), valid(2), stray} + _, err := p.StateTransition(ctx, 2, ocrtypes.AttributedQuery{}, aos, kv, testBlobs) + require.ErrorContains(t, err, "AttestedPredecessorRetirement is not empty even though this instance has no predecessor") }) - t.Run("fewer than 2f+1 decoded observations fail the round", func(t *testing.T) { - aos := []ocrtypes.AttributedObservation{valid(0), valid(1), invalid(2), invalid(3)} - _, err := p.StateTransition(ctx, 3, ocrtypes.AttributedQuery{}, aos, kv, testBlobs) - require.ErrorContains(t, err, "expected at least 2f+1 decoded observations, got 2 (f: 1)") + t.Run("valid observations proceed", func(t *testing.T) { + aos := []ocrtypes.AttributedObservation{valid(0), valid(1), valid(2)} + _, err := p.StateTransition(ctx, 2, ocrtypes.AttributedQuery{}, aos, kv, testBlobs) + require.NoError(t, err) }) } +// Test_ObservationQuorum_Byzantine checks the quorum is the Byzantine quorum: +// 2f+1 at n = 3f+1, more above it, never more than n-f, and that +// StateTransition holds the same invariant. +func Test_ObservationQuorum_Byzantine(t *testing.T) { + ctx := tests.Context(t) + aosOf := func(n int) []ocrtypes.AttributedObservation { + aos := make([]ocrtypes.AttributedObservation, 0, n) + for i := range n { + aos = append(aos, ao(i, nil)) + } + return aos + } + + cases := []struct{ n, f, quorum int }{ + {n: 4, f: 1, quorum: 3}, + {n: 5, f: 1, quorum: 4}, + {n: 7, f: 1, quorum: 5}, + {n: 7, f: 2, quorum: 5}, + {n: 10, f: 3, quorum: 7}, + } + for _, tc := range cases { + t.Run(fmt.Sprintf("n=%d f=%d", tc.n, tc.f), func(t *testing.T) { + p := testPlugin(t) + p.N, p.F = tc.n, tc.f + require.GreaterOrEqual(t, tc.quorum, 2*tc.f+1) + require.LessOrEqual(t, tc.quorum, tc.n-tc.f) + + below, err := p.ObservationQuorum(ctx, 2, ocrtypes.AttributedQuery{}, aosOf(tc.quorum-1), nil, nil) + require.NoError(t, err) + require.False(t, below) + reached, err := p.ObservationQuorum(ctx, 2, ocrtypes.AttributedQuery{}, aosOf(tc.quorum), nil, nil) + require.NoError(t, err) + require.True(t, reached) + + _, err = p.StateTransition(ctx, 1, ocrtypes.AttributedQuery{}, aosOf(tc.quorum-1), newMemKV(), testBlobs) + require.ErrorContains(t, err, "do not reach the observation quorum") + _, err = p.StateTransition(ctx, 1, ocrtypes.AttributedQuery{}, aosOf(tc.quorum), newMemKV(), testBlobs) + require.NoError(t, err) + }) + } +} + // equalStreamValue compares two stream values by their binary encoding. func equalStreamValue(a, b protocol.StreamValue) bool { ba, err := a.MarshalBinary() @@ -1353,7 +1415,7 @@ func Test_Observation_RejectsInlineStreamValues(t *testing.T) { }) require.NoError(t, err) - _, err = decodeObservation(ctx, frameObservation(nil, mainBytes), nil, nil) + _, err = fetchBlobsAndDecodeObservation(ctx, frameObservation(nil, mainBytes), nil, nil) require.ErrorContains(t, err, "inline stream values") // Deterministic across oracles, so it must not be a blob-fetch failure. @@ -1572,7 +1634,7 @@ func Test_Observation_SupportedReportFormats_RoundTrip(t *testing.T) { // The set is sorted on the wire and collapses back to a set on decode, so // one oracle can only ever contribute one vote per format to the tally. obs := Observation{ - UnixTimestampNanoseconds: 1, + ObservationTimestampNanoseconds: 1, SupportedReportFormats: formatSet( llotypes.ReportFormatJSON, llotypes.ReportFormatEVMPremiumLegacy, @@ -1580,7 +1642,7 @@ func Test_Observation_SupportedReportFormats_RoundTrip(t *testing.T) { } b, err := encodeObservation(obs, nil) require.NoError(t, err) - got, err := decodeObservation(ctx, b, nil, nil) + got, err := fetchBlobsAndDecodeObservation(ctx, b, nil, nil) require.NoError(t, err) require.Equal(t, formatSet(llotypes.ReportFormatEVMPremiumLegacy, llotypes.ReportFormatJSON), got.SupportedReportFormats) require.Equal(t, []uint32{uint32(llotypes.ReportFormatEVMPremiumLegacy), uint32(llotypes.ReportFormatJSON)}, sortedFormatsToWire(got.SupportedReportFormats)) @@ -1591,15 +1653,15 @@ func Test_Observation_SupportedReportFormats_RoundTrip(t *testing.T) { SupportedReportFormats: []uint32{uint32(llotypes.ReportFormatJSON), uint32(llotypes.ReportFormatJSON)}, }) require.NoError(t, err) - got, err = decodeObservation(ctx, frameObservation(nil, dup), nil, nil) + got, err = fetchBlobsAndDecodeObservation(ctx, frameObservation(nil, dup), nil, nil) require.NoError(t, err) require.Equal(t, formatSet(llotypes.ReportFormatJSON), got.SupportedReportFormats) // An oracle advertising nothing decodes as advertising nothing, rather than // as an empty-but-present list. - b, err = encodeObservation(Observation{UnixTimestampNanoseconds: 1}, nil) + b, err = encodeObservation(Observation{ObservationTimestampNanoseconds: 1}, nil) require.NoError(t, err) - got, err = decodeObservation(ctx, b, nil, nil) + got, err = fetchBlobsAndDecodeObservation(ctx, b, nil, nil) require.NoError(t, err) require.Nil(t, got.SupportedReportFormats) @@ -1610,7 +1672,7 @@ func Test_Observation_SupportedReportFormats_RoundTrip(t *testing.T) { } raw, err := proto.Marshal(&protocol.LLOObservationProto{UnixTimestampNanoseconds: 1, SupportedReportFormats: tooMany}) require.NoError(t, err) - _, err = decodeObservation(ctx, frameObservation(nil, raw), nil, nil) + _, err = fetchBlobsAndDecodeObservation(ctx, frameObservation(nil, raw), nil, nil) require.ErrorContains(t, err, "advertises too many report formats") } @@ -1640,7 +1702,7 @@ func Test_DecodeObservation_ChannelVoteBounds(t *testing.T) { t.Run(tc.name, func(t *testing.T) { raw, err := proto.Marshal(tc.main) require.NoError(t, err) - _, err = decodeObservation(ctx, frameObservation([][]byte{validBlobHandleBytes()}, raw), &errBroadcaster{}, nil) + _, err = fetchBlobsAndDecodeObservation(ctx, frameObservation([][]byte{validBlobHandleBytes()}, raw), &errBroadcaster{}, nil) require.ErrorContains(t, err, tc.err) }) } @@ -1654,7 +1716,7 @@ func Test_DecodeObservation_AttestedPredecessorRetirementBound(t *testing.T) { AttestedPredecessorRetirement: make([]byte, protocol.MaxAttestedRetirementReportBytes), }) require.NoError(t, err) - got, err := decodeObservation(ctx, frameObservation(nil, atLimit), nil, nil) + got, err := fetchBlobsAndDecodeObservation(ctx, frameObservation(nil, atLimit), nil, nil) require.NoError(t, err) require.Len(t, got.AttestedPredecessorRetirement, protocol.MaxAttestedRetirementReportBytes) @@ -1665,7 +1727,7 @@ func Test_DecodeObservation_AttestedPredecessorRetirementBound(t *testing.T) { AttestedPredecessorRetirement: make([]byte, protocol.MaxAttestedRetirementReportBytes+1), }) require.NoError(t, err) - _, err = decodeObservation(ctx, frameObservation(nil, overLimit), nil, nil) + _, err = fetchBlobsAndDecodeObservation(ctx, frameObservation(nil, overLimit), nil, nil) require.ErrorContains(t, err, "attested predecessor retirement of") } @@ -1697,18 +1759,17 @@ func Test_Precursor_ReportableChannelIDs_RoundTrip(t *testing.T) { require.ErrorContains(t, err, "reportable channel 4 has no definition") encodeRaw := func(ids ...uint32) []byte { - pb := &protocol.LLOPrecursorProto{ReportableChannelIDs: ids} - for id := range defs { - pb.ChannelDefinitions = append(pb.ChannelDefinitions, &protocol.LLOChannelIDAndDefinitionProto{ - ChannelID: id, - ChannelDefinition: protocol.ChannelDefinitionToProto(defs[id]), - }) - } - b, err := proto.Marshal(pb) + state, err := encodeChannelState(defs) require.NoError(t, err) - return b + b, err := proto.Marshal(&protocol.LLOPrecursorProto{ReportableChannelIDs: ids, ChannelState: state}) + require.NoError(t, err) + framed, err := framePrecursor(b) + require.NoError(t, err) + return framed } - _, err = decodePrecursor(encodeRaw(4)) + missing, err := decodePrecursor(encodeRaw(4)) + require.NoError(t, err) + _, err = missing.definitions(protocol.NewChannelCache()) require.ErrorContains(t, err, "reportable channel 4 has no definition") // Unsorted or repeated IDs would let Reports emit a channel twice. _, err = decodePrecursor(encodeRaw(2, 1)) @@ -1739,8 +1800,8 @@ func Test_StateTransition_TalliesReportFormatSupport(t *testing.T) { // Two oracles advertise JSON, one advertises nothing: the tally is a count // of advertisements, and an oracle that advertises nothing is not counted. - obsJSON := mustEncodeObs(t, Observation{UnixTimestampNanoseconds: 1, SupportedReportFormats: formatSet(llotypes.ReportFormatJSON)}) - obsNone := mustEncodeObs(t, Observation{UnixTimestampNanoseconds: 1, SupportedReportFormats: formatSet()}) + obsJSON := mustEncodeObs(t, Observation{ObservationTimestampNanoseconds: 1, SupportedReportFormats: formatSet(llotypes.ReportFormatJSON)}) + obsNone := mustEncodeObs(t, Observation{ObservationTimestampNanoseconds: 1, SupportedReportFormats: formatSet()}) _, err = p.StateTransition(ctx, 2, ocrtypes.AttributedQuery{}, []ocrtypes.AttributedObservation{ao(0, obsJSON), ao(1, obsJSON), ao(2, obsNone)}, kv, testBlobs) require.NoError(t, err) require.Equal(t, 2, supportAfter(t, p, kv)[llotypes.ReportFormatJSON]) @@ -1755,7 +1816,7 @@ func Test_StateTransition_ObservationTimestampDoesNotRegress(t *testing.T) { require.NoError(t, err) obsAt := func(ts uint64) []byte { - return mustEncodeObs(t, Observation{UnixTimestampNanoseconds: ts}) + return mustEncodeObs(t, Observation{ObservationTimestampNanoseconds: ts}) } agreedAt := func(seqNr uint64, aos ...ocrtypes.AttributedObservation) uint64 { precBytes, err := p.StateTransition(ctx, seqNr, ocrtypes.AttributedQuery{}, aos, kv, testBlobs) @@ -1824,9 +1885,9 @@ func Test_Observation_StampsTheRoundNotTheSnapshot(t *testing.T) { before := uint64(time.Now().UnixNano()) //nolint:gosec // G115 test clock is positive obsBytes, err := p.Observation(ctx, round, ocrtypes.AttributedQuery{}, kv, nil) require.NoError(t, err) - obs, err := decodeObservation(ctx, obsBytes, bc, nil) + obs, err := fetchBlobsAndDecodeObservation(ctx, obsBytes, bc, nil) require.NoError(t, err) - require.GreaterOrEqual(t, obs.UnixTimestampNanoseconds, before) + require.GreaterOrEqual(t, obs.ObservationTimestampNanoseconds, before) require.Eventually(t, func() bool { return p.pump.Cycles() >= 1 }, tests.WaitTimeout(t), 10*time.Millisecond) } } @@ -1851,10 +1912,10 @@ func Test_StateTransition_CodecSupportAccumulatesAcrossRounds(t *testing.T) { values := protocol.StreamValues{1: protocol.ToDecimal(decimal.NewFromInt(1))} obsJSON := func(ts uint64) []byte { - return mustEncodeObs(t, Observation{UnixTimestampNanoseconds: ts, StreamValues: values, SupportedReportFormats: formatSet(llotypes.ReportFormatJSON)}) + return mustEncodeObs(t, Observation{ObservationTimestampNanoseconds: ts, StreamValues: values, SupportedReportFormats: formatSet(llotypes.ReportFormatJSON)}) } obsNone := func(ts uint64) []byte { - return mustEncodeObs(t, Observation{UnixTimestampNanoseconds: ts, StreamValues: values, SupportedReportFormats: formatSet()}) + return mustEncodeObs(t, Observation{ObservationTimestampNanoseconds: ts, StreamValues: values, SupportedReportFormats: formatSet()}) } // All N oracles advertise JSON. @@ -1895,7 +1956,7 @@ func Test_StateTransition_PrunesUnusedReportFormatSupport(t *testing.T) { for i := 1; i < protocol.MaxObservationSupportedReportFormatsLength; i++ { formats[llotypes.ReportFormat(1_000_000+oracle*1_000+i)] = struct{}{} } - return mustEncodeObs(t, Observation{UnixTimestampNanoseconds: 1, SupportedReportFormats: formats}) + return mustEncodeObs(t, Observation{ObservationTimestampNanoseconds: 1, SupportedReportFormats: formats}) } _, err = p.StateTransition(ctx, 2, ocrtypes.AttributedQuery{}, []ocrtypes.AttributedObservation{ao(0, padded(0)), ao(1, padded(1)), ao(2, padded(2))}, kv, testBlobs) require.NoError(t, err) @@ -1971,8 +2032,8 @@ func Test_Observation_UnverifiableCommittedChannelIsNotFatal(t *testing.T) { _, err := p.StateTransition(ctx, 1, ocrtypes.AttributedQuery{}, []ocrtypes.AttributedObservation{ao(0, nil), ao(1, nil), ao(2, nil)}, kv, testBlobs) require.NoError(t, err) addObs := Observation{ - UnixTimestampNanoseconds: 1_000, - UpdateChannelDefinitions: llotypes.ChannelDefinitions{1: healthy, 2: rejected}, + ObservationTimestampNanoseconds: 1_000, + UpdateChannelDefinitions: llotypes.ChannelDefinitions{1: healthy, 2: rejected}, } addAOs := []ocrtypes.AttributedObservation{} for i := 0; i < 4; i++ { @@ -1997,7 +2058,7 @@ func Test_Observation_UnverifiableCommittedChannelIsNotFatal(t *testing.T) { obsBytes, err := p.Observation(ctx, 3, ocrtypes.AttributedQuery{}, kv, nil) require.NoError(t, err, "a committed definition this build rejects must not halt the node") - obs, err := decodeObservation(ctx, obsBytes, testBlobs, nil) + obs, err := fetchBlobsAndDecodeObservation(ctx, obsBytes, testBlobs, nil) require.NoError(t, err) // The tombstone vote is the recovery path, and it is only cast because the @@ -2033,8 +2094,8 @@ func Test_FullRound_RecoverFromUnverifiableChannel(t *testing.T) { _, err := p.StateTransition(ctx, 1, ocrtypes.AttributedQuery{}, []ocrtypes.AttributedObservation{ao(0, nil), ao(1, nil), ao(2, nil)}, kv, testBlobs) require.NoError(t, err) addObs := Observation{ - UnixTimestampNanoseconds: 1_000, - UpdateChannelDefinitions: llotypes.ChannelDefinitions{1: healthy, 2: rejected}, + ObservationTimestampNanoseconds: 1_000, + UpdateChannelDefinitions: llotypes.ChannelDefinitions{1: healthy, 2: rejected}, } addAOs := []ocrtypes.AttributedObservation{} for i := 0; i < 4; i++ { @@ -2054,9 +2115,9 @@ func Test_FullRound_RecoverFromUnverifiableChannel(t *testing.T) { tombstoned := rejected tombstoned.Tombstone = true tombstoneObs := Observation{ - UnixTimestampNanoseconds: 2_000, - UpdateChannelDefinitions: llotypes.ChannelDefinitions{2: tombstoned}, - StreamValues: protocol.StreamValues{100: protocol.ToDecimal(decimal.NewFromInt(42))}, + ObservationTimestampNanoseconds: 2_000, + UpdateChannelDefinitions: llotypes.ChannelDefinitions{2: tombstoned}, + StreamValues: protocol.StreamValues{100: protocol.ToDecimal(decimal.NewFromInt(42))}, } tombstoneAOs := []ocrtypes.AttributedObservation{} for i := 0; i < 4; i++ { @@ -2070,9 +2131,9 @@ func Test_FullRound_RecoverFromUnverifiableChannel(t *testing.T) { require.True(t, kvChannelDefs(t, kv)[2].Tombstone) removeObs := Observation{ - UnixTimestampNanoseconds: 3_000, - RemoveChannelIDs: map[llotypes.ChannelID]struct{}{2: {}}, - StreamValues: protocol.StreamValues{100: protocol.ToDecimal(decimal.NewFromInt(42))}, + ObservationTimestampNanoseconds: 3_000, + RemoveChannelIDs: map[llotypes.ChannelID]struct{}{2: {}}, + StreamValues: protocol.StreamValues{100: protocol.ToDecimal(decimal.NewFromInt(42))}, } removeAOs := []ocrtypes.AttributedObservation{} for i := 0; i < 4; i++ { @@ -2207,7 +2268,7 @@ func Test_Observation_RetirementCacheErrorsAreNotFatal(t *testing.T) { obsBytes, err := p.Observation(ctx, 2, ocrtypes.AttributedQuery{}, kv, nil) require.NoError(t, err, "a failing retirement cache must not halt the node") - obs, err := decodeObservation(ctx, obsBytes, testBlobs, nil) + obs, err := fetchBlobsAndDecodeObservation(ctx, obsBytes, testBlobs, nil) require.NoError(t, err) require.Empty(t, obs.AttestedPredecessorRetirement) @@ -2321,7 +2382,7 @@ func Test_StateTransition_BackfillValidAfterRequiresPreviousReport(t *testing.T) t.Helper() aos := make([]ocrtypes.AttributedObservation, 0, 4) for i := 0; i < 4; i++ { - obs := Observation{UnixTimestampNanoseconds: ts} + obs := Observation{ObservationTimestampNanoseconds: ts} if shape != nil { shape(&obs) } @@ -2403,7 +2464,7 @@ func Test_StateTransition_BackfillValidAfterRequiresPreviousReport(t *testing.T) require.NoError(t, writeHotState(kv, tenSec, map[llotypes.ChannelID]uint64{targetCID: tenSec, backfillCID: 0}, map[llotypes.ChannelID]bool{targetCID: false, backfillCID: false}, - nil, logger.Test(t))) + nil, nil, logger.Test(t))) // The verdict round. _, err := p.StateTransition(ctx, 2, ocrtypes.AttributedQuery{}, round(t, tenSec+1, tc.shape), kv, testBlobs) @@ -2520,3 +2581,9 @@ func Test_Precursor_ReportedAggregates(t *testing.T) { 999: {llotypes.AggregatorCalculated: one}, }, prec.reportedAggregates(nil)) } + +// loadDefinitions loads defs into c under seqNr as an encoded c/defs record, +// the way StateTransition and Reports load them. +func loadDefinitions(c *protocol.ChannelCache, seqNr uint64, defs llotypes.ChannelDefinitions) (*protocol.ChannelGeneration, error) { + return c.Load(seqNr, func() ([]byte, error) { return encodeChannelState(defs) }, decodeChannelState) +} diff --git a/llo/dev/v31/precursor.go b/llo/dev/v31/precursor.go index ab3340a0..9349a210 100644 --- a/llo/dev/v31/precursor.go +++ b/llo/dev/v31/precursor.go @@ -1,7 +1,6 @@ package llo import ( - "errors" "fmt" "slices" "sort" @@ -20,7 +19,13 @@ import ( type precursor struct { LifeCycleStage llotypes.LifeCycleStage ObservationTimestampNanoseconds uint64 - ChannelDefinitions llotypes.ChannelDefinitions + // ChannelDefinitions are the definitions ChannelState encodes. The wire + // carries ChannelState only, so a decoded precursor leaves this nil and + // Reports resolves it through the channel cache (see definitions). + ChannelDefinitions llotypes.ChannelDefinitions + // ChannelState is the encoded c/defs record ChannelDefinitions were decoded + // from. Nil encodes ChannelDefinitions instead, which yields the same bytes. + ChannelState []byte ValidAfterNanoseconds map[llotypes.ChannelID]uint64 StreamAggregates protocol.StreamAggregates // ChannelStateSeqNr is the c/seqnr of the channel-definitions record that @@ -34,24 +39,36 @@ type precursor struct { ReportableChannelIDs []llotypes.ChannelID } +// encodePrecursor marshals and frames the precursor. libocr digests these +// bytes, so the framing must be deterministic, which encodeFramedPayload is. func encodePrecursor(p precursor) (ocr3_1types.ReportsPlusPrecursor, error) { + raw, err := marshalPrecursor(p) + if err != nil { + return nil, err + } + return framePrecursor(raw) +} + +func framePrecursor(raw []byte) (ocr3_1types.ReportsPlusPrecursor, error) { + return encodeFramedPayload(raw, maxDecompressedPrecursorBytes, ocr3_1types.MaxMaxReportsPlusPrecursorBytes, "precursor") +} + +// marshalPrecursor serializes the precursor deterministically as +// LLOPrecursorProto, before framing. +func marshalPrecursor(p precursor) ([]byte, error) { pb := &protocol.LLOPrecursorProto{ LifeCycleStage: string(p.LifeCycleStage), ObservationTimestampNanoseconds: p.ObservationTimestampNanoseconds, ChannelStateSeqNr: p.ChannelStateSeqNr, + ChannelState: p.ChannelState, } - if len(p.ChannelDefinitions) > 0 { - pb.ChannelDefinitions = make([]*protocol.LLOChannelIDAndDefinitionProto, 0, len(p.ChannelDefinitions)) - for id, cd := range p.ChannelDefinitions { - pb.ChannelDefinitions = append(pb.ChannelDefinitions, &protocol.LLOChannelIDAndDefinitionProto{ - ChannelID: id, - ChannelDefinition: protocol.ChannelDefinitionToProto(cd), - }) + if pb.ChannelState == nil && len(p.ChannelDefinitions) > 0 { + b, err := encodeChannelState(p.ChannelDefinitions) + if err != nil { + return nil, err } - sort.Slice(pb.ChannelDefinitions, func(i, j int) bool { - return pb.ChannelDefinitions[i].ChannelID < pb.ChannelDefinitions[j].ChannelID - }) + pb.ChannelState = b } if len(p.ValidAfterNanoseconds) > 0 { @@ -92,7 +109,9 @@ func encodePrecursor(p precursor) (ocr3_1types.ReportsPlusPrecursor, error) { if len(p.ReportableChannelIDs) > 0 { pb.ReportableChannelIDs = make([]uint32, 0, len(p.ReportableChannelIDs)) for _, id := range p.ReportableChannelIDs { - if _, ok := p.ChannelDefinitions[id]; !ok { + // A decoded precursor holds its definitions only encoded, and + // definitions checks them when Reports resolves them. + if _, ok := p.ChannelDefinitions[id]; !ok && p.ChannelDefinitions != nil { return nil, fmt.Errorf("reportable channel %d has no definition", id) } pb.ReportableChannelIDs = append(pb.ReportableChannelIDs, id) @@ -108,46 +127,43 @@ func encodePrecursor(p precursor) (ocr3_1types.ReportsPlusPrecursor, error) { } // decodePrecursor decodes a precursor this oracle produced, or one fetched from -// a peer that libocr verified against the certified digest and size limit. Its -// channel definitions are the committed set, so the per-definition stream and -// opts caps are not applied here: they are admission-only, and rejecting a -// committed definition would fail Reports on every oracle. +// a peer that libocr verified against the certified digest and size limit. The +// channel definitions are left encoded in ChannelState: Reports resolves them +// through the channel cache, which in steady state already holds them. They are +// the committed set, so the per-definition stream and opts caps are not applied +// to them: they are admission-only, and rejecting a committed definition would +// fail Reports on every oracle. func decodePrecursor(b ocr3_1types.ReportsPlusPrecursor) (precursor, error) { + raw, err := decodeFramedPayload(b, maxDecompressedPrecursorBytes, "precursor") + if err != nil { + return precursor{}, err + } pb := &protocol.LLOPrecursorProto{} - if err := proto.Unmarshal(b, pb); err != nil { + if err := proto.Unmarshal(raw, pb); err != nil { return precursor{}, fmt.Errorf("unmarshal precursor: %w", err) } p := precursor{ LifeCycleStage: llotypes.LifeCycleStage(pb.LifeCycleStage), ObservationTimestampNanoseconds: pb.ObservationTimestampNanoseconds, ChannelStateSeqNr: pb.ChannelStateSeqNr, - ChannelDefinitions: llotypes.ChannelDefinitions{}, + ChannelState: pb.ChannelState, ValidAfterNanoseconds: map[llotypes.ChannelID]uint64{}, StreamAggregates: protocol.StreamAggregates{}, } - for _, cd := range pb.ChannelDefinitions { - if cd.ChannelDefinition == nil { - return precursor{}, errors.New("nil channel definition in precursor") - } - p.ChannelDefinitions[cd.ChannelID] = protocol.ChannelDefinitionFromProto(cd.ChannelDefinition) - } for _, va := range pb.ValidAfterNanoseconds { p.ValidAfterNanoseconds[va.ChannelID] = va.ValidAfterNanoseconds } - // Every reportable channel must have a definition and appear once, in - // ascending order, so Reports emits each at most once. The collections are - // otherwise left unbounded on purpose: the precursor is certified state, - // libocr bounds its size, and the promotion round legitimately carries more - // validAfter entries than channels. + // Every reportable channel must appear once, in ascending order, so Reports + // emits each at most once. definitions checks that each has a definition. + // The collections are otherwise left unbounded on purpose: the precursor is + // certified state, libocr bounds its size, and the promotion round + // legitimately carries more validAfter entries than channels. if len(pb.ReportableChannelIDs) > 0 { p.ReportableChannelIDs = make([]llotypes.ChannelID, 0, len(pb.ReportableChannelIDs)) for i, id := range pb.ReportableChannelIDs { if i > 0 && id <= pb.ReportableChannelIDs[i-1] { return precursor{}, fmt.Errorf("reportable channel IDs not strictly ascending at index %d", i) } - if _, ok := p.ChannelDefinitions[id]; !ok { - return precursor{}, fmt.Errorf("reportable channel %d has no definition", id) - } p.ReportableChannelIDs = append(p.ReportableChannelIDs, id) } } @@ -164,6 +180,26 @@ func decodePrecursor(b ocr3_1types.ReportsPlusPrecursor) (precursor, error) { return p, nil } +// definitions resolves the precursor's channel definitions through cache, +// decoding ChannelState only on a miss, and sets ChannelDefinitions to them. +// The generation for ChannelStateSeqNr is a pure function of that sequence +// number, so a hit serves the same definitions ChannelState decodes to. The +// returned generation carries the opts decoded from exactly these definitions. +func (o *precursor) definitions(cache *protocol.ChannelCache) (*protocol.ChannelGeneration, error) { + gen, err := cache.Load(o.ChannelStateSeqNr, func() ([]byte, error) { return o.ChannelState, nil }, decodeChannelState) + if err != nil { + return nil, fmt.Errorf("error loading channel generation: %w", err) + } + defs := gen.Definitions() + for _, id := range o.ReportableChannelIDs { + if _, ok := defs[id]; !ok { + return nil, fmt.Errorf("reportable channel %d has no definition", id) + } + } + o.ChannelDefinitions = defs + return gen, nil +} + // reportedAggregates returns the aggregates the reportable channels report, // which is all Reports reads from StreamAggregates. Backfill reports carry // their values in the backfill opts. diff --git a/llo/dev/v31/precursor_metrics.go b/llo/dev/v31/precursor_metrics.go new file mode 100644 index 00000000..b2843152 --- /dev/null +++ b/llo/dev/v31/precursor_metrics.go @@ -0,0 +1,43 @@ +package llo + +import ( + "strconv" + + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/promauto" +) + +// precursorSizeMetric exports the size of the precursor this node produced in +// its latest state transition, before and after framing. Their ratio is the +// compression the precursor gets in practice. Node-local, with no effect on +// consensus. +var precursorSizeMetric = promauto.NewGaugeVec(prometheus.GaugeOpts{ + Namespace: "llo", + Subsystem: "precursor", + Name: "size_bytes", + Help: "Size of the latest precursor: raw is the marshaled proto, framed is what libocr digests, stores and serves to peers.", +}, []string{"donID", "encoding"}) + +// precursorMetrics holds the label children for one DON, resolved once at +// plugin construction. +type precursorMetrics struct { + raw, framed prometheus.Gauge +} + +func newPrecursorMetrics(donID uint32) *precursorMetrics { + don := strconv.FormatUint(uint64(donID), 10) + return &precursorMetrics{ + raw: precursorSizeMetric.WithLabelValues(don, "raw"), + framed: precursorSizeMetric.WithLabelValues(don, "framed"), + } +} + +// record exports one precursor's sizes. A nil receiver records nothing, for +// plugins built without the factory. +func (m *precursorMetrics) record(raw, framed int) { + if m == nil { + return + } + m.raw.Set(float64(raw)) + m.framed.Set(float64(framed)) +} diff --git a/llo/dev/v31/precursor_metrics_test.go b/llo/dev/v31/precursor_metrics_test.go new file mode 100644 index 00000000..fd694f21 --- /dev/null +++ b/llo/dev/v31/precursor_metrics_test.go @@ -0,0 +1,34 @@ +package llo + +import ( + "testing" + + "github.com/prometheus/client_golang/prometheus" + dto "github.com/prometheus/client_model/go" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func gaugeValue(t *testing.T, g prometheus.Gauge) float64 { + t.Helper() + var m dto.Metric + require.NoError(t, g.Write(&m)) + return m.GetGauge().GetValue() +} + +func Test_Plugin_encodePrecursor_RecordsSizes(t *testing.T) { + p := &Plugin{precursorMetrics: newPrecursorMetrics(4242)} + raw, err := marshalPrecursor(goldenPrecursor()) + require.NoError(t, err) + + framed, err := p.encodePrecursor(goldenPrecursor()) + require.NoError(t, err) + + assert.InDelta(t, float64(len(raw)), gaugeValue(t, precursorSizeMetric.WithLabelValues("4242", "raw")), 0) + assert.InDelta(t, float64(len(framed)), gaugeValue(t, precursorSizeMetric.WithLabelValues("4242", "framed")), 0) +} + +func Test_Plugin_encodePrecursor_NilMetrics(t *testing.T) { + _, err := (&Plugin{}).encodePrecursor(goldenPrecursor()) + require.NoError(t, err) +} diff --git a/llo/dev/v31/reports.go b/llo/dev/v31/reports.go index 4a14f8bc..95d3ad14 100644 --- a/llo/dev/v31/reports.go +++ b/llo/dev/v31/reports.go @@ -32,11 +32,9 @@ func (p *Plugin) Reports(ctx context.Context, seqNr uint64, rawPrecursor ocr3_1t // behind) the definitions being reported - not when a StateTransition for a // later seqNr is running concurrently, and not after a restart, where no // StateTransition ran on this node to populate the cache. - gen, err := p.ChannelCache.Load(out.ChannelStateSeqNr, func() (llotypes.ChannelDefinitions, error) { - return out.ChannelDefinitions, nil - }) + gen, err := out.definitions(p.ChannelCache) if err != nil { - return nil, fmt.Errorf("error loading channel generation: %w", err) + return nil, err } channelOpts := gen.Opts() diff --git a/llo/dev/v31/restart_test.go b/llo/dev/v31/restart_test.go index 814c8a8e..0a7e8199 100644 --- a/llo/dev/v31/restart_test.go +++ b/llo/dev/v31/restart_test.go @@ -83,7 +83,7 @@ func Test_Restart_ColdKVRebuilds(t *testing.T) { // Values arriving before the channel is re-voted are tolerated and produce // nothing: there is no channel requiring the stream, so nothing is stored. - _, err := after.StateTransition(ctx, 1, ocrtypes.AttributedQuery{}, valueRound(t, 10_000, 1), cold, testBlobs) + _, err := after.StateTransition(ctx, 1, ocrtypes.AttributedQuery{}, emptyRound(), cold, testBlobs) require.NoError(t, err) require.Nil(t, readHistory(t, cold, 100, llotypes.AggregatorMedian)) require.False(t, reportedFlag(t, cold, 1)) diff --git a/llo/dev/v31/statetransition.go b/llo/dev/v31/statetransition.go index fe1aa853..20b0e950 100644 --- a/llo/dev/v31/statetransition.go +++ b/llo/dev/v31/statetransition.go @@ -48,12 +48,19 @@ import ( // KeyValueState and to the deferred-definitions rule above (v30 applies // definition changes within the same round). func (p *Plugin) StateTransition(ctx context.Context, seqNr uint64, _ ocrtypes.AttributedQuery, aos []ocrtypes.AttributedObservation, kvRW ocr3_1types.KeyValueStateReadWriter, bf ocr3_1types.BlobFetcher) (ocr3_1types.ReportsPlusPrecursor, error) { - if len(aos) < 2*p.F+1 { - return nil, fmt.Errorf("invariant violation: expected at least 2f+1 attributed observations, got %d (f: %d)", len(aos), p.F) + if !p.hasObservationQuorum(aos) { + return nil, fmt.Errorf("invariant violation: %d attributed observations do not reach the observation quorum (n: %d, f: %d)", len(aos), p.N, p.F) } // Initial round: establish the lifecycle stage and initial states, if seqNr <= 1 { + // libocr only passes observations this oracle's ValidateObservation + // accepted, and round 1 accepts only empty ones. + for _, ao := range aos { + if len(ao.Observation) != 0 { + return nil, fmt.Errorf("invariant violation: non-empty observation from oracle %v in round %d", ao.Observer, seqNr) + } + } stage := protocol.LifeCycleStageProduction if p.PredecessorConfigDigest != nil { stage = protocol.LifeCycleStageStaging @@ -64,10 +71,10 @@ func (p *Plugin) StateTransition(ctx context.Context, seqNr uint64, _ ocrtypes.A if err := writeChannelState(kvRW, seqNr, nil); err != nil { return nil, err } - if err := writeHotState(kvRW, 0, nil, nil, nil, p.Logger); err != nil { + if err := writeHotState(kvRW, 0, nil, nil, nil, nil, p.Logger); err != nil { return nil, err } - return encodePrecursor(precursor{LifeCycleStage: stage}) + return p.encodePrecursor(precursor{LifeCycleStage: stage}) } prev, err := loadKVState(kvRW, p.ChannelCache, p.Logger) @@ -75,13 +82,10 @@ func (p *Plugin) StateTransition(ctx context.Context, seqNr uint64, _ ocrtypes.A return nil, fmt.Errorf("failed to load KV state: %w", err) } - tally, err := p.decodeObservations(ctx, aos, bf, p.BlobPayloads.round(seqNr), p.collectAttributedObservations(seqNr)) + tally, err := p.fetchBlobsDecodeValidateAndTallyObservations(ctx, seqNr, aos, bf, p.collectAttributedObservations(seqNr)) if err != nil { return nil, err } - if len(tally.timestampsNanoseconds) < 2*p.F+1 { - return nil, fmt.Errorf("invariant violation: expected at least 2f+1 decoded observations, got %d (f: %d)", len(tally.timestampsNanoseconds), p.F) - } // Verifying an attested predecessor retirement report needs the // predecessor's signer set, which is node-local. Agree on it from this @@ -103,11 +107,15 @@ func (p *Plugin) StateTransition(ctx context.Context, seqNr uint64, _ ocrtypes.A out := precursor{ ObservationTimestampNanoseconds: p.agreedObservationTimestamp(tally.timestampsNanoseconds, prev.observationTimestampNs, seqNr), ChannelDefinitions: effective, + ChannelState: prev.channelState, ChannelStateSeqNr: prev.channelStateSeqNr, ValidAfterNanoseconds: map[llotypes.ChannelID]uint64{}, StreamAggregates: protocol.StreamAggregates{}, } p.warnIfAheadOfLocalClock(out.ObservationTimestampNanoseconds, seqNr) + // The window ends with this round, so a contribution gathered this round + // resolves to this round's agreed timestamp. + agreedTimestamps := appendAgreedTimestamp(prev.recentAgreedTimestamps, out.ObservationTimestampNanoseconds) // Lifecycle stage & promotion. promotedValidAfter := map[llotypes.ChannelID]uint64(nil) @@ -223,8 +231,20 @@ func (p *Plugin) StateTransition(ctx context.Context, seqNr uint64, _ ocrtypes.A // the r/agg record). carryForward accumulates the values to persist for the // next round. Runs over the effective set, which is what was observed. The // agreed value of every pair history requires is recorded as it is computed. + // + // Stale contributions are left out first, per stream, from replicated data + // only. See freshness.go. + streamValues, freshness := selectFreshContributions(tally.streamObservations, seqNr, out.ObservationTimestampNanoseconds, + agreedTimestamps, roundIntervalEstimate(agreedTimestamps, p.MinRoundInterval), p.minContributions()) + if freshness.any() && p.Config.VerboseLogging { + p.Logger.Debugw("Rejected stale stream values", "seqNr", seqNr, + "streamsFiltered", freshness.streamsFiltered, "streamsFallenBack", freshness.streamsFallenBack, + "contributionsStale", freshness.contributionsStale, "staleByRounds", freshness.staleByRounds, + "staleByTime", freshness.staleByTime, "staleBeforeWindow", freshness.staleBeforeWindow, + "maxStreamValueAge", freshness.maxStreamValueAge, "roundInterval", freshness.roundInterval) + } carryForward := map[llotypes.StreamID]map[llotypes.Aggregator]*protocol.TimestampedStreamValue{} - if err := p.aggregate(prev.carryForward, carryForward, effective, tally.streamObservations, out.StreamAggregates, + if err := p.aggregate(prev.carryForward, carryForward, effective, streamValues, out.StreamAggregates, history, requirements, out.ObservationTimestampNanoseconds); err != nil { return nil, err } @@ -250,7 +270,7 @@ func (p *Plugin) StateTransition(ctx context.Context, seqNr uint64, _ ocrtypes.A unreportable.log(p.Logger, "StateTransition", seqNr) // Flush KV mutations. - if err := p.flushKV(kvRW, seqNr, prev, out, pending, codecSupport, carryForward, history); err != nil { + if err := p.flushKV(kvRW, seqNr, prev, out, pending, codecSupport, carryForward, agreedTimestamps, history); err != nil { return nil, err } @@ -261,12 +281,27 @@ func (p *Plugin) StateTransition(ctx context.Context, seqNr uint64, _ ocrtypes.A // written. Node-local observation only; nothing reads these back. p.captureHistoryTelemetry(history, requirements) p.captureInsufficientHistory(effective, prev.opts, history) - p.captureOutcomeTelemetry(out, seqNr) + p.freshnessMetrics.record(freshness) + p.captureOutcomeTelemetry(out, seqNr, freshness) p.captureAttributedObservationTelemetry(out, seqNr, tally.attributed) // After telemetry, which reports every aggregate. out.StreamAggregates = out.reportedAggregates(prev.opts) - return encodePrecursor(out) + return p.encodePrecursor(out) +} + +// encodePrecursor encodes the round's precursor and records its sizes. +func (p *Plugin) encodePrecursor(out precursor) (ocr3_1types.ReportsPlusPrecursor, error) { + raw, err := marshalPrecursor(out) + if err != nil { + return nil, err + } + framed, err := framePrecursor(raw) + if err != nil { + return nil, err + } + p.precursorMetrics.record(len(raw), len(framed)) + return framed, nil } // observationTally is what the round's observations add up to: the votes, @@ -285,10 +320,12 @@ type observationTally struct { updateChannelDefinitionsByHash map[[32]byte]protocol.ChannelDefinitionWithID updateChannelVotesByHash map[[32]byte]int // supportedFormatsByOracle[oracleID] is the formats that oracle advertised - // this round, deduped by decodeObservation. It is merged into the persisted + // this round, deduped by fetchBlobsAndDecodeObservation. It is merged into the persisted // per-oracle record rather than counted here: see writeCodecSupport. supportedFormatsByOracle map[commontypes.OracleID]map[llotypes.ReportFormat]struct{} - streamObservations map[llotypes.StreamID][]protocol.StreamValue + // streamObservations keeps each oracle's contribution apart, so freshness + // can be judged per contribution before the values are aggregated. + streamObservations map[llotypes.StreamID][]streamContribution // attributed is every observation as decoded, in aos order. Collected only // for attributed observation telemetry. attributed []attributedObservation @@ -300,7 +337,13 @@ func (t observationTally) hasChannelVotes() bool { return len(t.removeChannelVotesByID) > 0 || len(t.updateChannelVotesByHash) > 0 } -func (p *Plugin) decodeObservations(ctx context.Context, aos []ocrtypes.AttributedObservation, bf ocr3_1types.BlobFetcher, memo *roundBlobPayloads, collect bool) (observationTally, error) { +// fetchBlobsDecodeValidateAndTallyObservations fetches every blob, decodes and validates each +// observation, then tallies votes and values. Every observation must pass the +// checks ValidateObservation ran on it: a decode failure here means the leader +// proposed an observation this build rejects, so the round fails rather than +// aggregating over a sample smaller than the quorum it was accepted on. A +// blob fetch failure is node-local and fails the round for this oracle only. +func (p *Plugin) fetchBlobsDecodeValidateAndTallyObservations(ctx context.Context, seqNr uint64, aos []ocrtypes.AttributedObservation, bf ocr3_1types.BlobFetcher, collect bool) (observationTally, error) { tally := observationTally{ predConfigsByHash: make(map[[32]byte]predecessorConfig), predConfigVotesByHash: make(map[[32]byte]int), @@ -308,7 +351,7 @@ func (p *Plugin) decodeObservations(ctx context.Context, aos []ocrtypes.Attribut updateChannelDefinitionsByHash: make(map[[32]byte]protocol.ChannelDefinitionWithID), updateChannelVotesByHash: make(map[[32]byte]int), supportedFormatsByOracle: make(map[commontypes.OracleID]map[llotypes.ReportFormat]struct{}), - streamObservations: make(map[llotypes.StreamID][]protocol.StreamValue), + streamObservations: make(map[llotypes.StreamID][]streamContribution), } // Decode concurrently: each observation may reference blobs that are not yet @@ -322,7 +365,7 @@ func (p *Plugin) decodeObservations(ctx context.Context, aos []ocrtypes.Attribut for i, ao := range aos { go func() { defer wg.Done() - decoded[i], decodeErrs[i] = decodeObservation(ctx, ao.Observation, bf, memo) + decoded[i], decodeErrs[i] = p.fetchBlobsDecodeAndValidateObservation(ctx, seqNr, ao, bf) }() } wg.Wait() @@ -342,14 +385,13 @@ func (p *Plugin) decodeObservations(ctx context.Context, aos []ocrtypes.Attribut // commit and a new epoch starts it over. return observationTally{}, fmt.Errorf("failed to fetch blob for observation from oracle %v: %w", ao.Observer, derr) } - // Unreachable while libocr runs ValidateObservation, which decodes - // the same bytes, before StateTransition. Drop rather than fail, and - // let the quorum check in StateTransition catch a shrunk sample. - p.Logger.Warnw("ignoring invalid observation", "oracleID", ao.Observer, "error", derr) - if collect { - tally.attributed = append(tally.attributed, attributedObservation{observer: ao.Observer, decodeErr: derr}) - } - continue + // Unreachable while every oracle runs the same ValidateObservation, + // which ran these checks on the same bytes before StateTransition. + // Reachable under version skew, where the leader accepted what this + // build rejects. Dropping would fork: oracles on the leader's build + // keep the observation. Failing stalls this oracle only, and the + // round is retried under a new leader if more than f fail. + return observationTally{}, fmt.Errorf("invariant violation: observation from oracle %v accepted by the leader fails validation on this oracle: %w", ao.Observer, derr) } if collect { tally.attributed = append(tally.attributed, attributedObservation{observer: ao.Observer, obs: observation}) @@ -370,7 +412,7 @@ func (p *Plugin) decodeObservations(ctx context.Context, aos []ocrtypes.Attribut if observation.ShouldRetire { tally.shouldRetireVotes++ } - tally.timestampsNanoseconds = append(tally.timestampsNanoseconds, observation.UnixTimestampNanoseconds) + tally.timestampsNanoseconds = append(tally.timestampsNanoseconds, observation.ObservationTimestampNanoseconds) // Recording the whole advertised set (including an empty one) // makes this round's advertisement replace that oracle's last, so an @@ -389,7 +431,7 @@ func (p *Plugin) decodeObservations(ctx context.Context, aos []ocrtypes.Attribut if sv == nil { continue } - tally.streamObservations[id] = append(tally.streamObservations[id], sv) + tally.streamObservations[id] = append(tally.streamObservations[id], streamContribution{value: sv, cycleStartSeqNr: observation.CycleStartSeqNr}) } } return tally, nil @@ -749,6 +791,7 @@ func (p *Plugin) flushKV( pending llotypes.ChannelDefinitions, codecSupport map[commontypes.OracleID]map[llotypes.ReportFormat]struct{}, carryForward map[llotypes.StreamID]map[llotypes.Aggregator]*protocol.TimestampedStreamValue, + recentAgreedTimestamps []uint64, history *historyStore, ) error { if out.LifeCycleStage != prev.lifeCycleStage { @@ -793,7 +836,7 @@ func (p *Plugin) flushKV( } } - return writeHotState(kvRW, out.ObservationTimestampNanoseconds, out.ValidAfterNanoseconds, reportable, carryForward, p.Logger) + return writeHotState(kvRW, out.ObservationTimestampNanoseconds, out.ValidAfterNanoseconds, reportable, carryForward, recentAgreedTimestamps, p.Logger) } // channelDefinitionsChanged reports whether the channel set or any individual diff --git a/llo/dev/v31/statetransition_bench_test.go b/llo/dev/v31/statetransition_bench_test.go index 0098c322..53d10997 100644 --- a/llo/dev/v31/statetransition_bench_test.go +++ b/llo/dev/v31/statetransition_bench_test.go @@ -121,7 +121,7 @@ func benchObservationHandles(b *testing.B, c stateTransitionBenchCase, blobs *ll for s := range c.streams + 2 { values[llotypes.StreamID(s+1)] = protocol.ToDecimal(decimal.New(int64(1_000_000_000+s*1_000+o), -8)) //nolint:gosec // G115 bounded by the case } - payload, err := marshalStreamValues(values) + payload, err := marshalStreamValues(values, 1) require.NoError(b, err) handle, err := blobs.BroadcastBlob(context.Background(), payload, ocr3_1types.BlobExpirationHintSequenceNumber{SeqNr: 0}) require.NoError(b, err) @@ -145,8 +145,8 @@ func BenchmarkStateTransition(b *testing.B) { aos := make([]ocrtypes.AttributedObservation, c.n) for o := range c.n { obs, err := encodeObservation(Observation{ - UnixTimestampNanoseconds: ts, - SupportedReportFormats: formatSet(llotypes.ReportFormatEVMABIEncodeUnpacked), + ObservationTimestampNanoseconds: ts, + SupportedReportFormats: formatSet(llotypes.ReportFormatEVMABIEncodeUnpacked), }, [][]byte{handles[o]}) require.NoError(b, err) aos[o] = ao(o, obs) @@ -156,9 +156,14 @@ func BenchmarkStateTransition(b *testing.B) { // Bootstrap, then install the channels directly: voting them in // takes MaxObservationUpdateChannelDefinitionsLength per round. + // Round 1 accepts only empty observations. kv := newMemKV() seqNr := uint64(1) - _, err := p.StateTransition(ctx, seqNr, ocrtypes.AttributedQuery{}, round(), kv, blobs) + bootstrap := make([]ocrtypes.AttributedObservation, c.n) + for o := range c.n { + bootstrap[o] = ao(o, nil) + } + _, err := p.StateTransition(ctx, seqNr, ocrtypes.AttributedQuery{}, bootstrap, kv, blobs) require.NoError(b, err) seqNr++ require.NoError(b, writeChannelState(kv, seqNr, benchChannelDefinitions(c))) @@ -188,6 +193,9 @@ func BenchmarkStateTransition(b *testing.B) { } seqNr++ } + // The hot state is rewritten every round, so its stored size is + // the per-round KV write the benchmark pays for. + b.ReportMetric(float64(len(kv.m[string(keyHotState)])), "hotStateBytes") }) } } diff --git a/llo/dev/v31/telemetry.go b/llo/dev/v31/telemetry.go index 956c99fc..7ed33498 100644 --- a/llo/dev/v31/telemetry.go +++ b/llo/dev/v31/telemetry.go @@ -24,11 +24,11 @@ import ( // captureOutcomeTelemetry emits the outcome of rounds whose stage emits // telemetry, when this oracle is one of the f+1 telemetry emitters for seqNr. // Every oracle computes the same outcome, so f+1 copies suffice. -func (p *Plugin) captureOutcomeTelemetry(out precursor, seqNr uint64) { +func (p *Plugin) captureOutcomeTelemetry(out precursor, seqNr uint64, freshness freshnessStats) { if p.OutcomeTelemetryCh == nil || !p.emitsTelemetry(out.LifeCycleStage) || !p.isTelemetryEmitter(seqNr) { return } - ot, err := makeOutcomeTelemetry(out, p.ConfigDigest, seqNr, p.DonID, p.minContributions()) + ot, err := makeOutcomeTelemetry(out, p.ConfigDigest, seqNr, p.DonID, p.minContributions(), freshness) if err != nil { p.Logger.Warnw("Error making outcome telemetry", "err", err) return @@ -40,7 +40,7 @@ func (p *Plugin) captureOutcomeTelemetry(out precursor, seqNr uint64) { } } -func makeOutcomeTelemetry(out precursor, configDigest ocrtypes.ConfigDigest, seqNr uint64, donID uint32, minContributions int) (*protocol.LLOOutcomeTelemetry, error) { +func makeOutcomeTelemetry(out precursor, configDigest ocrtypes.ConfigDigest, seqNr uint64, donID uint32, minContributions int, freshness freshnessStats) (*protocol.LLOOutcomeTelemetry, error) { ot := &protocol.LLOOutcomeTelemetry{ LifeCycleStage: string(out.LifeCycleStage), ObservationTimestampNanoseconds: out.ObservationTimestampNanoseconds, @@ -51,6 +51,9 @@ func makeOutcomeTelemetry(out precursor, configDigest ocrtypes.ConfigDigest, seq ConfigDigest: configDigest[:], DonId: donID, MinContributions: uint32(minContributions), + StreamsFiltered: uint32(freshness.streamsFiltered), //nolint:gosec // G115 bounded by stream count + StreamsFallenBack: uint32(freshness.streamsFallenBack), //nolint:gosec // G115 bounded by stream count + ContributionsStale: uint32(freshness.contributionsStale), //nolint:gosec // G115 bounded by N times streams } for id, cd := range out.ChannelDefinitions { ot.ChannelDefinitions[id] = protocol.ChannelDefinitionToProto(cd) @@ -145,12 +148,11 @@ const maxAttributedObservationTelemetryBytes = 1 << 20 const attributedObservationTelemetryQueueSize = 8 // attributedObservation is one entry of the round attributed observations, as -// decoded by StateTransition. decodeErr is set when the observation was dropped -// as invalid. +// decoded by StateTransition. Every entry decoded: an observation that fails +// to decode fails the round, which emits no telemetry. type attributedObservation struct { - observer commontypes.OracleID - obs Observation - decodeErr error + observer commontypes.OracleID + obs Observation } type attributedObservationRound struct { @@ -293,16 +295,12 @@ func (t *attributedObservationTelemeter) makeTelemetry(seqNr, agreedTs uint64, a DonId: t.donID, Observer: uint32(ao.observer), Emitter: uint32(t.emitter), - OracleObservationTimestampNanoseconds: ao.obs.UnixTimestampNanoseconds, + OracleObservationTimestampNanoseconds: ao.obs.ObservationTimestampNanoseconds, AgreedObservationTimestampNanoseconds: agreedTs, } } first := header() - if ao.decodeErr != nil { - first.DecodeError = proto.String(ao.decodeErr.Error()) - return []*protocol.LLOAttributedObservationTelemetry{first} - } if len(ao.obs.RemoveChannelIDs) > 0 { first.RemoveChannelIds = make([]uint32, 0, len(ao.obs.RemoveChannelIDs)) for id := range ao.obs.RemoveChannelIDs { diff --git a/llo/dev/v31/telemetry_test.go b/llo/dev/v31/telemetry_test.go index 6a9ad1bb..a9eb611c 100644 --- a/llo/dev/v31/telemetry_test.go +++ b/llo/dev/v31/telemetry_test.go @@ -1,7 +1,6 @@ package llo import ( - "errors" "sort" "sync" "sync/atomic" @@ -102,9 +101,9 @@ func Test_AttributedObservationTelemetry_StateTransition(t *testing.T) { channelDef := llotypes.ChannelDefinition{ReportFormat: llotypes.ReportFormatJSON, Streams: []llotypes.Stream{{StreamID: 100, Aggregator: llotypes.AggregatorMedian}}} obsAt := func(observer int, ts uint64) Observation { return Observation{ - UnixTimestampNanoseconds: ts, - RemoveChannelIDs: map[llotypes.ChannelID]struct{}{9: {}}, - UpdateChannelDefinitions: llotypes.ChannelDefinitions{1: channelDef}, + ObservationTimestampNanoseconds: ts, + RemoveChannelIDs: map[llotypes.ChannelID]struct{}{9: {}}, + UpdateChannelDefinitions: llotypes.ChannelDefinitions{1: channelDef}, StreamValues: protocol.StreamValues{ 100: protocol.ToDecimal(decimal.NewFromInt(int64(40 + observer))), 101: protocol.ToDecimal(decimal.NewFromInt(int64(50 + observer))), @@ -178,7 +177,7 @@ func Test_AttributedObservationTelemetry_StateTransition(t *testing.T) { require.Equal(t, out.ObservationTimestampNanoseconds, m.AgreedObservationTimestampNanoseconds) }) - t.Run("invalid observation carries only the decode error", func(t *testing.T) { + t.Run("invalid observation fails the round and emits nothing", func(t *testing.T) { p.OracleID = 1 // emitter for seqNr 5 aos := []ocrtypes.AttributedObservation{ ao(0, mustEncodeObs(t, obsAt(0, 3000))), @@ -187,20 +186,8 @@ func Test_AttributedObservationTelemetry_StateTransition(t *testing.T) { ao(3, []byte{0x7f}), } _, err := p.StateTransition(ctx, 5, ocrtypes.AttributedQuery{}, aos, kv, testBlobs) - require.NoError(t, err) - r := requireAORound(t, tel, true) - require.Len(t, r.aos, 4) - - bad := r.aos[3] - require.Equal(t, commontypes.OracleID(3), bad.observer) - msgs := tel.makeTelemetry(r.seqNr, r.agreedObservationTimestampNanos, bad) - require.Len(t, msgs, 1) - require.NotNil(t, msgs[0].DecodeError) - require.Contains(t, *msgs[0].DecodeError, "unknown observation wire version") - require.Empty(t, msgs[0].StreamValues) - require.Empty(t, msgs[0].RemoveChannelIds) - require.Empty(t, msgs[0].UpdateChannelDefinitions) - require.Zero(t, msgs[0].OracleObservationTimestampNanoseconds) + require.ErrorContains(t, err, "unknown observation wire version") + requireAORound(t, tel, false) }) t.Run("aborted round emits nothing", func(t *testing.T) { @@ -261,16 +248,16 @@ func testPluginTelemetryLifecycle(t *testing.T, stagingTelemetry bool) { ts += handoverTickNanos emitterRound(old) old.round(Observation{ - UnixTimestampNanoseconds: ts, - UpdateChannelDefinitions: llotypes.ChannelDefinitions{handoverChannelID: handoverChannel()}, - StreamValues: handoverStreamValues(), + ObservationTimestampNanoseconds: ts, + UpdateChannelDefinitions: llotypes.ChannelDefinitions{handoverChannelID: handoverChannel()}, + StreamValues: handoverStreamValues(), }) requireRoundTelemetry(t, oldTel, oldOT, protocol.LifeCycleStageProduction) for range 2 { ts += handoverTickNanos emitterRound(old) - old.round(Observation{UnixTimestampNanoseconds: ts, StreamValues: handoverStreamValues()}) + old.round(Observation{ObservationTimestampNanoseconds: ts, StreamValues: handoverStreamValues()}) requireRoundTelemetry(t, oldTel, oldOT, protocol.LifeCycleStageProduction) } @@ -295,28 +282,28 @@ func testPluginTelemetryLifecycle(t *testing.T, stagingTelemetry bool) { stagingTS += handoverTickNanos emitterRound(newInst) newInst.round(Observation{ - UnixTimestampNanoseconds: stagingTS, - UpdateChannelDefinitions: llotypes.ChannelDefinitions{handoverChannelID: handoverChannel()}, - StreamValues: handoverStreamValues(), + ObservationTimestampNanoseconds: stagingTS, + UpdateChannelDefinitions: llotypes.ChannelDefinitions{handoverChannelID: handoverChannel()}, + StreamValues: handoverStreamValues(), }) requireRoundTelemetry(t, newTel, newOT, stagingStage) stagingTS += handoverTickNanos emitterRound(newInst) - newInst.round(Observation{UnixTimestampNanoseconds: stagingTS, StreamValues: handoverStreamValues()}) + newInst.round(Observation{ObservationTimestampNanoseconds: stagingTS, StreamValues: handoverStreamValues()}) requireRoundTelemetry(t, newTel, newOT, stagingStage) // Retirement round: the outcome is retired, so nothing is emitted. old.p.ShouldRetireCache = &mockShouldRetireCache{retire: true} ts += handoverTickNanos emitterRound(old) - old.round(Observation{UnixTimestampNanoseconds: ts, ShouldRetire: true, StreamValues: handoverStreamValues()}) + old.round(Observation{ObservationTimestampNanoseconds: ts, ShouldRetire: true, StreamValues: handoverStreamValues()}) require.Equal(t, protocol.LifeCycleStageRetired, old.lifeCycleStage()) requireRoundTelemetry(t, oldTel, oldOT, "") ts += handoverTickNanos emitterRound(old) - old.round(Observation{UnixTimestampNanoseconds: ts, StreamValues: handoverStreamValues()}) + old.round(Observation{ObservationTimestampNanoseconds: ts, StreamValues: handoverStreamValues()}) requireRoundTelemetry(t, oldTel, oldOT, "") // Promotion round: the outcome is production, so it emits. @@ -328,18 +315,18 @@ func testPluginTelemetryLifecycle(t *testing.T, stagingTelemetry bool) { stagingTS += handoverTickNanos emitterRound(newInst) newInst.round(Observation{ - UnixTimestampNanoseconds: stagingTS, - AttestedPredecessorRetirement: attestedBytes, - PredecessorSigners: handoverPredecessorSigners, - PredecessorF: 1, - StreamValues: handoverStreamValues(), + ObservationTimestampNanoseconds: stagingTS, + AttestedPredecessorRetirement: attestedBytes, + PredecessorSigners: handoverPredecessorSigners, + PredecessorF: 1, + StreamValues: handoverStreamValues(), }) require.Equal(t, protocol.LifeCycleStageProduction, newInst.lifeCycleStage()) requireRoundTelemetry(t, newTel, newOT, protocol.LifeCycleStageProduction) stagingTS += handoverTickNanos emitterRound(newInst) - newInst.round(Observation{UnixTimestampNanoseconds: stagingTS, StreamValues: handoverStreamValues()}) + newInst.round(Observation{ObservationTimestampNanoseconds: stagingTS, StreamValues: handoverStreamValues()}) requireRoundTelemetry(t, newTel, newOT, protocol.LifeCycleStageProduction) } @@ -362,9 +349,9 @@ func Test_AttributedObservationTelemetry_Deterministic(t *testing.T) { var b []byte if seqNr > 1 { b = mustEncodeObs(t, Observation{ - UnixTimestampNanoseconds: seqNr * 1000, - UpdateChannelDefinitions: llotypes.ChannelDefinitions{1: channelDef}, - StreamValues: protocol.StreamValues{100: protocol.ToDecimal(decimal.NewFromInt(int64(i)))}, + ObservationTimestampNanoseconds: seqNr * 1000, + UpdateChannelDefinitions: llotypes.ChannelDefinitions{1: channelDef}, + StreamValues: protocol.StreamValues{100: protocol.ToDecimal(decimal.NewFromInt(int64(i)))}, }) } aos = append(aos, ao(i, b)) @@ -382,10 +369,10 @@ func Test_AttributedObservationTelemetry_Split(t *testing.T) { tel := newAttributedObservationTelemeter(logger.Test(t), nil, ocrtypes.ConfigDigest{1}, 7, 3) obs := Observation{ - UnixTimestampNanoseconds: 1234, - RemoveChannelIDs: map[llotypes.ChannelID]struct{}{5: {}, 2: {}}, - UpdateChannelDefinitions: llotypes.ChannelDefinitions{1: {ReportFormat: llotypes.ReportFormatJSON, Streams: []llotypes.Stream{{StreamID: 1, Aggregator: llotypes.AggregatorMedian}}}}, - StreamValues: protocol.StreamValues{}, + ObservationTimestampNanoseconds: 1234, + RemoveChannelIDs: map[llotypes.ChannelID]struct{}{5: {}, 2: {}}, + UpdateChannelDefinitions: llotypes.ChannelDefinitions{1: {ReportFormat: llotypes.ReportFormatJSON, Streams: []llotypes.Stream{{StreamID: 1, Aggregator: llotypes.AggregatorMedian}}}}, + StreamValues: protocol.StreamValues{}, } for id := llotypes.StreamID(1); id <= 500; id++ { obs.StreamValues[id] = protocol.ToDecimal(decimal.NewFromInt(int64(id) * 1_000_003)) @@ -455,13 +442,6 @@ func Test_AttributedObservationTelemetry_Split(t *testing.T) { require.Empty(t, msgs[0].StreamValues) requireParts(t, msgs) }) - - t.Run("decode error", func(t *testing.T) { - msgs := tel.makeTelemetry(9, 5678, attributedObservation{observer: 4, decodeErr: errors.New("boom")}) - require.Len(t, msgs, 1) - require.Equal(t, "boom", msgs[0].GetDecodeError()) - require.Empty(t, msgs[0].StreamValues) - }) } func Test_AttributedObservationTelemetry_NonBlocking(t *testing.T) { @@ -513,9 +493,9 @@ func Test_AttributedObservationTelemetry_Concurrent(t *testing.T) { var b []byte if seqNr > 1 { b = mustEncodeObs(t, Observation{ - UnixTimestampNanoseconds: seqNr * 1000, - UpdateChannelDefinitions: llotypes.ChannelDefinitions{1: channelDef}, - StreamValues: protocol.StreamValues{100: protocol.ToDecimal(decimal.NewFromInt(int64(i)))}, + ObservationTimestampNanoseconds: seqNr * 1000, + UpdateChannelDefinitions: llotypes.ChannelDefinitions{1: channelDef}, + StreamValues: protocol.StreamValues{100: protocol.ToDecimal(decimal.NewFromInt(int64(i)))}, }) } aos = append(aos, ao(i, b)) @@ -552,7 +532,7 @@ func Test_OutcomeTelemetry_Emitters(t *testing.T) { aos := make([]ocrtypes.AttributedObservation, 0, 4) for i := 0; i < 4; i++ { - aos = append(aos, ao(i, mustEncodeObs(t, Observation{UnixTimestampNanoseconds: seqNr * 1000}))) + aos = append(aos, ao(i, mustEncodeObs(t, Observation{ObservationTimestampNanoseconds: seqNr * 1000}))) } _, err := p.StateTransition(ctx, seqNr, ocrtypes.AttributedQuery{}, aos, kv, testBlobs) require.NoError(t, err) @@ -589,13 +569,13 @@ func Test_ReportTelemetry_Lifecycle(t *testing.T) { require.Equal(t, stage, v.lifeCycleStage()) ts += handoverTickNanos round(Observation{ - UnixTimestampNanoseconds: ts, - UpdateChannelDefinitions: llotypes.ChannelDefinitions{handoverChannelID: handoverChannel()}, - StreamValues: handoverStreamValues(), + ObservationTimestampNanoseconds: ts, + UpdateChannelDefinitions: llotypes.ChannelDefinitions{handoverChannelID: handoverChannel()}, + StreamValues: handoverStreamValues(), }) for range 3 { ts += handoverTickNanos - round(Observation{UnixTimestampNanoseconds: ts, StreamValues: handoverStreamValues()}) + round(Observation{ObservationTimestampNanoseconds: ts, StreamValues: handoverStreamValues()}) } require.NotEmpty(t, v.reports, "the channel must be reporting") return v, rtCh diff --git a/llo/dev/v31/testdata/golden/kv_channel_state.bin b/llo/dev/v31/testdata/golden/kv_channel_state.bin index 56c0f226..4840355d 100644 Binary files a/llo/dev/v31/testdata/golden/kv_channel_state.bin and b/llo/dev/v31/testdata/golden/kv_channel_state.bin differ diff --git a/llo/dev/v31/testdata/golden/kv_codec_support.bin b/llo/dev/v31/testdata/golden/kv_codec_support.bin index fcc69b68..74f7e296 100644 Binary files a/llo/dev/v31/testdata/golden/kv_codec_support.bin and b/llo/dev/v31/testdata/golden/kv_codec_support.bin differ diff --git a/llo/dev/v31/testdata/golden/kv_history_chunk.bin b/llo/dev/v31/testdata/golden/kv_history_chunk.bin index 311ee5e2..8cd1dda9 100644 Binary files a/llo/dev/v31/testdata/golden/kv_history_chunk.bin and b/llo/dev/v31/testdata/golden/kv_history_chunk.bin differ diff --git a/llo/dev/v31/testdata/golden/kv_history_chunk_full.bin b/llo/dev/v31/testdata/golden/kv_history_chunk_full.bin new file mode 100644 index 00000000..6956381b Binary files /dev/null and b/llo/dev/v31/testdata/golden/kv_history_chunk_full.bin differ diff --git a/llo/dev/v31/testdata/golden/kv_history_header.bin b/llo/dev/v31/testdata/golden/kv_history_header.bin index cd1164ac..d05d9daa 100644 Binary files a/llo/dev/v31/testdata/golden/kv_history_header.bin and b/llo/dev/v31/testdata/golden/kv_history_header.bin differ diff --git a/llo/dev/v31/testdata/golden/kv_hot_state.bin b/llo/dev/v31/testdata/golden/kv_hot_state.bin index f4f189ac..fae35b30 100644 Binary files a/llo/dev/v31/testdata/golden/kv_hot_state.bin and b/llo/dev/v31/testdata/golden/kv_hot_state.bin differ diff --git a/llo/dev/v31/testdata/golden/precursor_empty.bin b/llo/dev/v31/testdata/golden/precursor_empty.bin index e69de29b..f76dd238 100644 Binary files a/llo/dev/v31/testdata/golden/precursor_empty.bin and b/llo/dev/v31/testdata/golden/precursor_empty.bin differ diff --git a/llo/dev/v31/testdata/golden/precursor_full.bin b/llo/dev/v31/testdata/golden/precursor_full.bin index 9e6e9f8f..9d92886f 100644 Binary files a/llo/dev/v31/testdata/golden/precursor_full.bin and b/llo/dev/v31/testdata/golden/precursor_full.bin differ diff --git a/llo/internal/zstdenc/LICENSE b/llo/internal/zstdenc/LICENSE new file mode 100644 index 00000000..87d55747 --- /dev/null +++ b/llo/internal/zstdenc/LICENSE @@ -0,0 +1,304 @@ +Copyright (c) 2012 The Go Authors. All rights reserved. +Copyright (c) 2019 Klaus Post. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +------------------ + +Files: gzhttp/* + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2016-2017 The New York Times Company + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +------------------ + +Files: s2/cmd/internal/readahead/* + +The MIT License (MIT) + +Copyright (c) 2015 Klaus Post + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +--------------------- +Files: snappy/* +Files: internal/snapref/* + +Copyright (c) 2011 The Snappy-Go Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +----------------- + +Files: s2/cmd/internal/filepathx/* + +Copyright 2016 The filepathx Authors + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/llo/internal/zstdenc/README.md b/llo/internal/zstdenc/README.md new file mode 100644 index 00000000..450fdf51 --- /dev/null +++ b/llo/internal/zstdenc/README.md @@ -0,0 +1,68 @@ +# zstdenc + +A trimmed copy of the zstd encoder from +[klauspost/compress](https://github.com/klauspost/compress) **v1.20.3**, under +its BSD license (see `LICENSE`). + +## Why + +The v31 precursor is digested and signed, and the KV records feed the state +root, so every oracle must compress them to the same bytes. zstd only promises +that output for one encoder version and one set of options. As a regular +dependency, the encoder version is chosen by the binary that imports this +module, and any unrelated upgrade there can move it. This copy fixes the +encoder to code this repository owns. + +Only the encoder is copied. Decoding stays on the upstream module: any +conforming decoder reads these frames, and the decoder parses untrusted peer +input, so it should keep receiving upstream fixes. + +## What is kept + +Exactly what `NewWriter` with `SpeedDefault`, `WithEncoderCRC(true)`, +`WithZeroFrames(false)` and `WithSingleSegment(true)` followed by `EncodeAll` +links, on every supported build (amd64, arm64, 386, riscv64, and +`purego,noasm,nounsafe`): + +| package | upstream | +|---|---| +| `zstd` | `zstd`, the double fast encoder and the block, sequence and FSE encoders | +| `huff0` | `huff0`, the Huffman encoder | +| `fse` | `fse`, the FSE encoder huff0 uses for its weight table | +| `internal/le`, `internal/regmask` | the same internal packages | + +`zstd/internal/xxhash` is replaced by `github.com/cespare/xxhash/v2`, the +package it was forked from. XXH64 is fixed by its specification, so the frame +checksum does not depend on that version. + +## How it was trimmed + +The upstream files were copied with only the import paths rewritten, and then +code was only deleted, never edited: + +1. Functions the linker drops from a program that calls only the API above, + with inlining off, in every build configuration that compiles their file. +2. Types, constants, variables and struct fields nothing references. +3. Files and assembly left with no declarations. +4. The other compression levels from the `encoderOptions.encoder` switch, and + `ResetPrefix` and `UseBlock` from the `encoder` interface. +5. Compiled out blocks (`if false`, `if debugEncoder`) that call deleted + functions, in `fse.Compress`, `huff0.Compress4X` and `blockEnc.encode`. +6. The decoder tables from `initPredefined`. The encoder tables copy only the + normalized counts from them and build their own. + +Every remaining declaration is byte for byte identical to upstream, apart from +lines deleted by the steps above and gofmt realigning struct fields. Keep it +that way: a change here changes the bytes every oracle must agree on. + +## Verifying and upgrading + +`zstdenc_test.go` checks the copy against upstream on a corpus and with a fuzz +target, round trips it through the upstream decoder, and freezes the corpus +output in a digest. The differential tests skip once the upstream module is no +longer v1.20.3. The digest test and the v31 golden tests keep guarding the +bytes after that. + +Taking an upstream encoder change means copying and trimming again, and it +changes the encoded bytes, so it needs the same coordinated rollout as any +other wire format change. diff --git a/llo/internal/zstdenc/fse/bitwriter.go b/llo/internal/zstdenc/fse/bitwriter.go new file mode 100644 index 00000000..d58b3fe4 --- /dev/null +++ b/llo/internal/zstdenc/fse/bitwriter.go @@ -0,0 +1,167 @@ +// Copyright 2018 Klaus Post. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. +// Based on work Copyright (c) 2013, Yann Collet, released under BSD License. + +package fse + +import "fmt" + +// bitWriter will write bits. +// First bit will be LSB of the first byte of output. +type bitWriter struct { + bitContainer uint64 + nBits uint8 + out []byte +} + +// bitMask16 is bitmasks. Has extra to avoid bounds check. +var bitMask16 = [32]uint16{ + 0, 1, 3, 7, 0xF, 0x1F, + 0x3F, 0x7F, 0xFF, 0x1FF, 0x3FF, 0x7FF, + 0xFFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF, 0xFFFF, + 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, + 0xFFFF, 0xFFFF} /* up to 16 bits */ + +// addBits16NC will add up to 16 bits. +// It will not check if there is space for them, +// so the caller must ensure that it has flushed recently. +func (b *bitWriter) addBits16NC(value uint16, bits uint8) { + b.bitContainer |= uint64(value&bitMask16[bits&31]) << (b.nBits & 63) + b.nBits += bits +} + +// addBits16Clean will add up to 16 bits. value may not contain more set bits than indicated. +// It will not check if there is space for them, so the caller must ensure that it has flushed recently. +func (b *bitWriter) addBits16Clean(value uint16, bits uint8) { + b.bitContainer |= uint64(value) << (b.nBits & 63) + b.nBits += bits +} + +// addBits16ZeroNC will add up to 16 bits. +// It will not check if there is space for them, +// so the caller must ensure that it has flushed recently. +// This is fastest if bits can be zero. +func (b *bitWriter) addBits16ZeroNC(value uint16, bits uint8) { + if bits == 0 { + return + } + value <<= (16 - bits) & 15 + value >>= (16 - bits) & 15 + b.bitContainer |= uint64(value) << (b.nBits & 63) + b.nBits += bits +} + +// flush will flush all pending full bytes. +// There will be at least 56 bits available for writing when this has been called. +// Using flush32 is faster, but leaves less space for writing. +func (b *bitWriter) flush() { + v := b.nBits >> 3 + switch v { + case 0: + case 1: + b.out = append(b.out, + byte(b.bitContainer), + ) + case 2: + b.out = append(b.out, + byte(b.bitContainer), + byte(b.bitContainer>>8), + ) + case 3: + b.out = append(b.out, + byte(b.bitContainer), + byte(b.bitContainer>>8), + byte(b.bitContainer>>16), + ) + case 4: + b.out = append(b.out, + byte(b.bitContainer), + byte(b.bitContainer>>8), + byte(b.bitContainer>>16), + byte(b.bitContainer>>24), + ) + case 5: + b.out = append(b.out, + byte(b.bitContainer), + byte(b.bitContainer>>8), + byte(b.bitContainer>>16), + byte(b.bitContainer>>24), + byte(b.bitContainer>>32), + ) + case 6: + b.out = append(b.out, + byte(b.bitContainer), + byte(b.bitContainer>>8), + byte(b.bitContainer>>16), + byte(b.bitContainer>>24), + byte(b.bitContainer>>32), + byte(b.bitContainer>>40), + ) + case 7: + b.out = append(b.out, + byte(b.bitContainer), + byte(b.bitContainer>>8), + byte(b.bitContainer>>16), + byte(b.bitContainer>>24), + byte(b.bitContainer>>32), + byte(b.bitContainer>>40), + byte(b.bitContainer>>48), + ) + case 8: + b.out = append(b.out, + byte(b.bitContainer), + byte(b.bitContainer>>8), + byte(b.bitContainer>>16), + byte(b.bitContainer>>24), + byte(b.bitContainer>>32), + byte(b.bitContainer>>40), + byte(b.bitContainer>>48), + byte(b.bitContainer>>56), + ) + default: + panic(fmt.Errorf("bits (%d) > 64", b.nBits)) + } + b.bitContainer >>= v << 3 + b.nBits &= 7 +} + +// flush32 will flush out, so there are at least 32 bits available for writing. +func (b *bitWriter) flush32() { + if b.nBits < 32 { + return + } + b.out = append(b.out, + byte(b.bitContainer), + byte(b.bitContainer>>8), + byte(b.bitContainer>>16), + byte(b.bitContainer>>24)) + b.nBits -= 32 + b.bitContainer >>= 32 +} + +// flushAlign will flush remaining full bytes and align to next byte boundary. +func (b *bitWriter) flushAlign() { + nbBytes := (b.nBits + 7) >> 3 + for i := range nbBytes { + b.out = append(b.out, byte(b.bitContainer>>(i*8))) + } + b.nBits = 0 + b.bitContainer = 0 +} + +// close will write the alignment bit and write the final byte(s) +// to the output. +func (b *bitWriter) close() { + // End mark + b.addBits16Clean(1, 1) + // flush until next byte. + b.flushAlign() +} + +// reset and continue writing by appending to out. +func (b *bitWriter) reset(out []byte) { + b.bitContainer = 0 + b.nBits = 0 + b.out = out +} diff --git a/llo/internal/zstdenc/fse/bytereader.go b/llo/internal/zstdenc/fse/bytereader.go new file mode 100644 index 00000000..98a3e115 --- /dev/null +++ b/llo/internal/zstdenc/fse/bytereader.go @@ -0,0 +1,26 @@ +// Copyright 2018 Klaus Post. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. +// Based on work Copyright (c) 2013, Yann Collet, released under BSD License. + +package fse + +// byteReader provides a byte reader that reads +// little endian values from a byte stream. +// The input stream is manually advanced. +// The reader performs no bounds checks. +type byteReader struct { + b []byte + off int +} + +// init will initialize the reader and set the input. +func (b *byteReader) init(in []byte) { + b.b = in + b.off = 0 +} + +// remain will return the number of bytes remaining. +func (b byteReader) remain() int { + return len(b.b) - b.off +} diff --git a/llo/internal/zstdenc/fse/compress.go b/llo/internal/zstdenc/fse/compress.go new file mode 100644 index 00000000..bfecdb7d --- /dev/null +++ b/llo/internal/zstdenc/fse/compress.go @@ -0,0 +1,646 @@ +// Copyright 2018 Klaus Post. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. +// Based on work Copyright (c) 2013, Yann Collet, released under BSD License. + +package fse + +import ( + "errors" + "fmt" +) + +// Compress the input bytes. Input must be < 2GB. +// Provide a Scratch buffer to avoid memory allocations. +// Note that the output is also kept in the scratch buffer. +// If input is too hard to compress, ErrIncompressible is returned. +// If input is a single byte value repeated ErrUseRLE is returned. +func Compress(in []byte, s *Scratch) ([]byte, error) { + if len(in) <= 1 { + return nil, ErrIncompressible + } + if len(in) > (2<<30)-1 { + return nil, errors.New("input too big, must be < 2GB") + } + s, err := s.prepare(in) + if err != nil { + return nil, err + } + + // Create histogram, if none was provided. + maxCount := s.maxCount + if maxCount == 0 { + maxCount = s.countSimple(in) + } + // Reset for next run. + s.clearCount = true + s.maxCount = 0 + if maxCount == len(in) { + // One symbol, use RLE + return nil, ErrUseRLE + } + if maxCount == 1 || maxCount < (len(in)>>7) { + // Each symbol present maximum once or too well distributed. + return nil, ErrIncompressible + } + s.optimalTableLog() + err = s.normalizeCount() + if err != nil { + return nil, err + } + err = s.writeCount() + if err != nil { + return nil, err + } + + err = s.buildCTable() + if err != nil { + return nil, err + } + err = s.compress(in) + if err != nil { + return nil, err + } + s.Out = s.bw.out + // Check if we compressed. + if len(s.Out) >= len(in) { + return nil, ErrIncompressible + } + return s.Out, nil +} + +// cState contains the compression state of a stream. +type cState struct { + bw *bitWriter + stateTable []uint16 + state uint16 +} + +// init will initialize the compression state to the first symbol of the stream. +func (c *cState) init(bw *bitWriter, ct *cTable, tableLog uint8, first symbolTransform) { + c.bw = bw + c.stateTable = ct.stateTable + + nbBitsOut := (first.deltaNbBits + (1 << 15)) >> 16 + im := int32((nbBitsOut << 16) - first.deltaNbBits) + lu := (im >> nbBitsOut) + first.deltaFindState + c.state = c.stateTable[lu] +} + +// encode the output symbol provided and write it to the bitstream. +func (c *cState) encode(symbolTT symbolTransform) { + nbBitsOut := (uint32(c.state) + symbolTT.deltaNbBits) >> 16 + dstState := int32(c.state>>(nbBitsOut&15)) + symbolTT.deltaFindState + c.bw.addBits16NC(c.state, uint8(nbBitsOut)) + c.state = c.stateTable[dstState] +} + +// encode the output symbol provided and write it to the bitstream. +func (c *cState) encodeZero(symbolTT symbolTransform) { + nbBitsOut := (uint32(c.state) + symbolTT.deltaNbBits) >> 16 + dstState := int32(c.state>>(nbBitsOut&15)) + symbolTT.deltaFindState + c.bw.addBits16ZeroNC(c.state, uint8(nbBitsOut)) + c.state = c.stateTable[dstState] +} + +// flush will write the tablelog to the output and flush the remaining full bytes. +func (c *cState) flush(tableLog uint8) { + c.bw.flush32() + c.bw.addBits16NC(c.state, tableLog) + c.bw.flush() +} + +// compress is the main compression loop that will encode the input from the last byte to the first. +func (s *Scratch) compress(src []byte) error { + if len(src) <= 2 { + return errors.New("compress: src too small") + } + tt := s.ct.symbolTT[:256] + s.bw.reset(s.Out) + + // Our two states each encodes every second byte. + // Last byte encoded (first byte decoded) will always be encoded by c1. + var c1, c2 cState + + // Encode so remaining size is divisible by 4. + ip := len(src) + if ip&1 == 1 { + c1.init(&s.bw, &s.ct, s.actualTableLog, tt[src[ip-1]]) + c2.init(&s.bw, &s.ct, s.actualTableLog, tt[src[ip-2]]) + c1.encodeZero(tt[src[ip-3]]) + ip -= 3 + } else { + c2.init(&s.bw, &s.ct, s.actualTableLog, tt[src[ip-1]]) + c1.init(&s.bw, &s.ct, s.actualTableLog, tt[src[ip-2]]) + ip -= 2 + } + if ip&2 != 0 { + c2.encodeZero(tt[src[ip-1]]) + c1.encodeZero(tt[src[ip-2]]) + ip -= 2 + } + src = src[:ip] + + // Main compression loop. + switch { + case !s.zeroBits && s.actualTableLog <= 8: + // We can encode 4 symbols without requiring a flush. + // We do not need to check if any output is 0 bits. + for ; len(src) >= 4; src = src[:len(src)-4] { + s.bw.flush32() + v3, v2, v1, v0 := src[len(src)-4], src[len(src)-3], src[len(src)-2], src[len(src)-1] + c2.encode(tt[v0]) + c1.encode(tt[v1]) + c2.encode(tt[v2]) + c1.encode(tt[v3]) + } + case !s.zeroBits: + // We do not need to check if any output is 0 bits. + for ; len(src) >= 4; src = src[:len(src)-4] { + s.bw.flush32() + v3, v2, v1, v0 := src[len(src)-4], src[len(src)-3], src[len(src)-2], src[len(src)-1] + c2.encode(tt[v0]) + c1.encode(tt[v1]) + s.bw.flush32() + c2.encode(tt[v2]) + c1.encode(tt[v3]) + } + case s.actualTableLog <= 8: + // We can encode 4 symbols without requiring a flush + for ; len(src) >= 4; src = src[:len(src)-4] { + s.bw.flush32() + v3, v2, v1, v0 := src[len(src)-4], src[len(src)-3], src[len(src)-2], src[len(src)-1] + c2.encodeZero(tt[v0]) + c1.encodeZero(tt[v1]) + c2.encodeZero(tt[v2]) + c1.encodeZero(tt[v3]) + } + default: + for ; len(src) >= 4; src = src[:len(src)-4] { + s.bw.flush32() + v3, v2, v1, v0 := src[len(src)-4], src[len(src)-3], src[len(src)-2], src[len(src)-1] + c2.encodeZero(tt[v0]) + c1.encodeZero(tt[v1]) + s.bw.flush32() + c2.encodeZero(tt[v2]) + c1.encodeZero(tt[v3]) + } + } + + // Flush final state. + // Used to initialize state when decoding. + c2.flush(s.actualTableLog) + c1.flush(s.actualTableLog) + + s.bw.close() + return nil +} + +// writeCount will write the normalized histogram count to header. +// This is read back by readNCount. +func (s *Scratch) writeCount() error { + var ( + tableLog = s.actualTableLog + tableSize = 1 << tableLog + previous0 bool + charnum uint16 + + maxHeaderSize = ((int(s.symbolLen)*int(tableLog) + 4 + 2) >> 3) + 3 + + // Write Table Size + bitStream = uint32(tableLog - minTablelog) + bitCount = uint(4) + remaining = int16(tableSize + 1) /* +1 for extra accuracy */ + threshold = int16(tableSize) + nbBits = uint(tableLog + 1) + ) + if cap(s.Out) < maxHeaderSize { + s.Out = make([]byte, 0, s.br.remain()+maxHeaderSize) + } + outP := uint(0) + out := s.Out[:maxHeaderSize] + + // stops at 1 + for remaining > 1 { + if previous0 { + start := charnum + for s.norm[charnum] == 0 { + charnum++ + } + for charnum >= start+24 { + start += 24 + bitStream += uint32(0xFFFF) << bitCount + out[outP] = byte(bitStream) + out[outP+1] = byte(bitStream >> 8) + outP += 2 + bitStream >>= 16 + } + for charnum >= start+3 { + start += 3 + bitStream += 3 << bitCount + bitCount += 2 + } + bitStream += uint32(charnum-start) << bitCount + bitCount += 2 + if bitCount > 16 { + out[outP] = byte(bitStream) + out[outP+1] = byte(bitStream >> 8) + outP += 2 + bitStream >>= 16 + bitCount -= 16 + } + } + + count := s.norm[charnum] + charnum++ + max := (2*threshold - 1) - remaining + if count < 0 { + remaining += count + } else { + remaining -= count + } + count++ // +1 for extra accuracy + if count >= threshold { + count += max // [0..max[ [max..threshold[ (...) [threshold+max 2*threshold[ + } + bitStream += uint32(count) << bitCount + bitCount += nbBits + if count < max { + bitCount-- + } + + previous0 = count == 1 + if remaining < 1 { + return errors.New("internal error: remaining<1") + } + for remaining < threshold { + nbBits-- + threshold >>= 1 + } + + if bitCount > 16 { + out[outP] = byte(bitStream) + out[outP+1] = byte(bitStream >> 8) + outP += 2 + bitStream >>= 16 + bitCount -= 16 + } + } + + out[outP] = byte(bitStream) + out[outP+1] = byte(bitStream >> 8) + outP += (bitCount + 7) / 8 + + if charnum > s.symbolLen { + return errors.New("internal error: charnum > s.symbolLen") + } + s.Out = out[:outP] + return nil +} + +// symbolTransform contains the state transform for a symbol. +type symbolTransform struct { + deltaFindState int32 + deltaNbBits uint32 +} + +// String prints values as a human readable string. +func (s symbolTransform) String() string { + return fmt.Sprintf("dnbits: %08x, fs:%d", s.deltaNbBits, s.deltaFindState) +} + +// cTable contains tables used for compression. +type cTable struct { + tableSymbol []byte + stateTable []uint16 + symbolTT []symbolTransform +} + +// allocCtable will allocate tables needed for compression. +// If existing tables a re big enough, they are simply re-used. +func (s *Scratch) allocCtable() { + tableSize := 1 << s.actualTableLog + // get tableSymbol that is big enough. + if cap(s.ct.tableSymbol) < tableSize { + s.ct.tableSymbol = make([]byte, tableSize) + } + s.ct.tableSymbol = s.ct.tableSymbol[:tableSize] + + ctSize := tableSize + if cap(s.ct.stateTable) < ctSize { + s.ct.stateTable = make([]uint16, ctSize) + } + s.ct.stateTable = s.ct.stateTable[:ctSize] + + if cap(s.ct.symbolTT) < 256 { + s.ct.symbolTT = make([]symbolTransform, 256) + } + s.ct.symbolTT = s.ct.symbolTT[:256] +} + +// buildCTable will populate the compression table so it is ready to be used. +func (s *Scratch) buildCTable() error { + tableSize := uint32(1 << s.actualTableLog) + highThreshold := tableSize - 1 + var cumul [maxSymbolValue + 2]int16 + + s.allocCtable() + tableSymbol := s.ct.tableSymbol[:tableSize] + // symbol start positions + { + cumul[0] = 0 + for ui, v := range s.norm[:s.symbolLen-1] { + u := byte(ui) // one less than reference + if v == -1 { + // Low proba symbol + cumul[u+1] = cumul[u] + 1 + tableSymbol[highThreshold] = u + highThreshold-- + } else { + cumul[u+1] = cumul[u] + v + } + } + // Encode last symbol separately to avoid overflowing u + u := int(s.symbolLen - 1) + v := s.norm[s.symbolLen-1] + if v == -1 { + // Low proba symbol + cumul[u+1] = cumul[u] + 1 + tableSymbol[highThreshold] = byte(u) + highThreshold-- + } else { + cumul[u+1] = cumul[u] + v + } + if uint32(cumul[s.symbolLen]) != tableSize { + return fmt.Errorf("internal error: expected cumul[s.symbolLen] (%d) == tableSize (%d)", cumul[s.symbolLen], tableSize) + } + cumul[s.symbolLen] = int16(tableSize) + 1 + } + // Spread symbols + s.zeroBits = false + { + step := tableStep(tableSize) + tableMask := tableSize - 1 + var position uint32 + // if any symbol > largeLimit, we may have 0 bits output. + largeLimit := int16(1 << (s.actualTableLog - 1)) + for ui, v := range s.norm[:s.symbolLen] { + symbol := byte(ui) + if v > largeLimit { + s.zeroBits = true + } + for range v { + tableSymbol[position] = symbol + position = (position + step) & tableMask + for position > highThreshold { + position = (position + step) & tableMask + } /* Low proba area */ + } + } + + // Check if we have gone through all positions + if position != 0 { + return errors.New("position!=0") + } + } + + // Build table + table := s.ct.stateTable + { + tsi := int(tableSize) + for u, v := range tableSymbol { + // TableU16 : sorted by symbol order; gives next state value + table[cumul[v]] = uint16(tsi + u) + cumul[v]++ + } + } + + // Build Symbol Transformation Table + { + total := int16(0) + symbolTT := s.ct.symbolTT[:s.symbolLen] + tableLog := s.actualTableLog + tl := (uint32(tableLog) << 16) - (1 << tableLog) + for i, v := range s.norm[:s.symbolLen] { + switch v { + case 0: + case -1, 1: + symbolTT[i].deltaNbBits = tl + symbolTT[i].deltaFindState = int32(total - 1) + total++ + default: + maxBitsOut := uint32(tableLog) - highBits(uint32(v-1)) + minStatePlus := uint32(v) << maxBitsOut + symbolTT[i].deltaNbBits = (maxBitsOut << 16) - minStatePlus + symbolTT[i].deltaFindState = int32(total - v) + total += v + } + } + if total != int16(tableSize) { + return fmt.Errorf("total mismatch %d (got) != %d (want)", total, tableSize) + } + } + return nil +} + +// countSimple will create a simple histogram in s.count. +// Returns the biggest count. +// Does not update s.clearCount. +func (s *Scratch) countSimple(in []byte) (max int) { + for _, v := range in { + s.count[v]++ + } + m, symlen := uint32(0), s.symbolLen + for i, v := range s.count[:] { + if v == 0 { + continue + } + if v > m { + m = v + } + symlen = uint16(i) + 1 + } + s.symbolLen = symlen + return int(m) +} + +// minTableLog provides the minimum logSize to safely represent a distribution. +func (s *Scratch) minTableLog() uint8 { + minBitsSrc := highBits(uint32(s.br.remain()-1)) + 1 + minBitsSymbols := highBits(uint32(s.symbolLen-1)) + 2 + if minBitsSrc < minBitsSymbols { + return uint8(minBitsSrc) + } + return uint8(minBitsSymbols) +} + +// optimalTableLog calculates and sets the optimal tableLog in s.actualTableLog +func (s *Scratch) optimalTableLog() { + tableLog := s.TableLog + minBits := s.minTableLog() + maxBitsSrc := uint8(highBits(uint32(s.br.remain()-1))) - 2 + if maxBitsSrc < tableLog { + // Accuracy can be reduced + tableLog = maxBitsSrc + } + if minBits > tableLog { + tableLog = minBits + } + // Need a minimum to safely represent all symbol values + if tableLog < minTablelog { + tableLog = minTablelog + } + if tableLog > maxTableLog { + tableLog = maxTableLog + } + s.actualTableLog = tableLog +} + +var rtbTable = [...]uint32{0, 473195, 504333, 520860, 550000, 700000, 750000, 830000} + +// normalizeCount will normalize the count of the symbols so +// the total is equal to the table size. +func (s *Scratch) normalizeCount() error { + var ( + tableLog = s.actualTableLog + scale = 62 - uint64(tableLog) + step = (1 << 62) / uint64(s.br.remain()) + vStep = uint64(1) << (scale - 20) + stillToDistribute = int16(1 << tableLog) + largest int + largestP int16 + lowThreshold = (uint32)(s.br.remain() >> tableLog) + ) + + for i, cnt := range s.count[:s.symbolLen] { + // already handled + // if (count[s] == s.length) return 0; /* rle special case */ + + if cnt == 0 { + s.norm[i] = 0 + continue + } + if cnt <= lowThreshold { + s.norm[i] = -1 + stillToDistribute-- + } else { + proba := (int16)((uint64(cnt) * step) >> scale) + if proba < 8 { + restToBeat := vStep * uint64(rtbTable[proba]) + v := uint64(cnt)*step - (uint64(proba) << scale) + if v > restToBeat { + proba++ + } + } + if proba > largestP { + largestP = proba + largest = i + } + s.norm[i] = proba + stillToDistribute -= proba + } + } + + if -stillToDistribute >= (s.norm[largest] >> 1) { + // corner case, need another normalization method + return s.normalizeCount2() + } + s.norm[largest] += stillToDistribute + return nil +} + +// Secondary normalization method. +// To be used when primary method fails. +func (s *Scratch) normalizeCount2() error { + const notYetAssigned = -2 + var ( + distributed uint32 + total = uint32(s.br.remain()) + tableLog = s.actualTableLog + lowThreshold = total >> tableLog + lowOne = (total * 3) >> (tableLog + 1) + ) + for i, cnt := range s.count[:s.symbolLen] { + if cnt == 0 { + s.norm[i] = 0 + continue + } + if cnt <= lowThreshold { + s.norm[i] = -1 + distributed++ + total -= cnt + continue + } + if cnt <= lowOne { + s.norm[i] = 1 + distributed++ + total -= cnt + continue + } + s.norm[i] = notYetAssigned + } + toDistribute := (1 << tableLog) - distributed + + if (total / toDistribute) > lowOne { + // risk of rounding to zero + lowOne = (total * 3) / (toDistribute * 2) + for i, cnt := range s.count[:s.symbolLen] { + if (s.norm[i] == notYetAssigned) && (cnt <= lowOne) { + s.norm[i] = 1 + distributed++ + total -= cnt + continue + } + } + toDistribute = (1 << tableLog) - distributed + } + if distributed == uint32(s.symbolLen)+1 { + // all values are pretty poor; + // probably incompressible data (should have already been detected); + // find max, then give all remaining points to max + var maxV int + var maxC uint32 + for i, cnt := range s.count[:s.symbolLen] { + if cnt > maxC { + maxV = i + maxC = cnt + } + } + s.norm[maxV] += int16(toDistribute) + return nil + } + + if total == 0 { + // all of the symbols were low enough for the lowOne or lowThreshold + for i := uint32(0); toDistribute > 0; i = (i + 1) % (uint32(s.symbolLen)) { + if s.norm[i] > 0 { + toDistribute-- + s.norm[i]++ + } + } + return nil + } + + var ( + vStepLog = 62 - uint64(tableLog) + mid = uint64((1 << (vStepLog - 1)) - 1) + rStep = (((1 << vStepLog) * uint64(toDistribute)) + mid) / uint64(total) // scale on remaining + tmpTotal = mid + ) + for i, cnt := range s.count[:s.symbolLen] { + if s.norm[i] == notYetAssigned { + var ( + end = tmpTotal + uint64(cnt)*rStep + sStart = uint32(tmpTotal >> vStepLog) + sEnd = uint32(end >> vStepLog) + weight = sEnd - sStart + ) + if weight < 1 { + return errors.New("weight < 1") + } + s.norm[i] = int16(weight) + tmpTotal = end + } + } + return nil +} diff --git a/llo/internal/zstdenc/fse/fse.go b/llo/internal/zstdenc/fse/fse.go new file mode 100644 index 00000000..5948b6b5 --- /dev/null +++ b/llo/internal/zstdenc/fse/fse.go @@ -0,0 +1,142 @@ +// Copyright 2018 Klaus Post. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. +// Based on work Copyright (c) 2013, Yann Collet, released under BSD License. + +// Package fse provides Finite State Entropy encoding and decoding. +// +// Finite State Entropy encoding provides a fast near-optimal symbol encoding/decoding +// for byte blocks as implemented in zstd. +// +// See https://github.com/klauspost/compress/tree/master/fse for more information. +package fse + +import ( + "errors" + "fmt" + "math/bits" +) + +const ( + /*!MEMORY_USAGE : + * Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB; etc.) + * Increasing memory usage improves compression ratio + * Reduced memory usage can improve speed, due to cache effect + * Recommended max value is 14, for 16KB, which nicely fits into Intel x86 L1 cache */ + maxMemoryUsage = 14 + defaultMemoryUsage = 13 + + maxTableLog = maxMemoryUsage - 2 + maxTablesize = 1 << maxTableLog + defaultTablelog = defaultMemoryUsage - 2 + minTablelog = 5 + maxSymbolValue = 255 +) + +var ( + // ErrIncompressible is returned when input is judged to be too hard to compress. + ErrIncompressible = errors.New("input is not compressible") + + // ErrUseRLE is returned from the compressor when the input is a single byte value repeated. + ErrUseRLE = errors.New("input is single value repeated") +) + +// Scratch provides temporary storage for compression and decompression. +type Scratch struct { + // Private + count [maxSymbolValue + 1]uint32 + norm [maxSymbolValue + 1]int16 + br byteReader + bw bitWriter + ct cTable // Compression tables. + maxCount int // count of the most probable symbol + + // Per block parameters. + // These can be used to override compression parameters of the block. + // Do not touch, unless you know what you are doing. + + // Out is output buffer. + // If the scratch is re-used before the caller is done processing the output, + // set this field to nil. + // Otherwise the output buffer will be re-used for next Compression/Decompression step + // and allocation will be avoided. + Out []byte + + // DecompressLimit limits the maximum decoded size acceptable. + // If > 0 decompression will stop when approximately this many bytes + // has been decoded. + // If 0, maximum size will be 2GB. + DecompressLimit int + + symbolLen uint16 // Length of active part of the symbol table. + actualTableLog uint8 // Selected tablelog. + zeroBits bool // no bits has prob > 50%. + clearCount bool // clear count + + // MaxSymbolValue will override the maximum symbol value of the next block. + MaxSymbolValue uint8 + + // TableLog will attempt to override the tablelog for the next block. + TableLog uint8 +} + +// Histogram allows to populate the histogram and skip that step in the compression, +// It otherwise allows to inspect the histogram when compression is done. +// To indicate that you have populated the histogram call HistogramFinished +// with the value of the highest populated symbol, as well as the number of entries +// in the most populated entry. These are accepted at face value. +// The returned slice will always be length 256. +func (s *Scratch) Histogram() []uint32 { + return s.count[:] +} + +// HistogramFinished can be called to indicate that the histogram has been populated. +// maxSymbol is the index of the highest set symbol of the next data segment. +// maxCount is the number of entries in the most populated entry. +// These are accepted at face value. +func (s *Scratch) HistogramFinished(maxSymbol uint8, maxCount int) { + s.maxCount = maxCount + s.symbolLen = uint16(maxSymbol) + 1 + s.clearCount = maxCount != 0 +} + +// prepare will prepare and allocate scratch tables used for both compression and decompression. +func (s *Scratch) prepare(in []byte) (*Scratch, error) { + if s == nil { + s = &Scratch{} + } + if s.MaxSymbolValue == 0 { + s.MaxSymbolValue = 255 + } + if s.TableLog == 0 { + s.TableLog = defaultTablelog + } + if s.TableLog > maxTableLog { + return nil, fmt.Errorf("tableLog (%d) > maxTableLog (%d)", s.TableLog, maxTableLog) + } + if cap(s.Out) == 0 { + s.Out = make([]byte, 0, len(in)) + } + if s.clearCount && s.maxCount == 0 { + for i := range s.count { + s.count[i] = 0 + } + s.clearCount = false + } + s.br.init(in) + if s.DecompressLimit == 0 { + // Max size 2GB. + s.DecompressLimit = (2 << 30) - 1 + } + + return s, nil +} + +// tableStep returns the next table index. +func tableStep(tableSize uint32) uint32 { + return (tableSize >> 1) + (tableSize >> 3) + 3 +} + +func highBits(val uint32) (n uint32) { + return uint32(bits.Len32(val) - 1) +} diff --git a/llo/internal/zstdenc/huff0/bitwriter.go b/llo/internal/zstdenc/huff0/bitwriter.go new file mode 100644 index 00000000..12d634c8 --- /dev/null +++ b/llo/internal/zstdenc/huff0/bitwriter.go @@ -0,0 +1,97 @@ +// Copyright 2018 Klaus Post. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. +// Based on work Copyright (c) 2013, Yann Collet, released under BSD License. + +package huff0 + +import ( + "github.com/smartcontractkit/chainlink-data-streams/llo/internal/zstdenc/internal/le" + "github.com/smartcontractkit/chainlink-data-streams/llo/internal/zstdenc/internal/regmask" +) + +// bitState is a bit writer that stays in registers when passed and +// returned by value. It writes into a buffer owned by the caller. +type bitState struct { + c uint64 + nb uint + pos int +} + +// flush writes the whole bytes with one 8-byte store at pos, leaving +// at most 7 bits. buf must have 8 bytes of room at pos. +func (s bitState) flush(buf []byte) bitState { + le.Store64(buf, s.pos, s.c) + s.pos += int(s.nb >> 3) + s.c >>= (s.nb &^ 7) & regmask.Shift64ByUint + s.nb &= 7 + return s +} + +// add adds n bits from v, which must have no bits set above them. +// There must be room for them. +func (s bitState) add(v uint64, n uint) bitState { + s.c |= v << (s.nb & regmask.Shift64ByUint) + s.nb += n + return s +} + +// fourSymbols returns the codes for a, b, c and d packed in that order +// from the LSB, and their total length. +func fourSymbols(a, b, c, d cTableEntry) (uint64, uint) { + bitsA := uint(a.nBits) + bitsB := bitsA + uint(b.nBits) + bitsC := bitsB + uint(c.nBits) + v := uint64(a.val) | + uint64(b.val)<<(bitsA®mask.Shift64ByUint) | + uint64(c.val)<<(bitsB®mask.Shift64ByUint) | + uint64(d.val)<<(bitsC®mask.Shift64ByUint) + return v, bitsC + uint(d.nBits) +} + +// bitWriter will write bits. +// First bit will be LSB of the first byte of output. +type bitWriter struct { + bitContainer uint64 + nBits uint8 + out []byte +} + +// addBits16Clean will add up to 16 bits. value may not contain more set bits than indicated. +// It will not check if there is space for them, so the caller must ensure that it has flushed recently. +func (b *bitWriter) addBits16Clean(value uint16, bits uint8) { + b.bitContainer |= uint64(value) << (b.nBits & 63) + b.nBits += bits +} + +// encSymbol will add up to 16 bits. value may not contain more set bits than indicated. +// It will not check if there is space for them, so the caller must ensure that it has flushed recently. +func (b *bitWriter) encSymbol(ct cTable, symbol byte) { + enc := ct[symbol] + b.bitContainer |= uint64(enc.val) << (b.nBits & 63) + if false { + if enc.nBits == 0 { + panic("nbits 0") + } + } + b.nBits += enc.nBits +} + +// flushAlign will flush remaining full bytes and align to next byte boundary. +func (b *bitWriter) flushAlign() { + nbBytes := (b.nBits + 7) >> 3 + for i := range nbBytes { + b.out = append(b.out, byte(b.bitContainer>>(i*8))) + } + b.nBits = 0 + b.bitContainer = 0 +} + +// close will write the alignment bit and write the final byte(s) +// to the output. +func (b *bitWriter) close() { + // End mark + b.addBits16Clean(1, 1) + // flush until next byte. + b.flushAlign() +} diff --git a/llo/internal/zstdenc/huff0/compress.go b/llo/internal/zstdenc/huff0/compress.go new file mode 100644 index 00000000..358fc46f --- /dev/null +++ b/llo/internal/zstdenc/huff0/compress.go @@ -0,0 +1,611 @@ +package huff0 + +import ( + "fmt" + "math" + "slices" +) + +// Compress1X will compress the input. +// The output can be decoded using Decompress1X. +// Supply a Scratch object. The scratch object contains state about re-use, +// So when sharing across independent encodes, be sure to set the re-use policy. +func Compress1X(in []byte, s *Scratch) (out []byte, reUsed bool, err error) { + s, err = s.prepare(in) + if err != nil { + return nil, false, err + } + return compress(in, s, s.compress1X) +} + +// Compress4X will compress the input. The input is split into 4 independent blocks +// and compressed similar to Compress1X. +// The output can be decoded using Decompress4X. +// Supply a Scratch object. The scratch object contains state about re-use, +// So when sharing across independent encodes, be sure to set the re-use policy. +func Compress4X(in []byte, s *Scratch) (out []byte, reUsed bool, err error) { + s, err = s.prepare(in) + if err != nil { + return nil, false, err + } + return compress(in, s, s.compress4X) +} + +func compress(in []byte, s *Scratch, compressor func(src []byte) ([]byte, error)) (out []byte, reUsed bool, err error) { + // Nuke previous table if we cannot reuse anyway. + if s.Reuse == ReusePolicyNone { + s.prevTable = s.prevTable[:0] + } + + // Create histogram, if none was provided. + maxCount := s.maxCount + var canReuse = false + if maxCount == 0 { + maxCount, canReuse = s.countSimple(in) + } else { + canReuse = s.canUseTable(s.prevTable) + } + + // We want the output size to be less than this: + wantSize := len(in) + if s.WantLogLess > 0 { + wantSize -= wantSize >> s.WantLogLess + } + + // Reset for next run. + s.clearCount = true + s.maxCount = 0 + if maxCount >= len(in) { + if maxCount > len(in) { + return nil, false, fmt.Errorf("maxCount (%d) > length (%d)", maxCount, len(in)) + } + if len(in) == 1 { + return nil, false, ErrIncompressible + } + // One symbol, use RLE + return nil, false, ErrUseRLE + } + if maxCount == 1 || maxCount < (len(in)>>7) { + // Each symbol present maximum once or too well distributed. + return nil, false, ErrIncompressible + } + if s.Reuse == ReusePolicyMust && !canReuse { + // We must reuse, but we can't. + return nil, false, ErrIncompressible + } + if (s.Reuse == ReusePolicyPrefer || s.Reuse == ReusePolicyMust) && canReuse { + keepTable := s.cTable + keepTL := s.actualTableLog + s.cTable = s.prevTable + s.actualTableLog = s.prevTableLog + s.Out, err = compressor(in) + s.cTable = keepTable + s.actualTableLog = keepTL + if err == nil && len(s.Out) < wantSize { + s.OutData = s.Out + return s.Out, true, nil + } + if s.Reuse == ReusePolicyMust { + return nil, false, ErrIncompressible + } + // Do not attempt to re-use later. + s.prevTable = s.prevTable[:0] + } + + // Calculate new table. + err = s.buildCTable() + if err != nil { + return nil, false, err + } + + if false && !s.canUseTable(s.cTable) { + panic("invalid table generated") + } + + if s.Reuse == ReusePolicyAllow && canReuse { + hSize := len(s.Out) + oldSize := s.prevTable.estimateSize(s.count[:s.symbolLen]) + newSize := s.cTable.estimateSize(s.count[:s.symbolLen]) + if oldSize <= hSize+newSize || hSize+12 >= wantSize { + // Retain cTable even if we re-use. + keepTable := s.cTable + keepTL := s.actualTableLog + + s.cTable = s.prevTable + s.actualTableLog = s.prevTableLog + s.Out, err = compressor(in) + + // Restore ctable. + s.cTable = keepTable + s.actualTableLog = keepTL + if err != nil { + return nil, false, err + } + if len(s.Out) >= wantSize { + return nil, false, ErrIncompressible + } + s.OutData = s.Out + return s.Out, true, nil + } + } + + // Use new table + err = s.cTable.write(s) + if err != nil { + s.OutTable = nil + return nil, false, err + } + s.OutTable = s.Out + + // Compress using new table + s.Out, err = compressor(in) + if err != nil { + s.OutTable = nil + return nil, false, err + } + if len(s.Out) >= wantSize { + s.OutTable = nil + return nil, false, ErrIncompressible + } + // Move current table into previous. + s.prevTable, s.prevTableLog, s.cTable = s.cTable, s.actualTableLog, s.prevTable[:0] + s.OutData = s.Out[len(s.OutTable):] + return s.Out, false, nil +} + +func (s *Scratch) compress1X(src []byte) ([]byte, error) { + return s.compress1xDo(s.Out, src), nil +} + +func (s *Scratch) compress1xDo(dst, src []byte) []byte { + var bw = bitWriter{out: dst} + + // N is length divisible by 4. + n := len(src) + n -= n & 3 + cTable := s.cTable[:256] + + // Encode last bytes. + for i := len(src) & 3; i > 0; i-- { + bw.encSymbol(cTable, src[n+i-1]) + } + n -= 4 + + // flush leaves at most 7 bits, so four symbols (at most 4*tableLogMax + // bits) always fit. Each chunk checks room for bytesPer4 per four + // symbols plus the 8-byte store. + const bytesPer4 = (7 + 4*tableLogMax) / 8 + w := bitState{c: bw.bitContainer, nb: uint(bw.nBits), pos: len(bw.out)} + buf := bw.out[:cap(bw.out)] + for n >= 0 { + k := (len(buf) - w.pos - 8) / bytesPer4 + if k <= 0 { + buf = slices.Grow(buf[:w.pos], (n/4+1)*bytesPer4+8) + buf = buf[:cap(buf)] + continue + } + for stop := max(n-4*k, -4); n > stop; n -= 4 { + w = w.flush(buf) + tmp := src[n : n+4] + w = w.add(fourSymbols(cTable[tmp[3]], cTable[tmp[2]], cTable[tmp[1]], cTable[tmp[0]])) + } + } + bw.bitContainer, bw.nBits, bw.out = w.c, uint8(w.nb), buf[:w.pos] + bw.close() + return bw.out +} + +var sixZeros [6]byte + +func (s *Scratch) compress4X(src []byte) ([]byte, error) { + if len(src) < 12 { + return nil, ErrIncompressible + } + segmentSize := (len(src) + 3) / 4 + + // Add placeholder for output length + offsetIdx := len(s.Out) + s.Out = append(s.Out, sixZeros[:]...) + + for i := range 4 { + toDo := src + if len(toDo) > segmentSize { + toDo = toDo[:segmentSize] + } + src = src[len(toDo):] + + idx := len(s.Out) + s.Out = s.compress1xDo(s.Out, toDo) + if len(s.Out)-idx > math.MaxUint16 { + // We cannot store the size in the jump table + return nil, ErrIncompressible + } + // Write compressed length as little endian before block. + if i < 3 { + // Last length is not written. + length := len(s.Out) - idx + s.Out[i*2+offsetIdx] = byte(length) + s.Out[i*2+offsetIdx+1] = byte(length >> 8) + } + } + + return s.Out, nil +} + +// countSimple will create a simple histogram in s.count. +// Returns the biggest count. +// Does not update s.clearCount. +func (s *Scratch) countSimple(in []byte) (max int, reuse bool) { + reuse = true + _ = s.count // Assert that s != nil to speed up the following loop. + for _, v := range in { + s.count[v]++ + } + m := uint32(0) + if len(s.prevTable) > 0 { + for i, v := range s.count[:] { + if v == 0 { + continue + } + if v > m { + m = v + } + s.symbolLen = uint16(i) + 1 + if i >= len(s.prevTable) { + reuse = false + } else if s.prevTable[i].nBits == 0 { + reuse = false + } + } + return int(m), reuse + } + for i, v := range s.count[:] { + if v == 0 { + continue + } + if v > m { + m = v + } + s.symbolLen = uint16(i) + 1 + } + return int(m), false +} + +func (s *Scratch) canUseTable(c cTable) bool { + if len(c) < int(s.symbolLen) { + return false + } + for i, v := range s.count[:s.symbolLen] { + if v != 0 && c[i].nBits == 0 { + return false + } + } + return true +} + +// minTableLog provides the minimum logSize to safely represent a distribution. +func (s *Scratch) minTableLog() uint8 { + minBitsSrc := highBit32(uint32(s.srcLen)) + 1 + minBitsSymbols := highBit32(uint32(s.symbolLen-1)) + 2 + if minBitsSrc < minBitsSymbols { + return uint8(minBitsSrc) + } + return uint8(minBitsSymbols) +} + +// optimalTableLog calculates and sets the optimal tableLog in s.actualTableLog +func (s *Scratch) optimalTableLog() { + tableLog := s.TableLog + minBits := s.minTableLog() + maxBitsSrc := uint8(highBit32(uint32(s.srcLen-1))) - 1 + if maxBitsSrc < tableLog { + // Accuracy can be reduced + tableLog = maxBitsSrc + } + if minBits > tableLog { + tableLog = minBits + } + // Need a minimum to safely represent all symbol values + if tableLog < minTablelog { + tableLog = minTablelog + } + if tableLog > tableLogMax { + tableLog = tableLogMax + } + s.actualTableLog = tableLog +} + +type cTableEntry struct { + val uint16 + nBits uint8 + // We have 8 bits extra +} + +const huffNodesMask = huffNodesLen - 1 + +func (s *Scratch) buildCTable() error { + s.optimalTableLog() + s.huffSort() + if cap(s.cTable) < maxSymbolValue+1 { + s.cTable = make([]cTableEntry, s.symbolLen, maxSymbolValue+1) + } else { + s.cTable = s.cTable[:s.symbolLen] + for i := range s.cTable { + s.cTable[i] = cTableEntry{} + } + } + + var startNode = int16(s.symbolLen) + nonNullRank := s.symbolLen - 1 + + nodeNb := startNode + huffNode := s.nodes[1 : huffNodesLen+1] + + // This overlays the slice above, but allows "-1" index lookups. + // Different from reference implementation. + huffNode0 := s.nodes[0 : huffNodesLen+1] + + for huffNode[nonNullRank].count() == 0 { + nonNullRank-- + } + + lowS := int16(nonNullRank) + nodeRoot := nodeNb + lowS - 1 + lowN := nodeNb + huffNode[nodeNb].setCount(huffNode[lowS].count() + huffNode[lowS-1].count()) + huffNode[lowS].setParent(nodeNb) + huffNode[lowS-1].setParent(nodeNb) + nodeNb++ + lowS -= 2 + for n := nodeNb; n <= nodeRoot; n++ { + huffNode[n].setCount(1 << 30) + } + // fake entry, strong barrier + huffNode0[0].setCount(1 << 31) + + // create parents + for nodeNb <= nodeRoot { + var n1, n2 int16 + if huffNode0[lowS+1].count() < huffNode0[lowN+1].count() { + n1 = lowS + lowS-- + } else { + n1 = lowN + lowN++ + } + if huffNode0[lowS+1].count() < huffNode0[lowN+1].count() { + n2 = lowS + lowS-- + } else { + n2 = lowN + lowN++ + } + + huffNode[nodeNb].setCount(huffNode0[n1+1].count() + huffNode0[n2+1].count()) + huffNode0[n1+1].setParent(nodeNb) + huffNode0[n2+1].setParent(nodeNb) + nodeNb++ + } + + // distribute weights (unlimited tree height) + huffNode[nodeRoot].setNbBits(0) + for n := nodeRoot - 1; n >= startNode; n-- { + huffNode[n].setNbBits(huffNode[huffNode[n].parent()].nbBits() + 1) + } + for n := uint16(0); n <= nonNullRank; n++ { + huffNode[n].setNbBits(huffNode[huffNode[n].parent()].nbBits() + 1) + } + s.actualTableLog = s.setMaxHeight(int(nonNullRank)) + maxNbBits := s.actualTableLog + + // fill result into tree (val, nbBits) + if maxNbBits > tableLogMax { + return fmt.Errorf("internal error: maxNbBits (%d) > tableLogMax (%d)", maxNbBits, tableLogMax) + } + var nbPerRank [tableLogMax + 1]uint16 + var valPerRank [16]uint16 + for _, v := range huffNode[:nonNullRank+1] { + nbPerRank[v.nbBits()]++ + } + // determine stating value per rank + { + min := uint16(0) + for n := maxNbBits; n > 0; n-- { + // get starting value within each rank + valPerRank[n] = min + min += nbPerRank[n] + min >>= 1 + } + } + + // push nbBits per symbol, symbol order + for _, v := range huffNode[:nonNullRank+1] { + s.cTable[v.symbol()].nBits = v.nbBits() + } + + // assign value within rank, symbol order + t := s.cTable[:s.symbolLen] + for n, val := range t { + nbits := val.nBits & 15 + v := valPerRank[nbits] + t[n].val = v + valPerRank[nbits] = v + 1 + } + + return nil +} + +// huffSort will sort symbols, decreasing order. +func (s *Scratch) huffSort() { + type rankPos struct { + base uint32 + current uint32 + } + + // Clear nodes + nodes := s.nodes[:huffNodesLen+1] + s.nodes = nodes + nodes = nodes[1 : huffNodesLen+1] + + // Sort into buckets based on length of symbol count. + var rank [32]rankPos + for _, v := range s.count[:s.symbolLen] { + r := highBit32(v+1) & 31 + rank[r].base++ + } + // maxBitLength is log2(BlockSizeMax) + 1 + const maxBitLength = 18 + 1 + for n := maxBitLength; n > 0; n-- { + rank[n-1].base += rank[n].base + } + for n := range rank[:maxBitLength] { + rank[n].current = rank[n].base + } + for n, c := range s.count[:s.symbolLen] { + r := (highBit32(c+1) + 1) & 31 + pos := rank[r].current + rank[r].current++ + prev := nodes[(pos-1)&huffNodesMask] + for pos > rank[r].base && c > prev.count() { + nodes[pos&huffNodesMask] = prev + pos-- + prev = nodes[(pos-1)&huffNodesMask] + } + nodes[pos&huffNodesMask] = makeNodeElt(c, byte(n)) + } +} + +func (s *Scratch) setMaxHeight(lastNonNull int) uint8 { + maxNbBits := s.actualTableLog + huffNode := s.nodes[1 : huffNodesLen+1] + //huffNode = huffNode[: huffNodesLen] + + largestBits := huffNode[lastNonNull].nbBits() + + // early exit : no elt > maxNbBits + if largestBits <= maxNbBits { + return largestBits + } + totalCost := int(0) + baseCost := int(1) << (largestBits - maxNbBits) + n := uint32(lastNonNull) + + for huffNode[n].nbBits() > maxNbBits { + totalCost += baseCost - (1 << (largestBits - huffNode[n].nbBits())) + huffNode[n].setNbBits(maxNbBits) + n-- + } + // n stops at huffNode[n].nbBits <= maxNbBits + + for huffNode[n].nbBits() == maxNbBits { + n-- + } + // n end at index of smallest symbol using < maxNbBits + + // renorm totalCost + totalCost >>= largestBits - maxNbBits /* note : totalCost is necessarily a multiple of baseCost */ + + // repay normalized cost + { + const noSymbol = 0xF0F0F0F0 + var rankLast [tableLogMax + 2]uint32 + + for i := range rankLast[:] { + rankLast[i] = noSymbol + } + + // Get pos of last (smallest) symbol per rank + { + currentNbBits := maxNbBits + for pos := int(n); pos >= 0; pos-- { + if huffNode[pos].nbBits() >= currentNbBits { + continue + } + currentNbBits = huffNode[pos].nbBits() // < maxNbBits + rankLast[maxNbBits-currentNbBits] = uint32(pos) + } + } + + for totalCost > 0 { + nBitsToDecrease := uint8(highBit32(uint32(totalCost))) + 1 + + for ; nBitsToDecrease > 1; nBitsToDecrease-- { + highPos := rankLast[nBitsToDecrease] + lowPos := rankLast[nBitsToDecrease-1] + if highPos == noSymbol { + continue + } + if lowPos == noSymbol { + break + } + highTotal := huffNode[highPos].count() + lowTotal := 2 * huffNode[lowPos].count() + if highTotal <= lowTotal { + break + } + } + // only triggered when no more rank 1 symbol left => find closest one (note : there is necessarily at least one !) + // HUF_MAX_TABLELOG test just to please gcc 5+; but it should not be necessary + // FIXME: try to remove + for (nBitsToDecrease <= tableLogMax) && (rankLast[nBitsToDecrease] == noSymbol) { + nBitsToDecrease++ + } + totalCost -= 1 << (nBitsToDecrease - 1) + if rankLast[nBitsToDecrease-1] == noSymbol { + // this rank is no longer empty + rankLast[nBitsToDecrease-1] = rankLast[nBitsToDecrease] + } + huffNode[rankLast[nBitsToDecrease]].setNbBits(1 + + huffNode[rankLast[nBitsToDecrease]].nbBits()) + if rankLast[nBitsToDecrease] == 0 { + /* special case, reached largest symbol */ + rankLast[nBitsToDecrease] = noSymbol + } else { + rankLast[nBitsToDecrease]-- + if huffNode[rankLast[nBitsToDecrease]].nbBits() != maxNbBits-nBitsToDecrease { + rankLast[nBitsToDecrease] = noSymbol /* this rank is now empty */ + } + } + } + + for totalCost < 0 { /* Sometimes, cost correction overshoot */ + if rankLast[1] == noSymbol { /* special case : no rank 1 symbol (using maxNbBits-1); let's create one from largest rank 0 (using maxNbBits) */ + for huffNode[n].nbBits() == maxNbBits { + n-- + } + huffNode[n+1].setNbBits(huffNode[n+1].nbBits() - 1) + rankLast[1] = n + 1 + totalCost++ + continue + } + huffNode[rankLast[1]+1].setNbBits(huffNode[rankLast[1]+1].nbBits() - 1) + rankLast[1]++ + totalCost++ + } + } + return maxNbBits +} + +// A nodeElt is the fields +// +// count uint32 +// parent uint16 +// symbol byte +// nbBits uint8 +// +// in some order, all squashed into an integer so that the compiler +// always loads and stores entire nodeElts instead of separate fields. +type nodeElt uint64 + +func makeNodeElt(count uint32, symbol byte) nodeElt { + return nodeElt(count) | nodeElt(symbol)<<48 +} + +func (e *nodeElt) count() uint32 { return uint32(*e) } +func (e *nodeElt) parent() uint16 { return uint16(*e >> 32) } +func (e *nodeElt) symbol() byte { return byte(*e >> 48) } +func (e *nodeElt) nbBits() uint8 { return uint8(*e >> 56) } + +func (e *nodeElt) setCount(c uint32) { *e = (*e)&0xffffffff00000000 | nodeElt(c) } +func (e *nodeElt) setParent(p int16) { *e = (*e)&0xffff0000ffffffff | nodeElt(uint16(p))<<32 } +func (e *nodeElt) setNbBits(n uint8) { *e = (*e)&0x00ffffffffffffff | nodeElt(n)<<56 } diff --git a/llo/internal/zstdenc/huff0/huff0.go b/llo/internal/zstdenc/huff0/huff0.go new file mode 100644 index 00000000..57acfc8a --- /dev/null +++ b/llo/internal/zstdenc/huff0/huff0.go @@ -0,0 +1,257 @@ +// Package huff0 provides fast huffman encoding as used in zstd. +// +// See README.md at https://github.com/klauspost/compress/tree/master/huff0 for details. +package huff0 + +import ( + "errors" + "fmt" + "math/bits" + + "github.com/smartcontractkit/chainlink-data-streams/llo/internal/zstdenc/fse" +) + +const ( + maxSymbolValue = 255 + + // zstandard limits tablelog to 11, see: + // https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#huffman-tree-description + tableLogMax = 11 + tableLogDefault = 11 + minTablelog = 5 + huffNodesLen = 512 + + // BlockSizeMax is maximum input size for a single block uncompressed. + BlockSizeMax = 1<<18 - 1 +) + +var ( + // ErrIncompressible is returned when input is judged to be too hard to compress. + ErrIncompressible = errors.New("input is not compressible") + + // ErrUseRLE is returned from the compressor when the input is a single byte value repeated. + ErrUseRLE = errors.New("input is single value repeated") + + // ErrTooBig is return if input is too large for a single block. + ErrTooBig = errors.New("input too big") + + // ErrMaxDecodedSizeExceeded is return if input is too large for a single block. + ErrMaxDecodedSizeExceeded = errors.New("maximum output size exceeded") +) + +type ReusePolicy uint8 + +const ( + // ReusePolicyAllow will allow reuse if it produces smaller output. + ReusePolicyAllow ReusePolicy = iota + + // ReusePolicyPrefer will re-use aggressively if possible. + // This will not check if a new table will produce smaller output, + // except if the current table is impossible to use or + // compressed output is bigger than input. + ReusePolicyPrefer + + // ReusePolicyNone will disable re-use of tables. + // This is slightly faster than ReusePolicyAllow but may produce larger output. + ReusePolicyNone + + // ReusePolicyMust must allow reuse and produce smaller output. + ReusePolicyMust +) + +type Scratch struct { + count [maxSymbolValue + 1]uint32 + + // Per block parameters. + // These can be used to override compression parameters of the block. + // Do not touch, unless you know what you are doing. + + // Out is output buffer. + // If the scratch is re-used before the caller is done processing the output, + // set this field to nil. + // Otherwise the output buffer will be re-used for next Compression/Decompression step + // and allocation will be avoided. + Out []byte + + // OutTable will contain the table data only, if a new table has been generated. + // Slice of the returned data. + OutTable []byte + + // OutData will contain the compressed data. + // Slice of the returned data. + OutData []byte + + // MaxDecodedSize will set the maximum allowed output size. + // This value will automatically be set to BlockSizeMax if not set. + // Decoders will return ErrMaxDecodedSizeExceeded is this limit is exceeded. + MaxDecodedSize int + + srcLen int + + // MaxSymbolValue will override the maximum symbol value of the next block. + MaxSymbolValue uint8 + + // TableLog will attempt to override the tablelog for the next block. + // Must be <= 11 and >= 5. + TableLog uint8 + + // Reuse will specify the reuse policy + Reuse ReusePolicy + + // WantLogLess allows to specify a log 2 reduction that should at least be achieved, + // otherwise the block will be returned as incompressible. + // The reduction should then at least be (input size >> WantLogLess) + // If WantLogLess == 0 any improvement will do. + WantLogLess uint8 + + symbolLen uint16 // Length of active part of the symbol table. + maxCount int // count of the most probable symbol + clearCount bool // clear count + actualTableLog uint8 // Selected tablelog. + prevTableLog uint8 // Tablelog for previous table + prevTable cTable // Table used for previous compression. + cTable cTable // compression table + nodes []nodeElt + fse *fse.Scratch + huffWeight [maxSymbolValue + 1]byte +} + +// TransferCTable will transfer the previously used compression table. +func (s *Scratch) TransferCTable(src *Scratch) { + if cap(s.prevTable) < len(src.prevTable) { + s.prevTable = make(cTable, 0, maxSymbolValue+1) + } + s.prevTable = s.prevTable[:len(src.prevTable)] + copy(s.prevTable, src.prevTable) + s.prevTableLog = src.prevTableLog +} + +func (s *Scratch) prepare(in []byte) (*Scratch, error) { + if len(in) > BlockSizeMax { + return nil, ErrTooBig + } + if s == nil { + s = &Scratch{} + } + if s.MaxSymbolValue == 0 { + s.MaxSymbolValue = maxSymbolValue + } + if s.TableLog == 0 { + s.TableLog = tableLogDefault + } + if s.TableLog > tableLogMax || s.TableLog < minTablelog { + return nil, fmt.Errorf(" invalid tableLog %d (%d -> %d)", s.TableLog, minTablelog, tableLogMax) + } + if s.MaxDecodedSize <= 0 || s.MaxDecodedSize > BlockSizeMax { + s.MaxDecodedSize = BlockSizeMax + } + if s.clearCount && s.maxCount == 0 { + for i := range s.count { + s.count[i] = 0 + } + s.clearCount = false + } + if cap(s.Out) == 0 { + s.Out = make([]byte, 0, len(in)) + } + s.Out = s.Out[:0] + + s.OutTable = nil + s.OutData = nil + if cap(s.nodes) < huffNodesLen+1 { + s.nodes = make([]nodeElt, 0, huffNodesLen+1) + } + s.nodes = s.nodes[:0] + if s.fse == nil { + s.fse = &fse.Scratch{} + } + s.srcLen = len(in) + + return s, nil +} + +type cTable []cTableEntry + +func (c cTable) write(s *Scratch) error { + var ( + // precomputed conversion table + bitsToWeight [tableLogMax + 1]byte + huffLog = s.actualTableLog + // last weight is not saved. + maxSymbolValue = uint8(s.symbolLen - 1) + huffWeight = s.huffWeight[:256] + ) + const ( + maxFSETableLog = 6 + ) + // convert to weight + bitsToWeight[0] = 0 + for n := uint8(1); n < huffLog+1; n++ { + bitsToWeight[n] = huffLog + 1 - n + } + + // Acquire histogram for FSE. + hist := s.fse.Histogram() + hist = hist[:256] + for i := range hist[:16] { + hist[i] = 0 + } + for n := range maxSymbolValue { + v := bitsToWeight[c[n].nBits] & 15 + huffWeight[n] = v + hist[v]++ + } + + // FSE compress if feasible. + if maxSymbolValue >= 2 { + huffMaxCnt := uint32(0) + huffMax := uint8(0) + for i, v := range hist[:16] { + if v == 0 { + continue + } + huffMax = byte(i) + if v > huffMaxCnt { + huffMaxCnt = v + } + } + s.fse.HistogramFinished(huffMax, int(huffMaxCnt)) + s.fse.TableLog = maxFSETableLog + b, err := fse.Compress(huffWeight[:maxSymbolValue], s.fse) + if err == nil && len(b) < int(s.symbolLen>>1) { + s.Out = append(s.Out, uint8(len(b))) + s.Out = append(s.Out, b...) + return nil + } + // Unable to compress (RLE/uncompressible) + } + // write raw values as 4-bits (max : 15) + if maxSymbolValue > (256 - 128) { + // should not happen : likely means source cannot be compressed + return ErrIncompressible + } + op := s.Out + // special case, pack weights 4 bits/weight. + op = append(op, 128|(maxSymbolValue-1)) + // be sure it doesn't cause msan issue in final combination + huffWeight[maxSymbolValue] = 0 + for n := uint16(0); n < uint16(maxSymbolValue); n += 2 { + op = append(op, (huffWeight[n]<<4)|huffWeight[n+1]) + } + s.Out = op + return nil +} + +// estimateSize returns the estimated size in bytes of the input represented in the +// histogram supplied. +func (c cTable) estimateSize(hist []uint32) int { + nbBits := uint32(7) + for i, v := range c[:len(hist)] { + nbBits += uint32(v.nBits) * hist[i] + } + return int(nbBits >> 3) +} + +func highBit32(val uint32) (n uint32) { + return uint32(bits.Len32(val) - 1) +} diff --git a/llo/internal/zstdenc/internal/le/le.go b/llo/internal/zstdenc/internal/le/le.go new file mode 100644 index 00000000..e54909e1 --- /dev/null +++ b/llo/internal/zstdenc/internal/le/le.go @@ -0,0 +1,5 @@ +package le + +type Indexer interface { + int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64 +} diff --git a/llo/internal/zstdenc/internal/le/unsafe_disabled.go b/llo/internal/zstdenc/internal/le/unsafe_disabled.go new file mode 100644 index 00000000..27f41d8b --- /dev/null +++ b/llo/internal/zstdenc/internal/le/unsafe_disabled.go @@ -0,0 +1,22 @@ +//go:build !(amd64 || arm64 || ppc64le || riscv64) || nounsafe || purego + +package le + +import ( + "encoding/binary" +) + +// Load32 will load from b at index i. +func Load32[I Indexer](b []byte, i I) uint32 { + return binary.LittleEndian.Uint32(b[i:]) +} + +// Load64 will load from b at index i. +func Load64[I Indexer](b []byte, i I) uint64 { + return binary.LittleEndian.Uint64(b[i:]) +} + +// Store64 will store v at b. +func Store64[I Indexer](b []byte, i I, v uint64) { + binary.LittleEndian.PutUint64(b[i:], v) +} diff --git a/llo/internal/zstdenc/internal/le/unsafe_enabled.go b/llo/internal/zstdenc/internal/le/unsafe_enabled.go new file mode 100644 index 00000000..c4aeefe6 --- /dev/null +++ b/llo/internal/zstdenc/internal/le/unsafe_enabled.go @@ -0,0 +1,28 @@ +// We enable 64 bit LE platforms: + +//go:build (amd64 || arm64 || ppc64le || riscv64) && !nounsafe && !purego + +package le + +import ( + "unsafe" +) + +// Load32 will load from b at index i. +func Load32[I Indexer](b []byte, i I) uint32 { + //return binary.LittleEndian.Uint32(b[i:]) + //return *(*uint32)(unsafe.Pointer(&b[i])) + return *(*uint32)(unsafe.Add(unsafe.Pointer(unsafe.SliceData(b)), i)) +} + +// Load64 will load from b at index i. +func Load64[I Indexer](b []byte, i I) uint64 { + //return binary.LittleEndian.Uint64(b[i:]) + //return *(*uint64)(unsafe.Pointer(&b[i])) + return *(*uint64)(unsafe.Add(unsafe.Pointer(unsafe.SliceData(b)), i)) +} + +// Store64 will store v at b[i:]. +func Store64[I Indexer](b []byte, i I, v uint64) { + *(*uint64)(unsafe.Add(unsafe.Pointer(unsafe.SliceData(b)), i)) = v +} diff --git a/llo/internal/zstdenc/internal/regmask/regmask.go b/llo/internal/zstdenc/internal/regmask/regmask.go new file mode 100644 index 00000000..3da49d15 --- /dev/null +++ b/llo/internal/zstdenc/internal/regmask/regmask.go @@ -0,0 +1,50 @@ +//go:build !386 + +// Package regmask provides masks for variable shift counts. +// +// Go defines a shift by more than the width of the shifted value as producing +// zero, so the compiler has to guard every variable shift against that: on +// amd64 with a CMP and an SBB, on arm64 with a CMP and a CSEL, and so on. When +// the count is known to be smaller than the width anyway, masking it with the +// width minus one lets the compiler drop the guard. The mask itself costs +// nothing on the architectures whose shift instructions already use only the +// low bits of the count, which the compiler knows about. +// +// Each constant is named for the width of the value being shifted and the type +// of the shift count, and may only be used where the count is always smaller +// than that width: +// +// x := y >> (n & regmask.Shift64ByUint) // y is 64 bits, n is a uint below 64 +package regmask + +const ( + // ShiftNByUint8 - shifting an N bit value by a uint8 + Shift8ByUint8 = 7 + Shift16ByUint8 = 15 + Shift32ByUint8 = 31 + Shift64ByUint8 = 63 + + // ShiftNByUint16 - shifting an N bit value by a uint16 + Shift8ByUint16 = Shift8ByUint8 + Shift16ByUint16 = Shift16ByUint8 + Shift32ByUint16 = Shift32ByUint8 + Shift64ByUint16 = Shift64ByUint8 + + // ShiftNByUint32 - shifting an N bit value by a uint32 + Shift8ByUint32 = Shift8ByUint8 + Shift16ByUint32 = Shift16ByUint8 + Shift32ByUint32 = Shift32ByUint8 + Shift64ByUint32 = Shift64ByUint8 + + // ShiftNByUint64 - shifting an N bit value by a uint64 + Shift8ByUint64 = Shift8ByUint8 + Shift16ByUint64 = Shift16ByUint8 + Shift32ByUint64 = Shift32ByUint8 + Shift64ByUint64 = Shift64ByUint8 + + // ShiftNByUint - shifting an N bit value by a uint + Shift8ByUint = Shift8ByUint8 + Shift16ByUint = Shift16ByUint8 + Shift32ByUint = Shift32ByUint8 + Shift64ByUint = Shift64ByUint8 +) diff --git a/llo/internal/zstdenc/internal/regmask/regmask_386.go b/llo/internal/zstdenc/internal/regmask/regmask_386.go new file mode 100644 index 00000000..ff15f7c1 --- /dev/null +++ b/llo/internal/zstdenc/internal/regmask/regmask_386.go @@ -0,0 +1,39 @@ +//go:build 386 + +package regmask + +// A 64 bit shift on 386 is synthesized from 32 bit instructions, and masking its +// count makes the compiler emit more code rather than less, so those masks are +// no-ops here: each is the largest value its count type can hold, which the +// compiler folds away. Shifts of narrower values behave as elsewhere. +const ( + // ShiftNByUint8 - shifting an N bit value by a uint8 + Shift8ByUint8 = 7 + Shift16ByUint8 = 15 + Shift32ByUint8 = 31 + Shift64ByUint8 = 0xff + + // ShiftNByUint16 - shifting an N bit value by a uint16 + Shift8ByUint16 = Shift8ByUint8 + Shift16ByUint16 = Shift16ByUint8 + Shift32ByUint16 = Shift32ByUint8 + Shift64ByUint16 = 0xffff + + // ShiftNByUint32 - shifting an N bit value by a uint32 + Shift8ByUint32 = Shift8ByUint8 + Shift16ByUint32 = Shift16ByUint8 + Shift32ByUint32 = Shift32ByUint8 + Shift64ByUint32 = 0xffffffff + + // ShiftNByUint64 - shifting an N bit value by a uint64 + Shift8ByUint64 = Shift8ByUint8 + Shift16ByUint64 = Shift16ByUint8 + Shift32ByUint64 = Shift32ByUint8 + Shift64ByUint64 = 0xffffffffffffffff + + // ShiftNByUint - shifting an N bit value by a uint + Shift8ByUint = Shift8ByUint8 + Shift16ByUint = Shift16ByUint8 + Shift32ByUint = Shift32ByUint8 + Shift64ByUint = ^uint(0) +) diff --git a/llo/internal/zstdenc/zstd/bitwriter.go b/llo/internal/zstdenc/zstd/bitwriter.go new file mode 100644 index 00000000..7ade771d --- /dev/null +++ b/llo/internal/zstdenc/zstd/bitwriter.go @@ -0,0 +1,131 @@ +// Copyright 2018 Klaus Post. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. +// Based on work Copyright (c) 2013, Yann Collet, released under BSD License. + +package zstd + +import ( + "github.com/smartcontractkit/chainlink-data-streams/llo/internal/zstdenc/internal/le" + "github.com/smartcontractkit/chainlink-data-streams/llo/internal/zstdenc/internal/regmask" +) + +// bitState is a bit writer that stays in registers when passed and +// returned by value. It writes into a buffer owned by the caller. +type bitState struct { + c uint64 + nb uint + pos int +} + +// flush writes the whole bytes with one 8-byte store at pos, leaving +// at most 7 bits. buf must have 8 bytes of room at pos. +func (s bitState) flush(buf []byte) bitState { + le.Store64(buf, s.pos, s.c) + s.pos += int(s.nb >> 3) + s.c >>= (s.nb &^ 7) & regmask.Shift64ByUint + s.nb &= 7 + return s +} + +// add adds n bits from v, which must have no bits set above them. +// There must be room for them. +func (s bitState) add(v uint64, n uint) bitState { + s.c |= v << (s.nb & regmask.Shift64ByUint) + s.nb += n + return s +} + +// addState adds the bits that FSE-encode tt from state, and returns +// the next state from tab. +func (s bitState) addState(state uint16, tab []uint16, tt symbolTransform) (bitState, uint16) { + nbBitsOut := (uint32(state) + tt.deltaNbBits) >> 16 + s = s.add(uint64(state&bitMask16[nbBitsOut&31]), uint(nbBitsOut)) + return s, tab[int32(state>>(nbBitsOut®mask.Shift16ByUint32))+int32(tt.deltaFindState)] +} + +// bitWriter will write bits. +// First bit will be LSB of the first byte of output. +type bitWriter struct { + bitContainer uint64 + nBits uint8 + out []byte +} + +// bitMask16 is bitmasks. Has extra to avoid bounds check. +var bitMask16 = [32]uint16{ + 0, 1, 3, 7, 0xF, 0x1F, + 0x3F, 0x7F, 0xFF, 0x1FF, 0x3FF, 0x7FF, + 0xFFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF, 0xFFFF, + 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, + 0xFFFF, 0xFFFF} /* up to 16 bits */ + +var bitMask32 = [32]uint32{ + 0, 1, 3, 7, 0xF, 0x1F, 0x3F, 0x7F, 0xFF, + 0x1FF, 0x3FF, 0x7FF, 0xFFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF, + 0x1ffff, 0x3ffff, 0x7FFFF, 0xfFFFF, 0x1fFFFF, 0x3fFFFF, 0x7fFFFF, 0xffFFFF, + 0x1ffFFFF, 0x3ffFFFF, 0x7ffFFFF, 0xfffFFFF, 0x1fffFFFF, 0x3fffFFFF, 0x7fffFFFF, +} // up to 32 bits + +// addBits16NC will add up to 16 bits. +// It will not check if there is space for them, +// so the caller must ensure that it has flushed recently. +func (b *bitWriter) addBits16NC(value uint16, bits uint8) { + b.bitContainer |= uint64(value&bitMask16[bits&31]) << (b.nBits & 63) + b.nBits += bits +} + +// addBits32NC will add up to 31 bits. +// It will not check if there is space for them, +// so the caller must ensure that it has flushed recently. +func (b *bitWriter) addBits32NC(value uint32, bits uint8) { + b.bitContainer |= uint64(value&bitMask32[bits&31]) << (b.nBits & 63) + b.nBits += bits +} + +// addBits16Clean will add up to 16 bits. value may not contain more set bits than indicated. +// It will not check if there is space for them, so the caller must ensure that it has flushed recently. +func (b *bitWriter) addBits16Clean(value uint16, bits uint8) { + b.bitContainer |= uint64(value) << (b.nBits & 63) + b.nBits += bits +} + +// flush32 will flush out, so there are at least 32 bits available for writing. +func (b *bitWriter) flush32() { + if b.nBits < 32 { + return + } + b.out = append(b.out, + byte(b.bitContainer), + byte(b.bitContainer>>8), + byte(b.bitContainer>>16), + byte(b.bitContainer>>24)) + b.nBits -= 32 + b.bitContainer >>= 32 +} + +// flushAlign will flush remaining full bytes and align to next byte boundary. +func (b *bitWriter) flushAlign() { + nbBytes := (b.nBits + 7) >> 3 + for i := range nbBytes { + b.out = append(b.out, byte(b.bitContainer>>(i*8))) + } + b.nBits = 0 + b.bitContainer = 0 +} + +// close will write the alignment bit and write the final byte(s) +// to the output. +func (b *bitWriter) close() { + // End mark + b.addBits16Clean(1, 1) + // flush until next byte. + b.flushAlign() +} + +// reset and continue writing by appending to out. +func (b *bitWriter) reset(out []byte) { + b.bitContainer = 0 + b.nBits = 0 + b.out = out +} diff --git a/llo/internal/zstdenc/zstd/blockdec.go b/llo/internal/zstdenc/zstd/blockdec.go new file mode 100644 index 00000000..50e80dc5 --- /dev/null +++ b/llo/internal/zstdenc/zstd/blockdec.go @@ -0,0 +1,34 @@ +// Copyright 2019+ Klaus Post. All rights reserved. +// License information can be found in the LICENSE file. +// Based on work by Yann Collet, released under BSD License. + +package zstd + +type blockType uint8 + +//go:generate stringer -type=blockType,literalsBlockType,seqCompMode,tableIndex + +const ( + blockTypeRaw blockType = iota + blockTypeRLE + blockTypeCompressed + blockTypeReserved +) + +type literalsBlockType uint8 + +const ( + literalsBlockRaw literalsBlockType = iota + literalsBlockRLE + literalsBlockCompressed + literalsBlockTreeless +) + +const ( + // maxCompressedBlockSize is the biggest allowed compressed block size (128KB) + maxCompressedBlockSize = 128 << 10 + + // We support slightly less than the reference decoder to be able to + // use ints on 32 bit archs. + maxOffsetBits = 30 +) diff --git a/llo/internal/zstdenc/zstd/blockenc.go b/llo/internal/zstdenc/zstd/blockenc.go new file mode 100644 index 00000000..6ce4304f --- /dev/null +++ b/llo/internal/zstdenc/zstd/blockenc.go @@ -0,0 +1,784 @@ +// Copyright 2019+ Klaus Post. All rights reserved. +// License information can be found in the LICENSE file. +// Based on work by Yann Collet, released under BSD License. + +package zstd + +import ( + "errors" + "fmt" + "math" + "math/bits" + "slices" + + "github.com/smartcontractkit/chainlink-data-streams/llo/internal/zstdenc/huff0" +) + +type blockEnc struct { + size int + literals []byte + sequences []seq + coders seqCoders + litEnc *huff0.Scratch + dictLitEnc *huff0.Scratch + wr bitWriter + + extraLits int + output []byte + recentOffsets [3]uint32 + prevRecentOffsets [3]uint32 + + last bool + lowMem bool +} + +// init should be used once the block has been created. +// If called more than once, the effect is the same as calling reset. +func (b *blockEnc) init() { + if b.lowMem { + // 1K literals + if cap(b.literals) < 1<<10 { + b.literals = make([]byte, 0, 1<<10) + } + const defSeqs = 20 + if cap(b.sequences) < defSeqs { + b.sequences = make([]seq, 0, defSeqs) + } + // 1K + if cap(b.output) < 1<<10 { + b.output = make([]byte, 0, 1<<10) + } + } else { + if cap(b.literals) < maxCompressedBlockSize { + b.literals = make([]byte, 0, maxCompressedBlockSize) + } + const defSeqs = 2000 + if cap(b.sequences) < defSeqs { + b.sequences = make([]seq, 0, defSeqs) + } + if cap(b.output) < maxCompressedBlockSize { + b.output = make([]byte, 0, maxCompressedBlockSize) + } + } + + if b.coders.mlEnc == nil { + b.coders.mlEnc = &fseEncoder{} + b.coders.mlPrev = &fseEncoder{} + b.coders.ofEnc = &fseEncoder{} + b.coders.ofPrev = &fseEncoder{} + b.coders.llEnc = &fseEncoder{} + b.coders.llPrev = &fseEncoder{} + } + b.litEnc = &huff0.Scratch{WantLogLess: 4} + b.reset(nil) +} + +// initNewEncode can be used to reset offsets and encoders to the initial state. +func (b *blockEnc) initNewEncode() { + b.recentOffsets = [3]uint32{1, 4, 8} + b.litEnc.Reuse = huff0.ReusePolicyNone + b.coders.setPrev(nil, nil, nil) + b.dictLitEnc = nil +} + +// reset will reset the block for a new encode, but in the same stream, +// meaning that state will be carried over, but the block content is reset. +// If a previous block is provided, the recent offsets are carried over. +func (b *blockEnc) reset(prev *blockEnc) { + b.extraLits = 0 + b.literals = b.literals[:0] + b.size = 0 + b.sequences = b.sequences[:0] + b.output = b.output[:0] + b.last = false + if prev != nil { + b.recentOffsets = prev.prevRecentOffsets + } + b.dictLitEnc = nil +} + +// blockHeader contains the information for a block header. +type blockHeader uint32 + +// setLast sets the 'last' indicator on a block. +func (h *blockHeader) setLast(b bool) { + if b { + *h = *h | 1 + } else { + const mask = (1 << 24) - 2 + *h = *h & mask + } +} + +// setSize will store the compressed size of a block. +func (h *blockHeader) setSize(v uint32) { + const mask = 7 + *h = (*h)&mask | blockHeader(v<<3) +} + +// setType sets the block type. +func (h *blockHeader) setType(t blockType) { + const mask = 1 | (((1 << 24) - 1) ^ 7) + *h = (*h & mask) | blockHeader(t<<1) +} + +// appendTo will append the block header to a slice. +func (h blockHeader) appendTo(b []byte) []byte { + return append(b, uint8(h), uint8(h>>8), uint8(h>>16)) +} + +// literalsHeader contains literals header information. +type literalsHeader uint64 + +// setType can be used to set the type of literal block. +func (h *literalsHeader) setType(t literalsBlockType) { + const mask = math.MaxUint64 - 3 + *h = (*h & mask) | literalsHeader(t) +} + +// setSize can be used to set a single size, for uncompressed and RLE content. +func (h *literalsHeader) setSize(regenLen int) { + inBits := bits.Len32(uint32(regenLen)) + // Only retain 2 bits + const mask = 3 + lh := uint64(*h & mask) + switch { + case inBits < 5: + lh |= (uint64(regenLen) << 3) | (1 << 60) + if debugEncoder { + got := int(lh>>3) & 0xff + if got != regenLen { + panic(fmt.Sprint("litRegenSize = ", regenLen, "(want) != ", got, "(got)")) + } + } + case inBits < 12: + lh |= (1 << 2) | (uint64(regenLen) << 4) | (2 << 60) + case inBits < 20: + lh |= (3 << 2) | (uint64(regenLen) << 4) | (3 << 60) + default: + panic(fmt.Errorf("internal error: block too big (%d)", regenLen)) + } + *h = literalsHeader(lh) +} + +// setSizes will set the size of a compressed literals section and the input length. +func (h *literalsHeader) setSizes(compLen, inLen int, single bool) { + compBits, inBits := bits.Len32(uint32(compLen)), bits.Len32(uint32(inLen)) + // Only retain 2 bits + const mask = 3 + lh := uint64(*h & mask) + switch { + case compBits <= 10 && inBits <= 10: + if !single { + lh |= 1 << 2 + } + lh |= (uint64(inLen) << 4) | (uint64(compLen) << (10 + 4)) | (3 << 60) + if debugEncoder { + const mmask = (1 << 24) - 1 + n := (lh >> 4) & mmask + if int(n&1023) != inLen { + panic(fmt.Sprint("regensize:", int(n&1023), "!=", inLen, inBits)) + } + if int(n>>10) != compLen { + panic(fmt.Sprint("compsize:", int(n>>10), "!=", compLen, compBits)) + } + } + case compBits <= 14 && inBits <= 14: + lh |= (2 << 2) | (uint64(inLen) << 4) | (uint64(compLen) << (14 + 4)) | (4 << 60) + if single { + panic("single stream used with more than 10 bits length.") + } + case compBits <= 18 && inBits <= 18: + lh |= (3 << 2) | (uint64(inLen) << 4) | (uint64(compLen) << (18 + 4)) | (5 << 60) + if single { + panic("single stream used with more than 10 bits length.") + } + default: + panic("internal error: block too big") + } + *h = literalsHeader(lh) +} + +// appendTo will append the literals header to a byte slice. +func (h literalsHeader) appendTo(b []byte) []byte { + size := uint8(h >> 60) + switch size { + case 1: + b = append(b, uint8(h)) + case 2: + b = append(b, uint8(h), uint8(h>>8)) + case 3: + b = append(b, uint8(h), uint8(h>>8), uint8(h>>16)) + case 4: + b = append(b, uint8(h), uint8(h>>8), uint8(h>>16), uint8(h>>24)) + case 5: + b = append(b, uint8(h), uint8(h>>8), uint8(h>>16), uint8(h>>24), uint8(h>>32)) + default: + panic(fmt.Errorf("internal error: literalsHeader has invalid size (%d)", size)) + } + return b +} + +// size returns the output size with currently set values. +func (h literalsHeader) size() int { + return int(h >> 60) +} + +// pushOffsets will push the recent offsets to the backup store. +func (b *blockEnc) pushOffsets() { + b.prevRecentOffsets = b.recentOffsets +} + +// pushOffsets will push the recent offsets to the backup store. +func (b *blockEnc) popOffsets() { + b.recentOffsets = b.prevRecentOffsets +} + +// encodeRaw can be used to set the output to a raw representation of supplied bytes. +func (b *blockEnc) encodeRawTo(dst, src []byte) []byte { + var bh blockHeader + bh.setLast(b.last) + bh.setSize(uint32(len(src))) + bh.setType(blockTypeRaw) + dst = bh.appendTo(dst) + dst = append(dst, src...) + if debugEncoder { + println("Adding RAW block, length", len(src), "last:", b.last) + } + return dst +} + +// encodeLits can be used if the block is only litLen. +func (b *blockEnc) encodeLits(lits []byte, raw bool) error { + var bh blockHeader + bh.setLast(b.last) + bh.setSize(uint32(len(lits))) + + // Don't compress extremely small blocks + if len(lits) < 8 || (len(lits) < 32 && b.dictLitEnc == nil) || raw { + if debugEncoder { + println("Adding RAW block, length", len(lits), "last:", b.last) + } + bh.setType(blockTypeRaw) + b.output = bh.appendTo(b.output) + b.output = append(b.output, lits...) + return nil + } + + var ( + out []byte + reUsed, single bool + err error + ) + if b.dictLitEnc != nil { + b.litEnc.TransferCTable(b.dictLitEnc) + b.litEnc.Reuse = huff0.ReusePolicyAllow + b.dictLitEnc = nil + } + if len(lits) >= 1024 { + // Use 4 Streams. + out, reUsed, err = huff0.Compress4X(lits, b.litEnc) + } else if len(lits) > 16 { + // Use 1 stream + single = true + out, reUsed, err = huff0.Compress1X(lits, b.litEnc) + } else { + err = huff0.ErrIncompressible + } + if err == nil && len(out)+5 > len(lits) { + // If we are close, we may still be worse or equal to raw. + var lh literalsHeader + lh.setSizes(len(out), len(lits), single) + if len(out)+lh.size() >= len(lits) { + err = huff0.ErrIncompressible + } + } + switch err { + case huff0.ErrIncompressible: + if debugEncoder { + println("Adding RAW block, length", len(lits), "last:", b.last) + } + bh.setType(blockTypeRaw) + b.output = bh.appendTo(b.output) + b.output = append(b.output, lits...) + return nil + case huff0.ErrUseRLE: + if debugEncoder { + println("Adding RLE block, length", len(lits)) + } + bh.setType(blockTypeRLE) + b.output = bh.appendTo(b.output) + b.output = append(b.output, lits[0]) + return nil + case nil: + default: + return err + } + // Compressed... + // Now, allow reuse + b.litEnc.Reuse = huff0.ReusePolicyAllow + bh.setType(blockTypeCompressed) + var lh literalsHeader + if reUsed { + if debugEncoder { + println("Reused tree, compressed to", len(out)) + } + lh.setType(literalsBlockTreeless) + } else { + if debugEncoder { + println("New tree, compressed to", len(out), "tree size:", len(b.litEnc.OutTable)) + } + lh.setType(literalsBlockCompressed) + } + // Set sizes + lh.setSizes(len(out), len(lits), single) + bh.setSize(uint32(len(out) + lh.size() + 1)) + + // Write block headers. + b.output = bh.appendTo(b.output) + b.output = lh.appendTo(b.output) + // Add compressed data. + b.output = append(b.output, out...) + // No sequences. + b.output = append(b.output, 0) + return nil +} + +// encodeRLE will encode an RLE block. +func (b *blockEnc) encodeRLE(val byte, length uint32) { + var bh blockHeader + bh.setLast(b.last) + bh.setSize(length) + bh.setType(blockTypeRLE) + b.output = bh.appendTo(b.output) + b.output = append(b.output, val) +} + +// encode will encode the block and append the output in b.output. +// Previous offset codes must be pushed if more blocks are expected. +func (b *blockEnc) encode(org []byte, raw, rawAllLits bool) error { + if len(b.sequences) == 0 { + return b.encodeLits(b.literals, rawAllLits) + } + if len(b.sequences) == 1 && len(org) > 0 && len(b.literals) <= 1 { + // Check common RLE cases. + seq := b.sequences[0] + if seq.litLen == uint32(len(b.literals)) && seq.offset-3 == 1 { + // Offset == 1 and 0 or 1 literals. + b.encodeRLE(org[0], b.sequences[0].matchLen+zstdMinMatch+seq.litLen) + return nil + } + } + + // We want some difference to at least account for the headers. + saved := b.size - len(b.literals) - (b.size >> 6) + if saved < 16 { + if org == nil { + return errIncompressible + } + b.popOffsets() + return b.encodeLits(org, rawAllLits) + } + + var bh blockHeader + var lh literalsHeader + bh.setLast(b.last) + bh.setType(blockTypeCompressed) + // Store offset of the block header. Needed when we know the size. + bhOffset := len(b.output) + b.output = bh.appendTo(b.output) + + var ( + out []byte + reUsed, single bool + err error + ) + if b.dictLitEnc != nil { + b.litEnc.TransferCTable(b.dictLitEnc) + b.litEnc.Reuse = huff0.ReusePolicyAllow + b.dictLitEnc = nil + } + if len(b.literals) >= 1024 && !raw { + // Use 4 Streams. + out, reUsed, err = huff0.Compress4X(b.literals, b.litEnc) + } else if len(b.literals) > 16 && !raw { + // Use 1 stream + single = true + out, reUsed, err = huff0.Compress1X(b.literals, b.litEnc) + } else { + err = huff0.ErrIncompressible + } + + if err == nil && len(out)+5 > len(b.literals) { + // If we are close, we may still be worse or equal to raw. + var lh literalsHeader + lh.setSize(len(b.literals)) + szRaw := lh.size() + lh.setSizes(len(out), len(b.literals), single) + szComp := lh.size() + if len(out)+szComp >= len(b.literals)+szRaw { + err = huff0.ErrIncompressible + } + } + switch err { + case huff0.ErrIncompressible: + lh.setType(literalsBlockRaw) + lh.setSize(len(b.literals)) + b.output = lh.appendTo(b.output) + b.output = append(b.output, b.literals...) + if debugEncoder { + println("Adding literals RAW, length", len(b.literals)) + } + case huff0.ErrUseRLE: + lh.setType(literalsBlockRLE) + lh.setSize(len(b.literals)) + b.output = lh.appendTo(b.output) + b.output = append(b.output, b.literals[0]) + if debugEncoder { + println("Adding literals RLE") + } + case nil: + // Compressed litLen... + if reUsed { + if debugEncoder { + println("reused tree") + } + lh.setType(literalsBlockTreeless) + } else { + if debugEncoder { + println("new tree, size:", len(b.litEnc.OutTable)) + } + lh.setType(literalsBlockCompressed) + } + lh.setSizes(len(out), len(b.literals), single) + if debugEncoder { + printf("Compressed %d literals to %d bytes", len(b.literals), len(out)) + println("Adding literal header:", lh) + } + b.output = lh.appendTo(b.output) + b.output = append(b.output, out...) + b.litEnc.Reuse = huff0.ReusePolicyAllow + if debugEncoder { + println("Adding literals compressed") + } + default: + if debugEncoder { + println("Adding literals ERROR:", err) + } + return err + } + // Sequence compression + + // Write the number of sequences + switch { + case len(b.sequences) < 128: + b.output = append(b.output, uint8(len(b.sequences))) + case len(b.sequences) < 0x7f00: // TODO: this could be wrong + n := len(b.sequences) + b.output = append(b.output, 128+uint8(n>>8), uint8(n)) + default: + n := len(b.sequences) - 0x7f00 + b.output = append(b.output, 255, uint8(n), uint8(n>>8)) + } + if debugEncoder { + println("Encoding", len(b.sequences), "sequences") + } + b.genCodes() + llEnc := b.coders.llEnc + ofEnc := b.coders.ofEnc + mlEnc := b.coders.mlEnc + err = llEnc.normalizeCount(len(b.sequences)) + if err != nil { + return err + } + err = ofEnc.normalizeCount(len(b.sequences)) + if err != nil { + return err + } + err = mlEnc.normalizeCount(len(b.sequences)) + if err != nil { + return err + } + + // Write compression mode + var mode uint8 + if llEnc.useRLE { + mode |= uint8(compModeRLE) << 6 + llEnc.setRLE(b.sequences[0].llCode) + if debugEncoder { + println("llEnc.useRLE") + } + } else { + var m seqCompMode + llEnc, m = b.chooseComp(llEnc, b.coders.llPrev, &fsePredefEnc[tableLiteralLengths]) + mode |= uint8(m) << 6 + } + if ofEnc.useRLE { + mode |= uint8(compModeRLE) << 4 + ofEnc.setRLE(b.sequences[0].ofCode) + if debugEncoder { + println("ofEnc.useRLE") + } + } else { + var m seqCompMode + ofEnc, m = b.chooseComp(ofEnc, b.coders.ofPrev, &fsePredefEnc[tableOffsets]) + mode |= uint8(m) << 4 + } + + if mlEnc.useRLE { + mode |= uint8(compModeRLE) << 2 + mlEnc.setRLE(b.sequences[0].mlCode) + if debugEncoder { + println("mlEnc.useRLE, code: ", b.sequences[0].mlCode, "value", b.sequences[0].matchLen) + } + } else { + var m seqCompMode + mlEnc, m = b.chooseComp(mlEnc, b.coders.mlPrev, &fsePredefEnc[tableMatchLengths]) + mode |= uint8(m) << 2 + } + b.output = append(b.output, mode) + if debugEncoder { + printf("Compression modes: 0b%b", mode) + } + b.output, err = llEnc.writeCount(b.output) + if err != nil { + return err + } + start := len(b.output) + b.output, err = ofEnc.writeCount(b.output) + if err != nil { + return err + } + if false { + println("block:", b.output[start:], "tablelog", ofEnc.actualTableLog, "maxcount:", ofEnc.maxCount) + fmt.Printf("selected TableLog: %d, Symbol length: %d\n", ofEnc.actualTableLog, ofEnc.symbolLen) + for i, v := range ofEnc.norm[:ofEnc.symbolLen] { + fmt.Printf("%3d: %5d -> %4d \n", i, ofEnc.count[i], v) + } + } + b.output, err = mlEnc.writeCount(b.output) + if err != nil { + return err + } + + // Maybe in block? + wr := &b.wr + wr.reset(b.output) + + var ll, of, ml cState + + // Current sequence + seq := len(b.sequences) - 1 + s := b.sequences[seq] + llEnc.setBits(llBitsTable[:]) + mlEnc.setBits(mlBitsTable[:]) + ofEnc.setBits(nil) + + llTT, ofTT, mlTT := llEnc.ct.symbolTT[:256], ofEnc.ct.symbolTT[:256], mlEnc.ct.symbolTT[:256] + + // We have 3 bounds checks here (and in the loop). + // Since we are iterating backwards it is kinda hard to avoid. + llB, ofB, mlB := llTT[s.llCode], ofTT[s.ofCode], mlTT[s.mlCode] + ll.init(wr, &llEnc.ct, llB) + of.init(wr, &ofEnc.ct, ofB) + wr.flush32() + ml.init(wr, &mlEnc.ct, mlB) + + // Each of these lookups also generates a bounds check. + wr.addBits32NC(s.litLen, llB.outBits) + wr.addBits32NC(s.matchLen, mlB.outBits) + wr.flush32() + wr.addBits32NC(s.offset, ofB.outBits) + if debugSequences { + println("Encoded seq", seq, s, "codes:", s.llCode, s.mlCode, s.ofCode, "states:", ll.state, ml.state, of.state, "bits:", llB, mlB, ofB) + } + seq-- + wr.flush32() + + // Store sequences in reverse, with the bit writer and states in locals. + // flush stores 8 bytes and advances by whole bytes, so each chunk + // checks room for seqMaxBytes per sequence plus the store's slack. + const seqMaxBytes = 12 // 26 state bits + 63 extra bits. + w := bitState{c: wr.bitContainer, nb: uint(wr.nBits), pos: len(wr.out)} + buf := wr.out[:cap(wr.out)] + ofState, mlState, llState := of.state, ml.state, ll.state + ofTab, mlTab, llTab := of.stateTable, ml.stateTable, ll.stateTable + seqs := b.sequences + for seq >= 0 { + n := (len(buf) - w.pos - 16) / seqMaxBytes + if n <= 0 { + buf = slices.Grow(buf[:w.pos], (seq+1)*seqMaxBytes+16) + buf = buf[:cap(buf)] + continue + } + for stop := max(seq-n, -1); seq > stop; seq-- { + s := seqs[seq] + ofB, mlB, llB := ofTT[s.ofCode], mlTT[s.mlCode], llTT[s.llCode] + + // w.nb <= 37 here, and the states add at most 26 bits. + w, ofState = w.addState(ofState, ofTab, ofB) + w, mlState = w.addState(mlState, mlTab, mlB) + w, llState = w.addState(llState, llTab, llB) + + ofBits, mlBits, llBits := ofB.outBits&31, mlB.outBits&31, llB.outBits&31 + extra := uint64(s.offset&bitMask32[ofBits])<<(mlBits+llBits) | + uint64(s.matchLen&bitMask32[mlBits])< 63 { + w = w.flush(buf) + if extraN > 56 { + // Only offsets over 24 bits get here. + low := uint(mlBits + llBits) + w = w.add(extra&(1<>= low + extraN -= low + } + } + w = w.add(extra, extraN).flush(buf) + + if debugSequences { + println("Encoded seq", seq, s) + } + } + } + wr.bitContainer, wr.nBits, wr.out = w.c, uint8(w.nb), buf[:w.pos] + of.state, ml.state, ll.state = ofState, mlState, llState + ml.flush(mlEnc.actualTableLog) + of.flush(ofEnc.actualTableLog) + ll.flush(llEnc.actualTableLog) + wr.close() + b.output = wr.out + + // Maybe even add a bigger margin. + if len(b.output)-3-bhOffset >= b.size { + // Discard and encode as raw block. + b.output = b.encodeRawTo(b.output[:bhOffset], org) + b.popOffsets() + b.litEnc.Reuse = huff0.ReusePolicyNone + return nil + } + + // Size is output minus block header. + bh.setSize(uint32(len(b.output)-bhOffset) - 3) + if debugEncoder { + println("Rewriting block header", bh) + } + _ = bh.appendTo(b.output[bhOffset:bhOffset]) + b.coders.setPrev(llEnc, mlEnc, ofEnc) + return nil +} + +// chooseComp chooses the cheapest of the new, predefined and previous table. +func (b *blockEnc) chooseComp(cur, prev, preDef *fseEncoder) (*fseEncoder, seqCompMode) { + hist := cur.count[:cur.symbolLen] + nSize := cur.approxSize(hist) + cur.maxHeaderSize() + predefSize := preDef.approxSize(hist) + prevSize := prev.approxSize(hist) + + // Add a small penalty for new encoders. + // Don't bother with extremely small (<2 byte gains). + nSize = nSize + (nSize+2*8*16)>>4 + // The previous table may come from a dictionary and fit poorly, + // so it is compared against the exact header size, without penalty. + nSizePrev := nSize + if prevSize != math.MaxUint32 { + // Written to spare capacity; the real header goes there later. + if hdr, err := cur.writeCount(b.output[len(b.output):]); err == nil { + nSizePrev = cur.approxSize(hist) + uint32(len(hdr))*8 + } + } + // Each stream ends with a flush of tableLog bits. + nSize += uint32(cur.actualTableLog) + nSizePrev += uint32(cur.actualTableLog) + if predefSize != math.MaxUint32 { + predefSize += uint32(preDef.actualTableLog) + } + if prevSize != math.MaxUint32 { + prevSize += uint32(prev.actualTableLog) + } + switch { + case predefSize <= prevSize && predefSize <= nSize || forcePreDef: + if debugEncoder { + println("Using predefined", predefSize>>3, "<=", nSize>>3) + } + return preDef, compModePredefined + case prevSize <= nSizePrev: + if debugEncoder { + println("Using previous", prevSize>>3, "<=", nSizePrev>>3) + } + return prev, compModeRepeat + default: + if debugEncoder { + println("Using new, predef", predefSize>>3, ". previous:", prevSize>>3, ">", nSize>>3, "header max:", cur.maxHeaderSize()>>3, "bytes") + println("tl:", cur.actualTableLog, "symbolLen:", cur.symbolLen, "norm:", cur.norm[:cur.symbolLen], "hist", cur.count[:cur.symbolLen]) + } + return cur, compModeFSE + } +} + +var errIncompressible = errors.New("incompressible") + +func (b *blockEnc) genCodes() { + if len(b.sequences) == 0 { + // nothing to do + return + } + if len(b.sequences) > math.MaxUint16 { + panic("can only encode up to 64K sequences") + } + // No bounds checks after here: + llH := b.coders.llEnc.Histogram() + ofH := b.coders.ofEnc.Histogram() + mlH := b.coders.mlEnc.Histogram() + for i := range llH { + llH[i] = 0 + } + for i := range ofH { + ofH[i] = 0 + } + for i := range mlH { + mlH[i] = 0 + } + + var llMax, ofMax, mlMax uint8 + for i := range b.sequences { + seq := &b.sequences[i] + v := llCode(seq.litLen) + seq.llCode = v + llH[v]++ + if v > llMax { + llMax = v + } + + v = ofCode(seq.offset) + seq.ofCode = v + ofH[v]++ + if v > ofMax { + ofMax = v + } + + v = mlCode(seq.matchLen) + seq.mlCode = v + mlH[v]++ + if v > mlMax { + mlMax = v + if debugAsserts && mlMax > maxMatchLengthSymbol { + panic(fmt.Errorf("mlMax > maxMatchLengthSymbol (%d), matchlen: %d", mlMax, seq.matchLen)) + } + } + } + if debugAsserts && mlMax > maxMatchLengthSymbol { + panic(fmt.Errorf("mlMax > maxMatchLengthSymbol (%d)", mlMax)) + } + if debugAsserts && ofMax > maxOffsetBits { + panic(fmt.Errorf("ofMax > maxOffsetBits (%d)", ofMax)) + } + if debugAsserts && llMax > maxLiteralLengthSymbol { + panic(fmt.Errorf("llMax > maxLiteralLengthSymbol (%d)", llMax)) + } + + b.coders.mlEnc.HistogramFinished(mlMax, int(slices.Max(mlH[:mlMax+1]))) + b.coders.ofEnc.HistogramFinished(ofMax, int(slices.Max(ofH[:ofMax+1]))) + b.coders.llEnc.HistogramFinished(llMax, int(slices.Max(llH[:llMax+1]))) +} diff --git a/llo/internal/zstdenc/zstd/blocktype_string.go b/llo/internal/zstdenc/zstd/blocktype_string.go new file mode 100644 index 00000000..b935933d --- /dev/null +++ b/llo/internal/zstdenc/zstd/blocktype_string.go @@ -0,0 +1,28 @@ +// Code generated by "stringer -type=blockType,literalsBlockType,seqCompMode,tableIndex"; DO NOT EDIT. + +package zstd + +import "strconv" + +const _blockType_name = "blockTypeRawblockTypeRLEblockTypeCompressedblockTypeReserved" + +var _blockType_index = [...]uint8{0, 12, 24, 43, 60} + +const _literalsBlockType_name = "literalsBlockRawliteralsBlockRLEliteralsBlockCompressedliteralsBlockTreeless" + +var _literalsBlockType_index = [...]uint8{0, 16, 32, 55, 76} + +const _seqCompMode_name = "compModePredefinedcompModeRLEcompModeFSEcompModeRepeat" + +var _seqCompMode_index = [...]uint8{0, 18, 29, 40, 54} + +const _tableIndex_name = "tableLiteralLengthstableOffsetstableMatchLengths" + +var _tableIndex_index = [...]uint8{0, 19, 31, 48} + +func (i tableIndex) String() string { + if i >= tableIndex(len(_tableIndex_index)-1) { + return "tableIndex(" + strconv.FormatInt(int64(i), 10) + ")" + } + return _tableIndex_name[_tableIndex_index[i]:_tableIndex_index[i+1]] +} diff --git a/llo/internal/zstdenc/zstd/dict.go b/llo/internal/zstdenc/zstd/dict.go new file mode 100644 index 00000000..38130b09 --- /dev/null +++ b/llo/internal/zstdenc/zstd/dict.go @@ -0,0 +1,59 @@ +package zstd + +import ( + "io" + + "github.com/smartcontractkit/chainlink-data-streams/llo/internal/zstdenc/huff0" +) + +type dict struct { + id uint32 + + litEnc *huff0.Scratch + llEnc, ofEnc, mlEnc *fseEncoder + offsets [3]int + content []byte +} + +// ID returns the dictionary id or 0 if d is nil. +func (d *dict) ID() uint32 { + if d == nil { + return 0 + } + return d.id +} + +// ContentSize returns the dictionary content size or 0 if d is nil. +func (d *dict) ContentSize() int { + if d == nil { + return 0 + } + return len(d.content) +} + +type BuildDictOptions struct { + // Dictionary ID. + ID uint32 + + // Content to use to create dictionary tables. + Contents [][]byte + + // History to use for all blocks. + History []byte + + // Offsets to use. + Offsets [3]int + + // CompatV155 will make the dictionary compatible with Zstd v1.5.5 and earlier. + // See https://github.com/facebook/zstd/issues/3724 + CompatV155 bool + + // Use the specified encoder level. + // The dictionary will be built using the specified encoder level, + // which will reflect speed and make the dictionary tailored for that level. + // If not set SpeedBestCompression will be used. + Level EncoderLevel + + // DebugOut will write stats and other details here if set. + DebugOut io.Writer +} diff --git a/llo/internal/zstdenc/zstd/enc_base.go b/llo/internal/zstdenc/zstd/enc_base.go new file mode 100644 index 00000000..a61d1f2e --- /dev/null +++ b/llo/internal/zstdenc/zstd/enc_base.go @@ -0,0 +1,164 @@ +package zstd + +import ( + "fmt" + "math/bits" + + "github.com/cespare/xxhash/v2" +) + +const ( + dictShardBits = 7 +) + +type fastBase struct { + // cur is the offset at the start of hist + cur int32 + // maximum offset. Should be at least 2x block size. + maxMatchOff int32 + bufferReset int32 + hist []byte + crc *xxhash.Digest + tmp [8]byte + blk *blockEnc + lowMem bool +} + +// CRC returns the underlying CRC writer. +func (e *fastBase) CRC() *xxhash.Digest { + return e.crc +} + +// AppendCRC will append the CRC to the destination slice and return it. +func (e *fastBase) AppendCRC(dst []byte) []byte { + crc := e.crc.Sum(e.tmp[:0]) + dst = append(dst, crc[7], crc[6], crc[5], crc[4]) + return dst +} + +// WindowSize returns the window size of the encoder, +// or a window size small enough to contain the input size, if > 0. +func (e *fastBase) WindowSize(size int64) int32 { + if size > 0 && size < int64(e.maxMatchOff) { + b := max( + // Keep minimum window. + int32(1)< e.bufferReset { + panic(fmt.Sprintf("ecur (%d) > buffer reset (%d)", e.cur, e.bufferReset)) + } + // check if we have space already + if len(e.hist)+len(src) > cap(e.hist) { + if cap(e.hist) == 0 { + e.ensureHist(len(src)) + } else { + if cap(e.hist) < int(e.maxMatchOff+maxCompressedBlockSize) { + panic(fmt.Errorf("unexpected buffer cap %d, want at least %d with window %d", cap(e.hist), e.maxMatchOff+maxCompressedBlockSize, e.maxMatchOff)) + } + // Move down + offset := int32(len(e.hist)) - e.maxMatchOff + copy(e.hist[0:e.maxMatchOff], e.hist[offset:]) + e.cur += offset + e.hist = e.hist[:e.maxMatchOff] + } + } + s := int32(len(e.hist)) + e.hist = append(e.hist, src...) + return s +} + +// ensureHist will ensure that history can keep at least this many bytes. +func (e *fastBase) ensureHist(n int) { + if cap(e.hist) >= n { + return + } + l := e.maxMatchOff + if (e.lowMem && e.maxMatchOff > maxCompressedBlockSize) || e.maxMatchOff <= maxCompressedBlockSize { + l += maxCompressedBlockSize + } else { + l += e.maxMatchOff + } + // Make it at least 1MB. + if l < 1<<20 && !e.lowMem { + l = 1 << 20 + } + // Make it at least the requested size. + if l < int32(n) { + l = int32(n) + } + e.hist = make([]byte, 0, l) +} + +func (e *fastBase) matchlen(s, t int32, src []byte) int32 { + if debugAsserts { + if s < 0 { + err := fmt.Sprintf("s (%d) < 0", s) + panic(err) + } + if t < 0 { + err := fmt.Sprintf("t (%d) < 0", t) + panic(err) + } + if s-t > e.maxMatchOff { + err := fmt.Sprintf("s (%d) - t (%d) > maxMatchOff (%d)", s, t, e.maxMatchOff) + panic(err) + } + if len(src)-int(s) > maxCompressedBlockSize { + panic(fmt.Sprintf("len(src)-s (%d) > maxCompressedBlockSize (%d)", len(src)-int(s), maxCompressedBlockSize)) + } + } + return int32(matchLen(src[s:], src[t:])) +} + +// Reset the encoding table. +func (e *fastBase) resetBase(d *dict, singleBlock bool) { + if e.blk == nil { + e.blk = &blockEnc{lowMem: e.lowMem} + e.blk.init() + } else { + e.blk.reset(nil) + } + e.blk.initNewEncode() + if e.crc == nil { + e.crc = xxhash.New() + } else { + e.crc.Reset() + } + e.blk.dictLitEnc = nil + if d != nil { + low := e.lowMem + if singleBlock { + e.lowMem = true + } + e.ensureHist(d.ContentSize() + maxCompressedBlockSize) + e.lowMem = low + } + + // We offset current position so everything will be out of reach. + // If above reset line, history will be purged. + if e.cur < e.bufferReset { + e.cur += e.maxMatchOff + int32(len(e.hist)) + } + e.hist = e.hist[:0] + if d != nil { + // Set offsets (currently not used) + for i, off := range d.offsets { + e.blk.recentOffsets[i] = uint32(off) + e.blk.prevRecentOffsets[i] = e.blk.recentOffsets[i] + } + // Transfer litenc. + e.blk.dictLitEnc = d.litEnc + e.blk.coders.seedPrevFromDict(d) + e.hist = append(e.hist, d.content...) + } +} diff --git a/llo/internal/zstdenc/zstd/enc_dfast.go b/llo/internal/zstdenc/zstd/enc_dfast.go new file mode 100644 index 00000000..b0b07fcf --- /dev/null +++ b/llo/internal/zstdenc/zstd/enc_dfast.go @@ -0,0 +1,685 @@ +// Copyright 2019+ Klaus Post. All rights reserved. +// License information can be found in the LICENSE file. +// Based on work by Yann Collet, released under BSD License. + +package zstd + +import "fmt" + +const ( + dFastLongTableBits = 17 // Bits used in the long match table + dFastLongTableSize = 1 << dFastLongTableBits // Size of the table + dFastLongTableMask = dFastLongTableSize - 1 // Mask for table indices. Redundant, but can eliminate bounds checks. + dFastLongLen = 8 // Bytes used for table hash + + dFastShortTableBits = tableBits // Bits used in the short match table + dFastShortTableSize = 1 << dFastShortTableBits // Size of the table + dFastShortTableMask = dFastShortTableSize - 1 // Mask for table indices. Redundant, but can eliminate bounds checks. + dFastShortLen = 5 // Bytes used for table hash + +) + +// dFastHashL is hashLen(u, dFastLongTableBits, dFastLongLen) with prime = prime8bytes. +func dFastHashL(u, prime uint64) uint32 { + return uint32((u * prime) >> (64 - dFastLongTableBits)) +} + +// dFastHashS is hashLen(u, dFastShortTableBits, dFastShortLen) with prime = prime5bytes. +func dFastHashS(u, prime uint64) uint32 { + return uint32(((u << (64 - 40)) * prime) >> (64 - dFastShortTableBits)) +} + +type doubleFastEncoder struct { + fastEncoder + longTable [dFastLongTableSize]tableEntry +} + +// Encode mimmics functionality in zstd_dfast.c +func (e *doubleFastEncoder) Encode(blk *blockEnc, src []byte) { + const ( + // Input margin is the number of bytes we read (8) + // and the maximum we will read ahead (2) + inputMargin = 8 + 2 + minNonLiteralBlockSize = 16 + ) + + // Protect against e.cur wraparound. + for e.cur >= e.bufferReset-int32(len(e.hist)) { + if len(e.hist) == 0 { + e.table = [dFastShortTableSize]tableEntry{} + e.longTable = [dFastLongTableSize]tableEntry{} + e.cur = e.maxMatchOff + break + } + // Shift down everything in the table that isn't already too far away. + minOff := e.cur + int32(len(e.hist)) - e.maxMatchOff + for i := range e.table[:] { + v := e.table[i].offset + if v < minOff { + v = 0 + } else { + v = v - e.cur + e.maxMatchOff + } + e.table[i].offset = v + } + for i := range e.longTable[:] { + v := e.longTable[i].offset + if v < minOff { + v = 0 + } else { + v = v - e.cur + e.maxMatchOff + } + e.longTable[i].offset = v + } + e.cur = e.maxMatchOff + break + } + + s := e.addBlock(src) + blk.size = len(src) + if len(src) < minNonLiteralBlockSize { + blk.extraLits = len(src) + blk.literals = blk.literals[:len(src)] + copy(blk.literals, src) + return + } + + // Override src + src = e.hist + sLimit := int32(len(src)) - inputMargin + primeL, primeS := hashPrimes8and5() + // stepSize is the number of bytes to skip on every main loop iteration. + // It should be >= 1. + const stepSize = 1 + + const kSearchStrength = 8 + + // nextEmit is where in src the next emitLiteral should start from. + nextEmit := s + cv := load6432(src, s) + + // Relative offsets + offset1 := int32(blk.recentOffsets[0]) + offset2 := int32(blk.recentOffsets[1]) + + addLiterals := func(s *seq, until int32) { + if until == nextEmit { + return + } + blk.literals = append(blk.literals, src[nextEmit:until]...) + s.litLen = uint32(until - nextEmit) + } + if debugEncoder { + println("recent offsets:", blk.recentOffsets) + } + +encodeLoop: + for { + var t int32 + // We allow the encoder to optionally turn off repeat offsets across blocks + canRepeat := len(blk.sequences) > 2 + + for { + if debugAsserts && canRepeat && offset1 == 0 { + panic("offset0 was 0") + } + + nextHashL := dFastHashL(cv, primeL) + nextHashS := dFastHashS(cv, primeS) + candidateL := e.longTable[nextHashL] + candidateS := e.table[nextHashS] + + const repOff = 1 + repIndex := s - offset1 + repOff + entry := tableEntry{offset: s + e.cur, val: uint32(cv)} + e.longTable[nextHashL] = entry + e.table[nextHashS] = entry + + if canRepeat { + if repIndex >= 0 && load3232(src, repIndex) == uint32(cv>>(repOff*8)) { + // Consider history as well. + var seq seq + length := 4 + e.matchlen(s+4+repOff, repIndex+4, src) + + seq.matchLen = uint32(length - zstdMinMatch) + + // We might be able to match backwards. + // Extend as long as we can. + start := s + repOff + // We end the search early, so we don't risk 0 literals + // and have to do special offset treatment. + startLimit := nextEmit + 1 + + tMin := max(s-e.maxMatchOff, 0) + for repIndex > tMin && start > startLimit && src[repIndex-1] == src[start-1] && seq.matchLen < maxMatchLength-zstdMinMatch-1 { + repIndex-- + start-- + seq.matchLen++ + } + addLiterals(&seq, start) + + // rep 0 + seq.offset = 1 + if debugSequences { + println("repeat sequence", seq, "next s:", s) + } + blk.sequences = append(blk.sequences, seq) + s += length + repOff + nextEmit = s + if s >= sLimit { + if debugEncoder { + println("repeat ended", s, length) + + } + break encodeLoop + } + cv = load6432(src, s) + continue + } + } + // Find the offsets of our two matches. + coffsetL := s - (candidateL.offset - e.cur) + coffsetS := s - (candidateS.offset - e.cur) + + // Check if we have a long match. + if coffsetL < e.maxMatchOff && uint32(cv) == candidateL.val { + // Found a long match, likely at least 8 bytes. + // Reference encoder checks all 8 bytes, we only check 4, + // but the likelihood of both the first 4 bytes and the hash matching should be enough. + t = candidateL.offset - e.cur + if debugAsserts && s <= t { + panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) + } + if debugAsserts && s-t > e.maxMatchOff { + panic("s - t >e.maxMatchOff") + } + if debugMatches { + println("long match") + } + break + } + + // Check if we have a short match. + if coffsetS < e.maxMatchOff && uint32(cv) == candidateS.val { + // found a regular match + // See if we can find a long match at s+1 + const checkAt = 1 + cv := load6432(src, s+checkAt) + nextHashL = dFastHashL(cv, primeL) + candidateL = e.longTable[nextHashL] + coffsetL = s - (candidateL.offset - e.cur) + checkAt + + // We can store it, since we have at least a 4 byte match. + e.longTable[nextHashL] = tableEntry{offset: s + checkAt + e.cur, val: uint32(cv)} + if coffsetL < e.maxMatchOff && uint32(cv) == candidateL.val { + // Found a long match, likely at least 8 bytes. + // Reference encoder checks all 8 bytes, we only check 4, + // but the likelihood of both the first 4 bytes and the hash matching should be enough. + t = candidateL.offset - e.cur + s += checkAt + if debugMatches { + println("long match (after short)") + } + break + } + + t = candidateS.offset - e.cur + if debugAsserts && s <= t { + panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) + } + if debugAsserts && s-t > e.maxMatchOff { + panic("s - t >e.maxMatchOff") + } + if debugAsserts && t < 0 { + panic("t<0") + } + if debugMatches { + println("short match") + } + break + } + + // No match found, move forward in input. + s += stepSize + ((s - nextEmit) >> (kSearchStrength - 1)) + if s >= sLimit { + break encodeLoop + } + cv = load6432(src, s) + } + + // A 4-byte match has been found. Update recent offsets. + // We'll later see if more than 4 bytes. + offset2 = offset1 + offset1 = s - t + + if debugAsserts && s <= t { + panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) + } + + if debugAsserts && canRepeat && int(offset1) > len(src) { + panic("invalid offset") + } + + // Extend the 4-byte match as long as possible. + l := e.matchlen(s+4, t+4, src) + 4 + + // Extend backwards + tMin := max(s-e.maxMatchOff, 0) + for t > tMin && s > nextEmit && src[t-1] == src[s-1] && l < maxMatchLength { + s-- + t-- + l++ + } + + // Write our sequence + var seq seq + seq.litLen = uint32(s - nextEmit) + seq.matchLen = uint32(l - zstdMinMatch) + if seq.litLen > 0 { + blk.literals = append(blk.literals, src[nextEmit:s]...) + } + seq.offset = uint32(s-t) + 3 + s += l + if debugSequences { + println("sequence", seq, "next s:", s) + } + blk.sequences = append(blk.sequences, seq) + nextEmit = s + if s >= sLimit { + break encodeLoop + } + + // Index match start+1 (long) and start+2 (short) + index0 := s - l + 1 + // Index match end-2 (long) and end-1 (short) + index1 := s - 2 + + cv0 := load6432(src, index0) + cv1 := load6432(src, index1) + te0 := tableEntry{offset: index0 + e.cur, val: uint32(cv0)} + te1 := tableEntry{offset: index1 + e.cur, val: uint32(cv1)} + e.longTable[dFastHashL(cv0, primeL)] = te0 + e.longTable[dFastHashL(cv1, primeL)] = te1 + cv0 >>= 8 + cv1 >>= 8 + te0.offset++ + te1.offset++ + te0.val = uint32(cv0) + te1.val = uint32(cv1) + e.table[dFastHashS(cv0, primeS)] = te0 + e.table[dFastHashS(cv1, primeS)] = te1 + + cv = load6432(src, s) + + if !canRepeat { + continue + } + + // Check offset 2 + for { + o2 := s - offset2 + if load3232(src, o2) != uint32(cv) { + // Do regular search + break + } + + // Store this, since we have it. + nextHashS := dFastHashS(cv, primeS) + nextHashL := dFastHashL(cv, primeL) + + // We have at least 4 byte match. + // No need to check backwards. We come straight from a match + l := 4 + e.matchlen(s+4, o2+4, src) + + entry := tableEntry{offset: s + e.cur, val: uint32(cv)} + e.longTable[nextHashL] = entry + e.table[nextHashS] = entry + seq.matchLen = uint32(l) - zstdMinMatch + seq.litLen = 0 + + // Since litlen is always 0, this is offset 1. + seq.offset = 1 + s += l + nextEmit = s + if debugSequences { + println("sequence", seq, "next s:", s) + } + blk.sequences = append(blk.sequences, seq) + + // Swap offset 1 and 2. + offset1, offset2 = offset2, offset1 + if s >= sLimit { + // Finished + break encodeLoop + } + cv = load6432(src, s) + } + } + + if int(nextEmit) < len(src) { + blk.literals = append(blk.literals, src[nextEmit:]...) + blk.extraLits = len(src) - int(nextEmit) + } + blk.recentOffsets[0] = uint32(offset1) + blk.recentOffsets[1] = uint32(offset2) + if debugEncoder { + println("returning, recent offsets:", blk.recentOffsets, "extra literals:", blk.extraLits) + } +} + +// EncodeNoHist will encode a block with no history and no following blocks. +// Most notable difference is that src will not be copied for history and +// we do not need to check for max match length. +func (e *doubleFastEncoder) EncodeNoHist(blk *blockEnc, src []byte) { + const ( + // Input margin is the number of bytes we read (8) + // and the maximum we will read ahead (2) + inputMargin = 8 + 2 + minNonLiteralBlockSize = 16 + ) + + // Protect against e.cur wraparound. + if e.cur >= e.bufferReset { + for i := range e.table[:] { + e.table[i] = tableEntry{} + } + for i := range e.longTable[:] { + e.longTable[i] = tableEntry{} + } + e.cur = e.maxMatchOff + } + + s := int32(0) + blk.size = len(src) + if len(src) < minNonLiteralBlockSize { + blk.extraLits = len(src) + blk.literals = blk.literals[:len(src)] + copy(blk.literals, src) + return + } + + // Override src + sLimit := int32(len(src)) - inputMargin + primeL, primeS := hashPrimes8and5() + // stepSize is the number of bytes to skip on every main loop iteration. + // It should be >= 1. + const stepSize = 1 + + const kSearchStrength = 8 + + // nextEmit is where in src the next emitLiteral should start from. + nextEmit := s + cv := load6432(src, s) + + // Relative offsets + offset1 := int32(blk.recentOffsets[0]) + offset2 := int32(blk.recentOffsets[1]) + + addLiterals := func(s *seq, until int32) { + if until == nextEmit { + return + } + blk.literals = append(blk.literals, src[nextEmit:until]...) + s.litLen = uint32(until - nextEmit) + } + if debugEncoder { + println("recent offsets:", blk.recentOffsets) + } + +encodeLoop: + for { + var t int32 + for { + + nextHashL := dFastHashL(cv, primeL) + nextHashS := dFastHashS(cv, primeS) + candidateL := e.longTable[nextHashL] + candidateS := e.table[nextHashS] + + const repOff = 1 + repIndex := s - offset1 + repOff + entry := tableEntry{offset: s + e.cur, val: uint32(cv)} + e.longTable[nextHashL] = entry + e.table[nextHashS] = entry + + if len(blk.sequences) > 2 { + if load3232(src, repIndex) == uint32(cv>>(repOff*8)) { + // Consider history as well. + var seq seq + //length := 4 + e.matchlen(s+4+repOff, repIndex+4, src) + length := 4 + int32(matchLen(src[s+4+repOff:], src[repIndex+4:])) + + seq.matchLen = uint32(length - zstdMinMatch) + + // We might be able to match backwards. + // Extend as long as we can. + start := s + repOff + // We end the search early, so we don't risk 0 literals + // and have to do special offset treatment. + startLimit := nextEmit + 1 + + tMin := max(s-e.maxMatchOff, 0) + for repIndex > tMin && start > startLimit && src[repIndex-1] == src[start-1] { + repIndex-- + start-- + seq.matchLen++ + } + addLiterals(&seq, start) + + // rep 0 + seq.offset = 1 + if debugSequences { + println("repeat sequence", seq, "next s:", s) + } + blk.sequences = append(blk.sequences, seq) + s += length + repOff + nextEmit = s + if s >= sLimit { + if debugEncoder { + println("repeat ended", s, length) + + } + break encodeLoop + } + cv = load6432(src, s) + continue + } + } + // Find the offsets of our two matches. + coffsetL := s - (candidateL.offset - e.cur) + coffsetS := s - (candidateS.offset - e.cur) + + // Check if we have a long match. + if coffsetL < e.maxMatchOff && uint32(cv) == candidateL.val { + // Found a long match, likely at least 8 bytes. + // Reference encoder checks all 8 bytes, we only check 4, + // but the likelihood of both the first 4 bytes and the hash matching should be enough. + t = candidateL.offset - e.cur + if debugAsserts && s <= t { + panic(fmt.Sprintf("s (%d) <= t (%d). cur: %d", s, t, e.cur)) + } + if debugAsserts && s-t > e.maxMatchOff { + panic("s - t >e.maxMatchOff") + } + if debugMatches { + println("long match") + } + break + } + + // Check if we have a short match. + if coffsetS < e.maxMatchOff && uint32(cv) == candidateS.val { + // found a regular match + // See if we can find a long match at s+1 + const checkAt = 1 + cv := load6432(src, s+checkAt) + nextHashL = dFastHashL(cv, primeL) + candidateL = e.longTable[nextHashL] + coffsetL = s - (candidateL.offset - e.cur) + checkAt + + // We can store it, since we have at least a 4 byte match. + e.longTable[nextHashL] = tableEntry{offset: s + checkAt + e.cur, val: uint32(cv)} + if coffsetL < e.maxMatchOff && uint32(cv) == candidateL.val { + // Found a long match, likely at least 8 bytes. + // Reference encoder checks all 8 bytes, we only check 4, + // but the likelihood of both the first 4 bytes and the hash matching should be enough. + t = candidateL.offset - e.cur + s += checkAt + if debugMatches { + println("long match (after short)") + } + break + } + + t = candidateS.offset - e.cur + if debugAsserts && s <= t { + panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) + } + if debugAsserts && s-t > e.maxMatchOff { + panic("s - t >e.maxMatchOff") + } + if debugAsserts && t < 0 { + panic("t<0") + } + if debugMatches { + println("short match") + } + break + } + + // No match found, move forward in input. + s += stepSize + ((s - nextEmit) >> (kSearchStrength - 1)) + if s >= sLimit { + break encodeLoop + } + cv = load6432(src, s) + } + + // A 4-byte match has been found. Update recent offsets. + // We'll later see if more than 4 bytes. + offset2 = offset1 + offset1 = s - t + + if debugAsserts && s <= t { + panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) + } + + // Extend the 4-byte match as long as possible. + //l := e.matchlen(s+4, t+4, src) + 4 + l := int32(matchLen(src[s+4:], src[t+4:])) + 4 + + // Extend backwards + tMin := max(s-e.maxMatchOff, 0) + for t > tMin && s > nextEmit && src[t-1] == src[s-1] { + s-- + t-- + l++ + } + + // Write our sequence + var seq seq + seq.litLen = uint32(s - nextEmit) + seq.matchLen = uint32(l - zstdMinMatch) + if seq.litLen > 0 { + blk.literals = append(blk.literals, src[nextEmit:s]...) + } + seq.offset = uint32(s-t) + 3 + s += l + if debugSequences { + println("sequence", seq, "next s:", s) + } + blk.sequences = append(blk.sequences, seq) + nextEmit = s + if s >= sLimit { + break encodeLoop + } + + // Index match start+1 (long) and start+2 (short) + index0 := s - l + 1 + // Index match end-2 (long) and end-1 (short) + index1 := s - 2 + + cv0 := load6432(src, index0) + cv1 := load6432(src, index1) + te0 := tableEntry{offset: index0 + e.cur, val: uint32(cv0)} + te1 := tableEntry{offset: index1 + e.cur, val: uint32(cv1)} + e.longTable[dFastHashL(cv0, primeL)] = te0 + e.longTable[dFastHashL(cv1, primeL)] = te1 + cv0 >>= 8 + cv1 >>= 8 + te0.offset++ + te1.offset++ + te0.val = uint32(cv0) + te1.val = uint32(cv1) + e.table[dFastHashS(cv0, primeS)] = te0 + e.table[dFastHashS(cv1, primeS)] = te1 + + cv = load6432(src, s) + + if len(blk.sequences) <= 2 { + continue + } + + // Check offset 2 + for { + o2 := s - offset2 + if load3232(src, o2) != uint32(cv) { + // Do regular search + break + } + + // Store this, since we have it. + nextHashS := dFastHashS(cv1>>8, primeS) + nextHashL := dFastHashL(cv, primeL) + + // We have at least 4 byte match. + // No need to check backwards. We come straight from a match + //l := 4 + e.matchlen(s+4, o2+4, src) + l := 4 + int32(matchLen(src[s+4:], src[o2+4:])) + + entry := tableEntry{offset: s + e.cur, val: uint32(cv)} + e.longTable[nextHashL] = entry + e.table[nextHashS] = entry + seq.matchLen = uint32(l) - zstdMinMatch + seq.litLen = 0 + + // Since litlen is always 0, this is offset 1. + seq.offset = 1 + s += l + nextEmit = s + if debugSequences { + println("sequence", seq, "next s:", s) + } + blk.sequences = append(blk.sequences, seq) + + // Swap offset 1 and 2. + offset1, offset2 = offset2, offset1 + if s >= sLimit { + // Finished + break encodeLoop + } + cv = load6432(src, s) + } + } + + if int(nextEmit) < len(src) { + blk.literals = append(blk.literals, src[nextEmit:]...) + blk.extraLits = len(src) - int(nextEmit) + } + if debugEncoder { + println("returning, recent offsets:", blk.recentOffsets, "extra literals:", blk.extraLits) + } + + // We do not store history, so we must offset e.cur to avoid false matches for next user. + if e.cur < e.bufferReset { + e.cur += int32(len(src)) + } +} + +// ResetDict will reset and set a dictionary if not nil +func (e *doubleFastEncoder) Reset(d *dict, singleBlock bool) { + e.fastEncoder.Reset(d, singleBlock) + if d != nil { + panic("doubleFastEncoder: Reset with dict not supported") + } +} diff --git a/llo/internal/zstdenc/zstd/enc_fast.go b/llo/internal/zstdenc/zstd/enc_fast.go new file mode 100644 index 00000000..a68f7ca7 --- /dev/null +++ b/llo/internal/zstdenc/zstd/enc_fast.go @@ -0,0 +1,532 @@ +// Copyright 2019+ Klaus Post. All rights reserved. +// License information can be found in the LICENSE file. +// Based on work by Yann Collet, released under BSD License. + +package zstd + +import ( + "fmt" +) + +const ( + tableBits = 15 // Bits used in the table + tableSize = 1 << tableBits // Size of the table + tableShardCnt = 1 << (tableBits - dictShardBits) // Number of shards in the table + tableShardSize = tableSize / tableShardCnt // Size of an individual shard + tableFastHashLen = 6 + tableMask = tableSize - 1 // Mask for table indices. Redundant, but can eliminate bounds checks. + maxMatchLength = 131074 +) + +type tableEntry struct { + val uint32 + offset int32 +} + +type fastEncoder struct { + fastBase + table [tableSize]tableEntry +} + +// Encode mimmics functionality in zstd_fast.c +func (e *fastEncoder) Encode(blk *blockEnc, src []byte) { + const ( + inputMargin = 8 + minNonLiteralBlockSize = 1 + 1 + inputMargin + ) + + // Protect against e.cur wraparound. + for e.cur >= e.bufferReset-int32(len(e.hist)) { + if len(e.hist) == 0 { + for i := range e.table[:] { + e.table[i] = tableEntry{} + } + e.cur = e.maxMatchOff + break + } + // Shift down everything in the table that isn't already too far away. + minOff := e.cur + int32(len(e.hist)) - e.maxMatchOff + for i := range e.table[:] { + v := e.table[i].offset + if v < minOff { + v = 0 + } else { + v = v - e.cur + e.maxMatchOff + } + e.table[i].offset = v + } + e.cur = e.maxMatchOff + break + } + + s := e.addBlock(src) + blk.size = len(src) + if len(src) < minNonLiteralBlockSize { + blk.extraLits = len(src) + blk.literals = blk.literals[:len(src)] + copy(blk.literals, src) + return + } + + // Override src + src = e.hist + sLimit := int32(len(src)) - inputMargin + // stepSize is the number of bytes to skip on every main loop iteration. + // It should be >= 2. + const stepSize = 2 + + // TEMPLATE + const hashLog = tableBits + // seems global, but would be nice to tweak. + const kSearchStrength = 6 + + // nextEmit is where in src the next emitLiteral should start from. + nextEmit := s + cv := load6432(src, s) + + // Relative offsets + offset1 := int32(blk.recentOffsets[0]) + offset2 := int32(blk.recentOffsets[1]) + + addLiterals := func(s *seq, until int32) { + if until == nextEmit { + return + } + blk.literals = append(blk.literals, src[nextEmit:until]...) + s.litLen = uint32(until - nextEmit) + } + if debugEncoder { + println("recent offsets:", blk.recentOffsets) + } + +encodeLoop: + for { + // t will contain the match offset when we find one. + // When existing the search loop, we have already checked 4 bytes. + var t int32 + + // We will not use repeat offsets across blocks. + // By not using them for the first 3 matches + canRepeat := len(blk.sequences) > 2 + + for { + if debugAsserts && canRepeat && offset1 == 0 { + panic("offset0 was 0") + } + + nextHash := hashLen(cv, hashLog, tableFastHashLen) + nextHash2 := hashLen(cv>>8, hashLog, tableFastHashLen) + candidate := e.table[nextHash] + candidate2 := e.table[nextHash2] + repIndex := s - offset1 + 2 + + e.table[nextHash] = tableEntry{offset: s + e.cur, val: uint32(cv)} + e.table[nextHash2] = tableEntry{offset: s + e.cur + 1, val: uint32(cv >> 8)} + + if canRepeat && repIndex >= 0 && load3232(src, repIndex) == uint32(cv>>16) { + // Consider history as well. + var seq seq + length := 4 + e.matchlen(s+6, repIndex+4, src) + seq.matchLen = uint32(length - zstdMinMatch) + + // We might be able to match backwards. + // Extend as long as we can. + start := s + 2 + // We end the search early, so we don't risk 0 literals + // and have to do special offset treatment. + startLimit := nextEmit + 1 + + sMin := max(s-e.maxMatchOff, 0) + for repIndex > sMin && start > startLimit && src[repIndex-1] == src[start-1] && seq.matchLen < maxMatchLength-zstdMinMatch { + repIndex-- + start-- + seq.matchLen++ + } + addLiterals(&seq, start) + + // rep 0 + seq.offset = 1 + if debugSequences { + println("repeat sequence", seq, "next s:", s) + } + blk.sequences = append(blk.sequences, seq) + s += length + 2 + nextEmit = s + if s >= sLimit { + if debugEncoder { + println("repeat ended", s, length) + + } + break encodeLoop + } + cv = load6432(src, s) + continue + } + coffset0 := s - (candidate.offset - e.cur) + coffset1 := s - (candidate2.offset - e.cur) + 1 + if coffset0 < e.maxMatchOff && uint32(cv) == candidate.val { + // found a regular match + t = candidate.offset - e.cur + if debugAsserts && s <= t { + panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) + } + if debugAsserts && s-t > e.maxMatchOff { + panic("s - t >e.maxMatchOff") + } + break + } + + if coffset1 < e.maxMatchOff && uint32(cv>>8) == candidate2.val { + // found a regular match + t = candidate2.offset - e.cur + s++ + if debugAsserts && s <= t { + panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) + } + if debugAsserts && s-t > e.maxMatchOff { + panic("s - t >e.maxMatchOff") + } + if debugAsserts && t < 0 { + panic("t<0") + } + break + } + s += stepSize + ((s - nextEmit) >> (kSearchStrength - 1)) + if s >= sLimit { + break encodeLoop + } + cv = load6432(src, s) + } + // A 4-byte match has been found. We'll later see if more than 4 bytes. + offset2 = offset1 + offset1 = s - t + + if debugAsserts && s <= t { + panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) + } + + if debugAsserts && canRepeat && int(offset1) > len(src) { + panic("invalid offset") + } + + // Extend the 4-byte match as long as possible. + l := e.matchlen(s+4, t+4, src) + 4 + + // Extend backwards + tMin := max(s-e.maxMatchOff, 0) + for t > tMin && s > nextEmit && src[t-1] == src[s-1] && l < maxMatchLength { + s-- + t-- + l++ + } + + // Write our sequence. + var seq seq + seq.litLen = uint32(s - nextEmit) + seq.matchLen = uint32(l - zstdMinMatch) + if seq.litLen > 0 { + blk.literals = append(blk.literals, src[nextEmit:s]...) + } + // Don't use repeat offsets + seq.offset = uint32(s-t) + 3 + s += l + if debugSequences { + println("sequence", seq, "next s:", s) + } + blk.sequences = append(blk.sequences, seq) + nextEmit = s + if s >= sLimit { + break encodeLoop + } + cv = load6432(src, s) + + // Check offset 2 + if o2 := s - offset2; canRepeat && load3232(src, o2) == uint32(cv) { + // We have at least 4 byte match. + // No need to check backwards. We come straight from a match + l := 4 + e.matchlen(s+4, o2+4, src) + + // Store this, since we have it. + nextHash := hashLen(cv, hashLog, tableFastHashLen) + e.table[nextHash] = tableEntry{offset: s + e.cur, val: uint32(cv)} + seq.matchLen = uint32(l) - zstdMinMatch + seq.litLen = 0 + // Since litlen is always 0, this is offset 1. + seq.offset = 1 + s += l + nextEmit = s + if debugSequences { + println("sequence", seq, "next s:", s) + } + blk.sequences = append(blk.sequences, seq) + + // Swap offset 1 and 2. + offset1, offset2 = offset2, offset1 + if s >= sLimit { + break encodeLoop + } + // Prepare next loop. + cv = load6432(src, s) + } + } + + if int(nextEmit) < len(src) { + blk.literals = append(blk.literals, src[nextEmit:]...) + blk.extraLits = len(src) - int(nextEmit) + } + blk.recentOffsets[0] = uint32(offset1) + blk.recentOffsets[1] = uint32(offset2) + if debugEncoder { + println("returning, recent offsets:", blk.recentOffsets, "extra literals:", blk.extraLits) + } +} + +// EncodeNoHist will encode a block with no history and no following blocks. +// Most notable difference is that src will not be copied for history and +// we do not need to check for max match length. +func (e *fastEncoder) EncodeNoHist(blk *blockEnc, src []byte) { + const ( + inputMargin = 8 + minNonLiteralBlockSize = 1 + 1 + inputMargin + ) + if debugEncoder { + if len(src) > maxCompressedBlockSize { + panic("src too big") + } + } + + // Protect against e.cur wraparound. + if e.cur >= e.bufferReset { + for i := range e.table[:] { + e.table[i] = tableEntry{} + } + e.cur = e.maxMatchOff + } + + s := int32(0) + blk.size = len(src) + if len(src) < minNonLiteralBlockSize { + blk.extraLits = len(src) + blk.literals = blk.literals[:len(src)] + copy(blk.literals, src) + return + } + + sLimit := int32(len(src)) - inputMargin + // stepSize is the number of bytes to skip on every main loop iteration. + // It should be >= 2. + const stepSize = 2 + + // TEMPLATE + const hashLog = tableBits + // seems global, but would be nice to tweak. + const kSearchStrength = 6 + + // nextEmit is where in src the next emitLiteral should start from. + nextEmit := s + cv := load6432(src, s) + + // Relative offsets + offset1 := int32(blk.recentOffsets[0]) + offset2 := int32(blk.recentOffsets[1]) + + addLiterals := func(s *seq, until int32) { + if until == nextEmit { + return + } + blk.literals = append(blk.literals, src[nextEmit:until]...) + s.litLen = uint32(until - nextEmit) + } + if debugEncoder { + println("recent offsets:", blk.recentOffsets) + } + +encodeLoop: + for { + // t will contain the match offset when we find one. + // When existing the search loop, we have already checked 4 bytes. + var t int32 + + // We will not use repeat offsets across blocks. + // By not using them for the first 3 matches + + for { + nextHash := hashLen(cv, hashLog, tableFastHashLen) + nextHash2 := hashLen(cv>>8, hashLog, tableFastHashLen) + candidate := e.table[nextHash] + candidate2 := e.table[nextHash2] + repIndex := s - offset1 + 2 + + e.table[nextHash] = tableEntry{offset: s + e.cur, val: uint32(cv)} + e.table[nextHash2] = tableEntry{offset: s + e.cur + 1, val: uint32(cv >> 8)} + + if len(blk.sequences) > 2 && load3232(src, repIndex) == uint32(cv>>16) { + // Consider history as well. + var seq seq + length := 4 + e.matchlen(s+6, repIndex+4, src) + + seq.matchLen = uint32(length - zstdMinMatch) + + // We might be able to match backwards. + // Extend as long as we can. + start := s + 2 + // We end the search early, so we don't risk 0 literals + // and have to do special offset treatment. + startLimit := nextEmit + 1 + + sMin := max(s-e.maxMatchOff, 0) + for repIndex > sMin && start > startLimit && src[repIndex-1] == src[start-1] { + repIndex-- + start-- + seq.matchLen++ + } + addLiterals(&seq, start) + + // rep 0 + seq.offset = 1 + if debugSequences { + println("repeat sequence", seq, "next s:", s) + } + blk.sequences = append(blk.sequences, seq) + s += length + 2 + nextEmit = s + if s >= sLimit { + if debugEncoder { + println("repeat ended", s, length) + + } + break encodeLoop + } + cv = load6432(src, s) + continue + } + coffset0 := s - (candidate.offset - e.cur) + coffset1 := s - (candidate2.offset - e.cur) + 1 + if coffset0 < e.maxMatchOff && uint32(cv) == candidate.val { + // found a regular match + t = candidate.offset - e.cur + if debugAsserts && s <= t { + panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) + } + if debugAsserts && s-t > e.maxMatchOff { + panic("s - t >e.maxMatchOff") + } + if debugAsserts && t < 0 { + panic(fmt.Sprintf("t (%d) < 0, candidate.offset: %d, e.cur: %d, coffset0: %d, e.maxMatchOff: %d", t, candidate.offset, e.cur, coffset0, e.maxMatchOff)) + } + break + } + + if coffset1 < e.maxMatchOff && uint32(cv>>8) == candidate2.val { + // found a regular match + t = candidate2.offset - e.cur + s++ + if debugAsserts && s <= t { + panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) + } + if debugAsserts && s-t > e.maxMatchOff { + panic("s - t >e.maxMatchOff") + } + if debugAsserts && t < 0 { + panic("t<0") + } + break + } + s += stepSize + ((s - nextEmit) >> (kSearchStrength - 1)) + if s >= sLimit { + break encodeLoop + } + cv = load6432(src, s) + } + // A 4-byte match has been found. We'll later see if more than 4 bytes. + offset2 = offset1 + offset1 = s - t + + if debugAsserts && s <= t { + panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) + } + + if debugAsserts && t < 0 { + panic(fmt.Sprintf("t (%d) < 0 ", t)) + } + // Extend the 4-byte match as long as possible. + l := e.matchlen(s+4, t+4, src) + 4 + + // Extend backwards + tMin := max(s-e.maxMatchOff, 0) + for t > tMin && s > nextEmit && src[t-1] == src[s-1] { + s-- + t-- + l++ + } + + // Write our sequence. + var seq seq + seq.litLen = uint32(s - nextEmit) + seq.matchLen = uint32(l - zstdMinMatch) + if seq.litLen > 0 { + blk.literals = append(blk.literals, src[nextEmit:s]...) + } + // Don't use repeat offsets + seq.offset = uint32(s-t) + 3 + s += l + if debugSequences { + println("sequence", seq, "next s:", s) + } + blk.sequences = append(blk.sequences, seq) + nextEmit = s + if s >= sLimit { + break encodeLoop + } + cv = load6432(src, s) + + // Check offset 2 + if o2 := s - offset2; len(blk.sequences) > 2 && load3232(src, o2) == uint32(cv) { + // We have at least 4 byte match. + // No need to check backwards. We come straight from a match + l := 4 + e.matchlen(s+4, o2+4, src) + + // Store this, since we have it. + nextHash := hashLen(cv, hashLog, tableFastHashLen) + e.table[nextHash] = tableEntry{offset: s + e.cur, val: uint32(cv)} + seq.matchLen = uint32(l) - zstdMinMatch + seq.litLen = 0 + // Since litlen is always 0, this is offset 1. + seq.offset = 1 + s += l + nextEmit = s + if debugSequences { + println("sequence", seq, "next s:", s) + } + blk.sequences = append(blk.sequences, seq) + + // Swap offset 1 and 2. + offset1, offset2 = offset2, offset1 + if s >= sLimit { + break encodeLoop + } + // Prepare next loop. + cv = load6432(src, s) + } + } + + if int(nextEmit) < len(src) { + blk.literals = append(blk.literals, src[nextEmit:]...) + blk.extraLits = len(src) - int(nextEmit) + } + if debugEncoder { + println("returning, recent offsets:", blk.recentOffsets, "extra literals:", blk.extraLits) + } + // We do not store history, so we must offset e.cur to avoid false matches for next user. + if e.cur < e.bufferReset { + e.cur += int32(len(src)) + } +} + +// ResetDict will reset and set a dictionary if not nil +func (e *fastEncoder) Reset(d *dict, singleBlock bool) { + e.resetBase(d, singleBlock) + if d != nil { + panic("fastEncoder: Reset with dict") + } +} diff --git a/llo/internal/zstdenc/zstd/enc_jobs.go b/llo/internal/zstdenc/zstd/enc_jobs.go new file mode 100644 index 00000000..0e00f3c8 --- /dev/null +++ b/llo/internal/zstdenc/zstd/enc_jobs.go @@ -0,0 +1,53 @@ +// Copyright 2019+ Klaus Post. All rights reserved. +// License information can be found in the LICENSE file. +// Based on work by Yann Collet, released under BSD License. + +package zstd + +import ( + "sync" +) + +type encJob struct { +} + +type jobState struct { + jobSize int + overlapSize int + filling []byte // accumulates input up to jobSize + nextPrefix []byte // overlap prefix prepared for the next dispatched job + + jobSeq int // next job sequence number + + jobCh chan *encJob // dispatch to workers + resultCh chan *encJob // ordered results to flusher + + workerWg sync.WaitGroup + flusherWg sync.WaitGroup + + flushedSeq int // last flushed sequence number + + flusherErr error + started bool + + overlapPool sync.Pool // *[]byte buffers for overlap prefixes +} + +func (js *jobState) putOverlapBuf(b []byte) { + if cap(b) > 0 { + b = b[:0] + js.overlapPool.Put(&b) + } +} + +func (e *Encoder) shutdownJobWorkers() { + js := &e.state.jobs + if !js.started { + return + } + close(js.jobCh) + js.workerWg.Wait() + close(js.resultCh) + js.flusherWg.Wait() + js.started = false +} diff --git a/llo/internal/zstdenc/zstd/encoder.go b/llo/internal/zstdenc/zstd/encoder.go new file mode 100644 index 00000000..a499acf3 --- /dev/null +++ b/llo/internal/zstdenc/zstd/encoder.go @@ -0,0 +1,277 @@ +// Copyright 2019+ Klaus Post. All rights reserved. +// License information can be found in the LICENSE file. +// Based on work by Yann Collet, released under BSD License. + +package zstd + +import ( + "crypto/rand" + "io" + "sync" + + "github.com/cespare/xxhash/v2" +) + +// Encoder provides encoding to Zstandard. +// An Encoder can be used for either compressing a stream via the +// io.WriteCloser interface supported by the Encoder or as multiple independent +// tasks via the EncodeAll function. +// Smaller encodes are encouraged to use the EncodeAll function. +// Use NewWriter to create a new instance. +type Encoder struct { + o encoderOptions + encoders chan encoder + state encoderState + init sync.Once +} + +type encoder interface { + Encode(blk *blockEnc, src []byte) + EncodeNoHist(blk *blockEnc, src []byte) + Block() *blockEnc + CRC() *xxhash.Digest + AppendCRC([]byte) []byte + WindowSize(size int64) int32 + Reset(d *dict, singleBlock bool) +} + +type encoderState struct { + w io.Writer + filling []byte + current []byte + previous []byte + encoder encoder + writing *blockEnc + err error + writeErr error + nWritten int64 + nInput int64 + frameContentSize int64 + headerWritten bool + eofWritten bool + fullFrameWritten bool + + // This waitgroup indicates an encode is running. + wg sync.WaitGroup + // This waitgroup indicates we have a block encoding/writing. + wWg sync.WaitGroup + + // Parallel job state (used when concurrentBlocks is enabled). + jobs jobState +} + +// NewWriter will create a new Zstandard encoder. +// If the encoder will be used for encoding blocks a nil writer can be used. +func NewWriter(w io.Writer, opts ...EOption) (*Encoder, error) { + initPredefined() + var e Encoder + e.o.setDefault() + for _, o := range opts { + err := o(&e.o) + if err != nil { + return nil, err + } + } + if e.o.concurrentBlocks && (e.o.dict != nil || e.o.concurrent <= 1) { + e.o.concurrentBlocks = false + } + if w != nil { + e.Reset(w) + } + return &e, nil +} + +func (e *Encoder) initialize() { + if e.o.concurrent == 0 { + e.o.setDefault() + } + e.encoders = make(chan encoder, e.o.concurrent) + for i := 0; i < e.o.concurrent; i++ { + enc := e.o.encoder() + e.encoders <- enc + } +} + +// Reset will re-initialize the writer and new writes will encode to the supplied writer +// as a new, independent stream. +func (e *Encoder) Reset(w io.Writer) { + s := &e.state + + if e.o.concurrentBlocks { + e.shutdownJobWorkers() + js := &s.jobs + js.jobSize = e.o.jobSize() + js.overlapSize = e.o.overlapSize() + // js.filling is allocated lazily on first Write/ReadFrom so callers + // that only use EncodeAll don't pay the (up to ~32 MB) jobSize cost. + js.filling = js.filling[:0] + if js.nextPrefix != nil { + js.putOverlapBuf(js.nextPrefix) + js.nextPrefix = nil + } + js.jobSeq = 0 + js.flushedSeq = 0 + js.flusherErr = nil + js.started = false + } + + s.wg.Wait() + s.wWg.Wait() + if cap(s.filling) == 0 { + s.filling = make([]byte, 0, e.o.blockSize) + } + if e.o.concurrent > 1 && !e.o.concurrentBlocks { + if cap(s.current) == 0 { + s.current = make([]byte, 0, e.o.blockSize) + } + if cap(s.previous) == 0 { + s.previous = make([]byte, 0, e.o.blockSize) + } + s.current = s.current[:0] + s.previous = s.previous[:0] + if s.writing == nil { + s.writing = &blockEnc{lowMem: e.o.lowMem} + s.writing.init() + } + s.writing.initNewEncode() + } + if s.encoder == nil { + s.encoder = e.o.encoder() + } + s.filling = s.filling[:0] + s.encoder.Reset(e.o.dict, false) + s.headerWritten = false + s.eofWritten = false + s.fullFrameWritten = false + s.w = w + s.err = nil + s.nWritten = 0 + s.nInput = 0 + s.writeErr = nil + s.frameContentSize = 0 +} + +// EncodeAll will encode all input in src and append it to dst. +// This function can be called concurrently, but each call will only run on a single goroutine. +// If empty input is given, nothing is returned, unless WithZeroFrames is specified. +// Encoded blocks can be concatenated and the result will be the combined input stream. +// Data compressed with EncodeAll can be decoded with the Decoder, +// using either a stream or DecodeAll. +func (e *Encoder) EncodeAll(src, dst []byte) []byte { + e.init.Do(e.initialize) + enc := <-e.encoders + defer func() { + e.encoders <- enc + }() + return e.encodeAll(enc, src, dst) +} + +func (e *Encoder) encodeAll(enc encoder, src, dst []byte) []byte { + if len(src) == 0 { + if e.o.fullZero { + // Add frame header. + fh := frameHeader{ + ContentSize: 0, + WindowSize: MinWindowSize, + SingleSegment: true, + // Adding a checksum would be a waste of space. + Checksum: false, + DictID: 0, + } + dst = fh.appendTo(dst) + + // Write raw block as last one only. + var blk blockHeader + blk.setSize(0) + blk.setType(blockTypeRaw) + blk.setLast(true) + dst = blk.appendTo(dst) + } + return dst + } + + // Use single segments when above minimum window and below window size. + single := len(src) <= e.o.windowSize && len(src) > MinWindowSize + if e.o.single != nil { + single = *e.o.single + } + fh := frameHeader{ + ContentSize: uint64(len(src)), + WindowSize: uint32(enc.WindowSize(int64(len(src)))), + SingleSegment: single, + Checksum: e.o.crc, + DictID: e.o.dict.ID(), + } + + // If less than 1MB, allocate a buffer up front. + if len(dst) == 0 && cap(dst) == 0 && len(src) < 1<<20 && !e.o.lowMem { + dst = make([]byte, 0, len(src)) + } + dst = fh.appendTo(dst) + + // If we can do everything in one block, prefer that. + if len(src) <= e.o.blockSize { + enc.Reset(e.o.dict, true) + // Slightly faster with no history and everything in one block. + if e.o.crc { + _, _ = enc.CRC().Write(src) + } + blk := enc.Block() + blk.last = true + if e.o.dict == nil { + enc.EncodeNoHist(blk, src) + } else { + enc.Encode(blk, src) + } + + // If we got the exact same number of literals as input, + // assume the literals cannot be compressed. + oldout := blk.output + // Output directly to dst + blk.output = dst + + err := blk.encode(src, e.o.noEntropy, !e.o.allLitEntropy) + if err != nil { + panic(err) + } + dst = blk.output + blk.output = oldout + } else { + enc.Reset(e.o.dict, false) + blk := enc.Block() + for len(src) > 0 { + todo := src + if len(todo) > e.o.blockSize { + todo = todo[:e.o.blockSize] + } + src = src[len(todo):] + if e.o.crc { + _, _ = enc.CRC().Write(todo) + } + blk.pushOffsets() + enc.Encode(blk, todo) + if len(src) == 0 { + blk.last = true + } + err := blk.encode(todo, e.o.noEntropy, !e.o.allLitEntropy) + if err != nil { + panic(err) + } + dst = append(dst, blk.output...) + blk.reset(nil) + } + } + if e.o.crc { + dst = enc.AppendCRC(dst) + } + // Add padding with content from crypto/rand.Reader + if e.o.pad > 0 { + add := calcSkippableFrame(int64(len(dst)), int64(e.o.pad)) + var err error + dst, err = skippableFrame(dst, add, rand.Reader) + if err != nil { + panic(err) + } + } + return dst +} diff --git a/llo/internal/zstdenc/zstd/encoder_options.go b/llo/internal/zstdenc/zstd/encoder_options.go new file mode 100644 index 00000000..ea2c27ed --- /dev/null +++ b/llo/internal/zstdenc/zstd/encoder_options.go @@ -0,0 +1,175 @@ +package zstd + +import ( + "errors" + "fmt" + "math" + "runtime" +) + +// EOption is an option for creating a encoder. +type EOption func(*encoderOptions) error + +// options retains accumulated state of multiple options. +type encoderOptions struct { + resetOpt bool + concurrent int + level EncoderLevel + single *bool + pad int + blockSize int + windowSize int + crc bool + fullZero bool + noEntropy bool + allLitEntropy bool + customWindow bool + customALEntropy bool + customBlockSize bool + lowMem bool + dict *dict + concurrentBlocks bool +} + +func (o *encoderOptions) setDefault() { + *o = encoderOptions{ + concurrent: runtime.GOMAXPROCS(0), + crc: true, + single: nil, + blockSize: maxCompressedBlockSize, + windowSize: 8 << 20, + level: SpeedDefault, + allLitEntropy: false, + lowMem: false, + fullZero: true, + } +} + +// encoder returns an encoder with the selected options. +func (o encoderOptions) encoder() encoder { + switch o.level { + case SpeedDefault: + return &doubleFastEncoder{fastEncoder: fastEncoder{fastBase: fastBase{maxMatchOff: int32(o.windowSize), bufferReset: math.MaxInt32 - int32(o.windowSize*2), lowMem: o.lowMem}}} + } + panic("unknown compression level") +} + +// WithEncoderCRC will add CRC value to output. +// Output will be 4 bytes larger. +// Can be changed with ResetWithOptions. +func WithEncoderCRC(b bool) EOption { + return func(o *encoderOptions) error { o.crc = b; return nil } +} + +// EncoderLevel predefines encoder compression levels. +// Only use the constants made available, since the actual mapping +// of these values are very likely to change and your compression could change +// unpredictably when upgrading the library. +type EncoderLevel int + +const ( + speedNotSet EncoderLevel = iota + + // SpeedFastest will choose the fastest reasonable compression. + // This is roughly equivalent to the fastest Zstandard mode. + SpeedFastest + + // SpeedDefault is the default "pretty fast" compression option. + // This is roughly equivalent to the default Zstandard mode (level 3). + SpeedDefault + + // SpeedBetterCompression will yield better compression than the default. + // Currently it is about zstd level 7-8 with ~ 2x-3x the default CPU usage. + // By using this, notice that CPU usage may go up in the future. + SpeedBetterCompression + + // SpeedBestCompression will choose the best available compression option. + // This will offer the best compression no matter the CPU cost. + SpeedBestCompression + + // speedLast should be kept as the last actual compression option. + // The is not for external usage, but is used to keep track of the valid options. + speedLast +) + +// WithEncoderLevel specifies a predefined compression level. +// Cannot be changed with ResetWithOptions. +func WithEncoderLevel(l EncoderLevel) EOption { + return func(o *encoderOptions) error { + switch { + case l <= speedNotSet || l >= speedLast: + return fmt.Errorf("unknown encoder level") + } + if o.resetOpt && l != o.level { + return errors.New("WithEncoderLevel cannot be changed on Reset") + } + o.level = l + if !o.customWindow { + switch o.level { + case SpeedFastest: + o.windowSize = 4 << 20 + if !o.customBlockSize { + o.blockSize = 1 << 16 + } + case SpeedDefault: + o.windowSize = 8 << 20 + case SpeedBetterCompression: + o.windowSize = 8 << 20 + case SpeedBestCompression: + o.windowSize = 8 << 20 + } + } + if !o.customALEntropy { + o.allLitEntropy = l > SpeedDefault + } + + return nil + } +} + +// WithZeroFrames will encode 0 length input as full frames. +// This can be needed for compatibility with zstandard usage, +// but is not needed for this package. +// Can be changed with ResetWithOptions. +func WithZeroFrames(b bool) EOption { + return func(o *encoderOptions) error { + o.fullZero = b + return nil + } +} + +// WithSingleSegment will set the "single segment" flag when EncodeAll is used. +// If this flag is set, data must be regenerated within a single continuous memory segment. +// In this case, Window_Descriptor byte is skipped, but Frame_Content_Size is necessarily present. +// As a consequence, the decoder must allocate a memory segment of size equal or larger than size of your content. +// In order to preserve the decoder from unreasonable memory requirements, +// a decoder is allowed to reject a compressed frame which requests a memory size beyond decoder's authorized range. +// For broader compatibility, decoders are recommended to support memory sizes of at least 8 MB. +// This is only a recommendation, each decoder is free to support higher or lower limits, depending on local limitations. +// If this is not specified, block encodes will automatically choose this based on the input size and the window size. +// This setting has no effect on streamed encodes. +// Can be changed with ResetWithOptions. +func WithSingleSegment(b bool) EOption { + return func(o *encoderOptions) error { + o.single = &b + return nil + } +} + +// jobSize returns the input section size per parallel job. +func (o *encoderOptions) jobSize() int { + s := max(o.windowSize*4, 512<<10) + return s +} + +// overlapSize returns the overlap prefix size for parallel jobs. +func (o *encoderOptions) overlapSize() int { + switch o.level { + case SpeedBestCompression: + return o.windowSize / 2 + case SpeedBetterCompression: + return o.windowSize / 4 + default: + return o.windowSize / 8 + } +} diff --git a/llo/internal/zstdenc/zstd/framedec.go b/llo/internal/zstdenc/zstd/framedec.go new file mode 100644 index 00000000..3acbeac6 --- /dev/null +++ b/llo/internal/zstdenc/zstd/framedec.go @@ -0,0 +1,19 @@ +// Copyright 2019+ Klaus Post. All rights reserved. +// License information can be found in the LICENSE file. +// Based on work by Yann Collet, released under BSD License. + +package zstd + +const ( + // MinWindowSize is the minimum Window Size, which is 1 KB. + MinWindowSize = 1 << 10 + + // MaxWindowSize is the maximum encoder window size + // and the default decoder maximum window size. + MaxWindowSize = 1 << 29 +) + +const ( + frameMagic = "\x28\xb5\x2f\xfd" + skippableFrameMagic = "\x2a\x4d\x18" +) diff --git a/llo/internal/zstdenc/zstd/frameenc.go b/llo/internal/zstdenc/zstd/frameenc.go new file mode 100644 index 00000000..697298fe --- /dev/null +++ b/llo/internal/zstdenc/zstd/frameenc.go @@ -0,0 +1,135 @@ +// Copyright 2019+ Klaus Post. All rights reserved. +// License information can be found in the LICENSE file. +// Based on work by Yann Collet, released under BSD License. + +package zstd + +import ( + "encoding/binary" + "fmt" + "io" + "math" + "math/bits" +) + +type frameHeader struct { + ContentSize uint64 + WindowSize uint32 + SingleSegment bool + Checksum bool + DictID uint32 +} + +func (f frameHeader) appendTo(dst []byte) []byte { + dst = append(dst, frameMagic...) + var fhd uint8 + if f.Checksum { + fhd |= 1 << 2 + } + if f.SingleSegment { + fhd |= 1 << 5 + } + + var dictIDContent []byte + if f.DictID > 0 { + var tmp [4]byte + if f.DictID < 256 { + fhd |= 1 + tmp[0] = uint8(f.DictID) + dictIDContent = tmp[:1] + } else if f.DictID < 1<<16 { + fhd |= 2 + binary.LittleEndian.PutUint16(tmp[:2], uint16(f.DictID)) + dictIDContent = tmp[:2] + } else { + fhd |= 3 + binary.LittleEndian.PutUint32(tmp[:4], f.DictID) + dictIDContent = tmp[:4] + } + } + var fcs uint8 + if f.ContentSize >= 256 { + fcs++ + } + if f.ContentSize >= 65536+256 { + fcs++ + } + if f.ContentSize >= 0xffffffff { + fcs++ + } + + fhd |= fcs << 6 + + dst = append(dst, fhd) + if !f.SingleSegment { + const winLogMin = 10 + windowLog := (bits.Len32(f.WindowSize-1) - winLogMin) << 3 + dst = append(dst, uint8(windowLog)) + } + if f.DictID > 0 { + dst = append(dst, dictIDContent...) + } + switch fcs { + case 0: + if f.SingleSegment { + dst = append(dst, uint8(f.ContentSize)) + } + // Unless SingleSegment is set, framessizes < 256 are not stored. + case 1: + f.ContentSize -= 256 + dst = append(dst, uint8(f.ContentSize), uint8(f.ContentSize>>8)) + case 2: + dst = append(dst, uint8(f.ContentSize), uint8(f.ContentSize>>8), uint8(f.ContentSize>>16), uint8(f.ContentSize>>24)) + case 3: + dst = append(dst, uint8(f.ContentSize), uint8(f.ContentSize>>8), uint8(f.ContentSize>>16), uint8(f.ContentSize>>24), + uint8(f.ContentSize>>32), uint8(f.ContentSize>>40), uint8(f.ContentSize>>48), uint8(f.ContentSize>>56)) + default: + panic("invalid fcs") + } + return dst +} + +const skippableFrameHeader = 4 + 4 + +// calcSkippableFrame will return a total size to be added for written +// to be divisible by multiple. +// The value will always be > skippableFrameHeader. +// The function will panic if written < 0 or wantMultiple <= 0. +func calcSkippableFrame(written, wantMultiple int64) int { + if wantMultiple <= 0 { + panic("wantMultiple <= 0") + } + if written < 0 { + panic("written < 0") + } + leftOver := written % wantMultiple + if leftOver == 0 { + return 0 + } + toAdd := wantMultiple - leftOver + for toAdd < skippableFrameHeader { + toAdd += wantMultiple + } + return int(toAdd) +} + +// skippableFrame will add a skippable frame with a total size of bytes. +// total should be >= skippableFrameHeader and < math.MaxUint32. +func skippableFrame(dst []byte, total int, r io.Reader) ([]byte, error) { + if total == 0 { + return dst, nil + } + if total < skippableFrameHeader { + return dst, fmt.Errorf("requested skippable frame (%d) < 8", total) + } + if int64(total) > math.MaxUint32 { + return dst, fmt.Errorf("requested skippable frame (%d) > max uint32", total) + } + dst = append(dst, 0x50, 0x2a, 0x4d, 0x18) + f := uint32(total - skippableFrameHeader) + dst = append(dst, uint8(f), uint8(f>>8), uint8(f>>16), uint8(f>>24)) + start := len(dst) + dst = append(dst, make([]byte, f)...) + _, err := io.ReadFull(r, dst[start:]) + return dst, err +} diff --git a/llo/internal/zstdenc/zstd/fse_decoder.go b/llo/internal/zstdenc/zstd/fse_decoder.go new file mode 100644 index 00000000..94fe8c7c --- /dev/null +++ b/llo/internal/zstdenc/zstd/fse_decoder.go @@ -0,0 +1,37 @@ +// Copyright 2019+ Klaus Post. All rights reserved. +// License information can be found in the LICENSE file. +// Based on work by Yann Collet, released under BSD License. + +package zstd + +const ( + tablelogAbsoluteMax = 9 +) + +const ( + /*!MEMORY_USAGE : + * Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB; etc.) + * Increasing memory usage improves compression ratio + * Reduced memory usage can improve speed, due to cache effect + * Recommended max value is 14, for 16KB, which nicely fits into Intel x86 L1 cache */ + maxMemoryUsage = tablelogAbsoluteMax + 2 + + maxTableLog = maxMemoryUsage - 2 + maxTablesize = 1 << maxTableLog + maxTableMask = (1 << maxTableLog) - 1 + minTablelog = 5 + maxSymbolValue = 255 +) + +// fseDecoder provides temporary storage for compression and decompression. +type fseDecoder struct { + symbolLen uint16 // Length of active part of the symbol table. + actualTableLog uint8 // Selected tablelog. + + norm [maxSymbolValue + 1]int16 +} + +// tableStep returns the next table index. +func tableStep(tableSize uint32) uint32 { + return (tableSize >> 1) + (tableSize >> 3) + 3 +} diff --git a/llo/internal/zstdenc/zstd/fse_encoder.go b/llo/internal/zstdenc/zstd/fse_encoder.go new file mode 100644 index 00000000..3a0f4e7f --- /dev/null +++ b/llo/internal/zstdenc/zstd/fse_encoder.go @@ -0,0 +1,701 @@ +// Copyright 2019+ Klaus Post. All rights reserved. +// License information can be found in the LICENSE file. +// Based on work by Yann Collet, released under BSD License. + +package zstd + +import ( + "errors" + "fmt" + "math" +) + +const ( + // For encoding we only support up to + maxEncTableLog = 8 + maxEncTablesize = 1 << maxTableLog + maxEncTableMask = (1 << maxTableLog) - 1 + minEncTablelog = 5 + maxEncSymbolValue = maxMatchLengthSymbol +) + +// Scratch provides temporary storage for compression and decompression. +type fseEncoder struct { + symbolLen uint16 // Length of active part of the symbol table. + actualTableLog uint8 // Selected tablelog. + ct cTable // Compression tables. + maxCount int // count of the most probable symbol + zeroBits bool // no bits has prob > 50%. + clearCount bool // clear count + useRLE bool // This encoder is for RLE + preDefined bool // This encoder is predefined. + reUsed bool // Set to know when the encoder has been reused. + rleVal uint8 // RLE Symbol + maxBits uint8 // Maximum output bits after transform. + + // TODO: Technically zstd should be fine with 64 bytes. + count [256]uint32 + norm [256]int16 +} + +// cTable contains tables used for compression. +type cTable struct { + tableSymbol []byte + stateTable []uint16 + symbolTT []symbolTransform +} + +// symbolTransform contains the state transform for a symbol. +type symbolTransform struct { + deltaNbBits uint32 + deltaFindState int16 + outBits uint8 +} + +// String prints values as a human readable string. +func (s symbolTransform) String() string { + return fmt.Sprintf("{deltabits: %08x, findstate:%d outbits:%d}", s.deltaNbBits, s.deltaFindState, s.outBits) +} + +// Histogram allows to populate the histogram and skip that step in the compression, +// It otherwise allows to inspect the histogram when compression is done. +// To indicate that you have populated the histogram call HistogramFinished +// with the value of the highest populated symbol, as well as the number of entries +// in the most populated entry. These are accepted at face value. +func (s *fseEncoder) Histogram() *[256]uint32 { + return &s.count +} + +// HistogramFinished can be called to indicate that the histogram has been populated. +// maxSymbol is the index of the highest set symbol of the next data segment. +// maxCount is the number of entries in the most populated entry. +// These are accepted at face value. +func (s *fseEncoder) HistogramFinished(maxSymbol uint8, maxCount int) { + s.maxCount = maxCount + s.symbolLen = uint16(maxSymbol) + 1 + s.clearCount = maxCount != 0 +} + +// allocCtable will allocate tables needed for compression. +// If existing tables a re big enough, they are simply re-used. +func (s *fseEncoder) allocCtable() { + tableSize := 1 << s.actualTableLog + // get tableSymbol that is big enough. + if cap(s.ct.tableSymbol) < tableSize { + s.ct.tableSymbol = make([]byte, tableSize) + } + s.ct.tableSymbol = s.ct.tableSymbol[:tableSize] + + ctSize := tableSize + if cap(s.ct.stateTable) < ctSize { + s.ct.stateTable = make([]uint16, ctSize) + } + s.ct.stateTable = s.ct.stateTable[:ctSize] + + if cap(s.ct.symbolTT) < 256 { + s.ct.symbolTT = make([]symbolTransform, 256) + } + s.ct.symbolTT = s.ct.symbolTT[:256] +} + +// buildCTable will populate the compression table so it is ready to be used. +func (s *fseEncoder) buildCTable() error { + tableSize := uint32(1 << s.actualTableLog) + highThreshold := tableSize - 1 + var cumul [256]int16 + + s.allocCtable() + tableSymbol := s.ct.tableSymbol[:tableSize] + // symbol start positions + { + cumul[0] = 0 + for ui, v := range s.norm[:s.symbolLen-1] { + u := byte(ui) // one less than reference + if v == -1 { + // Low proba symbol + cumul[u+1] = cumul[u] + 1 + tableSymbol[highThreshold] = u + highThreshold-- + } else { + cumul[u+1] = cumul[u] + v + } + } + // Encode last symbol separately to avoid overflowing u + u := int(s.symbolLen - 1) + v := s.norm[s.symbolLen-1] + if v == -1 { + // Low proba symbol + cumul[u+1] = cumul[u] + 1 + tableSymbol[highThreshold] = byte(u) + highThreshold-- + } else { + cumul[u+1] = cumul[u] + v + } + if uint32(cumul[s.symbolLen]) != tableSize { + return fmt.Errorf("internal error: expected cumul[s.symbolLen] (%d) == tableSize (%d)", cumul[s.symbolLen], tableSize) + } + cumul[s.symbolLen] = int16(tableSize) + 1 + } + // Spread symbols + s.zeroBits = false + { + step := tableStep(tableSize) + tableMask := tableSize - 1 + var position uint32 + // if any symbol > largeLimit, we may have 0 bits output. + largeLimit := int16(1 << (s.actualTableLog - 1)) + for ui, v := range s.norm[:s.symbolLen] { + symbol := byte(ui) + if v > largeLimit { + s.zeroBits = true + } + for range v { + tableSymbol[position] = symbol + position = (position + step) & tableMask + for position > highThreshold { + position = (position + step) & tableMask + } /* Low proba area */ + } + } + + // Check if we have gone through all positions + if position != 0 { + return errors.New("position!=0") + } + } + + // Build table + table := s.ct.stateTable + { + tsi := int(tableSize) + for u, v := range tableSymbol { + // TableU16 : sorted by symbol order; gives next state value + table[cumul[v]] = uint16(tsi + u) + cumul[v]++ + } + } + + // Build Symbol Transformation Table + { + total := int16(0) + symbolTT := s.ct.symbolTT[:s.symbolLen] + tableLog := s.actualTableLog + tl := (uint32(tableLog) << 16) - (1 << tableLog) + for i, v := range s.norm[:s.symbolLen] { + switch v { + case 0: + case -1, 1: + symbolTT[i].deltaNbBits = tl + symbolTT[i].deltaFindState = total - 1 + total++ + default: + maxBitsOut := uint32(tableLog) - highBit(uint32(v-1)) + minStatePlus := uint32(v) << maxBitsOut + symbolTT[i].deltaNbBits = (maxBitsOut << 16) - minStatePlus + symbolTT[i].deltaFindState = total - v + total += v + } + } + if total != int16(tableSize) { + return fmt.Errorf("total mismatch %d (got) != %d (want)", total, tableSize) + } + } + return nil +} + +var rtbTable = [...]uint32{0, 473195, 504333, 520860, 550000, 700000, 750000, 830000} + +func (s *fseEncoder) setRLE(val byte) { + s.allocCtable() + s.actualTableLog = 0 + s.ct.stateTable = s.ct.stateTable[:1] + s.ct.symbolTT[val] = symbolTransform{ + deltaFindState: 0, + deltaNbBits: 0, + } + if debugEncoder { + println("setRLE: val", val, "symbolTT", s.ct.symbolTT[val]) + } + s.rleVal = val + s.useRLE = true +} + +// setBits will set output bits for the transform. +// if nil is provided, the number of bits is equal to the index. +func (s *fseEncoder) setBits(transform []byte) { + if s.reUsed || s.preDefined { + return + } + if s.useRLE { + if transform == nil { + s.ct.symbolTT[s.rleVal].outBits = s.rleVal + s.maxBits = s.rleVal + return + } + s.maxBits = transform[s.rleVal] + s.ct.symbolTT[s.rleVal].outBits = s.maxBits + return + } + if transform == nil { + for i := range s.ct.symbolTT[:s.symbolLen] { + s.ct.symbolTT[i].outBits = uint8(i) + } + s.maxBits = uint8(s.symbolLen - 1) + return + } + s.maxBits = 0 + for i, v := range transform[:s.symbolLen] { + s.ct.symbolTT[i].outBits = v + if v > s.maxBits { + // We could assume bits always going up, but we play safe. + s.maxBits = v + } + } +} + +// normalizeCount will normalize the count of the symbols so +// the total is equal to the table size. +// If successful, compression tables will also be made ready. +func (s *fseEncoder) normalizeCount(length int) error { + if s.reUsed { + return nil + } + s.optimalTableLog(length) + var ( + tableLog = s.actualTableLog + scale = 62 - uint64(tableLog) + step = (1 << 62) / uint64(length) + vStep = uint64(1) << (scale - 20) + stillToDistribute = int16(1 << tableLog) + largest int + largestP int16 + lowThreshold = (uint32)(length >> tableLog) + ) + if s.maxCount == length { + s.useRLE = true + return nil + } + s.useRLE = false + for i, cnt := range s.count[:s.symbolLen] { + // already handled + // if (count[s] == s.length) return 0; /* rle special case */ + + if cnt == 0 { + s.norm[i] = 0 + continue + } + if cnt <= lowThreshold { + s.norm[i] = -1 + stillToDistribute-- + } else { + proba := (int16)((uint64(cnt) * step) >> scale) + if proba < 8 { + restToBeat := vStep * uint64(rtbTable[proba]) + v := uint64(cnt)*step - (uint64(proba) << scale) + if v > restToBeat { + proba++ + } + } + if proba > largestP { + largestP = proba + largest = i + } + s.norm[i] = proba + stillToDistribute -= proba + } + } + + if -stillToDistribute >= (s.norm[largest] >> 1) { + // corner case, need another normalization method + err := s.normalizeCount2(length) + if err != nil { + return err + } + if debugAsserts { + err = s.validateNorm() + if err != nil { + return err + } + } + return s.buildCTable() + } + s.norm[largest] += stillToDistribute + if debugAsserts { + err := s.validateNorm() + if err != nil { + return err + } + } + return s.buildCTable() +} + +// Secondary normalization method. +// To be used when primary method fails. +func (s *fseEncoder) normalizeCount2(length int) error { + const notYetAssigned = -2 + var ( + distributed uint32 + total = uint32(length) + tableLog = s.actualTableLog + lowThreshold = total >> tableLog + lowOne = (total * 3) >> (tableLog + 1) + ) + for i, cnt := range s.count[:s.symbolLen] { + if cnt == 0 { + s.norm[i] = 0 + continue + } + if cnt <= lowThreshold { + s.norm[i] = -1 + distributed++ + total -= cnt + continue + } + if cnt <= lowOne { + s.norm[i] = 1 + distributed++ + total -= cnt + continue + } + s.norm[i] = notYetAssigned + } + toDistribute := (1 << tableLog) - distributed + + if (total / toDistribute) > lowOne { + // risk of rounding to zero + lowOne = (total * 3) / (toDistribute * 2) + for i, cnt := range s.count[:s.symbolLen] { + if (s.norm[i] == notYetAssigned) && (cnt <= lowOne) { + s.norm[i] = 1 + distributed++ + total -= cnt + continue + } + } + toDistribute = (1 << tableLog) - distributed + } + if distributed == uint32(s.symbolLen)+1 { + // all values are pretty poor; + // probably incompressible data (should have already been detected); + // find max, then give all remaining points to max + var maxV int + var maxC uint32 + for i, cnt := range s.count[:s.symbolLen] { + if cnt > maxC { + maxV = i + maxC = cnt + } + } + s.norm[maxV] += int16(toDistribute) + return nil + } + + if total == 0 { + // all of the symbols were low enough for the lowOne or lowThreshold + for i := uint32(0); toDistribute > 0; i = (i + 1) % (uint32(s.symbolLen)) { + if s.norm[i] > 0 { + toDistribute-- + s.norm[i]++ + } + } + return nil + } + + var ( + vStepLog = 62 - uint64(tableLog) + mid = uint64((1 << (vStepLog - 1)) - 1) + rStep = (((1 << vStepLog) * uint64(toDistribute)) + mid) / uint64(total) // scale on remaining + tmpTotal = mid + ) + for i, cnt := range s.count[:s.symbolLen] { + if s.norm[i] == notYetAssigned { + var ( + end = tmpTotal + uint64(cnt)*rStep + sStart = uint32(tmpTotal >> vStepLog) + sEnd = uint32(end >> vStepLog) + weight = sEnd - sStart + ) + if weight < 1 { + return errors.New("weight < 1") + } + s.norm[i] = int16(weight) + tmpTotal = end + } + } + return nil +} + +// optimalTableLog calculates and sets the optimal tableLog in s.actualTableLog +func (s *fseEncoder) optimalTableLog(length int) { + tableLog := uint8(maxEncTableLog) + minBitsSrc := highBit(uint32(length)) + 1 + minBitsSymbols := highBit(uint32(s.symbolLen-1)) + 2 + minBits := uint8(minBitsSymbols) + if minBitsSrc < minBitsSymbols { + minBits = uint8(minBitsSrc) + } + + maxBitsSrc := uint8(highBit(uint32(length-1))) - 2 + if maxBitsSrc < tableLog { + // Accuracy can be reduced + tableLog = maxBitsSrc + } + if minBits > tableLog { + tableLog = minBits + } + // Need a minimum to safely represent all symbol values + if tableLog < minEncTablelog { + tableLog = minEncTablelog + } + if tableLog > maxEncTableLog { + tableLog = maxEncTableLog + } + s.actualTableLog = tableLog +} + +// validateNorm validates the normalized histogram table. +func (s *fseEncoder) validateNorm() (err error) { + var total int + for _, v := range s.norm[:s.symbolLen] { + if v >= 0 { + total += int(v) + } else { + total -= int(v) + } + } + defer func() { + if err == nil { + return + } + fmt.Printf("selected TableLog: %d, Symbol length: %d\n", s.actualTableLog, s.symbolLen) + for i, v := range s.norm[:s.symbolLen] { + fmt.Printf("%3d: %5d -> %4d \n", i, s.count[i], v) + } + }() + if total != (1 << s.actualTableLog) { + return fmt.Errorf("warning: Total == %d != %d", total, 1<> 3) + 3 + 2 + + // Write Table Size + bitStream = uint32(tableLog - minEncTablelog) + bitCount = uint(4) + remaining = int16(tableSize + 1) /* +1 for extra accuracy */ + threshold = int16(tableSize) + nbBits = uint(tableLog + 1) + outP = len(out) + ) + if cap(out) < outP+maxHeaderSize { + out = append(out, make([]byte, maxHeaderSize*3)...) + out = out[:len(out)-maxHeaderSize*3] + } + out = out[:outP+maxHeaderSize] + + // stops at 1 + for remaining > 1 { + if previous0 { + start := charnum + for s.norm[charnum] == 0 { + charnum++ + } + for charnum >= start+24 { + start += 24 + bitStream += uint32(0xFFFF) << bitCount + out[outP] = byte(bitStream) + out[outP+1] = byte(bitStream >> 8) + outP += 2 + bitStream >>= 16 + } + for charnum >= start+3 { + start += 3 + bitStream += 3 << bitCount + bitCount += 2 + } + bitStream += uint32(charnum-start) << bitCount + bitCount += 2 + if bitCount > 16 { + out[outP] = byte(bitStream) + out[outP+1] = byte(bitStream >> 8) + outP += 2 + bitStream >>= 16 + bitCount -= 16 + } + } + + count := s.norm[charnum] + charnum++ + max := (2*threshold - 1) - remaining + if count < 0 { + remaining += count + } else { + remaining -= count + } + count++ // +1 for extra accuracy + if count >= threshold { + count += max // [0..max[ [max..threshold[ (...) [threshold+max 2*threshold[ + } + bitStream += uint32(count) << bitCount + bitCount += nbBits + if count < max { + bitCount-- + } + + previous0 = count == 1 + if remaining < 1 { + return nil, errors.New("internal error: remaining < 1") + } + for remaining < threshold { + nbBits-- + threshold >>= 1 + } + + if bitCount > 16 { + out[outP] = byte(bitStream) + out[outP+1] = byte(bitStream >> 8) + outP += 2 + bitStream >>= 16 + bitCount -= 16 + } + } + + if outP+2 > len(out) { + return nil, fmt.Errorf("internal error: %d > %d, maxheader: %d, sl: %d, tl: %d, normcount: %v", outP+2, len(out), maxHeaderSize, s.symbolLen, int(tableLog), s.norm[:s.symbolLen]) + } + out[outP] = byte(bitStream) + out[outP+1] = byte(bitStream >> 8) + outP += int((bitCount + 7) / 8) + + if charnum > s.symbolLen { + return nil, errors.New("internal error: charnum > s.symbolLen") + } + return out[:outP], nil +} + +// Approximate symbol cost, as fractional value, using fixed-point format (accuracyLog fractional bits) +// note 1 : assume symbolValue is valid (<= maxSymbolValue) +// note 2 : if freq[symbolValue]==0, @return a fake cost of tableLog+1 bits * +func (s *fseEncoder) bitCost(symbolValue uint8, accuracyLog uint32) uint32 { + minNbBits := s.ct.symbolTT[symbolValue].deltaNbBits >> 16 + threshold := (minNbBits + 1) << 16 + if debugAsserts { + if !(s.actualTableLog < 16) { + panic("!s.actualTableLog < 16") + } + // ensure enough room for renormalization double shift + if !(uint8(accuracyLog) < 31-s.actualTableLog) { + panic("!uint8(accuracyLog) < 31-s.actualTableLog") + } + } + tableSize := uint32(1) << s.actualTableLog + deltaFromThreshold := threshold - (s.ct.symbolTT[symbolValue].deltaNbBits + tableSize) + // linear interpolation (very approximate) + normalizedDeltaFromThreshold := (deltaFromThreshold << accuracyLog) >> s.actualTableLog + bitMultiplier := uint32(1) << accuracyLog + if debugAsserts { + if s.ct.symbolTT[symbolValue].deltaNbBits+tableSize > threshold { + panic("s.ct.symbolTT[symbolValue].deltaNbBits+tableSize > threshold") + } + if normalizedDeltaFromThreshold > bitMultiplier { + panic("normalizedDeltaFromThreshold > bitMultiplier") + } + } + return (minNbBits+1)*bitMultiplier - normalizedDeltaFromThreshold +} + +// Returns the cost in bits of encoding the distribution in count using ctable. +// Histogram should only be up to the last non-zero symbol. +// Returns an -1 if ctable cannot represent all the symbols in count. +func (s *fseEncoder) approxSize(hist []uint32) uint32 { + if int(s.symbolLen) < len(hist) { + // More symbols than we have. + return math.MaxUint32 + } + if s.useRLE { + // We will never reuse RLE encoders. + return math.MaxUint32 + } + const kAccuracyLog = 8 + badCost := (uint32(s.actualTableLog) + 1) << kAccuracyLog + var cost uint32 + for i, v := range hist { + if v == 0 { + continue + } + if s.norm[i] == 0 { + return math.MaxUint32 + } + bitCost := s.bitCost(uint8(i), kAccuracyLog) + if bitCost > badCost { + return math.MaxUint32 + } + cost += v * bitCost + } + return cost >> kAccuracyLog +} + +// maxHeaderSize returns the maximum header size in bits. +// This is not exact size, but we want a penalty for new tables anyway. +func (s *fseEncoder) maxHeaderSize() uint32 { + if s.preDefined { + return 0 + } + if s.useRLE { + return 8 + } + return (((uint32(s.symbolLen) * uint32(s.actualTableLog)) >> 3) + 3) * 8 +} + +// cState contains the compression state of a stream. +type cState struct { + bw *bitWriter + stateTable []uint16 + state uint16 +} + +// init will initialize the compression state to the first symbol of the stream. +func (c *cState) init(bw *bitWriter, ct *cTable, first symbolTransform) { + c.bw = bw + c.stateTable = ct.stateTable + if len(c.stateTable) == 1 { + // RLE + c.stateTable[0] = uint16(0) + c.state = 0 + return + } + nbBitsOut := (first.deltaNbBits + (1 << 15)) >> 16 + im := int32((nbBitsOut << 16) - first.deltaNbBits) + lu := (im >> nbBitsOut) + int32(first.deltaFindState) + c.state = c.stateTable[lu] +} + +// flush will write the tablelog to the output and flush the remaining full bytes. +func (c *cState) flush(tableLog uint8) { + c.bw.flush32() + c.bw.addBits16NC(c.state, tableLog) +} diff --git a/llo/internal/zstdenc/zstd/fse_predefined.go b/llo/internal/zstdenc/zstd/fse_predefined.go new file mode 100644 index 00000000..16fe17d3 --- /dev/null +++ b/llo/internal/zstdenc/zstd/fse_predefined.go @@ -0,0 +1,84 @@ +// Copyright 2019+ Klaus Post. All rights reserved. +// License information can be found in the LICENSE file. +// Based on work by Yann Collet, released under BSD License. + +package zstd + +import ( + "fmt" + "sync" +) + +var ( + // fsePredef are the predefined fse tables as defined here: + // https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#default-distributions + // These values are already transformed. + fsePredef [3]fseDecoder + + // fsePredefEnc are the predefined encoder based on fse tables as defined here: + // https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#default-distributions + // These values are already transformed. + fsePredefEnc [3]fseEncoder + + // bitTables is the bits table for each table. + bitTables = [3][]byte{tableLiteralLengths: llBitsTable[:], tableOffsets: nil, tableMatchLengths: mlBitsTable[:]} +) + +type tableIndex uint8 + +const ( + // indexes for fsePredef and symbolTableX + tableLiteralLengths tableIndex = 0 + tableOffsets tableIndex = 1 + tableMatchLengths tableIndex = 2 + + maxLiteralLengthSymbol = 35 + maxMatchLengthSymbol = 52 +) + +var predef sync.Once + +func initPredefined() { + predef.Do(func() { + // Fill predefined tables and transform them. + // https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#default-distributions + for i := range fsePredef[:] { + f := &fsePredef[i] + switch tableIndex(i) { + case tableLiteralLengths: + // https://github.com/facebook/zstd/blob/ededcfca57366461021c922720878c81a5854a0a/lib/decompress/zstd_decompress_block.c#L243 + f.actualTableLog = 6 + copy(f.norm[:], []int16{4, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 2, 1, 1, 1, 1, 1, + -1, -1, -1, -1}) + f.symbolLen = 36 + case tableOffsets: + // https://github.com/facebook/zstd/blob/ededcfca57366461021c922720878c81a5854a0a/lib/decompress/zstd_decompress_block.c#L281 + f.actualTableLog = 5 + copy(f.norm[:], []int16{ + 1, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1}) + f.symbolLen = 29 + case tableMatchLengths: + //https://github.com/facebook/zstd/blob/ededcfca57366461021c922720878c81a5854a0a/lib/decompress/zstd_decompress_block.c#L304 + f.actualTableLog = 6 + copy(f.norm[:], []int16{ + 1, 4, 3, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, + -1, -1, -1, -1, -1}) + f.symbolLen = 53 + } + // Create encoder as well + enc := &fsePredefEnc[i] + copy(enc.norm[:], f.norm[:]) + enc.symbolLen = f.symbolLen + enc.actualTableLog = f.actualTableLog + if err := enc.buildCTable(); err != nil { + panic(fmt.Errorf("building encoding table %v: %v", tableIndex(i), err)) + } + enc.setBits(bitTables[i]) + enc.preDefined = true + } + }) +} diff --git a/llo/internal/zstdenc/zstd/hash.go b/llo/internal/zstdenc/zstd/hash.go new file mode 100644 index 00000000..2b606a3b --- /dev/null +++ b/llo/internal/zstdenc/zstd/hash.go @@ -0,0 +1,57 @@ +// Copyright 2019+ Klaus Post. All rights reserved. +// License information can be found in the LICENSE file. +// Based on work by Yann Collet, released under BSD License. + +package zstd + +import "runtime" + +const ( + prime3bytes = 506832829 + prime4bytes = 2654435761 + prime5bytes = 889523592379 + prime6bytes = 227718039650203 + prime7bytes = 58295818150454627 + prime8bytes = 0xcf1bbcdcb7a56463 +) + +// hashPrimesInRegs reports whether encoders should keep the 64-bit hash primes +// in registers rather than as constants. The compiler rebuilds a constant at +// every use: one instruction on amd64, but up to 4 on arm64, which also has +// the registers to spare. See hashPrimes8and5. +const hashPrimesInRegs = runtime.GOARCH == "arm64" + +// hashLen returns a hash of the lowest mls bytes of with length output bits. +// mls must be >=3 and <=8. Any other value will return hash for 4 bytes. +// length should always be < 32. +// Preferably length and mls should be a constant for inlining. +func hashLen(u uint64, length, mls uint8) uint32 { + switch mls { + case 3: + return (uint32(u<<8) * prime3bytes) >> (32 - length) + case 5: + return uint32(((u << (64 - 40)) * prime5bytes) >> (64 - length)) + case 6: + return uint32(((u << (64 - 48)) * prime6bytes) >> (64 - length)) + case 7: + return uint32(((u << (64 - 56)) * prime7bytes) >> (64 - length)) + case 8: + return uint32((u * prime8bytes) >> (64 - length)) + default: + return (uint32(u) * prime4bytes) >> (32 - length) + } +} + +// hashPrimes85 is a var so arm64 keeps the primes in registers instead of +// rebuilding each 64-bit prime with up to 4 instructions per use. +var hashPrimes85 = [2]uint64{prime8bytes, prime5bytes} + +// hashPrimes8and5 returns prime8bytes and prime5bytes for encoders that hash +// 8 and 5 bytes. Where registers are too scarce to hold them, it returns the +// constants. +func hashPrimes8and5() (prime8, prime5 uint64) { + if hashPrimesInRegs { + return hashPrimes85[0], hashPrimes85[1] + } + return prime8bytes, prime5bytes +} diff --git a/llo/internal/zstdenc/zstd/matchlen_amd64.go b/llo/internal/zstdenc/zstd/matchlen_amd64.go new file mode 100644 index 00000000..1d89a600 --- /dev/null +++ b/llo/internal/zstdenc/zstd/matchlen_amd64.go @@ -0,0 +1,15 @@ +//go:build amd64 && !noasm && gc + +// Copyright 2019+ Klaus Post. All rights reserved. +// License information can be found in the LICENSE file. + +package zstd + +// matchLen returns how many bytes match in a and b +// +// It assumes that: +// +// len(a) <= len(b) and len(a) > 0 +// +//go:noescape +func matchLen(a []byte, b []byte) int diff --git a/llo/internal/zstdenc/zstd/matchlen_amd64.s b/llo/internal/zstdenc/zstd/matchlen_amd64.s new file mode 100644 index 00000000..760046f0 --- /dev/null +++ b/llo/internal/zstdenc/zstd/matchlen_amd64.s @@ -0,0 +1,66 @@ +// Copied from S2 implementation. + +//go:build !noasm && gc + +#include "textflag.h" + +// func matchLen(a []byte, b []byte) int +TEXT ·matchLen(SB), NOSPLIT, $0-56 + MOVQ a_base+0(FP), AX + MOVQ b_base+24(FP), CX + MOVQ a_len+8(FP), DX + + // matchLen + XORL SI, SI + CMPL DX, $0x08 + JB matchlen_match4_standalone + +matchlen_loopback_standalone: + MOVQ (AX)(SI*1), BX + XORQ (CX)(SI*1), BX + JZ matchlen_loop_standalone + +#ifdef GOAMD64_v3 + TZCNTQ BX, BX +#else + BSFQ BX, BX +#endif + SHRL $0x03, BX + LEAL (SI)(BX*1), SI + JMP gen_match_len_end + +matchlen_loop_standalone: + LEAL -8(DX), DX + LEAL 8(SI), SI + CMPL DX, $0x08 + JAE matchlen_loopback_standalone + +matchlen_match4_standalone: + CMPL DX, $0x04 + JB matchlen_match2_standalone + MOVL (AX)(SI*1), BX + CMPL (CX)(SI*1), BX + JNE matchlen_match2_standalone + LEAL -4(DX), DX + LEAL 4(SI), SI + +matchlen_match2_standalone: + CMPL DX, $0x02 + JB matchlen_match1_standalone + MOVW (AX)(SI*1), BX + CMPW (CX)(SI*1), BX + JNE matchlen_match1_standalone + LEAL -2(DX), DX + LEAL 2(SI), SI + +matchlen_match1_standalone: + CMPL DX, $0x01 + JB gen_match_len_end + MOVB (AX)(SI*1), BL + CMPB (CX)(SI*1), BL + JNE gen_match_len_end + INCL SI + +gen_match_len_end: + MOVQ SI, ret+48(FP) + RET diff --git a/llo/internal/zstdenc/zstd/matchlen_generic.go b/llo/internal/zstdenc/zstd/matchlen_generic.go new file mode 100644 index 00000000..bbb59e4e --- /dev/null +++ b/llo/internal/zstdenc/zstd/matchlen_generic.go @@ -0,0 +1,37 @@ +//go:build !amd64 || !gc || noasm + +// Copyright 2019+ Klaus Post. All rights reserved. +// License information can be found in the LICENSE file. + +package zstd + +import ( + "math/bits" + + "github.com/smartcontractkit/chainlink-data-streams/llo/internal/zstdenc/internal/le" +) + +// matchLen returns the maximum common prefix length of a and b. +// a must be the shortest of the two. +func matchLen(a, b []byte) (n int) { + left := len(a) + for left >= 8 { + diff := le.Load64(a, n) ^ le.Load64(b, n) + if diff != 0 { + return n + bits.TrailingZeros64(diff)>>3 + } + n += 8 + left -= 8 + } + a = a[n:] + b = b[n:] + + for i := range a { + if a[i] != b[i] { + break + } + n++ + } + return n + +} diff --git a/llo/internal/zstdenc/zstd/seqdec.go b/llo/internal/zstdenc/zstd/seqdec.go new file mode 100644 index 00000000..747044d8 --- /dev/null +++ b/llo/internal/zstdenc/zstd/seqdec.go @@ -0,0 +1,46 @@ +// Copyright 2019+ Klaus Post. All rights reserved. +// License information can be found in the LICENSE file. +// Based on work by Yann Collet, released under BSD License. + +package zstd + +import ( + "fmt" +) + +type seq struct { + litLen uint32 + matchLen uint32 + offset uint32 + + // Codes are stored here for the encoder + // so they only have to be looked up once. + llCode, mlCode, ofCode uint8 +} + +func (s seq) String() string { + if s.offset <= 3 { + if s.offset == 0 { + return fmt.Sprint("litLen:", s.litLen, ", matchLen:", s.matchLen+zstdMinMatch, ", offset: INVALID (0)") + } + return fmt.Sprint("litLen:", s.litLen, ", matchLen:", s.matchLen+zstdMinMatch, ", offset:", s.offset, " (repeat)") + } + return fmt.Sprint("litLen:", s.litLen, ", matchLen:", s.matchLen+zstdMinMatch, ", offset:", s.offset-3, " (new)") +} + +type seqCompMode uint8 + +const ( + compModePredefined seqCompMode = iota + compModeRLE + compModeFSE + compModeRepeat +) + +var bitMask [16]uint16 + +func init() { + for i := range bitMask[:] { + bitMask[i] = uint16((1 << uint(i)) - 1) + } +} diff --git a/llo/internal/zstdenc/zstd/seqenc.go b/llo/internal/zstdenc/zstd/seqenc.go new file mode 100644 index 00000000..dc2b4d35 --- /dev/null +++ b/llo/internal/zstdenc/zstd/seqenc.go @@ -0,0 +1,137 @@ +// Copyright 2019+ Klaus Post. All rights reserved. +// License information can be found in the LICENSE file. +// Based on work by Yann Collet, released under BSD License. + +package zstd + +import "math/bits" + +type seqCoders struct { + llEnc, ofEnc, mlEnc *fseEncoder + llPrev, ofPrev, mlPrev *fseEncoder +} + +// setPrev will update the previous encoders to the actually used ones +// and make sure a fresh one is in the main slot. +func (s *seqCoders) setPrev(ll, ml, of *fseEncoder) { + compareSwap := func(used *fseEncoder, current, prev **fseEncoder) { + // We used the new one, more current to history and reuse the previous history + if *current == used { + *prev, *current = *current, *prev + c := *current + p := *prev + c.reUsed = false + p.reUsed = true + return + } + if used == *prev { + return + } + // Ensure we cannot reuse by accident + prevEnc := *prev + prevEnc.symbolLen = 0 + } + compareSwap(ll, &s.llEnc, &s.llPrev) + compareSwap(ml, &s.mlEnc, &s.mlPrev) + compareSwap(of, &s.ofEnc, &s.ofPrev) +} + +func highBit(val uint32) (n uint32) { + return uint32(bits.Len32(val) - 1) +} + +var llCodeTable = [64]byte{0, 1, 2, 3, 4, 5, 6, 7, + 8, 9, 10, 11, 12, 13, 14, 15, + 16, 16, 17, 17, 18, 18, 19, 19, + 20, 20, 20, 20, 21, 21, 21, 21, + 22, 22, 22, 22, 22, 22, 22, 22, + 23, 23, 23, 23, 23, 23, 23, 23, + 24, 24, 24, 24, 24, 24, 24, 24, + 24, 24, 24, 24, 24, 24, 24, 24} + +// Up to 6 bits +const maxLLCode = 35 + +// llBitsTable translates from ll code to number of bits. +var llBitsTable = [maxLLCode + 1]byte{ + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 1, 1, 1, 1, 2, 2, 3, 3, + 4, 6, 7, 8, 9, 10, 11, 12, + 13, 14, 15, 16} + +// llCode returns the code that represents the literal length requested. +func llCode(litLength uint32) uint8 { + const llDeltaCode = 19 + if litLength <= 63 { + return llCodeTable[litLength&63] + } + return uint8(highBit(litLength)) + llDeltaCode +} + +var mlCodeTable = [128]byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, + 32, 32, 33, 33, 34, 34, 35, 35, 36, 36, 36, 36, 37, 37, 37, 37, + 38, 38, 38, 38, 38, 38, 38, 38, 39, 39, 39, 39, 39, 39, 39, 39, + 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, + 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, + 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, + 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42} + +// Up to 6 bits +const maxMLCode = 52 + +// mlBitsTable translates from ml code to number of bits. +var mlBitsTable = [maxMLCode + 1]byte{ + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 1, 1, 1, 1, 2, 2, 3, 3, + 4, 4, 5, 7, 8, 9, 10, 11, + 12, 13, 14, 15, 16} + +// note : mlBase = matchLength - MINMATCH; +// because it's the format it's stored in seqStore->sequences +func mlCode(mlBase uint32) uint8 { + const mlDeltaCode = 36 + if mlBase <= 127 { + return mlCodeTable[mlBase&127] + } + return uint8(highBit(mlBase)) + mlDeltaCode +} + +func ofCode(offset uint32) uint8 { + // A valid offset will always be > 0. + return uint8(bits.Len32(offset) - 1) +} + +// seedPrevFromDict loads the dictionary sequence tables as the "previous" +// encoders, so the first block can use repeat mode. +func (s *seqCoders) seedPrevFromDict(d *dict) { + seed := func(dst, src *fseEncoder) { + if src == nil { + return + } + ct := dst.ct + dst.symbolLen = src.symbolLen + dst.actualTableLog = src.actualTableLog + dst.maxBits = src.maxBits + dst.zeroBits = src.zeroBits + dst.useRLE = false + dst.preDefined = false + dst.reUsed = true + dst.norm = src.norm + // tableSymbol is only used while building, so it is not copied. + ct.stateTable = append(ct.stateTable[:0], src.ct.stateTable...) + if cap(ct.symbolTT) < len(src.ct.symbolTT) { + ct.symbolTT = make([]symbolTransform, len(src.ct.symbolTT)) + } + ct.symbolTT = ct.symbolTT[:len(src.ct.symbolTT)] + copy(ct.symbolTT, src.ct.symbolTT[:src.symbolLen]) + dst.ct = ct + } + seed(s.llPrev, d.llEnc) + seed(s.mlPrev, d.mlEnc) + seed(s.ofPrev, d.ofEnc) +} diff --git a/llo/internal/zstdenc/zstd/zstd.go b/llo/internal/zstdenc/zstd/zstd.go new file mode 100644 index 00000000..cb84442c --- /dev/null +++ b/llo/internal/zstdenc/zstd/zstd.go @@ -0,0 +1,116 @@ +// Package zstd provides decompression of zstandard files. +// +// For advanced usage and examples, go to the README: https://github.com/klauspost/compress/tree/master/zstd#zstd +package zstd + +import ( + "bytes" + "errors" + "log" + + "github.com/smartcontractkit/chainlink-data-streams/llo/internal/zstdenc/internal/le" +) + +// enable debug printing +const debug = false + +// enable encoding debug printing +const debugEncoder = debug + +// enable decoding debug printing +const debugDecoder = debug + +// Enable extra assertions. +const debugAsserts = debug || false + +// print sequence details +const debugSequences = false + +// print detailed matching information +const debugMatches = false + +// force encoder to use predefined tables. +const forcePreDef = false + +// zstdMinMatch is the minimum zstd match length. +const zstdMinMatch = 3 + +var ( + // ErrReservedBlockType is returned when a reserved block type is found. + // Typically this indicates wrong or corrupted input. + ErrReservedBlockType = errors.New("invalid input: reserved block type encountered") + + // ErrCompressedSizeTooBig is returned when a block is bigger than allowed. + // Typically this indicates wrong or corrupted input. + ErrCompressedSizeTooBig = errors.New("invalid input: compressed size too big") + + // ErrBlockTooSmall is returned when a block is too small to be decoded. + // Typically returned on invalid input. + ErrBlockTooSmall = errors.New("block too small") + + // ErrUnexpectedBlockSize is returned when a block has unexpected size. + // Typically returned on invalid input. + ErrUnexpectedBlockSize = errors.New("unexpected block size") + + // ErrMagicMismatch is returned when a "magic" number isn't what is expected. + // Typically this indicates wrong or corrupted input. + ErrMagicMismatch = errors.New("invalid input: magic number mismatch") + + // ErrWindowSizeExceeded is returned when a reference exceeds the valid window size. + // Typically this indicates wrong or corrupted input. + ErrWindowSizeExceeded = errors.New("window size exceeded") + + // ErrWindowSizeTooSmall is returned when no window size is specified. + // Typically this indicates wrong or corrupted input. + ErrWindowSizeTooSmall = errors.New("invalid input: window size was too small") + + // ErrDecoderSizeExceeded is returned if decompressed size exceeds the configured limit. + ErrDecoderSizeExceeded = errors.New("decompressed size exceeds configured limit") + + // ErrUnknownDictionary is returned if the dictionary ID is unknown. + ErrUnknownDictionary = errors.New("unknown dictionary") + + // ErrFrameSizeExceeded is returned if the stated frame size is exceeded. + // This is only returned if SingleSegment is specified on the frame. + ErrFrameSizeExceeded = errors.New("frame size exceeded") + + // ErrFrameSizeMismatch is returned if the stated frame size does not match the expected size. + // This is only returned if SingleSegment is specified on the frame. + ErrFrameSizeMismatch = errors.New("frame size does not match size on stream") + + // ErrCRCMismatch is returned if CRC mismatches. + ErrCRCMismatch = errors.New("CRC check failed") + + // ErrDecoderClosed will be returned if the Decoder was used after + // Close has been called. + ErrDecoderClosed = errors.New("decoder used after Close") + + // ErrEncoderClosed will be returned if the Encoder was used after + // Close has been called. + ErrEncoderClosed = errors.New("encoder used after Close") + + // ErrDecoderNilInput is returned when a nil Reader was provided + // and an operation other than Reset/DecodeAll/Close was attempted. + ErrDecoderNilInput = errors.New("nil input provided as reader") +) + +func printf(format string, a ...any) { + if debug || debugDecoder || debugEncoder { + log.Printf(format, a...) + } +} + +func load3232(b []byte, i int32) uint32 { + return le.Load32(b, i) +} + +func load6432(b []byte, i int32) uint64 { + return le.Load64(b, i) +} + +type byter interface { + Bytes() []byte + Len() int +} + +var _ byter = &bytes.Buffer{} diff --git a/llo/internal/zstdenc/zstd/zstdenc_test.go b/llo/internal/zstdenc/zstd/zstdenc_test.go new file mode 100644 index 00000000..d1bcd8f5 --- /dev/null +++ b/llo/internal/zstdenc/zstd/zstdenc_test.go @@ -0,0 +1,165 @@ +package zstd_test + +import ( + "crypto/sha256" + "encoding/hex" + "fmt" + "math/rand/v2" + "runtime/debug" + "sync" + "testing" + + upstream "github.com/klauspost/compress/zstd" + "github.com/stretchr/testify/require" + + "github.com/smartcontractkit/chainlink-data-streams/llo/internal/zstdenc/zstd" +) + +// upstreamVersion is the klauspost/compress release this package was copied +// from. The differential tests only hold against that release. +const upstreamVersion = "v1.20.3" + +// corpusDigest freezes the output for the whole corpus. It does not depend on +// the upstream module, so it guards the copy even after the decoder moves on. +const corpusDigest = "2b0fbc61999a0c977cf14f8ecd886a6a8fd68d7fc728b559760ac9cb2e8b1f3c" + +func newEncoder(t testing.TB) *zstd.Encoder { + t.Helper() + enc, err := zstd.NewWriter(nil, + zstd.WithEncoderLevel(zstd.SpeedDefault), + zstd.WithEncoderCRC(true), + zstd.WithZeroFrames(false), + zstd.WithSingleSegment(true), + ) + require.NoError(t, err) + return enc +} + +func newUpstreamEncoder(t testing.TB) *upstream.Encoder { + t.Helper() + enc, err := upstream.NewWriter(nil, + upstream.WithEncoderLevel(upstream.SpeedDefault), + upstream.WithEncoderCRC(true), + upstream.WithZeroFrames(false), + upstream.WithSingleSegment(true), + ) + require.NoError(t, err) + return enc +} + +func requireUpstreamVersion(t testing.TB) { + t.Helper() + info, ok := debug.ReadBuildInfo() + require.True(t, ok) + for _, dep := range info.Deps { + if dep.Path == "github.com/klauspost/compress" { + if dep.Version != upstreamVersion { + t.Skipf("upstream is %s, the copy is of %s", dep.Version, upstreamVersion) + } + return + } + } + t.Skip("upstream module not in build info") +} + +type input struct { + name string + data []byte +} + +// corpus covers the encoder paths: empty, raw and RLE blocks, inputs on both +// sides of the 256 byte and 1 KiB frame header thresholds, a single block, +// several 128 KiB blocks, and literal heavy and match heavy content. +func corpus() []input { + rng := rand.New(rand.NewPCG(1, 2)) + var out []input + for _, n := range []int{0, 1, 40, 255, 256, 1000, 1024, 1025, 4096, 128 << 10, 128<<10 + 1, 300_000, 1 << 20, 3 << 20} { + random := make([]byte, n) + for i := range random { + random[i] = byte(rng.Uint32()) + } + text := make([]byte, n) + for i := range text { + text[i] = byte('a' + rng.IntN(6)) + if rng.IntN(4) == 0 && i > 64 { + text[i] = text[i-1-rng.IntN(64)] + } + } + out = append(out, + input{fmt.Sprintf("zeros/%d", n), make([]byte, n)}, + input{fmt.Sprintf("random/%d", n), random}, + input{fmt.Sprintf("text/%d", n), text}, + ) + } + return out +} + +func TestEncodeAll_MatchesUpstream(t *testing.T) { + requireUpstreamVersion(t) + ours, theirs := newEncoder(t), newUpstreamEncoder(t) + for _, in := range corpus() { + require.Equal(t, theirs.EncodeAll(in.data, nil), ours.EncodeAll(in.data, nil), in.name) + } +} + +func TestEncodeAll_RoundTrips(t *testing.T) { + enc := newEncoder(t) + dec, err := upstream.NewReader(nil) + require.NoError(t, err) + defer dec.Close() + for _, in := range corpus() { + if len(in.data) == 0 { + continue // WithZeroFrames(false) writes no frame for empty input. + } + got, err := dec.DecodeAll(enc.EncodeAll(in.data, nil), nil) + require.NoError(t, err, in.name) + require.Equal(t, in.data, got, in.name) + } +} + +func TestEncodeAll_CorpusDigest(t *testing.T) { + enc := newEncoder(t) + h := sha256.New() + for _, in := range corpus() { + b := enc.EncodeAll(in.data, nil) + fmt.Fprintf(h, "%s|%d|", in.name, len(b)) + h.Write(b) + } + require.Equal(t, corpusDigest, hex.EncodeToString(h.Sum(nil))) +} + +func TestEncodeAll_DeterministicAcrossGoroutines(t *testing.T) { + // Encoders are pooled and reused, so an encode must not depend on what + // the pooled encoder compressed before. + enc := newEncoder(t) + inputs := corpus() + want := make([][]byte, len(inputs)) + for i, in := range inputs { + want[i] = enc.EncodeAll(in.data, nil) + } + var wg sync.WaitGroup + for g := range 8 { + wg.Go(func() { + rng := rand.New(rand.NewPCG(uint64(g), 7)) + for _, i := range rng.Perm(len(inputs)) { + if got := enc.EncodeAll(inputs[i].data, nil); string(got) != string(want[i]) { + t.Errorf("%s: output differs", inputs[i].name) + } + } + }) + } + wg.Wait() +} + +func FuzzEncodeAll_MatchesUpstream(f *testing.F) { + requireUpstreamVersion(f) + for _, in := range corpus() { + if len(in.data) <= 4096 { + f.Add(in.data) + } + } + ours, theirs := newEncoder(f), newUpstreamEncoder(f) + f.Fuzz(func(t *testing.T, data []byte) { + require.Equal(t, theirs.EncodeAll(data, nil), ours.EncodeAll(data, nil)) + }) +} diff --git a/llo/pluginconfig/v31config.go b/llo/pluginconfig/v31config.go index 75fafd71..3a50c58a 100644 --- a/llo/pluginconfig/v31config.go +++ b/llo/pluginconfig/v31config.go @@ -57,13 +57,9 @@ type V31Config struct { // VerboseLogging enables additional, potentially expensive logging. VerboseLogging bool `json:"verboseLogging" toml:"verboseLogging"` - // MaxSnapshotRounds bounds how stale this node's own stream values may be - // when it references them. Must be at least 2 and leave - // BlobFetchMarginRounds below BlobLifetimeRounds. - MaxSnapshotRounds uint64 `json:"maxSnapshotRounds" toml:"maxSnapshotRounds"` - // BlobLifetimeRounds bounds how long peers can still fetch a broadcast - // blob. It does not bound staleness, MaxSnapshotRounds does. + // blob, and so for how many rounds a snapshot can be offered. It does not + // bound staleness, the state transition does. BlobLifetimeRounds uint64 `json:"blobLifetimeRounds" toml:"blobLifetimeRounds"` // MaxDurationBlobObservation is the blob pump's per-cycle observation @@ -75,17 +71,6 @@ type V31Config struct { // less. BlobInFlightWaitFactor uint64 `json:"blobInFlightWaitFactor" toml:"blobInFlightWaitFactor"` - // MaxBlobSnapshotAge pins the wall-clock age at which a parked snapshot is - // discarded. Left at zero the pump derives it from the round period it - // measures. A negative value disables the check, leaving MaxSnapshotRounds - // as the only staleness bound. - MaxBlobSnapshotAge Duration `json:"maxBlobSnapshotAge" toml:"maxBlobSnapshotAge"` - - // MaxRoundPeriod bounds the round period the pump measures, so a stalled - // round cannot inflate the derived snapshot age bound. Must be set above the - // DON real round cadence. - MaxRoundPeriod Duration `json:"maxRoundPeriod" toml:"maxRoundPeriod"` - // Plugin telemetry. Each is decided here for v31, independently of // the node CaptureEATelemetry parameter, which keeps driving data source telemetry. // @@ -108,14 +93,11 @@ func (o V31Config) IsZero() bool { } func (o V31Config) Validate() (merr error) { - if _, _, err := v31.ResolveBlobRounds(o.MaxSnapshotRounds, o.BlobLifetimeRounds); err != nil { + if _, err := v31.ResolveBlobLifetimeRounds(o.BlobLifetimeRounds); err != nil { merr = errors.Join(merr, fmt.Errorf("llo: v31: %w", err)) } if o.MaxDurationBlobObservation < 0 { merr = errors.Join(merr, fmt.Errorf("llo: v31: MaxDurationBlobObservation must not be negative, got: %s", o.MaxDurationBlobObservation)) } - if o.MaxRoundPeriod < 0 { - merr = errors.Join(merr, fmt.Errorf("llo: v31: MaxRoundPeriod must not be negative, got: %s", o.MaxRoundPeriod)) - } return merr } diff --git a/llo/pluginconfig/v31config_test.go b/llo/pluginconfig/v31config_test.go index c77f8912..34528d3d 100644 --- a/llo/pluginconfig/v31config_test.go +++ b/llo/pluginconfig/v31config_test.go @@ -28,12 +28,9 @@ func Test_V31Config_Unmarshal(t *testing.T) { pluginVersion = "v31" [v31] verboseLogging = true - maxSnapshotRounds = 2 blobLifetimeRounds = 8 maxDurationBlobObservation = "1s" blobInFlightWaitFactor = 4 - maxBlobSnapshotAge = "-1s" - maxRoundPeriod = "3s" captureOutcomeTelemetry = true captureReportTelemetry = true captureAttributedObservationTelemetry = true @@ -44,12 +41,9 @@ func Test_V31Config_Unmarshal(t *testing.T) { assert.True(t, pc.IsV31()) assert.True(t, pc.V31.VerboseLogging) - assert.Equal(t, uint64(2), pc.V31.MaxSnapshotRounds) assert.Equal(t, uint64(8), pc.V31.BlobLifetimeRounds) assert.Equal(t, time.Second, pc.V31.MaxDurationBlobObservation.Duration()) assert.Equal(t, uint64(4), pc.V31.BlobInFlightWaitFactor) - assert.Equal(t, -time.Second, pc.V31.MaxBlobSnapshotAge.Duration()) - assert.Equal(t, 3*time.Second, pc.V31.MaxRoundPeriod.Duration()) assert.True(t, pc.V31.CaptureOutcomeTelemetry) assert.True(t, pc.V31.CaptureReportTelemetry) assert.True(t, pc.V31.CaptureAttributedObservationTelemetry) @@ -59,13 +53,14 @@ func Test_V31Config_Unmarshal(t *testing.T) { t.Run("from json, duration as string or nanoseconds", func(t *testing.T) { var pc PluginConfig - require.NoError(t, pc.Unmarshal([]byte(`{"v31":{"maxRoundPeriod":"2s","maxDurationBlobObservation":1500000000}}`))) - assert.Equal(t, 2*time.Second, pc.V31.MaxRoundPeriod.Duration()) + require.NoError(t, pc.Unmarshal([]byte(`{"v31":{"maxDurationBlobObservation":"2s"}}`))) + assert.Equal(t, 2*time.Second, pc.V31.MaxDurationBlobObservation.Duration()) + require.NoError(t, pc.Unmarshal([]byte(`{"v31":{"maxDurationBlobObservation":1500000000}}`))) assert.Equal(t, 1500*time.Millisecond, pc.V31.MaxDurationBlobObservation.Duration()) }) t.Run("round trips through json", func(t *testing.T) { - in := V31Config{MaxRoundPeriod: Duration(2 * time.Second), MaxBlobSnapshotAge: Duration(-time.Second)} + in := V31Config{MaxDurationBlobObservation: Duration(2 * time.Second), BlobLifetimeRounds: 8} b, err := json.Marshal(in) require.NoError(t, err) var out V31Config @@ -75,7 +70,7 @@ func Test_V31Config_Unmarshal(t *testing.T) { t.Run("rejects an invalid duration", func(t *testing.T) { var pc PluginConfig - require.Error(t, pc.Unmarshal([]byte(`{"v31":{"maxRoundPeriod":"banana"}}`))) + require.Error(t, pc.Unmarshal([]byte(`{"v31":{"maxDurationBlobObservation":"banana"}}`))) }) } @@ -94,23 +89,20 @@ func Test_V31Config_Validate(t *testing.T) { assert.Contains(t, err.Error(), "exceeds MaxBlobLifetimeRounds") }) - t.Run("rejects too little fetch margin", func(t *testing.T) { + t.Run("rejects a lifetime below the minimum", func(t *testing.T) { pc := v31Base() - pc.V31.MaxSnapshotRounds = 8 - pc.V31.BlobLifetimeRounds = 8 + pc.V31.BlobLifetimeRounds = 1 err := pc.Validate() require.Error(t, err) - assert.Contains(t, err.Error(), "rounds of fetch margin") + assert.Contains(t, err.Error(), "below MinBlobLifetimeRounds") }) - t.Run("rejects negative durations that are not the snapshot age", func(t *testing.T) { + t.Run("rejects a negative duration", func(t *testing.T) { pc := v31Base() pc.V31.MaxDurationBlobObservation = Duration(-time.Second) - pc.V31.MaxRoundPeriod = Duration(-time.Second) err := pc.Validate() require.Error(t, err) assert.Contains(t, err.Error(), "MaxDurationBlobObservation must not be negative") - assert.Contains(t, err.Error(), "MaxRoundPeriod must not be negative") }) t.Run("rejects the block on OCR3.0", func(t *testing.T) { diff --git a/llo/protocol/channel_cache.go b/llo/protocol/channel_cache.go index aee0aaee..c72105b8 100644 --- a/llo/protocol/channel_cache.go +++ b/llo/protocol/channel_cache.go @@ -1,6 +1,7 @@ package protocol import ( + "bytes" "slices" "sync" @@ -30,17 +31,19 @@ const channelGenerationsRetained = 4 // record by a concurrently running round. That is what keeps report encoding // from using opts that are ahead of (or behind) the definitions being reported. type ChannelGeneration struct { - seqNr uint64 - defs llotypes.ChannelDefinitions - opts *OptsCache + seqNr uint64 + record []byte + defs llotypes.ChannelDefinitions + opts *OptsCache } -func newChannelGeneration(seqNr uint64, defs llotypes.ChannelDefinitions) *ChannelGeneration { +func newChannelGeneration(seqNr uint64, record []byte, defs llotypes.ChannelDefinitions) *ChannelGeneration { own := CloneChannelDefinitions(defs) return &ChannelGeneration{ - seqNr: seqNr, - defs: own, - opts: newSealedOptsCache(own), + seqNr: seqNr, + record: bytes.Clone(record), + defs: own, + opts: newSealedOptsCache(own), } } @@ -50,6 +53,12 @@ func (g *ChannelGeneration) SeqNr() uint64 { return g.seqNr } +// Record returns the encoded channel-definitions record the definitions were +// decoded from. Read-only by contract, like Definitions. +func (g *ChannelGeneration) Record() []byte { + return g.record +} + // Definitions returns the snapshot's channel definitions. They are read-only by // contract: callers that mutate must clone first (see CloneChannelDefinitions). func (g *ChannelGeneration) Definitions() llotypes.ChannelDefinitions { @@ -84,31 +93,36 @@ func NewChannelCache() *ChannelCache { } } -// Load returns the generation for seqNr, calling build only on a miss. build -// supplies the definitions of that record; they are deep-copied into the -// generation, so build may return memory it does not own exclusively (a decoded -// KV record, a precursor's definitions) without the generation aliasing it. -func (c *ChannelCache) Load(seqNr uint64, build func() (llotypes.ChannelDefinitions, error)) (*ChannelGeneration, error) { - if c == nil { - defs, err := build() - if err != nil { - return nil, err - } - return newChannelGeneration(seqNr, defs), nil - } - +// Load returns the generation for seqNr, reading and decoding its record only +// on a miss. read supplies the encoded record and decode turns it into +// definitions. The generation keeps both, so Record is always the exact bytes +// its definitions were decoded from. Both are copied into the generation, so +// read may return memory it does not own exclusively (a KV read, a precursor) +// without the generation aliasing it. +func (c *ChannelCache) Load(seqNr uint64, read func() ([]byte, error), decode func([]byte) (llotypes.ChannelDefinitions, error)) (*ChannelGeneration, error) { if gen, ok := c.get(seqNr); ok { return gen, nil } - defs, err := build() + record, err := read() if err != nil { return nil, err } - return c.store(newChannelGeneration(seqNr, defs)), nil + defs, err := decode(record) + if err != nil { + return nil, err + } + gen := newChannelGeneration(seqNr, record, defs) + if c == nil { + return gen, nil + } + return c.store(gen), nil } func (c *ChannelCache) get(seqNr uint64) (*ChannelGeneration, bool) { + if c == nil { + return nil, false + } c.mu.Lock() defer c.mu.Unlock() gen, ok := c.gens[seqNr] diff --git a/llo/protocol/channel_cache_test.go b/llo/protocol/channel_cache_test.go index 4643bb6d..59f4c0fa 100644 --- a/llo/protocol/channel_cache_test.go +++ b/llo/protocol/channel_cache_test.go @@ -24,6 +24,40 @@ func genTestDefs(v int) llotypes.ChannelDefinitions { } } +// load adapts a definitions builder to Load for tests that do not care about +// the record: the record is fixed bytes and decode returns what build built. +func load(c *ChannelCache, seqNr uint64, build func() (llotypes.ChannelDefinitions, error)) (*ChannelGeneration, error) { + var defs llotypes.ChannelDefinitions + read := func() ([]byte, error) { + var err error + defs, err = build() + return []byte("record"), err + } + return c.Load(seqNr, read, func([]byte) (llotypes.ChannelDefinitions, error) { return defs, nil }) +} + +func Test_ChannelCache_KeepsTheRecordItDecoded(t *testing.T) { + c := NewChannelCache() + record := []byte("encoded definitions") + var decoded []byte + gen, err := c.Load(1, func() ([]byte, error) { return record, nil }, func(b []byte) (llotypes.ChannelDefinitions, error) { + decoded = b + return genTestDefs(1), nil + }) + require.NoError(t, err) + require.Equal(t, record, decoded) + require.Equal(t, record, gen.Record()) + + // The generation owns its copy, so the reader may reuse its buffer. + record[0] = 'X' + require.Equal(t, []byte("encoded definitions"), gen.Record()) + + // A hit serves the stored record without reading again. + again, err := c.Load(1, func() ([]byte, error) { return nil, fmt.Errorf("must not read on a hit") }, nil) + require.NoError(t, err) + require.Same(t, gen, again) +} + func Test_ChannelCache_MemoizesBySeqNr(t *testing.T) { c := NewChannelCache() @@ -35,18 +69,18 @@ func Test_ChannelCache_MemoizesBySeqNr(t *testing.T) { } } - first, err := c.Load(7, build(1)) + first, err := load(c, 7, build(1)) require.NoError(t, err) require.Equal(t, 1, builds) // Same seqNr resolves to the same generation without rebuilding: the record // is a pure function of its sequence number. - again, err := c.Load(7, build(2)) + again, err := load(c, 7, build(2)) require.NoError(t, err) require.Same(t, first, again) require.Equal(t, 1, builds) - other, err := c.Load(8, build(2)) + other, err := load(c, 8, build(2)) require.NoError(t, err) require.NotSame(t, first, other) require.Equal(t, 2, builds) @@ -63,7 +97,7 @@ func Test_ChannelCache_MemoizesBySeqNr(t *testing.T) { func Test_ChannelCache_NilReceiverBuildsEveryTime(t *testing.T) { var c *ChannelCache - gen, err := c.Load(1, func() (llotypes.ChannelDefinitions, error) { return genTestDefs(3), nil }) + gen, err := load(c, 1, func() (llotypes.ChannelDefinitions, error) { return genTestDefs(3), nil }) require.NoError(t, err) require.Equal(t, uint64(1), gen.SeqNr()) @@ -74,13 +108,13 @@ func Test_ChannelCache_NilReceiverBuildsEveryTime(t *testing.T) { func Test_ChannelCache_LoadPropagatesBuildError(t *testing.T) { c := NewChannelCache() - _, err := c.Load(1, func() (llotypes.ChannelDefinitions, error) { + _, err := load(c, 1, func() (llotypes.ChannelDefinitions, error) { return nil, fmt.Errorf("boom") }) require.ErrorContains(t, err, "boom") // The failure must not be memoized. - gen, err := c.Load(1, func() (llotypes.ChannelDefinitions, error) { return genTestDefs(1), nil }) + gen, err := load(c, 1, func() (llotypes.ChannelDefinitions, error) { return genTestDefs(1), nil }) require.NoError(t, err) require.NotNil(t, gen) } @@ -88,12 +122,12 @@ func Test_ChannelCache_LoadPropagatesBuildError(t *testing.T) { func Test_ChannelCache_EvictionDoesNotInvalidateHeldGeneration(t *testing.T) { c := NewChannelCache() - held, err := c.Load(1, func() (llotypes.ChannelDefinitions, error) { return genTestDefs(1), nil }) + held, err := load(c, 1, func() (llotypes.ChannelDefinitions, error) { return genTestDefs(1), nil }) require.NoError(t, err) for seqNr := uint64(2); seqNr <= uint64(channelGenerationsRetained+3); seqNr++ { v := int(seqNr) - _, err := c.Load(seqNr, func() (llotypes.ChannelDefinitions, error) { return genTestDefs(v), nil }) + _, err := load(c, seqNr, func() (llotypes.ChannelDefinitions, error) { return genTestDefs(v), nil }) require.NoError(t, err) } @@ -111,7 +145,7 @@ func Test_ChannelCache_EvictionDoesNotInvalidateHeldGeneration(t *testing.T) { func Test_ChannelGeneration_OptsAreSealed(t *testing.T) { c := NewChannelCache() - gen, err := c.Load(1, func() (llotypes.ChannelDefinitions, error) { return genTestDefs(1), nil }) + gen, err := load(c, 1, func() (llotypes.ChannelDefinitions, error) { return genTestDefs(1), nil }) require.NoError(t, err) // Every mutator is a no-op: a generation's opts can never be repointed at @@ -130,7 +164,7 @@ func Test_ChannelGeneration_DoesNotAliasItsSource(t *testing.T) { c := NewChannelCache() source := genTestDefs(1) - gen, err := c.Load(1, func() (llotypes.ChannelDefinitions, error) { return source, nil }) + gen, err := load(c, 1, func() (llotypes.ChannelDefinitions, error) { return source, nil }) require.NoError(t, err) // Mutating the source after the build must not reach the snapshot. @@ -174,7 +208,7 @@ func Test_ChannelCache_ConcurrentLoadYieldsOneGeneration(t *testing.T) { wg.Add(1) go func(i int) { defer wg.Done() - gen, err := c.Load(1, func() (llotypes.ChannelDefinitions, error) { return genTestDefs(1), nil }) + gen, err := load(c, 1, func() (llotypes.ChannelDefinitions, error) { return genTestDefs(1), nil }) require.NoError(t, err) o, err := GetOpts[genTestOpts](gen.Opts(), 1) require.NoError(t, err) diff --git a/llo/protocol/llo_plugin_telemetry.pb.go b/llo/protocol/llo_plugin_telemetry.pb.go index a6d7ce0e..48150c7c 100644 --- a/llo/protocol/llo_plugin_telemetry.pb.go +++ b/llo/protocol/llo_plugin_telemetry.pb.go @@ -39,8 +39,14 @@ type LLOOutcomeTelemetry struct { // 2*aggregationFaultTolerance+1. Zero in LLO v30, which derives the floor // from the consensus F instead. MinContributions uint32 `protobuf:"varint,12,opt,name=min_contributions,json=minContributions,proto3" json:"min_contributions,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Stream value freshness, LLO v31 only: streams whose aggregation left out + // stale contributions, streams that fell back to every contribution because + // the fresh ones missed min_contributions, and contributions judged stale. + StreamsFiltered uint32 `protobuf:"varint,13,opt,name=streams_filtered,json=streamsFiltered,proto3" json:"streams_filtered,omitempty"` + StreamsFallenBack uint32 `protobuf:"varint,14,opt,name=streams_fallen_back,json=streamsFallenBack,proto3" json:"streams_fallen_back,omitempty"` + ContributionsStale uint32 `protobuf:"varint,15,opt,name=contributions_stale,json=contributionsStale,proto3" json:"contributions_stale,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *LLOOutcomeTelemetry) Reset() { @@ -136,6 +142,27 @@ func (x *LLOOutcomeTelemetry) GetMinContributions() uint32 { return 0 } +func (x *LLOOutcomeTelemetry) GetStreamsFiltered() uint32 { + if x != nil { + return x.StreamsFiltered + } + return 0 +} + +func (x *LLOOutcomeTelemetry) GetStreamsFallenBack() uint32 { + if x != nil { + return x.StreamsFallenBack + } + return 0 +} + +func (x *LLOOutcomeTelemetry) GetContributionsStale() uint32 { + if x != nil { + return x.ContributionsStale + } + return 0 +} + type LLOAggregatorStreamValue struct { state protoimpl.MessageState `protogen:"open.v1"` AggregatorValues map[uint32]*LLOStreamValue `protobuf:"bytes,1,rep,name=aggregator_values,json=aggregatorValues,proto3" json:"aggregator_values,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` @@ -445,7 +472,7 @@ var File_llo_plugin_telemetry_proto protoreflect.FileDescriptor const file_llo_plugin_telemetry_proto_rawDesc = "" + "\n" + - "\x1allo_plugin_telemetry.proto\x12\x02v1\x1a\x13plugin_codecs.proto\"\xc8\x06\n" + + "\x1allo_plugin_telemetry.proto\x12\x02v1\x1a\x13plugin_codecs.proto\"\xd4\a\n" + "\x13LLOOutcomeTelemetry\x12(\n" + "\x10life_cycle_stage\x18\x01 \x01(\tR\x0elifeCycleStage\x12J\n" + "!observation_timestamp_nanoseconds\x18\x02 \x01(\x04R\x1fobservationTimestampNanoseconds\x12`\n" + @@ -456,7 +483,10 @@ const file_llo_plugin_telemetry_proto_rawDesc = "" + "\rconfig_digest\x18\n" + " \x01(\fR\fconfigDigest\x12\x15\n" + "\x06don_id\x18\v \x01(\rR\x05donId\x12+\n" + - "\x11min_contributions\x18\f \x01(\rR\x10minContributions\x1ad\n" + + "\x11min_contributions\x18\f \x01(\rR\x10minContributions\x12)\n" + + "\x10streams_filtered\x18\r \x01(\rR\x0fstreamsFiltered\x12.\n" + + "\x13streams_fallen_back\x18\x0e \x01(\rR\x11streamsFallenBack\x12/\n" + + "\x13contributions_stale\x18\x0f \x01(\rR\x12contributionsStale\x1ad\n" + "\x17ChannelDefinitionsEntry\x12\x10\n" + "\x03key\x18\x01 \x01(\rR\x03key\x123\n" + "\x05value\x18\x02 \x01(\v2\x1d.v1.LLOChannelDefinitionProtoR\x05value:\x028\x01\x1aH\n" + diff --git a/llo/protocol/llo_plugin_telemetry.proto b/llo/protocol/llo_plugin_telemetry.proto index c1311345..74737847 100644 --- a/llo/protocol/llo_plugin_telemetry.proto +++ b/llo/protocol/llo_plugin_telemetry.proto @@ -23,6 +23,12 @@ message LLOOutcomeTelemetry { // 2*aggregationFaultTolerance+1. Zero in LLO v30, which derives the floor // from the consensus F instead. uint32 min_contributions = 12; + // Stream value freshness, LLO v31 only: streams whose aggregation left out + // stale contributions, streams that fell back to every contribution because + // the fresh ones missed min_contributions, and contributions judged stale. + uint32 streams_filtered = 13; + uint32 streams_fallen_back = 14; + uint32 contributions_stale = 15; } message LLOAggregatorStreamValue { diff --git a/llo/protocol/plugin_codecs.pb.go b/llo/protocol/plugin_codecs.pb.go index 0502b807..42b88d2f 100644 --- a/llo/protocol/plugin_codecs.pb.go +++ b/llo/protocol/plugin_codecs.pb.go @@ -1209,8 +1209,13 @@ type LLOHotStateProto struct { ValidAfterNanoseconds []*LLOChannelIDAndValidAfterNanosecondsProto `protobuf:"bytes,2,rep,name=validAfterNanoseconds,proto3" json:"validAfterNanoseconds,omitempty"` ReportableChannelIDs []uint32 `protobuf:"varint,3,rep,packed,name=reportableChannelIDs,proto3" json:"reportableChannelIDs,omitempty"` StreamAggregates []*LLOStreamAggregate `protobuf:"bytes,4,rep,name=streamAggregates,proto3" json:"streamAggregates,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Agreed observation timestamps of the most recent rounds, oldest first, + // the last one being the round that wrote this record. Bounded to the + // window LLO v31 needs to judge the age of blob-carried stream values + // against replicated time; see llo/dev/v31 agreedTimestampWindow. + RecentAgreedTimestampsNanoseconds []uint64 `protobuf:"varint,5,rep,packed,name=recentAgreedTimestampsNanoseconds,proto3" json:"recentAgreedTimestampsNanoseconds,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *LLOHotStateProto) Reset() { @@ -1271,6 +1276,69 @@ func (x *LLOHotStateProto) GetStreamAggregates() []*LLOStreamAggregate { return nil } +func (x *LLOHotStateProto) GetRecentAgreedTimestampsNanoseconds() []uint64 { + if x != nil { + return x.RecentAgreedTimestampsNanoseconds + } + return nil +} + +// LLOBlobPayloadProto is the stream values blob a v31 observation references. +// cycleStartSeqNr is the sequence number the blob pump saw when the cycle that +// gathered these values started. The state transition measures the values' age +// from it against replicated data only, so the blob carries no clock reading. +type LLOBlobPayloadProto struct { + state protoimpl.MessageState `protogen:"open.v1"` + CycleStartSeqNr uint64 `protobuf:"varint,1,opt,name=cycleStartSeqNr,proto3" json:"cycleStartSeqNr,omitempty"` + StreamValues map[uint32]*LLOStreamValue `protobuf:"bytes,2,rep,name=streamValues,proto3" json:"streamValues,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *LLOBlobPayloadProto) Reset() { + *x = LLOBlobPayloadProto{} + mi := &file_plugin_codecs_proto_msgTypes[18] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *LLOBlobPayloadProto) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*LLOBlobPayloadProto) ProtoMessage() {} + +func (x *LLOBlobPayloadProto) ProtoReflect() protoreflect.Message { + mi := &file_plugin_codecs_proto_msgTypes[18] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use LLOBlobPayloadProto.ProtoReflect.Descriptor instead. +func (*LLOBlobPayloadProto) Descriptor() ([]byte, []int) { + return file_plugin_codecs_proto_rawDescGZIP(), []int{18} +} + +func (x *LLOBlobPayloadProto) GetCycleStartSeqNr() uint64 { + if x != nil { + return x.CycleStartSeqNr + } + return 0 +} + +func (x *LLOBlobPayloadProto) GetStreamValues() map[uint32]*LLOStreamValue { + if x != nil { + return x.StreamValues + } + return nil +} + // LLOPrecursorProto is the v31 ReportsPlusPrecursor: everything Reports needs, // since Reports gets no KeyValueStateReader. It mirrors LLOOutcomeProtoV1 (which // belongs to the v30 outcome and must not be changed for v31's benefit) and adds @@ -1278,19 +1346,24 @@ func (x *LLOHotStateProto) GetStreamAggregates() []*LLOStreamAggregate { // from, so that consumers can tell whether their decoded-opts cache already // matches these definitions. // +// channelState is that record as stored under c/defs, an encoded +// LLOChannelStateProto. It is carried as bytes so a consumer whose cache holds +// the generation for channelStateSeqNr skips decoding it, and one that does not +// decodes it exactly as the KeyValueState read does. +// // reportableChannelIDs is the reportability decision StateTransition made for // the round, so Reports emits exactly the channels whose watermark advances. // streamAggregates carries only the values those channels report. // // NOTE: must serialize deterministically, hence use of repeated tuple instead of -// maps. channelDefinitions, validAfterNanoseconds and reportableChannelIDs MUST -// be sorted ascending by channelID; streamAggregates MUST be sorted ascending by -// (streamID, aggregator). +// maps. validAfterNanoseconds and reportableChannelIDs MUST be sorted ascending +// by channelID; streamAggregates MUST be sorted ascending by (streamID, +// aggregator). type LLOPrecursorProto struct { state protoimpl.MessageState `protogen:"open.v1"` LifeCycleStage string `protobuf:"bytes,1,opt,name=lifeCycleStage,proto3" json:"lifeCycleStage,omitempty"` ObservationTimestampNanoseconds uint64 `protobuf:"varint,2,opt,name=observationTimestampNanoseconds,proto3" json:"observationTimestampNanoseconds,omitempty"` - ChannelDefinitions []*LLOChannelIDAndDefinitionProto `protobuf:"bytes,3,rep,name=channelDefinitions,proto3" json:"channelDefinitions,omitempty"` + ChannelState []byte `protobuf:"bytes,3,opt,name=channelState,proto3" json:"channelState,omitempty"` ValidAfterNanoseconds []*LLOChannelIDAndValidAfterNanosecondsProto `protobuf:"bytes,4,rep,name=validAfterNanoseconds,proto3" json:"validAfterNanoseconds,omitempty"` StreamAggregates []*LLOStreamAggregate `protobuf:"bytes,5,rep,name=streamAggregates,proto3" json:"streamAggregates,omitempty"` ChannelStateSeqNr uint64 `protobuf:"varint,6,opt,name=channelStateSeqNr,proto3" json:"channelStateSeqNr,omitempty"` @@ -1301,7 +1374,7 @@ type LLOPrecursorProto struct { func (x *LLOPrecursorProto) Reset() { *x = LLOPrecursorProto{} - mi := &file_plugin_codecs_proto_msgTypes[18] + mi := &file_plugin_codecs_proto_msgTypes[19] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1313,7 +1386,7 @@ func (x *LLOPrecursorProto) String() string { func (*LLOPrecursorProto) ProtoMessage() {} func (x *LLOPrecursorProto) ProtoReflect() protoreflect.Message { - mi := &file_plugin_codecs_proto_msgTypes[18] + mi := &file_plugin_codecs_proto_msgTypes[19] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1326,7 +1399,7 @@ func (x *LLOPrecursorProto) ProtoReflect() protoreflect.Message { // Deprecated: Use LLOPrecursorProto.ProtoReflect.Descriptor instead. func (*LLOPrecursorProto) Descriptor() ([]byte, []int) { - return file_plugin_codecs_proto_rawDescGZIP(), []int{18} + return file_plugin_codecs_proto_rawDescGZIP(), []int{19} } func (x *LLOPrecursorProto) GetLifeCycleStage() string { @@ -1343,9 +1416,9 @@ func (x *LLOPrecursorProto) GetObservationTimestampNanoseconds() uint64 { return 0 } -func (x *LLOPrecursorProto) GetChannelDefinitions() []*LLOChannelIDAndDefinitionProto { +func (x *LLOPrecursorProto) GetChannelState() []byte { if x != nil { - return x.ChannelDefinitions + return x.ChannelState } return nil } @@ -1391,7 +1464,7 @@ type LLOCodecSupportProto struct { func (x *LLOCodecSupportProto) Reset() { *x = LLOCodecSupportProto{} - mi := &file_plugin_codecs_proto_msgTypes[19] + mi := &file_plugin_codecs_proto_msgTypes[20] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1403,7 +1476,7 @@ func (x *LLOCodecSupportProto) String() string { func (*LLOCodecSupportProto) ProtoMessage() {} func (x *LLOCodecSupportProto) ProtoReflect() protoreflect.Message { - mi := &file_plugin_codecs_proto_msgTypes[19] + mi := &file_plugin_codecs_proto_msgTypes[20] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1416,7 +1489,7 @@ func (x *LLOCodecSupportProto) ProtoReflect() protoreflect.Message { // Deprecated: Use LLOCodecSupportProto.ProtoReflect.Descriptor instead. func (*LLOCodecSupportProto) Descriptor() ([]byte, []int) { - return file_plugin_codecs_proto_rawDescGZIP(), []int{19} + return file_plugin_codecs_proto_rawDescGZIP(), []int{20} } func (x *LLOCodecSupportProto) GetOracles() []*LLOOracleCodecSupportProto { @@ -1438,7 +1511,7 @@ type LLOOracleCodecSupportProto struct { func (x *LLOOracleCodecSupportProto) Reset() { *x = LLOOracleCodecSupportProto{} - mi := &file_plugin_codecs_proto_msgTypes[20] + mi := &file_plugin_codecs_proto_msgTypes[21] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1450,7 +1523,7 @@ func (x *LLOOracleCodecSupportProto) String() string { func (*LLOOracleCodecSupportProto) ProtoMessage() {} func (x *LLOOracleCodecSupportProto) ProtoReflect() protoreflect.Message { - mi := &file_plugin_codecs_proto_msgTypes[20] + mi := &file_plugin_codecs_proto_msgTypes[21] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1463,7 +1536,7 @@ func (x *LLOOracleCodecSupportProto) ProtoReflect() protoreflect.Message { // Deprecated: Use LLOOracleCodecSupportProto.ProtoReflect.Descriptor instead. func (*LLOOracleCodecSupportProto) Descriptor() ([]byte, []int) { - return file_plugin_codecs_proto_rawDescGZIP(), []int{20} + return file_plugin_codecs_proto_rawDescGZIP(), []int{21} } func (x *LLOOracleCodecSupportProto) GetOracleID() uint32 { @@ -1572,16 +1645,23 @@ const file_plugin_codecs_proto_rawDesc = "" + "aggregator\x18\x03 \x01(\rR\n" + "aggregator\"j\n" + "\x14LLOChannelStateProto\x12R\n" + - "\x12channelDefinitions\x18\x01 \x03(\v2\".v1.LLOChannelIDAndDefinitionProtoR\x12channelDefinitions\"\xb9\x02\n" + + "\x12channelDefinitions\x18\x01 \x03(\v2\".v1.LLOChannelIDAndDefinitionProtoR\x12channelDefinitions\"\x87\x03\n" + "\x10LLOHotStateProto\x12H\n" + "\x1fobservationTimestampNanoseconds\x18\x01 \x01(\x04R\x1fobservationTimestampNanoseconds\x12c\n" + "\x15validAfterNanoseconds\x18\x02 \x03(\v2-.v1.LLOChannelIDAndValidAfterNanosecondsProtoR\x15validAfterNanoseconds\x122\n" + "\x14reportableChannelIDs\x18\x03 \x03(\rR\x14reportableChannelIDs\x12B\n" + - "\x10streamAggregates\x18\x04 \x03(\v2\x16.v1.LLOStreamAggregateR\x10streamAggregates\"\xe4\x03\n" + + "\x10streamAggregates\x18\x04 \x03(\v2\x16.v1.LLOStreamAggregateR\x10streamAggregates\x12L\n" + + "!recentAgreedTimestampsNanoseconds\x18\x05 \x03(\x04R!recentAgreedTimestampsNanoseconds\"\xe3\x01\n" + + "\x13LLOBlobPayloadProto\x12(\n" + + "\x0fcycleStartSeqNr\x18\x01 \x01(\x04R\x0fcycleStartSeqNr\x12M\n" + + "\fstreamValues\x18\x02 \x03(\v2).v1.LLOBlobPayloadProto.StreamValuesEntryR\fstreamValues\x1aS\n" + + "\x11StreamValuesEntry\x12\x10\n" + + "\x03key\x18\x01 \x01(\rR\x03key\x12(\n" + + "\x05value\x18\x02 \x01(\v2\x12.v1.LLOStreamValueR\x05value:\x028\x01\"\xb4\x03\n" + "\x11LLOPrecursorProto\x12&\n" + "\x0elifeCycleStage\x18\x01 \x01(\tR\x0elifeCycleStage\x12H\n" + - "\x1fobservationTimestampNanoseconds\x18\x02 \x01(\x04R\x1fobservationTimestampNanoseconds\x12R\n" + - "\x12channelDefinitions\x18\x03 \x03(\v2\".v1.LLOChannelIDAndDefinitionProtoR\x12channelDefinitions\x12c\n" + + "\x1fobservationTimestampNanoseconds\x18\x02 \x01(\x04R\x1fobservationTimestampNanoseconds\x12\"\n" + + "\fchannelState\x18\x03 \x01(\fR\fchannelState\x12c\n" + "\x15validAfterNanoseconds\x18\x04 \x03(\v2-.v1.LLOChannelIDAndValidAfterNanosecondsProtoR\x15validAfterNanoseconds\x12B\n" + "\x10streamAggregates\x18\x05 \x03(\v2\x16.v1.LLOStreamAggregateR\x10streamAggregates\x12,\n" + "\x11channelStateSeqNr\x18\x06 \x01(\x04R\x11channelStateSeqNr\x122\n" + @@ -1606,7 +1686,7 @@ func file_plugin_codecs_proto_rawDescGZIP() []byte { } var file_plugin_codecs_proto_enumTypes = make([]protoimpl.EnumInfo, 1) -var file_plugin_codecs_proto_msgTypes = make([]protoimpl.MessageInfo, 23) +var file_plugin_codecs_proto_msgTypes = make([]protoimpl.MessageInfo, 25) var file_plugin_codecs_proto_goTypes = []any{ (LLOStreamValue_Type)(0), // 0: v1.LLOStreamValue.Type (*LLOObservationProto)(nil), // 1: v1.LLOObservationProto @@ -1627,15 +1707,17 @@ var file_plugin_codecs_proto_goTypes = []any{ (*LLOStreamAggregate)(nil), // 16: v1.LLOStreamAggregate (*LLOChannelStateProto)(nil), // 17: v1.LLOChannelStateProto (*LLOHotStateProto)(nil), // 18: v1.LLOHotStateProto - (*LLOPrecursorProto)(nil), // 19: v1.LLOPrecursorProto - (*LLOCodecSupportProto)(nil), // 20: v1.LLOCodecSupportProto - (*LLOOracleCodecSupportProto)(nil), // 21: v1.LLOOracleCodecSupportProto - nil, // 22: v1.LLOObservationProto.UpdateChannelDefinitionsEntry - nil, // 23: v1.LLOObservationProto.StreamValuesEntry + (*LLOBlobPayloadProto)(nil), // 19: v1.LLOBlobPayloadProto + (*LLOPrecursorProto)(nil), // 20: v1.LLOPrecursorProto + (*LLOCodecSupportProto)(nil), // 21: v1.LLOCodecSupportProto + (*LLOOracleCodecSupportProto)(nil), // 22: v1.LLOOracleCodecSupportProto + nil, // 23: v1.LLOObservationProto.UpdateChannelDefinitionsEntry + nil, // 24: v1.LLOObservationProto.StreamValuesEntry + nil, // 25: v1.LLOBlobPayloadProto.StreamValuesEntry } var file_plugin_codecs_proto_depIdxs = []int32{ - 22, // 0: v1.LLOObservationProto.updateChannelDefinitions:type_name -> v1.LLOObservationProto.UpdateChannelDefinitionsEntry - 23, // 1: v1.LLOObservationProto.streamValues:type_name -> v1.LLOObservationProto.StreamValuesEntry + 23, // 0: v1.LLOObservationProto.updateChannelDefinitions:type_name -> v1.LLOObservationProto.UpdateChannelDefinitionsEntry + 24, // 1: v1.LLOObservationProto.streamValues:type_name -> v1.LLOObservationProto.StreamValuesEntry 0, // 2: v1.LLOStreamValue.type:type_name -> v1.LLOStreamValue.Type 2, // 3: v1.LLOTimestampedStreamValue.streamValue:type_name -> v1.LLOStreamValue 2, // 4: v1.LLOStreamHistoryRecord.value:type_name -> v1.LLOStreamValue @@ -1652,17 +1734,18 @@ var file_plugin_codecs_proto_depIdxs = []int32{ 13, // 15: v1.LLOChannelStateProto.channelDefinitions:type_name -> v1.LLOChannelIDAndDefinitionProto 15, // 16: v1.LLOHotStateProto.validAfterNanoseconds:type_name -> v1.LLOChannelIDAndValidAfterNanosecondsProto 16, // 17: v1.LLOHotStateProto.streamAggregates:type_name -> v1.LLOStreamAggregate - 13, // 18: v1.LLOPrecursorProto.channelDefinitions:type_name -> v1.LLOChannelIDAndDefinitionProto + 25, // 18: v1.LLOBlobPayloadProto.streamValues:type_name -> v1.LLOBlobPayloadProto.StreamValuesEntry 15, // 19: v1.LLOPrecursorProto.validAfterNanoseconds:type_name -> v1.LLOChannelIDAndValidAfterNanosecondsProto 16, // 20: v1.LLOPrecursorProto.streamAggregates:type_name -> v1.LLOStreamAggregate - 21, // 21: v1.LLOCodecSupportProto.oracles:type_name -> v1.LLOOracleCodecSupportProto + 22, // 21: v1.LLOCodecSupportProto.oracles:type_name -> v1.LLOOracleCodecSupportProto 8, // 22: v1.LLOObservationProto.UpdateChannelDefinitionsEntry.value:type_name -> v1.LLOChannelDefinitionProto 2, // 23: v1.LLOObservationProto.StreamValuesEntry.value:type_name -> v1.LLOStreamValue - 24, // [24:24] is the sub-list for method output_type - 24, // [24:24] is the sub-list for method input_type - 24, // [24:24] is the sub-list for extension type_name - 24, // [24:24] is the sub-list for extension extendee - 0, // [0:24] is the sub-list for field type_name + 2, // 24: v1.LLOBlobPayloadProto.StreamValuesEntry.value:type_name -> v1.LLOStreamValue + 25, // [25:25] is the sub-list for method output_type + 25, // [25:25] is the sub-list for method input_type + 25, // [25:25] is the sub-list for extension type_name + 25, // [25:25] is the sub-list for extension extendee + 0, // [0:25] is the sub-list for field type_name } func init() { file_plugin_codecs_proto_init() } @@ -1676,7 +1759,7 @@ func file_plugin_codecs_proto_init() { GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_plugin_codecs_proto_rawDesc), len(file_plugin_codecs_proto_rawDesc)), NumEnums: 1, - NumMessages: 23, + NumMessages: 25, NumExtensions: 0, NumServices: 0, }, diff --git a/llo/protocol/plugin_codecs.proto b/llo/protocol/plugin_codecs.proto index 3a9cfc39..1e26abff 100644 --- a/llo/protocol/plugin_codecs.proto +++ b/llo/protocol/plugin_codecs.proto @@ -205,6 +205,20 @@ message LLOHotStateProto { repeated LLOChannelIDAndValidAfterNanosecondsProto validAfterNanoseconds = 2; repeated uint32 reportableChannelIDs = 3; repeated LLOStreamAggregate streamAggregates = 4; + // Agreed observation timestamps of the most recent rounds, oldest first, + // the last one being the round that wrote this record. Bounded to the + // window LLO v31 needs to judge the age of blob-carried stream values + // against replicated time; see llo/dev/v31 agreedTimestampWindow. + repeated uint64 recentAgreedTimestampsNanoseconds = 5; +} + +// LLOBlobPayloadProto is the stream values blob a v31 observation references. +// cycleStartSeqNr is the sequence number the blob pump saw when the cycle that +// gathered these values started. The state transition measures the values' age +// from it against replicated data only, so the blob carries no clock reading. +message LLOBlobPayloadProto { + uint64 cycleStartSeqNr = 1; + map streamValues = 2; } // LLOPrecursorProto is the v31 ReportsPlusPrecursor: everything Reports needs, @@ -214,18 +228,23 @@ message LLOHotStateProto { // from, so that consumers can tell whether their decoded-opts cache already // matches these definitions. // +// channelState is that record as stored under c/defs, an encoded +// LLOChannelStateProto. It is carried as bytes so a consumer whose cache holds +// the generation for channelStateSeqNr skips decoding it, and one that does not +// decodes it exactly as the KeyValueState read does. +// // reportableChannelIDs is the reportability decision StateTransition made for // the round, so Reports emits exactly the channels whose watermark advances. // streamAggregates carries only the values those channels report. // // NOTE: must serialize deterministically, hence use of repeated tuple instead of -// maps. channelDefinitions, validAfterNanoseconds and reportableChannelIDs MUST -// be sorted ascending by channelID; streamAggregates MUST be sorted ascending by -// (streamID, aggregator). +// maps. validAfterNanoseconds and reportableChannelIDs MUST be sorted ascending +// by channelID; streamAggregates MUST be sorted ascending by (streamID, +// aggregator). message LLOPrecursorProto { string lifeCycleStage = 1; uint64 observationTimestampNanoseconds = 2; - repeated LLOChannelIDAndDefinitionProto channelDefinitions = 3; + bytes channelState = 3; repeated LLOChannelIDAndValidAfterNanosecondsProto validAfterNanoseconds = 4; repeated LLOStreamAggregate streamAggregates = 5; uint64 channelStateSeqNr = 6;