Skip to main content

cja/observability/
posthog.rs

1//! Reconcile one application's declarations against the `PostHog` project API.
2use super::{
3    Alert, Bucket, Comparison, Dashboard, Declarations, FilterOperator, FilterValue, Item,
4    MetricQuery, ProductAggregate, ProductEventMetric, RatioMetric, TelemetryMetric,
5};
6use eyes_subscriber::eyes_query::{
7    AggregateFunction as EyesAggregate, BinaryOp, Expr, FieldPath, Function, Literal,
8    MONDAY_ORIGIN_US, PathSegment, Stage,
9};
10use http::Method;
11use serde_json::{Value, json};
12use std::{
13    collections::{BTreeMap, BTreeSet},
14    error::Error,
15    fmt,
16    process::ExitCode,
17    time::Duration,
18};
19
20/// CI credentials and stable application identity.
21pub struct SyncConfig {
22    pub host: String,
23    pub api_key: String,
24    pub project_id: i64,
25    pub app: String,
26}
27
28#[cfg(test)]
29mod sql_tests {
30    use super::*;
31    use crate::observability::{ProductMetricBuilder, RatioMetricBuilder, TelemetryMetricBuilder};
32
33    fn telemetry(metric: &super::super::Metric) -> &TelemetryMetric {
34        let MetricQuery::Telemetry(metric) = &metric.query else {
35            panic!("expected telemetry")
36        };
37        metric
38    }
39
40    #[test]
41    fn log_count_has_exact_predicate_coverage_and_outer_limit() {
42        let metric = TelemetryMetricBuilder::new("games", EyesAggregate::Count, None)
43            .unwrap()
44            .filter_eq("fields.event_type", "game_completed")
45            .unwrap()
46            .build()
47            .unwrap();
48        assert_eq!(
49            telemetry_sql(telemetry(&metric), "arena", SqlWindow::trailing(3600)).unwrap(),
50            "SELECT if((SELECT count() FROM (SELECT 1 FROM logs WHERE service_name = 'arena' AND timestamp <= now() - INTERVAL 3600 SECOND LIMIT 1)) > 0, count(), NULL) AS value FROM (SELECT NULL AS _metric_value FROM logs WHERE service_name = 'arena' AND timestamp >= now() - INTERVAL 3600 SECOND AND attributes['event_type'] = 'game_completed') AS _source LIMIT 1"
51        );
52    }
53
54    #[test]
55    fn span_http_percentile_maps_semantics_and_duration_units() {
56        let metric = TelemetryMetricBuilder::new("http.p95", EyesAggregate::P95, Some("duration"))
57            .unwrap()
58            .filter_eq("semantic_kind", "http.request")
59            .unwrap()
60            .build()
61            .unwrap();
62        let sql = telemetry_sql(telemetry(&metric), "arena", SqlWindow::trailing(300)).unwrap();
63        assert_eq!(
64            sql,
65            concat!(
66                "SELECT if((SELECT count() FROM (SELECT 1 FROM posthog.trace_spans WHERE service_name = 'arena' AND timestamp <= now() - INTERVAL 300 SECOND LIMIT 1)) > 0, ",
67                "if(count(_metric_value) = 0, NULL, quantile(0.95)(_metric_value)), NULL) AS value FROM ",
68                "(SELECT duration_nano / 1000 AS _metric_value FROM posthog.trace_spans WHERE service_name = 'arena' AND timestamp >= now() - INTERVAL 300 SECOND AND ",
69                "(attributes['target'] = 'cja::server::trace' AND attributes['kind'] = 'server')) AS _source LIMIT 1"
70            )
71        );
72        assert!(sql.contains("FROM posthog.trace_spans"));
73        assert!(!sql.contains("FROM logs"));
74        assert!(sql.contains("duration_nano / 1000 AS _metric_value"));
75        assert!(sql.contains(
76            "attributes['target'] = 'cja::server::trace' AND attributes['kind'] = 'server'"
77        ));
78        assert!(sql.contains("quantile(0.95)(_metric_value)"));
79        assert!(sql.contains("timestamp <= now() - INTERVAL 300 SECOND"));
80    }
81
82    #[test]
83    fn every_aggregate_and_typed_where_operator_compiles() {
84        let functions = [
85            EyesAggregate::Count,
86            EyesAggregate::CountDistinct,
87            EyesAggregate::Sum,
88            EyesAggregate::Avg,
89            EyesAggregate::Min,
90            EyesAggregate::Max,
91            EyesAggregate::P50,
92            EyesAggregate::P90,
93            EyesAggregate::P95,
94            EyesAggregate::P99,
95        ];
96        let expected = [
97            "count()",
98            "count(DISTINCT _metric_value)",
99            "sum(_metric_value)",
100            "avg(_metric_value)",
101            "min(_metric_value)",
102            "max(_metric_value)",
103            "quantile(0.50)(_metric_value)",
104            "quantile(0.90)(_metric_value)",
105            "quantile(0.95)(_metric_value)",
106            "quantile(0.99)(_metric_value)",
107        ];
108        for (function, aggregate) in functions.into_iter().zip(expected) {
109            let argument = if function == EyesAggregate::Count {
110                None
111            } else if function == EyesAggregate::CountDistinct {
112                Some("fields.user_id")
113            } else {
114                Some("fields.duration_ms")
115            };
116            let metric = TelemetryMetricBuilder::new("sample", function, argument)
117                .unwrap()
118                .filter_eq("fields.event_type", "game_completed")
119                .unwrap()
120                .filter_eq("fields.enabled", true)
121                .unwrap()
122                .filter_eq("fields.attempt", 2_i64)
123                .unwrap()
124                .filter_gte("fields.duration_ms", 1.5_f64)
125                .unwrap()
126                .build()
127                .unwrap();
128            let sql = telemetry_sql(telemetry(&metric), "arena", SqlWindow::trailing(60)).unwrap();
129            assert!(sql.contains(aggregate), "{sql}");
130            assert!(sql.contains("attributes['enabled'] = 'true'"), "{sql}");
131            assert!(
132                sql.contains("toFloatOrNull(attributes['attempt']) = 2"),
133                "{sql}"
134            );
135            assert!(
136                sql.contains("toFloatOrNull(attributes['duration_ms']) >= 1.5e0"),
137                "{sql}"
138            );
139            assert!(!sql.contains("posthog.trace_spans"), "{sql}");
140        }
141    }
142
143    #[test]
144    fn numeric_guard_preserves_f64_min_without_a_huge_integer_literal() {
145        let metric =
146            TelemetryMetricBuilder::new("latency", EyesAggregate::P95, Some("fields.duration_ms"))
147                .unwrap()
148                .filter_eq("fields.metric_type", "queue_wait")
149                .unwrap()
150                .filter_numeric("fields.duration_ms")
151                .unwrap()
152                .build()
153                .unwrap();
154        let sql = telemetry_sql(telemetry(&metric), "arena", SqlWindow::trailing(300)).unwrap();
155        assert!(
156            sql.contains("toFloatOrNull(attributes['duration_ms']) >= -1.7976931348623157e308"),
157            "{sql}"
158        );
159        assert!(!sql.contains("posthog.trace_spans"));
160        assert!(sql.contains("if(count(_metric_value) = 0, NULL, quantile(0.95)(_metric_value))"));
161    }
162
163    #[test]
164    fn covered_empty_sum_is_null() {
165        let metric = TelemetryMetricBuilder::new(
166            "suppressed",
167            EyesAggregate::Sum,
168            Some("fields.suppressed"),
169        )
170        .unwrap()
171        .filter_eq("fields.event_type", "shout_screening")
172        .unwrap()
173        .build()
174        .unwrap();
175        let sql = telemetry_sql(telemetry(&metric), "arena", SqlWindow::trailing(3600)).unwrap();
176        assert!(
177            sql.contains("if((SELECT count() FROM (SELECT 1 FROM logs"),
178            "{sql}"
179        );
180        assert!(
181            sql.contains("if(count(_metric_value) = 0, NULL, sum(_metric_value))"),
182            "{sql}"
183        );
184    }
185
186    #[test]
187    fn covered_empty_product_sum_is_null() {
188        let metric = ProductMetricBuilder::sum("sales", "purchased", "amount")
189            .build()
190            .unwrap();
191        let MetricQuery::ProductEvent(product) = &metric.query else {
192            panic!("expected product metric")
193        };
194        let sql = product_plan(product, "arena", SqlWindow::trailing(3600))
195            .unwrap()
196            .sql;
197        assert!(
198            sql.contains("if(count(_metric_value) = 0, NULL, sum(_metric_value))"),
199            "{sql}"
200        );
201    }
202
203    #[test]
204    fn buckets_groups_escaping_and_dual_source_coverage() {
205        let metric = TelemetryMetricBuilder::new("route", EyesAggregate::Count, None)
206            .unwrap()
207            .filter_eq("fields[\"o'key\"]", "it's ok")
208            .unwrap()
209            .group_by("fields[\"http.route\"]")
210            .unwrap()
211            .time_bucket_weeks(1)
212            .build()
213            .unwrap();
214        let sql = telemetry_sql(telemetry(&metric), "arena", SqlWindow::trailing(604_800)).unwrap();
215        assert!(sql.contains("attributes['o''key'] = 'it''s ok'"), "{sql}");
216        assert!(
217            sql.contains("toDateTime64('1970-01-05 00:00:00', 6, 'UTC')"),
218            "{sql}"
219        );
220        assert!(sql.contains("AS bucket"));
221        assert!(sql.contains("AS _dim_0"));
222        assert!(sql.contains("ORDER BY bucket DESC, _dim_0 LIMIT 50000"));
223        assert!(sql.ends_with("ORDER BY bucket, _dim_0 LIMIT 50000"));
224        assert_eq!(
225            sql.matches("timestamp <= now() - INTERVAL 604800 SECOND")
226                .count(),
227            2
228        );
229        let node = sql_query(&sql, SqlDisplay::Line, 1);
230        assert_eq!(node["kind"], "DataVisualizationNode");
231        assert_eq!(node["source"]["kind"], "HogQLQuery");
232        assert_eq!(node["display"], "ActionsLineGraph");
233    }
234
235    #[test]
236    fn ratio_uses_each_operand_window_and_null_safe_division() {
237        let numerator = TelemetryMetricBuilder::new("daily", EyesAggregate::Count, None)
238            .unwrap()
239            .filter_eq("fields.event_type", "game_completed")
240            .unwrap()
241            .build()
242            .unwrap();
243        let denominator = TelemetryMetricBuilder::new("monthly", EyesAggregate::Count, None)
244            .unwrap()
245            .filter_eq("fields.event_type", "game_started")
246            .unwrap()
247            .build()
248            .unwrap();
249        let ratio = RatioMetricBuilder::new("share", "daily", "monthly")
250            .numerator_window_seconds(86_400)
251            .denominator_window_seconds(2_419_200)
252            .as_percentage()
253            .build()
254            .unwrap();
255        let MetricQuery::Ratio(spec) = &ratio.query else {
256            panic!("expected ratio")
257        };
258        let declarations = Declarations::new()
259            .metric(numerator)
260            .metric(denominator)
261            .metric(ratio.clone());
262        let sql = ratio_sql(spec, &declarations, "arena", SqlWindow::trailing(3600)).unwrap();
263        assert_eq!(
264            sql,
265            concat!(
266                "SELECT if(isNull(_num_value) OR isNull(_den_value) OR _den_value = 0, NULL, _num_value * 100 / _den_value) AS value ",
267                "FROM (SELECT value AS _num_value FROM (SELECT if((SELECT count() FROM (SELECT 1 FROM logs WHERE service_name = 'arena' AND timestamp <= now() - INTERVAL 86400 SECOND LIMIT 1)) > 0, ",
268                "count(), NULL) AS value FROM (SELECT NULL AS _metric_value FROM logs WHERE service_name = 'arena' AND timestamp >= now() - INTERVAL 86400 SECOND AND attributes['event_type'] = 'game_completed') AS _source LIMIT 1) LIMIT 1) AS _num ",
269                "CROSS JOIN (SELECT value AS _den_value FROM (SELECT if((SELECT count() FROM (SELECT 1 FROM logs WHERE service_name = 'arena' AND timestamp <= now() - INTERVAL 2419200 SECOND LIMIT 1)) > 0, ",
270                "count(), NULL) AS value FROM (SELECT NULL AS _metric_value FROM logs WHERE service_name = 'arena' AND timestamp >= now() - INTERVAL 2419200 SECOND AND attributes['event_type'] = 'game_started') AS _source LIMIT 1) LIMIT 1) AS _den LIMIT 1"
271            )
272        );
273        assert!(sql.contains("FROM logs"));
274        assert!(!sql.contains("FROM events"));
275        assert!(sql.contains("timestamp <= now() - INTERVAL 86400 SECOND"));
276        assert!(sql.contains("timestamp <= now() - INTERVAL 2419200 SECOND"));
277        assert!(sql.contains("isNull(_num_value) OR isNull(_den_value) OR _den_value = 0"));
278        assert!(sql.contains("_num_value * 100 / _den_value"));
279    }
280
281    #[test]
282    fn mixed_cluster_ratio_is_rejected_before_sql_generation() {
283        let numerator = TelemetryMetricBuilder::new("completed", EyesAggregate::Count, None)
284            .unwrap()
285            .filter_eq("fields.event_type", "game_completed")
286            .unwrap()
287            .build()
288            .unwrap();
289        let denominator = ProductMetricBuilder::count("played", "game_played")
290            .build()
291            .unwrap();
292        let ratio = RatioMetricBuilder::new("share", "completed", "played")
293            .build()
294            .unwrap();
295        let MetricQuery::Ratio(spec) = &ratio.query else {
296            panic!("expected ratio")
297        };
298        let declarations = Declarations::new()
299            .metric(numerator)
300            .metric(denominator)
301            .metric(ratio.clone());
302        assert!(
303            matches!(ratio_sql(spec, &declarations, "arena", SqlWindow::trailing(3600)), Err(SyncError::Invalid(message)) if message.contains("PostHog cannot query both clusters"))
304        );
305    }
306
307    #[test]
308    fn absent_source_field_cannot_be_a_group_dimension() {
309        let metric = TelemetryMetricBuilder::new("kinds", EyesAggregate::Count, None)
310            .unwrap()
311            .group_by("semantic_kind")
312            .unwrap()
313            .build()
314            .unwrap();
315        assert!(matches!(
316            telemetry_sql(telemetry(&metric), "arena", SqlWindow::trailing(3600)),
317            Err(SyncError::Invalid(message)) if message.contains("cannot group by") && message.contains("semantic_kind")
318        ));
319    }
320
321    #[test]
322    fn product_product_ratio_uses_each_operand_window() {
323        let numerator = ProductMetricBuilder::count("played", "game_played")
324            .build()
325            .unwrap();
326        let denominator = ProductMetricBuilder::count("started", "game_started")
327            .build()
328            .unwrap();
329        let ratio = RatioMetricBuilder::new("share", "played", "started")
330            .numerator_window_seconds(86_400)
331            .denominator_window_seconds(2_419_200)
332            .build()
333            .unwrap();
334        let MetricQuery::Ratio(spec) = &ratio.query else {
335            panic!("expected ratio")
336        };
337        let declarations = Declarations::new()
338            .metric(numerator)
339            .metric(denominator)
340            .metric(ratio.clone());
341        let sql = ratio_sql(spec, &declarations, "arena", SqlWindow::trailing(3600)).unwrap();
342        assert_eq!(
343            sql,
344            include_str!("../../tests/fixtures/posthog_product_ratio.sql").trim_end()
345        );
346        assert!(sql.contains("event = 'game_played'"));
347        assert!(sql.contains("event = 'game_started'"));
348    }
349
350    #[test]
351    fn table_numerator_scalar_denominator_uses_cross_join() {
352        let numerator = TelemetryMetricBuilder::new("routes", EyesAggregate::Count, None)
353            .unwrap()
354            .filter_eq("semantic_kind", "http.request")
355            .unwrap()
356            .group_by("fields.route")
357            .unwrap()
358            .build()
359            .unwrap();
360        let denominator = TelemetryMetricBuilder::new("requests", EyesAggregate::Count, None)
361            .unwrap()
362            .filter_eq("semantic_kind", "http.request")
363            .unwrap()
364            .build()
365            .unwrap();
366        let ratio = RatioMetricBuilder::new("route-share", "routes", "requests")
367            .build()
368            .unwrap();
369        let MetricQuery::Ratio(spec) = &ratio.query else {
370            panic!("expected ratio")
371        };
372        let declarations = Declarations::new()
373            .metric(numerator)
374            .metric(denominator)
375            .metric(ratio.clone());
376        let sql = ratio_sql(spec, &declarations, "arena", SqlWindow::trailing(3600)).unwrap();
377        assert_eq!(
378            sql,
379            include_str!("../../tests/fixtures/posthog_table_scalar_ratio.sql").trim_end()
380        );
381        assert!(sql.contains("SELECT value AS _num_value, _dim_0"), "{sql}");
382        assert!(
383            sql.contains("CROSS JOIN (SELECT value AS _den_value"),
384            "{sql}"
385        );
386        assert!(sql.contains("GROUP BY _dim_0"), "{sql}");
387        assert!(sql.ends_with("ORDER BY _dim_0 LIMIT 50000"), "{sql}");
388        assert_eq!(
389            sql.matches("timestamp <= now() - INTERVAL 3600 SECOND")
390                .count(),
391            2
392        );
393    }
394
395    #[test]
396    fn grouped_ratio_regroups_every_key_after_union() {
397        let numerator = TelemetryMetricBuilder::new("num", EyesAggregate::Count, None)
398            .unwrap()
399            .filter_eq("fields.event_type", "game_completed")
400            .unwrap()
401            .group_by("fields.source")
402            .unwrap()
403            .time_bucket(300)
404            .build()
405            .unwrap();
406        let denominator = TelemetryMetricBuilder::new("den", EyesAggregate::Count, None)
407            .unwrap()
408            .filter_eq("fields.event_type", "game_started")
409            .unwrap()
410            .group_by("fields.source")
411            .unwrap()
412            .time_bucket(300)
413            .build()
414            .unwrap();
415        let ratio = RatioMetricBuilder::new("ratio", "num", "den")
416            .build()
417            .unwrap();
418        let MetricQuery::Ratio(spec) = &ratio.query else {
419            panic!("expected ratio")
420        };
421        let declarations = Declarations::new()
422            .metric(numerator)
423            .metric(denominator)
424            .metric(ratio.clone());
425        let sql = ratio_sql(spec, &declarations, "arena", SqlWindow::trailing(3600)).unwrap();
426        assert_eq!(
427            sql,
428            include_str!("../../tests/fixtures/posthog_grouped_ratio.sql").trim_end()
429        );
430        assert!(sql.contains(
431            "toNullable(value) AS numerator, NULL AS denominator, 1 AS num_present, bucket, _dim_0"
432        ));
433        assert!(
434            sql.contains("NULL AS numerator, toNullable(value) AS denominator, NULL AS num_present, bucket, _dim_0")
435        );
436        assert!(sql.contains("if(isNull(max(num_present)), 0, max(numerator))"));
437        assert!(sql.contains("isNull(_den_value) OR _den_value = 0"));
438        assert!(sql.contains("GROUP BY bucket, _dim_0 ORDER BY bucket DESC, _dim_0 LIMIT 50000"));
439        assert!(sql.ends_with("ORDER BY bucket, _dim_0 LIMIT 50000"));
440    }
441
442    #[test]
443    fn unbucketed_grouped_ratio_orders_before_truncation() {
444        let numerator = TelemetryMetricBuilder::new("num", EyesAggregate::Count, None)
445            .unwrap()
446            .group_by("fields.source")
447            .unwrap()
448            .build()
449            .unwrap();
450        let denominator = TelemetryMetricBuilder::new("den", EyesAggregate::Count, None)
451            .unwrap()
452            .group_by("fields.source")
453            .unwrap()
454            .build()
455            .unwrap();
456        let ratio = RatioMetricBuilder::new("ratio", "num", "den")
457            .build()
458            .unwrap();
459        let MetricQuery::Ratio(spec) = &ratio.query else {
460            panic!("expected ratio")
461        };
462        let declarations = Declarations::new()
463            .metric(numerator)
464            .metric(denominator)
465            .metric(ratio.clone());
466        let sql = ratio_sql(spec, &declarations, "arena", SqlWindow::trailing(3600)).unwrap();
467        assert!(
468            sql.contains("GROUP BY _dim_0 ORDER BY _dim_0 LIMIT 50000"),
469            "{sql}"
470        );
471    }
472
473    #[test]
474    fn unsupported_ir_stages_and_missing_query_name_the_metric() {
475        let base = TelemetryMetricBuilder::new("sample", EyesAggregate::Count, None)
476            .unwrap()
477            .build()
478            .unwrap();
479        let path = FieldPath::bare("message");
480        let stages = [
481            Stage::Regex {
482                pattern: "x".into(),
483                source: path.clone(),
484                alias: "match".into(),
485            },
486            Stage::ParseJson {
487                source: path,
488                alias: "json".into(),
489            },
490            Stage::Let {
491                alias: "x".into(),
492                expr: Expr::Literal {
493                    value: Literal::Int(1),
494                },
495            },
496            Stage::Project { outputs: vec![] },
497            Stage::Sort { keys: vec![] },
498            Stage::Limit { count: 1 },
499        ];
500        for stage in stages {
501            let mut metric = base.clone();
502            let MetricQuery::Telemetry(ref mut telemetry) = metric.query else {
503                panic!("expected telemetry")
504            };
505            telemetry
506                .named_metric_mut()
507                .query
508                .as_mut()
509                .unwrap()
510                .query
511                .stages
512                .insert(0, stage.clone());
513            let error = telemetry_sql(telemetry, "arena", SqlWindow::trailing(60)).unwrap_err();
514            assert!(
515                error
516                    .to_string()
517                    .contains("metric sample: unsupported stage"),
518                "{error}"
519            );
520            assert!(error.to_string().contains(&format!("{stage:?}")), "{error}");
521        }
522        let mut metric = base;
523        let MetricQuery::Telemetry(ref mut telemetry) = metric.query else {
524            panic!("expected telemetry")
525        };
526        telemetry.named_metric_mut().query = None;
527        assert!(
528            telemetry_sql(telemetry, "arena", SqlWindow::trailing(60))
529                .unwrap_err()
530                .to_string()
531                .contains("metric sample: missing query")
532        );
533    }
534
535    #[test]
536    fn delayed_window_bounds_and_overflow() {
537        let window = SqlWindow {
538            seconds: 300,
539            delay: 30,
540        };
541        assert_eq!(
542            window.time_predicate().unwrap(),
543            "timestamp >= now() - INTERVAL 330 SECOND AND timestamp < now() - INTERVAL 30 SECOND"
544        );
545        assert!(
546            SqlWindow {
547                seconds: u64::MAX,
548                delay: 1
549            }
550            .lower()
551            .is_err()
552        );
553    }
554
555    #[test]
556    fn bucket_row_cap_accepts_maximum_and_rejects_one_more() {
557        assert!(
558            ensure_bucket_rows(600, SqlWindow::trailing((MAX_SQL_ROWS - 1) * 600), "series")
559                .is_ok()
560        );
561        assert!(
562            ensure_bucket_rows(600, SqlWindow::trailing(MAX_SQL_ROWS * 600), "series").is_err()
563        );
564    }
565
566    /// cja's `Tracer::make_span` sets `otel.name = "<METHOD> <route>"`, so the
567    /// exported `PostHog` span is never named `server.request`. The plan maps
568    /// `semantic_kind = http.request` by target and kind only, not by name.
569    #[test]
570    fn http_semantic_kind_matches_renamed_server_spans_by_target_and_kind_only() {
571        let metric = TelemetryMetricBuilder::new("http.requests", EyesAggregate::Count, None)
572            .unwrap()
573            .filter_eq("semantic_kind", "http.request")
574            .unwrap()
575            .build()
576            .unwrap();
577        let sql = telemetry_sql(telemetry(&metric), "arena", SqlWindow::trailing(3600)).unwrap();
578        assert!(sql.contains("FROM posthog.trace_spans"), "{sql}");
579        assert!(
580            sql.contains(
581                "attributes['target'] = 'cja::server::trace' AND attributes['kind'] = 'server'"
582            ),
583            "{sql}"
584        );
585        assert!(
586            !sql.contains("name = 'server.request'"),
587            "renamed HTTP spans never match a server.request name filter: {sql}"
588        );
589    }
590}
591pub(crate) fn slug(app: &str) -> Result<(), String> {
592    if app.is_empty()
593        || app.starts_with('-')
594        || !app
595            .bytes()
596            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
597    {
598        return Err(format!("invalid app slug {app:?}"));
599    }
600    Ok(())
601}
602impl SyncConfig {
603    /// Validate the app slug and parse configuration, returning `None` for an unconfigured repo.
604    pub fn from_parts(
605        host: Option<String>,
606        api_key: Option<String>,
607        project_id: Option<String>,
608        app: impl Into<String>,
609    ) -> Result<Option<Self>, String> {
610        let app = app.into();
611        slug(&app)?;
612        let (Some(api_key), Some(id)) = (
613            api_key.filter(|v| !v.is_empty()),
614            project_id.filter(|v| !v.is_empty()),
615        ) else {
616            return Ok(None);
617        };
618        Ok(Some(Self {
619            host: host
620                .filter(|v| !v.is_empty())
621                .unwrap_or_else(|| "https://us.posthog.com".into())
622                .trim_end_matches('/')
623                .into(),
624            api_key,
625            project_id: id
626                .parse()
627                .map_err(|_| format!("invalid POSTHOG_PROJECT_ID {id:?}"))?,
628            app,
629        }))
630    }
631    /// Read only the three CI configuration variables from the environment.
632    pub fn from_env(app: impl Into<String>) -> Result<Option<Self>, String> {
633        Self::from_parts(
634            std::env::var("POSTHOG_API_HOST").ok(),
635            std::env::var("POSTHOG_PERSONAL_API_KEY").ok(),
636            std::env::var("POSTHOG_PROJECT_ID").ok(),
637            app,
638        )
639    }
640}
641/// The sync engine's HTTPS client: rustls on ring with the platform verifier
642/// (system roots) and a 30 second request timeout.
643///
644/// It carries its own TLS configuration, so building it installs no
645/// process-wide rustls `CryptoProvider`.
646#[derive(Debug, Clone)]
647pub struct SyncClient(reqwest_012::Client);
648impl SyncClient {
649    /// Build the client. Fails when the platform certificate verifier cannot
650    /// load (for example an empty system root store).
651    pub fn new() -> Result<Self, SyncClientError> {
652        let tls = crate::tls::ring_client_config().map_err(|e| SyncClientError(Box::new(e)))?;
653        reqwest_012::Client::builder()
654            .use_preconfigured_tls(tls)
655            .timeout(Duration::from_secs(30))
656            .build()
657            .map(Self)
658            .map_err(|e| SyncClientError(Box::new(e)))
659    }
660}
661/// [`SyncClient::new`] could not build the client; the cause is its `source`.
662#[derive(Debug, thiserror::Error)]
663#[error("building the PostHog sync HTTP client")]
664pub struct SyncClientError(#[source] Box<dyn Error + Send + Sync>);
665/// A request that never produced an HTTP response (connect, TLS, timeout or
666/// body read). Displays the transport's message; the OS cause is its `source`.
667#[derive(Debug)]
668pub struct TransportError(reqwest_012::Error);
669impl fmt::Display for TransportError {
670    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
671        self.0.fmt(f)
672    }
673}
674impl Error for TransportError {
675    fn source(&self) -> Option<&(dyn Error + 'static)> {
676        self.0.source()
677    }
678}
679/// Changes and unsupported declarations encountered during reconciliation.
680#[derive(Debug, Default)]
681pub struct SyncReport {
682    pub created: Vec<String>,
683    pub updated: Vec<String>,
684    pub deleted: Vec<String>,
685    pub skipped: Vec<String>,
686}
687impl fmt::Display for SyncReport {
688    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
689        writeln!(
690            f,
691            "created {} updated {} deleted {}",
692            self.created.len(),
693            self.updated.len(),
694            self.deleted.len()
695        )?;
696        for (action, keys) in [
697            ("created", &self.created),
698            ("updated", &self.updated),
699            ("deleted", &self.deleted),
700        ] {
701            for key in keys {
702                writeln!(f, "{action}: {key}")?;
703            }
704        }
705        for warning in &self.skipped {
706            writeln!(f, "warning: {warning}")?;
707        }
708        Ok(())
709    }
710}
711/// Error while validating declarations, reading remote state, or applying a change.
712#[derive(Debug, thiserror::Error)]
713pub enum SyncError {
714    #[error("{object}: {method} {url} returned {status}: {body}")]
715    Api {
716        object: String,
717        method: String,
718        url: String,
719        status: u16,
720        body: String,
721    },
722    #[error("{object}: {operation}")]
723    Http {
724        object: String,
725        operation: &'static str,
726        #[source]
727        source: TransportError,
728    },
729    #[error("{object}: decoding response")]
730    Decode {
731        object: String,
732        source: serde_json::Error,
733    },
734    #[error(
735        "{object}: PostHog did not persist our identity {tag} (a tag for dashboards/insights, a name suffix for alerts); {cleanup}"
736    )]
737    TagNotPersisted {
738        object: String,
739        tag: String,
740        /// What happened to the object the failed write touched.
741        cleanup: String,
742    },
743    #[error(
744        "{alert}: alert name is {length} characters and PostHog allows at most {ALERT_NAME_LIMIT}; shorten the {hint}"
745    )]
746    AlertNameTooLong {
747        alert: String,
748        length: usize,
749        hint: &'static str,
750    },
751    #[error("{0}")]
752    Invalid(String),
753}
754struct Api<'a> {
755    config: &'a SyncConfig,
756    http: &'a SyncClient,
757    base: String,
758}
759impl Api<'_> {
760    async fn call(
761        &self,
762        method: Method,
763        url: &str,
764        body: Option<&Value>,
765        object: &str,
766    ) -> Result<Value, SyncError> {
767        let error = |source| SyncError::Http {
768            object: object.into(),
769            operation: "requesting PostHog",
770            source: TransportError(source),
771        };
772        let mut req = self
773            .http
774            .0
775            .request(method.clone(), url)
776            .bearer_auth(&self.config.api_key)
777            .header("Content-Type", "application/json");
778        if let Some(v) = body {
779            req = req.body(v.to_string());
780        }
781        let res = req.send().await.map_err(error)?;
782        let status = res.status();
783        let bytes = res.bytes().await.map_err(error)?;
784        if !status.is_success() {
785            return Err(SyncError::Api {
786                object: object.into(),
787                method: method.to_string(),
788                url: url.into(),
789                status: status.as_u16(),
790                body: String::from_utf8_lossy(&bytes).chars().take(2048).collect(),
791            });
792        }
793        if bytes.is_empty() {
794            return Ok(Value::Null);
795        }
796        serde_json::from_slice(&bytes).map_err(|source| SyncError::Decode {
797            object: object.into(),
798            source,
799        })
800    }
801    async fn list(&self, kind: &str) -> Result<Vec<Value>, SyncError> {
802        let path = format!("{}{kind}/", self.base);
803        let mut url = format!("{path}?limit=100");
804        let mut rows = Vec::new();
805        let mut seen = BTreeSet::new();
806        loop {
807            if !seen.insert(url.clone()) {
808                return Err(SyncError::Invalid(format!("{kind}: pagination cycle")));
809            }
810            let page = self.call(Method::GET, &url, None, kind).await?;
811            rows.extend(
812                page["results"]
813                    .as_array()
814                    .ok_or_else(|| SyncError::Invalid(format!("{kind}: missing results")))?
815                    .iter()
816                    .filter(|r| r["deleted"] != true)
817                    .cloned(),
818            );
819            let next = match page.get("next") {
820                Some(Value::Null) => break,
821                Some(Value::String(next)) => next,
822                _ => {
823                    return Err(SyncError::Invalid(format!(
824                        "{kind}: missing or invalid next page"
825                    )));
826                }
827            };
828            let origin = url::Url::parse(&self.config.host)
829                .map_err(|e| SyncError::Invalid(format!("{kind}: invalid API host: {e}")))?;
830            let next_url = url::Url::parse(next)
831                .map_err(|e| SyncError::Invalid(format!("{kind}: invalid pagination URL: {e}")))?;
832            if origin.origin() != next_url.origin() {
833                return Err(SyncError::Invalid(format!(
834                    "{kind}: unexpected pagination URL"
835                )));
836            }
837            url.clone_from(next);
838        }
839        Ok(rows)
840    }
841    async fn write(
842        &self,
843        method: Method,
844        path: &str,
845        body: &Value,
846        key: &str,
847    ) -> Result<Value, SyncError> {
848        self.call(method, &format!("{}{path}", self.base), Some(body), key)
849            .await
850    }
851}
852fn subset(wanted: &Value, actual: &Value) -> bool {
853    match (wanted, actual) {
854        (Value::Object(w), Value::Object(a)) => w
855            .iter()
856            .all(|(k, v)| a.get(k).is_some_and(|x| subset(v, x))),
857        (Value::Array(w), Value::Array(a)) => {
858            w.len() == a.len() && w.iter().zip(a).all(|(v, x)| subset(v, x))
859        }
860        _ => wanted == actual,
861    }
862}
863fn insight_absences_match(wanted: &Value, actual: &Value) -> bool {
864    if wanted.pointer("/query/source/kind") != Some(&json!("TrendsQuery")) {
865        return true;
866    }
867    (wanted.pointer("/query/source/breakdownFilter").is_some()
868        || actual
869            .pointer("/query/source/breakdownFilter/breakdowns")
870            .and_then(Value::as_array)
871            .is_none_or(Vec::is_empty))
872        && (wanted
873            .pointer("/query/source/trendsFilter/display")
874            .is_some()
875            || actual
876                .pointer("/query/source/trendsFilter/display")
877                .is_none_or(|display| display == "ActionsLineGraph"))
878        && (wanted
879            .pointer("/query/source/dateRange/explicitDate")
880            .is_some()
881            || actual.pointer("/query/source/dateRange/explicitDate") != Some(&json!(true)))
882}
883const DEFAULT_RANGE_SECONDS: u64 = 30 * 86_400;
884const MAX_RANGE_SECONDS: u64 = 31_622_400;
885const TAG_LIMIT: usize = 255;
886// PostHog's HogQL QUERY/SQL_ALERT contexts cap SELECT results at 50,000 rows.
887const MAX_SQL_ROWS: u64 = 50_000;
888const SQL_COVERAGE_DESCRIPTION: &str =
889    "Shows no value until PostHog holds data back to the start of this window.";
890fn date_from(seconds: u64) -> String {
891    for (unit, suffix) in [(86_400, "d"), (3_600, "h"), (60, "M")] {
892        if seconds.is_multiple_of(unit) {
893            return format!("-{}{suffix}", seconds / unit);
894        }
895    }
896    format!("-{seconds}s")
897}
898fn resolve_presentation<'a>(
899    item: &'a Item,
900    dash: &Dashboard,
901) -> Option<(&'a str, &'static str, u64)> {
902    let (metric, display) = match item {
903        Item::Stat { metric_id, .. } => (metric_id, "BoldNumber"),
904        Item::Table { metric_id, .. } => (metric_id, "ActionsTable"),
905        Item::TimeSeries { metric_id, .. } => (metric_id, "ActionsLineGraph"),
906        Item::HealthSummary { .. } | Item::Links { .. } => return None,
907    };
908    Some((
909        metric,
910        display,
911        item.declared_window_seconds()
912            .or(dash.default_range_seconds)
913            .unwrap_or(DEFAULT_RANGE_SECONDS),
914    ))
915}
916fn interval(n: u64) -> usize {
917    match n {
918        0..=3600 => 0,
919        3601..=86400 => 1,
920        86401..=604_800 => 2,
921        _ => 3,
922    }
923}
924fn query(p: &ProductEventMetric, app: &str, presentation: Option<(&str, u64)>) -> Value {
925    let (_, math, property) = p.aggregate.parts();
926    let mut properties =
927        vec![json!({"type":"event","key":"service.name","operator":"exact","value":app})];
928    for f in &p.property_filters {
929        let value = match &f.value {
930            FilterValue::Bool(x) => json!(x),
931            FilterValue::Int(x) => json!(x),
932            FilterValue::Float(x) => json!(x),
933            FilterValue::Str(x) => json!(x),
934        };
935        let operator = match f.operator {
936            FilterOperator::Eq => "exact",
937            FilterOperator::Gte => "gte",
938        };
939        properties.push(
940            json!({"type": "event", "key": f.property, "operator": operator, "value": value}),
941        );
942    }
943    let mut series =
944        json!({"kind":"EventsNode","event":p.event,"math":math,"properties":properties});
945    if let Some(prop) = property {
946        series["math_property"] = json!(prop);
947    }
948    // PostHog has no multi-week interval, so every week-aligned bucket charts
949    // at `week`: its alignment matters more than its exact width.
950    let bucket = ["hour", "day", "week", "month"][match p.bucket {
951        None => 1,
952        Some(Bucket::Seconds(n)) => interval(n),
953        Some(Bucket::Weeks(_)) => 2,
954    }];
955    let mut source = json!({
956        "kind": "TrendsQuery",
957        "series": [series],
958        "interval": bucket,
959        "dateRange": {"date_from": "-30d"},
960        "filterTestAccounts": false
961    });
962    if let Some(prop) = &p.breakdown_property {
963        source["breakdownFilter"] = json!({"breakdowns":[{"property":prop,"type":"event"}]});
964    }
965    if let Some((display, seconds)) = presentation {
966        source["dateRange"] = if display == "ActionsLineGraph" {
967            json!({"date_from":date_from(seconds)})
968        } else {
969            json!({"date_from":date_from(seconds),"explicitDate":true})
970        };
971        source["trendsFilter"] = json!({"display":display});
972    }
973    json!({"kind":"InsightVizNode","source":source})
974}
975
976#[derive(Clone, Copy)]
977struct SqlWindow {
978    seconds: u64,
979    delay: u64,
980}
981impl SqlWindow {
982    fn trailing(seconds: u64) -> Self {
983        Self { seconds, delay: 0 }
984    }
985    fn lower(self) -> Result<String, SyncError> {
986        let age = self
987            .seconds
988            .checked_add(self.delay)
989            .ok_or_else(|| SyncError::Invalid("SQL window and evaluation delay overflow".into()))?;
990        Ok(format!("now() - INTERVAL {age} SECOND"))
991    }
992    fn time_predicate(self) -> Result<String, SyncError> {
993        let predicate = format!("timestamp >= {}", self.lower()?);
994        Ok(if self.delay == 0 {
995            predicate
996        } else {
997            format!(
998                "{predicate} AND timestamp < now() - INTERVAL {} SECOND",
999                self.delay
1000            )
1001        })
1002    }
1003}
1004#[derive(Clone, Copy, PartialEq, Eq)]
1005enum SqlDisplay {
1006    Number,
1007    Table,
1008    Line,
1009}
1010impl SqlDisplay {
1011    fn from_name(name: &str) -> Result<Self, SyncError> {
1012        Ok(match name {
1013            "BoldNumber" => Self::Number,
1014            "ActionsTable" => Self::Table,
1015            "ActionsLineGraph" => Self::Line,
1016            _ => {
1017                return Err(SyncError::Invalid(format!(
1018                    "unsupported SQL display {name:?}"
1019                )));
1020            }
1021        })
1022    }
1023    fn name(self) -> &'static str {
1024        match self {
1025            Self::Number => "BoldNumber",
1026            Self::Table => "ActionsTable",
1027            Self::Line => "ActionsLineGraph",
1028        }
1029    }
1030}
1031fn sql_query(sql: &str, display: SqlDisplay, dimensions: usize) -> Value {
1032    let mut node = json!({"kind":"DataVisualizationNode", "source":{"kind":"HogQLQuery","query":sql}, "display":display.name()});
1033    if display == SqlDisplay::Line && dimensions == 1 {
1034        node["chartSettings"] = json!({"seriesBreakdownColumn":"_dim_0"});
1035    }
1036    node
1037}
1038fn sql_quote(value: &str) -> String {
1039    format!("'{}'", value.replace('\\', "\\\\").replace('\'', "''"))
1040}
1041fn map_value(map: &str, key: &str) -> String {
1042    format!("{map}[{}]", sql_quote(key))
1043}
1044#[derive(Clone, Copy, PartialEq, Eq)]
1045enum SqlSource {
1046    Logs,
1047    Spans,
1048    Events,
1049}
1050impl SqlSource {
1051    fn table(self) -> &'static str {
1052        match self {
1053            Self::Logs => "logs",
1054            Self::Spans => "posthog.trace_spans",
1055            Self::Events => "events",
1056        }
1057    }
1058    fn app_column(self, app: &str) -> String {
1059        match self {
1060            Self::Events => format!(
1061                "{} = {}",
1062                map_value("properties", "service.name"),
1063                sql_quote(app)
1064            ),
1065            Self::Logs | Self::Spans => format!("service_name = {}", sql_quote(app)),
1066        }
1067    }
1068    fn coverage(self, app: &str, lower: &str) -> String {
1069        format!(
1070            "(SELECT count() FROM (SELECT 1 FROM {} WHERE {} AND timestamp <= {lower} LIMIT 1)) > 0",
1071            self.table(),
1072            self.app_column(app)
1073        )
1074    }
1075}
1076fn path_sql(path: &FieldPath, source: SqlSource, numeric: bool) -> Result<String, SyncError> {
1077    let raw = match (path.root.as_str(), path.segments.as_slice(), source) {
1078        ("timestamp", [], _) => "timestamp".into(),
1079        ("fields", [PathSegment::Key(key)], SqlSource::Events) => map_value("properties", key),
1080        ("fields", [PathSegment::Key(key)], _) => map_value("attributes", key),
1081        ("message", [], SqlSource::Logs) => "body".into(),
1082        ("level", [], SqlSource::Logs) => "upper(level)".into(),
1083        ("target", [], SqlSource::Logs) => "splitByChar('@', instrumentation_scope)[1]".into(),
1084        ("target", [], SqlSource::Spans) => map_value("attributes", "target"),
1085        ("name", [], SqlSource::Spans) => "name".into(),
1086        ("duration", [], SqlSource::Spans) => "duration_nano / 1000".into(),
1087        ("semantic_kind" | "message" | "level" | "target" | "name" | "duration", [], _) => {
1088            "NULL".into()
1089        }
1090        _ => {
1091            return Err(SyncError::Invalid(format!(
1092                "unsupported field path {path:?}"
1093            )));
1094        }
1095    };
1096    if numeric && (raw.starts_with("attributes[") || raw.starts_with("properties[")) {
1097        Ok(format!("toFloatOrNull({raw})"))
1098    } else {
1099        Ok(raw)
1100    }
1101}
1102fn expr_path(expr: &Expr) -> Result<&FieldPath, SyncError> {
1103    match expr {
1104        Expr::Path { path } => Ok(path),
1105        _ => Err(SyncError::Invalid(format!("expected path, got {expr:?}"))),
1106    }
1107}
1108fn literal_sql(literal: &Literal, attribute: bool) -> Result<String, SyncError> {
1109    Ok(match literal {
1110        Literal::String(v) => sql_quote(v),
1111        Literal::Bool(v) if attribute => sql_quote(if *v { "true" } else { "false" }),
1112        Literal::Bool(v) => v.to_string(),
1113        Literal::Int(v) => v.to_string(),
1114        Literal::Float(v) => format!("{:e}", v.get()),
1115        _ => {
1116            return Err(SyncError::Invalid(format!(
1117                "unsupported filter literal {literal:?}"
1118            )));
1119        }
1120    })
1121}
1122fn semantic_predicate(value: &str, source: SqlSource) -> &'static str {
1123    match (value, source) {
1124        ("http.request", SqlSource::Spans) => {
1125            "attributes['target'] = 'cja::server::trace' AND attributes['kind'] = 'server'"
1126        }
1127        ("job.run", SqlSource::Spans) => "name = 'worker.run_job'",
1128        ("job.enqueue", SqlSource::Spans) => "name = 'jobs.enqueue'",
1129        ("cron.fire", SqlSource::Logs) => {
1130            "instrumentation_scope LIKE 'cja::cron::registry@%' AND body LIKE 'Enqueuing Task%' AND upper(level) = 'INFO'"
1131        }
1132        _ => "false",
1133    }
1134}
1135fn predicate_sql(expr: &Expr, source: SqlSource) -> Result<String, SyncError> {
1136    let Expr::Binary { op, left, right } = expr else {
1137        return Err(SyncError::Invalid(format!(
1138            "unsupported Where predicate {expr:?}"
1139        )));
1140    };
1141    let operator = match op {
1142        BinaryOp::Eq => "=",
1143        BinaryOp::Gte => ">=",
1144        _ => {
1145            return Err(SyncError::Invalid(format!(
1146                "unsupported Where operator {op:?}"
1147            )));
1148        }
1149    };
1150    let path = expr_path(left)?;
1151    let Expr::Literal { value } = right.as_ref() else {
1152        return Err(SyncError::Invalid(format!(
1153            "unsupported Where right side {right:?}"
1154        )));
1155    };
1156    if path.root == "semantic_kind" {
1157        if let (BinaryOp::Eq, Literal::String(value)) = (op, value) {
1158            if !matches!(
1159                value.as_str(),
1160                "http.request" | "job.run" | "job.enqueue" | "cron.fire"
1161            ) {
1162                return Err(SyncError::Invalid(format!(
1163                    "unsupported semantic_kind {value:?}"
1164                )));
1165            }
1166            return Ok(format!("({})", semantic_predicate(value, source)));
1167        }
1168        return Err(SyncError::Invalid(
1169            "semantic_kind requires string Eq".into(),
1170        ));
1171    }
1172    let numeric = matches!(value, Literal::Int(_) | Literal::Float(_));
1173    let field = path_sql(path, source, numeric)?;
1174    let attribute = field.contains("attributes[") || field.contains("properties[");
1175    Ok(format!(
1176        "{field} {operator} {}",
1177        literal_sql(value, attribute)?
1178    ))
1179}
1180fn aggregate_sql(function: EyesAggregate) -> &'static str {
1181    match function {
1182        EyesAggregate::Count => "count()",
1183        EyesAggregate::CountDistinct => "count(DISTINCT _metric_value)",
1184        EyesAggregate::Sum => "sum(_metric_value)",
1185        EyesAggregate::Avg => "avg(_metric_value)",
1186        EyesAggregate::Min => "min(_metric_value)",
1187        EyesAggregate::Max => "max(_metric_value)",
1188        EyesAggregate::P50 => "quantile(0.50)(_metric_value)",
1189        EyesAggregate::P90 => "quantile(0.90)(_metric_value)",
1190        EyesAggregate::P95 => "quantile(0.95)(_metric_value)",
1191        EyesAggregate::P99 => "quantile(0.99)(_metric_value)",
1192    }
1193}
1194#[derive(Clone)]
1195struct SqlPlan {
1196    sql: String,
1197    groups: Vec<String>,
1198    coverage: String,
1199}
1200fn group_sql(expr: &Expr, source: SqlSource) -> Result<String, SyncError> {
1201    if let Expr::Path { path } = expr {
1202        let field = path_sql(path, source, false)?;
1203        if field == "NULL" {
1204            return Err(SyncError::Invalid(format!(
1205                "cannot group by {path:?} on {}",
1206                source.table()
1207            )));
1208        }
1209        return Ok(field);
1210    }
1211    let Expr::Call {
1212        function: Function::TimeBucket,
1213        args,
1214    } = expr
1215    else {
1216        return Err(SyncError::Invalid(format!("unsupported group {expr:?}")));
1217    };
1218    let [
1219        Expr::Path { path },
1220        Expr::Literal {
1221            value: Literal::Duration(width),
1222        },
1223        rest @ ..,
1224    ] = args.as_slice()
1225    else {
1226        return Err(SyncError::Invalid(format!("invalid time bucket {expr:?}")));
1227    };
1228    if path.root != "timestamp"
1229        || !path.segments.is_empty()
1230        || *width <= 0
1231        || width % 1_000_000 != 0
1232    {
1233        return Err(SyncError::Invalid(format!(
1234            "unsupported time bucket {expr:?}"
1235        )));
1236    }
1237    let origin = match rest {
1238        [] => String::new(),
1239        [
1240            Expr::Literal {
1241                value: Literal::Duration(MONDAY_ORIGIN_US),
1242            },
1243        ] => ", toDateTime64('1970-01-05 00:00:00', 6, 'UTC')".into(),
1244        _ => {
1245            return Err(SyncError::Invalid(format!(
1246                "unsupported time bucket origin {expr:?}"
1247            )));
1248        }
1249    };
1250    Ok(format!(
1251        "toStartOfInterval(timestamp, INTERVAL {} SECOND{origin})",
1252        width / 1_000_000
1253    ))
1254}
1255fn group_aliases(
1256    dimensions: &[eyes_subscriber::eyes_query::NamedExpr],
1257    metric_id: &str,
1258) -> Result<Vec<String>, SyncError> {
1259    let has_bucket = dimensions.first().is_some_and(|g| {
1260        matches!(
1261            g.expr,
1262            Expr::Call {
1263                function: Function::TimeBucket,
1264                ..
1265            }
1266        )
1267    });
1268    for (i, group) in dimensions.iter().enumerate() {
1269        let expected = if has_bucket && i == 0 {
1270            "bucket".into()
1271        } else {
1272            format!("_dim_{}", i - usize::from(has_bucket))
1273        };
1274        if group.alias != expected {
1275            return Err(SyncError::Invalid(format!(
1276                "metric {metric_id}: unsupported group alias {}",
1277                group.alias
1278            )));
1279        }
1280    }
1281    Ok(dimensions.iter().map(|g| g.alias.clone()).collect())
1282}
1283fn ensure_bucket_rows(
1284    width_seconds: u64,
1285    window: SqlWindow,
1286    metric_id: &str,
1287) -> Result<(), SyncError> {
1288    if width_seconds == 0 || window.seconds / width_seconds >= MAX_SQL_ROWS {
1289        return Err(SyncError::Invalid(format!(
1290            "metric {metric_id}: window would exceed PostHog's {MAX_SQL_ROWS}-row SQL limit"
1291        )));
1292    }
1293    Ok(())
1294}
1295fn source_selection(predicates: &[&Expr], argument: Option<&Expr>) -> Vec<SqlSource> {
1296    let mut logs = false;
1297    let mut spans = false;
1298    for expr in predicates {
1299        if let Expr::Binary { left, right, .. } = expr
1300            && let Expr::Path { path } = left.as_ref()
1301        {
1302            match path.root.as_str() {
1303                "level" | "message" => logs = true,
1304                "name" | "duration" => spans = true,
1305                "fields" if matches!(path.segments.as_slice(), [PathSegment::Key(key)] if key == "event_type" || key == "metric_type") =>
1306                {
1307                    logs = true;
1308                }
1309                "semantic_kind" => {
1310                    if let Expr::Literal {
1311                        value: Literal::String(s),
1312                    } = right.as_ref()
1313                    {
1314                        if s == "cron.fire" {
1315                            logs = true;
1316                        } else {
1317                            spans = true;
1318                        }
1319                    }
1320                }
1321                _ => {}
1322            }
1323        }
1324    }
1325    if let Some(Expr::Path { path }) = argument {
1326        match path.root.as_str() {
1327            "message" | "level" => logs = true,
1328            "name" | "duration" => spans = true,
1329            _ => {}
1330        }
1331    }
1332    match (logs, spans) {
1333        (true, false) => vec![SqlSource::Logs],
1334        (false, true) => vec![SqlSource::Spans],
1335        _ => vec![SqlSource::Logs, SqlSource::Spans],
1336    }
1337}
1338fn render_plan(
1339    branches: &[String],
1340    sources: &[SqlSource],
1341    groups: &[String],
1342    aggregate: &str,
1343    empty_is_null: bool,
1344    app: &str,
1345    window: SqlWindow,
1346) -> Result<SqlPlan, SyncError> {
1347    let lower = window.lower()?;
1348    let coverage = sources
1349        .iter()
1350        .map(|s| s.coverage(app, &lower))
1351        .collect::<Vec<_>>()
1352        .join(" AND ");
1353    let rows = branches.join(" UNION ALL ");
1354    let grouped = !groups.is_empty();
1355    let aggregate = if empty_is_null {
1356        format!("if(count(_metric_value) = 0, NULL, {aggregate})")
1357    } else {
1358        aggregate.to_owned()
1359    };
1360    let projection = if grouped {
1361        format!("{aggregate} AS value, {}", groups.join(", "))
1362    } else {
1363        format!("if({coverage}, {aggregate}, NULL) AS value")
1364    };
1365    let group_by = if grouped {
1366        format!(" WHERE {coverage} GROUP BY {}", groups.join(", "))
1367    } else {
1368        String::new()
1369    };
1370    let limit = if grouped { MAX_SQL_ROWS } else { 1 };
1371    let sql = format!("SELECT {projection} FROM ({rows}) AS _source{group_by}");
1372    let sql = if grouped && groups.first().is_some_and(|g| g == "bucket") {
1373        let recent_order = descending_bucket_order(groups);
1374        format!(
1375            "SELECT * FROM (SELECT * FROM ({sql}) AS _grouped ORDER BY {recent_order} LIMIT {limit}) AS _recent ORDER BY {} LIMIT {limit}",
1376            groups.join(", ")
1377        )
1378    } else if grouped {
1379        format!("{sql} ORDER BY {} LIMIT {limit}", groups.join(", "))
1380    } else {
1381        format!("{sql} LIMIT {limit}")
1382    };
1383    Ok(SqlPlan {
1384        sql,
1385        groups: groups.to_vec(),
1386        coverage,
1387    })
1388}
1389fn descending_bucket_order(groups: &[String]) -> String {
1390    let mut order = String::from("bucket DESC");
1391    for group in groups.iter().skip(1) {
1392        order.push_str(", ");
1393        order.push_str(group);
1394    }
1395    order
1396}
1397fn telemetry_plan(
1398    metric: &TelemetryMetric,
1399    app: &str,
1400    window: SqlWindow,
1401) -> Result<SqlPlan, SyncError> {
1402    let named = metric.named_metric();
1403    let stages = &named
1404        .query
1405        .as_ref()
1406        .ok_or_else(|| SyncError::Invalid(format!("metric {}: missing query", named.id)))?
1407        .query
1408        .stages;
1409    let mut predicates = Vec::new();
1410    let mut aggregate = None;
1411    for (index, stage) in stages.iter().enumerate() {
1412        match stage {
1413            Stage::Where { predicate } if aggregate.is_none() => predicates.push(predicate),
1414            Stage::Aggregate { aggregates, groups }
1415                if aggregate.is_none() && aggregates.len() == 1 && index + 1 == stages.len() =>
1416            {
1417                aggregate = Some((&aggregates[0], groups));
1418            }
1419            _ => {
1420                return Err(SyncError::Invalid(format!(
1421                    "metric {}: unsupported stage {stage:?}",
1422                    named.id
1423                )));
1424            }
1425        }
1426    }
1427    let (aggregate, dimensions) = aggregate.ok_or_else(|| {
1428        SyncError::Invalid(format!("metric {}: missing single aggregate", named.id))
1429    })?;
1430    let argument = aggregate.argument.as_ref();
1431    if !aggregate.function.is_count() && argument.is_none() {
1432        return Err(SyncError::Invalid(format!(
1433            "metric {}: missing aggregate argument",
1434            named.id
1435        )));
1436    }
1437    let sources = source_selection(&predicates, argument);
1438    let group_names = group_aliases(dimensions, &named.id)?;
1439    if let Some(group) = dimensions.first()
1440        && let Expr::Call {
1441            function: Function::TimeBucket,
1442            args,
1443        } = &group.expr
1444        && let Some(Expr::Literal {
1445            value: Literal::Duration(micros),
1446        }) = args.get(1)
1447        && *micros > 0
1448    {
1449        ensure_bucket_rows((*micros).cast_unsigned() / 1_000_000, window, &named.id)?;
1450    }
1451    let mut branches = Vec::new();
1452    for source in &sources {
1453        let value = if let Some(argument) = argument {
1454            let path = expr_path(argument)
1455                .map_err(|e| SyncError::Invalid(format!("metric {}: {e}", named.id)))?;
1456            path_sql(
1457                path,
1458                *source,
1459                !matches!(aggregate.function, EyesAggregate::CountDistinct),
1460            )
1461            .map_err(|e| SyncError::Invalid(format!("metric {}: {e}", named.id)))?
1462        } else {
1463            "NULL".into()
1464        };
1465        let mut selected = vec![format!("{value} AS _metric_value")];
1466        for (i, group) in dimensions.iter().enumerate() {
1467            selected.push(format!(
1468                "{} AS {}",
1469                group_sql(&group.expr, *source).map_err(|e| SyncError::Invalid(format!(
1470                    "metric {} group {i}: {e}",
1471                    named.id
1472                )))?,
1473                group.alias
1474            ));
1475        }
1476        let mut conditions = vec![source.app_column(app), window.time_predicate()?];
1477        for predicate in &predicates {
1478            conditions.push(
1479                predicate_sql(predicate, *source)
1480                    .map_err(|e| SyncError::Invalid(format!("metric {}: {e}", named.id)))?,
1481            );
1482        }
1483        branches.push(format!(
1484            "SELECT {} FROM {} WHERE {}",
1485            selected.join(", "),
1486            source.table(),
1487            conditions.join(" AND ")
1488        ));
1489    }
1490    render_plan(
1491        &branches,
1492        &sources,
1493        &group_names,
1494        aggregate_sql(aggregate.function),
1495        !matches!(
1496            aggregate.function,
1497            EyesAggregate::Count | EyesAggregate::CountDistinct
1498        ),
1499        app,
1500        window,
1501    )
1502}
1503#[allow(dead_code)] // Pure SQL interface retained for direct contract tests.
1504fn telemetry_sql(
1505    metric: &TelemetryMetric,
1506    app: &str,
1507    window: SqlWindow,
1508) -> Result<String, SyncError> {
1509    Ok(telemetry_plan(metric, app, window)?.sql)
1510}
1511fn product_plan(
1512    metric: &ProductEventMetric,
1513    app: &str,
1514    window: SqlWindow,
1515) -> Result<SqlPlan, SyncError> {
1516    let (aggregate, property) = match &metric.aggregate {
1517        ProductAggregate::Count => ("count()", None),
1518        ProductAggregate::DistinctUsers => ("count(DISTINCT _metric_value)", None),
1519        ProductAggregate::Sum { property } => ("sum(_metric_value)", Some(property)),
1520        ProductAggregate::Avg { property } => ("avg(_metric_value)", Some(property)),
1521        ProductAggregate::Min { property } => ("min(_metric_value)", Some(property)),
1522        ProductAggregate::Max { property } => ("max(_metric_value)", Some(property)),
1523        ProductAggregate::Median { property } => ("quantile(0.50)(_metric_value)", Some(property)),
1524        ProductAggregate::P90 { property } => ("quantile(0.90)(_metric_value)", Some(property)),
1525        ProductAggregate::P95 { property } => ("quantile(0.95)(_metric_value)", Some(property)),
1526        ProductAggregate::P99 { property } => ("quantile(0.99)(_metric_value)", Some(property)),
1527    };
1528    let value = property.map_or_else(
1529        || match metric.aggregate {
1530            ProductAggregate::DistinctUsers => "distinct_id".into(),
1531            _ => "NULL".into(),
1532        },
1533        |property| format!("toFloatOrNull({})", map_value("properties", property)),
1534    );
1535    let mut groups = Vec::new();
1536    let mut selected = vec![format!("{value} AS _metric_value")];
1537    if let Some(bucket) = metric.bucket {
1538        let bucket = match bucket {
1539            Bucket::Seconds(seconds) if seconds > 0 => {
1540                ensure_bucket_rows(seconds, window, &metric.event)?;
1541                format!("toStartOfInterval(timestamp, INTERVAL {seconds} SECOND)")
1542            }
1543            Bucket::Weeks(weeks) if weeks > 0 => {
1544                let width = u64::from(weeks) * 604_800;
1545                ensure_bucket_rows(width, window, &metric.event)?;
1546                format!(
1547                    "toStartOfInterval(timestamp, INTERVAL {width} SECOND, toDateTime64('1970-01-05 00:00:00', 6, 'UTC'))"
1548                )
1549            }
1550            _ => return Err(SyncError::Invalid("invalid product bucket".into())),
1551        };
1552        groups.push("bucket".into());
1553        selected.push(format!("{bucket} AS bucket"));
1554    }
1555    if let Some(property) = &metric.breakdown_property {
1556        groups.push("_dim_0".into());
1557        selected.push(format!("{} AS _dim_0", map_value("properties", property)));
1558    }
1559    let mut conditions = vec![
1560        SqlSource::Events.app_column(app),
1561        window.time_predicate()?,
1562        format!("event = {}", sql_quote(&metric.event)),
1563    ];
1564    for filter in &metric.property_filters {
1565        let numeric = matches!(filter.value, FilterValue::Int(_) | FilterValue::Float(_));
1566        let raw = map_value("properties", &filter.property);
1567        let field = if numeric {
1568            format!("toFloatOrNull({raw})")
1569        } else {
1570            raw
1571        };
1572        let value = match &filter.value {
1573            FilterValue::Bool(v) => sql_quote(if *v { "true" } else { "false" }),
1574            FilterValue::Int(v) => v.to_string(),
1575            FilterValue::Float(v) => format!("{v:e}"),
1576            FilterValue::Str(v) => sql_quote(v),
1577        };
1578        conditions.push(format!(
1579            "{field} {} {value}",
1580            match filter.operator {
1581                FilterOperator::Eq => "=",
1582                FilterOperator::Gte => ">=",
1583            }
1584        ));
1585    }
1586    let branch = format!(
1587        "SELECT {} FROM events WHERE {}",
1588        selected.join(", "),
1589        conditions.join(" AND ")
1590    );
1591    render_plan(
1592        &[branch],
1593        &[SqlSource::Events],
1594        &groups,
1595        aggregate,
1596        !matches!(
1597            metric.aggregate,
1598            ProductAggregate::Count | ProductAggregate::DistinctUsers
1599        ),
1600        app,
1601        window,
1602    )
1603}
1604fn operand_plan(
1605    metric: &super::Metric,
1606    app: &str,
1607    window: SqlWindow,
1608) -> Result<SqlPlan, SyncError> {
1609    match &metric.query {
1610        MetricQuery::Telemetry(telemetry) => telemetry_plan(telemetry, app, window),
1611        MetricQuery::ProductEvent(product) => product_plan(product, app, window),
1612        MetricQuery::Ratio(_) => Err(SyncError::Invalid(format!(
1613            "ratio {} cannot be an operand",
1614            metric.id
1615        ))),
1616    }
1617}
1618fn ratio_plan(
1619    ratio: &RatioMetric,
1620    declarations: &Declarations,
1621    app: &str,
1622    window: SqlWindow,
1623) -> Result<SqlPlan, SyncError> {
1624    if ratio_mixes_clusters(ratio, declarations) {
1625        return Err(SyncError::Invalid(format!(
1626            "ratio {} mixes product events with logs/spans: PostHog cannot query both clusters together",
1627            ratio.numerator
1628        )));
1629    }
1630    let numerator = declarations
1631        .metrics
1632        .iter()
1633        .find(|m| m.id == ratio.numerator)
1634        .ok_or_else(|| {
1635            SyncError::Invalid(format!("missing ratio numerator {}", ratio.numerator))
1636        })?;
1637    let denominator = declarations
1638        .metrics
1639        .iter()
1640        .find(|m| m.id == ratio.denominator)
1641        .ok_or_else(|| {
1642            SyncError::Invalid(format!("missing ratio denominator {}", ratio.denominator))
1643        })?;
1644    let num_window = SqlWindow {
1645        seconds: ratio.numerator_window_seconds.unwrap_or(window.seconds),
1646        delay: window.delay,
1647    };
1648    let den_window = SqlWindow {
1649        seconds: ratio.denominator_window_seconds.unwrap_or(window.seconds),
1650        delay: window.delay,
1651    };
1652    let num = operand_plan(numerator, app, num_window)?;
1653    let den = operand_plan(denominator, app, den_window)?;
1654    if !den.groups.is_empty() && num.groups != den.groups {
1655        return Err(SyncError::Invalid("ratio operand groups differ".into()));
1656    }
1657    let expression = if ratio.as_percentage {
1658        "_num_value * 100 / _den_value"
1659    } else {
1660        "_num_value / _den_value"
1661    };
1662    let formula = format!(
1663        "if(isNull(_num_value) OR isNull(_den_value) OR _den_value = 0, NULL, {expression})"
1664    );
1665    let sql = if num.groups.is_empty() {
1666        format!(
1667            "SELECT {formula} AS value FROM (SELECT value AS _num_value FROM ({}) LIMIT 1) AS _num CROSS JOIN (SELECT value AS _den_value FROM ({}) LIMIT 1) AS _den LIMIT 1",
1668            num.sql, den.sql
1669        )
1670    } else if den.groups.is_empty() {
1671        let keys = num.groups.join(", ");
1672        format!(
1673            "SELECT {formula} AS value, {keys} FROM (SELECT value AS _num_value, {keys} FROM ({}) AS _num_rows) AS _num CROSS JOIN (SELECT value AS _den_value FROM ({}) LIMIT 1) AS _den ORDER BY {keys} LIMIT {MAX_SQL_ROWS}",
1674            num.sql, den.sql
1675        )
1676    } else {
1677        let keys = num.groups.join(", ");
1678        let recent = if num.groups.first().is_some_and(|group| group == "bucket") {
1679            format!(" ORDER BY {}", descending_bucket_order(&num.groups))
1680        } else {
1681            format!(" ORDER BY {keys}")
1682        };
1683        let grouped = format!(
1684            "SELECT if({}, if(isNull(max(num_present)), 0, max(numerator)), NULL) AS _num_value, max(denominator) AS _den_value, {keys} FROM (SELECT toNullable(value) AS numerator, NULL AS denominator, 1 AS num_present, {keys} FROM ({}) UNION ALL SELECT NULL AS numerator, toNullable(value) AS denominator, NULL AS num_present, {keys} FROM ({})) AS _combined GROUP BY {keys}{recent} LIMIT {MAX_SQL_ROWS}",
1685            num.coverage, num.sql, den.sql
1686        );
1687        let selected = format!("SELECT {formula} AS value, {keys} FROM ({grouped}) AS _ratios");
1688        if num.groups.first().is_some_and(|group| group == "bucket") {
1689            let recent_order = descending_bucket_order(&num.groups);
1690            format!(
1691                "SELECT * FROM ({selected} ORDER BY {recent_order} LIMIT {MAX_SQL_ROWS}) AS _recent ORDER BY {keys} LIMIT {MAX_SQL_ROWS}"
1692            )
1693        } else {
1694            format!("{selected} ORDER BY {keys} LIMIT {MAX_SQL_ROWS}")
1695        }
1696    };
1697    Ok(SqlPlan {
1698        sql,
1699        groups: num.groups,
1700        coverage: format!("{} AND {}", num.coverage, den.coverage),
1701    })
1702}
1703#[allow(dead_code)] // Pure SQL interface retained for direct contract tests.
1704fn ratio_sql(
1705    ratio: &RatioMetric,
1706    declarations: &Declarations,
1707    app: &str,
1708    window: SqlWindow,
1709) -> Result<String, SyncError> {
1710    Ok(ratio_plan(ratio, declarations, app, window)?.sql)
1711}
1712fn ratio_mixes_clusters(ratio: &RatioMetric, declarations: &Declarations) -> bool {
1713    let is_product = |id: &str| {
1714        declarations
1715            .metrics
1716            .iter()
1717            .find(|metric| metric.id == id)
1718            .is_some_and(|metric| matches!(metric.query, MetricQuery::ProductEvent(_)))
1719    };
1720    is_product(&ratio.numerator) != is_product(&ratio.denominator)
1721}
1722fn health_sql(app: &str) -> Result<String, SyncError> {
1723    let window = SqlWindow::trailing(86_400);
1724    let lower = window.lower()?;
1725    Ok(format!(
1726        "SELECT if({}, count(), NULL) AS value FROM logs WHERE {} AND upper(level) = 'ERROR' AND {} LIMIT 1",
1727        SqlSource::Logs.coverage(app, &lower),
1728        SqlSource::Logs.app_column(app),
1729        window.time_predicate()?
1730    ))
1731}
1732fn bounds(a: &Alert) -> Value {
1733    let mut b = json!({});
1734    for v in [&a.warning, &a.critical].into_iter().flatten() {
1735        b[match v.comparison {
1736            Comparison::Above => "upper",
1737            Comparison::Below => "lower",
1738        }] = json!(v.threshold);
1739    }
1740    b
1741}
1742type Index = BTreeMap<String, Value>;
1743fn index(rows: Vec<Value>, prefix: &str) -> Result<Index, SyncError> {
1744    let mut idx = Index::new();
1745    for row in rows {
1746        let tags = row["tags"]
1747            .as_array()
1748            .into_iter()
1749            .flatten()
1750            .filter_map(Value::as_str)
1751            .filter(|t| t.starts_with("cja:"))
1752            .collect::<Vec<_>>();
1753        if tags.len() > 1 && tags.iter().any(|tag| tag.starts_with(prefix)) {
1754            return Err(SyncError::Invalid(format!(
1755                "ambiguous ownership tags: {tags:?}"
1756            )));
1757        }
1758        if let [tag] = tags.as_slice()
1759            && tag.starts_with(prefix)
1760            && idx.insert((*tag).into(), row.clone()).is_some()
1761        {
1762            return Err(SyncError::Invalid(format!("duplicate identity {tag}")));
1763        }
1764    }
1765    Ok(idx)
1766}
1767fn id(row: &Value, key: &str) -> Result<i64, SyncError> {
1768    row["id"]
1769        .as_i64()
1770        .ok_or_else(|| SyncError::Invalid(format!("{key}: missing numeric ID")))
1771}
1772fn insight_id(v: &Value) -> Option<i64> {
1773    v.as_i64().or_else(|| v["id"].as_i64())
1774}
1775const LEFT_IN_PLACE: &str = "the existing object was left in place";
1776/// Remove an object `PostHog` just created without our identity. Left alone
1777/// it would be invisible to every later sync: one orphan per deploy.
1778async fn discard(api: &Api<'_>, kind: &str, row: &Value, key: &str) -> String {
1779    let removed = if kind == "alerts" {
1780        match alert_path(row) {
1781            Ok(path) => api
1782                .call(Method::DELETE, &format!("{}{path}", api.base), None, key)
1783                .await
1784                .map(drop),
1785            Err(e) => Err(e),
1786        }
1787    } else {
1788        match id(row, key) {
1789            Ok(n) => api
1790                .write(
1791                    Method::PATCH,
1792                    &format!("{kind}/{n}/"),
1793                    &json!({"deleted":true}),
1794                    key,
1795                )
1796                .await
1797                .map(drop),
1798            Err(e) => Err(e),
1799        }
1800    };
1801    match removed {
1802        Ok(()) => "the object just created was removed".into(),
1803        Err(e) => format!(
1804            "removing the object just created failed, remove it by hand: {}",
1805            message(&e)
1806        ),
1807    }
1808}
1809async fn upsert(
1810    api: &Api<'_>,
1811    kind: &str,
1812    key: &str,
1813    mut body: Value,
1814    idx: &mut Index,
1815    report: &mut SyncReport,
1816) -> Result<i64, SyncError> {
1817    let old = idx.get(key);
1818    if let Some(row) = old
1819        && subset(&body, row)
1820        && (kind != "insights" || insight_absences_match(&body, row))
1821    {
1822        return id(row, key);
1823    }
1824    let (method, path) = if let Some(row) = old {
1825        body["tags"] = row["tags"].clone();
1826        (Method::PATCH, format!("{kind}/{}/", id(row, key)?))
1827    } else {
1828        body["tags"] = json!([key]);
1829        (Method::POST, format!("{kind}/"))
1830    };
1831    let row = api.write(method, &path, &body, key).await?;
1832    if !row["tags"]
1833        .as_array()
1834        .is_some_and(|t| t.iter().any(|x| x == key))
1835    {
1836        let cleanup = if old.is_some() {
1837            LEFT_IN_PLACE.into()
1838        } else {
1839            discard(api, kind, &row, key).await
1840        };
1841        return Err(SyncError::TagNotPersisted {
1842            object: key.into(),
1843            tag: key.into(),
1844            cleanup,
1845        });
1846    }
1847    let n = id(&row, key)?;
1848    if old.is_some() {
1849        report.updated.push(key.into());
1850    } else {
1851        report.created.push(key.into());
1852    }
1853    idx.insert(key.into(), row);
1854    Ok(n)
1855}
1856async fn tiles(
1857    api: &Api<'_>,
1858    key: &str,
1859    n: i64,
1860    wanted: &[i64],
1861    owned: &BTreeSet<i64>,
1862    r: &mut SyncReport,
1863) -> Result<(), SyncError> {
1864    let path = format!("dashboards/{n}/");
1865    let dashboard = api
1866        .call(Method::GET, &format!("{}{path}", api.base), None, key)
1867        .await?;
1868    let mut present = BTreeSet::new();
1869    for tile in dashboard["tiles"]
1870        .as_array()
1871        .ok_or_else(|| SyncError::Invalid(format!("{key}: missing tiles")))?
1872    {
1873        if tile["insight"]["deleted"] == true {
1874            continue;
1875        }
1876        if let Some(i) = insight_id(&tile["insight"]) {
1877            present.insert(i);
1878            if owned.contains(&i) && !wanted.contains(&i) {
1879                let tid = id(tile, key)?;
1880                api.write(
1881                    Method::POST,
1882                    &format!("{path}delete_tile/"),
1883                    &json!({"tile_id":tid}),
1884                    key,
1885                )
1886                .await?;
1887                r.updated.push(format!("{key}: removed tile {tid}"));
1888            }
1889        }
1890    }
1891    for i in wanted {
1892        if present.insert(*i) {
1893            api.write(
1894                Method::POST,
1895                &format!("{path}add_insight/"),
1896                &json!({"insight_id":i}),
1897                key,
1898            )
1899            .await?;
1900            r.updated.push(format!("{key}: added insight {i}"));
1901        }
1902    }
1903    Ok(())
1904}
1905/// `PostHog` caps an alert name at this many characters.
1906const ALERT_NAME_LIMIT: usize = 255;
1907/// Display name plus the identity suffix that marks the alert as ours.
1908fn alert_name(app: &str, a: &Alert) -> String {
1909    format!(
1910        "{} [cja:{app}:alert:{}]",
1911        a.description.as_ref().unwrap_or(&a.id),
1912        a.id
1913    )
1914}
1915fn alert_key<'a>(name: &'a str, app: &str) -> Option<&'a str> {
1916    let (_, key) = name
1917        .strip_suffix(']')?
1918        .rsplit_once(&format!("[cja:{app}:alert:"))?;
1919    (!key.is_empty() && !key.contains([']', '['])).then_some(key)
1920}
1921async fn alerts(
1922    api: &Api<'_>,
1923    decl: &Declarations,
1924    rows: Vec<Value>,
1925    ids: &BTreeMap<&str, i64>,
1926    skipped_metrics: &BTreeMap<&str, &'static str>,
1927    r: &mut SyncReport,
1928) -> Result<(), SyncError> {
1929    let app = &api.config.app;
1930    let mut existing = Index::new();
1931    for row in rows {
1932        if let Some(k) = row["name"].as_str().and_then(|s| alert_key(s, app))
1933            && existing.insert(k.into(), row.clone()).is_some()
1934        {
1935            return Err(SyncError::Invalid(format!("duplicate alert {k}")));
1936        }
1937    }
1938    for a in &decl.alerts {
1939        let tag = format!("cja:{app}:alert:{}", a.id);
1940        let Some(n) = ids.get(a.metric_id.as_str()) else {
1941            if let Some(reason) = skipped_metrics.get(a.metric_id.as_str()) {
1942                r.skipped.push(format!(
1943                    "{tag}: alert for {} skipped ({reason})",
1944                    a.metric_id
1945                ));
1946            } else {
1947                r.skipped.push(format!(
1948                    "{tag}: SQL metric {} alert (PostHog-unsupported: SQL alert payload and NULL evaluation unverified)", a.metric_id
1949                ));
1950            }
1951            continue;
1952        };
1953        let cadence =
1954            ["hourly", "daily", "weekly", "monthly"][interval(a.evaluation_interval_seconds)];
1955        let mut body = json!({
1956            "name": alert_name(app, a),
1957            "insight": n,
1958            "enabled": a.enabled,
1959            "condition": {"type": "absolute_value"},
1960            "config": {"type": "TrendsAlertConfig", "series_index": 0},
1961            "threshold": {"configuration": {"type": "absolute", "bounds": bounds(a)}},
1962            "calculation_interval": cadence
1963        });
1964        if let Some(row) = existing.remove(&a.id) {
1965            let desired = &body["threshold"]["configuration"];
1966            let stored = &row["threshold"]["configuration"];
1967            if row["name"] == body["name"]
1968                && insight_id(&row["insight"]) == Some(*n)
1969                && row["enabled"] == body["enabled"]
1970                && row["calculation_interval"] == cadence
1971                && subset(desired, stored)
1972                && ["lower", "upper"]
1973                    .iter()
1974                    .all(|k| desired["bounds"][*k] == stored["bounds"][*k])
1975            {
1976                continue;
1977            }
1978            let response = api
1979                .write(Method::PATCH, &alert_path(&row)?, &body, &tag)
1980                .await?;
1981            if alert_key(response["name"].as_str().unwrap_or_default(), app) != Some(a.id.as_str())
1982            {
1983                return Err(SyncError::TagNotPersisted {
1984                    object: tag.clone(),
1985                    tag,
1986                    cleanup: LEFT_IN_PLACE.into(),
1987                });
1988            }
1989            r.updated.push(tag);
1990        } else {
1991            // Creation requires a subscriber list. Only an operator edits it afterwards.
1992            body["subscribed_users"] = json!([]);
1993            let response = api.write(Method::POST, "alerts/", &body, &tag).await?;
1994            if alert_key(response["name"].as_str().unwrap_or_default(), app) != Some(a.id.as_str())
1995            {
1996                let cleanup = discard(api, "alerts", &response, &tag).await;
1997                return Err(SyncError::TagNotPersisted {
1998                    object: tag.clone(),
1999                    tag,
2000                    cleanup,
2001                });
2002            }
2003            r.created.push(tag);
2004        }
2005    }
2006    for (k, row) in existing {
2007        let key = format!("cja:{app}:alert:{k}");
2008        api.call(
2009            Method::DELETE,
2010            &format!("{}{}", api.base, alert_path(&row)?),
2011            None,
2012            &key,
2013        )
2014        .await?;
2015        r.deleted.push(key);
2016    }
2017    Ok(())
2018}
2019/// Insights a dashboard should tile, in declaration order. Items with no
2020/// `PostHog` equivalent are reported as skipped.
2021fn wanted_tiles(
2022    dash: &Dashboard,
2023    key: &str,
2024    presentations: &BTreeMap<(&str, u64), i64>,
2025    health: &BTreeMap<(String, usize), i64>,
2026    skipped_metrics: &BTreeMap<&str, &'static str>,
2027    skipped_presentations: &BTreeMap<(&str, u64), &'static str>,
2028    r: &mut SyncReport,
2029) -> Result<Vec<i64>, SyncError> {
2030    let mut wanted = vec![];
2031    let mut health_ordinal = 0;
2032    for item in dash.sections.iter().flat_map(|s| &s.items) {
2033        match (item, resolve_presentation(item, dash)) {
2034            (_, Some((mid, _, seconds))) => {
2035                if let Some(reason) = skipped_metrics
2036                    .get(mid)
2037                    .copied()
2038                    .or_else(|| skipped_presentations.get(&(mid, seconds)).copied())
2039                {
2040                    r.skipped
2041                        .push(format!("{key}: tile for {mid} skipped ({reason})"));
2042                    continue;
2043                }
2044                wanted.push(*presentations.get(&(mid, seconds)).ok_or_else(|| {
2045                    SyncError::Invalid(format!("{key}: missing insight for metric {mid}"))
2046                })?);
2047            }
2048            (Item::Links { .. }, None) => {
2049                r.skipped.push(format!("{key}: links item (Eyes-only)"));
2050            }
2051            (Item::HealthSummary { .. }, None) => {
2052                if let Some(id) = health.get(&(dash.id.clone(), health_ordinal)) {
2053                    wanted.push(*id);
2054                }
2055                health_ordinal += 1;
2056            }
2057            (_, None) => {
2058                return Err(SyncError::Invalid(format!(
2059                    "{key}: item lacks a presentation"
2060                )));
2061            }
2062        }
2063    }
2064    Ok(wanted)
2065}
2066fn alert_path(row: &Value) -> Result<String, SyncError> {
2067    let id = row["id"]
2068        .as_str()
2069        .and_then(|s| uuid::Uuid::parse_str(s).ok())
2070        .ok_or_else(|| SyncError::Invalid("invalid alert UUID".into()))?;
2071    Ok(format!("alerts/{id}/"))
2072}
2073type Presentations<'a> = BTreeMap<&'a str, Vec<(&'static str, u64)>>;
2074struct Prepared<'a> {
2075    alerted_ids: BTreeSet<&'a str>,
2076    presentations: Presentations<'a>,
2077    insights: BTreeMap<String, Value>,
2078    health: BTreeMap<String, Value>,
2079    skipped_metrics: BTreeMap<&'a str, &'static str>,
2080    skipped_presentations: BTreeMap<(&'a str, u64), &'static str>,
2081    canonical_windows: BTreeMap<&'a str, u64>,
2082}
2083#[allow(clippy::too_many_lines)]
2084fn preflight<'a>(
2085    config: &SyncConfig,
2086    declarations: &'a Declarations,
2087) -> Result<Prepared<'a>, SyncError> {
2088    slug(&config.app)
2089        .and_then(|()| declarations.validate())
2090        .map_err(SyncError::Invalid)?;
2091    for alert in &declarations.alerts {
2092        let length = alert_name(&config.app, alert).chars().count();
2093        if length > ALERT_NAME_LIMIT {
2094            return Err(SyncError::AlertNameTooLong {
2095                alert: format!("cja:{}:alert:{}", config.app, alert.id),
2096                length,
2097                hint: if alert.description.is_some() {
2098                    "alert description"
2099                } else {
2100                    "alert ID"
2101                },
2102            });
2103        }
2104    }
2105    let product_ids = declarations
2106        .metrics
2107        .iter()
2108        .filter(|metric| matches!(metric.query, MetricQuery::ProductEvent(_)))
2109        .map(|metric| metric.id.as_str())
2110        .collect::<BTreeSet<_>>();
2111    let alerted_ids = declarations
2112        .alerts
2113        .iter()
2114        .filter(|alert| product_ids.contains(alert.metric_id.as_str()))
2115        .map(|alert| alert.metric_id.as_str())
2116        .collect::<BTreeSet<_>>();
2117    let mut declared_presentations: Presentations<'a> = BTreeMap::new();
2118    for dash in &declarations.dashboards {
2119        if let Some(seconds) = dash.default_range_seconds
2120            && !(60..=MAX_RANGE_SECONDS).contains(&seconds)
2121        {
2122            return Err(SyncError::Invalid(format!(
2123                "dashboard {}: default_range_seconds {seconds} must be 60..={MAX_RANGE_SECONDS}",
2124                dash.id
2125            )));
2126        }
2127        for item in dash.sections.iter().flat_map(|section| &section.items) {
2128            let Some((metric_id, display, seconds)) = resolve_presentation(item, dash) else {
2129                continue;
2130            };
2131            if let Some(window) = item.declared_window_seconds()
2132                && !(1..=MAX_RANGE_SECONDS).contains(&window)
2133            {
2134                return Err(SyncError::Invalid(format!(
2135                    "dashboard {} metric {metric_id}: window_seconds {window} must be 1..={MAX_RANGE_SECONDS}",
2136                    dash.id
2137                )));
2138            }
2139            let entries = declared_presentations.entry(metric_id).or_default();
2140            if !entries.iter().any(|(_, old)| *old == seconds) {
2141                entries.push((display, seconds));
2142            }
2143        }
2144    }
2145    for (metric_id, entries) in &declared_presentations {
2146        for (_, seconds) in entries
2147            .iter()
2148            .skip(usize::from(!alerted_ids.contains(metric_id)))
2149        {
2150            let key = format!("cja:{}:insight:{metric_id}@{seconds}s", config.app);
2151            if key.len() > TAG_LIMIT {
2152                return Err(SyncError::Invalid(format!(
2153                    "insight variant tag {key} is {} characters; PostHog allows at most {TAG_LIMIT}",
2154                    key.len()
2155                )));
2156            }
2157        }
2158    }
2159    for metric in &declarations.metrics {
2160        let key = format!("cja:{}:insight:{}", config.app, metric.id);
2161        if key.len() > TAG_LIMIT {
2162            return Err(SyncError::Invalid(format!(
2163                "insight tag {key} exceeds {TAG_LIMIT} characters"
2164            )));
2165        }
2166    }
2167    for dash in &declarations.dashboards {
2168        let dashboard_key = format!("cja:{}:dashboard:{}", config.app, dash.id);
2169        if dashboard_key.len() > TAG_LIMIT {
2170            return Err(SyncError::Invalid(format!(
2171                "dashboard tag {dashboard_key} exceeds {TAG_LIMIT} characters"
2172            )));
2173        }
2174        let mut ordinal = 0;
2175        for item in dash.sections.iter().flat_map(|section| &section.items) {
2176            if matches!(item, Item::HealthSummary { .. }) {
2177                let key = format!("cja:{}:insight:{}@health{ordinal}", config.app, dash.id);
2178                if key.len() > TAG_LIMIT {
2179                    return Err(SyncError::Invalid(format!(
2180                        "health tag {key} exceeds {TAG_LIMIT} characters"
2181                    )));
2182                }
2183                ordinal += 1;
2184            }
2185        }
2186    }
2187    let mut prepared = Prepared {
2188        alerted_ids,
2189        presentations: declared_presentations,
2190        insights: BTreeMap::new(),
2191        health: BTreeMap::new(),
2192        skipped_metrics: BTreeMap::new(),
2193        skipped_presentations: BTreeMap::new(),
2194        canonical_windows: BTreeMap::new(),
2195    };
2196    for metric in &declarations.metrics {
2197        if let MetricQuery::Ratio(ratio) = &metric.query
2198            && ratio_mixes_clusters(ratio, declarations)
2199        {
2200            prepared
2201                .skipped_metrics
2202                .insert(&metric.id, "ratio mixes product events with logs/spans");
2203            continue;
2204        }
2205        let declared = prepared.presentations.get(metric.id.as_str());
2206        let alerted = prepared.alerted_ids.contains(metric.id.as_str());
2207        let fallback = [("ActionsLineGraph", DEFAULT_RANGE_SECONDS)];
2208        let entries = declared.map_or(fallback.as_slice(), Vec::as_slice);
2209        let mut rendered = Vec::new();
2210        for &(display, seconds) in entries {
2211            let query = metric_query(metric, declarations, &config.app, display, seconds, false)?;
2212            if query.is_none() {
2213                prepared.skipped_presentations.insert(
2214                    (metric.id.as_str(), seconds),
2215                    "PostHog-unsupported: SQL line charts break down by one column",
2216                );
2217            }
2218            rendered.push((display, seconds, query));
2219        }
2220        let legacy =
2221            (alerted || declared.is_none()) && matches!(metric.query, MetricQuery::ProductEvent(_));
2222        let canonical = if legacy {
2223            metric_query(
2224                metric,
2225                declarations,
2226                &config.app,
2227                entries[0].0,
2228                entries[0].1,
2229                true,
2230            )?
2231        } else {
2232            rendered.iter().find_map(|(_, _, query)| query.clone())
2233        };
2234        let Some(canonical) = canonical else { continue };
2235        let first_supported = rendered.iter().find(|(_, _, query)| query.is_some());
2236        if !legacy && let Some((_, seconds, _)) = first_supported {
2237            prepared
2238                .canonical_windows
2239                .insert(metric.id.as_str(), *seconds);
2240        }
2241        let name = metric.display_name.as_ref().unwrap_or(&metric.id);
2242        let description = if matches!(metric.query, MetricQuery::ProductEvent(_)) {
2243            Value::Null
2244        } else {
2245            json!(SQL_COVERAGE_DESCRIPTION)
2246        };
2247        let key = format!("cja:{}:insight:{}", config.app, metric.id);
2248        prepared.insights.insert(
2249            key,
2250            json!({"name":name,"description":description,"query":canonical}),
2251        );
2252        if declared.is_some() {
2253            for (_, seconds, query) in rendered {
2254                let Some(query) = query else { continue };
2255                if !alerted && prepared.canonical_windows.get(metric.id.as_str()) == Some(&seconds)
2256                {
2257                    continue;
2258                }
2259                let key = format!("cja:{}:insight:{}@{seconds}s", config.app, metric.id);
2260                prepared.insights.insert(
2261                    key,
2262                    json!({"name":name,"description":description,"query":query}),
2263                );
2264            }
2265        }
2266    }
2267    for dash in &declarations.dashboards {
2268        let mut ordinal = 0;
2269        for item in dash.sections.iter().flat_map(|section| &section.items) {
2270            if let Item::HealthSummary { label } = item {
2271                let key = format!("cja:{}:insight:{}@health{ordinal}", config.app, dash.id);
2272                let name = format!(
2273                    "{}Recent error events (24h) — health substitute",
2274                    label.as_deref().map_or(String::new(), |v| format!("{v}: "))
2275                );
2276                let sql = health_sql(&config.app)?;
2277                prepared.health.insert(key, json!({"name":name,"description":SQL_COVERAGE_DESCRIPTION,"query":sql_query(&sql, SqlDisplay::Number, 0)}));
2278                ordinal += 1;
2279            }
2280        }
2281    }
2282    Ok(prepared)
2283}
2284fn metric_query(
2285    metric: &super::Metric,
2286    decl: &Declarations,
2287    app: &str,
2288    display: &str,
2289    seconds: u64,
2290    legacy: bool,
2291) -> Result<Option<Value>, SyncError> {
2292    Ok(match &metric.query {
2293        MetricQuery::ProductEvent(product) => {
2294            Some(query(product, app, (!legacy).then_some((display, seconds))))
2295        }
2296        MetricQuery::Telemetry(telemetry) => {
2297            let plan = telemetry_plan(telemetry, app, SqlWindow::trailing(seconds))?;
2298            sql_node_for_plan(&plan, display)?
2299        }
2300        MetricQuery::Ratio(ratio) => {
2301            let plan = ratio_plan(ratio, decl, app, SqlWindow::trailing(seconds))?;
2302            sql_node_for_plan(&plan, display)?
2303        }
2304    })
2305}
2306fn sql_node_for_plan(plan: &SqlPlan, display: &str) -> Result<Option<Value>, SyncError> {
2307    let display = SqlDisplay::from_name(display)?;
2308    let dimensions = plan
2309        .groups
2310        .iter()
2311        .filter(|group| group.as_str() != "bucket")
2312        .count();
2313    if display == SqlDisplay::Line && dimensions > 1 {
2314        return Ok(None);
2315    }
2316    Ok(Some(sql_query(&plan.sql, display, dimensions)))
2317}
2318async fn prune(
2319    api: &Api<'_>,
2320    dashboards: Index,
2321    insights: Index,
2322    keep: &BTreeSet<String>,
2323    report: &mut SyncReport,
2324) -> Result<(), SyncError> {
2325    for (kind, rows) in [("dashboards", dashboards), ("insights", insights)] {
2326        for (key, row) in rows {
2327            if !keep.contains(&key) {
2328                api.write(
2329                    Method::PATCH,
2330                    &format!("{kind}/{}/", id(&row, &key)?),
2331                    &json!({"deleted":true}),
2332                    &key,
2333                )
2334                .await?;
2335                report.deleted.push(key);
2336            }
2337        }
2338    }
2339    Ok(())
2340}
2341async fn sync_dashboard_rows(
2342    api: &Api<'_>,
2343    declarations: &Declarations,
2344    dashboards: &mut Index,
2345    keep: &mut BTreeSet<String>,
2346    report: &mut SyncReport,
2347) -> Result<(), SyncError> {
2348    for dash in &declarations.dashboards {
2349        let key = format!("cja:{}:dashboard:{}", api.config.app, dash.id);
2350        let has_sql =
2351            dash.sections
2352                .iter()
2353                .flat_map(|section| &section.items)
2354                .any(|item| {
2355                    matches!(item, Item::HealthSummary { .. })
2356                        || item.reference().is_some_and(|(id, _)| {
2357                            declarations.metrics.iter().any(|m| {
2358                                m.id == id && !matches!(m.query, MetricQuery::ProductEvent(_))
2359                            })
2360                        })
2361                });
2362        let description = if has_sql {
2363            let note = "SQL tiles show NULL or no rows until the full source window has boundary coverage; health shows recent error events, not durable process/job state.";
2364            match dash.description.as_deref().filter(|s| !s.is_empty()) {
2365                Some(description) => format!("{description}\n{note}"),
2366                None => note.to_owned(),
2367            }
2368        } else {
2369            dash.description.clone().unwrap_or_default()
2370        };
2371        let body = json!({"name": dash.title, "description": description});
2372        upsert(api, "dashboards", &key, body, dashboards, report).await?;
2373        keep.insert(key);
2374    }
2375    Ok(())
2376}
2377async fn sync_health_rows(
2378    api: &Api<'_>,
2379    declarations: &Declarations,
2380    bodies: &BTreeMap<String, Value>,
2381    insights: &mut Index,
2382    keep: &mut BTreeSet<String>,
2383    report: &mut SyncReport,
2384) -> Result<BTreeMap<(String, usize), i64>, SyncError> {
2385    let mut ids = BTreeMap::new();
2386    for dash in &declarations.dashboards {
2387        let mut ordinal = 0;
2388        for item in dash.sections.iter().flat_map(|section| &section.items) {
2389            if let Item::HealthSummary { .. } = item {
2390                let key = format!("cja:{}:insight:{}@health{ordinal}", api.config.app, dash.id);
2391                let n = upsert(
2392                    api,
2393                    "insights",
2394                    &key,
2395                    bodies.get(&key).cloned().ok_or_else(|| {
2396                        SyncError::Invalid(format!("missing prepared health {key}"))
2397                    })?,
2398                    insights,
2399                    report,
2400                )
2401                .await?;
2402                ids.insert((dash.id.clone(), ordinal), n);
2403                keep.insert(key);
2404                ordinal += 1;
2405            }
2406        }
2407    }
2408    Ok(ids)
2409}
2410/// Apply a complete declaration set, including removal of stale owned objects.
2411#[allow(clippy::too_many_lines)]
2412pub async fn sync(
2413    config: &SyncConfig,
2414    declarations: &Declarations,
2415    http: &SyncClient,
2416) -> Result<SyncReport, SyncError> {
2417    let prepared = preflight(config, declarations)?;
2418    let api = Api {
2419        config,
2420        http,
2421        base: format!("{}/api/projects/{}/", config.host, config.project_id),
2422    };
2423    let tag = |kind: &str, key: &str| format!("cja:{}:{kind}:{key}", config.app);
2424    let mut insights = index(api.list("insights").await?, &tag("insight", ""))?;
2425    let mut dashboards = index(api.list("dashboards").await?, &tag("dashboard", ""))?;
2426    let alert_rows = api.list("alerts").await?;
2427    let mut report = SyncReport::default();
2428    let mut keep = BTreeSet::new();
2429    let mut ids = BTreeMap::new();
2430    let mut presentation_ids = BTreeMap::new();
2431    sync_dashboard_rows(&api, declarations, &mut dashboards, &mut keep, &mut report).await?;
2432    for metric in &declarations.metrics {
2433        let key = tag("insight", &metric.id);
2434        if prepared.skipped_metrics.contains_key(metric.id.as_str()) {
2435            report.skipped.push(format!("{key}: ratio mixes product events with logs/spans (PostHog-unsupported: HogQL cannot join events and logs/spans in one query)"));
2436            continue;
2437        }
2438        let Some(body) = prepared.insights.get(&key).cloned() else {
2439            continue;
2440        };
2441        let declared = prepared.presentations.get(metric.id.as_str());
2442        let alerted = prepared.alerted_ids.contains(metric.id.as_str());
2443        let insight_id = upsert(&api, "insights", &key, body, &mut insights, &mut report).await?;
2444        if matches!(metric.query, MetricQuery::ProductEvent(_)) {
2445            ids.insert(metric.id.as_str(), insight_id);
2446        }
2447        keep.insert(key);
2448        if let Some(entries) = declared {
2449            for (_, seconds) in entries {
2450                if prepared
2451                    .skipped_presentations
2452                    .contains_key(&(metric.id.as_str(), *seconds))
2453                {
2454                    continue;
2455                }
2456                let n = if !alerted
2457                    && prepared.canonical_windows.get(metric.id.as_str()) == Some(seconds)
2458                {
2459                    insight_id
2460                } else {
2461                    let variant = tag("insight", &format!("{}@{seconds}s", metric.id));
2462                    let body = prepared.insights.get(&variant).cloned().ok_or_else(|| {
2463                        SyncError::Invalid(format!("missing prepared insight {variant}"))
2464                    })?;
2465                    let n = upsert(&api, "insights", &variant, body, &mut insights, &mut report)
2466                        .await?;
2467                    keep.insert(variant);
2468                    n
2469                };
2470                presentation_ids.insert((metric.id.as_str(), *seconds), n);
2471            }
2472        }
2473    }
2474    let health_ids = sync_health_rows(
2475        &api,
2476        declarations,
2477        &prepared.health,
2478        &mut insights,
2479        &mut keep,
2480        &mut report,
2481    )
2482    .await?;
2483    let owned = insights
2484        .iter()
2485        .map(|(key, v)| id(v, key))
2486        .collect::<Result<_, _>>()?;
2487    for dash in &declarations.dashboards {
2488        let key = tag("dashboard", &dash.id);
2489        let wanted = wanted_tiles(
2490            dash,
2491            &key,
2492            &presentation_ids,
2493            &health_ids,
2494            &prepared.skipped_metrics,
2495            &prepared.skipped_presentations,
2496            &mut report,
2497        )?;
2498        tiles(
2499            &api,
2500            &key,
2501            id(&dashboards[&key], &key)?,
2502            &wanted,
2503            &owned,
2504            &mut report,
2505        )
2506        .await?;
2507    }
2508    alerts(
2509        &api,
2510        declarations,
2511        alert_rows,
2512        &ids,
2513        &prepared.skipped_metrics,
2514        &mut report,
2515    )
2516    .await?;
2517    prune(&api, dashboards, insights, &keep, &mut report).await?;
2518    Ok(report)
2519}
2520fn message(error: &dyn Error) -> String {
2521    let mut line = error.to_string();
2522    let mut source = error.source();
2523    while let Some(e) = source {
2524        line.push_str(": ");
2525        line.push_str(&e.to_string());
2526        source = e.source();
2527    }
2528    line.replace(['\n', '\r'], " ")
2529}
2530/// Run the CI command and translate its result to a process exit status.
2531/// Pass a client from [`SyncClient::new`].
2532pub async fn run_from_env(app: &str, d: &Declarations, http: &SyncClient) -> ExitCode {
2533    if let Err(e) = d.validate() {
2534        eprintln!("invalid declarations: {e}");
2535        return ExitCode::from(2);
2536    }
2537    match SyncConfig::from_env(app) {
2538        Ok(Some(c)) => match sync(&c, d, http).await {
2539            Ok(r) => {
2540                println!("{r}");
2541                ExitCode::SUCCESS
2542            }
2543            Err(e) => {
2544                eprintln!("{}", message(&e));
2545                ExitCode::FAILURE
2546            }
2547        },
2548        Ok(None) => {
2549            println!("::notice::PostHog sync skipped: credentials or project ID absent");
2550            ExitCode::SUCCESS
2551        }
2552        Err(e) => {
2553            eprintln!("{e}");
2554            ExitCode::FAILURE
2555        }
2556    }
2557}
2558
2559#[cfg(test)]
2560mod tests {
2561    use super::*;
2562    #[test]
2563    fn configuration_and_ownership() {
2564        for app in ["", "ABC", "-bad", "demo:bad", "a]"] {
2565            assert!(SyncConfig::from_parts(None, None, None, app).is_err());
2566        }
2567        for key in [None, Some(String::new())] {
2568            assert!(
2569                SyncConfig::from_parts(None, key, Some("1".into()), "demo")
2570                    .unwrap()
2571                    .is_none()
2572            );
2573        }
2574        let config = |host, id: &str| {
2575            SyncConfig::from_parts(host, Some("key".into()), Some(id.into()), "demo-1")
2576        };
2577        assert_eq!(
2578            config(Some(String::new()), "17").unwrap().unwrap().host,
2579            "https://us.posthog.com"
2580        );
2581        assert_eq!(
2582            config(Some("https://example.org/".into()), "17")
2583                .unwrap()
2584                .unwrap()
2585                .host,
2586            "https://example.org"
2587        );
2588        assert!(config(None, "bad").is_err());
2589        assert_eq!(
2590            alert_key("Human [cja:demo:alert:jobs]", "demo"),
2591            Some("jobs")
2592        );
2593        assert_eq!(alert_key("Human [cja:demo:alert:jobs]", "other"), None);
2594    }
2595    #[test]
2596    fn subset_accounts_for_server_defaults() {
2597        let desired = json!({"series":[{"event":"e"}]});
2598        assert!(subset(
2599            &desired,
2600            &json!({"version":2,"series":[{"event":"e","id":1}]})
2601        ));
2602        for other in [
2603            json!({}),
2604            json!({"series":[]}),
2605            json!({"series":[{"event":"x"}]}),
2606        ] {
2607            assert!(!subset(&desired, &other));
2608        }
2609    }
2610    #[test]
2611    fn bucket_boundaries() {
2612        for (n, i) in [
2613            (300, 0),
2614            (3600, 0),
2615            (3601, 1),
2616            (86400, 1),
2617            (86401, 2),
2618            (604_800, 2),
2619            (604_801, 3),
2620        ] {
2621            assert_eq!(interval(n), i);
2622        }
2623    }
2624    #[tokio::test]
2625    async fn https_error_prints_os_cause() {
2626        let source = SyncClient::new()
2627            .unwrap()
2628            .0
2629            .get("https://127.0.0.1:1/")
2630            .send()
2631            .await
2632            .unwrap_err();
2633        let err = SyncError::Http {
2634            object: "test-app".into(),
2635            operation: "listing",
2636            source: TransportError(source),
2637        };
2638        let text = message(&err);
2639        assert!(text.contains("test-app: listing"));
2640        assert!(text.to_lowercase().contains("connection refused"), "{text}");
2641        assert!(!text.contains("scheme is not http"));
2642        assert!(!text.contains('\n'));
2643    }
2644}
2645
2646#[cfg(test)]
2647mod mapping_tests {
2648    use super::*;
2649    use crate::observability::{AlertBuilder, ProductMetricBuilder};
2650    #[test]
2651    fn presentation_kinds_and_ranges() {
2652        let dash = Dashboard::new("d", "D")
2653            .unwrap()
2654            .default_range_seconds(364 * 86_400);
2655        for (item, display, seconds) in [
2656            (Item::stat("m"), "BoldNumber", 364 * 86_400),
2657            (
2658                Item::table("m").window_seconds(604_800),
2659                "ActionsTable",
2660                604_800,
2661            ),
2662            (Item::time_series("m"), "ActionsLineGraph", 364 * 86_400),
2663        ] {
2664            assert_eq!(
2665                resolve_presentation(&item, &dash),
2666                Some(("m", display, seconds))
2667            );
2668        }
2669        assert_eq!(resolve_presentation(&Item::health_summary(), &dash), None);
2670        assert_eq!(resolve_presentation(&Item::links(vec![]), &dash), None);
2671        for (seconds, expected) in [
2672            (61, "-61s"),
2673            (300, "-5M"),
2674            (3_600, "-1h"),
2675            (604_800, "-7d"),
2676            (2_592_000, "-30d"),
2677            (31_449_600, "-364d"),
2678        ] {
2679            assert_eq!(date_from(seconds), expected);
2680        }
2681    }
2682    #[test]
2683    fn legacy_absences_require_a_legacy_query() {
2684        let wanted =
2685            json!({"query":{"source":{"kind":"TrendsQuery","dateRange":{"date_from":"-30d"}}}});
2686        let mut actual = wanted.clone();
2687        assert!(insight_absences_match(&wanted, &actual));
2688        actual["query"]["source"]["trendsFilter"] = json!({});
2689        assert!(insight_absences_match(&wanted, &actual));
2690        actual["query"]["source"]["trendsFilter"] = json!({"display":"ActionsLineGraph"});
2691        actual["query"]["source"]["dateRange"]["explicitDate"] = json!(false);
2692        assert!(insight_absences_match(&wanted, &actual));
2693        actual["query"]["source"]["trendsFilter"] = json!({"display":"BoldNumber"});
2694        assert!(!insight_absences_match(&wanted, &actual));
2695        actual["query"]["source"]["dateRange"]["explicitDate"] = json!(true);
2696        assert!(!insight_absences_match(&wanted, &actual));
2697        actual["query"]["source"]["trendsFilter"] = json!({});
2698        assert!(!insight_absences_match(&wanted, &actual));
2699        let line = json!({"query":{"source":{"kind":"TrendsQuery","dateRange":{"date_from":"-30d"},"trendsFilter":{"display":"ActionsLineGraph"}}}});
2700        let mut stored_line = line.clone();
2701        stored_line["query"]["source"]["dateRange"]["explicitDate"] = json!(true);
2702        assert!(!insight_absences_match(&line, &stored_line));
2703        let sql = json!({"query":{"kind":"DataVisualizationNode","source":{"kind":"HogQLQuery","query":"SELECT 1 AS value"},"display":"BoldNumber"}});
2704        let stored_sql = json!({"query":{"kind":"DataVisualizationNode","source":{"kind":"HogQLQuery","query":"SELECT 1 AS value","version":2},"display":"BoldNumber"}});
2705        assert!(insight_absences_match(&sql, &stored_sql));
2706    }
2707    #[test]
2708    fn product_trend_wire_contract() {
2709        let metric = ProductMetricBuilder::p95("time", "opened", "seconds")
2710            .filter("paid", FilterOperator::Eq, true)
2711            .filter("attempt", FilterOperator::Gte, 2_i64)
2712            .breakdown("tier")
2713            .bucket_seconds(300)
2714            .build()
2715            .unwrap();
2716        let MetricQuery::ProductEvent(spec) = metric.query else {
2717            panic!("expected product metric")
2718        };
2719        assert_eq!(
2720            query(&spec, "demo", None),
2721            json!({
2722 "kind":"InsightVizNode","source":{"kind":"TrendsQuery",
2723 "series":[{"kind":"EventsNode","event":"opened","math":"p95","math_property":"seconds","properties":[
2724 {"type":"event","key":"service.name","operator":"exact","value":"demo"},
2725 {"type":"event","key":"paid","operator":"exact","value":true},
2726 {"type":"event","key":"attempt","operator":"gte","value":2}]}],
2727 "interval":"hour","dateRange":{"date_from":"-30d"},"filterTestAccounts":false,
2728 "breakdownFilter":{"breakdowns":[{"property":"tier","type":"event"}]}}})
2729        );
2730        let presented = query(&spec, "demo", Some(("ActionsTable", 300)));
2731        assert_eq!(
2732            presented["source"]["dateRange"],
2733            json!({"date_from":"-5M","explicitDate":true})
2734        );
2735        assert_eq!(
2736            presented["source"]["trendsFilter"],
2737            json!({"display":"ActionsTable"})
2738        );
2739        assert_eq!(
2740            presented["source"]["series"],
2741            query(&spec, "demo", None)["source"]["series"]
2742        );
2743        assert_eq!(
2744            presented["source"]["breakdownFilter"],
2745            query(&spec, "demo", None)["source"]["breakdownFilter"]
2746        );
2747        assert_eq!(presented["source"]["interval"], "hour");
2748        let line = query(&spec, "demo", Some(("ActionsLineGraph", 604_800)));
2749        assert_eq!(line["source"]["dateRange"], json!({"date_from":"-7d"}));
2750        assert_eq!(
2751            line["source"]["trendsFilter"],
2752            json!({"display":"ActionsLineGraph"})
2753        );
2754        let count = ProductMetricBuilder::count("sessions", "opened")
2755            .build()
2756            .unwrap();
2757        let MetricQuery::ProductEvent(spec) = count.query else {
2758            panic!("expected product metric")
2759        };
2760        let q = query(&spec, "demo", None);
2761        assert_eq!(q["source"]["interval"], "day");
2762        for weeks in [1, 2] {
2763            let weekly = ProductMetricBuilder::count("weekly", "opened")
2764                .bucket_weeks(weeks)
2765                .build()
2766                .unwrap();
2767            let MetricQuery::ProductEvent(spec) = weekly.query else {
2768                panic!("expected product metric")
2769            };
2770            assert_eq!(query(&spec, "demo", None)["source"]["interval"], "week");
2771        }
2772        assert_eq!(q["source"]["series"][0]["math"], "total");
2773        assert!(q["source"].get("breakdownFilter").is_none());
2774        assert!(q["source"]["series"][0].get("math_property").is_none());
2775    }
2776    #[test]
2777    fn critical_overrides_only_its_own_direction() {
2778        let builder = || {
2779            AlertBuilder::new("count", "activity")
2780                .window_seconds(60)
2781                .evaluation_interval_seconds(60)
2782        };
2783        for (warn, crit, wanted) in [
2784            (Comparison::Above, Comparison::Above, json!({"upper":4.})),
2785            (Comparison::Below, Comparison::Below, json!({"lower":4.})),
2786            (
2787                Comparison::Below,
2788                Comparison::Above,
2789                json!({"lower":2.,"upper":4.}),
2790            ),
2791            (
2792                Comparison::Above,
2793                Comparison::Below,
2794                json!({"upper":2.,"lower":4.}),
2795            ),
2796        ] {
2797            assert_eq!(
2798                bounds(
2799                    &builder()
2800                        .warning(warn, 2.)
2801                        .critical(crit, 4.)
2802                        .build()
2803                        .unwrap()
2804                ),
2805                wanted
2806            );
2807        }
2808        assert_eq!(
2809            bounds(&builder().warning(Comparison::Below, 2.).build().unwrap()),
2810            json!({"lower":2.})
2811        );
2812    }
2813}