mbutrovich commented on code in PR #7082:
URL: https://github.com/apache/datafusion-comet/pull/7082#discussion_r4351593833


##########
native/core/src/parquet/shared_metadata_cache.rs:
##########
@@ -0,0 +1,472 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! A registry that lets the tasks of one Spark stage share a Parquet 
`FileMetadataCache`.
+//!
+//! Comet builds a `RuntimeEnv`, and with it a metadata cache, for every Spark 
task, so two tasks
+//! that read splits of the same file each fetch and parse its footer and page 
index. This
+//! registry hands every task of a stage on this executor the same cache 
instead.
+//!
+//! The scope is the stage, not the executor, on purpose. A cache that 
outlives the query would
+//! answer a later query from metadata of a file that has since been deleted 
or rewritten, and
+//! `(size, modification time)` validation cannot catch that: Spark's cached 
file index lists the
+//! same size and time as the cached footer. Spark's `HiveMetadataCacheSuite` 
reads a table,
+//! deletes one data file, reads again, and expects `FILE_NOT_EXIST`. Every 
new query is a new
+//! stage, so it opens its files and sees the deletion, as it does without the 
registry.
+//!
+//! A stage attempt is part of the key because a retried stage may read a 
changed file. So is the
+//! Spark application: stage ids restart at zero in every `SparkContext`, and 
this registry is
+//! process-wide, so a context started after another one stopped in the same 
JVM must not match
+//! the stages the old one left behind.
+//!
+//! The registry holds a weak reference to the cache of every stage with a 
running task, since the
+//! tasks own it through their `RuntimeEnv`. It additionally holds strong 
references to the last
+//! [`MAX_IDLE_CACHES`] caches it handed out. Those matter when an executor 
runs one task at a
+//! time: the next task of the stage starts after the previous one released 
its plan. Whatever the
+//! tasks do, at most [`MAX_IDLE_CACHES`] caches outlive the tasks that used 
them.
+//!
+//! A stage's cache holds DataFusion's per-task limit for each of its tasks 
that is running, and one
+//! task's limit once none is, so that sharing does not shrink the room each 
task had with a cache
+//! of its own: tasks that read different files would otherwise evict each 
other's entries, among
+//! them the footers the Delta deletion vector planning loads before the scan 
opens them. Each task
+//! takes its share when it asks for the cache and gives it back when its 
`RuntimeEnv` drops it, so
+//! the limit follows the tasks that actually run, whatever the executor's 
configured cores say.
+//! Shared entries are stored once, so the tasks of a stage hold no more than 
they did, and a
+//! retained cache holds no more than one task's.
+//!
+//! The stage scopes the cache; it does not identify the files in it. 
DataFusion keys an entry by
+//! the file's path within its object store, which drops the bucket, so 
[`scope_to_store`] gives
+//! each scan a view of the cache that also keys by the scan's object store.
+
+use crate::execution::spark_config::{
+    SparkConfig, COMET_APP_ID, COMET_PARQUET_SHARED_METADATA_CACHE_ENABLED, 
COMET_STAGE_ATTEMPT,
+    COMET_STAGE_ID,
+};
+use datafusion::common::TableReference;
+use datafusion::datasource::object_store::ObjectStoreUrl;
+use datafusion::execution::cache::cache_manager::{
+    CachedFileMetadataEntry, FileMetadataCache, DEFAULT_METADATA_CACHE_LIMIT,
+};
+use datafusion::execution::cache::default_cache::DefaultCache;
+use datafusion::execution::cache::{Cache, CacheEntryInfo};
+use object_store::path::Path;
+use std::collections::{HashMap, VecDeque};
+use std::sync::{Arc, Mutex, OnceLock, Weak};
+use std::time::Duration;
+
+/// How many caches of stages with no running task the registry holds on to.
+const MAX_IDLE_CACHES: usize = 2;
+
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+pub(crate) struct StageKey {
+    pub app_id: String,
+    pub stage_id: i32,
+    pub stage_attempt: i32,
+}
+
+/// The cache of one stage, and how many of its tasks are running.
+struct StageCache {
+    cache: Arc<DefaultCache<Path, CachedFileMetadataEntry>>,
+    running: Mutex<usize>,
+}
+
+impl StageCache {
+    fn new() -> Self {
+        Self {
+            cache: Arc::new(
+                DefaultCache::new(DEFAULT_METADATA_CACHE_LIMIT)
+                    .with_name("SharedFileMetadataCache"),
+            ),
+            running: Mutex::new(0),
+        }
+    }
+
+    /// Counts a task in or out, and sizes the cache for the tasks left 
running. Lowering the limit
+    /// evicts the least recently used entries down to it.
+    fn update_running(&self, update: impl FnOnce(usize) -> usize) {
+        let mut running = self.running.lock().unwrap();
+        *running = update(*running);
+        self.cache
+            
.update_cache_limit(DEFAULT_METADATA_CACHE_LIMIT.saturating_mul((*running).max(1)));
+    }
+}
+
+/// One task's handle on its stage's cache, which counts the task as running 
for as long as it
+/// lives. The task's `RuntimeEnv` and the scans' views of the cache hold it, 
so it drops when the
+/// task's plan does. Strictly it counts native plans, of which a task usually 
has one; a task that
+/// runs several at once is counted once for each, which errs toward a larger 
cache.
+///
+/// It is the cache the task's `CacheManager` is given. 
`CacheManager::try_new` sets the limit of
+/// that cache to the one in its config, so this ignores limit updates: the 
stage's running tasks
+/// decide it.
+pub(crate) struct TaskCache {
+    stage: Arc<StageCache>,
+}
+
+impl TaskCache {
+    fn new(stage: Arc<StageCache>) -> Self {
+        stage.update_running(|running| running + 1);
+        Self { stage }
+    }
+}
+
+impl Drop for TaskCache {
+    fn drop(&mut self) {
+        self.stage
+            .update_running(|running| running.saturating_sub(1));
+    }
+}
+
+impl std::fmt::Debug for TaskCache {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        f.debug_struct("TaskCache")
+            .field("running", &*self.stage.running.lock().unwrap())
+            .finish()
+    }
+}
+
+impl Cache<Path, CachedFileMetadataEntry> for TaskCache {
+    fn get(&self, key: &Path) -> Option<CachedFileMetadataEntry> {
+        self.stage.cache.get(key)
+    }
+
+    fn put(&self, key: &Path, value: CachedFileMetadataEntry) -> 
Option<CachedFileMetadataEntry> {
+        self.stage.cache.put(key, value)
+    }
+
+    fn remove(&self, key: &Path) -> Option<CachedFileMetadataEntry> {
+        self.stage.cache.remove(key)
+    }
+
+    fn contains_key(&self, key: &Path) -> bool {
+        self.stage.cache.contains_key(key)
+    }
+
+    fn len(&self) -> usize {
+        self.stage.cache.len()
+    }
+
+    fn clear(&self) {
+        self.stage.cache.clear()
+    }
+
+    fn name(&self) -> String {
+        self.stage.cache.name()
+    }
+
+    fn cache_limit(&self) -> usize {
+        self.stage.cache.cache_limit()
+    }
+
+    fn update_cache_limit(&self, _limit: usize) {}
+
+    fn cache_ttl(&self) -> Option<Duration> {
+        self.stage.cache.cache_ttl()
+    }
+
+    fn update_cache_ttl(&self, ttl: Option<Duration>) {
+        self.stage.cache.update_cache_ttl(ttl)
+    }
+
+    fn drop_table_entries(&self, table_ref: &TableReference) -> 
datafusion::error::Result<()> {
+        self.stage.cache.drop_table_entries(table_ref)
+    }
+
+    fn list_entries(
+        &self,
+    ) -> datafusion::common::HashMap<Path, 
CacheEntryInfo<CachedFileMetadataEntry>> {
+        self.stage.cache.list_entries()
+    }
+}
+
+#[derive(Default)]
+struct Registry {
+    /// Every stage cache that is still alive, running or retained.
+    alive: HashMap<StageKey, Weak<StageCache>>,
+    /// The caches kept alive for the next task of their stage, least recently 
requested first.
+    retained: VecDeque<(StageKey, Arc<StageCache>)>,
+}
+
+#[derive(Default)]
+pub(crate) struct SharedMetadataCaches {
+    registry: Mutex<Registry>,
+}
+
+impl SharedMetadataCaches {
+    /// A task's handle on the cache shared by the tasks of `key`, created if 
no task of that stage
+    /// has asked for one yet.
+    pub(crate) fn cache_for(&self, key: StageKey) -> Arc<TaskCache> {
+        let mut registry = self.registry.lock().unwrap();
+        let stage = registry
+            .alive
+            .get(&key)
+            .and_then(Weak::upgrade)
+            .unwrap_or_else(|| Arc::new(StageCache::new()));
+        registry.alive.insert(key.clone(), Arc::downgrade(&stage));
+
+        registry.retained.retain(|(retained, _)| *retained != key);
+        registry.retained.push_back((key, Arc::clone(&stage)));
+        while registry.retained.len() > MAX_IDLE_CACHES {
+            registry.retained.pop_front();
+        }
+        registry.alive.retain(|_, weak| weak.strong_count() > 0);
+        Arc::new(TaskCache::new(stage))
+    }
+
+    #[cfg(test)]
+    fn len(&self) -> usize {
+        self.registry.lock().unwrap().alive.len()
+    }
+}
+
+/// A view of a [`FileMetadataCache`] that keys every entry by the object 
store as well as the
+/// path within it.
+///
+/// DataFusion keys an entry by `ObjectMeta.location`, and the location of a 
file in a scan has no
+/// bucket or authority, so equal paths in two stores collide. Two files at 
the same path with the
+/// same size then pass the cache's `(size, modification time)` check, and a 
task would plan its
+/// scan with the other file's footer and statistics. Only the key changes; 
the entries, the memory
+/// limit and the eviction are those of the cache underneath, which is why a 
view can be made per
+/// scan from the cache of the whole stage. `len`, `clear` and `list_entries` 
act on the whole
+/// cache, not on this scope.
+#[derive(Debug)]
+struct StoreScopedCache {
+    scope: String,
+    inner: Arc<FileMetadataCache>,
+}
+
+impl StoreScopedCache {
+    fn scoped(&self, key: &Path) -> Path {
+        std::iter::once(self.scope.clone())
+            .chain(key.parts().map(|part| part.as_ref().to_string()))
+            .collect()
+    }
+}
+
+impl Cache<Path, CachedFileMetadataEntry> for StoreScopedCache {
+    fn get(&self, key: &Path) -> Option<CachedFileMetadataEntry> {
+        self.inner.get(&self.scoped(key))
+    }
+
+    fn put(&self, key: &Path, value: CachedFileMetadataEntry) -> 
Option<CachedFileMetadataEntry> {
+        self.inner.put(&self.scoped(key), value)
+    }
+
+    fn remove(&self, key: &Path) -> Option<CachedFileMetadataEntry> {
+        self.inner.remove(&self.scoped(key))
+    }
+
+    fn contains_key(&self, key: &Path) -> bool {
+        self.inner.contains_key(&self.scoped(key))
+    }
+
+    fn len(&self) -> usize {
+        self.inner.len()
+    }
+
+    fn clear(&self) {
+        self.inner.clear()
+    }
+
+    fn name(&self) -> String {
+        self.inner.name()
+    }
+
+    fn cache_limit(&self) -> usize {
+        self.inner.cache_limit()
+    }
+
+    fn update_cache_limit(&self, limit: usize) {
+        self.inner.update_cache_limit(limit)
+    }
+
+    fn cache_ttl(&self) -> Option<Duration> {
+        self.inner.cache_ttl()
+    }
+
+    fn update_cache_ttl(&self, ttl: Option<Duration>) {
+        self.inner.update_cache_ttl(ttl)
+    }
+
+    fn drop_table_entries(&self, table_ref: &TableReference) -> 
datafusion::error::Result<()> {
+        self.inner.drop_table_entries(table_ref)
+    }
+
+    fn list_entries(
+        &self,
+    ) -> datafusion::common::HashMap<Path, 
CacheEntryInfo<CachedFileMetadataEntry>> {
+        self.inner.list_entries()
+    }
+}
+
+/// The metadata cache a scan of `object_store_url` should use, given the one 
of its
+/// `RuntimeEnv`.
+///
+/// `object_store_url` is the URL the scan's store is registered under, which 
already carries the
+/// backend and a hash of the store's configuration (see 
`object_store_registration_url`), so two
+/// stores with equal paths never share an entry. The scan and any code that 
reads the footers
+/// ahead of it, such as the Delta deletion vector planning, must pass the 
same URL to find each
+/// other's entries.
+pub(crate) fn scope_to_store(
+    cache: Arc<FileMetadataCache>,
+    object_store_url: &ObjectStoreUrl,
+) -> Arc<FileMetadataCache> {
+    Arc::new(StoreScopedCache {
+        scope: object_store_url.as_str().to_string(),
+        inner: cache,
+    })
+}
+
+/// The cache the task with these Spark configs should use, or `None` when 
sharing is off or the
+/// task's stage is unknown, in which case DataFusion's per-task cache applies.
+pub(crate) fn shared_metadata_cache_for_task(
+    spark_config: &HashMap<String, String>,
+) -> Option<Arc<FileMetadataCache>> {
+    static CACHES: OnceLock<SharedMetadataCaches> = OnceLock::new();

Review Comment:
   The contributor guide lists state that ["needs cleanup or refresh during 
process 
lifetime"](https://github.com/apache/datafusion-comet/blob/da2ff08134ba6ceeccade058aea09e7c21d9472b/docs/source/contributor-guide/development.md?plain=1#L192-L201)
 as a reason to avoid a singleton. As I read it, the retained caches fit that 
description. Spark gives every submission of a stage a new attempt number 
([`Stage.makeNewStageAttempt`](https://github.com/apache/spark/blob/e221b56be7b6d9e48e107fc4d1cf0c15f02700f8/core/src/main/scala/org/apache/spark/scheduler/Stage.scala#L111-L121)),
 so once a stage attempt's tasks finish, no task can hit its cache again. The 
registry frees a retained cache only after two other stages ask for one on this 
executor, or when the process exits. An executor that goes idle after a query 
keeps up to 100 MiB that nothing can use.
   
   Should `release_runtime` clear this registry, as it clears `FILE_IO_CACHE` 
through 
[`clear_file_io_cache`](https://github.com/apache/datafusion-comet/blob/da2ff08134ba6ceeccade058aea09e7c21d9472b/native/core/src/execution/jni_api.rs#L462-L468)?
 Then the static gets the same teardown at plugin shutdown as the other 
process-wide native caches. Could the module doc and the new 
`memory_management.md` bullet also say when a retained cache is freed? Today 
they say how many are kept, but not for how long.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to