T-157: edits made in the worktree
This commit is contained in:
parent
15f53dba9e
commit
4f4ff8b4fb
5 changed files with 729 additions and 2 deletions
|
|
@ -494,7 +494,7 @@ fn sanitize_opt_f64(value: Option<f64>) -> Option<f64> {
|
|||
|
||||
const HEX_LOWER: &[u8; 16] = b"0123456789abcdef";
|
||||
|
||||
fn push_json_str(out: &mut String, s: &str) {
|
||||
pub(crate) fn push_json_str(out: &mut String, s: &str) {
|
||||
out.push('"');
|
||||
let bytes = s.as_bytes();
|
||||
let mut start = 0usize;
|
||||
|
|
@ -534,7 +534,7 @@ fn push_json_str(out: &mut String, s: &str) {
|
|||
}
|
||||
|
||||
#[inline]
|
||||
fn push_json_opt_str(out: &mut String, s: Option<&str>) {
|
||||
pub(crate) fn push_json_opt_str(out: &mut String, s: Option<&str>) {
|
||||
match s {
|
||||
Some(v) => push_json_str(out, v),
|
||||
None => out.push_str("null"),
|
||||
|
|
|
|||
|
|
@ -27,6 +27,7 @@ pub mod parquet_corporate_actions;
|
|||
pub mod parquet_events;
|
||||
pub mod parquet_fundamentals;
|
||||
pub mod parquet_fx;
|
||||
pub mod parquet_posts;
|
||||
mod parquet_publish;
|
||||
pub mod parquet_shorts;
|
||||
pub mod posts;
|
||||
|
|
@ -172,6 +173,10 @@ pub use parquet_fx::{
|
|||
fx_1d_parquet_schema, write_fx_1d_dataset, Fx1dParquetRow, Fx1dWriteOptions, Fx1dWriteStats,
|
||||
ParquetFxError,
|
||||
};
|
||||
pub use parquet_posts::{
|
||||
posts_to_event_rows, EVENT_KIND_POST, KNOWN_AT_SOURCE_POST_EDITED,
|
||||
KNOWN_AT_SOURCE_POST_TIMESTAMP, POST_SUBTYPE_NEWSWIRE, POST_SUBTYPE_RETAIL,
|
||||
};
|
||||
pub use parquet_shorts::{
|
||||
shorts_parquet_schema, write_shorts_dataset, ParquetShortsError, ShortsParquetRow,
|
||||
ShortsWriteOptions, ShortsWriteStats,
|
||||
|
|
@ -312,6 +317,8 @@ pub use run_mongo::{
|
|||
CurateEventsMongoArgs, CurateFx1dMongoArgs, CurateShortsMongoArgs, RunMongoCurateError,
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
mod parquet_posts_tests;
|
||||
#[cfg(test)]
|
||||
mod posts_tests;
|
||||
#[cfg(test)]
|
||||
|
|
|
|||
109
tools/curate-etl/src/parquet_posts.rs
Normal file
109
tools/curate-etl/src/parquet_posts.rs
Normal file
|
|
@ -0,0 +1,109 @@
|
|||
//! Adapter mapping curated `ceoPosts` rows ([`PostRow<i32>`] / [`PostsBuild<i32>`]) into the
|
||||
//! 7-column `events` Parquet contract ([`EventsParquetRow`], `events/year=YYYY/part.parquet`).
|
||||
//!
|
||||
//! Aligned with `design/DATA-CONTRACTS.md` §1 & §3A and `design/PLATFORM-PLAN.md`:
|
||||
//! - `kind` is always [`EVENT_KIND_POST`] (`"post"`).
|
||||
//! - `subtype` is [`POST_SUBTYPE_NEWSWIRE`] (`"newswire"`) when `is_bot` is `true`, and
|
||||
//! [`POST_SUBTYPE_RETAIL`] (`"retail"`) otherwise, so wire releases are never pooled with crowd
|
||||
//! chat.
|
||||
//! - `ts` is the posting timestamp (`posted_at`) and `known_at` is the point-in-time text
|
||||
//! availability timestamp (`known_at >= posted_at`).
|
||||
//! - `known_at_source` is [`KNOWN_AT_SOURCE_POST_EDITED`] (`"post_edited"`) iff
|
||||
//! `known_at > posted_at`, and [`KNOWN_AT_SOURCE_POST_TIMESTAMP`] (`"post_timestamp"`) otherwise
|
||||
//! (including when an edit timestamp before `posted_at` was clamped back to `posted_at`).
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
use crate::events::{push_json_opt_str, push_json_str};
|
||||
use crate::parquet_events::EventsParquetRow;
|
||||
use crate::posts::{PostRow, PostsBuild};
|
||||
|
||||
/// Canonical `events.kind` label for curated `ceoPosts` rows.
|
||||
pub const EVENT_KIND_POST: &str = "post";
|
||||
|
||||
/// Canonical `events.subtype` label for `bot == "1"` newswire posts.
|
||||
pub const POST_SUBTYPE_NEWSWIRE: &str = "newswire";
|
||||
|
||||
/// Canonical `events.subtype` label for non-bot retail posts.
|
||||
pub const POST_SUBTYPE_RETAIL: &str = "retail";
|
||||
|
||||
/// Provenance label when `known_at` equals the post's creation timestamp (`posted_at`).
|
||||
pub const KNOWN_AT_SOURCE_POST_TIMESTAMP: &str = "post_timestamp";
|
||||
|
||||
/// Provenance label when `known_at` reflects a post-creation edit timestamp (`known_at > posted_at`).
|
||||
pub const KNOWN_AT_SOURCE_POST_EDITED: &str = "post_edited";
|
||||
|
||||
/// Encodes a curated post's `payload_json` as a compact RFC 8259 JSON object with fixed key order:
|
||||
/// `{"spiel_id":...,"user_id":...,"is_edited":...,"source":...,"text":...}`.
|
||||
fn encode_post_payload_json(row: &PostRow<i32>) -> String {
|
||||
let cap = 72
|
||||
+ row.spiel_id.len()
|
||||
+ row.user_id.as_deref().map_or(4, str::len)
|
||||
+ row.source.len()
|
||||
+ row.text.len();
|
||||
let mut out = String::with_capacity(cap);
|
||||
out.push_str("{\"spiel_id\":");
|
||||
push_json_str(&mut out, &row.spiel_id);
|
||||
out.push_str(",\"user_id\":");
|
||||
push_json_opt_str(&mut out, row.user_id.as_deref());
|
||||
out.push_str(",\"is_edited\":");
|
||||
out.push_str(if row.is_edited { "true" } else { "false" });
|
||||
out.push_str(",\"source\":");
|
||||
push_json_str(&mut out, row.source);
|
||||
out.push_str(",\"text\":");
|
||||
push_json_str(&mut out, &row.text);
|
||||
out.push('}');
|
||||
out
|
||||
}
|
||||
|
||||
impl From<&PostRow<i32>> for EventsParquetRow {
|
||||
fn from(row: &PostRow<i32>) -> Self {
|
||||
let known_at_source = if row.known_at > row.posted_at {
|
||||
KNOWN_AT_SOURCE_POST_EDITED
|
||||
} else {
|
||||
KNOWN_AT_SOURCE_POST_TIMESTAMP
|
||||
};
|
||||
let subtype = if row.is_bot {
|
||||
POST_SUBTYPE_NEWSWIRE
|
||||
} else {
|
||||
POST_SUBTYPE_RETAIL
|
||||
};
|
||||
|
||||
Self {
|
||||
listing_id: row.key,
|
||||
ts_micros: row.posted_at,
|
||||
known_at_micros: row.known_at,
|
||||
known_at_source: Cow::Borrowed(known_at_source),
|
||||
kind: Cow::Borrowed(EVENT_KIND_POST),
|
||||
subtype: subtype.to_string(),
|
||||
payload_json: encode_post_payload_json(row),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<PostRow<i32>> for EventsParquetRow {
|
||||
fn from(row: PostRow<i32>) -> Self {
|
||||
Self::from(&row)
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts both `newswire` and `retail` streams of a [`PostsBuild<i32>`] into
|
||||
/// [`EventsParquetRow`] records sorted in the exact order required by
|
||||
/// [`crate::parquet_events::write_events_dataset`]:
|
||||
/// `(listing_id, ts_micros, kind, subtype, payload_json, known_at_micros, known_at_source)`.
|
||||
pub fn posts_to_event_rows(build: &PostsBuild<i32>) -> Vec<EventsParquetRow> {
|
||||
let mut rows = Vec::with_capacity(build.newswire.len() + build.retail.len());
|
||||
rows.extend(build.newswire.iter().map(EventsParquetRow::from));
|
||||
rows.extend(build.retail.iter().map(EventsParquetRow::from));
|
||||
rows.sort_unstable_by(|a, b| {
|
||||
a.listing_id
|
||||
.cmp(&b.listing_id)
|
||||
.then_with(|| a.ts_micros.cmp(&b.ts_micros))
|
||||
.then_with(|| a.kind.as_ref().cmp(b.kind.as_ref()))
|
||||
.then_with(|| a.subtype.cmp(&b.subtype))
|
||||
.then_with(|| a.payload_json.cmp(&b.payload_json))
|
||||
.then_with(|| a.known_at_micros.cmp(&b.known_at_micros))
|
||||
.then_with(|| a.known_at_source.as_ref().cmp(b.known_at_source.as_ref()))
|
||||
});
|
||||
rows
|
||||
}
|
||||
609
tools/curate-etl/src/parquet_posts_tests.rs
Normal file
609
tools/curate-etl/src/parquet_posts_tests.rs
Normal file
|
|
@ -0,0 +1,609 @@
|
|||
use std::borrow::Cow;
|
||||
use std::collections::HashSet;
|
||||
use std::fs::{self, File};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering};
|
||||
|
||||
use parquet::basic::Compression;
|
||||
use parquet::column::reader::ColumnReader;
|
||||
use parquet::file::reader::{FileReader, SerializedFileReader};
|
||||
|
||||
use crate::parquet_events::{write_events_dataset, EventsParquetRow, EventsWriteOptions};
|
||||
use crate::parquet_posts::{
|
||||
posts_to_event_rows, EVENT_KIND_POST, KNOWN_AT_SOURCE_POST_EDITED,
|
||||
KNOWN_AT_SOURCE_POST_TIMESTAMP, POST_SUBTYPE_NEWSWIRE, POST_SUBTYPE_RETAIL,
|
||||
};
|
||||
use crate::posts::{build_posts, CeoPost, POSTS_SOURCE_CEO};
|
||||
use crate::split::ymd_to_epoch_days;
|
||||
|
||||
static TEMP_DIR_SEQ: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
struct TempDirGuard {
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl TempDirGuard {
|
||||
fn new(label: &str) -> Self {
|
||||
let seq = TEMP_DIR_SEQ.fetch_add(1, AtomicOrdering::Relaxed);
|
||||
let pid = std::process::id();
|
||||
let path =
|
||||
std::env::temp_dir().join(format!("curate-etl-pq-posts-test-{label}-{pid}-{seq}"));
|
||||
let _ = fs::remove_dir_all(&path);
|
||||
fs::create_dir_all(&path).expect("create test temp dir");
|
||||
Self { path }
|
||||
}
|
||||
|
||||
fn path(&self) -> &Path {
|
||||
&self.path
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempDirGuard {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.path);
|
||||
}
|
||||
}
|
||||
|
||||
fn utc_ms(year: i32, month: u32, day: u32, hour: u8, minute: u8, second: u8) -> i64 {
|
||||
let epoch_day = ymd_to_epoch_days(year, month, day).expect("valid test date");
|
||||
let secs = i64::from(epoch_day) * 86_400
|
||||
+ i64::from(hour) * 3_600
|
||||
+ i64::from(minute) * 60
|
||||
+ i64::from(second);
|
||||
secs * 1_000
|
||||
}
|
||||
|
||||
fn post(
|
||||
listing_id: i32,
|
||||
spiel_id: &str,
|
||||
timestamp_ms: i64,
|
||||
edited_ms: Option<i64>,
|
||||
bot: Option<&str>,
|
||||
user_id: Option<&str>,
|
||||
text: &str,
|
||||
) -> CeoPost<i32> {
|
||||
CeoPost {
|
||||
key: listing_id,
|
||||
spiel_id: spiel_id.to_string(),
|
||||
timestamp_ms,
|
||||
edited_ms,
|
||||
bot: bot.map(str::to_string),
|
||||
user_id: user_id.map(str::to_string),
|
||||
text: text.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Generates all permutations of `items` via Heap's algorithm.
|
||||
fn all_permutations<T: Clone>(items: &[T]) -> Vec<Vec<T>> {
|
||||
let mut out = Vec::new();
|
||||
let mut arr = items.to_vec();
|
||||
let n = arr.len();
|
||||
let mut c = vec![0usize; n];
|
||||
out.push(arr.clone());
|
||||
|
||||
let mut i = 0;
|
||||
while i < n {
|
||||
if c[i] < i {
|
||||
if i % 2 == 0 {
|
||||
arr.swap(0, i);
|
||||
} else {
|
||||
arr.swap(c[i], i);
|
||||
}
|
||||
out.push(arr.clone());
|
||||
c[i] += 1;
|
||||
i = 0;
|
||||
} else {
|
||||
c[i] = 0;
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn read_events_parquet_and_verify_zstd(path: &Path) -> Vec<EventsParquetRow> {
|
||||
let file = File::open(path).expect("open parquet file");
|
||||
let reader = SerializedFileReader::new(file).expect("open parquet reader");
|
||||
let meta = reader.metadata();
|
||||
let mut out = Vec::new();
|
||||
|
||||
for rg_idx in 0..meta.num_row_groups() {
|
||||
let rg_meta = meta.row_group(rg_idx);
|
||||
assert_eq!(rg_meta.num_columns(), 7, "expected 7 columns in events schema");
|
||||
for col_idx in 0..rg_meta.num_columns() {
|
||||
let compression = rg_meta.column(col_idx).compression();
|
||||
assert!(
|
||||
matches!(compression, Compression::ZSTD(_)),
|
||||
"expected ZSTD compression for row_group={rg_idx} col={col_idx}, got {compression:?}"
|
||||
);
|
||||
}
|
||||
|
||||
let rg_rows = rg_meta.num_rows() as usize;
|
||||
let rg_reader = reader.get_row_group(rg_idx).expect("row group reader");
|
||||
|
||||
let read_i32_col = |col_idx: usize| -> Vec<i32> {
|
||||
let mut vals = Vec::with_capacity(rg_rows);
|
||||
match rg_reader.get_column_reader(col_idx).expect("col reader") {
|
||||
ColumnReader::Int32ColumnReader(mut typed) => {
|
||||
let mut read = 0usize;
|
||||
while read < rg_rows {
|
||||
let (n, _, _) = typed
|
||||
.read_records(rg_rows - read, None, None, &mut vals)
|
||||
.expect("read i32 records");
|
||||
assert!(n > 0, "unexpected short read in INT32 column {col_idx}");
|
||||
read += n;
|
||||
}
|
||||
}
|
||||
_ => panic!("expected INT32 column at index {col_idx}"),
|
||||
}
|
||||
vals
|
||||
};
|
||||
|
||||
let read_i64_col = |col_idx: usize| -> Vec<i64> {
|
||||
let mut vals = Vec::with_capacity(rg_rows);
|
||||
match rg_reader.get_column_reader(col_idx).expect("col reader") {
|
||||
ColumnReader::Int64ColumnReader(mut typed) => {
|
||||
let mut read = 0usize;
|
||||
while read < rg_rows {
|
||||
let (n, _, _) = typed
|
||||
.read_records(rg_rows - read, None, None, &mut vals)
|
||||
.expect("read i64 records");
|
||||
assert!(n > 0, "unexpected short read in INT64 column {col_idx}");
|
||||
read += n;
|
||||
}
|
||||
}
|
||||
_ => panic!("expected INT64 column at index {col_idx}"),
|
||||
}
|
||||
vals
|
||||
};
|
||||
|
||||
let read_str_col = |col_idx: usize| -> Vec<String> {
|
||||
let mut raw = Vec::with_capacity(rg_rows);
|
||||
match rg_reader.get_column_reader(col_idx).expect("col reader") {
|
||||
ColumnReader::ByteArrayColumnReader(mut typed) => {
|
||||
let mut read = 0usize;
|
||||
while read < rg_rows {
|
||||
let (n, _, _) = typed
|
||||
.read_records(rg_rows - read, None, None, &mut raw)
|
||||
.expect("read byte_array records");
|
||||
assert!(n > 0, "unexpected short read in BYTE_ARRAY column {col_idx}");
|
||||
read += n;
|
||||
}
|
||||
}
|
||||
_ => panic!("expected BYTE_ARRAY column at index {col_idx}"),
|
||||
}
|
||||
raw.iter()
|
||||
.map(|b| std::str::from_utf8(b.data()).expect("valid utf8").to_string())
|
||||
.collect()
|
||||
};
|
||||
|
||||
let listing_ids = read_i32_col(0);
|
||||
let ts = read_i64_col(1);
|
||||
let known_at = read_i64_col(2);
|
||||
let known_at_source = read_str_col(3);
|
||||
let kind = read_str_col(4);
|
||||
let subtype = read_str_col(5);
|
||||
let payload_json = read_str_col(6);
|
||||
|
||||
for i in 0..rg_rows {
|
||||
out.push(EventsParquetRow {
|
||||
listing_id: listing_ids[i],
|
||||
ts_micros: ts[i],
|
||||
known_at_micros: known_at[i],
|
||||
known_at_source: Cow::Owned(known_at_source[i].clone()),
|
||||
kind: Cow::Owned(kind[i].clone()),
|
||||
subtype: subtype[i].clone(),
|
||||
payload_json: payload_json[i].clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maps_retail_unedited_edited_newswire_and_clamped_edit_for_borrowed_and_owned() {
|
||||
let t_post = utc_ms(2024, 6, 15, 14, 30, 0);
|
||||
let t_edit_later = t_post + 600_000; // +10 minutes
|
||||
let t_edit_earlier = t_post - 5_000; // -5 seconds (clamped to posted_at)
|
||||
|
||||
let build = build_posts(vec![
|
||||
post(
|
||||
101,
|
||||
"sp_retail_unedited",
|
||||
t_post,
|
||||
None,
|
||||
None,
|
||||
Some("u_retail"),
|
||||
"Retail baseline",
|
||||
),
|
||||
post(
|
||||
102,
|
||||
"sp_retail_edited",
|
||||
t_post,
|
||||
Some(t_edit_later),
|
||||
Some("0"),
|
||||
Some("u_editor"),
|
||||
"Edited retail text",
|
||||
),
|
||||
post(
|
||||
103,
|
||||
"sp_newswire",
|
||||
t_post,
|
||||
None,
|
||||
Some("1"),
|
||||
Some("thenewswire"),
|
||||
"Company announces drill results",
|
||||
),
|
||||
post(
|
||||
104,
|
||||
"sp_edit_clamped",
|
||||
t_post,
|
||||
Some(t_edit_earlier),
|
||||
None,
|
||||
None,
|
||||
"Clock-skewed edit",
|
||||
),
|
||||
])
|
||||
.expect("build_posts should succeed");
|
||||
|
||||
// Verify borrowed and owned From impls agree on every row.
|
||||
for row in build.newswire.iter().chain(build.retail.iter()) {
|
||||
let from_ref = EventsParquetRow::from(row);
|
||||
let from_owned = EventsParquetRow::from(row.clone());
|
||||
assert_eq!(from_ref, from_owned);
|
||||
}
|
||||
|
||||
let mapped = posts_to_event_rows(&build);
|
||||
assert_eq!(mapped.len(), 4);
|
||||
|
||||
// 101: retail unedited
|
||||
assert_eq!(
|
||||
mapped[0],
|
||||
EventsParquetRow {
|
||||
listing_id: 101,
|
||||
ts_micros: t_post * 1_000,
|
||||
known_at_micros: t_post * 1_000,
|
||||
known_at_source: Cow::Borrowed(KNOWN_AT_SOURCE_POST_TIMESTAMP),
|
||||
kind: Cow::Borrowed(EVENT_KIND_POST),
|
||||
subtype: POST_SUBTYPE_RETAIL.to_string(),
|
||||
payload_json: format!(
|
||||
"{{\"spiel_id\":\"sp_retail_unedited\",\"user_id\":\"u_retail\",\"is_edited\":false,\"source\":\"{POSTS_SOURCE_CEO}\",\"text\":\"Retail baseline\"}}"
|
||||
),
|
||||
}
|
||||
);
|
||||
|
||||
// 102: retail edited (known_at > posted_at)
|
||||
assert_eq!(
|
||||
mapped[1],
|
||||
EventsParquetRow {
|
||||
listing_id: 102,
|
||||
ts_micros: t_post * 1_000,
|
||||
known_at_micros: t_edit_later * 1_000,
|
||||
known_at_source: Cow::Borrowed(KNOWN_AT_SOURCE_POST_EDITED),
|
||||
kind: Cow::Borrowed(EVENT_KIND_POST),
|
||||
subtype: POST_SUBTYPE_RETAIL.to_string(),
|
||||
payload_json: format!(
|
||||
"{{\"spiel_id\":\"sp_retail_edited\",\"user_id\":\"u_editor\",\"is_edited\":true,\"source\":\"{POSTS_SOURCE_CEO}\",\"text\":\"Edited retail text\"}}"
|
||||
),
|
||||
}
|
||||
);
|
||||
|
||||
// 103: newswire (bot == "1")
|
||||
assert_eq!(
|
||||
mapped[2],
|
||||
EventsParquetRow {
|
||||
listing_id: 103,
|
||||
ts_micros: t_post * 1_000,
|
||||
known_at_micros: t_post * 1_000,
|
||||
known_at_source: Cow::Borrowed(KNOWN_AT_SOURCE_POST_TIMESTAMP),
|
||||
kind: Cow::Borrowed(EVENT_KIND_POST),
|
||||
subtype: POST_SUBTYPE_NEWSWIRE.to_string(),
|
||||
payload_json: format!(
|
||||
"{{\"spiel_id\":\"sp_newswire\",\"user_id\":\"thenewswire\",\"is_edited\":false,\"source\":\"{POSTS_SOURCE_CEO}\",\"text\":\"Company announces drill results\"}}"
|
||||
),
|
||||
}
|
||||
);
|
||||
|
||||
// 104: edit-before-post clamped -> known_at == ts, known_at_source == "post_timestamp",
|
||||
// payload preserves is_edited: true and user_id: null.
|
||||
assert_eq!(
|
||||
mapped[3],
|
||||
EventsParquetRow {
|
||||
listing_id: 104,
|
||||
ts_micros: t_post * 1_000,
|
||||
known_at_micros: t_post * 1_000,
|
||||
known_at_source: Cow::Borrowed(KNOWN_AT_SOURCE_POST_TIMESTAMP),
|
||||
kind: Cow::Borrowed(EVENT_KIND_POST),
|
||||
subtype: POST_SUBTYPE_RETAIL.to_string(),
|
||||
payload_json: format!(
|
||||
"{{\"spiel_id\":\"sp_edit_clamped\",\"user_id\":null,\"is_edited\":true,\"source\":\"{POSTS_SOURCE_CEO}\",\"text\":\"Clock-skewed edit\"}}"
|
||||
),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn payload_json_escapes_special_chars_control_chars_non_ascii_and_preserves_key_order() {
|
||||
let t_post = utc_ms(2024, 7, 1, 12, 0, 0);
|
||||
let build = build_posts(vec![
|
||||
post(
|
||||
10,
|
||||
"sp\"with\\slash",
|
||||
t_post,
|
||||
None,
|
||||
None,
|
||||
Some("user\"1"),
|
||||
"Quote \"here\", backslash \\, newline\nctrl\x01, non-ASCII café €",
|
||||
),
|
||||
post(
|
||||
11,
|
||||
"sp_null_user",
|
||||
t_post,
|
||||
Some(t_post + 1_000),
|
||||
Some("1"),
|
||||
None,
|
||||
"Simple wire text",
|
||||
),
|
||||
])
|
||||
.expect("build_posts should succeed");
|
||||
|
||||
let rows = posts_to_event_rows(&build);
|
||||
assert_eq!(rows.len(), 2);
|
||||
|
||||
assert_eq!(
|
||||
rows[0].payload_json,
|
||||
"{\"spiel_id\":\"sp\\\"with\\\\slash\",\"user_id\":\"user\\\"1\",\"is_edited\":false,\"source\":\"ceo_posts\",\"text\":\"Quote \\\"here\\\", backslash \\\\, newline\\nctrl\\u0001, non-ASCII café €\"}"
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
rows[1].payload_json,
|
||||
"{\"spiel_id\":\"sp_null_user\",\"user_id\":null,\"is_edited\":true,\"source\":\"ceo_posts\",\"text\":\"Simple wire text\"}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_trip_writes_two_years_via_events_writer_with_zstd_and_exact_readback() {
|
||||
let dir = TempDirGuard::new("round-trip");
|
||||
let t_2024_a = utc_ms(2024, 5, 10, 15, 0, 0);
|
||||
let t_2024_dec = utc_ms(2024, 12, 31, 23, 55, 0);
|
||||
let t_2025_jan_edit = utc_ms(2025, 1, 1, 0, 15, 0); // edited across UTC year boundary
|
||||
let t_2025_feb = utc_ms(2025, 2, 20, 13, 30, 0);
|
||||
|
||||
let build = build_posts(vec![
|
||||
// Two distinct posts sharing the exact same (listing_id=200, ts=t_2024_a), one newswire and one retail.
|
||||
post(
|
||||
200,
|
||||
"sp_2024_wire",
|
||||
t_2024_a,
|
||||
None,
|
||||
Some("1"),
|
||||
Some("thenewswire"),
|
||||
"Newswire release at identical ts",
|
||||
),
|
||||
post(
|
||||
200,
|
||||
"sp_2024_retail_1",
|
||||
t_2024_a,
|
||||
None,
|
||||
None,
|
||||
Some("u1"),
|
||||
"Retail reply 1 at identical ts",
|
||||
),
|
||||
post(
|
||||
200,
|
||||
"sp_2024_retail_2",
|
||||
t_2024_a,
|
||||
None,
|
||||
None,
|
||||
Some("u2"),
|
||||
"Retail reply 2 at identical ts",
|
||||
),
|
||||
// December 2024 post edited in January 2025: partitions by ts -> year=2024, known_at in 2025.
|
||||
post(
|
||||
201,
|
||||
"sp_2024_dec_edited_2025",
|
||||
t_2024_dec,
|
||||
Some(t_2025_jan_edit),
|
||||
None,
|
||||
Some("u3"),
|
||||
"Edited after New Year",
|
||||
),
|
||||
// 2025 newswire and retail posts.
|
||||
post(
|
||||
200,
|
||||
"sp_2025_wire",
|
||||
t_2025_feb,
|
||||
None,
|
||||
Some("1"),
|
||||
Some("thenewswire"),
|
||||
"2025 quarterly update",
|
||||
),
|
||||
post(
|
||||
202,
|
||||
"sp_2025_retail",
|
||||
t_2025_feb,
|
||||
None,
|
||||
Some("0"),
|
||||
None,
|
||||
"2025 retail commentary",
|
||||
),
|
||||
])
|
||||
.expect("build_posts should succeed");
|
||||
|
||||
let event_rows = posts_to_event_rows(&build);
|
||||
assert_eq!(event_rows.len(), 6);
|
||||
|
||||
let stats = write_events_dataset(dir.path(), &event_rows, EventsWriteOptions::default())
|
||||
.expect("write_events_dataset should accept posts_to_event_rows output");
|
||||
assert_eq!(stats.rows_written, 6);
|
||||
assert_eq!(stats.files_written, 2);
|
||||
assert_eq!(stats.rows_by_year.get(&2024), Some(&4));
|
||||
assert_eq!(stats.rows_by_year.get(&2025), Some(&2));
|
||||
|
||||
let path_2024 = dir.path().join("events/year=2024/part.parquet");
|
||||
let path_2025 = dir.path().join("events/year=2025/part.parquet");
|
||||
assert!(path_2024.exists(), "expected {}", path_2024.display());
|
||||
assert!(path_2025.exists(), "expected {}", path_2025.display());
|
||||
|
||||
let read_2024 = read_events_parquet_and_verify_zstd(&path_2024);
|
||||
let read_2025 = read_events_parquet_and_verify_zstd(&path_2025);
|
||||
|
||||
let expected_2024: Vec<EventsParquetRow> = event_rows
|
||||
.iter()
|
||||
.filter(|r| crate::events::partition_year_utc(r.ts_micros) == 2024)
|
||||
.cloned()
|
||||
.collect();
|
||||
let expected_2025: Vec<EventsParquetRow> = event_rows
|
||||
.iter()
|
||||
.filter(|r| crate::events::partition_year_utc(r.ts_micros) == 2025)
|
||||
.cloned()
|
||||
.collect();
|
||||
|
||||
assert_eq!(read_2024, expected_2024);
|
||||
assert_eq!(read_2025, expected_2025);
|
||||
|
||||
// Verify all read-back rows have kind == "post", both subtypes are present, and newswire vs
|
||||
// retail spiel_ids are strictly disjoint (never sharing a subtype).
|
||||
let mut newswire_payloads = HashSet::new();
|
||||
let mut retail_payloads = HashSet::new();
|
||||
for row in read_2024.iter().chain(read_2025.iter()) {
|
||||
assert_eq!(row.kind.as_ref(), EVENT_KIND_POST);
|
||||
match row.subtype.as_str() {
|
||||
POST_SUBTYPE_NEWSWIRE => {
|
||||
assert!(newswire_payloads.insert(row.payload_json.clone()));
|
||||
}
|
||||
POST_SUBTYPE_RETAIL => {
|
||||
assert!(retail_payloads.insert(row.payload_json.clone()));
|
||||
}
|
||||
other => panic!("unexpected post subtype: {other}"),
|
||||
}
|
||||
}
|
||||
assert_eq!(newswire_payloads.len(), 2);
|
||||
assert_eq!(retail_payloads.len(), 4);
|
||||
assert!(newswire_payloads.is_disjoint(&retail_payloads));
|
||||
|
||||
// Confirm the Dec 2024 post edited in Jan 2025 landed in year=2024 with 2025 known_at.
|
||||
let dec_row = read_2024
|
||||
.iter()
|
||||
.find(|r| r.listing_id == 201)
|
||||
.expect("December post must be in year=2024 partition");
|
||||
assert_eq!(dec_row.ts_micros, t_2024_dec * 1_000);
|
||||
assert_eq!(dec_row.known_at_micros, t_2025_jan_edit * 1_000);
|
||||
assert_eq!(dec_row.known_at_source.as_ref(), KNOWN_AT_SOURCE_POST_EDITED);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn posts_to_event_rows_is_permutation_invariant_and_handles_empty_input() {
|
||||
let empty_build = build_posts(Vec::<CeoPost<i32>>::new()).expect("empty build");
|
||||
assert!(posts_to_event_rows(&empty_build).is_empty());
|
||||
|
||||
let t0 = utc_ms(2024, 9, 1, 14, 0, 0);
|
||||
let t1 = t0 + 30_000;
|
||||
let fixture = vec![
|
||||
// Conflicting duplicate spiel_id: later edit wins regardless of input order.
|
||||
post(50, "sp_dup", t0, None, None, Some("u1"), "Original text"),
|
||||
post(
|
||||
50,
|
||||
"sp_dup",
|
||||
t0,
|
||||
Some(t1),
|
||||
None,
|
||||
Some("u1"),
|
||||
"Edited duplicate survivor",
|
||||
),
|
||||
// Two distinct posts sharing (listing_id=50, ts=t0), one newswire and one retail.
|
||||
post(
|
||||
50,
|
||||
"sp_same_ts_wire",
|
||||
t0,
|
||||
None,
|
||||
Some("1"),
|
||||
Some("thenewswire"),
|
||||
"Wire at t0",
|
||||
),
|
||||
post(
|
||||
50,
|
||||
"sp_same_ts_retail",
|
||||
t0,
|
||||
None,
|
||||
None,
|
||||
Some("u2"),
|
||||
"Retail at t0",
|
||||
),
|
||||
// Separate listing.
|
||||
post(40, "sp_other_listing", t1, None, None, None, "Earlier listing"),
|
||||
];
|
||||
|
||||
let reference =
|
||||
posts_to_event_rows(&build_posts(fixture.clone()).expect("reference build"));
|
||||
assert_eq!(reference.len(), 4);
|
||||
let reference_payload_bytes: Vec<&[u8]> = reference
|
||||
.iter()
|
||||
.map(|r| r.payload_json.as_bytes())
|
||||
.collect();
|
||||
|
||||
let perms = all_permutations(&fixture);
|
||||
assert_eq!(perms.len(), 120);
|
||||
for perm in perms {
|
||||
let got = posts_to_event_rows(&build_posts(perm).expect("permuted build"));
|
||||
assert_eq!(got, reference);
|
||||
let got_payload_bytes: Vec<&[u8]> =
|
||||
got.iter().map(|r| r.payload_json.as_bytes()).collect();
|
||||
assert_eq!(got_payload_bytes, reference_payload_bytes);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn point_in_time_guard_excludes_edited_post_until_edit_timestamp() {
|
||||
let t_post = utc_ms(2024, 8, 12, 13, 30, 0);
|
||||
let t_edit = t_post + 900_000; // +15 minutes
|
||||
|
||||
let build = build_posts(vec![
|
||||
post(
|
||||
300,
|
||||
"sp_unedited",
|
||||
t_post,
|
||||
None,
|
||||
None,
|
||||
Some("u1"),
|
||||
"Posted at open",
|
||||
),
|
||||
post(
|
||||
300,
|
||||
"sp_edited",
|
||||
t_post,
|
||||
Some(t_edit),
|
||||
None,
|
||||
Some("u2"),
|
||||
"Edited 15m later with hindsight",
|
||||
),
|
||||
])
|
||||
.expect("build_posts should succeed");
|
||||
|
||||
let rows = posts_to_event_rows(&build);
|
||||
let edited = rows
|
||||
.iter()
|
||||
.find(|r| r.payload_json.contains("\"sp_edited\""))
|
||||
.expect("edited row present");
|
||||
|
||||
assert_eq!(edited.ts_micros, t_post * 1_000);
|
||||
assert_eq!(edited.known_at_micros, t_edit * 1_000);
|
||||
assert_ne!(edited.known_at_micros, edited.ts_micros);
|
||||
assert_eq!(edited.known_at_source.as_ref(), KNOWN_AT_SOURCE_POST_EDITED);
|
||||
|
||||
// As-of cutoff between posting and editing must exclude the edited post.
|
||||
let cutoff_between = (t_post + 300_000) * 1_000;
|
||||
let visible_between: Vec<&EventsParquetRow> = rows
|
||||
.iter()
|
||||
.filter(|r| r.known_at_micros <= cutoff_between)
|
||||
.collect();
|
||||
assert_eq!(visible_between.len(), 1);
|
||||
assert!(visible_between[0].payload_json.contains("\"sp_unedited\""));
|
||||
|
||||
// As-of cutoff at the exact edit timestamp includes both.
|
||||
let visible_at_edit: Vec<&EventsParquetRow> = rows
|
||||
.iter()
|
||||
.filter(|r| r.known_at_micros <= t_edit * 1_000)
|
||||
.collect();
|
||||
assert_eq!(visible_at_edit.len(), 2);
|
||||
}
|
||||
|
|
@ -10,6 +10,8 @@
|
|||
//! never `posted_at`. In `ceoPosts`, an edit overwrites `spiel` in place without version
|
||||
//! history, so the builder retains one supplied version per `spiel_id` and cannot recover
|
||||
//! earlier pre-edit text.
|
||||
//! - See [`crate::parquet_posts`] for mapping [`PostRow<i32>`] / [`PostsBuild<i32>`] into the
|
||||
//! `events` Parquet contract (`kind = "post"`, `subtype = "newswire" | "retail"`).
|
||||
|
||||
use std::error::Error;
|
||||
use std::fmt;
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue