Skip to content

[kyo-system] read and write a file at an offset - #1865

Merged
fwbrasil merged 1 commit into
mainfrom
path-channels
Sep 1, 2026
Merged

fwbrasil merged 1 commit into
mainfrom
path-channels

Conversation

@DamianReeves

@DamianReeves DamianReeves commented Aug 8, 2026 •

Copy link
Copy Markdown
Collaborator

What this adds

Positioned file access. Path.ReadChannel[S], Path.WriteChannel[S] and Path.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. readAt tolerates a short read at end of file and returns fewer bytes than requested rather than failing. writeAt zero-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:

import kyo.*

val positioned =
    Scope.run {
        FileSystem.host.openReadWriteChannel(Path("index.bin"), FileSystem.WriteOpen.CreateNew).map { channel =>
            channel.writeAt(0L, Span.from(Array[Byte](1, 2, 3))).andThen(channel.readAt(0L, 3))
        }
    }

Acquisition takes two independent decisions and keeps them separate. The method chooses the capability, and FileSystem.WriteOpen chooses what should happen about existence:

  • Existing requires an existing regular file.
  • Create opens an existing file or creates an absent one.
  • CreateNew creates the file and fails when the path is already taken.

None of the three truncates an existing file. CreateNew is atomic against a concurrent creator, through CREATE_NEW on the JVM and Native and O_EXCL on Node, so exactly one of two racing openers wins and the loser sees FileAlreadyExistsException.

Capability is enforced at the type level in both directions. A ReadChannel has no writeAt, truncate or sync; a WriteChannel has no readAt or size. A FileSystem.Read backend vends openReadChannel and nothing else, so a read-only backend cannot hand out a write channel:

// compiles
def inspect[S](fs: FileSystem.Read[S], path: Path)(using Frame) = fs.openReadChannel(path)

// rejected at the call site
def mutate[S](fs: FileSystem.Read[S], path: Path)(using Frame) =
    fs.openWriteChannel(path, FileSystem.WriteOpen.Existing)

ReadWriteChannel extends 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 through Abort[FileReadException] and a write through Abort[FileWriteException], so a caller recovering from one does not silently catch the other.

Lifetime belongs to the Scope active at acquisition. The public channels expose no close, so a channel cannot outlive the scope that owns it, and there is no way to close one twice.

What changed

Path gains the three channel traits plus a private RawChannel and RawChannelAccess. RawChannel is the single narrow surface a platform must implement (readAt, writeAt, sync, truncate, size, close) and it stays private[kyo]; the public capabilities are assembled from it rather than exposing it.

FileSystem grows the acquisitions along its existing tier split. Read gains openReadChannel, Write gains openWriteChannel and openReadWriteChannel, and the WriteOpen enum is new. The unscoped variants stay private[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.

HostFileSystem wraps 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.

FileSystemOperation gains Channel and Sync so an acquisition failure and a force/fsync failure name what they were doing instead of borrowing Read or Write.

JVM and Native implement NioRawChannel over FileChannel, using the positioned read(ByteBuffer, long) and write(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 NodeRawChannel over a Node file descriptor, passing readSync/writeSync an explicit position for 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 as Double: JavaScript has no 64-bit integer and Scala.js compiles Long to a two-word object rather than a JS number, so the conversion happens once at the boundary and the arithmetic above it stays in Long.

Tests. PathChannelTest covers the capability and tier laws with typeCheckErrors, positioned short reads and sparse writes, the three open policies, concurrent CreateNew, invalid bounds, scope release, idempotent unscoped release, and release exactly once under interrupt. FileSystemChannelTestSuite is the reusable cross-backend contract, joining FileSystemReadTestSuite and FileSystemWriteTestSuite, 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.

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.
@fwbrasil
fwbrasil merged commit 272b1be into main Sep 1, 2026
21 of 22 checks passed
@fwbrasil
fwbrasil deleted the path-channels branch September 1, 2026 16:33
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.
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