shard

package
v0.13.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 23, 2026 License: Apache-2.0 Imports: 16 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package shard encodes per-component result rows into gzipped NDJSON shards sized to fit inside a ConfigMap (ADR-090).

It is deliberately free of any Kubernetes client dependency. The controller writes shards and nvcrectl reads them, so the schema and the encoding live where both can reach them, the same split pkg/noderesults already uses for the node-result ConfigMaps.

Index

Constants

View Source
const (
	// RollBytes is the compressed-output size at which the writer starts a new
	// shard. ADR-090 fixes it at 768 KiB.
	//
	// The bound is checked after a row is written, not before, so a shard can
	// exceed it by one row. That overshoot is what MaxRowRawBytes bounds, and
	// the two together are what keep a shard under MaxConfigMapBytes.
	RollBytes = 768 * 1024

	// MaxRowRawBytes is the largest encoded row the writer will accept.
	//
	// ADR-090 states 256 KiB of *compressed* output. Two changes here, both
	// deliberate deviations, both recorded in ADR-090's Amendments section.
	//
	// First the figure. 768 KiB of roll plus a 256 KiB row is exactly 1 MiB,
	// which is the whole object budget, leaving nothing for the plaintext data
	// block or for the output gzip has buffered but not yet emitted when the
	// roll is checked. 128 KiB leaves 128 KiB of headroom.
	//
	// Second the unit. A row's compressed contribution inside a shared stream
	// is not well defined, because it depends on everything written before it,
	// and compressing each row alone to find out doubles the CPU. Raw bytes
	// bound it from above instead: gzip's worst case expansion is about 0.03%
	// plus a fixed header, so a row under this raw bound cannot exceed it by
	// more than a rounding error once compressed. The ADR's objection to row
	// bounds is about the aggregate roll bound, where the 2.8x to 34x ratio
	// spread really does make a raw figure meaningless; a per-row backstop
	// only has to be conservative in one direction.
	MaxRowRawBytes = 128 * 1024

	// MaxTotalRawBytes bounds the encoded rows one Job may hold in memory.
	//
	// ADR-090 calls for spooling to a temporary file and sorting there. The
	// controller has no writable path to spool to: it runs with
	// readOnlyRootFilesystem true and no volumes at all, so os.CreateTemp
	// fails with EROFS. Rows are therefore sorted in memory under this budget,
	// and a producer that exceeds it stops and records a RowBudgetExceeded
	// truncation rather than growing without bound.
	//
	// The figure is sized against the PROCESS, not the Job, and that
	// distinction cost a measured defect. This counts only the encoded lines,
	// while a Builder also retains b.rows with its own copy of every string:
	// measured retention is 2.0x what the budget counts. And the budget is
	// per-Builder while the limit is shared — MaxConcurrentReconciles defaults
	// to 10, so ten Builders can be live at once. At 64 MiB that measured
	// 2,222 MiB of peak heap against the manager's 1Gi limit, 217% of it: the
	// guard that exists to contain a runaway producer was itself the OOM.
	//
	// 16 MiB holds the real producer with room to spare — a per-GPU GEMM burn
	// in at one node per Job is 14,400 rows for a 30 minute soak and 57,600
	// for two hours, 14.3 MB of encoded lines — and puts the ten-worker
	// default at roughly 320 MiB live.
	//
	// The consequence is owned rather than hidden: ADR-090's own largest
	// corpus, 480,000 rows from a per-link NCCL producer, does not fit and is
	// truncated with a RowBudgetExceeded record. That producer does not exist
	// yet, and ADR-090's Amendments section records the limit and its
	// consequence for that corpus.
	MaxTotalRawBytes = 16 * 1024 * 1024

	// MaxConfigMapBytes is the API server's per-object limit. ValidateConfigMap
	// sums len(value) across Data and BinaryData and rejects the object past
	// this. It counts decoded bytes, so base64 inflation on the wire costs
	// request body, not budget.
	MaxConfigMapBytes = 1024 * 1024

	// MaxShardsPerJob bounds one Job's shard set, so the %04d name suffix
	// cannot overflow and a runaway producer cannot create objects without
	// limit.
	MaxShardsPerJob = 9999
)
View Source
const (
	// ReasonRowTooLarge is a single row whose encoded form exceeds
	// MaxRowRawBytes. It cannot be written to an empty shard either, so
	// retrying it would hold the Workflow open forever.
	ReasonRowTooLarge = "RowTooLarge"
	// ReasonRowBudgetExceeded is a producer that emitted more than
	// MaxTotalRawBytes of rows.
	ReasonRowBudgetExceeded = "RowBudgetExceeded"
	// ReasonShardLimitExceeded is a row set that would need more than
	// MaxShardsPerJob shards.
	ReasonShardLimitExceeded = "ShardLimitExceeded"
	// ReasonRowUnencodable is a row carrying a value JSON cannot represent,
	// which in practice means NaN or an infinity.
	ReasonRowUnencodable = "RowUnencodable"
)

Truncation reasons.

The ComponentTruncation CRD enum in api/v1alpha1 is a SUPERSET of these: it also carries the reasons the controller raises rather than the encoder (LogUnpageable, ShardWritePartial, ProducerUnavailable, SealTimedOut). These four must stay a subset of it, or a seal carrying one is refused by the API server. Nothing checks the containment in either direction.

View Source
const (
	// FormatVersion is the shard payload's schema version. A reader that does
	// not recognise it refuses the shard rather than guessing.
	FormatVersion = 1

	// RowsKey is the binaryData key holding gzipped NDJSON rows, following the
	// naming of pkg/noderesults' succeeded-nodes.csv.gz.
	RowsKey = "rows.ndjson.gz"

	// TruncationKey is the binaryData key holding gzipped NDJSON records of
	// rows that could not be stored. It lives on its own ConfigMap, outside
	// the shard set, so the sealed shard count stays a clean equality.
	TruncationKey = "truncation.ndjson.gz"

	// Plaintext data keys. These sit in Data rather than BinaryData so a
	// reader, or a human with kubectl, can check a shard without decompressing
	// it. They count against the same per-object budget, which dataBlockReserve
	// holds back.
	FormatVersionKey = "formatVersion"
	ShardIndexKey    = "shardIndex"
	RowCountKey      = "rowCount"
	DigestKey        = "sha256"
)

Variables

View Source
var ErrNoRows = errors.New("configmap carries no rows payload")

ErrNoRows reports a ConfigMap carrying no rows payload at all, which is different from a payload that failed to decode. Distinguishing them is the point: FailedNodesFromRef returns nil for both, so an unreadable ConfigMap is indistinguishable from nothing to report, and ADR-090 states that conflation is not acceptable on the primary evidence path.

Functions

func EncodeTruncation

func EncodeTruncation(dropped []Dropped) ([]byte, error)

EncodeTruncation compresses dropped-row records for the truncation ConfigMap. It returns nil when there is nothing to record, so a caller can skip creating the object entirely.

The result is asserted against the object budget. This was the one path into a ConfigMap with no bound on it: the ledger grows with the size of a producer's overrun, and a large enough one produced an object the API server refuses, so the record of what was lost became the thing that was lost. The Builder now bounds both the record count and the strings inside each record, which makes this assertion unreachable; it is kept because an unwritable truncation object is a silent failure and a returned error is not.

Types

type Builder

type Builder struct {
	// contains filtered or unexported fields
}

Builder accumulates a Job's rows and encodes them into shards.

It is not safe for concurrent use; one Builder belongs to one Job attempt.

func NewBuilder

func NewBuilder(opts Options) (*Builder, error)

NewBuilder returns a Builder using opts, with the ADR defaults for any field opts leaves at zero.

It returns an error for options that cannot produce a writable shard. The roll bound, the flush cadence and the row cap together decide the largest shard the writer can emit, and only the first and last are settable, so a caller raising the row cap alone silently invalidates the arithmetic that keeps a shard inside the object budget. Catching it here beats catching it after a Job's rows have been gathered, where the only remaining answer is to fail a result set that was collected correctly.

func (*Builder) Add

func (b *Builder) Add(r Row) error

Add encodes a row and holds it for Build.

Every row that cannot be stored is dropped and recorded rather than returned as an error, because an error here fails the Job's whole result set. That covers size, budget, and values JSON cannot represent.

The last of those is not hypothetical. A harness that divides a work total by an elapsed time produces NaN when a device reports no elapsed time, and an infinity when it reports zero. JSON has no literal for either, so the encoder rejects the row. Letting that surface as an error would mean one device's arithmetic sinks every other device's results and the Job requeues on a row that can never be written.

An error from Add therefore means the encoder failed on something other than the value, which is a bug rather than data.

func (*Builder) Build

func (b *Builder) Build() (Result, error)

Build sorts the accumulated rows into the normative emission order and encodes them into shards.

The output is a pure function of the rows added: the sort key is total, the gzip level is fixed, and the gzip header carries no timestamp. Re-running Build on the same rows produces byte-identical shards, which is what lets a failed write be retried by rewriting the same object, and what lets the bundle manifest's per-file sha256 mean anything.

type Dropped

type Dropped struct {
	Node        string `json:"node"`
	ComponentID string `json:"componentID"`
	Index       int32  `json:"index"`
	Name        string `json:"name"`
	Sample      int64  `json:"sample"`
	Reason      string `json:"reason"`
	RawBytes    int    `json:"rawBytes"`
	// Count is how many rows this component lost for this reason. The ledger
	// holds one record per component rather than one per row, so that a
	// bounded ledger still names every affected component; Count carries the
	// magnitude that collapsing them would otherwise lose. Name and Sample are
	// the first lost row's, as an example rather than an enumeration.
	Count int64 `json:"count"`
	// Message is free text explaining a loss the record cannot express on its
	// own. The encoder's own drops leave it empty: the reason and the row
	// identity say everything about them. It is here for the records the
	// controller appends, where the reason alone does not tell a bundle reader
	// why a read came back short, and the bundle is the only thing that leaves
	// the cluster.
	Message string `json:"message,omitempty"`
}

