Skip to main content

micromegas_analytics/lakehouse/
write_partition.rs

1use crate::{
2    lakehouse::async_parquet_writer::AsyncParquetWriter, response_writer::Logger, time::TimeRange,
3};
4use anyhow::{Context, Result};
5use chrono::{DateTime, TimeDelta, Utc};
6use datafusion::{
7    arrow::{array::RecordBatch, datatypes::Schema},
8    parquet::{
9        arrow::AsyncArrowWriter,
10        basic::Compression,
11        file::properties::{WriterProperties, WriterVersion},
12    },
13};
14use micromegas_ingestion::data_lake_connection::DataLakeConnection;
15use micromegas_tracing::prelude::*;
16use object_store::ObjectStoreExt;
17use object_store::buffered::BufWriter;
18use sqlx::Row;
19use std::collections::hash_map::DefaultHasher;
20use std::hash::{Hash, Hasher};
21use std::sync::{Arc, atomic::AtomicI64};
22use tokio::sync::mpsc::Receiver;
23
24use super::{partition::Partition, partition_source_data, view::ViewMetadata};
25
26/// Adds a file to the temporary_files table for cleanup.
27///
28/// Files added to temporary_files will be automatically deleted by the cleanup process
29/// after the expiration time. The default expiration is 1 hour from now.
30pub async fn add_file_for_cleanup<'c, E>(executor: E, file_path: &str, file_size: i64) -> Result<()>
31where
32    E: sqlx::PgExecutor<'c>,
33{
34    let expiration = Utc::now()
35        + TimeDelta::try_hours(1)
36            .with_context(|| "calculating expiration time for temporary file")?;
37
38    instrument_named!(
39        sqlx::query("INSERT INTO temporary_files VALUES ($1, $2, $3)")
40            .bind(file_path)
41            .bind(file_size)
42            .bind(expiration)
43            .execute(executor),
44        "sql_insert_temporary_file"
45    )
46    .await
47    .with_context(|| format!("adding file {file_path} to temporary files for cleanup"))?;
48
49    Ok(())
50}
51
52/// A set of rows for a partition, along with their time range.
53pub struct PartitionRowSet {
54    pub rows_time_range: TimeRange,
55    pub rows: RecordBatch,
56    /// The true maximum value of the view's declared `Concatenated` leading sort column across
57    /// this row set (`begin`, for `thread_spans`). `None` for every sender except
58    /// `thread_spans_view.rs`, the only view that declares that ordering today; see
59    /// `Partition::max_sort_key_time`'s docs for the field it eventually feeds.
60    pub max_sort_key_time: Option<DateTime<Utc>>,
61}
62
63impl PartitionRowSet {
64    /// Takes `max_sort_key_time` as a required third argument (rather than defaulting it to
65    /// `None`) so every future caller has to make an explicit choice. `None` happens to be
66    /// correct for every caller today -- none of them declares a `Concatenated` event-time
67    /// ordering -- but a defaulted `new()` would hand that `None` out silently, and a future view
68    /// that does declare the ordering could be wired through `::new` and get a wrong bound with
69    /// no signal at all. The failure mode of a silent default here is a scan check that trusts a
70    /// bound nobody computed.
71    pub fn new(
72        rows_time_range: TimeRange,
73        rows: RecordBatch,
74        max_sort_key_time: Option<DateTime<Utc>>,
75    ) -> Self {
76        Self {
77            rows_time_range,
78            rows,
79            max_sort_key_time,
80        }
81    }
82}
83
84#[span_fn]
85async fn retire_expired_partitions_batch(
86    lake: &DataLakeConnection,
87    expiration: DateTime<Utc>,
88) -> Result<bool> {
89    let batch_size: i32 = 1000;
90    let mut transaction = lake.db_pool.begin().await?;
91    let rows = instrument_named!(
92        sqlx::query(
93            "DELETE FROM lakehouse_partitions
94         WHERE (view_set_name, view_instance_id, begin_insert_time, end_insert_time) IN (
95             SELECT view_set_name, view_instance_id, begin_insert_time, end_insert_time
96             FROM lakehouse_partitions
97             WHERE end_insert_time < $1
98             LIMIT $2
99         )
100         RETURNING file_path, file_size;",
101        )
102        .bind(expiration)
103        .bind(batch_size)
104        .fetch_all(&mut *transaction),
105        "sql_delete_expired_partitions_batch"
106    )
107    .await
108    .with_context(|| "deleting expired partitions batch")?;
109
110    if rows.is_empty() {
111        return Ok(false);
112    }
113    let count = rows.len();
114    for row in &rows {
115        let file_path: Option<String> = row.try_get("file_path")?;
116        let file_size: i64 = row.try_get("file_size")?;
117        if let Some(path) = file_path {
118            debug!("retiring expired partition file {path} ({file_size} bytes)");
119            add_file_for_cleanup(&mut *transaction, &path, file_size).await?;
120        }
121    }
122    transaction.commit().await.with_context(|| "commit")?;
123    info!("retired {count} expired partitions");
124    Ok(count == batch_size as usize)
125}
126
127#[span_fn]
128pub async fn retire_expired_partitions(
129    lake: &DataLakeConnection,
130    expiration: DateTime<Utc>,
131) -> Result<()> {
132    while retire_expired_partitions_batch(lake, expiration).await? {}
133    Ok(())
134}
135
136/// A new partition overlaps an existing one that the write's retire step did not replace (SQLSTATE
137/// 23P01 on `lakehouse_partitions_no_overlap`). Typed so that a caller that can recompute its
138/// plan, such as the JIT views racing another writer, can tell it apart from other failures.
139#[derive(Debug, thiserror::Error)]
140#[error(
141    "new partition {view_set_name}/{view_instance_id} [{}, {}] overlaps an existing partition \
142     that this write's retire step ({retire_match:?}) did not replace, so this write cannot \
143     replace it (likely a concurrent materialization or merge). Retire the conflicting partition \
144     (e.g. retire_partition_by_metadata) or align the requested range/delta, then retry. \
145     Postgres detail: {detail}",
146    begin.to_rfc3339(),
147    end.to_rfc3339()
148)]
149pub struct PartitionOverlapConflict {
150    pub view_set_name: String,
151    pub view_instance_id: String,
152    pub begin: DateTime<Utc>,
153    pub end: DateTime<Utc>,
154    pub retire_match: RetireMatch,
155    pub detail: String,
156}
157
158/// Which SQL predicate `retire_partitions` uses to find partitions to replace.
159///
160/// There is no JIT registry to infer "this view regroups blocks across runs" from
161/// `view_set_name`/`view_instance_id` alone, so callers must say which rule applies to them.
162#[derive(Clone, Copy, Debug, PartialEq, Eq)]
163pub enum RetireMatch {
164    /// The existing partition is fully contained in the new
165    /// `[begin_insert_time, end_insert_time]` range (`begin_insert_time >= $3 AND end_insert_time
166    /// <= $4`, with an exact-match special case when the new range is degenerate). Correct
167    /// whenever a view's cut points are stable across materialization runs: a rewritten range
168    /// either exactly reproduces an old partition's range (matched by the exact-match case) or
169    /// strictly extends it (matched by containment). This holds for every non-JIT (batch/merge)
170    /// partition write and for an `InsertTime` JIT bucket that has no partition straddling its
171    /// edge. Used by everything except the two `BlockOrder::EventTime` JIT views and an
172    /// `InsertTime` JIT bucket with such a straddling partition.
173    Containment,
174    /// An *inclusive* insert-range intersection test -- `tstzrange(begin, end, '[]') &&
175    /// tstzrange($3, $4, '[]')` -- with same-run siblings excluded by identity (see
176    /// `same_run_ranges` below). The `'[]'` bounds matter twice over: a partition's
177    /// `[begin_insert_time, end_insert_time]` is the inclusive min/max of its blocks' insert
178    /// times, so two partitions that merely *touch* at one instant can both contain a block at
179    /// that instant and must be considered intersecting; and an inclusive range is never empty,
180    /// so degenerate `[t, t]` partitions (on either side) intersect anything containing `t` --
181    /// with Postgres's default half-open ranges, `tstzrange(t, t)` is empty and `&&` is
182    /// vacuously false.
183    ///
184    /// Also used by an `InsertTime` JIT bucket when a partition written at another rung (for
185    /// example a legacy hour partition written while the hour was still open) straddles the
186    /// bucket's edge: the straddler is replaced rather than tripping the exclusion constraint.
187    ///
188    /// Required by `thread_spans_view.rs` / `net_spans_view.rs`, whose `BlockOrder::EventTime`
189    /// grouping can move an *earlier* cut point between `jit_update` runs (see
190    /// `jit_partitions::group_blocks_into_partitions`), so a later run's narrower spec can leave
191    /// behind a stale, wider partition that merely *overlaps* the new range instead of being
192    /// contained by it -- `Containment` alone would never retire it, and the subsequent insert
193    /// would trip the `lakehouse_partitions_no_overlap` exclusion constraint.
194    ///
195    /// Tolerated gap: retiring the stale partition and inserting the new, narrower one are two
196    /// statements in one transaction, so a range the old partition covered but the new one does not
197    /// yet (a sibling later in the same `jit_update` loop covers it) is transiently missing until
198    /// that sibling is written -- or, if the loop fails, until the next successful `jit_update`.
199    /// Tolerable because JIT partitions are regenerated on demand from `blocks_view` and are not
200    /// the source of truth for their own data.
201    Overlap,
202}
203
204/// Retires partitions from the active set.
205///
206/// `retire_match` selects the SQL predicate (see `RetireMatch`): `Containment` is an insert-range
207/// containment test on the *existing* partition (with an exact-match special case for a
208/// degenerate new range), correct whenever a view's cut points are stable across runs.
209/// `Overlap` additionally matches (and retires) an existing partition that merely overlaps the new
210/// range without containing it, which `BlockOrder::EventTime` JIT views need because their cut
211/// points can move between runs, and an `InsertTime` JIT bucket needs when a partition of another
212/// rung straddles it.
213///
214/// `same_run_ranges` lists the exact `(begin_insert_time, end_insert_time)` pairs the calling
215/// `jit_update` run has already written (or found already up to date) earlier in its own loop; a
216/// row matching one of these pairs is never retired, even when the `retire_match` predicate
217/// would otherwise match it (see `RetireMatch::Overlap`'s docs for why this is identity-, not
218/// shape-, based). Only meaningful for `RetireMatch::Overlap` -- pass `&[]` for `Containment`.
219#[expect(clippy::too_many_arguments)]
220#[span_fn]
221pub async fn retire_partitions(
222    transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
223    view_set_name: &str,
224    view_instance_id: &str,
225    begin_insert_time: DateTime<Utc>,
226    end_insert_time: DateTime<Utc>,
227    retire_match: RetireMatch,
228    same_run_ranges: &[TimeRange],
229    logger: Arc<dyn Logger>,
230) -> Result<()> {
231    // For RetireMatch::Containment: this is not an overlap test, we need to assume that we are
232    // not making a new smaller partition where a bigger one existed. It gets tricky in the jit
233    // case where a partition can have only one block and begin_insert == end_insert -- handled by
234    // the exact-match branch below. RetireMatch::Overlap (thread_spans/net_spans, and InsertTime JIT buckets beside a straddling
235    // partition) additionally
236    // matches a stale, wider partition that only overlaps the new range; see RetireMatch's docs.
237    let same_run_begins: Vec<DateTime<Utc>> = same_run_ranges.iter().map(|r| r.begin).collect();
238    let same_run_ends: Vec<DateTime<Utc>> = same_run_ranges.iter().map(|r| r.end).collect();
239
240    //todo: use DELETE+RETURNING
241    let old_partitions = match retire_match {
242        RetireMatch::Containment if begin_insert_time == end_insert_time => {
243            // For identical timestamps, look for exact matches to handle single-block partitions
244            instrument_named!(
245                sqlx::query(
246                    "SELECT file_path, file_size
247             FROM lakehouse_partitions
248             WHERE view_set_name = $1
249             AND view_instance_id = $2
250             AND begin_insert_time = $3
251             AND end_insert_time = $3
252             ;",
253                )
254                .bind(view_set_name)
255                .bind(view_instance_id)
256                .bind(begin_insert_time)
257                .fetch_all(&mut **transaction),
258                "sql_select_old_partitions"
259            )
260            .await
261            .with_context(|| "listing old partitions (exact match)")?
262        }
263        RetireMatch::Containment => {
264            // For time ranges, use inclusive inequalities
265            instrument_named!(
266                sqlx::query(
267                    "SELECT file_path, file_size
268             FROM lakehouse_partitions
269             WHERE view_set_name = $1
270             AND view_instance_id = $2
271             AND begin_insert_time >= $3
272             AND end_insert_time <= $4
273             ;",
274                )
275                .bind(view_set_name)
276                .bind(view_instance_id)
277                .bind(begin_insert_time)
278                .bind(end_insert_time)
279                .fetch_all(&mut **transaction),
280                "sql_select_old_partitions"
281            )
282            .await
283            .with_context(|| "listing old partitions (range)")?
284        }
285        RetireMatch::Overlap => {
286            // Inclusive-bounds intersection, with rows matching a same-run range excluded by
287            // identity; see RetireMatch::Overlap's docs for why the bounds must be '[]'.
288            instrument_named!(
289                sqlx::query(
290                    "SELECT file_path, file_size
291             FROM lakehouse_partitions
292             WHERE view_set_name = $1
293             AND view_instance_id = $2
294             AND tstzrange(begin_insert_time, end_insert_time, '[]') && tstzrange($3, $4, '[]')
295             AND NOT EXISTS (
296                 SELECT 1 FROM unnest($5::timestamptz[], $6::timestamptz[]) AS same_run(b, e)
297                 WHERE same_run.b = begin_insert_time AND same_run.e = end_insert_time
298             )
299             ;",
300                )
301                .bind(view_set_name)
302                .bind(view_instance_id)
303                .bind(begin_insert_time)
304                .bind(end_insert_time)
305                .bind(&same_run_begins)
306                .bind(&same_run_ends)
307                .fetch_all(&mut **transaction),
308                "sql_select_old_partitions"
309            )
310            .await
311            .with_context(|| "listing old partitions (overlap)")?
312        }
313    };
314
315    // LOG: Found partitions for retirement (only if any found)
316    if !old_partitions.is_empty() {
317        logger
318            .write_log_entry(format!(
319                "[RETIRE_FOUND] view={}/{} time_range=[{}, {}] found_partitions={}",
320                view_set_name,
321                view_instance_id,
322                begin_insert_time,
323                end_insert_time,
324                old_partitions.len()
325            ))
326            .await?;
327    }
328
329    let mut file_paths = Vec::new();
330    for old_part in &old_partitions {
331        let file_path: Option<String> = old_part.try_get("file_path")?;
332        let file_size: i64 = old_part.try_get("file_size")?;
333        if let Some(path) = file_path {
334            logger
335                .write_log_entry(format!(
336                    "adding out of date partition {path} to temporary files to be deleted"
337                ))
338                .await?;
339            add_file_for_cleanup(&mut **transaction, &path, file_size).await?;
340            file_paths.push(path);
341        }
342    }
343
344    match retire_match {
345        RetireMatch::Containment if begin_insert_time == end_insert_time => {
346            // For identical timestamps, delete exact matches to handle single-block partitions
347            instrument_named!(
348                sqlx::query(
349                    "DELETE from lakehouse_partitions
350             WHERE view_set_name = $1
351             AND view_instance_id = $2
352             AND begin_insert_time = $3
353             AND end_insert_time = $3
354             ;",
355                )
356                .bind(view_set_name)
357                .bind(view_instance_id)
358                .bind(begin_insert_time)
359                .execute(&mut **transaction),
360                "sql_delete_old_partitions"
361            )
362            .await
363            .with_context(|| "deleting out of date partitions (exact match)")?
364        }
365        RetireMatch::Containment => {
366            // For time ranges, use inclusive inequalities
367            instrument_named!(
368                sqlx::query(
369                    "DELETE from lakehouse_partitions
370             WHERE view_set_name = $1
371             AND view_instance_id = $2
372             AND begin_insert_time >= $3
373             AND end_insert_time <= $4
374             ;",
375                )
376                .bind(view_set_name)
377                .bind(view_instance_id)
378                .bind(begin_insert_time)
379                .bind(end_insert_time)
380                .execute(&mut **transaction),
381                "sql_delete_old_partitions"
382            )
383            .await
384            .with_context(|| "deleting out of date partitions (range)")?
385        }
386        RetireMatch::Overlap => {
387            // Same predicate (and same-run exclusion) as the SELECT above, so exactly the rows
388            // just listed (and scheduled for cleanup) are deleted.
389            instrument_named!(
390                sqlx::query(
391                    "DELETE from lakehouse_partitions
392             WHERE view_set_name = $1
393             AND view_instance_id = $2
394             AND tstzrange(begin_insert_time, end_insert_time, '[]') && tstzrange($3, $4, '[]')
395             AND NOT EXISTS (
396                 SELECT 1 FROM unnest($5::timestamptz[], $6::timestamptz[]) AS same_run(b, e)
397                 WHERE same_run.b = begin_insert_time AND same_run.e = end_insert_time
398             )
399             ;",
400                )
401                .bind(view_set_name)
402                .bind(view_instance_id)
403                .bind(begin_insert_time)
404                .bind(end_insert_time)
405                .bind(&same_run_begins)
406                .bind(&same_run_ends)
407                .execute(&mut **transaction),
408                "sql_delete_old_partitions"
409            )
410            .await
411            .with_context(|| "deleting out of date partitions (overlap)")?
412        }
413    };
414    Ok(())
415}
416
417/// Generate a deterministic advisory lock key for a partition
418fn generate_partition_lock_key(
419    view_set_name: &str,
420    view_instance_id: &str,
421    begin_insert_time: DateTime<Utc>,
422    end_insert_time: DateTime<Utc>,
423) -> i64 {
424    let mut hasher = DefaultHasher::new();
425    view_set_name.hash(&mut hasher);
426    view_instance_id.hash(&mut hasher);
427    begin_insert_time.hash(&mut hasher);
428    end_insert_time.hash(&mut hasher);
429    hasher.finish() as i64
430}
431
432/// Deletes `file_path` from object storage unless a partition row references it.
433///
434/// A failed commit may still have been applied server-side, so the returned error alone can't
435/// tell us whether the file is orphaned. Check the authoritative state instead: the path carries
436/// a per-write UUID, so if no `lakehouse_partitions` row references it, nothing ever will and it
437/// is safe to delete.
438pub(crate) async fn delete_if_orphan(lake: &DataLakeConnection, file_path: &str) -> Result<()> {
439    let referenced = instrument_named!(
440        sqlx::query("SELECT 1 FROM lakehouse_partitions WHERE file_path = $1 LIMIT 1;")
441            .bind(file_path)
442            .fetch_optional(&lake.db_pool),
443        "sql_select_partition_file_referenced"
444    )
445    .await
446    .with_context(|| "checking whether partition file is referenced")?
447    .is_some();
448    if !referenced {
449        let path = object_store::path::Path::from(file_path);
450        lake.blob_storage
451            .inner()
452            .delete(&path)
453            .await
454            .with_context(|| format!("deleting orphaned partition file {file_path}"))?;
455    }
456    Ok(())
457}
458
459/// Inserts a partition into `lakehouse_partitions`, retiring whatever `retire_match` says it
460/// replaces first.
461///
462/// Not intended as a general-purpose API: `write_partition_from_rows` is the production entry
463/// point that builds the `Partition` this function inserts. This is `pub` only so
464/// `rust/analytics/tests/` (an external crate) can drive the SQL plumbing directly in a
465/// persistence round-trip test, mirroring `thread_spans_view::update_partition`'s reason for
466/// being `pub`.
467#[span_fn]
468pub async fn insert_partition(
469    lake: &DataLakeConnection,
470    partition: &Partition,
471    retire_match: RetireMatch,
472    same_run_ranges: &[TimeRange],
473    logger: Arc<dyn Logger>,
474) -> Result<()> {
475    let result =
476        insert_partition_transaction(lake, partition, retire_match, same_run_ranges, logger).await;
477    if result.is_err()
478        && let Some(file_path) = &partition.file_path
479    {
480        // The insert failed. A failed commit may still have been applied server-side, so we
481        // can't assume the file is unreferenced -- delete_if_orphan checks and deletes only if
482        // nothing references it. Best-effort: never mask the original error.
483        if let Err(cleanup_err) = delete_if_orphan(lake, file_path).await {
484            warn!("delete_if_orphan failed for {file_path}: {cleanup_err}");
485        }
486    }
487    result
488}
489
490#[span_fn]
491async fn insert_partition_transaction(
492    lake: &DataLakeConnection,
493    partition: &Partition,
494    retire_match: RetireMatch,
495    same_run_ranges: &[TimeRange],
496    logger: Arc<dyn Logger>,
497) -> Result<()> {
498    // Generate deterministic lock key for this partition
499    let lock_key = generate_partition_lock_key(
500        &partition.view_metadata.view_set_name,
501        &partition.view_metadata.view_instance_id,
502        partition.begin_insert_time(),
503        partition.end_insert_time(),
504    );
505
506    let mut transaction = instrument_named!(lake.db_pool.begin(), "sql_transaction_begin").await?;
507
508    debug!(
509        "[PARTITION_LOCK] view={}/{} time_range=[{}, {}] lock_key={} - acquiring advisory lock",
510        &partition.view_metadata.view_set_name,
511        &partition.view_metadata.view_instance_id,
512        partition.begin_insert_time(),
513        partition.end_insert_time(),
514        lock_key
515    );
516
517    // Acquire advisory lock - this will block until we can proceed
518    // pg_advisory_xact_lock automatically releases when transaction ends.
519    // The lock only serializes writers of this exact (view, instance, range) key, avoiding
520    // duplicate work. Correctness against overlapping writers of *different* ranges depends on
521    // retire_match: under RetireMatch::Containment (every caller except thread_spans/net_spans
522    // and InsertTime JIT buckets beside a straddling partition), it is enforced by the
523    // lakehouse_partitions_no_overlap exclusion constraint at insert time --
524    // a losing writer's insert fails loudly (PartitionOverlapConflict). Under RetireMatch::Overlap,
525    // the Overlap retire step below routes around that constraint (it can delete a
526    // differently-ranged, already-committed partition before this insert), so two concurrent
527    // writers of different, overlapping ranges are instead reconciled afterwards -- by the next
528    // `jit_update`'s up-to-date check for thread_spans/net_spans, by `resolve_bucket_coverage` and
529    // `write_spec_with_conflict_retry` for InsertTime JIT buckets -- not by the exclusion
530    // constraint; see `RetireMatch::Overlap`'s docs.
531    instrument_named!(
532        sqlx::query("SELECT pg_advisory_xact_lock($1);")
533            .bind(lock_key)
534            .execute(&mut *transaction),
535        "sql_advisory_lock"
536    )
537    .await
538    .with_context(|| "acquiring advisory lock")?;
539
540    // Decode source_data_hash back to the row count (it's stored as i64 little-endian bytes)
541    let source_row_count = partition_source_data::hash_to_object_count(&partition.source_data_hash)
542        .with_context(|| "decoding source_data_hash to row count")?;
543
544    // LOG: Lock acquired, starting partition write
545    logger
546        .write_log_entry(format!(
547            "[PARTITION_WRITE_START] view={}/{} time_range=[{}, {}] source_rows={} - lock acquired",
548            partition.view_metadata.view_set_name,
549            partition.view_metadata.view_instance_id,
550            partition.begin_insert_time(),
551            partition.end_insert_time(),
552            source_row_count
553        ))
554        .await?;
555
556    // Which partitions this call replaces depends on retire_match (see RetireMatch's docs):
557    // Containment only replaces partitions fully covered by this write's range; Overlap (the two
558    // BlockOrder::EventTime JIT views, and InsertTime JIT buckets beside a straddling partition)
559    // also replaces a stale partition that merely overlaps it.
560    retire_partitions(
561        &mut transaction,
562        &partition.view_metadata.view_set_name,
563        &partition.view_metadata.view_instance_id,
564        partition.begin_insert_time(),
565        partition.end_insert_time(),
566        retire_match,
567        same_run_ranges,
568        logger.clone(),
569    )
570    .await
571    .with_context(|| "retire_partitions")?;
572
573    debug!(
574        "[PARTITION_INSERT_ATTEMPT] view={}/{} time_range=[{}, {}] source_rows={} file_path={:?}",
575        &partition.view_metadata.view_set_name,
576        &partition.view_metadata.view_instance_id,
577        partition.begin_insert_time(),
578        partition.end_insert_time(),
579        source_row_count,
580        partition.file_path
581    );
582
583    let insert_result = insert_partition_row(&mut transaction, partition).await;
584
585    match insert_result {
586        Ok(_) => {
587            debug!(
588                "[PARTITION_INSERT_SUCCESS] view={}/{} time_range=[{}, {}] source_rows={}",
589                &partition.view_metadata.view_set_name,
590                &partition.view_metadata.view_instance_id,
591                partition.begin_insert_time(),
592                partition.end_insert_time(),
593                source_row_count
594            );
595        }
596        Err(ref e) => {
597            logger
598                .write_log_entry(format!(
599                    "[PARTITION_INSERT_ERROR] view={}/{} time_range=[{}, {}] source_rows={} error={}",
600                    partition.view_metadata.view_set_name,
601                    partition.view_metadata.view_instance_id,
602                    partition.begin_insert_time(),
603                    partition.end_insert_time(),
604                    source_row_count,
605                    e
606                ))
607                .await?;
608            return Err(insert_failure(
609                partition,
610                retire_match,
611                insert_result.unwrap_err(),
612            ));
613        }
614    };
615
616    // Commit the transaction (this also releases the advisory lock). On failure the transaction
617    // rolls back and the caller's delete_if_orphan reclaims the now-unreferenced parquet file.
618    instrument_named!(transaction.commit(), "sql_transaction_commit")
619        .await
620        .with_context(|| "commit")?;
621
622    info!(
623        "[PARTITION_WRITE_COMMIT] view={}/{} time_range=[{}, {}] file_path={:?} - lock released",
624        &partition.view_metadata.view_set_name,
625        &partition.view_metadata.view_instance_id,
626        partition.begin_insert_time(),
627        partition.end_insert_time(),
628        partition.file_path
629    );
630    Ok(())
631}
632
633/// Replaces every partition of `view_meta` contained in `unit_range` by `partitions`, in one
634/// transaction: readers see either the old rows or all of the new ones, never a gap. The
635/// partitions must tile a sub-range of `unit_range` and have been written by `write_file`
636/// without being registered.
637///
638/// On any failure every file of `partitions` that no row references is deleted, as
639/// `insert_partition` does for its single file; a `PartitionOverlapConflict` rolls the whole
640/// transaction back.
641#[span_fn]
642pub async fn insert_partitions_replacing(
643    lake: &DataLakeConnection,
644    view_meta: &ViewMetadata,
645    unit_range: TimeRange,
646    partitions: &[Partition],
647    logger: Arc<dyn Logger>,
648) -> Result<()> {
649    let result =
650        insert_partitions_replacing_transaction(lake, view_meta, unit_range, partitions, logger)
651            .await;
652    if result.is_err() {
653        for file_path in partitions.iter().filter_map(|p| p.file_path.as_ref()) {
654            if let Err(cleanup_err) = delete_if_orphan(lake, file_path).await {
655                warn!("delete_if_orphan failed for {file_path}: {cleanup_err}");
656            }
657        }
658    }
659    result
660}
661
662#[span_fn]
663async fn insert_partitions_replacing_transaction(
664    lake: &DataLakeConnection,
665    view_meta: &ViewMetadata,
666    unit_range: TimeRange,
667    partitions: &[Partition],
668    logger: Arc<dyn Logger>,
669) -> Result<()> {
670    let lock_key = generate_partition_lock_key(
671        &view_meta.view_set_name,
672        &view_meta.view_instance_id,
673        unit_range.begin,
674        unit_range.end,
675    );
676    let mut transaction = instrument_named!(lake.db_pool.begin(), "sql_transaction_begin").await?;
677    instrument_named!(
678        sqlx::query("SELECT pg_advisory_xact_lock($1);")
679            .bind(lock_key)
680            .execute(&mut *transaction),
681        "sql_advisory_lock"
682    )
683    .await
684    .with_context(|| "acquiring advisory lock")?;
685
686    logger
687        .write_log_entry(format!(
688            "[PARTITION_WRITE_START] view={}/{} time_range=[{}, {}] nb_partitions={} - lock acquired",
689            view_meta.view_set_name,
690            view_meta.view_instance_id,
691            unit_range.begin,
692            unit_range.end,
693            partitions.len()
694        ))
695        .await?;
696
697    retire_partitions(
698        &mut transaction,
699        &view_meta.view_set_name,
700        &view_meta.view_instance_id,
701        unit_range.begin,
702        unit_range.end,
703        RetireMatch::Containment,
704        &[],
705        logger.clone(),
706    )
707    .await
708    .with_context(|| "retire_partitions")?;
709
710    for partition in partitions {
711        if let Err(e) = insert_partition_row(&mut transaction, partition).await {
712            logger
713                .write_log_entry(format!(
714                    "[PARTITION_INSERT_ERROR] view={}/{} time_range=[{}, {}] error={}",
715                    partition.view_metadata.view_set_name,
716                    partition.view_metadata.view_instance_id,
717                    partition.begin_insert_time(),
718                    partition.end_insert_time(),
719                    e
720                ))
721                .await?;
722            return Err(insert_failure(partition, RetireMatch::Containment, e));
723        }
724    }
725
726    instrument_named!(transaction.commit(), "sql_transaction_commit")
727        .await
728        .with_context(|| "commit")?;
729
730    for partition in partitions {
731        info!(
732            "[PARTITION_WRITE_COMMIT] view={}/{} time_range=[{}, {}] file_path={:?} - lock released",
733            &partition.view_metadata.view_set_name,
734            &partition.view_metadata.view_instance_id,
735            partition.begin_insert_time(),
736            partition.end_insert_time(),
737            partition.file_path
738        );
739    }
740    Ok(())
741}
742
743/// Inserts one partition row inside `transaction`.
744async fn insert_partition_row(
745    transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
746    partition: &Partition,
747) -> std::result::Result<(), sqlx::Error> {
748    // Insert the new partition with format version 2. Explicit column list (rather
749    // than a bare positional VALUES(...)) so the statement's dependency on the table's shape is
750    // visible at the call site: Postgres's ALTER TABLE ... ADD COLUMN always appends, so a bare
751    // positional list cannot mis-bind from an ordinary migration, but it also can't catch a
752    // *missing* bind -- adding column 15 without touching this statement would compile, run, and
753    // silently store NULL forever. Naming every column (and partition_format_version's literal
754    // `2` by name rather than by ordinal) is what makes that omission catchable in review.
755    instrument_named!(
756        sqlx::query(
757            "INSERT INTO lakehouse_partitions (
758                 view_set_name,
759                 view_instance_id,
760                 begin_insert_time,
761                 end_insert_time,
762                 min_event_time,
763                 max_event_time,
764                 updated,
765                 file_path,
766                 file_size,
767                 file_schema_hash,
768                 source_data_hash,
769                 num_rows,
770                 partition_format_version,
771                 sort_order,
772                 max_sort_key_time
773             ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, 2, $13, $14);",
774        )
775        .bind(&*partition.view_metadata.view_set_name)
776        .bind(&*partition.view_metadata.view_instance_id)
777        .bind(partition.begin_insert_time())
778        .bind(partition.end_insert_time())
779        .bind(partition.min_event_time())
780        .bind(partition.max_event_time())
781        .bind(partition.updated)
782        .bind(&partition.file_path)
783        .bind(partition.file_size)
784        .bind(&partition.view_metadata.file_schema_hash)
785        .bind(&partition.source_data_hash)
786        .bind(partition.num_rows)
787        .bind(&partition.sort_order)
788        .bind(partition.max_sort_key_time)
789        .execute(&mut **transaction),
790        "sql_insert_partition"
791    )
792    .await
793    .map(|_| ())
794}
795
796/// Translates an exclusion-constraint violation (raw SQLSTATE 23P01) into a legible domain error:
797/// it means an existing partition overlaps this one without being matched by this transaction's
798/// retire step (RetireMatch::Containment: not fully contained by the new range;
799/// RetireMatch::Overlap: not matched by the intersection predicate either, e.g. still committed by
800/// a concurrent writer racing this one -- see RetireMatch::Overlap's "Concurrent writers" docs) --
801/// e.g. a concurrent maintenance merge committed a wider partition.
802fn insert_failure(
803    partition: &Partition,
804    retire_match: RetireMatch,
805    e: sqlx::Error,
806) -> anyhow::Error {
807    let overlap_detail = e.as_database_error().and_then(|db_err| {
808        (db_err.constraint() == Some("lakehouse_partitions_no_overlap")).then(|| db_err.to_string())
809    });
810    match overlap_detail {
811        Some(detail) => PartitionOverlapConflict {
812            view_set_name: partition.view_metadata.view_set_name.to_string(),
813            view_instance_id: partition.view_metadata.view_instance_id.to_string(),
814            begin: partition.begin_insert_time(),
815            end: partition.end_insert_time(),
816            retire_match,
817            detail,
818        }
819        .into(),
820        None => e.into(),
821    }
822}
823
824/// Result of writing rows to a partition file.
825struct PartitionWriteResult {
826    num_rows: i64,
827    file_path: Option<String>,
828    file_size: i64,
829    event_time_range: Option<TimeRange>,
830    max_sort_key_time: Option<DateTime<Utc>>,
831}
832
833/// Result of `write_rows_and_track_times`: the partition's event time range, alongside the
834/// folded `max_sort_key_time`. `pub` because `write_rows_and_track_times` is itself `pub` and is
835/// called from `rust/analytics/tests/`, which compiles as an external crate.
836#[derive(Debug)]
837pub struct RowSetTrackingResult {
838    pub event_time_range: Option<TimeRange>,
839    pub max_sort_key_time: Option<DateTime<Utc>>,
840}
841
842/// Guards a declared non-nullable field against a `NULL` slipping through undetected.
843///
844/// The parquet writer does not enforce declared nullability itself: for a required top-level
845/// leaf, `ArrowLevels` has no definition levels, so `write_leaf` treats every index as non-null
846/// and a `NULL` in the batch is silently written as the type's default value (e.g. `""` for
847/// `Utf8`) rather than rejected. Builder-based views already catch this via
848/// `RecordBatch::try_new`'s own nullability check; what this guard adds is coverage for the two
849/// kinds of batch that bypass that check -- `blocks` (`rows_to_record_batch`, whose schema is
850/// inferred from Postgres and never compared to the declared one) and every DataFusion-produced
851/// batch (`SqlBatchView` transforms, every merge). One `null_count()` per declared non-nullable
852/// column per batch.
853fn check_non_nullable_columns(batch: &RecordBatch, file_schema: &Schema, desc: &str) -> Result<()> {
854    // Positional, not by-name: the parquet writer zips the declared schema's
855    // fields against the batch's columns by position with no name check, and a batch's column
856    // names need not match the declared schema's at all (e.g. `blocks`, whose batch is built
857    // from Postgres column aliases while the declared schema uses `processes.foo`-style names).
858    // A by-name lookup would therefore silently skip the check for exactly the view that needs
859    // it most.
860    for (i, field) in file_schema.fields().iter().enumerate() {
861        if field.is_nullable() {
862            continue;
863        }
864        let Some(column) = batch.columns().get(i) else {
865            continue;
866        };
867        if column.null_count() > 0 {
868            anyhow::bail!(
869                "writing partition {desc}: column {} ({:?}) is declared NOT NULL but the batch \
870                 carries {} null value(s)",
871                i,
872                field.name(),
873                column.null_count()
874            );
875        }
876    }
877    Ok(())
878}
879
880/// Writes rows from the stream and tracks event time ranges.
881///
882/// Also folds a running `max_sort_key_time` across every received `PartitionRowSet`: the
883/// partition-level value is `Some(max)` only if *every* received row set carried `Some` -- a
884/// single `None` poisons the whole partition to `None`. This must be a running `max`, never
885/// "last row set wins": this function is shared by four multi-row-set senders, and
886/// `BlockPartitionSpec` in particular streams row sets *out of order* via `buffer_unordered`
887/// (`block_partition_spec.rs`), where "last wins" would be actively wrong. `thread_spans_view.rs`
888/// sends exactly one row set today, so the distinction is invisible there, but do not let that
889/// fact simplify this fold away.
890#[span_fn]
891pub async fn write_rows_and_track_times(
892    rb_stream: &mut Receiver<Result<PartitionRowSet, anyhow::Error>>,
893    arrow_writer: &mut AsyncArrowWriter<AsyncParquetWriter>,
894    file_schema: &Schema,
895    logger: &Arc<dyn Logger>,
896    desc: &str,
897) -> Result<RowSetTrackingResult> {
898    let mut min_event_time: Option<DateTime<Utc>> = None;
899    let mut max_event_time: Option<DateTime<Utc>> = None;
900    let mut max_sort_key_time: Option<DateTime<Utc>> = None;
901    let mut any_row_set = false;
902    let mut all_some_sort_key_time = true;
903    let mut write_progression = 0;
904
905    while let Some(msg) = rb_stream.recv().await {
906        let row_set = msg?;
907        any_row_set = true;
908        min_event_time = Some(
909            min_event_time
910                .unwrap_or(row_set.rows_time_range.begin)
911                .min(row_set.rows_time_range.begin),
912        );
913        max_event_time = Some(
914            max_event_time
915                .unwrap_or(row_set.rows_time_range.end)
916                .max(row_set.rows_time_range.end),
917        );
918        match row_set.max_sort_key_time {
919            Some(t) => {
920                max_sort_key_time = Some(max_sort_key_time.map_or(t, |running| running.max(t)));
921            }
922            None => {
923                all_some_sort_key_time = false;
924            }
925        }
926        {
927            // The guard is !Send, so it must not be live across the awaits below.
928            let _span = span_scope!(name = "check_non_nullable_columns");
929            check_non_nullable_columns(&row_set.rows, file_schema, desc)?;
930        }
931        instrument_named!(arrow_writer.write(&row_set.rows), "arrow_writer_write")
932            .await
933            .with_context(|| "arrow_writer.write")?;
934        if arrow_writer.in_progress_size() > 100 * 1024 * 1024 {
935            instrument_named!(arrow_writer.flush(), "arrow_writer_flush")
936                .await
937                .with_context(|| "arrow_writer.flush")?;
938        }
939
940        // Log progress every 10MB to avoid spamming and prevent idle timeout
941        let progression = arrow_writer.bytes_written() / (10 * 1024 * 1024);
942        if progression != write_progression {
943            write_progression = progression;
944            let written = arrow_writer.bytes_written();
945            logger
946                .write_log_entry(format!("{desc}: written {written} bytes"))
947                .await
948                .with_context(|| "writing log entry")?;
949        }
950    }
951
952    let event_time_range = match (min_event_time, max_event_time) {
953        (Some(begin), Some(end)) => Some(TimeRange { begin, end }),
954        _ => None,
955    };
956    let max_sort_key_time = if any_row_set && all_some_sort_key_time {
957        max_sort_key_time
958    } else {
959        None
960    };
961    Ok(RowSetTrackingResult {
962        event_time_range,
963        max_sort_key_time,
964    })
965}
966
967/// Disposes of the object-store file of a partition that turned out empty.
968///
969/// The delete is deferred to the batched `temporary_files` cleanup so the object-store round
970/// trip stays off the materialization path. The writer bumps `byte_counter` before handing bytes
971/// to the store, so a zero counter means the object can't exist and there is nothing to clean up.
972async fn release_empty_file(
973    lake: &DataLakeConnection,
974    file_path: &str,
975    byte_counter: &Arc<AtomicI64>,
976) -> Result<()> {
977    let bytes_written = byte_counter.load(std::sync::atomic::Ordering::Relaxed);
978    if bytes_written == 0 {
979        return Ok(());
980    }
981    if let Err(register_err) = add_file_for_cleanup(&lake.db_pool, file_path, bytes_written).await {
982        // No caller receives this file path on error, so nothing else would ever remove it.
983        let path = object_store::path::Path::from(file_path);
984        if let Err(delete_err) = lake.blob_storage.inner().delete(&path).await {
985            warn!("failed to delete unregistered empty file {file_path}: {delete_err}");
986        }
987        return Err(register_err);
988    }
989    Ok(())
990}
991
992/// Finalizes the partition write, closing the file and creating metadata.
993#[expect(clippy::too_many_arguments)]
994#[span_fn]
995async fn finalize_partition_write(
996    event_time_range: Option<TimeRange>,
997    max_sort_key_time: Option<DateTime<Utc>>,
998    arrow_writer: AsyncArrowWriter<AsyncParquetWriter>,
999    file_path: String,
1000    byte_counter: &Arc<AtomicI64>,
1001    logger: &Arc<dyn Logger>,
1002    desc: &str,
1003    lake: &DataLakeConnection,
1004) -> Result<PartitionWriteResult> {
1005    if let Some(event_time_range) = event_time_range {
1006        // Potentially non-empty partition: close the file and get metadata
1007        let close_result = instrument_named!(arrow_writer.close(), "arrow_writer_close").await;
1008
1009        match close_result {
1010            Ok(parquet_metadata) => {
1011                let num_rows = parquet_metadata.file_metadata().num_rows();
1012
1013                // Check if the file actually contains rows
1014                // Even if we tracked event times, the file might be empty
1015                if num_rows == 0 {
1016                    // File contains no rows - treat as empty partition
1017                    logger
1018                        .write_log_entry(format!(
1019                            "created 0-row file, treating as empty partition for {desc}"
1020                        ))
1021                        .await
1022                        .with_context(|| "writing log entry")?;
1023
1024                    release_empty_file(lake, &file_path, byte_counter).await?;
1025
1026                    return Ok(PartitionWriteResult {
1027                        num_rows: 0,
1028                        file_path: None,
1029                        file_size: 0,
1030                        event_time_range: None,
1031                        max_sort_key_time: None,
1032                    });
1033                }
1034
1035                // Non-empty file: keep it and return the result
1036                debug!(
1037                    "wrote nb_rows={} size={} path={file_path}",
1038                    num_rows,
1039                    byte_counter.load(std::sync::atomic::Ordering::Relaxed)
1040                );
1041                let file_size = byte_counter.load(std::sync::atomic::Ordering::Relaxed);
1042                Ok(PartitionWriteResult {
1043                    num_rows,
1044                    file_path: Some(file_path),
1045                    file_size,
1046                    event_time_range: Some(event_time_range),
1047                    max_sort_key_time,
1048                })
1049            }
1050            Err(e) => {
1051                // Close failed - try to delete any partial file that may have been written
1052                warn!(
1053                    "arrow_writer.close failed, attempting to delete partial file: {}",
1054                    file_path
1055                );
1056                let path = object_store::path::Path::from(file_path.as_str());
1057                if let Err(delete_err) = lake.blob_storage.inner().delete(&path).await {
1058                    warn!(
1059                        "failed to delete partial file {}: {}",
1060                        file_path, delete_err
1061                    );
1062                }
1063                Err(e).with_context(|| "arrow_writer.close")
1064            }
1065        }
1066    } else {
1067        // Empty partition: no row set was ever handed to the writer, so there is no file to
1068        // keep; `release_empty_file` registers cleanup only if bytes were written.
1069        drop(arrow_writer);
1070
1071        logger
1072            .write_log_entry(format!("creating empty partition record for {desc}"))
1073            .await
1074            .with_context(|| "writing log entry")?;
1075
1076        release_empty_file(lake, &file_path, byte_counter).await?;
1077
1078        Ok(PartitionWriteResult {
1079            num_rows: 0,
1080            file_path: None,
1081            file_size: 0,
1082            event_time_range: None,
1083            max_sort_key_time: None,
1084        })
1085    }
1086}
1087
1088/// Writes a partition to a Parquet file from a stream of `PartitionRowSet`s.
1089///
1090/// `sort_order` is recorded on the resulting `Partition` as-is (see
1091/// `View::get_merged_partition_sort_order` and `MetadataPartitionSpec::sort_order`).
1092///
1093/// `retire_match` is forwarded to `retire_partitions` (see `RetireMatch`'s docs): pass
1094/// `RetireMatch::Containment` unless this call is one of the two `BlockOrder::EventTime` JIT
1095/// views (`thread_spans_view.rs` / `net_spans_view.rs`) or an `InsertTime` JIT bucket beside a
1096/// partition that straddles it, which must pass `RetireMatch::Overlap`.
1097///
1098/// `same_run_ranges` is forwarded to `retire_partitions` as-is (see its docs and
1099/// `RetireMatch::Overlap`'s); pass an empty `Vec` unless `retire_match` is `RetireMatch::Overlap`,
1100/// in which case it must list every insert range the calling `jit_update` run has already written
1101/// (or found already up to date) earlier in its own loop. Taken by value (not `&[TimeRange]`):
1102/// this whole call is normally wrapped in `spawn_with_context`, whose `Future` bound requires
1103/// `'static`, which a slice borrowed from the caller's loop-local accumulator cannot satisfy.
1104#[expect(clippy::too_many_arguments)]
1105#[span_fn(view = view_metadata.view_set_name)]
1106pub async fn write_partition_from_rows(
1107    lake: Arc<DataLakeConnection>,
1108    view_metadata: ViewMetadata,
1109    file_schema: Arc<Schema>,
1110    insert_range: TimeRange,
1111    source_data_hash: Vec<u8>,
1112    sort_order: Option<Vec<String>>,
1113    retire_match: RetireMatch,
1114    same_run_ranges: Vec<TimeRange>,
1115    rb_stream: Receiver<Result<PartitionRowSet, anyhow::Error>>,
1116    logger: Arc<dyn Logger>,
1117) -> Result<()> {
1118    let partition = write_partition_file(
1119        &lake,
1120        view_metadata,
1121        file_schema,
1122        insert_range,
1123        source_data_hash,
1124        sort_order,
1125        rb_stream,
1126        logger.clone(),
1127    )
1128    .await?;
1129    let file_size = partition.file_size;
1130    let warm_file_path = partition.file_path.clone();
1131    // On failure insert_partition reclaims the now-unreferenced parquet file via delete_if_orphan.
1132    insert_partition(&lake, &partition, retire_match, &same_run_ranges, logger)
1133        .await
1134        .with_context(|| "insert_partition")?;
1135
1136    // The file is now durable in S3 and registered in PostgreSQL: warm the
1137    // object cache with its key so the follow-up query's first read is a
1138    // cache hit instead of a cold origin GET. Fire-and-forget: this must
1139    // never delay or fail the write/materialization path.
1140    if let Some(file_path) = &warm_file_path {
1141        lake.warm_object(file_path, file_size);
1142    }
1143    Ok(())
1144}
1145
1146/// Writes the rows of `rb_stream` to a new parquet file and returns the `Partition` describing
1147/// it, without registering it in `lakehouse_partitions`. The caller owns the file until it is
1148/// registered: if it never is, it must delete the file (see `delete_if_orphan`).
1149#[expect(clippy::too_many_arguments)]
1150#[span_fn(view = view_metadata.view_set_name)]
1151pub async fn write_partition_file(
1152    lake: &DataLakeConnection,
1153    view_metadata: ViewMetadata,
1154    file_schema: Arc<Schema>,
1155    insert_range: TimeRange,
1156    source_data_hash: Vec<u8>,
1157    sort_order: Option<Vec<String>>,
1158    mut rb_stream: Receiver<Result<PartitionRowSet, anyhow::Error>>,
1159    logger: Arc<dyn Logger>,
1160) -> Result<Partition> {
1161    let file_id = uuid::Uuid::new_v4();
1162    let file_path = format!(
1163        "views/{}/{}/{}/{}_{file_id}.parquet",
1164        view_metadata.view_set_name,
1165        view_metadata.view_instance_id,
1166        insert_range.begin.format("%Y-%m-%d"),
1167        insert_range.begin.format("%H-%M-%S")
1168    );
1169    let byte_counter = Arc::new(AtomicI64::new(0));
1170    let object_store_writer = AsyncParquetWriter::new(
1171        BufWriter::new(
1172            lake.blob_storage.inner(),
1173            object_store::path::Path::parse(&file_path).with_context(|| "parsing path")?,
1174        )
1175        .with_max_concurrency(2),
1176        byte_counter.clone(),
1177    );
1178
1179    // Configure writer with page-level statistics enabled (default in Arrow 57.0+)
1180    // This ensures ColumnIndex with proper null_pages field is written for DataFusion 51+ compatibility
1181    let props = WriterProperties::builder()
1182        .set_writer_version(WriterVersion::PARQUET_2_0)
1183        .set_compression(Compression::LZ4_RAW)
1184        // Explicitly enable page-level statistics for clarity (this is the default in Arrow 57.0+)
1185        // This generates ColumnIndex structures with proper null_pages field
1186        .set_statistics_enabled(parquet::file::properties::EnabledStatistics::Page)
1187        // 8x finer than the 1 Mi default, so a clustered sort key actually pays off in row-group
1188        // pruning; only affects newly written partitions.
1189        .set_max_row_group_row_count(Some(128 * 1024))
1190        .build();
1191    let mut arrow_writer =
1192        AsyncArrowWriter::try_new(object_store_writer, file_schema.clone(), Some(props))
1193            .with_context(|| "allocating async arrow writer")?;
1194
1195    let desc = format!(
1196        "[{}, {}] {} {}",
1197        view_metadata.view_set_name,
1198        view_metadata.view_instance_id,
1199        insert_range.begin.to_rfc3339(),
1200        insert_range.end.to_rfc3339()
1201    );
1202
1203    // Write rows and track event time ranges
1204    let RowSetTrackingResult {
1205        event_time_range,
1206        max_sort_key_time,
1207    } = match write_rows_and_track_times(
1208        &mut rb_stream,
1209        &mut arrow_writer,
1210        &file_schema,
1211        &logger,
1212        &desc,
1213    )
1214    .await
1215    {
1216        Ok(result) => result,
1217        Err(e) => {
1218            // The writer is dropped without close/abort on this error path, which can
1219            // leave already-uploaded multipart data orphaned in object storage. Delete
1220            // any partial file before propagating the error (mirror finalize cleanup).
1221            drop(arrow_writer);
1222            warn!(
1223                "write_rows_and_track_times failed, attempting to delete partial file: {}",
1224                file_path
1225            );
1226            let path = object_store::path::Path::from(file_path.as_str());
1227            if let Err(delete_err) = lake.blob_storage.inner().delete(&path).await {
1228                warn!(
1229                    "failed to delete partial file {}: {}",
1230                    file_path, delete_err
1231                );
1232            }
1233            return Err(e).with_context(|| "write_rows_and_track_times");
1234        }
1235    };
1236
1237    // Finalize the write (close file or create empty metadata)
1238    let result = finalize_partition_write(
1239        event_time_range,
1240        max_sort_key_time,
1241        arrow_writer,
1242        file_path,
1243        &byte_counter,
1244        &logger,
1245        &desc,
1246        lake,
1247    )
1248    .await?;
1249
1250    info!(
1251        "wrote partition file view={}/{} time_range=[{}, {}] file_path={:?}",
1252        view_metadata.view_set_name,
1253        view_metadata.view_instance_id,
1254        insert_range.begin,
1255        insert_range.end,
1256        result.file_path
1257    );
1258    Ok(Partition {
1259        view_metadata,
1260        insert_time_range: insert_range,
1261        event_time_range: result.event_time_range,
1262        updated: sqlx::types::chrono::Utc::now(),
1263        file_path: result.file_path,
1264        file_size: result.file_size,
1265        source_data_hash,
1266        num_rows: result.num_rows,
1267        sort_order,
1268        max_sort_key_time: result.max_sort_key_time,
1269    })
1270}