reddb-io-server 1.43.20

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
//! Use the published HASH join projection before reading any document bodies.
use super::*;
use crate::catalog::CollectionModel;
use crate::runtime::impl_core::capture_current_snapshot;
use crate::runtime::index_store::IndexMethodKind;
use crate::runtime::paged_hash_index::{join_hash_key, PROBE_KEYS_MAX, PROBE_ROW_BYTES_MAX};
use crate::runtime::record_search::{
    runtime_table_record_from_entity_ref_with_schema, set_source_collection,
};
use crate::runtime::table_row_mvcc_resolver::TableRowMvccReadResolver;
use crate::storage::query::planner::CanonicalLogicalNode;
use crate::storage::unified::hash_index::JoinHashCandidates;
use crate::storage::StoreError;
use reddb_rql::ast::TableSource;

type JoinInputs = (Vec<UnifiedRecord>, Vec<UnifiedRecord>);

pub(super) fn try_inputs(
    runtime: &RedDBRuntime,
    node: &CanonicalLogicalNode,
    query: &JoinQuery,
    join_type: &JoinType,
    fields: [&FieldRef; 2],
) -> RedDBResult<Option<JoinInputs>> {
    let sources = [query.left.as_ref(), query.right.as_ref()];
    let [QueryExpr::Table(left), QueryExpr::Table(right)] = sources else {
        return Ok(None);
    };
    let tables = [left, right];
    if crate::runtime::execution_context::current_tenant().is_some()
        || crate::runtime::function_budget::stored_function_active()
        || tables.iter().zip(&node.children).any(|(table, child)| {
            !matches!(table.source, None | Some(TableSource::Name(_)))
                || table.as_of.is_some()
                || !child.children.is_empty()
                || !matches!(child.operator.as_str(), "table_scan" | "index_seek")
                || runtime.is_rls_enabled(&table.table)
        })
    {
        return Ok(None);
    }
    let db = runtime.db();
    let models = tables.map(|table| {
        db.collection_contract_arc(&table.table)
            .map(|c| c.declared_model)
    });
    let document_side = match (models, join_type) {
        (
            [Some(CollectionModel::Document), Some(CollectionModel::Table)],
            JoinType::Inner | JoinType::RightOuter,
        ) => 0,
        (
            [Some(CollectionModel::Table), Some(CollectionModel::Document)],
            JoinType::Inner | JoinType::LeftOuter,
        ) => 1,
        _ => return Ok(None),
    };
    let probe_side = 1 - document_side;
    let document = tables[document_side];
    let FieldRef::TableColumn { table, column } = fields[document_side] else {
        return Ok(None);
    };
    if !table.is_empty() && table != &document.table && document.alias.as_ref() != Some(table) {
        return Ok(None);
    }
    let collection = document.table.as_str();
    let indexes = runtime.index_store_ref();
    let Some(index) = indexes.find_hash_index_for_column(collection, column) else {
        return Ok(None);
    };
    if index.method != IndexMethodKind::Hash
        || !indexes.hash.is_paged(collection, &index.name)
        || !super::super::runtime_indexes_queryable(collection, indexes)
    {
        return Ok(None);
    }
    let Some(snapshot) = capture_current_snapshot() else {
        return Ok(None);
    };
    if snapshot.branch.is_some()
        || snapshot.serializable_reader.is_some()
        || crate::runtime::dml_target_scan::snapshot_requires_index_fallback_for(
            &snapshot, collection,
        )
    {
        return Ok(None);
    }
    let generation = indexes.indexed_mutation_generation_for(collection);
    let current = || {
        !indexes.indexed_mutation_active_for(collection)
            && generation == indexes.indexed_mutation_generation_for(collection)
            && !snapshot
                .manager
                .real_writer_of_began_after(&snapshot.snapshot, collection)
    };
    if !current() || !indexes.await_insert_publications(collection, Some(&snapshot.snapshot)) {
        return Ok(None);
    }
    let probe = execute_runtime_canonical_expr_node(
        runtime,
        &node.children[probe_side],
        sources[probe_side],
    )?;
    let probe_table = tables[probe_side];
    let mut keys = Vec::new();
    let mut covered = probe.len() <= PROBE_KEYS_MAX;
    if covered {
        for row in &probe {
            match resolve_runtime_field(
                row,
                fields[probe_side],
                Some(&probe_table.table),
                probe_table.alias.as_deref(),
            ) {
                None | Some(Value::Null) => {}
                Some(value) => match join_hash_key(&value) {
                    Some(key) => keys.push(key),
                    None => {
                        covered = false;
                        break;
                    }
                },
            }
        }
    }
    keys.sort_unstable();
    keys.dedup();
    let candidates = if covered && current() {
        indexes
            .hash
            .lookup_join_batch(collection, &index.name, &keys)
            .map_err(|error| RedDBError::Internal(error.to_string()))?
    } else {
        None
    };
    let mut documents = None;
    if let Some(mut candidates) = candidates {
        // Match the physical scan order before the existing join loop.
        // A seal can move a segment between the growing and sealed scans.
        candidates
            .postings
            .sort_unstable_by_key(|(key, rid)| (*rid, *key));
        candidates.postings.dedup();
        documents = load_documents(runtime, document, fields[document_side], &candidates)?;
    }
    let documents = match documents {
        Some(records) if current() => records,
        _ => execute_runtime_canonical_expr_node(
            runtime,
            &node.children[document_side],
            sources[document_side],
        )?,
    };
    Ok(Some(if document_side == 0 {
        (documents, probe)
    } else {
        (probe, documents)
    }))
}

