Skip to content

Share one engine per storage directory in a process; lock it against other processes - #2131

Merged
bplatz merged 10 commits into
mainfrom
fix/shared-engine-root-lock
Oct 20, 2026
Merged

bplatz merged 10 commits into
mainfrom
fix/shared-engine-root-lock

Conversation

@bplatz

@bplatz bplatz commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

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 with ConflictError: 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 run on 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-lock before the root is swept or its WAL is replayed.
    • A second locked instance on the root, in any process, fails with a new 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.
    • The lock lives as long as the instance: every clone shares it. It is released when the last clone is dropped or the process exits, however it exits. disconnect() does not release it.
    • A child forked without exec shares the lock's open file. Dropping the lock unlocks it rather than waiting for every copy to close, and the child gives up its copy as it starts, so the root is free once the parent drops the lock or exits.
    • Taking the lock fails closed. A filesystem that cannot lock is refused unless FLUREE_STORAGE_ALLOW_UNLOCKED=true. Any other error, such as an unwritable lock file, fails the build.
    • The option is opt-in, and it is refused alongside a shared WAL owner, because a Raft cluster shares its payload root on purpose. Storage listings skip the lock file.
  • 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.
    • A join that asks for different settings (indexing on or off) is refused.
    • The handles own the lifecycle. The instance shuts down when the last handle is closed or dropped, in a task of its own, so a cancelled close() can't cut the shutdown short.
    • disconnect() on a shared instance does nothing. A Fluree cloned from a handle keeps the root locked until that clone is dropped.
    • An open that finds the root still shutting down waits for the shutdown to finish.
    • The build runs in a task of its own, so a cancelled open leaves the next one to wait for it instead of being refused.

Python (fluree-db-python)

  • connect(path) goes through SharedFluree, so every connection in the process to a directory shares one engine.
    • Each call holds its own reference to the 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.
  • Another process opening the directory raises the new fluree.DatabaseInUseError, which has a pid attribute.
  • connect(config=...) to file storage takes the lock too, but its engine isn't shared.
  • The README's concurrency section and the connect/close docstrings are updated. The fork paragraph says a forked child does not keep the directory locked.
  • test_fork had 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.
    • Server init locks the root when storage_lock is set. That field isn't a command-line flag; server run and the server start child process set it.
    • server start's preflight uses the same policy.
  • For a server that will lock its storage, start checks the lock instead of trusting a live pid. A peer, a Raft node or a connection-config server keeps the pid check.
  • A foreground server writes server.meta.json only after its init has taken the lock. Before this, a refused second server run overwrote the running server's metadata and then deleted it, which broke CLI auto-routing.
  • server.meta.json records the root a server locks. When the root is free, start sets 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:
    • "One process per directory" in docs/operations/storage.md, including a lock that another kernel doesn't see (a Docker Desktop bind mount, NFS with local-only locking);
    • the new environment variable in docs/operations/configuration.md;
    • docs/cli/server.md;
    • the Rust library guide.

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 for next. That work also needs fluree memory's cache moved out of the shared storage first, or concurrent fluree memory add runs 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 memory cache 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-core root_lock:
    • a held root refuses a second lock and names the holder;
    • an unwritable lock file fails closed;
    • only a filesystem without locks counts as unsupported;
    • storage listings skip the lock file;
    • a copy of the lock's handle does not keep a dropped lock;
    • a forked child does not keep the root locked after its parent exits.
  • fluree-db-api shared::tests:
    • two opens share commits;
    • a join with other settings is refused;
    • the root stays held until the last close;
    • a reopen waits for a shutdown that is still running;
    • a reopen after a cancelled open waits for its build;
    • a cancelled close still finishes shutting down;
    • disconnect() through a handle leaves the instance alone;
    • a clone keeps the root locked;
    • concurrent open, write and close loses nothing.
  • fluree-db-server grp_http: a second transaction server on a locked root is refused; a shared-storage peer opens it.
  • fluree-db-cli commands::server::tests:
    • start refuses a held root and names its server;
    • it lets a peer share the root;
    • it ignores a live pid recorded for the free root;
    • it refuses while a recorded server that doesn't lock the root runs;
    • the recorded root comes from that server's metadata.
  • fluree-db-python/tests/test_concurrency.py:
    • 16 threads, each with its own connection, all commit;
    • open/close churn across threads;
    • connections share commits;
    • closing releases the directory while objects opened through it are still alive;
    • closing one connection leaves the others open;
    • connections must agree on indexing;
    • another process is refused, the refusal names the holder, and a killed holder frees the directory;
    • a config connection holds the directory.
  • 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.

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.
@bplatz bplatz added the bug Something isn't working as expected label Oct 17, 2026
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.
bplatz added a commit that referenced this pull request Oct 17, 2026
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 aaj3f left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@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). flock is 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::open makes 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 gets StorageInUse "use that instance" with no instance to use. I reproduced this too. Running the build in a task of its own, the way close() 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 FlureeBuilder and reuses fs2, as the WAL owner lock already does. ServerConfig::owns_storage_root() is one policy shared by the server and start, and StorageInUse joins 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. Fluree gains an Option<Arc> and a bool. Listings do one more filename compare per entry, but list_prefix serves GC and sweep, not queries. Python adds one Mutex + Arc clone per API call, not per row. No performance-degradation risk.
  • Deployment targets: ✔ Everything is behind native (root_lock is also not(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_lock tests are lib tests, shared::tests/storage_lock_tests are fluree-db-api lib tests, the server tests are in grp_http through integration.rs, and the CLI tests are in commands::server::tests. CI's python job ran test_concurrency.py on all three OSes. When I made try_lock_exclusive always succeed, 2 of the 6 root_lock tests and 4 of the 9 shared/storage_lock tests 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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in ccc02dc

Comment thread fluree-db-cli/src/commands/server.rs Outdated
return recorded.filter(|pid| is_process_alive(*pid)).map(running);
};
match fluree_db_core::RootLock::acquire(root) {
Ok(_probe) => None,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 621de36

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 3b50f8e

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.
@bplatz
bplatz merged commit 5be0772 into main Oct 20, 2026
18 of 19 checks passed
@bplatz
bplatz deleted the fix/shared-engine-root-lock branch October 20, 2026 03:15
bplatz added a commit that referenced this pull request Oct 20, 2026
#2009 added ApiError::ConfigUnavailable and #2131 added StorageInUse, and
each moved every_variant's count from 47 to 48. Merged, the identical edit
landed once: 49 variants counted as 48, so
every_variant_answers_the_same_typed_or_flattened failed on main.
bplatz added a commit that referenced this pull request Oct 20, 2026
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
bplatz added a commit that referenced this pull request Oct 20, 2026
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.
aaj3f added a commit that referenced this pull request Oct 20, 2026
…ferences

Brings in #2122, #2126, #2127, #2131 and #2133. The one conflict is in
fluree-db-api's re-exports, where #2131's `SharedFluree` / `SharedOptions`
and this branch's `target_dataset` items both land.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working as expected

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants