From 858b5f791a7d881015af7e374a26d10f4c2bb86b Mon Sep 17 00:00:00 2001 From: Nathan Young Date: Sun, 15 Nov 2026 13:10:46 -0500 Subject: [PATCH 01/10] Add durable publication and context-owned file locks Matrix-authored Enigma exposed a general library gap: a checked atomic write synchronized the candidate inode and published its name, but left the parent directory undurable, a stream flush was not a filesystem barrier, and no supported advisory-lock API existed. Applications had to supply their own platform host. Add write_bytes_durable, sync_directory, acquire_file_lock, and release_file_lock to nil.std.io as an additive POSIX profile. Durable writes reuse the atomic publication helper and synchronize the same anchored directory descriptor used to publish; a post-publication sync failure returns an explicitly uncertain outcome rather than implying the old destination survived. Existing write_bytes_atomic and File.flush contracts are unchanged. Locks are nonblocking exclusive advisory locks on private 0600 regular files. A runtime-owned registry holds the descriptors and hands out process-monotonic tokens that are never recycled, never expose a host descriptor, are checked against their owning execution context, and are closed at invocation termination and context teardown. Execution checkpoints reject open locks. Unsupported platforms fail closed before any filesystem mutation. Tests cover the shared OS helpers, embedded VM invocation/reset/destructor cleanup, static and shared native context lifetimes, paired Ny/Matrix textual and binary VM plus AOT and JIT routes, malformed ABI declarations, private file modes, contention, and Linux file and directory sync fault injection including uncertain publication. This is a Linux-tested POSIX mechanism, not a production database protocol, power-loss certification, pathname containment service, or rollback defense. Private-directory creation, owner/mode inspection, standalone SHA-256, and a complete storage host remain separate APIs. Source declarations alone do not give an installed SDK the new provider; release qualification is independent work. Co-Authored-By: Claude Opus 5 --- CMakeLists.txt | 23 + .../NIL-0028-durable-files-and-locks.md | 57 +++ docs/design/README.md | 1 + docs/standard-library/durable-files.md | 91 ++++ docs/standard-library/index.md | 6 + nilcompiler/src/native_runtime.cpp | 54 +++ nilcompiler/src/ordinary_io_intrinsic.hpp | 10 + nilcompiler/src/secure_file_io.cpp | 233 ++++++++- nilcompiler/src/secure_file_io.hpp | 35 ++ nilcompiler/src/vm.cpp | 98 +++- nilcompiler/src/vm.hpp | 2 + nilstd/src/io/file.ny | 29 ++ nilstd/src/io/package.ny | 1 + nilstd/src/text/string_utils.ny | 2 + tests/durable_file_io_tests.cpp | 455 ++++++++++++++++++ tests/durable_vm_lifecycle_tests.cpp | 231 +++++++++ .../language/durable-file-io-invalid-owner.ny | 18 + .../language/durable-file-io-invalid-width.ny | 11 + tests/language/durable-file-io.ny | 51 ++ tests/matrix/io/durable-file-io.matrix | 99 ++++ tests/native_runtime_tests.cpp | 86 ++++ tests/tools/durable_file_io_contract.py | 196 ++++++++ 22 files changed, 1750 insertions(+), 39 deletions(-) create mode 100644 docs/design/NIL-0028-durable-files-and-locks.md create mode 100644 docs/standard-library/durable-files.md create mode 100644 tests/durable_file_io_tests.cpp create mode 100644 tests/durable_vm_lifecycle_tests.cpp create mode 100644 tests/language/durable-file-io-invalid-owner.ny create mode 100644 tests/language/durable-file-io-invalid-width.ny create mode 100644 tests/language/durable-file-io.ny create mode 100644 tests/matrix/io/durable-file-io.matrix create mode 100644 tests/tools/durable_file_io_contract.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 78f23a6e..fc7404b5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -101,6 +101,23 @@ install( install(FILES LICENSE DESTINATION ".") if(BUILD_TESTING) + add_executable(nil_durable_file_io_tests + tests/durable_file_io_tests.cpp + nilcompiler/src/secure_file_io.cpp) + target_compile_features(nil_durable_file_io_tests PRIVATE cxx_std_17) + target_include_directories(nil_durable_file_io_tests PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/nilcompiler/src") + if(CMAKE_SYSTEM_NAME STREQUAL "Linux") + target_compile_definitions(nil_durable_file_io_tests PRIVATE NIL_TEST_WRAP_FSYNC=1) + target_link_options(nil_durable_file_io_tests PRIVATE "-Wl,--wrap=fsync") + endif() + add_test(NAME nil.durable-file-io COMMAND $) + set_tests_properties(nil.durable-file-io PROPERTIES LABELS "stdlib;io;security;rc" TIMEOUT 30) + add_executable(nil_durable_vm_lifecycle_tests tests/durable_vm_lifecycle_tests.cpp) + target_compile_features(nil_durable_vm_lifecycle_tests PRIVATE cxx_std_17) + target_include_directories(nil_durable_vm_lifecycle_tests PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/nilcompiler/src") + target_link_libraries(nil_durable_vm_lifecycle_tests PRIVATE nilcompiler_core) + add_test(NAME nil.durable-vm-lifecycle COMMAND $) + set_tests_properties(nil.durable-vm-lifecycle PROPERTIES LABELS "stdlib;io;security;vm;rc" TIMEOUT 30) foreach(nil_hook_profile IN ITEMS default override) add_executable(nil_freestanding_hook_${nil_hook_profile} tests/freestanding_hook_contract.cpp) target_compile_features(nil_freestanding_hook_${nil_hook_profile} PRIVATE cxx_std_17) @@ -725,6 +742,12 @@ if(BUILD_TESTING) # test suite when testing was explicitly enabled. find_package(Python3 3.8 REQUIRED COMPONENTS Interpreter) if(Python3_Interpreter_FOUND) + add_test(NAME nil.durable-file-io-routes + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/durable_file_io_contract.py" + --compiler $ --interpreter $ + --nilstd "${CMAKE_CURRENT_SOURCE_DIR}/nilstd/src" --runtime $ + --llvm "${NIL_ENABLE_LLVM}" --output "${CMAKE_BINARY_DIR}/durable-io-evidence") + set_tests_properties(nil.durable-file-io-routes PROPERTIES LABELS "storage;stl;routes;rc" TIMEOUT 300) if(CMAKE_SYSTEM_NAME STREQUAL "Linux") add_test(NAME nil.darwin-heap-accounting COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/darwin_heap_accounting_contract.py" diff --git a/docs/design/NIL-0028-durable-files-and-locks.md b/docs/design/NIL-0028-durable-files-and-locks.md new file mode 100644 index 00000000..63c4c626 --- /dev/null +++ b/docs/design/NIL-0028-durable-files-and-locks.md @@ -0,0 +1,57 @@ +# NIL-0028: Durable publication and context-owned file locks + +- **Status:** Implemented additive POSIX source-runtime profile; release SDK + qualification remains separate. + +## Motivation + +The Matrix-authored Enigma database exposed a general library gap. A checked +atomic write synchronized the candidate inode and published its name, but lacked +parent-directory durability. A stream flush was not a filesystem barrier, and no +supported advisory-lock API existed. Applications had to supply a platform host. + +General filesystem mechanisms belong in `nil.std.io`. Database schemas, evidence +semantics, permission policy, and recovery decisions stay in the application. + +## Decision + +Add `write_bytes_durable`, `sync_directory`, `acquire_file_lock`, and +`release_file_lock`. Preserve the existing `write_bytes_atomic` and `File.flush` +contracts. Durable writes reuse the atomic publication helper and synchronize +the exact publication directory descriptor. A post-publication sync failure +returns an explicitly uncertain outcome. + +File locks are nonblocking exclusive advisory locks on private regular backing +files. Runtime-owned registries hold the descriptors. Tokens are never recycled, +are checked against their owning execution context, and are closed at invocation +termination and context teardown. An execution checkpoint cannot clone one. +Unsupported platforms fail closed before mutation. + +Use the existing checked ordinary-I/O bridge for native execution, with exact +parameter/result and enum ownership validation. The VM checks the new result +metadata and concrete enum schema, and validates dynamic arguments before host +effects. The shared helper implements the OS contract once. + +## Boundaries and validation + +The Enigma consumer also requires the existing `text.byte_at` and `from_byte` +operations on native routes. Their native providers use the ordinary-I/O bridge +and preserve byte/range behavior within the native NUL-free text boundary. + +This is a Linux-tested POSIX mechanism, not a production database protocol, +power-loss certification, pathname containment service, credential, or general +rollback defense. Lock participants must cooperate and control the directory +ancestry. Fork-inherited descriptors retain ordinary POSIX lifetime semantics. +An uncertain publication requires caller recovery rather than transparent retry. + +Tests cover shared OS helpers, embedded VM invocation/reset/destructor cleanup, +static/shared native context lifetimes, Ny/Matrix VM text/binary and AOT/JIT +routes, malformed ABI declarations, private file modes, contention, and Linux +file/directory-sync fault injection. Existing secure-byte and ordinary-I/O +regressions remain part of focused validation. + +The [public API reference](../standard-library/durable-files.md) defines exact +limits. Existing SDKs do not gain the new provider from source declarations +alone. A development build must ship matching compiler, runtime, and library +sources; release/installed-SDK qualification and the remaining application-host +APIs are independent work. diff --git a/docs/design/README.md b/docs/design/README.md index 939f1e83..3abe5cbc 100644 --- a/docs/design/README.md +++ b/docs/design/README.md @@ -54,6 +54,7 @@ not assigned architecture identifiers. | NIL-0025 | [Matrix desktop UI](NIL-0025-matrix-desktop-ui.md) | Implemented GTK4 on Linux, Win32 on Windows and AppKit on Intel/Apple Silicon macOS; release qualification remains separate | | NIL-0026 | [Evolving the language without breaking what is written](NIL-0026-language-evolution.md) | Editions implemented in the project manifest | | NIL-0027 | [Multiline formatted text and structured markup literals](NIL-0027-structured-markup.md) | Proposed; staged, nothing shipped | +| NIL-0028 | [Durable publication and context-owned file locks](NIL-0028-durable-files-and-locks.md) | Implemented additive POSIX source-runtime profile; installed/release SDK qualification separate | | NIL-0093 | [Executable context is artifact self-description](NIL-0093-executable-context.md) | Implemented within the documented inspection profile | ## Retained Ny feature references diff --git a/docs/standard-library/durable-files.md b/docs/standard-library/durable-files.md new file mode 100644 index 00000000..8b4ae382 --- /dev/null +++ b/docs/standard-library/durable-files.md @@ -0,0 +1,91 @@ +# Durable files and advisory locks + +`nil.std.io` provides additive POSIX primitives for applications that need a +durable checkpoint and a cooperative single-writer protocol. Ny and Matrix use +the same runtime provider and checked results. + +| Function | Result | +| --- | --- | +| `write_bytes_durable(path, content, replace)` | `Result` | +| `sync_directory(path)` | `Result` | +| `acquire_file_lock(path, create)` | `Result` | +| `release_file_lock(token)` | `Result` | + +Matrix uses the same names with underscores or hyphens. Machine-width lock +tokens appear as `number`/`override long`; they are runtime handles, not host +descriptors or authentication credentials. + +## Publication and durability + +`write_bytes_durable` keeps the existing atomic byte-write rules: bounded byte +arrays, strict UTF-8 nonempty NUL-free filenames, a fresh private `0600` staging +inode, and no-clobber publication when `replace` is false. Replacement preflight +requires a regular destination, and publication replaces the entry without +following it. Existing ownership, mode, ACLs, and extended attributes are not +copied. It adds synchronization of the **same directory descriptor** used for +publication, after synchronizing the candidate file and publishing its entry. + +Success means those synchronization calls succeeded. It assumes a filesystem +and device stack honoring `fsync` and atomic rename/link. It does not prove +hardware power-cut behavior, protect against privileged namespace replacement, +or authenticate data. Parent-directory ancestry must be trusted. Cleanup can +leave an orphaned `.ny-write-*` entry after a host failure. + +If directory synchronization fails after publication, the operation returns +`Error("file.write_bytes_durable: publication durability uncertain")`. The +candidate may already be visible. A caller must stop or poison its session and +recover rather than assume the previous file remains or retry blindly. + +`sync_directory` synchronizes an existing directory selected without following +its final component. It is useful after separately controlled namespace changes, +including initial directory/lock creation. Its ancestors remain trusted. + +`write_bytes_atomic` retains its visibility-only contract. `File.flush` retains +its stream-flush contract; neither acquires the new durability guarantee. + +## Lock ownership + +`acquire_file_lock(path, true)` exclusively creates a new private backing file; +it fails if an entry already exists. Pass `false` to open an existing lock file. +The file must be regular, owned by the effective user, have one hard link, and +have exactly mode `0600`. Symlinks, special files, and unsafe permissions fail. +The runtime acquires a nonblocking exclusive advisory `flock`, with close-on-exec +and no-follow/nonblocking open flags, and checks the acquired inode still names +the inspected entry. Paths never appear in returned diagnostics. + +All writers must use the same persistent lock entry. Do not unlink or replace +that file while participants may still hold it. Creating the file does not +durably publish its name; synchronize the parent when the application needs it. +The limit is 4,096 held locks per execution context. + +Returned tokens are positive, monotonically allocated, and never recycled +within a runtime instance. `release_file_lock` checks ownership in the current +execution context; wrong, foreign, stale, and repeated-release tokens fail. +Runtime teardown closes remaining locks on VM completion, failure, reset, +replacement, destruction, or native context end. VM execution checkpoints reject +open locks. Normal POSIX descriptor inheritance still applies across `fork`: +an inherited descriptor can keep a lock held after its parent's copy closes. + +These are cooperative filesystem locks, not a security boundary against the +owner, root, arbitrary same-process memory access, or nonparticipating writers. + +## Evidence and platform limits + +The existing `nil.std.text.byte_at` and `from_byte` helpers also have native +providers for byte-oriented checkpoint serialization. Byte lookup returns `-1` +outside the string; out-of-range byte construction returns empty text. Native +`from_byte(0)` faults explicitly because native text is NUL-free. Use byte arrays +for arbitrary binary content. Joining nonzero byte fragments preserves their +bytes, including UTF-8 sequences. + +The source-runtime tests exercise Ny and Matrix through textual and binary VM, +AOT, and JIT, with exact host byte/mode oracles, checked ABI failures, runtime +context teardown, and process death. Linux helper tests inject file and directory +sync failures, including uncertain publication. Windows returns an explicit +unsupported-platform error before filesystem mutation. Other POSIX platforms +need their own execution evidence; this addition does not qualify an installed +or release SDK. + +Private-directory creation, owner/mode inspection, standalone SHA-256, and a +complete storage host are separate APIs. A consuming application should migrate +only the parts it has qualified. See [NIL-0028](../design/NIL-0028-durable-files-and-locks.md). diff --git a/docs/standard-library/index.md b/docs/standard-library/index.md index ab94ddd2..d0bae87d 100644 --- a/docs/standard-library/index.md +++ b/docs/standard-library/index.md @@ -148,6 +148,12 @@ so a rare host cleanup failure can leave a `.ny-write-*` orphan. Publication is visibility-atomic but does not promise parent-directory durability after a sudden power loss. +The additive [durable-files reference](durable-files.md) covers +`write_bytes_durable`, `sync_directory`, and context-owned advisory file locks. +Those POSIX primitives supply explicit filesystem barriers and nonblocking +single-writer coordination. They preserve existing atomic-write/stream-flush +semantics and do not expand an older installed SDK's guarantees. + These two secure whole-file APIs now have a native provider in the versioned `nilruntime` ABI. `native.runtime-abi` tests the C boundary directly, and `ny.routes.native_cli_secure_byte_io` exercises the public Ny wrappers through diff --git a/nilcompiler/src/native_runtime.cpp b/nilcompiler/src/native_runtime.cpp index 8300d975..54c66b0d 100644 --- a/nilcompiler/src/native_runtime.cpp +++ b/nilcompiler/src/native_runtime.cpp @@ -96,6 +96,7 @@ struct runtime_context { ny::memory_profile::Session profile; ny::database::Context databases; ny::ui::Context ui; + ny::detail::FileLockRegistry file_locks; struct file { std::unique_ptr stream; bool readable = false; @@ -869,6 +870,7 @@ void nyrt_context_end() noexcept { context.databases.clear(); context.ui.clear(); context.files.clear(); + context.file_locks.clear(); nyrt_owned_v1_unwind(0); context.pending_fault.reset(); std::vector().swap(context.fault_frames); @@ -1659,6 +1661,58 @@ std::int32_t nyrt_io_v1(const char *operation, std::uint64_t first, return std::filesystem::u8path(path); }; + if (name == "text.byte_at") { + const auto *input = text(first); + const auto index = static_cast(second); + const auto size = std::strlen(input); + *value = index < 0 || static_cast(index) >= size + ? static_cast(-1) + : static_cast(input[index]); + return 1; + } + if (name == "text.from_byte") { + if (first > 255) return output_text(""); + if (first == 0) return fail("native text cannot contain NUL"); + const char octet = static_cast(static_cast(first)); + return output_text(std::string_view(&octet, 1)); + } + + if (name == "file.release_file_lock") { + if (first > static_cast(INT64_MAX)) + return fail("invalid lock token"); + const auto released = context.file_locks.release(static_cast(first)); + if (!released.ok) { set_error(error, released.error); return 0; } + *value = 1; + return 1; + } + if (name == "file.acquire_file_lock") { + if (second > 1) return fail("create must be a bool"); + const auto acquired = context.file_locks.acquire(text(first), second != 0); + if (!acquired.ok) { set_error(error, acquired.error); return 0; } + *value = static_cast(acquired.token); + return 1; + } + if (name == "file.sync_directory") { + const auto synced = ny::detail::sync_directory_utf8(text(first)); + if (!synced.ok) { set_error(error, synced.error); return 0; } + *value = 1; + return 1; + } + if (name == "file.write_bytes_durable") { + if (third > 1) return fail("replace must be a bool"); + const auto *array = checked_array(reinterpret_cast(static_cast(second)), NYRT_ARRAY_U8); + if (!array || array->length > maximum_file_bytes) return fail("invalid or oversized byte array"); + std::vector bytes; + if (array->length) { + const auto *data = static_cast(array->data); + bytes.assign(data, data + array->length); + } + const auto written = ny::detail::write_file_durable_utf8(text(first), bytes, third != 0); + if (!written.ok) { set_error(error, written.error); return 0; } + *value = 1; + return 1; + } + if (name.rfind("path.", 0) == 0) { if (name == "path.separator") return output_text("/"); if (name == "path.ends_with") { diff --git a/nilcompiler/src/ordinary_io_intrinsic.hpp b/nilcompiler/src/ordinary_io_intrinsic.hpp index 1689f5b6..12c67977 100644 --- a/nilcompiler/src/ordinary_io_intrinsic.hpp +++ b/nilcompiler/src/ordinary_io_intrinsic.hpp @@ -17,6 +17,8 @@ struct Contract { // values. In particular environment.list's array of named structs is not a // scalar array and must not be reinterpreted as one. inline std::optional intrinsic(const std::string &name) { + if (name == "text.byte_at") return Contract{{"text", "i64"}, "i64"}; + if (name == "text.from_byte") return Contract{{"i64"}, "text"}; if (name == "path.separator" || name == "environment.current_directory" || name == "environment.newline" || name == "environment.machine_name" || name == "environment.user_name") @@ -42,6 +44,14 @@ inline std::optional intrinsic(const std::string &name) { return Contract{{"text", "text"}, "bool", Output::result}; if (name == "file.write_bytes") return Contract{{"text", "array"}, "bool", Output::result}; + if (name == "file.write_bytes_durable") + return Contract{{"text", "array", "bool"}, "bool", Output::result}; + if (name == "file.sync_directory") + return Contract{{"text"}, "bool", Output::result}; + if (name == "file.acquire_file_lock") + return Contract{{"text", "bool"}, "i64", Output::result}; + if (name == "file.release_file_lock") + return Contract{{"i64"}, "bool", Output::result}; if (name == "environment.get") return Contract{{"text"}, "text", Output::option}; if (name == "file.handle_open") return Contract{{"text", "i32"}, "i64"}; if (name == "file.handle_read" || name == "file.handle_write") diff --git a/nilcompiler/src/secure_file_io.cpp b/nilcompiler/src/secure_file_io.cpp index 076cda64..ab2060b8 100644 --- a/nilcompiler/src/secure_file_io.cpp +++ b/nilcompiler/src/secure_file_io.cpp @@ -13,6 +13,7 @@ #ifndef _WIN32 #include #include +#include #include #include @@ -240,15 +241,20 @@ BoundedFileRead read_regular_file_bounded(const std::filesystem::path &path, return {true, std::move(bytes), {}}; } -AtomicFileWrite write_file_atomic(const std::filesystem::path &path, - const std::vector &bytes, - bool replace) { +static AtomicFileWrite write_file_atomic_posix(const std::filesystem::path &path, + const std::vector &bytes, + bool replace, bool durable) { + const std::string operation = durable ? "file.write_bytes_durable" + : "file.write_bytes_atomic"; + const auto failure = [&](const char *reason) { + return AtomicFileWrite{false, operation + ": " + reason}; + }; if (!valid_file_path(path)) - return {false, "file.write_bytes_atomic: invalid destination path"}; + return failure("invalid destination path"); const std::filesystem::path destination = path; const std::filesystem::path filename = destination.filename(); if (filename.empty() || filename == "." || filename == "..") - return {false, "file.write_bytes_atomic: invalid destination path"}; + return failure("invalid destination path"); std::filesystem::path parent = destination.parent_path(); if (parent.empty()) parent = "."; @@ -256,19 +262,16 @@ AtomicFileWrite write_file_atomic(const std::filesystem::path &path, const int directory_flags = O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_DIRECTORY; UniqueFileDescriptor directory(::open(parent.c_str(), directory_flags)); if (directory.get() < 0) - return {false, - "file.write_bytes_atomic: cannot open destination directory"}; + return failure("cannot open destination directory"); if (replace) { struct stat destination_status {}; if (::fstatat(directory.get(), filename.c_str(), &destination_status, AT_SYMLINK_NOFOLLOW) == 0) { if (!S_ISREG(destination_status.st_mode)) - return {false, - "file.write_bytes_atomic: destination is not a regular file"}; + return failure("destination is not a regular file"); } else if (errno != ENOENT) { - return {false, - "file.write_bytes_atomic: cannot inspect destination"}; + return failure("cannot inspect destination"); } } @@ -287,11 +290,10 @@ AtomicFileWrite write_file_atomic(const std::filesystem::path &path, break; } if (errno != EEXIST) - return {false, - "file.write_bytes_atomic: cannot create staging file"}; + return failure("cannot create staging file"); } if (temporary.get() < 0) - return {false, "file.write_bytes_atomic: cannot create staging file"}; + return failure("cannot create staging file"); // openat's creation mode is filtered through the caller's umask. Enforce the // API's exact private-inode contract before any content becomes observable. @@ -301,7 +303,7 @@ AtomicFileWrite write_file_atomic(const std::filesystem::path &path, } while (chmod_status != 0 && errno == EINTR); if (chmod_status != 0) { ::unlinkat(directory.get(), temporary_name.c_str(), 0); - return {false, "file.write_bytes_atomic: cannot secure staging file"}; + return failure("cannot secure staging file"); } // Cleanup is best effort. In particular, publication cannot be safely @@ -319,20 +321,38 @@ AtomicFileWrite write_file_atomic(const std::filesystem::path &path, continue; if (count <= 0) { discard_temporary(); - return {false, "file.write_bytes_atomic: staging write failed"}; + return failure("staging write failed"); } offset += static_cast(count); } - if (::fsync(temporary.get()) != 0) { + int flush_status = -1; + do { + flush_status = ::fsync(temporary.get()); + } while (durable && flush_status != 0 && errno == EINTR); + if (flush_status != 0) { discard_temporary(); - return {false, "file.write_bytes_atomic: staging flush failed"}; + return failure("staging flush failed"); } const int temporary_descriptor = temporary.release(); if (::close(temporary_descriptor) != 0) { discard_temporary(); - return {false, "file.write_bytes_atomic: staging close failed"}; + return failure("staging close failed"); } + const auto finish_publication = [&]() -> AtomicFileWrite { + if (durable) { + int status = -1; + do { + status = ::fsync(directory.get()); + } while (status != 0 && errno == EINTR); + // The new inode is already visible. Never undo publication or imply that + // the previous destination survived an uncertain durability barrier. + if (status != 0) + return failure("publication durability uncertain"); + } + return {true, {}}; + }; + if (!replace) { // linkat is an atomic no-clobber publication: every existing directory // entry, including a dangling symlink, makes it fail with EEXIST. @@ -340,13 +360,11 @@ AtomicFileWrite write_file_atomic(const std::filesystem::path &path, filename.c_str(), 0) != 0) { const int publish_error = errno; discard_temporary(); - return {false, - publish_error == EEXIST - ? "file.write_bytes_atomic: destination already exists" - : "file.write_bytes_atomic: cannot publish staging file"}; + return failure(publish_error == EEXIST ? "destination already exists" + : "cannot publish staging file"); } discard_temporary(); - return {true, {}}; + return finish_publication(); } // renameat replaces the destination directory entry; it never follows a @@ -354,9 +372,15 @@ AtomicFileWrite write_file_atomic(const std::filesystem::path &path, if (::renameat(directory.get(), temporary_name.c_str(), directory.get(), filename.c_str()) != 0) { discard_temporary(); - return {false, "file.write_bytes_atomic: cannot publish staging file"}; + return failure("cannot publish staging file"); } - return {true, {}}; + return finish_publication(); +} + +AtomicFileWrite write_file_atomic(const std::filesystem::path &path, + const std::vector &bytes, + bool replace) { + return write_file_atomic_posix(path, bytes, replace, false); } #else @@ -615,4 +639,161 @@ AtomicFileWrite write_file_atomic(const char *path, return write_file_atomic(std::string(path), bytes, replace); } +AtomicFileWrite sync_directory_utf8(const std::string &path) { +#ifdef _WIN32 + (void)path; + return {false, "file.sync_directory: unsupported platform"}; +#else + const auto native_path = path_from_utf8_string(path); + if (!native_path) + return {false, "file.sync_directory: invalid directory path"}; + const int flags = O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK; + UniqueFileDescriptor directory(::open(native_path->c_str(), flags)); + if (directory.get() < 0) + return {false, "file.sync_directory: cannot open directory"}; + int status = -1; + do { + status = ::fsync(directory.get()); + } while (status != 0 && errno == EINTR); + if (status != 0) + return {false, "file.sync_directory: synchronization failed"}; + return {true, {}}; +#endif +} + +AtomicFileWrite write_file_durable_utf8(const std::string &path, + const std::vector &bytes, + bool replace) { +#ifdef _WIN32 + (void)path; + (void)bytes; + (void)replace; + return {false, "file.write_bytes_durable: unsupported platform"}; +#else + const auto native_path = path_from_utf8_string(path); + if (!native_path) + return {false, "file.write_bytes_durable: invalid destination path"}; + return write_file_atomic_posix(*native_path, bytes, replace, true); +#endif +} + +#ifndef _WIN32 +namespace { + +std::atomic next_lock_token{1}; + +bool private_lock_file(const struct stat &status) { + return S_ISREG(status.st_mode) && status.st_uid == ::geteuid() && + status.st_nlink == 1 && (status.st_mode & 07777) == 0600; +} + +} // namespace +#endif + +FileLockRegistry::~FileLockRegistry() noexcept { clear(); } + +FileLockResult FileLockRegistry::acquire(const std::string &path, bool create) { +#ifdef _WIN32 + (void)path; + (void)create; + return {false, 0, "file.acquire_file_lock: unsupported platform"}; +#else + const auto failure = [](const char *reason) { + return FileLockResult{false, 0, std::string("file.acquire_file_lock: ") + reason}; + }; + const auto native_path = path_from_utf8_string(path); + if (!native_path || native_path->filename().empty() || + native_path->filename() == "." || native_path->filename() == "..") + return failure("invalid lock path"); + if (descriptors_.size() >= 4096) + return failure("lock limit exceeded"); + + int flags = O_RDWR | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC; + if (create) + flags |= O_CREAT | O_EXCL; + int descriptor = -1; + do { + descriptor = ::open(native_path->c_str(), flags, 0600); + } while (descriptor < 0 && errno == EINTR); + UniqueFileDescriptor lock(descriptor); + if (lock.get() < 0) + return failure("cannot open lock file"); + if (create) { + int status = -1; + do { + status = ::fchmod(lock.get(), S_IRUSR | S_IWUSR); + } while (status != 0 && errno == EINTR); + if (status != 0) + return failure("cannot secure lock file"); + } + struct stat held {}; + if (::fstat(lock.get(), &held) != 0 || !private_lock_file(held)) + return failure("lock file is not private and regular"); + + int status = -1; + do { + status = ::flock(lock.get(), LOCK_EX | LOCK_NB); + } while (status != 0 && errno == EINTR); + if (status != 0) + return failure(errno == EWOULDBLOCK || errno == EAGAIN ? "lock is busy" + : "cannot acquire lock"); + + // Advisory locking is over the opened inode, not its path. Reject observed + // namespace replacement so cooperating callers do not knowingly lock two + // different files under the same name. Trusted ancestry remains required. + struct stat visible {}; + if (::fstat(lock.get(), &held) != 0 || !private_lock_file(held) || + ::lstat(native_path->c_str(), &visible) != 0 || + !private_lock_file(visible) || held.st_dev != visible.st_dev || + held.st_ino != visible.st_ino) + return failure("lock file changed while acquiring"); + + auto token = next_lock_token.load(std::memory_order_relaxed); + do { + if (token > static_cast( + (std::numeric_limits::max)())) + return failure("lock token space exhausted"); + } while (!next_lock_token.compare_exchange_weak(token, token + 1, + std::memory_order_relaxed)); + try { + descriptors_.emplace(static_cast(token), lock.get()); + } catch (const std::bad_alloc &) { + return failure("cannot track lock"); + } + lock.release(); + return {true, static_cast(token), {}}; +#endif +} + +AtomicFileWrite FileLockRegistry::release(std::int64_t token) { +#ifdef _WIN32 + (void)token; + return {false, "file.release_file_lock: unsupported platform"}; +#else + const auto found = descriptors_.find(token); + if (found == descriptors_.end()) + return {false, "file.release_file_lock: invalid lock token"}; + const int descriptor = found->second; + descriptors_.erase(found); + int status = -1; + do { + status = ::flock(descriptor, LOCK_UN); + } while (status != 0 && errno == EINTR); + // A failed close is uncertain and must not leave a reusable program token. + // Do not retry close after EINTR: some hosts already closed the descriptor. + const int closed = ::close(descriptor); + if (status != 0 || closed != 0) + return {false, "file.release_file_lock: release failed"}; + return {true, {}}; +#endif +} + +void FileLockRegistry::clear() noexcept { +#ifndef _WIN32 + for (const auto &entry : descriptors_) + ::close(entry.second); +#endif + descriptors_.clear(); +} + } // namespace ny::detail diff --git a/nilcompiler/src/secure_file_io.hpp b/nilcompiler/src/secure_file_io.hpp index 1db9bd2b..98789c9e 100644 --- a/nilcompiler/src/secure_file_io.hpp +++ b/nilcompiler/src/secure_file_io.hpp @@ -3,6 +3,7 @@ #include #include +#include #include #include @@ -19,6 +20,33 @@ struct AtomicFileWrite { std::string error; }; +struct FileLockResult { + bool ok = false; + std::int64_t token = 0; + std::string error; +}; + +// Registry ownership is the execution-context boundary. Tokens are process- +// monotonic and never recycled, and never expose the host descriptor. Locks +// are advisory; callers must control the directory ancestry and cooperate. +class FileLockRegistry { +public: + FileLockRegistry() = default; + ~FileLockRegistry() noexcept; + FileLockRegistry(const FileLockRegistry &) = delete; + FileLockRegistry &operator=(const FileLockRegistry &) = delete; + + // create=true exclusively creates a fresh private backing file; false + // requires an existing private regular file. Acquisition never blocks. + FileLockResult acquire(const std::string &path, bool create); + AtomicFileWrite release(std::int64_t token); + void clear() noexcept; + bool empty() const noexcept { return descriptors_.empty(); } + +private: + std::map descriptors_; +}; + bool valid_file_path(const std::string &path); bool valid_file_path(const std::filesystem::path &path); bool valid_file_path(const char *path); @@ -29,6 +57,13 @@ BoundedFileRead read_regular_file_bounded_utf8(const std::string &path, AtomicFileWrite write_file_atomic_utf8(const std::string &path, const std::vector &bytes, bool replace); +// POSIX only. Directory synchronization is explicit; durable publication +// synchronizes the same anchored directory used to publish the destination. +// An error after publication does not imply that the old destination remains. +AtomicFileWrite sync_directory_utf8(const std::string &path); +AtomicFileWrite write_file_durable_utf8(const std::string &path, + const std::vector &bytes, + bool replace); // Host callers retain the native path / legacy narrow-string contract. BoundedFileRead read_regular_file_bounded(const std::string &path, std::uint64_t maximum_bytes); diff --git a/nilcompiler/src/vm.cpp b/nilcompiler/src/vm.cpp index 5231c1f9..53c47b47 100644 --- a/nilcompiler/src/vm.cpp +++ b/nilcompiler/src/vm.cpp @@ -10,6 +10,7 @@ #include "nil_contract.hpp" #include "dynamic_type.hpp" #include "ui_intrinsic.hpp" +#include "ordinary_io_intrinsic.hpp" #include "numeric_literal.hpp" #include "scalar_text.hpp" #include "integer_conversion.hpp" @@ -723,7 +724,10 @@ int64_t invoke_native(void *fn_ptr, const std::vector &args) { VM::VM() : pc_(0) {} -VM::~VM() noexcept { closeOpenSockets(); } +VM::~VM() noexcept { + file_locks_.clear(); + closeOpenSockets(); +} void VM::beginMemoryProfile() { if (memory_profile_started_ || !memory_profile_allowed_) @@ -737,6 +741,7 @@ bool VM::finishMemoryProfile(const char *status, bool completed) noexcept { // This hook runs at every invocation terminal, even without profiling. // Paused debugger steps retain their UI until completion/reset. ui_.clear(); + file_locks_.clear(); closeOpenSockets(); if (!memory_profile_started_ || memory_profile_finished_) return true; @@ -1122,6 +1127,8 @@ void VM::validateCheckpointAdmission() const { throw std::runtime_error("VM checkpoints do not support memory profiling"); if (!file_handles_.empty()) throw std::runtime_error("VM checkpoints do not support open file handles"); + if (!file_locks_.empty()) + throw std::runtime_error("VM checkpoints do not support open file locks"); if (!socket_handles_.empty()) throw std::runtime_error("VM checkpoints do not support open sockets"); for (const auto &instruction : program_) { @@ -2749,6 +2756,31 @@ void VM::executeInstruction(const Instruction &instr) { "INTEROP_CALL " + lib_name + "::" + fn_name); const size_t result_base = stack_.size() - static_cast(arg_count); const bool returns_void = instr.args.size() > 3 && instr.args[3] == "void"; + if (lib_name == "intrinsic" && + (fn_name == "file.write_bytes_durable" || fn_name == "file.sync_directory" || + fn_name == "file.acquire_file_lock" || fn_name == "file.release_file_lock")) { + const auto contract = ordinary_io::intrinsic(fn_name); + const auto expected = "nil::std::core::Result<" + contract->payload + ",text>"; + bool valid = arg_count == static_cast(contract->parameters.size()) && + instr.args.size() == 4 && ui::abi_type(instr.args[3]) == expected; + std::size_t schemas = 0; + if (valid && class_metadata_) { + for (const auto &definition : class_metadata_->enums) { + if (ui::abi_type(definition.name) != expected) continue; + bool ok = false, error = false; + if (definition.variants.size() == 2) { + for (const auto &variant : definition.variants) { + if (variant.name == "Ok") ok = ui::abi_type(variant.associated_type) == contract->payload; + else if (variant.name == "Error") error = ui::abi_type(variant.associated_type) == "text"; + } + } + if (ok && error) ++schemas; + else valid = false; + } + } + if (!valid || schemas != 1) + throw std::runtime_error(fn_name + ": requires its checked result type and enum schema"); + } // Existing intrinsic handlers use both return and break. Funnel their // successful exits through one boundary so host status values cannot leak @@ -5247,8 +5279,46 @@ void VM::executeInstruction(const Instruction &instr) { push_ok(); return; } + if (fn_name == "file.sync_directory" || fn_name == "file.acquire_file_lock" || + fn_name == "file.release_file_lock") { + auto result = [&](bool ok, int64_t value, const std::string &error) { + EnumValue reply; + reply.variant_name = ok ? "Result::Ok" : "Result::Error"; + if (ok) reply.payloads.push_back(value); + else reply.payloads.push_back(error); + pushStack(reply); + }; + try { + if (fn_name == "file.release_file_lock") { + if (args.size() != 1 || !std::holds_alternative(args[0])) { + result(false, 0, fn_name + ": expected an i64 token"); + return; + } + const auto released = file_locks_.release(std::get(args[0])); + result(released.ok, 1, released.error); + return; + } + const bool acquire = fn_name == "file.acquire_file_lock"; + if (args.size() != (acquire ? 2 : 1) || !std::holds_alternative(args[0]) || + (acquire && (!std::holds_alternative(args[1]) || + (std::get(args[1]) != 0 && std::get(args[1]) != 1)))) { + result(false, 0, fn_name + ": invalid arguments"); + return; + } + if (acquire) { + const auto locked = file_locks_.acquire(std::get(args[0]), std::get(args[1]) != 0); + result(locked.ok, locked.token, locked.error); + } else { + const auto synced = detail::sync_directory_utf8(std::get(args[0])); + result(synced.ok, 1, synced.error); + } + } catch (...) { + result(false, 0, fn_name + ": host operation failed"); + } + return; + } // file.write_bytes_atomic(path, content, replace) -> result - if (fn_name == "file.write_bytes_atomic") { + if (fn_name == "file.write_bytes_atomic" || fn_name == "file.write_bytes_durable") { auto push_ok = [&]() { EnumValue result; result.variant_name = "Result::Ok"; @@ -5265,25 +5335,25 @@ void VM::executeInstruction(const Instruction &instr) { !std::holds_alternative(args[1]) || !std::holds_alternative(args[2])) { push_error( - "file.write_bytes_atomic: expected a text path, byte array, and bool replace"); + fn_name + ": expected a text path, byte array, and bool replace"); return; } const std::string &path = std::get(args[0]); if (!detail::valid_file_path(path)) { push_error( - "file.write_bytes_atomic: path must be non-empty and contain no NUL byte"); + fn_name + ": path must be non-empty and contain no NUL byte"); return; } const int64_t replace_value = std::get(args[2]); if (replace_value != 0 && replace_value != 1) { - push_error("file.write_bytes_atomic: replace must be a bool"); + push_error(fn_name + ": replace must be a bool"); return; } const int64_t handle = std::get(args[1]).address; const auto block = heap_.find(handle); if (block == heap_.end()) { - push_error("file.write_bytes_atomic: invalid byte array"); + push_error(fn_name + ": invalid byte array"); return; } std::vector bytes; @@ -5291,14 +5361,14 @@ void VM::executeInstruction(const Instruction &instr) { if (is_byte_heap_type(block->second.type_name)) { if (block->second.byte_data.size() > max_intrinsic_file_bytes) { push_error( - "file.write_bytes_atomic: byte array exceeds the 512 MiB safety limit"); + fn_name + ": byte array exceeds the 512 MiB safety limit"); return; } bytes = block->second.byte_data; } else if (block->second.type_name == "array") { if (block->second.data.size() > max_intrinsic_file_bytes) { push_error( - "file.write_bytes_atomic: array exceeds the 512 MiB safety limit"); + fn_name + ": array exceeds the 512 MiB safety limit"); return; } bytes.reserve(block->second.data.size()); @@ -5306,26 +5376,28 @@ void VM::executeInstruction(const Instruction &instr) { const auto *integer = std::get_if(&value); if (integer == nullptr || *integer < 0 || *integer > 255) { push_error( - "file.write_bytes_atomic: array contains a value outside u8"); + fn_name + ": array contains a value outside u8"); return; } bytes.push_back( static_cast(static_cast(*integer))); } } else { - push_error("file.write_bytes_atomic: value is not a byte array"); + push_error(fn_name + ": value is not a byte array"); return; } } catch (const std::bad_alloc &) { - push_error("file.write_bytes_atomic: allocation failed"); + push_error(fn_name + ": allocation failed"); return; } detail::AtomicFileWrite written; try { - written = detail::write_file_atomic_utf8(path, bytes, replace_value != 0); + written = fn_name == "file.write_bytes_durable" + ? detail::write_file_durable_utf8(path, bytes, replace_value != 0) + : detail::write_file_atomic_utf8(path, bytes, replace_value != 0); } catch (...) { - push_error("file.write_bytes_atomic: host operation failed"); + push_error(fn_name + ": host operation failed"); return; } if (!written.ok) { diff --git a/nilcompiler/src/vm.hpp b/nilcompiler/src/vm.hpp index 2f7db71c..e906e942 100644 --- a/nilcompiler/src/vm.hpp +++ b/nilcompiler/src/vm.hpp @@ -18,6 +18,7 @@ #include "database_runtime.hpp" #include "ui_runtime.hpp" #include "memory_profile.hpp" +#include "secure_file_io.hpp" namespace ny { @@ -612,6 +613,7 @@ class VM { }; std::unordered_map file_handles_; int64_t next_file_handle_ = 1; + detail::FileLockRegistry file_locks_; // Sockets follow the same rule as streams: a NIL program is given a token, // never a host descriptor, so it cannot read from or close something it was diff --git a/nilstd/src/io/file.ny b/nilstd/src/io/file.ny index c1058272..5248e9db 100644 --- a/nilstd/src/io/file.ny +++ b/nilstd/src/io/file.ny @@ -64,6 +64,35 @@ pub fn write_bytes(path: text, content: array) -> Result @intrinsic("file.write_bytes_atomic") pub fn write_bytes_atomic(path: text, content: array, replace: bool) -> Result +# POSIX durability: atomic byte publication plus synchronization of the same +# parent-directory handle used for publication. Existing atomic-write semantics +# remain unchanged. A failure after publication is an uncertain outcome: the +# destination may already contain the new bytes. Stop and recover before retry. +# Unsupported platforms return Error before filesystem mutation. Parent ancestry +# must be trusted; this is not encryption or a filesystem/device guarantee. +@intrinsic("file.write_bytes_durable") +pub fn write_bytes_durable(path: text, content: array, replace: bool) -> Result + +# Synchronize an existing directory. POSIX-only, no-follow final component; +# ancestors are trusted. Errors do not include the supplied path. +@intrinsic("file.sync_directory") +pub fn sync_directory(path: text) -> Result + +# Acquire a nonblocking exclusive advisory lock. create=true exclusively creates +# a new 0600 backing file; false opens an existing private, singly-linked regular +# file owned by the effective user. The runtime returns a context-owned token, +# never a descriptor. Invocation completion closes remaining locks. The backing +# file remains present after release; do not unlink or replace it while used. +# Lock creation does not synchronize its parent; call sync_directory as needed. +# POSIX-only, fails closed elsewhere. All writers must follow the same protocol. +@intrinsic("file.acquire_file_lock") +pub fn acquire_file_lock(path: text, create: bool) -> Result + +# Release only a live token owned by this execution context. Stale, foreign, and +# repeated-release tokens fail. Tokens are not reused during runtime lifetime. +@intrinsic("file.release_file_lock") +pub fn release_file_lock(token: i64) -> Result + # Append text to a file @intrinsic("file.append_text") pub fn append_text(path: text, content: text) -> Result diff --git a/nilstd/src/io/package.ny b/nilstd/src/io/package.ny index 095309a4..acf00f9c 100644 --- a/nilstd/src/io/package.ny +++ b/nilstd/src/io/package.ny @@ -8,6 +8,7 @@ # - Console I/O: write, writeln, read_line, write_error, flush (console.ny) # - File: checked whole-file operations, bounded regular-file input, atomic # byte publication, and opaque-handle streams (file.ny) +# - POSIX durable publication, directory synchronization, context-owned locks # - Stream: Read/Write/Seek/Close traits and checked stream_copy (stream.ny) # - Path: lexical path inspection and transformation (path.ny) # - Binary: bounded little/big-endian byte-array reads and writes (binary.ny) diff --git a/nilstd/src/text/string_utils.ny b/nilstd/src/text/string_utils.ny index 7c59ee50..df715abe 100644 --- a/nilstd/src/text/string_utils.ny +++ b/nilstd/src/text/string_utils.ny @@ -819,5 +819,7 @@ pub fn byte_at(s: text, index: i64) -> i64 # character can be built one byte at a time with this. # # A code outside 0..255 gives empty text. +# Native execution uses NUL-free text: code 0 faults explicitly rather than +# silently returning truncated text. Use byte arrays for arbitrary binary data. @intrinsic("text.from_byte") pub fn from_byte(code: i64) -> text diff --git a/tests/durable_file_io_tests.cpp b/tests/durable_file_io_tests.cpp new file mode 100644 index 00000000..0f1ee80d --- /dev/null +++ b/tests/durable_file_io_tests.cpp @@ -0,0 +1,455 @@ +#include "../nilcompiler/src/secure_file_io.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(__unix__) || defined(__APPLE__) +#include +#include +#include +#include +#include +#include +#include +#include +#include +#endif + +#if defined(__linux__) && defined(NIL_TEST_WRAP_FSYNC) && NIL_TEST_WRAP_FSYNC +namespace { +// This seam exists only in the Linux test executable. Production helpers have +// no fault switch, environment override, or alternate synchronization path. +enum class sync_fault { none, directory, regular }; +std::atomic pending_sync_fault{sync_fault::none}; +} + +extern "C" int __real_fsync(int descriptor); +extern "C" int __wrap_fsync(int descriptor) { + struct stat metadata {}; + if (::fstat(descriptor, &metadata) == 0) { + auto selected = S_ISDIR(metadata.st_mode) ? sync_fault::directory + : S_ISREG(metadata.st_mode) ? sync_fault::regular + : sync_fault::none; + if (selected != sync_fault::none && + pending_sync_fault.compare_exchange_strong(selected, sync_fault::none)) { + errno = EIO; + return -1; + } + } + return __real_fsync(descriptor); +} +#endif + +namespace { +namespace fs = std::filesystem; +using ny::detail::FileLockRegistry; + +void require(bool condition, const std::string &message) { + if (!condition) throw std::runtime_error(message); +} + +template +void require_error(const Result &result, const std::string &private_marker) { + require(!result.ok, "unsafe operation unexpectedly succeeded"); + require(!result.error.empty(), "operation failed without a diagnostic"); + require(result.error.find(private_marker) == std::string::npos, + "error disclosed a supplied private path"); +} + +class fixture { +public: + fixture() { +#if defined(__unix__) || defined(__APPLE__) + std::string pattern = (fs::temp_directory_path() / "nil-durable-io-XXXXXX").string(); + std::vector writable(pattern.begin(), pattern.end()); + writable.push_back('\0'); + const auto directory = ::mkdtemp(writable.data()); + require(directory != nullptr, "cannot create private durability fixture"); + root = fs::absolute(directory); +#else + const auto stamp = std::chrono::steady_clock::now().time_since_epoch().count(); + root = fs::temp_directory_path() / ("nil-durable-io-" + std::to_string(stamp)); + require(fs::create_directory(root), "cannot create durability fixture"); +#endif + } + ~fixture() { + std::error_code ignored; + fs::remove_all(root, ignored); + } + fs::path root; +}; + +std::string read_bytes(const fs::path &path) { + require(fs::file_size(path) <= 4096, "unexpectedly large fixture file"); + std::ifstream input(path, std::ios::binary); + require(static_cast(input), "cannot read fixture file"); + return {std::istreambuf_iterator(input), std::istreambuf_iterator()}; +} + +void write_bytes(const fs::path &path, const std::string &content) { + std::ofstream output(path, std::ios::binary | std::ios::trunc); + require(static_cast(output), "cannot create fixture file"); + output.write(content.data(), static_cast(content.size())); + output.close(); + require(static_cast(output), "cannot finish fixture write"); +#if defined(__unix__) || defined(__APPLE__) + require(::chmod(path.c_str(), 0600) == 0, "cannot secure fixture file"); +#endif +} + +#if defined(__unix__) || defined(__APPLE__) +class child_guard { +public: + explicit child_guard(pid_t child) : child_(child) {} + ~child_guard() { + if (child_ > 0) { + ::kill(child_, SIGKILL); + int status = 0; + while (::waitpid(child_, &status, 0) < 0 && errno == EINTR) {} + } + } + + int wait() { + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5); + while (std::chrono::steady_clock::now() < deadline) { + int status = 0; + const auto observed = ::waitpid(child_, &status, WNOHANG); + if (observed == child_) { + child_ = -1; + return status; + } + require(observed == 0 || (observed < 0 && errno == EINTR), + "cannot observe child process"); + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } + throw std::runtime_error("durability child exceeded its deadline"); + } + +private: + pid_t child_; +}; + +template +void in_bounded_child(Function function) { + const auto child = ::fork(); + require(child >= 0, "cannot fork durability fixture"); + if (child == 0) { + try { + function(); + ::_exit(0); + } catch (...) { + ::_exit(1); + } + } + child_guard owner(child); + const auto status = owner.wait(); + require(WIFEXITED(status) && WEXITSTATUS(status) == 0, + "durability child contract failed"); +} + +void check_directory_sync(const fs::path &root) { + const auto synced = ny::detail::sync_directory_utf8(root.u8string()); + require(synced.ok && synced.error.empty(), "directory synchronization failed"); + const auto missing = root / "private-sync-marker-missing"; + require_error(ny::detail::sync_directory_utf8(missing.u8string()), "private-sync-marker"); + const auto regular = root / "private-sync-marker-file"; + write_bytes(regular, "retained"); + require_error(ny::detail::sync_directory_utf8(regular.u8string()), "private-sync-marker"); + const auto linked = root / "private-sync-marker-link"; + fs::create_directory_symlink(root, linked); + require_error(ny::detail::sync_directory_utf8(linked.u8string()), "private-sync-marker"); + require_error(ny::detail::sync_directory_utf8(""), "private-sync-marker"); + require_error(ny::detail::sync_directory_utf8(std::string("private-sync-marker\0tail", 24)), + "private-sync-marker"); + require_error(ny::detail::sync_directory_utf8(root.u8string() + "/private-sync-marker-" + '\xff'), + "private-sync-marker"); + require(read_bytes(regular) == "retained", "failed synchronization changed file contents"); +} + +void check_durable_publication(const fs::path &root) { + const auto target = root / "checkpoint-caf\xc3\xa9.bin"; + const std::vector first{0, '\n', '\r', static_cast(0x80), static_cast(0xff)}; + auto created = ny::detail::write_file_durable_utf8(target.u8string(), first, false); + require(created.ok && created.error.empty(), "durable no-clobber write failed"); + require(read_bytes(target) == std::string(first.begin(), first.end()), "durable bytes changed"); + struct stat metadata {}; + require(::stat(target.c_str(), &metadata) == 0 && (metadata.st_mode & 0777) == 0600, + "durable publication did not create a private inode"); + const std::vector next{'n', 'e', 'x', 't'}; + require_error(ny::detail::write_file_durable_utf8(target.u8string(), next, false), "checkpoint-caf"); + require(read_bytes(target) == std::string(first.begin(), first.end()), "no-clobber replaced existing bytes"); + const auto alias = root / "old-checkpoint-alias"; + fs::create_hard_link(target, alias); + require(::chmod(target.c_str(), 0644) == 0, "cannot widen replacement fixture mode"); + const auto replaced = ny::detail::write_file_durable_utf8(target.u8string(), next, true); + require(replaced.ok, "durable replacement failed"); + require(read_bytes(target) == "next", "durable replacement did not publish new bytes"); + require(read_bytes(alias) == std::string(first.begin(), first.end()), "replacement mutated an old hardlink"); + require(::stat(target.c_str(), &metadata) == 0 && (metadata.st_mode & 0777) == 0600 && metadata.st_nlink == 1, + "durable replacement did not publish a fresh private inode"); + require(ny::detail::write_file_durable_utf8(target.u8string(), {}, true).ok, + "empty durable replacement failed"); + require(read_bytes(target).empty(), "empty durable publication retained old contents"); + const auto absent = root / "replace-absent"; + require(ny::detail::write_file_durable_utf8(absent.u8string(), next, true).ok, + "durable replacement could not create an absent destination"); + + const auto sentinel = root / "private-write-marker-sentinel"; + write_bytes(sentinel, "must remain unchanged"); + const auto symlink = root / "private-write-marker-symlink"; + fs::create_symlink(sentinel, symlink); + for (const auto replace : {false, true}) { + require_error(ny::detail::write_file_durable_utf8(symlink.u8string(), next, replace), "private-write-marker"); + require(read_bytes(sentinel) == "must remain unchanged", "durable write followed a destination symlink"); + } + const auto fifo = root / "private-write-marker-fifo"; + require(::mkfifo(fifo.c_str(), 0600) == 0, "cannot create durable FIFO fixture"); + in_bounded_child([&] { + require_error(ny::detail::write_file_durable_utf8(fifo.u8string(), next, true), "private-write-marker"); + }); + require_error(ny::detail::write_file_durable_utf8(root.u8string(), next, true), root.u8string()); + require_error(ny::detail::write_file_durable_utf8("", next, false), "private-write-marker"); + const auto bad_utf8 = root.u8string() + "/private-write-marker-" + '\xff'; + require_error(ny::detail::write_file_durable_utf8(bad_utf8, next, false), "private-write-marker"); + auto nul_path = (root / "private-write-marker-nul").u8string(); + nul_path += std::string("\0tail", 5); + require_error(ny::detail::write_file_durable_utf8(nul_path, next, false), "private-write-marker"); + require(!fs::exists(root / "private-write-marker-nul"), "NUL path was truncated into a created file"); + for (const auto &entry : fs::directory_iterator(root)) + require(entry.path().filename().string().rfind(".ny-write-", 0) != 0, + "durable publication left a staging file behind"); +} + +#if defined(__linux__) && defined(NIL_TEST_WRAP_FSYNC) && NIL_TEST_WRAP_FSYNC +class sync_fault_scope { +public: + explicit sync_fault_scope(sync_fault selected) { + pending_sync_fault.store(selected); + } + ~sync_fault_scope() { pending_sync_fault.store(sync_fault::none); } +}; + +void check_synchronization_failures(const fs::path &root) { + const std::vector candidate{'c', 'a', 'n', 'd', 'i', 'd', 'a', 't', 'e'}; + for (const auto replace : {false, true}) { + const auto target = root / (replace ? "private-sync-fault-replace" : "private-sync-fault-create"); + if (replace) write_bytes(target, "previous"); + sync_fault_scope fault(sync_fault::directory); + const auto result = ny::detail::write_file_durable_utf8(target.u8string(), candidate, replace); + require_error(result, "private-sync-fault"); + require(result.error == "file.write_bytes_durable: publication durability uncertain", + "post-publication failure did not identify uncertain durability"); + require(pending_sync_fault.load() == sync_fault::none, + "durable publication did not reach its directory barrier"); + require(read_bytes(target) == "candidate", + "uncertain publication incorrectly restored or hid the visible candidate"); + } + + const auto legacy_path = root / "private-sync-fault-legacy"; + { + sync_fault_scope fault(sync_fault::directory); + const auto legacy = ny::detail::write_file_atomic_utf8(legacy_path.u8string(), candidate, false); + require(legacy.ok && legacy.error.empty(), "visibility-only atomic write changed its flush semantics"); + require(pending_sync_fault.load() == sync_fault::directory, + "visibility-only atomic write unexpectedly synchronized its directory"); + require(read_bytes(legacy_path) == "candidate", "legacy atomic write failed to publish candidate bytes"); + const auto directory = ny::detail::sync_directory_utf8(root.u8string()); + require_error(directory, root.u8string()); + require(directory.error == "file.sync_directory: synchronization failed", + "standalone directory sync did not report its fixed synchronization failure"); + require(pending_sync_fault.load() == sync_fault::none, + "standalone directory sync did not consume the selected fault"); + } + + const auto target = root / "private-sync-fault-staging"; + write_bytes(target, "previous"); + { + sync_fault_scope fault(sync_fault::regular); + const auto result = ny::detail::write_file_durable_utf8(target.u8string(), candidate, true); + require_error(result, "private-sync-fault"); + require(result.error == "file.write_bytes_durable: staging flush failed", + "pre-publication failure did not report its staging barrier"); + require(pending_sync_fault.load() == sync_fault::none, + "staging write did not reach its regular-file barrier"); + require(read_bytes(target) == "previous", "failed staging sync changed the canonical destination"); + } + for (const auto &entry : fs::directory_iterator(root)) + require(entry.path().filename().string().rfind(".ny-write-", 0) != 0, + "failed staging synchronization left a temporary file"); + require(ny::detail::sync_directory_utf8(root.u8string()).ok, + "one-shot test fault remained active after its selected failure"); +} +#endif + +void check_lock_lifecycle(const fs::path &root) { + const auto path = root / "writer.lock"; + FileLockRegistry first; + FileLockRegistry second; + require(first.empty() && second.empty(), "new lock registry is not empty"); + const auto held = first.acquire(path.u8string(), true); + require(held.ok && held.token > 0 && held.error.empty(), "cannot create and acquire a private lock"); + require(!first.empty(), "held lock was not retained by its registry"); + struct stat metadata {}; + require(::stat(path.c_str(), &metadata) == 0 && (metadata.st_mode & 0777) == 0600 && metadata.st_nlink == 1, + "lock creation did not retain a private regular file"); + require_error(first.acquire(path.u8string(), true), "writer.lock"); + require_error(first.acquire(path.u8string(), false), "writer.lock"); + require_error(second.acquire(path.u8string(), false), "writer.lock"); + require_error(second.release(held.token), "writer.lock"); + require(!first.empty() && second.empty(), "wrong registry changed a live lock"); + in_bounded_child([&] { + FileLockRegistry child_registry; + require_error(child_registry.acquire(path.u8string(), false), "writer.lock"); + }); + require(first.release(held.token).ok, "lock release failed"); + require(first.empty(), "released lock remains in registry"); + require_error(first.release(held.token), "writer.lock"); + require_error(first.release(0), "writer.lock"); + require_error(first.release(-1), "writer.lock"); + const auto next = second.acquire(path.u8string(), false); + require(next.ok && next.token != held.token, "lock token was recycled after release"); + second.clear(); + require(second.empty(), "clear did not release registry locks"); + require_error(second.release(next.token), "writer.lock"); + const auto after_clear = first.acquire(path.u8string(), false); + require(after_clear.ok && after_clear.token != next.token && after_clear.token != held.token, + "lock token was recycled after registry clear"); + first.clear(); + const auto other = root / "destructor.lock"; + std::int64_t destroyed_token = 0; + { + FileLockRegistry transient; + const auto acquired = transient.acquire(other.u8string(), true); + require(acquired.ok, "cannot acquire destructor fixture lock"); + destroyed_token = acquired.token; + } + const auto after_destructor = second.acquire(other.u8string(), false); + require(after_destructor.ok && after_destructor.token != destroyed_token, + "registry destruction did not release lock or recycled its token"); + require_error(second.release(destroyed_token), "destructor.lock"); + second.clear(); +} + +void check_unsafe_locks(const fs::path &root) { + FileLockRegistry registry; + const auto missing = root / "private-lock-marker-missing"; + require_error(registry.acquire(missing.u8string(), false), "private-lock-marker"); + require(!fs::exists(missing), "open-existing lock silently initialized a missing file"); + const auto target = root / "private-lock-marker-target"; + write_bytes(target, "sentinel"); + const auto alias = root / "private-lock-marker-hardlink"; + fs::create_hard_link(target, alias); + require_error(registry.acquire(target.u8string(), false), "private-lock-marker"); + require_error(registry.acquire(alias.u8string(), false), "private-lock-marker"); + fs::remove(alias); + const auto link = root / "private-lock-marker-symlink"; + fs::create_symlink(target, link); + require_error(registry.acquire(link.u8string(), false), "private-lock-marker"); + require_error(registry.acquire(link.u8string(), true), "private-lock-marker"); + require(::chmod(target.c_str(), 0644) == 0, "cannot widen unsafe lock fixture mode"); + require_error(registry.acquire(target.u8string(), false), "private-lock-marker"); + require(::chmod(target.c_str(), 0600) == 0, "cannot restore lock fixture mode"); + require_error(registry.acquire(root.u8string(), false), root.u8string()); + const auto fifo = root / "private-lock-marker-fifo"; + require(::mkfifo(fifo.c_str(), 0600) == 0, "cannot create lock FIFO fixture"); + in_bounded_child([&] { + FileLockRegistry child_registry; + require_error(child_registry.acquire(fifo.u8string(), false), "private-lock-marker"); + }); + require_error(registry.acquire("", true), "private-lock-marker"); + require_error(registry.acquire(root.u8string() + "/private-lock-marker-" + '\xff', true), "private-lock-marker"); + auto nul_path = (root / "private-lock-marker-nul").u8string(); + nul_path += std::string("\0tail", 5); + require_error(registry.acquire(nul_path, true), "private-lock-marker"); + require(!fs::exists(root / "private-lock-marker-nul"), "NUL lock path was truncated into a created file"); + require(registry.empty(), "rejected lock operation retained a live descriptor"); + require(read_bytes(target) == "sentinel", "rejected lock operation changed fixture bytes"); +} + +void check_process_death_cleanup(const fs::path &root) { + const auto path = root / "process-death.lock"; + write_bytes(path, ""); + int ready[2] = {-1, -1}; + require(::pipe(ready) == 0, "cannot create bounded lock coordination pipe"); + const auto child = ::fork(); + if (child < 0) { + ::close(ready[0]); + ::close(ready[1]); + throw std::runtime_error("cannot fork lock owner"); + } + if (child == 0) { + ::close(ready[0]); + FileLockRegistry registry; + const auto held = registry.acquire(path.u8string(), false); + const char marker = held.ok ? '1' : '0'; + if (::write(ready[1], &marker, 1) != 1 || !held.ok) ::_exit(2); + ::close(ready[1]); + for (;;) ::pause(); + } + child_guard owner(child); + ::close(ready[1]); + pollfd waiting{ready[0], POLLIN, 0}; + int observed = -1; + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5); + do { + const auto remaining = std::chrono::duration_cast( + deadline - std::chrono::steady_clock::now()).count(); + if (remaining <= 0) break; + observed = ::poll(&waiting, 1, static_cast(remaining)); + } while (observed < 0 && errno == EINTR); + char marker = '0'; + const auto count = observed > 0 ? ::read(ready[0], &marker, 1) : 0; + ::close(ready[0]); + require(observed > 0 && count == 1 && marker == '1', "child did not acquire its lock within deadline"); + FileLockRegistry parent_registry; + require_error(parent_registry.acquire(path.u8string(), false), "process-death.lock"); + require(::kill(child, SIGKILL) == 0, "cannot terminate child lock owner"); + const auto status = owner.wait(); + require(WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL, "lock owner did not die as expected"); + const auto acquired = parent_registry.acquire(path.u8string(), false); + require(acquired.ok, "process death did not release the operating-system lock"); + require(parent_registry.release(acquired.token).ok, "cannot release post-crash lock"); +} +#else +void check_unsupported_host(const fs::path &root) { + const auto target = root / "private-unsupported-marker"; + require_error(ny::detail::sync_directory_utf8(root.u8string()), "private-unsupported-marker"); + require_error(ny::detail::write_file_durable_utf8(target.u8string(), {'x'}, false), "private-unsupported-marker"); + FileLockRegistry registry; + require_error(registry.acquire(target.u8string(), true), "private-unsupported-marker"); + require(registry.empty() && !fs::exists(target), "unsupported host mutated its namespace"); +} +#endif +} // namespace + +int main() { + try { + fixture owned; +#if defined(__unix__) || defined(__APPLE__) + check_directory_sync(owned.root); + check_durable_publication(owned.root); +#if defined(__linux__) && defined(NIL_TEST_WRAP_FSYNC) && NIL_TEST_WRAP_FSYNC + check_synchronization_failures(owned.root); +#endif + check_lock_lifecycle(owned.root); + check_unsafe_locks(owned.root); + check_process_death_cleanup(owned.root); +#else + check_unsupported_host(owned.root); +#endif + std::cout << "durable-file-io-ok\n"; + return 0; + } catch (const std::exception &error) { + std::cerr << "durable-file-io: " << error.what() << '\n'; + return 1; + } +} diff --git a/tests/durable_vm_lifecycle_tests.cpp b/tests/durable_vm_lifecycle_tests.cpp new file mode 100644 index 00000000..c52a1f75 --- /dev/null +++ b/tests/durable_vm_lifecycle_tests.cpp @@ -0,0 +1,231 @@ +// A lock must leave the actual operating system when its embedded VM invocation +// ends; process-exit cleanup alone is not sufficient for native embedding. +#include "codegen.hpp" +#include "nil_loader.hpp" +#include "secure_file_io.hpp" +#include "vm.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(__unix__) || defined(__APPLE__) +#include +#include +#endif + +namespace { +namespace fs = std::filesystem; +unsigned checks = 0; + +void require(bool condition, const std::string &message) { + ++checks; + if (!condition) throw std::runtime_error(message); +} + +class fixture_directory { +public: + fixture_directory() { +#if defined(__unix__) || defined(__APPLE__) + const auto pattern = (fs::temp_directory_path() / "nil-durable-vm-XXXXXX").string(); + std::vector writable(pattern.begin(), pattern.end()); + writable.push_back('\0'); + const auto directory = ::mkdtemp(writable.data()); + require(directory != nullptr, "cannot create private VM lock fixture"); + root = fs::absolute(directory); + lock = root / "invocation.lock"; + std::ofstream output(lock, std::ios::binary); + output.close(); + require(static_cast(output) && ::chmod(lock.c_str(), 0600) == 0, + "cannot create private VM lock file"); +#endif + } + ~fixture_directory() { + if (!root.empty()) { + std::error_code ignored; + fs::remove_all(root, ignored); + } + } + fs::path root; + fs::path lock; +}; + +const std::string token_result = "nil::std::core::Result"; +const std::string bool_result = "nil::std::core::Result"; + +ny::nil_function function(std::string name, std::vector parameters, + std::string result, std::vector body) { + ny::nil_function declaration; + declaration.name = std::move(name); + declaration.params = std::move(parameters); + declaration.return_type = std::move(result); + declaration.body = std::move(body); + return declaration; +} + +struct Program { + std::vector code; + std::unordered_map constants; +}; + +Program fixture(const fs::path &path, bool binary, bool fault) { + ny::nil_module module; + module.module_name = "durable_vm_lifecycle"; + module.enums = {{token_result, {{"Ok", "i64"}, {"Error", "text"}}}, + {bool_result, {{"Ok", "bool"}, {"Error", "text"}}}}; + module.string_constants = {{"lock_path", path.u8string()}}; + std::vector body{ + {"PUSH_CONST_STR", {"lock_path"}}, {"PUSH_CONST", {"0"}}, {"CAST", {"bool"}}, + {"INTEROP_CALL", {"intrinsic", "file.acquire_file_lock", "2", token_result}}, + {"UNWRAP_VARIANT", {"1", token_result, "i64"}}, + {"STORE_GLOBAL", {"opened", "i64"}}}; + if (fault) { + body.push_back({"PUSH_CONST", {"1"}}); + body.push_back({"PUSH_CONST", {"0"}}); + body.push_back({"DIV", {"i64"}}); + } else { + body.push_back({"PUSH_CONST", {"0"}}); + } + body.push_back({"RET", {}}); + module.functions.push_back(function("main", {}, "i64", std::move(body))); + module.functions.push_back(function("release", {"token:i64"}, bool_result, + {{"STORE_LOCAL", {"token"}}, {"LOAD_LOCAL", {"token"}}, + {"INTEROP_CALL", {"intrinsic", "file.release_file_lock", "1", bool_result}}, + {"RET", {}}})); + std::ostringstream serialized(std::ios::out | std::ios::binary); + if (binary) { + ny::codegen_options options; + ny::nil_binary_writer writer(serialized, options); + writer.emit_binary_module(module); + } else { + ny::nil_writer writer(serialized); + writer.emit_text_module(module); + } + std::istringstream input(serialized.str(), std::ios::in | std::ios::binary); + Program program; + program.code = binary ? ny::parseBinaryProgram(input, program.constants) + : ny::parseProgram(input, program.constants); + return program; +} + +void endpoint(const fs::path &path, bool held, const std::string &phase) { + ny::detail::FileLockRegistry external; + const auto probe = external.acquire(path.u8string(), false); + require(probe.ok != held, phase + (held ? " released its actual lock early" + : " retained its actual operating-system lock")); + if (held) + require(probe.error.find("lock is busy") != std::string::npos, + phase + " failed for an unrelated filesystem reason"); +} + +std::int64_t pause(ny::VM &vm, const Program &program, const fs::path &path) { + vm.loadProgram(program.code, program.constants); + vm.resetExecution("main"); + for (int step = 0; step < 50 && !vm.hasGlobal("opened"); ++step) + require(vm.stepInstruction(), "invocation did not reach its lock"); + require(vm.hasGlobal("opened"), "fixture did not retain its lock token"); + const auto token = std::get(vm.getGlobal("opened")); + require(token > 0, "lock token must be positive"); + endpoint(path, true, "paused invocation"); + return token; +} + +void stale(ny::VM &vm, std::int64_t token) { + vm.pushValue(token); + vm.callFunction("release", 1); + require(!vm.getStack().empty(), "release did not return a checked result"); + const auto &result = std::get(vm.getStack().back()); + require(result.variant_name == "Result::Error", "foreign or terminal token was accepted"); + require(result.payloads.size() == 1 && + std::get(result.payloads.front()) == + "file.release_file_lock: invalid lock token", + "stale token did not report its exact checked failure"); +} + +void lifecycle(const fs::path &path, bool binary) { + const auto normal = fixture(path, binary, false); + const auto faulty = fixture(path, binary, true); + ny::VM vm; + const auto first = pause(vm, normal, path); + bool checkpoint_rejected = false; + try { + (void)vm.createCheckpoint(); + } catch (const std::runtime_error &error) { + checkpoint_rejected = std::string(error.what()) == + "VM checkpoints do not support open file locks"; + } + require(checkpoint_rejected, "paused checkpoint was not rejected specifically for its open lock"); + endpoint(path, true, "rejected checkpoint"); + { + ny::VM foreign; + foreign.loadProgram(normal.code, normal.constants); + stale(foreign, first); + endpoint(path, true, "foreign VM release attempt"); + } + vm.execute(false); + endpoint(path, false, "normal completion"); + stale(vm, first); + + const auto second = pause(vm, normal, path); + require(second > first, "later invocation recycled a completed token"); + vm.resetExecution("main"); + endpoint(path, false, "debugger reset"); + // Reset prepares a new main frame. Replacing it before another host call + // keeps this test within the embedding API's existing frame contract. + vm.loadProgram(normal.code, normal.constants); + stale(vm, second); + + const auto third = pause(vm, normal, path); + require(third > second, "reset invocation recycled a token"); + vm.loadProgram(normal.code, normal.constants); + endpoint(path, false, "program replacement"); + stale(vm, third); + + const auto fourth = pause(vm, faulty, path); + require(fourth > third, "faulting invocation recycled a token"); + bool failed = false; + try { + vm.execute(false); + } catch (const std::runtime_error &error) { + failed = std::string(error.what()).find("Division by zero") != std::string::npos; + } + require(failed, "fault fixture did not execute its intended runtime error"); + endpoint(path, false, "failed invocation"); + vm.loadProgram(normal.code, normal.constants); + stale(vm, fourth); + + std::int64_t destroyed_token = 0; + { + auto owned = std::make_unique(); + destroyed_token = pause(*owned, normal, path); + owned.reset(); + } + endpoint(path, false, "paused VM destruction"); + ny::VM replacement; + replacement.loadProgram(normal.code, normal.constants); + stale(replacement, destroyed_token); +} +} // namespace + +int main() { + try { +#if defined(__unix__) || defined(__APPLE__) + fixture_directory owned; + lifecycle(owned.lock, false); + lifecycle(owned.lock, true); +#endif + std::cout << "Durable VM lifecycle: " << checks << " checks passed\n"; + return 0; + } catch (const std::exception &error) { + std::cerr << "Durable VM lifecycle failure: " << error.what() << '\n'; + return 1; + } +} diff --git a/tests/language/durable-file-io-invalid-owner.ny b/tests/language/durable-file-io-invalid-owner.ny new file mode 100644 index 00000000..6b8cada1 --- /dev/null +++ b/tests/language/durable-file-io-invalid-owner.ny @@ -0,0 +1,18 @@ +module nil.tests.durable_invalid_owner + +enum Result + Ok(T) + Error(E) +end enum + +@intrinsic("file.sync_directory") +fn wrong_sync(path: text) -> Result +end fn + +fn main() -> i32 + match wrong_sync(".") + Result.Ok(_) -> return 1 + Result.Error(_) -> return 0 + end match + return 0 +end fn diff --git a/tests/language/durable-file-io-invalid-width.ny b/tests/language/durable-file-io-invalid-width.ny new file mode 100644 index 00000000..66897400 --- /dev/null +++ b/tests/language/durable-file-io-invalid-width.ny @@ -0,0 +1,11 @@ +module nil.tests.durable_invalid_width +import nil.std.core + +@intrinsic("file.acquire_file_lock") +fn wrong_lock(path: text, create: bool) -> Result +end fn + +fn main() -> i32 + if wrong_lock("must-not-exist.lock", true).is_ok() then return 1 end if + return 0 +end fn diff --git a/tests/language/durable-file-io.ny b/tests/language/durable-file-io.ny new file mode 100644 index 00000000..f996650e --- /dev/null +++ b/tests/language/durable-file-io.ny @@ -0,0 +1,51 @@ +# Shared public durability and lock contract, paired with the Matrix fixture. +module nil.tests.durable_file_io +import nil.std.core +import nil.std.io +import nil.std.system +import nil.std.text + +fn main() -> i32 + if nil::std::system::arg_count() != 1 then return 64 end if + if nil::std::text::byte_at("é", 0) != 195 then return 20 end if + if nil::std::text::byte_at("é", 1) != 169 then return 21 end if + if nil::std::text::byte_at("é", -1) != -1 then return 22 end if + if nil::std::text::byte_at("é", 2) != -1 then return 23 end if + if nil::std::text::from_byte(195) + nil::std::text::from_byte(169) != "é" then return 24 end if + if nil::std::text::from_byte(-1) != "" or nil::std::text::from_byte(256) != "" then return 25 end if + let root = nil::std::system::arg(0) + let output = root + "/checkpoint.bin" + let lock = root + "/writer.lock" + let first: array = [0 as u8, 10 as u8, 13 as u8, 128 as u8, 255 as u8] + let second: array = [255 as u8, 0 as u8, 1 as u8] + let empty: array = [] + if not nil::std::io::write_bytes_durable(output, first, false).is_ok() then return 1 end if + if nil::std::io::write_bytes_durable(output, second, false).is_ok() then return 2 end if + match nil::std::io::read_bytes(output) + Result.Error(_) -> return 3 + Result.Ok(bytes) -> + if bytes.len() != 5 or bytes[0] != 0 as u8 or bytes[4] != 255 as u8 then return 4 end if + end match + if not nil::std::io::write_bytes_durable(output, second, true).is_ok() then return 5 end if + if not nil::std::io::write_bytes_durable(root + "/empty.bin", empty, false).is_ok() then return 6 end if + if not nil::std::io::sync_directory(root).is_ok() then return 7 end if + if nil::std::io::sync_directory(output).is_ok() then return 8 end if + println("durable-write-ok") + + let acquired = nil::std::io::acquire_file_lock(lock, true) + if acquired.is_error() then return 10 end if + let token = acquired.unwrap() + if token <= 0 then return 11 end if + if nil::std::io::acquire_file_lock(lock, false).is_ok() then return 12 end if + if nil::std::io::release_file_lock(0).is_ok() then return 13 end if + if not nil::std::io::release_file_lock(token).is_ok() then return 14 end if + if nil::std::io::release_file_lock(token).is_ok() then return 15 end if + let again = nil::std::io::acquire_file_lock(lock, false) + if again.is_error() then return 16 end if + if again.unwrap() <= token then return 17 end if + # Deliberately retain this lock until invocation completion. The host oracle + # independently acquires the backing file after every execution route. + if not nil::std::io::sync_directory(root).is_ok() then return 18 end if + println("locks-ok") + return 0 +end fn diff --git a/tests/matrix/io/durable-file-io.matrix b/tests/matrix/io/durable-file-io.matrix new file mode 100644 index 00000000..566a0518 --- /dev/null +++ b/tests/matrix/io/durable-file-io.matrix @@ -0,0 +1,99 @@ +!!! Shared public durability and lock contract, paired with the Ny fixture. +book nil.tests.durable_file_io + +read everything from nil.std.core +read write_bytes_durable, read_bytes, sync_directory, acquire_file_lock, release_file_lock from nil.std.io +read arg_count, arg from nil.std.system +read byte_at, from_byte from nil.std.text + +main returns override integer begin paragraph + when (arg_count with nothing) does not equal 1 then + give 64 + end when + when (byte_at with s being "é", index being 0) does not equal 195 then + give 20 + end when + when (byte_at with s being "é", index being 1) does not equal 169 then + give 21 + end when + when (byte_at with s being "é", index being minus 1) does not equal minus 1 then + give 22 + end when + when (byte_at with s being "é", index being 2) does not equal minus 1 then + give 23 + end when + value rebuilt is (from_byte with code being 195) plus (from_byte with code being 169) + when rebuilt does not equal "é" then + give 24 + end when + when (from_byte with code being minus 1) does not equal "" or (from_byte with code being 256) does not equal "" then + give 25 + end when + value root is arg with index being 0 + value output is root plus "/checkpoint.bin" + value lock is root plus "/writer.lock" + value first as array of override byte is [0 becomes override byte, 10 becomes override byte, 13 becomes override byte, 128 becomes override byte, 255 becomes override byte] + value second as array of override byte is [255 becomes override byte, 0 becomes override byte, 1 becomes override byte] + value empty as array of override byte is [] + when not ((write_bytes_durable with path being output, content being first, replace being no).is_ok with nothing) then + give 1 + end when + when (write_bytes_durable with path being output, content being second, replace being no).is_ok with nothing then + give 2 + end when + value loaded is read_bytes with path being output + when loaded.is_error with nothing then + give 3 + end when + value bytes is loaded.unwrap with nothing + when (the length of bytes) does not equal 5 or (bytes at 0) does not equal (0 becomes override byte) or (bytes at 4) does not equal (255 becomes override byte) then + give 4 + end when + when not ((write_bytes_durable with path being output, content being second, replace being yes).is_ok with nothing) then + give 5 + end when + when not ((write_bytes_durable with path being root plus "/empty.bin", content being empty, replace being no).is_ok with nothing) then + give 6 + end when + when not ((sync_directory with path being root).is_ok with nothing) then + give 7 + end when + when (sync_directory with path being output).is_ok with nothing then + give 8 + end when + say "durable-write-ok" + + value acquired is acquire_file_lock with path being lock, create being yes + when acquired.is_error with nothing then + give 10 + end when + value token is acquired.unwrap with nothing + when token is at most 0 then + give 11 + end when + when (acquire_file_lock with path being lock, create being no).is_ok with nothing then + give 12 + end when + when (release_file_lock with token being 0).is_ok with nothing then + give 13 + end when + when not ((release_file_lock with token being token).is_ok with nothing) then + give 14 + end when + when (release_file_lock with token being token).is_ok with nothing then + give 15 + end when + value reacquired is acquire_file_lock with path being lock, create being no + when reacquired.is_error with nothing then + give 16 + end when + when (reacquired.unwrap with nothing) is at most token then + give 17 + end when + !!! Intentionally retained until invocation completion; the host then checks it. + when not ((sync_directory with path being root).is_ok with nothing) then + give 18 + end when + say "locks-ok" + give 0 +end paragraph diff --git a/tests/native_runtime_tests.cpp b/tests/native_runtime_tests.cpp index c89584b7..083cc4bd 100644 --- a/tests/native_runtime_tests.cpp +++ b/tests/native_runtime_tests.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #ifndef _WIN32 #include @@ -765,6 +766,16 @@ void check_ordinary_io_contract(bool &ok) { const auto call = [&](const char *name, std::uint64_t a = 0, std::uint64_t b = 0, std::uint64_t c = 0) { return nyrt_io_v1(name, a, b, c, &value, &error); }; + ok &= expect(call("text.byte_at", word("A\xc3\xa9"), 1) == 1 && value == 195 && + call("text.byte_at", word("A"), 1) == 1 && static_cast(value) == -1 && + call("text.byte_at", word("A"), static_cast(-1)) == 1 && static_cast(value) == -1, + "native byte lookup changed byte or bounds semantics"); + ok &= expect(call("text.from_byte", 195) == 1 && + static_cast(*reinterpret_cast(value)) == 195 && + call("text.from_byte", 256) == 1 && *reinterpret_cast(value) == '\0', + "native byte construction changed byte or range semantics"); + ok &= expect(call("text.from_byte", 0) == 0 && value == 0 && error, + "native byte construction silently truncated a NUL byte"); for (const auto &item : std::initializer_list>{ {"path.basename", "file.ny"}, {"path.dirname", "alpha/beta"}, {"path.stem", "file"}, {"path.extension", ".ny"}, {"path.extension_no_dot", "ny"}, @@ -858,6 +869,80 @@ void check_ordinary_io_contract(bool &ok) { nyrt_context_end(); } +void check_durable_io_contract(bool &ok) { + nyrt_context_begin(0, nullptr); + try { + temporary_directory temporary; + const auto directory = temporary.path().u8string(); + const auto destination = (temporary.path() / "checkpoint.bin").u8string(); + const auto lock_path = (temporary.path() / "writer.lock").u8string(); + const auto word = [](const void *pointer) { + return static_cast(reinterpret_cast(pointer)); + }; + std::uint64_t value = 0; + const char *error = nullptr; + const auto call = [&](const char *name, std::uint64_t a = 0, std::uint64_t b = 0, std::uint64_t c = 0) { + return nyrt_io_v1(name, a, b, c, &value, &error); + }; +#ifdef _WIN32 + ok &= expect(call("file.sync_directory", word(directory.c_str())) == 0 && error, + "unsupported durable I/O reported success"); + ok &= expect(call("file.acquire_file_lock", word(lock_path.c_str()), 1) == 0 && error && + !std::filesystem::exists(std::filesystem::u8path(lock_path)), + "unsupported locking mutated the namespace"); +#else + ok &= expect(call("file.sync_directory", word(directory.c_str())) == 1 && value == 1 && !error, + "native directory synchronization failed"); + auto *bytes = make_bytes({0, 10, 255}); + ok &= expect(call("file.write_bytes_durable", word(destination.c_str()), word(bytes), 0) == 1 && value == 1, + "native durable publication failed"); + ok &= expect(call("file.write_bytes_durable", word(destination.c_str()), word(bytes), 0) == 0 && error, + "native durable no-clobber replaced an existing file"); + const auto before_size = std::filesystem::file_size(std::filesystem::u8path(destination)); + auto *wrong = nyrt_array_new(NYRT_ARRAY_I32, 1); + ok &= expect(call("file.write_bytes_durable", word(destination.c_str()), word(wrong), 1) == 0 && + std::filesystem::file_size(std::filesystem::u8path(destination)) == before_size, + "native durable write accepted an invalid byte array"); + ok &= expect(call("file.write_bytes_durable", word(destination.c_str()), word(bytes), 2) == 0, + "native durable write accepted a non-boolean replace"); + ok &= expect(call("file.acquire_file_lock", word(lock_path.c_str()), 2) == 0 && + !std::filesystem::exists(std::filesystem::u8path(lock_path)), + "invalid lock create mutated the namespace"); + ok &= expect(call("file.acquire_file_lock", word(lock_path.c_str()), 1) == 1 && value > 0 && !error, + "native lock acquisition failed"); + const auto token = value; + bool isolated = false; + std::thread foreign([&]() { + nyrt_context_begin(0, nullptr); + std::uint64_t foreign_value = 0; + const char *foreign_error = nullptr; + const bool rejects_release = nyrt_io_v1("file.release_file_lock", token, 0, 0, &foreign_value, &foreign_error) == 0; + const bool rejects_lock = nyrt_io_v1("file.acquire_file_lock", word(lock_path.c_str()), 0, 0, &foreign_value, &foreign_error) == 0; + isolated = rejects_release && rejects_lock; + nyrt_context_end(); + }); + foreign.join(); + ok &= expect(isolated, "native lock escaped its execution context"); + ok &= expect(call("file.release_file_lock", token) == 1 && value == 1 && + call("file.release_file_lock", token) == 0 && value == 0 && error, + "native lock token survived release"); + ok &= expect(call("file.acquire_file_lock", word(lock_path.c_str()), 0) == 1 && value > token, + "native lock token was reused"); + const auto abandoned = value; + nyrt_context_end(); + nyrt_context_begin(0, nullptr); + ok &= expect(call("file.release_file_lock", abandoned) == 0 && error, + "native lock survived context teardown"); + ok &= expect(call("file.acquire_file_lock", word(lock_path.c_str()), 0) == 1 && value > abandoned, + "native teardown failed to close the backing descriptor"); +#endif + } catch (const std::exception &exception) { + std::cerr << "durable I/O native test setup failed: " << exception.what() << '\n'; + ok = false; + } + nyrt_context_end(); +} + } // namespace int main() { @@ -951,5 +1036,6 @@ int main() { check_console_input_contract(ok); check_ordinary_io_contract(ok); + check_durable_io_contract(ok); return ok ? EXIT_SUCCESS : EXIT_FAILURE; } diff --git a/tests/tools/durable_file_io_contract.py b/tests/tools/durable_file_io_contract.py new file mode 100644 index 00000000..09ece16a --- /dev/null +++ b/tests/tools/durable_file_io_contract.py @@ -0,0 +1,196 @@ +#!/usr/bin/env python3 +"""Public Ny/Matrix durable-file and lock routes with a host filesystem oracle. + +This qualifies local POSIX source-runtime behavior, not storage hardware power +loss or an installed/release SDK. Each execution has its own private directory. +""" +from __future__ import annotations + +import argparse +import json +import os +from pathlib import Path +import stat +import sys +import tempfile +import time + +import ordinary_io_parity_contract as support + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT / "tests")) +from native_output_staging import native_output_path + +EXPECTED_STDOUT = b"durable-write-ok\nlocks-ok\n" +EXPECTED_BYTES = bytes((255, 0, 1)) + + +def host_oracle(directory: Path) -> dict: + import fcntl + + expected = {"checkpoint.bin": EXPECTED_BYTES, "empty.bin": b"", "writer.lock": b""} + observed = {item.name for item in directory.iterdir()} + if observed != set(expected): + raise AssertionError("unexpected durable-file namespace: " + repr(sorted(observed))) + for name, content in expected.items(): + path = directory / name + info = path.lstat() + if (not stat.S_ISREG(info.st_mode) or info.st_uid != os.geteuid() + or info.st_nlink != 1 or stat.S_IMODE(info.st_mode) != 0o600): + raise AssertionError("file is not a private owned regular inode: " + name) + if path.read_bytes() != content: + raise AssertionError("durable bytes differ: " + name) + descriptor = os.open(directory / "writer.lock", os.O_RDWR | os.O_NOFOLLOW | os.O_CLOEXEC) + try: + fcntl.flock(descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB) + fcntl.flock(descriptor, fcntl.LOCK_UN) + finally: + os.close(descriptor) + return {"bytes": "exact", "modes": "0600", "remaining_staging_files": 0, + "lock_after_process_completion": "released"} + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + for name in ("compiler", "interpreter", "nilstd"): + parser.add_argument("--" + name, type=Path, required=True) + parser.add_argument("--runtime", type=Path) + parser.add_argument("--llvm", choices=("ON", "OFF"), required=True) + parser.add_argument("--output", type=Path, required=True, + help="retained evidence parent; each run creates a fresh private child") + args = parser.parse_args() + + output_parent = args.output.resolve() + if output_parent == ROOT: + parser.error("evidence parent must not be the repository root") + output_parent.mkdir(parents=True, exist_ok=True) + output = Path(tempfile.mkdtemp(prefix="run-", dir=output_parent)) + logs = output / "logs" + logs.mkdir() + report = {"schema": "nil.durable-file-io.v1", "status": "FAIL", "commands": [], + "executions": [], "negative_abi": [], "llvm_enabled": args.llvm == "ON", + "scope": "POSIX_SOURCE_RUNTIME_NOT_RELEASE_OR_POWER_CUT_QUALIFICATION"} + if os.name != "posix": + report.update(status="SKIP", reason="POSIX implementation only; unsupported-host checks are separate") + support.save_new(output / "report.json", report) + print("SKIP: " + str(output / "report.json")) + return 0 + + ownership = support.load_ownership(ROOT) + compiler = args.compiler.resolve(strict=True) + interpreter = args.interpreter.resolve(strict=True) + nilstd = args.nilstd.resolve(strict=True) + runtime = args.runtime.resolve(strict=True) if args.runtime else None + sources = { + "ny": ROOT / "tests/language/durable-file-io.ny", + "matrix": ROOT / "tests/matrix/io/durable-file-io.matrix", + } + invalid = { + "width": (ROOT / "tests/language/durable-file-io-invalid-width.ny", "file.acquire_file_lock"), + "owner": (ROOT / "tests/language/durable-file-io-invalid-owner.ny", "file.sync_directory"), + } + inputs = {"compiler": compiler, "interpreter": interpreter, "runner": Path(__file__).resolve(), + **sources, **{name: row[0] for name, row in invalid.items()}} + if runtime: + inputs["runtime"] = runtime + report["inputs_before"] = {name: support.file_record(path) for name, path in inputs.items()} + environment = {key: value for key, value in os.environ.items() + if not key.startswith(("NIL_", "NY_"))} + environment["NIL_STRICT_BOUNDS"] = "1" + deadline = time.monotonic() + 240 + base = [compiler, "--quiet", "--no-stdlib", "--sdk-path", nilstd] + + def run(name: str, command: list, cwd: Path, expected: bytes | None = b"", + rejection: bytes | None = None) -> tuple[bytes, bytes]: + remaining = deadline - time.monotonic() + if remaining <= 0: + raise AssertionError("shared durable-file route deadline exhausted") + row = support.run_process(ownership, command, cwd, environment, logs, name, min(90, remaining)) + report["commands"].append(row) + stdout = (logs / row["stdout"]).read_bytes() + stderr = (logs / row["stderr"]).read_bytes() + if not row["cleanup_verified"] or row.get("timed_out"): + raise AssertionError(name + ": process cleanup/deadline failed") + if rejection is not None: + if row.get("exit_code", 0) == 0 or stdout or rejection not in stderr: + raise AssertionError(name + ": expected exact ABI rejection did not occur") + row["expected_rejection"] = True + elif row["status"] != "PASS" or stderr or (expected is not None and stdout != expected): + raise AssertionError(name + ": exit/stdout/stderr contract failed; see retained logs") + return stdout, stderr + + def execute(name: str, language: str, command: list) -> None: + working = output / name + working.mkdir() + data = working / "data-café 日本語 🦊" + data.mkdir(mode=0o700) + run(name, [*command, data], working, EXPECTED_STDOUT) + report["executions"].append({"route": name, "language": language, + "status": "PASS", "oracle": host_oracle(data)}) + + try: + # Record and check the runtime archive actually selected by the compiler. + analysis, _ = run("runtime-selection", [compiler, "--analyze", "--no-stdlib", + "--sdk-path", nilstd, sources["ny"]], output, None) + selected = json.loads(analysis)["nativeRuntime"] + report["selected_native_runtime"] = selected + if runtime and args.llvm == "ON" and (not selected or Path(selected).resolve() != runtime): + raise AssertionError("compiler selected a different native runtime archive") + for language, source in sources.items(): + build = output / (language + "-build") + build.mkdir() + for encoding in ("text", "binary"): + artifact = build / (encoding + ".nil") + flags = [] if encoding == "text" else ["--emit-binary-nil"] + run(language + "-compile-" + encoding, + [*base, "--no-bundle", *flags, "-o", artifact, source], build) + if artifact.read_bytes().startswith(b"NIL\0") != (encoding == "binary"): + raise AssertionError("unexpected NIL encoding") + execute(language + "-" + encoding + "-vm", language, + [interpreter, "--no-ai", artifact, "--"]) + if args.llvm == "ON": + executable = build / "native" + run(language + "-compile-aot", [*base, "--native", "-o", executable, source], build) + execute(language + "-aot", language, [native_output_path(executable)]) + execute(language + "-jit", language, + [*base, "--native", "--jit", "-o", build / "jit", source, "--"]) + for name, (source, operation) in invalid.items(): + for encoding in ("text", "binary"): + artifact = output / ("invalid-" + name + "-" + encoding + ".nil") + flags = [] if encoding == "text" else ["--emit-binary-nil"] + run("compile-invalid-" + name + "-" + encoding, + [*base, "--no-bundle", *flags, "-o", artifact, source], output) + wanted = (operation + ": requires its checked result type and enum schema").encode() + run("invalid-" + name + "-" + encoding, + [interpreter, "--no-ai", artifact], output, rejection=wanted) + if (output / "must-not-exist.lock").exists(): + raise AssertionError("rejected VM ABI created a lock") + report["negative_abi"].append({"case": name, "route": encoding + "-vm", "status": "PASS"}) + if args.llvm == "ON": + executable = output / ("invalid-" + name) + wanted = (operation + " requires its exact ordinary-I/O ABI and enum schema").encode() + run("invalid-" + name, [*base, "--native", "-o", executable, source], output, + rejection=wanted) + if native_output_path(executable).exists() or (output / "must-not-exist.lock").exists(): + raise AssertionError("rejected ABI published an artifact or lock") + report["negative_abi"].append({"case": name, "route": "llvm-aot", "status": "PASS"}) + expected_count = 8 if args.llvm == "ON" else 4 + if len(report["executions"]) != expected_count: + raise AssertionError("route matrix incomplete") + report["inputs_after"] = {name: support.file_record(path) for name, path in inputs.items()} + if report["inputs_after"] != report["inputs_before"]: + raise AssertionError("a test input changed during execution") + report["status"] = "PASS" + except Exception as error: + report["error"] = str(error) + finally: + report["cleanup_verified"] = all(row["cleanup_verified"] for row in report["commands"]) + support.save_new(output / "report.json", report) + print(report["status"] + ": " + str(output / "report.json")) + if report["status"] != "PASS": + print(report.get("error", "durable file route contract failed"), file=sys.stderr) + return 0 if report["status"] == "PASS" else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) From c8550d6e84ff5a171ef6ef494b331a80b7fd2a63 Mon Sep 17 00:00:00 2001 From: Nathan Young Date: Sun, 15 Nov 2026 13:36:30 -0500 Subject: [PATCH 02/10] Add private entries and content digests NIL-0028 left private-directory creation, owner/mode inspection, and a standalone SHA-256 as separate APIs, so a storage application still had to supply a platform host for them. Each mechanism already existed and was exercised inside the framework: owner-only directory creation for toolchain scratch space, the private-regular predicate used when acquiring a lock, and SHA-256 for module fingerprints. The gap was a supported language surface, not an algorithm. Add create_private_directory, is_private_regular_file, is_private_directory, and sha256_hex. Directory creation applies its mode at creation rather than through a later chmod, which would expose a writable directory in between, and an existing entry is reported rather than adopted. The predicates return Result so three outcomes stay distinct: inspected and matching, inspected and not, or not inspectable. Collapsing absence into a false verdict would let a caller read missing as unsafe or the reverse. Inspection does not follow a final symlink, so a link is judged as itself. A path predicate describes an entry at inspection time and is not a safe substitute for opening it under O_NOFOLLOW; publication and lock acquisition keep their own checked opens. A digest detects accidental corruption and identifies content, and authenticates nothing: whoever can replace the bytes can replace the digest beside them. Tests cover creation mode and exclusivity, cross-kind verdicts, loosened file and directory modes, symlinks to private targets, multiply-linked files, FIFOs, uninspectable entries, unsupported-platform behavior before mutation, and RFC 6234 vectors including embedded NUL bytes. The paired Ny and Matrix fixtures exercise every surface across textual and binary VM, AOT, and JIT, with the host oracle checking directory modes. Co-Authored-By: Claude Opus 5 --- .../NIL-0028-durable-files-and-locks.md | 4 +- .../NIL-0029-private-entries-and-digests.md | 70 ++++++++++++ docs/design/README.md | 1 + docs/standard-library/durable-files.md | 42 +++++++- docs/standard-library/index.md | 4 +- nilcompiler/src/native_runtime.cpp | 26 +++++ nilcompiler/src/ordinary_io_intrinsic.hpp | 6 ++ nilcompiler/src/secure_file_io.cpp | 58 ++++++++++ nilcompiler/src/secure_file_io.hpp | 21 ++++ nilcompiler/src/vm.cpp | 96 ++++++++++++++++- nilstd/src/io/checksum.ny | 11 ++ nilstd/src/io/file.ny | 26 +++++ nilstd/src/io/package.ny | 2 + tests/durable_file_io_tests.cpp | 101 ++++++++++++++++++ tests/language/durable-file-io.ny | 42 ++++++++ tests/matrix/io/durable-file-io.matrix | 71 +++++++++++- tests/tools/durable_file_io_contract.py | 15 ++- 17 files changed, 586 insertions(+), 10 deletions(-) create mode 100644 docs/design/NIL-0029-private-entries-and-digests.md diff --git a/docs/design/NIL-0028-durable-files-and-locks.md b/docs/design/NIL-0028-durable-files-and-locks.md index 63c4c626..60b6d4df 100644 --- a/docs/design/NIL-0028-durable-files-and-locks.md +++ b/docs/design/NIL-0028-durable-files-and-locks.md @@ -54,4 +54,6 @@ The [public API reference](../standard-library/durable-files.md) defines exact limits. Existing SDKs do not gain the new provider from source declarations alone. A development build must ship matching compiler, runtime, and library sources; release/installed-SDK qualification and the remaining application-host -APIs are independent work. +APIs are independent work. The private-directory, owner/mode, and standalone +SHA-256 surfaces reserved here are decided in +[NIL-0029](NIL-0029-private-entries-and-digests.md). diff --git a/docs/design/NIL-0029-private-entries-and-digests.md b/docs/design/NIL-0029-private-entries-and-digests.md new file mode 100644 index 00000000..cce85d8d --- /dev/null +++ b/docs/design/NIL-0029-private-entries-and-digests.md @@ -0,0 +1,70 @@ +# NIL-0029: Private directory creation, metadata verdicts, and content digests + +- **Status:** Implemented additive POSIX source-runtime profile, with a + portable digest; release SDK qualification remains separate. + +## Motivation + +NIL-0028 gave applications durable publication and cooperative single-writer +locking, and explicitly left private-directory creation, owner/mode inspection, +and a standalone SHA-256 as separate APIs. A storage application still had to +supply a platform host for them, which is the gap NIL-0028 set out to close. + +Each mechanism already existed inside the framework and was already exercised: +owner-only directory creation for toolchain scratch space, the private-regular +predicate used when acquiring a lock, and SHA-256 for module fingerprints. The +gap was a supported language surface, not an algorithm. + +## Decision + +Add `create_private_directory`, `is_private_regular_file`, +`is_private_directory`, and `sha256_hex`. The filesystem operations join +`nil.std.io`; the digest joins `nil.std.io`'s checksum surface beside +`crc32`, which already draws the line between corruption detection and +authentication. + +Directory creation applies its mode at creation rather than through a later +chmod, which would expose a writable directory in between. An existing entry is +reported, never adopted, so success means the caller created the directory. +Parents are neither created nor trusted beyond existing ancestry rules. + +The predicates return `Result` so three outcomes stay distinct: the +entry was inspected and matches, it was inspected and does not, or it could not +be inspected. Collapsing absence into a false verdict would let a caller read +"missing" as "unsafe" or the reverse. Inspection does not follow a final +symlink, so a link is judged as itself and never inherits its target's verdict. + +`sha256_hex` returns 64 lowercase hexadecimal characters over every supplied +byte, including embedded NULs. It reuses the existing portable implementation, +and on Apple platforms the existing CommonCrypto path, so a digest does not +depend on which route computed it. + +## Boundaries and validation + +A path predicate describes an entry at inspection time. It is not a safe +substitute for opening the entry under `O_NOFOLLOW`, because it cannot close the +window between inspection and use. Publication and lock acquisition keep their +own checked opens; these surfaces are for preflight and diagnosis. A caller that +needs a guarantee must act on an open descriptor, not on a prior verdict. + +A digest detects accidental corruption and identifies content. It is not a +signature, a message authentication code, encryption, or rollback protection: +whoever can replace the bytes can replace the digest beside them. Authenticating +a digest requires a secret these functions do not take. + +Mode and owner verdicts describe POSIX ownership and permission bits only. They +say nothing about ACLs, extended attributes, capabilities, or mandatory access +control, and they are not a security boundary against the owner or root. + +Tests cover creation mode and exclusivity, cross-kind verdicts, loosened file +and directory modes, symlinks to otherwise-private targets, multiply-linked +files, FIFOs, uninspectable entries, unsupported-platform behavior before any +mutation, and RFC 6234 digest vectors including embedded NUL bytes. The paired +Ny and Matrix fixtures exercise every surface across textual and binary VM, AOT, +and JIT, with an independent host oracle checking directory modes. + +Windows returns an explicit unsupported-platform error before filesystem +mutation; the digest is platform-independent. Other POSIX platforms need their +own execution evidence. As with NIL-0028, source declarations alone do not give +an installed SDK the new provider, and release qualification is independent +work. See the [public API reference](../standard-library/durable-files.md). diff --git a/docs/design/README.md b/docs/design/README.md index 3abe5cbc..c734e9b8 100644 --- a/docs/design/README.md +++ b/docs/design/README.md @@ -55,6 +55,7 @@ not assigned architecture identifiers. | NIL-0026 | [Evolving the language without breaking what is written](NIL-0026-language-evolution.md) | Editions implemented in the project manifest | | NIL-0027 | [Multiline formatted text and structured markup literals](NIL-0027-structured-markup.md) | Proposed; staged, nothing shipped | | NIL-0028 | [Durable publication and context-owned file locks](NIL-0028-durable-files-and-locks.md) | Implemented additive POSIX source-runtime profile; installed/release SDK qualification separate | +| NIL-0029 | [Private directory creation, metadata verdicts, and content digests](NIL-0029-private-entries-and-digests.md) | Implemented additive POSIX source-runtime profile with a portable digest; installed/release SDK qualification separate | | NIL-0093 | [Executable context is artifact self-description](NIL-0093-executable-context.md) | Implemented within the documented inspection profile | ## Retained Ny feature references diff --git a/docs/standard-library/durable-files.md b/docs/standard-library/durable-files.md index 8b4ae382..48d0ed05 100644 --- a/docs/standard-library/durable-files.md +++ b/docs/standard-library/durable-files.md @@ -10,6 +10,10 @@ the same runtime provider and checked results. | `sync_directory(path)` | `Result` | | `acquire_file_lock(path, create)` | `Result` | | `release_file_lock(token)` | `Result` | +| `create_private_directory(path)` | `Result` | +| `is_private_regular_file(path)` | `Result` | +| `is_private_directory(path)` | `Result` | +| `sha256_hex(data)` | `Result` | Matrix uses the same names with underscores or hyphens. Machine-width lock tokens appear as `number`/`override long`; they are runtime handles, not host @@ -86,6 +90,38 @@ unsupported-platform error before filesystem mutation. Other POSIX platforms need their own execution evidence; this addition does not qualify an installed or release SDK. -Private-directory creation, owner/mode inspection, standalone SHA-256, and a -complete storage host are separate APIs. A consuming application should migrate -only the parts it has qualified. See [NIL-0028](../design/NIL-0028-durable-files-and-locks.md). +## Private entries and digests + +`create_private_directory` exclusively creates one owner-only directory: POSIX +mode `0700`, applied by creation rather than a later chmod, which would leave a +writable window. An existing entry is reported, never adopted, so success means +this call created it. Parents are not created and remain trusted. Creation does +not durably publish the new name; call `sync_directory` when that matters. + +`is_private_regular_file` asks whether an entry is regular, owned by the +effective user, singly linked, and exactly mode `0600`. `is_private_directory` +asks whether it is a directory owned by the effective user with exactly mode +`0700`. Neither follows a final symlink, so a link is judged as itself and does +not inherit its target's verdict. + +An `Error` means the entry could not be inspected, which is distinct from a +verdict of `false`. Both are distinct from being safe to use: these inspect a +path, so the entry can change between inspection and use. Treat them as +preflight and diagnosis. A caller needing a guarantee must act on an open +descriptor; durable publication and lock acquisition keep their own checked +no-follow opens. The verdicts describe POSIX owner and permission bits only, +not ACLs, extended attributes, capabilities, or mandatory access control. + +`sha256_hex` returns 64 lowercase hexadecimal characters over every supplied +byte, embedded NULs included, bounded like the other byte-array operations. It +detects accidental corruption and identifies content. It is **not** a +signature, a message authentication code, encryption, or rollback protection: +anyone able to replace the bytes can replace the digest stored beside them. +Authenticating a digest needs a secret this function does not take. For +accidental-corruption checks over a window of a byte array, `crc32` remains +cheaper and is equally unauthenticated. + +A complete storage host remains the application's own. A consuming application +should migrate only the parts it has qualified. See +[NIL-0028](../design/NIL-0028-durable-files-and-locks.md) and +[NIL-0029](../design/NIL-0029-private-entries-and-digests.md). diff --git a/docs/standard-library/index.md b/docs/standard-library/index.md index d0bae87d..50135b25 100644 --- a/docs/standard-library/index.md +++ b/docs/standard-library/index.md @@ -149,7 +149,9 @@ visibility-atomic but does not promise parent-directory durability after a sudden power loss. The additive [durable-files reference](durable-files.md) covers -`write_bytes_durable`, `sync_directory`, and context-owned advisory file locks. +`write_bytes_durable`, `sync_directory`, context-owned advisory file locks, +owner-only directory creation, private-entry metadata verdicts, and +`sha256_hex`. Those POSIX primitives supply explicit filesystem barriers and nonblocking single-writer coordination. They preserve existing atomic-write/stream-flush semantics and do not expand an older installed SDK's guarantees. diff --git a/nilcompiler/src/native_runtime.cpp b/nilcompiler/src/native_runtime.cpp index 54c66b0d..b202ef71 100644 --- a/nilcompiler/src/native_runtime.cpp +++ b/nilcompiler/src/native_runtime.cpp @@ -13,6 +13,7 @@ #include "scalar_text.hpp" #include "secure_file_io.hpp" +#include "../../common/content_digest.hpp" #include "time_support.hpp" #include "file_time_support.hpp" #include "parallel_support.hpp" @@ -1712,6 +1713,31 @@ std::int32_t nyrt_io_v1(const char *operation, std::uint64_t first, *value = 1; return 1; } + if (name == "file.create_private_directory") { + const auto created = ny::detail::create_private_directory_utf8(text(first)); + if (!created.ok) { set_error(error, created.error); return 0; } + *value = 1; + return 1; + } + if (name == "file.is_private_regular_file" || + name == "file.is_private_directory") { + // An uninspectable entry is an error; a false verdict is a successful + // inspection, so the two never collapse into one answer. + const auto checked = name == "file.is_private_regular_file" + ? ny::detail::private_regular_file_utf8(text(first)) + : ny::detail::private_directory_utf8(text(first)); + if (!checked.ok) { set_error(error, checked.error); return 0; } + *value = checked.value ? 1 : 0; + return 1; + } + if (name == "checksum.sha256_hex") { + const auto *array = checked_array(reinterpret_cast(static_cast(first)), NYRT_ARRAY_U8); + if (!array || array->length > maximum_file_bytes) return fail("invalid or oversized byte array"); + nil::detail::sha256 hash; + if (array->length) hash.update(static_cast(array->data), array->length); + const std::string digest = hash.finish(); + return output_text(std::string_view(digest)); + } if (name.rfind("path.", 0) == 0) { if (name == "path.separator") return output_text("/"); diff --git a/nilcompiler/src/ordinary_io_intrinsic.hpp b/nilcompiler/src/ordinary_io_intrinsic.hpp index 12c67977..182f3828 100644 --- a/nilcompiler/src/ordinary_io_intrinsic.hpp +++ b/nilcompiler/src/ordinary_io_intrinsic.hpp @@ -52,6 +52,12 @@ inline std::optional intrinsic(const std::string &name) { return Contract{{"text", "bool"}, "i64", Output::result}; if (name == "file.release_file_lock") return Contract{{"i64"}, "bool", Output::result}; + if (name == "file.create_private_directory" || + name == "file.is_private_regular_file" || + name == "file.is_private_directory") + return Contract{{"text"}, "bool", Output::result}; + if (name == "checksum.sha256_hex") + return Contract{{"array"}, "text", Output::result}; if (name == "environment.get") return Contract{{"text"}, "text", Output::option}; if (name == "file.handle_open") return Contract{{"text", "i32"}, "i64"}; if (name == "file.handle_read" || name == "file.handle_write") diff --git a/nilcompiler/src/secure_file_io.cpp b/nilcompiler/src/secure_file_io.cpp index ab2060b8..e587c697 100644 --- a/nilcompiler/src/secure_file_io.cpp +++ b/nilcompiler/src/secure_file_io.cpp @@ -690,6 +690,64 @@ bool private_lock_file(const struct stat &status) { } // namespace #endif +AtomicFileWrite create_private_directory_utf8(const std::string &path) { +#ifdef _WIN32 + (void)path; + return {false, "file.create_private_directory: unsupported platform"}; +#else + const auto native_path = path_from_utf8_string(path); + if (!native_path) + return {false, "file.create_private_directory: invalid directory path"}; + // The requested mode is applied by creation. A default-permission mkdir + // followed by chmod would expose a writable directory in between. An + // existing entry is reported, never adopted, so a caller cannot be handed + // someone else's directory as if it had just created it. + if (::mkdir(native_path->c_str(), 0700) != 0) { + if (errno == EEXIST) + return {false, "file.create_private_directory: entry already exists"}; + return {false, "file.create_private_directory: cannot create directory"}; + } + return {true, {}}; +#endif +} + +FileCheck private_regular_file_utf8(const std::string &path) { +#ifdef _WIN32 + (void)path; + return {false, false, + "file.is_private_regular_file: unsupported platform"}; +#else + const auto native_path = path_from_utf8_string(path); + if (!native_path) + return {false, false, "file.is_private_regular_file: invalid file path"}; + struct stat status {}; + // lstat, so a symlink is judged as itself and reports false rather than + // silently describing its target. + if (::lstat(native_path->c_str(), &status) != 0) + return {false, false, + "file.is_private_regular_file: cannot inspect entry"}; + return {true, private_lock_file(status), {}}; +#endif +} + +FileCheck private_directory_utf8(const std::string &path) { +#ifdef _WIN32 + (void)path; + return {false, false, "file.is_private_directory: unsupported platform"}; +#else + const auto native_path = path_from_utf8_string(path); + if (!native_path) + return {false, false, "file.is_private_directory: invalid directory path"}; + struct stat status {}; + if (::lstat(native_path->c_str(), &status) != 0) + return {false, false, "file.is_private_directory: cannot inspect entry"}; + const bool owner_only = S_ISDIR(status.st_mode) && + status.st_uid == ::geteuid() && + (status.st_mode & 07777) == 0700; + return {true, owner_only, {}}; +#endif +} + FileLockRegistry::~FileLockRegistry() noexcept { clear(); } FileLockResult FileLockRegistry::acquire(const std::string &path, bool create) { diff --git a/nilcompiler/src/secure_file_io.hpp b/nilcompiler/src/secure_file_io.hpp index 98789c9e..3e185786 100644 --- a/nilcompiler/src/secure_file_io.hpp +++ b/nilcompiler/src/secure_file_io.hpp @@ -26,6 +26,16 @@ struct FileLockResult { std::string error; }; +// A three-state metadata answer. `ok` says the entry was inspected; `value` +// is the predicate's verdict. A missing or uninspectable entry is an error, +// never a false verdict, so a caller cannot read "absent" as "unsafe" or the +// reverse. +struct FileCheck { + bool ok = false; + bool value = false; + std::string error; +}; + // Registry ownership is the execution-context boundary. Tokens are process- // monotonic and never recycled, and never expose the host descriptor. Locks // are advisory; callers must control the directory ancestry and cooperate. @@ -64,6 +74,17 @@ AtomicFileWrite sync_directory_utf8(const std::string &path); AtomicFileWrite write_file_durable_utf8(const std::string &path, const std::vector &bytes, bool replace); +// POSIX only. Exclusive owner-only directory creation: an existing entry is +// never adopted, and the final mode is set by creation rather than a later +// chmod, which would leave a writable window. +AtomicFileWrite create_private_directory_utf8(const std::string &path); +// POSIX only. No-follow metadata predicates. These inspect a path, so the +// answer describes the entry at inspection time and is not a safe substitute +// for opening the entry under O_NOFOLLOW: a preflight check cannot close the +// window between inspection and use. Publication and lock acquisition keep +// their own checked opens. +FileCheck private_regular_file_utf8(const std::string &path); +FileCheck private_directory_utf8(const std::string &path); // Host callers retain the native path / legacy narrow-string contract. BoundedFileRead read_regular_file_bounded(const std::string &path, std::uint64_t maximum_bytes); diff --git a/nilcompiler/src/vm.cpp b/nilcompiler/src/vm.cpp index 53c47b47..56805522 100644 --- a/nilcompiler/src/vm.cpp +++ b/nilcompiler/src/vm.cpp @@ -17,6 +17,7 @@ #include "entropy_support.hpp" #include "net_support.hpp" #include "secure_file_io.hpp" +#include "../../common/content_digest.hpp" #include "time_support.hpp" #include "file_time_support.hpp" #include "../../common/windows_environment.hpp" @@ -2758,7 +2759,11 @@ void VM::executeInstruction(const Instruction &instr) { const bool returns_void = instr.args.size() > 3 && instr.args[3] == "void"; if (lib_name == "intrinsic" && (fn_name == "file.write_bytes_durable" || fn_name == "file.sync_directory" || - fn_name == "file.acquire_file_lock" || fn_name == "file.release_file_lock")) { + fn_name == "file.acquire_file_lock" || fn_name == "file.release_file_lock" || + fn_name == "file.create_private_directory" || + fn_name == "file.is_private_regular_file" || + fn_name == "file.is_private_directory" || + fn_name == "checksum.sha256_hex")) { const auto contract = ordinary_io::intrinsic(fn_name); const auto expected = "nil::std::core::Result<" + contract->payload + ",text>"; bool valid = arg_count == static_cast(contract->parameters.size()) && @@ -5317,6 +5322,95 @@ void VM::executeInstruction(const Instruction &instr) { } return; } + if (fn_name == "file.create_private_directory" || + fn_name == "file.is_private_regular_file" || + fn_name == "file.is_private_directory") { + auto reply = [&](bool ok, bool value, const std::string &error) { + EnumValue result; + result.variant_name = ok ? "Result::Ok" : "Result::Error"; + if (ok) result.payloads.push_back(static_cast(value ? 1 : 0)); + else result.payloads.push_back(error); + pushStack(result); + }; + if (args.size() != 1 || !std::holds_alternative(args[0])) { + reply(false, false, fn_name + ": expected a text path"); + return; + } + const std::string &path = std::get(args[0]); + try { + if (fn_name == "file.create_private_directory") { + const auto created = detail::create_private_directory_utf8(path); + reply(created.ok, true, created.error); + } else if (fn_name == "file.is_private_regular_file") { + const auto checked = detail::private_regular_file_utf8(path); + reply(checked.ok, checked.value, checked.error); + } else { + const auto checked = detail::private_directory_utf8(path); + reply(checked.ok, checked.value, checked.error); + } + } catch (...) { + reply(false, false, fn_name + ": host operation failed"); + } + return; + } + if (fn_name == "checksum.sha256_hex") { + auto push_digest = [&](const std::string &digest) { + EnumValue result; + result.variant_name = "Result::Ok"; + result.payloads.push_back(digest); + pushStack(result); + }; + auto push_error = [&](const std::string &message) { + EnumValue result; + result.variant_name = "Result::Error"; + result.payloads.push_back(message); + pushStack(result); + }; + if (args.size() != 1 || !std::holds_alternative(args[0])) { + push_error(fn_name + ": expected a byte array"); + return; + } + const auto block = heap_.find(std::get(args[0]).address); + if (block == heap_.end()) { + push_error(fn_name + ": invalid byte array"); + return; + } + std::vector bytes; + try { + if (is_byte_heap_type(block->second.type_name)) { + if (block->second.byte_data.size() > max_intrinsic_file_bytes) { + push_error(fn_name + ": byte array exceeds the 512 MiB safety limit"); + return; + } + bytes = block->second.byte_data; + } else if (block->second.type_name == "array") { + if (block->second.data.size() > max_intrinsic_file_bytes) { + push_error(fn_name + ": array exceeds the 512 MiB safety limit"); + return; + } + bytes.reserve(block->second.data.size()); + for (const Value &value : block->second.data) { + const auto *integer = std::get_if(&value); + if (integer == nullptr || *integer < 0 || *integer > 255) { + push_error(fn_name + ": array contains a value outside u8"); + return; + } + bytes.push_back(static_cast(static_cast(*integer))); + } + } else { + push_error(fn_name + ": value is not a byte array"); + return; + } + nil::detail::sha256 hash; + if (!bytes.empty()) hash.update(bytes.data(), bytes.size()); + push_digest(hash.finish()); + } catch (const std::bad_alloc &) { + push_error(fn_name + ": allocation failed"); + } catch (...) { + push_error(fn_name + ": host operation failed"); + } + return; + } // file.write_bytes_atomic(path, content, replace) -> result if (fn_name == "file.write_bytes_atomic" || fn_name == "file.write_bytes_durable") { auto push_ok = [&]() { diff --git a/nilstd/src/io/checksum.ny b/nilstd/src/io/checksum.ny index 57dd826c..06d9b2f2 100644 --- a/nilstd/src/io/checksum.ny +++ b/nilstd/src/io/checksum.ny @@ -45,3 +45,14 @@ end fn pub fn crc32(data: array, offset: i64, limit: i64) -> Result return crc32_update(0, data, offset, limit) end fn + +# SHA-256 of every byte, as 64 lowercase hexadecimal characters. +# +# This detects accidental corruption and identifies content. It is not a +# signature, a message authentication code, encryption, or rollback +# protection: anyone who can replace the bytes can replace the digest with +# them. Authenticating a digest needs a secret this function does not take. +# +# Bounded like the other byte-array operations; an oversized array is an error. +@intrinsic("checksum.sha256_hex") +pub fn sha256_hex(data: array) -> Result diff --git a/nilstd/src/io/file.ny b/nilstd/src/io/file.ny index 5248e9db..bc2cb192 100644 --- a/nilstd/src/io/file.ny +++ b/nilstd/src/io/file.ny @@ -93,6 +93,32 @@ pub fn acquire_file_lock(path: text, create: bool) -> Result @intrinsic("file.release_file_lock") pub fn release_file_lock(token: i64) -> Result +# Create a new owner-only directory: POSIX mode 0700, applied by creation +# rather than a later chmod, which would leave a writable window. An existing +# entry is an error and is never adopted, so success means this call created +# the directory. Parents are not created and are trusted; creation does not +# durably publish the new name, so call sync_directory when that is needed. +# POSIX-only, fails closed elsewhere. +@intrinsic("file.create_private_directory") +pub fn create_private_directory(path: text) -> Result + +# Is this entry a private regular file: regular, owned by the effective user, +# exactly one hard link, and exactly mode 0600? A symlink is judged as itself +# and answers false rather than describing its target. +# +# Error means the entry could not be inspected, which is distinct from an +# answer of false. Both are distinct from being safe to use: this inspects a +# path, so the entry can change before it is opened. Treat it as preflight and +# diagnosis, not as a guarantee; durable writes and lock acquisition perform +# their own checked no-follow opens. +@intrinsic("file.is_private_regular_file") +pub fn is_private_regular_file(path: text) -> Result + +# Is this entry a directory owned by the effective user with exactly mode +# 0700? The same inspection limits as is_private_regular_file apply. +@intrinsic("file.is_private_directory") +pub fn is_private_directory(path: text) -> Result + # Append text to a file @intrinsic("file.append_text") pub fn append_text(path: text, content: text) -> Result diff --git a/nilstd/src/io/package.ny b/nilstd/src/io/package.ny index acf00f9c..a3283792 100644 --- a/nilstd/src/io/package.ny +++ b/nilstd/src/io/package.ny @@ -9,6 +9,8 @@ # - File: checked whole-file operations, bounded regular-file input, atomic # byte publication, and opaque-handle streams (file.ny) # - POSIX durable publication, directory synchronization, context-owned locks +# - Owner-only directory creation and private-entry metadata verdicts +# - Checksum: CRC-32 windows and SHA-256 content digests (checksum.ny) # - Stream: Read/Write/Seek/Close traits and checked stream_copy (stream.ny) # - Path: lexical path inspection and transformation (path.ny) # - Binary: bounded little/big-endian byte-array reads and writes (binary.ny) diff --git a/tests/durable_file_io_tests.cpp b/tests/durable_file_io_tests.cpp index 0f1ee80d..4f2c8cef 100644 --- a/tests/durable_file_io_tests.cpp +++ b/tests/durable_file_io_tests.cpp @@ -1,4 +1,5 @@ #include "../nilcompiler/src/secure_file_io.hpp" +#include "../common/content_digest.hpp" #include #include @@ -419,6 +420,78 @@ void check_process_death_cleanup(const fs::path &root) { require(acquired.ok, "process death did not release the operating-system lock"); require(parent_registry.release(acquired.token).ok, "cannot release post-crash lock"); } +void check_private_metadata(const fs::path &root) { + const auto created = root / "owner-only"; + require(ny::detail::create_private_directory_utf8(created.u8string()).ok, + "cannot create an owner-only directory"); + struct stat status {}; + require(::lstat(created.c_str(), &status) == 0 && S_ISDIR(status.st_mode) && + (status.st_mode & 07777) == 0700, + "created directory is not owner-only"); + // An existing entry is never adopted, so a caller cannot be handed a + // directory it did not create. + require_error(ny::detail::create_private_directory_utf8(created.u8string()), "owner-only"); + require_error(ny::detail::create_private_directory_utf8(std::string("bad\0path", 8)), "bad"); + + auto verdict = [](const ny::detail::FileCheck &check, bool expected, + const std::string &message) { + require(check.ok, "metadata inspection failed: " + message); + require(check.value == expected, message); + }; + + const auto secret = root / "secret"; + write_bytes(secret, "payload"); + verdict(ny::detail::private_regular_file_utf8(secret.u8string()), true, + "a 0600 owned regular file is private"); + verdict(ny::detail::private_directory_utf8(created.u8string()), true, + "a 0700 owned directory is private"); + // Cross-kind answers are verdicts, not errors. + verdict(ny::detail::private_regular_file_utf8(created.u8string()), false, + "a directory is not a private regular file"); + verdict(ny::detail::private_directory_utf8(secret.u8string()), false, + "a regular file is not a private directory"); + + const auto loose = root / "loose"; + write_bytes(loose, "payload"); + require(::chmod(loose.c_str(), 0644) == 0, "cannot loosen fixture mode"); + verdict(ny::detail::private_regular_file_utf8(loose.u8string()), false, + "a 0644 file is not private"); + const auto loose_directory = root / "loose-directory"; + require(::mkdir(loose_directory.c_str(), 0755) == 0, "cannot create loose directory"); + verdict(ny::detail::private_directory_utf8(loose_directory.u8string()), false, + "a 0755 directory is not private"); + + // A symlink is judged as itself: it never inherits its target's verdict. + const auto link = root / "link"; + require(::symlink(secret.c_str(), link.c_str()) == 0, "cannot create fixture symlink"); + verdict(ny::detail::private_regular_file_utf8(link.u8string()), false, + "a symlink to a private file is not a private regular file"); + const auto directory_link = root / "directory-link"; + require(::symlink(created.c_str(), directory_link.c_str()) == 0, + "cannot create fixture directory symlink"); + verdict(ny::detail::private_directory_utf8(directory_link.u8string()), false, + "a symlink to a private directory is not a private directory"); + + // A second hard link means another name can reach the same inode. + const auto shared = root / "shared"; + require(::link(secret.c_str(), shared.c_str()) == 0, "cannot create fixture hard link"); + verdict(ny::detail::private_regular_file_utf8(shared.u8string()), false, + "a multiply-linked file is not private"); + require(::unlink(shared.c_str()) == 0, "cannot remove fixture hard link"); + + const auto pipe = root / "pipe"; + require(::mkfifo(pipe.c_str(), 0600) == 0, "cannot create fixture FIFO"); + verdict(ny::detail::private_regular_file_utf8(pipe.u8string()), false, + "a FIFO is not a private regular file"); + + // Absence cannot be inspected; it is an error, not a false verdict. + const auto absent = root / "absent-metadata-marker"; + require_error(ny::detail::private_regular_file_utf8(absent.u8string()), + "absent-metadata-marker"); + require_error(ny::detail::private_directory_utf8(absent.u8string()), + "absent-metadata-marker"); +} + #else void check_unsupported_host(const fs::path &root) { const auto target = root / "private-unsupported-marker"; @@ -426,9 +499,35 @@ void check_unsupported_host(const fs::path &root) { require_error(ny::detail::write_file_durable_utf8(target.u8string(), {'x'}, false), "private-unsupported-marker"); FileLockRegistry registry; require_error(registry.acquire(target.u8string(), true), "private-unsupported-marker"); + require_error(ny::detail::create_private_directory_utf8(target.u8string()), + "private-unsupported-marker"); + require_error(ny::detail::private_regular_file_utf8(target.u8string()), + "private-unsupported-marker"); + require_error(ny::detail::private_directory_utf8(target.u8string()), + "private-unsupported-marker"); require(registry.empty() && !fs::exists(target), "unsupported host mutated its namespace"); } #endif + +void check_content_digest() { + // RFC 6234 vectors, so a wrong digest fails rather than merely staying stable. + nil::detail::sha256 empty; + require(empty.finish() == + "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "SHA-256 of no bytes is wrong"); + nil::detail::sha256 abc; + abc.update("abc", 3); + require(abc.finish() == + "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", + "SHA-256 of \"abc\" is wrong"); + // An embedded NUL must be digested, not treated as a terminator. + nil::detail::sha256 embedded; + const char zeroed[] = {'a', '\0', 'b'}; + embedded.update(zeroed, sizeof(zeroed)); + require(embedded.finish() == + "59b271ae1bbcb1d31d41929817f4b16fb439eb4f31520b5ad1d5ce98920a7138", + "a digest over embedded NUL bytes must cover every byte"); +} } // namespace int main() { @@ -443,9 +542,11 @@ int main() { check_lock_lifecycle(owned.root); check_unsafe_locks(owned.root); check_process_death_cleanup(owned.root); + check_private_metadata(owned.root); #else check_unsupported_host(owned.root); #endif + check_content_digest(); std::cout << "durable-file-io-ok\n"; return 0; } catch (const std::exception &error) { diff --git a/tests/language/durable-file-io.ny b/tests/language/durable-file-io.ny index f996650e..e892f3f3 100644 --- a/tests/language/durable-file-io.ny +++ b/tests/language/durable-file-io.ny @@ -47,5 +47,47 @@ fn main() -> i32 # independently acquires the backing file after every execution route. if not nil::std::io::sync_directory(root).is_ok() then return 18 end if println("locks-ok") + + # RFC 6234 vectors, so a wrong digest fails rather than merely staying stable. + match nil::std::io::sha256_hex(empty) + Result.Error(_) -> return 20 + Result.Ok(digest) -> + if digest != "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" then return 21 end if + end match + let abc: array = [97 as u8, 98 as u8, 99 as u8] + match nil::std::io::sha256_hex(abc) + Result.Error(_) -> return 22 + Result.Ok(digest) -> + if digest != "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" then return 23 end if + end match + + # The harness creates the working directory owner-only. + match nil::std::io::is_private_directory(root) + Result.Error(_) -> return 24 + Result.Ok(private) -> if not private then return 25 end if + end match + let nested = root + "/private" + if not nil::std::io::create_private_directory(nested).is_ok() then return 26 end if + # An existing entry is reported, never adopted. + if nil::std::io::create_private_directory(nested).is_ok() then return 27 end if + match nil::std::io::is_private_directory(nested) + Result.Error(_) -> return 28 + Result.Ok(private) -> if not private then return 29 end if + end match + # A 0600 published file is a private regular file; a directory is not, and + # that is a false verdict rather than an error. + match nil::std::io::is_private_regular_file(output) + Result.Error(_) -> return 30 + Result.Ok(private) -> if not private then return 31 end if + end match + match nil::std::io::is_private_regular_file(nested) + Result.Error(_) -> return 32 + Result.Ok(private) -> if private then return 33 end if + end match + # An absent entry cannot be inspected, which is distinct from either verdict. + if nil::std::io::is_private_regular_file(nested + "/absent").is_ok() then return 34 end if + if nil::std::io::is_private_directory(nested + "/absent").is_ok() then return 35 end if + if not nil::std::io::sync_directory(nested).is_ok() then return 36 end if + println("metadata-ok") return 0 end fn diff --git a/tests/matrix/io/durable-file-io.matrix b/tests/matrix/io/durable-file-io.matrix index 566a0518..d4e7e05f 100644 --- a/tests/matrix/io/durable-file-io.matrix +++ b/tests/matrix/io/durable-file-io.matrix @@ -2,7 +2,8 @@ book nil.tests.durable_file_io read everything from nil.std.core -read write_bytes_durable, read_bytes, sync_directory, acquire_file_lock, release_file_lock from nil.std.io +read write_bytes_durable, read_bytes, sync_directory, acquire_file_lock, release_file_lock, + create_private_directory, is_private_regular_file, is_private_directory, sha256_hex from nil.std.io read arg_count, arg from nil.std.system read byte_at, from_byte from nil.std.text @@ -95,5 +96,73 @@ main returns override integer begin paragraph give 18 end when say "locks-ok" + + !!! RFC 6234 vectors, so a wrong digest fails rather than merely staying stable. + value empty_digest is sha256_hex with data being empty + when empty_digest.is_error with nothing then + give 20 + end when + when (empty_digest.unwrap with nothing) does not equal "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" then + give 21 + end when + value abc as array of override byte is [97 becomes override byte, 98 becomes override byte, 99 becomes override byte] + value abc_digest is sha256_hex with data being abc + when abc_digest.is_error with nothing then + give 22 + end when + when (abc_digest.unwrap with nothing) does not equal "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" then + give 23 + end when + + !!! The harness creates the working directory owner-only. + value root_private is is_private_directory with path being root + when root_private.is_error with nothing then + give 24 + end when + when not (root_private.unwrap with nothing) then + give 25 + end when + value nested is root plus "/private" + when not ((create_private_directory with path being nested).is_ok with nothing) then + give 26 + end when + !!! An existing entry is reported, never adopted. + when (create_private_directory with path being nested).is_ok with nothing then + give 27 + end when + value nested_private is is_private_directory with path being nested + when nested_private.is_error with nothing then + give 28 + end when + when not (nested_private.unwrap with nothing) then + give 29 + end when + !!! A 0600 published file is a private regular file; a directory is not, and + !!! that is a false verdict rather than an error. + value file_private is is_private_regular_file with path being output + when file_private.is_error with nothing then + give 30 + end when + when not (file_private.unwrap with nothing) then + give 31 + end when + value directory_as_file is is_private_regular_file with path being nested + when directory_as_file.is_error with nothing then + give 32 + end when + when directory_as_file.unwrap with nothing then + give 33 + end when + !!! An absent entry cannot be inspected, which is distinct from either verdict. + when (is_private_regular_file with path being nested plus "/absent").is_ok with nothing then + give 34 + end when + when (is_private_directory with path being nested plus "/absent").is_ok with nothing then + give 35 + end when + when not ((sync_directory with path being nested).is_ok with nothing) then + give 36 + end when + say "metadata-ok" give 0 end paragraph diff --git a/tests/tools/durable_file_io_contract.py b/tests/tools/durable_file_io_contract.py index 09ece16a..89ea6eec 100644 --- a/tests/tools/durable_file_io_contract.py +++ b/tests/tools/durable_file_io_contract.py @@ -21,7 +21,7 @@ sys.path.insert(0, str(ROOT / "tests")) from native_output_staging import native_output_path -EXPECTED_STDOUT = b"durable-write-ok\nlocks-ok\n" +EXPECTED_STDOUT = b"durable-write-ok\nlocks-ok\nmetadata-ok\n" EXPECTED_BYTES = bytes((255, 0, 1)) @@ -29,9 +29,17 @@ def host_oracle(directory: Path) -> dict: import fcntl expected = {"checkpoint.bin": EXPECTED_BYTES, "empty.bin": b"", "writer.lock": b""} + # The fixture also creates one owner-only subdirectory through the public + # surface, so the namespace is checked as files plus that single directory. + expected_directories = {"private"} observed = {item.name for item in directory.iterdir()} - if observed != set(expected): + if observed != set(expected) | expected_directories: raise AssertionError("unexpected durable-file namespace: " + repr(sorted(observed))) + for name in expected_directories: + info = (directory / name).lstat() + if (not stat.S_ISDIR(info.st_mode) or info.st_uid != os.geteuid() + or stat.S_IMODE(info.st_mode) != 0o700): + raise AssertionError("directory is not owner-only: " + name) for name, content in expected.items(): path = directory / name info = path.lstat() @@ -47,7 +55,8 @@ def host_oracle(directory: Path) -> dict: finally: os.close(descriptor) return {"bytes": "exact", "modes": "0600", "remaining_staging_files": 0, - "lock_after_process_completion": "released"} + "lock_after_process_completion": "released", + "private_directories": sorted(expected_directories), "directory_modes": "0700"} def main() -> int: From 0ecbf101f4f355fd5175200fd6dbcd1e34633cab Mon Sep 17 00:00:00 2001 From: Nathan Young Date: Sun, 15 Nov 2026 14:05:21 -0500 Subject: [PATCH 03/10] Answer None at end of input instead of faulting read_line faults at end of input, which suits a program that requires input but not a service that reads requests until its caller closes the stream: a clean shutdown became a fault. The Matrix durable host needs this. Its Python predecessor exits zero when standard input closes, and the recovery suite closes the stream to end a session, so a host that faulted there would report failure for an ordinary shutdown. Add read_line_option, which reads a line exactly as read_line does but answers None at end of input. read_line keeps its contract. A genuine input error still faults, and that is the decision rather than a detail: a reader that must fail closed cannot be handed "no more input" when the truth is "cannot read". Distinguishing the two is not free. A C++ stream reports a genuine end of input and a host read error identically, with eofbit and failbit set and badbit clear, so reading a directory descriptor as standard input is indistinguishable from an empty pipe by stream state alone. Only errno separates them, so both providers clear errno immediately before the read and inspect it only when nothing was extracted. The ambiguous case is a failure: a reader that stops early on a healthy stream is a visible bug, while one that reports success after an unread request is a silent one. The surface rides the existing checked ordinary-I/O bridge, so it is lowered once and reaches the interpreter, AOT and JIT routes without separate codegen. Paired Ny and Matrix fixtures cover several lines then a clean stop, a final line without a terminator, and empty input. A separate case feeds a directory descriptor as standard input and requires a fault with no clean-stop output, which is the check that fails if the implementation reads stream state instead of errno. Co-Authored-By: Claude Opus 5 --- docs/design/NIL-0030-end-of-input.md | 57 +++++++++++++++++++ docs/design/README.md | 1 + docs/standard-library/index.md | 7 ++- nilcompiler/src/native_runtime.cpp | 18 ++++++ nilcompiler/src/ordinary_io_intrinsic.hpp | 2 + nilcompiler/src/vm.cpp | 22 +++++++ nilstd/src/io/console.ny | 7 +++ .../fixtures/console-input-option.matrix | 20 +++++++ tests/tools/fixtures/console-input-option.ny | 20 +++++++ tests/tools/native_console_contract.py | 33 +++++++++++ 10 files changed, 186 insertions(+), 1 deletion(-) create mode 100644 docs/design/NIL-0030-end-of-input.md create mode 100644 tests/tools/fixtures/console-input-option.matrix create mode 100644 tests/tools/fixtures/console-input-option.ny diff --git a/docs/design/NIL-0030-end-of-input.md b/docs/design/NIL-0030-end-of-input.md new file mode 100644 index 00000000..4ccf3f52 --- /dev/null +++ b/docs/design/NIL-0030-end-of-input.md @@ -0,0 +1,57 @@ +# NIL-0030: Reading a line without faulting at end of input + +- **Status:** Implemented additive surface on every execution route; release + SDK qualification remains separate. + +## Motivation + +`read_line` faults at end of input. That suits a program that requires input, +but not a service that reads requests until its caller closes the stream: a +clean shutdown became a fault, so a long-running reader written in Ny or Matrix +could not terminate normally. + +The Matrix-authored Enigma durable host surfaced this. Its Python predecessor +exits zero when standard input closes, and its recovery suite closes the +stream to end a session, so a host that faulted there would report failure for +an ordinary shutdown and leave a crash report behind. + +## Decision + +Add `read_line_option`, which reads a line exactly as `read_line` does but +answers `None` at end of input instead of faulting. `read_line` keeps its +contract; nothing that reads input today changes behavior. + +A genuine input error still faults. This is the substance of the decision +rather than a detail: a reader that must fail closed cannot be handed "no more +input" when the truth is "cannot read". Shutting down cleanly on a broken +stream would silently convert an I/O failure into a successful, quiet exit. + +## Distinguishing the two is not free + +A C++ stream reports a genuine end of input and a host read error identically: +`eofbit` and `failbit` set, `badbit` clear. Reading a directory descriptor as +standard input, for example, is indistinguishable from an empty pipe by stream +state alone. Only `errno` separates them, so both providers clear `errno` +immediately before the read and inspect it only when no characters were +extracted. A nonzero `errno` is a failure; zero is end of input. + +Treating the ambiguous case as a failure is deliberate. A reader that stops +early on a healthy stream is a visible bug; a reader that reports success after +an unread request is a silent one. + +A final line without a terminator is still a line, as with `read_line`. Native +text cannot contain NUL, so native input rejects that byte explicitly. + +## Validation + +The surface rides the existing checked ordinary-I/O bridge, so it is lowered +once and reaches the interpreter, AOT and JIT routes without separate codegen. +Paired Ny and Matrix fixtures cover several lines then a clean stop, a final +line without a terminator, and empty input, across those routes. A separate +case feeds a directory descriptor as standard input and requires a fault with +no clean-stop output, which is the check that would fail if the implementation +read stream state instead of `errno`. + +As with NIL-0028 and NIL-0029, source declarations alone do not give an +installed SDK the new provider, and release qualification is independent work. +See the [console reference](../standard-library/index.md). diff --git a/docs/design/README.md b/docs/design/README.md index c734e9b8..3c46736e 100644 --- a/docs/design/README.md +++ b/docs/design/README.md @@ -56,6 +56,7 @@ not assigned architecture identifiers. | NIL-0027 | [Multiline formatted text and structured markup literals](NIL-0027-structured-markup.md) | Proposed; staged, nothing shipped | | NIL-0028 | [Durable publication and context-owned file locks](NIL-0028-durable-files-and-locks.md) | Implemented additive POSIX source-runtime profile; installed/release SDK qualification separate | | NIL-0029 | [Private directory creation, metadata verdicts, and content digests](NIL-0029-private-entries-and-digests.md) | Implemented additive POSIX source-runtime profile with a portable digest; installed/release SDK qualification separate | +| NIL-0030 | [Reading a line without faulting at end of input](NIL-0030-end-of-input.md) | Implemented additive surface on every execution route; installed/release SDK qualification separate | | NIL-0093 | [Executable context is artifact self-description](NIL-0093-executable-context.md) | Implemented within the documented inspection profile | ## Retained Ny feature references diff --git a/docs/standard-library/index.md b/docs/standard-library/index.md index 50135b25..57287b84 100644 --- a/docs/standard-library/index.md +++ b/docs/standard-library/index.md @@ -121,7 +121,12 @@ The active tree includes these deliberately scoped families: Console output, `nil.std.io.read_line`, and `flush` support the interpreter, native executables, and LLVM JIT. Line input preserves bytes except for the trailing LF; an empty line and a final nonempty line without LF are valid. -EOF and input errors fault explicitly. On POSIX, CR is preserved. Native text +EOF and input errors fault explicitly. +`read_line_option` reads the same way but answers `None` at end of input, so a +reader whose caller closes the stream can stop cleanly; an input error still +faults, because something that must fail closed cannot be handed "no more +input" when the truth is "cannot read". See +[NIL-0030](../design/NIL-0030-end-of-input.md). On POSIX, CR is preserved. Native text uses a NUL-terminated ABI and rejects embedded NUL input; the interpreter can retain that byte. Input publishes pending console output before reading, and `flush` publishes standard output explicitly. Native input text is managed by diff --git a/nilcompiler/src/native_runtime.cpp b/nilcompiler/src/native_runtime.cpp index b202ef71..6941938a 100644 --- a/nilcompiler/src/native_runtime.cpp +++ b/nilcompiler/src/native_runtime.cpp @@ -1713,6 +1713,24 @@ std::int32_t nyrt_io_v1(const char *operation, std::uint64_t first, *value = 1; return 1; } + if (name == "console.read_line_option") { + std::fflush(stdout); + std::string line; + // eofbit and failbit are set both at a genuine end of input and on a + // host read error, with badbit clear in each case, so the stream state + // cannot tell them apart. errno can: clear it immediately before the + // read and inspect it only when nothing was extracted. The ambiguous + // case is a failure, never a clean end of input. + errno = 0; + if (!std::getline(std::cin, line)) { + if (errno != 0) return fail("input is unavailable"); + return 1; + } + if (line.find('\0') != std::string::npos) + return fail("embedded NUL is unsupported by native text"); + if (!output_text(std::string_view(line))) return 0; + return 2; + } if (name == "file.create_private_directory") { const auto created = ny::detail::create_private_directory_utf8(text(first)); if (!created.ok) { set_error(error, created.error); return 0; } diff --git a/nilcompiler/src/ordinary_io_intrinsic.hpp b/nilcompiler/src/ordinary_io_intrinsic.hpp index 182f3828..1efc7d3e 100644 --- a/nilcompiler/src/ordinary_io_intrinsic.hpp +++ b/nilcompiler/src/ordinary_io_intrinsic.hpp @@ -59,6 +59,8 @@ inline std::optional intrinsic(const std::string &name) { if (name == "checksum.sha256_hex") return Contract{{"array"}, "text", Output::result}; if (name == "environment.get") return Contract{{"text"}, "text", Output::option}; + if (name == "console.read_line_option") + return Contract{{}, "text", Output::option}; if (name == "file.handle_open") return Contract{{"text", "i32"}, "i64"}; if (name == "file.handle_read" || name == "file.handle_write") return Contract{{"i64", "ptr", "i32"}, "i32"}; diff --git a/nilcompiler/src/vm.cpp b/nilcompiler/src/vm.cpp index 56805522..337374a6 100644 --- a/nilcompiler/src/vm.cpp +++ b/nilcompiler/src/vm.cpp @@ -3749,6 +3749,28 @@ void VM::executeInstruction(const Instruction &instr) { pushStack(line); return; } + if (lib_name == "intrinsic" && fn_name == "console.read_line_option") { + std::string line; + EnumValue result; + // A C++ stream reports a genuine end of input and a host read error with + // the same state: eofbit and failbit set, badbit clear. Only errno tells + // them apart, so it is cleared immediately before the read and inspected + // only when no characters were extracted. Something that must fail + // closed cannot be handed "no more input" when the truth is "cannot + // read", so the ambiguous case is treated as a failure. + errno = 0; + if (std::getline(inputStream(), line)) { + result.variant_name = "Option::Some"; + result.payloads.push_back(line); + } else if (errno != 0) { + throw std::runtime_error("console.read_line_option: input is unavailable"); + } else { + // End of input is an answer, not a failure: a reader can stop cleanly. + result.variant_name = "Option::None"; + } + pushStack(result); + return; + } if (lib_name == "intrinsic" && fn_name == "console.flush") { outputStream() << std::flush; return; diff --git a/nilstd/src/io/console.ny b/nilstd/src/io/console.ny index 91af8260..bf39a8b2 100644 --- a/nilstd/src/io/console.ny +++ b/nilstd/src/io/console.ny @@ -8,6 +8,13 @@ import nil.std.core # rejects that byte explicitly. Flushes pending console output before reading. @intrinsic("console.read_line") pub fn read_line() -> text + +# Reads one line like read_line, but answers None at end of input instead of +# faulting, so a reader can stop cleanly when its input closes. A genuine +# input error still faults: a broken stream must never be mistaken for a +# clean end of input by something that has to fail closed. +@intrinsic("console.read_line_option") +pub fn read_line_option() -> Option end fn # Basic Output diff --git a/tests/tools/fixtures/console-input-option.matrix b/tests/tools/fixtures/console-input-option.matrix new file mode 100644 index 00000000..68b2a4d9 --- /dev/null +++ b/tests/tools/fixtures/console-input-option.matrix @@ -0,0 +1,20 @@ +!!! Clean end of input, paired with the Ny fixture. read_line faults at EOF; +!!! read_line_option answers None, so a reader can stop without failing. +book nil.tests.console_input_option + +read everything from nil.std.core +read read_line_option, writeln from nil.std.io + +main returns override integer begin paragraph + variable count as number is 0 + repeat forever + value received is read_line_option with nothing + when received.is_none with nothing then + stop repeating + end when + set count to count plus 1 + say "line:" plus (received.unwrap with nothing) + end repeat + say "eof:" plus (formatted "{count}") + give 0 +end paragraph diff --git a/tests/tools/fixtures/console-input-option.ny b/tests/tools/fixtures/console-input-option.ny new file mode 100644 index 00000000..b78fc837 --- /dev/null +++ b/tests/tools/fixtures/console-input-option.ny @@ -0,0 +1,20 @@ +# Clean end of input, paired with the Matrix fixture. read_line faults at EOF; +# read_line_option answers None, so a reader can stop without failing. +module nil.tests.console_input_option + +import nil.std.core +import nil.std.io + +fn main() -> i32 + let mut count = 0 + loop + match read_line_option() + Option.None -> break + Option.Some(line) -> + count = count + 1 + writeln("line:" + line) + end match + end loop + writeln("eof:" + count.to_text()) + return 0 +end fn diff --git a/tests/tools/native_console_contract.py b/tests/tools/native_console_contract.py index a534c0e1..73df2882 100644 --- a/tests/tools/native_console_contract.py +++ b/tests/tools/native_console_contract.py @@ -125,6 +125,32 @@ def check_prompt(command): assert len(sites) == 1 and sites[0]['allocated_bytes'] == 9, sites assert 'read_line' in sites[0]['function'], sites + # read_line_option: end of input is an answer, a broken stream is not. + option_commands = [] + for language in ('ny', 'matrix'): + source = fixtures / ('console-input-option.' + language) + nil = root / (language + '-option.nil') + compile_flags = [tools['compiler'], '--quiet', '--no-bundle', '--no-stdlib', + '--sdk-path', tools['stdlib']] + run([*compile_flags, '-o', nil, source]) + vm = [tools['interpreter'], '--no-ai', nil] + native = build_native(nil, language + '-option', False) + jit = [*compile_flags, '--native', '--jit', + '-o', root / (language + '-option.jit'), source] + option_commands.append(native) + for command in (vm, native, jit): + # Several lines, then a clean stop. + result = run(command, data=b'alpha\nbeta\n') + assert result.stdout == b'line:alpha\nline:beta\neof:2\n', result + assert not result.stderr, result + # A final line without a terminator is still a line. + result = run(command, data=b'solo') + assert result.stdout == b'line:solo\neof:1\n', result + # Empty input ends immediately instead of faulting. + result = run(command, data=b'') + assert result.stdout == b'eof:0\n' and not result.stderr, result + checks += 3 + # A directory descriptor is readable at the OS level but cannot yield # stream input. Exercise host read errors separately from clean EOF. if os.name == 'posix': @@ -133,6 +159,13 @@ def check_prompt(command): for command in native_commands: result = run(command, status=1, stdin=descriptor) assert b'input is unavailable or reached EOF' in result.stderr, result + # The option form must not turn a broken stream into a clean + # None: something that has to fail closed depends on the + # difference between "no more input" and "cannot read". + for command in option_commands: + result = run(command, status=1, stdin=descriptor) + assert b'input is unavailable' in result.stderr, result + assert b'eof:' not in result.stdout, result finally: os.close(descriptor) From 5eb34b9604165a043d923275fe522287a63486d6 Mon Sep 17 00:00:00 2001 From: Nathan Young Date: Sun, 15 Nov 2026 14:17:37 -0500 Subject: [PATCH 04/10] Give random_hex a native provider A Matrix application that draws a fresh identifier per session or per recovery could not be built natively: random.hex was interpreter-only, so native code generation refused the reachable declaration. The Enigma durable host draws a new incarnation on every recovery and hit exactly that. Route the intrinsic through the checked ordinary-I/O bridge and provide it from the same entropy helper and hex encoding the interpreter uses, so a draw does not depend on which route asked for it. Riding the bridge means the interpreter, AOT and JIT routes are all covered without separate codegen. random_bytes stays interpreter-only on purpose. It returns arbitrary bytes, which can include NUL, and native text is a NUL-terminated ABI, so that form cannot cross it. Callers that need raw bytes on a native route can draw hex and decode. Paired Ny and Matrix fixtures check the encoding, the lengths for one, 16 and 32 bytes, that independent draws differ, and that a zero, negative or oversized count is an error rather than a short draw, across every route. The existing secure-random fixtures stay interpreter-only because they also exercise random_bytes. Co-Authored-By: Claude Opus 5 --- CMakeLists.txt | 16 +++++++ docs/standard-library/index.md | 8 +++- docs/standard-library/random.md | 10 +++- nilcompiler/src/native_runtime.cpp | 10 ++++ nilcompiler/src/ordinary_io_intrinsic.hpp | 4 ++ tests/language/secure-hex-matrix.matrix | 58 +++++++++++++++++++++++ tests/language/secure-hex-matrix.stdout | 1 + tests/language/secure-hex.ny | 45 ++++++++++++++++++ tests/language/secure-hex.stdout | 1 + 9 files changed, 150 insertions(+), 3 deletions(-) create mode 100644 tests/language/secure-hex-matrix.matrix create mode 100644 tests/language/secure-hex-matrix.stdout create mode 100644 tests/language/secure-hex.ny create mode 100644 tests/language/secure-hex.stdout diff --git a/CMakeLists.txt b/CMakeLists.txt index fc7404b5..b88e804e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3407,6 +3407,22 @@ if(BUILD_TESTING) --compiler-arg=${CMAKE_CURRENT_SOURCE_DIR}/nilstd/src ) endforeach() + foreach(nil_entropy_fixture IN ITEMS secure-hex secure-hex-matrix) + if(nil_entropy_fixture MATCHES "-matrix$") + set(nil_entropy_suffix matrix) + else() + set(nil_entropy_suffix ny) + endif() + add_ny_route_test( + ny.routes.${nil_entropy_fixture} + --source "${CMAKE_CURRENT_SOURCE_DIR}/tests/language/${nil_entropy_fixture}.${nil_entropy_suffix}" + --expected-stdout "${CMAKE_CURRENT_SOURCE_DIR}/tests/language/${nil_entropy_fixture}.stdout" + --expected-exit 0 + --routes all + --compiler-arg=--sdk-path + --compiler-arg=${CMAKE_CURRENT_SOURCE_DIR}/nilstd/src + ) + endforeach() add_ny_route_test( ny.routes.math-runtime --source "${CMAKE_CURRENT_SOURCE_DIR}/tests/language/math-runtime.ny" diff --git a/docs/standard-library/index.md b/docs/standard-library/index.md index 57287b84..62cdb4bf 100644 --- a/docs/standard-library/index.md +++ b/docs/standard-library/index.md @@ -237,8 +237,12 @@ experimental, and active `nil.std.system` does not include subprocess execution or agent messaging. TCP stream sockets are active as of `nil.std.net.socket`, and secure random -values as of `nil.std.security.random`; both are interpreter-backed and their -contracts are checked by dedicated fixtures. See the +values as of `nil.std.security.random`; their contracts are checked by +dedicated fixtures. Sockets are interpreter-backed. Of the secure-random +surface only `random_hex` has a native provider, because an application that +draws an identifier per recovery has to be buildable natively; `random_bytes` +returns arbitrary bytes, which can include NUL, and native text is a +NUL-terminated ABI, so it stays interpreter-only. See the [socket reference](sockets.md) and the secure-random section of the [random reference](random.md). `http.send` and the higher-level transports — HTTP client and server, WebSocket, IMAP, SMTP — remain quarantined, now for diff --git a/docs/standard-library/random.md b/docs/standard-library/random.md index 11db0eda..eb8af0a1 100644 --- a/docs/standard-library/random.md +++ b/docs/standard-library/random.md @@ -110,7 +110,15 @@ reveal the stream. | `random_bytes(byte_count: i64) -> Result` | Random bytes as they are, carried as text. | | `random_below(bound: i64) -> Result` | A uniform whole number in `[0, bound)`. | -Interpreter-backed. The native route does not carry these yet. +`random_hex` has a native provider and reaches the interpreter, AOT and JIT +routes, drawing from the same kernel source and hex encoding on each, so a +draw does not depend on which route asked for it. An application that needs a +fresh identifier per session or per recovery can therefore be built natively. + +`random_bytes` and `random_below` remain interpreter-only. `random_bytes` +returns arbitrary bytes, which can include NUL, and native text is a +NUL-terminated ABI, so that form cannot cross it; use `random_hex` and decode +if raw bytes are wanted on a native route. `random_hex` is the one to reach for. A credential wants to be text anyway, and hex survives a cookie, a URL, a header and a log line with no further escaping; diff --git a/nilcompiler/src/native_runtime.cpp b/nilcompiler/src/native_runtime.cpp index 6941938a..f664dc92 100644 --- a/nilcompiler/src/native_runtime.cpp +++ b/nilcompiler/src/native_runtime.cpp @@ -12,6 +12,7 @@ #include "nildata.hpp" #include "scalar_text.hpp" +#include "entropy_support.hpp" #include "secure_file_io.hpp" #include "../../common/content_digest.hpp" #include "time_support.hpp" @@ -1713,6 +1714,15 @@ std::int32_t nyrt_io_v1(const char *operation, std::uint64_t first, *value = 1; return 1; } + if (name == "random.hex") { + if (first > static_cast(INT64_MAX)) + return fail("ask for at least one byte"); + // The same kernel entropy source and hex encoding the interpreter uses, + // so a draw does not depend on which route asked for it. + const auto drawn = ny::entropy_support::random_hex(static_cast(first)); + if (!drawn.ok()) { set_error(error, drawn.error); return 0; } + return output_text(std::string_view(drawn.bytes)); + } if (name == "console.read_line_option") { std::fflush(stdout); std::string line; diff --git a/nilcompiler/src/ordinary_io_intrinsic.hpp b/nilcompiler/src/ordinary_io_intrinsic.hpp index 1efc7d3e..90a840c4 100644 --- a/nilcompiler/src/ordinary_io_intrinsic.hpp +++ b/nilcompiler/src/ordinary_io_intrinsic.hpp @@ -61,6 +61,10 @@ inline std::optional intrinsic(const std::string &name) { if (name == "environment.get") return Contract{{"text"}, "text", Output::option}; if (name == "console.read_line_option") return Contract{{}, "text", Output::option}; + // Hex only. random.bytes yields arbitrary bytes, which can include NUL, and + // native text is a NUL-terminated ABI, so that form stays interpreter-only. + if (name == "random.hex") + return Contract{{"i64"}, "text", Output::result}; if (name == "file.handle_open") return Contract{{"text", "i32"}, "i64"}; if (name == "file.handle_read" || name == "file.handle_write") return Contract{{"i64", "ptr", "i32"}, "i32"}; diff --git a/tests/language/secure-hex-matrix.matrix b/tests/language/secure-hex-matrix.matrix new file mode 100644 index 00000000..f75e0990 --- /dev/null +++ b/tests/language/secure-hex-matrix.matrix @@ -0,0 +1,58 @@ +!!! Secure hex draws on every execution route, paired with the Ny fixture. +!!! random_bytes is deliberately absent: it yields arbitrary bytes, which can +!!! include NUL, so it has no native provider and stays interpreter-only. +book nil.tests.secure_hex + +read everything from nil.std.core +read char_at, contains from nil.std.text +read random_hex from nil.std.security + +hex_only receives drawn as text returns boolean begin paragraph + repeat for index from 0 to (the length of drawn) + value character is char_at with s being drawn, index being index + when not (contains with s being "0123456789abcdef", needle being character) then + give no + end when + end repeat + give yes +end paragraph + +draw receives count as number returns text begin paragraph + value drawn is random_hex with byte_count being count + when drawn.is_error with nothing then + give "" + end when + give drawn.unwrap with nothing +end paragraph + +main returns override integer begin paragraph + value identifier is draw with count being 16 + when (the length of identifier) does not equal 32 then + give 1 + end when + when not (hex_only with drawn being identifier) then + give 2 + end when + when (the length of (draw with count being 1)) does not equal 2 then + give 3 + end when + when (the length of (draw with count being 32)) does not equal 64 then + give 4 + end when + !!! Two draws colliding would mean the source is not random at all. + when (draw with count being 16) equals (draw with count being 16) then + give 5 + end when + !!! A count outside the documented range is an error, not a short draw. + when not ((random_hex with byte_count being 0).is_error with nothing) then + give 6 + end when + when not ((random_hex with byte_count being minus 1).is_error with nothing) then + give 7 + end when + when not ((random_hex with byte_count being 1025).is_error with nothing) then + give 8 + end when + say "secure hex draws" + give 0 +end paragraph diff --git a/tests/language/secure-hex-matrix.stdout b/tests/language/secure-hex-matrix.stdout new file mode 100644 index 00000000..648ae352 --- /dev/null +++ b/tests/language/secure-hex-matrix.stdout @@ -0,0 +1 @@ +secure hex draws diff --git a/tests/language/secure-hex.ny b/tests/language/secure-hex.ny new file mode 100644 index 00000000..c5b48500 --- /dev/null +++ b/tests/language/secure-hex.ny @@ -0,0 +1,45 @@ +# Secure hex draws on every execution route, paired with the Matrix fixture. +# random_bytes is deliberately absent: it yields arbitrary bytes, which can +# include NUL, so it has no native provider and stays interpreter-only. +import nil.std.core +import nil.std.io +import nil.std.security +import nil.std.text + +fn require(ok: bool, message: text) + if not ok then panic(message) end if +end fn + +fn hex_only(drawn: text) -> bool + for index in range(drawn.len()) + if not nil::std::text::contains("0123456789abcdef", nil::std::text::char_at(drawn, index)) then + return false + end if + end for + return true +end fn + +fn draw(count: i64) -> text + match nil::std::security::random_hex(count) + Result.Error(message) -> + panic("random_hex rejected a valid count: " + message) + return "" + Result.Ok(value) -> return value + end match +end fn + +fn main() -> i32 + let identifier = draw(16) + require(identifier.len() == 32, "16 bytes is 32 hex characters") + require(hex_only(identifier), "draws are lower-case hex") + require(draw(1).len() == 2, "one byte is two hex characters") + require(draw(32).len() == 64, "32 bytes is 64 hex characters") + # Two draws colliding would mean the source is not random at all. + require(draw(16) != draw(16), "independent draws differ") + # A count outside the documented range is an error, not a short draw. + require(nil::std::security::random_hex(0).is_error(), "zero bytes is rejected") + require(nil::std::security::random_hex(-1).is_error(), "a negative count is rejected") + require(nil::std::security::random_hex(1025).is_error(), "an oversized draw is rejected") + println("secure hex draws") + return 0 +end fn diff --git a/tests/language/secure-hex.stdout b/tests/language/secure-hex.stdout new file mode 100644 index 00000000..648ae352 --- /dev/null +++ b/tests/language/secure-hex.stdout @@ -0,0 +1 @@ +secure hex draws From 84e76aeacf0802babb67ce6f7c636c31312e5249 Mon Sep 17 00:00:00 2001 From: Nathan Young Date: Fri, 20 Nov 2026 21:49:09 -0500 Subject: [PATCH 05/10] Reject slash-terminated directory entries before no-follow checks --- docs/standard-library/durable-files.md | 7 ++++++- nilcompiler/src/secure_file_io.cpp | 16 ++++++++++++++-- nilcompiler/src/secure_file_io.hpp | 2 ++ nilstd/src/io/file.ny | 4 +++- tests/durable_file_io_tests.cpp | 25 +++++++++++++++++++++++++ 5 files changed, 50 insertions(+), 4 deletions(-) diff --git a/docs/standard-library/durable-files.md b/docs/standard-library/durable-files.md index 48d0ed05..5818aed0 100644 --- a/docs/standard-library/durable-files.md +++ b/docs/standard-library/durable-files.md @@ -43,6 +43,10 @@ recover rather than assume the previous file remains or retry blindly. `sync_directory` synchronizes an existing directory selected without following its final component. It is useful after separately controlled namespace changes, including initial directory/lock creation. Its ancestors remain trusted. +Directory synchronization and inspection reject trailing `/` separators except +for filesystem-root paths such as `/`. Pass a named directory without trailing +separators: POSIX otherwise resolves a slash-terminated symlink before applying +the final-component no-follow rule. `write_bytes_atomic` retains its visibility-only contract. `File.flush` retains its stream-flush contract; neither acquires the new durability guarantee. @@ -102,7 +106,8 @@ not durably publish the new name; call `sync_directory` when that matters. effective user, singly linked, and exactly mode `0600`. `is_private_directory` asks whether it is a directory owned by the effective user with exactly mode `0700`. Neither follows a final symlink, so a link is judged as itself and does -not inherit its target's verdict. +not inherit its target's verdict. Directory inspection uses the same +trailing-separator operand rule as `sync_directory`. An `Error` means the entry could not be inspected, which is distinct from a verdict of `false`. Both are distinct from being safe to use: these inspect a diff --git a/nilcompiler/src/secure_file_io.cpp b/nilcompiler/src/secure_file_io.cpp index e587c697..e0ebd838 100644 --- a/nilcompiler/src/secure_file_io.cpp +++ b/nilcompiler/src/secure_file_io.cpp @@ -120,6 +120,18 @@ path_from_api_string(const std::string &path) { } } +#ifndef _WIN32 +// A trailing separator makes POSIX lstat/open resolve the preceding symlink +// as a directory before their no-follow rule applies. Keep a named final +// component for entry inspection and directory synchronization. A pathname +// consisting entirely of separators names the root and has no such symlink. +bool valid_directory_entry_operand(const std::filesystem::path &path) { + const auto &native = path.native(); + return !native.empty() && + (native.back() != '/' || native.find_first_not_of('/') == native.npos); +} +#endif + } // namespace #ifndef _WIN32 @@ -645,7 +657,7 @@ AtomicFileWrite sync_directory_utf8(const std::string &path) { return {false, "file.sync_directory: unsupported platform"}; #else const auto native_path = path_from_utf8_string(path); - if (!native_path) + if (!native_path || !valid_directory_entry_operand(*native_path)) return {false, "file.sync_directory: invalid directory path"}; const int flags = O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK; UniqueFileDescriptor directory(::open(native_path->c_str(), flags)); @@ -736,7 +748,7 @@ FileCheck private_directory_utf8(const std::string &path) { return {false, false, "file.is_private_directory: unsupported platform"}; #else const auto native_path = path_from_utf8_string(path); - if (!native_path) + if (!native_path || !valid_directory_entry_operand(*native_path)) return {false, false, "file.is_private_directory: invalid directory path"}; struct stat status {}; if (::lstat(native_path->c_str(), &status) != 0) diff --git a/nilcompiler/src/secure_file_io.hpp b/nilcompiler/src/secure_file_io.hpp index 3e185786..21328199 100644 --- a/nilcompiler/src/secure_file_io.hpp +++ b/nilcompiler/src/secure_file_io.hpp @@ -70,6 +70,8 @@ AtomicFileWrite write_file_atomic_utf8(const std::string &path, // POSIX only. Directory synchronization is explicit; durable publication // synchronizes the same anchored directory used to publish the destination. // An error after publication does not imply that the old destination remains. +// Directory synchronization and directory metadata inspection reject trailing +// separators except for filesystem-root paths, preserving no-follow rules. AtomicFileWrite sync_directory_utf8(const std::string &path); AtomicFileWrite write_file_durable_utf8(const std::string &path, const std::vector &bytes, diff --git a/nilstd/src/io/file.ny b/nilstd/src/io/file.ny index bc2cb192..8b3af980 100644 --- a/nilstd/src/io/file.ny +++ b/nilstd/src/io/file.ny @@ -115,7 +115,9 @@ pub fn create_private_directory(path: text) -> Result pub fn is_private_regular_file(path: text) -> Result # Is this entry a directory owned by the effective user with exactly mode -# 0700? The same inspection limits as is_private_regular_file apply. +# 0700? The same inspection limits as is_private_regular_file apply. Trailing +# separators are rejected except for filesystem-root paths, preserving the +# final-component no-follow rule. @intrinsic("file.is_private_directory") pub fn is_private_directory(path: text) -> Result diff --git a/tests/durable_file_io_tests.cpp b/tests/durable_file_io_tests.cpp index 4f2c8cef..8883b458 100644 --- a/tests/durable_file_io_tests.cpp +++ b/tests/durable_file_io_tests.cpp @@ -168,6 +168,19 @@ void check_directory_sync(const fs::path &root) { const auto linked = root / "private-sync-marker-link"; fs::create_directory_symlink(root, linked); require_error(ny::detail::sync_directory_utf8(linked.u8string()), "private-sync-marker"); + for (const auto *suffix : {"/", "///"}) { + require_error(ny::detail::sync_directory_utf8(linked.u8string() + suffix), + "private-sync-marker"); + // Real directories use the same operand rule, without trying to infer the + // entry kind by following a slash-terminated pathname first. + require_error(ny::detail::sync_directory_utf8(root.u8string() + suffix), + root.filename().u8string()); + } + for (const auto *root_operand : {"/", "///"}) { + const auto root_sync = ny::detail::sync_directory_utf8(root_operand); + require(root_sync.error != "file.sync_directory: invalid directory path", + "root directory was rejected as a trailing-separator operand"); + } require_error(ny::detail::sync_directory_utf8(""), "private-sync-marker"); require_error(ny::detail::sync_directory_utf8(std::string("private-sync-marker\0tail", 24)), "private-sync-marker"); @@ -471,6 +484,18 @@ void check_private_metadata(const fs::path &root) { "cannot create fixture directory symlink"); verdict(ny::detail::private_directory_utf8(directory_link.u8string()), false, "a symlink to a private directory is not a private directory"); + for (const auto *suffix : {"/", "///"}) { + require_error(ny::detail::private_directory_utf8(directory_link.u8string() + suffix), + "directory-link"); + require_error(ny::detail::private_directory_utf8(created.u8string() + suffix), + "owner-only"); + } + // Root has no final named entry to follow. Its privacy verdict depends on + // the actual owner/mode, but it must remain an inspectable operand. + for (const auto *root_operand : {"/", "///"}) { + require(ny::detail::private_directory_utf8(root_operand).ok, + "filesystem-root metadata could not be inspected"); + } // A second hard link means another name can reach the same inode. const auto shared = root / "shared"; From 668a9d6fc1e44791f15f2f676ecc718422df3622 Mon Sep 17 00:00:00 2001 From: Nathan Young Date: Fri, 20 Nov 2026 21:49:10 -0500 Subject: [PATCH 06/10] Require a clean EOF before returning no console input --- CMakeLists.txt | 6 + docs/design/NIL-0030-end-of-input.md | 24 ++-- nilcompiler/src/native_runtime.cpp | 11 +- nilcompiler/src/vm.cpp | 14 +- tests/console_input_state_tests.cpp | 204 +++++++++++++++++++++++++++ 5 files changed, 237 insertions(+), 22 deletions(-) create mode 100644 tests/console_input_state_tests.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index b88e804e..2583037a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -101,6 +101,12 @@ install( install(FILES LICENSE DESTINATION ".") if(BUILD_TESTING) + add_executable(nil_console_input_state_tests tests/console_input_state_tests.cpp) + target_compile_features(nil_console_input_state_tests PRIVATE cxx_std_17) + target_include_directories(nil_console_input_state_tests PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/nilcompiler/src") + target_link_libraries(nil_console_input_state_tests PRIVATE nilcompiler_core) + add_test(NAME nil.console-input-state COMMAND $) + set_tests_properties(nil.console-input-state PROPERTIES LABELS "console;runtime;embedding" TIMEOUT 30) add_executable(nil_durable_file_io_tests tests/durable_file_io_tests.cpp nilcompiler/src/secure_file_io.cpp) diff --git a/docs/design/NIL-0030-end-of-input.md b/docs/design/NIL-0030-end-of-input.md index 4ccf3f52..e1a6c82f 100644 --- a/docs/design/NIL-0030-end-of-input.md +++ b/docs/design/NIL-0030-end-of-input.md @@ -28,12 +28,17 @@ stream would silently convert an I/O failure into a successful, quiet exit. ## Distinguishing the two is not free -A C++ stream reports a genuine end of input and a host read error identically: -`eofbit` and `failbit` set, `badbit` clear. Reading a directory descriptor as -standard input, for example, is indistinguishable from an empty pipe by stream -state alone. Only `errno` separates them, so both providers clear `errno` -immediately before the read and inspect it only when no characters were -extracted. A nonzero `errno` is a failure; zero is end of input. +Some host read errors leave an EOF-looking C++ stream state: `eofbit` and +`failbit` set, `badbit` clear. Reading a directory descriptor as standard input, +for example, can resemble an empty pipe by stream state alone. Both providers +therefore clear `errno` immediately before the read and inspect it when the +read fails. A nonzero `errno` is a failure. + +Zero `errno` is not sufficient to establish end of input. An embedding host +can supply a stream with `failbit` or `badbit` set without a matching host error. +`None` requires `eofbit` set, `badbit` clear, and zero `errno`; every other failed +read faults. A final line that successfully extracts characters is still +`Some`, including when reaching EOF sets `eofbit` during that read. Treating the ambiguous case as a failure is deliberate. A reader that stops early on a healthy stream is a visible bug; a reader that reports success after @@ -49,8 +54,11 @@ once and reaches the interpreter, AOT and JIT routes without separate codegen. Paired Ny and Matrix fixtures cover several lines then a clean stop, a final line without a terminator, and empty input, across those routes. A separate case feeds a directory descriptor as standard input and requires a fault with -no clean-stop output, which is the check that would fail if the implementation -read stream state instead of `errno`. +no clean-stop output, which catches an implementation that consults stream +state alone. Embedded VM text/binary and native-provider checks supply failed +streams with zero `errno`, including `badbit` together with `eofbit`, and require +a failure rather than `None`. They also preserve blank lines, final nonempty +lines, repeated clean EOF, and the original required `read_line` EOF failure. As with NIL-0028 and NIL-0029, source declarations alone do not give an installed SDK the new provider, and release qualification is independent work. diff --git a/nilcompiler/src/native_runtime.cpp b/nilcompiler/src/native_runtime.cpp index f664dc92..9d598d84 100644 --- a/nilcompiler/src/native_runtime.cpp +++ b/nilcompiler/src/native_runtime.cpp @@ -1726,14 +1726,13 @@ std::int32_t nyrt_io_v1(const char *operation, std::uint64_t first, if (name == "console.read_line_option") { std::fflush(stdout); std::string line; - // eofbit and failbit are set both at a genuine end of input and on a - // host read error, with badbit clear in each case, so the stream state - // cannot tell them apart. errno can: clear it immediately before the - // read and inspect it only when nothing was extracted. The ambiguous - // case is a failure, never a clean end of input. + // Some host read errors look like EOF but set errno. Embedded streams + // can also fail without setting errno, so require a clean EOF state as + // well as an error-free host read before answering None. errno = 0; if (!std::getline(std::cin, line)) { - if (errno != 0) return fail("input is unavailable"); + if (errno != 0 || !std::cin.eof() || std::cin.bad()) + return fail("input is unavailable"); return 1; } if (line.find('\0') != std::string::npos) diff --git a/nilcompiler/src/vm.cpp b/nilcompiler/src/vm.cpp index 337374a6..b18ff610 100644 --- a/nilcompiler/src/vm.cpp +++ b/nilcompiler/src/vm.cpp @@ -3752,17 +3752,15 @@ void VM::executeInstruction(const Instruction &instr) { if (lib_name == "intrinsic" && fn_name == "console.read_line_option") { std::string line; EnumValue result; - // A C++ stream reports a genuine end of input and a host read error with - // the same state: eofbit and failbit set, badbit clear. Only errno tells - // them apart, so it is cleared immediately before the read and inspected - // only when no characters were extracted. Something that must fail - // closed cannot be handed "no more input" when the truth is "cannot - // read", so the ambiguous case is treated as a failure. + auto &input = inputStream(); + // Some host read errors set errno while leaving an EOF-looking stream + // state. Conversely, an embedded stream can fail without setting errno. + // Only a clean EOF is None; both witnesses must permit that answer. errno = 0; - if (std::getline(inputStream(), line)) { + if (std::getline(input, line)) { result.variant_name = "Option::Some"; result.payloads.push_back(line); - } else if (errno != 0) { + } else if (errno != 0 || !input.eof() || input.bad()) { throw std::runtime_error("console.read_line_option: input is unavailable"); } else { // End of input is an answer, not a failure: a reader can stop cleanly. diff --git a/tests/console_input_state_tests.cpp b/tests/console_input_state_tests.cpp new file mode 100644 index 00000000..9ca0c4a8 --- /dev/null +++ b/tests/console_input_state_tests.cpp @@ -0,0 +1,204 @@ +// An embedding host may supply a failed C++ stream without a corresponding +// errno. Such a stream is not a clean end of input on either runtime route. +#include "codegen.hpp" +#include "native_runtime.hpp" +#include "nil_loader.hpp" +#include "vm.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +unsigned checks = 0; + +void require(bool condition, const std::string &message) { + ++checks; + if (!condition) throw std::runtime_error(message); +} + +struct Program { + std::vector code; + std::unordered_map constants; +}; + +Program fixture(bool binary, bool optional) { + ny::nil_module module; + module.module_name = "console_input_state"; + const std::string result = optional ? "nil::std::core::Option" : "text"; + module.enums = {{"nil::std::core::Option", + {{"None", ""}, {"Some", "text"}}}}; + ny::nil_function read; + read.name = "read"; + read.return_type = result; + read.body = {{"INTEROP_CALL", {"intrinsic", + optional ? "console.read_line_option" : "console.read_line", "0", result}}, + {"RET", {}}}; + module.functions.push_back(read); + std::ostringstream serialized(std::ios::out | std::ios::binary); + if (binary) { + ny::codegen_options options; + ny::nil_binary_writer writer(serialized, options); + writer.emit_binary_module(module); + } else { + ny::nil_writer writer(serialized); + writer.emit_text_module(module); + } + std::istringstream input(serialized.str(), std::ios::in | std::ios::binary); + Program program; + program.code = binary ? ny::parseBinaryProgram(input, program.constants) + : ny::parseProgram(input, program.constants); + return program; +} + +void vm_answer(ny::VM &vm, const char *variant, const std::string &line = {}) { + vm.callFunction("read", 0); + require(!vm.getStack().empty(), "VM console input returned no result"); + const auto &answer = std::get(vm.getStack().back()); + require(answer.variant_name == variant, "VM console input returned the wrong variant"); + if (answer.variant_name == "Option::Some") { + require(answer.payloads.size() == 1 && + std::get(answer.payloads.front()) == line, + "VM console input changed the line"); + } else { + require(answer.payloads.empty(), "VM EOF carried a line payload"); + } +} + +void vm_contract(bool binary) { + const auto program = fixture(binary, true); + const std::ios::iostate failures[] = { + std::ios::failbit, std::ios::badbit, + std::ios::badbit | std::ios::eofbit, + std::ios::badbit | std::ios::failbit | std::ios::eofbit}; + for (const auto state : failures) { + ny::VM vm; + std::istringstream input("unread\n"); + input.setstate(state); + vm.setInputStream(input); + vm.loadProgram(program.code, program.constants); + bool failed = false; + errno = 0; + try { + vm.callFunction("read", 0); + } catch (const std::runtime_error &error) { + failed = std::string(error.what()).find( + "console.read_line_option: input is unavailable") != std::string::npos; + } + require(failed, "VM accepted a failed embedded stream as clean EOF"); + } + { + ny::VM vm; + std::istringstream input("\nlast"); + vm.setInputStream(input); + vm.loadProgram(program.code, program.constants); + vm_answer(vm, "Option::Some", ""); + vm_answer(vm, "Option::Some", "last"); + errno = EACCES; // An old unrelated host error is not an input error. + vm_answer(vm, "Option::None"); + vm_answer(vm, "Option::None"); + } + { + ny::VM vm; + std::istringstream input; + vm.setInputStream(input); + vm.loadProgram(program.code, program.constants); + vm_answer(vm, "Option::None"); + } + { + const auto required_line = fixture(binary, false); + ny::VM vm; + std::istringstream input; + vm.setInputStream(input); + vm.loadProgram(required_line.code, required_line.constants); + bool failed = false; + try { + vm.callFunction("read", 0); + } catch (const std::runtime_error &error) { + failed = std::string(error.what()).find( + "console.read_line: input is unavailable or reached EOF") != std::string::npos; + } + require(failed, "VM required read_line lost its existing EOF failure contract"); + } +} + +class cin_buffer { +public: + explicit cin_buffer(std::streambuf *buffer) + : previous_state_(std::cin.rdstate()), previous_buffer_(std::cin.rdbuf(buffer)) {} + ~cin_buffer() { + std::cin.rdbuf(previous_buffer_); + std::cin.clear(previous_state_); + } +private: + std::ios::iostate previous_state_; + std::streambuf *previous_buffer_; +}; + +void native_answer(std::int32_t expected, const std::string &line = {}) { + std::uint64_t value = UINT64_MAX; + const char *error = nullptr; + const auto status = nyrt_io_v1("console.read_line_option", 0, 0, 0, &value, &error); + require(status == expected && !error, "native console input returned the wrong status"); + if (expected == 2) { + const auto *text = reinterpret_cast(static_cast(value)); + require(text && text == line, "native console input changed the line"); + } else { + require(value == 0, "native EOF carried a line payload"); + } +} + +void native_contract() { + nyrt_context_begin(0, nullptr); + const std::ios::iostate failures[] = { + std::ios::failbit, std::ios::badbit, + std::ios::badbit | std::ios::eofbit, + std::ios::badbit | std::ios::failbit | std::ios::eofbit}; + for (const auto state : failures) { + std::istringstream input("unread\n"); + cin_buffer redirect(input.rdbuf()); + std::cin.setstate(state); + std::uint64_t value = UINT64_MAX; + const char *error = nullptr; + errno = 0; + const auto status = nyrt_io_v1("console.read_line_option", 0, 0, 0, &value, &error); + require(status == 0 && error && std::string(error) == + "console.read_line_option: input is unavailable", + "native accepted a failed embedded stream as clean EOF"); + require(value == 0, "native failed read returned a line payload"); + } + { + std::istringstream input("\nlast"); + cin_buffer redirect(input.rdbuf()); + native_answer(2, ""); + native_answer(2, "last"); + errno = EACCES; + native_answer(1); + native_answer(1); + } + { + std::istringstream input; + cin_buffer redirect(input.rdbuf()); + native_answer(1); + } + nyrt_context_end(); +} +} // namespace + +int main() { + try { + vm_contract(false); + vm_contract(true); + native_contract(); + std::cout << "Console input state: " << checks << " checks passed\n"; + return 0; + } catch (const std::exception &error) { + std::cerr << "Console input state failure: " << error.what() << '\n'; + return 1; + } +} From 451a4ff2328f2ff7552588e7fc74e23bcf81ce42 Mon Sep 17 00:00:00 2001 From: Nathan Young Date: Fri, 20 Nov 2026 21:49:10 -0500 Subject: [PATCH 07/10] Record Enigma durable-host library findings --- matrix/docs/next-version-findings.md | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/matrix/docs/next-version-findings.md b/matrix/docs/next-version-findings.md index 93c2fd21..7ba19880 100644 --- a/matrix/docs/next-version-findings.md +++ b/matrix/docs/next-version-findings.md @@ -2566,3 +2566,31 @@ than by name. a composed document keeps its own indentation; a compact renderer and the XML dialect are future work. Element and attribute names are fixed, so dynamic attribute sets (`data-*` generation) still need a design. + +### F90 — A Matrix database exposed missing durable-host mechanisms + +**Observed:** Enigma could encode its evidence and revocation state in Matrix, +but atomic byte publication did not synchronize the parent directory, stream +flush was not an `fsync`, and no context-owned writer lock existed. Private +directory creation, owner/mode verdicts, SHA-256, and an explicit end-of-input +result were also missing. Native providers were absent for existing byte-text +helpers and `random.hex`, despite their public declarations. + +**Implemented:** [NIL-0028](../../docs/design/NIL-0028-durable-files-and-locks.md) +adds durable publication, directory synchronization, and nonblocking locks whose +descriptors belong to the runtime context. [NIL-0029](../../docs/design/NIL-0029-private-entries-and-digests.md) +adds private entries and a standalone digest; [NIL-0030](../../docs/design/NIL-0030-end-of-input.md) +separates EOF from a blank line and input failure. Shared native providers fill +the byte-text and entropy gaps. Database policy remains in Enigma. + +Review added regressions for slash-terminated directory symlinks, which bypass +POSIX final-component no-follow checks unless rejected, and failed embedded +input streams with zero `errno`, which must not be mistaken for EOF. + +**Evidence and boundary:** Shared helper and embedded runtime tests, paired +Ny/Matrix interpreter text/binary and AOT/JIT routes, plus Enigma's independent +filesystem and restart oracle exercise the source-runtime profile. Unsupported +platforms fail closed for the POSIX filesystem additions. These checks do not +qualify a release SDK, hardware power loss, hostile storage ancestry, or a +database rollback defense. Existing atomic-write and stream-flush semantics +remain unchanged. From ebc4eb518156248cee9dbc6585d16ba09eb464f3 Mon Sep 17 00:00:00 2001 From: Nathan Young Date: Fri, 20 Nov 2026 22:13:58 -0500 Subject: [PATCH 08/10] Canonicalize text choice types in record and class fields --- CMakeLists.txt | 17 +++++ matrix/docs/next-version-findings.md | 21 +++++++ nilcompiler/src/codegen.cpp | 8 ++- .../language/choice-text-fields-matrix.matrix | 59 +++++++++++++++++ .../language/choice-text-fields-matrix.stdout | 8 +++ tests/language/choice-text-fields.ny | 63 +++++++++++++++++++ tests/language/choice-text-fields.stdout | 8 +++ 7 files changed, 182 insertions(+), 2 deletions(-) create mode 100644 tests/language/choice-text-fields-matrix.matrix create mode 100644 tests/language/choice-text-fields-matrix.stdout create mode 100644 tests/language/choice-text-fields.ny create mode 100644 tests/language/choice-text-fields.stdout diff --git a/CMakeLists.txt b/CMakeLists.txt index 2583037a..39d224b4 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2401,6 +2401,23 @@ if(BUILD_TESTING) --expected-exit 0 --routes all ) + foreach(nil_choice_fixture IN ITEMS choice-text-fields choice-text-fields-matrix) + if(nil_choice_fixture MATCHES "-matrix$") + set(nil_choice_suffix matrix) + else() + set(nil_choice_suffix ny) + endif() + add_ny_route_test( + ny.routes.${nil_choice_fixture} + --source "${CMAKE_CURRENT_SOURCE_DIR}/tests/language/${nil_choice_fixture}.${nil_choice_suffix}" + --expected-stdout "${CMAKE_CURRENT_SOURCE_DIR}/tests/language/${nil_choice_fixture}.stdout" + --expected-exit 0 + --routes all + --with-stdlib + --compiler-arg=--sdk-path + --compiler-arg=${CMAKE_CURRENT_SOURCE_DIR}/nilstd/src + ) + endforeach() add_ny_route_test( ny.routes.native-exhaustive-result-return --source "${CMAKE_CURRENT_SOURCE_DIR}/tests/language/native-exhaustive-result-return.ny" diff --git a/matrix/docs/next-version-findings.md b/matrix/docs/next-version-findings.md index 7ba19880..32fc624b 100644 --- a/matrix/docs/next-version-findings.md +++ b/matrix/docs/next-version-findings.md @@ -2594,3 +2594,24 @@ platforms fail closed for the POSIX filesystem additions. These checks do not qualify a release SDK, hardware power loss, hostile storage ancestry, or a database rollback defense. Existing atomic-write and stream-flush semantics remain unchanged. + +### F91 — Text choice fields need the same aliases as their enum schemas + +**Observed:** Enigma's typed discovery pattern stores `Option of text` in a +record. VM execution worked, but native compilation refused the field as +opaque: the field metadata said `Option` while its concrete enum +schema said `Option`. Qualification did not change the failure. The same +shape with a numeric payload worked. Both Ny and Matrix reproduced the mismatch +in records and classes, including `Result`. + +**Implemented:** Record and class field emission now uses the same recursive +primitive-alias canonicalization as concrete enum schemas and function types. +Nominal owners remain intact, and native lookup keeps its exact schema checks. +Paired `choice-text-fields` fixtures exercise construction, field reads, +mutation, and methods across the standard execution routes. + +**Open limitation:** An independent discovery probe also confirmed that native +arrays of nominal records are outside the current scalar-array profile, both +as locals and aggregate fields. This patch does not extend their layout or GC +contract. Enigma uses a bounded typed report batch with primitive columns and +checked element access; its durable interchange still returns report objects. diff --git a/nilcompiler/src/codegen.cpp b/nilcompiler/src/codegen.cpp index bde58c9e..a89d180a 100644 --- a/nilcompiler/src/codegen.cpp +++ b/nilcompiler/src/codegen.cpp @@ -7264,7 +7264,7 @@ codegen::assemble_module(const ast_program &program, nil_struct_def s; s.name = concrete_class; for (const auto &f : class_decl.checked_fields) { - s.fields.push_back({f.name, f.type_name}); + s.fields.push_back({f.name, canonical_nil_type_name(f.type_name)}); } mod->structs.push_back(s); @@ -7375,7 +7375,11 @@ codegen::assemble_module(const ast_program &program, ? struct_decl.name : current_module + "::" + struct_decl.name; for (const auto &field : struct_decl.fields) { - def.fields.emplace_back(field.name, field.type_name); + // The checker may infer String inside Option/Result fields even when + // source spells text. Use the same recursive ABI aliases as concrete + // enum schemas and function signatures, preserving nominal owners. + def.fields.emplace_back(field.name, + canonical_nil_type_name(field.type_name)); } // Rendered the same way a function's are, so one spelling reaches the // artifact whatever the declaration is. diff --git a/tests/language/choice-text-fields-matrix.matrix b/tests/language/choice-text-fields-matrix.matrix new file mode 100644 index 00000000..63c4f8bd --- /dev/null +++ b/tests/language/choice-text-fields-matrix.matrix @@ -0,0 +1,59 @@ +book validation.choice_text_fields + +read nil.std.core.option +read nil.std.core.result + +!!! Record and class fields share the concrete enum's canonical text spelling, +!!! even when payload expressions are checked using the internal String alias. +Slot begin record + field optional_text as Option of text + field result_text as Result of text, text +end record + +Holder begin class + field optional_text as Option of text + field result_text as Result of text, text + + public read_optional returns text begin paragraph + give option_text with input being my optional_text + end paragraph + + public read_result returns text begin paragraph + give result_payload with input being my result_text + end paragraph +end class + +option_text receives input as Option of text returns text begin paragraph + consider input + when Option.Some holding found then give found + when Option.None then give "none" + end consider +end paragraph + +result_payload receives input as Result of text, text returns text begin paragraph + consider input + when Result.Ok holding found then give found + when Result.Error holding failure then give failure + end consider +end paragraph + +main returns number begin paragraph + value slot_value is build Slot with optional_text being (Option.Some holding "record:alpha"), + result_text being (Result.Ok holding "record:ok") + say option_text with input being slot_value.optional_text + say result_payload with input being slot_value.result_text + set slot_value.optional_text to Option.None + set slot_value.result_text to (Result.Error holding "record:error") + say option_text with input being slot_value.optional_text + say result_payload with input being slot_value.result_text + + value holder_value is build Holder with optional_text being (Option.Some holding "class:alpha"), + result_text being (Result.Ok holding "class:ok") + say holder_value.read_optional with nothing + say holder_value.read_result with nothing + set holder_value.optional_text to Option.None + set holder_value.result_text to (Result.Error holding "class:error") + say holder_value.read_optional with nothing + say holder_value.read_result with nothing + give 0 +end paragraph diff --git a/tests/language/choice-text-fields-matrix.stdout b/tests/language/choice-text-fields-matrix.stdout new file mode 100644 index 00000000..b6aa8bc3 --- /dev/null +++ b/tests/language/choice-text-fields-matrix.stdout @@ -0,0 +1,8 @@ +record:alpha +record:ok +none +record:error +class:alpha +class:ok +none +class:error diff --git a/tests/language/choice-text-fields.ny b/tests/language/choice-text-fields.ny new file mode 100644 index 00000000..29b9d888 --- /dev/null +++ b/tests/language/choice-text-fields.ny @@ -0,0 +1,63 @@ +module validation.choice_text_fields + +import nil.std.core.option +import nil.std.core.result + +# Inferred String payloads and declared text fields must select the same exact +# enum schema, including when the schema is nested in a record or class field. +struct Slot + optional_text: Option + result_text: Result +end struct + +class Holder + optional_text: Option + result_text: Result + + pub fn read_optional(self) -> text + return option_text(self.optional_text) + end fn + + pub fn read_result(self) -> text + return result_payload(self.result_text) + end fn +end class + +fn option_text(input: Option) -> text + match input + Option.Some(found) -> return found + Option.None -> return "none" + end match +end fn + +fn result_payload(input: Result) -> text + match input + Result.Ok(found) -> return found + Result.Error(failure) -> return failure + end match +end fn + +fn main() -> i32 + let slot_value = Slot { + optional_text: Option.Some("record:alpha"), + result_text: Result.Ok("record:ok") + } + println(option_text(slot_value.optional_text)) + println(result_payload(slot_value.result_text)) + slot_value.optional_text = Option.None + slot_value.result_text = Result.Error("record:error") + println(option_text(slot_value.optional_text)) + println(result_payload(slot_value.result_text)) + + let holder_value = Holder { + optional_text: Option.Some("class:alpha"), + result_text: Result.Ok("class:ok") + } + println(holder_value.read_optional()) + println(holder_value.read_result()) + holder_value.optional_text = Option.None + holder_value.result_text = Result.Error("class:error") + println(holder_value.read_optional()) + println(holder_value.read_result()) + return 0 +end fn diff --git a/tests/language/choice-text-fields.stdout b/tests/language/choice-text-fields.stdout new file mode 100644 index 00000000..b6aa8bc3 --- /dev/null +++ b/tests/language/choice-text-fields.stdout @@ -0,0 +1,8 @@ +record:alpha +record:ok +none +record:error +class:alpha +class:ok +none +class:error From dbb4379946f6800a79e485dcd890e8f5b0902b31 Mon Sep 17 00:00:00 2001 From: Nathan Young Date: Fri, 20 Nov 2026 22:53:36 -0500 Subject: [PATCH 09/10] Expose current execution ownership of file locks --- .../NIL-0028-durable-files-and-locks.md | 15 ++++++++++--- docs/standard-library/durable-files.md | 10 +++++++++ docs/standard-library/index.md | 3 ++- matrix/docs/next-version-findings.md | 20 +++++++++++++++++ nilcompiler/src/native_runtime.cpp | 10 +++++++++ nilcompiler/src/ordinary_io_intrinsic.hpp | 2 +- nilcompiler/src/secure_file_io.cpp | 9 ++++++++ nilcompiler/src/secure_file_io.hpp | 3 +++ nilcompiler/src/vm.cpp | 14 ++++++++---- nilstd/src/io/file.ny | 7 ++++++ tests/durable_file_io_tests.cpp | 12 ++++++++++ tests/durable_vm_lifecycle_tests.cpp | 22 +++++++++++++++++-- .../durable-file-io-query-invalid-owner.ny | 18 +++++++++++++++ .../durable-file-io-query-invalid-width.ny | 11 ++++++++++ tests/language/durable-file-io.ny | 6 +++++ tests/matrix/io/durable-file-io.matrix | 18 ++++++++++++++- tests/native_runtime_tests.cpp | 19 +++++++++++++++- tests/tools/durable_file_io_contract.py | 2 ++ 18 files changed, 188 insertions(+), 13 deletions(-) create mode 100644 tests/language/durable-file-io-query-invalid-owner.ny create mode 100644 tests/language/durable-file-io-query-invalid-width.ny diff --git a/docs/design/NIL-0028-durable-files-and-locks.md b/docs/design/NIL-0028-durable-files-and-locks.md index 60b6d4df..fa6f877d 100644 --- a/docs/design/NIL-0028-durable-files-and-locks.md +++ b/docs/design/NIL-0028-durable-files-and-locks.md @@ -15,8 +15,8 @@ semantics, permission policy, and recovery decisions stay in the application. ## Decision -Add `write_bytes_durable`, `sync_directory`, `acquire_file_lock`, and -`release_file_lock`. Preserve the existing `write_bytes_atomic` and `File.flush` +Add `write_bytes_durable`, `sync_directory`, `acquire_file_lock`, +`release_file_lock`, and `file_lock_is_held`. Preserve the existing `write_bytes_atomic` and `File.flush` contracts. Durable writes reuse the atomic publication helper and synchronize the exact publication directory descriptor. A post-publication sync failure returns an explicitly uncertain outcome. @@ -27,6 +27,14 @@ are checked against their owning execution context, and are closed at invocation termination and context teardown. An execution checkpoint cannot clone one. Unsupported platforms fail closed before mutation. +`file_lock_is_held` asks whether the current execution context still retains +the token. Missing, stale, foreign, zero, and negative tokens return `Ok(false)`; +unsupported platforms return `Error`. The query does not inspect a pathname, +release or reacquire a descriptor, or change ownership. An application object +can survive an embedded VM invocation while that invocation's locks have been +retired, so retaining a positive token in an object is not evidence of a live +lock. Applications check current ownership before using that object's state. + Use the existing checked ordinary-I/O bridge for native execution, with exact parameter/result and enum ownership validation. The VM checks the new result metadata and concrete enum schema, and validates dynamic arguments before host @@ -45,7 +53,8 @@ ancestry. Fork-inherited descriptors retain ordinary POSIX lifetime semantics. An uncertain publication requires caller recovery rather than transparent retry. Tests cover shared OS helpers, embedded VM invocation/reset/destructor cleanup, -static/shared native context lifetimes, Ny/Matrix VM text/binary and AOT/JIT +static/shared native context lifetimes, ownership queries before and after +retirement, Ny/Matrix VM text/binary and AOT/JIT routes, malformed ABI declarations, private file modes, contention, and Linux file/directory-sync fault injection. Existing secure-byte and ordinary-I/O regressions remain part of focused validation. diff --git a/docs/standard-library/durable-files.md b/docs/standard-library/durable-files.md index 5818aed0..181ccebc 100644 --- a/docs/standard-library/durable-files.md +++ b/docs/standard-library/durable-files.md @@ -10,6 +10,7 @@ the same runtime provider and checked results. | `sync_directory(path)` | `Result` | | `acquire_file_lock(path, create)` | `Result` | | `release_file_lock(token)` | `Result` | +| `file_lock_is_held(token)` | `Result` | | `create_private_directory(path)` | `Result` | | `is_private_regular_file(path)` | `Result` | | `is_private_directory(path)` | `Result` | @@ -69,6 +70,15 @@ The limit is 4,096 held locks per execution context. Returned tokens are positive, monotonically allocated, and never recycled within a runtime instance. `release_file_lock` checks ownership in the current execution context; wrong, foreign, stale, and repeated-release tokens fail. +`file_lock_is_held` returns `Ok(true)` only while that context's registry retains +the token. Unknown, stale, foreign, zero, and negative tokens return `Ok(false)`. +It is a query without pathname access or release/reacquisition; it does not +change the lock or verify a new path identity. Unsupported platforms return +an explicit `Error`, including when the token would otherwise be absent. + +An embedded application can retain an object after its execution invocation +has finished. Its saved positive token must be checked again before guarded +state is used; the object does not extend the runtime lock's lifetime. Runtime teardown closes remaining locks on VM completion, failure, reset, replacement, destruction, or native context end. VM execution checkpoints reject open locks. Normal POSIX descriptor inheritance still applies across `fork`: diff --git a/docs/standard-library/index.md b/docs/standard-library/index.md index 62cdb4bf..75a17291 100644 --- a/docs/standard-library/index.md +++ b/docs/standard-library/index.md @@ -154,7 +154,8 @@ visibility-atomic but does not promise parent-directory durability after a sudden power loss. The additive [durable-files reference](durable-files.md) covers -`write_bytes_durable`, `sync_directory`, context-owned advisory file locks, +`write_bytes_durable`, `sync_directory`, context-owned advisory file locks and +the `file_lock_is_held` ownership query, owner-only directory creation, private-entry metadata verdicts, and `sha256_hex`. Those POSIX primitives supply explicit filesystem barriers and nonblocking diff --git a/matrix/docs/next-version-findings.md b/matrix/docs/next-version-findings.md index 32fc624b..5023adb4 100644 --- a/matrix/docs/next-version-findings.md +++ b/matrix/docs/next-version-findings.md @@ -2615,3 +2615,23 @@ arrays of nominal records are outside the current scalar-array profile, both as locals and aggregate fields. This patch does not extend their layout or GC contract. Enigma uses a bounded typed report batch with primitive columns and checked element access; its durable interchange still returns report objects. + +### F92 — A retained application object can outlive its file lock + +**Observed:** Enigma's importable durable session retains a positive lock token +in a Matrix object. Embedded VM invocation completion retires all file locks, +even when application objects remain reachable. The token alone therefore +cannot establish that a later call still owns the writer lock. Releasing and +reacquiring to test it would introduce a writer race and could admit stale +application state. + +**Implemented:** `nil.std.io.file_lock_is_held(token)` returns a checked current +execution-context ownership verdict without path access or lock mutation. +Missing, stale, foreign, zero, and negative tokens answer false; unsupported +platforms return an error. It does not extend lock lifetime or turn the token +into an authentication credential. + +Paired Ny/Matrix routes check live and released verdicts. Embedded VM lifecycle +and native context tests check foreign contexts and retirement after completion, +reset, replacement, faults, and teardown; malformed result schemas remain +rejected by the ordinary-I/O ABI checks. diff --git a/nilcompiler/src/native_runtime.cpp b/nilcompiler/src/native_runtime.cpp index 9d598d84..c17e194c 100644 --- a/nilcompiler/src/native_runtime.cpp +++ b/nilcompiler/src/native_runtime.cpp @@ -1679,6 +1679,16 @@ std::int32_t nyrt_io_v1(const char *operation, std::uint64_t first, return output_text(std::string_view(&octet, 1)); } + if (name == "file.file_lock_is_held") { + // Negative i64 tokens arrive in the unsigned ABI word's high half. + // They are a false ownership verdict, not a filesystem operation. + const auto held = context.file_locks.is_held( + first <= static_cast(INT64_MAX) + ? static_cast(first) : 0); + if (!held.ok) { set_error(error, held.error); return 0; } + *value = held.value ? 1 : 0; + return 1; + } if (name == "file.release_file_lock") { if (first > static_cast(INT64_MAX)) return fail("invalid lock token"); diff --git a/nilcompiler/src/ordinary_io_intrinsic.hpp b/nilcompiler/src/ordinary_io_intrinsic.hpp index 90a840c4..c152a0c0 100644 --- a/nilcompiler/src/ordinary_io_intrinsic.hpp +++ b/nilcompiler/src/ordinary_io_intrinsic.hpp @@ -50,7 +50,7 @@ inline std::optional intrinsic(const std::string &name) { return Contract{{"text"}, "bool", Output::result}; if (name == "file.acquire_file_lock") return Contract{{"text", "bool"}, "i64", Output::result}; - if (name == "file.release_file_lock") + if (name == "file.release_file_lock" || name == "file.file_lock_is_held") return Contract{{"i64"}, "bool", Output::result}; if (name == "file.create_private_directory" || name == "file.is_private_regular_file" || diff --git a/nilcompiler/src/secure_file_io.cpp b/nilcompiler/src/secure_file_io.cpp index e0ebd838..8727cad2 100644 --- a/nilcompiler/src/secure_file_io.cpp +++ b/nilcompiler/src/secure_file_io.cpp @@ -835,6 +835,15 @@ FileLockResult FileLockRegistry::acquire(const std::string &path, bool create) { #endif } +FileCheck FileLockRegistry::is_held(std::int64_t token) const { +#ifdef _WIN32 + (void)token; + return {false, false, "file.file_lock_is_held: unsupported platform"}; +#else + return {true, token > 0 && descriptors_.find(token) != descriptors_.end(), {}}; +#endif +} + AtomicFileWrite FileLockRegistry::release(std::int64_t token) { #ifdef _WIN32 (void)token; diff --git a/nilcompiler/src/secure_file_io.hpp b/nilcompiler/src/secure_file_io.hpp index 21328199..45973d64 100644 --- a/nilcompiler/src/secure_file_io.hpp +++ b/nilcompiler/src/secure_file_io.hpp @@ -49,6 +49,9 @@ class FileLockRegistry { // create=true exclusively creates a fresh private backing file; false // requires an existing private regular file. Acquisition never blocks. FileLockResult acquire(const std::string &path, bool create); + // Query only this registry; never releases, reacquires, or inspects a path. + // Missing, stale, foreign and nonpositive tokens have a false verdict. + FileCheck is_held(std::int64_t token) const; AtomicFileWrite release(std::int64_t token); void clear() noexcept; bool empty() const noexcept { return descriptors_.empty(); } diff --git a/nilcompiler/src/vm.cpp b/nilcompiler/src/vm.cpp index b18ff610..0bfa8c5f 100644 --- a/nilcompiler/src/vm.cpp +++ b/nilcompiler/src/vm.cpp @@ -2760,6 +2760,7 @@ void VM::executeInstruction(const Instruction &instr) { if (lib_name == "intrinsic" && (fn_name == "file.write_bytes_durable" || fn_name == "file.sync_directory" || fn_name == "file.acquire_file_lock" || fn_name == "file.release_file_lock" || + fn_name == "file.file_lock_is_held" || fn_name == "file.create_private_directory" || fn_name == "file.is_private_regular_file" || fn_name == "file.is_private_directory" || @@ -5305,7 +5306,7 @@ void VM::executeInstruction(const Instruction &instr) { return; } if (fn_name == "file.sync_directory" || fn_name == "file.acquire_file_lock" || - fn_name == "file.release_file_lock") { + fn_name == "file.release_file_lock" || fn_name == "file.file_lock_is_held") { auto result = [&](bool ok, int64_t value, const std::string &error) { EnumValue reply; reply.variant_name = ok ? "Result::Ok" : "Result::Error"; @@ -5314,13 +5315,18 @@ void VM::executeInstruction(const Instruction &instr) { pushStack(reply); }; try { - if (fn_name == "file.release_file_lock") { + if (fn_name == "file.release_file_lock" || fn_name == "file.file_lock_is_held") { if (args.size() != 1 || !std::holds_alternative(args[0])) { result(false, 0, fn_name + ": expected an i64 token"); return; } - const auto released = file_locks_.release(std::get(args[0])); - result(released.ok, 1, released.error); + if (fn_name == "file.file_lock_is_held") { + const auto held = file_locks_.is_held(std::get(args[0])); + result(held.ok, held.value ? 1 : 0, held.error); + } else { + const auto released = file_locks_.release(std::get(args[0])); + result(released.ok, 1, released.error); + } return; } const bool acquire = fn_name == "file.acquire_file_lock"; diff --git a/nilstd/src/io/file.ny b/nilstd/src/io/file.ny index 8b3af980..92e4a96d 100644 --- a/nilstd/src/io/file.ny +++ b/nilstd/src/io/file.ny @@ -93,6 +93,13 @@ pub fn acquire_file_lock(path: text, create: bool) -> Result @intrinsic("file.release_file_lock") pub fn release_file_lock(token: i64) -> Result +# Ask whether this execution context still owns a live lock token. This does +# not release/reacquire the lock or inspect its pathname. Stale, foreign, +# unknown, zero and negative tokens return Ok(false); POSIX-only. +# Invocation termination can retire a token while application objects remain. +@intrinsic("file.file_lock_is_held") +pub fn file_lock_is_held(token: i64) -> Result + # Create a new owner-only directory: POSIX mode 0700, applied by creation # rather than a later chmod, which would leave a writable window. An existing # entry is an error and is never adopted, so success means this call created diff --git a/tests/durable_file_io_tests.cpp b/tests/durable_file_io_tests.cpp index 8883b458..76f2ea22 100644 --- a/tests/durable_file_io_tests.cpp +++ b/tests/durable_file_io_tests.cpp @@ -309,9 +309,16 @@ void check_lock_lifecycle(const fs::path &root) { FileLockRegistry first; FileLockRegistry second; require(first.empty() && second.empty(), "new lock registry is not empty"); + require(first.is_held(1).ok && !first.is_held(1).value, + "empty registry reported an unknown token as held"); const auto held = first.acquire(path.u8string(), true); require(held.ok && held.token > 0 && held.error.empty(), "cannot create and acquire a private lock"); require(!first.empty(), "held lock was not retained by its registry"); + require(first.is_held(held.token).ok && first.is_held(held.token).value, + "registry did not report its held token"); + require(second.is_held(held.token).ok && !second.is_held(held.token).value && + !first.is_held(0).value && !first.is_held(-1).value, + "registry query accepted a foreign or nonpositive token"); struct stat metadata {}; require(::stat(path.c_str(), &metadata) == 0 && (metadata.st_mode & 0777) == 0600 && metadata.st_nlink == 1, "lock creation did not retain a private regular file"); @@ -326,6 +333,8 @@ void check_lock_lifecycle(const fs::path &root) { }); require(first.release(held.token).ok, "lock release failed"); require(first.empty(), "released lock remains in registry"); + require(first.is_held(held.token).ok && !first.is_held(held.token).value, + "registry query retained a released token"); require_error(first.release(held.token), "writer.lock"); require_error(first.release(0), "writer.lock"); require_error(first.release(-1), "writer.lock"); @@ -333,6 +342,8 @@ void check_lock_lifecycle(const fs::path &root) { require(next.ok && next.token != held.token, "lock token was recycled after release"); second.clear(); require(second.empty(), "clear did not release registry locks"); + require(second.is_held(next.token).ok && !second.is_held(next.token).value, + "registry query retained a cleared token"); require_error(second.release(next.token), "writer.lock"); const auto after_clear = first.acquire(path.u8string(), false); require(after_clear.ok && after_clear.token != next.token && after_clear.token != held.token, @@ -524,6 +535,7 @@ void check_unsupported_host(const fs::path &root) { require_error(ny::detail::write_file_durable_utf8(target.u8string(), {'x'}, false), "private-unsupported-marker"); FileLockRegistry registry; require_error(registry.acquire(target.u8string(), true), "private-unsupported-marker"); + require_error(registry.is_held(0), "private-unsupported-marker"); require_error(ny::detail::create_private_directory_utf8(target.u8string()), "private-unsupported-marker"); require_error(ny::detail::private_regular_file_utf8(target.u8string()), diff --git a/tests/durable_vm_lifecycle_tests.cpp b/tests/durable_vm_lifecycle_tests.cpp index c52a1f75..2e67977b 100644 --- a/tests/durable_vm_lifecycle_tests.cpp +++ b/tests/durable_vm_lifecycle_tests.cpp @@ -86,7 +86,11 @@ Program fixture(const fs::path &path, bool binary, bool fault) { {"PUSH_CONST_STR", {"lock_path"}}, {"PUSH_CONST", {"0"}}, {"CAST", {"bool"}}, {"INTEROP_CALL", {"intrinsic", "file.acquire_file_lock", "2", token_result}}, {"UNWRAP_VARIANT", {"1", token_result, "i64"}}, - {"STORE_GLOBAL", {"opened", "i64"}}}; + {"STORE_GLOBAL", {"opened", "i64"}}, + {"LOAD_GLOBAL", {"opened", "i64"}}, + {"INTEROP_CALL", {"intrinsic", "file.file_lock_is_held", "1", bool_result}}, + {"UNWRAP_VARIANT", {"1", bool_result, "bool"}}, + {"STORE_GLOBAL", {"held_during", "bool"}}}; if (fault) { body.push_back({"PUSH_CONST", {"1"}}); body.push_back({"PUSH_CONST", {"0"}}); @@ -100,6 +104,10 @@ Program fixture(const fs::path &path, bool binary, bool fault) { {{"STORE_LOCAL", {"token"}}, {"LOAD_LOCAL", {"token"}}, {"INTEROP_CALL", {"intrinsic", "file.release_file_lock", "1", bool_result}}, {"RET", {}}})); + module.functions.push_back(function("held", {"token:i64"}, bool_result, + {{"STORE_LOCAL", {"token"}}, {"LOAD_LOCAL", {"token"}}, + {"INTEROP_CALL", {"intrinsic", "file.file_lock_is_held", "1", bool_result}}, + {"RET", {}}})); std::ostringstream serialized(std::ios::out | std::ios::binary); if (binary) { ny::codegen_options options; @@ -129,17 +137,27 @@ void endpoint(const fs::path &path, bool held, const std::string &phase) { std::int64_t pause(ny::VM &vm, const Program &program, const fs::path &path) { vm.loadProgram(program.code, program.constants); vm.resetExecution("main"); - for (int step = 0; step < 50 && !vm.hasGlobal("opened"); ++step) + for (int step = 0; step < 50 && !vm.hasGlobal("held_during"); ++step) require(vm.stepInstruction(), "invocation did not reach its lock"); require(vm.hasGlobal("opened"), "fixture did not retain its lock token"); const auto token = std::get(vm.getGlobal("opened")); require(token > 0, "lock token must be positive"); + require(vm.hasGlobal("held_during") && + std::get(vm.getGlobal("held_during")) == 1, + "active invocation did not report ownership of its lock"); endpoint(path, true, "paused invocation"); return token; } void stale(ny::VM &vm, std::int64_t token) { vm.pushValue(token); + vm.callFunction("held", 1); + require(!vm.getStack().empty(), "ownership query did not return a checked result"); + const auto &held = std::get(vm.getStack().back()); + require(held.variant_name == "Result::Ok" && held.payloads.size() == 1 && + std::get(held.payloads.front()) == 0, + "foreign or terminal token was reported as held"); + vm.pushValue(token); vm.callFunction("release", 1); require(!vm.getStack().empty(), "release did not return a checked result"); const auto &result = std::get(vm.getStack().back()); diff --git a/tests/language/durable-file-io-query-invalid-owner.ny b/tests/language/durable-file-io-query-invalid-owner.ny new file mode 100644 index 00000000..6473d4e5 --- /dev/null +++ b/tests/language/durable-file-io-query-invalid-owner.ny @@ -0,0 +1,18 @@ +module nil.tests.durable_query_invalid_owner + +enum Result + Ok(T) + Error(E) +end enum + +@intrinsic("file.file_lock_is_held") +fn wrong_query(token: i64) -> Result +end fn + +fn main() -> i32 + match wrong_query(0) + Result.Ok(_) -> return 1 + Result.Error(_) -> return 0 + end match + return 0 +end fn diff --git a/tests/language/durable-file-io-query-invalid-width.ny b/tests/language/durable-file-io-query-invalid-width.ny new file mode 100644 index 00000000..cc0d31aa --- /dev/null +++ b/tests/language/durable-file-io-query-invalid-width.ny @@ -0,0 +1,11 @@ +module nil.tests.durable_query_invalid_width +import nil.std.core + +@intrinsic("file.file_lock_is_held") +fn wrong_query(token: i64) -> Result +end fn + +fn main() -> i32 + if wrong_query(0).is_ok() then return 1 end if + return 0 +end fn diff --git a/tests/language/durable-file-io.ny b/tests/language/durable-file-io.ny index e892f3f3..77dc27b6 100644 --- a/tests/language/durable-file-io.ny +++ b/tests/language/durable-file-io.ny @@ -36,13 +36,19 @@ fn main() -> i32 if acquired.is_error() then return 10 end if let token = acquired.unwrap() if token <= 0 then return 11 end if + if not nil::std::io::file_lock_is_held(token).unwrap() then return 31 end if + if nil::std::io::file_lock_is_held(0).unwrap() or + nil::std::io::file_lock_is_held(-1).unwrap() then return 32 end if if nil::std::io::acquire_file_lock(lock, false).is_ok() then return 12 end if if nil::std::io::release_file_lock(0).is_ok() then return 13 end if if not nil::std::io::release_file_lock(token).is_ok() then return 14 end if if nil::std::io::release_file_lock(token).is_ok() then return 15 end if + if nil::std::io::file_lock_is_held(token).unwrap() then return 33 end if let again = nil::std::io::acquire_file_lock(lock, false) if again.is_error() then return 16 end if if again.unwrap() <= token then return 17 end if + if not nil::std::io::file_lock_is_held(again.unwrap()).unwrap() then return 34 end if + if nil::std::io::file_lock_is_held(token).unwrap() then return 35 end if # Deliberately retain this lock until invocation completion. The host oracle # independently acquires the backing file after every execution route. if not nil::std::io::sync_directory(root).is_ok() then return 18 end if diff --git a/tests/matrix/io/durable-file-io.matrix b/tests/matrix/io/durable-file-io.matrix index d4e7e05f..d85283a7 100644 --- a/tests/matrix/io/durable-file-io.matrix +++ b/tests/matrix/io/durable-file-io.matrix @@ -2,7 +2,7 @@ book nil.tests.durable_file_io read everything from nil.std.core -read write_bytes_durable, read_bytes, sync_directory, acquire_file_lock, release_file_lock, +read write_bytes_durable, read_bytes, sync_directory, acquire_file_lock, release_file_lock, file_lock_is_held, create_private_directory, is_private_regular_file, is_private_directory, sha256_hex from nil.std.io read arg_count, arg from nil.std.system read byte_at, from_byte from nil.std.text @@ -72,6 +72,13 @@ main returns override integer begin paragraph when token is at most 0 then give 11 end when + when not ((file_lock_is_held with token being token).unwrap with nothing) then + give 31 + end when + when ((file_lock_is_held with token being 0).unwrap with nothing) or + ((file_lock_is_held with token being minus 1).unwrap with nothing) then + give 32 + end when when (acquire_file_lock with path being lock, create being no).is_ok with nothing then give 12 end when @@ -84,6 +91,9 @@ main returns override integer begin paragraph when (release_file_lock with token being token).is_ok with nothing then give 15 end when + when (file_lock_is_held with token being token).unwrap with nothing then + give 33 + end when value reacquired is acquire_file_lock with path being lock, create being no when reacquired.is_error with nothing then give 16 @@ -91,6 +101,12 @@ main returns override integer begin paragraph when (reacquired.unwrap with nothing) is at most token then give 17 end when + when not ((file_lock_is_held with token being (reacquired.unwrap with nothing)).unwrap with nothing) then + give 34 + end when + when (file_lock_is_held with token being token).unwrap with nothing then + give 35 + end when !!! Intentionally retained until invocation completion; the host then checks it. when not ((sync_directory with path being root).is_ok with nothing) then give 18 diff --git a/tests/native_runtime_tests.cpp b/tests/native_runtime_tests.cpp index 083cc4bd..c00a0900 100644 --- a/tests/native_runtime_tests.cpp +++ b/tests/native_runtime_tests.cpp @@ -890,7 +890,12 @@ void check_durable_io_contract(bool &ok) { ok &= expect(call("file.acquire_file_lock", word(lock_path.c_str()), 1) == 0 && error && !std::filesystem::exists(std::filesystem::u8path(lock_path)), "unsupported locking mutated the namespace"); + ok &= expect(call("file.file_lock_is_held", 0) == 0 && error && + std::string(error) == "file.file_lock_is_held: unsupported platform", + "unsupported lock ownership query reported a verdict"); #else + ok &= expect(call("file.file_lock_is_held", 1) == 1 && value == 0 && !error, + "new native context reported an unknown token as held"); ok &= expect(call("file.sync_directory", word(directory.c_str())) == 1 && value == 1 && !error, "native directory synchronization failed"); auto *bytes = make_bytes({0, 10, 255}); @@ -911,6 +916,11 @@ void check_durable_io_contract(bool &ok) { ok &= expect(call("file.acquire_file_lock", word(lock_path.c_str()), 1) == 1 && value > 0 && !error, "native lock acquisition failed"); const auto token = value; + ok &= expect(call("file.file_lock_is_held", token) == 1 && value == 1 && !error, + "native owner did not report its live lock"); + ok &= expect(call("file.file_lock_is_held", 0) == 1 && value == 0 && !error && + call("file.file_lock_is_held", UINT64_MAX) == 1 && value == 0 && !error, + "nonpositive native tokens did not have a false ownership verdict"); bool isolated = false; std::thread foreign([&]() { nyrt_context_begin(0, nullptr); @@ -918,7 +928,10 @@ void check_durable_io_contract(bool &ok) { const char *foreign_error = nullptr; const bool rejects_release = nyrt_io_v1("file.release_file_lock", token, 0, 0, &foreign_value, &foreign_error) == 0; const bool rejects_lock = nyrt_io_v1("file.acquire_file_lock", word(lock_path.c_str()), 0, 0, &foreign_value, &foreign_error) == 0; - isolated = rejects_release && rejects_lock; + const bool absent = nyrt_io_v1("file.file_lock_is_held", token, 0, 0, + &foreign_value, &foreign_error) == 1 && + foreign_value == 0 && !foreign_error; + isolated = rejects_release && rejects_lock && absent; nyrt_context_end(); }); foreign.join(); @@ -926,11 +939,15 @@ void check_durable_io_contract(bool &ok) { ok &= expect(call("file.release_file_lock", token) == 1 && value == 1 && call("file.release_file_lock", token) == 0 && value == 0 && error, "native lock token survived release"); + ok &= expect(call("file.file_lock_is_held", token) == 1 && value == 0 && !error, + "released native token was still reported as held"); ok &= expect(call("file.acquire_file_lock", word(lock_path.c_str()), 0) == 1 && value > token, "native lock token was reused"); const auto abandoned = value; nyrt_context_end(); nyrt_context_begin(0, nullptr); + ok &= expect(call("file.file_lock_is_held", abandoned) == 1 && value == 0 && !error, + "native ownership verdict survived context teardown"); ok &= expect(call("file.release_file_lock", abandoned) == 0 && error, "native lock survived context teardown"); ok &= expect(call("file.acquire_file_lock", word(lock_path.c_str()), 0) == 1 && value > abandoned, diff --git a/tests/tools/durable_file_io_contract.py b/tests/tools/durable_file_io_contract.py index 89ea6eec..8354973c 100644 --- a/tests/tools/durable_file_io_contract.py +++ b/tests/tools/durable_file_io_contract.py @@ -97,6 +97,8 @@ def main() -> int: invalid = { "width": (ROOT / "tests/language/durable-file-io-invalid-width.ny", "file.acquire_file_lock"), "owner": (ROOT / "tests/language/durable-file-io-invalid-owner.ny", "file.sync_directory"), + "query-width": (ROOT / "tests/language/durable-file-io-query-invalid-width.ny", "file.file_lock_is_held"), + "query-owner": (ROOT / "tests/language/durable-file-io-query-invalid-owner.ny", "file.file_lock_is_held"), } inputs = {"compiler": compiler, "interpreter": interpreter, "runner": Path(__file__).resolve(), **sources, **{name: row[0] for name, row in invalid.items()}} From c2fa80bec7bdb946ece5cc35513088277d6ca31d Mon Sep 17 00:00:00 2001 From: Nathan Young Date: Fri, 20 Nov 2026 23:15:44 -0500 Subject: [PATCH 10/10] Record imported choice shadowing found by the durable client --- matrix/docs/next-version-findings.md | 40 ++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/matrix/docs/next-version-findings.md b/matrix/docs/next-version-findings.md index 5023adb4..6a983889 100644 --- a/matrix/docs/next-version-findings.md +++ b/matrix/docs/next-version-findings.md @@ -2635,3 +2635,43 @@ Paired Ny/Matrix routes check live and released verdicts. Embedded VM lifecycle and native context tests check foreign contexts and retirement after completion, reset, replacement, faults, and teardown; malformed result schemas remain rejected by the ordinary-I/O ABI checks. + +### F93 — A later local binding can rename an imported choice constructor + +**Status:** Open Matrix name-resolution defect; application workaround only. + +**Observed:** While building Enigma's durable client, a local binding named +`result` in one paragraph changed `Result.Error` construction in an earlier, +unrelated paragraph. Both source variants passed type checking. With the local +name `result`, generated NIL called an unresolved function `Error` instead of +constructing the checked Result variant; execution failed with an unknown-call +error, or the exact-signature loader check rejected that call first. + +Minimal reproducer: + +```matrix +book findings.result_shadow +read nil.std.core.result + +answer returns Result of number, text begin paragraph + give Result.Error holding "failure" +end paragraph + +later returns number begin paragraph + value result as number is 7 + give result +end paragraph +``` + +The parser's declaration pre-scan records local bindings in a page-wide name +map. `resolve_name` then folds the unqualified imported owner `Result` to the +local spelling `result`, including in another paragraph. This is broader than +a same-scope shadowing rule: merely declaring the later local changes the +earlier constructor's emitted identity. + +**Workaround and boundary:** Renaming the local to `gathered` restores the +Result constructor and the isolated program executes correctly. Enigma uses +that source workaround. Avoid local or parameter names differing only in case +from imported type names within a page until resolution becomes lexical or +reports the collision before code generation. No compiler behavior, loader +provenance check, or ABI rule was relaxed, and no failing CI fixture was added.