use std::path::Path;
use std::time::{Duration, Instant};
use rudb_common::{LogicalType, Result, Value};
use rudb_graph::{Form, KeyMap, Keys, wire};
use rudb_vector::Chunk;
use crate::section::{self, Attachment};
use crate::{Catalog, Reader, invalid, type_tag};
#[derive(Debug)]
pub struct KeyColumn<'a> {
reader: &'a Reader,
column: usize,
}
impl<'a> KeyColumn<'a> {
pub fn new(reader: &'a Reader, column: usize) -> Result<Self> {
let fields = reader.table().fields();
let Some(field) = fields.get(column) else {
return Err(invalid(&format!(
"column {column} is past the {} of table {}",
fields.len(),
reader.table().name()
)));
};
if !mappable(&field.ty) {
return Err(invalid(&format!(
"a key map over {} needs an integer key form, and {} has none",
field.name, field.ty
)));
}
Ok(Self { reader, column })
}
}
impl Keys for KeyColumn<'_> {
fn scan(&self, each: &mut dyn FnMut(Option<i128>) -> Result<()>) -> Result<()> {
for part in 0..self.reader.parts() {
let chunk = self.reader.read(part, &[self.column])?;
let values = chunk.column(0)?;
for row in 0..chunk.len() {
each(key_at(&chunk, values, row)?)?;
}
}
Ok(())
}
}
fn mappable(ty: &LogicalType) -> bool {
matches!(
ty,
LogicalType::TinyInt
| LogicalType::SmallInt
| LogicalType::Integer
| LogicalType::BigInt
| LogicalType::HugeInt
| LogicalType::UTinyInt
| LogicalType::USmallInt
| LogicalType::UInteger
| LogicalType::UBigInt
| LogicalType::Date
| LogicalType::Decimal { .. }
)
}
fn key_at(chunk: &Chunk, values: &rudb_vector::Vector, row: usize) -> Result<Option<i128>> {
if let Some(key) = values.signed_at(row) {
return Ok(Some(key));
}
match chunk.value_at(row, 0) {
Value::Null => Ok(None),
Value::TinyInt(key) => Ok(Some(i128::from(key))),
Value::SmallInt(key) => Ok(Some(i128::from(key))),
Value::Integer(key) | Value::Date(key) => Ok(Some(i128::from(key))),
Value::BigInt(key) | Value::Time(key) | Value::Timestamp(key) => Ok(Some(i128::from(key))),
Value::HugeInt(key) | Value::Decimal { unscaled: key, .. } => Ok(Some(key)),
Value::UTinyInt(key) => Ok(Some(i128::from(key))),
Value::USmallInt(key) => Ok(Some(i128::from(key))),
Value::UInteger(key) => Ok(Some(i128::from(key))),
Value::UBigInt(key) => Ok(Some(i128::from(key))),
other => Err(invalid(&format!("a key column holds {other}, which is not a key"))),
}
}
#[derive(Debug, Clone, Copy)]
pub struct Built {
pub column: usize,
pub form: Form,
pub rows: u64,
pub distinct: bool,
pub bytes: usize,
pub column_bytes: u64,
pub built: bool,
pub build: Duration,
}
pub fn build_key_map(reader: &Reader, column: usize) -> Result<KeyMap> {
KeyMap::build_from(&KeyColumn::new(reader, column)?)
}
pub const BUDGET_SHARE: u64 = 10;
pub const BUDGET_FLOOR: u64 = 64 * 1024;
pub fn build_key_maps(path: &Path, table: &str, columns: &[usize]) -> Result<Vec<Built>> {
build_key_maps_within(path, table, columns, BUDGET_SHARE)
}
pub fn build_key_maps_within(
path: &Path,
table: &str,
columns: &[usize],
share: u64,
) -> Result<Vec<Built>> {
let reader = Catalog::open(path)?.table(table)?;
let column_bytes = reader.layout().columns_total();
let allowance = (column_bytes.saturating_mul(share) / 100).max(BUDGET_FLOOR);
let mut spent = held_bytes(&reader, columns)?;
let mut report = Vec::with_capacity(columns.len());
let mut payloads = Vec::with_capacity(columns.len());
for &column in columns {
let start = Instant::now();
let map = build_key_map(&reader, column)?;
let payload = wire::encode(&map, type_tag(&reader.table().fields()[column].ty)?)?;
report.push(Built {
column,
form: map.form(),
rows: map.observed().rows,
distinct: map.observed().distinct,
bytes: payload.bytes.len(),
column_bytes,
built: false,
build: start.elapsed(),
});
payloads.push((column, payload));
}
let mut order = (0..payloads.len()).collect::<Vec<_>>();
order.sort_by_key(|&at| payloads[at].1.bytes.len());
let mut keep = vec![false; payloads.len()];
for at in order {
if !report[at].distinct {
continue;
}
let cost = payloads[at].1.bytes.len() as u64;
if spent.saturating_add(cost) <= allowance {
spent += cost;
keep[at] = true;
report[at].built = true;
}
}
drop(reader);
let attachments = payloads
.iter()
.zip(&keep)
.filter(|&(_, &keep)| keep)
.map(|((column, payload), _)| {
Ok(Attachment {
kind: *section::KEY_MAP,
id: u64::try_from(*column).map_err(|_| invalid("column index overflow"))?,
flags: payload.flags,
header_bytes: payload.header_bytes,
bytes: &payload.bytes,
})
})
.collect::<Result<Vec<_>>>()?;
crate::attach(path, table, &attachments)?;
Ok(report)
}
fn held_bytes(reader: &Reader, replacing: &[usize]) -> Result<u64> {
let mut total = 0;
for held in reader.table().sections() {
if !held.among(section::GRAPH_KINDS) {
continue;
}
let replaced = held.kind == *section::KEY_MAP
&& replacing.iter().any(|&column| u64::try_from(column) == Ok(held.id));
if replaced || !held.usable(reader.table().generation()) {
continue;
}
let Ok(extents) = reader.extents(held) else { continue };
total += extents.iter().map(|extent| u64::from(extent.length)).sum::<u64>();
}
Ok(total)
}
#[must_use]
pub fn key_map(reader: &Reader, column: usize) -> Option<KeyMap> {
let table = reader.table();
let id = u64::try_from(column).ok()?;
let held = table
.sections()
.iter()
.find(|section| section.kind == *section::KEY_MAP && section.id == id)?;
if !held.usable(table.generation()) {
return None;
}
let (map, tag) = wire::decode(&reader.payload(held).ok()?).ok()?;
if tag != type_tag(&table.fields().get(column)?.ty).ok()? {
return None;
}
Some(map)
}
#[cfg(test)]
mod tests {
use std::fs;
use std::path::PathBuf;
use std::time::{SystemTime, UNIX_EPOCH};
use rudb_common::Field;
use rudb_graph::Rid;
use rudb_vector::Vector;
use super::*;
use crate::Writer;
fn path(label: &str) -> PathBuf {
let stamp = SystemTime::now().duration_since(UNIX_EPOCH).expect("time advances").as_nanos();
std::env::temp_dir().join(format!("rudb-graph-{label}-{}-{stamp}.rdb", std::process::id()))
}
fn table_of(label: &str, keys: &[Option<i64>]) -> PathBuf {
let path = path(label);
let mut writer =
Writer::create(&path, "parent", vec![Field::new("key", LogicalType::BigInt)])
.expect("new file");
for part in keys.chunks(1000) {
let values =
part.iter().map(|key| key.map_or(Value::Null, Value::BigInt)).collect::<Vec<_>>();
let chunk =
Chunk::new(vec![Vector::from_values(LogicalType::BigInt, &values).expect("keys")])
.expect("one column");
writer.append(&chunk).expect("a part");
}
writer.finish().expect("commit");
path
}
fn resolves(keys: &[Option<i64>], map: &KeyMap) {
for (rid, key) in keys.iter().enumerate() {
let Some(key) = *key else { continue };
let found =
map.lookup(i128::from(key)).expect("lookup").expect("a key in the column resolves");
assert_eq!(found, rid as Rid, "key {key} resolved to {found} rather than {rid}");
}
}
#[test]
fn a_key_map_built_over_a_file_resolves_every_key_to_its_own_row() {
let keys = (1..=3000_i64).map(Some).collect::<Vec<_>>();
let path = table_of("identity", &keys);
let built = build_key_maps(&path, "parent", &[0]).expect("build");
assert_eq!(built.len(), 1);
assert_eq!(built[0].form, Form::Identity);
assert_eq!(built[0].rows, 3000);
assert!(built[0].distinct);
assert_eq!(built[0].bytes, wire::HEADER_BYTES, "identity is a header and nothing else");
let reader = Catalog::open(&path).expect("reopen").table("parent").expect("the table");
let map = key_map(&reader, 0).expect("the map is in the file");
assert_eq!(map.form(), Form::Identity);
resolves(&keys, &map);
assert_eq!(map.lookup(0).expect("a key below the column"), None);
assert_eq!(map.lookup(3001).expect("a key past the column"), None);
fs::remove_file(&path).expect("clean up");
}
#[test]
fn a_column_with_gaps_takes_the_bitmap_form_and_still_resolves() {
let keys = (0..2000_i64).map(|value| Some(value * 4 + 7)).collect::<Vec<_>>();
let path = table_of("dense", &keys);
let built = build_key_maps(&path, "parent", &[0]).expect("build");
assert_eq!(built[0].form, Form::Dense);
let reader = Catalog::open(&path).expect("reopen").table("parent").expect("the table");
let map = key_map(&reader, 0).expect("the map is in the file");
resolves(&keys, &map);
assert_eq!(map.lookup(8).expect("a value in the range but not the column"), None);
fs::remove_file(&path).expect("clean up");
}
#[test]
fn a_column_out_of_order_takes_the_sorted_form_and_still_resolves() {
let keys = (0..1500_i64).map(|value| Some((value * 7919) % 100_003)).collect::<Vec<_>>();
let path = table_of("sorted", &keys);
let built = build_key_maps(&path, "parent", &[0]).expect("build");
assert_eq!(built[0].form, Form::Sorted);
assert!(built[0].distinct, "the sort settles distinctness for an unordered column");
let reader = Catalog::open(&path).expect("reopen").table("parent").expect("the table");
let map = key_map(&reader, 0).expect("the map is in the file");
resolves(&keys, &map);
fs::remove_file(&path).expect("clean up");
}
#[test]
fn a_null_in_the_key_column_does_not_shift_the_rows_after_it() {
let mut keys = (1..=1200_i64).map(Some).collect::<Vec<_>>();
keys[3] = None;
keys[900] = None;
let path = table_of("nulls", &keys);
let built = build_key_maps(&path, "parent", &[0]).expect("build");
assert_eq!(built[0].rows, 1198, "a null is not a key");
let reader = Catalog::open(&path).expect("reopen").table("parent").expect("the table");
let map = key_map(&reader, 0).expect("the map is in the file");
resolves(&keys, &map);
fs::remove_file(&path).expect("clean up");
}
#[test]
fn a_column_with_a_repeat_in_it_is_mapped_and_reported_as_no_parent() {
let mut keys = (1..=500_i64).map(Some).collect::<Vec<_>>();
keys[200] = Some(7);
let path = table_of("repeat", &keys);
let built = build_key_maps(&path, "parent", &[0]).expect("build");
assert!(!built[0].distinct, "a repeat is observed rather than declared away");
assert!(!built[0].built, "and a map no rid can be resolved through is not kept");
assert!(built[0].bytes > 0, "what it would have cost is still reported");
let reader = Catalog::open(&path).expect("reopen").table("parent").expect("the table");
assert!(key_map(&reader, 0).is_none(), "nothing was written to read back");
assert!(reader.table().sections().is_empty());
fs::remove_file(&path).expect("clean up");
}
#[test]
fn a_table_with_no_key_map_answers_with_none_rather_than_an_error() {
let path = table_of("absent", &[Some(1), Some(2)]);
let reader = Catalog::open(&path).expect("reopen").table("parent").expect("the table");
assert!(key_map(&reader, 0).is_none());
assert!(key_map(&reader, 99).is_none(), "a column that does not exist is not a panic");
fs::remove_file(&path).expect("clean up");
}
#[test]
fn a_stale_key_map_is_ignored_and_the_table_still_reads() {
let path = table_of("stale", &(1..=100_i64).map(Some).collect::<Vec<_>>());
build_key_maps(&path, "parent", &[0]).expect("build");
let reader = Catalog::open(&path).expect("reopen").table("parent").expect("the table");
assert!(key_map(&reader, 0).is_some());
let generation = reader.table().generation();
drop(reader);
let mut entry = Catalog::open(&path)
.expect("reopen")
.table("parent")
.expect("the table")
.table()
.sections()[0];
assert!(entry.usable(generation));
entry.generation = generation + 1;
assert!(!entry.usable(generation), "a rewrite invalidates rather than corrupts");
fs::remove_file(&path).expect("clean up");
}
#[test]
fn a_torn_key_map_costs_the_shortcut_and_not_the_query() {
let keys = (1..=200_i64).map(Some).collect::<Vec<_>>();
let path = table_of("torn", &keys);
build_key_maps(&path, "parent", &[0]).expect("build");
let reader = Catalog::open(&path).expect("reopen").table("parent").expect("the table");
let extent = reader
.extents(&reader.table().sections()[0])
.expect("extent table")
.first()
.copied()
.expect("one extent");
drop(reader);
let file = fs::OpenOptions::new().write(true).open(&path).expect("reopen to corrupt");
crate::write_at(&file, extent.offset, &[0xff; 8]).expect("flip the header");
drop(file);
let reader = Catalog::open(&path).expect("reopen").table("parent").expect("the table");
assert!(key_map(&reader, 0).is_none(), "a payload that does not checksum is not a map");
assert_eq!(reader.table().rows(), 200, "and the table is untouched");
fs::remove_file(&path).expect("clean up");
}
#[test]
fn a_column_with_no_integer_key_form_is_refused_by_name() {
let path = path("varchar");
let mut writer =
Writer::create(&path, "parent", vec![Field::new("name", LogicalType::Varchar)])
.expect("new file");
let chunk = Chunk::new(vec![
Vector::from_values(LogicalType::Varchar, &[Value::Varchar("a".into())])
.expect("one name"),
])
.expect("one column");
writer.append(&chunk).expect("a part");
writer.finish().expect("commit");
let reader = Catalog::open(&path).expect("reopen").table("parent").expect("the table");
let error = KeyColumn::new(&reader, 0).expect_err("a string key needs its codes");
assert!(error.to_string().contains("integer key form"), "{error}");
fs::remove_file(&path).expect("clean up");
}
#[test]
fn several_columns_are_mapped_in_one_commit() {
let path = path("two_columns");
let mut writer = Writer::create(
&path,
"parent",
vec![
Field::required("id", LogicalType::BigInt),
Field::required("code", LogicalType::Integer),
],
)
.expect("new file");
let ids = (1..=400_i64).map(Value::BigInt).collect::<Vec<_>>();
let codes = (1..=400_i32).map(|code| Value::Integer(code * 3)).collect::<Vec<_>>();
let chunk = Chunk::new(vec![
Vector::from_values(LogicalType::BigInt, &ids).expect("ids"),
Vector::from_values(LogicalType::Integer, &codes).expect("codes"),
])
.expect("two columns");
writer.append(&chunk).expect("a part");
writer.finish().expect("commit");
let built = build_key_maps(&path, "parent", &[0, 1]).expect("build both");
assert_eq!(built.len(), 2);
assert_eq!(built[0].form, Form::Identity);
assert_eq!(built[1].form, Form::Dense);
let reader = Catalog::open(&path).expect("reopen").table("parent").expect("the table");
assert_eq!(reader.table().sections().len(), 2, "one commit and two entries");
assert_eq!(key_map(&reader, 0).expect("the id map").form(), Form::Identity);
assert_eq!(key_map(&reader, 1).expect("the code map").form(), Form::Dense);
assert_eq!(
key_map(&reader, 1).expect("the code map").lookup(9).expect("lookup"),
Some(2),
"the third code is the third row"
);
fs::remove_file(&path).expect("clean up");
}
#[test]
fn the_statistics_sections_do_not_count_against_the_graph_budget() {
let keys = (1..=3000_i64).map(Some).collect::<Vec<_>>();
let path = table_of("apart", &keys);
crate::stats::build_stats(&path, "parent", &[0]).expect("summaries first");
let reader = Catalog::open(&path).expect("reopen").table("parent").expect("the table");
let statistics = reader
.table()
.sections()
.iter()
.filter(|held| held.among(section::STATISTICS_KINDS))
.count();
assert_eq!(statistics, 2, "a summary and a sketch are in the file");
assert_eq!(held_bytes(&reader, &[0]).expect("held"), 0, "and neither is the graph's");
drop(reader);
fs::remove_file(&path).expect("clean up");
}
#[test]
fn a_map_that_does_not_fit_the_budget_is_measured_and_not_written() {
let keys = (0..100_000_i64).map(|value| Some(value * 8)).collect::<Vec<_>>();
let path = table_of("budget", &keys);
let built = build_key_maps(&path, "parent", &[0]).expect("build");
assert_eq!(built[0].form, Form::Dense);
assert!(!built[0].built, "a map ten times its column does not fit a tenth of it");
assert!(built[0].bytes as u64 > built[0].column_bytes, "{built:?}");
let reader = Catalog::open(&path).expect("reopen").table("parent").expect("the table");
assert!(reader.table().sections().is_empty(), "and nothing was written");
assert!(key_map(&reader, 0).is_none());
drop(reader);
let built = build_key_maps_within(&path, "parent", &[0], 100_000).expect("build");
assert!(built[0].built);
let reader = Catalog::open(&path).expect("reopen").table("parent").expect("the table");
let map = key_map(&reader, 0).expect("the map is in the file");
resolves(&keys, &map);
fs::remove_file(&path).expect("clean up");
}
#[test]
fn the_budget_admits_the_cheapest_maps_it_can_fit() {
let path = path("budget_order");
let mut writer = Writer::create(
&path,
"parent",
vec![
Field::required("id", LogicalType::BigInt),
Field::required("code", LogicalType::BigInt),
],
)
.expect("new file");
let ids = (1..=100_000_i64).map(Value::BigInt).collect::<Vec<_>>();
let codes = (1..=100_000_i64)
.map(|code| Value::BigInt((code * 2_147_483_647) % 999_999_937))
.collect::<Vec<_>>();
for part in 0..100 {
let at = part * 1000;
let chunk = Chunk::new(vec![
Vector::from_values(LogicalType::BigInt, &ids[at..at + 1000]).expect("ids"),
Vector::from_values(LogicalType::BigInt, &codes[at..at + 1000]).expect("codes"),
])
.expect("two columns");
writer.append(&chunk).expect("a part");
}
writer.finish().expect("commit");
let built = build_key_maps(&path, "parent", &[1, 0]).expect("build");
assert_eq!(built[0].column, 1, "the report is in the order it was asked in");
assert_eq!(built[0].form, Form::Sorted);
assert!(!built[0].built, "the sorted map did not fit: {built:?}");
assert!(built[1].built, "the identity map did, and was reached second: {built:?}");
let reader = Catalog::open(&path).expect("reopen").table("parent").expect("the table");
assert!(key_map(&reader, 0).is_some());
assert!(key_map(&reader, 1).is_none());
fs::remove_file(&path).expect("clean up");
}
}