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


##########
native/core/src/parquet/shared_metadata_cache.rs:
##########
@@ -0,0 +1,715 @@
+// 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. An executor is
+//! not told that a stage has finished, so a retained cache is freed once no 
task of its stage has
+//! run for [`IDLE_CACHE_TIMEOUT`], once tasks of [`MAX_IDLE_CACHES`] other 
stages have asked for
+//! theirs, or when the plugin shuts down and [`clear_shared_metadata_caches`] 
runs, whichever comes
+//! first. An executor that goes idle after a query frees them within the 
timeout.
+//!
+//! A stage's cache holds DataFusion's per-task limit for each of the tasks 
that have run at once
+//! since the stage was last idle, and one task's limit once none is running, 
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. The limit stays up while a task finishes 
and others run on,
+//! because the cache evicts the least recently used entry whoever loaded it, 
so lowering it would
+//! take those footers from a running task as readily as the finished task's. 
That does not make
+//! the footers a running task preloaded safe: they are older than the 
finished task's entries, so
+//! when the next task loads its own, they are evicted first, and the scan 
that needed them fetches
+//! them again. This is an accepted cost, a refetch of a footer a task of its 
own would have kept,
+//! and only when the entries the stage's tasks load exceed what the limit 
holds. 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::jni_api::get_runtime;
+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 log::debug;
+use object_store::path::Path;
+use std::collections::{HashMap, VecDeque};
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{Arc, LazyLock, Mutex, Weak};
+use std::time::{Duration, Instant};
+
+/// How many caches of stages with no running task the registry holds on to.
+const MAX_IDLE_CACHES: usize = 2;
+
+/// How long the registry holds on to the cache of a stage with no running 
task. The next task of a
+/// stage that runs one task at a time on an executor starts well within it.
+const IDLE_CACHE_TIMEOUT: Duration = Duration::from_secs(10);
+
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+pub(crate) struct StageKey {
+    pub app_id: String,
+    pub stage_id: i32,
+    pub stage_attempt: i32,
+}
+
+/// How many tasks of a stage are running, the most that have been at once 
since none was, and
+/// since when none has been.
+#[derive(Default)]
+struct Running {
+    tasks: usize,
+    peak: usize,
+    idle_since: Option<Instant>,
+}
+
+/// The cache of one stage, and how many of its tasks are running.
+struct StageCache {
+    cache: Arc<DefaultCache<Path, CachedFileMetadataEntry>>,
+    running: Mutex<Running>,
+}
+
+impl StageCache {
+    fn new() -> Self {
+        Self {
+            cache: Arc::new(
+                DefaultCache::new(DEFAULT_METADATA_CACHE_LIMIT)
+                    .with_name("SharedFileMetadataCache"),
+            ),
+            running: Mutex::new(Running::default()),
+        }
+    }
+
+    /// Counts a task in or out, and sizes the cache for the most tasks that 
have run at once since
+    /// the stage was last idle. The limit falls only when no task is left, so 
that a task finishing
+    /// does not evict the entries of the tasks still running, which the cache 
cannot tell apart
+    /// from its own. 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.tasks = update(running.tasks);
+        running.peak = if running.tasks == 0 {
+            0
+        } else {
+            running.peak.max(running.tasks)

Review Comment:
   Could the limit track running tasks again? With four tasks at once, a 
probe's last task kept 200 MiB of finished tasks' entries. A private cache caps 
at 50 MiB.



##########
native/core/src/parquet/shared_metadata_cache.rs:
##########
@@ -0,0 +1,715 @@
+// 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. An executor is
+//! not told that a stage has finished, so a retained cache is freed once no 
task of its stage has
+//! run for [`IDLE_CACHE_TIMEOUT`], once tasks of [`MAX_IDLE_CACHES`] other 
stages have asked for
+//! theirs, or when the plugin shuts down and [`clear_shared_metadata_caches`] 
runs, whichever comes
+//! first. An executor that goes idle after a query frees them within the 
timeout.
+//!
+//! A stage's cache holds DataFusion's per-task limit for each of the tasks 
that have run at once
+//! since the stage was last idle, and one task's limit once none is running, 
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. The limit stays up while a task finishes 
and others run on,
+//! because the cache evicts the least recently used entry whoever loaded it, 
so lowering it would
+//! take those footers from a running task as readily as the finished task's. 
That does not make
+//! the footers a running task preloaded safe: they are older than the 
finished task's entries, so
+//! when the next task loads its own, they are evicted first, and the scan 
that needed them fetches
+//! them again. This is an accepted cost, a refetch of a footer a task of its 
own would have kept,
+//! and only when the entries the stage's tasks load exceed what the limit 
holds. 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::jni_api::get_runtime;
+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 log::debug;
+use object_store::path::Path;
+use std::collections::{HashMap, VecDeque};
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{Arc, LazyLock, Mutex, Weak};
+use std::time::{Duration, Instant};
+
+/// How many caches of stages with no running task the registry holds on to.
+const MAX_IDLE_CACHES: usize = 2;
+
+/// How long the registry holds on to the cache of a stage with no running 
task. The next task of a
+/// stage that runs one task at a time on an executor starts well within it.
+const IDLE_CACHE_TIMEOUT: Duration = Duration::from_secs(10);
+
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+pub(crate) struct StageKey {
+    pub app_id: String,
+    pub stage_id: i32,
+    pub stage_attempt: i32,
+}
+
+/// How many tasks of a stage are running, the most that have been at once 
since none was, and
+/// since when none has been.
+#[derive(Default)]
+struct Running {
+    tasks: usize,
+    peak: usize,
+    idle_since: Option<Instant>,
+}
+
+/// The cache of one stage, and how many of its tasks are running.
+struct StageCache {
+    cache: Arc<DefaultCache<Path, CachedFileMetadataEntry>>,
+    running: Mutex<Running>,
+}
+
+impl StageCache {
+    fn new() -> Self {
+        Self {
+            cache: Arc::new(
+                DefaultCache::new(DEFAULT_METADATA_CACHE_LIMIT)
+                    .with_name("SharedFileMetadataCache"),
+            ),
+            running: Mutex::new(Running::default()),
+        }
+    }
+
+    /// Counts a task in or out, and sizes the cache for the most tasks that 
have run at once since
+    /// the stage was last idle. The limit falls only when no task is left, so 
that a task finishing
+    /// does not evict the entries of the tasks still running, which the cache 
cannot tell apart
+    /// from its own. 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.tasks = update(running.tasks);
+        running.peak = if running.tasks == 0 {
+            0
+        } else {
+            running.peak.max(running.tasks)
+        };
+        running.idle_since = (running.tasks == 0).then(Instant::now);
+        self.cache
+            
.update_cache_limit(DEFAULT_METADATA_CACHE_LIMIT.saturating_mul(running.peak.max(1)));
+    }
+
+    /// When the cache has gone unused for `timeout`, or `None` while a task 
of the stage runs.
+    fn expires_at(&self, timeout: Duration) -> Option<Instant> {
+        Some(self.running.lock().unwrap().idle_since? + timeout)
+    }
+}
+
+/// 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().tasks)
+            .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>,
+    /// Whether a task that frees the idle caches is running.
+    expiring: AtomicBool,
+}
+
+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 existing = registry.alive.get(&key).and_then(Weak::upgrade);
+        debug!(
+            "shared metadata cache: {} for {key:?}",
+            if existing.is_some() {
+                "reusing"
+            } else {
+                "creating"
+            }
+        );
+        let stage = existing.unwrap_or_else(|| Arc::new(StageCache::new()));
+        registry.alive.insert(key.clone(), Arc::downgrade(&stage));
+
+        registry.retained.retain(|(retained, _)| *retained != key);