Dropped records one row that could not be stored, with enough of the row's identity to say which component lost evidence.

func DecodeTruncation

func DecodeTruncation(b []byte) ([]Dropped, error)

DecodeTruncation reads dropped-row records written by EncodeTruncation.

type Options

type Options struct {
	// RollBytes overrides RollBytes.
	RollBytes int
	// MaxRowRawBytes overrides MaxRowRawBytes.
	MaxRowRawBytes int
	// MaxTotalRawBytes overrides MaxTotalRawBytes.
	MaxTotalRawBytes int
	// MaxShardsPerJob overrides MaxShardsPerJob. Settable mainly so the limit
	// can be reached in a test without encoding ten thousand shards; a branch
	// that cannot be exercised is a branch nothing defends.
	MaxShardsPerJob int
}

Options tunes a Builder. The zero value means "use the ADR defaults", so callers that do not care can pass Options{}.

type Result

type Result struct {
	// Shards are in emission order; Shards[i].Index == i.
	Shards []Shard
	// Rows is the number of rows actually stored, across every shard.
	Rows int64
	// Dropped names rows that could not be stored, up to maxDroppedRecords of
	// them. Never collapsed to a count alone: a run that lost evidence has to
	// be able to say whose.
	Dropped []Dropped
	// DroppedTotal is how many rows were dropped in all, including any beyond
	// the ledger's bound. It is the exact figure; len(Dropped) is the named
	// subset. Keeping both means a bounded ledger never makes the loss look
	// smaller than it was.
	DroppedTotal int64
}

Result is everything one Job's rows produced.

type Row

type Row struct {
	// Node is the Kubernetes node name the component sits in.
	Node string `json:"node"`
	// ComponentID identifies the component within the node. For a GPU it is
	// the UUID, which is stable across reboots and renumbering.
	ComponentID string `json:"componentID"`
	// Index is the component's device index within the node. It addresses a
	// row to a component and is NOT a sample counter; see Sample (ADR-091).
	Index int32 `json:"index"`
	// Name is the metric name.
	Name string `json:"name"`
	// Value is the measurement, carried to valuePrecision decimal places.
	Value float64 `json:"value"`
	// Unit is the measurement's unit.
	Unit string `json:"unit"`
	// Sample is a monotonic ordinal starting at zero, scoped to one Job
	// attempt. Every component on the node shares the ordinal for a given
	// sweep, which is what makes "component 3 fell behind at sample 900 while
	// the others held" answerable from the rows (ADR-091).
	Sample int64 `json:"sample"`
	// Timestamp is the wall clock time of the sample, RFC 3339.
	Timestamp string `json:"timestamp"`
	// Outcome is the producer's verdict for this row.
	Outcome string `json:"outcome"`
}

Row is one measurement of one metric on one component at one sample.

Field order is the wire order and is load bearing: encoding/json emits struct fields in declaration order, and the bundle manifest's sha256 is taken over the bytes this produces.

func DecodeNDJSON

func DecodeNDJSON(b []byte) ([]Row, error)

DecodeNDJSON parses newline-delimited rows.

func DecodeRows

func DecodeRows(cm *corev1.ConfigMap) ([]Row, error)

DecodeRows reads the rows out of a shard ConfigMap.

It verifies the payload against the digest the writer recorded, so a shard edited in the cluster is caught here rather than being carried into a bundle and certified by its manifest.

func (Row) MarshalJSON

func (r Row) MarshalJSON() ([]byte, error)

MarshalJSON encodes the row with a fixed-precision value.

func (*Row) UnmarshalJSON

func (r *Row) UnmarshalJSON(b []byte) error

UnmarshalJSON decodes a row written by MarshalJSON. The alias avoids recursing back into Row's own marshaller.

type Shard

type Shard struct {
	// Index is the shard's position in the Job's set, from zero.
	Index int
	// Payload is the gzipped NDJSON for binaryData.
	Payload []byte
	// Rows is how many rows Payload holds.
	Rows int64
	// SHA256 is the hex digest of Payload. It is carried in the shard's
	// plaintext data block so a reader can tell a shard mutated in the cluster
	// from one mutated on disk after the bundle was written.
	SHA256 string
}

Shard is one ConfigMap's worth of compressed rows.

func (Shard) BinaryData

func (s Shard) BinaryData() map[string][]byte

BinaryData returns the binaryData block for a shard.

func (Shard) Data

func (s Shard) Data() map[string]string

Data returns the plaintext data block for a shard.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL