diff --git a/.env.example b/.env.example index ab31ea15..a9a38f25 100644 --- a/.env.example +++ b/.env.example @@ -121,6 +121,11 @@ # Default: 50000 # PITOT_INGEST_BATCH_SIZE= +# PITOT_INGEST_MAX_FUTURE_SKEW; duration +# Sets how far client timestamps may lead the server clock. Zero disables clock-skew checks. Timestamps must still fit in finite signed nanoseconds. +# Default: 5m +# PITOT_INGEST_MAX_FUTURE_SKEW= + # PITOT_INGEST_MAX_IN_FLIGHT_BYTES; integer # Caps decoded telemetry held across concurrent requests until durable publication. Zero is unbounded. A single request is admitted when no other request holds budget, even if it exceeds the limit. # Default: 268435456 diff --git a/docs/operations.md b/docs/operations.md index fd99824d..9401c1d7 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -148,6 +148,25 @@ derive `/v1/traces`, `/v1/metrics`, and `/v1/logs` from the general endpoint. Signal-specific endpoint variables require the full path. OTLP/gRPC uses the same address and authorization value, over HTTP/2. +## Rejected telemetry timestamps + +Pitot checks client timestamps against its clock when it receives an export. +The default future tolerance is five minutes. Set +`PITOT_INGEST_MAX_FUTURE_SKEW` to change it or to `0` to disable it. +`PITOT_RETENTION_DAYS` sets the oldest accepted event time. Zero disables expiry. +Timestamps at or above 9223372036854775807 Unix nanoseconds always exceed the +finite storage range. With skew checks disabled, a finite timestamp can still +be too close to the limit for rollup arithmetic. For example, the minute +containing the largest finite timestamp in April 2262 has no representable +end, and can stall rollup processing. + +A Collector can send data from several hosts in one export. Pitot commits the +valid rows and returns OTLP `PartialSuccess` with the number of rejected spans, +log records, or metric data points, including when it rejects every row. Both +HTTP 200 and gRPC OK acknowledge this outcome. Retrying the export can duplicate +accepted rows. Monitor `pitot_ingest_rejected_rows_total{signal,reason}` and +check source clocks for `future` or delayed delivery for `expired`. + ## Mobile boundary Pitot remains a backend receiver, not a public mobile collector. The supported diff --git a/docs/proposals/0014-ingest-timestamp-bounds.md b/docs/proposals/0014-ingest-timestamp-bounds.md new file mode 100644 index 00000000..5c010024 --- /dev/null +++ b/docs/proposals/0014-ingest-timestamp-bounds.md @@ -0,0 +1,52 @@ +# Bounds for OTLP client timestamps + +Status: Implemented +Date: 2026-12-01 +Pull request: [#525](https://github.com/labstack/pitot/pull/525) + +## Summary + +Use OTLP partial success to keep healthy rows when one sender supplies an +out-of-range timestamp. + +## Motivation + +One device with a fast clock can advance the latest service rollup bucket by +years. Alerts then look for every service in that future window, and ordinary +retention leaves the bucket in place. A Collector often sends several devices' +data in one request. [Issue #216](https://github.com/labstack/pitot/issues/216) + +## Goals and non-goals + +Keep late telemetry within retention queryable, keep alert evaluation usable +after an upgrade, and give Collector operators a count of discarded items. +Client clock synchronization remains the sender’s responsibility. + +## Design + +Check timestamps once per item against the receipt time of its export. Accept +event times from the retention cutoff through five minutes ahead, inclusive. +An operator can configure the future tolerance independently of retention. +Zero denotes a missing timestamp. Always require timestamps to fit in finite +signed nanoseconds, including timestamps on nested events and exemplars. +Apply the retention cutoff only to the event time so a cumulative metric can +keep its original start. + +Drop the containing span, log record, or metric point when a timestamp fails. +Acknowledge the export with OTLP partial success after its accepted rows are +durable. Include the rejection count and expose counts by signal and reason. +Anchor both alert windows to the latest nonfuture bucket and remove existing +rollup buckets beyond the configured tolerance during maintenance. + +## Alternatives + +Rejecting the whole export loses healthy devices' telemetry alongside the bad +rows. Moving an out-of-range timestamp to receipt time would create artificial +traffic and error spikes. + +## Risks + +Rejected data is lost. Operators who need a longer backfill window can adjust +retention before sending the export. Disabling the future tolerance exposes +rollups to dates near the end of the signed-nanosecond range, where adding a rollup interval can overflow. Edge rollups, for example, +look ahead by up to one hour. diff --git a/docs/proposals/README.md b/docs/proposals/README.md index e8dfe27c..3698190e 100644 --- a/docs/proposals/README.md +++ b/docs/proposals/README.md @@ -45,5 +45,6 @@ Earlier proposals predate the template and keep their original structure. | 0011 | [One cost-aware admission layer at the engine boundary](0011-engine-admission-classes.md) | Draft | | 0012 | [Bounded trace ranking for drill-down](0012-bounded-trace-ranking.md) | Implemented | | 0013 | [Indexed trace logs](0013-log-trace-lookup.md) | Implemented | +| 0014 | [Bounds for OTLP client timestamps](0014-ingest-timestamp-bounds.md) | Implemented | Settled decisions that a proposal leads to are recorded in [../adr](../adr/README.md). diff --git a/internal/alert/engine.go b/internal/alert/engine.go index 548f4dfc..cc2a946a 100644 --- a/internal/alert/engine.go +++ b/internal/alert/engine.go @@ -514,14 +514,18 @@ func (e *Engine) buildEnvs(ctx context.Context) map[string]Env { } const envSQL = ` -WITH current AS ( +WITH latest AS ( + SELECT max(bucket) AS bucket FROM service_rollup WHERE bucket <= now()::TIMESTAMP_NS +), +current AS ( SELECT service, avg(error_rate) as error_rate, COALESCE(avg(p50_ms) FILTER (WHERE served_spans > 0), avg(p50_ms)) as p50, COALESCE(avg(p95_ms) FILTER (WHERE served_spans > 0), avg(p95_ms)) as p95, sum(spans)::DOUBLE as throughput, sum(log_count)::DOUBLE as log_count FROM service_rollup - WHERE bucket >= (SELECT max(bucket) FROM service_rollup) - INTERVAL '5 minutes' + WHERE bucket >= (SELECT bucket FROM latest) - INTERVAL '5 minutes' + AND bucket <= now()::TIMESTAMP_NS GROUP BY service ), previous AS ( @@ -530,8 +534,8 @@ previous AS ( COALESCE(avg(p95_ms) FILTER (WHERE served_spans > 0), avg(p95_ms)) as p95, sum(spans)::DOUBLE as throughput FROM service_rollup - WHERE bucket >= (SELECT max(bucket) FROM service_rollup) - INTERVAL '10 minutes' - AND bucket < (SELECT max(bucket) FROM service_rollup) - INTERVAL '5 minutes' + WHERE bucket >= (SELECT bucket FROM latest) - INTERVAL '10 minutes' + AND bucket < (SELECT bucket FROM latest) - INTERVAL '5 minutes' GROUP BY service ) SELECT c.service, coalesce(c.error_rate, 0), coalesce(c.p50, 0), coalesce(c.p95, 0), diff --git a/internal/alert/engine_env_test.go b/internal/alert/engine_env_test.go index acd87c61..0fbaa0cf 100644 --- a/internal/alert/engine_env_test.go +++ b/internal/alert/engine_env_test.go @@ -17,12 +17,16 @@ import ( // throughput/log_count read 0 while the DOUBLE fields (error_rate, p50, p95, // deltas) stay populated. Seen live 2026-07-03: Throughput=0 with ThroughputDelta=7.65 // for a service pushing ~600 spans/min, making throughput rules unusable. -func TestBuildEnvs_IntegerSumsSurviveHugeint(t *testing.T) { +func TestBuildEnvsUsesLatestNonfutureBucketForTotalsAndDeltas(t *testing.T) { db, err := sql.Open("duckdb", "") if err != nil { t.Fatalf("open duckdb: %v", err) } t.Cleanup(func() { _ = db.Close() }) + db.SetMaxOpenConns(1) + if _, err := db.Exec("SET TimeZone='UTC'"); err != nil { + t.Fatal(err) + } if _, err := db.Exec(` CREATE TABLE service_rollup ( @@ -35,7 +39,10 @@ CREATE TABLE service_rollup ( if _, err := db.Exec(` INSERT INTO service_rollup VALUES ('', now(), 'svc-a', 100, 100, 0.0, 10.0, 20.0, 5, 0), - ('', now() - INTERVAL 1 MINUTE, 'svc-a', 100, 100, 0.0, 10.0, 20.0, 5, 0)`); err != nil { + ('', now() - INTERVAL 1 MINUTE, 'svc-a', 100, 100, 0.0, 10.0, 20.0, 5, 0), + ('', now() - INTERVAL 8 MINUTE, 'svc-a', 50, 50, 0.0, 10.0, 20.0, 5, 0), + ('', now() + INTERVAL 4 MINUTE, 'svc-a', 999, 0, 0.0, 0.0, 0.0, 0, 0), + ('', now() + INTERVAL 10 YEAR, 'future-only', 1, 0, 0.0, 0.0, 0.0, 0, 0)`); err != nil { t.Fatalf("seed service_rollup: %v", err) } @@ -46,6 +53,12 @@ INSERT INTO service_rollup VALUES t.Fatalf("buildEnvs returned no env for svc-a: %#v", envs) } + if _, ok := envs["future-only"]; ok { + t.Error("future-only service appeared in alert environment") + } + if env.ThroughputDelta != 300 { + t.Errorf("ThroughputDelta = %v, want 300%% (50 to 200 spans)", env.ThroughputDelta) + } if env.Throughput != 200 { t.Errorf("Throughput = %v, want 200 (sum(spans) is HUGEINT — lost in conversion?)", env.Throughput) } diff --git a/internal/config/config.go b/internal/config/config.go index 0cb4dc96..7af3593a 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -3,6 +3,7 @@ package config import ( "fmt" "log/slog" + "math" "net" "net/url" "path/filepath" @@ -59,6 +60,9 @@ type Config struct { // IngestBatchSize sets the group-commit row target; valid values are 1–50000. // Individual requests remain atomic and can exceed this target. IngestBatchSize int `group:"ingest" env:"PITOT_INGEST_BATCH_SIZE" default:"50000"` + // IngestMaxFutureSkew sets how far client timestamps may lead the server clock. + // Zero disables clock-skew checks. Timestamps must still fit in finite signed nanoseconds. + IngestMaxFutureSkew time.Duration `group:"ingest" env:"PITOT_INGEST_MAX_FUTURE_SKEW" default:"5m"` // IngestMaxInFlightBytes caps decoded telemetry held across concurrent requests // until durable publication. Zero is unbounded. A single request is admitted // when no other request holds budget, even if it exceeds the limit. @@ -304,6 +308,43 @@ func nameListed(raw string) bool { return len(strings.FieldsFunc(raw, func(r rune) bool { return r == ',' || unicode.IsSpace(r) })) != 0 } +var ( + firstFiniteTimestamp = time.Unix(0, math.MinInt64+2).UTC() + lastFiniteTimestamp = time.Unix(0, math.MaxInt64-1).UTC() +) + +// RetentionCutoff returns the oldest retained Unix nanosecond, when the cutoff +// falls within the finite timestamp range. Do the day arithmetic in seconds: +// a valid retention period can exceed the range of a time.Duration. +func (c Config) RetentionCutoff(now time.Time) (int64, bool) { + const secondsPerDay = 24 * 60 * 60 + days := int64(c.RetentionDays) + if days <= 0 || days > (now.Unix()-firstFiniteTimestamp.Unix())/secondsPerDay { + return 0, false + } + cutoff := time.Unix(now.Unix()-days*secondsPerDay, int64(now.Nanosecond())) + if cutoff.Before(firstFiniteTimestamp) || cutoff.After(lastFiniteTimestamp) { + return 0, false + } + return cutoff.UnixNano(), true +} + +// LatestEventTime returns the inclusive upper bound used by ingest and rollup pruning. +// DuckDB reserves MaxInt64 for infinity, even when the clock-skew check is disabled. +func (c Config) LatestEventTime(now time.Time) time.Time { + if c.IngestMaxFutureSkew <= 0 { + return lastFiniteTimestamp + } + candidate := now.Add(c.IngestMaxFutureSkew).UTC() + if candidate.Before(firstFiniteTimestamp) { + return firstFiniteTimestamp + } + if candidate.After(lastFiniteTimestamp) { + return lastFiniteTimestamp + } + return candidate +} + func (c Config) TelemetryDir() string { return filepath.Join(c.DataDir, "telemetry") } @@ -356,6 +397,9 @@ func (c Config) Validate() error { if c.IngestBatchSize <= 0 || c.IngestBatchSize > maxIngestBatchSize { return fmt.Errorf("PITOT_INGEST_BATCH_SIZE must be between 1 and %d, got %d", maxIngestBatchSize, c.IngestBatchSize) } + if c.IngestMaxFutureSkew < 0 { + return fmt.Errorf("PITOT_INGEST_MAX_FUTURE_SKEW must be >= 0, got %s", c.IngestMaxFutureSkew) + } if c.IngestToken != "" && !secret.ValidSecret(c.IngestToken, "foi_") { return fmt.Errorf("PITOT_INGEST_TOKEN must be foi_ followed by 43 base64url characters") } diff --git a/internal/config/config_test.go b/internal/config/config_test.go index a9895a5e..cd3a9e99 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -3,6 +3,7 @@ package config import ( "bytes" "log/slog" + "math" "os" "path/filepath" "reflect" @@ -29,7 +30,7 @@ func TestLoadReturnsDefaults(t *testing.T) { if err != nil { t.Fatal(err) } - if cfg.Addr != "127.0.0.1:7520" || cfg.DataDir != "./data" || cfg.IngestBatchSize != 50000 || cfg.RollupInterval != time.Minute || cfg.RetentionDays != 30 || cfg.DefaultNamespace != "default" || !cfg.MCPEnabled || !cfg.AlertEnabled || cfg.AIProvider != "" { + if cfg.Addr != "127.0.0.1:7520" || cfg.DataDir != "./data" || cfg.IngestBatchSize != 50000 || cfg.IngestMaxFutureSkew != 5*time.Minute || cfg.RollupInterval != time.Minute || cfg.RetentionDays != 30 || cfg.DefaultNamespace != "default" || !cfg.MCPEnabled || !cfg.AlertEnabled || cfg.AIProvider != "" { t.Fatal("built-in defaults were not resolved") } if cfg.DuckDBThreads != runtime.GOMAXPROCS(0) || cfg.DuckDBMaxConns < minDuckDBConns || cfg.DuckDBMaxConns > maxAutoDuckDBConns { @@ -40,13 +41,13 @@ func TestLoadReturnsDefaults(t *testing.T) { func TestLoadTypedEnvironmentValues(t *testing.T) { cfg, err := Load(LoadOptions{Environ: append(validEnvironment(), "PITOT_ADDR=:9000", "PITOT_MCP_ENABLED=false", "PITOT_METRICS_PUBLIC=true", - "PITOT_SESSION_IDLE_TTL=10h", "PITOT_SELF_SIGNUP=true", "PITOT_RETENTION_DAYS=0", + "PITOT_SESSION_IDLE_TTL=10h", "PITOT_SELF_SIGNUP=true", "PITOT_RETENTION_DAYS=0", "PITOT_INGEST_MAX_FUTURE_SKEW=0", "PITOT_ROLLUP_INTERVAL=5m", "PITOT_MAINTENANCE_INTERVAL=2h", "PITOT_ALERTS_EVALUATION_INTERVAL=45s", )}) if err != nil { t.Fatal(err) } - if cfg.Addr != ":9000" || cfg.MCPEnabled || !cfg.MetricsPublic || cfg.SessionIdleTTL != 10*time.Hour || !cfg.SelfSignup || cfg.RetentionDays != 0 || cfg.RollupInterval != 5*time.Minute || cfg.MaintenanceInterval != 2*time.Hour || cfg.AlertEvaluationInterval != 45*time.Second { + if cfg.Addr != ":9000" || cfg.MCPEnabled || !cfg.MetricsPublic || cfg.SessionIdleTTL != 10*time.Hour || !cfg.SelfSignup || cfg.IngestMaxFutureSkew != 0 || cfg.RetentionDays != 0 || cfg.RollupInterval != 5*time.Minute || cfg.MaintenanceInterval != 2*time.Hour || cfg.AlertEvaluationInterval != 45*time.Second { t.Fatal("environment values were not decoded") } } @@ -61,6 +62,33 @@ func TestLoadTreatsEmptyEnvironmentValuesAsAbsent(t *testing.T) { } } +func TestIngestTimeBoundsStayWithinFiniteNanoseconds(t *testing.T) { + cfg := Config{RetentionDays: 1, IngestMaxFutureSkew: 5 * time.Minute} + first, last := time.Unix(0, math.MinInt64+2), time.Unix(0, math.MaxInt64-1) + if got := cfg.LatestEventTime(time.Time{}); !got.Equal(first) { + t.Errorf("future bound from year 1 = %v, want %v", got, first) + } + if got := cfg.LatestEventTime(last); !got.Equal(last) { + t.Errorf("future bound from last finite timestamp = %v, want %v", got, last) + } + for _, tc := range []struct { + cutoff time.Time + want int64 + ok bool + }{ + {first.Add(-time.Nanosecond), 0, false}, + {first, math.MinInt64 + 2, true}, + {last, math.MaxInt64 - 1, true}, + {last.Add(time.Nanosecond), 0, false}, + {time.Date(2400, 1, 1, 0, 0, 0, 0, time.UTC), 0, false}, + } { + got, ok := cfg.RetentionCutoff(tc.cutoff.Add(24 * time.Hour)) + if got != tc.want || ok != tc.ok { + t.Errorf("retention cutoff %v = (%d, %t), want (%d, %t)", tc.cutoff, got, ok, tc.want, tc.ok) + } + } +} + func TestConfigurationSchemaUsesUnitBearingDurations(t *testing.T) { specs, err := configFieldSpecs() if err != nil { @@ -70,8 +98,8 @@ func TestConfigurationSchemaUsesUnitBearingDurations(t *testing.T) { if strings.HasSuffix(spec.env, "_SECONDS") || strings.HasSuffix(spec.env, "_MS") { t.Errorf("unit suffix in %s", spec.env) } - if spec.typ == reflect.TypeOf(time.Duration(0)) && !strings.HasSuffix(spec.env, "_INTERVAL") && !strings.HasSuffix(spec.env, "_TTL") { - t.Errorf("duration name %s must end in _INTERVAL or _TTL", spec.env) + if spec.typ == reflect.TypeOf(time.Duration(0)) && !strings.HasSuffix(spec.env, "_INTERVAL") && !strings.HasSuffix(spec.env, "_TTL") && !strings.HasSuffix(spec.env, "_SKEW") { + t.Errorf("duration name %s must end in _INTERVAL, _TTL or _SKEW", spec.env) } } } @@ -257,6 +285,7 @@ func TestValidate(t *testing.T) { {"IngestBatchSize=50001", func(c *Config) { c.IngestBatchSize = 50001 }}, {"RollupInterval=0", func(c *Config) { c.RollupInterval = 0 }}, {"RollupInterval=999ms", func(c *Config) { c.RollupInterval = 999 * time.Millisecond }}, + {"IngestMaxFutureSkew=-1", func(c *Config) { c.IngestMaxFutureSkew = -time.Nanosecond }}, {"RetentionDays=-1", func(c *Config) { c.RetentionDays = -1 }}, {"Addr empty", func(c *Config) { c.Addr = "" }}, {"DataDir empty", func(c *Config) { c.DataDir = "" }}, diff --git a/internal/engine/duck.go b/internal/engine/duck.go index e547cb9e..46f9d3b8 100644 --- a/internal/engine/duck.go +++ b/internal/engine/duck.go @@ -1036,8 +1036,8 @@ func (d *Duck) runRepositoryMaintenance(ctx context.Context) error { compactStart := time.Now() var parquetErr error cleanupErr := d.repository.CleanupParquet() - if d.cfg.RetentionDays > 0 { - _, parquetErr = d.repository.PruneParquetPass(ctx, d, time.Now().Add(-time.Duration(d.cfg.RetentionDays)*24*time.Hour).UnixNano(), parquetMaintenanceBatchLimit, parquetMaintenancePhaseBudget) + if cutoff, ok := d.cfg.RetentionCutoff(time.Now()); ok { + _, parquetErr = d.repository.PruneParquetPass(ctx, d, cutoff, parquetMaintenanceBatchLimit, parquetMaintenancePhaseBudget) } compacted, compactErr := d.repository.CompactParquetPass(ctx, d, parquetMaintenanceBatchLimit, parquetMaintenancePhaseBudget) compactResult := metrics.TelemetryNoop @@ -1086,11 +1086,12 @@ func (d *Duck) runRepositoryMaintenance(ctx context.Context) error { return err } -// pruneRollupCache deletes retention-expired rows from the rollup-cache tables +// pruneRollupCache deletes expired and implausibly future-dated rollup buckets // under both write gates and the background slot. It is a no-op taking no gate -// when retention is disabled. +// when neither bound applies. func (d *Duck) pruneRollupCache(ctx context.Context) error { - if d.cfg.RetentionDays <= 0 { + cutoff, pruneExpired := d.cfg.RetentionCutoff(time.Now()) + if !pruneExpired && d.cfg.IngestMaxFutureSkew <= 0 { return nil } unlock, err := d.writeGate.LockContext(ctx, writegate.Maintenance) @@ -1108,9 +1109,20 @@ func (d *Duck) pruneRollupCache(ctx context.Context) error { return err } defer background() + var predicates []string + var args []any + if pruneExpired { + predicates = append(predicates, "bucket < make_timestamp_ns(?)") + args = append(args, cutoff) + } + if d.cfg.IngestMaxFutureSkew > 0 { + predicates = append(predicates, "bucket > make_timestamp_ns(?)") + args = append(args, d.cfg.LatestEventTime(time.Now()).UnixNano()) + } + where := strings.Join(predicates, " OR ") var errs []error for _, table := range []string{"service_rollup", "span_rollup", "log_rollup", "endpoint_rollup", "receiver_rollup", "resource_rollup", "receiver_entity_rollup", "edge_rollup"} { - if _, err := d.writer().ExecContext(ctx, fmt.Sprintf("DELETE FROM %s WHERE bucket < (now() - INTERVAL %d DAY)::TIMESTAMP_NS", table, d.cfg.RetentionDays)); err != nil { + if _, err := d.writer().ExecContext(ctx, "DELETE FROM "+table+" WHERE "+where, args...); err != nil { errs = append(errs, fmt.Errorf("prune %s: %w", table, err)) } } diff --git a/internal/engine/duck_test.go b/internal/engine/duck_test.go index 342b68d6..05385e64 100644 --- a/internal/engine/duck_test.go +++ b/internal/engine/duck_test.go @@ -481,6 +481,69 @@ func TestCheckpointTracksConsecutiveFailures(t *testing.T) { } } +func TestRollupPruningHonorsPastAndFutureBoundsIndependently(t *testing.T) { + tables := []struct{ name, dimensions string }{ + {"service_rollup", ", 'svc' AS service"}, + {"span_rollup", ", 'svc' AS service, 'server' AS kind, 'ok' AS status"}, + {"log_rollup", ", 'svc' AS service, 'info' AS severity"}, + {"endpoint_rollup", ", 'svc' AS service, 'server' AS kind, 'ok' AS status, '/' AS route, false AS overflow"}, + {"receiver_rollup", ""}, + {"resource_rollup", ""}, + {"receiver_entity_rollup", ""}, + {"edge_rollup", ", 'client' AS caller, 'svc' AS callee"}, + } + for _, tc := range []struct { + name string + days int + skew time.Duration + want string + }{ + {"both", 1, 5 * time.Minute, "current,tolerated"}, + {"future only", 0, 5 * time.Minute, "current,expired,tolerated"}, + {"retention before the finite range", 150000, 5 * time.Minute, "current,expired,tolerated"}, + {"past only", 1, 0, "current,future,tolerated"}, + } { + t.Run(tc.name, func(t *testing.T) { + db := openTestDuck(t) + if err := CreateCacheTables(db); err != nil { + t.Fatal(err) + } + d := &Duck{DB: db, writeDB: db, cfg: config.Config{RetentionDays: tc.days, IngestMaxFutureSkew: tc.skew}} + for _, table := range tables { + if _, err := db.Exec("INSERT INTO " + table.name + " BY NAME SELECT namespace, bucket" + table.dimensions + ` FROM (VALUES + ('expired', now() - INTERVAL 2 DAY), ('current', now()), + ('tolerated', now() + INTERVAL 1 MINUTE), ('future', now() + INTERVAL 1 YEAR) + ) AS t(namespace, bucket)`); err != nil { + t.Fatal(err) + } + } + if err := d.pruneRollupCache(t.Context()); err != nil { + t.Fatal(err) + } + for _, table := range tables { + var got string + if err := db.QueryRow("SELECT string_agg(namespace, ',' ORDER BY namespace) FROM " + table.name).Scan(&got); err != nil { + t.Fatal(err) + } + if got != tc.want { + t.Errorf("%s retained %s, want %s", table.name, got, tc.want) + } + } + }) + } +} + +func TestRollupPruningSkipsWriteGateWhenNeitherBoundApplies(t *testing.T) { + d := &Duck{cfg: config.Config{RetentionDays: 150000}} + unlock := d.writeGate.Lock(writegate.Maintenance) + defer unlock() + ctx, cancel := context.WithCancel(t.Context()) + cancel() + if err := d.pruneRollupCache(ctx); err != nil { + t.Fatalf("pruning with no applicable bound tried to acquire a gate: %v", err) + } +} + // Retention DELETEs on the rollup cache are real maintenance work: a failure // there still degrades maintenance health and consecutive-failure tracking, // while leaving checkpoint health clean when the fold itself succeeds. diff --git a/internal/ingest/server.go b/internal/ingest/server.go index 5efcb626..092870cd 100644 --- a/internal/ingest/server.go +++ b/internal/ingest/server.go @@ -2,6 +2,7 @@ package ingest import ( "bytes" + "cmp" "context" "encoding/hex" "encoding/json" @@ -38,6 +39,7 @@ type batchSubmitter interface { type Server struct { cfg config.Config submitter batchSubmitter + now func() time.Time } type traceService struct { @@ -56,7 +58,7 @@ type metricsService struct { } func NewServer(cfg config.Config, submitter batchSubmitter) *Server { - return &Server{cfg: cfg, submitter: submitter} + return &Server{cfg: cfg, submitter: submitter, now: time.Now} } func RegisterOTLP(s grpc.ServiceRegistrar, srv *Server) { @@ -82,6 +84,7 @@ func (s *Server) exportTraces(ctx context.Context, req *collectortrace.ExportTra if err := s.submitter.Admit(ctx, count); err != nil { return nil, ingestStatusError(err) } + times := s.timestampFilter() batch := telemetrystore.Batch{} if count > 0 { batch.Spans = make([]telemetry.Span, 0, count) @@ -94,6 +97,9 @@ func (s *Server) exportTraces(ctx context.Context, req *collectortrace.ExportTra for _, ss := range rs.ScopeSpans { scopeName, scopeVer := scopeInfo(ss.Scope) for _, sp := range ss.Spans { + if times.reject(sp.StartTimeUnixNano, max(sp.EndTimeUnixNano, latestTimestamp(sp.Events))) { + continue + } attrs, err := attributes(sp.Attributes) if err != nil { return nil, status.Error(codes.InvalidArgument, err.Error()) @@ -150,10 +156,15 @@ func (s *Server) exportTraces(ctx context.Context, req *collectortrace.ExportTra } } } - if err := s.submitter.Submit(ctx, batch); err != nil { - return nil, ingestStatusError(err) + rejected, err := s.submitFiltered(ctx, batch, count, "spans", times) + if err != nil { + return nil, err } - return &collectortrace.ExportTraceServiceResponse{}, nil + resp := &collectortrace.ExportTraceServiceResponse{} + if rejected > 0 { + resp.PartialSuccess = &collectortrace.ExportTracePartialSuccess{RejectedSpans: rejected, ErrorMessage: timestampRejectionMessage} + } + return resp, nil } // shedRetryDelay is how long a shed sender is asked to wait before resending. @@ -199,6 +210,7 @@ func (s *Server) exportLogs(ctx context.Context, req *collectorlogs.ExportLogsSe if err := s.submitter.Admit(ctx, count); err != nil { return nil, ingestStatusError(err) } + times := s.timestampFilter() batch := telemetrystore.Batch{} if count > 0 { batch.Logs = make([]telemetry.Log, 0, count) @@ -211,6 +223,10 @@ func (s *Server) exportLogs(ctx context.Context, req *collectorlogs.ExportLogsSe for _, sl := range rl.ScopeLogs { scopeName, scopeVer := scopeInfo(sl.Scope) for _, lr := range sl.LogRecords { + event := cmp.Or(lr.TimeUnixNano, lr.ObservedTimeUnixNano) + if times.reject(event, lr.ObservedTimeUnixNano) { + continue + } attrs, err := attributes(lr.Attributes) if err != nil { return nil, status.Error(codes.InvalidArgument, err.Error()) @@ -238,10 +254,15 @@ func (s *Server) exportLogs(ctx context.Context, req *collectorlogs.ExportLogsSe } } } - if err := s.submitter.Submit(ctx, batch); err != nil { - return nil, ingestStatusError(err) + rejected, err := s.submitFiltered(ctx, batch, count, "logs", times) + if err != nil { + return nil, err + } + resp := &collectorlogs.ExportLogsServiceResponse{} + if rejected > 0 { + resp.PartialSuccess = &collectorlogs.ExportLogsPartialSuccess{RejectedLogRecords: rejected, ErrorMessage: timestampRejectionMessage} } - return &collectorlogs.ExportLogsServiceResponse{}, nil + return resp, nil } // ---- Metrics ingest ---- @@ -274,6 +295,7 @@ func (s *Server) exportMetrics(ctx context.Context, req *collectormetrics.Export if err := s.submitter.Admit(ctx, count); err != nil { return nil, ingestStatusError(err) } + times := s.timestampFilter() batch := telemetrystore.Batch{} if count > 0 { batch.Metrics = make([]telemetry.Metric, 0, count) @@ -290,21 +312,26 @@ func (s *Server) exportMetrics(ctx context.Context, req *collectormetrics.Export Namespace: namespace, Name: m.Name, Description: m.Description, Unit: m.Unit, ServiceName: svc, Resource: resources, ScopeName: scopeName, ScopeVersion: scopeVer, } - if batch.Metrics, err = appendMetricPoints(batch.Metrics, base, m); err != nil { + if batch.Metrics, err = appendMetricPoints(batch.Metrics, base, m, ×); err != nil { return nil, status.Error(codes.InvalidArgument, fmt.Sprintf("metric %q: %v", m.Name, err)) } } } } - if err := s.submitter.Submit(ctx, batch); err != nil { - return nil, ingestStatusError(err) + rejected, err := s.submitFiltered(ctx, batch, count, "metrics", times) + if err != nil { + return nil, err + } + resp := &collectormetrics.ExportMetricsServiceResponse{} + if rejected > 0 { + resp.PartialSuccess = &collectormetrics.ExportMetricsPartialSuccess{RejectedDataPoints: rejected, ErrorMessage: timestampRejectionMessage} } - return &collectormetrics.ExportMetricsServiceResponse{}, nil + return resp, nil } // appendMetricPoints converts one OTLP metric's points. A malformed point // rejects the export: the quantile path relies on what is checked here. -func appendMetricPoints(out []telemetry.Metric, base telemetry.Metric, m *metricspb.Metric) ([]telemetry.Metric, error) { +func appendMetricPoints(out []telemetry.Metric, base telemetry.Metric, m *metricspb.Metric, times *timestampFilter) ([]telemetry.Metric, error) { point := func(attrs []*common.KeyValue, start, at uint64, flags uint32) (telemetry.Metric, error) { row := base var err error @@ -319,6 +346,9 @@ func appendMetricPoints(out []telemetry.Metric, base telemetry.Metric, m *metric switch d := m.Data.(type) { case *metricspb.Metric_Gauge: for _, dp := range d.Gauge.DataPoints { + if times.rejectPoint(dp.TimeUnixNano, dp.StartTimeUnixNano, dp.Exemplars) { + continue + } row, err := point(dp.Attributes, dp.StartTimeUnixNano, dp.TimeUnixNano, dp.Flags) if err != nil { return out, err @@ -342,6 +372,9 @@ func appendMetricPoints(out []telemetry.Metric, base telemetry.Metric, m *metric kind = "counter" } for _, dp := range d.Sum.DataPoints { + if times.rejectPoint(dp.TimeUnixNano, dp.StartTimeUnixNano, dp.Exemplars) { + continue + } row, err := point(dp.Attributes, dp.StartTimeUnixNano, dp.TimeUnixNano, dp.Flags) if err != nil { return out, err @@ -361,6 +394,9 @@ func appendMetricPoints(out []telemetry.Metric, base telemetry.Metric, m *metric return out, err } for _, dp := range d.Histogram.DataPoints { + if times.rejectPoint(dp.TimeUnixNano, dp.StartTimeUnixNano, dp.Exemplars) { + continue + } if err := checkBuckets(dp.ExplicitBounds, dp.BucketCounts); err != nil { return out, err } @@ -384,6 +420,9 @@ func appendMetricPoints(out []telemetry.Metric, base telemetry.Metric, m *metric return out, err } for _, dp := range d.ExponentialHistogram.DataPoints { + if times.rejectPoint(dp.TimeUnixNano, dp.StartTimeUnixNano, dp.Exemplars) { + continue + } if math.IsNaN(dp.ZeroThreshold) || math.IsInf(dp.ZeroThreshold, 0) || dp.ZeroThreshold < 0 { return out, errors.New("exponential histogram zero_threshold must be a finite, non-negative number") } @@ -406,6 +445,9 @@ func appendMetricPoints(out []telemetry.Metric, base telemetry.Metric, m *metric } case *metricspb.Metric_Summary: for _, dp := range d.Summary.DataPoints { + if times.rejectPoint(dp.TimeUnixNano, dp.StartTimeUnixNano, nil) { + continue + } row, err := point(dp.Attributes, dp.StartTimeUnixNano, dp.TimeUnixNano, dp.Flags) if err != nil { return out, err diff --git a/internal/ingest/timestamps.go b/internal/ingest/timestamps.go new file mode 100644 index 00000000..d7a4996e --- /dev/null +++ b/internal/ingest/timestamps.go @@ -0,0 +1,80 @@ +package ingest + +import ( + "context" + "slices" + + metricspb "go.opentelemetry.io/proto/otlp/metrics/v1" + + "github.com/labstack/pitot/internal/metrics" + telemetrystore "github.com/labstack/pitot/internal/telemetry/store" +) + +const timestampRejectionMessage = "client timestamp outside the accepted time range" + +// Each export uses one receipt clock, including exports with multiple resources. +type timestampFilter struct { + earliest, latest uint64 + expired, future int64 +} + +func (s *Server) timestampFilter() timestampFilter { + now := s.now() + f := timestampFilter{latest: uint64(max(0, s.cfg.LatestEventTime(now).UnixNano()))} + if cutoff, ok := s.cfg.RetentionCutoff(now); ok { + f.earliest = uint64(max(0, cutoff)) + } + return f +} + +// Only the effective event time controls expiry. Every supplied timestamp +// must fit within the future bound before conversion to signed nanoseconds. +func (f *timestampFilter) reject(event, latestOther uint64) bool { + if max(event, latestOther) > f.latest { + f.future++ + return true + } + if event != 0 && event < f.earliest { + f.expired++ + return true + } + return false +} + +// A point's start can predate retention for a long-running cumulative series. +func (f *timestampFilter) rejectPoint(at, start uint64, exemplars []*metricspb.Exemplar) bool { + return f.reject(at, max(start, latestTimestamp(exemplars))) +} + +func latestTimestamp[T interface{ GetTimeUnixNano() uint64 }](items []T) uint64 { + var latest uint64 + for _, item := range items { + latest = max(latest, item.GetTimeUnixNano()) + } + return latest +} + +// Report permanent drops only after the accepted rows commit. A retryable +// failure still applies to the whole request. +func (s *Server) submitFiltered(ctx context.Context, batch telemetrystore.Batch, count int, signal string, times timestampFilter) (int64, error) { + rejected := times.future + times.expired + if rejected == 0 || rejected < int64(count) { + // Conversion reserves space for the whole export. Release sparsely + // populated arrays before the writer holds the survivors for commit. + if rejected > int64(count)/2 { + batch.Spans = slices.Clone(batch.Spans) + batch.Logs = slices.Clone(batch.Logs) + batch.Metrics = slices.Clone(batch.Metrics) + } + if err := s.submitter.Submit(ctx, batch); err != nil { + return 0, ingestStatusError(err) + } + } + if times.future > 0 { + metrics.IngestRejectedRows.WithLabelValues(signal, "future").Add(float64(times.future)) + } + if times.expired > 0 { + metrics.IngestRejectedRows.WithLabelValues(signal, "expired").Add(float64(times.expired)) + } + return rejected, nil +} diff --git a/internal/ingest/timestamps_test.go b/internal/ingest/timestamps_test.go new file mode 100644 index 00000000..1e241d82 --- /dev/null +++ b/internal/ingest/timestamps_test.go @@ -0,0 +1,201 @@ +package ingest + +import ( + "context" + "errors" + "math" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/labstack/pitot/internal/config" + "github.com/labstack/pitot/internal/metrics" + httpserver "github.com/labstack/pitot/internal/server" + telemetrystore "github.com/labstack/pitot/internal/telemetry/store" + "github.com/prometheus/client_golang/prometheus/testutil" + collectorlogs "go.opentelemetry.io/proto/otlp/collector/logs/v1" + collectormetrics "go.opentelemetry.io/proto/otlp/collector/metrics/v1" + collectortrace "go.opentelemetry.io/proto/otlp/collector/trace/v1" + logspb "go.opentelemetry.io/proto/otlp/logs/v1" + metricspb "go.opentelemetry.io/proto/otlp/metrics/v1" + tracepb "go.opentelemetry.io/proto/otlp/trace/v1" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/proto" +) + +func TestTimestampFilterIncludesCutoffsAndAlwaysRejectsInfinity(t *testing.T) { + now := time.Unix(300000, 123) + s := NewServer(config.Config{RetentionDays: 1, IngestMaxFutureSkew: 5 * time.Minute}, nil) + s.now = func() time.Time { return now } + lo, hi := uint64(now.Add(-24*time.Hour).UnixNano()), uint64(now.Add(5*time.Minute).UnixNano()) + check := func(stamp uint64, wantExpired, wantFuture int64) { + t.Helper() + f := s.timestampFilter() + rejected := f.reject(stamp, 0) + if rejected != (wantExpired+wantFuture > 0) || f.expired != wantExpired || f.future != wantFuture { + t.Errorf("timestamp %d: rejected=%t expired=%d future=%d", stamp, rejected, f.expired, f.future) + } + } + check(0, 0, 0) + check(lo-1, 1, 0) + check(lo, 0, 0) + check(hi, 0, 0) + check(hi+1, 0, 1) + s.cfg.IngestMaxFutureSkew = 0 + check(math.MaxInt64-1, 0, 0) + for _, stamp := range []uint64{math.MaxInt64, 1 << 63, math.MaxUint64} { + check(stamp, 0, 1) + } + s.cfg.RetentionDays = math.MaxInt + s.cfg.IngestMaxFutureSkew = time.Duration(math.MaxInt64) + check(1, 0, 0) + check(math.MaxInt64-1, 0, 0) +} + +func TestRetentionAppliesToEveryMetricPointType(t *testing.T) { + _, _, points := conversionExports(1) // gauge, sum, explicit and exponential histogram, summary + srv := NewServer(config.Config{RetentionDays: 1}, conversionSubmitter(func(context.Context, telemetrystore.Batch) error { + t.Fatal("expired metric points reached storage") + return nil + })) + at := points.ResourceMetrics[0].ScopeMetrics[0].Metrics[0].GetGauge().DataPoints[0].TimeUnixNano + srv.now = func() time.Time { return time.Unix(0, int64(at)).Add(24*time.Hour + time.Nanosecond) } + resp, err := srv.exportMetrics(t.Context(), points) + if err != nil || resp.GetPartialSuccess().GetRejectedDataPoints() != 5 { + t.Fatalf("expired points: %v, %v", resp, err) + } +} + +func TestRetryableCommitFailureDoesNotAcknowledgeTimestampDrops(t *testing.T) { + want := errors.New("storage unavailable") + srv := NewServer(config.Config{}, conversionSubmitter(func(context.Context, telemetrystore.Batch) error { return want })) + req := testTraceRequest() + scope := req.ResourceSpans[0].ScopeSpans[0] + scope.Spans = append(scope.Spans, &tracepb.Span{EndTimeUnixNano: math.MaxUint64}) + counter := metrics.IngestRejectedRows.WithLabelValues("spans", "future") + before := testutil.ToFloat64(counter) + resp, err := srv.exportTraces(t.Context(), req) + if !errors.Is(err, want) || resp != nil || testutil.ToFloat64(counter) != before { + t.Fatalf("failed commit: response %v, error %v, counted drops %v", resp, err, testutil.ToFloat64(counter)-before) + } +} + +func TestOTLPReportsTimestampDropsAfterSubmittingOnlyAcceptedRows(t *testing.T) { + f := newHTTPIngestFixture(t, true) + submitted := make(chan telemetrystore.Batch, 1) + cfg := config.Config{RetentionDays: 1, IngestMaxFutureSkew: time.Minute} + srv := NewServer(cfg, conversionSubmitter(func(_ context.Context, b telemetrystore.Batch) error { + submitted <- b + return nil + })) + now := time.Unix(300000, 0) + srv.now = func() time.Time { return now } + handler := NewHTTPHandler(srv, f.store) + g := grpc.NewServer(GRPCServerOptions(f.store)...) + RegisterOTLP(g, srv) + defer g.Stop() + ts := httptest.NewUnstartedServer(nil) + ts.Config = httpserver.New("", http.NotFoundHandler(), handler, g) + ts.Start() + defer ts.Close() + conn, err := grpc.NewClient(ts.Listener.Addr().String(), grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) + defer cancel() + ctx = metadata.AppendToOutgoingContext(ctx, "authorization", "Bearer "+f.token) + + for _, allRejected := range []bool{false, true} { + at := uint64(now.UnixNano()) + mode := "mixed" + wantExpired := int64(1) + if allRejected { + at = 1 + mode = "all rejected" + wantExpired++ + } + traces := testTraceRequest() + traces.ResourceSpans[0].ScopeSpans[0].Spans = []*tracepb.Span{ + {StartTimeUnixNano: at}, {StartTimeUnixNano: 1}, {EndTimeUnixNano: uint64(now.Add(time.Hour).UnixNano())}, + {Events: []*tracepb.Span_Event{{TimeUnixNano: math.MaxInt64}}}, + } + logs := testLogsRequest() + logs.ResourceLogs[0].ScopeLogs[0].LogRecords = []*logspb.LogRecord{ + {TimeUnixNano: at, ObservedTimeUnixNano: 1}, {ObservedTimeUnixNano: 1}, + {TimeUnixNano: math.MaxUint64}, {TimeUnixNano: at, ObservedTimeUnixNano: 1 << 63}, + } + points := testMetricsRequest() + points.ResourceMetrics[0].ScopeMetrics[0].Metrics[0].Data = &metricspb.Metric_Sum{Sum: &metricspb.Sum{ + AggregationTemporality: metricspb.AggregationTemporality_AGGREGATION_TEMPORALITY_CUMULATIVE, + DataPoints: []*metricspb.NumberDataPoint{ + {TimeUnixNano: at, StartTimeUnixNano: 1, Value: &metricspb.NumberDataPoint_AsInt{AsInt: 3}}, + {TimeUnixNano: 1}, {StartTimeUnixNano: math.MaxInt64}, + {Exemplars: []*metricspb.Exemplar{{TimeUnixNano: math.MaxUint64}}}, + }, + }} + total := wantExpired + 2 + for _, tc := range []struct { + signal, path, method string + req, want proto.Message + }{ + {"spans", "/v1/traces", collectortrace.TraceService_Export_FullMethodName, traces, + &collectortrace.ExportTraceServiceResponse{PartialSuccess: &collectortrace.ExportTracePartialSuccess{RejectedSpans: total, ErrorMessage: timestampRejectionMessage}}}, + {"logs", "/v1/logs", collectorlogs.LogsService_Export_FullMethodName, logs, + &collectorlogs.ExportLogsServiceResponse{PartialSuccess: &collectorlogs.ExportLogsPartialSuccess{RejectedLogRecords: total, ErrorMessage: timestampRejectionMessage}}}, + {"metrics", "/v1/metrics", collectormetrics.MetricsService_Export_FullMethodName, points, + &collectormetrics.ExportMetricsServiceResponse{PartialSuccess: &collectormetrics.ExportMetricsPartialSuccess{RejectedDataPoints: total, ErrorMessage: timestampRejectionMessage}}}, + } { + for _, transport := range []string{"HTTP", "gRPC"} { + t.Run(tc.signal+"/"+mode+"/"+transport, func(t *testing.T) { + expired := metrics.IngestRejectedRows.WithLabelValues(tc.signal, "expired") + future := metrics.IngestRejectedRows.WithLabelValues(tc.signal, "future") + beforeExpired, beforeFuture := testutil.ToFloat64(expired), testutil.ToFloat64(future) + resp := tc.want.ProtoReflect().New().Interface() + if transport == "HTTP" { + assertOTLPHTTPSuccess(t, handler, tc.path, tc.req, f.token, resp) + } else if err := conn.Invoke(ctx, tc.method, tc.req, resp); err != nil { + t.Fatal(err) + } + if !proto.Equal(resp, tc.want) { + t.Errorf("response %v, want %v", resp, tc.want) + } + if testutil.ToFloat64(expired)-beforeExpired != float64(wantExpired) || testutil.ToFloat64(future)-beforeFuture != 2 { + t.Error("rejection counters disagree with the timestamps in the export") + } + select { + case batch := <-submitted: + if allRejected { + t.Fatal("fully rejected export submitted a batch") + } + if cap(batch.Spans)+cap(batch.Logs)+cap(batch.Metrics) >= 4 { + t.Fatal("sparse batch retained space for rejected rows") + } + switch tc.signal { + case "spans": + if len(batch.Spans) != 1 || batch.Spans[0].StartUnixNanos != int64(at) { + t.Fatalf("submitted spans: %+v", batch.Spans) + } + case "logs": + if len(batch.Logs) != 1 || batch.Logs[0].TimeUnixNanos != int64(at) { + t.Fatalf("submitted logs: %+v", batch.Logs) + } + case "metrics": + if len(batch.Metrics) != 1 || batch.Metrics[0].TimeUnixNanos != int64(at) || batch.Metrics[0].StartTimeUnixNanos != 1 { + t.Fatalf("submitted metrics: %+v", batch.Metrics) + } + } + default: + if !allRejected { + t.Fatal("mixed export did not submit valid row") + } + } + }) + } + } + } +} diff --git a/internal/metrics/metrics.go b/internal/metrics/metrics.go index 9f49fdef..e848e069 100644 --- a/internal/metrics/metrics.go +++ b/internal/metrics/metrics.go @@ -99,6 +99,11 @@ var ( Help: "Total flush operations", }, []string{"signal"}) + IngestRejectedRows = promauto.NewCounterVec(prometheus.CounterOpts{ + Name: "pitot_ingest_rejected_rows_total", + Help: "Telemetry rows rejected because a client timestamp was outside the accepted range", + }, []string{"signal", "reason"}) + // IngestShedTotal counts requests refused because accepting them would // take the process past the bytes it is willing to hold in flight. A // non-zero value is the system protecting itself, not a fault -- but a diff --git a/internal/observability/service_test.go b/internal/observability/service_test.go index 2b91cdc1..280618ca 100644 --- a/internal/observability/service_test.go +++ b/internal/observability/service_test.go @@ -190,8 +190,8 @@ func TestTraceSelectsRecentErrorAndCorrelatesLogs(t *testing.T) { WithArgs(start, end, "prod", "prod", "checkout", "checkout", 1). WillReturnRows(sqlmock.NewRows([]string{"namespace", "trace_id", "has_error"}).AddRow("prod", "trace-1", 1)) if err := repository.Commit(context.Background(), telemetrystore.Batch{ID: "trace-fixture", Spans: []telemetry.Span{ - {Namespace: "prod", TraceID: "trace-1", SpanID: "root", ServiceName: "checkout", Name: "POST /pay", Kind: "SERVER", StartUnixNanos: start.UnixNano(), DurationMS: 200, StatusCode: "STATUS_CODE_ERROR", StatusMsg: "declined"}, - {Namespace: "prod", TraceID: "trace-1", SpanID: "child", ParentSpanID: "root", ServiceName: "payments", Name: "charge", Kind: "CLIENT", StartUnixNanos: start.Add(20 * time.Millisecond).UnixNano(), DurationMS: 80, StatusCode: "OK"}, + {Namespace: "prod", TraceID: "trace-1", SpanID: "root", ServiceName: "checkout", Name: "POST /pay", Kind: "SERVER", StartUnixNanos: start.UnixNano(), EndUnixNanos: start.Add(200 * time.Millisecond).UnixNano(), DurationMS: 200, StatusCode: "STATUS_CODE_ERROR", StatusMsg: "declined"}, + {Namespace: "prod", TraceID: "trace-1", SpanID: "child", ParentSpanID: "root", ServiceName: "payments", Name: "charge", Kind: "CLIENT", StartUnixNanos: start.Add(20 * time.Millisecond).UnixNano(), EndUnixNanos: start.Add(100 * time.Millisecond).UnixNano(), DurationMS: 80, StatusCode: "OK"}, }, Logs: []telemetry.Log{ {Namespace: "prod", TimeUnixNanos: start.Add(150 * time.Millisecond).UnixNano(), Severity: "ERROR", ServiceName: "checkout", Body: "payment declined", TraceID: "trace-1", SpanID: "root"}, {Namespace: "prod", TimeUnixNanos: start.Add(160 * time.Millisecond).UnixNano(), Severity: "ERROR", ServiceName: "payments", Body: `charge failed: token=abc123 {"client_secret":"cs_live_9"}`, TraceID: "trace-1", SpanID: "child"}, diff --git a/internal/observability/trace_test.go b/internal/observability/trace_test.go index 508feeef..7f749402 100644 --- a/internal/observability/trace_test.go +++ b/internal/observability/trace_test.go @@ -25,17 +25,17 @@ func TestTracePagedSpansStillDescribeTheWholeTrace(t *testing.T) { { Namespace: "prod", TraceID: "wide-trace", SpanID: "root", ServiceName: "cart", Name: "ResolveBoolean", Kind: "CLIENT", - StartUnixNanos: start.UnixNano(), DurationMS: 2, StatusCode: "OK", + StartUnixNanos: start.UnixNano(), EndUnixNanos: start.Add(2 * time.Millisecond).UnixNano(), DurationMS: 2, StatusCode: "OK", }, { Namespace: "prod", TraceID: "wide-trace", SpanID: "child", ParentSpanID: "root", ServiceName: "cart", Name: "POST", Kind: "CLIENT", - StartUnixNanos: start.Add(time.Millisecond).UnixNano(), DurationMS: 1, StatusCode: "OK", + StartUnixNanos: start.Add(time.Millisecond).UnixNano(), EndUnixNanos: start.Add(2 * time.Millisecond).UnixNano(), DurationMS: 1, StatusCode: "OK", }, { Namespace: "prod", TraceID: "wide-trace", SpanID: "leaf", ParentSpanID: "child", ServiceName: "flagd", Name: "resolveBoolean", Kind: "SERVER", - StartUnixNanos: start.Add(2 * time.Millisecond).UnixNano(), DurationMS: 1, StatusCode: "STATUS_CODE_ERROR", + StartUnixNanos: start.Add(2 * time.Millisecond).UnixNano(), EndUnixNanos: start.Add(3 * time.Millisecond).UnixNano(), DurationMS: 1, StatusCode: "STATUS_CODE_ERROR", StatusMsg: "error evaluating flag with key failedReadinessProbe", }, }}); err != nil { diff --git a/internal/telemetry/store/repository.go b/internal/telemetry/store/repository.go index fabbcf8e..3d7cba34 100644 --- a/internal/telemetry/store/repository.go +++ b/internal/telemetry/store/repository.go @@ -265,10 +265,16 @@ func validateBatch(batch Batch) error { func normalizeBatch(batch *Batch, ingestedAt int64) { for i := range batch.Spans { - batch.Spans[i].Namespace = telemetry.NormalizeNamespace(batch.Spans[i].Namespace) - batch.Spans[i].IngestedAt = ingestedAt - if batch.Spans[i].StartUnixNanos == 0 { - batch.Spans[i].StartUnixNanos = batch.Spans[i].IngestedAt + span := &batch.Spans[i] + span.Namespace = telemetry.NormalizeNamespace(span.Namespace) + span.IngestedAt = ingestedAt + if span.StartUnixNanos == 0 { + span.StartUnixNanos = ingestedAt + span.EndUnixNanos = max(span.EndUnixNanos, ingestedAt) + span.DurationMS = float64(span.EndUnixNanos-ingestedAt) / 1e6 + } else if span.EndUnixNanos == 0 { + span.EndUnixNanos = span.StartUnixNanos + span.DurationMS = 0 } } for i := range batch.Logs { diff --git a/internal/telemetry/store/repository_test.go b/internal/telemetry/store/repository_test.go index 752ea47b..b5b4d710 100644 --- a/internal/telemetry/store/repository_test.go +++ b/internal/telemetry/store/repository_test.go @@ -306,6 +306,24 @@ func TestRepositoryCleanupOwnsRetiredDirectories(t *testing.T) { } } +func TestMissingTimestampsNormalizeToConsistentEventTimes(t *testing.T) { + batch := Batch{ + Spans: []telemetry.Span{{}, {StartUnixNanos: 32, DurationMS: 12}, {EndUnixNanos: 16}, {EndUnixNanos: 1500000}}, + Logs: []telemetry.Log{{}}, Metrics: []telemetry.Metric{{}}, + } + const receipt = 1000000 + normalizeBatch(&batch, receipt) + for i, want := range [][2]int64{{receipt, receipt}, {32, 32}, {receipt, receipt}, {receipt, 1500000}} { + span := batch.Spans[i] + if span.StartUnixNanos != want[0] || span.EndUnixNanos != want[1] || span.DurationMS != float64(want[1]-want[0])/1e6 { + t.Errorf("span %d: start=%d end=%d duration=%v", i, span.StartUnixNanos, span.EndUnixNanos, span.DurationMS) + } + } + if batch.Logs[0].EventUnixNanos != receipt || batch.Metrics[0].EventUnixNanos != receipt { + t.Fatal("missing log and metric event times should use receipt time") + } +} + func TestRepositoryRetentionUsesIngestTimeNotEventTime(t *testing.T) { repository, err := Open(t.TempDir()) if err != nil { diff --git a/site/src/content/docs/docs/concepts/storage.mdx b/site/src/content/docs/docs/concepts/storage.mdx index c04f390b..60698b20 100644 --- a/site/src/content/docs/docs/concepts/storage.mdx +++ b/site/src/content/docs/docs/concepts/storage.mdx @@ -58,6 +58,20 @@ completes, so a sender that gives up during it and retries stores those rows twice. Delivery is therefore at least once only within that commit window: OTLP has no idempotency key that lets Pitot recognize a resent request. +## Which event times reach storage + +Pitot applies retention to the span start, log time (or observed time when the +log time is absent), and metric point time. Missing event times use ingestion +time. A cumulative metric may retain a process start time older than retention. +All supplied timestamps, including span events and metric exemplars, must fit +in finite signed nanoseconds and respect the configured future tolerance +(`PITOT_INGEST_MAX_FUTURE_SKEW`, default `5m`). + +An out-of-range timestamp drops the containing span, log record, or metric +data point. OTLP `PartialSuccess` reports how many rows were dropped after the +valid rows are durable. An entirely rejected request creates no batch. Rollup +maintenance also removes existing buckets beyond the configured future tolerance. + ## One authoritative copy for logs and metrics Every signal is written once, to typed Zstandard-compressed Parquet. DuckDB diff --git a/site/src/content/docs/docs/reference/configuration/ingest.mdx b/site/src/content/docs/docs/reference/configuration/ingest.mdx index 45f296de..ed1827b9 100644 --- a/site/src/content/docs/docs/reference/configuration/ingest.mdx +++ b/site/src/content/docs/docs/reference/configuration/ingest.mdx @@ -21,6 +21,7 @@ Vendor credentials and endpoints keep the vendor's documented names. |---|---|---| | `PITOT_DEFAULT_NAMESPACE` | string | `default` | | `PITOT_INGEST_BATCH_SIZE` | integer | `50000` | +| `PITOT_INGEST_MAX_FUTURE_SKEW` | duration | `5m` | | `PITOT_INGEST_MAX_IN_FLIGHT_BYTES` | integer | `268435456` | | `PITOT_INGEST_TOKEN` or `PITOT_INGEST_TOKEN_FILE` | string · secret | — | @@ -34,6 +35,10 @@ Supplies the namespace for telemetry without one. Sets the group-commit row target; valid values are 1–50000. Individual requests remain atomic and can exceed this target. +### `PITOT_INGEST_MAX_FUTURE_SKEW` + +Sets how far client timestamps may lead the server clock. Zero disables clock-skew checks. Timestamps must still fit in finite signed nanoseconds. + ### `PITOT_INGEST_MAX_IN_FLIGHT_BYTES` Caps decoded telemetry held across concurrent requests until durable publication. Zero is unbounded. A single request is admitted when no other request holds budget, even if it exceeds the limit.