diff --git a/sandbox/libs/analytics-framework/src/main/java/org/opensearch/analytics/spi/AnalyticsSearchBackendPlugin.java b/sandbox/libs/analytics-framework/src/main/java/org/opensearch/analytics/spi/AnalyticsSearchBackendPlugin.java index e7c6125df7320..274cd039d3a3f 100644 --- a/sandbox/libs/analytics-framework/src/main/java/org/opensearch/analytics/spi/AnalyticsSearchBackendPlugin.java +++ b/sandbox/libs/analytics-framework/src/main/java/org/opensearch/analytics/spi/AnalyticsSearchBackendPlugin.java @@ -112,12 +112,20 @@ default FilterDelegationHandle getFilterDelegationHandle(ListThe driving backend registers the handle so that FFM upcalls from Rust - * (createProvider, createCollector, collectDocs) route to it. + * (createProvider, createCollector, collectDocs) route to the correct per-query binding. * - * @param handle the delegation handle from the accepting backend + * @param contextId the per-query identifier (task ID), threaded through every FFM upcall + * @param handle the delegation handle from the accepting backend + * @param tracker the thread tracker for resource attribution, or {@code null} * @param backendContext the driving backend's execution context (from instruction handlers) + * @return a cleanup action that must be called (in a finally block) after query execution */ - default void configureFilterDelegation(FilterDelegationHandle handle, BackendExecutionContext backendContext) { + default Runnable configureFilterDelegation( + long contextId, + FilterDelegationHandle handle, + DelegationThreadTracker tracker, + BackendExecutionContext backendContext + ) { throw new UnsupportedOperationException("configureFilterDelegation not implemented for [" + name() + "]"); } @@ -153,12 +161,6 @@ default EngineResultStream fetchByRowIds(Reader reader, BigIntVector rowIdVector throw new UnsupportedOperationException("fetchByRowIds not implemented for [" + name() + "]"); } - /** - * Install a thread tracker for attribution of delegation callbacks executing on foreign threads. - * Called after {@link #configureFilterDelegation}. Pass {@code null} to clear. - */ - default void setDelegationThreadTracker(DelegationThreadTracker tracker) {} - /** * Converts a backend-specific exception into an appropriate OpenSearch exception type. * diff --git a/sandbox/plugins/analytics-backend-datafusion/rust/src/indexed_executor.rs b/sandbox/plugins/analytics-backend-datafusion/rust/src/indexed_executor.rs index efd504c2f96b8..6238d0c8ab4af 100644 --- a/sandbox/plugins/analytics-backend-datafusion/rust/src/indexed_executor.rs +++ b/sandbox/plugins/analytics-backend-datafusion/rust/src/indexed_executor.rs @@ -475,6 +475,10 @@ async unsafe fn execute_indexed_with_context_inner( let object_metas = handle.object_metas; let writer_generations = handle.writer_generations; let query_context = handle.query_context; + // Extract context_id early so it can be captured by the per-segment closures + // below. The closures pass it through every FFM upcall so Java can route each + // callback to the correct per-query FilterDelegationHandle and DelegationThreadTracker. + let context_id = query_context.context_id(); // SessionContext already has RuntimeEnv, caches, memory pool, UDF from create_session_context_indexed. // Deregister the default ListingTable (registered by create_session_context) — will be replaced @@ -612,7 +616,7 @@ async unsafe fn execute_indexed_with_context_inner( let correctness_provider: Option> = match single_collector_id(&extraction.tree) { Some(annotation_id) => Some(Arc::new( - create_provider(annotation_id) + create_provider(context_id, annotation_id) .map_err(|e| DataFusionError::External(e.into()))?, )), None => None, @@ -660,6 +664,7 @@ async unsafe fn execute_indexed_with_context_inner( let collector_opt: Option> = match &correctness_provider { Some(provider) => { let collector = FfmSegmentCollector::create( + context_id, provider.key(), segment.writer_generation, chunk.doc_min, @@ -667,7 +672,8 @@ async unsafe fn execute_indexed_with_context_inner( ) .map_err(|e| { format!( - "FfmSegmentCollector::create(provider={}, writer_generation={}, doc_range=[{},{})): {}", + "FfmSegmentCollector::create(context_id={}, provider={}, writer_generation={}, doc_range=[{},{})): {}", + context_id, provider.key(), segment.writer_generation, chunk.doc_min, @@ -695,6 +701,7 @@ async unsafe fn execute_indexed_with_context_inner( Arc::clone(&performance_provider_locks), segment.writer_generation, Arc::new(crate::indexed_table::eval::single_collector::FfmDelegatedBackendCollectorFactory), + context_id, )); Ok(eval) }, @@ -716,7 +723,8 @@ async unsafe fn execute_indexed_with_context_inner( let mut providers: Vec> = Vec::with_capacity(leaf_ids.len()); for annotation_id in &leaf_ids { providers.push(Arc::new( - create_provider(*annotation_id).map_err(|e| DataFusionError::External(e.into()))?, + create_provider(context_id, *annotation_id) + .map_err(|e| DataFusionError::External(e.into()))?, )); } let tree = Arc::new(tree); @@ -752,6 +760,7 @@ async unsafe fn execute_indexed_with_context_inner( Vec::with_capacity(providers.len()); for (idx, provider) in providers.iter().enumerate() { let collector = FfmSegmentCollector::create( + context_id, provider.key(), segment.writer_generation, chunk.doc_min, @@ -836,7 +845,6 @@ async unsafe fn execute_indexed_with_context_inner( let (cross_rt_stream, abort_handle) = CrossRtStream::new_with_df_error_stream_cancellable(df_stream, cpu_executor); - let context_id = query_context.context_id(); if let Some(h) = abort_handle { crate::query_tracker::set_abort_handle(context_id, h); } diff --git a/sandbox/plugins/analytics-backend-datafusion/rust/src/indexed_table/eval/single_collector.rs b/sandbox/plugins/analytics-backend-datafusion/rust/src/indexed_table/eval/single_collector.rs index d7a407d83a649..b23c24427e2a6 100644 --- a/sandbox/plugins/analytics-backend-datafusion/rust/src/indexed_table/eval/single_collector.rs +++ b/sandbox/plugins/analytics-backend-datafusion/rust/src/indexed_table/eval/single_collector.rs @@ -55,6 +55,9 @@ const HARDCODED_SELECTIVITY_THRESHOLD: f64 = 0.05; /// wraps `FfmSegmentCollector::create` (Java/Lucene round-trip); fuzz tests inject a /// mock that replays a pre-computed bitset without an FFM call. /// +/// `context_id` is the per-query identifier passed through to every FFM upcall so Java +/// can route each callback to the correct per-query handle and tracker. +/// /// TODO: extend this factory to also build the *correctness* collector currently passed /// in pre-built by `indexed_executor.rs`. Today delegated-backend (perf-delegated) /// collectors are built inside this evaluator while correctness collectors are built @@ -63,6 +66,7 @@ const HARDCODED_SELECTIVITY_THRESHOLD: f64 = 0.05; pub trait DelegatedBackendCollectorFactory: Send + Sync + std::fmt::Debug { fn create( &self, + context_id: i64, provider_key: i32, writer_generation: i64, doc_min: i32, @@ -78,12 +82,13 @@ pub struct FfmDelegatedBackendCollectorFactory; impl DelegatedBackendCollectorFactory for FfmDelegatedBackendCollectorFactory { fn create( &self, + context_id: i64, provider_key: i32, writer_generation: i64, doc_min: i32, doc_max: i32, ) -> Result, String> { - let collector = FfmSegmentCollector::create(provider_key, writer_generation, doc_min, doc_max)?; + let collector = FfmSegmentCollector::create(context_id, provider_key, writer_generation, doc_min, doc_max)?; Ok(Arc::new(collector) as Arc) } } @@ -166,6 +171,9 @@ pub struct SingleCollectorEvaluator { /// wires `FfmDelegatedBackendCollectorFactory`; fuzz tests inject a mock that /// replays a pre-computed bitset without an FFM call. delegated_backend_collector_factory: Arc, + /// Per-query context identifier passed through every FFM upcall so Java can route + /// each callback to the correct per-query `FilterDelegationHandle` and tracker. + context_id: i64, } impl SingleCollectorEvaluator { @@ -180,6 +188,7 @@ impl SingleCollectorEvaluator { performance_provider_locks: Arc>>>, writer_generation: i64, delegated_backend_collector_factory: Arc, + context_id: i64, ) -> Self { Self { collector, @@ -192,6 +201,7 @@ impl SingleCollectorEvaluator { performance_provider_locks, writer_generation, delegated_backend_collector_factory, + context_id, } } } @@ -366,24 +376,26 @@ impl RowGroupBitsetSource for SingleCollectorEvaluator { .performance_provider_locks .get(&annotation_id) .expect("annotation_id was just pulled from the map's keys"); + let context_id = self.context_id; let mut just_initialized = false; let provider = lock.get_or_init(|| { just_initialized = true; - create_provider(annotation_id).expect("create_provider FFM upcall failed") + create_provider(context_id, annotation_id).expect("create_provider FFM upcall failed") }); if just_initialized { log_debug!( - "[scf-rust] lazy provider initialized annotation_id={} provider_key={}", - annotation_id, provider.key() + "[scf-rust] lazy provider initialized context_id={} annotation_id={} provider_key={}", + context_id, annotation_id, provider.key() ); } let collector = self .delegated_backend_collector_factory - .create(provider.key(), self.writer_generation, min_doc, max_doc) + .create(context_id, provider.key(), self.writer_generation, min_doc, max_doc) .map_err(|e| { format!( - "DelegatedBackendCollectorFactory::create(provider={}, writer_generation={}, doc_range=[{},{})): {}", + "DelegatedBackendCollectorFactory::create(context_id={}, provider={}, writer_generation={}, doc_range=[{},{})): {}", + context_id, provider.key(), self.writer_generation, min_doc, @@ -632,7 +644,7 @@ mod tests { docs: vec![0, 3, 7], }) as Arc; let pruner = minimal_page_pruner(); - let eval = SingleCollectorEvaluator::new(Some(collector), pruner, None, None, None, None, CollectorCallStrategy::FullRange, Arc::new(HashMap::new()), 0, Arc::new(FfmDelegatedBackendCollectorFactory)); + let eval = SingleCollectorEvaluator::new(Some(collector), pruner, None, None, None, None, CollectorCallStrategy::FullRange, Arc::new(HashMap::new()), 0, Arc::new(FfmDelegatedBackendCollectorFactory), 0); let rg = RowGroupInfo { index: 0, @@ -648,7 +660,7 @@ mod tests { fn on_batch_mask_returns_none_for_path_b() { let collector = Arc::new(StubCollector { docs: vec![0] }) as Arc; let pruner = minimal_page_pruner(); - let eval = SingleCollectorEvaluator::new(Some(collector), pruner, None, None, None, None, CollectorCallStrategy::FullRange, Arc::new(HashMap::new()), 0, Arc::new(FfmDelegatedBackendCollectorFactory)); + let eval = SingleCollectorEvaluator::new(Some(collector), pruner, None, None, None, None, CollectorCallStrategy::FullRange, Arc::new(HashMap::new()), 0, Arc::new(FfmDelegatedBackendCollectorFactory), 0); let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)])); let batch = datafusion::arrow::record_batch::RecordBatch::try_new( schema, @@ -676,7 +688,7 @@ mod tests { // (it's the only post-decode filter we have on this path). let collector = Arc::new(StubCollector { docs: vec![0] }) as Arc; let pruner = minimal_page_pruner(); - let eval = SingleCollectorEvaluator::new(Some(collector), pruner, None, None, None, None, CollectorCallStrategy::FullRange, Arc::new(HashMap::new()), 0, Arc::new(FfmDelegatedBackendCollectorFactory)); + let eval = SingleCollectorEvaluator::new(Some(collector), pruner, None, None, None, None, CollectorCallStrategy::FullRange, Arc::new(HashMap::new()), 0, Arc::new(FfmDelegatedBackendCollectorFactory), 0); assert!(eval.needs_row_mask()); } @@ -684,7 +696,7 @@ mod tests { fn empty_match_returns_none() { let collector = Arc::new(StubCollector { docs: vec![] }) as Arc; let pruner = minimal_page_pruner(); - let eval = SingleCollectorEvaluator::new(Some(collector), pruner, None, None, None, None, CollectorCallStrategy::FullRange, Arc::new(HashMap::new()), 0, Arc::new(FfmDelegatedBackendCollectorFactory)); + let eval = SingleCollectorEvaluator::new(Some(collector), pruner, None, None, None, None, CollectorCallStrategy::FullRange, Arc::new(HashMap::new()), 0, Arc::new(FfmDelegatedBackendCollectorFactory), 0); let rg = RowGroupInfo { index: 0, first_row: 0, @@ -704,7 +716,7 @@ mod tests { docs: vec![0, 3, 7], }) as Arc; let pruner = minimal_page_pruner(); - let eval = SingleCollectorEvaluator::new(Some(collector), pruner, None, None, None, None, CollectorCallStrategy::FullRange, Arc::new(HashMap::new()), 0, Arc::new(FfmDelegatedBackendCollectorFactory)); + let eval = SingleCollectorEvaluator::new(Some(collector), pruner, None, None, None, None, CollectorCallStrategy::FullRange, Arc::new(HashMap::new()), 0, Arc::new(FfmDelegatedBackendCollectorFactory), 0); let rg = RowGroupInfo { index: 0, diff --git a/sandbox/plugins/analytics-backend-datafusion/rust/src/indexed_table/ffm_callbacks.rs b/sandbox/plugins/analytics-backend-datafusion/rust/src/indexed_table/ffm_callbacks.rs index 4934f87d3aeee..7810b35054745 100644 --- a/sandbox/plugins/analytics-backend-datafusion/rust/src/indexed_table/ffm_callbacks.rs +++ b/sandbox/plugins/analytics-backend-datafusion/rust/src/indexed_table/ffm_callbacks.rs @@ -8,17 +8,21 @@ //! FFM upcall surface for index-filter providers and collectors. //! -//! Four callback slots, populated once at startup by +//! Five callback slots, populated once at startup by //! `df_register_filter_tree_callbacks` (see `ffm.rs`): //! -//! - `createProvider(annotationId) -> providerKey|-1` -//! - `createCollector(providerKey, writerGeneration, minDoc, maxDoc) -> collectorKey|-1` -//! - `collectDocs(collectorKey, minDoc, maxDoc, outBuf, outWordCap) -> wordsWritten|-1` -//! - `releaseCollector(collectorKey)` -//! - `releaseProvider(providerKey)` +//! - `createProvider(contextId, annotationId) -> providerKey|-1` +//! - `createCollector(contextId, providerKey, writerGeneration, minDoc, maxDoc) -> collectorKey|-1` +//! - `collectDocs(contextId, collectorKey, minDoc, maxDoc, outBuf, outWordCap) -> wordsWritten|-1` +//! - `releaseCollector(contextId, collectorKey)` +//! - `releaseProvider(contextId, providerKey)` //! //! `ProviderHandle` and `FfmSegmentCollector` are the lifetime wrappers — //! they call the release callbacks on drop. +//! +//! The `context_id` is the per-query identifier (from `QueryTrackingContext::context_id()`) +//! that Java uses to route each callback to the correct per-query handle and tracker, +//! eliminating the global-singleton concurrency bug when multiple queries run in parallel. use std::sync::atomic::{AtomicPtr, Ordering}; @@ -26,14 +30,15 @@ use super::index::RowGroupDocsCollector; // ── Callback signatures ─────────────────────────────────────────────── -type CreateProviderFn = unsafe extern "C" fn(i32) -> i32; -type ReleaseProviderFn = unsafe extern "C" fn(i32); -/// `(provider_key, writer_generation, doc_min, doc_max) -> collector_key | -1`. +type CreateProviderFn = unsafe extern "C" fn(i64, i32) -> i32; +type ReleaseProviderFn = unsafe extern "C" fn(i64, i32); +/// `(context_id, provider_key, writer_generation, doc_min, doc_max) -> collector_key | -1`. /// -/// `writer_generation` is the stable per-segment identifier -type CreateCollectorFn = unsafe extern "C" fn(i32, i64, i32, i32) -> i32; -type CollectDocsFn = unsafe extern "C" fn(i32, i32, i32, *mut u64, i64) -> i64; -type ReleaseCollectorFn = unsafe extern "C" fn(i32); +/// `writer_generation` is the stable per-segment identifier. +/// `context_id` routes the upcall to the correct per-query Java handle. +type CreateCollectorFn = unsafe extern "C" fn(i64, i32, i64, i32, i32) -> i32; +type CollectDocsFn = unsafe extern "C" fn(i64, i32, i32, i32, *mut u64, i64) -> i64; +type ReleaseCollectorFn = unsafe extern "C" fn(i64, i32); static CREATE_PROVIDER: AtomicPtr<()> = AtomicPtr::new(std::ptr::null_mut()); static RELEASE_PROVIDER: AtomicPtr<()> = AtomicPtr::new(std::ptr::null_mut()); @@ -111,6 +116,7 @@ fn load_release_collector() -> Option { /// Returned from `create_provider`. Drop releases the provider. pub struct ProviderHandle { + context_id: i64, key: i32, } @@ -124,13 +130,14 @@ impl ProviderHandle { /// callback isn't registered, which is always the case in unit/fuzz tests. #[cfg(test)] pub fn new_for_test(key: i32) -> Self { - ProviderHandle { key } + ProviderHandle { context_id: 0, key } } } impl std::fmt::Debug for ProviderHandle { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("ProviderHandle") + .field("context_id", &self.context_id) .field("key", &self.key) .finish() } @@ -139,51 +146,59 @@ impl std::fmt::Debug for ProviderHandle { impl Drop for ProviderHandle { fn drop(&mut self) { if let Some(release) = load_release_provider() { - unsafe { release(self.key) }; + unsafe { release(self.context_id, self.key) }; } } } /// Create a provider by annotation ID by upcalling Java. -pub fn create_provider(annotation_id: i32) -> Result { +/// +/// `context_id` is the per-query identifier used by Java to route this upcall +/// to the correct per-query `FilterDelegationHandle`. +pub fn create_provider(context_id: i64, annotation_id: i32) -> Result { let create = load_create_provider()?; - let key = unsafe { create(annotation_id) }; + let key = unsafe { create(context_id, annotation_id) }; if key < 0 { return Err(format!( - "createProvider failed: annotation_id={} -> {}", + "createProvider failed: context_id={} annotation_id={} -> {}", + context_id, annotation_id, key )); } - Ok(ProviderHandle { key }) + Ok(ProviderHandle { context_id, key }) } // ── FfmSegmentCollector — owns `releaseCollector` on drop ───────────── #[derive(Debug)] pub struct FfmSegmentCollector { + context_id: i64, key: i32, } impl FfmSegmentCollector { /// Ask Java for a collector keyed by `provider_key` for the given segment/doc range. /// + /// `context_id` is the per-query identifier used by Java to route this upcall + /// to the correct per-query `FilterDelegationHandle`. /// `writer_generation` identifies the segment. pub fn create( + context_id: i64, provider_key: i32, writer_generation: i64, doc_min: i32, doc_max: i32, ) -> Result { let create = load_create_collector()?; - let key = unsafe { create(provider_key, writer_generation, doc_min, doc_max) }; + let key = unsafe { create(context_id, provider_key, writer_generation, doc_min, doc_max) }; if key < 0 { return Err(format!( - "createCollector(provider={}, writer_generation={}) failed: {}", - provider_key, writer_generation, key + "createCollector(context_id={}, provider={}, writer_generation={}) failed: {}", + context_id, provider_key, writer_generation, key )); } - Ok(FfmSegmentCollector { key }) + Ok(FfmSegmentCollector { context_id, key }) } } @@ -198,6 +213,7 @@ impl RowGroupDocsCollector for FfmSegmentCollector { let collect_fn = load_collect_docs()?; let n = unsafe { collect_fn( + self.context_id, self.key, min_doc, max_doc, @@ -206,7 +222,10 @@ impl RowGroupDocsCollector for FfmSegmentCollector { ) }; if n < 0 { - return Err(format!("collectDocs(key={}) failed: {}", self.key, n)); + return Err(format!( + "collectDocs(context_id={}, key={}) failed: {}", + self.context_id, self.key, n + )); } // Defensive: the Java callback is contracted to return // `wordsWritten <= outWordCap`. If it lied, the buffer already @@ -216,9 +235,9 @@ impl RowGroupDocsCollector for FfmSegmentCollector { let n = n as usize; if n > word_count { return Err(format!( - "collectDocs(key={}) reported wordsWritten={} > capacity={}; \ + "collectDocs(context_id={}, key={}) reported wordsWritten={} > capacity={}; \ callback contract violated (possible heap overflow)", - self.key, n, word_count, + self.context_id, self.key, n, word_count, )); } buf.truncate(n); @@ -229,7 +248,7 @@ impl RowGroupDocsCollector for FfmSegmentCollector { impl Drop for FfmSegmentCollector { fn drop(&mut self) { if let Some(release) = load_release_collector() { - unsafe { release(self.key) }; + unsafe { release(self.context_id, self.key) }; } } } diff --git a/sandbox/plugins/analytics-backend-datafusion/rust/src/indexed_table/tests_e2e/fuzz/delegation.rs b/sandbox/plugins/analytics-backend-datafusion/rust/src/indexed_table/tests_e2e/fuzz/delegation.rs index 599971432c362..92ee01c5cde47 100644 --- a/sandbox/plugins/analytics-backend-datafusion/rust/src/indexed_table/tests_e2e/fuzz/delegation.rs +++ b/sandbox/plugins/analytics-backend-datafusion/rust/src/indexed_table/tests_e2e/fuzz/delegation.rs @@ -240,6 +240,7 @@ struct MockDelegatedBackendCollectorFactory { impl DelegatedBackendCollectorFactory for MockDelegatedBackendCollectorFactory { fn create( &self, + _context_id: i64, provider_key: i32, _writer_generation: i64, _doc_min: i32, @@ -420,6 +421,7 @@ pub(in crate::indexed_table::tests_e2e) async fn execute_delegation_tree( Arc::clone(&provider_locks), segment.writer_generation, Arc::clone(&factory), + 0, )); Ok(eval) }) diff --git a/sandbox/plugins/analytics-backend-datafusion/rust/src/indexed_table/tests_e2e/fuzz/harness.rs b/sandbox/plugins/analytics-backend-datafusion/rust/src/indexed_table/tests_e2e/fuzz/harness.rs index 1a7f8583022cb..0e0a6bb86ec43 100644 --- a/sandbox/plugins/analytics-backend-datafusion/rust/src/indexed_table/tests_e2e/fuzz/harness.rs +++ b/sandbox/plugins/analytics-backend-datafusion/rust/src/indexed_table/tests_e2e/fuzz/harness.rs @@ -401,6 +401,7 @@ pub(in crate::indexed_table::tests_e2e) async fn execute_tree_single_collector( std::sync::Arc::new(std::collections::HashMap::new()), segment.writer_generation, std::sync::Arc::new(crate::indexed_table::eval::single_collector::FfmDelegatedBackendCollectorFactory), + 0, )); let _ = segment; Ok(eval) diff --git a/sandbox/plugins/analytics-backend-datafusion/rust/src/indexed_table/tests_e2e/multi_segment.rs b/sandbox/plugins/analytics-backend-datafusion/rust/src/indexed_table/tests_e2e/multi_segment.rs index cb9b53840a772..42d63bb8df214 100644 --- a/sandbox/plugins/analytics-backend-datafusion/rust/src/indexed_table/tests_e2e/multi_segment.rs +++ b/sandbox/plugins/analytics-backend-datafusion/rust/src/indexed_table/tests_e2e/multi_segment.rs @@ -159,6 +159,7 @@ async fn run_two_segment_query( std::sync::Arc::new(std::collections::HashMap::new()), segment.writer_generation, std::sync::Arc::new(crate::indexed_table::eval::single_collector::FfmDelegatedBackendCollectorFactory), + 0, ), ); Ok(eval) @@ -362,6 +363,7 @@ async fn run_segments(specs: Vec, num_partitions: usize) -> Vec<(i32, S std::sync::Arc::new(std::collections::HashMap::new()), segment.writer_generation, std::sync::Arc::new(crate::indexed_table::eval::single_collector::FfmDelegatedBackendCollectorFactory), + 0, ), ); Ok(eval) diff --git a/sandbox/plugins/analytics-backend-datafusion/rust/src/indexed_table/tests_e2e/page_pruning.rs b/sandbox/plugins/analytics-backend-datafusion/rust/src/indexed_table/tests_e2e/page_pruning.rs index 8415fdd2a3ecc..7d019535f22f4 100644 --- a/sandbox/plugins/analytics-backend-datafusion/rust/src/indexed_table/tests_e2e/page_pruning.rs +++ b/sandbox/plugins/analytics-backend-datafusion/rust/src/indexed_table/tests_e2e/page_pruning.rs @@ -361,6 +361,7 @@ async fn run_single_collector( std::sync::Arc::new(std::collections::HashMap::new()), segment.writer_generation, std::sync::Arc::new(crate::indexed_table::eval::single_collector::FfmDelegatedBackendCollectorFactory), + 0, )); Ok(eval) }) diff --git a/sandbox/plugins/analytics-backend-datafusion/src/main/java/org/opensearch/be/datafusion/DataFusionAnalyticsBackendPlugin.java b/sandbox/plugins/analytics-backend-datafusion/src/main/java/org/opensearch/be/datafusion/DataFusionAnalyticsBackendPlugin.java index 0dfb97e06cfe4..7dba353453901 100644 --- a/sandbox/plugins/analytics-backend-datafusion/src/main/java/org/opensearch/be/datafusion/DataFusionAnalyticsBackendPlugin.java +++ b/sandbox/plugins/analytics-backend-datafusion/src/main/java/org/opensearch/be/datafusion/DataFusionAnalyticsBackendPlugin.java @@ -13,6 +13,9 @@ import org.apache.calcite.sql.SqlOperator; import org.apache.calcite.sql.fun.SqlLibraryOperators; import org.apache.calcite.sql.fun.SqlStdOperatorTable; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.message.ParameterizedMessage; import org.opensearch.analytics.backend.EngineResultStream; import org.opensearch.analytics.spi.AbstractNameMappingAdapter; import org.opensearch.analytics.spi.AggregateCapability; @@ -68,6 +71,8 @@ */ public class DataFusionAnalyticsBackendPlugin implements AnalyticsSearchBackendPlugin { + private static final Logger LOGGER = LogManager.getLogger(DataFusionAnalyticsBackendPlugin.class); + private static final Set ENGINE_CAPS = Set.of(EngineCapability.SORT, EngineCapability.UNION, EngineCapability.VALUES); private static final Set SUPPORTED_FIELD_TYPES = new HashSet<>(); @@ -823,11 +828,27 @@ public ExchangeSink createSink(ExchangeSinkContext ctx, BackendExecutionContext }; } + /** + * Context-aware override: registers the handle and tracker under {@code contextId} + * so that concurrent queries each have their own isolated FFM callback binding. + * Returns a cleanup action that removes the binding when execution finishes. + */ @Override - public void configureFilterDelegation(FilterDelegationHandle handle, BackendExecutionContext backendContext) { - // Install the handle as the FFM upcall target. All Rust callbacks - // (createProvider, createCollector, collectDocs, release*) route to it. - FilterTreeCallbacks.setHandle(handle); + public Runnable configureFilterDelegation( + long contextId, + FilterDelegationHandle handle, + DelegationThreadTracker tracker, + BackendExecutionContext backendContext + ) { + FilterTreeCallbacks.register(contextId, handle, tracker); + return () -> { + FilterTreeCallbacks.unregister(contextId); + try { + handle.close(); + } catch (Exception e) { + LOGGER.warn(new ParameterizedMessage("FilterDelegationHandle.close() failed for contextId={}", contextId), e); + } + }; } @Override @@ -876,11 +897,6 @@ public EngineResultStream fetchByRowIds(Reader reader, BigIntVector rowIdVector, return new DatafusionResultStream(streamHandle, allocator); } - @Override - public void setDelegationThreadTracker(DelegationThreadTracker tracker) { - FilterTreeCallbacks.setThreadTracker(tracker); - } - public Exception convertException(Exception original) { return NativeErrorConverter.convert(original); } diff --git a/sandbox/plugins/analytics-backend-datafusion/src/main/java/org/opensearch/be/datafusion/indexfilter/FilterTreeCallbacks.java b/sandbox/plugins/analytics-backend-datafusion/src/main/java/org/opensearch/be/datafusion/indexfilter/FilterTreeCallbacks.java index 04ac08e2902f4..a6a2984592c37 100644 --- a/sandbox/plugins/analytics-backend-datafusion/src/main/java/org/opensearch/be/datafusion/indexfilter/FilterTreeCallbacks.java +++ b/sandbox/plugins/analytics-backend-datafusion/src/main/java/org/opensearch/be/datafusion/indexfilter/FilterTreeCallbacks.java @@ -15,112 +15,184 @@ import org.opensearch.analytics.spi.FilterDelegationHandle; import java.lang.foreign.MemorySegment; -import java.util.concurrent.atomic.AtomicReference; +import java.util.concurrent.ConcurrentHashMap; /** * Static callback targets invoked by the native engine via FFM upcalls. * - *

All calls delegate to the currently installed {@link FilterDelegationHandle}. - * The handle is set per-query-per-shard before execution and cleared after. + *

Each callback receives a {@code contextId} (the per-query identifier assigned by + * {@code QueryTrackingContext}) as its first argument, which is used to look up the + * correct per-query {@link FilterDelegationHandle} and {@link DelegationThreadTracker} + * from {@link #BINDINGS}. This eliminates the global-singleton race condition that + * existed when concurrent queries shared a single AtomicReference. + * + *

Lifecycle

+ *
    + *
  1. Before query execution: {@link #register(long, FilterDelegationHandle, DelegationThreadTracker)} + * installs a binding for the query's contextId.
  2. + *
  3. FFM upcalls route to the correct per-query handle via contextId.
  4. + *
  5. After query completion: {@link #unregister(long)} removes the binding.
  6. + *
* *

Error-handling contract

*

Every method catches all {@link Throwable}s and returns {@code -1} * (or silently returns for void methods). A Java exception escaping through * an FFM upcall stub crashes the JVM. * - * // TODO: remove old Registries-based code path and CollectorRegistry/FilterProviderRegistry - * // once all tests are migrated to the FilterDelegationHandle path. + *

Lifecycle assertions

+ *

When assertions are enabled ({@code -ea}, default in tests and {@code ./gradlew run}), + * the callbacks {@code assert} that a binding exists before performing the upcall, and + * {@link #register} asserts no stale binding is left behind. These catch lifecycle bugs + * (double-register, premature unregister, leaked bindings) during development without + * affecting production behavior — assertions are off in production, where the same paths + * fall back to returning -1 silently. */ public final class FilterTreeCallbacks { private static final Logger LOGGER = LogManager.getLogger(FilterTreeCallbacks.class); - private static final AtomicReference HANDLE = new AtomicReference<>(); - private static final AtomicReference TRACKER = new AtomicReference<>(); + /** + * Per-query binding of handle and tracker, keyed by contextId. + * ConcurrentHashMap provides safe concurrent access across parallel queries. + */ + private static final ConcurrentHashMap BINDINGS = new ConcurrentHashMap<>(); + + /** Immutable pair of handle + tracker for a single query. */ + private record QueryBinding(FilterDelegationHandle handle, DelegationThreadTracker tracker) { + } private FilterTreeCallbacks() {} /** - * Install the delegation handle for the current execution. - * Called by {@code configureFilterDelegation} before query execution. - * Tests may call with {@code null} to reset. + * Register a per-query binding keyed by {@code contextId}. + * Must be called before query execution begins. + * + *

Asserts no prior binding exists for {@code contextId}. A pre-existing binding + * indicates a leaked binding from an earlier query (missing {@link #unregister}) or + * a duplicate register call. + * + * @param contextId the per-query identifier (from the native {@code QueryTrackingContext}) + * @param handle the delegation handle for this query (must not be null) + * @param tracker the thread tracker for this query (may be null) */ - public static void setHandle(FilterDelegationHandle handle) { - HANDLE.set(handle); + public static void register(long contextId, FilterDelegationHandle handle, DelegationThreadTracker tracker) { + QueryBinding prev = BINDINGS.put(contextId, new QueryBinding(handle, tracker)); + assert prev == null : "FilterTreeCallbacks.register: binding already present for contextId=" + contextId; } /** - * Install or clear the thread tracker for resource attribution. + * Remove the per-query binding for {@code contextId}. + * Must be called after query execution completes (in a finally block). + * + *

Idempotent — calling with no current binding is a no-op. */ - public static void setThreadTracker(DelegationThreadTracker tracker) { - TRACKER.set(tracker); + public static void unregister(long contextId) { + BINDINGS.remove(contextId); } - private static long trackStart() { - DelegationThreadTracker t = TRACKER.get(); + private static long trackStart(long contextId) { + QueryBinding binding = BINDINGS.get(contextId); + if (binding == null) return -1; + DelegationThreadTracker t = binding.tracker(); return (t != null) ? t.trackStart() : -1; } - private static void trackEnd(long threadId) { + private static void trackEnd(long contextId, long threadId) { if (threadId < 0) return; - DelegationThreadTracker t = TRACKER.get(); + QueryBinding binding = BINDINGS.get(contextId); + if (binding == null) return; + DelegationThreadTracker t = binding.tracker(); if (t != null) t.trackEnd(threadId); } + /** + * Asserts a binding exists. Lifecycle bugs (premature unregister, missing register, + * stale Rust handle outliving its query) trip this in tests; production silently + * returns -1 from the caller's null check. + * + *

Throws {@link AssertionError} when assertions are enabled and binding is null. + * Upcall methods catch {@code Throwable} and re-throw {@code AssertionError} so it + * surfaces in tests (causing the JVM to exit through the FFM stub) rather than + * being silently logged. + */ + private static void assertBindingExists(QueryBinding binding, String op, long contextId) { + assert binding != null : "FilterTreeCallbacks." + + op + + ": no binding for contextId=" + + contextId + + " (registered: " + + BINDINGS.keySet() + + ")"; + } + // ── Provider lifecycle (cold path, once per query) ──────────────── /** - * {@code createProvider(annotationId) -> providerKey|-1}. + * {@code createProvider(contextId, annotationId) -> providerKey|-1}. */ - public static int createProvider(int annotationId) { - long tid = trackStart(); + public static int createProvider(long contextId, int annotationId) { + long tid = trackStart(contextId); try { - FilterDelegationHandle handle = HANDLE.get(); - if (handle == null) { + QueryBinding binding = BINDINGS.get(contextId); + assertBindingExists(binding, "createProvider", contextId); + if (binding == null || binding.handle() == null) { return -1; } - return handle.createProvider(annotationId); + return binding.handle().createProvider(annotationId); + } catch (AssertionError e) { + // Propagate so lifecycle bugs surface in tests; in production -ea is off and this branch never runs. + throw e; } catch (Throwable throwable) { - LOGGER.error("createProvider failed for annotationId=" + annotationId, throwable); + LOGGER.error("createProvider failed for contextId=" + contextId + " annotationId=" + annotationId, throwable); return -1; } finally { - trackEnd(tid); + trackEnd(contextId, tid); } } /** - * {@code releaseProvider(providerKey)}. Never throws. + * {@code releaseProvider(contextId, providerKey)}. Never throws. */ - public static void releaseProvider(int providerKey) { + public static void releaseProvider(long contextId, int providerKey) { try { - FilterDelegationHandle handle = HANDLE.get(); - if (handle != null) { - handle.releaseProvider(providerKey); + QueryBinding binding = BINDINGS.get(contextId); + assertBindingExists(binding, "releaseProvider", contextId); + if (binding != null && binding.handle() != null) { + binding.handle().releaseProvider(providerKey); } + } catch (AssertionError e) { + throw e; } catch (Throwable throwable) { - LOGGER.error(new ParameterizedMessage("releaseProvider({}) failed", providerKey), throwable); + LOGGER.error( + new ParameterizedMessage("releaseProvider(contextId={}, providerKey={}) failed", contextId, providerKey), + throwable + ); } } // ── Collector lifecycle (hot path, per segment per query) ───────── /** - * {@code createCollector(providerKey, writerGeneration, minDoc, maxDoc) -> collectorKey|-1}. + * {@code createCollector(contextId, providerKey, writerGeneration, minDoc, maxDoc) -> collectorKey|-1}. * - *

Segments are identified by writer generation + *

Segments are identified by writer generation. */ - public static int createCollector(int providerKey, long writerGeneration, int minDoc, int maxDoc) { - long tid = trackStart(); + public static int createCollector(long contextId, int providerKey, long writerGeneration, int minDoc, int maxDoc) { + long tid = trackStart(contextId); try { - FilterDelegationHandle handle = HANDLE.get(); - if (handle == null) { + QueryBinding binding = BINDINGS.get(contextId); + assertBindingExists(binding, "createCollector", contextId); + if (binding == null || binding.handle() == null) { return -1; } - return handle.createCollector(providerKey, writerGeneration, minDoc, maxDoc); + return binding.handle().createCollector(providerKey, writerGeneration, minDoc, maxDoc); + } catch (AssertionError e) { + throw e; } catch (Throwable throwable) { LOGGER.error( new ParameterizedMessage( - "createCollector(providerKey={}, writerGeneration={}, [{}, {})) failed", + "createCollector(contextId={}, providerKey={}, writerGeneration={}, [{}, {})) failed", + contextId, providerKey, writerGeneration, minDoc, @@ -130,20 +202,22 @@ public static int createCollector(int providerKey, long writerGeneration, int mi ); return -1; } finally { - trackEnd(tid); + trackEnd(contextId, tid); } } /** - * {@code collectDocs(collectorKey, minDoc, maxDoc, outPtr, outWordCap) -> wordsWritten|-1}. + * {@code collectDocs(contextId, collectorKey, minDoc, maxDoc, outPtr, outWordCap) -> wordsWritten|-1}. */ - public static long collectDocs(int collectorKey, int minDoc, int maxDoc, MemorySegment outPtr, long outWordCap) { - long tid = trackStart(); + public static long collectDocs(long contextId, int collectorKey, int minDoc, int maxDoc, MemorySegment outPtr, long outWordCap) { + long tid = trackStart(contextId); try { - FilterDelegationHandle handle = HANDLE.get(); - if (handle == null) { + QueryBinding binding = BINDINGS.get(contextId); + assertBindingExists(binding, "collectDocs", contextId); + if (binding == null || binding.handle() == null) { return -1L; } + FilterDelegationHandle handle = binding.handle(); if (handle.isCancelled()) { return -1L; } @@ -151,28 +225,42 @@ public static long collectDocs(int collectorKey, int minDoc, int maxDoc, MemoryS MemorySegment view = outPtr.reinterpret((long) maxWords * Long.BYTES); int wordsWritten = handle.collectDocs(collectorKey, minDoc, maxDoc, view); return (wordsWritten < 0) ? -1L : wordsWritten; + } catch (AssertionError e) { + throw e; } catch (Throwable throwable) { LOGGER.error( - new ParameterizedMessage("collectDocs(collectorKey={}, [{}, {})) failed", collectorKey, minDoc, maxDoc), + new ParameterizedMessage( + "collectDocs(contextId={}, collectorKey={}, [{}, {})) failed", + contextId, + collectorKey, + minDoc, + maxDoc + ), throwable ); return -1L; } finally { - trackEnd(tid); + trackEnd(contextId, tid); } } /** - * {@code releaseCollector(collectorKey)}. Never throws. + * {@code releaseCollector(contextId, collectorKey)}. Never throws. */ - public static void releaseCollector(int collectorKey) { + public static void releaseCollector(long contextId, int collectorKey) { try { - FilterDelegationHandle handle = HANDLE.get(); - if (handle != null) { - handle.releaseCollector(collectorKey); + QueryBinding binding = BINDINGS.get(contextId); + assertBindingExists(binding, "releaseCollector", contextId); + if (binding != null && binding.handle() != null) { + binding.handle().releaseCollector(collectorKey); } + } catch (AssertionError e) { + throw e; } catch (Throwable throwable) { - LOGGER.error(new ParameterizedMessage("releaseCollector({}) failed", collectorKey), throwable); + LOGGER.error( + new ParameterizedMessage("releaseCollector(contextId={}, collectorKey={}) failed", contextId, collectorKey), + throwable + ); } } } diff --git a/sandbox/plugins/analytics-backend-datafusion/src/main/java/org/opensearch/be/datafusion/nativelib/NativeBridge.java b/sandbox/plugins/analytics-backend-datafusion/src/main/java/org/opensearch/be/datafusion/nativelib/NativeBridge.java index 2a457956c5e51..28003e06f995e 100644 --- a/sandbox/plugins/analytics-backend-datafusion/src/main/java/org/opensearch/be/datafusion/nativelib/NativeBridge.java +++ b/sandbox/plugins/analytics-backend-datafusion/src/main/java/org/opensearch/be/datafusion/nativelib/NativeBridge.java @@ -530,25 +530,29 @@ private static void installFilterTreeCallbacks(Linker linker) { Class cb = org.opensearch.be.datafusion.indexfilter.FilterTreeCallbacks.class; var lookup = java.lang.invoke.MethodHandles.lookup(); + // All five callbacks now receive contextId (long) as their first parameter. + // Rust passes it through every FFM upcall; Java uses it to look up the + // correct per-query FilterDelegationHandle in FilterTreeCallbacks.BINDINGS. MethodHandle createProvider = lookup.findStatic( cb, "createProvider", - java.lang.invoke.MethodType.methodType(int.class, int.class) + java.lang.invoke.MethodType.methodType(int.class, long.class, int.class) ); MethodHandle releaseProvider = lookup.findStatic( cb, "releaseProvider", - java.lang.invoke.MethodType.methodType(void.class, int.class) + java.lang.invoke.MethodType.methodType(void.class, long.class, int.class) ); MethodHandle createCollector = lookup.findStatic( cb, "createCollector", - java.lang.invoke.MethodType.methodType(int.class, int.class, long.class, int.class, int.class) + java.lang.invoke.MethodType.methodType(int.class, long.class, int.class, long.class, int.class, int.class) ); MethodHandle collectDocs = lookup.findStatic( cb, "collectDocs", java.lang.invoke.MethodType.methodType( + long.class, long.class, int.class, int.class, @@ -560,23 +564,24 @@ private static void installFilterTreeCallbacks(Linker linker) { MethodHandle releaseCollector = lookup.findStatic( cb, "releaseCollector", - java.lang.invoke.MethodType.methodType(void.class, int.class) + java.lang.invoke.MethodType.methodType(void.class, long.class, int.class) ); java.lang.foreign.MemorySegment createProviderStub = linker.upcallStub( createProvider, - FunctionDescriptor.of(ValueLayout.JAVA_INT, ValueLayout.JAVA_INT), + FunctionDescriptor.of(ValueLayout.JAVA_INT, ValueLayout.JAVA_LONG, ValueLayout.JAVA_INT), arena ); java.lang.foreign.MemorySegment releaseProviderStub = linker.upcallStub( releaseProvider, - FunctionDescriptor.ofVoid(ValueLayout.JAVA_INT), + FunctionDescriptor.ofVoid(ValueLayout.JAVA_LONG, ValueLayout.JAVA_INT), arena ); java.lang.foreign.MemorySegment createCollectorStub = linker.upcallStub( createCollector, FunctionDescriptor.of( ValueLayout.JAVA_INT, + ValueLayout.JAVA_LONG, ValueLayout.JAVA_INT, ValueLayout.JAVA_LONG, ValueLayout.JAVA_INT, @@ -587,6 +592,7 @@ private static void installFilterTreeCallbacks(Linker linker) { java.lang.foreign.MemorySegment collectDocsStub = linker.upcallStub( collectDocs, FunctionDescriptor.of( + ValueLayout.JAVA_LONG, ValueLayout.JAVA_LONG, ValueLayout.JAVA_INT, ValueLayout.JAVA_INT, @@ -598,7 +604,7 @@ private static void installFilterTreeCallbacks(Linker linker) { ); java.lang.foreign.MemorySegment releaseCollectorStub = linker.upcallStub( releaseCollector, - FunctionDescriptor.ofVoid(ValueLayout.JAVA_INT), + FunctionDescriptor.ofVoid(ValueLayout.JAVA_LONG, ValueLayout.JAVA_INT), arena ); NativeCall.invokeVoid( diff --git a/sandbox/plugins/analytics-backend-datafusion/src/test/java/org/opensearch/be/datafusion/indexfilter/DelegationTaskTrackingTests.java b/sandbox/plugins/analytics-backend-datafusion/src/test/java/org/opensearch/be/datafusion/indexfilter/DelegationTaskTrackingTests.java index 05a93d24edaba..0f048de49c37b 100644 --- a/sandbox/plugins/analytics-backend-datafusion/src/test/java/org/opensearch/be/datafusion/indexfilter/DelegationTaskTrackingTests.java +++ b/sandbox/plugins/analytics-backend-datafusion/src/test/java/org/opensearch/be/datafusion/indexfilter/DelegationTaskTrackingTests.java @@ -34,9 +34,14 @@ /** * Tests verifying that FilterTreeCallbacks correctly attributes delegation * callback work to the AnalyticsShardTask via TaskResourceTrackingService. + * + *

Tests use contextId=0 directly via {@link FilterTreeCallbacks#register} / + * {@link FilterTreeCallbacks#unregister} to exercise the per-query binding path. */ public class DelegationTaskTrackingTests extends OpenSearchTestCase { + private static final long TEST_CONTEXT_ID = 0L; + private ThreadPool threadPool; private TaskResourceTrackingService trackingService; @@ -50,46 +55,44 @@ public void setUp() throws Exception { threadPool ); trackingService.setTaskResourceTrackingEnabled(true); - FilterTreeCallbacks.setHandle(null); - FilterTreeCallbacks.setThreadTracker(null); + // Clear any leftover bindings from a previous test. + FilterTreeCallbacks.unregister(TEST_CONTEXT_ID); } @Override public void tearDown() throws Exception { - FilterTreeCallbacks.setThreadTracker(null); - FilterTreeCallbacks.setHandle(null); + FilterTreeCallbacks.unregister(TEST_CONTEXT_ID); terminate(threadPool); super.tearDown(); } /** - * Tests the full production wiring: setDelegationThreadTracker via SPI, then - * all three callback methods (createProvider, createCollector, collectDocs) - * on a foreign thread. Verifies the thread is tracked against the task. + * Tests the full production wiring: register handle + tracker, then + * all five callback methods (createProvider, createCollector, collectDocs, + * releaseCollector, releaseProvider) on a foreign thread. + * Verifies the thread is tracked against the task. */ public void testAllCallbackMethodsTrackedOnForeignThread() throws Exception { AnalyticsShardTask task = createAndTrackTask(1); - var backendPlugin = new org.opensearch.be.datafusion.DataFusionAnalyticsBackendPlugin(null); - backendPlugin.setDelegationThreadTracker(createTracker(task.getId())); - FilterTreeCallbacks.setHandle(new MockHandle(new long[] { 0xCAFEL })); + FilterTreeCallbacks.register(TEST_CONTEXT_ID, new MockHandle(new long[] { 0xCAFEL }), createTracker(task.getId())); CountDownLatch done = new CountDownLatch(1); Thread foreignThread = new Thread(() -> { - int pk = FilterTreeCallbacks.createProvider(1); - int ck = FilterTreeCallbacks.createCollector(pk, 0, 0, 64); + int pk = FilterTreeCallbacks.createProvider(TEST_CONTEXT_ID, 1); + int ck = FilterTreeCallbacks.createCollector(TEST_CONTEXT_ID, pk, 0, 0, 64); try (Arena arena = Arena.ofConfined()) { MemorySegment buf = arena.allocate(Long.BYTES); - FilterTreeCallbacks.collectDocs(ck, 0, 64, buf, 1); + FilterTreeCallbacks.collectDocs(TEST_CONTEXT_ID, ck, 0, 64, buf, 1); } - FilterTreeCallbacks.releaseCollector(ck); - FilterTreeCallbacks.releaseProvider(pk); + FilterTreeCallbacks.releaseCollector(TEST_CONTEXT_ID, ck); + FilterTreeCallbacks.releaseProvider(TEST_CONTEXT_ID, pk); done.countDown(); }, "test-tokio-worker"); foreignThread.start(); assertTrue(done.await(5, TimeUnit.SECONDS)); - backendPlugin.setDelegationThreadTracker(null); + FilterTreeCallbacks.unregister(TEST_CONTEXT_ID); trackingService.stopTracking(task); Map> stats = task.getResourceStats(); @@ -97,37 +100,23 @@ public void testAllCallbackMethodsTrackedOnForeignThread() throws Exception { } /** - * Tests that clearing the thread tracker stops attribution. After clearing, - * callbacks on a new thread should NOT be attributed to the old task. + * Lifecycle assertion: invoking an upcall on a contextId that has no registered + * binding throws AssertionError when -ea is on. This catches premature unregister + * or stale Rust handles outliving their query. + * + * In production (no -ea), this same path silently returns -1 — the upcall's null + * check is the production safety net. */ - public void testClearTaskTrackingStopsAttribution() throws Exception { - AnalyticsShardTask task = createAndTrackTask(2); - - FilterTreeCallbacks.setThreadTracker(createTracker(task.getId())); - FilterTreeCallbacks.setHandle(new MockHandle(new long[] { 1L })); - - // Clear tracking BEFORE running callbacks - FilterTreeCallbacks.setThreadTracker(null); - - CountDownLatch done = new CountDownLatch(1); - Thread foreignThread = new Thread(() -> { - int pk = FilterTreeCallbacks.createProvider(1); - int ck = FilterTreeCallbacks.createCollector(pk, 0, 0, 64); - try (Arena arena = Arena.ofConfined()) { - MemorySegment buf = arena.allocate(Long.BYTES); - FilterTreeCallbacks.collectDocs(ck, 0, 64, buf, 1); - } - FilterTreeCallbacks.releaseCollector(ck); - FilterTreeCallbacks.releaseProvider(pk); - done.countDown(); - }, "post-clear-thread"); - foreignThread.start(); - assertTrue(done.await(5, TimeUnit.SECONDS)); - - trackingService.stopTracking(task); - - Map> stats = task.getResourceStats(); - assertFalse("Thread after clearing tracker should NOT be tracked", stats.containsKey(foreignThread.threadId())); + public void testUnregisteredContextIdAssertsInTests() throws Exception { + long unregisteredCtx = 9999L; + // Sanity: nothing registered for this contextId. + FilterTreeCallbacks.unregister(unregisteredCtx); + + AssertionError failure = expectThrows(AssertionError.class, () -> FilterTreeCallbacks.createProvider(unregisteredCtx, 1)); + assertTrue( + "AssertionError should mention the offending contextId. Got: " + failure.getMessage(), + failure.getMessage().contains("contextId=" + unregisteredCtx) + ); } /** @@ -136,8 +125,7 @@ public void testClearTaskTrackingStopsAttribution() throws Exception { public void testConcurrentThreadsAllTracked() throws Exception { AnalyticsShardTask task = createAndTrackTask(3); - FilterTreeCallbacks.setThreadTracker(createTracker(task.getId())); - FilterTreeCallbacks.setHandle(new MockHandle(new long[] { 0xFFL })); + FilterTreeCallbacks.register(TEST_CONTEXT_ID, new MockHandle(new long[] { 0xFFL }), createTracker(task.getId())); int threadCount = 4; CyclicBarrier barrier = new CyclicBarrier(threadCount); @@ -148,14 +136,14 @@ public void testConcurrentThreadsAllTracked() throws Exception { threads[i] = new Thread(() -> { try { barrier.await(5, TimeUnit.SECONDS); - int pk = FilterTreeCallbacks.createProvider(1); - int ck = FilterTreeCallbacks.createCollector(pk, 0, 0, 64); + int pk = FilterTreeCallbacks.createProvider(TEST_CONTEXT_ID, 1); + int ck = FilterTreeCallbacks.createCollector(TEST_CONTEXT_ID, pk, 0, 0, 64); try (Arena arena = Arena.ofConfined()) { MemorySegment buf = arena.allocate(Long.BYTES); - FilterTreeCallbacks.collectDocs(ck, 0, 64, buf, 1); + FilterTreeCallbacks.collectDocs(TEST_CONTEXT_ID, ck, 0, 64, buf, 1); } - FilterTreeCallbacks.releaseCollector(ck); - FilterTreeCallbacks.releaseProvider(pk); + FilterTreeCallbacks.releaseCollector(TEST_CONTEXT_ID, ck); + FilterTreeCallbacks.releaseProvider(TEST_CONTEXT_ID, pk); } catch (Exception e) { throw new RuntimeException(e); } finally { @@ -166,7 +154,7 @@ public void testConcurrentThreadsAllTracked() throws Exception { } assertTrue(done.await(10, TimeUnit.SECONDS)); - FilterTreeCallbacks.setThreadTracker(null); + FilterTreeCallbacks.unregister(TEST_CONTEXT_ID); trackingService.stopTracking(task); Map> stats = task.getResourceStats(); @@ -175,6 +163,117 @@ public void testConcurrentThreadsAllTracked() throws Exception { } } + /** + * Simulates the production concurrency bug: multiple queries register different + * handles and trackers, then fire upcalls concurrently on shared threads. + * + * Without per-query contextId isolation, this test fails because: + * - HANDLE race: collectDocs routes to the wrong handle -> returns -1 + * - TRACKER race: trackEnd routes to the wrong task -> IllegalStateException -> AssertionError + */ + public void testConcurrentQueriesIsolated() throws Exception { + int queryCount = 4; + int upcallsPerQuery = 10; + + AnalyticsShardTask[] tasks = new AnalyticsShardTask[queryCount]; + long[] contextIds = new long[queryCount]; + MockHandle[] handles = new MockHandle[queryCount]; + + for (int q = 0; q < queryCount; q++) { + tasks[q] = createAndTrackTask(100 + q); + contextIds[q] = tasks[q].getId(); + handles[q] = new MockHandle(new long[] { 0xABCD_0000L | q }); + FilterTreeCallbacks.register(contextIds[q], handles[q], createTracker(tasks[q].getId())); + } + + CyclicBarrier barrier = new CyclicBarrier(queryCount); + CountDownLatch done = new CountDownLatch(queryCount); + AssertionError[] errors = new AssertionError[queryCount]; + Thread[] threads = new Thread[queryCount]; + + for (int q = 0; q < queryCount; q++) { + final int queryIdx = q; + final long ctxId = contextIds[q]; + threads[q] = new Thread(() -> { + try { + barrier.await(5, TimeUnit.SECONDS); + for (int i = 0; i < upcallsPerQuery; i++) { + int pk = FilterTreeCallbacks.createProvider(ctxId, 1); + assertTrue("createProvider should succeed for query " + queryIdx, pk >= 0); + + int ck = FilterTreeCallbacks.createCollector(ctxId, pk, 0, 0, 64); + assertTrue("createCollector should succeed for query " + queryIdx, ck >= 0); + + try (Arena arena = Arena.ofConfined()) { + MemorySegment buf = arena.allocate(Long.BYTES); + long words = FilterTreeCallbacks.collectDocs(ctxId, ck, 0, 64, buf, 1); + assertTrue("collectDocs should succeed for query " + queryIdx + " (got " + words + ")", words >= 0); + + long value = buf.getAtIndex(ValueLayout.JAVA_LONG, 0); + long expected = 0xABCD_0000L | queryIdx; + assertEquals("collectDocs should return this query's data, not another query's", expected, value); + } + + FilterTreeCallbacks.releaseCollector(ctxId, ck); + FilterTreeCallbacks.releaseProvider(ctxId, pk); + } + } catch (AssertionError e) { + errors[queryIdx] = e; + } catch (Exception e) { + errors[queryIdx] = new AssertionError("Unexpected exception in query " + queryIdx, e); + } finally { + done.countDown(); + } + }, "concurrent-query-" + q); + threads[q].start(); + } + + assertTrue("All queries should complete within timeout", done.await(15, TimeUnit.SECONDS)); + + for (int q = 0; q < queryCount; q++) { + FilterTreeCallbacks.unregister(contextIds[q]); + trackingService.stopTracking(tasks[q]); + } + + // Check no assertion errors from any query thread + for (int q = 0; q < queryCount; q++) { + if (errors[q] != null) { + throw new AssertionError("Query " + q + " failed", errors[q]); + } + } + + // Verify each task was tracked on its own thread (not cross-contaminated) + for (int q = 0; q < queryCount; q++) { + Map> stats = tasks[q].getResourceStats(); + assertTrue( + "Task " + tasks[q].getId() + " should have tracking entries on thread " + threads[q].threadId(), + stats.containsKey(threads[q].threadId()) + ); + } + } + + /** + * Lifecycle assertion: registering a second binding for the same contextId without + * an intervening unregister trips the double-register assert. This catches leaked + * bindings (missing unregister) and accidental sharing of contextIds across queries. + */ + public void testDoubleRegisterAsserts() throws Exception { + long ctx = 1234L; + FilterTreeCallbacks.register(ctx, new MockHandle(new long[] { 1L }), null); + try { + AssertionError failure = expectThrows( + AssertionError.class, + () -> FilterTreeCallbacks.register(ctx, new MockHandle(new long[] { 2L }), null) + ); + assertTrue( + "AssertionError should mention the offending contextId. Got: " + failure.getMessage(), + failure.getMessage().contains("contextId=" + ctx) + ); + } finally { + FilterTreeCallbacks.unregister(ctx); + } + } + private DelegationThreadTracker createTracker(long taskId) { TaskResourceTrackingService service = trackingService; return new DelegationThreadTracker() { diff --git a/sandbox/plugins/analytics-backend-datafusion/src/test/java/org/opensearch/be/datafusion/indexfilter/IndexFilterCallbackTests.java b/sandbox/plugins/analytics-backend-datafusion/src/test/java/org/opensearch/be/datafusion/indexfilter/IndexFilterCallbackTests.java index 2c78d1af1cb4d..58dc6501f3abf 100644 --- a/sandbox/plugins/analytics-backend-datafusion/src/test/java/org/opensearch/be/datafusion/indexfilter/IndexFilterCallbackTests.java +++ b/sandbox/plugins/analytics-backend-datafusion/src/test/java/org/opensearch/be/datafusion/indexfilter/IndexFilterCallbackTests.java @@ -19,33 +19,38 @@ * Tests the Java-side FFM callback dispatch via {@link FilterTreeCallbacks} * routing to a {@link FilterDelegationHandle} without going through the full * substrait → native pipeline. + * + *

All callbacks now receive a {@code contextId} as their first argument. + * Tests use {@code contextId=0} via {@link FilterTreeCallbacks#register}. */ public class IndexFilterCallbackTests extends OpenSearchTestCase { + private static final long CTX = 0L; + @Override public void setUp() throws Exception { super.setUp(); - FilterTreeCallbacks.setHandle(null); + FilterTreeCallbacks.unregister(CTX); } @Override public void tearDown() throws Exception { - FilterTreeCallbacks.setHandle(null); + FilterTreeCallbacks.unregister(CTX); super.tearDown(); } public void testFullRoundTrip() { long[] cannedWords = new long[] { 0x5L, 0x3L }; MockHandle handle = new MockHandle(cannedWords); - FilterTreeCallbacks.setHandle(handle); + FilterTreeCallbacks.register(CTX, handle, null); // createProvider - int providerKey = FilterTreeCallbacks.createProvider(42); + int providerKey = FilterTreeCallbacks.createProvider(CTX, 42); assertTrue("providerKey >= 0", providerKey >= 0); assertEquals("handle received annotationId", 42, handle.lastAnnotationId); // createCollector - int collectorKey = FilterTreeCallbacks.createCollector(providerKey, 2L, 0, 128); + int collectorKey = FilterTreeCallbacks.createCollector(CTX, providerKey, 2L, 0, 128); assertTrue("collectorKey >= 0", collectorKey >= 0); assertEquals("handle received providerKey", providerKey, handle.lastProviderKey); assertEquals("handle received writerGeneration", 2L, handle.lastWriterGeneration); @@ -55,35 +60,39 @@ public void testFullRoundTrip() { // collectDocs try (Arena arena = Arena.ofConfined()) { MemorySegment buf = arena.allocate(Long.BYTES * 2); - long wordsWritten = FilterTreeCallbacks.collectDocs(collectorKey, 0, 128, buf, 2); + long wordsWritten = FilterTreeCallbacks.collectDocs(CTX, collectorKey, 0, 128, buf, 2); assertEquals("wordsWritten matches canned length", 2L, wordsWritten); assertEquals(0x5L, buf.getAtIndex(ValueLayout.JAVA_LONG, 0)); assertEquals(0x3L, buf.getAtIndex(ValueLayout.JAVA_LONG, 1)); } // releaseCollector - FilterTreeCallbacks.releaseCollector(collectorKey); + FilterTreeCallbacks.releaseCollector(CTX, collectorKey); assertEquals("handle received collectorKey for release", collectorKey, handle.lastReleasedCollectorKey); // releaseProvider - FilterTreeCallbacks.releaseProvider(providerKey); + FilterTreeCallbacks.releaseProvider(CTX, providerKey); assertEquals("handle received providerKey for release", providerKey, handle.lastReleasedProviderKey); } - public void testNoHandleReturnsNegativeOne() { - FilterTreeCallbacks.setHandle(null); - assertEquals(-1, FilterTreeCallbacks.createProvider(1)); - assertEquals(-1, FilterTreeCallbacks.createCollector(1, 0L, 0, 64)); - try (Arena arena = Arena.ofConfined()) { - MemorySegment buf = arena.allocate(Long.BYTES); - assertEquals(-1L, FilterTreeCallbacks.collectDocs(1, 0, 64, buf, 1)); - } - } - - public void testReleaseWithNoHandleIsSafe() { - FilterTreeCallbacks.setHandle(null); - FilterTreeCallbacks.releaseCollector(Integer.MAX_VALUE); - FilterTreeCallbacks.releaseProvider(Integer.MAX_VALUE); + /** + * Lifecycle assertion: invoking an upcall on an unregistered contextId trips + * {@code assert binding != null}. With {@code -ea} on (test default), this throws + * AssertionError rather than silently returning -1 — surfacing missing-register + * or premature-unregister bugs. + */ + public void testUnregisteredContextIdAsserts() { + FilterTreeCallbacks.unregister(CTX); + expectThrows(AssertionError.class, () -> FilterTreeCallbacks.createProvider(CTX, 1)); + expectThrows(AssertionError.class, () -> FilterTreeCallbacks.createCollector(CTX, 1, 0L, 0, 64)); + expectThrows(AssertionError.class, () -> { + try (Arena arena = Arena.ofConfined()) { + MemorySegment buf = arena.allocate(Long.BYTES); + FilterTreeCallbacks.collectDocs(CTX, 1, 0, 64, buf, 1); + } + }); + expectThrows(AssertionError.class, () -> FilterTreeCallbacks.releaseCollector(CTX, Integer.MAX_VALUE)); + expectThrows(AssertionError.class, () -> FilterTreeCallbacks.releaseProvider(CTX, Integer.MAX_VALUE)); } public void testHandleReturningNegativeOnePropagates() { @@ -112,13 +121,13 @@ public void releaseProvider(int providerKey) {} @Override public void close() {} }; - FilterTreeCallbacks.setHandle(failingHandle); + FilterTreeCallbacks.register(CTX, failingHandle, null); - assertEquals(-1, FilterTreeCallbacks.createProvider(1)); - assertEquals(-1, FilterTreeCallbacks.createCollector(1, 0L, 0, 64)); + assertEquals(-1, FilterTreeCallbacks.createProvider(CTX, 1)); + assertEquals(-1, FilterTreeCallbacks.createCollector(CTX, 1, 0L, 0, 64)); try (Arena arena = Arena.ofConfined()) { MemorySegment buf = arena.allocate(Long.BYTES); - assertEquals(-1L, FilterTreeCallbacks.collectDocs(1, 0, 64, buf, 1)); + assertEquals(-1L, FilterTreeCallbacks.collectDocs(CTX, 1, 0, 64, buf, 1)); } } diff --git a/sandbox/plugins/analytics-engine/src/main/java/org/opensearch/analytics/exec/AnalyticsSearchService.java b/sandbox/plugins/analytics-engine/src/main/java/org/opensearch/analytics/exec/AnalyticsSearchService.java index 47fb48682eb78..fb282267cf0e3 100644 --- a/sandbox/plugins/analytics-engine/src/main/java/org/opensearch/analytics/exec/AnalyticsSearchService.java +++ b/sandbox/plugins/analytics-engine/src/main/java/org/opensearch/analytics/exec/AnalyticsSearchService.java @@ -325,15 +325,24 @@ private FragmentResources startFragment(FragmentExecutionRequest request, Resolv // (e.g., Lucene + Tantivy), group expressions by acceptingBackendId and create one handle per group. DelegationDescriptor delegation = resolved.plan.getDelegationDescriptor(); if (delegation != null) { + // Filter delegation routes per-query state via taskId; without a task we cannot + // isolate concurrent queries from each other. Validate before allocating any + // delegation resources to avoid leaks. + if (task == null) { + throw new IllegalStateException("Filter delegation requires a tracked task for per-query isolation"); + } + long contextId = task.getId(); + String acceptingBackendId = delegation.delegatedExpressions().getFirst().getAcceptingBackendId(); AnalyticsSearchBackendPlugin acceptingBackend = backends.get(acceptingBackendId); FilterDelegationHandle handle = acceptingBackend.getFilterDelegationHandle(delegation.delegatedExpressions(), ctx); - backend.configureFilterDelegation(handle, backendContext); - if (task != null && taskResourceTrackingService != null) { + // Build a thread tracker when task resource tracking is available. + DelegationThreadTracker tracker = null; + if (taskResourceTrackingService != null) { long taskId = task.getId(); TaskResourceTrackingService service = taskResourceTrackingService; - backend.setDelegationThreadTracker(new DelegationThreadTracker() { + tracker = new DelegationThreadTracker() { @Override public long trackStart() { long threadId = Thread.currentThread().threadId(); @@ -345,9 +354,13 @@ public long trackStart() { public void trackEnd(long threadId) { service.taskExecutionFinishedOnThread(taskId, threadId); } - }); - trackerCleanup = () -> backend.setDelegationThreadTracker(null); + }; } + + // Register handle and tracker together under the query's contextId so concurrent + // queries have isolated FFM callback bindings. The returned cleanup removes the + // binding after query execution completes. + trackerCleanup = backend.configureFilterDelegation(contextId, handle, tracker, backendContext); } engine = backend.getSearchExecEngineProvider().createSearchExecEngine(ctx, backendContext); diff --git a/sandbox/plugins/analytics-engine/src/main/java/org/opensearch/analytics/exec/FragmentResources.java b/sandbox/plugins/analytics-engine/src/main/java/org/opensearch/analytics/exec/FragmentResources.java index 69af5e863c740..7ddfa371bea20 100644 --- a/sandbox/plugins/analytics-engine/src/main/java/org/opensearch/analytics/exec/FragmentResources.java +++ b/sandbox/plugins/analytics-engine/src/main/java/org/opensearch/analytics/exec/FragmentResources.java @@ -77,17 +77,22 @@ public EngineResultStream stream() { @Override public void close() throws Exception { - Exception first = null; + // Close the stream and engine first so any in-flight release upcalls from native + // code (e.g. ProviderHandle::drop -> releaseProvider) can still find their + // per-query binding in FilterTreeCallbacks. Running onClose first would unregister + // the binding while release upcalls are still pending, causing the eager release + // of Lucene resources to be skipped. + Exception first = closeQuietly(stream, null); + first = closeQuietly(engine, first); + first = closeQuietly(rowIdVector, first); if (onClose != null) { try { onClose.run(); } catch (Exception e) { - first = e; + if (first == null) first = e; + else first.addSuppressed(e); } } - first = closeQuietly(stream, first); - first = closeQuietly(engine, first); - first = closeQuietly(rowIdVector, first); // Release (not close) — the store's reaper closes after keepAlive, and the QTF // fetch phase may still need this reader before then. if (readerContext != null) {