Skip to content

[kyo-system] make a write survive a crash - #1868

Open
DamianReeves wants to merge 7 commits into
mainfrom
path-durability
Open

DamianReeves wants to merge 7 commits into
mainfrom
path-durability

Conversation

@DamianReeves

@DamianReeves DamianReeves commented Aug 8, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

Writing a file does not by itself guarantee that its contents and directory entry survive a crash. Atomic replacement must also preserve an existing file's access permissions.

Solution

syncDirectory persists directory entries. durableReplace writes a create-new sibling temporary, syncs its content and metadata, closes it, atomically replaces the target, then syncs the parent directory. When it creates missing parent directories, it also syncs their entries through the first existing ancestor. A directory-sync failure is reported even if replacement has already happened.

Temporary names use a random identifier per execution, have bounded length, and skip the target itself. Exclusive creation handles name collisions. Invalid parent paths fail without collision retries. Cleanup ownership transfers synchronously with acquisition, before an effect continuation can be interrupted. Cleanup failures are logged and attached to the primary exception, and failures in the logger cannot replace that exception. Scoped sibling temporaries also clean up if acquisition finishes after their scope closes. Directory sync preserves precise missing-path and non-directory errors, including Windows Node errors for paths below regular files. Unsupported host platforms return a typed failure.

Host replacement preserves the existing regular file's owner, group, permission mode, and access ACLs. A native helper acquires the replacement with restrictive access, restores and verifies the captured controls before file synchronization, and fails before replacement when the controls cannot be preserved. The helper is shared by JVM, Node.js, Scala Native, and Wasm through kyo-ffi. Node.js and Wasm require koffi and the native library for the host platform. On Windows, restoration preserves legacy and automatically inherited security descriptors, including mandatory integrity labels, without adding inherited ACEs. Delete authorization is checked without backup privileges before temporary creation. Metadata changes by another process are not serialized.

Rebased onto origin/main (432aac1f6). Main had changed kyo-system substantially, so the branch now carries five follow-up commits on top of the original patch:

  • New kernel. Two tests reached kernel internals that [kernel] New kernel: an explicit region stack, fused arrows, structural resource release #1988 removed, and a panic now also carries the kernel's EffectTrace. The tests are adapted.
  • Late acquisition. A backend whose file creation is asynchronous must hand ownership over uninterruptibly, so the temporary can arrive after an interrupt has already run the operation's cleanup. Before this change it then had no owner. An ownership slot now cleans a late temporary on arrival. The fix comes with a reproducing test.
  • Dolt backend. DoltFileSystem from [kyo-sql] add the Dolt and DoltLite backends, and a filesystem over them #1956 implements the new members. durableReplace is one transaction, with no temporary entry, and its checks fail as values. A non-SQL failure inside a kyo-sql transaction discards the session, and over an in-memory DoltLite database that discards the database. syncDirectory confirms the path is a directory.
  • Conformance. The durability suite moved into kyo-system-conformance ([kyo-test, kyo-data, kyo-flow, kyo-system, kyo-sql] Conformance suites published as -conformance artifacts #2015) and is mixed into FileSystemWriteConformanceTest, so host and Dolt both run it. New laws cover precise syncDirectory failures, a replacement beneath a regular file or over a directory, and leftover temporaries. The module's Node, Wasm, and JVM tests now load the native helper.
  • Precise failures. A directory target fails with FileIsADirectoryException(target) on every backend. A link target fails before anything changes, on the host and on Dolt. A write that makes no progress reports FileWriteStalledException ([kyo-system] fail a write that reports no progress instead of retrying #1966). Sync failures are labelled Sync.
  • macOS flush. File sync and the Native directory sync use F_FULLFSYNC, because fsync there leaves data in the drive cache. The JDK and libuv already do this for the JVM and Node paths.

Notes

Stack

The lower PRs through #1867 have merged into main. This PR is the next layer, followed by #1869, #1870, #1871, and #1799. Merge bottom up.

The earlier stack history remains available in the original PR timeline.

Validation

After rebasing onto 432aac1f6:

Suite JVM JS Native Wasm
kyo-system 606 596 572 574
kyo-system-conformance 179 179 179 148
kyo-system-doltfs 57 57 57 57

Other checks:

  • kyo-ffi-itJVM/test passed 178 tests.
  • The kyo-system and kyo-system-doltfs README doctests passed.
  • scalafmtCheckAll passed.
  • The C helpers compile without warnings for Windows x64 and ARM64 and for Linux x64 and ARM64 (checked with zig cc).
  • Windows was not run locally.

Earlier validation:

After extracting the unrelated fixes, this PR passed its isolated JVM (671 tests) and Native (637 tests) suites directly on main. The FFI JVM suite passed 345 tests, and the relocated loader integration tests passed all nine cases. The rebuilt filesystem stack also passed all four platform suites and compiled all 41 README examples.

  • kyo-systemJVM/test
  • kyo-systemJS/test
  • kyo-systemNative/test
  • kyo-systemWasm/test
  • kyo-systemJVM/doctest

Shared regression coverage includes exact mode and ACL preservation, inherited ACL protection, denied metadata/deletion access, native path validation, protocol ordering, new parent entries, concurrent replacement, forced filename collisions, invalid-parent retry behavior, cleanup and logger failures, acquisition panics, long and reserved filenames, interruption at acquisition and ownership transfer, and acquisition after scope closure. Host durability tests explicitly cover Windows' unsupported-directory-sync result. Local four-platform checks ran on macOS; a targeted Windows permission matrix passed all 26 checks, and the helper compiled and linked for Windows x64 and ARM64 at both ends of the stack.

Separate fixes

Merged into the current base: #1946, #1947, #1948, #1949, #1952, and #1953. The remaining unrelated fixes continue in their own PRs:

@DamianReeves

Copy link
Copy Markdown
Collaborator Author

Heads-up: #1864 and #1865 are rebased onto main

#1864 and #1865 now sit directly on main rather than on the old stack base, and #1864 picked up a change to the temp surface. This branch has not moved yet, so its diff on GitHub currently re-includes everything below it. That clears once it is rebased onto its new parent. Rebase bottom up.

Two groups of work are waiting when it does.

1. Renames that landed on main during review of the lower branches

The squash merges of #1862 and #1863 carried review renames that this branch predates. Each one will surface during the rebase:

On this branch On main
Path.follow, the private polling loop Path.watch
private enum Poll private enum Observed
PathDirectories.temp, the unscoped primitive tempUnscoped
PathDirectories.tempScoped temp
StreamFileExtensions StreamSystemExtensions
readStream(charset, bufferSize: Int) readStream(charset, bufferSize: ByteSize)
readBytesStream(bufferSize: Int) readBytesStream(bufferSize: ByteSize)
ReadHandle.size(): Result[_, ByteSize] Result[_, Long]
Jsonl.follow, Jsonl.followResults Jsonl.watch, Jsonl.watchResults

StreamSystemExtensions also gained a writeWith helper, append and options overloads, and append-preserving failure semantics. Its tests moved out of PathTest into StreamSystemExtensionsTest, which does not exist on this branch yet. readBufferCapacity now clamps rather than throwing, so a zero or oversized buffer is no longer an argument-validation failure.

The two temp renames are a swap, and that makes them the dangerous ones. temp and tempScoped did not move in the same direction: the unscoped primitive took the tempUnscoped name, and tempScoped took the now-vacant temp. So an existing Path.temp(...) callsite on this branch keeps compiling after the rebase while silently changing meaning, from "unscoped, caller removes it" to "scoped, removed at Scope exit through the service". Every Path.temp(...) callsite has to be read and classified rather than left alone. The ones that call remove themselves afterwards are the unscoped kind and want tempUnscoped. This bit the #1864 rebase in CommandTest.

2. Path.temp now goes through the service

#1864 closed a gap where Path.temp created and removed its file on the host regardless of the installed backend, while Path.tempDir correctly routed through the service. The temp file surface now mirrors tempDir:

  • case Temp(prefix: String, suffix: String) extends Op[Path.TempFileHandle], dispatched to service.temp(prefix, suffix)
  • def temp(prefix: String, suffix: String)(using Frame): Path.TempFileHandle < (S & Abort[FileStructureException]) is a new abstract member on FileSystem.Write
  • Path.temp is now Path < (PathWrite & Sync & Scope), and its Scope finalizer removes through the service that vended the handle
  • Path.tempUnscoped and Path.tempDirUnscoped stay host primitives deliberately, since an entry whose lifetime the caller owns has no scope for a service-vended handle to hang from

So for every branch above: Path.temp callsites need a runner, and every FileSystem.Write implementation needs a temp member.

One further note, because it caused two real test failures during the #1864 rebase. A backend failure is raised by the runner, not by the frame that suspended the op, so an Abort.run nested inside a Path.run cannot observe it. Code that needs to inspect a filesystem failure has to run its own runner at the point it catches:

result <- Abort.run[FileSystemException] {
    Path.run(Scope.run(stream.writeTo(file, options = Path.WriteOptions(createFolders = false))))
}

What this branch needs

Beyond the rename set, one direct collision.

This branch declares Path.TempFileHandle for siblingTemporary:

/** Service-owned sibling temporary cleanup handle. Internal. */
abstract private[kyo] class TempFileHandle:
    def path: Path
    def remove()(using AllowUnsafe): Unit
end TempFileHandle

#1864 now declares TempFileHandle with the same two members, for the scoped Path.temp. The rebase will conflict on the declaration. Resolution is to drop this branch's copy and keep #1864's, then siblingTemporary and tempFileHandle compile against it unchanged. Worth widening the scaladoc at that point so it covers both uses rather than only the sibling one.

siblingTemporary itself is unaffected. It stays a distinct operation from temp: a create-new file next to a specific target for the durable-replace path, not a general temp factory.

Base automatically changed from path-watch to main September 10, 2026 13:43
DamianReeves added a commit that referenced this pull request Sep 15, 2026
Persist file contents and directory entries through a sibling temporary
and required atomic replacement. Transfer cleanup ownership before
interruptible continuations, including scoped temporary acquisition.

Preserve precise filesystem failures and the merged capability, channel,
lock, and watcher contracts. Cover durability and cleanup on all four
platforms.

Refs #1868
@DamianReeves
DamianReeves force-pushed the path-durability branch 2 times, most recently from 256b3f9 to 8b1400f Compare September 15, 2026 21:31
var moved = false
def open(attempt: Int): (Path, Path.WriteChannel[S & Sync], () => Unit < (S & Sync)) <
(S & Sync & Abort[FileWriteException | FileStructureException]) =
val temporary = parent / s".kyo-durable-$attempt"

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

if parent isn't a valid path, it seems this code can keep retrying up to the attempt limit

@DamianReeves DamianReeves Sep 16, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in the bundled update (c873f0260, acquisition changes in 8fdda0d52). Parent creation runs before exclusive candidate acquisition. A regular-file parent or ancestor fails immediately; only a genuine temporary-name collision triggers a retry. Shared regressions cover both invalid-parent cases and forced candidate collisions.

if !completed then
acquired.foreach { (close, handle) =>
try close.close()
catch case _: Throwable => ()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

can you avoid swallowing exceptions?

@DamianReeves DamianReeves Sep 16, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in c873f0260. Cleanup errors are logged and attached to the original failure, while both close and removal are attempted. A throwing logger cannot replace that failure. The host removal handle also propagates a failed Result instead of discarding it. Regressions cover deletion failure, both cleanup actions failing, a failing logger, and preservation of the original panic.

var acquired: Maybe[(Path.ChannelCloseHandle, Path.TempFileHandle)] = Absent
var completed = false
def loop(attempt: Int): Path.TempFileHandle < (S & Sync & Abort[FileWriteException | FileStructureException]) =
val temporary = parent / s".kyo-temporary-$attempt"

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

can't we have conflicts with different executions using the same file name?

@DamianReeves DamianReeves Sep 16, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in c873f0260. Each execution gets a random UUID, while retaining exclusive creation, collision retries, and the check against the target itself. The regression reproduces one execution targeting .kyo-durable-0 while another uses that name as its temporary; the corrected implementation installs the requested bytes. A separate test forces a genuine candidate collision.

}
end siblingTemporary

private[kyo] def durableReplace[S](fileSystem: FileSystem.Write[S & Sync], target: Path, bytes: Span[Byte])(using

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

can you check if this method keeps the same permissions as the original?

@DamianReeves DamianReeves Sep 16, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Implemented in 8fdda0d52, with the Windows restoration follow-up in 480c5f7e3. Existing regular files retain their owner, group, permission bits, and access ACLs. The native helper creates a restrictive temporary, restores and verifies the captured controls before synchronization and atomic replacement, and fails before replacing the target if preservation is unsupported. New files use their destination parent's normal creation permissions.

Windows now preserves both legacy and automatically inherited descriptors, including mandatory integrity labels, and checks ordinary delete authorization before creating the temporary. The Windows matrix passed all 26 checks. The Windows ARM64 Scala run passed all durability and permission tests on JVM and Node.

Shared regressions cover private modes, full ACLs, inherited ACLs, and denied metadata/deletion access. PR #1799 carries the same requirements through nested overlays and recovery, protects recovery logs with private directories, and retains destination-parent defaults for new files.

DamianReeves added a commit that referenced this pull request Sep 17, 2026
### Problem

Leak checks compared a trace token against a second worker snapshot
after the fiber could yield, causing a false failure on Linux ARM64. A
matching worker could also hide another busy worker that was not
allowlisted.

### Solution

Retain the workers captured with each trace observation. Require every
busy worker to match the allowlist. Regressions force the snapshot gap
and cover mixed allowlisted and unaccounted workers.

### Notes

`kyo-test-runnerJVM/test` passed on this standalone branch: 251 passed,
2 cancelled, 1 pending. The deterministic snapshot-gap and mixed-worker
regressions were reproduced before the fix.

Extracted from #1868 so the filesystem stack can be reviewed
independently.
DamianReeves added a commit that referenced this pull request Sep 17, 2026
### Problem

Scala 3.9 can emit JVM signatures referring to inaccessible macro helper
modules, which makes reflective class loading fail.

### Solution

Mark the affected helpers public in the generated binary while retaining
their Scala access restrictions. Add regressions that resolve the
generated method signatures in data, prelude, HTTP, SQL, and TASTy.

### Notes

All nine JVM signature regressions passed on this standalone branch,
covering data, prelude, HTTP, SQL, and TASTy.

Extracted from #1868 so the filesystem stack can be reviewed
independently.
DamianReeves added a commit that referenced this pull request Sep 17, 2026
### Problem

The setup action failed when a pinned Coursier download or its setup
command encountered a transient failure.

### Solution

Run download and setup through bounded retries, preserve action outputs
and the Windows ARM64 JDK path, and use Node 24.

### Notes

`bash scripts/setup-coursier-test.sh`: all six cases passed on the
standalone branch.

Extracted from #1868 so the filesystem stack can be reviewed
independently.
@fwbrasil

Copy link
Copy Markdown
Collaborator

@DamianReeves the recent leak check improvements uncovered a new leak that I fixed directly in main: d0518a7

There's only an option to rebase the PR so I'll let you handle it to avoid issues

fwbrasil pushed a commit that referenced this pull request Sep 18, 2026
### Problem

The JavaScript WeakReference shim was also compiled for Scala Native,
shadowing its runtime implementation. That broke reference casts and
inherited thread-local copying, including the runtime stack-unwinding
buffers.

### Solution

Restrict the shim to JS and Wasm. Add regressions for clearing
references, replacing cleared registry entries, and child-local
inheritance. Enable Native machine-metric readback tests and remove the
scheduler tests' exception suppression.

### Notes

Validated on this standalone branch: 282 registry tests across JVM,
Native, JS, and Wasm; three machine-metric tests each on JVM and Native;
both README doctests; and serial `scalafmtCheckAll`. The three Native
weak-reference regressions reproduced the original defects before the
fix.

Extracted from #1868 so the filesystem stack can be reviewed
independently.

Rebased onto `6d50eecae` on September 17. Revalidated all 282 registry
tests across JVM, Native, JS, and Wasm, plus six machine-metric tests
across JVM and Native. The previous Linux JVM CI failures are addressed
separately in #1953 and #1954.
fwbrasil pushed a commit that referenced this pull request Sep 18, 2026
### Problem

Scala Native 0.5.12 can produce Linux binaries with executable stacks
because its safepoint assembly lacks GNU-stack notes. Some checks also
pass JVM options to other runtimes or refer to unavailable plugin
documentation symbols.

### Solution

Add a Linux-only noexecstack linker option and verify stack permissions
after initial and incremental links. Clear JVM-only test options on
Native, JS, and Wasm, repair unresolved plugin Scaladoc references, and
make the Native worker-count warning describe what it measures.

### Notes

Validated on this standalone branch:

- `scalafmtSbtCheck` and documentation builds for kyo-ffi-plugin,
kyo-test-sbt, and kyo-test-sbt-publish passed.
- `scripts/ci-test.sh --self-test`: 55 passed.
- `scripts/native-relink-selftest.sh --self-test`: 12 passed, including
Linux executable-stack rejection after initial and incremental links.
- Confirmed Native, JS, and Wasm test JVM options are empty.

Extracted from #1868 so the filesystem stack can be reviewed
independently.
Preserve existing access permissions through atomic replacement.
Synchronize file metadata and parent entries, and retain temporary-file
ownership through interruption and cleanup failures.
The kernel rewrite removed Safepoint.get's interceptor, so the tests that
interrupt the running fiber at an ownership hand-off now reach it
through IOTask.currentTask.

A panic now also carries the kernel's EffectTrace as a suppressed
diagnostic. The cleanup-report test compared the whole suppressed list,
so it filters that trace out before checking for the two cleanup
failures, as the kernel's own tests do.

Also applies main's formatter to the rebased sources.
The replacement protocols recorded an acquired temporary in a plain
variable that their finalizer read once. A backend whose acquisition is
asynchronous must transfer ownership uninterruptibly, so an interrupt
can run the finalizer before the temporary arrives. The temporary then
had no owner and stayed on disk.

A small ownership slot now decides who cleans up. While the operation
runs, its finalizer does. A temporary that arrives after the operation
ended is closed and removed on arrival, and its cleanup failures are
logged rather than thrown, since nothing waits on them.

The new tests hold an acquisition until the operation's finalizers have
run, then check that the late temporary is removed exactly once, for
both durable replacement and sibling temporaries.
FileSystem.Write now declares directory synchronization, sibling
temporaries, and durable replacement, so the Dolt backend implements
them.

- durableReplace writes the entry and its missing parents in one
  transaction. The transaction gives what the host's synchronized
  temporary and atomic rename give, so no temporary entry exists.
  Checks run before the first write and report failure as a value: the
  pool discards a session that a non-engine failure crossed, and over an
  in-memory database that discards the database.
- syncDirectory confirms the path is a directory, with the host's
  precise failures. An entry change is already a committed statement.
- Sibling temporaries use the shared protocol. Creating an entry is a
  statement, so creation and the ownership hand-off run
  uninterruptibly, and never land beneath a regular file.

The durability suite gains laws for the precise syncDirectory failures,
a replacement beneath a regular file, and leftover temporaries. The host
and Dolt write tiers both run them.
… runs

The write tier now carries the durability suite, and the host's
durable replacement always loads kyo-system's native helper. The
conformance module's Node and Wasm tests had no path to that library
and no koffi, so the host's replacement laws failed there. They now
read the library from kyo-system's target and install koffi in their
own, and the JVM tests enable native access as kyo-system's do.
…n macOS

- A directory at the target now fails with FileIsADirectoryException
  naming the target. POSIX reported a generic I/O failure, and Windows
  reported the parent as not being a directory.
- A link or other non-regular target fails with an I/O failure that
  says the replacement needs an absent target or a regular file. The
  Dolt backend refuses a link the same way.
- A native write that makes no progress reports
  FileWriteStalledException with the unwritten count, as main's write
  loops do, rather than a generic I/O failure.
- Native sync failures are labelled Sync, not Write.
- On macOS, file and Native directory synchronization use F_FULLFSYNC,
  since fsync there leaves data in the drive cache. A volume that cannot
  honor it falls back to fsync, as libuv does. The JDK and libuv already
  do this for the JVM and Node paths.

The durability suite gains a law for a directory target. The host
tests now check the precise directory failure and the link refusal.
Three tests read the result of an interrupted fiber with `poll` as soon as a
latch reported that cleanup ran. The latch is released while the fiber unwinds,
before the fiber publishes its result, so `poll` could answer Absent.

"a close panic still removes the durable temporary and preserves the
interruption panic" failed this way on linux-arm64 with
`NoSuchElementException: Maybe.get`. The two interruption tests beside it
compared the same early `poll` and could fail on the same window.

Each test now awaits the result with `getResult`.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants