1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
// Copyright Materialize, Inc. and contributors. All rights reserved.
//
// Use of this software is governed by the Business Source License
// included in the LICENSE file.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0.

//! Apache Arrow encodings and utils for persist data

use std::collections::HashMap;
use std::io::{Read, Seek, Write};
use std::sync::Arc;

use arrow2::array::{BinaryArray, PrimitiveArray};
use arrow2::datatypes::{DataType, Field, Schema};
use arrow2::io::ipc::read::{read_file_metadata, FileMetadata, FileReader};
use arrow2::io::ipc::write::{FileWriter, WriteOptions};
use arrow2::record_batch::RecordBatch;
use differential_dataflow::trace::Description;
use lazy_static::lazy_static;
use timely::progress::{Antichain, Timestamp};

use crate::error::Error;
use crate::gen::persist::ProtoBatchFormat;
use crate::indexed::columnar::ColumnarRecords;
use crate::indexed::encoding::{
    decode_trace_inline_meta, decode_unsealed_inline_meta, encode_trace_inline_meta,
    encode_unsealed_inline_meta, BlobTraceBatch, BlobUnsealedBatch,
};
use crate::storage::SeqNo;

lazy_static! {
    /// The Arrow schema we use to encode ((K, V), T, D) tuples.
    pub static ref SCHEMA_ARROW_KVTD: Arc<Schema> = Arc::new(Schema::new(vec![
        Field {
            name: "k".into(),
            data_type: DataType::Binary,
            nullable: false,
            dict_id: 0,
            dict_is_ordered: false,
            metadata: None,
        },
        Field {
            name: "v".into(),
            data_type: DataType::Binary,
            nullable: false,
            dict_id: 0,
            dict_is_ordered: false,
            metadata: None,
        },
        Field {
            name: "t".into(),
            data_type: DataType::UInt64,
            nullable: false,
            dict_id: 0,
            dict_is_ordered: false,
            metadata: None,
        },
        Field {
            name: "d".into(),
            data_type: DataType::Int64,
            nullable: false,
            dict_id: 0,
            dict_is_ordered: false,
            metadata: None,
        },
    ]));
}

const INLINE_METADATA_KEY: &'static str = "MZ:inline";

/// Encodes an BlobUnsealedBatch into the Arrow file format.
///
/// NB: This is currently unused, but it's here because we may want to use it
/// for the local cache and so we can easily compare arrow vs parquet.
pub fn encode_unsealed_arrow<W: Write>(w: &mut W, batch: &BlobUnsealedBatch) -> Result<(), Error> {
    let mut metadata = HashMap::with_capacity(1);
    metadata.insert(
        INLINE_METADATA_KEY.into(),
        encode_unsealed_inline_meta(batch, ProtoBatchFormat::ArrowKvtd),
    );
    let schema = Schema::new_from(SCHEMA_ARROW_KVTD.fields().clone(), metadata);
    let options = WriteOptions { compression: None };
    let mut writer = FileWriter::try_new(w, &schema, options)?;
    for records in batch.updates.iter() {
        writer.write(&encode_arrow_batch_kvtd(records))?;
    }
    writer.finish()?;
    Ok(())
}

/// Encodes an BlobTraceBatch into the Arrow file format.
///
/// NB: This is currently unused, but it's here because we may want to use it
/// for the local cache and so we can easily compare arrow vs parquet.
pub fn encode_trace_arrow<W: Write>(w: &mut W, batch: &BlobTraceBatch) -> Result<(), Error> {
    let mut metadata = HashMap::with_capacity(1);
    metadata.insert(
        INLINE_METADATA_KEY.into(),
        encode_trace_inline_meta(batch, ProtoBatchFormat::ArrowKvtd),
    );
    let schema = Schema::new_from(SCHEMA_ARROW_KVTD.fields().clone(), metadata);
    let options = WriteOptions { compression: None };
    let mut writer = FileWriter::try_new(w, &schema, options)?;
    for records in batch.updates.iter() {
        writer.write(&encode_arrow_batch_kvtd(&records))?;
    }
    writer.finish()?;
    Ok(())
}

/// Decodes a BlobUnsealedBatch from the Arrow file format.
///
/// NB: This is currently unused, but it's here because we may want to use it
/// for the local cache and so we can easily compare arrow vs parquet.
pub fn decode_unsealed_arrow<R: Read + Seek>(r: &mut R) -> Result<BlobUnsealedBatch, Error> {
    let file_meta = read_file_metadata(r)?;
    let (format, meta) =
        decode_unsealed_inline_meta(file_meta.schema().metadata().get(INLINE_METADATA_KEY))?;

    let updates = match format {
        ProtoBatchFormat::Unknown => return Err("unknown format".into()),
        ProtoBatchFormat::ArrowKvtd => decode_arrow_file_kvtd(r, file_meta)?,
        ProtoBatchFormat::ParquetKvtd => {
            return Err("ParquetKvtd format not supported in arrow".into())
        }
    };

    let ret = BlobUnsealedBatch {
        desc: SeqNo(meta.seqno_lower)..SeqNo(meta.seqno_upper),
        updates,
    };
    ret.validate()?;
    Ok(ret)
}

