parquet 0.5.0 → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,486 @@
1
+ use super::{
2
+ build_column_collectors_from_dsl, copy_temp_file_to_io_like, create_writer,
3
+ parse_parquet_write_args, DEFAULT_MEMORY_THRESHOLD, INITIAL_BATCH_SIZE, MIN_BATCH_SIZE,
4
+ SAMPLE_SIZE,
5
+ };
6
+ use crate::{
7
+ logger::RubyLogger,
8
+ types::{
9
+ schema_node::build_arrow_schema, ColumnCollector, ParquetGemError, ParquetSchemaType,
10
+ PrimitiveType, WriterOutput,
11
+ },
12
+ IoLikeValue, ParquetWriteArgs,
13
+ };
14
+ use arrow_array::{Array, RecordBatch};
15
+ use magnus::{
16
+ value::ReprValue, Error as MagnusError, RArray, RHash, Ruby, Symbol, TryConvert, Value,
17
+ };
18
+ use rand::Rng;
19
+ use std::sync::Arc;
20
+
21
+ const MIN_SAMPLES_FOR_ESTIMATE: usize = 10;
22
+
23
+ #[inline]
24
+ pub fn write_rows(args: &[Value]) -> Result<(), MagnusError> {
25
+ let ruby = unsafe { Ruby::get_unchecked() };
26
+ write_rows_impl(Arc::new(ruby), args).map_err(|e| {
27
+ let z: MagnusError = e.into();
28
+ z
29
+ })?;
30
+ Ok(())
31
+ }
32
+
33
+ #[inline]
34
+ fn write_rows_impl(ruby: Arc<Ruby>, args: &[Value]) -> Result<(), ParquetGemError> {
35
+ let ParquetWriteArgs {
36
+ read_from,
37
+ write_to,
38
+ schema,
39
+ batch_size: user_batch_size,
40
+ compression,
41
+ flush_threshold,
42
+ sample_size: user_sample_size,
43
+ logger,
44
+ } = parse_parquet_write_args(&ruby, args)?;
45
+
46
+ let logger = RubyLogger::new(&ruby, logger)?;
47
+ let flush_threshold = flush_threshold.unwrap_or(DEFAULT_MEMORY_THRESHOLD);
48
+
49
+ // Get the Arrow schema from the SchemaNode (we only have DSL schema now, since legacy is converted)
50
+ let arrow_schema = build_arrow_schema(&schema, &logger).map_err(|e| {
51
+ MagnusError::new(
52
+ magnus::exception::runtime_error(),
53
+ format!("Failed to build Arrow schema from DSL schema: {}", e),
54
+ )
55
+ })?;
56
+
57
+ // Create the writer
58
+ let mut writer = create_writer(&ruby, &write_to, arrow_schema.clone(), compression)?;
59
+
60
+ if read_from.is_kind_of(ruby.class_enumerator()) {
61
+ // Build column collectors - we only have DSL schema now
62
+ let mut column_collectors =
63
+ build_column_collectors_from_dsl(&ruby, &arrow_schema, &schema)?;
64
+
65
+ let mut rows_in_batch = 0;
66
+ let mut total_rows = 0;
67
+ let mut rng = rand::rng();
68
+ let sample_size = user_sample_size.unwrap_or(SAMPLE_SIZE);
69
+ let mut size_samples = Vec::with_capacity(sample_size);
70
+ let mut current_batch_size = user_batch_size.unwrap_or(INITIAL_BATCH_SIZE);
71
+
72
+ loop {
73
+ match read_from.funcall::<_, _, Value>("next", ()) {
74
+ Ok(row) => {
75
+ // Process the row
76
+ process_row(&ruby, row, &mut column_collectors)?;
77
+
78
+ // Update row sampling for dynamic batch sizing
79
+ if size_samples.len() < sample_size {
80
+ // estimate row size
81
+ let row_array = RArray::from_value(row).ok_or_else(|| {
82
+ MagnusError::new(ruby.exception_type_error(), "Row must be an array")
83
+ })?;
84
+ let row_size = estimate_single_row_size(&row_array, &column_collectors)?;
85
+ size_samples.push(row_size);
86
+ } else if rng.random_range(0..=total_rows) < sample_size as usize {
87
+ let idx = rng.random_range(0..sample_size as usize);
88
+ let row_array = RArray::from_value(row).ok_or_else(|| {
89
+ MagnusError::new(ruby.exception_type_error(), "Row must be an array")
90
+ })?;
91
+ let row_size = estimate_single_row_size(&row_array, &column_collectors)?;
92
+ size_samples[idx] = row_size;
93
+ }
94
+
95
+ rows_in_batch += 1;
96
+ total_rows += 1;
97
+
98
+ // Calculate batch size progressively once we have minimum samples
99
+ if user_batch_size.is_none() && size_samples.len() >= MIN_SAMPLES_FOR_ESTIMATE {
100
+ current_batch_size =
101
+ update_batch_size(&size_samples, flush_threshold, MIN_BATCH_SIZE);
102
+ }
103
+
104
+ // When we reach batch size, write the batch
105
+ if rows_in_batch >= current_batch_size {
106
+ write_batch(&mut writer, &mut column_collectors, flush_threshold)?;
107
+ rows_in_batch = 0;
108
+ }
109
+ }
110
+ Err(e) => {
111
+ if e.is_kind_of(ruby.exception_stop_iteration()) {
112
+ // Write any remaining rows
113
+ if rows_in_batch > 0 {
114
+ write_batch(&mut writer, &mut column_collectors, flush_threshold)?;
115
+ }
116
+ break;
117
+ }
118
+ return Err(e)?;
119
+ }
120
+ }
121
+ }
122
+ } else {
123
+ return Err(MagnusError::new(
124
+ magnus::exception::type_error(),
125
+ "read_from must be an Enumerator".to_string(),
126
+ ))?;
127
+ }
128
+
129
+ // Ensure everything is written and get the temp file if it exists
130
+ if let Some(temp_file) = writer.close()? {
131
+ // If we got a temp file back, we need to copy its contents to the IO-like object
132
+ copy_temp_file_to_io_like(temp_file, IoLikeValue(write_to))?;
133
+ }
134
+
135
+ Ok(())
136
+ }
137
+
138
+ // Processes a single data row and adds values to the corresponding column collectors
139
+ // This function is called for each row of input data when writing in row-wise mode.
140
+ // It performs important validation to ensure the row structure matches the schema:
141
+ // - Verifies that the number of columns in the row matches the schema
142
+ // - Distributes each value to the appropriate ColumnCollector
143
+ //
144
+ // Each ColumnCollector handles type conversion and accumulation for its specific column,
145
+ // allowing this function to focus on row-level validation and distribution.
146
+ fn process_row(
147
+ ruby: &Ruby,
148
+ row: Value,
149
+ column_collectors: &mut [ColumnCollector],
150
+ ) -> Result<(), MagnusError> {
151
+ let row_array = RArray::from_value(row)
152
+ .ok_or_else(|| MagnusError::new(ruby.exception_type_error(), "Row must be an array"))?;
153
+
154
+ // Validate row length matches schema
155
+ if row_array.len() != column_collectors.len() {
156
+ return Err(MagnusError::new(
157
+ magnus::exception::runtime_error(),
158
+ format!(
159
+ "Row length ({}) does not match schema length ({}). Schema expects columns: {:?}",
160
+ row_array.len(),
161
+ column_collectors.len(),
162
+ column_collectors
163
+ .iter()
164
+ .map(|c| c.name.as_str())
165
+ .collect::<Vec<_>>()
166
+ ),
167
+ ));
168
+ }
169
+
170
+ // Process each value in the row
171
+ for (collector, value) in column_collectors.iter_mut().zip(row_array) {
172
+ collector.push_value(value)?;
173
+ }
174
+
175
+ Ok(())
176
+ }
177
+
178
+ // Converts all accumulated data from ColumnCollectors into an Arrow RecordBatch
179
+ // and writes it to the Parquet file/output. This is a crucial function that bridges
180
+ // between our Ruby-oriented data collectors and the Arrow/Parquet ecosystem.
181
+ //
182
+ // The function:
183
+ // 1. Takes all collected values from each ColumnCollector and converts them to Arrow arrays
184
+ // 2. Creates a RecordBatch from these arrays (column-oriented data format)
185
+ // 3. Writes the batch to the ParquetWriter
186
+ // 4. Flushes the writer if the accumulated memory exceeds the threshold
187
+ //
188
+ // This approach enables efficient batch-wise writing while controlling memory usage.
189
+ fn write_batch(
190
+ writer: &mut WriterOutput,
191
+ collectors: &mut [ColumnCollector],
192
+ flush_threshold: usize,
193
+ ) -> Result<(), ParquetGemError> {
194
+ // Convert columns to Arrow arrays
195
+ let arrow_arrays: Vec<(String, Arc<dyn Array>)> = collectors
196
+ .iter_mut()
197
+ .map(|c| {
198
+ let arr = c.take_array()?;
199
+ Ok((c.name.clone(), arr))
200
+ })
201
+ .collect::<Result<_, ParquetGemError>>()?;
202
+
203
+ let record_batch = RecordBatch::try_from_iter(arrow_arrays.clone()).map_err(|e| {
204
+ MagnusError::new(
205
+ magnus::exception::runtime_error(),
206
+ format!("Failed to create RecordBatch: {}", e),
207
+ )
208
+ })?;
209
+
210
+ writer.write(&record_batch)?;
211
+
212
+ // Check if we need to flush based on memory usage thresholds
213
+ match writer {
214
+ WriterOutput::File(w) | WriterOutput::TempFile(w, _) => {
215
+ if w.in_progress_size() >= flush_threshold || w.memory_size() >= flush_threshold {
216
+ w.flush()?;
217
+ }
218
+ }
219
+ }
220
+ Ok(())
221
+ }
222
+
223
+ // Estimates the memory size of a single row by examining each value
224
+ // This is used for dynamic batch sizing to optimize memory usage during writes
225
+ // by adapting batch sizes based on the actual data being processed.
226
+ pub fn estimate_single_row_size(
227
+ row_array: &RArray,
228
+ collectors: &[ColumnCollector],
229
+ ) -> Result<usize, MagnusError> {
230
+ let mut size = 0;
231
+ for (idx, val) in row_array.into_iter().enumerate() {
232
+ let col_type = &collectors[idx].type_;
233
+ // Calculate size based on the type-specific estimation
234
+ size += estimate_value_size(val, col_type)?;
235
+ }
236
+ Ok(size)
237
+ }
238
+
239
+ // Estimates the memory footprint of a single value based on its schema type
240
+ // This provides type-specific size estimates that help with dynamic batch sizing
241
+ // For complex types like lists, maps, and structs, we use reasonable approximations
242
+ pub fn estimate_value_size(
243
+ value: Value,
244
+ schema_type: &ParquetSchemaType,
245
+ ) -> Result<usize, MagnusError> {
246
+ use ParquetSchemaType as PST;
247
+ if value.is_nil() {
248
+ return Ok(0); // nil => minimal
249
+ }
250
+ match schema_type {
251
+ PST::Primitive(PrimitiveType::Int8) | PST::Primitive(PrimitiveType::UInt8) => Ok(1),
252
+ PST::Primitive(PrimitiveType::Int16) | PST::Primitive(PrimitiveType::UInt16) => Ok(2),
253
+ PST::Primitive(PrimitiveType::Int32)
254
+ | PST::Primitive(PrimitiveType::UInt32)
255
+ | PST::Primitive(PrimitiveType::Float32) => Ok(4),
256
+ PST::Primitive(PrimitiveType::Int64)
257
+ | PST::Primitive(PrimitiveType::UInt64)
258
+ | PST::Primitive(PrimitiveType::Float64) => Ok(8),
259
+ PST::Primitive(PrimitiveType::Boolean) => Ok(1),
260
+ PST::Primitive(PrimitiveType::Date32)
261
+ | PST::Primitive(PrimitiveType::TimestampMillis)
262
+ | PST::Primitive(PrimitiveType::TimestampMicros) => Ok(8),
263
+ PST::Primitive(PrimitiveType::String) | PST::Primitive(PrimitiveType::Binary) => {
264
+ if let Ok(s) = String::try_convert(value) {
265
+ // Account for string length plus Rust String's capacity+pointer overhead
266
+ Ok(s.len() + std::mem::size_of::<usize>() * 3)
267
+ } else {
268
+ // Try to convert the value to a string using to_s for non-string types
269
+ // This handles numeric values that will be converted to strings later
270
+ match value.funcall::<_, _, Value>("to_s", ()) {
271
+ Ok(str_val) => {
272
+ if let Ok(s) = String::try_convert(str_val) {
273
+ Ok(s.len() + std::mem::size_of::<usize>() * 3)
274
+ } else {
275
+ // If to_s conversion fails, just use a reasonable default
276
+ Ok(8) // Reasonable size estimate for small values
277
+ }
278
+ }
279
+ Err(_) => {
280
+ // If to_s method fails, use a default size
281
+ Ok(8) // Reasonable size estimate for small values
282
+ }
283
+ }
284
+ }
285
+ }
286
+ PST::List(item_type) => {
287
+ if let Ok(arr) = RArray::try_convert(value) {
288
+ let len = arr.len();
289
+
290
+ // Base overhead for the array structure (pointer, length, capacity)
291
+ let base_size = std::mem::size_of::<usize>() * 3;
292
+
293
+ // If empty, just return the base size
294
+ if len == 0 {
295
+ return Ok(base_size);
296
+ }
297
+
298
+ // Sample up to 5 elements to get average element size
299
+ let sample_count = std::cmp::min(len, 5);
300
+ let mut total_sample_size = 0;
301
+
302
+ for i in 0..sample_count {
303
+ let element = arr.entry(i as isize)?;
304
+ let element_size = estimate_value_size(element, &item_type.item_type)?;
305
+ total_sample_size += element_size;
306
+ }
307
+
308
+ // If we couldn't sample any elements properly, that's an error
309
+ if sample_count > 0 && total_sample_size == 0 {
310
+ return Err(MagnusError::new(
311
+ magnus::exception::runtime_error(),
312
+ "Failed to estimate size of list elements",
313
+ ));
314
+ }
315
+
316
+ // Calculate average element size from samples
317
+ let avg_element_size = if sample_count > 0 {
318
+ total_sample_size as f64 / sample_count as f64
319
+ } else {
320
+ return Err(MagnusError::new(
321
+ magnus::exception::runtime_error(),
322
+ "Failed to sample list elements for size estimation",
323
+ ));
324
+ };
325
+
326
+ // Estimate total size based on average element size * length + base overhead
327
+ Ok(base_size + (avg_element_size as usize * len))
328
+ } else {
329
+ // Instead of assuming it's a small list, return an error
330
+ Err(MagnusError::new(
331
+ magnus::exception::runtime_error(),
332
+ format!("Expected array for List type but got: {:?}", value),
333
+ ))
334
+ }
335
+ }
336
+ PST::Map(map_field) => {
337
+ if let Ok(hash) = RHash::try_convert(value) {
338
+ let size_estimate = hash.funcall::<_, _, usize>("size", ())?;
339
+
340
+ // Base overhead for the hash structure
341
+ let base_size = std::mem::size_of::<usize>() * 4;
342
+
343
+ // If empty, just return the base size
344
+ if size_estimate == 0 {
345
+ return Ok(base_size);
346
+ }
347
+
348
+ // Sample up to 5 key-value pairs to estimate average sizes
349
+ let mut key_sample_size = 0;
350
+ let mut value_sample_size = 0;
351
+ let mut sample_count = 0;
352
+
353
+ // Get an enumerator for the hash
354
+ let enumerator = hash.funcall::<_, _, Value>("to_enum", ())?;
355
+
356
+ // Sample up to 5 entries
357
+ for _ in 0..std::cmp::min(size_estimate, 5) {
358
+ match enumerator.funcall::<_, _, Value>("next", ()) {
359
+ Ok(pair) => {
360
+ if let Ok(pair_array) = RArray::try_convert(pair) {
361
+ if pair_array.len() == 2 {
362
+ let key = pair_array.entry(0)?;
363
+ let val = pair_array.entry(1)?;
364
+
365
+ key_sample_size +=
366
+ estimate_value_size(key, &map_field.key_type)?;
367
+ value_sample_size +=
368
+ estimate_value_size(val, &map_field.value_type)?;
369
+ sample_count += 1;
370
+ }
371
+ }
372
+ }
373
+ Err(_) => break, // Stop if we reach the end
374
+ }
375
+ }
376
+
377
+ // If we couldn't sample any pairs, return an error
378
+ if size_estimate > 0 && sample_count == 0 {
379
+ return Err(MagnusError::new(
380
+ magnus::exception::runtime_error(),
381
+ "Failed to sample map entries for size estimation",
382
+ ));
383
+ }
384
+
385
+ // Calculate average key and value sizes
386
+ let (avg_key_size, avg_value_size) = if sample_count > 0 {
387
+ (
388
+ key_sample_size as f64 / sample_count as f64,
389
+ value_sample_size as f64 / sample_count as f64,
390
+ )
391
+ } else {
392
+ return Err(MagnusError::new(
393
+ magnus::exception::runtime_error(),
394
+ "Failed to sample hash key-value pairs for size estimation",
395
+ ));
396
+ };
397
+
398
+ // Each entry has overhead (node pointers, etc.) in a hash map
399
+ let entry_overhead = std::mem::size_of::<usize>() * 2;
400
+
401
+ // Estimate total size:
402
+ // base size + (key_size + value_size + entry_overhead) * count
403
+ Ok(base_size
404
+ + ((avg_key_size + avg_value_size + entry_overhead as f64) as usize
405
+ * size_estimate))
406
+ } else {
407
+ // Instead of assuming a small map, return an error
408
+ Err(MagnusError::new(
409
+ magnus::exception::runtime_error(),
410
+ format!("Expected hash for Map type but got: {:?}", value),
411
+ ))
412
+ }
413
+ }
414
+ PST::Struct(struct_field) => {
415
+ if let Ok(hash) = RHash::try_convert(value) {
416
+ // Base overhead for the struct
417
+ let base_size = std::mem::size_of::<usize>() * 3;
418
+
419
+ // Estimate size for each field
420
+ let mut total_fields_size = 0;
421
+
422
+ for field in &struct_field.fields {
423
+ // Try to get the field value from the hash
424
+ match hash.get(Symbol::new(&field.name)) {
425
+ Some(field_value) => {
426
+ total_fields_size += estimate_value_size(field_value, &field.type_)?;
427
+ }
428
+ None => {
429
+ if let Some(field_value) = hash.get(&*field.name) {
430
+ total_fields_size +=
431
+ estimate_value_size(field_value, &field.type_)?;
432
+ } else {
433
+ if field.nullable {
434
+ total_fields_size += 0;
435
+ } else {
436
+ return Err(MagnusError::new(
437
+ magnus::exception::runtime_error(),
438
+ format!("Missing field: {} in hash {:?}", field.name, hash),
439
+ ));
440
+ }
441
+ }
442
+ }
443
+ }
444
+ }
445
+
446
+ // We no longer error on missing fields during size estimation
447
+ Ok(base_size + total_fields_size)
448
+ } else {
449
+ // Instead of trying instance_variables or assuming a default, return an error
450
+ Err(MagnusError::new(
451
+ magnus::exception::runtime_error(),
452
+ format!("Expected hash for Struct type but got: {:?}", value),
453
+ ))
454
+ }
455
+ }
456
+ }
457
+ }
458
+
459
+ // Dynamically calculates an optimal batch size based on estimated row sizes
460
+ // and memory constraints. This function enables the writer to adapt to different
461
+ // data characteristics for optimal performance.
462
+ //
463
+ // The algorithm:
464
+ // 1. Requires a minimum number of samples to make a reliable estimate
465
+ // 2. Calculates the average row size from the samples
466
+ // 3. Determines a batch size that would consume approximately the target memory threshold
467
+ // 4. Ensures the batch size doesn't go below a minimum value for efficiency
468
+ //
469
+ // This approach balances memory usage with processing efficiency by targeting
470
+ // a specific memory footprint per batch.
471
+ fn update_batch_size(
472
+ size_samples: &[usize],
473
+ flush_threshold: usize,
474
+ min_batch_size: usize,
475
+ ) -> usize {
476
+ if size_samples.len() < MIN_SAMPLES_FOR_ESTIMATE {
477
+ return min_batch_size;
478
+ }
479
+
480
+ let total_size = size_samples.iter().sum::<usize>();
481
+ // Safe because we know we have at least MIN_SAMPLES_FOR_ESTIMATE samples
482
+ let avg_row_size = total_size as f64 / size_samples.len() as f64;
483
+ let avg_row_size = avg_row_size.max(1.0); // Ensure we don't divide by zero
484
+ let suggested_batch_size = (flush_threshold as f64 / avg_row_size).floor() as usize;
485
+ suggested_batch_size.max(min_batch_size)
486
+ }
@@ -1,3 +1,3 @@
1
1
  module Parquet
2
- VERSION = "0.5.0"
2
+ VERSION = "0.5.2"
3
3
  end
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: parquet
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.5.0
4
+ version: 0.5.2
5
5
  platform: ruby
6
6
  authors:
7
7
  - Nathan Jaremko
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2025-02-27 00:00:00.000000000 Z
11
+ date: 2025-03-17 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: rb_sys
@@ -77,6 +77,8 @@ files:
77
77
  - ext/parquet/src/types/writer_types.rs
78
78
  - ext/parquet/src/utils.rs
79
79
  - ext/parquet/src/writer/mod.rs
80
+ - ext/parquet/src/writer/write_columns.rs
81
+ - ext/parquet/src/writer/write_rows.rs
80
82
  - lib/parquet.rb
81
83
  - lib/parquet.rbi
82
84
  - lib/parquet/schema.rb