fn load_documents(
    runtime: &RedDBRuntime,
    document: &TableQuery,
    field: &FieldRef,
    candidates: &JoinHashCandidates,
) -> RedDBResult<Option<Vec<UnifiedRecord>>> {
    let postings = &candidates.postings;
    let db = runtime.db();
    let collection = document.table.as_str();
    let Some(manager) = db.store().get_collection(collection) else {
        return Ok(None);
    };
    let Some(_memory) =
        runtime.try_reserve_query_buffer(PROBE_ROW_BYTES_MAX * 3 * postings.len().max(1))
    else {
        return Ok(None);
    };
    let rids: Vec<_> = postings.iter().map(|(_, rid)| *rid).collect();
    let schema = manager.column_schema();
    let resolver = TableRowMvccReadResolver::current_statement();
    let mut records = Vec::with_capacity(postings.len());
    let mut found = 0;
    let result = manager.try_for_each_id(&rids, PROBE_ROW_BYTES_MAX, |position, entity| {
        if !matches!(entity.kind, EntityKind::TableRow { .. }) {
            return false;
        }
        if resolver.resolve_candidate(entity).is_none()
            || !db.entity_visible_at_read(collection, entity)
        {
            found += 1;
            return true;
        }
        let Some(mut record) =
            runtime_table_record_from_entity_ref_with_schema(entity, schema.as_ref())
        else {
            return false;
        };
        set_source_collection(&mut record, collection);
        let actual =
            resolve_runtime_field(&record, field, Some(collection), document.alias.as_deref())
                .as_ref()
                .and_then(join_hash_key);
        if actual != Some(postings[position].0) {
            return false;
        }
        found += 1;
        records.push(record);
        true
    });
    match result {
        Ok(()) if found == postings.len() => {
            crate::runtime::function_budget::charge(found as u64)?;
            tracing::debug!(
                collection,
                candidates = found,
                resident_postings = candidates.resident_postings,
                "paged HASH document join"
            );
            Ok(Some(records))
        }
        Ok(()) | Err(StoreError::ReadLimitExceeded { .. }) => Ok(None),
        Err(error) => Err(error.into()),
    }
}