Repository navigation
Share one engine per storage directory in a process; lock it against other processes - #2131
Conversation
Two instances on one file storage root are not coordinated: each serves its own cached state, and their writes race each other's compare-and-swap instead of queueing on one per-ledger write lock, while both index and sweep the same files. Nothing stopped a second process, or a second instance in the same process, from opening a root another was using. `FlureeBuilder::with_storage_lock()` takes an exclusive OS lock on `<root>/.fluree-lock` before the root is swept or its WAL replayed. Building a second locked instance on the root, in any process, fails with the new `ApiError::StorageInUse` (423, `err:system/StorageInUse`), which names the holder's pid where the lock file can be read (not on Windows). The lock lasts as long as the instance: every clone shares it, and it is released when the last clone is dropped or the process exits, however it exits. Taking it fails closed. A filesystem that cannot lock refuses the open unless FLUREE_STORAGE_ALLOW_UNLOCKED allows it unprotected, and any other error, such as an unwritable lock file, fails the build. The option is opt-in and refused together with a shared WAL owner, since a Raft cluster's payload root is shared on purpose. Storage listings skip the lock file. `SharedFluree::open(path, SharedOptions)` gives every caller in a process that opens a root, by any spelling, the same locked instance. A join that asks for other settings (background indexing on or off) is refused. The handles own the lifecycle: the instance shuts down once the last handle is closed or dropped, in a task of its own, so a cancelled `close()` cannot cut the shutdown short and let another owner in while the WAL is still being retired. `disconnect()` on a shared instance does nothing, and a `Fluree` cloned from a handle keeps the root locked until it drops. An open that finds the root still shutting down waits for it, then opens it afresh.
Each `fluree.connect(path)` built an engine of its own, so threads that each opened a connection to one directory, the habit sqlite3 teaches, ran separate engines on it. Their commits raced: with 16 threads writing 25 inserts each through their own connections, 138 of the 400 failed with a ConflictError after running out of commit retries. Each engine also served reads from its own cache, so one connection did not see another's commits. `connect(path)` now opens the directory through `SharedFluree`: every connection in the process to a directory shares one engine, and it shuts down when the last of them closes. Connections must agree on `indexing`. Each call holds its own reference to the engine while it runs, and `close()` gives the connection's reference back at once, so a closed connection releases the directory even while ledgers or snapshots opened through it are still alive. The engine holds the directory's lock, so another process that opens it meanwhile raises the new `fluree.DatabaseInUseError`, whose `pid` names the holder. `connect(config=...)` to file storage takes the lock too, but is not shared. The README's concurrency section and the `connect` and `close` docstrings say so, and `indexing=False` no longer suggests that another process may index the same directory. test_fork's spawned worker opened the directory its parent held; it now checks that this is refused and works on a directory of its own.
Two `fluree server run` in one project both started as transactors on the same storage, each serving stale reads of the other's commits. `server start` decided "already running" from whether its recorded pid was alive, which a foreground server (no PID file) slipped past and a reused pid after a crash wrongly tripped. `ServerConfig::owns_storage_root()` is the one decision about who may lock: a transaction server, not a shared-storage peer, which reads its transaction server's root, or a Raft node, whose cluster shares one payload root. Server init locks the root when `storage_lock` (not a flag; the CLI's `server run` and the `server start` child set it) asks and the server owns it, and `server start`'s preflight asks the same question. A second owning server, or any other process taking the lock, is refused with the holder's pid. For a server that will lock its file storage, `start` checks the lock before launching anything, so it names a holder of either kind, ignores a live but unrelated recorded pid, and fails closed on a lock error as the server itself would. A peer, a Raft node or a connection-config server keeps the pid check, so a peer starts against its running transaction server's storage. A foreground server writes `server.meta.json` only once its init has taken the lock: before, a refused second `server run` overwrote the running server's metadata and then deleted it, breaking CLI auto-routing to the server still running. The storage guide gains "One process per directory": what takes the lock, what does not yet (one-shot CLI commands run with `--direct` or without a server, Rust programs that do not ask for it), and FLUREE_STORAGE_ALLOW_UNLOCKED, also listed among the environment variables.
A refusal told "this process holds the root" from "another process does" by reading the holder's pid from the lock file. Windows does not let a second handle read a locked file, so there a second open in the same process (a path connection beside a config connection to the same directory) got the cross-process message, telling the user to run a server instead of reusing the instance they already have. The lock now keeps the set of roots this process holds and checks it first; the lock file is read only for a holder in another process. A root leaves the set before its handle closes, so a root that another lock has just taken is never still listed as held here.
… ends `build_async` and the file client build take the root's lock, then replay the WAL on the blocking pool. If the caller dropped the build while the replay was running or still queued, the lock went with the dropped future and the replay carried on: another owner could take the root while this one was still replaying into it. The replay now runs in a spawned task that owns the lock and hands it back when it ends, so a caller that stops waiting no longer frees the root early.
Brings the fix that holds the root lock through a cancelled build's WAL replay. On next a build also migrates the nameservice after replay, and that writes the store too, so the task that holds the lock runs both.
aaj3f
left a comment
There was a problem hiding this comment.
@bplatz this is really nice, and at a design level no pushback from me: one OS lock as the oracle (the RocksDB/SQLite/LMDB shape #2040 proposed), failing closed, and SharedFluree meeting Python users where the sqlite3 habit actually puts them, one connection per thread. I went looking for the identity-by-path trap we keep hitting (a thing named by its spelling rather than by what it is), and I think it's answered twice here: the registry keys on the canonical path (on APFS, Data/data/./Data/./a symlink all resolve to one key; I checked), and the lock itself lives on the inode, so a spelling the registry misses still fails closed in-process instead of opening a second engine.
Two headline notes. (1) The lock's lifetime under fork(): flock belongs to the open file description, so a child forked while a connection is open keeps the directory locked after the parent closes it, and the parent's next open is then told the directory is "already open in this process". #2040's design already said the child should close the handle it inherited, so I think that belongs here. (2) A class I'd name: state torn when a caller drops the future that owned it (#1261, #1718 and #2023 before this). This PR already handles it in two places: the replay task owns the lock (d1df1a5), and close() shuts down in a task of its own. SharedFluree::open is the one site left. A cancelled open clears its registry slot while its replay still holds the lock, and I reproduced the next open failing. The point fix belongs here. The class fix (maybe a harness that drops each public async method at every await) isn't for this PR.
Full review below:
✅ Approve with nits.
This is carefully built, @bplatz. The lock is taken before the sweep and the WAL replay, it fails closed, server start now asks the lock instead of trusting a pid, and server.meta.json is only written once init has the lock, which fixes a real auto-routing break. The opt-in scope is the right call for main, and the "Not covered yet" items (the lock on by default, the CLI taking it, the fluree memory cache move) are #2132 itself. They break compatibility, so next is where they belong, and nothing is left waiting in the backlog.
Two things I'd like to see folded in before merge, both small (details inline):
- A forked child keeps the root locked after the parent closes it (
fluree-db-core/src/storage/root_lock.rs:75).flockis shared with the child through the open file description, nothing in the child closes it, and the parent's next open is then told the directory is "already open in this process". I reproduced this with a throwaway test. #2040's design said the child should close the handle it inherited. - A cancelled
SharedFluree::openmakes the next open fail (fluree-db-api/src/shared.rs:150). The registry slot goes with the cancelled future while the replay task still holds the lock, so the next opener getsStorageInUse"use that instance" with no instance to use. I reproduced this too. Running the build in a task of its own, the wayclose()already runs its shutdown, fixes it.
Two smaller ones, also inline: fluree-db-cli/src/commands/server.rs:420 lets a plain start delete the pid file and meta of a live server that doesn't lock this root (a --connection-config server, say), where the live pid used to refuse it. And docs/operations/storage.md:380 covers the loud failure (a filesystem that can't lock) but not the silent one (a lock that one kernel takes and another never sees). I confirmed that with a Docker Desktop bind mount.
Adherence to repo commitments:
- Patterns/abstractions: ✔ It extends
FlureeBuilderand reusesfs2, as the WAL owner lock already does.ServerConfig::owns_storage_root()is one policy shared by the server andstart, andStorageInUsejoins the one status/code table (423,err:system/StorageInUse). - Performance (speed first, memory second): ✔ No hot-path change. The lock is taken once per build.
Flureegains anOption<Arc>and a bool. Listings do one more filename compare per entry, butlist_prefixserves GC and sweep, not queries. Python adds oneMutex+Arcclone per API call, not per row. No performance-degradation risk. - Deployment targets: ✔ Everything is behind
native(root_lockis alsonot(wasm32)), and the wasm32/wasm-smoke jobs are green. The embedded host in solo's Lambdas uses S3 and never builds file storage. solo's standalone uses file storage, but this PR is opt-in, so nothing changes there until #2132. - Testing: ✔ The new tests are wired in and have teeth. The
root_locktests are lib tests,shared::tests/storage_lock_testsarefluree-db-apilib tests, the server tests are ingrp_httpthroughintegration.rs, and the CLI tests are incommands::server::tests. CI's python job rantest_concurrency.pyon all three OSes. When I madetry_lock_exclusivealways succeed, 2 of the 6root_locktests and 4 of the 9shared/storage_locktests went red.⚠️ No test covers the two cases above. - Conventions: ✔ Multi-line commit bodies that explain the why. The docs are updated (storage guide, configuration table, CLI server page, Rust guide, Python README), and CI's fmt and clippy are green.
Verified locally at d1df1a5f3: fluree-db-core root_lock + listing_keeps_out_the_root_lock_file (6/6 + 1), fluree-db-api shared::tests + storage_lock_tests (9/9), fluree-db-cli commands::server::tests (3/3), and fluree-db-server grp_http a_second_transaction_server_on_a_locked_root_is_refused + a_shared_storage_peer_reads_a_locked_root, all green by name. The mutation above went red and was restored. Throwaway probes (since reverted) showed that closing another fd on .fluree-lock does not drop the lock (no fcntl close-any-fd trap, since fs2 is flock), and reproduced the fork and cancelled-open cases.
Approving so you can merge when ready, but I'd love to see the two 🟠s folded in first. Both are small, and if you agree they're right, I'd rather see them land here than get lost in the backlog.
| let holder = if held_here().contains(&key) { | ||
| Some(std::process::id()) | ||
| } else { | ||
| read_holder(&mut file) |
There was a problem hiding this comment.
🟠 Should address: a child forked while a connection is open keeps the directory locked after the parent closes it, and the refusal then names the parent as "this process".
On unix, fs2 0.4.3's try_lock_exclusive is flock, which belongs to the open file description, and fork() shares that description with the child. So the lock is released only once the parent and every child forked while it was held have closed it or exited. The Python runtime refuses engine use in a forked child and leaks what the child inherited (InRuntime in runtime.rs), so nothing in the child ever closes it. Back in the parent, the key has already left HELD_HERE, so this branch reads the pid from the file. That pid is still the parent's own, so storage_in_use_message renders "already open in this process; use that instance instead" when no such instance exists.
I reproduced it here with a throwaway test. I took the lock, libc::fork()ed a child that just sleeps, and dropped the lock in the parent. Acquiring again then returned Held { holder: Some(<own pid>) }, and once the child exited it succeeded. Through the Python package, that's fluree.connect(path), then a multiprocessing pool on Linux's default fork start method doing unrelated work (the README allows that, since those children never touch Fluree), then close() and fluree.connect(path) again: DatabaseInUseError naming this process. Another process is told the parent's pid, even after the parent has exited. I didn't build the wheel to repeat it through fluree.connect, but it's the same lock.
#2040's design anticipated this ("The child should close the handle it inherited. Closing that copy doesn't release the parent's lock."). One cheap shape: keep each held lock's raw fd next to its HELD_HERE entry and give RootLock a function that closes every inherited fd. It must close, never LOCK_UN: unlocking the shared description would free the parent too. The Python package could call it from os.register_at_fork(after_in_child=...), using try_lock on the set, since another thread may have held its mutex at the fork. And when the file names this process but HELD_HERE doesn't, the message could say that a process forked from this one holds the directory. At minimum, the README's fork paragraph (fluree-db-python/README.md:454-458) should say that a forked child keeps the directory locked until it exits.
There was a problem hiding this comment.
Addressed in efd3001
The parent's drop also unlocks: the child's handler runs only once the child is scheduled, so the parent could otherwise reopen first. The child itself never unlocks.
| fn drop(&mut self) { | ||
| // Before the handle closes and frees the root, so no other lock can | ||
| // have taken it and entered it in the set by then. | ||
| if let Some(key) = self.held_here.take() { |
There was a problem hiding this comment.
👍 Taking the key out of HELD_HERE before the handle closes is exactly right. Drop::drop runs before the fields drop, so no other acquire can take the root and register it here, only to have this drop erase its entry. It's a small thing, and easy to get backwards.
| options: SharedOptions, | ||
| opened: watch::Sender<()>, | ||
| ) -> Result<Self> { | ||
| let built = build(&key, options).await; |
There was a problem hiding this comment.
🟠 Should address: after a cancelled SharedFluree::open, the next open in this process fails with "already open in this process; use that instance", and there is no instance.
d1df1a5 made the lock outlive a cancelled build (the replay task owns it until the replay ends), which is right. The registry slot, though, is still tied to the caller's future. opened lives in start()'s future, so a cancel drops it, and next_step (:123-129) clears the abandoned Opening slot. The next opener then starts a fresh build, whose RootLock::acquire meets the lock the orphaned replay still holds, giving Held { own pid } and then StorageInUse.
I ran it with the setup from a_cancelled_build_keeps_the_root_locked_until_its_replay_ends (one blocking thread held busy so the replay queues). I cancelled SharedFluree::open(dir, ..) with timeout(ZERO, ..) and opened again, and the second open returned at once with storage '…' is already open in this process; use that instance instead of opening the storage again. Any Rust caller that wraps an open in timeout or select! and retries will hit this. Python can't, since connect blocks.
The fix mirrors what close() already does: run the build in a task of its own that owns opened and settles the slot (Open, or removed), so a cancelled opener leaves the next one waiting on the slot, and it then joins or reopens. Roughly, open does tokio::spawn(Self::start(key, options, opened)) and awaits the handle (illustrative). A test next to a_cancelled_close_still_finishes_shutting_down that cancels an open and then reopens would pin it. It's small, and if you agree it's right, I'd rather see it folded in now than lost in the backlog.
| return recorded.filter(|pid| is_process_alive(*pid)).map(running); | ||
| }; | ||
| match fluree_db_core::RootLock::acquire(root) { | ||
| Ok(_probe) => None, |
There was a problem hiding this comment.
🟡 Optional: when the root is free, the recorded pid is ignored entirely, so start now deletes the pid file and server.meta.json of a live server that doesn't lock this root.
That's right for the case this is meant for, a pid reused after a crash. But the recorded server may also be alive and simply not hold this root: a --connection-config server, or a peer started from the same project. In that case already_running returns None, and the stale-file cleanup at :306-309 deletes the running server's files. Take fluree server start --connection-config s3.json, then later a plain fluree server start. The second start deletes the first's server.pid and server.meta.json. If both use the default listen address, the new child then fails to bind, and the first server is left running with nothing that server stop/status or auto-routing can find. Before this PR, the live pid refused the second start.
Maybe on Ok(_probe), read the recorded meta, and if it names a server that wouldn't hold this root (a connection config, or another storage path) and its pid is alive, keep the old "server already running" answer. It's minor, but if you agree it's right, I'd rather see it folded in now than lost in the backlog.
| Rust program takes the lock only when it asks for it (`FlureeBuilder::with_storage_lock()`, or | ||
| `SharedFluree`). | ||
|
|
||
| A filesystem that cannot lock (some network and FUSE mounts) fails to open. Set |
There was a problem hiding this comment.
🟡 Optional: this names the loud failure (a filesystem that can't lock fails to open) but not the silent one, where a lock one kernel takes is never seen by another.
flock is enforced by the kernel that took it. Over a Docker Desktop bind mount, an NFS mount with local-only locking (nolock, local_lock), or SMB on older Linux clients, both sides take "the" lock without complaint. I checked the first case. With a host process holding flock(LOCK_EX) on .fluree-lock (a second host process got EAGAIN), an alpine container with the directory bind-mounted (a fakeowner mount) took the same lock with flock -n right away.
So a fluree server on the host and a containerized process on the same directory (or the reverse) get no protection, and no error either. Maybe one sentence after this paragraph: "The lock only keeps out processes whose kernel sees it. Two machines on NFSv4 exclude each other, but a container and its host over a Docker Desktop bind mount, or clients of a mount with local-only locking, do not." It's a small addition, and I'd rather see it here than lost in the backlog.
The registry slot's sender lived in the opener's future. A cancelled open dropped it, so the next open cleared the slot as abandoned and started a build of its own, while the cancelled build's WAL replay still held the root. That build was refused with "already open in this process; use that instance", and there was no instance. The build now runs in a task of its own, as close()'s shutdown already does, so the next opener waits on the slot and then joins or reopens.
flock belongs to the open file, which a child forked without exec shares. Nothing in such a child closes it (Python's multiprocessing fork pools and os.fork leave what the child inherits alone), so the root stayed locked until the child exited. The parent's next open was refused as "already open in this process", and other processes were told a pid that might no longer exist. Dropping the lock now unlocks it before the handle closes, so the parent letting go frees the root whatever copies remain. For a parent that exits without dropping, a pthread_atfork child handler points the child's copy of each held descriptor at /dev/null as the child starts. Unlocking there would free the parent's lock too, and closing would free a number the child's `File` still owns.
…s root When the root was free, start ignored the recorded pid, which is right for a pid reused after a crash. It also deleted server.pid and server.meta.json of a live server that never locked this root, such as a connection-config server, leaving it running where stop, status and auto-routing could not find it. Before the lock, a live pid refused the start. server.meta.json now records the root a server locks. A live recorded pid is set aside only when its server locked this same root. Restart, which replays args without resolving them, records none, so it keeps the pid check.
flock is enforced by the kernel that took it. A container and its host on a Docker Desktop bind mount, or clients of an NFS mount with local-only locking, both take the lock without error and so are not refused.
Brings in main through #2137, including #2009's graph scope and explicit SHACL, the storage root lock (#2131) and reasoning limits (#2126). Ported to next's annotation links: - main's annotation lowering (annotation nodes included in their edge's subject, `GraphScope::emit` as the one `f:reifiesGraph` writer) keeps next's link fold: the slots fold into `rdf:reifies` links after the variable-graph refusal, and the fold drops the anchors - a selector-form annotation delete matches the edge through its link, scoped with main's node-level `@graph` - `@reifies` with several triples includes the extra ones in the reifier (main's `@included`) rather than as top-level siblings - triple-term objects keep their shape under main's forward/reverse edge classification, and `rdf:reifies` stays refused as a key - main's parser tests that read `f:reifies*` slots and anchors read the link and the annotation's graph instead Also: - JSON-LD expansion keeps next's triple-term `@id` and value-object `@annotation` under main's `Path`; CONSTRUCT templates keep `TripleTermValue` - the JSON-LD adapter keeps next's quads, `@reverse` and `@included`, and refuses `@graph` for a sink without named graphs with main's error - file builds migrate the nameservice after main's WAL replay, with the root lock held - the cross-ledger shape cache key keeps `model_instance` - the error table counts both sides' variants; consensus and the server map Fenced, LifecycleConflict and ConfigUnavailable - main's new tests await next's async `genesis_ledger`; a next SHACL test enables SHACL, as #2009 requires; the reasoning-limit tests suffix the ledger name, not the branch
next now carries #2131 through main, so its commits drop out of this branch's diff. Resolved: - error.rs: next's count of 50 covers StorageInUse and next's own ConfigUnavailable. - lib.rs: build_async keeps holding_root, so the nameservice migration runs under the lock as well as WAL replay. - server.rs: ServerMeta lives in local_server; it gains #2131's locked_root there, and recorded_server reads it through read_meta.
Several engines on one file storage directory aren't coordinated, and nothing stopped anyone from opening a second one. This PR makes a process share one engine per directory and locks the directory against other processes.
The problem
Python users hit this from threads, not just from separate processes.
fluree.connect(path)built a new engine on every call, so the sqlite3 habit of one connection per thread put several engines on one directory. Each engine keeps its own cache and its own per-ledger write lock, so those threads' commits raced each other's compare-and-swap. With 16 threads each writing 25 inserts through its own connection, 138 of the 400 failed withConflictError: Commit contention: 16 commit attempts lost to concurrent writers. Reads were also stale across connections.Two processes were worse, because nothing coordinates them. Each serves its own cached state, and both index and sweep the same files. Two
fluree server runon one project both started as transactors.server start's PID check missed a foreground server, and it refused to start after a crash if the old pid had been reused.What changes
Engine (
fluree-db-core,fluree-db-api)FlureeBuilder::with_storage_lock()takes an exclusive OS lock on<root>/.fluree-lockbefore the root is swept or its WAL is replayed.ApiError::StorageInUse(423,err:system/StorageInUse). The error names the holder's pid when the lock file can be read, which is not possible on Windows.disconnect()does not release it.FLUREE_STORAGE_ALLOW_UNLOCKED=true. Any other error, such as an unwritable lock file, fails the build.SharedFluree::open(path, SharedOptions)returns the one instance this process keeps for a directory. The path is canonicalized, so any spelling of it finds the same instance.close()can't cut the shutdown short.disconnect()on a shared instance does nothing. AFlureecloned from a handle keeps the root locked until that clone is dropped.Python (
fluree-db-python)connect(path)goes throughSharedFluree, so every connection in the process to a directory shares one engine.close()returns the connection's reference at once, so a closed connection releases the directory even while ledgers or snapshots opened through it are still alive.fluree.DatabaseInUseError, which has apidattribute.connect(config=...)to file storage takes the lock too, but its engine isn't shared.connect/closedocstrings are updated. The fork paragraph says a forked child does not keep the directory locked.test_forkhad a spawned worker open the directory its parent was holding. The test now asserts that this is refused, and has the worker open a directory of its own.Server and CLI (
fluree-db-server,fluree-db-cli)ServerConfig::owns_storage_root()is the single policy for who takes the lock: a transaction server takes it; a shared-storage peer and a Raft node don't.storage_lockis set. That field isn't a command-line flag;server runand theserver startchild process set it.server start's preflight uses the same policy.startchecks the lock instead of trusting a live pid. A peer, a Raft node or a connection-config server keeps the pid check.server.meta.jsononly after its init has taken the lock. Before this, a refused secondserver runoverwrote the running server's metadata and then deleted it, which broke CLI auto-routing.server.meta.jsonrecords the root a server locks. When the root is free,startsets a live recorded pid aside only if that server locked this same root. A live server that doesn't lock it, such as a connection-config server, still refuses the start, and its pid file and metadata are kept.docs/operations/storage.md, including a lock that another kernel doesn't see (a Docker Desktop bind mount, NFS with local-only locking);docs/operations/configuration.md;docs/cli/server.md;Not covered yet
The lock is opt-in for Rust embedders. One-shot CLI commands don't take it: they route to a running server, but with
--direct, or with no server running, they open the directory unlocked beside a Python process. The storage guide says so. Turning the lock on by default, and having the CLI take it, are breaking changes, so they are planned fornext. That work also needsfluree memory's cache moved out of the shared storage first, or concurrentfluree memory addruns would refuse each other.Partially addresses #2040: the opt-in lock, Python and the standalone server are done here. Still open: the lock on by default, one-shot CLI commands taking it, and the
fluree memorycache move.Follow-up: #2141, a harness that cancels each public async call at every await point, for the class of bug that the cancelled build, close and open cases here belong to.
Tests
Each new regression test fails with its fix reverted.
fluree-db-coreroot_lock:fluree-db-apishared::tests:disconnect()through a handle leaves the instance alone;fluree-db-servergrp_http: a second transaction server on a locked root is refused; a shared-storage peer opens it.fluree-db-clicommands::server::tests:startrefuses a held root and names its server;fluree-db-python/tests/test_concurrency.py:indexing;fluree-db-python/tests/test_fork.py: a forked child does not keep the directory locked, whether its parent exits holding it or closes it.