PureOne's picture
Upload research package with Eve Uploader
fa25917 verified
|
Raw History Blame Contribute Delete
19.2 kB
# Python API reference
The standalone runtime contains a standard-library-only `pagefs` module and
the `nyarion` command package. The storage API operates on regular POSIX files.
It requires `fcntl.flock`, `os.pread`, `os.pwrite`, and working `fsync` semantics.
The current implementation is not a native Windows backend.
## Open and create
```python
from pagefs import PageStore
with PageStore.create("experiment.img", pool_blocks=4096) as store:
epoch = store.transact({"/measurements/run-1": b"12.345"}, "run-1")
assert store.query("run-1")["epoch"] == epoch
with PageStore("experiment.img", writable=False) as store:
assert store.get("/measurements/run-1") == b"12.345"
```
`PageStore.create(path, *, initial_files=None, pool_blocks=16384)` exclusively
creates a new image. An existing path is not overwritten. `initial_files`, when
provided, is a dictionary from validated path strings to byte strings. Creation
publishes epoch zero and synchronizes its parent directory. A failed creation
may leave a partial image at its exclusively created path; a failure is not a
successful usable-volume response.
`PageStore(path, *, writable=True, minimum_epoch=None)` opens and recovers an
existing image. Writable open takes a nonblocking exclusive process lock and
repairs recoverable selected mirrors before allowing later operations.
Read-only open takes a nonblocking shared lock and does not apply repairs.
Multiple read-only processes may open an image; they do not coexist with a
writer holding the lock. `minimum_epoch`, when supplied, is a caller-provided
unsigned epoch floor: recovery fails if the recovered epoch is lower.
The instance has no per-method thread mutex. Callers must serialize writable
methods and must not race logical reads against an in-progress mutation on the
same instance.
When an outstanding capsule tail exists, writable open also reconstructs an
exact executable checkpoint plan. An older writer can have left a recoverable
tail that cannot checkpoint in the configured arena. Such an image remains
available to read-only recovery, but this version refuses writable open with
`AdmissionRejected`. Writable open may already have repaired redundant copies
before discovering that admission failure.
Use a context manager or call `close()`. Close is idempotent; it does not make
an additional logical checkpoint. Already acknowledged capsules retain their
own persistence contract. A closed instance cannot be used again.
`CutStore` and `ImageStore` are aliases of `PageStore`, supplied for source
compatibility with project naming. They do not add selective-checkpoint APIs.
## Path, value and token rules
Paths are logical keys, not host paths. A key must start with `/`, have no empty,
`.` or `..` components, contain no backslash or NUL, fit within 1,024 UTF-8 bytes,
and fit the separate canonical-JSON entry bound. `/` alone is not a file key.
Unicode paths are allowed when they satisfy the byte and encoding bounds.
No directory objects, ACLs, hard links or host path resolution are implied by
the slash-separated spelling.
Values are Python `bytes`. `None` is a deletion marker in a transaction; it is
not a stored value. `b""` is a valid empty value. Values replace complete logical
files. There is no range-write interface.
Tokens contain 1 through 64 characters from `A-Z`, `a-z`, `0-9`, `_`, `.`, `:`,
and `-`. A token identifies one intent for the life of its retained receipt.
There is no implicit receipt expiration or garbage collection of live tokens.
## `transact(changes, token) -> int`
`changes` is a nonempty dictionary from path keys to replacement `bytes` or
`None`. The call is one atomic logical transaction, including multiple paths.
Deleting an absent key is accepted as an intent, subject to the other rules.
The transaction's complete encoded capsule must fit the bounded record. The
65,432-byte payload limit includes JSON, base64, paths, token and metadata;
it is not the maximum raw value size available to every request.
On success the call returns its logical epoch. New epochs increase by one.
Ordinary fitting transactions write two complete capsule copies and wait for
a successful `fsync` before returning. A transaction may also trigger ordered
checkpoint work before its own capsule can be acknowledged. Measure the full
call when measuring durable transaction latency.
Before the offered capsule's first write, release 8 checks the hypothetical
acknowledged window using one of two capacity paths. Its ordinary path updates
a conservative upper bound for affected published-leaf cells, their shared
ancestors and new blob pages. A cell contains a weighted persistent symbolic
trie. Leaves maintain entry counts and encoded-entry size sums; branches cache
their subtree page counts. An offer copies changed budget paths and updates
the affected leaf maps rather than recounting every entry of a pending cell.
Unchanged symbolic subtrees are shared.
New symbolic descriptors use maximum format widths. When a symbolic leaf
overflows, it splits by the next hash nibble. A symbolic branch can remain after
values shrink, conservatively charging pages that the physical builder might
no longer require; empty symbolic branches are pruned. If the sufficient bound
fits the available arena, the engine need not compile the complete pending
window before acknowledgment.
When the upper bound exceeds free blocks, the engine compiles the complete
exact plan, including the new receipt, actual free addresses and dependency/
seal bytes. A loose bound does not by itself reject an offer that the exact
planner can fit. A saturated symbolic count is inconclusive and also routes
to exact planning rather than claiming the actual checkpoint cannot fit. If exact planning fails while an earlier admitted tail exists,
the engine can first publish that tail and retry the offer against reclaimed
space. A final `AdmissionRejected` writes no offered capsule and adds no
receipt. That refusal keeps the instance usable; maintenance of earlier
acknowledged work may have advanced the catalogue generation.
The accepted window therefore has sufficient engine-arena checkpoint headroom
under the bound/compiler, serialization and unchanged-allocation assumptions
in the theory notes. Some accepted windows retain exact plans; fast-path
windows retain incremental reservation metadata and compile their plan when
checkpoint execution or an exact-plan query requires it. This does not
guarantee host free space, RAM, successful I/O, indefinite token growth or
acceptance at full utilization. Capsule writes occupy a separate fixed region
and do not consume arena addresses. Checkpoint verifies exact plan bindings
before publication. Reservation proposals are private persistent updates: the
new budget root and accounting totals become accepted state only after the
offered capsule's successful persistence force.
Retrying an already acknowledged token with the same intent returns its
original epoch without applying the changes twice. Reusing that token with a
different intent raises `TransactionConflict`. The intent includes deletion
markers and the length/digest of every replacement value, in sorted path order.
It does not depend on dictionary insertion order.
```python
with PageStore("experiment.img") as store:
original = store.transact({"/a": b"one", "/b": b"two"}, "batch-1")
assert store.transact({"/b": b"two", "/a": b"one"}, "batch-1") == original
```
An interrupted caller can query its token after successful recovery. A valid
committed capsule can be recovered even when the caller did not receive its
success response. Conversely, an exception must not be interpreted as proof
that an operation could not have become durable.
## Reads and receipts
`get(path) -> bytes` returns the recovered/current logical value. An absent key
raises `FileNotFoundError`. Reads use RAM state; this call does not reread and
revalidate the backing image on every access. Reopening and verifying the
selected graph is a separate operation.
`files() -> list[str]` returns all current path keys in sorted order.
`query(token) -> dict | None` returns `{"epoch": int, "intent_sha256": str}`
for a retained successful receipt, or `None` if no receipt exists. Invalid
token spelling raises `ValueError`; it is not an absent-token query.
## Checkpoint and inspection
`checkpoint() -> int` publishes the full outstanding logical prefix and returns
its checkpoint epoch. It copies changed trie paths, shares unchanged immutable
objects, publishes a catalogue, and retires covered capsule slots after ordered
persistence. It is global: shard arguments from earlier project engines are
not supported. Fast-path accepted tails may compile their exact plan here; an existing current
exact plan is reused. Calling without new logical changes may advance the
catalogue generation without advancing the logical epoch.
`inspect() -> dict` reports format and volume identity, logical/checkpoint
epochs, generation, arena capacity, live/free blocks, file names, receipt count
and I/O/statistics counters. Its `admission` member contains the fields returned
by `admission_reservation()`, plus `planned_blocks`, the physical dependency
replica count of a cached exact plan or `None` when no exact plan is cached.
An upper-bound-certified fast-path tail can consequently have
`tail_certified: true` and `planned_blocks: null`.
`admission_reservation() -> dict` returns a detached process-time summary:
| Field | Meaning |
|---|---|
| `certificate_kind` | `empty`, `exact_plan`, or `upper_bound` |
| `reserved_upper_blocks` | Conservative physical replica-block bound |
| `free_blocks` | Current engine-arena free block count |
| `cells` | Number of affected published-leaf cells |
| `dirty_ancestors` | Number of shared published ancestors charged once |
| `tail_certified` | No tail, a current state-bound exact plan, or an upper bound that fits |
The word `reserved` describes capacity accounting, not newly allocated blocks
or host disk reservation. Calling inspection may lazily reconstruct reservation
metadata and grow lookup caches, but does not write or force the image. A
read-only legacy tail may show `tail_certified: false` when its conservative
bound is too loose; that does not prove it is infeasible. An explicit exact
`checkpoint_plan()` query can decide the exact compiler's fit. These summaries
are not persistent certificate fields. `reset_stats()` resets diagnostic
counters rather than persistent state, and correctness does not depend on them.
A fixed apparent image length is not physical storage traffic or allocation.
Symbolic leaf size accounting is exact for its conservative entry encodings.
For compact canonical JSON encoding `E`, each entry has weight
`len(E(key)) + 1 + len(E(value))`. Add the entry-weight sum and
`max(entry_count - 1, 0)` commas to the empty-entry leaf skeleton containing its
actual family and depth. This yields the symbolic leaf payload size without
serializing all stored entries on each update. Maximum-width new-blob values
make this size sufficient for the corresponding physical leaf, not a minimum
physical allocation claim.
## `checkpoint_plan(*, include_writes=False) -> dict`
This method returns a detached summary of the exact checkpoint for the current
logical state. It performs no image writes or persistence forces and does not
consume the selected allocator's free blocks. It may compile a plan and update
diagnostic counters; writable instances may retain the compiled plan for later
execution. Read-only instances may inspect feasibility but cannot publish.
The returned fields are `epoch`, `generation`, `history`, `pool_blocks`,
`physical_blocks`, `bytes_written`, `root_sha256`, and `force_boundaries`.
`physical_blocks` counts new physical dependency replicas, not logical objects.
`bytes_written` includes both dependency pages and seal records. The two force
boundaries identify the cumulative write counts after which dependencies and
publication respectively require their persistence barriers.
With `include_writes=True`, the result also contains `writes`, an ordered tuple
of `(byte_offset, immutable_bytes)` pairs: dependency pages followed by seals.
These bytes can contain file data and receipt metadata. The result is useful
for audit and fault injection; it is not permission to replay records manually
without the engine's binding checks, locks and two-force publication protocol.
Calling this method can raise `AdmissionRejected` on a read-only recovered
legacy tail that has no feasible checkpoint, while ordinary reads remain
available. A no-change checkpoint still needs a successor catalogue; the fact
that the current state is already fully checkpointed does not guarantee spare
space for arbitrarily many extra publications.
## Errors and session state
| Error | Meaning |
|---|---|
| `ValueError`, `TypeError` | Invalid request spelling, type or bounded representation |
| `FileNotFoundError` | Missing image on open, or missing logical key on `get` |
| `TransactionConflict` | Existing token was associated with a different intent |
| `AdmissionRejected` | Offered state or recovered writable tail has no feasible exact arena checkpoint |
| `InvalidImage` | Invalid structured data, bounds or descriptor relationships |
| `RecoveryBlocked` | Required evidence or dependency cannot be safely reconstructed |
| `SplitIdentity` | Conflicting volume or same-generation/epoch identities |
| `UnsupportedFormat` | A checksum-valid record claims an unsupported format |
| `WriterFenced` | Read-only or uncertain session cannot perform an operation |
| `OSError` | Host I/O, locking or storage error; inspect the original error details |
`SplitIdentity` and `UnsupportedFormat` derive from `RecoveryBlocked`; the
other listed named engine errors derive from `StoreError`, except
`AdmissionRejected`, which derives from `OSError` and carries `errno.ENOSPC`.
A closed instance raises
`StoreError`. A read-only instance remains readable but rejects mutations.
After uncertain persistent I/O or a partially adopted in-memory update, the
engine fences the instance. Logical reads and writes then fail until it is
closed and reopened successfully. Fencing prevents an inconsistent live
session from being treated as a valid recovered view. It is distinct from a
safe request rejection before the proposed intent is persisted.
## Resource and durability boundary
All live file values, receipt history, reservation metadata and any retained
exact plan remain in RAM.
Arena capacity is finite, and copy-on-write requires room for the old and
successor graphs to coexist through publication. Admission rejects an
offered state that cannot satisfy that coexistence requirement; it does not
make the requirement disappear. The fast path updates changed symbolic paths
and bounded leaf maps, their shared ancestor charges and blob debits. A split
may redistribute a leaf's entries; first access to a published leaf initializes
its weights. No constant-time latency, balanced worst-case hash distribution,
or independence from offered data size is implied. Exact fallback and checkpoint
compilation can still rebuild the bounded dirty window. Recovery reconstructs
the pending admission state. Receipt history itself is live data and can fill the arena. Initial imports and individual transaction encodings
have explicit size limits. No unlimited-write or full-utilization promise
follows merely from physical address reuse.
The API supplies atomic logical updates under its declared persistence and
fault assumptions. It does not supply filesystem mount semantics, host file
descriptors for individual keys, memory mapping, concurrent writers, snapshots,
whole-drive redundancy, encryption or malicious-modification authentication.
The finite tests document their own scopes; they are not hardware durability
certification.
## Command-line interface
Use `python3 -m nyarion`, the installed `nyarion` command, or the standalone
`python3 nyarion.pyz`. The same commands are available in each form:
| Command | Behavior |
|---|---|
| `init IMAGE --pool-blocks N` | Exclusively create an empty image |
| `put IMAGE KEY --token T --text TEXT` | Store UTF-8 bytes of one text value |
| `put IMAGE KEY --token T --file PATH` | Store input bytes; `-` reads standard input |
| `get IMAGE KEY --output PATH` | Write raw bytes; default output `-` is standard output |
| `ls IMAGE` / `list IMAGE` | Return sorted logical keys as JSON |
| `delete IMAGE KEY --token T` | Submit one logical deletion |
| `transact IMAGE REQUEST.json` | Submit one atomic UTF-8 JSON transaction; `-` reads standard input |
| `checkpoint IMAGE` | Publish the outstanding global prefix |
| `inspect IMAGE` | Inspect recovered state without applying repairs |
| `plan IMAGE` | Report the current exact checkpoint summary without writing |
| `query IMAGE TOKEN` | Return one retry receipt or JSON `null` |
| `verify IMAGE` | Recover read-only and report a logical snapshot digest |
| `repair IMAGE` | Open writable, repair available redundant copies and inspect |
| `export IMAGE --output PATH` | Export logical file bytes and receipt metadata as audit JSON |
The `put` command requires exactly one of `--text` and `--file`. Input files
and transaction documents have an additional 1 MiB command-level limit; the
engine's much smaller encoded-capsule limit still applies. Successful metadata
responses are JSON. `get` emits raw bytes without a JSON wrapper. Listed keys
are JSON-escaped rather than printed as unsafe raw control characters.
File outputs use exclusive creation. An existing `--output` path is rejected,
including an existing image or input file; output is not silently overwritten.
`verify` and `export` read a recovered logical view without modifying the image.
A successful verify means that view is recoverable under the engine's checks;
it does not assert that every redundant copy is healthy or that the hardware
has been power-loss qualified.
A transaction document has exactly the following structure:
```json
{
"token": "batch-2",
"changes": {
"/a": {"base64": "dGhyZWU="},
"/b": null
}
}
```
This writes `b"three"` to `/a` and deletes `/b` atomically. Each change must be
JSON `null` or an object containing only `base64`. Duplicate fields, invalid
UTF-8, invalid base64 and unknown top-level fields are rejected.
The export contains `export_format`, `engine_format`, `volume`, `epoch`, the
file list, receipt list and `snapshot_sha256`. Each file includes its path,
base64 bytes, length and SHA-256. The snapshot digest covers the canonical
export body before its own digest field is added. This is a logical audit
snapshot, not a complete physical image; no import/restore or receipt-migration
guarantee is supplied by this command. Preserving a physical image preserves
its format-level recovery information separately.
Expected command/data/I/O errors print a message on standard error and return
exit status `2`; successful commands return `0`. After an uncertain I/O error,
follow recovery and token-query semantics rather than assuming the offer
definitely failed. The CLI does not mount the image or install an OS driver.