/// Decodes a BlobTraceBatch from the Arrow file format.
///
/// NB: This is currently unused, but it's here because we may want to use it
/// for the local cache and so we can easily compare arrow vs parquet.
pub fn decode_trace_arrow<R: Read + Seek>(r: &mut R) -> Result<BlobTraceBatch, Error> {
    let file_meta = read_file_metadata(r)?;
    let (format, meta) =
        decode_trace_inline_meta(file_meta.schema().metadata().get(INLINE_METADATA_KEY))?;

    let updates = match format {
        ProtoBatchFormat::Unknown => return Err("unknown format".into()),
        ProtoBatchFormat::ArrowKvtd => decode_arrow_file_kvtd(r, file_meta)?,
        ProtoBatchFormat::ParquetKvtd => {
            return Err("ParquetKvtd format not supported in arrow".into())
        }
    };

    let ret = BlobTraceBatch {
        desc: meta.desc.map_or_else(
            || {
                Description::new(
                    Antichain::from_elem(u64::minimum()),
                    Antichain::from_elem(u64::minimum()),
                    Antichain::from_elem(u64::minimum()),
                )
            },
            |x| x.into(),
        ),
        updates,
    };
    ret.validate()?;
    Ok(ret)
}

fn decode_arrow_file_kvtd<R: Read + Seek>(
    r: &mut R,
    file_meta: FileMetadata,
) -> Result<Vec<ColumnarRecords>, Error> {
    let projection = None;
    let file_reader = FileReader::new(r, file_meta, projection);

    let file_schema = file_reader.schema().fields().as_slice();
    // We're not trying to accept any sort of user created data, so be strict.
    if file_schema != SCHEMA_ARROW_KVTD.fields() {
        return Err(format!(
            "expected arrow schema {:?} got: {:?}",
            SCHEMA_ARROW_KVTD.fields(),
            file_schema
        )
        .into());
    }

    let mut ret = Vec::new();
    for batch in file_reader {
        ret.push(decode_arrow_batch_kvtd(&batch?)?);
    }
    Ok(ret)
}

/// Converts a ColumnarRecords into an arrow [(K, V, T, D)] RecordBatch.
pub fn encode_arrow_batch_kvtd(x: &ColumnarRecords) -> RecordBatch {
    RecordBatch::try_new(
        SCHEMA_ARROW_KVTD.clone(),
        vec![
            Arc::new(BinaryArray::from_data(
                DataType::Binary,
                x.key_offsets.clone(),
                x.key_data.clone(),
                None,
            )),
            Arc::new(BinaryArray::from_data(
                DataType::Binary,
                x.val_offsets.clone(),
                x.val_data.clone(),
                None,
            )),
            Arc::new(PrimitiveArray::from_data(
                DataType::UInt64,
                x.timestamps.clone(),
                None,
            )),
            Arc::new(PrimitiveArray::from_data(
                DataType::Int64,
                x.diffs.clone(),
                None,
            )),
        ],
    )
    .expect("schema matches fields")
}

/// Converts an arrow [(K, V, T, D)] RecordBatch into a ColumnarRecords.
pub fn decode_arrow_batch_kvtd(x: &RecordBatch) -> Result<ColumnarRecords, String> {
    // We're not trying to accept any sort of user created data, so be strict.
    if x.schema().fields() != SCHEMA_ARROW_KVTD.fields() {
        return Err(format!(
            "expected arrow schema {:?} got: {:?}",
            SCHEMA_ARROW_KVTD.fields(),
            x.schema()
        ));
    }

    let columns = x.columns();
    if columns.len() != 4 {
        return Err(format!("expected 4 fields got {}", columns.len()));
    }
    let key_col = x.column(0);
    let val_col = x.column(1);
    let ts_col = x.column(2);
    let diff_col = x.column(3);

    let key_array = key_col
        .as_any()
        .downcast_ref::<BinaryArray<i32>>()
        .ok_or(format!("column 0 doesn't match schema"))?
        .clone();
    let key_offsets = key_array.offsets().clone();
    let key_data = key_array.values().clone();
    let val_array = val_col
        .as_any()
        .downcast_ref::<BinaryArray<i32>>()
        .ok_or(format!("column 1 doesn't match schema"))?
        .clone();
    let val_offsets = val_array.offsets().clone();
    let val_data = val_array.values().clone();
    let timestamps = ts_col
        .as_any()
        .downcast_ref::<PrimitiveArray<u64>>()
        .ok_or(format!("column 2 doesn't match schema"))?
        .values()
        .clone();
    let diffs = diff_col
        .as_any()
        .downcast_ref::<PrimitiveArray<i64>>()
        .ok_or(format!("column 3 doesn't match schema"))?
        .values()
        .clone();

    let len = x.num_rows();
    let ret = ColumnarRecords {
        len,
        key_data,
        key_offsets,
        val_data,
        val_offsets,
        timestamps,
        diffs,
    };
    ret.borrow().validate()?;
    Ok(ret)
}