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): keep volume buckets as long as the team's logs (#103044)

Jon McCallume6fddf270075
diff --git a/docs/internal/logs-anomaly-bands.md b/docs/internal/logs-anomaly-bands.md
index c440e9759543..95eb546e76d4 100644
--- a/docs/internal/logs-anomaly-bands.md
+++ b/docs/internal/logs-anomaly-bands.md
@@ -8,6 +8,15 @@ The API keeps the existing `lower`, `upper`, and `verdict` fields.
## History and readiness
+The volume rollup keeps each bucket for at least 42 days or until its latest raw-log expiry, whichever is later.
+The lifetime is measured from the five-minute bucket start and rounded up to whole days, so timestamp skew and bucket rounding cannot shorten it.
+A 3650-day guard bounds corrupt expiry values, and rows written before the retention migration keep the 42-day floor.
+Rows can expire independently within a shared part; deletion happens during ClickHouse merges, not at an exact wall-clock deadline.
+
+Storage retention does not extend the chart's supported date range by itself.
+The chart still limits the start of a displayed window to 35 days ago; longer history needs a separate reader, API, and UI change.
+The on-demand anomaly scan queries raw logs rather than this rollup, so this storage change does not extend its history.
+
The chart uses complete UTC weeks before the displayed window, up to the five-week lookback.
It needs at least four complete weeks: two to fit the weekly pattern and count variability, followed by two separate weeks to calibrate the prediction errors.
With five available weeks, three train the model and two calibrate it.
diff --git a/posthog/clickhouse/hcl/golden/dev/logs.hcl b/posthog/clickhouse/hcl/golden/dev/logs.hcl
index 26f92c6b1fc1..ff2ed1de78a6 100644
--- a/posthog/clickhouse/hcl/golden/dev/logs.hcl
+++ b/posthog/clickhouse/hcl/golden/dev/logs.hcl
@@ -761,10 +761,10 @@ SQL
table "logs_volume_buckets" {
order_by = ["team_id", "time_bucket", "service_name", "namespace", "environment", "severity_text"]
partition_by = "toDate(time_bucket)"
- ttl = "time_bucket + toIntervalDay(42)"
+ ttl = "time_bucket + toIntervalDay(greatest(42, retention_days))"
settings = {
index_granularity = "8192"
- ttl_only_drop_parts = "1"
+ ttl_only_drop_parts = "0"
}
column "team_id" {
type = "Int32"
@@ -785,6 +785,9 @@ SQL
column "severity_text" {
type = "LowCardinality(String)"
}
+ column "retention_days" {
+ type = "SimpleAggregateFunction(max, UInt16)"
+ }
column "log_count" {
type = "SimpleAggregateFunction(sum, UInt64)"
}
@@ -814,6 +817,9 @@ SQL
column "severity_text" {
type = "LowCardinality(String)"
}
+ column "retention_days" {
+ type = "SimpleAggregateFunction(max, UInt16)"
+ }
column "log_count" {
type = "SimpleAggregateFunction(sum, UInt64)"
}
@@ -3706,6 +3712,7 @@ SELECT
namespace,
environment,
severity_text,
+ maxSimpleState(retention_days) AS retention_days,
sumSimpleState(1) AS log_count
FROM
(
@@ -3727,7 +3734,17 @@ FROM
resource_attributes['env']
)
) AS environment,
- lower(severity_text) AS severity_text
+ lower(severity_text) AS severity_text,
+ toUInt16(
+ least(
+ intDiv(
+ greatest(dateDiff('microsecond', time_bucket, original_expiry_timestamp), 0)
+ + 86399999999,
+ 86400000000
+ ),
+ 3650
+ )
+ ) AS retention_days
FROM posthog.logs34
)
GROUP BY
@@ -3752,6 +3769,9 @@ SQL
column "severity_text" {
type = "LowCardinality(String)"
}
+ column "retention_days" {
+ type = "SimpleAggregateFunction(max, UInt16)"
+ }
column "log_count" {
type = "SimpleAggregateFunction(sum, UInt64)"
}
diff --git a/posthog/clickhouse/hcl/golden/local-multi/logs.hcl b/posthog/clickhouse/hcl/golden/local-multi/logs.hcl
index e6a4c3ce72ac..e96c9918dc1c 100644
--- a/posthog/clickhouse/hcl/golden/local-multi/logs.hcl
+++ b/posthog/clickhouse/hcl/golden/local-multi/logs.hcl
@@ -1325,10 +1325,10 @@ SQL
table "logs_volume_buckets" {
order_by = ["team_id", "time_bucket", "service_name", "namespace", "environment", "severity_text"]
partition_by = "toDate(time_bucket)"
- ttl = "time_bucket + toIntervalDay(42)"
+ ttl = "time_bucket + toIntervalDay(greatest(42, retention_days))"
settings = {
index_granularity = "8192"
- ttl_only_drop_parts = "1"
+ ttl_only_drop_parts = "0"
}
column "team_id" {
type = "Int32"
@@ -1349,6 +1349,9 @@ SQL
column "severity_text" {
type = "LowCardinality(String)"
}
+ column "retention_days" {
+ type = "SimpleAggregateFunction(max, UInt16)"
+ }
column "log_count" {
type = "SimpleAggregateFunction(sum, UInt64)"
}
@@ -1378,6 +1381,9 @@ SQL
column "severity_text" {
type = "LowCardinality(String)"
}
+ column "retention_days" {
+ type = "SimpleAggregateFunction(max, UInt16)"
+ }
column "log_count" {
type = "SimpleAggregateFunction(sum, UInt64)"
}
@@ -4450,6 +4456,7 @@ SELECT
namespace,
environment,
severity_text,
+ maxSimpleState(retention_days) AS retention_days,
sumSimpleState(1) AS log_count
FROM
(
@@ -4471,7 +4478,17 @@ FROM
resource_attributes['env']
)
) AS environment,
- lower(severity_text) AS severity_text
+ lower(severity_text) AS severity_text,
+ toUInt16(
+ least(
+ intDiv(
+ greatest(dateDiff('microsecond', time_bucket, original_expiry_timestamp), 0)
+ + 86399999999,
+ 86400000000
+ ),
+ 3650
+ )
+ ) AS retention_days
FROM posthog.logs34
)
GROUP BY
@@ -4496,6 +4513,9 @@ SQL
column "severity_text" {
type = "LowCardinality(String)"
}
+ column "retention_days" {
+ type = "SimpleAggregateFunction(max, UInt16)"
+ }
column "log_count" {
type = "SimpleAggregateFunction(sum, UInt64)"
}
diff --git a/posthog/clickhouse/hcl/golden/local-single/all.hcl b/posthog/clickhouse/hcl/golden/local-single/all.hcl
index 3f2ba1d2b02d..283282480b5d 100644
--- a/posthog/clickhouse/hcl/golden/local-single/all.hcl
+++ b/posthog/clickhouse/hcl/golden/local-single/all.hcl
@@ -5945,10 +5945,10 @@ SQL
table "logs_volume_buckets" {
order_by = ["team_id", "time_bucket", "service_name", "namespace", "environment", "severity_text"]
partition_by = "toDate(time_bucket)"
- ttl = "time_bucket + toIntervalDay(42)"
+ ttl = "time_bucket + toIntervalDay(greatest(42, retention_days))"
settings = {
index_granularity = "8192"
- ttl_only_drop_parts = "1"
+ ttl_only_drop_parts = "0"
}
column "team_id" {
type = "Int32"
@@ -5969,6 +5969,9 @@ SQL
column "severity_text" {
type = "LowCardinality(String)"
}
+ column "retention_days" {
+ type = "SimpleAggregateFunction(max, UInt16)"
+ }
column "log_count" {
type = "SimpleAggregateFunction(sum, UInt64)"
}
@@ -5998,6 +6001,9 @@ SQL
column "severity_text" {
type = "LowCardinality(String)"
}
+ column "retention_days" {
+ type = "SimpleAggregateFunction(max, UInt16)"
+ }
column "log_count" {
type = "SimpleAggregateFunction(sum, UInt64)"
}
@@ -21812,6 +21818,7 @@ SELECT
namespace,
environment,
severity_text,
+ maxSimpleState(retention_days) AS retention_days,
sumSimpleState(1) AS log_count
FROM
(
@@ -21833,7 +21840,17 @@ FROM
resource_attributes['env']
)
) AS environment,
- lower(severity_text) AS severity_text
+ lower(severity_text) AS severity_text,
+ toUInt16(
+ least(
+ intDiv(
+ greatest(dateDiff('microsecond', time_bucket, original_expiry_timestamp), 0)
+ + 86399999999,
+ 86400000000
+ ),
+ 3650
+ )
+ ) AS retention_days
FROM posthog.logs34
)
GROUP BY
@@ -21858,6 +21875,9 @@ SQL
column "severity_text" {
type = "LowCardinality(String)"
}
+ column "retention_days" {
+ type = "SimpleAggregateFunction(max, UInt16)"
+ }
column "log_count" {
type = "SimpleAggregateFunction(sum, UInt64)"
}
diff --git a/posthog/clickhouse/hcl/golden/prod-eu/logs.hcl b/posthog/clickhouse/hcl/golden/prod-eu/logs.hcl
index 2974525976cd..4593556aa2ad 100644
--- a/posthog/clickhouse/hcl/golden/prod-eu/logs.hcl
+++ b/posthog/clickhouse/hcl/golden/prod-eu/logs.hcl
@@ -911,10 +911,10 @@ SQL
table "logs_volume_buckets" {
order_by = ["team_id", "time_bucket", "service_name", "namespace", "environment", "severity_text"]
partition_by = "toDate(time_bucket)"
- ttl = "time_bucket + toIntervalDay(42)"
+ ttl = "time_bucket + toIntervalDay(greatest(42, retention_days))"
settings = {
index_granularity = "8192"
- ttl_only_drop_parts = "1"
+ ttl_only_drop_parts = "0"
}
column "team_id" {
type = "Int32"
@@ -935,6 +935,9 @@ SQL
column "severity_text" {
type = "LowCardinality(String)"
}
+ column "retention_days" {
+ type = "SimpleAggregateFunction(max, UInt16)"
+ }
column "log_count" {
type = "SimpleAggregateFunction(sum, UInt64)"
}
@@ -964,6 +967,9 @@ SQL
column "severity_text" {
type = "LowCardinality(String)"
}
+ column "retention_days" {
+ type = "SimpleAggregateFunction(max, UInt16)"
+ }
column "log_count" {
type = "SimpleAggregateFunction(sum, UInt64)"
}
@@ -4032,6 +4038,7 @@ SELECT
namespace,
environment,
severity_text,
+ maxSimpleState(retention_days) AS retention_days,
sumSimpleState(1) AS log_count
FROM
(
@@ -4053,7 +4060,17 @@ FROM
resource_attributes['env']
)
) AS environment,
- lower(severity_text) AS severity_text
+ lower(severity_text) AS severity_text,
+ toUInt16(
+ least(
+ intDiv(
+ greatest(dateDiff('microsecond', time_bucket, original_expiry_timestamp), 0)
+ + 86399999999,
+ 86400000000
+ ),
+ 3650
+ )
+ ) AS retention_days
FROM posthog.logs34
)
GROUP BY
@@ -4078,6 +4095,9 @@ SQL
column "severity_text" {
type = "LowCardinality(String)"
}
+ column "retention_days" {
+ type = "SimpleAggregateFunction(max, UInt16)"
+ }
column "log_count" {
type = "SimpleAggregateFunction(sum, UInt64)"
}
diff --git a/posthog/clickhouse/hcl/golden/prod-us/logs.hcl b/posthog/clickhouse/hcl/golden/prod-us/logs.hcl
index 147b95c3400d..f32a873d1ec3 100644
--- a/posthog/clickhouse/hcl/golden/prod-us/logs.hcl
+++ b/posthog/clickhouse/hcl/golden/prod-us/logs.hcl
@@ -911,10 +911,10 @@ SQL
table "logs_volume_buckets" {
order_by = ["team_id", "time_bucket", "service_name", "namespace", "environment", "severity_text"]
partition_by = "toDate(time_bucket)"
- ttl = "time_bucket + toIntervalDay(42)"
+ ttl = "time_bucket + toIntervalDay(greatest(42, retention_days))"
settings = {
index_granularity = "8192"
- ttl_only_drop_parts = "1"
+ ttl_only_drop_parts = "0"
}
column "team_id" {
type = "Int32"
@@ -935,6 +935,9 @@ SQL
column "severity_text" {
type = "LowCardinality(String)"
}
+ column "retention_days" {
+ type = "SimpleAggregateFunction(max, UInt16)"
+ }
column "log_count" {
type = "SimpleAggregateFunction(sum, UInt64)"
}
@@ -964,6 +967,9 @@ SQL
column "severity_text" {
type = "LowCardinality(String)"
}
+ column "retention_days" {
+ type = "SimpleAggregateFunction(max, UInt16)"
+ }
column "log_count" {
type = "SimpleAggregateFunction(sum, UInt64)"
}
@@ -4014,6 +4020,7 @@ SELECT
namespace,
environment,
severity_text,
+ maxSimpleState(retention_days) AS retention_days,
sumSimpleState(1) AS log_count
FROM
(
@@ -4035,7 +4042,17 @@ FROM
resource_attributes['env']
)
) AS environment,
- lower(severity_text) AS severity_text
+ lower(severity_text) AS severity_text,
+ toUInt16(
+ least(
+ intDiv(
+ greatest(dateDiff('microsecond', time_bucket, original_expiry_timestamp), 0)
+ + 86399999999,
+ 86400000000
+ ),
+ 3650
+ )
+ ) AS retention_days
FROM posthog.logs34
)
GROUP BY
@@ -4060,6 +4077,9 @@ SQL
column "severity_text" {
type = "LowCardinality(String)"
}
+ column "retention_days" {
+ type = "SimpleAggregateFunction(max, UInt16)"
+ }
column "log_count" {
type = "SimpleAggregateFunction(sum, UInt64)"
}
diff --git a/posthog/clickhouse/hcl/roles/logs/base/sql/logs34_to_volume_buckets.sql b/posthog/clickhouse/hcl/roles/logs/base/sql/logs34_to_volume_buckets.sql
index 7e3ceb49e729..7a8579665cbf 100644
--- a/posthog/clickhouse/hcl/roles/logs/base/sql/logs34_to_volume_buckets.sql
+++ b/posthog/clickhouse/hcl/roles/logs/base/sql/logs34_to_volume_buckets.sql
@@ -5,6 +5,7 @@ SELECT
namespace,
environment,
severity_text,
+ maxSimpleState(retention_days) AS retention_days,
sumSimpleState(1) AS log_count
FROM
(
@@ -26,7 +27,16 @@ FROM
resource_attributes['env']
)
) AS environment,
- lower(severity_text) AS severity_text
+ lower(severity_text) AS severity_text,
+ toUInt16(
+ least(
+ intDiv(
+ greatest(dateDiff('microsecond', time_bucket, original_expiry_timestamp), 0) + 86399999999,
+ 86400000000
+ ),
+ 3650
+ )
+ ) AS retention_days
FROM posthog.logs34
)
GROUP BY
diff --git a/posthog/clickhouse/hcl/roles/logs/base/tables.hcl b/posthog/clickhouse/hcl/roles/logs/base/tables.hcl
index 3c88eb052467..5ba62b99d817 100644
--- a/posthog/clickhouse/hcl/roles/logs/base/tables.hcl
+++ b/posthog/clickhouse/hcl/roles/logs/base/tables.hcl
@@ -193,6 +193,9 @@ database "posthog" {
column "severity_text" {
type = "LowCardinality(String)"
}
+ column "retention_days" {
+ type = "SimpleAggregateFunction(max, UInt16)"
+ }
column "log_count" {
type = "SimpleAggregateFunction(sum, UInt64)"
}
@@ -663,10 +666,10 @@ database "posthog" {
table "logs_volume_buckets" {
order_by = ["team_id", "time_bucket", "service_name", "namespace", "environment", "severity_text"]
partition_by = "toDate(time_bucket)"
- ttl = "time_bucket + toIntervalDay(42)"
+ ttl = "time_bucket + toIntervalDay(greatest(42, retention_days))"
settings = {
index_granularity = "8192"
- ttl_only_drop_parts = "1"
+ ttl_only_drop_parts = "0"
}
column "team_id" {
type = "Int32"
@@ -687,6 +690,9 @@ database "posthog" {
column "severity_text" {
type = "LowCardinality(String)"
}
+ column "retention_days" {
+ type = "SimpleAggregateFunction(max, UInt16)"
+ }
column "log_count" {
type = "SimpleAggregateFunction(sum, UInt64)"
}
@@ -716,6 +722,9 @@ database "posthog" {
column "severity_text" {
type = "LowCardinality(String)"
}
+ column "retention_days" {
+ type = "SimpleAggregateFunction(max, UInt16)"
+ }
column "log_count" {
type = "SimpleAggregateFunction(sum, UInt64)"
}
diff --git a/posthog/clickhouse/hcl/sql/dev/logs.sql b/posthog/clickhouse/hcl/sql/dev/logs.sql
index f91bbaf8f778..c68e8deccad2 100644
--- a/posthog/clickhouse/hcl/sql/dev/logs.sql
+++ b/posthog/clickhouse/hcl/sql/dev/logs.sql
@@ -219,8 +219,9 @@ CREATE TABLE posthog.logs_volume_buckets (
namespace LowCardinality(String),
environment LowCardinality(String),
severity_text LowCardinality(String),
+ retention_days SimpleAggregateFunction(max, UInt16),
log_count SimpleAggregateFunction(sum, UInt64)
-) ENGINE = ReplicatedAggregatingMergeTree('/clickhouse/tables/noshard/posthog.logs_volume_buckets', '{replica}-{shard}') ORDER BY (team_id, time_bucket, service_name, namespace, environment, severity_text) PARTITION BY toDate(time_bucket) TTL time_bucket + toIntervalDay(42) SETTINGS index_granularity = 8192, ttl_only_drop_parts = 1;
+) ENGINE = ReplicatedAggregatingMergeTree('/clickhouse/tables/noshard/posthog.logs_volume_buckets', '{replica}-{shard}') ORDER BY (team_id, time_bucket, service_name, namespace, environment, severity_text) PARTITION BY toDate(time_bucket) TTL time_bucket + toIntervalDay(greatest(42, retention_days)) SETTINGS index_granularity = 8192, ttl_only_drop_parts = 0;
CREATE TABLE posthog.logs_volume_buckets_distributed (
team_id Int32,
time_bucket DateTime('UTC') CODEC(DoubleDelta, ZSTD(1)),
@@ -228,6 +229,7 @@ CREATE TABLE posthog.logs_volume_buckets_distributed (
namespace LowCardinality(String),
environment LowCardinality(String),
severity_text LowCardinality(String),
+ retention_days SimpleAggregateFunction(max, UInt16),
log_count SimpleAggregateFunction(sum, UInt64)
) ENGINE = Distributed('logs', 'posthog', 'logs_volume_buckets');
CREATE TABLE posthog.metric_attributes (
@@ -1024,13 +1026,14 @@ FROM
GROUP BY
team_id, time_bucket, original_expiry_time_bucket, service_name, resource_fingerprint, severity_text, resource_attributes
);
-CREATE MATERIALIZED VIEW posthog.logs34_to_volume_buckets TO posthog.logs_volume_buckets (team_id Int32, time_bucket DateTime('UTC'), service_name LowCardinality(String), namespace LowCardinality(String), environment LowCardinality(String), severity_text LowCardinality(String), log_count SimpleAggregateFunction(sum, UInt64)) AS SELECT
+CREATE MATERIALIZED VIEW posthog.logs34_to_volume_buckets TO posthog.logs_volume_buckets (team_id Int32, time_bucket DateTime('UTC'), service_name LowCardinality(String), namespace LowCardinality(String), environment LowCardinality(String), severity_text LowCardinality(String), retention_days SimpleAggregateFunction(max, UInt16), log_count SimpleAggregateFunction(sum, UInt64)) AS SELECT
team_id,
time_bucket,
service_name,
namespace,
environment,
severity_text,
+ maxSimpleState(retention_days) AS retention_days,
sumSimpleState(1) AS log_count
FROM
(
@@ -1052,7 +1055,17 @@ FROM
resource_attributes['env']
)
) AS environment,
- lower(severity_text) AS severity_text
+ lower(severity_text) AS severity_text,
+ toUInt16(
+ least(
+ intDiv(
+ greatest(dateDiff('microsecond', time_bucket, original_expiry_timestamp), 0)
+ + 86399999999,
+ 86400000000
+ ),
+ 3650
+ )
+ ) AS retention_days
FROM posthog.logs34
)
GROUP BY
diff --git a/posthog/clickhouse/hcl/sql/local-multi/logs.sql b/posthog/clickhouse/hcl/sql/local-multi/logs.sql
index 225dad4140aa..3ffcaf305630 100644
--- a/posthog/clickhouse/hcl/sql/local-multi/logs.sql
+++ b/posthog/clickhouse/hcl/sql/local-multi/logs.sql
@@ -332,8 +332,9 @@ CREATE TABLE posthog.logs_volume_buckets (
namespace LowCardinality(String),
environment LowCardinality(String),
severity_text LowCardinality(String),
+ retention_days SimpleAggregateFunction(max, UInt16),
log_count SimpleAggregateFunction(sum, UInt64)
-) ENGINE = ReplicatedAggregatingMergeTree('/clickhouse/tables/noshard/posthog.logs_volume_buckets', '{replica}-{shard}') ORDER BY (team_id, time_bucket, service_name, namespace, environment, severity_text) PARTITION BY toDate(time_bucket) TTL time_bucket + toIntervalDay(42) SETTINGS index_granularity = 8192, ttl_only_drop_parts = 1;
+) ENGINE = ReplicatedAggregatingMergeTree('/clickhouse/tables/noshard/posthog.logs_volume_buckets', '{replica}-{shard}') ORDER BY (team_id, time_bucket, service_name, namespace, environment, severity_text) PARTITION BY toDate(time_bucket) TTL time_bucket + toIntervalDay(greatest(42, retention_days)) SETTINGS index_granularity = 8192, ttl_only_drop_parts = 0;
CREATE TABLE posthog.logs_volume_buckets_distributed (
team_id Int32,
time_bucket DateTime('UTC') CODEC(DoubleDelta, ZSTD(1)),
@@ -341,6 +342,7 @@ CREATE TABLE posthog.logs_volume_buckets_distributed (
namespace LowCardinality(String),
environment LowCardinality(String),
severity_text LowCardinality(String),
+ retention_days SimpleAggregateFunction(max, UInt16),
log_count SimpleAggregateFunction(sum, UInt64)
) ENGINE = Distributed('posthog_single_shard', 'posthog', 'logs_volume_buckets');
CREATE TABLE posthog.metric_attributes (
@@ -1197,13 +1199,14 @@ FROM
GROUP BY
team_id, time_bucket, original_expiry_time_bucket, service_name, resource_fingerprint, severity_text, resource_attributes
);
-CREATE MATERIALIZED VIEW posthog.logs34_to_volume_buckets TO posthog.logs_volume_buckets (team_id Int32, time_bucket DateTime('UTC'), service_name LowCardinality(String), namespace LowCardinality(String), environment LowCardinality(String), severity_text LowCardinality(String), log_count SimpleAggregateFunction(sum, UInt64)) AS SELECT
+CREATE MATERIALIZED VIEW posthog.logs34_to_volume_buckets TO posthog.logs_volume_buckets (team_id Int32, time_bucket DateTime('UTC'), service_name LowCardinality(String), namespace LowCardinality(String), environment LowCardinality(String), severity_text LowCardinality(String), retention_days SimpleAggregateFunction(max, UInt16), log_count SimpleAggregateFunction(sum, UInt64)) AS SELECT
team_id,
time_bucket,
service_name,
namespace,
environment,
severity_text,
+ maxSimpleState(retention_days) AS retention_days,
sumSimpleState(1) AS log_count
FROM
(
@@ -1225,7 +1228,17 @@ FROM
resource_attributes['env']
)
) AS environment,
- lower(severity_text) AS severity_text
+ lower(severity_text) AS severity_text,
+ toUInt16(
+ least(
+ intDiv(
+ greatest(dateDiff('microsecond', time_bucket, original_expiry_timestamp), 0)
+ + 86399999999,
+ 86400000000
+ ),
+ 3650
+ )
+ ) AS retention_days
FROM posthog.logs34
)
GROUP BY
diff --git a/posthog/clickhouse/hcl/sql/local-single/all.sql b/posthog/clickhouse/hcl/sql/local-single/all.sql
index 9a21a17c6ac2..210c9ff715fe 100644
--- a/posthog/clickhouse/hcl/sql/local-single/all.sql
+++ b/posthog/clickhouse/hcl/sql/local-single/all.sql
@@ -1223,8 +1223,9 @@ CREATE TABLE posthog.logs_volume_buckets (
namespace LowCardinality(String),
environment LowCardinality(String),
severity_text LowCardinality(String),
+ retention_days SimpleAggregateFunction(max, UInt16),
log_count SimpleAggregateFunction(sum, UInt64)
-) ENGINE = ReplicatedAggregatingMergeTree('/clickhouse/tables/noshard/posthog.logs_volume_buckets', '{replica}-{shard}') ORDER BY (team_id, time_bucket, service_name, namespace, environment, severity_text) PARTITION BY toDate(time_bucket) TTL time_bucket + toIntervalDay(42) SETTINGS index_granularity = 8192, ttl_only_drop_parts = 1;
+) ENGINE = ReplicatedAggregatingMergeTree('/clickhouse/tables/noshard/posthog.logs_volume_buckets', '{replica}-{shard}') ORDER BY (team_id, time_bucket, service_name, namespace, environment, severity_text) PARTITION BY toDate(time_bucket) TTL time_bucket + toIntervalDay(greatest(42, retention_days)) SETTINGS index_granularity = 8192, ttl_only_drop_parts = 0;
CREATE TABLE posthog.logs_volume_buckets_distributed (
team_id Int32,
time_bucket DateTime('UTC') CODEC(DoubleDelta, ZSTD(1)),
@@ -1232,6 +1233,7 @@ CREATE TABLE posthog.logs_volume_buckets_distributed (
namespace LowCardinality(String),
environment LowCardinality(String),
severity_text LowCardinality(String),
+ retention_days SimpleAggregateFunction(max, UInt16),
log_count SimpleAggregateFunction(sum, UInt64)
) ENGINE = Distributed('posthog_single_shard', 'posthog', 'logs_volume_buckets');
CREATE TABLE posthog.message_assets_data (
@@ -5180,13 +5182,14 @@ FROM
GROUP BY
team_id, time_bucket, original_expiry_time_bucket, service_name, resource_fingerprint, severity_text, resource_attributes
);
-CREATE MATERIALIZED VIEW posthog.logs34_to_volume_buckets TO posthog.logs_volume_buckets (team_id Int32, time_bucket DateTime('UTC'), service_name LowCardinality(String), namespace LowCardinality(String), environment LowCardinality(String), severity_text LowCardinality(String), log_count SimpleAggregateFunction(sum, UInt64)) AS SELECT
+CREATE MATERIALIZED VIEW posthog.logs34_to_volume_buckets TO posthog.logs_volume_buckets (team_id Int32, time_bucket DateTime('UTC'), service_name LowCardinality(String), namespace LowCardinality(String), environment LowCardinality(String), severity_text LowCardinality(String), retention_days SimpleAggregateFunction(max, UInt16), log_count SimpleAggregateFunction(sum, UInt64)) AS SELECT
team_id,
time_bucket,
service_name,
namespace,
environment,
severity_text,
+ maxSimpleState(retention_days) AS retention_days,
sumSimpleState(1) AS log_count
FROM
(
@@ -5208,7 +5211,17 @@ FROM
resource_attributes['env']
)
) AS environment,
- lower(severity_text) AS severity_text
+ lower(severity_text) AS severity_text,
+ toUInt16(
+ least(
+ intDiv(
+ greatest(dateDiff('microsecond', time_bucket, original_expiry_timestamp), 0)
+ + 86399999999,
+ 86400000000
+ ),
+ 3650
+ )
+ ) AS retention_days
FROM posthog.logs34
)
GROUP BY
diff --git a/posthog/clickhouse/hcl/sql/prod-eu/logs.sql b/posthog/clickhouse/hcl/sql/prod-eu/logs.sql
index ba77f7b2b4d7..be5956ca83f3 100644
--- a/posthog/clickhouse/hcl/sql/prod-eu/logs.sql
+++ b/posthog/clickhouse/hcl/sql/prod-eu/logs.sql
@@ -264,8 +264,9 @@ CREATE TABLE posthog.logs_volume_buckets (
namespace LowCardinality(String),
environment LowCardinality(String),
severity_text LowCardinality(String),
+ retention_days SimpleAggregateFunction(max, UInt16),
log_count SimpleAggregateFunction(sum, UInt64)
-) ENGINE = ReplicatedAggregatingMergeTree('/clickhouse/tables/noshard/posthog.logs_volume_buckets', '{replica}-{shard}') ORDER BY (team_id, time_bucket, service_name, namespace, environment, severity_text) PARTITION BY toDate(time_bucket) TTL time_bucket + toIntervalDay(42) SETTINGS index_granularity = 8192, ttl_only_drop_parts = 1;
+) ENGINE = ReplicatedAggregatingMergeTree('/clickhouse/tables/noshard/posthog.logs_volume_buckets', '{replica}-{shard}') ORDER BY (team_id, time_bucket, service_name, namespace, environment, severity_text) PARTITION BY toDate(time_bucket) TTL time_bucket + toIntervalDay(greatest(42, retention_days)) SETTINGS index_granularity = 8192, ttl_only_drop_parts = 0;
CREATE TABLE posthog.logs_volume_buckets_distributed (
team_id Int32,
time_bucket DateTime('UTC') CODEC(DoubleDelta, ZSTD(1)),
@@ -273,6 +274,7 @@ CREATE TABLE posthog.logs_volume_buckets_distributed (
namespace LowCardinality(String),
environment LowCardinality(String),
severity_text LowCardinality(String),
+ retention_days SimpleAggregateFunction(max, UInt16),
log_count SimpleAggregateFunction(sum, UInt64)
) ENGINE = Distributed('logs', 'posthog', 'logs_volume_buckets');
CREATE TABLE posthog.metric_attributes (
@@ -1117,13 +1119,14 @@ FROM
GROUP BY
team_id, time_bucket, original_expiry_time_bucket, service_name, resource_fingerprint, severity_text, resource_attributes
);
-CREATE MATERIALIZED VIEW posthog.logs34_to_volume_buckets TO posthog.logs_volume_buckets (team_id Int32, time_bucket DateTime('UTC'), service_name LowCardinality(String), namespace LowCardinality(String), environment LowCardinality(String), severity_text LowCardinality(String), log_count SimpleAggregateFunction(sum, UInt64)) AS SELECT
+CREATE MATERIALIZED VIEW posthog.logs34_to_volume_buckets TO posthog.logs_volume_buckets (team_id Int32, time_bucket DateTime('UTC'), service_name LowCardinality(String), namespace LowCardinality(String), environment LowCardinality(String), severity_text LowCardinality(String), retention_days SimpleAggregateFunction(max, UInt16), log_count SimpleAggregateFunction(sum, UInt64)) AS SELECT
team_id,
time_bucket,
service_name,
namespace,
environment,
severity_text,
+ maxSimpleState(retention_days) AS retention_days,
sumSimpleState(1) AS log_count
FROM
(
@@ -1145,7 +1148,17 @@ FROM
resource_attributes['env']
)
) AS environment,
- lower(severity_text) AS severity_text
+ lower(severity_text) AS severity_text,
+ toUInt16(
+ least(
+ intDiv(
+ greatest(dateDiff('microsecond', time_bucket, original_expiry_timestamp), 0)
+ + 86399999999,
+ 86400000000
+ ),
+ 3650
+ )
+ ) AS retention_days
FROM posthog.logs34
)
GROUP BY
diff --git a/posthog/clickhouse/hcl/sql/prod-us/logs.sql b/posthog/clickhouse/hcl/sql/prod-us/logs.sql
index a435019af360..363374b239b5 100644
--- a/posthog/clickhouse/hcl/sql/prod-us/logs.sql
+++ b/posthog/clickhouse/hcl/sql/prod-us/logs.sql
@@ -264,8 +264,9 @@ CREATE TABLE posthog.logs_volume_buckets (
namespace LowCardinality(String),
environment LowCardinality(String),
severity_text LowCardinality(String),
+ retention_days SimpleAggregateFunction(max, UInt16),
log_count SimpleAggregateFunction(sum, UInt64)
-) ENGINE = ReplicatedAggregatingMergeTree('/clickhouse/tables/noshard/posthog.logs_volume_buckets', '{replica}-{shard}') ORDER BY (team_id, time_bucket, service_name, namespace, environment, severity_text) PARTITION BY toDate(time_bucket) TTL time_bucket + toIntervalDay(42) SETTINGS index_granularity = 8192, ttl_only_drop_parts = 1;
+) ENGINE = ReplicatedAggregatingMergeTree('/clickhouse/tables/noshard/posthog.logs_volume_buckets', '{replica}-{shard}') ORDER BY (team_id, time_bucket, service_name, namespace, environment, severity_text) PARTITION BY toDate(time_bucket) TTL time_bucket + toIntervalDay(greatest(42, retention_days)) SETTINGS index_granularity = 8192, ttl_only_drop_parts = 0;
CREATE TABLE posthog.logs_volume_buckets_distributed (
team_id Int32,
time_bucket DateTime('UTC') CODEC(DoubleDelta, ZSTD(1)),
@@ -273,6 +274,7 @@ CREATE TABLE posthog.logs_volume_buckets_distributed (
namespace LowCardinality(String),
environment LowCardinality(String),
severity_text LowCardinality(String),
+ retention_days SimpleAggregateFunction(max, UInt16),
log_count SimpleAggregateFunction(sum, UInt64)
) ENGINE = Distributed('logs', 'posthog', 'logs_volume_buckets');
CREATE TABLE posthog.metric_attributes (
@@ -1111,13 +1113,14 @@ FROM
GROUP BY
team_id, time_bucket, original_expiry_time_bucket, service_name, resource_fingerprint, severity_text, resource_attributes
);
-CREATE MATERIALIZED VIEW posthog.logs34_to_volume_buckets TO posthog.logs_volume_buckets (team_id Int32, time_bucket DateTime('UTC'), service_name LowCardinality(String), namespace LowCardinality(String), environment LowCardinality(String), severity_text LowCardinality(String), log_count SimpleAggregateFunction(sum, UInt64)) AS SELECT
+CREATE MATERIALIZED VIEW posthog.logs34_to_volume_buckets TO posthog.logs_volume_buckets (team_id Int32, time_bucket DateTime('UTC'), service_name LowCardinality(String), namespace LowCardinality(String), environment LowCardinality(String), severity_text LowCardinality(String), retention_days SimpleAggregateFunction(max, UInt16), log_count SimpleAggregateFunction(sum, UInt64)) AS SELECT
team_id,
time_bucket,
service_name,
namespace,
environment,
severity_text,
+ maxSimpleState(retention_days) AS retention_days,
sumSimpleState(1) AS log_count
FROM
(
@@ -1139,7 +1142,17 @@ FROM
resource_attributes['env']
)
) AS environment,
- lower(severity_text) AS severity_text
+ lower(severity_text) AS severity_text,
+ toUInt16(
+ least(
+ intDiv(
+ greatest(dateDiff('microsecond', time_bucket, original_expiry_timestamp), 0)
+ + 86399999999,
+ 86400000000
+ ),
+ 3650
+ )
+ ) AS retention_days
FROM posthog.logs34
)
GROUP BY
diff --git a/posthog/clickhouse/logs/__init__.py b/posthog/clickhouse/logs/__init__.py
index 7a99a3ace1e7..fdcdc9c07d09 100644
--- a/posthog/clickhouse/logs/__init__.py
+++ b/posthog/clickhouse/logs/__init__.py
@@ -20,6 +20,7 @@ from .logs34 import (
LOGS34_TO_LOG_ATTRIBUTES3_MV,
LOGS34_TO_RESOURCE_ATTRIBUTES3_MV,
LOGS34_TO_VOLUME_BUCKETS_MV,
+ LOGS34_TO_VOLUME_BUCKETS_MV_SELECT,
LOGS_DISTRIBUTED_TABLE_SQL as LOGS34_DISTRIBUTED_TABLE_SQL,
WRITABLE_LOGS34_TABLE_SQL,
)
@@ -61,4 +62,5 @@ __all__ = [
"LOGS_PATTERN_BUCKETS_TABLE_SQL",
"LOGS_PATTERN_BUCKETS_DISTRIBUTED_TABLE_SQL",
"LOGS34_TO_VOLUME_BUCKETS_MV",
+ "LOGS34_TO_VOLUME_BUCKETS_MV_SELECT",
]
diff --git a/posthog/clickhouse/logs/logs34.py b/posthog/clickhouse/logs/logs34.py
index 048836fcd689..6c02f1d783f3 100644
--- a/posthog/clickhouse/logs/logs34.py
+++ b/posthog/clickhouse/logs/logs34.py
@@ -362,32 +362,29 @@ AS {KAFKA_LOGS34_AVRO_MV_SELECT()}
"""
-def LOGS34_TO_VOLUME_BUCKETS_MV():
+def LOGS34_TO_VOLUME_BUCKETS_MV_SELECT():
db = settings.CLICKHOUSE_LOGS_CLUSTER_DATABASE
# Groups rows exactly like _rollup_sql in
# products/logs/backend/temporal/volume_tick/aggregation.py, which carries
- # the reasoning for the environment fallback and severity lowercasing. The
- # 300s grid literal is frozen into the DDL at migration time; BUCKET_SECONDS
- # there must stay equal to it or the detector reads buckets this MV never
- # writes.
- return f"""
-CREATE MATERIALIZED VIEW IF NOT EXISTS {db}.logs34_to_volume_buckets TO {db}.logs_volume_buckets
-(
- `team_id` Int32,
- `time_bucket` DateTime('UTC'),
- `service_name` LowCardinality(String),
- `namespace` LowCardinality(String),
- `environment` LowCardinality(String),
- `severity_text` LowCardinality(String),
- `log_count` SimpleAggregateFunction(sum, UInt64)
-)
-AS SELECT
+ # the reasoning for the environment fallback and severity lowercasing;
+ # `retention_days` is a measure folded into each group, not a dimension.
+ # The 300s grid literal is frozen into the DDL at migration time;
+ # BUCKET_SECONDS there must stay equal to it or the detector reads buckets
+ # this MV never writes.
+ #
+ # `retention_days` rounds the lifetime from the bucket to the raw expiry up
+ # to whole days, so event-time skew and bucket rounding cannot expire the
+ # rollup before its logs. Microseconds preserve fractional-second expiries.
+ # The 3650-day guard sits above the product's retention ceiling and bounds
+ # corrupt expiries. Max keeps mixed retentions as long as the latest expiry.
+ return f"""SELECT
team_id,
time_bucket,
service_name,
namespace,
environment,
severity_text,
+ maxSimpleState(retention_days) AS retention_days,
sumSimpleState(1) AS log_count
FROM
(
@@ -409,10 +406,28 @@ FROM
resource_attributes['env']
)
) AS environment,
- lower(severity_text) AS severity_text
+ lower(severity_text) AS severity_text,
+ toUInt16(least(intDiv(greatest(dateDiff('microsecond', time_bucket, original_expiry_timestamp), 0) + 86399999999, 86400000000), 3650)) AS retention_days
FROM {db}.{TABLE_NAME}
)
-GROUP BY team_id, time_bucket, service_name, namespace, environment, severity_text
+GROUP BY team_id, time_bucket, service_name, namespace, environment, severity_text"""
+
+
+def LOGS34_TO_VOLUME_BUCKETS_MV():
+ db = settings.CLICKHOUSE_LOGS_CLUSTER_DATABASE
+ return f"""
+CREATE MATERIALIZED VIEW IF NOT EXISTS {db}.logs34_to_volume_buckets TO {db}.logs_volume_buckets
+(
+ `team_id` Int32,
+ `time_bucket` DateTime('UTC'),
+ `service_name` LowCardinality(String),
+ `namespace` LowCardinality(String),
+ `environment` LowCardinality(String),
+ `severity_text` LowCardinality(String),
+ `retention_days` SimpleAggregateFunction(max, UInt16),
+ `log_count` SimpleAggregateFunction(sum, UInt64)
+)
+AS {LOGS34_TO_VOLUME_BUCKETS_MV_SELECT()}
"""
diff --git a/posthog/clickhouse/logs/logs_volume_buckets.py b/posthog/clickhouse/logs/logs_volume_buckets.py
index 14a38bff024a..530a591b5e41 100644
--- a/posthog/clickhouse/logs/logs_volume_buckets.py
+++ b/posthog/clickhouse/logs/logs_volume_buckets.py
@@ -19,8 +19,13 @@ from posthog.clickhouse.table_engines import AggregatingMergeTree, Distributed,
# series per day are few enough that a dims-early key would make every granule
# span the whole day.
#
-# TTL is 42 days (6 weekly samples per time-of-week slot), independent of raw
-# log retention.
+# The TTL floor is 42 days, which buys 6 weekly samples per time-of-week slot.
+# A team whose raw logs outlive that keeps the rollup alongside them, so the
+# TTL takes whichever of the two is longer. `retention_days` is the bucket's
+# lifetime rounded up to whole days, folded with max: a series whose rows carry
+# mixed retentions lives at least as long as its longest lived log. Rows in one partition
+# carry different TTLs, so ttl_only_drop_parts is off; a whole-part drop would
+# hold every team's rows to the longest retention in the part.
TABLE_NAME = "logs_volume_buckets"
@@ -35,13 +40,14 @@ CREATE TABLE IF NOT EXISTS {settings.CLICKHOUSE_LOGS_CLUSTER_DATABASE}.{TABLE_NA
`namespace` LowCardinality(String),
`environment` LowCardinality(String),
`severity_text` LowCardinality(String),
+ `retention_days` SimpleAggregateFunction(max, UInt16),
`log_count` SimpleAggregateFunction(sum, UInt64)
)
ENGINE = {AggregatingMergeTree(TABLE_NAME, replication_scheme=ReplicationScheme.REPLICATED)}
PARTITION BY toDate(time_bucket)
ORDER BY (team_id, time_bucket, service_name, namespace, environment, severity_text)
-TTL time_bucket + INTERVAL 42 DAY
-SETTINGS index_granularity = 8192, ttl_only_drop_parts = 1
+TTL time_bucket + toIntervalDay(greatest(42, retention_days))
+SETTINGS index_granularity = 8192, ttl_only_drop_parts = 0
"""
diff --git a/posthog/clickhouse/migrations/0329_logs_volume_buckets_retention_ttl.py b/posthog/clickhouse/migrations/0329_logs_volume_buckets_retention_ttl.py
new file mode 100644
index 000000000000..f6f30014f8c1
--- /dev/null
+++ b/posthog/clickhouse/migrations/0329_logs_volume_buckets_retention_ttl.py
@@ -0,0 +1,43 @@
+from django.conf import settings
+
+from posthog.clickhouse.client.connection import NodeRole
+from posthog.clickhouse.client.migration_tools import run_sql_with_exceptions
+from posthog.clickhouse.logs import LOGS34_TO_VOLUME_BUCKETS_MV_SELECT
+
+DB = settings.CLICKHOUSE_LOGS_CLUSTER_DATABASE
+
+operations = [
+ # Rows written before this runs read as `retention_days` 0, so greatest(42, 0)
+ # reproduces the TTL they already carry. materialize_ttl_after_modify would
+ # rewrite every part to arrive back at its current state, so it is turned off.
+ run_sql_with_exceptions(
+ f"""
+ALTER TABLE {DB}.logs_volume_buckets
+ ADD COLUMN IF NOT EXISTS retention_days SimpleAggregateFunction(max, UInt16) AFTER severity_text,
+ MODIFY TTL time_bucket + toIntervalDay(greatest(42, retention_days))
+ SETTINGS materialize_ttl_after_modify = 0
+""",
+ node_roles=[NodeRole.LOGS],
+ sharded=False,
+ is_alter_on_replicated_table=True,
+ ),
+ run_sql_with_exceptions(
+ f"ALTER TABLE {DB}.logs_volume_buckets MODIFY SETTING ttl_only_drop_parts = 0",
+ node_roles=[NodeRole.LOGS],
+ sharded=False,
+ is_alter_on_replicated_table=True,
+ ),
+ run_sql_with_exceptions(
+ f"ALTER TABLE {DB}.logs_volume_buckets_distributed "
+ "ADD COLUMN IF NOT EXISTS retention_days SimpleAggregateFunction(max, UInt16) AFTER severity_text",
+ node_roles=[NodeRole.LOGS],
+ sharded=False,
+ is_alter_on_replicated_table=False,
+ ),
+ run_sql_with_exceptions(
+ f"ALTER TABLE {DB}.logs34_to_volume_buckets MODIFY QUERY\n{LOGS34_TO_VOLUME_BUCKETS_MV_SELECT()}",
+ node_roles=[NodeRole.LOGS],
+ sharded=False,
+ is_alter_on_replicated_table=False,
+ ),
+]
diff --git a/posthog/clickhouse/migrations/max_migration.txt b/posthog/clickhouse/migrations/max_migration.txt
index 6e9eaef8f55b..9085bc03afd1 100644
--- a/posthog/clickhouse/migrations/max_migration.txt
+++ b/posthog/clickhouse/migrations/max_migration.txt
@@ -1 +1 @@
-0328_sessions_v3_ws_pipeline
+0329_logs_volume_buckets_retention_ttl
diff --git a/posthog/clickhouse/test/__snapshots__/test_schema.ambr b/posthog/clickhouse/test/__snapshots__/test_schema.ambr
index a121f4f70548..3aaad87d8589 100644
--- a/posthog/clickhouse/test/__snapshots__/test_schema.ambr
+++ b/posthog/clickhouse/test/__snapshots__/test_schema.ambr
@@ -3882,6 +3882,7 @@
`namespace` LowCardinality(String),
`environment` LowCardinality(String),
`severity_text` LowCardinality(String),
+ `retention_days` SimpleAggregateFunction(max, UInt16),
`log_count` SimpleAggregateFunction(sum, UInt64)
)
AS SELECT
@@ -3891,6 +3892,7 @@
namespace,
environment,
severity_text,
+ maxSimpleState(retention_days) AS retention_days,
sumSimpleState(1) AS log_count
FROM
(
@@ -3912,7 +3914,8 @@
resource_attributes['env']
)
) AS environment,
- lower(severity_text) AS severity_text
+ lower(severity_text) AS severity_text,
+ toUInt16(least(intDiv(greatest(dateDiff('microsecond', time_bucket, original_expiry_timestamp), 0) + 86399999999, 86400000000), 3650)) AS retention_days
FROM posthog_test.logs34
)
GROUP BY team_id, time_bucket, service_name, namespace, environment, severity_text
@@ -4028,13 +4031,14 @@
`namespace` LowCardinality(String),
`environment` LowCardinality(String),
`severity_text` LowCardinality(String),
+ `retention_days` SimpleAggregateFunction(max, UInt16),
`log_count` SimpleAggregateFunction(sum, UInt64)
)
ENGINE = ReplicatedAggregatingMergeTree('/clickhouse/tables/77f1df52-4b43-11e9-910f-b8ca3a9b9f3e_noshard/posthog.logs_volume_buckets', '{replica}-{shard}')
PARTITION BY toDate(time_bucket)
ORDER BY (team_id, time_bucket, service_name, namespace, environment, severity_text)
- TTL time_bucket + INTERVAL 42 DAY
- SETTINGS index_granularity = 8192, ttl_only_drop_parts = 1
+ TTL time_bucket + toIntervalDay(greatest(42, retention_days))
+ SETTINGS index_granularity = 8192, ttl_only_drop_parts = 0
'''
# ---
@@ -11933,13 +11937,14 @@
`namespace` LowCardinality(String),
`environment` LowCardinality(String),
`severity_text` LowCardinality(String),
+ `retention_days` SimpleAggregateFunction(max, UInt16),
`log_count` SimpleAggregateFunction(sum, UInt64)
)
ENGINE = ReplicatedAggregatingMergeTree('/clickhouse/tables/77f1df52-4b43-11e9-910f-b8ca3a9b9f3e_noshard/posthog.logs_volume_buckets', '{replica}-{shard}')
PARTITION BY toDate(time_bucket)
ORDER BY (team_id, time_bucket, service_name, namespace, environment, severity_text)
- TTL time_bucket + INTERVAL 42 DAY
- SETTINGS index_granularity = 8192, ttl_only_drop_parts = 1
+ TTL time_bucket + toIntervalDay(greatest(42, retention_days))
+ SETTINGS index_granularity = 8192, ttl_only_drop_parts = 0
'''
# ---
diff --git a/posthog/clickhouse/test/test_schema.py b/posthog/clickhouse/test/test_schema.py
index d30746207dc4..d9c38fec0416 100644
--- a/posthog/clickhouse/test/test_schema.py
+++ b/posthog/clickhouse/test/test_schema.py
@@ -2,15 +2,19 @@ import re
import json
import uuid
from collections.abc import Iterator
+from datetime import UTC, datetime, timedelta
from pathlib import Path
import pytest
+from django.conf import settings as django_settings
+
from posthog.hogql.database.models import DatabaseField, Table
from posthog.hogql.database.schema.flag_evaluations import FLAG_EVALUATIONS_CLICKHOUSE_TABLE, FlagEvaluationsTable
from posthog.clickhouse.client import sync_execute
from posthog.clickhouse.kafka_engine import CONSUMER_GROUP_EVENTS_JSON_NATIVE_JSON, KAFKA_COLUMNS_WITH_PARTITION
+from posthog.clickhouse.logs import LOGS34_TO_VOLUME_BUCKETS_MV_SELECT
from posthog.clickhouse.schema import (
CREATE_KAFKA_TABLE_QUERIES,
CREATE_MERGETREE_TABLE_QUERIES,
@@ -111,6 +115,61 @@ def test_person_property_mutation_projection(properties: dict[str, object], expe
assert [json.loads(row[2]) for row in rows] == ([] if expected is None else [expected])
+ "timestamp_offset,observed_delay,retentions,expected_days",
+ [
+ (timedelta(), timedelta(), [90], 90),
+ (timedelta(), timedelta(hours=23), [90], 91),
+ (timedelta(), timedelta(hours=-23), [90], 90),
+ (timedelta(minutes=4, seconds=59), timedelta(), [90], 91),
+ (timedelta(microseconds=1), timedelta(), [90], 91),
+ (timedelta(), timedelta(), [14], 14),
+ (timedelta(), timedelta(), [30, 90], 90),
+ (timedelta(), timedelta(), [-7], 0),
+ (timedelta(), timedelta(), [5000], 3650),
+ ],
+ ids=["aligned", "backdated", "future", "bucket_rounding", "subsecond", "floor", "mixed", "negative", "clamp"],
+)
+def test_logs_volume_bucket_retention_covers_raw_expiry(
+ timestamp_offset: timedelta,
+ observed_delay: timedelta,
+ retentions: list[int],
+ expected_days: int,
+) -> None:
+ bucket_start = datetime(2026, 1, 2, 12, tzinfo=UTC)
+ timestamp = bucket_start + timestamp_offset
+ observed_timestamp = timestamp + observed_delay
+ select = LOGS34_TO_VOLUME_BUCKETS_MV_SELECT().replace(
+ f"FROM {django_settings.CLICKHOUSE_LOGS_CLUSTER_DATABASE}.logs34", "FROM retention_input"
+ )
+ rows = sync_execute(
+ """
+ WITH retention_input AS (
+ SELECT
+ 42 AS team_id,
+ toDateTime64(%(timestamp)s, 6, 'UTC') AS timestamp,
+ toDateTime64(%(observed_timestamp)s, 6, 'UTC') AS observed_timestamp,
+ observed_timestamp + toIntervalDay(arrayJoin(%(retentions)s)) AS original_expiry_timestamp,
+ 'checkout' AS service_name,
+ 'INFO' AS severity_text,
+ CAST(map(), 'Map(String, String)') AS resource_attributes
+ )
+ SELECT retention_days, log_count FROM ("""
+ + select
+ + ")",
+ {
+ "timestamp": timestamp.strftime("%Y-%m-%d %H:%M:%S.%f"),
+ "observed_timestamp": observed_timestamp.strftime("%Y-%m-%d %H:%M:%S.%f"),
+ "retentions": retentions,
+ },
+ )
+ assert rows == [(expected_days, len(retentions))]
+ if max(retentions) <= 2580:
+ assert bucket_start + timedelta(days=max(42, rows[0][0])) >= observed_timestamp + timedelta(
+ days=max(retentions)
+ )
+
+
def _column_definition_lines(block: str) -> Iterator[str]:
for raw_line in block.splitlines():
line = raw_line.strip().lstrip(",").strip()