Skip to main content

timelake_format/
contract.rs

1//! The Timelake table contract (SPEC §7.1): which column is time, which columns identify a series,
2//! and the layout/maintenance policy derived from them. Stored as `timelake.*` Iceberg table
3//! properties (see [`property`]), so the contract travels with the table and other
4//! engines simply ignore it.
5
6use std::collections::HashMap;
7use std::fmt;
8use std::str::FromStr;
9use std::time::Duration;
10
11use chrono::Datelike;
12
13use crate::{FORMAT_VERSION, FormatError, FormatVersion, Result, property};
14
15const HOUR_MICROS: i64 = 3_600_000_000;
16const DAY_MICROS: i64 = 24 * HOUR_MICROS;
17const DAY_SECS: u64 = 86_400;
18
19/// Time partition granularity: how much time one partition covers.
20///
21/// Parses from `hour`, `day` or `month` (and spellings such as `1h`, `1 day`).
22#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
23pub enum Chunk {
24    /// One partition per hour.
25    Hour,
26    /// One partition per day (the default).
27    Day,
28    /// One partition per calendar month.
29    Month,
30}
31
32impl Chunk {
33    /// The canonical name, as stored in the table properties.
34    pub fn as_str(self) -> &'static str {
35        match self {
36            Self::Hour => "hour",
37            Self::Day => "day",
38            Self::Month => "month",
39        }
40    }
41
42    /// Iceberg transform value (hours/days/months since the epoch) of a timestamp in microseconds.
43    pub fn value(self, micros: i64) -> Result<i32> {
44        let out_of_range = || FormatError::new(format!("timestamp {micros}µs is out of range for {self} partitions"));
45        let t = chrono::DateTime::from_timestamp_micros(micros).ok_or_else(out_of_range)?;
46        let v = match self {
47            Self::Hour => micros.div_euclid(HOUR_MICROS),
48            Self::Day => micros.div_euclid(DAY_MICROS),
49            Self::Month => (i64::from(t.year()) - 1970) * 12 + i64::from(t.month0()),
50        };
51        i32::try_from(v).map_err(|_| out_of_range())
52    }
53
54    /// Start of a partition, in microseconds since the epoch.
55    pub fn start_micros(self, value: i32) -> Result<i64> {
56        let start = match self {
57            Self::Hour => Some(i64::from(value) * HOUR_MICROS),
58            Self::Day => i64::from(value).checked_mul(DAY_MICROS),
59            Self::Month => {
60                let (year, month0) = (1970 + value.div_euclid(12), value.rem_euclid(12).unsigned_abs());
61                chrono::NaiveDate::from_ymd_opt(year, month0 + 1, 1)
62                    .and_then(|d| d.and_hms_opt(0, 0, 0))
63                    .map(|t| t.and_utc().timestamp_micros())
64            }
65        };
66        start.ok_or_else(|| self.out_of_range(value))
67    }
68
69    /// End (exclusive) of a partition, in microseconds since the epoch.
70    pub fn end_micros(self, value: i32) -> Result<i64> {
71        self.start_micros(value.checked_add(1).ok_or_else(|| self.out_of_range(value))?)
72    }
73
74    /// Human-readable partition value, used in data file paths (`time_day=2026-01-01`). Values
75    /// outside the supported time range fall back to the plain number.
76    pub fn label(self, value: i32) -> String {
77        let Some(t) = self.start_micros(value).ok().and_then(chrono::DateTime::from_timestamp_micros) else {
78            return value.to_string();
79        };
80        let format = match self {
81            Self::Hour => "%Y-%m-%d-%H",
82            Self::Day => "%Y-%m-%d",
83            Self::Month => "%Y-%m",
84        };
85        t.format(format).to_string()
86    }
87
88    fn out_of_range(self, value: i32) -> FormatError {
89        FormatError::new(format!("{self} partition {value} is out of range"))
90    }
91}
92
93impl FromStr for Chunk {
94    type Err = FormatError;
95
96    fn from_str(s: &str) -> Result<Self> {
97        match s.trim().to_ascii_lowercase().as_str() {
98            "hour" | "1h" | "1 hour" => Ok(Self::Hour),
99            "day" | "1d" | "1 day" | "24h" => Ok(Self::Day),
100            "month" | "1 month" => Ok(Self::Month),
101            other => Err(FormatError::new(format!("chunk interval must be hour, day or month, got {other:?}"))),
102        }
103    }
104}
105
106impl fmt::Display for Chunk {
107    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
108        f.write_str(self.as_str())
109    }
110}
111
112/// Options for creating a table. Only `time_column` is required for a time-series table; leave it
113/// unset for a plain (dimension) table such as device metadata.
114#[derive(Clone, Debug, Default)]
115pub struct TableOptions {
116    /// The timestamp column; makes the table a time-series table.
117    pub time_column: Option<String>,
118    /// Columns that identify a series (e.g. `device_id`); requires a time column.
119    pub series_key: Vec<String>,
120    /// Time partition size (default: [`Chunk::Day`]).
121    pub chunk: Option<Chunk>,
122    /// Remove duplicate `(series_key, time)` rows during compaction (default: on with a series key).
123    pub dedup: Option<bool>,
124    /// Drop partitions entirely older than this.
125    pub retention: Option<Duration>,
126    /// Add an insertion-time column (`_ingest_ts`) to a time-series table (default: on).
127    pub ingest_time: Option<bool>,
128    /// Extra Iceberg/Timelake table properties.
129    pub properties: HashMap<String, String>,
130}
131
132/// The parsed contract of an existing table.
133#[derive(Clone, Debug)]
134pub struct Contract {
135    /// The timestamp column, if this is a time-series table.
136    pub time_column: Option<String>,
137    /// Columns that identify a series.
138    pub series_key: Vec<String>,
139    /// Time partition size.
140    pub chunk: Option<Chunk>,
141    /// Remove rows with the same `(series_key, time)` during compaction; the latest write wins.
142    pub dedup: bool,
143    /// The column holding each row's insertion time, if the table has one.
144    pub ingest_time_column: Option<String>,
145    /// Partitions entirely older than this are dropped by maintenance.
146    pub retention: Option<Duration>,
147    /// Compaction writes files of about this size.
148    pub target_file_size: u64,
149    /// Rows per Parquet row group.
150    pub row_group_rows: usize,
151    /// Appends run inline maintenance when thresholds are crossed.
152    pub auto_maintain: bool,
153    /// Snapshots younger than this are kept.
154    pub snapshot_retention: Duration,
155    /// The newest snapshots kept regardless of age.
156    pub min_snapshots: usize,
157    /// Snapshots beyond the newest `max_snapshots` are expired even if younger than the retention.
158    pub max_snapshots: usize,
159    /// Inline auto-maintenance merges a size tier of a partition once it has this many files.
160    pub compact_min_files: usize,
161    /// Inline auto-maintenance rewrites a partition whole once the table holds data newer than the
162    /// partition's end by this much (`None`: never).
163    pub compact_cold_after: Option<Duration>,
164    /// The Timelake reader removes copies of a `(series…, time)` when reading.
165    pub read_dedup: bool,
166    /// How the Timelake reader removes copies: `merge` or `keys-first`.
167    pub read_dedup_strategy: String,
168    /// Format of the head object, or `none` to not write one.
169    pub head_format: String,
170    /// Bytes the head may spend on optional sections (the last-value index).
171    pub head_inline_bytes: u64,
172    /// The table format version (see [`crate::FORMAT_VERSION`]).
173    pub format_version: FormatVersion,
174    /// No snapshot expires before this time (milliseconds since the epoch).
175    pub keep_snapshots_until: Option<i64>,
176    /// The table's rollups (table names).
177    pub rollups: Vec<String>,
178    /// The Timelake reader may answer queries on this table from its rollups.
179    pub rollup_routing: bool,
180    /// For a rollup: inline maintenance of its raw table refreshes it once its last refresh is this
181    /// old (`None`: never).
182    pub rollup_refresh_interval: Option<Duration>,
183}
184
185impl Contract {
186    /// Defaults for properties a table doesn't set.
187    const DEFAULT_TARGET_FILE_SIZE: u64 = 256 << 20;
188    const DEFAULT_ROW_GROUP_ROWS: usize = 1 << 20;
189    const DEFAULT_SNAPSHOT_RETENTION: Duration = Duration::from_secs(3600);
190    const DEFAULT_MIN_SNAPSHOTS: usize = 5;
191    const DEFAULT_MAX_SNAPSHOTS: usize = 100;
192    const DEFAULT_COMPACT_MIN_FILES: usize = 8;
193    const DEFAULT_COMPACT_COLD_AFTER: Duration = Duration::from_secs(3600);
194    const DEFAULT_HEAD_FORMAT: &str = "arrow";
195    const DEFAULT_HEAD_INLINE_BYTES: u64 = 1 << 20;
196    const DEFAULT_ROLLUP_REFRESH_INTERVAL: Duration = Duration::from_secs(60);
197
198    /// Reads the contract from Iceberg table properties, with defaults for what isn't set.
199    pub fn from_properties(properties: &HashMap<String, String>) -> Result<Self> {
200        let p = Properties(properties);
201        Ok(Self {
202            time_column: p.get(property::TIME_COLUMN).map(str::to_string),
203            series_key: p.list(property::SERIES_KEY),
204            chunk: p.get(property::CHUNK).map(str::parse).transpose()?,
205            dedup: p.flag(property::DEDUP, false)?,
206            ingest_time_column: p.get(property::INGEST_TIME_COLUMN).map(str::to_string),
207            retention: p.duration(property::RETENTION)?,
208            target_file_size: p.number(property::TARGET_FILE_SIZE, Self::DEFAULT_TARGET_FILE_SIZE)?,
209            row_group_rows: p.number(property::ROW_GROUP_ROWS, Self::DEFAULT_ROW_GROUP_ROWS)?,
210            auto_maintain: p.flag(property::AUTO_MAINTAIN, true)?,
211            snapshot_retention: p.duration(property::SNAPSHOT_RETENTION)?.unwrap_or(Self::DEFAULT_SNAPSHOT_RETENTION),
212            min_snapshots: p.number(property::MIN_SNAPSHOTS, Self::DEFAULT_MIN_SNAPSHOTS)?,
213            max_snapshots: p.number(property::MAX_SNAPSHOTS, Self::DEFAULT_MAX_SNAPSHOTS)?,
214            compact_min_files: p.number(property::COMPACT_MIN_FILES, Self::DEFAULT_COMPACT_MIN_FILES)?,
215            compact_cold_after: match p.get(property::COMPACT_COLD_AFTER) {
216                Some(s) if s.eq_ignore_ascii_case("off") => None,
217                Some(s) => Some(parse_duration(s)?),
218                None => Some(Self::DEFAULT_COMPACT_COLD_AFTER),
219            },
220            read_dedup: p.flag(property::READ_DEDUP, p.flag(property::DEDUP, false)?)?,
221            read_dedup_strategy: p.get(property::READ_DEDUP_STRATEGY).unwrap_or("merge").to_ascii_lowercase(),
222            head_format: p.get(property::HEAD_FORMAT).unwrap_or(Self::DEFAULT_HEAD_FORMAT).to_ascii_lowercase(),
223            head_inline_bytes: p.number(property::HEAD_INLINE_BYTES, Self::DEFAULT_HEAD_INLINE_BYTES)?,
224            format_version: p.get(property::FORMAT_VERSION).map_or(Ok(FormatVersion::UNVERSIONED), str::parse)?,
225            keep_snapshots_until: p
226                .get(property::KEEP_SNAPSHOTS_UNTIL)
227                .map(|_| p.number(property::KEEP_SNAPSHOTS_UNTIL, 0))
228                .transpose()?,
229            rollups: p.list(property::ROLLUPS),
230            rollup_routing: p.flag(property::ROLLUP_ROUTING, true)?,
231            rollup_refresh_interval: match p.get(property::ROLLUP_REFRESH_INTERVAL) {
232                Some(s) if s.eq_ignore_ascii_case("off") => None,
233                Some(s) => Some(parse_duration(s)?),
234                None => Some(Self::DEFAULT_ROLLUP_REFRESH_INTERVAL),
235            },
236        })
237    }
238
239    /// Errors when this Timelake can't read the table correctly: its format is newer than
240    /// [`FORMAT_VERSION`] in a way that breaks older readers.
241    pub fn check_readable(&self) -> Result<()> {
242        if self.format_version.readable_by(FORMAT_VERSION) {
243            return Ok(());
244        }
245        Err(FormatError::new(format!(
246            "table format {} is newer than this Timelake reads ({FORMAT_VERSION}): upgrade Timelake",
247            self.format_version
248        )))
249    }
250
251    /// Errors when this Timelake must not write to the table: it wouldn't keep what the table's
252    /// newer format relies on.
253    pub fn check_writable(&self) -> Result<()> {
254        if self.format_version.writable_by(FORMAT_VERSION) {
255            return Ok(());
256        }
257        Err(FormatError::new(format!(
258            "table format {} is newer than this Timelake writes ({FORMAT_VERSION}): upgrade Timelake",
259            self.format_version
260        )))
261    }
262
263    /// Whether the table has a time column.
264    pub fn is_time_series(&self) -> bool {
265        self.time_column.is_some()
266    }
267
268    /// Sort key: series key columns, then time.
269    pub fn sort_columns(&self) -> Vec<String> {
270        let mut v = self.series_key.clone();
271        v.extend(self.time_column.clone());
272        v
273    }
274
275    /// The sort key, then the insertion time: in this order (ties kept in commit order) the last
276    /// row of each `(series…, time)` is its latest write.
277    pub fn write_order(&self) -> Vec<String> {
278        let mut v = self.sort_columns();
279        v.extend(self.ingest_time_column.clone());
280        v
281    }
282}
283
284/// Typed access to table properties; blank values count as unset.
285struct Properties<'a>(&'a HashMap<String, String>);
286
287impl Properties<'_> {
288    fn get(&self, key: &str) -> Option<&str> {
289        self.0.get(key).map(|s| s.trim()).filter(|s| !s.is_empty())
290    }
291
292    fn number<T: FromStr>(&self, key: &str, default: T) -> Result<T> {
293        self.get(key).map_or(Ok(default), |s| {
294            s.parse().map_err(|_| FormatError::new(format!("{key} must be a non-negative integer, got {s:?}")))
295        })
296    }
297
298    fn flag(&self, key: &str, default: bool) -> Result<bool> {
299        self.get(key).map_or(Ok(default), |s| {
300            s.to_ascii_lowercase()
301                .parse()
302                .map_err(|_| FormatError::new(format!("{key} must be true or false, got {s:?}")))
303        })
304    }
305
306    fn duration(&self, key: &str) -> Result<Option<Duration>> {
307        self.get(key).map(parse_duration).transpose()
308    }
309
310    /// A comma-separated list (empty items dropped).
311    fn list(&self, key: &str) -> Vec<String> {
312        self.get(key)
313            .map(|s| s.split(',').map(str::trim).filter(|c| !c.is_empty()).map(str::to_string).collect())
314            .unwrap_or_default()
315    }
316}
317
318/// Parses durations like `90d`, `12h`, `30m`, `45s`, `2w`, `1y`, or spelled out (`1 day`, `3 hours`).
319pub fn parse_duration(s: &str) -> Result<Duration> {
320    let s = s.trim();
321    let split = s.find(|c: char| !c.is_ascii_digit()).unwrap_or(s.len());
322    let (n, unit) = s.split_at(split);
323    let n: u64 = n.parse().map_err(|_| FormatError::new(format!("bad duration {s:?}")))?;
324    let unit_secs = match unit.trim().to_ascii_lowercase().as_str() {
325        "s" | "sec" | "secs" | "second" | "seconds" => 1,
326        "m" | "min" | "mins" | "minute" | "minutes" => 60,
327        "h" | "hr" | "hrs" | "hour" | "hours" => 3600,
328        "d" | "day" | "days" => DAY_SECS,
329        "w" | "week" | "weeks" => 7 * DAY_SECS,
330        "y" | "year" | "years" => 365 * DAY_SECS,
331        _ => return Err(FormatError::new(format!("bad duration unit in {s:?} (use s, m, h, d, w, y)"))),
332    };
333    let secs = n.checked_mul(unit_secs).ok_or_else(|| FormatError::new(format!("duration {s:?} is too long")))?;
334    Ok(Duration::from_secs(secs))
335}
336
337/// Formats whole seconds of a duration in the largest exact unit (`90d`, `36h`, `45s`), the
338/// inverse of [`parse_duration`].
339pub fn format_duration(d: Duration) -> String {
340    let secs = d.as_secs();
341    match [(DAY_SECS, 'd'), (3600, 'h'), (60, 'm')]
342        .into_iter()
343        .find(|(unit, _)| secs != 0 && secs.is_multiple_of(*unit))
344    {
345        Some((unit, suffix)) => format!("{}{suffix}", secs / unit),
346        None => format!("{secs}s"),
347    }
348}
349
350#[cfg(test)]
351mod tests {
352    use super::*;
353    use crate::property::*;
354
355    const T: i64 = 1_767_225_600_000_000; // 2026-01-01T00:00:00Z
356
357    #[test]
358    fn chunk_values_round_trip() {
359        for c in [Chunk::Hour, Chunk::Day, Chunk::Month] {
360            let v = c.value(T + 1).unwrap();
361            assert_eq!(c.start_micros(v).unwrap(), T, "{c:?}");
362            assert!(c.end_micros(v).unwrap() > T);
363        }
364        assert_eq!(Chunk::Day.label(Chunk::Day.value(T).unwrap()), "2026-01-01");
365        assert_eq!(Chunk::Hour.label(Chunk::Hour.value(T).unwrap()), "2026-01-01-00");
366        assert_eq!(Chunk::Month.label(Chunk::Month.value(T).unwrap()), "2026-01");
367        assert_eq!(Chunk::Month.value(T).unwrap(), (2026 - 1970) * 12);
368        // Before the epoch, values are negative and still round down.
369        assert_eq!(Chunk::Day.value(-1).unwrap(), -1);
370        assert_eq!(Chunk::Month.value(-1).unwrap(), -1);
371        assert_eq!(Chunk::Month.start_micros(-1).unwrap(), -31 * DAY_MICROS);
372    }
373
374    #[test]
375    fn out_of_range_times_are_errors() {
376        for c in [Chunk::Hour, Chunk::Day, Chunk::Month] {
377            assert!(c.value(i64::MAX).is_err(), "{c:?}");
378            assert!(c.value(i64::MIN).is_err(), "{c:?}");
379        }
380        assert!(Chunk::Day.start_micros(i32::MAX).is_err());
381        assert!(Chunk::Month.start_micros(i32::MAX).is_err());
382        assert!(Chunk::Hour.end_micros(i32::MAX).is_err());
383        assert_eq!(Chunk::Month.label(i32::MAX), i32::MAX.to_string());
384    }
385
386    #[test]
387    fn chunk_parses_and_displays() {
388        for (s, c) in [("hour", Chunk::Hour), (" 1 Day ", Chunk::Day), ("24h", Chunk::Day), ("month", Chunk::Month)] {
389            assert_eq!(s.parse::<Chunk>().unwrap(), c, "{s}");
390        }
391        assert!("week".parse::<Chunk>().is_err());
392        for c in [Chunk::Hour, Chunk::Day, Chunk::Month] {
393            assert_eq!(c.to_string().parse::<Chunk>().unwrap(), c);
394        }
395    }
396
397    #[test]
398    fn durations() {
399        assert_eq!(parse_duration("90d").unwrap().as_secs(), 90 * 86_400);
400        assert_eq!(parse_duration("1h").unwrap().as_secs(), 3600);
401        assert_eq!(parse_duration(" 0s ").unwrap(), Duration::ZERO);
402        assert!(parse_duration("1 parsec").is_err());
403        assert!(parse_duration("d").is_err());
404        assert!(parse_duration("-1d").is_err());
405    }
406
407    #[test]
408    fn durations_accept_singular_and_plural_units() {
409        assert_eq!(parse_duration("1 day").unwrap().as_secs(), 86_400);
410        assert_eq!(parse_duration("1 hour").unwrap().as_secs(), 3600);
411        assert_eq!(parse_duration("1 week").unwrap().as_secs(), 7 * 86_400);
412        assert_eq!(parse_duration("2 Weeks").unwrap().as_secs(), 14 * 86_400);
413        assert_eq!(parse_duration("1 minute").unwrap().as_secs(), 60);
414        assert_eq!(parse_duration("1 year").unwrap().as_secs(), 365 * 86_400);
415    }
416
417    #[test]
418    fn duration_overflow_is_an_error() {
419        assert!(parse_duration("99999999999999999y").is_err());
420        assert!(parse_duration("99999999999999999999s").is_err());
421    }
422
423    #[test]
424    fn durations_format_in_the_largest_exact_unit() {
425        for (secs, s) in [(90 * 86_400, "90d"), (36 * 3600, "36h"), (90, "90s"), (120, "2m"), (0, "0s")] {
426            assert_eq!(format_duration(Duration::from_secs(secs)), s);
427            assert_eq!(parse_duration(s).unwrap().as_secs(), secs);
428        }
429    }
430
431    fn props(kv: &[(&str, &str)]) -> HashMap<String, String> {
432        kv.iter().map(|(k, v)| ((*k).to_string(), (*v).to_string())).collect()
433    }
434
435    #[test]
436    fn contract_defaults() {
437        let c = Contract::from_properties(&HashMap::new()).unwrap();
438        assert!(!c.is_time_series() && !c.dedup && c.auto_maintain);
439        assert_eq!(c.retention, None);
440        assert_eq!(c.snapshot_retention, Duration::from_secs(3600));
441        assert_eq!((c.min_snapshots, c.max_snapshots, c.compact_min_files), (5, 100, 8));
442        assert_eq!(
443            (c.head_format.as_str(), c.head_inline_bytes, c.format_version),
444            ("arrow", 1 << 20, FormatVersion::UNVERSIONED)
445        );
446        assert_eq!((c.compact_cold_after, c.read_dedup), (Some(Duration::from_hours(1)), false));
447        let dedup = Contract::from_properties(&props(&[(property::DEDUP, "true")])).unwrap();
448        assert!(dedup.read_dedup, "read dedup follows dedup");
449        let off =
450            props(&[(property::DEDUP, "true"), (property::READ_DEDUP, "false"), (property::COMPACT_COLD_AFTER, "off")]);
451        let off = Contract::from_properties(&off).unwrap();
452        assert_eq!((off.compact_cold_after, off.read_dedup), (None, false));
453        let cold = Contract::from_properties(&props(&[(property::COMPACT_COLD_AFTER, "6h")])).unwrap();
454        assert_eq!(cold.compact_cold_after, Some(Duration::from_hours(6)));
455        assert_eq!(c.sort_columns(), [] as [String; 0]);
456    }
457
458    #[test]
459    fn contract_parses_properties() {
460        let c = Contract::from_properties(&props(&[
461            (TIME_COLUMN, "time"),
462            (SERIES_KEY, "site, device,"),
463            (CHUNK, "hour"),
464            (DEDUP, "True"),
465            (AUTO_MAINTAIN, "FALSE"),
466            (RETENTION, "1 day"),
467            (MIN_SNAPSHOTS, "3"),
468            (TARGET_FILE_SIZE, " 1024 "),
469            (HEAD_FORMAT, "JSON"),
470            (HEAD_INLINE_BYTES, "0"),
471        ]))
472        .unwrap();
473        assert_eq!((c.head_format.as_str(), c.head_inline_bytes), ("json", 0));
474        assert_eq!(c.sort_columns(), ["site", "device", "time"]);
475        assert_eq!(c.chunk, Some(Chunk::Hour));
476        assert!(c.dedup && !c.auto_maintain);
477        assert_eq!(c.retention, Some(Duration::from_hours(24)));
478        assert_eq!((c.min_snapshots, c.target_file_size), (3, 1024));
479    }
480
481    #[test]
482    fn contract_rejects_bad_values() {
483        for kv in [(DEDUP, "yes"), (AUTO_MAINTAIN, "0"), (CHUNK, "week"), (RETENTION, "forever"), (MAX_SNAPSHOTS, "-1")]
484        {
485            assert!(Contract::from_properties(&props(&[kv])).is_err(), "{kv:?}");
486        }
487    }
488}