This is an automated email from the ASF dual-hosted git repository.
Xuanwo pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/opendal.git
The following commit(s) were added to refs/heads/main by this push:
new 5b8347854d fix(services/persy): replace overwritten records, serialize
writes, and initialize datafiles (#8917)
5b8347854d is described below
commit 5b8347854df15381dc7af260a18efea26a16c115
Author: Xuanwo <[email protected]>
AuthorDate: Tue Nov 24 03:11:36 2026 +0800
fix(services/persy): replace overwritten records, serialize writes, and
initialize datafiles (#8917)
fix(services/persy): update records in place and initialize existing
datafiles
`PersyCore::set` inserted a new record and replaced the index entry on every
write, leaving the previous record orphaned in the segment so the datafile
grew with each overwrite. Read the index inside the write transaction and
update the existing record in place instead.
`PersyCore::delete` resolved the record id outside the write transaction, so
concurrent deletes could act on an id that the index no longer referred to
and fail with `RecordNotFound`. Read the id in the transaction that removes
the record and the index entry, and return `Ok(())` when the path is absent.
Serialize write transactions: persy acquires its record and index locks only
in `prepare`, so read-modify-write transactions started at the same time can
all observe the same index entry, and every transaction but the winner fails
with `RecordNotFound`. Persy holds an exclusive file lock on the datafile,
so
the lock covers every writer of the database.
`PersyBuilder::build` relied on `prepare_with`, which persy runs only while
creating a datafile. Opening an existing datafile with a new segment or
index
succeeded, but every later operation failed with `SegmentNotFound` or
`IndexNotFound`. Create the configured segment and index after opening and
cover all three fixes with regression tests.
---
core/services/persy/src/backend.rs | 47 +++------
core/services/persy/src/core.rs | 164 +++++++++++++++++++++++-------
core/services/persy/tests/transactions.rs | 120 ++++++++++++++++++++++
3 files changed, 266 insertions(+), 65 deletions(-)
diff --git a/core/services/persy/src/backend.rs
b/core/services/persy/src/backend.rs
index 1245041a0c..e02bd0c9f2 100644
--- a/core/services/persy/src/backend.rs
+++ b/core/services/persy/src/backend.rs
@@ -17,6 +17,7 @@
use std::fmt::Debug;
use std::sync::Arc;
+use std::sync::Mutex;
use super::PERSY_SCHEME;
use super::config::PersyConfig;
@@ -63,23 +64,18 @@ impl Builder for PersyBuilder {
.with_context("service", PERSY_SCHEME)
})?;
- let segment_name = self.config.segment.ok_or_else(|| {
+ let segment = self.config.segment.ok_or_else(|| {
Error::new(ErrorKind::ConfigInvalid, "segment is required but not
set")
.with_context("service", PERSY_SCHEME)
})?;
- let segment = segment_name.clone();
-
- let index_name = self.config.index.ok_or_else(|| {
+ let index = self.config.index.ok_or_else(|| {
Error::new(ErrorKind::ConfigInvalid, "index is required but not
set")
.with_context("service", PERSY_SCHEME)
})?;
- let index = index_name.clone();
-
let persy = persy::OpenOptions::new()
.create(true)
- .prepare_with(move |p| init(p, &segment_name, &index_name))
.open(&datafile_path)
.map_err(|e| {
Error::new(ErrorKind::ConfigInvalid, "open db")
@@ -88,33 +84,22 @@ impl Builder for PersyBuilder {
.set_source(e)
})?;
- // This function will only be called on database creation
- fn init(
- persy: &persy::Persy,
- segment_name: &str,
- index_name: &str,
- ) -> Result<(), Box<dyn std::error::Error>> {
- let mut tx = persy.begin()?;
-
- if !tx.exists_segment(segment_name)? {
- tx.create_segment(segment_name)?;
- }
- if !tx.exists_index(index_name)? {
- tx.create_index::<String, persy::PersyId>(index_name,
persy::ValueMode::Replace)?;
- }
-
- let prepared = tx.prepare()?;
- prepared.commit()?;
-
- Ok(())
- }
-
- Ok(PersyBackend::new(PersyCore {
- datafile: datafile_path,
+ let core = PersyCore {
+ datafile: datafile_path.clone(),
segment,
index,
persy,
- }))
+ write_lock: Arc::new(Mutex::new(())),
+ };
+
+ // `persy` only runs the initialization of a datafile while creating
it, so an
+ // already existing datafile needs its segment and index created here.
+ core.init().map_err(|err| {
+ err.with_context("service", PERSY_SCHEME)
+ .with_context("datafile", datafile_path)
+ })?;
+
+ Ok(PersyBackend::new(core))
}
}
diff --git a/core/services/persy/src/core.rs b/core/services/persy/src/core.rs
index 60a64ac566..d480e1e31d 100644
--- a/core/services/persy/src/core.rs
+++ b/core/services/persy/src/core.rs
@@ -16,6 +16,9 @@
// under the License.
use std::fmt::Debug;
+use std::sync::Arc;
+use std::sync::Mutex;
+use std::sync::MutexGuard;
use opendal_core::raw::ServiceOperation;
use opendal_core::*;
@@ -38,6 +41,13 @@ pub struct PersyCore {
pub segment: String,
pub index: String,
pub persy: persy::Persy,
+ /// Serializes write transactions so that reading the index and updating
the record
+ /// happen without another writer committing in between. `persy` acquires
its data
+ /// locks only in `prepare`, so concurrent transactions would otherwise
act on stale
+ /// index entries and the loser would fail with `RecordNotFound` instead
of observing
+ /// the committed write. `persy` holds an exclusive file lock for the
datafile, so this
+ /// lock covers every writer of the database.
+ pub write_lock: Arc<Mutex<()>>,
}
impl Debug for PersyCore {
@@ -51,6 +61,57 @@ impl Debug for PersyCore {
}
impl PersyCore {
+ fn lock_write(&self) -> MutexGuard<'_, ()> {
+ // A panic while writing must not disable writes for the rest of the
database.
+ self.write_lock
+ .lock()
+ .unwrap_or_else(|err| err.into_inner())
+ }
+
+ /// Create the configured segment and index if they are missing.
+ ///
+ /// `persy` initializes a datafile only while creating the file itself, so
a datafile
+ /// that already exists must be initialized explicitly before it can be
used.
+ pub fn init(&self) -> Result<()> {
+ let mut tx = self.persy.begin().map_err(|err| {
+
parse_error(ErrorContext::new(ServiceOperation("BeginTransaction")), err)
+ })?;
+
+ if !tx
+ .exists_segment(&self.segment)
+ .map_err(|err|
parse_error(ErrorContext::new(ServiceOperation("ExistsSegment")), err))?
+ {
+ tx.create_segment(&self.segment).map_err(|err| {
+
parse_error(ErrorContext::new(ServiceOperation("CreateSegment")), err)
+ })?;
+ }
+
+ if !tx
+ .exists_index(&self.index)
+ .map_err(|err|
parse_error(ErrorContext::new(ServiceOperation("ExistsIndex")), err))?
+ {
+ tx.create_index::<String, persy::PersyId>(&self.index,
persy::ValueMode::Replace)
+ .map_err(|err| {
+
parse_error(ErrorContext::new(ServiceOperation("CreateIndex")), err)
+ })?;
+ }
+
+ let prepared = tx.prepare().map_err(|err| {
+ parse_error(
+ ErrorContext::new(ServiceOperation("PrepareTransaction")),
+ err,
+ )
+ })?;
+ prepared.commit().map_err(|err| {
+ parse_error(
+ ErrorContext::new(ServiceOperation("CommitTransaction")),
+ err,
+ )
+ })?;
+
+ Ok(())
+ }
+
pub fn get(&self, path: &str) -> Result<Option<Buffer>> {
let mut read_id = self
.persy
@@ -67,15 +128,36 @@ impl PersyCore {
}
pub fn set(&self, path: &str, value: Buffer) -> Result<()> {
+ let _guard = self.lock_write();
+
let mut tx = self.persy.begin().map_err(|err| {
parse_error(ErrorContext::new(ServiceOperation("BeginTransaction")), err)
})?;
+
+ let path = path.to_string();
+ let value = value.to_vec();
+
+ // Read the record id in this transaction so that overwriting a path
updates the
+ // record the index already refers to instead of inserting an orphaned
one.
let id = tx
- .insert(&self.segment, &value.to_vec())
- .map_err(|err|
parse_error(ErrorContext::new(ServiceOperation("InsertRecord")), err))?;
+ .one::<String, persy::PersyId>(&self.index, &path)
+ .map_err(|err|
parse_error(ErrorContext::new(ServiceOperation("GetIndex")), err))?;
+
+ match id {
+ Some(id) => tx.update(&self.segment, &id, &value).map_err(|err| {
+
parse_error(ErrorContext::new(ServiceOperation("UpdateRecord")), err)
+ })?,
+ None => {
+ let id = tx.insert(&self.segment, &value).map_err(|err| {
+
parse_error(ErrorContext::new(ServiceOperation("InsertRecord")), err)
+ })?;
+ tx.put::<String, persy::PersyId>(&self.index, path, id)
+ .map_err(|err| {
+
parse_error(ErrorContext::new(ServiceOperation("PutIndex")), err)
+ })?;
+ }
+ }
- tx.put::<String, persy::PersyId>(&self.index, path.to_string(), id)
- .map_err(|err|
parse_error(ErrorContext::new(ServiceOperation("PutIndex")), err))?;
let prepared = tx.prepare().map_err(|err| {
parse_error(
ErrorContext::new(ServiceOperation("PrepareTransaction")),
@@ -93,45 +175,59 @@ impl PersyCore {
}
pub fn delete(&self, path: &str) -> Result<()> {
- let mut delete_id = self
- .persy
- .get::<String, persy::PersyId>(&self.index, &path.to_string())
+ let _guard = self.lock_write();
+
+ let mut tx = self.persy.begin().map_err(|err| {
+
parse_error(ErrorContext::new(ServiceOperation("BeginTransaction")), err)
+ })?;
+
+ let path = path.to_string();
+
+ // Look up the record id inside the transaction that removes the
record and its
+ // index entry, so both always refer to the same record.
+ let id = tx
+ .one::<String, persy::PersyId>(&self.index, &path)
.map_err(|err|
parse_error(ErrorContext::new(ServiceOperation("GetIndex")), err))?;
- if let Some(id) = delete_id.next() {
- // Begin a transaction.
- let mut tx = self.persy.begin().map_err(|err| {
-
parse_error(ErrorContext::new(ServiceOperation("BeginTransaction")), err)
- })?;
- // Delete the record.
- tx.delete(&self.segment, &id).map_err(|err| {
-
parse_error(ErrorContext::new(ServiceOperation("DeleteRecord")), err)
- })?;
- // Remove the index.
- tx.remove::<String, persy::PersyId>(&self.index, path.to_string(),
Some(id))
- .map_err(|err| {
-
parse_error(ErrorContext::new(ServiceOperation("RemoveIndex")), err)
- })?;
- // Commit the tx.
- let prepared = tx.prepare().map_err(|err| {
- parse_error(
- ErrorContext::new(ServiceOperation("PrepareTransaction")),
- err,
- )
- })?;
- prepared.commit().map_err(|err| {
- parse_error(
- ErrorContext::new(ServiceOperation("CommitTransaction")),
+ let Some(id) = id else {
+ return Ok(());
+ };
+
+ if let Err(err) = tx.delete(&self.segment, &id) {
+ let err = err.persy_error();
+ if !matches!(err, persy::PersyError::RecordNotFound(_)) {
+ return Err(parse_persy_error(
+ ErrorContext::new(ServiceOperation("DeleteRecord")),
err,
- )
- })?;
+ ));
+ }
+ // The record is already gone, so only the index entry below needs
removal.
}
+ tx.remove::<String, persy::PersyId>(&self.index, path, Some(id))
+ .map_err(|err|
parse_error(ErrorContext::new(ServiceOperation("RemoveIndex")), err))?;
+
+ let prepared = tx.prepare().map_err(|err| {
+ parse_error(
+ ErrorContext::new(ServiceOperation("PrepareTransaction")),
+ err,
+ )
+ })?;
+ prepared.commit().map_err(|err| {
+ parse_error(
+ ErrorContext::new(ServiceOperation("CommitTransaction")),
+ err,
+ )
+ })?;
+
Ok(())
}
}
fn parse_error<T: Into<persy::PersyError>>(ctx: ErrorContext, err:
persy::PE<T>) -> Error {
- let err: persy::PersyError = err.persy_error();
+ parse_persy_error(ctx, err.persy_error())
+}
+
+fn parse_persy_error(ctx: ErrorContext, err: persy::PersyError) -> Error {
let kind = match err {
persy::PersyError::RecordNotFound(_) => ErrorKind::NotFound,
_ => ErrorKind::Unexpected,
diff --git a/core/services/persy/tests/transactions.rs
b/core/services/persy/tests/transactions.rs
new file mode 100644
index 0000000000..3416f108fa
--- /dev/null
+++ b/core/services/persy/tests/transactions.rs
@@ -0,0 +1,120 @@
+// 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.
+
+use std::path::Path;
+use std::path::PathBuf;
+use std::sync::Arc;
+use std::sync::atomic::AtomicU64;
+use std::sync::atomic::Ordering;
+
+use opendal_core::Operator;
+use opendal_service_persy::Persy;
+
+/// Temporary directory removed together with its contents when dropped.
+struct TempDir {
+ path: PathBuf,
+}
+
+impl TempDir {
+ fn new() -> Self {
+ static NEXT: AtomicU64 = AtomicU64::new(0);
+
+ let path = std::env::temp_dir().join(format!(
+ "opendal-persy-{}-{}",
+ std::process::id(),
+ NEXT.fetch_add(1, Ordering::Relaxed)
+ ));
+ std::fs::create_dir_all(&path).expect("create temporary directory");
+
+ Self { path }
+ }
+
+ fn path(&self) -> &Path {
+ &self.path
+ }
+}
+
+impl Drop for TempDir {
+ fn drop(&mut self) {
+ let _ = std::fs::remove_dir_all(&self.path);
+ }
+}
+
+fn build_operator(datafile: &Path, segment: &str, index: &str) -> Operator {
+ Operator::new(
+ Persy::default()
+ .datafile(datafile.to_str().expect("datafile path is UTF-8"))
+ .segment(segment)
+ .index(index),
+ )
+ .expect("build operator")
+}
+
+#[tokio::test]
+async fn overwrite_replaces_record_instead_of_leaking() {
+ let dir = TempDir::new();
+ let datafile = dir.path().join("db.persy");
+ let op = build_operator(&datafile, "data", "index");
+
+ for round in 0..20 {
+ op.write("k", format!("value-{round}")).await.unwrap();
+ }
+ assert_eq!(op.read("k").await.unwrap().to_vec(), b"value-19");
+
+ drop(op);
+
+ let persy = persy::OpenOptions::new().open(&datafile).unwrap();
+ assert_eq!(persy.scan("data").unwrap().count(), 1);
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 8)]
+async fn concurrent_delete_is_idempotent() {
+ let dir = TempDir::new();
+ let datafile = dir.path().join("db.persy");
+ let op = Arc::new(build_operator(&datafile, "data", "index"));
+
+ for round in 0..8 {
+ op.write("k", format!("value-{round}")).await.unwrap();
+
+ let mut deletes = Vec::new();
+ for _ in 0..16 {
+ let op = op.clone();
+ deletes.push(tokio::spawn(async move { op.delete("k").await }));
+ }
+ for delete in deletes {
+ delete.await.unwrap().unwrap();
+ }
+ }
+}
+
+#[tokio::test]
+async fn build_initializes_new_segment_and_index_in_existing_datafile() {
+ let dir = TempDir::new();
+ let datafile = dir.path().join("db.persy");
+
+ {
+ let op = build_operator(&datafile, "s1", "i1");
+ op.write("k", "value-1").await.unwrap();
+ assert_eq!(op.read("k").await.unwrap().to_vec(), b"value-1");
+ }
+
+ {
+ let op = build_operator(&datafile, "s2", "i2");
+ op.write("k", "value-2").await.unwrap();
+ assert_eq!(op.read("k").await.unwrap().to_vec(), b"value-2");
+ }
+}