Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(logs): accept backdated timestamps on an authorized import path (#105445)

Jimmy Zhu65a22c9e90fb
diff --git a/rust/capture-logs/README.md b/rust/capture-logs/README.md
index 9ddf4f6a8e69..ae0c899160d4 100644
--- a/rust/capture-logs/README.md
+++ b/rust/capture-logs/README.md
@@ -25,6 +25,7 @@ The service is configured using environment variables:
| MAX_REQUEST_BODY_SIZE_BYTES | 2097152 | Rejects larger request bodies, before and after gzip decompression |
| FIREHOSE_MAX_REQUEST_BODY_SIZE_BYTES | 8388608 | Body cap for the Amazon Data Firehose route only |
| DROP_EVENTS_BY_TOKEN | (none) | Comma-separated tokens to drop |
+| MAX_BACKFILL_DAYS | 0 | How far back a request may ask to keep its own timestamps. `0` refuses every `backfill_days` request |
## Authentication
@@ -44,12 +45,41 @@ POST /v1/logs?token=your-project-token
The token is your PostHog project token.
+## Backdated logs
+
+A log record whose timestamp is more than 24 hours behind the ingest time is normally replaced
+with the ingest time, and the original is kept on the `$originalTimestamp` attribute. That guard
+protects every query range on the team from one client with a broken clock.
+
+A historical import needs the original timestamps. Widen the past bound for one request with the
+`backfill_days` query parameter, on `POST /v1/logs` and `POST /i/v1/logs` only. The Datadog and
+Prometheus routes do not accept it, because the Datadog agent cannot send a query string at all.
+Traces and metrics do not accept it either.
+
+```http
+POST /i/v1/logs?backfill_days=540
+```
+
+The value must be between 1 and `MAX_BACKFILL_DAYS`. A request outside that range is answered 400,
+rather than being narrowed to the default, because an import whose timestamps are quietly replaced
+looks successful and writes most of its records onto the ingest time.
+
+`MAX_BACKFILL_DAYS` is per-deployment, so turning it on grants the capability to every project on
+that deployment.
+
+The future bound stays at 24 hours whatever `backfill_days` says. A timestamp ahead of the
+ingest time is a client clock error in every case, and accepting one would let a single client
+write rows past the end of every other query range on the team.
+
+Imported records take their retention from the ingest time, not from their own timestamp, so a
+backfill expires `retention_days` after it is imported.
+
## Response codes
| Status | Meaning | Client behavior |
|--------|---------|-----------------|
| 200 | Accepted | — |
-| 400 | Body could not be decoded as OTLP protobuf or JSON | Permanent |
+| 400 | Body could not be decoded as OTLP protobuf or JSON, or `backfill_days` was rejected | Permanent |
| 401 | No token, or a token that cannot be a project API key (for example a `phx_` personal API key) | Permanent, so the client stops and surfaces the misconfiguration |
| 413 | Body over `MAX_REQUEST_BODY_SIZE_BYTES` | Permanent |
diff --git a/rust/capture-logs/src/config.rs b/rust/capture-logs/src/config.rs
index e4c42e284cfc..c7dbfbf8bf68 100644
--- a/rust/capture-logs/src/config.rs
+++ b/rust/capture-logs/src/config.rs
@@ -33,6 +33,9 @@ pub struct Config {
// own, larger body cap. Decoded size is bounded separately by the endpoint.
#[envconfig(from = "FIREHOSE_MAX_REQUEST_BODY_SIZE_BYTES", default = "8388608")] // 8 MiB
pub firehose_max_request_body_size_bytes: usize,
+
+ #[envconfig(from = "MAX_BACKFILL_DAYS", default = "0")]
+ pub max_backfill_days: u32,
}
impl Config {
diff --git a/rust/capture-logs/src/endpoints/prometheus.rs b/rust/capture-logs/src/endpoints/prometheus.rs
index 580e208c145e..83a066576af3 100644
--- a/rust/capture-logs/src/endpoints/prometheus.rs
+++ b/rust/capture-logs/src/endpoints/prometheus.rs
@@ -17,7 +17,8 @@ use tracing::{debug, error, instrument, warn};
use uuid::Uuid;
use crate::authorizer::Signal;
-use crate::metric_record::{compute_series_fingerprint, override_timestamp, KafkaMetricRow};
+use crate::log_record::override_timestamp;
+use crate::metric_record::{compute_series_fingerprint, KafkaMetricRow};
use crate::service::Service;
const METRIC_NAME_LABEL: &str = "__name__";
diff --git a/rust/capture-logs/src/log_record.rs b/rust/capture-logs/src/log_record.rs
index c5bad4622bae..d4ee6244c6bb 100644
--- a/rust/capture-logs/src/log_record.rs
+++ b/rust/capture-logs/src/log_record.rs
@@ -100,6 +100,7 @@ impl KafkaLogRow {
record: LogRecord,
resource: Option<Resource>,
scope: Option<InstrumentationScope>,
+ max_past: TimeDelta,
) -> Result<(Self, bool)> {
// Extract body - convert any AnyValue type to JSON string
let body = match record.body {
@@ -161,7 +162,8 @@ impl KafkaLogRow {
_ => DateTime::<Utc>::from_timestamp_nanos(record.time_unix_nano.try_into()?),
};
- let (timestamp, was_overridden) = apply_timestamp_override(raw_timestamp, &mut attributes);
+ let (timestamp, was_overridden) =
+ apply_timestamp_override_with_past_limit(raw_timestamp, &mut attributes, max_past);
let observed_timestamp = Utc::now();
@@ -192,15 +194,33 @@ impl KafkaLogRow {
}
}
-const TIMESTAMP_OVERRIDE_HOURS: i64 = 24;
+const DEFAULT_MAX_PAST_HOURS: i64 = 24;
-/// Override timestamps outside of 24 hours from now. Returns the final timestamp
-/// and the original if it was overridden.
+pub fn default_max_past() -> TimeDelta {
+ TimeDelta::hours(DEFAULT_MAX_PAST_HOURS)
+}
+
+/// Never widens with the past bound. A timestamp ahead of the ingest time is always a client
+/// clock error, so widening both together would let one client write past every other query range.
+const MAX_FUTURE_HOURS: i64 = 24;
+
+/// Returns the final timestamp, and the original when it was overridden.
pub fn override_timestamp(timestamp: DateTime<Utc>) -> (DateTime<Utc>, Option<DateTime<Utc>>) {
+ override_timestamp_with_past_limit(timestamp, default_max_past())
+}
+
+pub fn override_timestamp_with_past_limit(
+ timestamp: DateTime<Utc>,
+ max_past: TimeDelta,
+) -> (DateTime<Utc>, Option<DateTime<Utc>>) {
let now = Utc::now();
- let max_delta = TimeDelta::hours(TIMESTAMP_OVERRIDE_HOURS);
- if timestamp < now - max_delta || timestamp > now + max_delta {
+ // `Sub` panics when the result leaves chrono's year range, which a large ceiling reaches.
+ let earliest = now
+ .checked_sub_signed(max_past)
+ .unwrap_or(DateTime::<Utc>::MIN_UTC);
+
+ if timestamp < earliest || timestamp > now + TimeDelta::hours(MAX_FUTURE_HOURS) {
(now, Some(timestamp))
} else {
(timestamp, None)
@@ -213,7 +233,15 @@ pub(crate) fn apply_timestamp_override(
raw: DateTime<Utc>,
attributes: &mut HashMap<String, String>,
) -> (DateTime<Utc>, bool) {
- let (timestamp, original) = override_timestamp(raw);
+ apply_timestamp_override_with_past_limit(raw, attributes, default_max_past())
+}
+
+pub(crate) fn apply_timestamp_override_with_past_limit(
+ raw: DateTime<Utc>,
+ attributes: &mut HashMap<String, String>,
+ max_past: TimeDelta,
+) -> (DateTime<Utc>, bool) {
+ let (timestamp, original) = override_timestamp_with_past_limit(raw, max_past);
if let Some(original) = original {
attributes.insert("$originalTimestamp".to_string(), original.to_rfc3339());
}
@@ -562,7 +590,7 @@ mod tests {
#[test]
fn test_new_populates_bytes_uncompressed() {
let log_record = LogRecord::default();
- let (row, _) = KafkaLogRow::new(log_record, None, None).expect("ok");
+ let (row, _) = KafkaLogRow::new(log_record, None, None, default_max_past()).expect("ok");
assert!(row.bytes_uncompressed.is_some());
assert_eq!(
row.bytes_uncompressed.unwrap(),
@@ -571,47 +599,86 @@ mod tests {
}
#[test]
- fn test_override_timestamp_within_range_is_unchanged() {
- let now = Utc::now();
- let one_hour_ago = now - TimeDelta::hours(1);
- let (final_ts, original) = override_timestamp(one_hour_ago);
- assert_eq!(final_ts, one_hour_ago);
- assert!(original.is_none());
- }
+ fn override_timestamp_keeps_a_timestamp_inside_the_window() {
+ let wide_past = TimeDelta::days(500);
- #[test]
- fn test_override_timestamp_far_past_is_overridden() {
- let now = Utc::now();
- let two_days_ago = now - TimeDelta::hours(48);
- let (final_ts, original) = override_timestamp(two_days_ago);
- assert!((final_ts - now).num_seconds().abs() < 2);
- assert_eq!(original.unwrap(), two_days_ago);
+ for (case, offset, max_past) in [
+ ("an hour ago", TimeDelta::hours(-1), default_max_past()),
+ (
+ "just inside the default bound",
+ TimeDelta::hours(-22),
+ default_max_past(),
+ ),
+ (
+ "400 days ago, inside a widened bound",
+ TimeDelta::days(-400),
+ wide_past,
+ ),
+ ] {
+ let now = Utc::now();
+ let timestamp = now + offset;
+
+ let (final_ts, original) = override_timestamp_with_past_limit(timestamp, max_past);
+
+ assert_eq!(final_ts, timestamp, "{case}");
+ assert!(original.is_none(), "{case}");
+ }
}
#[test]
- fn test_override_timestamp_far_future_is_overridden() {
- let now = Utc::now();
- let two_days_ahead = now + TimeDelta::hours(48);
- let (final_ts, original) = override_timestamp(two_days_ahead);
- assert!((final_ts - now).num_seconds().abs() < 2);
- assert_eq!(original.unwrap(), two_days_ahead);
+ fn override_timestamp_replaces_a_timestamp_outside_the_window() {
+ let wide_past = TimeDelta::days(500);
+
+ for (case, offset, max_past) in [
+ (
+ "just past the default bound",
+ TimeDelta::hours(-24) - TimeDelta::seconds(1),
+ default_max_past(),
+ ),
+ ("two days ago", TimeDelta::hours(-48), default_max_past()),
+ (
+ "400 days ago, past a narrower widened bound",
+ TimeDelta::days(-400),
+ TimeDelta::days(300),
+ ),
+ (
+ "a day ahead, widened past bound",
+ TimeDelta::hours(25),
+ wide_past,
+ ),
+ ] {
+ let now = Utc::now();
+ let timestamp = now + offset;
+
+ let (final_ts, original) = override_timestamp_with_past_limit(timestamp, max_past);
+
+ assert!(
+ (final_ts - now).num_seconds().abs() < 2,
+ "{case}: expected the ingest time, got {final_ts}"
+ );
+ assert_eq!(original.unwrap(), timestamp, "{case}");
+ }
}
#[test]
- fn test_override_timestamp_at_boundary_is_not_overridden() {
- let now = Utc::now();
- let just_within = now - TimeDelta::hours(22);
- let (final_ts, original) = override_timestamp(just_within);
- assert_eq!(final_ts, just_within);
+ fn override_timestamp_keeps_a_timestamp_under_an_oversized_past_bound() {
+ let timestamp = Utc::now() - TimeDelta::days(400);
+
+ // A bound this wide makes `now - max_past` leave chrono's range.
+ let (final_ts, original) =
+ override_timestamp_with_past_limit(timestamp, TimeDelta::days(200_000_000));
+
+ assert_eq!(final_ts, timestamp);
assert!(original.is_none());
}
#[test]
- fn test_override_timestamp_just_past_boundary_is_overridden() {
- let now = Utc::now();
- let just_outside = now - TimeDelta::hours(24) - TimeDelta::seconds(1);
- let (final_ts, original) = override_timestamp(just_outside);
- assert!((final_ts - now).num_seconds().abs() < 2);
- assert_eq!(original.unwrap(), just_outside);
+ fn override_timestamp_applies_a_24_hour_past_bound() {
+ // Asserts the original only: the replacement is the ingest time, which races the clock.
+ let inside = Utc::now() - TimeDelta::hours(23);
+ let outside = Utc::now() - TimeDelta::hours(25);
+
+ assert!(override_timestamp(inside).1.is_none());
+ assert_eq!(override_timestamp(outside).1, Some(outside));
}
}
diff --git a/rust/capture-logs/src/main.rs b/rust/capture-logs/src/main.rs
index 67a528e501c4..b2abf447651f 100644
--- a/rust/capture-logs/src/main.rs
+++ b/rust/capture-logs/src/main.rs
@@ -126,6 +126,7 @@ async fn main() {
authorizer,
config.max_request_body_size_bytes,
config.firehose_max_request_body_size_bytes,
+ config.max_backfill_days,
)
.await
{
diff --git a/rust/capture-logs/src/metric_record.rs b/rust/capture-logs/src/metric_record.rs
index 864d9619be19..eab62d41e929 100644
--- a/rust/capture-logs/src/metric_record.rs
+++ b/rust/capture-logs/src/metric_record.rs
@@ -5,7 +5,6 @@ use anyhow::Result;
use base64::{prelude::BASE64_STANDARD, Engine};
use chrono::serde::ts_microseconds;
use chrono::DateTime;
-use chrono::TimeDelta;
use chrono::Utc;
use opentelemetry_proto::tonic::{
common::v1::{
@@ -23,7 +22,7 @@ use siphasher::sip::SipHasher13;
use tracing::debug;
use uuid::Uuid;
-use crate::log_record::{extract_span_id, extract_trace_id};
+use crate::log_record::{extract_span_id, extract_trace_id, override_timestamp};
#[derive(Debug, Serialize, Deserialize)]
pub struct KafkaMetricRow {
@@ -452,19 +451,6 @@ fn temporality_str(temporality: i32) -> String {
}
}
-const TIMESTAMP_OVERRIDE_HOURS: i64 = 24;
-
-pub fn override_timestamp(timestamp: DateTime<Utc>) -> (DateTime<Utc>, Option<DateTime<Utc>>) {
- let now = Utc::now();
- let max_delta = TimeDelta::hours(TIMESTAMP_OVERRIDE_HOURS);
-
- if timestamp < now - max_delta || timestamp > now + max_delta {
- (now, Some(timestamp))
- } else {
- (timestamp, None)
- }
-}
-
fn extract_string_from_map(attributes: &HashMap<String, String>, key: &str) -> String {
if let Some(value) = attributes.get(key) {
if let Ok(JsonValue::String(value)) = serde_json::from_str::<JsonValue>(value) {
@@ -534,33 +520,7 @@ fn any_value_to_string(value: AnyValue) -> String {
#[cfg(test)]
mod tests {
use super::*;
-
- #[test]
- fn test_override_timestamp_within_range_is_unchanged() {
- let now = Utc::now();
- let one_hour_ago = now - TimeDelta::hours(1);
- let (final_ts, original) = override_timestamp(one_hour_ago);
- assert_eq!(final_ts, one_hour_ago);
- assert!(original.is_none());
- }
-
- #[test]
- fn test_override_timestamp_far_past_is_overridden() {
- let now = Utc::now();
- let two_days_ago = now - TimeDelta::hours(48);
- let (final_ts, original) = override_timestamp(two_days_ago);
- assert!((final_ts - now).num_seconds().abs() < 2);
- assert_eq!(original.unwrap(), two_days_ago);
- }
-
- #[test]
- fn test_override_timestamp_far_future_is_overridden() {
- let now = Utc::now();
- let two_days_ahead = now + TimeDelta::hours(48);
- let (final_ts, original) = override_timestamp(two_days_ahead);
- assert!((final_ts - now).num_seconds().abs() < 2);
- assert_eq!(original.unwrap(), two_days_ahead);
- }
+ use chrono::TimeDelta;
#[test]
fn test_number_value_as_double() {
diff --git a/rust/capture-logs/src/service.rs b/rust/capture-logs/src/service.rs
index 31e300fbaf26..e21af11b1b6a 100644
--- a/rust/capture-logs/src/service.rs
+++ b/rust/capture-logs/src/service.rs
@@ -1,5 +1,5 @@
use crate::authorizer::{Authorizer, Signal};
-use crate::log_record::KafkaLogRow;
+use crate::log_record::{default_max_past, KafkaLogRow};
use crate::metric_record::{flatten_metric, KafkaMetricRow};
use crate::trace_record::KafkaTraceRow;
use axum::{
@@ -9,6 +9,7 @@ use axum::{
response::Json,
};
use bytes::Bytes;
+use chrono::TimeDelta;
use common_compression::{decompress_gzip_capped, has_gzip_magic_header, CompressionError};
use opentelemetry_proto::tonic::collector::logs::v1::ExportLogsServiceRequest;
use opentelemetry_proto::tonic::collector::metrics::v1::ExportMetricsServiceRequest;
@@ -305,6 +306,7 @@ pub struct Service {
pub(crate) authorizer: Authorizer,
pub(crate) max_request_body_size_bytes: usize,
pub(crate) firehose_max_request_body_size_bytes: usize,
+ pub(crate) max_backfill_days: u32,
}
#[derive(Deserialize)]
@@ -312,18 +314,26 @@ pub struct QueryParams {
token: Option<String>,
}
+/// Logs-only, so the traces and metrics handlers cannot accept a parameter they do not honor.
+#[derive(Deserialize)]
+pub struct BackfillParams {
+ backfill_days: Option<u32>,
+}
+
impl Service {
pub async fn new(
kafka_sink: KafkaSink,
authorizer: Authorizer,
max_request_body_size_bytes: usize,
firehose_max_request_body_size_bytes: usize,
+ max_backfill_days: u32,
) -> Result<Self, anyhow::Error> {
Ok(Self {
sink: kafka_sink,
authorizer,
max_request_body_size_bytes,
firehose_max_request_body_size_bytes,
+ max_backfill_days,
})
}
}
@@ -353,6 +363,29 @@ pub(crate) fn gunzip_if_magic(
}
}
+/// An over-wide request is rejected, not narrowed to the default. A quietly narrowed import
+/// writes most of its records onto the ingest time and still returns 200, so nobody notices.
+pub(crate) fn resolve_backfill_window(
+ requested_days: Option<u32>,
+ max_backfill_days: u32,
+) -> Result<TimeDelta, String> {
+ let Some(days) = requested_days else {
+ return Ok(default_max_past());
+ };
+
+ if max_backfill_days == 0 {
+ return Err("This deployment does not accept backdated logs. Remove backfill_days, or contact PostHog support to turn on historical imports.".to_string());
+ }
+
+ if days == 0 || days > max_backfill_days {
+ return Err(format!(
+ "backfill_days {days} is outside the accepted range. Use a value between 1 and {max_backfill_days}."
+ ));
+ }
+
+ Ok(TimeDelta::days(days as i64))
+}
+
pub(crate) fn decode_body_if_gzip_magic(
body: Bytes,
max_request_body_size_bytes: usize,
@@ -382,6 +415,7 @@ pub(crate) fn decode_body_if_gzip_magic(
pub async fn export_logs_http(
State(service): State<Service>,
Query(query_params): Query<QueryParams>,
+ Query(backfill_params): Query<BackfillParams>,
headers: HeaderMap,
body: Bytes,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
@@ -392,6 +426,10 @@ pub async fn export_logs_http(
tracing::Span::current().record("token", token);
+ let max_past =
+ resolve_backfill_window(backfill_params.backfill_days, service.max_backfill_days)
+ .map_err(|message| (StatusCode::BAD_REQUEST, Json(json!({ "error": message }))))?;
+
let body = decode_body_if_gzip_magic(body, service.max_request_body_size_bytes)?;
// Try to decode as Protobuf, if this fails, try JSON.
@@ -433,6 +471,7 @@ pub async fn export_logs_http(
log_record,
resource_logs.resource.clone(),
scope_logs.scope.clone(),
+ max_past,
) {
Ok(result) => result,
Err(e) => {
@@ -777,6 +816,41 @@ mod tests {
assert_eq!(decoded, Bytes::from_static(br#"{"resourceLogs":[]}"#));
}
+ #[test]
+ fn resolve_backfill_window_defaults_when_no_window_is_requested() {
+ for (case, ceiling) in [("backfill off", 0), ("backfill on", 400)] {
+ let window = resolve_backfill_window(None, ceiling);
+
+ assert_eq!(window, Ok(default_max_past()), "{case}");
+ }
+ }
+
+ #[test]
+ fn resolve_backfill_window_accepts_a_window_within_the_ceiling() {
+ for (case, days, ceiling) in [
+ ("at the ceiling", 400, 400),
+ ("under the ceiling", 30, 400),
+ ("the smallest window", 1, 400),
+ ] {
+ let window = resolve_backfill_window(Some(days), ceiling);
+
+ assert_eq!(window, Ok(TimeDelta::days(days as i64)), "{case}");
+ }
+ }
+
+ #[test]
+ fn resolve_backfill_window_rejects_a_window_it_cannot_grant() {
+ for (case, days, ceiling) in [
+ ("above the ceiling", 401, 400),
+ ("zero is not a window", 0, 400),
+ ("any window where backfill is off", 1, 0),
+ ] {
+ let window = resolve_backfill_window(Some(days), ceiling);
+
+ assert!(window.is_err(), "{case}");
+ }
+ }
+
#[test]
fn decode_body_if_gzip_magic_preserves_plain_body() {
let body = Bytes::from_static(br#"{"resourceLogs":[]}"#);
diff --git a/rust/capture-logs/tests/service_test.rs b/rust/capture-logs/tests/service_test.rs
index 19003a55261f..c739eb482b4a 100644
--- a/rust/capture-logs/tests/service_test.rs
+++ b/rust/capture-logs/tests/service_test.rs
@@ -571,7 +571,7 @@ fn test_parse_jsonl_with_empty_resource_logs() {
}
#[test]
fn test_otel_log_row_overridden_timestamp_tracking() {
- use capture_logs::log_record::KafkaLogRow;
+ use capture_logs::log_record::{default_max_past, KafkaLogRow};
use chrono::{TimeDelta, Utc};
use opentelemetry_proto::tonic::{
common::v1::{any_value, AnyValue},
@@ -593,7 +593,7 @@ fn test_otel_log_row_overridden_timestamp_tracking() {
};
let (row_overridden, was_overridden) =
- KafkaLogRow::new(log_record_overridden, None, None).unwrap();
+ KafkaLogRow::new(log_record_overridden, None, None, default_max_past()).unwrap();
assert!(was_overridden);
assert!(row_overridden.attributes.contains_key("$originalTimestamp"));
@@ -612,7 +612,7 @@ fn test_otel_log_row_overridden_timestamp_tracking() {
};
let (row_overridden, was_overridden) =
- KafkaLogRow::new(log_record_overridden, None, None).unwrap();
+ KafkaLogRow::new(log_record_overridden, None, None, default_max_past()).unwrap();
assert!(was_overridden);
assert!(row_overridden.attributes.contains_key("$originalTimestamp"));
@@ -630,7 +630,8 @@ fn test_otel_log_row_overridden_timestamp_tracking() {
..Default::default()
};
- let (row_recent, was_not_overridden) = KafkaLogRow::new(log_record_recent, None, None).unwrap();
+ let (row_recent, was_not_overridden) =
+ KafkaLogRow::new(log_record_recent, None, None, default_max_past()).unwrap();
assert!(!was_not_overridden);
assert!(!row_recent.attributes.contains_key("$originalTimestamp"));
}