Repository navigation
[kyo-system] read and write a file at an offset - #1865
Merged
Merged
Conversation
DamianReeves
force-pushed
the
path-channels
branch
from
August 25, 2026 14:05
326e8f1 to
74f21ac
Compare
DamianReeves
force-pushed
the
path-channels
branch
from
August 25, 2026 14:45
74f21ac to
b987dc8
Compare
This was referenced Aug 25, 2026
DamianReeves
force-pushed
the
path-channels
branch
from
August 27, 2026 16:34
b987dc8 to
553b50f
Compare
DamianReeves
force-pushed
the
path-channels
branch
from
August 27, 2026 18:04
553b50f to
e631292
Compare
ReadChannel, WriteChannel and ReadWriteChannel expose positioned access to an open file, so a caller can read a header, seek, and write in place without loading the whole file. Channels are Scope-managed, and FileSystem.WriteOpen selects whether opening creates, truncates, or requires an existing file.
DamianReeves
force-pushed
the
path-channels
branch
from
August 31, 2026 20:37
e631292 to
7cc3fe6
Compare
fwbrasil
pushed a commit
that referenced
this pull request
Sep 3, 2026
### What this adds
Advisory file locks. `Path.Lock` is scope-managed: acquiring registers
the release with the enclosing `Scope` before anything is claimed, so an
interrupt landing between the claim and the finalizer cannot strand the
lock. `LockMode` selects shared or exclusive compatibility, and
`LockWait` selects whether a contended attempt fails immediately, waits,
or waits until a deadline.
```scala
import kyo.*
val guarded = Scope.run {
Path.runReadOnly {
Path("state.bin").lock(Path.LockMode.Exclusive, Path.LockWait.Immediate).map(_.check)
}
}
```
`tryLock` answers `Absent` for a conflicting holder and never waits for
one. It still carries `Async`, for a different reason: a backend that
merges same-process claims onto one platform lock has a span in which a
compatible claim is being taken but is not yet shareable, and answering
during that span would report a conflict that does not exist. Waiting it
out is bounded and needs no holder to release anything.
There is no public manual release. A lock goes when its `Scope` closes,
and `check` reports `FileLockOwnershipLostException` for the backends
that can lose a claim underneath the handle.
### What changed
**`Path`** gains `LockMode`, `LockWait`, the public `Lock` trait, and
the `lock` and `tryLock` extension methods. The private surface a
platform implements is `RawLock` plus `LockAttempt`, which separates
"no" from "not yet": only the unsettled answer is worth retrying on its
own, since a real conflict clears when the holder releases and that is
the waiting caller's concern.
**`FileSystem.Read`** gains `tryLock` and `lock`, so a read-only backend
still vends locks. `FileSystem.awaitLock` holds the waiting policy in
one place and paces its retries with `Async.sleep` rather than
`Clock.sleep`, since the latter hands back the timer fiber instead of
suspending on it and would turn the retry into a busy spin against the
holder it is waiting on.
**`FileSystemException`** gains the `FileLockException` marker and the
`FileLockUnavailableException`, `FileLockTimeoutException` and
`FileLockOwnershipLostException` leaves. `FileSystemOperation` gains
`Lock`, so an acquisition failure names what it was doing instead of
borrowing `Read`.
**JVM and Native** back a lock with `FileChannel.tryLock` behind a
process-wide `NioPathLockRegistry`. POSIX advisory locks do not exclude
the owning process from reacquiring its own lock, so same-process
exclusion is enforced explicitly rather than assumed from the platform
call. The registry key is the resolved real path, so two names for one
file through a symbolic link share one entry instead of opening two
channels the JVM then refuses as overlapping.
**JS and Wasm** implement an `O_EXCL` lockfile protocol. A claim records
host, pid and a random token, and an owner whose process is provably
gone is reclaimed rather than left blocking the path for good.
**Tests.** `FileSystemLockTest` joins the read, write and channel suites
as the fourth cross-backend contract, so every backend added later
inherits the same laws. `HostPathLockTest` covers the interrupt window
from both ends: an interrupt delivered from inside the claim node with
the OS lock already held, and repeated interrupts landing before the
claim is made. The repeated-interrupt stress case is currently marked
ignored: it reliably exposes #1928, a core defect where an interrupted
fiber can lose its `Scope.ensure` finalizers under load, which no
backend-side code can compensate for. The claim path additionally
records the holder through a tombstone, so a claim that completes after
the finalizer has already drained releases the lock in place instead of
stranding it.
### Stack
Part of the path-capability stack: process fixes, filesystem vocabulary,
abstraction, capability flip, channels, locks, watch, durability,
confinement, in-memory, zip, then overlay (#1799). Merge bottom up;
GitHub retargets the stack above each merge.
The lower branches (#1856, #1857, #1852, #1854, #1888, #1861, #1862,
#1863, #1864, #1865) have landed, so this branch is now a single commit
rebased onto `main`. The original incremental development history
remains visible in #1799's earlier timeline and in the backup refs
recorded in the working notes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What this adds
Positioned file access.
Path.ReadChannel[S],Path.WriteChannel[S]andPath.ReadWriteChannel[S]expose reads and writes at absolute offsets over an open file, so a caller can read a header, skip past it, and overwrite a record in place without loading the file into memory or rewriting it.Every operation names its own offset and no call moves an implicit cursor, so two callers holding the same channel cannot disturb each other's position.
readAttolerates a short read at end of file and returns fewer bytes than requested rather than failing.writeAtzero-fills a gap past the current end, so a sparse write is an ordinary write.What the new callsites look like
A channel is acquired from a backend rather than from a
Path, which is what keeps it substitutable like every other filesystem operation:Acquisition takes two independent decisions and keeps them separate. The method chooses the capability, and
FileSystem.WriteOpenchooses what should happen about existence:Existingrequires an existing regular file.Createopens an existing file or creates an absent one.CreateNewcreates the file and fails when the path is already taken.None of the three truncates an existing file.
CreateNewis atomic against a concurrent creator, throughCREATE_NEWon the JVM and Native andO_EXCLon Node, so exactly one of two racing openers wins and the loser seesFileAlreadyExistsException.Capability is enforced at the type level in both directions. A
ReadChannelhas nowriteAt,truncateorsync; aWriteChannelhas noreadAtorsize. AFileSystem.Readbackend vendsopenReadChanneland nothing else, so a read-only backend cannot hand out a write channel:ReadWriteChannelextends both parents and keeps their distinct failure rows rather than widening every operation to one filesystem error. A read on a read-write channel still fails throughAbort[FileReadException]and a write throughAbort[FileWriteException], so a caller recovering from one does not silently catch the other.Lifetime belongs to the
Scopeactive at acquisition. The public channels expose noclose, so a channel cannot outlive the scope that owns it, and there is no way to close one twice.What changed
Pathgains the three channel traits plus a privateRawChannelandRawChannelAccess.RawChannelis the single narrow surface a platform must implement (readAt,writeAt,sync,truncate,size,close) and it staysprivate[kyo]; the public capabilities are assembled from it rather than exposing it.FileSystemgrows the acquisitions along its existing tier split.ReadgainsopenReadChannel,WritegainsopenWriteChannelandopenReadWriteChannel, and theWriteOpenenum is new. The unscoped variants stayprivate[kyo]: they hand back a release function for the cases inside the module that own the lifetime themselves, and they are not part of the public surface.HostFileSystemwraps the raw channel into the typed capabilities and validates bounds at the boundary, so a negative position, length or truncation size fails through the channel's own typed error instead of reaching the OS.FileSystemOperationgainsChannelandSyncso an acquisition failure and aforce/fsyncfailure name what they were doing instead of borrowingReadorWrite.JVM and Native implement
NioRawChanneloverFileChannel, using the positionedread(ByteBuffer, long)andwrite(ByteBuffer, long)overloads, which by contract do not touch the channel's own file-position cursor. Both loop until the request is satisfied, since a single call may transfer fewer bytes than asked.JS and Wasm implement
NodeRawChannelover a Node file descriptor, passingreadSync/writeSyncan explicitpositionfor the same reason. Opening uses numeric flags rather than mode strings, because the string modes carry truncation and append semantics that a positioned channel must not have. The facade declares those position parameters asDouble: JavaScript has no 64-bit integer and Scala.js compilesLongto a two-word object rather than a JS number, so the conversion happens once at the boundary and the arithmetic above it stays inLong.Tests.
PathChannelTestcovers the capability and tier laws withtypeCheckErrors, positioned short reads and sparse writes, the three open policies, concurrentCreateNew, invalid bounds, scope release, idempotent unscoped release, and release exactly once under interrupt.FileSystemChannelTestSuiteis the reusable cross-backend contract, joiningFileSystemReadTestSuiteandFileSystemWriteTestSuite, so every mutable backend added later inherits the same laws.Stack
Part of the path-capability stack: process fixes, filesystem vocabulary, abstraction, capability flip, channels, locks, watch, durability, confinement, in-memory, zip, then overlay (#1799). Merge bottom up; GitHub retargets the stack above each merge.
The lower branches (#1856, #1857, #1852, #1854, #1888, #1861, #1862, #1863, #1864) have landed, so this branch is now a single commit rebased onto
main. The original incremental development history remains visible in #1799's earlier timeline and in the backup refs recorded in the working notes.