Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
19 changes: 19 additions & 0 deletions docs/operations.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
52 changes: 52 additions & 0 deletions docs/proposals/0014-ingest-timestamp-bounds.md
Original file line number Diff line number Diff line change
@@ -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.
1 change: 1 addition & 0 deletions docs/proposals/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
12 changes: 8 additions & 4 deletions internal/alert/engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand All @@ -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),
Expand Down
17 changes: 15 additions & 2 deletions internal/alert/engine_env_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand All @@ -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)
}

Expand All @@ -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)
}
Expand Down
44 changes: 44 additions & 0 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package config
import (
"fmt"
"log/slog"
"math"
"net"
"net/url"
"path/filepath"
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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")
}
Expand Down Expand Up @@ -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")
}
Expand Down
39 changes: 34 additions & 5 deletions internal/config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package config
import (
"bytes"
"log/slog"
"math"
"os"
"path/filepath"
"reflect"
Expand All @@ -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 {
Expand All @@ -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")
}
}
Expand All @@ -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 {
Expand All @@ -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)
}
}
}
Expand Down Expand Up @@ -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 = "" }},
Expand Down
24 changes: 18 additions & 6 deletions internal/engine/duck.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand All @@ -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))
}
}
Expand Down
Loading
Loading