From 858b5f791a7d881015af7e374a26d10f4c2bb86b Mon Sep 17 00:00:00 2001 From: Nathan Young Date: Sun, 15 Nov 2026 13:10:46 -0500 Subject: [PATCH 01/15] 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/15] 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/15] 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/15] 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/15] 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/15] 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/15] 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/15] 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/15] 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/15] 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. From 6a0563438aff61b3cb751012ae00c323f836cf13 Mon Sep 17 00:00:00 2001 From: Nathan Young Date: Sat, 21 Nov 2026 00:21:36 -0500 Subject: [PATCH 11/15] Make durable I/O fixtures portable across POSIX build environments --- README.md | 5 +++-- notebook/2026-11-21-goetic-enigma-sdk.md | 10 ++++++++++ tests/durable_file_io_tests.cpp | 4 ++++ tests/durable_vm_lifecycle_tests.cpp | 1 + 4 files changed, 18 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 0551d86c..6e128933 100644 --- a/README.md +++ b/README.md @@ -265,8 +265,9 @@ and the failed report is retained. A separate Windows account exposed a packaged-library permission defect; the correction passes real cross-account access tests. -The newer socket, entropy and text-byte APIs pass the same interpreter contracts -on every host; these APIs currently require the interpreter on all platforms. +The socket, arbitrary random-byte and bytes-to-text APIs pass the same +interpreter contracts on every host; these APIs currently require the +interpreter on all platforms. File timestamps also pass textual/binary NIL, LLVM JIT and AOT checks everywhere. The [platform support matrix](docs/platform-support.md) records exact SDK/source revisions, retained failures and remaining deployment boundaries. diff --git a/notebook/2026-11-21-goetic-enigma-sdk.md b/notebook/2026-11-21-goetic-enigma-sdk.md index b1e5a310..c5ef101f 100644 --- a/notebook/2026-11-21-goetic-enigma-sdk.md +++ b/notebook/2026-11-21-goetic-enigma-sdk.md @@ -46,6 +46,16 @@ twelve malformed-schema rejections and 36 foreign-library rejections. The focused JUnit SHA-256 is `376498e076efdc305fe452ca423c08b307ce6bbfced4af63a84a5252757a919a`. +The first full SDK attempt at `d08e1cf` retained 608 passes, one failure and +zero skips. Its `077` umask correctly exposed a test setup assumption: the +directory intended as a non-private `0755` control was actually created as +`0700`. The fixture now explicitly sets its own mode before inspection; neither +the runtime nor the runner's umask is weakened. This failed attempt published +no SDK. Initial hosted Apple Silicon builds also found a missing direct POSIX +`mkdtemp` declaration in the lifecycle fixture; it now includes `` +explicitly. Those original failures remain retained, with fresh qualification +required after the corrections. + Both corrections have retained old-behavior controls. Original durable helper tests pass against the old directory helper; adding the umask cases fails that helper, and the corrected helper passes. Before the VM guard, a foreign-library diff --git a/tests/durable_file_io_tests.cpp b/tests/durable_file_io_tests.cpp index 339cbc7e..207b5e47 100644 --- a/tests/durable_file_io_tests.cpp +++ b/tests/durable_file_io_tests.cpp @@ -482,6 +482,10 @@ void check_private_metadata(const fs::path &root) { "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"); + // The negative fixture must stay non-private even under an embedding + // process's restrictive umask. This changes only our newly created fixture. + require(::chmod(loose_directory.c_str(), 0755) == 0, + "cannot loosen fixture directory mode"); verdict(ny::detail::private_directory_utf8(loose_directory.u8string()), false, "a 0755 directory is not private"); diff --git a/tests/durable_vm_lifecycle_tests.cpp b/tests/durable_vm_lifecycle_tests.cpp index 2e67977b..3964235a 100644 --- a/tests/durable_vm_lifecycle_tests.cpp +++ b/tests/durable_vm_lifecycle_tests.cpp @@ -20,6 +20,7 @@ #if defined(__unix__) || defined(__APPLE__) #include #include +#include // Darwin declares mkdtemp here. #endif namespace { From 9ca4272086b55d5573b3ff013a7d5c378ba7fecb Mon Sep 17 00:00:00 2001 From: Nathan Young Date: Sat, 21 Nov 2026 01:01:36 -0500 Subject: [PATCH 12/15] Preserve checked class values through interpreter globals and enums --- .../workflows/macos-application-parity.yml | 32 ++- .github/workflows/web-runtime-parity.yml | 29 ++- CMakeLists.txt | 1 + README.md | 4 + docs/advanced/nil-format.md | 29 ++- docs/language-reference/classes.md | 10 +- nilcompiler/src/codegen.cpp | 120 +++++++--- nilcompiler/src/llvm_backend.cpp | 4 + nilcompiler/src/nil_contract.hpp | 60 +++++ nilcompiler/src/nil_loader.cpp | 217 +++++++++++++---- nilcompiler/src/vm.cpp | 90 ++++++- nilcompiler/src/vm.hpp | 1 + notebook/2026-11-21-goetic-enigma-sdk.md | 74 +++++- scripts/check-sdk-durable-io.py | 30 ++- tests/class_vm_tests.cpp | 226 +++++++++++++++++- tests/tools/global_contract.py | 163 ++++++++++++- 16 files changed, 990 insertions(+), 100 deletions(-) diff --git a/.github/workflows/macos-application-parity.yml b/.github/workflows/macos-application-parity.yml index a0f3e8d5..ec271d6f 100644 --- a/.github/workflows/macos-application-parity.yml +++ b/.github/workflows/macos-application-parity.yml @@ -34,6 +34,9 @@ name: macOS application platform checks - 'tests/tools/markup_contract.py' - 'tests/tools/module_alias_contract.py' - 'tests/tools/checked_conversion_intrinsic_contract.py' + - 'tests/class_vm_tests.cpp' + - 'tests/tools/global_contract.py' + - 'tests/language/module-global-contract.*' - 'tests/console_input_state_tests.cpp' - 'tests/durable_file_io_tests.cpp' - 'tests/durable_vm_lifecycle_tests.cpp' @@ -186,13 +189,13 @@ jobs: cmake --build build/application --parallel 2 --target \ nilcompiler nilinterpreter nilassembler nillinker nillsp nildebugger nilbuild niltest aperture nilruntime_shared \ nil_vscode_host_runner nil_file_time_support_tests nil_rooted_file_snapshot_tests nil_webview_runtime_tests \ - nil_compiler_module_darwin_tests nilruntime \ + nil_compiler_module_darwin_tests ny_class_vm_tests nilruntime \ nil_console_input_state_tests nil_durable_file_io_tests nil_durable_vm_lifecycle_tests \ ny_native_runtime_tests nil_shared_runtime_tests \ nil_darwin_toolchain_inputs_tests nil_freestanding_hook_default nil_freestanding_hook_override \ nildebugger_core_tests nildebugger_source_metadata_tests nildebugger_dap_owner_tests \ 2>&1 | tee build/application-evidence/build.log - - name: Verify formatted text, markup, module aliases and checked conversions + - name: Verify text, aliases, checked conversions, class and global contracts if: ${{ !cancelled() && steps.tools.outcome == 'success' }} timeout-minutes: 8 run: | @@ -200,10 +203,11 @@ jobs: import json, subprocess, xml.etree.ElementTree as ET from pathlib import Path expected = {'nil.formatted-text-contract', 'nil.markup-contract', - 'nil.module-alias', 'nil.checked-conversion-intrinsic-contract'} + 'nil.module-alias', 'nil.checked-conversion-intrinsic-contract', + 'nil.class-contract', 'ny.global-contract'} expected.update('ny.'+route+'.'+fixture for route in ['routes', 'tools'] for fixture in ['formatted-text', 'formatted-text-matrix', 'markup', 'markup-matrix']) - pattern = r'^(nil[.](formatted-text-contract|markup-contract|module-alias|checked-conversion-intrinsic-contract)|ny[.](routes|tools)[.](formatted-text|markup)(-matrix)?)$' + pattern = r'^(nil[.](formatted-text-contract|markup-contract|module-alias|checked-conversion-intrinsic-contract|class-contract)|ny[.]global-contract|ny[.](routes|tools)[.](formatted-text|markup)(-matrix)?)$' base = ['ctest', '--test-dir', 'build/application', '-R', pattern] root = Path('build/application-evidence').resolve() inventory = subprocess.check_output(base+['--show-only=json-v1'], timeout=30) @@ -220,6 +224,12 @@ jobs: assert len(cases) == len(expected) and {case.get('name') for case in cases} == expected assert all(case.get('status') == 'run' and all(case.find(kind) is None for kind in ['failure', 'error', 'skipped']) for case in cases) + by_name = {case.get('name'): case for case in cases} + assert by_name['nil.class-contract'].findtext('system-out', '').strip() == \ + 'Class metadata, provenance, dispatch, alias and version contracts passed' + assert by_name['ny.global-contract'].findtext('system-out', '').strip() == ( + 'global contracts passed: 9 negative and 3 control cases in text/binary NIL\n' + 'nominal global contracts passed: 8 VM executions, 2 initialization rejections, 2 native rejections') PYTHON - name: Verify durable I/O, console EOF, choice fields and secure hex if: ${{ !cancelled() && steps.tools.outcome == 'success' }} @@ -570,6 +580,20 @@ jobs: if logs.is_dir(): shutil.copytree(logs, root/'editor-logs'/record['runId']) dirty = subprocess.check_output(['git','status','--porcelain','--untracked-files=no'], text=True, timeout=15) revision = subprocess.check_output(['git','rev-parse','HEAD'], text=True, timeout=15).strip() + source_inputs = [ + 'CMakeLists.txt', '.github/workflows/web-runtime-parity.yml', + '.github/workflows/macos-application-parity.yml', + 'nilcompiler/src/codegen.cpp', 'nilcompiler/src/llvm_backend.cpp', + 'nilcompiler/src/nil_contract.hpp', 'nilcompiler/src/nil_loader.cpp', + 'nilcompiler/src/vm.cpp', 'nilcompiler/src/vm.hpp', 'nilcompiler/src/dynamic_type.hpp', + 'nilstd/src/core/option.ny', 'tests/class_vm_tests.cpp', 'tests/tools/global_contract.py', + 'tests/language/module-global-contract.ny', 'tests/language/module-global-contract.stdout'] + inputs = {} + for name in source_inputs: + data = Path(name).read_bytes() + inputs[name] = dict(bytes=len(data), sha256=hashlib.sha256(data).hexdigest()) + (root/'nominal-global-inputs.json').write_text(json.dumps(dict( + revision=revision, files=inputs), indent=2)+'\n') files = {} for path in sorted(root.rglob('*')): if path.is_file() and not path.is_symlink(): diff --git a/.github/workflows/web-runtime-parity.yml b/.github/workflows/web-runtime-parity.yml index 6300b092..799672cc 100644 --- a/.github/workflows/web-runtime-parity.yml +++ b/.github/workflows/web-runtime-parity.yml @@ -23,6 +23,9 @@ name: Web runtime platform checks - 'tests/tools/markup_contract.py' - 'tests/tools/module_alias_contract.py' - 'tests/tools/checked_conversion_intrinsic_contract.py' + - 'tests/class_vm_tests.cpp' + - 'tests/tools/global_contract.py' + - 'tests/language/module-global-contract.*' - 'tests/console_input_state_tests.cpp' - 'tests/durable_file_io_tests.cpp' - 'tests/durable_vm_lifecycle_tests.cpp' @@ -105,7 +108,7 @@ jobs: run: | set -o pipefail cmake --build build/web-parity --config Release --parallel 2 \ - --target nilcompiler nilinterpreter nilassembler nil_net_support_tests \ + --target nilcompiler nilinterpreter nilassembler nillinker ny_class_vm_tests nil_net_support_tests \ nil_net_lifecycle_tests nil_file_time_support_tests \ nil_rooted_file_snapshot_tests nil_webview_runtime_tests \ nil_console_input_state_tests nil_durable_file_io_tests \ @@ -117,7 +120,7 @@ jobs: "$NIL_CI_PYTHON" - <<'PY' import json, os, re, subprocess from pathlib import Path - pattern = r'^(net[.](support-contract|lifecycle-contract|socket-contract)|nil[.](file-time-support|file-modified-at-contract|rooted-file-snapshot|rooted-file-snapshot-contract|webview-runtime|webview-intrinsic-contract|formatted-text-contract|markup-contract|module-alias|checked-conversion-intrinsic-contract|console-input-state|durable-file-io)|matrix[.]execution)$' + pattern = r'^(net[.](support-contract|lifecycle-contract|socket-contract)|nil[.](file-time-support|file-modified-at-contract|rooted-file-snapshot|rooted-file-snapshot-contract|webview-runtime|webview-intrinsic-contract|formatted-text-contract|markup-contract|module-alias|checked-conversion-intrinsic-contract|console-input-state|durable-file-io|class-contract)|ny[.]global-contract|matrix[.]execution)$' base = ['ctest', '--test-dir', 'build/web-parity', '-C', 'Release', '-R', pattern] root = Path('build/web-parity-evidence').resolve() inventory = subprocess.check_output(base+['--show-only=json-v1'], timeout=30) @@ -128,7 +131,8 @@ jobs: 'nil.webview-runtime', 'nil.webview-intrinsic-contract', 'nil.formatted-text-contract', 'nil.markup-contract', 'nil.module-alias', 'nil.checked-conversion-intrinsic-contract', - 'nil.console-input-state', 'nil.durable-file-io'} + 'nil.console-input-state', 'nil.durable-file-io', + 'nil.class-contract', 'ny.global-contract'} assert {test['name'] for test in json.loads(inventory)['tests']} == expected with (root/'ctest.log').open('wb') as output: result = subprocess.run(base+['--no-tests=error', '--output-on-failure', @@ -145,6 +149,11 @@ jobs: assert re.fullmatch(r'Console input state: [1-9][0-9]* checks passed\s*', by_name['nil.console-input-state'].findtext('system-out', '')) assert by_name['nil.durable-file-io'].findtext('system-out', '').strip() == 'durable-file-io-ok' + assert by_name['nil.class-contract'].findtext('system-out', '').strip() == \ + 'Class metadata, provenance, dispatch, alias and version contracts passed' + assert by_name['ny.global-contract'].findtext('system-out', '').strip() == ( + 'global contracts passed: 9 negative and 3 control cases in text/binary NIL\n' + 'nominal global contracts passed: 8 VM executions, 2 initialization rejections, 0 native rejections') # The Windows helper exercises checked unsupported errors and nonmutation. # Do not count its zero-check VM lifecycle or skipped POSIX route as support. (root/'durable-platform-boundary.json').write_text(json.dumps({ @@ -325,6 +334,20 @@ jobs: shutil.copytree(durable, root/'durable-io') dirty = subprocess.check_output(['git', 'status', '--porcelain', '--untracked-files=no'], text=True, timeout=15) revision = subprocess.check_output(['git', 'rev-parse', 'HEAD'], text=True, timeout=15).strip() + source_inputs = [ + 'CMakeLists.txt', '.github/workflows/web-runtime-parity.yml', + '.github/workflows/macos-application-parity.yml', + 'nilcompiler/src/codegen.cpp', 'nilcompiler/src/llvm_backend.cpp', + 'nilcompiler/src/nil_contract.hpp', 'nilcompiler/src/nil_loader.cpp', + 'nilcompiler/src/vm.cpp', 'nilcompiler/src/vm.hpp', 'nilcompiler/src/dynamic_type.hpp', + 'nilstd/src/core/option.ny', 'tests/class_vm_tests.cpp', 'tests/tools/global_contract.py', + 'tests/language/module-global-contract.ny', 'tests/language/module-global-contract.stdout'] + inputs = {} + for name in source_inputs: + data = Path(name).read_bytes() + inputs[name] = dict(bytes=len(data), sha256=hashlib.sha256(data).hexdigest()) + (root/'nominal-global-inputs.json').write_text(json.dumps(dict( + revision=revision, files=inputs), indent=2)+'\n') files = {} for path in sorted(root.rglob('*')): if path.is_file() and not path.is_symlink(): diff --git a/CMakeLists.txt b/CMakeLists.txt index bcecaa39..2264eb6d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1443,6 +1443,7 @@ if(BUILD_TESTING) --assembler $ --linker $ --runtime $ + --nilstd "${CMAKE_CURRENT_SOURCE_DIR}/nilstd/src" --llvm "${NIL_ENABLE_LLVM}" ) set_tests_properties(ny.global-contract PROPERTIES LABELS "routes;rc" TIMEOUT 180) diff --git a/README.md b/README.md index 6e128933..d8b2332c 100644 --- a/README.md +++ b/README.md @@ -284,6 +284,10 @@ random draws. Durable filesystem operations currently support POSIX hosts; Windows returns explicit unsupported errors. The [integration notebook](notebook/2026-11-21-goetic-enigma-sdk.md) separates source checks, installed SDK evidence and remaining limitations. +The interpreter also preserves imported class values through typed module +globals, record wrappers and explicit `Option` factories. Native +aggregate globals remain unsupported; the real Goetic/Enigma consumer is an +additional acceptance gate before SDK handoff. These are development results. Windows and macOS release qualification remains pending. The diff --git a/docs/advanced/nil-format.md b/docs/advanced/nil-format.md index 4e61e000..8b583b27 100644 --- a/docs/advanced/nil-format.md +++ b/docs/advanced/nil-format.md @@ -207,7 +207,15 @@ checked method boundary, not through general reference covariance. Readers validate class schemas, acyclic ancestry (at most 256 levels), inherited field identity, method signatures and concrete abstract-method obligations. Class provenance is checked through operand/local control flow, calls, returns -and fields. A cast, raw pointer or foreign return cannot manufacture a class +and fields. On interpreted routes, class-bearing typed enums preserve the exact +nominal identity and payload views through those boundaries. +`NEW_VARIANT tag count enum_type payload_type`, +`IS_VARIANT tag enum_type payload_type` and +`UNWRAP_VARIANT count enum_type payload_type` resolve one declared enum schema. +The constructor must supply the declared payload types; an ancestor class +payload requires an explicit `CLASS_UPCAST`. At execution, extraction checks the +actual live variant and its payload layout before exposing a class-bearing +value. A cast, raw pointer or foreign return cannot manufacture a class handle. Native objects carry a private dynamic tag; field accesses select the actual concrete layout, including fields inherited from a non-first base. Dispatch uses checked direct targets, not NIL-supplied host function pointers. @@ -234,14 +242,25 @@ declared-width arithmetic instead of the legacy untyped instruction behavior. ## Typed globals `LOAD_GLOBAL name type` and `STORE_GLOBAL name type` carry an optional trailing -storage type: `text`, `bool`, `u8`, `i32`, `i64`, or `f64`. Every access to one +storage type: `text`, `bool`, `u8`, `i32`, `i64`, `f64`, or `anything`. Every access to one name must agree; mixing typed and untyped accesses is invalid. Text/binary readers check that metadata and both engines reject incompatible stored values. -Typed native globals track initialization and fail on a read before a store. +Typed globals track initialization and fail on a read before a store. + +The interpreter additionally accepts an exact declared record, class or enum +identity, including a concrete `Option` schema. The compiler +materializes that schema before emitting global accesses. The loader checks +every store's proven nominal type; the interpreter recursively checks stored +values, class static views and initialization on both reads and writes. +Borrowed and affine handles cannot escape through this storage. Repeated +references retain aliasing, with validation keyed by both backing object and +resolved schema. Native compilation explicitly rejects nominal aggregate +globals before replacing an existing output artifact. The historical one-operand form remains readable, with the legacy integer ABI -on native routes and general VM values on interpreted routes. Aggregate globals -remain interpreter-only. These optional operands use the existing instruction +on native routes and general VM values on interpreted routes. Legacy untyped +globals cannot establish class provenance. Aggregate globals remain +interpreter-only. These optional operands use the existing instruction encoding, not a new binary section or version; older tools that require exactly one operand must be rebuilt with the SDK. Source globals use exact `module::name` storage identities; unnamed-root globals retain bare names. diff --git a/docs/language-reference/classes.md b/docs/language-reference/classes.md index cf846455..0d6b1464 100644 --- a/docs/language-reference/classes.md +++ b/docs/language-reference/classes.md @@ -88,9 +88,17 @@ dispatch uses a closed set of validated direct-call targets. This is not a foreign C++ ABI or a publicly writable vtable. Match tools from the same SDK when consuming class-bearing NIL. +On interpreted routes, a module global can retain a class directly, in a record, +or in an explicit `Option` value. Use `Option.none()` and +`Option.some(value)`; `unwrap()` preserves the class's checked static +view. Imported Matrix classes follow the same contract. These globals retain +their exact declared schemas and reject reads before initialization. Native +aggregate globals remain unsupported. + Generic class execution, generic method execution, first-class bound methods, trait objects, dynamic loading, ownership/borrowing, automatic destructors and -broader aggregate global/array storage are not supplied by this contract. +native aggregate globals are not supplied by this contract. Broader +class-bearing array storage also remains outside this contract. The `class-polymorphism` pipeline fixture checks ordinary and reference receivers, aliases, typed boundaries, multiple inheritance, collection and faults alongside targeted source and malformed-NIL tests. diff --git a/nilcompiler/src/codegen.cpp b/nilcompiler/src/codegen.cpp index f369b298..a8ed66bf 100644 --- a/nilcompiler/src/codegen.cpp +++ b/nilcompiler/src/codegen.cpp @@ -7461,33 +7461,37 @@ codegen::assemble_module(const ast_program &program, generate_impl_method_specialization(req, *mod, diags); } - // Preserve the checked storage type on every access, including initializer - // stores and accesses in specialized functions. Non-scalar globals retain - // their legacy interpreted representation until they have a native ABI. - for (auto &function : mod->functions) { - for (auto &instruction : function.body) { - if ((instruction.opname != "LOAD_GLOBAL" && - instruction.opname != "STORE_GLOBAL") || - instruction.args.size() != 1) - continue; - const auto declaration = global_var_decls_.find(instruction.args.front()); - if (declaration == global_var_decls_.end()) - continue; - const auto *variable = declaration->second; - auto type = variable->type_name; - if (!type && variable->initializer) - type = variable->initializer->inferred_type; - if (!type) - continue; - const auto storage_type = canonical_nil_type_name(*type); - if (is_typed_global_storage_type(storage_type)) - instruction.args.push_back(storage_type); - } - } - // Concrete aggregate types can be reachable through ABI signatures without // a literal or variant operation in this module. Materialize those schemas // independently of the checker's optional synthetic AST declarations. + const auto canonical_enum_signature = [&](const std::string &raw_type) { + const auto type = canonical_nil_type_name(raw_type); + const auto parsed = parse_generic_type_name(type); + if (!parsed || parsed->base_name.find("::") != std::string::npos) + return type; + const auto base = canonical_builtin_enum_base(parsed->base_name); + const ast_enum_decl *declaration = nullptr; + std::string owner; + const auto suffix = "::" + base; + for (const auto &[name, candidate] : enum_decls_) { + if (name != base && (name.size() <= suffix.size() || + name.compare(name.size() - suffix.size(), suffix.size(), suffix) != 0)) + continue; + // A leaf spelling can only name one registered declaration. Never pick + // an owner by shortest/longest namespace or erase an explicit owner. + if (declaration && declaration != candidate) + return type; + declaration = candidate; + if (owner.empty() || name != base) + owner = name; + } + if (!declaration || declaration->variants.empty()) + return type; + const auto qualified = owner + type.substr(type.find('<')); + const auto metadata = resolve_concrete_enum_variant(*this, *mod, qualified, + owner + "::" + declaration->variants.front().name); + return metadata ? metadata->enum_type : type; + }; std::set visited_enum_signatures; std::function materialize_enum_signature = [&](const std::string &raw_type, unsigned depth) { @@ -7522,7 +7526,7 @@ codegen::assemble_module(const ast_program &program, // Parameters already use this normalization at serialization. Return // types must share the exact schema key: String/text and spacing cannot // produce distinct native ABI identities for the same qualified enum. - function.return_type = canonical_nil_type_name(function.return_type); + function.return_type = canonical_enum_signature(function.return_type); for (const auto &instruction : function.body) if ((instruction.opname == "BOX_ANY" || instruction.opname == "UNBOX_ANY" || instruction.opname == "IS_ANY_TYPE") && instruction.args.size() == 1) @@ -7530,15 +7534,75 @@ codegen::assemble_module(const ast_program &program, materialize_struct_schema(function.return_type, *mod, function.source_line, 0, false); materialize_enum_signature(function.return_type, 0); - for (const auto ¶meter : function.params) { + for (auto ¶meter : function.params) { const auto colon = parameter.find(':'); if (colon != std::string::npos) { - materialize_struct_schema(parameter.substr(colon + 1), *mod, + const auto type = canonical_enum_signature(parameter.substr(colon + 1)); + parameter = parameter.substr(0, colon) + ": " + type; + materialize_struct_schema(type, *mod, function.source_line, 0, false); - materialize_enum_signature(parameter.substr(colon + 1), 0); + materialize_enum_signature(type, 0); } } } + for (auto &klass : mod->classes) { + for (auto &method : klass.methods) { + method.return_type = canonical_enum_signature(method.return_type); + for (auto ¶meter : method.parameter_types) + parameter = canonical_enum_signature(parameter); + } + } + + // Globals need the same concrete schemas as function signatures, even when + // initialized through a factory with no literal at the storage declaration. + // Preserve exact nominal identities on every access; the interpreter checks + // their provenance and native consumers still reject this storage profile. + std::map global_storage_types; + for (const auto &[storage, variable] : global_var_decls_) { + auto type = variable->type_name; + if (!type && variable->initializer) + type = variable->initializer->inferred_type; + if (!type) + continue; + auto storage_type = canonical_enum_signature(*type); + if (is_typed_global_storage_type(storage_type)) { + global_storage_types.emplace(storage, storage_type); + continue; + } + if (!has_nominal_global_storage_syntax(storage_type)) + continue; + storage_type = materialize_struct_schema(storage_type, *mod, + variable->line, 0, true); + materialize_enum_signature(storage_type, 0); + std::size_t matching_schemas = 0; + for (const auto &schema : mod->structs) + if (schema.name == storage_type) + ++matching_schemas; + for (const auto &schema : mod->enums) + if (schema.name == storage_type) + ++matching_schemas; + // A class has one accompanying record layout; do not count its class + // dispatch metadata as a second storage schema. + if (matching_schemas != 1) { + reject_codegen_construct(variable->line, + "global '" + storage + "' requires one exact declared storage schema for '" + + storage_type + "'", + "use a checked concrete record, class, or enum type for this global"); + continue; + } + global_storage_types.emplace(storage, storage_type); + } + for (auto &function : mod->functions) { + for (auto &instruction : function.body) { + if ((instruction.opname != "LOAD_GLOBAL" && + instruction.opname != "STORE_GLOBAL") || + instruction.args.size() != 1) + continue; + const auto storage = global_storage_types.find(instruction.args.front()); + if (storage != global_storage_types.end()) + instruction.args.push_back(storage->second); + } + } // Add string constants from local mapping for (const auto &kv : string_const_map_) { diff --git a/nilcompiler/src/llvm_backend.cpp b/nilcompiler/src/llvm_backend.cpp index 7cce0682..fa06ea64 100644 --- a/nilcompiler/src/llvm_backend.cpp +++ b/nilcompiler/src/llvm_backend.cpp @@ -2242,6 +2242,10 @@ bool NativeCodegen::generateModule(const nil_module &mod) { const Opcode op = stringToOpcode(instr.opname); if (op != Opcode::LOAD_GLOBAL && op != Opcode::STORE_GLOBAL) continue; + if (instr.args.size() == 2 && has_nominal_global_storage_syntax(instr.args[1])) { + std::cerr << "[NativeCodegen] nominal aggregate globals are not supported by native compilation\n"; + return false; + } if (instr.args.empty() || instr.args.size() > 2 || instr.args[0].empty() || (instr.args.size() == 2 && diff --git a/nilcompiler/src/nil_contract.hpp b/nilcompiler/src/nil_contract.hpp index 8d5f5788..fbe4f514 100644 --- a/nilcompiler/src/nil_contract.hpp +++ b/nilcompiler/src/nil_contract.hpp @@ -51,6 +51,62 @@ inline bool is_typed_global_storage_type(std::string_view type) { type == "i32" || type == "i64" || type == "f64" || type == "anything"; } +// The interpreter also accepts exact declared nominal aggregate identities. +// This checks only the canonical spelling, never the existence or safety of a +// schema. Consumers must separately resolve one exact record/class/enum schema +// and validate its contents and value provenance. Keep the scalar/native ABI +// predicate above separate: nominal globals have no native storage ABI yet. +inline bool has_nominal_global_storage_syntax(std::string_view type) { + const auto identifier_start = [](char value) { + return (value >= 'a' && value <= 'z') || + (value >= 'A' && value <= 'Z') || value == '_'; + }; + const auto identifier_part = [&](char value) { + return identifier_start(value) || (value >= '0' && value <= '9'); + }; + std::size_t position = 0; + const auto parse = [&](const auto &self, unsigned depth) -> bool { + if (depth > 64 || position == type.size()) return false; + const auto begin = position; + do { + if (position == type.size() || !identifier_start(type[position])) + return false; + while (position < type.size() && identifier_part(type[position])) + ++position; + if (type.substr(position, 2) != "::") break; + position += 2; + } while (true); + const auto name = type.substr(begin, position - begin); + // Borrowed, affine, structural and raw-pointer forms are outside this + // nominal-global profile, including when hidden in generic arguments. + if (name == "array" || name == "slice" || name == "tuple" || + name == "pointer" || name == "ptr" || name == "ref" || + name == "mut_ref" || name == "binding_cell" || name == "cell" || + name == "owned" || name == "borrow" || name == "fn" || + name == "function" || name == "any" || name == "__local") + return false; + if (depth == 0 && (is_typed_global_storage_type(name) || name == "void" || + name == "String" || name == "string" || name == "str" || + name == "char" || name == "boolean" || name == "flag" || + name == "int" || name == "float" || name == "double" || + name == "i8" || name == "i16" || name == "u16" || + name == "u32" || name == "u64" || name == "f32" || + name == "isize" || name == "usize")) + return false; + if (position < type.size() && type[position] == '<') { + ++position; + if (!self(self, depth + 1)) return false; + while (position < type.size() && type[position] == ',') { + ++position; + if (!self(self, depth + 1)) return false; + } + if (position == type.size() || type[position++] != '>') return false; + } + return true; + }; + return parse(parse, 0) && position == type.size(); +} + // Compiler-generated non-void fallthrough is represented explicitly in NIL. // A consumer must fail at runtime if this path is reached. For typed functions, // ordinary RET requires exactly zero frame-local operands for void or one for @@ -64,6 +120,10 @@ inline constexpr const char *nil_nonvoid_fallthrough_operand = struct Instruction; struct nil_function; struct nil_module; +// True for values whose provenance cannot be recovered from an untyped value, +// including classes, aggregates containing classes, anything and binding cells. +bool nil_type_requires_provenance(const nil_module &module, + const std::string &type); struct nil_class_def; struct nil_class_method; struct nil_class_method_resolution { diff --git a/nilcompiler/src/nil_loader.cpp b/nilcompiler/src/nil_loader.cpp index 0623633c..8d4f1962 100644 --- a/nilcompiler/src/nil_loader.cpp +++ b/nilcompiler/src/nil_loader.cpp @@ -398,7 +398,8 @@ void validate_instruction(Opcode opcode, const std::string &name, if ((opcode == Opcode::LOAD_GLOBAL || opcode == Opcode::STORE_GLOBAL) && (arguments.front().empty() || (arguments.size() == 2 && - !is_typed_global_storage_type(arguments[1])))) + !is_typed_global_storage_type(arguments[1]) && + !has_nominal_global_storage_syntax(arguments[1])))) throw std::runtime_error("NIL global access has an empty name or unsupported " "storage type" + context); @@ -564,6 +565,43 @@ struct fault_flow_state { static std::optional, std::string>> fault_callable_signature(const std::string &raw); +std::optional> enum_payload_types(const std::string &raw) { + const auto type = canonical_dynamic_type(raw); + if (type.empty() || type == "void") return std::vector{}; + if (type.front() == '(' && type.back() == ')') + return array_tuple_elements("tuple<" + type.substr(1, type.size() - 2) + ">"); + return std::vector{type}; +} + +const nil_enum_def *exact_enum_schema(const nil_module &module, const std::string &raw) { + const auto type = canonical_dynamic_type(raw); + const nil_enum_def *result = nullptr; + for (const auto &schema : module.structs) + if (canonical_dynamic_type(schema.name) == type) return nullptr; + for (const auto &schema : module.enums) + if (canonical_dynamic_type(schema.name) == type) { + if (result) return nullptr; + result = &schema; + } + return result; +} + +bool variant_owner_matches(const std::string &tag, const nil_enum_def &schema) { + const auto separator = tag.rfind("::"); + if (separator == std::string::npos) return false; + const auto owner = canonical_dynamic_type(tag.substr(0, separator)); + auto declared = canonical_dynamic_type(schema.name); + if (owner.find('<') == std::string::npos) { + const auto generic = declared.find('<'); + if (generic != std::string::npos) declared.resize(generic); + } + // The instruction's exact enum identity resolves the schema. A source tag + // may omit its namespace/generic arguments, but cannot select another owner. + return owner == declared || (declared.size() > owner.size() + 2 && + declared.compare(declared.size() - owner.size() - 2, owner.size() + 2, + "::" + owner) == 0); +} + bool class_sensitive_type(const std::string &raw, const nil_module &module) { std::unordered_set visited; std::vector pending{compact_binding_type(raw)}; @@ -571,6 +609,8 @@ bool class_sensitive_type(const std::string &raw, const nil_module &module) { auto type = pending.back(); pending.pop_back(); if (type.rfind("ref<", 0) == 0 && type.back() == '>') type = type.substr(4, type.size() - 5); if (!visited.insert(type).second) continue; + if (visited.size() > 4096) + throw std::runtime_error("NIL provenance type graph exceeds its bound"); if (type == "anything") return true; // Compiler-owned binding cells carry stack storage in native code. Use // the existing exact-provenance CFG analysis for these handles too, so @@ -582,8 +622,16 @@ bool class_sensitive_type(const std::string &raw, const nil_module &module) { pending.push_back(signature->second); pending.insert(pending.end(), signature->first.begin(), signature->first.end()); } - for (const auto &schema : module.structs) if (schema.name == type) - for (const auto &field : schema.fields) pending.push_back(compact_binding_type(field.second)); + for (const auto &schema : module.structs) + if (canonical_dynamic_type(schema.name) == canonical_dynamic_type(type)) + for (const auto &field : schema.fields) pending.push_back(compact_binding_type(field.second)); + for (const auto &schema : module.enums) + if (canonical_dynamic_type(schema.name) == canonical_dynamic_type(type)) + for (const auto &variant : schema.variants) { + const auto payloads = enum_payload_types(variant.associated_type); + if (!payloads) throw std::runtime_error("NIL enum has malformed payload metadata"); + pending.insert(pending.end(), payloads->begin(), payloads->end()); + } } return false; } @@ -595,6 +643,8 @@ bool class_provenance_type(const std::string &type, const nil_module &module) { // as a scalar callback, including through nested callable signatures. if (type.rfind("#callable:", 0) == 0) return class_sensitive_type(type.substr(10), module); + if (type.rfind("#enum:", 0) == 0) + return class_sensitive_type(type.substr(6), module); if (!type.empty() && (type.front() == '@' || type.front() == '!')) { const auto marker = type.find('@'); if (marker != std::string::npos) return class_sensitive_type(type.substr(marker + 1), module); @@ -679,7 +729,9 @@ std::string fault_stack_type(const std::string &type, const nil_module &module) if (!type.empty() && type.front() != '&' && type.front() != '*' && type.find('[') == std::string::npos && type != "any" && type != "void") { for (const auto &schema : module.enums) - if (schema.name == type) return "#enum"; + if (canonical_dynamic_type(schema.name) == canonical_dynamic_type(type)) + return exact_enum_schema(module, type) + ? "#enum:" + canonical_dynamic_type(type) : unproven_class_value; return "?"; } return "?"; @@ -858,6 +910,9 @@ nil_fault_analysis analyze_fault_body(const nil_function &function, fail("anything must be extracted with a checked cast before use as '" + expected + "'", pc); if ((class_type(checked) || class_type(actual)) && checked != actual) fail("class argument or storage requires its exact checked static view", pc); + if (checked.rfind("#enum:", 0) == 0 && checked != actual && + !(actual == "#enum" && !class_sensitive_type(expected, module))) + fail("enum argument or storage requires its exact proven nominal type", pc); if (checked.rfind("#callable:", 0) == 0 && checked != actual) fail("callable argument or storage requires its exact checked signature", pc); }; @@ -867,6 +922,30 @@ nil_fault_analysis analyze_fault_body(const nil_function &function, fail("opaque result metadata cannot establish a checked callable signature", pc); return type; }; + const auto checked_enum = [&](const std::string &raw) -> const nil_enum_def & { + const auto *schema = exact_enum_schema(module, raw); + if (!schema) fail("enum operation requires one exact concrete enum schema", pc); + validate_nil_dynamic_type(module, canonical_dynamic_type(raw)); + std::set variants; + for (const auto &variant : schema->variants) + if (variant.name.empty() || !variants.insert(variant.name).second) + fail("enum operation requires unique declared variants", pc); + return *schema; + }; + const auto checked_variant_payload = [&](const nil_enum_def &schema, + const std::string &tag, + const std::string &payload) { + if (!variant_owner_matches(tag, schema)) fail("enum tag owner disagrees with its schema", pc); + const auto name = tag.substr(tag.rfind("::") + 2); + const auto variant = std::find_if(schema.variants.begin(), schema.variants.end(), + [&](const auto &candidate) { return candidate.name == name; }); + if (variant == schema.variants.end()) fail("enum tag is absent from its schema", pc); + const auto declared = enum_payload_types(variant->associated_type); + const auto written = enum_payload_types(payload); + if (!declared || !written || *declared != *written) + fail("enum payload metadata disagrees with its exact schema", pc); + return *declared; + }; const auto exception_edge = [&](fault_flow_state exceptional) { if (exceptional.regions.empty()) return; const auto region = exceptional.regions.back(); @@ -961,7 +1040,10 @@ nil_fault_analysis analyze_fault_body(const nil_function &function, state.stack.push_back(type); break; } case Opcode::STORE_GLOBAL: - if (args.size() == 2 && args[1] == "anything") { + if (args.size() == 2 && has_nominal_global_storage_syntax(args[1])) { + if (state.stack.empty() || state.stack.back() != stack_type(args[1], module)) + fail("aggregate global store requires its exact proven nominal type", pc); + } else if (args.size() == 2 && args[1] == "anything") { if (state.stack.empty() || state.stack.back() != "#anything") fail("anything global requires a boxed value", pc); } else reject_class_operands(1); pop(1); break; @@ -1065,47 +1147,55 @@ nil_fault_analysis analyze_fault_body(const nil_function &function, case Opcode::NEW_VARIANT: { const auto count = static_cast(std::stoull(args[1])); if (state.stack.size() < count) fail("enum constructor requires payloads", pc); - std::vector payloads; - if (args.size() == 4 && args[3] != "void") { - if (args[3].front() == '(' && args[3].back() == ')') { - const auto parts = array_tuple_elements("tuple<" + args[3].substr(1, args[3].size() - 2) + ">"); - if (parts) payloads = *parts; - } else payloads.push_back(args[3]); - } - if (payloads.size() == count && std::find(payloads.begin(), payloads.end(), "anything") != payloads.end()) { + if (args.size() == 4) { + const auto &schema = checked_enum(args[2]); + const auto payloads = checked_variant_payload(schema, args[0], args[3]); + if (payloads.size() != count) fail("enum payload count disagrees with its schema", pc); for (std::size_t index = 0; index < count; ++index) { const auto &actual = state.stack[state.stack.size() - count + index]; - if (payloads[index] == "anything") { - if (actual != "#anything") fail("anything enum payload requires a boxed value", pc); - } else if (class_type(actual)) fail("enum payload cannot erase class or boxed provenance", pc); + check_class_argument(payloads[index], actual); + if (actual != stack_type(payloads[index], module)) + fail("enum payload requires its exact checked value category", pc); } - } else reject_class_operands(count); - std::string enumeration_type; - if (args.size() == 4) enumeration_type = args[2]; - else { - const auto separator = args[0].rfind("::"); - if (separator != std::string::npos) enumeration_type = args[0].substr(0, separator); + pop(count); state.stack.push_back("#enum:" + canonical_dynamic_type(schema.name)); break; } + reject_class_operands(count); + const auto separator = args[0].rfind("::"); + if (separator != std::string::npos && + class_sensitive_type(args[0].substr(0, separator), module)) + fail("class-bearing enum construction requires exact payload metadata", pc); pop(count); - state.stack.push_back(has_dynamic_operations && !enumeration_type.empty() - ? stack_type(enumeration_type, module) : "#enum"); break; - } - case Opcode::IS_VARIANT: reject_class_operands(1); pop(1); state.stack.push_back(stack_type("bool", module)); break; + state.stack.push_back("#enum"); break; + } + case Opcode::IS_VARIANT: + if (args.size() == 3) { + const auto &schema = checked_enum(args[1]); + (void)checked_variant_payload(schema, args[0], args[2]); + if (state.stack.empty() || state.stack.back() != "#enum:" + canonical_dynamic_type(schema.name)) + fail("enum test requires its exact proven nominal receiver", pc); + } else reject_class_operands(1); + pop(1); state.stack.push_back(stack_type("bool", module)); break; case Opcode::UNWRAP_VARIANT: { + if (state.stack.empty()) fail("enum unwrap requires a receiver", pc); + const bool typed = args.size() == 3; + if (typed) { + const auto &schema = checked_enum(args[1]); + if (state.stack.back() != "#enum:" + canonical_dynamic_type(schema.name)) + fail("enum unwrap requires its exact proven nominal receiver", pc); + const auto written = enum_payload_types(args[2]); + const auto count = static_cast(std::stoull(args[0])); + if (!written || written->size() != count || + std::none_of(schema.variants.begin(), schema.variants.end(), [&](const auto &variant) { + const auto declared = enum_payload_types(variant.associated_type); + return declared && *declared == *written; + })) fail("enum unwrap payload metadata disagrees with its schema", pc); + pop(1); + for (const auto &payload : *written) state.stack.push_back(opaque_stack_type(payload)); + break; + } reject_class_operands(1); - std::vector payloads; - if (args.size() == 3 && args[2] != "void") { - if (args[2].front() == '(' && args[2].back() == ')') { - const auto parts = array_tuple_elements("tuple<" + args[2].substr(1, args[2].size() - 2) + ">"); - if (parts) payloads = *parts; - } else payloads.push_back(args[2]); - } - for (const auto &payload : payloads) - if (payload != "anything" && class_sensitive_type(payload, module)) - fail("enum payload metadata cannot fabricate class provenance", pc); pop(1); const auto count = args.empty() ? 0 : std::stoull(args[0]); - if (args.size() == 3 && payloads.size() != count) fail("enum payload count disagrees with its metadata", pc); - for (std::size_t i = 0; i < count; ++i) state.stack.push_back(args.size() == 3 ? opaque_stack_type(payloads[i]) : "?"); + for (std::size_t i = 0; i < count; ++i) state.stack.push_back("?"); break; } case Opcode::CALL: { @@ -1155,6 +1245,17 @@ nil_fault_analysis analyze_fault_body(const nil_function &function, if (callee != module.functions.end()) { if (callee->return_type.empty() || callee->params.size() != count) fail("call requires an exact signature and matching arity", pc); + const bool external = callee->body.empty() || std::any_of(callee->annotations.begin(), callee->annotations.end(), + [](const auto &annotation) { + const auto dispatch = compact_binding_type(annotation); + return dispatch.rfind("@intrinsic", 0) == 0 || dispatch.rfind("@interop", 0) == 0 || + dispatch.rfind("@ritual", 0) == 0 || dispatch.rfind("@native", 0) == 0; + }); + if (external) { + reject_class_operands(count); + if (class_sensitive_type(callee->return_type, module)) + fail("external calls cannot establish class-bearing result provenance", pc); + } for (std::size_t i = 0; i < count; ++i) { const auto colon = callee->params[i].find(':'); auto type = colon == std::string::npos ? "" : callee->params[i].substr(colon + 1); @@ -1273,6 +1374,8 @@ nil_fault_analysis analyze_fault_body(const nil_function &function, if (source_type == "#owned") fail("CAST cannot erase affine ownership provenance", pc); if (class_type(source_type) || class_type(target_type)) fail("CAST cannot fabricate or erase class provenance; use CLASS_UPCAST", pc); + if (target_type.rfind("#enum:", 0) == 0 && source_type != target_type) + fail("CAST cannot fabricate or change enum provenance", pc); if (target_type.rfind("#callable:", 0) == 0 && source_type != target_type) fail("CAST cannot fabricate or change a callable signature", pc); if (!target_type.empty() && target_type.front() == '@' && source_type != target_type) @@ -1346,6 +1449,10 @@ nil_fault_analysis analyze_fault_body(const nil_function &function, } // namespace +bool nil_type_requires_provenance(const nil_module &module, const std::string &type) { + return class_sensitive_type(type, module); +} + void validate_nil_dynamic_type(const nil_module &module, const std::string &raw, bool allow_anything) { const auto fail = [&](const std::string &type) { @@ -1458,6 +1565,20 @@ void validate_nil_fault_contract(const nil_module &module) { void validate_nil_class_provenance(const nil_module &module) { std::unordered_set related; + for (const auto &function : module.functions) + for (const auto &instruction : function.body) + if ((instruction.opname == "LOAD_GLOBAL" || instruction.opname == "STORE_GLOBAL") && + instruction.args.size() == 2 && has_nominal_global_storage_syntax(instruction.args[1])) { + const auto &type = instruction.args[1]; + validate_nil_dynamic_type(module, type); + const auto records = std::count_if(module.structs.begin(), module.structs.end(), + [&](const auto &schema) { return canonical_dynamic_type(schema.name) == type; }); + const auto enumerations = std::count_if(module.enums.begin(), module.enums.end(), + [&](const auto &schema) { return canonical_dynamic_type(schema.name) == type; }); + if (records + enumerations != 1) + throw std::runtime_error("NIL aggregate global requires one exact nominal schema"); + related.insert(type); + } bool dynamic_operations = false; for (const auto &function : module.functions) for (const auto &instruction : function.body) @@ -1563,6 +1684,7 @@ void validate_nil_class_provenance(const nil_module &module) { if (!related.count(enumeration.name) && std::any_of(enumeration.variants.begin(), enumeration.variants.end(), [&](const auto &variant) { return related.count(compact_binding_type(variant.associated_type)) != 0 || + class_sensitive_type(variant.associated_type, module) || (dynamic_operations && variant.associated_type.find("anything") != std::string::npos); })) changed = related.insert(enumeration.name).second || changed; @@ -1576,7 +1698,8 @@ void validate_nil_class_provenance(const nil_module &module) { } const auto related_type = [&](const std::string &raw) { const auto type = compact_binding_type(raw); - return related.count(type) != 0 || (dynamic_operations && type.find("anything") != std::string::npos) || contains_binding_cell_type(type) || + return related.count(type) != 0 || class_sensitive_type(type, module) || + (dynamic_operations && type.find("anything") != std::string::npos) || contains_binding_cell_type(type) || fault_callable_signature(type).has_value(); }; for (const auto &function : module.functions) { @@ -1671,11 +1794,20 @@ static void attach_class_metadata(std::vector &program, nil_module } else if (instruction.op == Opcode::INTEROP_CALL) { const nil_instruction call{"INTEROP_CALL", instruction.args, instruction.line}; checked_conversion::validate_instruction(metadata, call); - } else if (instruction.op == Opcode::CLASS_UPCAST || instruction.op == Opcode::CALL_METHOD || + } else if ((instruction.op == Opcode::LOAD_GLOBAL || instruction.op == Opcode::STORE_GLOBAL) && + instruction.args.size() == 2 && has_nominal_global_storage_syntax(instruction.args[1])) + throw std::runtime_error("Nominal global instructions require a declared function"); + else if (((instruction.op == Opcode::NEW_VARIANT && instruction.args.size() == 4) && + class_sensitive_type(instruction.args[2], metadata)) || + ((instruction.op == Opcode::IS_VARIANT || instruction.op == Opcode::UNWRAP_VARIANT) && + instruction.args.size() == 3 && class_sensitive_type(instruction.args[1], metadata))) + throw std::runtime_error("Class-bearing enum instructions require a declared function"); + else if (instruction.op == Opcode::CLASS_UPCAST || instruction.op == Opcode::CALL_METHOD || instruction.op == Opcode::BOX_ANY || instruction.op == Opcode::UNBOX_ANY || instruction.op == Opcode::IS_ANY_TYPE) throw std::runtime_error("Class or anything instruction outside a declared function"); } checked_conversion::validate_module(metadata); + validate_global_storage_contract(metadata); validate_nil_class_contract(metadata); // Tuple arrays also use exact record schemas at execution time, including // modules that declare no classes at all. @@ -1688,10 +1820,13 @@ static void attach_class_metadata(std::vector &program, nil_module void validate_nil_class_contract(const std::vector &program) { if (program.empty()) return; + validate_global_storage_contract(program); const auto metadata = program.front().module_metadata; if (!metadata) { for (const auto &instruction : program) - if (instruction.op == Opcode::CLASS_UPCAST || instruction.op == Opcode::CALL_METHOD || + if (((instruction.op == Opcode::LOAD_GLOBAL || instruction.op == Opcode::STORE_GLOBAL) && + instruction.args.size() == 2 && has_nominal_global_storage_syntax(instruction.args[1])) || + instruction.op == Opcode::CLASS_UPCAST || instruction.op == Opcode::CALL_METHOD || instruction.op == Opcode::BOX_ANY || instruction.op == Opcode::UNBOX_ANY || instruction.op == Opcode::IS_ANY_TYPE) throw std::runtime_error("NIL class/anything instructions require explicit module metadata"); else { diff --git a/nilcompiler/src/vm.cpp b/nilcompiler/src/vm.cpp index 8c3fb42a..5cc67a15 100644 --- a/nilcompiler/src/vm.cpp +++ b/nilcompiler/src/vm.cpp @@ -826,6 +826,7 @@ void VM::loadProgram(const std::vector &program, ++checkpoint_generation_; program_ = program; class_metadata_ = program.empty() ? nullptr : program.front().module_metadata; + provenance_type_cache_.clear(); constants_ = constants; labels_.clear(); functions_.clear(); @@ -1627,7 +1628,8 @@ void VM::executeInstruction(const Instruction &instr) { } return match; }; - std::unordered_set validated_storage_objects; + std::unordered_map> + validated_storage_objects; const auto validate_tuple_value = [&](const auto &self, const Value &value, const std::string &type, const std::string &operation, @@ -1756,9 +1758,11 @@ void VM::executeInstruction(const Instruction &instr) { if (!actual_schema) reject(); schema = actual_schema; } else if (actual_schema != schema) reject(); - // Repeated record references preserve aliasing, and recursive interpreter - // records must not recurse forever during this storage-boundary check. - if (!validated_storage_objects.insert(object->data.get()).second) return; + // Repeated references to the same object and schema preserve aliasing and + // terminate recursion. An embedding caller can present the same backing + // data through different nominal wrappers; each schema must be checked. + // Class ancestor views resolve to the actual schema above. + if (!validated_storage_objects[object->data.get()].insert(schema).second) return; const auto &data = *object->data; if (data.fields.size() + data.array_fields.size() + data.string_fields.size() + data.double_fields.size() + data.struct_fields.size() + data.enum_fields.size() + @@ -1828,7 +1832,22 @@ void VM::executeInstruction(const Instruction &instr) { if (instr.args.size() != 2) return; const auto &type = instr.args[1]; - if (type == "anything") { + if (type == "anything" || has_nominal_global_storage_syntax(type)) { + if (type != "anything") { + if (!class_metadata_) + throw std::runtime_error("global storage requires exact module type metadata"); + // Nominal globals are an interpreter contract. Their serialized + // spelling must identify a declared schema, never infer one from a + // suffix, an opaque integer, or a borrowed storage handle. + validate_nil_dynamic_type(*class_metadata_, type, true); + const auto exact = canonical_dynamic_type(type); + const auto structures = std::count_if(class_metadata_->structs.begin(), class_metadata_->structs.end(), + [&](const auto &schema) { return canonical_dynamic_type(schema.name) == exact; }); + const auto enumerations = std::count_if(class_metadata_->enums.begin(), class_metadata_->enums.end(), + [&](const auto &schema) { return canonical_dynamic_type(schema.name) == exact; }); + if (structures + enumerations != 1) + throw std::runtime_error("global storage requires one exact declared nominal schema"); + } validate_tuple_value(validate_tuple_value, value, type, "global storage", 0); return; } @@ -1845,6 +1864,58 @@ void VM::executeInstruction(const Instruction &instr) { throw std::runtime_error("Global '" + instr.args[0] + "' value does not match storage type '" + type + "'"); }; + const auto enum_payload_types = [](const std::string &raw) { + const auto type = canonical_dynamic_type(raw); + if (type.empty() || type == "void") return std::vector{}; + if (type.front() == '(' && type.back() == ')') { + const auto parts = array_tuple_elements("tuple<" + type.substr(1, type.size() - 2) + ">"); + if (!parts) throw std::runtime_error("enum operation has malformed payload metadata"); + return *parts; + } + return std::vector{type}; + }; + const auto requires_provenance = [&](const std::string &type) { + if (!class_metadata_) return false; + const auto known = provenance_type_cache_.find(type); + if (known != provenance_type_cache_.end()) return known->second; + const bool required = nil_type_requires_provenance(*class_metadata_, type); + provenance_type_cache_.emplace(type, required); + return required; + }; + const auto validate_provenance_enum = [&](const Value &value, const std::string &type, + const std::string &payload, std::size_t count, + const std::string &operation) { + const auto reject = [&]() { + throw std::runtime_error(operation + ": requires its exact declared enum, live variant and payload types"); + }; + if (!class_metadata_) reject(); + const auto exact = canonical_dynamic_type(type); + const nil_enum_def *schema = nullptr; + for (const auto &candidate : class_metadata_->enums) { + if (canonical_dynamic_type(candidate.name) != exact) continue; + if (schema) reject(); + schema = &candidate; + } + const auto *item = std::get_if(&value); + if (!schema || !item || canonical_dynamic_type(item->type_name) != exact) reject(); + validate_nil_dynamic_type(*class_metadata_, exact, true); + const auto tag = canonical_variant_name(item->variant_name); + const auto separator = tag.rfind("::"); + const auto name = separator == std::string::npos ? tag : tag.substr(separator + 2); + const nil_enum_def::variant *variant = nullptr; + for (const auto &candidate : schema->variants) { + if (candidate.name != name) continue; + if (variant) reject(); + variant = &candidate; + } + if (!variant || item->payloads.size() != count) reject(); + const auto requested = enum_payload_types(payload); + const auto declared = enum_payload_types(variant->associated_type); + if (requested.size() != count || requested != declared) reject(); + // The actual tag selects the payload layout. Metadata for another variant + // must never turn a scalar or another class into a checked receiver. + validate_tuple_value(validate_tuple_value, value, exact, operation, 0); + }; switch (instr.op) { case Opcode::PUSH_CONST_STR: pushStack(constants_.at(instr.args[0])); @@ -7680,6 +7751,10 @@ void VM::executeInstruction(const Instruction &instr) { std::reverse(payloads.begin(), payloads.end()); ev.payloads = std::move(payloads); + if (instr.args.size() == 4 && requires_provenance(instr.args[2])) + validate_provenance_enum(Value(ev), instr.args[2], instr.args[3], + static_cast(arg_count), "NEW_VARIANT"); + pushStack(ev); } break; case Opcode::IS_VARIANT: { @@ -7705,6 +7780,11 @@ void VM::executeInstruction(const Instruction &instr) { int payload_count = instr.args.empty() ? 0 : std::stoi(instr.args[0]); Value v = popStack(); + if (instr.args.size() == 3 && + (requires_provenance(instr.args[1]) || requires_provenance(instr.args[2]))) + validate_provenance_enum(v, instr.args[1], instr.args[2], + static_cast(payload_count), "UNWRAP_VARIANT"); + if (std::holds_alternative(v)) { const auto &ev = std::get(v); // Push payloads onto stack (in order, up to payload_count) diff --git a/nilcompiler/src/vm.hpp b/nilcompiler/src/vm.hpp index 2553b1a9..e5950c74 100644 --- a/nilcompiler/src/vm.hpp +++ b/nilcompiler/src/vm.hpp @@ -494,6 +494,7 @@ class VM { std::vector program_; std::shared_ptr class_metadata_; + std::unordered_map provenance_type_cache_; std::unordered_map constants_; // A simple call frame description stored on the call stack. It keeps the // return program-counter and the local variable map for the function. diff --git a/notebook/2026-11-21-goetic-enigma-sdk.md b/notebook/2026-11-21-goetic-enigma-sdk.md index c5ef101f..a7333bbb 100644 --- a/notebook/2026-11-21-goetic-enigma-sdk.md +++ b/notebook/2026-11-21-goetic-enigma-sdk.md @@ -2,9 +2,12 @@ ## Status and question -Implementation integrated; twenty focused Linux contracts pass without skips. -Full source and installed SDK qualification is in progress. This is a development -SDK candidate, not a stable release or a live application migration. +The combined SDK at `6a0563438aff61b3cb751012ae00c323f836cf13` passes all +609 Linux source tests without skips and 1,248 installed fixed-output routes. +Its handoff is held: the actual Goetic/Enigma consumer exposed missing class +provenance through module globals and enum payloads. Corrections and fresh +consumer qualification are in progress. This remains development SDK work, +not a stable release or a live application migration. Goetic needs its qualified compiler fixes together with Enigma's durable I/O surface, including `nil.std.io.file_lock_is_held`. The existing Goetic SDK came @@ -56,6 +59,17 @@ no SDK. Initial hosted Apple Silicon builds also found a missing direct POSIX explicitly. Those original failures remain retained, with fresh qualification required after the corrections. +The corrected clean `6a05634` candidate then passed all 609 Linux source tests, +1,248 installed fixed-output routes, sixteen installed durable executions, +24 malformed-ABI rejections and 72 foreign-library rejections. Each installed +library form passed 202 console executions/checks. Independent replay verified +all 279 payload files and the unchanged shared SDK selection. Both hosted +source campaigns passed LLVM-ON coverage and the LLVM-OFF profile with its +explicit expected skips; all four host interpreter campaigns passed. Intel +and Apple Silicon macOS also passed the application campaign, including all +88 editor groups each with no exclusions. These results belong to `6a05634`, +before the actual-consumer corrections below, and do not qualify those changes. + Both corrections have retained old-behavior controls. Original durable helper tests pass against the old directory helper; adding the umask cases fails that helper, and the corrected helper passes. Before the VM guard, a foreign-library @@ -80,6 +94,60 @@ and an Enigma application-record API require their own application evidence. ## Boundaries and follow-up +### Actual consumer findings + +The real snapshot adapter imports Matrix `record_owner` and `record_client` +classes. An explicit `Option.none()/some(owner)/unwrap()` path +compiled but failed loader admission; a guarded record wrapper and a direct +class global also lost the receiver's exact static view. Compilation alone +therefore did not establish consumer support. The held SDK manifest is +`5da8dc24656533137619628787358f3a6bd46198027ec9231c882c4d4981b219`. + +The correction materializes exact global schemas before emitting access +metadata, preserves concrete enum identities in the loader's control-flow +analysis and checks actual enum tags and payload layouts during extraction. +Class payloads require proven static views; casts, erased globals, foreign +returns, external stubs and forged schemas cannot establish that provenance. +The runtime recursively validates nominal globals, including class fields and +initialization. Its cycle guard includes both backing-object and resolved +schema identity, so two different nominal wrappers cannot share a validation +result just because they share data. + +The first actual-consumer replay after that correction found a further emitted +signature mismatch: an imported Matrix function returned an unqualified +`Result` while its specialized caller used the qualified concrete +enum. Code generation now resolves an unqualified generic enum signature only +when the registered declaration is unique, keeping explicit owners intact. +Function parameters, returns, class method metadata and global metadata share +that resolved identity. The loader continues to require exact provenance. + +Before packaging, the provenance correction passed all 609 source tests with +zero skips; the later signature correction passed 25 focused contracts and the +expanded global contract. A private real-engine consumer then passed textual +and binary interpreter execution: actual owner/client creation and admission, +optional storage, put/get, close/reset, reopen with a new incarnation and +persisted-data checks. The engine's manifest oracle verified bytes, checksums +and modes. These runs used a diagnostic tool stage, not a qualified SDK. + +The exact copied Goetic harness now passes loader admission and begins normal +execution, but encounters an `unwrap()` on an error result. That application +acceptance failure remains under investigation; no final SDK handoff follows +from the successful engine-only probe. The expanded small signature fixture +also passes the old tools, so it is a positive regression case, not proof of the +original compiler defect. The retained real-consumer before/after executions +establish that boundary. + +Regression coverage includes imported Matrix classes used from Ny and Matrix, +textual/binary NIL, fresh interpreter instances, direct and record-wrapped +globals, explicit optional values, initialization failure and native rejection +without replacing prior output. Installed qualification repeats the contract +against both standard-library forms. The actual Goetic runner and a separate +real-engine optional-value consumer must also pass in private source copies +before a new immutable SDK is handed over. No live application or data change +is part of this check. + +### Remaining boundaries + Durable filesystem primitives are currently POSIX-only. Windows rejection checks prove explicit unsupported behavior, not parity. macOS needs its own current-source execution evidence. Synchronization tests do not qualify storage diff --git a/scripts/check-sdk-durable-io.py b/scripts/check-sdk-durable-io.py index 60471989..753a01ae 100644 --- a/scripts/check-sdk-durable-io.py +++ b/scripts/check-sdk-durable-io.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Qualify installed durable I/O and console providers on POSIX hosts. +"""Qualify installed durable I/O, console and nominal globals on POSIX hosts. Uses the existing source contracts and SDK validator. Evidence is retained in a fresh directory outside the SDK; success is not a language release declaration. @@ -34,6 +34,10 @@ NEGATIVE_LIBRARY = {(operation, route, schema) for operation in OPERATIONS for route in ("text-vm", "binary-vm") for schema in ("present", "absent")} +GLOBAL_SUMMARY = ( + b"global contracts passed: 9 negative and 3 control cases in text/binary NIL\n" + b"nominal global contracts passed: 8 VM executions, 2 initialization rejections, 2 native rejections\n" +) def require(condition: bool, message: str) -> None: @@ -131,10 +135,13 @@ def helper_inputs() -> list[Path]: ROOT / "scripts/check-sdk-routes.py", ROOT / "scripts/sdk_capabilities.py", ROOT / "tests/tools/durable_file_io_contract.py", ROOT / "tests/tools/native_console_contract.py", + ROOT / "tests/tools/global_contract.py", ROOT / "tests/tools/ordinary_io_parity_contract.py", ROOT / "validation/ny-3d/scripts/debugger_process.py", ROOT / "tests/native_output_staging.py", - ROOT / "tests/matrix/io/durable-file-io.matrix"] + ROOT / "tests/matrix/io/durable-file-io.matrix", + ROOT / "tests/language/module-global-contract.ny", + ROOT / "tests/language/module-global-contract.stdout"] paths.extend(sorted((ROOT / "tests/language").glob("durable-file-io*.ny"))) paths.extend(sorted((ROOT / "tests/tools/fixtures").glob("console-input*.*"))) return paths @@ -144,7 +151,7 @@ def qualify(args: argparse.Namespace, sdk: Path, work: Path) -> dict: logs = work / "logs" logs.mkdir() ownership = support.load_ownership(ROOT) - # Python assertions are part of the existing console contract. Do not let + # Python assertions are part of the existing console/global contracts. Do not let # caller optimization or module-path overrides disable/replace that proof. spec = importlib.util.spec_from_file_location("nil_installed_route_policy", ROOT / "scripts/check-sdk-routes.py") route_policy = importlib.util.module_from_spec(spec) @@ -156,7 +163,7 @@ def qualify(args: argparse.Namespace, sdk: Path, work: Path) -> dict: temporary = work / "temporary" temporary.mkdir() environment["TMPDIR"] = str(temporary) - deadline = time.monotonic() + 1200 + deadline = time.monotonic() + 1800 report = {"schema": "nil.sdk.durable-io.v1", "status": "FAIL", "release_declaration": False, "source_revision": args.expected_revision, "sdk": str(sdk), "require_rc_checks": args.require_rc_checks, @@ -221,7 +228,16 @@ def run(name: str, command: list, limit: int, *, final: bool = False) -> bytes: # of program executions. Extra output, SKIP and an empty run fail. matched = re.fullmatch(rb"native console contract: ([1-9][0-9]*) executions/checks passed\n", stdout) require(matched is not None, "console helper did not report a complete PASS") - result.update(console_executions_and_checks=int(matched.group(1)), status="PASS") + result["console_executions_and_checks"] = int(matched.group(1)) + stdout = run(library_name + "-globals", [sys.executable, + ROOT / "tests/tools/global_contract.py", "--compiler", sdk / "nilcompiler", + "--interpreter", sdk / "nilinterpreter", "--assembler", sdk / "nilassembler", + "--linker", sdk / "nillinker", "--runtime", runtime, + "--nilstd", library, "--llvm", "ON"], 180) + require(stdout == GLOBAL_SUMMARY, "global helper did not report every required PASS case") + result.update(nominal_global_vm_executions=8, + nominal_global_initialization_rejections=2, + nominal_global_native_rejections=2, status="PASS") except Exception as error: report["errors"].append(str(error)) finally: @@ -245,7 +261,9 @@ def run(name: str, command: list, limit: int, *, final: bool = False) -> bytes: report["errors"].append(str(error)) if not report["errors"] and len(report["libraries"]) == 2 and report.get("sdk_unchanged"): report.update(status="PASS", execution_count=16, negative_abi_count=24, - negative_library_count=72) + negative_library_count=72, nominal_global_vm_executions=16, + nominal_global_initialization_rejections=4, + nominal_global_native_rejections=4) report["cleanup_verified"] = bool(report["commands"]) and all( row.get("cleanup_verified") is True for row in report["commands"]) return report diff --git a/tests/class_vm_tests.cpp b/tests/class_vm_tests.cpp index 27198f5a..50422752 100644 --- a/tests/class_vm_tests.cpp +++ b/tests/class_vm_tests.cpp @@ -88,6 +88,230 @@ void negative_constructed(std::vector body, const std::stri {"SET_FIELD", {"padding"}}, {"PUSH_CONST", {"40"}}, {"SET_FIELD", {"x"}}}; prefix.insert(prefix.end(), body.begin(), body.end()); negative_body(std::move(prefix), label); } + +std::vector base_value() { + return {{"NEW_STRUCT", {"Leaf"}}, {"PUSH_CONST", {"9"}}, {"SET_FIELD", {"padding"}}, + {"PUSH_CONST", {"40"}}, {"SET_FIELD", {"x"}}, {"CLASS_UPCAST", {"Base"}}}; +} +ny::nil_function &enum_main(ny::nil_module &module) { + return *std::find_if(module.functions.begin(), module.functions.end(), + [](const auto &value) { return value.name == "main"; }); +} +ny::nil_module class_enum_fixture() { + auto module = fixture(); + module.enums = {{"Container", {{"Item", "Base"}, {"None", ""}, {"Other", "i64"}}}, + {"OtherContainer", {{"Item", "Base"}, {"None", ""}}}, + {"Nested", {{"Item", "Container"}}}}; + module.structs.push_back({"ChoiceBox", {{"item", "Container"}}}); + auto body = base_value(); + const std::vector rest = { + {"NEW_VARIANT", {"Container::Item", "1", "Container", "Base"}}, + {"STORE_GLOBAL", {"stored", "Container"}}, + {"LOAD_GLOBAL", {"stored", "Container"}}, {"CALL", {"enum_identity", "1"}}, + {"STORE_LOCAL", {"choice"}}, {"LOAD_LOCAL", {"choice"}}, + {"IS_VARIANT", {"Container::Item", "Container", "Base"}}, {"CONSOLE_WRITELN", {}}, + {"LOAD_LOCAL", {"choice"}}, {"UNWRAP_VARIANT", {"1", "Container", "Base"}}, + {"CALL_METHOD", {"Base", "read", "1"}}, {"CONSOLE_WRITELN", {}}, + {"NEW_STRUCT", {"ChoiceBox"}}, {"LOAD_LOCAL", {"choice"}}, {"SET_FIELD", {"item"}}, + {"STORE_GLOBAL", {"boxed", "ChoiceBox"}}, {"LOAD_GLOBAL", {"boxed", "ChoiceBox"}}, + {"GET_FIELD", {"item"}}, {"UNWRAP_VARIANT", {"1", "Container", "Base"}}, + {"CALL_METHOD", {"Base", "read", "1"}}, {"CONSOLE_WRITELN", {}}, + {"NEW_VARIANT", {"Container::None", "0", "Container", "void"}}, + {"STORE_GLOBAL", {"stored", "Container"}}, {"LOAD_GLOBAL", {"stored", "Container"}}, + {"IS_VARIANT", {"Container::None", "Container", "void"}}, {"CONSOLE_WRITELN", {}}, {"RET", {}}}; + body.insert(body.end(), rest.begin(), rest.end()); + enum_main(module).body = std::move(body); + module.functions.push_back(function("enum_identity", {"value:Container"}, "Container", + {{"STORE_LOCAL", {"value"}}, {"LOAD_LOCAL", {"value"}}, {"RET", {}}})); + return module; +} + +void class_enum_contract() { + for (bool binary : {false, true}) { + auto module = class_enum_fixture(); + std::unordered_map constants; + const auto program = parse(module, binary, constants); + ny::VM vm; std::ostringstream output; vm.setOutputStream(output); + vm.loadProgram(program, constants); vm.execute(); + check(output.str() == "1\n42\n42\n1\n", + "typed class enum survives calls, globals, record fields and inherited dispatch"); + std::istringstream source(serialize(module, binary)); + const auto parsed = binary ? ny::parseBinaryNilModule(source) : ny::parseTextNilModule(source); + check(parsed->enums.size() == 3, "module readers accept checked class enum payloads"); + for (const auto &mutation : std::vector&)>>{ + [](auto &instructions) { + for (auto &instruction : instructions) if (instruction.op == ny::Opcode::NEW_VARIANT) { + instruction.args[3] = "i64"; return; + } + }, + [](auto &instructions) { + for (auto &instruction : instructions) if (instruction.op == ny::Opcode::UNWRAP_VARIANT) { + instruction.args[1] = "OtherContainer"; return; + } + }, + [](auto &instructions) { + for (auto &instruction : instructions) if (instruction.op == ny::Opcode::STORE_GLOBAL) { + instruction.args.resize(1); return; + } + }, + [](auto &instructions) { + const auto metadata = instructions.front().module_metadata; + instructions.insert(instructions.begin(), {ny::Opcode::LOAD_GLOBAL, {"stored", "Container"}}); + instructions.front().module_metadata = metadata; + }}) { + auto altered = program; mutation(altered); bool caught = false; + try { vm.loadProgram(altered, constants); } catch (const std::runtime_error &) { caught = true; } + check(caught, "embedding revalidates enum/global provenance after instruction mutation"); + } + // Static enum identity does not tell us which variant is currently live. + // Both payload layouts are declared, so this must reach the VM's actual + // tag/count check rather than being accepted on metadata alone. + for (bool empty : {false, true}) { + auto wrong = class_enum_fixture(); + auto &body = enum_main(wrong).body; + body = empty ? std::vector{{"NEW_VARIANT", {"Container::None", "0", "Container", "void"}}} + : std::vector{{"PUSH_CONST", {"7"}}, {"NEW_VARIANT", {"Container::Other", "1", "Container", "i64"}}}; + body.insert(body.end(), {{"UNWRAP_VARIANT", {"1", "Container", "Base"}}, {"POP", {}}, {"RET", {}}}); + auto wrong_program = parse(wrong, binary, constants); + vm.loadProgram(wrong_program, constants); bool caught = false; + try { vm.execute(); } catch (const std::runtime_error &error) { + caught = std::string(error.what()).find("UNWRAP_VARIANT") != std::string::npos; + } + check(caught, "runtime rejects a different live enum variant before exposing its payload"); + } + } + const auto negative = [](std::vector body, const std::string &label) { + auto module = class_enum_fixture(); enum_main(module).body = std::move(body); rejected(module, label); + }; + negative({{"PUSH_CONST", {"0"}}, {"NEW_VARIANT", {"Container::Item", "1", "Container", "Base"}}, + {"POP", {}}, {"RET", {}}}, "scalar cannot fabricate a class enum payload"); + for (const auto &constructor : std::vector>{ + {"OtherContainer::Item", "1", "Container", "Base"}, + {"Container::Missing", "1", "Container", "Base"}, + {"Container::Item", "1", "Container", "i64"}, + {"Container::Item", "0", "Container", "Base"}, + {"Missing::Item", "1", "Missing", "Base"}, + {"Container::Item", "1"}}) { + auto body = base_value(); body.push_back({"NEW_VARIANT", constructor}); + body.insert(body.end(), {{"POP", {}}, {"RET", {}}}); negative(body, "class enum constructor requires exact schema and payload metadata"); + } + auto without_upcast = base_value(); without_upcast.pop_back(); + without_upcast.insert(without_upcast.end(), {{"NEW_VARIANT", {"Container::Item", "1", "Container", "Base"}}, + {"POP", {}}, {"RET", {}}}); + negative(without_upcast, "class enum payload requires explicit checked ancestor view"); + for (const auto &tail : std::vector>{ + {{"CAST", {"i64"}}, {"POP", {}}, {"RET", {}}}, + {{"FREE", {}}, {"RET", {}}}, + {{"CALL", {"unknown", "1"}}, {"RET", {}}}, + {{"STORE_GLOBAL", {"legacy"}}, {"RET", {}}}, + {{"STORE_GLOBAL", {"wrong", "Base"}}, {"RET", {}}}, + {{"UNWRAP_VARIANT", {"1", "OtherContainer", "Base"}}, {"POP", {}}, {"RET", {}}}, + {{"UNWRAP_VARIANT", {"1", "Container", "Leaf"}}, {"POP", {}}, {"RET", {}}}, + {{"NEW_VARIANT", {"Nested::Item", "1", "Nested", "Container"}}, {"FREE", {}}, {"RET", {}}}}) { + auto body = base_value(); body.push_back({"NEW_VARIANT", {"Container::Item", "1", "Container", "Base"}}); + body.insert(body.end(), tail.begin(), tail.end()); negative(body, "class enum provenance survives operations and nesting"); + } + negative({{"LOAD_GLOBAL", {"legacy"}}, {"CALL", {"enum_identity", "1"}}, {"POP", {}}, {"RET", {}}}, + "legacy global cannot supply a proven class enum"); + negative({{"LOAD_GLOBAL", {"unknown", "Missing"}}, {"POP", {}}, {"RET", {}}}, + "typed global requires a real unique schema"); + negative({{"PUSH_CONST", {"0"}}, {"STORE_GLOBAL", {"wrong", "Container"}}, {"RET", {}}}, + "scalar cannot initialize a nominal enum global"); + negative({{"PUSH_CONST", {"0"}}, {"CAST", {"Container"}}, {"POP", {}}, {"RET", {}}}, + "cast metadata cannot fabricate a class enum"); + negative({{"INTEROP_CALL", {"intrinsic", "forged", "0", "Container"}}, {"POP", {}}, {"RET", {}}}, + "foreign result metadata cannot fabricate a class enum"); + for (bool annotated : {false, true}) { + auto external = class_enum_fixture(); + external.functions.push_back(function("foreign_enum", {}, "Container", + annotated ? std::vector{{"NEW_VARIANT", {"Container::None", "0", "Container", "void"}}, {"RET", {}}} + : std::vector{})); + if (annotated) external.functions.back().annotations.push_back("@intrinsic(\"foreign.enum\")"); + enum_main(external).body = {{"CALL", {"foreign_enum", "0"}}, {"POP", {}}, {"RET", {}}}; + rejected(external, "external declaration cannot establish class-bearing enum return provenance"); + } + auto join = base_value(); + join.insert(join.end(), {{"NEW_VARIANT", {"Container::Item", "1", "Container", "Base"}}, + {"STORE_LOCAL", {"choice"}}, {"PUSH_CONST", {"1"}}, {"JMP_IF", {"join"}}, + {"LOAD_LOCAL", {"missing"}}, {"STORE_LOCAL", {"choice"}}, {"LABEL", {"join"}}, + {"LOAD_LOCAL", {"choice"}}, {"FREE", {}}, {"RET", {}}}); + negative(join, "enum class taint survives an unknown local CFG predecessor"); + auto duplicate = class_enum_fixture(); duplicate.enums.push_back(duplicate.enums.front()); + rejected(duplicate, "duplicate enum schemas cannot establish class provenance"); + duplicate = class_enum_fixture(); duplicate.enums.front().variants.push_back({"Item", "Base"}); + rejected(duplicate, "duplicate variant names cannot establish class provenance"); + auto binding = class_enum_fixture(); binding.enums.front().variants[0].associated_type = "$nil.binding.cell.i64"; + rejected(binding, "enum closure cannot smuggle binding-reference storage"); + ny::VM vm; bool caught = false; + try { vm.loadProgram({{ny::Opcode::LOAD_GLOBAL, {"unknown", "Container"}}}, {}); } + catch (const std::runtime_error &) { caught = true; } + check(caught, "raw embedding global metadata requires explicit schemas"); +} + +void nominal_global_alias_contract() { + const auto transfer = [](const std::string &type) { + return function("main", {}, "void", { + {"LOAD_GLOBAL", {"stored", type}}, {"STORE_GLOBAL", {"copied", type}}, + {"PUSH_CONST", {"1"}}, {"STORE_GLOBAL", {"completed", "i64"}}, {"RET", {}}}); + }; + for (bool binary : {false, true}) { + for (bool mismatched_schema : {false, true}) { + ny::nil_module module; module.module_name = "global_alias_tests"; + module.structs = {{"First", {{"x", "i64"}}}, {"Second", {{"x", "text"}}}, + {"Pair", {{"first", "First"}, {"second", mismatched_schema ? "Second" : "First"}}}}; + module.functions = {transfer("Pair")}; + std::unordered_map constants; + const auto program = parse(module, binary, constants); + ny::StructValue first; first.type_name = "First"; first.fields()["x"] = 7; + auto second = first; second.type_name = mismatched_schema ? "Second" : "First"; + ny::StructValue pair; pair.type_name = "Pair"; + pair.struct_fields()["first"] = std::make_shared(first); + pair.struct_fields()["second"] = std::make_shared(second); + ny::VM vm; vm.loadProgram(program, constants); vm.setGlobal("stored", pair); + bool caught = false; + try { vm.execute(); } + catch (const std::runtime_error &error) { + caught = std::string(error.what()).find("global storage") != std::string::npos; + } + if (mismatched_schema) { + check(caught, "shared backing storage is validated independently for each nominal schema"); + check(!vm.hasGlobal("copied") && !vm.hasGlobal("completed") && + std::get(vm.getGlobal("stored")).data == pair.data && + first.fields().size() == 1 && first.fields().at("x") == 7 && + first.string_fields().empty() && first.data == second.data, + "rejected nominal global preserves existing storage and publishes no result"); + } else { + check(!caught && vm.hasGlobal("completed"), "shared same-schema record remains a valid nominal global"); + if (vm.hasGlobal("copied")) { + const auto copied = std::get(vm.getGlobal("copied")); + check(copied.data == pair.data && + copied.struct_fields().at("first")->data == copied.struct_fields().at("second")->data, + "accepted nominal global preserves repeated record identity"); + } + } + } + ny::nil_module module; module.module_name = "global_recursive_tests"; + module.structs = {{"Node", {{"value", "i64"}, {"next", "Node"}}}}; + module.functions = {transfer("Node")}; + std::unordered_map constants; + const auto program = parse(module, binary, constants); + ny::StructValue node; node.type_name = "Node"; node.fields()["value"] = 9; + node.struct_fields()["next"] = std::make_shared(node); + ny::VM vm; vm.loadProgram(program, constants); vm.setGlobal("stored", node); + bool caught = false; + try { vm.execute(); } catch (const std::runtime_error &) { caught = true; } + check(!caught && vm.hasGlobal("completed"), "recursive same-schema global terminates validation"); + if (vm.hasGlobal("copied")) { + const auto copied = std::get(vm.getGlobal("copied")); + check(copied.data == node.data && copied.struct_fields().at("next")->data == node.data, + "recursive nominal global preserves its cycle and identity"); + } + // The fixture deliberately creates a shared_ptr cycle. Release that edge + // after observing it so the regression itself leaves no allocation behind. + node.struct_fields().clear(); + } +} + void positives() { for (bool binary : {false, true}) { auto module = fixture(); std::unordered_map constants; @@ -227,7 +451,7 @@ void negatives() { } } // namespace int main() { - try { positives(); negatives(); } + try { positives(); negatives(); class_enum_contract(); nominal_global_alias_contract(); } catch (const std::exception &error) { std::cerr << "Unexpected exception: " << error.what() << '\n'; return 1; } if (failures) return 1; std::cout << "Class metadata, provenance, dispatch, alias and version contracts passed\n"; diff --git a/tests/tools/global_contract.py b/tests/tools/global_contract.py index 08536d30..61704fb5 100644 --- a/tests/tools/global_contract.py +++ b/tests/tools/global_contract.py @@ -11,6 +11,8 @@ import struct import subprocess import tempfile +import textwrap +import shlex # The toolchain appends .exe to extensionless executables on Windows. sys.path.insert(0, str(Path(__file__).resolve().parents[1])) @@ -50,12 +52,13 @@ def main() -> None: parser.add_argument("--assembler", type=Path, required=True) parser.add_argument("--linker", type=Path, required=True) parser.add_argument("--runtime", type=Path, required=True) + parser.add_argument("--nilstd", type=Path, required=True) parser.add_argument("--llvm", choices=("ON", "OFF"), required=True) args = parser.parse_args() environment = os.environ.copy() for key in ("NY_LIBRARY_PATH", "NIL_LIBRARY_PATH", "NY_LEX_DUMP", "NY_PARSE_TRACE", "NY_STDLIB_PATH"): environment.pop(key, None) - for name in ("compiler", "interpreter", "assembler", "linker", "runtime"): + for name in ("compiler", "interpreter", "assembler", "linker", "runtime", "nilstd"): setattr(args, name, getattr(args, name).resolve()) with tempfile.TemporaryDirectory(prefix="ny-global-contract-") as temporary: @@ -84,8 +87,8 @@ def write(name, body, binary): + '\nend function\n', encoding="utf-8", newline='\n') return path - # Non-scalar globals keep their established interpreted representation; - # the new optional scalar/text contract must not reject existing Ny. + # Nominal globals retain their exact declared identities, while legacy + # scalar-array globals continue to use the existing interpreted profile. aggregate_source = root / "aggregate-globals.ny" aggregate_source.write_text( "struct Record\nvalue: i32\nend struct\n" @@ -102,6 +105,158 @@ def write(name, body, binary): "--output", output, aggregate_source])) require(run([args.interpreter, "--no-ai", output]), output="3\n17\n") + # Real imported Matrix classes flow through private Ny module globals, + # concrete Option methods and record fields before dispatching methods. + # No cast, fake owner, erased global or compiler-only acceptance can + # satisfy these execution controls. + package = root / "probe" + package.mkdir() + (package / "foreign_types.matrix").write_text(textwrap.dedent("""\ + book probe.foreign_types + read everything from nil.std.core + read everything from nil.std.nildata + public record_owner begin class + field identity as number + public read_identity returns number begin paragraph + give my identity + end paragraph + public echo_result receives candidate as Result of `Value`, text returns Result of `Value`, text begin paragraph + give candidate + end paragraph + end class + public make_value returns Result of `Value`, text begin paragraph + value content is "nominal" + give string_value with content + end paragraph + public pass_value receives candidate as Result of `Value`, text returns Result of `Value`, text begin paragraph + give candidate + end paragraph + public record_client begin class + field identity as number + public read_identity returns number begin paragraph + give my identity + end paragraph + end class + """), encoding="utf-8", newline='\n') + (package / "adapter.ny").write_text(textwrap.dedent("""\ + module probe.adapter + import nil.std.core + import nil.std.nildata + import probe.foreign_types + struct OwnerSlot + owner: record_owner + end struct + let mut stored_owner: Option = Option.none() + let mut stored_client: Option = Option.none() + let mut direct_owner: record_owner = record_owner { identity: 7 } + let mut wrapped_owner: OwnerSlot = OwnerSlot { owner: record_owner { identity: 8 } } + fn bind(owner: record_owner, client: record_client) + stored_owner = Option.some(owner) + stored_client = Option.some(client) + direct_owner = owner + wrapped_owner = OwnerSlot { owner: owner } + end fn + fn reset() + stored_owner = Option.none() + stored_client = Option.none() + end fn + pub fn exercise() + println(direct_owner.read_identity()) + println(wrapped_owner.owner.read_identity()) + println(stored_owner.is_none()) + println(stored_client.is_none()) + let owner = record_owner { identity: 41 } + let client = record_client { identity: 42 } + let materialized = pass_value(owner.echo_result(make_value())) + println(materialized.is_error()) + println(nil::std::nildata::to_json(materialized.unwrap()).unwrap()) + bind(owner, client) + println(stored_owner.unwrap().read_identity()) + println(stored_client.unwrap().read_identity()) + println(direct_owner.read_identity()) + println(wrapped_owner.owner.read_identity()) + reset() + println(stored_owner.is_none()) + println(stored_client.is_none()) + end fn + """), encoding="utf-8", newline='\n') + nominal_expected = '7\n8\n1\n1\n0\n"nominal"\n41\n42\n41\n41\n1\n1\n' + nominal_types = { + "probe::adapter::stored_owner": "nil::std::core::Option", + "probe::adapter::stored_client": "nil::std::core::Option", + "probe::adapter::direct_owner": "probe::foreign_types::record_owner", + "probe::adapter::wrapped_owner": "probe::adapter::OwnerSlot", + } + nominal_inputs = { + "ny": "module choice_client\nimport probe.adapter\n" + "fn main() -> i32\nexercise()\nreturn 0\nend fn\n", + "matrix": "book choice_client\nread everything from probe.adapter\n" + "main returns number begin paragraph\n" + "evaluate exercise with nothing\ngive 0\nend paragraph\n", + } + nominal_options = ["--no-stdlib", "--sdk-path", args.nilstd, "-I", root] + for language, contents in nominal_inputs.items(): + source = root / ("nominal-globals." + language) + source.write_text(contents, encoding="utf-8", newline='\n') + analysis = run([args.compiler, *nominal_options, "--analyze", source]) + assert analysis.returncode == 0 and not analysis.stderr, analysis + for binary in (False, True): + output = root / ("nominal-" + language + ("-binary.nil" if binary else "-text.nil")) + require(run([args.compiler, "--quiet", *nominal_options, "--no-bundle", + *(["--emit-binary-nil"] if binary else []), "--output", output, source])) + if not binary: + serialized = output.read_text(encoding="utf-8") + resolved_result = "nil::std::core::Result" + for name in ("probe__foreign_types__make_value", "probe__foreign_types__pass_value", + "probe::foreign_types::record_owner::echo_result"): + signature = next(line for line in serialized.splitlines() + if line.startswith(("function " + name + "(", + "function " + name + " ->"))) + assert signature.endswith(" -> " + resolved_result + ":"), signature + if "make_value" not in name: + assert "candidate: " + resolved_result in signature, signature + method = next(line for line in serialized.splitlines() + if line.strip().startswith("method echo_result ")) + assert shlex.split(method)[4] == resolved_result, method + assert shlex.split(method)[8] == resolved_result, method + accesses = [] + for line in serialized.splitlines(): + if not line.strip().startswith(("LOAD_GLOBAL ", "STORE_GLOBAL ")): + continue + lexer = shlex.shlex(line, posix=True) + lexer.whitespace_split = True + lexer.commenters = ";" + accesses.append(list(lexer)) + observed = set() + for access in accesses: + if access[1] in nominal_types: + assert access == [access[0], access[1], nominal_types[access[1]]], access + observed.add(access[1]) + assert observed == set(nominal_types), observed + # A new interpreter instance must begin with its own globals. + for _ in range(2): + require(run([args.interpreter, "--no-ai", output]), output=nominal_expected) + if args.llvm == "ON": + protected = linked_executable_path(root / ("nominal-native-" + language)) + protected.write_bytes(b"prior native artifact\n") + require(run([args.compiler, "--quiet", *nominal_options, "--native", + "--output", protected, source]), + diagnostic="nominal aggregate globals are not supported by native compilation") + assert protected.read_bytes() == b"prior native artifact\n" + + forward_nominal = root / "forward-nominal.ny" + forward_nominal.write_text( + "module forward_nominal\nimport probe.foreign_types\n" + "let first: record_owner = later\n" + "let later: record_owner = record_owner { identity: 9 }\n" + "fn main() -> i32\nprintln(first.read_identity())\nreturn 0\nend fn\n", + encoding="utf-8", newline='\n') + for binary in (False, True): + output = root / ("forward-nominal-binary.nil" if binary else "forward-nominal-text.nil") + require(run([args.compiler, "--quiet", *nominal_options, "--no-bundle", + *(["--emit-binary-nil"] if binary else []), "--output", output, forward_nominal])) + require(run([args.interpreter, "--no-ai", output]), diagnostic="Global not found") + source_modes = [["--no-bundle"], ["--no-bundle", "--emit-binary-nil"]] if args.llvm == "ON": source_modes.append(["--native"]) @@ -269,6 +424,8 @@ def source_control(path, expected, providers=(), extra=()): require(run([executable]), output=output, diagnostic="read before initialization" if uninitialized else "") print("global contracts passed: 9 negative and 3 control cases in text/binary NIL") + print("nominal global contracts passed: 8 VM executions, 2 initialization rejections, " + + ("2" if args.llvm == "ON" else "0") + " native rejections") if __name__ == "__main__": From 2db8c9b7a13f45bd2b6a9effb1c973ed7d887ef7 Mon Sep 17 00:00:00 2001 From: Nathan Young Date: Sat, 21 Nov 2026 01:08:15 -0500 Subject: [PATCH 13/15] Align enum field metadata with resolved function signatures --- nilcompiler/src/codegen.cpp | 10 ++++++++++ notebook/2026-11-21-goetic-enigma-sdk.md | 19 +++++++++++++++---- 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/nilcompiler/src/codegen.cpp b/nilcompiler/src/codegen.cpp index a8ed66bf..8bbe418a 100644 --- a/nilcompiler/src/codegen.cpp +++ b/nilcompiler/src/codegen.cpp @@ -7604,6 +7604,16 @@ codegen::assemble_module(const ast_program &program, } } + // GET_FIELD derives its proven type from the record layout, including the + // layout accompanying a class. Keep that identity equal to the function + // signatures above: a checked Option field and its qualified method + // parameter cannot describe different enum owners. Run after globals too, + // because their declarations can materialize additional concrete records. + // Field access instructions name the field rather than repeat its type. + for (auto &schema : mod->structs) + for (auto &field : schema.fields) + field.second = canonical_enum_signature(field.second); + // Add string constants from local mapping for (const auto &kv : string_const_map_) { mod->string_constants.emplace_back(kv.second, kv.first); diff --git a/notebook/2026-11-21-goetic-enigma-sdk.md b/notebook/2026-11-21-goetic-enigma-sdk.md index a7333bbb..28a7e777 100644 --- a/notebook/2026-11-21-goetic-enigma-sdk.md +++ b/notebook/2026-11-21-goetic-enigma-sdk.md @@ -129,14 +129,25 @@ optional storage, put/get, close/reset, reopen with a new incarnation and persisted-data checks. The engine's manifest oracle verified bytes, checksums and modes. These runs used a diagnostic tool stage, not a qualified SDK. -The exact copied Goetic harness now passes loader admission and begins normal -execution, but encounters an `unwrap()` on an error result. That application -acceptance failure remains under investigation; no final SDK handoff follows -from the successful engine-only probe. The expanded small signature fixture +The exact copied Goetic harness passed loader admission, then exposed an +application guard that rejected Enigma's valid initial generation zero. Goetic +corrected its guard to accept the engine's documented bounded generation range. +A fresh copy then passed the unchanged harness's lifecycle, reopen and +foreign-scope checks, alongside the real-engine optional-value test. These +diagnostic-stage results still require a complete installed SDK replay. +The expanded small signature fixture also passes the old tools, so it is a positive regression case, not proof of the original compiler defect. The retained real-consumer before/after executions establish that boundary. +The first clean SDK attempt for `9ca4272` stopped before packaging: 607 source +tests passed and two existing Ny/Matrix `choice-text-fields` route tests failed. +Qualifying function signatures also requires qualifying their matching record +and class field metadata. The same mismatch reproduced in hosted Linux and +Apple Silicon interpreter campaigns. Those failures remain retained; no +failed candidate was published. The correction keeps field and function enum +identities consistent without changing loader provenance checks. + Regression coverage includes imported Matrix classes used from Ny and Matrix, textual/binary NIL, fresh interpreter instances, direct and record-wrapped globals, explicit optional values, initialization failure and native rejection From 167ae3a6b0abb69c26e943a008ee6eb1eac8f13d Mon Sep 17 00:00:00 2001 From: Nathan Young Date: Sat, 21 Nov 2026 01:38:22 -0500 Subject: [PATCH 14/15] Index provenance metadata within each NIL admission pass --- nilcompiler/src/nil_loader.cpp | 244 +++++++++++++++-------- notebook/2026-11-21-goetic-enigma-sdk.md | 53 ++++- tests/class_vm_tests.cpp | 47 ++++- 3 files changed, 257 insertions(+), 87 deletions(-) diff --git a/nilcompiler/src/nil_loader.cpp b/nilcompiler/src/nil_loader.cpp index 8d4f1962..aeb431ff 100644 --- a/nilcompiler/src/nil_loader.cpp +++ b/nilcompiler/src/nil_loader.cpp @@ -27,6 +27,7 @@ #include #include #include +#include #include #include @@ -573,8 +574,50 @@ std::optional> enum_payload_types(const std::string &ra return std::vector{type}; } -const nil_enum_def *exact_enum_schema(const nil_module &module, const std::string &raw) { +// One immutable admission pass owns these indexes and completed-query caches. +// Do not retain them across loads: embedding callers may edit a program or its +// declarations between validations. Duplicate declarations remain separate. +struct provenance_type_index { + const nil_module *module; + std::unordered_map> records; + std::unordered_map> enumerations; + std::unordered_map> functions; + std::unordered_set classes; + std::unordered_map sensitive; + std::unordered_set dynamic_types; + std::unordered_set checked_enums; + static constexpr std::size_t memo_limit = 4096; + static constexpr std::size_t memo_key_limit = 4096; + + explicit provenance_type_index(const nil_module &value, bool index_functions = false) + : module(&value) { + for (const auto &schema : value.structs) + records[canonical_dynamic_type(schema.name)].push_back(&schema); + for (const auto &schema : value.enums) + enumerations[canonical_dynamic_type(schema.name)].push_back(&schema); + if (index_functions) + for (const auto &function : value.functions) + functions[function.name].push_back(&function); + for (const auto &klass : value.classes) classes.insert(klass.name); + } + + void validate_dynamic(const std::string &type) { + if (dynamic_types.count(type)) return; + validate_nil_dynamic_type(*module, type); + if (dynamic_types.size() < memo_limit && type.size() <= memo_key_limit) + dynamic_types.insert(type); + } +}; + +const nil_enum_def *exact_enum_schema(const nil_module &module, const std::string &raw, + const provenance_type_index *types = nullptr) { const auto type = canonical_dynamic_type(raw); + if (types) { + if (types->records.count(type)) return nullptr; + const auto found = types->enumerations.find(type); + return found != types->enumerations.end() && found->second.size() == 1 + ? found->second.front() : nullptr; + } const nil_enum_def *result = nullptr; for (const auto &schema : module.structs) if (canonical_dynamic_type(schema.name) == type) return nullptr; @@ -602,52 +645,72 @@ bool variant_owner_matches(const std::string &tag, const nil_enum_def &schema) { "::" + owner) == 0); } -bool class_sensitive_type(const std::string &raw, const nil_module &module) { - std::unordered_set visited; - std::vector pending{compact_binding_type(raw)}; - while (!pending.empty()) { - auto type = pending.back(); pending.pop_back(); - if (type.rfind("ref<", 0) == 0 && type.back() == '>') type = type.substr(4, type.size() - 5); - if (!visited.insert(type).second) continue; - if (visited.size() > 4096) - throw std::runtime_error("NIL provenance type graph exceeds its bound"); - if (type == "anything") return true; - // Compiler-owned binding cells carry stack storage in native code. Use - // the existing exact-provenance CFG analysis for these handles too, so - // casts, unknown calls, globals, arrays and raw pointers cannot erase the - // bounded lifetime proven by their reference-parameter contract. - if (contains_binding_cell_type(type)) return true; - if (find_nil_class(module, type)) return true; - if (const auto signature = fault_callable_signature(type)) { - pending.push_back(signature->second); - pending.insert(pending.end(), signature->first.begin(), signature->first.end()); +bool class_sensitive_type(const std::string &raw, const nil_module &module, + provenance_type_index *types = nullptr) { + if (!types) { + provenance_type_index local(module); + return class_sensitive_type(raw, module, &local); + } + const auto cached = types->sensitive.find(raw); + if (cached != types->sensitive.end()) return cached->second; + const auto compute = [&]() { + std::unordered_set visited; + std::vector pending{compact_binding_type(raw)}; + while (!pending.empty()) { + auto type = pending.back(); pending.pop_back(); + if (type.rfind("ref<", 0) == 0 && type.back() == '>') type = type.substr(4, type.size() - 5); + if (!visited.insert(type).second) continue; + if (visited.size() > 4096) + throw std::runtime_error("NIL provenance type graph exceeds its bound"); + if (type == "anything") return true; + // Compiler-owned binding cells carry stack storage in native code. Use + // the existing exact-provenance CFG analysis for these handles too, so + // casts, unknown calls, globals, arrays and raw pointers cannot erase the + // bounded lifetime proven by their reference-parameter contract. + if (contains_binding_cell_type(type)) return true; + if (types->classes.count(type)) return true; + if (const auto signature = fault_callable_signature(type)) { + pending.push_back(signature->second); + pending.insert(pending.end(), signature->first.begin(), signature->first.end()); + } + const auto canonical = canonical_dynamic_type(type); + const auto records = types->records.find(canonical); + if (records != types->records.end()) + for (const auto *schema : records->second) + for (const auto &field : schema->fields) pending.push_back(compact_binding_type(field.second)); + const auto enumerations = types->enumerations.find(canonical); + if (enumerations != types->enumerations.end()) + for (const auto *schema : enumerations->second) + for (const auto &variant : schema->variants) { + const auto payloads = enum_payload_types(variant.associated_type); + if (!payloads) throw std::runtime_error("NIL enum has malformed payload metadata"); + pending.insert(pending.end(), payloads->begin(), payloads->end()); + } } - for (const auto &schema : module.structs) - if (canonical_dynamic_type(schema.name) == canonical_dynamic_type(type)) - for (const auto &field : schema.fields) pending.push_back(compact_binding_type(field.second)); - for (const auto &schema : module.enums) - if (canonical_dynamic_type(schema.name) == canonical_dynamic_type(type)) - for (const auto &variant : schema.variants) { - const auto payloads = enum_payload_types(variant.associated_type); - if (!payloads) throw std::runtime_error("NIL enum has malformed payload metadata"); - pending.insert(pending.end(), payloads->begin(), payloads->end()); - } - } - return false; + return false; + }; + const bool result = compute(); + // Cache only this complete root query. Reusing a false subtree would change + // cycle handling and could skip the per-query 4096-node validation bound. + if (types->sensitive.size() < provenance_type_index::memo_limit && + raw.size() <= provenance_type_index::memo_key_limit) + types->sensitive.emplace(raw, result); + return result; } constexpr const char *unproven_class_value = "#class-unproven"; -bool class_provenance_type(const std::string &type, const nil_module &module) { +bool class_provenance_type(const std::string &type, const nil_module &module, + provenance_type_index *types = nullptr) { if (type == unproven_class_value || type == "#anything") return true; // An opaque cast of a callable must not disguise a class-returning target // as a scalar callback, including through nested callable signatures. if (type.rfind("#callable:", 0) == 0) - return class_sensitive_type(type.substr(10), module); + return class_sensitive_type(type.substr(10), module, types); if (type.rfind("#enum:", 0) == 0) - return class_sensitive_type(type.substr(6), module); + return class_sensitive_type(type.substr(6), module, types); if (!type.empty() && (type.front() == '@' || type.front() == '!')) { const auto marker = type.find('@'); - if (marker != std::string::npos) return class_sensitive_type(type.substr(marker + 1), module); + if (marker != std::string::npos) return class_sensitive_type(type.substr(marker + 1), module, types); } return false; } @@ -705,7 +768,8 @@ static std::string fault_callable_type(const nil_function &function) { return fault_callable_signature(signature) ? "#callable:" + signature : "#text"; } -std::string fault_stack_type(const std::string &type, const nil_module &module) { +std::string fault_stack_type(const std::string &type, const nil_module &module, + const provenance_type_index *types = nullptr) { if (contains_binding_cell_type(type)) { const auto canonical = compact_binding_type(type); for (const auto &schema : module.structs) @@ -728,6 +792,13 @@ std::string fault_stack_type(const std::string &type, const nil_module &module) // VM embedders may supply instruction objects without serialized schemas. if (!type.empty() && type.front() != '&' && type.front() != '*' && type.find('[') == std::string::npos && type != "any" && type != "void") { + if (types) { + const auto canonical = canonical_dynamic_type(type); + if (types->enumerations.count(canonical)) + return exact_enum_schema(module, type, types) + ? "#enum:" + canonical : unproven_class_value; + return "?"; + } for (const auto &schema : module.enums) if (canonical_dynamic_type(schema.name) == canonical_dynamic_type(type)) return exact_enum_schema(module, type) @@ -741,7 +812,8 @@ nil_fault_analysis analyze_fault_body(const nil_function &function, const nil_module &module, bool require_schemas, bool force_class_validation = false, - const std::unordered_set *source_returns = nullptr) { + const std::unordered_set *source_returns = nullptr, + provenance_type_index *shared_types = nullptr) { nil_fault_analysis result; result.instructions.resize(function.body.size()); std::vector ops; @@ -755,8 +827,13 @@ nil_fault_analysis analyze_fault_body(const nil_function &function, has_dynamic_operations = has_dynamic_operations || opcode == Opcode::BOX_ANY || opcode == Opcode::UNBOX_ANY || opcode == Opcode::IS_ANY_TYPE; } if (!has_faults && !force_class_validation) return result; + std::optional local_types; + if (!shared_types) local_types.emplace(module, true); + auto *provenance_types = shared_types ? shared_types : &*local_types; + if (provenance_types->module != &module) + throw std::logic_error("NIL provenance index belongs to another module"); const auto stack_type = [&](const std::string &type, const nil_module &context) { - const auto category = fault_stack_type(type, context); + const auto category = fault_stack_type(type, context, provenance_types); if (!has_dynamic_operations) return category; if (category == "#word") return std::string("#scalar:") + canonical_dynamic_type(type); if (category == "#enum") return std::string("#enum:") + canonical_dynamic_type(type); @@ -834,7 +911,7 @@ nil_fault_analysis analyze_fault_body(const nil_function &function, if (old.stack[i] == state.stack[i]) continue; if ((old.stack[i] == "?" || state.stack[i] == "?" || old.stack[i] == unproven_class_value || state.stack[i] == unproven_class_value) && - (class_provenance_type(old.stack[i], module) || class_provenance_type(state.stack[i], module))) { + (class_provenance_type(old.stack[i], module, provenance_types) || class_provenance_type(state.stack[i], module, provenance_types))) { if (old.stack[i] != unproven_class_value) { old.stack[i] = unproven_class_value; changed = true; } continue; } @@ -849,14 +926,14 @@ nil_fault_analysis analyze_fault_body(const nil_function &function, for (auto &local : old.locals) { const auto found = state.locals.find(local.first); if (found == state.locals.end() || found->second != local.second) { - const bool tainted = class_provenance_type(local.second, module) || - (found != state.locals.end() && class_provenance_type(found->second, module)); + const bool tainted = class_provenance_type(local.second, module, provenance_types) || + (found != state.locals.end() && class_provenance_type(found->second, module, provenance_types)); const std::string merged = tainted ? unproven_class_value : "?"; if (local.second != merged) { local.second = merged; changed = true; } } } for (const auto &local : state.locals) - if (!old.locals.count(local.first) && class_provenance_type(local.second, module)) { + if (!old.locals.count(local.first) && class_provenance_type(local.second, module, provenance_types)) { old.locals[local.first] = unproven_class_value; changed = true; } for (auto &initialization : old.initialized_fields) { @@ -891,7 +968,7 @@ nil_fault_analysis analyze_fault_body(const nil_function &function, state.stack.resize(state.stack.size() - count); }; const auto class_type = [&](const std::string &type) { - return class_provenance_type(type, module); + return class_provenance_type(type, module, provenance_types); }; const auto reject_class_operands = [&](std::size_t count) { if (state.stack.size() < count) fail("operand underflow", pc); @@ -911,7 +988,7 @@ nil_fault_analysis analyze_fault_body(const nil_function &function, if ((class_type(checked) || class_type(actual)) && checked != actual) fail("class argument or storage requires its exact checked static view", pc); if (checked.rfind("#enum:", 0) == 0 && checked != actual && - !(actual == "#enum" && !class_sensitive_type(expected, module))) + !(actual == "#enum" && !class_sensitive_type(expected, module, provenance_types))) fail("enum argument or storage requires its exact proven nominal type", pc); if (checked.rfind("#callable:", 0) == 0 && checked != actual) fail("callable argument or storage requires its exact checked signature", pc); @@ -923,13 +1000,17 @@ nil_fault_analysis analyze_fault_body(const nil_function &function, return type; }; const auto checked_enum = [&](const std::string &raw) -> const nil_enum_def & { - const auto *schema = exact_enum_schema(module, raw); + const auto *schema = exact_enum_schema(module, raw, provenance_types); if (!schema) fail("enum operation requires one exact concrete enum schema", pc); - validate_nil_dynamic_type(module, canonical_dynamic_type(raw)); - std::set variants; - for (const auto &variant : schema->variants) - if (variant.name.empty() || !variants.insert(variant.name).second) - fail("enum operation requires unique declared variants", pc); + if (!provenance_types->checked_enums.count(schema)) { + provenance_types->validate_dynamic(canonical_dynamic_type(raw)); + std::set variants; + for (const auto &variant : schema->variants) + if (variant.name.empty() || !variants.insert(variant.name).second) + fail("enum operation requires unique declared variants", pc); + if (provenance_types->checked_enums.size() < provenance_type_index::memo_limit) + provenance_types->checked_enums.insert(schema); + } return *schema; }; const auto checked_variant_payload = [&](const nil_enum_def &schema, @@ -1009,9 +1090,9 @@ nil_fault_analysis analyze_fault_body(const nil_function &function, case Opcode::PUSH_CONST_STR: state.stack.push_back("#text"); break; case Opcode::PUSH_FN_PTR: { - const auto target = std::find_if(module.functions.begin(), module.functions.end(), - [&](const auto &candidate) { return candidate.name == args[0]; }); - state.stack.push_back(target == module.functions.end() ? "#text" : fault_callable_type(*target)); + const auto targets = provenance_types->functions.find(args[0]); + state.stack.push_back(targets == provenance_types->functions.end() + ? "#text" : fault_callable_type(*targets->second.front())); break; } case Opcode::LOAD_LOCAL: { @@ -1030,7 +1111,7 @@ nil_fault_analysis analyze_fault_body(const nil_function &function, std::any_of(module.structs.begin(), module.structs.end(), [&](const auto &schema) { return schema.name == local->second.substr(1); })) state.stack.push_back("@ref<" + local->second.substr(1) + ">"); - else if (local != state.locals.end() && class_provenance_type(local->second, module)) + else if (local != state.locals.end() && class_provenance_type(local->second, module, provenance_types)) state.stack.push_back(unproven_class_value); else state.stack.push_back("?"); break; @@ -1056,7 +1137,7 @@ nil_fault_analysis analyze_fault_body(const nil_function &function, fail("cannot construct an abstract class", pc); const auto schema = std::find_if(module.structs.begin(), module.structs.end(), [&](const auto &value) { return value.name == args[0]; }); - if ((has_dynamic_operations || class_sensitive_type(args[0], module)) && schema != module.structs.end() && !schema->fields.empty()) { + if ((has_dynamic_operations || class_sensitive_type(args[0], module, provenance_types)) && schema != module.structs.end() && !schema->fields.empty()) { const auto construction = "!" + std::to_string(pc) + "@" + args[0]; state.initialized_fields[construction].clear(); state.stack.push_back(construction); @@ -1162,7 +1243,7 @@ nil_fault_analysis analyze_fault_body(const nil_function &function, reject_class_operands(count); const auto separator = args[0].rfind("::"); if (separator != std::string::npos && - class_sensitive_type(args[0].substr(0, separator), module)) + class_sensitive_type(args[0].substr(0, separator), module, provenance_types)) fail("class-bearing enum construction requires exact payload metadata", pc); pop(count); state.stack.push_back("#enum"); break; @@ -1230,9 +1311,9 @@ nil_fault_analysis analyze_fault_body(const nil_function &function, // cannot authorize passing caller storage or class provenance. reject_class_operands(count); for (const auto &type : signature->first) - if (class_sensitive_type(type, module)) + if (class_sensitive_type(type, module, provenance_types)) fail("indirect calls cannot receive binding-reference or class storage", pc); - if (class_sensitive_type(signature->second, module)) + if (class_sensitive_type(signature->second, module, provenance_types)) fail("indirect calls cannot return binding-reference or class storage", pc); pop(count); if (signature->second != "void") @@ -1241,8 +1322,9 @@ nil_fault_analysis analyze_fault_body(const nil_function &function, } if (local_callable != state.locals.end()) fail("indirect call lacks a checked callable signature", pc); - const auto callee = std::find_if(module.functions.begin(), module.functions.end(), [&](const auto &fn) { return fn.name == args[0]; }); - if (callee != module.functions.end()) { + const auto callees = provenance_types->functions.find(args[0]); + const auto *callee = callees == provenance_types->functions.end() ? nullptr : callees->second.front(); + if (callee) { if (callee->return_type.empty() || callee->params.size() != count) fail("call requires an exact signature and matching arity", pc); const bool external = callee->body.empty() || std::any_of(callee->annotations.begin(), callee->annotations.end(), @@ -1253,7 +1335,7 @@ nil_fault_analysis analyze_fault_body(const nil_function &function, }); if (external) { reject_class_operands(count); - if (class_sensitive_type(callee->return_type, module)) + if (class_sensitive_type(callee->return_type, module, provenance_types)) fail("external calls cannot establish class-bearing result provenance", pc); } for (std::size_t i = 0; i < count; ++i) { @@ -1265,7 +1347,7 @@ nil_fault_analysis analyze_fault_body(const nil_function &function, } } else reject_class_operands(count); pop(count); - if (callee != module.functions.end()) { + if (callee) { if (callee->return_type != "void") { const auto result_type = stack_type(callee->return_type, module); if (result_type.rfind("#callable:", 0) == 0 && @@ -1343,7 +1425,7 @@ nil_fault_analysis analyze_fault_body(const nil_function &function, reject_class_operands(static_cast(std::stoull(args[2]))); pop(static_cast(std::stoull(args[2]))); if (args.size() < 4) fail("interop in a fault-bearing function requires explicit result metadata", pc); - if (class_sensitive_type(args[3], module)) fail("interop cannot synthesize class provenance", pc); + if (class_sensitive_type(args[3], module, provenance_types)) fail("interop cannot synthesize class provenance", pc); if (args[3] != "void") state.stack.push_back(opaque_stack_type(args[3])); break; } @@ -1559,23 +1641,24 @@ void finalize_nil_switch_returns(nil_module &module) { } void validate_nil_fault_contract(const nil_module &module) { + provenance_type_index types(module, true); for (const auto &function : module.functions) - (void)analyze_fault_body(function, module, true); + (void)analyze_fault_body(function, module, true, false, nullptr, &types); } void validate_nil_class_provenance(const nil_module &module) { + provenance_type_index types(module, true); std::unordered_set related; for (const auto &function : module.functions) for (const auto &instruction : function.body) if ((instruction.opname == "LOAD_GLOBAL" || instruction.opname == "STORE_GLOBAL") && instruction.args.size() == 2 && has_nominal_global_storage_syntax(instruction.args[1])) { const auto &type = instruction.args[1]; - validate_nil_dynamic_type(module, type); - const auto records = std::count_if(module.structs.begin(), module.structs.end(), - [&](const auto &schema) { return canonical_dynamic_type(schema.name) == type; }); - const auto enumerations = std::count_if(module.enums.begin(), module.enums.end(), - [&](const auto &schema) { return canonical_dynamic_type(schema.name) == type; }); - if (records + enumerations != 1) + types.validate_dynamic(type); + const auto records = types.records.find(type); + const auto enumerations = types.enumerations.find(type); + if ((records == types.records.end() ? 0 : records->second.size()) + + (enumerations == types.enumerations.end() ? 0 : enumerations->second.size()) != 1) throw std::runtime_error("NIL aggregate global requires one exact nominal schema"); related.insert(type); } @@ -1684,7 +1767,7 @@ void validate_nil_class_provenance(const nil_module &module) { if (!related.count(enumeration.name) && std::any_of(enumeration.variants.begin(), enumeration.variants.end(), [&](const auto &variant) { return related.count(compact_binding_type(variant.associated_type)) != 0 || - class_sensitive_type(variant.associated_type, module) || + class_sensitive_type(variant.associated_type, module, &types) || (dynamic_operations && variant.associated_type.find("anything") != std::string::npos); })) changed = related.insert(enumeration.name).second || changed; @@ -1692,13 +1775,13 @@ void validate_nil_class_provenance(const nil_module &module) { if (!related.count(schema.name) && std::any_of(schema.fields.begin(), schema.fields.end(), [&](const auto &field) { return related.count(compact_binding_type(field.second)) != 0 || - class_sensitive_type(field.second, module) || fault_callable_signature(field.second).has_value(); + class_sensitive_type(field.second, module, &types) || fault_callable_signature(field.second).has_value(); })) changed = related.insert(schema.name).second || changed; } const auto related_type = [&](const std::string &raw) { const auto type = compact_binding_type(raw); - return related.count(type) != 0 || class_sensitive_type(type, module) || + return related.count(type) != 0 || class_sensitive_type(type, module, &types) || (dynamic_operations && type.find("anything") != std::string::npos) || contains_binding_cell_type(type) || fault_callable_signature(type).has_value(); }; @@ -1714,17 +1797,20 @@ void validate_nil_class_provenance(const nil_module &module) { instruction.opname == "BOX_ANY" || instruction.opname == "UNBOX_ANY" || instruction.opname == "IS_ANY_TYPE") relevant = true; for (const auto &argument : instruction.args) if (related_type(argument)) relevant = true; - if ((instruction.opname == "CALL" || instruction.opname == "PUSH_FN_PTR") && !instruction.args.empty()) - for (const auto &target : module.functions) if (target.name == instruction.args[0]) { - if (related_type(target.return_type)) relevant = true; - for (const auto ¶meter : target.params) { + if ((instruction.opname == "CALL" || instruction.opname == "PUSH_FN_PTR") && !instruction.args.empty()) { + const auto targets = types.functions.find(instruction.args[0]); + if (targets == types.functions.end()) continue; + for (const auto *target : targets->second) { + if (related_type(target->return_type)) relevant = true; + for (const auto ¶meter : target->params) { const auto colon = parameter.find(':'); const auto start = colon == std::string::npos ? std::string::npos : parameter.find_first_not_of(" \t", colon + 1); if (start != std::string::npos && related_type(parameter.substr(start))) relevant = true; } } + } } - if (relevant) (void)analyze_fault_body(function, module, true, true); + if (relevant) (void)analyze_fault_body(function, module, true, true, nullptr, &types); } } diff --git a/notebook/2026-11-21-goetic-enigma-sdk.md b/notebook/2026-11-21-goetic-enigma-sdk.md index 28a7e777..0b526b9b 100644 --- a/notebook/2026-11-21-goetic-enigma-sdk.md +++ b/notebook/2026-11-21-goetic-enigma-sdk.md @@ -2,12 +2,17 @@ ## Status and question -The combined SDK at `6a0563438aff61b3cb751012ae00c323f836cf13` passes all -609 Linux source tests without skips and 1,248 installed fixed-output routes. -Its handoff is held: the actual Goetic/Enigma consumer exposed missing class -provenance through module globals and enum payloads. Corrections and fresh -consumer qualification are in progress. This remains development SDK work, -not a stable release or a live application migration. +Clean source `2db8c9b7a13f45bd2b6a9effb1c973ed7d887ef7` produced development +SDK `ae06ead0f5d3312deaa29c2832c9bfd6665b91be107396323954cc88022ce317`. +All 609 Linux source tests, 1,248 installed fixed-output routes, installed +durable/console/global checks and the real snapshot/optional-value consumers +pass. Canonical relocation also passes markup, rooted-file and real consumer +checks. Shared defaults and accepted consumer pins remain unchanged. + +Goetic's broader application suite subsequently exposed severe startup cost. +Adoption is held while admission performance is corrected; successful value +and persistence tests alone do not qualify application responsiveness. This +remains development SDK work, not a stable release or a live migration. Goetic needs its qualified compiler fixes together with Enigma's durable I/O surface, including `nil.std.io.file_lock_is_held`. The existing Goetic SDK came @@ -157,7 +162,41 @@ real-engine optional-value consumer must also pass in private source copies before a new immutable SDK is handed over. No live application or data change is part of this check. -### Remaining boundaries +### Admission performance + +Goetic reports all 26 Matrix fixtures passing, followed by an HTTP startup +deadline failure. In a fresh synthetic legacy store, the full application +became ready after 69.658 seconds; subsequent health requests took about four +milliseconds. Its separate in-process fixture measured 7.068 seconds before +main, but ten 32 KiB raw reads took only 0.000410 seconds. Redundant adapter +copies add roughly 50 milliseconds per 32 KiB read and are a separate consumer +optimization, not an explanation for the startup delay. + +The new provenance analysis repeatedly classifies instruction operands, +including labels and constants, by scanning and canonicalizing all record and +enum schemas. It also repeats type-closure checks and function lookups. The +correction indexes immutable metadata within each validation invocation and +memoizes only completed queries. Duplicate and exact-owner checks, bounded graph +walks and per-instruction validation remain required. Parsing and VM loading +must both continue to revalidate because embedding callers can change the +instruction vector. Admission-only probes must never execute the application +or access its data; before/after measurements use the same sealed bytecode. + +That admission-only comparison measured the same 6,946,497-byte application at +22.1942 seconds parsing plus 23.3772 seconds loading before the change, versus +0.2493 plus 0.1928 seconds afterward. Total measured time fell from 45.5799 to +0.4508 seconds, about 101 times faster. The maintenance program fell from +17.7566 to 0.3018 seconds. Instruction, function and schema counts matched +exactly; no application instructions executed, and the old binaries were +retained. These are admission measurements, not an HTTP-readiness claim. + +Twenty-eight focused contracts pass, including metadata mutation between +admissions, same-named types in separate modules, and the exact 4096-node graph +boundary, overflow rejection and recovery. The fresh installed SDK must still +pass the full source/installed campaign and Goetic's original HTTP startup +deadline before adoption. Increasing that deadline is not the performance fix. + +### Platform and language boundaries Durable filesystem primitives are currently POSIX-only. Windows rejection checks prove explicit unsupported behavior, not parity. macOS needs its own diff --git a/tests/class_vm_tests.cpp b/tests/class_vm_tests.cpp index 50422752..08659d82 100644 --- a/tests/class_vm_tests.cpp +++ b/tests/class_vm_tests.cpp @@ -312,6 +312,50 @@ void nominal_global_alias_contract() { } } +void provenance_admission_lifetime_contract() { + auto module = class_enum_fixture(); + ny::validate_nil_class_contract(module); + // A successful admission cannot authorize a later edit at the same module + // address. The exact enum payload no longer agrees with its instructions. + module.enums.front().variants.front().associated_type = "i64"; + bool caught = false; + try { ny::validate_nil_class_contract(module); } + catch (const std::runtime_error &) { caught = true; } + check(caught, "changed enum metadata is revalidated after successful admission"); + module.enums.front().variants.front().associated_type = "Base"; + ny::validate_nil_class_contract(module); + + auto scalar = module; + scalar.enums.front().variants.front().associated_type = "i64"; + check(!ny::nil_type_requires_provenance(scalar, "Container") && + ny::nil_type_requires_provenance(module, "Container"), + "same named enum in distinct modules retains independent provenance"); + scalar.enums.front().variants.front().associated_type = "Base"; + check(ny::nil_type_requires_provenance(scalar, "Container"), + "false provenance result cannot survive a declaration edit"); + + ny::nil_module graph; + // 4095 nominal nodes plus the scalar leaf exactly reach the existing + // 4096-node bound. A cached valid query must not authorize a larger graph. + for (unsigned index = 0; index < 4095; ++index) + graph.structs.push_back({"Node" + std::to_string(index), + {{"next", index == 4094 ? "i64" : "Node" + std::to_string(index + 1)}}}); + check(!ny::nil_type_requires_provenance(graph, "Node0"), + "provenance traversal accepts its exact existing node bound"); + graph.structs.back().fields.front().second = "Overflow"; + graph.structs.push_back({"Overflow", {{"value", "i64"}}}); + caught = false; + try { (void)ny::nil_type_requires_provenance(graph, "Node0"); } + catch (const std::runtime_error &error) { + caught = std::string(error.what()).find("provenance type graph exceeds its bound") != std::string::npos; + } + check(caught, "provenance query still rejects a graph beyond 4096 nodes"); + graph.structs.pop_back(); + graph.structs.back().fields.front().second = "i64"; + check(!ny::nil_type_requires_provenance(graph, "Node0"), + "a rejected graph does not poison a later valid admission"); +} + void positives() { for (bool binary : {false, true}) { auto module = fixture(); std::unordered_map constants; @@ -451,7 +495,8 @@ void negatives() { } } // namespace int main() { - try { positives(); negatives(); class_enum_contract(); nominal_global_alias_contract(); } + try { positives(); negatives(); class_enum_contract(); nominal_global_alias_contract(); + provenance_admission_lifetime_contract(); } catch (const std::exception &error) { std::cerr << "Unexpected exception: " << error.what() << '\n'; return 1; } if (failures) return 1; std::cout << "Class metadata, provenance, dispatch, alias and version contracts passed\n"; From fd4417dbb5e7b614ee3fd7962409395a95793521 Mon Sep 17 00:00:00 2001 From: Nathan Young Date: Sat, 21 Nov 2026 02:10:13 -0500 Subject: [PATCH 15/15] Document qualified Goetic SDK and remaining Windows durability work --- README.md | 27 +++-- notebook/2026-11-21-goetic-enigma-sdk.md | 121 +++++++++++++++++++---- 2 files changed, 120 insertions(+), 28 deletions(-) diff --git a/README.md b/README.md index d8b2332c..414ad6bc 100644 --- a/README.md +++ b/README.md @@ -250,11 +250,13 @@ such as `say formatted "value={5}"`; it works on interpreted and native routes. ## Project status The current version is **1.0.0-rc.1**. Development coverage spans Linux x86_64, -Windows x86_64, Intel macOS and Apple Silicon macOS. Relocated development SDKs -on all four hosts pass 1,184 installed standard-library routes, twelve PostgreSQL -source/binary routes, 146 debugger checks and same-process execution checkpoints. -Linux's current SDK also passes all 590 source tests, twenty installed GTK -desktop/input cases and all 88 real VS Code host groups without exclusions. +Windows x86_64, Intel macOS and Apple Silicon macOS. The earlier platform +qualification campaign verified relocated development SDKs on all four hosts: +1,184 installed standard-library routes, twelve PostgreSQL source/binary routes, +146 debugger checks and same-process execution checkpoints. Its Linux SDK also +passed all 590 source tests, twenty installed GTK desktop/input cases and all 88 +real VS Code host groups without exclusions. The newer Goetic/Enigma integration +results are recorded separately below. Windows uses Win32 and macOS uses AppKit. Windows and both Mac architectures also pass twenty installed desktop/input cases, four desktop debugger sessions @@ -277,7 +279,8 @@ combines rooted file snapshots, the Matrix WebView bridge and the completed formatted-text/markup work. Its [qualification record](notebook/2026-11-13-formatted-markup-handoff.md#current-framework-integration) tracks current-source checks separately from the installed SDK results above. -The Goetic/Enigma integration additionally combines those compiler and editor +The [Goetic/Enigma integration](https://github.com/exec-software/exec-nil-framework/pull/43) +additionally combines those compiler and editor fixes with [durable files and context-owned locks](docs/standard-library/durable-files.md), private-entry checks, SHA-256, optional console input and native hexadecimal random draws. Durable filesystem operations currently support POSIX hosts; @@ -286,8 +289,16 @@ Windows returns explicit unsupported errors. The checks, installed SDK evidence and remaining limitations. The interpreter also preserves imported class values through typed module globals, record wrappers and explicit `Option` factories. Native -aggregate globals remain unsupported; the real Goetic/Enigma consumer is an -additional acceptance gate before SDK handoff. +aggregate globals remain unsupported. The real Goetic/Enigma snapshot and +optional-value consumers pass against the relocated Linux development SDK. +The current Linux development SDK passes 609 source tests and 1,248 installed +artifact routes; all four hosts pass 18 interpreter contracts and 32 fixture +routes each. Admission indexing reduces the measured Goetic parse/load time +from 45.58 seconds to 0.45 seconds. With the updated SDK, an isolated Goetic +instance reached HTTP readiness in 0.56 seconds within its unchanged ten-second +deadline. Its complete application suite passes all 26 Matrix fixtures and 101 +HTTP tests; canonical SDK relocation also passes. The notebook records the +exact source and SDK identities and separately tracks hosted application checks. These are development results. Windows and macOS release qualification remains pending. The diff --git a/notebook/2026-11-21-goetic-enigma-sdk.md b/notebook/2026-11-21-goetic-enigma-sdk.md index 0b526b9b..3464d8ac 100644 --- a/notebook/2026-11-21-goetic-enigma-sdk.md +++ b/notebook/2026-11-21-goetic-enigma-sdk.md @@ -2,17 +2,46 @@ ## Status and question -Clean source `2db8c9b7a13f45bd2b6a9effb1c973ed7d887ef7` produced development -SDK `ae06ead0f5d3312deaa29c2832c9bfd6665b91be107396323954cc88022ce317`. -All 609 Linux source tests, 1,248 installed fixed-output routes, installed -durable/console/global checks and the real snapshot/optional-value consumers -pass. Canonical relocation also passes markup, rooted-file and real consumer -checks. Shared defaults and accepted consumer pins remain unchanged. - -Goetic's broader application suite subsequently exposed severe startup cost. -Adoption is held while admission performance is corrected; successful value -and persistence tests alone do not qualify application responsiveness. This -remains development SDK work, not a stable release or a live migration. +Clean source `167ae3a6b0abb69c26e943a008ee6eb1eac8f13d` produced development +SDK `5931094a3cf696f0c176d370864df4b15c4f22f108074f9ca682a3db15f8388a`. +All 609 Linux source tests, 1,248 installed fixed-output routes and installed +durable/console/global checks pass. Both hosted source campaigns and the +four-host interpreter campaign also pass. The admission correction restores +Goetic's original ten-second HTTP readiness gate; the measured result is +0.560294 seconds in an isolated temporary workspace. + +Goetic's complete rerun exits successfully in 350.64 seconds: 26 Matrix +fixtures, 101 HTTP tests, 23 filesystem migration tests, nine Node checks, +native security/tooling and the actual snapshot lifecycle/alias harness. +The original ten-second startup deadline is unchanged. Owned test processes +and listeners are cleaned up. + +The immutable generation is published under the canonical SDK store with a +private alias. Relocation passes durable/console/global checks, 32 markup +routes, eight rooted snapshot routes, four unbox rejections, two conversion +routes and six native rejection controls. The exact Goetic snapshot harness +and real Enigma optional-value flows pass again against the physical path, +including both library packages and textual/binary NIL. All 279 payload files +remain unchanged. Goetic confirms pinning the delivered generation and building +successfully with it at its safe build boundary. Consumer activation is handled +separately by that project; the shared SDK default is unchanged. + +Both Intel and Apple Silicon macOS pass the current-source application/editor +campaign, including all 88 real editor groups without skips. Each architecture +also passes fourteen language/class/global contracts, twelve native contracts, +six debugger contracts, six SDK/project contracts, two incremental contracts, +eleven Enigma contracts and 24 fixture routes. The +[hosted campaign](https://github.com/exec-software/exec-nil-framework/actions/runs/44876499033) +tests the integration merge of `167ae3a` with its base branch. + +The previous clean `2db8c9b` candidate produced SDK +`ae06ead0f5d3312deaa29c2832c9bfd6665b91be107396323954cc88022ce317`. +Its 609 source tests, 1,248 installed routes, durable/console/global checks, +real snapshot/optional-value consumers and canonical relocation all passed. +Goetic's broader suite then exposed startup cost, so adoption was held for the +admission correction. Shared defaults and accepted consumer pins remain +unchanged at the handoff boundary. This remains development SDK work, not a +stable release or a live migration. Goetic needs its qualified compiler fixes together with Enigma's durable I/O surface, including `nil.std.io.file_lock_is_held`. The existing Goetic SDK came @@ -45,7 +74,25 @@ remain in place. ## Qualification contract -The focused Release/LLVM-ON run passes all twenty contracts, including existing +For source `167ae3a`, both hosted source campaigns pass 609 LLVM-ON tests +without skips, the 603-test LLVM-OFF profile with 145 expected skips, and 204 editor +unit tests without skips. Linux, Windows, Intel macOS and Apple Silicon macOS +each pass 18 interpreter contracts and all 32 fixed-output fixture routes. +Each host also executes eight nominal-global cases and two initialization +rejections within those contracts. The three POSIX hosts pass the additional +durable lifecycle/route contracts; Windows confirms checked unsupported errors +and nonmutation, not durable filesystem support. + +The independently reviewed `5931094a` SDK seals 279 payload files and eleven +tools to the tested build. Both `nilstd` and `nillib` pass the installed checks: +1,248 fixed-output executions in total; sixteen durable executions, 24 ABI and +72 foreign-library rejections; 202 console executions/checks per library; and +sixteen nominal-global VM executions, four initialization rejections and four +native aggregate-global rejections. The SDK and shared selection are unchanged +through qualification. Application acceptance and final relocation have their +own passing evidence, summarized above. + +The initial focused Release/LLVM-ON run passed all twenty contracts, including existing module identities, checked conversions, rooted file snapshots, ordinary I/O, native ABI and same-process checkpoints. Console state has 58 checks, durable VM lifecycle has 250, and the native console contract has 202 executions/checks. @@ -192,15 +239,26 @@ retained. These are admission measurements, not an HTTP-readiness claim. Twenty-eight focused contracts pass, including metadata mutation between admissions, same-named types in separate modules, and the exact 4096-node graph -boundary, overflow rejection and recovery. The fresh installed SDK must still -pass the full source/installed campaign and Goetic's original HTTP startup -deadline before adoption. Increasing that deadline is not the performance fix. +boundary, overflow rejection and recovery. The resulting `5931094a` SDK passes +the complete source/installed campaign. In a fresh explicit legacy temporary +workspace, the actual Goetic application becomes HTTP-ready in 0.560294 seconds +under the original ten-second deadline; listener cleanup is verified. This is +a separate application measurement from the admission-only comparison above. + +The first optimized aggregate run subsequently failed during imported unittest +class discovery, after all 26 Matrix fixtures, 100 other HTTP checks and the +actual staging checks had passed. Goetic selected `StageEnigmaTests` explicitly +with `defaultTest` and restarted the full command. The original failed report +is retained; its partial passes are not an aggregate acceptance claim. The +completed rerun passes all 101 HTTP tests and the complete command in 350.64 +seconds. No startup deadline was raised. ### Platform and language boundaries Durable filesystem primitives are currently POSIX-only. Windows rejection -checks prove explicit unsupported behavior, not parity. macOS needs its own -current-source execution evidence. Synchronization tests do not qualify storage +checks prove explicit unsupported behavior, not parity. Current macOS +interpreter and native application/editor evidence passes on both architectures. +Synchronization tests do not qualify storage hardware against power loss. Native text remains NUL-free. F93 remains open: a later Matrix local named `result` can interfere with an @@ -211,6 +269,29 @@ passes all four routes. Both variants pass analysis, so a successful analysis alone is not a workaround. F21 definite assignment and native arrays of nominal records also remain outside this integration. -Follow-up: record exact source/SDK identities and source, installed and hosted -results here after qualification, then deliver the immutable development SDK -to Goetic without changing the shared default. +Windows implementation should proceed in three separately qualified groups: + +1. Private-entry checks: `create_private_directory`, `is_private_regular_file` + and `is_private_directory`. +2. Context-owned locks: `acquire_file_lock`, `release_file_lock` and + `file_lock_is_held`. +3. Durable publication: `write_bytes_durable` and `sync_directory`. + +Keep checked unsupported behavior until each group passes its Windows backend +and installed-route contracts. The Linux development SDK handoff is complete; +current Mac application evidence remains separate from Linux consumer +acceptance. The shared SDK default remains unchanged. + +## Retained qualification identities + +- Independent installed SDK proof SHA-256: + `600eaf666ca1b86041b13f620486c46d5c76c8ada03c640cd5d9e9db4410fdf4`. +- Source and four-host interpreter proof SHA-256: + `81422c3da689c880476cc716330a23efc0b4902d9b3fedfa53c34397a13c34df`. +- Relocated actual-consumer proof SHA-256: + `4faa863555f57bf2bd2f5942dea956e545adb7fa6426709796193f90bc80d976`. +- Final Linux development handoff proof SHA-256: + `f83cc28b90fe554a6e87f77b992e0ad02488c24173d9be7ebc343ab123551344`. + +These identities refer to the qualified `167ae3a` source and `5931094a` SDK. +The subsequent documentation closeout does not rebuild or relabel that SDK.