reddb-io-server 1.46.0

RedDB server-side engine: storage, runtime, replication, MCP, AI, and the gRPC/HTTP/RedWire/PG-wire dispatchers. Re-exported by the umbrella `reddb` crate.
Documentation
//! Fixed-width keys of a document HASH projection for indexed joins.
use super::*;
use reddb_engine::query::runtime::values::{runtime_value_number, runtime_value_text_cow};
use reddb_types::Value;

const UNCOVERED: [u8; 1] = [0];
const POSTINGS_MAX: usize = 1024;
// Bound the resident projection work under the publication lock.
const RESIDENT_ROWS_MAX: usize = 4096;
const RESIDENT_BYTES_MAX: usize = 16 * 1024 * 1024;
pub(in crate::runtime) const PROBE_KEYS_MAX: usize = 64;
pub(in crate::runtime) const PROBE_ROW_BYTES_MAX: usize = 64 * 1024;

pub(in crate::runtime) fn join_storage_name(index: &str) -> String {
    format!(
        "\0reddb/document-hash-join/{}",
        hex::encode(Sha256::digest(index))
    )
}

pub(super) fn projection_identity(
    hash_identity: &SecondaryIndexIdentity,
) -> SecondaryIndexIdentity {
    join_identity(hash_identity, 2, b"document-hash-join-numeric-text-v2")
}

fn join_identity(
    hash_identity: &SecondaryIndexIdentity,
    codec_version: u32,
    domain: &[u8],
) -> SecondaryIndexIdentity {
    let mut definition = Sha256::new();
    definition.update(domain);
    definition.update(hash_identity.definition);
    SecondaryIndexIdentity {
        codec_version,
        definition: definition.finalize().into(),
    }
}

pub(in crate::runtime) fn join_hash_key(value: &Value) -> Option<JoinHashKey> {
    // Keep the class precedence of runtime_join_lookup_key. UTF-8 bytes
    // preserve its case and normalization semantics.
    if let Some(number) = runtime_value_number(value) {
        Some(JoinHashKey::Number(number.to_bits()))
    } else if matches!(value, Value::Boolean(_)) {
        None
    } else {
        runtime_value_text_cow(value)
            .map(|text| JoinHashKey::Text(Sha256::digest(text.as_bytes()).into()))
    }
}

pub(super) struct JoinProjection(pub(super) Arc<HashProjection>);

impl JoinProjection {
    pub(super) fn supports(column: &str) -> bool {
        !column.contains('.')
            && !matches!(
                column,
                "body"
                    | "rid"
                    | "entity_id"
                    | "collection"
                    | "kind"
                    | "tenant"
                    | "created_at"
                    | "updated_at"
                    | "red_collection"
                    | "red_kind"
            )
    }
    /// An error denotes a row whose fields cannot establish join coverage.
    fn key(&self, entity: &UnifiedEntity) -> Result<Option<JoinHashKey>, ()> {
        let EntityData::Row(row) = &entity.data else {
            return Err(());
        };
        let schema = row.schema.as_ref().or(self.0.schema.as_ref());
        let field = |name: &str| {
            row.get_field(name).or_else(|| {
                let position = schema?.iter().position(|column| column == name)?;
                row.columns.get(position)
            })
        };
        let Some(Value::Json(body)) = field("body") else {
            return Err(());
        };
        let fields = crate::document_body::container_field_names(body).ok_or(())?;
        // Literal dotted keys can shadow the alias-qualified field in the
        // executor. Legacy JSON and ambiguous rows make the batch ineligible.
        if fields.iter().any(|name| name.contains('.'))
            || row.iter_fields().any(|(name, _)| name.contains('.'))
            || schema.is_some_and(|names| names.iter().any(|name| name.contains('.')))
        {
            return Err(());
        }
        let column = &self.0.columns[0];
        Ok(if fields.contains(column) {
            let value = crate::document_body::read_body_field(body, column).ok_or(())?;
            join_hash_key(&value)
        } else {
            field(column).and_then(join_hash_key)
        })
    }
}

impl SecondaryIndexProjector for JoinProjection {
    fn project(
        &self,
        entity: &UnifiedEntity,
        key: &mut [u8; SECONDARY_KEY_BYTES_MAX],
    ) -> Result<Option<usize>, StoreError> {
        // Retained versions can still be visible (for example an aborted
        // delete). Leave visibility to the reader's snapshot.
        Ok(match self.key(entity) {
            Ok(posting) => posting.map(|value| write_posting_key(value, key).len()),
            Err(()) => {
                key[0] = UNCOVERED[0];
                Some(UNCOVERED.len())
            }
        })
    }
}

