You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@spark.apache.org by "liviazhu (via GitHub)" <gi...@apache.org> on 2026/06/04 18:45:44 UTC

[PR] [SPARK-57225][SS] Enforce read-only access in the state data source read path [spark]

liviazhu opened a new pull request, #56332:
URL: https://github.com/apache/spark/pull/56332

   ### What changes were proposed in this pull request?
   
   This PR ensures the state data source read path never writes to the checkpoint, so reads
   work against read-only storage (e.g. a read-only cloud object store path).
   
   - `StatePartitionReader` / `StatePartitionAllColumnFamiliesReader`: open the store via
     `getReadStore` and `release()` on close instead of `getStore` + `abort()`. Column-family
     registration is an in-memory operation and is now supported on the read store via
     `ReadStateStore.createColFamilyIfAbsent`.
   - `StreamStreamJoinStatePartitionReader`: constructs `SymmetricHashJoinStateManager` with
     `readOnly = true`.
   - `SymmetricHashJoinStateManager` (V1/V2/V4): adds a `readOnly` constructor flag. The store
     handler exposes a writable `stateStore` (guarded with `require(!readOnly)`) and a mode-aware
     `readStateStore`. Inner-store reads and `createColFamilyIfAbsent` route through
     `readStateStore`; writes stay on `stateStore`. `abortIfNeeded` calls `release()` in read-only
     mode.
   - `StateStore`: `ReadStateStore.createColFamilyIfAbsent` is declared on the trait with a default
     `UnsupportedOperationException` and overridden by `WrappedReadStateStore`.
   - `HDFSBackedStateStoreProvider`: `baseDir` mkdirs is deferred from `init()` to the first write
     (`createBaseDirIfNotExists`), so read-only callers never mkdirs on the checkpoint; `release()`
     is state-machine-guarded; `replayStateFromSnapshot` rejects `readOnly = true` and directs
     callers to `replayReadStateFromSnapshot`.
   
   A test framework (`WriteProtectedLocalFileSystem` / `WriteProtectedAbstractFileSystem` /
   `WriteProtectedPaths` / `WriteProtectedCheckpointTestMixin`) installs write-protected
   filesystems and auto-protects every `withTempDir`; `testStream` and `withWritableCheckpoint`
   temporarily suspend protection for legitimate writes. It is mixed into `StateDataSourceTestBase`
   so existing tests gain enforcement transparently.
   
   ### Why are the changes needed?
   
   Reading state via the state data source could previously issue writes (mkdirs, taking a writable
   store) to the checkpoint path, which fails when the checkpoint lives on read-only storage.
   
   ### Does this PR introduce _any_ user-facing change?
   
   No.
   
   ### How was this patch tested?
   
   `StateDataSourceReadSuite` (HDFS and RocksDB variants), `StateDataSourceChangeDataReadSuite`,
   `StateDataSourceTransformWithStateSuite`, `StatePartitionAllColumnFamilies{Reader,Writer}Suite`,
   `OfflineStateRepartitionIntegrationSuite`, and `StateStoreSuite`. A framework-sanity test and
   new read-only enforcement tests were added. A regression check confirmed the framework catches
   an unintended `mkdir` on the read path.
   
   ### Was this patch authored or co-authored using generative AI tooling?
   
   Yes, authored with assistance from Claude (Claude Code).
   


-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-57269][SS] Enforce read-only access in the StateDateSource/StateMetadataSource [spark]

Posted by "anishshri-db (via GitHub)" <gi...@apache.org>.
anishshri-db closed pull request #56332: [SPARK-57269][SS] Enforce read-only access in the StateDateSource/StateMetadataSource
URL: https://github.com/apache/spark/pull/56332


-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-57269][SS] Enforce read-only access in the StateDateSource/StateMetadataSource [spark]

Posted by "liviazhu (via GitHub)" <gi...@apache.org>.
liviazhu commented on code in PR #56332:
URL: https://github.com/apache/spark/pull/56332#discussion_r3365662139


##########
sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/v2/state/WriteProtectedLocalFileSystem.scala:
##########
@@ -0,0 +1,348 @@
+/*
+ * 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.spark.sql.execution.datasources.v2.state
+
+import java.net.URI
+import java.nio.file.AccessDeniedException
+import java.util
+import java.util.concurrent.atomic.AtomicReference
+
+import scala.jdk.CollectionConverters._
+
+import org.apache.hadoop.conf.Configuration
+import org.apache.hadoop.fs.{CreateFlag, DelegateToFileSystem, FSDataOutputStream, FsServerDefaults, Options, Path}
+import org.apache.hadoop.fs.local.LocalConfigKeys
+import org.apache.hadoop.fs.permission.FsPermission
+import org.apache.hadoop.util.Progressable
+import org.scalatest.BeforeAndAfterEach
+
+import org.apache.spark.SparkConf
+import org.apache.spark.sql.streaming.StreamTest
+
+/**
+ * Write protection for the Hadoop FileSystem API (`fs.file.impl`).
+ *
+ * Extends [[org.apache.spark.DebugFilesystem]] so it replaces DebugFilesystem
+ * without losing open-connection tracking. Every write entry point is overridden to deny
+ * the operation when the target path is protected; reads are left untouched.
+ */
+class WriteProtectedLocalFileSystem extends org.apache.spark.DebugFilesystem {
+
+  override def create(
+      f: Path,
+      permission: FsPermission,
+      overwrite: Boolean,
+      bufferSize: Int,
+      replication: Short,
+      blockSize: Long,
+      progress: Progressable): FSDataOutputStream = {
+    if (WriteProtectedPaths.isProtected(f)) WriteProtectedPaths.deny("create", f)
+    super.create(f, permission, overwrite, bufferSize, replication, blockSize, progress)
+  }
+
+  override def create(
+      f: Path,
+      permission: FsPermission,
+      flags: util.EnumSet[CreateFlag],
+      bufferSize: Int,
+      replication: Short,
+      blockSize: Long,
+      progress: Progressable,
+      checksumOpt: Options.ChecksumOpt): FSDataOutputStream = {
+    if (WriteProtectedPaths.isProtected(f)) WriteProtectedPaths.deny("create", f)
+    super.create(
+      f, permission, flags, bufferSize, replication, blockSize, progress, checksumOpt)
+  }
+
+  override def createNonRecursive(
+      f: Path,
+      permission: FsPermission,
+      flags: util.EnumSet[CreateFlag],
+      bufferSize: Int,
+      replication: Short,
+      blockSize: Long,
+      progress: Progressable): FSDataOutputStream = {
+    if (WriteProtectedPaths.isProtected(f)) WriteProtectedPaths.deny("createNonRecursive", f)
+    super.createNonRecursive(f, permission, flags, bufferSize, replication, blockSize, progress)
+  }
+
+  override def append(f: Path, bufferSize: Int, progress: Progressable): FSDataOutputStream = {
+    if (WriteProtectedPaths.isProtected(f)) WriteProtectedPaths.deny("append", f)
+    super.append(f, bufferSize, progress)
+  }
+
+  override def rename(src: Path, dst: Path): Boolean = {
+    // A rename out of a protected path is also a write to that path -- check both ends.
+    if (WriteProtectedPaths.isProtected(src)) WriteProtectedPaths.deny("rename from", src)
+    if (WriteProtectedPaths.isProtected(dst)) WriteProtectedPaths.deny("rename to", dst)
+    super.rename(src, dst)
+  }
+
+  override def delete(f: Path, recursive: Boolean): Boolean = {
+    if (WriteProtectedPaths.isProtected(f)) WriteProtectedPaths.deny("delete", f)
+    super.delete(f, recursive)
+  }
+
+  override def mkdirs(f: Path, permission: FsPermission): Boolean = {
+    if (WriteProtectedPaths.isProtected(f)) WriteProtectedPaths.deny("mkdirs", f)
+    super.mkdirs(f, permission)
+  }
+
+  override def truncate(f: Path, newLength: Long): Boolean = {
+    if (WriteProtectedPaths.isProtected(f)) WriteProtectedPaths.deny("truncate", f)
+    super.truncate(f, newLength)
+  }
+
+  override def setTimes(f: Path, mtime: Long, atime: Long): Unit = {
+    if (WriteProtectedPaths.isProtected(f)) WriteProtectedPaths.deny("setTimes", f)
+    super.setTimes(f, mtime, atime)
+  }
+}
+
+/**
+ * Write protection for the Hadoop FileContext/AbstractFileSystem API
+ * (`fs.AbstractFileSystem.file.impl`).
+ *
+ * Needed because FileContextBasedCheckpointFileManager goes through FileContext, which
+ * bypasses the FileSystem-level write methods overridden in [[WriteProtectedLocalFileSystem]].
+ */
+class WriteProtectedAbstractFileSystem(uri: URI, conf: Configuration)
+    extends DelegateToFileSystem(
+      uri,
+      new WriteProtectedLocalFileSystem,
+      conf,
+      "file",
+      false) {
+
+  override def getUriDefaultPort(): Int = -1
+  override def getServerDefaults(): FsServerDefaults = LocalConfigKeys.getServerDefaults
+  override def isValidName(src: String): Boolean = true
+
+  override def createInternal(
+      f: Path,
+      flag: util.EnumSet[CreateFlag],
+      absolutePermission: FsPermission,
+      bufferSize: Int,
+      replication: Short,
+      blockSize: Long,
+      progress: Progressable,
+      checksumOpt: Options.ChecksumOpt,
+      createParent: Boolean): FSDataOutputStream = {
+    if (WriteProtectedPaths.isProtected(f)) WriteProtectedPaths.deny("create", f)
+    super.createInternal(
+      f, flag, absolutePermission, bufferSize, replication, blockSize,
+      progress, checksumOpt, createParent)
+  }
+
+  override def mkdir(
+      dir: Path, permission: FsPermission, createParent: Boolean): Unit = {
+    if (WriteProtectedPaths.isProtected(dir)) WriteProtectedPaths.deny("mkdir", dir)
+    super.mkdir(dir, permission, createParent)
+  }
+
+  override def delete(f: Path, recursive: Boolean): Boolean = {
+    if (WriteProtectedPaths.isProtected(f)) WriteProtectedPaths.deny("delete", f)
+    super.delete(f, recursive)
+  }
+
+  override def renameInternal(src: Path, dst: Path): Unit = {
+    // A rename out of a protected path is also a write to that path -- check both ends.
+    if (WriteProtectedPaths.isProtected(src)) WriteProtectedPaths.deny("rename from", src)
+    if (WriteProtectedPaths.isProtected(dst)) WriteProtectedPaths.deny("rename to", dst)
+    super.renameInternal(src, dst)
+  }
+
+  override def truncate(f: Path, newLength: Long): Boolean = {
+    if (WriteProtectedPaths.isProtected(f)) WriteProtectedPaths.deny("truncate", f)
+    super.truncate(f, newLength)
+  }
+
+  override def setTimes(f: Path, mtime: Long, atime: Long): Unit = {
+    if (WriteProtectedPaths.isProtected(f)) WriteProtectedPaths.deny("setTimes", f)
+    super.setTimes(f, mtime, atime)
+  }
+}
+
+/**
+ * Shared state for write-protected paths. Used by both [[WriteProtectedLocalFileSystem]]
+ * (FileSystem API) and [[WriteProtectedAbstractFileSystem]] (FileContext API).
+ *
+ * State is JVM-global: parallel suites in the same JVM would interfere. Tests in this
+ * package run serially via [[StateDataSourceTestBase]], which clears state in `afterEach`.
+ *
+ * Path normalization: prefixes are stored with a trailing "/", and matches use
+ * `pathStr.startsWith(prefix)`. Operations on the protected directory itself
+ * (without trailing "/") are NOT matched -- only operations on its descendants.
+ */
+object WriteProtectedPaths {

Review Comment:
   Thanks for flagging. I checked both parallelism axes and WriteProtectedPaths' global state is never accessed concurrently under Spark's test config:
   1. Suites in the same JVM — Spark forks a separate JVM per test group (SparkParallelTestGrouping / Test / testGrouping in SparkBuild.scala); Test / parallelExecution only parallelizes across those groups, which are separate OS processes. Within a single forked JVM, suites run serially — testForkedParallel is left at sbt's default of false.
   2. Test cases within a suite — none of the bases here (SparkFunSuite, StreamTest, SharedSparkSession) mix in ScalaTest's ParallelTestExecution, so a suite's tests run sequentially (ScalaTest's default). StreamTest.testStream is additionally synchronized to block concurrent stream runs. 
   
   So snapshotAndClear/restore are never interleaved across tests. Unfortunately, thread-local won't work since we need the paths to be respected across executor / async threads as well.



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-57269][SS] Enforce read-only access in the StateDateSource/StateMetadataSource [spark]

Posted by "liviazhu (via GitHub)" <gi...@apache.org>.
liviazhu commented on code in PR #56332:
URL: https://github.com/apache/spark/pull/56332#discussion_r3625983282


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/SymmetricHashJoinStateManager.scala:
##########
@@ -353,19 +400,34 @@ class SymmetricHashJoinStateManagerV4(
             stateStoreProvider.getClass.toString)
         }
         val opts = handlerSnapshotOptions.get