Review Comment:
   Could we test this line? All 14 registry tests pass for me without it, but 
requesting `A`, `B`, `B` evicts `A` from the retained queue.



##########
spark/src/test/scala/org/apache/comet/exec/CometSharedMetadataCacheRestartSuite.scala:
##########
@@ -0,0 +1,110 @@
+/*
+ * 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.
+ */
+
+package org.apache.comet.exec
+
+import java.io.File
+import java.nio.file.{Files, Paths, StandardCopyOption}
+
+import org.scalatest.funsuite.AnyFunSuite
+
+import org.apache.commons.io.FileUtils
+import org.apache.spark.sql.SparkSession
+
+/**
+ * The native Parquet scan shares a footer cache between the tasks of a stage 
in a registry that
+ * lives as long as the JVM. Stage ids restart at zero in every SparkContext, 
so a context started
+ * after another one stopped must not be handed the footers the old one left 
in it.
+ *
+ * Runs its own contexts, which is why it is not part of a suite that shares a 
session.
+ */
+class CometSharedMetadataCacheRestartSuite extends AnyFunSuite {
+
+  private def newSession(): SparkSession =
+    SparkSession
+      .builder()
+      .master("local[2]")
+      .config("spark.plugins", "org.apache.spark.CometPlugin")
+      .config(
+        "spark.shuffle.manager",
+        "org.apache.spark.sql.comet.execution.shuffle.CometShuffleManager")
+      .config("spark.sql.extensions", 
"org.apache.comet.CometSparkSessionExtensions")
+      .config("spark.comet.enabled", "true")
+      .config("spark.comet.exec.enabled", "true")
+      .config("spark.comet.parquet.metadataCache.sharedWithinStage.enabled", 
"true")
+      .config("spark.memory.offHeap.enabled", "true")
+      .config("spark.memory.offHeap.size", "256m")
+      // Equal sizes for different values need an encoding whose size does not 
follow the values.
+      .config("spark.sql.parquet.compression.codec", "uncompressed")
+      .config("spark.ui.enabled", "false")
+      .getOrCreate()
+
+  /**
+   * Writes the ids in `[from, until)` as a single file named `part.parquet` 
in `table`, replacing
+   * the file already there, then counts the rows with an id of at least 1000 
in a fresh context.
+   * The jobs run are the same ones each time, so the scan has the same stage 
id in every context.
+   */
+  private def countFrom1000(scratch: File, table: File, from: Long, until: 
Long): (Long, Long) = {
+    val spark = newSession()
+    try {
+      val written = new File(scratch, s"written-$from")
+      spark.range(from, 
until).coalesce(1).write.parquet(written.getAbsolutePath)
+      val source = written
+        .listFiles()
+        .filter(_.getName.endsWith(".parquet"))
+        .head
+        .toPath
+      Files.copy(
+        source,
+        new File(table, "part.parquet").toPath,
+        StandardCopyOption.REPLACE_EXISTING)
+
+      val df = spark.read.parquet(table.getAbsolutePath).where("id >= 1000")
+      val count = df.count()
+      val plan = df.queryExecution.executedPlan.toString
+      require(plan.contains("CometNativeScan"), s"Expected a native scan but 
got:\n$plan")
+      (count, new File(table, "part.parquet").length())
+    } finally {
+      spark.stop()
+    }
+  }
+
+  test("a restarted SparkContext does not read the footers of the previous 
one") {
+    assume(SparkSession.getDefaultSession.isEmpty, "another SparkSession is 
running in this JVM")
+    // java.io.tmpdir is pinned to target/tmp by the pom and may not exist yet
+    val tmpDir = 
Files.createDirectories(Paths.get(System.getProperty("java.io.tmpdir")))
+    val scratch = Files.createTempDirectory(tmpDir, 
"comet-footer-restart").toFile
+    try {
+      val table = new File(scratch, "table")
+      assert(table.mkdirs())
+
+      // The first file holds ids 0 to 999, so its footer says nothing is at 
least 1000.
+      val (before, sizeBefore) = countFrom1000(scratch, table, 0, 1000)

Review Comment:
   Could `newSession().stop()` run before this read? The JVM's first stop 
clears caches, so this still passes for me without `app_id` in the key.



-- 
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