From 747ef467050819c6c920715806c4a618e9d691de Mon Sep 17 00:00:00 2001 From: Aravind Sagar Date: Wed, 27 May 2026 05:43:31 +0000 Subject: [PATCH 1/5] Fix filter delegation concurrency bug by threading context_id through FFM upcalls FilterTreeCallbacks used global AtomicReference singletons for HANDLE and TRACKER. Under concurrent indexed-path queries, these were overwritten by the last query to enter startFragment, causing: - Query failures: collectDocs routed to wrong query's Lucene handle -> -1 - Tracking mis-attribution: trackEnd routed to wrong task -> AssertionError Fix: pass context_id (= OpenSearch task ID, already available in Rust from QueryTrackingContext) as the first parameter of every FFM upcall. Java uses it to look up the correct (handle, tracker) pair from a ConcurrentHashMap keyed by contextId. Each query gets isolated bindings. Additionally guards trackStart against same-thread double-tracking (the original Slack-reported variant) by checking isThreadTrackedForTask before calling taskExecutionStartedOnThread. Signed-off-by: Aravind Sagar Co-Authored-By: Claude Opus 4.6 (1M context) --- .../spi/AnalyticsSearchBackendPlugin.java | 20 +- .../rust/src/indexed_executor.rs | 16 +- .../indexed_table/eval/single_collector.rs | 34 ++- .../rust/src/indexed_table/ffm_callbacks.rs | 71 +++-- .../tests_e2e/fuzz/delegation.rs | 2 + .../indexed_table/tests_e2e/fuzz/harness.rs | 1 + .../indexed_table/tests_e2e/multi_segment.rs | 2 + .../indexed_table/tests_e2e/page_pruning.rs | 1 + .../DataFusionAnalyticsBackendPlugin.java | 22 +- .../indexfilter/FilterTreeCallbacks.java | 149 +++++++---- .../be/datafusion/nativelib/NativeBridge.java | 20 +- .../DelegationTaskTrackingTests.java | 246 +++++++++++++++--- .../indexfilter/IndexFilterCallbackTests.java | 43 +-- .../exec/AnalyticsSearchService.java | 21 +- .../tasks/TaskResourceTrackingService.java | 8 +- 15 files changed, 474 insertions(+), 182 deletions(-) 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 66f43d483f96e..dfde1eac563f5 100644 --- a/sandbox/plugins/analytics-backend-datafusion/rust/src/indexed_executor.rs +++ b/sandbox/plugins/analytics-backend-datafusion/rust/src/indexed_executor.rs @@ -460,6 +460,10 @@ pub async unsafe fn execute_indexed_with_context( 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 @@ -597,7 +601,7 @@ pub async unsafe fn execute_indexed_with_context( 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, @@ -645,6 +649,7 @@ pub async unsafe fn execute_indexed_with_context( let collector_opt: Option> = match &correctness_provider { Some(provider) => { let collector = FfmSegmentCollector::create( + context_id, provider.key(), segment.writer_generation, chunk.doc_min, @@ -652,7 +657,8 @@ pub async unsafe fn execute_indexed_with_context( ) .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, @@ -680,6 +686,7 @@ pub async unsafe fn execute_indexed_with_context( Arc::clone(&performance_provider_locks), segment.writer_generation, Arc::new(crate::indexed_table::eval::single_collector::FfmDelegatedBackendCollectorFactory), + context_id, )); Ok(eval) }, @@ -701,7 +708,8 @@ pub async unsafe fn execute_indexed_with_context( 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); @@ -737,6 +745,7 @@ pub async unsafe fn execute_indexed_with_context( 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, @@ -821,7 +830,6 @@ pub async unsafe fn execute_indexed_with_context( 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..748dabeb9d40b 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 @@ -11,14 +11,18 @@ //! Four 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 b59d04cdd2f80..315ca223441ef 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 @@ -805,11 +805,20 @@ 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); } @Override @@ -858,11 +867,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..832bc55b918c0 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,139 @@ 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. */ 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. + * + * @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) { + BINDINGS.put(contextId, new QueryBinding(handle, tracker)); } /** - * 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). */ - 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); } // ── 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); + if (binding == null || binding.handle() == null) { return -1; } - return handle.createProvider(annotationId); + return binding.handle().createProvider(annotationId); } 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); + if (binding != null && binding.handle() != null) { + binding.handle().releaseProvider(providerKey); } } 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); + if (binding == null || binding.handle() == null) { return -1; } - return handle.createCollector(providerKey, writerGeneration, minDoc, maxDoc); + return binding.handle().createCollector(providerKey, writerGeneration, minDoc, maxDoc); } catch (Throwable throwable) { LOGGER.error( new ParameterizedMessage( - "createCollector(providerKey={}, writerGeneration={}, [{}, {})) failed", + "createCollector(contextId={}, providerKey={}, writerGeneration={}, [{}, {})) failed", + contextId, providerKey, writerGeneration, minDoc, @@ -130,20 +157,21 @@ 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); + if (binding == null || binding.handle() == null) { return -1L; } + FilterDelegationHandle handle = binding.handle(); if (handle.isCancelled()) { return -1L; } @@ -153,26 +181,35 @@ public static long collectDocs(int collectorKey, int minDoc, int maxDoc, MemoryS return (wordsWritten < 0) ? -1L : wordsWritten; } 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); + if (binding != null && binding.handle() != null) { + binding.handle().releaseCollector(collectorKey); } } 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..e5c99952cfe6b 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,28 +100,29 @@ 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. + * Tests that clearing the thread tracker (via unregister) stops attribution. + * After clearing, callbacks on a new thread should NOT be attributed to the old task. */ public void testClearTaskTrackingStopsAttribution() throws Exception { AnalyticsShardTask task = createAndTrackTask(2); - FilterTreeCallbacks.setThreadTracker(createTracker(task.getId())); - FilterTreeCallbacks.setHandle(new MockHandle(new long[] { 1L })); + FilterTreeCallbacks.register(TEST_CONTEXT_ID, new MockHandle(new long[] { 1L }), createTracker(task.getId())); // Clear tracking BEFORE running callbacks - FilterTreeCallbacks.setThreadTracker(null); + FilterTreeCallbacks.unregister(TEST_CONTEXT_ID); CountDownLatch done = new CountDownLatch(1); Thread foreignThread = new Thread(() -> { - int pk = FilterTreeCallbacks.createProvider(1); - int ck = FilterTreeCallbacks.createCollector(pk, 0, 0, 64); + // With no binding, createProvider returns -1 (safe no-op); remaining calls + // also find no binding and return -1 or do nothing. + 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(); }, "post-clear-thread"); foreignThread.start(); @@ -136,8 +140,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 +151,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 +169,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 +178,181 @@ 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()) + ); + } + } + + /** + * Demonstrates why per-query isolation is necessary. When multiple queries share + * the same contextId (simulating the old global singleton behavior), concurrent + * upcalls read the wrong handle and get incorrect results. + * + * This test is expected to FAIL if all queries share a single contextId (the old bug). + * It passes only because each query has its own contextId. + */ + public void testSharedContextIdCausesDataCorruption() throws Exception { + int queryCount = 4; + long SHARED_CONTEXT_ID = 999L; + + MockHandle[] handles = new MockHandle[queryCount]; + for (int q = 0; q < queryCount; q++) { + handles[q] = new MockHandle(new long[] { 0xABCD_0000L | q }); + } + + CyclicBarrier barrier = new CyclicBarrier(queryCount); + CountDownLatch done = new CountDownLatch(queryCount); + int[] corruptionCount = new int[queryCount]; + + Thread[] threads = new Thread[queryCount]; + for (int q = 0; q < queryCount; q++) { + final int queryIdx = q; + threads[q] = new Thread(() -> { + try { + barrier.await(5, TimeUnit.SECONDS); + for (int i = 0; i < 20; i++) { + // Each iteration overwrites the shared binding — last writer wins + FilterTreeCallbacks.register(SHARED_CONTEXT_ID, handles[queryIdx], null); + + int pk = FilterTreeCallbacks.createProvider(SHARED_CONTEXT_ID, 1); + if (pk < 0) { + corruptionCount[queryIdx]++; + continue; + } + int ck = FilterTreeCallbacks.createCollector(SHARED_CONTEXT_ID, pk, 0, 0, 64); + if (ck < 0) { + corruptionCount[queryIdx]++; + FilterTreeCallbacks.releaseProvider(SHARED_CONTEXT_ID, pk); + continue; + } + + try (Arena arena = Arena.ofConfined()) { + MemorySegment buf = arena.allocate(Long.BYTES); + long words = FilterTreeCallbacks.collectDocs(SHARED_CONTEXT_ID, ck, 0, 64, buf, 1); + if (words < 0) { + corruptionCount[queryIdx]++; + } else { + long value = buf.getAtIndex(ValueLayout.JAVA_LONG, 0); + long expected = 0xABCD_0000L | queryIdx; + if (value != expected) { + corruptionCount[queryIdx]++; + } + } + } + FilterTreeCallbacks.releaseCollector(SHARED_CONTEXT_ID, ck); + FilterTreeCallbacks.releaseProvider(SHARED_CONTEXT_ID, pk); + } + } catch (Exception e) { + corruptionCount[queryIdx] += 100; + } finally { + done.countDown(); + } + }, "shared-ctx-query-" + q); + threads[q].start(); + } + + assertTrue(done.await(15, TimeUnit.SECONDS)); + FilterTreeCallbacks.unregister(SHARED_CONTEXT_ID); + + int totalCorruption = 0; + for (int c : corruptionCount) + totalCorruption += c; + + assertTrue( + "With a shared contextId, concurrent queries SHOULD see data corruption " + + "(wrong handle's data returned). Got " + + totalCorruption + + " corruptions out of " + + (queryCount * 20) + + " attempts. If this is 0, the test is not exercising the race.", + totalCorruption > 0 + ); + } + 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..7f59058b66673 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,35 @@ 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)); + FilterTreeCallbacks.unregister(CTX); + 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)); } } public void testReleaseWithNoHandleIsSafe() { - FilterTreeCallbacks.setHandle(null); - FilterTreeCallbacks.releaseCollector(Integer.MAX_VALUE); - FilterTreeCallbacks.releaseProvider(Integer.MAX_VALUE); + FilterTreeCallbacks.unregister(CTX); + FilterTreeCallbacks.releaseCollector(CTX, Integer.MAX_VALUE); + FilterTreeCallbacks.releaseProvider(CTX, Integer.MAX_VALUE); } public void testHandleReturningNegativeOnePropagates() { @@ -112,13 +117,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 d62652df0c3d5..c221294848dfd 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 @@ -327,15 +327,20 @@ private FragmentResources startFragment(FragmentExecutionRequest request, Resolv String acceptingBackendId = delegation.delegatedExpressions().getFirst().getAcceptingBackendId(); AnalyticsSearchBackendPlugin acceptingBackend = backends.get(acceptingBackendId); FilterDelegationHandle handle = acceptingBackend.getFilterDelegationHandle(delegation.delegatedExpressions(), ctx); - backend.configureFilterDelegation(handle, backendContext); + // Build a thread tracker when task resource tracking is available. + DelegationThreadTracker tracker = null; if (task != null && taskResourceTrackingService != null) { long taskId = task.getId(); TaskResourceTrackingService service = taskResourceTrackingService; - backend.setDelegationThreadTracker(new DelegationThreadTracker() { + Task trackedTask = task; + tracker = new DelegationThreadTracker() { @Override public long trackStart() { long threadId = Thread.currentThread().threadId(); + if (service.isThreadTrackedForTask(trackedTask, threadId)) { + return -1; + } service.taskExecutionStartedOnThread(taskId, threadId); return threadId; } @@ -344,9 +349,17 @@ 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. + if (task == null) { + throw new IllegalStateException("Filter delegation requires a tracked task for per-query isolation"); + } + long contextId = task.getId(); + trackerCleanup = backend.configureFilterDelegation(contextId, handle, tracker, backendContext); } engine = backend.getSearchExecEngineProvider().createSearchExecEngine(ctx, backendContext); diff --git a/server/src/main/java/org/opensearch/tasks/TaskResourceTrackingService.java b/server/src/main/java/org/opensearch/tasks/TaskResourceTrackingService.java index 645e8e93bda04..caa82c9c5ae27 100644 --- a/server/src/main/java/org/opensearch/tasks/TaskResourceTrackingService.java +++ b/server/src/main/java/org/opensearch/tasks/TaskResourceTrackingService.java @@ -233,10 +233,8 @@ private ResourceUsageMetric[] getResourceUsageMetricsForThread(long threadId) { return new ResourceUsageMetric[] { currentMemoryUsage, currentCPUUsage }; } - private boolean isCurrentThreadWorkingOnTask(Task task) { - long threadId = Thread.currentThread().threadId(); + public boolean isThreadTrackedForTask(Task task, long threadId) { List threadResourceInfos = task.getResourceStats().getOrDefault(threadId, Collections.emptyList()); - for (ThreadResourceInfo threadResourceInfo : threadResourceInfos) { if (threadResourceInfo.isActive()) { return true; @@ -245,6 +243,10 @@ private boolean isCurrentThreadWorkingOnTask(Task task) { return false; } + private boolean isCurrentThreadWorkingOnTask(Task task) { + return isThreadTrackedForTask(task, Thread.currentThread().threadId()); + } + private List getThreadsWorkingOnTask(Task task) { List activeThreads = new ArrayList<>(); for (List threadResourceInfos : task.getResourceStats().values()) { From f94151cac85ccf1048a6d67898237f1109a3ef86 Mon Sep 17 00:00:00 2001 From: Aravind Sagar Date: Wed, 27 May 2026 09:04:42 +0000 Subject: [PATCH 2/5] Remove redundant double-tracking guard in DelegationThreadTracker MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The isThreadTrackedForTask check guarded against the same-thread double-tracking scenario from the original Slack report. That scenario is structurally impossible on current main: cpu_executor.spawn(...).await in df_execute_with_context (commit 19b99d8300f) ensures all FFM upcalls fire on datafusion-cpu workers, never on the runTask thread that TaskAwareRunnable pre-tracked. Removing the guard so the assertion will fire if a future Rust change reintroduces the synchronous path — silent no-op would hide the bug. Also reverts the public isThreadTrackedForTask method on TaskResourceTrackingService that was added to support the guard. Signed-off-by: Aravind Sagar Co-Authored-By: Claude Opus 4.7 (1M context) --- .../opensearch/analytics/exec/AnalyticsSearchService.java | 4 ---- .../org/opensearch/tasks/TaskResourceTrackingService.java | 8 +++----- 2 files changed, 3 insertions(+), 9 deletions(-) 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 c221294848dfd..6194439748fca 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 @@ -333,14 +333,10 @@ private FragmentResources startFragment(FragmentExecutionRequest request, Resolv if (task != null && taskResourceTrackingService != null) { long taskId = task.getId(); TaskResourceTrackingService service = taskResourceTrackingService; - Task trackedTask = task; tracker = new DelegationThreadTracker() { @Override public long trackStart() { long threadId = Thread.currentThread().threadId(); - if (service.isThreadTrackedForTask(trackedTask, threadId)) { - return -1; - } service.taskExecutionStartedOnThread(taskId, threadId); return threadId; } diff --git a/server/src/main/java/org/opensearch/tasks/TaskResourceTrackingService.java b/server/src/main/java/org/opensearch/tasks/TaskResourceTrackingService.java index caa82c9c5ae27..645e8e93bda04 100644 --- a/server/src/main/java/org/opensearch/tasks/TaskResourceTrackingService.java +++ b/server/src/main/java/org/opensearch/tasks/TaskResourceTrackingService.java @@ -233,8 +233,10 @@ private ResourceUsageMetric[] getResourceUsageMetricsForThread(long threadId) { return new ResourceUsageMetric[] { currentMemoryUsage, currentCPUUsage }; } - public boolean isThreadTrackedForTask(Task task, long threadId) { + private boolean isCurrentThreadWorkingOnTask(Task task) { + long threadId = Thread.currentThread().threadId(); List threadResourceInfos = task.getResourceStats().getOrDefault(threadId, Collections.emptyList()); + for (ThreadResourceInfo threadResourceInfo : threadResourceInfos) { if (threadResourceInfo.isActive()) { return true; @@ -243,10 +245,6 @@ public boolean isThreadTrackedForTask(Task task, long threadId) { return false; } - private boolean isCurrentThreadWorkingOnTask(Task task) { - return isThreadTrackedForTask(task, Thread.currentThread().threadId()); - } - private List getThreadsWorkingOnTask(Task task) { List activeThreads = new ArrayList<>(); for (List threadResourceInfos : task.getResourceStats().values()) { From bc592cb7277527217c97c0bebbdff390bfb82d90 Mon Sep 17 00:00:00 2001 From: Aravind Sagar Date: Wed, 27 May 2026 10:08:46 +0000 Subject: [PATCH 3/5] Address review feedback on filter delegation concurrency fix MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three changes from code review: 1. Fix cleanup ordering in FragmentResources.close() The previous order ran onClose (which calls FilterTreeCallbacks.unregister) BEFORE closing the result stream. Closing the stream is what triggers Rust to drop ProviderHandle/FfmSegmentCollector, which fire releaseProvider/ releaseCollector upcalls. With unregister already done, those upcalls found no binding and skipped the eager Lucene Weight/Scorer release. Reorder: close stream → engine → reader first, then run onClose. Release upcalls now find their binding and call handle.releaseProvider/Collector as intended. 2. Move null-task check before handle creation in AnalyticsSearchService Previously the IllegalStateException for null task fired AFTER getFilterDelegationHandle had already been called, leaking the handle. Move the check to the top of the delegation block so we never allocate resources we won't track. 3. Close FilterDelegationHandle in cleanup DataFusionAnalyticsBackendPlugin.configureFilterDelegation now returns a cleanup that both unregisters from FilterTreeCallbacks and closes the handle. Previously nothing closed the handle eagerly — its internal ConcurrentHashMaps relied on GC. Also clarifies the testSharedContextIdCausesDataCorruption javadoc to explain that each thread re-registers its own handle at the shared contextId, simulating the old AtomicReference race. Signed-off-by: Aravind Sagar Co-Authored-By: Claude Opus 4.7 (1M context) --- .../DataFusionAnalyticsBackendPlugin.java | 14 +++++++++++++- .../DelegationTaskTrackingTests.java | 19 +++++++++++++------ .../exec/AnalyticsSearchService.java | 14 +++++++++----- .../analytics/exec/FragmentResources.java | 15 ++++++++++----- 4 files changed, 45 insertions(+), 17 deletions(-) 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 315ca223441ef..fa8076a6f033c 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; @@ -66,6 +69,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<>(); @@ -818,7 +823,14 @@ public Runnable configureFilterDelegation( BackendExecutionContext backendContext ) { FilterTreeCallbacks.register(contextId, handle, tracker); - return () -> FilterTreeCallbacks.unregister(contextId); + return () -> { + FilterTreeCallbacks.unregister(contextId); + try { + handle.close(); + } catch (Exception e) { + LOGGER.warn(new ParameterizedMessage("FilterDelegationHandle.close() failed for contextId={}", contextId), e); + } + }; } @Override 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 e5c99952cfe6b..f9748f2e422b7 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 @@ -268,12 +268,15 @@ public void testConcurrentQueriesIsolated() throws Exception { } /** - * Demonstrates why per-query isolation is necessary. When multiple queries share - * the same contextId (simulating the old global singleton behavior), concurrent - * upcalls read the wrong handle and get incorrect results. + * Demonstrates why per-query isolation is necessary. Simulates the old global-singleton + * race: each thread installs its own per-query handle but at a shared contextId. The race + * is between {@code register(SHARED, myHandle)} and the subsequent upcalls — another + * thread may overwrite the binding with its handle before our upcalls fire, so we read + * back the wrong handle's data. * - * This test is expected to FAIL if all queries share a single contextId (the old bug). - * It passes only because each query has its own contextId. + * This test asserts that corruption count is greater than zero — proving the singleton + * pattern is unsafe under concurrency. Use of distinct contextIds eliminates this race + * (see {@link #testConcurrentQueriesIsolated}). */ public void testSharedContextIdCausesDataCorruption() throws Exception { int queryCount = 4; @@ -295,7 +298,11 @@ public void testSharedContextIdCausesDataCorruption() throws Exception { try { barrier.await(5, TimeUnit.SECONDS); for (int i = 0; i < 20; i++) { - // Each iteration overwrites the shared binding — last writer wins + // Each thread re-registers ITS OWN handle at the shared contextId before + // every iteration. This mirrors the old global-singleton race where each + // query installed its handle into a single AtomicReference. Concurrent + // threads will overwrite each other's binding between this register call + // and the upcalls below — leading to wrong-handle reads. FilterTreeCallbacks.register(SHARED_CONTEXT_ID, handles[queryIdx], null); int pk = FilterTreeCallbacks.createProvider(SHARED_CONTEXT_ID, 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 6194439748fca..3191ed7185260 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 @@ -324,13 +324,21 @@ 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); // Build a thread tracker when task resource tracking is available. DelegationThreadTracker tracker = null; - if (task != null && taskResourceTrackingService != null) { + if (taskResourceTrackingService != null) { long taskId = task.getId(); TaskResourceTrackingService service = taskResourceTrackingService; tracker = new DelegationThreadTracker() { @@ -351,10 +359,6 @@ public void trackEnd(long threadId) { // 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. - if (task == null) { - throw new IllegalStateException("Filter delegation requires a tracked task for per-query isolation"); - } - long contextId = task.getId(); trackerCleanup = backend.configureFilterDelegation(contextId, handle, tracker, 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) { From 6badb560103c074cb485214ce757971cdfa45529 Mon Sep 17 00:00:00 2001 From: Aravind Sagar Date: Fri, 29 May 2026 04:10:04 +0000 Subject: [PATCH 4/5] Fix stale module comment in ffm_callbacks.rs The header comment said "Four callback slots" but lists five (and the code defines five). Pre-existing typo, easy to fix while in this area. Signed-off-by: Aravind Sagar --- .../rust/src/indexed_table/ffm_callbacks.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 748dabeb9d40b..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,7 +8,7 @@ //! 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(contextId, annotationId) -> providerKey|-1` From c05f752b29af4cb171672108383473f777af2689 Mon Sep 17 00:00:00 2001 From: Aravind Sagar Date: Sun, 31 May 2026 05:23:53 +0000 Subject: [PATCH 5/5] Add lifecycle assertions to FilterTreeCallbacks MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Production keeps its silent fallbacks (return -1 / no-op) so a misuse never crashes the JVM through an FFM upcall. With assertions enabled (-ea, default in tests and ./gradlew run), the callbacks now also fail loudly on lifecycle violations so they surface in development: - register: asserts no prior binding exists for the contextId. Catches leaked bindings from earlier queries (missing unregister) and duplicate register calls. - createProvider/createCollector/collectDocs/release*: assert a binding exists for the contextId. Catches premature unregister and stale Rust handles outliving their query. The upcall methods catch Throwable but re-throw AssertionError so the assertion isn't swallowed by the surrounding error-handling block. In production (no -ea), these branches never execute. Replaces testNoHandleReturnsNegativeOne / testReleaseWithNoHandleIsSafe with testUnregisteredContextIdAsserts (now expects AssertionError). Replaces testSharedContextIdCausesDataCorruption (probabilistic race test) with testDoubleRegisterAsserts (deterministic — the assertion catches the bug at the API boundary). Signed-off-by: Aravind Sagar Co-Authored-By: Claude Opus 4.7 (1M context) --- .../indexfilter/FilterTreeCallbacks.java | 53 ++++++- .../DelegationTaskTrackingTests.java | 150 ++++-------------- .../indexfilter/IndexFilterCallbackTests.java | 30 ++-- 3 files changed, 101 insertions(+), 132 deletions(-) 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 832bc55b918c0..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 @@ -38,6 +38,14 @@ *

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. + * + *

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 { @@ -59,17 +67,24 @@ private FilterTreeCallbacks() {} * 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 register(long contextId, FilterDelegationHandle handle, DelegationThreadTracker tracker) { - BINDINGS.put(contextId, new QueryBinding(handle, tracker)); + QueryBinding prev = BINDINGS.put(contextId, new QueryBinding(handle, tracker)); + assert prev == null : "FilterTreeCallbacks.register: binding already present for contextId=" + contextId; } /** * 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 unregister(long contextId) { BINDINGS.remove(contextId); @@ -90,6 +105,26 @@ private static void trackEnd(long contextId, long threadId) { 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) ──────────────── /** @@ -99,10 +134,14 @@ public static int createProvider(long contextId, int annotationId) { long tid = trackStart(contextId); try { QueryBinding binding = BINDINGS.get(contextId); + assertBindingExists(binding, "createProvider", contextId); if (binding == null || binding.handle() == null) { return -1; } 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 contextId=" + contextId + " annotationId=" + annotationId, throwable); return -1; @@ -117,9 +156,12 @@ public static int createProvider(long contextId, int annotationId) { public static void releaseProvider(long contextId, int providerKey) { try { 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(contextId={}, providerKey={}) failed", contextId, providerKey), @@ -139,10 +181,13 @@ public static int createCollector(long contextId, int providerKey, long writerGe long tid = trackStart(contextId); try { QueryBinding binding = BINDINGS.get(contextId); + assertBindingExists(binding, "createCollector", contextId); if (binding == null || binding.handle() == null) { return -1; } return binding.handle().createCollector(providerKey, writerGeneration, minDoc, maxDoc); + } catch (AssertionError e) { + throw e; } catch (Throwable throwable) { LOGGER.error( new ParameterizedMessage( @@ -168,6 +213,7 @@ public static long collectDocs(long contextId, int collectorKey, int minDoc, int long tid = trackStart(contextId); try { QueryBinding binding = BINDINGS.get(contextId); + assertBindingExists(binding, "collectDocs", contextId); if (binding == null || binding.handle() == null) { return -1L; } @@ -179,6 +225,8 @@ public static long collectDocs(long contextId, int collectorKey, int minDoc, int 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( @@ -202,9 +250,12 @@ public static long collectDocs(long contextId, int collectorKey, int minDoc, int public static void releaseCollector(long contextId, int collectorKey) { try { 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(contextId={}, collectorKey={}) failed", contextId, collectorKey), 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 f9748f2e422b7..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 @@ -100,38 +100,23 @@ public void testAllCallbackMethodsTrackedOnForeignThread() throws Exception { } /** - * Tests that clearing the thread tracker (via unregister) 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.register(TEST_CONTEXT_ID, new MockHandle(new long[] { 1L }), createTracker(task.getId())); - - // Clear tracking BEFORE running callbacks - FilterTreeCallbacks.unregister(TEST_CONTEXT_ID); - - CountDownLatch done = new CountDownLatch(1); - Thread foreignThread = new Thread(() -> { - // With no binding, createProvider returns -1 (safe no-op); remaining calls - // also find no binding and return -1 or do nothing. - 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(TEST_CONTEXT_ID, ck, 0, 64, buf, 1); - } - FilterTreeCallbacks.releaseCollector(TEST_CONTEXT_ID, ck); - FilterTreeCallbacks.releaseProvider(TEST_CONTEXT_ID, pk); - done.countDown(); - }, "post-clear-thread"); - foreignThread.start(); - assertTrue(done.await(5, TimeUnit.SECONDS)); - - trackingService.stopTracking(task); + public void testUnregisteredContextIdAssertsInTests() throws Exception { + long unregisteredCtx = 9999L; + // Sanity: nothing registered for this contextId. + FilterTreeCallbacks.unregister(unregisteredCtx); - Map> stats = task.getResourceStats(); - assertFalse("Thread after clearing tracker should NOT be tracked", stats.containsKey(foreignThread.threadId())); + AssertionError failure = expectThrows(AssertionError.class, () -> FilterTreeCallbacks.createProvider(unregisteredCtx, 1)); + assertTrue( + "AssertionError should mention the offending contextId. Got: " + failure.getMessage(), + failure.getMessage().contains("contextId=" + unregisteredCtx) + ); } /** @@ -268,96 +253,25 @@ public void testConcurrentQueriesIsolated() throws Exception { } /** - * Demonstrates why per-query isolation is necessary. Simulates the old global-singleton - * race: each thread installs its own per-query handle but at a shared contextId. The race - * is between {@code register(SHARED, myHandle)} and the subsequent upcalls — another - * thread may overwrite the binding with its handle before our upcalls fire, so we read - * back the wrong handle's data. - * - * This test asserts that corruption count is greater than zero — proving the singleton - * pattern is unsafe under concurrency. Use of distinct contextIds eliminates this race - * (see {@link #testConcurrentQueriesIsolated}). + * 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 testSharedContextIdCausesDataCorruption() throws Exception { - int queryCount = 4; - long SHARED_CONTEXT_ID = 999L; - - MockHandle[] handles = new MockHandle[queryCount]; - for (int q = 0; q < queryCount; q++) { - handles[q] = new MockHandle(new long[] { 0xABCD_0000L | q }); - } - - CyclicBarrier barrier = new CyclicBarrier(queryCount); - CountDownLatch done = new CountDownLatch(queryCount); - int[] corruptionCount = new int[queryCount]; - - Thread[] threads = new Thread[queryCount]; - for (int q = 0; q < queryCount; q++) { - final int queryIdx = q; - threads[q] = new Thread(() -> { - try { - barrier.await(5, TimeUnit.SECONDS); - for (int i = 0; i < 20; i++) { - // Each thread re-registers ITS OWN handle at the shared contextId before - // every iteration. This mirrors the old global-singleton race where each - // query installed its handle into a single AtomicReference. Concurrent - // threads will overwrite each other's binding between this register call - // and the upcalls below — leading to wrong-handle reads. - FilterTreeCallbacks.register(SHARED_CONTEXT_ID, handles[queryIdx], null); - - int pk = FilterTreeCallbacks.createProvider(SHARED_CONTEXT_ID, 1); - if (pk < 0) { - corruptionCount[queryIdx]++; - continue; - } - int ck = FilterTreeCallbacks.createCollector(SHARED_CONTEXT_ID, pk, 0, 0, 64); - if (ck < 0) { - corruptionCount[queryIdx]++; - FilterTreeCallbacks.releaseProvider(SHARED_CONTEXT_ID, pk); - continue; - } - - try (Arena arena = Arena.ofConfined()) { - MemorySegment buf = arena.allocate(Long.BYTES); - long words = FilterTreeCallbacks.collectDocs(SHARED_CONTEXT_ID, ck, 0, 64, buf, 1); - if (words < 0) { - corruptionCount[queryIdx]++; - } else { - long value = buf.getAtIndex(ValueLayout.JAVA_LONG, 0); - long expected = 0xABCD_0000L | queryIdx; - if (value != expected) { - corruptionCount[queryIdx]++; - } - } - } - FilterTreeCallbacks.releaseCollector(SHARED_CONTEXT_ID, ck); - FilterTreeCallbacks.releaseProvider(SHARED_CONTEXT_ID, pk); - } - } catch (Exception e) { - corruptionCount[queryIdx] += 100; - } finally { - done.countDown(); - } - }, "shared-ctx-query-" + q); - threads[q].start(); + 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); } - - assertTrue(done.await(15, TimeUnit.SECONDS)); - FilterTreeCallbacks.unregister(SHARED_CONTEXT_ID); - - int totalCorruption = 0; - for (int c : corruptionCount) - totalCorruption += c; - - assertTrue( - "With a shared contextId, concurrent queries SHOULD see data corruption " - + "(wrong handle's data returned). Got " - + totalCorruption - + " corruptions out of " - + (queryCount * 20) - + " attempts. If this is 0, the test is not exercising the race.", - totalCorruption > 0 - ); } private DelegationThreadTracker createTracker(long taskId) { 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 7f59058b66673..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 @@ -75,20 +75,24 @@ public void testFullRoundTrip() { assertEquals("handle received providerKey for release", providerKey, handle.lastReleasedProviderKey); } - public void testNoHandleReturnsNegativeOne() { + /** + * 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); - 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(CTX, 1, 0, 64, buf, 1)); - } - } - - public void testReleaseWithNoHandleIsSafe() { - FilterTreeCallbacks.unregister(CTX); - FilterTreeCallbacks.releaseCollector(CTX, Integer.MAX_VALUE); - FilterTreeCallbacks.releaseProvider(CTX, Integer.MAX_VALUE); + 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() {