fn write_posting_key(value: JoinHashKey, key: &mut [u8]) -> &[u8] {
    match value {
        JoinHashKey::Number(bits) => {
            key[0] = 1;
            key[1..9].copy_from_slice(&bits.to_le_bytes());
            &key[..9]
        }
        JoinHashKey::Text(digest) => {
            key[0] = 2;
            key[1..33].copy_from_slice(&digest);
            &key[..33]
        }
    }
}

impl RuntimeHashIndex {
    pub(super) fn join_postings(
        &self,
        keys: &[JoinHashKey],
    ) -> Result<Option<JoinHashCandidates>, HashIndexError> {
        let Some((name, identity)) = &self.join_index else {
            return Ok(None);
        };
        if keys.len() > PROBE_KEYS_MAX {
            return Ok(None);
        }
        let Some(inner) = self.runtime.upgrade() else {
            return Err(read_error("runtime closed"));
        };
        let runtime = RedDBRuntime {
            inner,
            background_tasks: None,
        };
        let Some(reservation) = runtime.try_reserve_query_buffer(
            POSTINGS_MAX * std::mem::size_of::<(JoinHashKey, EntityId)>(),
        ) else {
            return Ok(None);
        };
        let store = runtime.db().store();
        let index = {
            // Pin the trees without waiting for a checkpoint to publish.
            let Some(_publication) = store.vault_publication_lock.try_lock() else {
                return Ok(None);
            };
            let index = store.secondary_index_unfenced(&self.collection, name, identity);
            // V1 covers numeric keys but cannot establish absence of text.
            index.or_else(|| {
                if keys.iter().all(|key| matches!(key, JoinHashKey::Number(_))) {
                    let numeric_identity =
                        join_identity(&self.identity, 1, b"document-hash-join-numeric-v1");
                    store.secondary_index_unfenced(&self.collection, name, &numeric_identity)
                } else {
                    None
                }
            })
        };
        let Some(index) = index else {
            return Ok(None);
        };
        if index
            .candidates(&UNCOVERED)
            .map_err(storage_error)?
            .next_id()
            .map_err(storage_error)?
            .is_some()
        {
            return Ok(None);
        }
        let mut postings = Vec::with_capacity(POSTINGS_MAX);
        let mut key_bytes = [0; 33];
        for &key in keys {
            let mut cursor = index
                .candidates(write_posting_key(key, &mut key_bytes))
                .map_err(storage_error)?;
            while let Some(id) = cursor.next_id().map_err(storage_error)? {
                if postings.len() == POSTINGS_MAX {
                    return Ok(None);
                }
                postings.push((key, id));
            }
        }
        // Disk reads are complete. Verify that the pinned postings still cover
        // the installed base, then merge the resident rows under the fence.
        let Some(_publication) = store.vault_publication_lock.try_lock() else {
            return Ok(None);
        };
        let Some(manager) = store.get_collection(&self.collection) else {
            return Ok(None);
        };
        let Some(base) = manager.backing_source() else {
            return Ok(None);
        };
        if !index.covers_source(base.as_ref()) {
            return Ok(None);
        }
        postings.retain(|(_, id)| !manager.backing_row_is_shadowed(*id));
        let base_postings = postings.len();

        let projection = JoinProjection(Arc::clone(&self.projection));
        let mut resident_rows = 0;
        let mut remaining_bytes = RESIDENT_BYTES_MAX;
        let mut covered = true;
        manager.for_each_entity(|entity| {
            let bytes = crate::storage::unified::memory_size::entity_bytes(entity);
            if resident_rows == RESIDENT_ROWS_MAX
                || bytes > PROBE_ROW_BYTES_MAX
                || bytes > remaining_bytes
            {
                covered = false;
                return false;
            }
            resident_rows += 1;
            remaining_bytes -= bytes;
            match projection.key(entity) {
                Ok(Some(key)) if keys.binary_search(&key).is_ok() => {
                    if postings.len() == POSTINGS_MAX {
                        covered = false;
                        return false;
                    }
                    postings.push((key, entity.id));
                }
                Ok(_) => {}
                Err(()) => {
                    covered = false;
                    return false;
                }
            }
            true
        });
        if !covered {
            return Ok(None);
        }
        Ok(Some(JoinHashCandidates {
            resident_postings: postings.len() - base_postings,
            postings,
            resident_rows,
            _reservation: Box::new(reservation),
        }))
    }
}