refactor: reuse the backend for packed database exports (#10482)

* refactor: reuse packed export destination backend

Signed-off-by: jeremyhi <fengjiachun@gmail.com>

* test: cover managed packed routing and update CLI writer caller

Signed-off-by: jeremyhi <fengjiachun@gmail.com>

* fix: reuse packed backend for logical table exports

Signed-off-by: jeremyhi <fengjiachun@gmail.com>

* refactor: reuse the owned file path in managed exports

Signed-off-by: jeremyhi <fengjiachun@gmail.com>

---------

Signed-off-by: jeremyhi <fengjiachun@gmail.com>
This commit is contained in:
jeremyhi
2026-11-20 13:12:54 +00:00
committed by GitHub
parent b4ce259859
commit 83bf74193f
7 changed files with 372 additions and 109 deletions
@@ -577,8 +577,6 @@ mod tests {
)]));
let mut table = ParquetFileWriter::open_packed(
schema,
store.clone(),
"unused",
None,
PackedTableWriter::new(packed.clone(), "empty".into(), 1, false),
)
+48 -2
View File
@@ -329,6 +329,11 @@ impl PackedTableWriter {
}
}
/// Parquet stream name, used as the object name when standalone and as an error label when packed.
pub fn path(&self) -> &str {
&self.path
}
pub(crate) async fn write(&mut self, bytes: Bytes) -> Result<()> {
if self.standalone.is_none()
&& (self.ordinary || self.buffer.len().saturating_add(bytes.len()) > WRITE_BYTES)
@@ -460,8 +465,6 @@ mod tests {
PackedTableWriter::new(shared.clone(), format!("table{id}"), id as u32, false);
let mut writer = ParquetFileWriter::open_packed(
batch.schema(),
store.clone(),
"unused",
Some(ParquetWriterLimits {
row_group_rows: 8192,
flush_threshold_bytes: WRITE_BYTES,
@@ -626,6 +629,49 @@ mod tests {
}
}
#[tokio::test]
async fn ordinary_parquet_failure_and_cancellation_abort_shared_destination() {
for cancel in [false, true] {
let directory = common_test_util::temp_dir::create_temp_dir("packed-ordinary-failure");
let store = object_store::secure_fs::SecureFsRoot::open(directory.path())
.unwrap()
.build_operator();
let factory: MockWriterFactory = Arc::new(|_, _, writer| Box::new(FailClose(writer)));
let store = store.layer(
MockLayerBuilder::default()
.writer_factory(factory)
.build()
.unwrap(),
);
let shared = PackedWriter::new(store.clone()).unwrap();
let packed = PackedTableWriter::new(shared.clone(), "audit".into(), 42, true);
let batch = RecordBatch::try_from_iter([(
"value",
Arc::new(Int64Array::from(vec![1, 2, 3])) as ArrayRef,
)])
.unwrap();
let mut writer = ParquetFileWriter::open_packed(batch.schema(), None, packed).unwrap();
writer.write(batch, None).await.unwrap();
let token = CancellationToken::new();
if cancel {
token.cancel();
}
let error = writer.finish(Some(&token)).await.unwrap_err();
if cancel {
assert!(matches!(error, error::Error::ParquetWriteCancelled { .. }));
} else {
assert!(matches!(
error,
error::Error::WriteObject { ref path, .. } if path == "table-42.parquet"
));
}
writer.abort().await.unwrap();
assert!(!store.exists("table-42.parquet").await.unwrap());
assert!(shared.lock().await.index.tables.is_empty());
assert!(!store.exists(PACK_INDEX_FILE).await.unwrap());
}
}
#[tokio::test]
async fn close_failure_cancellation_and_collision_never_publish_index() {
for failure in ["pack-000000.bin", PACK_INDEX_FILE, "cancel", "collision"] {
+21 -17
View File
@@ -55,7 +55,6 @@ pub struct ParquetFileWriter {
encoder: Option<ArrowWriter<Vec<u8>>>,
sink: ParquetSink,
rows: u64,
store: ObjectStore,
path: String,
limits: Option<ParquetWriterLimits>,
creation: ParquetCreationPolicy,
@@ -63,7 +62,7 @@ pub struct ParquetFileWriter {
}
enum ParquetSink {
Object(Writer),
Object { writer: Writer, store: ObjectStore },
Packed(Box<PackedTableWriter>),
}
@@ -107,9 +106,11 @@ impl ParquetFileWriter {
.context(error::WriteObjectSnafu { path })?;
Ok(Self {
encoder: Some(encoder),
sink: ParquetSink::Object(sink),
sink: ParquetSink::Object {
writer: sink,
store,
},
rows: 0,
store,
path: path.to_owned(),
limits,
creation,
@@ -120,17 +121,15 @@ impl ParquetFileWriter {
/// Encode into a request-owned pack or standalone destination.
pub fn open_packed(
schema: SchemaRef,
store: ObjectStore,
path: &str,
limits: Option<ParquetWriterLimits>,
packed: PackedTableWriter,
) -> Result<Self> {
let path = packed.path().to_owned();
Ok(Self {
encoder: Some(build_encoder(schema, limits, path)?),
encoder: Some(build_encoder(schema, limits, &path)?),
sink: ParquetSink::Packed(Box::new(packed)),
rows: 0,
store,
path: path.into(),
path,
limits,
creation: ParquetCreationPolicy::IfNotExists,
close_started: false,
@@ -196,7 +195,7 @@ impl ParquetFileWriter {
let bytes = Bytes::from(bytes);
let sink = match &mut self.sink {
ParquetSink::Packed(packed) => return packed.write(bytes).await,
ParquetSink::Object(sink) => sink,
ParquetSink::Object { writer, .. } => writer,
};
let chunk = DEFAULT_WRITE_BUFFER_SIZE.as_bytes() as usize;
// Slices retain the complete encoded allocation until its last submission.
@@ -228,7 +227,7 @@ impl ParquetFileWriter {
check_cancelled(cancellation)?;
let sink = match &mut self.sink {
ParquetSink::Packed(packed) => return packed.finish(self.rows, cancellation).await,
ParquetSink::Object(sink) => sink,
ParquetSink::Object { writer, .. } => writer,
};
self.close_started = true;
sink.close()
@@ -241,9 +240,9 @@ impl ParquetFileWriter {
/// Abort after all in-flight operations complete. Preserve ambiguous commits;
/// conditional callers delegate cleanup exclusively to the backend.
pub async fn abort(mut self) -> Result<()> {
let result = match &mut self.sink {
let (result, store) = match &mut self.sink {
ParquetSink::Packed(packed) => return packed.abort().await,
ParquetSink::Object(sink) => sink.abort().await,
ParquetSink::Object { writer, store } => (writer.abort().await, store),
};
if self.creation == ParquetCreationPolicy::Overwrite
&& result.as_ref().is_err_and(|error| {
@@ -252,7 +251,7 @@ impl ParquetFileWriter {
|| object_store::secure_fs::is_unsynced_overwrite_abort(error))
})
{
let store = self.store.clone();
let store = store.clone();
let path = self.path.clone();
// Secure filesystem writers require dropping the handle before deletion.
drop(self);
@@ -534,7 +533,10 @@ mod tests {
.await
.unwrap();
// No storage-layer chunking: observe the application's actual submissions.
writer.sink = ParquetSink::Object(store.writer("large.parquet").await.unwrap());
writer.sink = ParquetSink::Object {
writer: store.writer("large.parquet").await.unwrap(),
store: store.clone(),
};
writer.write(batch.clone(), None).await.unwrap();
writer.finish(None).await.unwrap();
let sizes = observations.lock().unwrap().write_sizes.clone();
@@ -737,8 +739,10 @@ mod tests {
.await
.unwrap();
// Force footer bytes through the sink before its close operation.
writer.sink =
ParquetSink::Object(store.writer_with("cancel.parquet").chunk(1).await.unwrap());
writer.sink = ParquetSink::Object {
writer: store.writer_with("cancel.parquet").chunk(1).await.unwrap(),
store: store.clone(),
};
let cancellation = CancellationToken::new();
let result = {
let finish = writer.finish(Some(&cancellation));
+178 -41
View File
@@ -23,7 +23,7 @@ use common_datasource::file_format::Format;
use common_datasource::file_format::csv::stream_to_csv;
use common_datasource::file_format::json::stream_to_json;
use common_datasource::file_format::parquet::stream_to_parquet;
use common_datasource::object_store::{build_backend_for_write, build_backend_for_write_with_path};
use common_datasource::object_store::{LocalFileAccess, build_backend_for_write_with_path};
use common_datasource::packed_writer::PackedTableWriter;
use common_datasource::parquet_writer::ParquetFileWriter;
use common_query::Output;
@@ -62,7 +62,6 @@ const WRITE_CONCURRENCY: usize = 8;
impl StatementExecutor {
async fn stream_to_file(
&self,
stream: SendableRecordBatchStream,
format: &Format,
object_store: ObjectStore,
@@ -187,8 +186,16 @@ impl StatementExecutor {
} = &req;
debug!("Copy table: {table_id} to location: {location}");
self.copy_to_file_managed(&format, output, location, connection, managed, packed)
.await
Self::copy_to_file_managed(
&self.local_file_access,
&format,
output,
location,
connection,
managed,
packed,
)
.await
}
pub(crate) async fn copy_to_file(
@@ -198,12 +205,20 @@ impl StatementExecutor {
location: &str,
connection: &HashMap<String, String>,
) -> Result<usize> {
self.copy_to_file_managed(format, output, location, connection, None, None)
.await
Self::copy_to_file_managed(
&self.local_file_access,
format,
output,
location,
connection,
None,
None,
)
.await
}
async fn copy_to_file_managed(
&self,
local_file_access: &LocalFileAccess,
format: &Format,
output: Output,
location: &str,
@@ -224,30 +239,47 @@ impl StatementExecutor {
_ => unreachable!(),
};
let (store, filename) = if packed.is_some() {
let store = build_backend_for_write(location, connection, &self.local_file_access)
.await
.context(error::BuildBackendSnafu)?;
(store, location.to_string())
} else {
let backend =
build_backend_for_write_with_path(location, connection, &self.local_file_access)
.await
.context(error::BuildBackendSnafu)?;
let filename = backend.object_path.context(error::UnexpectedSnafu {
if let (Some((budget, token)), Some(packed)) = (managed, packed) {
return stream_to_managed_parquet_with_packed(
stream,
ManagedParquetDestination::Packed(packed),
budget,
token,
)
.await;
}
let backend = build_backend_for_write_with_path(location, connection, local_file_access)
.await
.context(error::BuildBackendSnafu)?;
let filename = backend
.object_path
.with_context(|| error::UnexpectedSnafu {
violated: format!("Expected filename, path: {location}"),
})?;
(backend.object_store, filename)
};
if let Some((budget, token)) = managed {
stream_to_managed_parquet_with_packed(stream, store, &filename, budget, token, packed)
.await
stream_to_managed_parquet_with_packed(
stream,
ManagedParquetDestination::Object {
store: backend.object_store,
path: filename,
},
budget,
token,
)
.await
} else {
self.stream_to_file(stream, format, store, &filename).await
Self::stream_to_file(stream, format, backend.object_store, &filename).await
}
}
}
/// File destinations own their object key; packed streams use their writer's stream name.
enum ManagedParquetDestination {
Object { store: ObjectStore, path: String },
Packed(PackedTableWriter),
}
#[cfg(test)]
pub(crate) async fn stream_to_managed_parquet(
stream: SendableRecordBatchStream,
@@ -256,16 +288,23 @@ pub(crate) async fn stream_to_managed_parquet(
budget: &ExportWriteBudget,
token: &CancellationToken,
) -> Result<usize> {
stream_to_managed_parquet_with_packed(stream, store, path, budget, token, None).await
stream_to_managed_parquet_with_packed(
stream,
ManagedParquetDestination::Object {
store,
path: path.to_owned(),
},
budget,
token,
)
.await
}
async fn stream_to_managed_parquet_with_packed(
mut stream: SendableRecordBatchStream,
store: ObjectStore,
path: &str,
destination: ManagedParquetDestination,
budget: &ExportWriteBudget,
token: &CancellationToken,
packed: Option<PackedTableWriter>,
) -> Result<usize> {
use common_recordbatch::{RecordBatch, map_dictionary_to_values_schema};
let original = stream.schema();
@@ -284,21 +323,25 @@ async fn stream_to_managed_parquet_with_packed(
} else {
expanded_schema.clone()
};
let packed_destination = packed.is_some();
let mut writer = if let Some(packed) = packed {
ParquetFileWriter::open_packed(
output_schema.arrow_schema().clone(),
store,
let packed_destination = matches!(destination, ManagedParquetDestination::Packed(_));
let schema = output_schema.arrow_schema().clone();
let (writer, path) = match destination {
ManagedParquetDestination::Packed(packed) => {
let path = packed.path().to_owned();
let limits =
crate::statement::export_logical_tables::LogicalTableExportLimits::default();
(
ParquetFileWriter::open_packed(schema, Some(limits.writer), packed),
path,
)
}
ManagedParquetDestination::Object { store, path } => (
ParquetFileWriter::open(schema, store, &path, 1, None).await,
path,
Some(
crate::statement::export_logical_tables::LogicalTableExportLimits::default().writer,
),
packed,
)
} else {
ParquetFileWriter::open(output_schema.arrow_schema().clone(), store, path, 1, None).await
}
.context(error::WriteStreamToFileSnafu { path })?;
),
};
let path = path.as_str();
let mut writer = writer.context(error::WriteStreamToFileSnafu { path })?;
let mut started = false;
let result = async {
let mut rows = 0;
@@ -443,6 +486,100 @@ mod tests {
use super::*;
#[tokio::test]
async fn managed_packed_copy_uses_shared_backend_and_stream_error_label() {
use common_datasource::packed_writer::PackedWriter;
let directory = common_test_util::temp_dir::create_temp_dir("managed_packed_copy");
let location = url::Url::from_directory_path(directory.path()).unwrap();
let access = LocalFileAccess::sandboxed(directory.path()).unwrap();
let store = object_store::secure_fs::SecureFsRoot::open(directory.path())
.unwrap()
.build_operator();
let schema = Arc::new(Schema::new(vec![ColumnSchema::new(
"value",
ConcreteDataType::int32_datatype(),
false,
)]));
let output = |invalid_schema| {
let values: ArrayRef = if invalid_schema {
Arc::new(StringArray::from(vec!["a", "b", "c"]))
} else {
Arc::new(Int32Array::from(vec![1, 2, 3]))
};
let batch =
arrow::record_batch::RecordBatch::try_from_iter([("value", values)]).unwrap();
let stream = datafusion::physical_plan::stream::RecordBatchStreamAdapter::new(
schema.arrow_schema().clone(),
futures::stream::iter([Ok(batch)]),
);
let stream =
common_recordbatch::adapter::RecordBatchStreamAdapter::try_new(Box::pin(stream))
.unwrap();
Output::new_with_stream(Box::pin(stream))
};
let format = Format::Parquet(Default::default());
let connection = HashMap::new();
let budget = ExportWriteBudget::new(1);
let token = CancellationToken::new();
let result = StatementExecutor::copy_to_file_managed(
&access,
&format,
output(false),
location.as_str(),
&connection,
Some((&budget, &token)),
None,
)
.await;
assert!(matches!(
result,
Err(error::Error::BuildBackend {
source: common_datasource::error::Error::MissingObjectName { .. },
..
})
));
for (id, invalid_schema) in [(42, false), (43, true)] {
let shared = PackedWriter::new(store.clone()).unwrap();
let packed = PackedTableWriter::new(shared, "audit".into(), id, true);
let token = CancellationToken::new();
let result = StatementExecutor::copy_to_file_managed(
&access,
&format,
output(invalid_schema),
location.as_str(),
&connection,
Some((&budget, &token)),
Some(packed),
)
.await;
let path = format!("table-{id}.parquet");
if invalid_schema {
let error::Error::WriteStreamToFile {
path: actual,
source,
..
} = result.unwrap_err()
else {
panic!("expected stream write error");
};
assert_eq!(actual, path);
assert!(
matches!(source, common_datasource::error::Error::WriteParquet { path: actual, .. } if actual == path)
);
assert!(!store.exists(&path).await.unwrap());
} else {
assert_eq!(result.unwrap(), 3);
let reader = ParquetRecordBatchReaderBuilder::try_new(
store.read(&path).await.unwrap().to_bytes(),
)
.unwrap();
assert_eq!(reader.metadata().file_metadata().num_rows(), 3);
}
}
}
#[tokio::test]
async fn managed_copy_preserves_existing_file_before_sink_open() {
let temp_dir = common_test_util::temp_dir::create_temp_dir("managed_copy_existing_file");
@@ -30,7 +30,7 @@ use arrow::compute::{cast, take};
use arrow::datatypes::{DataType, SchemaRef};
use arrow::downcast_dictionary_array;
use arrow::record_batch::RecordBatch;
use common_datasource::object_store::build_backend_for_write;
use common_datasource::object_store::{LocalFileAccess, build_backend_for_write};
use common_datasource::packed_writer::{PackedTableWriter, PackedWriterRef};
use common_datasource::parquet_writer::{
ParquetCreationPolicy, ParquetFileWriter, ParquetWriterLimits,
@@ -352,13 +352,12 @@ impl StatementExecutor {
packed: Option<PackedWriterRef>,
) -> Result<LogicalTableExportSummary> {
limits.validate()?;
let (store, stream) = tokio::select! {
let (destination, stream) = tokio::select! {
biased;
_ = cancellation.cancelled() => return error::LogicalTableExportCancelledSnafu.fail(),
result = async {
unit.validate_table_routes(self.table_metadata_manager.table_route_manager()).await?;
let store = build_backend_for_write(&format!("{}/", directory.trim_end_matches('/')), connection, &self.local_file_access)
.await.context(error::BuildBackendSnafu)?;
let destination = LogicalExportDestination::new(directory, connection, &self.local_file_access, packed).await?;
let output = self.query_engine.execute(unit.build_plan(time_range)?, query_ctx)
.await.context(error::ExecLogicalPlanSnafu)?;
let stream = match output.data {
@@ -366,10 +365,37 @@ impl StatementExecutor {
OutputData::RecordBatches(batches) => batches.as_stream(),
_ => return error::UnexpectedSnafu { violated: "expected physical query rows" }.fail(),
};
Ok((store, stream))
Ok((destination, stream))
} => result?,
};
export_stream_managed(unit, stream, &store, limits, cancellation, budget, packed).await
export_stream_managed(unit, stream, destination, limits, cancellation, budget).await
}
}
/// Uses a per-unit backend for files or the request-owned packed destination.
pub(crate) enum LogicalExportDestination {
Object(ObjectStore),
Packed(PackedWriterRef),
}
impl LogicalExportDestination {
async fn new(
directory: &str,
connection: &HashMap<String, String>,
local_file_access: &LocalFileAccess,
packed: Option<PackedWriterRef>,
) -> Result<Self> {
if let Some(packed) = packed {
return Ok(Self::Packed(packed));
}
let store = build_backend_for_write(
&format!("{}/", directory.trim_end_matches('/')),
connection,
local_file_access,
)
.await
.context(error::BuildBackendSnafu)?;
Ok(Self::Object(store))
}
}
@@ -384,11 +410,10 @@ async fn export_stream(
export_stream_managed(
unit,
stream,
store,
LogicalExportDestination::Object(store.clone()),
limits,
&cancellation.child_token(),
ExportWriteBudget::new(1),
None,
)
.await
}
@@ -396,18 +421,16 @@ async fn export_stream(
async fn export_stream_managed(
unit: &LogicalTableExport,
stream: SendableRecordBatchStream,
store: &ObjectStore,
destination: LogicalExportDestination,
limits: LogicalTableExportLimits,
cancellation: &CancellationToken,
budget: Arc<ExportWriteBudget>,
packed: Option<PackedWriterRef>,
) -> Result<LogicalTableExportSummary> {
let mut writers = TableWriters::new(budget.clone());
writers.packed = packed;
let result = write_tables(
unit,
stream,
store,
&destination,
limits,
cancellation,
&mut writers,
@@ -433,7 +456,7 @@ fn check_cancelled(cancellation: &CancellationToken) -> Result<()> {
async fn write_tables(
unit: &LogicalTableExport,
mut stream: SendableRecordBatchStream,
store: &ObjectStore,
destination: &LogicalExportDestination,
limits: LogicalTableExportLimits,
cancellation: &CancellationToken,
writers: &mut TableWriters,
@@ -501,7 +524,9 @@ async fn write_tables(
check_cancelled(cancellation)?;
if let Some(file) = unit.logical_tables.get(&id) {
if writers.table_id().is_none() {
writers.open(id, file, store, limits, cancellation).await?;
writers
.open(id, file, destination, limits, cancellation)
.await?;
written.insert(id);
summary.files += 1;
}
@@ -536,7 +561,9 @@ async fn write_tables(
for (&id, file) in &unit.logical_tables {
if !written.contains(&id) {
check_cancelled(cancellation)?;
writers.open(id, file, store, limits, cancellation).await?;
writers
.open(id, file, destination, limits, cancellation)
.await?;
writers.close_input();
summary.files += 1;
}
@@ -554,20 +581,14 @@ impl ActiveWriter {
fn open_packed(
table: &LogicalTableProjection,
id: u32,
store: &ObjectStore,
limits: LogicalTableExportLimits,
shared: PackedWriterRef,
) -> Result<Self> {
let path = format!("table-{id}.parquet");
let packed = PackedTableWriter::new(shared, table.name.clone(), id, false);
let writer = ParquetFileWriter::open_packed(
table.schema.clone(),
store.clone(),
&path,
Some(limits.writer),
packed,
)
.map_err(|e| map_writer_error(e, &path))?;
let path = packed.path().to_owned();
let writer =
ParquetFileWriter::open_packed(table.schema.clone(), Some(limits.writer), packed)
.map_err(|e| map_writer_error(e, &path))?;
Ok(Self { path, writer })
}
@@ -309,6 +309,57 @@ async fn narrow_batches_share_row_groups() {
assert_eq!(rows, summary.rows);
}
#[tokio::test]
async fn packed_destination_reuses_backend_with_local_access_disabled() {
use common_datasource::packed_snapshot::{PACK_INDEX_FILE, PackIndex};
use common_datasource::packed_writer::PackedWriter;
let directory = common_test_util::temp_dir::create_temp_dir("packed_metric_destination");
let location = url::Url::from_directory_path(directory.path()).unwrap();
let store = object_store::secure_fs::SecureFsRoot::open(directory.path())
.unwrap()
.build_operator();
let connection = HashMap::new();
let access = LocalFileAccess::Disabled;
let result = LogicalExportDestination::new(location.as_str(), &connection, &access, None).await;
assert!(matches!(
result,
Err(error::Error::BuildBackend {
source: common_datasource::error::Error::LocalFileAccessDisabled { .. },
..
})
));
let packed = PackedWriter::new(store.clone()).unwrap();
let destination = LogicalExportDestination::new(
location.as_str(),
&connection,
&access,
Some(packed.clone()),
)
.await
.unwrap();
let token = CancellationToken::new();
let summary = export_stream_managed(
&unit(),
stream(vec![batch(vec![Some(1025)], vec![Some("a")])]),
destination,
export_limits(),
&token,
ExportWriteBudget::new(1),
)
.await
.unwrap();
assert_eq!(summary.rows, 1);
assert_eq!(summary.files, 3);
packed.lock().await.finish(&token).await.unwrap();
let index: PackIndex =
serde_json::from_slice(&store.read(PACK_INDEX_FILE).await.unwrap().to_bytes()).unwrap();
index
.validate_membership(["cpu.v1", "empty", "requests"])
.unwrap();
}
#[tokio::test]
async fn routes_across_batches_and_writes_empty_files() {
let unit = unit();
@@ -324,11 +375,10 @@ async fn routes_across_batches_and_writes_empty_files() {
let result = export_stream_managed(
&unit,
stream(batches),
&store,
LogicalExportDestination::Object(store.clone()),
export_limits(),
&CancellationToken::new(),
budget.clone(),
None,
)
.await
.unwrap();
@@ -619,11 +669,13 @@ async fn supported_metric_types_parquet_roundtrip() {
let summary = export_stream_managed(
&unit,
stream(vec![input.clone()]),
&store,
match &writer {
Some(writer) => LogicalExportDestination::Packed(writer.clone()),
None => LogicalExportDestination::Object(store.clone()),
},
export_limits(),
&CancellationToken::new(),
ExportWriteBudget::new(1),
writer.clone(),
)
.await
.unwrap();
@@ -803,11 +855,13 @@ async fn cancellation_drains_storage_and_preserves_committed_files() {
let export = export_stream_managed(
&unit,
stream(vec![input]),
&store,
match &packed {
Some(packed) => LogicalExportDestination::Packed(packed.clone()),
None => LogicalExportDestination::Object(store.clone()),
},
limits,
&cancellation,
budget.clone(),
packed.clone(),
);
tokio::pin!(export);
tokio::select! {
@@ -1128,20 +1182,18 @@ async fn groups_and_ordinary_files_share_writer_admission_and_drain() {
export_stream_managed(
&a,
rows(),
&store,
LogicalExportDestination::Object(store.clone()),
export_limits(),
&token,
budget.clone(),
None,
),
export_stream_managed(
&b,
rows(),
&store,
LogicalExportDestination::Object(store.clone()),
export_limits(),
&token,
budget.clone(),
None,
),
ordinary,
)
@@ -1237,7 +1289,13 @@ async fn completed_table_workers_are_reaped_during_admission() {
for id in 0..64 {
file.output.path = format!("empty-{id}.parquet");
writers
.open(id, file, &store, export_limits(), &token)
.open(
id,
file,
&LogicalExportDestination::Object(store.clone()),
export_limits(),
&token,
)
.await
.unwrap();
assert!(writers.pending_tasks() <= parallelism + 1);
@@ -15,10 +15,8 @@
use std::sync::Arc;
use arrow::record_batch::RecordBatch;
use common_datasource::packed_writer::PackedWriterRef;
use futures::stream::FuturesUnordered;
use futures::{FutureExt, StreamExt};
use object_store::ObjectStore;
use snafu::{OptionExt, ResultExt, ensure};
use tokio::sync::{OwnedSemaphorePermit, Semaphore, mpsc};
use tokio::task::JoinHandle;
@@ -26,8 +24,8 @@ use tokio_util::sync::CancellationToken;
use crate::error::{self, Result};
use crate::statement::export_logical_tables::{
ActiveWriter, LogicalTableExportLimits, LogicalTableProjection, check_cancelled,
map_writer_error,
ActiveWriter, LogicalExportDestination, LogicalTableExportLimits, LogicalTableProjection,
check_cancelled, map_writer_error,
};
const PAYLOAD_BYTES: usize = 64 * 1024 * 1024;
@@ -112,7 +110,6 @@ pub(crate) struct Payload {
}
pub(crate) struct TableWriters {
pub(crate) packed: Option<PackedWriterRef>,
current: Option<(u32, mpsc::Sender<Payload>)>,
tasks: FuturesUnordered<JoinHandle<Result<()>>>,
budget: Arc<ExportWriteBudget>,
@@ -122,7 +119,6 @@ impl TableWriters {
pub(crate) fn new(budget: Arc<ExportWriteBudget>) -> Self {
Self {
current: None,
packed: None,
tasks: FuturesUnordered::new(),
budget,
}
@@ -145,7 +141,7 @@ impl TableWriters {
&mut self,
id: u32,
table: &LogicalTableProjection,
store: &ObjectStore,
destination: &LogicalExportDestination,
limits: LogicalTableExportLimits,
token: &CancellationToken,
) -> Result<()> {
@@ -153,10 +149,13 @@ impl TableWriters {
self.close_input();
let permit = self.budget.writer(token).await?;
self.reap_for_admission(token).await?;
let writer = if let Some(packed) = &self.packed {
ActiveWriter::open_packed(table, id, store, limits, packed.clone())?
} else {
ActiveWriter::open(table, store, limits).await?
let writer = match destination {
LogicalExportDestination::Packed(packed) => {
ActiveWriter::open_packed(table, id, limits, packed.clone())?
}
LogicalExportDestination::Object(store) => {
ActiveWriter::open(table, store, limits).await?
}
};
let (sender, receiver) = mpsc::channel(2);
self.current = Some((id, sender));