From 782ec7c8183782ab75a2c4c3a2004bc8129b9cbc Mon Sep 17 00:00:00 2001 From: Nathan Date: Fri, 23 Oct 2026 14:26:42 -0400 Subject: [PATCH 1/3] Record Aperture memory profiles across VM and native execution --- CMakeLists.txt | 29 ++ README.md | 7 +- aperture/README.md | 156 +++++---- aperture/docs/DESIGN.md | 186 +++++----- aperture/src/agent/agent_interface.cpp | 16 +- aperture/src/main.cpp | 179 +++++----- aperture/src/memory/memory_engine.cpp | 428 ++++++++++++++++++------ aperture/src/memory/memory_engine.hpp | 72 +--- docs/tools/index.md | 15 +- matrix/docs/next-version-findings.md | 53 +++ nilcompiler/CMakeLists.txt | 1 + nilcompiler/src/llvm_backend.cpp | 39 +++ nilcompiler/src/memory_profile.cpp | 296 ++++++++++++++++ nilcompiler/src/memory_profile.hpp | 42 +++ nilcompiler/src/native_runtime.cpp | 49 ++- nilcompiler/src/native_runtime.hpp | 4 + nilcompiler/src/vm.cpp | 118 ++++++- nilcompiler/src/vm.hpp | 14 + tests/tools/aperture_memory_contract.py | 290 ++++++++++++++++ tests/tools/memory_profile_contract.py | 152 +++++++++ tests/tools/memory_profile_probe.cpp | 88 +++++ tests/vm_memory_profile_tests.cpp | 184 ++++++++++ vscode/README.md | 13 + vscode/package.json | 22 +- vscode/src/extension.ts | 18 + vscode/src/tasks.ts | 17 +- vscode/src/test/assets.test.ts | 2 +- vscode/src/toolchain.ts | 2 +- vscode/src/vscodeToolchain.ts | 3 +- vscode/test/memory-profile-checks.cjs | 32 ++ vscode/test/run-host.cjs | 2 +- vscode/test/suite.cjs | 1 + 32 files changed, 2070 insertions(+), 460 deletions(-) create mode 100644 nilcompiler/src/memory_profile.cpp create mode 100644 nilcompiler/src/memory_profile.hpp create mode 100644 tests/tools/aperture_memory_contract.py create mode 100644 tests/tools/memory_profile_contract.py create mode 100644 tests/tools/memory_profile_probe.cpp create mode 100644 tests/vm_memory_profile_tests.cpp create mode 100644 vscode/test/memory-profile-checks.cjs diff --git a/CMakeLists.txt b/CMakeLists.txt index a690a681..98369284 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1008,6 +1008,35 @@ if(BUILD_TESTING) --compiler-arg=--sdk-path --compiler-arg=${CMAKE_CURRENT_SOURCE_DIR}/nilstd/src ) + if(TARGET aperture) + add_executable(nil_vm_memory_profile_tests tests/vm_memory_profile_tests.cpp) + target_link_libraries(nil_vm_memory_profile_tests PRIVATE nilcompiler_core) + target_compile_features(nil_vm_memory_profile_tests PRIVATE cxx_std_17) + foreach(profile_mode IN ITEMS restart failure stepping abandoned) + add_test(NAME aperture.vm-profile-${profile_mode} + COMMAND $ ${profile_mode}) + set_tests_properties(aperture.vm-profile-${profile_mode} + PROPERTIES LABELS "aperture;memory;interpreter" TIMEOUT 30) + endforeach() + add_executable(nil_memory_profile_probe tests/tools/memory_profile_probe.cpp nilcompiler/src/memory_profile.cpp) + target_include_directories(nil_memory_profile_probe PRIVATE nilcompiler/src) + target_compile_features(nil_memory_profile_probe PRIVATE cxx_std_17) + target_link_libraries(nil_memory_profile_probe PRIVATE Threads::Threads) + add_test(NAME aperture.memory-collector-contract + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/memory_profile_contract.py" + --probe $) + set_tests_properties(aperture.memory-collector-contract PROPERTIES LABELS "aperture;memory" TIMEOUT 30) + if(UNIX) + add_test(NAME aperture.memory-contract + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/aperture_memory_contract.py" + --aperture $ + --compiler $ + --interpreter $ + --stdlib "${CMAKE_CURRENT_SOURCE_DIR}/nilstd/src" + --llvm "${NIL_ENABLE_LLVM}") + set_tests_properties(aperture.memory-contract PROPERTIES LABELS "aperture;memory;routes" TIMEOUT 180) + endif() + endif() add_test( NAME nil.analysis COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/analysis_contract.py" diff --git a/README.md b/README.md index 6c47de8f..ad047760 100644 --- a/README.md +++ b/README.md @@ -89,9 +89,10 @@ The framework includes: workspace snapshot. Compiler-resolved source bindings support Go to Definition for local variables, parameters and imported functions across both languages. Certified local variables also support references and checked rename. -- **Aperture — unified analysis suite.** Code exploration, memory profiling, - and performance tracing in a single tool designed for both human developers - and AI agents. See [aperture/README.md](aperture/README.md). +- **Aperture runtime diagnostics.** Memory profiles record runtime allocations, + frees, retained storage, peaks and source locations for VM and native programs. + Saved JSON reports support inspection and automated analysis. See + [aperture/README.md](aperture/README.md) for coverage and planned capabilities. See the [standard-library reference](docs/standard-library/index.md), [analysis API](docs/analysis-api.md), and [tool reference](docs/tools/index.md) diff --git a/aperture/README.md b/aperture/README.md index 9c8dbc98..db6ee2de 100644 --- a/aperture/README.md +++ b/aperture/README.md @@ -1,81 +1,93 @@ -# Aperture — NIL Framework Analysis & Debugging Suite +# Aperture -Aperture is an all-in-one static and dynamic analysis environment for the NIL -framework. It unifies code exploration, memory profiling, performance tracing, -and interactive debugging in a single tool designed for both human developers -and AI agents. +Aperture is the NIL framework's runtime diagnostics tool. Its first implemented +capability records memory activity from Ny and Matrix programs running in the +interpreter or as native executables, then connects allocation totals to source +locations. -## Vision +## Record a memory profile -Aperture brings together what JetBrains split across dotPeek (decompilation and -exploration), dotMemory (memory profiling), and dotTrace (performance tracing) — -but with the ability for AI agents to drive analysis, correlate findings, and -surface actionable insights. +Aperture ships with the SDK and uses the compiler, interpreter, assembler, and +linker installed beside it. -## Capabilities +```sh +# Compile and run source in the VM, saving a new report. +sdk/aperture memory --output vm-memory.json example.matrix -| Module | Purpose | JetBrains Analog | -|--------|---------|-----------------| -| `aperture-explore` | Code navigation, decompilation, call graphs | dotPeek | -| `aperture-memory` | Heap profiling, allocation tracing, leak detection | dotMemory | -| `aperture-trace` | CPU profiling, flame graphs, hotspot analysis | dotTrace | -| `aperture-agent` | AI-driven analysis and recommendation engine | — | +# Compile the same source with source metadata, then assemble and link natively. +sdk/aperture memory --native --output native-memory.json example.matrix -## Architecture +# Profile an existing NIL artifact or an instrumented native executable. +sdk/aperture memory --output memory.json example.nil +sdk/aperture memory --output native.json ./example +# Inspect a saved report without executing the program again. +sdk/aperture memory --report memory.json +sdk/aperture memory --report memory.json --json ``` -aperture/ -├── CMakeLists.txt # Build configuration -├── README.md # This file -├── src/ # Core source -│ ├── explore/ # Code exploration engine -│ ├── memory/ # Memory profiling engine -│ ├── trace/ # Performance tracing engine -│ ├── agent/ # AI agent interface -│ ├── core/ # Shared utilities and types -│ └── main.cpp # CLI entry point -└── docs/ # Design documentation -``` - -## Building - -Aperture is built as part of the NIL SDK: - -```bash -./scripts/build-sdk.sh -``` - -## Usage - -```bash -# Explore code structure and generate call graphs -sdk/aperture explore --call-graph example.nil - -# Profile memory allocations -sdk/aperture memory --profile example.nil - -# Trace execution performance -sdk/aperture trace --flame example.nil - -# Agent-assisted analysis (interactive) -sdk/aperture agent analyze --target example.nil -``` - -## AI Agent Integration - -Aperture exposes structured analysis output (JSON, NDJSON) designed for -machine consumption. The `agent` mode provides a conversational interface -where an AI agent can: - -1. **Query the codebase** — ask about call graphs, dependencies, or types -2. **Correlate findings** — combine memory and trace data to spot patterns -3. **Generate reports** — produce structured analysis summaries -4. **Recommend fixes** — suggest code changes based on detected issues - -This is Aperture's differentiator: analysis that doesn't stop at the human -screen. An AI agent can operate Aperture autonomously, producing insights -that no single human analyst could gather in the same time. - -## Status -Prototype. Core architecture is being defined alongside the NIL 1.0 release. +Recording preserves the program's standard input, output, error stream, working +directory, and exit status. The profile summary goes to standard error. `--json` +prints the full report there while recording; use `--output` or saved-report +inspection for a separate machine-readable stream. Program arguments follow +`--`, for example `aperture memory ./example -- "input file.txt"`. + +`--output` creates a new file and refuses to overwrite existing files, including +symlinks. A missing, malformed, or incomplete runtime profile makes recording +fail; a nonzero program exit remains the command's exit status. A valid report +can still be saved after a program failure. Abrupt termination may prevent the +runtime from finishing its report. + +For source compilation, `--sdk-path ` selects the standard-library +search root. This is a single-file workflow; project builds and dependency +configuration remain the responsibility of `nilbuild`. Programs compiled +separately need `--debug-info` in their NIL to retain source paths and line +numbers. Native source recording goes through that annotated NIL before native +assembly and linking. Older native programs must be rebuilt against the updated +runtime to produce profiles. + +`--memory-mode safe|unsafe` selects the interpreter memory mode, or the mode used +to compile source natively. Without it, each tool keeps its normal default. The +mode of an existing native executable cannot be changed by the profiler. + +## What the report measures + +Reports use the versioned `aperture.memory.v1` JSON schema. They contain: + +- Cumulative allocations and frees, current live storage, peak live storage, and + resize counts, in objects and runtime logical bytes. +- Allocation sites with source file, function, line, and allocation kind. +- Garbage-collection count, elapsed collection time, and reclaimed storage. +- Completion state, instrumentation errors, and scope limitations. + +Logical bytes describe storage tracked by each execution runtime. They are not +process RSS, allocator overhead, or a guarantee of identical byte counts between +VM and native execution. Live totals are captured before runtime teardown. An +object remaining live at that point is **not a proven memory leak**. + +Source attribution identifies the allocating instruction; it does not yet retain +full call stacks or ownership/retention paths. Reports aggregate allocation sites, +not individual allocation events. Reports include absolute source paths and +function names, so review them before sharing outside your project. + +## Current scope + +Recording is supported on POSIX hosts. Saved JSON reports can be inspected +without executing their targets. The current profiler covers the NIL runtime +allocations described in each report's `scope`. VM coverage currently includes +typed arrays, raw buffers, and iterator payloads; VM text and record storage, +container capacity, and `Value` overhead are excluded. Native coverage includes +runtime-managed allocations, array descriptors and capacity, and runtime buffer +storage. Native unmanaged instructions that allocate directly through libc are +excluded, including raw allocations, records, variants, and string concatenation. +External library allocations, OS resources, and unrelated process memory are +outside that accounting. + +Heap snapshots and comparison, retained-object graphs, allocation rates and +lifetimes, invalid-access diagnostics, CPU profiling, debugger capture, and an +interactive analysis interface are planned. The `explore`, `trace`, and `agent` +commands currently return an explicit unsupported-command error. + +Build with the framework or generate a complete SDK using +`./scripts/build-sdk.sh`. See [design notes](docs/DESIGN.md) for the runtime +contract and integration boundaries. diff --git a/aperture/docs/DESIGN.md b/aperture/docs/DESIGN.md index dd6aa5c0..bb9efd4b 100644 --- a/aperture/docs/DESIGN.md +++ b/aperture/docs/DESIGN.md @@ -1,99 +1,87 @@ -# Aperture Design Notes - -## Rationale - -The NIL framework has three existing analysis/debugging tools: - -1. **`nilcompiler --analyze`** — static analysis of source -2. **`nildebugger`** — interactive runtime debugging (DAP-based) -3. **`nilinterpreter`** — runtime execution with instrumentation hooks - -These cover individual phases but lack a unified interface. Aperture unifies -them into a single analysis engine, and adds a machine-readable interface for -AI agents. - -## Architecture - -### Engine Model - -Each analysis capability is a self-contained engine: - -``` -┌─────────────┐ -│ Aperture CLI │ dispatches to the appropriate engine -└──────┬──────┘ - │ - ┌───┼───┬───────────┐ - ▼ ▼ ▼ ▼ -┌────┐┌────┐┌──────┐┌────────┐ -│Explore││Memory││Trace ││Agent │ -│Engine││Engine││Engine││Interface│ -└────┘└────┘└──────┘└────────┘ - │ │ │ │ - └──────┼────────┴─────────┘ - ▼ - ┌──────────────┐ - │ Aperture Core │ shared types, logger, target resolution - └──────────────┘ -``` - -### Engine Responsibilities - -| Engine | Responsibility | Output | -|--------|---------------|--------| -| **Explore** | Decompilation, call graphs, type hierarchy | Function map, call graph | -| **Memory** | Heap profiling, allocation tracking, leak detection | Snapshots, leak list | -| **Trace** | CPU profiling, flame graphs, hotspot analysis | Stack samples, timing data | -| **Agent** | AI-driven analysis orchestration | Recommendations, findings | - -### Data Flow - -1. **CLI** resolves the target file (`.nil`, `.ny`, `.matrix`, or native) -2. **Core** provides shared infrastructure: logger, target metadata -3. **Engine** performs its analysis, producing structured results -4. **Agent** can orchestrate multiple engines and correlate results - -### AI Agent Interface - -Aperture's differentiator is its machine-readable output. Every engine supports -`--json` mode, emitting structured JSON that an AI agent can consume. The -`agent` subcommand orchestrates all engines and produces a unified report. - -This enables: -- Autonomous code analysis by AI agents -- Correlation of findings across engines (e.g., memory leaks + hotspots) -- Recommendation generation based on multiple data sources - -## Integration Points - -### With nilcompiler - -The explore engine will eventually use nilcompiler's semantic analysis API -to get accurate call graphs and type information from source code. - -### With nilinterpreter - -The memory and trace engines need hooks into the NIL VM to capture: -- Allocation events (for memory profiling) -- Execution ticks (for CPU tracing) -- Stack frames (for flame graphs) - -### With nildebugger - -The debugger's DAP protocol provides source-level debugging. Aperture can -use this for interactive analysis sessions where the agent queries live -program state. - -## Future Extensions - -- **Visual flame graphs** — HTML output for browser viewing -- **Diff analysis** — compare two versions of a program -- **Continuous profiling** — attach to running processes -- **Custom analysis plugins** — extensible engine system -- **Web interface** — GUI for interactive exploration - -## Naming - -"Aperture" — a lens opening that lets light in. Aperture illuminates the -inside of NIL programs. It's a single word, easy to type, and fits the -photography metaphor: memory snapshots, call graph exposures, trace captures. +# Aperture memory profiling + +Aperture's first complete workflow records a program, reports where runtime +memory accumulates, and provides source locations for investigation. The CLI and +runtime share a versioned report format so editor features and automated tools +can consume the same evidence. + +## Recording flow + +1. The CLI validates the target and exclusively reserves an optional output + destination before execution. +2. Source inputs are compiled with debug metadata to temporary NIL. Native source + inputs then pass through `nilassembler` and `nillinker` using that metadata. +3. Aperture starts the interpreter or native target directly, with an argument + vector and no shell. `NIL_MEMORY_PROFILE` names a fresh file in a private + temporary directory. Compilation tools do not receive that setting. +4. The runtime reserves its report path exclusively, records allocations and + releases, and finalizes the report before tearing down its managed state. +5. Aperture validates the report before displaying or publishing it. Failed or + incomplete runs remain explicitly identified; a successful target without a + valid completed profile is a profiling failure. + +The child inherits standard input/output/error and the caller's working +directory. Target output stays on standard output; recording summaries go to +standard error. Saved-report inspection uses standard output and does not run a +program. Target exit codes are propagated, including signal-derived statuses. + +## Runtime contract + +`NIL_MEMORY_PROFILE` activates an opt-in recording session. The shared collector +is inert when the variable is absent. Runtime hooks identify allocation sites, +record allocation and resize deltas, and record logical release and collection +events. The native compiler emits source-site updates at allocating instructions; +the interpreter uses its current instruction and debug metadata. + +A session writes one `aperture.memory.v1` JSON object containing: + +| Field | Meaning | +|---|---| +| `schema` | Exactly `aperture.memory.v1` | +| `route` | `vm` or `native` | +| `measurement` | `runtime_logical_bytes` | +| `completed`, `status` | Whether recording finalized, and how execution ended | +| `totals` | Allocated/freed/live/peak bytes and objects; resize count | +| `collections` | Collection count, elapsed nanoseconds, reclaimed bytes and objects | +| `sites` | The same counters grouped by file, function, line, and allocation kind | +| `scope` | Accounting boundaries and runtime-specific exclusions | +| `errors` | Instrumentation/reporting failures | +| `excluded_sessions` | Runtime sessions outside the recorded session | +| `site_limit_reached` | Whether source-site detail reached its recording limit | + +Byte counters use delta accounting: growth adds allocated bytes, shrinkage adds +freed bytes, and resizing does not create or free an object. Therefore +`allocated - freed = live`, with `live <= peak <= allocated`. Peak values are +maxima over the session, not sums of per-site peaks. Unknown source metadata uses +an empty file and line zero; it must not be replaced with guessed source lines. + +Reports aggregate sites rather than retaining all individual events. Native and +VM storage models differ, so byte-for-byte parity is not a contract. Both routes +must preserve program behavior and identify the relevant source allocation. +The report is finalized before ordinary shutdown cleanup, retaining useful live +storage evidence instead of automatically reporting zero. + +## Limits and failure behavior + +Live allocations are not classified as leaks. No root-retention graph, allocation +lifetime, full call stack, allocation-rate timeline, CPU sample, or debugger heap +snapshot is produced yet. Source locations can be unavailable in artifacts built +without debug metadata. Allocations outside the NIL runtime's tracked storage +are outside the report's scope. In native unmanaged mode, raw allocations, +records, variants, and string concatenation use libc directly and are excluded; +arrays and other storage allocated through the NIL runtime remain tracked. + +The CLI rejects malformed JSON, unknown schema versions, missing fields, +inconsistent counters, oversized reports, and unsupported status values. It +never interprets report strings as commands. Existing output files and symlink +referents are not overwritten. Runtime output failures are diagnostics and +nonzero results, not apparently successful empty profiles. Abrupt process death +may leave an unfinished temporary report and cannot promise a final snapshot. + +## Next integrations + +VS Code can launch recording and read the same saved JSON for source navigation. +Future debugger support should reuse the source identity and allocation hooks to +capture snapshots while paused. Retention analysis, snapshot comparison, +allocation timelines, and CPU call trees can extend the suite without claiming +those features in the current memory report. diff --git a/aperture/src/agent/agent_interface.cpp b/aperture/src/agent/agent_interface.cpp index 9b46f571..3ecdc531 100644 --- a/aperture/src/agent/agent_interface.cpp +++ b/aperture/src/agent/agent_interface.cpp @@ -118,21 +118,9 @@ AgentResponse AgentInterface::ask_call_graph(const std::string& target, const st } AgentResponse AgentInterface::ask_memory(const std::string& target) { - Logger::info("Agent query: memory analysis"); - - MemoryEngine engine; - auto leaks = engine.detect_leaks(target); - + (void)target; AgentResponse response; - response.analysis = "Memory scan complete"; - - if (leaks.empty()) { - response.analysis += " — no leaks detected"; - } else { - response.analysis += " — " + std::to_string(leaks.size()) + " leaks found"; - response.recommendations.push_back("Review " + std::to_string(leaks.size()) + " allocation sites for leaks"); - } - + response.analysis = "Automated memory analysis is not implemented; use aperture memory to record a runtime profile."; return response; } diff --git a/aperture/src/main.cpp b/aperture/src/main.cpp index a69b5f76..3947f7ea 100644 --- a/aperture/src/main.cpp +++ b/aperture/src/main.cpp @@ -1,102 +1,111 @@ -// Aperture — main entry point -// Unified analysis and debugging suite for NIL framework. - +// Aperture — runtime diagnostics for the NIL framework. +#include +#include #include +#include #include -#include -#include -#include -#include "core/aperture_core.hpp" -#include "explore/explore_engine.hpp" #include "memory/memory_engine.hpp" -#include "trace/trace_engine.hpp" -#include "agent/agent_interface.hpp" -static constexpr char VERSION[] = "aperture 0.1.0-dev (NIL Framework)"; +#ifndef _WIN32 +#include +#endif -static void print_usage() { +static void usage() { std::cout << - "Aperture — NIL Framework Analysis & Debugging Suite\n" - "\n" - "Usage: aperture [options] \n" - "\n" - "Subcommands:\n" - " explore Explore code structure, generate call graphs\n" - " memory Profile memory allocations and detect leaks\n" - " trace Trace execution performance, flame graphs\n" - " agent AI-assisted interactive analysis\n" - "\n" + "Aperture — NIL Framework Diagnostics\n\n" + "Usage: aperture memory [options] [-- args...]\n" + " aperture memory --report [--json]\n\n" "Options:\n" - " --help Show this help message\n" - " --version Show version information\n" - " --output Output file (default: stdout)\n" - " --json Output structured JSON\n" - "\n"; + " --output Save a new aperture.memory.v1 JSON report\n" + " --json Print the complete JSON report\n" + " --native Compile Ny/Matrix source through the native toolchain\n" + " --memory-mode safe or unsafe; VM and source compilation only\n" + " --sdk-path Standard-library search root for source compilation\n" + " --help Show this help\n" + " --version Show version information\n\n" + "Recording preserves program stdout; the profile is printed on stderr.\n" + "Saved-report inspection prints on stdout. Output files are never overwritten.\n" + "CPU tracing, heap snapshots, leak detection and interactive analysis are planned.\n"; } -static void print_version() { - std::cout << VERSION << '\n'; +static std::string tool_directory(const char* executable) { + namespace fs = std::filesystem; + std::error_code error; +#if defined(__linux__) + auto path = fs::read_symlink("/proc/self/exe", error); + if (!error) return path.parent_path().string(); +#endif + fs::path supplied(executable); + if (supplied.has_parent_path()) return fs::absolute(supplied).parent_path().string(); + if (const char* value = std::getenv("PATH")) { + std::string paths(value); + std::size_t start = 0; + do { + auto end = paths.find(':', start); + auto directory = paths.substr(start, end - start); + auto candidate = fs::path(directory.empty() ? "." : directory) / supplied; + if (fs::is_regular_file(candidate, error)) + return fs::absolute(candidate).parent_path().string(); + if (end == std::string::npos) break; + start = end + 1; + } while (start <= paths.size()); + } + throw std::runtime_error("cannot locate adjacent NIL tools"); } int main(int argc, char* argv[]) { - // Minimal argument parsing - std::string subcommand; - std::string target; - bool json = false; - - static struct option long_options[] = { - {"help", no_argument, nullptr, 'h'}, - {"version", no_argument, nullptr, 'v'}, - {"json", no_argument, nullptr, 'j'}, - {nullptr, 0, nullptr, 0 } - }; - - int c; - while ((c = getopt_long(argc, argv, "hjv", long_options, nullptr)) != -1) { - switch (c) { - case 'h': print_usage(); return 0; - case 'v': print_version(); return 0; - case 'j': json = true; break; - case '?': print_usage(); return 1; + try { + if (argc == 2 && std::string(argv[1]) == "--version") { + std::cout << "aperture 0.1.0-dev (NIL Framework)\n"; + return 0; } - } - - if (optind >= argc) { - std::cerr << "aperture: missing subcommand\n"; - print_usage(); - return 1; - } - - subcommand = argv[optind++]; - - if (optind >= argc) { - std::cerr << "aperture: " << subcommand << " requires a target file\n"; - return 1; - } - - target = argv[optind++]; - - // Dispatch to the appropriate engine - if (subcommand == "explore") { - aperture::ExploreEngine engine; - return engine.run(target, json) ? 0 : 1; - } - else if (subcommand == "memory") { - aperture::MemoryEngine engine; - return engine.run(target, json) ? 0 : 1; - } - else if (subcommand == "trace") { - aperture::TraceEngine engine; - return engine.run(target, json) ? 0 : 1; - } - else if (subcommand == "agent") { - aperture::AgentInterface agent; - return agent.interact(target, json) ? 0 : 1; - } - else { - std::cerr << "aperture: unknown subcommand '" << subcommand << "'\n"; - print_usage(); + if (argc == 1 || (argc == 2 && (std::string(argv[1]) == "--help" || std::string(argv[1]) == "-h"))) { + usage(); + return argc == 1 ? 1 : 0; + } + const std::string command = argv[1]; + if (command == "trace" || command == "explore" || command == "agent") + throw std::runtime_error(command + " is not implemented; use memory to record runtime allocations"); + if (command != "memory") throw std::runtime_error("unknown subcommand: " + command); + aperture::MemoryOptions options; + for (int i = 2; i < argc; ++i) { + std::string argument = argv[i]; + auto value = [&]() { + if (++i == argc) throw std::runtime_error(argument + " requires a value"); + return std::string(argv[i]); + }; + if (argument == "--help" || argument == "-h") { usage(); return 0; } + else if (argument == "--json") options.json = true; + else if (argument == "--native") options.native = true; + else if (argument == "--output") { + if (!options.output.empty()) throw std::runtime_error("--output specified more than once"); + options.output = value(); + } else if (argument == "--report") { + if (!options.report.empty()) throw std::runtime_error("--report specified more than once"); + options.report = value(); + } else if (argument == "--sdk-path") options.sdk_path = value(); + else if (argument == "--memory-mode") options.memory_mode = value(); + else if (argument.rfind("--memory-mode=", 0) == 0) options.memory_mode = argument.substr(14); + else if (argument == "--") { + if (options.target.empty()) throw std::runtime_error("program arguments require a target before --"); + while (++i < argc) options.arguments.emplace_back(argv[i]); + } else if (!argument.empty() && argument[0] == '-') { + throw std::runtime_error("unknown memory option: " + argument); + } else if (options.target.empty()) options.target = argument; + else throw std::runtime_error("only one target is accepted; separate program arguments with --"); + } + if (!options.memory_mode.empty() && options.memory_mode != "safe" && options.memory_mode != "unsafe") + throw std::runtime_error("--memory-mode must be safe or unsafe"); + if (!options.report.empty()) { + if (!options.target.empty() || !options.output.empty() || options.native || + !options.arguments.empty() || !options.memory_mode.empty() || !options.sdk_path.empty()) + throw std::runtime_error("--report accepts only --json; it does not execute a target"); + } else if (options.target.empty()) throw std::runtime_error("memory requires a target or --report"); + options.tool_directory = tool_directory(argv[0]); + return aperture::MemoryEngine{}.run(options); + } catch (const std::exception& error) { + std::cerr << "aperture: " << error.what() << '\n'; return 1; } } diff --git a/aperture/src/memory/memory_engine.cpp b/aperture/src/memory/memory_engine.cpp index ec234e82..c9cd8351 100644 --- a/aperture/src/memory/memory_engine.cpp +++ b/aperture/src/memory/memory_engine.cpp @@ -1,136 +1,342 @@ -// Aperture Memory — implementation - #include "memory_engine.hpp" +#include "../../../common/strict_json.hpp" + +#include +#include +#include +#include +#include +#include #include -#include #include +#include +#include +#include + +#ifndef _WIN32 +#include +#include +#include +#include +#include +#endif namespace aperture { +namespace { +namespace fs = std::filesystem; +using Json = nil::detail::json; -MemoryEngine::MemoryEngine() {} -MemoryEngine::~MemoryEngine() {} - -bool MemoryEngine::run(const std::string& target, bool json_output) { - Logger::info("Profiling memory: " + target); - - auto info = resolve_target(target); - Logger::info("Target: " + info.path); - - MemoryResult result = trace_allocations(target); - - // Detect leaks - result.leaks = detect_leaks(target); - Logger::info("Detected " + std::to_string(result.leaks.size()) + " potential leaks"); - - // Output - if (json_output) { - std::cout << to_json(result) << '\n'; - } else { - // Human-readable summary - std::cout << "=== Memory Profile: " << target << " ===\n"; - std::cout << "Snapshots: " << result.snapshots.size() << "\n"; - std::cout << "Potential leaks: " << result.leaks.size() << "\n"; - std::cout << "Leak ratio: " << result.leak_ratio << "\n"; - - std::cout << "\nAllocation hotspots:\n"; - for (auto& [site, bytes] : result.site_totals) { - std::cout << " " << site << ": " << bytes << " bytes\n"; - } - } - - return true; +std::string string_field(const Json& object, const std::string& field) { + const auto& item = object.at(field); + if (item.type != Json::kind::string) throw std::runtime_error("invalid profile string: " + field); + return item.text; +} + +std::uint64_t count_field(const Json& object, const std::string& field) { + const auto& item = object.at(field); + if (item.type != Json::kind::number || item.text.empty() || + item.text.find_first_not_of("0123456789") != std::string::npos) + throw std::runtime_error("invalid profile count: " + field); + try { return std::stoull(item.text); } + catch (...) { throw std::runtime_error("profile count is out of range: " + field); } } -HeapSnapshot MemoryEngine::capture(const std::string& target) { - HeapSnapshot snapshot; - snapshot.timestamp = 0; - - // TODO: integrate with NIL runtime's heap metadata - // Placeholder snapshot - - snapshot.total_allocated = 0; - snapshot.total_objects = 0; - snapshot.total_freed = 0; - - return snapshot; +bool flag_field(const Json& object, const std::string& field) { + const auto& item = object.at(field); + if (item.type != Json::kind::boolean) throw std::runtime_error("invalid profile flag: " + field); + return item.boolean; } -std::vector MemoryEngine::detect_leaks(const std::string& target) { - std::vector leaks; - - Logger::trace("Scanning for leaks in: " + target); - - // TODO: analyze allocation/freedom pairs against runtime heap state - // Placeholder — no leaks yet - - return leaks; +void validate_counters(const Json& object) { + for (const char* field : {"allocated_bytes", "allocated_objects", "live_bytes", "live_objects", + "peak_bytes", "peak_objects", "freed_bytes", "freed_objects", "resizes"}) + count_field(object, field); + for (const char* unit : {"bytes", "objects"}) { + const auto allocated = count_field(object, std::string("allocated_") + unit); + const auto freed = count_field(object, std::string("freed_") + unit); + const auto live = count_field(object, std::string("live_") + unit); + const auto peak = count_field(object, std::string("peak_") + unit); + if (freed > allocated || live != allocated - freed || peak < live || peak > allocated) + throw std::runtime_error("inconsistent profile counters"); + } } -MemoryResult MemoryEngine::trace_allocations(const std::string& target) { - MemoryResult result; - - Logger::trace("Tracing allocations in: " + target); - - // Capture initial and final snapshots - HeapSnapshot before = capture(target); - HeapSnapshot after = capture(target); - - result.snapshots.push_back(before); - result.snapshots.push_back(after); - - // Diff to find what changed - diff_snapshots(before, after); - - // Calculate leak ratio - if (before.total_allocated > 0) { - result.leak_ratio = double(after.total_allocated) / double(before.total_allocated); +struct Profile { std::string raw; Json data; }; +Profile read_profile(const fs::path& file) { + constexpr std::uintmax_t maximum_bytes = 64 * 1024 * 1024; + std::error_code error; + const auto size = fs::file_size(file, error); + if (error || !fs::is_regular_file(file) || size > maximum_bytes) + throw std::runtime_error("cannot read memory profile (regular file up to 64 MiB required): " + file.string()); + std::ifstream input(file, std::ios::binary); + if (!input) throw std::runtime_error("cannot open memory profile: " + file.string()); + std::string raw(static_cast(size), '\0'); + input.read(raw.data(), static_cast(raw.size())); + if (input.gcount() != static_cast(raw.size()) || input.peek() != EOF) + throw std::runtime_error("memory profile changed while reading"); + auto data = nil::detail::json_parser(raw).parse(); + if (string_field(data, "schema") != "aperture.memory.v1") + throw std::runtime_error("unsupported memory profile schema"); + const auto route = string_field(data, "route"); + if (route != "vm" && route != "native") throw std::runtime_error("invalid profile route"); + if (string_field(data, "measurement") != "runtime_logical_bytes") + throw std::runtime_error("unsupported profile measurement"); + const auto status = string_field(data, "status"); + if (status != "completed" && status != "failed" && status != "exited" && + status != "abandoned" && status != "profile_error") + throw std::runtime_error("invalid profile status"); + flag_field(data, "completed"); + flag_field(data, "site_limit_reached"); + count_field(data, "excluded_sessions"); + validate_counters(data.at("totals")); + for (const char* field : {"count", "duration_ns", "freed_bytes", "freed_objects"}) + count_field(data.at("collections"), field); + for (const char* field : {"scope", "errors"}) { + const auto& list = data.at(field); + if (list.type != Json::kind::array) throw std::runtime_error("invalid profile list: " + std::string(field)); + for (const auto& item : list.array) + if (item.type != Json::kind::string) throw std::runtime_error("invalid profile list entry"); } - - return result; + const auto& sites = data.at("sites"); + if (sites.type != Json::kind::array) throw std::runtime_error("invalid profile sites"); + for (const auto& site : sites.array) { + for (const char* field : {"file", "function", "kind"}) string_field(site, field); + count_field(site, "line"); + validate_counters(site); + } + return {std::move(raw), std::move(data)}; +} + +bool complete(const Profile& profile) { + const auto status = string_field(profile.data, "status"); + return flag_field(profile.data, "completed") && (status == "completed" || status == "exited") && + profile.data.at("errors").array.empty(); } -void MemoryEngine::diff_snapshots(const HeapSnapshot& before, const HeapSnapshot& after) { - size_t delta = after.total_allocated - before.total_allocated; - Logger::info("Heap delta: " + std::to_string(delta) + " bytes"); +void print_profile(const Profile& profile, bool json, std::ostream& stream) { + if (json) { stream << profile.raw; if (profile.raw.empty() || profile.raw.back() != '\n') stream << '\n'; return; } + const auto& data = profile.data; + const auto& totals = data.at("totals"); + stream << "Aperture memory profile (" << string_field(data, "route") << ", " + << string_field(data, "status") << ")\n" + << " Allocated: " << count_field(totals, "allocated_bytes") << " bytes in " + << count_field(totals, "allocated_objects") << " objects\n" + << " Live at session end: " << count_field(totals, "live_bytes") << " bytes in " + << count_field(totals, "live_objects") << " objects\n" + << " Peak live: " << count_field(totals, "peak_bytes") << " bytes\n" + << " Freed: " << count_field(totals, "freed_bytes") << " bytes; resizes: " + << count_field(totals, "resizes") << '\n' + << " Collections: " << count_field(data.at("collections"), "count") + << "; elapsed: " << count_field(data.at("collections"), "duration_ns") << " ns\n" + << " Measurements cover runtime logical storage, not process RSS. Live objects are not classified as leaks.\n"; + std::vector sites; + for (const auto& site : data.at("sites").array) sites.push_back(&site); + std::stable_sort(sites.begin(), sites.end(), [](const Json* a, const Json* b) { + return count_field(*a, "live_bytes") > count_field(*b, "live_bytes"); + }); + stream << "Allocation sites (largest live totals first):\n"; + for (std::size_t i = 0; i < std::min(sites.size(), 20); ++i) { + const auto& site = *sites[i]; + auto file = string_field(site, "file"); + if (file.empty()) file = ""; + stream << " " << file << ':' << count_field(site, "line") << " in " + << string_field(site, "function") << " [" << string_field(site, "kind") << "]: " + << count_field(site, "live_bytes") << " live, " << count_field(site, "allocated_bytes") + << " allocated bytes\n"; + } + if (sites.size() > 20) stream << " " << sites.size() - 20 << " more sites in the JSON report\n"; + if (flag_field(data, "site_limit_reached")) stream << " Warning: allocation-site detail reached its recording limit.\n"; + if (count_field(data, "excluded_sessions")) stream << " Warning: additional runtime sessions were excluded.\n"; + for (const auto& message : data.at("errors").array) stream << " Profile error: " << message.text << '\n'; } -std::vector> MemoryEngine::find_hotspots( - const std::vector& events) -{ - std::vector> hotspots; - - // Aggregate by site - std::map site_bytes; - for (auto& ev : events) { - site_bytes[ev.site] += ev.size; +#ifndef _WIN32 +class TemporaryDirectory { +public: + fs::path path; + TemporaryDirectory() { + auto pattern = (fs::temp_directory_path() / "aperture-memory-XXXXXX").string(); + std::vector storage(pattern.begin(), pattern.end()); storage.push_back('\0'); + auto created = mkdtemp(storage.data()); + if (!created) throw std::runtime_error("cannot create private profile directory"); + path = created; + } + ~TemporaryDirectory() { std::error_code error; fs::remove_all(path, error); } +}; + +// Reserve the user destination before executing anything. Failed publication +// removes only the new file this invocation created; existing files are intact. +class OutputFile { + fs::path path; + int descriptor = -1; + bool published = false; +public: + explicit OutputFile(const std::string& requested) : path(requested) { + if (path.empty()) return; + descriptor = open(path.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0600); + if (descriptor < 0) throw std::runtime_error("cannot create output report: " + path.string() + ": " + std::strerror(errno)); } - - // Convert to sorted list - for (auto& [site, bytes] : site_bytes) { - hotspots.push_back({site, bytes}); + ~OutputFile() { + if (descriptor >= 0) close(descriptor); + if (!path.empty() && !published) { std::error_code error; fs::remove(path, error); } } - - return hotspots; + void publish(const std::string& raw) { + if (descriptor < 0) return; + std::size_t offset = 0; + while (offset < raw.size()) { + const auto written = write(descriptor, raw.data() + offset, raw.size() - offset); + if (written < 0 && errno == EINTR) continue; + if (written <= 0) throw std::runtime_error("cannot write output report: " + path.string()); + offset += static_cast(written); + } + if (fsync(descriptor) != 0) throw std::runtime_error("cannot flush output report: " + path.string()); + const auto closed = close(descriptor); descriptor = -1; + if (closed != 0) throw std::runtime_error("cannot close output report: " + path.string()); + published = true; + } +}; + +volatile sig_atomic_t active_child = 0; +volatile sig_atomic_t pending_signal = 0; +void forward_signal(int signal) { + const int saved = errno; + pending_signal = signal; + if (active_child > 0) kill(active_child, signal); + errno = saved; } +class SignalForwarding { + struct sigaction previous_int{}, previous_term{}; +public: + SignalForwarding() { + active_child = 0; pending_signal = 0; + struct sigaction action{}; + action.sa_handler = forward_signal; + sigemptyset(&action.sa_mask); + if (sigaction(SIGINT, &action, &previous_int) != 0) + throw std::runtime_error("cannot install interruption handler"); + if (sigaction(SIGTERM, &action, &previous_term) != 0) { + sigaction(SIGINT, &previous_int, nullptr); + throw std::runtime_error("cannot install termination handler"); + } + } + ~SignalForwarding() { + active_child = 0; + sigaction(SIGINT, &previous_int, nullptr); + sigaction(SIGTERM, &previous_term, nullptr); + } +}; -std::string MemoryEngine::to_json(const MemoryResult& result) { - std::ostringstream out; - out << "{\n"; - out << " \"type\": \"memory\",\n"; - out << " \"snapshots\": " << result.snapshots.size() << ",\n"; - out << " \"leaks\": ["; - - bool first = true; - for (auto& leak : result.leaks) { - if (!first) out << ","; - first = false; - out << "\n \"" << leak << "\""; +int execute(const std::vector& arguments, const std::string& report = {}) { + SignalForwarding forwarding; + std::vector argv; + for (const auto& argument : arguments) argv.push_back(const_cast(argument.c_str())); + argv.push_back(nullptr); + std::cout.flush(); std::cerr.flush(); + const auto child = fork(); + if (child < 0) throw std::runtime_error("cannot start target process"); + if (child == 0) { + signal(SIGINT, SIG_DFL); signal(SIGTERM, SIG_DFL); + // Keep the terminal's foreground process group so input still works. + if (report.empty()) { + unsetenv("NIL_MEMORY_PROFILE"); + // Tool progress belongs with diagnostics, never target stdout. + if (dup2(STDERR_FILENO, STDOUT_FILENO) < 0) _exit(126); + } + else if (setenv("NIL_MEMORY_PROFILE", report.c_str(), 1) != 0) _exit(126); + execv(argv.front(), argv.data()); + const char message[] = "aperture: cannot execute target or adjacent tool\n"; + (void)!write(STDERR_FILENO, message, sizeof(message) - 1); + _exit(127); + } + active_child = child; + if (pending_signal) kill(child, pending_signal); + int status = 0; + while (waitpid(child, &status, 0) < 0) { + if (errno == EINTR) continue; + throw std::runtime_error("cannot collect target exit status"); } - out << "\n ],\n"; - out << " \"leak_ratio\": " << result.leak_ratio << "\n"; - out << "}\n"; - - return out.str(); + active_child = 0; + return WIFEXITED(status) ? WEXITSTATUS(status) : WIFSIGNALED(status) ? 128 + WTERMSIG(status) : 1; } +std::string tool(const MemoryOptions& options, const char* name) { + auto path = fs::path(options.tool_directory) / name; + if (!fs::is_regular_file(path) || access(path.c_str(), X_OK) != 0) + throw std::runtime_error("required adjacent NIL tool is unavailable: " + path.string()); + return path.string(); +} +#endif +} // namespace + +int MemoryEngine::run(const MemoryOptions& options) { + if (!options.report.empty()) { + const auto profile = read_profile(options.report); + print_profile(profile, options.json, std::cout); + return complete(profile) ? 0 : 1; + } +#ifdef _WIN32 + throw std::runtime_error("memory recording currently requires a POSIX host; saved reports can be inspected on this platform"); +#else + auto target = fs::absolute(options.target); + if (!fs::is_regular_file(target)) throw std::runtime_error("target is not a regular file: " + target.string()); + auto extension = target.extension().string(); + for (char& c : extension) if (c >= 'A' && c <= 'Z') c = static_cast(c - 'A' + 'a'); + const bool source = extension == ".ny" || extension == ".matrix" || extension == ".mat"; + bool bytecode = extension == ".nil"; + if (!source && !options.sdk_path.empty()) throw std::runtime_error("--sdk-path is only used for source compilation"); + if (options.native && !source) throw std::runtime_error("--native requires Ny or Matrix source; pass a native executable directly to profile it"); + if (!source && !bytecode && !options.memory_mode.empty()) + throw std::runtime_error("--memory-mode cannot change a precompiled native program"); + TemporaryDirectory temporary; + OutputFile output(options.output); + const auto report_path = temporary.path / "profile.json"; + if (source) { + const auto nil = temporary.path / "program.nil"; + std::vector compiler{tool(options, "nilcompiler"), "--quiet", "--debug-info", "--no-bundle"}; + if (!options.sdk_path.empty()) compiler.insert(compiler.end(), {"--sdk-path", options.sdk_path}); + compiler.insert(compiler.end(), {"-o", nil.string(), target.string()}); + auto status = execute(compiler); + if (status != 0) return status; + target = nil; + bytecode = true; + if (options.native) { + const auto object = temporary.path / "program.o"; + std::vector assembler{tool(options, "nilassembler")}; + if (options.memory_mode == "unsafe") assembler.push_back("--unmanaged"); + assembler.insert(assembler.end(), {"-o", object.string(), nil.string()}); + status = execute(assembler); + if (status != 0) return status; + target = temporary.path / "program"; + status = execute({tool(options, "nillinker"), "-o", target.string(), object.string()}); + if (status != 0) return status; + bytecode = false; + } + } + std::vector command; + if (bytecode) { + command = {tool(options, "nilinterpreter"), "--no-ai"}; + if (!options.memory_mode.empty()) command.push_back("--memory-mode=" + options.memory_mode); + command.push_back(target.string()); + command.push_back("--"); + } else command.push_back(target.string()); + command.insert(command.end(), options.arguments.begin(), options.arguments.end()); + const int status = execute(command, report_path.string()); + try { + const auto profile = read_profile(report_path); + output.publish(profile.raw); + print_profile(profile, options.json, std::cerr); + if (!options.output.empty() && !options.json) + std::cerr << "Saved memory profile: " << fs::absolute(options.output).string() << '\n'; + if (status != 0) return status; + if (!complete(profile)) { + std::cerr << "aperture: runtime did not produce a complete memory profile\n"; + return 1; + } + return 0; + } catch (const std::exception& error) { + std::cerr << "aperture: " << error.what() << '\n'; + return status != 0 ? status : 1; + } +#endif +} } // namespace aperture diff --git a/aperture/src/memory/memory_engine.hpp b/aperture/src/memory/memory_engine.hpp index e68e491e..95637e87 100644 --- a/aperture/src/memory/memory_engine.hpp +++ b/aperture/src/memory/memory_engine.hpp @@ -1,69 +1,25 @@ -// Aperture Memory — memory profiling engine -// Heap analysis, allocation tracing, leak detection. - +// Aperture records runtime memory measurements; it does not classify leaks. #pragma once -#include "core/aperture_core.hpp" +#include #include -#include namespace aperture { - -// A recorded allocation event -struct AllocationEvent { - size_t address; - size_t size; - std::string site; // call site (function:line) - std::string type; // allocated type - int generation = 0; // GC generation (if managed) - bool freed = false; -}; - -// A heap snapshot -struct HeapSnapshot { - int timestamp; // execution tick - size_t total_allocated; // bytes alive - size_t total_objects; // objects alive - size_t total_freed; // bytes freed since start - std::vector events; +struct MemoryOptions { + std::string target; + std::string report; + std::string output; + std::string tool_directory; + std::string memory_mode; + std::string sdk_path; + std::vector arguments; + bool json = false; + bool native = false; }; -// Memory analysis results -struct MemoryResult { - std::vector snapshots; - std::vector leaks; // unfreed allocations - std::map site_totals; // site -> total bytes allocated - double leak_ratio; // leaked bytes / total allocated -}; - -// Memory profiling engine class MemoryEngine { public: - MemoryEngine(); - ~MemoryEngine(); - - // Run memory profiling on a target - bool run(const std::string& target, bool json_output); - - // Capture a heap snapshot - HeapSnapshot capture(const std::string& target); - - // Detect memory leaks - std::vector detect_leaks(const std::string& target); - - // Export as structured JSON - std::string to_json(const MemoryResult& result); - -private: - // Trace allocations during execution - MemoryResult trace_allocations(const std::string& target); - - // Compare two snapshots - void diff_snapshots(const HeapSnapshot& before, const HeapSnapshot& after); - - // Identify allocation hotspots - std::vector> find_hotspots( - const std::vector& events); + // Return the target's exit status, or 1 when recording/report validation fails. + int run(const MemoryOptions& options); }; - } // namespace aperture diff --git a/docs/tools/index.md b/docs/tools/index.md index fe2bfbc4..af300eff 100644 --- a/docs/tools/index.md +++ b/docs/tools/index.md @@ -42,10 +42,17 @@ help/version identity. Aperture retains its own preview version. ## `aperture` -Aperture is the framework's analysis and debugging preview, with `explore`, -`memory`, `trace`, and `agent` commands. Run `aperture --help` for its command -interface. Its prototype capabilities are separate from the v1 language and -`nildebugger` contracts. See the [Aperture overview](../../aperture/README.md). +Aperture records runtime memory activity from Ny and Matrix programs. Use +`aperture memory --output memory.json example.matrix` for the interpreter or +add `--native` for native compilation and execution. Inspect a saved report with +`aperture memory --report memory.json`, optionally adding `--json`. + +Reports include allocated, freed, live and peak logical storage, allocation +sites, and GC activity within their stated accounting scope. They do not measure +process RSS or establish memory leaks. Recording currently requires a POSIX +host; saved-report inspection does not execute the target. Heap snapshots, +CPU tracing, code exploration and debugger integration remain planned. See the +[Aperture overview](../../aperture/README.md) for options and limitations. ## `nilbuild` diff --git a/matrix/docs/next-version-findings.md b/matrix/docs/next-version-findings.md index b1ed87aa..21431918 100644 --- a/matrix/docs/next-version-findings.md +++ b/matrix/docs/next-version-findings.md @@ -1714,3 +1714,56 @@ custom formatting and native FFI layout remain separate work from storing typed tuple handles. The VM still represents raw pointers as integers: a matching virtual address can establish a live allocation, but cannot establish the value's provenance. + +### F53 — Memory diagnostics need explicit accounting and capture boundaries + +**Observation:** Aperture's initial memory command returned placeholder +snapshots. Runtime allocation counts alone cannot establish leaks: retained +values may still be reachable, and VM values and native allocations have +different storage representations. A report taken after shutdown cleanup also +hides the storage developers need to investigate. + +**Resolution:** Opt-in sessions record real allocation, resize, release and GC +activity and finalize before runtime teardown. VM and native source execution +share the versioned `aperture.memory.v1` report contract, with source attribution, +completion status, explicit scope and bounded tracking. Counters obey +`allocated - freed = live`; peaks describe simultaneous live storage. Aperture +preserves target output and exit status, refuses to overwrite reports, and +rejects missing or malformed measurements. VS Code can run either route and +open the saved report. + +**Follow-up:** VM text, record and host-container storage remain outside this +first accounting scope. Native descriptor/capacity measurements differ from VM +payload bytes. Neither represents process RSS. Full call stacks, retention +graphs, allocation lifetimes, parallel-session aggregation, CPU sampling and +debugger snapshots need separate contracts. The first capture owns one runtime +session; restarting a paused VM must mark its old capture abandoned rather than +silently combining executions. See the [Aperture design](../../aperture/docs/DESIGN.md). + +### F54 — Native system-call arguments and console input still have route gaps + +**Observation:** Aperture's real-program qualification exposed two existing +native limitations. Importing `nil.std.system.*` and calling `exit(7)` passes +source checking and works in the interpreter, but direct native compilation +rejects the call with `std_sys.exit requires one i32 operand`. Writing +`exit(7 as i32)` qualifies the native boundary and preserves exit status 7 on +both routes. The source declaration already requires `i32`; an accepted literal +argument should acquire the same scalar representation as an explicitly cast +argument before native interop lowering. + +Separately, `nil.std.io.read_line()` works in the interpreter but native +compilation rejects its reachable `console.read_line` intrinsic as unsupported. +Both failures reproduce through direct native compilation with the SDK that +predates Aperture recording, so they are not profiling regressions. + +**Current handling:** Aperture passes program arguments without shell expansion +and keeps standard input attached to the target. Its contract tests exercise +space-containing and empty arguments on both routes, and line input on the VM. +Native console input is not claimed as supported. Explicitly typed `exit` +arguments qualify orderly exit profiling in both execution routes. + +**Follow-up:** Apply declared scalar parameter conversions consistently at native +interop calls, then add a paired literal/variable/explicit-cast contract. Add +native console line input with an explicit EOF, encoding and allocation-lifetime +contract, including memory-source attribution for the returned text. These are +language/runtime parity tasks rather than profiler-specific workarounds. diff --git a/nilcompiler/CMakeLists.txt b/nilcompiler/CMakeLists.txt index 0403c2e2..596c918a 100644 --- a/nilcompiler/CMakeLists.txt +++ b/nilcompiler/CMakeLists.txt @@ -47,6 +47,7 @@ set(NILCOMPILER_CORE_SOURCES # the static companion use the same implementation and versioned C ABI. add_library(nilruntime_objects OBJECT src/native_runtime.cpp + src/memory_profile.cpp src/owned_runtime.cpp src/secure_file_io.cpp src/database_runtime.cpp diff --git a/nilcompiler/src/llvm_backend.cpp b/nilcompiler/src/llvm_backend.cpp index 2fe4f4fa..d97601dd 100644 --- a/nilcompiler/src/llvm_backend.cpp +++ b/nilcompiler/src/llvm_backend.cpp @@ -2525,6 +2525,22 @@ bool NativeCodegen::generateModule(const nil_module &mod) { impl_->value_nil_types.clear(); impl_->label_map.clear(); + // Source capsules are opt-in; programs without them still identify the + // generated function and available line, without inventing a source path. + // The runtime makes this a no-op unless memory recording was requested. + const auto emit_profile_site = [&](const std::string &file, int line) { + auto *pointer = llvm::PointerType::getUnqual(ctx); + auto *word = llvm::Type::getInt64Ty(ctx); + auto site = impl_->module->getOrInsertFunction("nyrt_profile_site", + llvm::FunctionType::get(llvm::Type::getVoidTy(ctx), + {pointer, pointer, word}, false)); + impl_->builder->CreateCall(site, + {impl_->builder->CreateGlobalString(file), + impl_->builder->CreateGlobalString(fn.name), + llvm::ConstantInt::get(word, std::max(0, line))}); + }; + emit_profile_site(fn.source_file, fn.source_line); + struct NativeStructInitialization { const nil_struct_def *definition = nullptr; }; @@ -3945,6 +3961,28 @@ bool NativeCodegen::generateModule(const nil_module &mod) { return false; } + // Builtins dispatched directly from a call can allocate in the runtime; + // publish their call site as well as explicit allocating instructions. + switch (op) { + case Opcode::ALLOC: + case Opcode::OWN_ALLOC: + case Opcode::NEW_ARRAY: + case Opcode::NEW_ARRAY_LITERAL: + case Opcode::NEW_STRUCT: + case Opcode::NEW_VARIANT: + case Opcode::STR_CONCAT: + case Opcode::TO_STRING: + case Opcode::CALL: + case Opcode::CALL_METHOD: + case Opcode::INTEROP_CALL: + case Opcode::PARALLEL_MAP: + emit_profile_site(minstr.source_file.empty() ? fn.source_file : minstr.source_file, + minstr.debug_line); + break; + default: + break; + } + switch (op) { case Opcode::PUSH_CONST: if (!minstr.args.empty()) { @@ -8415,6 +8453,7 @@ int NativeCodegen::executeJIT(const std::vector &program_args) { expose_runtime_symbol("nyrt_owned_v1_unwind", &nyrt_owned_v1_unwind); expose_runtime_symbol("nyrt_context_begin", &nyrt_context_begin); expose_runtime_symbol("nyrt_context_end", &nyrt_context_end); + expose_runtime_symbol("nyrt_profile_site", &nyrt_profile_site); expose_runtime_symbol("nyrt_roots_enter", &nyrt_roots_enter); expose_runtime_symbol("nyrt_roots_leave", &nyrt_roots_leave); expose_runtime_symbol("nyrt_safepoint", &nyrt_safepoint); diff --git a/nilcompiler/src/memory_profile.cpp b/nilcompiler/src/memory_profile.cpp new file mode 100644 index 00000000..07510d2b --- /dev/null +++ b/nilcompiler/src/memory_profile.cpp @@ -0,0 +1,296 @@ +#include "memory_profile.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef _WIN32 +#include +#include +#include +#else +#include +#include +#endif + +namespace ny::memory_profile { +namespace { +constexpr std::size_t maximum_sites = 4096; +constexpr std::size_t maximum_live_objects = 1024 * 1024; +std::atomic capture_claimed{false}; +std::atomic excluded_sessions{0}; + +void diagnostic(const char *message) noexcept { + std::fprintf(stderr, "Aperture memory profile error: %s\n", message); + std::fflush(stderr); +} + +void add(std::uint64_t &value, std::uint64_t amount) noexcept { + value += std::min(amount, (std::numeric_limits::max)() - value); +} + +struct Counters { + std::uint64_t allocated_bytes = 0, allocated_objects = 0; + std::uint64_t live_bytes = 0, live_objects = 0; + std::uint64_t peak_bytes = 0, peak_objects = 0; + std::uint64_t freed_bytes = 0, freed_objects = 0, resizes = 0; + void increase(std::uint64_t bytes, bool object) noexcept { + add(allocated_bytes, bytes); + add(live_bytes, bytes); + if (object) { add(allocated_objects, 1); add(live_objects, 1); } + peak_bytes = std::max(peak_bytes, live_bytes); + peak_objects = std::max(peak_objects, live_objects); + } + void decrease(std::uint64_t bytes, bool object) noexcept { + add(freed_bytes, bytes); + live_bytes -= std::min(live_bytes, bytes); + if (object) { add(freed_objects, 1); if (live_objects) --live_objects; } + } +}; + +// Escape arbitrary bytes as valid JSON. UTF-8 remains readable; malformed +// UTF-8 is escaped byte-by-byte, rather than emitting an invalid document. +void quoted(std::FILE *file, std::string_view value) noexcept { + std::fputc('"', file); + for (std::size_t i = 0; i < value.size(); ++i) { + const auto ch = static_cast(value[i]); + if (ch == '"' || ch == '\\') { std::fputc('\\', file); std::fputc(ch, file); } + else if (ch < 0x20 || ch == 0x7f) std::fprintf(file, "\\u%04x", ch); + else if (ch < 0x80) std::fputc(ch, file); + else { + const std::size_t width = ch >= 0xc2 && ch <= 0xdf ? 2 : + ch >= 0xe0 && ch <= 0xef ? 3 : ch >= 0xf0 && ch <= 0xf4 ? 4 : 0; + bool valid = width != 0 && width <= value.size() - i; + for (std::size_t j = 1; valid && j < width; ++j) { + const auto next = static_cast(value[i + j]); + valid = next >= 0x80 && next <= 0xbf; + } + if (valid && width >= 3) { + const auto next = static_cast(value[i + 1]); + valid = !((ch == 0xe0 && next < 0xa0) || (ch == 0xed && next >= 0xa0) || + (ch == 0xf0 && next < 0x90) || (ch == 0xf4 && next >= 0x90)); + } + if (valid) { std::fwrite(value.data() + i, 1, width, file); i += width - 1; } + else std::fprintf(file, "\\u%04x", ch); + } + } + std::fputc('"', file); +} + +void counters(std::FILE *file, const Counters &value) noexcept { + std::fprintf(file, + "\"allocated_bytes\":%llu,\"allocated_objects\":%llu," + "\"live_bytes\":%llu,\"live_objects\":%llu," + "\"peak_bytes\":%llu,\"peak_objects\":%llu," + "\"freed_bytes\":%llu,\"freed_objects\":%llu,\"resizes\":%llu", + static_cast(value.allocated_bytes), + static_cast(value.allocated_objects), + static_cast(value.live_bytes), + static_cast(value.live_objects), + static_cast(value.peak_bytes), + static_cast(value.peak_objects), + static_cast(value.freed_bytes), + static_cast(value.freed_objects), + static_cast(value.resizes)); +} + +std::FILE *reserve_file(const char *path) noexcept { +#ifdef _WIN32 + const int descriptor = ::_open(path, _O_WRONLY | _O_CREAT | _O_EXCL | _O_BINARY, + _S_IREAD | _S_IWRITE); + if (descriptor < 0) return nullptr; + auto *file = ::_fdopen(descriptor, "wb"); + if (!file) ::_close(descriptor); +#else + const int descriptor = ::open(path, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC | O_NOFOLLOW, 0600); + if (descriptor < 0) return nullptr; + auto *file = ::fdopen(descriptor, "wb"); + if (!file) ::close(descriptor); +#endif + return file; +} +} // namespace + +struct Session::State { + using Key = std::tuple; + struct Site { Key key; Counters counts; }; + struct Allocation { std::size_t site; std::uint64_t bytes; }; + std::FILE *file = nullptr; + bool active = true, failed = false, site_limit_reached = false; + const char *error = nullptr; + std::string route, current_file, current_function; + std::uint64_t current_line = 0; + Counters totals; + std::uint64_t collections = 0, collection_ns = 0, collected_bytes = 0, collected_objects = 0; + std::vector sites; + std::map site_index; + std::unordered_map allocations; + + void fail(const char *message) noexcept { + if (!failed) diagnostic(message); + failed = true; + error = message; + } + std::size_t current_site(std::string_view kind) { + Key key{current_file, current_function, current_line, std::string(kind.substr(0, 64))}; + auto found = site_index.find(key); + if (found != site_index.end()) return found->second; + if (sites.size() >= maximum_sites) { + site_limit_reached = true; + key = Key{"", "", 0, "other"}; + found = site_index.find(key); + if (found != site_index.end()) return found->second; + } + const auto index = sites.size(); + site_index.emplace(key, index); + sites.push_back({std::move(key), {}}); + return index; + } +}; + +Session::Session() noexcept = default; +Session::~Session() { (void)finish("abandoned", false); } + +bool Session::begin(std::string_view route) noexcept { + if (state_ && state_->active) return true; + const char *path = std::getenv("NIL_MEMORY_PROFILE"); + if (!path || !*path) return true; + if (capture_claimed.exchange(true)) { ++excluded_sessions; return true; } + try { + state_ = std::make_unique(); + state_->route = std::string(route.substr(0, 64)); + state_->file = reserve_file(path); + if (!state_->file) { + state_->active = false; + diagnostic("could not create capture destination (it must be a new writable file)"); + return false; + } + return true; + } catch (...) { + if (state_) state_->active = false; + diagnostic("could not initialize capture state"); + return false; + } +} + +bool Session::enabled() const noexcept { return state_ && state_->active; } + +void Session::site(std::string_view file, std::string_view function, std::uint64_t line) noexcept { + if (!enabled() || state_->failed) return; + try { + state_->current_file.assign(file.substr(0, 4096)); + state_->current_function.assign(function.substr(0, 1024)); + state_->current_line = line; + } catch (...) { state_->fail("could not retain source attribution"); } +} + +void Session::allocate(const void *identity, std::uint64_t bytes, std::string_view kind) noexcept { + if (!enabled() || state_->failed || !identity) return; + try { + if (state_->allocations.size() >= maximum_live_objects) { + state_->fail("capture exceeded the live allocation tracking limit"); return; + } + if (state_->allocations.find(identity) != state_->allocations.end()) { + state_->fail("duplicate live allocation identity"); return; + } + const auto maximum = (std::numeric_limits::max)(); + if (bytes > maximum - state_->totals.allocated_bytes || + state_->totals.allocated_objects == maximum) { + state_->fail("capture counters exceeded their representable range"); return; + } + const auto site = state_->current_site(kind); + state_->allocations.emplace(identity, State::Allocation{site, bytes}); + state_->totals.increase(bytes, true); + state_->sites[site].counts.increase(bytes, true); + } catch (...) { state_->fail("could not retain allocation event"); } +} + +void Session::resize(const void *identity, std::uint64_t bytes) noexcept { + if (!enabled() || state_->failed) return; + const auto found = state_->allocations.find(identity); + if (found == state_->allocations.end()) return; + auto &allocation = found->second; + auto &site = state_->sites[allocation.site].counts; + if (bytes >= allocation.bytes && bytes - allocation.bytes > + (std::numeric_limits::max)() - state_->totals.allocated_bytes) { + state_->fail("capture counters exceeded their representable range"); return; + } + add(state_->totals.resizes, 1); add(site.resizes, 1); + if (bytes >= allocation.bytes) { + state_->totals.increase(bytes - allocation.bytes, false); + site.increase(bytes - allocation.bytes, false); + } else { + state_->totals.decrease(allocation.bytes - bytes, false); + site.decrease(allocation.bytes - bytes, false); + } + allocation.bytes = bytes; +} + +void Session::release(const void *identity) noexcept { + if (!enabled() || state_->failed) return; + const auto found = state_->allocations.find(identity); + if (found == state_->allocations.end()) return; + state_->totals.decrease(found->second.bytes, true); + state_->sites[found->second.site].counts.decrease(found->second.bytes, true); + state_->allocations.erase(found); +} + +void Session::collection(std::uint64_t duration_ns, std::uint64_t freed_bytes, + std::uint64_t freed_objects) noexcept { + if (!enabled() || state_->failed) return; + add(state_->collections, 1); add(state_->collection_ns, duration_ns); + add(state_->collected_bytes, freed_bytes); add(state_->collected_objects, freed_objects); +} + +bool Session::finish(std::string_view status, bool completed) noexcept { + if (!enabled()) return true; + auto &state = *state_; + state.active = false; + auto *file = state.file; + state.file = nullptr; + std::fputs("{\"schema\":\"aperture.memory.v1\",\"route\":", file); + quoted(file, state.route); + std::fprintf(file, ",\"completed\":%s,\"status\":", completed && !state.failed ? "true" : "false"); + quoted(file, state.failed ? std::string_view("profile_error") : status); + std::fputs(",\"measurement\":\"runtime_logical_bytes\",\"totals\":{", file); + counters(file, state.totals); + std::fprintf(file, "},\"collections\":{\"count\":%llu,\"duration_ns\":%llu,\"freed_bytes\":%llu,\"freed_objects\":%llu},\"sites\":[", + static_cast(state.collections), static_cast(state.collection_ns), + static_cast(state.collected_bytes), static_cast(state.collected_objects)); + for (std::size_t i = 0; i < state.sites.size(); ++i) { + const auto &site = state.sites[i]; + if (i) std::fputc(',', file); + std::fputs("{\"file\":", file); quoted(file, std::get<0>(site.key)); + std::fputs(",\"function\":", file); quoted(file, std::get<1>(site.key)); + std::fprintf(file, ",\"line\":%llu,\"kind\":", static_cast(std::get<2>(site.key))); + quoted(file, std::get<3>(site.key)); std::fputc(',', file); counters(file, site.counts); std::fputc('}', file); + } + std::fprintf(file, "],\"excluded_sessions\":%llu,\"site_limit_reached\":%s,\"scope\":[", + static_cast(excluded_sessions.load()), state.site_limit_reached ? "true" : "false"); + quoted(file, "Live allocations are a snapshot before runtime teardown; retained does not mean leaked."); + std::fputc(',', file); quoted(file, "Runtime logical accounting is not process RSS; allocator overhead, external libraries and profiler storage are excluded."); + std::fputc(',', file); quoted(file, "Only the first opted-in runtime session is captured; parallel workers and later sessions are excluded."); + std::fputc(',', file); quoted(file, "Source sites are bounded to 4096 distinct entries plus an overflow entry; growth remains attributed to the original allocation site."); + std::fputc(',', file); + if (state.route == "vm") + quoted(file, "VM coverage is typed array, raw buffer and iterator payload bytes; Value storage, vector capacity, maps, text and record storage are excluded."); + else + quoted(file, "Native coverage is runtime-managed allocations, array descriptors/capacity and runtime buffer descriptors/guards; unmanaged instructions that allocate directly through libc are excluded. Logically freed buffer tombstones are excluded even while retained for stale-pointer protection."); + std::fputs("],\"errors\":[", file); + if (state.error) quoted(file, state.error); + std::fputs("]}\n", file); + bool ok = std::ferror(file) == 0; + if (std::fclose(file) != 0) ok = false; + if (!ok) diagnostic("could not finish writing capture destination"); + return ok && !state.failed; +} +} // namespace ny::memory_profile diff --git a/nilcompiler/src/memory_profile.hpp b/nilcompiler/src/memory_profile.hpp new file mode 100644 index 00000000..c46cc3a0 --- /dev/null +++ b/nilcompiler/src/memory_profile.hpp @@ -0,0 +1,42 @@ +#ifndef NIL_MEMORY_PROFILE_HPP +#define NIL_MEMORY_PROFILE_HPP + +#include +#include +#include + +namespace ny::memory_profile { + +// A capture owns one runtime invocation, not the process allocator. No +// allocation addresses or language values are serialized. The first opted-in +// session in a process owns the capture; other sessions remain uninstrumented. +class Session { +public: + Session() noexcept; + ~Session(); + Session(const Session &) = delete; + Session &operator=(const Session &) = delete; + + // NIL_MEMORY_PROFILE is a new destination path. Existing files are never + // truncated, including symlinks. False means an explicit capture error. + bool begin(std::string_view route) noexcept; + bool enabled() const noexcept; + void site(std::string_view file, std::string_view function, + std::uint64_t line) noexcept; + void allocate(const void *identity, std::uint64_t bytes, + std::string_view kind) noexcept; + void resize(const void *identity, std::uint64_t bytes) noexcept; + void release(const void *identity) noexcept; + void collection(std::uint64_t duration_ns, std::uint64_t freed_bytes, + std::uint64_t freed_objects) noexcept; + // Snapshot before runtime teardown. Live values are retained, not proven + // leaks. On failure a diagnostic is emitted and false is returned. + bool finish(std::string_view status = "completed", bool completed = true) noexcept; + +private: + struct State; + std::unique_ptr state_; +}; + +} // namespace ny::memory_profile +#endif diff --git a/nilcompiler/src/native_runtime.cpp b/nilcompiler/src/native_runtime.cpp index c1fc3171..37941917 100644 --- a/nilcompiler/src/native_runtime.cpp +++ b/nilcompiler/src/native_runtime.cpp @@ -1,6 +1,7 @@ #include "native_runtime.hpp" #include "database_runtime.hpp" #include "integer_conversion.hpp" +#include "memory_profile.hpp" #include "scalar_text.hpp" #include "secure_file_io.hpp" @@ -11,6 +12,7 @@ #include #include #include +#include #include #include #include @@ -65,6 +67,7 @@ struct nyrt_buffer { }; struct runtime_context { + ny::memory_profile::Session profile; ny::database::Context databases; struct allocation { void *data; @@ -342,6 +345,7 @@ nyrt_array *make_array(std::uint32_t kind, std::uint64_t length) noexcept { context.arrays.push_back(std::move(array)); account_managed_bytes(byte_count); account_managed_bytes(sizeof(nyrt_array)); + context.profile.allocate(result, sizeof(nyrt_array) + byte_count, "array"); } catch (...) { return nullptr; } @@ -373,13 +377,15 @@ void *make_buffer(std::uint32_t kind, std::uint64_t length) noexcept { void *result = buffer->data; try { context.buffers.push_back(std::move(buffer)); + context.profile.allocate(context.buffers.back().get(), sizeof(nyrt_buffer) + storage_bytes, "buffer"); } catch (...) { return nullptr; } return result; } -void *allocate_owned(std::uint64_t requested_size) noexcept { +void *allocate_owned(std::uint64_t requested_size, + std::string_view kind = "managed") noexcept { std::uint64_t size_limit = std::numeric_limits::max(); if constexpr (sizeof(std::size_t) <= sizeof(std::uint64_t)) { size_limit = @@ -396,6 +402,7 @@ void *allocate_owned(std::uint64_t requested_size) noexcept { try { context.allocations.push_back({storage, size}); account_managed_bytes(size); + context.profile.allocate(storage, size, kind); } catch (...) { std::free(storage); return nullptr; @@ -407,7 +414,7 @@ const char *own_string(std::string_view value) noexcept { if (value.size() == std::numeric_limits::max()) return nullptr; auto *storage = static_cast( - allocate_owned(static_cast(value.size()) + 1U)); + allocate_owned(static_cast(value.size()) + 1U, "text")); if (storage == nullptr) return nullptr; if (!value.empty()) @@ -520,6 +527,7 @@ bool reserve(nyrt_array &array, std::uint64_t capacity) noexcept { array.capacity = capacity; account_managed_bytes(byte_count - array.allocated_bytes); array.allocated_bytes = byte_count; + context.profile.resize(&array, sizeof(nyrt_array) + byte_count); return true; } @@ -669,6 +677,8 @@ void *nyrt_parallel_map_v1(const void *inputs, std::uint32_t input_kind, void nyrt_context_begin(int argc, const char *const *argv) noexcept { nyrt_context_end(); + if (!context.profile.begin("native")) + nyrt_fail("NIL native runtime error: could not start memory capture\n"); if (argc < 0 || (argc > 0 && argv == nullptr)) nyrt_fail("NIL native runtime error: invalid process argument vector\n"); if (argc == 0) @@ -678,6 +688,7 @@ void nyrt_context_begin(int argc, const char *const *argv) noexcept { for (int index = 0; index < argc; ++index) context.arguments.emplace_back(argv[index] == nullptr ? "" : argv[index]); } catch (...) { + (void)context.profile.finish("failed", false); nyrt_context_end(); nyrt_fail("NIL native runtime error: could not initialize process " "arguments\n"); @@ -685,6 +696,9 @@ void nyrt_context_begin(int argc, const char *const *argv) noexcept { } void nyrt_context_end() noexcept { + // Capture application retention before invocation-owned storage is torn down. + if (!context.profile.finish()) + nyrt_fail("NIL native runtime error: memory capture failed\n"); context.databases.clear(); nyrt_owned_v1_unwind(0); context.pending_fault.reset(); @@ -700,7 +714,13 @@ void nyrt_context_end() noexcept { std::vector().swap(context.arguments); } +void nyrt_profile_site(const char *file, const char *function, + std::uint64_t line) noexcept { + context.profile.site(file ? file : "", function ? function : "", line); +} + [[noreturn]] void nyrt_fail(const char *message) noexcept { + (void)context.profile.finish("failed", false); if (message != nullptr) std::fputs(message, stderr); std::fflush(nullptr); @@ -757,6 +777,7 @@ std::int32_t nyrt_free(void *pointer) noexcept { context.allocations.end(), [pointer](const auto &item) { return item.data == pointer; }); if (allocation == context.allocations.end()) return 0; + context.profile.release(allocation->data); std::free(allocation->data); context.allocations.erase(allocation); return 1; @@ -902,6 +923,8 @@ void nyrt_fault_v1_report_uncaught() noexcept { } std::fprintf(stderr, " at line %lld\n", static_cast(fault.line)); std::fflush(stderr); + if (!context.profile.finish("failed", false)) + nyrt_fail("NIL native runtime error: memory capture failed\n"); } std::uint64_t nyrt_managed_bytes() noexcept { @@ -920,6 +943,11 @@ void nyrt_collect() noexcept { // Uninstrumented embedding and older SDK objects keep their historical // invocation lifetime. Never guess at arbitrary C/C++ machine-stack roots. if (context.frames.empty()) return; + const bool profiling = context.profile.enabled(); + const auto collection_start = profiling ? std::chrono::steady_clock::now() + : std::chrono::steady_clock::time_point{}; + const auto bytes_before = profiling ? nyrt_managed_bytes() : 0; + const auto objects_before = profiling ? nyrt_managed_objects() : 0; try { struct object { void *data; @@ -990,12 +1018,23 @@ void nyrt_collect() noexcept { context.allocations.erase(std::remove_if(context.allocations.begin(), context.allocations.end(), [&](const auto &item) { if (live(item.data)) return false; + context.profile.release(item.data); std::free(item.data); return true; }), context.allocations.end()); context.arrays.erase(std::remove_if(context.arrays.begin(), context.arrays.end(), - [&](const auto &item) { return !live(item.get()); }), context.arrays.end()); + [&](const auto &item) { + if (live(item.get())) return false; + context.profile.release(item.get()); + return true; + }), context.arrays.end()); context.allocated_since_collection = 0; + if (profiling) { + const auto elapsed = std::chrono::duration_cast( + std::chrono::steady_clock::now() - collection_start).count(); + context.profile.collection(static_cast(std::max(elapsed, 0)), + bytes_before - nyrt_managed_bytes(), objects_before - nyrt_managed_objects()); + } } catch (...) { // All tracing allocations precede sweep. An exhausted tracing workspace // must preserve the heap, never turn a partial mark into reclamation. @@ -1026,6 +1065,8 @@ const char *nyrt_arg(std::int64_t index) noexcept { if (code < 0 || code > 255) nyrt_fail("NIL native runtime error: std_sys.exit: code must be between 0 " "and 255\n"); + if (!context.profile.finish("exited", true)) + nyrt_fail("NIL native runtime error: memory capture failed\n"); std::fflush(nullptr); std::exit(static_cast(code)); } @@ -1137,6 +1178,7 @@ std::int32_t nyrt_buffer_free(void *value) noexcept { // Retain the allocation as an inactive tombstone until context teardown. // Its address therefore cannot be reused to make a stale pointer valid. candidate->active = false; + context.profile.release(candidate.get()); return 1; } return 0; @@ -1148,6 +1190,7 @@ std::int32_t nyrt_owned_buffer_release(void *value) noexcept { const auto &candidate = *item; if (candidate->data == value && candidate->active && checked_buffer(value, candidate->kind) == candidate.get()) { + context.profile.release(candidate.get()); context.buffers.erase(item); return 1; } diff --git a/nilcompiler/src/native_runtime.hpp b/nilcompiler/src/native_runtime.hpp index 6bd3d0ca..c7544748 100644 --- a/nilcompiler/src/native_runtime.hpp +++ b/nilcompiler/src/native_runtime.hpp @@ -48,6 +48,10 @@ void nyrt_parallel_fail_v1(const char *message) noexcept; std::int32_t nyrt_parallel_failed_v1() noexcept; void nyrt_context_begin(int argc, const char *const *argv) noexcept; void nyrt_context_end() noexcept; +// Additive opt-in profiling attribution. Source strings are copied only during +// NIL_MEMORY_PROFILE captures; line zero/file empty mean unavailable. +void nyrt_profile_site(const char *file, const char *function, + std::uint64_t line) noexcept; [[noreturn]] void nyrt_fail(const char *message) noexcept; // Native text is NUL-free, byte-indexed UTF-8 storage. Substring clamps a // negative start/count to zero and clips count to the remaining byte length. diff --git a/nilcompiler/src/vm.cpp b/nilcompiler/src/vm.cpp index feaa9b86..0f1bd766 100644 --- a/nilcompiler/src/vm.cpp +++ b/nilcompiler/src/vm.cpp @@ -692,6 +692,21 @@ int64_t invoke_native(void *fn_ptr, const std::vector &args) { VM::VM() : pc_(0) {} +void VM::beginMemoryProfile() { + if (memory_profile_started_ || !memory_profile_allowed_) + return; + memory_profile_started_ = true; + if (!memory_profile_.begin("vm")) + throw std::runtime_error("Could not start Aperture memory profile"); +} + +bool VM::finishMemoryProfile(const char *status, bool completed) noexcept { + if (!memory_profile_started_ || memory_profile_finished_) + return true; + memory_profile_finished_ = true; + return memory_profile_.finish(status, completed); +} + std::istream &VM::inputStream() { return input_stream_ ? *input_stream_ : std::cin; } @@ -703,6 +718,10 @@ std::ostream &VM::outputStream() { void VM::resetRuntimeState(const std::string &root_function) { // Configuration belongs to the host and survives a restart. Everything that // can be observed or owned by the Ny program belongs to one invocation. + // A restart abandons a paused invocation; it must not combine its allocation + // history with the next run or count teardown as program releases. + if (!finishMemoryProfile("abandoned", false)) + throw std::runtime_error("Could not finish Aperture memory profile"); unwindOwned(0); databases_.clear(); file_handles_.clear(); @@ -790,12 +809,17 @@ bool VM::stepInstruction() try { validateInstructionLocation(); if (pc_ >= program_.size()) return false; + beginMemoryProfile(); executeInstruction(program_[pc_]); ++pc_; validateInstructionLocation(); debug_state_ = DebugState::PAUSED; + if (pc_ >= program_.size() && + !finishMemoryProfile("completed", true)) + throw std::runtime_error("Could not finish Aperture memory profile"); return pc_ < program_.size(); } catch (...) { + (void)finishMemoryProfile("failed", false); unwindOwned(0); throw; } @@ -811,6 +835,7 @@ std::vector VM::getDebugFrames() const { } void VM::execute(bool reset) try { + beginMemoryProfile(); if (reset) { // Preserve the historical embedding contract: callers may load a program, // inject globals with setGlobal(), and then use execute(true). A debugger @@ -859,6 +884,11 @@ void VM::execute(bool reset) try { ++pc_; validateInstructionLocation(); debug_state_ = DebugState::PAUSED; + if (pc_ >= program_.size()) { + if (!finishMemoryProfile("completed", true)) + throw std::runtime_error("Could not finish Aperture memory profile"); + return; + } bool should_continue = false; if (debug_callback_) { // Callback with NEXT instruction (if valid) @@ -875,14 +905,21 @@ void VM::execute(bool reset) try { ++pc_; validateInstructionLocation(); } + if (!finishMemoryProfile("completed", true)) + throw std::runtime_error("Could not finish Aperture memory profile"); } catch (...) { + (void)finishMemoryProfile("failed", false); unwindOwned(0); throw; } void VM::executeInstruction(const Instruction &instr) { + if (memory_profile_.enabled()) + memory_profile_.site(instr.source_file, + call_stack_.empty() ? "" : call_stack_.back().fn_name, + instr.line > 0 ? static_cast(instr.line) : 0); if (pending_fault_ && instr.op != Opcode::LABEL && instr.op != Opcode::FAULT_SAVE) throw std::runtime_error("pending fault must be saved before ordinary execution"); const auto is_array_value = [](const Value &value) { @@ -1544,6 +1581,10 @@ void VM::executeInstruction(const Instruction &instr) { it->second.data.push_back( canonical_pointer_value(it->second, args[1], "array__push")); it->second.element_count++; + if (memory_profile_.enabled()) + memory_profile_.resize( + reinterpret_cast(static_cast(handle)), + profileHeapBlockBytes(it->second)); } } // A void call has no operand-stack result. @@ -2923,7 +2964,9 @@ void VM::executeInstruction(const Instruction &instr) { pc_ = program_.size(); return; } - std::exit(code); + // std::exit bypasses VM destruction. Preserve the retained heap before + // leaving, while keeping the program's requested status on success. + std::exit(finishMemoryProfile("completed", true) ? code : 1); } else if (fn_name == "arg_count") { if (!args.empty()) throw std::runtime_error("std_sys.arg_count: expected no arguments"); @@ -5472,6 +5515,10 @@ void VM::executeInstruction(const Instruction &instr) { workers.reserve(slots); for (std::size_t index = 0; index < slots; ++index) { auto worker = std::make_unique(); + // A scalar worker is part of the parent invocation, never a separate + // report owner. Worker implementation allocations are outside VM heap + // block coverage; the parent records the resulting array below. + worker->memory_profile_allowed_ = false; worker->setMemoryMode(memory_mode_); worker->setProcessExitTrapping(true); worker->loadProgram(program_, constants_); @@ -6006,7 +6053,7 @@ void VM::executeInstruction(const Instruction &instr) { int64_t ptr = std::get(ptr_val); auto it = heap_.find(ptr); if (it != heap_.end()) { - heap_.erase(it); + releaseHeapBlock(ptr); } else { std::cerr << "[nilinterpreter] FREE: invalid pointer " << ptr << std::endl; @@ -6208,7 +6255,7 @@ void VM::unwindOwned(std::size_t depth) { while (owned_scopes_.size() > depth) { const auto &scope = owned_scopes_.back(); for (const auto &slot : scope.slots) { - heap_.erase(slot.second); + releaseHeapBlock(slot.second); if (scope.frame_depth > 0 && scope.frame_depth <= call_stack_.size()) call_stack_[scope.frame_depth - 1].locals[slot.first] = int64_t(0); } @@ -6407,6 +6454,44 @@ std::uint64_t VM::currentHeapBytes() const { return total; } +std::uint64_t VM::profileHeapBlockBytes(const HeapBlock &block) const { + // These are language-visible payload bytes, not the host's sizeof(Value), + // vector capacity, allocator overhead, or transitive string/record storage. + // Keep profiling independent of the historical gc.allocated_bytes metric. + auto stride = heap_element_stride(block.type_name); + if (block.type_name == "array") { + const auto element = canonical_array_type(block.element_type); + stride = element == "i32" || element == "f32" ? 4 + : element == "bool" || element == "u8" ? 1 + : 8; + } + const auto maximum = std::numeric_limits::max(); + const auto bytes = static_cast(block.byte_data.size()); + const auto count = static_cast(block.data.size()); + if (count > (maximum - bytes) / stride) + return maximum; + return count * stride + bytes; +} + +std::uint64_t VM::profileHeapBytes() const { + const auto maximum = std::numeric_limits::max(); + std::uint64_t total = 0; + for (const auto &[pointer, block] : heap_) { + (void)pointer; + const auto bytes = profileHeapBlockBytes(block); + if (bytes > maximum - total) + return maximum; + total += bytes; + } + return total; +} + +void VM::releaseHeapBlock(int64_t pointer) { + if (heap_.erase(pointer)) + memory_profile_.release( + reinterpret_cast(static_cast(pointer))); +} + void VM::storeHeapBlock(int64_t pointer, HeapBlock block) { const std::uint64_t bytes = heapBlockBytes(block); const std::uint64_t observable_limit = @@ -6417,6 +6502,17 @@ void VM::storeHeapBlock(int64_t pointer, HeapBlock block) { else total_allocated_bytes_ += bytes; heap_[pointer] = std::move(block); + if (memory_profile_.enabled()) { + const auto &stored = heap_.at(pointer); + const auto kind = stored.type_name == "array" + ? "array<" + stored.element_type + ">" + : stored.type_name == "__iter" ? std::string("iterator") + : (pc_ < program_.size() && program_[pc_].op == Opcode::OWN_ALLOC + ? "owned_buffer<" : "buffer<") + stored.type_name + ">"; + memory_profile_.allocate( + reinterpret_cast(static_cast(pointer)), + profileHeapBlockBytes(stored), kind); + } } void VM::gcCollect() { @@ -6424,6 +6520,12 @@ void VM::gcCollect() { return; // Only run GC in safe mode } + const bool profiling = memory_profile_.enabled(); + const auto profile_bytes_before = profiling ? profileHeapBytes() : 0; + const auto profile_objects_before = heap_.size(); + const auto profile_start = profiling ? std::chrono::steady_clock::now() + : std::chrono::steady_clock::time_point{}; + // Reset all marks for (auto &[ptr, block] : heap_) { (void)ptr; @@ -6442,6 +6544,14 @@ void VM::gcCollect() { if (total_collections_ < static_cast(std::numeric_limits::max())) ++total_collections_; + if (profiling) { + const auto elapsed = std::chrono::duration_cast( + std::chrono::steady_clock::now() - profile_start).count(); + memory_profile_.collection( + elapsed > 0 ? static_cast(elapsed) : 0, + profile_bytes_before - std::min(profile_bytes_before, profileHeapBytes()), + profile_objects_before - heap_.size()); + } } void VM::gcMarkRoots() { @@ -6551,7 +6661,7 @@ void VM::gcSweep() { } for (int64_t ptr : to_free) { - heap_.erase(ptr); + releaseHeapBlock(ptr); } } diff --git a/nilcompiler/src/vm.hpp b/nilcompiler/src/vm.hpp index 04a4cd1f..80e229e3 100644 --- a/nilcompiler/src/vm.hpp +++ b/nilcompiler/src/vm.hpp @@ -16,6 +16,7 @@ #include #include "source_debug.hpp" #include "database_runtime.hpp" +#include "memory_profile.hpp" namespace ny { @@ -485,6 +486,19 @@ class VM { std::uint64_t gc_critical_depth_ = 0; std::unordered_set gc_marked_structs_; + // One capture belongs to the VM's first execution. It is finalized while + // heap blocks are still live, so retained bytes describe the program at its + // execution boundary rather than the VM destructor's housekeeping. + memory_profile::Session memory_profile_; + bool memory_profile_started_ = false; + bool memory_profile_finished_ = false; + bool memory_profile_allowed_ = true; + void beginMemoryProfile(); + bool finishMemoryProfile(const char *status, bool completed) noexcept; + std::uint64_t profileHeapBlockBytes(const HeapBlock &block) const; + std::uint64_t profileHeapBytes() const; + void releaseHeapBlock(int64_t pointer); + // Interpreter-owned streams never expose host descriptors to Ny code. A // monotonically increasing token indexes the stream and its access rights; // dropping the VM closes every remaining stream through RAII. diff --git a/tests/tools/aperture_memory_contract.py b/tests/tools/aperture_memory_contract.py new file mode 100644 index 00000000..577fe7a0 --- /dev/null +++ b/tests/tools/aperture_memory_contract.py @@ -0,0 +1,290 @@ +#!/usr/bin/env python3 +"""Aperture records real VM/native memory activity without changing program output.""" +from __future__ import annotations + +import argparse +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--aperture', required=True, type=Path) + parser.add_argument('--compiler', required=True, type=Path) + parser.add_argument('--interpreter', required=True, type=Path) + parser.add_argument('--stdlib', required=True, type=Path) + parser.add_argument('--llvm', choices=('ON', 'OFF'), default='OFF') + args = parser.parse_args() + aperture, compiler, interpreter, stdlib = (p.resolve() for p in + (args.aperture, args.compiler, args.interpreter, args.stdlib)) + environment = {key: value for key, value in os.environ.items() + if not key.startswith(('NIL_', 'NY_'))} + checks = 0 + with tempfile.TemporaryDirectory(prefix='aperture memory contract ') as directory: + root = Path(directory) + + def run(command, status=0, env=None, input_text=None): + nonlocal checks + result = subprocess.run(list(map(str, command)), cwd=root, + env=environment if env is None else env, + stdin=subprocess.DEVNULL if input_text is None else None, + input=input_text, capture_output=True, + text=True, timeout=120) + assert result.returncode == status, (command, result.returncode, + result.stdout, result.stderr) + checks += 1 + return result + + def validate(path, route, source=None): + nonlocal checks + profile = json.loads(path.read_text()) + assert profile['schema'] == 'aperture.memory.v1', profile + assert profile['route'] == route, profile + assert profile['completed'] and not profile['errors'], profile + assert profile['measurement'] == 'runtime_logical_bytes', profile + totals = profile['totals'] + assert totals['allocated_bytes'] > 0 and totals['allocated_objects'] > 0, profile + for values in [totals, *profile['sites']]: + for units in ('bytes', 'objects'): + assert values['allocated_' + units] - values['freed_' + units] == values['live_' + units], values + assert values['allocated_' + units] >= values['peak_' + units] >= values['live_' + units], values + if source: + assert any(site['file'] == str(source) and site['line'] > 0 and 'main' in site['function'] + for site in profile['sites']), profile['sites'] + checks += 1 + return profile + + # Metacharacters are literal path components. A shell command assembled + # from this path would attempt to create an unexpected marker file. + source = root / 'memory $(touch INJECTED) source.ny' + source.write_text('''fn main() -> i32 + let pointer = allocate(1) + pointer[0] = 42 + println(pointer[0]) + deallocate(pointer) + let values: array = [1 as i64] + let mut index = 0 + while index < 64 + values.push(index as i64) + index = index + 1 + end while + let pair = (values, $"items-{values.len()}") + println(pair.1) + println(pair.0.len()) + return 0 +end fn +''') + expected = '42\nitems-65\n65\n' + nil = root / 'compiled program.nil' + run([compiler, '--quiet', '--debug-info', '--no-bundle', '--no-stdlib', '-o', nil, source]) + plain = run([interpreter, '--no-ai', nil]) + assert plain.stdout == expected and not plain.stderr, plain + assert not list(root.glob('*.json')), list(root.iterdir()) + checks += 1 + reports = [] + for route in ('vm', 'native') if args.llvm == 'ON' else ('vm',): + output = root / (route + ' memory report.json') + command = [aperture, 'memory', '--output', output, '--sdk-path', stdlib] + if route == 'native': + command += ['--native'] + result = run([*command, source]) + assert result.stdout == expected, result + assert 'Live at session end:' in result.stderr and 'not classified as leaks' in result.stderr, result + profile = validate(output, route, source) + assert profile['totals']['freed_objects'] >= 1, profile + assert profile['totals']['resizes'] >= 1, profile + assert profile['totals']['live_objects'] > 0, profile + reports.append(output) + inspection = run([aperture, 'memory', '--report', output, '--json']) + assert json.loads(inspection.stdout) == profile and not inspection.stderr, inspection + human = run([aperture, 'memory', '--report', output]) + assert str(source) in human.stdout and not human.stderr, human + checks += 2 + if args.llvm == 'ON': + executable = root / 'native $(touch INJECTED) executable' + run([compiler, '--quiet', '--no-stdlib', '--native', '-o', executable, source]) + direct = run([executable]) + assert direct.stdout == expected and not direct.stderr, direct + output = root / 'precompiled native.json' + recorded = run([aperture, 'memory', '--output', output, executable]) + assert recorded.stdout == direct.stdout, recorded + validate(output, 'native') + checks += 1 + assert not (root / 'INJECTED').exists(), 'target path was interpreted by a shell' + checks += 1 + + # Text and binary NIL retain their debug-source identity, and JSON mode + # leaves target stdout untouched while the saved file stays machine-readable. + for encoding in ('text', 'binary'): + artifact = root / (encoding + '.nil') + flags = ['--emit-binary-nil'] if encoding == 'binary' else [] + run([compiler, '--quiet', '--debug-info', '--no-bundle', '--no-stdlib', *flags, + '-o', artifact, source]) + output = root / (encoding + '.json') + result = run([aperture, 'memory', '--json', '--output', output, artifact]) + assert result.stdout == expected, result + profile = validate(output, 'vm', source) + assert json.loads(result.stderr) == profile, result.stderr + checks += 1 + + # Matrix uses the same report contract and source mapping. + matrix = root / 'matrix source.MATRIX' + matrix.write_text('''book memory_contract +main returns override integer begin paragraph + value pair is (41, "matrix") + value items is [pair, (42, "second")] + say (items at 1).0 + say (items at 0).1 + give 0 +end paragraph +''') + for route in ('vm', 'native') if args.llvm == 'ON' else ('vm',): + output = root / ('matrix-' + route + '.json') + flags = ['--native'] if route == 'native' else [] + result = run([aperture, 'memory', '--output', output, *flags, matrix]) + assert result.stdout == '42\nmatrix\n', result + validate(output, route, matrix) + + # Normal nonzero program exits are propagated with a usable report. + failure = root / 'failure.ny' + failure.write_text('fn main() -> i32\nlet values = [7]\nprintln(values[0])\nreturn 7\nend fn\n') + for route in ('vm', 'native') if args.llvm == 'ON' else ('vm',): + output = root / ('failure-' + route + '.json') + flags = ['--native'] if route == 'native' else [] + result = run([aperture, 'memory', '--output', output, *flags, failure], 7) + assert result.stdout == '7\n', result + validate(output, route, failure) + + # Collection accounting distinguishes reclaimed storage from rooted + # live values. VM collection is requested explicitly in safe mode. + gc_source = root / 'collection.ny' + gc_source.write_text('import nil.std.runtime.*\n' + 'fn discarded() -> i32\nlet transient: array = [1, 2, 3]\nreturn transient[0]\nend fn\n' + 'fn main() -> i32\nlet retained: array = [42]\n' + 'println(discarded())\ncollect(2)\nprintln(retained[0])\nreturn 0\nend fn\n') + gc_report = root / 'collection.json' + gc_result = run([aperture, 'memory', '--memory-mode', 'safe', '--sdk-path', stdlib, + '--output', gc_report, gc_source]) + assert gc_result.stdout == '1\n42\n', gc_result + gc_profile = validate(gc_report, 'vm', gc_source) + assert gc_profile['collections']['count'] >= 1, gc_profile + assert gc_profile['collections']['freed_objects'] >= 1, gc_profile + assert gc_profile['collections']['freed_bytes'] >= 12, gc_profile + assert gc_profile['totals']['live_objects'] >= 1, gc_profile + checks += 1 + + owned = root / 'owned.ny' + owned.write_text('fn main() -> i32\nif true then\nlet value = owned(4)\n' + 'println(42)\nend if\nreturn 0\nend fn\n') + fault = root / 'fault.ny' + fault.write_text('struct Problem\ncode: i32\nend struct\nfn main() -> i32\n' + 'let values = [42]\nprintln(values[0])\n' + 'raise Problem { code: 7 }\nreturn 0\nend fn\n') + explicit_exit = root / 'explicit exit.ny' + explicit_exit.write_text('import nil.std.system.*\nfn main() -> i32\n' + 'let values = [42]\nprintln(values[0])\nexit(7 as i32)\nreturn 0\nend fn\n') + for route in ('vm', 'native') if args.llvm == 'ON' else ('vm',): + flags = ['--native'] if route == 'native' else [] + output = root / ('owned-' + route + '.json') + result = run([aperture, 'memory', '--output', output, *flags, owned]) + assert result.stdout == '42\n', result + profile = validate(output, route, owned) + assert profile['totals']['freed_objects'] >= 1 and profile['totals']['live_objects'] == 0, profile + output = root / ('fault-' + route + '.json') + result = run([aperture, 'memory', '--output', output, *flags, fault], 1) + assert result.stdout == '42\n', result + profile = json.loads(output.read_text()) + assert profile['status'] == 'failed' and not profile['completed'], profile + assert profile['totals']['allocated_objects'] > 0, profile + output = root / ('exit-' + route + '.json') + result = run([aperture, 'memory', '--sdk-path', stdlib, '--output', output, + *flags, explicit_exit], 7) + assert result.stdout == '42\n', result + validate(output, route, explicit_exit) + checks += 2 + + forwarding = root / 'arguments and input.ny' + for route in ('vm', 'native') if args.llvm == 'ON' else ('vm',): + # console.read_line is currently VM-only; argument forwarding is + # qualified on both routes without implying native console support. + forwarding.write_text('import nil.std.system.*\n' + + ('import nil.std.io.*\n' if route == 'vm' else '') + + 'fn main() -> i32\nlet values = [42]\nprintln(arg_count())\n' + 'println(arg(0))\nprintln(arg(1))\nprintln(arg(2))\n' + + ('println(read_line())\n' if route == 'vm' else '') + + 'println(values[0])\nreturn 0\nend fn\n') + flags = ['--native'] if route == 'native' else [] + output = root / ('arguments-' + route + '.json') + result = run([aperture, 'memory', '--sdk-path', stdlib, '--output', output, + *flags, forwarding, '--', 'space argument', '', '$(touch INJECTED)'], + input_text='hello from stdin\n') + expected_forwarding = '3\nspace argument\n\n$(touch INJECTED)\n' + ('hello from stdin\n' if route == 'vm' else '') + '42\n' + assert result.stdout == expected_forwarding, result + validate(output, route, forwarding) + assert not (root / 'INJECTED').exists(), 'program argument was interpreted by a shell' + checks += 1 + + # The requested destination must be writable and fresh before target + # execution. Existing files, target source, and symlink referents survive. + sentinel = root / 'existing.json' + sentinel.write_text('do not replace') + alias = root / 'existing-link.json' + alias.symlink_to(sentinel) + for output in (sentinel, alias, root / 'absent-parent' / 'out.json', root): + result = run([aperture, 'memory', '--output', output, source], 1) + assert not result.stdout and 'cannot create output report' in result.stderr, result + assert sentinel.read_text() == 'do not replace' and alias.is_symlink() + checks += 1 + result = run([aperture, 'memory', root / 'missing.nil'], 1) + assert 'not a regular file' in result.stderr, result + invalid = root / 'invalid.nil' + invalid.write_text('not valid NIL') + failed_report = root / 'invalid.json' + run([aperture, 'memory', '--output', failed_report, invalid], 1) + # A loader failure can either carry an explicitly failed report or no + # profile; it must never leave a successful fabricated measurement. + if failed_report.exists(): + assert not json.loads(failed_report.read_text())['completed'] + checks += 1 + if os.name != 'nt': + result = run([aperture, 'memory', '/bin/true'], 1) + assert 'cannot read memory profile' in result.stderr, result + checks += 1 + + # Report inspection is strict and never executes a file's contents. + original = json.loads(reports[0].read_text()) + malformed = root / 'malformed.json' + mutations = [None, {'schema': 'aperture.memory.v999'}, {'schema': 'aperture.memory.v1'}] + negative = json.loads(json.dumps(original)) + negative['totals']['allocated_bytes'] = -1 + mutations.append(negative) + inconsistent = json.loads(json.dumps(original)) + inconsistent['totals']['live_bytes'] += 1 + mutations.append(inconsistent) + for profile in mutations: + malformed.write_text('not JSON' if profile is None else json.dumps(profile)) + result = run([aperture, 'memory', '--report', malformed], 1) + assert not result.stdout, result + malformed.write_text('{"schema":"aperture.memory.v1","schema":"duplicate"}') + run([aperture, 'memory', '--report', malformed], 1) + unfinished = json.loads(json.dumps(original)) + unfinished['completed'] = False + unfinished['status'] = 'failed' + malformed.write_text(json.dumps(unfinished)) + inspected = run([aperture, 'memory', '--json', '--report', malformed], 1) + assert json.loads(inspected.stdout) == unfinished, inspected + for command in ('explore', 'trace', 'agent'): + result = run([aperture, command, source], 1) + assert 'not implemented' in result.stderr and not result.stdout, result + for flags in (['--unknown'], ['--native', nil], ['--report', reports[0], source], + ['--memory-mode', 'invalid', source], ['--output'], [source, 'extra']): + run([aperture, 'memory', *flags], 1) + print(f'Aperture memory contract: {checks} checks passed') + + +if __name__ == '__main__': + main() diff --git a/tests/tools/memory_profile_contract.py b/tests/tools/memory_profile_contract.py new file mode 100644 index 00000000..e8114ae7 --- /dev/null +++ b/tests/tools/memory_profile_contract.py @@ -0,0 +1,152 @@ +#!/usr/bin/env python3 +"""Validate Aperture collector accounting, boundedness, output and isolation.""" +from __future__ import annotations + +import argparse +import json +import os +from pathlib import Path +import subprocess +import tempfile + + +COUNTERS = ( + "allocated_bytes", "allocated_objects", "live_bytes", "live_objects", + "peak_bytes", "peak_objects", "freed_bytes", "freed_objects", "resizes", +) + + +def invariants(report): + assert report["schema"] == "aperture.memory.v1" + assert report["route"] == "native" + assert report["measurement"] == "runtime_logical_bytes" + assert isinstance(report["completed"], bool) + assert report["scope"] and all(isinstance(item, str) for item in report["scope"]) + assert all(isinstance(item, str) for item in report["errors"]) + for counts in [report["totals"], *report["sites"]]: + for key in COUNTERS: + assert type(counts[key]) is int and 0 <= counts[key] <= 2**64 - 1, (key, counts) + for unit in ("bytes", "objects"): + assert counts[f"allocated_{unit}"] - counts[f"freed_{unit}"] == counts[f"live_{unit}"], counts + assert counts[f"live_{unit}"] <= counts[f"peak_{unit}"] <= counts[f"allocated_{unit}"], counts + for key in COUNTERS: + if not key.startswith("peak_"): + assert sum(site[key] for site in report["sites"]) == report["totals"][key], key + for site in report["sites"]: + assert set(site) == {"file", "function", "line", "kind", *COUNTERS} + assert all(isinstance(site[key], str) for key in ("file", "function", "kind")) + assert type(site["line"]) is int and site["line"] >= 0 + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--probe", type=Path, required=True) + args = parser.parse_args() + probe = args.probe.resolve() + environment = {key: value for key, value in os.environ.items() + if key != "NIL_MEMORY_PROFILE"} + checks = 0 + with tempfile.TemporaryDirectory(prefix="nil-memory-collector-") as directory: + root = Path(directory) + + def capture(mode, exit_code=0): + nonlocal checks + output = root / (mode + ".json") + result = subprocess.run([str(probe), mode], + env={**environment, "NIL_MEMORY_PROFILE": str(output)}, + capture_output=True, text=True, timeout=10) + assert result.returncode == exit_code, (mode, result.returncode, result.stderr) + assert result.stdout == "", (mode, result.stdout) + raw = output.read_bytes() + report = json.loads(raw) + invariants(report) + checks += 1 + return report, result, raw + + report, result, _ = capture("basic") + assert result.stderr == "" + assert report["completed"] and report["status"] == "completed" + assert report["totals"] == dict(zip(COUNTERS, (39, 3, 7, 1, 32, 3, 32, 2, 2))) + assert report["collections"] == {"count": 1, "duration_ns": 25, + "freed_bytes": 32, "freed_objects": 2} + first, second = report["sites"] + assert (first["file"], first["function"], first["line"], first["kind"]) == ( + "fixture.ny", "fixture.main", 12, "array") + assert first["resizes"] == 2 and first["freed_objects"] == 2 + assert second["file"] == "other.matrix" and second["live_bytes"] == 7 + + report, _, _ = capture("zero") + assert report["totals"]["live_bytes"] == 0 + assert report["totals"]["live_objects"] == 1 + + report, _, raw = capture("escape") + site = report["sites"][0] + assert site["file"] == '/tmp/Δ "path"\\\n\t\0ÿ' + assert site["function"] == "function\n\r\t\x01" + assert site["kind"] == 'kind"\\\n' + assert "Δ".encode() in raw + + for mode, diagnostic in (("duplicate", "duplicate live allocation identity"), + ("overflow", "representable range"), + ("resize-overflow", "representable range")): + report, result, _ = capture(mode, 2) + assert not report["completed"] and report["status"] == "profile_error" + assert diagnostic in result.stderr and any(diagnostic in item for item in report["errors"]) + assert report["totals"]["resizes"] == 0 + + report, _, _ = capture("spill") + assert report["site_limit_reached"] + assert len(report["sites"]) == 4097 + assert report["totals"]["allocated_objects"] == 4099 + assert report["totals"]["peak_objects"] == 1 + overflow = report["sites"][-1] + assert overflow["function"] == "" + assert overflow["allocated_objects"] == 2 + assert report["sites"][0]["allocated_objects"] == 2 + + report, _, _ = capture("worker") + assert report["excluded_sessions"] == 1 + assert report["totals"]["allocated_bytes"] == 5 + assert all(site["kind"] != "worker" for site in report["sites"]) + + report, _, _ = capture("abandoned") + assert not report["completed"] and report["status"] == "abandoned" + assert report["totals"]["live_bytes"] == 3 + report, _, _ = capture("failed") + assert not report["completed"] and report["status"] == "failed" + assert report["totals"]["live_bytes"] == 3 + report, _, _ = capture("finish-twice") + assert report["completed"] and report["status"] == "completed" + assert report["totals"]["allocated_bytes"] == 3 + + for extra in ({}, {"NIL_MEMORY_PROFILE": ""}): + result = subprocess.run([str(probe), "disabled"], env={**environment, **extra}, + capture_output=True, text=True, timeout=10) + assert result.returncode == 0 and result.stdout == result.stderr == "", result + checks += 1 + + existing = root / "existing.json" + sentinel = b"existing user data\n" + existing.write_bytes(sentinel) + for destination in (existing, root / "missing" / "capture.json"): + result = subprocess.run([str(probe), "basic"], + env={**environment, "NIL_MEMORY_PROFILE": str(destination)}, + capture_output=True, text=True, timeout=10) + assert result.returncode == 3 and "could not create capture destination" in result.stderr, result + assert result.stdout == "" + assert existing.read_bytes() == sentinel + checks += 1 + if os.name != "nt": + link = root / "symlink.json" + link.symlink_to(existing) + result = subprocess.run([str(probe), "basic"], + env={**environment, "NIL_MEMORY_PROFILE": str(link)}, + capture_output=True, text=True, timeout=10) + assert result.returncode == 3 and link.is_symlink() + assert existing.read_bytes() == sentinel + checks += 1 + print(f"Aperture memory collector contract: {checks} checks passed") + + +if __name__ == "__main__": + main() diff --git a/tests/tools/memory_profile_probe.cpp b/tests/tools/memory_profile_probe.cpp new file mode 100644 index 00000000..2e9a8e6b --- /dev/null +++ b/tests/tools/memory_profile_probe.cpp @@ -0,0 +1,88 @@ +// A small process boundary for exercising collector behavior independently of +// VM/native allocation implementations. The Python contract validates reports. +#include "memory_profile.hpp" + +#include +#include +#include +#include +#include + +int main(int argc, char **argv) { + if (argc != 2) return 64; + const std::string mode = argv[1]; + ny::memory_profile::Session session; + if (!session.begin("native")) return 3; + if (mode == "disabled") return session.enabled() ? 4 : 0; + if (!session.enabled()) return 5; + int identities[4] = {}; + session.site("fixture.ny", "fixture.main", 12); + if (mode == "basic") { + session.allocate(&identities[0], 8, "array"); + session.allocate(&identities[1], 0, "array"); + session.resize(&identities[0], 32); + session.resize(&identities[0], 12); + session.site("other.matrix", "other.allocate", 34); + session.allocate(&identities[2], 7, "buffer"); + session.release(&identities[0]); + session.release(&identities[1]); + session.release(&identities[3]); // Unknown handles must not fabricate frees. + session.resize(&identities[3], 100); + session.collection(25, 32, 2); + } else if (mode == "zero") { + session.allocate(&identities[0], 0, "zero"); + } else if (mode == "escape") { + std::string file = u8"/tmp/Δ \"path\"\\\n\t"; + file.push_back('\0'); + file.push_back(static_cast(0xff)); + session.site(file, "function\n\r\t\x01", 42); + session.allocate(&identities[0], 1, "kind\"\\\n"); + } else if (mode == "duplicate") { + session.allocate(&identities[0], 8, "buffer"); + session.allocate(&identities[0], 16, "buffer"); + } else if (mode == "overflow") { + session.allocate(&identities[0], (std::numeric_limits::max)(), "buffer"); + session.allocate(&identities[1], 1, "buffer"); + } else if (mode == "resize-overflow") { + session.allocate(&identities[0], (std::numeric_limits::max)() - 1, "buffer"); + session.allocate(&identities[1], 1, "buffer"); + session.resize(&identities[1], 2); + } else if (mode == "spill") { + for (std::uint64_t i = 1; i <= 4098; ++i) { + session.site("fixture.ny", "fixture.main", i); + session.allocate(&identities[0], 1, "array"); + session.release(&identities[0]); + } + // Existing sites remain precise after overflow begins. + session.site("fixture.ny", "fixture.main", 1); + session.allocate(&identities[0], 1, "array"); + session.release(&identities[0]); + } else if (mode == "worker") { + session.allocate(&identities[0], 5, "parent"); + bool worker_enabled = true, worker_began = false; + std::thread worker([&] { + ny::memory_profile::Session other; + worker_began = other.begin("vm"); + worker_enabled = other.enabled(); + other.site("worker.ny", "worker.run", 1); + other.allocate(&identities[1], 100, "worker"); + (void)other.finish(); + }); + worker.join(); + if (!worker_began || worker_enabled) return 6; + } else if (mode == "abandoned") { + session.allocate(&identities[0], 3, "buffer"); + return 0; // Destructor must preserve retained counts and mark incomplete. + } else if (mode == "failed") { + session.allocate(&identities[0], 3, "buffer"); + return session.finish("failed", false) ? 0 : 2; + } else if (mode == "finish-twice") { + session.allocate(&identities[0], 3, "buffer"); + if (!session.finish()) return 2; + session.allocate(&identities[1], 100, "after-finish"); + return session.finish("failed", false) ? 0 : 2; + } else { + return 64; + } + return session.finish() ? 0 : 2; +} diff --git a/tests/vm_memory_profile_tests.cpp b/tests/vm_memory_profile_tests.cpp new file mode 100644 index 00000000..a8840eb6 --- /dev/null +++ b/tests/vm_memory_profile_tests.cpp @@ -0,0 +1,184 @@ +#include "nil_loader.hpp" +#include "vm.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +void require(bool condition, const char *message) { + if (!condition) throw std::runtime_error(message); +} + +struct Capture { + std::filesystem::path directory; + std::filesystem::path path; + + Capture() { + const auto stamp = std::chrono::steady_clock::now().time_since_epoch().count(); + for (unsigned attempt = 0; attempt != 100; ++attempt) { + auto candidate = std::filesystem::temp_directory_path() / + ("nil-vm-profile-" + std::to_string(stamp) + "-" + std::to_string(attempt)); + if (std::filesystem::create_directory(candidate)) { + directory = std::move(candidate); + break; + } + } + require(!directory.empty(), "could not reserve test directory"); + path = directory / "capture.json"; +#ifdef _WIN32 + require(_putenv_s("NIL_MEMORY_PROFILE", path.string().c_str()) == 0, + "could not enable capture"); +#else + require(setenv("NIL_MEMORY_PROFILE", path.string().c_str(), 1) == 0, + "could not enable capture"); +#endif + } + + ~Capture() { + std::error_code ignored; + std::filesystem::remove_all(directory, ignored); + } + + std::string read() const { + std::ifstream input(path); + require(input.good(), "capture was not created"); + return {std::istreambuf_iterator(input), std::istreambuf_iterator()}; + } +}; + +void validate(const std::string &report, const char *status, bool completed) { + require(report.find(std::string("\"status\":\"") + status + '"') != std::string::npos, + "incorrect capture status"); + require(report.find(completed ? "\"completed\":true" : "\"completed\":false") != + std::string::npos, + "incorrect capture completeness"); + const auto totals_start = report.find("\"totals\":{"); + require(totals_start != std::string::npos, "missing totals"); + const auto totals = report.substr(totals_start, report.find('}', totals_start) - totals_start); + require(totals.find("\"live_bytes\":16,") != std::string::npos, + "retained bytes were lost to VM teardown"); + require(totals.find("\"allocated_objects\":1,") != std::string::npos, + "capture combined separate invocations"); + require(totals.find("\"freed_objects\":0,") != std::string::npos, + "teardown was counted as an application release"); + require(report.find("\"file\":\"lifecycle.ny\"") != std::string::npos && + report.find("\"line\":17,") != std::string::npos, + "allocation source attribution was lost"); +} + +void load(ny::VM &vm, bool fail) { + std::istringstream source(fail ? R"( +module memory_profile +function main() -> i64: + OWN_ENTER + PUSH_CONST 4 + OWN_ALLOC i32 + STORE_LOCAL owner + OWN_BIND owner + PUSH_CONST 1 + PUSH_CONST 0 + DIV + POP + OWN_LEAVE + PUSH_CONST 0 + RET +end function +)" : R"( +module memory_profile +function main() -> i64: + PUSH_CONST 4 + ALLOC i32 + STORE_LOCAL buffer + PUSH_CONST 0 + RET +end function +)"); + std::unordered_map constants; + auto program = ny::parseProgram(source, constants); + for (auto &instruction : program) { + if (instruction.op == ny::Opcode::ALLOC || instruction.op == ny::Opcode::OWN_ALLOC) { + instruction.source_file = "lifecycle.ny"; + instruction.line = 17; + } + } + vm.loadProgram(program, constants); +} + +void pause_after_allocation(ny::VM &vm) { + const auto &program = vm.getProgram(); + for (std::size_t index = 0; index != program.size(); ++index) { + if (program[index].op == ny::Opcode::STORE_LOCAL) { + vm.setBreakpoint(index + 1); + vm.execute(); + require(vm.getPC() == index + 1, "VM did not pause after allocation"); + return; + } + } + throw std::runtime_error("missing pause instruction"); +} + +} // namespace + +int main(int argc, char **argv) try { + require(argc == 2, "expected restart, failure, stepping, or abandoned mode"); + const std::string mode = argv[1]; + Capture capture; + if (mode == "restart") { + ny::VM vm; + load(vm, false); + pause_after_allocation(vm); + const auto paused_pc = vm.getPC(); + vm.resetExecution("main"); + const auto report = capture.read(); + validate(report, "abandoned", false); + vm.clearBreakpoint(paused_pc); + vm.setDebugState(ny::VM::DebugState::RUNNING); + vm.execute(false); + require(capture.read() == report, "restart overwrote the first invocation's capture"); + } else if (mode == "failure") { + ny::VM vm; + load(vm, true); + bool failed = false; + try { vm.execute(); } + catch (const std::runtime_error &) { failed = true; } + require(failed, "division by zero did not fail"); + validate(capture.read(), "failed", false); + const auto frames = vm.getDebugFrames(); + require(!frames.empty() && std::get(frames.back().locals.at("owner")) == 0, + "failure no longer unwinds owned storage after the snapshot"); + } else if (mode == "stepping") { + ny::VM vm; + load(vm, false); + vm.resetExecution("main"); + unsigned steps = 0; + while (vm.getPC() < vm.getProgram().size()) { + require(++steps < 20, "stepping did not terminate"); + vm.setDebugState(ny::VM::DebugState::STEPPING); + vm.execute(false); + } + validate(capture.read(), "completed", true); + } else if (mode == "abandoned") { + { + ny::VM vm; + load(vm, false); + pause_after_allocation(vm); + } + validate(capture.read(), "abandoned", false); + } else { + throw std::runtime_error("unknown test mode"); + } + std::cout << "VM memory profile " << mode << " lifecycle passed\n"; + return 0; +} catch (const std::exception &error) { + std::cerr << "VM memory profile lifecycle failure: " << error.what() << '\n'; + return 1; +} diff --git a/vscode/README.md b/vscode/README.md index 59ffb987..8a129fab 100644 --- a/vscode/README.md +++ b/vscode/README.md @@ -111,6 +111,8 @@ Open the Command Palette and run: - **NIL Framework: Compile Current File to NIL** - **NIL Framework: Compile and Run Current File** - **NIL Framework: Compile Current File Natively** +- **NIL Framework: Profile Current File Memory (VM)** +- **NIL Framework: Profile Current File Memory (Native)** - **NIL Framework: Build and Install Workspace SDK** - **NIL Framework: Run Workspace CTest Suite** @@ -122,6 +124,16 @@ These source commands accept saved `.ny`, `.matrix`, and `.mat` files in the matching language mode. Matrix selects the same shared compiler pipeline and supports both NIL/VM execution and the optional LLVM native backend. +The memory commands save the current source, run it through Aperture, and open +a fresh JSON report in the editor. Reports are stored in extension workspace +storage; program output and the profile summary appear in the task terminal. +These commands use a single source file and the configured SDK. Project-specific +dependencies and compiler argument settings are not yet applied. Aperture uses +the toolchain installed beside its executable; `ny.aperture.path` can select it. +Profiles measure runtime logical allocations rather than process RSS, and live +objects at exit are not classified as leaks. See the +[Aperture guide](../aperture/README.md) for accounting scope and CLI options. + The SDK and CTest commands target a NIL Framework repository checkout. The SDK command runs `scripts/build-sdk.sh`; the CTest command uses `ny.buildDirectory`, which defaults to `build/cmake`. @@ -222,6 +234,7 @@ editor builds. | `ny.interpreter.path` | empty | Explicit `nilinterpreter` path or command. | | `ny.debugger.path` | empty | Explicit `nildebugger` path or command. | | `ny.projectTool.path` | empty | Explicit `nilbuild` path or command. | +| `ny.aperture.path` | empty | Explicit `aperture` path or command for memory profiling. | | `ny.compiler.noStdlib` | `false` | Add `--no-stdlib` to compiler tasks and editor checks. | | `ny.compiler.extraArgs` | `[]` | Extra arguments for every compiler task. | | `ny.native.extraArgs` | `[]` | Extra arguments for native compiler tasks. | diff --git a/vscode/package.json b/vscode/package.json index 933be658..ddeb24f6 100644 --- a/vscode/package.json +++ b/vscode/package.json @@ -57,7 +57,9 @@ "onCommand:ny.buildNativeProject", "onCommand:ny.runProject", "onCommand:ny.runNativeProject", - "workspaceContains:**/nil.project.json" + "workspaceContains:**/nil.project.json", + "onCommand:ny.profileMemory", + "onCommand:ny.profileNativeMemory" ], "capabilities": { "untrustedWorkspaces": { @@ -290,6 +292,14 @@ { "command": "ny.runNativeProject", "title": "NIL Framework: Build and Run Project (Native)" + }, + { + "command": "ny.profileMemory", + "title": "NIL Framework: Profile Current File Memory (VM)" + }, + { + "command": "ny.profileNativeMemory", + "title": "NIL Framework: Profile Current File Memory (Native)" } ], "configuration": { @@ -404,6 +414,12 @@ "default": "", "scope": "machine-overridable", "description": "Absolute path or command name for nilbuild. Overrides SDK and PATH discovery." + }, + "ny.aperture.path": { + "type": "string", + "default": "", + "scope": "machine-overridable", + "description": "Absolute path or command name for Aperture. Overrides SDK and PATH discovery." } } }, @@ -424,7 +440,9 @@ "ctest", "project-check", "project-build", - "project-run" + "project-run", + "profile-memory", + "profile-memory-native" ], "description": "NIL Framework task to execute." }, diff --git a/vscode/src/extension.ts b/vscode/src/extension.ts index 853f9b31..aa531449 100644 --- a/vscode/src/extension.ts +++ b/vscode/src/extension.ts @@ -1,4 +1,5 @@ import * as vscode from "vscode"; +import { randomUUID } from "node:crypto"; import { NyLanguageClientManager } from "./languageClient"; import { NyDebugIntegration } from "./debugger"; @@ -150,6 +151,23 @@ export async function activate(context: vscode.ExtensionContext): Promise await runToolTask(provider, "native", source); } }), + ...([ ["ny.profileMemory", "profile-memory"], ["ny.profileNativeMemory", "profile-memory-native"] ] as const) + .map(([command, kind]) => vscode.commands.registerCommand(command, async () => { + if (!(await requireTrustedWorkspace())) return undefined; + const source = await currentSource(); + if (!source) return undefined; + const directory = vscode.Uri.joinPath(context.storageUri ?? context.globalStorageUri, "memory-profiles"); + await vscode.workspace.fs.createDirectory(directory); + const report = vscode.Uri.joinPath(directory, `${Date.now()}-${randomUUID()}.json`); + await runToolTask(provider, kind, source, { output: report.fsPath }); + try { + await vscode.workspace.fs.stat(report); + await vscode.window.showTextDocument(await vscode.workspace.openTextDocument(report), { preview: false }); + return report; + } catch { + return undefined; + } + })), vscode.commands.registerCommand("ny.runCurrentFile", async () => { const source = await currentSource(); if (!source) { diff --git a/vscode/src/tasks.ts b/vscode/src/tasks.ts index c5d16a13..51a2ba1a 100644 --- a/vscode/src/tasks.ts +++ b/vscode/src/tasks.ts @@ -18,7 +18,7 @@ import { resolveConfiguredTool } from "./vscodeToolchain"; -export type NyTaskKind = "compile" | "run" | "native" | "project-check" | "project-build" | "project-run" | "build-sdk" | "ctest"; +export type NyTaskKind = "compile" | "run" | "native" | "profile-memory" | "profile-memory-native" | "project-check" | "project-build" | "project-run" | "build-sdk" | "ctest"; export interface NyTaskDefinition extends vscode.TaskDefinition { readonly type: "ny"; @@ -127,6 +127,21 @@ export class NyTaskProvider implements vscode.TaskProvider { // and deriving a default output require a source document. if (!source && !(definition.task === "run" && definition.output && !definition.source)) return undefined; const resource = resourceForSource(source ?? definition.output); + if (definition.task === "profile-memory" || definition.task === "profile-memory-native") { + if (!source || !definition.output) return undefined; + const aperture = resolveConfiguredTool("aperture", resource); + if (!aperture.executable) return undefined; + const sdkPath = definition.sdkPath ?? configuredSdkPath(resource); + const args = ["memory", "--output", definition.output, + ...(definition.task === "profile-memory-native" ? ["--native"] : []), + ...(sdkPath ? ["--sdk-path", sdkPath] : []), source]; + const task = new vscode.Task({ ...definition, source }, taskScope(resource), + `Profile memory (${definition.task === "profile-memory-native" ? "native" : "VM"}): ${path.basename(source)}`, + "NIL Framework", new vscode.ProcessExecution(aperture.executable, args, + { cwd: workspaceRoot(resource) ?? path.dirname(source) })); + task.detail = "Record runtime allocations for the saved source file with Aperture."; + return presentation(task); + } const mode: CompileMode = definition.task === "native" ? "native" : "nil"; const output = definition.output ?? diff --git a/vscode/src/test/assets.test.ts b/vscode/src/test/assets.test.ts index b0c6e6f1..82245294 100644 --- a/vscode/src/test/assets.test.ts +++ b/vscode/src/test/assets.test.ts @@ -49,7 +49,7 @@ test("manifest contributes both frontends, shared tasks, and source debugger int "run", "native", "build-sdk", - "ctest", "project-check", "project-build", "project-run" + "ctest", "project-check", "project-build", "project-run", "profile-memory", "profile-memory-native" ]); assert.equal(manifest.contributes.debuggers[0]?.type, "ny"); assert.deepEqual(manifest.contributes.debuggers[0]?.languages, ["ny", "matrix"]); diff --git a/vscode/src/toolchain.ts b/vscode/src/toolchain.ts index d76fd74d..6cf1bf70 100644 --- a/vscode/src/toolchain.ts +++ b/vscode/src/toolchain.ts @@ -2,7 +2,7 @@ import * as fs from "node:fs"; import * as os from "node:os"; import * as path from "node:path"; -export type NyTool = "nilcompiler" | "nilinterpreter" | "nillsp" | "nildebugger" | "nilbuild"; +export type NyTool = "nilcompiler" | "nilinterpreter" | "nillsp" | "nildebugger" | "nilbuild" | "aperture"; export interface ResolveToolOptions { readonly tool: NyTool; diff --git a/vscode/src/vscodeToolchain.ts b/vscode/src/vscodeToolchain.ts index 1c0d6fc8..7a34a4e9 100644 --- a/vscode/src/vscodeToolchain.ts +++ b/vscode/src/vscodeToolchain.ts @@ -12,7 +12,8 @@ const settingForTool: Record = { nilinterpreter: "interpreter.path", nillsp: "server.path", nildebugger: "debugger.path", - nilbuild: "projectTool.path" + nilbuild: "projectTool.path", + aperture: "aperture.path" }; function orderedWorkspaceFolders(resource?: vscode.Uri): string[] { diff --git a/vscode/test/memory-profile-checks.cjs b/vscode/test/memory-profile-checks.cjs new file mode 100644 index 00000000..7807345d --- /dev/null +++ b/vscode/test/memory-profile-checks.cjs @@ -0,0 +1,32 @@ +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const vscode = require("vscode"); + +exports.run = async ({ check, workspace }) => { + for (const language of ["ny", "matrix"]) { + const source = path.join(workspace, `memory profile.${language}`); + await fs.writeFile(source, language === "ny" ? + 'fn main() -> i32\n let values = [41, 42]\n println(values[1])\n return 0\nend fn\n' : + 'book editor.memory\nmain returns override integer begin paragraph\n value items is [41, 42]\n say items at 1\n give 0\nend paragraph\n'); + const document = await vscode.workspace.openTextDocument(source); + for (const route of ["vm", "native"]) { + await check(`${language}: ${route} memory command saves and opens an attributed profile`, async () => { + await vscode.window.showTextDocument(document, { preview: false }); + const uri = await vscode.commands.executeCommand(route === "vm" ? "ny.profileMemory" : "ny.profileNativeMemory"); + assert.ok(uri instanceof vscode.Uri, "Profiling should return its saved report URI"); + assert.equal(vscode.window.activeTextEditor.document.uri.toString(), uri.toString()); + const report = JSON.parse(await fs.readFile(uri.fsPath, "utf8")); + assert.equal(report.schema, "aperture.memory.v1"); + assert.equal(report.route, route); + assert.equal(report.completed, true); + assert.deepEqual(report.errors, []); + assert.ok(report.totals.allocated_bytes > 0); + assert.ok(report.totals.allocated_objects > 0); + assert.ok(report.sites.some(site => site.file === source && site.line > 0 && site.function.includes("main"))); + assert.equal(report.totals.allocated_bytes - report.totals.freed_bytes, report.totals.live_bytes); + return { language, route, allocatedObjects: report.totals.allocated_objects }; + }); + } + } +}; diff --git a/vscode/test/run-host.cjs b/vscode/test/run-host.cjs index 3c0a19a0..c429a4af 100644 --- a/vscode/test/run-host.cjs +++ b/vscode/test/run-host.cjs @@ -27,7 +27,7 @@ const settings = { "telemetry.telemetryLevel": "off" }; for (const [setting, tool] of Object.entries({ - server: "nillsp", compiler: "nilcompiler", interpreter: "nilinterpreter", debugger: "nildebugger", projectTool: "nilbuild" + server: "nillsp", compiler: "nilcompiler", interpreter: "nilinterpreter", debugger: "nildebugger", projectTool: "nilbuild", aperture: "aperture" })) { const executable = path.join(tools, tool + (process.platform === "win32" ? ".exe" : "")); fs.accessSync(executable, fs.constants.X_OK); diff --git a/vscode/test/suite.cjs b/vscode/test/suite.cjs index a45f7da2..ebac5e3b 100644 --- a/vscode/test/suite.cjs +++ b/vscode/test/suite.cjs @@ -242,6 +242,7 @@ exports.run = async function run() { await require("./completion-checks.cjs").run({ check, workspace }); await require("./member-signature-checks.cjs").run({ check, workspace }); await require("./language-values-checks.cjs").run({ check, workspace }); + await require("./memory-profile-checks.cjs").run({ check, workspace }); report.status = "PASS"; } catch (error) { report.status = "FAIL"; From 491900f6f8e3ea3ac355ff5396567a7c789a9511 Mon Sep 17 00:00:00 2001 From: Nathan Date: Fri, 23 Oct 2026 14:31:04 -0400 Subject: [PATCH 2/3] Preserve native parallel worker isolation while profiling --- nilcompiler/src/llvm_backend.cpp | 7 +++++ tests/tools/aperture_memory_contract.py | 35 +++++++++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/nilcompiler/src/llvm_backend.cpp b/nilcompiler/src/llvm_backend.cpp index d97601dd..4d0a482a 100644 --- a/nilcompiler/src/llvm_backend.cpp +++ b/nilcompiler/src/llvm_backend.cpp @@ -8115,6 +8115,13 @@ bool NativeCodegen::generateModule(const nil_module &mod) { std::cerr << "[NativeCodegen] isolated worker contains an indirect native call\n"; return false; } + if (callee->getName() == "nyrt_profile_site") { + // Worker clones are certified scalar-only and outside the parent + // capture. Keep their copies free of runtime context access while + // retaining attribution in the ordinary callable function. + call->eraseFromParent(); + continue; + } if (callee->getName() == "nyrt_fail") { auto *terminator = call->getParent()->getTerminator(); if (!llvm::isa(terminator) || call->getNextNode() != terminator) { diff --git a/tests/tools/aperture_memory_contract.py b/tests/tools/aperture_memory_contract.py index 577fe7a0..137bf675 100644 --- a/tests/tools/aperture_memory_contract.py +++ b/tests/tools/aperture_memory_contract.py @@ -149,6 +149,41 @@ def validate(path, route, source=None): assert result.stdout == '42\nmatrix\n', result validate(output, route, matrix) + # Scalar worker clones must remain isolated even when source-site + # instrumentation is present in their ordinary callable originals. + # Only the parent's input and output arrays belong to this capture. + parallel = root / 'parallel workers.ny' + parallel.write_text('fn square(value: i64) -> i64\nreturn value * value\nend fn\n' + 'fn transform(value: i64) -> i64\nreturn square(value) + 3\nend fn\n' + 'fn main() -> i32\n' + 'let inputs: array = [1 as i64, 2 as i64, 3 as i64, 4 as i64, ' + '5 as i64, 6 as i64, 7 as i64, 8 as i64]\n' + 'let outputs = parallel_map(transform, inputs)\n' + 'println(outputs[7])\nprintln(inputs[2])\nprintln(outputs.len())\n' + 'println(transform(5))\nreturn 0\nend fn\n') + for route in ('vm', 'native') if args.llvm == 'ON' else ('vm',): + output = root / ('parallel-' + route + '.json') + flags = ['--native'] if route == 'native' else [] + result = run([aperture, 'memory', '--output', output, *flags, parallel]) + assert result.stdout == '67\n3\n8\n28\n', result + profile = validate(output, route, parallel) + totals = profile['totals'] + assert totals['allocated_objects'] == totals['live_objects'] == 2, profile + assert totals['freed_objects'] == totals['resizes'] == 0, profile + assert all(site['function'] == 'main' and site['kind'].startswith('array') + and site['file'] == str(parallel) and site['line'] > 0 + for site in profile['sites']), profile['sites'] + assert sum(site['allocated_objects'] for site in profile['sites']) == 2, profile + assert any('parallel workers' in scope for scope in profile['scope']), profile + if route == 'vm': + # VM workers disable recording before opening a session. + assert profile['excluded_sessions'] == 0, profile + else: + # Native workers initialize their own invocation contexts; + # the first-session collector explicitly excludes those. + assert profile['excluded_sessions'] > 0, profile + checks += 2 + # Normal nonzero program exits are propagated with a usable report. failure = root / 'failure.ny' failure.write_text('fn main() -> i32\nlet values = [7]\nprintln(values[0])\nreturn 7\nend fn\n') From 32a3ab6f7ebcf15ed087bafc9f9021db7b328ef2 Mon Sep 17 00:00:00 2001 From: Nathan Date: Fri, 23 Oct 2026 14:36:46 -0400 Subject: [PATCH 3/3] Qualify native GC profiling and record collection API gap --- matrix/docs/next-version-findings.md | 9 ++++++++- tests/tools/aperture_memory_contract.py | 16 ++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/matrix/docs/next-version-findings.md b/matrix/docs/next-version-findings.md index 21431918..d414b41a 100644 --- a/matrix/docs/next-version-findings.md +++ b/matrix/docs/next-version-findings.md @@ -1753,9 +1753,16 @@ argument before native interop lowering. Separately, `nil.std.io.read_line()` works in the interpreter but native compilation rejects its reachable `console.read_line` intrinsic as unsupported. -Both failures reproduce through direct native compilation with the SDK that +These two failures reproduce through direct native compilation with the SDK that predates Aperture recording, so they are not profiling regressions. +The public `nil.std.runtime.collect` wrapper also retains a VM-only +`gc.collect` intrinsic; native lowering rejects an explicit call. Native managed +safepoints do collect automatically. Profiling the existing text-lifetime stress +fixture confirms that reclaimed native storage appears in collection counters +while rooted strings survive. An explicit cross-route collection API remains +separate work from observing the collector that already runs. + **Current handling:** Aperture passes program arguments without shell expansion and keeps standard input attached to the target. Its contract tests exercise space-containing and empty arguments on both routes, and line input on the VM. diff --git a/tests/tools/aperture_memory_contract.py b/tests/tools/aperture_memory_contract.py index 137bf675..b39c024c 100644 --- a/tests/tools/aperture_memory_contract.py +++ b/tests/tools/aperture_memory_contract.py @@ -212,6 +212,22 @@ def validate(path, route, source=None): assert gc_profile['totals']['live_objects'] >= 1, gc_profile checks += 1 + if args.llvm == 'ON': + # Native collection runs at managed safepoints; the public + # gc.collect intrinsic is not yet lowered on that route. + fixture = Path(__file__).resolve().parents[1] / 'language/stdlib-native-primitives-lifetime.ny' + native_gc = root / 'native collection.ny' + native_gc.write_text(fixture.read_text()) + output = root / 'native-collection.json' + result = run([aperture, 'memory', '--native', '--output', output, native_gc]) + assert result.stdout == fixture.with_suffix('.stdout').read_text(), result + profile = validate(output, 'native', native_gc) + assert profile['collections']['count'] >= 1, profile + assert profile['collections']['freed_objects'] >= 1, profile + assert profile['collections']['freed_bytes'] > 0, profile + assert profile['totals']['live_objects'] >= 1, profile + checks += 1 + owned = root / 'owned.ny' owned.write_text('fn main() -> i32\nif true then\nlet value = owned(4)\n' 'println(42)\nend if\nreturn 0\nend fn\n')