:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(logs): add the Loki import engine (#105591)
Jimmy Zhu04cdf1c6dede
diff --git a/cli/Cargo.lock b/cli/Cargo.lockindex 83a38bdaff33..5f80962a8292 100644--- a/cli/Cargo.lock+++ b/cli/Cargo.lock@@ -1100,6 +1100,7 @@ dependencies = ["hyper","hyper-util","rustls",+ "rustls-native-certs","rustls-pki-types","tokio","tokio-rustls",@@ -2465,6 +2466,7 @@ dependencies = ["pin-project-lite","quinn","rustls",+ "rustls-native-certs","rustls-pki-types","serde","serde_json",diff --git a/cli/Cargo.toml b/cli/Cargo.tomlindex 3ea8b8981494..938ba33fadd0 100644--- a/cli/Cargo.toml+++ b/cli/Cargo.toml@@ -48,11 +48,16 @@ proguard = "5.6.2"magic_string = "0.3.4"miette = { version = "7.5.0", features = ["fancy"] }serde_json = "1.0.140"+# Both root stores. `rustls-tls` compiles in the public CA list, which verifies PostHog+# Cloud even where no trust store exists. `rustls-tls-native-roots` reads the machine's+# store, which is the only way to reach an internally signed host, because the compiled-in+# list cannot be extended from outside.reqwest = { version = "0.12.14", features = ["blocking","json","multipart","rustls-tls",+ "rustls-tls-native-roots",], default-features = false }anyhow = "1.0.97"serde = { version = "1.0.219", features = ["derive"] }diff --git a/cli/src/experimental/logs/README.md b/cli/src/experimental/logs/README.mdindex a61058f81689..d91166e8ba30 100644--- a/cli/src/experimental/logs/README.md+++ b/cli/src/experimental/logs/README.md@@ -27,10 +27,36 @@ no extra setting.personal token, and the project key is already public-facing, so a long unattended run never holdsthe operator's own credential.+Log in to the same project that `POSTHOG_PROJECT_API_KEY` belongs to. The retention check below+reads the logged-in project, so the import stops before sending anything when the two projects+differ.++PostHog keeps backdated logs only for teams with historical imports turned on. For any other team,+intake drops them after answering 200, so contact PostHog support before the first import.+Always run `--dry-run` first. It sizes the job and reports how many sampled records each extractionrule actually matched. A rule that matches nothing reports `NOT FOUND`, which is the only warningyou get before a run that would otherwise take hours and produce unusable data.+## Internal certificates++A self-hosted Loki usually answers on an internal hostname, and no public certificate authority+issues certificates for a name that does not resolve on the public internet. Clusters sign those+hosts with an authority they run themselves.++The CLI trusts the public authorities and whatever is in the trust store of the machine it runs+on, so an internally signed Loki works once its root certificate is in that store. In a container,+install the certificate into the image, or mount it and set `SSL_CERT_FILE` to the file or+`SSL_CERT_DIR` to a directory of them.++Setting either variable replaces the machine's trust store instead of adding to it. The public+authorities are compiled into the CLI and stay trusted either way, so pointing `SSL_CERT_FILE` at+a single internal root does not break the connection to PostHog.++A certificate the CLI cannot verify stops the run on its first request, with+`invalid peer certificate: UnknownIssuer`. Add the root certificate through one of the routes+above.+## The config```yaml@@ -95,5 +121,28 @@ Widening `range.from` discards the checkpoint and re-imports everything, and say## Retention-Imported records take their retention from when they were imported, not from their own timestamp,-so a backfill expires the configured number of retention days after the import finishes.+PostHog keeps only the records that are still inside the project's retention. A record whose+timestamp plus the retention is already in the past is dropped at intake, even though the request+succeeds, so a range older than the retention adds nothing but transfer time.++Before it sends anything, the import reads the project's logs retention and says which part of the+range would be dropped. `--dry-run` prints the same summary. To keep that part, raise logs+retention in the project settings first.++When part of the range is past retention, the import asks before it goes ahead, and then skips+those records instead of sending them. One answer covers the whole run, even though the cutoff+moves forward while a long import runs. Without a terminal, for example in a Kubernetes Job, the+import stops before sending anything unless you pass `--skip-expired`, which answers the question+in advance.++If the import cannot read the retention, for example because the API key lacks `project:read`,+it says so and asks the same question. Nothing is skipped in that case, and intake still drops+whatever is past retention.++The check uses the project's default logs retention only. Retention rules can give some logs a+longer or shorter retention than the default, and the import does not read them. If you use+retention rules, logs that a longer rule would keep may still be skipped, and logs that a shorter+rule covers may be dropped at intake without a warning.++Records that are kept take their retention from when they were imported, not from their own+timestamp, so they expire the configured number of retention days after the import finishes.diff --git a/cli/src/experimental/logs/checkpoint.rs b/cli/src/experimental/logs/checkpoint.rsnew file mode 100644index 000000000000..8a6e110eb0a3--- /dev/null+++ b/cli/src/experimental/logs/checkpoint.rs@@ -0,0 +1,199 @@+use std::collections::BTreeMap;+use std::path::{Path, PathBuf};++use anyhow::{Context, Result};+use serde::{Deserialize, Serialize};++/// Progress through a run, written after each shard is fully acknowledged.+///+/// The unit is a whole shard because the intake assigns record ids at ingest and `logs34` does not+/// deduplicate, so a resumed run cannot avoid re-sending the shard it was in the middle of. Keeping+/// the unit small bounds that duplication to one shard of one selector.+#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]+pub struct Checkpoint {+ /// The range this progress was built under. A high-water mark alone cannot tell that the+ /// operator widened `range.from`, so a rerun would produce no windows and report success+ /// without importing the newly requested history.+ #[serde(default)]+ range: Option<(i64, i64)>,+ /// Selector to the exclusive end of the last shard completed for it, as a nanosecond epoch.+ #[serde(default)]+ completed_through: BTreeMap<String, i64>,+ #[serde(default)]+ pub records_sent: u64,+ #[serde(default)]+ pub bytes_sent: u64,+}++impl Checkpoint {+ pub fn load(path: &Path) -> Result<Self> {+ match std::fs::read_to_string(path) {+ Ok(contents) => serde_json::from_str(&contents)+ .with_context(|| format!("checkpoint at {} is not readable", path.display())),+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Self::default()),+ Err(error) => Err(error).with_context(|| format!("cannot read {}", path.display())),+ }+ }++ /// Writes through a temporary file in the same directory, so a process killed mid-write leaves+ /// the previous checkpoint intact rather than a truncated one.+ pub fn save(&self, path: &Path) -> Result<()> {+ let parent = path.parent().unwrap_or(Path::new("."));+ std::fs::create_dir_all(parent)+ .with_context(|| format!("cannot create {}", parent.display()))?;++ let temporary: PathBuf = path.with_extension("tmp");+ let encoded = serde_json::to_vec_pretty(self).context("cannot encode the checkpoint")?;+ std::fs::write(&temporary, encoded)+ .with_context(|| format!("cannot write {}", temporary.display()))?;+ std::fs::rename(&temporary, path)+ .with_context(|| format!("cannot move the checkpoint into {}", path.display()))+ }++ /// Discards progress when the configured range starts earlier than the one it was built for,+ /// so widening a range re-imports the part that was never covered rather than silently doing+ /// nothing. A range that only moved its end forward keeps its progress.+ pub fn reconcile_range(&mut self, from_ns: i64, to_ns: i64) -> bool {+ match self.range {+ Some((previous_from, _)) if previous_from <= from_ns => {+ self.range = Some((previous_from.min(from_ns), to_ns));+ false+ }+ Some(_) => {+ self.completed_through.clear();+ self.range = Some((from_ns, to_ns));+ true+ }+ None => {+ self.range = Some((from_ns, to_ns));+ false+ }+ }+ }++ /// The shard a selector should resume from, or `None` when it has never run.+ pub fn resume_from(&self, selector: &str) -> Option<i64> {+ self.completed_through.get(selector).copied()+ }++ /// A shard is only recorded once every record in it is acknowledged. Recording it earlier would+ /// skip data on resume, which is worse than the duplication the shard unit already accepts.+ pub fn complete_shard(&mut self, selector: &str, shard_end_ns: i64, records: u64, bytes: u64) {+ let entry = self+ .completed_through+ .entry(selector.to_string())+ .or_insert(shard_end_ns);+ *entry = (*entry).max(shard_end_ns);+ self.records_sent += records;+ self.bytes_sent += bytes;+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ /// A unique directory per call, removed when the guard drops. Callers hold the guard so the+ /// directory outlives the path they use.+ fn temp_path(name: &str) -> (tempfile::TempDir, PathBuf) {+ let dir = tempfile::TempDir::new().expect("temp dir");+ let path = dir.path().join(name);+ (dir, path)+ }++ #[test]+ fn a_missing_checkpoint_starts_a_run_rather_than_failing_it() {+ let (_guard, path) = temp_path("does-not-exist.json");+ let loaded = Checkpoint::load(&path).expect("starts clean");++ assert_eq!(loaded, Checkpoint::default());+ assert_eq!(loaded.resume_from("{app=\"api\"}"), None);+ }++ #[test]+ fn a_saved_checkpoint_resumes_each_selector_independently() {+ let (_guard, path) = temp_path("two-selectors.json");+ let mut checkpoint = Checkpoint::default();+ checkpoint.complete_shard("{app=\"api\"}", 200, 10, 1000);+ checkpoint.complete_shard("{app=\"web\"}", 500, 5, 500);+ checkpoint.save(&path).expect("saves");++ let loaded = Checkpoint::load(&path).expect("loads");++ assert_eq!(loaded.resume_from("{app=\"api\"}"), Some(200));+ assert_eq!(loaded.resume_from("{app=\"web\"}"), Some(500));+ assert_eq!(loaded.records_sent, 15);+ }++ #[test]+ fn a_shard_completed_out_of_order_never_moves_progress_backwards() {+ // Shards run concurrently, so an earlier one can finish after a later one. Taking the+ // lower value would re-send everything between them on resume.+ let mut checkpoint = Checkpoint::default();++ checkpoint.complete_shard("{app=\"api\"}", 900, 1, 1);+ checkpoint.complete_shard("{app=\"api\"}", 300, 1, 1);++ assert_eq!(checkpoint.resume_from("{app=\"api\"}"), Some(900));+ }++ #[test]+ fn widening_the_range_discards_progress_instead_of_importing_nothing() {+ // The high-water mark alone would make shards() produce no windows, so the rerun would+ // report success without importing the newly requested history.+ let mut checkpoint = Checkpoint::default();+ checkpoint.reconcile_range(100, 500);+ checkpoint.complete_shard("{app=\"api\"}", 500, 10, 10);++ let discarded = checkpoint.reconcile_range(50, 500);++ assert!(discarded, "an earlier start must reset progress");+ assert_eq!(checkpoint.resume_from("{app=\"api\"}"), None);+ }++ #[test]+ fn extending_the_range_forward_keeps_progress() {+ let mut checkpoint = Checkpoint::default();+ checkpoint.reconcile_range(100, 500);+ checkpoint.complete_shard("{app=\"api\"}", 500, 10, 10);++ let discarded = checkpoint.reconcile_range(100, 900);++ assert!(!discarded, "a later end must not replay what is done");+ assert_eq!(checkpoint.resume_from("{app=\"api\"}"), Some(500));+ }++ #[test]+ fn a_truncated_checkpoint_is_reported_rather_than_silently_restarting() {+ // Silently starting over would re-import months of data without saying so.+ let (_guard, path) = temp_path("truncated.json");+ std::fs::write(&path, b"{\"completed_through\": {").expect("writes");++ let error = Checkpoint::load(&path).expect_err("must not be treated as a fresh run");++ assert!(format!("{error:#}").contains("not readable"));+ }++ #[test]+ fn saving_replaces_the_previous_checkpoint_atomically() {+ let (_guard, path) = temp_path("atomic.json");+ let mut first = Checkpoint::default();+ first.complete_shard("{app=\"api\"}", 100, 1, 1);+ first.save(&path).expect("first save");++ let mut second = Checkpoint::default();+ second.complete_shard("{app=\"api\"}", 400, 2, 2);+ second.save(&path).expect("second save");++ assert_eq!(+ Checkpoint::load(&path)+ .unwrap()+ .resume_from("{app=\"api\"}"),+ Some(400)+ );+ assert!(+ !path.with_extension("tmp").exists(),+ "the temporary file must be moved, not left"+ );+ }+}diff --git a/cli/src/experimental/logs/command.rs b/cli/src/experimental/logs/command.rsindex 078f6a5d1e05..3cbd1ccf1400 100644--- a/cli/src/experimental/logs/command.rs+++ b/cli/src/experimental/logs/command.rs@@ -27,10 +27,29 @@ pub enum ImportSource {/// Report the size, duration and mapping coverage of the run without sending anything.#[arg(long, default_value_t = false)]dry_run: bool,++ /// Skip records older than the project's logs retention without asking. Required when no+ /// terminal can answer the confirmation, for example in a Kubernetes Job.+ #[arg(long, default_value_t = false)]+ skip_expired: bool,},}+use std::io::IsTerminal;+use anyhow::{bail, Result};+use inquire::InquireError;++use super::config::LokiImportConfig;+use super::loki::{LokiAuth, LokiClient};+use super::mapping::Mapper;+use super::plan::{render, RunPlan};+use super::project::{check_login_matches_target, login_project_token};+use super::retention::{assess, project_retention_days, Expiry};++/// How many records a dry run pulls to prove the mapping. Large enough that a rule matching a+/// minority of records still shows a non-zero count, small enough to return in seconds.+const SAMPLE_RECORDS: usize = 100;impl LogsCommand {pub fn run(&self) -> Result<()> {@@ -43,20 +62,156 @@ impl LogsCommand {impl ImportSource {fn run(&self) -> Result<()> {match self {- ImportSource::Loki { config, .. } => {- // Parsing and validating the config is the whole of this layer. Reading Loki and- // sending to the intake arrives with the engine.+ ImportSource::Loki {+ config,+ checkpoint,+ dry_run,+ skip_expired,+ } => {let text = std::fs::read_to_string(config).map_err(|error| {anyhow::anyhow!("cannot read {}: {error}", config.display())})?;- super::config::LokiImportConfig::parse(&text)?;+ let parsed = LokiImportConfig::parse(&text)?;++ let target_key = std::env::var(super::run::PROJECT_KEY_VAR)+ .ok()+ .filter(|key| !key.is_empty());+ check_login_matches_target(+ login_project_token().as_deref(),+ target_key.as_deref(),+ )?;++ let retention_days = project_retention_days();+ let expiry = assess(+ parsed.range.from,+ parsed.range.to,+ retention_days,+ chrono::Utc::now(),+ );- bail!(- "this build validates the import config but cannot run an import yet. \- The config at {} parsed cleanly.",- config.display()- )+ if *dry_run {+ return dry_run_report(&parsed, &expiry);+ }++ confirm_expiry(&expiry, *skip_expired)?;+ run_import(&parsed, checkpoint, retention_days)}}}}++/// Intake drops records older than retention without telling the sender, so the run states what+/// it will drop and goes ahead only on an explicit yes.+fn confirm_expiry(expiry: &Expiry, skip_expired: bool) -> Result<()> {+ let Some(confirmation) = expiry.confirmation() else {+ return Ok(());+ };+ eprintln!("{}", confirmation.summary);+ if skip_expired {+ return Ok(());+ }+ // The prompt reads stdin, so stdin is what has to be a terminal. Output piped to a log file+ // must not stop a run that can still be answered.+ if !std::io::stdin().is_terminal() {+ bail!("Stopped before sending anything. Pass --skip-expired to go ahead without asking.");+ }+ let confirmed = match inquire::Confirm::new(&confirmation.prompt)+ .with_default(false)+ .prompt()+ {+ Ok(answer) => answer,+ Err(InquireError::OperationCanceled | InquireError::OperationInterrupted) => false,+ Err(error) => return Err(error.into()),+ };+ if !confirmed {+ bail!("Import cancelled. Nothing was sent.");+ }+ Ok(())+}++fn dry_run_report(config: &LokiImportConfig, expiry: &Expiry) -> Result<()> {+ let client = LokiClient::new(+ &config.source,+ LokiAuth::from_env(),+ reqwest::blocking::Client::builder()+ .timeout(std::time::Duration::from_secs(120))+ .build()?,+ );+ let mapper = Mapper::new(config.extract.clone())?;++ // Each selector gets an equal share of the sample. A first selector that filled the whole+ // sample would report a field that only later selectors carry as NOT FOUND.+ let per_selector = SAMPLE_RECORDS.div_ceil(config.range.select.len());+ let from = expiry.effective_from(config.range.from, config.range.to);+ let mut volume = 0;+ let mut sample = Vec::new();+ // A range wholly past retention leaves nothing to size or sample.+ for selector in config+ .range+ .select+ .iter()+ .filter(|_| from < config.range.to)+ {+ volume += client.volume_bytes(selector, from, config.range.to)?;+ let share = per_selector.min(SAMPLE_RECORDS - sample.len());+ if share > 0 {+ sample.extend(client.sample(selector, from, config.range.to, share)?);+ }+ }++ let hits = mapper.hits(&sample);+ let mapped: Vec<_> = sample.iter().map(|entry| mapper.map(entry)).collect();+ // First record that actually carried each field. Reading only the first record would report+ // NOT FOUND for a field most records have, in the output built to prevent exactly that.+ let samples = [+ (+ "service_name",+ mapped.iter().find_map(|r| r.service_name.clone()),+ ),+ (+ "severity",+ mapped+ .iter()+ .find_map(|r| r.severity.as_ref().map(|(text, _)| text.clone())),+ ),+ ("trace_id", mapped.iter().find_map(|r| r.trace_id.clone())),+ ("span_id", mapped.iter().find_map(|r| r.span_id.clone())),+ ];++ let sample_bytes: u64 = sample.iter().map(|entry| entry.line.len() as u64).sum();+ let plan = RunPlan::build(config, from, volume, sample.len() as u64, sample_bytes);+ print!("{}", render(config, &plan, &hits, &samples));+ if let Some(confirmation) = expiry.confirmation() {+ println!("\n{}", confirmation.summary);+ }+ Ok(())+}++fn run_import(+ config: &LokiImportConfig,+ checkpoint: &std::path::Path,+ retention_days: Option<i64>,+) -> Result<()> {+ use super::run::{intake_url, project_key_from_env, Importer};++ let http = reqwest::blocking::Client::builder()+ .timeout(std::time::Duration::from_secs(120))+ .build()?;+ let client = LokiClient::new(&config.source, LokiAuth::from_env(), http.clone());+ let mapper = Mapper::new(config.extract.clone())?;+ // The CLI already resolved the host from --host, then the stored login, then the default.+ // Re-deriving it here would send an EU project's logs to US.+ let host = crate::invocation_context::context().config.host.clone();++ Importer {+ config,+ loki: &client,+ mapper: &mapper,+ http: &http,+ intake_url: intake_url(&host, config.range.from),+ project_key: project_key_from_env()?,+ checkpoint_path: checkpoint,+ retention_days,+ }+ .run()+}diff --git a/cli/src/experimental/logs/emit.rs b/cli/src/experimental/logs/emit.rsnew file mode 100644index 000000000000..f1c0d75b2a85--- /dev/null+++ b/cli/src/experimental/logs/emit.rs@@ -0,0 +1,246 @@+use std::collections::BTreeMap;++use serde_json::{json, Value as Json};++use super::mapping::MappedRecord;++/// A batch of records serialized as one OTLP/JSON request body.+///+/// The intake accepts protobuf or JSON, and JSON keeps `opentelemetry-proto` out of a binary that+/// ships to seven targets through npm.+#[derive(Debug, Clone, PartialEq)]+pub struct Batch {+ pub body: Vec<u8>,+ pub records: usize,+}++/// Groups records into request bodies that each stay under `max_bytes`.+///+/// Sizes each record once and accumulates, rather than re-encoding the batch per record, which+/// would be quadratic in the batch size. The running total counts every record's resource+/// attributes, while the encoded body writes them once per distinct resource, so the estimate is+/// never below the real body and a batch cannot overshoot the ceiling.+///+/// A single record over the ceiling still becomes its own batch. Dropping it would lose data+/// silently, and the intake answers an oversized body with 413, which the caller surfaces.+pub fn batch_records(records: &[MappedRecord], max_bytes: usize) -> Vec<Batch> {+ // `{"resourceLogs":[{"resource":{"attributes":[]},"scopeLogs":[{"logRecords":[]}]}]}`+ const ENVELOPE_BYTES: usize = 128;++ let mut batches = Vec::new();+ let mut current: Vec<&MappedRecord> = Vec::new();+ let mut estimate = ENVELOPE_BYTES;++ for record in records {+ let size = estimated_size(record);++ if !current.is_empty() && estimate + size > max_bytes {+ batches.push(Batch {+ body: encode(¤t),+ records: current.len(),+ });+ current.clear();+ estimate = ENVELOPE_BYTES;+ }++ current.push(record);+ estimate += size;+ }++ if !current.is_empty() {+ batches.push(Batch {+ body: encode(¤t),+ records: current.len(),+ });+ }++ batches+}++/// Upper bound on the bytes one record adds, counting its resource attributes even though the+/// encoder writes them once per resource group.+fn estimated_size(record: &MappedRecord) -> usize {+ let log = serde_json::to_vec(&log_record(record)).map_or(0, |bytes| bytes.len());+ let resource: usize = record+ .resource_attributes+ .iter()+ .map(|(key, value)| key.len() + value.len() + 40)+ .sum();+ let service = record+ .service_name+ .as_ref()+ .map_or(0, |name| name.len() + 52);+ // One comma between array elements, plus the per-resource scopeLogs wrapper.+ log + resource + service + 96+}++/// One OTLP/JSON `resourceLogs` entry per distinct resource, which is what keeps the resource+/// attributes from repeating on every record.+fn encode(records: &[&MappedRecord]) -> Vec<u8> {+ let mut grouped: BTreeMap<Vec<(String, String)>, Vec<&MappedRecord>> = BTreeMap::new();+ for record in records {+ grouped+ .entry(resource_key(record))+ .or_default()+ .push(record);+ }++ let resource_logs: Vec<Json> = grouped+ .into_iter()+ .map(|(key, records)| {+ json!({+ "resource": { "attributes": attributes(key.into_iter()) },+ "scopeLogs": [{ "logRecords": records.iter().map(|r| log_record(r)).collect::<Vec<_>>() }],+ })+ })+ .collect();++ serde_json::to_vec(&json!({ "resourceLogs": resource_logs })).unwrap_or_default()+}++/// `service.name` joins the resource attributes, so records that share a service and labels share+/// one resource block.+fn resource_key(record: &MappedRecord) -> Vec<(String, String)> {+ let mut key: Vec<(String, String)> = record+ .resource_attributes+ .iter()+ .map(|(k, v)| (k.clone(), v.clone()))+ .collect();+ if let Some(service) = &record.service_name {+ key.push(("service.name".to_string(), service.clone()));+ }+ key.sort();+ key+}++fn attributes(pairs: impl Iterator<Item = (String, String)>) -> Vec<Json> {+ pairs+ .map(|(key, value)| json!({ "key": key, "value": { "stringValue": value } }))+ .collect()+}++fn log_record(record: &MappedRecord) -> Json {+ let mut fields = json!({+ "timeUnixNano": record.timestamp_ns.to_string(),+ "body": { "stringValue": record.body },+ "attributes": attributes(record.attributes.iter().map(|(k, v)| (k.clone(), v.clone()))),+ });++ let object = fields.as_object_mut().expect("built from a json! object");+ if let Some((text, number)) = &record.severity {+ object.insert("severityText".to_string(), json!(text));+ object.insert("severityNumber".to_string(), json!(number));+ }+ // OTLP/JSON carries trace and span ids as hex strings. Lowercase them so they join the+ // spans table, which stores them uppercase but matches on a normalized form.+ if let Some(trace_id) = &record.trace_id {+ object.insert("traceId".to_string(), json!(trace_id.to_lowercase()));+ }+ if let Some(span_id) = &record.span_id {+ object.insert("spanId".to_string(), json!(span_id.to_lowercase()));+ }++ fields+}++#[cfg(test)]+mod tests {+ use super::*;++ fn record(service: &str, body: &str) -> MappedRecord {+ MappedRecord {+ timestamp_ns: 1_700_000_000_000_000_000,+ body: body.to_string(),+ service_name: Some(service.to_string()),+ severity: Some(("error".to_string(), 17)),+ trace_id: None,+ span_id: None,+ resource_attributes: BTreeMap::from([("namespace".to_string(), "prod".to_string())]),+ attributes: BTreeMap::from([("pod".to_string(), "abc".to_string())]),+ }+ }++ #[test]+ fn every_batch_stays_under_the_ceiling() {+ let records: Vec<MappedRecord> = (0..500)+ .map(|i| {+ record(+ "api",+ &format!("line {i} with some padding to give it weight"),+ )+ })+ .collect();++ let batches = batch_records(&records, 4096);++ assert!(batches.len() > 1, "expected the ceiling to force a split");+ for batch in &batches {+ assert!(+ batch.body.len() <= 4096,+ "a batch encoded to {} bytes, over the 4096 ceiling",+ batch.body.len()+ );+ }+ let total: usize = batches.iter().map(|b| b.records).sum();+ assert_eq!(total, 500, "every record must land in exactly one batch");+ }++ #[test]+ fn batching_is_linear_enough_to_handle_a_real_shard() {+ // The first implementation re-encoded the whole batch per record, which made this hang.+ let records: Vec<MappedRecord> = (0..20_000)+ .map(|i| record("api", &format!("line {i}")))+ .collect();++ let batches = batch_records(&records, 1_500_000);++ let total: usize = batches.iter().map(|b| b.records).sum();+ assert_eq!(total, 20_000);+ }++ #[test]+ fn a_record_over_the_ceiling_becomes_its_own_batch_rather_than_being_dropped() {+ let records = vec![+ record("api", "small"),+ record("api", &"x".repeat(9000)),+ record("api", "small again"),+ ];++ let batches = batch_records(&records, 4096);++ let total: usize = batches.iter().map(|b| b.records).sum();+ assert_eq!(total, 3, "the oversized record must still be emitted");+ }++ #[test]+ fn records_sharing_a_resource_are_written_under_one_resource_block() {+ let batches = batch_records(+ &[+ record("api", "one"),+ record("api", "two"),+ record("web", "three"),+ ],+ 1_000_000,+ );++ let json: serde_json::Value = serde_json::from_slice(&batches[0].body).expect("valid json");+ let resources = json["resourceLogs"].as_array().expect("resourceLogs");++ assert_eq!(resources.len(), 2, "one block per distinct service");+ }++ #[test]+ fn severity_and_ids_are_omitted_rather_than_sent_empty() {+ let mut bare = record("api", "line");+ bare.severity = None;+ bare.service_name = None;++ let batches = batch_records(&[bare], 1_000_000);+ let json: serde_json::Value = serde_json::from_slice(&batches[0].body).expect("valid json");+ let log = &json["resourceLogs"][0]["scopeLogs"][0]["logRecords"][0];++ assert!(log.get("severityText").is_none());+ assert!(log.get("traceId").is_none());+ assert_eq!(log["body"]["stringValue"], "line");+ }+}diff --git a/cli/src/experimental/logs/loki.rs b/cli/src/experimental/logs/loki.rsnew file mode 100644index 000000000000..f26eb315d7ee--- /dev/null+++ b/cli/src/experimental/logs/loki.rs@@ -0,0 +1,497 @@+use std::collections::HashMap;++use anyhow::{bail, Context, Result};+use chrono::{DateTime, Utc};+use reqwest::blocking::{Client, RequestBuilder, Response};+use reqwest::StatusCode;+use serde::Deserialize;++use super::config::Source;++/// Entries kept per page, well under Loki's per-request cap (see `INSTANT_LIMIT`).+const PAGE_LIMIT: usize = 1000;++/// The most entries one request may ask for under Loki's default `max_entries_limit_per_query`.+/// Reading one instant needs the largest page Loki allows, because it cannot page within an instant.+pub const INSTANT_LIMIT: usize = 5000;++pub struct LokiClient {+ http: Client,+ base_url: String,+ tenant: Option<String>,+ auth: LokiAuth,+}++pub enum LokiAuth {+ None,+ Basic { username: String, password: String },+ Bearer { token: String },+}++impl LokiAuth {+ pub fn from_env() -> Self {+ Self::resolve(+ std::env::var("LOKI_BEARER_TOKEN").ok(),+ std::env::var("LOKI_USERNAME").ok(),+ std::env::var("LOKI_PASSWORD").ok(),+ )+ }++ /// Grafana Cloud uses basic auth with the numeric instance id as the username, while a+ /// self-hosted gateway usually sits behind a bearer token. A bearer token wins when both are+ /// set, rather than silently sending the wrong one.+ fn resolve(bearer: Option<String>, username: Option<String>, password: Option<String>) -> Self {+ if let Some(token) = bearer.filter(|t| !t.is_empty()) {+ return LokiAuth::Bearer { token };+ }+ match (username.filter(|u| !u.is_empty()), password) {+ (Some(username), Some(password)) => LokiAuth::Basic { username, password },+ _ => LokiAuth::None,+ }+ }+}++/// One log line as Loki returns it.+#[derive(Debug, Clone)]+pub struct Entry {+ pub timestamp_ns: i64,+ pub line: String,+ pub structured_metadata: HashMap<String, String>,+ pub labels: HashMap<String, String>,+}++#[derive(Debug, Deserialize)]+struct QueryResponse {+ data: QueryData,+}++#[derive(Debug, Deserialize)]+struct QueryData {+ #[serde(default)]+ result: Vec<StreamResult>,+}++#[derive(Debug, Deserialize)]+struct StreamResult {+ stream: HashMap<String, String>,+ #[serde(default)]+ values: Vec<StreamValue>,+}++/// `[timestamp_ns, line]` before Loki 3.0, `[timestamp_ns, line, {metadata}]` after it.+#[derive(Debug, Deserialize)]+#[serde(untagged)]+enum StreamValue {+ WithMetadata(String, String, HashMap<String, String>),+ Bare(String, String),+}++#[derive(Debug, Deserialize)]+struct VolumeResponse {+ data: VolumeData,+}++#[derive(Debug, Deserialize)]+struct VolumeData {+ #[serde(default)]+ result: Vec<VolumeResult>,+}++#[derive(Debug, Deserialize)]+struct VolumeResult {+ #[serde(default)]+ values: Vec<(f64, String)>,+}++impl LokiClient {+ pub fn new(source: &Source, auth: LokiAuth, http: Client) -> Self {+ Self {+ http,+ base_url: source.url.as_str().trim_end_matches('/').to_string(),+ tenant: source.tenant.clone(),+ auth,+ }+ }++ fn get(&self, path: &str) -> RequestBuilder {+ let mut request = self.http.get(format!("{}{path}", self.base_url));+ if let Some(tenant) = &self.tenant {+ request = request.header("X-Scope-OrgID", tenant);+ }+ match &self.auth {+ LokiAuth::None => request,+ LokiAuth::Basic { username, password } => request.basic_auth(username, Some(password)),+ LokiAuth::Bearer { token } => request.bearer_auth(token),+ }+ }++ /// Bytes stored per selector over a window, used to size a run before it moves any data.+ pub fn volume_bytes(+ &self,+ selector: &str,+ start: DateTime<Utc>,+ end: DateTime<Utc>,+ ) -> Result<u64> {+ let response = send(+ self.get("/loki/api/v1/index/volume_range").query(&[+ ("query", selector),+ ("start", &nanos(start)?.to_string()),+ ("end", &nanos(end)?.to_string()),+ ("step", "24h"),+ ]),+ "a volume lookup",+ )?;++ let body: VolumeResponse = decode(response, "index/volume_range")?;+ let total = body+ .data+ .result+ .iter()+ .flat_map(|series| series.values.iter())+ .filter_map(|(_, value)| value.parse::<f64>().ok())+ .sum::<f64>();+ Ok(total as u64)+ }++ /// One page of a shard, oldest first.+ pub fn query_page(&self, selector: &str, start_ns: i64, end: DateTime<Utc>) -> Result<Page> {+ // One more than is kept, so a full page is distinguishable from an exhausted shard without+ // inferring it from the count.+ let entries = self.query_range(selector, start_ns, nanos(end)?, PAGE_LIMIT + 1)?;+ Ok(split_page(entries, PAGE_LIMIT))+ }++ pub fn sample(+ &self,+ selector: &str,+ start: DateTime<Utc>,+ end: DateTime<Utc>,+ limit: usize,+ ) -> Result<Vec<Entry>> {+ self.query_range(selector, nanos(start)?, nanos(end)?, limit)+ }++ /// Every entry at exactly `at_ns`, or `None` when the instant holds `INSTANT_LIMIT` entries or+ /// more, which no single request can read.+ pub fn query_instant(&self, selector: &str, at_ns: i64) -> Result<Option<Vec<Entry>>> {+ // `end` is exclusive, so this range holds one nanosecond.+ let entries = self.query_range(selector, at_ns, at_ns + 1, INSTANT_LIMIT)?;+ Ok((entries.len() < INSTANT_LIMIT).then_some(entries))+ }++ fn query_range(+ &self,+ selector: &str,+ start_ns: i64,+ end_ns: i64,+ limit: usize,+ ) -> Result<Vec<Entry>> {+ let response = send(+ self.get("/loki/api/v1/query_range").query(&[+ ("query", selector),+ ("start", &start_ns.to_string()),+ ("end", &end_ns.to_string()),+ ("direction", "forward"),+ ("limit", &limit.to_string()),+ ]),+ "a query_range page",+ )?;++ let body: QueryResponse = decode(response, "query_range")?;+ entries_from(body)+ }+}++#[derive(Debug)]+pub enum Page {+ Last(Vec<Entry>),+ More {+ entries: Vec<Entry>,+ resume_at: i64,+ },+ /// A full page that holds one instant only. Loki answers every query starting at that instant+ /// with the same page, so paging cannot get past it.+ Crowded(i64),+}++/// `entries` is one request of up to `limit + 1` entries, oldest first.+///+/// Loki truncates a response by entry count, so the instant of the entry past the limit can be cut+/// short. Every instant before it is complete, so the page keeps only those and the next page starts+/// at that instant. Nothing is sent twice and nothing needs to be deduplicated.+fn split_page(entries: Vec<Entry>, limit: usize) -> Page {+ let Some(overflow) = entries.get(limit) else {+ return Page::Last(entries);+ };+ let resume_at = overflow.timestamp_ns;+ let complete = entries.partition_point(|entry| entry.timestamp_ns < resume_at);+ if complete == 0 {+ return Page::Crowded(resume_at);+ }+ let mut entries = entries;+ entries.truncate(complete);+ Page::More { entries, resume_at }+}++/// Flattens Loki's per-stream blocks into one timestamp-ordered run.+fn entries_from(body: QueryResponse) -> Result<Vec<Entry>> {+ let mut entries = Vec::new();+ for stream in body.data.result {+ for value in stream.values {+ let (raw_ts, line, metadata) = match value {+ StreamValue::WithMetadata(ts, line, metadata) => (ts, line, metadata),+ StreamValue::Bare(ts, line) => (ts, line, HashMap::new()),+ };+ let timestamp_ns = raw_ts+ .parse::<i64>()+ .with_context(|| format!("Loki returned an unparseable timestamp: {raw_ts}"))?;+ entries.push(Entry {+ timestamp_ns,+ line,+ structured_metadata: metadata,+ labels: stream.stream.clone(),+ });+ }+ }++ // Loki returns one block per stream, so a page arrives interleaved across streams.+ entries.sort_by_key(|entry| entry.timestamp_ns);+ Ok(entries)+}++/// The config rejects a range outside chrono's nanosecond span, so `None` here means the caller+/// bypassed validation rather than that the user asked for it.+fn nanos(at: DateTime<Utc>) -> Result<i64> {+ at.timestamp_nanos_opt()+ .with_context(|| format!("{at} is outside the range Loki nanosecond epochs can express"))+}++/// reqwest exposes no typed variant for a trust failure, so this matches the rustls message.+fn tls_trust_hint(error: &(dyn std::error::Error + 'static)) -> &'static str {+ let mut cause = Some(error);+ while let Some(current) = cause {+ if current.to_string().contains("invalid peer certificate") {+ return " The certificate is signed by an authority this machine does not trust. \+ Install that authority's root certificate on this machine, or set SSL_CERT_FILE \+ to a PEM file holding it.";+ }+ cause = current.source();+ }+ ""+}++fn send(request: RequestBuilder, what: &str) -> Result<Response> {+ request.send().map_err(|error| {+ let hint = tls_trust_hint(&error);+ anyhow::Error::new(error).context(format!("failed to reach Loki for {what}.{hint}"))+ })+}++fn decode<T: serde::de::DeserializeOwned>(response: Response, endpoint: &str) -> Result<T> {+ let status = response.status();+ if !status.is_success() {+ let body = response.text().unwrap_or_default();+ let hint = match status {+ StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN => {+ " Check LOKI_USERNAME/LOKI_PASSWORD or LOKI_BEARER_TOKEN."+ }+ StatusCode::BAD_REQUEST => {+ " Check the selector and that the shard is inside Loki's max_query_length."+ }+ StatusCode::TOO_MANY_REQUESTS => " Loki is rate limiting this query; retry later.",+ _ => "",+ };+ bail!("Loki {endpoint} returned {status}.{hint} Body: {body}");+ }+ response+ .json::<T>()+ .with_context(|| format!("failed to decode the Loki {endpoint} response"))+}++#[cfg(test)]+mod tests {+ use super::*;++ fn at(timestamps: &[i64]) -> Vec<Entry> {+ timestamps+ .iter()+ .enumerate()+ .map(|(i, ×tamp_ns)| Entry {+ timestamp_ns,+ line: format!("line {i}"),+ structured_metadata: HashMap::new(),+ labels: HashMap::new(),+ })+ .collect()+ }++ fn timestamps(entries: &[Entry]) -> Vec<i64> {+ entries.iter().map(|entry| entry.timestamp_ns).collect()+ }++ #[test]+ fn a_page_keeps_only_complete_instants_and_resumes_at_the_cut_one() {+ // Loki cut the response inside instant 30, so its entries wait for the next page, which+ // starts at 30 and returns all of them. Sending them now would send them twice.+ match split_page(at(&[10, 20, 30, 30]), 3) {+ Page::More { entries, resume_at } => {+ assert_eq!(timestamps(&entries), [10, 20]);+ assert_eq!(resume_at, 30);+ }+ page => panic!("expected More, got {page:?}"),+ }+ }++ #[test]+ fn a_full_page_of_one_instant_is_crowded_rather_than_empty() {+ // Keeping no entries and resuming at the same instant would ask Loki for the same page+ // forever.+ assert!(matches!(+ split_page(at(&[30, 30, 30, 30]), 3),+ Page::Crowded(30)+ ));+ }++ #[test]+ fn a_page_under_the_limit_is_the_last_and_keeps_everything() {+ match split_page(at(&[10, 20, 20]), 3) {+ Page::Last(entries) => assert_eq!(timestamps(&entries), [10, 20, 20]),+ page => panic!("expected Last, got {page:?}"),+ }+ }++ #[derive(Debug)]+ struct Layer(&'static str, Option<Box<Layer>>);++ impl std::fmt::Display for Layer {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.write_str(self.0)+ }+ }++ impl std::error::Error for Layer {+ fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {+ self.1+ .as_deref()+ .map(|inner| inner as &(dyn std::error::Error + 'static))+ }+ }++ #[test]+ fn tls_trust_hint_reads_the_whole_chain() {+ // The trust failure is never the outermost error, which is what this pins.+ let trust_failure = Layer(+ "error sending request for url (https://loki.example.com)",+ Some(Box::new(Layer(+ "invalid peer certificate: UnknownIssuer",+ None,+ ))),+ );+ assert!(tls_trust_hint(&trust_failure).contains("SSL_CERT_FILE"));++ let unreachable = Layer("connection refused", None);+ assert!(tls_trust_hint(&unreachable).is_empty());+ }++ fn parse(json: &str) -> Vec<Entry> {+ let body: QueryResponse = serde_json::from_str(json).expect("decodes");+ entries_from(body).expect("entries")+ }++ #[test]+ fn decodes_entries_with_and_without_structured_metadata() {+ // Loki before 3.0 returns two elements per value, 3.0 and later return three.+ let entries = parse(+ r#"{"data":{"result":[+ {"stream":{"app":"api"},"values":[+ ["1700000000000000001","old shape"]+ ]},+ {"stream":{"app":"web"},"values":[+ ["1700000000000000002","new shape",{"trace_id":"abc"}]+ ]}+ ]}}"#,+ );++ assert_eq!(entries.len(), 2);+ assert!(entries[0].structured_metadata.is_empty());+ assert_eq!(+ entries[1]+ .structured_metadata+ .get("trace_id")+ .map(String::as_str),+ Some("abc")+ );+ assert_eq!(+ entries[1].labels.get("app").map(String::as_str),+ Some("web")+ );+ }++ #[test]+ fn merges_interleaved_streams_into_timestamp_order() {+ // Loki returns one block per stream, so a page arrives out of order across streams.+ let entries = parse(+ r#"{"data":{"result":[+ {"stream":{"app":"a"},"values":[["300","third"],["100","first"]]},+ {"stream":{"app":"b"},"values":[["200","second"]]}+ ]}}"#,+ );++ let lines: Vec<&str> = entries.iter().map(|e| e.line.as_str()).collect();+ assert_eq!(lines, ["first", "second", "third"]);+ }++ #[test]+ fn an_empty_result_decodes_rather_than_erroring() {+ assert!(parse(r#"{"data":{"result":[]}}"#).is_empty());+ assert!(parse(r#"{"data":{}}"#).is_empty());+ }++ #[test]+ fn auth_resolution_picks_one_scheme() {+ let some = |s: &str| Some(s.to_string());++ // (case, bearer, username, password, expected scheme)+ let cases = [+ (+ "a bearer token wins over basic",+ some("tok"),+ some("123"),+ some("pw"),+ "bearer",+ ),+ (+ "basic when no bearer token",+ None,+ some("123"),+ some("pw"),+ "basic",+ ),+ (+ "an empty bearer falls through",+ some(""),+ some("123"),+ some("pw"),+ "basic",+ ),+ (+ "a username with no password is not basic",+ None,+ some("123"),+ None,+ "none",+ ),+ ("nothing set", None, None, None, "none"),+ ];++ for (case, bearer, username, password, expected) in cases {+ let resolved = match LokiAuth::resolve(bearer, username, password) {+ LokiAuth::Bearer { .. } => "bearer",+ LokiAuth::Basic { .. } => "basic",+ LokiAuth::None => "none",+ };++ assert_eq!(resolved, expected, "{case}");+ }+ }+}diff --git a/cli/src/experimental/logs/mapping.rs b/cli/src/experimental/logs/mapping.rsnew file mode 100644index 000000000000..38f84c53ea91--- /dev/null+++ b/cli/src/experimental/logs/mapping.rs@@ -0,0 +1,418 @@+use std::collections::BTreeMap;++use regex::Regex;+use serde_json::Value as Json;++use super::config::{Extract, Extractor, Extractors};+use super::loki::Entry;++/// One Loki entry rendered into the fields an OTLP log record carries.+#[derive(Debug, Clone, PartialEq)]+pub struct MappedRecord {+ pub timestamp_ns: i64,+ pub body: String,+ pub service_name: Option<String>,+ pub severity: Option<(String, i32)>,+ pub trace_id: Option<String>,+ pub span_id: Option<String>,+ pub resource_attributes: BTreeMap<String, String>,+ pub attributes: BTreeMap<String, String>,+}++/// Which fields a mapping actually produced, counted over a sample so `--dry-run` can report a+/// rule that silently matches nothing.+#[derive(Debug, Default, Clone, PartialEq)]+pub struct MappingHits {+ pub total: usize,+ pub service_name: usize,+ pub severity: usize,+ pub trace_id: usize,+ pub span_id: usize,+}++pub struct Mapper {+ extract: Extract,+ compiled: Vec<Regex>,+}++impl Mapper {+ /// Compiles every regex extractor once. The config already proved they compile, so a failure+ /// here means the config was bypassed.+ pub fn new(extract: Extract) -> anyhow::Result<Self> {+ let mut compiled = Vec::new();+ for extractor in all_extractors(&extract) {+ if let Extractor::Regex { pattern, .. } = extractor {+ compiled.push(Regex::new(pattern)?);+ }+ }+ Ok(Self { extract, compiled })+ }++ pub fn map(&self, entry: &Entry) -> MappedRecord {+ let service_name = self.first_match(self.extract.service_name.as_slice(), entry);+ let severity = self+ .extract+ .severity+ .as_ref()+ .and_then(|e| self.first_match(e.as_slice(), entry))+ .map(|text| normalize_severity(&text));++ let (resource_attributes, mut attributes) = self.split_labels(entry);++ for (name, extractors) in &self.extract.extra_attributes {+ if let Some(value) = self.first_match(extractors.as_slice(), entry) {+ attributes.insert(name.clone(), value);+ }+ }++ MappedRecord {+ timestamp_ns: entry.timestamp_ns,+ body: entry.line.clone(),+ service_name,+ severity,+ trace_id: self+ .optional(self.extract.trace_id.as_ref(), entry)+ .and_then(|id| normalize_hex_id(&id, 32)),+ span_id: self+ .optional(self.extract.span_id.as_ref(), entry)+ .and_then(|id| normalize_hex_id(&id, 16)),+ resource_attributes,+ attributes,+ }+ }++ pub fn hits(&self, entries: &[Entry]) -> MappingHits {+ let mut hits = MappingHits {+ total: entries.len(),+ ..Default::default()+ };+ for entry in entries {+ let record = self.map(entry);+ hits.service_name += usize::from(record.service_name.is_some());+ hits.severity += usize::from(record.severity.is_some());+ hits.trace_id += usize::from(record.trace_id.is_some());+ hits.span_id += usize::from(record.span_id.is_some());+ }+ hits+ }++ fn optional(&self, extractors: Option<&Extractors>, entry: &Entry) -> Option<String> {+ self.first_match(extractors?.as_slice(), entry)+ }++ fn first_match(&self, extractors: &[Extractor], entry: &Entry) -> Option<String> {+ extractors+ .iter()+ .find_map(|extractor| self.evaluate(extractor, entry))+ }++ fn evaluate(&self, extractor: &Extractor, entry: &Entry) -> Option<String> {+ let found = match extractor {+ Extractor::Label { name } => entry.labels.get(name).cloned(),+ Extractor::StructuredMetadata { key } => entry.structured_metadata.get(key).cloned(),+ Extractor::JsonField { path } => json_field(&entry.line, path),+ Extractor::Regex { pattern, group } => self+ .compiled+ .iter()+ .find(|compiled| compiled.as_str() == pattern)+ .and_then(|compiled| compiled.captures(&entry.line))+ .and_then(|captures| captures.get(*group))+ .map(|matched| matched.as_str().to_string()),+ Extractor::Literal { value } => Some(value.clone()),+ };+ found.filter(|value| !value.is_empty())+ }++ /// Listed labels identify the resource, the rest ride on the record. Every label is a resource+ /// attribute when the key is absent, which is how Loki itself treats stream labels.+ fn split_labels(&self, entry: &Entry) -> (BTreeMap<String, String>, BTreeMap<String, String>) {+ let mut resource = BTreeMap::new();+ let mut attributes = BTreeMap::new();++ for (key, value) in &entry.labels {+ let is_resource = match &self.extract.resource_labels {+ None => true,+ Some(listed) => listed.iter().any(|name| name == key),+ };+ if is_resource {+ resource.insert(key.clone(), value.clone());+ } else {+ attributes.insert(key.clone(), value.clone());+ }+ }++ for (key, value) in &entry.structured_metadata {+ attributes.insert(key.clone(), value.clone());+ }++ (resource, attributes)+ }+}++fn all_extractors(extract: &Extract) -> impl Iterator<Item = &Extractor> {+ extract+ .service_name+ .as_slice()+ .iter()+ .chain(+ [+ extract.severity.as_ref(),+ extract.trace_id.as_ref(),+ extract.span_id.as_ref(),+ ]+ .into_iter()+ .flatten()+ .flat_map(|e| e.as_slice().iter()),+ )+ .chain(+ extract+ .extra_attributes+ .values()+ .flat_map(|e| e.as_slice().iter()),+ )+}++/// Reads a dotted path out of a JSON log line. A line that is not JSON yields nothing rather than+/// an error, because a stream usually mixes JSON and plain lines.+fn json_field(line: &str, path: &str) -> Option<String> {+ let mut current: &Json = &serde_json::from_str::<Json>(line).ok()?;+ for segment in path.split('.') {+ current = current.get(segment)?;+ }+ match current {+ Json::String(value) => Some(value.clone()),+ Json::Null => None,+ other => Some(other.to_string()),+ }+}++/// OTLP carries a trace id as 32 hex characters and a span id as 16. Anything else is dropped+/// rather than sent: the intake would either reject the batch, blaming an unrelated setting, or+/// store an id that joins to no span. Dashes are stripped so a UUID-shaped id still maps.+fn normalize_hex_id(raw: &str, expected: usize) -> Option<String> {+ let stripped: String = raw.chars().filter(|c| *c != '-').collect();+ let looks_hex = stripped.len() == expected && stripped.chars().all(|c| c.is_ascii_hexdigit());+ looks_hex.then(|| stripped.to_lowercase())+}++/// Mirrors `normalize_datadog_severity` in capture-logs, so a log imported here and a log sent+/// live land on the same severity number.+pub fn normalize_severity(text: &str) -> (String, i32) {+ match text.to_lowercase().as_str() {+ "emergency" | "emerg" | "critical" | "crit" | "alert" | "fatal" => {+ ("fatal".to_string(), 21)+ }+ "error" | "err" => ("error".to_string(), 17),+ "warning" | "warn" => ("warn".to_string(), 13),+ "notice" | "info" => ("info".to_string(), 9),+ "debug" => ("debug".to_string(), 5),+ "trace" => ("trace".to_string(), 1),+ _ => ("info".to_string(), 9),+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::experimental::logs::config::LokiImportConfig;++ fn entry(line: &str, labels: &[(&str, &str)], metadata: &[(&str, &str)]) -> Entry {+ Entry {+ timestamp_ns: 1_700_000_000_000_000_000,+ line: line.to_string(),+ labels: labels+ .iter()+ .map(|(k, v)| (k.to_string(), v.to_string()))+ .collect(),+ structured_metadata: metadata+ .iter()+ .map(|(k, v)| (k.to_string(), v.to_string()))+ .collect(),+ }+ }++ fn mapper(extract_yaml: &str) -> Mapper {+ let yaml = format!(+ r#"+version: 1+source: {{ url: https://loki.example.com }}+range:+ from: 2025-03-01T00:00:00Z+ to: 2025-03-02T00:00:00Z+ select: ['{{namespace="prod"}}']+extract:+{extract_yaml}+"#+ );+ let config = LokiImportConfig::parse(&yaml).expect("valid config");+ Mapper::new(config.extract).expect("valid mapper")+ }++ #[test]+ fn severity_falls_through_the_list_in_order() {+ let mapper = mapper(+ " service_name: { type: label, name: app }\n \+ severity:\n - { type: json_field, path: level }\n - { type: label, name: level }",+ );++ let from_json = mapper.map(&entry(r#"{"level":"ERROR"}"#, &[("level", "info")], &[]));+ let from_label = mapper.map(&entry("plain text line", &[("level", "warn")], &[]));+ let neither = mapper.map(&entry("plain text line", &[], &[]));++ assert_eq!(from_json.severity, Some(("error".to_string(), 17)));+ assert_eq!(from_label.severity, Some(("warn".to_string(), 13)));+ assert_eq!(neither.severity, None);+ }++ #[test]+ fn resource_labels_decide_which_side_a_label_lands_on() {+ let listed = mapper(+ " service_name: { type: label, name: app }\n resource_labels: [app, namespace]",+ );+ let absent = mapper(" service_name: { type: label, name: app }");+ let record = entry("line", &[("app", "checkout"), ("pod", "checkout-abc")], &[]);++ let with_list = listed.map(&record);+ let without_list = absent.map(&record);++ assert!(with_list.resource_attributes.contains_key("app"));+ assert!(with_list.attributes.contains_key("pod"));+ assert!(without_list.resource_attributes.contains_key("pod"));+ assert!(without_list.attributes.is_empty());+ }++ #[test]+ fn structured_metadata_rides_on_the_record_not_the_resource() {+ let mapper = mapper(+ " service_name: { type: label, name: app }\n \+ trace_id: { type: structured_metadata, key: trace_id }\n resource_labels: [app]",+ );++ let record = mapper.map(&entry(+ "line",+ &[("app", "api")],+ &[("trace_id", "4bf92f3577b34da6a3ce929d0e0e4736")],+ ));++ assert_eq!(+ record.trace_id,+ Some("4bf92f3577b34da6a3ce929d0e0e4736".to_string())+ );+ assert_eq!(+ record.attributes.get("trace_id").map(String::as_str),+ Some("4bf92f3577b34da6a3ce929d0e0e4736")+ );+ assert!(!record.resource_attributes.contains_key("trace_id"));+ }++ #[test]+ fn an_extractor_that_matches_nothing_yields_none_rather_than_an_empty_string() {+ let mapper = mapper(+ " service_name: { type: label, name: app }\n \+ severity: { type: json_field, path: nested.level }",+ );++ // (case, line, labels)+ let cases = [+ ("a line that is not JSON at all", "not json", vec![]),+ ("JSON without the path", r#"{"other":1}"#, vec![]),+ (+ "the path present but empty",+ r#"{"nested":{"level":""}}"#,+ vec![],+ ),+ (+ "the path present but null",+ r#"{"nested":{"level":null}}"#,+ vec![],+ ),+ ];++ for (case, line, labels) in cases {+ let record = mapper.map(&entry(line, &labels, &[]));++ assert_eq!(record.severity, None, "{case}");+ }+ }++ #[test]+ fn a_trace_id_that_cannot_join_a_span_is_dropped_rather_than_sent() {+ let mapper = mapper(+ " service_name: { type: label, name: app }\n \+ trace_id: { type: structured_metadata, key: trace_id }\n \+ span_id: { type: structured_metadata, key: span_id }",+ );++ // (case, raw trace id, expected)+ let cases = [+ (+ "plain hex",+ "4bf92f3577b34da6a3ce929d0e0e4736",+ Some("4bf92f3577b34da6a3ce929d0e0e4736"),+ ),+ (+ "uppercase is normalized",+ "4BF92F3577B34DA6A3CE929D0E0E4736",+ Some("4bf92f3577b34da6a3ce929d0e0e4736"),+ ),+ (+ "a dashed UUID still maps",+ "4bf92f35-77b3-4da6-a3ce-929d0e0e4736",+ Some("4bf92f3577b34da6a3ce929d0e0e4736"),+ ),+ (+ "a full traceparent is not a trace id",+ "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01",+ None,+ ),+ ("too short", "4bf92f35", None),+ ("not hex", "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz", None),+ ];++ for (case, raw, expected) in cases {+ let record = mapper.map(&entry("line", &[("app", "api")], &[("trace_id", raw)]));++ assert_eq!(record.trace_id.as_deref(), expected, "{case}");+ }+ }++ #[test]+ fn hits_counts_what_a_dry_run_reports() {+ let mapper = mapper(+ " service_name: { type: label, name: app }\n \+ trace_id: { type: structured_metadata, key: trace_id }",+ );+ let entries = vec![+ entry(+ "a",+ &[("app", "api")],+ &[("trace_id", "4bf92f3577b34da6a3ce929d0e0e4736")],+ ),+ entry("b", &[("app", "api")], &[]),+ entry("c", &[], &[]),+ ];++ let hits = mapper.hits(&entries);++ assert_eq!(hits.total, 3);+ assert_eq!(hits.service_name, 2);+ assert_eq!(hits.trace_id, 1);+ }++ #[test]+ fn severity_text_matches_the_intake_table() {+ for (text, expected) in [+ ("CRITICAL", ("fatal", 21)),+ ("err", ("error", 17)),+ ("Warning", ("warn", 13)),+ ("notice", ("info", 9)),+ ("debug", ("debug", 5)),+ ("trace", ("trace", 1)),+ ("something else", ("info", 9)),+ ] {+ let (name, number) = normalize_severity(text);++ assert_eq!((name.as_str(), number), expected, "severity text {text}");+ }+ }+}diff --git a/cli/src/experimental/logs/mod.rs b/cli/src/experimental/logs/mod.rsindex 6d982acc80b8..24ed9726c5b1 100644--- a/cli/src/experimental/logs/mod.rs+++ b/cli/src/experimental/logs/mod.rs@@ -1,2 +1,12 @@+pub mod checkpoint;pub mod command;pub mod config;+pub mod emit;+pub mod loki;+pub mod mapping;+pub mod plan;+pub mod project;+pub mod retention;+pub mod run;+pub mod send;+pub mod shard;diff --git a/cli/src/experimental/logs/plan.rs b/cli/src/experimental/logs/plan.rsnew file mode 100644index 000000000000..0d1f3af8a64e--- /dev/null+++ b/cli/src/experimental/logs/plan.rs@@ -0,0 +1,222 @@+use std::fmt::Write as _;++use chrono::{DateTime, Utc};++use super::config::LokiImportConfig;+use super::mapping::MappingHits;++/// What a run will do, computed before it moves any data.+#[derive(Debug, Clone, PartialEq)]+pub struct RunPlan {+ /// Where the records the run sends begin, which is later than `range.from` when part of the+ /// range is past retention.+ pub from: DateTime<Utc>,+ pub shards: u64,+ pub bytes: u64,+ pub seconds: u64,+}++impl RunPlan {+ /// `sample_records` and `sample_bytes` come from the dry run's sample, and scale the reported+ /// volume into a record count. Using the sample count as the workload would report the time to+ /// send a hundred records, which is about a second for any run.+ pub fn build(+ config: &LokiImportConfig,+ from: DateTime<Utc>,+ volume_bytes: u64,+ sample_records: u64,+ sample_bytes: u64,+ ) -> Self {+ let span = (config.range.to - from).num_seconds().max(0) as u64;+ let shard = config.tuning.shard.seconds().max(1);+ let shards = span.div_ceil(shard) * config.range.select.len() as u64;+ let rate = u64::from(config.tuning.max_records_per_second.get());++ let bytes_per_record = sample_bytes.checked_div(sample_records).unwrap_or(0);+ let total_records = volume_bytes+ .checked_div(bytes_per_record.max(1))+ .unwrap_or(0);++ Self {+ from,+ shards,+ bytes: volume_bytes,+ seconds: if bytes_per_record == 0 {+ 0+ } else {+ total_records.div_ceil(rate)+ },+ }+ }+}++/// The report `--dry-run` prints. A change-control process approves a run from this, so it states+/// the cost before the run and the mapping coverage that decides whether the data will be usable.+pub fn render(+ config: &LokiImportConfig,+ plan: &RunPlan,+ hits: &MappingHits,+ samples: &[(&str, Option<String>)],+) -> String {+ let mut out = String::new();++ let _ = writeln!(out, "Source {}", config.source.url);+ if let Some(tenant) = &config.source.tenant {+ let _ = writeln!(out, "Tenant {tenant}");+ }+ let _ = writeln!(+ out,+ "Range {} to {} ({} days, {} shards)",+ day(plan.from),+ day(config.range.to),+ whole_days(plan.from, config.range.to),+ plan.shards+ );+ let _ = writeln!(+ out,+ "Volume {} across {} selector(s)",+ human_bytes(plan.bytes),+ config.range.select.len()+ );+ let _ = writeln!(+ out,+ "Estimated {} at {} records/sec, {} egress",+ human_duration(plan.seconds),+ config.tuning.max_records_per_second,+ human_bytes(plan.bytes)+ );+ let _ = writeln!(out);+ let _ = writeln!(out, "Mapping, from {} sampled records:", hits.total);++ for (field, example) in samples {+ let matched = match *field {+ "service_name" => hits.service_name,+ "severity" => hits.severity,+ "trace_id" => hits.trace_id,+ "span_id" => hits.span_id,+ _ => 0,+ };+ let detail = match example {+ Some(value) if matched > 0 => format!("e.g. {value:?}"),+ _ => "NOT FOUND, no record carried this field".to_string(),+ };+ let _ = writeln!(out, " {field:<16}{matched:>4}/{:<4} {detail}", hits.total);+ }++ out+}++pub(super) fn day(at: DateTime<Utc>) -> String {+ at.format("%Y-%m-%d").to_string()+}++/// Days from `from` to `to`, a part day counting as a whole one.+pub(super) fn whole_days(from: DateTime<Utc>, to: DateTime<Utc>) -> i64 {+ ((to - from).num_hours().max(0) as u64).div_ceil(24) as i64+}++fn human_bytes(bytes: u64) -> String {+ const UNITS: [&str; 5] = ["B", "KB", "MB", "GB", "TB"];+ let mut value = bytes as f64;+ let mut unit = 0;+ while value >= 1024.0 && unit < UNITS.len() - 1 {+ value /= 1024.0;+ unit += 1;+ }+ if unit == 0 {+ format!("{bytes} B")+ } else {+ format!("{value:.1} {}", UNITS[unit])+ }+}++fn human_duration(seconds: u64) -> String {+ match seconds {+ 0..=59 => format!("{seconds}s"),+ 60..=3599 => format!("{}m", seconds / 60),+ _ => format!("{}h{:02}m", seconds / 3600, (seconds % 3600) / 60),+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::experimental::logs::config::LokiImportConfig;++ fn config(select: &str, shard: &str) -> LokiImportConfig {+ LokiImportConfig::parse(&format!(+ r#"+version: 1+source: {{ url: https://loki.example.com }}+range:+ from: 2025-03-01T00:00:00Z+ to: 2025-03-03T00:00:00Z+ select: [{select}]+extract:+ service_name: {{ type: label, name: app }}+tuning:+ shard: {shard}+"#+ ))+ .expect("valid config")+ }++ #[test]+ fn shard_count_covers_every_selector_and_rounds_up() {+ // Two days at 6h is 8 shards per selector; a partial shard still has to run.+ let two = config("'{a=\"1\"}', '{b=\"2\"}'", "6h");+ let two_selectors = RunPlan::build(&two, two.range.from, 0, 0, 0);+ let five_hours = config("'{a=\"1\"}'", "5h");+ let uneven = RunPlan::build(&five_hours, five_hours.range.from, 0, 0, 0);++ assert_eq!(two_selectors.shards, 16);+ assert_eq!(uneven.shards, 10, "48h at 5h must round up to 10, not 9");+ }++ #[test]+ fn a_field_that_matched_nothing_reads_as_not_found() {+ // This line is why --dry-run exists: it is the only warning before a multi-hour run that+ // an extraction rule will produce nothing.+ let hits = MappingHits {+ total: 100,+ service_name: 100,+ severity: 94,+ trace_id: 0,+ span_id: 0,+ };+ let samples = [+ ("service_name", Some("checkout-api".to_string())),+ ("severity", Some("error".to_string())),+ ("trace_id", None),+ ];++ let one_hour = config("'{a=\"1\"}'", "1h");+ let report = render(+ &one_hour,+ &RunPlan::build(&one_hour, one_hour.range.from, 0, 0, 0),+ &hits,+ &samples,+ );++ assert!(+ report.contains("service_name 100/100"),+ "got:\n{report}"+ );+ assert!(report.contains("trace_id"), "got:\n{report}");+ assert!(report.contains("NOT FOUND"), "got:\n{report}");+ }++ #[test]+ fn sizes_and_durations_render_in_units_a_person_reads() {+ for (bytes, expected) in [+ (512u64, "512 B"),+ (2048, "2.0 KB"),+ (2_600_000_000_000, "2.4 TB"),+ ] {+ assert_eq!(human_bytes(bytes), expected);+ }+ for (seconds, expected) in [(45u64, "45s"), (900, "15m"), (50_400, "14h00m")] {+ assert_eq!(human_duration(seconds), expected);+ }+ }+}diff --git a/cli/src/experimental/logs/project.rs b/cli/src/experimental/logs/project.rsnew file mode 100644index 000000000000..4b2a39d89429--- /dev/null+++ b/cli/src/experimental/logs/project.rs@@ -0,0 +1,53 @@+use anyhow::{bail, Result};+use serde::Deserialize;++#[derive(Debug, Deserialize)]+struct ProjectToken {+ api_token: String,+}++pub fn login_project_token() -> Option<String> {+ let client = &crate::invocation_context::context().client;+ let response = client.send_get(client.env_url("").ok()?, |req| req).ok()?;+ let project: ProjectToken = response.json().ok()?;+ Some(project.api_token)+}++/// The retention check reads the project from `posthog-cli login`, but the import writes to the project+/// that owns the write key. When they differ, the check answers for the wrong project. A missing value+/// skips the comparison: the check already warns when it cannot read the project, and a real run fails+/// later without a write key.+pub fn check_login_matches_target(+ login_token: Option<&str>,+ target_token: Option<&str>,+) -> Result<()> {+ match (login_token, target_token) {+ (Some(login), Some(target)) if login != target => bail!(+ "POSTHOG_PROJECT_API_KEY belongs to a different project than the one you're logged in to, \+ so the retention check would describe the wrong project. Nothing \+ was sent. Run posthog-cli login and choose the project you're importing into."+ ),+ _ => Ok(()),+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn only_two_different_projects_stop_the_run() {+ for (case, login, target, stops) in [+ ("same project", Some("phc_a"), Some("phc_a"), false),+ ("different projects", Some("phc_a"), Some("phc_b"), true),+ ("login project unreadable", None, Some("phc_b"), false),+ ("no write key in a dry run", Some("phc_a"), None, false),+ ] {+ assert_eq!(+ check_login_matches_target(login, target).is_err(),+ stops,+ "{case}"+ );+ }+ }+}diff --git a/cli/src/experimental/logs/retention.rs b/cli/src/experimental/logs/retention.rsnew file mode 100644index 000000000000..d2eeaa933ba0--- /dev/null+++ b/cli/src/experimental/logs/retention.rs@@ -0,0 +1,166 @@+use chrono::{DateTime, TimeDelta, Utc};+use serde::Deserialize;++use super::plan::{day, whole_days};++/// Kept in sync with `DEFAULT_LOGS_RETENTION_DAYS` in `posthog/models/team/logs_retention.py`,+/// which applies when a project never set its logs retention.+const DEFAULT_RETENTION_DAYS: i64 = 14;++#[derive(Debug, Deserialize)]+struct Team {+ #[serde(default)]+ logs_settings: Option<LogsSettings>,+}++#[derive(Debug, Deserialize)]+struct LogsSettings {+ #[serde(default)]+ retention_days: Option<i64>,+}++/// The project's default logs retention in days, or `None` when the project cannot be read, for+/// example because the API key lacks `project:read`.+pub fn project_retention_days() -> Option<i64> {+ let client = &crate::invocation_context::context().client;+ let response = client.send_get(client.env_url("").ok()?, |req| req).ok()?;+ let team: Team = response.json().ok()?;+ Some(retention_days(team))+}++fn retention_days(team: Team) -> i64 {+ team.logs_settings+ .and_then(|settings| settings.retention_days)+ .filter(|days| *days > 0)+ .unwrap_or(DEFAULT_RETENTION_DAYS)+}++pub fn retention_cutoff(retention_days: i64, now: DateTime<Utc>) -> DateTime<Utc> {+ now - TimeDelta::days(retention_days)+}++#[derive(Debug, PartialEq)]+pub enum Expiry {+ Unknown,+ WithinRetention,+ PartlyExpired {+ retention_days: i64,+ cutoff: DateTime<Utc>,+ expired_days: i64,+ total_days: i64,+ },+}++pub fn assess(+ from: DateTime<Utc>,+ to: DateTime<Utc>,+ retention_days: Option<i64>,+ now: DateTime<Utc>,+) -> Expiry {+ let Some(retention_days) = retention_days else {+ return Expiry::Unknown;+ };+ let cutoff = retention_cutoff(retention_days, now);+ if from >= cutoff {+ return Expiry::WithinRetention;+ }+ // Dropped days are the total less the days the dry run reports as sent, so the two add up.+ let total_days = whole_days(from, to);+ Expiry::PartlyExpired {+ retention_days,+ cutoff,+ expired_days: total_days - whole_days(cutoff.min(to), to),+ total_days,+ }+}++pub struct Confirmation {+ pub summary: String,+ pub prompt: String,+}++impl Expiry {+ pub fn confirmation(&self) -> Option<Confirmation> {+ match self {+ Expiry::WithinRetention => None,+ Expiry::Unknown => Some(Confirmation {+ summary: "Could not read this project's logs retention, so this run cannot tell \+ which records PostHog keeps. Records older than the retention are \+ dropped when they arrive."+ .to_string(),+ prompt: "Import without a retention check?".to_string(),+ }),+ Expiry::PartlyExpired {+ retention_days,+ cutoff,+ expired_days,+ total_days,+ } => Some(Confirmation {+ summary: format!(+ "This project keeps logs for {retention_days} days. Records before {} are \+ dropped when they arrive: {expired_days} of the {total_days} days in this \+ range. Raise logs retention in the project settings to keep them.",+ day(*cutoff)+ ),+ prompt: format!("Skip records before {} and import the rest?", day(*cutoff)),+ }),+ }+ }++ pub fn effective_from(&self, from: DateTime<Utc>, to: DateTime<Utc>) -> DateTime<Utc> {+ match self {+ Expiry::PartlyExpired { cutoff, .. } => (*cutoff).min(to),+ Expiry::Unknown | Expiry::WithinRetention => from,+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn an_unset_or_empty_retention_falls_back_to_the_project_default() {+ for json in [+ r#"{}"#,+ r#"{"logs_settings": null}"#,+ r#"{"logs_settings": {"retention_days": null}}"#,+ ] {+ let team: Team = serde_json::from_str(json).unwrap();+ assert_eq!(retention_days(team), DEFAULT_RETENTION_DAYS, "{json}");+ }+ let team: Team =+ serde_json::from_str(r#"{"logs_settings": {"retention_days": 540}}"#).unwrap();+ assert_eq!(retention_days(team), 540);+ }++ #[test]+ fn a_range_reaching_past_retention_reports_how_much_is_dropped() {+ let now = DateTime::parse_from_rfc3339("2026-10-05T00:00:00Z")+ .unwrap()+ .with_timezone(&Utc);+ let from = now - TimeDelta::days(100);++ assert_eq!(+ assess(from, now, Some(30), now),+ Expiry::PartlyExpired {+ retention_days: 30,+ cutoff: now - TimeDelta::days(30),+ expired_days: 70,+ total_days: 100,+ }+ );+ assert_eq!(assess(from, now, Some(365), now), Expiry::WithinRetention);+ assert_eq!(assess(from, now, None, now), Expiry::Unknown);++ // The run sends from the cutoff, and from nothing at all when the whole range is past it.+ let partly = assess(from, now, Some(30), now);+ assert_eq!(partly.effective_from(from, now), now - TimeDelta::days(30));+ let whole = assess(from, from + TimeDelta::days(10), Some(30), now);+ assert_eq!(+ whole.effective_from(from, from + TimeDelta::days(10)),+ from + TimeDelta::days(10)+ );+ assert_eq!(assess(from, now, None, now).effective_from(from, now), from);+ }+}diff --git a/cli/src/experimental/logs/run.rs b/cli/src/experimental/logs/run.rsnew file mode 100644index 000000000000..b0dc66189236--- /dev/null+++ b/cli/src/experimental/logs/run.rs@@ -0,0 +1,319 @@+use std::path::Path;+use std::thread::sleep;+use std::time::{Duration, Instant};++use anyhow::{bail, Context, Result};+use reqwest::blocking::Client;++use super::checkpoint::Checkpoint;+use super::config::LokiImportConfig;+use super::emit::{batch_records, Batch};+use super::loki::{Entry, LokiClient, Page, INSTANT_LIMIT};+use super::mapping::Mapper;+use super::retention::retention_cutoff;+use super::send::{backoff, classify, Disposition};+use super::shard::shards;++/// The intake rejects a personal API token, so the import takes the project write key. That key is+/// already public-facing, which keeps a long unattended run off the user's personal credential.+pub const PROJECT_KEY_VAR: &str = "POSTHOG_PROJECT_API_KEY";++const MAX_ATTEMPTS: u32 = 8;++/// Paces sending so an import cannot saturate the intake, which has no rate limiting of its own.+struct Pacer {+ per_second: u32,+ window_start: Instant,+ sent_in_window: u32,+}++impl Pacer {+ fn new(per_second: u32) -> Self {+ Self {+ per_second,+ window_start: Instant::now(),+ sent_in_window: 0,+ }+ }++ /// Sleeps out the rest of the current second once the allowance is spent, repeating while the+ /// carried debt still exceeds one second's worth.+ fn record(&mut self, records: u32) {+ self.sent_in_window = self.sent_in_window.saturating_add(records);++ while self.sent_in_window >= self.per_second {+ let elapsed = self.window_start.elapsed();+ if elapsed < Duration::from_secs(1) {+ sleep(Duration::from_secs(1) - elapsed);+ }+ self.window_start = Instant::now();+ // Subtract rather than reset, so a batch larger than the allowance is paid for over+ // the seconds that follow instead of being forgiven.+ self.sent_in_window = self.sent_in_window.saturating_sub(self.per_second);+ }+ }+}++#[derive(Default)]+struct ShardTally {+ records: u64,+ bytes: u64,+}++pub struct Importer<'a> {+ pub config: &'a LokiImportConfig,+ pub loki: &'a LokiClient,+ pub mapper: &'a Mapper,+ pub http: &'a Client,+ pub intake_url: String,+ pub project_key: String,+ pub checkpoint_path: &'a Path,+ /// The project's default logs retention. Each shard starts at the retention cutoff when it+ /// begins before it, because intake would drop the records before the cutoff.+ pub retention_days: Option<i64>,+}++pub fn project_key_from_env() -> Result<String> {+ resolve_project_key(std::env::var(PROJECT_KEY_VAR).ok())+}++/// Split from the environment read so the message can be tested without mutating process globals.+fn resolve_project_key(raw: Option<String>) -> Result<String> {+ match raw.filter(|key| !key.is_empty()) {+ Some(key) => Ok(key),+ None => bail!(+ "set {PROJECT_KEY_VAR} to the project API key for the project you are importing into. \+ The intake rejects a personal API token."+ ),+ }+}++impl Importer<'_> {+ pub fn run(&self) -> Result<()> {+ let mut checkpoint = Checkpoint::load(self.checkpoint_path)?;+ let width = self.config.tuning.shard.seconds();+ let mut pacer = Pacer::new(self.config.tuning.max_records_per_second.get());++ let from_ns = self+ .config+ .range+ .from+ .timestamp_nanos_opt()+ .context("range.from is outside the nanosecond range")?;+ let to_ns = self+ .config+ .range+ .to+ .timestamp_nanos_opt()+ .context("range.to is outside the nanosecond range")?;+ if checkpoint.reconcile_range(from_ns, to_ns) {+ eprintln!(+ "the configured range now starts earlier than the checkpoint covers, so previous \+ progress was discarded and the whole range will be imported"+ );+ }++ for selector in &self.config.range.select {+ let windows = shards(+ self.config.range.from,+ self.config.range.to,+ width,+ checkpoint.resume_from(selector),+ );++ for window in windows {+ // Starts at the cutoff when the shard begins before it, so no record intake would+ // drop is sent. Rechecked per shard, because the cutoff moves forward during a run.+ let start = match self.retention_days {+ Some(days) => window.start.max(retention_cutoff(days, chrono::Utc::now())),+ None => window.start,+ };+ if start >= window.end {+ continue;+ }+ let mut cursor = start+ .timestamp_nanos_opt()+ .context("shard start is outside the nanosecond range")?;+ let mut tally = ShardTally::default();++ loop {+ cursor = match self.loki.query_page(selector, cursor, window.end)? {+ Page::Last(entries) => {+ self.send_entries(&entries, &mut pacer, &mut tally)?;+ break;+ }+ Page::More { entries, resume_at } => {+ // Loki answering with entries before the requested start would+ // otherwise re-fetch and re-send the same page forever.+ if resume_at <= cursor {+ bail!(+ "Loki returned entries before the requested start for {selector}; \+ refusing to re-send the same page"+ );+ }+ self.send_entries(&entries, &mut pacer, &mut tally)?;+ resume_at+ }+ Page::Crowded(at) => {+ if at < cursor {+ bail!(+ "Loki returned entries before the requested start for {selector}; \+ refusing to re-send the same page"+ );+ }+ let Some(instant) = self.loki.query_instant(selector, at)? else {+ bail!(+ "{INSTANT_LIMIT} or more entries for {selector} share the \+ timestamp {at}, and Loki cannot page within one instant. \+ Narrow the selector, with more label matchers or a line \+ filter, so fewer entries share that timestamp"+ );+ };+ self.send_entries(&instant, &mut pacer, &mut tally)?;+ at + 1+ }+ };+ }++ // Only after every batch in the window is acknowledged, so a crash re-sends this+ // shard rather than skipping it.+ let end = window+ .end+ .timestamp_nanos_opt()+ .context("shard end is outside the nanosecond range")?;+ checkpoint.complete_shard(selector, end, tally.records, tally.bytes);+ checkpoint.save(self.checkpoint_path)?;+ }+ }++ println!(+ "Imported {} records ({} bytes sent). Checkpoint: {}",+ checkpoint.records_sent,+ checkpoint.bytes_sent,+ self.checkpoint_path.display()+ );+ Ok(())+ }++ fn send_entries(+ &self,+ entries: &[Entry],+ pacer: &mut Pacer,+ tally: &mut ShardTally,+ ) -> Result<()> {+ let mapped: Vec<_> = entries.iter().map(|e| self.mapper.map(e)).collect();+ for batch in batch_records(&mapped, self.config.tuning.max_request_bytes) {+ self.send(&batch)?;+ pacer.record(batch.records as u32);+ tally.records += batch.records as u64;+ tally.bytes += batch.body.len() as u64;+ }+ Ok(())+ }++ fn send(&self, batch: &Batch) -> Result<()> {+ let mut last_transport_error = None;++ for attempt in 0..MAX_ATTEMPTS {+ let sent = self+ .http+ .post(&self.intake_url)+ .header("Content-Type", "application/json")+ .bearer_auth(&self.project_key)+ .body(batch.body.clone())+ .send();++ let disposition = match sent {+ Ok(response) => {+ let retry_after = response+ .headers()+ .get(reqwest::header::RETRY_AFTER)+ .and_then(|value| value.to_str().ok())+ .map(str::to_string);+ classify(response.status(), retry_after.as_deref(), attempt)+ }+ // A reset connection, a DNS blip or a client timeout is transient. Failing the+ // whole run on one costs a shard of duplicates when it restarts.+ Err(error) if error.is_timeout() || error.is_connect() => {+ last_transport_error = Some(error.to_string());+ Disposition::Retry(backoff(attempt))+ }+ Err(error) => return Err(error).context("failed to reach the PostHog logs intake"),+ };++ match disposition {+ Disposition::Accepted => return Ok(()),+ Disposition::Permanent(message) => bail!(message),+ Disposition::Retry(wait) => {+ // Sleeping before giving up wastes up to five minutes on a doomed run.+ if attempt + 1 == MAX_ATTEMPTS {+ break;+ }+ eprintln!(+ "retrying in {}s (attempt {}/{MAX_ATTEMPTS})",+ wait.as_secs(),+ attempt + 1+ );+ sleep(wait);+ }+ }+ }++ match last_transport_error {+ Some(error) => bail!(+ "gave up after {MAX_ATTEMPTS} attempts against the logs intake; last error: {error}"+ ),+ None => bail!("gave up after {MAX_ATTEMPTS} attempts against the logs intake"),+ }+ }+}++/// The intake route, carrying the backfill window the range needs.+pub fn intake_url(host: &str, from: chrono::DateTime<chrono::Utc>) -> String {+ let days = (chrono::Utc::now() - from).num_days().max(1) + 1;+ format!(+ "{}/i/v1/logs?backfill_days={days}",+ host.trim_end_matches('/')+ )+}++#[cfg(test)]+mod tests {+ use super::*;+ use chrono::{Duration, Utc};++ #[test]+ fn the_backfill_window_covers_the_oldest_record_in_the_range() {+ // Asking for exactly the age of the oldest record loses it to rounding, so the window is+ // one day wider than the range's age.+ let from = Utc::now() - Duration::days(540);++ let url = intake_url("https://us.i.posthog.com", from);++ assert!(url.contains("backfill_days=541"), "got {url}");+ }++ #[test]+ fn a_trailing_slash_on_the_host_does_not_double_up() {+ let url = intake_url("https://us.i.posthog.com/", Utc::now() - Duration::days(1));++ assert!(+ url.starts_with("https://us.i.posthog.com/i/v1/logs?"),+ "got {url}"+ );+ }++ #[test]+ fn a_missing_project_key_says_which_variable_to_set_and_why() {+ for (case, raw) in [("unset", None), ("set but empty", Some(String::new()))] {+ let error = resolve_project_key(raw).expect_err(case);++ let rendered = format!("{error:#}");+ assert!(rendered.contains(PROJECT_KEY_VAR), "{case}: {rendered}");+ assert!(+ rendered.contains("personal API token"),+ "{case}: {rendered}"+ );+ }+ }+}diff --git a/cli/src/experimental/logs/send.rs b/cli/src/experimental/logs/send.rsnew file mode 100644index 000000000000..a1abada7d770--- /dev/null+++ b/cli/src/experimental/logs/send.rs@@ -0,0 +1,173 @@+use std::time::Duration;++use reqwest::StatusCode;++/// What to do with one intake response.+#[derive(Debug, Clone, PartialEq)]+pub enum Disposition {+ Accepted,+ /// Wait, then send the same batch again. An import is the one client that reliably saturates+ /// the intake, so backing off is the client's job.+ Retry(Duration),+ /// Sending the same batch again cannot succeed, so the run stops and says why.+ Permanent(String),+}++const DEFAULT_BACKOFF: Duration = Duration::from_secs(5);++/// Decides from the status and `Retry-After` alone, so the whole policy is testable without a+/// server.+pub fn classify(status: StatusCode, retry_after: Option<&str>, attempt: u32) -> Disposition {+ if status.is_success() {+ return Disposition::Accepted;+ }++ match status {+ StatusCode::TOO_MANY_REQUESTS | StatusCode::SERVICE_UNAVAILABLE => {+ Disposition::Retry(parse_retry_after(retry_after).unwrap_or_else(|| backoff(attempt)))+ }+ StatusCode::REQUEST_TIMEOUT | StatusCode::BAD_GATEWAY | StatusCode::GATEWAY_TIMEOUT => {+ Disposition::Retry(backoff(attempt))+ }+ StatusCode::PAYLOAD_TOO_LARGE => Disposition::Permanent(+ "the intake rejected the body as too large. Lower tuning.max_request_bytes to below \+ the deployment's MAX_REQUEST_BODY_SIZE_BYTES."+ .to_string(),+ ),+ StatusCode::UNAUTHORIZED => Disposition::Permanent(+ "the intake rejected the project API key. Check POSTHOG_PROJECT_API_KEY; a personal API \+ token is not accepted."+ .to_string(),+ ),+ StatusCode::BAD_REQUEST => Disposition::Permanent(+ "the intake rejected the request. If the range reaches past the deployment's \+ MAX_BACKFILL_DAYS, backdated logs are not enabled for it."+ .to_string(),+ ),+ other if other.is_server_error() => Disposition::Retry(backoff(attempt)),+ other => Disposition::Permanent(format!("the intake answered {other}")),+ }+}++/// Doubles per attempt and stops at a minute, so a long outage does not turn into a tight loop or+/// an unbounded sleep.+pub fn backoff(attempt: u32) -> Duration {+ let seconds = DEFAULT_BACKOFF+ .as_secs()+ .saturating_mul(1u64 << attempt.min(4));+ Duration::from_secs(seconds.min(60))+}++/// RFC 7231 allows either a delay in seconds or an HTTP date. Only the delay form is honored,+/// because a date form from a skewed clock can produce an enormous sleep.+fn parse_retry_after(header: Option<&str>) -> Option<Duration> {+ let seconds: u64 = header?.trim().parse().ok()?;+ Some(Duration::from_secs(seconds.min(300)))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn a_rate_limit_honors_retry_after_over_the_backoff() {+ let waited = classify(StatusCode::TOO_MANY_REQUESTS, Some("30"), 0);++ assert_eq!(waited, Disposition::Retry(Duration::from_secs(30)));+ }++ #[test]+ fn transient_statuses_retry_and_terminal_ones_stop() {+ // (case, status, expect a retry)+ let cases = [+ ("rate limited", StatusCode::TOO_MANY_REQUESTS, true),+ (+ "the intake is restarting",+ StatusCode::SERVICE_UNAVAILABLE,+ true,+ ),+ ("a gateway timeout", StatusCode::GATEWAY_TIMEOUT, true),+ (+ "an unnamed server error",+ StatusCode::INTERNAL_SERVER_ERROR,+ true,+ ),+ (+ "a body over the limit",+ StatusCode::PAYLOAD_TOO_LARGE,+ false,+ ),+ ("a rejected token", StatusCode::UNAUTHORIZED, false),+ ("backfill not enabled", StatusCode::BAD_REQUEST, false),+ ("a forbidden project", StatusCode::FORBIDDEN, false),+ ];++ for (case, status, expect_retry) in cases {+ let disposition = classify(status, None, 0);++ assert_eq!(+ matches!(disposition, Disposition::Retry(_)),+ expect_retry,+ "{case}: got {disposition:?}"+ );+ }+ }++ #[test]+ fn a_permanent_failure_names_the_setting_that_caused_it() {+ // An import runs unattended for hours, so the message is the only diagnosis its operator gets.+ let cases = [+ (StatusCode::PAYLOAD_TOO_LARGE, "max_request_bytes"),+ (StatusCode::UNAUTHORIZED, "POSTHOG_PROJECT_API_KEY"),+ (StatusCode::BAD_REQUEST, "MAX_BACKFILL_DAYS"),+ ];++ for (status, expected) in cases {+ match classify(status, None, 0) {+ Disposition::Permanent(message) => assert!(+ message.contains(expected),+ "expected {status} to mention {expected}, got: {message}"+ ),+ other => panic!("expected {status} to be permanent, got {other:?}"),+ }+ }+ }++ #[test]+ fn backoff_grows_then_stops_growing() {+ // Without the ceiling a long outage sleeps for hours; without the growth it hammers.+ let waits: Vec<u64> = (0..8)+ .map(+ |attempt| match classify(StatusCode::INTERNAL_SERVER_ERROR, None, attempt) {+ Disposition::Retry(wait) => wait.as_secs(),+ other => panic!("expected a retry, got {other:?}"),+ },+ )+ .collect();++ assert_eq!(waits, [5, 10, 20, 40, 60, 60, 60, 60]);+ }++ #[test]+ fn an_unusable_retry_after_falls_back_to_the_backoff() {+ // A date-form header from a skewed clock must not become an enormous sleep.+ let cases = ["Wed, 21 Oct 2026 07:28:00 GMT", "", "soon", "-5"];++ for header in cases {+ let disposition = classify(StatusCode::TOO_MANY_REQUESTS, Some(header), 0);++ assert_eq!(+ disposition,+ Disposition::Retry(DEFAULT_BACKOFF),+ "header {header:?} should fall back"+ );+ }+ }++ #[test]+ fn a_huge_retry_after_is_capped() {+ let disposition = classify(StatusCode::TOO_MANY_REQUESTS, Some("86400"), 0);++ assert_eq!(disposition, Disposition::Retry(Duration::from_secs(300)));+ }+}diff --git a/cli/src/experimental/logs/shard.rs b/cli/src/experimental/logs/shard.rsnew file mode 100644index 000000000000..09a71765b429--- /dev/null+++ b/cli/src/experimental/logs/shard.rs@@ -0,0 +1,103 @@+use chrono::{DateTime, Duration, Utc};++/// A half-open window `[start, end)` that one `query_range` call covers.+#[derive(Debug, Clone, Copy, PartialEq)]+pub struct Shard {+ pub start: DateTime<Utc>,+ pub end: DateTime<Utc>,+}++/// Splits a range into windows, resuming past what a checkpoint already completed.+///+/// Windows are half-open so the boundary record belongs to exactly one shard. Closing both ends+/// would re-send one record per boundary, which across 13,000 shards is 13,000 duplicates.+pub fn shards(+ from: DateTime<Utc>,+ to: DateTime<Utc>,+ width_seconds: u64,+ resume_from_ns: Option<i64>,+) -> Vec<Shard> {+ let width = Duration::seconds(width_seconds.max(1) as i64);++ let mut start = match resume_from_ns.map(DateTime::from_timestamp_nanos) {+ // A checkpoint past the configured range means the range shrank since the last run.+ Some(resume) if resume >= to => return Vec::new(),+ Some(resume) if resume > from => resume,+ _ => from,+ };++ let mut windows = Vec::new();+ while start < to {+ let end = (start + width).min(to);+ windows.push(Shard { start, end });+ start = end;+ }+ windows+}++#[cfg(test)]+mod tests {+ use super::*;++ fn at(day: u32, hour: u32) -> DateTime<Utc> {+ DateTime::parse_from_rfc3339(&format!("2025-03-{day:02}T{hour:02}:00:00Z"))+ .expect("valid")+ .with_timezone(&Utc)+ }++ #[test]+ fn windows_are_half_open_and_cover_the_range_exactly_once() {+ let windows = shards(at(1, 0), at(1, 6), 3600 * 2, None);++ assert_eq!(windows.len(), 3);+ assert_eq!(windows[0].end, windows[1].start, "no gap and no overlap");+ assert_eq!(windows[2].end, at(1, 6));+ }++ #[test]+ fn a_partial_final_window_still_runs() {+ // 5 hours at a 2h shard is 2 full windows and a 1h tail. Dropping the tail silently+ // skips the end of the range.+ let windows = shards(at(1, 0), at(1, 5), 3600 * 2, None);++ assert_eq!(windows.len(), 3);+ assert_eq!(windows[2].start, at(1, 4));+ assert_eq!(windows[2].end, at(1, 5));+ }++ #[test]+ fn a_checkpoint_resumes_without_replaying_completed_windows() {+ let resume = at(1, 4).timestamp_nanos_opt().expect("in range");++ let windows = shards(at(1, 0), at(1, 8), 3600 * 2, Some(resume));++ assert_eq!(windows.len(), 2);+ assert_eq!(+ windows[0].start,+ at(1, 4),+ "must not replay the first four hours"+ );+ }++ #[test]+ fn a_checkpoint_past_the_range_produces_no_work() {+ // The range shrank since the last run. Returning windows would re-import data the+ // checkpoint says is already done.+ let resume = at(2, 0).timestamp_nanos_opt().expect("in range");++ assert!(shards(at(1, 0), at(1, 8), 3600, Some(resume)).is_empty());+ }++ #[test]+ fn a_checkpoint_before_the_range_does_not_widen_it() {+ let resume = at(1, 0).timestamp_nanos_opt().expect("in range");++ let windows = shards(at(1, 4), at(1, 8), 3600 * 2, Some(resume));++ assert_eq!(+ windows[0].start,+ at(1, 4),+ "the config bounds the run, not the checkpoint"+ );+ }+}