-        stateStoreProvider.asInstanceOf[SupportsFineGrainedReplay]
-          .replayStateFromSnapshot(
+        val replayer = stateStoreProvider.asInstanceOf[SupportsFineGrainedReplay]
+        if (readOnly) {
+          replayer.replayReadStateFromSnapshot(
             opts.snapshotVersion,
             opts.endVersion,
-            readOnly = true,
             opts.startStateStoreCkptId,
             opts.endStateStoreCkptId)
+        } else {
+          replayer.replayStateFromSnapshot(
+            opts.snapshotVersion,
+            opts.endVersion,
+            readOnly = false,
+            opts.startStateStoreCkptId,
+            opts.endStateStoreCkptId)
+        }
+      } else if (readOnly) {
+        stateStoreProvider.getReadStore(stateInfo.get.storeVersion, stateStoreCkptId)
       } else {
         stateStoreProvider.getStore(stateInfo.get.storeVersion, stateStoreCkptId)
       }
     }
-    logInfo(log"Loaded store ${MDC(STATE_STORE_ID, store.id)}")
-    store
+    if (readOnly) {
+      _readStateStore = handle
+      logInfo(log"Loaded read-only store ${MDC(STATE_STORE_ID, handle.id)}")
+    } else {
+      _stateStore = handle.asInstanceOf[StateStore]
+      logInfo(log"Loaded store ${MDC(STATE_STORE_ID, handle.id)}")
+    }

Review Comment:
   Hm can't think of a way to do this that makes it less complicated.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDBStateStoreProvider.scala:
##########
@@ -201,16 +201,44 @@ private[sql] class RocksDBStateStoreProvider
       }
     }
 
+    // Read-only registration: sets up the virtual column-family id and the key/value encoders
+    // needed to decode this family. Purely in-memory -- it does not write to the checkpoint and
+    // carries no write intent (no forced snapshot). Safe to call on a read-only store.
+    override def registerColFamily(
+        colFamilyName: String,
+        keySchema: StructType,
+        valueSchema: StructType,
+        keyStateEncoderSpec: KeyStateEncoderSpec,
+        useMultipleValuesPerKey: Boolean = false,
+        isInternal: Boolean = false): Unit = {
+      registerColFamilyInternal(colFamilyName, keySchema, valueSchema, keyStateEncoderSpec,
+        useMultipleValuesPerKey, isInternal, forceSnapshot = false)
+    }
+
     override def createColFamilyIfAbsent(
         colFamilyName: String,
         keySchema: StructType,
         valueSchema: StructType,
         keyStateEncoderSpec: KeyStateEncoderSpec,
         useMultipleValuesPerKey: Boolean = false,
         isInternal: Boolean = false): Unit = {
+      // Writable variant: same registration plus write intent -- a newly created family forces a
+      // snapshot on commit so it is durably persisted.
+      registerColFamilyInternal(colFamilyName, keySchema, valueSchema, keyStateEncoderSpec,
+        useMultipleValuesPerKey, isInternal, forceSnapshot = true)
+    }
+
+    private def registerColFamilyInternal(
+        colFamilyName: String,
+        keySchema: StructType,
+        valueSchema: StructType,
+        keyStateEncoderSpec: KeyStateEncoderSpec,
+        useMultipleValuesPerKey: Boolean,
+        isInternal: Boolean,
+        forceSnapshot: Boolean): Unit = {
       validateAndTransitionState(UPDATE)
       verifyColFamilyCreationOrDeletion("create_col_family", colFamilyName, isInternal)
-      val cfId = rocksDB.createColFamilyIfAbsent(colFamilyName, isInternal)
+      val cfId = rocksDB.createColFamilyIfAbsent(colFamilyName, isInternal, forceSnapshot)

Review Comment:
   Done



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-57269][SS] Enforce read-only access in the StateDateSource/StateMetadataSource [spark]

Posted by "shrirangmhalgi (via GitHub)" <gi...@apache.org>.
shrirangmhalgi commented on code in PR #56332:
URL: https://github.com/apache/spark/pull/56332#discussion_r3364758245


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/HDFSBackedStateStoreProvider.scala:
##########
@@ -149,7 +149,10 @@ private[sql] class HDFSBackedStateStoreProvider extends StateStoreProvider with
     private val newVersion = version + 1
     @volatile private var state: STATE = UPDATING
     private val finalDeltaFile: Path = deltaFile(newVersion)
-    private lazy val deltaFileStream = fm.createAtomic(finalDeltaFile, overwriteIfPossible = true)
+    private lazy val deltaFileStream = {
+      createBaseDirIfNotExists()

Review Comment:
   Nit: `baseDirChecked` is `@volatile` but not atomically guarded - two concurrent tasks on the same partition can both enter the `if (!baseDirChecked)` block and issue parallel `mkdirs`. On HDFS this is idempotent, but on some object stores a racing `mkdirs` against an already-created marker can fail. 
   
   Maybe consider `AtomicBoolean.compareAndSet(false, true)` here.
   



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-57269][SS] Enforce read-only access in the StateDateSource/StateMetadataSource [spark]

Posted by "shrirangmhalgi (via GitHub)" <gi...@apache.org>.
shrirangmhalgi commented on code in PR #56332:
URL: https://github.com/apache/spark/pull/56332#discussion_r3364783855


##########
sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/v2/state/WriteProtectedLocalFileSystem.scala:
##########
@@ -0,0 +1,348 @@
+/*
+ * 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.spark.sql.execution.datasources.v2.state
+
+import java.net.URI
+import java.nio.file.AccessDeniedException
+import java.util
+import java.util.concurrent.atomic.AtomicReference
+
+import scala.jdk.CollectionConverters._
+
+import org.apache.hadoop.conf.Configuration
+import org.apache.hadoop.fs.{CreateFlag, DelegateToFileSystem, FSDataOutputStream, FsServerDefaults, Options, Path}
+import org.apache.hadoop.fs.local.LocalConfigKeys
+import org.apache.hadoop.fs.permission.FsPermission
+import org.apache.hadoop.util.Progressable
+import org.scalatest.BeforeAndAfterEach
+
+import org.apache.spark.SparkConf
+import org.apache.spark.sql.streaming.StreamTest
+
+/**
+ * Write protection for the Hadoop FileSystem API (`fs.file.impl`).
+ *
+ * Extends [[org.apache.spark.DebugFilesystem]] so it replaces DebugFilesystem
+ * without losing open-connection tracking. Every write entry point is overridden to deny
+ * the operation when the target path is protected; reads are left untouched.
+ */
+class WriteProtectedLocalFileSystem extends org.apache.spark.DebugFilesystem {
+
+  override def create(
+      f: Path,
+      permission: FsPermission,
+      overwrite: Boolean,
+      bufferSize: Int,
+      replication: Short,
+      blockSize: Long,
+      progress: Progressable): FSDataOutputStream = {
+    if (WriteProtectedPaths.isProtected(f)) WriteProtectedPaths.deny("create", f)
+    super.create(f, permission, overwrite, bufferSize, replication, blockSize, progress)
+  }
+
+  override def create(
+      f: Path,
+      permission: FsPermission,
+      flags: util.EnumSet[CreateFlag],
+      bufferSize: Int,
+      replication: Short,
+      blockSize: Long,
+      progress: Progressable,
+      checksumOpt: Options.ChecksumOpt): FSDataOutputStream = {
+    if (WriteProtectedPaths.isProtected(f)) WriteProtectedPaths.deny("create", f)
+    super.create(
+      f, permission, flags, bufferSize, replication, blockSize, progress, checksumOpt)
+  }
+
+  override def createNonRecursive(
+      f: Path,
+      permission: FsPermission,
+      flags: util.EnumSet[CreateFlag],
+      bufferSize: Int,
+      replication: Short,
+      blockSize: Long,
+      progress: Progressable): FSDataOutputStream = {
+    if (WriteProtectedPaths.isProtected(f)) WriteProtectedPaths.deny("createNonRecursive", f)
+    super.createNonRecursive(f, permission, flags, bufferSize, replication, blockSize, progress)
+  }
+
+  override def append(f: Path, bufferSize: Int, progress: Progressable): FSDataOutputStream = {
+    if (WriteProtectedPaths.isProtected(f)) WriteProtectedPaths.deny("append", f)
+    super.append(f, bufferSize, progress)
+  }
+
+  override def rename(src: Path, dst: Path): Boolean = {
+    // A rename out of a protected path is also a write to that path -- check both ends.
+    if (WriteProtectedPaths.isProtected(src)) WriteProtectedPaths.deny("rename from", src)
+    if (WriteProtectedPaths.isProtected(dst)) WriteProtectedPaths.deny("rename to", dst)
+    super.rename(src, dst)
+  }
+
+  override def delete(f: Path, recursive: Boolean): Boolean = {
+    if (WriteProtectedPaths.isProtected(f)) WriteProtectedPaths.deny("delete", f)
+    super.delete(f, recursive)
+  }
+
+  override def mkdirs(f: Path, permission: FsPermission): Boolean = {
+    if (WriteProtectedPaths.isProtected(f)) WriteProtectedPaths.deny("mkdirs", f)
+    super.mkdirs(f, permission)
+  }
+
+  override def truncate(f: Path, newLength: Long): Boolean = {
+    if (WriteProtectedPaths.isProtected(f)) WriteProtectedPaths.deny("truncate", f)
+    super.truncate(f, newLength)
+  }
+
+  override def setTimes(f: Path, mtime: Long, atime: Long): Unit = {
+    if (WriteProtectedPaths.isProtected(f)) WriteProtectedPaths.deny("setTimes", f)
+    super.setTimes(f, mtime, atime)
+  }
+}
+
+/**
+ * Write protection for the Hadoop FileContext/AbstractFileSystem API
+ * (`fs.AbstractFileSystem.file.impl`).
+ *
+ * Needed because FileContextBasedCheckpointFileManager goes through FileContext, which
+ * bypasses the FileSystem-level write methods overridden in [[WriteProtectedLocalFileSystem]].
+ */
+class WriteProtectedAbstractFileSystem(uri: URI, conf: Configuration)
+    extends DelegateToFileSystem(
+      uri,
+      new WriteProtectedLocalFileSystem,
+      conf,
+      "file",
+      false) {
+
+  override def getUriDefaultPort(): Int = -1
+  override def getServerDefaults(): FsServerDefaults = LocalConfigKeys.getServerDefaults
+  override def isValidName(src: String): Boolean = true
+
+  override def createInternal(
+      f: Path,
+      flag: util.EnumSet[CreateFlag],
+      absolutePermission: FsPermission,
+      bufferSize: Int,
+      replication: Short,
+      blockSize: Long,
+      progress: Progressable,
+      checksumOpt: Options.ChecksumOpt,
+      createParent: Boolean): FSDataOutputStream = {
+    if (WriteProtectedPaths.isProtected(f)) WriteProtectedPaths.deny("create", f)
+    super.createInternal(
+      f, flag, absolutePermission, bufferSize, replication, blockSize,
+      progress, checksumOpt, createParent)
+  }
+
+  override def mkdir(
+      dir: Path, permission: FsPermission, createParent: Boolean): Unit = {
+    if (WriteProtectedPaths.isProtected(dir)) WriteProtectedPaths.deny("mkdir", dir)
+    super.mkdir(dir, permission, createParent)
+  }
+
+  override def delete(f: Path, recursive: Boolean): Boolean = {
+    if (WriteProtectedPaths.isProtected(f)) WriteProtectedPaths.deny("delete", f)
+    super.delete(f, recursive)
+  }
+
+  override def renameInternal(src: Path, dst: Path): Unit = {
+    // A rename out of a protected path is also a write to that path -- check both ends.
+    if (WriteProtectedPaths.isProtected(src)) WriteProtectedPaths.deny("rename from", src)
+    if (WriteProtectedPaths.isProtected(dst)) WriteProtectedPaths.deny("rename to", dst)
+    super.renameInternal(src, dst)
+  }
+
+  override def truncate(f: Path, newLength: Long): Boolean = {
+    if (WriteProtectedPaths.isProtected(f)) WriteProtectedPaths.deny("truncate", f)
+    super.truncate(f, newLength)
+  }
+
+  override def setTimes(f: Path, mtime: Long, atime: Long): Unit = {
+    if (WriteProtectedPaths.isProtected(f)) WriteProtectedPaths.deny("setTimes", f)
+    super.setTimes(f, mtime, atime)
+  }
+}
+
+/**
+ * Shared state for write-protected paths. Used by both [[WriteProtectedLocalFileSystem]]
+ * (FileSystem API) and [[WriteProtectedAbstractFileSystem]] (FileContext API).
+ *
+ * State is JVM-global: parallel suites in the same JVM would interfere. Tests in this
+ * package run serially via [[StateDataSourceTestBase]], which clears state in `afterEach`.
+ *
+ * Path normalization: prefixes are stored with a trailing "/", and matches use
+ * `pathStr.startsWith(prefix)`. Operations on the protected directory itself
+ * (without trailing "/") are NOT matched -- only operations on its descendants.
+ */
+object WriteProtectedPaths {

Review Comment:
   `WriteProtectedPaths` uses JVM-global mutable state (`AtomicReference[Set[String]]`). The doc comment notes "assumes a single suite runs at a time within a JVM" - but sbt's default is to fork one JVM per project and run suites in parallel within that JVM. If any other suite in `sql/core` touches state store paths concurrently, `isProtected` will false-positive. Is there a guarantee these suites run serially (e.g., via a shared `Sequential` tag), or should this use a thread-local / suite-scoped key to avoid flaky failures when new suites are added?
   
   



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-57269][SS] Enforce read-only access in the StateDateSource/StateMetadataSource [spark]

Posted by "liviazhu (via GitHub)" <gi...@apache.org>.
liviazhu commented on code in PR #56332:
URL: https://github.com/apache/spark/pull/56332#discussion_r3365647220


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/HDFSBackedStateStoreProvider.scala:
##########
@@ -149,7 +149,10 @@ private[sql] class HDFSBackedStateStoreProvider extends StateStoreProvider with
     private val newVersion = version + 1
     @volatile private var state: STATE = UPDATING
     private val finalDeltaFile: Path = deltaFile(newVersion)
-    private lazy val deltaFileStream = fm.createAtomic(finalDeltaFile, overwriteIfPossible = true)
+    private lazy val deltaFileStream = {
+      createBaseDirIfNotExists()

Review Comment:
   Fixed



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-57269][SS] Enforce read-only access in the StateDateSource/StateMetadataSource [spark]

Posted by "ericm-db (via GitHub)" <gi...@apache.org>.
ericm-db commented on code in PR #56332:
URL: https://github.com/apache/spark/pull/56332#discussion_r3616794911


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/SymmetricHashJoinStateManager.scala:
##########
@@ -353,19 +400,34 @@ class SymmetricHashJoinStateManagerV4(
             stateStoreProvider.getClass.toString)
         }
         val opts = handlerSnapshotOptions.get
-        stateStoreProvider.asInstanceOf[SupportsFineGrainedReplay]
-          .replayStateFromSnapshot(
+        val replayer = stateStoreProvider.asInstanceOf[SupportsFineGrainedReplay]
+        if (readOnly) {
+          replayer.replayReadStateFromSnapshot(
             opts.snapshotVersion,
             opts.endVersion,
-            readOnly = true,
             opts.startStateStoreCkptId,
             opts.endStateStoreCkptId)
+        } else {
+          replayer.replayStateFromSnapshot(
+            opts.snapshotVersion,
+            opts.endVersion,
+            readOnly = false,
+            opts.startStateStoreCkptId,
+            opts.endStateStoreCkptId)
+        }
+      } else if (readOnly) {
+        stateStoreProvider.getReadStore(stateInfo.get.storeVersion, stateStoreCkptId)
       } else {
         stateStoreProvider.getStore(stateInfo.get.storeVersion, stateStoreCkptId)
       }
     }
-    logInfo(log"Loaded store ${MDC(STATE_STORE_ID, store.id)}")
-    store
+    if (readOnly) {
+      _readStateStore = handle
+      logInfo(log"Loaded read-only store ${MDC(STATE_STORE_ID, handle.id)}")
+    } else {
+      _stateStore = handle.asInstanceOf[StateStore]
+      logInfo(log"Loaded store ${MDC(STATE_STORE_ID, handle.id)}")
+    }

Review Comment:
   Is there any way to consolidate the if-else statements here to one if else?



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDBStateStoreProvider.scala:
##########
@@ -201,16 +201,44 @@ private[sql] class RocksDBStateStoreProvider
       }
     }
 
+    // Read-only registration: sets up the virtual column-family id and the key/value encoders
+    // needed to decode this family. Purely in-memory -- it does not write to the checkpoint and
+    // carries no write intent (no forced snapshot). Safe to call on a read-only store.
+    override def registerColFamily(
+        colFamilyName: String,
+        keySchema: StructType,
+        valueSchema: StructType,
+        keyStateEncoderSpec: KeyStateEncoderSpec,
+        useMultipleValuesPerKey: Boolean = false,
+        isInternal: Boolean = false): Unit = {
+      registerColFamilyInternal(colFamilyName, keySchema, valueSchema, keyStateEncoderSpec,
+        useMultipleValuesPerKey, isInternal, forceSnapshot = false)
+    }
+
     override def createColFamilyIfAbsent(
         colFamilyName: String,
         keySchema: StructType,
         valueSchema: StructType,
         keyStateEncoderSpec: KeyStateEncoderSpec,
         useMultipleValuesPerKey: Boolean = false,
         isInternal: Boolean = false): Unit = {
+      // Writable variant: same registration plus write intent -- a newly created family forces a
+      // snapshot on commit so it is durably persisted.
+      registerColFamilyInternal(colFamilyName, keySchema, valueSchema, keyStateEncoderSpec,
+        useMultipleValuesPerKey, isInternal, forceSnapshot = true)
+    }
+
+    private def registerColFamilyInternal(
+        colFamilyName: String,
+        keySchema: StructType,
+        valueSchema: StructType,
+        keyStateEncoderSpec: KeyStateEncoderSpec,
+        useMultipleValuesPerKey: Boolean,
+        isInternal: Boolean,
+        forceSnapshot: Boolean): Unit = {
       validateAndTransitionState(UPDATE)
       verifyColFamilyCreationOrDeletion("create_col_family", colFamilyName, isInternal)
-      val cfId = rocksDB.createColFamilyIfAbsent(colFamilyName, isInternal)
+      val cfId = rocksDB.createColFamilyIfAbsent(colFamilyName, isInternal, forceSnapshot)

Review Comment:
   could we just pass in readOnly here instead of adding the forceSnapshot boolean?



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org