mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-29 22:21:12 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f8810a48af | ||
|
|
ba95e83c34 | ||
|
|
45564d9fe9 | ||
|
|
62c7702e50 | ||
|
|
d3ae607fb6 | ||
|
|
4ba4926d2f | ||
|
|
677686e356 | ||
|
|
8c9eceb05a | ||
|
|
706b669e95 | ||
|
|
a402287474 | ||
|
|
8cc2f8ffbc | ||
|
|
9ae6d1ee70 |
No files matched your search
@@ -31,7 +31,7 @@ jobs:
|
||||
test "$(sysctl -n sysctl.proc_translated)" = 0
|
||||
- name: Install Rust toolchain
|
||||
run: |
|
||||
rustup toolchain install "$RUSTUP_TOOLCHAIN" --profile minimal --component rustfmt --component clippy --target x86_64-pc-windows-gnu
|
||||
rustup toolchain install "$RUSTUP_TOOLCHAIN" --profile minimal --component rustfmt --component clippy
|
||||
rustc -vV
|
||||
- name: Check ARM64 Rust workspace (launcher + shader-transpiler)
|
||||
run: |
|
||||
|
||||
@@ -29,8 +29,6 @@ jobs:
|
||||
fetch-depth: 0
|
||||
- name: Install PyYAML
|
||||
run: python3 -c 'import yaml' 2>/dev/null || python3 -m pip install --user --break-system-packages pyyaml
|
||||
- name: Unit-test the hygiene checks
|
||||
run: python3 -m unittest scripts/audit/test_docs_hygiene.py
|
||||
- name: Check documentation and workflow files
|
||||
run: python3 scripts/audit/docs_hygiene.py --require-yaml
|
||||
- name: Remind about the changelog (advisory)
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
name: Merge policy audit
|
||||
|
||||
# Detects a pull request merged by its own author (AGENTS.md §7, "Merge
|
||||
# eligibility"). GitHub rulesets cannot block this, so the run fails after the
|
||||
# merge. It is not a required check and never checks out pull request code.
|
||||
|
||||
on:
|
||||
pull_request_target:
|
||||
types: [closed]
|
||||
branches: [main]
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
author-merge:
|
||||
name: Author did not merge
|
||||
if: github.event.pull_request.merged == true && github.event.pull_request.merged_by.login == github.event.pull_request.user.login
|
||||
runs-on: ubuntu-24.04-arm
|
||||
timeout-minutes: 2
|
||||
steps:
|
||||
- name: Report a self-merge
|
||||
env:
|
||||
PR: ${{ github.event.pull_request.number }}
|
||||
AUTHOR: ${{ github.event.pull_request.user.login }}
|
||||
run: |
|
||||
echo "::error::Pull request #$PR was merged by its own author, $AUTHOR. A maintainer other than the author must merge (AGENTS.md section 7)."
|
||||
exit 1
|
||||
@@ -4,59 +4,34 @@ These rules apply to every human contributor and coding agent (`CLAUDE.md` is a
|
||||
|
||||
---
|
||||
|
||||
## 0. What to Do When Told "Work"
|
||||
## 0. First-Time Contributor Onboarding
|
||||
|
||||
Collaborators point their agent at this repository and say "work" (or "contribute", "continue", "what next?"). That is a complete instruction. Do not ask what to work on: follow this section. The method behind it is in [docs/process/working-method.md](docs/process/working-method.md); the stages are in [docs/roadmap.md](docs/roadmap.md).
|
||||
If the user asks to contribute, get started, or pick a task (even with a short prompt like *"help me contribute"*), walk them through this exact end-to-end flow:
|
||||
|
||||
**"Work" authorizes, for the one item you pick:** posting a claim or a review, committing with DCO sign-off, pushing a branch, and opening a pull request. It does not authorize merging your own person's pull request, changing rules, or anything marked `needs-human`. A more specific instruction from your person always wins.
|
||||
|
||||
### Step 1 — Preflight
|
||||
|
||||
- Check `uname -m` (`arm64`), `git`, `gh`, `cargo`, `cmake`, `x86_64-w64-mingw32-g++`, and `python3`. If `mingw-w64`, `cmake`, or `gh` is missing on macOS, ask permission before running `brew install mingw-w64 cmake gh`.
|
||||
- Run `gh auth status` (if not logged in, pause and ask the user to run `gh auth login`). Verify push access or fork (`gh repo fork MacosPorters/betterxen --remote`), and sync with `origin/main`.
|
||||
- Run `cargo build --locked -p bx-cli && target/debug/bx-cli doctor`. It must report the toolchain, CrossOver, at least 10 GB of free disk space, and no other game run on this machine.
|
||||
- Work in your own worktree and your own bottle. Never use a bottle another session is using.
|
||||
|
||||
### Step 2 — Pick exactly one thing, in this order
|
||||
|
||||
Take the first that applies. Do not skip ahead because a later one looks more interesting.
|
||||
|
||||
1. **Your person's pull requests that need attention.**
|
||||
```sh
|
||||
gh pr list --repo MacosPorters/betterxen --author "@me" --state open --json number,title,headRefName,reviewDecision,statusCheckRollup,mergeStateStatus
|
||||
```
|
||||
If one has requested changes, unresolved review comments, failing checks or conflicts: fix that pull request. Resolve every review point, re-run Section 8, push, and reply to each point.
|
||||
|
||||
2. **Review someone else's pull request.**
|
||||
```sh
|
||||
gh pr list --repo MacosPorters/betterxen --state open --json number,title,author,reviewDecision,isDraft,createdAt
|
||||
```
|
||||
Take the oldest open, non-draft pull request that your person did not open and that has no current review. Check out its branch, run Section 8 and its new test, confirm the test fails without the fix, read its proof, and post an approval or a change request with what you ran. If it needs deep review (the list is in the working method) and you can give one, do. If it is approved, green and not your person's, merge it (Section 7).
|
||||
|
||||
3. **Fix one blocker of the current stage.**
|
||||
```sh
|
||||
gh issue list --repo MacosPorters/betterxen --state open --label blocker --label "stage: <current>" --json number,title,labels,comments
|
||||
```
|
||||
The current stage is named on the pinned issue labelled `ladder`. Take the top unclaimed blocker: those labelled `first`, then lowest number. A blocker is claimed if it has a `Claiming —` comment less than 3 days old or an open pull request. Then follow Step 3.
|
||||
|
||||
4. **Discover.** If the current stage has no unclaimed blocker, run the stage's gate check (ten runs, [run protocol](docs/process/working-method.md#run-protocol)). For each signature in the report that has no issue, open or closed, file a blocker issue in the fixed shape. If the gate passes, post the ten-run result on the ladder issue and label it `needs-human`.
|
||||
|
||||
5. **Nothing applies.** Say so and stop. Do not invent work, open research documents, or start on a later stage's blockers while the current stage has claimed, unfinished ones — unless your person tells you to.
|
||||
|
||||
**Stop and label `needs-human`** whenever the next step is a decision that is not yours: a decision gate, a licence or provenance question, sources of truth that disagree, or a rule change.
|
||||
|
||||
### Step 3 — Work one blocker
|
||||
|
||||
1. **Claim:** comment `Claiming — branch: track-<a..f>/<issue>-<slug>` and branch from `origin/main`.
|
||||
2. **Evidence before code:** find what the build asked for and what it got, from the run report and the diagnostics. If you cannot explain the blocker in this session, write what you learned on the issue, release the claim, and stop. Do not guess a fix.
|
||||
3. **Smallest fix:** only what removes this blocker. Stay inside the track directories it needs (Section 2); a new cross-DLL export goes through an `[ABI]` pull request first.
|
||||
4. **Test:** every contract the fix introduces gets a synthetic conformance test under `tests/conformance/test_<name>/` that fails without the fix.
|
||||
5. **Verify:** every command in Section 8. Without CrossOver you can still run the Rust checks, `scripts/build-shims.sh` and the docs check; say plainly which live checks were not run. Never report an unrun check as passed.
|
||||
6. **Proof:** ten runs before and ten after, every run reported, with the machine and the `main` commit.
|
||||
7. **Pull request:** one blocker; the five-part description (Blocker, Contract with its source rank, Fix, Test, Proof); `Closes #<issue>`; DCO sign-off; no AI trailers. Watch CI until `Hybrid build and shim checks` and `Repository hygiene` pass.
|
||||
8. **Stop.** The next "work" starts again at Step 2.
|
||||
|
||||
Nothing from the target build goes into a commit, issue or pull request (Section 6): keep run logs, dumps and captures in your private evidence folder outside the repository.
|
||||
1. **Preflight host & tools:**
|
||||
- Check `uname -m` (`arm64`), `git`, `gh`, `cargo`, `cmake`, `x86_64-w64-mingw32-g++`, and `python3`.
|
||||
- If `mingw-w64`, `cmake`, or `gh` is missing on macOS, ask permission before running `brew install mingw-w64 cmake gh`.
|
||||
- Run `gh auth status` (if not logged in, pause and ask the user to run `gh auth login`).
|
||||
- Run `cargo build --locked -p bx-cli && target/debug/bx-cli doctor` to report Apple Silicon, Rosetta 2, CrossOver, and toolchain readiness.
|
||||
- Verify whether the user has push access or needs a fork (`gh repo fork MacosPorters/betterxen --remote`), and sync with `origin/main`.
|
||||
2. **Discover & pick an unclaimed issue:**
|
||||
- Query ready issues in the active milestone:
|
||||
```sh
|
||||
gh issue list --repo MacosPorters/betterxen --state open --label "status: ready" --json number,title,labels,assignees
|
||||
```
|
||||
- Inspect comments and open PRs on candidate issues to filter out any issue that already has an active claim (< 7 days old).
|
||||
- Present the unclaimed options in plain English (recommending 1–2 good starting issues matching the user's background) and wait for the user to choose one before coding.
|
||||
3. **Claim & isolate:**
|
||||
- Post `Claiming — branch: track-<a..f>/<issue>-<slug>` on the chosen issue and create that branch (or `git worktree`) off `origin/main`.
|
||||
4. **Implement strictly in scope:**
|
||||
- Read the full issue body (`gh issue view <issue> --repo MacosPorters/betterxen`) and the relevant contracts in `abi/defs/` and `abi/include/`.
|
||||
- Edit **only** files inside the issue's **Exclusive file scope** (plus `CHANGELOG.md`). Add new synthetic C++ conformance tests under `tests/conformance/test_<name>/CMakeLists.txt` + `main.cpp` (auto-discovered by CMake).
|
||||
5. **Verify locally (including hosts without CrossOver):**
|
||||
- Run every command in Section 8 and fix all warnings/failures before stopping.
|
||||
- **No CrossOver installed?** The contributor can still run all ARM64 Rust checks, `scripts/build-shims.sh` (verifying all 16 PE32+ DLLs and exact exports), and `python3 scripts/audit/docs_hygiene.py`. Report honestly in the PR that live CrossOver execution was not run locally and needs verification on a CrossOver host—never report an unrun check as passed.
|
||||
6. **Review & submit PR:**
|
||||
- Present a concise summary of changes and exact verification outputs, and ask explicit user permission before running `git commit -s` (DCO sign-off, zero AI trailers), pushing, and opening a PR (`Closes #<issue>`).
|
||||
- After opening the PR, watch CI (`gh pr checks --watch`) until both `Hybrid build and shim checks` and `Repository hygiene` pass.
|
||||
|
||||
---
|
||||
|
||||
@@ -89,8 +64,8 @@ Every feature issue belongs to **one track** and defines an **exclusive file sco
|
||||
| **Track F** | `tests/conformance/`, `docs/` | Synthetic PE32+ conformance tests, integration fixture, benchmarks, documentation |
|
||||
|
||||
### Cross-Track `[ABI]` Rule
|
||||
- For issue-claimed contributor work, stay inside your issue's track directory; if your track needs a new cross-DLL helper or export, open a small `[ABI]` PR touching only `abi/` first so provider and consumer tracks can implement in parallel.
|
||||
- Maintainer-directed compatibility and startup-unblocking tasks may touch the required shim and `tests/conformance/` directories across tracks without a pre-existing issue claim. They must not overlap another contributor's active claim or open PR without that contributor's or a maintainer's recorded agreement, any new cross-DLL helper or export still goes through an `abi/`-only `[ABI]` PR first, and independent review (Section 5) still applies.
|
||||
- Never edit another track's directory inside a feature PR.
|
||||
- If your track needs a new cross-DLL helper or export, open a small `[ABI]` PR touching only `abi/` first. Once merged, both provider and consumer tracks implement against the frozen contract in parallel.
|
||||
- When adding a new conformance test, create `tests/conformance/test_<name>/CMakeLists.txt` + `main.cpp` — CMake auto-discovers `test_*` directories without editing `tests/conformance/CMakeLists.txt`.
|
||||
|
||||
---
|
||||
@@ -106,7 +81,9 @@ Every feature issue belongs to **one track** and defines an **exclusive file sco
|
||||
|
||||
## 4. Dependencies, Licensing & Provenance
|
||||
|
||||
_Reserved — policy migration in progress._
|
||||
- Before integrating or copying any third-party code: verify the **per-file** license (not just repository metadata), confirm compatibility with `GPL-3.0-or-later` and every selected component, preserve copyright notices, record the upstream repository and exact commit/version, document modifications, and record the entry in `docs/research/upstream-registry.md` and `docs/research/component-reuse-matrix.md`. If licensing is uncertain, do not use it until resolved.
|
||||
- Never bundle, modify, or redistribute proprietary components (CrossOver binaries, D3DMetal, Rosetta 2, Apple tools) unless their license explicitly allows it. Never bypass licensing or activation requirements of any dependency.
|
||||
- **Provenance first:** Exclude anything derived from leaked proprietary material or unauthorized software. A project's license being GPL does not clear material it was built from or for. Projects whose stated purpose depends on leaked or unauthorized builds (including VIctory, PE-Vulkan, KyTx, AnyPS5, and similar efforts) are never adopted as code, shader, asset, or tooling sources without a recorded per-file provenance and license audit. Game-specific, asset-specific, and decryption-related code is never adopted.
|
||||
|
||||
---
|
||||
|
||||
@@ -120,34 +97,26 @@ _Reserved — policy migration in progress._
|
||||
|
||||
---
|
||||
|
||||
## 6. Compatibility Evidence & Legal Boundaries
|
||||
## 6. Legal & Clean-Room Rules
|
||||
|
||||
- **Authorized compatibility evidence:** Contributors and agents may use publicly accessible documentation, publicly licensed software, synthetic workloads, and **project-authorized target builds** (via local call-site inspection and runtime diagnostics) to establish undocumented Xbox OS, graphics, memory, storage, and runtime ABI contracts (struct layouts, flags, COM IIDs, vtable slot orders, and expected return/error semantics). Separate direct observations from inferences and verify every implemented contract with a synthetic conformance test under `tests/conformance/`. Such a test shows that a shim matches the recorded inference, not that the inference is correct.
|
||||
- Use only publicly accessible documentation, publicly licensed software, and authorized synthetic workloads. Never obtain, paste, or commit leaked executables or SDKs, confidential Xbox documentation, restricted console tools, firmware, encryption keys, unauthorized assets or source code, or proprietary game builds and shader collections.
|
||||
- **Legal boundary (`docs/legal.md`):** BetterXen does not circumvent console security or DRM and does not load encrypted or protected content. Validate technical compatibility and safety of user-provided files; do not ask for ownership receipts, accounts, or acquisition provenance as part of file loading.
|
||||
- Never place restricted material, personal paths, or secrets in the repository or its Git history.
|
||||
|
||||
---
|
||||
|
||||
## 7. Claiming, Git Safety & Changelog
|
||||
|
||||
1. **Check before coding (open backlog issues):** When picking an unclaimed backlog issue, read every comment and check open PRs so you never claim over an active claim; reply `Claiming — branch: track-<a..f>/<issue>-<slug>` (stale after 7 days without commits/PR). Direct maintainer-assigned tasks do not require a prior issue claim, but still check open issues and PRs first and never take over another contributor's active claim.
|
||||
2. **Isolate with branches or worktrees:**
|
||||
1. **Check before coding:** Read every comment on the issue and check open PRs. Never claim over an active claim.
|
||||
2. **Claim in plain text:** Reply `Claiming — branch: track-<a..f>/<issue>-<slug>` on the issue (earliest claim wins; stale after 7 days without commits/PR).
|
||||
3. **Isolate with branches or worktrees:**
|
||||
```sh
|
||||
git worktree add ../wt-<issue> -b track-<a..f>/<issue>-<slug> origin/main
|
||||
```
|
||||
3. **Link & sign off:** Reference any related issue (`Closes #<issue>` when applicable) in the PR description and sign off every commit (`git commit -s`, DCO).
|
||||
4. **Git safety:** Commit, push, and open PRs only when requested or authorized by the user (being told to "work" authorizes them for the one item picked, Section 0); never change repository visibility without explicit instruction. Do not add AI attribution or `Co-authored-by` trailers to commits. Preserve the configured Git author and committer identity.
|
||||
5. **Changelog & docs index:** Read `CHANGELOG.md` before starting and update `[Unreleased]` for every meaningful addition, change, fix, removal, or security update. Update `docs/README.md` whenever documentation is added, removed, or reorganized.
|
||||
|
||||
### Merge eligibility
|
||||
|
||||
Four roles are separate: the **original author** (who opened the PR), **corrective contributors** (who later push to its branch), **independent approvers**, and the **merger**.
|
||||
|
||||
- The original author never merges their own PR. Any other maintainer may merge once required checks pass, at least one approval is current and blocking review conversations are resolved.
|
||||
- Maintainers may resolve conflicts, correct defects, update documentation and push fixes to a contributor's PR branch where GitHub permissions allow. Doing so does not disqualify them from merging.
|
||||
- Any push that changes the PR dismisses earlier approvals. After a **routine** push (conflict resolution that changes no behaviour, changelog correction, minor documentation fix), one new approval is enough and may come from the maintainer who pushed it, if they are not the original author. No further approval is required beyond the ruleset.
|
||||
- **Substantive** implementation changes need independent review (Section 5): the approval must come from someone who did not write them. A maintainer who wrote substantive corrections may merge after another person has approved those corrections, but may not approve them. If in doubt, treat a change as substantive.
|
||||
- A coding agent acts as the person it works for and merges only with that person's authorization.
|
||||
|
||||
The `Protect main` ruleset enforces pull requests, one approval, dismissal of stale approvals, resolved conversations, the required CI checks and no force push or deletion, with no bypass actors. GitHub cannot enforce two rules above: who may merge (`Merge policy audit` only fails after an author self-merge) and whether an approver wrote part of the change.
|
||||
4. **Link & sign off:** Put `Closes #<issue>` in the PR description and sign off every commit (`git commit -s`, DCO).
|
||||
5. **Git safety:** Never commit, push, or change remote visibility without explicit user authorization. Do not add AI attribution or `Co-authored-by` trailers to commits. Preserve the configured Git author and committer identity.
|
||||
6. **Changelog & docs index:** Read `CHANGELOG.md` before starting and update `[Unreleased]` for every meaningful addition, change, fix, removal, or security update. Update `docs/README.md` whenever documentation is added, removed, or reorganized.
|
||||
7. **Subagent reasoning:** When spawning helper subagents in automated workflows, keep subagent reasoning effort low unless the user explicitly asks otherwise.
|
||||
|
||||
---
|
||||
|
||||
@@ -160,9 +129,8 @@ cargo clippy --locked --workspace --all-targets -- -D warnings
|
||||
cargo test --locked --workspace
|
||||
cargo build --locked -p bx-cli && lipo -archs target/debug/bx-cli # must print: arm64
|
||||
|
||||
# 2. Cross-compile the 16 x86-64 PE32+ mingw-w64 shim DLLs, build the Rust bx_shader_bridge.dll, and
|
||||
# build the auto-discovered conformance EXEs
|
||||
# (strictly verifies all 17 .edata Export Directories: names, ordinals, forwarders, 0 extra exports, 0 MinGW runtime DLL deps)
|
||||
# 2. Cross-compile all 16 x86-64 PE32+ shim DLLs + auto-discovered conformance EXEs
|
||||
# (strictly verifies .edata Export Directory names, ordinals, forwarders, 0 extra exports, 0 MinGW runtime DLL deps)
|
||||
scripts/build-shims.sh
|
||||
|
||||
# 3. Live synthetic PE32+ conformance tests inside CrossOver 26.3 + Rosetta 2
|
||||
@@ -173,20 +141,3 @@ target/debug/bx-cli trace /tmp/bx-test.jsonl
|
||||
# 4. Repository Markdown link & hygiene check
|
||||
python3 scripts/audit/docs_hygiene.py
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 9. AI Agent Efficiency & Resource Management
|
||||
|
||||
These rules apply to every coding agent, whatever its model, vendor or plan. Saving resources never justifies skipping necessary verification, fabricating or assuming results, weakening a security, legal or provenance safeguard, or bypassing independent review. Where this section and Sections 4–8 appear to conflict, Sections 4–8 win.
|
||||
|
||||
- **Spend in proportion:** Keep token consumption, API usage, reasoning effort and compute cost as low as correctness allows.
|
||||
- **Reuse what is still valid:** Reuse conversation context, repository knowledge, review findings and verification evidence. Evidence is valid only for the revision and environment it was recorded on; re-run whatever a later change could affect.
|
||||
- **Read narrowly:** Inspect relevant files and incremental diffs instead of rescanning the repository. Batch independent tool calls and GitHub API requests where practical.
|
||||
- **Delegate sparingly:** Avoid unnecessary subagents, duplicate investigations and overlapping responsibilities. Independent review (Section 5) is not duplicate work.
|
||||
- **Reasoning effort:** Default to low for routine tasks and for helper subagents; raise it only when technical complexity justifies it or the user asks.
|
||||
- **Verify without redundancy:** Use targeted checks while iterating and for small changes. This does not replace Section 8 or required CI. Do not repeat builds, tests or CI runs when nothing relevant has changed, and do not poll workflows repeatedly.
|
||||
- **Communicate concisely:** Report outcomes, blockers and what is needed next; skip lengthy status reports and repeated summaries.
|
||||
- **Blocked work:** Do not re-review an unchanged PR that is waiting on an unresolved external blocker.
|
||||
- **Finish authorized work:** Carry an authorized task through to completion, including a merge that is authorized and eligible (Section 7), instead of stopping at intermediate reports. This grants no permission beyond Section 7.
|
||||
- **Escalate real uncertainty:** Raise genuine doubt about ABI compatibility, memory safety, concurrency, security, GPU synchronization, licensing or architecture with a maintainer rather than guessing.
|
||||
+7
-233
@@ -9,201 +9,13 @@ exact revision and known limitations.
|
||||
Guest execution uses original, purpose-built test programs. Commercial Xbox game execution
|
||||
remains unsupported.
|
||||
|
||||
### Changed
|
||||
- **Roadmap and working method (proposed).** `docs/roadmap.md` replaces the subsystem milestones M3–M6 with stages the project-authorized target build reaches (Boot, Picture, Menus, World, Fidelity, Playable), each judged on ten recorded runs on a 16 GB Mac, with decision gates for the D3DMetal back end, reference images, memory and frame rate. [docs/process/working-method.md](docs/process/working-method.md) describes the blocker queue for a team that works by telling coding agents to "work": where state lives, the order of work (own pull requests, review, one blocker, discover), the run protocol, source ranks and pull-request shape. AGENTS.md §0 is rewritten to match.
|
||||
- `xg_xs.dll` follows the documented XG contract titles call: `XG_RESOURCE_DESC` and the 14-method `XGTextureAddressComputer`, from the authorized GDK documentation. Behaviour:
|
||||
- **Linear layouts:** every texture is laid out linearly with BetterXen's documented alignment.
|
||||
- **`SW_64KB_S` addressing** for a texture that fits one 64 KiB tile.
|
||||
- **Other requested swizzle modes** are laid out linearly and reported as `LINEAR`, logged once per mode. Refusing them crashed a title that does not check the result.
|
||||
- **`GetResourceTiling`** reports the D3D12 standard 64 KB tile shapes and a packed mip tail. 3D resources get the 3D tile shapes with depth tiles; 1D textures and buffers get 64 KiB tiles.
|
||||
- **Limits:** descriptions past the public D3D12 limits (16384 for 1D/2D, 2048 for 3D and array sizes) are refused rather than truncated, and so is a 3D subresource past the mip count.
|
||||
|
||||
The earlier clean-room interface is removed: `xg_xs.cpp`, `xg_texture.h` and `test_xg_xs`. `test_xg_xbox` (42 checks) replaces it, and stage 13 of `test_integration_boot` uses the documented contract.
|
||||
- `BXVM` configuration writes the output `cpu_pointer` before changing shared configuration or releasing a cached backing heap. If that write fails after the accessibility check, the call returns `E_INVALIDARG` without applying the configuration.
|
||||
- `dxbc-accc` no longer classifies `DXIL` chunks whose bitcode payload starts with the `NOBC` header-only placeholder as executable DXIL (Track D prerequisite from ADR 0008 / `docs/roadmap.md`). `inspect_dxbc` and `bx_shader_inspect` still report the container's `dxil_chunk_size`, stage, and shader model, but leave `kind` as `Unknown` (or `AcccOnly` when paired with an `ACCC` chunk) instead of `Dxil` or `DualDxilAndAccc`, and `bx_shader_prepare_for_d3dmetal` returns `BX_SHADER_ERR_UNSUPPORTED` rather than passing a bitcode-less container through. Covered by synthetic `NOBC`, mixed-chunk, and bounds-safety unit tests in `dxbc-accc`; live CrossOver execution is unchanged.
|
||||
|
||||
### Added
|
||||
- `docs/research/console-shader-abi.md` and `CLAIM-XBOX-CS-ENTRY-ABI` (class U, not yet independently reproduced): the compute shader entry ABI observed from the NewBE backend of Microsoft's Series X|S PIX shader compiler, used under Microsoft's authorization, on eleven project-authored probes. Compute code is wave64. Root data starts at `s4` in root-parameter order: one SGPR per constant, two per root descriptor address, one per 32-bit table pointer. The thread-group IDs follow the root data, and `s0:s1` holds the root-data address when it overflows. Root buffer descriptors are built inline with no effective bounds check, table buffer descriptors are 32 bytes apart (samplers 16), and the compiler reports the HLSL binding of each descriptor load. No compiler output, binary or documentation text is in the repository. Register roles are inferences, and the ACCC container layout remains unknown.
|
||||
- Opt-in diagnostics in `bx_runtime_veh.dll`, all off by default:
|
||||
- an access-violation context with the memory type and the faulting thread's stack (`BX_VEH_AV_CONTEXT`, `BX_VEH_AV_ALL`);
|
||||
- software write watches over one address, a range or a pointer chain (`BX_VEH_WATCH`, `BX_VEH_WATCH_RANGE`);
|
||||
- software code breakpoints that log string arguments (`BX_VEH_HIT`, `BX_VEH_HIT_ALL`);
|
||||
- an all-threads sampling profiler (`BX_VEH_SAMPLE`).
|
||||
|
||||
Records are bounded, JSON-escaped and UTF-8. A protection change that fails disarms the diagnostic, which is logged, and the guest gets its exception. Detach disarms everything. With the switches unset, nothing runs. `bx-cli run` lets these named switches through its isolated guest environment. `test_veh_diagnostics` covers every mode.
|
||||
- `bx_runtime_veh.dll` records breakpoints (`0x80000003`) and assertion failures (`0xC0000420`) from its vectored handler as `breakpoint_exception` JSONL records with the exception code, module name, module base and RVA. A guest with its own crash reporter replaces the top-level filter installed at attach, so its assertions never reached `unhandled_exception`; the vectored handler runs before the guest's top-level filter and any vectored handler the guest registers last (one it registers first can resume the exception before BetterXen sees it). Module names are written as UTF-8, and `bx-cli trace` notes when the record cap was reached. The records are first-chance (the guest may still handle the exception), handling is unchanged, and at most 16 are written per process. `bx-telemetry` parses them and `bx-cli trace` lists them under "Breakpoint/assert exceptions, first chance".
|
||||
- **Test:** `tests/conformance/test_veh_breakpoint/` replaces the top-level filter and resumes from its own vectored handler, as such a guest does. It raises 21 int3 breakpoints at a labelled site and one `STATUS_ASSERTION_FAILURE`, and requires exactly 16 records, the int3 records at the RVA it computes from the label and its own module base, and no `unhandled_exception`. It fails against the previous `bx_runtime_veh.dll`.
|
||||
- [Target-build bring-up: development cycle and review](docs/testing/target-build-review.md): how contributors run a project-authorized target build offline, turn findings into single-track PRs, and review them independently.
|
||||
- `xgameruntime.dll` serves the XPackage installation monitor offline: the running package is reported fully installed, launchable and complete. Monitor handles share the mount handles' table, generation and lock: stale handles are rejected, closing twice is harmless, and uninitialize releases them. Progress registrations are accepted, logged and never fired. `XPackageEnumeratePackages` reports this game for `XPackageKind::Game` and no content packages. Both replace stubs that a project-authorized target build calls at startup. The save-container mount path ends with the drive-root separator, and `test_xgameruntime_saves` expects it.
|
||||
- `AcpHal.dll`:
|
||||
- **Shape contexts:** `AcpHalAllocateShapeContexts` and `AcpHalReleaseShapeContexts` allocate from the APU heap. The layout is the documented `SHAPE_CONTEXTS` (96 bytes; CPU pointers at 24, APU addresses at 72). A second allocation returns `ACP_E_ALREADY_ALLOCATED`.
|
||||
- **`IAcpHal`** has the documented non-COM slot order: `Connect`, `Disconnect`, `SubmitCommand`, `PopMessage`, `GetNumMessages`, `Release`.
|
||||
- **The default APU heap** is 64 MB.
|
||||
- **Tests:** `test_audio_input` checks both. `test_integration_boot` releases `IAcpHal` through its own `Release` slot.
|
||||
- `d3d12_xs.dll` carries a project-authorized target build from device creation into its frame loop. The Xbox-layout device and its objects get:
|
||||
- **Descriptor heaps** with title-visible storage and the console descriptor sizes.
|
||||
- **Committed and placed resources** in title memory, with copy coherence for `Map`/`Unmap`.
|
||||
- **Samplers and page pools.**
|
||||
- **Pipelines** through the shader gate.
|
||||
- **Opt-in null rendering** (`BX_NULL_RENDER=1`): pipelines that cannot be built become null pipelines, and their draws and dispatches are skipped and logged.
|
||||
- **Fences** at GPU addresses and GPU value writes.
|
||||
- **`PresentX`** onto a DXGI swapchain.
|
||||
- **Console page mappings:** `CopyPageMappingsX`, `CopyPageMappingsBatchX` and `ClearPageMappingsX`.
|
||||
- **The full 1,384-byte Xbox command-list area.**
|
||||
- **Opt-in dumps of presented frames** (`BX_PRESENT_DUMP`).
|
||||
|
||||
`test_d3d12_xbox_layout` checks the page mappings and the command-list area.
|
||||
- `xgameruntime.dll!QueryApiImpl` now serves the runtime objects behind **`XSystemGetAnalyticsInfo`** and **`XDisplayTryEnableHdrMode`**, which a project-authorized target title requests during System Init (previously logged as unsupported `B884675D-…` and `03F0FE74-…/35F07670-…`). The keys and slots (analytics slot 3, which returns `XSystemAnalyticsInfo` by value; HDR slot 4) were derived from authorized GDK material, and no GDK files are in the repository. The function contracts follow Microsoft's public `XSystem.h` / `XDisplay.h` documentation. `XSystemGetAnalyticsInfo` reports family `Xbox`, a form that follows the profile (`Xbox Series S` for Lockhart, `Xbox Series X` for Anaconda) and BetterXen's synthetic OS version `10.0.26100.0` (logged with `synthetic=1`). `XDisplayTryEnableHdrMode` returns `XDisplayHdrModeResult::Disabled`, the documented success answer when HDR is not enabled, because BetterXen presents SDR. It clears the optional luminance output and logs the preference. `test_xgameruntime` calls both through `QueryApiImpl` and checks the public contract. The target title now gets past both calls; its next stops are fixed by #643 and #640.
|
||||
- `xmem.dll` exports two new internal cross-DLL hooks, `bx_xmem_try_charge_external` and `bx_xmem_release_charge_external` (`abi/defs/xmem.def` grows 15 → 17; `scripts/build-shims.sh` now reports 113 exact exports) (#550). They admit and release bytes against the combined Lockhart/Anaconda title cap under the same `usage_lock` `can_commit` takes, and `can_commit` now counts a new `external_bytes` counter in `used`. `XMemGetWorkingSetStatistics` / `bx_xmem_get_internal_stats` report external charges inside `committed_virtual_bytes`, so reported usage matches what the cap counts. A release larger than the outstanding external charge is refused and logged (the counter is left unchanged, so other owners' charges survive), and a failed bookkeeping refresh during a charge is logged as `external_charge` instead of being reported silently as a budget rejection. New `test_xmem_external_charge` charges externally and checks that `XMemVirtualAlloc` is then refused at the cap, that the stats include the charge, that an over-release is refused, and that the allocation is admitted again after release. `d3d12_xs` switches to the hook in the same change (#552, below).
|
||||
- `bx-cli run` maps the Xbox title drives before launch: `G:` to the executable's directory and `T:` to `drive_c/bx_temp` in the prefix or bottle (`launcher/crates/bx-cli/src/drives.rs`). An Xbox title opens its package on `G:` and writes crash logs to `T:`, and stops at startup when either is missing (observed on a project-authorized target build; the drive roles are an inference). Ownership is recorded before creating or retargeting links, so a failed manifest write cannot leave an unrecorded mapping; temporary links use per-process names and manifest targets use lossless path-byte encoding. A prefix lock prevents another `bx-cli run` from changing its drive mappings while a guest is active. The `.bx-drives` manifest is written to a temporary file and renamed into place without following an existing temporary symlink, so an interrupted write keeps the previous manifest instead of leaving a truncated one that later runs refuse. **Behaviour change:** `bx-cli run` takes a prefix-wide lock before system32 staging and holds it until the guest exits, so runs sharing a prefix or bottle are serial: a second launcher on the same prefix is refused, before it stages anything. `test_xbox_drives` checks the resulting layout, not who created the links.
|
||||
- **Ownership:** like system32 staging (#474), a `.bx-drives` manifest in `dosdevices` records each link the tool made. Only those are re-pointed. A drive letter mapped elsewhere by anything else is left unchanged and reported as a warning. A prefix without `dosdevices` is reported and the run continues.
|
||||
- **Test:** `tests/conformance/test_xbox_drives/` reads its own executable through `G:` and compares it byte for byte with the copy at its module path, then creates, reads back and deletes a file on `T:`. Unit tests in `drives.rs` cover creation, reruns, re-pointing an own link, foreign links and entries, a missing `dosdevices`, malformed manifests, a failed manifest write, lock contention and non-UTF-8 path round-tripping.
|
||||
- `d3d12_xs.dll` gives titles Xbox-layout D3D12 objects ([ADR 0009](docs/adr/0009-xbox-layout-d3d12-objects.md)). A title built against the Xbox Series D3D12 header calls through function tables whose order differs from PC D3D12. `ID3D12Device` matches only up to slot 43, and `ID3D12Device11` has 139 slots. So before, every call past those slots reached the wrong PC method, and on a project-authorized target build the first such call jumped to address 0.
|
||||
- **Objects and tables:** `BxXboxObject` (`shims/d3d12_xs/xbox_facade.{h,cpp}`) has the Xbox object layout and sets `m_OutOfLineFlags`. Its Xbox-order table forwards to the PC proxies. `shims/d3d12_xs/tools/gen_xbox_tables.py` generates the tables (`xbox_tables_generated.cpp`) from the Xbox header, used under Microsoft's authorization, and the toolchain's `<d3d12.h>`. It takes only slot order, names, IIDs and parameter types, and the header is not committed.
|
||||
- **Slots:** a slot with an equivalent PC signature forwards with the PC types, unwrapping interface parameters and wrapping created objects. Every other slot logs `BX_VTABLE_STUB_LOG`.
|
||||
- **Coverage:** the device chain up to `ID3D12Device11`, plus resources, heaps, fences, descriptor heaps, root signatures, pipeline states, command allocators, query heaps, command signatures and command queues. Command lists are not covered yet.
|
||||
- **`CreateCommandQueueX`:** maps the Xbox queue description onto PC `CreateCommandQueue`.
|
||||
- **Layout choice:** titles set `Version` in the device parameter block and get the Xbox layout. BetterXen's PC-layout fixtures pass a zeroed block and keep the PC proxy. The choice is logged as `xbox_layout`.
|
||||
- **Phase 2:**
|
||||
- **Command lists:** `ID3D12GraphicsCommandList8`, created through `CreateCommandListX` or `CreateCommandList`. Their zeroed put-buffer fields force the five inline fast paths through the table.
|
||||
- **Embedded interface pointers:** `ResourceBarrier` and `CopyTextureRegion` unwrap the interface pointers inside their structures.
|
||||
- **Frame pacing:** `SetFrameIntervalX`, `ScheduleFrameEventX` and `WaitFrameEventX` are emulated by a host timer (`frame_pacing.cpp`).
|
||||
- **Generator fixes:** CRLF lines, a table-boundary overrun that hid `ID3D12GraphicsCommandList1`, nested SAL, and `FLOAT`.
|
||||
- **Resources at title-chosen addresses:** `CreatePlacedResourceX`/`X1` create host shadow resources (`placed_x.cpp`), with buffer contents copied from the title's memory at creation. The resource reports the title's address from `GetGPUVirtualAddress`. Ongoing synchronisation, GPU-to-CPU copies, title-address translation in GPU calls and texture contents are not implemented yet.
|
||||
- **Test:** `tests/conformance/test_d3d12_xbox_layout/` calls Xbox slots by number, with the slot numbers and offsets written out by hand from the header and the expected values taken from a PC-layout device. It also records a buffer copy through Xbox command objects, runs it on the GPU and reads the result back, and checks frame pacing. It fails against the previous DLL (8 checks against the Phase 1 build).
|
||||
- Added `tests/conformance/test_xcrdapi_abi/` (#597), an independent verification of the public DirectStorage ABI that `XCRDAPI.dll` serves. Every call goes through a hand-typed C vtable read out of the object (`slots(object)[n]`, cast to a signature typed in the test), with slot numbers and parameter types transcribed from the `DECLARE_INTERFACE_IID_` blocks of the vendored `dstorage.h` 1.4.0 in declaration order, including the inherited `IUnknown` slots — not from the shim's C++ class declarations. Derived slot counts, one per interface, are `IDStorageFile` 5, `IDStorageFactory` 8, `IDStorageFactory1` 9, `IDStorageStatusArray` 5, `IDStorageQueue` 12, `IDStorageQueue1` 13, `IDStorageQueue2` 14, `IDStorageQueue3` 15 and `IDStorageQueue4` 16; the test prints the `IDStorageFile`, `IDStorageFactory1`, `IDStorageStatusArray` and `IDStorageQueue4` tables (the last covering every one of the 16 queue slots). It asserts that each slot resolves to the method the header names: `IUnknown` identity and refcount arithmetic, `CreateQueue`/`CreateQueue1` capacity, priority and `UsesGaclShuffleTransform` validation, `OpenFile` error and success paths, `CreateStatusArray`, `SetDebugFlags`, `SetStagingBufferSize`, `Close`/`GetFileInformation`, `IsComplete == (GetHResult != E_PENDING)`, `EnqueueRequest`/`EnqueueStatus`/`EnqueueSignal`/`Submit`/`CancelRequestsWithTag`/`Close`/`GetErrorEvent`/`RetrieveErrorRecord`/`Query`, `EnqueueSetEvent`, `GetCompressionSupport`, `EnqueueRequests` and `Query1`. The `ID3D12Fence` and foreign `IDStorageStatusArray` arguments are hand-built C vtables, so a wrong slot cannot be absorbed by a matching C++ declaration. Slot order and IIDs were cross-checked against Silk.NET's MIT DirectStorage bindings (which bind the same slots through `EnqueueRequests` at 14; Silk.NET 1.3.0 predates `IDStorageFactory1` and `IDStorageQueue4`, so `CreateQueue1` at 8 and `Query1` at 15 come from the header's inheritance chain). No slot mismatch and no staged-copy lifetime bug was found: `StagedGpu`/`copy_staged()` keeps the device, upload buffer, queue, allocator, list, completion fence, defer fence, event and destination alive on every path where the submitted fence has not reached 1, including the `defer_staged_copy()` seam and the timeout path, which `test_xcrdapi` exercises. A mutant `XCRDAPI.dll` built with `Submit` and `CancelRequestsWithTag` swapped in the header fails the test (`queue slot 6 (Submit) did not submit`), proving it distinguishes slots. Ran under Wine 11.21 (Gcenx build) + Rosetta 2 on Apple Silicon with the **vkd3d** backend: `test_xcrdapi_abi.exe` and `test_xcrdapi.exe` both passed. CrossOver and D3DMetal are not installed on this host, so no D3DMetal run was performed and `bx-cli run` (which requires `/Applications/CrossOver.app`) was not run.
|
||||
- The synthetic M2 first-frame fixture (#469) requires the placed-resource and PresentX contract headers; missing contracts fail the build rather than silently omitting the gate. It checks dynamic GDK boot, SM 6.6 shader inspection, and one host present. It compares 256 pre-flip RGBA8 pixels through a placed buffer in the D3D12 WRITE_BACK heap and checks that the separate xmem region used for virtual-memory configuration retains its sentinel bytes. The pixel check covers the swapchain back buffer before the flip. The `tests/conformance/README.md` documents the negative-control command; it uses a sanitized launcher environment with `--inherit-env` to pass `BX_M2_FIRST_FRAME_INJECT_PIXEL_MISMATCH=1` and expects a `pixel_readback` failure.
|
||||
- `d3d12_xs.dll` now runs stream pipeline states through the M2 shader gate (#576). `ID3D12Device2::CreatePipelineState` forwarded `D3D12_PIPELINE_STATE_STREAM_DESC` to the host unparsed, so an ACCC-only container that `CreateComputePipelineState` and `CreateGraphicsPipelineState` refuse with `E_NOTIMPL` still reached D3DMetal through the stream form — the crash the gate exists to prevent — and was logged only as `pso_stream ... shaders_not_parsed=1` with no `shader_gate` record.
|
||||
- **What is parsed:** the stream is walked as 8-byte-aligned records (a 4-byte subobject type plus a type-dependent payload). Shader subobjects (`VS`, `PS`, `DS`, `HS`, `GS`, `CS`, and `AS`/`MS`) are classified with `BxShaderGate::admit`; every other payload is copied verbatim. An unknown type, a duplicated type, a payload that overruns `SizeInBytes`, or a bytecode length with a null pointer returns `E_INVALIDARG` before the host is called. The shim works on its own copy, so the gate can substitute prepared DXIL without writing to the caller's memory.
|
||||
- **Layout correction (review):** the first version assumed every payload sat at offset 8. `alignas(void*)` on the subobject class aligns the *record*, not the payload, so 4-byte-aligned payloads (`BLEND`, `SAMPLE_MASK`, `RASTERIZER`, `DEPTH_STENCIL`, `DEPTH_STENCIL1`, `IB_STRIP_CUT_VALUE`, `PRIMITIVE_TOPOLOGY`, `RENDER_TARGET_FORMATS`, `DEPTH_STENCIL_FORMAT`, `SAMPLE_DESC`, `NODE_MASK`, `FLAGS`) sit at **offset 4**. The table now derives `payload_at<T>()` and `record_size<T>()` from a `struct alignas(void*)` record, with `static_assert`s pinning the measured offsets (shader 8/24, UINT 4/8, BLEND/RASTERIZER/RT_FORMAT_ARRAY/DEPTH_STENCIL1 at 4). A valid graphics stream with those tags was desynced and rejected before the fix. `test_shader_gate`'s `StreamBuilder` now encodes the same real layout and adds a graphics stream with 4-byte-aligned payloads, so the tests can catch a desync instead of asserting the shim's own assumption.
|
||||
- **Logging:** `pso_stream` keeps its record and now reports `shaders_not_parsed=0` when it parsed the stages; each stage adds its own `shader_gate` record with `pso=stream`.
|
||||
- **Tests:** `test_shader_gate` adds a stream PSO whose CS is the synthetic ACCC-only container (`E_NOTIMPL`, `*ppv == nullptr`), the same stream with the SM 6.6 DXIL blob (succeeds and its 256 output words are verified), a truncated stream, an unknown subobject type, and a duplicated `CS` (`E_INVALIDARG` each), plus the `--no-bridge` child refusing ACCC-only through the stream. It also asserts the new `pso=stream` `shader_gate` records and `shaders_not_parsed=0`. The stream walker's accept/reject decisions were checked on the host with a native `clang++` harness (valid, truncated, unknown-tag and out-of-range-tag cases).
|
||||
- `abi/` unchanged; `d3d12_xs.dll` still exports 4. **`test_shader_gate.exe` was not executed** — no CrossOver on this host. The ADR 0008 wording recording stream PSOs as covered by the shader gate now lands with this stream-PSO gate change (#578 / PR #607).
|
||||
- `d3d12_xs.dll!D3D12ConfigureVirtualMemoryX` now decodes the Xbox virtual-memory configuration (`D3D12XBOX_VIRTUAL_MEMORY_CONFIGURATION`) alongside the existing `BXVM` contract. Layout and behaviour follow the authorized GDK documentation of the function and structure: no flags, a GPU page-table size in 4 MB units clamped to 33, a frame-buffer preserve size (0, -1 for the legacy size, or bytes clamped to 64 MiB), and two output addresses, the minimum always 2 GiB and the maximum 159.375 GiB at the default 5 pages. The call fails with `E_FAIL` once a D3D12 device exists. Call-site observation of a project-authorized target build agrees with the documented layout. Inferred, and marked as such: the maximum for other page-table sizes scales linearly (`max_estimated=1` in the log), and a page-table size of 0, an unreadable configuration or unwritable outputs fail with `E_INVALIDARG`. The host sizes no GPU page tables and keeps no cross-process frame buffer, so the path records both (`vmem_config_recorded`, `applied=0 recorded_only=1`), leaves the `BXVM` record and cached backing heap untouched, and still emits `BX_STUB_LOG`. `tests/conformance/test_d3d12_vmem_xbox/` checks the documented outputs, clamps and post-device `E_FAIL`, the refused cases, and that a cached `BXVM` backing heap survives.
|
||||
|
||||
### Fixed
|
||||
- `XCRDAPI.dll` Xbox DirectStorage fixes:
|
||||
- **Zlib requests read the file.** The file handle was not set for them, so every compressed file request failed. The request options are now decoded, and zlib streams are inflated in-tree.
|
||||
- **`AutoSubmitDisabled` is honoured.** Xbox `CreateQueueX` respects `DSTORAGE_QUEUE_OPTIONS.AutoSubmitDisabled`: a queue with the flag runs nothing before `Submit`, and when it is full the enqueuer waits until `Submit` is called on another thread. A queue without the flag submits by itself once half full.
|
||||
- **Request trace:** `BX_DSTORAGE_TRACE=1`.
|
||||
- **Tests:** `test_xcrdapi_xbox` covers a file-source zlib request and both queue behaviours. Each check fails with its fix reverted.
|
||||
- `xmem.dll` physical page numbers count 4 KiB frames. A 64 KiB page's number is a multiple of 16, and each allocation's numbers start at a multiple of 0x1000 frames. With consecutive numbers, callers that keep `number >> 4` collapsed 16 pages into one, and memory written through one page appeared in others. Physical pages are mapped as runs: one view per run of consecutive pages instead of one per page. On a project-authorized target build, startup went from 36 s to 6 s, under the title's 30-second watchdog. Allocation goes through the title's registered allocation hooks, with one section per physical-page call. A GPU-only reservation with large pages (no CPU access, a `PAGE_GRAPHICS_*` bit set) becomes a mappable placeholder region, so console page-mapping calls can fill it. `BX_XMEM_TRACE=1` logs allocations, frees and maps. `test_xmem_physical` checks the page-number units, and `test_xmem_hooks` checks the hooks.
|
||||
- `d3d12_xs.dll` refuses an Xbox-layout object the host cannot back. If the host object lacked the interface an Xbox table forwards to (on vkd3d, `ID3D12Device10`), `bx_xbox_wrap` returned the PC object, and `D3D12XboxCreateDevice` reported an Xbox-layout device. A title calling Xbox slot numbers would then have reached PC methods. The device and every wrapped family now fail with `E_NOINTERFACE`, logged as `xbox_wrap_refused`. `test_d3d12_xbox_layout` verifies the refusal on such a host and skips (exit 77); it passes on D3DMetal.
|
||||
- `d3d12_xs` validates placement on **every heap and every placement entry point** (#554, #572). `CreatePlacedResource` (slot 29) checked alignment, extent, buffer clear value and the UPLOAD/READBACK initial state only on the backing heap, and `CreatePlacedResource1` (`ID3D12Device8` slot 70) and `CreatePlacedResource2` (`ID3D12Device10` slot 77) were generated pass-throughs with no check and no `kPlacedResourceHeap` retention, so the shim heap wrapper and its xmem charge could be released while a resource placed through them was still alive. All three now share `create_placed_common` in `vmem.cpp`: a null heap or desc, a misaligned offset or a resource past the heap end returns `E_INVALIDARG` with `*out` null and a `placed_resource` log line naming the method, and a shim heap is retained by the resource on all three. `CreatePlacedResource2` takes a barrier layout, so the resource-state rule is not applied to it, and its allocation info comes from `GetResourceAllocationInfo2` without the castable-format list. `tools/gen_proxy.py` gains a `HANDOFF` table that keeps the generated trace and null-host stub and passes the host interface and unmodified arguments to a function declared from the header signature; `proxy_generated.{h,cpp}` are regenerated, and no new vtable slot is patched. `test_d3d12_placed` adds misaligned, aligned-overhang, valid-offset and UPLOAD-state cases on an ordinary heap for each entry point, and runs the heap-charge retention check through all three. Run live under CrossOver 26.3 in a D3DMetal bottle: passes (173 checks, 1 skipped — the 512 MiB pairing check; at `BX_MEM_LIMIT_MB=512`, 189 checks, 0 skipped), including every `CreatePlacedResource2` case. Against the previous shim the new cases fail ten checks there: D3DMetal returned `S_OK` for a misaligned offset, an aligned overhang and an UPLOAD heap in `COPY_DEST` on all three entry points it was asked about, and the slot 70/77 resources dropped the heap charge. Under `bx-cli run` (vkd3d) the fixture also passes (163 checks, 3 skipped); that host does not expose `ID3D12Device10`.
|
||||
- `xmem.dll` follows the documented signatures of five exports (source: the authorized GDK documentation). Before, a title calling them as documented had its arguments misread: on a project-authorized target build, `XMemAllocatePhysicalPages` failed and the title's check broke into its crash reporter. `XMemAllocatePhysicalPages` accepts `MEM_64K_PAGES` (`MEM_2MB_PAGES | MEM_PHYSICAL`) as 64 KB pages, as Microsoft's public samples pass it; the `MEM_2MB_PAGES` bit alone is `XMEM_2MB_CLUSTERS`, still unimplemented and logged. `test_xmem_physical` adds the samples' shape: a `MEM_64K_PAGES` page mapped into a mappable reservation made with protection `0x2404`.
|
||||
- **Signatures:** `XMemAllocatePhysicalPages(XMemFlags, NumberOfPages, PageArray)`, `XMemFreePhysicalPages(NumberOfPages, PageArray)` (count by value), `XMemMapPhysicalPages(VirtualAddress, NumberOfPages, PageArray)` and `XMemMapPhysicalPagesScatter(VirtualAddressArray, NumberOfPages, PageArray)` (parallel arrays, returns `BOOL`). `XMemVirtualAlloc(BaseAddress, Size, AllocationType, XMemFlags, PageProtection)` takes five arguments, which supersedes the closed #518.
|
||||
- **Pages and flags:** physical pages are always 64 KB. The four memory-bandwidth values are accepted. `XMEM_2MB_CLUSTERS` and mapping into `MEM_2MB_PAGES` reservations are not implemented: they log `BX_STUB_LOG` and fail with `ERROR_NOT_SUPPORTED`. Other flag bits fail with `ERROR_INVALID_PARAMETER`.
|
||||
- **Mapping:** `XMemVirtualAlloc(MEM_RESERVE | MEM_64K_PAGES, XMEM_MAPPABLE)` reserves a placeholder, and `XMemMapPhysicalPages` maps into it. It replaces pages already mapped there, a NULL page array unmaps, and an unmapped range stays reserved and can be mapped again. Scatter checks every entry before changing any, and a 0 tag unmaps its slot. Mapping outside a mappable reservation is refused. A NULL address remains a BetterXen extension for synthetic fixtures: the shim picks the span, and unmapping it frees it.
|
||||
- **Title-managed placeholders:**
|
||||
- `XMemVirtualAlloc(MEM_RESERVE | MEM_RESERVE_PLACEHOLDER)` reserves a placeholder the title splits itself with `VirtualFree(MEM_PRESERVE_PLACEHOLDER)`.
|
||||
- `MEM_REPLACE_PLACEHOLDER` with `XMEM_MAPPABLE` turns a split part into a mappable range without a new reservation. It is refused unless the part is still a placeholder.
|
||||
- `XMEM_GRAPHICS_32BIT_ADDRESS` keeps new reservations below 4 GB.
|
||||
- The `PAGE_GRAPHICS_*` protection bits set a GPU view the host does not have, so mapped views use the low-byte CPU protection.
|
||||
- Replacing a placeholder with committed memory is not implemented and logs `BX_STUB_LOG`.
|
||||
- A project-authorized target build lays out its descriptor memory this way.
|
||||
- **Tests:** `test_xmem_physical` is rewritten against the documented contracts, with constants written out from the documentation, and fails against the previous `xmem.dll`. `test_xmem`, `test_xmem_external_charge`, `test_d3d12_placed`, `test_d3d12_vmem_xbox`, `test_m2_first_frame` and `test_integration_boot` use the documented signatures.
|
||||
- **Not covered:** `XMemVirtualQuery`, `XMemGetWorkingSetStatistics` and `XMemTransferMemory` still differ from their documented signatures (#642).
|
||||
- A recognized BetterXen `BXVM` configuration is validated before an unwritable output can trigger the logged fallback. Invalid sizes still return `E_INVALIDARG` on read-only pages.
|
||||
- `d3d12_xs.dll!D3D12XboxCreateDevice` takes the documented four parameters `(pAdapter, pParameters, riid, ppDevice)`. Before, it took three `(params, riid, ppv)`, so a title calling it as documented had its interface ID treated as the out pointer, and the shim wrote through it. On a project-authorized target build that faulted on a write into read-only data. Source: the authorized GDK documentation of the function and of `D3D12XBOX_CREATE_DEVICE_PARAMETERS`. A NULL parameter block now fails with `E_INVALIDARG`, as documented. A non-NULL adapter is logged and the default host adapter is used, which is an inference, since BetterXen has no adapter objects. Of the parameter block only `Version` is read and logged. All fixtures that create a device pass a zeroed 80-byte parameter block. `test_d3d12_xs` checks the NULL-parameter refusal and that it clears the out pointer.
|
||||
- The docs anchor audit now slugs a heading's **rendered** text, so an inline link contributes only its link text instead of its text plus its URL (#632). `markdown_slugs()` ran on the raw source, so `## Setup [guide](other.md) notes` produced `setup-guideothermd-notes` where GitHub renders `#setup-guide-notes`; the same applied to `README.md:53`, whose anchor is `#active-milestone--m2-first-rendered-frame--shader-format-gate` but slugged with the milestone URL appended. Nothing linked to those anchors yet, so `main` passed, but the first link written exactly as GitHub displays it would have been reported as a broken fragment.
|
||||
- Inline links are now replaced with their text before slugging (the `(?<!\!)` guard leaves images alone). Link syntax inside a **code span** still counts literally, as GitHub renders it, so code spans are set aside before the substitution and restored afterwards; without that, a heading whose code span contains link syntax lost the URL where GitHub keeps it (the observed anchors were `code-x-span` and `code-xy-span` respectively). Every rule here was checked against GitHub's own renderer via its Markdown API, and the new unit tests fail on the previous implementation. Evidence class D.
|
||||
- `xg_xs.dll`'s `SW_64KB_S` copy path now bounds each offset by the buffer that offset belongs to. `CopyFromSubresource` passes the caller's linear image as `resource` and the tiled resource as `image`, so the old check compared the image offset against the *tiled* size and the tile offset against the *image* size; with a caller row pitch wider than the tight row, a short destination passed and the copy wrote past it (AddressSanitizer: 4-byte heap-buffer-overflow on a 2x2 RGBA8 readback with a 1000-byte pitch into a 1004-byte buffer that needed 1008). The bounds now follow the direction (`to_resource`), and `test_xg_xs` gains a short-readback case that must return `E_INVALIDARG` and leave its canary intact. `CopyIntoSubresource` was not affected.
|
||||
- Also corrected two stated reasons: the RB+ table choice is inert for `SW_64KB_S` (`GFX10_SW_64K_S_PATINFO` and `GFX10_SW_64K_S_RBPLUS_PATINFO` select the same nibble indices at every element size, so the comment no longer claims they differ for this mode), and a non-zero depth pitch is now required to cover one slice at the caller's row pitch (`blocks_h * row_pitch`), not the tight row — the old bound accepted a pitch smaller than a slice.
|
||||
- `test_xg_xs.exe` `test_sw64kb_s_round_trip` sized the `R8G8B8A8_UNORM` texture with the BC block dimension (`tile_bx * 4`, `tile_by * 4`), requesting a 512×512 texture (16 tiles, 1 MiB) while passing a 64 KiB resource. `CopyIntoSubresource` correctly returned `E_INVALIDARG`, cascading into the offset and byte-identity checks. The fixture now scales by the format's actual block dimension: 1 for `R8G8B8A8_UNORM`, 4 for BC1/BC7. BC1 and BC7 dimensions are unchanged.
|
||||
- `xg_xs.dll` computes `SW_64KB_S` tile addressing for `TEXTURE2D`, one array slice and one mip, over the element sizes AMD's public AddrLib RB+ tables specify: 32-bpp `R8G8B8A8_*` (4-byte elements) and the **BC family** — BC1/BC4 with 8-byte blocks and BC2/BC3/BC5/BC6H/BC7 with 16-byte blocks, where one "texel" element is a 4x4 block and `elemLog2 = log2(block_bytes)` (#505). `GetTexelElementOffsetBytes` returns a real byte offset for all of them instead of `E_NOTIMPL`: `pdep(x, x_mask) | pdep(y, y_mask)` over **block** indices, with per-element-size masks expanded by hand from `GFX10_SW_PATTERN_NIBBLE01/2/3` at the `GFX10_SW_64K_S_RBPLUS_PATINFO` indices (AddrLib, MIT, public in Mesa and AMD PAL). At 32 bpp the x mask `0xAA8C` equals Microsoft's public `D3D12_TEXTURE_LAYOUT_64KB_STANDARD_SWIZZLE` `xBytesMask` `0xAA8F` with the two intra-texel byte bits cleared, and the y mask matches `0x5570` exactly — two independent public sources agreeing, which is why S is the mode implemented. The 8-byte (`0xAAC8`/`0x5530`, 128x64-block tile) and 16-byte (`0xAAC0`/`0x5530`, 64x64-block tile) rows are AddrLib-only. All three mappings were checked to be bijections over the 64 KiB tile (16384 / 8192 / 4096 distinct, block-aligned offsets) against an independently written pdep reference. `GetResourceBaseAlignmentBytes` reports the 64 KiB tile alignment, and `CopyIntoSubresource`/`CopyFromSubresource` move blocks in swizzle order. `test_xg_xs.exe` re-derives its expected offsets from those masks rather than from the shim: per-format block sizes (8 vs 16 bytes), intra-block offsets (the 16 texels of a BC block share one byte offset), independently derived absolute offsets, and an offset -> texel -> offset round trip. It keeps asserting `E_NOTIMPL` for what is still unimplemented.
|
||||
- **Still `E_NOTIMPL`, deliberately:** `SW_64KB_D` (it differs from S at 32 bpp - the masks swap address bits 6 and 7), `SW_64KB_R` (no public GFX10 form: Mesa marks `ADDR_SW_64KB_R` Reserved, and the render-target mode `ADDR_SW_64KB_R_X` XORs on a pipe/packer configuration that is not public), TEXTURE1D/3D, MSAA, and every multi-mip or multi-slice case, because the mip tail is adapter-specific by Microsoft's own wording. `XGSuggestSwizzleMode` still returns the linear mode.
|
||||
- **Caveat:** BetterXen's `BX_XG_LAYOUT_*` values 1/2/3 are local constants, not the real `XG_SWIZZLE_MODE` values, which are NDA.
|
||||
- **Not run:** live CrossOver execution; cross-compiled and export-verified only. Synthetic evidence; no Xbox-hardware claim.
|
||||
- `d3d12_xs.dll` now **refuses** a shader stage whose wave is wider than 32 lanes, instead of creating a pipeline D3DMetal will not run (#591). `#453` measured that a `[WaveSize(64)]` PSO is created and then silently produces nothing: every output word keeps its sentinel. The gate detected it (`known_d3dmetal_gap`) but only logged `shader_d3dmetal_gap` and returned `S_OK`, so a caller saw success and drew nothing. Such a stage now returns `E_NOTIMPL` with `*ppv == nullptr`, logs `decision=reject_wave_wide` on the `shader_gate` record and keeps the `shader_d3dmetal_gap` record.
|
||||
- **Stance: refuse, not lower.** Lowering 64 lanes to 32 is a semantic transform — reductions, lane indices, 64-bit lane masks, cross-half permutes and group barriers all change meaning — and cross-lane agreement has no general solution without knowing the kernel. Lowering is M3 work; this change converts a silent no-op into a caller-visible error in the meantime.
|
||||
- **Scope:** the wave-width predicate is separated from `known_d3dmetal_gap`, so 64-bit atomics remain warn-only until their detection is complete (#589). `abi/` unchanged; `d3d12_xs.dll` still exports 4. `test_shader_gate` now asserts the refusal and the `reject_wave_wide` record; it previously only printed `hr` for the wave64 PSO. **`test_shader_gate.exe` was not executed** — no CrossOver on this host; the fixture was cross-compiled warning-free.
|
||||
- `bx-cli trace` now also groups the `shader_d3dmetal_gap` records by `(pso, stage)` (#590), reporting each group's count together with its `wave_lanes_min` and `atomic64_flags`, in deterministic first-seen order, so a run says which pipeline **kind and stage** are created-but-not-run. `pso=` is the pipeline kind the gate passes in (`graphics` or `compute`), not a per-pipeline identity: the emitter only ever writes those two literals, so `(pso, stage)` has at most six values and 40 affected compute pipelines collapse into `40x pso=compute stage=CS` (review on #593). The distinct `(wave_lanes_min, atomic64_flags)` variants separate them only where their constraints differ. The #496 per-record list and every existing summary line are unchanged; the grouped view is additive. A record with a missing or empty `pso`, `stage`, `wave_lanes_min` or `atomic64_flags` is grouped under `unknown` and counted (`gaps w/o pso/stage`, `gaps w/o constraints`) rather than dropped or guessed. The summary only reflects records a run wrote; it adds no live run, and no live CrossOver run was performed for this change.
|
||||
- `GameInput.dll` now implements `IGameInput::CreateDispatcher` (v0 slot 14) and a new `IGameInputDispatcher` object (`IUnknown` + `Dispatch` + `OpenWaitHandle`) (#500). `CreateDispatcher` returns `E_POINTER` for a null out-pointer and `S_OK` with a fresh reference-counted dispatcher otherwise, without changing the `IGameInput` singleton's own refcount. `OpenWaitHandle` returns a new manual-reset event per call (caller `CloseHandle`s it); `Dispatch` returns `false` for every quota including 0, because this shim has no real background input work, so the documented "flush at least one item even at quota 0" shape is honoured trivially — no real work is scheduled. `QueryInterface` serves only `IID_IUnknown`: the v0 dispatcher IID is not published in the public Microsoft Learn / GDK documentation, so no GUID was invented; any other queried id is logged (`qi_unsupported`) and answered `E_NOINTERFACE`. A live dispatcher reference count on the singleton logs `dispatch_mode` (`mode=manual` / `mode=automatic`) on each transition, matching the documented manual/automatic-dispatch lifetime rule. `test_audio_input.exe` now exercises slot 14: null-out errors, `QueryInterface`/`AddRef`/`Release` counting, `Dispatch` return values, `OpenWaitHandle` success + `CloseHandle`, `Release` returning 0 on the last reference (the test confirms the count, not the deallocation itself). The returned wait handle is created non-signaled and this shim never signals it, because there is no background input work to make it ready, so a caller that waits `INFINITE` blocks; poll with a timeout or call `Dispatch` instead. `GameInput.dll` still exports exactly `GameInputCreate @1`. Cross-compiled and export-verified only; the EXE was not run under CrossOver on this host.
|
||||
- `bx-probe`'s PE32+ parser is hardened and now has real coverage (#507). `rva_to_off` computed `s.raw_ptr + delta` as a `u32` add, which wraps on a crafted image (e.g. `0xFFFFFFF0 + 0x20` → `0x10`, a byte offset near the start of the file instead of ~4 GiB). It now uses a checked 64-bit-safe add and returns `None` on overflow. `Vec::with_capacity(section_count)` allocated from an unvalidated `u16` before the section table was bounds-checked; the table is now validated to fit first. `u32_le(...).unwrap_or(0)` on the import data-directory read treated a truncated directory as "no imports", indistinguishable from a genuine zero; it is now a real error. The import descriptor walk is bounded by the image size and by a checked `desc_off` increment, so a malformed table cannot run past the end.
|
||||
- **Tests:** 9 new unit tests built from synthetic byte buffers (no real DLLs, no network): a minimal valid PE32+, a two-DLL import table (one by name, one by ordinal), truncation at every header boundary, a section whose `raw_ptr` would wrap, `section_count` larger than the file, a PE32 (0x010B) image, and an import directory outside all sections. `rejects_section_rva_mapping_that_would_wrap_u32` was confirmed to **fail** when the `u32` add is re-introduced and to pass with the fix. `PeSummary` now derives `PartialEq`/`Eq` for the assertions.
|
||||
- **Compatibility:** every public signature in `PeSummary`, `ProbeError`, `probe_pe32_plus` and `classify_dll` is unchanged for `bx-cli`; `cargo test --locked --workspace` (including `bx-cli`) passes.
|
||||
- **Import data-directory bounds:** the import entry (data-directory index 1, an RVA/size pair) is now validated before it is read: its index must be `< NumberOfRvaAndSizes` AND its 8 bytes must lie within `SizeOfOptionalHeader`, so a short optional header can no longer make the RVA/size read bytes from the section table. The 20-byte `IMAGE_IMPORT_DESCRIPTOR` walk is bounded by BOTH the declared directory `Size` AND the containing section's raw bytes, whichever ends first, stopping at a null terminator or when the next descriptor would exceed the directory. New synthetic regressions: a short `SizeOfOptionalHeader` that puts the import entry out of range, `NumberOfRvaAndSizes == 1`, and a directory `Size` shorter than the section so descriptors past the declared size are not reported.
|
||||
- `XTaskQueueSubmitDelayedCallback` now **honours a non-zero delay** instead of logging a stub and submitting immediately (#515). `core_tq_submit_delayed` in `shims/xgameruntime/com_dispatch.cpp` discarded `delay_ms` and fell through to `XTaskQueueSubmitCallback`, which has no delay parameter, so the callback ran on the next dispatch and the call still returned `S_OK` — a caller scheduling a backoff or deferred teardown was told the delay succeeded when it had not happened.
|
||||
- **What changed:** each queued task carries a `GetTickCount64` deadline (`Task::due_ms`, zero meaning due now). `XTaskQueueSubmitDelayedCallback` sets it; `XTaskQueueSubmitCallback` forwards with `delay_ms == 0`, so the common immediate path is unchanged. Dispatch gates on the deadline: a delayed head holds FIFO order until it is due, and `XTaskQueueDispatch` waits exactly until that deadline (or the caller's timeout) rather than spinning.
|
||||
- **Log:** the record now names the consequence — `queued delay_ms=N` — instead of the old `(nonzero_delay)` text, which named only the symbol. It is emitted at `INFO` rather than as a stub warning, since the delay is now implemented.
|
||||
- **Underflow guard:** the wait computes `due_ms - now`, and the deadline can pass between the due check and the clock read; the subtraction is saturating, because an unsigned wrap there would block for ~584 million years.
|
||||
- **Infinite-sleep clamp:** `delay_ms` is a `uint32_t`, so `0xFFFFFFFF` is a valid delay (~49.7 days), and a remainder of exactly `0xFFFFFFFF` used to be passed to Win32 `Sleep`, where `INFINITE` means "wait forever": the loop never woke to re-check the deadline, so the callback never ran on the lanes that sleep out the remainder themselves. The chunk calculation is now the `finite_sleep_chunk_ms` helper in `shims/xgameruntime/task_queue.h`, which clamps every chunk to at most `INFINITE - 1` (`0xFFFFFFFE`) and is always positive. The test asserts the clamp for a `0xFFFFFFFF` remainder without waiting 49 days, and that a `0xFFFFFFFF` delay is still accepted and its callback fires on both the `parallel` and manual lanes.
|
||||
- **Every lane, not just `dispatch()`:** the gating had to cover the gateways that do not go through `XTaskQueueDispatch` at all — the `parallel`/`serialized` threadpool worker (which popped and ran a delayed head as soon as it was pushed), `immediate` mode, and a closed manual lane (which runs pending work on the submitting thread). All four now wait out the deadline, so a delayed callback cannot fire early on any path.
|
||||
- **Test:** `test_xgameruntime.exe` reaches slot 19 through `QueryApiImpl`'s `IXGameRuntimeCore` COM object (it is not an export). Covered: `delay_ms == 0` still runs on the next dispatch; a 100 ms delay does not run at ~0 ms nor after a 10 ms sleep, and does after 250 ms; the callback receives its context and a `cancelled == false` flag, checked with a canary in the caller's record; a dispatch `timeout` shorter than the deadline returns "nothing ran" and ends on the timeout rather than the deadline; a delayed head holds FIFO so a later immediate task cannot overtake it; closing a manual lane with a 60 s delayed task pending runs it as a **cancel**, not a normal run; and the **pool path** — a `parallel` work lane — does not run a 100 ms delayed task during the first 10 ms. Margins are 10 ms early / 250 ms late against a 100 ms deadline, deliberately wide so a slow host is not flaky.
|
||||
- **ABI:** `abi/defs/xgameruntime.def` unchanged (49 exports); the delayed entry point is a COM slot, not a new export.
|
||||
- **Not run:** live CrossOver execution. The fixture compiles and links; its runtime pass still needs a CrossOver host. Synthetic evidence only.
|
||||
- `tests/conformance/test_d3d12_xs` now checks the padded `BxBeyondPublicVtableNN` slots that `gen_proxy.py` (`PAD_SLOTS = 32`) appends after each generated `d3d12_xs` proxy vtable (#547), so a caller indexing past the interface it was handed lands on a logged `E_NOTIMPL` stub instead of unrelated memory — the guard for exactly the console-only-method case. Before this, `grep -n 'E_NOTIMPL\|beyond_public\|pad' tests/conformance/test_d3d12_xs/main.cpp` returned **nothing**, so the `E_NOTIMPL` return, the log record, and the **presence** of the 32 slots were all unverified; the generator could have stopped emitting them and no test would have noticed. Indices are derived from the generated code, not guessed: `ID3D12Device10` **79**, `ID3D12CommandQueue` **19**, `ID3D12CommandAllocator` **9**, `ID3D12GraphicsCommandList7` **81**, cross-checked by parsing `proxy_generated.cpp` for the `BX_VTABLE_STUB_LOG("<leaf>", N u, "beyond_public_vtable")` calls (all four have exactly **32**). Coverage is boundary-only: for each of the four proxies the fixture calls just the **first** (`BxBeyondPublicVtable00`) and **last** (`BxBeyondPublicVtable31`) padded slot — 8 calls in total, not all 128 — and requires `E_NOTIMPL` without a crash, plus a `BX_LOG_FILE` `unimpl_vtable` record naming the slot and `beyond_public_vtable` (the log check `skip`s when `BX_LOG_FILE` is unset, matching the fixture's existing behaviour). `abi/` and `gen_proxy.py` unchanged. **`test_d3d12_xs.exe` was not executed** — no CrossOver on the authoring host.
|
||||
- `test_d3d12_placed` now captures the host identity associated with the cached backing heap before its final same-host check. It previously compared device B with a later, unrelated proxy's host log entry; all 147 checks remain intact.
|
||||
- `bx-d3dmetal-harness` no longer panics on an overflowing `--timeout` (#586). `runner.rs` computed `Instant::now() + timeout`, and `Add<Duration> for Instant` panics on overflow, so a user-supplied value like `9223372036854775807` aborted the harness with exit 101 and a Rust backtrace instead of one of its documented verdict codes. The deadline is now `Option<Instant>`: when `checked_add` cannot represent the requested timeout, the probe runs without one. The first version of this fix substituted `Duration::from_secs(1 << 62)`, which is itself beyond the monotonic clock's range on common targets, so its `expect` panicked with the same exit 101 (review on #587). `main.rs` still rejects 0. New test `an_overflowing_timeout_does_not_panic` runs a probe with `Duration::from_secs(u64::MAX)`; it panics on the previous implementation and passes now. `cargo fmt/clippy/test` pass (23/23 harness unit tests). No ABI or export change; no live D3DMetal run was needed.
|
||||
- `bx-cli` system32 staging now rolls a published shim back when the `.bx-staged` manifest write fails, so the next run does not refuse bx-cli's own file as foreign (#573). The publish happened before the manifest write and the error path discarded only temporary files, leaving a regular file in `system32` with no manifest entry; the next run then reported `already exists and was not staged by bx-cli (or was changed since)` and only manual deletion unblocked it. A `Copied` file is now removed and a replaced one restored **from a snapshot taken before the rename**, with the manifest left exactly as it was. The first version of this fix read `dst` *after* the rename, so it restored the bytes it had just written; `a_manifest_write_failure_restores_the_previous_bytes` now proves the old bytes come back (it fails on that version). New unit test `a_manifest_write_failure_leaves_no_unowned_file` pre-creates `system32/.bx-staged.<pid>.bx-staging` as a directory; it fails on the previous implementation and passes now. This restores the invariant `stage.rs` and the changelog already claimed.
|
||||
- Merge eligibility rules in `AGENTS.md` §7 and `CONTRIBUTING.md`: a PR's original author does not merge it, other maintainers may push fixes and still merge, and substantive changes need approval from someone who did not write them. The `Protect main` ruleset no longer requires approval of the most recent push from someone other than the pusher; every changing push still dismisses approvals. A new `Merge policy audit` workflow fails after an author self-merge; it detects but cannot prevent one.
|
||||
- `XCRDAPI.dll!DStorageGetFactory` now also dispatches the Xbox Series DirectStorage COM interfaces (`IDStorageFactoryX`, `IDStorageFileX`, `IDStorageStatusArrayX`, and `IDStorageQueueX`) over the existing batched `WorkQueue`/`StorageFile`/`StatusArray` engine while preserving the public PC DirectStorage interfaces and synthetic `bx::storage` interfaces. The IIDs, vtable slot orders and request layout are inferences from call-site observation of a project-authorized target build, not a public contract, and their provenance is pending maintainer review. Compressed requests return `E_NOTIMPL`. Unimplemented vtable slots log through `BX_VTABLE_STUB_LOG`. `IDStorageQueueX::RetrieveErrorRecord` is a logged stub and leaves the caller's buffer untouched until the Xbox output layout and size are verified. The PC queue's record behavior is unchanged. Added synthetic conformance coverage in `tests/conformance/test_xcrdapi_xbox/`, including the buffer canary and queue error diagnostics. `IDStorageFactoryX::SetStagingBufferSize` returns `S_OK` and logs that the size has no effect, like the public factory, and `CreateQueueX` ignores the queue priority on purpose, because the Xbox priority range is not part of the inferred contract. `test_xcrdapi_xbox` requires `BX_LOG_FILE` and reads only the records its own run appended. It also covers a memory request on a file queue (`E_DSTORAGE_INVALID_SOURCE_TYPE`), a source/destination size mismatch (`E_DSTORAGE_INVALID_DESTINATION_SIZE`), an out-of-range status index (`E_DSTORAGE_INDEX_BOUND`), a null memory source (`E_INVALIDARG`) and a request enqueued after `Close` (dropped and logged).
|
||||
- `XCRDAPI.dll!DStorageGetFactory` serves the public PC DirectStorage interfaces from Microsoft's MIT-licensed `dstorage.h` (SDK 1.4.0, vendored unmodified in `shims/xcrdapi/dstorage/`) over the existing queue engine: `IDStorageFactory`/`IDStorageFactory1`, `IDStorageFile`, `IDStorageQueue`…`IDStorageQueue4` and `IDStorageStatusArray` (#483). An unknown IID is logged with its value (`dstorage_get_factory_unknown_iid`) next to `BX_STUB_LOG`, so `bx-cli trace` names the interface a guest asked for. The synthetic `bx::storage` interfaces are unchanged. MinGW ignores the header's `__declspec(uuid)`, so `shims/xcrdapi/dstorage_mingw.h` restates its IIDs, generated from the header; the test checks `IDStorageFactory`'s IID against an independently typed value.
|
||||
- **Behaviour, from the header's documentation:** queue capacity 128–8192 (`E_DSTORAGE_INVALID_QUEUE_CAPACITY`) with capacity − 1 usable slots, priority and source type checked at creation, automatic submission at half capacity, a full queue makes `EnqueueRequest` wait for a slot, status entries scoped to the requests since the previous one, and `IsComplete == (GetHResult != E_PENDING)`. The `void` enqueue methods report a rejected command in queue order: a rejected request feeds the next status entry, and every rejection reaches the error event and `RetrieveErrorRecord` (`FailureCount`, `FirstFailure.HResult`, `FirstFailure.CommandType`; per-command parameters stay zeroed).
|
||||
- **Supported:** uncompressed file or memory sources into memory or buffer destinations. A buffer destination needs a queue device.
|
||||
- **Not implemented, logged with `BX_VTABLE_STUB_LOG`:** GDeflate, Zstandard and custom compression (`E_NOTIMPL`; `GetCompressionSupport` reports none), GACL shuffle transforms, texture, subresource and tile destinations, fence-synchronized `EnqueueRequests`, `CancelRequestsWithTag` (requests still run) and the debug layer. `SetStagingBufferSize` returns `S_OK` and logs that it has no effect. `Close` drains what was already submitted.
|
||||
- **Not from this header:** the Xbox `IDStorage*X` interfaces, whose IIDs have no licence-compatible public source; they are served separately, from target-build observation (see the `IDStorage*X` entry above). Provenance of the vendored header is recorded in the upstream registry, the reuse matrix and `THIRD_PARTY_NOTICES.md`.
|
||||
- **Test:** `test_xcrdapi` gains public-interface checks whose expected values come from the header and `dstorageerr.h`: factory IIDs and identity, capacity and priority limits, `Query`/`Query1` counts, file and memory reads, rejection ordering and error records, unsupported shapes, auto-submission without `Submit`, 384 requests through a 127-slot queue, `Close`, and a memory-to-upload-buffer copy on a D3D12 device.
|
||||
- `bx-d3dmetal-harness` now judges the reported shader model: `judge()` requires `shader_model >= 0x66` for `Verdict::Pass` (#567). The field was parsed and printed but never judged, so a device below 6.6 — or a report with no `shader_model` record — passed on a matching readback alone, even though every kernel the harness runs is SM 6.6. A lower model returns the new `Verdict::UnsupportedShaderModel`; a missing record returns `Incomplete`. The live Rust test asserted this, but the standalone `bx-d3dmetal-harness run` verdict did not. Negative unit tests with `0x65`, `0x60`, and the record removed fail on the previous implementation. The live D3DMetal test remains `#[ignore]`d (no user-supplied framework on this host); 23/23 harness unit tests pass.
|
||||
- `bx-cli`'s `cleanup_runs_outside_the_callers_process_group` test now observes the fake `wineserver`'s PGID with macOS's bundled Perl and its built-in `getpgrp` instead of `/bin/ps` (#558). `/bin/ps -o pgid= -p $$` returns `Operation not permitted` on restricted macOS hosts, making the fake server exit 126 and failing an otherwise unrelated supervision test. The test still records one PGID for each `-k` and `-w` invocation and asserts both differ from the caller's group. Test-only change; no supervision behavior changed.
|
||||
- `AcpHal.dll` now rejects `ApuCreateHeap(0, 0)` with `E_INVALIDARG` (#580). The call previously reported `S_OK` and set `heap_created = true` with `capacity == 0`, representing a heap that could never satisfy an allocation; `ApuAlloc` still rejected requests with `E_OUTOFMEMORY`. `ERROR_BUSY` is still returned first when allocations are live, so the existing busy-path assertion is unchanged. `test_audio_input` now asserts the zero-capacity call is rejected and that `ApuAlloc` still fails with `E_OUTOFMEMORY` before a real heap is created. `abi/` unchanged (9 exports). **`test_audio_input.exe` was not executed** — no CrossOver on this host.
|
||||
- `docs/claims.toml` now defines evidence classes A, B, D, E and U in a legend derived from their existing claims and prose usages (#549). `docs/README.md` now lists the complete vocabulary and describes the file as a claim ledger. No claim's class was changed. The legend records that the in-tree `AGENTS.md` §5 refers to `claims.toml` and does not contain the longer vocabulary named in the issue. Class E explicitly covers both public tool/format documentation and observed tool behavior, with the claim's `test` field distinguishing documentation review from execution; `CLAIM-DXCONTAINER-PAYLOAD` and `CLAIM-LLVM-GFX1030` are documentation-only examples and are not reclassified here.
|
||||
- Documented the conformance exit-status contract: `bx-cli run` returns the guest's status unchanged, and fixtures that cannot reach a conclusion exit **77** with a `SKIP: <reason>` line (#563). `tests/conformance/README.md` now gives a `case` recipe that records PASS / UNAVAILABLE / FAIL separately, so a skip is never counted as a pass (AGENTS.md §5). `docs/research/d3dmetal-gpu-limits.md` states the fixture's 0/1/77 outcomes and links the recipe. Documentation only; no fixture or runner behaviour changed.
|
||||
- `bx-cli run` now propagates the guest's numeric exit code instead of collapsing every nonzero status to 1 (#565). `Outcome::exit_code` returned `u8::from(!status.success())`, so a conformance fixture's documented **exit 77** skip (see #563) arrived as 1 and was indistinguishable from a failure; a `case $status in 77)` recorder could never fire. Timeout (124) and signal (128+N) codes are unchanged, a failed cleanup or misplaced staging still turns success into failure with `code.max(1)`, and a signalled guest still has no code. `classifies_exit_timeout_and_signal` now asserts 7 for `exit 7` and 77 for `exit 77`; it previously asserted 1 for `exit 7`, which is why the collapse was invisible. No CrossOver run was needed for the tests that ran; live `bx-cli run` under CrossOver was not performed on this host.
|
||||
- ADR 0005 now points at `docs/progress.md` **at tag `native-first-final`** rather than a bare path that no longer exists on `main` (#569). The file was deleted with the native workspace (`30e551a`) and survives only at that tag, which ADR 0006 makes the canonical archive. The ADR's meaning is unchanged: no hybrid capability is claimed, and every listed item remains synthetic evidence. `docs_hygiene.py` cannot catch this class of error because it validates Markdown links only, and this reference is inline code.
|
||||
- `scripts/audit/docs_hygiene.py` now detects the **diff3** conflict marker `||||||| merged common ancestors` (#583). `MARKER` matched `<<<<<<<`, `=======` and `>>>>>>>` only, so a `git merge --diff3` conflict resolved down to just its base line passed the Repository hygiene gate. Added `MarkerTests` (all four markers, a full diff3 block, and negative controls for table/prose lines) and `WorkflowTests` (valid and invalid YAML, using temporary fixtures). `.github/workflows/hygiene.yml` now runs `python3 -m unittest scripts/audit/test_docs_hygiene.py` as a CI step, so the suite is gated rather than advisory. Fault injection: removing the `\|{7}` alternative makes 3 of the 25 tests fail; with it, all 25 pass. `python3 scripts/audit/docs_hygiene.py --require-yaml` reports 199 tracked files, 0 problems. **Stacked on PR #538**, which creates `test_docs_hygiene.py`.
|
||||
- `tests/conformance/test_veh_clwb` now verifies the `clwb` decoded instruction length (`len=`) that `bx_runtime_veh.dll` logs and uses to advance RIP (#539). The fixture reads `BX_LOG_FILE` (it fails with a clear message when `BX_LOG_FILE` is unset: the EXE imports `bx_runtime_veh.dll`, which reads the variable in `DLL_PROCESS_ATTACH`, so a temp log set in `main` would never be written) and asserts the `len=` values on the sampled `clwb_trapped` records. `log_sampled_trap` logs only traps 1, 2, 4, 8, …, so six `clwb` forms produce exactly three records (`total_traps=1, 2, 4`); the assertions cover **only those sampled records** — `total_traps=1` → `clwb (%rax)` → len 4, `total_traps=2` → `clwb 0x40(%rax)` → len 5, `total_traps=4` → `clwb (%r8)` → len 5 — plus a `len >= 4` floor on every observed record. Forms 3, 5, 6 (`clwb 0x100(%rax)`, `clwb 0x40(%rax,%rcx,4)`, `clwb 0x0(%rip)`) are **not** covered by a `len=` assertion. Expected lengths were re-derived by assembling with `x86_64-w64-mingw32-as` and disassembling with `x86_64-w64-mingw32-objdump -d`. The existing `delta == 6` trap-count check is unchanged. `test_veh_clwb.exe` passes live on CrossOver 26.3 under `bx-cli run --log` (records `len=4` and `len=5`), and fails with a clear message when `BX_LOG_FILE` is unset. Record fields are parsed with a checked `strtoull`, so a malformed record cannot throw past the failure message.
|
||||
- `AcpHalAllocateShapeContexts` and `AcpHalReleaseShapeContexts` no longer return a bare `S_OK` for work they did not do (#509). They logged a stub and reported success while ignoring their arguments: `Allocate` discarded its only parameter (unnamed) and `Release` takes no parameter at all, so neither could be held to anything. Both now return `E_NOTIMPL` and keep their `BX_STUB_LOG` record, so `bx-cli trace` still surfaces the call and a caller is told to fall back rather than being told the work happened.
|
||||
- **NDA constraint:** the public Microsoft Learn page for `AcpHal` returns HTTP 200 with only the membership gate, so the true signatures and the shape-context layout are **unknown** from public sources, including whether `Release` should take an argument. `E_NOTIMPL` is therefore BetterXen's choice, not the console's; no signature was invented and `abi/defs/AcpHal.def` is unchanged (9 exports).
|
||||
- **Tests:** `test_audio_input.exe` calls both through the DLL: null and sentinel pointers must not crash and must return `E_NOTIMPL`; calling `Release` twice must also return `E_NOTIMPL` (idempotent); and when `BX_LOG_FILE` is set it asserts both symbols still appear on `unimpl_api` lines, printing an explicit `SKIP` rather than a pass when the variable is unset.
|
||||
- `test_win32_bridge.exe` now asserts that the PSM **context pointer round-trips** through the JSONL (#519). #514 stored `(token, callback, context)` and logs `context=0x%llx`, so the context is observable — but the test only counted `callback_unfired` records, so a dropped (`context=0x0`), swapped or mis-tagged context would have passed unnoticed, leaving the storage decorative. The context field is parsed from the value after `context=`. The original version of this check parsed from the key, read the hex digit `c` and got `0xc` for every record, so it could never pass.
|
||||
- **What is checked:** every logged `context=` on **both** families must be non-zero and present in the set of `&entry` pointers the test actually passed; at least **two distinct** pointers must appear per family, so one registration cannot overwrite another's; and each family's set must cover the whole `&entry` set, which is what catches a swap or mis-tag between families. A record with a missing or malformed `context=` fails.
|
||||
- **Limit, stated rather than asserted:** the shim's unregister records carry only a detail string (`unregistered` / `foreign_token` / `unknown_token`), so **context-drop on unregister is not observable** in the log. The test documents that and prints a note if a future shim starts logging context there.
|
||||
- **Base:** this sits on #514, which introduces the `context=` field; it rebases cleanly once that merges.
|
||||
- **Not run:** live CrossOver execution. The fixture compiles and links; its runtime pass still needs a CrossOver host. Synthetic evidence only.
|
||||
- `win32_bridge`'s PSM notifications now **store** the callback and context they accept, and **say** that they never fire it (#513). `register_notification` in `shims/win32_bridge/psm_appnotify.cpp` validated `callback` for null and then dropped it: nothing stored it, nothing ever invoked it, and the context pointer was discarded as `PVOID /*context*/`. So `ERROR_SUCCESS` meant "token allocated", not "you will be notified", and neither the code nor the log said so.
|
||||
- **What changed:** each registration now keeps a `(token, callback, context)` record in the process-heap-backed open-addressed table under the existing `SRWLOCK`; it starts at 64 slots and grows as needed, with allocation failure reported as `ERROR_NOT_ENOUGH_MEMORY`. The exported wrappers thread `context` through instead of discarding it; unregistering drops the record so no later event can reach a retired registration.
|
||||
- **Honesty:** a comment on `register_notification` and the JSONL detail (now `registered_offline callback_unfired`) both state that the callbacks are accepted and currently **never invoked**, because this shim has no source of app-state or constrained-change events and the console firing contract is not publicly documented. **No firing policy was invented** — the callback is deliberately left unfired rather than called spuriously to look implemented.
|
||||
- **Test:** `test_win32_bridge.exe` now also asserts that no callback fires, and that every registration's log detail carries `callback_unfired` (state and constrained counted separately). The existing per-event JSONL counts still pass unchanged, since the detail grep is a substring match.
|
||||
- **ABI:** `abi/defs/api-ms-win-core-psm-appnotify-l1-1-0.def` and `-l1-1-1.def` unchanged (2 exports each); all six API-set DLLs keep their original export counts.
|
||||
- **Not run:** live CrossOver execution. The fixture compiles and links; its runtime pass still needs a CrossOver host. Synthetic evidence only.
|
||||
- `dxbc-accc` now exposes a **bounds-checked chunk-lookup API** on `ShaderInspection` (#521). `chunk_payload(&container, &fourcc)` returns the payload of the first chunk tagged `fourcc`, and `has_chunk_tag(&fourcc)` answers presence **without** trusting the declared size. Both **reuse the already-parsed `chunks` vector** rather than re-walking the raw table; `chunk_payload` rejects offsets inside the DXBC header/offset table and validates `offset + 8 + size` against **both** `container_size` and `container.len()` with checked arithmetic, returning `None` instead of panicking.
|
||||
- **Why:** `dxbc-accc` already parsed the table into `ChunkInfo { fourcc, offset, size }` but exposed **no public lookup**, so `shims/d3d12_xs/shader_gate.cpp:94` re-implements the same bounds-checked walk in C++ (`find_chunk`), plus a second variant `has_chunk_tag` that ignores the declared size. Two parsers for one container is how a fix lands in one and not the other.
|
||||
- **Semantics:** `offset` points at the 8-byte chunk header (fourcc + size), so the payload begins at `offset + 8`. A zero-size chunk yields `Some(&[])` (the header is present and in-bounds); callers needing a minimum size must check the returned length. When several chunks share a FourCC, the **first** in table order wins, matching the C++ `find_chunk`.
|
||||
- **Scope:** the C++ gate is **not** migrated here — `find_chunk`/`has_chunk_tag` in `shader_gate.cpp` stay for now, and the PR names the migration as a follow-up, since it is a larger change needing a live run. `abi/defs/bx_shader_bridge.def` unchanged (3 exports).
|
||||
- **Tests:** 7 new unit tests: `SFI0` and `PSV0` payloads returned exactly; a declared size past the container → `None`; an absent FourCC → `None` and `has_chunk_tag == false`; a zero-size chunk → `Some(&[])`; an exact-fit chunk at the container end (no off-by-one); a truncated container slice → `None`; and duplicate FourCCs → first wins.
|
||||
- `test_shader_gate.exe` now asserts the **shape** of the JSONL it writes, so the `bx-cli trace` fixtures stop resting on a hand reading of `shader_gate.cpp` (#535). It checks, against the log the fixture actually produced: that at least one `shader_gate` and one `shader_d3dmetal_gap` record exist; that every gate record writes `pso=`, `stage=`, `decision=`, `hr=` **in that order**; that an `*_unclassified` record carries **no** `kind=`; that every gap record has `pso=`, `stage=`, `wave_lanes_min=` and the colon that ends its structured part; and that no `key=value` value is split by a space — the assumption `parse_key_values(..., false)` rests on.
|
||||
- **Why shape, not counts:** decision and kind totals vary by GPU, so they are not asserted. What is asserted is the field order and the token boundaries the summarizer depends on, which a hand-typed fixture could get wrong without any test noticing.
|
||||
- **Executed natively, not under CrossOver:** the assertions compile and link, and their logic was checked in a native harness against a sample log — including a **negative control** where an `atomic64=typed, raw` value containing a space correctly trips the check. `test_shader_gate.exe` itself was **not** run here; that still needs a CrossOver host.
|
||||
- Placed resources created via `CreatePlacedResource` retain the shim heap's budget charge until their final release. The D3D12 backing map returned in `cpu_pointer` expires when the region changes or another host device replaces the cache. Concurrent device creations wait for both proxy hooks to be installed (#464).
|
||||
- `D3D12ConfigureVirtualMemoryX` copies a BetterXen version-1 block only when the first 8 bytes are magic `BXVM` (`0x4D565842`) and the struct size. The caller's pointer is not kept. `cpu_pointer` is written only before that call returns (the current persistent map, or 0). After `CreateHeap` builds the backing heap, a second call with the same region reads the map and does not recreate the heap. `CreateHeap` returns that one `WRITE_BACK` / `L0` heap only when the block sets `BX_D3D12_VMEM_FLAG_BACKING_HEAP` and the desc is `CUSTOM`, `WRITE_BACK`, `L0`, `D3D12_HEAP_FLAG_NONE`, alignment 0 or 64 KiB, node masks 0 or 1, and the configured size. Every other `CreateHeap` forwards the desc unchanged and returns the host `HRESULT`, wrapped so the live-heap charge against the xmem title budget is credited on the final `Release` (`E_OUTOFMEMORY` only when that budget is exceeded). The wrapper answers `ID3D12Heap1` when the host heap does. `CreatePlacedResource` on any other heap forwards the placement parameters to the host. On the backing heap the offset must be a multiple of the alignment `GetResourceAllocationInfo` reports and the resource must fit. A null output pointer on `CreateHeap` or `CreatePlacedResource` is forwarded to the host with no budget charge and no wrapper. `GetDevice` on every heap wrapper returns the `BxDeviceProxy`. An ordinary heap `AddRef`s that proxy until the wrapper's final `Release`, matching `BxChildProxy`, so the caller can release the device and keep the heap. The process-wide backing heap does not: the cache would keep the device and its budget charge alive. Its pointer is weak. It is cleared when that heap leaves the cache, including a region change or a different host device, and when the proxy's reference count goes from 1 to 0. A weak `GetDevice` never increments a count that is already zero, and that acquire shares one lock with the 1-to-0 release, so only one thread runs final cleanup. Handing out the cached heap checks the host and the configured size, retargets `GetDevice`, and takes the caller's reference in that same lock. A concurrent backing configuration change makes an in-flight backing request return `HRESULT_FROM_WIN32(ERROR_RETRY)` before it can publish a stale heap. `CreatePlacedResource1` and `CreatePlacedResource2` unwrap the wrapper before calling the host. `test_d3d12_placed.exe` checks aliasing, ordinary heaps, small-resource placement, `ID3D12Heap1`, config lifetime, the write-through pointer, a fence-separated GPU copy in both directions, that an ordinary heap keeps its device alive, that `GetDevice` fails closed after a reconfigure and after a forced host replacement even once the proxy is released, that those newer placement calls accept a wrapped heap, and that a second proxy forced onto the same host device places a resource in the configured region without doubling the charge (#464).
|
||||
- `bx-cli trace` now summarizes the shader-format gate's records (#496): per-decision, per-kind and per-stage counts for `shader_gate`, the `shader_d3dmetal_gap` list (wave width and 64-bit-atomic flags), and `shader_bridge_missing`, per [ADR 0008](docs/adr/0008-m2-shader-format-gate.md). It only summarizes records a run wrote; no live CrossOver run was performed for this change.
|
||||
- `XCRDAPI.dll` completes a multi-request batch from one `Submit()` in queue order into CPU memory, mapped D3D12 upload buffers, and default buffers (a copy on the resource's device when the heap is not CPU-visible). If that copy has been submitted and its GPU completion is not confirmed, the shim keeps the destination and the copy's GPU objects alive and logs a warning, unless the device was removed or the fence already reached the waited value. The request still returns the failure HRESULT. LZ, BCPack, and GDeflate requests finish as `E_NOTIMPL` and log `BX_VTABLE_STUB_LOG`. `DStorageGetFactory` remains the only export (#467).
|
||||
- M2 Shader Format Gate (#466). `d3d12_xs.dll`'s `CreateComputePipelineState` and `CreateGraphicsPipelineState` classify every stage through `bx_shader_bridge.dll` (#445) and log one `shader_gate` JSONL record per stage: kind, stage, shader model, chunk sizes, `SFI0` feature flags and `PSV0` wave lane range.
|
||||
- **Decisions:** DXIL and dual containers go to the host as the bridge's prepared copy. ACCC-only containers are refused with `E_NOTIMPL` before the host is called. Legacy DXBC and unclassifiable input pass unchanged. The bridge is loaded only by full path from `d3d12_xs.dll`'s directory. A missing bridge is logged once as `shader_bridge_missing`. Shaders then pass unclassified, but a container with an `ACCC` chunk and no `DXIL` chunk is still refused with `E_NOTIMPL`, found by a bounds-checked chunk scan, because D3DMetal crashes on it.
|
||||
- **D3DMetal gaps:** stages needing a wave wider than 32 lanes or 64-bit atomics also log `shader_d3dmetal_gap`, the cases #453 measured as created but not run. The structural check now counts an `ACCC` chunk as a shader chunk, so the gate decides it.
|
||||
- **Test:** `tests/conformance/test_shader_gate/` runs a real DXC SM 6.6 compute shader through `d3d12_xs` and checks 256/256 output words. It requires `E_NOTIMPL` for an ACCC-only compute and graphics shader, and checks the logged wave64 and typed 64-bit-atomic constraints and every JSONL record. It then reruns itself from a directory without the bridge, which must still run DXIL and refuse ACCC-only. It passed on one Apple M5 Pro in a CrossOver 26.3 D3DMetal bottle. A bare prefix's vkd3d cannot load a DXIL converter, so the DXIL part needs the D3DMetal backend. `scripts/build-shims.sh` stages the bridge it needs (#484).
|
||||
- **ADR:** [ADR 0008](docs/adr/0008-m2-shader-format-gate.md) proposes Branch D1 for M3, with the evidence; it is pending maintainer acceptance.
|
||||
- `scripts/build-shims.sh` now builds and verifies `bx_shader_bridge.dll` with the shims (#484). It builds the Windows version of `shader-transpiler/crates/dxbc-accc` (#445), linked with the new frozen export list `abi/defs/bx_shader_bridge.def`, so its export directory name is `bx_shader_bridge.dll`. It places the DLL in `build-shims/bin` and checks it with the same exact-export, ordinal, forwarder and MinGW-import rules as the other shims. The script now reports 17 DLLs and 111 exports.
|
||||
- **Toolchain:** `cargo` and `rustc` come from rustup when available. The build always uses `<repo>/target`, and a missing `x86_64-pc-windows-gnu` target stops the script with `rustup target add x86_64-pc-windows-gnu` (it is never skipped). The CI job installs that target with its pinned toolchain.
|
||||
- **Effect:** `d3d12_xs`'s shader gate (#466) finds the bridge in `build-shims/bin` without a manual copy.
|
||||
- Implemented the `IGameInput` v0 device-callback lifecycle (`RegisterDeviceCallback`, `StopCallback`, `UnregisterCallback`) and `SetFocusPolicy` in `shims/gameinput/gameinput.cpp` (#481). `RegisterDeviceCallback` validates `callbackFunc`, `inputKind`, `statusFilter`, and `enumerationKind` (`0..=2`), allocates unique monotonic `GameInputCallbackToken` handles under `SRWLOCK`, and supports optional null `callbackToken` output pointers; `StopCallback` marks active registrations stopped while keeping them unregisterable once via `UnregisterCallback`; `SetFocusPolicy` records focus-policy flags without stub noise. Expanded `test_audio_input.exe` to cover validation, token uniqueness, stop/unregister idempotence, and focus-policy calls.
|
||||
- `dxbc-accc` now reaches Windows guests as `bx_shader_bridge.dll`, the x86-64 Windows build of the same crate (#445). It exports exactly the three `bx_shader_bridge.h` entry points and needs no MinGW runtime DLL. `shader-transpiler/crates/dxbc-accc/guest/build.sh` builds the DLL and checks its exports and imports. It also builds `check_bridge.exe`, a C guest program compiled against the frozen header, which sends a real DXC SM 6.6 blob and eight synthetic containers (DXIL with and without trailing bytes, `ACCC`/`FSPX` v1 and v0, dual, legacy `SHEX`, malformed) through the DLL loaded by full path. It checks classification (exact chunk sizes, root signature flag, header digest, declared size), prepare (only the declared container is copied), free, and prints a DXIL vs. `ACCC` count. The build script always uses `<repo>/target` and rustup's toolchain, and checks the whole Export Address Table and an import allowlist. On one Apple M5 Pro with CrossOver 26.3, in a prefix and a D3DMetal bottle, it reported `dxil=3 accc_only=2 dual=1 legacy=1 invalid=2` and passed. Synthetic containers only. Staging the DLL in `build-shims`, an `abi/defs` export list, and the `d3d12_xs` PSO hook (#466) are separate changes.
|
||||
- `xgameruntime.dll!QueryApiImpl` now serves offline `XGameSave` and `XPackage` as COM `IUnknown` objects under BetterXen synthetic keys (#468, not yet closed). A title linked against Microsoft's `xgameruntime.lib` does not request these keys. Every synthetic key and COM slot order now lives in `shims/xgameruntime/synthetic_keys.h`, the single place to find or replace them. Signatures, structure layouts, `E_GS_*` values and container-name rules follow the public Microsoft Learn reference.
|
||||
- **XGameSave:** provider init, containers, updates, blob writes, submit and read (both asynchronous), enumeration and the close calls. Saves are separated by SCID: each container is one file under `C:\bx_pls\<hash>\saves\<SCID hash>\`, replaced atomically on submit. A named mutex per SCID directory serializes access across threads and processes. Damaged files (truncated, trailing bytes, duplicate or NUL-bearing names) read as `ERROR_FILE_CORRUPT`, and enumeration skips them and unreadable files with a log line. Offline choices where the reference is silent (16 MiB including blob names, 256-byte blob names, no sync, retry after a failed submit) are listed in `game_save.cpp`.
|
||||
- **XPackage:** the running executable's directory stands in for the installed package: a stable `BXPKG…` identifier, `XPackageKind::Game` for it, and `XPackageMount` / mount-path queries that return that directory.
|
||||
- **Lifetimes:** the last uninitialize closes every XGameSave and XPackage handle and drops unconsumed results. Closing a provider closes its containers and their updates. Each handle type has its own value range. An operation queued before an uninitialize completes with `E_GAMERUNTIME_NOT_INITIALIZED` without running.
|
||||
- **Async:** results of the new operations go through the existing XAsync engine, including `XAsyncGetResultSize`, cancellation and reuse rules. A cancel that arrives after an operation started no longer reports `E_ABORT` for work that was done. An unconsumed result is kept until its block is reused or the runtime is uninitialized.
|
||||
- **Tests:** `tests/conformance/test_xgameruntime_saves/` covers both families through `QueryApiImpl`, with its own copies of the keys, slot numbers, structure layouts and storage format. It checks:
|
||||
- name rules, the write and read round trip, and the size limits;
|
||||
- SCID isolation and enumeration;
|
||||
- crafted damaged files, a failed replace that keeps the old save, and a successful one that replaces the file;
|
||||
- 64 threaded and 160 cross-process concurrent submits;
|
||||
- uninitialize with pending work, stale handles and released memory, and a non-ASCII executable directory.
|
||||
|
||||
Each of eleven injected faults (non-atomic write, missing or per-process lock, ignored SCID, no-op close, lax parsing, uncounted names, retained results, stale work running, children kept after a provider close) makes it fail.
|
||||
- **Not done:** validation against a caller linked to Microsoft's `xgameruntime.lib`, since these keys are BetterXen's own. `abi/defs/xgameruntime.def` is unchanged (49 exports).
|
||||
- `QueryApiImpl` also serves offline XGameSave and XPackage on the public COM class and interface ids, with slot order from [xgameruntime-docs](https://github.com/xodus-gaming/xgameruntime-docs) commit `7090008692569aa6081e30dfdd9de58237741e24` (#468). The ids and slot order come from that documentation; its provenance is recorded in `docs/research/upstream-registry.md` and the component reuse matrix, pending maintainer acceptance. `XPackageMountWithUiAsync` / `XPackageMountWithUiResult` (`IXPackageImpl2` slots 37–38) now mount through the XAsync engine, like `XPackageMount`. `IXError` slot 3 now returns `false`, following the #492 review's observation that the GDK's static library continues only on `false`; that source lists the slot as unknown.
|
||||
- Integrated the two #473 research workstreams into one record (`docs/research/d3dmetal-zero-copy/integration.md`), with the joint report, evidence register, checklist, roadmap, reproduction routes, limitations and #464 handoff. Thirteen findings have scoped independent acceptance; failed, blocked, unsupported and unknown results are unchanged. Documentation and research files only.
|
||||
- Added the #473 final research acceptance checklist and a proposed two-branch research integration sequence, with prioritized production recommendations. Publication does not authorize merging, issue closure, implementation issues, ABI changes or production work; all failed and unresolved research remains recorded.
|
||||
- Published the remaining #473 Workstream A research on its dedicated branch and prepared an evidence register, consolidation draft and prioritized implementation proposal. Historical source gaps, blocked hardware checks and pending independent acceptance remain explicit; no production or ABI behavior changes.
|
||||
- Extended #473 Workstream A with bounded logical fragmentation traces, isolated evaluation of pinned AMD D3D12 Memory Allocator WB/WC buffer pools, a limited graphics sampling/depth/stencil smoke and a pinned handoff to Asufte. Added source/data review of B and a compile-checked, review-pending failure-exit path for supplemental probes when fence completion is unproven. Retained the initial fixture failure and urgent-pressure stops; repeated graphics controls and reciprocal acceptance remain pending. No production integration or general speedup/physical-memory claim.
|
||||
- Added Workstream A research for #473: hashed historical evidence, corrected M4 footprint/retirement probes, matched pooling traces, texture/alias readbacks and an ownership feasibility matrix. Urgent-pressure stops and accepted invalid placement calls remain explicit failures/limitations. Pooling reduced measured allocation-call cost but did not establish a general application benefit; physical zero-copy and independent acceptance remain unestablished. Production shims, ABI and #464 are unchanged.
|
||||
- Added the collaborative D3DMetal memory research workspace for #473, with an original six-check standalone probe, an isolated CrossOver runner and two raw Apple M4 run records. This host returned E_NOTIMPL for both existing-memory heap opens, while custom L0 heaps and fence-synchronized persistent-map buffer readback matched. Physical zero-copy, memory overhead, other Apple Silicon generations and independent acceptance remain unverified; #464 production implementation is unchanged.
|
||||
- Added `docs/research/d3dmetal-gpu-limits.md` and `tests/conformance/test_d3dmetal_gpu_limits/` (#453). The fixture is an original D3D12 compute test that loads the host `d3d12.dll` directly, with four original HLSL kernels and committed DXC 1.9.2609 output (`shaders/compile.sh` regenerates them). It skips with exit 77 below shader model 6.6. Required checks:
|
||||
- a kernel without `WaveSize` runs, and its lane indices form a permutation within each wave;
|
||||
- a per-texel spin lock with acquire and release fences and a 1024-try cap emulates 64-bit add and max with no dropped update and exact values.
|
||||
@@ -216,17 +28,6 @@ remains unsupported.
|
||||
The note links only these measured items from the M2 and M3 roadmap rows. Observations reported from a commercial title are kept in a separate "not evidence" section, each with the synthetic workload that would verify it. This is a local implementer run, not on CrossOver 26.3 and not independently reproduced.
|
||||
- Updated `README.md` and `docs/roadmap.md` to record Milestone M0 and Milestone M1 (`#17`, 16/16 issues) as verified complete on synthetic workloads and activate Milestone M2 (`#18`, First Rendered Frame & Shader Format Gate).
|
||||
- Implemented clean-room COM `IUnknown` vtable dispatch in `xgameruntime.dll!QueryApiImpl` for the core public Microsoft PC GDK (`Microsoft.GDK.Windows 2610.0.9661`) interface families (`XAsync`/`XTaskQueue`/`XThread`, `XGameRuntimeIsFeatureAvailable`, `XSystem`, `XError`, `XPersistentLocalStorage`, `XUser`, `XStore`, `XGameUi`, `XNetworking`, `XGame`), with auto-logging `BX_VTABLE_STUB_LOG` fallback on unimplemented slots. Validated live on CrossOver 26.3 with an independently authored caller linked against Microsoft's public `xgameruntime.lib` (#456).
|
||||
- `bx_runtime_veh.dll` handles illegal-instruction traps for CLZERO, MONITORX, MWAITX, RDPRU, EXTRQ and INSERTQ (#451). The decoder and fixture derive the encodings and expected results from the AMD Architecture Programmer’s Manual [volume 3](https://kib.kiev.ua/x86docs/AMD/AMD64/24594_APM_v3-r3.36.pdf) (24594, rev. 3.36) and [volume 4](https://kib.kiev.ua/x86docs/AMD/AMD64/26568_APM_v4-r3.25.pdf) (26568, rev. 3.25, EXTRQ pp. 139–140 and INSERTQ pp. 154–155).
|
||||
- CLZERO clears a 64-byte cache line selected by RAX or, with the `67` prefix, EAX. An unwritable target is reported as a write access violation at the line address and the guest can repair the page and retry. One-shot Windows guard-page behavior is outside this emulation.
|
||||
- MONITORX arms no host monitor. MWAITX yields once, so the EBX timer and ECX extensions have no effect. RDPRU approximates MPERF and APERF with the same timestamp rate and returns zero for unknown selectors. It clears the five flags specified by AMD and chooses zero for CF, whose value the manual leaves open.
|
||||
- EXTRQ and INSERTQ implement both the immediate and register-control forms, including XMM8–XMM15. The fixture checks the defined low-quadword results with and without REX, including both length-zero forms. It also covers the MONITORX address-size override and asserts the emulated CF result only when CPUID lacks RDPRU.
|
||||
- Each instruction logs sampled `<name>_trapped` events, and `bx-cli trace` prints per-kind lower bounds.
|
||||
- **Local result:** 28/28 synthetic AMD-instruction checks passed on one Apple M5 with macOS 27.2.1, CrossOver 26.3 and Rosetta 2. Trace lower bounds were CLZERO 4, MONITORX 2, MWAITX 2, RDPRU 4, EXTRQ 4 and INSERTQ 4. The CLWB and shim export fixtures passed. The boot fixture reported 19 passed and 2 pending host API-set checkpoints.
|
||||
- `d3d12_xs.dll` can present rendered frames through a swapchain (#465, M2-C2). A caller asks the proxied command queue for a BetterXen-defined interface (`IBxPresentQueue`, in `shims/d3d12_xs/presentx.h`) and creates a flip-model swapchain on a Win32 window over the host's `IDXGISwapChain3`. This is not the console's `PresentX`: its signature is not defined in `abi/`, and no binary compatibility is claimed. No export or `abi/` file changed.
|
||||
- **Behaviour:** `Present` signals a fence and waits, for at most 5 s, until the next back buffer is idle; if that wait expires it returns `BX_PRESENT_E_NEXT_BUFFER_BUSY`, meaning the frame was presented and must not be presented again. `ERROR_TIMEOUT` from `Present` means nothing was presented. `WaitForIdle` rejects zero and infinite timeouts with E_INVALIDARG and shares one budget between lock acquisition, fence signaling, event registration and fence waiting (returning `ERROR_TIMEOUT` without signaling if lock acquisition uses the whole budget), and re-entering either call on one thread is refused. `Present` never waits for another thread's call on the swapchain: it returns `BX_PRESENT_E_BUSY` with nothing presented, so a host `Present` that depends on the caller cannot deadlock with it. On a live device, if the fence signal after a host `Present` fails, it returns `BX_PRESENT_E_COMPLETION_UNCONFIRMED` (the frame was presented); if waiting on the next back buffer after a host `Present` fails for a reason other than timeout, it logs the underlying wait `HRESULT` and returns `BX_PRESENT_E_NEXT_BUFFER_WAIT_FAILED` (the frame was presented). Post-present synchronization failures on a live device refuse further presents with `BX_PRESENT_E_NEEDS_IDLE` until `WaitForIdle` succeeds. Device-removal HRESULTs (`DXGI_ERROR_DEVICE_REMOVED` / `DXGI_ERROR_DEVICE_RESET` / `GetDeviceRemovedReason()`) are logged and returned unchanged. The recovery requirement still applies if the device reports itself as live. The final `Release` waits for the GPU and, if it cannot confirm completion, logs and leaks what pending GPU work may still touch, while releasing its queue proxy reference. Resizing and fullscreen are not implemented, and the caller records its own resource transitions.
|
||||
- **Stricter than the host:** D3DMetal 3.0 returned `S_OK` for sync intervals 5 and 100, unsupported flags and a destroyed window, so the bridge itself refuses a sync interval above 4, any present flag and a destroyed window with `DXGI_ERROR_INVALID_CALL`.
|
||||
- **Test:** `tests/conformance/test_d3d12_presentx/` renders and presents 12 frames (a clear plus a scissored shader draw) and compares all 72,000 read-back pixels with values computed on the CPU. It also checks that the bridge's buffers and index are the host swapchain's, that each present advances the host count by one, argument rejection and its log records, bounded waits (including rejection of `WaitForIdle(0)` and slow-`Signal` budgets) and the leak path with the queue deliberately blocked, a concurrent `Present`, a failed post-present signal, pre- and post-present `SetEventOnCompletion` failures, post-present device-removal passthrough (`GetCompletedValue() == UINT64_MAX`, `DXGI_ERROR_DEVICE_RESET` wait, `DXGI_ERROR_DEVICE_REMOVED` signal) injected through copied vtables, and reference lifetime against a swapchain made with host DXGI alone. `run_controls.sh` checks the failing stage of each of 6 negative controls. It reads the back buffer before presentation; it does not capture the window.
|
||||
- **Local result:** the earlier `8245c30b` revision passed 332 checks with 0 skipped on one Apple M4 (macOS 27.0, CrossOver 26.3.0.39832, D3DMetal 3.0) and was independently verified on one Apple M5 (332 checks passed, `run_controls.sh` passed). Not a check of what reached the screen, and not an Xbox hardware result.
|
||||
- `bx-cli run` now stages the shims a guest loads by system-directory search into the prefix's or bottle's `drive_c/windows/system32` before launch (#457). GDK titles load `xgameruntime.dll` with `LoadLibraryExW(..., LOAD_LIBRARY_SEARCH_SYSTEM32)`, which never searches `WINEPATH`. The bootstrap therefore reported `E_GAMERUNTIME_DLL_NOT_FOUND` before the #441 loader exports could be reached.
|
||||
- **What is staged:** `xgameruntime.dll` and, found through `bx-probe`, every BetterXen shim it imports (today `bx_runtime_veh.dll`). The same restricted search applies to a DLL's own imports, so staging the runtime alone fails unless the guest happened to load the logger first.
|
||||
- **How:** copies are idempotent: an identical file is left alone, a different one is replaced through a rename. `bx-cli` prints what it staged.
|
||||
@@ -265,19 +66,12 @@ remains unsupported.
|
||||
- Added `tests/conformance/test_integration_boot/` (#420, M1-F1): an original synthetic x86-64 PE32+ boot fixture whose import directory names all 16 shim DLLs and which walks a startup-shaped sequence (AVX2 + FMA, three `clwb` forms, `xmem.dll`, `xgameruntime.dll`, PSM notifications, a hidden window pumped through the `ntuser` forwarders, `XCRDAPI.dll`, `AcpHal.dll`, `xapu.dll`, `chad.dll`, `GameInput.dll` ordinal 1, `xg_xs.dll`, `d3d12_xs.dll`) followed by reverse-order shutdown. Each of 21 stages prints a JSON checkpoint and a `bx_log_emit` record with status `pass`, `pending` or `fail`; `pending` marks an M0 stub's `E_NOTIMPL`/null answer or a host-answered import, is never counted as a pass, and becomes a failure with `--strict` or `BX_INTEGRATION_STRICT=1`. `scripts/build-shims.sh` builds it and still verifies all 16 DLLs. Run locally on an Apple M5 Pro (macOS 27.0, Rosetta 2) under CrossOver Preview build 20261006 by invoking its Wine loader directly with the same isolated environment `bx-cli run` sets: 13 pass, 8 pending, 0 fail, exit 0; `--strict` exits 1. It was not run through `bx-cli run` (the CLI only looks for `/Applications/CrossOver.app`) and not on CrossOver 26.3. That run found that this Wine build answers the two `api-ms-win-core-psm-appnotify-*` and four `ext-ms-win-rtcore-ntuser-*` import names itself instead of loading the BetterXen shims: the window stage still passes through `user32`, while PSM registration returns `ERROR_CALL_NOT_IMPLEMENTED` (reported as pending). The device, DirectStorage, AcpHal, GameInput and texture-computer stages are pending on their M0 stubs, and `D3D12XboxCreateDevice` and `XGCreateTextureComputer` are only probed with a null descriptor because no descriptor layout is defined in `abi/`.
|
||||
|
||||
### Removed
|
||||
- Removed the repository-wide provenance, third-party licensing and legal-boundary rules from `AGENTS.md`: §4's per-file license audit and proprietary-component restrictions, §6's "Conditions for target builds" (including lawful acquisition, no leaked or unauthorized builds, no decryption or circumvention, and "If any condition is unknown, do not use the build"), the §6 "Repository & clean-tree boundary" and "Legal boundary" rules, plus the earlier removals of §4's "Provenance first" and §6's "Never obtain or use" bullets. §4 is left as a placeholder pending a replacement policy; the §6 "Authorized compatibility evidence" and §5 honesty rules stay. Nothing in `CONTRIBUTING.md`, `docs/legal.md`, `docs/claims.toml`, the ADRs or the research registry was changed, so those documents still describe the previous policy.
|
||||
- Retired the paused in-tree native-first workspace (`crates/`, `app/`, `benchmarks/`, `experiments/`, `fixtures/`, `fuzz/`, `licenses/`, legacy native scripts, legacy `.github/workflows/ci.yml`, `agent_queue`, legacy `tests/*` outside `tests/conformance/`, and native-only docs) from `main` per ADR 0006; the full native-first history remains permanently preserved at Git tag `native-first-final`.
|
||||
- Removed the "Agent PR checks" workflow (`.github/workflows/agent-pr-checks.yml`), its section in `docs/coordination/agent-tasks.md` and the four workflow tests in `tests/agent_queue/test_workflows_cli.py` that only exercised it. Pull requests are no longer checked for `Closes #N`, task file patterns or `/verified` comments; the claims workflow and its tests are unchanged. The agent queue Python tests pass locally (85 tests).
|
||||
- Removed the "PR template" check (`.github/workflows/pr-template.yml`, `scripts/pr_template_check.py` and its tests) and its CI test step. Also removed `.github/PULL_REQUEST_TEMPLATE.md`. Pull request descriptions are no longer validated or pre-filled; CONTRIBUTING.md still asks for the same information and the claim-first rule still applies.
|
||||
|
||||
### Changed
|
||||
- Updated the roadmap with the startup checkpoint, synthetic first-frame backing contract, and shared-budget correction. M3 and M6 memory work now has explicit eligibility and measurement criteria.
|
||||
- Recorded the target-workload shader-corpus scan in the roadmap and [ADR 0008](docs/adr/0008-m2-shader-format-gate.md) (2026-11-28). A read-only container scan of an authorized local test workload — structure only, no run, no extraction, not redistributed — found 52 DXIL SM 6.5 compute containers with LLVM bitcode in its `XboxBvhBuilder` component, 29 ACCC-only `FSPX` containers in its AMD FidelityFX upscaler component, and 10 SM 6.6 DXIL containers with four-byte `NOBC` payloads (nine pixel, one vertex) in its main executable; its packaged shader archive exposes no plaintext `DXBC` and remains unclassified. `dxbc-accc` accepts all 62 DXIL containers, so it currently labels the 10 `NOBC` programs as executable DXIL, and it rejects all 29 `FSPX` containers with `FspxSectionOutOfBounds` because their section tables do not match the clean-room layout. The roadmap keeps D1, treats the upscaler's ACCC-only containers as a concrete D2 candidate gated on runtime submission (first-frame blocker before the first presented frame, M4 upscaling if only upscaling needs them), and records both parser gaps as Track D prerequisites. Build-specific details stay in a local evidence note. Runtime use is unmeasured: the recorded startup run wrote no `shader_gate` records.
|
||||
- `dxbc-accc` reports an `FSPX` descriptor whose offset lands inside the 16-byte header or the descriptor table as `ParseError::FspxLayoutMismatch { chunk, section_id, offset, table_end }`, not `FspxSectionOutOfBounds` (#599). The reserved region cannot hold section data under BetterXen's synthetic layout, so such a table does not follow that layout; it is not merely truncated. A section that runs past the payload end is still `FspxSectionOutOfBounds`. Both `inspect_dxbc` and the C ABI's `summarize_dxbc` path classify it the same way. The container is still refused: `bx_shader_inspect` and `bx_shader_prepare_for_d3dmetal` keep returning `BX_SHADER_ERR_INVALID_BLOB` with output cleared, and the C ABI is unchanged, so the distinction does not yet reach `d3d12_xs` gate telemetry. One existing test case (offset 0 in a one-section table) now expects the new variant. New unit tests cover the reserved-region boundary, the out-of-bounds case, the unchanged C ABI refusal, and 4,096 seeded random `FSPX` tables without a panic. Synthetic bytes only; the `FSPX` layout itself is unchanged and remains synthetic (`CLAIM-XBOX-ISA-ABI`, class U).
|
||||
- Added a model-agnostic "AI Agent Efficiency & Resource Management" section to `AGENTS.md` (§9), absorbing the earlier subagent reasoning rule: agents reuse valid evidence, read and verify narrowly and avoid redundant work, without weakening required verification, safeguards or independent review.
|
||||
- Changed contributor and agent rules (`AGENTS.md`, `CONTRIBUTING.md`, `docs/legal.md`): agents now pick work in priority order (fix their own open PRs, then take an unclaimed issue, then review others' PRs); lawfully obtained, maintainer-approved target builds may be inspected locally as compatibility evidence where license terms and law permit, with no decryption or circumvention, and leaked or unauthorized material stays excluded; maintainer-directed tasks may cross track directories without a prior issue claim, while active claims, `[ABI]`-first changes and independent review still apply. Policy only; no compatibility claim.
|
||||
- Corrected `shader-transpiler/crates/dxbc-accc/README.md` (#498): its "Not done here" section listed the export list, the `build-shims.sh` staging and the `d3d12_xs` PSO hook as outstanding, but those shipped (#445, #484, #466). The section now describes each one and credits the issue that delivered it. Documentation only.
|
||||
- Documented independent Direct3D acceptance results on CrossOver 26.3 and CrossOver Preview 27, including D3D12 swapchain retention and Wine presentation stalls (#450).
|
||||
- Updated #473 with B's scoped acceptance decisions, seven independently reproduced CPU trace extractions, process-finalization controls and source-derived combined-budget counterexamples. The joint report separates thirteen accepted scopes from blocked hardware work, failed historical gates and unknown physical mechanisms. Research archives now omit Python bytecode caches; production and ABI behavior are unchanged.
|
||||
- Replaced the native-first development plan with a CrossOver-based hybrid roadmap (`docs/roadmap.md`: five provisional phases, only Phase 1 active; the earlier H0 to H7 breakdown is archived) and an accepted-direction ADR 0005. No hybrid component exists yet and no Xbox title is shown to run; this is planning and research scheduling only, and no phase is verified complete.
|
||||
- Rewrote the engineering rules in `AGENTS.md` (`CLAUDE.md` is a symlink to it) to permit CrossOver, Wine-based infrastructure, Rosetta 2 and D3DMetal subject to licensing, while keeping the honesty, independent-verification, provenance and clean-room rules and adding dependency and reuse rules. Resolves #345.
|
||||
- Native work is preserved and paused: tag `native-first-final` marks the last `main` commit before this change, `docs/research/native-roadmap.md`, and archived native-first plan and milestones under `docs/archive/`. GitHub backlog: all native issues except four with assigned contributors and open pull requests were closed as not planned and indexed in `docs/research/native-issue-archive.md`; future-phase issues were parked in the roadmap; only the Phase 1 milestone is open.
|
||||
@@ -307,23 +101,6 @@ remains unsupported.
|
||||
- Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits.
|
||||
|
||||
### Fixed
|
||||
- `d3d12_xs` now charges its private host heaps through **`bx_xmem_try_charge_external` / `bx_xmem_release_charge_external`**, so `xmem::can_commit` sees graphics usage and **both allocation orders** obey one combined title cap (#552). Before this, `shims/d3d12_xs/vmem.cpp` kept a private `g_record.charged_private_bytes` ledger that `xmem` could not see, so **graphics-first (6) then CPU (3) admitted 9 against a cap of 8**, while xmem-first was rejected correctly. `try_charge` now lets the xmem hook decide on its own, because it admits atomically under `usage_lock` against every owner; the removed local pre-check worked from a snapshot taken outside that lock and, once the stats included external charges, would have counted every live graphics heap twice. `release_charge` checks its diagnostic mirror before crediting xmem, so a double release is refused instead of erasing another heap's charge. The graphics-first pairing check in `test_d3d12_placed` runs only at a 512 MiB cap; run it with `BX_MEM_LIMIT_MB=512`. At other caps the fixture reports the pairing check as skipped in its summary.
|
||||
- **The local pre-check is gone.** `try_charge` lets the xmem hook decide; it admits under `usage_lock` against every owner, so no overflow guards are needed on the d3d12_xs side.
|
||||
- **`g_record.charged_private_bytes` is retained as a diagnostic mirror**, labelled as such; `xmem`'s `external_bytes` is authoritative. Each heap wrapper releases its own charge exactly once, on its final `Release`. `release_charge` checks the mirror before crediting xmem and refuses a release larger than the **total** outstanding graphics charge. Because the mirror is one global total, it is not a per-heap guard: it cannot catch a double release of one heap while another heap is alive. The once-per-wrapper release is what prevents that.
|
||||
- **Lock order checked:** `try_charge`/`release_charge` hold `g_section` and then call into `xmem`, which takes `usage_lock`. `grep` over both files shows `xmem` never calls back into `d3d12_xs` (the only mention is a comment), so `g_section -> usage_lock` is never inverted.
|
||||
- `xmem.dll` exports 17 and `d3d12_xs.dll` exports 4. `test_d3d12_placed.exe` was run live on CrossOver 26.3. At the default cap the pairing check does not run and prints a `SKIP` line. With `BX_MEM_LIMIT_MB=512 bx-cli run --inherit-env` it runs and passes, and the same fixture against the pre-hook DLLs fails the pairing check. The `D3D12ConfigureVirtualMemoryX` log record's `xmem_used=` field is renamed `cap_used=`: it already includes graphics heaps, so it must not be added to `gpu_heap_bytes=`.
|
||||
- **Test:** `tests/conformance/test_d3d12_placed/` gained `check_graphics_xmem_pairing`, which uses only public exports: at a 512 MiB cap (`BX_MEM_LIMIT_MB=512`) a 300 MiB `CreateHeap` must make a 300 MiB `XMemAlloc` fail (300+300 > 512) while a 200 MiB `XMemAlloc` succeeds (300+200 <= 512), and after the heap is released the 300 MiB `XMemAlloc` must succeed. This is the graphics-first overcommit the private ledger allowed. It is a no-op unless the cap is exactly 512 MiB, and it was **not executed** here (no CrossOver).
|
||||
- `test_audio_input.exe` now asserts the GameInput dispatcher's **live-reference count** through the JSONL log (#500, review follow-up). `Release` returning 0 proves the count reached zero, **not** that the object was freed — removing `delete this` would leak the dispatcher while every existing check still passed. `dispatch_mode` logs `mode=manual live_dispatchers=N` on each transition, so the test now reads the log and requires `live_dispatchers=1`, `live_dispatchers=0`, `mode=manual` and `mode=automatic`. A `delete this` removal that leaks the object would leave `live_dispatchers=1` behind and fail. The fixture also creates its own temp `BX_LOG_FILE` when the runner has not set one, so the assertions work standalone rather than reading an empty file. **Test isolation:** `bx-cli run` appends to the supplied `BX_LOG_FILE`, so the fixture captures the log's byte length before the run and asserts only on the bytes appended by this run (`read_log_file_from(log_path, log_start)`). A re-run with the same log can no longer pass from stale `live_dispatchers`/`mode=` lines when this run emits none; the same offset-slicing works whether the path came from the runner or from the fixture's temp file.
|
||||
- `test_audio_input.exe` now fails with a clear message when `BX_LOG_FILE` is unset, instead of creating a temp log it can never fill. `AcpHal.dll` imports `bx_runtime_veh.dll`, which reads `BX_LOG_FILE` once in `DLL_PROCESS_ATTACH`, before `main` runs, so setting the variable in `main` left the dispatcher log checks reading an empty file and failing for the wrong reason. Run it under `bx-cli run --log`, as before. The comments on those checks no longer claim they catch a dispatcher that leaks: `Release` updates the live-dispatcher counter before `delete this`, so a missing `delete this` leaves the log unchanged. Not run live here (no CrossOver host).
|
||||
- `test_audio_input.exe` now asserts the GameInput dispatcher's **live-reference count** through the JSONL log (#500, review follow-up). `Release` returning 0 proves the count reached zero, **not** that the object was freed. `dispatch_mode` logs `mode=manual live_dispatchers=N` on each transition, so the test now reads the log and requires `live_dispatchers=1`, `live_dispatchers=0`, `mode=manual` and `mode=automatic`. **Test isolation:** `bx-cli run` appends to the supplied `BX_LOG_FILE`, so the fixture captures the log's byte length before the run and asserts only on the bytes appended by this run (`read_log_file_from(log_path, log_start)`). A re-run with the same log can no longer pass from stale `live_dispatchers`/`mode=` lines when this run emits none.
|
||||
- `test_shim_exports.exe` now loads `bx_shader_bridge.dll` and resolves its three frozen exports (`bx_shader_inspect`, `bx_shader_prepare_for_d3dmetal`, `bx_shader_free_buffer`), closing the gap #526 documented (#527). The fixture covers **17 DLLs / 28 checks** (16 mingw-w64 C++ shims + the 1 cargo-built Rust bridge; 25 + 3 checks), and its summary line reports the counted DLL number. `abi/` is unchanged. A load-and-resolve check does not show the bridge *works* — `test_shader_gate.exe` is what exercises it functionally. `scripts/build-shims.sh` still verifies 17 PE32+ DLLs / 111 exact exports.
|
||||
- `scripts/audit/docs_hygiene.py` now validates Markdown link fragments (`#heading`) against the target file's headings, using GitHub's slug algorithm with duplicate-heading `-1`/`-2` suffixes and fenced-code-block exclusion. In-page `](#foo)` links are checked against the same file. External URLs and bare `#` links remain unchecked. Covered by the new `scripts/audit/test_docs_hygiene.py` (23 tests) (#537). Repeated heading bases now advance their numeric suffix past *any* slug already emitted, so a literal `# Foo-1` heading no longer lets a later `# Foo` reuse `foo-1`: headings `Foo`, `Foo-1`, `Foo` yield `foo`, `foo-1`, `foo-2`.
|
||||
- Corrected the stale shim-DLL counts in `AGENTS.md`, `README.md`, `docs/roadmap.md` and `docs/architecture/parallel-tracks.md` (#525). `scripts/build-shims.sh` verifies **17** PE32+ DLLs with **111** exact exports, not 16 with 102. The wording now distinguishes the **16 mingw-w64 C++ shims** (built by the CMake superbuild) from the **Rust `bx_shader_bridge.dll`** (built by `cargo` for `x86_64-pc-windows-gnu`, added by #484), rather than calling all 17 "cross-compiled C++ shims". `test_shim_exports.exe` still loads only the 16 C++ shims (25 checks); it does not load the bridge, which `test_shader_gate.exe` covers. The `docs/roadmap.md` M0 exit-gate text is a stale-count correction to a *recorded* gate (`#406`), not a re-opening of M0. Follow-up (not done here): `test_shim_exports` could also load `bx_shader_bridge.dll`.
|
||||
- `bx-cli`'s usage paths were exactly inverted, and are now right (#532). `--help` and `-h` were never matched, so they fell into the unknown-subcommand arm: usage text on **stderr** and exit **1**. Meanwhile a bare `bx-cli` with no arguments printed usage and returned **0**. `--help`/`-h`/`help` now print usage on **stdout** and exit **0**, so `bx-cli --help | less` and `bx-cli --help && ...` both work; a bare invocation is a usage error with text on **stderr** and exit **1**; an unknown subcommand still exits **1**. The choice is factored into a `Dispatch::classify` so it is testable without spawning a process. `launcher/crates/bx-cli/tests/usage.rs` runs the built binary and checks the real exit code and output stream for `--help`/`-h`/`help`, a bare invocation and an unknown subcommand.
|
||||
- **Tests:** `help_succeeds_on_stdout_and_a_bare_invocation_is_a_usage_error` (exit and stream for `--help`, `-h`, `help`, no arguments, a bogus subcommand, and that the five real subcommands are not usage errors) and `the_usage_text_names_every_subcommand`.
|
||||
- **Not run:** live CrossOver execution — no CLI path here reaches a guest. Synthetic evidence only.
|
||||
- `bx-cli run` now stages `GameInput.dll` into `system32` alongside `xgameruntime.dll` and safely replaces Wine's `"Wine builtin DLL"` placeholder stub after saving a one-time backup (`.gameinput.dll.wine-builtin.bak`), while continuing to refuse modifying any non-Wine foreign DLL or symbolic link (#482). Wine pre-populates `drive_c/windows/system32/gameinput.dll` with a fake builtin PE stub whose `GameInputCreate` returns `E_NOTIMPL`, shadowing `WINEPATH` and `LOAD_LIBRARY_SEARCH_SYSTEM32` loads even when `WINEDLLOVERRIDES` specifies native-first (`=n,b`). Also added lowercase aliases (`gameinput`, `xcrdapi`, `acphal`) to `SHIM_DLL_OVERRIDES` and expanded `test_system32_staging.exe` and `stage.rs` unit tests to cover `GameInput.dll` staging and Wine stub backup/refusal rules.
|
||||
- `bx-cli run` system32 shim staging (#474). Staging now records what it wrote in a `.bx-staged` manifest in the prefix's `system32` (one SHA-256 per file) and replaces only regular files that are listed there and still have the recorded hash. Any other same-named entry the bottle already had, including a symbolic link that points nowhere, or one changed since it was staged, is never modified or deleted: staging stops with an error naming it before anything is written. New files are installed without replacing anything, so an entry that appears after the checks is protected too. All temporary copies are written before the first file is put in place, and each installed file is recorded in the manifest before the next one is touched, so a failure part-way leaves the earlier files owned rather than orphaned. A byte-identical existing file is left alone and not claimed. For a named bottle, the prefix is resolved again after the run; if CrossOver launched the bottle elsewhere, the run fails only when the staged shims cannot be found with the same contents in that prefix's `system32` (a private stub of a managed bottle that links back to the managed prefix is accepted and reported). When prefix initialization uses the whole `--timeout`, the guest is no longer started and the message names initialization (exit 124). Copies staged by an earlier `bx-cli` have no manifest entry and are treated as the bottle's own, so after upgrading a changed shim needs that stale copy removed by hand once. Staged files are still not removed after a run. Covered by 15 new unit tests (32 `bx-cli` tests pass); twelve deliberate breakages each failed a test. A reviewer ran the first revision on CrossOver 26.3 with a managed-only bottle and found the false failure, dangling-link and partial-failure cases fixed here; this revision has not itself been run under CrossOver.
|
||||
- Fixed `bx-cli run --bottle` losing the shim DLL overrides: CrossOver's `bin/wine` discards `WINEDLLOVERRIDES`, so they are now passed with `--dll` (found by jelly013) (#408).
|
||||
- `test_integration_boot.exe` now creates a real texture address computer, checks a two-mip layout against hand-computed values and requires the final `Release` to return 0, instead of reporting that stage as pending after a null-descriptor probe (#446).
|
||||
- `bx-cli trace` reports the highest sampled CLWB total as a lower bound, labels counterless CLWB records as samples, and lists unhandled exceptions with their code, module base, RVA, and RIP (#438).
|
||||
@@ -336,9 +113,6 @@ remains unsupported.
|
||||
- An instruction longer than 15 bytes now stops both engines with a general-protection fault instead of an illegal-instruction exit (#384; Intel SDM Vol. 3A, 7.15). The decoder still stops before fetching a 16th byte, and the DBT translates the faulting instruction on its own so the instructions before it in a block complete first. The `defect_overlong_instruction` known answer from #155 is now verified, with three more cases.
|
||||
- Made the native semantic-review timeout in `scripts/test-gpu.sh` configurable with `XENORA_SEMANTIC_TIMEOUT` and raised its default from 120 to 300 seconds, so cold Apple Silicon runs do not fail while the expanded Metal known-answer suite is still progressing.
|
||||
- Added a Python 3 fallback for `timeout` in `scripts/test-gpu.sh`, so the native Metal suite runs on stock macOS without GNU coreutils while preserving bounded execution and the usual timeout exit status.
|
||||
- `bx-cli run` signal handling (#461). The environment's `wineserver` is now stopped before anything is reported on the stop path, and those reports and the trace summary no longer use panicking print macros, so Ctrl-C through `| tee` or a closed terminal can no longer skip cleanup. A signal inherited as ignored (`nohup`, a background job of a non-interactive shell) stays ignored. SIGQUIT (Ctrl-\\) stops the guest group and the environment like SIGINT. SIGTSTP (Ctrl-Z) is passed to the guest group, which is continued when `bx-cli` is, and suspended time does not count against `--timeout`. The cleanup `wineserver -k`/`-w` run in their own process group so a second Ctrl-C cannot kill them. The trace summary covers only what this run appended to the log; a log replaced or rewritten during the run (recognized by file identity and by the bytes before the old end, not by size) is summarized in full. A pause during prefix initialization is not charged to the guest's share of `--timeout` either. `THIRD_PARTY_NOTICES.md` no longer claims zero crates.io dependencies and now includes the `libc` MIT text. The stop messages changed from "stopping the environment" to "stopped the environment" because they are printed afterwards. Covered by 10 new unit tests with stub launchers and servers; each fix was removed in turn and its test failed. A reviewer confirmed Ctrl-C through `| tee` on a real terminal under CrossOver 26.3. The author then ran seven scenarios under CrossOver Preview build 20261006 (Ctrl-C through `tee`, an inherited-ignored SIGHUP, Ctrl-\\, Ctrl-Z and continue, repeated Ctrl-C during cleanup, a pause during prefix setup, a log replaced mid-run) with signals sent to the process group rather than typed, using a build that differs only in where it looks for CrossOver; each showed the old behaviour before the change and the fixed behaviour after. Not confirmed with real key presses, and not on CrossOver 26.3 for anything but the first. The same pattern in the unmerged #425 is not touched.
|
||||
- `d3dmetal-harness` runner tests no longer give a freshly written script only 300–500 ms to start (#479); both use a 2 s deadline. The kill test now also checks that the probe ran until the deadline and that its process is gone, which catches a timeout path that neither kills nor waits for the probe. It passes the PID-file path as a script argument so temporary directory names containing apostrophes work. Test-only change. Slow script start-up as the cause of the earlier failures is inferred, not measured. `output_complete` is not asserted for the killed probe, because a child spawned by a parallel test may inherit its pipe.
|
||||
- `bx-cli run` no longer blocks when `--log` names something other than a regular file (#502). The trace-log reads added for #461 opened the path and read it to the end, which waits forever on a FIFO nobody writes to; the log is now opened without waiting and only a regular file is summarized (anything else gets no summary). Also added the missing test for the file-identity half of the replaced-log check (a different file that begins with the old log's bytes), which a reviewer found untested, and documented that Ctrl-Z typed between supervised phases takes effect when the next phase starts. Covered by 2 new unit tests; three deliberate breakages each failed a test. Not run under CrossOver.
|
||||
|
||||
### Added
|
||||
- Added opt-in `betterxen run --startup-report <path>` JSON diagnostics with the last observed startup stage, fixture verification outcome and preserved failure or termination detail (#255).
|
||||
|
||||
+2
-11
@@ -8,7 +8,7 @@ The single authoritative plan is [docs/roadmap.md](docs/roadmap.md) (Milestones
|
||||
|
||||
1. Pick an open unclaimed issue on your track (A–F) using `.github/ISSUE_TEMPLATE/track-handoff.yml`.
|
||||
2. Check all comments and open PRs, then claim in plain text (`Claiming — branch: track-<a..f>/<issue>-<slug>`). A claim with no commits or PR after 7 days is stale and may be taken over with a reply saying so.
|
||||
3. Work in a dedicated branch or `git worktree` and stay strictly inside the issue's **exclusive file scope**. Maintainer-directed tasks have a narrow exception ([AGENTS.md](AGENTS.md) §2).
|
||||
3. Work in a dedicated branch or `git worktree` and stay strictly inside the issue's **exclusive file scope**.
|
||||
4. If your track needs a new cross-DLL helper or export, open a small `[ABI]` PR touching only `abi/` first. Once merged, both tracks implement in parallel.
|
||||
5. Add new synthetic PE32+ conformance binaries under `tests/conformance/test_<name>/CMakeLists.txt` + `main.cpp` (auto-discovered by CMake — no shared-file edits needed).
|
||||
|
||||
@@ -33,7 +33,7 @@ Report exact commands, host hardware/macOS/CrossOver versions, and pass/fail/ski
|
||||
|
||||
## Clean-Room, Licensing & Provenance Policy
|
||||
|
||||
- Use publicly accessible specifications, publicly licensed software, independently authored synthetic workloads, and project-authorized target builds only under every condition in [AGENTS.md](AGENTS.md) §6 (maintainer approval alone is not enough). Never obtain or use leaked or unauthorized material, and never submit leaked executables or SDKs, confidential Xbox documentation, firmware, keys, proprietary game binaries, or unauthorized shader dumps.
|
||||
- Use publicly accessible specifications, publicly licensed software, and independently authored synthetic workloads only. Never submit leaked executables or SDKs, confidential Xbox documentation, firmware, keys, proprietary game binaries, or unauthorized shader dumps.
|
||||
- Under BetterXen's clean-room policy, anyone who has accessed leaked or confidential Xbox materials must not contribute. Do not post details of restricted material in issues or PRs.
|
||||
- Before incorporating third-party code, verify **per-file** license compatibility with `GPL-3.0-or-later`, record provenance in [docs/research/upstream-registry.md](docs/research/upstream-registry.md) and [docs/research/component-reuse-matrix.md](docs/research/component-reuse-matrix.md), preserve copyright notices, and update [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). Public visibility or a GPL license does not clear code derived from leaked material.
|
||||
- Never bundle or redistribute proprietary components (CrossOver, D3DMetal, Rosetta 2).
|
||||
@@ -49,13 +49,4 @@ Report exact commands, host hardware/macOS/CrossOver versions, and pass/fail/ski
|
||||
git commit -s -m "Describe the change"
|
||||
```
|
||||
|
||||
## Review and Merging
|
||||
|
||||
- A PR needs at least one current approval, passing required checks and resolved blocking conversations. Any later push that changes the PR dismisses earlier approvals.
|
||||
- You do not merge your own PR. A maintainer other than the original author merges it.
|
||||
- Please leave **Allow edits by maintainers** enabled on fork PRs (GitHub does not offer it for organization-owned forks). Maintainers may then resolve conflicts and push fixes to your branch, and may still merge it.
|
||||
- A maintainer may re-approve after their own routine fix (conflicts, changelog, minor docs). Substantive changes need approval from someone who did not write them.
|
||||
|
||||
The full rule, including what GitHub does not enforce, is in [AGENTS.md](AGENTS.md) §7, "Merge eligibility".
|
||||
|
||||
See [AGENTS.md](AGENTS.md), [docs/legal.md](docs/legal.md), [SECURITY.md](SECURITY.md), and [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md).
|
||||
@@ -67,7 +67,7 @@ Legend: 🟢 **Done / Merged** · 🔵 **Active Milestone** · ⚪ **Planned**
|
||||
|
||||
| Milestone | Scope | Status |
|
||||
| --- | --- | --- |
|
||||
| **M0 — Repo, ABI & Cross-Build** | 6-track layout, frozen `abi/`, ARM64 `bx-cli`, 16 mingw-w64 C++ PE32+ shims plus the Rust `bx_shader_bridge.dll` (17 verified DLLs), live CrossOver + Rosetta 2 smoke tests (`test_veh_clwb`, `test_shim_exports`) | 🟢 **Verified complete (`#406`)** |
|
||||
| **M0 — Repo, ABI & Cross-Build** | 6-track layout, frozen `abi/`, ARM64 `bx-cli`, 16 cross-compiled PE32+ shims, live CrossOver + Rosetta 2 smoke tests (`test_veh_clwb`, `test_shim_exports`) | 🟢 **Verified complete (`#406`)** |
|
||||
| **M1 — Boot to `D3D12XboxCreateDevice`** | Full startup shim coverage (`xmem` physical/scatter pages, `XCRDAPI` async file reads, `d3d12_xs` auto-logging COM proxy, offline `xgameruntime` + dynamic loader exports, audio queue stubs, supervised `bx-cli run`, ADR 0007, `test_integration_boot` 19 pass / 2 pending / 0 fail) | 🟢 **Verified complete ([Milestone #17](https://github.com/MacosPorters/betterxen/milestone/17))** |
|
||||
| **M2 — First Frame & Shader Gate** | Reversible `system32` staging, public GDK COM `QueryApiImpl` dispatch, `PresentX` → `IDXGISwapChain3::Present` via D3DMetal 3.0, `dxbc-accc` Windows bridge, D3DMetal GPU limits, and Shader Format Gate ADR | 🔵 **Active ([Milestone #18](https://github.com/MacosPorters/betterxen/milestone/18))** |
|
||||
| **M3 — Shaders, Streaming & Textures** | DirectStorage decompression, RDNA 2 `xg_xs` texture deswizzling, full shader pipeline | ⚪ Planned |
|
||||
@@ -129,7 +129,7 @@ The repository is organized into disjoint track directories around a single froz
|
||||
|
||||
| Directory | Track | Stack | Contents |
|
||||
| --- | --- | --- | --- |
|
||||
| [`abi/`](abi/README.md) | Shared (frozen) | C headers + `.def` | Versioned cross-DLL headers (`bx_config.h`, `bx_log.h`, `bx_xmem_internal.h`, `bx_shader_bridge.h`) and canonical export tables for all 17 shim DLLs (16 mingw-w64 C++ shims plus the Rust `bx_shader_bridge.dll`) |
|
||||
| [`abi/`](abi/README.md) | Shared (frozen) | C headers + `.def` | Versioned cross-DLL headers (`bx_config.h`, `bx_log.h`, `bx_xmem_internal.h`, `bx_shader_bridge.h`) and canonical export tables for all 16 shim DLLs |
|
||||
| `launcher/` | Track A | Rust (`arm64`) | `bx-cli` (`doctor`, `probe`, `shader`, `trace`, `run`), `bx-probe` (PE32+ import classifier), `bx-telemetry` (JSONL trace aggregator) |
|
||||
| `shims/runtime_veh/` | Track A | C++20 (`x86_64` PE) | `bx_runtime_veh.dll`: `clwb` VEH trap, `adcx`/`adox` tripwire, Lockhart/Anaconda memory profile config, structured JSONL logging |
|
||||
| `shims/win32_bridge/` | Track A | C++20 (`x86_64` PE) | `api-ms-win-core-psm-appnotify-l1-1-0/1.dll` stubs and `ext-ms-win-rtcore-ntuser-*` → `user32.dll` forwarders; CrossOver answers these API-set names itself for static imports, so the files are not loaded that way ([ADR 0007](docs/adr/0007-api-set-shims-under-crossover.md)) |
|
||||
@@ -165,9 +165,8 @@ cargo build -p bx-cli
|
||||
# 2. Check host Apple Silicon, Rosetta 2, CrossOver, D3DMetal, and mingw-w64 readiness
|
||||
target/debug/bx-cli doctor
|
||||
|
||||
# 3. Cross-compile the 16 x86-64 PE32+ mingw-w64 shim DLLs, build the Rust
|
||||
# bx_shader_bridge.dll with cargo, and build the conformance binaries
|
||||
# (automatically verifies every abi/defs/*.def export across all 17 DLLs and zero MinGW runtime DLL deps)
|
||||
# 3. Cross-compile all 16 x86-64 PE32+ shim DLLs + conformance binaries
|
||||
# (automatically verifies every abi/defs/*.def export and zero MinGW runtime DLL deps)
|
||||
scripts/build-shims.sh
|
||||
|
||||
# 4. Run live synthetic PE32+ conformance tests inside CrossOver + Rosetta 2
|
||||
@@ -209,11 +208,9 @@ See [AGENTS.md](AGENTS.md), [CONTRIBUTING.md](CONTRIBUTING.md), [docs/architectu
|
||||
|
||||
- **Verified (local Apple M5, macOS 27.2.1, CrossOver 26.3, Rosetta 2):**
|
||||
- Native ARM64 `bx-cli`, `bx-probe`, `bx-telemetry`, and `dxbc-accc` unit tests.
|
||||
- All 17 x86-64 PE32+ shim DLLs — the 16 mingw-w64 C++ shims plus the Rust-built `bx_shader_bridge.dll` — pass strict PE Export Directory verification (111 exact names, ordinals, forwarders, 0 extra exports) and carry zero dynamic MinGW runtime dependencies. `scripts/build-shims.sh` cross-compiles the 16 C++ shims with CMake/mingw-w64 and builds `bx_shader_bridge.dll` with `cargo` for `x86_64-pc-windows-gnu`.
|
||||
- All 16 x86-64 PE32+ shim DLLs cross-compile with zero warnings, pass strict PE Export Directory verification (102 exact names, ordinals, forwarders, 0 extra exports), and carry zero dynamic MinGW runtime dependencies.
|
||||
- `test_veh_clwb.exe` executes AVX2+FMA, traps and skips `clwb` via `bx_runtime_veh.dll`, and exercises starter `XMemAlloc`/`XMemTransferMemory` under CrossOver/Wine.
|
||||
- `test_shim_exports.exe` loads all 16 mingw-w64 C++ shim DLLs and resolves 25 runtime exports via `LoadLibraryA` / `GetProcAddress` inside CrossOver/Wine.
|
||||
- **Not yet verified at runtime (built and export-verified locally, not run under CrossOver):**
|
||||
- The build of `test_shim_exports.exe` on this revision also loads the Rust-built `bx_shader_bridge.dll` and resolves its three frozen exports (`bx_shader_inspect`, `bx_shader_prepare_for_d3dmetal`, `bx_shader_free_buffer`), so the table covers 17 DLLs / 28 checks. The fixture compiles and links and `scripts/build-shims.sh` confirms the bridge's three exports statically, but the 28-check run across 17 DLLs under CrossOver/Wine has **not** been executed on this revision — the previous 16-DLL / 25-check pass was. Compiling, linking and export agreement do not establish that `LoadLibraryA` / `GetProcAddress` succeed for the bridge. This remains a load-and-resolve check in any case: it does not show the bridge *works*; `test_shader_gate.exe` exercises it functionally.
|
||||
- `test_shim_exports.exe` loads all 16 shim DLLs and resolves 25 runtime exports via `LoadLibraryA` / `GetProcAddress` inside CrossOver/Wine.
|
||||
- **Not yet implemented (M1–M6):**
|
||||
- `d3d12_xs.dll` COM device/command-list/PSO proxy and `PresentX` swapchain presentation.
|
||||
- `xmem.dll` physical/scatter page mapping and `XCRDAPI.dll` async DirectStorage queues.
|
||||
|
||||
+2
-64
@@ -1,14 +1,8 @@
|
||||
# Third-party notices
|
||||
|
||||
The active BetterXen Rust workspace (`Cargo.toml` / `Cargo.lock`) is original `GPL-3.0-or-later` source with **one external crates.io dependency**: `libc`, used only by `bx-cli`.
|
||||
The active BetterXen Rust workspace (`Cargo.toml` / `Cargo.lock`) currently has **zero external crates.io dependencies** and is original `GPL-3.0-or-later` source.
|
||||
|
||||
`bx-cli` links the unmodified `libc` 0.2.191 crate (`ccc2ff4aaab962f7fde7b8edda7379c045b1ca12`) for POSIX process groups and signals, under its MIT option. The crate is licensed `MIT OR Apache-2.0`; its notice and permission text (`LICENSE-MIT` in the 0.2.191 crate) are reproduced under [libc MIT license text](#libc-mit-license-text) below.
|
||||
|
||||
## Vendored source files
|
||||
|
||||
| Files | Origin | License |
|
||||
| --- | --- | --- |
|
||||
| `shims/xcrdapi/dstorage/dstorage.h`, `shims/xcrdapi/dstorage/dstorageerr.h` | Microsoft DirectStorage SDK headers, NuGet `Microsoft.Direct3D.DirectStorage` 1.4.0, unmodified (#483). Provenance and hashes: [shims/xcrdapi/dstorage/README.md](shims/xcrdapi/dstorage/README.md). | MIT, per-file notice. The package's `LICENSE-CODE.txt` is kept next to the headers and reproduced under [DirectStorage headers MIT license text](#directstorage-headers-mit-license-text) below. |
|
||||
`bx-cli` links the unmodified `libc` 0.2.191 crate (`ccc2ff4aaab962f7fde7b8edda7379c045b1ca12`) for POSIX process groups and signals, under its MIT option. Preserve the Rust Project Developers notice and permission text.
|
||||
|
||||
## External Host Tools & Runtime Dependencies (Never Bundled)
|
||||
|
||||
@@ -19,59 +13,3 @@ The active BetterXen Rust workspace (`Cargo.toml` / `Cargo.lock`) is original `G
|
||||
| `mingw-w64` & CMake | Developer cross-compilation toolchain for x86-64 PE32+ shims | Installed externally via Homebrew (`brew install mingw-w64 cmake`) for building `shims/` and `tests/conformance/`. |
|
||||
|
||||
Historical third-party notices for the retired native-first workspace (including AMD RDNA 2 ISA metadata, `bitflags`, and `objc2-*`) remain preserved at Git tag `native-first-final` and are summarized in [docs/licenses.md](docs/licenses.md).
|
||||
|
||||
## libc MIT license text
|
||||
|
||||
```text
|
||||
Copyright (c) The Rust Project Developers
|
||||
|
||||
Permission is hereby granted, free of charge, to any
|
||||
person obtaining a copy of this software and associated
|
||||
documentation files (the "Software"), to deal in the
|
||||
Software without restriction, including without
|
||||
limitation the rights to use, copy, modify, merge,
|
||||
publish, distribute, sublicense, and/or sell copies of
|
||||
the Software, and to permit persons to whom the Software
|
||||
is furnished to do so, subject to the following
|
||||
conditions:
|
||||
|
||||
The above copyright notice and this permission notice
|
||||
shall be included in all copies or substantial portions
|
||||
of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
|
||||
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
|
||||
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
|
||||
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
|
||||
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
|
||||
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
DEALINGS IN THE SOFTWARE.
|
||||
```
|
||||
|
||||
## DirectStorage headers MIT license text
|
||||
|
||||
```text
|
||||
Copyright (c) Microsoft Corporation.
|
||||
|
||||
MIT License
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
```
|
||||
+1
-1
@@ -7,4 +7,4 @@ This directory holds the **only shared interface boundary** across BetterXen's s
|
||||
1. **ABI-First Changes:** If one track needs a new cross-DLL helper, config flag, or export symbol, open a small, focused `[ABI]` pull request touching only `abi/`.
|
||||
2. **Zero File Collisions:** Never edit another track's implementation directory in an `[ABI]` PR. Once the `[ABI]` PR merges to `main`, both provider and consumer tracks implement in parallel.
|
||||
3. **Versioned Contracts:** Increment `BX_ABI_VERSION` in `abi/include/bx_config.h` on any breaking struct or signature change.
|
||||
4. **Canonical `.def` Exports:** Every DLL under `shims/` links directly against its corresponding `abi/defs/<name>.def`. CI verifies the built PE32+ export table matches these `.def` files. One entry is not under `shims/`: `bx_shader_bridge.def` is the export list of `bx_shader_bridge.dll`, the x86-64 Windows build of `shader-transpiler/crates/dxbc-accc` (#445). `scripts/build-shims.sh` links it into that build and verifies it with the shims (#484).
|
||||
4. **Canonical `.def` Exports:** Every DLL under `shims/` links directly against its corresponding `abi/defs/<name>.def`. CI verifies the built PE32+ export table matches these `.def` files.
|
||||
@@ -1,5 +0,0 @@
|
||||
LIBRARY bx_shader_bridge.dll
|
||||
EXPORTS
|
||||
bx_shader_inspect
|
||||
bx_shader_prepare_for_d3dmetal
|
||||
bx_shader_free_buffer
|
||||
@@ -15,5 +15,3 @@ EXPORTS
|
||||
XMemVirtualQuery
|
||||
bx_xmem_query_region
|
||||
bx_xmem_get_internal_stats
|
||||
bx_xmem_try_charge_external
|
||||
bx_xmem_release_charge_external
|
||||
@@ -33,24 +33,9 @@ typedef struct bx_xmem_stats {
|
||||
/* Query the XMem region covering `va`. Returns 1 if tracked, 0 otherwise. */
|
||||
int bx_xmem_query_region(uint64_t va, bx_xmem_region_info_t* out_info);
|
||||
|
||||
/* Snapshot current XMem usage against the active Lockhart/Anaconda cap.
|
||||
* committed_virtual_bytes includes bytes admitted through
|
||||
* bx_xmem_try_charge_external(), so committed + physical is everything the
|
||||
* cap counts and peak_committed_bytes never exceeds what was reported. */
|
||||
/* Snapshot current XMem usage against the active Lockhart/Anaconda cap. */
|
||||
void bx_xmem_get_internal_stats(bx_xmem_stats_t* out_stats);
|
||||
|
||||
/* Admit `bytes` against the combined title cap, counting every owner.
|
||||
* Returns 1 on success, 0 when the cap would be exceeded or xmem's own
|
||||
* bookkeeping could not be refreshed (logged as external_charge). On success the
|
||||
* caller owns the charge and must release it exactly once with
|
||||
* bx_xmem_release_charge_external(). Never silently succeeds on failure. */
|
||||
int bx_xmem_try_charge_external(uint64_t bytes);
|
||||
|
||||
/* Release a charge previously admitted by bx_xmem_try_charge_external().
|
||||
* Releasing more than is outstanding is refused: the counter is left
|
||||
* unchanged and an external_charge error is logged. */
|
||||
void bx_xmem_release_charge_external(uint64_t bytes);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
+8
-8
@@ -3,8 +3,7 @@
|
||||
## Getting Started & Architecture
|
||||
|
||||
- [Project README](../README.md) — Overview, quick start, `bx-cli` commands, and verified scope.
|
||||
- [Roadmap](roadmap.md) — Single authoritative plan: the foundation milestones (M0–M2) and the stages the target build reaches (Boot, Picture, Menus, World, Fidelity, Playable), with exit gates and decision gates.
|
||||
- [Working Method](process/working-method.md) — What an agent does when told "work" — the blocker queue, run protocol, source ranks, pull-request shape and the starting queue.
|
||||
- [Roadmap](roadmap.md) — Single authoritative plan (Milestones M0–M6) and completion gates.
|
||||
- [Parallel Track Architecture](architecture/parallel-tracks.md) — 6-track directory ownership, ABI freeze rule, and multi-agent Git workflow.
|
||||
- [Wave 1 Parallel Backlog](issues/wave-1-backlog.md) — Non-overlapping starter issues across Tracks A–F.
|
||||
- [Frozen ABI Contracts](../abi/README.md) — Cross-DLL C headers (`abi/include/`) and canonical `.def` export tables (`abi/defs/`).
|
||||
@@ -16,25 +15,26 @@
|
||||
- [ADR 0005: CrossOver-based hybrid direction](adr/0005-crossover-hybrid-direction.md) — Pivot to CrossOver + Rosetta 2 + D3DMetal as the external foundation.
|
||||
- [ADR 0006: Retire in-tree native-first workspace](adr/0006-retire-in-tree-native-workspace.md) — Retirement of paused native code/scripts/docs from `main` (preserved at Git tag `native-first-final`).
|
||||
- [ADR 0007: API-set win32_bridge shims under CrossOver](adr/0007-api-set-shims-under-crossover.md) — Accepted: CrossOver answers the six API-set import names itself, so the shims are not loaded for static imports.
|
||||
- [ADR 0008: M2 Shader Format Gate](adr/0008-m2-shader-format-gate.md) — Proposed: Branch D1 (DXIL through D3DMetal, with the measured wave64 and 64-bit-atomic gaps as M3 work); ACCC-only containers refused with `E_NOTIMPL` until a lawful format source exists.
|
||||
- [ADR 0009: Xbox-layout D3D12 objects](adr/0009-xbox-layout-d3d12-objects.md) — Proposed: `d3d12_xs` gives titles objects with the Xbox object layout and function-table order (generated from the Xbox header), hosting the PC proxies; Phase 1 covers the device chain and the objects it creates.
|
||||
|
||||
## Research, Testing & Licensing
|
||||
|
||||
- [Target-Build Bring-Up: Development Cycle and Review](testing/target-build-review.md) — How contributors run a project-authorized target build offline, turn findings into single-track PRs, and review them independently without proprietary details.
|
||||
- [Joint D3DMetal Memory Research Record](research/d3dmetal-zero-copy/integration.md) — Integrated A/B results for #473: report, evidence register, acceptance checklist, implementation roadmap, reproduction routes and limitations. Physical zero-copy and production performance are unproven.
|
||||
- [Workstream A Memory and Resource Research](research/d3dmetal-zero-copy/allocation-profiling/README.md) — Historical evidence, Asufte handoff and reciprocal source/data review, footprint/retirement correction, xmem feasibility, bounded fragmentation, isolated allocator evaluation and texture/graphics protocols; local observations with explicit review/pressure limitations for #473.
|
||||
|
||||
- [D3DMetal Unified-Memory and Zero-Copy Research](research/d3dmetal-zero-copy/README.md) — Shared six-check synthetic probe, per-host raw logs and evidence limits for #473 / #464.
|
||||
|
||||
- [Hybrid Workloads & Measurement Protocol](testing/hybrid-workloads.md) — Original Windows workloads, receipt fields, timing conventions, and negative controls.
|
||||
- [CrossOver Licensing & Redistribution Boundaries](research/crossover-licensing.md) — Per-component license review for CrossOver, Wine, DXMT, DXVK, VKD3D-Proton, MoltenVK, D3DMetal, and Rosetta 2.
|
||||
- [Upstream Research Registry](research/upstream-registry.md) & [Component Reuse Matrix](research/component-reuse-matrix.md) — Public upstream evaluation and provenance screening.
|
||||
- [Primary-Source Verification (2026-11-25)](research/primary-source-verification-2026-11-25.md) & [Hybrid Backlog Research Record](research/hybrid-backlog-research-2026-11-25.md) — Vendor documentation verification notes.
|
||||
- [D3D12 Swapchain References under D3DMetal](research/d3dmetal-swapchain-references.md) — Swapchain lifetime results across two Apple Silicon hosts and CrossOver builds.
|
||||
- [D3D12 Swapchain References under D3DMetal](research/d3dmetal-swapchain-references.md) — One-host observation to check before M2 presentation work.
|
||||
- [D3DMetal GPU Limits](research/d3dmetal-gpu-limits.md) — Constraints a shader translator targeting D3DMetal must handle, measured by the `test_d3dmetal_gpu_limits` fixture (`WaveSize(64)` and SM 6.6 64-bit atomics not run, bounded lock emulation), plus unverified reports kept separate as leads (#453).
|
||||
- [Console Compute Shader Entry ABI](research/console-shader-abi.md) — Wave size, root-argument registers, descriptor forms and binding metadata observed from the NewBE backend of Microsoft's Series X|S PIX shader compiler on project-authored probes (class U: an authorized, not yet independently reproduced observation; inferred register roles).
|
||||
- [Public Technical References](research/sources.md), [Xbox GDK Notes](research/xbox-gdk.md), [RDNA 2 Notes](research/rdna2.md), and [Shader Containers](research/shader-containers.md) — Public specification references for shim and shader work.
|
||||
|
||||
## Governance, Security & Legal
|
||||
|
||||
- [Engineering & Agent Rules](../AGENTS.md) (`CLAUDE.md` symlink) — Mandatory rules for human contributors and coding agents.
|
||||
- [Contributing Guidelines](../CONTRIBUTING.md) — Claiming, verification, clean-room policy, and DCO sign-off.
|
||||
- [Claims & Evidence Classes](claims.toml) — Scoped claims with an evidence-class legend (A, B, D, E, U); classes describe evidence type, not Xbox hardware verification.
|
||||
- [Claims & Evidence Classes](claims.toml) — Evidence classification definitions (classes A–D, U).
|
||||
- [Legal Scope](legal.md), [Dependency Licensing](licenses.md), and [Third-Party Notices](../THIRD_PARTY_NOTICES.md) — Input policy, attribution, and redistribution boundaries.
|
||||
- [Threat Model](threat-model.md) & [Security Policy](../SECURITY.md) — Isolation boundaries and vulnerability reporting.
|
||||
@@ -26,7 +26,7 @@ BetterXen provides integration, configuration, environment management, diagnosti
|
||||
|
||||
## Verified implementation capabilities
|
||||
|
||||
None for the hybrid architecture. Verified native-research capabilities (synthetic evidence only) are unchanged and listed in `docs/progress.md` at tag `native-first-final`, the archive ADR 0006 makes canonical; the file is retired from `main`.
|
||||
None for the hybrid architecture. Verified native-research capabilities (synthetic evidence only) are unchanged and listed in `docs/progress.md`.
|
||||
|
||||
## Planning consequence
|
||||
|
||||
|
||||
@@ -1,78 +0,0 @@
|
||||
# ADR 0008: M2 Shader Format Gate — Branch D1 (DXIL normalization) for M3
|
||||
|
||||
Status: **Proposed** (2026-11-26, issue #466). The choice for M3 is the maintainers' to accept. The evidence below is from local Apple Silicon runs by the implementer and has not been independently reproduced.
|
||||
|
||||
## Context
|
||||
|
||||
The roadmap's M2 gate asks which shader path M3 builds:
|
||||
- **Branch D1, DXIL normalization:** shaders reach D3DMetal as DXIL, and BetterXen rewrites only what D3DMetal cannot run.
|
||||
- **Branch D2, `ACCC`/`FSPX` translation:** console-compiled RDNA 2 code in `ACCC` chunks is translated to DXIL or MSL.
|
||||
|
||||
The gate needs a classifier that guest pipeline creation actually reaches, plus measurements of what D3DMetal does with each form.
|
||||
|
||||
## What M2 built
|
||||
|
||||
- **Bridge (#445):** `bx_shader_bridge.dll` is the x86-64 Windows build of `dxbc-accc`, so guest code can call the inspector.
|
||||
- **Gate (#466):** `d3d12_xs.dll`'s `CreateComputePipelineState` and `CreateGraphicsPipelineState` pass every stage through `bx_shader_inspect`. One `shader_gate` JSONL record per stage gives:
|
||||
- the container kind, stage, shader model and chunk sizes;
|
||||
- the `SFI0` feature flags (`D3D_SHADER_FEATURE_*` values from DirectX-Headers `d3dcommon.h`);
|
||||
- the `PSV0` wave lane range.
|
||||
- **Decisions:**
|
||||
- **DXIL and dual containers:** go to the host as the bridge's prepared copy (`bx_shader_prepare_for_d3dmetal`).
|
||||
- **ACCC-only containers:** are refused with `E_NOTIMPL` before the host device is called.
|
||||
- **Legacy DXBC and unclassifiable input:** pass unchanged.
|
||||
- **A missing bridge:** is logged once (`shader_bridge_missing`). Shaders then pass unclassified, except that a container with an `ACCC` chunk and no `DXIL` chunk is still refused with `E_NOTIMPL`, found by a bounds-checked chunk scan, because D3DMetal crashes on it. The bridge is loaded only by full path from `d3d12_xs.dll`'s own directory.
|
||||
- **Known D3DMetal gaps:** a stage that needs a wave wider than 32 lanes, or 64-bit atomics, also gets a `shader_d3dmetal_gap` record.
|
||||
|
||||
`tests/conformance/test_shader_gate` exercises all of this.
|
||||
|
||||
## Evidence
|
||||
|
||||
| Observation | Source | Host and class |
|
||||
| --- | --- | --- |
|
||||
| A real DXC 1.9.2609 SM 6.6 compute shader (`fill_cs66`) creates a PSO through `d3d12_xs`, runs, and all 256 output words match the CPU reference. | `test_shader_gate` | Apple M5 Pro, macOS 27.2.1, CrossOver 26.3 (`26.3.0.39832`) bottle with `CX_GRAPHICS_BACKEND=d3dmetal`; class A, this host only |
|
||||
| The same shader, run outside Wine through `d3dmetal-native` against CrossOver's D3DMetal 3.0, matches 256/256. | [d3dmetal-harness](../../shader-transpiler/crates/d3dmetal-harness/README.md) (#417) | Same host; class A |
|
||||
| An ACCC-only container is refused with `E_NOTIMPL` for compute and graphics, no host object is created, and the device stays usable. | `test_shader_gate` | Same bottle; class A |
|
||||
| In a bare CrossOver 26.3 prefix (vkd3d), SM 6.6 DXIL PSOs fail with `E_FAIL`. vkd3d reports `Cannot load DXIL conversion library`. | `test_shader_gate`, same host | Class A; DXIL needs the D3DMetal backend under CrossOver |
|
||||
| `[WaveSize(64)]` kernels and kernels with SM 6.6 64-bit atomics are created but never run on D3DMetal. | [D3DMetal GPU limits](../research/d3dmetal-gpu-limits.md#measured-constraints) (#453) | Apple M3 Pro, Wine 11.0 source build, D3DMetal 4.0b3; class A for that host |
|
||||
| DXC records `[WaveSize(64)]` as `PSV0` lanes 64/64, and 64-bit atomics on typed resources as `SFI0` `0x400000`. 64-bit atomics on raw buffers set only `INT64_OPS` (`0x8000`), the same as other 64-bit integer use. | The #453 blobs, read by the gate and by a script | Class A |
|
||||
| Public sources do not establish a console-native shader container layout. BetterXen's `FSPX` is a clean-room synthetic layout, not a description of a console compiler's format. | `CLAIM-XBOX-ISA-ABI` (class U) in [claims.toml](../claims.toml); `shader-transpiler/crates/dxbc-accc/src/fspx.rs` | Source review |
|
||||
| A serialized console pipeline path exists for Series X\|S, with no public version-independent format. | `CLAIM-XBOX-ACO-SAMPLE` (class D) | Source review |
|
||||
| A read-only structural scan of an authorized local test workload (2026-11-28) found 52 DXIL SM 6.5 compute containers with LLVM bitcode in its `XboxBvhBuilder` component, 29 ACCC-only `FSPX` containers in its AMD FidelityFX upscaler component, 10 SM 6.6 DXIL containers with four-byte `NOBC` payloads (nine pixel, one vertex) in its main executable, and no plaintext `DXBC` in its packaged shader archive. | Static container scan on this host, re-run through `dxbc-accc`; private evidence note, workload not redistributed | This host; structure only, runtime use unmeasured |
|
||||
|
||||
Runtime gate telemetry still covers only synthetic programs; no target-workload run has reached pipeline creation, so what a run submits remains unmeasured. One static measurement now exists (2026-11-28): a read-only container scan of an authorized local test workload, re-run through `dxbc-accc`, with the counts in the table above. The scan measures what shipped components contain, not what any run submits, and the workload is not redistributed. Wherever the gate runs, its `shader_gate` records count it.
|
||||
|
||||
## Decision
|
||||
|
||||
Branch **D1** is proposed for M3:
|
||||
|
||||
1. **Pass DXIL through the gate to D3DMetal.** This is the only path with measured, end-to-end execution evidence.
|
||||
2. **Spend M3 shader work on the two measured gaps,** within the [D3DMetal GPU limits](../research/d3dmetal-gpu-limits.md#measured-constraints):
|
||||
- lower `WaveSize(64)` programs to 32-lane code;
|
||||
- lower SM 6.6 64-bit atomics to 32-bit operations or bounded lock emulation.
|
||||
|
||||
The gate's `shader_d3dmetal_gap` records show which pipelines need this.
|
||||
3. **Keep refusing ACCC-only containers** with `E_NOTIMPL` and a structured log.
|
||||
|
||||
Branch **D2** is deferred. It needs a documented, lawfully available description of console-compiled containers and their RDNA 2 code, and none exists (`CLAIM-XBOX-ISA-ABI`). A translator built against the synthetic `FSPX` layout would prove nothing about real inputs.
|
||||
|
||||
Revisit this ADR in any of these cases:
|
||||
- an authorized public source for that format appears;
|
||||
- gate telemetry shows a required pipeline-creation path refusing an ACCC-only container at runtime — a static scan already established that the target workload's upscaler component embeds 29, so the open question is submission, not existence;
|
||||
- D3DMetal starts running the gap cases.
|
||||
|
||||
## Consequences
|
||||
|
||||
- **Pipeline creation:** `CreateComputePipelineState` and `CreateGraphicsPipelineState` now depend on `bx_shader_bridge.dll` for classification. Without it, they still work, refuse ACCC-only containers, and say so in the log.
|
||||
- **Stream PSOs (#576):** `ID3D12Device2::CreatePipelineState` stream descriptions are gated too. The stream is walked as 8-byte-aligned records (a 4-byte subobject type plus a type-dependent payload). Both the payload offset and the record size come from the compiler: `alignas(void*)` aligns the record, not the payload, so 4-byte-aligned payloads sit at offset 4, and `static_assert`s pin the measured values. Shader subobjects (`VS`, `PS`, `DS`, `HS`, `GS`, `CS`, `AS`, `MS`) go through `BxShaderGate::admit`; every other payload is copied verbatim. A subobject type at or above `D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MAX_VALID` from the toolchain header (mingw-w64 `d3d12.h`: `0x1a`, immediately after `MS`), a duplicated subobject type, a payload that overruns `SizeInBytes`, or a bytecode length with a null pointer returns `E_INVALIDARG` before the host is called. The shim edits its own copy of the stream, so prepared DXIL can be substituted without writing to the caller's memory. `pso_stream` now reports `shaders_not_parsed=0` when it parsed, and each stream stage logs its own `shader_gate` record with `pso=stream`. The `--no-bridge` path also refuses ACCC-only through the stream. `test_shader_gate.exe` covers the stream form but was cross-compiled only, not run under CrossOver on the authoring host.
|
||||
- **Packaging:** `scripts/build-shims.sh` builds the bridge, links it with `abi/defs/bx_shader_bridge.def`, and stages it in `build-shims/bin` beside `d3d12_xs.dll` (#484).
|
||||
- **Not covered by the gate yet:**
|
||||
- **Raw-buffer 64-bit atomics:** these cannot be flagged from `SFI0`; the DXIL bitcode would have to be read.
|
||||
- **Telemetry summary:** `bx-cli trace` now summarizes the gate's records (#496): per-decision, per-kind and per-stage counts for `shader_gate`, the `shader_d3dmetal_gap` list with its wave-width and 64-bit-atomic flags, and `shader_bridge_missing`. The summary only reflects records a run actually wrote; it adds no live run and no new compatibility claim.
|
||||
- **Observed `FSPX` tables:** the clean-room section-table layout does not describe the 29 containers embedded in the target workload's upscaler component. In the 2026-11-28 scan, `dxbc-accc` rejected them with `FspxSectionOutOfBounds` before any section body was read, so the current refusal is structural, not a measured D3DMetal incompatibility. The cause the scan recorded, a descriptor offset inside the region the layout reserves for the header and section table, is reported as `FspxLayoutMismatch` since #599, apart from a section past the payload end; the scan has not been re-run against that change. Over the C ABI both are still `BX_SHADER_ERR_INVALID_BLOB`. Extending the layout against measured containers is a Track D prerequisite for any D2 trial and a maintainer provenance decision, because no public format description exists.
|
||||
- **`NOBC` programs:** the classifier validates the `DXIL` program header's sizes but not the LLVM bitcode signature, so a container whose bitcode payload is the four-byte placeholder `NOBC` still classifies as executable DXIL and is prepared for the host unchanged. The target workload's main executable embeds 10 such containers (nine pixel, one vertex, SM 6.6). They carry no bitcode, so D1 cannot run them as-is; their signature and validation chunks are intact.
|
||||
- **Wave size:** the gate logs constraints but changes no shader. A pipeline that D3DMetal creates but does not run still behaves that way.
|
||||
|
||||
## Not claimed
|
||||
|
||||
Nothing here describes any Xbox title's shaders, behaviour on Xbox hardware, or D3DMetal versions other than those named. Evidence class: local Apple Silicon runs, one local static container scan of an authorized test workload, and public-source review. The scan counts containers embedded in shipped components on this host; it does not establish what any run submits, and it documents no console-compiled format layout beyond the stated mismatch.
|
||||
@@ -1,59 +0,0 @@
|
||||
# ADR 0009: Xbox-layout D3D12 objects in d3d12_xs
|
||||
|
||||
Status: **Proposed** (2026-11-28). Phase 1 is implemented with this ADR; the maintainers decide whether the direction stands. The evidence is from local Apple Silicon runs by the implementer and has not been independently reproduced.
|
||||
|
||||
## Context
|
||||
|
||||
`d3d12_xs.dll` handed titles PC D3D12 objects: C++ proxies (`proxy.h`, `proxy_generated.cpp`) whose vtables follow the PC `<d3d12.h>` order. A title built against the Xbox Series D3D12 header (`d3d12_xs.h`, part of the GDK material Microsoft authorized the project to use) calls through each object's **function table**, and that order is different:
|
||||
|
||||
| Interface | Xbox slots | PC slots | Orders agree up to |
|
||||
| --- | --- | --- | --- |
|
||||
| `ID3D12Device` | 83 | 44 | slot 43. Xbox then adds 39 methods (`CreatePlacedResourceX`, `CreateCommandQueueX`, ...) before `ID3D12Device1`. |
|
||||
| `ID3D12Device11` (chain) | 139 | — | `ID3D12Device11` is the interface a project-authorized target build asks for. |
|
||||
| `ID3D12GraphicsCommandList` | 107 | 60 | slot 27 |
|
||||
| `ID3D12CommandQueue` | 38 | 19 | slot 13 |
|
||||
|
||||
So every call past those slots reached the wrong PC method. On the target build, the first call on the device after `QueryInterface(ID3D12Device11)` jumped to address 0.
|
||||
|
||||
From the same header:
|
||||
- **Base layout:** every object starts with the table pointer, a 32-bit flags word and `m_RefCount`, 16 bytes in all.
|
||||
- **`ID3D12Device` fields:** a 64-bit null constant-buffer address at +16 and a 64-byte union at +24. The union's first byte, `m_OutOfLineFlags`, makes the two inline device helpers (`CopyDescriptorsSimple`, `CreateConstantBufferView`) call out through the table when it is non-zero. That holds unless a title is compiled with `D3DCOMPILE_NO_DEBUG`, in which case they write descriptors inline.
|
||||
- **Command lists:** they add a put buffer and CPU state. Of their 76 inline methods, 71 call the table. The other five write command packets directly when the next write fits below `m_Putter`'s limits, and call the table otherwise.
|
||||
- **IIDs:** the interface IDs of shared interfaces are the PC ones (`ID3D12Device` `189819f1-…`, `ID3D12Resource` `696442be-…`).
|
||||
|
||||
## Decision
|
||||
|
||||
1. **Xbox-layout objects:** titles get `BxXboxObject`s (`xbox_facade.h`). They have the Xbox object layout, with `m_OutOfLineFlags` set, and an Xbox-order function table. Each object hosts a PC object, normally one of the existing proxies, so their logging, shader gate, heap hooks and wrapping stay in force.
|
||||
2. **Generated tables:** `tools/gen_xbox_tables.py` reads the Xbox header locally and the toolchain's `<d3d12.h>`, and writes `xbox_tables_generated.cpp`. It takes only slot order, names, IIDs and parameter types from the Xbox header. The header is never committed.
|
||||
- **Forwarders:** a slot whose Xbox and PC signatures are equivalent gets a typed forwarder written with the PC types. That includes the free-function versus member struct-return difference, so the compiler produces the right calling convention. Interface pointers passed in are unwrapped, and `(REFIID, void**)` results are wrapped.
|
||||
- **Stubs:** every other slot is a `BX_VTABLE_STUB_LOG` stub.
|
||||
- **Hand-written slots:** Xbox-only methods are implemented in `xbox_facade.cpp` as titles need them.
|
||||
3. **Who gets which layout:** titles set `Version` in the `D3D12XBOX_CREATE_DEVICE_PARAMETERS` block they pass to `D3D12XboxCreateDevice`, and the documentation requires it. Those calls get the Xbox layout. BetterXen's synthetic fixtures are PC-layout clients built against `<d3d12.h>`, pass a zeroed block, and keep the PC proxy. The log records which layout was chosen (`xbox_layout`).
|
||||
4. **Command lists (Phase 2):** command lists get an Xbox object whose zeroed put-buffer pointers fail every inline room check, so every call reaches the table.
|
||||
|
||||
## Consequences
|
||||
|
||||
- **Phase 1 (this change):**
|
||||
- The device chain up to `ID3D12Device11` is covered: 139 slots, 75 forwarded, 4 shared or hand-written, 60 stubs.
|
||||
- So are the objects it creates: resources, heaps, fences, descriptor heaps, root signatures, pipeline states, command allocators, query heaps, command signatures and command queues.
|
||||
- `CreateCommandQueueX` maps the Xbox queue description onto PC `CreateCommandQueue`. The engine and queue indices are logged and not used.
|
||||
- On the target build, the title now creates its device and four compute queues, and stops at `CreateCommandListX`, which is Phase 2.
|
||||
- **Phase 2:**
|
||||
- **Command lists:** `ID3D12GraphicsCommandList8`, 150 slots: 75 forwarded, 6 shared or hand-written, 69 stubs. They are created through `CreateCommandListX` and the PC `CreateCommandList`, and their Xbox field area is zeroed, so the five inline fast paths call through the table.
|
||||
- **Interface pointers inside structures:** `ResourceBarrier` and `CopyTextureRegion` unwrap them before the host call. The Xbox `ResourceBarrier` returns 0 actions.
|
||||
- **Frame pacing:** `SetFrameIntervalX`, `ScheduleFrameEventX` and `WaitFrameEventX` (`frame_pacing.cpp`) are emulated from the recorded interval by a host timer. It signals the origin, vblank and flip events and their ancillary handles, and gives out frame-pipeline tokens as documented.
|
||||
- **Generator fixes:** CRLF lines in parts of the header, a table definition whose end the boundary pattern ran past (it hid `ID3D12GraphicsCommandList1`), SAL annotations with nested parentheses, and `FLOAT`/`float`.
|
||||
- **Resources at title-chosen addresses** (`placed_x.cpp`), translation by copy:
|
||||
- `CreatePlacedResourceX` and `CreatePlacedResourceX1` create a host shadow resource. A buffer gets a committed buffer in a CPU-visible write-back heap, filled from the title's memory at creation; a texture gets a committed texture whose contents are not filled, which is logged.
|
||||
- The resource reports the title's address from `GetGPUVirtualAddress`.
|
||||
- Not yet done: keeping shadows in step with later CPU writes (planned: page-protection dirty tracking, copying at submit), copying GPU writes back, and translating title addresses in GPU calls.
|
||||
- **On the target build:** the title creates 581 command lists, sets a 30 Hz interval and schedules its origin and flip events. It then lays out its own descriptor memory with `xmem` placeholders (#643) and creates a 174 MB buffer at a title-chosen address through `CreatePlacedResourceX1`, now served by a shadow.
|
||||
- **Where it stops:** the title creates a descriptor heap and requires `GetCPUDescriptorHandleForHeapStart` to equal an address in its own descriptor memory. D3DMetal returns an opaque handle.
|
||||
- **What that needs:** BetterXen-owned descriptor heaps whose handles are addresses, translated to host descriptors when used. That is the descriptor-heap item under Consequences.
|
||||
- **Fixtures:** the existing fixtures are unaffected, since they use the PC layout. `tests/conformance/test_d3d12_xbox_layout` calls Xbox slots by number, with the expected results taken from a PC-layout device. It fails against the previous `d3d12_xs.dll`.
|
||||
- **What the fixture can and cannot show:** its slot numbers and object offsets are written by hand, but from the same header the generator reads. It shows that the generator and the fixture agree. It cannot show that either read the header correctly; only an independent re-derivation from the header, or a title running further, can.
|
||||
- **On a host without the forwarded interface** (vkd3d stops at `ID3D12Device9`): the Xbox-layout device is refused with `E_NOINTERFACE` and logged. The fixture verifies the refusal and skips (exit 77). `bx_xbox_wrap` refuses the same way for every wrapped family, so a title never gets a PC object where it expects an Xbox one.
|
||||
- **Frame pacing:** the emulated frame interval follows host `Sleep` and is not synchronised to the display. The pacing thread is detached and never exits, which is safe only while `d3d12_xs.dll` stays loaded for the life of the process.
|
||||
- **Descriptor heaps:** a title compiled with `D3DCOMPILE_NO_DEBUG` writes console-format descriptors straight into descriptor-heap memory and computes handles with Xbox descriptor sizes. Supporting that needs BetterXen-owned descriptor heaps translated at bind time, which is not part of this ADR.
|
||||
- **Identity:** QueryInterface on an Xbox object for another wrapped family returns that family's Xbox object over the same host. A host reached through another path, such as `GetDevice` returning the raw host device, may get a second Xbox object.
|
||||
- **Replacing the PC proxy:** this ADR supersedes the PC proxy for titles. Whether the PC proxy is eventually removed in favour of fixtures that use the Xbox layout is left open.
|
||||
@@ -25,7 +25,7 @@ BetterXen is organized so **5 to 8+ contributors** can develop the CrossOver-bas
|
||||
## Milestones (M0 → M6)
|
||||
|
||||
1. **M0 — Repo, ABI & Cross-Build:** One-command ARM64 + x86-64 PE32+ build, export verification, and `test_veh_clwb.exe` passing under CrossOver + Rosetta 2 (`ROSETTA_ADVERTISE_AVX=1`).
|
||||
2. **M1 — Boot to `D3D12XboxCreateDevice`:** Zero missing imports; all 17 shim DLLs (16 mingw-w64 C++ shims plus the Rust `bx_shader_bridge.dll`) load cleanly; auto-logging COM proxy captures startup call traces.
|
||||
2. **M1 — Boot to `D3D12XboxCreateDevice`:** Zero missing imports; all 16 shim DLLs load cleanly; auto-logging COM proxy captures startup call traces.
|
||||
3. **M2 — First Frame & Shader Format Gate:** Present real frames through D3DMetal 3.0 (`PresentX` → `IDXGISwapChain3::Present`) and classify runtime shaders (`DXIL` fast path vs. `ACCC`/`FSPX` RDNA 2 transpilation).
|
||||
4. **M3 — Full Shaders, Streaming & Texture Correctness:** Async DirectStorage decompression, accurate RDNA 2 `xg_xs` tiling/deswizzling, full shader pipeline.
|
||||
5. **M4 — 3D World, Ray Tracing & Input:** BVH4 rehydration → live D3DMetal 3.0 DXR build, FidelityFX/MetalFX upscaling shim, full `GameInput` controller/KB/M mapping.
|
||||
|
||||
@@ -1,30 +1,4 @@
|
||||
# Source review is distinct from a Xenora test run.
|
||||
#
|
||||
# Evidence classes (derived from existing usage; claim classes are unchanged):
|
||||
# A — Executed measurement on a named Apple Silicon host, with an independent
|
||||
# CPU/reference expectation. Valid only for the named host/software versions;
|
||||
# implementer-run unless independently reproduced. Never Xbox verification.
|
||||
# B — Source-derived semantics from a public vendor specification, scoped to the
|
||||
# documented target (e.g. desktop RDNA 2, public D3D12, Metal/MSL). May be
|
||||
# exercised by synthetic tests, but does not establish console applicability.
|
||||
# D — Public documentation or sample-source inspection (Microsoft/Xbox/Apple),
|
||||
# without console execution. Establishes only what the reviewed source states.
|
||||
# E — Public tool/format documentation or observed behavior of a public
|
||||
# software tool (e.g. LLVM's gfx1030 documentation, or its assembler/
|
||||
# disassembler accepting gfx1030 forms), scoped to the pinned tool version.
|
||||
# Documentation review and execution are distinct; the claim's test field
|
||||
# records which one applies.
|
||||
# U — Unknown/unestablished by the reviewed public sources: a bounded statement
|
||||
# about the evidence reviewed, not proof that no authorized source exists.
|
||||
#
|
||||
# Use B for semantics from a specification, D for a claim about what a public
|
||||
# document or sample says, and E for a claim about a tool or its format support.
|
||||
# The current registry does not assign class C.
|
||||
#
|
||||
# These are the repository's evidence classes. AGENTS.md §5 refers to this
|
||||
# file and does not define a second vocabulary; the longer VERIFIED /
|
||||
# REPRODUCED / SOURCE-DERIVED / ... vocabulary named in issue #549 is not
|
||||
# present in the in-tree AGENTS.md, so no mapping is invented here.
|
||||
schema_version = 1
|
||||
|
||||
[[claim]]
|
||||
@@ -268,13 +242,3 @@ retrieved = "2026-11-22"
|
||||
architecture = "Xbox Series X, Hot Chips 32 architectural presentation"
|
||||
test = "Read slides 12 and 13. No console execution."
|
||||
uncertainty = "The slides do not specify opcode semantics, an ABI or a command packet layout."
|
||||
|
||||
[[claim]]
|
||||
id = "CLAIM-XBOX-CS-ENTRY-ABI"
|
||||
class = "U"
|
||||
claim = "For project-authored compute shaders with explicit root signatures, the NewBE backend of Microsoft's Series X|S PIX shader compiler generated wave64 code that receives root data from s4 in root-parameter order (one SGPR per constant, two per root descriptor address, one per 32-bit table pointer), thread-group IDs after the root data, the root-data address in s0:s1 when the data overflows, and root buffer descriptors built inline with a record count of -1."
|
||||
sources = ["docs/research/console-shader-abi.md"]
|
||||
retrieved = "2026-11-28"
|
||||
architecture = "Xbox Series X|S compute shaders, as compiled by the GDK 2026.10 (10.0.26100.9661) Scarlett PIX shader compiler (NewBE) under CrossOver 26.3 (26.3.0.39832) on Apple M5, macOS 27.2.1"
|
||||
test = "Compiled eleven project-authored cs_6_5/cs_6_6 probes and read the compiler's assembly listings; the compiler and its outputs are used under Microsoft's authorization and are not in the repository."
|
||||
uncertainty = "Class U: no public source establishes this; it rests on an authorized reading of a non-public compiler's listings, which only a contributor with the same authorization can reproduce, and which has not been independently reproduced. Register roles are inferred from the generated code and the reported COMPUTE_PGM_RSRC2 fields. NewBE only: the ACO backend (xdxc), which produces ACCC code, generates different code and agrees so far only on the root UAV address in s[4:5]. One compiler build, compute only, no console execution, and the ACCC container layout is not covered."
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
# Clean-room scope
|
||||
|
||||
BetterXen does not circumvent console security or DRM, does not load encrypted or protected content, and is a research project built from public documentation, its own synthetic workloads and, under the conditions in [AGENTS.md](../AGENTS.md) §6, local observation of lawfully obtained target builds.
|
||||
BetterXen does not circumvent console security or DRM, does not load encrypted or protected content, and is a research project built from public documentation.
|
||||
|
||||
## User-provided game files
|
||||
|
||||
|
||||
@@ -1,200 +0,0 @@
|
||||
# Working Method: the Blocker Queue
|
||||
|
||||
**Status: in effect since 2026-11-29** (#662), together with [AGENTS.md §0](../../AGENTS.md). The pinned ladder issue is #663.
|
||||
|
||||
BetterXen is built by collaborators who each have the project-authorized target build and who work by pointing a coding agent at this repository and saying **"work"**. This document is written for that. It answers one question for an agent that has just been told to work: *what is the single most useful thing to do now, and how do I do it without colliding with the other agents?*
|
||||
|
||||
There are no meetings, no rotating roles and no plan to interpret. The state of the project is in GitHub; the rules are here and in AGENTS.md.
|
||||
|
||||
## Why this shape
|
||||
|
||||
What the first target-build runs taught us:
|
||||
|
||||
- **The build finds what tests cannot.** With the start-up milestone verified complete, the build still stopped on a missing handle-duplication call, an instruction loop that trapped two million times and a page-remapping race. Nobody would have written an issue for any of them in advance.
|
||||
- **Guessing is expensive.** A stall was blamed on network polling for a day; a thread sample found the real cause in minutes.
|
||||
- **A helpful workaround can hide the real path.** Answering every pipeline call with success kept the frame loop alive and hid the build's fallback to shader containers.
|
||||
- **One run proves little.** The build takes different start-up paths from run to run. Two blockers looked like one "intermittent stop" until runs were counted.
|
||||
- **Agents left alone drift.** They wrote long documents, opened large stacked pull requests that nobody reviewed, investigated the same symptom twice, shared one game bottle and filled a disk.
|
||||
|
||||
So: the build decides what is next, the queue makes it unambiguous, and reviewing comes before new work.
|
||||
|
||||
## The stages
|
||||
|
||||
The [roadmap](../roadmap.md) is a ladder of stages the target build reaches: **Boot → Picture → Menus → World → Fidelity → Playable**. Exactly one stage is current. Its exit gate is a ten-run check anyone can repeat.
|
||||
|
||||
## Where the state lives
|
||||
|
||||
| What | Where | Who writes it |
|
||||
| --- | --- | --- |
|
||||
| The current stage and its latest gate result | The pinned **ladder issue** (label `ladder`) | Any agent that runs the gate check |
|
||||
| Everything the build is known to stop on | One **blocker issue** each (label `blocker`, plus `stage: <name>` and a track label) | The agent that found it |
|
||||
| Who is working on what | A claim comment on the blocker issue | The claiming agent |
|
||||
| What needs a person | Label `needs-human` | Any agent |
|
||||
| Rules | AGENTS.md and this document | Maintainers, by pull request |
|
||||
|
||||
Nothing about status is kept in files in the repository: agents editing one status file would conflict all day.
|
||||
|
||||
### Blocker issues
|
||||
|
||||
A blocker issue is small and has a fixed shape, so that two agents that find the same thing file the same issue.
|
||||
|
||||
- **Title:** `[blocker] <signature>`. The signature is taken from the run report, not invented: for example `unimplemented IXUser slot 3`, `fault in XCRDAPI.dll (write, unmapped)`, `exit status 1 after save query`, `stall: presenting thread in trapped instruction`. Before filing, search open and closed issues for the signature.
|
||||
- **Body:** the stage it blocks; how many of ten runs hit it; the run-report lines; what is known and not known. No bytes, names, hashes or addresses from the build.
|
||||
- **Order:** within a stage, the label `first` marks blockers that every run hits before any other; after those, lower issue number first.
|
||||
|
||||
## What an agent does when told "work"
|
||||
|
||||
AGENTS.md §0 has the binding version. In short, in strict order:
|
||||
|
||||
1. **Preflight.** Tools, login, disk space, an own bottle, a current `main`.
|
||||
2. **Your own pull requests first.** Requested changes, failing checks or conflicts on a pull request your person opened.
|
||||
3. **Then review.** The oldest open, non-draft pull request from *another* person that has no current review. Review it, and merge it if it is approved, green and not your person's. Review comes before new work because unreviewed work is worth nothing to the next run.
|
||||
4. **Then one blocker.** The top unclaimed blocker of the current stage. Claim it, and do only that.
|
||||
5. **Then discover.** If the current stage has no unclaimed blocker, run the stage's gate check and file what it finds. If the gate passes, post the result on the ladder issue and label it `needs-human`: a person confirms the stage change.
|
||||
6. **Otherwise stop.** Report that the queue is empty. Do not invent work.
|
||||
|
||||
An agent stops and labels `needs-human` whenever it meets a decision that is not its to make: a decision gate, a licence or provenance question, a rule change, or two sources of truth that disagree.
|
||||
|
||||
## Working one blocker
|
||||
|
||||
```text
|
||||
claim → evidence → smallest fix + test → ten runs → pull request → (someone else reviews and merges)
|
||||
```
|
||||
|
||||
1. **Claim.** Comment `Claiming — branch: track-<a..f>/<issue>-<slug>` on the issue. A claim with no commits or pull request after 3 days is free to take; say so in a comment when you take it.
|
||||
2. **Evidence before code.** Find what the build asked for and what it got. Use the run report, then the diagnostics (thread sampler, fault context, call trace). If that does not explain it within the session, write what was learned on the issue and release the claim; do not guess a fix.
|
||||
3. **Smallest fix.** Only what removes this blocker, inside the track directories it needs. A new cross-DLL export still goes through an `[ABI]` pull request first.
|
||||
4. **A test for the contract.** Every contract the fix teaches a shim gets a synthetic conformance test that fails without the fix.
|
||||
5. **Proof.** Ten runs before and ten after. Report every run.
|
||||
6. **Pull request.** One blocker, five short parts (below). Then stop: the next "work" starts from the top of the list.
|
||||
|
||||
### Pull-request description
|
||||
|
||||
Five parts and nothing else:
|
||||
|
||||
1. **Blocker:** `Closes #<issue>` and one sentence on what the build did.
|
||||
2. **Contract:** what the console does, and which source says so (ranks below).
|
||||
3. **Fix:** what changed.
|
||||
4. **Test:** the conformance test, and that it fails without the fix.
|
||||
5. **Proof:** before and after over ten runs (for example "status-5 exits: 4/10 → 0/10"), with the machine and the `main` commit.
|
||||
|
||||
### Review
|
||||
|
||||
The reviewing agent checks out the branch, runs the Section 8 commands and the new test, confirms the test fails without the fix, and reads the proof. It does not repeat the ten runs unless the proof looks wrong.
|
||||
|
||||
**Deep review** — re-deriving the contract from its source, by an agent working for a different person than the author — is required only for:
|
||||
|
||||
- a change under `abi/`;
|
||||
- a new or changed translator instruction class;
|
||||
- a contract from source rank 4 or 5;
|
||||
- anything touching the sandbox, security or licensing.
|
||||
|
||||
**Merging.** The author's agent never merges its own person's pull request. Any other collaborator's agent merges once the pull request is approved and green. A pull request that is green and unreviewed after one working day gets the label `needs-human`.
|
||||
|
||||
**Stacks.** A pull request is based on `main`. One level of stacking is allowed when a fix truly needs an unmerged one; deeper stacks are not.
|
||||
|
||||
## Run protocol
|
||||
|
||||
A run counts only if it is made this way. The launcher does it; agents do not hand-roll it.
|
||||
|
||||
Until the launcher does, the offline-run procedure and the diagnostic switches are in [Target-Build Bring-Up: Development Cycle and Review](../testing/target-build-review.md). Where that document and this one differ on roles, the order of work or review, this one replaces it once accepted.
|
||||
|
||||
- **Build:** current `main`, or `main` plus exactly the one branch under test.
|
||||
- **Sandbox:** the offline runner, which refuses to start unless a probe confirms outbound network is blocked.
|
||||
- **Bottle:** one per agent session, created by the launcher and named for the session. Never a shared one.
|
||||
- **One game at a time per machine.** The launcher takes a machine-wide lock; a second run waits.
|
||||
- **Disk:** at least 10 GB free, checked before the run; the session's scratch bottle and build directory are removed afterwards.
|
||||
- **Count and length:** ten runs, each as long as the stage needs (five minutes for Boot).
|
||||
- **Machine:** the report states chip and memory. Gates are judged on 16 GB machines.
|
||||
|
||||
**The run report** is generated, not written. Per run:
|
||||
|
||||
- outcome: frames presented, clean timeout, early exit with its status, or hang;
|
||||
- the start-up path taken;
|
||||
- every unimplemented call reached, counted;
|
||||
- every fault inside a BetterXen module;
|
||||
- pipelines drawn with: translated, passed through, skipped;
|
||||
- on a stall: every thread's stack.
|
||||
|
||||
It ends with a ten-run summary and a list of **signatures**, the strings blocker issues are titled with.
|
||||
|
||||
## Sources of truth
|
||||
|
||||
When a fix needs to know what the console does, use the strongest source available and name its rank in the pull request.
|
||||
|
||||
| Rank | Source | Notes |
|
||||
| --- | --- | --- |
|
||||
| 1 | Authorized GDK documentation and headers | Derived facts may be committed. The files never are. |
|
||||
| 2 | Our own compiler output for our own source | Built with the console compiler from the GDK. |
|
||||
| 3 | Run-time observation of the target build | What it calls, with what, and what it does with the answer. |
|
||||
| 4 | Call-site analysis of the target build (a disassembler such as Ghidra) | When observation cannot explain a wait or a branch. Local only. |
|
||||
| 5 | The authorized upstream emulator's source | A hint about what the build needs, not a reference for correctness. Confirm with ranks 1–4 or with runs. |
|
||||
|
||||
Collaborators may install the GDK and a disassembler for this. AGENTS.md §6 is unchanged: nothing from the build enters git, issues or pull requests — no bytes, file names, hashes, addresses or decompiled code.
|
||||
|
||||
## Evidence and references
|
||||
|
||||
- **Private evidence store.** Run logs, dumps, disassembly and captures go in a folder outside the repository on the collaborator's machine. Issues and pull requests carry counts, sizes, call shapes and the contract learned.
|
||||
- **Reference images** (needed from the Picture stage on): a collaborator's own capture from a real console running the same content, or published footage. They live in the private store; a pull request says "matches reference screen 3".
|
||||
|
||||
## Finding blockers once the game runs
|
||||
|
||||
From the Menus stage on, the build no longer stops by itself at the next missing piece: someone has to take it somewhere. Agents are poor players, so the method does not depend on an agent holding a controller. BetterXen owns both ends of the build's contact with the machine — input (`GameInput`) and graphics (`d3d12_xs`) — and records and replays both.
|
||||
|
||||
**1. People play; the launcher records.** A play session with recording on saves the input stream with timestamps and the save files it started from. A hotkey marks a moment ("texture wrong here", "audio cut out"). A crash or hang needs no mark: the run report has it.
|
||||
|
||||
**2. Agents replay routes.** A route is a starting save plus a short recorded input stream (about two minutes: load, walk somewhere, enter a vehicle). An agent replays it through the input shim and compares the run with the last good one. Replays drift, because the build is not deterministic, so routes stay short and start from a save. Each route is a regression test, run ten times like any gate.
|
||||
|
||||
**3. Frame capture and offline replay.** The graphics layer records every call the build makes for one frame, with the data it referenced. The frame is then redrawn without the build running, in seconds and identically every time. An agent fixing a picture bug replays that frame after each change instead of booting and travelling to the spot again.
|
||||
|
||||
**How a problem is recognised,** from most to least reliable without a person:
|
||||
|
||||
| Signal | Catches | Needs a person |
|
||||
| --- | --- | --- |
|
||||
| Crash, hang, early exit | Stability | No |
|
||||
| Run-report counters: skipped draws, stubbed shader instructions, unimplemented calls, failed storage requests | Missing pieces, even when the picture looks plausible | No |
|
||||
| Frame compared with the last good capture of the same route | Regressions | No |
|
||||
| Frame compared with a console reference image | Wrong rendering | To supply the reference |
|
||||
| An agent looking at a capture | Obvious breakage: black screen, missing geometry, garbage textures | No; subtle errors are missed |
|
||||
| A person's mark during play | Feel, audio sync, input lag, anything that "looks off" | Yes |
|
||||
|
||||
Findings enter the queue as blocker issues with signatures of the same kind: `route 7: crash at 1:40 (3/10)`, `capture 12: 340 draws skipped`, `capture 12: differs from reference in the sky`. The order of work does not change.
|
||||
|
||||
Whether the game is good to play is a question only people answer. Their time goes into playing and marking, never into reproducing or bisecting.
|
||||
|
||||
## What people do
|
||||
|
||||
People are needed for exactly four things, each marked `needs-human`:
|
||||
|
||||
1. confirming a stage change after a gate passes;
|
||||
2. deciding a decision gate (for example the graphics back end);
|
||||
3. licence, provenance and legal questions;
|
||||
4. changing these rules.
|
||||
|
||||
Everything else is the queue.
|
||||
|
||||
## Starting the queue
|
||||
|
||||
The queue starts with what the first target-build runs already found. Each line was filed as an issue on 2026-11-29 (#664–#680); the table is kept as a record of the starting point, and the issues are the live state.
|
||||
|
||||
| Stage | Signature or task | Track |
|
||||
| --- | --- | --- |
|
||||
| Boot | Run tooling in the repository: offline runner, per-run report with signatures, ten-run summary, thread sampler, machine-wide run lock, per-session bottle | A |
|
||||
| Boot | `stall: presenting thread in trapped CLZERO loop` | A |
|
||||
| Boot | `unimplemented IXUser slot 3` (handle duplication) | E |
|
||||
| Boot | `unimplemented IXGameRuntimeCore slots 6, 13, 14, 15` (async run; task-queue composite, port, duplicate) | E |
|
||||
| Boot | `unimplemented IXGameSaveImpl slot 13` (container info; and slot 15) | E |
|
||||
| Boot | `fault in XCRDAPI.dll (write, unmapped)` — page remapping is not atomic | B |
|
||||
| Boot | `serialized-pipeline calls succeed with a null pipeline` — they must fail and be logged | C |
|
||||
| Boot | `exit status 1, nothing logged` (1 run in 5) | A |
|
||||
| Picture | D3DMetal capability checks: direct heap indexing, 64-lane compute through the translator, 64-bit atomics, mesh and amplification shaders | D, F |
|
||||
| Picture | Vendor the upstream translator with provenance entries; amend ADR 0008 | D |
|
||||
| Picture | Translator behind `bx_shader_bridge.dll`; host pipelines created on first use | C, D |
|
||||
| Picture | `placed texture contents not uploaded` | C |
|
||||
| Picture | `build waits after sign-in with nothing unimplemented` — needs evidence | E |
|
||||
| Picture | Reference images for the first screens | `needs-human` |
|
||||
| Menus | Input record and replay in the `GameInput` shim; routes as ten-run regression tests | E, A |
|
||||
| Menus | Play-session recording in the launcher: input stream, starting saves, mark hotkey | A |
|
||||
| Fidelity | Frame capture in `d3d12_xs` and an offline frame replayer | C |
|
||||
|
||||
Fixes for several Boot lines exist on a local experiment branch; they still go through the queue, one pull request each, with tests and ten-run proof.
|
||||
@@ -21,8 +21,11 @@ Companion to the [upstream registry](upstream-registry.md); same evidence limits
|
||||
| Test and diagnostics methodology | BetterXen existing audits, benchmark harness, claims registry | **Reuse** | Existing evidence classes, claims audit and benchmark gating apply to hybrid work (Phase 1 onward). |
|
||||
| Configuration, diagnostics, benchmarking around CrossOver | BetterXen | **Build** (Phase 2, provisional) | Only after Phase 1 shows what CrossOver does not already provide (#351). |
|
||||
| Process groups and signals for `bx-cli run` | rust-lang/libc 0.2.191 (MIT) | **Reuse** | Unmodified crates.io dependency (#408). |
|
||||
| Public PC DirectStorage interface definitions (IIDs, structs, vtable order) | `dstorage.h` and `dstorageerr.h` from NuGet `Microsoft.Direct3D.DirectStorage` 1.4.0 (MIT per file) | **Vendor unmodified** (#483) | MIT notices kept in the files, with `LICENSE-CODE.txt` alongside and in `THIRD_PARTY_NOTICES.md`. Only the headers are used; the package's DLLs and other files fall under Microsoft's proprietary SDK terms and are never redistributed. |
|
||||
| Xbox console DirectStorage interfaces (`IDStorageFactoryX` and others) | `dstorage_xs.h` (GDK with Xbox Extensions) | **Rejected until a licence-compatible source exists** (#483) | Available only to licensed partners. Microsoft Learn and the MIT `Xbox-GDK-Samples` `dstorage_win32.h` document signatures and struct layouts but not the IIDs. |
|
||||
| GDK `QueryApiImpl` class and interface ids, inheritance and slot order for XGameSave and XPackage | xodus-gaming/xgameruntime-docs at `7090008` (GPL-3.0 text) | **Use as factual reference, pending maintainer provenance acceptance** (#468, #492) | Only interface facts are used, written as BetterXen's own code; no text or code is copied. The source describes its method as black-box reverse engineering under Wine's clean-room guidelines. `IXError` slot 3's `false` answer comes from the #492 review's interop observation instead; that source lists the slot as unknown. Revisit if the source's method or licence status changes. |
|
||||
|
||||
Open items: license text for every selected component must be read from the exact release used; DXMT, DXVK and Wine contributor and file-level notices are not reviewed.
|
||||
|
||||
## #473 external allocator evaluation
|
||||
|
||||
| Need | Candidate | Decision | Conditions |
|
||||
| --- | --- | --- | --- |
|
||||
| Bounded CUSTOM heap pools, allocation statistics and resource ownership | AMD D3D12 Memory Allocator 3.3.0 at `600949266be004553f74c9ef809384380a9d44cf` | Evaluate externally in isolated A research; not adopted in production | Exact header/CPP/LICENSE notices reviewed and recorded in the registry; retain unchanged MIT notices. Public general-purpose provenance; GPL-3.0-or-later-compatible under notice obligations. Source/build artifacts remain ignored. Build, CrossOver behavior, overhead, retirement and independent review are separate evidence gates, not inferred from source features. |
|
||||
@@ -1,75 +0,0 @@
|
||||
# Console compute shader entry ABI (probe results)
|
||||
|
||||
Recorded 2026-11-28 (CLAIM-XBOX-CS-ENTRY-ABI). This page lists facts derived from the assembly listing of Microsoft's Series X|S PIX shader compiler (its NewBE code generator), used under an authorization Microsoft gave the project for its GDK material (see "Provenance"). The compiler, its output and the GDK files are not in this repository. No listing, binary or documentation text is reproduced. Only the observations below are. It complements [RDNA 2 notes](rdna2.md), which cover AMD's public ISA, and [Shader containers](shader-containers.md).
|
||||
|
||||
What this is:
|
||||
- **Measured:** what the compiler emitted for eleven compute shaders the project wrote (p00–p10 below), compiled on one host: Apple M5, macOS 27.2.1, CrossOver 26.3 (26.3.0.39832), GDK 2026.10 (10.0.26100.9661).
|
||||
- **Inferred:** what each register holds. The interpretations below are read from the generated code. They agree with the user-SGPR, thread-group-ID and thread-ID fields of AMD's publicly documented `COMPUTE_PGM_RSRC2` register, which the compiler reports for each shader.
|
||||
|
||||
What this is not: a console run, a description of the ACCC/FSPX container, a description of the ACO backend that produces the code in ACCC containers (see "Root buffer access"), or anything about graphics stages. The compiler used here writes plain DXIL objects. The console code appears only in its assembly listing, so how that code is stored in an ACCC container is still unknown (CLAIM-XBOX-ISA-ABI).
|
||||
|
||||
## Method
|
||||
|
||||
Each probe is a `cs_6_5` compute shader (`cs_6_6` for the 64-bit atomic) with an explicit `[RootSignature]`. The compiler needs a root signature to generate console code. It reported "GFX10" for the target. The probes change one thing at a time:
|
||||
|
||||
| Probe | Root signature | Shader |
|
||||
| --- | --- | --- |
|
||||
| p00 | `SRV(t0), SRV(t1), UAV(u0)` | `o[i] = a[i] + b[i]`, 64 threads |
|
||||
| p01 | `RootConstants(num32BitConstants=4, b0), UAV(u0)` | uses all four constants |
|
||||
| p02 | `CBV(b0), UAV(u0)` | reads two constants |
|
||||
| p03 | `DescriptorTable(SRV(t0, numDescriptors=2)), DescriptorTable(UAV(u0))` | p00 through tables |
|
||||
| p04 | `DescriptorTable(SRV(t0)), DescriptorTable(Sampler(s0)), UAV(u0)` | `Texture2D.SampleLevel` |
|
||||
| p05 | `UAV(u0), SRV(t0), SRV(t1)` | p00 with the parameters reordered |
|
||||
| p06 | `UAV(u0)` | `[numthreads(8,8,1)]`, writes group and thread IDs |
|
||||
| p07 | `SRV(t0), UAV(u0)` | `WaveActiveSum` |
|
||||
| p08 | `SRV(t0), UAV(u0)` | 256 bytes of `groupshared` and a barrier |
|
||||
| p09 | `UAV(u0)` | 64-bit `InterlockedAdd` |
|
||||
| p10 | `RootConstants(num32BitConstants=20, b0), UAV(u0)` | sums all 20 constants |
|
||||
|
||||
## Observations
|
||||
|
||||
**Wave size.** Every probe was compiled for 64-lane waves: the compiler reported wave32 as disabled. In p07 `WaveActiveSum` became a full 64-lane reduction that combines the two 32-lane halves and uses a 64-bit execution mask. D3DMetal 4.0b3, the version measured in [D3DMetal GPU limits](d3dmetal-gpu-limits.md), runs 32-lane waves only; D3DMetal 3.0 was not measured. None of the probes declares a wave size, so wave64 is what this compiler generates by default, and console-compiled compute code has to be treated as wave64 unless it declares otherwise, not only when a shader declares `WaveSize(64)`.
|
||||
|
||||
**Root arguments in registers.** Root-signature data starts at `s4`, in root-parameter order. p05 moves the registers with the parameters.
|
||||
- A root constant takes one SGPR (p01: `s4`–`s7`).
|
||||
- A root CBV, SRV or UAV takes two SGPRs, a 64-bit GPU address (p00: `s4:s5`, `s6:s7`, `s8:s9`).
|
||||
- A descriptor table takes one SGPR, a 32-bit pointer. The shader clears the upper half itself (p03, p04).
|
||||
- The thread-group IDs follow the root data, x before y (p00: `s10`; p06: `s6`, `s7`). Thread IDs arrive in `v0` (x) and `v1` (y), as the reported thread-ID count indicates.
|
||||
|
||||
**Overflow.** `s0`–`s3` come before the root data. When the root data does not fit in user SGPRs (p10: 20 constants and a UAV), only those four are passed, and `s0:s1` holds the address of the root data in memory. The shader loads the constants from offset 0 and the UAV address from offset `0x50`, which is root dword 20. Whether `s0:s1` points at the same data when the arguments also fit in registers was not tested.
|
||||
|
||||
**Root buffer access.** For a root SRV, UAV or CBV, the shader builds the buffer descriptor itself from the root address:
|
||||
- **Stride:** in word 1, the `STRIDE` field (bits 29:16 in the public GFX10 layout), taken from the element type: 4 bytes for `uint`, 8 for `uint64_t`, 16 for the root CBV.
|
||||
- **Record count:** `-1` (`NUM_RECORDS` = 0xFFFFFFFF). With the `OOB_SELECT` below, the only bounds check compares the index against `NUM_RECORDS`, so it never fires: accesses through root descriptors are effectively not bounds-checked.
|
||||
- **Word 3:** the constant `0x11014fac` in every probe. Decoded with the public GFX10 buffer-descriptor layout (Mesa `src/amd/common/ac_descriptors.c` / `gfx10-rsrc.json`, LLVM `SIDefines.h`): destination swizzle X, Y, Z, W; `FORMAT` 20 (`32_UINT`); `RESOURCE_LEVEL` 1; `OOB_SELECT` 1 (the index is checked against `NUM_RECORDS`); `TYPE` 0 (buffer). These observations describe the NewBE path only. The ACO path (`xdxc`), which produces the code in the ACCC containers titles ship, generates different code for the same HLSL: its word 3 is `0x31016fac`, which decodes the same way except `FORMAT` 22 (`32_FLOAT`) and `OOB_SELECT` 3 (raw), two bits apart (`0x20002000`). Of these probes' facts, only the root UAV address in `s[4:5]` has been checked to agree on ACO. That comparison is recorded in the shader corpus PR [#650](https://github.com/MacosPorters/betterxen/pull/650) (open); until it lands, treat ACO agreement beyond that as unverified.
|
||||
|
||||
**Descriptor tables.** Descriptors are loaded from the table address:
|
||||
- buffer descriptors 32 bytes apart (p03 loads at offsets `0` and `0x20`);
|
||||
- a texture descriptor of 32 bytes and a sampler descriptor of 16 bytes (p04).
|
||||
|
||||
For each such load, the compiler also reported the instruction offset and the HLSL binding it came from: class, register, space and resource kind.
|
||||
|
||||
**Other.** p08 uses LDS (`ds_write_b32`, `ds_read_b32`), and its size shows in the reported LDS allocation. p09 is a native `buffer_atomic_add_x2`. The shader hash from the container's `HASH` part is embedded at the start of the generated code.
|
||||
|
||||
## Consequences
|
||||
|
||||
- **Branch D2** ([ADR 0008](../adr/0008-m2-shader-format-gate.md)) gains a candidate compute entry ABI: where root constants, root descriptors, table pointers and IDs are, and how buffer descriptors are formed, as the NewBE path generates them. It is not accepted for D2 until it is reproduced independently, and checked against the ACO code that ACCC containers carry.
|
||||
- **Binding recovery** may not need data-flow analysis if ACCC containers carry the same per-load binding table. That depends on the container format, which is still unknown.
|
||||
- **Wave64** is the default. The D1 path also needs to know whether a title's DXIL assumes 64 lanes.
|
||||
- **Bounds:** out-of-range accesses through root descriptors are not discarded on the console the way bounds-checked descriptors would discard them.
|
||||
|
||||
## Open
|
||||
|
||||
- **Graphics stages** (vertex and pixel inputs, exports) were not probed.
|
||||
- **ACCC-only output:** `xdxc` emits containers that keep DXIL and add ACCC. Which compiler or option emits ACCC-only (DXIL-stripped) containers, like those in the target workload's upscaler component (see the [roadmap](../roadmap.md) scan entry), is open.
|
||||
- **ACO agreement:** which of these NewBE facts hold for the ACO code (see "Root buffer access").
|
||||
- **SGPR alignment:** every probe placed its 64-bit root addresses after an even number of SGPRs. Whether an odd count of one-SGPR parameters before a root descriptor inserts a padding SGPR is untested.
|
||||
- **Overflow threshold:** the probes jump from 6 root dwords to 22. The exact cutoff, and whether overflow is always all-or-nothing, are unmeasured.
|
||||
- **`s0`–`s3`:** what they hold when root data fits in registers.
|
||||
- **One compiler build, one host:** a different GDK version may differ.
|
||||
|
||||
## Provenance
|
||||
|
||||
- **Source:** facts were read from listings that Microsoft's licensed Series X|S shader compiler produced for shaders the project wrote. That compiler is not public, so none of this can be checked against a public source, except the descriptor decode above.
|
||||
- **Authorization:** the maintainer (@atesahmet0) has stated that Microsoft's authorization for the project's use of its GDK material covers publishing derived observations like these in this repository. The material itself (the compiler, its listings and binaries, and the GDK documentation) is never committed. The authorization record is held privately (the process is proposed in [#661](https://github.com/MacosPorters/betterxen/pull/661)).
|
||||
- **Reproduction:** only a contributor with the same authorization can reproduce these observations. That reproduction has not happened yet, so the claim is recorded as class U: unestablished by public sources, with an authorized observation behind it.
|
||||
@@ -108,7 +108,7 @@ independently reproduced, not CrossOver 26.3, and not an Xbox hardware result.
|
||||
|
||||
| Check | Outcome |
|
||||
| --- | --- |
|
||||
| `device.shader_model` | 6.6 |
|
||||
| `device.shader_model` | 6.6 (the fixture skips with exit 77 below 6.6) |
|
||||
| `wave.reported` | `WaveOps=1`, lane count min 32, max 32 |
|
||||
| `wave.control` | ran at width 32, lanes a permutation within each wave (required: pass) |
|
||||
| `wave.wavesize64` | created but not run (output still sentinel) |
|
||||
@@ -118,12 +118,6 @@ independently reproduced, not CrossOver 26.3, and not an Xbox hardware result.
|
||||
| `lock64.cap64` | 108, 96 and 108 of 512 updates dropped (values not compared) |
|
||||
| `lock64.cap1024` | 0 of 512 dropped, 16/16 values exact (required: pass) |
|
||||
|
||||
**Exit codes.** The fixture exits **0** with every required check passed, **1** on a failed
|
||||
required check, and **77** with a `SKIP: <reason>` line when `d3d12.dll`, its exports, device
|
||||
creation, or shader model 6.6 is unavailable. 77 is not a pass; see the exit-status section of
|
||||
[`tests/conformance/README.md`](../../tests/conformance/README.md#exit-status-pass-fail-and-unavailable)
|
||||
for a recording recipe. Through `bx-cli run` the guest status is returned unchanged.
|
||||
|
||||
Still to do for the issue's validation requirement: an independent run on CrossOver 26.3
|
||||
(D3DMetal 3.0) by another contributor.
|
||||
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
# D3D12 swapchain references under D3DMetal
|
||||
|
||||
An observation to check before M2 builds presentation on `IDXGISwapChain3`. One Apple M4,
|
||||
macOS 27, CrossOver 26.3.0 (26.3.0.39832), 2026-11-26. See the independent Apple M2 Pro run below.
|
||||
macOS 27, CrossOver 26.3.0 (26.3.0.39832), 2026-11-26. Not independently reproduced, and not an
|
||||
Xbox hardware result.
|
||||
|
||||
| | D3DMetal | Wine `vkd3d` path |
|
||||
| --- | --- | --- |
|
||||
@@ -17,72 +18,3 @@ is explained.
|
||||
The probe is
|
||||
[`lifetime.c` at `7c512af`](https://github.com/MacosPorters/betterxen/blob/7c512af/tests/conformance/test_d3d12_lifetime/lifetime.c)
|
||||
on the branch of #425; it is not part of this branch. Tracked in #450.
|
||||
|
||||
## Independent run on Apple M2 Pro
|
||||
|
||||
On 2026-11-26, an Apple M2 Pro (16 GiB, macOS 27.3 build 26C5035r) reproduced
|
||||
the swapchain retention in CrossOver 26.3.0.39832 with D3DMetal 3.0. The
|
||||
same x86-64 probe under Rosetta 2 released all swapchains in CrossOver
|
||||
Preview 27.0.0.41303. Each CrossOver build used a fresh Windows 11
|
||||
64-bit bottle. The Direct3D 12 workload loaded the `apple_gptk` D3D12
|
||||
and DXGI modules in both builds. The bundled framework in the Preview
|
||||
build's `apple_gptk` directory reports version 4.0b3.
|
||||
|
||||
| Swapchain lifetime probe | Initial reference count | Application release returned | Witnesses retained |
|
||||
| --- | ---: | ---: | ---: |
|
||||
| 26.3 D3DMetal | 2 | 1 | 12 of 12 |
|
||||
| 26.3 Wine D3D12 | 1 | 0 | 0 of 12 |
|
||||
| Preview D3DMetal | 1 | 0 | 0 of 12 |
|
||||
| Preview Wine D3D12 | 1 | 0 | 0 of 12 |
|
||||
|
||||
Destroying the window before releasing the swapchain and calling
|
||||
`ResizeBuffers` before teardown each left 3 of 3 witnesses retained on
|
||||
26.3 D3DMetal. Explicitly detaching the witness released the probe's
|
||||
private data, while the swapchain's release still returned 1. The
|
||||
deliberately retained witness control failed as expected. An extra
|
||||
application-side `Release` would drop a reference the application
|
||||
does not own.
|
||||
|
||||
The separate D3D12 integrated workload presented 600 frames and verified
|
||||
eight readbacks with zero mismatches on both D3DMetal builds. It failed
|
||||
only the shutdown gate on 26.3, where the final device release returned
|
||||
2. Preview passed shutdown with a final device release of 0. These runs
|
||||
used the direct host D3D12 path without BetterXen's D3D12 shim. The
|
||||
comparison establishes behavior for these two CrossOver builds on this
|
||||
host. The underlying ownership change is unknown.
|
||||
|
||||
Build the probe from the pinned source linked above with
|
||||
`x86_64-w64-mingw32-clang -std=c11 -O2 -Wall -Wextra -Werror lifetime.c -o d3d12-lifetime.exe -ld3d12 -ldxgi -ldxguid -luser32`
|
||||
(LLVM-MinGW 20261117 in this run). Run in a clean bottle using
|
||||
`ROSETTA_ADVERTISE_AVX=1 CX_GRAPHICS_BACKEND=d3dmetal wine --bottle <bottle> <absolute-path-to-exe> --cycles 12`
|
||||
and repeat with `CX_GRAPHICS_BACKEND=wined3d`. The two witness controls
|
||||
use `--cycles 3 --detach-witness` with and without `--retain-app-reference`.
|
||||
|
||||
## Related Direct3D acceptance failures
|
||||
|
||||
The [integrated D3D12 workload](https://github.com/MacosPorters/betterxen/blob/7c512af/tests/conformance/test_d3d12_integrated/integrated12.c)
|
||||
also reproduced the presentation slowdown on the Wine D3D12 path on
|
||||
26.3. With `CX_GRAPHICS_BACKEND=wined3d` and a 600-frame target, the
|
||||
workload logged approximately 2,000 ms inside `Present` on frames
|
||||
12–38, then exited 3 after a 10-second GPU completion wait failed. The
|
||||
previous M4 report saw the slowdown around frame 437. This run exited
|
||||
before reaching normal teardown. Preview completed the same 600-frame
|
||||
workload on the Wine path with eight verified readbacks, no mismatches
|
||||
and clean shutdown. A 600-frame repeat on 26.3 passed with `--vsync`
|
||||
enabled. A subsequent 600-frame repeat also passed with the flag off,
|
||||
so the slowdown remains intermittent and the successful vsync run
|
||||
does not establish a workaround.
|
||||
|
||||
The [integrated D3D11 workload](https://github.com/MacosPorters/betterxen/blob/7c512af/tests/conformance/test_d3d11_integrated/integrated.c)
|
||||
completed the 20,000-frame soak on 26.3 with 46 verified readbacks,
|
||||
zero mismatches and a clean shutdown. The intermittent GPU event
|
||||
stall did not recur in this run. Preview also completed all 20,000
|
||||
frames and all 46 readbacks, then failed the shutdown gate with one
|
||||
device reference remaining. A separate 600-frame Preview run
|
||||
reproduced that shutdown result.
|
||||
|
||||
The 26.3 keyboard check delivered five macOS events to the workload and
|
||||
reached the expected offset (16, 32). The negative control delivered
|
||||
two Up events and reached (0, -32), which the input gate rejected as
|
||||
expected. These were isolated runs, so they do not reproduce the
|
||||
intermittent failure observed inside the full acceptance suite.
|
||||
@@ -0,0 +1,3 @@
|
||||
# Preserve Windows stdout/stderr bytes as recorded, including CRLF line endings.
|
||||
results/**/stdout.txt -text whitespace=cr-at-eol
|
||||
results/**/stderr.txt -text whitespace=cr-at-eol
|
||||
@@ -0,0 +1,97 @@
|
||||
# D3DMetal unified-memory and zero-copy research
|
||||
|
||||
Collaborative research for [#473](https://github.com/MacosPorters/betterxen/issues/473), informing [#464](https://github.com/MacosPorters/betterxen/issues/464). Maintainer-agreed participants are @Arths17, @skakwy and @CarReal8917; participation is not an exclusive claim. The shared branch is [`research/d3dmetal-zero-copy`](https://github.com/MacosPorters/betterxen/tree/research/d3dmetal-zero-copy). It is based on `origin/main` commit `f7fb52bc56f671f9da7109f8aef8d3f04de59aee` and is not being merged into main.
|
||||
|
||||
This directory contains an original synthetic probe, a runner, separate run records and [consolidated findings](findings.md). It neither imports nor tests the production `xmem` or `d3d12_xs` implementation. @devil8blade retains the implementation of #464. Findings here do not certify that implementation or establish Xbox compatibility.
|
||||
|
||||
Start with the [integration record](integration.md): it lists the joint report, evidence register, acceptance checklist, roadmap, reproduction routes, limitations and the #464 handoff from both workstreams. The sections below describe the six-check baseline only.
|
||||
|
||||
## Build and run
|
||||
|
||||
Requirements: Apple Silicon macOS, an externally installed licensed CrossOver with D3DMetal, supported Rosetta 2, Python 3.11+, and native ARM64 MinGW-w64 cross-compiler tools. Nothing proprietary is downloaded or bundled. The compiler is an ARM64 host executable; its output is a Windows x86-64 guest executable.
|
||||
|
||||
Use an existing **win64** CrossOver bottle. The runner copies it into a fresh scratch directory, changes only that temporary copy, builds outside the checkout, selects D3DMetal, runs with `ROSETTA_ADVERTISE_AVX=1`, and enforces a **30-second** process timeout. No BetterXen shim directory is added to the search path. It prints the resolved `d3d12.dll` path and checks that `d3d12_xs.dll` is absent. The original bottle and the checkout are not written by the runner.
|
||||
|
||||
```sh
|
||||
# Fetch this branch even in a clone that normally fetches only main.
|
||||
git fetch origin research/d3dmetal-zero-copy:refs/remotes/origin/research/d3dmetal-zero-copy
|
||||
git worktree add --detach ../betterxen-zero-copy origin/research/d3dmetal-zero-copy
|
||||
cd ../betterxen-zero-copy
|
||||
python3 docs/research/d3dmetal-zero-copy/run.py \
|
||||
--bottle "/absolute/path/to/an/existing/CrossOver/bottle" \
|
||||
--scratch /tmp/bx-uma-verify/run-01
|
||||
```
|
||||
|
||||
The scratch directory must not exist. `--crossover /Applications/CrossOver.app` and `--compiler x86_64-w64-mingw32-g++` select non-default installations. Existing bottle configuration can affect a run; record relevant settings and verify the loaded backend. The runner uses a small child-environment allowlist and never forwards host credential variables.
|
||||
|
||||
The runner invokes this compilation, with absolute scratch paths in the actual receipt:
|
||||
|
||||
```sh
|
||||
x86_64-w64-mingw32-g++ -std=c++20 -O2 -static -static-libgcc -static-libstdc++ \
|
||||
-Wall -Wextra -Werror probe.cpp -o probe.exe -lkernel32
|
||||
```
|
||||
|
||||
Outputs are `probe.cpp`, `probe.exe`, `receipt.json`, `stdout.txt` and `stderr.txt`. The receipt records source/executable SHA-256, compiler command/result, PE format/imports, host, software, environment and run outcome. Temporary bottle contents are removed after its private wineserver is stopped. The caller removes the remaining scratch files **after preserving the selected research records**.
|
||||
|
||||
Two launch attempts in the initial experiment stopped before the probe because the host ClamAV database was absent. For the original executable compiled locally from this source, the temporary bottle uses `AllowUntrusted=1` and `AntiVirusScan=untrusted`; the source bottle's scanner settings are unchanged. This does not bypass any dependency license or activation requirement.
|
||||
|
||||
## Fixed six-check baseline
|
||||
|
||||
Do not change these checks to improve an outcome. Unsupported HRESULTs and not-run paths are evidence, not passes. Exit 0 means no observed data/submission mismatch; it does **not** mean every capability is supported. Inspect each printed result.
|
||||
|
||||
| Check | Fixed experiment |
|
||||
| --- | --- |
|
||||
| 1: device | Obtain `ID3D12Device3`; query `ARCHITECTURE1` (`UMA`, `CacheCoherentUMA`, `TileBasedRenderer`, `IsolatedMMU`) and `D3D12_OPTIONS.ResourceHeapTier`. |
|
||||
| 2: existing memory | `OpenExistingHeapFromAddress` on 64 KiB `VirtualAlloc` (`MEM_COMMIT\|MEM_RESERVE`, `PAGE_READWRITE`); `OpenExistingHeapFromFileMapping` on 64 KiB anonymous read/write mapping. Print HRESULTs; if supported, place a buffer and check CPU writes by GPU readback with no staging upload. |
|
||||
| 3: custom/placement | Six heap cases: WRITE_BACK/L0/ALLOW_ALL; WRITE_COMBINE/L0/ALLOW_ALL; WRITE_BACK/L0 with each of the three ALLOW_ONLY restrictions; WRITE_BACK/L1/ALLOW_ALL control. Place a UAV-capable buffer and 64×64 RGBA8 texture together on one WRITE_BACK/L0 heap at disjoint allocation-info-aligned offsets; run `WriteToSubresource`/`ReadFromSubresource` round-trip. |
|
||||
| 4: persistent Map | Two CPU→GPU copies with different magic pairs, followed by UPLOAD→placed GPU copy and direct CPU read through the original pointer. Fence after each; no buffer Unmap/remap or CPU→GPU staging upload in the forward direction. |
|
||||
| 5: latency | WRITE_BACK/L0 at 64 KiB and 256 MiB; WRITE_COMBINE/L0 at 256 MiB; UPLOAD at 256 MiB, in that order. Touch each 64 KiB interval before timing, then 5 warmups and 40 timed submissions. Every iteration updates offsets 0 and size−64, copies 64 bytes from each end to READBACK and checks all 32 words after its fence. Print total ms, average ms/submit, N/40 and warmup matches. |
|
||||
| 6: dirty pages | 64 KiB `MEM_WRITE_WATCH`; write bytes at offsets 0 and 16384; `GetWriteWatch(WRITE_WATCH_FLAG_RESET,...)`; print return, count, granularity and dirty offsets. |
|
||||
|
||||
All CUSTOM test heaps use explicit CPU-page and memory-pool properties; UPLOAD uses the standard heap type. The six creation cases use 2 MiB heaps, mixed placement uses 2 MiB, and the persistent coherence buffer uses a 64 KiB heap. The latency tests use exactly the named buffer/heap sizes and copy only 128 bytes per submit. READBACK buffers are 128 bytes. Latency includes CPU writes, command-list reset/encoding, transitions, queue submission, fence wait, device-status query and comparison; it is not GPU-only time. Prefault and warmups are excluded. No API-validation or verbose loader tracing is enabled in the timed baseline.
|
||||
|
||||
The 64 KiB prefault stride follows the requested experiment; it does not touch every physical 16 KiB host page in the 256 MiB region. A separately named, fully resident memory-overhead experiment is needed before interpreting resident allocation sizes.
|
||||
|
||||
## Synchronization and lifetime
|
||||
|
||||
The CPU finishes stores and executes an x86 store fence before submission. Each submission has its own D3D12 fence value and a bounded event wait. CUSTOM buffers transition from COMMON to COPY_SOURCE/COPY_DEST and back; UPLOAD stays GENERIC_READ and READBACK stays COPY_DEST. The CPU overwrites or reads GPU-used memory only after the previous fence. Resources remain mapped until release, with placed resources destroyed before their heaps. Wrapping allocations, mapping views and mapping handles are retained through any successful visibility test and released after resources and GPU completion.
|
||||
|
||||
The texture is in COMMON, mapped with a null output pointer before the CPU subresource methods, then unmapped after that separate round-trip. A CPU texture round-trip is not a GPU texture coherence test. The baseline does not test simultaneous CPU/GPU access, atomic interoperability, console flush APIs, multiple queues, aliasing barriers, resource reuse while work is in flight, render-target/depth texture placement, other formats or texture GPU readback.
|
||||
|
||||
These rules follow the public [Map contract](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12resource-map), [resource barriers](https://learn.microsoft.com/en-us/windows/win32/direct3d12/using-resource-barriers-to-synchronize-resource-states-in-direct3d-12) and [CPU texture access requirements](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12resource-writetosubresource). They do not establish console semantics.
|
||||
|
||||
## Backend receipt and supplemental investigations
|
||||
|
||||
A selected setting is insufficient to identify the backend. For a **separate, untimed diagnostic** use a new scratch directory:
|
||||
|
||||
```sh
|
||||
python3 docs/research/d3dmetal-zero-copy/run.py \
|
||||
--bottle "/absolute/path/to/an/existing/CrossOver/bottle" \
|
||||
--scratch /tmp/bx-uma-verify/backend-receipt --receipt-only
|
||||
```
|
||||
|
||||
This mode only creates a device, repeats existing-memory wrapping, and pauses for 10 seconds to permit OS loaded-library inspection; it does not replace or change the six-check baseline. The runner enables `--debugmsg -all,+loaddll,+d3d12`. Inspect the specific probe PID with `lsof -n -p <pid>` or `vmmap <pid>` and preserve the app's `apple_gptk/.../d3d12.dll`, `dxgi.dll` and `D3DMetal.framework` paths. Sample only the intended process, not another contributor's Wine session. Avoid including account names or personal paths in committed diagnostics; disclose any excerpts/redactions. The initial runtime inspection is recorded as an excerpt in its run directory.
|
||||
|
||||
Supplemental experiments must be versioned separately and must not alter baseline sizes, checks or iteration counts. Follow-up work includes:
|
||||
|
||||
- Resident/physical memory at allocation, prefault, submission and retirement; record measurement tool, baselines, page residency, compression, pressure and variability. Virtual size alone is insufficient.
|
||||
- Copy profiling that distinguishes shared storage, full-buffer shadow copies and dirty-page copies. Similar small-copy latency is consistent with sharing but does not prove physical aliasing or absence of internal copies.
|
||||
- GPU texture readback/coherence by format/layout and render/depth usage. Buffer success does not establish these.
|
||||
- Dirty-page fallback with reset/rearming races, alignment, coalescing, explicit copies, budget accounting and concurrent writes. Baseline `GetWriteWatch` success does not establish a working fallback.
|
||||
|
||||
## Independent results and acceptance
|
||||
|
||||
Create a new `results/<date>-<chip>-<contributor>-<run>/` directory for every run. Retain raw benchmark stdout/stderr unedited (the local `.gitattributes` preserves their Windows CRLF bytes), exact software/hardware receipts, timeout/exit status, backend evidence, source revision/hash and run limitations. Do not commit the executable, bottle, caches, proprietary frameworks or credentials. A result owner may append new runs; do not rewrite another contributor's measurements. DCO-sign commits with the contributor's existing Git identity and push normally without force. If another contributor updated the shared branch, fetch and reconcile before pushing.
|
||||
|
||||
An independent reviewer must re-derive expected values and API legality from primary sources. The author of this probe has not certified it independently. Require independent results from at least two contributors on at least two Apple Silicon generations, with repeated sessions before scaling claims. M1–M5 are coverage targets, not measured support. Follow the full evidence checklist in #473; unresolved mechanisms remain class U. Hardware readbacks are local class A observations, not independent acceptance or Xbox hardware validation.
|
||||
|
||||
## Provenance and primary sources
|
||||
|
||||
`probe.cpp` and `run.py` are newly authored synthetic research under the repository's GPL-3.0-or-later license. No upstream implementation or emulator code was copied. MinGW-w64 14.0.0 headers and GCC 16.2.0 are externally installed build tools on the initial host. CrossOver 26.3.0.39832, D3DMetal 3.0 and Rosetta 2 are externally installed runtime components; nothing proprietary is redistributed. Existing [upstream registry](../upstream-registry.md) and [reuse matrix](../component-reuse-matrix.md) cover runtime research; this work adds no vendored dependency. Review exact file licenses and update those records before adopting any future third-party source.
|
||||
|
||||
Public API references used to author and review the experiments:
|
||||
|
||||
- [Architecture1 flags](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ns-d3d12-d3d12_feature_data_architecture1) and [heap properties](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ns-d3d12-d3d12_heap_properties).
|
||||
- [OpenExistingHeapFromAddress](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device3-openexistingheapfromaddress) and [OpenExistingHeapFromFileMapping](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device3-openexistingheapfromfilemapping).
|
||||
- [CreatePlacedResource](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device-createplacedresource), [Map](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12resource-map), [WriteToSubresource](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12resource-writetosubresource) and [ReadFromSubresource](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12resource-readfromsubresource).
|
||||
- [GetWriteWatch](https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-getwritewatch).
|
||||
@@ -0,0 +1,81 @@
|
||||
# Workstream A memory and allocation research
|
||||
|
||||
Research for [#473](https://github.com/MacosPorters/betterxen/issues/473), on an isolated worktree based on `9ae6d1ee7092b6021aad075531f50ba60de4fd53`. This work does not change production shims, ABI, main or the six-check baseline. The requester manually published initial A work at 8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8; the final-stage request now authorizes DCO-signed publication of resumed A work on the dedicated research/473-workstream-a-memory branch. Local runs are author observations, not independent acceptance or Xbox compatibility.
|
||||
|
||||
Start with the [research report](report.md) and [existing evidence inventory](inventory/README.md), [ownership feasibility matrix](inverted-ownership.md), [resource/lifetime contract](../gpu-correctness/contracts/resource-placement-lifetime.md), [optional allocator assessment](allocator-assessment.md) and [texture fixtures](../gpu-correctness/textures-and-resources/README.md). See [footprint findings](footprint-findings.md), [pooling findings](pooling-findings.md) and [texture/alias findings](../gpu-correctness/textures-and-resources/findings.md). Findings and review status are tracked in #473.
|
||||
|
||||
## Local protocol A2
|
||||
|
||||
`run.py` is an A-local harness; shared helpers and shared protocol files remain unchanged pending reciprocal coordination. `support.h` reuses the preserved original supplemental queue/buffer and full-consumption shader logic, formatted for readability, with shader capture added. It does not run B's dirty-page/coherence/tracking suite. The historical code's exact original bytes/hashes remain in `inventory/frozen-phase2/`.
|
||||
|
||||
Requirements: native ARM64 macOS, licensed externally installed CrossOver/D3DMetal/Rosetta, existing win64 bottle, native MinGW-w64 C++20 compiler, Python 3.11+, public Apple Command Line Tools. Compilation uses `-O2 -static -static-libgcc -static-libstdc++ -Wall -Wextra -Werror`; observer uses `xcrun clang++ -arch arm64`. Exact commands, native-tool architecture/linkage, source/executable/shader hashes and environment are retained in each receipt. The observed Wine compiler warns that optimization flag 0x8000 is ignored; no compiler optimization claim is inferred.
|
||||
|
||||
```sh
|
||||
python3 docs/research/d3dmetal-zero-copy/allocation-profiling/run.py \
|
||||
--bottle "/absolute/path/to/an/existing/win64/bottle" \
|
||||
--scratch /tmp/bx473-a-memory-run --suite memory
|
||||
python3 docs/research/d3dmetal-zero-copy/allocation-profiling/run.py \
|
||||
--bottle "/absolute/path/to/an/existing/win64/bottle" \
|
||||
--scratch /tmp/bx473-a-pool-run --suite pool
|
||||
python3 docs/research/d3dmetal-zero-copy/allocation-profiling/run.py \
|
||||
--bottle "/absolute/path/to/an/existing/win64/bottle" \
|
||||
--scratch /tmp/bx473-a-texture-run --suite texture
|
||||
```
|
||||
|
||||
Each scratch directory must be new and outside the checkout. Add `--smoke` for a reduced harness check, recorded separately. The runner copies the source bottle privately, selects D3DMetal, sets ROSETTA_ADVERTISE_AVX=1 and WINEDEBUG=-all, rejects a loaded d3d12_xs shim in the guest and captures loaded framework/DLL/Rosetta paths at a paused checkpoint. It records missing tools and failures. It stops only its private Wine server and checks the source configuration unchanged. It does not download/install or redistribute proprietary components. Disposable bottle scanner/trust settings permit the original locally built probe; source bottle settings are untouched.
|
||||
|
||||
One A process owns `/tmp/betterxen-473-gpu.lock` for a batch. Other contributors must coordinate the single-GPU-workload rule; this local advisory lock cannot exclude unrelated applications. No profiling/polling is performed inside allocation API timing windows. A process timeout is 240 seconds; GPU fence waits are bounded at 10 seconds. The initial A2 sweep used free-percentage guards only and was interrupted after observing kernel pressure level 2. A-local-2.1 additionally required kern.memorystatus_vm_pressure_level=0 before each case and at each snapshot. After the requester freed memory and explicitly allowed bounded continuation, A-local-2.2 added an explicit --allow-warning profile that permits level 1 while still stopping at >=2; its receipts record that selection. Default behavior still requires level 0. Warning-profile observations are not relabeled as normal-pressure evidence. It retains the 30%/25% free-percentage guards, but does not interpret those percentages as an OS pressure class. Unreadable pressure also stops the run. The partial A2 profile is not a completed two-session sweep. Existing swap/background load is retained in receipts; no idle-machine benchmark claim is made.
|
||||
|
||||
## Footprint correction
|
||||
|
||||
For two sessions, run each of 64/256/1024 MiB in a fresh process using CPU-only without graphics, graphics-warmed CPU allocation control, CUSTOM/WB/L0 and UPLOAD. Reverse size/type order in the second session. No optional >1 GiB allocation is part of this run. The graphics cases reuse the historical full-consumption checksum shader, write every source word and validate 256 checksum words after the fence; checksum agreement is not byte-exact evidence for every source word.
|
||||
|
||||
Checkpoints: warmed baseline, settled baseline, allocation/placement, Map, full initialization, full GPU consumption, resource release, disposal of command/output/pipeline objects, settled retirement, device release. CPU controls explicitly report GPU consumption not run. DLL/framework handles remain loaded at device release; it is not process exit or a guarantee of runtime-pool reclamation.
|
||||
|
||||
At each paused stage retain three proc_pid_rusage snapshots, `footprint -f bytes --swapped`, `vmmap -summary`, mapped-pointer `vmmap -w PID ADDRESS` where applicable, `vm_stat`, memory-pressure and swap readings. Tools execute sequentially, so readings can differ. Three samples at one pause are correlated snapshots, not three independent sessions. Virtual range size, RSS, physical-footprint accounting and graphics retention are reported separately; do not add categories or infer physical page identity.
|
||||
|
||||
## Pooling and retirement trace
|
||||
|
||||
Compare per-resource CUSTOM/WB/L0 heaps against one 32 MiB heap with placed suballocations, using matched seeds, buffer descriptions/alignment and GPU work. Three fresh-process pairs alternate case order. Each has two warmup cycles and ten measured cycles over 24 live slots with non-aligned requested sizes 65540, 262148, 393220 and 1048580 bytes. Allocate all, verify, free even slots, refill with seeded varied sizes, verify again, free all and check free-list coalescing. No grow/unbounded allocation occurs.
|
||||
|
||||
Each ALLOC retains heap/suballocation, placement and Map API timings; FREE retains resource and backing/free-list costs. Initialization, I/O and GPU work are outside these API samples. Cycle time includes them and is descriptive; the live snapshot pause is explicitly subtracted. A one-time pooled heap setup is separately recorded and must be included when comparing first-use costs. No benchmark improvement is promised.
|
||||
|
||||
Logical records track live payload, allocation-aligned live bytes, reserved backing, alignment waste, free space and largest free span. Individual heaps have no reusable cross-heap free span; report this as not applicable. Pool slack and logical fragmentation are not process footprint. GPU readback checks leading/trailing guards and an interior region for each live buffer, not every byte. A real gate-delayed queued copy verifies that the allocator withholds a pending range; it opens the gate before waiting and frees only after completion. The trace also rejects a fictitious future retirement value as a policy control. Every reused placed resource is activated; command list reset occurs after completed work and before resources are released. B's independent barrier/fence review remains required.
|
||||
|
||||
## Host ceiling and reduced profiles
|
||||
|
||||
The requester set a 23 GB RAM-use ceiling. A-local-2.2 records a conservative non-file-cache occupied estimate derived from physical RAM minus free and file-backed pages in vm_stat; this is not an exact Activity Monitor value. Before starting a case it reserves headroom below 23,000,000,000 bytes for twice the source plus 512 MiB (memory suite), or 512 MiB (small suites). It stops at paused checkpoints if the remaining margin falls below 256 MiB. This observation-based guard cannot control concurrent applications; the fixed source/slab caps and urgent-pressure stop remain necessary. A skipped case is recorded as not-run and makes the profile incomplete. No 2 GiB extension is used.
|
||||
|
||||
Use --allow-warning only with the requester's explicitly permitted warning-pressure conditions; otherwise default normal-pressure gating remains in force. A ceiling is not a target. Keep all actual reservations, pressure signals, swap changes and raw failures visible.
|
||||
|
||||
For the pool omitted-copy control, add --negative-control to --suite pool; the guest must fail with the specific trace guard/interior mismatch. The harness validates that expected failure separately. The texture matrix currently fails its negative-rejection gate on this runtime; all two sessions still run, and the batch returns failure. --suite alias performs the separate valid buffer-inheritance follow-up.
|
||||
|
||||
## Bottle receipt correction
|
||||
|
||||
Source review found that the historical/plain string insertion of AllowUntrusted matched the commented Bottle heading before the actual section. A22 run receipts preserve that malformed requested-setting line rather than claiming it was applied correctly; the appended scanner setting and actual loaded backend are separately recorded. Current run.py anchors the insertion to the actual section line and checks its construction without writing the source bottle. This configuration-only correction was made after the GPU runs; a post-correction launch is not claimed. Exact prior executed runner snapshots remain in every run bundle.
|
||||
|
||||
## Resumed evidence
|
||||
|
||||
[Handoff to Asufte](handoff-asufte.md) links the exact manually published pin and executed historical/A2/A22 sources. [B review expectations](b-review-expectations.md) distinguish attributed M5 reports from source-reviewed reproduction. The new [logical fragmentation study](fragmentation/README.md) exercises saturated holes and retirement without GPU/physical allocation claims. The [external allocator experiment](allocator-evaluation/README.md) adds isolated build/runtime evidence under registry/license controls, without a production dependency.
|
||||
|
||||
## Resumed A-local-2.3 status
|
||||
|
||||
The [Asufte handoff](handoff-asufte.md) pins the initial publication and distinguishes historical B-related sources from corrected A2/A22 work. New [logical fragmentation](fragmentation/README.md) and [isolated allocator](allocator-evaluation/README.md) studies extend allocation evidence; [B review expectations](b-review-expectations.md) and [actual B review](review-b.md) distinguish completed source/data checks from pending hardware/trace validation. The [continuation status](resume-status.md) lists completed, failed and blocked work without reclassifying interrupted profiles.
|
||||
|
||||
Version 2.3 adds the separate graphics `--suite render`, an omitted-draw control and an early headroom/kernel-pressure check before cloning a private bottle. The default memory profile remains 64/256/1024 MiB × all four controls/types × two repeats. Explicit `--memory-sizes`, `--memory-types`, `--memory-repeats` and `--memory-repeat-start` permit a recorded subset to fill a missing case without rerunning completed cases; a subset is never a completed common profile. A 256 MiB graphics continuation can use `--memory-sizes 256 --memory-types wb,upload --memory-repeats 1 --memory-repeat-start 1` only when all safety gates permit it. Default normal-pressure and explicitly selected warning-pressure runs remain distinct. The original six-check baseline is unaffected.
|
||||
|
||||
A-local-2.4 subsequently adds a proposed process-exit policy for unproven fence completion, following B's independent safety finding. It was initially compile-only; B subsequently independently reviewed it and ran bounded M5 positive/exit/timeout cases, accepted only for single-threaded disposable research guests. See [A review of published B](review-b.md) for the actual source/data checks and remaining reproduction/trace-input questions.
|
||||
|
||||
## Final-stage publication and consolidation draft
|
||||
|
||||
The remaining A research is published at `8c9eceb05ab660504ee981c2f4fcaf1728a5dbff` on the dedicated `research/473-workstream-a-memory` branch. The [pinned handoff](https://github.com/MacosPorters/betterxen/issues/473#issuecomment-7204949581) requests B's independent inspection. The [publication audit](publication-audit.md) records historical missing sources and the verbatim-snapshot whitespace warning rather than hiding them.
|
||||
|
||||
The A-owned [consolidation draft](consolidation-draft/report.md), [joint evidence register](consolidation-draft/evidence-register.md) and [implementation proposal](consolidation-draft/implementation-roadmap.md) remain review drafts while single-author/independent-reviewer ownership is confirmed. Shared root findings, production, ABI and main are unchanged. The original fixed baseline remains frozen; publication does not imply independent acceptance.
|
||||
|
||||
## Final reciprocal verification update (local)
|
||||
|
||||
B's review/evidence at `4ba4926d2f491517c01b1e94fb8539184055dc22` is incorporated in the [final verification findings](final-verification/findings.md) and [joint report](consolidation-draft/report.md). All seven CPU XML extractions reproduce exactly. Thirteen register entries have narrowly scoped independent acceptance; incomplete graphics/accounting and M4 B hardware runs remain blocked. A independently confirms a combined-budget source defect and a remaining failed-cleanup propagation issue. The historical failed receipts and unsupported/unknown mechanisms remain explicit. This update is authorized for dedicated A-branch publication; branch integration, main and production changes remain unauthorized.
|
||||
|
||||
## Integrated record
|
||||
|
||||
The sections above are a dated history of Workstream A's branch; their "pending", "draft" and "unauthorized" statements describe the time they were written. B [signed off the consolidation at d3ae607](https://github.com/MacosPorters/betterxen/issues/473#issuecomment-7206014568). Current inputs, deliverables and limitations are in the [integration record](../integration.md).
|
||||
@@ -0,0 +1,35 @@
|
||||
# Optional allocator reference assessment
|
||||
|
||||
Reviewed 2026-11-26: AMD's [D3D12 Memory Allocator](https://github.com/GPUOpen-LibrariesAndSDKs/D3D12MemoryAllocator/tree/600949266be004553f74c9ef809384380a9d44cf), exact commit `600949266be004553f74c9ef809384380a9d44cf`; the pinned header reports version 3.3.0. This is a public, general-purpose GPUOpen allocation library, with no game/console material used in this assessment.
|
||||
|
||||
The exact files reviewed were [LICENSE.txt](https://github.com/GPUOpen-LibrariesAndSDKs/D3D12MemoryAllocator/blob/600949266be004553f74c9ef809384380a9d44cf/LICENSE.txt), [include/D3D12MemAlloc.h](https://github.com/GPUOpen-LibrariesAndSDKs/D3D12MemoryAllocator/blob/600949266be004553f74c9ef809384380a9d44cf/include/D3D12MemAlloc.h) (Git blob `b685a5cd6188519606efaf039cd88c2faffa261a`) and [src/D3D12MemAlloc.cpp](https://github.com/GPUOpen-LibrariesAndSDKs/D3D12MemoryAllocator/blob/600949266be004553f74c9ef809384380a9d44cf/src/D3D12MemAlloc.cpp) (blob `b7ba60a3a4deb0ed466b235b7c5298f91ba5c976`). Both source files carry the full AMD 2019–2026 MIT notice. The MIT grant permits use/modification/distribution while requiring preservation of its notice; it is compatible with inclusion in a GPL-3.0-or-later work under those obligations. This does not license CrossOver/D3DMetal/Rosetta or change their external status.
|
||||
|
||||
At the initial assessment, no source from this project had been copied, compiled, linked, modified or adopted. The resumed isolated experiment below supersedes that build/runtime status; no source is adopted in production. A's small first-fit trace allocator is original experimental code, not an alternative production allocator. Exact registry/reuse-matrix entries and preserved upstream notices are required before any future source integration; that would be a separately scoped decision.
|
||||
|
||||
| Requirement | Pinned source/API assessment | What remains unmeasured |
|
||||
| --- | --- | --- |
|
||||
| CUSTOM WB/WC L0 pools | POOL_DESC accepts D3D12_HEAP_PROPERTIES and heap flags; configurable block size/counts provide a plausible fit. | CreatePool/resource behavior under this exact CrossOver/D3DMetal build. |
|
||||
| Placed buffers/textures | Existing allocator handles resource allocation alignment and heap-tier separation; alias resources are documented. | Our mixed/RT/depth cases through the allocator, not merely raw D3D12. |
|
||||
| Pool bounds and accounting | Explicit block sizing and max counts can bound reservations; detailed statistics distinguish allocations, blocks and unused ranges. | Memory cost and latency against the A trace; its budget reports are DXGI estimates, not physical residency or BetterXen's unified title budget. |
|
||||
| Fragmentation | Multiple allocation algorithms/statistics and defragmentation support exist. | BetterXen workloads, fixed-pointer constraints and migration cost. Moving a guest-visible mapped allocation cannot silently preserve pointer identity. |
|
||||
| Fence retirement | Caller must ensure GPU use is complete before freeing/reassigning allocation/resource storage. Library allocation ownership is not a substitute for application queue/fence tracking. | Multi-queue retirement integration and stress. |
|
||||
| Inverted CPU ownership | Resource Map remains a public D3D12 operation; allocator metadata cannot add requested CPU-VA or arbitrary scatter/section alias semantics. | No evidence that this library solves the infeasible rows in the [ownership matrix](inverted-ownership.md). |
|
||||
| Portability/toolchain | Header has a path for externally supplied D3D12-compatible headers; implementation explicitly handles MinGW variants. | Initial source assessment had no runtime test; the separately versioned resumed buffer study below adds narrow evidence. |
|
||||
|
||||
Initial recommendation was to evaluate this reuse candidate with an externally built pinned version before selection; the later isolated study below partially supplies that evidence. Raw-D3D12 pooling results cannot be presented as this allocator's performance, fragmentation quality or CrossOver compatibility. Documentation/source assessment is class D (project evidence); public D3D12 contracts are class B. Independent review and runtime qualification remain pending.
|
||||
|
||||
## Resumed isolated evaluation
|
||||
|
||||
After per-file notice revalidation and registry/reuse-matrix entries, exact unmodified files were obtained into ignored artifacts and verified against their Git blobs. Python urllib initially failed TLS certificate verification before obtaining bytes; normal verified curl succeeded. TLS verification was not disabled. The original [evaluation harness](allocator-evaluation/README.md) compiled cleanly with strict flags.
|
||||
|
||||
A [WB/WC pilot](../results/2026-11-26-apple-m4-arths17-external-allocator-pilot/receipt.json) ran when kernel pressure improved to the explicitly permitted Warning profile. Each fresh process completed 24 guard/interior readbacks across two warmup plus ten measured cycles. Library statistics stayed at one 33,554,432-byte block and returned zero live allocation bytes/count with largest free span equal to the block size at every empty checkpoint. The pilot's seed-473 payload/phase/slot sequence matches all 432 published raw-trace allocation requests. Combined CreateResource median was 0.0011 ms in both pilot types; this is a different API aggregation/session from the earlier raw allocator, not a controlled speedup claim.
|
||||
|
||||
This is new version-scoped author-run buffer/pool/statistics evidence, not qualification of every D3D12MA feature. Caller-managed fence/command retirement remains necessary. Texture allocation through the library, multi-queue use, defragmentation/migration, device-loss handling, all heap-tier restrictions and independent review remain open. The separately recorded bounded-request/repeated-seed run is described below. Registry source notices and external/no-production boundaries are unchanged.
|
||||
|
||||
## Repeated bounded-buffer result
|
||||
|
||||
[Six fresh processes](../results/2026-11-26-apple-m4-arths17-external-allocator-bounded/receipt.json) alternated WB/WC order across seeds 473/474/475. Every process exited 0 without a timeout. All 24 readback events per process matched 1152/1152 sampled leading/interior/trailing words; this samples each buffer, rather than verifying every initialized byte. The valid 33,554,436-byte request returned E_OUTOFMEMORY (0x8007000E) in all six cases without growing the single 32 MiB pool. Caller-managed completed fences and command reset precede each release.
|
||||
|
||||
The separate [analysis program](allocator-evaluation/analyze.py) derives free gaps from recorded live intervals, checks bounds/overlap and every reported full/holes/empty statistic, and compares each phase/slot/request size with the original corrected raw-pool seed. All 432 allocation requests per process matched; 36 statistics checkpoints per process matched the independent interval calculation. Both producer and checker are author work and remain subject to independent contributor acceptance. Empty checkpoints consistently reported zero live allocations with 33,554,432 bytes as the largest free range; block retention is explicitly configured, not a measured leak.
|
||||
|
||||
Measured CreateResource medians were 0.00105–0.00110 ms and whole-cycle medians 9.73–10.00 ms across these sessions. CreateResource combines library allocation and D3D12 placement. Earlier raw allocation-call costs are separate API boundaries, and the sessions were non-idle under existing swap and warning pressure. No controlled performance superiority, physical memory savings, automatic queue-fence retirement, texture/heap-tier qualification or production adoption follows from these data.
|
||||
@@ -0,0 +1,23 @@
|
||||
# External allocator compatibility experiment
|
||||
|
||||
A separately versioned, original Workstream A harness evaluates AMD D3D12 Memory Allocator 3.3.0 at `600949266be004553f74c9ef809384380a9d44cf`. The [assessment](../allocator-assessment.md), upstream registry and reuse matrix record per-file MIT notices and exact Git blob identities before obtaining the external files. Vendor source remains unchanged in ignored artifacts; no production dependency or vendored implementation is added.
|
||||
|
||||
Supply the exact pinned `D3D12MemAlloc.h`, `D3D12MemAlloc.cpp` and `LICENSE.txt` in an external directory. The runner checks all three Git blob hashes, preserves the original notices and records SHA-256 identities. It uses native ARM64 MinGW-w64 host tools to build a Windows guest, with `-O2 -static -static-libgcc -static-libstdc++ -Wall -Wextra -Werror`. Only the original probe/harness and metadata are part of the research source tree. Build/runtime executables remain local.
|
||||
|
||||
```sh
|
||||
python3 docs/research/d3dmetal-zero-copy/allocation-profiling/allocator-evaluation/run.py --external /absolute/path/to/pinned/files --scratch /tmp/bx473-allocator-review --bottle /absolute/path/to/existing/win64/bottle
|
||||
```
|
||||
|
||||
Default execution requires normal pressure; the explicitly authorized `--allow-warning` profile permits warning but stops on urgent pressure. The conservative 23 GB host metric reserves 512 MiB headroom for this small workload. The pool is exactly one 32 MiB block (minimum and maximum block counts both 1); source buffers and GPU work are bounded. `--build-only` compiles without launching a guest. All command arrays, source/PE hashes, native observer architecture, backend evidence, pressure/footprint/vmmap checkpoints, exit/timeout status and raw outputs are retained in new scratch paths.
|
||||
|
||||
Two warmup and ten measured cycles use the same 24-slot payload sequence as the original seed-matched raw pooling trace. The original trace consumes one random draw for its gate control, so this reference deliberately advances that one draw before its comparable allocation sequence. Every live buffer is initialized and its leading/interior/trailing regions GPU-copied to readback. Releases occur after the completed queue fence and command-list reset. The library does not thereby become an automatic fence-retirement system.
|
||||
|
||||
A valid request for 33,554,436 bytes exceeds this explicit one-block pool. It must fail without growing the pool; an unexpected success is a fixture failure. Allocation statistics are checked after full/holes/empty phases; an empty pool can retain its one block by configuration. Statistics are logical library accounting, not physical residency. The pilot and repeated-bound fixture have distinct executed source snapshots. Timing comparisons must account for combined allocator+placement API versus the original separate calls, cold setup, different sessions and CPU load; these data alone do not establish an application benefit.
|
||||
|
||||
The [six-case bounded raw bundle](../../results/2026-11-26-apple-m4-arths17-external-allocator-bounded/receipt.json) can be rechecked without a GPU:
|
||||
|
||||
```sh
|
||||
python3 docs/research/d3dmetal-zero-copy/allocation-profiling/allocator-evaluation/analyze.py docs/research/d3dmetal-zero-copy/results/2026-11-26-apple-m4-arths17-external-allocator-bounded --raw-pool-results docs/research/d3dmetal-zero-copy/results/2026-11-26-apple-m4-arths17-a22-pool-corrected --output /tmp/bx473-allocator-analysis.json
|
||||
```
|
||||
|
||||
This separately derives free gaps from recorded live intervals, checks every reported statistic and compares exact request sequences; it does not reuse the library's allocation algorithm. Both producer/checker are author work. The [assessment](../allocator-assessment.md) states the measured scope and unqualified features.
|
||||
@@ -0,0 +1,96 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Re-derive recorded allocator spans/statistics; no upstream allocation algorithm used."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import statistics
|
||||
|
||||
|
||||
def fields(line):
|
||||
return dict(re.findall(r'(\w+)=([^\s]+)', line))
|
||||
|
||||
|
||||
def check(condition, detail):
|
||||
if not condition:
|
||||
raise ValueError(detail)
|
||||
|
||||
|
||||
def analyze(root, raw):
|
||||
receipt = json.loads((root / 'receipt.json').read_text())
|
||||
check(len(receipt['cases']) == 6 and not receipt.get('stop_reason'), 'incomplete six-case profile')
|
||||
result = {'scope': 'author-written data re-derivation, independent acceptance pending', 'cases': []}
|
||||
for case in receipt['cases']:
|
||||
check(case['exit'] == 0 and not case['timed_out'], case['name'])
|
||||
text = (root / case['name'] / 'stdout.txt').read_text()
|
||||
live, requests, allocations, frees, cycles = {}, [], [], [], []
|
||||
verified = stats = bound = 0
|
||||
peak_payload = peak_reserved = peak_waste = 0
|
||||
for line in text.splitlines():
|
||||
v = fields(line)
|
||||
if line.startswith('POOL_BOUND_CONTROL '):
|
||||
check(v['rejected'] == '1' and v['HRESULT'] == '0x8007000E', line)
|
||||
bound += 1
|
||||
elif line.startswith('REFERENCE_ALLOC '):
|
||||
slot, size, reserved, offset = (int(v[k]) for k in ['slot', 'bytes', 'allocation_size', 'offset'])
|
||||
check(slot not in live and offset % 65536 == 0 and reserved >= size and offset + reserved <= 33554432, line)
|
||||
check(all(offset + reserved <= a[0] or a[0] + a[1] <= offset for a in live.values()), 'overlap: ' + line)
|
||||
live[slot] = (offset, reserved, size)
|
||||
peak_payload = max(peak_payload, sum(a[2] for a in live.values()))
|
||||
peak_reserved = max(peak_reserved, sum(a[1] for a in live.values()))
|
||||
peak_waste = max(peak_waste, sum(a[1] - a[2] for a in live.values()))
|
||||
requests.append(tuple(int(v[k]) for k in ['cycle', 'phase', 'slot', 'bytes']))
|
||||
if int(v['cycle']) >= 0:
|
||||
allocations.append(float(v['create_resource_ms']))
|
||||
elif line.startswith('REFERENCE_FREE '):
|
||||
check(int(v['slot']) in live, line)
|
||||
del live[int(v['slot'])]
|
||||
if int(v['cycle']) >= 0:
|
||||
frees.append(float(v['release_resource_and_allocation_ms']))
|
||||
elif line.startswith('ALLOCATOR_STATS '):
|
||||
spans = sorted(live.values())
|
||||
cursor, gaps = 0, []
|
||||
for start, length, _ in spans:
|
||||
if start > cursor:
|
||||
gaps.append(start - cursor)
|
||||
cursor = start + length
|
||||
if cursor < 33554432:
|
||||
gaps.append(33554432 - cursor)
|
||||
expected = dict(blocks=1, block_bytes=33554432, allocation_count=len(live), allocation_bytes=sum(a[1] for a in spans), unused_ranges=len(gaps), largest_free=max(gaps, default=0))
|
||||
check(all(int(v[k]) == value for k, value in expected.items()), ('statistics', v, expected))
|
||||
stats += 1
|
||||
elif line.startswith('REFERENCE_VERIFY '):
|
||||
actual, total = map(int, v['matched'].split('/'))
|
||||
check(actual == total == 24 * 3 * 16 and len(live) == 24, line)
|
||||
verified += 1
|
||||
elif line.startswith('REFERENCE_CYCLE ') and int(v['cycle']) >= 0:
|
||||
cycles.append(float(v['ms']))
|
||||
check(not live and len(requests) == 432 and len(allocations) == len(frees) == 360 and len(cycles) == 10 and stats == 36 and verified == 24 and bound == 1 and text.rstrip().endswith('END success'), 'missing events: ' + case['name'])
|
||||
seed = int(case['name'].rsplit('-', 1)[1])
|
||||
original = (raw / f'pool-pooled-s{seed - 473}' / 'stdout.txt').read_text()
|
||||
original_requests = []
|
||||
for line in original.splitlines():
|
||||
if line.startswith('ALLOC '):
|
||||
v = fields(line)
|
||||
if int(v['iteration']) >= -2:
|
||||
original_requests.append(tuple(int(v[k]) for k in ['iteration', 'phase', 'slot', 'bytes']))
|
||||
check(requests == original_requests, 'request sequence differs from seed-matched raw trace')
|
||||
result['cases'].append(dict(name=case['name'], stdout_sha256=hashlib.sha256((root / case['name'] / 'stdout.txt').read_bytes()).hexdigest(), peak_live_payload_bytes=peak_payload, peak_reserved_suballocation_bytes=peak_reserved, peak_internal_rounding_bytes=peak_waste, matched_raw_requests=len(requests), statistics_checked=stats, readbacks_checked=verified, oversized_request_rejected=True, measured_allocations=len(allocations), create_resource_median_ms=statistics.median(allocations), release_median_ms=statistics.median(frees), cycle_median_ms=statistics.median(cycles)))
|
||||
return result
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description=__doc__)
|
||||
ap.add_argument('results', type=Path)
|
||||
ap.add_argument('--raw-pool-results', type=Path, required=True)
|
||||
ap.add_argument('--output', type=Path, required=True)
|
||||
a = ap.parse_args()
|
||||
result = analyze(a.results, a.raw_pool_results)
|
||||
a.output.write_text(json.dumps(result, indent=2) + '\n')
|
||||
print(json.dumps(result, indent=2))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,234 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Original isolated compatibility/statistics fixture; upstream allocator stays
|
||||
// external.
|
||||
#include "../support.h"
|
||||
#include "D3D12MemAlloc.h"
|
||||
#include <memory>
|
||||
#include <random>
|
||||
static void stage(const char *name) {
|
||||
std::printf("STAGE %s cpu_ptr=0\n", name);
|
||||
if (std::getchar() == EOF)
|
||||
throw std::runtime_error("stage handshake");
|
||||
}
|
||||
static double ms(double start) {
|
||||
return (ticks() - start) * 1000 / frequency();
|
||||
}
|
||||
struct Item {
|
||||
Ref<D3D12MA::Allocation> allocation;
|
||||
Ref<ID3D12Resource> resource;
|
||||
UINT64 bytes = 0;
|
||||
UINT seed = 0;
|
||||
void *cpu = nullptr;
|
||||
};
|
||||
static void statistics(D3D12MA::Pool *pool, int cycle, const char *label) {
|
||||
D3D12MA::DetailedStatistics s{};
|
||||
pool->CalculateStatistics(&s);
|
||||
std::printf("ALLOCATOR_STATS cycle=%d phase=%s blocks=%u block_bytes=%llu "
|
||||
"allocation_count=%u allocation_bytes=%llu unused_ranges=%u "
|
||||
"largest_free=%llu\n",
|
||||
cycle, label, s.Stats.BlockCount, s.Stats.BlockBytes,
|
||||
s.Stats.AllocationCount, s.Stats.AllocationBytes,
|
||||
s.UnusedRangeCount, s.UnusedRangeSizeMax);
|
||||
if (s.Stats.BlockCount > 1 || s.Stats.BlockBytes > 33554432ULL)
|
||||
throw std::runtime_error("allocator pool exceeded bound");
|
||||
}
|
||||
int main(int argc, char **argv) {
|
||||
setvbuf(stdout, nullptr, _IONBF, 0);
|
||||
try {
|
||||
if (argc != 3)
|
||||
throw std::runtime_error("usage: allocator wb|wc SEED");
|
||||
std::string type = argv[1];
|
||||
if (type != "wb" && type != "wc")
|
||||
throw std::runtime_error("type");
|
||||
UINT seed = UINT(std::strtoul(argv[2], nullptr, 10));
|
||||
std::mt19937 rng(seed);
|
||||
Context c;
|
||||
identity(c);
|
||||
HMODULE dxgi = LoadLibraryA("dxgi.dll");
|
||||
using Factory = HRESULT(WINAPI *)(UINT, REFIID, void **);
|
||||
Ref<IDXGIFactory4> factory;
|
||||
require(symbol<Factory>(dxgi, "CreateDXGIFactory2")(
|
||||
0, __uuidof(IDXGIFactory4), factory.out()),
|
||||
"allocator factory");
|
||||
Ref<IDXGIAdapter> adapter;
|
||||
require(factory->EnumAdapterByLuid(c.device->GetAdapterLuid(),
|
||||
__uuidof(IDXGIAdapter), adapter.out()),
|
||||
"allocator actual adapter");
|
||||
Ref<D3D12MA::Allocator> allocator;
|
||||
D3D12MA::ALLOCATOR_DESC ad{};
|
||||
ad.Flags = D3D12MA::ALLOCATOR_FLAG_SINGLETHREADED;
|
||||
ad.pDevice = c.device.p;
|
||||
ad.pAdapter = adapter.p;
|
||||
ad.PreferredBlockSize = 33554432;
|
||||
double start = ticks();
|
||||
require(D3D12MA::CreateAllocator(&ad, &allocator.p),
|
||||
"D3D12MA CreateAllocator");
|
||||
std::printf("ALLOCATOR_CREATE type=%s ms=%.6f\n", type.c_str(), ms(start));
|
||||
std::unique_ptr<Queue> q = std::make_unique<Queue>(c.device.p);
|
||||
Buffer read;
|
||||
read.allocate(c.device.p, 24 * 192, "readback");
|
||||
read.map();
|
||||
stage("baseline");
|
||||
Ref<D3D12MA::Pool> pool;
|
||||
D3D12MA::POOL_DESC pd{};
|
||||
pd.HeapProperties = properties(D3D12_HEAP_TYPE_CUSTOM);
|
||||
pd.HeapProperties.CPUPageProperty =
|
||||
type == "wb" ? D3D12_CPU_PAGE_PROPERTY_WRITE_BACK
|
||||
: D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE;
|
||||
pd.HeapProperties.MemoryPoolPreference = D3D12_MEMORY_POOL_L0;
|
||||
pd.HeapFlags = D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS;
|
||||
pd.BlockSize = 33554432;
|
||||
pd.MinBlockCount = 1;
|
||||
pd.MaxBlockCount = 1;
|
||||
start = ticks();
|
||||
require(allocator->CreatePool(&pd, &pool.p), "D3D12MA CreatePool");
|
||||
std::printf("ALLOCATOR_POOL type=%s ms=%.6f bytes=33554432 min_blocks=1 "
|
||||
"max_blocks=1\n",
|
||||
type.c_str(), ms(start));
|
||||
stage("heap_ready");
|
||||
// Valid allocation request that cannot fit an explicit, single 32 MiB pool.
|
||||
{
|
||||
D3D12MA::ALLOCATION_DESC request{};
|
||||
request.CustomPool = pool.p;
|
||||
auto tooLarge = bufferDesc(33554436);
|
||||
Ref<D3D12MA::Allocation> a;
|
||||
Ref<ID3D12Resource> resource;
|
||||
HRESULT rejected = allocator->CreateResource(
|
||||
&request, &tooLarge, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, &a.p,
|
||||
__uuidof(ID3D12Resource), resource.out());
|
||||
std::printf("POOL_BOUND_CONTROL requested_bytes=33554436 HRESULT=0x%08lX "
|
||||
"rejected=%d\n",
|
||||
(unsigned long)rejected, FAILED(rejected));
|
||||
if (SUCCEEDED(rejected))
|
||||
throw std::runtime_error(
|
||||
"single-block pool accepted oversized request");
|
||||
}
|
||||
|
||||
// Match the published raw trace RNG draw used by its separate gate-control
|
||||
// allocation.
|
||||
(void)rng();
|
||||
std::array<Item, 24> live;
|
||||
auto allocate = [&](int slot, int cycle, int phase) {
|
||||
auto &item = live[slot];
|
||||
UINT64 sizes[] = {65540, 262148, 1048580, 393220};
|
||||
item.bytes = sizes[rng() % 4];
|
||||
item.seed = seed ^ UINT(cycle + 11) * 0x1020301u ^ UINT(slot) * 0x9001u ^
|
||||
UINT(phase) * 0xB3u;
|
||||
auto desc = bufferDesc(item.bytes);
|
||||
D3D12MA::ALLOCATION_DESC d{};
|
||||
d.CustomPool = pool.p;
|
||||
double t = ticks();
|
||||
require(allocator->CreateResource(
|
||||
&d, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr,
|
||||
&item.allocation.p, __uuidof(ID3D12Resource),
|
||||
item.resource.out()),
|
||||
"D3D12MA CreateResource");
|
||||
double createMs = ms(t);
|
||||
t = ticks();
|
||||
D3D12_RANGE empty{0, 0};
|
||||
require(item.resource->Map(0, &empty, &item.cpu), "D3D12MA resource Map");
|
||||
double mapMs = ms(t);
|
||||
if (!item.cpu)
|
||||
throw std::runtime_error("allocator null Map");
|
||||
auto cpu = static_cast<volatile uint32_t *>(item.cpu);
|
||||
for (UINT64 i = 0; i < item.bytes / 4; ++i)
|
||||
cpu[i] = pattern(i, item.seed);
|
||||
_mm_sfence();
|
||||
std::printf("REFERENCE_ALLOC cycle=%d phase=%d slot=%d bytes=%llu "
|
||||
"allocation_size=%llu offset=%llu create_resource_ms=%.6f "
|
||||
"map_ms=%.6f\n",
|
||||
cycle, phase, slot, item.bytes, item.allocation->GetSize(),
|
||||
item.allocation->GetOffset(), createMs, mapMs);
|
||||
};
|
||||
auto release = [&](int slot, int cycle) {
|
||||
auto &item = live[slot];
|
||||
if (q->fence->GetCompletedValue() < q->value)
|
||||
throw std::runtime_error("unsafe allocator retirement");
|
||||
double t = ticks();
|
||||
item.resource->Unmap(0, nullptr);
|
||||
item.cpu = nullptr;
|
||||
item.resource.clear();
|
||||
item.allocation.clear();
|
||||
std::printf("REFERENCE_FREE cycle=%d slot=%d "
|
||||
"release_resource_and_allocation_ms=%.6f\n",
|
||||
cycle, slot, ms(t));
|
||||
};
|
||||
auto verify = [&](int cycle, int phase) {
|
||||
q->begin();
|
||||
std::memset(read.cpu, 0xA7, 24 * 192);
|
||||
for (int slot = 0; slot < 24; ++slot) {
|
||||
auto &x = live[slot];
|
||||
if (!x.resource.p)
|
||||
continue;
|
||||
D3D12_RESOURCE_BARRIER b{};
|
||||
b.Type = D3D12_RESOURCE_BARRIER_TYPE_ALIASING;
|
||||
b.Aliasing.pResourceAfter = x.resource.p;
|
||||
q->list->ResourceBarrier(1, &b);
|
||||
for (int part = 0; part < 3; ++part) {
|
||||
UINT64 offset = part == 0 ? 0
|
||||
: part == 1 ? x.bytes / 2 / 4 * 4
|
||||
: x.bytes - 64;
|
||||
q->list->CopyBufferRegion(read.resource.p, slot * 192 + part * 64,
|
||||
x.resource.p, offset, 64);
|
||||
}
|
||||
}
|
||||
q->finish();
|
||||
UINT matched = 0, count = 0;
|
||||
for (int slot = 0; slot < 24; ++slot) {
|
||||
auto &x = live[slot];
|
||||
if (!x.resource.p)
|
||||
continue;
|
||||
for (int part = 0; part < 3; ++part) {
|
||||
UINT64 offset = part == 0 ? 0
|
||||
: part == 1 ? x.bytes / 2 / 4 * 4
|
||||
: x.bytes - 64;
|
||||
auto p = reinterpret_cast<volatile uint32_t *>(
|
||||
static_cast<unsigned char *>(read.cpu) + slot * 192 + part * 64);
|
||||
for (int i = 0; i < 16; ++i) {
|
||||
++count;
|
||||
matched += p[i] == pattern(offset / 4 + i, x.seed);
|
||||
}
|
||||
}
|
||||
}
|
||||
std::printf("REFERENCE_VERIFY cycle=%d phase=%d matched=%u/%u\n", cycle,
|
||||
phase, matched, count);
|
||||
if (matched != count)
|
||||
throw std::runtime_error("allocator guard/interior mismatch");
|
||||
q->begin();
|
||||
q->close();
|
||||
};
|
||||
for (int cycle = -2; cycle < 10; ++cycle) {
|
||||
start = ticks();
|
||||
for (int i = 0; i < 24; ++i)
|
||||
allocate(i, cycle, 0);
|
||||
statistics(pool.p, cycle, "full");
|
||||
verify(cycle, 0);
|
||||
for (int i = 0; i < 24; i += 2)
|
||||
release(i, cycle);
|
||||
statistics(pool.p, cycle, "holes");
|
||||
for (int i = 0; i < 24; i += 2)
|
||||
allocate(i, cycle, 1);
|
||||
verify(cycle, 1);
|
||||
if (cycle == 0) {
|
||||
double pause = ticks();
|
||||
stage("live");
|
||||
start += ticks() - pause;
|
||||
}
|
||||
for (int i = 0; i < 24; ++i)
|
||||
release(i, cycle);
|
||||
statistics(pool.p, cycle, "empty");
|
||||
std::printf("REFERENCE_CYCLE cycle=%d ms=%.6f\n", cycle, ms(start));
|
||||
}
|
||||
stage("resources_released");
|
||||
q.reset();
|
||||
read.release();
|
||||
pool.clear();
|
||||
allocator.clear();
|
||||
stage("commands_retired");
|
||||
std::puts("END success");
|
||||
return 0;
|
||||
} catch (const std::exception &e) {
|
||||
std::printf("END failure reason=%s\n", e.what());
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Compile an external pinned allocator reference; run only within explicit pressure/headroom bounds."""
|
||||
import argparse
|
||||
import fcntl
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import plistlib
|
||||
import re
|
||||
import shutil
|
||||
import signal
|
||||
import subprocess
|
||||
import threading
|
||||
from datetime import datetime,timezone
|
||||
|
||||
|
||||
def main():
|
||||
ap=argparse.ArgumentParser(description=__doc__);ap.add_argument('--external',type=Path,required=True);ap.add_argument('--scratch',type=Path,required=True);ap.add_argument('--bottle',type=Path);ap.add_argument('--build-only',action='store_true');ap.add_argument('--allow-warning',action='store_true');ap.add_argument('--seeds',default='473,474,475');args=ap.parse_args()
|
||||
src=Path(__file__).resolve().parent;parent=src.parent;out=args.scratch.expanduser().resolve();up=args.external.expanduser().resolve()
|
||||
if out.exists():ap.error('append-only scratch must be new')
|
||||
if not args.build_only and args.bottle is None:ap.error('--bottle required for execution')
|
||||
seeds=[int(v) for v in args.seeds.split(',')]
|
||||
if not seeds or len(seeds)>3:ap.error('one to three bounded paired seeds')
|
||||
spec=importlib.util.spec_from_file_location('a_capture',parent/'run.py');helpers=importlib.util.module_from_spec(spec);spec.loader.exec_module(helpers)
|
||||
env={k:os.environ[k] for k in ['HOME','USER','LOGNAME','PATH','LANG','LC_ALL'] if k in os.environ};out.mkdir(parents=True,mode=0o700);env.update(TMPDIR=str(out)+'/',ROSETTA_ADVERTISE_AVX='1',CX_GRAPHICS_BACKEND='d3dmetal',WINEDEBUG='-all')
|
||||
r=dict(protocol='A-external-allocator-1',utc=datetime.now(timezone.utc).isoformat(),upstream_revision='600949266be004553f74c9ef809384380a9d44cf',upstream_modifications='none',runtime_executed=False,allow_warning=args.allow_warning,cases=[],tools={},sources={},external={})
|
||||
def save():(out/'receipt.json').write_text(json.dumps(r,indent=2)+'\n')
|
||||
def capture(cmd,timeout=20):return helpers.capture(cmd,env,out,timeout)
|
||||
expected={'LICENSE.txt':'3d5a69a6f5695507ecc9c412c783ca60572bf878','D3D12MemAlloc.h':'b685a5cd6188519606efaf039cd88c2faffa261a','D3D12MemAlloc.cpp':'b7ba60a3a4deb0ed466b235b7c5298f91ba5c976'}
|
||||
for name,blob in expected.items():
|
||||
p=up/name;data=p.read_bytes();actual=hashlib.sha1(b'blob '+str(len(data)).encode()+b'\0'+data).hexdigest()
|
||||
if actual!=blob:ap.error('external source bytes differ: '+name)
|
||||
r['external'][name]=dict(git_blob=actual,sha256=helpers.sha(p))
|
||||
snap=out/'source';(snap/'allocator-evaluation').mkdir(parents=True)
|
||||
for p,dst in [(src/'probe.cpp',snap/'allocator-evaluation/probe.cpp'),(src/'run.py',snap/'allocator-evaluation/run.py'),(parent/'support.h',snap/'support.h'),(parent/'observe.cpp',snap/'observe.cpp'),(parent/'run.py',snap/'capture-helper.py')]:shutil.copy2(p,dst);r['sources'][p.name if p!=parent/'run.py' else 'capture-helper.py']=helpers.sha(p)
|
||||
exe=out/'reference.exe';observer=out/'observe';cx=Path('/Applications/CrossOver.app/Contents/SharedSupport/CrossOver')
|
||||
cmds={'build_pe':['x86_64-w64-mingw32-g++','-std=c++20','-O2','-static','-static-libgcc','-static-libstdc++','-Wall','-Wextra','-Werror','-I',up,snap/'allocator-evaluation/probe.cpp',up/'D3D12MemAlloc.cpp','-o',exe,'-lkernel32','-lole32','-ldxguid'],
|
||||
'build_observer':['xcrun','clang++','-std=c++20','-O2','-arch','arm64','-Wall','-Wextra','-Werror',snap/'observe.cpp','-o',observer],
|
||||
'formats':['file',exe,observer],'observer_arch':['lipo','-archs',observer],'observer_links':['otool','-L',observer],
|
||||
'gcc':['x86_64-w64-mingw32-g++','--version'],'macos':['sw_vers'],'chip':['sysctl','-n','machdep.cpu.brand_string'],'ram':['sysctl','-n','hw.memsize'],
|
||||
'crossover':[cx/'bin/wine','--version'],'wine':[cx/'bin/wineloader','--version'],'rosetta':['pkgutil','--pkg-info','com.apple.pkg.RosettaUpdateAuto'],
|
||||
'imports':['x86_64-w64-mingw32-objdump','-p',exe]}
|
||||
for name,cmd in cmds.items():
|
||||
r['tools'][name]=capture(cmd,120 if name.startswith('build') else 20);save()
|
||||
if name.startswith('build') and r['tools'][name]['exit']:raise RuntimeError('build failed: '+name)
|
||||
r['binaries']={p.name:helpers.sha(p) for p in [exe,observer]};resources=cx/'lib64/apple_gptk/external/D3DMetal.framework/Versions/A/Resources';r['framework']={p.name:plistlib.loads(p.read_bytes()) for p in resources.glob('*.plist')};save()
|
||||
if args.build_only:print('external pinned allocator compiled; runtime NOT_RUN by --build-only');return 0
|
||||
def pressure():
|
||||
k=capture(['sysctl','-n','kern.memorystatus_vm_pressure_level']);vm=capture(['vm_stat']);ram=capture(['sysctl','-n','hw.memsize']);percent=capture(['memory_pressure','-Q']);swap=capture(['sysctl','vm.swapusage'])
|
||||
page=re.search(r'page size of (\d+) bytes',vm['stdout']);free=re.search(r'Pages free:\s+(\d+)',vm['stdout']);file=re.search(r'File-backed pages:\s+(\d+)',vm['stdout']);pct=re.search(r'free percentage: (\d+)%',percent['stdout'])
|
||||
if any(x['exit'] for x in [k,vm,ram,percent,swap]) or not all([page,free,file,pct]) or not k['stdout'].strip().isdigit():return dict(safe=False,reason='pressure measurement unavailable',kernel=k,vmstat=vm,percentage=percent)
|
||||
used=int(ram['stdout'])-(int(free[1])+int(file[1]))*int(page[1]);safe=int(k['stdout'])<=(1 if args.allow_warning else 0) and used+512*1024**2<23000000000 and int(pct[1])>=30
|
||||
return dict(safe=safe,kernel=k,vmstat=vm,percentage=percent,swap=swap,conservative_non_file_cache_occupied_bytes=used,ceiling_bytes=23000000000)
|
||||
pre=pressure();r['preflight']=pre;save()
|
||||
if not pre['safe']:print('runtime NOT_RUN: pressure/headroom guard');r['not_run']='pressure/headroom guard before guest or bottle copy';save();return 2
|
||||
lock=open('/tmp/betterxen-473-gpu.lock','a');fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
|
||||
bottle=args.bottle.expanduser().resolve();original=(bottle/'cxbottle.conf').read_bytes();temp=out/'bottle';shutil.copytree(bottle,temp,symlinks=True)
|
||||
conf=re.sub(r'(?m)^\[Bottle\]\s*$','[Bottle]\n"AllowUntrusted" = "1"',original.decode(),count=1);conf+='\n[EnvironmentVariables]\n"CX_GRAPHICS_BACKEND" = "d3dmetal"\n[CrossOver]\n"AntiVirusScan" = "untrusted"\n';(temp/'cxbottle.conf').write_text(conf)
|
||||
try:
|
||||
for i,seed in enumerate(seeds):
|
||||
for typ in (['wb','wc'] if i%2==0 else ['wc','wb']):
|
||||
pcheck=pressure()
|
||||
if not pcheck['safe']:r['stop_reason']=pcheck;save();raise RuntimeError('pressure guard before case')
|
||||
case=out/f'{typ}-seed-{seed}';case.mkdir();cmd=[str(cx/'bin/wine'),'--bottle',str(temp),'--no-update','--no-gui',str(exe),typ,str(seed)];c=dict(name=case.name,command=cmd,pressure_before=pcheck,snapshots=[]);r['cases'].append(c);save()
|
||||
with (case/'stdout.txt').open('wb') as stdout,(case/'stderr.txt').open('wb') as stderr:
|
||||
p=subprocess.Popen(cmd,env=env,cwd=case,stdout=subprocess.PIPE,stderr=stderr,stdin=subprocess.PIPE,start_new_session=True);r['runtime_executed']=True
|
||||
def kill():
|
||||
try:os.killpg(p.pid,signal.SIGKILL)
|
||||
except ProcessLookupError:pass
|
||||
expired=threading.Event()
|
||||
def expire():expired.set();kill()
|
||||
timer=threading.Timer(120,expire);timer.start();pid=None
|
||||
try:
|
||||
for line in p.stdout:
|
||||
stdout.write(line);stdout.flush()
|
||||
if not line.startswith(b'STAGE '):continue
|
||||
reading=pressure()
|
||||
if not reading['safe']:
|
||||
c['stop_pressure']=reading;save();raise RuntimeError('pressure guard at checkpoint')
|
||||
if pid is None:
|
||||
lookup=capture(['lsof','-t','-a','-c','reference.exe',exe]);pids=sorted({int(v) for v in lookup['stdout'].split() if v.isdigit()})
|
||||
if len(pids)!=1:raise RuntimeError('ambiguous guest PID')
|
||||
pid=pids[0];libs=capture(['lsof','-n','-p',str(pid)]);c['backend_paths_excerpt']=['/'+l.split('/',1)[1] for l in libs['stdout'].splitlines() if any(k in l for k in ['apple_gptk/wine/x86_64-windows/d3d12.dll','D3DMetal.framework/Versions/A/D3DMetal','/rosetta/runtime'])]
|
||||
phase=line.decode().split()[1];sample=capture([observer,str(pid)]);snap=dict(phase=phase,pressure=reading,observer=sample)
|
||||
for name,command in {'footprint':['footprint','-p',str(pid),'-f','bytes','--swapped'],'vmmap':['vmmap','-summary',str(pid)]}.items():
|
||||
value=capture(command);(case/f'{phase}-{name}.json').write_text(json.dumps(value,indent=2)+'\n');snap[name]=dict(exit=value['exit'],file=f'{phase}-{name}.json')
|
||||
c['snapshots'].append(snap);save();p.stdin.write(b'\n');p.stdin.flush()
|
||||
p.wait()
|
||||
except BaseException as e:c['harness_error']=repr(e);kill();p.wait();raise
|
||||
finally:timer.cancel();c['exit']=p.returncode;c['timed_out']=expired.is_set();save()
|
||||
if c['exit']:raise RuntimeError('allocator case failed')
|
||||
print(case.name,'exit',c['exit'],flush=True)
|
||||
finally:
|
||||
stop=dict(env,WINEPREFIX=str(temp));r['server_stop']=helpers.capture([cx/'bin/wineserver','-k'],stop,out);r['server_wait']=helpers.capture([cx/'bin/wineserver','-w'],stop,out);r['source_bottle_unchanged']=(bottle/'cxbottle.conf').read_bytes()==original;shutil.rmtree(temp);save()
|
||||
return 0
|
||||
|
||||
if __name__=='__main__':raise SystemExit(main())
|
||||
@@ -0,0 +1,90 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Recalculate descriptive A-local-2 statistics from raw receipts/logs, without editing them."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
from pathlib import Path
|
||||
import re
|
||||
import statistics
|
||||
|
||||
|
||||
def distribution(values):
|
||||
s=sorted(values)
|
||||
if not s: return None
|
||||
return dict(n=len(s),median=statistics.median(s),minimum=s[0],maximum=s[-1],
|
||||
p10=s[max(0,math.ceil(len(s)*.1)-1)],p90=s[max(0,math.ceil(len(s)*.9)-1)])
|
||||
|
||||
|
||||
def fields(line):
|
||||
return dict(re.findall(r'(\w+)=([^\s]+)',line))
|
||||
|
||||
|
||||
def analyze(base,allow_partial=False):
|
||||
receipt=json.loads((base/'receipt.json').read_text())
|
||||
result=dict(protocol=receipt['protocol'],suite=receipt['suite'],receipt_sha256=hashlib.sha256((base/'receipt.json').read_bytes()).hexdigest(),
|
||||
review='author-run; independent acceptance pending',not_run=receipt.get('not_run',[]),cases=[],tool_failures={k:v['exit'] for k,v in receipt['tools'].items() if v['exit']})
|
||||
for case in receipt['cases']:
|
||||
name=case['name'];root=base/name;raw=(root/'stdout.txt').read_bytes();out=raw.decode()
|
||||
if case['exit']!=case.get('expected_exit',0) or case['timed_out']:
|
||||
if not allow_partial: raise ValueError('unsatisfied case '+name)
|
||||
result['cases'].append(dict(name=name,exit=case['exit'],status='incomplete or failed; not counted as passed',harness_error=case.get('harness_error'),snapshots=len(case['snapshots']),outcomes=[l for l in out.splitlines() if l.startswith(('OUTCOME ','NEGATIVE','END '))]))
|
||||
continue
|
||||
for output,digest in case.get('outputs',{}).items():
|
||||
if hashlib.sha256((root/output).read_bytes()).hexdigest()!=digest:raise ValueError('changed output '+name+'/'+output)
|
||||
c=dict(name=name,exit=case['exit'],seconds=case['seconds'],backend=case.get('backend_paths_excerpt',[]))
|
||||
if receipt['suite']=='memory':
|
||||
stages={}
|
||||
for snap in case['snapshots']:
|
||||
values=[x['data'] for x in snap['samples'] if x.get('exit')==0 and x.get('data',{}).get('return')==0]
|
||||
if len(values)!=3:raise ValueError('missing native accounting samples')
|
||||
stage=dict(physical_footprint_bytes=statistics.median(x['phys_footprint'] for x in values),
|
||||
resident_bytes=statistics.median(x['resident_size'] for x in values))
|
||||
for tool in ['footprint','vmmap','pressure','swap']:
|
||||
stage[tool+'_exit']=snap[tool]['exit']
|
||||
ptr=int(snap['marker'].split('cpu_ptr=')[1],16)
|
||||
if ptr:stage.update(cpu_pointer_hex=hex(ptr),cpu_pointer_mod_64KiB=ptr%65536,cpu_pointer_mod_2MiB=ptr%2097152)
|
||||
stages[snap['phase']]=stage
|
||||
if len(stages)!=10:raise ValueError('incomplete memory checkpoints')
|
||||
baseline=stages['baseline']['physical_footprint_bytes']
|
||||
for v in stages.values():v['delta_baseline_bytes']=v['physical_footprint_bytes']-baseline
|
||||
c.update(args=case['args'],stages=stages)
|
||||
if case['args'][0] not in ['cpu','cpu-plain'] and 'checksum_matches=256/256' not in out:raise ValueError('missing full consumption checksum')
|
||||
elif receipt['suite']=='pool':
|
||||
alloc=[fields(l) for l in out.splitlines() if l.startswith('ALLOC ')]
|
||||
frees=[fields(l) for l in out.splitlines() if l.startswith('FREE ')]
|
||||
if case.get('expected_exit')==1:
|
||||
if 'END failure reason=trace guard/interior mismatch' not in out:raise ValueError('negative control reason')
|
||||
c['negative_control']='omitted copy detected'
|
||||
else:
|
||||
c['allocation_ms']={k:distribution([float(v[k]) for v in alloc if int(v['iteration'])>=0]) for k in ['heap_or_suballoc_ms','placement_ms','map_ms']}
|
||||
c['free_ms']={k:distribution([float(v[k]) for v in frees if int(v['iteration'])>=0]) for k in ['resource_ms','backing_or_freelist_ms']}
|
||||
c['cycle_ms']=distribution([float(fields(l)['ms']) for l in out.splitlines() if l.startswith('CYCLE ') and int(fields(l)['iteration'])>=0])
|
||||
c['fragmentation']=[fields(l) for l in out.splitlines() if l.startswith('FRAGMENT ')]
|
||||
checks=[fields(l) for l in out.splitlines() if l.startswith('READBACK ')]
|
||||
if len(checks)!=24:raise ValueError('missing trace readback checks')
|
||||
for x in checks:
|
||||
a,b=map(int,x['matches'].split('/'))
|
||||
if a!=b:raise ValueError('readback mismatch')
|
||||
if 'withheld=1' not in out or 'DELAYED_RETIRE' not in out:raise ValueError('missing delayed retirement')
|
||||
if c['cycle_ms']['n']!=10 or c['allocation_ms']['map_ms']['n']!=360:raise ValueError('wrong trace sample count')
|
||||
c['readback_checks']=len(checks)
|
||||
elif receipt['suite']=='alias':
|
||||
c['rounds']=[fields(l) for l in out.splitlines() if l.startswith('BUFFER_INHERIT ')]
|
||||
if len(c['rounds'])!=3:raise ValueError('missing inheritance rounds')
|
||||
for row in c['rounds']:
|
||||
for key in ['source_matches','inherited_matches','disjoint_guard_matches']:
|
||||
if row[key]!='16384/16384':raise ValueError('inheritance mismatch')
|
||||
c['addresses']=[fields(l) for l in out.splitlines() if l.startswith('ALIAS_RESOURCE ')]
|
||||
else:
|
||||
c['outcomes']=[l for l in out.splitlines() if l.startswith(('OUTCOME ','NEGATIVE ','FOOTPRINT '))]
|
||||
result['cases'].append(c)
|
||||
return result
|
||||
|
||||
|
||||
def main():
|
||||
p=argparse.ArgumentParser(description=__doc__);p.add_argument('scratch',type=Path);p.add_argument('--allow-partial',action='store_true');p.add_argument('--output',required=True,type=Path);args=p.parse_args()
|
||||
result=analyze(args.scratch,args.allow_partial);args.output.write_text(json.dumps(result,indent=2)+'\n');print(result['suite'],len(result['cases']),'cases; tool failures',result['tool_failures'])
|
||||
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,30 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Append a redacted diagnostic copy and hash manifest; original bytes stay untouched."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def main():
|
||||
ap=argparse.ArgumentParser(description=__doc__);ap.add_argument('scratch',type=Path);ap.add_argument('destination',type=Path);args=ap.parse_args()
|
||||
src=args.scratch.resolve();dst=args.destination.resolve()
|
||||
if dst.exists():ap.error('append-only destination must be new')
|
||||
dst.mkdir(parents=True)
|
||||
manifest=dict(originals_unchanged=True,redaction='JSON diagnostics replace local home-directory prefix with <HOME>; raw stdout/stderr unchanged',files=[])
|
||||
for p in sorted(src.rglob('*')):
|
||||
if not p.is_file() or p.is_symlink():continue
|
||||
rel=p.relative_to(src)
|
||||
if p.suffix in ['.exe','.pyc','.pyo'] or '__pycache__' in rel.parts or p.name=='observe' or any(v.startswith('.wine') or v=='bottle' for v in rel.parts):continue
|
||||
original=p.read_bytes()
|
||||
if original[:2]==b'MZ' or original[:4] in [b'\xcf\xfa\xed\xfe',b'\xfe\xed\xfa\xcf',b'\xca\xfe\xba\xbe',b'\xbe\xba\xfe\xca']:
|
||||
continue # Executables remain in ignored artifacts, not public research records.
|
||||
data=original
|
||||
if p.suffix=='.json':data=data.replace(str(Path.home()).encode(),b'<HOME>')
|
||||
target=dst/rel;target.parent.mkdir(parents=True,exist_ok=True);target.write_bytes(data)
|
||||
manifest['files'].append(dict(path=rel.as_posix(),bytes=len(data),original_sha256=hashlib.sha256(original).hexdigest(),archived_sha256=hashlib.sha256(data).hexdigest(),redacted=original!=data))
|
||||
(dst/'archive-manifest.json').write_text(json.dumps(manifest,indent=2)+'\n')
|
||||
print('Archived',len(manifest['files']),'files to',dst)
|
||||
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,23 @@
|
||||
# Independent expectations prepared for B review
|
||||
|
||||
Prepared after reading the B report but before access to its actual source/raw bundle. These are public-contract expectations and review questions, not completed independent implementation acceptance. B now operates as Asufte/@atesahmet0; CarReal is unavailable. The [A handoff](https://github.com/MacosPorters/betterxen/issues/473#issuecomment-7204146451) provides the published A pin. B's [small M5 report](https://github.com/MacosPorters/betterxen/issues/473#issuecomment-7204220454) is attributed evidence until its actual source/receipts are inspected.
|
||||
|
||||
[GetWriteWatch](https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-getwritewatch) applies to a VirtualAlloc region created with MEM_WRITE_WATCH. Check address-array capacity before calls, returned count/granularity, error handling and exact page sets. The API tracks writes, not a comparison of byte values; a real same-value store can dirty a page, while an ordinary read should not be counted as a write. Source must actually perform the store, rather than an optimizer deleting it. With reported 4096-byte granularity, offsets 12288 and 16383 address the same reported page, while 16384 addresses the next. Do not substitute the host's 16 KiB page size for the returned granularity.
|
||||
|
||||
[ResetWriteWatch](https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-resetwritewatch) and the reset flag on GetWriteWatch clear prior records. Check empty queries after reset, new stores rearming tracking and no writers between separate query/reset operations. Those single-thread cases do not establish a safe concurrent-reset fallback.
|
||||
|
||||
[VirtualAlloc](https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtualalloc) requires MEM_RESERVE with MEM_WRITE_WATCH. An arbitrary D3D12 Map pointer is not thereby an eligible allocation. Successful CPU tracking on a separate allocation cannot be transferred to the mapped heap without a valid documented allocation path.
|
||||
|
||||
[Architecture1](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ns-d3d12-d3d12_feature_data_architecture1) defines the guarantee provided by IsolatedMMU=TRUE; FALSE removes that guarantee, rather than measuring universal absence of GPU tracking. An E_NOTIMPL heap open on a write-watch allocation leaves GPU access/tracking through that route untested.
|
||||
|
||||
For creation/alignment review, inspect complete heap/resource descriptors, alignment-info queries, non-null output objects, legal offset-zero control, pointer-width formatting and cleanup. Invalid placements must never be mapped or submitted. Compare CPU pointer modulo separately from GPU virtual address/heap offset. Creation success does not satisfy caller preconditions. Confirm loaded DLL/framework receipts for each actual process, not a launcher setting or another Wine process. Exact B source/raw access and critical M4 reproduction remain pending.
|
||||
|
||||
## Larger B handoff: interpretation review only
|
||||
|
||||
B's [later handoff](https://github.com/MacosPorters/betterxen/issues/473#issuecomment-7204560629) reports seeded M5 copy sweeps, shader access, separately profiled GPU intervals, an alignment-only invalid placement check in a 128 KiB heap, same-source A texture/alias reproduction and representative footprint recalculation. These remain attributed reports pending actual source/raw publication; their locally retained status does not permit A to certify counts, rates, synchronization or joins. B explicitly has not reviewed the new A graphics supplement.
|
||||
|
||||
A's interpretation response distinguishes end-to-end copy completion from profiled GPU interval rates, payload bytes from total read/write traffic, uninstrumented from instrumented samples, and a bound on a timed window from a proof of no hidden copies. Review will check exact shader workloads, poisoned/omitted controls, timing boundaries, outlier retention, target-process/command-buffer/encoder joins and numerator definitions. Representative footprint recalculation must preserve device-release versus process-exit distinctions. The invalid-placement negative outcomes must remain failures of the original gate in same-source reproduction. No additional B sweep is commissioned while its existing source/raw handoff is pending.
|
||||
|
||||
## Source access and review update
|
||||
|
||||
B subsequently published a40228747470f0d184375e451b0173769c90aef5. Actual source and raw-data review is now recorded in [A's B review](review-b.md), including an isolated stopped-run output-hash discrepancy and the requested target-only trace inputs. Earlier paragraphs describe the prior pending-access state, not a continuing source-publication blocker. M4 hardware reproduction is still pending urgent-pressure recovery.
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
# Final research acceptance checklist
|
||||
|
||||
This checklist separates publication integrity, narrowly accepted findings, unresolved research and permission to act. It does not close #473 or accept an implementation. A consolidates the report; Asufte/@atesahmet0 is the independent reviewer. Arths17 authorized research-only integration into `research/d3dmetal-zero-copy`, not main/ABI/production changes or implementation issues.
|
||||
|
||||
## Publication and evidence integrity
|
||||
|
||||
- [x] Keep the six-check baseline probe and runner identical to `9ae6d1ee7092b6021aad075531f50ba60de4fd53`; probe SHA-256 remains `33e90bfee89e812f48990613cd74ced56473e5c3fc5d973f2ba1116090646a0c`.
|
||||
- [x] Preserve all historical raw results, including invalid-rejection failures, urgent stops, the initial graphics bug and the stopped-run hash discrepancy. New verification uses append-only A result bundles.
|
||||
- [x] Verify A archive manifests and retained source identities. Five declared references in already-published historical/setup runs have no matching retained source bytes; they remain unverified, rather than reconstructed or relabeled.
|
||||
- [x] Verify all 29 register entries, reviewer attribution, acceptance scope and pinned raw-evidence paths. Match B review/trace inputs to `4ba4926d2f491517c01b1e94fb8539184055dc22` and the inspected budget source to `c13f9c76650edded41774528b50f40798244a6f3`.
|
||||
- [x] Check documentation, Python sources, credential/personal-path scans and excluded executable/cache artifacts. Preserve byte-exact source snapshots; any retained whitespace warning is documented rather than silently reformatted.
|
||||
- [x] Preserve per-file allocator MIT provenance/notices and external-only vendor/runtime status; no proprietary runtime or executable payload is published.
|
||||
- [x] Confirm that the A-branch publication made no production, ABI, main or shared-branch source modification. That publication was confined to `research/473-workstream-a-memory`.
|
||||
- [x] Publish the DCO-signed research update at `d3ae607fb68865fb5cd449f11d43d36543d1432a`, verify the remote HEAD and post the [pinned issue handoff](https://github.com/MacosPorters/betterxen/issues/473#issuecomment-7205840779). The handoff records the latest verified publication SHA, including this checklist completion; it does not substitute for final independent review.
|
||||
- [x] Obtain Asufte's final review of the new consolidation: [signed off at `d3ae607`](https://github.com/MacosPorters/betterxen/issues/473#issuecomment-7206014568). The later `62c7702` commit changes two publication-checklist lines only and is submitted for acknowledgment with the integrated commit.
|
||||
|
||||
The first seven checks are mechanical/source checks, not self-certification of experimental results. Publication is recorded separately from independent review, and an unchecked item is not a passing result.
|
||||
|
||||
## Thirteen independently accepted scopes
|
||||
|
||||
| Register ID | Accepting reviewer | Accepted scope and boundary |
|
||||
| --- | --- | --- |
|
||||
| BASE-1 | B | Reported flags/heap tier on the tested versions; not physical topology. |
|
||||
| BASE-3 | B | Five L0 heaps, L1 rejection, initial mixed placement and CPU subresource round-trip. |
|
||||
| BASE-4 | B | Fence-separated persistent-map copy visibility, not concurrent atomic interoperability. |
|
||||
| BASE-5 | B | Negative methodological conclusion: baseline small-copy latency does not prove absence of copies. |
|
||||
| BASE-6 | B | Ordinary CPU VirtualAlloc MEM_WRITE_WATCH behavior, not tracking foreign Map/GPU memory. |
|
||||
| A-3 | B | Bounded CPU logical spans, not driver fragmentation. B reports its independent bitmap/rerun; those raw/checker artifacts are not included in the current B pin. |
|
||||
| A-4 | B | Single-block, single-queue CUSTOM WB/WC buffer compatibility/statistics. B reviews six M4 cases and reproduces the two-case M5 seed-473 subset with the corrected helper. |
|
||||
| A-6 | B | Placement alignment does not guarantee 64 KiB CPU Map alignment in the M4/M5 observations. |
|
||||
| A-8 | B | Advanced-model whole-buffer data inheritance and disjoint guards in tested states. |
|
||||
| A-9 | B | Three-format, three-mip transfer/guard positives; the full process still exits 1 at the invalid-rejection gate. |
|
||||
| A-10 | B | Post-activation RT/depth clear/readback, not raw texture pointers or texture data inheritance. |
|
||||
| A-13 | B | Single-threaded disposable research-helper behavior: real positive gated copy, direct failure-dispatch exit and empty unsignaled-fence timeout. Not actual failure injection of every queue API or arbitrary production teardown. |
|
||||
| B-7 | A | All seven exact CPU extractions from supplied sanitized XML; independent PID/ref/join/unit/distribution checks. Not independent GPU recapture or physical traffic measurement. |
|
||||
|
||||
These are the explicit [register](evidence-register.json) scopes, not thirteen universal component certifications. B's exact shared-runner functional baseline reproduction closes that earlier gap, while its lsof backend receipt remains a separate receipt-only PID.
|
||||
|
||||
## Unresolved, failed and unsupported outcomes
|
||||
|
||||
| State | Required treatment / next evidence |
|
||||
| --- | --- |
|
||||
| Urgent-pressure blocked | M4 B hardware reproduction; repeated A graphics datasets, omitted draw and actual packed-frame inspection; missing footprint repeats; local fault-case repetition. Do not launch under urgent pressure or exceed the 23 GB ceiling/reserve. |
|
||||
| Partial graphics evidence | B variant0 and omitted draw are reproduced; variant1 completes depth and stops at STAGE stencil. Hash expectations match, but B raw RGBA bytes are absent. Overall A-12 remains incomplete. |
|
||||
| Failed historical gates | A-7 invalid-rejection gate, B-6 timestamp-query/resolve path and B-8 historical sealed-output digest remain Failed. Do not rewrite those receipts to turn them into passes. |
|
||||
| Unsupported routes | Existing-memory opens and watch-allocation import return E_NOTIMPL in their stated configurations; GPU visibility/tracking through unsupported routes remains untested. |
|
||||
| Budget correctness defect | At c13f9c7, one-way visibility and non-atomic cross-DLL admission permit a source-derived combined-cap violation. Production execution/repair is not performed; existing owners must review a separately authorized design and regression plan. |
|
||||
| Cleanup-timeout handling gap | B-local-1.1 fixes the demonstrated late-write ordering, but normal wineserver wait errors are discarded. A's controlled CPU test exposes exit0/no-error despite a simulated wait124; failed drain cannot establish receipt finality. |
|
||||
| Provenance follow-ups | B bitmap/M5 logical rerun records, raw frames, raw stat/real-Wine forced-stop transcript and full fault-build/PE receipt remain requested. Their absence is recorded; reported reviewer decisions are attributed rather than invented as A executions. |
|
||||
| Unknown mechanisms / generality | Physical backing identity, universal no-copy behavior, GPU dirty tracking, unmeasured resource classes/generations, production performance and commercial game compatibility are unproven. |
|
||||
|
||||
Unknown mechanisms do not erase scoped functional results, and a scoped acceptance does not erase failed or blocked neighboring gates. The eight decision questions are answered in the [joint report](report.md); final scientific acceptance may include an explicit unknown answer rather than a fabricated mechanism conclusion.
|
||||
|
||||
## Integration and implementation permission gates
|
||||
|
||||
- [x] Obtain authorization and reviewer agreement for exact A/B inputs and destination `research/d3dmetal-zero-copy`: [B's confirmation](https://github.com/MacosPorters/betterxen/issues/473#issuecomment-7206014568) and Arths17's authorization. See the [integration record](../../integration.md).
|
||||
- [ ] Independent reviewer examines the exact integrated commit and its mechanical checks. This box cannot be ticked inside the commit under review; the decision is recorded in #473.
|
||||
- [ ] Obtain separate implementation/ABI authorization and affected-owner agreement before acting on production recommendations.
|
||||
- [ ] Obtain separate authorization before opening implementation issues or closing #473. This publication does neither.
|
||||
|
||||
Priority recommendations are R3 combined-admission correctness, R2 production lifetime/failure handling, R1 eligibility validation and R4 receipt finalization, followed by the evidence-dependent P2/P3/P4 work. The [roadmap](implementation-roadmap.md) specifies evidence, affected components, risks, dependencies, regressions and independent verification for every task. No production performance improvement is promised.
|
||||
+1631
File diff suppressed because it is too large.
Load diff
+58
@@ -0,0 +1,58 @@
|
||||
# Joint evidence register
|
||||
|
||||
A consolidates the register under its owned directory. The register incorporates B's explicit scoped decisions and A's CPU verification; B [signed off this content at d3ae607](https://github.com/MacosPorters/betterxen/issues/473#issuecomment-7206014568). Integration changed no finding record (see the [integration record](../../integration.md)). It combines pinned evidence without changing either workstream's raw results. No entry is independently accepted merely because agents agree. The [complete machine-readable register](evidence-register.json) contains every field for each finding, including hardware/runtime, exact source revision, raw links, review/reproduction attribution, limitations and architectural relevance.
|
||||
|
||||
The A pin is `8c9eceb05ab660504ee981c2f4fcaf1728a5dbff`; historical B benchmark source is `a40228747470f0d184375e451b0173769c90aef5` and B review/trace inputs are `4ba4926d2f491517c01b1e94fb8539184055dc22`; the six-check baseline is `9ae6d1ee7092b6021aad075531f50ba60de4fd53`. Exact executed snapshot hashes in receipts take precedence over a later helper revision. M4 has 24 GiB/macOS 27.0; M5 16 GiB/macOS 27.2.1; both use CrossOver 26.3.0.39832, Wine 11.0-8726-g2e2f5fca349 and D3DMetal 3.0, with the detailed differences recorded in JSON.
|
||||
|
||||
| ID | Research question | Owner | Evidence status | Acceptance |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| BASE-1 | What architecture/heap capabilities are reported? | A | Author-tested; Independently source-reviewed; Independently reproduced; Independently accepted | Independently accepted |
|
||||
| BASE-2 | Can existing CPU address/file-mapping allocations become D3D12 heaps? | A | Author-tested; Independently source-reviewed; Independently reproduced; Unsupported | Unsupported |
|
||||
| BASE-3 | Which CUSTOM combinations and initial mixed placement work? | A | Author-tested; Independently source-reviewed; Independently reproduced; Independently accepted | Independently accepted |
|
||||
| BASE-4 | Does fence-separated persistent-map copy visibility work? | A | Author-tested; Independently source-reviewed; Independently reproduced; Independently accepted | Independently accepted |
|
||||
| BASE-5 | Does original small-copy latency prove no shadow copy? | A | Author-tested; Independently source-reviewed; Independently reproduced; Independently accepted | Independently accepted |
|
||||
| BASE-6 | Does ordinary CPU MEM_WRITE_WATCH work? | A | Author-tested; Independently source-reviewed; Independently reproduced; Independently accepted | Independently accepted |
|
||||
| A-1 | What is process-accounted cost across 64/256/1024 MiB and complete retirement? | A | Author-tested; Independently source-reviewed; Blocked | Unknown |
|
||||
| A-2 | Does bounded pooling improve matched allocation/retirement cost? | A | Author-tested; Independently source-reviewed | Unknown |
|
||||
| A-3 | Can total free bytes hide fragmentation and pending-fence unavailability? | A | Author-tested; Independently source-reviewed; Independently reproduced; Independently accepted | Independently accepted |
|
||||
| A-4 | Does pinned AMD D3D12 Memory Allocator support bounded CUSTOM WB/WC buffers here? | A | Author-tested; Independently source-reviewed; Independently reproduced; Independently accepted | Independently accepted |
|
||||
| A-5 | Can inverted ownership satisfy every current xmem requirement? | A | Independently source-reviewed; Unknown; Failed | Unknown |
|
||||
| A-6 | Are mapped CPU pointers guaranteed 64 KiB aligned? | A | Author-tested; Independently source-reviewed; Independently reproduced; Independently accepted | Independently accepted |
|
||||
| A-7 | Does creation success reject invalid resource placement? | A | Author-tested; Independently source-reviewed; Independently reproduced; Failed | Failed |
|
||||
| A-8 | Do valid overlapping buffers inherit data with explicit ordering? | A | Author-tested; Independently source-reviewed; Independently reproduced; Independently accepted | Independently accepted |
|
||||
| A-9 | Do mixed opaque mip textures and disjoint guards transfer correctly? | A | Author-tested; Independently source-reviewed; Independently reproduced; Independently accepted | Independently accepted |
|
||||
| A-10 | Are render/depth aliases correct after activation and reinitialization? | A | Author-tested; Independently source-reviewed; Independently reproduced; Independently accepted | Independently accepted |
|
||||
| A-11 | Do UNKNOWN and legal ROW_MAJOR controls have the same scope? | A | Author-tested; Independently source-reviewed | Unknown |
|
||||
| A-12 | Do sampled rendering, raster depth and stencil work in the new fixture? | A | Author-tested; Independently source-reviewed; Independently reproduced; Blocked | Unknown |
|
||||
| A-13 | Is fence failure safe without proven completion? | A | Independently source-reviewed; Independently reproduced; Independently accepted | Independently accepted |
|
||||
| B-1 | What hidden-copy costs can matched small/full copy windows bound? | B | Author-tested; Independently source-reviewed; Blocked | Unknown |
|
||||
| B-2 | What bandwidth does the workload actually measure? | B | Author-tested; Independently source-reviewed; Blocked | Unknown |
|
||||
| B-3 | Does direct SRV/UAV access preserve fence-separated visibility? | B | Author-tested; Independently source-reviewed; Blocked | Unknown |
|
||||
| B-4 | Are 4 KiB subpages, reset/rearm, reads and same-value CPU stores tracked? | B | Author-tested; Independently source-reviewed; Blocked | Unknown |
|
||||
| B-5 | Can the watch allocation be GPU-written through import? | B | Author-tested; Independently source-reviewed; Unsupported; Unknown | Unsupported |
|
||||
| B-6 | Are D3D12 timestamp resolves reliable for these measurements? | B | Author-tested; Independently source-reviewed; Failed | Failed |
|
||||
| B-7 | Do target-only Metal intervals support independently extracted GPU rates? | B | Author-tested; Independently source-reviewed; Independently reproduced; Independently accepted | Independently accepted |
|
||||
| B-8 | Why does a stopped trace stderr not match its receipt hash? | B | Failed; Independently source-reviewed; Unknown | Failed |
|
||||
| X-1 | Has physical zero-copy/page identity been established? | A+B | Unknown; Independently source-reviewed | Unknown |
|
||||
| X-2 | Is generation/normal-pressure/general resource coverage sufficient? | A+B | Blocked; Unknown; Independently source-reviewed | Unknown |
|
||||
|
||||
## Coverage of the revised plan
|
||||
|
||||
| Original objective | Register coverage |
|
||||
| --- | --- |
|
||||
| Six frozen checks | BASE-1 through BASE-6 |
|
||||
| A footprint and complete retirement | A-1 |
|
||||
| A pooling, fragmentation and reuse | A-2 through A-4, A-13 |
|
||||
| A allocator reuse/provenance | A-4 and pinned allocator assessment |
|
||||
| A ownership/budget/placement | A-5 through A-8, A-13 |
|
||||
| A texture/layout/storage correctness | A-9 through A-12, X-2 |
|
||||
| B matched copy detection and bandwidth | B-1, B-2, B-7 |
|
||||
| B shader visibility and synchronization | B-3, A-13, pinned contract notes |
|
||||
| B CPU/GPU write tracking | B-4, B-5 |
|
||||
| Reciprocal review, failures and measurement validity | B-6 through B-8, X-1, X-2 |
|
||||
|
||||
## Reading acceptance correctly
|
||||
|
||||
Unknown acceptance means the overall proposition has not received explicit independent acceptance; it does not erase recorded successful subcases. Failed describes the named rejection/timestamp/finalization gate, not a fabricated failure of valid GPU data. Unsupported is version/configuration scoped. Blocked identifies work that could not safely run or lacks review input. Same-source reproduction and independently authored probes remain distinct. Thirteen findings now have scoped independent acceptance: twelve credited to B's explicit decisions and B-7 accepted by A for CPU extraction of supplied XML. Their acceptance scopes in JSON are mandatory; none establishes physical zero-copy, general production performance or complete compatibility. A-12 remains incomplete, and A-5 records a source-proven combined-budget defect. Dedicated A-branch publication is authorized; no integration or production acceptance is implied.
|
||||
|
||||
See [verification details](../final-verification/findings.md) for seven exact XML replays, process-finalization controls, peer-artifact limits and the budget counterexamples. B review/input pin is `4ba4926d2f491517c01b1e94fb8539184055dc22`; original executed-source pins above remain historical.
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
# Evidence-supported implementation roadmap — proposal
|
||||
|
||||
This is a proposed sequence for review, not authorization to modify production, ABI contracts, existing issue ownership or milestones. No implementation issues are created. A prepared it and B [signed off the d3ae607 revision](https://github.com/MacosPorters/betterxen/issues/473#issuecomment-7206014568). Research branch integration is authorized; main and production changes are not. The [register](evidence-register.json) supplies exact pins/raw evidence for the IDs below; the [report](report.md) supplies the eight decision-gate answers.
|
||||
|
||||
“Ready for implementation” below means a bounded correctness/diagnostic task can be specified from available contracts without assuming physical zero-copy or a performance gain. It still requires separate maintainer authorization, coordination with the affected owner and independent verification. Items requiring unresolved compatibility/performance evidence stay in the research-dependent group. Nothing here requires #464 to wait for a universal mechanism proof.
|
||||
|
||||
## Ready to scope after separate authorization
|
||||
|
||||
Priority update: R3 combined-admission correctness is now highest priority alongside R2 lifetime correctness, ahead of allocator/performance selection. This is a technical finding for existing owners, not an unauthorized PR blocker, new issue or implementation change.
|
||||
|
||||
### R1 — Extend owned placement and allocation-eligibility regression coverage
|
||||
|
||||
- **Technical justification/evidence:** A-5–A-8 show that successful creation is not sufficient validation and CPU pointer alignment differs from placement alignment. #486 reviewed head c13f9c7 (vmem unchanged from c44ae4e) already contains backing-heap checks and ordinary-request forwarding; reuse/review those checks rather than create a parallel provider.
|
||||
- **Expected benefit:** Reject ineligible provider requests before unsafe use and preserve unrelated D3D12 behavior. No throughput gain is promised.
|
||||
- **Dependencies:** #464 implementation owner's agreement; current head/source review; public allocation-info contracts. Any new cross-DLL contract requires separate ABI authorization.
|
||||
- **Affected components:** Existing provider's private validation/metadata, resource-class eligibility and its synthetic conformance tests; no assumed ABI change.
|
||||
- **Compatibility risks:** A global 64 KiB rule can incorrectly reject small aligned textures; forcing replacement of existing/fixed CPU pointers can violate caller contracts; overriding forwarded ordinary calls can change host behavior.
|
||||
- **Acceptance criteria:** Check the actual required CPU alignment and returned pointer; verify a valid queried resource alignment, overflow-safe span and required properties at the owned boundary. Keep pre-device/existing-content/requested-address/section cases explicitly eligible or rejected/fallback. Unsupported combinations report a reason.
|
||||
- **Regression tests:** Offset 0; misalignment isolated from bounds with a larger heap; end-of-heap/size overflow; offsets near UINT64_MAX; buffer and available small-texture alignment; invalid allocation-info results; source pointer lifetime and existing contents; ordinary forwarded requests matching the host. Never submit caller-invalid objects to the GPU.
|
||||
- **Independent verification:** Reviewer derives expectations from Microsoft contracts and inspects actual provider source; execute original synthetic tests on stated backend/runtime, with failed/skipped configurations distinct. Direct #473 host probes do not certify the shim path.
|
||||
|
||||
### R2 — Specify and test ownership, retirement and failure supervision
|
||||
|
||||
- **Technical justification/evidence:** A-2/A-8 and B-3 depend on successful final-use fences. B independently found A's historical post-submit exception hazard; B independently source-reviews and runtime-checks A-13 within the bounded disposable-guest scope; production API-failure/device-loss and multithreaded teardown remain unqualified.
|
||||
- **Expected benefit:** Prevent reuse/free while GPU ownership is pending, and make incomplete work a visible failure. No recovery or device-loss support is presumed.
|
||||
- **Dependencies:** Reuse the completed narrow peer review/fault verification; separately qualify production failure supervision; owner-approved queue/lifetime design; explicit final-use dependencies for each queue.
|
||||
- **Affected components:** Provider resource/heap owners, mapped-pointer metadata, command/descriptor retention and process supervision; existing conformance harnesses.
|
||||
- **Compatibility risks:** DLL detach can deadlock in ExitProcess; killing a launcher group may not prove its Wine guest has ended; command objects can retain resources; a signal from the CPU is not GPU completion.
|
||||
- **Acceptance criteria:** Completed final-use values on every participating queue before recycle/destruction. Failed signal, event, timeout, device removal or incomplete completion never allows reuse. The parent bounds termination, confirms owned private guest/server completion and records failure without claiming a successful GPU result.
|
||||
- **Regression tests:** Real bounded delayed work with guards; free while pending withheld; safe reuse after completion; event wake with incomplete fence; signal/event/wait failures; device-removed sentinel; multi-queue producer/consumer retirement; parent timeout and private-process cleanup. CPU fault-policy tests remain distinct from actual GPU synchronization tests.
|
||||
- **Independent verification:** Reviewer re-derives queue ordering and object lifetime from public contracts; independently runs critical positive and failure cases with external process-state evidence. Do not count a mocked completion as GPU verification.
|
||||
|
||||
### R3 — Correct combined budget admission and expose distinct accounting layers
|
||||
|
||||
- **Technical justification/evidence:** A-1/A-4/A-5 separate payload, reservation and retained host charge; A-6 and B's version-scoped results require actual capabilities/addresses. At c13f9c7, A and B independently identify one-way private-heap visibility. A's source-derived private6/CPU3 example exceeds cap8; a stale-snapshot interleaving also exceeds the cap. Reuse current counters, but correct combined admission rather than claiming the sum is enforced.
|
||||
- **Expected benefit:** Enforce the combined title cap in either allocation order and under concurrent admission, while explaining distinct logical/backing/retained measures. No physical release or performance gain is presumed.
|
||||
- **Dependencies:** Existing budget owner's agreement and lock/transaction review across CPU and graphics records. If current internal interfaces cannot maintain coherent accounting, design/approve the required contract separately before implementation.
|
||||
- **Affected components:** Existing private allocation/budget metadata and diagnostics; runtime capability/version/backend receipts. Host tooling remains native ARM64.
|
||||
- **Compatibility risks:** Double charging a slice plus slab, missing pending or migration backing, racing independent budget snapshots, overflowing totals, or relying on a driver estimate as a title cap.
|
||||
- **Acceptance criteria:** One coherent reserve/commit/release authority with atomic admission against all counted owners, plus separate reserved/pending/migration measures. Graphics-first and xmem-first sequences must obey the same cap; a statistics snapshot followed by a separate private charge is insufficient. Update/rollback failures coherently; old plus new migration backing remains charged through retirement. Diagnostics separately label footprint/RSS/compression/swap and unknown driver domains; no fixed-generation hardware assumptions.
|
||||
- **Regression tests:** Both allocation orders, the 6+3/cap8 counterexample and concurrent stale-snapshot schedule (scaled bounded fixtures, not actual GiB allocations); heap/virtual/physical admission; allocate/free/retire; rollback on host failure; repeated config; slab/slice nonduplication; fragmented logical free space; pending and migration peaks; concurrent request budget bounds; overflow and underflow; runtime capability changes. Driver retention is logged, not asserted to vanish.
|
||||
- **Independent verification:** Reviewer checks every allocation path and concurrency boundary, recalculates ledger transitions, and compares actual host observations without claiming page identity. A full unified budget is not accepted from one counter test.
|
||||
|
||||
### R4 — Seal reproducible research receipts after owned-process finalization
|
||||
|
||||
- **Technical justification/evidence:** B-8 identifies one stale stopped-run stderr hash. B's timestamp table and A's exact CPU process-race reproduction support sealing before the final child write. B-local-1.1 corrects the tested ordering; A additionally demonstrates that normal wineserver wait failure is ignored and cannot certify finality.
|
||||
- **Expected benefit:** Make future successful and failed run receipts auditable without silent post-seal output changes.
|
||||
- **Dependencies:** Preserve B's forensic reconciliation and A's controlled process check; obtain the minimal original stat/forced-stop transcripts for provenance; one agreed harness owner per patch. Preserve existing receipt/output and append a reconciliation record.
|
||||
- **Affected components:** Research launch, stream closure, private Wine supervision, output manifest and archival code; coordinate B-owned changes with B.
|
||||
- **Compatibility risks:** A wrapper's exit may not imply guest exit; arbitrary global Wine termination could affect other work; timeouts or missing process evidence can leave finality unknown.
|
||||
- **Acceptance criteria:** Identify only owned processes, bound their termination/drain, close owned streams and seal a final manifest afterward. Propagate nonzero/timeout cleanup results into a failed or unknown finalization; do not discard the normal wineserver wait result or treat an error-path drain failure as finalized. Original bytes/receipts are never rewritten to make hashes agree.
|
||||
- **Regression tests:** Normal completion, paused-backend stop, late stderr/stdout, timeout/interruption, surviving child, private server stop failure and archive redaction. A final digest covers archived bytes and identifies deliberate metadata redaction.
|
||||
- **Independent verification:** Other workstream replays a bounded synthetic late-output case and independently hashes final outputs after process completion; no claims about completed historical benchmarks without matching evidence.
|
||||
|
||||
## Requires further evidence before production selection
|
||||
|
||||
### P1 — Close reciprocal review and the remaining safe verification cases
|
||||
|
||||
- **Technical justification/evidence:** A-1/A-12/A-13, B-1/B-3/B-7/B-8 and X-2 retain explicit missing gates.
|
||||
- **Expected benefit:** Establish reproducible functional/synchronization evidence and provenance for the recommendations, not optimistic agreement.
|
||||
- **Dependencies:** Kernel pressure recovery and size-dependent reserve below 23 GB; the now-supplied B target-only XML/schema/reference inputs (CPU verification completed); acknowledgment of review ownership. Urgent pressure remains a blocker and is never bypassed.
|
||||
- **Affected components:** Research-only sources, append-only results, the register and independent review notes.
|
||||
- **Compatibility risks:** Treating a reduced profile as full, combining correlated stage samples as sessions, mixing old/current helpers, losing trace outliers or changing a negative gate.
|
||||
- **Acceptance criteria:** Finish changing-dataset graphics repetition and omitted-draw control; independently check packed frames; safe failed-fence behavior; only missing footprint repeats when eligible; critical same-source B small/representative compute/copy reproduction on M4. Seven exact trace extractions with independent PID/ID/unit/denominator/exclusion checks are completed; do not repeat unless source/inputs change. B's disposable-helper runtime scope is accepted, but production fault recovery remains separate.
|
||||
- **Regression tests:** Existing exact controls, including failed texture rejection outcomes, retained stop/timeout receipts and unmatched source declarations. No unnecessary complete B sweep is commissioned.
|
||||
- **Independent verification:** A/B exchange pinned actual sources, primary derivations, raw results and discrepancies. Reviewer records an explicit decision per criterion; no item becomes accepted from source publication or agent consensus.
|
||||
|
||||
### P2 — Qualify a bounded AMD allocator-backed buffer provider candidate
|
||||
|
||||
- **Technical justification/evidence:** A-4 demonstrates limited CUSTOM WB/WC pool compatibility; A-2/A-3 establish why setup/slack/fragmentation/retirement matter. Reuse is preferable to promoting the experimental allocator.
|
||||
- **Expected benefit:** Established allocation/statistics machinery and potentially lower allocation-call overhead; application benefit remains to be measured.
|
||||
- **Dependencies:** P1 critical reviews; per-file license/provenance registry preserved; existing provider owner and separately authorized integration; actual workload eligibility and stable-pointer policy.
|
||||
- **Affected components:** Future private graphics-buffer pool provider and its tests; no default universal xmem replacement or implicit ABI changes.
|
||||
- **Compatibility risks:** Fixed mapped pointers prohibit arbitrary defragmentation, bounded pools reject fragmented/oversized requests, retained blocks can consume headroom, and library object ownership does not provide queue retirement.
|
||||
- **Acceptance criteria:** Explicit feature whitelist (initially only qualified buffer/property combinations), bounded reservations, correct statistics/rollback, safe fences and lifecycle. Compare cold setup, allocation/placement/Map, retirement, payload/slack and full-workload cost against the existing implementation. No application speedup claim without production measurements.
|
||||
- **Regression tests:** Existing six seeded traces plus capacity/fragmentation, varied lifetimes, alignment, failed requests, pool release/retention and actual GPU guards. Multi-thread/queue, texture and device-loss features require their own added qualification before enabling.
|
||||
- **Independent verification:** Reviewer evaluates exact upstream files/notices and wrapper source, re-derives span/statistic expectations and reproduces critical runs; performance assessment uses matched workload distributions and permitted host conditions.
|
||||
|
||||
### P3 — Select buffer and texture storage by matched workload evidence
|
||||
|
||||
- **Technical justification/evidence:** A-9–A-12/B-3/B-7 show functional paths but unmatched transfer work and single captures prevent a general heap ranking.
|
||||
- **Expected benefit:** Workload-specific storage choices where measured costs justify them; no assumed Metal mode or bandwidth gain.
|
||||
- **Dependencies:** P1 trace-input validation and normal-pressure sensitivity; agreed timing boundaries and equal useful work. Existing correct explicit transfer path remains available.
|
||||
- **Affected components:** Future resource-class eligibility/policy and original benchmarks; retain B's ownership of bandwidth/compute methods.
|
||||
- **Compatibility risks:** Comparing direct output with DEFAULT readback as identical GPU work, cache effects, deferred copies outside windows, and overgeneralizing point sampling or clears.
|
||||
- **Acceptance criteria:** Separately compare CPU work, encoding, submission/fence and device intervals. Match resource descriptions/data/concurrency and account explicitly for necessary transfers/barriers. Retain per-iteration distributions/outliers and unknown mechanisms.
|
||||
- **Regression tests:** CPU-visible buffers, staged DEFAULT buffers, tested opaque textures, correct RT/depth/stencil paths and required negative controls. Extend MSAA/BC/planar/arrays/3D only when an actual current-phase need is demonstrated.
|
||||
- **Independent verification:** Other workstream re-derives payloads, checks raw trace selection and reproduces representative configurations; a version-specific policy never becomes a universal chip guarantee.
|
||||
|
||||
### P4 — Evaluate CPU write-watch as an optional selective-copy optimization
|
||||
|
||||
- **Technical justification/evidence:** BASE-6/B-4 establish ordinary CPU tracking; B-5 leaves foreign Map/GPU tracking unresolved.
|
||||
- **Expected benefit:** Potentially reduce explicit CPU-to-GPU copied ranges for a demonstrated CPU-owned workload. Copy cost and tracker overhead must both be measured.
|
||||
- **Dependencies:** A valid watch-enabled reservation, known writer ownership, synchronization/retry design and baseline full-copy fallback. No GPU-write-watch assumption.
|
||||
- **Affected components:** Future explicit CPU transfer planner and bounded tests; existing caller pointer ownership stays unchanged.
|
||||
- **Compatibility risks:** Query/reset/copy races, missing rearmed writes, same-value writes, address-array limits, unsupported allocation kinds and incorrectly converting host page size into returned tracking granularity.
|
||||
- **Acceptance criteria:** No lost dirty coverage under the supported writer protocol; all relevant bytes copied/validated; errors or uncertain ownership choose explicit conservative handling. Report tracker/write/copy overhead separately.
|
||||
- **Regression tests:** Subpages, boundaries, reset/rearm/read/same-value cases; writer quiescence, writes around reset/copy, failed or partial transfer, retry and allocation teardown. No unsupported concurrent protocol is accepted on a single-thread test.
|
||||
- **Independent verification:** Reviewer derives dirty sets and race timelines from public API contracts, independently compares final bytes and measures the complete supported workload. GPU-written memory tracking stays Unknown unless separately demonstrated.
|
||||
|
||||
## Deferred conclusions
|
||||
|
||||
Physical backing-page identity, a universal absence of hidden copies, commercial game/FPS gains, broad console ABI semantics and general M1–M5 compatibility are not implementation acceptance criteria satisfied by this research. Stronger claims need discriminating authorized evidence. This roadmap neither creates distant-phase trackers nor expands native-only work; it supplies bounded proposals for existing hybrid ownership after separate authorization.
|
||||
|
||||
## Current closure boundary
|
||||
|
||||
BASE-1/3/4/5/6 and A-3/4/6/8/9/10/13 have B's explicit narrow acceptance; B-7 supplied-input extraction is accepted by A. A-12 remains incomplete despite M5 positive/omitted-control evidence, and B-1–B-4 still lack M4 hardware reproduction. The historical B-8 receipt stays Failed, its mechanism is independently supported, and unsuccessful cleanup handling remains open. Raw-frame/checker/stat transcript requests are provenance follow-ups rather than GPU blockers. No source-level combined-budget fix has been implemented or authorized.
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
# Integration plan for the two research branches
|
||||
|
||||
**Historical plan, since accepted.** B [confirmed it](https://github.com/MacosPorters/betterxen/issues/473#issuecomment-7206014568) and Arths17 authorized research-only integration. The text below is kept as proposed; the [integration record](../../integration.md) states the actual inputs, including A `62c7702` rather than the `d3ae607` revision B signed off, and where review stands.
|
||||
|
||||
## Inputs and ownership
|
||||
|
||||
| Input | Exact identity / rule |
|
||||
| --- | --- |
|
||||
| Shared destination before integration | `research/d3dmetal-zero-copy` at `8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8` |
|
||||
| A | Exact verified remote SHA in this publication's #473 handoff; branch `research/473-workstream-a-memory`. Do not use an unverified moving tip. |
|
||||
| B | Reviewed `4ba4926d2f491517c01b1e94fb8539184055dc22` on `research/473-workstream-b` |
|
||||
| Common research ancestor | `8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8` |
|
||||
| Original six-check baseline | `9ae6d1ee7092b6021aad075531f50ba60de4fd53`; preserve original source and parameters |
|
||||
| Proposed integrator | A, only after maintainer authorization and confirmation through #473 |
|
||||
| Proposed independent integration reviewer | Asufte/Workstream B, subject to acknowledgment; prior reviews remain attributed to their actual pins |
|
||||
|
||||
A read-only changed-path comparison between the published A parent plus this candidate and B found no overlapping changed paths. This is a scope observation, not proof that Git can merge cleanly or that the combined documentation/code is semantically consistent. The report and register stay under A's owned directory so existing shared root findings are not edited simultaneously.
|
||||
|
||||
## Sequence to authorize later
|
||||
|
||||
1. Agree exact A/B input SHAs, expected old destination SHA and integrator/reviewer in #473. Request authorization explicitly for integration and any destination push; current publication authority does not suffice.
|
||||
2. Fetch and verify all three refs again. If any changes, preserve the observed identity and review the delta before proceeding; no force push, rebase or history overwrite.
|
||||
3. Use an isolated research integration worktree based on the approved shared revision. Preserve the two research histories using ordinary DCO-signed integration commits. Do not merge current main or production changes into the research result as an incidental update.
|
||||
4. Preserve append-only raw directories, exact executed snapshots, all failures and original receipts. Keep B's sanitized XML and its provenance with the corresponding extract outputs. Do not replace older experiment sources with the latest helper or reconcile a stale hash by editing historical data.
|
||||
5. Let one agreed author handle shared index/findings/changelog references; the other independently reviews that patch. Link the final consolidated report/register/roadmap/checklist without claiming all work accepted or manufacturing unavailable evidence.
|
||||
6. Audit the integrated tree: protected production/ABI trees against the old shared research base, baseline source/runner identity, manifests/source hashes, private-path/credential/binary scans, Git source refs, documentation and relevant CPU processing/layout checks. Keep urgent-pressure GPU work blocked. Read-only path nonoverlap does not substitute for this step.
|
||||
7. Obtain the independent reviewer's explicit findings on the actual integrated SHA. Record scoped acceptance, historical failures, unresolved cleanup/budget/provenance findings and pressure-blocked studies separately. Follow up on new differences rather than treating a merge as certification.
|
||||
8. Only with the separately granted destination-push authorization, publish a normal non-force update to the shared research branch after checking its expected old SHA. Verify the remote result and post the actual integrated SHA plus reviewer status on #473.
|
||||
|
||||
## Invariants and stop conditions
|
||||
|
||||
Production, frozen ABI and the original baseline must remain unchanged relative to the approved shared research base; current main has its own later history and is not an integration target. A and B branches must not be overwritten. Any source/provenance conflict, changed destination, unexpected protected-file diff, failed mechanical check or missing independent review pauses integration for review; it does not justify discarding evidence or weakening gates.
|
||||
|
||||
Research findings are preserved even when they preclude an optimistic conclusion. The source-confirmed combined-budget defect is not fixed by merging research branches; the cleanup-timeout handling gap is not fixed by publishing an explanation. Physical zero-copy and production performance remain unproven. Hardware studies remain blocked under urgent pressure. No implementation issue is created, no contributor is reassigned and #473 is not closed by this plan.
|
||||
|
||||
## Prioritized production recommendations after separate authorization
|
||||
|
||||
| Priority | Existing roadmap item | Why now / independent acceptance required |
|
||||
| --- | --- | --- |
|
||||
| P0 | R3 — combined admission correctness | A/B source review and A's bounded arithmetic demonstrate one-way visibility and stale snapshots. Existing budget/provider owners need one atomic authority or equivalent design, both allocation orders, concurrency, rollback and overflow regressions. ABI work requires its own approval. |
|
||||
| P0 | R2 — lifetime and production failure handling | Research-helper scope is accepted; production multi-queue, actual API failures, device loss and DLL/process recovery are not. Verify final-use ownership and failed-completion supervision independently. |
|
||||
| P1 | R1 — eligibility and placement validation | Reuse existing #464/#486 checks; validate actual CPU alignment, adapter allocation alignment, bounds and pointer/content contracts. Preserve ordinary forwarding and explicit fallbacks. |
|
||||
| P1 | R4 — receipt sealing / cleanup failure propagation | The specific race is reproduced and corrected; failed drain status must prevent a false finalized-success claim. Coordinate the B-owned harness patch rather than duplicate it. |
|
||||
| P2 | P2 — bounded allocator provider qualification | Pinned allocator compatibility/statistics is accepted only for the tested buffer scope. Require correct budget/lifetime integration and matched end-to-end production measurement before selection or benefit claims. |
|
||||
| P3 | P3/P4 — storage selection and CPU write-watch optimization | Require workload need, matched timing/transfer scope and race-safe eligible CPU ownership. Unknown GPU tracking or physical mechanisms cannot be silently assumed. |
|
||||
|
||||
These recommendations describe technically justified work, not implementation authorization, new blocking dependencies for #464 or guaranteed improvements. The detailed [roadmap](implementation-roadmap.md) contains acceptance criteria and independent regression requirements; the [research acceptance checklist](acceptance-checklist.md) controls evidence status rather than counting commits or closed issues.
|
||||
@@ -0,0 +1,158 @@
|
||||
# Joint memory architecture research report
|
||||
|
||||
BetterXen #473, 2026-11-26. Author: Workstream A under Arths17. Independent reviewer: Workstream B under Asufte/@atesahmet0, who reviewed the prior draft at 4ba4926 and [signed off the updated consolidation at d3ae607](https://github.com/MacosPorters/betterxen/issues/473#issuecomment-7206014568) within its narrowed scopes. This integrated copy changes only status, authorization and navigation text relative to that revision; see the [integration record](../../integration.md), whose own review is recorded in #473. Sign-off does not mean the whole research is accepted. The [evidence register](evidence-register.md) and [complete records](evidence-register.json) identify each source, platform, raw receipt, review, reproduction, limitation and acceptance state.
|
||||
|
||||
## 1. Executive summary
|
||||
|
||||
The tested CrossOver/D3DMetal configuration supports useful application-visible mapped-buffer access with fence-separated CPU/GPU visibility, legal buffer aliases and several texture transfer/clear cases. It does not provide the tested existing-memory import routes. Actual CPU pointers are not consistently 64 KiB aligned. Existing CPU allocation identity, requested virtual addresses, section/scatter semantics and opaque texture layouts therefore require separate treatment.
|
||||
|
||||
Bounded pooling and the pinned AMD allocator reduce or avoid certain allocation-call costs in synthetic traces, but have not demonstrated production memory savings or end-to-end application performance improvement. Process-ledger retention, logical free spans and physical residency are different measurements. Physical backing identity and a universal absence of internal copies remain unknown.
|
||||
|
||||
B has independently reviewed/reproduced selected earlier A cases on M5. A has reviewed B's published source/raw data and recalculated its distributions, but critical M4 hardware reproduction remains blocked, while all seven extractions from supplied sanitized XML now reproduce exactly under independent A checks. The newer A graphics supplement has one passing smoke, an earlier author bug and a pressure-stopped repeat. B independently accepts the fence-error correction for narrowly tested single-threaded disposable research guests; that is not production failure-recovery qualification. These limitations constrain the recommendations below.
|
||||
|
||||
## 2. Original objectives and eight decision gates
|
||||
|
||||
The six-check baseline at `9ae6d1ee7092b6021aad075531f50ba60de4fd53` remains frozen, including timeout, order, allocations, values, five warmups and 40 timed submissions. A's published continuation is `8c9eceb05ab660504ee981c2f4fcaf1728a5dbff`; B benchmark evidence is `a40228747470f0d184375e451b0173769c90aef5`; its new peer review, corrected harness and sanitized inputs are `4ba4926d2f491517c01b1e94fb8539184055dc22`. Executed source snapshots, rather than later helper revisions, govern historical results.
|
||||
|
||||
| Revised-plan decision gate | Evidence-supported answer | Remaining gate |
|
||||
| --- | --- | --- |
|
||||
| 1. Physically shared buffer configurations? | Application-visible persistent mapping and alias inheritance work in scoped cases (BASE-4, A-8, B-3). | Physical backing-page identity remains Unknown; do not rename functional sharing as physical proof. |
|
||||
| 2. Hidden full-buffer/dirty-page copies? | B's matched windows constrain cost relative to its explicit full READBACK copy (B-1/B-2). | Faster, overlapping, deferred, CPU-write-stage or referenced-range work remains possible. Supplied-input extraction is now independently reproduced; independent GPU recapture/physical traffic remain unestablished. |
|
||||
| 3. Can inverted ownership satisfy xmem? | Candidate for eligible graphics bytes; not a universal provider (A-5/A-6). | Preserve unsupported address/section/reservation/pre-device/existing-content contracts; console meanings remain unverified. A confirms a combined-cap source defect in c13f9c7. |
|
||||
| 4. Shared versus GPU-optimized resources? | Both CPU-visible and DEFAULT paths have scoped correctness evidence; B measures different workloads (A-9–A-12, B-3/B-7). | No intrinsic heap ranking or identification of opaque Metal storage modes. |
|
||||
| 5. Does pooling help? | Certain allocation-call costs improve; bounded statistics/reuse are demonstrated (A-2–A-4). | Cold setup, slack, fragmentation, host retention and production workload cost remain separate; no general application gain. |
|
||||
| 6. Necessary synchronization/lifetimes? | CPU ownership, states, fences, alias ordering and owner retention are required. | Multi-queue/production failure cleanup need qualification; the bounded disposable-helper tests are accepted within scope (A-13/B-3). |
|
||||
| 7. Required fallbacks? | CPU/section ownership and explicit transfers where the mapped provider cannot meet the contract; format-aware texture paths. | CPU watch is only a serialized eligible-allocation optimization; general GPU tracking remains Unknown (B-4/B-5). |
|
||||
| 8. What informs #464? | Validate actual alignment/span/ownership and preserve logical versus host accounting; provide scoped reproduction fixtures. | No production edit or certification of its implementation; existing owner and independent acceptance remain intact. |
|
||||
|
||||
These answers fulfill the consolidation questions as research outcomes, including unresolved ones. They do not satisfy every independent acceptance criterion or complete M2.
|
||||
|
||||
## 3. Experimental methodology
|
||||
|
||||
Only original or authorized synthetic workloads, public interfaces and publicly licensed source were used. CrossOver, D3DMetal, Rosetta and host tools remain external. AMD D3D12 Memory Allocator 3.3.0 is pinned at `600949266be004553f74c9ef809384380a9d44cf`, with per-file MIT notices and Git blobs recorded before use. Its implementation remains in ignored artifacts, not a production dependency.
|
||||
|
||||
A's accounting profile requests fresh processes for 64/256/1024 MiB across CPU-only, graphics-warmed CPU, CUSTOM WB/L0 and UPLOAD. It separates settled baselines, initialization, full GPU consumption, resource release, command/pipeline/output retirement and device release. Repeated in-stage samples are correlated. The checksum validates a reduction across source words, not every byte independently. Repeated sessions are incomplete.
|
||||
|
||||
A's pooling study uses matched payload, description, alignment and GPU work, deterministic seeds and changing data. Cold pool creation, allocation, placement, Map and retirement are separate. Real delayed queued work, guard/interior readbacks and an omitted-copy negative control accompany a separate logical interval model. The latter does not measure a driver allocator.
|
||||
|
||||
B's sweeps use 1/16/64 MiB, WB/WC/UPLOAD, two write strides, seeded case/page order, three warmups and twelve measured iterations. Whole-byte rewrites are distinct from one word per page. Small GPU copies preserve fixed endpoint/interior work; full copies validate the full destination. CPU writing, command encoding, execution, signal/wait and validation have separate intervals. Compute poisoning/omitted-dispatch controls are separate from copy controls. Instruments captures remain separate from uninstrumented host timings.
|
||||
|
||||
The host safety policy independently gates kernel pressure and the conservative occupied-memory metric, with explicit reserve below 23,000,000,000 bytes. It cannot redefine existing swap or correlated samples as normal-pressure independent runs. Urgent pressure blocks required remaining GPU/large studies; no optional 2 GiB or concurrent polling experiment was run.
|
||||
|
||||
## 4. Workstream A findings
|
||||
|
||||
The corrected first accounting sweep completed twelve processes; the bounded continuation completed six smaller/control cases and stopped the next graphics case under urgent pressure. In the first sweep, large graphics allocations retained process-accounted charge after resource, command and device release; CPU controls differed and 64 MiB graphics could fit previously charged pools. RSS and footprint diverged under compression/swap. This does not identify physical residency, allocation count or a leak.
|
||||
|
||||
Three matched pooled/individual pairs show reduced heap/suballocation-call components, separately measured pool setup and noisy whole-cycle results. The 32 MiB GPU trace did not exhaust the slab. The separate model exercises 6012 snapshots, fixed external fragmentation, variable alignment/lifetimes and simulated pending retirement; corrupted copied statistics are rejected.
|
||||
|
||||
Six WB/WC allocator processes use one 32 MiB block. Each 432-request sequence matches its original pool seed; all 216 full/holes/empty statistics agree with a separate interval calculation. Sampled readbacks match and oversized valid requests return E_OUTOFMEMORY. Empty library allocations coexist with configured block retention. Library ownership does not automate queue-fence retirement.
|
||||
|
||||
Valid overlapping buffers, mixed mip textures and reinitialized render/depth aliases have scoped M4/M5 evidence. The texture rejection gate fails because two invalid buffer calls succeed; invalid objects are never GPU-used. A's offset-1 call also overflows the heap span by one byte, while B isolates alignment with a larger heap. One corrected graphics smoke checks seven 512-pixel outcomes for point sampling, raster depth and stencil. B reproduces variant0 and the omitted-draw control on M5, but variant1 stops at STAGE stencil after depth passes. Its repeated profile remains incomplete; published frame hashes match A's independently generated expectations, while raw RGBA bytes are not supplied.
|
||||
|
||||
## 5. Workstream B findings
|
||||
|
||||
Two M5 copy sweeps complete 36 processes and 5040 measured comparisons. Four WB 64 MiB comparisons show full rewrite versus no-write small-copy completion excess of 46–279 microseconds. Word-per-page timings are variable and nonmonotonic. The no-write explicit full-copy workload takes approximately 2.09–2.36 milliseconds median. This challenges comparable-cost serial full copying within the small-copy window, not copying in every stage or domain.
|
||||
|
||||
Two uninstrumented compute sessions produce 576 measured comparisons across WB→WB, WC→WC, UPLOAD→WB and staged DEFAULT→DEFAULT. CPU/GPU visibility is fence-separated; poison remains when dispatch is omitted. Shader workloads use 4 MiB. Direct and staged outputs have different transfer work, and sparse cases are completion-latency dominated.
|
||||
|
||||
Separate Metal extracts report 300 shader and 45 full-copy intervals including warmups. Payload divided by interval duration is workload throughput, not physical transaction bandwidth. Published medians and variability recalculate, and A now independently reruns all seven XML extractions and verifies the supplied-table PID/reference/join/timing arithmetic. Unfiltered capture completeness is not independently established. Single pressured captures and substantial outliers preclude a general ordering of heap types.
|
||||
|
||||
CPU write-watch's 4096-byte returned page sets distinguish subpages, reset/rearm, reads and same-value stores. Those allocations cannot be imported through the tested address-open route. General GPU tracking remains unresolved. D3D12 timestamp resolves leave distinct sentinels unchanged; the corrected clock result declines to supply GPU elapsed time, preserving the earlier invalid sentinel-difference diagnostic.
|
||||
|
||||
## 6. Cross-generation comparisons
|
||||
|
||||
M4: 24 GiB, macOS 27.0 (26A428). M5: 16 GiB, macOS 27.2.1 (26B131). Both recorded CrossOver 26.3.0.39832, D3DMetal 3.0 and the later-observed Wine 11.0-8726-g2e2f5fca349, with different Rosetta/toolchain receipts. The initial baseline did not independently record its exact Wine engine. Per-run metadata governs each claim.
|
||||
|
||||
B rebuilds the same earlier A alias/texture source on M5 and independently derives expectations; PE build hashes differ. CPU pointer remainders vary across both hosts. Positive texture subcases and the overall failed rejection gate reproduce. These are useful cross-generation observations under stated protocols, not controlled isolation of chip generation from OS, pressure or runtime effects. B now executes the unmodified six-check shared runner on M5 with matching functional results; separate receipt-only lsof corroborates the backend but is not the full benchmark PID. The exact-runner functional reproduction gap is closed, while normal-pressure comparisons remain open. No new M1–M3 hardware coverage is claimed.
|
||||
|
||||
## 7. Independent verification results
|
||||
|
||||
B's pinned A review re-derives mip sizes, clear values, pointer/placement distinctions, aliases and accounting checkpoints, and records its hardware reproduction. It identifies the old A helper's unsafe error unwinding. B now reviews the allocator/model/graphics additions and publishes explicit scoped decisions, paired allocator and partial graphics reproductions, plus bounded helper fault tests. Its bitmap checker/M5 logical rerun raw are still only described, not included.
|
||||
|
||||
A exports B read-only, checks 98 source identities, 33 watch phases, reported uninstrumented match counts and 1080 recorded compute endpoint pairs including separate traced captures. A recalculates every published trace median, median absolute deviation and useful-payload rate. These are actual source/data checks, not M4 hardware reproduction. A additionally reproduces all seven trace extractions from sanitized XML with a separate resolver/join/unit/statistics audit, and independently reproduces the late-output process race without Wine/GPU execution. Twelve A findings have explicit scoped B acceptance; A accepts B-7 for supplied-input extraction, making thirteen scoped accepted entries. A's build-only B snapshot launches zero guests. No independent acceptance is inferred from matching summaries or from an author-written second checker.
|
||||
|
||||
## 8. Failed experiments and negative controls
|
||||
|
||||
Preserved failures include initial build/setup errors, historical timeout, two corrected-accounting pressure stops, accepted-invalid creation calls, the first graphics compiler-DLL lifetime bug, the no-guest graphics repeat stop, unavailable timestamp resolves, an Instruments pressure stop and a capture-save timeout/retry. Specific omitted-copy/dispatch poison and corrupted-statistic controls retain expected outcomes. An unrun control is not a pass.
|
||||
|
||||
One stopped B stderr differs from its recorded empty-file hash; all other 155 reviewed stdout/stderr/HLSL/DXBC hashes match. Original receipt and output remain unchanged. B supplies an APFS timestamp table and source explanation; A reproduces the exact empty-to-handshake SHA race with real Python subprocesses. The late-writer/finalization mechanism is supported independently; the historic filesystem timings remain attributed to B. B-local-1.1 fixes the tested ordering, but ignores a failed normal wineserver wait, so unsuccessful cleanup cannot certify finality. There is no evidence that this stopped-run discrepancy affects the completed benchmark data.
|
||||
|
||||
## 9. Remaining limitations
|
||||
|
||||
Required M4 B reproduction, repeated graphics datasets, omitted draw, frame-data recalculation, local failed-fence reproduction and missing accounting repeats are blocked by pressure. B's bounded M5 helper tests are now accepted within disposable-guest scope. Supplied XML/schema/reference inputs have been independently replayed; missing raw bitmap/RGBA/forensic transcripts and failed-cleanup propagation remain separate review follow-ups. Five already-published historical/setup source references lack retained matching bytes; newer successful runs retain sources.
|
||||
|
||||
The studies do not establish arbitrary texture formats/layouts, MSAA, compressed/planar data, arrays/3D, general filtering, all heap tiers, production allocator defragmentation, device loss or multi-queue lifetime. These gaps limit admission of those resource classes, while the existing evidence already rules out a universal raw-buffer treatment of opaque textures. Console cache/ABI semantics, game execution and physical backing mechanisms are not verified.
|
||||
|
||||
## 10. Proposed unified-memory architecture
|
||||
|
||||
Use a requirement-based provider decision, not a single physical-sharing assumption. Before exposing any pointer, classify the requested CPU address/alignment, device availability, protection/commit semantics, section/scatter requirements, contents/identity obligations and resource class. Inspect the actual returned Map address. A legal byte slice inside a buffer still needs its own valid views, offsets and bounds; it does not become a newly placed resource at a biased offset.
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
Q[Allocation and resource requirements] --> E{Mapped buffer contract fits?}
|
||||
E -->|Yes| M[Bounded D3D12-owned buffer candidate]
|
||||
E -->|No| C[CPU or section-owned allocation]
|
||||
C --> T[Explicit synchronized transfer]
|
||||
M --> L[Owner metadata and final-use fences]
|
||||
T --> L
|
||||
O[Opaque texture requirements] --> F[Format-aware subresource or upload/readback path]
|
||||
F --> L
|
||||
L --> R[Retire before reuse or destruction]
|
||||
M --> B[Logical payload and backing budget]
|
||||
C --> B
|
||||
B --> H[Separate host footprint and retained-charge observation]
|
||||
```
|
||||
|
||||
B endorsed the architectural recommendation and confirmed the source-derived budget correction at d3ae607. It is not a new frozen ABI or working production provider. Existing/pre-device/fixed-address data must retain its original owner unless an independently validated transfer of ownership can preserve the required contract.
|
||||
|
||||
## 11. Allocation and pooling recommendations
|
||||
|
||||
Prefer evaluating the established pinned AMD allocator over turning the experimental first-fit model into a production allocator. Its demonstrated bounded CUSTOM buffer/statistics behavior fits a limited candidate use. Eligibility, queue retirement, stable guest pointers and unified accounting remain BetterXen responsibilities. Do not silently enable defragmentation that moves exposed pointers.
|
||||
|
||||
Distinguish requested payload, allocation-rounded spans, reserved slabs, alignment waste, reusable free space, largest free span and fence-pending storage. Do not charge a slice and its parent as two guest payloads. During migration, old and new backing both remain reserved until retirement. A library's empty allocation statistics do not establish OS physical release. Benchmark cold setup, steady allocation, retirement and a full workload before promising performance or memory benefit.
|
||||
|
||||
## 12. Synchronization and lifetime requirements
|
||||
|
||||
Finish CPU producers before submission; wait for the appropriate final-use queue fence before CPU reads, overwrite, destruction or reuse. Persistent mapping alone supplies neither scheduling nor an atomic interoperability contract. Bind states appropriate to buffers, textures and queue use; uphold required alias ordering and post-activation render/depth initialization. Retain resource, heap, descriptor and command owners through use. Multi-queue work needs explicit cross-queue dependencies and final-use ownership.
|
||||
|
||||
Validate adapter/resource allocation alignment and overflow-safe spans at the owned placement boundary: a valid alignment, offset within heap, and size no greater than heap size minus offset. Do not impose a global 64 KiB placement rule on small textures whose allocation-info alignment differs. CPU alignment is independently checked. These are derived requirements from the public [placed-resource contract](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device-createplacedresource) and the scoped failures, not new console semantics.
|
||||
|
||||
A's independently peer-reviewed research helper fails the disposable process with exit 2 when fence completion is unproven, instead of unwinding reusable storage. Runtime qualification must also cover supervisor termination and final output sealing. [ExitProcess](https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-exitprocess) can call DLL detach code and deadlock; compilation is not a teardown proof. B observes clean termination for its three bounded M5 cases and explicitly accepts this single-threaded research-helper scope. It does not inject actual Signal API failure or qualify arbitrary production teardown; production recovery remains open.
|
||||
|
||||
## 13. Explicit fallback mechanisms
|
||||
|
||||
| Contract or resource need | Candidate fallback | Condition |
|
||||
| --- | --- | --- |
|
||||
| CPU-only, pre-device, requested VA or existing exposed pointer/content | Conventional CPU/section allocation with explicit transfer where graphics needs it | Preserve identity and protection/commit semantics; do not replace a live pointer silently. |
|
||||
| Physical tags, independent CPU aliases or scatter views | Existing section/physical mapping engine and an explicit graphics boundary | D3D12 GPU aliasing is not proof of equivalent CPU section semantics. |
|
||||
| Opaque textures or GPU-oriented rendering | Format-aware subresource writes or DEFAULT upload/readback path | DEFAULT is not proof of D3DMetal's underlying private Metal storage mode; qualify each format/use. |
|
||||
| CPU-written selective transfer | Optional write-watch on the eligible CPU allocation | Serialize writers/query/reset/snapshot/copy/retry; returned granularity governs. |
|
||||
| Unknown GPU writers | Supported explicit synchronization and conservative transfer/known-writer instrumentation | Do not assume watch on a foreign Map pointer or universal GPU dirty tracking. |
|
||||
|
||||
The public [write-watch allocation contract](https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-getwritewatch) limits applicability. Its CPU success does not validate a general GPU coherence fallback.
|
||||
|
||||
## 14. Implementation risks
|
||||
|
||||
The main correctness risks are pointer/offset confusion, losing existing contents, freeing fence-pending storage, double or inconsistent budget charges, integer overflow, unsupported opaque layout reinterpretation, and accepting creation as validation. Failure cleanup and concurrent budget/lifetime transitions need dedicated verification. Main performance risks are cold setup, unused slab capacity, fragmentation, retained driver charges, extra transfers, compression/swap and costs moved outside timed windows. Required mitigations appear as acceptance criteria in the [roadmap](implementation-roadmap.md), not assumed implementations.
|
||||
|
||||
## 15. Recommendations relevant to #464
|
||||
|
||||
The existing implementation owner retains its scope. #486 was previously inspected at 6308fdc; the reviewed successor is `c13f9c76650edded41774528b50f40798244a6f3`, which merges main onto c44ae4e without changing vmem files. It already describes a bounded backing-heap opt-in, allocation-info alignment/span validation there, ordinary-request forwarding and live-heap accounting. Reuse/review that work instead of proposing a duplicate provider. A independently confirms a combined-budget source defect: xmem admission does not see private D3D12 heap charges, and the separate locks do not make admission atomic. A private6-then-CPU3 sequence can pass both local checks against cap8, assuming successful distinct allocations. A stale-snapshot schedule can reach12 against8. This is a bounded source-derived counterexample, not a production run; no production or ABI code is changed. The report does not certify its wrappers or runtime behavior.
|
||||
|
||||
Its comment attributing physical/shared-memory interpretation to #473 exceeds this research's mechanism evidence if read as page identity or no copies. The appropriate handoff is version-scoped mapped visibility and legal alias behavior, plus explicit eligibility, lifecycle and fallback constraints. Reported CrossOver 26.2/vkd3d tests are separate from direct-host D3DMetal probes. Existing xmem address identity and Map address must be tested independently; initializing a new Map pointer does not prove preservation of preexisting section contents.
|
||||
|
||||
## 16. Remaining research questions
|
||||
|
||||
The supplied-input trace extraction and core stopped-output mechanism are now independently verified; historical failed receipts remain preserved. Require explicit handling of failed cleanup, request the remaining peer-artifact transcripts, obtain critical M4 hardware and incomplete graphics/accounting sessions when safe, and qualify production error paths separately. The combined-budget source defect needs an owner-authorized atomic admission design and regressions, not just observability. Only then consider workload-qualified allocator integration, further resource classes, multi-queue/device-loss stress and controlled production measurements. Stronger physical-mechanism claims require a separate discriminating observation, not another repetition of flat timing.
|
||||
|
||||
## 17. Evidence and reproduction appendix
|
||||
|
||||
Use [the register](evidence-register.json) for exact revisions and raw links. [A's pinned handoff](https://github.com/MacosPorters/betterxen/issues/473#issuecomment-7204949581) contains source/PE/shader hashes and historical/current reproduction distinctions. [B's published source guide](https://github.com/MacosPorters/betterxen/blob/a40228747470f0d184375e451b0173769c90aef5/docs/research/d3dmetal-zero-copy/copy-detection/README.md) and review inputs are pinned. [A's B review](../review-b.md), [publication audit](../publication-audit.md) and [resource/lifetime derivation](../../gpu-correctness/contracts/resource-placement-lifetime.md) retain scope and failures.
|
||||
|
||||
This report can be published and reviewed with blocked work explicitly identified. It cannot be called independently accepted or complete merely because all sections are written. The proposed roadmap is a reviewable recommendation; production implementation, ABI changes, issue creation and merging remain unauthorized.
|
||||
|
||||
## Final verification record
|
||||
|
||||
[Detailed findings](../final-verification/findings.md) identify exact new replay receipts, fault-test scope, the corrected stencil-stop description, source-budget counterexamples and unresolved packaging/cleanup limitations. B [signed off d3ae607](https://github.com/MacosPorters/betterxen/issues/473#issuecomment-7206014568), confirming the A-12 correction, the R3 admission analysis and the R4 cleanup follow-up. All 29 register records are retained, with scoped acceptance attributed to the actual reviewer. Research branch integration is authorized; main and production/ABI changes remain unauthorized.
|
||||
|
||||
The [final research acceptance checklist](acceptance-checklist.md) distinguishes scoped findings, blocked work, publication and future permission gates. The [integration proposal](integration-proposal.md) specifies exact-ref coordination and prioritized production recommendations; the [integration record](../../integration.md) states how it was carried out. Neither authorizes implementation.
|
||||
@@ -0,0 +1,12 @@
|
||||
# CPU-only final verification
|
||||
|
||||
This A-owned follow-up reviews B commit `4ba4926d2f491517c01b1e94fb8539184055dc22`. [Findings](findings.md) and the [joint report](../consolidation-draft/report.md) distinguish independently accepted scopes from historical failures, missing artifacts and pressure-blocked hardware work. The requester now authorizes DCO-signed publication of these research changes on the dedicated A branch; they do not modify or consolidate either production branch.
|
||||
|
||||
The four original Python tools perform source/data/process checks only:
|
||||
|
||||
- `verify-traces.py /path/to/B-worktree --output /tmp/new-trace-output`: run B's unchanged extraction on all seven sanitized XML pairs and independently check references, PIDs, ID joins, durations/units, denominators and distributions. No GPU or Instruments is used.
|
||||
- `verify-harness.py /path/to/B-worktree --output /tmp/new-process-output`: run real bounded Python parent/child processes through old and corrected B orchestration. Backend identification and Wine cleanup are explicitly simulated; these controls cannot establish GPU or actual Wine correctness. They reproduce the historical hash-race class and reveal ignored cleanup failure.
|
||||
- `review-peer.py /path/to/B-worktree --output /tmp/peer-review.json`: inspect baseline source/exit, published fault logs, the two-case M5 allocator subset and independently generated expected frame hashes. It does not inspect absent raw RGBA files or claim to have executed B's unpublished bitmap checker.
|
||||
- `verify-budget.py /path/to/c13-source-export --output /tmp/budget-review.json`: check pinned source expressions and produce small integer counterexamples, allocating no buffers or heaps. Export the pinned `shims/xmem/{xmem.cpp,physical_pages.cpp}`, `shims/d3d12_xs/vmem.cpp` and `abi/include/bx_xmem_internal.h` into that read-only root. No production code executes.
|
||||
|
||||
The first process-fixture import setup failed before any child launched; its [record](../../results/2026-11-26-apple-m4-arths17-final-process-fixture-setup/setup-failure.json) is preserved separately. The corrected layout and successful controls are in the process-sealing bundle. Raw results and their append-only manifests remain separate from later documentation. Python cache files/native executables are excluded from public research archives. Historical receipts are not rehashed in place to suppress discrepancies.
|
||||
@@ -0,0 +1,65 @@
|
||||
# Final reciprocal verification findings
|
||||
|
||||
A reviewed B revision `4ba4926d2f491517c01b1e94fb8539184055dc22` and all three specified #473 comments in full. B independently reviewed A evidence at 8c9eceb and the prior consolidation at 677686e. The requester authorizes DCO-signed publication of this research update on the dedicated A branch; branch consolidation and production changes still require separate authorization. No production, ABI, main or frozen baseline source was changed. No Wine, Instruments or GPU workload was launched on M4 in this pass.
|
||||
|
||||
## Seven trace extractions: independently reproduced and accepted within scope
|
||||
|
||||
[Exact replay receipts](../../results/2026-11-26-apple-m4-arths17-final-trace-replay/receipt.json) retain all seven command arrays, input/extractor SHA-256 identities and complete output JSON. Every unmodified B extractor invocation exits 0 and produces JSON equal to the corresponding published result. A's separate XML reader resolves references, checks only the declared guest PID, schema columns, unique encoder/command-buffer associations and CPU/GPU chronological order. Duration numbers agree with the XML's formatted units at their displayed precision. Payloads are 4 MiB shader workloads versus 64 MiB copy workloads, and bytes/ns correctly yields decimal GB/s. All measured medians, median absolute deviations, extrema and rates recalculate; warmups and outliers remain present.
|
||||
|
||||
| Capture | PID | Selected intervals | Excluded target encoder rows |
|
||||
| --- | ---: | ---: | ---: |
|
||||
| WB compute | 60493 | 75 | 0 |
|
||||
| WC compute | 60634 | 75 | 0 |
|
||||
| UPLOAD→WB compute | 60758 | 75 | 0 |
|
||||
| DEFAULT compute | 60843 | 75 | 270 staging/readback blits |
|
||||
| WB full copy | 60920 | 15 | 0 |
|
||||
| WC full copy | 61014 | 15 | 0 |
|
||||
| UPLOAD copy retry | 61276 | 15 | 0 |
|
||||
|
||||
B-7 is independently accepted **for deterministic extraction from these supplied sanitized XML tables**. This goes beyond the previous arithmetic-only check. It does not independently recapture the GPU, establish completeness against the unavailable full unfiltered trace, identify physical transactions or establish intrinsic heap rankings. The sanitizer source and its declared full-export hashes support provenance, but A did not obtain the original full traces.
|
||||
|
||||
```sh
|
||||
python3 docs/research/d3dmetal-zero-copy/allocation-profiling/final-verification/verify-traces.py /path/to/detached/B-4ba4926 --output /tmp/fresh-trace-replay
|
||||
```
|
||||
|
||||
## Stopped-run forensics and corrected harness
|
||||
|
||||
The original historical receipt/output are unchanged. A reconfirms the empty declared stderr digest versus the handshake-error bytes. B's published APFS table places the stderr modification 3,656,510 ns after case.json; A verifies that subtraction, while attributing the filesystem timestamps to B's record rather than an independent query of B's host.
|
||||
|
||||
A's [real Python process fixture](../../results/2026-11-26-apple-m4-arths17-final-process-sealing-clean/receipt.json) independently reproduces the same empty-to-handshake SHA transition with old B `run_case`: the launcher group exits while a separately grouped child waits on inherited stdin; sealing precedes scope-exit EOF and the child's final stderr write. Against B-local-1.1, normal and forced-stop fixture outputs have matching recorded/final hashes, and the after-guest callback finalizes its simulated wrapper log before sealing. This supports the late-writer/finalization mechanism and specific correction. It is not a real Wine or historical APFS replay; Wine cleanup calls are deliberately simulated and no graphics API is involved.
|
||||
|
||||
One hardening issue remains: the normal-path `wineserver -w` result is discarded. A controlled return of exit 124 still leaves `exit=0` and no error. Error-path cleanup results are retained but their failures are not enforced either. Therefore receipt finality is not established when cleanup fails/times out. B's real-Wine forced-stop verification is reported in prose, but its original result/command transcript is not present in this pin. A requested that minimal record. B-8 remains Failed for the historical sealed receipt, with the cause/source mechanism now independently supported and this further failure-path limitation explicit. No evidence implicates completed benchmark guest/shader outputs; wrapper xctrace logs have separate mid-save hashes/redaction records.
|
||||
|
||||
```sh
|
||||
python3 docs/research/d3dmetal-zero-copy/allocation-profiling/final-verification/verify-harness.py /path/to/detached/B-4ba4926 --output /tmp/fresh-process-review
|
||||
```
|
||||
|
||||
The first A fixture setup attempt failed before launching any child because the old module's path was too shallow for its original relative-directory calculation; the corrected fixture restores that layout. This setup failure is distinct from all process/GPU outcomes.
|
||||
|
||||
## Peer decisions and runtime-test limits
|
||||
|
||||
B explicitly accepts BASE-1/3/4/5/6, A-3/4/6/8/9/10/13 within its stated scope. The register credits those twelve decisions to B; A does not certify its own components. BASE-2 remains version-scoped Unsupported and A-7 retains the failed negative-rejection gate. A independently checks B's published source/logs and regenerates thirteen expected graphics hashes; the [review receipt](../../results/2026-11-26-apple-m4-arths17-final-source-data-review/peer-evidence-review.json) records exactly what was checked.
|
||||
|
||||
The shared baseline source and full-run exit/timeout records match; B's lsof evidence is from a **separate receipt-only process**, not the full benchmark PID. This closes exact shared-runner functional cross-generation reproduction while retaining that backend-provenance distinction and baseline timing limits.
|
||||
|
||||
A-4's M5 reproduction is a WB/WC seed-473 pair using the corrected helper, not six M5 cases or byte-identical historical helper execution. All six M4 logs receive B's source/data review. A-3's independent bitmap checker and M5 rerun are reported by B but their source/raw reproduction are not in this pin; the register attributes them rather than claiming A ran that checker. Split remainders are visited in vector/split-age order between sorting/coalescing operations, and rounding assumes the bounded input domain.
|
||||
|
||||
B's A-13 fixture has a real positive queued gated-copy and two exit/canary controls. The Signal control **directly invokes stopInFlight**, rather than inducing a real queue Signal failure. The timeout uses an empty unsignaled fence with no stalled GPU work. Logs match the result JSON, exit codes are 0/2/2, and the stack canary does not run on failure exits. The fault bundle supplies source/logs and a peer attribution to the exact helper, but no dedicated full build/PE-hash receipt; A does not claim to verify a missing executable identity chain. B accepts the research helper for single-threaded disposable guests; production multithreaded/DLL-detach, device-removal and arbitrary failed API supervision remain separate. M4 pressure is still a safety blocker, but B helper review is no longer a blocker to later safe dependent runs.
|
||||
|
||||
A-12 remains incomplete. Raw stdout shows M5 variant1 completed both depth comparisons and then emitted **STAGE stencil** before the urgent-pressure stop, correcting the review comment's “depth” wording. B publishes frame SHA manifests and omitted-control oracle metadata, not raw RGBA payloads. A's independent expected-byte hashes all match the thirteen provided hashes; this is not direct inspection of the missing frame bytes. Variant0 and omitted draw are scoped reproductions, while the two-dataset matrix stays Blocked/Unknown.
|
||||
|
||||
## Independently confirmed combined-budget defect
|
||||
|
||||
A inspected exact sources at PR #486 revision `c13f9c76650edded41774528b50f40798244a6f3`; its vmem files are unchanged from c44ae4e. Source fingerprints and a bounded [arithmetic counterexample](../../results/2026-11-26-apple-m4-arths17-final-source-data-review/budget-review.json) are retained. This is source-derived reasoning, not production execution or a physical-memory measurement.
|
||||
|
||||
`shims/xmem/xmem.cpp:73` admits requests against heap+virtual+physical bytes under `usage_lock`. Both virtual commits and physical reservations use that authority, and heap allocations do too. PR `vmem.cpp:101` takes `g_section`, obtains an xmem statistics snapshot and additionally counts its private live heaps. No reverse private-heap visibility exists in xmem admission. Its exported committed statistic already includes xmem heap bytes, so the defect is not an omission of that particular field; it is missing reverse visibility and atomic combined admission.
|
||||
|
||||
With a stable common cap of 8 abstract units, a distinct private heap of 6 can succeed with xmem=0; then an xmem request of 3 sees xmem=0 and succeeds, yielding combined live storage 9. Reverse order rejects the heap. A concurrent source-permitted schedule starts with xmem4, snapshots4 for the graphics request, commits another CPU4 and then graphics4 from the stale snapshot, yielding12 against8. These examples assume successful underlying allocations and no aliases; no GiB buffers are allocated. R3 must address correctness/atomicity, not merely display summed counters. Source proof does not replace backend regression tests or authorize a fix, and does not certify/reject the entire PR.
|
||||
|
||||
```sh
|
||||
python3 docs/research/d3dmetal-zero-copy/allocation-profiling/final-verification/verify-budget.py /path/to/read-only/c13f9c7-export --output /tmp/budget-review.json
|
||||
```
|
||||
|
||||
## Status boundary
|
||||
|
||||
Thirteen register entries have scoped independent acceptance: twelve explicit B peer decisions and A's supplied-input trace extraction decision. Unsupported imports, failed rejection/timestamp/receipt gates and Unknown physical mechanisms remain distinct. M4 B hardware reproduction, graphics repetition/omitted draw and missing footprint sessions remain urgent-pressure blocked. B's bitmap/raw-frame/forensic transcript packaging and finalization failure propagation are review follow-ups, not memory-pressure blockers to CPU work. No physical zero-copy, guaranteed production speedup or game compatibility is claimed.
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Inspect published peer receipts, fault logs and image-hash expectations without GPU work."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
|
||||
|
||||
def main():
|
||||
ap=argparse.ArgumentParser(description=__doc__);ap.add_argument('b_worktree',type=Path);ap.add_argument('--output',type=Path,required=True);a=ap.parse_args()
|
||||
rs=a.b_worktree/'docs/research/d3dmetal-zero-copy/results';prefix='2026-11-27-apple-m5-atesahmet0-'
|
||||
record={'b_revision':'4ba4926d2f491517c01b1e94fb8539184055dc22','scope':'published source/data inspection, no GPU or Wine launch'}
|
||||
base=rs/(prefix+'b-baseline-runner-01');d=json.loads((base/'receipt.json').read_text())
|
||||
assert hashlib.sha256((base/'probe.cpp').read_bytes()).hexdigest()=='33e90bfee89e812f48990613cd74ced56473e5c3fc5d973f2ba1116090646a0c'
|
||||
assert d['run_exit_code']==0 and not d['timed_out']
|
||||
record['baseline']={'source_hash_matches':True,'exit':d['run_exit_code'],'timed_out':False,'backend_scope':'separate receipt-only process supplies lsof evidence, not the full benchmark PID'}
|
||||
fault=rs/(prefix+'b-a-fence-fault-01');cases=json.loads((fault/'results.json').read_text());record['fault_cases']=[]
|
||||
for name,c in cases.items():
|
||||
text=(fault/name/'stdout.txt').read_text();assert text==c['stdout'] and 'UNSAFE_UNWIND' not in text
|
||||
assert c['exit']==(0 if name=='positive_gate' else 2)
|
||||
record['fault_cases'].append({'name':name,'exit':c['exit'],'stdout_matches':True,'canary_output_absent':True})
|
||||
record['fault_scope']='positive real queued copy; Signal failure dispatcher called directly; timeout on empty unsignaled fence; no actual Signal HRESULT failure or arbitrary multithreaded teardown injection'
|
||||
record['graphics_hash_expectations']=[]
|
||||
for group in ['b-a-render-01','b-a-render-omit-01']:
|
||||
root=rs/(prefix+group)
|
||||
if (root/'rgba-hashes.json').exists():manifest=json.loads((root/'rgba-hashes.json').read_text())
|
||||
else:
|
||||
omitted=json.loads((root/'archive.json').read_text())['omitted_local_artifacts_sha256']
|
||||
manifest={p:{'bytes':2048,'sha256':h} for p,h in omitted.items() if p.endswith('.rgba')}
|
||||
for path,entry in manifest.items():
|
||||
match=re.fullmatch(r'(render-s[01]|render-omitted-draw-control)/readback_(wb|wc|default)_m([012])_p([01])\.rgba',path);assert match,path
|
||||
variant=1 if match[1]=='render-s1' else 0
|
||||
visible=(int(match[3])==0 or int(match[4])==1) and match[1]!='render-omitted-draw-control'
|
||||
palettes=[[(255,0,0,255),(0,255,0,255),(255,0,255,255),(0,255,255,255)],[(0,0,255,255),(0,255,0,255),(255,0,255,255),(255,255,0,255)]]
|
||||
raw=bytes(v for y in range(16) for x in range(32) for v in (palettes[variant][(2 if y>=8 else 0)+(1 if x>=16 else 0)] if visible else (0,0,0,0)))
|
||||
assert len(raw)==entry['bytes']==2048 and hashlib.sha256(raw).hexdigest()==entry['sha256']
|
||||
record['graphics_hash_expectations'].append({'group':group,'path':path,'expected_sha_matches_reported':True,'raw_rgba_published':(root/path).exists()})
|
||||
record['graphics_stop']='render-s1 completed both depth passes; last marker STAGE stencil, Urgent stop; repeat incomplete'
|
||||
record['forensic_delta_ns']=1795730540932343519-1795730540928687009;assert record['forensic_delta_ns']==3656510
|
||||
record['forensic_timestamp_provenance']='published B stat table, not an independently retrieved APFS transcript; separate A process fixture reproduces the hash race'
|
||||
record['missing_artifacts']=['independent B bitmap checker and M5 logical rerun raw','raw RGBA bytes (hash-only verification available)','raw stat transcript / corrected forced-stop receipt']
|
||||
# The paired allocator run is a subset, not a six-case M5 reproduction.
|
||||
allocator=rs/(prefix+'b-a-d3d12ma-01');r=json.loads((allocator/'receipt.json').read_text());assert len(r['cases'])==2
|
||||
record['allocator_subset']=[]
|
||||
for c in r['cases']:
|
||||
assert c['exit']==0 and not c['timed_out'];text=(allocator/c['name']/'stdout.txt').read_text()
|
||||
alloc=[line for line in text.splitlines() if line.startswith('REFERENCE_ALLOC ')]
|
||||
stats=[line for line in text.splitlines() if line.startswith('ALLOCATOR_STATS ')]
|
||||
reads=[line for line in text.splitlines() if line.startswith('REFERENCE_VERIFY ')]
|
||||
assert len(alloc)==432 and len(stats)==36 and len(reads)==24
|
||||
assert all('matched=1152/1152' in line for line in reads)
|
||||
assert 'POOL_BOUND_CONTROL requested_bytes=33554436 HRESULT=0x8007000E rejected=1' in text
|
||||
record['allocator_subset'].append({'case':c['name'],'requests':len(alloc),'stats':len(stats),'readbacks':len(reads),'bound_rejected':True})
|
||||
a.output.write_text(json.dumps(record,indent=2)+'\n');print('Peer evidence inspected:',len(cases),'fault cases,',len(record['graphics_hash_expectations']),'hash expectations,',len(record['allocator_subset']),'allocator cases')
|
||||
|
||||
|
||||
if __name__=='__main__':main()
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Bounded arithmetic/source counterexamples; no allocation or production code execution."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def cpu_allows(used, request, cap):
|
||||
return used <= cap and request <= cap - used
|
||||
|
||||
|
||||
def graphics_allows(snapshot, charged, request, cap):
|
||||
return not (request > cap or snapshot > cap or charged > cap - snapshot) and request <= cap - snapshot - charged
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description=__doc__);ap.add_argument('source_root', type=Path);ap.add_argument('--output', type=Path, required=True);a=ap.parse_args()
|
||||
paths=['shims/xmem/xmem.cpp','shims/xmem/physical_pages.cpp','shims/d3d12_xs/vmem.cpp','abi/include/bx_xmem_internal.h']
|
||||
text={f:(a.source_root/f).read_text() for f in paths}
|
||||
assert 'const uint64_t used = heap_bytes + virtual_bytes + physical_bytes;' in text[paths[0]]
|
||||
assert 'return used <= limit && bytes <= limit - used;' in text[paths[0]]
|
||||
assert 'charged_private_bytes' not in text[paths[0]]
|
||||
assert 'bx_xmem::try_reserve_physical(total_bytes)' in text[paths[1]]
|
||||
assert 'const uint64_t xmem_used = stats.committed_virtual_bytes + stats.allocated_physical_bytes;' in text[paths[2]]
|
||||
assert 'g_record.charged_private_bytes += bytes;' in text[paths[2]]
|
||||
# Values are abstract GiB units, not allocated memory.
|
||||
cap=8; x=g=0
|
||||
first=graphics_allows(x,g,6,cap);assert first;g+=6
|
||||
second=cpu_allows(x,3,cap);assert second;x+=3
|
||||
sequential={'cap_units':cap,'graphics_request_units':6,'cpu_request_units':3,'graphics_allowed':first,'cpu_allowed':second,'combined_units':x+g,'combined_cap_exceeded':x+g>cap}
|
||||
assert not graphics_allows(3,0,6,cap) # Reverse-order control sees CPU bytes.
|
||||
x=4;g=0;snapshot=x
|
||||
assert cpu_allows(x,4,cap);x+=4
|
||||
assert graphics_allows(snapshot,g,4,cap);g+=4
|
||||
interleaving={'initial_xmem_units':4,'graphics_snapshot_units':snapshot,'intervening_xmem_commit_units':4,'graphics_commit_units':4,'final_combined_units':x+g,'cap_units':cap,'combined_cap_exceeded':x+g>cap}
|
||||
result={'scope':'source-derived logical counterexample only; no host memory allocation, shim invocation or production modification','source_revision':'c13f9c76650edded41774528b50f40798244a6f3','source_sha256':{f:hashlib.sha256((a.source_root/f).read_bytes()).hexdigest() for f in paths},'assumptions':['stable common configured cap','underlying host allocations succeed','distinct live CPU and D3D12 allocations, not aliases or double counting'],'sequential':sequential,'reverse_order_control_rejects':True,'snapshot_interleaving':interleaving,'conclusion':'One-way visibility violates combined admission even sequentially; separate locks also permit a stale cross-DLL snapshot. Real shim/backend reproduction remains unrun.'}
|
||||
a.output.write_text(json.dumps(result,indent=2)+'\n');print(json.dumps(result,indent=2))
|
||||
|
||||
|
||||
if __name__=='__main__':main()
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""CPU-only real Python child-process tests of B's run_case finalization; no Wine/GPU."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
|
||||
def main():
|
||||
ap=argparse.ArgumentParser(description=__doc__);ap.add_argument('b_worktree',type=Path);ap.add_argument('--output',type=Path,required=True);a=ap.parse_args();a.output.mkdir(exist_ok=False)
|
||||
child=a.output/'child.py';child.write_text("import os,sys\nprint('CHILD_PID='+str(os.getpid()),flush=True)\nprint('BACKEND_READY',flush=True)\nline=sys.stdin.buffer.read(1)\nif not line:sys.stderr.write('END failure: backend receipt handshake\\r\\n');sys.stderr.flush()\nelse:print('END complete',flush=True)\n")
|
||||
parent=a.output/'parent.py';parent.write_text("import subprocess,sys\np=subprocess.Popen([sys.executable,sys.argv[1]],stdin=sys.stdin,stdout=sys.stdout,stderr=sys.stderr,start_new_session=True)\nsys.exit(p.wait())\n")
|
||||
old=a.output/'source/docs/research/d3dmetal-zero-copy/copy-detection/run.py';old.parent.mkdir(parents=True);old.write_bytes(subprocess.check_output(['git','-C',str(a.b_worktree),'show','a40228747470f0d184375e451b0173769c90aef5:docs/research/d3dmetal-zero-copy/copy-detection/run.py']))
|
||||
new=a.b_worktree/'docs/research/d3dmetal-zero-copy/copy-detection/run.py'
|
||||
results=[]
|
||||
for tag,path,allow,wait_rc in [('old-stop',old,False,0),('new-stop',new,False,0),('new-normal',new,True,0),('new-wait-timeout',new,True,124)]:
|
||||
spec=importlib.util.spec_from_file_location(tag,path);m=importlib.util.module_from_spec(spec);spec.loader.exec_module(m)
|
||||
case=a.output/tag
|
||||
def backend(*_):
|
||||
content=(case/'stdout.txt').read_text();pid=content.split('CHILD_PID=')[1].splitlines()[0]
|
||||
return {'verified':True,'guest_pid':pid,'scope':'actual Python fixture PID; synthetic backend identification, no graphics'}
|
||||
m.backend=backend;m.pressure=lambda *_:{'allowed':allow,'scope':'injected process-test condition; not a bypassed GPU pressure guard'}
|
||||
calls=[]
|
||||
def capture(cmd,*_,**__):
|
||||
argv=list(map(str,cmd));rc=wait_rc if '-w' in argv else 0;calls.append({'command':argv,'exit':rc});return {'command':argv,'exit':rc,'stdout':'','stderr':''}
|
||||
m.capture=capture
|
||||
if tag!='old-stop':
|
||||
m.after_guest=lambda directory,result:(directory/'wrapper-final.txt').write_text('completed before sealing\n')
|
||||
private=a.output/(tag+'-private');private.mkdir()
|
||||
env={k:os.environ[k] for k in ['PATH','HOME','USER','LANG'] if k in os.environ}
|
||||
command=[sys.executable,str(parent),str(child)]
|
||||
kwargs={} if tag=='old-stop' else {'private':private}
|
||||
# has_gpu enables the marker/identity orchestration only; command is Python, never Wine/D3D12.
|
||||
result=m.run_case(command,parent,'copy',True,case,env,1,**kwargs)
|
||||
deadline=time.monotonic()+2
|
||||
if tag=='old-stop':
|
||||
while time.monotonic()<deadline and not (case/'stderr.txt').read_bytes():time.sleep(.01)
|
||||
actual=hashlib.sha256((case/'stderr.txt').read_bytes()).hexdigest();same=actual==result['output_hashes']['stderr.txt']
|
||||
if tag=='old-stop':assert not same,'old late-write race was not reproduced'
|
||||
else:assert same,'corrected subprocess output changed after sealing'
|
||||
if tag=='new-normal':assert result['exit']==0 and 'error' not in result
|
||||
if tag=='new-wait-timeout':assert result['exit']==0 and 'error' not in result and any(c['exit']==124 for c in calls)
|
||||
results.append({'case':tag,'exit':result['exit'],'error':result.get('error'),'stderr_recorded_sha256':result['output_hashes']['stderr.txt'],'stderr_actual_sha256':actual,'hash_matches':same,'simulated_wineserver_calls':calls,'normal_cleanup_failure_not_propagated':tag=='new-wait-timeout','fixture_only_no_wine_gpu':True})
|
||||
record={'scope':'real controlled Python subprocesses; Wine cleanup is simulated; not a GPU or real wineserver reproduction','b_revision':'4ba4926d2f491517c01b1e94fb8539184055dc22','old_source_sha256':hashlib.sha256(old.read_bytes()).hexdigest(),'new_source_sha256':hashlib.sha256(new.read_bytes()).hexdigest(),'results':results,'remaining_issue':'normal wineserver -w result is discarded; error cleanup return codes are retained but not enforced. Forced cleanup failure cannot certify output finality.'}
|
||||
(a.output/'receipt.json').write_text(json.dumps(record,indent=2)+'\n');print(json.dumps(record,indent=2))
|
||||
|
||||
|
||||
if __name__=='__main__':main()
|
||||
+119
@@ -0,0 +1,119 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""CPU-only exact B extractor replay and separate XML/join/statistics verification."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import statistics
|
||||
import subprocess
|
||||
import sys
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
|
||||
def check(ok, detail):
|
||||
if not ok:
|
||||
raise ValueError(detail)
|
||||
|
||||
|
||||
def digest(p):
|
||||
return hashlib.sha256(p.read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def decode(path, expected_pid):
|
||||
tree = ET.parse(path).getroot()
|
||||
lookup = {}
|
||||
for node in tree.iter():
|
||||
if 'id' in node.attrib:
|
||||
key = node.attrib['id']
|
||||
if key in lookup:
|
||||
check(ET.tostring(lookup[key]) == ET.tostring(node), 'conflicting XML id')
|
||||
lookup[key] = node
|
||||
resolved = 0
|
||||
|
||||
def deref(node, trail=()):
|
||||
nonlocal resolved
|
||||
if 'ref' not in node.attrib:
|
||||
return node
|
||||
ref = node.attrib['ref']
|
||||
check(ref not in trail and ref in lookup, 'missing/cyclic XML reference')
|
||||
resolved += 1
|
||||
return deref(lookup[ref], trail + (ref,))
|
||||
|
||||
schema = tree.find('.//schema')
|
||||
names = [col.findtext('mnemonic') for col in schema.findall('col')]
|
||||
rows = []
|
||||
duration_formats = 0
|
||||
for row in tree.findall('.//row'):
|
||||
check(len(row) == len(names), 'XML column count')
|
||||
cells = {name: deref(node) for name, node in zip(names, row)}
|
||||
pid = int(deref(cells['process'].find('pid')).text)
|
||||
check(pid == expected_pid, 'unexpected process in sanitized input')
|
||||
values = {name: node.text or node.get('fmt') for name, node in cells.items()}
|
||||
# Independently confirm the nanosecond scale against XML human-readable units.
|
||||
node = cells['duration'];match = re.fullmatch(r'([\d.]+)\s*(ns|[µμu]s|ms|s)', node.get('fmt', ''))
|
||||
if match:
|
||||
factors = {'ns': 1, 'us': 1000, 'µs': 1000, 'μs': 1000, 'ms': 1000000, 's': 1000000000}
|
||||
factor = factors[match[2]];places = len(match[1].split('.')[1]) if '.' in match[1] else 0
|
||||
check(abs(int(node.text) - float(match[1]) * factor) <= 0.51 * factor * 10**(-places), 'duration unit/format mismatch')
|
||||
duration_formats += 1
|
||||
rows.append(values)
|
||||
return rows, resolved, duration_formats
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description=__doc__)
|
||||
ap.add_argument('b_worktree', type=Path);ap.add_argument('--output', required=True, type=Path)
|
||||
args = ap.parse_args();args.output.mkdir(parents=True, exist_ok=False)
|
||||
root = args.b_worktree / 'docs/research/d3dmetal-zero-copy'
|
||||
inputs = root / 'results/2026-11-27-apple-m5-atesahmet0-b-trace-inputs-01'
|
||||
manifest = json.loads((inputs / 'receipt.json').read_text())
|
||||
parser = root / 'copy-detection/summarize-trace.py'
|
||||
check(digest(parser) == manifest['tools']['docs/research/d3dmetal-zero-copy/copy-detection/summarize-trace.py'], 'extractor source digest')
|
||||
report = {'scope': 'CPU-only same-source extraction replay plus independent XML/data audit, no GPU capture or execution', 'b_revision': '4ba4926d2f491517c01b1e94fb8539184055dc22', 'extractor_sha256': digest(parser), 'captures': []}
|
||||
for capture in manifest['captures']:
|
||||
short = capture['short_name'];run = root / 'results' / capture['published_run_dir']
|
||||
rec = json.loads((run / 'receipt.json').read_text());case, = rec['cases'];outcome = case['run']
|
||||
pid = int(outcome['backend']['guest_pid']);check(pid == capture['guest_pid'] and outcome['exit'] == 0 and outcome['backend']['verified'], 'receipt process identity')
|
||||
files = [inputs / short / capture[k]['sanitized_xml'] for k in ['gpu_intervals', 'encoders']]
|
||||
for path, key in zip(files, ['gpu_intervals', 'encoders']):
|
||||
check(digest(path) == capture[key]['sanitized_xml_sha256'], 'sanitized input hash')
|
||||
cmd = [sys.executable, str(parser), str(run), *map(str, files)]
|
||||
result = subprocess.run(cmd, capture_output=True, text=True, timeout=15)
|
||||
(args.output / (short + '.stdout.json')).write_text(result.stdout)
|
||||
(args.output / (short + '.stderr.txt')).write_text(result.stderr)
|
||||
check(result.returncode == 0, result.stderr)
|
||||
actual = json.loads(result.stdout);published = json.loads((run / 'gpu-samples.json').read_text())
|
||||
check(actual == published, 'full extraction JSON differs')
|
||||
gpu, gpu_refs, gpu_units = decode(files[0], pid);encoders, enc_refs, enc_units = decode(files[1], pid)
|
||||
check(len(gpu) == capture['gpu_intervals']['retained_target_rows'] and len(encoders) == capture['encoders']['retained_target_rows'], 'retained row count')
|
||||
is_shader = 'COMPUTE ' in (run / case['directory'] / 'stdout.txt').read_text()
|
||||
prefix = 'Compute Command ' if is_shader else 'Blit Command '
|
||||
key = lambda r: (int(r['cmdbuffer-id']), int(r['encoder-id']))
|
||||
selected = [r for r in encoders if r['event-type'] == 'Encoding' and r['encoder-label'].startswith(prefix)]
|
||||
selected.sort(key=lambda r: int(r['start']));ids = [key(r) for r in selected]
|
||||
check(len(set(ids)) == len(ids), 'duplicate encoder pair')
|
||||
active = {key(r): r for r in gpu if r['state'] == 'Active' and key(r) in set(ids)}
|
||||
check(len(active) == len(ids) == len(actual['samples']), 'independent join count')
|
||||
check(ids == [key(r) for r in sorted(active.values(), key=lambda r: int(r['start']))], 'GPU/encoder chronological order')
|
||||
for item, row in zip(actual['samples'], selected):
|
||||
interval = active[key(row)]
|
||||
check(tuple(item['ids']) == key(row) and item['encoder_label'] == row['encoder-label'], 'sample identity')
|
||||
check(item['gpu_start_ns'] == int(interval['start']) and item['gpu_duration_ns'] == int(interval['duration']) > 0 and item['metal_encode_ns'] == int(row['duration']), 'sample timing')
|
||||
check(item['read_bytes'] in [0, 1024, 4096, 4194304] and item['written_bytes'] in [0, 1024, 4096, 262144, 4194304], 'shader denominator')
|
||||
if not is_shader:check(item['workload_payload'] == 67108864, 'copy denominator')
|
||||
for mode, stats in actual['distributions'].items():
|
||||
measured = [v for v in actual['samples'] if v['mode'] == mode and v['iter'] >= 0]
|
||||
check(len(measured) == stats['n'] == 12, 'measured sample count')
|
||||
times = [v['gpu_duration_ns'] / 1000 for v in measured];mid = statistics.median(times)
|
||||
check(mid == stats['median_gpu_us'] and min(times) == stats['minimum_gpu_us'] and max(times) == stats['maximum_gpu_us'], 'median/min/max')
|
||||
check(statistics.median(abs(t-mid) for t in times) == stats['mad_gpu_us'], 'MAD')
|
||||
for field, value in stats['payload_GB_s'].items():check(statistics.median(v[field] / v['gpu_duration_ns'] for v in measured) == value, 'payload rate')
|
||||
report['captures'].append({'name': short, 'pid': pid, 'command': cmd, 'exit': result.returncode, 'exact_json_match': True, 'input_sha256': [digest(p) for p in files], 'published_output_sha256': digest(run / 'gpu-samples.json'), 'selected_intervals': len(ids), 'excluded_encoder_rows': len(encoders)-len(selected), 'resolved_references': gpu_refs+enc_refs, 'duration_format_checks': gpu_units+enc_units, 'outliers_and_warmups_preserved': True})
|
||||
check(sum(c['selected_intervals'] for c in report['captures']) == 345, 'total interval count')
|
||||
(args.output / 'receipt.json').write_text(json.dumps(report, indent=2)+'\n')
|
||||
print(json.dumps(report, indent=2))
|
||||
|
||||
|
||||
if __name__ == '__main__':main()
|
||||
@@ -0,0 +1,56 @@
|
||||
# Physical-footprint observations and limits
|
||||
|
||||
The historical data inventory and corrected A2 data below are author observations on one Apple M4 with 24 GiB, macOS 27.0 (26A428), CrossOver 26.3.0.39832 and loaded D3DMetal 3.0. They are not independent acceptance. The original six baseline experiments remain unchanged.
|
||||
|
||||
## Existing data and correction
|
||||
|
||||
The historical 18-case profile has two fresh-process repeats at 64/256/1024 MiB for graphics-warmed CPU allocation, CUSTOM/WB/L0 and UPLOAD. Its baseline is about 340–341 MiB, dropping about 40 MiB by the next checkpoint. It fully writes the source and runs a checksum shader across all source words. However, it leaves command/pipeline/output objects live at its release checkpoint. It does not establish retention after their disposal. Exact historical sources/receipts and the earlier timeout are preserved in the [inventory](inventory/README.md).
|
||||
|
||||
The A2 correction disposes warm-up command objects before its settled baseline and separates resource release, command/pipeline/output disposal, a 500 ms settled interval and device release. It adds CPU-only processes without any D3D12 device, alongside matched graphics-warmed CPU allocation controls. Loaded-library evidence is collected separately at a paused stage, and exact-pointer vmmap is added.
|
||||
|
||||
The [first A2 profile](../results/2026-11-26-apple-m4-arths17-a2-memory-partial/receipt.json) completed 12 cases: four types at three sizes. The second session was interrupted after the host reported kernel pressure level 2; it is incomplete, not a pass. Operator stop, raw logs, shader bytes/hashes, failed/missing diagnostic and exact executed source snapshots are preserved. Later checking identified the actual Wine engine as `wine-11.0-8726-g2e2f5fca349`; the original runner's nonexistent `wine64 --version` lookup failed with exit 127, so its CrossOver version was known but its engine-version field was missing. Do not rewrite that receipt as a success.
|
||||
|
||||
## First-session accounting
|
||||
|
||||
MiB are 2^20 bytes. Each number below is the median of three correlated proc_pid_rusage readings at one paused checkpoint, not three independent sessions. Deltas are from that process's settled baseline. Values are rounded only in this table; raw bytes remain in the logs.
|
||||
|
||||
| Type | Requested MiB | Baseline MiB | After full initialization delta MiB | After full GPU consumption delta MiB | After settled complete retirement delta MiB |
|
||||
| --- | ---: | ---: | ---: | ---: | ---: |
|
||||
| CPU-only | 64 | 13.26 | 64.16 | 64.17 (GPU not run) | 0.03 |
|
||||
| CPU with graphics warmed | 64 | 300.78 | 64.71 | 64.71 (GPU not run) | 0.57 |
|
||||
| CUSTOM WB/L0 | 64 | 300.62 | 0.09 | 40.50 | 0.19 |
|
||||
| UPLOAD | 64 | 300.21 | 0.09 | 40.54 | 0.22 |
|
||||
| CPU-only | 256 | 13.15 | 256.59 | 256.59 (GPU not run) | 0.07 |
|
||||
| CPU with graphics warmed | 256 | 300.46 | 256.54 | 257.18 (GPU not run) | 0.78 |
|
||||
| CUSTOM WB/L0 | 256 | 300.38 | 256.58 | 297.04 | 256.74 |
|
||||
| UPLOAD | 256 | 301.12 | 256.52 | 296.86 | 256.54 |
|
||||
| CPU-only | 1024 | 13.19 | 1026.28 | 1026.28 (GPU not run) | 0.26 |
|
||||
| CPU with graphics warmed | 1024 | 300.17 | 1026.73 | 1026.73 (GPU not run) | 0.90 |
|
||||
| CUSTOM WB/L0 | 1024 | 301.36 | 1026.51 | 1066.96 | 1026.66 |
|
||||
| UPLOAD | 1024 | 301.04 | 1025.98 | 1066.34 | 1026.04 |
|
||||
|
||||
The CPU control releases its large charge; larger graphics allocations remain mostly process-accounted at complete retirement and device release. This is stronger retirement scoping than the historical resource-release checkpoint, but still does not isolate runtime/driver caching or prove a leak. The device-release checkpoint leaves the process and loaded DLL/framework alive.
|
||||
|
||||
The 64 MiB graphics allocations add little charge at creation/initialization. Their mapped pointers lie in a 256 MiB IOAccelerator virtual region in this run. Larger allocations have separate pointer-specific regions. This supports an existing-pool explanation, rather than a linear assumption that every allocation creates a new equally sized physical charge. It does not prove which physical pages back the data.
|
||||
|
||||
## Accounting is not residency or page identity
|
||||
|
||||
The same first-session 1 GiB WB case reports approximately 1368 MiB physical-footprint accounting at GPU completion, but only 448 MiB resident size. The graphics-warmed CPU control has about 1327 MiB footprint accounting and 53 MiB RSS at that checkpoint. System compression/swap and the sequential sampling windows confound physical-residency interpretation. A near-1x size slope is an accounting observation, not proof of unique physical allocation, no duplication, or absence of copies elsewhere.
|
||||
|
||||
The exact mapped CPU pointers also refute an unqualified alignment assumption: the 64 MiB WB/UPLOAD pointers were 16384 modulo 65536, and the 256/1024 MiB WB/UPLOAD pointers were 49152 modulo 65536. Heap/resource placement alignment is not CPU-pointer alignment. See the [ownership matrix](inverted-ownership.md).
|
||||
|
||||
`footprint`, `vmmap`, native accounting and system-pressure tools measure different categories at different times. Virtual address ranges, resident pages, process ledger charges and driver-retained memory must not be summed or relabeled as physical page identity. Profiler permissions/timeouts and missing tools remain explicit outcomes.
|
||||
|
||||
## Pressure correction and remaining evidence
|
||||
|
||||
The initial guard used memory_pressure -Q free percentage only. The kernel subsequently reported pressure level 2 even with 51% reported free. Apple's [XNU documentation](https://github.com/apple-oss-distributions/xnu/blob/main/doc/vm/memorystatus_notify.md) calls level 2 urgent/warning-equivalent. This host's pressure state during earlier stages was not recorded by that stronger signal, so it is unknown. Existing swap and substantial background CPU load were recorded and limit interpretation.
|
||||
|
||||
A-local-2.1 adds kernel-level receipts and requires normal pressure at case and stage boundaries, with retained free-percentage guards. Fresh normal-pressure sessions and reciprocal review are required before treating the profile as reproducibly settled. The partial A2 results remain valid records of the workload under their stated conditions, not a completed repeated profile or a controlled benchmark.
|
||||
|
||||
Physical page identity remains unestablished. No result here certifies physical zero-copy, console coherence or #464. Independent review must inspect pinned source, exact shader/PE identities, full raw snapshots, failure paths and controls rather than accepting this interpretation.
|
||||
|
||||
## Bounded continuation and remaining repeats
|
||||
|
||||
After the requester freed memory and allowed bounded warning-pressure work under a 23 GB ceiling, [A-local-2.2 continuation](../results/2026-11-26-apple-m4-arths17-a22-memory-pressure-stop/receipt.json) completed six processes: all four 64 MiB controls/types and both CPU 256 MiB controls. The next WB 256 MiB process was killed at a paused checkpoint when kernel pressure returned to 2. Its exit -9 and harness stop reason are preserved, not a completed GPU result. The private Wine server was stopped and the source bottle configuration remained unchanged. No additional 1 GiB source was started in this continuation.
|
||||
|
||||
The maximum recorded conservative non-file-cache occupied estimate in completed snapshots was 21,187,198,976 bytes, below the 23,000,000,000-byte ceiling; this is a sampled metric, not a guarantee about unobserved intervals or an exact Activity Monitor value. The urgent-pressure guard stopped the profile independently of that ceiling. Both profiles remain explicitly partial. Further repeated large/normal-pressure characterization remains open rather than forcing execution under urgent pressure.
|
||||
@@ -0,0 +1,15 @@
|
||||
# Logical fragmentation and delayed-retirement model
|
||||
|
||||
This small native ARM64 experiment fills a gap in the original 32 MiB pooled GPU trace, which did not saturate the pool. It models bounded spans and fence-delayed eligibility, without allocating a 32 MiB backing buffer or using a GPU. Logical fragmentation is not driver fragmentation or physical memory usage.
|
||||
|
||||
```sh
|
||||
python3 docs/research/d3dmetal-zero-copy/allocation-profiling/fragmentation/run.py --scratch /tmp/bx473-fragmentation-review
|
||||
```
|
||||
|
||||
The original C++ trace maintains its free-list; a separate Python oracle derives free gaps from the union of live and pending allocations. It validates bounds, alignment, overlap, failed-allocation feasibility, payload/reservation waste, total/largest usable free spans and delayed retirement at every snapshot. It does not import or reuse the C++ allocation algorithm. Both implementations are still author work and require independent contributor review.
|
||||
|
||||
The fixed negative case fills eight 4 MiB slots, retires alternating slots and leaves 16 MiB free in four 4 MiB gaps. An 8 MiB request fails. Marking the remaining slots free but leaving their retirement fence incomplete still cannot satisfy it; only completing that fence coalesces a full 32 MiB range and permits the request. Three seeded traces then exercise 2000 operations apiece, varied 4 KiB-to-3 MiB requested sizes, 64 KiB/2 MiB logical alignment and varied retirement delays. These alignments are chosen allocator-policy inputs, not host pointer/page guarantees.
|
||||
|
||||
[Raw traces and separate oracle outputs](../../results/2026-11-26-apple-m4-arths17-logical-fragmentation/receipt.json) record seeds 473/474/475, each with 2004 checked statistics snapshots (6012 total). Failed logical allocation requests were 180, 93 and 142 respectively; they are expected capacity/fragmentation outcomes, not test failures or physical out-of-memory events. Every trace coalesced to the full empty slab. A [separate control run](../../results/2026-11-26-apple-m4-arths17-logical-oracle-control/receipt.json) changed one statistic in a copy of the log; the oracle rejected it. Original logs remain unchanged.
|
||||
|
||||
This verifies the recorded logical traces, not universal allocator correctness, actual GPU fence implementation, driver pooling, physical memory efficiency or Xbox behavior. The existing GPU trace remains the separate evidence for guard readback and a real delayed queued copy.
|
||||
@@ -0,0 +1,87 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Independent interval-union validation; does not use the C++ free-list implementation."""
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def verify(path):
|
||||
live, pending = {}, {}
|
||||
capacity = None
|
||||
checked = 0
|
||||
failed_requests = 0
|
||||
completion = 0
|
||||
labels = {}
|
||||
def holes():
|
||||
ranges = sorted((r['offset'], r['offset'] + r['size']) for r in [*live.values(), *pending.values()])
|
||||
result = []
|
||||
end = 0
|
||||
for start, stop in ranges:
|
||||
assert start >= end and stop <= capacity, 'overlap or bounds'
|
||||
if start > end:
|
||||
result.append((end, start))
|
||||
end = stop
|
||||
if end < capacity:
|
||||
result.append((end, capacity))
|
||||
return result
|
||||
for line in path.read_text().splitlines():
|
||||
row = json.loads(line)
|
||||
op = row['op']
|
||||
if op == 'begin':
|
||||
assert capacity is None
|
||||
capacity = row['capacity']
|
||||
elif op in ['allocate', 'failed_allocate']:
|
||||
assert row['size'] == ((row['payload'] + 65535)//65536)*65536
|
||||
if op == 'failed_allocate':
|
||||
failed_requests += 1
|
||||
assert not any(((start+row['alignment']-1)//row['alignment'])*row['alignment']+row['size'] <= end for start,end in holes()), 'false exhaustion'
|
||||
else:
|
||||
assert row['id'] not in live and row['id'] not in pending
|
||||
assert row['offset'] % row['alignment'] == 0
|
||||
assert any(start <= row['offset'] and row['offset']+row['size'] <= end for start,end in holes())
|
||||
live[row['id']] = row
|
||||
elif op == 'request_free':
|
||||
assert row['id'] in live
|
||||
pending[row['id']] = dict(live.pop(row['id']), fence=row['fence'])
|
||||
elif op == 'signal':
|
||||
assert row['completed'] >= completion
|
||||
completion = row['completed']
|
||||
pending = {k:v for k,v in pending.items() if v['fence'] > completion}
|
||||
elif op == 'stats':
|
||||
gaps = holes()
|
||||
payload = sum(v['payload'] for v in live.values())
|
||||
reserved = sum(v['size'] for v in live.values())
|
||||
held = sum(v['size'] for v in pending.values())
|
||||
free = sum(end-start for start,end in gaps)
|
||||
largest = max((end-start for start,end in gaps),default=0)
|
||||
usable = max((max(0,end-((start+2097151)//2097152)*2097152) for start,end in gaps),default=0)
|
||||
expected = dict(capacity=capacity,live_payload=payload,live_reserved=reserved,pending_reserved=held,
|
||||
internal_waste=reserved-payload,total_free=free,largest_free=largest,
|
||||
largest_2MiB_aligned_span=usable,free_spans=len(gaps))
|
||||
for k,v in expected.items():
|
||||
assert row[k] == v, (k,row[k],v)
|
||||
assert reserved + held + free == capacity
|
||||
if row['label'] != 'varied_trace':
|
||||
labels[row['label']] = row
|
||||
checked += 1
|
||||
elif op == 'end':
|
||||
assert row['success'] and not live and not pending
|
||||
assert holes() == [(0,capacity)]
|
||||
else:
|
||||
raise AssertionError('unexpected record '+op)
|
||||
assert checked == 2004
|
||||
assert labels['alternating_holes']['total_free'] == capacity//2
|
||||
assert labels['alternating_holes']['largest_free'] == 4*1024**2
|
||||
assert labels['pending_blocks_reuse']['pending_reserved'] == capacity//2
|
||||
assert labels['fully_coalesced']['total_free'] == capacity
|
||||
assert labels['final_empty']['total_free'] == capacity
|
||||
return dict(file=path.name,stats_checked=checked,failed_allocation_requests=failed_requests,labels=labels,
|
||||
scope='logical interval model; not GPU, physical allocation or independent contributor acceptance')
|
||||
|
||||
|
||||
def main():
|
||||
ap=argparse.ArgumentParser(description=__doc__);ap.add_argument('stdout',type=Path);ap.add_argument('--output',required=True,type=Path);args=ap.parse_args()
|
||||
result=verify(args.stdout);args.output.write_text(json.dumps(result,indent=2)+'\n');print('verified',result['stats_checked'],'logical snapshots')
|
||||
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,53 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Run bounded logical allocation traces and a separate interval oracle; no GPU work."""
|
||||
import argparse
|
||||
from datetime import datetime, timezone
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
|
||||
def main():
|
||||
ap=argparse.ArgumentParser(description=__doc__);ap.add_argument('--scratch',required=True,type=Path);ap.add_argument('--seeds',default='473,474,475');args=ap.parse_args()
|
||||
src=Path(__file__).resolve().parent;out=args.scratch.expanduser().resolve()
|
||||
if out.exists():ap.error('scratch must be new')
|
||||
if src==out or src in out.parents:ap.error('scratch cannot be inside source directory')
|
||||
seeds=[int(x) for x in args.seeds.split(',')]
|
||||
if not seeds or len(seeds)>3:ap.error('one to three bounded traces')
|
||||
out.mkdir(parents=True);(out/'source').mkdir();exe=out/'trace'
|
||||
receipt=dict(protocol='A-logical-fragmentation-1',utc=datetime.now(timezone.utc).isoformat(),scope='logical spans only; no 32 MiB physical allocation, no GPU/driver-fragmentation claim',source_hashes={},tools=[],cases=[])
|
||||
for p in src.iterdir():
|
||||
if p.is_file() and p.suffix in ['.cpp','.py']:
|
||||
receipt['source_hashes'][p.name]=hashlib.sha256(p.read_bytes()).hexdigest();shutil.copy2(p,out/'source'/p.name)
|
||||
def capture(cmd,timeout=20):
|
||||
p=subprocess.run([str(x) for x in cmd],capture_output=True,timeout=timeout)
|
||||
return dict(command=[str(x) for x in cmd],exit=p.returncode,stdout=p.stdout.decode(errors='replace'),stderr=p.stderr.decode(errors='replace'))
|
||||
try:
|
||||
build=capture(['xcrun','clang++','-std=c++20','-O2','-arch','arm64','-Wall','-Wextra','-Werror',src/'trace.cpp','-o',exe],60);receipt['build']=build
|
||||
if build['exit']:raise RuntimeError('build failed')
|
||||
receipt['executable_sha256']=hashlib.sha256(exe.read_bytes()).hexdigest()
|
||||
for cmd in [['file',exe],['lipo','-archs',exe],['otool','-L',exe],['xcrun','clang++','--version'],['sw_vers'],['sysctl','-n','kern.memorystatus_vm_pressure_level']]:receipt['tools'].append(capture(cmd))
|
||||
for seed in seeds:
|
||||
cmd=[str(exe),str(seed)];p=subprocess.run(cmd,capture_output=True,timeout=15)
|
||||
stdout=out/f'seed-{seed}-stdout.jsonl';stderr=out/f'seed-{seed}-stderr.txt';stdout.write_bytes(p.stdout);stderr.write_bytes(p.stderr)
|
||||
oracle=capture(['python3',src/'oracle.py',stdout,'--output',out/f'seed-{seed}-oracle.json'])
|
||||
receipt['cases'].append(dict(seed=seed,command=cmd,exit=p.returncode,oracle=oracle))
|
||||
if p.returncode or oracle['exit']:raise RuntimeError('trace/oracle failure')
|
||||
# An intentionally corrupted COPY is a negative control for the independent oracle.
|
||||
bad=out/'corrupted-control.jsonl';rows=(out/f'seed-{seeds[0]}-stdout.jsonl').read_text().splitlines()
|
||||
for i,line in enumerate(rows):
|
||||
row=json.loads(line)
|
||||
if row['op']=='stats':
|
||||
row['largest_free']+=65536;rows[i]=json.dumps(row);break
|
||||
bad.write_text('\n'.join(rows)+'\n')
|
||||
control=capture(['python3',src/'oracle.py',bad,'--output',out/'should-not-exist.json']);receipt['corrupted_log_control']=control
|
||||
if control['exit']==0 or 'AssertionError' not in control['stderr']:raise RuntimeError('oracle did not reject corrupted statistic')
|
||||
print('logical traces checked:',len(seeds),'; corrupted-statistic control rejected')
|
||||
finally:
|
||||
receipt['output_hashes']={p.name:hashlib.sha256(p.read_bytes()).hexdigest() for p in out.iterdir() if p.is_file() and p!=exe}
|
||||
(out/'receipt.json').write_text(json.dumps(receipt,indent=2)+'\n')
|
||||
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,177 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Original bounded logical span experiment. No graphics API or physical memory
|
||||
// claims.
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <map>
|
||||
#include <random>
|
||||
#include <stdexcept>
|
||||
#include <vector>
|
||||
using U = std::uint64_t;
|
||||
static constexpr U capacity = 32ULL * 1024 * 1024;
|
||||
static U up(U n, U a) { return (n + a - 1) / a * a; }
|
||||
struct Span {
|
||||
U start, size;
|
||||
};
|
||||
struct Item {
|
||||
U start, reserved, payload, retire = 0;
|
||||
};
|
||||
struct Arena {
|
||||
std::vector<Span> free{{0, capacity}};
|
||||
std::map<U, Item> live, pending;
|
||||
U next = 1, completed = 0;
|
||||
U allocate(U bytes, U alignment) {
|
||||
U size = up(bytes, 65536), id = next++;
|
||||
for (std::size_t i = 0; i < free.size(); ++i) {
|
||||
auto old = free[i];
|
||||
U offset = up(old.start, alignment);
|
||||
if (offset < old.start || offset - old.start > old.size ||
|
||||
size > old.size - (offset - old.start))
|
||||
continue;
|
||||
free.erase(free.begin() + i);
|
||||
if (offset > old.start)
|
||||
free.push_back({old.start, offset - old.start});
|
||||
if (offset + size < old.start + old.size)
|
||||
free.push_back({offset + size, old.start + old.size - offset - size});
|
||||
live[id] = {offset, size, bytes, 0};
|
||||
std::printf("{\"op\":\"allocate\",\"id\":%llu,\"payload\":%llu,\"size\":%"
|
||||
"llu,\"alignment\":%llu,\"offset\":%llu}\n",
|
||||
(unsigned long long)id, (unsigned long long)bytes,
|
||||
(unsigned long long)size, (unsigned long long)alignment,
|
||||
(unsigned long long)offset);
|
||||
return id;
|
||||
}
|
||||
std::printf("{\"op\":\"failed_allocate\",\"id\":%llu,\"payload\":%llu,"
|
||||
"\"size\":%llu,\"alignment\":%llu}\n",
|
||||
(unsigned long long)id, (unsigned long long)bytes,
|
||||
(unsigned long long)size, (unsigned long long)alignment);
|
||||
return 0;
|
||||
}
|
||||
void give(U offset, U size) {
|
||||
free.push_back({offset, size});
|
||||
std::sort(free.begin(), free.end(),
|
||||
[](auto a, auto b) { return a.start < b.start; });
|
||||
std::vector<Span> merged;
|
||||
for (auto s : free) {
|
||||
if (!merged.empty() && merged.back().start + merged.back().size > s.start)
|
||||
throw std::runtime_error("overlap");
|
||||
if (!merged.empty() &&
|
||||
merged.back().start + merged.back().size == s.start)
|
||||
merged.back().size += s.size;
|
||||
else
|
||||
merged.push_back(s);
|
||||
}
|
||||
free = merged;
|
||||
}
|
||||
void release(U id, U fence) {
|
||||
auto it = live.find(id);
|
||||
if (it == live.end())
|
||||
throw std::runtime_error("unknown id");
|
||||
auto item = it->second;
|
||||
item.retire = fence;
|
||||
live.erase(it);
|
||||
pending[id] = item;
|
||||
std::printf("{\"op\":\"request_free\",\"id\":%llu,\"fence\":%llu}\n",
|
||||
(unsigned long long)id, (unsigned long long)fence);
|
||||
}
|
||||
void signal(U value) {
|
||||
if (value < completed)
|
||||
throw std::runtime_error("regressive fence");
|
||||
completed = value;
|
||||
for (auto it = pending.begin(); it != pending.end();) {
|
||||
if (it->second.retire <= completed) {
|
||||
give(it->second.start, it->second.reserved);
|
||||
it = pending.erase(it);
|
||||
} else
|
||||
++it;
|
||||
}
|
||||
std::printf("{\"op\":\"signal\",\"completed\":%llu}\n",
|
||||
(unsigned long long)value);
|
||||
}
|
||||
void stats(const char *label) {
|
||||
U payload = 0, reserved = 0, held = 0, total = 0, largest = 0, usable2M = 0;
|
||||
for (auto [id, x] : live) {
|
||||
(void)id;
|
||||
payload += x.payload;
|
||||
reserved += x.reserved;
|
||||
}
|
||||
for (auto [id, x] : pending) {
|
||||
(void)id;
|
||||
held += x.reserved;
|
||||
}
|
||||
for (auto s : free) {
|
||||
total += s.size;
|
||||
largest = std::max(largest, s.size);
|
||||
U start = up(s.start, 2097152);
|
||||
if (start < s.start + s.size)
|
||||
usable2M = std::max(usable2M, s.start + s.size - start);
|
||||
}
|
||||
std::printf(
|
||||
"{\"op\":\"stats\",\"label\":\"%s\",\"capacity\":%llu,\"live_payload\":"
|
||||
"%llu,\"live_reserved\":%llu,\"pending_reserved\":%llu,\"internal_"
|
||||
"waste\":%llu,\"total_free\":%llu,\"largest_free\":%llu,\"largest_2MiB_"
|
||||
"aligned_span\":%llu,\"free_spans\":%zu}\n",
|
||||
label, (unsigned long long)capacity, (unsigned long long)payload,
|
||||
(unsigned long long)reserved, (unsigned long long)held,
|
||||
(unsigned long long)(reserved - payload), (unsigned long long)total,
|
||||
(unsigned long long)largest, (unsigned long long)usable2M, free.size());
|
||||
}
|
||||
};
|
||||
int main(int argc, char **argv) {
|
||||
try {
|
||||
U seed = argc == 2 ? std::strtoull(argv[1], nullptr, 10) : 473;
|
||||
std::printf("{\"op\":\"begin\",\"protocol\":\"A-logical-fragmentation-1\","
|
||||
"\"seed\":%llu,\"capacity\":%llu}\n",
|
||||
(unsigned long long)seed, (unsigned long long)capacity);
|
||||
Arena a;
|
||||
std::vector<U> ids;
|
||||
for (int i = 0; i < 8; ++i)
|
||||
ids.push_back(a.allocate(4 * 1024 * 1024, 65536));
|
||||
for (int i = 0; i < 8; i += 2)
|
||||
a.release(ids[i], 1);
|
||||
a.signal(1);
|
||||
a.stats("alternating_holes");
|
||||
if (a.allocate(8 * 1024 * 1024, 65536))
|
||||
throw std::runtime_error("fragmented request unexpectedly fit");
|
||||
for (int i = 1; i < 8; i += 2)
|
||||
a.release(ids[i], 2);
|
||||
a.stats("pending_blocks_reuse");
|
||||
if (a.allocate(8 * 1024 * 1024, 65536))
|
||||
throw std::runtime_error("pending spans reused");
|
||||
a.signal(2);
|
||||
a.stats("fully_coalesced");
|
||||
U large = a.allocate(8 * 1024 * 1024, 2097152);
|
||||
if (!large)
|
||||
throw std::runtime_error("coalesced allocation failed");
|
||||
a.release(large, 3);
|
||||
a.signal(3);
|
||||
std::mt19937 rng(static_cast<unsigned>(seed));
|
||||
const U sizes[] = {4097, 65535, 65537, 131073, 393220, 1048580, 3145732};
|
||||
for (U step = 4; step < 2004; ++step) {
|
||||
if (!a.live.empty() && (a.live.size() >= 48 || rng() % 100 < 45)) {
|
||||
auto it = a.live.begin();
|
||||
std::advance(it, rng() % a.live.size());
|
||||
a.release(it->first, step + 1 + rng() % 9);
|
||||
} else
|
||||
a.allocate(sizes[rng() % 7], rng() % 4 ? 65536 : 2097152);
|
||||
a.signal(step);
|
||||
a.stats("varied_trace");
|
||||
}
|
||||
ids.clear();
|
||||
for (auto [id, item] : a.live) {
|
||||
(void)item;
|
||||
ids.push_back(id);
|
||||
}
|
||||
for (auto id : ids)
|
||||
a.release(id, 2016);
|
||||
a.signal(2016);
|
||||
a.stats("final_empty");
|
||||
std::puts("{\"op\":\"end\",\"success\":true}");
|
||||
return 0;
|
||||
} catch (const std::exception &e) {
|
||||
std::fprintf(stderr, "failure: %s\n", e.what());
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
# Evidence handoff for placed-resource integration
|
||||
|
||||
This narrow handoff informs [#464](https://github.com/MacosPorters/betterxen/issues/464) and [PR #486](https://github.com/MacosPorters/betterxen/pull/486) without changing or certifying production code. The PR's `vmem.h` and `vmem.cpp` were read at `6308fdc0462d14f1f0b732e21dbc45329fb034c9`; this is boundary inspection, not a full independent implementation review. Its reported CrossOver 26.2/vkd3d runs are not the CrossOver 26.3/D3DMetal 3.0 environment used here.
|
||||
|
||||
| Integration question | Evidence-supported handoff |
|
||||
| --- | --- |
|
||||
| Can caller-owned xmem memory be wrapped? | Both existing-memory heap opens returned E_NOTIMPL in published version-scoped baseline observations. Keep this explicit; no bridge has been demonstrated. |
|
||||
| What does mapped ownership provide? | A D3D12-owned WB/L0 buffer exposes a persistent CPU pointer and supports observed synchronized buffer access/alias inheritance. This is a candidate allocation provider, not evidence that arbitrary fixed/pre-device/scatter mappings are satisfied. |
|
||||
| Can heap alignment be used as CPU alignment? | No. A2 mapped-pointer receipts include 16384 and 49152 modulo 65536 despite 64 KiB heap/resource alignment. Validate the actual requested CPU contract separately. |
|
||||
| Does the configured block preserve an old address? | The inspected PR publishes a newly mapped cpu_pointer. That is not proof of an alias at existing base_va or preservation of its previous allocation contents/attributes. Distinguish the BetterXen-defined synthetic configuration from a verified console ABI. |
|
||||
| May successful creation validate placement? | The M4 runtime accepted misaligned/out-of-bounds creation calls that were never GPU-used. Validate allocation-info alignment and bounds before forwarding. The PR's create_placed has explicit checks; no claim is made that this audit independently certifies all edge cases. |
|
||||
| What do texture results cover? | Correct mixed-heap mip copies and RT/depth clear/alias readbacks in the tested configurations. Opaque texture layout, raw guest-pointer aliasing, sampling, console tiling and other formats remain separate. |
|
||||
| What is released from the budget? | Logical heap/slice accounting and observed host/driver retention are separate quantities. Resource, command and device release checkpoints can retain graphics charges. Avoid calling that a proven leak or immediate physical reclamation. |
|
||||
| Does pooling justify adoption? | It reduces the allocation-call component in this synthetic trace, with cold setup/slack costs and small/noisy cycle differences. It is not a demonstrated production speedup or memory reduction. |
|
||||
| What may be claimed about copies? | Synchronized access, same-address alias behavior, footprint slopes and region labels do not establish physical page identity or universal absence of copies. The inspected PR's stronger “true shared”/“no extra copy” language is not established by #473. |
|
||||
|
||||
The maintainer's #464 claim remains respected. No forced ADR/ABI sequence, new dependency/blocking gate, production patch or approval of PR #486 is implied. Scoped independent acceptance is recorded per finding in the [evidence register](consolidation-draft/evidence-register.md); unlisted scopes are not accepted. The underlying research is limited to original synthetic workloads on stated versions, with no Xbox hardware or game-execution claim.
|
||||
|
||||
## Update after reciprocal review
|
||||
|
||||
PR #486 was re-inspected at `c13f9c76650edded41774528b50f40798244a6f3` (vmem files unchanged from `c44ae4e`).
|
||||
|
||||
- **Combined budget admission can exceed the cap.** `xmem` admission cannot see `d3d12_xs` private heap charges, and the two use separate locks. Source-derived: private 6 then CPU 3 admits 9 against a cap of 8; a stale-snapshot schedule admits 12 against 8. Both assume successful, distinct underlying allocations. This is arithmetic from source, not a production run. A reported it and B confirmed it. See [the findings](final-verification/findings.md#independently-confirmed-combined-budget-defect) and roadmap item R3 in [the roadmap](consolidation-draft/implementation-roadmap.md). Any fix needs its owner's agreement and separate authorization.
|
||||
- **Accepted scopes that bear on placement:** A-6 (placement alignment does not give 64 KiB CPU alignment), A-8 to A-10 (bounded alias, mip-transfer and clear positives). A-7, the invalid-placement rejection gate, is Failed: validate before forwarding.
|
||||
@@ -0,0 +1,90 @@
|
||||
## Workstream A evidence handoff to Asufte / @atesahmet0
|
||||
|
||||
I am the Codex AI research agent acting under Arths17's explicit authorization. The requester confirmed that Asufte (@atesahmet0) now leads B, CarReal is unavailable, and A/B execution is authorized. I do not identify those accounts as aliases.
|
||||
|
||||
I verified that the local worktree is clean on `research/473-workstream-a-memory` at **8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8**, and `git ls-remote` confirms the shared `research/d3dmetal-zero-copy` ref at that exact manually published commit. No new commit/push is authorized. The fixed baseline remains at `9ae6d1ee7092b6021aad075531f50ba60de4fd53`; its probe SHA-256 is still `33e90bfee89e812f48990613cd74ced56473e5c3fc5d973f2ba1116090646a0c`. Its six cases/parameters are untouched.
|
||||
|
||||
This answers your kickoff requests with pinned paths checked against the commit tree. All new A observations remain author-run/unaccepted, not physical-page identity or unconditional zero-copy. The [report](https://github.com/MacosPorters/betterxen/blob/8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8/docs/research/d3dmetal-zero-copy/allocation-profiling/report.md), [inventory/gap classifications](https://github.com/MacosPorters/betterxen/blob/8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8/docs/research/d3dmetal-zero-copy/allocation-profiling/inventory/README.md) and [original/archive hash manifest](https://github.com/MacosPorters/betterxen/blob/8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8/docs/research/d3dmetal-zero-copy/allocation-profiling/inventory/manifest.json) give the full context.
|
||||
|
||||
### A2 / A22 source and raw evidence
|
||||
|
||||
| Requested evidence | Pinned implementation and executed source | Raw output / receipt |
|
||||
| --- | --- | --- |
|
||||
| Mapped CPU-pointer alignment; accounting/retention | [memory.cpp](https://github.com/MacosPorters/betterxen/blob/8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8/docs/research/d3dmetal-zero-copy/allocation-profiling/memory.cpp); [A2 exact executed source](https://github.com/MacosPorters/betterxen/blob/8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8/docs/research/d3dmetal-zero-copy/results/2026-11-26-apple-m4-arths17-a2-memory-partial/source/memory.cpp); [A22 exact source/helper/runner snapshot](https://github.com/MacosPorters/betterxen/tree/8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8/docs/research/d3dmetal-zero-copy/results/2026-11-26-apple-m4-arths17-a22-memory-pressure-stop/source/docs/research/d3dmetal-zero-copy/allocation-profiling) | [A2 WB64 stdout](https://github.com/MacosPorters/betterxen/blob/8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8/docs/research/d3dmetal-zero-copy/results/2026-11-26-apple-m4-arths17-a2-memory-partial/memory-wb-64MiB-r0/stdout.txt), [stderr](https://github.com/MacosPorters/betterxen/blob/8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8/docs/research/d3dmetal-zero-copy/results/2026-11-26-apple-m4-arths17-a2-memory-partial/memory-wb-64MiB-r0/stderr.txt), [A2 receipt](https://github.com/MacosPorters/betterxen/blob/8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8/docs/research/d3dmetal-zero-copy/results/2026-11-26-apple-m4-arths17-a2-memory-partial/receipt.json), [A22 receipt](https://github.com/MacosPorters/betterxen/blob/8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8/docs/research/d3dmetal-zero-copy/results/2026-11-26-apple-m4-arths17-a22-memory-pressure-stop/receipt.json); every case directory contains all checkpoint tool JSON and pointer-specific vmmap |
|
||||
| Invalid placement, mixed mip textures, RT/depth aliases | [resource probe](https://github.com/MacosPorters/betterxen/blob/8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8/docs/research/d3dmetal-zero-copy/gpu-correctness/textures-and-resources/probe.cpp); [exact executed source](https://github.com/MacosPorters/betterxen/blob/8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8/docs/research/d3dmetal-zero-copy/results/2026-11-26-apple-m4-arths17-a22-texture-matrix/source/docs/research/d3dmetal-zero-copy/gpu-correctness/textures-and-resources/probe.cpp) | [session 0 stdout](https://github.com/MacosPorters/betterxen/blob/8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8/docs/research/d3dmetal-zero-copy/results/2026-11-26-apple-m4-arths17-a22-texture-matrix/texture-s0/stdout.txt), [stderr](https://github.com/MacosPorters/betterxen/blob/8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8/docs/research/d3dmetal-zero-copy/results/2026-11-26-apple-m4-arths17-a22-texture-matrix/texture-s0/stderr.txt), [session 1 stdout](https://github.com/MacosPorters/betterxen/blob/8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8/docs/research/d3dmetal-zero-copy/results/2026-11-26-apple-m4-arths17-a22-texture-matrix/texture-s1/stdout.txt), [receipt/backend/commands](https://github.com/MacosPorters/betterxen/blob/8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8/docs/research/d3dmetal-zero-copy/results/2026-11-26-apple-m4-arths17-a22-texture-matrix/receipt.json) |
|
||||
| Valid buffer alias inheritance | [alias.cpp](https://github.com/MacosPorters/betterxen/blob/8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8/docs/research/d3dmetal-zero-copy/gpu-correctness/textures-and-resources/alias.cpp); [executed snapshot](https://github.com/MacosPorters/betterxen/blob/8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8/docs/research/d3dmetal-zero-copy/results/2026-11-26-apple-m4-arths17-a22-buffer-inheritance/source/docs/research/d3dmetal-zero-copy/gpu-correctness/textures-and-resources/alias.cpp) | [session 0 stdout](https://github.com/MacosPorters/betterxen/blob/8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8/docs/research/d3dmetal-zero-copy/results/2026-11-26-apple-m4-arths17-a22-buffer-inheritance/alias-s0/stdout.txt), [stderr](https://github.com/MacosPorters/betterxen/blob/8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8/docs/research/d3dmetal-zero-copy/results/2026-11-26-apple-m4-arths17-a22-buffer-inheritance/alias-s0/stderr.txt), [session 1 stdout](https://github.com/MacosPorters/betterxen/blob/8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8/docs/research/d3dmetal-zero-copy/results/2026-11-26-apple-m4-arths17-a22-buffer-inheritance/alias-s1/stdout.txt), [receipt/backend/commands](https://github.com/MacosPorters/betterxen/blob/8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8/docs/research/d3dmetal-zero-copy/results/2026-11-26-apple-m4-arths17-a22-buffer-inheritance/receipt.json) |
|
||||
| Corrected pooling / lifetime trace | [exact corrected trace source](https://github.com/MacosPorters/betterxen/blob/8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8/docs/research/d3dmetal-zero-copy/results/2026-11-26-apple-m4-arths17-a22-pool-corrected/source/docs/research/d3dmetal-zero-copy/allocation-profiling/pool.cpp) (current source only renames its pre-setup log field); [setup/slack/timing interpretation](https://github.com/MacosPorters/betterxen/blob/8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8/docs/research/d3dmetal-zero-copy/allocation-profiling/pooling-findings.md) | [individual raw samples](https://github.com/MacosPorters/betterxen/blob/8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8/docs/research/d3dmetal-zero-copy/results/2026-11-26-apple-m4-arths17-a22-pool-corrected/pool-individual-s0/stdout.txt), [pooled raw samples](https://github.com/MacosPorters/betterxen/blob/8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8/docs/research/d3dmetal-zero-copy/results/2026-11-26-apple-m4-arths17-a22-pool-corrected/pool-pooled-s0/stdout.txt), [all six cases / backend / commands](https://github.com/MacosPorters/betterxen/blob/8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8/docs/research/d3dmetal-zero-copy/results/2026-11-26-apple-m4-arths17-a22-pool-corrected/receipt.json) |
|
||||
| Omitted-copy pool control | [executed source after log-field rename](https://github.com/MacosPorters/betterxen/blob/8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8/docs/research/d3dmetal-zero-copy/results/2026-11-26-apple-m4-arths17-a22-pool-negative/source/docs/research/d3dmetal-zero-copy/allocation-profiling/pool.cpp) | [expected-failure stdout](https://github.com/MacosPorters/betterxen/blob/8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8/docs/research/d3dmetal-zero-copy/results/2026-11-26-apple-m4-arths17-a22-pool-negative/pool-omitted-copy-control/stdout.txt), [stderr](https://github.com/MacosPorters/betterxen/blob/8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8/docs/research/d3dmetal-zero-copy/results/2026-11-26-apple-m4-arths17-a22-pool-negative/pool-omitted-copy-control/stderr.txt), [receipt](https://github.com/MacosPorters/betterxen/blob/8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8/docs/research/d3dmetal-zero-copy/results/2026-11-26-apple-m4-arths17-a22-pool-negative/receipt.json) |
|
||||
|
||||
The common A helper is [support.h](https://github.com/MacosPorters/betterxen/blob/8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8/docs/research/d3dmetal-zero-copy/allocation-profiling/support.h); the native ARM64 accounting helper is [observe.cpp](https://github.com/MacosPorters/betterxen/blob/8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8/docs/research/d3dmetal-zero-copy/allocation-profiling/observe.cpp). Resource/state/alias expectations and remaining review questions are in [A resource/lifetime contract notes](https://github.com/MacosPorters/betterxen/blob/8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8/docs/research/d3dmetal-zero-copy/gpu-correctness/contracts/resource-placement-lifetime.md) and [review handoff](https://github.com/MacosPorters/betterxen/blob/8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8/docs/research/d3dmetal-zero-copy/allocation-profiling/review-handoff.md) (the latter's old team/publication status is historical and will be updated locally).
|
||||
|
||||
Expected/observed distinctions to audit independently:
|
||||
|
||||
- Map markers include 16384 and 49152 modulo 65536; these are CPU virtual addresses, not physical backing evidence or a guarantee that all maps have those remainders.
|
||||
- Resource negatives: offset 1 and offset 65536 for a 64 KiB buffer in a 64 KiB heap returned S_OK. Neither invalid resource was GPU-used. Texture-on-buffer-only returned E_INVALIDARG. **Both full texture sessions exited 1; the negative-rejection gate is still failed.** The public API imposes caller preconditions and does not promise every rejection HRESULT; do not call this alone a formal runtime conformance violation.
|
||||
- Valid mixed placement: 3 mips on 65x37 RGBA8/R32_UINT match 12500/12500 texel bytes, R8_UNORM 3125/3125; all 16384 buffer guard words match, for WB/WC/DEFAULT in both sessions. Transfer offsets/row pitches are printed; padding is not counted as texels.
|
||||
- Overlapping RGBA8 render/depth fixtures reinitialize every alias after activation: both 2405/2405 values match for RT clear colors and D32_FLOAT 0.5/0.25. This does not establish sampling, stencil, rasterized depth testing or texture data inheritance.
|
||||
- Advanced-model buffer inheritance: 3 changing full-GPU-write rounds/session; source, inherited and disjoint guard each 16384/16384 in two sessions. Map/GPU addresses are recorded; no raw CPU alias dereference is used to generate the GPU result. Please independently re-derive the inheritance expectation and barrier/state legality.
|
||||
- A2 accounting completed the first 12 cases, then an interrupted repeat; A22 completed six small/control cases and stopped the next graphics case when urgent pressure returned. **Neither is a complete repeated corrected sweep.** Historical two-repeat data has different baseline/retirement limitations. No physical identity, leak, residency or universal absence-of-copy conclusion follows.
|
||||
- Pool control guest exit 1 is expected only for `trace guard/interior mismatch`. This is separate from positive GPU correctness. The corrected six positive trace processes have all guard checks and a real gate-delayed retirement case; cold setup and pool slack are retained, not hidden.
|
||||
|
||||
### Hash identities
|
||||
|
||||
Full SHA-256 values below are copied from pinned receipts; PE builds are distinct artifacts, not assumed byte-identical across paths/time:
|
||||
|
||||
| Fixture | Source SHA-256 | Executed PE SHA-256 |
|
||||
| --- | --- | --- |
|
||||
| A2 memory | `d3747cdefb77bdaa0a570871895dc5cdf9683c4e807eff383d7444425184cf74` | `59566252cdd6170f52626fd835760bc16cbbaf36407e2afeff5d4508c70ee171` |
|
||||
| A22 texture matrix | `e9658020c77523916999f870ec595686fb1fe52d8271a8738dffe1dade07073a` | `134457afd9b631917ad28e39d5ddceaef3c1452090e3a592ffb7eb680a83a31b` |
|
||||
| Buffer inheritance | `4034866cc66761076ab0ea87c7928b9d4f17bcb244adfae79c95078e4dfb614e` | `ac6139de735084b5d801bf8a21ad95a0fb3bf89f860f7c4fd498dedc50f20ba8` |
|
||||
| Corrected pooling | `fda87a93e7212da8fea211405647877708e5c36f11c6c9c8df2897c368cf2a3c` | `6051db5166d98f00884429833d17560786ec60164097127fafd95d1051e7c539` |
|
||||
| Historical phase-two final | `fbe300e6b9f9b88a061ef80778a7ffbb712a82d0720002693b0892d1329bee9e` | functional `f15895f146d04021d0a39ce5df7c95ab649d9a8915e49a5e6c5ff8f68526b435`; memory `4904d7b1ac1c1989f67e3968206abad6150afe8816f75916192ff4ff66960cff` |
|
||||
|
||||
A helper SHA-256: `df6ba2201c120c80e3ce26ae0b1d21d05ea69149e0ff25c88b0abb8e1446ae69`. Native observer executable: `09bdf1513f982e9229ef0d2f6e1e9e397a9f14a13c244a695995e08e2b878e55` (ARM64).
|
||||
|
||||
A2 memory archives the original [HLSL](https://github.com/MacosPorters/betterxen/blob/8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8/docs/research/d3dmetal-zero-copy/results/2026-11-26-apple-m4-arths17-a2-memory-partial/memory-wb-64MiB-r0/consumption.hlsl) (`57a2cf0b068574fb05483b133968308ca593a0cf349d85ccd5ac3c8b11a5fc09`) and [compiled DXBC](https://github.com/MacosPorters/betterxen/blob/8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8/docs/research/d3dmetal-zero-copy/results/2026-11-26-apple-m4-arths17-a2-memory-partial/memory-wb-64MiB-r0/consumption.dxbc) (`a8458e0abaf39fd6e1a0de145f2c1f3cd5ce1e4ba69502b0f130a30ea4bc1420`). Texture/alias/pool cases use copy/clear, not a shader. The **historical phase-two compiled shader bytes/hashes were not retained**; do not retroactively substitute this new shader identity. Historical HLSL is embedded in its source.
|
||||
|
||||
### Commands and historical B-relevant evidence
|
||||
|
||||
Current pinned [A runner instructions](https://github.com/MacosPorters/betterxen/blob/8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8/docs/research/d3dmetal-zero-copy/allocation-profiling/README.md) and every receipt retain exact command arrays, source/PE hashes, environment, loaded D3DMetal DLL/framework evidence, timings/exit/timeout and raw stdout/stderr. All paths below are from a checkout of `8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8`:
|
||||
|
||||
```sh
|
||||
git fetch origin research/d3dmetal-zero-copy
|
||||
git worktree add --detach ../bx473-a-review 8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8
|
||||
cd ../bx473-a-review
|
||||
python3 docs/research/d3dmetal-zero-copy/allocation-profiling/run.py --bottle "/absolute/path/to/existing/win64/bottle" --scratch /tmp/bx473-texture-review --suite texture
|
||||
python3 docs/research/d3dmetal-zero-copy/allocation-profiling/run.py --bottle "/absolute/path/to/existing/win64/bottle" --scratch /tmp/bx473-alias-review --suite alias
|
||||
```
|
||||
|
||||
`--suite memory` runs the common-size/control profile; `--suite pool` runs three seeded pairs, and `--suite pool --negative-control` runs the expected-failure control. Use unique scratch paths; run serially on each host. Default is normal-pressure gating. `--allow-warning` is an explicit separately authorized profile, not an idle/normal-pressure claim. The 23 GB ceiling is a stop guard, not a target; no optional 2 GiB runs were commissioned. Do not force large runs under pressure.
|
||||
|
||||
Compile command shape (receipt provides exact paths):
|
||||
|
||||
```sh
|
||||
x86_64-w64-mingw32-g++ -std=c++20 -O2 -static -static-libgcc -static-libstdc++ -Wall -Wextra -Werror <probe.cpp> -o <probe.exe> -lkernel32
|
||||
xcrun clang++ -std=c++20 -O2 -arch arm64 -Wall -Wextra -Werror <observe.cpp> -o <observe>
|
||||
```
|
||||
|
||||
For **earlier M4 copy/coherence/tracking**, use the preserved historical source, not an A2/A22 reinterpretation:
|
||||
|
||||
- [Exact phase-two final probe](https://github.com/MacosPorters/betterxen/blob/8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8/docs/research/d3dmetal-zero-copy/allocation-profiling/inventory/frozen-phase2/probe.cpp), [runner](https://github.com/MacosPorters/betterxen/blob/8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8/docs/research/d3dmetal-zero-copy/allocation-profiling/inventory/frozen-phase2/run.py), [native observer](https://github.com/MacosPorters/betterxen/blob/8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8/docs/research/d3dmetal-zero-copy/allocation-profiling/inventory/frozen-phase2/observe.cpp), [summary script](https://github.com/MacosPorters/betterxen/blob/8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8/docs/research/d3dmetal-zero-copy/allocation-profiling/inventory/frozen-phase2/summarize.py), [original protocol bytes](https://github.com/MacosPorters/betterxen/blob/8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8/docs/research/d3dmetal-zero-copy/allocation-profiling/inventory/frozen-phase2/README.md.txt).
|
||||
- [Final functional receipt](https://github.com/MacosPorters/betterxen/blob/8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8/docs/research/d3dmetal-zero-copy/results/2026-11-26-apple-m4-arths17-historical-p2-functional-final/receipt.json): 23 cases including 18 dirty-stride cases (WB/WC/UPLOAD × 4/16 KiB stride × 3 sessions), shader coherence, omitted-dispatch control, CPU write-watch and identity/texture. Dirty means one word per chosen stride, **not every byte rewritten**. Endpoint copies are timed; page-first-word checksum validation is outside the timer. Preserve these limitations and distinguish from your upcoming matched B protocol.
|
||||
- [Shader coherence stdout](https://github.com/MacosPorters/betterxen/blob/8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8/docs/research/d3dmetal-zero-copy/results/2026-11-26-apple-m4-arths17-historical-p2-functional-final/coherence/stdout.txt), [stderr](https://github.com/MacosPorters/betterxen/blob/8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8/docs/research/d3dmetal-zero-copy/results/2026-11-26-apple-m4-arths17-historical-p2-functional-final/coherence/stderr.txt), [omitted-dispatch failure](https://github.com/MacosPorters/betterxen/blob/8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8/docs/research/d3dmetal-zero-copy/results/2026-11-26-apple-m4-arths17-historical-p2-functional-final/negative-control/stdout.txt); 3 rounds of 256 checksum matches, while omitted dispatch exits 1 specifically for GPU checksum mismatch.
|
||||
- [CPU tracking stdout](https://github.com/MacosPorters/betterxen/blob/8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8/docs/research/d3dmetal-zero-copy/results/2026-11-26-apple-m4-arths17-historical-p2-functional-final/watch/stdout.txt), [stderr](https://github.com/MacosPorters/betterxen/blob/8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8/docs/research/d3dmetal-zero-copy/results/2026-11-26-apple-m4-arths17-historical-p2-functional-final/watch/stderr.txt); offsets include 4 KiB subpages and both sides of the 16 KiB boundary. No claim of GPU-write tracking or a complete dirty-copy fallback.
|
||||
- [Example complete dirty timing/check samples](https://github.com/MacosPorters/betterxen/blob/8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8/docs/research/d3dmetal-zero-copy/results/2026-11-26-apple-m4-arths17-historical-p2-functional-final/dirty-wb-4096-s0/stdout.txt), [stderr](https://github.com/MacosPorters/betterxen/blob/8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8/docs/research/d3dmetal-zero-copy/results/2026-11-26-apple-m4-arths17-historical-p2-functional-final/dirty-wb-4096-s0/stderr.txt); all other individual samples are in sibling case directories.
|
||||
- [Historical 18-case accounting receipt](https://github.com/MacosPorters/betterxen/blob/8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8/docs/research/d3dmetal-zero-copy/results/2026-11-26-apple-m4-arths17-historical-p2-memory-final/receipt.json); graphics-warmed CPU control is not a process without graphics, warm baseline drifts, command objects remain live at release. Earlier `p2-acceptance`/`p2-memory` snapshots have unavailable old source bytes; the latter includes a timeout. Their labels are not independent acceptance.
|
||||
|
||||
The historical runner's original relative layout matters. For source review or justified reproduction, reconstruct its phase2 directory in an isolated review worktree without changing the frozen snapshot:
|
||||
|
||||
```sh
|
||||
mkdir -p docs/research/d3dmetal-zero-copy/phase2
|
||||
cp docs/research/d3dmetal-zero-copy/allocation-profiling/inventory/frozen-phase2/probe.cpp docs/research/d3dmetal-zero-copy/phase2/
|
||||
cp docs/research/d3dmetal-zero-copy/allocation-profiling/inventory/frozen-phase2/run.py docs/research/d3dmetal-zero-copy/phase2/
|
||||
cp docs/research/d3dmetal-zero-copy/allocation-profiling/inventory/frozen-phase2/observe.cpp docs/research/d3dmetal-zero-copy/phase2/
|
||||
cp docs/research/d3dmetal-zero-copy/allocation-profiling/inventory/frozen-phase2/summarize.py docs/research/d3dmetal-zero-copy/phase2/
|
||||
python3 docs/research/d3dmetal-zero-copy/phase2/run.py --bottle "/absolute/path/to/existing/win64/bottle" --scratch /tmp/bx473-historical-review --modes identity,coherence,negative-control,watch,dirty
|
||||
```
|
||||
|
||||
This is a reproduction recipe, **not a request to duplicate all existing B studies**. Please audit first and reproduce only critical cases or corrected methods you identify. The historical runner lacks current pressure/headroom guards; review that before any run. Current A runner includes a post-run Bottle-section trust-setting insertion fix that was structurally checked but not guest-launched afterward; executed old runner snapshots and malformed requested-setting receipt are preserved. Actual backend proof is separate from configuration intent.
|
||||
|
||||
@atesahmet0: please prioritize your requested small M5 alignment/creation-only negatives and independent source review of the valid alias/mip/RT/depth cases. Preserve your independent expected derivation and disagreements rather than accepting my interpretations. Please send your pinned B source/raw handoff when ready; I will review actual implementation and reproduce critical findings on M4 where safe. I will continue A-only gaps (accounting when pressure permits, allocation/fragmentation, ownership and resource classes) and leave copy/bandwidth/coherence/tracking development to B. Shared baseline/helpers/findings remain frozen; agree one owner before any shared protocol change. Neither workstream independently certifies its own code.
|
||||
@@ -0,0 +1,41 @@
|
||||
# Existing evidence inventory
|
||||
|
||||
This is Workstream A's inventory for [#473](https://github.com/MacosPorters/betterxen/issues/473), based on research revision `9ae6d1ee7092b6021aad075531f50ba60de4fd53`. The baseline source hash is `33e90bfee89e812f48990613cd74ced56473e5c3fc5d973f2ba1116090646a0c` and has not changed. [manifest.json](manifest.json) records original and archived SHA-256 hashes for each preserved historical file. The exact final supplemental source is in [frozen-phase2](frozen-phase2/README.md). Its historical proposed commands do not constitute a new shared protocol or authorization to run B's modes.
|
||||
|
||||
## Available records
|
||||
|
||||
| Evidence | Availability and review limits |
|
||||
| --- | --- |
|
||||
| Original M4 baseline, two sessions | Pinned branch source, two raw runs and receipts already published; first executable hash missing; no new independent certification |
|
||||
| M4 `p2-memory-final` | 18 cases: CPU allocation control, WB/L0, UPLOAD; 64/256/1024 MiB, two fresh-process repeats; all recorded exit 0. Source/runner hashes match frozen final bytes. All footprint/vmmap stage commands recorded exit 0. CPU control initializes a graphics context before its baseline: it is not a process without graphics. |
|
||||
| M4 `p2-functional-final` | 23 cases: identity, shader coherence, omitted-dispatch negative control, CPU write-watch, texture, 18 dirty-stride cases. All expected exits recorded, including negative control exit 1. A inventories but does not take ownership of B's tests or accept their conclusions. |
|
||||
| M4 `p2-acceptance` | Historical name only: 22 earlier author-run cases, not independent acceptance. Probe/runner source hashes differ from the available final source. Executable retained locally; exact earlier source bytes not recovered. Not final-source reproducibility evidence. |
|
||||
| M4 `p2-memory` | One CPU 64 MiB process killed at timeout (exit -9). Failure preserved. Earlier source bytes not recovered; method corrected in later runs. |
|
||||
| Development logs | Identity/coherence/texture/watch stdout/stderr remain at the original scratch root; inventory hashes supplement the archived bundles. No complete development launch receipt; do not promote to final evidence. |
|
||||
| 2elliti M5 report | [Comment](https://github.com/MacosPorters/betterxen/issues/473#issuecomment-7201953364): five reported baseline runs; launcher/bottle/timeout differ, later runs polled, backend evidence partial. Separately written private probe unavailable. Source/raw evidence requested. |
|
||||
| atesahmet0 M5 report | [Comment](https://github.com/MacosPorters/betterxen/issues/473#issuecomment-7202142335): 1 GiB footprint/region excerpts, dirty-stride timings, adapter/heap/write-watch data. No accessible pinned supplemental source or complete raw distributions linked; requested. Physical-sharing conclusions exceed the accounting/timing evidence. |
|
||||
| CarReal8917 B implementation | No pinned B revision or raw handoff in the five comments read at start. Confirmation and source/receipts requested in #473. No alias with another account assumed. |
|
||||
|
||||
Archives under `../../results/2026-11-26-apple-m4-arths17-historical-*` contain original stdout/stderr bytes, receipts and tool outputs, excluding executables and bottles. JSON diagnostics replace the original home-directory prefix with `<HOME>`; manifest retains both original and redacted hashes. Original evidence and executable bytes remain locally unmodified. Embedded source paths are historical, not a promise that those paths exist on another host. No proprietary DLL/framework is archived.
|
||||
|
||||
Two new harness preparation failures are also preserved: the first nonexistent wine64 lookup interrupted setup, and the next strict -Werror build detected unused header helpers. No guest ran in either. The first setup attempt has source hashes but no copied source snapshot; later attempts save exact source bytes before compiling. The fixed inline helpers and correct wineloader version command are exercised in subsequent runs.
|
||||
|
||||
## Objective classification before new experiments
|
||||
|
||||
| Objective | Classification | Next justified work |
|
||||
| --- | --- | --- |
|
||||
| Fixed six baseline checks | Already tested; requires independent source review/reproduction | Preserve unchanged; obtain M5 source/raw receipts and B review |
|
||||
| Footprint sizes/CPU controls | Already tested; requires methodological correction | Baseline drops ~40 MiB; small allocations can use existing pools; add settled baseline and full retirement instead of repeating identical protocol |
|
||||
| Physical page identity / excluded copies | Unsupported or currently untestable with these tools | Process accounting and region labels cannot identify all physical backing or copies outside the sampled process/window |
|
||||
| Pointer-specific region evidence | Requires additional experimentation | Old M4 vmmap is summary-only; retain exact mapped-pointer region at paused checkpoints |
|
||||
| Full resource retirement | Requires additional experimentation | Historical release leaves command/shader objects alive; dispose them and separately record device release |
|
||||
| Inverted ownership/xmem requirements | Requires additional experimentation and requirement derivation | Inspect pinned public in-tree contracts; requested VA, reservation/decommit, attributes, aliases/scatter and pre-device allocations need explicit limits |
|
||||
| Pooling/allocation latency | Requires additional experimentation | Matched individual/pool resource traces; raw allocation/placement/Map/free samples, retained memory and logical fragmentation |
|
||||
| Fence-safe recycling/aliasing | Requires additional experimentation | Fixed traces, guards, readback, delayed reuse; no intentional in-flight destruction or unsafe writes |
|
||||
| RGBA8 65x37 UNKNOWN CPU write + GPU readback | Already tested; requires independent review/reproduction | 2405/2405 pixels recorded, padded pitch 512; preserve original evidence |
|
||||
| ROW_MAJOR DEFAULT cross-adapter control | Already tested; requires independent review/reproduction | Creation and GPU upload/readback recorded; do not rerun identical case without a review need |
|
||||
| Mixed placement, RT/depth, formats/mips, storage classes | Requires additional experimentation | Extend texture matrix using public API restrictions and exact readbacks; do not infer sampling from copies |
|
||||
| AMD allocator | Requires additional research | Exact-pin, per-file license/provenance and feature review; no integration authorized by evaluation |
|
||||
| B copy/bandwidth/coherence/tracking | Requires independent reproduction after pinned handoff | B implementation responsibility; no duplicate fixture development by A |
|
||||
|
||||
Hardware logs are local class A observations within their workloads, public API contracts class B, unobserved mechanisms class U. Historical shaders were compiled at runtime but their exact compiled bytecode hashes were not archived; this is a receipt gap, not filled by new builds. The new memory fixture saves its own shader source and bytecode. All new A implementation remains author-run and independently unaccepted until reciprocal review. No Xbox hardware or game compatibility is established.
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
# Frozen historical source snapshot
|
||||
|
||||
The [original README bytes](README.md.txt) are preserved unchanged as text, because their relative links and proposed paths describe the original location. This is an inventory snapshot, not an adopted shared protocol. Exact sources and hashes are in [the inventory manifest](../manifest.json). Some historical participant/protocol wording has been superseded by the revised two-workstream plan in #473.
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
# Phase-two standardized supplemental protocol 1
|
||||
|
||||
Research [#473](https://github.com/MacosPorters/betterxen/issues/473). Read the [source/API review](review.md) and [separate concurrent-experiment assessment](concurrent-review.md). The original six experiments in `../probe.cpp` and their runner are frozen and unchanged. These additions do not touch #464, production shims, ABI or main.
|
||||
|
||||
## Identical reproduction
|
||||
|
||||
Use native ARM64 MinGW-w64, Python 3.11+, Apple Command Line Tools, licensed CrossOver/D3DMetal and supported Rosetta. The runner builds a Windows x86-64 probe and a native ARM64 process-accounting observer, uses a private copy of an existing win64 bottle, and writes only to a new scratch directory. Preserve source revision/hash, compiler/runtime receipts and raw logs; remove scratch after archiving evidence. No proprietary binaries are committed.
|
||||
|
||||
```sh
|
||||
git fetch origin research/d3dmetal-zero-copy:refs/remotes/origin/research/d3dmetal-zero-copy
|
||||
git worktree add --detach ../betterxen-zero-copy-p2 origin/research/d3dmetal-zero-copy
|
||||
cd ../betterxen-zero-copy-p2
|
||||
python3 docs/research/d3dmetal-zero-copy/phase2/run.py \
|
||||
--bottle "/absolute/path/to/an/existing/CrossOver/bottle" \
|
||||
--scratch /tmp/bx-uma-verify/phase2-run
|
||||
```
|
||||
|
||||
Default modes are identity, shader coherence, omitted-dispatch negative control, write-watch, textures, dirty-page scaling and memory footprint. Expected exit is 1 only for the deliberate negative control, and it must specifically report a GPU checksum mismatch. Other failures/timeouts are retained and never treated as passes. Source hash, PE/observer hashes, exact compiler commands, host/software versions and child environment are in receipt.json; every case has unedited stdout/stderr and case.json. `--modes identity,coherence,negative-control,watch,texture,dirty` and `--modes memory` split the suite into serial batches when convenient; do not run GPU batches concurrently.
|
||||
|
||||
The common profile is identical on **16 GiB and 24 GiB** hosts: 64, 256 and 1024 MiB, one allocation per fresh process, two repeats per size/type. CPU-only VirtualAlloc is the accounting control; CUSTOM/WRITE_BACK/L0 and standard UPLOAD are the graphics cases. `--large` adds 2048 MiB only when installed RAM is at least 24 GiB; never extrapolate an unrun case. A 4 GiB allocation is intentionally outside the common profile. Review recorded pressure/swap/compression and stop/reduce the study rather than forcing an allocation under pressure; label reduced profiles, do not mix them silently. Close unrelated heavy applications when practical and record background load. Tools run outside timed latency windows.
|
||||
|
||||
Compilation (the receipt records actual absolute paths):
|
||||
|
||||
```sh
|
||||
x86_64-w64-mingw32-g++ -std=c++20 -O2 -static -static-libgcc -static-libstdc++ \
|
||||
-Wall -Wextra -Werror phase2/probe.cpp -o phase2.exe -lkernel32
|
||||
xcrun clang++ -std=c++20 -O2 -arch arm64 -Wall -Wextra -Werror \
|
||||
phase2/observe.cpp -o observe
|
||||
file phase2.exe observe
|
||||
lipo -archs observe
|
||||
otool -L observe
|
||||
```
|
||||
|
||||
The HLSL is original, embedded in the source, compiled at runtime through the externally installed d3dcompiler_47.dll (cs_5_0; optimization-level-3 requested). Preserve compiler diagnostics: this Wine compiler reports that it ignores flag 0x8000, so no claim is made that the requested optimization was applied. The application loads host d3d12.dll directly and rejects a loaded d3d12_xs.dll. Environment uses an allowlist, ROSETTA_ADVERTISE_AVX=1, CX_GRAPHICS_BACKEND=d3dmetal and WINEDEBUG=-all. The copied bottle alone receives the locally compiled executable's trust/scanner configuration. Original bottle configuration is checked unchanged.
|
||||
|
||||
## 1. Physical footprint and overhead
|
||||
|
||||
Each memory process warms the shader, queue and fixed 64 KiB output before the baseline sample. The requested large source is then created, mapped, **fully written word-by-word** using index-mixed data, consumed by a full-allocation GPU shader read, fence-waited and released. A CPU-only control skips the GPU source pass explicitly. The shader reduces the entire allocation into 256 checksum words; validation is a checksum test, not a byte-for-byte proof for every source word.
|
||||
|
||||
At each handshake point—baseline, created, mapped, fully_initialized, gpu_complete, released—the guest pauses with no GPU work pending. The host resolves the process mapping the unique scratch PE, excluding wineserver's open file handle. It records:
|
||||
|
||||
- Three proc_pid_rusage(RUSAGE_INFO_V4) snapshots: physical footprint, resident/wired size, pageins and lifetime maximum; native observer return codes are retained.
|
||||
- `footprint -p PID -f bytes` and `vmmap -summary PID`, each with bounded timeout and full stdout/stderr.
|
||||
- `vm_stat` and `memory_pressure -Q`, to identify changing compression/swap/pressure.
|
||||
- A separate loaded-library excerpt proving the app's D3DMetal DLL/framework; unrelated personal paths are not needed for this receipt.
|
||||
|
||||
These are API/process accounting measurements, not a physical-page identity test. Report deltas from each process's baseline and slopes across sizes, with both repeats and the CPU control. Do not add shared/RSS/footprint categories together or call a region label proof of sharing. Allocation caches and driver accounting may survive release. A near-1x slope supports a small *observed process-accounted* overhead; it does not exclude transient copies or memory charged elsewhere. Permission failures of footprint/vmmap remain visible; proc_pid_rusage is a separate signal, not a fabricated replacement for a failed tool.
|
||||
|
||||
## 2. Dirty-page scaling
|
||||
|
||||
Use a 256 MiB source in WB/L0, WC/L0 and UPLOAD, with 4096- and 16384-byte strides. Fully initialize once. For each stride modify k={0,1,64,4096,all} page-first words, evenly spread including endpoints when k>1. Thus all=65536 for 4 KiB and all=16384 for 16 KiB. Here “dirty” means application-modified strides, not a claim about the driver's actual tracking granularity. Each new write uses an iteration-specific pattern; k=0 changes nothing. Changes from previous k cases remain part of the expected state, so there is no hidden reset that dirties the full allocation between cases.
|
||||
|
||||
Three fresh-process sessions rotate k order and alternate heap order. Each k has 5 warmups + 30 recorded iterations. All sources use GENERIC_READ, including CUSTOM, with the same pre-recorded two-copy command list and no source transitions. CPU writes/store fence occur outside the timed window, and their cost is recorded separately as dirty_cpu_ms. Only ExecuteCommandLists + Signal + fence wait are timed as ms; command encoding, device-status check and validation are outside it. Readback checks the first and final stride's first 64 bytes. An additional untimed shader reads all page-first words and validates 256 independent output words against a CPU checksum, so modifying interior pages is not ignored.
|
||||
|
||||
Publish all per-iteration samples, median and nearest-rank p10/p90; compare per-session medians rather than pooling correlated samples without disclosure. The untimed verification uses another serialized queue; each submission completes before any subsequent CPU access or queue use. No concurrent queue accesses occur. Flat timing cannot exclude copies on CPU faults, at other API points or below noise; a slope cannot by itself distinguish copies from tracking/cache costs. No lsof/ps/vmmap polling runs during these cases.
|
||||
|
||||
## 3. Direct shader access and synchronized coherence
|
||||
|
||||
Persistent WB/L0 input (64 KiB) and UAV-capable WB/L0 output (64 KiB). Three rounds overwrite all 16384 input words and poison the 256-word output. After CPU store completion, 256 shader invocations read the input directly through a root SRV and write checksums through a root UAV. Output transitions COMMON→UNORDERED_ACCESS→COMMON; a queue fence completes before direct CPU reads from the same original output pointer. All 256 outputs must match each round. No CopyBufferRegion or CPU→GPU staging upload is used in this mode. The omitted-dispatch control must fail against the poison pattern. This establishes synchronized shader usability, not physical zero-copy or concurrent atomic coherence.
|
||||
|
||||
## 4. GPU texture readback and layout limits
|
||||
|
||||
Use an intentionally non-aligned width: 65×37 RGBA8, one mip/slice. UNKNOWN texture on CUSTOM WB/L0 is mapped with ppData=nullptr, filled with WriteToSubresource in COMMON, transitioned to COPY_SOURCE and GPU-copied into a READBACK buffer using GetCopyableFootprints. Respect returned row pitch/offset; check exactly 2405 pixel words after the fence. Padding is not interpreted as pixels. A single cold elapsed time is recorded but is not a throughput benchmark or a comparison of layout speed.
|
||||
|
||||
The ROW_MAJOR control uses a DEFAULT heap with SHARED|SHARED_CROSS_ADAPTER and a resource with ALLOW_CROSS_ADAPTER. It is filled from a footprint-pitched UPLOAD buffer by GPU copy, then GPU-copied to READBACK and compared. Map is explicitly not called on this CPU-inaccessible control. If shared/cross-adapter creation is unsupported, record the HRESULT and not-run path. No portability inference comes from the earlier development variant that omitted required flags; that variant was corrected before protocol-1 acceptance evidence.
|
||||
|
||||
This does not establish texture sampling/render/depth correctness, opaque-layout pointer aliasing, arbitrary formats/mips or a requirement that all textures internally copy. Public restrictions and buffer/texture ownership implications are in the review.
|
||||
|
||||
## 5. Adapter and heap-property identification
|
||||
|
||||
Match DXGI to **the actual D3D12 device LUID** using GetAdapterLuid and EnumAdapterByLuid, not an assumed adapter index. Record GetDesc2 name, IDs, flags and exact byte counts; these are advertised values, not physical memory measurements. Query architecture flags, heap tier, cross-adapter row-major and standard-swizzle support. Log GetCustomHeapProperties(0, DEFAULT/UPLOAD/READBACK), including Type, CPUPageProperty, MemoryPoolPreference and both node masks. Record guest page size/allocation granularity alongside the native observer's host page size. Loaded-library evidence, not adapter branding alone, identifies the backend.
|
||||
|
||||
## 6. Write-watch boundaries
|
||||
|
||||
Allocate a separate 64 KiB VirtualAlloc MEM_WRITE_WATCH region. Reset before each disjoint case; write one byte at {0}, {4096}, {12288}, {16383}, {16384}, {0,4096}, {0,4096,8192,12288}, {12288,16384}, {16383,16384}. Report dirty offsets, return/count/granularity and an immediate second query showing the reset state. There are no other threads writing during reset/query. These tests cover separate 4 KiB subpages in one 16 KiB interval and both sides of the 16 KiB boundary. They exercise CPU tracking only; GPU write-watch tracking remains untested and cannot be inferred from IsolatedMMU=false.
|
||||
|
||||
## Evidence and provenance
|
||||
|
||||
Source and native observer are original GPL-3.0-or-later research, using externally installed Microsoft-compatible headers/runtime APIs and Apple's public local SDK interfaces. No upstream implementation, restricted SDK, shader corpus, game code, proprietary compiler or runtime binary is copied into this directory. Existing runtime/toolchain research provenance remains in the [registry](../../upstream-registry.md) and [reuse matrix](../../component-reuse-matrix.md); any future vendored third-party code requires a per-file review before adoption.
|
||||
|
||||
Archive results by chip/contributor/run, preserving numerical logs; disclose any home-path redaction in host diagnostics. Keep the exact input source hashes and execution outcome. Hardware results are local class A evidence; public D3D12 contracts class B; physical aliasing/internal mechanisms and unmeasured generations remain class U. New probe authors do not independently certify their own code. Another contributor must review the implementation and run the same revision before independent acceptance.
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
# Concurrent visibility: exploratory only
|
||||
|
||||
The proposed CPU-after-submit/GPU-spin and GPU-store/CPU-spin experiment intentionally omits the synchronization used by ordinary D3D12 applications. It is excluded from this protocol's executables and acceptance gates. No result from it is claimed here.
|
||||
|
||||
Microsoft's [Map contract](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12resource-map) requires the CPU to finish writes before GPU execution in the persistent-map usage model and cautions against assuming CPU/GPU atomic guarantees. A CPU store fence, volatile load or a shader barrier alone does not create an API-guaranteed interprocessor rendezvous. [ALLOW_SIMULTANEOUS_ACCESS](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ne-d3d12-d3d12_resource_flags) is not permission for conflicting concurrent CPU/GPU writes to the same location.
|
||||
|
||||
A positive result would not prove a mid-flight observation: the GPU may start after the CPU store, commands may be delayed or serialized, and an implementation may synchronize/copy at a different point. A negative result would not prove shadow copying: CPU/GPU cache behavior, compiler hoisting, shader scheduling and unsupported atomic/visibility assumptions can all prevent progress. Neither outcome establishes physical page identity.
|
||||
|
||||
Any future exploratory implementation must be separate, explicitly opted into, bounded in shader iterations and process duration, and must preserve its exact compiled shader, scheduling evidence and outcomes without counting them as conformance passes/failures. A bounded spin may still monopolize a device or encounter watchdog limits; do not make an unbounded poll part of the shared suite. Establish actual GPU start/progress independently before interpreting apparent mid-flight behavior, and keep any conclusion conditional on that evidence.
|
||||
|
||||
The standard test instead completes CPU stores before dispatch, waits on a queue fence after the shader, and reads the existing mapped output pointer. This tests application-usable synchronized coherence without claiming to identify its physical implementation.
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Original macOS process accounting observer; native ARM64 only.
|
||||
#include <libproc.h>
|
||||
#include <sys/resource.h>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cerrno>
|
||||
#include <unistd.h>
|
||||
int main(int argc,char** argv){
|
||||
if(argc!=2)return 2;
|
||||
rusage_info_v4 r{};int pid=std::atoi(argv[1]);
|
||||
int rc=proc_pid_rusage(pid,RUSAGE_INFO_V4,reinterpret_cast<rusage_info_t*>(&r));
|
||||
std::printf("{\"pid\":%d,\"return\":%d,\"errno\":%d,\"host_page_size\":%d,\"phys_footprint\":%llu,\"resident_size\":%llu,\"wired_size\":%llu,\"pageins\":%llu,\"max_phys_footprint\":%llu}\n",pid,rc,rc?errno:0,getpagesize(),r.ri_phys_footprint,r.ri_resident_size,r.ri_wired_size,r.ri_pageins,r.ri_lifetime_max_phys_footprint);
|
||||
return rc?1:0;
|
||||
}
|
||||
+264
@@ -0,0 +1,264 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Supplemental original synthetic tests; baseline ../probe.cpp is unchanged.
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#define NOMINMAX
|
||||
#include <windows.h>
|
||||
#include <d3d12.h>
|
||||
#include <dxgi1_4.h>
|
||||
#include <d3dcompiler.h>
|
||||
#include <emmintrin.h>
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
template<class T> struct Ref{
|
||||
T* p=nullptr;Ref()=default;Ref(const Ref&)=delete;Ref& operator=(const Ref&)=delete;
|
||||
~Ref(){clear();} void clear(){if(p){p->Release();p=nullptr;}}
|
||||
T* operator->()const{return p;} void** out(){return reinterpret_cast<void**>(&p);}
|
||||
};
|
||||
static void require(HRESULT h,const char* name){
|
||||
if(FAILED(h)){std::printf("FAIL %s HRESULT=0x%08lX\n",name,(unsigned long)h);throw std::runtime_error(name);}
|
||||
}
|
||||
static void report(HRESULT h,const char* name){std::printf("API %s HRESULT=0x%08lX\n",name,(unsigned long)h);}
|
||||
template<class T> static T symbol(HMODULE m,const char* name){
|
||||
FARPROC p=GetProcAddress(m,name);if(!p)throw std::runtime_error(name);
|
||||
T result;static_assert(sizeof(result)==sizeof(p));std::memcpy(&result,&p,sizeof(p));return result;
|
||||
}
|
||||
static double ticks(){LARGE_INTEGER t;QueryPerformanceCounter(&t);return double(t.QuadPart);}
|
||||
static double frequency(){LARGE_INTEGER t;QueryPerformanceFrequency(&t);return double(t.QuadPart);}
|
||||
static D3D12_HEAP_PROPERTIES properties(D3D12_HEAP_TYPE type){
|
||||
D3D12_HEAP_PROPERTIES p{};p.Type=type;p.CreationNodeMask=1;p.VisibleNodeMask=1;return p;
|
||||
}
|
||||
static D3D12_RESOURCE_DESC bufferDesc(UINT64 bytes,D3D12_RESOURCE_FLAGS flags=D3D12_RESOURCE_FLAG_NONE){
|
||||
D3D12_RESOURCE_DESC r{};r.Dimension=D3D12_RESOURCE_DIMENSION_BUFFER;r.Width=bytes;r.Height=1;r.DepthOrArraySize=1;r.MipLevels=1;r.SampleDesc.Count=1;r.Layout=D3D12_TEXTURE_LAYOUT_ROW_MAJOR;r.Flags=flags;return r;
|
||||
}
|
||||
struct Context{
|
||||
HMODULE dll=nullptr;Ref<ID3D12Device3> device;
|
||||
Context(){
|
||||
dll=LoadLibraryA("d3d12.dll");if(!dll)throw std::runtime_error("LoadLibrary d3d12");
|
||||
char path[2048]{};GetModuleFileNameA(dll,path,sizeof(path));std::printf("D3D12_DLL %s\n",path);
|
||||
using Create=HRESULT(WINAPI*)(IUnknown*,D3D_FEATURE_LEVEL,REFIID,void**);
|
||||
require(symbol<Create>(dll,"D3D12CreateDevice")(nullptr,D3D_FEATURE_LEVEL_11_0,__uuidof(ID3D12Device3),device.out()),"CreateDevice3");
|
||||
bool shim=GetModuleHandleA("d3d12_xs.dll")!=nullptr;std::printf("SHIM_LOADED %d\n",shim);if(shim)throw std::runtime_error("shim contamination");
|
||||
}
|
||||
};
|
||||
struct Queue{
|
||||
ID3D12Device3* d;Ref<ID3D12CommandQueue> q;Ref<ID3D12CommandAllocator> allocator;Ref<ID3D12GraphicsCommandList> list;Ref<ID3D12Fence> fence;
|
||||
HANDLE event=nullptr;UINT64 value=0;
|
||||
explicit Queue(ID3D12Device3* device):d(device){
|
||||
D3D12_COMMAND_QUEUE_DESC desc{};desc.Type=D3D12_COMMAND_LIST_TYPE_DIRECT;
|
||||
require(d->CreateCommandQueue(&desc,__uuidof(ID3D12CommandQueue),q.out()),"CreateCommandQueue");
|
||||
require(d->CreateCommandAllocator(desc.Type,__uuidof(ID3D12CommandAllocator),allocator.out()),"CreateCommandAllocator");
|
||||
require(d->CreateCommandList(0,desc.Type,allocator.p,nullptr,__uuidof(ID3D12GraphicsCommandList),list.out()),"CreateCommandList");
|
||||
require(list->Close(),"initial Close");require(d->CreateFence(0,D3D12_FENCE_FLAG_NONE,__uuidof(ID3D12Fence),fence.out()),"CreateFence");
|
||||
event=CreateEventW(nullptr,FALSE,FALSE,nullptr);if(!event)throw std::runtime_error("CreateEvent");
|
||||
}
|
||||
~Queue(){if(event)CloseHandle(event);}
|
||||
void begin(){require(allocator->Reset(),"allocator Reset");require(list->Reset(allocator.p,nullptr),"list Reset");}
|
||||
void transition(ID3D12Resource* r,D3D12_RESOURCE_STATES a,D3D12_RESOURCE_STATES b){
|
||||
if(a==b)return;
|
||||
D3D12_RESOURCE_BARRIER x{};x.Type=D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;x.Transition.pResource=r;x.Transition.StateBefore=a;x.Transition.StateAfter=b;x.Transition.Subresource=D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;list->ResourceBarrier(1,&x);
|
||||
}
|
||||
void close(){require(list->Close(),"Close");}
|
||||
void executeClosed(){
|
||||
ID3D12CommandList* lists[]={list.p};q->ExecuteCommandLists(1,lists);require(q->Signal(fence.p,++value),"Signal");
|
||||
UINT64 completed=fence->GetCompletedValue();if(completed==~UINT64(0))throw std::runtime_error("device removed fence");
|
||||
if(completed<value){require(fence->SetEventOnCompletion(value,event),"SetEventOnCompletion");DWORD w=WaitForSingleObject(event,10000);if(w!=WAIT_OBJECT_0)throw std::runtime_error("fence timeout");}
|
||||
}
|
||||
void finish(){close();_mm_sfence();executeClosed();require(d->GetDeviceRemovedReason(),"GetDeviceRemovedReason");}
|
||||
};
|
||||
struct Buffer{
|
||||
Ref<ID3D12Heap> heap;Ref<ID3D12Resource> resource;void* cpu=nullptr;UINT64 size=0;
|
||||
void allocate(ID3D12Device3* d,UINT64 bytes,const std::string& type,bool uav=false){
|
||||
size=bytes;auto desc=bufferDesc(bytes,uav?D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS:D3D12_RESOURCE_FLAG_NONE);
|
||||
auto state=uav?D3D12_RESOURCE_STATE_COMMON:D3D12_RESOURCE_STATE_GENERIC_READ;
|
||||
if(type=="upload"||type=="readback"){
|
||||
if(uav)throw std::runtime_error("UAV on upload/readback forbidden in this probe");
|
||||
auto p=properties(type=="upload"?D3D12_HEAP_TYPE_UPLOAD:D3D12_HEAP_TYPE_READBACK);
|
||||
if(type=="readback")state=D3D12_RESOURCE_STATE_COPY_DEST;
|
||||
require(d->CreateCommittedResource(&p,D3D12_HEAP_FLAG_NONE,&desc,state,nullptr,__uuidof(ID3D12Resource),resource.out()),"committed buffer");
|
||||
}else{
|
||||
D3D12_HEAP_DESC hd{};hd.SizeInBytes=(bytes+65535)&~UINT64(65535);hd.Alignment=65536;hd.Properties=properties(D3D12_HEAP_TYPE_CUSTOM);hd.Properties.CPUPageProperty=type=="wc"?D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE:D3D12_CPU_PAGE_PROPERTY_WRITE_BACK;hd.Properties.MemoryPoolPreference=D3D12_MEMORY_POOL_L0;
|
||||
require(d->CreateHeap(&hd,__uuidof(ID3D12Heap),heap.out()),"custom heap");
|
||||
require(d->CreatePlacedResource(heap.p,0,&desc,state,nullptr,__uuidof(ID3D12Resource),resource.out()),"placed buffer");
|
||||
}
|
||||
}
|
||||
void map(){require(resource->Map(0,nullptr,&cpu),"Map buffer");if(!cpu)throw std::runtime_error("null buffer pointer");}
|
||||
void release(){cpu=nullptr;resource.clear();heap.clear();}
|
||||
};
|
||||
static void identity(Context& c){
|
||||
using Factory=HRESULT(WINAPI*)(UINT,REFIID,void**);
|
||||
HMODULE dxgi=LoadLibraryA("dxgi.dll");if(!dxgi)throw std::runtime_error("dxgi load");
|
||||
Ref<IDXGIFactory4> f;require(symbol<Factory>(dxgi,"CreateDXGIFactory2")(0,__uuidof(IDXGIFactory4),f.out()),"factory4");
|
||||
LUID luid=c.device->GetAdapterLuid();Ref<IDXGIAdapter2> a;require(f->EnumAdapterByLuid(luid,__uuidof(IDXGIAdapter2),a.out()),"adapter by device LUID");
|
||||
DXGI_ADAPTER_DESC2 ad{};require(a->GetDesc2(&ad),"GetDesc2");char name[512]{};WideCharToMultiByte(CP_UTF8,0,ad.Description,-1,name,sizeof(name),nullptr,nullptr);
|
||||
std::printf("ADAPTER description=%s vendor=0x%04X device=0x%04X subsystem=0x%08X revision=%u flags=%u dedicated_video_bytes=%llu dedicated_system_bytes=%llu shared_system_bytes=%llu luid=%08lX:%08lX\n",name,ad.VendorId,ad.DeviceId,ad.SubSysId,ad.Revision,ad.Flags,(unsigned long long)ad.DedicatedVideoMemory,(unsigned long long)ad.DedicatedSystemMemory,(unsigned long long)ad.SharedSystemMemory,(unsigned long)luid.HighPart,(unsigned long)luid.LowPart);
|
||||
D3D12_FEATURE_DATA_D3D12_OPTIONS opts{};require(c.device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS,&opts,sizeof(opts)),"options");std::printf("OPTIONS ResourceHeapTier=%d CrossAdapterRowMajorTextureSupported=%d StandardSwizzle64KBSupported=%d\n",opts.ResourceHeapTier,opts.CrossAdapterRowMajorTextureSupported,opts.StandardSwizzle64KBSupported);
|
||||
D3D12_FEATURE_DATA_ARCHITECTURE1 arch{};require(c.device->CheckFeatureSupport(D3D12_FEATURE_ARCHITECTURE1,&arch,sizeof(arch)),"architecture1");std::printf("ARCH UMA=%d CacheCoherentUMA=%d TileBasedRenderer=%d IsolatedMMU=%d\n",arch.UMA,arch.CacheCoherentUMA,arch.TileBasedRenderer,arch.IsolatedMMU);
|
||||
for(auto type:{D3D12_HEAP_TYPE_DEFAULT,D3D12_HEAP_TYPE_UPLOAD,D3D12_HEAP_TYPE_READBACK}){
|
||||
auto p=c.device->GetCustomHeapProperties(0,type);std::printf("CUSTOM_PROPERTIES input_type=%d Type=%d CPUPageProperty=%d MemoryPoolPreference=%d CreationNodeMask=%u VisibleNodeMask=%u\n",type,p.Type,p.CPUPageProperty,p.MemoryPoolPreference,p.CreationNodeMask,p.VisibleNodeMask);
|
||||
}
|
||||
SYSTEM_INFO si{};GetSystemInfo(&si);std::printf("GUEST_PAGE_SIZE %lu ALLOCATION_GRANULARITY %lu\n",si.dwPageSize,si.dwAllocationGranularity);
|
||||
}
|
||||
struct Shader{
|
||||
Ref<ID3D12RootSignature> root;Ref<ID3D12PipelineState> pipeline;
|
||||
static constexpr const char* code=R"HLSL(
|
||||
ByteAddressBuffer source : register(t0);
|
||||
RWByteAddressBuffer result : register(u0);
|
||||
cbuffer Parameters : register(b0) { uint count; uint salt; uint wordStride; };
|
||||
[numthreads(64,1,1)]
|
||||
void main(uint3 tid : SV_DispatchThreadID) {
|
||||
uint accum=0;
|
||||
for(uint i=tid.x; i<count; i+=256) accum ^= source.Load(i*wordStride*4)+salt;
|
||||
result.Store(tid.x*4,accum);
|
||||
}
|
||||
)HLSL";
|
||||
explicit Shader(Context& c){
|
||||
HMODULE compiler=LoadLibraryA("d3dcompiler_47.dll");if(!compiler)throw std::runtime_error("d3dcompiler47 unavailable");
|
||||
char path[2048]{};GetModuleFileNameA(compiler,path,sizeof(path));std::printf("SHADER_COMPILER %s\n",path);
|
||||
using Compile=HRESULT(WINAPI*)(LPCVOID,SIZE_T,LPCSTR,const D3D_SHADER_MACRO*,ID3DInclude*,LPCSTR,LPCSTR,UINT,UINT,ID3DBlob**,ID3DBlob**);
|
||||
Ref<ID3DBlob> binary,error;
|
||||
HRESULT h=symbol<Compile>(compiler,"D3DCompile")(code,std::strlen(code),"original-phase2.hlsl",nullptr,nullptr,"main","cs_5_0",D3DCOMPILE_OPTIMIZATION_LEVEL3,0,&binary.p,&error.p);
|
||||
if(error.p)std::printf("COMPILER_LOG %.*s\n",(int)error->GetBufferSize(),(const char*)error->GetBufferPointer());
|
||||
require(h,"D3DCompile cs5_0");
|
||||
std::printf("SHADER_BYTECODE bytes=%zu magic=%.4s\n",binary->GetBufferSize(),(char*)binary->GetBufferPointer());
|
||||
D3D12_ROOT_PARAMETER params[3]{};
|
||||
params[0].ParameterType=D3D12_ROOT_PARAMETER_TYPE_SRV;params[0].Descriptor.ShaderRegister=0;
|
||||
params[1].ParameterType=D3D12_ROOT_PARAMETER_TYPE_UAV;params[1].Descriptor.ShaderRegister=0;
|
||||
params[2].ParameterType=D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;params[2].Constants.ShaderRegister=0;params[2].Constants.Num32BitValues=3;
|
||||
D3D12_ROOT_SIGNATURE_DESC desc{};desc.NumParameters=3;desc.pParameters=params;
|
||||
using Serialize=HRESULT(WINAPI*)(const D3D12_ROOT_SIGNATURE_DESC*,D3D_ROOT_SIGNATURE_VERSION,ID3DBlob**,ID3DBlob**);
|
||||
Ref<ID3DBlob> serialized,serializeError;require(symbol<Serialize>(c.dll,"D3D12SerializeRootSignature")(&desc,D3D_ROOT_SIGNATURE_VERSION_1,&serialized.p,&serializeError.p),"serialize root");
|
||||
require(c.device->CreateRootSignature(0,serialized->GetBufferPointer(),serialized->GetBufferSize(),__uuidof(ID3D12RootSignature),root.out()),"CreateRootSignature");
|
||||
D3D12_COMPUTE_PIPELINE_STATE_DESC pd{};pd.pRootSignature=root.p;pd.CS={binary->GetBufferPointer(),binary->GetBufferSize()};require(c.device->CreateComputePipelineState(&pd,__uuidof(ID3D12PipelineState),pipeline.out()),"CreateComputePipelineState");
|
||||
}
|
||||
void dispatch(Queue& q,Buffer& src,Buffer& dst,UINT count,UINT salt,UINT stride){
|
||||
q.begin();q.transition(dst.resource.p,D3D12_RESOURCE_STATE_COMMON,D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
|
||||
q.list->SetPipelineState(pipeline.p);q.list->SetComputeRootSignature(root.p);q.list->SetComputeRootShaderResourceView(0,src.resource->GetGPUVirtualAddress());q.list->SetComputeRootUnorderedAccessView(1,dst.resource->GetGPUVirtualAddress());UINT values[]={count,salt,stride};q.list->SetComputeRoot32BitConstants(2,3,values,0);q.list->Dispatch(4,1,1);
|
||||
q.transition(dst.resource.p,D3D12_RESOURCE_STATE_UNORDERED_ACCESS,D3D12_RESOURCE_STATE_COMMON);q.finish();
|
||||
}
|
||||
};
|
||||
static uint32_t pattern(UINT64 i,UINT seed){uint32_t x=uint32_t(i)^seed;x^=x>>16;x*=0x7FEB352Du;x^=x>>15;x*=0x846CA68Bu;return x^(x>>16);}
|
||||
static void compare(const char* label,const std::array<uint32_t,256>& expected,void* cpu){
|
||||
auto p=static_cast<volatile uint32_t*>(cpu);size_t n=0;for(size_t i=0;i<256;++i)n+=p[i]==expected[i];std::printf("VERIFY %s matches=%zu/256 first_actual=%08X first_expected=%08X\n",label,n,p[0],expected[0]);if(n!=256)throw std::runtime_error("GPU checksum mismatch");
|
||||
}
|
||||
static void stage(const char* name,void* pointer=nullptr){
|
||||
std::printf("STAGE %s cpu_ptr=%p\n",name,pointer);
|
||||
// Host snapshots happen while no GPU work is pending; never in latency windows.
|
||||
if(std::getchar()==EOF)throw std::runtime_error("stage handshake lost");
|
||||
}
|
||||
static void coherent(Context& c,bool omitDispatch=false){
|
||||
Shader shader(c);Queue q(c.device.p);Buffer src,dst;src.allocate(c.device.p,65536,"wb");src.map();dst.allocate(c.device.p,65536,"wb",true);dst.map();
|
||||
for(UINT round=0;round<3;++round){
|
||||
auto p=static_cast<volatile uint32_t*>(src.cpu);std::array<uint32_t,256> expected{};UINT salt=0x100103u*(round+1);
|
||||
for(UINT i=0;i<16384;++i){uint32_t v=pattern(i,0x3412198u+round);p[i]=v;expected[i%256]^=v+salt;}
|
||||
// Poison result on CPU before every dispatch so an omitted shader cannot pass.
|
||||
auto output=static_cast<volatile uint32_t*>(dst.cpu);for(UINT i=0;i<256;++i)output[i]=0xDEADC0DEu;_mm_sfence();
|
||||
if(!omitDispatch)shader.dispatch(q,src,dst,16384,salt,1);
|
||||
compare("direct_shader_same_cpu_pointer",expected,dst.cpu);
|
||||
std::printf("COHERENCE_ROUND %u input_ptr=%p output_ptr=%p shader_read_words=16384 shader_written_words=256\n",round,src.cpu,dst.cpu);
|
||||
}
|
||||
}
|
||||
static void memory(Context& c,const std::string& type,UINT64 bytes){
|
||||
// Warm shader, queue and tiny result resources BEFORE the baseline snapshot.
|
||||
Shader shader(c);Queue q(c.device.p);Buffer small,out;small.allocate(c.device.p,65536,"upload");small.map();std::memset(small.cpu,0,65536);out.allocate(c.device.p,65536,"wb",true);out.map();shader.dispatch(q,small,out,1,0,1);small.release();
|
||||
std::printf("MEMORY type=%s bytes=%llu\n",type.c_str(),bytes);stage("baseline");
|
||||
Buffer src;void* cpu=nullptr;
|
||||
if(type=="cpu"){cpu=VirtualAlloc(nullptr,bytes,MEM_COMMIT|MEM_RESERVE,PAGE_READWRITE);if(!cpu)throw std::runtime_error("VirtualAlloc control");}
|
||||
else src.allocate(c.device.p,bytes,type);
|
||||
stage("created");
|
||||
if(type!="cpu"){src.map();cpu=src.cpu;}stage("mapped",cpu);
|
||||
auto p=static_cast<volatile uint32_t*>(cpu);std::array<uint32_t,256> expected{};UINT64 words=bytes/4;
|
||||
for(UINT64 i=0;i<words;++i){uint32_t value=pattern(i,0x24681357u);p[i]=value;expected[i%256]^=value+0x10101u;}_mm_sfence();
|
||||
stage("fully_initialized",cpu);
|
||||
if(type!="cpu"){shader.dispatch(q,src,out,UINT(words),0x10101u,1);compare("full_allocation_shader_read",expected,out.cpu);}else std::puts("GPU_PASS NOT_RUN CPU_control");
|
||||
stage("gpu_complete",cpu);
|
||||
if(type=="cpu")VirtualFree(cpu,0,MEM_RELEASE);else src.release();
|
||||
stage("released");
|
||||
}
|
||||
static void dirty(Context& c,const std::string& type,UINT stride,UINT session){
|
||||
const UINT64 bytes=268435456;const UINT pages=UINT(bytes/stride);Shader shader(c);Queue copy(c.device.p),verify(c.device.p);Buffer src,out,read;
|
||||
src.allocate(c.device.p,bytes,type);src.map();out.allocate(c.device.p,65536,"wb",true);out.map();read.allocate(c.device.p,128,"readback");read.map();
|
||||
std::memset(src.cpu,0,bytes);_mm_sfence();std::vector<uint32_t> pageValues(pages,0);
|
||||
// Both heap types use identical GENERIC_READ source states and no source barriers.
|
||||
copy.begin();copy.list->CopyBufferRegion(read.resource.p,0,src.resource.p,0,64);copy.list->CopyBufferRegion(read.resource.p,64,src.resource.p,bytes-stride,64);copy.close();
|
||||
std::vector<UINT> ks={0,1,64,4096,pages};std::rotate(ks.begin(),ks.begin()+session%ks.size(),ks.end());
|
||||
for(UINT k:ks){
|
||||
std::vector<double> times;int matches=0;
|
||||
for(int iteration=-5;iteration<30;++iteration){
|
||||
double dirtyStart=ticks();
|
||||
for(UINT j=0;j<k;++j){UINT page=k==1?0:UINT(UINT64(j)*(pages-1)/(k-1));uint32_t value=pattern(UINT64(page)+UINT64(iteration+5)*pages,0xAB3000u+session*17+k);*reinterpret_cast<volatile uint32_t*>(static_cast<unsigned char*>(src.cpu)+UINT64(page)*stride)=value;pageValues[page]=value;}
|
||||
_mm_sfence();double dirtyMs=(ticks()-dirtyStart)*1000.0/frequency();double start=ticks();copy.executeClosed();double ms=(ticks()-start)*1000.0/frequency();require(c.device->GetDeviceRemovedReason(),"dirty device status");
|
||||
auto rp=static_cast<volatile uint32_t*>(read.cpu);bool sentinels=rp[0]==pageValues[0]&&rp[16]==pageValues[pages-1];for(int i=1;i<16;++i)sentinels=sentinels&&rp[i]==0&&rp[16+i]==0;
|
||||
std::array<uint32_t,256> expected{};for(UINT i=0;i<pages;++i)expected[i%256]^=pageValues[i]+0x321u;
|
||||
// Additional full page-first-word validation is outside the timed window.
|
||||
shader.dispatch(verify,src,out,pages,0x321u,stride/4);
|
||||
auto op=static_cast<volatile uint32_t*>(out.cpu);bool all=sentinels;for(UINT i=0;i<256;++i)all=all&&op[i]==expected[i];
|
||||
if(iteration>=0){times.push_back(ms);matches+=all;std::printf("DIRTY_SAMPLE type=%s stride=%u session=%u k=%u iteration=%d dirty_cpu_ms=%.6f ms=%.6f match=%d\n",type.c_str(),stride,session,k,iteration,dirtyMs,ms,all);}
|
||||
if(!all)throw std::runtime_error("dirty page validation");
|
||||
}
|
||||
std::sort(times.begin(),times.end());std::printf("DIRTY_RESULT type=%s bytes=%llu stride=%u total_pages=%u session=%u k=%u n=30 median_ms=%.6f p10_ms=%.6f p90_ms=%.6f matches=%d/30\n",type.c_str(),bytes,stride,pages,session,k,(times[14]+times[15])/2,times[2],times[26],matches);
|
||||
}
|
||||
}
|
||||
static void watch(){
|
||||
auto p=static_cast<unsigned char*>(VirtualAlloc(nullptr,65536,MEM_COMMIT|MEM_RESERVE|MEM_WRITE_WATCH,PAGE_READWRITE));if(!p)throw std::runtime_error("writewatch allocation");
|
||||
const std::vector<std::vector<UINT>> cases={{0},{4096},{12288},{16383},{16384},{0,4096},{0,4096,8192,12288},{12288,16384},{16383,16384}};
|
||||
for(size_t c=0;c<cases.size();++c){
|
||||
require(HRESULT_FROM_WIN32(ResetWriteWatch(p,65536)),"ResetWriteWatch");
|
||||
for(UINT off:cases[c])*reinterpret_cast<volatile unsigned char*>(p+off)=0x6B;
|
||||
PVOID addresses[64]{};ULONG_PTR count=64;DWORD gran=0;UINT rc=GetWriteWatch(WRITE_WATCH_FLAG_RESET,p,65536,addresses,&count,&gran);
|
||||
std::printf("WATCH case=%zu writes=",c);for(UINT off:cases[c])std::printf("%u,",off);std::printf(" return=%u count=%llu granularity=%lu dirty=",rc,(unsigned long long)count,gran);if(!rc)for(ULONG_PTR i=0;i<count;++i)std::printf("%llu,",(unsigned long long)(static_cast<unsigned char*>(addresses[i])-p));std::puts("");if(rc)throw std::runtime_error("GetWriteWatch failed");
|
||||
count=64;gran=0;rc=GetWriteWatch(0,p,65536,addresses,&count,&gran);std::printf("WATCH_AFTER_RESET case=%zu return=%u count=%llu granularity=%lu\n",c,rc,(unsigned long long)count,gran);if(rc||count)throw std::runtime_error("writewatch reset not empty");
|
||||
}
|
||||
VirtualFree(p,0,MEM_RELEASE);
|
||||
}
|
||||
static void textures(Context& c){
|
||||
Queue q(c.device.p);
|
||||
for(auto layout:{D3D12_TEXTURE_LAYOUT_UNKNOWN,D3D12_TEXTURE_LAYOUT_ROW_MAJOR}){
|
||||
D3D12_RESOURCE_DESC td{};td.Dimension=D3D12_RESOURCE_DIMENSION_TEXTURE2D;td.Width=65;td.Height=37;td.DepthOrArraySize=1;td.MipLevels=1;td.Format=DXGI_FORMAT_R8G8B8A8_UNORM;td.SampleDesc.Count=1;td.Layout=layout;
|
||||
if(layout==D3D12_TEXTURE_LAYOUT_ROW_MAJOR)td.Flags=D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER;
|
||||
auto ai=c.device->GetResourceAllocationInfo(0,1,&td);std::printf("TEXTURE layout=%d allocation_bytes=%llu alignment=%llu\n",layout,ai.SizeInBytes,ai.Alignment);
|
||||
if(ai.SizeInBytes==~UINT64(0)||!ai.Alignment){std::puts("TEXTURE_UNSUPPORTED allocation info invalid");continue;}
|
||||
Ref<ID3D12Heap> h;D3D12_HEAP_DESC hd{};hd.SizeInBytes=ai.SizeInBytes;hd.Alignment=ai.Alignment;hd.Properties=properties(D3D12_HEAP_TYPE_CUSTOM);hd.Properties.CPUPageProperty=D3D12_CPU_PAGE_PROPERTY_WRITE_BACK;hd.Properties.MemoryPoolPreference=D3D12_MEMORY_POOL_L0;
|
||||
if(layout==D3D12_TEXTURE_LAYOUT_ROW_MAJOR){hd.Properties=properties(D3D12_HEAP_TYPE_DEFAULT);hd.Flags=D3D12_HEAP_FLAG_SHARED|D3D12_HEAP_FLAG_SHARED_CROSS_ADAPTER;}
|
||||
HRESULT heapResult=c.device->CreateHeap(&hd,__uuidof(ID3D12Heap),h.out());report(heapResult,"texture heap");if(FAILED(heapResult)){if(layout==D3D12_TEXTURE_LAYOUT_UNKNOWN)require(heapResult,"required UNKNOWN texture heap");std::puts("TEXTURE_NOT_RUN heap unsupported");continue;}Ref<ID3D12Resource> t;HRESULT created=c.device->CreatePlacedResource(h.p,0,&td,D3D12_RESOURCE_STATE_COMMON,nullptr,__uuidof(ID3D12Resource),t.out());report(created,"placed texture");if(FAILED(created))continue;
|
||||
// UNKNOWN: request access without asking runtime to disclose opaque layout.
|
||||
void* pointer=nullptr;HRESULT mapped=layout==D3D12_TEXTURE_LAYOUT_UNKNOWN?t->Map(0,nullptr,nullptr):S_OK;if(layout==D3D12_TEXTURE_LAYOUT_UNKNOWN)report(mapped,"texture Map");else std::puts("TEXTURE Map NOT_RUN CPU-inaccessible DEFAULT cross-adapter heap");std::printf("TEXTURE layout=%d returned_cpu_ptr=%p pointer_requested=%d\n",layout,pointer,0);if(FAILED(mapped))continue;
|
||||
std::vector<uint32_t> input(65*37);for(UINT i=0;i<input.size();++i)input[i]=pattern(i,0x12345678u);
|
||||
if(layout==D3D12_TEXTURE_LAYOUT_UNKNOWN){HRESULT w=t->WriteToSubresource(0,nullptr,input.data(),65*4,65*37*4);report(w,"WriteToSubresource");require(w,"required UNKNOWN CPU write");}
|
||||
D3D12_PLACED_SUBRESOURCE_FOOTPRINT fp{};UINT rows=0;UINT64 rowBytes=0,total=0;c.device->GetCopyableFootprints(&td,0,1,0,&fp,&rows,&rowBytes,&total);std::printf("TEXTURE_FOOTPRINT layout=%d rows=%u row_bytes=%llu row_pitch=%u total_bytes=%llu offset=%llu\n",layout,rows,rowBytes,fp.Footprint.RowPitch,total,fp.Offset);
|
||||
Buffer upload;if(layout==D3D12_TEXTURE_LAYOUT_ROW_MAJOR){
|
||||
upload.allocate(c.device.p,total,"upload");upload.map();std::memset(upload.cpu,0,total);for(UINT y=0;y<37;++y)std::memcpy(static_cast<unsigned char*>(upload.cpu)+fp.Offset+UINT64(y)*fp.Footprint.RowPitch,input.data()+y*65,260);_mm_sfence();
|
||||
D3D12_TEXTURE_COPY_LOCATION fromUpload{},toTexture{};fromUpload.pResource=upload.resource.p;fromUpload.Type=D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;fromUpload.PlacedFootprint=fp;toTexture.pResource=t.p;toTexture.Type=D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
|
||||
q.begin();q.transition(t.p,D3D12_RESOURCE_STATE_COMMON,D3D12_RESOURCE_STATE_COPY_DEST);q.list->CopyTextureRegion(&toTexture,0,0,0,&fromUpload,nullptr);q.transition(t.p,D3D12_RESOURCE_STATE_COPY_DEST,D3D12_RESOURCE_STATE_COMMON);q.finish();
|
||||
}
|
||||
Buffer read;read.allocate(c.device.p,total,"readback");read.map();std::memset(read.cpu,0xA7,total);
|
||||
D3D12_TEXTURE_COPY_LOCATION from{},to{};from.pResource=t.p;from.Type=D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;from.SubresourceIndex=0;to.pResource=read.resource.p;to.Type=D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;to.PlacedFootprint=fp;
|
||||
double start=ticks();q.begin();q.transition(t.p,D3D12_RESOURCE_STATE_COMMON,D3D12_RESOURCE_STATE_COPY_SOURCE);q.list->CopyTextureRegion(&to,0,0,0,&from,nullptr);q.transition(t.p,D3D12_RESOURCE_STATE_COPY_SOURCE,D3D12_RESOURCE_STATE_COMMON);q.finish();double ms=(ticks()-start)*1000.0/frequency();
|
||||
size_t matches=0;for(UINT y=0;y<37;++y)for(UINT x=0;x<65;++x){auto row=reinterpret_cast<volatile uint32_t*>(static_cast<unsigned char*>(read.cpu)+fp.Offset+UINT64(y)*fp.Footprint.RowPitch);matches+=row[x]==input[y*65+x];}
|
||||
std::printf("TEXTURE_GPU_READBACK layout=%d matches=%zu/2405 ms=%.6f\n",layout,matches,ms);if(matches!=2405)throw std::runtime_error("texture GPU mismatch");if(layout==D3D12_TEXTURE_LAYOUT_UNKNOWN)t->Unmap(0,nullptr);
|
||||
}
|
||||
}
|
||||
int main(int argc,char** argv){
|
||||
setvbuf(stdout,nullptr,_IONBF,0);
|
||||
try{
|
||||
if(argc<2)throw std::runtime_error("usage: phase2 identity|coherence|watch|texture|memory TYPE BYTES|dirty TYPE STRIDE SESSION");
|
||||
std::printf("PHASE2 protocol=1 mode=%s guest_pid=%lu\n",argv[1],GetCurrentProcessId());
|
||||
if(std::string(argv[1])=="watch"){watch();std::puts("END success");return 0;}
|
||||
Context c;
|
||||
if(std::string(argv[1])=="identity")identity(c);
|
||||
else if(std::string(argv[1])=="coherence")coherent(c);
|
||||
else if(std::string(argv[1])=="negative-control")coherent(c,true);
|
||||
else if(std::string(argv[1])=="texture")textures(c);
|
||||
else if(std::string(argv[1])=="memory"&&argc==4)memory(c,argv[2],std::strtoull(argv[3],nullptr,10));
|
||||
else if(std::string(argv[1])=="dirty"&&argc==5)dirty(c,argv[2],UINT(std::strtoul(argv[3],nullptr,10)),UINT(std::strtoul(argv[4],nullptr,10)));
|
||||
else throw std::runtime_error("invalid mode or arguments");
|
||||
std::puts("END success");return 0;
|
||||
}catch(const std::exception& e){std::printf("END failure reason=%s\n",e.what());return 1;}
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
# Review of the M5 report and baseline source
|
||||
|
||||
Reviewed 2026-11-26: [2elliti's comment](https://github.com/MacosPorters/betterxen/issues/473#issuecomment-7201953364) and the actual [baseline source at 9ae6d1e](https://github.com/MacosPorters/betterxen/blob/9ae6d1ee7092b6021aad075531f50ba60de4fd53/docs/research/d3dmetal-zero-copy/probe.cpp). Public API expectations were re-derived from the Microsoft pages below, rather than treating either contributor's conclusions as ground truth. This is a technical source audit, not independent certification of the original author's probe or of the new supplemental code.
|
||||
|
||||
## What the M5 report establishes
|
||||
|
||||
The reported M5 has 17179869184 bytes RAM, macOS 27.0.1 (26A434), and CrossOver 26.3.0.39832. The report says the baseline source hash matched and all non-timing outcomes agreed with the M4 across five runs. The M5 used win10_64, bx-cli from cc5ce59, an empty shim directory and a 90-second timeout. Our M4 used the shared runner, win11_64 and 30 seconds. The M5 captured libd3dshared, which CrossOver also uses when D3DMetal is disabled; that alone does not identify the D3D12 backend. Its backend attribution therefore remains partial as the author states. This review did not obtain the private second probe or independently inspect the reported M5 raw logs: numerical M5 values below are attributed reports, not newly verified hardware measurements.
|
||||
|
||||
| Run | WB 64 KiB | WB 256 MiB | WC 256 MiB | UPLOAD 256 MiB |
|
||||
| --- | ---: | ---: | ---: | ---: |
|
||||
| M4 initial | 0.515898 | 0.773432 | 0.294052 | 0.252970 |
|
||||
| M4 shared runner | 0.288957 | 0.299042 | 0.249347 | 0.204955 |
|
||||
| M5 reported 1 | 0.607320 | 0.638232 | 0.449325 | 0.244737 |
|
||||
| M5 reported 2 | 0.542233 | 0.663497 | 0.476485 | 0.233453 |
|
||||
| M5 reported 3, OS polling | 0.430563 | 0.416307 | 0.419900 | 0.460607 |
|
||||
| M5 reported 4, OS polling | 0.467363 | 0.615115 | 0.491113 | 0.244192 |
|
||||
| M5 reported 5, OS polling | 0.479218 | 0.483435 | 0.466577 | 0.285473 |
|
||||
|
||||
Units: average ms/submit; each reported row had 40/40 timed and 5/5 warmup matches. Heap rankings are not stable. Different launch protocols, background polling, one chip of each type and large within-host variation prevent a generational speed comparison. A reproduction of the same source also reproduces any source defect; it is not an independently implemented oracle. The independent second M5 probe's reported AMD Compatibility Mode identity is a useful lead, not proof of physical GPU topology or a second independent data check for CUSTOM WB/L0, which that probe skipped.
|
||||
|
||||
## Claim-by-claim API and source assessment
|
||||
|
||||
| Material claim | Re-derived assessment and public primary reference |
|
||||
| --- | --- |
|
||||
| CPU-visible L0 CUSTOM heaps are UMA-only | Incorrect; 2elliti's correction is supported. For UMA=false, UPLOAD maps to WRITE_COMBINE/L0 and READBACK to WRITE_BACK/L0. DEFAULT maps to NOT_AVAILABLE/L1. Successful L0 creation does not establish awareness of physical unified memory. [GetCustomHeapProperties](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device-getcustomheapproperties%28uint_d3d12_heap_type%29). |
|
||||
| L1 control distinguishes physical architectures | It does not. L1 is unavailable on UMA; CPU-visible L1 is invalid on NUMA. E_INVALIDARG is the observed runtime result, not a promise that every implementation must return exactly that HRESULT. [Memory pools](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ne-d3d12-d3d12_memory_pool), [heap properties](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ns-d3d12-d3d12_heap_properties). |
|
||||
| Check 5 measures allocation-sized transfer cost | Source inspection confirms only two 64-byte copies. The allocation's size changes the final source address, not copied byte count. Its timer also includes CPU stores, reset/encoding, barriers, fence wait and verification. [CopyBufferRegion](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12graphicscommandlist-copybufferregion). |
|
||||
| UPLOAD and CUSTOM benchmark times are directly comparable | Source inspection confirms two source-state transitions for CUSTOM and none for UPLOAD. GENERIC_READ includes COPY_SOURCE and UPLOAD must remain in it. The baseline cannot fairly rank heap types. Supplemental dirty tests use GENERIC_READ for all sources and reuse pre-recorded command lists with no source barriers. [Resource states and barriers](https://learn.microsoft.com/en-us/windows/win32/direct3d12/using-resource-barriers-to-synchronize-resource-states-in-direct3d-12). |
|
||||
| The timing rules out full-allocation copies | Too strong as a general mechanism claim. 256 MiB / 120 billion bytes/s is about 2.237 ms, but 120 GB/s was not measured here and is not a D3D12 guarantee. Read/write traffic, work overlap, caching, residency, compression and copying before the timing window matter. The source only establishes the observed elapsed times. Neither a theoretical bandwidth estimate nor flat timing proves physical sharing. |
|
||||
| Persistent-map coherence proves physical aliasing | No. Public D3D12 permits persistent mapping of CPU-accessible resources with application synchronization. CPU stores must complete before GPU execution, and the CPU must wait for GPU completion before reading its results. The baseline's fence-separated visibility can also be implemented by copies. [Map](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12resource-map), [SetEventOnCompletion](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12fence-seteventoncompletion). |
|
||||
| UNKNOWN texture Map supplies no ordinary texel pointer | The baseline asks for no pointer at all: ppData=nullptr. Thus it never measured a pointer-return failure. Microsoft describes opaque layouts as precluding pointer disclosure for normal texel manipulation; Map with null ppData enables the CPU subresource methods. Do not infer an ordinary guest-pointer alias for such textures. [Map](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12resource-map). |
|
||||
| Every texture therefore requires an explicit staging copy | Not established. WriteToSubresource permits CPU texture updates and documents possible near-zero-copy UMA optimizations. That does not guarantee the implementation's internal mechanism. Texture GPU readback must be tested separately, with layout/format constraints; ROW_MAJOR is not a general substitute for opaque layout. [WriteToSubresource](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12resource-writetosubresource), [ReadFromSubresource](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12resource-readfromsubresource). |
|
||||
| ROW_MAJOR creation success on an ordinary CPU-visible heap is portable evidence | No. The layout documentation requires a cross-adapter shared heap and limits textures to 2D, one mip/slice, 64 KiB alignment, no MSAA, no depth/stencil, no YUV. Phase two uses a DEFAULT shared-cross-adapter heap and ALLOW_CROSS_ADAPTER resource for this separate staging-copy control. It never reports a fabricated Map result when Map was not called. [Texture layouts](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ne-d3d12-d3d12_texture_layout), [shared heaps](https://learn.microsoft.com/en-us/windows/win32/direct3d12/shared-heaps), [resource flags](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ne-d3d12-d3d12_resource_flags). |
|
||||
| 0/16384 write-watch writes test 4 KiB subpages | No; they address different 16 KiB intervals. Separate tests at 4096, 8192, 12288 and the 16383/16384 boundary are required. GetWriteWatch reports dirty page addresses and its own granularity; reset tests must exclude concurrent writes. [GetWriteWatch](https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-getwritewatch). |
|
||||
| IsolatedMMU=false proves GPU writes cannot be reported by write-watch | Too categorical. TRUE indicates GPU honoring of CPU page-table properties; FALSE supplies no such guarantee. A translation implementation could still cause CPU-side bookkeeping or copies that mark pages. A fallback must not rely on GPU writes being tracked, but absence of tracking cannot be inferred as a universal measured fact from this flag. [Architecture1](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ns-d3d12-d3d12_feature_data_architecture1). |
|
||||
| 1x/2x footprint or a vmmap region label proves allocation identity | It does not. These are process-accounting observations influenced by graphics/driver charging, shared mappings, compression, allocator caches and sampling. A controlled slope across fully initialized sizes can reveal overhead in the observed accounting domain, but cannot identify physical pages or uncharged driver allocations. Microsoft's DXGI memory descriptions/budgets are also not a physical-page aliasing API. [DXGI adapter description](https://learn.microsoft.com/en-us/windows/win32/api/dxgi1_2/ns-dxgi1_2-dxgi_adapter_desc2), [QueryVideoMemoryInfo](https://learn.microsoft.com/en-us/windows/win32/api/dxgi1_4/nf-dxgi1_4-idxgiadapter3-queryvideomemoryinfo). |
|
||||
| Dirty-k timing slope alone identifies internal dirty-page copies | No. It can expose a cost correlated with changed pages, but CPU page faults/tracking, cache behavior, transfer at other times and scheduling are alternative explanations. Phase two records dirty-write time separately, times identical submit/fence work and validates checksums outside the window. |
|
||||
| OpenExistingHeapFrom* is the natural bridge on this installed stack | These public diagnostic APIs can expose system-memory heaps, but both observed versions returned E_NOTIMPL. Availability in Microsoft documentation does not imply implementation by D3DMetal. [Address API](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device3-openexistingheapfromaddress), [mapping API](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device3-openexistingheapfromfilemapping). |
|
||||
|
||||
The shared-heaps page itself has inconsistent wording about CPU page properties for cross-adapter heaps (a paragraph mentions WRITE_COMBINE; the subsequent limitations require DEFAULT or NOT_AVAILABLE/L0). This suite uses the unambiguous DEFAULT option, does not attempt CPU Map on that control, and does not generalize its result to CPU-visible shared heaps.
|
||||
|
||||
## Additional baseline audit observations
|
||||
|
||||
- Its six checks remain unchanged. Unsupported HRESULTs often return from a helper without incrementing the mismatch counter; exit 0 is not all-capabilities-supported. Read each result rather than the final counter alone.
|
||||
- Its 64 KiB prefault stride does not fully initialize the intervening host pages. Phase-two footprint tests write every 32-bit word with an index-mixed pattern instead.
|
||||
- The buffer coherence test performs copies, not shader reads/writes. The new shader test poisons the result before each dispatch, then validates three separate data rounds. An omitted-dispatch negative control must be detected.
|
||||
- Resources remain live through their fences. The baseline uses disjoint placed-resource regions rather than switching overlapping aliases. CreatePlacedResource's advanced model permits non-overlapping use without the simple model's activation bookkeeping; it does not excuse missing barriers when memory is actually aliased. [CreatePlacedResource](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device-createplacedresource).
|
||||
- No GPU texture readback, arbitrary-memory integration, lifetime stress, memory-overhead study, GPU write-watch tracking or valid concurrent CPU/GPU atomic protocol can be inferred from the baseline.
|
||||
|
||||
The proposed concurrent-visibility experiment is assessed separately in [concurrent-review.md](concurrent-review.md). It is not a conformance gate and is not executed by the standardized synchronized suite.
|
||||
@@ -0,0 +1,222 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Protocol 1 supplemental suite, separate from all six frozen baseline checks."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import plistlib
|
||||
import shutil
|
||||
import signal
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
|
||||
|
||||
def sha(p):
|
||||
return hashlib.sha256(p.read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def capture(cmd, env, cwd, timeout=15):
|
||||
start = time.monotonic()
|
||||
try:
|
||||
p = subprocess.run([str(x) for x in cmd], env=env, cwd=cwd,
|
||||
capture_output=True, timeout=timeout)
|
||||
return {"command": [str(x) for x in cmd], "exit": p.returncode,
|
||||
"stdout": p.stdout.decode(errors="replace"),
|
||||
"stderr": p.stderr.decode(errors="replace"),
|
||||
"elapsed_seconds": time.monotonic() - start}
|
||||
except subprocess.TimeoutExpired as e:
|
||||
return {"command": [str(x) for x in cmd], "exit": 124, "timeout": True,
|
||||
"stdout": (e.stdout or b"").decode(errors="replace"),
|
||||
"stderr": (e.stderr or b"").decode(errors="replace")}
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description=__doc__)
|
||||
ap.add_argument("--bottle", required=True, type=Path)
|
||||
ap.add_argument("--scratch", required=True, type=Path)
|
||||
ap.add_argument("--modes", default="identity,coherence,negative-control,watch,texture,dirty,memory")
|
||||
ap.add_argument("--sessions", type=int, default=3, choices=[1, 2, 3])
|
||||
ap.add_argument("--memory-repeats", type=int, default=2, choices=[1, 2, 3])
|
||||
ap.add_argument("--large", action="store_true", help="also 2 GiB footprint cases; requires >=24 GiB RAM")
|
||||
ap.add_argument("--crossover", type=Path, default=Path("/Applications/CrossOver.app"))
|
||||
args = ap.parse_args()
|
||||
src = Path(__file__).resolve().parent
|
||||
repo = src.parents[3]
|
||||
base = args.scratch.expanduser().resolve()
|
||||
if base.exists() or base == repo or repo in base.parents:
|
||||
ap.error("scratch must be a new directory outside the checkout")
|
||||
bottle = args.bottle.expanduser().resolve()
|
||||
if not (bottle / "cxbottle.conf").is_file():
|
||||
ap.error("bottle must be an existing CrossOver bottle")
|
||||
original = (bottle / "cxbottle.conf").read_bytes()
|
||||
if b'"WineArch" = "win64"' not in original:
|
||||
ap.error("requires win64 bottle")
|
||||
modes = args.modes.split(",")
|
||||
if set(modes) - {"identity", "coherence", "negative-control", "watch", "texture", "dirty", "memory"}:
|
||||
ap.error("unknown mode")
|
||||
base.mkdir(parents=True, mode=0o700)
|
||||
env = {k: os.environ[k] for k in ["HOME", "USER", "LOGNAME", "PATH", "LANG", "LC_ALL", "DISPLAY"] if k in os.environ}
|
||||
env.update(TMPDIR=str(base) + "/", ROSETTA_ADVERTISE_AVX="1", CX_GRAPHICS_BACKEND="d3dmetal", WINEDEBUG="-all")
|
||||
cx = args.crossover.resolve() / "Contents/SharedSupport/CrossOver"
|
||||
wine = cx / "bin/wine"
|
||||
exe = base / "phase2.exe"
|
||||
observer = base / "observe"
|
||||
receipt = {"protocol": 1, "recorded_utc": datetime.now(timezone.utc).isoformat(),
|
||||
"modes": modes, "sessions": args.sessions, "memory_repeats": args.memory_repeats,
|
||||
"environment": {k: env[k] for k in ["ROSETTA_ADVERTISE_AVX", "CX_GRAPHICS_BACKEND", "WINEDEBUG"]},
|
||||
"source_hashes": {p.name: sha(p) for p in src.iterdir() if p.suffix in [".cpp", ".py"]},
|
||||
"baseline_sha256": sha(src.parent / "probe.cpp"), "tools": {}, "cases": []}
|
||||
commands = {
|
||||
"chip": ["sysctl", "-n", "machdep.cpu.brand_string"],
|
||||
"ram": ["sysctl", "-n", "hw.memsize"], "macos": ["sw_vers"],
|
||||
"host_page_size": ["sysctl", "-n", "hw.pagesize"],
|
||||
"crossover": [wine, "--version"], "rosetta": ["pkgutil", "--pkg-info", "com.apple.pkg.RosettaUpdateAuto"],
|
||||
"gcc": ["x86_64-w64-mingw32-g++", "--version"],
|
||||
"clang": ["xcrun", "clang++", "--version"], "sdk": ["xcrun", "--show-sdk-version"],
|
||||
"pressure_before": ["memory_pressure", "-Q"], "vm_before": ["vm_stat"],
|
||||
"load_before": ["ps", "-axo", "pid,pcpu,comm"],
|
||||
"build_pe": ["x86_64-w64-mingw32-g++", "-std=c++20", "-O2", "-static", "-static-libgcc", "-static-libstdc++", "-Wall", "-Wextra", "-Werror", src / "probe.cpp", "-o", exe, "-lkernel32"],
|
||||
"build_observer": ["xcrun", "clang++", "-std=c++20", "-O2", "-arch", "arm64", "-Wall", "-Wextra", "-Werror", src / "observe.cpp", "-o", observer],
|
||||
"binary_formats": ["file", exe, observer], "observer_arch": ["lipo", "-archs", observer],
|
||||
"observer_links": ["otool", "-L", observer],
|
||||
}
|
||||
for name, cmd in commands.items():
|
||||
receipt["tools"][name] = capture(cmd, env, base, timeout=45)
|
||||
if name.startswith("build_") and receipt["tools"][name]["exit"]:
|
||||
(base / "receipt.json").write_text(json.dumps(receipt, indent=2))
|
||||
raise RuntimeError(receipt["tools"][name])
|
||||
receipt["binary_hashes"] = {"phase2.exe": sha(exe), "observe": sha(observer)}
|
||||
ram = int(receipt["tools"]["ram"]["stdout"].strip())
|
||||
if args.large and ram < 24 * 1024**3:
|
||||
ap.error("--large requires >=24 GiB; common profile is identical on 16/24 GiB hosts")
|
||||
framework = cx / "lib64/apple_gptk/external/D3DMetal.framework/Versions/A/Resources"
|
||||
receipt["framework"] = {p.name: plistlib.loads(p.read_bytes()) for p in framework.glob("*.plist")}
|
||||
for p in [cx / "lib64/apple_gptk/wine/x86_64-windows/d3d12.dll", cx / "lib/wine/x86_64-windows/d3dcompiler_47.dll"]:
|
||||
receipt.setdefault("installed_dll_hashes", {})[str(p)] = sha(p)
|
||||
temp = base / "bottle"
|
||||
shutil.copytree(bottle, temp, symlinks=True)
|
||||
conf = original.decode().replace("[Bottle]", '[Bottle]\n"AllowUntrusted" = "1"', 1)
|
||||
conf += '\n[EnvironmentVariables]\n"CX_GRAPHICS_BACKEND" = "d3dmetal"\n[CrossOver]\n"AntiVirusScan" = "untrusted"\n'
|
||||
(temp / "cxbottle.conf").write_text(conf)
|
||||
receipt["source_bottle_config_sha256"] = hashlib.sha256(original).hexdigest()
|
||||
receipt["temporary_bottle_config"] = {"template": "inherited; inspect source config", "architecture": "win64", "backend": "d3dmetal", "no_update": True, "AntiVirusScan": "untrusted", "AllowUntrusted": 1}
|
||||
common = [str(wine), "--bottle", str(temp), "--no-update", "--no-gui", str(exe)]
|
||||
backend_seen = False
|
||||
|
||||
def run_case(name, argv, memory=False):
|
||||
nonlocal backend_seen
|
||||
case = base / name
|
||||
case.mkdir()
|
||||
metadata = {"expected_exit": 1 if argv[0] == "negative-control" else 0, "name": name, "args": argv, "command": common + argv, "timeout_seconds": 150 if memory else 90, "snapshots": []}
|
||||
stdout = case / "stdout.txt"
|
||||
stderr = case / "stderr.txt"
|
||||
timed_out = threading.Event()
|
||||
start = time.monotonic()
|
||||
with stdout.open("wb") as out, stderr.open("wb") as err:
|
||||
p = subprocess.Popen(common + argv, env=env, cwd=case, stdin=subprocess.PIPE,
|
||||
stdout=subprocess.PIPE, stderr=err, start_new_session=True)
|
||||
def expire():
|
||||
timed_out.set()
|
||||
try:
|
||||
os.killpg(p.pid, signal.SIGKILL)
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
timer = threading.Timer(metadata["timeout_seconds"], expire)
|
||||
timer.start()
|
||||
hostpid = None
|
||||
try:
|
||||
for line in p.stdout:
|
||||
out.write(line)
|
||||
out.flush()
|
||||
if not line.startswith(b"STAGE "):
|
||||
continue
|
||||
if hostpid is None:
|
||||
found = capture(["lsof", "-t", "-a", "-c", "phase2.exe", str(exe)], env, base)
|
||||
candidates = sorted({int(x) for x in found["stdout"].split() if x.isdigit()})
|
||||
if len(candidates) != 1:
|
||||
metadata["pid_lookup"] = found
|
||||
raise RuntimeError("need exactly one process mapping this scratch PE")
|
||||
hostpid = candidates[0]
|
||||
metadata["host_pid"] = hostpid
|
||||
phase = line.decode().split()[1]
|
||||
snap = {"phase": phase, "marker": line.decode().strip(), "samples": []}
|
||||
for _ in range(3):
|
||||
sample = capture([observer, str(hostpid)], env, base)
|
||||
try:
|
||||
sample["data"] = json.loads(sample["stdout"])
|
||||
except json.JSONDecodeError:
|
||||
pass
|
||||
snap["samples"].append(sample)
|
||||
for tool, command in {
|
||||
"footprint": ["footprint", "-p", str(hostpid), "-f", "bytes"],
|
||||
"vmmap": ["vmmap", "-summary", str(hostpid)],
|
||||
"vmstat": ["vm_stat"], "pressure": ["memory_pressure", "-Q"],
|
||||
}.items():
|
||||
result = capture(command, env, base, timeout=12)
|
||||
(case / f"{phase}-{tool}.json").write_text(json.dumps(result, indent=2))
|
||||
snap[tool] = {"exit": result["exit"], "file": f"{phase}-{tool}.json"}
|
||||
if not backend_seen:
|
||||
result = capture(["lsof", "-n", "-p", str(hostpid)], env, base)
|
||||
metadata["backend_paths_excerpt"] = ["/" + line.split("/", 1)[1] for line in result["stdout"].splitlines() if any(key in line for key in ["apple_gptk/wine/x86_64-windows/d3d12.dll", "apple_gptk/wine/x86_64-windows/dxgi.dll", "D3DMetal.framework/Versions/A/D3DMetal", "/rosetta/runtime"])]
|
||||
backend_seen = any("/D3DMetal" in path for path in metadata["backend_paths_excerpt"])
|
||||
metadata["snapshots"].append(snap)
|
||||
p.stdin.write(b"\n")
|
||||
p.stdin.flush()
|
||||
p.wait()
|
||||
except BaseException:
|
||||
try:
|
||||
os.killpg(p.pid, signal.SIGKILL)
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
p.wait()
|
||||
raise
|
||||
finally:
|
||||
timer.cancel()
|
||||
metadata.update(exit=p.returncode, timed_out=timed_out.is_set(), elapsed_seconds=time.monotonic() - start)
|
||||
(case / "case.json").write_text(json.dumps(metadata, indent=2))
|
||||
receipt["cases"].append(metadata)
|
||||
(base / "receipt.json").write_text(json.dumps(receipt, indent=2))
|
||||
if argv[0] == "negative-control":
|
||||
metadata["negative_control_detected"] = b"END failure reason=GPU checksum mismatch" in stdout.read_bytes()
|
||||
if not metadata["negative_control_detected"]:
|
||||
raise RuntimeError("negative control did not detect an omitted dispatch")
|
||||
print(name, "exit", metadata["exit"], "expected", metadata["expected_exit"], "timeout", metadata["timed_out"], flush=True)
|
||||
|
||||
try:
|
||||
for mode in ["identity", "coherence", "negative-control", "watch", "texture"]:
|
||||
if mode in modes:
|
||||
run_case(mode, [mode])
|
||||
if "dirty" in modes:
|
||||
for session in range(args.sessions):
|
||||
for stride in [4096, 16384]:
|
||||
# Alternate heap order; no background OS polling during latency cases.
|
||||
types = ["wb", "wc", "upload"]
|
||||
if session % 2:
|
||||
types.reverse()
|
||||
for heap in types:
|
||||
run_case(f"dirty-{heap}-{stride}-s{session}", ["dirty", heap, str(stride), str(session)])
|
||||
if "memory" in modes:
|
||||
for repeat in range(args.memory_repeats):
|
||||
for size in [64, 256, 1024] + ([2048] if args.large else []):
|
||||
for heap in ["cpu", "wb", "upload"]:
|
||||
run_case(f"memory-{heap}-{size}MiB-r{repeat}", ["memory", heap, str(size * 1024**2)], memory=True)
|
||||
finally:
|
||||
receipt["tools"]["pressure_after"] = capture(["memory_pressure", "-Q"], env, base)
|
||||
receipt["tools"]["vm_after"] = capture(["vm_stat"], env, base)
|
||||
receipt["source_bottle_config_unchanged"] = (bottle / "cxbottle.conf").read_bytes() == original
|
||||
stop = dict(env, WINEPREFIX=str(temp))
|
||||
receipt["server_stop"] = capture([cx / "bin/wineserver", "-k"], stop, base)
|
||||
receipt["server_wait"] = capture([cx / "bin/wineserver", "-w"], stop, base)
|
||||
shutil.rmtree(temp)
|
||||
(base / "receipt.json").write_text(json.dumps(receipt, indent=2) + "\n")
|
||||
failures = [c["name"] for c in receipt["cases"] if c["exit"] != c["expected_exit"] or c["timed_out"]]
|
||||
print("Completed", len(receipt["cases"]), "cases; failures:", failures)
|
||||
return bool(failures)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Derive inspectable summaries from protocol-1 raw logs; never rewrite inputs."""
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import statistics
|
||||
|
||||
|
||||
def fields(line):
|
||||
return dict(re.findall(r"(\w+)=([^ ]+)", line))
|
||||
|
||||
|
||||
def summarize(root):
|
||||
result = {"memory": [], "dirty": [], "runs": []}
|
||||
for receipt in sorted(root.rglob("receipt.json")):
|
||||
doc = json.loads(receipt.read_text())
|
||||
if doc.get("protocol") != 1:
|
||||
continue
|
||||
result["runs"].append({"path": str(receipt.relative_to(root)),
|
||||
"source_hashes": doc["source_hashes"],
|
||||
"baseline_sha256": doc["baseline_sha256"]})
|
||||
for path in sorted(root.rglob("case.json")):
|
||||
case = json.loads(path.read_text())
|
||||
result.setdefault("outcomes", []).append({"path": str(path.relative_to(root)),
|
||||
"exit": case["exit"], "expected_exit": case.get("expected_exit", 0),
|
||||
"timed_out": case["timed_out"]})
|
||||
if case["name"].startswith("memory-") and case.get("snapshots"):
|
||||
stages = {}
|
||||
for snapshot in case["snapshots"]:
|
||||
data = [sample["data"] for sample in snapshot["samples"]
|
||||
if sample.get("data", {}).get("return") == 0]
|
||||
if data:
|
||||
stages[snapshot["phase"]] = {key: statistics.median(d[key] for d in data)
|
||||
for key in ["phys_footprint", "resident_size", "wired_size", "pageins"]}
|
||||
baseline = stages["baseline"]["phys_footprint"]
|
||||
result["memory"].append({"name": case["name"], "args": case["args"], "stages": stages,
|
||||
"footprint_delta_bytes": {phase: values["phys_footprint"] - baseline for phase, values in stages.items()}})
|
||||
stdout = path.with_name("stdout.txt")
|
||||
if stdout.exists():
|
||||
lines = stdout.read_text().splitlines()
|
||||
samples = [fields(line) for line in lines if line.startswith("DIRTY_SAMPLE ")]
|
||||
for line in lines:
|
||||
if not line.startswith("DIRTY_RESULT "):
|
||||
continue
|
||||
row = fields(line)
|
||||
row["case"] = case["name"]
|
||||
matching = [s for s in samples if s["k"] == row["k"]]
|
||||
cpu = [float(s["dirty_cpu_ms"]) for s in matching if "dirty_cpu_ms" in s]
|
||||
row["median_dirty_cpu_ms"] = statistics.median(cpu) if cpu else None
|
||||
result["dirty"].append(row)
|
||||
return result
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("root", type=Path)
|
||||
args = parser.parse_args()
|
||||
print(json.dumps(summarize(args.root), indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,41 @@
|
||||
# Inverted ownership feasibility
|
||||
|
||||
This requirement matrix informs [#464](https://github.com/MacosPorters/betterxen/issues/464) without modifying or certifying it. The inspected in-tree contracts are pinned at research revision `9ae6d1ee7092b6021aad075531f50ba60de4fd53`: `abi/include/bx_xmem_internal.h`, `shims/xmem/xmem.cpp`, `shims/xmem/physical_pages.cpp` and `abi/defs/xmem.def`. They describe BetterXen's implementation, not an independently verified console allocation contract. Memory-attribute meanings not established by public evidence remain unknown.
|
||||
|
||||
A D3D12-owned mapped buffer is a candidate provider for a subset of allocations. It is not a general replacement for the present xmem allocation engines.
|
||||
|
||||
| Requirement | Evidence / feasibility | Necessary fallback or further work |
|
||||
| --- | --- | --- |
|
||||
| Ordinary CPU-visible byte allocation | Persistent buffer Map supported in baseline; A2 full-consumption checks add accounting evidence. Candidate within live resource lifetime. | Keep owner/resource metadata and explicit synchronization; independent acceptance pending. |
|
||||
| 64-byte alignment of XMemAllocDefault | Existing xmem heap returns 64-byte-aligned data. Biased byte slices can potentially satisfy this inside a sufficiently sized buffer. | Validate buffer offsets and bounds; do not change production in this research. |
|
||||
| 64 KiB resource placement | GetResourceAllocationInfo and aligned heap offsets determine GPU placement. | Not a CPU-pointer alignment guarantee. |
|
||||
| 64 KiB CPU pointer | New M4 64 MiB WB and UPLOAD maps observed at 16 KiB modulo 64 KiB. Unconditionally handing out the base does not satisfy this requirement. | Overallocate and bias byte slices only where guest/GPU address-offset contracts permit it; otherwise CPU-owned allocation and explicit transfer. |
|
||||
| 2 MiB CPU alignment/page size | Physical-page engine supports flagged 2 MiB sections; no D3D12 Map promise provides this CPU alignment or page identity. | Preserve section-backed path; extra padding alone does not provide physical-page semantics. |
|
||||
| Requested CPU virtual address | CreateHeap/CreatePlacedResource/Map provide no requested CPU-VA parameter. XMemVirtualAlloc and physical map paths accept one. | VirtualAlloc/placeholder/section mechanism; logged explicit graphics transfer where needed. Do not relocate a guest allocation silently. |
|
||||
| Reserve now, commit/decommit later | In-tree XMemVirtualAlloc forwards MEM_RESERVE/COMMIT/RESET and tracks commits; decommits are reconciled with VirtualQuery. A mapped D3D12 buffer is not an interchangeable reservation. | Keep CPU VA reservation path. GPU reserved resources are a separate GPU-VA concept, not proof of CPU-VA equivalence. |
|
||||
| Win32 protection/guard/cache flags | In-tree xmem normalizes a subset of page protections and flags. CPU cache property selection exists in CUSTOM heaps, not a general VirtualProtect/page-guard contract. | Preserve unsupported combinations on CPU path, retain original attributes rather than infer their console meaning. |
|
||||
| Caller-owned allocation made before device creation | No D3D12 buffer can exist before its device. Both existing-memory heap opens returned E_NOTIMPL in published baseline observations on these runtime versions. | CPU allocation plus explicit copy; do not move a live pointer after creating the device. |
|
||||
| Physical tags and multiple CPU aliases | Physical engine owns file-mapping sections, stable tags and independently placed CPU views. Public D3D12 GPU heap aliasing does not expose equivalent section handles or arbitrary CPU aliases. | Retain section-backed pages and translation/copy boundary; alias correctness is not solved by Map. |
|
||||
| Scatter mappings/reordered page views | In-tree contiguous/scatter entry points both route through section/placeholder view logic; D3D12 Map alone exposes no equivalent requested CPU scatter mapping. | Preserve engine; future bridging requires a demonstrated interface, not pointer arithmetic. |
|
||||
| xmem region query | Current bx_xmem_query_region describes physical mapped views, verifies MEM_MAPPED, and returns page tag/protection/type. Ordinary virtual and D3D12 allocations are not automatically registered. | Any future cross-DLL provider metadata would need separate maintainer/ABI work outside #473. |
|
||||
| Unified logical budget | Current xmem tracks virtual commits/heap bytes/physical pages; D3D12 allocations outside it are not automatically included. | One logical owner/charge, bounded slab reservation and retirement accounting; host footprint/headroom tracked separately. Do not double-charge a live slice and its slab. |
|
||||
| GPU lifetime while guest frees pointer | Resource/heap/mapped pointer must survive last GPU use; A tests explicit delayed retirement. | Queue/fence retirement records, no reuse or pointer access after disposal. Multi-queue/reference stress remains open. |
|
||||
| Texture placed over arbitrary CPU pointer | UNKNOWN texture layouts are opaque; buffer sharing does not supply a raw texel alias or console tile mapping. | Explicit texture upload/readback APIs and format/layout handling; do not assume every internal texture path copies. |
|
||||
|
||||
[Resource and lifetime contracts](../gpu-correctness/contracts/resource-placement-lifetime.md) link primary D3D12 documentation. Local observations are class A within their workloads; public API constraints class B; compatibility with unverified console semantics and physical backing remain class U. No production adoption is recommended solely from these synthetic checks.
|
||||
|
||||
## Alignment, contents and budget decisions after the resumed review
|
||||
|
||||
Let a mapped buffer base be P, a byte-slice offset be d and the required CPU alignment be A. CPU alignment requires `(P + d) mod A = 0`. A placed resource beginning at heap offset d separately requires `d mod resource_alignment = 0`. When A and resource_alignment are both 64 KiB and P has the observed 16 KiB or 48 KiB remainder, no 64 KiB-multiple offset solves both requirements. Adding an aligned heap offset cannot repair the base pointer. Padding/biasing can only be a candidate for a byte slice *inside* a legal buffer, with its own bounds, view/descriptor alignment, GPU offset and lifetime validated; it cannot be treated as a new legally placed resource at that biased offset. Two MiB pointer padding likewise does not establish two MiB physical sections or page identity. No combined CPU/GPU-offset qualification is claimed by the earlier +64 KiB alias observation.
|
||||
|
||||
Existing contents and guest pointer identity are separate requirements. An allocation selected for a D3D12 provider before exposing its pointer could use that provider's lifetime. An already exposed CPU allocation cannot silently move to a new Map pointer. Copying its bytes to graphics storage preserves a snapshot of contents under synchronization, but preserves neither pointer identity nor CPU section aliases. Without an existing-memory wrapping interface, keep the original owner and an explicit transfer boundary. CPU-only and pre-device allocations therefore retain conventional CPU allocation. UNKNOWN textures retain format-aware upload/readback paths; CPU-visible texture success does not make them ordinary mapped byte arrays. DEFAULT storage is a correctness-tested option, with relative bandwidth and physical cost still awaiting B's evidence.
|
||||
|
||||
| Accounting layer | Required treatment |
|
||||
| --- | --- |
|
||||
| Guest logical payload | Track each live allocation once, including size, attributes and owner. A slice and its containing slab are related records, not two payload charges. |
|
||||
| Reserved backing | Track slab capacity, live/pending suballocation reservations, alignment waste, total free span and largest usable span separately. Fixed bounds can reject requests despite sufficient total fragmented space. |
|
||||
| Pending GPU retirement | A guest free can remove live payload while storage remains unavailable until all final-use fences complete. The real queued-copy trace and the logical delayed-retirement model cover different parts of this requirement. |
|
||||
| Migration peak | Old backing remains charged until retired, while new backing is also reserved. A transfer does not temporarily make either backing free. Fixed guest pointers can rule out migration entirely. |
|
||||
| Host process/driver | Observe footprint, resident/compressed/swapped accounting and retained driver charges independently. Logical free/reusable spans do not imply physical release, nor do retained driver charges alone prove a leak. |
|
||||
|
||||
The bounded allocator experiment supports one optional implementation candidate for the feasible buffer rows. It cannot add requested virtual addresses, decommit, section handles, physical tags, scatter semantics or device-independent ownership. An eventual production design needs explicit per-requirement eligibility and fallback, then independent review; there is no blanket recommendation to route xmem through D3D12.
|
||||
@@ -0,0 +1,110 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Workstream A protocol A2: correct baseline and retirement scope, not a copy
|
||||
// detector.
|
||||
#include "support.h"
|
||||
#include <memory>
|
||||
static void stage(const char *name, void *cpu = nullptr) {
|
||||
std::printf("STAGE %s cpu_ptr=%p\n", name, cpu);
|
||||
if (std::getchar() == EOF)
|
||||
throw std::runtime_error("stage handshake lost");
|
||||
}
|
||||
int main(int argc, char **argv) {
|
||||
setvbuf(stdout, nullptr, _IONBF, 0);
|
||||
try {
|
||||
if (argc != 3)
|
||||
throw std::runtime_error("usage: memory cpu|cpu-plain|wb|upload BYTES");
|
||||
std::string type = argv[1];
|
||||
UINT64 bytes = std::strtoull(argv[2], nullptr, 10);
|
||||
if (bytes != 64 * 1024 * 1024ULL && bytes != 256 * 1024 * 1024ULL &&
|
||||
bytes != 1024 * 1024 * 1024ULL)
|
||||
throw std::runtime_error("size outside common profile");
|
||||
if (type != "cpu" && type != "cpu-plain" && type != "wb" &&
|
||||
type != "upload")
|
||||
throw std::runtime_error("type");
|
||||
std::printf("MEMORY_A protocol=2 type=%s bytes=%llu\n", type.c_str(),
|
||||
bytes);
|
||||
std::unique_ptr<Context> c;
|
||||
std::unique_ptr<Shader> shader;
|
||||
std::unique_ptr<Queue> q;
|
||||
Buffer output;
|
||||
if (type != "cpu-plain") {
|
||||
c = std::make_unique<Context>();
|
||||
shader = std::make_unique<Shader>(*c);
|
||||
q = std::make_unique<Queue>(c->device.p);
|
||||
Buffer tiny;
|
||||
tiny.allocate(c->device.p, 65536, "upload");
|
||||
tiny.map();
|
||||
std::memset(tiny.cpu, 0, 65536);
|
||||
output.allocate(c->device.p, 65536, "wb", true);
|
||||
output.map();
|
||||
shader->dispatch(*q, tiny, output, 1, 0, 1);
|
||||
// Dispose the warm-up command objects before baseline; keep matched
|
||||
// pipeline/output.
|
||||
q.reset();
|
||||
tiny.release();
|
||||
q = std::make_unique<Queue>(c->device.p);
|
||||
}
|
||||
stage("warm_baseline");
|
||||
Sleep(500);
|
||||
stage("baseline");
|
||||
Buffer src;
|
||||
void *cpu = nullptr;
|
||||
if (type == "cpu" || type == "cpu-plain") {
|
||||
cpu = VirtualAlloc(nullptr, bytes, MEM_COMMIT | MEM_RESERVE,
|
||||
PAGE_READWRITE);
|
||||
if (!cpu)
|
||||
throw std::runtime_error("VirtualAlloc");
|
||||
} else
|
||||
src.allocate(c->device.p, bytes, type);
|
||||
stage("created");
|
||||
if (src.resource.p) {
|
||||
src.map();
|
||||
cpu = src.cpu;
|
||||
}
|
||||
stage("mapped", cpu);
|
||||
auto p = static_cast<volatile uint32_t *>(cpu);
|
||||
std::array<uint32_t, 256> expected{};
|
||||
for (UINT64 i = 0; i < bytes / 4; ++i) {
|
||||
uint32_t v = pattern(i, 0x24681357u);
|
||||
p[i] = v;
|
||||
expected[i % 256] ^= v + 0x10101u;
|
||||
}
|
||||
_mm_sfence();
|
||||
stage("fully_initialized", cpu);
|
||||
if (src.resource.p) {
|
||||
shader->dispatch(*q, src, output, UINT(bytes / 4), 0x10101u, 1);
|
||||
size_t matches = 0;
|
||||
for (UINT i = 0; i < 256; ++i)
|
||||
matches +=
|
||||
static_cast<volatile uint32_t *>(output.cpu)[i] == expected[i];
|
||||
std::printf(
|
||||
"VERIFY full_consumption checksum_matches=%zu/256 words=%llu\n",
|
||||
matches, bytes / 4);
|
||||
if (matches != 256)
|
||||
throw std::runtime_error("full-consumption checksum mismatch");
|
||||
} else
|
||||
std::puts("GPU_CONSUMPTION NOT_RUN CPU_allocation_control");
|
||||
stage("gpu_complete", cpu);
|
||||
if (src.resource.p)
|
||||
src.release();
|
||||
else if (!VirtualFree(cpu, 0, MEM_RELEASE))
|
||||
throw std::runtime_error("VirtualFree");
|
||||
cpu = nullptr;
|
||||
stage("resources_released");
|
||||
// Fence already completed; dispose all
|
||||
// command-list/allocator/queue/fence/pipeline resources.
|
||||
q.reset();
|
||||
output.release();
|
||||
shader.reset();
|
||||
stage("commands_retired");
|
||||
Sleep(500);
|
||||
stage("retired_settled");
|
||||
c.reset();
|
||||
stage("device_released");
|
||||
std::puts("END success");
|
||||
return 0;
|
||||
} catch (const std::exception &e) {
|
||||
std::printf("END failure reason=%s\n", e.what());
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Original macOS process accounting observer; native ARM64 only.
|
||||
#include <cerrno>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <libproc.h>
|
||||
#include <sys/resource.h>
|
||||
#include <unistd.h>
|
||||
int main(int argc, char **argv) {
|
||||
if (argc != 2)
|
||||
return 2;
|
||||
rusage_info_v4 r{};
|
||||
int pid = std::atoi(argv[1]);
|
||||
int rc = proc_pid_rusage(pid, RUSAGE_INFO_V4,
|
||||
reinterpret_cast<rusage_info_t *>(&r));
|
||||
std::printf("{\"pid\":%d,\"return\":%d,\"errno\":%d,\"host_page_size\":%d,"
|
||||
"\"phys_footprint\":%llu,\"resident_size\":%llu,\"wired_size\":%"
|
||||
"llu,\"pageins\":%llu,\"max_phys_footprint\":%llu}\n",
|
||||
pid, rc, rc ? errno : 0, getpagesize(), r.ri_phys_footprint,
|
||||
r.ri_resident_size, r.ri_wired_size, r.ri_pageins,
|
||||
r.ri_lifetime_max_phys_footprint);
|
||||
return rc ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,359 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Original bounded allocation trace. Not a production allocator.
|
||||
#include "support.h"
|
||||
#include <memory>
|
||||
#include <random>
|
||||
|
||||
static constexpr UINT64 slabBytes = 32ULL * 1024 * 1024;
|
||||
static constexpr int slots = 24;
|
||||
static void stage(const char *phase) {
|
||||
std::printf("STAGE %s cpu_ptr=0\n", phase);
|
||||
if (std::getchar() == EOF)
|
||||
throw std::runtime_error("stage handshake lost");
|
||||
}
|
||||
static double milliseconds(double start) {
|
||||
return (ticks() - start) * 1000 / frequency();
|
||||
}
|
||||
struct Span {
|
||||
UINT64 offset, size;
|
||||
};
|
||||
struct FreeList {
|
||||
std::vector<Span> free{{0, slabBytes}};
|
||||
UINT64 take(UINT64 size, UINT64 align) {
|
||||
for (size_t i = 0; i < free.size(); ++i) {
|
||||
Span old = free[i];
|
||||
UINT64 start = (old.offset + align - 1) / align * align;
|
||||
if (start < old.offset || start - old.offset > old.size ||
|
||||
size > old.size - (start - old.offset))
|
||||
continue;
|
||||
free.erase(free.begin() + i);
|
||||
if (start > old.offset)
|
||||
free.push_back({old.offset, start - old.offset});
|
||||
if (start + size < old.offset + old.size)
|
||||
free.push_back({start + size, old.offset + old.size - start - size});
|
||||
return start;
|
||||
}
|
||||
throw std::runtime_error("bounded slab exhausted");
|
||||
}
|
||||
void give(UINT64 offset, UINT64 size) {
|
||||
free.push_back({offset, size});
|
||||
std::sort(free.begin(), free.end(),
|
||||
[](auto a, auto b) { return a.offset < b.offset; });
|
||||
std::vector<Span> merged;
|
||||
for (auto v : free) {
|
||||
if (!merged.empty() &&
|
||||
merged.back().offset + merged.back().size > v.offset)
|
||||
throw std::runtime_error("overlapping free span");
|
||||
if (!merged.empty() &&
|
||||
merged.back().offset + merged.back().size == v.offset)
|
||||
merged.back().size += v.size;
|
||||
else
|
||||
merged.push_back(v);
|
||||
}
|
||||
free = merged;
|
||||
}
|
||||
};
|
||||
struct Allocation {
|
||||
Ref<ID3D12Heap> heap;
|
||||
Ref<ID3D12Resource> resource;
|
||||
void *cpu = nullptr;
|
||||
UINT64 bytes = 0, reserved = 0, offset = 0;
|
||||
UINT seed = 0;
|
||||
};
|
||||
struct Trace {
|
||||
Context c;
|
||||
std::unique_ptr<Queue> q;
|
||||
Ref<ID3D12Heap> slab;
|
||||
FreeList free;
|
||||
std::array<Allocation, slots> live;
|
||||
Buffer read;
|
||||
bool pooled, omit = false;
|
||||
UINT seed;
|
||||
std::mt19937 rng;
|
||||
double heapSetup = 0;
|
||||
UINT64 peakLive = 0, peakReserved = 0;
|
||||
Trace(bool pool, UINT s, bool omitCopy)
|
||||
: pooled(pool), omit(omitCopy), seed(s), rng(s) {
|
||||
q = std::make_unique<Queue>(c.device.p);
|
||||
read.allocate(c.device.p, slots * 192, "readback");
|
||||
read.map();
|
||||
std::printf("TRACE mode=%s seed=%u slab_bytes=%llu slots=%d "
|
||||
"pre_setup_ms=%.6f warmups=2 timed=10\n",
|
||||
pooled ? "pooled" : "individual", seed, pooled ? slabBytes : 0,
|
||||
slots, heapSetup);
|
||||
}
|
||||
void createHeap(UINT64 bytes, Ref<ID3D12Heap> &heap) {
|
||||
D3D12_HEAP_DESC d{};
|
||||
d.SizeInBytes = bytes;
|
||||
d.Alignment = 65536;
|
||||
d.Properties = properties(D3D12_HEAP_TYPE_CUSTOM);
|
||||
d.Properties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_WRITE_BACK;
|
||||
d.Properties.MemoryPoolPreference = D3D12_MEMORY_POOL_L0;
|
||||
d.Flags = D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS;
|
||||
require(c.device->CreateHeap(&d, __uuidof(ID3D12Heap), heap.out()),
|
||||
"trace CreateHeap");
|
||||
}
|
||||
void allocate(int slot, int iteration, int phase) {
|
||||
auto &a = live[slot];
|
||||
if (a.resource.p)
|
||||
throw std::runtime_error("occupied slot");
|
||||
const UINT64 sizes[] = {65540, 262148, 1048580, 393220};
|
||||
a.bytes = sizes[rng() % 4];
|
||||
a.seed = seed ^ UINT(iteration + 11) * 0x1020301u ^ UINT(slot) * 0x9001u ^
|
||||
UINT(phase) * 0xB3u;
|
||||
auto desc = bufferDesc(a.bytes);
|
||||
auto ai = c.device->GetResourceAllocationInfo(0, 1, &desc);
|
||||
if (!ai.Alignment || ai.SizeInBytes == ~UINT64(0))
|
||||
throw std::runtime_error("buffer allocation info");
|
||||
a.reserved = ai.SizeInBytes;
|
||||
double start = ticks();
|
||||
if (pooled)
|
||||
a.offset = free.take(ai.SizeInBytes, ai.Alignment);
|
||||
else
|
||||
createHeap(ai.SizeInBytes, a.heap);
|
||||
double heapMs = milliseconds(start);
|
||||
start = ticks();
|
||||
require(c.device->CreatePlacedResource(
|
||||
pooled ? slab.p : a.heap.p, a.offset, &desc,
|
||||
D3D12_RESOURCE_STATE_GENERIC_READ, nullptr,
|
||||
__uuidof(ID3D12Resource), a.resource.out()),
|
||||
"trace placement");
|
||||
double placeMs = milliseconds(start);
|
||||
start = ticks();
|
||||
D3D12_RANGE empty{0, 0};
|
||||
require(a.resource->Map(0, &empty, &a.cpu), "trace Map");
|
||||
double mapMs = milliseconds(start);
|
||||
if (!a.cpu)
|
||||
throw std::runtime_error("trace null map");
|
||||
auto p = static_cast<volatile uint32_t *>(a.cpu);
|
||||
for (UINT64 i = 0; i < a.bytes / 4; ++i)
|
||||
p[i] = pattern(i, a.seed);
|
||||
_mm_sfence();
|
||||
std::printf("ALLOC iteration=%d phase=%d slot=%d bytes=%llu reserved=%llu "
|
||||
"offset=%llu alignment=%llu heap_or_suballoc_ms=%.6f "
|
||||
"placement_ms=%.6f map_ms=%.6f warmup=%d\n",
|
||||
iteration, phase, slot, a.bytes, a.reserved, a.offset,
|
||||
ai.Alignment, heapMs, placeMs, mapMs, iteration < 0);
|
||||
}
|
||||
void stats(int iteration, const char *phase) {
|
||||
UINT64 payload = 0, reserved = 0, totalFree = 0, largest = 0;
|
||||
for (auto &a : live)
|
||||
if (a.resource.p) {
|
||||
payload += a.bytes;
|
||||
reserved += a.reserved;
|
||||
}
|
||||
if (pooled)
|
||||
for (auto s : free.free) {
|
||||
totalFree += s.size;
|
||||
largest = std::max(largest, s.size);
|
||||
}
|
||||
UINT64 backing = pooled ? slabBytes : reserved;
|
||||
peakLive = std::max(peakLive, payload);
|
||||
peakReserved = std::max(peakReserved, backing);
|
||||
std::printf("FRAGMENT iteration=%d phase=%s live_payload=%llu "
|
||||
"live_reserved=%llu backing_reserved=%llu alignment_waste=%llu "
|
||||
"total_free=%llu largest_free=%llu free_span_count=%zu\n",
|
||||
iteration, phase, payload, reserved, backing,
|
||||
reserved - payload, totalFree, largest,
|
||||
pooled ? free.free.size() : 0);
|
||||
}
|
||||
void verify(int iteration, int phase) {
|
||||
// Every recycled placed resource is explicitly activated; no inheritance is
|
||||
// assumed.
|
||||
q->begin();
|
||||
auto rb = static_cast<unsigned char *>(read.cpu);
|
||||
std::memset(rb, 0xA7, slots * 192);
|
||||
for (int slot = 0; slot < slots; ++slot) {
|
||||
auto &a = live[slot];
|
||||
if (!a.resource.p)
|
||||
continue;
|
||||
D3D12_RESOURCE_BARRIER alias{};
|
||||
alias.Type = D3D12_RESOURCE_BARRIER_TYPE_ALIASING;
|
||||
alias.Aliasing.pResourceAfter = a.resource.p;
|
||||
q->list->ResourceBarrier(1, &alias);
|
||||
if (!omit)
|
||||
for (int part = 0; part < 3; ++part) {
|
||||
UINT64 src = part == 0 ? 0
|
||||
: part == 1 ? (a.bytes / 2 / 4) * 4
|
||||
: a.bytes - 64;
|
||||
q->list->CopyBufferRegion(read.resource.p, slot * 192 + part * 64,
|
||||
a.resource.p, src, 64);
|
||||
}
|
||||
}
|
||||
_mm_sfence();
|
||||
q->finish();
|
||||
int matches = 0, expected = 0;
|
||||
for (int slot = 0; slot < slots; ++slot) {
|
||||
auto &a = live[slot];
|
||||
if (!a.resource.p)
|
||||
continue;
|
||||
for (int part = 0; part < 3; ++part) {
|
||||
UINT64 src = part == 0 ? 0
|
||||
: part == 1 ? (a.bytes / 2 / 4) * 4
|
||||
: a.bytes - 64;
|
||||
auto p =
|
||||
reinterpret_cast<volatile uint32_t *>(rb + slot * 192 + part * 64);
|
||||
for (int i = 0; i < 16; ++i) {
|
||||
++expected;
|
||||
matches += p[i] == pattern(src / 4 + i, a.seed);
|
||||
}
|
||||
}
|
||||
}
|
||||
std::printf("READBACK iteration=%d phase=%d matches=%d/%d fence=%llu "
|
||||
"completed=%llu\n",
|
||||
iteration, phase, matches, expected, q->value,
|
||||
q->fence->GetCompletedValue());
|
||||
if (matches != expected)
|
||||
throw std::runtime_error("trace guard/interior mismatch");
|
||||
// Complete list retirement precedes free-list reuse; a fence alone is not
|
||||
// ref-count evidence.
|
||||
q->begin();
|
||||
q->close();
|
||||
}
|
||||
void release(int slot, int iteration) {
|
||||
auto &a = live[slot];
|
||||
if (!a.resource.p)
|
||||
return;
|
||||
UINT64 completed = q->fence->GetCompletedValue();
|
||||
if (completed < q->value)
|
||||
throw std::runtime_error("premature reuse rejected");
|
||||
double start = ticks();
|
||||
a.resource->Unmap(0, nullptr);
|
||||
a.cpu = nullptr;
|
||||
a.resource.clear();
|
||||
double resourceMs = milliseconds(start);
|
||||
start = ticks();
|
||||
if (pooled)
|
||||
free.give(a.offset, a.reserved);
|
||||
else
|
||||
a.heap.clear();
|
||||
double backingMs = milliseconds(start);
|
||||
std::printf(
|
||||
"FREE iteration=%d slot=%d resource_ms=%.6f "
|
||||
"backing_or_freelist_ms=%.6f retire_fence=%llu completed=%llu\n",
|
||||
iteration, slot, resourceMs, backingMs, q->value, completed);
|
||||
}
|
||||
void delayedRetirement() {
|
||||
allocate(0, -3, 0);
|
||||
auto &a = live[0];
|
||||
Ref<ID3D12Fence> gate;
|
||||
require(c.device->CreateFence(0, D3D12_FENCE_FLAG_NONE,
|
||||
__uuidof(ID3D12Fence), gate.out()),
|
||||
"retirement gate");
|
||||
struct OpenGate {
|
||||
ID3D12Fence *f;
|
||||
~OpenGate() { f->Signal(1); }
|
||||
} cleanup{gate.p};
|
||||
q->begin();
|
||||
D3D12_RESOURCE_BARRIER activation{};
|
||||
activation.Type = D3D12_RESOURCE_BARRIER_TYPE_ALIASING;
|
||||
activation.Aliasing.pResourceAfter = a.resource.p;
|
||||
q->list->ResourceBarrier(1, &activation);
|
||||
q->list->CopyBufferRegion(read.resource.p, 0, a.resource.p, 0, 64);
|
||||
q->close();
|
||||
_mm_sfence();
|
||||
require(q->q->Wait(gate.p, 1), "queue gate wait");
|
||||
ID3D12CommandList *lists[] = {q->list.p};
|
||||
q->q->ExecuteCommandLists(1, lists);
|
||||
UINT64 target = ++q->value;
|
||||
HRESULT signalled = q->q->Signal(q->fence.p, target);
|
||||
if (FAILED(signalled))
|
||||
q->stopInFlight("retirement Signal", signalled, target,
|
||||
q->fence->GetCompletedValue());
|
||||
UINT64 completed = q->fence->GetCompletedValue();
|
||||
bool withheld = completed < target;
|
||||
// No free, overwrite, or second resource activation occurs while this range
|
||||
// is pending.
|
||||
HRESULT opened = gate->Signal(1);
|
||||
if (FAILED(opened))
|
||||
q->stopInFlight("open retirement gate", opened, target,
|
||||
q->fence->GetCompletedValue());
|
||||
q->waitFor(target);
|
||||
std::printf(
|
||||
"DELAYED_RETIRE target=%llu before=%llu withheld=%d after=%llu\n",
|
||||
target, completed, withheld, q->fence->GetCompletedValue());
|
||||
if (!withheld)
|
||||
throw std::runtime_error("pending range was not withheld");
|
||||
for (int i = 0; i < 16; ++i)
|
||||
if (static_cast<volatile uint32_t *>(read.cpu)[i] != pattern(i, a.seed))
|
||||
throw std::runtime_error("delayed readback mismatch");
|
||||
q->begin();
|
||||
q->close();
|
||||
release(0, -3);
|
||||
}
|
||||
void run() {
|
||||
stage("baseline");
|
||||
if (pooled) {
|
||||
double start = ticks();
|
||||
createHeap(slabBytes, slab);
|
||||
heapSetup = milliseconds(start);
|
||||
}
|
||||
std::printf("POOL_SETUP mode=%s heap_ms=%.6f reserved_bytes=%llu\n",
|
||||
pooled ? "pooled" : "individual", heapSetup,
|
||||
pooled ? slabBytes : 0);
|
||||
stage("heap_ready");
|
||||
delayedRetirement();
|
||||
for (int iteration = -2; iteration < 10; ++iteration) {
|
||||
double start = ticks();
|
||||
for (int i = 0; i < slots; ++i)
|
||||
allocate(i, iteration, 0);
|
||||
stats(iteration, "full");
|
||||
verify(iteration, 0);
|
||||
for (int i = 0; i < slots; i += 2)
|
||||
release(i, iteration);
|
||||
stats(iteration, "holes");
|
||||
// Before the next real fence, a fictitious future retirement value must
|
||||
// be rejected.
|
||||
UINT64 completed = q->fence->GetCompletedValue(), future = q->value + 1;
|
||||
bool withheld = completed < future;
|
||||
std::printf("RETIRE_POLICY future=%llu completed=%llu withheld=%d\n",
|
||||
future, completed, withheld);
|
||||
if (!withheld)
|
||||
throw std::runtime_error("retire policy control");
|
||||
for (int i = 0; i < slots; i += 2)
|
||||
allocate(i, iteration, 1);
|
||||
stats(iteration, "refill");
|
||||
verify(iteration, 1);
|
||||
if (iteration == 0) {
|
||||
double pause = ticks();
|
||||
stage("live");
|
||||
start += ticks() - pause;
|
||||
}
|
||||
for (int i = 0; i < slots; ++i)
|
||||
release(i, iteration);
|
||||
stats(iteration, "empty");
|
||||
if (pooled && (free.free.size() != 1 || free.free[0].offset ||
|
||||
free.free[0].size != slabBytes))
|
||||
throw std::runtime_error("free-list failed to coalesce");
|
||||
std::printf("CYCLE iteration=%d ms=%.6f warmup=%d\n", iteration,
|
||||
milliseconds(start), iteration < 0);
|
||||
}
|
||||
stage("resources_released");
|
||||
q.reset();
|
||||
read.release();
|
||||
slab.clear();
|
||||
stage("commands_retired");
|
||||
Sleep(500);
|
||||
stage("retired_settled");
|
||||
std::printf("TRACE_END peak_logical_live=%llu peak_reserved=%llu\n",
|
||||
peakLive, peakReserved);
|
||||
}
|
||||
};
|
||||
int main(int argc, char **argv) {
|
||||
setvbuf(stdout, nullptr, _IONBF, 0);
|
||||
try {
|
||||
if (argc != 3)
|
||||
throw std::runtime_error("usage: pool individual|pooled|omit SEED");
|
||||
std::string mode = argv[1];
|
||||
if (mode != "individual" && mode != "pooled" && mode != "omit")
|
||||
throw std::runtime_error("mode");
|
||||
Trace trace(mode != "individual", UINT(std::strtoul(argv[2], nullptr, 10)),
|
||||
mode == "omit");
|
||||
trace.run();
|
||||
std::puts("END success");
|
||||
return 0;
|
||||
} catch (const std::exception &e) {
|
||||
std::printf("END failure reason=%s\n", e.what());
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
# Allocation, pooling, fragmentation and retirement
|
||||
|
||||
Local author observations on the M4/CrossOver/D3DMetal environment recorded by the [corrected trace receipt](../results/2026-11-26-apple-m4-arths17-a22-pool-corrected/receipt.json). Independent acceptance is pending. The trace is an original bounded experimental allocator, not production code or an evaluation run of AMD's allocator.
|
||||
|
||||
## Comparison
|
||||
|
||||
Six fresh processes form three matched seeded pairs (473, 474, 475). Each uses 24 buffer slots, two warmup cycles, ten timed cycles, and exactly the same live sizes/data/GPU readback work in both modes. Individual mode creates a CUSTOM/WB/L0 heap per allocation; pooled mode places resources in a 32 MiB slab. Each measured process has 360 allocation samples and 360 frees; samples within cycles are correlated. Reported distributions, raw samples, seeds and executed sources are retained. No background profiler runs inside the API windows.
|
||||
|
||||
| Seed | Individual heap creation median ms | Pool suballocation median ms | Individual placement median ms | Pool placement median ms | Individual cycle median ms | Pool cycle median ms |
|
||||
| --- | ---: | ---: | ---: | ---: | ---: | ---: |
|
||||
| 473 | 0.01250 | 0.00010 | 0.00070 | 0.00100 | 12.62715 | 12.47335 |
|
||||
| 474 | 0.01230 | 0.00010 | 0.00070 | 0.00090 | 12.33830 | 11.90645 |
|
||||
| 475 | 0.01265 | 0.00010 | 0.00070 | 0.00100 | 12.68280 | 12.33040 |
|
||||
|
||||
Cold pooled heap setup was separately 6.5561, 6.8396 and 6.5303 ms. Do not omit that cost when discussing first use. Map median was near the reporting floor in both modes. Whole cycles include initialization, raw-log output, GPU copies/fence waits, validation and free-list operations, so they are not isolated allocator timings. The live snapshot pause is subtracted. Zero/near-zero API samples reflect measurement precision and call overhead, not zero execution cost.
|
||||
|
||||
Within this workload, replacing repeated heap creation with a free-list operation reduces the measured allocation-call component. The cycle difference is small, placement is slightly costlier, the host is busy and uses the explicit warning-pressure profile. An earlier preserved pair even had the opposite whole-cycle ordering (12.2991 versus 15.8891 ms). These data do not establish a stable application-level speedup or a production benefit. No title/framerate or cross-generation claim is supported.
|
||||
|
||||
## Memory and fragmentation
|
||||
|
||||
The first trace version created its pooled heap before the baseline. Its raw runs remain [preserved](../results/2026-11-26-apple-m4-arths17-a22-pool-first-pair/receipt.json), with [continuation pairs](../results/2026-11-26-apple-m4-arths17-a22-pool-pre-correction/receipt.json). Their API samples are inspectable, but baseline deltas hide slab creation. The corrected source moves slab creation after a matched baseline and adds heap_ready. Its initial TRACE line still contains the pre-allocation setup value 0; actual cost is the subsequent POOL_SETUP record. Current source renames that initial field pre_setup_ms only; the timing results above are tied to the exact archived executed source. The later omitted-copy control exercises the source after that logging-only rename.
|
||||
|
||||
In corrected seed 473, individual baseline was 34.58 MiB and heap_ready 34.67 MiB; pool baseline was 34.49 MiB and heap_ready 66.73 MiB. Thus the one-time slab charge is visible. At the live checkpoint both are about 332 MiB, and after command/slab/readback release both remain about 292 MiB. This shared accounting behavior does not establish a memory saving from pooling or identify the retained backing. The three pairs have similar absolute readings; all raw tool categories and RSS/footprint distinctions remain available.
|
||||
|
||||
The pool reserves 32 MiB irrespective of live payload. Individual heaps reserve the sum of resource allocation sizes. In seed 473's first measured holes checkpoint, both have 5,963,824 live requested bytes and 6,750,208 live allocation-aligned bytes, so alignment waste is 786,384 bytes. The pool has 26,804,224 free bytes in 13 spans, with largest span 22,675,456 bytes. Individual heaps do not have a reusable cross-heap free span; their printed zeros are not evidence of zero fragmentation.
|
||||
|
||||
Every cycle records full/holes/refill/empty snapshots and checks that all free spans coalesce back to one 32 MiB range. The trace demonstrates bounded recycling and quantifies logical slack/waste. It does not saturate arbitrary allocation patterns or establish a general fragmentation bound. The fixed slab is deliberately oversized for this trace; an adaptive production allocator could behave differently. Logical payload/slab/slack statistics are not physical memory measurements.
|
||||
|
||||
## Resource retirement and checks
|
||||
|
||||
Each process has 24 successful guard/interior readbacks (two phases in each of 12 cycles), plus a separate real gate-delayed copy. Before releasing the gate, the completion fence is below the retirement target and the allocation is withheld. After opening the gate and waiting with a timeout, readback matches before any release/reuse. A separate future-value policy control is also retained. This is a bounded one-queue retirement fixture, not exhaustive multi-queue lifetime certification.
|
||||
|
||||
The [omitted-copy negative control](../results/2026-11-26-apple-m4-arths17-a22-pool-negative/receipt.json) deliberately leaves poisoned readback in place and must exit 1 specifically for a guard/interior mismatch. It is a control success only if that exact failure is observed; it is not a passing GPU data path. Production changes and AMD allocator integration remain outside this task.
|
||||
|
||||
Recommendation: pooling is a plausible candidate for amortizing heap-creation overhead, with a measured cold reservation/setup cost and a required bounded slack/retirement policy. It is not yet a demonstrated overall memory/performance improvement. Prefer evaluating the [established allocator candidate](allocator-assessment.md) against the same trace before designing production machinery.
|
||||
@@ -0,0 +1,15 @@
|
||||
# Workstream A publication audit
|
||||
|
||||
The final-stage requester instruction authorizes DCO-signed publication of A research on `research/473-workstream-a-memory`. This is a research publication, not independent acceptance or a production merge. The original A parent is `8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8`; reviewed B is `a40228747470f0d184375e451b0173769c90aef5`.
|
||||
|
||||
All candidate files were read or examined as structured source/data, classified as original research, authorized synthetic output, documentation, diagnostic receipts or source snapshots. Pattern and binary-magic scans found no credentials, personal filesystem paths, executable payloads, runtime locks or temporary configuration in the candidates. Original HLSL and compiled synthetic DXBC are retained as research inputs; proprietary runtime binaries, vendor allocator implementation files, bottles and native/PE executables stay external or in ignored artifacts. Configured Git identity and DCO attribution are preserved.
|
||||
|
||||
All 24 A archive manifests verify 2081 archived file hashes. The declared source-reference audit finds 104 byte-identical source matches among 109 references across all retained receipts. Five references in already-published historical/setup failures have no retained matching source bytes: the old `769cf0...` runner and `0ee894...` probe in historical-p2-memory and historical-p2-acceptance, and the `6641ea...` runner in a2-setup-failure. These are not claimed verified or reconstructed. They remain historical evidence limitations; no new successful run has an unmatched source reference. The inventory and raw receipts remain unchanged.
|
||||
|
||||
Exact AMD allocator LICENSE/header/implementation Git blob identities were rechecked against the external unchanged files; complete MIT notices remain present. The registry and reuse matrix record provenance and license scope. The original six-check probe still hashes to `33e90bfee89e812f48990613cd74ced56473e5c3fc5d973f2ba1116090646a0c`, and its runner is byte-identical to the frozen baseline. Production, ABI and main are untouched.
|
||||
|
||||
All current supplemental C++ sources were strictly compiled before this final-stage request; executed source and build-only receipts distinguish those revisions. Python checks, archive hashes and candidate documentation hygiene are retained. Current urgent kernel pressure and limited headroom under 23 GB block new GPU experiments and memory-heavy engineering checks. Earlier exact-revision production checks remain historical evidence, not a claim that unrun checks ran again. The compile-checked fence-error correction still needs independent review and runtime fault verification.
|
||||
|
||||
The publication audit JSON records a point-in-time candidate file/hash manifest before adding its own bundle. It is diagnostic evidence, not a self-referential hash of the final Git commit. The pushed Git tree and remote SHA identify the complete published revision. Missing historical sources, pressure stops, invalid-creation gate failures, the initial graphics fixture bug and B's stopped-output discrepancy remain explicit. None is converted into a passing result by publication.
|
||||
|
||||
One staged whitespace check reports a blank line at EOF in the byte-preserved B `support.h` snapshot under the A B-source-build archive. That snapshot's bytes match its recorded source hash. It is retained verbatim rather than reformatted; the whitespace warning is an explicit exception, not a passing whole-tree whitespace result. Active edited source passes the working-tree diff check. This has no bearing on numerical gates or unsupported outcomes.
|
||||
@@ -0,0 +1,61 @@
|
||||
# Workstream A research report
|
||||
|
||||
BetterXen [#473](https://github.com/MacosPorters/betterxen/issues/473), 2026-11-26. This is local, original synthetic research on Apple M4 with 24 GiB. Independent acceptance remains pending. The objective is a defensible memory architecture, not proof of zero-copy. No production shim, ABI, main-branch file or original baseline probe was changed.
|
||||
|
||||
## Findings that affect the architecture
|
||||
|
||||
A D3D12-owned mapped buffer is a viable candidate for selected graphics allocations in the observed configuration. It is not a replacement for arbitrary xmem virtual/physical/scatter semantics. New Map-pointer receipts are not always 64 KiB aligned, even when heap placement is. Valid overlapping buffer placements exhibited the expected application-level data inheritance, but this does not identify physical pages or wrap an arbitrary existing allocation.
|
||||
|
||||
Process footprint depends on allocation size, prior runtime charging and retirement scope. Small allocations can use already charged regions; larger graphics allocations can remain process-accounted after resources, command objects and the device are released. RSS and footprint accounting can differ sharply under compression/swap. Neither a near-1x slope nor SM=SHM establishes unique physical backing or the absence of internal copies.
|
||||
|
||||
Pooling reduces the measured heap-creation component in a matched synthetic trace, but has a separately measured cold setup cost, reserved slack and noisy whole-cycle differences. It has not demonstrated a general application-level performance or memory improvement. The candidate architecture should not assume pooling is beneficial before workload-specific measurements and independent review.
|
||||
|
||||
Valid texture/mip/mixed-placement and RT/depth clear/alias readbacks matched in two new sessions. The overall texture matrix nevertheless failed its negative-rejection gate: the runtime accepted misaligned and out-of-bounds creation calls that were never GPU-used. Caller-side validation remains necessary. Invalid-call acceptance is not by itself proof of a runtime conformance defect because the public contract imposes preconditions without promising every rejection HRESULT.
|
||||
|
||||
## Deliverables and evidence
|
||||
|
||||
| Deliverable | Current evidence and status |
|
||||
| --- | --- |
|
||||
| Physical memory analysis | [Footprint findings](footprint-findings.md): historical two-repeat profile, corrected retirement checkpoints, controls, compression/pressure limits and interrupted attempt. Raw tool outputs are append-only. |
|
||||
| Inverted ownership | [Requirement matrix](inverted-ownership.md): requested addresses, CPU alignment, attributes, reservation/decommit, aliases/scatter, pre-device allocations, budget and lifetime. Distinguishes in-tree implementation from unverified console semantics. |
|
||||
| Allocation/pooling comparison | [Three corrected matched pairs](pooling-findings.md), raw API samples/distributions and separately timed cold heap setup. No stable production improvement claimed. |
|
||||
| Fragmentation/retirement | Deterministic sizes/seeds, guard/interior GPU checks, logical free-span/waste/slack records, coalescing and a real gate-delayed retirement case. Multi-queue and arbitrary workloads remain open. |
|
||||
| Texture/resource correctness | [Version-scoped matrix](../gpu-correctness/textures-and-resources/findings.md): three formats/three mips/WB/WC/DEFAULT, disjoint guards, RT/depth aliases and valid buffer inheritance. Failed negatives retained. |
|
||||
| Shared versus GPU-optimized storage | Conditional guidance below; matched bandwidth and actual internal Metal storage modes remain unmeasured, requiring B's contribution. |
|
||||
| Optional allocator reuse | [Exact-pin, per-file assessment](allocator-assessment.md) of AMD D3D12 Memory Allocator. No source adopted or runtime qualification claimed. |
|
||||
| Independent review of B | [Pending](review-handoff.md): M5 comments reviewed as attributed reports; pinned B implementation/raw handoff and critical reproduction not yet available. |
|
||||
| Recommended architecture | Candidate ownership split and explicit fallbacks below; no production adoption decision. |
|
||||
| Limitations and fallbacks | [Inventory/gaps](inventory/README.md), ownership matrix, pressure interruptions, negative outcomes and unresolved mechanisms remain explicit. |
|
||||
| #464 handoff | [Narrow evidence note](handoff-464.md), including current PR #486 source boundary at a pinned revision. No implementation changes or certification. |
|
||||
|
||||
## Candidate memory architecture
|
||||
|
||||
Keep a CPU-owned family for pre-device allocations, requested virtual addresses, reservations/decommit, section-backed physical tags/aliases/scatter views and unsupported attributes. Where graphics must consume those bytes, preserve an explicit, logged transfer path rather than silently relocating guest pointers or claiming unsupported wrapping.
|
||||
|
||||
Evaluate a D3D12-owned mapped-buffer family only for allocations whose CPU address, alignment, ownership and lifetime requirements it actually satisfies. Maintain resource ownership through every live pointer and last GPU use. Biased byte suballocation can be investigated for alignment, but does not automatically satisfy separately placed-resource offsets or CPU/GPU alias contracts. Retain explicit fallback mechanisms for incompatible rows in the matrix.
|
||||
|
||||
Use one logical budget with clearly separated live payload, reserved slabs, alignment waste, pending retirement and cached storage. Track host headroom/pressure and observed runtime retention separately. Logical release must not be presented as immediate physical reclamation, and a slice plus its slab must not be double charged. Bound pooling/caching rather than growing until pressure forces eviction.
|
||||
|
||||
Separate texture storage from raw mapped-buffer ownership. The tested CPU-subresource and DEFAULT upload/readback paths are usable candidates for their observed formats. For CPU-frequent buffers/textures, choose a valid CPU-visible path by measured access requirements; for GPU-owned resources evaluate DEFAULT with explicit transfers where needed. The A data cannot rank WB, WC and DEFAULT bandwidth or reveal D3DMetal's Metal storage mode. Combine correctness/accounting with B's measured copy/coherence/bandwidth tradeoffs before choosing by resource class.
|
||||
|
||||
Reuse established allocation infrastructure if it satisfies demonstrated requirements. The optional AMD allocator assessment is a starting point; production integration requires its own pinned build/runtime comparison, provenance/registry work and approval. The original trace free list is not a proposed production replacement.
|
||||
|
||||
## Environment and methodological limits
|
||||
|
||||
Recorded host: Apple M4, 25769803776 bytes unified RAM, macOS 27.0 build 26A428; CrossOver 26.3.0.39832 (cxoffice-26.3.0rc2), Wine engine wine-11.0-8726-g2e2f5fca349; loaded D3DMetal 3.0, SourceVersion 32047000000000; Rosetta receipt 1.0.0.0.1788432274. Tool receipts include native ARM64 GCC 16.2.0/MinGW-w64 14.0.0_3, Apple clang 17.0.0, SDK 26.2 and Python 3.14.3. Host page size is 16384 bytes. Own observer and CLI architecture/linkage checks are retained.
|
||||
|
||||
The host was not idle and had existing swap. A large sweep was interrupted when the stronger kernel pressure signal reported urgent; it remains incomplete. The bounded continuation completed six smaller/control processes and stopped automatically before proceeding with the WB 256 MiB graphics case when urgent pressure recurred. Large corrected repeats remain open. After the requester freed memory and authorized bounded continuation, runs explicitly used the warning-pressure profile, with urgent/critical stops and a conservative 23 GB host-headroom ceiling. No optional 2 GiB extension was run. The ceiling is a guard, not a target or a claim to control other applications. Three readings at one pause are correlated snapshots, not independent repetitions. Repeated runs on the same host do not establish cross-generation acceptance.
|
||||
|
||||
Hardware observations are local class A within their workloads; public API contracts class B; allocator project-source assessment class D; physical mechanisms, untested configurations and console compatibility class U. No Xbox hardware or commercial game execution was tested. Shared baseline sources and historical failures are preserved. No result is independently accepted merely because the author wrote both a probe and this report.
|
||||
|
||||
## Review and publication dependency
|
||||
|
||||
Exact executed sources, hashes, commands, raw data and review questions are in the append-only bundles and [handoff](review-handoff.md). B must independently review and reproduce A's critical findings; A has now inspected B's published implementation and recalculated raw data; critical M4 reproduction and trace-input validation remain open. The requester manually published initial A work at `8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8`. Publication on the dedicated A research branch is now explicitly authorized, and this report does not certify #464 or recommend adoption on the strength of synthetic success alone.
|
||||
|
||||
## Local validation
|
||||
|
||||
[Validation logs and receipts](../results/2026-11-26-apple-m4-arths17-a-verification/verification.json) record formatting, Clippy, 66 passed Rust tests with one existing ignored test, all 16 strict PE32+ shim/export checks, ARM64 CLI format/linkage and the two unchanged baseline CPU conformance programs (test_veh_clwb and test_shim_exports). Documentation hygiene passed with a temporary index containing candidate files, without changing the real index. Archive/source hash checks and Python/C++ formatting/compilation checks are retained. These engineering checks do not independently accept the new research or turn the texture negative failures into passes.
|
||||
|
||||
## Resume after the initial publication
|
||||
|
||||
The [continuation status](resume-status.md) records new bounded logical fragmentation, six pinned external-allocator WB/WC buffer cases, refined ownership/budget decisions and the graphics supplement's one passing smoke, initial fixture failure and pressure-stopped repeat. The initial studies above remain separate protocols with their original raw records. No new result establishes physical backing identity, an application speedup, a blanket xmem provider or independently accepted texture/allocator support. M4 reproduction, trace-input validation and remaining reciprocal acceptance are dependencies; urgent host pressure blocks further controlled graphics/large footprint runs.
|
||||
@@ -0,0 +1,59 @@
|
||||
# Workstream A continuation after initial publication
|
||||
|
||||
Research issue [#473](https://github.com/MacosPorters/betterxen/issues/473), 2026-11-26. The requester manually published the initial A work at `8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8` on `research/d3dmetal-zero-copy`. The final-stage request authorizes DCO-signed publication on the dedicated `research/473-workstream-a-memory` branch; earlier local-only checkpoints below remain historical. Production, ABI, main and the original six-check baseline remain untouched. This page records evidence scope, including unresolved work, rather than declaring the research complete.
|
||||
|
||||
The [pinned handoff to Asufte](handoff-asufte.md) and [issue handoff](https://github.com/MacosPorters/betterxen/issues/473#issuecomment-7204146451) identify historical phase-two sources, corrected A2/A22 snapshots, exact hashes, commands, raw results and failures. The current B lead is Asufte/@atesahmet0 and his agent; CarReal is unavailable and skakwy is not participating. No identities are inferred from aliases.
|
||||
|
||||
## Inventory and remaining objectives
|
||||
|
||||
| Objective | Available evidence | Remaining limitation/dependency |
|
||||
| --- | --- | --- |
|
||||
| Physical accounting | Initial corrected 12-case size/type sweep; A22 six completed smaller/control cases and one urgent-pressure interruption; distinct creation, initialization, consumption, retirement and device-release accounting | Both repeated profiles remain incomplete. WB/UPLOAD 256 MiB continuation and larger repeats need sufficient headroom and acceptable kernel pressure. Earlier sampling cannot identify physical pages or a leak. |
|
||||
| Matched pooling/retirement | Published three seeded pairs, separate cold setup and API costs, guards, real delayed queued-copy retirement and omitted-copy failure control | No general application speedup; multi-queue stress and independent review remain open. |
|
||||
| Fragmentation | [Logical trace](fragmentation/README.md): 6012 checked snapshots across three seeds; capacity/fragmentation failures and pending-fence eligibility; corrupted-statistic rejection | Logical spans are not driver/physical fragmentation. The small published GPU trace did not saturate its slab. |
|
||||
| External allocator | [Pinned 3.3.0 evaluation](allocator-evaluation/README.md): WB/WC pilot plus six repeated, bounded-buffer cases; source/license checks before use; exact matched request traces and logical statistics | Buffers only, single queue/thread and one block. No runtime qualification of textures, every heap tier, defragmentation, migration or device loss. Caller supplies retirement. No production adoption. |
|
||||
| Inverted ownership | [Requirement matrix](inverted-ownership.md), now separating CPU alignment from resource placement, contents from pointer identity, migration peak from payload, pending retirement and driver retention | Console semantics not established by public evidence remain unknown. Requested VA, sections/scatter, reserve/decommit and pre-device allocations cannot be supplied by ordinary Map alone. |
|
||||
| Texture and placement | Published mip/mixed-heap/alias readbacks; invalid alignment/bounds creation accepted and rejection gate failed; valid buffer inheritance | Accepted invalid creation is not permission to submit it, nor independently a conformance finding. General format/layout coverage remains open. |
|
||||
| Sampling/render/depth/stencil | [One corrected graphics smoke](../gpu-correctness/textures-and-resources/findings.md): seven exact 512-pixel checks; initial author fixture bug preserved | Repeated two-dataset profile stopped before launching a guest on urgent pressure. New packed-frame checking and omitted-draw control remain pending; smoke predates frame capture. |
|
||||
| Reciprocal independent review | [B expectations](b-review-expectations.md) re-derived from public contracts; interpretation response to B; B reports A source reproduction/representative accounting audit | B subsequently published a402287; A source/data review is recorded below. M4 hardware reproduction, trace-input validation and a stopped-run hash discrepancy remain open. B has not reviewed new A graphics/allocator/fragmentation work. No final independent acceptance. |
|
||||
|
||||
## New records and reproducibility
|
||||
|
||||
All paths below are relative to the shared research root. Each raw bundle retains its own source snapshots, hashes and receipts; a later source revision never retroactively replaces an executed snapshot.
|
||||
|
||||
- `results/2026-11-26-apple-m4-arths17-logical-fragmentation/`: three seeded logical traces and separate interval-union oracle results.
|
||||
- `results/2026-11-26-apple-m4-arths17-logical-oracle-control/`: deliberate copied-log statistic corruption rejected.
|
||||
- `results/2026-11-26-apple-m4-arths17-external-allocator-pilot/`: WB/WC seed-473 pilot without the later oversized control.
|
||||
- `results/2026-11-26-apple-m4-arths17-external-allocator-bounded/`: six fresh WB/WC processes, seeds 473–475, valid oversized-request rejection and per-cycle data. A separate interval calculation checks all 216 statistics records and all six 432-request sequences against published raw pooling traces.
|
||||
- `results/2026-11-26-apple-m4-arths17-a23-render-lifetime-failure/`: original compiler-DLL lifetime bug; interrupted failure, not GPU acceptance.
|
||||
- `results/2026-11-26-apple-m4-arths17-a23-render-fixed-smoke/`: corrected single-process seven-frame comparisons, shader source/bytecode, no packed-frame dumps yet.
|
||||
- `results/2026-11-26-apple-m4-arths17-a23-render-pressure-stop/`: newer frame-capture source built, zero guest processes launched; urgent-pressure gate.
|
||||
|
||||
The external allocator source is unchanged and remains in ignored artifacts. Public records contain the original evaluation harness, exact file Git blob/SHA-256 identities, preserved license assessment and diagnostics; they do not redistribute proprietary runtimes or native/PE executables. Host tooling is ARM64; Windows guest probes are x86-64 PE32+ by design.
|
||||
|
||||
The graphics recipe and negative-control expectations are in the [fixture README](../gpu-correctness/textures-and-resources/README.md). The allocator recipe and separate statistical re-derivation command are in its [README](allocator-evaluation/README.md). A-local-2.3's explicit reduced memory selectors fill a missing case only when safety permits; selected sizes, types, session index and order are recorded. Reduced profiles cannot satisfy the full two-session common-profile gate.
|
||||
|
||||
## Architectural decision boundary
|
||||
|
||||
| Resource/requirement class | Evidence-supported candidate | What cannot be inferred |
|
||||
| --- | --- | --- |
|
||||
| Ordinary CPU-only, pre-device, fixed-address or section/scatter allocation | Conventional CPU/section ownership with explicit graphics transfer where required | Existing-memory wrapping, arbitrary CPU aliases or preservation of a pointer after moving storage |
|
||||
| Eligible CPU-visible graphics buffer | Bounded D3D12-owned persistent buffer/slab, only after checking actual CPU pointer alignment, legal resource/view offsets, owner and final-use fences | Universal xmem provider, physical zero-copy or automatic retirement from an allocator library |
|
||||
| Opaque textures and render/depth resources | Format-aware CPU subresource operations or DEFAULT upload/readback paths within tested contracts; explicit alias activation/initialization | Raw CPU texel pointers, console tiling, all formats/filters or physical backing representation |
|
||||
| Storage-class selection | Combine A correctness/accounting with independently reviewed B matched bandwidth/copy/coherence data | A heap-type performance ranking from unmatched barriers, non-idle sessions or a single profiled capture |
|
||||
|
||||
One logical payload budget must distinguish reserved slab backing, alignment waste, pending retirement and migration peak. Physical-footprint/RSS/compression/swap/driver observations remain separate accounting layers. Successful logical reuse does not imply that the OS releases a physical charge.
|
||||
|
||||
The initial claims that small allocations might fit precharged pools and that pooling might reduce API overhead remain hypotheses constrained by measurements; neither is promoted into a universal architecture claim. The invalid-placement acceptances, probe-owned DLL lifetime bug, failed negative gate and repeated urgent-pressure stops are retained as contrary or limiting evidence.
|
||||
|
||||
## Safety and independent acceptance
|
||||
|
||||
The user permits at most 23,000,000,000 bytes of the recorded conservative host occupied-memory estimate, with explicit margins; this is a ceiling, not a target or a guarantee about unrelated applications. Kernel urgent pressure independently blocks new cases even when that estimate is below the ceiling. Default runs require normal pressure; explicitly authorized warning runs remain labeled. No optional 2 GiB extension or concurrent CPU/GPU polling experiment was run. No pressure setting, baseline gate or tolerance was weakened to complete a profile.
|
||||
|
||||
Next authorized execution requires pressure recovery: finish tiny graphics repetition/control first, then only missing footprint cases if their size-dependent reserves fit. B source/raw evidence is now accessible; [actual A review](review-b.md) records source/data checks and open trace/finalization questions. Critical M4 reproduction still needs pressure recovery. The proposed A-local-2.4 fence-error patch also needs reciprocal review before dependent GPU execution. Publication authority is limited to the dedicated A research branch; main and B remain untouched. The report remains author evidence until those dependencies are satisfied; the #464 implementation is not certified here.
|
||||
|
||||
## Subsequent reciprocal review
|
||||
|
||||
A read-only export of B's newly published commit enabled independent source/raw review: 98 source snapshots matched, 5040 measured copy rows and 576 compute rows were checked, and published trace distributions recalculated. One stopped-run stderr hash mismatch and the missing target-only XML inputs remain explicit review findings, with requests on #473. A prepared a failure-2 disposable-process patch for its own post-submit fence errors; all five A probes compile, but no new GPU/fault-injection outcome is claimed. See [review details](review-b.md). The publication-access dependency above is resolved for B's source; pressure, trace provenance and reciprocal acceptance remain open.
|
||||
|
||||
Reproducible review/build records are retained separately in [B review data](../results/2026-11-26-apple-m4-arths17-a-b-reciprocal-review/review-receipt.json), [exact B small-02 build-only receipt](../results/2026-11-26-apple-m4-arths17-a-b-source-build/receipt.json), [five A probe builds after the fence patch](../results/2026-11-26-apple-m4-arths17-a24-fence-build/receipt.json), and [external allocator build after the patch](../results/2026-11-26-apple-m4-arths17-a24-allocator-build/receipt.json). All are explicitly separate from actual GPU execution. [Data-analysis controls](../results/2026-11-26-apple-m4-arths17-a23-data-analysis/receipt.json) rejected a corrupted allocator statistic and an empty pressure-stopped graphics profile. Existing archived logs are unchanged.
|
||||
@@ -0,0 +1,99 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Independent A recalculation of B's published records; no guest or B code execution."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import statistics
|
||||
|
||||
|
||||
def require(ok, message):
|
||||
if not ok:
|
||||
raise ValueError(message)
|
||||
|
||||
|
||||
def fields(line):
|
||||
return dict(re.findall(r'(\w+)=([^\s]+)', line))
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description=__doc__)
|
||||
ap.add_argument('b_research_root', type=Path)
|
||||
ap.add_argument('--output', required=True, type=Path)
|
||||
args = ap.parse_args()
|
||||
root = args.b_research_root
|
||||
results = root / 'results'
|
||||
summary = dict(scope='A source/raw-data review; no M4 hardware reproduction or physical-mechanism acceptance', source_snapshots=0, watch_phases=0, sweep_measured=0, compute_measured=0, compute_endpoint_pairs=0, traces=[])
|
||||
for receipt in sorted(results.glob('*/receipt.json')):
|
||||
r = json.loads(receipt.read_text())
|
||||
for relative, sha in r.get('sources', {}).items():
|
||||
source = receipt.parent / 'source' / relative
|
||||
require(source.is_file() and hashlib.sha256(source.read_bytes()).hexdigest() == sha, ('source hash', source))
|
||||
summary['source_snapshots'] += 1
|
||||
if r.get('group') not in ['small', 'sweep', 'compute']:
|
||||
continue
|
||||
for case in r['cases']:
|
||||
run = case.get('run', {})
|
||||
if run.get('exit') != 0 or run.get('error'):
|
||||
continue
|
||||
directory = receipt.parent / case['directory']
|
||||
text = (directory / 'stdout.txt').read_text()
|
||||
for line in text.splitlines():
|
||||
f = fields(line)
|
||||
if line.startswith('WATCH phase='):
|
||||
expected = {'fresh': [], 'only_second_guest_page': [4096], 'query_without_reset': [4096], 'second_and_third': [4096, 8192], 'after_query_reset': [], 'same_page_rearmed': [4096], 'host_boundary': [12288, 16384], 'after_explicit_reset': [], 'after_read_only': [], 'same_value_store_after_reset': [16384], 'final_empty': []}[f['phase']]
|
||||
actual_match = re.search(r' actual=(.*?) expected=', line)
|
||||
actual = [int(v) for v in actual_match[1].split(',') if v]
|
||||
require(f['rc'] == '0' and f['granularity'] == '4096' and int(f['count']) == len(expected) and actual == expected, line)
|
||||
summary['watch_phases'] += 1
|
||||
elif line.startswith('COPY '):
|
||||
a, b = map(int, f['matches'].split('/'))
|
||||
require(a == b and f['expected'] == f['actual'], line)
|
||||
if int(f['iter']) >= 0 and receipt.parent.name.endswith(('b-sweep-01', 'b-sweep-02')):
|
||||
summary['sweep_measured'] += 1
|
||||
elif line.startswith('COMPUTE '):
|
||||
outputs = int(f['matches'].split('/')[1])
|
||||
mode = f['mode']
|
||||
nloads, stride = {'both': (1, 1), 'full_read': (16, 1), 'sparse_read_4k': (1, 1024), 'sparse_read_16k': (1, 4096), 'write': (0, 1), 'omitted': (1, 1)}[mode]
|
||||
seed = int(f['seed'])
|
||||
expected = []
|
||||
for j in [0, outputs - 1]:
|
||||
total = seed + 37 * j
|
||||
for n in range(nloads):
|
||||
k = stride * (j + n * outputs)
|
||||
value = ((k ^ ((seed * 0x01010301) & 0xffffffff)) + 17 * k) & 0xffffffff
|
||||
total += value
|
||||
expected.append(0x6ba8fa03 if mode == 'omitted' else ((total & 0xffffffff) ^ 0xa5c35a3c))
|
||||
actual = [int(v, 16) for v in f['actual'].split(',')]
|
||||
require(actual == expected and int(f['matches'].split('/')[0]) == outputs, line)
|
||||
summary['compute_endpoint_pairs'] += 1
|
||||
if int(f['iter']) >= 0 and receipt.parent.name.endswith(('b-compute-01', 'b-compute-02')):
|
||||
summary['compute_measured'] += 1
|
||||
for path in sorted(results.glob('*/gpu-samples.json')):
|
||||
data = json.loads(path.read_text())
|
||||
require(len(data['samples']) == data['matched_intervals'] and len({tuple(v['ids']) for v in data['samples']}) == len(data['samples']), str(path))
|
||||
groups = {}
|
||||
for sample in data['samples']:
|
||||
require(sample['gpu_duration_ns'] > 0 and len(set(sample['comparison'].split('/'))) == 1, str(path))
|
||||
if sample['iter'] >= 0:
|
||||
groups.setdefault(sample['mode'], []).append(sample)
|
||||
for mode, samples in groups.items():
|
||||
require(len(samples) == 12, (path, mode))
|
||||
durations = [v['gpu_duration_ns'] / 1000 for v in samples]
|
||||
mid = statistics.median(durations)
|
||||
reported = data['distributions'][mode]
|
||||
require(abs(reported['median_gpu_us'] - mid) < 1e-8, (path, mode, 'median'))
|
||||
require(abs(reported['mad_gpu_us'] - statistics.median(abs(v - mid) for v in durations)) < 1e-8, (path, mode, 'mad'))
|
||||
for numerator, rate in reported['payload_GB_s'].items():
|
||||
derived = statistics.median(v[numerator] / v['gpu_duration_ns'] for v in samples)
|
||||
require(abs(derived - rate) < 1e-8, (path, mode, 'rate'))
|
||||
summary['traces'].append(dict(path=str(path.relative_to(root)), intervals=len(data['samples']), measured_groups=len(groups)))
|
||||
require(summary['sweep_measured'] == 5040 and summary['compute_measured'] == 576, ('incomplete reported uninstrumented profile', summary))
|
||||
args.output.write_text(json.dumps(summary, indent=2) + '\n')
|
||||
print(json.dumps(summary, indent=2))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,29 @@
|
||||
# A review of the published Workstream B evidence
|
||||
|
||||
Independent reviewer: Arths17's Codex agent, 2026-11-26 (America/Chicago). Reviewed [B commit a40228747470f0d184375e451b0173769c90aef5](https://github.com/MacosPorters/betterxen/commit/a40228747470f0d184375e451b0173769c90aef5), based on the requester-published A commit 8cc2f8f. B's raw directory names retain their original 2026-11-27 labels. No B source or results were edited or merged into A. [Expectations](b-review-expectations.md) were prepared before actual source access; [issue findings and patch review request](https://github.com/MacosPorters/betterxen/issues/473#issuecomment-7204728260) distinguish source/data review from pending hardware reproduction.
|
||||
|
||||
## Source and raw-data findings
|
||||
|
||||
The small-02 executed snapshot's two PE guests strictly compile on M4 using its build-only mode; zero guests were launched. All 98 published receipt source snapshots match their SHA-256 identities. The source uses volatile byte stores in the CPU watch case, so the same-value store is not removed by optimization. Actual page sets agree with the separately prepared contract expectations across 33 retained watch phases. The returned 4096-byte granularity is a version-scoped observation, not a substitute for querying granularity on another runtime. CPU-only watch does not load D3D12 or establish GPU tracking. The import case actually uses the watch-enabled allocation and records E_NOTIMPL.
|
||||
|
||||
The first placement negative combines misalignment and an overrun. The later small-03 fixture correctly adds offset 1 within a 128 KiB heap, isolating alignment while the resource span fits. Both creations return S_OK with objects. Invalid resources are neither mapped nor submitted. Actual CPU Map remainders vary between processes and remain separate from heap/GPU alignment. These facts support caller-side validation, not a formal invalid-call rejection contract.
|
||||
|
||||
For copy timing, source inspection finds fixed endpoint/interior sentinels, separately labeled word-per-page and full-byte modification, pre-timing poisoning, omitted-copy controls, full-output validation, seeded ordering and three warmups. Buffer heaps have matched copy descriptions and READBACK targets; necessary COMMON promotion versus UPLOAD GENERIC_READ states remain explicit. The [separate A recalculation](review-b-data.py) confirms 5040 measured copy records and 576 uninstrumented measured compute records. Its count selects the two uninstrumented sessions explicitly, rather than accidentally adding separate traced cases.
|
||||
|
||||
Compute source and HLSL use compatible root bindings, changing seeds, bounded indices, direct persistent custom outputs and an explicit staged DEFAULT control. The shader's unsigned sum is checked against a widened CPU expectation. A separately regenerated both recorded endpoint words in 1080 samples, including separate profiled captures, from source indices and modular arithmetic; all pairs match. This rechecks recorded endpoints and logged match counts, not an independently captured array of every GPU output. DEFAULT's fence interval includes readback while direct output does not; no intrinsic heap ranking follows. The shader payload is 4 MiB; the separate full-copy profile is 64 MiB.
|
||||
|
||||
B's published A review re-derives mip extents/byte counts, alias colors/depth words, placement/pointer distinctions, retirement boundaries and accounting limits. Its M5 alias and texture sources match A's hashes. The retained texture processes exit 1 at the same invalid-rejection gate while preserving the named positive readbacks; the alias runs exit 0. This is scoped same-source reproduction plus independent expectation review, distinct from independently authored B placement code and from any physical-mechanism conclusion. It does not accept the newly resumed A allocator/fragmentation/graphics work.
|
||||
|
||||
## Trace extraction limitation and retained hash discrepancy
|
||||
|
||||
Seven target-only extracts contain 300 shader dispatch intervals and 45 full-copy intervals, with unique command-buffer/encoder pairs in each capture. A recalculated all published measured medians, median absolute deviations and useful-payload rates from their individual durations. These arithmetic checks pass. Source inspection confirms PID filtering, encoder/GPU ID matching, count/order checks and exclusion of omitted shader dispatches and staging/readback blits from shader intervals. Those are promising safeguards, but the published extracts are outputs of that logic. They cannot independently validate its XML reference resolution or source-row selection. Minimal target-PID XML inputs with required reference nodes are requested; unrelated host trace data is unnecessary. GPU physical transaction rates and general heap ordering remain unaccepted.
|
||||
|
||||
A checked 156 published stdout/stderr/HLSL/DXBC output hashes. One discrepancy occurs in the already stopped `b-trace-01/00-wb/stderr.txt`: its receipt records the empty-file hash `e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855`, while the retained file contains the backend-handshake failure and hashes to `b7eab1251cc975b771929b1c6dfe6cb8511bb1ec75b3241336abe9651a151f83`. Both versions of the evidence are retained. The cause is unresolved; a late surviving guest write is a hypothesis requiring B's finalization audit. The reviewed completed-performance output hashes match. This discrepancy is not concealed by an overall pass label.
|
||||
|
||||
The timestamp diagnostic retains unchanged distinct poison values and correctly declines to report GPU duration in its corrected confirmation. The older sentinel difference is explicitly identified as invalid timing. This supports only that observed query/resolve failure on this stack; it is not a claim about hardware timestamp capability. Instrumented GPU intervals, uninstrumented completion intervals and physical memory traffic are different quantities.
|
||||
|
||||
## Reciprocal safety finding and next reproduction
|
||||
|
||||
B correctly identified that A's original Queue helper can throw after submission on a signal/event/wait error, unwinding resources without proven completion. This is a real error-path limitation; passing completed-fence records do not exercise it. The proposed A-local-2.4 patch changes that path to log and exit the disposable guest with failure 2, verifies the completed fence after the event, and shares that policy with the special delayed-gate path. It strictly compiles, but runtime fault injection and B's independent patch review remain pending. Historical helpers/snapshots, B helpers and the six frozen baseline checks are unchanged. No dependent GPU run is started before reciprocal helper review.
|
||||
|
||||
M4 reproduction of B's critical small placement/watch/import and representative copy/compute controls remains blocked by urgent host pressure. Build-only and source/data checks are not substituted for those hardware runs. The architecture interpretation is supported within these reviewed records, with the trace-input and stopped-output discrepancy open; final reciprocal acceptance remains pending controlled reproduction and resolution of those limitations.
|
||||
@@ -0,0 +1,32 @@
|
||||
# Reciprocal review status and reproduction handoff
|
||||
|
||||
Workstream A owns allocation/footprint and resource/lifetime fixtures. Workstream B owns copy/bandwidth, compute/coherence, synchronization and tracking implementation. B's implementation has not been re-created by A. A's footprint shader/queue support reuses the frozen historical implementation; it is not a newly commissioned B workstream.
|
||||
|
||||
## What has been reviewed
|
||||
|
||||
A read all five #473 comments present at start, including the complete revised plan, the six-check pinned baseline, the actual retained M4 supplemental sources/raw receipts, M5 report/review notes and the architectural discussion. M5 claim analysis distinguishes public contracts from attributed observations. The common baseline timings copy only endpoints, and different CUSTOM/UPLOAD barriers prevent ranking heap types. Process accounting, region labels and flat timings do not prove page identity. UMA=0 does not invalidate CPU-visible L0 heaps. The historical UNKNOWN texture Map requested no pointer, so it did not test a pointer-return failure.
|
||||
|
||||
These are A's source/documentation assessments, not independent certification of A's own baseline or supplemental implementation. See the [inventory](inventory/README.md) for the missing earlier source bytes, compiled historical shader identities, partial M5 backend receipt and unavailable private probe.
|
||||
|
||||
## B source/data review and reproduction status
|
||||
|
||||
The requester designated Asufte/@atesahmet0 as B lead; CarReal is unavailable. B has now published a40228747470f0d184375e451b0173769c90aef5, and A has reviewed actual executed sources and raw data. [A's B review](review-b.md) records verified source identities, data/statistical recalculation, a stopped-run stderr hash discrepancy and the target-only XML inputs needed to validate trace selection. M4 hardware reproduction is blocked by urgent pressure. Publication access is no longer the B blocker; final independent acceptance remains open.
|
||||
|
||||
B's published review independently derives the earlier A expectations and records M5 same-source alias/texture reproduction, preserving the texture negative gate's exit 1. Those scoped outcomes are distinct from the resumed A allocator, fragmentation and graphics work, which B has not reviewed. A prepared an A-local-2.4 fence-error patch after B identified unsafe exception unwinding without proven completion. It is compile-checked and submitted through #473 for review before dependent GPU runs. No account identity is inferred beyond the requester's explicit confirmation, and no B-owned implementation was modified.
|
||||
|
||||
## Review A independently
|
||||
|
||||
The exact executed sources, commands, source/PE/shader hashes and raw stdout/stderr are in append-only `../results/2026-11-26-apple-m4-arths17-*` bundles. Each source snapshot/receipt pins bytes independently of the mutable working tree. Archives preserve raw stdout/stderr; JSON diagnostic copies explicitly redact the local home prefix, retaining original and archived hashes. Build/runtime binaries and bottle copies are not published. The requester manually published the initial A research at 8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8. The [pinned evidence handoff](handoff-asufte.md) and [pre-review expectations](b-review-expectations.md) support reciprocal review. The final-stage request authorizes publication of resumed sources/results on the dedicated A research branch; independent acceptance remains separate.
|
||||
|
||||
One-command harness reproduction is in [README.md](README.md); choose the default normal-pressure profile or explicitly record an authorized warning-pressure profile. Respect the 23 GB conservative host-headroom guard and the single-GPU-workload rule. Do not turn the texture matrix's observed nonzero exits into passing status. The omitted-copy pool control must fail specifically for the expected mismatch.
|
||||
|
||||
Independent B review requests:
|
||||
|
||||
- Re-derive placed-resource allocation alignment/bounds, texture transfer layouts/mip extents and per-subresource CPU access from Microsoft documentation.
|
||||
- Inspect resource states, alias activation/post-activation RT/depth initialization, full-buffer inheritance under the advanced model, CPU store completion, queue-gate cleanup and fence/command retirement.
|
||||
- Reproduce critical pointer-alignment, buffer-inheritance, invalid-creation observations and representative mip/RT/depth cases on M5; retain unsupported/failure outcomes.
|
||||
- Audit footprint baseline/retirement definitions, correlated snapshots versus fresh sessions, compression/RSS/process-ledger distinctions, pool setup/reservation/slack and cold/warm timing boundaries.
|
||||
- Check raw per-allocation/per-free samples and per-session distributions; do not treat aggregate sample counts as independent machines or rank heaps from unmatched barriers.
|
||||
- Independently evaluate whether the requirement matrix justifies any proposed architecture, with all required fallbacks and unresolved console semantics explicit.
|
||||
|
||||
Author-run, reported, reproduced and independently accepted are distinct statuses. The resumed A results remain author-run/unaccepted. The earlier alias/texture observations have scoped B review/reproduction; see the actual review records. Critical M4 reproduction and remaining reciprocal acceptance are still dependencies.
|
||||
@@ -0,0 +1,265 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Workstream A local harness, version 2. Does not change shared protocols."""
|
||||
import argparse
|
||||
import fcntl
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import plistlib
|
||||
import re
|
||||
import shutil
|
||||
import signal
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
|
||||
|
||||
def sha(p):
|
||||
return hashlib.sha256(p.read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def capture(cmd, env, cwd, timeout=20):
|
||||
start = time.monotonic()
|
||||
try:
|
||||
p = subprocess.run([str(v) for v in cmd], env=env, cwd=cwd,
|
||||
capture_output=True, timeout=timeout)
|
||||
return dict(command=[str(v) for v in cmd], exit=p.returncode,
|
||||
stdout=p.stdout.decode(errors='replace'),
|
||||
stderr=p.stderr.decode(errors='replace'), seconds=time.monotonic()-start)
|
||||
except OSError as e:
|
||||
return dict(command=[str(v) for v in cmd], exit=127, stdout='', stderr=str(e))
|
||||
except subprocess.TimeoutExpired as e:
|
||||
return dict(command=[str(v) for v in cmd], exit=124, timeout=True,
|
||||
stdout=(e.stdout or b'').decode(errors='replace'),
|
||||
stderr=(e.stderr or b'').decode(errors='replace'))
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description=__doc__)
|
||||
ap.add_argument('--bottle', required=True, type=Path)
|
||||
ap.add_argument('--scratch', required=True, type=Path)
|
||||
ap.add_argument('--suite', choices=['memory', 'pool', 'texture', 'alias', 'render'], required=True)
|
||||
ap.add_argument('--smoke', action='store_true')
|
||||
ap.add_argument('--memory-sizes',default='64,256,1024')
|
||||
ap.add_argument('--memory-types',default='cpu-plain,cpu,wb,upload')
|
||||
ap.add_argument('--memory-repeats',type=int,choices=[1,2],default=2)
|
||||
ap.add_argument('--memory-repeat-start',type=int,choices=[0,1],default=0)
|
||||
ap.add_argument('--sessions',type=int,choices=[1,2,3],default=3,help='pool sessions')
|
||||
ap.add_argument('--session-start',type=int,choices=[0,1,2],default=0,help='pool trace session offset for nonduplicating continuation')
|
||||
ap.add_argument('--allow-warning', action='store_true', help='explicitly permit kernel warning level 1; urgent/critical still stop')
|
||||
ap.add_argument('--negative-control', action='store_true', help='pool omitted-copy or render omitted-draw control; expected exit 1')
|
||||
args = ap.parse_args()
|
||||
try:
|
||||
memory_sizes=[int(v) for v in args.memory_sizes.split(',')]
|
||||
except ValueError:
|
||||
ap.error('memory sizes must be comma-separated integer MiB values')
|
||||
memory_types=args.memory_types.split(',')
|
||||
if not memory_sizes or set(memory_sizes)-{64,256,1024} or not memory_types or set(memory_types)-{'cpu-plain','cpu','wb','upload'}:
|
||||
ap.error('memory profile must be an explicit subset of the common sizes/types')
|
||||
if len(set(memory_sizes)) != len(memory_sizes) or len(set(memory_types)) != len(memory_types):
|
||||
ap.error('memory profile must not contain duplicate sizes/types')
|
||||
if args.suite == 'memory' and args.memory_repeat_start + (1 if args.smoke else args.memory_repeats) > 2:
|
||||
ap.error('memory repeat indices must stay within the common two-session profile')
|
||||
if args.negative_control and args.suite not in ['pool','render']:
|
||||
ap.error('--negative-control only applies to pool/render')
|
||||
src = Path(__file__).resolve().parent
|
||||
repo = src.parents[3]
|
||||
base = args.scratch.expanduser().resolve()
|
||||
if base.exists() or base == repo or repo in base.parents:
|
||||
ap.error('scratch must be new and outside checkout')
|
||||
bottle = args.bottle.expanduser().resolve()
|
||||
original = (bottle/'cxbottle.conf').read_bytes()
|
||||
if b'"WineArch" = "win64"' not in original:
|
||||
ap.error('requires win64 bottle')
|
||||
lock = open('/tmp/betterxen-473-gpu.lock', 'a')
|
||||
try:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
except BlockingIOError:
|
||||
ap.error('another Workstream A GPU batch owns the lock')
|
||||
base.mkdir(mode=0o700)
|
||||
env = {k: os.environ[k] for k in ['HOME', 'USER', 'LOGNAME', 'PATH', 'LANG', 'LC_ALL'] if k in os.environ}
|
||||
env.update(TMPDIR=str(base)+'/', ROSETTA_ADVERTISE_AVX='1', CX_GRAPHICS_BACKEND='d3dmetal', WINEDEBUG='-all')
|
||||
cx = Path('/Applications/CrossOver.app/Contents/SharedSupport/CrossOver')
|
||||
wine = cx/'bin/wine'
|
||||
source = src/(args.suite+'.cpp') if args.suite in ['memory','pool'] else src.parent/'gpu-correctness/textures-and-resources'/{'texture':'probe.cpp','alias':'alias.cpp','render':'render.cpp'}[args.suite]
|
||||
exe, observer = base/'a-probe.exe', base/'observe'
|
||||
receipt = dict(protocol='A-local-2.4', suite=args.suite, allow_warning=args.allow_warning, utc=datetime.now(timezone.utc).isoformat(),
|
||||
ram_ceiling_bytes=23000000000, smoke=args.smoke, selected_memory_profile=(dict(sizes_MiB=[64] if args.smoke else memory_sizes,types=['wb'] if args.smoke else memory_types,repeats=1 if args.smoke else args.memory_repeats,repeat_start=args.memory_repeat_start) if args.suite=='memory' else None), independent_review='pending', environment={k: env[k] for k in ['ROSETTA_ADVERTISE_AVX', 'CX_GRAPHICS_BACKEND', 'WINEDEBUG']},
|
||||
sources={str(p.relative_to(repo)): sha(p) for p in [source, src/'support.h', src/'observe.cpp', Path(__file__)]},
|
||||
baseline_sha256=sha(src.parent/'probe.cpp'), tools={}, cases=[])
|
||||
snapshot=base/'source';snapshot.mkdir()
|
||||
for source_path in [source, src/'support.h', src/'observe.cpp', Path(__file__)]:
|
||||
destination = snapshot/source_path.relative_to(repo)
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(source_path, destination)
|
||||
def save():
|
||||
(base/'receipt.json').write_text(json.dumps(receipt, indent=2)+'\n')
|
||||
cmds = {
|
||||
'chip': ['sysctl','-n','machdep.cpu.brand_string'], 'ram':['sysctl','-n','hw.memsize'],
|
||||
'host':['uname','-m'], 'macos':['sw_vers'], 'page':['sysctl','-n','hw.pagesize'],
|
||||
'swap_before':['sysctl','vm.swapusage'], 'pressure_before':['memory_pressure','-Q'], 'vm_before':['vm_stat'],
|
||||
'load_before':['ps','-axo','pid,pcpu,comm'], 'wine_version':[wine,'--version'],
|
||||
'wine_build':[cx/'bin/wineloader','--version'],
|
||||
'kernel_pressure_before':['sysctl','-n','kern.memorystatus_vm_pressure_level'],
|
||||
'rosetta':['pkgutil','--pkg-info','com.apple.pkg.RosettaUpdateAuto'],
|
||||
'gcc':['x86_64-w64-mingw32-g++','--version'], 'clang':['xcrun','clang++','--version'],
|
||||
'sdk':['xcrun','--show-sdk-version'], 'python':['python3','--version'],
|
||||
'compiler_arch':['file',str(Path(shutil.which('x86_64-w64-mingw32-g++')).resolve())],
|
||||
'compiler_lipo':['lipo','-archs',str(Path(shutil.which('x86_64-w64-mingw32-g++')).resolve())],
|
||||
'compiler_links':['otool','-L',str(Path(shutil.which('x86_64-w64-mingw32-g++')).resolve())],
|
||||
'build_pe':['x86_64-w64-mingw32-g++','-std=c++20','-O2','-static','-static-libgcc','-static-libstdc++','-Wall','-Wextra','-Werror',source,'-o',exe,'-lkernel32'],
|
||||
'build_observer':['xcrun','clang++','-std=c++20','-O2','-arch','arm64','-Wall','-Wextra','-Werror',src/'observe.cpp','-o',observer],
|
||||
'formats':['file',exe,observer], 'observer_arch':['lipo','-archs',observer], 'observer_links':['otool','-L',observer],
|
||||
}
|
||||
for name, cmd in cmds.items():
|
||||
receipt['tools'][name]=capture(cmd,env,base,60)
|
||||
save()
|
||||
if name.startswith('build_') and receipt['tools'][name]['exit']:
|
||||
raise RuntimeError(receipt['tools'][name])
|
||||
receipt['binaries']={p.name:sha(p) for p in [exe,observer]}
|
||||
resources=cx/'lib64/apple_gptk/external/D3DMetal.framework/Versions/A/Resources'
|
||||
receipt['framework']={p.name:plistlib.loads(p.read_bytes()) for p in resources.glob('*.plist')}
|
||||
receipt['runtime_hashes']={str(p):sha(p) for p in [cx/'lib64/apple_gptk/wine/x86_64-windows/d3d12.dll', cx/'lib/wine/x86_64-windows/d3dcompiler_47.dll']}
|
||||
def headroom():
|
||||
vm=capture(['vm_stat'],env,base)
|
||||
ram=capture(['sysctl','-n','hw.memsize'],env,base)
|
||||
page=re.search(r'page size of (\d+) bytes',vm['stdout'])
|
||||
free=re.search(r'Pages free:\s+(\d+)',vm['stdout'])
|
||||
filebacked=re.search(r'File-backed pages:\s+(\d+)',vm['stdout'])
|
||||
if vm['exit'] or ram['exit'] or not all([page,free,filebacked]):
|
||||
raise RuntimeError('cannot measure host RAM headroom')
|
||||
# Report the metric precisely; this is not a claim to match Activity Monitor.
|
||||
used=max(0,int(ram['stdout'])-(int(free[1])+int(filebacked[1]))*int(page[1]))
|
||||
return dict(metric='physical RAM minus free and file-backed pages; conservative non-file-cache occupied estimate',
|
||||
occupied_bytes=used,ceiling_bytes=23000000000,available_below_ceiling_bytes=23000000000-used,vm_stat=vm,ram=ram)
|
||||
|
||||
preflight = headroom()
|
||||
kernel = capture(['sysctl','-n','kern.memorystatus_vm_pressure_level'],env,base)
|
||||
receipt['preflight_before_bottle_copy'] = dict(ram=preflight,kernel_pressure=kernel)
|
||||
if (preflight['available_below_ceiling_bytes'] < 512*1024**2 or kernel['exit'] or
|
||||
not kernel['stdout'].strip().isdigit() or
|
||||
int(kernel['stdout'].strip()) > (1 if args.allow_warning else 0)):
|
||||
receipt['stop_reason'] = 'preflight headroom/pressure guard; no bottle copied or guest started'
|
||||
receipt['source_bottle_unchanged'] = (bottle/'cxbottle.conf').read_bytes() == original
|
||||
save()
|
||||
return 2
|
||||
temp=base/'bottle'
|
||||
shutil.copytree(bottle,temp,symlinks=True)
|
||||
conf=re.sub(r'(?m)^\[Bottle\]\s*$', '[Bottle]\n"AllowUntrusted" = "1"', original.decode(), count=1)
|
||||
conf+='\n[EnvironmentVariables]\n"CX_GRAPHICS_BACKEND" = "d3dmetal"\n[CrossOver]\n"AntiVirusScan" = "untrusted"\n'
|
||||
(temp/'cxbottle.conf').write_text(conf)
|
||||
receipt['bottle_original_sha256']=hashlib.sha256(original).hexdigest()
|
||||
receipt['bottle_settings']=[line.strip() for line in conf.splitlines() if re.match(r'"(WineArch|Template|WindowsVersion|Version|CX_GRAPHICS_BACKEND|AllowUntrusted|AntiVirusScan)"',line)]
|
||||
common=[str(wine),'--bottle',str(temp),'--no-update','--no-gui',str(exe)]
|
||||
|
||||
def run(name, argv, expected_exit=0):
|
||||
memory=headroom()
|
||||
reserve=512*1024**2+(2*int(argv[1]) if args.suite=='memory' else 0)
|
||||
if memory['available_below_ceiling_bytes']<reserve:
|
||||
receipt.setdefault('not_run',[]).append(dict(name=name,reason='23 GB headroom guard; no guest started',headroom=memory,required_reserve_bytes=reserve));save();return
|
||||
kernel_pressure=capture(['sysctl','-n','kern.memorystatus_vm_pressure_level'],env,base)
|
||||
if kernel_pressure['exit'] or not kernel_pressure['stdout'].strip().isdigit() or int(kernel_pressure['stdout'].strip())>(1 if args.allow_warning else 0):
|
||||
receipt['stop_reason']={'kernel_pressure_gate_before':name,'reading':kernel_pressure};save()
|
||||
raise RuntimeError('kernel memory pressure exceeds explicitly selected profile; no case started')
|
||||
pressure=capture(['memory_pressure','-Q'],env,base)
|
||||
match=re.search(r'free percentage: (\d+)%',pressure['stdout'])
|
||||
if pressure['exit'] or not match or int(match[1])<30:
|
||||
receipt['stop_reason']={'pressure_gate_before':name,'reading':pressure};save()
|
||||
raise RuntimeError('memory pressure headroom below 30% or unreadable')
|
||||
case=base/name;case.mkdir()
|
||||
metadata=dict(name=name,args=argv,expected_exit=expected_exit,command=common+argv,timeout_seconds=240,pressure_before=pressure,kernel_pressure_before=kernel_pressure,ram_before=memory,snapshots=[])
|
||||
receipt['cases'].append(metadata);save()
|
||||
expired=threading.Event()
|
||||
start=time.monotonic()
|
||||
with (case/'stdout.txt').open('wb') as out,(case/'stderr.txt').open('wb') as err:
|
||||
p=subprocess.Popen(common+argv,env=env,cwd=case,stdout=subprocess.PIPE,stderr=err,stdin=subprocess.PIPE,start_new_session=True)
|
||||
def kill():
|
||||
try: os.killpg(p.pid,signal.SIGKILL)
|
||||
except ProcessLookupError: pass
|
||||
def expire():
|
||||
expired.set();kill()
|
||||
timer=threading.Timer(240,expire);timer.start()
|
||||
pid=None
|
||||
try:
|
||||
for line in p.stdout:
|
||||
out.write(line);out.flush()
|
||||
if not line.startswith(b'STAGE '):continue
|
||||
if pid is None:
|
||||
found=capture(['lsof','-t','-a','-c','a-probe.exe',str(exe)],env,base)
|
||||
candidates=sorted({int(x) for x in found['stdout'].split() if x.isdigit()})
|
||||
if len(candidates)!=1:raise RuntimeError('ambiguous PE PID: '+repr(found))
|
||||
pid=candidates[0];metadata['host_pid']=pid
|
||||
libs=capture(['lsof','-n','-p',str(pid)],env,base)
|
||||
metadata['backend_paths_excerpt']=['/'+line.split('/',1)[-1] for line in libs['stdout'].splitlines() if any(x in line for x in ['apple_gptk/wine/x86_64-windows/d3d12.dll','D3DMetal.framework/Versions/A/D3DMetal','/rosetta/runtime'])]
|
||||
metadata['backend_lsof_exit']=libs['exit']
|
||||
phase=line.decode().split()[1]
|
||||
snap=dict(phase=phase,marker=line.decode().strip(),samples=[],ram=headroom())
|
||||
if snap['ram']['available_below_ceiling_bytes']<256*1024**2:
|
||||
raise RuntimeError('stop before 23 GB host occupied-memory ceiling')
|
||||
for _ in range(3):
|
||||
result=capture([observer,str(pid)],env,base)
|
||||
if not result['exit']:result['data']=json.loads(result['stdout'])
|
||||
snap['samples'].append(result)
|
||||
commands={'footprint':['footprint','-p',str(pid),'-f','bytes','--swapped'],
|
||||
'vmmap':['vmmap','-summary',str(pid)], 'vmstat':['vm_stat'],
|
||||
'pressure':['memory_pressure','-Q'],'swap':['sysctl','vm.swapusage'],
|
||||
'kernel_pressure':['sysctl','-n','kern.memorystatus_vm_pressure_level']}
|
||||
ptr=re.search(rb'cpu_ptr=([0-9A-Fa-f]+)',line)
|
||||
if ptr and int(ptr[1],16):commands['pointer_vmmap']=['vmmap','-w',str(pid),'0x'+ptr[1].decode()]
|
||||
for tool,cmd in commands.items():
|
||||
result=capture(cmd,env,base,15)
|
||||
filename=f'{phase}-{tool}.json';(case/filename).write_text(json.dumps(result,indent=2)+'\n')
|
||||
snap[tool]=dict(exit=result['exit'],file=filename)
|
||||
if tool=='kernel_pressure' and (result['exit'] or not result['stdout'].strip().isdigit() or int(result['stdout'].strip())>(1 if args.allow_warning else 0)):
|
||||
raise RuntimeError('kernel pressure changed; stop this case without resuming guest')
|
||||
if tool=='pressure':
|
||||
m=re.search(r'free percentage: (\d+)%',result['stdout'])
|
||||
if result['exit'] or not m or int(m[1])<25:raise RuntimeError('stage pressure safety stop')
|
||||
metadata['snapshots'].append(snap);save()
|
||||
p.stdin.write(b'\n');p.stdin.flush()
|
||||
p.wait()
|
||||
except BaseException as e:
|
||||
metadata['harness_error']=repr(e);kill();p.wait();raise
|
||||
finally:
|
||||
timer.cancel();metadata.update(exit=p.returncode,timed_out=expired.is_set(),seconds=time.monotonic()-start)
|
||||
metadata['outputs']={f.name:sha(f) for f in case.iterdir() if f.is_file()}
|
||||
(case/'case.json').write_text(json.dumps(metadata,indent=2)+'\n');save()
|
||||
print(name,'exit',metadata['exit'],'timeout',metadata['timed_out'],flush=True)
|
||||
if metadata['timed_out']:raise RuntimeError('case timed out: '+name)
|
||||
if metadata['exit']!=expected_exit:
|
||||
receipt.setdefault('failed_cases',[]).append(name);save()
|
||||
if args.suite not in ['texture','alias','render']:raise RuntimeError('case failed: '+name)
|
||||
if expected_exit and (b'END failure reason=sampled pixels mismatch' if args.suite=='render' else b'END failure reason=trace guard/interior mismatch') not in (case/'stdout.txt').read_bytes():
|
||||
raise RuntimeError('negative control failed for an unexpected reason')
|
||||
try:
|
||||
if args.suite=='memory':
|
||||
for repeat in range(args.memory_repeat_start,args.memory_repeat_start+(1 if args.smoke else args.memory_repeats)):
|
||||
sizes=[64] if args.smoke else list(memory_sizes)
|
||||
types=['wb'] if args.smoke else list(memory_types)
|
||||
if repeat%2:types.reverse();sizes.reverse()
|
||||
for size in sizes:
|
||||
for typ in types:run(f'memory-{typ}-{size}MiB-r{repeat}',[typ,str(size*1024**2)])
|
||||
elif args.suite=='render' and args.negative_control:
|
||||
run('render-omitted-draw-control',['omit'],1)
|
||||
elif args.suite=='pool' and args.negative_control:
|
||||
run('pool-omitted-copy-control',['omit','473'],1)
|
||||
elif args.suite=='pool':
|
||||
for session in range(args.session_start,args.session_start+(1 if args.smoke else args.sessions)):
|
||||
modes=['individual','pooled'] if session%2==0 else ['pooled','individual']
|
||||
for mode in modes:run(f'pool-{mode}-s{session}',[mode,str(473+session)])
|
||||
else:
|
||||
for session in range(1 if args.smoke else 2):run(f'{args.suite}-s{session}',[str(session)])
|
||||
finally:
|
||||
for name,cmd in {'pressure_after':['memory_pressure','-Q'],'vm_after':['vm_stat'],'swap_after':['sysctl','vm.swapusage'],'kernel_pressure_after':['sysctl','-n','kern.memorystatus_vm_pressure_level']}.items():receipt['tools'][name]=capture(cmd,env,base)
|
||||
stop=dict(env,WINEPREFIX=str(temp))
|
||||
receipt['server_stop']=capture([cx/'bin/wineserver','-k'],stop,base)
|
||||
receipt['server_wait']=capture([cx/'bin/wineserver','-w'],stop,base)
|
||||
receipt['source_bottle_unchanged']=(bottle/'cxbottle.conf').read_bytes()==original
|
||||
shutil.rmtree(temp);save()
|
||||
return int(bool(receipt.get('failed_cases') or receipt.get('not_run')))
|
||||
|
||||
if __name__=='__main__':
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,409 @@
|
||||
#pragma once
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Supplemental original synthetic tests; baseline ../probe.cpp is unchanged.
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#define NOMINMAX
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <d3d12.h>
|
||||
#include <d3dcompiler.h>
|
||||
#include <dxgi1_4.h>
|
||||
#include <emmintrin.h>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <windows.h>
|
||||
|
||||
template <class T> struct Ref {
|
||||
T *p = nullptr;
|
||||
Ref() = default;
|
||||
Ref(const Ref &) = delete;
|
||||
Ref &operator=(const Ref &) = delete;
|
||||
~Ref() { clear(); }
|
||||
void clear() {
|
||||
if (p) {
|
||||
p->Release();
|
||||
p = nullptr;
|
||||
}
|
||||
}
|
||||
T *operator->() const { return p; }
|
||||
void **out() { return reinterpret_cast<void **>(&p); }
|
||||
};
|
||||
inline void require(HRESULT h, const char *name) {
|
||||
if (FAILED(h)) {
|
||||
std::printf("FAIL %s HRESULT=0x%08lX\n", name, (unsigned long)h);
|
||||
throw std::runtime_error(name);
|
||||
}
|
||||
}
|
||||
inline void report(HRESULT h, const char *name) {
|
||||
std::printf("API %s HRESULT=0x%08lX\n", name, (unsigned long)h);
|
||||
}
|
||||
template <class T> static T symbol(HMODULE m, const char *name) {
|
||||
FARPROC p = GetProcAddress(m, name);
|
||||
if (!p)
|
||||
throw std::runtime_error(name);
|
||||
T result;
|
||||
static_assert(sizeof(result) == sizeof(p));
|
||||
std::memcpy(&result, &p, sizeof(p));
|
||||
return result;
|
||||
}
|
||||
inline double ticks() {
|
||||
LARGE_INTEGER t;
|
||||
QueryPerformanceCounter(&t);
|
||||
return double(t.QuadPart);
|
||||
}
|
||||
inline double frequency() {
|
||||
LARGE_INTEGER t;
|
||||
QueryPerformanceFrequency(&t);
|
||||
return double(t.QuadPart);
|
||||
}
|
||||
inline D3D12_HEAP_PROPERTIES properties(D3D12_HEAP_TYPE type) {
|
||||
D3D12_HEAP_PROPERTIES p{};
|
||||
p.Type = type;
|
||||
p.CreationNodeMask = 1;
|
||||
p.VisibleNodeMask = 1;
|
||||
return p;
|
||||
}
|
||||
static D3D12_RESOURCE_DESC
|
||||
bufferDesc(UINT64 bytes,
|
||||
D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE) {
|
||||
D3D12_RESOURCE_DESC r{};
|
||||
r.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
|
||||
r.Width = bytes;
|
||||
r.Height = 1;
|
||||
r.DepthOrArraySize = 1;
|
||||
r.MipLevels = 1;
|
||||
r.SampleDesc.Count = 1;
|
||||
r.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
|
||||
r.Flags = flags;
|
||||
return r;
|
||||
}
|
||||
struct Context {
|
||||
HMODULE dll = nullptr;
|
||||
Ref<ID3D12Device3> device;
|
||||
Context() {
|
||||
dll = LoadLibraryA("d3d12.dll");
|
||||
if (!dll)
|
||||
throw std::runtime_error("LoadLibrary d3d12");
|
||||
char path[2048]{};
|
||||
GetModuleFileNameA(dll, path, sizeof(path));
|
||||
std::printf("D3D12_DLL %s\n", path);
|
||||
using Create =
|
||||
HRESULT(WINAPI *)(IUnknown *, D3D_FEATURE_LEVEL, REFIID, void **);
|
||||
require(symbol<Create>(dll, "D3D12CreateDevice")(
|
||||
nullptr, D3D_FEATURE_LEVEL_11_0, __uuidof(ID3D12Device3),
|
||||
device.out()),
|
||||
"CreateDevice3");
|
||||
bool shim = GetModuleHandleA("d3d12_xs.dll") != nullptr;
|
||||
std::printf("SHIM_LOADED %d\n", shim);
|
||||
if (shim)
|
||||
throw std::runtime_error("shim contamination");
|
||||
}
|
||||
};
|
||||
struct Queue {
|
||||
ID3D12Device3 *d;
|
||||
Ref<ID3D12CommandQueue> q;
|
||||
Ref<ID3D12CommandAllocator> allocator;
|
||||
Ref<ID3D12GraphicsCommandList> list;
|
||||
Ref<ID3D12Fence> fence;
|
||||
HANDLE event = nullptr;
|
||||
UINT64 value = 0;
|
||||
explicit Queue(ID3D12Device3 *device) : d(device) {
|
||||
D3D12_COMMAND_QUEUE_DESC desc{};
|
||||
desc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
|
||||
require(d->CreateCommandQueue(&desc, __uuidof(ID3D12CommandQueue), q.out()),
|
||||
"CreateCommandQueue");
|
||||
require(d->CreateCommandAllocator(
|
||||
desc.Type, __uuidof(ID3D12CommandAllocator), allocator.out()),
|
||||
"CreateCommandAllocator");
|
||||
require(d->CreateCommandList(0, desc.Type, allocator.p, nullptr,
|
||||
__uuidof(ID3D12GraphicsCommandList),
|
||||
list.out()),
|
||||
"CreateCommandList");
|
||||
require(list->Close(), "initial Close");
|
||||
require(d->CreateFence(0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence),
|
||||
fence.out()),
|
||||
"CreateFence");
|
||||
event = CreateEventW(nullptr, FALSE, FALSE, nullptr);
|
||||
if (!event)
|
||||
throw std::runtime_error("CreateEvent");
|
||||
}
|
||||
~Queue() {
|
||||
if (event)
|
||||
CloseHandle(event);
|
||||
}
|
||||
void begin() {
|
||||
require(allocator->Reset(), "allocator Reset");
|
||||
require(list->Reset(allocator.p, nullptr), "list Reset");
|
||||
}
|
||||
void transition(ID3D12Resource *r, D3D12_RESOURCE_STATES a,
|
||||
D3D12_RESOURCE_STATES b) {
|
||||
if (a == b)
|
||||
return;
|
||||
D3D12_RESOURCE_BARRIER x{};
|
||||
x.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
|
||||
x.Transition.pResource = r;
|
||||
x.Transition.StateBefore = a;
|
||||
x.Transition.StateAfter = b;
|
||||
x.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
|
||||
list->ResourceBarrier(1, &x);
|
||||
}
|
||||
void close() { require(list->Close(), "Close"); }
|
||||
[[noreturn]] void stopInFlight(const char *operation, HRESULT status,
|
||||
UINT64 target, UINT64 completed,
|
||||
DWORD wait = WAIT_FAILED) {
|
||||
std::printf("FAIL in_flight operation=%s HRESULT=0x%08lX target=%llu "
|
||||
"completed=%llu wait=%lu process_exit=2\n",
|
||||
operation, (unsigned long)status, target, completed,
|
||||
(unsigned long)wait);
|
||||
std::fflush(nullptr);
|
||||
// The disposable guest must not unwind/recycle resources without proof of
|
||||
// completion. Its supervising runner records exit 2 as a failed case.
|
||||
ExitProcess(2);
|
||||
}
|
||||
void waitFor(UINT64 target) {
|
||||
UINT64 completed = fence->GetCompletedValue();
|
||||
if (completed == ~UINT64(0))
|
||||
stopInFlight("device removed fence", E_FAIL, target, completed);
|
||||
if (completed >= target)
|
||||
return;
|
||||
HRESULT armed = fence->SetEventOnCompletion(target, event);
|
||||
if (FAILED(armed))
|
||||
stopInFlight("SetEventOnCompletion", armed, target, completed);
|
||||
DWORD waited = WaitForSingleObject(event, 10000);
|
||||
completed = fence->GetCompletedValue();
|
||||
if (waited != WAIT_OBJECT_0 || completed == ~UINT64(0) || completed < target)
|
||||
stopInFlight("fence completion", E_FAIL, target, completed, waited);
|
||||
}
|
||||
void executeClosed() {
|
||||
ID3D12CommandList *lists[] = {list.p};
|
||||
q->ExecuteCommandLists(1, lists);
|
||||
HRESULT signalled = q->Signal(fence.p, ++value);
|
||||
if (FAILED(signalled))
|
||||
stopInFlight("Signal", signalled, value, fence->GetCompletedValue());
|
||||
waitFor(value);
|
||||
}
|
||||
void finish() {
|
||||
close();
|
||||
_mm_sfence();
|
||||
executeClosed();
|
||||
require(d->GetDeviceRemovedReason(), "GetDeviceRemovedReason");
|
||||
}
|
||||
};
|
||||
struct Buffer {
|
||||
Ref<ID3D12Heap> heap;
|
||||
Ref<ID3D12Resource> resource;
|
||||
void *cpu = nullptr;
|
||||
UINT64 size = 0;
|
||||
void allocate(ID3D12Device3 *d, UINT64 bytes, const std::string &type,
|
||||
bool uav = false) {
|
||||
size = bytes;
|
||||
auto desc =
|
||||
bufferDesc(bytes, uav ? D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS
|
||||
: D3D12_RESOURCE_FLAG_NONE);
|
||||
auto state =
|
||||
uav ? D3D12_RESOURCE_STATE_COMMON : D3D12_RESOURCE_STATE_GENERIC_READ;
|
||||
if (type == "upload" || type == "readback") {
|
||||
if (uav)
|
||||
throw std::runtime_error(
|
||||
"UAV on upload/readback forbidden in this probe");
|
||||
auto p = properties(type == "upload" ? D3D12_HEAP_TYPE_UPLOAD
|
||||
: D3D12_HEAP_TYPE_READBACK);
|
||||
if (type == "readback")
|
||||
state = D3D12_RESOURCE_STATE_COPY_DEST;
|
||||
require(d->CreateCommittedResource(&p, D3D12_HEAP_FLAG_NONE, &desc, state,
|
||||
nullptr, __uuidof(ID3D12Resource),
|
||||
resource.out()),
|
||||
"committed buffer");
|
||||
} else {
|
||||
D3D12_HEAP_DESC hd{};
|
||||
hd.SizeInBytes = (bytes + 65535) & ~UINT64(65535);
|
||||
hd.Alignment = 65536;
|
||||
hd.Properties = properties(D3D12_HEAP_TYPE_CUSTOM);
|
||||
hd.Properties.CPUPageProperty =
|
||||
type == "wc" ? D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE
|
||||
: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK;
|
||||
hd.Properties.MemoryPoolPreference = D3D12_MEMORY_POOL_L0;
|
||||
require(d->CreateHeap(&hd, __uuidof(ID3D12Heap), heap.out()),
|
||||
"custom heap");
|
||||
require(d->CreatePlacedResource(heap.p, 0, &desc, state, nullptr,
|
||||
__uuidof(ID3D12Resource), resource.out()),
|
||||
"placed buffer");
|
||||
}
|
||||
}
|
||||
void map() {
|
||||
require(resource->Map(0, nullptr, &cpu), "Map buffer");
|
||||
if (!cpu)
|
||||
throw std::runtime_error("null buffer pointer");
|
||||
}
|
||||
void release() {
|
||||
cpu = nullptr;
|
||||
resource.clear();
|
||||
heap.clear();
|
||||
}
|
||||
};
|
||||
[[maybe_unused]] inline void identity(Context &c) {
|
||||
using Factory = HRESULT(WINAPI *)(UINT, REFIID, void **);
|
||||
HMODULE dxgi = LoadLibraryA("dxgi.dll");
|
||||
if (!dxgi)
|
||||
throw std::runtime_error("dxgi load");
|
||||
Ref<IDXGIFactory4> f;
|
||||
require(symbol<Factory>(dxgi, "CreateDXGIFactory2")(
|
||||
0, __uuidof(IDXGIFactory4), f.out()),
|
||||
"factory4");
|
||||
LUID luid = c.device->GetAdapterLuid();
|
||||
Ref<IDXGIAdapter2> a;
|
||||
require(f->EnumAdapterByLuid(luid, __uuidof(IDXGIAdapter2), a.out()),
|
||||
"adapter by device LUID");
|
||||
DXGI_ADAPTER_DESC2 ad{};
|
||||
require(a->GetDesc2(&ad), "GetDesc2");
|
||||
char name[512]{};
|
||||
WideCharToMultiByte(CP_UTF8, 0, ad.Description, -1, name, sizeof(name),
|
||||
nullptr, nullptr);
|
||||
std::printf(
|
||||
"ADAPTER description=%s vendor=0x%04X device=0x%04X subsystem=0x%08X "
|
||||
"revision=%u flags=%u dedicated_video_bytes=%llu "
|
||||
"dedicated_system_bytes=%llu shared_system_bytes=%llu luid=%08lX:%08lX\n",
|
||||
name, ad.VendorId, ad.DeviceId, ad.SubSysId, ad.Revision, ad.Flags,
|
||||
(unsigned long long)ad.DedicatedVideoMemory,
|
||||
(unsigned long long)ad.DedicatedSystemMemory,
|
||||
(unsigned long long)ad.SharedSystemMemory, (unsigned long)luid.HighPart,
|
||||
(unsigned long)luid.LowPart);
|
||||
D3D12_FEATURE_DATA_D3D12_OPTIONS opts{};
|
||||
require(c.device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &opts,
|
||||
sizeof(opts)),
|
||||
"options");
|
||||
std::printf(
|
||||
"OPTIONS ResourceHeapTier=%d CrossAdapterRowMajorTextureSupported=%d "
|
||||
"StandardSwizzle64KBSupported=%d\n",
|
||||
opts.ResourceHeapTier, opts.CrossAdapterRowMajorTextureSupported,
|
||||
opts.StandardSwizzle64KBSupported);
|
||||
D3D12_FEATURE_DATA_ARCHITECTURE1 arch{};
|
||||
require(c.device->CheckFeatureSupport(D3D12_FEATURE_ARCHITECTURE1, &arch,
|
||||
sizeof(arch)),
|
||||
"architecture1");
|
||||
std::printf(
|
||||
"ARCH UMA=%d CacheCoherentUMA=%d TileBasedRenderer=%d IsolatedMMU=%d\n",
|
||||
arch.UMA, arch.CacheCoherentUMA, arch.TileBasedRenderer,
|
||||
arch.IsolatedMMU);
|
||||
for (auto type : {D3D12_HEAP_TYPE_DEFAULT, D3D12_HEAP_TYPE_UPLOAD,
|
||||
D3D12_HEAP_TYPE_READBACK}) {
|
||||
auto p = c.device->GetCustomHeapProperties(0, type);
|
||||
std::printf(
|
||||
"CUSTOM_PROPERTIES input_type=%d Type=%d CPUPageProperty=%d "
|
||||
"MemoryPoolPreference=%d CreationNodeMask=%u VisibleNodeMask=%u\n",
|
||||
type, p.Type, p.CPUPageProperty, p.MemoryPoolPreference,
|
||||
p.CreationNodeMask, p.VisibleNodeMask);
|
||||
}
|
||||
SYSTEM_INFO si{};
|
||||
GetSystemInfo(&si);
|
||||
std::printf("GUEST_PAGE_SIZE %lu ALLOCATION_GRANULARITY %lu\n", si.dwPageSize,
|
||||
si.dwAllocationGranularity);
|
||||
}
|
||||
struct Shader {
|
||||
Ref<ID3D12RootSignature> root;
|
||||
Ref<ID3D12PipelineState> pipeline;
|
||||
static constexpr const char *code = R"HLSL(
|
||||
ByteAddressBuffer source : register(t0);
|
||||
RWByteAddressBuffer result : register(u0);
|
||||
cbuffer Parameters : register(b0) { uint count; uint salt; uint wordStride; };
|
||||
[numthreads(64,1,1)]
|
||||
void main(uint3 tid : SV_DispatchThreadID) {
|
||||
uint accum=0;
|
||||
for(uint i=tid.x; i<count; i+=256) accum ^= source.Load(i*wordStride*4)+salt;
|
||||
result.Store(tid.x*4,accum);
|
||||
}
|
||||
)HLSL";
|
||||
explicit Shader(Context &c) {
|
||||
HMODULE compiler = LoadLibraryA("d3dcompiler_47.dll");
|
||||
if (!compiler)
|
||||
throw std::runtime_error("d3dcompiler47 unavailable");
|
||||
char path[2048]{};
|
||||
GetModuleFileNameA(compiler, path, sizeof(path));
|
||||
std::printf("SHADER_COMPILER %s\n", path);
|
||||
using Compile = HRESULT(WINAPI *)(
|
||||
LPCVOID, SIZE_T, LPCSTR, const D3D_SHADER_MACRO *, ID3DInclude *,
|
||||
LPCSTR, LPCSTR, UINT, UINT, ID3DBlob **, ID3DBlob **);
|
||||
Ref<ID3DBlob> binary, error;
|
||||
HRESULT h = symbol<Compile>(compiler, "D3DCompile")(
|
||||
code, std::strlen(code), "original-phase2.hlsl", nullptr, nullptr,
|
||||
"main", "cs_5_0", D3DCOMPILE_OPTIMIZATION_LEVEL3, 0, &binary.p,
|
||||
&error.p);
|
||||
if (error.p)
|
||||
std::printf("COMPILER_LOG %.*s\n", (int)error->GetBufferSize(),
|
||||
(const char *)error->GetBufferPointer());
|
||||
require(h, "D3DCompile cs5_0");
|
||||
std::printf("SHADER_BYTECODE bytes=%zu magic=%.4s\n",
|
||||
binary->GetBufferSize(), (char *)binary->GetBufferPointer());
|
||||
FILE *bytecode = std::fopen("consumption.dxbc", "wb");
|
||||
if (!bytecode ||
|
||||
std::fwrite(binary->GetBufferPointer(), 1, binary->GetBufferSize(),
|
||||
bytecode) != binary->GetBufferSize())
|
||||
throw std::runtime_error("archive shader");
|
||||
std::fclose(bytecode);
|
||||
FILE *hlsl = std::fopen("consumption.hlsl", "wb");
|
||||
if (!hlsl)
|
||||
throw std::runtime_error("archive HLSL");
|
||||
std::fwrite(code, 1, std::strlen(code), hlsl);
|
||||
std::fclose(hlsl);
|
||||
D3D12_ROOT_PARAMETER params[3]{};
|
||||
params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_SRV;
|
||||
params[0].Descriptor.ShaderRegister = 0;
|
||||
params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV;
|
||||
params[1].Descriptor.ShaderRegister = 0;
|
||||
params[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
|
||||
params[2].Constants.ShaderRegister = 0;
|
||||
params[2].Constants.Num32BitValues = 3;
|
||||
D3D12_ROOT_SIGNATURE_DESC desc{};
|
||||
desc.NumParameters = 3;
|
||||
desc.pParameters = params;
|
||||
using Serialize =
|
||||
HRESULT(WINAPI *)(const D3D12_ROOT_SIGNATURE_DESC *,
|
||||
D3D_ROOT_SIGNATURE_VERSION, ID3DBlob **, ID3DBlob **);
|
||||
Ref<ID3DBlob> serialized, serializeError;
|
||||
require(symbol<Serialize>(c.dll, "D3D12SerializeRootSignature")(
|
||||
&desc, D3D_ROOT_SIGNATURE_VERSION_1, &serialized.p,
|
||||
&serializeError.p),
|
||||
"serialize root");
|
||||
require(c.device->CreateRootSignature(
|
||||
0, serialized->GetBufferPointer(), serialized->GetBufferSize(),
|
||||
__uuidof(ID3D12RootSignature), root.out()),
|
||||
"CreateRootSignature");
|
||||
D3D12_COMPUTE_PIPELINE_STATE_DESC pd{};
|
||||
pd.pRootSignature = root.p;
|
||||
pd.CS = {binary->GetBufferPointer(), binary->GetBufferSize()};
|
||||
require(c.device->CreateComputePipelineState(
|
||||
&pd, __uuidof(ID3D12PipelineState), pipeline.out()),
|
||||
"CreateComputePipelineState");
|
||||
}
|
||||
void dispatch(Queue &q, Buffer &src, Buffer &dst, UINT count, UINT salt,
|
||||
UINT stride) {
|
||||
q.begin();
|
||||
q.transition(dst.resource.p, D3D12_RESOURCE_STATE_COMMON,
|
||||
D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
|
||||
q.list->SetPipelineState(pipeline.p);
|
||||
q.list->SetComputeRootSignature(root.p);
|
||||
q.list->SetComputeRootShaderResourceView(
|
||||
0, src.resource->GetGPUVirtualAddress());
|
||||
q.list->SetComputeRootUnorderedAccessView(
|
||||
1, dst.resource->GetGPUVirtualAddress());
|
||||
UINT values[] = {count, salt, stride};
|
||||
q.list->SetComputeRoot32BitConstants(2, 3, values, 0);
|
||||
q.list->Dispatch(4, 1, 1);
|
||||
q.transition(dst.resource.p, D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
|
||||
D3D12_RESOURCE_STATE_COMMON);
|
||||
q.finish();
|
||||
}
|
||||
};
|
||||
inline uint32_t pattern(UINT64 i, UINT seed) {
|
||||
uint32_t x = uint32_t(i) ^ seed;
|
||||
x ^= x >> 16;
|
||||
x *= 0x7FEB352Du;
|
||||
x ^= x >> 15;
|
||||
x *= 0x846CA68Bu;
|
||||
return x ^ (x >> 16);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
# Workstream B copy, memory and synchronization research
|
||||
|
||||
This supplement to [#473](https://github.com/MacosPorters/betterxen/issues/473) uses only synthetic buffers and the installed public D3D12 interfaces. The six baseline cases are frozen. See the [baseline](../README.md) and [measured findings](findings.md). [Contracts](../gpu-correctness/contracts/synchronization-mapping-tracking.md), the [initial independent A review](review-a.md), and the [continuation and consolidation review](review-a-consolidation.md) accompany these experiments. No production shim or ABI participates.
|
||||
|
||||
## Reproduce
|
||||
|
||||
Use a licensed CrossOver installation on Apple Silicon, Rosetta and a local win64 CrossOver bottle. The runner clones the bottle, records settings and source bottle configuration hash, and stops the private server on return. Each graphics case checks loaded D3DMetal DLL/framework paths before running the workload. Each case has a 45-second timeout and individual fence waits have a 5-second timeout. The host lock serializes runs from both workstreams when they use the common local lock path. Launch filters environment variables and copies only the external HLSL source into the compute guest's working directory.
|
||||
|
||||
```sh
|
||||
probe_dir=docs/research/d3dmetal-zero-copy/copy-detection
|
||||
python3 "$probe_dir/run.py" --group small --bottle "/path/to/win64/bottle" --scratch /tmp/b473-small
|
||||
python3 "$probe_dir/run.py" --group compute --seed 473 --bottle "/path/to/win64/bottle" --scratch /tmp/b473-compute
|
||||
python3 "$probe_dir/run.py" --group sweep --seed 473 --bottle "/path/to/win64/bottle" --scratch /tmp/b473-sweep
|
||||
python3 "$probe_dir/summarize.py" /tmp/b473-compute /tmp/b473-sweep
|
||||
```
|
||||
|
||||
Each scratch path must be new. A build-only invocation omits the bottle and uses `--group build`. Repeat with a new seed and fresh scratch directory. The default profile requires normal kernel pressure. A separately labeled `--allow-warning` case can run at Warning while still stopping at Urgent. Pressure and compression are recorded outside benchmark windows. Treat stopped and partial runs as incomplete. [XNU pressure levels](https://github.com/apple-oss-distributions/xnu/blob/main/doc/vm/memorystatus_notify.md).
|
||||
|
||||
## Measurements
|
||||
|
||||
- The copy sweep uses 1, 16 and 64 MiB with WB, WC and standard UPLOAD sources, a matching READBACK output, and 4 KiB or 16 KiB write strides. CUSTOM buffers begin in COMMON and use legal promotion/decay. UPLOAD remains GENERIC_READ. The workload uses the same READBACK destinations, command lists and fence path for each source heap.
|
||||
- Each case has three warmups and twelve timed iterations. Case and page order use the receipt seed. The first three pages in the seeded order cover the first word, an interior word and the last stride's first word. Cases range from zero modified pages to one word per page in the measured allocation. Genuine whole-buffer rewrites are separate cases. Allocation, initialization and output poisoning are outside the write, encoding and submission intervals.
|
||||
- Constant-size GPU work copies three words. Full GPU work copies the allocation and validates every word, including unchanged words inside modified pages. The full workload brackets the copy with D3D12 timestamp queries. GPU rates use useful copy payload bytes divided by query elapsed time. Empty command lists and signal-only waits provide host controls. Omitted copies keep poisoned output, including in the timestamped no-copy case.
|
||||
- Record CPU write (including store fence), reset and encoding, Execute call, queue Signal call, fence arm/wait, end-to-end submission/completion, and validation separately. The CPU bandwidth loop measures whole-allocation memset and a one-stream checksum scan after that write. Report these as effective workload rates with cache and prior-write effects.
|
||||
- The separate [compute and tracking fixture](../gpu-correctness/coherence-and-tracking/README.md) measures direct shader access, wide reads with compact output, sparse reads and store-only throughput. Compiled DXBC remains in the scratch receipt with its SHA-256.
|
||||
|
||||
Compare excess elapsed time and variation across fixed-workload slices, sizes, write counts and strides separately. Sparse CPU writes can change cache ownership, trigger first access or write-combine effects, and create synchronization overhead without a byte-for-byte copy. Full-buffer reads can move data inside a backend before the first GPU counter query or during later work outside it. The elapsed-time distributions can constrain added cost in the measured scenario. They cannot identify physical page identity, pin a copy to a stage based only on correlation, or exclude work that is deferred, overlapped, restricted to referenced ranges, or charged elsewhere. No theoretical Apple memory bandwidth is assumed.
|
||||
|
||||
One host run can expose a regression or specific measured behavior. A stable comparison needs repeat sessions, reported dispersion and actual backend verification. Timestamp results at or below zero are reported as unavailable. Query overhead is visible in the timestamped omitted-copy case. Graphics pipeline and validation work, cache effects and the admitted host pressure limit GB/s comparisons to the defined workloads. [D3D12 timing](https://learn.microsoft.com/en-us/windows/win32/direct3d12/timing).
|
||||
|
||||
## Device-side timing with Instruments
|
||||
|
||||
The tested D3D12 timestamp resolves leave the output unchanged. Use a separate Metal System Trace recording to time GPU work. This needs the installed Apple Xcode and its Instruments permissions. The wrapper attaches to the verified synthetic guest process before releasing the backend handshake. Keep traced host timing apart from the uninstrumented measurements.
|
||||
|
||||
```sh
|
||||
probe_dir=docs/research/d3dmetal-zero-copy/copy-detection
|
||||
scratch=/tmp/b473-metal-wb
|
||||
python3 "$probe_dir/trace.py" wb --group compute --seed 947 --bottle "/path/to/win64/bottle" --scratch "$scratch"
|
||||
trace=$(find "$scratch" -maxdepth 2 -name 'gpu.trace' -print)
|
||||
export DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer
|
||||
xcrun xctrace export --input "$trace" --xpath '/trace-toc/run[@number="1"]/data/table[@schema="metal-gpu-intervals"]' --output "$scratch/gpu-intervals.xml"
|
||||
xcrun xctrace export --input "$trace" --xpath '/trace-toc/run[@number="1"]/data/table[@schema="metal-application-encoders-list"]' --output "$scratch/metal-encoders.xml"
|
||||
python3 "$probe_dir/summarize-trace.py" "$scratch" "$scratch/gpu-intervals.xml" "$scratch/metal-encoders.xml"
|
||||
```
|
||||
|
||||
Repeat serially with `wc`, `upload-wb`, `default`, `copy-wb`, `copy-wc`, or `copy-upload` as the wrapper's first argument and use a fresh scratch directory each time. The copy workload moves 64 MiB to READBACK, compares every word, and varies the two endpoints. All traced inputs retain three warmups and twelve measured iterations in their own process.
|
||||
|
||||
The parser requires a complete, unique sequence of matching Metal command-buffer and encoder IDs for the verified probe PID, along with successful output oracles and matching guest/encoder/GPU interval counts. For the shader it uses active Compute intervals and excludes staging and omitted dispatches. The denominator is the GPU interval duration. Report useful bytes per interval, which includes shader work and cache effects. It does not count physical bus traffic. The full trace and XML exports stay in the local scratch directory because the template can include unrelated host processes. The archived JSON extracts contain only the synthetic guest's matched intervals, and sanitized target-PID-only XML exports retaining referenced XML nodes are archived in [`2026-11-27-apple-m5-atesahmet0-b-trace-inputs-01`](../results/2026-11-27-apple-m5-atesahmet0-b-trace-inputs-01/receipt.json) via [`export-target-trace.py`](export-target-trace.py); see the [B1/B2 audit](b1-b2-audit.md). [Apple Instruments Metal analysis](https://developer.apple.com/documentation/xcode/analyzing-the-performance-of-your-metal-app).
|
||||
@@ -0,0 +1,54 @@
|
||||
# Workstream B append-only audit: B1 stopped-run hash discrepancy and B2 target-PID trace inputs
|
||||
|
||||
Author: Workstream B AI research agent under @atesahmet0's authorization (2026-11-27).
|
||||
Scope: Resolves Workstream A's two concrete review findings in [#473 (comment)](https://github.com/MacosPorters/betterxen/issues/473#issuecomment-7204728260) against B commit `a40228747470f0d184375e451b0173769c90aef5` without rewriting any historical receipt or archived output.
|
||||
|
||||
## 1. B1 — Forensic timeline and audit of `b-trace-01/00-wb/stderr.txt`
|
||||
|
||||
### Retained evidence in `/private/tmp/b473-trace-01` and published `2026-11-27-apple-m5-atesahmet0-b-trace-01`
|
||||
|
||||
All original files from the stopped run remain preserved on the M5 host. Subsecond APFS `stat` timestamps (`btime`, `mtime_ns`, `ctime_ns`) establish the exact sequence:
|
||||
|
||||
| File | Bytes | Birth (`s`) | Modify (`ns` since epoch) | SHA-256 |
|
||||
| --- | ---: | ---: | ---: | --- |
|
||||
| `00-wb/stdout.txt` | 121 | `1795730535.214490175` | `1795730537091268055` | `dca5ad5caa4f0940d193ea3ef60d56b9b98adde3a47470c1f28338ccbd072307` |
|
||||
| `00-wb/stderr.txt` | 40 | `1795730535.214524984` | `1795730540932343519` | `b7eab1251cc975b771929b1c6dfe6cb8511bb1ec75b3241336abe9651a151f83` |
|
||||
| `00-wb/case.json` | 3943 | `1795730540.928579330` | `1795730540928687009` | `2380bf2e49963014...` |
|
||||
| `receipt.json` | 23377 | `1795730532.366539478` | `1795730542894906836` | `2e537107cb1ae7e9...` |
|
||||
| `00-wb/xctrace-output.txt` | 257 | `1795730537.167738199` | `1795730551460369485` | `b5769eac9dd93b50f0bfbac3ae33b3a0e30f066f6005c96e6bc40bc5ec184f7e` |
|
||||
| `00-wb/xctrace.json` | 391 | `1795730551.524590492` | `1795730551524795927` | `27a6e0d0500fd5a9...` |
|
||||
|
||||
### Established cause from timestamps and code inspection
|
||||
|
||||
1. `run_case()` in `B-local-1` (`copy-detection/run.py`) launched CrossOver's Perl wrapper `bin/wine` with `stdin=subprocess.PIPE`, `stdout=out`, `stderr=err`, and `start_new_session=True`.
|
||||
2. At `1795730537.091`, the Windows guest (`b-coherence.exe`, `guest_pid=57987`) printed `BACKEND_READY` to `stdout.txt` and blocked in `receipt_pause()` (`std::getchar()` on `stdin`, `support.h:214`).
|
||||
3. `b473-trace-launch.py` verified `guest_pid=57987` and attached `xctrace` (`1795730537.168`). Immediately afterward, `pressure_ready` observed `kern.memorystatus_vm_pressure_level=2` (Urgent) and raised `RuntimeError('pressure gate at paused device before workload')`.
|
||||
4. Exiting the `with` block closed `run.py`'s parent file descriptors `out` and `err`, **not** the guest's inherited `stderr` descriptor, and **did not close `process.stdin`**, which remained open on local variable `process` (`subprocess.Popen`).
|
||||
5. In `except BaseException:`, `os.killpg(process.pid, signal.SIGKILL)` killed the `bin/wine` launcher process group and `process.wait()` reaped `exit=-9`, **without** signaling `guest_pid=57987` directly or stopping the bottle's `wineserver` (`wineserver -k` ran later in `main()`'s outer `finally:`). Because `process.stdin` was still open, `b-coherence.exe` (`57987`) remained alive and blocked in `std::getchar()`.
|
||||
6. In `run_case()`'s `finally:`, `stderr.txt` was hashed while still genuinely 0 bytes (`e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855`), and `case.json` finished writing at `1795730540.928687009`.
|
||||
7. Immediately upon `return result` from `run_case()`, local `process` went out of scope and CPython closed `process.stdin`. That pipe EOF woke `std::getchar() == EOF` in `b-coherence.exe`, which threw `std::runtime_error("backend receipt handshake")`, caught it in `main()`, and wrote `END failure: backend receipt handshake\r\n` (40 bytes) to `stderr.txt` at `1795730540.932343519` — **3,656,510 ns (3.657 ms) after `case.json` was written**. `receipt.json` (`1795730542.895`) serialized the already-computed in-memory `result['output_hashes']` dictionary rather than re-hashing on disk.
|
||||
|
||||
### Full audit across all 20 published Workstream B bundles (165 `output_hashes` entries)
|
||||
|
||||
- Across all 156 guest/shader entries (`64` `stdout.txt`, `64` `stderr.txt`, `16` `access.hlsl`, `12` `access.dxbc`), **155/156 match**; `b-trace-01/00-wb/stderr.txt` is the sole mismatch. Zero completed runs are affected because normal completion writes `\n` to `process.stdin`, waits for guest `END complete`, and reaps clean exit `0` before hashing.
|
||||
- Across the remaining 9 `xctrace-output.txt` entries in traced runs, 8 of 9 `case.json` hashes recorded the mid-save `xctrace-output.txt` digest at the end of `run_case()` because `trace.py` awaited `trace.wait()` in its outer `finally:` after `runner.main()` returned (for the 7 archived trace runs, `archive.json` separately recorded both post-`trace.wait()` `raw_sha256` and `<HOME>`-redacted `archive_sha256`).
|
||||
|
||||
### Harness correction (`B-local-1.1`)
|
||||
|
||||
`copy-detection/run.py` (`7a4599fcb8f3ebf46c830eda1334d76beed3f89c3fd05c30fb6b54d4ef64e930`) and `copy-detection/trace.py` (`e82533b3abe4eee45978bd549cdc0a648744568cc6fdfcf3b607a65a692ebc88`) are updated to:
|
||||
- Close `process.stdin` explicitly on both normal and error paths before process reaping;
|
||||
- Send `SIGKILL` to both `process.pid`'s process group and any verified `guest_pid`, followed by `wineserver -k` and `wineserver -w` on the private bottle before hashing error outputs;
|
||||
- Wait on `wineserver -w` after normal case exit and finalize `xctrace` via `runner.after_guest` **before** computing `output_hashes` and writing `case.json`.
|
||||
|
||||
A controlled forced stop at `pressure_ready` (`max_level=-1`) verified `recorded_sha == actual_sha` (`True`) after full bottle teardown. Historical `B-local-1` receipts remain untouched.
|
||||
|
||||
## 2. B2 — Sanitized target-PID Metal trace XML inputs
|
||||
|
||||
To distinguish arithmetic re-evaluation of `gpu-samples.json` from independent validation of `summarize-trace.py`'s XML `id`/`ref` resolution, target-PID filtering, staging/readback `Blit Command` exclusion, `Active` GPU-state selection, and `(cmdbuffer-id, encoder-id)` sequence join, `copy-detection/export-target-trace.py` (`0195ca28b0a6f7d8d30e732f4b741b19804814e00645a83ab1f4edc69ae94b6c`) exports minimal target-PID-only XML inputs from the preserved `/private/tmp/b473-*` `xctrace` captures into [the append-only trace-input bundle](../results/2026-11-27-apple-m5-atesahmet0-b-trace-inputs-01/receipt.json).
|
||||
|
||||
Each export retains:
|
||||
- Full `<schema>` column mnemonics;
|
||||
- A `<referenced-nodes>` block holding every transitive `id="..."` XML node referenced via `ref="..."` from outside the target rows (exercising `resolve()`'s `elements[element.attrib['ref']]` path);
|
||||
- Every `<row>` matching the verified `guest_pid`, including all 270 staging/readback `Blit Command` rows in `b-metal-default` (`345` total target encoder/GPU rows -> `75` matched `Compute Command` intervals) while stripping all unrelated host processes and verifying zero personal paths.
|
||||
|
||||
Running unmodified `summarize-trace.py` on each published run directory plus its sanitized `target-gpu-intervals.xml` and `target-metal-encoders.xml` reproduces all 7 published `gpu-samples.json` outputs (300 shader intervals + 45 copy intervals) with exact JSON equality.
|
||||
@@ -0,0 +1,125 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Export minimal target-PID-only xctrace XML tables preserving referenced XML nodes."""
|
||||
import argparse
|
||||
import copy
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
|
||||
def sha(path: Path) -> str:
|
||||
return hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def export_target_table(xml_path: Path, target_pid: str, out_path: Path) -> dict:
|
||||
tree = ET.parse(xml_path)
|
||||
root = tree.getroot()
|
||||
elements = {e.attrib['id']: e for e in root.iter() if 'id' in e.attrib}
|
||||
schema = root.find('.//schema')
|
||||
if schema is None:
|
||||
raise ValueError(f'missing schema in {xml_path}')
|
||||
columns = [col.findtext('mnemonic') for col in schema.findall('col')]
|
||||
|
||||
def resolve(element):
|
||||
return elements[element.attrib['ref']] if 'ref' in element.attrib else element
|
||||
|
||||
all_rows = root.findall('.//row')
|
||||
retained_rows = []
|
||||
for raw in all_rows:
|
||||
mapped = dict(zip(columns, map(resolve, raw), strict=True))
|
||||
pid_node = mapped['process'].find('pid')
|
||||
if pid_node is not None and resolve(pid_node).text == target_pid:
|
||||
retained_rows.append(copy.deepcopy(raw))
|
||||
|
||||
defined_ids = {
|
||||
e.attrib['id'] for row in retained_rows for e in row.iter() if 'id' in e.attrib
|
||||
}
|
||||
needed_ids = []
|
||||
needed_set = set()
|
||||
queue = [
|
||||
e.attrib['ref'] for row in retained_rows for e in row.iter() if 'ref' in e.attrib
|
||||
]
|
||||
while queue:
|
||||
ref_id = queue.pop(0)
|
||||
if ref_id in defined_ids or ref_id in needed_set:
|
||||
continue
|
||||
needed_set.add(ref_id)
|
||||
needed_ids.append(ref_id)
|
||||
target = elements[ref_id]
|
||||
for child in target.iter():
|
||||
if 'id' in child.attrib and child is not target:
|
||||
defined_ids.add(child.attrib['id'])
|
||||
if 'ref' in child.attrib:
|
||||
queue.append(child.attrib['ref'])
|
||||
|
||||
sanitized_root = ET.Element(root.tag, root.attrib)
|
||||
node = ET.SubElement(sanitized_root, 'node')
|
||||
node.append(copy.deepcopy(schema))
|
||||
if needed_ids:
|
||||
defs = ET.SubElement(node, 'referenced-nodes')
|
||||
for ref_id in needed_ids:
|
||||
defs.append(copy.deepcopy(elements[ref_id]))
|
||||
for row in retained_rows:
|
||||
node.append(row)
|
||||
|
||||
ET.indent(sanitized_root, space=' ')
|
||||
payload = ET.tostring(sanitized_root, encoding='utf-8', xml_declaration=True) + b'\n'
|
||||
text = payload.decode('utf-8')
|
||||
home = str(Path.home())
|
||||
if home in text:
|
||||
raise ValueError(f'personal path present in sanitized export for {xml_path}')
|
||||
check_root = ET.fromstring(payload)
|
||||
pids = {e.text for e in check_root.findall('.//pid') if e.text}
|
||||
if not pids <= {target_pid}:
|
||||
raise ValueError(f'unexpected PIDs in sanitized export: {pids}')
|
||||
processes = sorted(
|
||||
{e.attrib.get('fmt', '') for e in check_root.findall('.//process') if 'fmt' in e.attrib}
|
||||
)
|
||||
|
||||
out_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
out_path.write_bytes(payload)
|
||||
return {
|
||||
'raw_xml_sha256': sha(xml_path),
|
||||
'raw_xml_bytes': xml_path.stat().st_size,
|
||||
'raw_total_rows': len(all_rows),
|
||||
'sanitized_xml': out_path.name,
|
||||
'sanitized_xml_sha256': sha(out_path),
|
||||
'sanitized_xml_bytes': len(payload),
|
||||
'retained_target_rows': len(retained_rows),
|
||||
'retained_referenced_nodes': len(needed_ids),
|
||||
'retained_processes': processes,
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--receipt', type=Path, required=True)
|
||||
parser.add_argument('--raw-gpu-intervals', type=Path, required=True)
|
||||
parser.add_argument('--raw-encoders', type=Path, required=True)
|
||||
parser.add_argument('--output-dir', type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
|
||||
receipt = json.loads(args.receipt.read_text())
|
||||
case, = receipt['cases']
|
||||
outcome = case['run']
|
||||
if outcome['exit'] != 0 or not outcome['backend']['verified']:
|
||||
raise ValueError('verified completed guest case required')
|
||||
pid = str(outcome['backend']['guest_pid'])
|
||||
|
||||
summary = {
|
||||
'guest_pid': int(pid),
|
||||
'case': case['directory'],
|
||||
'encoders': export_target_table(
|
||||
args.raw_encoders, pid, args.output_dir / 'target-metal-encoders.xml'
|
||||
),
|
||||
'gpu_intervals': export_target_table(
|
||||
args.raw_gpu_intervals, pid, args.output_dir / 'target-gpu-intervals.xml'
|
||||
),
|
||||
}
|
||||
print(json.dumps(summary, indent=2))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,99 @@
|
||||
# Workstream B findings for #473
|
||||
|
||||
Two M5 sessions reproduced synchronized direct SRV/UAV access on the tested CUSTOM WB and WC heaps. The placement and tracking failures impose API boundaries on a BetterXen design. The copy timing shows configuration- and session-dependent latency and leaves physical page identity and internal copies unresolved.
|
||||
|
||||
## Host, runtime and receipts
|
||||
|
||||
Apple M5, 16 GiB unified RAM, 16 KiB host pages, macOS 27.2.1 build 26B131, CrossOver 26.3.0.39832, Wine 11.0-8726-g2e2f5fca349, D3DMetal 3.0 and Rosetta 1.0.0.0.1793943009 with `ROSETTA_ADVERTISE_AVX=1`. Compiled with native ARM64 MinGW GCC 16.2.0 to x86-64 PE32+. The loaded GPTK D3D12 DLL, D3DMetal framework and Rosetta runtime were verified for each graphics probe process. The write-watch-only probe did not load D3D12. Runs used a temporary clone of a Win64 bottle. Pressures were Warning with substantial compression and swap, including about 6–8 GiB of swap at performance-group start. The sessions describe this host under those conditions.
|
||||
|
||||
| Group | Archive |
|
||||
| --- | --- |
|
||||
| Normal-pressure preflight | [No workload started](../results/2026-11-27-apple-m5-atesahmet0-b-small-01/receipt.json) |
|
||||
| Placement and tracking | [First session](../results/2026-11-27-apple-m5-atesahmet0-b-small-02/receipt.json), [second and clock check](../results/2026-11-27-apple-m5-atesahmet0-b-small-03/receipt.json), [clock confirmation](../results/2026-11-27-apple-m5-atesahmet0-b-small-05/03-clock/stdout.txt) |
|
||||
| Copy and CPU rates | [Seed 473](../results/2026-11-27-apple-m5-atesahmet0-b-sweep-01/receipt.json), [seed 947](../results/2026-11-27-apple-m5-atesahmet0-b-sweep-02/receipt.json) |
|
||||
| Compute | [Seed 473](../results/2026-11-27-apple-m5-atesahmet0-b-compute-01/receipt.json), [seed 947](../results/2026-11-27-apple-m5-atesahmet0-b-compute-02/receipt.json) |
|
||||
| Metal System Trace | [Urgent stop before guest workload](../results/2026-11-27-apple-m5-atesahmet0-b-trace-01/receipt.json), [sanitized target-PID XML inputs](../results/2026-11-27-apple-m5-atesahmet0-b-trace-inputs-01/receipt.json), [B1/B2 audit](b1-b2-audit.md) |
|
||||
| A same-source reproduction | [Alias](../results/2026-11-27-apple-m5-atesahmet0-b-a-alias-01/receipt.json), [texture](../results/2026-11-27-apple-m5-atesahmet0-b-a-texture-01/receipt.json), [review](review-a.md) |
|
||||
|
||||
## Hidden-copy detection
|
||||
|
||||
The two seeded sweeps used 1, 16 and 64 MiB across WB/WC/UPLOAD and both strides, 18 guest processes per session. All 5040 measured copy/control iterations matched their oracle, including poison checks. Each session also recorded 216 CPU measurements and 216 empty/signal-only measurements. Warmups and individual distributions are in the archives.
|
||||
|
||||
The following rows show 64 MiB WB with a 12-byte GPU copy and two distinct write strides. Times are medians in microseconds. Full rewrite touches every byte. A word per page writes 64 KiB of data at 4 KiB stride or 16 KiB at 16 KiB stride.
|
||||
|
||||
| Seed | Stride | No writes | One page | 64 pages | One word per page | Full rewrite | CPU write, word per page / full rewrite |
|
||||
| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
|
||||
| 473 | 4 KiB | 184 | 364 | 224 | 364 | 463 | 165 / 1296 |
|
||||
| 947 | 4 KiB | 181 | 393 | 383 | 188 | 377 | 160 / 1241 |
|
||||
| 473 | 16 KiB | 249 | 364 | 236 | 377 | 446 | 42 / 1618 |
|
||||
| 947 | 16 KiB | 360 | 355 | 371 | 373 | 406 | 38 / 1286 |
|
||||
|
||||
WB 64 MiB full-rewrite small-copy completion increased versus the no-write case in these four comparisons. The increase ranged from 46 to 279 µs, with different baselines. The word-per-page cases show substantial differences between seeds and strides, including nearly flat repetition and nonmonotonic behavior. Across all 64 MiB sources and both seeds the small clean-copy medians span 181–401 µs. A measured explicit full-allocation GPU copy at that size took about 2.09–2.36 ms median in the no-write cases. The small-copy path therefore does not show a serialized copy with the cost of that explicit full READBACK workload. That comparison does not rule out a faster or overlapped backend copy, copy outside the measured interval, or work restricted to referenced pages. The returns also fit cache ownership, page activity, queue scheduling, and host pressure as alternative contributors. Full-byte CPU write time is visible before submission and varies independently of it.
|
||||
|
||||
The earlier M5 report touched one word per 4 KiB and verified only endpoints. The historical M4 timing likewise used endpoint copies, with a separate checksum run. The current 64 MiB sweep validates endpoint/interior sentinels or every copied word and distinguishes whole-byte rewrites. There is no validated upper bound at 256 MiB or across other D3DMetal versions. There is also no direct evidence that the CPU and GPU mappings identify the same physical pages.
|
||||
|
||||
## Timing and effective bandwidth
|
||||
|
||||
Each table entry is the range of case medians across both seeds, both strides and three source heap types. Full GPU copies use the no-write case with an identical READBACK destination. Rates are decimal GB/s.
|
||||
|
||||
| Size | CPU checksum read | CPU memset write | GPU copy payload / fence interval |
|
||||
| --- | ---: | ---: | ---: |
|
||||
| 1 MiB | 8.91–17.53 | 32.36–88.12 | 2.07–4.60 |
|
||||
| 16 MiB | 16.03–16.55 | 58.90–76.30 | 5.56–20.41 |
|
||||
| 64 MiB | 15.74–16.51 | 47.70–56.38 | 28.38–32.33 |
|
||||
|
||||
Empty submit medians across both sessions were 0.30–0.60 µs for reset/encode/close, 1.80–2.95 µs for Execute, 0.20–0.30 µs for Signal, 40.25–55.05 µs for fence arm/wait and 42.60–58.30 µs total. Signal-only was 43.00–59.90 µs. These controls expose the fixed host synchronization scale and are not blindly subtracted from each workload.
|
||||
|
||||
D3D12 timestamp duration was unavailable. The runtime reported a 60 Hz timestamp query frequency. Regular query pairs were zero-initialized and read back 0/0. A separate fence-separated clock check at roughly 153 ms left **both distinct poison slots unchanged** even when their respective query was resolved. The old diagnostic printed the arithmetic difference of those sentinels as 16666.667 µs. The corrected clock confirmation reproduced the unchanged sentinels after about 158 ms and reported no GPU duration. The first Metal System Trace recorded a paused target and stopped at Urgent before the workload. After pressure recovered, separate captures succeeded. Fence-interval rates include all queue work and scheduling in the interval and are not device-only bandwidth. See the [clock stdout](../results/2026-11-27-apple-m5-atesahmet0-b-small-03/03-clock/stdout.txt).
|
||||
|
||||
## Direct shader access and persistent mapping
|
||||
|
||||
Each of four configurations ran six modes, twelve measured iterations and three warmups per mode, in each of two sessions. All 576 measured comparisons and their warmups were exact. That includes the two direct CUSTOM outputs and the UPLOAD→WB control using the original mapped pointers through every round. The DEFAULT control used explicit staging. Output remained poisoned when dispatch was omitted.
|
||||
|
||||
The table reports median submission-to-fence completion in µs for seed 473 / 947. The full-read kernel reads 4 MiB and writes a compact result. Store-only writes 4 MiB. The sparse kernels read 4096 or 1024 bytes across the same 4 MiB allocation and write equally sized results.
|
||||
|
||||
| Source → destination | Full read | Sparse 4 KiB | Sparse 16 KiB | Store only | Omitted dispatch |
|
||||
| --- | ---: | ---: | ---: | ---: | ---: |
|
||||
| WB → WB | 314 / 572 | 204 / 189 | 188 / 200 | 308 / 488 | 60 / 48 |
|
||||
| WC → WC | 535 / 502 | 178 / 175 | 191 / 180 | 506 / 393 | 57 / 52 |
|
||||
| UPLOAD → WB | 322 / 524 | 203 / 191 | 185 / 186 | 258 / 500 | 56 / 51 |
|
||||
| DEFAULT → DEFAULT | 275 / 217 | 228 / 180 | 222 / 167 | 326 / 253 | 268 / 233 |
|
||||
|
||||
WB's full-read rate is approximately 13.3 / 7.3 GB/s and its store-only rate is 13.6 / 8.6 GB/s on the fence interval. WC's are approximately 7.8 / 8.4 and 8.3 / 10.7 GB/s. DEFAULT includes dependent readback in its fence interval. The staged and direct cases share shader commands while differing in transfer and barrier work. Sparse operations are completion-latency dominated. Useful-byte rates in these cases cannot be converted into physical transaction bandwidth or an intrinsic ranking of heap types. The shader compiler reported ignoring requested optimization flag 0x8000, with the same DXBC hash in all four modes and both sessions. An independent Python expression regenerated the two reported word values in each of the 720 samples including warmups and confirmed each pair.
|
||||
|
||||
The CPU finishes stores before GPU access, and observes writes after a queue fence. No test relies on concurrent CPU/GPU access, mapped-pointer atomics, or a console cache contract. [Synchronization and mapping contracts](../gpu-correctness/contracts/synchronization-mapping-tracking.md).
|
||||
|
||||
## GPU intervals from Metal System Trace
|
||||
|
||||
Each configuration used a separate attached Instruments capture. The analysis joins the verified probe PID's GPU work to the Metal application's encoder IDs. All 75 shader dispatches and 15 omitted controls per configuration were accounted for. Staging and readback blits remain outside the reported shader intervals. Some blits run on a trace channel named Compute, so the analysis distinguishes blits and shaders by encoder type and matching command-buffer and encoder IDs.
|
||||
|
||||
The table reports GPU duration median and median absolute deviation in µs for 12 measured iterations, followed by median useful payload rates in decimal GB/s. Each case has three additional warmups. Full read includes the compact dependent output. Store-only has no shader input loads.
|
||||
|
||||
| Heap source → output | Full read µs median ± MAD | Full read GB/s | Store-only µs median ± MAD | Store-only GB/s | Sparse read 4 / 16 KiB stride µs |
|
||||
| --- | ---: | ---: | ---: | ---: | ---: |
|
||||
| WB → WB | 110.23 ± 1.56 | 38.05 | 51.02 ± 3.08 | 82.21 | 6.75 / 3.92 |
|
||||
| WC → WC | 106.00 ± 0.81 | 39.57 | 39.85 ± 8.40 | 105.25 | 4.98 / 1.98 |
|
||||
| UPLOAD → WB | 104.54 ± 5.10 | 40.12 | 28.23 ± 4.29 | 148.62 | 6.60 / 5.71 |
|
||||
| DEFAULT → DEFAULT | 32.12 ± 0.92 | 130.56 | 18.83 ± 0.04 | 222.70 | 1.83 / 1.25 |
|
||||
|
||||
The 64 MiB full-copy profile used the same 15 copy workloads per source heap, identical READBACK destinations and explicit fences. It verified all 16777216 words per copy. WB, WC and UPLOAD median GPU intervals were 1319.44, 1236.90 and 1476.63 µs, respectively. Median payload rates were 50.88, 54.26 and 45.87 GB/s. The MADs were 180.56, 191.69 and 299.42 µs. The first UPLOAD guest completed its checks but Instruments did not save its capture within the original timeout. The separate retry saved and matched all 15 intervals. The instrumented copy fixture uses a different data initialization from the uninstrumented sweep. Compare only the same kind of measurement.
|
||||
|
||||
These are per-encoder device-side timings, with GPU execution, cache and trace effects included. Application payload divided by duration does not reveal physical memory transactions. An individual interval can be much longer than its case's median, and cells come from separate single captures on a pressured host. Inspect the individual samples before using the rates for design decisions. The substantial difference between the two write-only workloads with WB output is a direct cross-capture reproducibility limit.
|
||||
|
||||
[WB trace](../results/2026-11-27-apple-m5-atesahmet0-b-trace-02/gpu-samples.json), [WC trace](../results/2026-11-27-apple-m5-atesahmet0-b-metal-wc/gpu-samples.json), [UPLOAD→WB trace](../results/2026-11-27-apple-m5-atesahmet0-b-metal-upload-wb/gpu-samples.json), [DEFAULT trace](../results/2026-11-27-apple-m5-atesahmet0-b-metal-default/gpu-samples.json), [WB copy trace](../results/2026-11-27-apple-m5-atesahmet0-b-metal-copy-wb/gpu-samples.json), [WC copy trace](../results/2026-11-27-apple-m5-atesahmet0-b-metal-copy-wc/gpu-samples.json), [UPLOAD copy trace](../results/2026-11-27-apple-m5-atesahmet0-b-metal-copy-upload-retry/gpu-samples.json).
|
||||
|
||||
## Alignment and write tracking
|
||||
|
||||
The first independent M5 placement probe found CPU Map remainders of 16384 for WB/WC/UPLOAD and 0 for the VirtualAlloc control. A later fresh process returned 0 for the valid maps. The same-source alias runs returned 32768 and 16384. All checked valid GPU VAs remained 64 KiB aligned. For invalid creation only, a 64 KiB heap accepted offsets 1 and 65536, and a 128 KiB heap accepted offset 1 with the allocation span otherwise in bounds. None of these resources was used after the creation call. Caller alignment and bounds validation remain required.
|
||||
|
||||
A CPU-only watch-enabled allocation gave exact 4096-byte page sets through eleven phases in each small group. Same-host-page subpages were distinguishable, boundary stores appeared at 12288 and 16384, query and separate reset cleared tracking, and rearming captured later stores including a same-value write. A read did not set a dirty bit. The watch-enabled allocation could not be wrapped by D3D12 (E_NOTIMPL). IsolatedMMU was false. General GPU-write tracking and coherence on a foreign Map pointer remain unestablished.
|
||||
|
||||
## BetterXen handoff
|
||||
|
||||
1. Use D3D12-owned CPU-visible buffers as a candidate for allocations whose alignment, lifetime and ownership contracts match the actual returned pointer. Keep heap-relative validation, CPU pointer checks and fence-delayed reuse explicit. A mapped aligned slice does not automatically give a legal corresponding placed-resource offset.
|
||||
2. Use the ordinary texture layout, initialization, state and copy rules for opaque textures. The M4/M5 mixed and alias fixtures establish the reported functional subcases. They do not establish raw pointer equivalence or general texture inheritance.
|
||||
3. Keep device-owned and predevice CPU-owned memory paths explicit. Existing-memory import returned E_NOTIMPL in the tested cases. Write-watch may reduce CPU-to-GPU explicit-copy work with controlled writer ownership, rearming and retry handling. GPU-to-CPU synchronization requires a fence and a supported visibility/transfer contract.
|
||||
4. Use one logical budget and monitor separate process-accounting or runtime-retention measurements. A's large runs observe retained charges and incomplete repeats. No Class A evidence here proves a leak or a universal retention amount.
|
||||
5. Preserve #464's scope. [PR #486](https://github.com/MacosPorters/betterxen/pull/486) reports vkd3d execution and already guards placement. Its statements about physical sharing and absence of copies exceed the scope established by this research.
|
||||
|
||||
Outstanding items include repeated GPU traces at normal pressure, independent repetition of B on M4, normal-pressure sensitivity, same-host accounting repeats for large allocations, generalized GPU-write tracking, any stronger physical-page or copy-mechanism claim, and reciprocal acceptance of the architecture handoff. Workstream B's own runs are author-run. The A review records separate source analysis, same-source M5 reproduction, and separately implemented placement verification.
|
||||
@@ -0,0 +1,303 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#include "support.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <bit>
|
||||
#include <numeric>
|
||||
#include <random>
|
||||
#include <vector>
|
||||
|
||||
constexpr UINT MiB = 1024 * 1024;
|
||||
constexpr UINT placement = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT;
|
||||
|
||||
static void placement_probe(Device& d) {
|
||||
const auto desc = buffer_desc(placement, D3D12_RESOURCE_FLAG_NONE);
|
||||
const auto alloc = d.device->GetResourceAllocationInfo(0, 1, &desc);
|
||||
for (const auto& [heap_size, offset] : {
|
||||
std::pair{UINT64(placement), 0ull}, std::pair{UINT64(placement), 1ull},
|
||||
std::pair{UINT64(placement), UINT64(placement)}, std::pair{UINT64(2 * placement), 1ull}}) {
|
||||
auto heap = d.heap(Heap::wb, heap_size);
|
||||
Com<ID3D12Resource> resource;
|
||||
const HRESULT hr = d.device->CreatePlacedResource(heap.get(), offset, &desc,
|
||||
D3D12_RESOURCE_STATE_COMMON, nullptr, __uuidof(ID3D12Resource), resource.out());
|
||||
const bool aligned = alloc.Alignment && offset % alloc.Alignment == 0;
|
||||
const bool in_bounds = offset <= heap_size && alloc.SizeInBytes <= heap_size - offset;
|
||||
const bool legal = aligned && in_bounds;
|
||||
std::printf("PLACEMENT offset=%llu heap=%llu size=%llu alignment=%llu aligned=%d in_bounds=%d eligible=%d hr=%08lx object=%d\n",
|
||||
offset, heap_size, alloc.SizeInBytes, alloc.Alignment, aligned, in_bounds, legal,
|
||||
static_cast<unsigned long>(hr), resource.get() != nullptr);
|
||||
// Creation-only negatives: no Map, GPU VA lookup, command recording, or submission.
|
||||
if (!legal) continue;
|
||||
check(hr, "valid placement");
|
||||
void* pointer = nullptr;
|
||||
check(resource->Map(0, nullptr, &pointer), "valid placement Map");
|
||||
if (!pointer) throw std::runtime_error("valid placement Map returned null");
|
||||
const auto addr = reinterpret_cast<uintptr_t>(pointer);
|
||||
std::printf("MAP heap=wb size=%u cpu_mod16k=%llu cpu_mod64k=%llu gpu_mod64k=%llu\n",
|
||||
placement, UINT64(addr % 16384), UINT64(addr % placement),
|
||||
resource->GetGPUVirtualAddress() % placement);
|
||||
resource->Unmap(0, nullptr);
|
||||
}
|
||||
for (const auto& [kind, name] : {std::pair{Heap::wb, "wb"}, {Heap::wc, "wc"}, {Heap::upload, "upload"}}) {
|
||||
Buffer buffer(d, kind, 4 * MiB, kind == Heap::upload
|
||||
? D3D12_RESOURCE_STATE_GENERIC_READ : D3D12_RESOURCE_STATE_COMMON);
|
||||
const auto addr = reinterpret_cast<uintptr_t>(buffer.map());
|
||||
std::printf("MAP heap=%s size=%u cpu_mod16k=%llu cpu_mod64k=%llu gpu_mod64k=%llu\n",
|
||||
name, 4 * MiB, UINT64(addr % 16384), UINT64(addr % placement),
|
||||
buffer.resource->GetGPUVirtualAddress() % placement);
|
||||
}
|
||||
void* ptr = VirtualAlloc(nullptr, placement, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
|
||||
if (!ptr) throw std::runtime_error("VirtualAlloc alignment control");
|
||||
std::printf("MAP heap=virtualalloc size=%u cpu_mod64k=%llu\n",
|
||||
placement, UINT64(reinterpret_cast<uintptr_t>(ptr) % placement));
|
||||
if (!VirtualFree(ptr, 0, MEM_RELEASE)) throw std::runtime_error("VirtualFree");
|
||||
}
|
||||
|
||||
static void clock_probe(Device& d) {
|
||||
Queue queue(d);
|
||||
Timestamp stamp(d, queue);
|
||||
const UINT64 poison[] = {0x9cde12154b320001ull, 0x9cde12154b320002ull};
|
||||
std::memcpy(stamp.output.pointer, poison, sizeof(poison));
|
||||
_mm_sfence();
|
||||
|
||||
const auto start = ticks();
|
||||
queue.begin();
|
||||
stamp.start(queue);
|
||||
queue.list->ResolveQueryData(stamp.queries.get(), D3D12_QUERY_TYPE_TIMESTAMP, 0, 1,
|
||||
stamp.output.resource.get(), 0);
|
||||
queue.close();
|
||||
queue.execute();
|
||||
const UINT64 early = stamp.data[0];
|
||||
const UINT64 untouched = stamp.data[1];
|
||||
|
||||
Sleep(150);
|
||||
queue.begin();
|
||||
queue.list->EndQuery(stamp.queries.get(), D3D12_QUERY_TYPE_TIMESTAMP, 1);
|
||||
queue.list->ResolveQueryData(stamp.queries.get(), D3D12_QUERY_TYPE_TIMESTAMP, 1, 1,
|
||||
stamp.output.resource.get(), sizeof(UINT64));
|
||||
queue.close();
|
||||
queue.execute();
|
||||
UINT64 gpu_calibration = 0, cpu_calibration = 0;
|
||||
const HRESULT hr = queue.queue->GetClockCalibration(&gpu_calibration, &cpu_calibration);
|
||||
const bool resolved_first = early != poison[0];
|
||||
const bool resolved_last = stamp.data[1] != poison[1];
|
||||
const double gpu_us = resolved_first && resolved_last ? stamp.elapsed() : -1;
|
||||
std::printf("CLOCK cpu_elapsed_us=%.3f first=%llu expected_poison_first=%llu untouched=%llu "
|
||||
"expected_poison_last=%llu last=%llu resolved_first=%d resolved_last=%d gpu_elapsed_us=%.3f "
|
||||
"calibration_hr=%08lx calibration_gpu=%llu calibration_cpu=%llu\n",
|
||||
us(ticks() - start), early, poison[0], untouched, poison[1], stamp.data[1],
|
||||
resolved_first, resolved_last, gpu_us, static_cast<unsigned long>(hr), gpu_calibration, cpu_calibration);
|
||||
if (untouched != poison[1]) throw std::runtime_error("query resolve overwrote untouched slot");
|
||||
}
|
||||
|
||||
static uint32_t repeated_byte(uint8_t value) {
|
||||
return 0x01010101u * value;
|
||||
}
|
||||
|
||||
struct Case {
|
||||
UINT dirty;
|
||||
bool full_write;
|
||||
bool full_read;
|
||||
bool omit;
|
||||
};
|
||||
|
||||
static void sweep(Device& d, Heap kind, UINT bytes, UINT stride, UINT seed) {
|
||||
// Buffers in COMMON promote to COPY_SOURCE and decay at each completed Execute.
|
||||
// UPLOAD stays GENERIC_READ, which includes COPY_SOURCE.
|
||||
Buffer src(d, kind, bytes, kind == Heap::upload ? D3D12_RESOURCE_STATE_GENERIC_READ
|
||||
: D3D12_RESOURCE_STATE_COMMON);
|
||||
Buffer dst(d, Heap::readback, bytes, D3D12_RESOURCE_STATE_COPY_DEST);
|
||||
auto* in = src.map();
|
||||
auto* out = dst.map();
|
||||
Queue q(d);
|
||||
Timestamp stamp(d, q);
|
||||
const UINT words = bytes / 4;
|
||||
const UINT pages = bytes / stride;
|
||||
const UINT page_words = stride / 4;
|
||||
const UINT offsets[] = {0, words / 2, words - page_words};
|
||||
std::vector<UINT> order(pages);
|
||||
std::iota(order.begin(), order.end(), 0u);
|
||||
std::mt19937 random(seed);
|
||||
// Fix endpoint and interior coverage. Randomize the remaining pages and case order.
|
||||
std::shuffle(order.begin(), order.end(), random);
|
||||
for (UINT i = 0; i < 3; ++i)
|
||||
std::iter_swap(order.begin() + i, std::find(order.begin(), order.end(), offsets[i] / page_words));
|
||||
|
||||
std::vector<Case> cases;
|
||||
for (bool full_read : {false, true}) {
|
||||
for (UINT dirty : {0u, 1u, std::min(64u, pages), pages}) {
|
||||
if (dirty == pages && cases.back().dirty == pages) continue;
|
||||
cases.push_back({dirty, false, full_read, false});
|
||||
}
|
||||
cases.push_back({pages, true, full_read, false});
|
||||
cases.push_back({pages, false, full_read, true});
|
||||
}
|
||||
std::shuffle(cases.begin(), cases.end(), random);
|
||||
for (const Case test : cases) {
|
||||
constexpr uint8_t initial = 0x27;
|
||||
constexpr uint32_t poison = 0xefefefefu;
|
||||
std::memset(in, initial, bytes);
|
||||
_mm_sfence();
|
||||
std::vector<bool> changed(pages);
|
||||
for (UINT i = 0; i < test.dirty; ++i) changed[order[i]] = true;
|
||||
const UINT copied_words = test.full_read ? words : 3;
|
||||
for (int i = -3; i < 12; ++i) {
|
||||
const auto byte = uint8_t(0x60 + i);
|
||||
std::memset(out, 0xef, copied_words * 4u);
|
||||
_mm_sfence();
|
||||
const auto write_start = ticks();
|
||||
if (test.full_write) {
|
||||
std::memset(in, byte, bytes);
|
||||
} else {
|
||||
for (UINT j = 0; j < test.dirty; ++j)
|
||||
in[order[j] * page_words] = repeated_byte(byte);
|
||||
}
|
||||
_mm_sfence();
|
||||
const auto written = ticks();
|
||||
q.begin();
|
||||
if (test.full_read) stamp.start(q);
|
||||
if (!test.omit) {
|
||||
if (test.full_read) {
|
||||
q.list->CopyBufferRegion(dst.resource.get(), 0, src.resource.get(), 0, bytes);
|
||||
} else {
|
||||
for (UINT j = 0; j < 3; ++j)
|
||||
q.list->CopyBufferRegion(dst.resource.get(), j * 4u,
|
||||
src.resource.get(), offsets[j] * 4u, 4);
|
||||
}
|
||||
}
|
||||
if (test.full_read) stamp.end(q);
|
||||
q.close();
|
||||
const auto encoded = ticks();
|
||||
const auto latency = q.execute();
|
||||
const auto validate_start = ticks();
|
||||
bool ok = true;
|
||||
uint32_t first_expected = 0, last_expected = 0;
|
||||
UINT matches = 0;
|
||||
for (UINT j = 0; j < copied_words; ++j) {
|
||||
const UINT index = test.full_read ? j : offsets[j];
|
||||
const bool modified = test.full_write ||
|
||||
(index % page_words == 0 && changed[index / page_words]);
|
||||
const auto expected = test.omit ? poison : repeated_byte(modified ? byte : initial);
|
||||
if (!j) first_expected = expected;
|
||||
if (j == copied_words - 1) last_expected = expected;
|
||||
const auto actual = out[j];
|
||||
if (ok && actual != expected) {
|
||||
std::printf("MISMATCH index=%u expected=%08x actual=%08x\n", index, expected, actual);
|
||||
ok = false;
|
||||
}
|
||||
matches += actual == expected;
|
||||
}
|
||||
const auto verified = ticks();
|
||||
const double gpu_us = test.full_read ? stamp.elapsed() : -1;
|
||||
std::printf("COPY bytes=%u stride=%u seed=%u dirty=%u full_write=%d full_read=%d omit=%d iter=%d "
|
||||
"cpu_written=%u gpu_payload=%u gpu_tick_begin=%llu gpu_tick_end=%llu cpu_write_us=%.3f encode_us=%.3f execute_us=%.3f "
|
||||
"signal_us=%.3f wait_us=%.3f completion_us=%.3f gpu_us=%.3f validation_us=%.3f "
|
||||
"expected=%08x,%08x actual=%08x,%08x matches=%u/%u\n",
|
||||
bytes, stride, seed, test.dirty, test.full_write, test.full_read, test.omit, i,
|
||||
test.full_write ? bytes : test.dirty * 4, test.omit ? 0 : copied_words * 4,
|
||||
test.full_read ? stamp.data[0] : 0, test.full_read ? stamp.data[1] : 0,
|
||||
us(written - write_start), us(encoded - written), latency.execute, latency.signal,
|
||||
latency.wait, latency.total, gpu_us, us(verified - validate_start),
|
||||
first_expected, last_expected, out[0], out[copied_words - 1], matches, copied_words);
|
||||
if (!ok) throw std::runtime_error("copy/omit oracle");
|
||||
}
|
||||
}
|
||||
|
||||
for (int i = -3; i < 12; ++i) {
|
||||
const auto byte = uint8_t(0x40 + i);
|
||||
const auto write_start = ticks();
|
||||
std::memset(in, byte, bytes);
|
||||
_mm_sfence();
|
||||
const auto written = ticks();
|
||||
uint64_t sum = 0;
|
||||
for (UINT j = 0; j < words; ++j) sum += in[j];
|
||||
const auto read = ticks();
|
||||
const auto expected = uint64_t(repeated_byte(byte)) * words;
|
||||
std::printf("CPU bytes=%u iter=%d write_us=%.3f read_us=%.3f sum=%llu expected=%llu\n",
|
||||
bytes, i, us(written - write_start), us(read - written),
|
||||
static_cast<unsigned long long>(sum), static_cast<unsigned long long>(expected));
|
||||
if (sum != expected) throw std::runtime_error("CPU bandwidth oracle");
|
||||
}
|
||||
for (int i = -3; i < 12; ++i) {
|
||||
const auto start = ticks();
|
||||
q.begin();
|
||||
q.close();
|
||||
const auto encoded = ticks();
|
||||
const auto latency = q.execute();
|
||||
const auto signal_only = q.execute(false);
|
||||
std::printf("EMPTY iter=%d encode_us=%.3f execute_us=%.3f signal_us=%.3f wait_us=%.3f "
|
||||
"completion_us=%.3f signal_only_us=%.3f\n", i, us(encoded - start),
|
||||
latency.execute, latency.signal, latency.wait, latency.total, signal_only.total);
|
||||
}
|
||||
}
|
||||
|
||||
static void trace_copy(Device& d, Heap kind) {
|
||||
constexpr UINT bytes = 64 * MiB;
|
||||
constexpr UINT count = bytes / 4;
|
||||
Buffer src(d, kind, bytes, kind == Heap::upload ? D3D12_RESOURCE_STATE_GENERIC_READ
|
||||
: D3D12_RESOURCE_STATE_COMMON);
|
||||
Buffer dst(d, Heap::readback, bytes, D3D12_RESOURCE_STATE_COPY_DEST);
|
||||
auto* in = src.map();
|
||||
auto* out = dst.map();
|
||||
for (UINT j = 0; j < count; ++j) in[j] = j ^ 0x5A3367F9u;
|
||||
Queue q(d);
|
||||
for (int i = -3; i < 12; ++i) {
|
||||
const UINT salt = 0xC6D2B000u + UINT(i + 3);
|
||||
in[0] = salt;
|
||||
in[count - 1] = ~salt;
|
||||
std::memset(out, 0x5D, bytes);
|
||||
_mm_sfence();
|
||||
q.begin();
|
||||
q.list->CopyBufferRegion(dst.resource.get(), 0, src.resource.get(), 0, bytes);
|
||||
q.close();
|
||||
const auto latency = q.execute();
|
||||
UINT matches = (out[0] == salt) + (out[count - 1] == ~salt);
|
||||
for (UINT j = 1; j < count - 1; ++j) matches += out[j] == (j ^ 0x5A3367F9u);
|
||||
std::printf("TRACE_COPY iter=%d gpu_payload=%u completion_us=%.3f "
|
||||
"actual=%08x,%08x expected=%08x,%08x matches=%u/%u\n",
|
||||
i, bytes, latency.total, out[0], out[count - 1], salt, ~salt, matches, count);
|
||||
if (matches != count) throw std::runtime_error("trace copy oracle");
|
||||
}
|
||||
}
|
||||
|
||||
static Heap parse_heap(const std::string& name) {
|
||||
if (name == "wb") return Heap::wb;
|
||||
if (name == "wc") return Heap::wc;
|
||||
if (name == "upload") return Heap::upload;
|
||||
throw std::runtime_error("unknown heap");
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
setvbuf(stdout, nullptr, _IONBF, 0);
|
||||
try {
|
||||
if (argc != 2 && argc != 3 && argc != 6)
|
||||
throw std::runtime_error("usage: probe placement | clock | trace-copy HEAP | sweep HEAP MIB STRIDE SEED");
|
||||
Device device;
|
||||
receipt_pause();
|
||||
if (argc == 2 && std::string(argv[1]) == "placement") {
|
||||
placement_probe(device);
|
||||
} else if (argc == 2 && std::string(argv[1]) == "clock") {
|
||||
clock_probe(device);
|
||||
} else if (argc == 3 && std::string(argv[1]) == "trace-copy") {
|
||||
trace_copy(device, parse_heap(argv[2]));
|
||||
} else if (argc == 6 && std::string(argv[1]) == "sweep") {
|
||||
const std::string name = argv[2];
|
||||
const auto mib = std::stoul(argv[3]);
|
||||
const auto stride = std::stoul(argv[4]);
|
||||
const auto seed = std::stoul(argv[5]);
|
||||
if (!std::has_single_bit(mib) || mib > 64 || (stride != 4096 && stride != 16384))
|
||||
throw std::runtime_error("sweep bounds");
|
||||
std::printf("CONFIG heap=%s MiB=%lu stride=%lu seed=%lu warmups=3 measured=12\n",
|
||||
name.c_str(), mib, stride, seed);
|
||||
sweep(device, parse_heap(name),
|
||||
UINT(mib) * MiB, UINT(stride), UINT(seed));
|
||||
} else {
|
||||
throw std::runtime_error("unknown mode");
|
||||
}
|
||||
std::puts("END complete");
|
||||
return 0;
|
||||
} catch (const std::exception& e) {
|
||||
std::fprintf(stderr, "END failure: %s\n", e.what());
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
# Independent review of Workstream A continuation (`8c9eceb`) and consolidation draft (`677686e`)
|
||||
|
||||
Reviewer: Workstream B AI research agent under @atesahmet0's authorization (2026-11-27).
|
||||
Reviewed Workstream A commits on `research/473-workstream-a-memory`:
|
||||
- Continuation evidence pin: [`8c9eceb05ab660504ee981c2f4fcaf1728a5dbff`](https://github.com/MacosPorters/betterxen/commit/8c9eceb05ab660504ee981c2f4fcaf1728a5dbff)
|
||||
- Consolidation draft pin: [`677686e356c82a91886cc7d6fa93e39ce1400494`](https://github.com/MacosPorters/betterxen/commit/677686e356c82a91886cc7d6fa93e39ce1400494)
|
||||
- Frozen six-check baseline pin: [`9ae6d1ee7092b6021aad075531f50ba60de4fd53`](https://github.com/MacosPorters/betterxen/commit/9ae6d1ee7092b6021aad075531f50ba60de4fd53) (`probe.cpp` SHA-256 `33e90bfee89e812f48990613cd74ced56473e5c3fc5d973f2ba1116090646a0c`)
|
||||
|
||||
## 1. Frozen six-check baseline (`BASE-1`..`BASE-6`): source review and M5 shared-runner reproduction
|
||||
|
||||
- **Source review of `probe.cpp` (`33e90bfee89e...`) and `run.py`:** Verified `ID3D12Device3::CheckFeatureSupport` (`ARCHITECTURE1` and `D3D12_OPTIONS`), `OpenExistingHeapFromAddress`/`FromFileMapping` error gates, five `CUSTOM` L0 heap combinations plus the `L1` `E_INVALIDARG` control, disjoint `offset=0` UAV buffer + `offset=65536` `64×64` `R8G8B8A8_UNORM` CPU subresource round-trip, persistent-map bidirectional copies, 5-warmup + 40-timed endpoint copies, and `MEM_WRITE_WATCH`. Known baseline limits remain explicit: `readEnds()` transitions `CUSTOM` buffers (`COMMON <-> COPY_SOURCE`) while leaving `UPLOAD` in `GENERIC_READ`, `submit()` predates `~UINT64(0)` device-removal and `ExitProcess(2)` guards, and the `64 KiB` prefault stride touches one fourth of `16 KiB` host pages.
|
||||
- **Exact shared-runner M5 reproduction:** Executed unmodified `docs/research/d3dmetal-zero-copy/run.py` against a private clone of `win11_64` (`WineArch=win64`) on Apple M5 (`16 GiB`, macOS `27.2.1` `26B131`, CrossOver `26.3.0.39832`, D3DMetal `3.0`, Rosetta `1.0.0.0.1793943009`, kernel pressure `1` Warning, `49%` free), plus `--receipt-only` `lsof` verification confirming `/usr/libexec/rosetta/runtime`, `D3DMetal.framework/Versions/A/D3DMetal`, and `apple_gptk/wine/x86_64-windows/d3d12.dll` (`d3d12_xs_loaded=0`). Functional checks matched M4 identically (`RUN_EXIT=0`, `40/40` and `5/5` on all four benchmarks: `0.332687`, `0.336705`, `0.320010`, `0.168213 ms/submit`). Archived in [`2026-11-27-apple-m5-atesahmet0-b-baseline-runner-01`](../results/2026-11-27-apple-m5-atesahmet0-b-baseline-runner-01/receipt.json).
|
||||
|
||||
## 2. Fence-error correction (`A-13`: `support.h` `b9dfbddb...`, `pool.cpp` `55fbc7fe...`)
|
||||
|
||||
- **Primary-source derivation:** Per Microsoft's `ID3D12CommandQueue::Signal`, `ID3D12Fence::SetEventOnCompletion`, `ID3D12Fence::GetCompletedValue`, and resource-lifetime rules, throwing a C++ exception after `ExecuteCommandLists` when completion is unproven unwinds stack-owned `ID3D12Resource`/`ID3D12Heap` wrappers while GPU execution may still be active. `stopInFlight()` flushes stdio and terminates the disposable guest via `ExitProcess(2)` without stack unwinding; `waitFor()` rejects `completed == ~UINT64(0)` both before and after `WaitForSingleObject` and verifies `completed >= target` after wake.
|
||||
- **Minor non-blocking observations:** `pool.cpp:217` and `allocator-evaluation/probe.cpp:145` check `completed < q->value` (safe in context because preceded by `finish()`/`waitFor()` with no new submission, though `completed == ~UINT64(0) || completed < q->value` is more self-contained). Supervising `allocation-profiling/run.py` should also close `p.stdin` and stop `wineserver` before hashing `stderr.txt` on harness-initiated aborts.
|
||||
- **Bounded M5 runtime verification:** Executed positive gated-copy (`exit=0`, `withheld=1`, `0xCAFE1234`), `stopInFlight` (`exit=2`), and unsignaled `waitFor(1)` 10s timeout (`exit=2`, `wait=258`) with a stack destructor canary confirming `unsafe_unwind=false`. Archived in [`2026-11-27-apple-m5-atesahmet0-b-a-fence-fault-01`](../results/2026-11-27-apple-m5-atesahmet0-b-a-fence-fault-01/results.json).
|
||||
|
||||
## 3. Logical fragmentation (`A-3`: `fragmentation/trace.cpp` `8be2dbde...`, `oracle.py` `ef5193fc...`)
|
||||
|
||||
- **Independent verification (distinct from A's `oracle.py`):** Re-verified all `6,012` snapshots across seeds `473` (`180` failed requests), `474` (`93`), and `475` (`142`) using a separately implemented 512-granule (`64 KiB` granule) bitmap model, plus reran `fragmentation/run.py` on M5 (corrupted-log control rejected).
|
||||
- **Source findings:** `Arena::allocate` splits `free[i]` and appends prefix/suffix remainders via `push_back`, while `give()` sorts and merges adjacent spans; between `allocate` calls without an intervening `give()`, `free` is split-age ordered rather than strictly address-sorted while remaining pairwise disjoint. `up(n, a)` assumes bounded research inputs (`n <= UINT64_MAX - (a - 1)`). Strictly scoped to logical suballocator spans — not D3DMetal driver fragmentation.
|
||||
|
||||
## 4. AMD D3D12 Memory Allocator 3.3.0 (`A-4`: `600949266be004553f74c9ef809384380a9d44cf`)
|
||||
|
||||
- **Provenance and licensing:** Independently fetched upstream `LICENSE.txt` (blob `3d5a69a6f5695507ecc9c412c783ca60572bf878`), `include/D3D12MemAlloc.h` (`b685a5cd6188519606efaf039cd88c2faffa261a`), and `src/D3D12MemAlloc.cpp` (`b7ba60a3a4deb0ed466b235b7c5298f91ba5c976`); verified full 2019–2026 AMD MIT notices in all three files, `GPL-3.0-or-later` compatibility under notice preservation, and external-only non-vendored status in `upstream-registry.md` and `component-reuse-matrix.md`.
|
||||
- **Source/data review and M5 bounded reproduction:** Independently verified all 6 M4 logs (`216` statistics checkpoints, `6 × 432` matched requests against `a22-pool-corrected`, `6` `0x8007000E` `POOL_BOUND_CONTROL` rejections, `144` sampled guard/interior readbacks). Reproduced paired `wb-seed-473` and `wc-seed-473` on M5 using A's updated `support.h` (`b9dfbddb...`); both exited `0` with verified D3DMetal 3.0 backend, rejected `33,554,436` bytes with `0x8007000E`, and matched all `432` requests, `36` stats checkpoints, and `24` readbacks per process (`create_resource` medians `0.0008 ms` WB, `0.0011 ms` WC). Archived in [`2026-11-27-apple-m5-atesahmet0-b-a-d3d12ma-01`](../results/2026-11-27-apple-m5-atesahmet0-b-a-d3d12ma-01/receipt.json). Does not establish application speedups, physical memory savings, texture qualification, or automatic fence retirement.
|
||||
|
||||
## 5. Graphics sampling, depth, and stencil (`A-12`: `render.cpp` `c7433935...`, `check-render.py`)
|
||||
|
||||
- **Source & failure-archive review:** Verified `SV_VertexID` fullscreen triangle math (`uv = (x+0.5)/32, (y+0.5)/16` -> point-sampled `16×16` texel `(x/2, y)`), `D32_FLOAT` `LESS` (`0.75` rejected vs `0.5` clear; `0.25` accepted), and `D24_UNORM_S8_UINT` (`INCR_SAT` from `0` to `1` with `RenderTargetWriteMask=0`, then `EQUAL` rejecting `ref=2` and accepting `ref=1`), resource barriers (`COPY_DEST -> PIXEL_SHADER_RESOURCE`, `DEPTH_WRITE`, `RENDER_TARGET -> COPY_SOURCE -> COMMON`), and the root cause of `a23-render-lifetime-failure` (`render.cpp` `7ed4124f:91` called `FreeLibrary(compiler)` while `ID3DBlob` COM pointers still referenced `d3dcompiler_47.dll`'s vtable; fixed by declaring `CompilerLibrary` before `Ref<ID3DBlob>`).
|
||||
- **M5 same-source execution:** On M5, `render-s0` (`variant=0`) exited `0` and all 7 packed `.rgba` frames matched `512/512` pixels under an independent pixel check; `render-s1` (`variant=1`) stopped cleanly at `STAGE depth` when M5 kernel pressure transiently hit `2` (Urgent) and is preserved verbatim in [`2026-11-27-apple-m5-atesahmet0-b-a-render-01`](../results/2026-11-27-apple-m5-atesahmet0-b-a-render-01/receipt.json). After pressure returned to `1`, `render-omitted-draw-control` (`--negative-control`) exited `1` for `sampled pixels mismatch` with `0/512` matching pixels, verified by `check-render.py` in [`2026-11-27-apple-m5-atesahmet0-b-a-render-omit-01`](../results/2026-11-27-apple-m5-atesahmet0-b-a-render-omit-01/receipt.json). Because M4's two-dataset repeat/control and M5's `render-s1` remain incomplete under Urgent pressure stops, `A-12` properly remains incomplete rather than a completed acceptance matrix.
|
||||
|
||||
## 6. Inverted ownership (`A-5`) and `#464` / PR `#486` (`c13f9c7`) cross-check
|
||||
|
||||
- Inspected `inverted-ownership.md` directly against in-tree `abi/include/bx_xmem_internal.h`, `shims/xmem/xmem.cpp`, `shims/xmem/physical_pages.cpp`, and open PR `#486` (`c13f9c76650edded41774528b50f40798244a6f3`).
|
||||
- Confirmed A's alignment proof (`(P + d) mod 65536 == 0` with `P mod 65536 in {16384, 32768, 49152}` requires `d mod 65536 != 0`, which cannot be a legal 64 KiB-aligned `CreatePlacedResource` heap offset; byte-slice biasing applies only *within* a legally placed buffer and never provides 2 MiB section semantics, requested CPU VAs, `MEM_RESERVE`/decommit reconciliation via `VirtualQuery`, `VirtualAlloc2`/`MapViewOfFile3` scatter views, pre-device allocations, or raw `UNKNOWN` texture pointers).
|
||||
- **Additional concrete source finding for Roadmap R3:** Comparing `shims/xmem/xmem.cpp:73-77` (`can_commit`) with PR `#486`'s `shims/d3d12_xs/vmem.cpp:101-115` (`try_charge` at `c13f9c7`) shows one-way budget visibility: `d3d12_xs` queries `bx_xmem_get_internal_stats` and adds `charged_private_bytes`, whereas `xmem.dll` has no visibility into `d3d12_xs`'s `charged_private_bytes` and uses a separate lock (`usage_lock` vs `g_section`), allowing a subsequent `XMemVirtualAlloc`/`XMemAllocatePhysicalPages` call to exceed the combined title cap after private D3D12 heaps are allocated. Roadmap item `R3` appropriately scopes unified ledger/lock coordination after separate maintainer/ABI review without blocking `#464`.
|
||||
|
||||
## 7. Remaining Workstream B objective inventory
|
||||
|
||||
All assigned Workstream B objectives are accounted for without repeating completed sweeps:
|
||||
- Matched small/full copy bounds, stride/byte-write separation, CPU write/scan timing, and empty/signal-only controls (`b-sweep-01`, `b-sweep-02`).
|
||||
- Direct root SRV/UAV persistent-map shader coherence, poisoned outputs, and omitted-dispatch controls (`b-compute-01`, `b-compute-02`).
|
||||
- Timestamp failure proof (`b-small-03`, `b-small-05`), separate process-scoped Metal System Trace captures (`300` shader + `45` copy intervals), and sanitized target-PID XML inputs (`b-trace-inputs-01`) + `B-local-1.1` finalization fix (`b1-b2-audit.md`).
|
||||
- 4 KiB subpage / 16 KiB boundary / reset / rearm / read / volatile same-value `MEM_WRITE_WATCH` verification (`33` phases), `OpenExistingHeapFromAddress` `E_NOTIMPL` on watch memory (`Unsupported`), GPU-write tracking preserved as `Unknown` (`IsolatedMMU=0` not treated as universal absence), and unauthorized concurrent CPU/GPU spin tests excluded.
|
||||
|
||||
## 8. Reciprocal review decisions on `consolidation-draft` (`677686e`)
|
||||
|
||||
- **Consolidation structure, 8 decision gates (`report.md`), and 8 roadmap items (`implementation-roadmap.md` `R1–R4`, `P1–P4`):** Independently reviewed and **endorsed as technically accurate, properly scoped, and non-blocking to `#464`** (noting PR `#486`'s latest head is now `c13f9c76650edded41774528b50f40798244a6f3`, merging `main` shader-gate work onto `c44ae4e` with `vmem.{h,cpp}` unchanged).
|
||||
- **Scoped per-finding review/acceptance updates for `evidence-register.json`:**
|
||||
- `BASE-1`..`BASE-6`: Upgrade `independent_source_review` (`Independently source-reviewed` by B) and `independent_reproduction` (`Independently reproduced` on M5 via exact shared `run.py` + `--receipt-only` `lsof` in `b-baseline-runner-01`); `BASE-1`, `BASE-3`, `BASE-4`, `BASE-6` meet scoped functional/contract `Independently accepted` criteria, `BASE-2` remains version-scoped `Unsupported` (reproduced on M4+M5), and `BASE-5` is `Independently accepted` specifically for its negative methodological conclusion (small-copy latency does **not** prove absence of copies).
|
||||
- `A-3`: Upgrade to `Independently source-reviewed`, `Independently reproduced` (both `fragmentation/run.py` and B's separate 512-granule bitmap checker), and `Independently accepted` **strictly as a CPU logical-interval model** (not driver fragmentation).
|
||||
- `A-4`: Upgrade to `Independently source-reviewed` (upstream blobs/MIT notices + all 6 M4 logs verified) and `Independently reproduced` (bounded `wb/wc-seed-473` subset on M5 in `b-a-d3d12ma-01`); keep overall acceptance conservative/scoped to single-block single-queue CUSTOM WB/WC buffers (`Independently accepted` for that narrow compatibility/statistics scope only; textures/multi-queue/production speedup remain `Unknown`).
|
||||
- `A-5`: Upgrade to `Independently source-reviewed` against `bx_xmem_internal.h`, `xmem.cpp`, `physical_pages.cpp`, and PR `#486` `vmem.cpp` (including the one-way `charged_private_bytes` accounting note); console ABI meanings remain `Unknown`.
|
||||
- `A-6`: Meets scoped `Independently accepted` criteria (D3D12 placement alignment does not guarantee 64 KiB CPU `Map` alignment; M4+M5 reproduced).
|
||||
- `A-7`: Remains `Failed` on the negative-rejection gate (M4+M5 reproduced; caller-side validation mandatory).
|
||||
- `A-8`, `A-9`, `A-10`: Positive subcases (advanced-model whole-buffer alias inheritance `A-8`, 3-mip `RGBA8`/`R8_UNORM`/`R32_UINT` transfer + disjoint buffer guard `A-9`, post-activation RT/depth clear/readback `A-10`) meet scoped `Independently accepted` criteria across M4+M5 while explicitly retaining `A-9`'s overall process `exit=1` due to `A-7` and claiming no raw texture pointers or texture data inheritance.
|
||||
- `A-11`: `Independently source-reviewed` (historical `frozen-phase2` source/log checked; M5 not rerun; keep `Unknown` beyond tested 1-mip case).
|
||||
- `A-12`: Upgrade to `Independently source-reviewed` and partial M5 same-source reproduction (`render-s0` + `render-omitted-draw-control` passed with `check-render.py`; `render-s1` Urgent-pressure stop preserved); keep overall `Blocked` / `Unknown` until two-dataset repeat completes cleanly.
|
||||
- `A-13`: Upgrade to `Independently source-reviewed`, `Independently reproduced` (M5 positive gate + bounded fault injection in `b-a-fence-fault-01`), and `Independently accepted` **for disposable-guest research probes** (production DLL/process recovery remains separate per `R2`).
|
||||
- `B-7`, `B-8`: Record B's supplied `B-trace-inputs-1` sanitized target-PID XML bundle (`b-trace-inputs-01`) and `b-trace-01` `+3.657 ms` `process.stdin` EOF forensic resolution + `B-local-1.1` fix (`b1-b2-audit.md`); `B-7` awaits A's independent rerun on `B-trace-inputs-1` once published, and `B-8` remains `Failed` on the preserved historical receipt with root cause established and `B-local-1.1` verified.
|
||||
- `B-1`..`B-4`, `X-1`, `X-2`: Keep B's own findings un-self-certified (`B-1..4` awaiting M4 hardware reproduction when M4 pressure recovers; `X-1` `Unknown`; `X-2` `Blocked`/`Unknown` for M1–M3, normal-pressure repeats, and broader resource classes).
|
||||
@@ -0,0 +1,40 @@
|
||||
# Independent review of Workstream A
|
||||
|
||||
Reviewed source and executed snapshots at [8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8](https://github.com/MacosPorters/betterxen/commit/8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8). The published receipts identify the guest builds and retain raw M4 results. I recalculated source snapshot hashes and inspected the command paths and original stdout. M5 reproduction status is recorded separately below.
|
||||
|
||||
## Placement and resource correctness
|
||||
|
||||
| Evidence | Independent expectation and assessment |
|
||||
| --- | --- |
|
||||
| WB mapped CPU pointer alignment | Microsoft specifies alignment for heap-relative placement. Nothing in the Map contract equates CPU and GPU virtual addresses or makes the CPU address 64 KiB aligned. In A's two raw buffer-alias runs, CPU pointers ended in `4000` modulo `10000` (hex). That is 16384 modulo 65536. The GPU VAs were multiples of 65536. Independently written B placement code reproduced the distinction on M5. |
|
||||
| Two invalid creations | A's 64 KiB buffer at offset 1 is misaligned and its allocation span also exceeds the heap by one byte. The aligned offset 65536 lies at the end of the 64 KiB heap and leaves zero bytes for the nonempty buffer. A's two M4 logs show successful returns for both and E_INVALIDARG for a texture on a buffer-only heap. A submitted neither invalid buffer. B separately reproduced the buffer returns on M5. Compare against a valid offset 0. |
|
||||
| Same-offset buffer aliases | The placed buffers have the same known layout, while the guard range is wholly disjoint. The advanced-model alias barrier orders the write and second resource's COPY_SOURCE read in one submitted list. The explicit COMMON transitions scope each use, the fence follows all copies, and the guard exercises a displaced range. The expected pointer and GPU VA deltas are 0 and 65536 respectively. The two raw runs show the correct deltas and 16384/16384 for each of source, inherited and guard readbacks in each of three rounds. The seed steps 0x101 each round and 0x10000 each session. These results demonstrate application-visible addresses and GPU data inheritance for these whole-buffer ranges. The backend's backing pages and arbitrary CPU aliases remain unresolved. |
|
||||
| Mixed mip textures | The three mips have dimensions 65×37, 32×18 and 16×9, totaling 3125 texels. This yields 3125 useful bytes for R8_UNORM and 12500 for RGBA8 or R32_UINT. Distinguish 512-byte copy-placement offsets and 256-byte row pitches from allocation alignment and actual texel widths. WB/WC use per-mip Map with null output and WriteToSubresource in COMMON. DEFAULT uses a staged copy. The readback transition and fence are explicit, and guard writes finish before the subsequent steps. Both raw runs record all nine useful-byte and guard checks exact. Byte count excludes padding. The test does not assert texture sampling or raw texture Map pointer results. |
|
||||
| RGBA8 and depth alias clears | The fixture activates each RT/DS alias and then clears in RENDER_TARGET or DEPTH_WRITE, respectively. Readbacks are distinct and the transition to COPY_SOURCE orders the transfer. RGBA8 clear tuples are (1,0,1,1) and (0,1,1,1), equivalent to little-endian words 0xffff00ff and 0xffffff00. Depth 0.5 and 0.25 correspond to 0x3f000000 and 0x3e800000. Both M4 logs show 2405/2405 per alias for WB and DEFAULT. Each alias is reinitialized. This tests separated activation and clear, so it leaves texture data inheritance, stencil and rasterized depth open. |
|
||||
|
||||
[Microsoft placed resources](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device-createplacedresource), [buffer footprints](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device-getcopyablefootprints), [memory aliasing and data inheritance](https://learn.microsoft.com/en-us/windows/win32/direct3d12/memory-aliasing-and-data-inheritance).
|
||||
|
||||
One harness limitation: A's normal successful runs wait before object teardown. After a fence failure, the shared Queue helper throws with possible outstanding work, unwinding local resources before the parent terminates the guest. That error path should use explicit retirement or disposable-process teardown in future fixtures. It does not change the reported results with valid fences.
|
||||
|
||||
## Physical accounting
|
||||
|
||||
The corrected A2 source retires allocation, command and shader objects, then releases the device. It also includes truly CPU-only and graphics-warmed CPU controls. That materially improves the earlier release checkpoint. The A2 bundle contains 12 completed cases and an interrupted later case. A22 includes a second distinct pressure stop and cannot be pooled as a full repeat of A2.
|
||||
|
||||
A's three in-stage readings are correlated samples within one process. The 64 MiB heap observations can fit existing driver accounting, while the 256 MiB and 1 GiB cases add a charge close to requested size and retain most of that charge after teardown. The same large case has process-ledger footprint and RSS that differ substantially. These observations establish accounting over the observed lifetime, with incomplete independent repetitions, under reported compression and swap. They leave driver pools, caching, mappings billed elsewhere, transient copies and actual physical-page identity open. A dropped CPU-only allocation is a useful control for process accounting, but carries no information about uncharged GPU domains.
|
||||
|
||||
The historical M5 1 GiB fixture copied chunks into one readback region and compared the final chunk's first word. Its command stream requests consumption of the entire buffer, while its oracle directly verifies just that last word. This limits what it can establish about actual work performed. The retained output has no complete independent set of vmmap stages and no raw timing samples for the two dirty runs. Keep the prior comment's numbers as attributed historical results.
|
||||
|
||||
## Pooling and #464
|
||||
|
||||
A's corrected pool trace distinguishes warm allocation/free call timing from cold setup and unused slab capacity. Its real delayed-retirement gate is more meaningful than a future value inserted into the CPU model. The omitted-copy exit is the expected guard/interior mismatch. A smaller warm call cost on the one M4 does not by itself quantify whole-application residency, fragmentation or retained driver memory.
|
||||
|
||||
At [PR #486 head 6308fdc](https://github.com/MacosPorters/betterxen/pull/486), the code already validates a 64 KiB grid, resource allocation alignment and the overflow-safe heap span. The reported PR execution is CrossOver 26.2 vkd3d. Treat this M5 D3DMetal study as research for the implementation, without attributing its results to the PR executable. The PR publishes a Map address. Any 64 KiB or larger xmem alignment promise, fixed-address reservation, alias/scatter view or pre-device ownership requirement must be validated independently. Budget logical bytes separately from the driver-retention envelope.
|
||||
|
||||
## Same-source reproduction on M5
|
||||
|
||||
At the pinned A revision, I rebuilt both sources with their A-local runner, MinGW GCC 16.2.0 and Apple clang 21. The archived source hashes match A's originals. The file hashes of the rebuilt PEs differ, as expected for separate builds. Both sessions loaded the D3DMetal framework and GPTK D3D12, as confirmed by the loaded-library receipt. Host pressure was Warning.
|
||||
|
||||
- Both buffer sessions exited 0 and matched all 18 arrays of 16384 words across the source, inherited and guard outputs. The overlapping pairs had equal CPU and GPU virtual addresses. The disjoint CPU and GPU deltas were both 65536 bytes. Map remainders were 32768 and 16384. See the [alias reproduction](../results/2026-11-27-apple-m5-atesahmet0-b-a-alias-01/receipt.json).
|
||||
- Each texture session matched all nine mixed-heap data and guard comparisons and all eight render/depth clears. Each exited 1 at the same invalid-placement rejection gate. Wrong heap flags still returned E_INVALIDARG. This is a reproduced failure in the full fixture and reproduced positive results in the named valid subcases. See the [texture reproduction](../results/2026-11-27-apple-m5-atesahmet0-b-a-texture-01/receipt.json).
|
||||
- The independently implemented B placement case additionally used offset 1 in a 128 KiB heap, making the span fit while keeping alignment invalid. The backend returned S_OK. In a separate session the valid maps happened to be 64 KiB aligned. This variation reinforces the need to check each actual CPU address. Invalid resources had no Map, GPU address lookup or submission. See the [isolated placement controls](../results/2026-11-27-apple-m5-atesahmet0-b-small-03/00-placement/stdout.txt).
|
||||
- Physical-memory accounting and pooling received source and raw-data review. I did not repeat the large M4 accounting profile under the M5's Warning/Urgent conditions. I independently recomputed three native receipt checkpoints. The 1 GiB CPU-only control was charged 13.19 MiB (settled baseline), 1039.47 MiB (initialization) and 13.45 MiB (device-release checkpoint without a device). The WB graphics process was charged 301.36 MiB (baseline), 1368.32 MiB (GPU-complete) and 1328.02 MiB (after device release). The 64 MiB WB process returned from 341.13 MiB after GPU use to 300.79 MiB after device release, near its 300.62 MiB baseline. These are distinct workload-scoped accounting outcomes. See the [A2 raw accounting receipt](../results/2026-11-26-apple-m4-arths17-a2-memory-partial/receipt.json).
|
||||
@@ -0,0 +1,308 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Build and run B-local probes in a temporary CrossOver bottle."""
|
||||
import argparse
|
||||
import fcntl
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import plistlib
|
||||
import random
|
||||
import re
|
||||
import shutil
|
||||
import signal
|
||||
import subprocess
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
REPO = HERE.parents[3]
|
||||
COHERENCE = HERE.parent / 'gpu-correctness' / 'coherence-and-tracking'
|
||||
CROSSOVER = Path('/Applications/CrossOver.app/Contents/SharedSupport/CrossOver')
|
||||
WINE = CROSSOVER / 'bin/wine'
|
||||
FRAMEWORK = CROSSOVER / 'lib64/apple_gptk/external/D3DMetal.framework/Versions/A'
|
||||
APPLE_GPTK_DLL = CROSSOVER / 'lib64/apple_gptk/wine/x86_64-windows/d3d12.dll'
|
||||
COMPILER_DLL = CROSSOVER / 'lib/wine/x86_64-windows/d3dcompiler_47.dll'
|
||||
BASELINE_SHA = '33e90bfee89e812f48990613cd74ced56473e5c3fc5d973f2ba1116090646a0c'
|
||||
COMPILER = 'x86_64-w64-mingw32-g++'
|
||||
|
||||
|
||||
def sha(path):
|
||||
with path.open('rb') as source:
|
||||
return hashlib.file_digest(source, 'sha256').hexdigest()
|
||||
|
||||
|
||||
def capture(cmd, env, cwd, timeout=15):
|
||||
argv = [str(arg) for arg in cmd]
|
||||
try:
|
||||
result = subprocess.run(argv, env=env, cwd=cwd, text=True,
|
||||
errors='replace', capture_output=True, timeout=timeout)
|
||||
return dict(command=argv, exit=result.returncode, stdout=result.stdout, stderr=result.stderr)
|
||||
except (OSError, subprocess.TimeoutExpired) as failure:
|
||||
return dict(command=argv, exit=None, failure=repr(failure))
|
||||
|
||||
|
||||
def pressure(env, cwd, max_level):
|
||||
kernel = capture(['sysctl', '-n', 'kern.memorystatus_vm_pressure_level'], env, cwd)
|
||||
free = capture(['memory_pressure', '-Q'], env, cwd)
|
||||
match = re.search(r'free percentage: (\d+)%', free.get('stdout', ''))
|
||||
level = kernel.get('stdout', '').strip()
|
||||
ok = (kernel['exit'] == free['exit'] == 0 and level.isdigit()
|
||||
and int(level) <= max_level and match and int(match[1]) >= 30)
|
||||
return dict(allowed=bool(ok), max_kernel_level=max_level, kernel=kernel, free=free,
|
||||
swap=capture(['sysctl', 'vm.swapusage'], env, cwd),
|
||||
vm=capture(['vm_stat'], env, cwd))
|
||||
|
||||
|
||||
def cases_for(group, seed):
|
||||
if group == 'small':
|
||||
return [('copy', ['placement']), ('coherence', ['watch']), ('coherence', ['wrap-watch']), ('copy', ['clock'])]
|
||||
if group == 'compute':
|
||||
names = ['wb', 'wc', 'upload-wb', 'default']
|
||||
random.Random(seed).shuffle(names)
|
||||
return [('coherence', [name]) for name in names]
|
||||
matrix = [('copy', ['sweep', heap, str(size), str(stride), str(seed)])
|
||||
for heap in ['wb', 'wc', 'upload'] for size in [1, 16, 64]
|
||||
for stride in [4096, 16384]]
|
||||
random.Random(seed).shuffle(matrix)
|
||||
return matrix
|
||||
|
||||
|
||||
def ready(process, path, timeout):
|
||||
while time.monotonic() < timeout:
|
||||
if b'BACKEND_READY' in path.read_bytes():
|
||||
return
|
||||
if process.poll() is not None:
|
||||
raise RuntimeError('guest exited before backend marker')
|
||||
time.sleep(0.05)
|
||||
raise TimeoutError('backend marker')
|
||||
|
||||
|
||||
def backend(exe, env, cwd):
|
||||
deadline = time.monotonic() + 5
|
||||
while time.monotonic() < deadline:
|
||||
found = capture(['lsof', '-t', '-a', '-c', exe.name, str(exe)], env, cwd, 2)
|
||||
pids = {p for p in found.get('stdout', '').split() if p.isdigit()}
|
||||
if len(pids) == 1:
|
||||
pid = pids.pop()
|
||||
libs = capture(['lsof', '-n', '-p', pid], env, cwd, 3)
|
||||
markers = ('apple_gptk/wine/x86_64-windows/d3d12.dll',
|
||||
'D3DMetal.framework/Versions/A/D3DMetal', '/rosetta/runtime',
|
||||
'd3d12_xs.dll')
|
||||
paths = [line[line.index('/'):] for line in libs.get('stdout', '').splitlines()
|
||||
if '/' in line and any(marker in line for marker in markers)]
|
||||
verified = (libs['exit'] == 0 and all(any(m in path for path in paths) for m in markers[:2])
|
||||
and not any(markers[-1] in path for path in paths))
|
||||
return dict(verified=verified, guest_pid=pid, lsof_exit=libs['exit'], paths=paths)
|
||||
time.sleep(0.05)
|
||||
return dict(verified=False, message='could not identify unique probe PID', lookup=found)
|
||||
|
||||
|
||||
BASE_PROTOCOL = 'B-local-1.1'
|
||||
after_guest = None
|
||||
|
||||
|
||||
def stop_private_wine(private, env, cwd):
|
||||
if private is None or not private.is_dir():
|
||||
return None
|
||||
stop_env = env | {'WINEPREFIX': str(private), 'CX_BOTTLE_PATH': str(private)}
|
||||
stopped = capture([CROSSOVER / 'bin/wineserver', '-k'], stop_env, cwd, 10)
|
||||
waited = capture([CROSSOVER / 'bin/wineserver', '-w'], stop_env, cwd, 10)
|
||||
return dict(kill=stopped, wait=waited)
|
||||
|
||||
|
||||
def close_stdin(process):
|
||||
if process is not None and process.stdin is not None and not process.stdin.closed:
|
||||
try:
|
||||
process.stdin.close()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def run_case(command, exe, label, has_gpu, case, env, max_level, private=None):
|
||||
case.mkdir()
|
||||
if label == 'coherence' and has_gpu:
|
||||
shader = case.parent / 'source' / (COHERENCE / 'access.hlsl').relative_to(REPO)
|
||||
shutil.copy2(shader, case)
|
||||
result = dict(command=command, timeout_seconds=45, exit=None)
|
||||
deadline = time.monotonic() + result['timeout_seconds']
|
||||
stdout = case / 'stdout.txt'
|
||||
process = None
|
||||
try:
|
||||
with stdout.open('wb') as out, (case / 'stderr.txt').open('wb') as err:
|
||||
process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=out, stderr=err,
|
||||
env=env, cwd=case, start_new_session=True)
|
||||
if has_gpu:
|
||||
ready(process, stdout, min(deadline, time.monotonic() + 20))
|
||||
result['backend'] = backend(exe, env, case)
|
||||
if not result['backend']['verified']:
|
||||
raise RuntimeError('active D3DMetal verification failed before workload')
|
||||
result['pressure_ready'] = pressure(env, case, max_level)
|
||||
if not result['pressure_ready']['allowed']:
|
||||
raise RuntimeError('pressure gate at paused device before workload')
|
||||
process.stdin.write(b'\n')
|
||||
process.stdin.flush()
|
||||
close_stdin(process)
|
||||
result['exit'] = process.wait(timeout=max(0, deadline - time.monotonic()))
|
||||
except BaseException as failure:
|
||||
result['error'] = repr(failure)
|
||||
close_stdin(process)
|
||||
if process is not None:
|
||||
if process.poll() is None:
|
||||
try:
|
||||
os.killpg(process.pid, signal.SIGKILL)
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
guest_pid = result.get('backend', {}).get('guest_pid', '')
|
||||
if str(guest_pid).isdigit():
|
||||
try:
|
||||
os.kill(int(guest_pid), signal.SIGKILL)
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
result['exit'] = process.wait(timeout=5)
|
||||
result['error_wineserver_stop'] = stop_private_wine(private, env, case)
|
||||
if isinstance(failure, KeyboardInterrupt):
|
||||
result['interrupted'] = True
|
||||
finally:
|
||||
if private is not None and private.is_dir() and 'error' not in result:
|
||||
stop_env = env | {'WINEPREFIX': str(private), 'CX_BOTTLE_PATH': str(private)}
|
||||
capture([CROSSOVER / 'bin/wineserver', '-w'], stop_env, case, 10)
|
||||
if after_guest is not None:
|
||||
after_guest(case, result)
|
||||
result['output_hashes'] = {p.name: sha(p) for p in case.iterdir() if p.is_file()}
|
||||
(case / 'case.json').write_text(json.dumps(result, indent=2) + '\n')
|
||||
return result
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--bottle', type=Path)
|
||||
parser.add_argument('--scratch', type=Path, required=True)
|
||||
parser.add_argument('--group', choices=['build', 'small', 'compute', 'sweep'], required=True)
|
||||
parser.add_argument('--seed', type=int, default=473)
|
||||
parser.add_argument('--allow-warning', action='store_true')
|
||||
args = parser.parse_args()
|
||||
if not 0 <= args.seed < 2**32:
|
||||
parser.error('seed must fit uint32')
|
||||
if args.group != 'build' and not args.bottle:
|
||||
parser.error('a win64 CrossOver bottle is required for execution')
|
||||
root = args.scratch.expanduser().resolve()
|
||||
if root == REPO or REPO in root.parents:
|
||||
parser.error('scratch must be outside the checkout')
|
||||
root.mkdir(mode=0o700)
|
||||
env = {k: os.environ[k] for k in ['HOME', 'USER', 'LOGNAME', 'PATH', 'LANG', 'LC_ALL'] if k in os.environ}
|
||||
env.update(TMPDIR=str(root) + '/', ROSETTA_ADVERTISE_AVX='1',
|
||||
CX_GRAPHICS_BACKEND='d3dmetal', WINEDEBUG='-all')
|
||||
receipt = dict(protocol=BASE_PROTOCOL, group=args.group, seed=args.seed,
|
||||
utc=datetime.now(timezone.utc).isoformat(), independent_review='pending',
|
||||
environment={k: env[k] for k in ['ROSETTA_ADVERTISE_AVX', 'CX_GRAPHICS_BACKEND', 'WINEDEBUG']},
|
||||
commands={}, cases=[])
|
||||
source_files = [Path(__file__), HERE / 'support.h', HERE / 'probe.cpp',
|
||||
COHERENCE / 'probe.cpp', COHERENCE / 'access.hlsl']
|
||||
receipt['sources'] = {}
|
||||
for path in source_files:
|
||||
relative = path.resolve().relative_to(REPO)
|
||||
snapshot = root / 'source' / relative
|
||||
snapshot.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(path, snapshot)
|
||||
receipt['sources'][str(relative)] = sha(snapshot)
|
||||
|
||||
def save():
|
||||
(root / 'receipt.json').write_text(json.dumps(receipt, indent=2) + '\n')
|
||||
|
||||
executables = {}
|
||||
tools = {'git': ['git', '-C', REPO, 'rev-parse', 'HEAD'], 'hardware': ['sysctl', '-n',
|
||||
'machdep.cpu.brand_string', 'hw.memsize', 'hw.pagesize'],
|
||||
'os': ['sw_vers'], 'host': ['uname', '-m'], 'cpu_load': ['uptime'],
|
||||
'rosetta': ['pkgutil', '--pkg-info', 'com.apple.pkg.RosettaUpdateAuto'],
|
||||
'compiler': [COMPILER, '--version'], 'compiler_arch': ['file', '-L', shutil.which(COMPILER) or COMPILER],
|
||||
'cx_version': [WINE, '--version'],
|
||||
'wine_engine': [CROSSOVER / 'bin/wineloader', '--version'],
|
||||
'python': ['python3', '--version']}
|
||||
for name, subcommand in tools.items():
|
||||
receipt['commands'][name] = capture(subcommand, env, root)
|
||||
receipt['baseline_sha256'] = sha(HERE.parent / 'probe.cpp')
|
||||
if receipt['baseline_sha256'] != BASELINE_SHA:
|
||||
save()
|
||||
raise RuntimeError('frozen baseline hash differs')
|
||||
receipt['framework'] = plistlib.loads((FRAMEWORK / 'Resources/Info.plist').read_bytes())
|
||||
receipt['runtime_sha256'] = {str(p): sha(p) for p in [APPLE_GPTK_DLL, COMPILER_DLL]}
|
||||
max_level = int(args.allow_warning)
|
||||
receipt['pressure_before'] = pressure(env, root, max_level)
|
||||
save()
|
||||
for name, path in [('copy', HERE), ('coherence', COHERENCE)]:
|
||||
exe = root / ('b-' + name + '.exe')
|
||||
source = root / 'source' / (path / 'probe.cpp').relative_to(REPO)
|
||||
cmd = [COMPILER, '-std=c++20', '-O2', '-static', '-static-libgcc', '-static-libstdc++',
|
||||
'-Wall', '-Wextra', '-Werror', source, '-o', exe]
|
||||
result = capture(cmd, env, root, 60)
|
||||
receipt['commands']['build_' + name] = result
|
||||
save()
|
||||
if result['exit'] != 0:
|
||||
return 1
|
||||
executables[name] = exe
|
||||
receipt.setdefault('executables', {})[name] = dict(filename=exe.name, sha256=sha(exe),
|
||||
format=capture(['file', exe], env, root))
|
||||
save()
|
||||
if args.group == 'build':
|
||||
return 0
|
||||
receipt['pressure_before_bottle'] = pressure(env, root, max_level)
|
||||
if not receipt['pressure_before_bottle']['allowed']:
|
||||
receipt['stop_reason'] = 'pressure gate before bottle clone; execution did not start'
|
||||
save()
|
||||
return 2
|
||||
lock = open('/tmp/betterxen-473-gpu.lock', 'a')
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
bottle = args.bottle.expanduser().resolve()
|
||||
config = bottle / 'cxbottle.conf'
|
||||
original = config.read_text()
|
||||
if '"WineArch" = "win64"' not in original:
|
||||
raise RuntimeError('requires a win64 bottle')
|
||||
receipt['bottle_input_sha256'] = sha(config)
|
||||
private = root / 'bottle'
|
||||
succeeded = True
|
||||
try:
|
||||
shutil.copytree(bottle, private, symlinks=True)
|
||||
clone_config = re.sub(r'(?m)^\[Bottle\]\s*$', '[Bottle]\n"AllowUntrusted" = "1"',
|
||||
original, count=1)
|
||||
clone_config += '\n[EnvironmentVariables]\n"CX_GRAPHICS_BACKEND" = "d3dmetal"\n'
|
||||
clone_config += '\n[CrossOver]\n"AntiVirusScan" = "untrusted"\n'
|
||||
(private / 'cxbottle.conf').write_text(clone_config)
|
||||
receipt['bottle_settings'] = [line for line in clone_config.splitlines() if re.match(
|
||||
r'"(WineArch|Template|WindowsVersion|CX_GRAPHICS_BACKEND|AllowUntrusted|AntiVirusScan)"', line)]
|
||||
receipt['case_order'] = cases_for(args.group, args.seed)
|
||||
for index, (label, argv) in enumerate(receipt['case_order']):
|
||||
before = pressure(env, root, max_level)
|
||||
case = root / ('%02d-' % index + '-'.join(argv))
|
||||
item = dict(directory=case.name, pressure_before=before)
|
||||
receipt['cases'].append(item)
|
||||
if not before['allowed']:
|
||||
receipt['stop_reason'] = 'pressure gate before ' + case.name
|
||||
succeeded = False
|
||||
break
|
||||
exe = executables[label]
|
||||
command = [str(WINE), '--bottle', str(private), '--no-update', '--no-gui',
|
||||
'--workdir', str(case), str(exe), *argv]
|
||||
result = run_case(command, exe, label, argv != ['watch'], case, env, max_level, private)
|
||||
after = pressure(env, root, max_level)
|
||||
item.update(run=result, pressure_after=after)
|
||||
save()
|
||||
succeeded &= result['exit'] == 0 and 'error' not in result
|
||||
if result.get('interrupted') or not after['allowed']:
|
||||
receipt['stop_reason'] = 'interruption or pressure gate after ' + case.name
|
||||
succeeded = False
|
||||
break
|
||||
finally:
|
||||
if private.is_dir():
|
||||
stop_env = env | {'WINEPREFIX': str(private), 'CX_BOTTLE_PATH': str(private)}
|
||||
receipt['commands']['private_wineserver_stop'] = capture(
|
||||
[CROSSOVER / 'bin/wineserver', '-k'], stop_env, root, 10)
|
||||
shutil.rmtree(private)
|
||||
receipt['bottle_unchanged'] = sha(config) == receipt['bottle_input_sha256']
|
||||
save()
|
||||
return 0 if succeeded else 1
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,120 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Match task-only Metal intervals to exact synthetic guest samples."""
|
||||
import argparse
|
||||
from collections import defaultdict
|
||||
import json
|
||||
from pathlib import Path
|
||||
from statistics import median
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
|
||||
def table(path, pid):
|
||||
root = ET.parse(path)
|
||||
elements = {e.attrib['id']: e for e in root.iter() if 'id' in e.attrib}
|
||||
schema = [col.findtext('mnemonic') for col in root.findall('.//schema/col')]
|
||||
|
||||
def resolve(element):
|
||||
if 'ref' in element.attrib:
|
||||
return elements[element.attrib['ref']]
|
||||
return element
|
||||
|
||||
rows = []
|
||||
for raw in root.findall('.//row'):
|
||||
row = dict(zip(schema, map(resolve, raw), strict=True))
|
||||
process = row['process'].find('pid')
|
||||
if process is None or resolve(process).text != str(pid):
|
||||
continue
|
||||
rows.append({k: e.text or e.get('fmt') for k, e in row.items()})
|
||||
return rows
|
||||
|
||||
|
||||
def key(row):
|
||||
return [int(row['cmdbuffer-id']), int(row['encoder-id'])]
|
||||
|
||||
|
||||
def summarize(run, gpu_path, encoding_path):
|
||||
receipt = json.loads((run / 'receipt.json').read_text())
|
||||
case, = receipt['cases']
|
||||
outcome = case['run']
|
||||
if outcome['exit'] != 0 or not outcome['backend']['verified']:
|
||||
raise ValueError('successful guest and verified backend required')
|
||||
pid = int(outcome['backend']['guest_pid'])
|
||||
stdout = run / case['directory'] / 'stdout.txt'
|
||||
compute = False
|
||||
guest = []
|
||||
omitted = 0
|
||||
for line in stdout.read_text().splitlines():
|
||||
name, _, fields = line.partition(' ')
|
||||
if name not in ('COMPUTE', 'TRACE_COPY'):
|
||||
continue
|
||||
row = dict(x.split('=', 1) for x in fields.split())
|
||||
actual, expected = map(int, row['matches'].split('/'))
|
||||
if actual != expected:
|
||||
raise ValueError('guest output mismatch')
|
||||
if name == 'COMPUTE':
|
||||
compute = True
|
||||
if row['mode'] == 'omitted':
|
||||
omitted += 1
|
||||
continue
|
||||
guest.append(row)
|
||||
|
||||
label = 'Compute Command ' if compute else 'Blit Command '
|
||||
encoders = [r for r in table(encoding_path, pid)
|
||||
if r['event-type'] == 'Encoding' and r['encoder-label'].startswith(label)]
|
||||
encoder_keys = {tuple(key(r)) for r in encoders}
|
||||
# The GPU channel may be named Compute even for a Blit encoder. Identify
|
||||
# commands by the encoder's type and pair of IDs, irrespective of nesting.
|
||||
gpu = [r for r in table(gpu_path, pid)
|
||||
if r['state'] == 'Active' and tuple(key(r)) in encoder_keys]
|
||||
gpu.sort(key=lambda r: int(r['start']))
|
||||
encoders.sort(key=lambda r: int(r['start']))
|
||||
if not len(guest) == len(gpu) == len(encoders) or not guest:
|
||||
raise ValueError(f'Unmatched sample, GPU or encoder counts: {len(guest)}, {len(gpu)}, {len(encoders)}')
|
||||
if [key(row) for row in gpu] != [key(row) for row in encoders]:
|
||||
raise ValueError('Metal command-buffer and encoder sequence disagrees')
|
||||
if len({tuple(key(row)) for row in gpu}) != len(gpu):
|
||||
raise ValueError('Duplicate command or encoder pair')
|
||||
|
||||
samples = []
|
||||
grouped = defaultdict(list)
|
||||
for expected, device, cpu in zip(guest, gpu, encoders, strict=True):
|
||||
samples.append(dict(mode=expected.get('mode', 'copy'), iter=int(expected['iter']),
|
||||
workload_payload=int(expected.get('gpu_payload', '0')),
|
||||
read_bytes=int(expected.get('read_bytes', '0')),
|
||||
written_bytes=int(expected.get('written_bytes', '0')),
|
||||
guest_completion_us=float(expected['completion_us']),
|
||||
ids=key(device), channel=device['channel-name'],
|
||||
nested_depth=int(device['event-depth']), encoder_label=cpu['encoder-label'],
|
||||
gpu_start_ns=int(device['start']), gpu_duration_ns=int(device['duration']),
|
||||
metal_encode_ns=int(cpu['duration']), comparison=expected['matches']))
|
||||
if samples[-1]['iter'] >= 0:
|
||||
grouped[samples[-1]['mode']].append(samples[-1])
|
||||
distributions = {}
|
||||
for mode, values in grouped.items():
|
||||
if len(values) != 12:
|
||||
raise ValueError(f'Incorrect measured sample count for {mode}')
|
||||
durations = [s['gpu_duration_ns'] / 1000 for s in values]
|
||||
mid = median(durations)
|
||||
distributions[mode] = dict(n=len(values), median_gpu_us=mid,
|
||||
minimum_gpu_us=min(durations), maximum_gpu_us=max(durations),
|
||||
mad_gpu_us=median(abs(x - mid) for x in durations),
|
||||
payload_GB_s={field: median(s[field] / s['gpu_duration_ns'] for s in values)
|
||||
for field in ('workload_payload', 'read_bytes', 'written_bytes')
|
||||
if values[0][field]})
|
||||
return dict(guest_pid=pid, case=case['directory'], matched_intervals=len(gpu),
|
||||
omitted_dispatch_guest_samples=omitted, distributions=distributions,
|
||||
samples=samples)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('scratch', type=Path)
|
||||
parser.add_argument('gpu_intervals', type=Path)
|
||||
parser.add_argument('encoders', type=Path)
|
||||
args = parser.parse_args()
|
||||
print(json.dumps(summarize(args.scratch, args.gpu_intervals, args.encoders), indent=2))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,84 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Summarize raw measured iterations without pooling independent sessions."""
|
||||
import argparse
|
||||
import json
|
||||
import statistics
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def distribution(values):
|
||||
if not values:
|
||||
return None
|
||||
ordered = sorted(values)
|
||||
n = len(ordered)
|
||||
return dict(n=n, min=ordered[0], p10=ordered[(n - 1) // 10],
|
||||
median=statistics.median(ordered), p90=ordered[((n - 1) * 9 + 9) // 10],
|
||||
max=ordered[-1], mad=statistics.median(
|
||||
abs(x - statistics.median(ordered)) for x in ordered))
|
||||
|
||||
|
||||
def summarize(path):
|
||||
receipt = json.loads((path / 'receipt.json').read_text())
|
||||
metrics = {}
|
||||
rows = []
|
||||
for item in receipt['cases']:
|
||||
case = item['directory']
|
||||
run = item.get('run', {})
|
||||
stdout = path / case / 'stdout.txt'
|
||||
cases = []
|
||||
metrics[case] = dict(exit=run.get('exit'), backend=run.get('backend'),
|
||||
error=run.get('error'), samples=cases)
|
||||
if not stdout.is_file():
|
||||
continue
|
||||
for line in stdout.read_text().splitlines():
|
||||
name, _, fields = line.partition(' ')
|
||||
if name not in {'COPY', 'CPU', 'COMPUTE', 'EMPTY'}:
|
||||
continue
|
||||
row = dict(field.split('=', 1) for field in fields.split())
|
||||
if int(row['iter']) < 0:
|
||||
continue
|
||||
keys = ('bytes', 'stride', 'dirty', 'full_write', 'full_read', 'omit', 'mode')
|
||||
identity = (case, name, tuple((k, row[k]) for k in keys if k in row))
|
||||
rows.append((identity, row))
|
||||
groups = {}
|
||||
for identity, row in rows:
|
||||
groups.setdefault(identity, []).append(row)
|
||||
for (case, name, group), samples in groups.items():
|
||||
times = {k: distribution([float(s[k]) for s in samples if float(s[k]) >= 0])
|
||||
for k in samples[0] if k.endswith('_us')}
|
||||
rates = {}
|
||||
for payload, timer, label in [
|
||||
('bytes', 'write_us', 'cpu_write'), ('bytes', 'read_us', 'cpu_read'),
|
||||
('gpu_payload', 'gpu_us', 'gpu_copy'), ('read_bytes', 'gpu_us', 'gpu_read_with_output'),
|
||||
('written_bytes', 'gpu_us', 'gpu_write_with_input'),
|
||||
('gpu_payload', 'completion_us', 'copy_end_to_end'),
|
||||
('read_bytes', 'completion_us', 'shader_read_end_to_end'),
|
||||
('written_bytes', 'completion_us', 'shader_write_end_to_end'),
|
||||
]:
|
||||
if payload not in samples[0] or timer not in samples[0]:
|
||||
continue
|
||||
if label == 'gpu_copy' and group and dict(group).get('full_read') != '1':
|
||||
continue
|
||||
vals = [int(s[payload]) / float(s[timer]) / 1000 for s in samples
|
||||
if int(s[payload]) > 0 and float(s[timer]) > 0]
|
||||
if vals:
|
||||
rates[label] = distribution(vals)
|
||||
comparisons = [s['matches'].split('/') for s in samples if 'matches' in s]
|
||||
metrics[case]['samples'].append(dict(kind=name, factors=dict(group), n=len(samples),
|
||||
exact_iterations=sum(a == b for a, b in comparisons) if comparisons else None,
|
||||
timestamp_invalid=sum(float(s['gpu_us']) <= 0 for s in samples) if 'gpu_us' in samples[0] else None,
|
||||
microseconds=times, decimal_GB_s=rates))
|
||||
return dict(directory=path.name, group=receipt['group'], seed=receipt['seed'],
|
||||
stop_reason=receipt.get('stop_reason'), cases=metrics)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('run', nargs='+', type=Path)
|
||||
args = parser.parse_args()
|
||||
print(json.dumps([summarize(path) for path in args.run], indent=2))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,240 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#pragma once
|
||||
|
||||
#include <windows.h>
|
||||
#include <d3d12.h>
|
||||
#include <immintrin.h>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
template <typename T> class Com {
|
||||
T* ptr = nullptr;
|
||||
public:
|
||||
Com() = default;
|
||||
~Com() { if (ptr) ptr->Release(); }
|
||||
Com(const Com&) = delete;
|
||||
Com& operator=(const Com&) = delete;
|
||||
Com(Com&& other) noexcept : ptr(std::exchange(other.ptr, nullptr)) {}
|
||||
Com& operator=(Com&& other) noexcept {
|
||||
std::swap(ptr, other.ptr);
|
||||
return *this;
|
||||
}
|
||||
T* get() const { return ptr; }
|
||||
T* operator->() const { return ptr; }
|
||||
void** out() { return reinterpret_cast<void**>(&ptr); }
|
||||
};
|
||||
|
||||
inline void check(HRESULT hr, const char* name) {
|
||||
if (SUCCEEDED(hr)) return;
|
||||
std::fprintf(stderr, "%s hr=%08lx\n", name, static_cast<unsigned long>(hr));
|
||||
throw std::runtime_error(name);
|
||||
}
|
||||
|
||||
inline long long ticks() {
|
||||
LARGE_INTEGER value;
|
||||
QueryPerformanceCounter(&value);
|
||||
return value.QuadPart;
|
||||
}
|
||||
|
||||
inline double us(long long delta) {
|
||||
static const double frequency = [] {
|
||||
LARGE_INTEGER value;
|
||||
QueryPerformanceFrequency(&value);
|
||||
return double(value.QuadPart);
|
||||
}();
|
||||
return double(delta) * 1e6 / frequency;
|
||||
}
|
||||
|
||||
inline D3D12_RESOURCE_DESC buffer_desc(UINT64 bytes, D3D12_RESOURCE_FLAGS flags) {
|
||||
D3D12_RESOURCE_DESC desc{};
|
||||
desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
|
||||
desc.Width = bytes;
|
||||
desc.Height = 1;
|
||||
desc.DepthOrArraySize = 1;
|
||||
desc.MipLevels = 1;
|
||||
desc.SampleDesc.Count = 1;
|
||||
desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
|
||||
desc.Flags = flags;
|
||||
return desc;
|
||||
}
|
||||
|
||||
enum class Heap { wb, wc, upload, readback, gpu };
|
||||
|
||||
inline D3D12_HEAP_PROPERTIES properties(Heap kind) {
|
||||
D3D12_HEAP_PROPERTIES prop{};
|
||||
prop.CreationNodeMask = prop.VisibleNodeMask = 1;
|
||||
switch (kind) {
|
||||
case Heap::wb:
|
||||
case Heap::wc:
|
||||
prop.Type = D3D12_HEAP_TYPE_CUSTOM;
|
||||
prop.MemoryPoolPreference = D3D12_MEMORY_POOL_L0;
|
||||
prop.CPUPageProperty = kind == Heap::wb
|
||||
? D3D12_CPU_PAGE_PROPERTY_WRITE_BACK : D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE;
|
||||
break;
|
||||
case Heap::upload: prop.Type = D3D12_HEAP_TYPE_UPLOAD; break;
|
||||
case Heap::readback: prop.Type = D3D12_HEAP_TYPE_READBACK; break;
|
||||
case Heap::gpu: prop.Type = D3D12_HEAP_TYPE_DEFAULT; break;
|
||||
}
|
||||
return prop;
|
||||
}
|
||||
|
||||
struct Device {
|
||||
HMODULE dll = LoadLibraryW(L"d3d12.dll");
|
||||
Com<ID3D12Device> device;
|
||||
Device() {
|
||||
if (!dll || GetModuleHandleW(L"d3d12_xs.dll"))
|
||||
throw std::runtime_error("host d3d12.dll or shim gate");
|
||||
auto create = reinterpret_cast<decltype(&D3D12CreateDevice)>(
|
||||
reinterpret_cast<void*>(GetProcAddress(dll, "D3D12CreateDevice")));
|
||||
if (!create) throw std::runtime_error("D3D12CreateDevice symbol");
|
||||
check(create(nullptr, D3D_FEATURE_LEVEL_11_0, __uuidof(ID3D12Device),
|
||||
device.out()), "D3D12CreateDevice");
|
||||
char path[MAX_PATH]{};
|
||||
GetModuleFileNameA(dll, path, MAX_PATH);
|
||||
D3D12_FEATURE_DATA_ARCHITECTURE1 arch{};
|
||||
const HRESULT result = device->CheckFeatureSupport(D3D12_FEATURE_ARCHITECTURE1,
|
||||
&arch, sizeof(arch));
|
||||
std::printf("DEVICE dll=%s shim=0 architecture_hr=%08lx uma=%d coherent=%d isolated_mmu=%d\n",
|
||||
path, static_cast<unsigned long>(result), arch.UMA,
|
||||
arch.CacheCoherentUMA, arch.IsolatedMMU);
|
||||
}
|
||||
|
||||
Com<ID3D12Heap> heap(Heap kind, UINT64 bytes) {
|
||||
D3D12_HEAP_DESC desc{};
|
||||
desc.SizeInBytes = bytes;
|
||||
desc.Alignment = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT;
|
||||
desc.Properties = properties(kind);
|
||||
desc.Flags = D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS;
|
||||
Com<ID3D12Heap> result;
|
||||
check(device->CreateHeap(&desc, __uuidof(ID3D12Heap), result.out()), "CreateHeap");
|
||||
return result;
|
||||
}
|
||||
};
|
||||
|
||||
struct Buffer {
|
||||
Com<ID3D12Heap> backing;
|
||||
Com<ID3D12Resource> resource;
|
||||
void* pointer = nullptr;
|
||||
Buffer(Device& d, Heap kind, UINT64 bytes, D3D12_RESOURCE_STATES state,
|
||||
D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE) {
|
||||
const auto desc = buffer_desc(bytes, flags);
|
||||
if (kind == Heap::wb || kind == Heap::wc) {
|
||||
const auto alloc = d.device->GetResourceAllocationInfo(0, 1, &desc);
|
||||
backing = d.heap(kind, alloc.SizeInBytes);
|
||||
check(d.device->CreatePlacedResource(backing.get(), 0, &desc, state, nullptr,
|
||||
__uuidof(ID3D12Resource), resource.out()), "CreatePlacedResource");
|
||||
} else {
|
||||
const auto prop = properties(kind);
|
||||
check(d.device->CreateCommittedResource(&prop, D3D12_HEAP_FLAG_NONE, &desc,
|
||||
state, nullptr, __uuidof(ID3D12Resource), resource.out()),
|
||||
"CreateCommittedResource");
|
||||
}
|
||||
}
|
||||
~Buffer() { if (pointer) resource->Unmap(0, nullptr); }
|
||||
uint32_t* map() {
|
||||
check(resource->Map(0, nullptr, &pointer), "Map");
|
||||
if (!pointer) throw std::runtime_error("Map returned null");
|
||||
return static_cast<uint32_t*>(pointer);
|
||||
}
|
||||
};
|
||||
|
||||
struct Queue {
|
||||
Com<ID3D12CommandQueue> queue;
|
||||
Com<ID3D12CommandAllocator> allocator;
|
||||
Com<ID3D12GraphicsCommandList> list;
|
||||
Com<ID3D12Fence> fence;
|
||||
HANDLE event = nullptr;
|
||||
UINT64 value = 0;
|
||||
ID3D12Device* device;
|
||||
explicit Queue(Device& d) : device(d.device.get()) {
|
||||
D3D12_COMMAND_QUEUE_DESC desc{};
|
||||
desc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
|
||||
check(device->CreateCommandQueue(&desc, __uuidof(ID3D12CommandQueue), queue.out()), "CreateCommandQueue");
|
||||
check(device->CreateCommandAllocator(desc.Type, __uuidof(ID3D12CommandAllocator), allocator.out()), "CreateCommandAllocator");
|
||||
check(device->CreateCommandList(0, desc.Type, allocator.get(), nullptr,
|
||||
__uuidof(ID3D12GraphicsCommandList), list.out()), "CreateCommandList");
|
||||
check(list->Close(), "initial Close");
|
||||
check(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), fence.out()), "CreateFence");
|
||||
event = CreateEventW(nullptr, FALSE, FALSE, nullptr);
|
||||
if (!event) throw std::runtime_error("CreateEvent");
|
||||
}
|
||||
~Queue() { CloseHandle(event); }
|
||||
void begin() {
|
||||
check(allocator->Reset(), "allocator Reset");
|
||||
check(list->Reset(allocator.get(), nullptr), "list Reset");
|
||||
}
|
||||
void transition(ID3D12Resource* resource, D3D12_RESOURCE_STATES from,
|
||||
D3D12_RESOURCE_STATES to) {
|
||||
D3D12_RESOURCE_BARRIER barrier{};
|
||||
barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
|
||||
barrier.Transition = {resource, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, from, to};
|
||||
list->ResourceBarrier(1, &barrier);
|
||||
}
|
||||
void alias(ID3D12Resource* before, ID3D12Resource* after) {
|
||||
D3D12_RESOURCE_BARRIER barrier{};
|
||||
barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_ALIASING;
|
||||
barrier.Aliasing = {before, after};
|
||||
list->ResourceBarrier(1, &barrier);
|
||||
}
|
||||
void close() { check(list->Close(), "Close command list"); }
|
||||
struct Latency { double execute, signal, wait, total; };
|
||||
Latency execute(bool submit = true) {
|
||||
ID3D12CommandList* lists[] = {list.get()};
|
||||
const auto start = ticks();
|
||||
if (submit) queue->ExecuteCommandLists(1, lists);
|
||||
const auto executed = ticks();
|
||||
// A signal/event failure leaves work in flight. Terminate the disposable
|
||||
// guest without unwinding resources that may still be referenced.
|
||||
const HRESULT signal = queue->Signal(fence.get(), ++value);
|
||||
const auto signalled = ticks();
|
||||
const HRESULT arm = SUCCEEDED(signal) ? fence->SetEventOnCompletion(value, event) : signal;
|
||||
const DWORD wait = SUCCEEDED(arm) ? WaitForSingleObject(event, 5000) : WAIT_FAILED;
|
||||
const auto complete = ticks();
|
||||
if (wait != WAIT_OBJECT_0 || fence->GetCompletedValue() < value ||
|
||||
fence->GetCompletedValue() == UINT64_MAX) {
|
||||
std::fprintf(stderr, "fence failure signal=%08lx arm=%08lx wait=%lu completed=%llu target=%llu\n",
|
||||
static_cast<unsigned long>(signal), static_cast<unsigned long>(arm),
|
||||
static_cast<unsigned long>(wait), fence->GetCompletedValue(), value);
|
||||
std::fflush(nullptr);
|
||||
ExitProcess(2);
|
||||
}
|
||||
check(device->GetDeviceRemovedReason(), "GetDeviceRemovedReason");
|
||||
return {us(executed - start), us(signalled - executed), us(complete - signalled),
|
||||
us(complete - start)};
|
||||
}
|
||||
};
|
||||
|
||||
inline void receipt_pause() {
|
||||
std::puts("BACKEND_READY");
|
||||
if (std::getchar() == EOF) throw std::runtime_error("backend receipt handshake");
|
||||
}
|
||||
|
||||
struct Timestamp {
|
||||
Com<ID3D12QueryHeap> queries;
|
||||
Buffer output;
|
||||
UINT64 hz = 0;
|
||||
const UINT64* data;
|
||||
Timestamp(Device& d, Queue& q)
|
||||
: output(d, Heap::readback, 16, D3D12_RESOURCE_STATE_COPY_DEST) {
|
||||
const D3D12_QUERY_HEAP_DESC desc{D3D12_QUERY_HEAP_TYPE_TIMESTAMP, 2, 0};
|
||||
check(d.device->CreateQueryHeap(&desc, __uuidof(ID3D12QueryHeap), queries.out()), "timestamp heap");
|
||||
check(q.queue->GetTimestampFrequency(&hz), "GetTimestampFrequency");
|
||||
if (!hz) throw std::runtime_error("zero GPU timestamp frequency");
|
||||
data = reinterpret_cast<const UINT64*>(output.map());
|
||||
std::printf("TIMESTAMP hertz=%llu\n", hz);
|
||||
}
|
||||
void start(Queue& q) { q.list->EndQuery(queries.get(), D3D12_QUERY_TYPE_TIMESTAMP, 0); }
|
||||
void end(Queue& q) {
|
||||
q.list->EndQuery(queries.get(), D3D12_QUERY_TYPE_TIMESTAMP, 1);
|
||||
q.list->ResolveQueryData(queries.get(), D3D12_QUERY_TYPE_TIMESTAMP, 0, 2, output.resource.get(), 0);
|
||||
}
|
||||
double elapsed() const {
|
||||
if (data[1] <= data[0]) return -1;
|
||||
return double(data[1] - data[0]) * 1e6 / double(hz);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,81 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""One Instruments capture attached to the verified synthetic guest."""
|
||||
import importlib.util
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
if len(sys.argv) < 2:
|
||||
sys.exit('Provide a trace case followed by the run.py options.')
|
||||
selection = sys.argv.pop(1)
|
||||
if selection in {'wb', 'wc', 'upload-wb', 'default'}:
|
||||
workload = ('coherence', [selection])
|
||||
elif selection.startswith('copy-') and selection[5:] in {'wb', 'wc', 'upload'}:
|
||||
workload = ('copy', ['trace-copy', selection[5:]])
|
||||
else:
|
||||
sys.exit('Select wb, wc, upload-wb, default, copy-wb, copy-wc or copy-upload.')
|
||||
runner_path = Path(__file__).resolve().with_name('run.py')
|
||||
spec = importlib.util.spec_from_file_location("b_runner", runner_path)
|
||||
runner = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(runner)
|
||||
detect = runner.backend
|
||||
trace = None
|
||||
args = None
|
||||
log_file = None
|
||||
trace_exit = 0
|
||||
|
||||
def attach(exe, env, cwd):
|
||||
global trace, args, log_file
|
||||
result = detect(exe, env, cwd)
|
||||
if not result["verified"]:
|
||||
return result
|
||||
# Attach only to the verified private guest, before releasing its handshake.
|
||||
args = ["xcrun", "xctrace", "record", "--template", "Metal System Trace",
|
||||
"--attach", result["guest_pid"], "--time-limit", "5s",
|
||||
"--no-prompt", "--output", str(cwd / "gpu.trace")]
|
||||
log_file = cwd / "xctrace-output.txt"
|
||||
trace_env = env | {"DEVELOPER_DIR": "/Applications/Xcode.app/Contents/Developer"}
|
||||
with log_file.open("wb") as log:
|
||||
trace = subprocess.Popen(args, stdin=subprocess.DEVNULL, stdout=log,
|
||||
stderr=subprocess.STDOUT, env=trace_env, cwd=cwd,
|
||||
start_new_session=True)
|
||||
deadline = time.monotonic() + 8
|
||||
while time.monotonic() < deadline and trace.poll() is None:
|
||||
if b"Ctrl-C" in log_file.read_bytes():
|
||||
time.sleep(0.3)
|
||||
break
|
||||
time.sleep(0.1)
|
||||
return result
|
||||
|
||||
|
||||
def finalize_trace(case, _result):
|
||||
global trace, trace_exit
|
||||
if trace is None:
|
||||
return
|
||||
try:
|
||||
result_code = trace.wait(30)
|
||||
except subprocess.TimeoutExpired:
|
||||
trace.terminate()
|
||||
result_code = trace.wait(5)
|
||||
trace = None
|
||||
trace_exit = result_code
|
||||
receipt = {"command": args, "exit": result_code, "xcrun_developer_dir":
|
||||
"/Applications/Xcode.app/Contents/Developer", "log": log_file.name,
|
||||
"trace_exists": (case / "gpu.trace").exists()}
|
||||
(case / "xctrace.json").write_text(json.dumps(receipt, indent=2) + "\n")
|
||||
|
||||
|
||||
runner.backend = attach
|
||||
runner.after_guest = finalize_trace
|
||||
runner.cases_for = lambda group, seed: [workload]
|
||||
status = 1
|
||||
try:
|
||||
status = runner.main()
|
||||
finally:
|
||||
if trace is not None and log_file is not None:
|
||||
finalize_trace(log_file.parent, None)
|
||||
if trace_exit and status == 0:
|
||||
status = trace_exit
|
||||
sys.exit(status)
|
||||
@@ -0,0 +1,57 @@
|
||||
# Version-scoped findings
|
||||
|
||||
> Initial one-host baseline record, kept as written. Later review and reproduction status is in the [evidence register](allocation-profiling/consolidation-draft/evidence-register.md); see the [integration record](integration.md).
|
||||
|
||||
Research issue [#473](https://github.com/MacosPorters/betterxen/issues/473); methodology and limitations are in the [research README](README.md). This is a one-host observation, independent of #464's production implementation. The newly written probe still needs independent source review and reproduction by another contributor.
|
||||
|
||||
## Recorded host and runtime
|
||||
|
||||
Both sessions used Apple M4; unified RAM 25769803776 bytes (24 GiB); macOS 27.0, build 26A428; CrossOver public 26.3.0, product 26.3.0.39832, build tag cxoffice-26.3.0rc2, timestamp 20260715T103801Z; D3DMetal framework short/build version 3.0, SourceVersion 32047000000000; Rosetta package 1.0.0.0.1788432274; Windows 11 template win11_64 / WineArch win64; native ARM64 GCC 16.2.0 / MinGW-w64 14.0.0_3. The source bottle was copied into a temporary private prefix. ROSETTA_ADVERTISE_AVX=1 and CX_GRAPHICS_BACKEND=d3dmetal were set; timed runs had WINEDEBUG=-all.
|
||||
|
||||
Loaded-library inspection in a separate diagnostic confirmed the app's apple_gptk D3D12 DLL, DXGI DLL, D3DMetal framework and Rosetta runtime. The guest reported no d3d12_xs.dll. No timed-run stderr or method-specific D3DMetal log message was emitted. Unsupported calls returned their printed HRESULTs.
|
||||
|
||||
## Baseline outcomes
|
||||
|
||||
These exact outcomes agreed in both local sessions:
|
||||
|
||||
| Experiment | Observation | Evidence scope |
|
||||
| --- | --- | --- |
|
||||
| Architecture | UMA=0, CacheCoherentUMA=0, TileBasedRenderer=0, IsolatedMMU=0; ResourceHeapTier=2 | API-reported values, not a description of the Mac's physical topology |
|
||||
| Existing-memory opens | Address and mapping both 0x80004001 (E_NOTIMPL) | CPU visibility through these heaps not tested because no heap opened |
|
||||
| CUSTOM heaps | All five WRITE_BACK/WRITE_COMBINE L0 cases 0x00000000; WRITE_BACK/L1 control 0x80070057 (E_INVALIDARG) | Creation only for restricted heap cases; no render/depth texture usage tested |
|
||||
| Mixed placement | UAV-capable 64 KiB buffer at 0; 64×64 RGBA8 texture at 65536; both alive on one heap | Texture CPU round-trip 4096/4096 words; no GPU texture readback |
|
||||
| CPU→GPU persistent map | 11223344/A1B2C3D4 then 55AA00FF/F00DBA5E both matched | Fence-separated buffer copies; no Unmap/remap or staging upload |
|
||||
| GPU→CPU persistent map | C001D00D/9E3779B9 matched at original CPU pointer | GPU copy from UPLOAD, fence, direct CPU read |
|
||||
| Dirty-page tracking | Return 0; count 2; granularity 4096; offsets 0 and 16384 | Single allocation/reset query; fallback correctness not established |
|
||||
|
||||
Hardware execution is local class A evidence within these workloads. Public D3D12 API contracts are class B; internal sharing/copy mechanism and cross-generation behavior are class U. These are not independent acceptance or Xbox compatibility claims.
|
||||
|
||||
## Latency observations
|
||||
|
||||
Each row has 5/5 warmup matches and 40/40 timed matches. Size increases by 4096× between the two WRITE_BACK cases. Each submission copies just 128 bytes; timings include CPU encoding, fence synchronization and validation.
|
||||
|
||||
| Session | Case | Total ms / 40 | Average ms/submit | Exact matches |
|
||||
| --- | --- | ---: | ---: | ---: |
|
||||
| Initial | WRITE_BACK/L0 64 KiB | 20.635900 | 0.515898 | 40/40 |
|
||||
| Initial | WRITE_BACK/L0 256 MiB | 30.937300 | 0.773432 | 40/40 |
|
||||
| Initial | WRITE_COMBINE/L0 256 MiB | 11.762100 | 0.294052 | 40/40 |
|
||||
| Initial | UPLOAD 256 MiB | 10.118800 | 0.252970 | 40/40 |
|
||||
| Shared-runner verification | WRITE_BACK/L0 64 KiB | 11.558300 | 0.288957 | 40/40 |
|
||||
| Shared-runner verification | WRITE_BACK/L0 256 MiB | 11.961700 | 0.299042 | 40/40 |
|
||||
| Shared-runner verification | WRITE_COMBINE/L0 256 MiB | 9.973900 | 0.249347 | 40/40 |
|
||||
| Shared-runner verification | UPLOAD 256 MiB | 8.198200 | 0.204955 | 40/40 |
|
||||
|
||||
The two sizes do not show latency proportional to the 4096× size difference in these sessions. This is consistent with shared storage or a sparse-copy mechanism; it does not establish O(1) behavior generally, physical aliasing, or guaranteed zero-copy. The machine was not idle; a background C++ language-service process was observed using about one CPU core before the initial run. Session variation is substantial, and no statistical confidence or performance improvement is claimed.
|
||||
|
||||
## Raw records
|
||||
|
||||
- [Initial stdout](results/2026-11-26-apple-m4-arths17-initial/stdout.txt), [stderr](results/2026-11-26-apple-m4-arths17-initial/stderr.txt), [receipt](results/2026-11-26-apple-m4-arths17-initial/receipt.json), [backend excerpt and launch notes](results/2026-11-26-apple-m4-arths17-initial/backend-receipt.txt).
|
||||
- [Shared-runner stdout](results/2026-11-26-apple-m4-arths17-runner/stdout.txt), [stderr](results/2026-11-26-apple-m4-arths17-runner/stderr.txt), [receipt](results/2026-11-26-apple-m4-arths17-runner/receipt.json). This run records the exact published source hash and executed PE hash. The initial executable was not retained/hashed before the diagnostic extension was added; its incomplete receipt is explicitly marked.
|
||||
|
||||
## Unresolved work for the collaborators
|
||||
|
||||
1. Independently review the probe against public contracts and reproduce the same source revision on another Apple Silicon generation; append independent raw logs and repeated timing sessions.
|
||||
2. Measure resident/physical memory and internal copy activity in a separately named supplemental experiment. Neither was measured here. A 64 KiB prefault stride does not make every host page resident; do not infer a second 256 MiB allocation from virtual size or these timings.
|
||||
3. Establish GPU texture coherence/readback, format/layout and render/depth restrictions separately. The current texture check is only a CPU round-trip.
|
||||
4. Verify lifetime/reuse, dirty-page rearming/reset races and explicit fallback copying where necessary. The baseline only serializes accesses with per-submission fences.
|
||||
5. Give #464 evidence-scoped recommendations: these runtime versions reject both caller-memory wrapping APIs, while host-allocated custom L0 heaps support the observed buffer access. This does not supply an arbitrary-xmem-to-heap bridge, justify silent fallbacks or permit console flush operations to become no-ops.
|
||||
@@ -0,0 +1,26 @@
|
||||
# Direct compute coherence and write-watch
|
||||
|
||||
The [B runner](../../copy-detection/README.md) builds this original C++20 guest and runs the original HLSL through the installed d3dcompiler_47 DLL with `main`, `cs_5_0` and requests optimization level 3. The tested compiler emits a diagnostic that it ignores flag 0x8000. The runner records compiler/module identity and DXBC hashes. It retains stdout/stderr, pipeline and device errors, the exact HLSL and every comparison.
|
||||
|
||||
## Correctness and throughput
|
||||
|
||||
The shader consumes a CPU-written dataset through a raw root SRV and writes a raw root UAV. WB and WC trials keep each pointer mapped through dataset changes and fence-separated GPU output reads. An UPLOAD-to-WB trial and a fully staged DEFAULT-to-DEFAULT trial provide controls. DEFAULT staging and poison copies finish before the measured dispatch. Any output staging copy is ordered by a UAV-to-COPY_SOURCE transition and sits outside the GPU timestamp pair.
|
||||
|
||||
For a result slot `i`, the CPU independently enumerates the conceptual input word indices, regenerates input values from the seed, performs a widened sum and reduces it modulo 2^32. GPU arithmetic is unsigned 32-bit. Sample extremes, mismatch positions and exact match counts are retained. Poisoning each prior output detects stale data. The omitted dispatch control compares against the poison so the predicted negative behavior is explicit. The separate frozen historical shader probe uses an intentionally failing omitted-dispatch oracle.
|
||||
|
||||
The four configurations use identical dispatch shapes, but staging and command encoding differ between direct and DEFAULT output. Compare useful GPU payload rates using the GPU timestamp interval. Submission/fence timings include each configuration's actual transfer and barrier commands.
|
||||
|
||||
| Workload | Input reads | Output writes |
|
||||
| --- | --- | --- |
|
||||
| Both | Every word in 4 MiB | Every result word in 4 MiB |
|
||||
| Full read | Every word in 4 MiB | 256 KiB of dependent output |
|
||||
| Sparse 4 KiB | One word per 4 KiB of 4 MiB | 4 KiB of dependent output |
|
||||
| Sparse 16 KiB | One word per 16 KiB of 4 MiB | 1 KiB of dependent output |
|
||||
| Write | Zero input loads by uniform zero iteration count | Every result word in 4 MiB |
|
||||
| Omitted | Zero | Zero, and CPU verifies unchanged poison |
|
||||
|
||||
The read workloads include shader indexing, accumulation and an observable output. Rates apply to those workloads and do not measure isolated memory-pin bandwidth or hardware counters for physical transactions.
|
||||
|
||||
## Write tracking
|
||||
|
||||
A CPU-only guest tests a fresh allocation, one subpage, nonresetting queries, adjacent 4 KiB writes, both sides of a 16 KiB boundary, automatic and separate reset, rearming, read-only and same-value store. A separate D3D12 process attempts to wrap the actual watch-enabled region and reports capability and exact HRESULT. GPU tracking remains untested if the region cannot be imported. The fixture does not apply GetWriteWatch to a foreign pointer. [Tracking and synchronization contract](../contracts/synchronization-mapping-tracking.md).
|
||||
@@ -0,0 +1,21 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
ByteAddressBuffer source : register(t0);
|
||||
RWByteAddressBuffer target : register(u0);
|
||||
|
||||
cbuffer Params : register(b0) {
|
||||
uint outputs;
|
||||
uint strideWords;
|
||||
uint readsPerOutput;
|
||||
uint seed;
|
||||
};
|
||||
|
||||
[numthreads(64, 1, 1)]
|
||||
void main(uint index : SV_DispatchThreadID) {
|
||||
if (index >= outputs)
|
||||
return;
|
||||
uint result = seed + index * 37u;
|
||||
// At stride one the wave reads consecutive words for each iteration.
|
||||
for (uint n = 0; n < readsPerOutput; ++n)
|
||||
result += source.Load(4u * strideWords * (index + n * outputs));
|
||||
target.Store(4u * index, result ^ 0xa5c35a3cu);
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#include "../../copy-detection/support.h"
|
||||
#include <d3dcompiler.h>
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <vector>
|
||||
|
||||
constexpr UINT capacity = 4 * 1024 * 1024;
|
||||
constexpr UINT words = capacity / 4;
|
||||
constexpr UINT poison = 0x6ba8fa03u;
|
||||
|
||||
static void watch() {
|
||||
constexpr UINT size = 65536;
|
||||
auto* ptr = static_cast<unsigned char*>(VirtualAlloc(nullptr, size,
|
||||
MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE));
|
||||
if (!ptr) throw std::runtime_error("VirtualAlloc MEM_WRITE_WATCH");
|
||||
SYSTEM_INFO system{};
|
||||
GetSystemInfo(&system);
|
||||
std::printf("WATCH guest_page=%lu allocation_granularity=%lu cpu_mod16k=%llu\n",
|
||||
system.dwPageSize, system.dwAllocationGranularity,
|
||||
UINT64(reinterpret_cast<uintptr_t>(ptr) % 16384));
|
||||
bool exact = true;
|
||||
auto expect = [&](const char* label, DWORD flags, const std::vector<UINT>& expected) {
|
||||
std::array<void*, 64> addresses{};
|
||||
ULONG_PTR count = addresses.size();
|
||||
DWORD granularity = 0;
|
||||
const UINT status = GetWriteWatch(flags, ptr, size, addresses.data(), &count, &granularity);
|
||||
std::vector<UINT> actual;
|
||||
if (!status && count <= addresses.size())
|
||||
for (ULONG_PTR i = 0; i < count; ++i)
|
||||
actual.push_back(UINT(static_cast<unsigned char*>(addresses[i]) - ptr));
|
||||
std::sort(actual.begin(), actual.end());
|
||||
std::printf("WATCH phase=%s rc=%u granularity=%lu count=%llu actual=",
|
||||
label, status, granularity, UINT64(count));
|
||||
for (const auto offset : actual) std::printf("%u,", offset);
|
||||
std::printf(" expected=");
|
||||
for (const auto offset : expected) std::printf("%u,", offset);
|
||||
std::puts("");
|
||||
if (status || count > addresses.size() || granularity != 4096 || actual != expected)
|
||||
exact = false;
|
||||
};
|
||||
auto* mapped = static_cast<volatile unsigned char*>(ptr);
|
||||
expect("fresh", 0, {});
|
||||
mapped[4096] = 1;
|
||||
expect("only_second_guest_page", 0, {4096});
|
||||
expect("query_without_reset", 0, {4096});
|
||||
mapped[8192] = 2;
|
||||
expect("second_and_third", WRITE_WATCH_FLAG_RESET, {4096, 8192});
|
||||
expect("after_query_reset", 0, {});
|
||||
mapped[4096] = 3;
|
||||
expect("same_page_rearmed", WRITE_WATCH_FLAG_RESET, {4096});
|
||||
mapped[16383] = 4;
|
||||
mapped[16384] = 5;
|
||||
expect("host_boundary", 0, {12288, 16384});
|
||||
const UINT reset = ResetWriteWatch(ptr, size);
|
||||
std::printf("WATCH ResetWriteWatch rc=%u\n", reset);
|
||||
if (reset) throw std::runtime_error("ResetWriteWatch");
|
||||
expect("after_explicit_reset", 0, {});
|
||||
const auto read = mapped[16384];
|
||||
std::printf("WATCH read_only value=%u\n", UINT(read));
|
||||
expect("after_read_only", 0, {});
|
||||
mapped[16384] = 5;
|
||||
expect("same_value_store_after_reset", WRITE_WATCH_FLAG_RESET, {16384});
|
||||
expect("final_empty", 0, {});
|
||||
if (!VirtualFree(ptr, 0, MEM_RELEASE)) throw std::runtime_error("VirtualFree");
|
||||
if (!exact) throw std::runtime_error("watch page oracle");
|
||||
}
|
||||
|
||||
static void wrap_watch(Device& d) {
|
||||
constexpr UINT size = 65536;
|
||||
Com<ID3D12Device3> dev;
|
||||
check(d.device->QueryInterface(__uuidof(ID3D12Device3), dev.out()), "ID3D12Device3");
|
||||
void* pointer = VirtualAlloc(nullptr, size, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE);
|
||||
if (!pointer) throw std::runtime_error("VirtualAlloc wrapper control");
|
||||
HRESULT hr;
|
||||
{
|
||||
Com<ID3D12Heap> heap;
|
||||
hr = dev->OpenExistingHeapFromAddress(pointer, __uuidof(ID3D12Heap), heap.out());
|
||||
std::printf("WATCH_WRAP hr=%08lx object=%d gpu_writes=NOT_RUN\n",
|
||||
static_cast<unsigned long>(hr), heap.get() != nullptr);
|
||||
}
|
||||
if (!VirtualFree(pointer, 0, MEM_RELEASE)) throw std::runtime_error("VirtualFree");
|
||||
if (SUCCEEDED(hr)) throw std::runtime_error("wrapper available; GPU tracking remains untested");
|
||||
}
|
||||
|
||||
struct Pipeline {
|
||||
Com<ID3D12RootSignature> root;
|
||||
Com<ID3D12PipelineState> pso;
|
||||
explicit Pipeline(Device& d) {
|
||||
auto* compiler = LoadLibraryW(L"d3dcompiler_47.dll");
|
||||
if (!compiler) throw std::runtime_error("D3DCompiler 47");
|
||||
char path[MAX_PATH]{};
|
||||
GetModuleFileNameA(compiler, path, MAX_PATH);
|
||||
std::printf("SHADER compiler=%s profile=cs_5_0 flags=O3\n", path);
|
||||
FILE* file = std::fopen("access.hlsl", "rb");
|
||||
if (!file) throw std::runtime_error("open HLSL");
|
||||
std::array<char, 8192> hlsl{};
|
||||
const size_t length = std::fread(hlsl.data(), 1, hlsl.size(), file);
|
||||
std::fclose(file);
|
||||
if (!length || length == hlsl.size()) throw std::runtime_error("HLSL length");
|
||||
auto compile = reinterpret_cast<decltype(&D3DCompile)>(
|
||||
reinterpret_cast<void*>(GetProcAddress(compiler, "D3DCompile")));
|
||||
auto serialize = reinterpret_cast<decltype(&D3D12SerializeRootSignature)>(
|
||||
reinterpret_cast<void*>(GetProcAddress(d.dll, "D3D12SerializeRootSignature")));
|
||||
if (!compile || !serialize) throw std::runtime_error("shader tool symbols");
|
||||
Com<ID3DBlob> shader, errors;
|
||||
const auto hr = compile(hlsl.data(), length, "access.hlsl", nullptr, nullptr,
|
||||
"main", "cs_5_0", D3DCOMPILE_OPTIMIZATION_LEVEL3, 0,
|
||||
reinterpret_cast<ID3DBlob**>(shader.out()),
|
||||
reinterpret_cast<ID3DBlob**>(errors.out()));
|
||||
if (errors.get()) std::fwrite(errors->GetBufferPointer(), 1, errors->GetBufferSize(), stderr);
|
||||
check(hr, "D3DCompile");
|
||||
file = std::fopen("access.dxbc", "wb");
|
||||
if (!file) throw std::runtime_error("open shader receipt");
|
||||
const size_t written = std::fwrite(shader->GetBufferPointer(), 1, shader->GetBufferSize(), file);
|
||||
if (std::fclose(file) || written != shader->GetBufferSize())
|
||||
throw std::runtime_error("write shader receipt");
|
||||
D3D12_ROOT_PARAMETER params[3]{};
|
||||
params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_SRV;
|
||||
params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV;
|
||||
params[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
|
||||
params[2].Constants.Num32BitValues = 4;
|
||||
D3D12_ROOT_SIGNATURE_DESC signature{3, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE};
|
||||
Com<ID3DBlob> blob, root_errors;
|
||||
check(serialize(&signature, D3D_ROOT_SIGNATURE_VERSION_1,
|
||||
reinterpret_cast<ID3DBlob**>(blob.out()),
|
||||
reinterpret_cast<ID3DBlob**>(root_errors.out())), "serialize root");
|
||||
check(d.device->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(),
|
||||
__uuidof(ID3D12RootSignature), root.out()), "root signature");
|
||||
D3D12_COMPUTE_PIPELINE_STATE_DESC desc{};
|
||||
desc.pRootSignature = root.get();
|
||||
desc.CS = {shader->GetBufferPointer(), shader->GetBufferSize()};
|
||||
check(d.device->CreateComputePipelineState(&desc, __uuidof(ID3D12PipelineState), pso.out()),
|
||||
"compute PSO");
|
||||
}
|
||||
};
|
||||
|
||||
static uint32_t input_word(UINT index, UINT seed) {
|
||||
return (index ^ (seed * 0x01010301u)) + index * 17u;
|
||||
}
|
||||
|
||||
static void compute(Device& d, Heap input_kind, Heap output_kind) {
|
||||
using State = D3D12_RESOURCE_STATES;
|
||||
constexpr State common = D3D12_RESOURCE_STATE_COMMON;
|
||||
constexpr State generic = D3D12_RESOURCE_STATE_GENERIC_READ;
|
||||
constexpr State uav = D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
|
||||
constexpr State copy_dest = D3D12_RESOURCE_STATE_COPY_DEST;
|
||||
constexpr State copy_src = D3D12_RESOURCE_STATE_COPY_SOURCE;
|
||||
|
||||
Buffer source(d, input_kind, capacity, input_kind == Heap::upload ? generic : common);
|
||||
Buffer target(d, output_kind, capacity, common, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS);
|
||||
Buffer readback(d, Heap::readback, capacity, copy_dest);
|
||||
Buffer stage(d, Heap::upload, capacity, generic);
|
||||
const bool direct_output = output_kind != Heap::gpu;
|
||||
auto* cpu_source = input_kind == Heap::gpu ? stage.map() : source.map();
|
||||
auto* cpu_result = direct_output ? target.map() : readback.map();
|
||||
auto* stage_data = input_kind == Heap::gpu ? cpu_source : stage.map();
|
||||
Pipeline shader(d);
|
||||
Queue q(d);
|
||||
Timestamp timing(d, q);
|
||||
|
||||
struct Work { const char* name; UINT outputs, stride, reads; bool omit; };
|
||||
for (const auto work : {Work{"both", words, 1, 1, false},
|
||||
Work{"full_read", words / 16, 1, 16, false},
|
||||
Work{"sparse_read_4k", words / 1024, 1024, 1, false},
|
||||
Work{"sparse_read_16k", words / 4096, 4096, 1, false},
|
||||
Work{"write", words, 1, 0, false},
|
||||
Work{"omitted", words, 1, 1, true}}) {
|
||||
for (int iteration = -3; iteration < 12; ++iteration) {
|
||||
const UINT seed = 407 + UINT(iteration + 3) * 13u;
|
||||
for (UINT j = 0; j < words; ++j) cpu_source[j] = input_word(j, seed);
|
||||
if (direct_output) std::fill_n(cpu_result, work.outputs, poison);
|
||||
_mm_sfence();
|
||||
|
||||
// DEFAULT controls stage data and poison in a separate, fenced list.
|
||||
if (input_kind == Heap::gpu) {
|
||||
q.begin();
|
||||
q.list->CopyBufferRegion(source.resource.get(), 0, stage.resource.get(), 0, capacity);
|
||||
q.close();
|
||||
q.execute();
|
||||
}
|
||||
if (!direct_output) {
|
||||
std::fill_n(stage_data, work.outputs, poison);
|
||||
_mm_sfence();
|
||||
q.begin();
|
||||
q.list->CopyBufferRegion(target.resource.get(), 0, stage.resource.get(), 0,
|
||||
work.outputs * 4u);
|
||||
q.close();
|
||||
q.execute();
|
||||
}
|
||||
const auto start = ticks();
|
||||
q.begin();
|
||||
q.transition(target.resource.get(), common, uav);
|
||||
q.list->SetPipelineState(shader.pso.get());
|
||||
q.list->SetComputeRootSignature(shader.root.get());
|
||||
q.list->SetComputeRootShaderResourceView(0, source.resource->GetGPUVirtualAddress());
|
||||
q.list->SetComputeRootUnorderedAccessView(1, target.resource->GetGPUVirtualAddress());
|
||||
const UINT constants[] = {work.outputs, work.stride, work.reads, seed};
|
||||
q.list->SetComputeRoot32BitConstants(2, 4, constants, 0);
|
||||
timing.start(q);
|
||||
if (!work.omit) q.list->Dispatch((work.outputs + 63) / 64, 1, 1);
|
||||
timing.end(q);
|
||||
if (!direct_output) {
|
||||
q.transition(target.resource.get(), uav, copy_src);
|
||||
q.list->CopyBufferRegion(readback.resource.get(), 0, target.resource.get(), 0,
|
||||
work.outputs * 4u);
|
||||
q.transition(target.resource.get(), copy_src, common);
|
||||
} else {
|
||||
q.transition(target.resource.get(), uav, common);
|
||||
}
|
||||
q.close();
|
||||
const auto encoded = ticks();
|
||||
const auto latency = q.execute();
|
||||
UINT matches = 0;
|
||||
uint32_t first_expected = 0, last_expected = 0;
|
||||
for (UINT j = 0; j < work.outputs; ++j) {
|
||||
// Reconstruct the conceptual indices and input values without
|
||||
// consulting either mapped buffer. Use a widened sum and reduce
|
||||
// modulo 2^32 once to model unsigned shader overflow.
|
||||
uint64_t sum = uint64_t(j) * 37 + seed;
|
||||
for (UINT n = 0; n < work.reads; ++n)
|
||||
sum += input_word(work.stride * (j + n * work.outputs), seed);
|
||||
const uint32_t expected = work.omit ? poison : uint32_t(sum) ^ 0xa5c35a3cu;
|
||||
if (!j) first_expected = expected;
|
||||
if (j == work.outputs - 1) last_expected = expected;
|
||||
if (matches == j && cpu_result[j] != expected)
|
||||
std::printf("MISMATCH index=%u actual=%08x expected=%08x\n", j, cpu_result[j], expected);
|
||||
matches += cpu_result[j] == expected;
|
||||
}
|
||||
std::printf("COMPUTE mode=%s iter=%d seed=%u direct_out=%d read_bytes=%u written_bytes=%u "
|
||||
"gpu_tick_begin=%llu gpu_tick_end=%llu encode_us=%.3f execute_us=%.3f signal_us=%.3f wait_us=%.3f completion_us=%.3f gpu_us=%.3f "
|
||||
"expected=%08x,%08x actual=%08x,%08x matches=%u/%u\n",
|
||||
work.name, iteration, seed, direct_output,
|
||||
work.omit ? 0 : work.outputs * work.reads * 4u,
|
||||
work.omit ? 0 : work.outputs * 4u, timing.data[0], timing.data[1], us(encoded - start),
|
||||
latency.execute, latency.signal, latency.wait, latency.total, timing.elapsed(),
|
||||
first_expected, last_expected, cpu_result[0], cpu_result[work.outputs - 1],
|
||||
matches, work.outputs);
|
||||
if (matches != work.outputs) throw std::runtime_error("compute or poison oracle");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
setvbuf(stdout, nullptr, _IONBF, 0);
|
||||
try {
|
||||
if (argc != 2) throw std::runtime_error("usage: probe watch|wrap-watch|wb|wc|upload-wb|default");
|
||||
const std::string mode = argv[1];
|
||||
if (mode == "watch") {
|
||||
watch();
|
||||
} else {
|
||||
Device device;
|
||||
receipt_pause();
|
||||
if (mode == "wrap-watch") wrap_watch(device);
|
||||
else if (mode == "wb") compute(device, Heap::wb, Heap::wb);
|
||||
else if (mode == "wc") compute(device, Heap::wc, Heap::wc);
|
||||
else if (mode == "upload-wb") compute(device, Heap::upload, Heap::wb);
|
||||
else if (mode == "default") compute(device, Heap::gpu, Heap::gpu);
|
||||
else throw std::runtime_error("unknown mode");
|
||||
}
|
||||
std::puts("END complete");
|
||||
return 0;
|
||||
} catch (const std::exception& e) {
|
||||
std::fprintf(stderr, "END failure: %s\n", e.what());
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
# Resource, placement and lifetime contract
|
||||
|
||||
Workstream A's public-contract derivation for [#473](https://github.com/MacosPorters/betterxen/issues/473), read 2026-11-26. Class B describes API contracts, not console semantics or implementation certification. B's independent synchronization review is requested and pending. A-local helper code is isolated; it is not an agreed replacement for shared helpers.
|
||||
|
||||
## Ownership and addressing
|
||||
|
||||
[CreatePlacedResource](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device-createplacedresource) takes a heap-relative offset, with resource allocation alignment and bounds. It accepts no requested CPU virtual address. [GetResourceAllocationInfo](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device-getresourceallocationinfo%28uint_uint_constd3d12_resource_desc%29) gives adapter/resource allocation size and alignment; these are not CPU Map-pointer guarantees. Ordinary buffers round their allocation size to 64 KiB; texture requirements depend on the adapter.
|
||||
|
||||
[Map](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12resource-map) supports persistent mapping until the resource's final reference is released. It does not promise normal pointer capabilities or a fixed address across unnested maps. The allocation owner must retain the resource and heap for any live guest pointer; callers cannot free or decommit an interior mapped pointer using ordinary VirtualFree. A 64 KiB heap offset and a 64 KiB-aligned CPU pointer are different conditions.
|
||||
|
||||
## Placement, aliases and initialization
|
||||
|
||||
For a simple alias model, activate the resource with an aliasing barrier, invalidate overlapping resources and initialize render/depth resources after activation. Full clear or full-subresource copies satisfy the required initialization. An alias switch has no implicit data-inheritance assumption. A's texture alias fixture uses two render/depth resources at the same heap offset in one command list, clears each after its own activation and reads each before the next activation. Disjoint buffer/texture cases retain and verify a separate buffer guard.
|
||||
|
||||
The API also has an advanced model: an ExecuteCommandLists boundary can provide alias-ordering guarantees between separate invocations. This does not excuse concurrent overlapping access or eliminate required texture initialization. A's fixtures explicitly issue aliasing barriers to keep their intended use inspectable. [CreatePlacedResource remarks](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device-createplacedresource).
|
||||
|
||||
## Retirement and synchronization handoff
|
||||
|
||||
CPU writes finish before GPU submission. CPU reads, overwrites, destruction and allocator reuse occur only after completion of the last queue fence using that range. A's allocation trace holds a real queued copy behind a short CPU-signaled gate, observes its retirement value still pending, withholds the allocation, releases the gate and waits with a timeout before validating/releasing. This tests the fixture's delayed-retirement policy; it does not exhaust every multi-queue lifetime case. No unsafe free or data race is deliberately executed.
|
||||
|
||||
[CreateHeap](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device-createheap) requires the GPU to stop using the heap before its final reference is released; placed resources hold heap references. Process-accounted memory after resource release alone cannot distinguish application references, runtime caches and driver retention. The corrected accounting fixture records resource release, disposal of all command objects/output/pipeline, a settled retirement checkpoint and device release separately. A high remaining footprint is not by itself a leak.
|
||||
|
||||
B owns common mapping/synchronization/tracking contracts and implementation. Review requested: CPU store completion, transition states, fence error paths, alias activation, reset/retirement ordering and queue-gate cleanup. A owns resource lifetime scenarios and observed accounting, not general CPU/GPU atomic interoperability. No concurrent CPU/GPU polling test is included.
|
||||
|
||||
## Texture copies and storage
|
||||
|
||||
[GetCopyableFootprints](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device-getcopyablefootprints) returns copy-buffer offsets, padded row pitches and unpadded row bytes. These describe transfer layouts, not opaque texture backing. Fixtures test offsets in 512-byte units, row pitches in 256-byte units and exact pixel bytes without interpreting padding as texels. CPU texture writes occur in COMMON; GPU reads use COPY_SOURCE and readback buffers stay COPY_DEST.
|
||||
|
||||
[Texture layouts](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ne-d3d12-d3d12_texture_layout) distinguish UNKNOWN from restricted cross-adapter ROW_MAJOR. Ordinary opaque textures do not expose a conventional texel pointer through Map; requesting a null output pointer is not an experiment proving pointer-return failure. The historical valid ROW_MAJOR control uses a shared cross-adapter DEFAULT heap and ALLOW_CROSS_ADAPTER, one mip/slice, no depth/MSAA. Ordinary UPLOAD/READBACK textures are excluded by the [heap-type contract](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ne-d3d12-d3d12_heap_type).
|
||||
|
||||
Apple's [storage-mode documentation](https://developer.apple.com/documentation/metal/choosing-a-resource-storage-mode-for-apple-gpus) distinguishes CPU/GPU-accessible shared resources from GPU-only private resources even on unified-memory hardware. That is a Metal contract; it does not establish which Metal mode an opaque D3DMetal D3D12 heap uses. DEFAULT versus CUSTOM is a D3D12 test comparison, not a measurement of the underlying Metal storage mode.
|
||||
|
||||
## Buffer data inheritance scope
|
||||
|
||||
The separate buffer fixture uses overlapping placed buffers with fully defined ROW_MAJOR layouts and compatible buffer states, an explicit alias barrier between each GPU write/read use, and full source initialization. It alternates the writer and verifies inherited data plus a disjoint guard. The expectation is derived from [Memory Aliasing and Data Inheritance](https://learn.microsoft.com/en-us/windows/win32/direct3d12/memory-aliasing-and-data-inheritance), rather than from the simple model's no-inheritance assumption. Its passing observations remain subject to B's independent source/contract review.
|
||||
|
||||
## Graphics supplement expectations
|
||||
|
||||
The graphics fixture binds an SRV table, a static point/clamp sampler and a vertex-stage root constant; graphics root state is explicitly set on every new command list. Microsoft's [root-signature contract](https://learn.microsoft.com/en-us/windows/win32/direct3d12/using-a-root-signature) requires compatibility with the active graphics pipeline. Source textures transition to PIXEL_SHADER_RESOURCE; render targets transition through RENDER_TARGET/COPY_SOURCE/COMMON, and depth/stencil resources use DEPTH_WRITE. Readback is inspected only after the queue fence. These rules do not authorize simultaneous CPU writes while sampling.
|
||||
|
||||
From the [depth/stencil state definition](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ns-d3d12-d3d12_depth_stencil_desc), the fixture's LESS test accepts 0.25 against clear depth 0.5 and rejects 0.75. Stencil starts at zero and uses [INCR_SAT](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ne-d3d12-d3d12_stencil_op) with color writes disabled, yielding one where the triangle covers; a later EQUAL comparison accepts reference one and rejects two. Identical front/back settings remove face-selection ambiguity. Correct RGBA output therefore tests the interaction of rasterization, sampling and the selected comparison outcomes, not a raw stencil-plane readback or all stencil operations. Expectations are class B derivations, results class A within their recorded workload, with reciprocal B review pending.
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
# Synchronization, mapping and write tracking
|
||||
|
||||
Workstream B contract review for [#473](https://github.com/MacosPorters/betterxen/issues/473) and [#464](https://github.com/MacosPorters/betterxen/issues/464). Public D3D12 and Windows contracts are class B. The [probe and result guide](../../copy-detection/README.md) records version-scoped local observations and the status of reciprocal review.
|
||||
|
||||
## Ordering and lifetime
|
||||
|
||||
- Finish CPU stores before the GPU submission that can read them. For this x86-64 guest, the fixtures order the stores before submission with an SFENCE. The caller owns ordering between CPU producer threads and the thread that submits. For CPU reads of GPU-written data, wait for the fence value signaled on the consuming or writing queue. Treat a failed wait, timeout or device-removed fence as a failed run. [Map contract](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12resource-map).
|
||||
- On one queue, place the fence signal after the relevant execution. A CPU-side fence signal cannot establish GPU completion. Across queues, signal the producing queue and wait on the consuming queue before dependent commands. Keep the queue-specific resource state requirements and use one progress timeline per fence where possible. [Multi-engine synchronization](https://learn.microsoft.com/en-us/windows/win32/direct3d12/user-mode-heap-synchronization).
|
||||
- Persistent mapping of CPU-accessible resources is supported. Keep the resource alive as long as the pointer is used and retire commands before reclaiming memory or overwriting ranges still in use. Map and Unmap ranges convey CPU access information for tools. Persistent access does not wait for the GPU, guarantee a stable pointer across resource destruction, or imply concurrent CPU/GPU atomic interoperability. Use Map with a null output for CPU subresource access to opaque textures where the API supports it. [Map](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12resource-map), [WriteToSubresource](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12resource-writetosubresource).
|
||||
- Complete outstanding GPU use before releasing heaps, resources, descriptors, command allocators or mapped storage they reference. For reusing an overlapping span, retire the last use and apply the aliasing rules for the new resource. For GPU-queued reuse without a CPU wait, enforce the dependency on the participating queues. [Resource barriers](https://learn.microsoft.com/en-us/windows/win32/direct3d12/using-resource-barriers-to-synchronize-resource-states-in-direct3d-12), [placed-resource usage](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device-createplacedresource).
|
||||
|
||||
## States and aliases used in this research
|
||||
|
||||
| Operation | Contract used |
|
||||
| --- | --- |
|
||||
| Buffer copied from or read as a shader resource | Use COPY_SOURCE or NON_PIXEL_SHADER_RESOURCE. COMMON buffers may promote implicitly to these read states. Implicitly promoted buffers decay at completed ExecuteCommandLists operation boundaries. STANDARD UPLOAD remains GENERIC_READ, which includes these states. |
|
||||
| GPU copy into readback | READBACK stays COPY_DEST. Map may remain live and CPU consumes bytes after the fence. |
|
||||
| Shader UAV output | Transition to UNORDERED_ACCESS before the dispatch. Transition from UAV to COPY_SOURCE before a dependent readback copy, or restore COMMON for the next submission. When dependent UAV accesses remain in UAV state, order them with a UAV barrier. |
|
||||
| Mixed placed buffer and texture | Use heap tier and flags appropriate to both resources. Use allocation-info alignment and size for the heap span. Use copyable footprints for buffer offsets and row pitches, and apply states per resource or subresource as needed. |
|
||||
| Overlapping render/depth textures | Activate the new alias at the execution boundary or via the appropriate alias barrier. In the simple model, initialize each RT/DS resource after activation using an allowed clear, discard or full subresource copy before other uses. |
|
||||
| Buffer alias inheritance | The advanced model permits inheritance in documented compatible overlapping layouts. Establish ordering with an alias barrier inside one Execute operation or with the documented separate Execute operation boundary. Verify distinct guard data and do not extrapolate across layouts. |
|
||||
|
||||
[Resource state promotion, decay and barrier rules](https://learn.microsoft.com/en-us/windows/win32/direct3d12/using-resource-barriers-to-synchronize-resource-states-in-direct3d-12), [aliasing and data inheritance](https://learn.microsoft.com/en-us/windows/win32/direct3d12/memory-aliasing-and-data-inheritance), [placed-resource lifetime and initialization](resource-placement-lifetime.md).
|
||||
|
||||
D3D12 placement alignment constrains a heap-relative byte offset. Validate candidate offsets and spans before creation with checks equivalent to `offset % alignment == 0`, `offset <= heap_size` and `allocation_size <= heap_size - offset`. A CPU virtual pointer has its own alignment. Biasing a CPU pointer within a mapped buffer can align that pointer, but a separately placed resource at the matching biased heap offset may violate placement requirements. A constant whole-heap offset on a 64 KiB grid cannot change the mapped base's remainder. [CreatePlacedResource](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device-createplacedresource).
|
||||
|
||||
## Write tracking
|
||||
|
||||
GetWriteWatch and ResetWriteWatch require a region reserved with VirtualAlloc and MEM_WRITE_WATCH. Use returned granularity and address offsets, and track application ownership of each dirty range. To use these pages as the source of an explicit selective copy, quiesce writers or establish coherent per-range ownership over collection, reset, snapshot/copy, and reuse. A separate GetWriteWatch followed by ResetWriteWatch can drop writes in the middle. Combining collection and reset still leaves races with data copying when writers can modify the same bytes concurrently. Retry paths must retain or conservatively restore dirty coverage. [GetWriteWatch](https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-getwritewatch), [ResetWriteWatch](https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-resetwritewatch).
|
||||
|
||||
A 4 KiB guest report can distinguish stores within a 16 KiB host page. That observation describes the Windows API on the tested Wine version. It does not establish the tracking implementation's physical granularity. A D3D12 Map address has no demonstrated MEM_WRITE_WATCH allocation contract. GPU stores remain untracked unless an independently validated mechanism is available. IsolatedMMU TRUE states a GPU guarantee regarding CPU page-table properties, with documented granularity and false-positive caveats. FALSE supplies no guarantee and cannot establish a universal absence of GPU-related dirty reports. Application-managed flags or shader instrumentation can cover known writers and ranges. Arbitrary GPU writes require a separate supported mechanism or conservative copies. [Architecture1](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ns-d3d12-d3d12_feature_data_architecture1).
|
||||
|
||||
Apple's public Metal shared resource contract governs applications that create resources with that storage mode and coordinate access. It cannot identify an opaque D3D12 translation's storage or exclude internal copies. [Metal shared storage](https://developer.apple.com/documentation/metal/mtlstoragemode/shared).
|
||||
@@ -0,0 +1,30 @@
|
||||
# Texture and placed-resource fixtures
|
||||
|
||||
Workstream A extends the frozen baseline and preserved M4 supplemental texture check for [#473](https://github.com/MacosPorters/betterxen/issues/473). [The inventory](../../allocation-profiling/inventory/README.md) records the already tested 65x37 RGBA8 one-mip UNKNOWN and valid ROW_MAJOR cross-adapter controls; their identical experiments are not newly commissioned here. [Resource/lifetime notes](../contracts/resource-placement-lifetime.md) derive expected behavior from primary D3D12 documentation. Independent review is pending.
|
||||
|
||||
Run `../../allocation-profiling/run.py --suite texture` with the documented `--bottle` and a fresh external `--scratch` directory. It compiles this original `probe.cpp`, performs two fresh-process sessions with different datasets, and archives raw results, exact source/PE hashes, commands, backend evidence and failures. `--smoke` performs one session. No shader is needed by these copy/clear cases, so shader hashes are not applicable.
|
||||
|
||||
New cases use 65x37 textures with three mip levels in RGBA8, R8_UNORM and R32_UINT, on CUSTOM/WB/L0, CUSTOM/WC/L0 and DEFAULT heaps. Each texture coexists with a disjoint 64 KiB buffer on the same Tier-2 heap. Every buffer guard word and every actual mip texel byte is compared after GPU readback. CPU-visible textures use per-subresource Map with a null output pointer and WriteToSubresource in COMMON. DEFAULT textures are initialized through a footprint-pitched UPLOAD buffer. Copy footprints use a nonzero 512-byte base offset, padded row pitches and separately checked unpadded row sizes. These transfer layouts do not reveal opaque texture storage.
|
||||
|
||||
Separate RGBA8 render-target and D32_FLOAT depth cases place two resources at the same heap offset on WB and DEFAULT heaps. Within one command list, activate A, clear/initialize it, copy it out, then activate B with an A-to-B aliasing barrier, clear B and copy it out. Exact endpoint colors (0/1) and exactly representable depth values (0.5/0.25) have fixed expected bits. No previous alias contents are assumed. This tests clear/copy/alias behavior, not rasterized depth testing, stencil or sampled filtering.
|
||||
|
||||
Negative creation checks ask for misaligned and out-of-bounds buffer placements and a texture on a buffer-only heap. An unexpected success fails our rejection gate and is never permission to use that invalid resource; caller-invalid calls do not independently establish a conformance violation. Unsupported creation/CPU-access paths print exact HRESULT and explicit not-run status; exit 0 alone does not mean every configuration worked. Read each outcome.
|
||||
|
||||
MSAA, compressed/planar formats, arrays/3D, texture reinterpretation and console tiling are not covered by these fixtures. The later graphics supplement below has narrower sampling/depth/stencil observations. They remain explicit gaps, and are not inferred from successful copies or clears. In particular, neither a null ppData request nor readback agreement establishes that raw xmem pointers alias texture pixels. DEFAULT versus CUSTOM cases do not identify D3DMetal's internal Metal storage mode or measure its bandwidth.
|
||||
|
||||
The follow-up alias.cpp (run with --suite alias) tests valid buffer data inheritance under the advanced model, with two overlapping buffers and a disjoint guard, three changing GPU-write rounds per session and no raw CPU alias dereference used as a GPU oracle. Exact Map-pointer/GPU-VA relations are recorded as observations. See [findings](findings.md) for the distinction between the passing positive readbacks and failed negative-rejection gate.
|
||||
|
||||
## A-local-2.3 graphics supplement
|
||||
|
||||
The original `render.cpp` adds a graphics pipeline with a shader-resource view, point/clamp sampling and a full-screen triangle. It uses authored Shader Model 5.0 HLSL compiled by the externally installed shader compiler. Per-process HLSL/DXBC bytes and hashes are retained. It does not implement B's compute access, copy-detection or synchronization studies.
|
||||
|
||||
```sh
|
||||
python3 docs/research/d3dmetal-zero-copy/allocation-profiling/run.py --suite render --bottle /absolute/path/to/win64/bottle --scratch /tmp/bx473-render-review
|
||||
python3 docs/research/d3dmetal-zero-copy/gpu-correctness/textures-and-resources/check-render.py /tmp/bx473-render-review --output /tmp/bx473-render-oracle.json
|
||||
```
|
||||
|
||||
The full profile requests two fresh processes with changing endpoint-color palettes. Source textures are 16x16 RGBA8 on CUSTOM WB/L0, CUSTOM WC/L0 and DEFAULT. CPU-visible textures use null-pointer Map plus WriteToSubresource; DEFAULT uses upload/copy. A 32x16 DEFAULT render target is read back after the completed fence and every pixel is compared. One-to-two horizontal scaling with point sampling has fixed quadrant colors; no tolerance or interpolation approximation is used. Additional DEFAULT D32_FLOAT cases clear depth to 0.5, reject z=0.75 and accept z=0.25 under LESS. DEFAULT D24_UNORM_S8_UINT cases clear stencil to zero, increment it with a color-write-disabled triangle, then reject reference 2 and accept reference 1 under EQUAL. Both face states agree. This covers one stencil operation near zero, not saturation edges or every operation.
|
||||
|
||||
Run the separate omitted-draw negative control using the same command with a new scratch directory and `--negative-control`. The guest must exit 1 specifically for a pixel mismatch; the checker expects 512 mismatches against the required sampled image. Packed raw `.rgba` frames enable separate recalculation without importing the C++ pixel routine. The checker rejects empty/stopped profiles. The earlier corrected smoke precedes raw frame capture and cannot be retrospectively checked this way. Results, the initial probe bug and pressure-stopped repeat are preserved in [findings](findings.md).
|
||||
|
||||
Every unsupported creation or pipeline path is a failure with its exact HRESULT, not a skipped success. There is no feature-wide acceptance or inference about UNKNOWN storage's internal representation, sampled mips/filtering, MSAA, other formats or console tiling. Independent source review and critical reproduction remain required.
|
||||
@@ -0,0 +1,127 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Buffer data inheritance under the D3D12 advanced aliasing model; GPU copies
|
||||
// only.
|
||||
#include "../../allocation-profiling/support.h"
|
||||
static void activate(Queue &q, ID3D12Resource *before, ID3D12Resource *after) {
|
||||
D3D12_RESOURCE_BARRIER b{};
|
||||
b.Type = D3D12_RESOURCE_BARRIER_TYPE_ALIASING;
|
||||
b.Aliasing.pResourceBefore = before;
|
||||
b.Aliasing.pResourceAfter = after;
|
||||
q.list->ResourceBarrier(1, &b);
|
||||
}
|
||||
static void stage(const char *name) {
|
||||
std::printf("STAGE %s cpu_ptr=0\n", name);
|
||||
if (std::getchar() == EOF)
|
||||
throw std::runtime_error("handshake");
|
||||
}
|
||||
int main(int argc, char **argv) {
|
||||
setvbuf(stdout, nullptr, _IONBF, 0);
|
||||
try {
|
||||
if (argc != 2)
|
||||
throw std::runtime_error("usage: alias SESSION");
|
||||
UINT session = UINT(std::strtoul(argv[1], nullptr, 10));
|
||||
Context c;
|
||||
stage("baseline");
|
||||
Ref<ID3D12Heap> heap;
|
||||
D3D12_HEAP_DESC hd{};
|
||||
hd.SizeInBytes = 131072;
|
||||
hd.Alignment = 65536;
|
||||
hd.Properties = properties(D3D12_HEAP_TYPE_CUSTOM);
|
||||
hd.Properties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_WRITE_BACK;
|
||||
hd.Properties.MemoryPoolPreference = D3D12_MEMORY_POOL_L0;
|
||||
hd.Flags = D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS;
|
||||
require(c.device->CreateHeap(&hd, __uuidof(ID3D12Heap), heap.out()),
|
||||
"alias heap");
|
||||
Ref<ID3D12Resource> placed[3];
|
||||
auto desc = bufferDesc(65536);
|
||||
for (int i = 0; i < 3; ++i) {
|
||||
UINT64 offset = i == 2 ? 65536 : 0;
|
||||
require(c.device->CreatePlacedResource(
|
||||
heap.p, offset, &desc, D3D12_RESOURCE_STATE_COMMON, nullptr,
|
||||
__uuidof(ID3D12Resource), placed[i].out()),
|
||||
"alias placed buffer");
|
||||
void *pointer = nullptr;
|
||||
require(placed[i]->Map(0, nullptr, &pointer),
|
||||
"alias Map pointer receipt");
|
||||
std::printf(
|
||||
"ALIAS_RESOURCE index=%d heap_offset=%llu cpu_ptr=%p gpu_va=%llu\n",
|
||||
i, offset, pointer, placed[i]->GetGPUVirtualAddress());
|
||||
}
|
||||
Buffer source, guardSource, read;
|
||||
source.allocate(c.device.p, 65536, "upload");
|
||||
source.map();
|
||||
guardSource.allocate(c.device.p, 65536, "upload");
|
||||
guardSource.map();
|
||||
read.allocate(c.device.p, 3 * 65536, "readback");
|
||||
read.map();
|
||||
Queue q(c.device.p);
|
||||
UINT discrepancies = 0;
|
||||
for (UINT round = 0; round < 3; ++round) {
|
||||
UINT salt = 0x13579BDFu + session * 0x10000u + round * 0x101u;
|
||||
auto u = static_cast<volatile uint32_t *>(source.cpu);
|
||||
auto g = static_cast<volatile uint32_t *>(guardSource.cpu);
|
||||
for (UINT i = 0; i < 16384; ++i) {
|
||||
u[i] = i * 1664525u + salt;
|
||||
g[i] = i ^ 0xC1A0BEEFu;
|
||||
}
|
||||
_mm_sfence();
|
||||
std::memset(read.cpu, 0xA7, 3 * 65536);
|
||||
// Alternate which overlapping buffer receives the new full-subresource
|
||||
// GPU write.
|
||||
int from = round % 2, to = 1 - from;
|
||||
q.begin();
|
||||
activate(q, nullptr, placed[from].p);
|
||||
activate(q, nullptr, placed[2].p);
|
||||
q.transition(placed[from].p, D3D12_RESOURCE_STATE_COMMON,
|
||||
D3D12_RESOURCE_STATE_COPY_DEST);
|
||||
q.list->CopyBufferRegion(placed[from].p, 0, source.resource.p, 0, 65536);
|
||||
q.transition(placed[from].p, D3D12_RESOURCE_STATE_COPY_DEST,
|
||||
D3D12_RESOURCE_STATE_COPY_SOURCE);
|
||||
q.list->CopyBufferRegion(read.resource.p, 0, placed[from].p, 0, 65536);
|
||||
q.transition(placed[from].p, D3D12_RESOURCE_STATE_COPY_SOURCE,
|
||||
D3D12_RESOURCE_STATE_COMMON);
|
||||
q.transition(placed[2].p, D3D12_RESOURCE_STATE_COMMON,
|
||||
D3D12_RESOURCE_STATE_COPY_DEST);
|
||||
q.list->CopyBufferRegion(placed[2].p, 0, guardSource.resource.p, 0,
|
||||
65536);
|
||||
q.transition(placed[2].p, D3D12_RESOURCE_STATE_COPY_DEST,
|
||||
D3D12_RESOURCE_STATE_COPY_SOURCE);
|
||||
activate(q, placed[from].p, placed[to].p);
|
||||
q.transition(placed[to].p, D3D12_RESOURCE_STATE_COMMON,
|
||||
D3D12_RESOURCE_STATE_COPY_SOURCE);
|
||||
q.list->CopyBufferRegion(read.resource.p, 65536, placed[to].p, 0, 65536);
|
||||
q.transition(placed[to].p, D3D12_RESOURCE_STATE_COPY_SOURCE,
|
||||
D3D12_RESOURCE_STATE_COMMON);
|
||||
q.list->CopyBufferRegion(read.resource.p, 131072, placed[2].p, 0, 65536);
|
||||
q.transition(placed[2].p, D3D12_RESOURCE_STATE_COPY_SOURCE,
|
||||
D3D12_RESOURCE_STATE_COMMON);
|
||||
q.finish();
|
||||
auto p = static_cast<volatile uint32_t *>(read.cpu);
|
||||
UINT a = 0, b = 0, gmatch = 0;
|
||||
for (UINT i = 0; i < 16384; ++i) {
|
||||
UINT expected = i * 1664525u + salt;
|
||||
a += p[i] == expected;
|
||||
b += p[16384 + i] == expected;
|
||||
gmatch += p[32768 + i] == (i ^ 0xC1A0BEEFu);
|
||||
}
|
||||
std::printf("BUFFER_INHERIT session=%u round=%u from=%d to=%d "
|
||||
"source_matches=%u/16384 inherited_matches=%u/16384 "
|
||||
"disjoint_guard_matches=%u/16384 first_source=%08X "
|
||||
"first_inherited=%08X expected=%08X\n",
|
||||
session, round, from, to, a, b, gmatch, p[0], p[16384], salt);
|
||||
discrepancies += a != 16384 || b != 16384 || gmatch != 16384;
|
||||
}
|
||||
q.begin();
|
||||
q.close();
|
||||
for (auto &p : placed)
|
||||
p->Unmap(0, nullptr);
|
||||
stage("gpu_complete");
|
||||
if (discrepancies)
|
||||
throw std::runtime_error("buffer data inheritance mismatch");
|
||||
std::puts("END success");
|
||||
return 0;
|
||||
} catch (const std::exception &e) {
|
||||
std::printf("END failure reason=%s\n", e.what());
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Check packed GPU readback against explicit endpoint palettes; no C++ expectation code imported."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
|
||||
|
||||
def main():
|
||||
ap=argparse.ArgumentParser(description=__doc__);ap.add_argument('scratch',type=Path);ap.add_argument('--output',required=True,type=Path);args=ap.parse_args()
|
||||
r=json.loads((args.scratch/'receipt.json').read_text());result={'scope':'separate author-written pixel oracle, not independent contributor acceptance','cases':[]}
|
||||
if not r['cases'] or r.get('stop_reason') or r.get('not_run'):
|
||||
raise ValueError('incomplete or stopped run cannot pass the readback oracle')
|
||||
for c in r['cases']:
|
||||
omit=c['args'][0]=='omit';variant=0 if omit else int(c['args'][0])
|
||||
assert c['exit']==(1 if omit else 0) and not c['timed_out']
|
||||
palette=([(255,0,0,255),(0,255,0,255),(255,0,255,255),(0,255,255,255)] if variant%2==0 else [(0,0,255,255),(0,255,0,255),(255,0,255,255),(255,255,0,255)])
|
||||
files=sorted((args.scratch/c['name']).glob('readback_*.rgba'));assert len(files)==(1 if omit else 7)
|
||||
rows=[]
|
||||
for f in files:
|
||||
match=re.fullmatch(r'readback_(wb|wc|default)_m([012])_p([01])\.rgba',f.name);assert match
|
||||
mode,phase=int(match[2]),int(match[3]);visible=mode==0 or phase==1;raw=f.read_bytes();assert len(raw)==32*16*4
|
||||
matched=0
|
||||
for y in range(16):
|
||||
for x in range(32):
|
||||
expected=bytes(palette[(2 if y>=8 else 0)+(1 if x>=16 else 0)]) if visible else bytes(4)
|
||||
matched+=raw[(y*32+x)*4:(y*32+x+1)*4]==expected
|
||||
if omit:assert matched==0,'omitted draw was not detected across all expected pixels'
|
||||
else:assert matched==512,(f,matched)
|
||||
rows.append({'file':f.name,'matched':matched,'pixels':512,'sha256':hashlib.sha256(raw).hexdigest(),'visible_expected':visible})
|
||||
result['cases'].append({'name':c['name'],'negative_control':omit,'frames':rows})
|
||||
args.output.write_text(json.dumps(result,indent=2)+'\n');print('checked',sum(len(c['frames']) for c in result['cases']),'raw GPU readback frames')
|
||||
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,44 @@
|
||||
# Texture, placement and alias observations
|
||||
|
||||
Local author results on Apple M4, CrossOver 26.3.0.39832, Wine engine 11.0-8726-g2e2f5fca349 and loaded D3DMetal 3.0. Two fresh processes used changing input datasets. [Raw matrix records](../../results/2026-11-26-apple-m4-arths17-a22-texture-matrix/receipt.json) include source/PE hashes and backend receipts. Independent review/reproduction remains pending.
|
||||
|
||||
| Configuration | Exact observed data | Scope |
|
||||
| --- | --- | --- |
|
||||
| UNKNOWN RGBA8, 65x37, three mips, disjoint buffer on same heap | WB/WC/DEFAULT each matched 12500/12500 texel bytes and 16384/16384 buffer guard words per session | WB/WC use per-mip CPU subresource writes; DEFAULT uses GPU upload; all use GPU readback |
|
||||
| UNKNOWN R8_UNORM, same dimensions/mips/mixed placement | Each heap type matched 3125/3125 texel bytes and all guards in each session | Padded 256-byte row pitches, no padding treated as pixels |
|
||||
| UNKNOWN R32_UINT, same dimensions/mips/mixed placement | Each heap type matched 12500/12500 texel bytes and all guards in each session | Bit-exact integer texture copies, not sampling |
|
||||
| Overlapping RGBA8 render targets, WB/DEFAULT | Both aliases matched 2405/2405 pixels after distinct endpoint-color clears in each session | Explicit alias barrier and post-activation clear, then copy/readback |
|
||||
| Overlapping D32_FLOAT depth resources, WB/DEFAULT | Both aliases matched 2405/2405 words for exactly representable 0.5/0.25 clears in each session | Depth clear/copy only; no stencil or rasterized depth comparison |
|
||||
| Buffer placement at offset 1 | S_OK in both sessions | Caller-invalid alignment and a one-byte heap-span overrun; never GPU-used |
|
||||
| 64 KiB buffer at offset 65536 in 64 KiB heap | S_OK in both sessions | Caller-invalid bounds; never GPU-used |
|
||||
| Texture on buffer-only heap | E_INVALIDARG in both sessions | Negative creation observed rejected |
|
||||
|
||||
All valid positive cases above matched, but each overall matrix process exited 1 because two negative creation calls unexpectedly succeeded. No failures were removed or reclassified. The first smoke process stopped at the first such acceptance and is [preserved separately](../../results/2026-11-26-apple-m4-arths17-a22-texture-first-failure/receipt.json). The later source logs all negative outcomes before reporting the same failing gate.
|
||||
|
||||
Interpret this carefully: [CreatePlacedResource](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device-createplacedresource) imposes valid offset/alignment/bounds preconditions on callers. It does not promise a specific rejection HRESULT for every invalid call without validation tooling. Therefore these observations show that S_OK is insufficient as an application validation boundary; they do not independently prove a runtime conformance bug or permission to use invalid placements. The unchanged failed negative-rejection gate is explicit in the report.
|
||||
|
||||
## Buffer inheritance follow-up
|
||||
|
||||
The invalid acceptances prompted a separate valid test of whether correct overlapping placements preserve the public buffer-alias contract. [Microsoft's memory-aliasing/data-inheritance documentation](https://learn.microsoft.com/en-us/windows/win32/direct3d12/memory-aliasing-and-data-inheritance) describes inheritance for defined layouts and compatible resource states. This fixture uses the advanced model and explicit A-to-B/B-to-A alias barriers.
|
||||
|
||||
[Two fresh processes](../../results/2026-11-26-apple-m4-arths17-a22-buffer-inheritance/receipt.json) each performed three changing GPU-copy/alias/readback rounds. Two 64 KiB buffers at heap offset 0 returned identical CPU Map pointers and GPU virtual addresses; a disjoint buffer at offset 65536 returned corresponding +65536 addresses. Every source and inherited buffer matched 16384/16384 words in all rounds, and all disjoint guard words matched. No CPU alias dereference is used to manufacture the GPU result. Both processes exited 0.
|
||||
|
||||
This establishes the observed application-level buffer alias behavior for this configuration. It neither identifies physical pages nor supplies arbitrary requested CPU addresses, independent section handles or xmem scatter aliases. B must independently review the advanced-model expectation and barriers before acceptance. The RT/depth fixture reinitializes each alias; it does not test texture data inheritance.
|
||||
|
||||
## Storage choices and untested cases
|
||||
|
||||
CPU-visible and DEFAULT texture paths both produced correct copies/clears in this matrix. No matched bandwidth, sampling/rendering performance, physical texture-footprint comparison or internal Metal storage-mode identification was performed. B's bandwidth/copy/coherence evidence is still required for storage recommendations. A successful buffer map is not a raw pointer to UNKNOWN-layout texels; Map is called with null ppData for CPU texture access.
|
||||
|
||||
The historical valid ROW_MAJOR shared-cross-adapter one-mip control remains in the evidence inventory; no identical repeat was needed here. Ordinary ROW_MAJOR CPU-visible heaps, arbitrary format reinterpretation, compressed/planar formats, arrays/3D, MSAA, general sampled filtering and console tiling remain unsupported by this copy/clear evidence. A separate limited graphics supplement follows. Do not treat not-run configurations as successes or generalize these synthetic readbacks to Xbox workloads.
|
||||
|
||||
## Resumed graphics supplement: smoke observation and incomplete repeat
|
||||
|
||||
The [corrected smoke](../../results/2026-11-26-apple-m4-arths17-a23-render-fixed-smoke/receipt.json) completed one fresh process, exiting 0. WB/WC/DEFAULT source texture sampling each matched 512/512 output pixels; DEFAULT D32 raster depth rejection and pass each matched 512/512; DEFAULT D24S8 stencil rejection and pass each matched 512/512. Shader source and compiled bytes are captured. This is one author-run dataset on the existing M4/runtime, not independent acceptance or a complete repeated matrix.
|
||||
|
||||
The [first attempt](../../results/2026-11-26-apple-m4-arths17-a23-render-lifetime-failure/receipt.json) failed because our probe unloaded the shader compiler while retaining its COM blobs. Inspection placed the exception at a subsequent blob access. It was stopped and retained as an author fixture bug, not a runtime GPU failure. The corrected version declares its compiler owner before blob/root members so the DLL outlives them.
|
||||
|
||||
The subsequent [full-profile attempt](../../results/2026-11-26-apple-m4-arths17-a23-render-pressure-stop/receipt.json) compiled but launched zero guests: kernel pressure reached urgent (2) at the first-case gate. It is a stopped run. Its newer source also captures packed readback frames, which the prior smoke did not capture. Two changing datasets, raw-frame oracle validation and the omitted-draw control are still pending and must not be inferred from that smoke. CPU/GPU work remains paused under urgent pressure and the separate 23 GB ceiling.
|
||||
|
||||
## Reciprocal review clarification
|
||||
|
||||
B's [pinned source/reproduction review](https://github.com/MacosPorters/betterxen/blob/a40228747470f0d184375e451b0173769c90aef5/docs/research/d3dmetal-zero-copy/copy-detection/review-a.md) reproduces the earlier A alias/texture source on M5, including the overall texture exit 1. It also identifies that A's offset-1 case exceeds the 64 KiB heap span by one byte; it does not isolate alignment alone. B's separately authored small-03 adds offset 1 in a 128 KiB heap and still records success. A has inspected that source/raw distinction in [its reciprocal review](../../allocation-profiling/review-b.md); critical B M4 reproduction and new A graphics review remain open.
|
||||
@@ -0,0 +1,425 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Original Workstream A placement/texture fixtures; no production shim is
|
||||
// loaded.
|
||||
#include "../../allocation-profiling/support.h"
|
||||
#include <memory>
|
||||
static void stage(const char *name) {
|
||||
std::printf("STAGE %s cpu_ptr=0\n", name);
|
||||
if (std::getchar() == EOF)
|
||||
throw std::runtime_error("handshake");
|
||||
}
|
||||
static UINT64 alignUp(UINT64 n, UINT64 a) { return (n + a - 1) / a * a; }
|
||||
static D3D12_HEAP_PROPERTIES heapProperties(const std::string &type) {
|
||||
if (type == "default")
|
||||
return properties(D3D12_HEAP_TYPE_DEFAULT);
|
||||
auto p = properties(D3D12_HEAP_TYPE_CUSTOM);
|
||||
p.CPUPageProperty = type == "wc" ? D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE
|
||||
: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK;
|
||||
p.MemoryPoolPreference = D3D12_MEMORY_POOL_L0;
|
||||
return p;
|
||||
}
|
||||
static void activate(Queue &q, ID3D12Resource *after,
|
||||
ID3D12Resource *before = nullptr) {
|
||||
D3D12_RESOURCE_BARRIER b{};
|
||||
b.Type = D3D12_RESOURCE_BARRIER_TYPE_ALIASING;
|
||||
b.Aliasing.pResourceBefore = before;
|
||||
b.Aliasing.pResourceAfter = after;
|
||||
q.list->ResourceBarrier(1, &b);
|
||||
}
|
||||
static D3D12_RESOURCE_DESC textureDesc(DXGI_FORMAT format,
|
||||
D3D12_RESOURCE_FLAGS flags, UINT mips) {
|
||||
D3D12_RESOURCE_DESC d{};
|
||||
d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
|
||||
d.Width = 65;
|
||||
d.Height = 37;
|
||||
d.DepthOrArraySize = 1;
|
||||
d.MipLevels = UINT16(mips);
|
||||
d.Format = format;
|
||||
d.SampleDesc.Count = 1;
|
||||
d.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
|
||||
d.Flags = flags;
|
||||
return d;
|
||||
}
|
||||
static void copyOut(Queue &q, ID3D12Resource *texture, UINT sub,
|
||||
ID3D12Resource *read,
|
||||
const D3D12_PLACED_SUBRESOURCE_FOOTPRINT &fp) {
|
||||
D3D12_TEXTURE_COPY_LOCATION from{}, to{};
|
||||
from.pResource = texture;
|
||||
from.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
|
||||
from.SubresourceIndex = sub;
|
||||
to.pResource = read;
|
||||
to.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
|
||||
to.PlacedFootprint = fp;
|
||||
q.list->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr);
|
||||
}
|
||||
static void copyIn(Queue &q, ID3D12Resource *texture, UINT sub,
|
||||
ID3D12Resource *upload,
|
||||
const D3D12_PLACED_SUBRESOURCE_FOOTPRINT &fp) {
|
||||
D3D12_TEXTURE_COPY_LOCATION from{}, to{};
|
||||
from.pResource = upload;
|
||||
from.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
|
||||
from.PlacedFootprint = fp;
|
||||
to.pResource = texture;
|
||||
to.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
|
||||
to.SubresourceIndex = sub;
|
||||
q.list->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr);
|
||||
}
|
||||
static unsigned char dataset(UINT x, UINT y, UINT sub, UINT channel,
|
||||
UINT round) {
|
||||
return static_cast<unsigned char>(
|
||||
(x * 17 + y * 29 + sub * 71 + channel * 43 + round * 53) ^ 0x96);
|
||||
}
|
||||
static bool supportedFormat(Context &c, DXGI_FORMAT format, bool rt = false,
|
||||
bool depth = false) {
|
||||
D3D12_FEATURE_DATA_FORMAT_SUPPORT f{};
|
||||
f.Format = format;
|
||||
HRESULT hr = c.device->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &f,
|
||||
sizeof(f));
|
||||
std::printf(
|
||||
"FORMAT format=%u HRESULT=0x%08lX support1=0x%08X support2=0x%08X\n",
|
||||
format, (unsigned long)hr, unsigned(f.Support1), unsigned(f.Support2));
|
||||
bool supported =
|
||||
SUCCEEDED(hr) && (f.Support1 & D3D12_FORMAT_SUPPORT1_TEXTURE2D);
|
||||
if (rt)
|
||||
supported = supported && (f.Support1 & D3D12_FORMAT_SUPPORT1_RENDER_TARGET);
|
||||
if (depth)
|
||||
supported = supported && (f.Support1 & D3D12_FORMAT_SUPPORT1_DEPTH_STENCIL);
|
||||
if (!supported)
|
||||
std::puts("OUTCOME unsupported advertised_format_support");
|
||||
return supported;
|
||||
}
|
||||
static void mixed(Context &c, const std::string &type, DXGI_FORMAT format,
|
||||
UINT bpp, UINT round) {
|
||||
if (!supportedFormat(c, format))
|
||||
return;
|
||||
auto d = textureDesc(format, D3D12_RESOURCE_FLAG_NONE, 3);
|
||||
auto ai = c.device->GetResourceAllocationInfo(0, 1, &d);
|
||||
auto bd = bufferDesc(65536);
|
||||
auto bi = c.device->GetResourceAllocationInfo(0, 1, &bd);
|
||||
std::printf("CASE mixed type=%s format=%u mips=3 texture_size=%llu "
|
||||
"texture_alignment=%llu\n",
|
||||
type.c_str(), format, ai.SizeInBytes, ai.Alignment);
|
||||
if (!ai.Alignment || ai.SizeInBytes == ~UINT64(0)) {
|
||||
std::puts("OUTCOME unsupported allocation_info");
|
||||
return;
|
||||
}
|
||||
UINT64 offset = alignUp(bi.SizeInBytes, ai.Alignment);
|
||||
Ref<ID3D12Heap> heap;
|
||||
D3D12_HEAP_DESC hd{};
|
||||
hd.Properties = heapProperties(type);
|
||||
hd.Alignment = std::max(ai.Alignment, bi.Alignment);
|
||||
hd.SizeInBytes = alignUp(offset + ai.SizeInBytes, hd.Alignment);
|
||||
HRESULT hr = c.device->CreateHeap(&hd, __uuidof(ID3D12Heap), heap.out());
|
||||
report(hr, "mixed CreateHeap");
|
||||
if (FAILED(hr)) {
|
||||
std::puts("OUTCOME unsupported heap");
|
||||
return;
|
||||
}
|
||||
Ref<ID3D12Resource> guard, t;
|
||||
require(c.device->CreatePlacedResource(heap.p, 0, &bd,
|
||||
D3D12_RESOURCE_STATE_COMMON, nullptr,
|
||||
__uuidof(ID3D12Resource), guard.out()),
|
||||
"mixed guard");
|
||||
hr = c.device->CreatePlacedResource(heap.p, offset, &d,
|
||||
D3D12_RESOURCE_STATE_COMMON, nullptr,
|
||||
__uuidof(ID3D12Resource), t.out());
|
||||
report(hr, "mixed texture");
|
||||
if (FAILED(hr)) {
|
||||
std::puts("OUTCOME unsupported texture");
|
||||
return;
|
||||
}
|
||||
std::printf("PLACEMENT guard_offset=0 guard_size=%llu texture_offset=%llu "
|
||||
"heap_bytes=%llu disjoint=1\n",
|
||||
bi.SizeInBytes, offset, hd.SizeInBytes);
|
||||
std::array<D3D12_PLACED_SUBRESOURCE_FOOTPRINT, 3> fp{};
|
||||
UINT rows[3]{};
|
||||
UINT64 rowBytes[3]{}, total = 0;
|
||||
c.device->GetCopyableFootprints(&d, 0, 3, 512, fp.data(), rows, rowBytes,
|
||||
&total);
|
||||
if (total == ~UINT64(0))
|
||||
throw std::runtime_error("copy footprints");
|
||||
for (UINT m = 0; m < 3; ++m)
|
||||
total = std::max(total, fp[m].Offset +
|
||||
UINT64(fp[m].Footprint.Height - 1) *
|
||||
fp[m].Footprint.RowPitch +
|
||||
rowBytes[m]);
|
||||
Buffer upload, read, guardUpload, guardRead;
|
||||
upload.allocate(c.device.p, total, "upload");
|
||||
upload.map();
|
||||
read.allocate(c.device.p, total, "readback");
|
||||
read.map();
|
||||
guardUpload.allocate(c.device.p, 65536, "upload");
|
||||
guardUpload.map();
|
||||
guardRead.allocate(c.device.p, 65536, "readback");
|
||||
guardRead.map();
|
||||
std::memset(upload.cpu, 0xDA, total);
|
||||
std::memset(read.cpu, 0xA7, total);
|
||||
auto gu = static_cast<volatile uint32_t *>(guardUpload.cpu);
|
||||
for (UINT i = 0; i < 65536 / 4; ++i)
|
||||
gu[i] = 0xF1A20000u + i + round;
|
||||
std::array<std::vector<unsigned char>, 3> expected;
|
||||
for (UINT m = 0; m < 3; ++m) {
|
||||
UINT width = std::max(1u, 65u >> m), height = std::max(1u, 37u >> m);
|
||||
expected[m].resize(width * height * bpp);
|
||||
if (fp[m].Offset % 512 || fp[m].Footprint.RowPitch % 256 ||
|
||||
rowBytes[m] != width * bpp || rows[m] != height)
|
||||
throw std::runtime_error("unexpected footprint contract");
|
||||
std::printf("FOOTPRINT mip=%u offset=%llu rows=%u row_bytes=%llu "
|
||||
"row_pitch=%u total=%llu\n",
|
||||
m, fp[m].Offset, rows[m], rowBytes[m], fp[m].Footprint.RowPitch,
|
||||
total);
|
||||
for (UINT y = 0; y < height; ++y)
|
||||
for (UINT x = 0; x < width; ++x)
|
||||
for (UINT b = 0; b < bpp; ++b) {
|
||||
auto v = dataset(x, y, m, b, round);
|
||||
expected[m][(y * width + x) * bpp + b] = v;
|
||||
static_cast<unsigned char *>(
|
||||
upload.cpu)[fp[m].Offset + UINT64(y) * fp[m].Footprint.RowPitch +
|
||||
x * bpp + b] = v;
|
||||
}
|
||||
}
|
||||
Queue q(c.device.p);
|
||||
q.begin();
|
||||
activate(q, guard.p);
|
||||
activate(q, t.p);
|
||||
q.transition(guard.p, D3D12_RESOURCE_STATE_COMMON,
|
||||
D3D12_RESOURCE_STATE_COPY_DEST);
|
||||
q.list->CopyBufferRegion(guard.p, 0, guardUpload.resource.p, 0, 65536);
|
||||
q.transition(guard.p, D3D12_RESOURCE_STATE_COPY_DEST,
|
||||
D3D12_RESOURCE_STATE_COMMON);
|
||||
q.finish();
|
||||
if (type != "default") {
|
||||
for (UINT m = 0; m < 3; ++m) {
|
||||
hr = t->Map(m, nullptr, nullptr);
|
||||
report(hr, "mixed Map null pointer");
|
||||
if (FAILED(hr)) {
|
||||
std::puts("OUTCOME unsupported CPU_texture_Map");
|
||||
return;
|
||||
}
|
||||
UINT width = std::max(1u, 65u >> m), height = std::max(1u, 37u >> m);
|
||||
hr = t->WriteToSubresource(m, nullptr, expected[m].data(), width * bpp,
|
||||
width * height * bpp);
|
||||
report(hr, "mixed WriteToSubresource");
|
||||
t->Unmap(m, nullptr);
|
||||
if (FAILED(hr)) {
|
||||
std::puts("OUTCOME unsupported CPU_texture_write");
|
||||
return;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
q.begin();
|
||||
q.transition(t.p, D3D12_RESOURCE_STATE_COMMON,
|
||||
D3D12_RESOURCE_STATE_COPY_DEST);
|
||||
for (UINT m = 0; m < 3; ++m)
|
||||
copyIn(q, t.p, m, upload.resource.p, fp[m]);
|
||||
q.transition(t.p, D3D12_RESOURCE_STATE_COPY_DEST,
|
||||
D3D12_RESOURCE_STATE_COMMON);
|
||||
q.finish();
|
||||
}
|
||||
_mm_sfence();
|
||||
q.begin();
|
||||
q.transition(t.p, D3D12_RESOURCE_STATE_COMMON,
|
||||
D3D12_RESOURCE_STATE_COPY_SOURCE);
|
||||
for (UINT m = 0; m < 3; ++m)
|
||||
copyOut(q, t.p, m, read.resource.p, fp[m]);
|
||||
q.transition(t.p, D3D12_RESOURCE_STATE_COPY_SOURCE,
|
||||
D3D12_RESOURCE_STATE_COMMON);
|
||||
q.transition(guard.p, D3D12_RESOURCE_STATE_COMMON,
|
||||
D3D12_RESOURCE_STATE_COPY_SOURCE);
|
||||
q.list->CopyBufferRegion(guardRead.resource.p, 0, guard.p, 0, 65536);
|
||||
q.transition(guard.p, D3D12_RESOURCE_STATE_COPY_SOURCE,
|
||||
D3D12_RESOURCE_STATE_COMMON);
|
||||
q.finish();
|
||||
UINT64 matches = 0, count = 0;
|
||||
for (UINT m = 0; m < 3; ++m) {
|
||||
UINT width = std::max(1u, 65u >> m), height = std::max(1u, 37u >> m);
|
||||
for (UINT y = 0; y < height; ++y)
|
||||
for (UINT x = 0; x < width * bpp; ++x) {
|
||||
++count;
|
||||
matches +=
|
||||
static_cast<volatile unsigned char *>(
|
||||
read.cpu)[fp[m].Offset + UINT64(y) * fp[m].Footprint.RowPitch +
|
||||
x] == expected[m][y * width * bpp + x];
|
||||
}
|
||||
}
|
||||
UINT guards = 0;
|
||||
for (UINT i = 0; i < 65536 / 4; ++i)
|
||||
guards += static_cast<volatile uint32_t *>(guardRead.cpu)[i] ==
|
||||
0xF1A20000u + i + round;
|
||||
std::printf("OUTCOME mixed type=%s format=%u bytes_match=%llu/%llu "
|
||||
"guard_words=%u/16384\n",
|
||||
type.c_str(), format, matches, count, guards);
|
||||
if (matches != count || guards != 16384)
|
||||
throw std::runtime_error("mixed texture/guard mismatch");
|
||||
}
|
||||
static void clearAlias(Context &c, const std::string &type, bool depth) {
|
||||
auto d =
|
||||
textureDesc(depth ? DXGI_FORMAT_D32_FLOAT : DXGI_FORMAT_R8G8B8A8_UNORM,
|
||||
depth ? D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL
|
||||
: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET,
|
||||
1);
|
||||
if (!supportedFormat(c, d.Format, !depth, depth))
|
||||
return;
|
||||
auto ai = c.device->GetResourceAllocationInfo(0, 1, &d);
|
||||
std::printf("CASE clear_alias type=%s depth=%d size=%llu alignment=%llu\n",
|
||||
type.c_str(), depth, ai.SizeInBytes, ai.Alignment);
|
||||
if (!ai.Alignment || ai.SizeInBytes == ~UINT64(0)) {
|
||||
std::puts("OUTCOME unsupported allocation_info");
|
||||
return;
|
||||
}
|
||||
Ref<ID3D12Heap> heap;
|
||||
D3D12_HEAP_DESC hd{};
|
||||
hd.Properties = heapProperties(type);
|
||||
hd.Alignment = ai.Alignment;
|
||||
hd.SizeInBytes = ai.SizeInBytes;
|
||||
hd.Flags = D3D12_HEAP_FLAG_ALLOW_ONLY_RT_DS_TEXTURES;
|
||||
HRESULT hr = c.device->CreateHeap(&hd, __uuidof(ID3D12Heap), heap.out());
|
||||
report(hr, "clear heap");
|
||||
if (FAILED(hr)) {
|
||||
std::puts("OUTCOME unsupported clear_heap");
|
||||
return;
|
||||
}
|
||||
Ref<ID3D12Resource> textures[2];
|
||||
for (int i = 0; i < 2; ++i) {
|
||||
hr = c.device->CreatePlacedResource(
|
||||
heap.p, 0, &d, D3D12_RESOURCE_STATE_COMMON, nullptr,
|
||||
__uuidof(ID3D12Resource), textures[i].out());
|
||||
report(hr, "clear alias texture");
|
||||
if (FAILED(hr)) {
|
||||
std::puts("OUTCOME unsupported clear_texture");
|
||||
return;
|
||||
}
|
||||
}
|
||||
Ref<ID3D12DescriptorHeap> views;
|
||||
D3D12_DESCRIPTOR_HEAP_DESC vd{};
|
||||
vd.Type =
|
||||
depth ? D3D12_DESCRIPTOR_HEAP_TYPE_DSV : D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
|
||||
vd.NumDescriptors = 2;
|
||||
require(c.device->CreateDescriptorHeap(&vd, __uuidof(ID3D12DescriptorHeap),
|
||||
views.out()),
|
||||
"clear views");
|
||||
auto start = views->GetCPUDescriptorHandleForHeapStart();
|
||||
UINT inc = c.device->GetDescriptorHandleIncrementSize(vd.Type);
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE handles[2] = {{start.ptr}, {start.ptr + inc}};
|
||||
for (int i = 0; i < 2; ++i)
|
||||
if (depth)
|
||||
c.device->CreateDepthStencilView(textures[i].p, nullptr, handles[i]);
|
||||
else
|
||||
c.device->CreateRenderTargetView(textures[i].p, nullptr, handles[i]);
|
||||
D3D12_PLACED_SUBRESOURCE_FOOTPRINT fp{};
|
||||
UINT rows = 0;
|
||||
UINT64 rowBytes = 0, total = 0;
|
||||
c.device->GetCopyableFootprints(&d, 0, 1, 0, &fp, &rows, &rowBytes, &total);
|
||||
Buffer read[2];
|
||||
for (auto &b : read) {
|
||||
b.allocate(c.device.p, total, "readback");
|
||||
b.map();
|
||||
std::memset(b.cpu, 0xA7, total);
|
||||
}
|
||||
Queue q(c.device.p);
|
||||
q.begin();
|
||||
for (int i = 0; i < 2; ++i) {
|
||||
activate(q, textures[i].p, i ? textures[0].p : nullptr);
|
||||
auto state = depth ? D3D12_RESOURCE_STATE_DEPTH_WRITE
|
||||
: D3D12_RESOURCE_STATE_RENDER_TARGET;
|
||||
q.transition(textures[i].p, D3D12_RESOURCE_STATE_COMMON, state);
|
||||
if (depth)
|
||||
q.list->ClearDepthStencilView(handles[i], D3D12_CLEAR_FLAG_DEPTH,
|
||||
i ? 0.25f : 0.5f, 0, 0, nullptr);
|
||||
else {
|
||||
FLOAT color[4] = {i ? 0.0f : 1.0f, i ? 1.0f : 0.0f, 1.0f, 1.0f};
|
||||
q.list->ClearRenderTargetView(handles[i], color, 0, nullptr);
|
||||
}
|
||||
q.transition(textures[i].p, state, D3D12_RESOURCE_STATE_COPY_SOURCE);
|
||||
copyOut(q, textures[i].p, 0, read[i].resource.p, fp);
|
||||
q.transition(textures[i].p, D3D12_RESOURCE_STATE_COPY_SOURCE,
|
||||
D3D12_RESOURCE_STATE_COMMON);
|
||||
}
|
||||
q.finish();
|
||||
for (int i = 0; i < 2; ++i) {
|
||||
UINT expected = depth ? (i ? 0x3E800000u : 0x3F000000u)
|
||||
: (i ? 0xFFFFFF00u : 0xFFFF00FFu);
|
||||
UINT matches = 0;
|
||||
for (UINT y = 0; y < 37; ++y) {
|
||||
auto p = reinterpret_cast<volatile uint32_t *>(
|
||||
static_cast<unsigned char *>(read[i].cpu) + fp.Offset +
|
||||
UINT64(y) * fp.Footprint.RowPitch);
|
||||
for (UINT x = 0; x < 65; ++x)
|
||||
matches += p[x] == expected;
|
||||
}
|
||||
std::printf("OUTCOME clear_alias type=%s depth=%d alias=%d expected=%08X "
|
||||
"matches=%u/2405\n",
|
||||
type.c_str(), depth, i, expected, matches);
|
||||
if (matches != 2405)
|
||||
throw std::runtime_error("clear/alias mismatch");
|
||||
}
|
||||
}
|
||||
static UINT rejectedPlacements(Context &c) {
|
||||
UINT violations = 0;
|
||||
Ref<ID3D12Heap> h;
|
||||
D3D12_HEAP_DESC hd{};
|
||||
hd.Properties = heapProperties("wb");
|
||||
hd.SizeInBytes = 65536;
|
||||
hd.Alignment = 65536;
|
||||
hd.Flags = D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS;
|
||||
require(c.device->CreateHeap(&hd, __uuidof(ID3D12Heap), h.out()),
|
||||
"negative heap");
|
||||
auto b = bufferDesc(65536);
|
||||
for (UINT64 offset : {1ULL, 65536ULL}) {
|
||||
Ref<ID3D12Resource> r;
|
||||
HRESULT hr = c.device->CreatePlacedResource(
|
||||
h.p, offset, &b, D3D12_RESOURCE_STATE_COMMON, nullptr,
|
||||
__uuidof(ID3D12Resource), r.out());
|
||||
std::printf("NEGATIVE placement offset=%llu HRESULT=0x%08lX rejected=%d\n",
|
||||
offset, (unsigned long)hr, FAILED(hr));
|
||||
if (SUCCEEDED(hr))
|
||||
++violations;
|
||||
}
|
||||
auto t = textureDesc(DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE, 1);
|
||||
Ref<ID3D12Resource> r;
|
||||
HRESULT hr = c.device->CreatePlacedResource(
|
||||
h.p, 0, &t, D3D12_RESOURCE_STATE_COMMON, nullptr,
|
||||
__uuidof(ID3D12Resource), r.out());
|
||||
std::printf("NEGATIVE texture_on_buffer_only HRESULT=0x%08lX rejected=%d\n",
|
||||
(unsigned long)hr, FAILED(hr));
|
||||
if (SUCCEEDED(hr))
|
||||
++violations;
|
||||
std::printf("NEGATIVE_SUMMARY unexpected_successes=%u/3\n", violations);
|
||||
return violations;
|
||||
}
|
||||
int main(int argc, char **argv) {
|
||||
setvbuf(stdout, nullptr, _IONBF, 0);
|
||||
try {
|
||||
if (argc != 2)
|
||||
throw std::runtime_error("usage: textures ROUND");
|
||||
UINT round = UINT(std::strtoul(argv[1], nullptr, 10));
|
||||
Context c;
|
||||
identity(c);
|
||||
stage("baseline");
|
||||
D3D12_FEATURE_DATA_D3D12_OPTIONS opts{};
|
||||
require(c.device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &opts,
|
||||
sizeof(opts)),
|
||||
"heap tier");
|
||||
if (opts.ResourceHeapTier < D3D12_RESOURCE_HEAP_TIER_2)
|
||||
std::puts("MIXED NOT_RUN tier_below_2");
|
||||
else
|
||||
for (const std::string type : {"wb", "wc", "default"}) {
|
||||
mixed(c, type, DXGI_FORMAT_R8G8B8A8_UNORM, 4, round);
|
||||
mixed(c, type, DXGI_FORMAT_R8_UNORM, 1, round);
|
||||
mixed(c, type, DXGI_FORMAT_R32_UINT, 4, round);
|
||||
}
|
||||
for (const std::string type : {"wb", "default"}) {
|
||||
clearAlias(c, type, false);
|
||||
clearAlias(c, type, true);
|
||||
}
|
||||
UINT violations = rejectedPlacements(c);
|
||||
stage("resources_released");
|
||||
if (violations)
|
||||
throw std::runtime_error("invalid creations accepted");
|
||||
std::puts("END success");
|
||||
return 0;
|
||||
} catch (const std::exception &e) {
|
||||
std::printf("END failure reason=%s\n", e.what());
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
Loaded 100 of 3695 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user