Merge origin/main into hands/variants-c2a-main (main-into-c2a)
Sixteen conflicted files resolved by the spec's rule: main owns payload ownership, bounds and the Clock seam; C2a owns persistence semantics and exact binding. MintStoredAt is internal static (previous, now); the cache and the store pass their cache's Clock. Package versions are main's. The cultmesh-ts payload-parse acceptance and its test are deleted under retire-schema-alias; peer snapshot reads take the schema's own id, else an id the definition lists as compatible. The held firstRecordAtKey fallback is removed: main's handles take definitions only, so nothing could reach it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
3b83cb6c08
287 changed files with 55077 additions and 1820 deletions
12
.gitattributes
vendored
12
.gitattributes
vendored
|
|
@ -29,3 +29,15 @@ packages/cultmesh-ts/native/**/*.so.* binary
|
|||
# ends in `\r`) while CI, checking out on Linux, stays green.
|
||||
packages/cultmesh-ts/native/SHA256SUMS text eol=lf
|
||||
packages/cultmesh-ts/native/MANIFEST.txt text eol=lf
|
||||
|
||||
# CultMath source keeps CRLF in the working tree on every checkout. The release
|
||||
# gate compares the CultMath.dll it builds with the one org.gamecult.cultmath
|
||||
# tracks, byte for byte, and the bytes follow the checkout's line endings: the
|
||||
# pdb's document checksums feed the DLL's pdb id, timestamp and MVID. The
|
||||
# tracked DLL was built from CRLF source, so CRLF here keeps it valid, and an
|
||||
# LF-configured or Linux clone builds the same bytes as a Windows one. The index
|
||||
# stays LF; only the checkout changes.
|
||||
packages/cultmath/src/** text eol=crlf
|
||||
|
||||
# Stores the Python typed-leaf tests write for the C# reference to open.
|
||||
tests/vectors/**/*.cc binary
|
||||
|
|
|
|||
9
.github/workflows/cultmesh-portability.yml
vendored
9
.github/workflows/cultmesh-portability.yml
vendored
|
|
@ -103,6 +103,15 @@ jobs:
|
|||
# Linux at all, and the browser client's never ran in CI on any OS.
|
||||
# packages/cultnet-ts verifies both vector files; cultmesh-browser proves
|
||||
# the browser client reads the shared rules rather than its own.
|
||||
# No workflow ran cultcache-ts's tests, and its test script listed two files by hand while a third sat compiled
|
||||
# and unrun. The wiring check fails when any TypeScript test file is run by no script, and the cache's own suite
|
||||
# runs here beside the packages built on it.
|
||||
- name: Check that every TypeScript test file is run by its package
|
||||
run: node scripts/check-typescript-tests-wired.mjs
|
||||
|
||||
- name: Verify the CultCache document owner with the TypeScript cache
|
||||
run: npm run test --workspace packages/cultcache-ts
|
||||
|
||||
- name: Verify the CultMesh authority rules with the TypeScript verifier
|
||||
run: npm run test --workspace packages/cultnet-ts
|
||||
|
||||
|
|
|
|||
13
.github/workflows/cultnet-interop.yml
vendored
13
.github/workflows/cultnet-interop.yml
vendored
|
|
@ -12,6 +12,13 @@ jobs:
|
|||
name: C# / TypeScript / Rust / Python / Kotlin
|
||||
runs-on: windows-latest
|
||||
timeout-minutes: 60
|
||||
# Windows runners default to pwsh, which does not stop when a native command fails: a
|
||||
# multi-command step reported only its last command, and a failing cultnet-py suite
|
||||
# went green that way. Git Bash runs as `bash -e -o pipefail`, so every command counts.
|
||||
# Steps that name `shell: pwsh` check $LASTEXITCODE themselves.
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
|
||||
env:
|
||||
DOTNET: dotnet
|
||||
|
|
@ -69,7 +76,11 @@ jobs:
|
|||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = "Stop"
|
||||
$stray = git ls-files '*.schema.json' | Where-Object { $_ -notmatch '^contracts/cultnet/' }
|
||||
# packages/cultnet-rs/contracts/cultnet/ holds R-AB's vendored byte copies (the crate must build
|
||||
# when copied alone). Their drift guard is packages/cultnet-rs/tests/schema_discovery_contracts.rs:74-99.
|
||||
$tracked = git ls-files '*.schema.json'
|
||||
if ($LASTEXITCODE -ne 0) { throw "git ls-files failed" }
|
||||
$stray = $tracked | Where-Object { $_ -notmatch '^(packages/cultnet-rs/)?contracts/cultnet/' }
|
||||
# -I skips binary files: unity/org.gamecult.cultlib/Runtime/Plugins/GameCult.Networking.dll
|
||||
# still embeds the retired namespace until it is rebuilt (REC-032 D4, deferred).
|
||||
$oldNamespace = git grep -I -lE 'GameCult/cultnet-ts/(integration/)?contracts' -- ':!.voidbot'
|
||||
|
|
|
|||
93
.github/workflows/publish-packages.yml
vendored
93
.github/workflows/publish-packages.yml
vendored
|
|
@ -10,8 +10,8 @@ name: Publish packages
|
|||
#
|
||||
# Tag a release to publish, for example `cultcache-ts-v0.13.6` or
|
||||
# `cultnet-py-v0.1.0`. The tag's version must match the version in the package
|
||||
# manifest; the workflow refuses the publish otherwise rather than shipping a
|
||||
# mislabelled artifact.
|
||||
# manifest; scripts/release-after-suite.mjs refuses the release otherwise rather
|
||||
# than shipping a mislabelled artifact.
|
||||
|
||||
on:
|
||||
push:
|
||||
|
|
@ -42,7 +42,7 @@ jobs:
|
|||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 20
|
||||
steps:
|
||||
# fetch-depth: 0 so the semver check below can see every previously
|
||||
# fetch-depth: 0 so the semver check in the release step can see every previously
|
||||
# published tag, not just the one that triggered this run.
|
||||
- name: Check out CultLib
|
||||
uses: actions/checkout@v4
|
||||
|
|
@ -55,42 +55,30 @@ jobs:
|
|||
node-version: 24.x
|
||||
registry-url: https://registry.npmjs.org
|
||||
|
||||
# The release-checks suite, which Publish runs, needs .NET for the API gate.
|
||||
- name: Set up .NET
|
||||
uses: actions/setup-dotnet@v4
|
||||
with:
|
||||
dotnet-version: 10.0.x
|
||||
|
||||
- name: Install workspace dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: Verify the tag matches the manifest version
|
||||
if: startsWith(github.ref, 'refs/tags/cultcache-ts-v')
|
||||
run: |
|
||||
manifest="$(node -p "require('./packages/cultcache-ts/package.json').version")"
|
||||
tagged="${GITHUB_REF_NAME#cultcache-ts-v}"
|
||||
if [ "$manifest" != "$tagged" ]; then
|
||||
echo "tag $GITHUB_REF_NAME does not match manifest version $manifest" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# docs/semver-policy.md: a breaking change under too small a bump, or a
|
||||
# version that skips or reverses the previous release, fails here
|
||||
# instead of shipping with a number that lies.
|
||||
- name: Verify semver policy
|
||||
if: startsWith(github.ref, 'refs/tags/cultcache-ts-v')
|
||||
run: |
|
||||
tagged="${GITHUB_REF_NAME#cultcache-ts-v}"
|
||||
node scripts/check-changelog-semver.mjs \
|
||||
--package "@gamecult/cultcache-ts" \
|
||||
--changelog packages/cultcache-ts/CHANGELOG.md \
|
||||
--version "$tagged" \
|
||||
--tag-prefix cultcache-ts
|
||||
|
||||
# Manual runs publish nothing, so they build and test here. A tag run's
|
||||
# Publish runs these tests itself.
|
||||
- name: Build and test
|
||||
if: ${{ !startsWith(github.ref, 'refs/tags/') }}
|
||||
working-directory: packages/cultcache-ts
|
||||
run: npm test
|
||||
|
||||
# Scoped packages default to restricted even on public npm, and this is
|
||||
# MIT like the rest of the repo, so say public explicitly.
|
||||
# One process checks that the tag is the manifest version, runs the
|
||||
# release-checks suite, the semver policy check (docs/semver-policy.md)
|
||||
# and npm test, and only then runs npm publish --access public. Only
|
||||
# npm publish receives the token. It starts without NODE_OPTIONS, so no
|
||||
# preloaded module runs inside it.
|
||||
- name: Publish
|
||||
if: startsWith(github.ref, 'refs/tags/cultcache-ts-v')
|
||||
working-directory: packages/cultcache-ts
|
||||
run: npm publish --access public
|
||||
run: env -u NODE_OPTIONS node scripts/release-after-suite.mjs npm-publish packages/cultcache-ts "$GITHUB_REF"
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
|
||||
|
|
@ -122,7 +110,7 @@ jobs:
|
|||
echo "run=false" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
# fetch-depth: 0 so the semver check below can see every previously
|
||||
# fetch-depth: 0 so the semver check in the release step can see every previously
|
||||
# published tag, not just the one that triggered this run.
|
||||
- name: Check out CultLib
|
||||
if: steps.selected.outputs.run == 'true'
|
||||
|
|
@ -142,42 +130,27 @@ jobs:
|
|||
with:
|
||||
node-version: 24.x
|
||||
|
||||
- name: Verify the tag matches the manifest version
|
||||
if: steps.selected.outputs.run == 'true' && startsWith(github.ref, 'refs/tags/')
|
||||
run: |
|
||||
manifest="$(python -c "import tomllib,pathlib;print(tomllib.loads(pathlib.Path('packages/${{ matrix.package }}/pyproject.toml').read_text())['project']['version'])")"
|
||||
tagged="${GITHUB_REF_NAME#${{ matrix.package }}-v}"
|
||||
if [ "$manifest" != "$tagged" ]; then
|
||||
echo "tag $GITHUB_REF_NAME does not match manifest version $manifest" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# docs/semver-policy.md: a breaking change under too small a bump, or a
|
||||
# version that skips or reverses the previous release, fails here
|
||||
# instead of shipping with a number that lies.
|
||||
- name: Verify semver policy
|
||||
if: steps.selected.outputs.run == 'true' && startsWith(github.ref, 'refs/tags/')
|
||||
run: |
|
||||
tagged="${GITHUB_REF_NAME#${{ matrix.package }}-v}"
|
||||
node scripts/check-changelog-semver.mjs \
|
||||
--package "${{ matrix.package }}" \
|
||||
--changelog packages/${{ matrix.package }}/CHANGELOG.md \
|
||||
--version "$tagged" \
|
||||
--tag-prefix "${{ matrix.package }}"
|
||||
- name: Set up .NET
|
||||
if: steps.selected.outputs.run == 'true'
|
||||
uses: actions/setup-dotnet@v4
|
||||
with:
|
||||
dotnet-version: 10.0.x
|
||||
|
||||
# Lower layers install from source so a release of one package is tested
|
||||
# against the sibling revision it was cut with, not whatever PyPI has.
|
||||
- name: Install and test
|
||||
- name: Install
|
||||
if: steps.selected.outputs.run == 'true'
|
||||
run: |
|
||||
python -m pip install -e packages/cultcache-py -e packages/cultnet-py -e packages/cultmesh-py
|
||||
python -m unittest discover -s packages/${{ matrix.package }}/tests
|
||||
run: python -m pip install --upgrade build -e packages/cultcache-py -e packages/cultnet-py -e packages/cultmesh-py
|
||||
|
||||
# One process checks, on a tag, that the tag is the manifest version, runs
|
||||
# the release-checks suite, on a tag the semver policy check
|
||||
# (docs/semver-policy.md), and the package's unit tests, and only then
|
||||
# builds the sdist and wheel. Publish uploads only what this step built,
|
||||
# so it has nothing to upload unless every check passed. It starts without
|
||||
# NODE_OPTIONS, so no preloaded module runs inside it.
|
||||
- name: Build sdist and wheel
|
||||
if: steps.selected.outputs.run == 'true'
|
||||
run: |
|
||||
python -m pip install --upgrade build
|
||||
python -m build packages/${{ matrix.package }}
|
||||
run: env -u NODE_OPTIONS node scripts/release-after-suite.mjs python-build packages/${{ matrix.package }} "$GITHUB_REF"
|
||||
|
||||
- name: Publish
|
||||
if: steps.selected.outputs.run == 'true' && startsWith(github.ref, 'refs/tags/')
|
||||
|
|
|
|||
307
docs/cultcache-union-parity-map.md
Normal file
307
docs/cultcache-union-parity-map.md
Normal file
|
|
@ -0,0 +1,307 @@
|
|||
# CultCache Union Parity: Map
|
||||
|
||||
Campaign `cultlib-gaps`, follow-up `cultlib-gaps:follow_up:union-parity-and-unknown-arms` (from
|
||||
`thing2:follow_up:cultcache-union-parity`), under operator ruling `thing2:ruling:contract-decode-tolerance`
|
||||
("CultCache refuses unknown union arms in every runtime, the C# reference included"). This file holds body facts,
|
||||
the model page and rationale; the cut specs and the question are documents in the mind and cite this file by
|
||||
section and fact number.
|
||||
|
||||
Pinned base: `origin/main` at `aaf0d7f6` (2026-10-10). Imagination pass `imagination-cl-union-parity`, session
|
||||
`self-2026-10-10c-eureka`. Probes live under the session scratchpad, `imagination-cl-union-parity/` (`cs` payload
|
||||
probe, `cs2` store probe, `rs` payload probe, `py` store walkers, `il` decompiled MessagePack-CSharp). None of it is
|
||||
committed. Earlier evidence is not repeated here: Eve `docs/thing2-map.md` P12-P13 (the cross-runtime probe) and
|
||||
`docs/research/cultcache-union-decode-tolerance-prior-art.md` (prior art).
|
||||
|
||||
## Cut order
|
||||
|
||||
1. `union-refusal-cs`: the C# reference refuses an unknown union arm on read and a subtype the union does not name
|
||||
on write. Ruled; nothing blocks it.
|
||||
2. `union-golden`: the recursive-union golden and the arm refusal goldens in `tests/vectors/union-parity/`,
|
||||
written by the C# reference and held by its tests.
|
||||
3. `union-derive-rs` and `union-codec-ts`, in either order or together: cultcache-rs and cultcache-ts gain a
|
||||
union (and, in TS, a slot record) codec that writes the reference shape and decodes the golden byte-identically.
|
||||
`union-codec-py` follows the same golden for cultcache-py.
|
||||
4. `slot-tolerance` (C# reference), then `slot-readonly-parity` (Rust, TypeScript, Python): a record carrying a
|
||||
slot past its reader's declared slots, at any depth, is read-only (ruling
|
||||
`cultlib-gaps:ruling:extra-trailing-slots`; the refinement is settled by section S). Both change a slot rule the
|
||||
cuts in step 3 build, so they wait for 1-3 rather than reopening them.
|
||||
5. `union-parity-release`: changelogs and tags, Breaking where `docs/semver-policy.md` says so.
|
||||
|
||||
Thing2's `cut-contract-rs` waits on step 3 (Rust) only: its first step pins cultcache-rs at the commit that lands
|
||||
`union-derive-rs` and re-runs P12 or the `union-golden` vector both ways.
|
||||
|
||||
Why this order: the C# reference is the wire authority, so its refusal and its golden come first and the other
|
||||
runtimes are held to bytes C# wrote, as `document-variants-c1` was (`docs/runtime-parity-scope.md`). Arms are
|
||||
ruled and slots are not, so the slot rule is its own cut rather than a blocked step inside every runtime's cut.
|
||||
|
||||
## Model page (step 0b)
|
||||
|
||||
| Kind | What names it | Over time | Who decides |
|
||||
|---|---|---|---|
|
||||
| Union arm | An integer key, `[Union(k, typeof(Arm))]` on the abstract base (C#), assigned by the union's author. The wire carries `[k, armSlots]`; the arm's type name never travels. `nil` is a null reference, not an arm. | **Added:** a key never used before. **Retired:** the attribute is removed or commented out and the key is never reused (Aetheria `Behaviors.cs:160,173`; Aetheria-legacy `Behaviors.cs:37-38`). **Renamed type:** free, the key is the identity. **Unknown to a reader** (a newer writer's arm, or a retired arm in an old store): refused, naming the union and the key (ruling). | The union's author assigns keys. The C# reference defines the shape; every runtime keeps parity with it (doctrine, `runtime-parity-scope.md`). |
|
||||
| Arm subtype on write | The value's runtime type must be one the union names. | A subtype the union does not name is today written as `nil` (U4). After cut 1 it is refused. | The union's author, by naming the arm. |
|
||||
| Arm slots, record slots | `[Key(n)]` integers, base-class keys included (an arm is a flat array). Gaps are written `nil`. | **Added:** appended at the next free key. **Retired:** kept as a gap, never reused (Aetheria `ItemInstance.cs:35`, `EntitySerializer.cs` key 5). **Missing in an older store:** the reader's default (C# field initializer; Rust and Python need a declared default). **Extra past the reader's last key, at any depth:** the record is read and is read-only; every write or removal of it is refused, and it is persisted from its original bytes (ruling, S). | The type's author. The slot rule is CultCache's (`src/GameCult.Caching/Contracts/cultcache-schema-compatibility.md`). |
|
||||
| Serde-enum member (Rust) | serde's external tag: the variant **name** (`{"Name": fields}`, a unit variant the bare string). | Persisted already by Rust consumers (section C). They keep their bytes: the union derive is opt-in and serde enums are untouched. | The Rust consumer. Not a cross-runtime shape. |
|
||||
|
||||
## U. Mechanism facts (C# reference, Rust, TS)
|
||||
|
||||
- **U1. The miss branch is `Skip` then `null`, in both union formatters MessagePack-CSharp 3.1.7 can hand out.**
|
||||
`DynamicUnionResolver.BuildDeserialize` (decompiled from `MessagePack.dll` 3.1.7 net9.0 with ilspycmd): after
|
||||
`ReadArrayHeader() == 2` (else `InvalidOperationException "Invalid Union data was detected"`) and `ReadInt32`, a
|
||||
non-zero-start key set is mapped through `keyToJumpMap.TryGetValue`, a miss sets the index to `-1`, the `switch`
|
||||
default calls `reader.Skip()`, and the result local stays `null`. The source generator's `UnionTemplate`
|
||||
(`MessagePackAnalyzer` 3.1.7, `MessagePack.SourceGenerator.dll`) emits the same: `default: reader.Skip(); break;`
|
||||
with `result = null`. Its serializer writes `nil` when `typeToKeyAndJumpMap` has no entry for `value.GetType()`.
|
||||
- **U2. The C# reference decodes an unknown arm to null and does not re-encode to its bytes.** Probe `cs`
|
||||
(payload built by hand with `MessagePackWriter`, decoded with `CultDocumentMessagePackSerialization.OptionsFor`):
|
||||
unknown key 9 in a union field gives `Root=NULL`, in a list `Items=[TextNode,NULL]`; re-encode equal: False in
|
||||
both. The formatter the reference composite hands out for the union is `MessagePack.Formatters.NodeFormatter1`
|
||||
(DynamicUnionResolver's emitted type; the probe assembly carries no generated resolver).
|
||||
- **U3. Missing and extra trailing slots, C# payload level.** Same probe: a payload one slot short decodes with
|
||||
the field initializer (`Added=42`); a payload one slot long decodes with the extra slot skipped. Neither
|
||||
re-encodes to its bytes.
|
||||
- **U4. The reference writes an unnamed subtype as nil.** Same probe: `Root = new RogueNode()` (a subclass the
|
||||
union does not list) serializes to `94 a2 64 32 c0 90 2a`: the root slot is `nil`, and it reads back `Root=NULL`.
|
||||
Silent loss on the write side, the mirror of U2.
|
||||
- **U5. Refusal can live at the CultCache layer; no MessagePack-CSharp fork.** Same probe, `strict` options: a
|
||||
resolver placed ahead of `StandardResolver` returns, for any abstract or interface type with `[Union]`s, a
|
||||
formatter that peeks (`CreatePeekReader`) the `[key, ...]` header, throws
|
||||
`MessagePackSerializationException("union Node has no arm 9")` for a key the union does not list, refuses to
|
||||
serialize an unnamed subtype, and otherwise delegates to the formatter `StandardResolver` would have handed out.
|
||||
Baseline round-trips byte-identical; both unknown-arm cases and U4 are refused; slot behaviour is unchanged.
|
||||
Every C# decode path reaches the composite through `CultDocumentMessagePackSerialization.OptionsFor`
|
||||
(`CultCacheMessagePack.CreateCodec`, `DirectoryMessagePackBackingStore.cs:345`, `CultMesh.cs:2779,3493,3499`,
|
||||
`CultMeshPrimitives.cs:1158,1230,2357`), so one resolver covers the cache, the directory store and CultMesh.
|
||||
Consumer resolvers named by `[CultCacheFormatterResolver]` sit ahead of `CultDocumentResolver` today
|
||||
(`CultDocumentMessagePackSerialization.cs:58-62`); the guard goes first and delegates to the rest of the
|
||||
composite, so a consumer formatter still encodes the arm while the key check still runs.
|
||||
- **U6. A top-level extra slot is dropped on write-back.** Probe `cs2`: a C#-written store, mutated as a newer
|
||||
writer would (catalog member slot 2 added, payload slot 2 `"newer writer data"`), is pulled, the record edited
|
||||
and flushed. The read succeeds, and the written payload is `['n1', 'edited by the older build']`: the newer
|
||||
writer's slot is gone. (The schema id was left unchanged, so the migration report said `Kind=Exact`; with a
|
||||
changed id the documented drift path reports `IgnoredExtraSlots`, `CultCache.cs:840-924`, but writes back the
|
||||
same way.)
|
||||
- **U7. Rust at `aaf0d7f6`, before the union cuts.** Probe `rs` (`cultcache-rs` at `aaf0d7f6`, payloads built with `rmpv`, decoded with
|
||||
`rmp_serde::from_slice`): a serde enum's unknown variant is refused (`unknown variant 'Exploded'`); the C# arm
|
||||
shape `[0, [...]]` is refused (`expected variant identifier`); a non-nil value in a gap slot is skipped; a missing
|
||||
trailing slot is refused (`missing field 'added'`) unless the field is `#[cultcache(default)]`; an extra trailing
|
||||
slot is skipped (`cultcache-rs-derive/src/lib.rs`, the `IgnoredAny` loop after the slot loop). The derive
|
||||
accepts named structs only (`lib.rs:51-67`) and writes an empty member list into the catalog
|
||||
(`src/lib.rs:2706`).
|
||||
- **U8. TypeScript at `aaf0d7f6`, before the union cuts.** No typed codec: with no `formatter` a document encodes as a MessagePack **map** of the
|
||||
zod-parsed object and decodes raw (`cult-cache.ts:679-692`; `@msgpack/msgpack` `encode({id:'d',version:7})` is
|
||||
`82 a2 69 64 ...`, a fixmap, where the reference writes an array); positional slots exist only in hand-written
|
||||
formatters (`test/cult-cache.test.ts:1263-1310`). P13 measured that a hand codec matches whichever encoding its
|
||||
author chose.
|
||||
- **U9. Python at `aaf0d7f6`, before the union cuts.** `define_database_entry_type` (`packages/cultcache-py/src/cultcache_py/documents.py:185-276`)
|
||||
is a slot codec: gaps written `nil`, extra slots ignored, a missing slot defaulted or refused. No union codec.
|
||||
- **U10. The written contracts.** `cultcache-schema-compatibility.md:75-91` classifies "persisted slot is missing
|
||||
locally and can be ignored" as soft-migratable drift, reported as `IgnoredExtraSlots`;
|
||||
`cultcache-persistence-format.md:215-218` says a store reader "never skips a slot it does not understand" for
|
||||
record envelope slots, and every runtime refuses `extra-slot-full-payload.msgpack`
|
||||
(`tests/vectors/document-variants-c0`). `docs/persisted-record-encoding.md` says consumers verify canonicality
|
||||
by re-encoding and comparing bytes. The two contracts disagree about payload slots; the question below is
|
||||
about that disagreement.
|
||||
- **U11. Fixture home.** `tests/vectors/<name>/`: committed bytes every runtime's tests read
|
||||
(`document-variants-c0` by Python `generate.py`, `document-variants-c1` written by C#), consumed by
|
||||
`tests/GameCult.Caching.Tests/PreCut2StoreFormatTests.cs`, `packages/cultcache-rs/src/lib.rs`,
|
||||
`packages/cultcache-ts/test/cult-cache.test.ts` and `packages/cultcache-py/tests/test_cultcache.py`. The CultNet
|
||||
precedent for a reference-written vector is `CULTNET_WRITE_VECTORS=1` (`docs/cultnet-error-contract-cut.md:170`).
|
||||
|
||||
## S. Slot read-only probe (any depth)
|
||||
|
||||
Imagination pass `imagination-cl-slot-readonly` (session `self-2026-10-10c-eureka`), under ruling
|
||||
`cultlib-gaps:ruling:extra-trailing-slots` ("b, and probe the any-depth refinement"). Probes live under the session
|
||||
scratchpad, `imagination-cl-slot-readonly/` (`cs` C# synthetic, `aeth` C# on Aetheria's game database, `rs`, `py`,
|
||||
`ts`, `il` decompiled MessagePack-CSharp 3.1.7). None is committed. The ruling's test: every runtime's decoder
|
||||
carries a "slot skipped" mark to the record cheaply, on the one decode path, with no second pass and no per-type
|
||||
consumer code.
|
||||
|
||||
- **S1. Where C# skips, and why a resolver sees it.**
|
||||
`DynamicObjectTypeBuilder.BuildDeserializeInternalDeserializeLoopIntKey` emits the slot loop's `switch` default as
|
||||
a direct `MessagePackReader.Skip()` call; the source generator's `FormatterTemplate` writes
|
||||
`default: reader.Skip(); break;`. `MessagePackReader` is a struct, and neither path raises an event or reads an
|
||||
option, so the skip itself cannot be observed without a fork. Both fetch every member formatter from
|
||||
`options.Resolver` (the generated code's `formatterResolver = options.Resolver`), and the union formatters fetch arm
|
||||
formatters the same way (U1). A resolver ahead of the composite is therefore handed every nested object, list
|
||||
element and union arm, and can read each one's array header before delegating.
|
||||
- **S2. The mark arrives in C#.** Probe `cs`: a guard resolver returns, for each concrete int-keyed
|
||||
`[MessagePackObject]` type, a formatter that reads the array count (from `NextCode` for a fixarray, a peek for
|
||||
array16 and array32), compares it with the highest `[Key]` plus one (base keys included, MessagePack's member
|
||||
visibility rule), notes a skip into a `[ThreadStatic]` scope the decode's caller opened, and delegates to the
|
||||
formatter the rest of the composite hands out. An extra slot at depth 0 (record), depth 1 (nested object), depth 2
|
||||
(object in an object), in a union arm and in a list element each arrives as one mark naming the type and both
|
||||
counts; the clean payload gives none. The guard needs `CompositeResolver.Create` around it so formatters are
|
||||
cached (uncached, it was 40 times slower).
|
||||
- **S3. C# cost.** Aetheria `GameData/Aetheria.cc` (12.1 MB; 237 of 238 records decodable with Aetheria.Shared's
|
||||
types; decoded with `OptionsFor` that assembly; best of 9, three rounds): plain 165-209 ms, a second plain composite
|
||||
(A/A) 174-193 ms, guarded 179-196 ms. That is 3.7-8.9% over the best plain run, inside the A/A spread. Worst case,
|
||||
synthetic tiny objects (120,000 records, 23.1 MB, about 24 objects each): plain 618-637 ms with A/A within 4%,
|
||||
guarded 704-705 ms: 11-19%, about 30 ns per decoded object.
|
||||
- **S4. A live case in Aetheria.** The same probe, run with the AetherDb release binaries (built 2026-09-30) against
|
||||
today's `Aetheria.cc`, marks 25 records: `WeaponItemData` whose `BehaviorData` arms (`AutoWeaponData`,
|
||||
`ChargedWeaponData` and others) carry 34 slots where that build declares 21 or 33. The extra slot is
|
||||
`WeaponData.Tracking` (key 33, Aetheria `8cd71ed6`, 2026-10-07): inside a union arm, inside a list. Today that tool
|
||||
reads these records and drops `Tracking` from all 25 at its next landing (S5). Refusing nested extra slots would
|
||||
stop it opening `Aetheria.cc` at all; read-only lets it open the store and refuses writes to those 25.
|
||||
- **S5. A C# flush re-encodes every held record, not only the edited one.** `PushAll` and an unconditional
|
||||
`CommitBatch` write `ToPersistedRecord(entry, SerializePayload)` for every entry (`CultCache.cs:3191-3201`, `3355`,
|
||||
`3384`), under the local descriptor's schema id and catalog entry. So U6's loss reaches every held record with
|
||||
unread slots at the next flush of anything. Rust (holds payload bytes and decodes on `get`, `lib.rs:2280-2293`),
|
||||
Python (holds envelopes and decodes at load, `cache.py:257-285`) and TypeScript (holds payload bytes) carry an
|
||||
untouched record's bytes. In C#, read-only therefore also means persisted from the original record (bytes, schema
|
||||
id, catalog entry), never from the decoded document.
|
||||
- **S6. Rust.** Probe `rs`: the derive's slot loop, with the trailing `IgnoredAny` loop counting into a
|
||||
`thread_local`, marks depth 1, depth 2 and a list element. Depth 0 is the `DatabaseEntry` derive's own trailing
|
||||
loop (`cultcache-rs-derive/src/lib.rs:258`), the same edit. A plain serde struct nested in a record already refuses
|
||||
an extra element (`array had incorrect length, expected 2`), so only derived slot types skip. Cost (120,000
|
||||
records, 21.4 MB): inside the A/A spread (A/A from -3% to +9%; marked against plain from -14% to +13% over six
|
||||
runs). The added code is one branch per object, never taken on a clean payload. Rust decodes on `get`, so whether
|
||||
a held record is writable is answered by decoding its held bytes through the same derive, on the write path only.
|
||||
- **S7. Python and TypeScript.** Probes `py` and `ts`: a slot codec tree passing a context argument (the shape
|
||||
`union-codec-py` and `union-codec-ts` build) marks all five positions. Python (40,000 records, 11.1 MB, msgpack
|
||||
unpack included): +14% against an A/A spread of 8%. TypeScript (120,000 decoded records, codec walk only; no
|
||||
msgpack in the scratch copy): +20% against an A/A spread of 18%. The check is one length comparison per object.
|
||||
- **S8. Kotlin has no library slot codec.** `CultDocumentCodec<T>.decode` is written per type by the consumer
|
||||
(`packages/cultmesh-kotlin/src/main/kotlin/org/gamecult/cultmesh/CultMesh.kt:31-36`), and the package's own Eve
|
||||
decoders skip extras by hand at 8 sites (`repeat((count - N).coerceAtLeast(0)) { reader.skip() }` in
|
||||
`eve/EveDocuments.kt`). No slot rule, refusal or read-only, can be held by the library there until it owns slot
|
||||
decoding. That is a follow-up, not a per-runtime rule.
|
||||
- **S9. CultMesh decode paths** (`CultMesh.cs:2779,3493,3499`, `CultMeshPrimitives.cs:1158,1230,2357`) go through
|
||||
`OptionsFor`, so through the guard, with no scope open: unchanged. Whether a Mesh replica that re-publishes a
|
||||
decoded document drops slots is a follow-up.
|
||||
- **S10. The refinement is in.** Every runtime with a library slot decoder (C#, Rust, Python, and the TypeScript
|
||||
codec being built) carries the mark to the record on its one decode path, with no second pass and no consumer
|
||||
code. The cost on Aetheria's real store is inside the A/A noise (S3); the worst synthetic case is 11-19% in C#.
|
||||
A nested extra slot makes the record read-only; it is not refused.
|
||||
|
||||
## A. Aetheria (C#, the only consumer persisting `[Union]`s)
|
||||
|
||||
Aetheria consumes the reference through Unity packages pinned by tag (`Packages/manifest.json:55-57`:
|
||||
`caching-unity-v1.4.0`, `cultlib-unity-v1.0.60`), so a CultLib change reaches it only when it bumps the pin.
|
||||
Its only consumer resolver is `MathResolver` (`AssemblyInfo.cs:4`), which supplies no union formatter.
|
||||
|
||||
- **A1. Unions inside persisted documents** (Aetheria `aac2cf91`, `Assets/Scripts/ServerShared`):
|
||||
`BehaviorData` (`Behaviors/Behaviors.cs:147-191`, keys 0-11, 15, 16, 18, 20-24, 28, 31-40; 12 and 26 retired,
|
||||
14, 17, 19, 25, 27, 29, 30 commented out) in `List<BehaviorData> Behaviors` of the item data documents
|
||||
(`ItemData.cs:346,368`); `WeaponData` (`Behaviors/Weapon.cs:15-18`); `EntityPack` (`EntitySerializer.cs:172-173`)
|
||||
in `aetheria.savedzone` contents and its own `Children`; `ItemInstance` and `CraftedItemInstance`
|
||||
(`ItemInstance.cs:18-31`, a union whose arms are also a union) in entity cargo and docking bays
|
||||
(`EntitySerializer.cs:186-187`); `Provenance` (`Provenance.cs:96-98`) in `aetheria.provenanceledger`
|
||||
(`Provenance.cs:11-15`, `Lot.Origin`); `SavedActionBarBinding` (`SavedGame.cs:221-223`) in `aetheria.savedgame`;
|
||||
the input layout rows and keys (`InputLayout.cs:29-50`) in `aetheria.inputlayout`. `Brush`
|
||||
(`Environment.cs:73`) was not traced to a persisted document.
|
||||
- **A2. `GameData/Aetheria.cc` carries no unknown arm.** Walker `py/store_unions.py` over the git-tracked game
|
||||
database (12.7 MB, `cultcache.store.v1`, 238 records, 13 catalog entries): `Behaviors` arm keys
|
||||
{0:3, 1:2, 2:10, 3:5, 4:2, 5:2, 6:3, 8:7, 9:23, 11:2, 16:4, 23:7, 24:5, 31:1, 32:1, 34:1, 35:2, 37:4, 38:10, 39:2,
|
||||
40:1}; none retired or commented out; no `nil` element.
|
||||
- **A3. The run save carries no unknown arm, and does carry missing trailing slots.** Walker `py/run_unions.py`
|
||||
over `GameData/run.cc` (2026-09-30): `EntityPack` arms 0 and 1 (3 each), `ItemInstance` arm 2 (12),
|
||||
`Provenance` arm 0 (64), `SavedActionBarBinding` 9 `nil` (empty bar slots). The `EntityPack` arms carry 21 slots
|
||||
(orbital) and 20 (ship) against today's 22: the `Boss` slot (key 21, added 2026-10-07 in `db4617d8`) is missing,
|
||||
so today's Aetheria reads this save only because a missing trailing slot defaults. `py/gaps.py`: no non-nil
|
||||
retired slot (ItemInstance 2, 9, 10; EntityPack 5). `GameData/stale-2026-09-22/run.cc` is the same shape;
|
||||
`player.cc` holds only `aetheria.playersettings`. `py/slots.py`: every top-level record matches its own store's
|
||||
catalog exactly.
|
||||
- **A4. What changes for Aetheria.** After it adopts a CultLib with cut 1, its current stores load unchanged
|
||||
(A2, A3). A store written later by a build that has added an arm is refused by a build that lacks it, naming the
|
||||
union and key, where today the arm silently becomes `null` (a gear item quietly loses a behaviour, a lot loses
|
||||
its provenance) and the next save writes the loss back. Builds already pinned to 1.0.60 keep the null path; a
|
||||
shipped binary cannot change. Aetheria-legacy does not use CultCache and has no store.
|
||||
- **A5. Other C# stores.** `%LOCALAPPDATA%Low/GameCult/Aetheria/aetheria-unity.cc` (2026-08-08, 1.2 KB) is a
|
||||
`cultcache.store.v2.directory-indexed` header from an older layout, not a union carrier.
|
||||
|
||||
## C. Rust, TypeScript and other consumers
|
||||
|
||||
Eyes audit for this pass (session `self-2026-10-10c-eureka`), `git grep` at each repo's `origin/HEAD`, Rust reach
|
||||
by a lexical script (it can over-count; it does not under-count named fields). Aetheria and CultLib's tests excluded.
|
||||
|
||||
- **C1. Rust: no `DatabaseEntry` record crosses runtimes as a union, and none uses the reference arm shape.**
|
||||
Records that reach serde enums, each keeping its bytes because the derive is opt-in:
|
||||
Huginn `epiphany.pipeline.resolution.v2` (`ResolutionOutcome`, external tag, `eureka-pipeline/src/lib.rs:746`,
|
||||
live on Yggdrasil); Idunn `idunn.deployment_transaction` and `idunn.admitted_generation` (v4 and legacy forms;
|
||||
internally tagged `#[serde(tag = ..., deny_unknown_fields)]` enums in `control_plane.rs`, `deployment_plan.rs`,
|
||||
and two `#[serde(untagged)]` enums kept so older transactions decode, `drivers.rs:259,387`; live at
|
||||
`/var/lib/gamecult/idunn/control.cc`); CodexConnector `gamecult.codex.replay_record.v1` (`CodexReplayState`,
|
||||
`lib.rs:1017`); Epiphany's Atlas, model-request, persona and receipt records (internal, adjacent, external and
|
||||
untagged representations; `.cc` files under `F:\Projects\.epiphany-runtime\` and on Yggdrasil). Unit-only serde
|
||||
enums (a bare string) are widespread in Idunn, Huginn (`Faculty`, the pipeline's unit enums), CodexConnector and
|
||||
Epiphany. No enum reaches any record in Odin, Muninn, Ghostlight, Huginn `mind-body`, or cultnet-rs and
|
||||
cultmesh-rs production records. None of these is read by another runtime as a union today, so none is affected
|
||||
by the arm refusal; the derive changes nothing for them.
|
||||
- **C2. TypeScript: no consumer encodes a tagged union.** The only hand formatters are StreamPixels
|
||||
`apps/service/src/realtime/overlay-state-documents.ts:190,232,277` (positional arrays, no union). Bifrost,
|
||||
Heimdall, Hermodr, Odin scripts, Stonks, Vili, VoidBot (vendored `cultcache-ts`) and weksa have none.
|
||||
- **C3. C# outside Aetheria: StreamPixels' overlay declares unions; its tracked store holds none of them.**
|
||||
`apps/overlay-unity/Assets/Scripts/Assembly-CSharp/` (`8d40541`): `ActivationCondition` (10 arms),
|
||||
`BattleEffect` (2), `StatusEffect` (4), `ItemInstance` (3), `EquippableItemInstance` (2), reachable from
|
||||
`streampixels.status`, `streampixels.action_item`, `streampixels.skill` and gear documents. Walker
|
||||
`py/sp_catalog.py` over `apps/overlay-unity/Data/catalog.cc` (`cultcache.store.v1`, 20 records): only
|
||||
`outfit`, `skin_color`, `hair_style`, `emote` and `hair_color` records, and no `[int, array]` pair at any depth.
|
||||
Its only consumer resolver is `MathResolver` (`Catalog/CatalogAssembly.cs:6`). CultLib's own
|
||||
`GameCult.Networking` `Message` union (`Messages.cs:10`) is a CultNet wire message, decoded with
|
||||
`MessageSerialization.Options` (`MessageSerialization.cs:7`, `DefaultOptions`), outside `OptionsFor`: the arm
|
||||
guard does not reach it (follow-up).
|
||||
- **C4. Python and Kotlin: no union-shaped record.** repixelizer uses `define_database_entry_type` with flat
|
||||
slots; `cultmesh-kotlin` documents are `data class`es with no sealed type.
|
||||
|
||||
So the stores the arm refusal can affect today are Aetheria's (A2-A4, none carrying an unknown arm) and
|
||||
StreamPixels' overlay catalog (C3, carrying no arm). Every other runtime's persisted enums are serde shapes that
|
||||
the opt-in derive leaves alone.
|
||||
|
||||
## D. Payload depth bound (body at `c028c511`)
|
||||
|
||||
One bound, 256 nested MessagePack arrays and maps, on read and on write (ruling
|
||||
`cultlib-gaps:ruling:payload-depth-limit-256`; prior art `docs/research/payload-depth-limit.md`). The C# reference
|
||||
landed in `ead5260c`, Python in `5618d8dd`, Rust in `c028c511`. TypeScript is not landed (spec
|
||||
`cultlib-gaps:cut_spec:cut-union-bounds-ts.r2`, blocked on question `cultlib-gaps:question:ts-payload-opaque-type`).
|
||||
|
||||
| Runtime | Owner of the decision (constant and walker) | Doors routed through it |
|
||||
|---|---|---|
|
||||
| C# | `CultPayloadDepth.Check` (`src/GameCult.Caching.MessagePack/CultPayloadDepth.cs`), limit `CultMessagePackSecurity.MaximumPayloadDepth`. MessagePack's own graph counter is set to the same value as a backstop only. | Write: `CultDocumentMessagePackSerialization.SerializeUntyped`. Read: `DeserializeUntyped`. The cache store (`SerializePayload`/`DeserializePayload`), the directory store, `CultMesh` and single-file documents all call those two; C# has no separate raw-envelope or prepared-batch door. |
|
||||
| Rust | `cultcache_rs::check_payload_depth` and `MAX_PAYLOAD_DEPTH` (`packages/cultcache-rs/src/lib.rs`). | Read: `decode_payload` (get, list, `validate_envelope`/`put_envelope`, `finish_prepared_entry`). Write: `put`/`prepare_entry`/`prepare_entry_named` reach it through `finish_prepared_entry`, which decodes what it just encoded. Raw envelope: `put_raw_envelope`, the door CultMesh network puts use (`cultmesh-rs` `lib.rs`, two call sites). Prepared batch: `put_prepared_batch` via `require_payload_depth`. cultnet-rs: every free-form or skippable wire payload decodes through `cultcache_rs::decode_payload` (message decode in `contracts.rs`, `provider_session`, `media_stream_wire`, `replication`, `service_identity`). |
|
||||
| Python | `_refuse_past_depth_limit` and `MAX_PAYLOAD_DEPTH` (`packages/cultcache-py/src/cultcache_py/documents.py`); a msgpack `StackError` on read maps to the same error. | `DocumentDefinition.encode_payload` (write) and `decode_payload` (read). `CultCache.put`, `put_envelope`, `put_envelopes` and load-time hydration go through them; there is no raw-envelope door. cultmesh-py round trips call the same pair. |
|
||||
|
||||
- **Doors deliberately not routed.** cultnet-rs `idunn_lifecycle_brake`, `provider_health_contracts` and
|
||||
`runtime_authority_contracts` decode records whose positional array length is checked exactly before decoding. A
|
||||
fixed shape has no undeclared slot to skip and no free-form content, so the derive's depth is its shape (commit
|
||||
`84bb1e28`). The five media records have no length check and are held by the test instead. C# `CultCacheMessagePack.CreateCodec`
|
||||
serialises member values and deserialises member types without the document guard, by design (codec comment); only
|
||||
the document type goes through the guard.
|
||||
- **Forbidden writers.** No second walker and no second constant: a runtime's decoders, stores and wire layers call
|
||||
the owner above, never re-count depth or restate 256. An added payload door routes through the owner or names
|
||||
itself in the exact-length list.
|
||||
- **Shared path.** `tests/vectors/union-parity/` (`bounds-outcomes.msgpack`, `depth-*.msgpack`; table in its
|
||||
`README.md`), written by the C# reference and held by `tests/GameCult.Caching.Tests/UnionParityVectorTests.cs` and
|
||||
`PayloadDepthTests.cs`, `packages/cultcache-rs/tests/union_parity.rs`, `packages/cultcache-py/tests/test_union_parity.py`.
|
||||
- **Cut line.** `packages/cultnet-rs/tests/payload_depth.rs` and the `service_identity`/`cultmesh-rs` tests pin the
|
||||
Rust wire doors. cultnet-py and cultmesh-py message and replication decoders call `msgpack.unpackb` directly and
|
||||
are outside the Python cut; they hold only msgpack's own stack limit.
|
||||
- **Verification layer.** Vector held by each runtime's own suite (limit 256 accepted, 257 refused, skipped content
|
||||
counted, non-recursive walk); Rust wire doors by the cultnet-rs test above.
|
||||
|
||||
## Rationale
|
||||
|
||||
- **Why a guard formatter, not a fork or a re-implementation.** U5 shows a guard that only checks the key and the
|
||||
subtype and delegates the encoding is enough. It keeps MessagePack-CSharp's union encoding as the one encoder,
|
||||
costs one small file, and covers every path that already goes through `OptionsFor`. Forking the generated
|
||||
template or vendoring `DynamicUnionResolver` would put a second encoder in CultLib.
|
||||
- **Why the Rust derive is opt-in.** Serde enums already persisted by Rust consumers keep their bytes
|
||||
(`docs/persisted-record-encoding.md`); a changed default would make every such store unreadable or
|
||||
non-canonical. A new derive with explicit arm keys is how a Rust type says "this crosses runtimes".
|
||||
- **Why arms use newtype variants over slot structs.** A C# arm is a subclass whose slots include the base class's
|
||||
keys. A Rust newtype variant over a struct with keyed slots is the same thing, and it needs the slot code the
|
||||
`DatabaseEntry` derive already has, factored so both derives share one slot generator.
|
||||
- **Why the slot rule is a separate, asked cut.** The ruling settles arms and asks for extra trailing slots to be
|
||||
"settled against the same re-encode rule". Two written contracts disagree (U10), and the current behaviour drops
|
||||
data silently (U6), so the choice is the operator's and it should change every runtime at once.
|
||||
- **The recommendation on extra slots was refusal; the ruling chose read-only, and S settles its depth.** An extra trailing slot is the slot-level twin of an unknown
|
||||
arm: data from a newer writer that the reader's types do not describe. The operator ruled refusal for arms
|
||||
knowing it costs an older reader the newer record; the same reasoning gives refusal for slots, and record
|
||||
envelope slots are already refused in every runtime (U10). The alternative with precedent is
|
||||
`variants:ruling:undeclared-read-only` (a record a type can read but does not declare loads read-only): it would
|
||||
let an older reader see a newer record without overwriting it, but only where a catalog shows the extra slot
|
||||
(top level), while most evolution here is nested (A3's `Boss` slot sits inside a union arm).
|
||||
- **Missing trailing slots stay tolerated.** The reader knows a missing slot and its default, so it carries no
|
||||
bytes it does not understand, and Aetheria's live run save depends on it (A3). A store whose guard compares
|
||||
re-encoded bytes (Idunn's) refuses such a record by its own stricter rule, which is that guard's purpose.
|
||||
606
docs/cultlib-gaps-map.md
Normal file
606
docs/cultlib-gaps-map.md
Normal file
|
|
@ -0,0 +1,606 @@
|
|||
# CultLib Gaps: Map
|
||||
|
||||
Campaign `cultlib-gaps` (target: `docs/cultlib-gaps-target.md`). This file holds body facts, probes and
|
||||
rationale for the cuts the mind's `cut_spec`s name; the specs cite it by section and fact number.
|
||||
|
||||
Pinned base: `origin/main` at `6bdc23c9` (2026-10-10). Imagination pass `imagination-cl-gaps-cultmath`, session
|
||||
`self-2026-10-10-ag`. Probes live under the session scratchpad, `imagination-cl-gaps-cultmath/` (`probe1` traced
|
||||
copy of the solver and the warm/cold sweep, `suite` a scratch copy of `packages/cultmath` with the candidate fix,
|
||||
`probe2` the sweep against that copy, `probe3` the overload probe). None of it is committed.
|
||||
|
||||
## Cut order
|
||||
|
||||
1. `bls-release-stop`: BoundedLeastSquares stops on a release only when the release is not real.
|
||||
2. `bls-input-field`: a validation helper names the invalid input (follow-up `bls-invalid-input-field`). Blocked on
|
||||
question `cultlib-gaps:question:bls-input-error-shape`.
|
||||
3. `cultmath-release-0-4-1`: release `org.gamecult.cultmath` with cuts 1 and 2. Version follows question
|
||||
`cultlib-gaps:question:bls-fix-release-lane`.
|
||||
4. `cultmath-rotation-algebra`: quaternion algebra, swing-twist and joint clamps (ruling
|
||||
`aetheria-release:ruling:solver-in-gamecult-animation`). Ships in the CultMath release that the first
|
||||
GameCult.Animation release pins; that release is mapped with GameCult.Animation.
|
||||
5. `py-msgpack-default` revision 4 (section P, "Revision 4"): the fix batch (h4) on `hands/py-msgpack-default`
|
||||
at `a59bbc7d`. `migrate_payloads` is replaced by `convert` (ruling `py-migration-shape-ruled`), and Soul s3's
|
||||
open codec Lows are fixed. Its merge to main waits on the Brokkr cut (follow-up `brokkr-msgpack-payloads-r4`).
|
||||
5a. Not mapped: the Python store takes the cross-process sidecar lock the C# and Rust stores take (follow-up
|
||||
`py-ts-store-cross-process-lock`). It is a store parity cut of its own; `convert` does not need it (P15).
|
||||
6. Not mapped: the C# leaf-vectors revision (`leaf-vectors-next`) gains the P2 map-key rows, so the Python
|
||||
key tests read C#-written bytes instead of literals.
|
||||
7. `decode-stack-safety` (section D): cultcache-rs's one decode door grows its stack at every container level
|
||||
(ruling `decode-stack-mechanism-ruled`). Independent of 5 and 6; thing2's contract-rs merge waits on it.
|
||||
|
||||
## B. BoundedLeastSquares stopping
|
||||
|
||||
Finding `aetheria-release:finding:cut-thrust-allocator-core.s1.solver-converged-early` (Soul, Medium): a cold start
|
||||
reports `Converged` at a non-optimal point, so Aetheria's thrust allocator (tolerance 1e-12) answers differently
|
||||
warm and cold, by up to .078 throttle.
|
||||
|
||||
### Body facts
|
||||
|
||||
- **B1. One runtime ships the solver.** `BoundedLeastSquares` exists only in
|
||||
`packages/cultmath/src/CultMath/BoundedLeastSquares.cs` (C#, netstandard2.1 and net8.0). The type doc says there is
|
||||
no HLSL mirror; grep over `packages/*` finds no Rust, TypeScript, Python or Kotlin sibling, and no other CultLib
|
||||
project calls it. Its consumer outside CultLib is Aetheria's `ThrustAllocator`.
|
||||
- **B2. The defect reproduces against CultMath at base, outside Aetheria.** `probe1` rebuilds Soul's allocator
|
||||
matrix (Soul's `ProbeAllocator2`, constants H=100, Wy=1000, W=.3, kappa=10, rho=.1, EMax=2) for hull
|
||||
`Synthetic(8, 7005)` and the 8th intent of `System.Random(5)`, (-0.8505, 0.6739, 0.5587): 15 rows, 12 columns.
|
||||
Real `BoundedLeastSquares.Solve` at tolerance 1e-12 from x = 0: `Converged`, 13 iterations, cost 36.0313737,
|
||||
x7 = 1. Re-solving from that answer: 1 iteration, cost 36.0312608, x7 = 0.9222145, which is also the warm answer.
|
||||
The same literals (dumped with `"R"` floats, `probe1 dump`) reproduce it at tolerance 1e-9 and 1e-12, and not at
|
||||
the default 1e-6, where the cold solve stops at iteration 10 inside the tolerance and the re-solve takes 0
|
||||
iterations.
|
||||
- **B2a. The W5 problem as literals** (`probe1 dump`, float `"R"` round trip; m = 15, n = 12, row-major; the
|
||||
regression fixture for `bls-release-stop`). Nonzero entries of A:
|
||||
- row 0: a[0,2] = 100f, a[0,8] = -100f, a[0,9] = 100f
|
||||
- row 1: 13.882518f, 20.86695f, 0, 14.8965845f, 12.38046f, 22.115599f, -13.706654f, 15.85789f, 0, 0, -100f, 100f
|
||||
- row 2: -187.72859f, 239.31168f, 158.87828f, -270.31165f, 235.38467f, -14.704258f, 121.61232f, 244.81305f, 0, 0,
|
||||
0, 0
|
||||
- rows 3-6: a[3+k, 8+k] = 0.3f (k = 0..3); rows 7-14: a[7+i, i] = 0.1f (i = 0..7)
|
||||
- b = {0, 67.385445f, 558.70917f, -3f, -3f, -3f, -3f, 0 x 8}; lo = 0; hi = 1f for columns 0-7, 2f for 8-11.
|
||||
At base, tolerance 1e-12 from x = 0: `Converged`, 13 iterations, x[7] = 1, cost 36.031373704487095; a re-solve
|
||||
from that answer: 1 iteration, x[7] = 0.92221445f, cost 36.031260771352414.
|
||||
- **B3. The stopping rule that fires is the progress rule, after a release** (`BoundedLeastSquares.cs:273-278`). A
|
||||
traced copy of the solver, bit-equal to the real one on this problem, shows the last two passes:
|
||||
- iteration 12: full step lands; column 2 sits at its lower bound with gradient -0.00205 (violation 2.05e-3,
|
||||
tolerance 1.5e-7); the solver releases it and records fMark = f.
|
||||
- iteration 13: the re-solve moves x2 from 0 to 2.05e-7. The cost falls by about 2.1e-10, and the stall band
|
||||
`1e-15 * fScale` is 2.11e-10, so `f >= fMark - band` holds and the solver reports `Converged`. Column 7 is then at
|
||||
its upper bound with gradient +0.00145, ten thousand times the tolerance; releasing it is worth 1.1e-4 of cost.
|
||||
- **B4. Why the progress rule cannot judge a release.** Near a minimiser, a cost difference resolves only about the
|
||||
square root of what a gradient comparison resolves: a real step of size dx against gradient g lowers the cost by
|
||||
about g*dx, while the cost itself is a sum of terms of size fScale. Here g*dx (2e-10) sat exactly at the cost's
|
||||
rounding band. The gradient comparison is far from its own rounding: for column 7, the bound on the double
|
||||
gradient's rounding error, `(n+1) * eps * (|A^T b|_7 + sum_k |(A^T A)_7k x_k|)` (Higham's inner-product bound,
|
||||
gamma_(n+1)), is 9.3e-10, and the violation is 1.56e6 times that.
|
||||
- **B5. What the progress rule is for** (commit 43035bc8, and the tests at `BoundedLeastSquaresTests.cs:774-942`).
|
||||
It stops two kinds of pass that can never reach the tolerance: a free-set re-solve whose residual is rounding on a
|
||||
near-singular free set, and a release whose violation is itself rounding (kktTol at or below the noise, including
|
||||
kktTol = 0 when the box point nearest the origin is stationary). Deleting it outright breaks both: with a noise
|
||||
gate on every test and no progress rule, 8 of 66 BLS tests fail (`wide`, `integer-tie`, `collinear`, `cond` spin to
|
||||
the cap; `NearSingularFreeSetsConfirmOnceAndStop` sees 0 confirmations). Exempting releases from the progress rule
|
||||
with no noise gate fails one: `StalledPassesConvergeInsteadOfSpinningToTheCap("plain")` seed 141, b = 0,
|
||||
kktTol = 0, cycles release 3 (violation 1.7e-18) / stationarity miss / block on 3 until the cap.
|
||||
- **B6. The candidate fix, measured.** In a scratch copy of the package (`suite`, diff `suite/clean.diff`, 44 lines):
|
||||
(a) a bound column is a release candidate only if its violation exceeds both kktTol and the rounding bound of B4;
|
||||
(b) the progress rule judges only passes that release nothing; a pass that releases sets fMark to +Inf, so a
|
||||
release is never measured against a cost recorded before it. Results:
|
||||
- all 66 tests in `BoundedLeastSquaresTests` pass, including `DefaultSolvesAreBitIdenticalToTheirGoldenBits` and
|
||||
every stall and noise-floor test; the same holds with the bound's factor at 1, 16 and 256 in place of n+1;
|
||||
- the W5 problem: cold `Converged` in 14 iterations at the warm answer (x7 = 0.92221, cost 36.03126077);
|
||||
- 400 synthetic hulls x 60 random intents (24,000 calls, warm and cold) at tolerance 1e-12: every call `Converged`,
|
||||
max iterations 45, warm and cold agree within 6e-8 on every call (the original: one call off by .078 in the first
|
||||
2,400). At the default tolerance warm and cold still differ, by more than .1 in 10,273 of 24,000 calls: that is
|
||||
the documented resolution of 1e-6 times the gradient scale, pinned by
|
||||
`AnAllocatorShapedProblemIsStartIndependentAtATightTolerance` (spread >= 0.5), and not this cut's subject.
|
||||
- **B7. Released columns the factor drops.** With the fix, 266 releases in the suite land on a column that
|
||||
`SolveFreeSet` marks dependent (p = 0). The next pass is then a stationarity miss with no release, and the
|
||||
progress rule stops it, as before. No release in the suite or the 24,000 allocator calls produced a step that moves
|
||||
the released column outward. A Lawson-Hanson style rejection guard (re-bind the column, try the next candidate)
|
||||
was prototyped and is not needed by any measured case; it is not in the cut.
|
||||
|
||||
### Prior art, and which one the solver follows
|
||||
|
||||
- The solver is a primal active-set method on the normal equations: solve the free set, step to the first bound
|
||||
crossed, release the most violated bound only after a full step lands. That is the outer/inner loop of
|
||||
Lawson-Hanson NNLS (1974) generalised to two-sided bounds, which is the shape of Stark-Parker BVLS (1995) and of
|
||||
scipy's `lsq_linear(method='bvls')`. It differs in factorisation (Cholesky of `A^T A`, not QR of `A`) and in
|
||||
stopping.
|
||||
- Lawson-Hanson stop on the dual test only (netlib `NNLS`, label 350: `IF (WMAX .le. ZERO)`), and guard roundoff
|
||||
per candidate: a column whose new norm is negligible against rounding (`DIFF(UNORM+...)`) or whose new
|
||||
coefficient is not positive (`ZTEST .gt. ZERO`) is rejected with `W(J)=ZERO` and the next candidate tried. There is
|
||||
no cost-based stop.
|
||||
- scipy's BVLS (`scipy/optimize/_lsq/bvls.py`, main) measures KKT exactly as CultMath's status doc states
|
||||
(`g * on_bound` for bound variables, `|g|` for free ones, max over components) and has two stops: optimality below
|
||||
`tol` (status 1) and a relative cost change below `tol` (status 2), reported as different statuses.
|
||||
- CultMath reported its cost stop as `Converged`, which its status doc defines as "the KKT conditions hold". The fix
|
||||
follows Lawson-Hanson: a release is judged on the gradient against its rounding (the role of their `DIFF` test),
|
||||
and the cost stop is kept only where no gradient test can decide (a free-set residual at rounding level), which is
|
||||
where scipy's status 2 also lives.
|
||||
|
||||
### Rejected alternatives
|
||||
|
||||
- Remove the progress rule and stop on the gradient alone: B5, 8 failures.
|
||||
- Report the cost stop as a new status (scipy's status 2): the W5 answer would still be wrong, just labelled, and a
|
||||
new enum member is a breaking change for callers that switch on the status.
|
||||
- Measure progress from the step (the exact model decrease `t(1-t/2)|L^-1 g|^2`) instead of differencing the cost:
|
||||
exact, but a noise-level gradient still yields a tiny positive decrease, so it needs the same noise threshold, on a
|
||||
quantity further from the KKT test than the gradient itself.
|
||||
|
||||
## I. Naming the invalid input
|
||||
|
||||
Follow-up `cultlib-gaps:follow_up:bls-invalid-input-field` (from Soul finding
|
||||
`cut-bls-kkt-tolerance.s1.invalid-input-names-no-field`): every validation failure returns the same `InvalidInput`.
|
||||
|
||||
- **I1.** Validation today is three sites in `Solve`: tolerance (`:147-148`), bounds (`:149-151`), and finiteness of
|
||||
A and b folded into the `A^T b` build (`:153-161`), which cannot tell A from b.
|
||||
- **I2.** Precedent: LAPACK reports a bad argument as `INFO = -i`, naming the argument and never its value. .NET
|
||||
throws `ArgumentException` with a parameter name, which the solver's no-throw, zero-allocation contract rules out.
|
||||
- Recommended shape (question `bls-input-error-shape`, option `validate-helper`): a public
|
||||
`BoundedLeastSquares.Validate(m, n, a, b, lo, hi, kktRelativeTolerance)` returning a new enum
|
||||
`BoundedLeastSquaresInput { Valid, InvalidTolerance, InvalidBounds, NonFiniteMatrix, NonFiniteTarget }`, the first
|
||||
failure in that order. `Solve` calls it and returns `InvalidInput` for anything but `Valid`, so validation has
|
||||
one owner and the folded finiteness check in the `A^T b` loop is deleted. Additive: `InvalidInput` and every
|
||||
existing result stay.
|
||||
|
||||
## R. Release 0.4.1
|
||||
|
||||
- **R1.** `org.gamecult.cultmath` is at 0.4.0 (`package.json:4`, `CultMath.csproj:13`, tag
|
||||
`cultmath-unity-v0.4.0`). `scripts/check-changelog-semver.mjs:97-101`: in 0.y.z a minor bump is the breaking lane;
|
||||
additions and fixes take the patch lane (0.2.4 added `erf` as a patch).
|
||||
- **R2.** Cut 1 changes results only where the old solver stopped after a release whose violation was above both the
|
||||
caller's tolerance and the gradient's rounding, that is, where it reported `Converged` in breach of its status doc.
|
||||
The default path's golden bits are unchanged (B6). The 0.4.0 precedent (ruling `cultmath-0-4-0-breaking-r2`)
|
||||
declared the snoise tie fix Breaking because two valid functions gave different values; here the old value broke
|
||||
the documented contract. Question `bls-fix-release-lane` asks which lane; the recommendation is `fixed-patch`
|
||||
(0.4.1, `### Fixed`).
|
||||
- The release procedure is the 0.4.0 cut's (`cultlib-gaps:cut_spec:cut-cultmath-release.r1`): Windows-only DLL rebuild
|
||||
on Starfire, tests on Yggdrasil, public-surface diff, Unity import smoke, Soul before the tag.
|
||||
|
||||
## Q. Rotation algebra
|
||||
|
||||
Ruling `aetheria-release:ruling:solver-in-gamecult-animation`: CultMath gains quaternion algebra, swing-twist and
|
||||
joint clamps; the aim-chain solve lives in a new package GameCult.Animation. The interface the consumer needs is the
|
||||
Aetheria map's section "The rig's interface to GameCult.Animation and CultMath" (Aetheria `origin/master`
|
||||
`30d02719`, `docs/aetheria-release-map.md:7559-7601`).
|
||||
|
||||
### Body facts
|
||||
|
||||
- **Q1. What exists.** `quaternion` (`src/CultMath/quaternion.cs`, 95 lines): public float fields x, y, z, w;
|
||||
`identity`; `LookRotation(float3 forward, float3 up)`; implicit conversions to and from `float4`; scalar `==`.
|
||||
`math.normalize(quaternion)` (`math.cs:225-235`) returns identity below length 1e-20. No mul, rotate, conjugate,
|
||||
inverse, axis-angle, slerp, swing-twist or clamp exists. `math` is a partial class (`math.cs`,
|
||||
`math.Interval.cs`, `math.Affine.cs`, `math.Phacelle.cs`); `math.rotate(float2, float)` exists (`math.cs:240`).
|
||||
- **Q2. Serialization.** `GameCult.Caching.MessagePack` serialises `quaternion` as the float array [x, y, z, w]
|
||||
(`CultMathResolver.cs:170-171`) and as an xyzw object in JSON (`CultMathJson.cs:468`). No other runtime
|
||||
(`cultcache-rs`, `-ts`, `-py`) has a quaternion type. The cut adds static functions only: no field, layout or
|
||||
formatter changes, so no wire change and no cross-runtime fixture.
|
||||
- **Q3. Runtimes.** The algebra is C#-only, like `LookRotation`: shaders carry rotations as `float4` (the type's doc),
|
||||
the mirror tests map shader functions to C# and never the reverse (`HlslSourceCompatibilityTests.cs:114-117`), and
|
||||
the native core (`native/cultmath-core`) is a Voronoi tone helper. The Unity bridge already converts `quaternion`
|
||||
(`UnityConversions.cs:16,23`); it needs no change.
|
||||
- **Q4. An overload trap, probed.** `quaternion` converts implicitly from `float4`, and CultMath has no
|
||||
`mul(float4, float4)`. `probe3` declares `mul(quaternion, quaternion)` beside scalar and matrix `mul` overloads and
|
||||
calls it with two `float4`: it compiles and returns the quaternion product. HLSL's `mul(vector, vector)` is the
|
||||
inner product, and Unity.Mathematics 1.3.3 (the copy in Aetheria's PackageCache) defines `mul(float4 a, float4 b)`
|
||||
as such (`matrix.gen.cs:129`), so the same call there is a dot product. The cut therefore adds HLSL's vector
|
||||
`mul(float2|3|4, float2|3|4)` (dot) beside the quaternion `mul`, so a `float4` pair keeps its shader meaning.
|
||||
- **Q5. Unity.Mathematics as reference, not template.** Its signatures for `mul`, `rotate`, `conjugate`, `inverse`,
|
||||
`AxisAngle` and `slerp` (`quaternion.cs:99,493,502,630,651,678`) are the consumer's stated convention ("`mul(a, b)`
|
||||
applies `b` first"). CultMath's design rule is to state semantics in code and not copy Unity.Mathematics
|
||||
(`docs/design.md:465-469`), so the formulas are written from the definitions below.
|
||||
|
||||
### Semantics the cut lands
|
||||
|
||||
Quaternions are Hamilton, stored xyzw, unit for rotation; angles are radians, right-handed about the axis.
|
||||
|
||||
- `math.mul(quaternion a, quaternion b)`: the Hamilton product; `rotate(mul(a, b), v) == rotate(a, rotate(b, v))`.
|
||||
- `math.rotate(quaternion q, float3 v)`: `t = 2 cross(q.xyz, v); v + q.w t + cross(q.xyz, t)`; q assumed unit.
|
||||
- `math.conjugate(q)`: (-x, -y, -z, w). `math.inverse(q)`: `conjugate(q) / dot(q, q)`, no guard (zero in, non-finite
|
||||
out, as HLSL division).
|
||||
- `quaternion.AxisAngle(float3 unitAxis, float radians)`: (axis sin(r/2), cos(r/2)); the axis is not normalised.
|
||||
- `math.slerp(a, b, t)`: shortest arc (negate b when `dot(a, b) < 0`); normalised lerp when the quaternions are
|
||||
nearly parallel; t is not clamped.
|
||||
- `math.swing_twist(q, unitTwistAxis, out swing, out twist)`: twist is q's projection onto the axis, normalised
|
||||
(identity when that projection vanishes, a half-turn swing); `swing = mul(q, conjugate(twist))`, so
|
||||
`q == mul(swing, twist)` (twist applied first).
|
||||
- `math.clamp_twist(twist, unitAxis, min, max)`: angle `2 atan2(dot(twist.xyz, axis), twist.w)` wrapped to (-pi, pi];
|
||||
inside [min, max] the input is returned unchanged, otherwise `AxisAngle(axis, clamp(angle, min, max))`.
|
||||
- `math.clamp_hinge(q, unitAxis, min, max)`: `clamp_twist` of q's twist about the axis; the swing is discarded.
|
||||
- `math.clamp_cone(swing, unitAxis, maxAngle)`: the angle between `rotate(swing, axis)` and `axis`; inside the cone
|
||||
the input is returned unchanged, otherwise the rotation by `maxAngle` about `normalize(cross(axis,
|
||||
rotate(swing, axis)))` (at a half turn, where that cross product vanishes, about the swing's own axis).
|
||||
- Preconditions (`min <= max`, unit axes) are documented, not checked, as everywhere in `math`.
|
||||
|
||||
### What GameCult.Animation will need from this cut (not mapped here)
|
||||
|
||||
- From cut 4: `mul`, `rotate`, `AxisAngle` for `AimChain.Pose` and `EffectorDirection`; `conjugate` or `inverse` for
|
||||
frame changes; `swing_twist` and the clamps if its joints ever carry cone or twist limits (the presenter's per-axis
|
||||
boxes do not).
|
||||
- From cut 1: start-independent `BoundedLeastSquares` at a tight tolerance. `AimChainSolver.Solve` is warm-started
|
||||
from `current`; without cut 1 its answer would depend on the previous frame exactly as the allocator's did.
|
||||
- A CultMath release that carries cut 4, which `org.gamecult.animation`'s `package.json` pins. That release is
|
||||
mapped with GameCult.Animation, so one Soul-verified release pair ships both.
|
||||
|
||||
## P. cultcache-py payload format (py-msgpack-default, revisions 2 to 4)
|
||||
|
||||
Imagination pass `imagination-py-msgpack-r2`, session `self-2026-10-12-eureka`, against `hands/py-msgpack-default`
|
||||
at `7f2c7477`. Probes ran from the session scratchpad and were removed afterwards; their results are recorded here (`jobK` ran
|
||||
the C# reference on Yggdrasil at `7f2c7477`; `p1`-`p3` ran Python 3.13.15 with msgpack 1.2.2 on Starfire). Revision 1's facts
|
||||
are in `docs/research/py-msgpack-default/README.md`, and Soul's are in verdict `cut-py-msgpack-default.s1`.
|
||||
|
||||
### Body facts
|
||||
|
||||
P1. **What decides a payload's format at 7f2c7477.** A search of every `packb`, `unpackb`, `json.loads` and
|
||||
`json.dumps` call in cultcache-py, cultnet-py and cultmesh-py found five places:
|
||||
- (a) `PayloadCodec.encode`/`decode`, through `DocumentDefinition.encode_payload`/`decode_payload`.
|
||||
- (b) `_check_payload_tree` (documents.py:75), which holds the map-key rule. `MESSAGEPACK_PAYLOAD_CODEC.encode`
|
||||
does not apply that rule, so a direct call writes `{1: 'a'}` and its own `decode` refuses the bytes.
|
||||
- (c) `stores.py:217`, `_infer_schema_version_from_payload`. A v1 record whose schema id is missing from the
|
||||
catalog is read by unpacking its payload as MessagePack to find a schema stamp.
|
||||
- (d) `replication.py:186`, the same stamp reader copied into cultnet-py behind a lazy `import msgpack`.
|
||||
- (e) `stores.py:257`. A legacy envelope whose payload is an inline map or array is repacked as MessagePack.
|
||||
|
||||
The other JSON sites are wire messages, schema JSON, CLI output and the cultmesh ready file. None of them is a
|
||||
document payload.
|
||||
|
||||
P2. **The C# reference's object slot, map keys** (`jobK`, `NumericLeafVectorTests.AnySlot` under
|
||||
`CultDocumentMessagePackSerialization.OptionsFor`, MessagePack `UntrustedData` security):
|
||||
- Accepted: str, int at every width (negative fixint, u64 max, i64 min), float32, float64, bool, and timestamp
|
||||
ext. The reference rewrites each one at its own width, for example `9181ff01` becomes `9181d0ffcc01`.
|
||||
- Refused: nil (inner `ArgumentNullException`); bin, array and map keys (inner `TypeAccessException`, because
|
||||
UntrustedData has no collision-resistant comparer for them).
|
||||
- Refused as duplicates (inner `ArgumentException`): `{1:1,1:2}`, `{"a":1,"a":2}`, and `{01:1, cc01:2}`, which
|
||||
is the same value written at two widths.
|
||||
- Accepted as two keys: `{1:1, 1.0:2}` and `{1:1, true:2}`. The CLR types differ, so the keys are distinct.
|
||||
- An `object` value of u64 max or i64 min is accepted and rewritten byte-identical.
|
||||
|
||||
P3. **msgpack-python with `strict_map_key=False`** (`p2`, `p3`). Every key kind decodes: nil becomes None, bin
|
||||
becomes bytes, and a timestamp ext becomes `msgpack.Timestamp`. An array or map key raises TypeError
|
||||
(unhashable) without a hook. Duplicates are silently last-wins: `{1:1,1:2}`, `{"a":1,"a":2}`, `{01, cc01}`,
|
||||
`{1, 1.0}` and `{1, true}` each decode to a single key. An `object_pairs_hook` sees every key kind, lists and
|
||||
dicts included. An exception it raises propagates with `__context__` None. On 100k small maps the hook costs
|
||||
2.2x the decode time (0.087 s becomes 0.200 s). `packb` raises an untyped `OverflowError` for 2**64 and
|
||||
-(2**63)-1.
|
||||
|
||||
P4. **Hash flooding with non-str keys** (`p1`). This is msgpack-python's reason for `strict_map_key=True`.
|
||||
Within the 64-bit MessagePack integer range, at most 13 integers share one CPython hash. The full-hash collision
|
||||
attack on int keys therefore needs unbounded integers, and MessagePack cannot carry them. Keys crafted to share
|
||||
low hash bits (`k << 43`) took 0.44 s for 200k keys and 1.34 s for 400k. 200k str keys take 0.25 s. The cost is
|
||||
mildly superlinear, not quadratic. The reference defends itself with UntrustedData's collision-resistant
|
||||
comparers. Python's dict has no such comparer, and the measured bound makes one unnecessary.
|
||||
|
||||
P5. **Schema-stamp recovery.** The C# store deleted its stamp recovery in `a3cc3942` (2026-09-13), so a persisted
|
||||
schema id that is absent from the embedded catalog is refused ("Persisted schema ... is not present in the
|
||||
embedded catalog", `CultCache.cs:504-507`). The C# CultNet registry keeps payload-stamp routing for raw wire
|
||||
records (`CultNetDocumentRegistry.ResolveDescriptorForRawDocument`, `TryResolveDescriptorByPayloadSchema`).
|
||||
cultcache-py's store copy (P1c) is therefore a divergence from the reference. cultnet-py's copy (P1d) mirrors
|
||||
the reference. The TS store (`single-file-messagepack-backing-store.ts:336`) also keeps the store copy.
|
||||
|
||||
P6. **Legacy envelope arrays.** The C# reference does not read them. TS (`normalizePayload`, line 490) and Python
|
||||
both repack an inline payload with MessagePack `encode`. A legacy inline payload is a subtree of a MessagePack
|
||||
document, so it is MessagePack by construction. No JSON-payload writer ever produced one: the 0.3 JSON default
|
||||
wrote bytes, which land as bin.
|
||||
|
||||
P7. **Brokkr** (read-only, `f97d4dc`). The bridge imports cultcache-py from `F:/Projects/CultLib/packages`
|
||||
(`blender_target.py:19`) and defines 8 types with `define_document_type` (630-637). Merging to that checkout's
|
||||
main is therefore the switch itself: Soul s1 measured that the next `_open_node` pull refuses the whole Blender
|
||||
store. The daemon writes JSON into the Blender store and the Unity store with `put_json_document`
|
||||
(`main.rs:1424`, called at 790-1392 and in tests from 2710). It also has `put_messagepack_document` (1435) and
|
||||
reads JSON first, then MessagePack (`decode_payload`, 1447). The daemon is Rust and cannot call cultcache-py.
|
||||
|
||||
### Authority, and why
|
||||
|
||||
- **Payload format.** The definition's `PayloadCodec` owns its bytes: the encoding, and which maps and integers
|
||||
the format can carry. On read, `MESSAGEPACK_PAYLOAD_CODEC` refuses key kinds and duplicates through its
|
||||
`object_pairs_hook`; that is the only place they are visible, because a dict cannot show a collapsed duplicate
|
||||
afterwards. On write, its encode walks the tree first, so a direct `codec.encode` call cannot write bytes
|
||||
its own `decode` refuses (Soul's single path).
|
||||
- **What the definition owns.** `DocumentDefinition.encode_payload`/`decode_payload` own the cross-codec rules
|
||||
(depth 256) and the translation of codec faults into the typed refusals, naming the type. `PayloadCodec.map_keys`
|
||||
is deleted, and `_check_payload_tree` goes back to checking depth only.
|
||||
- **The key rule is P2's.** It is not `strict_map_key`'s. Duplicates are refused as the reference refuses them.
|
||||
- **Residual.** Keys Python holds as one but the reference holds as two (`1` and `1.0`, `1` and `true`) are
|
||||
refused, because a dict cannot hold both. The refusal is typed (`duplicate_map_key`) and pinned so a change is
|
||||
seen. Matching the reference here would need a decoded map type that is not a dict. No consumer is known to
|
||||
write such maps.
|
||||
- **Prior art for refusing duplicates** (from knowledge, not fetched this pass): CBOR's RFC 8949 section 5.6
|
||||
expects decoders to reject duplicate keys; I-JSON (RFC 7493) requires the same of JSON; MessagePack-CSharp's
|
||||
`UntrustedData` refuses duplicates and keys it cannot hash safely (P2). msgpack-python's `strict_map_key` exists
|
||||
for hash flooding, which P4 bounds.
|
||||
- **Integer range.** Beyond 64 bits is a format limit, so the MessagePack codec's write walk refuses it with the
|
||||
code `integer_out_of_range`. The value is never named, and neither is a map key on its path, because in a
|
||||
free-form tree a key is payload data. Entry slots keep their leaf refusals, which name the slot and the field.
|
||||
A bigint was never wire-parity data: MessagePack has no integer wider than 64 bits (P3), and the 0.3 JSON
|
||||
payloads that could hold one were unreadable by the reference (`py-default-payload-json`).
|
||||
- **The stamp readers.** P1c is deleted and its record is refused as the reference refuses it (P5). P1d stays as
|
||||
cultnet-py's raw-record router, mirroring C#. It reads a stamp and decides no format: the resolved definition's
|
||||
codec decodes the payload or refuses it. It loses its lazy import.
|
||||
- **Legacy envelopes.** P1e is demoted and stays (P6). It extracts the MessagePack bytes the inline subtree
|
||||
already is. A definition whose codec is not MessagePack refuses the record like any other foreign record.
|
||||
- **The default codec.** The `DocumentDefinition` field is its only author. `define_document_type`'s parameter
|
||||
defaults to None and forwards only a codec it was given.
|
||||
- **Refusal text.** The JSON remedy sentence is dropped from the read refusal: it was false for every entry
|
||||
definition. Each refusal carries a `code` (`not_one_value`, `map_key_kind`, `duplicate_map_key`,
|
||||
`integer_out_of_range`) and names the kind or the fault class. It is raised after the `except` block, so
|
||||
`__context__` holds no decoder exception and no payload.
|
||||
|
||||
### Migration: what CultLib owns
|
||||
|
||||
Revision 1's README procedure (read under JSON, then put each value) was per record and not atomic. Soul s1
|
||||
stranded a store with it. Revision 2 replaces the procedure with
|
||||
`migrate_payloads(store, definitions, *, source_codec=JSON_PAYLOAD_CODEC) -> int` in cultcache-py:
|
||||
|
||||
1. It pulls every envelope from the store.
|
||||
2. For each record whose type is among `definitions`, it decodes under that definition with `source_codec` and
|
||||
encodes under the definition itself. That is the whole definition path, validation and every refusal included.
|
||||
3. Any refusal stops the migration before the store is touched. The error names the type, the record key and
|
||||
the refusal's code, never the value.
|
||||
4. Otherwise one `push_all` writes the store whole. `SingleFileMessagePackBackingStore` and
|
||||
`JsonLinesBackingStore` each do that as a temp file and a rename.
|
||||
5. Records of other types keep their bytes and `stored_at`. The return value is the count rewritten.
|
||||
|
||||
It never sniffs, and it cannot leave a store half-migrated. Revision 2 also claimed that a second run is refused;
|
||||
Soul s2 falsified that (P10), and a concurrent writer strands the store (P11). Revision 3 replaced this shape with a
|
||||
backup-and-swap (P12), which Soul s3 broke three more ways. Revision 4 deletes the in-place migration: CultLib owns
|
||||
only `convert`, which writes a new file and never writes its source (P14).
|
||||
|
||||
Rejected alternatives:
|
||||
- A sniffing reader that accepts both formats: P1's one-digit payloads are valid in both formats, and r1's map
|
||||
forbade readers that try one format and then another.
|
||||
- A consumer-run loop over `put`: that is the procedure that stranded the store.
|
||||
|
||||
### Brokkr landing contract (follow-up `brokkr-msgpack-payloads-r4`)
|
||||
|
||||
The merge of `hands/py-msgpack-default` to main waits on three things:
|
||||
1. Soul holds on the fix batch.
|
||||
2. A Brokkr branch, Soul-held, is ready in its own campaign. On it, the daemon writes MessagePack
|
||||
(`put_messagepack_document`) into both stores. The JSON-first read becomes a read of exactly one MessagePack
|
||||
value with a trailing-bytes check, and the bridge's 8 definitions are unchanged. The Blender store is converted
|
||||
by `cultcache_py.convert` over those 8 definitions into a new file beside it, because those payloads came from
|
||||
cultcache-py's old default (P14). The daemon-written JSON receipts in the Unity store are the daemon's own, and
|
||||
it rewrites them, also into a new file.
|
||||
3. An operator window: close Blender and stop sync, Self merges CultLib and Brokkr together, build the daemon,
|
||||
run both conversions, open each new file, swap it into place, then restart. The JSON originals are kept under
|
||||
another name for as long as the operator wants them.
|
||||
|
||||
### Revision 3
|
||||
|
||||
Imagination pass `imagination-py-msgpack-r3`, session `self-2026-10-12-eureka`, against `hands/py-msgpack-default`
|
||||
at `57f85acd`. Python probes ran on Starfire (Python 3.13, msgpack 1.2.2) over a `git archive` of the cultcache-py
|
||||
and cultnet-py sources at that head, and were removed afterwards. The C# facts are Soul s2's (`jobB`, Yggdrasil),
|
||||
not rerun here.
|
||||
|
||||
P8. **What still decides map keys at 57f85acd.** One search found three MessagePack readers that see document
|
||||
payload maps. (a) The codec's `_unpack_tree` applies the reference rule through `_checked_map`. (b) The store's
|
||||
whole-file `msgpack.unpackb(data, raw=False)` (`stores.py:98`) applies msgpack's `strict_map_key=True`. A legacy
|
||||
envelope file whose inline payload is `{1: 'a'}` is refused with "int is not allowed for map key". Read through
|
||||
`_unpack_tree` instead, the same file yields the payload `8101a161`, and a v1 snapshot's framing decodes
|
||||
identically either way. (c) cultnet-py's stamp router (`replication.py:192`) applies `strict_map_key=True`. Read
|
||||
through the codec, `['x.v1', {1: 'a'}]` and `{'schemaVersion': 'x.v1', 'v': {1: 'a'}}` both route to `x.v1` (C#
|
||||
routes both, Soul s2 STAMPPROBE). A nil-keyed payload gives `None`, as it does today and in C#. Every other
|
||||
`unpackb` in cultnet-py and cultmesh-py reads wire messages, cursor files or fixed-slot protocol records, whose
|
||||
maps are frames rather than payload data. Their bound is follow-up `py-wire-decoders-unbounded`. Unmeasured: C#
|
||||
reads a map stamp as `IReadOnlyDictionary<string, object>`, so a top-level non-str key may stop C# routing where
|
||||
Python routes. The resolved definition decides the record either way.
|
||||
|
||||
P9. **The two depth counters.** `_check_writable` (documents.py:184) counts every node, scalars included, to
|
||||
`_PACK_DEPTH_LIMIT = 511`. `_check_payload_tree` counts containers to 256. Commit `eef1cb15` moved the codec
|
||||
from 256 to 511 so that `test_union_parity.py:650` could build its 257-deep read fixture with
|
||||
`document.payload_codec.encode(past)`. The fixture needs bytes that are 257 deep, not a codec that writes them:
|
||||
`msgpack.packb(past, use_bin_type=True)` and `json.dumps(past).encode()` build them, and both writers nest to 511
|
||||
or further. One container walk, bounded at `MAX_PAYLOAD_DEPTH`, serves both the definition and the codec. It also
|
||||
ends a cycle, because a cycle reaches 257.
|
||||
|
||||
P10. **Rerun.** No byte in a CultCache store records a payload format, and no wire change is wanted for one. A
|
||||
migration that rewrites the live store in place therefore cannot tell its own output from its input when a
|
||||
payload is valid in both formats. `b'5'` is the JSON 5 or the MessagePack 53, and Soul s2 saw 53 become 5. No
|
||||
check on the payload content can separate the two, so the rerun guard has to come from outside the payload.
|
||||
|
||||
P11. **Concurrency in the store.** cultcache-py's file stores hold a per-object `threading.RLock` only, so every
|
||||
`push` is a read-modify-write that loses another process's write. The C# store opens a `.lock` sidecar with
|
||||
`FileShare.None` (`CultCache.cs:3489-3509`), and cultcache-rs takes an `fs2` lock on its sidecar (`lib.rs:853-859`).
|
||||
cultcache-ts has none (a search of `packages/cultcache-ts/src` finds no lock). The migration race is one case of a
|
||||
store that lacks the reference's lock.
|
||||
|
||||
P12. **Prior art and the shape chosen** (primary docs fetched 2026-10-12). SQLite `VACUUM INTO`: "the original
|
||||
database file is unchanged", and the target "must not previously exist, or else it must be an empty file". LMDB
|
||||
`mdb_env_copy`: the target directory "must already exist and be writable but must otherwise be empty". Realm is
|
||||
the counter-example to Self's hypothesis. It migrates in place on open, and a rerun is safe because the file
|
||||
records its schema version, which CultCache's payload format does not (P10). The chosen shape follows `VACUUM
|
||||
INTO`, with the destination role taken by a mandatory backup:
|
||||
|
||||
`migrate_payloads(store, definitions, *, backup, source_codec=JSON_PAYLOAD_CODEC) -> int`
|
||||
|
||||
1. Copy the live store's bytes to `backup` with exclusive create (`open(backup, "xb")`). If the backup exists,
|
||||
the call is refused before anything is read. Every rerun is refused this way, whatever the payloads hold.
|
||||
2. Read the records from the backup, the frozen copy, and rewrite the listed ones. Any refusal of any exception
|
||||
class raises `CultCacheError` naming the type, the record key and the code or class.
|
||||
3. Compare the live bytes with the copied bytes. A difference means a writer ran during the migration, and the
|
||||
call refuses and says to stop every writer.
|
||||
4. Replace the live file in one `_replace_all` (temp file and rename).
|
||||
5. On any failure after step 1, the backup is removed and the live store is unchanged. A count of zero also
|
||||
removes it.
|
||||
|
||||
Probe (`probe2`, this shape over the 57f85acd sources). The first run over `b'53'`, `b'5'` and an unlisted type
|
||||
gives 53 and 5, keeps the unlisted bytes, and keeps the JSON in the backup. A second identical call raises
|
||||
`FileExistsError` and leaves the live bytes unchanged. A push between the read and the swap (the s2 interleave)
|
||||
is refused, with the backup removed and the live store holding the writer's JSON record. A validate that raises
|
||||
`AssertionError` is named by class and the backup is removed.
|
||||
|
||||
What remains and is stated: the window between the compare and the rename, closed by the lock in `5a`. The
|
||||
precondition is to stop every writer, as it is for SQLite's offline tools. If someone deletes the backup and then
|
||||
reruns the migration on its own output, P10 recurs. The README says to delete the backup only after the
|
||||
migrated store has been opened, and never to rerun after that.
|
||||
|
||||
P13. **Float32 keys.** `Float32(0.1).value` is `0.1`, so a `Float32` key is not rounded until it is packed.
|
||||
Decoded, it is the float32-rounded value. Writing `{1, F32(1.0)}`, `{True, F32(1.0)}`, `{1.5, F32(1.5)}` or
|
||||
`{0, F32(-0.0)}` produces bytes that the codec's own decode refuses as `duplicate_map_key`. `{0.1, F32(0.1)}` and
|
||||
two NaN keys read back as two keys. The rule that matches decode exactly compares each key's decoded image (a
|
||||
`Float32` key's image is `struct.unpack('>f', struct.pack('>f', v))[0]`) and refuses a collision on write as
|
||||
`duplicate_map_key`. The reference reads all four collision maps as two keys (Soul s2 KEYPROBE). Python cannot,
|
||||
for the same reason it cannot read `{1, 1.0}`, which is the residual already recorded. Refusing on write keeps
|
||||
Python inside what it can read back, and it is the write half of that residual.
|
||||
|
||||
### Revision 4
|
||||
|
||||
Imagination pass `imagination-py-msgpack-r4`, session `self-2026-10-14-eureka`, against `hands/py-msgpack-default`
|
||||
at `a59bbc7d`, under ruling `py-migration-shape-ruled` (convert-to-new-file). Source reads only; nothing was run.
|
||||
|
||||
P14. **The shape ruled.** `convert(source, destination, definitions, *, source_codec=JSON_PAYLOAD_CODEC) -> int`
|
||||
replaces `migrate_payloads`. It creates `destination` with exclusive create (`open(path, "xb")`) before it reads
|
||||
anything, so an existing file (the source itself, an earlier output, anything) is refused and left alone. It reads
|
||||
the source once through the source store's `pull_all`, rewrites the listed records in memory, writes the store
|
||||
bytes into the file it created, and fsyncs it. Any failure after the create removes that file. It never opens the
|
||||
source for writing. The destination is the same store kind as the source, and its bytes come from the same
|
||||
per-kind encoder `_replace_all` uses, so the two writers cannot drift. The caller stops writers, converts, opens
|
||||
the new file and swaps it in. This follows SQLite `VACUUM INTO` and LMDB `mdb_env_copy` (P12) without the backup
|
||||
role that r3 added to them.
|
||||
|
||||
P15. **What the shape makes impossible, and what stays.** The library no longer writes a live store during a
|
||||
format change. That leaves no code to fix for s2's `migrate-races-concurrent-writer` or s3's
|
||||
`inflight-writer-strands-migration`, `rerun-guard-is-per-backup-path` and `stopped-migration-has-no-recovery`,
|
||||
because the backup, the compare and the swap are deleted. The library does not lose a write made during
|
||||
`convert`. The write lands in the source, and only the caller's swap can drop it. The README makes stopping
|
||||
writers the caller's precondition, as SQLite's offline tools do. A killed run leaves the source intact and possibly
|
||||
a partial destination; recovery is to delete the destination and run again. A partial JSON Lines destination can
|
||||
parse as a smaller store, so the README says the destination is complete only once `convert` has returned.
|
||||
Converting a store that is already MessagePack can still produce wrong values in the destination (P10: `b'5'`),
|
||||
but the source is untouched. The cross-process store lock (follow-up `py-ts-store-cross-process-lock`) is still a
|
||||
store parity gap, but nothing in this cut waits on it.
|
||||
|
||||
P16. **The codec decodes only what it writes.** At `a59bbc7d`, `MESSAGEPACK_PAYLOAD_CODEC.decode` is `_unpack_tree`
|
||||
alone. It returns trees 257 or more deep, `ExtType` values, and timestamps outside .NET `DateTime` (Soul s3); the
|
||||
definition or the reference refuses every one of them. Revision 4 also runs the write check over the decoded tree
|
||||
(`_check_carried`, renamed from `_check_writable`). That gives one rule in both directions. The depth walk, the
|
||||
integer range and the key kinds apply as before. No `ExtType` node is carried (code `value_kind`, kind `ext`).
|
||||
A timestamp's seconds must lie within `-62135596800..253402300799` (code `timestamp_out_of_range`). That interval
|
||||
is `DateTime.MinValue` to `DateTime.MaxValue`. It is derived from MessagePack-CSharp's timestamp reader, which adds
|
||||
the seconds to the Unix epoch and then the nanoseconds as ticks. It was not measured at the seam here, and a
|
||||
C#-written seam row belongs to follow-up `leaf-vectors-next`. The store's whole-file read keeps `_unpack_tree`
|
||||
alone, because a store frame is not a payload. The `any` leaf keeps its own ext refusal, which is the slot's rule
|
||||
for a value handed to it directly.
|
||||
|
||||
P17. **NaN keys.** The reference holds a map's keys in a `Dictionary` keyed by CLR type and value, where a NaN
|
||||
equals a NaN of the same width. It therefore refuses two float64 NaN keys and accepts a float64 NaN beside a
|
||||
float32 NaN (Soul s3). Python reads both widths as one `float` and cannot tell them apart. Revision 4 gives
|
||||
`_key_image` one NaN image, used by `_checked_map` on read and by `_check_carried` on write. Any two NaN keys are
|
||||
refused both ways as `duplicate_map_key`. On the mixed-width pair this refuses something the reference accepts,
|
||||
the same kind of residual as `1` beside `1.0`. The other choice would read two float64 NaN keys that the
|
||||
reference refuses.
|
||||
|
||||
Revision 5 records this as a deliberate exception to ruling `leaf-acceptance-follows-reference`, because Python
|
||||
cannot tell the two widths apart (msgpack-python decodes both to one `float`) and no ruling lets the codec read a
|
||||
pair the reference refuses. Soul s4 probed the C# behaviour: `Dictionary<object,object>{float.NaN, double.NaN}`
|
||||
serialises as `82 ca ffc00000 01 cb fff8000000000000 02`, the reference reads it back as two keys, and cultcache-py
|
||||
refuses it on read as `duplicate_map_key` (base `a59bbc7d` accepted that read). Every same-width NaN pair, with
|
||||
equal or different payload bits and with +NaN beside -NaN, is refused by both runtimes. The exception lives where a
|
||||
consumer reads it: the cultcache-py README's Wire Parity section, pinned by a test vector (the bytes above).
|
||||
|
||||
## D. cultcache-rs decode stack safety (cut `decode-stack-safety`)
|
||||
|
||||
Pinned base: `origin/main` at `ae6ef5a8` (2026-10-14). Imagination pass `imagination-decode-stack`, session
|
||||
`self-2026-10-14-eureka`. Ruling `decode-stack-mechanism-ruled` (grow-stack); prior art
|
||||
`docs/research/decode-stack-safety.md`. Probes live under the session scratchpad, `imagination-decode-stack/`:
|
||||
`probe` decodes through a scratch copy of cultcache-rs at the base whose derive calls a hook per derived level
|
||||
(off, observe the stack used between levels, or `stacker::maybe_grow`), against Eve's `thing-contract` at
|
||||
`2467e1b`; `wasmprobe` is the wasm run. Yggdrasil rust image (rustc 1.95.0, rmp-serde 1.3.1, serde_stacker
|
||||
0.1.14, stacker 0.1.25, psm 0.1.32), jobs `job1` to `job5`. None of it is committed.
|
||||
|
||||
Shapes: `box` is a thing-contract Box chain (3 containers a level, the bound admits 83), `repeat` a Repeat chain
|
||||
(2 a level, admits 125), `fat` a 32-slot record of `[u64; 32]` with an `Option<Box<Self>>` slot (1 a level,
|
||||
admits 255, so the leaf arrays sit at depth 256), `json` a one-slot record holding a `serde_json::Value` nested
|
||||
255 arrays, `ignored` a one-slot record whose extra trailing slot nests 255 arrays (skipped as `IgnoredAny`).
|
||||
|
||||
### Body facts
|
||||
|
||||
D1. **Today's abort, reproduced.** `decode_payload` at the bound, first level that aborts (process abort, no
|
||||
exit code, every time):
|
||||
|
||||
| Profile, thread | box (83) | repeat (125) | fat (255) | json, 64 KiB | ignored, 32 KiB |
|
||||
|---|---|---|---|---|---|
|
||||
| release, 1 MiB | 44 | 56 | 13 | 115 | 24 |
|
||||
| release, 2 MiB | ok | 114 | 25 | | |
|
||||
| debug, 1 MiB | 11 | 14 | 5 | 15 | 8 |
|
||||
| debug, 2 MiB | 23 | 30 | 10 | | |
|
||||
|
||||
One level past the bound is refused typed (`PayloadTooDeep { depth: 257, limit: 256 }`) for every shape and
|
||||
every variant, before any recursion.
|
||||
|
||||
D2. **Recursion points.** Per container level a typed decode passes through: the derive's generated
|
||||
`Deserialize::deserialize` (`cultcache-rs-derive/src/lib.rs:294-330` for slots, `534-684` for unions), which
|
||||
calls `deserialize_tuple`; rmp-serde's `Deserializer::any_inner` (`decode.rs:530`), which calls
|
||||
`visitor.visit_seq`/`visit_map`/`visit_newtype_struct` under `depth_count!` (566, 583, 616); the derive's
|
||||
`visit_seq`, whose frame holds one `Option<T>` per slot; and `next_element`, which re-enters either a derived
|
||||
type, serde's own impls (`Vec`, `Option`, `Box`) or another crate's (`serde_json::Value`, `rmpv::Value`).
|
||||
rmp-serde 1.3.1 has no skip of its own: `IgnoredAny` goes through `any_inner` and a visitor like any value.
|
||||
`check_payload_depth` is iterative.
|
||||
|
||||
D3. **Where the grow must sit.** A `maybe_grow` in the derive's `deserialize` covers derived levels only: `json`
|
||||
on a 64 KiB debug thread still aborts at 15 with a 32 KiB red zone, and passes only when the first derived
|
||||
level happens to hand it a whole new segment. A `serde_stacker::Deserializer` over rmp-serde at the door checks
|
||||
at every `deserialize_*` call it forwards (`maybe_grow` at `de.rs:476, 489, 502, 511, 520`), so
|
||||
rmp-serde's recursion, serde's impls, foreign `Value` types and `IgnoredAny` skips all re-enter through a check:
|
||||
every shape passes in both profiles (D4). Consumers decode non-derived recursive types through the door today:
|
||||
cultnet-rs `replication.rs:525` (`serde_json::Value`) and `contracts.rs:607` (`rmpv::Value`).
|
||||
|
||||
D4. **The frame between checks, measured.** Stack used from one derived `deserialize` to the next nested one,
|
||||
at the bound: release box 13,168 B, repeat 12,192 B, fat 84,944 B; debug box 52,064 B, repeat 49,760 B, fat
|
||||
207,504 B. The door wrapper checks more often, so its gap is smaller: release, every shape passes at a red zone
|
||||
of 32 KiB on 128 KiB, 1 MiB and 2 MiB threads; debug, box and repeat pass at 32 KiB, fat fails at 128 KiB and
|
||||
passes at 144 KiB through 256 KiB (1 MiB thread). So the worst gap constructed is between 128 and 144 KiB,
|
||||
the debug `visit_seq` of the 32-slot record. serde_stacker's defaults (red zone 64 KiB, segment 2 MiB,
|
||||
`param.rs:10-11`) fail debug fat. The cut sets 256 KiB and 2 MiB: 1.8x the worst measured gap. A type whose
|
||||
single `visit_seq` frame exceeds the red zone can still overflow; that is documented, not prevented.
|
||||
|
||||
D5. **Same values, same errors.** Through the wrapper, box 83, repeat 125 and a 1,000-node surface decode equal
|
||||
to the plain decode. The wrapper forwards `is_human_readable` (`de.rs:313`) and returns rmp-serde's own error
|
||||
type, so `opaque_decode_error` and the derive's refusal texts are unchanged.
|
||||
|
||||
D6. **Cost.** No growth (release, repeat 125 on an 8 MiB thread): 322-339 us through the wrapper against 320 us
|
||||
plain. A shallow 27 KB, 1,000-node surface on 1 MiB: 1.57 ms plain, 1.61-1.80 ms wrapped (run-to-run noise is
|
||||
about that wide). When the decode does grow, it pays for faulting in fresh segment pages: repeat 125 on a 1 MiB
|
||||
thread 1.5-1.7 ms; fat 255 on 1 MiB 25 ms against 9.3 ms on a 64 MiB thread. A 1 MiB and a 2 MiB segment cost
|
||||
the same.
|
||||
|
||||
D7. **Windows x86_64: source read, not run.** stacker 0.1.25 does not use psm on Windows: `backends/windows.rs`
|
||||
grows by fibers (`ConvertThreadToFiber`, `CreateFiber`, `SwitchToFiber`, `SetThreadStackGuarantee`), reads the
|
||||
limit with `VirtualQuery`, and links a C helper built by `cc`. psm's README marks its own Windows stack switching
|
||||
disabled; that is the other layer, so the research's conflict (C) is two layers, not a contradiction. Yggdrasil
|
||||
has no Windows: the rust image carries `x86_64-pc-windows-gnu` (cross-compile, no run). Whether it actually grows
|
||||
on Starfire is question `decode-stack-windows-check`.
|
||||
|
||||
D8. **wasm32: stacker is not a no-op.** psm's `build.rs:53` ships a precompiled `wasm32.o` and sets
|
||||
`switchable_stack`; stacker then allocates segments from the global allocator with no guard page
|
||||
(`alloc_stack_restore_guard.rs`). `remaining_stack()` is `None` on wasm, so the first check always grows and
|
||||
the limit is known from then on. Under wasmtime 48.0.5 (wasm32-wasip1, release), a nested 9-slot record: plain
|
||||
decodes 48 levels and traps at 64 ("out of bounds memory access" at `0xffffe510`: the stack-first shadow stack
|
||||
wrapped below zero); wrapped decodes 64, 255, 400 and 600 levels (linear memory 1,088 KiB before, 8,896 KiB
|
||||
after 255) and traps at 1,000 with "call stack exhausted", the engine's own stack, which stacker cannot grow.
|
||||
`wasm32-unknown-unknown` builds. This corrects the ruling's premise that wasm keeps the abort: the shadow stack
|
||||
grows and the engine stack is the host's setting, so the documentation says that instead.
|
||||
|
||||
D9. **Dependency.** `serde_stacker` 0.1.14 (dtolnay), pulling `stacker` 0.1.25 and `psm` 0.1.32 (rust-lang),
|
||||
all `MIT OR Apache-2.0`; plus `cfg-if`, `libc`, `cc` (build) and `windows-sys` on Windows. psm assembles and
|
||||
stacker compiles C at build time, so a C toolchain becomes a build requirement (gcc in the rust image, MSVC on
|
||||
Starfire). cultcache-rs is MIT. Written by hand, the wrapper would be serde_stacker's ~650 lines of forwarding.
|
||||
|
||||
### Authority, and why
|
||||
|
||||
The door owns stack safety as it owns the bound: `decode_payload` runs the bound walk, then rmp-serde through
|
||||
`serde_stacker::Deserializer` with two private constants. The ruling's "every container level the derive and the
|
||||
door descend through" is met there, because every derived level is entered through the wrapper (D3); a
|
||||
`maybe_grow` in the derive would be a second owner of the same check, needs a red zone of 128 KiB in release
|
||||
and 256 KiB in debug for fat where the wrapper needs 32 and 144 KiB (D4), and still misses foreign recursive types. The derive is unchanged.
|
||||
|
||||
The thread's size no longer decides whether an accepted payload decodes, on targets where stacker switches
|
||||
stacks. rmp-serde's 1024 counter stays a backstop that never decides. Callers that decode a payload with
|
||||
`rmp_serde::from_slice` directly bypass the door, the bound and the grow alike; cultnet-rs re-decodes
|
||||
door-checked `rmpv::Value`s that way (follow-up `rs-redecode-outside-door-r2`).
|
||||
|
||||
Rejected inside the ruling: the derive placement (above), and writing the wrapper by hand (D9: established
|
||||
tooling, one owner upstream).
|
||||
|
||||
## Observed, not owned by these cuts
|
||||
|
||||
- At the default tolerance the solver's answer on allocator-shaped problems depends on the start by up to the whole
|
||||
box (B6). That is documented and pinned (`AnAllocatorShapedProblemIsStartIndependentAtATightTolerance`); a
|
||||
consumer that needs one answer passes a tight tolerance, as Aetheria does.
|
||||
32
docs/cultlib-gaps-target.md
Normal file
32
docs/cultlib-gaps-target.md
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
# CultLib Gaps: Target
|
||||
|
||||
Date: 2026-10-09. Campaign `cultlib-gaps` in the Eureka mind.
|
||||
|
||||
## Why
|
||||
|
||||
Consumers of CultLib keep finding capabilities a reasonable consumer of a general
|
||||
library would expect and that CultLib lacks. Doctrine says a gap is filled in its
|
||||
owner, never worked around in the consumer. This campaign is the standing home for
|
||||
those gaps, so each one lands in CultLib as a small cut instead of a local helper in
|
||||
whichever project hit it.
|
||||
|
||||
Known gaps at opening (each a follow-up in the mind, owned by the consumer campaign
|
||||
that found it):
|
||||
|
||||
- CultMath `BoundedLeastSquares.Solve` has a fixed KKT tolerance (1e-6); Aetheria's
|
||||
thrust allocator needs a tighter one (`aetheria-release:follow_up:cultmath-bls-kkt-tolerance`).
|
||||
- `cultcache-rs` has no decimal type, its snapshot reads follow symlinks, and its
|
||||
single-file store stages files with the process umask and no mode option
|
||||
(`eureka-body:follow_up:cultcache-rs-decimal-and-nofollow`).
|
||||
|
||||
## Invariants
|
||||
|
||||
- `owner-fills-gap`: a capability a consumer needs from CultLib is added to CultLib, with the consumer adopting it; no consumer-local copy survives the cut that adds it.
|
||||
- `defaults-unchanged`: a new option defaults to today's behaviour; existing callers and stored bytes do not change.
|
||||
- `wire-parity`: a CultCache wire change keeps byte parity across runtimes against the C# reference, with a cross-runtime fixture.
|
||||
- `semver-measured`: a public API change bumps the package version by measured semver and ships as a tagged release consumers can pin.
|
||||
|
||||
## Not in scope
|
||||
|
||||
- Growing CultCache into a general database (memory `cultcache-scope-restraint`).
|
||||
- Any consumer's adoption code beyond the pin bump; that stays in the consumer's campaign.
|
||||
201
docs/cultmath-interval-ground-cut-glsl-lowering.r2.spec.json
Normal file
201
docs/cultmath-interval-ground-cut-glsl-lowering.r2.spec.json
Normal file
|
|
@ -0,0 +1,201 @@
|
|||
{
|
||||
"campaign": "cultmath-tapes",
|
||||
"cut": "glsl-lowering",
|
||||
"revision": 2,
|
||||
"title": "GLSL lowering r2: Phacelle as its own MPL-2.0 file so CultMath.glsl is MIT, notices corrected, iv_exp in the fixture, fixture regenerated, glslang and dxc run",
|
||||
"repo": "GameCult/CultLib",
|
||||
"branch": "hands/cultmath-glsl-lowering",
|
||||
"base": "3ac7250a",
|
||||
"depends_on": [
|
||||
"interval-ops"
|
||||
],
|
||||
"first": [
|
||||
"Follow-up on cut report cultmath-tapes:cut_report:cut-glsl-lowering.h1 (range c9bd003b..5ae207e8, no verdict yet; worktree F:\\Projects\\CultLib-glsl). Rulings in force: operator-split-phacelle, operator-compiler-downloads, self-exp-measure-in-site. Map: docs/cultmath-interval-ground-cut.md, 'Pass 3'. First commit: MERGE 3ac7250a (interval-ops r3's head, which Soul s2 found holds for everything this cut lowers) into hands/cultmath-glsl-lowering. Do not rebase: the branch is pushed, and the git rules forbid force-pushing a shared branch. Probed by Imagination in a scratch clone: the merge conflicts only in packages/cultmath/README.md. Resolve it by keeping r3's Intervals bullet (iv_frustum_ball, its rounding bound, the envelope), then r1's GLSL bullet, so the GLSL bullet sits at :48-53. design.md and HlslSourceCompatibilityTests.cs merge clean.",
|
||||
"Second commit: regeneration alone (CULTMATH_WRITE_GLSL=1). Probed on the merge: CultMath.glsl gains 15 lines (cultmath_iv_frustum_ball with the r3 widening); the fixture does not change until this revision adds its families; GlslMirrorTests 4/4 and HlslSourceCompatibilityTests green (16 tests). Soul's range is 3ac7250a..HEAD, which carries r1's four commits through the merge, so the whole lowering gets its first verdict. Runs in parallel with interval-ops r4: r4 changes no src, HLSL or README, only NoiseBoundTests.cs and design.md's saving section (:475-512 at 3ac7250a, :533-570 after this merge), disjoint from this cut's :136-193. Do not merge r4's head into this branch.",
|
||||
"The split (operator-split-phacelle). Transformation step 1 becomes: each #include is inlined in place, except an include whose file is under its own licence, which is lowered on its own into its own output file. The list of such includes is one table in GlslLowering, SeparateFiles = { \"CultMath.Phacelle.hlsl\" -> \"CultMath.Phacelle.glsl\" }, with the reason beside the entry (file-level MPL-2.0). That is an enumerated rule of the lowering, documented as step 1 in design.md; it is not a per-function special case, and nothing else is keyed by name. Lower(root) returns the two texts; Lower(string) stays for the inlined body if that is simpler, but there is one resolver (ReadShaderSource, generalised to accept the include predicate), never a second.",
|
||||
"shaders/CultMath.glsl: the provenance line says it is generated from CultMath.hlsl and CultMath.Interval.hlsl, MIT, and that cultmath_phacelle is in CultMath.Phacelle.glsl, to be concatenated after this file by consumers that call it. The dropped include line leaves nothing behind. shaders/CultMath.Phacelle.glsl: its own provenance line (generated from CultMath.Phacelle.hlsl, MPL-2.0, requires CultMath.glsl before it), the MPL-2.0 header and attribution exactly as the HLSL carries them, the CultPhasor struct and cultmath_phacelle, guard CULTMATH_PHACELLE_GLSL. Both files pinned by CommittedGlslEqualsLowering; CULTMATH_WRITE_GLSL=1 writes both.",
|
||||
"Pin tests over both files: NoHlslOnlyTokensSurvive runs on each; EveryPublicFunctionIsLowered takes the union of both files' definitions against the HLSL (minus texture samplers) and additionally asserts cultmath_phacelle and CultPhasor appear only in the Phacelle file; a new PhacelleFileCompilesOnlyAfterTheLibrary is not needed, the compile check below proves it.",
|
||||
"The fixture (self-exp-measure-in-site). The site measures WebGL2 exp against the fixture, so iv_exp joins it; its C# bits come from the platform exp and differ by OS, so its entry carries tolerance \"ulp-bounded, platform exp\" and names the OS that generated it. GoldenFixtureMatchesCSharp parses the committed JSON (System.Text.Json, BCL) and compares family by family: text-equal for every family except those whose tolerance names the platform, which compare case by case within 1 ulp and print the maximum observed. One fixture, one writer, one tolerance field already in the format; no second fixture. The phacelle family stays in the fixture; the site's parity harness concatenates both GLSL files for that run (the site ships only CultMath.glsl), say so in design.md.",
|
||||
"Notices: packages/cultmath/THIRD-PARTY-NOTICES.md :35-43 lists the MPL-2.0 files as math.Phacelle.cs, CultPhasor.cs, CultMath.Phacelle.hlsl with its Unity copy, and shaders/CultMath.Phacelle.glsl; CultMath.glsl is MIT and says so in its header. The package licence expressions (MIT AND MPL-2.0) do not change: the NuGet still ships the HLSL include. README :36-37 and :48-53 (after the merge) name both GLSL files and when a consumer needs the second. design.md :136-192: step 1 rewritten, the second file, the wrapper runs, the fixture's platform tolerance. Unity ships neither GLSL file.",
|
||||
"Compile checks on Starfire (operator-compiler-downloads), one job each, detached with a log, polled in the foreground: tools/get-glslang.ps1 (16.6.0, the pinned SHA already in the script; if the published digest differs, stop and report, do not edit the pin to match); tools/compile-glsl.ps1 gains a -Phacelle switch and runs twice: the MIT-only wrapper over CultMath.glsl calling every function in it, and the full wrapper over both files calling every function including cultmath_phacelle. Negative controls, both must fail: -Body 'float x = lerp(0.0, 1.0, 0.5);' and the MIT-only wrapper with -Body calling cultmath_phacelle (proves Phacelle is not in CultMath.glsl). Then tools/get-dxc.ps1 and dxc -T lib_6_3 -HV 2021 on both HLSL copies, exit 0. The browser-pane WebGL2 probe of r1 is repeated on the two-file wrapper.",
|
||||
"Carried from r1 and still out of scope, name them in the report: the fixture's ulp bounds on WebGL2 are measured by the site cut; Stryker is not re-run unless packages/cultmath/src changes in 3ac7250a..HEAD (it should not; the lowering lives in tests; interval-ops r3's Stryker evidence, Soul s2, stands). Deviations r1 reported that stand: the anchored token regex; the iv_exp absence is now resolved by this revision; the HLSL edits (damp splat, pcg3d order) stay."
|
||||
],
|
||||
"deletes": [
|
||||
{
|
||||
"path": "packages/cultmath/shaders/CultMath.glsl",
|
||||
"lines": 100,
|
||||
"note": "the inlined Phacelle block (:510-612 at 5ae207e8: MPL header, CultPhasor, cultmath_phacelle) leaves this file; it is regenerated, not edited."
|
||||
},
|
||||
{
|
||||
"path": "packages/cultmath/THIRD-PARTY-NOTICES.md",
|
||||
"lines": 3,
|
||||
"note": ":39-41 the sentence making CultMath.glsl MPL-2.0 as a whole."
|
||||
}
|
||||
],
|
||||
"keeps_moves": [
|
||||
"Transformation steps 2-9 and their order: unchanged; the cast scanner, saturate lowering, the guard and provenance mechanism stay.",
|
||||
"Both tracked CultMath.hlsl copies stay one blob; no HLSL edit is expected in this revision (a dialect gap found by the two-file compile is fixed in the HLSL in the common subset, bit-identical, listed in the report).",
|
||||
"HlslSourceCompatibilityTests' mirror and FindCultMathRoot: the resolver generalises in place; no second include resolver.",
|
||||
"tests/CultMath.Tests/fixtures/glsl-parity.json: the same file, regenerated; families keep their order so the diff shows only the two additions."
|
||||
],
|
||||
"adds": [
|
||||
"packages/cultmath/shaders/CultMath.Phacelle.glsl: generated, MPL-2.0, guard CULTMATH_PHACELLE_GLSL.",
|
||||
"GlslLowering: the SeparateFiles table and the two-text Lower; GlslMirrorTests: the second file in CommittedGlslEqualsLowering, NoHlslOnlyTokensSurvive and EveryPublicFunctionIsLowered; GoldenFixtureMatchesCSharp's per-family comparison with the platform tolerance.",
|
||||
"fixture families: cultmath_iv_frustum_ball (exact) and cultmath_iv_exp (ulp-bounded, platform exp).",
|
||||
"tools/compile-glsl.ps1: -Phacelle switch (appends CultMath.Phacelle.glsl after the library and includes cultmath_phacelle in the calls).",
|
||||
"design.md and README: the two files, the concatenation order, the fixture tolerance."
|
||||
],
|
||||
"file_changes": [
|
||||
{
|
||||
"location": {
|
||||
"path": "packages/cultmath/tests/CultMath.Tests/GlslLowering.cs",
|
||||
"line": 24
|
||||
},
|
||||
"change": "Lower takes the root (or the resolver's two texts) and returns both outputs; SeparateFiles table with the MPL reason; ProvenanceLine per file."
|
||||
},
|
||||
{
|
||||
"location": {
|
||||
"path": "packages/cultmath/tests/CultMath.Tests/HlslSourceCompatibilityTests.cs",
|
||||
"line": 320
|
||||
},
|
||||
"change": "ReadShaderSource accepts a predicate (or returns the separated include's text beside the inlined body); the C# mirror keeps inlining everything."
|
||||
},
|
||||
{
|
||||
"location": {
|
||||
"path": "packages/cultmath/tests/CultMath.Tests/GlslMirrorTests.cs",
|
||||
"line": 30
|
||||
},
|
||||
"change": "CommittedGlslEqualsLowering over both files; :45 NoHlslOnlyTokensSurvive over both; :54 EveryPublicFunctionIsLowered union plus the phacelle-only-in-its-file assertion; :64 GoldenFixtureMatchesCSharp per family with the platform tolerance."
|
||||
},
|
||||
{
|
||||
"location": {
|
||||
"path": "packages/cultmath/tools/compile-glsl.ps1",
|
||||
"line": 1
|
||||
},
|
||||
"change": "-Phacelle switch; the library text is CultMath.glsl, plus CultMath.Phacelle.glsl when set; the call list covers whichever functions are present."
|
||||
},
|
||||
{
|
||||
"location": {
|
||||
"path": "packages/cultmath/THIRD-PARTY-NOTICES.md",
|
||||
"line": 35
|
||||
},
|
||||
"change": "MPL-2.0 file list: the two C# files, the HLSL include and its Unity copy, shaders/CultMath.Phacelle.glsl. CultMath.glsl is MIT."
|
||||
},
|
||||
{
|
||||
"location": {
|
||||
"path": "packages/cultmath/README.md",
|
||||
"line": 48
|
||||
},
|
||||
"change": "both GLSL files; a consumer concatenates CultMath.Phacelle.glsl after CultMath.glsl only when it calls cultmath_phacelle."
|
||||
},
|
||||
{
|
||||
"location": {
|
||||
"path": "packages/cultmath/docs/design.md",
|
||||
"line": 150
|
||||
},
|
||||
"change": "step 1 rewritten for the separated include; :182-192 the two wrapper runs and the fixture's platform tolerance; the site's parity run concatenates both files."
|
||||
}
|
||||
],
|
||||
"authority_map": {
|
||||
"owner": "GlslLowering owns the HLSL -> GLSL transformation and now emits two derived files, one per licence; both are pinned by GlslMirrorTests and never edited. The fixture stays owned by GoldenFixtureMatchesCSharp with one tolerance field per family. THIRD-PARTY-NOTICES.md states which files are MPL-2.0 and is the one place that does.",
|
||||
"inputs": [
|
||||
"shaders/CultMath.hlsl, CultMath.Interval.hlsl and CultMath.Phacelle.hlsl text at the merged head (3ac7250a merged into the branch)",
|
||||
"C# math for the fixture values, including the platform exp for iv_exp"
|
||||
],
|
||||
"outputs": [
|
||||
"shaders/CultMath.glsl (MIT) and shaders/CultMath.Phacelle.glsl (MPL-2.0)",
|
||||
"tests/CultMath.Tests/fixtures/glsl-parity.json with cultmath_iv_frustum_ball and cultmath_iv_exp families"
|
||||
],
|
||||
"derived_state": [
|
||||
"both GLSL files are derived; a hand edit to either fails CommittedGlslEqualsLowering",
|
||||
"the fixture is derived from C#; the iv_exp family is derived from the generating platform's exp and compared within 1 ulp, every other family bit for bit"
|
||||
],
|
||||
"forbidden_writers": [
|
||||
"no per-function special case in the lowering; the only name-keyed rule is the SeparateFiles table, one entry, licence-justified",
|
||||
"no second include resolver, no PowerShell or JS copy of the transformation",
|
||||
"no GLSL in the Unity package; no precision statement in either library file",
|
||||
"no edit to the pinned glslang or dxc hashes to make a download pass"
|
||||
],
|
||||
"shared_paths": [
|
||||
"the same dotnet test run pins the C# mirror, both GLSL files and the fixture",
|
||||
"compile-glsl.ps1 is the one wrapper writer for the MIT-only run, the two-file run and both negative controls"
|
||||
],
|
||||
"deletion_line": "The Phacelle block leaves CultMath.glsl by regeneration and the MPL sentence leaves the notices before the new file is added. Net: one more generated file and one switch; what it buys is an MIT CultMath.glsl the site can vendor without carrying MPL text, and the compile checks r1 could not run."
|
||||
},
|
||||
"verification": {
|
||||
"builds": [
|
||||
"Yggdrasil: dotnet test packages/cultmath/tests/CultMath.Tests green on the merged branch; paste counts; GlslMirrorTests 4/4 with the per-family fixture line printed",
|
||||
"Starfire: tools/get-glslang.ps1 installs 16.6.0 with the pinned SHA matching; tools/compile-glsl.ps1 exits 0 on the MIT-only wrapper and on -Phacelle; both negative controls fail with the error quoted",
|
||||
"Starfire: tools/get-dxc.ps1 then dxc -T lib_6_3 -HV 2021 on both HLSL copies, exit 0; FXC cs_5_0 still green",
|
||||
"Browser pane WebGL2: the two-file wrapper compiles with an empty log"
|
||||
],
|
||||
"tests": [
|
||||
{
|
||||
"name": "GlslMirrorTests.CommittedGlslEqualsLowering",
|
||||
"pins": "CultMath.glsl and CultMath.Phacelle.glsl are exactly the lowering of the committed HLSL; the regeneration path is the same code."
|
||||
},
|
||||
{
|
||||
"name": "GlslMirrorTests.EveryPublicFunctionIsLowered",
|
||||
"pins": "the union of both files equals the HLSL's cultmath_* set minus texture samplers; cultmath_phacelle and CultPhasor live only in the Phacelle file."
|
||||
},
|
||||
{
|
||||
"name": "GlslMirrorTests.NoHlslOnlyTokensSurvive",
|
||||
"pins": "no HLSL-only token in either file."
|
||||
},
|
||||
{
|
||||
"name": "GlslMirrorTests.GoldenFixtureMatchesCSharp",
|
||||
"pins": "every family is C#'s current output bit for bit, except iv_exp within 1 ulp of the platform exp; iv_frustum_ball is present and exact."
|
||||
},
|
||||
{
|
||||
"name": "HlslSourceCompatibilityTests.EveryMirrorFunctionMatchesCSharpMath (existing)",
|
||||
"pins": "no HLSL edit in this range changed a bit."
|
||||
}
|
||||
],
|
||||
"negative": [
|
||||
{
|
||||
"pattern": "Mozilla|MPL|Johansen|CultPhasor|cultmath_phacelle\\(",
|
||||
"scope": "packages/cultmath/shaders/CultMath.glsl: 0 matches; the header's file-name pointer to CultMath.Phacelle.glsl is the only mention of Phacelle."
|
||||
},
|
||||
{
|
||||
"pattern": "^CultPhasor cultmath_phacelle\\(",
|
||||
"scope": "packages/cultmath/shaders/CultMath.Phacelle.glsl: exactly 1 match."
|
||||
},
|
||||
{
|
||||
"pattern": "CultMath\\.glsl|Phacelle\\.glsl",
|
||||
"scope": "packages/cultmath/unity/**: 0 matches."
|
||||
},
|
||||
{
|
||||
"pattern": "\\b(float|u?int|bool)[234]\\b|\\blerp\\(|\\bfrac\\(|\\bsaturate\\(|\\brsqrt\\(|\\basuint\\(|\\basfloat\\(|static const|#include|precision (high|medium|low)p",
|
||||
"scope": "both GLSL files: 0 matches (the anchored regex r1 settled on)."
|
||||
},
|
||||
{
|
||||
"pattern": "CultMath\\.glsl",
|
||||
"scope": "packages/cultmath/THIRD-PARTY-NOTICES.md: 0 matches in the MPL-2.0 file list; CultMath.Phacelle.glsl appears there once."
|
||||
},
|
||||
{
|
||||
"pattern": "git diff 3ac7250a..HEAD -- packages/cultmath/src",
|
||||
"scope": "empty; the lowering and the fixture live in tests, so interval-ops r3's Stryker evidence (verdict s2) stands for this range."
|
||||
}
|
||||
],
|
||||
"operator": []
|
||||
},
|
||||
"estimate": {
|
||||
"lines_added": 320,
|
||||
"lines_removed": 130,
|
||||
"dependencies_added": [],
|
||||
"dependencies_removed": [],
|
||||
"formats_added": [
|
||||
"GLSL ES 3.00 library file (generated, MPL-2.0): shaders/CultMath.Phacelle.glsl"
|
||||
],
|
||||
"formats_removed": [],
|
||||
"targets_added": [],
|
||||
"targets_removed": []
|
||||
},
|
||||
"rulings": [
|
||||
"cultmath-tapes:ruling:operator-split-phacelle",
|
||||
"cultmath-tapes:ruling:operator-compiler-downloads",
|
||||
"cultmath-tapes:ruling:self-exp-measure-in-site",
|
||||
"cultmath-tapes:ruling:operator-campaign-home"
|
||||
],
|
||||
"questions": []
|
||||
}
|
||||
141
docs/cultmath-interval-ground-cut-glsl-lowering.spec.json
Normal file
141
docs/cultmath-interval-ground-cut-glsl-lowering.spec.json
Normal file
|
|
@ -0,0 +1,141 @@
|
|||
{
|
||||
"campaign": "cultmath-tapes",
|
||||
"cut": "glsl-lowering",
|
||||
"revision": 1,
|
||||
"title": "GLSL lowering: shaders/CultMath.glsl is generated from CultMath.hlsl by one enumerated textual transformation, pinned by a test, compiled by glslang, with a committed golden fixture for WebGL2 parity",
|
||||
"repo": "GameCult/CultLib",
|
||||
"branch": "hands/cultmath-glsl-lowering",
|
||||
"base": "c49c76ee",
|
||||
"depends_on": [],
|
||||
"first": [
|
||||
"Map: docs/cultmath-interval-ground-cut.md, sections 'Where the interval math lives' (route C) and 'The authority map'. Model: the HLSL -> C# mirror in tests/CultMath.Tests/HlslSourceCompatibilityTests.cs (wrapper at :348) and its complete transformation list in packages/cultmath/docs/design.md:92-134. The GLSL lowering follows the same discipline: a complete, enumerated list; anything outside it fails the test rather than being patched around.",
|
||||
"Read how HlslSourceCompatibilityTests resolves #include \"CultMath.Phacelle.hlsl\" (CultMath.hlsl:506); the GLSL lowering inlines the included file at that line, because GLSL has no #include.",
|
||||
"Target dialect: GLSL ES 3.00 (#version 300 es), WebGL2. No implicit int/uint -> float conversion; step(vec4, float) and max(vec4, float) differ (max(genType, float) exists, step(genType, float) does not); C-style casts do not exist; lerp/frac/saturate/rsqrt/asuint are mix/fract/clamp(x,0.0,1.0)/inversesqrt/floatBitsToUint; floatN/intN are vecN/ivecN; static const is const. Mixed-signedness shifts are allowed.",
|
||||
"Where the lowered text does not compile, fix the HLSL into the common subset with a legal, bit-identical HLSL edit (e.g. CultMath.hlsl:114 and :200 step(h, 0.0) -> step(h, float4(0.0, 0.0, 0.0, 0.0)); :471-473 and :502 (float)((uint)hash.x >> 8) before the float multiply). The HLSL -> C# mirror test and the FXC/dxc compiles keep those edits honest. Never special-case the lowering for one function.",
|
||||
"Casts need a balanced-paren scanner, not a regex: (int)((state >> 28) + 4) at CultMath.hlsl:396 is the case that breaks a regex.",
|
||||
"Dropped, as the C# mirror drops them: include guards (replaced by CULTMATH_GLSL guards), and the Texture2D/SamplerState functions at CultMath.hlsl:535-573. The GLSL declares no precision; the host shader does (precision highp float; precision highp int; the pcg hashes need 32-bit int).",
|
||||
"Regeneration: the pin test writes shaders/CultMath.glsl when the environment variable CULTMATH_WRITE_GLSL=1 is set, then asserts equality. No new project, no PowerShell copy of the transformation.",
|
||||
"Golden fixture: tests export 256 seeded points per function family (snoise float3/float2, snoise_grad, fbm_grad 4 octaves, ridged_grad, cellular, pcg3d/pcg4d, iv_* if present on main by then) with outputs as float32 bit patterns in hex, to tests/CultMath.Tests/fixtures/glsl-parity.json. JSON is tolerated here: the consumer is a browser-pane WebGL2 readback, a xenos boundary. The site cut evaluates it.",
|
||||
"glslang: tools/get-glslang.ps1 fetches a pinned glslangValidator release the way tools/get-dxc.ps1 does; tools/compile-glsl.ps1 compiles a #version 300 es fragment wrapper that includes shaders/CultMath.glsl and calls every public function once. Run on Starfire, one job, detached with a log, polled in the foreground.",
|
||||
"Verification on Yggdrasil: dotnet test from packages/cultmath/tests/CultMath.Tests; Stryker --since:c49c76ee from a plain clone (not a linked worktree: Stryker resolves --since paths against the main checkout). Never run verification as a background shell task."
|
||||
],
|
||||
"deletes": [],
|
||||
"keeps_moves": [
|
||||
"Both tracked CultMath.hlsl copies (packages/cultmath/shaders and unity/org.gamecult.cultmath/Shaders) stay one blob; the common-subset edits land in both.",
|
||||
"The C# mirror test, the FXC probe and dxc -T lib_6_3 -HV 2021 all still pass on the edited HLSL; the Unity package does not ship the GLSL file.",
|
||||
"design.md's HLSL -> C# transformation list (92-134) is unchanged; the GLSL list is a new sibling section."
|
||||
],
|
||||
"adds": [
|
||||
"tests/CultMath.Tests/GlslLowering.cs: the HLSL -> GLSL ES 3.00 transformation, one static function string -> string, with the list as named steps in order: inline includes; drop guards and texture functions; type names; static const; casts via the balanced scanner; intrinsic renames (lerp, frac, saturate, rsqrt, asuint/asfloat); float literal passthrough; guards CULTMATH_GLSL added; a provenance header line naming the source file and that the file is generated.",
|
||||
"tests/CultMath.Tests/GlslMirrorTests.cs: CommittedGlslEqualsLowering (writes when CULTMATH_WRITE_GLSL=1, prints a unified diff on failure); NoHlslOnlyTokensSurvive (regex over the output for float[234]\\(|int[234]\\(|lerp\\(|frac\\(|saturate\\(|static const|\\((float|int|uint)\\)|Texture2D|SamplerState -> 0 matches); EveryPublicFunctionIsLowered (the set of cultmath_* function names in the HLSL minus the texture ones equals the set in the GLSL); GoldenFixtureMatchesCSharp (regenerates the fixture in memory from C# and asserts equality with the committed file).",
|
||||
"shaders/CultMath.glsl: the committed generated artifact.",
|
||||
"tests/CultMath.Tests/fixtures/glsl-parity.json: the golden fixture (seed, points, per-function expected bit patterns, tolerance class per function: exact for integer-hash paths, ulp-bounded for transcendental).",
|
||||
"tools/get-glslang.ps1 and tools/compile-glsl.ps1, mirroring get-dxc.ps1 / compile-hlsl-spirv.ps1 in shape.",
|
||||
"packages/cultmath/docs/design.md: a section 'GLSL Target: Source Transformations' after :134 with the complete list, the common-subset rule for HLSL, the regeneration command, and that the GLSL is a derived file never edited by hand.",
|
||||
"packages/cultmath/README.md: one paragraph that CultMath.glsl exists, what dialect it is, and how a WebGL consumer includes it (string concatenation before its own #version-led source; declare highp)."
|
||||
],
|
||||
"file_changes": [
|
||||
{
|
||||
"location": { "path": "packages/cultmath/shaders/CultMath.hlsl", "line": 114 },
|
||||
"change": "step(h, 0.0) -> step(h, float4(0.0, 0.0, 0.0, 0.0)); same at :200. Bit-identical in HLSL and C#."
|
||||
},
|
||||
{
|
||||
"location": { "path": "packages/cultmath/shaders/CultMath.hlsl", "line": 470 },
|
||||
"change": "jitter components and the id at :502: an explicit (float) cast around the shifted uint before the float multiply, so the lowered text has no uint*float."
|
||||
},
|
||||
{
|
||||
"location": { "path": "packages/cultmath/shaders/CultMath.Phacelle.hlsl", "line": 1 },
|
||||
"change": "whatever common-subset edits the glslang compile demands; each one bit-identical, each one listed in the cut report."
|
||||
},
|
||||
{
|
||||
"location": { "path": "packages/cultmath/docs/design.md", "line": 134 },
|
||||
"change": "new section: GLSL Target: Source Transformations."
|
||||
}
|
||||
],
|
||||
"authority_map": {
|
||||
"owner": "GlslLowering (tests/CultMath.Tests) owns the HLSL -> GLSL transformation; shaders/CultMath.glsl is its derived output, pinned by GlslMirrorTests. CultMath.hlsl stays the one hand-written shader source.",
|
||||
"inputs": [
|
||||
"shaders/CultMath.hlsl and shaders/CultMath.Phacelle.hlsl text",
|
||||
"C# math for the golden fixture values"
|
||||
],
|
||||
"outputs": [
|
||||
"shaders/CultMath.glsl (GLSL ES 3.00 library, every public cultmath_* function except texture samplers)",
|
||||
"tests/CultMath.Tests/fixtures/glsl-parity.json"
|
||||
],
|
||||
"derived_state": [
|
||||
"CultMath.glsl is derived; a hand edit fails CommittedGlslEqualsLowering",
|
||||
"the fixture is derived from C#; a stale fixture fails GoldenFixtureMatchesCSharp"
|
||||
],
|
||||
"forbidden_writers": [
|
||||
"no per-function special case in the lowering; a dialect gap is fixed in the HLSL in the common subset",
|
||||
"no second transformation implementation (no PowerShell or JS copy of the rules)",
|
||||
"no GLSL in the Unity package; no precision statement in the library file"
|
||||
],
|
||||
"shared_paths": [
|
||||
"both tracked CultMath.hlsl copies receive the same edits; the existing one-blob rule covers them",
|
||||
"the same dotnet test run pins the C# mirror, the GLSL pin and the fixture"
|
||||
],
|
||||
"deletion_line": "Nothing is deleted in CultLib. The liability bought is one generated file, one test file, one fixture and two tool scripts; what it retires is every future hand copy of CultMath noise in a GLSL consumer, starting with the site."
|
||||
},
|
||||
"verification": {
|
||||
"builds": [
|
||||
"Yggdrasil: dotnet test packages/cultmath/tests/CultMath.Tests green; paste counts",
|
||||
"Yggdrasil: dotnet stryker --since:c49c76ee from a plain clone; triage every survivor by name",
|
||||
"Starfire: tools/compile-glsl.ps1 exits 0 on the wrapper over shaders/CultMath.glsl; a negative-control wrapper with one lerp( call must fail (records that the compile check sees errors)",
|
||||
"Starfire: FXC cs_5_0 and dxc -T lib_6_3 -HV 2021 still compile both HLSL copies after the common-subset edits"
|
||||
],
|
||||
"tests": [
|
||||
{
|
||||
"name": "GlslMirrorTests.CommittedGlslEqualsLowering",
|
||||
"pins": "the committed GLSL is exactly the lowering of the committed HLSL; the regeneration path is the same code."
|
||||
},
|
||||
{
|
||||
"name": "GlslMirrorTests.NoHlslOnlyTokensSurvive",
|
||||
"pins": "the list is complete: no HLSL-only token survives in the output."
|
||||
},
|
||||
{
|
||||
"name": "GlslMirrorTests.EveryPublicFunctionIsLowered",
|
||||
"pins": "no function is silently dropped except the texture samplers."
|
||||
},
|
||||
{
|
||||
"name": "GlslMirrorTests.GoldenFixtureMatchesCSharp",
|
||||
"pins": "the fixture the site will read on WebGL2 is C#'s current truth."
|
||||
},
|
||||
{
|
||||
"name": "HlslSourceCompatibilityTests.EveryMirrorFunctionMatchesCSharpMath (existing)",
|
||||
"pins": "the common-subset edits changed no bit of any HLSL function."
|
||||
}
|
||||
],
|
||||
"negative": [
|
||||
{
|
||||
"pattern": "lerp\\(|frac\\(|saturate\\(|float[234]\\(|int[234]\\(|static const|\\((float|int|uint)\\)|Texture2D|SamplerState|#include",
|
||||
"scope": "packages/cultmath/shaders/CultMath.glsl: 0 matches."
|
||||
},
|
||||
{
|
||||
"pattern": "precision (high|medium|low)p",
|
||||
"scope": "packages/cultmath/shaders/CultMath.glsl: 0 matches (the host declares precision)."
|
||||
},
|
||||
{
|
||||
"pattern": "CultMath\\.glsl",
|
||||
"scope": "packages/cultmath/unity/**: 0 matches; the Unity package does not ship the GLSL."
|
||||
},
|
||||
{
|
||||
"pattern": "git diff c49c76ee..HEAD -- packages/cultmath/shaders/CultMath.hlsl | grep '^[-+]' | grep -v '^[-+][-+]'",
|
||||
"scope": "every changed HLSL line is listed in the cut report with the reason (dialect gap it closes); none changes a value, proven by the mirror test and the existing goldens."
|
||||
}
|
||||
],
|
||||
"operator": []
|
||||
},
|
||||
"estimate": {
|
||||
"lines_added": 1100,
|
||||
"lines_removed": 8,
|
||||
"dependencies_added": [],
|
||||
"dependencies_removed": [],
|
||||
"formats_added": ["GLSL ES 3.00 library file (generated)", "glsl-parity.json fixture"],
|
||||
"formats_removed": [],
|
||||
"targets_added": [],
|
||||
"targets_removed": []
|
||||
},
|
||||
"rulings": [],
|
||||
"questions": []
|
||||
}
|
||||
219
docs/cultmath-interval-ground-cut-interval-ops.r2.spec.json
Normal file
219
docs/cultmath-interval-ground-cut-interval-ops.r2.spec.json
Normal file
|
|
@ -0,0 +1,219 @@
|
|||
{
|
||||
"campaign": "cultmath-tapes",
|
||||
"cut": "interval-ops",
|
||||
"revision": 2,
|
||||
"title": "Interval ops r2: envelope-then-noise fields, scenarios with authored empty space including the void, the tile march on cell ranges, iv_frustum_ball, wasted probes removed, dxc run",
|
||||
"repo": "GameCult/CultLib",
|
||||
"branch": "hands/cultmath-interval-ops",
|
||||
"base": "c9bd003b",
|
||||
"depends_on": [],
|
||||
"first": [
|
||||
"Follow-up on cut report cultmath-tapes:cut_report:cut-interval-ops.h1 (head c9bd003b, worktree F:\\Projects\\CultLib-iv). Rulings in force: operator-tile-amortized-march (the bound stays; one probe per screen tile), operator-compiler-downloads. The operator's challenge, verbatim in the map's Pass 3 section: r1 measured a uniform noise slab with no empty space to skip, the worst case for intervals, and the density that matters is an analytic envelope (a pre-distortion SDF) modulated by noise, where the envelope's interval is tight and proves whole ray lengths empty in one probe. Map: docs/cultmath-interval-ground-cut.md, 'Pass 3'. r1's ops and bounds stay; this revision touches math.Interval.cs, CultMath.Interval.hlsl (both tracked copies), NoiseBoundTests.cs, design.md and README only.",
|
||||
"The field, from Aetheria (Volumetric.cginc:165-221 and :91-102; Zone.cs:369-397 GetHeight, :426 PowerPulse; Settings.asset). SDF s(p) = p.y + h(p.xz), h >= 0 the well map: h = PowerPulse(|p.xz| / (2R), 2) * 64 (the zone bowl) + sum over wells of PowerPulse(|p.xz - c_b| / r_b, 16) * d_b, with PowerPulse(x, e) = (1 - 4x^2)^e for x in [0, 1/2] and 0 beyond, r_b = 500 M^0.25, d_b = 30 M^0.175 (Aetheria's GravityRadius/GravityDepth curves). Noise only where s < S: fade(s) = 1 - smoothstep(0.75 S, S, s); displaced height s' = s + A fade(s) n(p) with n the warped two-phase coverage noise plus half the detail octave (r1's field shape); density = max(0, (F - s') / B) (Aetheria's floor: FloorOffset F = -20, FloorBlend B = 10; the patch band and the 1e-9 fill are left out). Above the safety distance density is exactly 0, and so is the noise cost: Aetheria's dense march gates the noise pointwise (`if (dist < _SafetyDistance)`); the test's dense march does the same.",
|
||||
"The composed bound over a tile's frustum slice [z0, z1], Envelope over the slice's exact box, not the ball: with slopes m in [m_c - s, m_c + s] per axis and z in [z0, z1], y = iv_mul([z0, z1], m_y) and x = iv_mul([z0, z1], m_x) (plus the tile's translation o); h's interval over the xz box is the sum over bowls of [pulse(far), pulse(near)], near and far the least and greatest distance from the box to the bowl's centre (pulse is monotone decreasing in distance, so each term is exact; the only slack is the sum). iv_s = iv_add(y, iv_h); iv_fade = the ordered endpoints of fade over iv_s (monotone); iv_n = iv_snoise_ball(ball.xyz * F0, ball.w * F0) with ball = iv_frustum_ball(..., warp = D); iv_s' = iv_add(iv_s, iv_scale(iv_mul(iv_fade, iv_n), A)); the slice is provably empty iff iv_s'.lo >= F. When iv_fade.hi == 0 the noise term is identically zero and iv_snoise_ball is not evaluated: the envelope alone proves the slice empty at no snoise cost. That short-circuit is what tiles compound.",
|
||||
"Where the warp lives in the bound. Aetheria warps only the noise argument (triNoise3d(pos + fl * ...)); the surface height is read at the unwarped xz and the displacement is applied to y afterwards. So the envelope is evaluated on the pre-distortion SDF over the unwarped slice (no D), and only the noise ball is enlarged by D (iv_frustum_ball's warp argument). A warp applied to the envelope's argument would be unsound without enlarging the box by D; the field is defined so that it is not. The test EnvelopeBoundEnclosesDensity pins this: 2,000 seeded slices x 64 warped points, the composed bound encloses density(p) with no tolerance (every op is monotone or already widened in r1; if a seeded case fails at an endpoint, widen in the implementation, never the test).",
|
||||
"iv_frustum_ball(float2 centreSlope, float z0, float z1, float footprintPerDepth, float warp) -> float4(centre, radius), in C# and both HLSL copies, is the one new CultMath function: the noise ball of a tile over a depth segment. Camera: pinhole at the origin looking +z, focal length f pixels; a pixel's ray is p(z') = (m z', z'); a tile's slopes lie in m_c + [-N/(2f), N/(2f)]^2 (full footprint, so sub-pixel jitter is covered), s = N / (sqrt(2) f). Centre c = (m_c z_m, z_m), z_m = (z0 + z1) / 2; radius r = ((z1 - z0) / 2) |(m_c, 1)| + z1 s + warp. Proof: a point of slope m_c + e (|e| <= s) at depth z' is c + (z' - z_m)(m_c, 1) + z'(e, 0), the terms bounded by the two radius terms, and the warp moves it by at most D (WarpedPointsStayEnclosed). The slice is a convex polytope, so every point between rays is enclosed too. The two vectors are never parallel, so the inequality is strict and float32 cannot cross it.",
|
||||
"(Tile ball, continued.) Test TileBallEnclosesEveryRaySegment: 2,000 seeded tiles (N in {1, 4, 8, 16}, f in [500, 3000], |m_c| <= 1.1, segments across each scenario's z range), 64 points each with sub-pixel offsets, both depth ends and a flow of length <= warp; no tolerance. Hand mutations that must die, listed in the file header: z0 for z1 in the lateral term; |m_c| for |(m_c, 1)|; the warp dropped. A moving camera needs nothing more: every frame's pre-pass evaluates iv_frustum_ball from that frame's camera and never carries a ball, a mask or a probe result across frames; the only cross-frame state is the TAA history, which is colour, not a soundness input. The test says so by drawing each tile's camera independently.",
|
||||
"Implementation review of r1's march (NoiseBoundTests.cs:344-376), each item fixed here: (1) every probe was charged one snoise per ray; the tile shares it (ruling). (2) Coarse probes were attempted where the ball could never prove emptiness: iv_snoise_ball's hi is n(c) + L r clamped to 1, so a probe with L r F0 >= 1 + cutoff is a guaranteed failure; at r1's StepMax = 2 that is L r F0 = 3.7, so every coarse probe was a wasted evaluation (the 0.74x row). r2 attempts a noise probe only when L * radius * F0 < 1 - (the cutoff the probe needs), otherwise the level is 'maybe' at no cost. (3) Growth was capped at StepMax = 8 Step0, so a ray through clear space paid Depth / StepMax probes; r2 grows to the remaining range (the hierarchy is over cell-index ranges, halving on maybe, doubling on skip, capped only by the grid's end).",
|
||||
"(Review, continued.) (4) The dense sample evaluated the detail octave even where occupancy was 0; r2's dense sample evaluates coverage first and the detail only when the envelope and coverage leave density > 0, as Aetheria's `if (dist < _SafetyDistance)` does; the dense baseline gets cheaper and the comparison honest. (5) The finest-level probe before integrating a cell stays: amortized over the tile it costs 1/N^2 and can skip 3 snoise per ray. (6) The step never regrew after a dense cell until a skip; with (3) it regrows from the next skip, which is enough.",
|
||||
"The march, on cell ranges. The dense grid is a scenario-owned list of cell boundaries z_0 < ... < z_J (uniform for the slab scenarios; Aetheria's quadratic spacing z_j = near + (j/J)^2 (far - near), J = 256, for the Aetheria-like ones, from CloudShader.shader:116). MarchTile takes a range [j0, j1): the envelope probe over the slice (z_j0, z_j1); if empty, skip and double the next range; else if the noise probe is affordable (item 2) and proves empty, skip; else if the range is more than one cell, halve; else the cell is dense. It runs to the grid's end once per tile (a pre-pass does not know any ray's transmittance) and yields the dense cells; each of the N^2 rays integrates exactly those cells in order with the dense march's own Integrate and early-out at 0.02. Counted separately: snoise evaluations and envelope evaluations (pointwise in the dense march; interval probes in the tile march), per ray with probes divided by N^2.",
|
||||
"The cost model, printed and reasoned about in snoise units: a pointwise envelope evaluation or an envelope probe costs e = 0.2 (a handful of pulses or a height-map fetch against ~150 flops of snoise; stated as an estimate, both counts printed so any weight can be applied). Per scenario the test prints: dense snoise and envelope per ray, tile snoise and envelope probes per ray, the combined cost ratio, and the probe-free ceiling (dense cost over the cost of the dense cells alone). The 2x contract is on the combined cost at N = 8 for scenarios (a) and (c); (b) and (d) are printed as the worst cases and not asserted.",
|
||||
"Scenarios (IV-REPORT lines, each with 64 tiles at N in {1, 4, 8, 16}, warp in {0, D}): (a) height fog: h = 0, camera at y = S + 30, rays with slope m_y in [0, 0.5] (level and up), Aetheria's grid, expected near-total skip (0 snoise either way; the envelope count carries the ratio). (b) inside the fog: h = 0, camera at y = F - 10, rays level, expected near 1x: every ray saturates within a few cells and the pre-pass still probes the whole grid. (c) Aetheria-like: the zone bowl R = 2000 and four wells of mass {100, 1000, 10000, 1000} at seeded positions inside R, camera at a seeded xz in the bowl at y = max(0, S + 10 - h(camera)), rays gazing across with m_y in [-0.25, 0.1], Aetheria's units (noise scale 414 so F0 = 1/414, D = 15 * 8 / 2 = 60, A = 20 with snoise in [-1, 1]), Aetheria's grid. (d) the uniform slab: r1's field and parameters, kept as the reported worst case. The headline is (e) at N = 8, 200 tiles, printed with both its numbers; (a) and (c) are asserted.",
|
||||
"(e) the void, the shipped scene (rulings operator-ground-void-brush, operator-void-true-cavity; site-ground r3): a cloud volume everywhere, carved by one negative pseudo-Gaussian sphere, parametrised by the hollow radius Rh (density exactly 0 inside) and the ramp width S (density rises to full over [Rh, Rh + S]); the brush (1 - (d / Rc)^2)^e with CARVE gives Rh = Rc sqrt(1 - CARVE^(-1/e)) and S from the exponent, so (Rh, S) are the authored knobs and (Rc, e) derived. Noise displaces the wall only: fade(d) = smoothstep(Rh - S, Rh, d); d' = d + A fade(d) n(warp(p)), A = 20, F0 = 0.01 (wavelengths 100 and 25), D = 10; K = 1/30 (optical depth 1 per 30 units of full density), termination at T < 0.02. Shipped point: Rh = 198, S = 50, the sun on the hollow's bottom, the camera 120 behind it along the orbit tangent and 45 above it (186 from the centre, 'low'). Rays over the whole frustum (vertical FOV 60, f = 935, so theta_px = 1/f). Every ray crosses empty interior and ends in a wall.",
|
||||
"Footprint LOD (the operator's challenge, map 'Footprint LOD'): theta_px = 2 tan(fov/2) / H; the footprint at distance z is z theta_px. Step: Delta(z) = max(k z theta_px, min(S / 4, lambda_fine(z) / 2)), k = 4: never finer than four footprints, otherwise the finer of the two content limits (four samples across the ramp, two per wavelength of the finest live octave). Octaves: octave i of wavelength lambda_i carries weight w_i(z) = 1 - smoothstep(lambda_i / (2m), lambda_i / m, z theta_px), m = 4: one smooth blend per octave, no popping; TAA hides per-frame sparsity. The weights are part of the field, so the bound encloses the truncated field exactly: the noise interval over a slice is the sum over octaves of iv_mul([w_i(z1), w_i(z0)], iv_snoise_ball(c F_i, r F_i)), w_i monotone in z. At the shipped parameters (wavelengths 100 and 25, z <= 2 Rc) every weight is 1 in the frustum and the content limits set the step; the footprint bites when S < 4 k z theta_px.",
|
||||
"(e) runs three marches per tile and prints them: the fixed-step reference (Delta_fixed = min(10, S / 4) everywhere, the pointwise envelope gate, the baseline a march that does not know where the wall is must pay); the masked fixed-step march (the same cells, so transmittance agrees exactly: the soundness pin, as (a)-(d)); and the masked LOD march, the shipped one (steps from Delta(z) inside the unmasked range only, octave weights applied), whose transmittance must be within 0.02 of the reference (printed; an approximation by design, not a soundness claim). Printed per configuration: steps per pixel and snoise per pixel for all three, the combined cost ratio reference / LOD, probes per tile. The grid for (e): Rh in {100, 200, 400, 1000} x camera offset in {centred, mid (0.5 Rh), low (0.94 Rh, the shipped)} x S in {10, 50, 150}, 32 tiles each at N = 8; the shipped point with 200 tiles.",
|
||||
"Predictions to confirm or refute, N = 8, combined cost: (a) above 50x. (b) 0.8-1.0x. (c) 2-4x: clear cells collapse to a few probes per tile, fog cells cost the same on both sides; the noise ball proves nothing at Aetheria's scale (L r F0 >= 1.6), so item 2 keeps it unevaluated and the saving is the envelope's. (d) 1.3-1.5x: the ceiling at L = 10.099261. (e), from Imagination's model (scratchpad cavity_model.py): the LOD march needs about 6 steps and 12 snoise per pixel at every grid point with S <= 50 (the content limits S / 4 and the detail half-wavelength 12.5 set the step, not the footprint); S = 150 needs 14 steps and 36 snoise. Against the fixed-step reference at the shipped point: steps 35 to 6 (5-8x fewer), combined cost 1.7x, snoise alone 1.25x; cost 3.2x at S = 10, 1.4x at S = 150, 2.5x at Rh = 1000; camera offset barely matters. (e)'s contract is steps per pixel (Q8 retired). If (a) or (c) misses 2x, skip naming saving-2x-scenarios. Never tune the fields, the grids or e.",
|
||||
"Stryker on Yggdrasil from a plain clone: --since:c9bd003b -m math.Interval.cs; report timeouts separately from kills (a timeout is not a demonstrated kill); if the saving test is what times mutants out, exclude it from Stryker's test selection (a measurement, not a pin) rather than raising the timeout. Compile checks on Starfire, one job, detached with a log, polled in the foreground: FXC cs_5_0 over every cultmath_iv_* including the new function, both tracked copies; then tools/get-dxc.ps1 (pinned, ruling operator-compiler-downloads) and dxc -T lib_6_3 -HV 2021 on both copies. Carried from r1 and still out of scope, name them in the report: the Unity CultMath.dll is not rebuilt; the Unity HLSL copies stay one blob with packages/cultmath/shaders; public asfloat(uint) stays. Branch from c9bd003b; if main moved by docs only, say so as r1 did."
|
||||
],
|
||||
"deletes": [
|
||||
{
|
||||
"path": "packages/cultmath/tests/CultMath.Tests/NoiseBoundTests.cs",
|
||||
"lines": 33,
|
||||
"note": ":344-376 MarchIntervals, the per-ray adaptive march with its StepMax cap and unconditional probes, replaced by MarchTile on cell ranges."
|
||||
},
|
||||
{
|
||||
"path": "packages/cultmath/tests/CultMath.Tests/NoiseBoundTests.cs",
|
||||
"lines": 10,
|
||||
"note": ":401-408 the doc comment naming the r1 fork and :424-425 the Assert.Skip naming it; the fork is answered. A skip survives only on a shortfall in (a) or (c), naming saving-2x-scenarios."
|
||||
},
|
||||
{
|
||||
"path": "packages/cultmath/tests/CultMath.Tests/NoiseBoundTests.cs",
|
||||
"lines": 12,
|
||||
"note": ":319-330 Density: the unconditional three-snoise sample is replaced by the envelope-gated sample (coverage first, detail only when density can be nonzero)."
|
||||
},
|
||||
{
|
||||
"path": "packages/cultmath/docs/design.md",
|
||||
"lines": 15,
|
||||
"note": ":423-437 the saving paragraph with r1's numbers (0.93x, 1.83x, 0.74x), replaced by the scenario paragraph with r2's printed numbers."
|
||||
}
|
||||
],
|
||||
"keeps_moves": [
|
||||
"Every iv_* op, both ball bounds, SNOISE_LIPSCHITZ and its provenance tests: untouched. The ruling keeps the bound; only the field model, the march and its test change.",
|
||||
"SavingField's noise shape (F0 0.35 in the slab, the warped two-phase coverage, the detail octave, period 4) and (d)'s parameters: kept, as the worst case; scenario (d) must reproduce r1's dense count where the detail gating does not bite (print it).",
|
||||
"MarchDense and Integrate: unchanged except that Density is envelope-gated; the dense grid becomes the scenario's boundary list.",
|
||||
"IntervalTests, WarpedPointsStayEnclosed, TightnessReport, MeasureLipschitz, LipschitzConstantPinsSampledGradients: unchanged.",
|
||||
"HlslSourceCompatibilityTests: no change expected; the new function must find its C# twin through the existing mirror."
|
||||
],
|
||||
"adds": [
|
||||
"packages/cultmath/src/CultMath/math.Interval.cs: iv_frustum_ball after iv_fbm_ball, doc comment carrying the derivation and that the caller scales by F0 and adds its translation.",
|
||||
"packages/cultmath/shaders/CultMath.Interval.hlsl: cultmath_iv_frustum_ball, same text in both tracked copies.",
|
||||
"tests/CultMath.Tests/NoiseBoundTests.cs: Scenario (grid, wells, camera, ray slopes, units), SavingField with the envelope (PowerPulse wells, fade, floor), EnvelopeBound (the composed interval, test-side; iv_* ops only), MarchTile, MarchLod (footprint step and octave weights, the shipped march), the per-tile Run; TileBallEnclosesEveryRaySegment; EnvelopeBoundEnclosesDensity; IntervalSkipHalvesEvaluations prints the scenario x N x warp grid and asserts (a) and (c) at N = 8.",
|
||||
"packages/cultmath/docs/design.md, 'Intervals': the frustum-ball paragraph after :401; the envelope-then-noise paragraph (how a consumer composes the bound, the short-circuit, where the warp lives); the rewritten saving paragraph with the four scenarios and the headline.",
|
||||
"packages/cultmath/README.md :38-43: iv_frustum_ball named; one sentence that the bounds compose with an analytic envelope."
|
||||
],
|
||||
"file_changes": [
|
||||
{
|
||||
"location": {
|
||||
"path": "packages/cultmath/src/CultMath/math.Interval.cs",
|
||||
"line": 152
|
||||
},
|
||||
"change": "after iv_fbm_ball: public static float4 iv_frustum_ball(float2 centreSlope, float z0, float z1, float footprintPerDepth, float warp)."
|
||||
},
|
||||
{
|
||||
"location": {
|
||||
"path": "packages/cultmath/shaders/CultMath.Interval.hlsl",
|
||||
"line": 91
|
||||
},
|
||||
"change": "after cultmath_iv_fbm_ball: float4 cultmath_iv_frustum_ball(...); both tracked copies."
|
||||
},
|
||||
{
|
||||
"location": {
|
||||
"path": "packages/cultmath/tests/CultMath.Tests/NoiseBoundTests.cs",
|
||||
"line": 294
|
||||
},
|
||||
"change": "SavingField becomes envelope-then-noise over a Scenario; Density is envelope-gated; MarchTile replaces MarchIntervals; Run draws tiles and N^2 rays each, counting snoise and envelope evaluations separately."
|
||||
},
|
||||
{
|
||||
"location": {
|
||||
"path": "packages/cultmath/tests/CultMath.Tests/NoiseBoundTests.cs",
|
||||
"line": 409
|
||||
},
|
||||
"change": "IntervalSkipHalvesEvaluations: scenarios (a)-(e), N in {1, 4, 8, 16}, warp in {0, D}; the (e) grid Rh x offset x S with three marches; assert >= 2x combined cost for (a) and (c) and >= 2x fewer steps per pixel for (e) at the shipped point, else Skip naming saving-2x-scenarios."
|
||||
},
|
||||
{
|
||||
"location": {
|
||||
"path": "packages/cultmath/tests/CultMath.Tests/NoiseBoundTests.cs",
|
||||
"line": 89
|
||||
},
|
||||
"change": "TileBallEnclosesEveryRaySegment and EnvelopeBoundEnclosesDensity beside WarpedPointsStayEnclosed."
|
||||
},
|
||||
{
|
||||
"location": {
|
||||
"path": "packages/cultmath/docs/design.md",
|
||||
"line": 401
|
||||
},
|
||||
"change": "the frustum-ball and envelope-composition paragraphs; :423-437 the saving paragraph rewritten with r2's printed numbers only."
|
||||
},
|
||||
{
|
||||
"location": {
|
||||
"path": "packages/cultmath/README.md",
|
||||
"line": 38
|
||||
},
|
||||
"change": "iv_frustum_ball named; the envelope composition in one sentence."
|
||||
}
|
||||
],
|
||||
"authority_map": {
|
||||
"owner": "CultMath owns the interval ops, the noise bounds and now the frustum ball; a consumer (the test's SavingField, the site's pre-pass, Aetheria's march) owns its envelope and composes the bound from iv_* ops. The saving test owns the proving-ground numbers per scenario; the site's browser measurement owns the shipped gain. The bound (SNOISE_LIPSCHITZ, iv_snoise_ball) is unchanged.",
|
||||
"inputs": [
|
||||
"the r1 interval surface, unchanged",
|
||||
"a tile's geometry (centre slope, depth segment, footprint per depth, warp bound) and a scenario's grid, wells, camera and units; Aetheria's shapes and settings as read from its checkout, cited by file:line in the test"
|
||||
],
|
||||
"outputs": [
|
||||
"iv_frustum_ball / cultmath_iv_frustum_ball: a ball enclosing every point of every ray of the tile over the segment, warped",
|
||||
"printed numbers per scenario: dense and tile snoise and envelope counts per ray, combined cost ratio, probe-free ceiling, at N in {1, 4, 8, 16}"
|
||||
],
|
||||
"derived_state": [
|
||||
"the tile ball and the envelope box are derived from the tile's geometry; no radius is read from a texture, a uniform or a tuned constant",
|
||||
"whether a noise probe is attempted is derived from L, the radius and the cutoff (item 2), never from a mode flag",
|
||||
"the probe-free ceiling is derived from the same run; it states what no amortization can beat"
|
||||
],
|
||||
"forbidden_writers": [
|
||||
"no change to SNOISE_LIPSCHITZ, iv_snoise_ball, the noise shape or e; the scenarios may not be tuned toward 2x",
|
||||
"no per-ray probe in the tile march; no early-out of the pre-pass on any ray's transmittance",
|
||||
"no warp on the envelope's argument; the warp enlarges the noise ball only",
|
||||
"no new CultMath function for the envelope: PowerPulse, the box and the composition are consumer-side, built from iv_* ops",
|
||||
"no tape, prune, affine or choice token in the interval files; no number in design.md or a comment that the committed test did not print in this run"
|
||||
],
|
||||
"shared_paths": [
|
||||
"the dense march and the tile march integrate the same cells of the same grid with the same Integrate; the transmittance check is the proof that nothing provably empty was there",
|
||||
"the one composed bound (EnvelopeBound) serves the enclosure test and the march; no second composition",
|
||||
"the existing mirror test covers the new HLSL function; the Unity copy stays one blob"
|
||||
],
|
||||
"deletion_line": "r1's per-ray march, its unconditional probes, its growth cap and the unconditional three-snoise dense sample go first; the tile march on cell ranges and the gated sample are written in their place. Nothing in src is deleted. The liability added is one geometry function and two tests plus the scenario model; it buys the tile-march soundness invariant in three runtimes and a saving number measured where there is empty space to find."
|
||||
},
|
||||
"verification": {
|
||||
"builds": [
|
||||
"Yggdrasil: dotnet test packages/cultmath/tests/CultMath.Tests green (MeasureLipschitz/MeasureMonotonicity excluded by trait); paste counts and every IV-REPORT line",
|
||||
"Yggdrasil: dotnet stryker --since:c9bd003b -m math.Interval.cs from a plain clone; 0 survivors; timeouts listed separately from kills",
|
||||
"Starfire: FXC cs_5_0 kernel over every cultmath_iv_* including cultmath_iv_frustum_ball, both HLSL copies",
|
||||
"Starfire: tools/get-dxc.ps1 then dxc -T lib_6_3 -HV 2021 on both HLSL copies, exit 0"
|
||||
],
|
||||
"tests": [
|
||||
{
|
||||
"name": "NoiseBoundTests.TileBallEnclosesEveryRaySegment",
|
||||
"pins": "every sample point of every ray of an N x N tile over a depth segment, sub-pixel jitter and warp included, lies inside iv_frustum_ball."
|
||||
},
|
||||
{
|
||||
"name": "NoiseBoundTests.EnvelopeBoundEnclosesDensity",
|
||||
"pins": "the composed bound (envelope box, fade, noise ball enlarged by the warp) encloses density at every warped point of 2,000 slices, no tolerance; intervals-enclose holds for the composition the site and Aetheria will use."
|
||||
},
|
||||
{
|
||||
"name": "NoiseBoundTests.IntervalSkipHalvesEvaluations",
|
||||
"pins": "scenarios (a) and (c) at N = 8 cost at most half the dense combined cost with transmittance within 1e-3; (e) at the shipped point: the masked LOD march takes at most half the fixed-step reference's steps per pixel, the masked fixed-step march agrees exactly, the LOD march within 0.02; the (e) grid and every scenario, N and warp printed with both counts and the ceiling."
|
||||
},
|
||||
{
|
||||
"name": "IntervalTests.EveryOpEnclosesItsPoints (existing)",
|
||||
"pins": "r1's enclosure for every op still holds."
|
||||
},
|
||||
{
|
||||
"name": "HlslSourceCompatibilityTests.EveryMirrorFunctionMatchesCSharpMath (existing)",
|
||||
"pins": "cultmath_iv_frustum_ball matches iv_frustum_ball bit for bit."
|
||||
}
|
||||
],
|
||||
"negative": [
|
||||
{
|
||||
"pattern": "tape|prune|affine|choice",
|
||||
"scope": "math.Interval.cs and CultMath.Interval.hlsl: 0 matches (case-insensitive)."
|
||||
},
|
||||
{
|
||||
"pattern": "snoise_grad|fbm_grad",
|
||||
"scope": "math.Interval.cs and CultMath.Interval.hlsl: 0 matches."
|
||||
},
|
||||
{
|
||||
"pattern": "PowerPulse|pulse|envelope|Scenario",
|
||||
"scope": "math.Interval.cs and CultMath.Interval.hlsl: 0 matches; the envelope is consumer-side."
|
||||
},
|
||||
{
|
||||
"pattern": "Assert\\.Skip",
|
||||
"scope": "NoiseBoundTests.cs: at most one, in IntervalSkipHalvesEvaluations, naming saving-2x-scenarios; 0 if (a), (c) and (e) meet their contracts."
|
||||
},
|
||||
{
|
||||
"pattern": "10\\.099261|0\\.35f",
|
||||
"scope": "git diff c9bd003b..HEAD -- packages/cultmath/src: the constant is not touched; the slab's F0 stays in (d)."
|
||||
},
|
||||
{
|
||||
"pattern": "git diff --name-only c9bd003b..HEAD",
|
||||
"scope": "only packages/cultmath/**; both tracked CultMath.Interval.hlsl copies change together."
|
||||
}
|
||||
],
|
||||
"operator": []
|
||||
},
|
||||
"estimate": {
|
||||
"lines_added": 420,
|
||||
"lines_removed": 80,
|
||||
"dependencies_added": [],
|
||||
"dependencies_removed": [],
|
||||
"formats_added": [],
|
||||
"formats_removed": [],
|
||||
"targets_added": [],
|
||||
"targets_removed": []
|
||||
},
|
||||
"rulings": [
|
||||
"cultmath-tapes:ruling:operator-tile-amortized-march",
|
||||
"cultmath-tapes:ruling:operator-ground-void-brush",
|
||||
"cultmath-tapes:ruling:operator-void-true-cavity",
|
||||
"cultmath-tapes:ruling:operator-compiler-downloads",
|
||||
"cultmath-tapes:ruling:operator-campaign-home"
|
||||
],
|
||||
"questions": []
|
||||
}
|
||||
268
docs/cultmath-interval-ground-cut-interval-ops.r3.spec.json
Normal file
268
docs/cultmath-interval-ground-cut-interval-ops.r3.spec.json
Normal file
|
|
@ -0,0 +1,268 @@
|
|||
{
|
||||
"campaign": "cultmath-tapes",
|
||||
"cut": "interval-ops",
|
||||
"revision": 3,
|
||||
"title": "Interval ops r3: the frustum ball widened by its derived float32 bound, the analytic constant-density body, one shipped void, (c) held to its ceiling, LOD weights exercised, Stryker kills demonstrated",
|
||||
"repo": "GameCult/CultLib",
|
||||
"branch": "hands/cultmath-interval-ops",
|
||||
"base": "43183276",
|
||||
"depends_on": [],
|
||||
"first": [
|
||||
"Follow-up on cut report cultmath-tapes:cut_report:cut-interval-ops.h2 (head 43183276, worktree F:\\Projects\\CultLib-iv) and Soul's verdict cultmath-tapes:verdict:cut-interval-ops.s1 with its five findings, each resolved below in order. New rulings in force: operator-wells-contract-vs-ceiling ((c)'s contract is at least 90% of the probe-free ceiling, not 2x) and operator-analytic-wall-body (where the envelope interval proves the density constant, one closed-form Beer-Lambert step). Map: docs/cultmath-interval-ground-cut.md, 'Pass 4'. r2's ops, field models, tile march and scenarios stand; this revision touches math.Interval.cs, both tracked CultMath.Interval.hlsl copies, NoiseBoundTests.cs, SnoiseBall tests in the same file, design.md and README only. Nothing new in src beyond the radius widening.",
|
||||
"Finding 1, frustum-ball-float-crossing (Medium). The ball is widened, in C# and both HLSL copies: radius += (|c.x| + |c.y| + |c.z| + radius) * 2^-20 (the literal 9.5367431640625e-7, exact in float32), after the r2 radius. Derivation, u = 2^-24: the centre c = (m_c z_m, z_m) carries at most two roundings per component (z_m = fl(z0 + z1) * 0.5, then the product), so |c_float - c_exact| <= 2u |c|_1; the radius carries at most seven first-order roundings (z1 - z0; the axis sqrt at 3u; the product; z1 * footprint; the sum; + warp), so r_exact <= r_float (1 + 7u); the widening's own addition rounds once more. 2^-20 = 16u covers 8u (|c|_1 + r) twice over. fma contraction removes roundings and only tightens, so dxc's HLSL and any driver's GLSL stay covered. The sentence 'the two vectors are never parallel, so the inequality is strict and float32 cannot cross it' leaves math.Interval.cs:179-180, the HLSL and design.md:412; the rule and its derivation take its place.",
|
||||
"(Finding 1, continued.) TileBallEnclosesEveryRaySegment gains Soul's extreme families beside the r2 domain, 2,000 cases each, 8 footprint corners at both depth ends with the flow pointed outward along the corner's direction from the centre, the distance computed in double from the float ball and the float ray (point (m z, z) formed in double from the float m and z), no tolerance: z0 == z1; thin (z1 - z0 = 1e-6 z1); |m_c| up to 1000; far (z up to 1e7); z0 = 0 with z1 down to 1e-3; f down to 1; warp up to 1e6. The derivation pin becomes two-sided: r_exact <= ball.w <= r_exact + 2^-19 (r_exact + |c|_1), r_exact in double, so a ball that forgets the widening fails and a ball that grows past the rule fails. The hand mutations of r2 stay; a fourth, the widening dropped, must fail the degenerate family alone. WarpedPointsStayEnclosed is unchanged.",
|
||||
"Finding 2, aetheria-far-plane-miscited (Low). FogField's grid becomes Quadratic(0.3, 2048, 256), cited as the Main Camera (Aetheria d3075eb0 Assets/Scenes/ARPG.unity:31777 m_Name Main Camera, :31830 far clip plane 2048; VolumeCloudRenderer.cs:36 RequireComponent(Camera)); the comment at NoiseBoundTests.cs:594 no longer names the Tint camera's 1000. Soul re-measured (c) at far 2048: 1.39-1.51x at warp D, 2.46-2.74x at warp 0, ceiling within 1-2% of the ratio; the verdict on (c) does not move. Print every (a)-(c) row again at 2048.",
|
||||
"Finding 3, shipped-void-two-scenes (Medium). ONE shipped void, authored as (Rh, S) per the map's own rule, everything else derived; the map, the site-ground r3 spec and the test agree on it: Rh = 198, S = 50, so Rc = Rh + S = 248 and e = -ln CARVE / ln(1 - (Rh / Rc)^2) = 0.40 (CARVE 1.5); fade band [Rh - S, Rh], A = 20, F0 = 0.01, D = 10, K = 1/30. This is the scene r2 measured (2.21x) and the Footprint-LOD rule's; the map's site section (Rc 640, e 4, a 442-wide ramp) was the other scene and is superseded. The honest choice changes the look (a 50-wide noisy wall with a kinked outer edge, not a soft pseudo-Gaussian wall), so it is Q9 in the map, a fork for the operator with (a) recommended. Hands codes (a); another ruling moves only the shipped constants and the site section. VoidField's doc comment derives (Rc, e) from (Rh, S) and names it the one shipped void.",
|
||||
"Finding 4, lod-weights-never-exercised (Low). VoidField takes a focal length. One configuration reaches the weights: '(e) LOD far' Rh = 4000, S = 50, camera low, f = 467 (1080 rows at a 98 degree vertical FOV): theta = 1/467, so the fine weight (wavelength 25) is below 1 past z = 1460 and 0 past 2920, the coarse weight (100) below 1 past 5840, and the grid (|camera - c_v| + Rc + 6/K, about 7990) reaches both; 4 z theta exceeds 12.5 past z = 1460, so LodStep is footprint-set there too. It joins EnvelopeBoundEnclosesDensity's field list (the truncated check is no longer vacuous) and the saving test prints it, not asserted. Hand mutation that must fail the truncated check on it: w(z0) for w(z1) in WeightBound.",
|
||||
"(Finding 4, continued: the deviation.) Recorded in the test's doc and design.md: the bound takes each octave weight over [w(z1), 1], not the spec's [w(z1), w(z0)], because one Bound serves the full field (w = 1) and the truncated one (w in [w(z1), w(z0)], w decreasing in z). [w(z1), 1] contains both, iv_mul is monotone in its interval argument, so the composed interval is a superset of either field's and encloses both. The slack is only in far tiles whose step the footprint already sets.",
|
||||
"Finding 5, stryker-timeout-survivor (Low). Mutant 2525 (iv_sqr a.x >= 0 to a.x > 0) is equivalent: at a.x == 0 both branches return the same ends ((0, h) either way, (0, 0) when a.y == 0); the report says so by its diff, since numbers are per run. New enclosure cases kill the mirror-only survivors semantically: SnoiseBallEnclosesPoints and FbmBallEnclosesPoints draw radii LogUniform(1e-3, 1e3), so L / r in iv_snoise_ball (too tight once r > 1: at r = 100 the mutant's bound is 0.2 wide while snoise over the ball spans [-1, 1]) dies to an enclosure test, not only to the HLSL mirror. The mutants Soul listed as mirror-only (iv_scale s >= 0 to s > 0; the two iv_abs mutants) are hand-run and each either named equivalent with the one-line argument (signed zero or a boundary both branches map alike) or killed by one added point case in IntervalTests.",
|
||||
"(Finding 5, continued.) Stryker runs again as r2 did, --since:43183276; every timeout in math.Interval.cs is hand-run (patch from the mutation report, dotnet test minus IntervalSkipHalvesEvaluations) and the report lists killed, survived and equivalent by diff. The report claims only demonstrated kills; a timeout is not a kill.",
|
||||
"The analytic body (ruling operator-analytic-wall-body), consumer-side in the test and the site, no new CultMath function. When it applies: the Scenario's Bound over the remaining range [z, z_end] of the grid, gated, is a point interval with positive value: the envelope with the free noise interval [-1.5, 1.5] (coverage in [-1, 1] plus half the detail) proves fade = 1 and d_lo + A (fade n)_lo >= Rc, so every point of every ray of the tile over the rest of the grid has density exactly K for any noise value; or, generically, lo == hi > 0 from whichever path the bound took. Only then does the march integrate T *= exp(-K ext (z_end - z) |dir|) in one step and terminate (the grid end is past opacity by construction). For (a)-(d) no Bound is a positive point (the fog's density varies with s'), so the step never applies there, and the test asserts bodyStart = -1 for every (a)-(d) tile.",
|
||||
"(Analytic body, continued.) MarchTile returns (dense cells, bodyStart, bodyDensity). As r2 on cell ranges; when a single cell is found not provably empty and its own gated bound is a positive point (the cell is provably constant), one more probe over [grid[j], grid[^1]]: if that is a positive point too, bodyStart = j, bodyDensity = its value, and every remaining cell is appended dense without probing (adding cells is always sound; it also drops the body's probes). The mask's meaning is unchanged, so the masked fixed-step march's exact agreement with the reference stands as the soundness pin. MarchLod: inside unmasked runs as r2; on reaching a cell >= bodyStart it takes the one analytic step over [z, grid end], counts one step, and stops.",
|
||||
"(Analytic body, the grid end.) Every void configuration's grid ends at |camera - c_v| + Rc + 6/K (was 5/K): the body starts at d >= Rc + A 1.5 = Rc + 30 plus box slack, so 6/K leaves at least 4.9 of optical depth, T <= 0.0075 < 0.02, and 'unfinished rays 0' still prints. This is the grid end, not the field; the reference stops by opacity and its count does not move.",
|
||||
"(Analytic body, the pin.) New test AnalyticBodyMatchesFineMarch over the (e) grid, the shipped void and the LOD-far configuration, 2,000 seeded tiles at N in {1, 4, 8, 16}: (1) wherever MarchTile reports bodyStart b: the Bound over [grid[b], grid end] is a positive point; the full and the truncated Density at 64 random (pixel, sub-pixel, cell >= b, depth in cell) points equal bodyDensity exactly, no tolerance; (2) the analytic factor exp(-bodyDensity ext L) over the body equals the fixed-step product of the body cells' Integrate factors (no early-out, same cells) within 1e-4 relative; (3) for every (a)-(d) tile bodyStart = -1. Hand mutation that must fail (1): in VoidField.Compose, CarveRadius for HollowRadius in the lo test (the body claimed from the ramp). The site's mirror of this (site-ground r3): the pre-pass writes the body-start cell in the texel's fourth word, the main pass takes the same one step; its browser check is the dense-reference agreement already in that spec.",
|
||||
"Contracts after r3, asserted at N = 8 in IntervalSkipHalvesEvaluations, else one Assert.Skip naming saving-2x-scenarios with every shortfall: (a) at least 2x combined cost (the lower of warp 0 and D), measured 16384x. (c) at least 0.90 of its probe-free ceiling (Ratio / Ceiling, the lower of warp 0 and D), measured 0.99 at warp D and 0.96 at warp 0 in r2; the ruling's reading is that the ceiling is what intervals control and the fog band's cost is the field's. (e) at least 2x fewer LOD steps per pixel than the fixed-step reference at the ONE shipped void (200 tiles), the masked fixed-step march agreeing exactly and the LOD march within 0.02 of the reference. (b), (d) and the (e) grid incl. LOD-far: printed, not asserted. Nothing is tuned toward any contract: the fields, the grids (beyond the stated 6/K end), e = 0.2 and the seeds stay.",
|
||||
"Predictions to confirm or refute (Imagination's rule from r2's printed rows: the LOD steps that evaluated noise are about snoise / 2.8 plus two pre-band steps; the rest were constant-body steps, which the analytic step makes one). Shipped void: steps per pixel 36.34 (ref) to about 12.5 (was 16.45), 2.6-3.3x fewer; snoise per pixel about 26.6, unchanged; combined cost about 1.38x (was 1.34x); envelope probes per tile about 50 (was 59.1). Grid, low camera, ref/LOD steps: S = 10 about 5-6x at Rh 100-400 and 11x at Rh 1000 (was 2.1-3.4x and 6.8x); S = 50 about 2.5x, 2.8x, 3.5x, 5.2x for Rh 100, 200, 400, 1000 (was 1.8, 2.2, 2.9, 4.5); S = 150 unchanged (rays end inside the 150-wide ramp before the body is proven). Rh 1000 centred S 10: about 30x (was 12.4x). LOD-far: printed, none predicted. If the shipped point lands under 2.6x, say which assumption failed: the pre-band's 0-snoise steps, or a body start later than Rc + 30 by box slack.",
|
||||
"Compile and mutation checks as r2: Yggdrasil dotnet test (counts and every IV-REPORT line pasted); Stryker --since:43183276 -m math.Interval.cs from a plain clone with every timeout hand-run as in Finding 5; Starfire FXC cs_5_0 over every cultmath_iv_* on both HLSL copies and tools/get-dxc.ps1 then dxc -T lib_6_3 -HV 2021 on both, exit 0 (Soul could not re-run these for r2; they are re-run here because the HLSL changes). Carried and still out of scope, named in the report: the Unity CultMath.dll is not rebuilt; the Unity HLSL copies stay one blob with packages/cultmath/shaders; public asfloat(uint) stays. Main moved by docs only since 43183276's base (Imagination passes 3-3d and 4); say so. glsl-lowering r2 rebases onto this revision's head, not r2's (its fixture family for cultmath_iv_frustum_ball changes with the widening); its spec now says so."
|
||||
],
|
||||
"deletes": [
|
||||
{
|
||||
"path": "packages/cultmath/src/CultMath/math.Interval.cs",
|
||||
"lines": 2,
|
||||
"note": ":179-180 the sentence 'The two vectors are never parallel, so the triangle inequality is strict' and its float32 claim; replaced by the widening rule and its derivation."
|
||||
},
|
||||
{
|
||||
"path": "packages/cultmath/docs/design.md",
|
||||
"lines": 1,
|
||||
"note": ":412 'the two vectors are never parallel, so the bound is strict'; replaced by the rule."
|
||||
},
|
||||
{
|
||||
"path": "packages/cultmath/tests/CultMath.Tests/NoiseBoundTests.cs",
|
||||
"lines": 1,
|
||||
"note": ":594 the Tint camera citation (ARPG.unity:635-636, far 1000); replaced by the Main Camera's :31830, far 2048."
|
||||
},
|
||||
{
|
||||
"path": "packages/cultmath/tests/CultMath.Tests/NoiseBoundTests.cs",
|
||||
"lines": 3,
|
||||
"note": ":1181-1194 the 2x test on ratios[c] and the skip message's wording; replaced by the 0.90-of-ceiling test and a message naming each shortfall."
|
||||
},
|
||||
{
|
||||
"path": "packages/cultmath/docs/design.md",
|
||||
"lines": 12,
|
||||
"note": ":461-497 the r2 numbers (1.41x, 16.45, 2.21x, the (c) shortfall paragraph); replaced by r3's printed numbers and the three contracts."
|
||||
}
|
||||
],
|
||||
"keeps_moves": [
|
||||
"Every iv_* op, iv_snoise_ball, iv_fbm_ball, SNOISE_LIPSCHITZ and its provenance tests: untouched. iv_frustum_ball's centre and the r2 radius terms: untouched; only the widening term is appended.",
|
||||
"FogField, SlabField, WarpedNoise, Compose, the gated probe (BestBall), MarchTile's range hierarchy, the masked fixed-step march and Run: kept; MarchTile gains the body return and MarchLod the one analytic step.",
|
||||
"VoidField's field, Density, Bound, Weight, WeightBound and LodStep: kept; the constructor gains the focal length and the grid end moves to 6/K; the shipped point stays Shipped() = (198, 50, shipped camera).",
|
||||
"TileBallEnclosesEveryRaySegment's r2 domain, EnvelopeBoundEnclosesDensity, IntervalTests, TightnessReport, MeasureLipschitz, LipschitzConstantPinsSampledGradients: kept; the first two gain cases.",
|
||||
"HlslSourceCompatibilityTests: the mirror count stays 53; cultmath_iv_frustum_ball's new text must match the C# bit for bit."
|
||||
],
|
||||
"adds": [
|
||||
"math.Interval.cs and both CultMath.Interval.hlsl: the widening line in iv_frustum_ball / cultmath_iv_frustum_ball, and the rule in the doc comment.",
|
||||
"NoiseBoundTests.cs: the extreme families and the two-sided derivation pin in TileBallEnclosesEveryRaySegment; VoidField focal parameter and the LOD-far configuration; MarchTile's (bodyStart, bodyDensity); MarchLod's analytic step; AnalyticBodyMatchesFineMarch; the (c) ceiling contract; radii to 1e3 in the two ball tests; the WeightBound deviation in the doc comment; the shipped-void derivation in VoidField's doc comment.",
|
||||
"IntervalTests.cs: at most three point cases for the mirror-only mutants that are not equivalent (Finding 5).",
|
||||
"design.md 'Intervals': the widening rule and derivation; the analytic-body paragraph (condition, pre-pass word, one step, the pin); the WeightBound deviation; r3's printed numbers under the three contracts; the one shipped void with (Rc, e) derived.",
|
||||
"README.md :41: one clause that iv_frustum_ball's radius carries its float32 rounding bound."
|
||||
],
|
||||
"file_changes": [
|
||||
{
|
||||
"location": {
|
||||
"path": "packages/cultmath/src/CultMath/math.Interval.cs",
|
||||
"line": 183
|
||||
},
|
||||
"change": "iv_frustum_ball: after the r2 radius, radius += (abs(cx) + abs(cy) + abs(zm) + radius) * 9.5367431640625e-7f; doc comment :168-182 states the rule and derivation in place of the strictness sentence."
|
||||
},
|
||||
{
|
||||
"location": {
|
||||
"path": "packages/cultmath/shaders/CultMath.Interval.hlsl",
|
||||
"line": 110
|
||||
},
|
||||
"change": "cultmath_iv_frustum_ball: the same widening line; both tracked copies (packages/cultmath/unity/org.gamecult.cultmath/Shaders/CultMath.Interval.hlsl identical blob)."
|
||||
},
|
||||
{
|
||||
"location": {
|
||||
"path": "packages/cultmath/tests/CultMath.Tests/NoiseBoundTests.cs",
|
||||
"line": 128
|
||||
},
|
||||
"change": "TileBallEnclosesEveryRaySegment: the seven extreme families, outward flow at corners, double distance, the two-sided pin; the file header lists the fourth hand mutation (widening dropped) and the WeightBound and Compose mutations."
|
||||
},
|
||||
{
|
||||
"location": {
|
||||
"path": "packages/cultmath/tests/CultMath.Tests/NoiseBoundTests.cs",
|
||||
"line": 58
|
||||
},
|
||||
"change": "SnoiseBallEnclosesPoints and FbmBallEnclosesPoints: radius LogUniform(1e-3, 1e3)."
|
||||
},
|
||||
{
|
||||
"location": {
|
||||
"path": "packages/cultmath/tests/CultMath.Tests/NoiseBoundTests.cs",
|
||||
"line": 594
|
||||
},
|
||||
"change": "FogField: Grid = Quadratic(0.3, 2048, 256), Main Camera citation."
|
||||
},
|
||||
{
|
||||
"location": {
|
||||
"path": "packages/cultmath/tests/CultMath.Tests/NoiseBoundTests.cs",
|
||||
"line": 829
|
||||
},
|
||||
"change": "VoidField: focal parameter (default 935); LodFar() = (4000, 50, low, f 467); grid end reach + Rc + 6/K; doc comment with the (Rh, S) -> (Rc, e) derivation, the one shipped void, the [w(z1), 1] deviation."
|
||||
},
|
||||
{
|
||||
"location": {
|
||||
"path": "packages/cultmath/tests/CultMath.Tests/NoiseBoundTests.cs",
|
||||
"line": 1009
|
||||
},
|
||||
"change": "MarchTile returns (cells, bodyStart, bodyDensity) with the one confirming probe; MarchLod takes the analytic step at bodyStart; Run and RunStats carry it; ReportVoid prints body steps."
|
||||
},
|
||||
{
|
||||
"location": {
|
||||
"path": "packages/cultmath/tests/CultMath.Tests/NoiseBoundTests.cs",
|
||||
"line": 1160
|
||||
},
|
||||
"change": "IntervalSkipHalvesEvaluations: (c) asserted as Ratio >= 0.90 Ceiling; the LOD-far row printed; the (e) grid printed with the analytic body; AnalyticBodyMatchesFineMarch added beside it."
|
||||
},
|
||||
{
|
||||
"location": {
|
||||
"path": "packages/cultmath/docs/design.md",
|
||||
"line": 403
|
||||
},
|
||||
"change": ":403-430 the frustum-ball paragraph gains the widening rule; :412 strictness sentence deleted; :461-497 the saving section rewritten with r3's printed numbers, the three contracts, the analytic body and the shipped void."
|
||||
},
|
||||
{
|
||||
"location": {
|
||||
"path": "packages/cultmath/README.md",
|
||||
"line": 41
|
||||
},
|
||||
"change": "iv_frustum_ball: 'its radius carries its own float32 rounding bound'."
|
||||
}
|
||||
],
|
||||
"authority_map": {
|
||||
"owner": "CultMath owns the interval ops, the noise bounds and the frustum ball, whose enclosure promise now covers its own float32 rounding (the widening is part of the function, not of any consumer). The consumer (the test's Scenario, the site's pre-pass) owns the envelope, the composed bound, the body proof and the Beer-Lambert step. The saving test owns the proving-ground numbers; the operator owns the shipped void (Q9) and the contracts (the two rulings).",
|
||||
"inputs": [
|
||||
"the r2 surface unchanged; a tile's geometry and warp; a scenario's grid, wells, camera, focal length and units, Aetheria's Main Camera far plane 2048 cited by line",
|
||||
"the one shipped void as (Rh, S) = (198, 50); every other void constant derived from it"
|
||||
],
|
||||
"outputs": [
|
||||
"iv_frustum_ball / cultmath_iv_frustum_ball: a float32 ball that encloses every exact point of every ray of the tile over the segment, warped, under float32 evaluation of the ball itself",
|
||||
"per tile: the dense cells and, when the envelope proves the rest constant, the body-start cell and its density; printed numbers per scenario including the body steps"
|
||||
],
|
||||
"derived_state": [
|
||||
"the widening is derived from the computed centre and radius (2^-20 of |c|_1 + r), never a tuned epsilon; a consumer adds nothing for the ball's own rounding and remains responsible for its world transform",
|
||||
"(Rc, e) are derived from (Rh, S): Rc = Rh + S, e = -ln CARVE / ln(1 - (Rh/Rc)^2); no void constant is authored twice",
|
||||
"the body start is derived from the same Bound the mask is derived from, by one more probe; the main pass reads it, never decides it",
|
||||
"the (c) contract value is derived from the run (0.90 of its own ceiling); no absolute target is written for (c)"
|
||||
],
|
||||
"forbidden_writers": [
|
||||
"no change to SNOISE_LIPSCHITZ, iv_snoise_ball, iv_fbm_ball, the noise shape, e = 0.2, the seeds or any field toward a contract; the grid end moves to 6/K for termination only",
|
||||
"no analytic step from a pointwise density or from the noise ball alone: only a point-interval Bound over the whole remaining range proves the body",
|
||||
"no early-out of the pre-pass on transmittance; no probe in the main pass (the body-start cell is read, its constant is one pointwise envelope value)",
|
||||
"no second shipped void anywhere: the map's site section, the site-ground spec and VoidField.Shipped() name (198, 50) and derive the rest; no number in a doc or comment that the committed test did not print in this run",
|
||||
"no new CultMath function; PowerPulse, the box, the composition and the Beer-Lambert step stay consumer-side; no tape, prune, affine or choice token in the interval files"
|
||||
],
|
||||
"shared_paths": [
|
||||
"the masked fixed-step march still integrates exactly the dense march's cells (the soundness pin); only MarchLod takes the analytic step, and AnalyticBodyMatchesFineMarch ties that step to the fixed-step product over the same cells",
|
||||
"one Bound serves the enclosure tests, the mask, the body proof and the gated probe; no second composition and no second constancy test",
|
||||
"the widening lives once in C# and is mirrored bit for bit into both HLSL copies by the existing mirror test; GLSL follows by the lowering (glsl-lowering r2 rebases onto this head)"
|
||||
],
|
||||
"deletion_line": "The false strictness claim leaves the C# doc, the HLSL and design.md before the widening is written; the Tint camera citation leaves before the Main Camera's is written; the (c) 2x assertion and the second shipped void leave before the ceiling contract and the one void are written. Net in src: one line and a doc comment. In tests: one new pin test, seven case families, one configuration, the body return; what they buy is intervals-enclose holding for the ball's own float32 evaluation, the analytic body the ruling asked for with its soundness pinned, LOD weights actually exercised, and a mutation report that claims only what it demonstrated."
|
||||
},
|
||||
"verification": {
|
||||
"builds": [
|
||||
"Yggdrasil: dotnet test packages/cultmath/tests/CultMath.Tests green (MeasureLipschitz/MeasureMonotonicity excluded by trait); paste counts and every IV-REPORT line, (a)-(d) at far 2048, the (e) grid with body steps, LOD-far, the shipped headline",
|
||||
"Yggdrasil: dotnet stryker --since:43183276 -m math.Interval.cs from a plain clone; every timeout hand-run; killed, survived and equivalent listed by diff; 0 undemonstrated",
|
||||
"Starfire: FXC cs_5_0 kernel over every cultmath_iv_* including cultmath_iv_frustum_ball, both HLSL copies, exit 0",
|
||||
"Starfire: tools/get-dxc.ps1 (pinned) then dxc -T lib_6_3 -HV 2021 on both HLSL copies, exit 0, no diagnostics"
|
||||
],
|
||||
"tests": [
|
||||
{
|
||||
"name": "NoiseBoundTests.TileBallEnclosesEveryRaySegment",
|
||||
"pins": "every exact point of every ray of the tile, corners at both depth ends with an outward flow, lies inside the float32 ball, in the r2 domain and in the seven extreme families, distance in double, no tolerance; the radius is the derivation plus at most 2^-19 (r + |c|_1) and at least the derivation."
|
||||
},
|
||||
{
|
||||
"name": "NoiseBoundTests.EnvelopeBoundEnclosesDensity",
|
||||
"pins": "the composed bound encloses the full and the footprint-truncated density at every warped point of 2,000 slices, including the LOD-far configuration where octave weights are strictly between 0 and 1 and at 0."
|
||||
},
|
||||
{
|
||||
"name": "NoiseBoundTests.AnalyticBodyMatchesFineMarch",
|
||||
"pins": "a body start is reported only where the Bound over the whole remaining range is a positive point and every sampled density there equals it exactly; the analytic factor equals the fixed-step product within 1e-4 relative; no (a)-(d) tile reports a body."
|
||||
},
|
||||
{
|
||||
"name": "NoiseBoundTests.IntervalSkipHalvesEvaluations",
|
||||
"pins": "(a) at least 2x combined cost; (c) at least 0.90 of its probe-free ceiling; (e) at the one shipped void at least 2x fewer LOD steps per pixel, the masked fixed-step march exact, the LOD march within 0.02; every row printed including body steps; one Skip naming saving-2x-scenarios on any shortfall."
|
||||
},
|
||||
{
|
||||
"name": "NoiseBoundTests.SnoiseBallEnclosesPoints and FbmBallEnclosesPoints",
|
||||
"pins": "the ball bounds enclose their functions for radii up to 1e3, so a bound tightened for r > 1 (L / r) dies to an enclosure test."
|
||||
},
|
||||
{
|
||||
"name": "IntervalTests.EveryOpEnclosesItsPoints (existing, plus point cases)",
|
||||
"pins": "r1's enclosure for every op still holds; any non-equivalent mirror-only mutant from Finding 5 has a point case that kills it."
|
||||
},
|
||||
{
|
||||
"name": "HlslSourceCompatibilityTests.EveryMirrorFunctionMatchesCSharpMath (existing)",
|
||||
"pins": "the widened cultmath_iv_frustum_ball matches iv_frustum_ball bit for bit; 53 functions compared."
|
||||
}
|
||||
],
|
||||
"negative": [
|
||||
{
|
||||
"pattern": "never parallel|cannot cross|strict",
|
||||
"scope": "math.Interval.cs iv_frustum_ball doc comment, CultMath.Interval.hlsl, design.md 'Intervals' frustum-ball paragraph: 0 matches."
|
||||
},
|
||||
{
|
||||
"pattern": "635-636|far 1000|Tint",
|
||||
"scope": "NoiseBoundTests.cs: 0 matches; ':31830' and '2048' appear in FogField's citation."
|
||||
},
|
||||
{
|
||||
"pattern": "Rc = 640|e = 4\\b|Rc ~ 220|e ~ 0\\.6|about 220|about 0\\.6",
|
||||
"scope": "NoiseBoundTests.cs and design.md: 0 matches; the shipped void is derived from (198, 50) as Rc = 248, e = 0.40."
|
||||
},
|
||||
{
|
||||
"pattern": "tape|prune|affine|choice|PowerPulse|pulse|envelope|Scenario|body|Beer",
|
||||
"scope": "math.Interval.cs and CultMath.Interval.hlsl: 0 matches (case-insensitive); the analytic body is consumer-side."
|
||||
},
|
||||
{
|
||||
"pattern": "Assert\\.Skip",
|
||||
"scope": "NoiseBoundTests.cs: at most one, in IntervalSkipHalvesEvaluations, naming saving-2x-scenarios; 0 if (a), (c) and (e) meet their contracts."
|
||||
},
|
||||
{
|
||||
"pattern": "10\\.099261|0\\.35f",
|
||||
"scope": "git diff 43183276..HEAD -- packages/cultmath/src: the constant is not touched; the slab's F0 stays in (d)."
|
||||
},
|
||||
{
|
||||
"pattern": "git diff --name-only 43183276..HEAD",
|
||||
"scope": "only packages/cultmath/**; both tracked CultMath.Interval.hlsl copies change together and stay one blob."
|
||||
},
|
||||
{
|
||||
"pattern": "git diff 43183276..HEAD -- packages/cultmath/src | grep '^[-+]' | grep -v '^[-+][-+]' | grep -v '///' | wc -l",
|
||||
"scope": "at most 4 changed code lines in src: the widening line in iv_frustum_ball and nothing else."
|
||||
}
|
||||
],
|
||||
"operator": []
|
||||
},
|
||||
"estimate": {
|
||||
"lines_added": 260,
|
||||
"lines_removed": 40,
|
||||
"dependencies_added": [],
|
||||
"dependencies_removed": [],
|
||||
"formats_added": [],
|
||||
"formats_removed": [],
|
||||
"targets_added": [],
|
||||
"targets_removed": []
|
||||
},
|
||||
"rulings": [
|
||||
"cultmath-tapes:ruling:operator-wells-contract-vs-ceiling",
|
||||
"cultmath-tapes:ruling:operator-analytic-wall-body",
|
||||
"cultmath-tapes:ruling:operator-tile-amortized-march",
|
||||
"cultmath-tapes:ruling:operator-measure-with-empty-space",
|
||||
"cultmath-tapes:ruling:operator-footprint-lod-march",
|
||||
"cultmath-tapes:ruling:operator-ground-void-brush",
|
||||
"cultmath-tapes:ruling:operator-void-true-cavity",
|
||||
"cultmath-tapes:ruling:operator-compiler-downloads",
|
||||
"cultmath-tapes:ruling:operator-campaign-home"
|
||||
],
|
||||
"questions": [
|
||||
"Q9 in the map: the one shipped void. (a, recommended) Rh 198, S 50, derived Rc 248, e 0.40, the scene r2 measured; (b) the site section's Rc 640, e 4; (c) Rh 198, S 100. Hands codes (a)."
|
||||
]
|
||||
}
|
||||
292
docs/cultmath-interval-ground-cut-interval-ops.r4.spec.json
Normal file
292
docs/cultmath-interval-ground-cut-interval-ops.r4.spec.json
Normal file
|
|
@ -0,0 +1,292 @@
|
|||
{
|
||||
"campaign": "cultmath-tapes",
|
||||
"cut": "interval-ops",
|
||||
"revision": 4,
|
||||
"title": "Interval ops r4: LOD agreement against a converged march at the body start, BodyDepth pinned, (c) against an oracle ceiling, WeightBound pinned, design.md from r4's own run",
|
||||
"repo": "GameCult/CultLib",
|
||||
"branch": "hands/cultmath-interval-ops",
|
||||
"base": "3ac7250a",
|
||||
"depends_on": [],
|
||||
"first": [
|
||||
"Follow-up on verdict cultmath-tapes:verdict:cut-interval-ops.s2 (range 43183276..3ac7250a, worktree F:\\Projects\\CultLib-iv), four findings, one item each below. Touches packages/cultmath/tests/CultMath.Tests/NoiseBoundTests.cs and packages/cultmath/docs/design.md only: no src, no HLSL, no README. Question cultmath-tapes:question:wells-ceiling-oracle decides only (c)'s assertion lines (item 9). Self dispatches with its ruling in the brief. Line numbers are at 3ac7250a. Every probe number quoted here is from Imagination's scratch probe at 3ac7250a, with the test's own seeds, tiles and N = 8. It is never committed; r4's run reprints its own numbers.",
|
||||
"Finding lod-agreement-blind-past-body (High), measured. Comparing with the 10-unit fixed-step march cannot pin LodStep. At the shipped void, the LOD march's T at the body start differs from it by up to 0.300 of max(T, 0.02). LodStep doubled differs by 0.309. Both are unconverged midpoint quadratures of a ramp with 25-unit detail. A converged march separates them: h = 0.5, which agrees with h = 1 to 0.0065. Relative optical-depth error per ray, max at the headline: fixed-step 0.061, LOD 0.086, LodStep x2 0.177, LodStep x0.5 0.036. With the pre-body integration dropped, T is wrong by 26.5x max(T, 0.02). So the LOD march is 1.4x less accurate than the dense march before the body. Report it; it is not tuned.",
|
||||
"The agreement rule. MarchLod gains `float cutoff`; Run's costed march passes 0.02, as now. It returns (Transmittance, AtBody). AtBody is T when z first reaches the body start, before the body step, or the final T when there is no body. New helper ConvergedDepth(field, tile, slope, stop, h, lod) returns the optical depth in double, by midpoint quadrature at step h. It runs over EVERY grid cell before `stop`, never the mask's, so it trusts no pre-pass, using the field's Density.",
|
||||
"(Agreement, continued.) In Run with lod, per ray, with stop = bodyStart, or the cell count (grid.Length - 1) when there is none:\n- tauConv = ConvergedDepth(..., stop, 0.5, lod: true).\n- tauLod = -ln(max(AtBody, 1e-30)) from a second MarchLod at cutoff 0.\n- tauRef = -ln of the product of Integrate over cells < stop, lod: false, with no early-out.\nRunStats keeps MaxLodDepthError and MaxRefDepthError, each max |tau - tauConv| / max(tauConv, 1e-3). The converged march and the cutoff-0 march count into a throwaway Counts and no steps, so cost rows do not move.",
|
||||
"The (e) agreement contract replaces 'LOD within 0.02 at the end': at the shipped headline, MaxLodDepthError <= 2 x MaxRefDepthError. The footprint march may be at most twice as wrong as the dense march it is measured against. This mirrors the 2x step contract and is Imagination's default; Self may put it to the operator. Measured 0.086 <= 0.122. LodStep x2 and the dropped pre-body integration fail it. The end-of-ray assertion :1455 is deleted. End-of-ray |dT| stays printed. Every (e) row and LOD-far prints both errors and their ratio, which is printed and not asserted. LOD-far's tauRef carries the deliberate octave truncation, so its ratio is not comparable.",
|
||||
"BodyFactor becomes BodyDepth (:1198-1201). It returns the optical depth Density x ext x (grid end - z) x |dir| as a float. MarchLod multiplies by exp(-BodyDepth(...)). AnalyticBodyMatchesFineMarch part (2) deletes its own tau and analytic (:1375-1377). It compares BodyDepth(field, tile, ray, grid[b], lod: true, counts) with the double sum over body cells of -ln(Integrate(cell, lod: true)), within 1e-4 relative. Probe: in the T domain the comparison underflows at LOD-far (float exp of about -256 is 0, relative error 1); in the depth domain it does not. With |dir| dropped, the depth error is |dir| - 1, at least 0.00145 at the shipped camera, so the mutant dies on every tile.",
|
||||
"Finding wells-ceiling-contract-vacuous (Medium), measured at N = 8. Warp 0: ratio 2.744x, mask ceiling 2.855x (0.961), oracle ceiling 7.263x (0.378), oracle-empty cells skipped 0.952, skip-nothing pre-pass 0.136. Warp D: 1.391x, 1.401x (0.993), 7.165x (0.194), 0.842, 0.139. At warp D about 80% of the masked cost lies in cells where every ray's sample is 0, so design.md's 'where the rays need them' is false. The ruling's reason needs a ceiling the pre-pass cannot move. Hence the question.",
|
||||
"Measurement, whatever the ruling. Run draws a tile's N^2 slopes first, then marches. The random stream reorders, so every IV-REPORT row reprints. The oracle mask is the cells whose Density at mid-depth is > 0 for at least one of those slopes, evaluated into a throwaway Counts. The oracle march runs each ray over the oracle cells only, with the same Integrate and early-out, costed into a new RunStats.Oracle. Assert its T equals the dense march's exactly (probe max |dT| 0). RunStats.Ceiling (:1259-1260) goes. In its place: OracleCeiling = Dense.Cost / Oracle.Cost; Efficiency = Oracle.Cost / (Masked.Cost + Probes.Cost); ProbeOverhead = Masked.Cost / (Masked.Cost + Probes.Cost); CullFraction = oracle-empty cells the mask skips / oracle-empty cells. Report prints all four.",
|
||||
"(c)'s assertion, at N = 8, the lower of warp 0 and D, per the ruling on wells-ceiling-oracle. :1437 records the chosen value. For the cull floor, Assert.True fails rather than skips.\n- oracle-target-cull-floor (recommended): hard CullFraction >= 0.5, plus Efficiency >= 0.90 in the shortfall list.\n- oracle-target-only: the shortfall alone.\n- cull-fraction: CullFraction >= 0.90 in the shortfall list.\n- overhead-plus-floor: ProbeOverhead >= 0.90 in the shortfall list, plus the hard floor.\nThe contracts line names the measured quantity. Note: under options 1 and 2 the test skips today, naming saving-2x-scenarios with (c)'s shortfall; (a) and (e) are still evaluated and listed.",
|
||||
"Finding weightbound-mutation-survives (Low). VoidField gains public (float2 Coarse, float2 Fine) WeightBounds(float z0, float z1) beside Weights(z) (:992). WeightBound (:1035) stays private and is what WeightBounds calls. New Fact WeightBoundEnclosesOneSignedNoise on LodFar, 2,000 cases: z0 ~ U(1460, 0.95 x grid end), z1 ~ U(z0, grid end), 16 depths in [z0, z1] including both ends. Each octave weight lies in its bound. For the one-signed noise interval n = [0.25, 1] and n_s in {0.25, U(0.25, 1), 1}, w(z) n_s lies in iv_mul(bound, n). Probe: the spec's mutant [w(z0), 1] misses w(z1) x 0.25 in 2000 of 2000 fine-octave cases on (1460, 2920). The header (:14-20) moves that mutant to this test.",
|
||||
"Finding design-saving-section-stale (Medium). Rewrite design.md :475-512 from r4's final run, where every figure appears in an IV-REPORT line the report pastes. Delete :422-423's '6e-4 at the shipped scales' sentence, which no test prints. Contents:\n- the tile march and its marches;\n- (a)-(d) at far 2048, with (c)'s oracle ceiling, efficiency, cull fraction and probe overhead;\n- (e) at the shipped void, Rh 198, S 50, Rc = Rh + S, e = -ln 1.5 / ln(1 - (Rh/Rc)^2): steps, snoise, cost, body tiles, the two depth errors;\n- the analytic body (condition, one probe, one step, the pin);\n- the WeightBound [w(z1), 1] deviation and why it encloses;\n- the contracts as asserted, (c) in the ruling's words.\n'The test skips' appears only if this run skips. No r2 or r3 number survives.",
|
||||
"Site-ground's dense-reference browser check has the same blind spot (its converged mean luminance is compared after the walls' bodies). It is follow-up cultmath-tapes:follow_up:site-ground-dense-check-blind-past-body, owned by the next site-ground spec. Not this cut.",
|
||||
"Mutation evidence, cheap by design. src is untouched, so Stryker has nothing in scope and is not run; the negative check proves the premise. Run ONE tools/mutation-table.sh job on Yggdrasil against the final head, test filter FullyQualifiedName~NoiseBoundTests, with these rows:\n- MarchLod `transmittance *= Integrate(field, tile, slope, z, next, lod: true, counts);` -> `transmittance *= 1.0f;` must fail IntervalSkipHalvesEvaluations;\n- LodStep's return wrapped in `2.0f * (...)`: same test;\n- BodyDepth without its sqrt factor: AnalyticBodyMatchesFineMarch;\n- WeightBound `).x, 1.0f)` -> `).y, 1.0f)`: WeightBoundEnclosesOneSignedNoise;\n- MarchTile `if (bound.y <= 0.0f)` -> `if (bound.y <= 0.0f && !field.Name.Contains(\"wells\"))`: IntervalSkipHalvesEvaluations, under the floor options; a survivor under oracle-target-only, by that option's design;\n- Compose `CarveRadius` -> `HollowRadius` in the lo test: AnalyticBodyMatchesFineMarch (carried).\nNo per-mutant hand loops, no Starfire jobs.",
|
||||
"Budget: under 200k Hands tokens. Read NoiseBoundTests.cs :480-1469 and design.md :344-515 once; no other file. Verification is one full CultMath.Tests run on Yggdrasil after the code commits (paste counts and every IV-REPORT line), the mutation-table job, and one fix round. If the headline agreement fails at r4's own numbers, do not move the factor or the step: report the measured errors as a fork."
|
||||
],
|
||||
"deletes": [
|
||||
{
|
||||
"path": "packages/cultmath/tests/CultMath.Tests/NoiseBoundTests.cs",
|
||||
"lines": 1,
|
||||
"note": ":1455 the end-of-ray assertion 'the footprint-aware march differs from the reference by'; blind past the body (finding lod-agreement-blind-past-body)."
|
||||
},
|
||||
{
|
||||
"path": "packages/cultmath/tests/CultMath.Tests/NoiseBoundTests.cs",
|
||||
"lines": 4,
|
||||
"note": ":1198-1201 BodyFactor and its comment; replaced by BodyDepth, the one owner of the body's optical depth."
|
||||
},
|
||||
{
|
||||
"path": "packages/cultmath/tests/CultMath.Tests/NoiseBoundTests.cs",
|
||||
"lines": 3,
|
||||
"note": ":1375-1377 the test's own tau, its exp and the T-domain comparison; replaced by BodyDepth against the cells' summed depth."
|
||||
},
|
||||
{
|
||||
"path": "packages/cultmath/tests/CultMath.Tests/NoiseBoundTests.cs",
|
||||
"lines": 2,
|
||||
"note": ":1259-1260 RunStats.Ceiling and 'What no amortization can beat'; the mask-derived ceiling stops being a contract owner."
|
||||
},
|
||||
{
|
||||
"path": "packages/cultmath/docs/design.md",
|
||||
"lines": 38,
|
||||
"note": ":475-512 the saving section with r2's rows (1.41x, 16.45, 2.21x, 1.34x) and '(c) does not, so the test skips'."
|
||||
},
|
||||
{
|
||||
"path": "packages/cultmath/docs/design.md",
|
||||
"lines": 2,
|
||||
"note": ":422-423 'At the shipped scales (|c|_1 near 600, r near 5) it adds 6e-4.'; printed by no test."
|
||||
}
|
||||
],
|
||||
"keeps_moves": [
|
||||
"packages/cultmath/src, both CultMath.Interval.hlsl copies, README.md and every other test file: untouched.",
|
||||
"Fields, grids (6/K end), seeds, e = 0.2, LodStep, Density, Bound, Compose, MarchTile, Integrate, the masked fixed-step march's exactness asserts, the (a) and (e) step contracts and the Skip mechanism: unchanged.",
|
||||
"TileBallEnclosesEveryRaySegment, EnvelopeBoundEnclosesDensity, the Lipschitz tests, TightnessReport, IntervalTests, HlslSourceCompatibilityTests: unchanged.",
|
||||
"AnalyticBodyMatchesFineMarch parts (1) and (3): unchanged; part (2) changes domain and owner only.",
|
||||
"design.md :344-474 (Intervals up to the saving section, with the r3 frustum-ball paragraph minus the 6e-4 sentence) and every other section: unchanged."
|
||||
],
|
||||
"adds": [
|
||||
"NoiseBoundTests.cs: BodyDepth; MarchLod's cutoff and (Transmittance, AtBody) return; ConvergedDepth; Run's slope-first draw, oracle mask, oracle march and the cutoff-0 agreement march; RunStats Oracle, OracleCeiling, Efficiency, ProbeOverhead, CullFraction, MaxOracleDifference, MaxLodDepthError, MaxRefDepthError; Report and ReportVoid fields; the (e) depth contract; (c)'s assertion per the ruling.",
|
||||
"NoiseBoundTests.cs: VoidField.WeightBounds(z0, z1); Fact WeightBoundEnclosesOneSignedNoise; the header's mutation list updated.",
|
||||
"design.md: the saving section rewritten from r4's run."
|
||||
],
|
||||
"file_changes": [
|
||||
{
|
||||
"location": {
|
||||
"path": "packages/cultmath/tests/CultMath.Tests/NoiseBoundTests.cs",
|
||||
"line": 14,
|
||||
"end_line": 20
|
||||
},
|
||||
"change": "Header mutation list: w(z0) for w(z1) now fails WeightBoundEnclosesOneSignedNoise. Add: the dropped pre-body integration and LodStep x2 fail IntervalSkipHalvesEvaluations's depth agreement; BodyDepth without |dir| fails AnalyticBodyMatchesFineMarch."
|
||||
},
|
||||
{
|
||||
"location": {
|
||||
"path": "packages/cultmath/tests/CultMath.Tests/NoiseBoundTests.cs",
|
||||
"line": 992
|
||||
},
|
||||
"change": "Beside Weights(z): public (float2 Coarse, float2 Fine) WeightBounds(float z0, float z1) => (WeightBound(CoarseWavelength, z0, z1), WeightBound(FineWavelength, z0, z1))."
|
||||
},
|
||||
{
|
||||
"location": {
|
||||
"path": "packages/cultmath/tests/CultMath.Tests/NoiseBoundTests.cs",
|
||||
"line": 1198,
|
||||
"end_line": 1201
|
||||
},
|
||||
"change": "BodyFactor -> BodyDepth(Scenario field, Tile tile, float2 slope, float z, bool lod, Counts counts): the float optical depth Density x Extinction x (Grid[^1] - z) x sqrt(m.x^2 + m.y^2 + 1), with no exp."
|
||||
},
|
||||
{
|
||||
"location": {
|
||||
"path": "packages/cultmath/tests/CultMath.Tests/NoiseBoundTests.cs",
|
||||
"line": 1205,
|
||||
"end_line": 1235
|
||||
},
|
||||
"change": "MarchLod(..., float cutoff, ref long steps, ref long bodySteps) returns (float Transmittance, float AtBody). Both loop guards use cutoff. At z >= body: AtBody = transmittance, then transmittance *= exp(-BodyDepth(...)), steps++, bodySteps++, return. Without a body, AtBody = final T."
|
||||
},
|
||||
{
|
||||
"location": {
|
||||
"path": "packages/cultmath/tests/CultMath.Tests/NoiseBoundTests.cs",
|
||||
"line": 1236
|
||||
},
|
||||
"change": "New ConvergedDepth(Scenario field, Tile tile, float2 slope, int stop, float h, bool lod): sum over cells c < stop of ceil(len / h) midpoint samples, Density(field, tile, slope, z, lod, throwaway) x Extinction x dz x |dir| in double. Every cell, not the mask's."
|
||||
},
|
||||
{
|
||||
"location": {
|
||||
"path": "packages/cultmath/tests/CultMath.Tests/NoiseBoundTests.cs",
|
||||
"line": 1237,
|
||||
"end_line": 1265
|
||||
},
|
||||
"change": "RunStats:\n- Counts Oracle; OracleEmpty and OracleEmptySkipped; MaxOracleDifference; MaxLodDepthError; MaxRefDepthError.\n- OracleCeiling, Efficiency, ProbeOverhead and CullFraction as the spec's 'first' defines them.\n- Ceiling deleted.\nRatio and LodRatio are unchanged."
|
||||
},
|
||||
{
|
||||
"location": {
|
||||
"path": "packages/cultmath/tests/CultMath.Tests/NoiseBoundTests.cs",
|
||||
"line": 1270,
|
||||
"end_line": 1305
|
||||
},
|
||||
"change": "Run, per tile:\n- MarchTile.\n- Draw N^2 slopes.\n- Oracle mask over all cells (mid-depth Density > 0 for any slope; throwaway Counts); count oracle-empty cells and those the mask skips.\n- Per ray: dense, masked and oracle marches (oracle into stats.Oracle; MaxOracleDifference).\n- With lod: the costed MarchLod (cutoff 0.02), then a cutoff-0 MarchLod and ConvergedDepth at h 0.5 into throwaway Counts, and tauRef with no early-out; update both depth errors."
|
||||
},
|
||||
{
|
||||
"location": {
|
||||
"path": "packages/cultmath/tests/CultMath.Tests/NoiseBoundTests.cs",
|
||||
"line": 1307,
|
||||
"end_line": 1318
|
||||
},
|
||||
"change": "Report prints oracle ceiling, efficiency, cull fraction (with counts), probe overhead and max oracle |dT| in place of 'ceiling'. ReportVoid adds the depth errors of LOD and fixed-step against the converged march and their ratio; the end-of-ray |dT| stays."
|
||||
},
|
||||
{
|
||||
"location": {
|
||||
"path": "packages/cultmath/tests/CultMath.Tests/NoiseBoundTests.cs",
|
||||
"line": 1332
|
||||
},
|
||||
"change": "AnalyticBodyMatchesFineMarch part (2): depth = BodyDepth(field, tile, ray, grid[b], lod: true, counts); sum = the double sum over c in [b, last) of -Math.Log(Integrate(field, tile, ray, grid[c], grid[c + 1], lod: true, counts)); assert |depth - sum| <= 1e-4 x sum, naming field, b and both values. The doc comment says so."
|
||||
},
|
||||
{
|
||||
"location": {
|
||||
"path": "packages/cultmath/tests/CultMath.Tests/NoiseBoundTests.cs",
|
||||
"line": 1430,
|
||||
"end_line": 1440
|
||||
},
|
||||
"change": "(a)-(d) loop: Assert MaxOracleDifference == 0 beside the existing <= 1e-3. :1437 records the ruling's (c) quantity (Efficiency, CullFraction or ProbeOverhead), the lower of warp 0 and D at N = 8, and the CullFraction floor value when the ruling has one."
|
||||
},
|
||||
{
|
||||
"location": {
|
||||
"path": "packages/cultmath/tests/CultMath.Tests/NoiseBoundTests.cs",
|
||||
"line": 1453,
|
||||
"end_line": 1466
|
||||
},
|
||||
"change": "Headline:\n- MaxDifference == 0 stays.\n- :1455 is replaced by Assert MaxLodDepthError <= 2 x MaxRefDepthError, with both values in the message.\n- Under a floor option: Assert CullFraction >= 0.5 for (c) at both warps (hard).\n- Shortfalls: (c) per the ruling.\n- The contracts line names the quantity and prints the (e) depth errors."
|
||||
},
|
||||
{
|
||||
"location": {
|
||||
"path": "packages/cultmath/tests/CultMath.Tests/NoiseBoundTests.cs",
|
||||
"line": 1402,
|
||||
"end_line": 1414
|
||||
},
|
||||
"change": "IntervalSkipHalvesEvaluations doc comment:\n- the (e) agreement is the converged depth, 2x the fixed-step's;\n- (c) per the ruling, citing it;\n- the oracle is defined;\n- 'within 0.02' leaves."
|
||||
},
|
||||
{
|
||||
"location": {
|
||||
"path": "packages/cultmath/tests/CultMath.Tests/NoiseBoundTests.cs",
|
||||
"line": 304
|
||||
},
|
||||
"change": "After EnvelopeBoundEnclosesDensity: Fact WeightBoundEnclosesOneSignedNoise, as item 10 of 'first'. Its message names z0, z1, z, the octave, the weight and the bound."
|
||||
},
|
||||
{
|
||||
"location": {
|
||||
"path": "packages/cultmath/docs/design.md",
|
||||
"line": 475,
|
||||
"end_line": 512
|
||||
},
|
||||
"change": "The saving section is rewritten from r4's IV-REPORT lines (contents in item 11 of 'first'). The next paragraph, 'Consumers: ...' at :514, is kept."
|
||||
},
|
||||
{
|
||||
"location": {
|
||||
"path": "packages/cultmath/docs/design.md",
|
||||
"line": 422,
|
||||
"end_line": 423
|
||||
},
|
||||
"change": "Delete the sentence 'At the shipped scales (|c|_1 near 600, r near 5) it adds 6e-4.' Leave the rest of the paragraph."
|
||||
}
|
||||
],
|
||||
"authority_map": {
|
||||
"owner": "The saving test owns the proving-ground numbers and their oracles. The converged march (h = 0.5) is the accuracy oracle before the body. The oracle mask (cells some ray of the tile samples nonzero) is (c)'s ceiling oracle. BodyDepth is the one owner of the body's optical depth, in the march and in its pin. CultMath src is untouched. The operator owns the contracts: the rulings and the answer to wells-ceiling-oracle.",
|
||||
"inputs": [
|
||||
"the r3 fields, grids, seeds, tiles and marches at 3ac7250a",
|
||||
"the ruling answering cultmath-tapes:question:wells-ceiling-oracle"
|
||||
],
|
||||
"outputs": [
|
||||
"IV-REPORT rows: the LOD and fixed-step depth errors against the converged march; (c)'s oracle ceiling, efficiency, cull fraction and probe overhead",
|
||||
"design.md's saving section, every figure from those rows"
|
||||
],
|
||||
"derived_state": [
|
||||
"(c)'s ceiling is no longer derived from the pre-pass's own mask; it is derived from the oracle mask, which the pre-pass cannot move.",
|
||||
"Dense/Masked is no longer a contract owner; Masked/(Masked+Probes) is printed as probe overhead (an owner only under overhead-plus-floor).",
|
||||
"The fixed-step march is no longer the LOD march's accuracy oracle; it is a peer measured against the converged march, and its error sets the LOD's allowance (2x).",
|
||||
"End-of-ray |dT| is display-only.",
|
||||
"The body's optical depth is derived once, by BodyDepth; the test no longer re-derives it."
|
||||
],
|
||||
"forbidden_writers": [
|
||||
"no assertion compares the LOD march with the fixed-step march directly, or after the body",
|
||||
"AnalyticBodyMatchesFineMarch does not compute the body's depth itself; it calls BodyDepth",
|
||||
"neither the oracle mask nor ConvergedDepth reads MarchTile's output",
|
||||
"no change to src, the HLSL, the fields, grids, LodStep, seeds, the 0.2 weight or the 2x factor toward a contract",
|
||||
"no figure in design.md that this run's IV-REPORT lines do not print"
|
||||
],
|
||||
"shared_paths": [
|
||||
"MarchLod is one function for the costed march (cutoff 0.02) and the agreement march (cutoff 0)",
|
||||
"one Run computes dense, masked, oracle, LOD and converged for every scenario; the headline and the grid print the same fields",
|
||||
"the site's mirror of the march inherits the same check through follow-up site-ground-dense-check-blind-past-body"
|
||||
],
|
||||
"deletion_line": "The end-of-ray LOD assertion, BodyFactor, the test's own tau, RunStats.Ceiling, the (c) Ratio/Ceiling special case, design.md's r2 rows and the unprinted 6e-4 sentence all leave before their replacements are written. Net: about +170 / -60 in tests and docs, nothing in src. What that buys: (e) can now fail on a wrong pre-body march, the body depth can fail on a wrong |dir|, (c) can fail on a pre-pass that proves nothing, and the WeightBound mutant dies."
|
||||
},
|
||||
"verification": {
|
||||
"builds": [
|
||||
"Yggdrasil: dotnet test packages/cultmath/tests/CultMath.Tests -c Release green or skipped only by saving-2x-scenarios as the ruling implies (MeasureLipschitz/MeasureMonotonicity excluded by trait); paste counts and every IV-REPORT line",
|
||||
"Yggdrasil: one tools/mutation-table.sh job at the final head with the six rows in 'first' item 13; the table pasted; every row CAUGHT by the named test except the wells row under oracle-target-only",
|
||||
"No Stryker run and no Starfire job: no src or HLSL change in 3ac7250a..HEAD (negative check)"
|
||||
],
|
||||
"tests": [
|
||||
{
|
||||
"name": "NoiseBoundTests.IntervalSkipHalvesEvaluations",
|
||||
"pins": "At the shipped void the footprint march's optical depth at the body start is within 2x the fixed-step march's error of a converged march; the oracle march equals the dense march exactly; (c) is asserted per the ruling against a ceiling the pre-pass cannot move; (a) and (e) step contracts as before."
|
||||
},
|
||||
{
|
||||
"name": "NoiseBoundTests.AnalyticBodyMatchesFineMarch",
|
||||
"pins": "BodyDepth, the depth MarchLod uses, equals the summed fixed-step depth of the body cells within 1e-4 relative, in the depth domain (no underflow), so a body depth without |dir| fails on every tile; parts (1) and (3) unchanged."
|
||||
},
|
||||
{
|
||||
"name": "NoiseBoundTests.WeightBoundEnclosesOneSignedNoise",
|
||||
"pins": "Each octave weight at every sampled depth in [z0, z1] lies in WeightBounds(z0, z1), and w(z) n lies in iv_mul(bound, n) for a one-signed n, so a lower end above w(z1) fails."
|
||||
},
|
||||
{
|
||||
"name": "NoiseBoundTests (rest) and CultMath.Tests (rest)",
|
||||
"pins": "unchanged and green."
|
||||
}
|
||||
],
|
||||
"negative": [
|
||||
{
|
||||
"pattern": "git diff --name-only 3ac7250a..HEAD",
|
||||
"scope": "exactly NoiseBoundTests.cs and design.md under packages/cultmath."
|
||||
},
|
||||
{
|
||||
"pattern": "git diff 3ac7250a..HEAD -- packages/cultmath/src packages/cultmath/shaders packages/cultmath/unity",
|
||||
"scope": "empty."
|
||||
},
|
||||
{
|
||||
"pattern": "BodyFactor|Ceiling =>|\\.Ceiling\\b|MaxLodDifference <= ",
|
||||
"scope": "NoiseBoundTests.cs: 0 matches."
|
||||
},
|
||||
{
|
||||
"pattern": "Math\\.Exp\\(-\\(double\\)tau\\)|var tau = density",
|
||||
"scope": "NoiseBoundTests.cs: 0 matches (the test does not re-derive the body)."
|
||||
},
|
||||
{
|
||||
"pattern": "1\\.41x|16\\.45|2\\.21x|1\\.34x|6e-4|does not, so the test skips|where the rays need them",
|
||||
"scope": "packages/cultmath/docs/design.md: 0 matches."
|
||||
},
|
||||
{
|
||||
"pattern": "Assert\\.Skip",
|
||||
"scope": "NoiseBoundTests.cs: at most one, in IntervalSkipHalvesEvaluations, naming saving-2x-scenarios."
|
||||
}
|
||||
],
|
||||
"operator": []
|
||||
},
|
||||
"estimate": {
|
||||
"lines_added": 170,
|
||||
"lines_removed": 60,
|
||||
"dependencies_added": [],
|
||||
"dependencies_removed": [],
|
||||
"formats_added": [],
|
||||
"formats_removed": [],
|
||||
"targets_added": [],
|
||||
"targets_removed": []
|
||||
},
|
||||
"rulings": [
|
||||
"cultmath-tapes:ruling:operator-wells-contract-vs-ceiling",
|
||||
"cultmath-tapes:ruling:operator-analytic-wall-body",
|
||||
"cultmath-tapes:ruling:operator-footprint-lod-march",
|
||||
"cultmath-tapes:ruling:operator-measure-with-empty-space",
|
||||
"cultmath-tapes:ruling:operator-tile-amortized-march",
|
||||
"cultmath-tapes:ruling:operator-shipped-void"
|
||||
],
|
||||
"questions": [
|
||||
"cultmath-tapes:question:wells-ceiling-oracle"
|
||||
]
|
||||
}
|
||||
146
docs/cultmath-interval-ground-cut-interval-ops.spec.json
Normal file
146
docs/cultmath-interval-ground-cut-interval-ops.spec.json
Normal file
|
|
@ -0,0 +1,146 @@
|
|||
{
|
||||
"campaign": "cultmath-tapes",
|
||||
"cut": "interval-ops",
|
||||
"revision": 1,
|
||||
"title": "Interval ops: cultmath_iv_* over float2(lo, hi) in C# and HLSL with enclosure tests, a committed Lipschitz constant for snoise, and ball bounds for snoise and fbm",
|
||||
"repo": "GameCult/CultLib",
|
||||
"branch": "hands/cultmath-interval-ops",
|
||||
"base": "c49c76ee",
|
||||
"depends_on": [],
|
||||
"first": [
|
||||
"Map: docs/cultmath-interval-ground-cut.md, sections 'Ownership', 'Interval culling along the ray' and 'The proving-ground contract'. Parked target: docs/cultmath-tape-target.md, sketch step 1 (:59-64) and 'Open before unparking' (:106-115). This cut is step 1 and nothing after it: no tape, no pruning, no min/max choice tracking, no affine arithmetic (map D1).",
|
||||
"Common rules from the Asura cut map (Asura docs/cut-map.md, 'Common rules for every addition', :453-489): C# in packages/cultmath/src/CultMath as a partial of math (the Phacelle pattern: math.Phacelle.cs beside math.cs), HLSL in a new shaders/CultMath.Interval.hlsl included from CultMath.hlsl the way CultMath.Phacelle.hlsl is (:506), names prefixed cultmath_, both tracked HLSL copies one blob, bodies inside design.md's transformation list (:92-134), THIRD-PARTY-NOTICES untouched (nothing is ported; Fidget's ideas are used, not its code).",
|
||||
"Representation: an interval is float2(lo, hi), lo <= hi, both finite. The empty interval does not exist; a caller that needs 'provably empty' tests hi < cutoff. Point intervals are iv_point(x) = float2(x, x).",
|
||||
"Op set, each with the C# twin the mirror test demands: iv_point, iv_add, iv_sub, iv_neg, iv_mul, iv_scale(iv, float), iv_abs, iv_min, iv_max, iv_sqr, iv_sqrt (lo clamped at 0), iv_exp, iv_clamp(iv, float, float), iv_saturate, iv_smoothstep(float e0, float e1, iv) (monotone: endpoints), iv_lerp(iv, iv, float t). No others until a consumer names one.",
|
||||
"Noise bounds: CULTMATH_SNOISE_LIPSCHITZ (static const float, provenance in the comment: measured max |snoise_grad| over 1e6 seeded points plus 1e4 gradient-ascent refinements, times 1.10; the test that measures it is committed as a slow, explicitly-run test and the constant is pinned by a fast test). iv_snoise_ball(float3 c, float r) = [snoise(c) - L r, snoise(c) + L r] intersected with [-1, 1]. iv_fbm_ball(c, r, octaves, lacunarity, gain) = the octave sum of iv_snoise_ball(c * f_i, r * f_i) scaled by a_i, octaves clamped to [0, 16] like fbm_grad.",
|
||||
"Write the enclosure property first, as the shared harness: for each op, 10,000 seeded random intervals (widths from 1e-4 to 10, centres in [-20, 20]) and 16 points inside each; assert f(x) in op(I) with no tolerance (the bound is computed in the same float32 arithmetic; where rounding could exclude an endpoint, widen the op by one ulp in the implementation, not the test, and say so in design.md). For the ball bounds: 2,000 balls, r in [1e-3, 2], 64 points inside each.",
|
||||
"The saving test: a representative coverage field (one snoise octave at F0 = 0.35, cutoff 0.25) and 1,000 seeded rays through a slab of depth 12; march once at the dense step and once with the adaptive interval march from the map (Δ0, ΔMAX = 8 Δ0, ΔDENSE = Δ0/2, grow on skip, halve on maybe); count snoise evaluations; assert the integrated transmittance agrees within 1e-3 and the evaluation count is at least 2x lower. Print both counts and the ratio; the cut report quotes them.",
|
||||
"The warp enclosure test (the site's march rests on it): for 2,000 seeded (centre c, radius r, warp bound D) triples and random flow vectors with |flow| <= D, every warped point c' = x + flow (x in the ball of radius r) lies in the ball of radius r + D, and snoise(c') lies in iv_snoise_ball(c, r + D). This is a property of the existing bound, not a new function; it is written as a named test so the domain-warp use is pinned and documented in design.md.",
|
||||
"The saving test's field is domain-warped: coverage = sum over two phases of snoise(p + flow * (phase_k - 0.5) * PERIOD) with a bounded flow, matching the map's field shape, so the interval radius includes D.",
|
||||
"Tightness: a committed test prints the mean width ratio (interval width / true range over the 64 points) for iv_snoise_ball at r = 0.05, 0.25, 1.0 and for iv_fbm_ball at 4 octaves. No assertion beyond finiteness; the number is for the report and for a later affine cut to beat.",
|
||||
"Verification on Yggdrasil: dotnet test from packages/cultmath/tests/CultMath.Tests; Stryker --since:c49c76ee from a plain clone. Starfire: FXC cs_5_0 kernel calling every iv_* function and both ball bounds; dxc -T lib_6_3 -HV 2021. Detached with a log, polled in the foreground; never a background shell task. Numbers in comments or docs come from committed tests only.",
|
||||
"If glsl-lowering has merged to main before this branch does, rebase and regenerate shaders/CultMath.glsl (CULTMATH_WRITE_GLSL=1) so the pin test is green on the merge; if not, the lowering cut regenerates after this one. Either order works because the GLSL is derived."
|
||||
],
|
||||
"deletes": [],
|
||||
"keeps_moves": [
|
||||
"snoise, snoise_grad, fbm_grad, ridged_grad, cellular, phacelle: untouched. The bounds call snoise (value) only; snoise_grad is used by the Lipschitz measurement test, not by any bound (map D2).",
|
||||
"design.md's invariant 8 section (136-) is unchanged; intervals are not value-and-gradient primitives and do not claim the float4(grad, value) layout.",
|
||||
"HlslMirrorTests' ban on erosion kernels stands; nothing named interval touches it."
|
||||
],
|
||||
"adds": [
|
||||
"packages/cultmath/src/CultMath/math.Interval.cs: public static partial class math with iv_point, iv_add, iv_sub, iv_neg, iv_mul, iv_scale, iv_abs, iv_min, iv_max, iv_sqr, iv_sqrt, iv_exp, iv_clamp, iv_saturate, iv_smoothstep, iv_lerp, iv_snoise_ball, iv_fbm_ball, and the constant SNOISE_LIPSCHITZ; each with a doc comment stating the enclosure it guarantees and the ulp widening where one is needed.",
|
||||
"packages/cultmath/shaders/CultMath.Interval.hlsl: the HLSL mirrors with the same names prefixed cultmath_, and CULTMATH_SNOISE_LIPSCHITZ as static const; included from CultMath.hlsl after the Phacelle include (:506). Both tracked HLSL copies.",
|
||||
"tests/CultMath.Tests/IntervalTests.cs: the enclosure harness over every op; iv_mul sign cases (all four quadrant combinations and a zero-straddling factor); iv_sqrt with lo < 0; iv_abs straddling zero gives [0, max(|lo|,|hi|)]; iv_smoothstep monotonicity; iv_min/iv_max against the pointwise min/max; a mutant that shrinks any bound by one ulp dies (hand-mutation list in the file header for the float arithmetic Stryker cannot reach, as in 2a-ii-a).",
|
||||
"tests/CultMath.Tests/NoiseBoundTests.cs: iv_snoise_ball and iv_fbm_ball enclosure; LipschitzConstantPinsSampledGradients (fast, 1e5 points); MeasureLipschitz (slow, explicit trait, prints the max and the refined max); TightnessReport; the saving test (InvalSkipHalvesEvaluations) with its printed counts.",
|
||||
"packages/cultmath/docs/design.md: a section 'Intervals' after the invariant 8 section: representation, the op list, the ulp-widening rule, the Lipschitz provenance and margin, what the ball bounds guarantee and what they do not (nothing about tapes), and that the site's ground shader and Aetheria's nebula raymarch are the consumers.",
|
||||
"packages/cultmath/README.md: one paragraph under the noise entry naming the interval family and its purpose (empty-space culling with a proof)."
|
||||
],
|
||||
"file_changes": [
|
||||
{
|
||||
"location": { "path": "packages/cultmath/shaders/CultMath.hlsl", "line": 506 },
|
||||
"change": "add #include \"CultMath.Interval.hlsl\" after the Phacelle include; both tracked copies."
|
||||
},
|
||||
{
|
||||
"location": { "path": "packages/cultmath/src/CultMath/math.cs", "line": 602 },
|
||||
"change": "no change to snoise; a comment pointer from snoise to SNOISE_LIPSCHITZ in math.Interval.cs so the next kernel change knows the constant must be re-measured."
|
||||
},
|
||||
{
|
||||
"location": { "path": "packages/cultmath/docs/design.md", "line": 136 },
|
||||
"change": "new 'Intervals' section after invariant 8."
|
||||
},
|
||||
{
|
||||
"location": { "path": "packages/cultmath/tests/CultMath.Tests/HlslSourceCompatibilityTests.cs", "line": 348 },
|
||||
"change": "none expected; confirm the mirror resolves the second #include and that every cultmath_iv_* finds its C# twin (a mirror without a twin fails Assert.Contains MirrorOnly)."
|
||||
}
|
||||
],
|
||||
"authority_map": {
|
||||
"owner": "CultMath owns interval arithmetic and the noise bounds in C# and HLSL (and GLSL by derivation). The Lipschitz constant is owned by the committed measurement test; the kernel of snoise owns its value.",
|
||||
"inputs": [
|
||||
"the existing snoise(float3) value function; snoise_grad for the measurement test only",
|
||||
"seeded random points and intervals in tests"
|
||||
],
|
||||
"outputs": [
|
||||
"cultmath_iv_* and the two ball bounds, each enclosing its function over its input region",
|
||||
"three printed numbers for the report: the Lipschitz max, the tightness ratios, the evaluation saving"
|
||||
],
|
||||
"derived_state": [
|
||||
"CULTMATH_SNOISE_LIPSCHITZ is derived from the snoise kernel; a kernel change must re-run MeasureLipschitz and re-pin",
|
||||
"shaders/CultMath.glsl (if the lowering has landed) is derived and regenerated, never edited"
|
||||
],
|
||||
"forbidden_writers": [
|
||||
"no interval op without the enclosure test and a C# twin",
|
||||
"no bound that reads snoise_grad; no value-only/gradient twin of any iv_* function",
|
||||
"no tape, bytecode, pruning, choice flag or affine form in this cut; names containing tape, prune or affine do not appear",
|
||||
"no number in a comment or design.md that a committed test did not print"
|
||||
],
|
||||
"shared_paths": [
|
||||
"the same IntervalTests enclosure harness runs every op; a new op is one entry in its table",
|
||||
"the existing HLSL mirror test covers every HLSL interval function with no new comparison path"
|
||||
],
|
||||
"deletion_line": "Nothing is deleted. The liability is one C# file, one HLSL file, two test files and a doc section; it buys the invariant intervals-enclose for every GPU consumer, and it is step 1 of the parked tapes campaign landed in advance."
|
||||
},
|
||||
"verification": {
|
||||
"builds": [
|
||||
"Yggdrasil: dotnet test packages/cultmath/tests/CultMath.Tests green (MeasureLipschitz excluded by trait); paste counts",
|
||||
"Yggdrasil: dotnet stryker --since:c49c76ee from a plain clone; 0 survivors in math.Interval.cs except listed equivalents; hand mutations for float3 arithmetic listed and killed",
|
||||
"Starfire: FXC cs_5_0 kernel over every new function; dxc -T lib_6_3 -HV 2021 on both HLSL copies"
|
||||
],
|
||||
"tests": [
|
||||
{
|
||||
"name": "IntervalTests.EveryOpEnclosesItsPoints",
|
||||
"pins": "intervals-enclose for every op, no tolerance."
|
||||
},
|
||||
{
|
||||
"name": "NoiseBoundTests.SnoiseBallEnclosesPoints / FbmBallEnclosesPoints",
|
||||
"pins": "the ball bounds enclose snoise and fbm over 2,000 balls x 64 points."
|
||||
},
|
||||
{
|
||||
"name": "NoiseBoundTests.WarpedPointsStayEnclosed",
|
||||
"pins": "a domain warp bounded by D is enclosed by enlarging the ball radius by D; the site's interval march is sound."
|
||||
},
|
||||
{
|
||||
"name": "NoiseBoundTests.LipschitzConstantPinsSampledGradients",
|
||||
"pins": "no sampled |snoise_grad| exceeds the constant; a constant lowered by 1% fails."
|
||||
},
|
||||
{
|
||||
"name": "NoiseBoundTests.IntervalSkipHalvesEvaluations",
|
||||
"pins": "the adaptive march needs <= half the evaluations of the dense march for the same transmittance within 1e-3."
|
||||
},
|
||||
{
|
||||
"name": "HlslSourceCompatibilityTests.EveryMirrorFunctionMatchesCSharpMath (existing)",
|
||||
"pins": "every cultmath_iv_* and both bounds match C# bit for bit."
|
||||
}
|
||||
],
|
||||
"negative": [
|
||||
{
|
||||
"pattern": "tape|prune|affine|choice",
|
||||
"scope": "packages/cultmath/src/CultMath/math.Interval.cs and shaders/CultMath.Interval.hlsl: 0 matches (case-insensitive)."
|
||||
},
|
||||
{
|
||||
"pattern": "snoise_grad|fbm_grad",
|
||||
"scope": "math.Interval.cs and CultMath.Interval.hlsl: 0 matches; the bounds use values only."
|
||||
},
|
||||
{
|
||||
"pattern": "spherical_erosion|AdvancedErosionFilter",
|
||||
"scope": "packages/cultmath: 0 matches (HlslMirrorTests' standing rule)."
|
||||
},
|
||||
{
|
||||
"pattern": "git diff --name-only c49c76ee..HEAD",
|
||||
"scope": "only packages/cultmath/** (and shaders/CultMath.glsl if regenerated); no other package or src tree."
|
||||
}
|
||||
],
|
||||
"operator": []
|
||||
},
|
||||
"estimate": {
|
||||
"lines_added": 900,
|
||||
"lines_removed": 0,
|
||||
"dependencies_added": [],
|
||||
"dependencies_removed": [],
|
||||
"formats_added": [],
|
||||
"formats_removed": [],
|
||||
"targets_added": [],
|
||||
"targets_removed": []
|
||||
},
|
||||
"rulings": [],
|
||||
"questions": []
|
||||
}
|
||||
246
docs/cultmath-interval-ground-cut-site-ground.r3.spec.json
Normal file
246
docs/cultmath-interval-ground-cut-site-ground.r3.spec.json
Normal file
|
|
@ -0,0 +1,246 @@
|
|||
{
|
||||
"campaign": "cultmath-tapes",
|
||||
"cut": "site-ground",
|
||||
"revision": 3,
|
||||
"title": "Site ground r3: A cloud volume carved by one negative pseudo-Gaussian sphere, a sun at the hollow's bottom lights the walls and orbits, the camera follows low inside; pre-pass, camera-aware TAA",
|
||||
"repo": "GameCult/gamecult-site",
|
||||
"branch": "main",
|
||||
"base": "535d170",
|
||||
"depends_on": [
|
||||
"site-masthead:cut_spec:wash-home-only.r1",
|
||||
"cultmath-tapes:cut_spec:glsl-lowering.r2",
|
||||
"cultmath-tapes:cut_spec:interval-ops.r3"
|
||||
],
|
||||
"first": [
|
||||
"Map: F:/Projects/CultLib/docs/cultmath-interval-ground-cut.md, 'Pass 3' (the void scene, the composed bound, the pre-pass, the budget), then 'The shader design' for what pass 3 does not restate (sampled wash, palette input, pausing, contrast). Rulings in force: cultmath-tapes:ruling:operator-ground-void-brush (the scene), operator-tile-amortized-march (the march), site-masthead:ruling:operator-chromeless-column; wash-home-only's authority map. Re-pin base to main after wash-home-only lands. Stardust and DoF stay the next cut; leave the named composite slot. r2's token, readback, controller, vendoring, parity and fallback items stand unless this revision names them.",
|
||||
"The original, read once (Aetheria at e6181c11, 2021-03-13, Assets/Scenes/Main Menu.unity; Prefabs/RPG/Planets/Sun.prefab; Materials/Brushes/Gravity Well.mat, Main Menu Sun Fog Tint.mat, Main Menu Ambient Fog Tint.mat, Sector Boundary Fog.mat; Materials/Fog Marching Main Menu.mat; Shaders/Raymarching/VolumeRender.shader at that commit; Shaders/Brushes/PowerBrush.shader). What survives, in the original's units: the brush is PowerBrush (1 - x^2)^16 with depth 40 over radius 256 (half depth at r = 52, pseudo-Gaussian sigma about 45), the sun's own gravity-well child; a wide boundary bowl (depth 75, power 0.25, radius 1500) is flat across the scene and acts as a constant 75; floor offset -16.46, floor blend 39.6, so the fog top is at y = -91 outside the void and dips to -131 at the sun; the sun sphere (radius 12.5) sits at y = -130, the bottom of the void.",
|
||||
"What survives (continued): the sun is a child of 'Center', which rotates 5 degrees per second about y (72 s period), at orbit radius 175; the camera is a Cinemachine vcam following the sun (framing transposer, distance 150, damping 10, handheld noise amplitude 1 at frequency 0.25) and looking at 'Look Target' (0, -130, 0), the orbit centre at the sun's depth; the saved camera sits at y = -27, 64 above the fog top. The lighting was authored, not marched: the sun's 'Fog Tint' brush (1 - x^2)^3, depth 2, radius 128, colour (1, 0.4, 0.1) orange, painted into the tint map, times a scene-wide ambient tint (0.18, 0.59, 1) blue, depth 0.01. Stardust: 256^2 particles, spacing 2, floor -60, ceiling 0, height exponent 800 / (ceiling + wellDepth) so particles climb higher where the well is deeper (the void fills with stardust). Noise: strength 150, frequency 0.01, safety 50. Not surviving: the 2021 d() details, the tint map's runtime contents, the video.",
|
||||
"The field (ruling operator-void-true-cavity: a spherical hollow inside a cloud volume that surrounds it on every side, not the 2021 bowl). Units are the original's. Outer volume: an unbounded uniform fill, chosen over a shell because every ray then ends in a wall and the march terminates by opacity, never by a far plane; Z1 = |camera - c_v| + Rc + 6/K (614 at the shipped point) bounds the pre-pass range and is past opacity for every ray, so the analytic body step below always terminates. The carve is the pseudo-Gaussian brush g(d) = (1 - (d / Rc)^2)^e, d = |p - c_v|, density = K max(0, 1 - CARVE g(d')), authored by two knobs: the hollow radius Rh (density exactly 0 inside; Rh = Rc sqrt(1 - CARVE^(-1/e))) and the ramp width S (density full at Rh + S; set by the exponent: e = 4 gives S = 1.3 Rh, e = 0.25 gives S = 0.12 Rh).",
|
||||
"Shipped (Q9 in the map, option (a) pending the operator): Rh = 198, S = 50, so Rc = Rh + S = 248 and e = -ln CARVE / ln(1 - (Rh / Rc)^2) = 0.40; CARVE = 1.5, K = 1/30: a wall is opaque within about 150 units of full density. The ramp and the noise fade band are both S wide; nothing void-shaped is authored twice (interval-ops r3, finding shipped-void-two-scenes). Noise displaces the wall only: fade(d) = smoothstep(Rh - S, Rh, d), d' = d + A fade(d) n(warp(p)), A = 20, F0 = 0.01.",
|
||||
"Scene motion. The sun orbits the origin at radius 175 in xz with period 72 s (5 degrees per second, the original's Center pivot). The cavity centre is c_v = sun + (0, Rh - 12.5, 0): the sun sphere (radius 12.5) rests on the hollow's bottom and the hollow moves with it. The camera follows the sun 120 behind it along the orbit's tangent and 45 above it, so it sits 186 from c_v, 12 inside the hollow (the handheld drift is 2 units, two low-frequency snoise on time), low in the cavity, looking at the sun's position plus (0, 60, 0) so the lit lower wall and the dark upper wall share the frame. The 2021 follow distance 150 and height 25 do not fit a hollow a camera can stand in; 120 and 45 are the re-derivation, and the report says so. worldAt(t) in ground.js is the one owner of sun, cavity and camera, uploaded as uniforms; the shaders never integrate motion.",
|
||||
"The flow field, authored around the void: flow(xz) = SWIRL * tangent(xz - sun.xz) * (1 - (r / Rw)^2)^2 + GLOBAL * (snoise(xz Ff + o1), snoise(xz Ff + o2)) (the swirl is largest mid-slope and zero at the rim and the centre; the global term is r2's). The flow texture is a world-space window of side 4 Rw centred on the sun, quarter of the canvas resolution, re-rendered every frame; warp, hue, motion vectors and (next cut) the stardust read it, so D4 holds with a moving scene. D = FLOW_MAX * PERIOD / 2 as before, with FLOW_MAX the authored maximum of the swirl plus the global amplitude.",
|
||||
"The march (tile pre-pass, interval-ops r2's design). Pre-pass at W/8 x H/8: per tile, the loop over the slab's cell ranges (uniform cells, StepDense = min(10, S / 4) = 10, 62 cells to Z1 = 614 along +view depth; the mask has 96 bits): the envelope probe first (exact box: y and xz ranges by cultmath_iv_mul of the depth and slope intervals, d's interval is the box's least and greatest distance to c_v, exact; g, fade and the carve are monotone in it), then the noise ball (cultmath_iv_frustum_ball with D, cultmath_iv_snoise_ball) only when fade.hi > 0 and L r F0 leaves room to prove anything; writes the 96-bit mask of cells not proven empty to an RGBA32UI texel's first three words, and in the fourth word the body-start cell: the first cell whose own bound is a positive point and whose slice to Z1 is one too (the envelope with the free noise interval proves density exactly K for the rest of the range), 0xFFFFFFFF when none (interval-ops r3, ruling operator-analytic-wall-body).",
|
||||
"(March, continued.) Main pass: texelFetch the mask, then march the unmasked range with the footprint step Delta(z) and the octave weights (next item), the per-frame sample count capped by the budget S_budget and the start jittered so TAA completes what one frame does not; masked cells are skipped exactly; at the body-start cell take one analytic Beer-Lambert step, T *= exp(-K (Z1 - z) |dir|) with K the field's pointwise envelope value there (no probe in the main pass), and stop; integrate transmittance and the depth-weighted mean distance, apply the light. Every tile's interior cells retire in a few envelope probes and its wall cells are marked; there are no sky tiles. Behind a fully transmissive pixel the resolve shows --gamecult-nebula-base; by construction only an unfinished ray (budget exhausted before the wall, measured, must be under 1%) reaches it.",
|
||||
"Footprint LOD (the operator's challenge, map 'Footprint LOD'): theta_px = 2 tan(fov/2) / H; the footprint at distance z is z theta_px. Step: Delta(z) = max(k z theta_px, min(S / 4, lambda_fine(z) / 2)), k = 4: never finer than four footprints, otherwise the finer of the two content limits (four samples across the ramp, two per wavelength of the finest live octave). Octaves: octave i of wavelength lambda_i carries weight w_i(z) = 1 - smoothstep(lambda_i / (2m), lambda_i / m, z theta_px), m = 4: one smooth blend per octave, no popping; TAA hides per-frame sparsity. The weights are part of the field, so the bound encloses the truncated field exactly: the noise interval over a slice is the sum over octaves of iv_mul([w_i(z1), w_i(z0)], iv_snoise_ball(c F_i, r F_i)), w_i monotone in z. At the shipped parameters (wavelengths 100 and 25, z <= 2 Rc) every weight is 1 in the frustum and the content limits set the step; the footprint bites when S < 4 k z theta_px.",
|
||||
"Where the scene sits and what to turn (Imagination's model, scratchpad cavity_model.py; the test and the browser confirm): interval-ops r2 measured the shipped point at 16.45 LOD steps and 26.6 snoise per pixel against 36.3 fixed steps (2.21x); r3's analytic body is predicted to bring the steps to about 12.5 (2.6-3.3x), snoise unchanged; the wall's step is set by S / 4 and the detail half-wavelength, not by distance; the browser confirms or refutes. Cheaper without losing the mood, in order: (1) a lower per-frame S_budget, which LOD and the mask make nearly lossless (S_budget = 4 converges in about three frames at the walls); (2) a thinner ramp S (S = 10 is 3.2x on cost but reads as a surface; 25-50 keeps the fog); (3) a longer detail wavelength or no detail octave near the far wall (the 12.5-unit half-wavelength is the floor for S >= 50); (4) a larger hollow (Rh = 1000: 2.5x) costs nothing per pixel and changes the composition. Camera offset barely matters at these scales.",
|
||||
"Lighting, the cheapest version that keeps it moody (the original's own mechanism, made 3D): at each sample, light = SUN_COLOUR * (1 - (d / Rl)^2)^3 for d = |p - sun| < Rl, Rl = Rh = 198 (the original's 128 scaled with the hollow), plus AMBIENT * ambientTint; colour = density * (light + ambient) * hue(flow). No light march: zero extra snoise, one length and one pow per sample. The lower wall within Rl of the sun glows and the upper wall stays dark because the pulse is zero beyond Rl, which is the moody split; the sun inside the hollow is occluded by nothing, so the sun itself is a small additive disc drawn in the resolve at its projected position, occluded by the accumulated transmittance along its ray. Not in this cut, measured before it is ever added: one envelope-only transmittance sample toward the sun per primary sample (self-shadowing by the bowl's geometry), about +25% march cost; it is desktop-only if ever.",
|
||||
"TAA with a moving camera. ground.js uploads this frame's and the previous frame's view-projection. For each pixel the resolve reconstructs the world point at the march's depth-weighted mean distance (written by the main pass into a second history channel, R16F), moves it back by the field motion (p + flow(p) * dt: the pattern moves at -flow), projects it with the previous VP and fetches history at that uv. The same 3x3 min/max clamp, alpha = max(1/frames, 1/32), out-of-bounds alpha 1; history reset on resize, first frame and budget step. Transmittance, colour and the depth channel are all reprojected by the one motion vector. ?ground=debug-mv shows |mv| with the camera moving and the flow frozen, and with the flow moving and the camera frozen, so both terms are seen separately.",
|
||||
"Stardust distribution and the sun disc are the next cut (site-stardust), authored to the void: particles spawned in the bowl's volume with the original's height rule (more headroom where the well is deeper), lit by the same pulse, moving with the swirl. This cut leaves the composite slot and the depth history they need.",
|
||||
"Fit with the tokens. Inputs: --gamecult-nebula-0 (orange 255 138 42) is SUN_COLOUR; --gamecult-nebula-2 (sky 89 183 255) is the ambient tint; --gamecult-nebula-1 (violet 109 96 255) is the cloud hue's second pole; --gamecult-nebula-base the sky. Outputs from the 8x8 readback as r2, with one change: --gamecult-light-0-at is written from the sun's projected screen position (quantised to 1%, at most 2 Hz), so the CSS wash's main light follows the sun while the shader runs; --gamecult-light-0 and -a come from the texel there; lights 1 and 2 keep their seed positions and sample their colours. When the canvas is absent the seeds paint a still of the same composition (the seed light-0-at is the sun's mean screen position).",
|
||||
"Prove in the browser pane, in addition to r2's list: with ?ground=debug the pre-pass's mean probes per tile and the fraction of cells masked, and the mean snoise per pixel and the fraction of samples placed in the wall ramp against a dense-reference frame (?ground=dense: no pre-pass, S samples over the whole slab; the two converged frames' mean luminance agree within 1/255; the masked frame's per-frame variance at the walls is lower, printed); the camera reprojection test above; the orbit (after 36 s the sun's screen position has moved half an orbit and the TAA shows no smear at the walls); the contrast clamp with the lit cavity (max luminance <= 0.035 still holds; the sun disc is exempt only inside its own radius, which the clamp test masks and reports)."
|
||||
],
|
||||
"deletes": [
|
||||
{
|
||||
"path": "site/quartz/styles/custom.scss",
|
||||
"lines": 6,
|
||||
"note": "ritual body block 119-124: its own background goes; its seeds live under :root:has(body[data-slug]) (r2)."
|
||||
},
|
||||
{
|
||||
"path": "site/quartz/styles/custom.scss",
|
||||
"lines": 9,
|
||||
"note": "body 10-27: the literal colours and stops become token references (r2)."
|
||||
}
|
||||
],
|
||||
"keeps_moves": [
|
||||
"r2's tokens, sampled wash, controller, vendoring (now two files: the site vendors CultMath.glsl only, MIT; the parity run concatenates CultMath.Phacelle.glsl for the phacelle family), parity flags, fallbacks and the contrast clamp: unchanged except where this revision names them.",
|
||||
"--gamecult-wash and the index override from wash-home-only: untouched.",
|
||||
".page::before, the tour/Pitch VN ground, the Thing deck's .hero-bg, the masthead, the engine: untouched.",
|
||||
"The CSS wash stays the ground when the canvas is absent, not yet drawn, or removed by the controller."
|
||||
],
|
||||
"adds": [
|
||||
"site/quartz/components/GameCultGround.tsx: as r2.",
|
||||
"site/quartz/static/ground/ground.js (~500 lines): r2's passes plus worldAt(t) (sun, void, camera), the two view-projections, the pre-pass, the mask texture, the depth history, the sun-disc composite and the light-0-at writer.",
|
||||
"site/quartz/static/ground/flow.frag.glsl (world-space window, swirl plus global), prepass.frag.glsl (the tile loop, mask and body-start out), cloud.frag.glsl (masked sampling, light, depth out), taa.frag.glsl (camera plus flow reprojection), downsample.frag.glsl.",
|
||||
"site/quartz/static/ground/CultMath.glsl and glsl-parity.json, vendored from CultLib at interval-ops r3's head or later (cultmath_iv_frustum_ball with its float32 widening present).",
|
||||
"scripts/ground/check-cultmath-glsl.ps1: the vendoring drift check.",
|
||||
"custom.scss and docs/brand-design-language.md: as r2, with the void composition named in the brand doc's ground paragraph."
|
||||
],
|
||||
"file_changes": [
|
||||
{
|
||||
"location": {
|
||||
"path": "site/quartz/styles/custom.scss",
|
||||
"line": 4,
|
||||
"end_line": 8
|
||||
},
|
||||
"change": ":root block: the fifteen ground seeds and --gamecult-ground-mean; light-0-at seeded at the sun's mean screen position."
|
||||
},
|
||||
{
|
||||
"location": {
|
||||
"path": "site/quartz/styles/custom.scss",
|
||||
"line": 10,
|
||||
"end_line": 31
|
||||
},
|
||||
"change": "body: four nebula input tokens; radials and the linear gradient reference the ground tokens (r2)."
|
||||
},
|
||||
{
|
||||
"location": {
|
||||
"path": "site/quartz/styles/custom.scss",
|
||||
"line": 103,
|
||||
"end_line": 124
|
||||
},
|
||||
"change": "ritual block: background declaration deleted; :root:has(body[data-slug]) carries its seeds and nebula inputs (r2)."
|
||||
},
|
||||
{
|
||||
"location": {
|
||||
"path": "site/quartz.layout.ts",
|
||||
"line": 19
|
||||
},
|
||||
"change": "header: [GameCultThemeLock(), GameCultGround(), GameCultMasthead()]."
|
||||
},
|
||||
{
|
||||
"location": {
|
||||
"path": "docs/brand-design-language.md",
|
||||
"line": 69,
|
||||
"end_line": 84
|
||||
},
|
||||
"change": "wash section rewritten: the void scene, the sampled wash, the seeds, the nebula inputs and what each drives."
|
||||
}
|
||||
],
|
||||
"authority_map": {
|
||||
"owner": "The shader owns the ground. ground.js owns worldAt(t) (sun, void, camera), the flow texture, the pre-pass mask, the march, the TAA, the readback and the sampled tokens; custom.scss owns the four nebula inputs, --gamecult-wash and the seeds; CultLib owns every noise and interval function; the composed bound in prepass.frag.glsl is built from cultmath_iv_* only.",
|
||||
"inputs": [
|
||||
"the four nebula tokens and --gamecult-wash (computed on body)",
|
||||
"prefers-reduced-motion, visibilityState, canvas size, devicePixelRatio, elapsed time",
|
||||
"measured GPU frame time (timer query, fence, or rAF cadence)",
|
||||
"the shader's own 8x8 readback and the sun's projected position",
|
||||
"the vendored CultMath.glsl at its pinned CultLib commit"
|
||||
],
|
||||
"outputs": [
|
||||
"one opaque moving canvas under the page, luminance <= 0.035 outside the sun disc",
|
||||
"the fifteen ground tokens and --gamecult-ground-mean on :root inline, at most 2 Hz; light-0-at follows the sun",
|
||||
"debug, dense-reference and parity readbacks (console, flag only)"
|
||||
],
|
||||
"derived_state": [
|
||||
"sun, void and camera positions are derived from time by worldAt(t); nothing integrates motion frame to frame",
|
||||
"the tile mask is derived each frame from that frame's camera and the field; it is never carried across frames",
|
||||
"the flow texture is the one owner of motion: warp, hue, motion vectors and the stardust read it",
|
||||
"the TAA history (colour, transmittance, depth) is a cache reprojected by camera and flow; reset on resize, first frame and budget step",
|
||||
"the ground tokens are derived from the readback while the shader runs; the seeds are the fallback; the shader never reads them",
|
||||
"S and dpr are derived from measurement within the session; the sessionStorage token set is a cache"
|
||||
],
|
||||
"forbidden_writers": [
|
||||
"no colour, alpha, position or radius literal in ground.js or any GLSL file; the scene's dimensions (H0, Dw, Rw, F, S, Rl, orbit radius, period, camera offset) are named constants in one place in ground.js, uploaded as uniforms",
|
||||
"no sample placed in a masked cell; no probe in the main pass; no early-out of the pre-pass on transmittance",
|
||||
"no light march in this cut; the light is the analytic pulse",
|
||||
"no read of the ground output tokens by the shader or ground.js except the seed read before the first readback",
|
||||
"no userAgent, platform or maxTouchPoints; no class or attribute set on body or html; no second wash token; no second flow evaluation; no noise or interval function defined in the site's GLSL",
|
||||
"no synchronous readPixels to client memory; one requestAnimationFrame scheduler; localStorage never"
|
||||
],
|
||||
"shared_paths": [
|
||||
"every page paints one canvas and one token set; the ritual essays differ only in seeds and inputs",
|
||||
"slow device, hidden tab, reduced motion, missing WebGL2 and missing half-float all pass through the one controller",
|
||||
"the 8x8 readback and the sun projection are the only paths from the shader to CSS",
|
||||
"the pre-pass and the main pass read the same uniforms from the same worldAt(t); the dense-reference mode differs only by skipping the mask"
|
||||
],
|
||||
"deletion_line": "As r2: the ritual block's own background and the body literals go in the same commit the tokens are declared. Nothing else in the engine or content changes. Against pass 2's design this revision removes the static camera and the everywhere-clouds field; it adds one pre-pass, one mask texture, one depth history channel and the scene function."
|
||||
},
|
||||
"verification": {
|
||||
"builds": [
|
||||
"Deploy Quartz green on the landing commit: gh run list -R GameCult/gamecult-site -w \"Deploy Quartz\" -L 1",
|
||||
"scripts/ground/check-cultmath-glsl.ps1 exits 0 against a CultLib checkout at the pinned commit",
|
||||
"the built stylesheet contains rgb(var(--gamecult-light-0) / calc(var(--gamecult-light-0-a) * var(--gamecult-wash))) verbatim and the ritual :root:has rule"
|
||||
],
|
||||
"tests": [
|
||||
{
|
||||
"name": "browser pane, /?ground=debug: max relative luminance over the canvas outside the sun disc after 32 frames <= 0.035",
|
||||
"pins": "text contrast with the lit cavity."
|
||||
},
|
||||
{
|
||||
"name": "browser pane, /?ground=debug vs /?ground=dense: converged mean luminance within 1/255; steps and snoise per pixel printed for both, debug at most half of dense's steps; mask fraction printed",
|
||||
"pins": "the mask culls only provably empty cells; the shipped march takes at most half the fixed-step steps; the saving on the shipped scene is a number."
|
||||
},
|
||||
{
|
||||
"name": "browser pane, /?ground=debug-mv: |mv| non-zero with the camera moving and flow frozen, and with flow moving and camera frozen; zero under reduced motion",
|
||||
"pins": "both reprojection terms are live and separable."
|
||||
},
|
||||
{
|
||||
"name": "browser pane, / for 40 s: the sun's screen position moves about half an orbit; no history smear at the walls (3x3 clamp); light-0-at on :root follows within 2 s",
|
||||
"pins": "the moving scene converges and the CSS wash follows the sun."
|
||||
},
|
||||
{
|
||||
"name": "browser pane, /?ground=parity: every fixture family within its tolerance class on WebGL2, cultmath_iv_frustum_ball exact; numbers and GPU string in the report",
|
||||
"pins": "GLSL = C# on a device, including the tile ball."
|
||||
},
|
||||
{
|
||||
"name": "browser pane, /?ground=parity-wash and a ritual essay: canvas vs CSS seed wash within 2/255 at 16 points with density 0 and the sun disc off",
|
||||
"pins": "the seeds and the shader's base agree."
|
||||
},
|
||||
{
|
||||
"name": "reduced motion, hidden tab, WebGL2 disabled, sessionStorage cleared: as r2",
|
||||
"pins": "every fallback goes through the controller."
|
||||
},
|
||||
{
|
||||
"name": "git diff base..head --stat: custom.scss, quartz.layout.ts, docs/brand-design-language.md, the new component, static/ground/*, scripts/ground/* only",
|
||||
"pins": "no engine, content or masthead change."
|
||||
}
|
||||
],
|
||||
"negative": [
|
||||
{
|
||||
"pattern": "#[0-9a-fA-F]{6}\\b|rgba?\\(|\\b(255|138|109|183)\\b",
|
||||
"scope": "site/quartz/static/ground/*.js and *.glsl: 0 matches."
|
||||
},
|
||||
{
|
||||
"pattern": "gamecult-ground-|gamecult-light-",
|
||||
"scope": "site/quartz/static/ground/*.glsl: 0 matches; in ground.js only inside the token writer and the seed read."
|
||||
},
|
||||
{
|
||||
"pattern": "userAgent|navigator\\.platform|maxTouchPoints|localStorage|setInterval|classList|setAttribute\\(",
|
||||
"scope": "site/quartz/static/ground/ground.js: 0 matches."
|
||||
},
|
||||
{
|
||||
"pattern": "cultmath_iv_",
|
||||
"scope": "cloud.frag.glsl, taa.frag.glsl, flow.frag.glsl: 0 matches; the bound lives only in prepass.frag.glsl."
|
||||
},
|
||||
{
|
||||
"pattern": "float cultmath_|vec4 cultmath_|float snoise|hash\\(",
|
||||
"scope": "every site .frag.glsl: 0 matches; cultmath_* is defined only in the vendored CultMath.glsl."
|
||||
},
|
||||
{
|
||||
"pattern": "Mozilla|MPL|cultmath_phacelle",
|
||||
"scope": "site/quartz/static/ground/CultMath.glsl: 0 matches; the site vendors the MIT file."
|
||||
},
|
||||
{
|
||||
"pattern": "radial-gradient\\([^)]*rgba?\\([0-9]",
|
||||
"scope": "site/quartz/styles/custom.scss, body rule and ritual block: 0 matches."
|
||||
},
|
||||
{
|
||||
"pattern": "gamecult-titlebar|gamecult-nav-link|sidebar|composite|GameCult-Quartz",
|
||||
"scope": "git diff base..head changed lines: 0 matches."
|
||||
}
|
||||
],
|
||||
"operator": [
|
||||
"open / on the desktop and on the phone; say whether the hollow, the sun's orbit and the camera's height read as the old main menu's mood (uniforms: A, SWIRL, Rl, CARVE, the camera offset)",
|
||||
"on the phone with ?ground=debug, read the logged GPU ms per pass and the controller's final S/dpr; say whether it got warm after five minutes",
|
||||
"say whether the analytic light is moody enough or the self-shadowing sample (desktop only) should be tried",
|
||||
"navigate / -> /Blog -> back; say whether the ground is continuous (Q5)"
|
||||
]
|
||||
},
|
||||
"estimate": {
|
||||
"lines_added": 1250,
|
||||
"lines_removed": 15,
|
||||
"dependencies_added": [],
|
||||
"dependencies_removed": [],
|
||||
"formats_added": [
|
||||
"GLSL ES 3.00 shader files in static/ground",
|
||||
"vendored glsl-parity.json",
|
||||
"one sessionStorage key holding the last sampled token set",
|
||||
"an RGBA32UI tile-mask texture and an R16F depth history (GPU-side only)"
|
||||
],
|
||||
"formats_removed": [],
|
||||
"targets_added": [],
|
||||
"targets_removed": []
|
||||
},
|
||||
"rulings": [
|
||||
"cultmath-tapes:ruling:operator-ground-void-brush",
|
||||
"cultmath-tapes:ruling:operator-void-true-cavity",
|
||||
"cultmath-tapes:ruling:operator-tile-amortized-march",
|
||||
"cultmath-tapes:ruling:operator-analytic-wall-body",
|
||||
"cultmath-tapes:ruling:operator-split-phacelle",
|
||||
"site-masthead:ruling:operator-chromeless-column"
|
||||
],
|
||||
"questions": [
|
||||
"Q4 in the map: palette input tokens (a, recommended)",
|
||||
"Q5 in the map: carry the last sampled wash across page loads (a, recommended)",
|
||||
"Q9 in the map: the one shipped void (a, recommended: Rh 198, S 50, Rc 248, e 0.40); ruled in interval-ops r3's fork, this spec follows it"
|
||||
]
|
||||
}
|
||||
206
docs/cultmath-interval-ground-cut-site-ground.spec.json
Normal file
206
docs/cultmath-interval-ground-cut-site-ground.spec.json
Normal file
|
|
@ -0,0 +1,206 @@
|
|||
{
|
||||
"campaign": "cultmath-tapes",
|
||||
"cut": "site-ground",
|
||||
"revision": 2,
|
||||
"title": "Site ground: a per-pixel WebGL2 nebula under every page, flow-warped, interval-culled, TAA-reprojected, budget-controlled by measurement; the CSS wash is sampled from the result, seeds fall back",
|
||||
"repo": "GameCult/gamecult-site",
|
||||
"branch": "main",
|
||||
"base": "535d170",
|
||||
"depends_on": [
|
||||
"site-masthead:cut_spec:wash-home-only.r1",
|
||||
"cultmath-tapes:cut_spec:glsl-lowering.r1",
|
||||
"cultmath-tapes:cut_spec:interval-ops.r1"
|
||||
],
|
||||
"first": [
|
||||
"Map: F:/Projects/CultLib/docs/cultmath-interval-ground-cut.md, 'The shader design' (field, culling with the warp, TAA motion-aware, sampled wash, palette input), 'Budget', D4-D8, Q4 and Q5. Rulings in force: site-masthead:ruling:operator-chromeless-column; wash-home-only's authority map (no second wash token, no class toggled by script, no page rule setting a radial alpha). Re-pin base to main after wash-home-only lands; line numbers below are from 535d170; re-read by selector. Stardust and DoF are the next cut: leave the resolve pass with a named, empty composite slot for them (a uniform-gated branch is not needed; a comment and a function stub are).",
|
||||
"Aetheria reference, read once, copy nothing: Volumetric.cginc:165-221 (two-phase flow-map warp, tri2 cross-fade), :130-135 (globalFlow); Raymarching/CloudShader.shader:83-104 (integration) and :261-314 (what not to do: gamma 0.5 clip, fixed 0.05 blend, packed depth, the density2 bug at :311).",
|
||||
"Engine facts to confirm before writing: how GameCult-Quartz bundles a component's afterDOMLoaded and whether a dynamic import() of /static/ground/ground.js is allowed, else emit a module script tag; site/quartz/static/** served at /static/**; enableSPA false (quartz.config.ts:15). Local build: scripts/quartz/quartz.ps1 dev.",
|
||||
"Tokens. Inputs (Q4 a), on body in custom.scss beside --gamecult-wash: --gamecult-nebula-0/1/2 (\"255 138 42\", \"109 96 255\", \"89 183 255\") and --gamecult-nebula-base (#07111a). Outputs with seeds, on :root: --gamecult-ground-0/1/2 (#03070d #07111a #09141f), and for N in 0..2 --gamecult-light-N (rgb triple), -a (0.18/0.16/0.14), -at (\"78% 14%\"/\"18% 10%\"/\"52% 0%\"), -r (18%/24%/28%), plus --gamecult-ground-mean (#07111a). The body background becomes radial-gradient(circle at var(--gamecult-light-0-at), rgb(var(--gamecult-light-0) / calc(var(--gamecult-light-0-a) * var(--gamecult-wash))), transparent var(--gamecult-light-0-r)) x3 over linear-gradient(180deg, var(--gamecult-ground-0) 0%, var(--gamecult-ground-1) 44%, var(--gamecult-ground-2) 100%).",
|
||||
"Ritual essays: their seeds go under :root:has(body[data-slug=\"Blog/...\"]) for the three slugs (yellow 255 178 30 .15 at 78% 8% 24rem; cobalt 49 88 255 .22 at 18% 4% 30rem; violet 91 54 184 .19 at 44% 20% 34rem; stops #030414 0%, #070b24 42%, #040514 100%; nebula inputs likewise overridden to yellow/cobalt/violet and base #050614). The ritual block's own background declaration is deleted; it inherits body's.",
|
||||
"ground.js owns: WebGL2 context on #gamecult-ground (alpha:false, antialias:false, powerPreference 'low-power'); capability check (WebGL2, EXT_color_buffer_half_float or float); input token read via getComputedStyle(document.body) -> uniforms; the flow texture pass (quarter res, RG16F, two snoise per texel, once per frame); the march pass; the TAA resolve with reprojection; the 8x8 downsample and the async PBO readback; the token writer on document.documentElement.style; the scheduler (30 fps cadence, visibilityState pause, reduced-motion freeze and stop at 32 frames); the budget controller; the debug flag (?ground=debug) and parity flags.",
|
||||
"Sampled wash: after the resolve, draw the final frame into an 8x8 RGBA8 target; gl.readPixels into a PIXEL_PACK_BUFFER; gl.fenceSync; on later frames poll getSyncParameter(SYNC_STATUS) and only when SIGNALED call getBufferSubData. Never readPixels to client memory directly (that stalls). At most 2 Hz. Compute the token values as the map states (row means for the stops; light colour and excess at the seed light's centre texel; the mean for --gamecult-ground-mean) and write them with setProperty on :root only when a value moved by more than 1/255. Q5 (a): keep the last written set in sessionStorage under one key and apply it on load before the first frame; it is a cache, and a missing or malformed entry means the seeds.",
|
||||
"Budget controller, one function, one state machine: GPU time per frame by EXT_disjoint_timer_query_webgl2 when present, else a fenceSync after the resolve polled to completion, else rAF cadence. Over a 60-frame window: if the median exceeds the budget (4.0 ms), step down: S 16 -> 8 -> 4, then dpr -> 1 (Q2), then remove the canvas (the seeds paint). Never step up within a session. A median rising 50% over 5 minutes also steps down. No storage of the verdict, no userAgent, no maxTouchPoints.",
|
||||
"cloud.frag.glsl: #version 300 es; precision highp float; precision highp int; the vendored CultMath.glsl is concatenated by ground.js before this file's body. The field, warp, interval march (ball radius F0 * (Δ/2 + D) with D = FLOW_MAX * PERIOD / 2) and integration exactly as the map's pseudocode; hue from the flow texture's channels mixed over the three nebula inputs; uniforms: resolution, time, dt, frame, jitter, S, intensity, nebula colours, base, Z0/Z1, F0, CUTOFF, K, PERIOD, FLOW_MAX. flow.frag.glsl: the two low-frequency snoise. taa.frag.glsl: motion vector from the flow texture (mv = project(-flow * dt)), history fetched at uv - mv, 3x3 min/max clamp, alpha = max(1/frames, 1/32), out-of-bounds alpha 1; writes new history and the screen (luminance clamp 0.035) via drawBuffers or two draws.",
|
||||
"Vendoring (D3): site/quartz/static/ground/CultMath.glsl byte-equal to CultLib shaders/CultMath.glsl at the commit named in its first line. scripts/ground/check-cultmath-glsl.ps1 diffs it against git show <sha>:packages/cultmath/shaders/CultMath.glsl from a CultLib checkout and exits non-zero on drift.",
|
||||
"Parity on the device: with ?ground=parity, ground.js evaluates the vendored fixture (CultLib tests/CultMath.Tests/fixtures/glsl-parity.json) one pixel per point, reads back float bit patterns, and reports per function the max ulp distance and the count outside its tolerance class. With ?ground=parity-wash, density and stardust are forced to 0 and the flow frozen; the canvas must equal the CSS seed wash within 2/255 at 16 points on / and on a ritual essay (this pins that the seed values and the shader's base agree at zero density, which is what the fallback promises).",
|
||||
"Prove in the browser pane: max relative luminance after 32 frames on / at intensity 1 (<= 0.035); the parity-wash probe; the debug readback (mean evals per pixel, unfinished-ray fraction < 1%); the token writer (after 2 s on /, :root's inline style carries all fifteen tokens and --gamecult-ground-mean, each within the expected range, and getComputedStyle(body).backgroundImage resolves to the sampled values); the motion test (with ?ground=debug-mv the resolve writes |mv| into red: non-zero where flow is non-zero, zero under reduced motion); GPU ms per pass with the timer query at the pane's desktop size and at the mobile preset's pixel count. Phone GPU time is operator verification."
|
||||
],
|
||||
"deletes": [
|
||||
{
|
||||
"path": "site/quartz/styles/custom.scss",
|
||||
"lines": 6,
|
||||
"note": "ritual body block 119-124: its own background (three radials and the linear gradient) goes; its seeds live under :root:has(body[data-slug]) and it inherits body's ground."
|
||||
},
|
||||
{
|
||||
"path": "site/quartz/styles/custom.scss",
|
||||
"lines": 9,
|
||||
"note": "body 10-27: the six literal colours and three literal stops leave as literals (rewritten as token references in the same lines; counted 9 removed, 9 added)."
|
||||
}
|
||||
],
|
||||
"keeps_moves": [
|
||||
"--gamecult-wash and the index override from wash-home-only: untouched; the shader reads it as intensity and the CSS wash still multiplies by it.",
|
||||
".page::before (the grid overlay), the tour/Pitch VN ground, the Thing deck's .hero-bg, the masthead, the engine: untouched.",
|
||||
"The CSS wash stays the ground when the canvas is absent, not yet drawn, or removed by the controller; it renders the sampled tokens when there are any and the seeds otherwise.",
|
||||
"docs/brand-design-language.md 'The ground is a wash, not a flat fill' (69-84): rewritten: the ground is the shader; the CSS wash is sampled from it; the seeds are today's literal wash; the four nebula inputs are where the palette is tuned."
|
||||
],
|
||||
"adds": [
|
||||
"site/quartz/components/GameCultGround.tsx: renders <canvas id=\"gamecult-ground\" aria-hidden=\"true\"></canvas>, mounts /static/ground/ground.js after DOM load; in sharedPageComponents.header after GameCultThemeLock (quartz.layout.ts:19). Its beforeDOMLoaded script applies the sessionStorage token cache to :root if present (Q5 a), so the first paint matches the last sample.",
|
||||
"site/quartz/static/ground/ground.js (~400 lines, no dependencies, no build step): context, tokens in and out, flow/march/resolve/downsample passes, PBO readback, scheduler, controller, debug and parity modes, a named composite slot for the stardust cut.",
|
||||
"site/quartz/static/ground/flow.frag.glsl, cloud.frag.glsl, taa.frag.glsl, downsample.frag.glsl; a shared 3-vertex full-screen vertex shader inline in ground.js.",
|
||||
"site/quartz/static/ground/CultMath.glsl and glsl-parity.json, vendored from CultLib with the pin in the header.",
|
||||
"scripts/ground/check-cultmath-glsl.ps1: the vendoring drift check.",
|
||||
"custom.scss: the four nebula input tokens on body; the fifteen ground seeds plus --gamecult-ground-mean on :root with the ritual overrides under :root:has(body[data-slug]); #gamecult-ground { position: fixed; inset: 0; width: 100%; height: 100%; z-index: -1; pointer-events: none; }.",
|
||||
"docs/brand-design-language.md: the wash section rewritten as above; one paragraph on the ground shader: what it reads (inputs), what it writes (outputs), what it may not hold, and the fallback."
|
||||
],
|
||||
"file_changes": [
|
||||
{
|
||||
"location": { "path": "site/quartz/styles/custom.scss", "line": 4, "end_line": 8 },
|
||||
"change": ":root block: the fifteen ground seeds and --gamecult-ground-mean declared beside color-scheme."
|
||||
},
|
||||
{
|
||||
"location": { "path": "site/quartz/styles/custom.scss", "line": 10, "end_line": 31 },
|
||||
"change": "body: four nebula input tokens declared; radials and the linear gradient reference the ground tokens; alphas keep the wash-home-only calc."
|
||||
},
|
||||
{
|
||||
"location": { "path": "site/quartz/styles/custom.scss", "line": 103, "end_line": 124 },
|
||||
"change": "ritual block: background declaration deleted; a :root:has(body[data-slug]) rule carries its seeds and nebula inputs."
|
||||
},
|
||||
{
|
||||
"location": { "path": "site/quartz.layout.ts", "line": 19 },
|
||||
"change": "header: [GameCultThemeLock(), GameCultGround(), GameCultMasthead()]."
|
||||
},
|
||||
{
|
||||
"location": { "path": "docs/brand-design-language.md", "line": 69, "end_line": 84 },
|
||||
"change": "wash section rewritten: shader-owned ground, sampled wash, seeds, nebula inputs."
|
||||
}
|
||||
],
|
||||
"authority_map": {
|
||||
"owner": "The shader owns the ground. custom.scss owns the four nebula inputs, --gamecult-wash and the seed values; ground.js owns the flow texture, the march, the TAA, the readback and the sampled ground tokens on :root; CultLib owns every noise and interval function the field calls.",
|
||||
"inputs": [
|
||||
"the four nebula tokens and --gamecult-wash (computed on body)",
|
||||
"prefers-reduced-motion, visibilityState, canvas size, devicePixelRatio, elapsed time",
|
||||
"measured GPU frame time (timer query, fence, or rAF cadence)",
|
||||
"the shader's own 8x8 readback",
|
||||
"the vendored CultMath.glsl at its pinned CultLib commit"
|
||||
],
|
||||
"outputs": [
|
||||
"one opaque moving canvas under the page, luminance <= 0.035",
|
||||
"the fifteen ground tokens and --gamecult-ground-mean on :root inline, at most 2 Hz",
|
||||
"debug and parity readbacks (console, flag only)"
|
||||
],
|
||||
"derived_state": [
|
||||
"the ground tokens are derived from the shader's result while it runs; the seeds are the fallback; the CSS wash renders whichever is in force; the shader never reads them",
|
||||
"the flow texture is the one owner of motion: warp, hue, motion vectors (and the stardust, next cut) read it",
|
||||
"the TAA history is a cache, reprojected by the flow; reset on resize, first frame and budget step",
|
||||
"S and dpr are derived from measurement within the session; never stored",
|
||||
"the sessionStorage token set is a cache of the last sample; absent or malformed means seeds",
|
||||
"CultMath.glsl in the site is derived from CultLib at the pinned commit"
|
||||
],
|
||||
"forbidden_writers": [
|
||||
"no colour, alpha, position or radius literal in ground.js or any GLSL file",
|
||||
"no read of --gamecult-ground-* or --gamecult-light-* by the shader or by ground.js, except the seed read before the first readback",
|
||||
"no navigator.userAgent, platform, maxTouchPoints, or any device-name branch",
|
||||
"no class or attribute set on body or html by ground.js; token writes are setProperty on :root only",
|
||||
"no second wash token; no page rule setting a radial alpha; no second flow evaluation outside flow.frag.glsl",
|
||||
"no noise or interval function defined in the site's GLSL; only cultmath_* calls",
|
||||
"no synchronous readPixels to client memory; no setInterval; one requestAnimationFrame scheduler; localStorage never"
|
||||
],
|
||||
"shared_paths": [
|
||||
"home, every content page and the ritual essays paint one canvas and one token set, in CSS and in the shader",
|
||||
"slow device, hidden tab, reduced motion, missing WebGL2 and missing half-float all pass through the one controller",
|
||||
"the 8x8 readback is the only path from the shader to CSS; the beforeDOMLoaded cache apply and the live writer set the same tokens the same way",
|
||||
"the same Deploy Quartz workflow; static files ship with the overlay"
|
||||
],
|
||||
"deletion_line": "The ritual block's own background and the nine body literals go in the same commit the tokens are declared. The canvas, four shaders, ground.js and the vendored library are the whole addition; nothing else in the engine or the content changes."
|
||||
},
|
||||
"verification": {
|
||||
"builds": [
|
||||
"Deploy Quartz green on the landing commit: gh run list -R GameCult/gamecult-site -w \"Deploy Quartz\" -L 1",
|
||||
"scripts/ground/check-cultmath-glsl.ps1 exits 0 against a CultLib checkout at the pinned commit",
|
||||
"the built stylesheet contains rgb(var(--gamecult-light-0) / calc(var(--gamecult-light-0-a) * var(--gamecult-wash))) verbatim and a :root:has(body[data-slug=\"Blog/small-ritual-of-reach\"]) rule"
|
||||
],
|
||||
"tests": [
|
||||
{
|
||||
"name": "browser pane, /?ground=debug: max relative luminance over the canvas after 32 frames <= 0.035",
|
||||
"pins": "text contrast: body text keeps >= 7:1 on every ground pixel."
|
||||
},
|
||||
{
|
||||
"name": "browser pane, /?ground=parity-wash and a ritual essay: canvas vs CSS seed wash within 2/255 at 16 points with density 0 and flow frozen",
|
||||
"pins": "the seeds and the shader's base agree; the fallback promise holds."
|
||||
},
|
||||
{
|
||||
"name": "browser pane, / after 2 s: :root inline style carries the sixteen tokens; body's computed backgroundImage resolves to the sampled values; a read 1 s later differs only where the frame changed",
|
||||
"pins": "the CSS wash is sampled from the shader, at most 2 Hz, without a stall (no readPixels-to-client in the profiler)."
|
||||
},
|
||||
{
|
||||
"name": "browser pane, /?ground=parity: every fixture function within its tolerance class on WebGL2; numbers and GPU string in the report",
|
||||
"pins": "GLSL = C# on a device; the proving ground's third runtime."
|
||||
},
|
||||
{
|
||||
"name": "browser pane, /?ground=debug at desktop and the mobile preset: mean evals per pixel, unfinished rays < 1%, GPU ms per pass; ?ground=debug-mv shows motion where flow is non-zero",
|
||||
"pins": "the step budget, the interval saving with the warp, and the reprojection on the shipped field."
|
||||
},
|
||||
{
|
||||
"name": "reduced motion emulated: frames stop at 32, mv is 0, time frozen; hidden tab: no frames; WebGL2 disabled: no canvas in the DOM and the seed wash paints; sessionStorage cleared: seeds paint first",
|
||||
"pins": "every fallback goes through the controller and lands on the same CSS ground."
|
||||
},
|
||||
{
|
||||
"name": "git diff base..head --stat: custom.scss, quartz.layout.ts, docs/brand-design-language.md, the new component, static/ground/*, scripts/ground/* only",
|
||||
"pins": "no engine, content or masthead change."
|
||||
}
|
||||
],
|
||||
"negative": [
|
||||
{
|
||||
"pattern": "#[0-9a-fA-F]{6}\\b|rgba?\\(|\\b(255|138|109|183)\\b",
|
||||
"scope": "site/quartz/static/ground/*.js and *.glsl: 0 matches."
|
||||
},
|
||||
{
|
||||
"pattern": "gamecult-ground-|gamecult-light-",
|
||||
"scope": "site/quartz/static/ground/*.glsl: 0 matches; in ground.js only inside the token writer and the seed read, never in a uniform upload."
|
||||
},
|
||||
{
|
||||
"pattern": "userAgent|navigator\\.platform|maxTouchPoints|localStorage|setInterval|classList|setAttribute\\(",
|
||||
"scope": "site/quartz/static/ground/ground.js: 0 matches."
|
||||
},
|
||||
{
|
||||
"pattern": "readPixels\\([^)]*(Uint8Array|Float32Array|Uint16Array)",
|
||||
"scope": "ground.js: 0 matches outside the parity and debug readbacks, which are flag-gated and named."
|
||||
},
|
||||
{
|
||||
"pattern": "float cultmath_|vec4 cultmath_|float snoise|hash\\(",
|
||||
"scope": "flow/cloud/taa/downsample.frag.glsl: 0 matches; cultmath_* is defined only in the vendored CultMath.glsl."
|
||||
},
|
||||
{
|
||||
"pattern": "radial-gradient\\([^)]*rgba?\\([0-9]",
|
||||
"scope": "site/quartz/styles/custom.scss, body rule and ritual block: 0 matches."
|
||||
},
|
||||
{
|
||||
"pattern": "gamecult-titlebar|gamecult-nav-link|sidebar|composite|GameCult-Quartz",
|
||||
"scope": "git diff base..head changed lines: 0 matches."
|
||||
}
|
||||
],
|
||||
"operator": [
|
||||
"open / on the desktop and on the phone; say whether the nebula's motion and intensity are right (uniforms: PERIOD, FLOW_MAX, intensity)",
|
||||
"on the phone with ?ground=debug, read the logged GPU ms and the controller's final S/dpr; say whether it got warm after five minutes",
|
||||
"navigate / -> /Blog -> back; say whether the ground is continuous or shows a seed flash (Q5)",
|
||||
"open a ritual essay and confirm its ground still reads as its own paper"
|
||||
]
|
||||
},
|
||||
"estimate": {
|
||||
"lines_added": 980,
|
||||
"lines_removed": 15,
|
||||
"dependencies_added": [],
|
||||
"dependencies_removed": [],
|
||||
"formats_added": ["GLSL ES 3.00 shader files in static/ground", "vendored glsl-parity.json", "one sessionStorage key holding the last sampled token set"],
|
||||
"formats_removed": [],
|
||||
"targets_added": [],
|
||||
"targets_removed": []
|
||||
},
|
||||
"rulings": [
|
||||
"site-masthead:ruling:operator-chromeless-column"
|
||||
],
|
||||
"questions": [
|
||||
"Q4 in the map: palette input tokens (a, recommended)",
|
||||
"Q5 in the map: carry the last sampled wash across page loads (a, recommended)"
|
||||
]
|
||||
}
|
||||
141
docs/cultmath-interval-ground-cut-site-stardust.spec.json
Normal file
141
docs/cultmath-interval-ground-cut-site-stardust.spec.json
Normal file
|
|
@ -0,0 +1,141 @@
|
|||
{
|
||||
"campaign": "cultmath-tapes",
|
||||
"cut": "site-stardust",
|
||||
"revision": 1,
|
||||
"title": "Site stardust: stateless particles advected by the ground's flow texture, rendered to a half-res layer, blurred by the clouds' accumulated opacity (raymarch-driven DoF), composited behind the nebula",
|
||||
"repo": "GameCult/gamecult-site",
|
||||
"branch": "main",
|
||||
"base": "535d170",
|
||||
"depends_on": [
|
||||
"cultmath-tapes:cut_spec:site-ground.r2"
|
||||
],
|
||||
"first": [
|
||||
"Map: F:/Projects/CultLib/docs/cultmath-interval-ground-cut.md, 'Stardust', 'Depth of field driven by the raymarch', 'Budget', D4, D9, D10. Re-pin base to main after site-ground lands. The composite slot site-ground left in the resolve is where this cut plugs in; do not restructure the resolve.",
|
||||
"Aetheria reference, read once, copy nothing: Compute/Stardust/Stardust.compute:118-147 (grid cell -> hashed spawn, lifetime = frac(time/period + hash), position -= flow * lifetime * period, size = parabola(lifetime, 2), colour from a hue ramp x nebula tint); Stardust.shader:49-86 (billboard from quadPoints by SV_VertexID/SV_InstanceID, powerPulse falloff, distance exponents); CustomDoF/DepthOfField.hlsl:29-32 (CoC read from a raymarch output), :150-201 (disk gather weighted by CoC), :217-242 (combine). The web version is far smaller: no distance exponents (the slab is thin), no shadow pass, no near/far split.",
|
||||
"Particles are stateless: no buffers are updated. One static 6-vertex quad VBO; drawArraysInstanced with count N; the vertex shader derives everything from gl_InstanceID, time and the flow texture (vertex texture fetch is standard in WebGL2): cell = (id mod G, id / G) over the slab mid-plane; hashes via cultmath_pcg3d (the vendored CultMath.glsl is concatenated before the vertex source too) for spawn jitter, lifetime offset, size and brightness; lifetime = fract(t / PERIOD_P + offset); position = spawn - flow(spawn uv) * lifetime * PERIOD_P; size = base * parabola(lifetime, 2); colour = hue at the screen position (from the flow texture's channels, the same mix as the clouds) * brightness. Reduced motion freezes t as site-ground does.",
|
||||
"Stardust layer: half-resolution RGBA16F target, cleared each frame, additive blend, powerPulse falloff in the fragment shader; N = 16384 desktop, 4096 phone; the controller scales N with S (N halves when S halves) and the layer follows dpr.",
|
||||
"DoF: in the resolve's composite slot, read opacity = 1 - T from the reprojected, clamped history (not the current frame) and gather the stardust layer with an 8-tap Poisson disk of radius RMAX * opacity in layer texels (RMAX ~ 12 px at dpr 1, scaled by dpr); weight taps by a soft disk; composite out = ground + clouds + stardust_blurred * T, then the luminance clamp. All stardust is behind the whole cloud layer (D9).",
|
||||
"Debug flags: ?ground=debug-stardust writes the stardust layer alone; ?ground=debug-coc writes opacity into red. Prove in the browser pane: the stardust and the clouds move together (with ?ground=debug-mv from site-ground and the particle velocity written in green under ?ground=debug-stardust-v, the two directions agree within 5 degrees at 64 sampled pixels where |flow| is above a threshold); luminance clamp still holds after the composite; GPU ms per pass (stardust layer, gather) with the timer query at desktop and at the mobile preset's pixel count; the full-stack total against the budget table; the unfinished-ray fraction unchanged by this cut.",
|
||||
"Budget contract (map, 'Budget'): the stardust layer plus the gather cost no more than a quarter of the march at the same S; if the measurement says otherwise, the gather drops to 4 taps before N drops, and the report says which. Stardust is never cut before the clouds' S on the ladder."
|
||||
],
|
||||
"deletes": [],
|
||||
"keeps_moves": [
|
||||
"site-ground's flow texture, march, TAA, readback and token writer: untouched; the stardust reads the flow texture and the hue mix the same way the clouds do.",
|
||||
"The sampled wash now includes the stardust in its 8x8 readback by construction (it samples the final frame); nothing changes in the writer.",
|
||||
"The budget controller gains one scaled quantity (N) and no new state; the ladder order is unchanged."
|
||||
],
|
||||
"adds": [
|
||||
"site/quartz/static/ground/stardust.vert.glsl and stardust.frag.glsl: the instanced billboard and the powerPulse sprite.",
|
||||
"ground.js: the stardust pass (one VBO, one program, drawArraysInstanced), the half-res layer, N in the controller, the gather in the resolve's composite slot, the two debug flags.",
|
||||
"taa.frag.glsl: the composite slot filled: opacity from history, the 8-tap gather, out = ground + clouds + stardust_blurred * T.",
|
||||
"docs/brand-design-language.md: two sentences under the ground shader paragraph: the stardust and the DoF, and that they read the same flow and hue as the nebula."
|
||||
],
|
||||
"file_changes": [
|
||||
{
|
||||
"location": { "path": "site/quartz/static/ground/ground.js", "line": 1 },
|
||||
"change": "stardust pass, layer, N scaling, gather hookup, debug flags; line numbers are site-ground's and are re-read by function name."
|
||||
},
|
||||
{
|
||||
"location": { "path": "site/quartz/static/ground/taa.frag.glsl", "line": 1 },
|
||||
"change": "the named composite slot becomes the opacity-weighted gather and the final composite."
|
||||
},
|
||||
{
|
||||
"location": { "path": "docs/brand-design-language.md", "line": 69 },
|
||||
"change": "two sentences on stardust and DoF under the ground shader paragraph (post site-ground numbering)."
|
||||
}
|
||||
],
|
||||
"authority_map": {
|
||||
"owner": "ground.js owns the stardust pass and the DoF gather; the flow texture (site-ground) owns the particles' motion; the TAA history owns the opacity the DoF reads; the nebula input tokens own the particles' hue through the same mix as the clouds.",
|
||||
"inputs": [
|
||||
"the flow texture and the hue mix (site-ground)",
|
||||
"the reprojected, clamped history's transmittance",
|
||||
"time, N and dpr from the controller; gl_InstanceID"
|
||||
],
|
||||
"outputs": [
|
||||
"a half-res stardust layer per frame",
|
||||
"the composite with stardust blurred by cloud opacity behind the nebula, still under the luminance clamp"
|
||||
],
|
||||
"derived_state": [
|
||||
"every particle's position, lifetime, size and colour are derived from gl_InstanceID, time and the flow texture each frame; nothing is stored or updated",
|
||||
"N is derived from S by the controller; the layer size from dpr",
|
||||
"the blur radius is derived from the accumulated opacity; there is no second CoC source"
|
||||
],
|
||||
"forbidden_writers": [
|
||||
"no particle buffer update, transform feedback or CPU-side particle state",
|
||||
"no second flow function or hue mix; the vertex shader samples the flow texture",
|
||||
"no colour literal; no per-depth transmittance; no second march",
|
||||
"no new controller state beyond N; the ladder order is not changed",
|
||||
"no change to the readback or the token writer"
|
||||
],
|
||||
"shared_paths": [
|
||||
"clouds and stardust read one flow texture and one hue mix, so they move and colour as one",
|
||||
"the one resolve pass composites ground, clouds and stardust and applies the one luminance clamp",
|
||||
"the one controller scales S, N and dpr together"
|
||||
],
|
||||
"deletion_line": "Nothing is deleted. The addition is two small shaders, one pass and one gather; it buys the stardust and the DoF the operator named, and it must prove it fits the same budget."
|
||||
},
|
||||
"verification": {
|
||||
"builds": [
|
||||
"Deploy Quartz green on the landing commit",
|
||||
"scripts/ground/check-cultmath-glsl.ps1 still exits 0"
|
||||
],
|
||||
"tests": [
|
||||
{
|
||||
"name": "browser pane, /?ground=debug-stardust-v with ?ground=debug-mv: particle velocity and cloud motion vectors agree within 5 degrees at 64 sampled pixels where |flow| exceeds the threshold",
|
||||
"pins": "one flow: the stardust and the nebula move as one."
|
||||
},
|
||||
{
|
||||
"name": "browser pane, /?ground=debug-coc: opacity is 0 where the clouds are empty and rises inside them; the stardust gather radius follows it (a visible blur under a dense cloud, sharp in a gap)",
|
||||
"pins": "the raymarch drives the DoF, as in Aetheria's hack."
|
||||
},
|
||||
{
|
||||
"name": "browser pane, /?ground=debug: max relative luminance after 32 frames <= 0.035 with stardust on",
|
||||
"pins": "the clamp holds after the composite."
|
||||
},
|
||||
{
|
||||
"name": "browser pane, timer query at desktop and at the mobile preset: stardust layer + gather <= 25% of the march at the same S; full-stack totals quoted against the budget table",
|
||||
"pins": "the stardust fits the same budget or the report says what gave."
|
||||
},
|
||||
{
|
||||
"name": "reduced motion: particles frozen, frames stop at 32; hidden tab: no frames",
|
||||
"pins": "the stardust obeys the one controller."
|
||||
}
|
||||
],
|
||||
"negative": [
|
||||
{
|
||||
"pattern": "bufferSubData|transformFeedback|TRANSFORM_FEEDBACK|new Float32Array\\((N|count|particles)",
|
||||
"scope": "ground.js stardust section: 0 matches; particles are stateless."
|
||||
},
|
||||
{
|
||||
"pattern": "#[0-9a-fA-F]{6}\\b|rgba?\\(",
|
||||
"scope": "stardust.vert.glsl, stardust.frag.glsl, ground.js: 0 matches."
|
||||
},
|
||||
{
|
||||
"pattern": "snoise\\(|float cultmath_",
|
||||
"scope": "stardust.vert.glsl and stardust.frag.glsl: 0 matches; the flow and hue come from the texture, not from a second evaluation."
|
||||
},
|
||||
{
|
||||
"pattern": "readPixels|setProperty",
|
||||
"scope": "git diff base..head changed lines in ground.js: 0 matches; the readback and the token writer are not touched."
|
||||
}
|
||||
],
|
||||
"operator": [
|
||||
"open / on the desktop and on the phone; say whether the stardust sells the motion and whether the blur under the clouds reads like the video (RMAX, N, PERIOD_P are the dials)",
|
||||
"on the phone with ?ground=debug, read the full-stack GPU ms and the final S/N/dpr; say whether it got warm"
|
||||
]
|
||||
},
|
||||
"estimate": {
|
||||
"lines_added": 320,
|
||||
"lines_removed": 4,
|
||||
"dependencies_added": [],
|
||||
"dependencies_removed": [],
|
||||
"formats_added": [],
|
||||
"formats_removed": [],
|
||||
"targets_added": [],
|
||||
"targets_removed": []
|
||||
},
|
||||
"rulings": [
|
||||
"site-masthead:ruling:operator-chromeless-column"
|
||||
],
|
||||
"questions": []
|
||||
}
|
||||
1648
docs/cultmath-interval-ground-cut.md
Normal file
1648
docs/cultmath-interval-ground-cut.md
Normal file
File diff suppressed because it is too large
Load diff
119
docs/cultmath-tape-target.md
Normal file
119
docs/cultmath-tape-target.md
Normal file
|
|
@ -0,0 +1,119 @@
|
|||
# CultMath tapes: interval-pruned field evaluation on CPU and GPU
|
||||
|
||||
Status: steps 2-5 (tape, pruning, HLSL interpreter, meshing) are **parked**
|
||||
(2026-10-02; ruling tape-target-unparks-when-asura-stable). The affine-forms
|
||||
piece was unparked on 2026-10-03 (ruling affine-forms-unparked) and is on main
|
||||
(156782da), alongside step 1's intervals; its map and as-built record are in
|
||||
`docs/cultmath-interval-ground-cut.md`. This note records the direction for the
|
||||
parked steps so they can be picked up without re-deriving it.
|
||||
|
||||
## Intent
|
||||
|
||||
Evaluate large implicit fields, meaning deeply nested CSG trees of brushes with
|
||||
thousands of nodes, cheaply enough to mesh at many levels of detail and to
|
||||
raymarch. The operator's words (2026-10-02): "I would love to design a space
|
||||
station out of a grammar of nested brushes, and have the ability to
|
||||
automatically mesh it at multiple levels of detail so I can get arbitrarily
|
||||
close to its tiny details without melting my GPU."
|
||||
|
||||
GameCult has no deep CSG trees today because nothing could evaluate them
|
||||
cheaply. The capability comes first, and the content follows.
|
||||
|
||||
## Prior art
|
||||
|
||||
[Fidget](https://www.mattkeeter.com/projects/fidget/) by Matt Keeter
|
||||
(MPL-2.0, Rust, v0.5.1 on 2026-09-27; repo `mkeeter/fidget`).
|
||||
- It compiles an expression to a register-allocated bytecode tape.
|
||||
- It evaluates that tape as points, SIMD batches, intervals, and forward-mode
|
||||
gradients.
|
||||
- The central trick is interval evaluation over a region. When it proves that
|
||||
one operand of a `min` or `max` always wins, the tape for that region is
|
||||
rewritten without the other branch. In the project's example, the tape
|
||||
shrinks from 254 clauses to about 20 at pixel level.
|
||||
- `fidget-jit` targets x86-64 and AArch64.
|
||||
- `fidget-wgpu` has a WGSL tape interpreter, interval ops and tape
|
||||
simplification on the GPU (`interval_ops.wgsl`, `tape_interpreter.wgsl`,
|
||||
`tape_simplify.wgsl`).
|
||||
- `fidget-mesh` implements Manifold Dual Contouring. It is known to be weak on
|
||||
thin features.
|
||||
- Halfspace is the IDE codesigned with `fidget-wgpu` (Rust, egui and wgpu,
|
||||
MPL-2.0).
|
||||
|
||||
## Chosen shape (option c)
|
||||
|
||||
The ideas are ported into CultLib and owned here. Fidget is not a dependency.
|
||||
Unity renders HLSL on its own graphics backend, so `fidget-wgpu` cannot run
|
||||
inside it.
|
||||
|
||||
Three options were weighed on 2026-10-02:
|
||||
|
||||
| Option | What it is | Trade |
|
||||
|---|---|---|
|
||||
| a | Fidget as a Rust native plugin in Unity | Fastest demo; costs per-platform native builds, an FFI boundary, and an upstream that warns of breaking changes |
|
||||
| b | Offline bake with a Rust tool; ship meshes | Simplest; the baked depth caps how close a viewer can get |
|
||||
| c | CultLib owns tape, interval and pruning in C# and HLSL | Most coherent end state; the largest code liability we would own |
|
||||
|
||||
The operator parked (c). An (a) spike to validate authoring and LOD behaviour
|
||||
before owning code was suggested but not ruled.
|
||||
|
||||
Sketch, to be replaced by the target pass:
|
||||
|
||||
1. **CultMath `interval`** in C# and HLSL with parity tests:
|
||||
- arithmetic, `min`/`max`, `smin`, `sqrt`, `clamp` and `smoothstep`;
|
||||
- interval or Lipschitz bounds for every CultMath noise primitive.
|
||||
|
||||
This step needs no tape. It stands alone, and is the first cut to take even
|
||||
if the rest stays parked.
|
||||
2. **Tape**: an expression graph lowered to bytecode, with point, interval and
|
||||
gradient evaluators in C#. Gradients reuse CultMath's analytic-gradient
|
||||
primitives, which Asura cut 2a built.
|
||||
3. **Pruning**: per-region tape simplification driven by interval results.
|
||||
4. **HLSL interpreter** for the same bytecode, with interval ops and pruning.
|
||||
Fidget's MPL-2.0 WGSL is the reference. MPL code keeps its own MPL-headed
|
||||
files, as Phacelle does.
|
||||
5. **Meshing**: an octree of chunks with seams stitched between LOD levels.
|
||||
- The default is surface nets (GameCult.Geometry, Asura Cut 2) plus
|
||||
Asura's tile pass: Newton refinement onto `f = 0`, then crease snapping
|
||||
from field gradients (Asura Cut 6c).
|
||||
- The operator's lean (2026-10-02) is that gradient work beats dual
|
||||
contouring here. Thin authored bevels can be shaded by their analytic
|
||||
normals, and the refined positions can be iterated further.
|
||||
- Dual contouring is not planned. The tile pass on station brushes is its
|
||||
test.
|
||||
|
||||
## Truth and lowerings
|
||||
|
||||
The field is data: a typed CultCache document holding the expanded tree. A
|
||||
generator, such as a brush grammar, expands into that document, and everything
|
||||
downstream caches it. The CPU evaluator, the HLSL interpreter, the mesher and
|
||||
collision are all lowerings of that one document. This is how "one
|
||||
implementation of the field" survives having both CPU and GPU evaluators.
|
||||
Asura's invariant 2 had to forbid CPU evaluation because its field is HLSL
|
||||
source.
|
||||
|
||||
## Known consumers
|
||||
|
||||
- **Aetheria volumetric raymarching** (clouds, nebulae). Step 1 alone gives it
|
||||
empty-space skipping. Coverage and shape terms carry the culling, because
|
||||
detail octaves only bound to ±amplitude.
|
||||
- Prerequisite: Aetheria's shaders must use CultMath noise, not their own
|
||||
copies. That is already owed at Aetheria's CultMath pin bump (see the Asura
|
||||
cut map, snoise release follow-ups).
|
||||
- **Space stations from a brush grammar**, meshed in LOD chunks around the
|
||||
camera. This is a separate project with its own target. This campaign
|
||||
supplies its evaluator.
|
||||
- Asura does not need this campaign. Its field is noise-dominated, and its
|
||||
`A_max` shell and band-limiting already give the cheap culling.
|
||||
|
||||
## Open before unparking
|
||||
|
||||
- Run the (a) spike first, or go straight to (c)?
|
||||
- Pick the interval representation (plain intervals or affine arithmetic) and
|
||||
the noise bound strategy.
|
||||
Affine forms for noise and warp were unparked on 2026-10-03 (ruling
|
||||
`cultmath-tapes:ruling:affine-forms-unparked`): one shared symbol, mapped in
|
||||
`docs/cultmath-interval-ground-cut.md`, "Pass 5".
|
||||
- Choose the bytecode register model for the HLSL interpreter, given GPU
|
||||
register pressure.
|
||||
- Decide whether the brush-grammar station project lives in Aetheria or in
|
||||
its own repo.
|
||||
|
|
@ -13,6 +13,25 @@ Depends on: `hands/cultmesh-put-serve-bound` merging first. It introduces `docum
|
|||
cultmesh-rs (`c9cdad12`, `85288a5a`). The cuts below convert those sites. Their anchors are by commit, not by
|
||||
line, because the branch is not on main.
|
||||
|
||||
Found by the put-serve Hands (batch 3, `38000efa`, 2026-09-30); they belong to this map's cuts:
|
||||
- **Python codes outside the closed code list.** Python refuses with `document_unservable`,
|
||||
`malformed_document_put` and `snapshot_*_exceeded`. None of these are in the closed `cultnet.error.v0` code
|
||||
list, and Rust and TS peers refuse to decode an unknown code.
|
||||
- **Two error-map shapes.** TS sends a two-key error map that its own peers cannot parse. Rust sends the five-key
|
||||
contract shape. The two agree only at the message level.
|
||||
- **The session after a refusal.** TS and Python keep the session open after a refusal; Rust sends a goodbye and
|
||||
ends it.
|
||||
- **New Rust refusal frame.** The put-serve branch adds a Rust refusal frame, `cultnet.error.v0` carrying the
|
||||
reason text with no code and no details, sent before the goodbye and acknowledging nothing. Cut 1 gives it a
|
||||
code.
|
||||
- Found by the put-serve Soul (merge verdict, 2026-09-30):
|
||||
- A store `OSError(ENOSPC)` in Python is refused as `malformed_document_put`, with the text "Raw put document could
|
||||
not be stored." That is a server fault reported as the peer's fault.
|
||||
- Over RUDP, Python's `document_unservable` details add `fragmentCount` and `maxFragmentCount`, and send
|
||||
`maxSnapshotBytes: null` when it is unbounded. The map specifies `{responseBytes, maxSnapshotBytes}`.
|
||||
- `response_unqueueable` (Python, P3) is a new code outside the closed list.
|
||||
- A TS peer cannot tell "stored, receipt lost" from "refused" (put-serve Soul F4, pass 3).
|
||||
|
||||
Map branch: `main`.
|
||||
|
||||
---
|
||||
|
|
|
|||
|
|
@ -1,5 +1,28 @@
|
|||
# CultNet RUDP: Acknowledged means delivered, one watermark owns ordered delivery, and a write belongs to its session
|
||||
|
||||
**PIVOT, 2026-09-30 (operator): RUDP is retired in favour of QUIC.** Operator: "RUDP really ballooned into
|
||||
maintaining a robust custom transport across runtimes, when it started as just 'hey, let's do LiteNetLib but
|
||||
better'. Is there any point maintaining it when we have QUIC?" and then "Yeah, pivot to QUIC adoption, I ain't
|
||||
gonna let sunk costs take the wheel."
|
||||
- **Landed 2026-09-30: Cut D, merged at `2f06ef84`** (Soul passes 1-4, batch 5 closing pass 4). It fixes live crashes: a spoofed datagram crashing Node, a malformed frame
|
||||
killing Python's server, C# stale peers corrupting sessions.
|
||||
- **Parked, not built:** Cut F, Cut 2 (held on F), Cut 4, Cut K and K1 (including the Kotlin resend-loop gap), Cut 7
|
||||
and the receipts port. Nothing of theirs exists to tag, so this map is their record.
|
||||
- Defects found in RUDP from here on are fixed only if they are live crashes or data loss, until the QUIC campaign
|
||||
sets RUDP's retirement.
|
||||
- **Data-loss item from Odin Soul S-5 (2026-09-30).** At Odin's pin `3bf1c0ce`, cultnet-rs records a reliable
|
||||
packet as received when it arrives, and `create_ack` reports it while ordered delivery still holds an earlier
|
||||
packet.
|
||||
- Probe: two pipelined puts, with the first datagram dropped. The second put was ACKed but not on disk. If the
|
||||
first never arrives, the ACKed second put is never delivered.
|
||||
- Sessions that carry a single put are safe.
|
||||
- **Checked (Odin Q5 Imagination, probe P1 at `e4e2a0b9`): still open after ack Cuts 1-1c.** A held, undelivered
|
||||
put is ACKed, so the pin bump does not close it, and it is a data-loss fix under the pivot rule. Related, P2: a
|
||||
Pong ACKs a put received before the Ping; P3: a reliable reply created after a put ACKs it. The Odin writer-thread
|
||||
cut (C5) adds `acknowledgement_withheld` to the document server; the transport fix belongs in cultnet-rs.
|
||||
- The "CultNet over QUIC" campaign is new, so it opens as a typed Eureka campaign in the Huginn-backed session, not
|
||||
as a prose map here.
|
||||
|
||||
Status: cut map, Imagination pass 3, 2026-09-30. Pass 3 maps the four rulings below, re-maps Cuts 1c and
|
||||
4, and adds Cut F (FORWARD-TSN), Cuts 6a-6c (receipts), Cut 7 (expiry, if Q-A8), Cut K (Kotlin), Cut 2c (the
|
||||
C# fragment bound) and Cut D (a failed send to one peer stays that peer's loss). The text of Cuts 1, 1b, 2
|
||||
|
|
@ -730,7 +753,7 @@ The ack cuts build on these behaviours and do not alter them:
|
|||
| Rust hub `CultNetRudpServerHub` | `poll_resends` returns on the first failure (`rudp.rs:1762-1777`); the receive path's sends to one peer abort `receive_event_once` (`:1644`, `:1673`, `:1708`, `:1711`, `:1714`, `:1759`, through `send_packet` `:1799-1804`) | Cut D |
|
||||
| C# `CultNetRudpSocketTransportServer` (and `RudpCultNetSchemaServer` over it) | `PollResends` walks every peer and the first `SocketException` from `SendTo` (`CultNetTransport.cs:2829-2834`) escapes the loop (`:2796-2805`); `TryReceiveOnce`'s sends are unguarded except the refusal goodbye (`:2687`, `:2704`, `:2749-2750`, `:2788`; guarded `:2739-2745`) | Cut D |
|
||||
| cultmesh-py server | worse: an `OSError` from `sendto` (`server.py:302-307`) in `_poll_rudp_resends` (`:277-285`) or the receive path escapes `_rudp_loop` (`:203-…`, which catches only `recvfrom`'s errors), and the RUDP thread dies for every peer | Cut D |
|
||||
| cultmesh-ts document server | none: Node's `socket.send` is asynchronous and reports failures on the socket's `error` event (`cultmesh-ts/src/index.ts:5858`), which `reportError` logs (`:5778-5785`) | none |
|
||||
| cultmesh-ts document server | none. **Corrected 2026-09-30:** Node does not report send failures on the socket's `error` event. With a callback they go to the callback; without one, libuv drops them silently (Node 24). Only port 0 throws synchronously. Cut D routes every send through `sendRudpDatagram`. | none |
|
||||
| Kotlin interop server | none that matters: a catch-all logs and continues (K:4025), and it is interop-only | none (Cut K1 reviews it) |
|
||||
|
||||
|
||||
|
|
@ -1048,8 +1071,8 @@ Design in §10. Independent of every other cut; it touches send sites, not sessi
|
|||
(`:2739-2745`) becomes redundant and goes;
|
||||
- cultmesh-py `server.py`: `_send_rudp_packet` (`:302-307`) catches `OSError` and counts it.
|
||||
- **Not changed:** single-peer socket transports (a failed send already concerns only their one peer, and
|
||||
their callers, flush among them, get the error); `cultmesh-ts`'s document server (Node reports send
|
||||
failures on the socket's `error` event, `index.ts:5858`).
|
||||
their callers, flush among them, get the error); `cultmesh-ts`'s document server. (Corrected 2026-09-30: Node reports send failures only to a send
|
||||
callback, never on the socket's `error` event; see the table above.)
|
||||
- **Authority map:**
|
||||
- Owner: each peer's session owns its peer's fate (idle timeout, lifetime, refusal, Disconnect). A send
|
||||
failure is an input to nothing but a counter.
|
||||
|
|
@ -1590,6 +1613,25 @@ profiles.
|
|||
a permanent failure is returned from a caller-directed send and, inside a poll, ends only that peer's session with a
|
||||
typed reason; transient failures stay counted losses. Windows `ConnectionResetError` on receive is idle, never fatal,
|
||||
in every server. Cut D's negative grep `send_packet(...)?;` is obsolete: the `?` now propagates encode errors only.
|
||||
- **Cut 3 merged at `1210fdc7` (2026-09-30).**
|
||||
- Batch 2 fixed Rust `send`, which checked the window before purging expired packets. It also added a
|
||||
new-generation test in all four runtimes.
|
||||
- Soul pass on batch 2: nothing found. 18 mutants were killed. Interop was 27/27, run in `ack1d-interop:2`,
|
||||
whose Linux wrappers let the Windows-only Kotlin build run.
|
||||
- Residual: `packages/cultmesh-rs/Cargo.lock` is stale.
|
||||
- Also recorded: `packages/cultmesh-kotlin/build.ps1` is Windows-only, so Kotlin interop runs off Windows only
|
||||
through an image with wrappers.
|
||||
- P2 (the expiry hole) stays with Cut F.
|
||||
- **Cut D batch 2, Soul pass 2: fix first.**
|
||||
- cultnet-ts emits transient send failures as `"error"`, which crashes processes with no listener. Section 10's
|
||||
claim that "Node reports send failures on the socket's error event" is false on Node 24 without a callback:
|
||||
they are dropped silently.
|
||||
- C# stale peer objects write into the replacing session.
|
||||
- cultmesh-py dies on a non-ValueError per-peer failure.
|
||||
- Six guards are unpinned.
|
||||
- Batch 3 is in Hands.
|
||||
- **K1 gains:** Kotlin's idle resend loop (`CultMesh.kt:4033-4036`) is one `try`, so one peer's permanent failure
|
||||
stops resends for every later peer. That is in addition to a refused packet not ending that peer's session.
|
||||
- **Recorded (liveness, not fixed):** a lowest reliable packet lost forever stalls the sender 1,023 sequences ahead
|
||||
while the peer stays alive; session timeout doesn't end it. TCP ends such a connection after a retransmission
|
||||
limit (R2). Decide with Cut F (abandonment) whether a reliable packet outstanding past a bound ends the session.
|
||||
|
|
|
|||
|
|
@ -271,6 +271,15 @@ Current progress:
|
|||
flush where the runtime supports one, so callers that require confirmed
|
||||
transport delivery do not substitute a fixed sleep. TCP-framed profiles do
|
||||
not publish the field because they do not own the RUDP pending-reliable queue.
|
||||
- The receive window is a contract, not a discovery. A receiver must hold 1,023
|
||||
sequences and 4 MiB of payload beyond its contiguous received watermark, and
|
||||
a conforming sender never exceeds either. The sender's flow window enforces
|
||||
it without a wire field: a reliable packet is admitted only while its
|
||||
sequence is at most 1,023 above the lowest unacked sequence and the payload
|
||||
above that sequence stays within 4 MiB. The first packet is always
|
||||
admissible, so a payload larger than 4 MiB goes out alone, and packets wait
|
||||
in the FIFO in order, so a small packet never overtakes a large one. C#,
|
||||
Rust, TypeScript, and Python enforce it; Kotlin does not yet.
|
||||
- TypeScript, C#, Rust, Python, and Kotlin now share a portable
|
||||
`cultnet.reconnect_policy.v0` document and deterministic exponential delay
|
||||
helper, and RUDP transport profiles advertise that policy under
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -11,9 +11,12 @@ CultNet, and CultCache ownership boundaries.
|
|||
powershell -ExecutionPolicy Bypass -File .\scripts\pack-nuget.ps1
|
||||
```
|
||||
|
||||
The command creates a local feed under `artifacts/nuget`, verifies that every
|
||||
internal dependency package exists at the same version, then restores and runs
|
||||
a clean .NET consumer using only `PackageReference Include="GameCult.Mesh"`.
|
||||
The command packs `GameCult.Mesh`, `GameCult.Networking.WebSockets`, and every
|
||||
project they reach through `ProjectReference` (including `GameCult.Math`, which
|
||||
carries its own version) into a local feed under `artifacts/nuget`. It verifies
|
||||
that each of those packages exists at the identity MSBuild reports for it, then
|
||||
restores and runs a clean .NET consumer using only
|
||||
`PackageReference Include="GameCult.Mesh"`.
|
||||
|
||||
The Unity distribution remains `org.gamecult.cultlib`, built by
|
||||
`scripts/build-unity-package.ps1`, because Unity consumes the managed assembly
|
||||
|
|
|
|||
286
docs/research/analytic-integration-feasibility.md
Normal file
286
docs/research/analytic-integration-feasibility.md
Normal file
|
|
@ -0,0 +1,286 @@
|
|||
# Analytic noise integration along warped rays: feasibility probe
|
||||
|
||||
Campaign `cultmath-tapes`, Imagination probe, 2026-10-03. This is a measurement,
|
||||
not a spec. The tape target stays parked under ruling
|
||||
`cultmath-tapes:ruling:tape-target-unparks-when-asura-stable`.
|
||||
|
||||
**Verdict.** Exact integration of the noise does not beat sampling for optical
|
||||
depth on either shipped field.
|
||||
- The exact line integral of CultMath `snoise` is cheap and correct. Affine warp
|
||||
spans are long, at 100 to 300 world units.
|
||||
- The exact noise integral is not the optical depth, because both densities are
|
||||
nonlinear in the noise.
|
||||
- The void's wall profile is `pow(·, 0.40)` with two clamps.
|
||||
- Aetheria's fog is clamped at zero and goes opaque within a few world units.
|
||||
- Given the *exact* span mean of the noise for free, the resulting transmittance
|
||||
is still 3.6x worse than the shipped march on the void and 22x worse on the
|
||||
wells.
|
||||
- Exact integration wins only on the linear functional `∫ n dt` of octaves the
|
||||
march undersamples. That gain does not survive the density's nonlinearity.
|
||||
- Aetheria's triangle noise is integrable exactly as piecewise linear, but costs
|
||||
3x to 22x the march, and its shipped form does not meet the preconditions.
|
||||
|
||||
## Scenarios and method
|
||||
|
||||
- **Void:** the shipped void (`NoiseBoundTests.VoidField.Shipped()` at
|
||||
`hands/cultmath-interval-ops` 2c8585bd).
|
||||
- Rh 198, S 50, Rc 248, K 1/30, A 20, F0 0.01 (cells of 100 and 25 world), warp
|
||||
D 10.
|
||||
- The shipped orbiting camera, N = 8 tiles at f = 935, one jittered pixel ray per
|
||||
tile.
|
||||
- **Wells:** the test's Aetheria wells at warp D = 60 (`FogField.Wells(60)`).
|
||||
- F0 1/414.2167, A 20, B 10, extinction 0.5, flow frequency 1/512, period 8.
|
||||
- Like the test, this uses the snoise field shape (r1's), not Aetheria's own
|
||||
triangle noise. Triangle noise is measured separately below, on the same rays.
|
||||
- **Rays:** 200 per scenario, and 120 for the triangle basis.
|
||||
- The wells give 147 rays with an active interval; the rest look up and miss
|
||||
the fog.
|
||||
- The active interval is where the envelope leaves the density to the noise.
|
||||
It is cut where the true optical depth reaches 6.
|
||||
- Active length per ray: void median 140 world (p10 114, p90 193); wells median
|
||||
268 (p10 137, p90 623).
|
||||
- **March steps:** the void's march step (LodStep, 12.5 in z) is a median 14.9
|
||||
world along the ray. The wells' quadratic grid gives a median of 9.1 in the
|
||||
active region.
|
||||
- **Warp:** `w(p) = flow(p) · shift`, so the affine error scales exactly with
|
||||
`|shift|`.
|
||||
- Spans are grown at the worst phase shift, Period / 2. A span is therefore
|
||||
valid at every frame's phase, for any camera that crosses the same world
|
||||
segment.
|
||||
- Each span is anchored at p0 with J·d from a central difference. It grows in
|
||||
1-unit (void) or 2-unit (wells) steps until `|w − (w0 + J·d·Δ)| > τ`.
|
||||
- **Exact simplex integral:** CultMath `snoise(float3)` has kernel radius² 0.5,
|
||||
so its support never leaves the incident simplices.
|
||||
- Along a line it is therefore a sum over the lattice points within √0.5 of the
|
||||
line. Each point contributes `∫ (0.5 − |x|²)⁴ (g·x) dt` on its chord, a
|
||||
closed-form degree-9 polynomial.
|
||||
- Validation:
|
||||
- The lattice sum matches `snoise` within 2e-4 (float32 rounding at
|
||||
coordinates near 300).
|
||||
- The segment integral matches a 5e-4-step quadrature within 2.5e-5 per
|
||||
unit length.
|
||||
- **Run:** probe code was in a scratch clone (probe-clone@91c8cbf1, never merged)
|
||||
and ran on Yggdrasil through the verify stopgap, in a dotnet 10 container with
|
||||
4 CPUs. Timings are single-threaded C# on that host and are relative.
|
||||
|
||||
## 1. Affine-valid span length (ray length, world units)
|
||||
|
||||
| τ (× coverage cell) | Void p10 / median / p90 | Wells p10 / median / p90 |
|
||||
|---|---|---|
|
||||
| 0.05 | 94 / 129 / 211 | 71 / 103 / 169 |
|
||||
| 0.10 | 141 / 197 / 324 | 108 / 151 / 253 |
|
||||
| 0.25 | 263 / 420 / 1244 | 184 / 275 / 715 |
|
||||
| 0.05 × detail cell | 44 / 63 / 97 | 34 / 47 / 75 |
|
||||
|
||||
- One affine span at τ = 0.1 covers about 13 void march steps and about 16 wells
|
||||
march steps.
|
||||
- The void shell is shorter than one span. The tiled spans are clipped by the
|
||||
active interval, at a median of 27 world and 2 spans per ray.
|
||||
- On the wells, the tiled spans run a median of 128 world, with 2 per ray (p90 4).
|
||||
- The tangent anchor is the worst affine choice. A secant or Chebyshev fit over
|
||||
the span cuts the error bound by 2x to 8x, so the spans could be about 1.4x to
|
||||
2.8x longer at the same τ. That was not measured.
|
||||
|
||||
## 2. Simplex cells per span, per octave
|
||||
|
||||
Octave `xm` is the coverage octave's frequency times m, warped like the coverage
|
||||
octave. The shipped detail octave is x4 and is *unwarped* in both fields, so it
|
||||
needs no affine span at all.
|
||||
|
||||
Counts are for τ = 0.1 tiled spans with both warp phases, given as the median and
|
||||
then the p90. The rows are simplex cells crossed, then lattice points touched,
|
||||
which is the exact work.
|
||||
|
||||
| Octave | Void cells | Void lattice points | Wells cells | Wells lattice points |
|
||||
|---|---|---|---|---|
|
||||
| x1 | 6 / 16 | 10 / 16 | 4 / 8 | 8 / 10 |
|
||||
| x2 | 8 / 27 | 10 / 26 | 8 / 12 | 10 / 14 |
|
||||
| x4 | 13 / 52 | 14 / 44 | 12 / 20 | 14 / 20 |
|
||||
| x8 | 20 / 100 | 20 / 80 | 22 / 38 | 22 / 34 |
|
||||
| x16 | 40 / 201 | 35 / 154 | 44 / 72 | 38 / 60 |
|
||||
| x32 | 75 / 396 | 62 / 302 | 86 / 144 | 70 / 112 |
|
||||
| x64 | 151 / 793 | 118 / 592 | 172 / 287 | 132 / 218 |
|
||||
|
||||
- On the same spans, the march takes a median of 2 samples per span on the void
|
||||
(p90 10) and 12 on the wells (p90 25).
|
||||
- A straight line touches 3.44 lattice points per noise unit.
|
||||
|
||||
## 3. Cost: exact against the march
|
||||
|
||||
- **Measured cost.**
|
||||
- One snoise is 530 to 610 ns in C# on this host.
|
||||
- One lattice-point integral (hash, gradient, closed-form polynomial) is
|
||||
85 ns, or 0.16 snoise.
|
||||
- With this probe's naive box-scan enumeration it is 1.24 snoise. That is an
|
||||
upper bound; a simplex walk visits only crossed cells.
|
||||
- **How the table counts.** Exact is lattice points × 0.16 + 1 snoise per span
|
||||
for the Jacobian. March is 1 snoise per sample. Both sides carry the two warp
|
||||
phases.
|
||||
- **Tolerance.** τ is 0.1 × *that octave's own* cell, so the affine error is
|
||||
comparable across octaves.
|
||||
- **Columns.** The two error columns are RMS errors of the active-length mean
|
||||
of one warped octave. The last error column is what replacing the octave by its
|
||||
expectation of 0 costs.
|
||||
|
||||
| Octave | Void exact/march cost | Void err exact / march / expectation | Wells exact/march cost | Wells err exact / march / expectation |
|
||||
|---|---|---|---|---|
|
||||
| x1 | 0.36 | 1.1e-2 / 1.6e-3 / 0.21 | 0.11 | 1.9e-2 / 9e-5 / 0.29 |
|
||||
| x2 | 0.46 | 1.0e-2 / 4.7e-3 / 0.13 | 0.15 | 1.5e-2 / 2e-4 / 0.21 |
|
||||
| x4 | 0.68 | 9.0e-3 / 4.0e-2 / 0.10 | 0.23 | 1.1e-2 / 5e-4 / 0.18 |
|
||||
| x8 | **1.03** | 5.8e-3 / 8.0e-2 / 0.067 | 0.36 | 7.2e-3 / 1.1e-3 / 0.10 |
|
||||
| x16 | 1.64 | 4.0e-3 / 9.0e-2 / 0.050 | 0.56 | 6.4e-3 / 9.4e-3 / 0.088 |
|
||||
| x32 | 2.89 | 2.8e-3 / 0.105 / 0.036 | 0.87 | 4.7e-3 / 3.3e-2 / 0.057 |
|
||||
| x64 | 5.26 | 2.0e-3 / 0.095 / 0.025 | **1.44** | 3.2e-3 / 5.3e-2 / 0.040 |
|
||||
|
||||
- **Where exact stops paying on cost:**
|
||||
- At the measured kernel cost: x8 on the void and between x32 and x64 on the
|
||||
wells.
|
||||
- At the brief's model of one snoise per cell crossed: about x1 to x2 on the
|
||||
void and x8 on the wells, from the per-span table in the probe log.
|
||||
- **Exact against the march on accuracy:**
|
||||
- At the shipped step the march is *more* accurate for octaves it oversamples:
|
||||
void x1 to x2, wells x1 to x8. The exact path's error floor is the affine warp
|
||||
error, about 1e-2 at τ = 0.1 per cell, and it scales with τ.
|
||||
- Exact is more accurate at about 0.7x the cost where the march undersamples:
|
||||
void x4 to x8, wells x16 to x32.
|
||||
- Above about x16 on the void, the undersampled march is worse than simply
|
||||
using the expectation (0.095 against 0.025 at x64). That is a band-limiting
|
||||
result, which the footprint octave weights already exploit. It is not an
|
||||
exact-integration result.
|
||||
|
||||
## 4. High-octave variance over a span
|
||||
|
||||
- **Span-mean statistics.** Over straight lines of noise length ℓ, the std of
|
||||
the snoise span mean, against a point std of 0.358, is:
|
||||
- 0.234 at ℓ = 1;
|
||||
- 0.170 at ℓ = 2;
|
||||
- 0.121 at ℓ = 4;
|
||||
- 0.087 at ℓ = 8;
|
||||
- 0.061 at ℓ = 16;
|
||||
- 0.031 at ℓ = 64.
|
||||
|
||||
This is about ℓ^-0.5: the high octaves average out like a random field, not
|
||||
like a periodic one.
|
||||
- **Detail octave replaced by its expectation of 0,** on τ = 0.1 spans, measured
|
||||
as |ΔOD| per span:
|
||||
- Void: median 0.000 and p90 0.091. Relative to the span's OD (OD > 0.01) the
|
||||
median is 2.5% and the p90 is 7.6%. The mean detail displacement is a median
|
||||
1.0 world (p90 3.6) against the ramp width S = 50.
|
||||
- Wells: median 0.11 and p90 5.7 optical depths. The relative median is 72%.
|
||||
- **Why the wells are so bad.** Normalised to the clamp, the density moves
|
||||
A·fade/B = 2 per unit of noise, and with extinction 0.5 that is 1 optical depth
|
||||
per world unit per unit of noise. The mean detail displacement of 1.5 world
|
||||
(p90 3.8) is 15% to 38% of the floor blend B = 10. The wells' optical depth is
|
||||
set by where the clamp boundary lies, and that is exactly what the expectation
|
||||
erases.
|
||||
- So the expectation is adequate for the void's detail octave and is not
|
||||
adequate for the wells.
|
||||
|
||||
## 5. The clamp and other nonlinearity
|
||||
|
||||
- **Void.** 50.0% of τ = 0.1 spans cross a regime boundary: 0 (d' ≤ Rh), the
|
||||
wall ramp, or K (d' ≥ Rc). 45.6% of the active length lies in the ramp, where
|
||||
the density is `K max(0, 1 − 1.5 (1 − (d'/Rc)²)^0.40)`. That is not a
|
||||
polynomial in n, so exact ∫n does not give ∫ρ there. Outside the ramp the
|
||||
density is constant and needs no noise.
|
||||
- **Wells.** 42.3% of spans cross the clamp. Only 9.8% of the active length is
|
||||
unclamped, so most of the length where the noise "matters" is length where the
|
||||
noise only decides whether the density is zero.
|
||||
- **The decisive check: transmittance error.** This is the sup over the ray of
|
||||
|T_est − T_true|, with the truth taken on a 0.5- or 1-unit grid.
|
||||
|
||||
| Estimator | Void median / p90 | Wells median / p90 |
|
||||
|---|---|---|
|
||||
| Shipped march | 0.020 / 0.038 | 0.033 / 0.155 |
|
||||
| March at 4x density | 0.006 / 0.009 | 0.030 / 0.049 |
|
||||
| Density of the *exact* span-mean n (τ = 0.1 spans) | 0.072 / 0.125 | 0.719 / 0.997 |
|
||||
|
||||
The last row is an upper bound on what any exact-mean method can deliver
|
||||
without also modelling the distribution inside the span. It is the
|
||||
Heitz-style correction the survey describes. It loses to the march on both
|
||||
fields.
|
||||
|
||||
## Triangle basis (operator's addition)
|
||||
|
||||
The triangle noise is `triNoise3d` in Aetheria `Assets/Shaders/Volumetric.cginc`
|
||||
(origin/master f1dee184).
|
||||
- `tri(x) = |frac(x) − 0.5|`.
|
||||
- It runs two Nimitz-style iterations. Each iterates `p += tri3(bp·2)`, scales
|
||||
`bp` by 1.8 and `p` by 1.2, and adds `tri(p.z + tri(p.x + tri(p.y)))/z`.
|
||||
- It makes 18 tri calls per evaluation.
|
||||
|
||||
As shipped, `density()` uses it as follows:
|
||||
- `pow(triNoise3d(·), exponent)`, with Noise.Exponent −0.25 multiplied by a
|
||||
slope `flatness` read from a texture (NOISE_SLOPE is on).
|
||||
- Two phases, warped by `globalFlow`, which is
|
||||
`Tri3D = cross(normalize(tri3(P)), normalize(tri3(1.618P))) × 15`.
|
||||
- The fine octave at ×8 is evaluated at a `pos` whose y the coarse octave has
|
||||
already displaced.
|
||||
- Amplitude −36.17.
|
||||
|
||||
Self's reading, tested:
|
||||
|
||||
- **"The warped ray is an exact polyline."** This holds for the warp *inside*
|
||||
`triNoise3d`. It does not hold for Aetheria's flow: `normalize` and `cross`
|
||||
make the flow piecewise rational. With the normalize dropped, the cross product
|
||||
of two piecewise-linear vectors is piecewise quadratic. tri composed with a
|
||||
piecewise polynomial stays piecewise polynomial of the same degree, with
|
||||
breakpoints at quadratic roots, so that variant is still closed-form.
|
||||
Counted along the real flow at the worst shift, the kinks run 15% to 30% above
|
||||
the straight-ray counts, but the pieces between them are curved.
|
||||
- **"The clamp roots are linear."** This holds only if the exponent is 1. With
|
||||
−0.25·flatness, each piece is `(a + bt)^e`. One such piece has a closed-form
|
||||
integral, but the clamp's root on a sum of two powered phases plus the
|
||||
smoothstep fade has none.
|
||||
- **"Whole periods give the exact mean."** This holds for one triangle wave at
|
||||
whole periods, where the mean is exactly 0.25. It fails for the composed form,
|
||||
which has no period along a general line; the scales 2, 1.8 and 1.2 and the
|
||||
nested warp are incommensurate.
|
||||
- Measured on lines, the span-mean std of `triNoise3d` is 0.029 at ℓ = 1,
|
||||
0.010 at ℓ = 8 and 0.0042 at ℓ = 64, against a point std of 0.083. That is
|
||||
about ℓ^-0.47, the same random-field decay as simplex.
|
||||
- Its bias against the global mean of 0.1995 is within ±0.0015, so the
|
||||
expectation is unbiased. It is not exact.
|
||||
- **The cost decides it.** The exact piecewise-linear walk is verified, matching
|
||||
a 1e-4 quadrature within 3.4e-8. But the nest has 77.7 linear pieces per noise
|
||||
unit of straight line, against 3.44 lattice points for simplex.
|
||||
- One piece costs 1.38 point evaluations with a derivative carried.
|
||||
- At Aetheria's scale, on the wells rays, the pieces per world unit and the
|
||||
exact cost relative to the march are:
|
||||
|
||||
| Octave | Pieces per world unit | Exact cost / march |
|
||||
|---|---|---|
|
||||
| x1 | 0.20 | 2.8x |
|
||||
| x2 | 0.38 | 5.5x |
|
||||
| x4 | 0.76 | 11x |
|
||||
| x8 (shipped fine) | 1.5 | 22x |
|
||||
| x64 | 12 | 176x |
|
||||
|
||||
- On the void rays it is 4.1x at x1 and 29x at x8.
|
||||
- At the same time the march's RMS error on the span mean is already small:
|
||||
2.4e-3 at x1 and 1.7e-2 at x8.
|
||||
|
||||
## Per-basis verdict
|
||||
|
||||
| Basis | Exact line integral | Under the shipped warp | Optical depth | Verdict |
|
||||
|---|---|---|---|---|
|
||||
| Simplex (CultMath `snoise`) | Closed form, 0.16 snoise per lattice point, 3.44 points per noise unit; validated | Affine spans of 100 to 300 world at τ = 0.1 cell; error floor about 1e-2 | Not delivered: the void's pow profile and the wells' clamp make ρ nonlinear in n; the exact-mean transmittance loses 3.6x and 22x | **Viable kernel, wrong target.** Pays only if the density were affine in n over the span, or as a control variate for a march (survey §4, Kettunen 2021) |
|
||||
| Triangle (`triNoise3d`) | Closed form per linear piece; validated | Not piecewise linear under Aetheria's normalized-cross flow or the −0.25 power; made linear by exponent 1 and a non-normalized flow | Same nonlinearity, plus 78 pieces per noise unit | **Loses.** 3x to 22x the march even where its preconditions hold |
|
||||
| Gabor kernels (survey §1.2, not probed) | Closed form for any affine-transformed kernel (complex erf, at most 16 terms) | The affine warp spans above transfer directly, with each span a whitening transform | Same density-nonlinearity limit | **Candidate smooth basis for large structure**, to be measured only if the density is first made linear in the noise over a span |
|
||||
|
||||
## What would change the verdict
|
||||
|
||||
- **A density that is affine in the noise inside a span.** For example, the
|
||||
void's ramp replaced by a linear ramp in d', with clamp crossings bracketed by
|
||||
the interval bound. Exact simplex integration would then deliver optical depth
|
||||
directly in the 54% of void length that is outside the ramp's clamps. As
|
||||
measured, that 54% is constant density and needs no noise at all.
|
||||
- **Exact integration as a control variate,** not a replacement. The exact mean
|
||||
is cheap and unbiased for ∫n, and the march corrects the nonlinear residual.
|
||||
That is the Kettunen construction. It was not measured here.
|
||||
- **Wider skipping.** The operator's first idea, skipping space outside the warp
|
||||
range, is already what the interval envelope does, and the probe's active
|
||||
intervals are its output.
|
||||
- On the void the noise matters over only about 140 world per ray.
|
||||
- On the wells, opacity ends the ray within a few world units of entering the
|
||||
unclamped region.
|
||||
425
docs/research/analytic-noise-integration-prior-art.md
Normal file
425
docs/research/analytic-noise-integration-prior-art.md
Normal file
|
|
@ -0,0 +1,425 @@
|
|||
# Analytic Noise Integration Along Warped Rays: Prior Art Survey
|
||||
|
||||
This is the facts file for an idea the operator raised on 2026-10-03:
|
||||
|
||||
> "I would be happy if we could just skip the space we know has no meaningful structure
|
||||
> because it's outside of the noise warp range. But what you said about affine arithmetic
|
||||
> makes me wonder if we can somehow, even within the distorted domain, figure out a series
|
||||
> of optimal (in terms of extracting structure over multiple frames) spans for which we can
|
||||
> analytically integrate the noise gradients over those ray segments."
|
||||
|
||||
Self's sketch, as given to this pass:
|
||||
|
||||
- Simplex noise along a straight ray is piecewise polynomial in t, so its line integral
|
||||
is closed-form per crossed cell.
|
||||
- A domain warp p + w(p) is nearly affine over a short span, with an affine-arithmetic
|
||||
error bound, so within that span the warped ray is a straight line in noise space.
|
||||
- Low octaves are integrated exactly. High octaves are replaced by their expectation,
|
||||
with a variance bound.
|
||||
- Clamped density max(0, n - c) is integrated by root-finding per piece.
|
||||
- Spans are cached and refined across frames.
|
||||
|
||||
Eyes pass, 2026-10-03. This file gives facts and evidence pointers only. It makes no
|
||||
recommendation.
|
||||
|
||||
Verification marks:
|
||||
|
||||
- **[fetched]** The claim was read in the cited source's full text during this pass.
|
||||
PDFs were converted with `pdftotext -layout`.
|
||||
- **[search]** The claim came from a search-result summary or abstract, not a full read.
|
||||
- **[derivation]** The claim is elementary mathematics worked out in this pass from a
|
||||
fetched definition. It is not a claim made by any cited source.
|
||||
- **[not found]** The pass searched for this kind of work and found nothing.
|
||||
|
||||
## 0. Premises of the sketch, checked against definitions
|
||||
|
||||
- **[fetched] + [derivation]** Simplex noise kernel degree. Gustavson, *Simplex noise
|
||||
demystified* (2005), gives the 3D reference code. Each of the four simplex corners
|
||||
contributes `t^4 * dot(g, d)` with `t = 0.6 - |d|^2`, and the contribution is zero
|
||||
when `t < 0`. On a straight ray `d` is affine in the ray parameter, so `|d|^2` is
|
||||
quadratic and each corner term is a polynomial of degree 8 + 1 = 9. The pieces have
|
||||
two kinds of breakpoint: the simplex faces the ray crosses (where the corner set
|
||||
changes), and the entry and exit of each corner's support sphere (`|d|^2 = 0.6`).
|
||||
Both kinds are roots of polynomials of degree 2 or lower in the ray parameter, so the
|
||||
breakpoints are closed-form. With the 0.6 radius, the support extends past the
|
||||
simplex, and the reference code truncates it at the simplex boundary. The resulting
|
||||
small discontinuity across faces is a known property of that constant. It does not
|
||||
change the piecewise-polynomial structure.
|
||||
- **[derivation]** Classic Perlin noise (Perlin 2002 quintic fade `6t^5 - 15t^4 + 10t^3`,
|
||||
read in Gustavson's text **[fetched]**) is, within one lattice cube along a straight
|
||||
ray, a polynomial of degree 3 x 5 + 1 = 16. Its breakpoints are the cube faces.
|
||||
- **[fetched]** Piece count grows with frequency. Balint (CESCG 2019, section 2)
|
||||
states that many noise functions are piecewise integrable, but the number of pieces
|
||||
is linear in the noise frequency. Their cost is therefore similar to numerical
|
||||
integration. Balint designed cosine noise to escape this limit (section 1.1 below).
|
||||
- **[derivation]** For the clamp `max(0, n - c)` on a degree-9 or degree-16 piece,
|
||||
the roots of `n - c` are needed. Polynomials of degree 5 or more have no general
|
||||
closed-form roots (Abel-Ruffini), so the clamp needs numerical root isolation per
|
||||
piece, for example Sturm sequences, Descartes' rule or Bernstein-basis subdivision.
|
||||
The integral between the isolated roots is closed-form.
|
||||
|
||||
## 1. Closed-form line integrals of noise, and analytic optical depth
|
||||
|
||||
### 1.1 Cosine noise: Balint, *Closed Form Transmittance in Heterogeneous Media Using Cosine Noise*, CESCG 2019 (non-peer-reviewed)
|
||||
|
||||
- **[fetched]** It computes noise defined as an offset plus a sum of cosines of
|
||||
`x . S_i`. The paper uses 24 quasirandom vectors S_i, with Sobol directions on the
|
||||
sphere and lengths in [0.8, 1.2], to look roughly like Perlin noise. Fractal octaves
|
||||
are further cosine sets. Its line integral is a sum of sines, so the optical depth
|
||||
over any segment is exact. The paper says this takes two noise samples, one at each
|
||||
segment end. It also gives closed-form distance sampling, by inverting the integral
|
||||
with binary search.
|
||||
- **[fetched]** Cost: two noise-sized evaluations per segment, independent of octave
|
||||
count. Table 1 reports transmittance evaluation at 179 ms closed-form against
|
||||
1250 ms for delta tracking, about 7x faster. A real-time demo with 16 samples ran
|
||||
at 80 fps at 675 x 1200 (RTX 2080 Ti).
|
||||
- **[fetched]** Error: exact, with no error term, for the bare sum. The limits are
|
||||
stated in section 6. Multiplying by a shape function, or composing with a shaping
|
||||
function, generally destroys the elementary antiderivative. The workarounds
|
||||
recover exactness only piecewise: constant multipliers between bounding isosurfaces,
|
||||
or a cubic polynomial interpolant of the multiplier along the ray, since the product
|
||||
of a polynomial and cosines has an elementary antiderivative. Negative densities from
|
||||
a low offset are handled by clamping samples and integrals, which is not an exact
|
||||
`max(0, .)` integral. Domain warp is not discussed.
|
||||
|
||||
### 1.2 Gabor kernels: Condor, Hermann, Yurtsever, Didyk, *Gabor Fields: Orientation-Selective Level-of-Detail for Volume Rendering*, ACM TOG 45(4) art. 62, 2026 (arXiv 2602.05081)
|
||||
|
||||
- **[fetched]** It computes closed-form definite line integrals of anisotropic 3D Gabor
|
||||
kernels along an arbitrary ray segment (eq. 9). Each kernel is whitened into its
|
||||
canonical space with a ZCA matrix, so any covariance, that is any affine-transformed
|
||||
kernel, uses the same formula. The segment integral is the real part of a
|
||||
complex-erf (Faddeeva) difference.
|
||||
- **[fetched]** Cost: the complex erf is evaluated by a truncated Taylor series with
|
||||
early exit, capped at 16 terms. Segments shorter than 1e-4 in whitened units fall back
|
||||
to a single midpoint evaluation. Kernels are spatially clamped with an adaptive extent
|
||||
that shrinks with frequency (eq. 15). The paper also renders procedural clouds as
|
||||
Gaussians modulated by Gabor noise.
|
||||
- **[fetched]** Error: each segment integral is exact apart from the erf truncation.
|
||||
Orientation-selective masking of kernels whose line integral is near zero trades a
|
||||
small error, or variance under stochastic selection, for speed. The paper reports
|
||||
about 1.78x to 1.96x speedups. Per segment the density-integral estimator is
|
||||
unbiased, but transmittance is biased by Jensen's inequality. Eq. 19 gives the
|
||||
second-order bias as `0.5 * Var(tau) * exp(-E[tau])`.
|
||||
|
||||
### 1.3 Analytically integrable media, older
|
||||
|
||||
- **[search]** Iser, *Real-time Light Transport in Analytically Integrable
|
||||
Quasi-heterogeneous Media*, CESCG 2018. Balint cites it **[fetched]** as using only
|
||||
exponential and spherical density functions.
|
||||
- **[fetched via Gabor Fields related work]** The closed-form Gaussian-primitive
|
||||
transmittance line (Knoll et al. 2021; Condor et al. 2025, *Don't Splat your
|
||||
Gaussians*) is the base that Gabor Fields extends.
|
||||
|
||||
### 1.4 Piecewise-polynomial segment integration in scientific volume rendering
|
||||
|
||||
- **[fetched]** Engel, Kraus, Ertl, *High-Quality Pre-Integrated Volume Rendering Using
|
||||
Hardware-Accelerated Pixel Shading*, Graphics Hardware 2001. The scalar field along
|
||||
the ray is assumed piecewise linear between samples. The volume rendering integral of
|
||||
each linear segment, through an arbitrary nonlinear transfer function, is then one
|
||||
lookup in a table indexed by front scalar, back scalar and segment length. Cost: one
|
||||
texture lookup per segment, plus recomputing the table when the transfer function
|
||||
changes. Error: exact for the piecewise-linear model. The model error is the
|
||||
scalar field's deviation from linear between samples.
|
||||
- **[search]** Williams, Max, Stein, *A High Accuracy Volume Renderer for Unstructured
|
||||
Data*, IEEE TVCG 4(1), 1998. Exact integration through tetrahedra with linearly
|
||||
varying scalar and piecewise-linear transfer functions.
|
||||
|
||||
### 1.5 Polynomial noise along a ray
|
||||
|
||||
- **[not found]** No published closed-form segment integral of Perlin or simplex noise
|
||||
was found, as a method or a code library. Balint's remark in section 0 is the only
|
||||
published statement found on the piecewise approach, and it dismisses it on cost
|
||||
grounds.
|
||||
|
||||
## 2. Noise designed for analytic filtering or integration
|
||||
|
||||
- **[fetched]** Lagae, Lefebvre, Drettakis, Dutré, *Procedural Noise using Sparse Gabor
|
||||
Convolution*, ACM TOG 28(3), 2009. It computes a sparse-convolution noise of Poisson
|
||||
impulses with Gabor kernels. Each kernel is a Gaussian in frequency, so filtering with
|
||||
a Gaussian pixel filter multiplies Gaussians, which gives an analytically filtered
|
||||
kernel. Cost: the paper typically uses 100 impulses per kernel, or 25 to 50 at lower
|
||||
densities. Table 2 (GTX 280) reports, at 20 impulses per cell, 290 fps for 2D noise,
|
||||
111 fps for unfiltered surface noise and 50 fps for filtered surface noise. Error:
|
||||
the filtering is exact for a Gaussian filter. The noise statistics converge with
|
||||
impulse density.
|
||||
- **[fetched]** Lagae, Drettakis, *Filtering Solid Gabor Noise*, ACM TOG 30(4), 2011. It
|
||||
slices solid Gabor noise, filters each slice of each Gabor kernel, and gets a
|
||||
generalisation of the projection-slice theorem. It also states that wavelet noise
|
||||
integrates solid noise perpendicular to the surface. That is a line integral of noise
|
||||
along the normal, done in the basis.
|
||||
- **[search]** Cook, DeRose, *Wavelet Noise*, ACM TOG 24(3), 2005. A quadratic B-spline
|
||||
noise band, which is almost band-limited, built from a precomputed coefficient tile.
|
||||
Its 3D-to-surface projection integrates the noise along the normal. The original PDF
|
||||
was not retrievable in this pass. Pixar and ACM both returned HTML.
|
||||
- **[fetched, survey]** Lagae et al., *A Survey of Procedural Noise Functions*, CGF 2010.
|
||||
- Lewis's sparse convolution noise has a power spectrum equal to the kernel's,
|
||||
scaled.
|
||||
- Frequency clamping (Norton, Rockwood, Skolmoski 1982) cancels bands above the filter
|
||||
rate. It works only for narrowly band-pass noise, and Perlin noise is only weakly
|
||||
band-pass.
|
||||
- Nonlinear functions of noise, such as thresholds and colour maps, are not filtered
|
||||
by filtering the noise. That is unsolved in general.
|
||||
- Heidrich, Slusallek, Seidel 1998 (below) computes an area average of a procedural
|
||||
shader with an error bound, using affine arithmetic.
|
||||
- Perlin noise's amplitude distribution is visibly non-Gaussian, because it is zero at
|
||||
every lattice point and has few gradients. The other noises surveyed are
|
||||
approximately Gaussian.
|
||||
- **[fetched, via the survey above]** "Filtering procedural textures" lineage:
|
||||
- Rhoades et al. 1992 filters the colour table over `[N - e, N + e]`.
|
||||
- Hart et al. 1999 sets `e` from the local noise gradient.
|
||||
- Lagae 2009 sets the range from the analytically known loss of variance.
|
||||
|
||||
## 3. Affine arithmetic, reduced AA, Taylor models, and bounds on warps
|
||||
|
||||
### 3.1 Gamito and Maddock
|
||||
|
||||
- **[fetched]** Gamito, Maddock, *Ray Casting Implicit Fractal Surfaces with Reduced
|
||||
Affine Arithmetic*, The Visual Computer 23:155-165, 2007. The full method is read in
|
||||
Gamito's PhD thesis (Sheffield), sections 5.3 to 5.4.
|
||||
- **Computes:** a root of `g(t) = 0` along a ray, by subdividing intervals of t. Each
|
||||
interval is tested with an inclusion `G(T)` computed in reduced AA (Messine's AF1).
|
||||
The form is `t0 + t1 e1 + t2 e2`: e1 is the shared ray-parameter symbol, and e2
|
||||
absorbs every new nonlinearity by condensation after each operation.
|
||||
- **Noise in RAA:** gradient-noise kernels lose no correlation under RAA, because the
|
||||
three multiplications are local to one kernel and the cubic Hermite fade is done by
|
||||
a single Chebyshev affine approximation. The same holds for sparse convolution
|
||||
noise. Cellular noise loses accuracy, because `min` needs cancellation between
|
||||
condensed terms, and the F2 and F3 kernels were not implementable.
|
||||
- **Interval optimisation:** the parallelogram `g1/t1` slope plus or minus `g2`
|
||||
shrinks `[ta, tb]` before subdividing (eq. 5.27).
|
||||
- **Cost:** Table 5.2, gradient-noise hypertexture, average evaluations per ray and
|
||||
time:
|
||||
|
||||
| Method | Evaluations per ray | Time |
|
||||
|---|---|---|
|
||||
| IA | 116.57 | 7m35s |
|
||||
| Standard AA | 61.69 | 40m41s |
|
||||
| RAA | 61.69 | 6m43s |
|
||||
| RAA + interval optimisation | 46.39 | 5m04s |
|
||||
|
||||
RAA costs three numbers per quantity against two for IA. Standard AA is tight
|
||||
but slow because its error-symbol lists grow.
|
||||
- **Error bound:** conservative inclusion, as proven for AA by Comba and Stolfi 1993.
|
||||
Rounding error is ignored.
|
||||
- **[fetched]** Gamito thesis, chapter 9, *Surface Deformation with Flow Mapping*.
|
||||
- Domain deformation `f(d(x))` with `d` defined by streamlines, that is by an ODE.
|
||||
This is the case closest to a domain warp in this survey.
|
||||
- Gamito states that a robust and tight AA estimate of the deformed ray `s(t)` was not
|
||||
obtainable through the numerical ODE solution, so robustness was given up.
|
||||
- The replacement test uses Lipschitz unbounding spheres at `s(ta)` and `s(tb)`. A
|
||||
span is skipped if `|s(tb) - s(ta)| < min(ra, rb)` (eq. 9.23). A sharp turn of the
|
||||
deformed ray between the endpoints can make this test wrong.
|
||||
- He names truncated Taylor-series range estimation (Nedialkov et al. 2004) as the
|
||||
possible fix, at higher cost and complexity.
|
||||
|
||||
### 3.2 Other affine and interval arithmetic sources
|
||||
|
||||
- **[fetched, bibliographic]** Comba, Stolfi, *Affine Arithmetic and its Applications to
|
||||
Computer Graphics*, SIBGRAPI 1993. de Figueiredo, Stolfi, *Affine Arithmetic: Concepts
|
||||
and Applications*, Numerical Algorithms 37, 2004. Gamito cites both. AA keeps
|
||||
first-order correlations through shared noise symbols. Each nonaffine operation adds
|
||||
one symbol, whose coefficient bounds the linearisation error. Chebyshev or min-range
|
||||
affine approximations give that coefficient for unary functions.
|
||||
- **[search]** Knoll, Hijazi, Kensler, Schott, Hansen, Hagen, *Fast Ray Tracing of
|
||||
Arbitrary Implicit Surfaces with Interval and Affine Arithmetic*, CGF 28(1), 2009.
|
||||
Inclusion-preserving reduced AA, SIMD CPU at interactive rates, and a stackless GPU
|
||||
version.
|
||||
- **[fetched, abstract]** Fryazinov, Pasko, Comninos, *Fast Reliable Ray-tracing of
|
||||
Procedurally Defined Implicit Surfaces Using Revised Affine Arithmetic*, Bournemouth
|
||||
TR-NCCA-2009-04. Revised AA, which also keeps one accumulated error symbol, is
|
||||
reported fastest among the IA and AA variants compared, including on pseudo-random
|
||||
procedural objects.
|
||||
- **[fetched]** Sharp, Jacobson, *Spelunking the Deep: Guaranteed Queries on General
|
||||
Neural Implicit Surfaces via Range Analysis*, ACM TOG 41(4), 2022. This is AA through
|
||||
long compositions of nonlinear layers, which is structurally like noise composed with
|
||||
a warp. Table 1 compares the variants. Time is relative to one scalar evaluation,
|
||||
length is the 1D region that can be certified, and raycast time is relative to the
|
||||
best method:
|
||||
|
||||
| Variant | Time | Length | Raycast time |
|
||||
|---|---|---|---|
|
||||
| Interval | 2.4x | 0.011 | 34.3x |
|
||||
| Affine-full | 95.3x | 0.821 | 8.4x |
|
||||
| Affine-fixed (no new symbols kept, extra error condensed into one) | 4.7x | 0.306 | 1.0x |
|
||||
|
||||
The paper uses affine-fixed for ray casting and affine-full for 3D queries.
|
||||
- **[fetched, survey quote of abstract]** Heidrich, Slusallek, Seidel, *Sampling of
|
||||
Procedural Shaders using Affine Arithmetic*, ACM TOG 17(3):158-176, 1998. It computes
|
||||
the average of a procedural shader over a finite area, with an AA error bound.
|
||||
- **[fetched, project page]** Keeter, *Massively Parallel Rendering of Complex
|
||||
Closed-Form Implicit Surfaces*, ACM TOG 39(4), 2020. Interval arithmetic over a
|
||||
shallow, high-branching tile hierarchy does two things: it skips empty tiles, and it
|
||||
prunes the expression tape per tile. One benchmark drops the expression size by about
|
||||
two orders of magnitude. It requires only C0 continuity, so warps and blends that break
|
||||
Lipschitz continuity are allowed.
|
||||
|
||||
### 3.3 Lipschitz bounds through warps
|
||||
|
||||
- **[fetched]** Galin, Guérin, Paris, Peytavie, *Segment Tracing Using Local Lipschitz
|
||||
Bounds*, CGF 39(2), 2020. It computes a local Lipschitz bound over a ray segment
|
||||
instead of a global one. Section 4.4 covers warps `f o w^-1`, and bounds the gradient
|
||||
by the product of the field gradient bound over the transformed segment and the
|
||||
Jacobian norm bound over the segment. Cost: fewer field queries than sphere tracing,
|
||||
with no acceleration structure. Error: conservative, if the local bounds are
|
||||
conservative.
|
||||
- **[fetched]** Seyb, Jacobson, Nowrouzezahrai, Jarosz, *Non-linear Sphere Tracing for
|
||||
Rendering Deformed Signed Distance Fields*, ACM TOG 38(6), 2019.
|
||||
- **Computes:** the ray in deformed space as a curve in undeformed space, by
|
||||
integrating an ODE whose derivative is the inverse-deformation Jacobian times the ray
|
||||
direction. An initial value comes from rasterising a deformed hull mesh.
|
||||
- **Error control:** step requirements for the curve are separated from those for the
|
||||
SDF. Adaptive Runge-Kutta (RKF45 and DP54 evaluated) is used far from the surface,
|
||||
and forward Euler near it, against an error tolerance.
|
||||
- **Scope:** surfaces only. There is no density integration.
|
||||
- **[fetched]** Moinet, Neyret, *Fast Sphere Tracing of Procedural Volumetric Noise for
|
||||
Very Large and Detailed Scenes*, CGF 2025 (Eurographics), HAL hal-05046040.
|
||||
- **Computes:** sphere tracing of FBM density fields, using first- and second-order
|
||||
(2-Lipschitz) forward inclusion functions. The FBM partial sums act as a nested
|
||||
bounding volume hierarchy: the remaining octaves are bounded by their amplitude sum
|
||||
`s(i+1, n)`, so evaluation stops early once a point is provably outside.
|
||||
- **Cost:** up to 12x faster than classical sphere tracing on opaque or constant-density
|
||||
scenes. Only up to 1.8x on non-constant density, and that gain comes from empty-space
|
||||
skipping alone. One example frame: 16 ms against 110 ms naive at 1024 x 1024 on a
|
||||
4080 Ti.
|
||||
- **Stated limits:** FBM used as a domain warp is not supported, nor are nonlinear
|
||||
transforms of FBM. The paper names analytic estimation of the contribution of
|
||||
sub-pixel detail as an open problem.
|
||||
|
||||
### 3.4 Taylor models
|
||||
|
||||
- **[search]** Berz, Makino, *Verified Integration of ODEs and Flows Using Differential
|
||||
Algebraic Methods on High-Order Taylor Models*, Reliable Computing 4, 1998. Makino,
|
||||
Berz, *Taylor Models and Other Validated Functional Inclusion Methods*, IJPAM 2003.
|
||||
- **Computes:** a Taylor model is a polynomial of order n plus an interval remainder
|
||||
bound, which encloses any function given as code over a box. The sharpness of the
|
||||
remainder scales with the box width to the power n + 1. The method also gives
|
||||
verified ODE flows.
|
||||
- **Verified integration:** Berz and Makino also published *New Methods for
|
||||
High-Dimensional Verified Quadrature* (Reliable Computing 1999). There the integral
|
||||
of the polynomial part is exact, and the remainder bound times the domain measure
|
||||
bounds the error.
|
||||
- First-order AA is the n = 1 case in spirit: an affine part plus a bounded remainder.
|
||||
|
||||
### 3.5 Affine bound on a warp over a span
|
||||
|
||||
- **[derivation]** Over a segment of half-length r, the best affine approximation
|
||||
(Chebyshev) of a C2 coordinate function has sup error at most `r^2 / 4` times the
|
||||
maximum of its second derivative along the segment. Linear interpolation of the
|
||||
endpoints has `r^2 / 2` times that maximum. The noise error caused by a displacement
|
||||
error of size `delta` is at most `L_noise * delta`. This is the same chain-rule
|
||||
structure Galin uses in section 4.4.
|
||||
|
||||
## 4. Statistical or expected-value treatment of high-frequency detail
|
||||
|
||||
- **[fetched]** Heitz, Nowrouzezahrai, Poulin, Neyret, *Filtering Color Mapped Textures
|
||||
and Surfaces*, I3D 2013. It computes the filtered value of a colour map applied to a
|
||||
procedural function as `<C, N(mu, sigma^2)>`. The noise's footprint distribution is
|
||||
replaced by a Gaussian with the footprint's mean and variance. This equals the colour
|
||||
map convolved with `N(0, sigma^2)` and evaluated at the mean, which is precomputed into
|
||||
a 2D table indexed by (mu, sigma). Cost: one lookup after mu and sigma are computed.
|
||||
Error: exact when the driving function's footprint distribution is Gaussian. For a
|
||||
specific noise instance it converges as the footprint grows, and the paper states this
|
||||
limit.
|
||||
- **[derivation]** For `X ~ N(mu, sigma^2)`, `E[max(0, X - c)] = (mu - c) Phi(z) +
|
||||
sigma phi(z)` with `z = (mu - c) / sigma`. This is the rectified-Gaussian mean, and the
|
||||
scalar instance of the Heitz 2013 construction for the map `max(0, . - c)`. The
|
||||
survey's fetched finding that Perlin noise is non-Gaussian bears on how accurate it is.
|
||||
- **[search]** Olano, Baker, *LEAN Mapping*, I3D 2010. Dupuy et al., *LEADR Mapping*, ACM
|
||||
TOG 32(6), 2013. They store the first and second moments of slopes in mipmaps. Linear
|
||||
filtering of the moments gives a Gaussian or Beckmann slope distribution per
|
||||
footprint. Cost: two extra texture channels and linear filtering. Error: the Gaussian
|
||||
assumption.
|
||||
- **[fetched]** Gabor Fields (1.2): band and orientation masking of high-frequency
|
||||
kernels, with the Jensen bias of transmittance `~ 0.5 Var(tau) exp(-E[tau])`.
|
||||
- **[search]** Vicini, Jakob, Kaplanyan, *A Non-exponential Transmittance Model for
|
||||
Volumetric Scene Representations*, ACM TOG 40(4), 2021. Bitterli et al., *A Radiative
|
||||
Transfer Framework for Non-exponential Media*, ACM TOG 37(6), 2018. Jarabo, Aliaga,
|
||||
Gutierrez 2018, arXiv 1805.02651. Unresolved, correlated sub-voxel density makes
|
||||
transmittance non-exponential. Positive correlation gives slower decay than exponential.
|
||||
- **[search]** Kettunen, d'Eon, Pantaleoni, Novák, *An Unbiased Ray-Marching
|
||||
Transmittance Estimator*, ACM TOG 40(4), 2021. A power-series estimator built around a
|
||||
control variate. The control variate is a ray-marched mean-density estimate, and rare
|
||||
higher-order terms remove the bias. It is relevant as the known way to make a
|
||||
deterministic or expected-value optical depth unbiased.
|
||||
- **[fetched]** Schneider, *The Real-time Volumetric Cloudscapes of Horizon: Zero Dawn*,
|
||||
SIGGRAPH 2015 Advances course. The high-detail noise is applied only as erosion where
|
||||
the low-detail sample is non-zero. Rays take cheap large steps until the low-detail
|
||||
isosurface is hit, step back once, and then take full samples. After several zero
|
||||
samples they return to cheap stepping. This is an octave-level skip heuristic with no
|
||||
bound. Moinet (3.3) is the bounded version for FBM.
|
||||
|
||||
## 5. Temporal reuse of per-pixel or per-tile raymarch structure
|
||||
|
||||
- **[fetched]** Schneider 2015 (above). The full raymarch cost about 20 ms. Each frame
|
||||
renders 1 of 16 pixels per 4 x 4 block into a quarter-resolution buffer, and
|
||||
reprojects the previous frame. Where reprojection fails, for example at screen edges,
|
||||
a low-resolution buffer is substituted. The paper reports 10x or more faster, with a
|
||||
target of about 2 ms on PS4.
|
||||
- **[search]** Klein, Strengert, Stegmaier, Ertl, *Exploiting Frame-to-Frame Coherence
|
||||
for Accelerating High-Quality Volume Raycasting on Graphics Hardware*, IEEE
|
||||
Visualization 2005. First-hit depths of the previous frame are reprojected by point
|
||||
splatting to estimate per-pixel ray start points. About 2x on typical datasets.
|
||||
- **[search]** Yagel, Shi, *Accelerating Volume Animation by Space-Leaping*, IEEE
|
||||
Visualization 1993. A C-buffer of first non-transparent voxel coordinates, updated
|
||||
across frames. Gudmundsson, Randén 1990 introduced inter-frame empty-space skipping.
|
||||
- **[search]** Scherzer et al., *Temporal Coherence Methods in Real-Time Rendering*,
|
||||
CGF 2012 STAR (Eurographics 2011). Reprojection caches, with depth-tolerance validity
|
||||
tests for disocclusion.
|
||||
- **[search]** Hillaire, *Physically Based Sky, Atmosphere and Cloud Rendering in
|
||||
Frostbite*, SIGGRAPH 2016 course. Temporal reprojection for volumetric clouds. Details
|
||||
were not read in this pass.
|
||||
- **[fetched]** Gamito thesis, chapter 7: progressive refinement rendering of
|
||||
Lipschitz-bounded and AA-bounded surfaces. It refines across passes within one image,
|
||||
not across animated frames.
|
||||
- **[not found]** No source was found that caches per-ray span partitions, affine
|
||||
forms or certified intervals across frames and refines them.
|
||||
|
||||
## 6. Warp linearisation combined with exact segment integration
|
||||
|
||||
- **[not found]** No source was found that combines piecewise affine linearisation of a
|
||||
domain warp, with an error bound, and exact closed-form integration of noise over the
|
||||
resulting segments.
|
||||
- Nearest pieces, each covering part of the combination:
|
||||
|
||||
| Source | What it covers | What it leaves out |
|
||||
|---|---|---|
|
||||
| Gamito ch. 9 | Bounding a deformed ray | No integral. AA gave up on the ODE warp |
|
||||
| Seyb 2019 | ODE curved ray with adaptive error control | Surfaces only |
|
||||
| Galin 2020 | Jacobian-norm local bounds through warps | Surfaces, not integration |
|
||||
| Keeter 2020 | Interval pruning that tolerates warps | Surfaces |
|
||||
| Gabor Fields 2026 | Closed form for any affine-transformed Gabor kernel along a segment | No warp |
|
||||
| Balint 2019 | Closed form for cosine noise | Composition and warps break it |
|
||||
| Pre-integration (Engel 2001) | Exact per-segment integral | Under a piecewise-linear model of the scalar |
|
||||
| Moinet 2025 | Bounded FBM octave skipping | Excludes FBM used as a domain warp |
|
||||
|
||||
- **[search]** Rezk-Salama et al., *Fast Volumetric Deformation on General Purpose
|
||||
Hardware*, Graphics Hardware 2001. Fetched text: piecewise-trilinear deformation
|
||||
patches with adaptive subdivision, rendered by object-aligned slicing. The
|
||||
approximate inverse is `x + O(delta^2)`. A search summary describes the deformed rays
|
||||
as polylines, but the fetched text uses slicing, not per-ray exact integration.
|
||||
|
||||
## Sources
|
||||
|
||||
- Balint 2019: https://www.cl.cam.ac.uk/~rkm38/pdfs/balint2019cosine_noise.pdf
|
||||
- Condor et al. 2026, Gabor Fields: https://arxiv.org/pdf/2602.05081
|
||||
- Gamito PhD thesis: https://staffwww.dcs.shef.ac.uk/people/S.Maddock/phd_theses/gamito/thesis_small.pdf
|
||||
- Gamito, Maddock 2007: https://link.springer.com/article/10.1007/s00371-006-0090-7
|
||||
- Lagae et al. 2009, Gabor noise: https://www-sop.inria.fr/reves/Basilic/2009/LLDD09/LLDD09PNSGC_paper.pdf
|
||||
- Lagae, Drettakis 2011: https://inria.hal.science/inria-00606907/file/paper_0049_preprint.pdf
|
||||
- Lagae et al. 2010 survey: https://www-sop.inria.fr/reves/Basilic/2010/LLCDDELPZ10/LLCDDELPZ10STARPNF.pdf
|
||||
- Heitz et al. 2013: https://inria.hal.science/hal-00765799
|
||||
- Sharp, Jacobson 2022: https://arxiv.org/pdf/2202.02444
|
||||
- Seyb et al. 2019: https://cs.dartmouth.edu/~wjarosz/publications/seyb19nonlinear.html
|
||||
- Galin et al. 2020: https://hal.science/hal-02507361
|
||||
- Moinet, Neyret 2025: https://inria.hal.science/hal-05046040
|
||||
- Keeter 2020: https://www.mattkeeter.com/research/mpr/
|
||||
- Fryazinov et al. 2009: https://eprints.bournemouth.ac.uk/11708/1/TR-NCCA-2009-04.pdf
|
||||
- Knoll et al. 2009: https://onlinelibrary.wiley.com/doi/10.1111/j.1467-8659.2008.01189.x
|
||||
- Berz, Makino 1998: https://link.springer.com/article/10.1023/A:1024467732637
|
||||
- Engel et al. 2001: https://www3.cs.stonybrook.edu/~mueller/teaching/cse616/engel.pdf
|
||||
- Gustavson 2005: https://cgvr.cs.uni-bremen.de/teaching/cg_literatur/simplexnoise.pdf
|
||||
- Schneider 2015: https://advances.realtimerendering.com/s2015/
|
||||
- Kettunen et al. 2021: https://jannovak.info/publications/URM/URM.pdf
|
||||
- Vicini et al. 2021: https://dvicini.github.io/non-exponential-representation/
|
||||
- Rezk-Salama et al. 2001: https://www3.cs.stonybrook.edu/~mueller/teaching/cse616/p17-rezk-salama.pdf
|
||||
- Klein et al. 2005: https://www.researchgate.net/publication/4188150
|
||||
158
docs/research/cross-process-file-locking-prior-art.md
Normal file
158
docs/research/cross-process-file-locking-prior-art.md
Normal file
|
|
@ -0,0 +1,158 @@
|
|||
# Cross-process file locking and atomic replace: prior art
|
||||
|
||||
Facts only. Gathered 2026-10-02 for fork `variants:question:ts-python-write-lock`. No conclusions, no recommendation.
|
||||
|
||||
Provenance legend: **[src]** read from CultLib source this pass; **[primary]** vendor/spec/upstream doc or source fetched this pass (the fetch tool summarises pages through a small model, so quoted phrasing is paraphrase-grade unless shown in quotes); **[secondary]** search-result snippet or third-party issue, weak; **[UNVERIFIED]** not confirmed by any source read, or derived by inference only. Nothing here was tested by running code on Windows or Linux.
|
||||
|
||||
Dates caveat: the doc-site fetches reported release dates for `fs2 0.4.3` ("September 9, 2026") and `fs4 1.1.0` ("September 23, 2026"). The fs2 date is implausible against my memory of that crate (long stable, last release years earlier); treat crate dates as **[UNVERIFIED]**.
|
||||
|
||||
---
|
||||
|
||||
## 0. What CultLib does today (source, this checkout)
|
||||
|
||||
| Runtime | Lock | Temp name | Replace | Pointer |
|
||||
|---|---|---|---|---|
|
||||
| C# | Sidecar `<file>.lock`, `new FileStream(lockPath, OpenOrCreate, ReadWrite, FileShare.None, bufferSize 1)`. On `IOException`: if `wait` is false return null, else sleep 10 ms and retry for up to 30 s, after which the exception propagates. | `.{name}.{Guid:N}.tmp`, `FileMode.CreateNew`, `FileShare.None`, `WriteThrough`, `Flush(true)` | `File.Replace(temp, path, null)` if target exists, else `File.Move` | `F:\Projects\CultLib\src\GameCult.Caching\CultCache.cs` lines ~3475-3530 |
|
||||
| Rust | Sidecar `<file>.lock` (`.lock` appended to full file name), opened `create/read/write/truncate(false)` (std default share mode), then `fs2::FileExt::lock_exclusive` / `lock_shared` / `try_lock_exclusive` (WouldBlock => `None`). Unlock explicit, then drop. | `{name}.{uuid v4}.tmp`; staged file `sync_all` then closed | Unix: `fs::rename`. Windows: `MoveFileExW(MOVEFILE_REPLACE_EXISTING \| MOVEFILE_WRITE_THROUGH)` retried 25 times, 20 ms apart, on ERROR_ACCESS_DENIED(5)/SHARING_VIOLATION(32)/LOCK_VIOLATION(33). Comment cites a Muninn crash on 2026-09-11. | `F:\Projects\CultLib\packages\cultcache-rs\src\lib.rs` ~925-945, 1040-1084, 2870-3030; `Cargo.toml`: `fs2 = "0.4"`, edition 2024 |
|
||||
| TypeScript | None. In-process promise queue only (`next`/`result` chain). | `${file}.tmp-${pid}-${Date.now()}-${random}` (unique per writer) | `fs/promises.rename`, retried 10 times with 10 ms doubling on EPERM/EBUSY/EACCES; temp removed on error. No fsync of temp. | `F:\Projects\CultLib\packages\cultcache-ts\src\single-file-messagepack-backing-store.ts` ~143-205 |
|
||||
| Python | None. `threading.RLock` per store object (in-process only). | Fixed `path.with_suffix(suffix + ".tmp")`, i.e. `store.cc.tmp`, shared by all writers | `Path.replace` (`os.replace`); no fsync | `F:\Projects\CultLib\packages\cultcache-py\src\cultcache_py\stores.py` lines 70-82, 121-126 |
|
||||
|
||||
Both C# and Rust name the lock `<store path>.lock`. The same-name sidecar is the only thing the two currently share. Both also hold the lock around read-modify-write of the snapshot **[src]**. A lock file is never deleted by either (no stale-file problem; the lock is the kernel object, not the file's existence) **[src, inferred from absence of delete]**.
|
||||
|
||||
Note re the fork text: C# does use a lock (stated in the C# code comment: "excludes other handles in this process and in others alike").
|
||||
|
||||
---
|
||||
|
||||
## 1. Language and OS primitives
|
||||
|
||||
### 1.1 .NET `FileStream` / `FileShare`
|
||||
|
||||
- **Windows**: `FileShare` maps to the `dwShareMode` of `CreateFile`. `FileShare.None` = share mode 0: "Any request to open the file (by this process or another process) will fail until the file is closed." **[primary]** https://learn.microsoft.com/en-us/dotnet/api/system.io.fileshare . Win32 side: dwShareMode 0 "cannot be opened again, either by the application that opened it or by another application, until its handle has been closed"; failure is ERROR_SHARING_VIOLATION. **[primary]** https://learn.microsoft.com/en-us/windows/win32/fileio/creating-and-opening-files . Share modes are checked at **open** time and are not byte-range locks; they do not call `LockFileEx` **[inferred]**.
|
||||
- **Unix**: .NET emulates `FileShare` with advisory `flock(2)`. Source (`SafeFileHandle.Unix.cs`, runtime main): `lockOperation = (share == FileShare.None) ? LOCK_EX : LOCK_SH`, called as `FLock(handle, lockOperation | LOCK_NB)`; on `EWOULDBLOCK` an `IOException` is thrown; handle close issues `LOCK_UN`. **[primary]** https://raw.githubusercontent.com/dotnet/runtime/main/src/libraries/System.Private.CoreLib/src/Microsoft/Win32/SafeHandles/SafeFileHandle.Unix.cs
|
||||
- So non-`None` opens take a **shared** flock; `None` takes an **exclusive** flock; non-blocking in all cases. A plain read with `FileShare.ReadWrite | Delete` still takes `LOCK_SH`, which would conflict with a writer holding `LOCK_EX` on the same file (only relevant if the same file is opened both ways). **[inferred from source above]**
|
||||
- Disable switch: env `DOTNET_SYSTEM_IO_DISABLEFILELOCKING`; locking is off by default on Browser/WASI and iOS/tvOS (not Mac Catalyst). **[primary]**
|
||||
- Because it is advisory flock, it excludes only other openers that also take flock (other .NET processes, or any program calling flock on that file). It does not stop a process that merely `open()`s and writes. **[inferred]**
|
||||
- Since which .NET version: **[UNVERIFIED]**. I believe the flock-based FileShare emulation has existed since .NET Core 1.x/2.x, and .NET 6 rewrote FileStream into strategies while keeping it, but no source read this pass dates it.
|
||||
- Windows `FileShare.Delete` is meaningful; the Unix code does not differentiate it. **[primary]**
|
||||
- `File.Replace(src, dst, backup)` -> Win32 `ReplaceFile`; throws if volumes differ. **[primary]** https://learn.microsoft.com/en-us/dotnet/api/system.io.file.replace . Unix mapping to `rename` **[UNVERIFIED]**.
|
||||
|
||||
### 1.2 Rust
|
||||
|
||||
- `std::fs::File::lock`, `lock_shared`, `try_lock`, `try_lock_shared`, `unlock`: stable since **Rust 1.89.0**. **[primary]** https://doc.rust-lang.org/std/fs/struct.File.html
|
||||
- Unix/WASI: `flock` (`LOCK_EX`, `LOCK_SH`, `+LOCK_NB`, `LOCK_UN`). Windows: `LockFileEx` (flags `LOCKFILE_EXCLUSIVE_LOCK`, `LOCKFILE_FAIL_IMMEDIATELY`) and `UnlockFile`.
|
||||
- Docs: lock "may be advisory or mandatory", platform-dependent; on Windows the file must be opened for write (or read+append) for an exclusive lock; re-locking the same handle or a clone is unspecified, possibly deadlock; locks released when the file and all duplicated handles close; "this may change in the future".
|
||||
- `fs2` 0.4.x (what CultCache Rust uses): Unix `flock(2)`; Windows `LockFileEx` (source `src/windows.rs`: `lock_shared` passes 0, `lock_exclusive` passes `LOCKFILE_EXCLUSIVE_LOCK`, try variants add `LOCKFILE_FAIL_IMMEDIATELY`; `unlock` uses `UnlockFile`). Docs: "advisory"; do not lock one `File` concurrently; duplicated files need great care. **[primary]** https://docs.rs/fs2/latest/fs2/trait.FileExt.html , https://raw.githubusercontent.com/danburkert/fs2-rs/master/src/windows.rs . An earlier summary of the fs2 docs page said "LockFile" for Windows; the source file says `LockFileEx`. Maintenance status of fs2: **[UNVERIFIED]**.
|
||||
- `fs4`: fork of fs2 adding async, rustix instead of libc; docs say `flock`/`fcntl` on Unix, `LockFileEx` on Windows. Whether std's `File::lock` is mentioned or deprecates it: not stated on the page read. **[primary]** https://docs.rs/fs4/latest/fs4/ . Which Unix call it picks by default (flock vs fcntl): **[UNVERIFIED]**.
|
||||
- Windows default share mode of Rust `OpenOptions`: `FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE`; `share_mode(0)` makes exclusive. **[primary]** https://doc.rust-lang.org/std/os/windows/fs/trait.OpenOptionsExt.html
|
||||
- `std::fs::rename`: Unix `rename(2)`; Windows 10 1607+ `MoveFileExW(MOVEFILE_REPLACE_EXISTING)` or `SetFileInformationByHandle(FileRenameInfoEx)` (POSIX semantics); earlier, MoveFileExW only. "may change in future". **[primary]** https://doc.rust-lang.org/std/fs/fn.rename.html . (CultCache Rust bypasses std rename on Windows and calls MoveFileExW itself, per 0.)
|
||||
|
||||
### 1.3 Node
|
||||
|
||||
- No built-in advisory file lock in `node:fs`; **[UNVERIFIED]** by a direct docs read this pass, but nothing in the packages read contradicts it. Options seen:
|
||||
- `proper-lockfile`: "mkdir strategy" - creates `<target>.lock` as a **directory**; works across local and network FS; stale detection by lock dir **mtime** (default `stale` 10 s, min 5 s; mtime refreshed every `update` = stale/2, min 1 s); `onCompromised` callback when refresh fails or is late; avoids `O_EXCL` because "O_EXCL is broken on NFS" (their README); contrasts with `lockfile` package which uses ctime for staleness, unsuitable for long-running holders. **[primary]** https://raw.githubusercontent.com/moxystudio/node-proper-lockfile/master/README.md
|
||||
- `lockfile` (npm), `fs-ext` (native `flock`/`fcntl` bindings): not fetched. **[UNVERIFIED]**
|
||||
- Libuv rename on Windows uses `MoveFileExW(MOVEFILE_REPLACE_EXISTING)`; reports say it fails with EPERM while any handle holds the destination open, and refuses a READONLY destination; some runtimes (Bun PR) fall back to POSIX-semantic replace. **[secondary]** search snippets: https://github.com/oven-sh/bun/pull/43997 , https://github.com/joyent/libuv/issues/283 . Not read from libuv source: **[UNVERIFIED]**.
|
||||
- `npm/write-file-atomic`: temp name = `filename + "." + murmurhex(__filename, process.pid, ++invocations)` (plus worker thread id); same-process writes to one file queued and serialised; fsync on by default; no cross-process lock mentioned. **[primary]** https://raw.githubusercontent.com/npm/write-file-atomic/main/README.md
|
||||
|
||||
### 1.4 Python
|
||||
|
||||
- `fcntl.flock()` wraps `flock(2)`; docs: "On some systems, this function is emulated using fcntl()". `fcntl.lockf()` is "essentially a wrapper around the fcntl() locking calls". Unix only. "On at least some systems, LOCK_EX can only be used if the file descriptor refers to a file opened for writing." The page does not state whether flock and lockf interact. **[primary]** https://docs.python.org/3/library/fcntl.html
|
||||
- `msvcrt.locking(fd, mode, nbytes)`: locks `nbytes` from the current file position (may extend past EOF); `LK_LOCK`/`LK_RLCK` retry once per second, 10 attempts, then `OSError`; `LK_NBLCK` fails immediately; regions cannot overlap; adjacent regions not merged. Underlying Win32 call not stated in docs. **[primary]** https://docs.python.org/3/library/msvcrt.html . (The CRT `_locking` is documented elsewhere as `LockFile`-based; **[UNVERIFIED]** here.)
|
||||
- `filelock` (tox-dev): `FileLock` alias = `UnixFileLock` (`fcntl.flock`, described as kernel-enforced and released on crash) on Unix; `WindowsFileLock` described as `LockFileEx` byte-range locking on Windows (older versions used `msvcrt.locking`; version not checked, **[UNVERIFIED]**); `SoftFileLock` is a "cooperative file-existence marker", with same-host PID inspection and reclaim from dead processes; docs recommend verifying shared-filesystem semantics before deploying soft locks; no statement on cross-type exclusion. **[primary]** https://py-filelock.readthedocs.io/en/latest/index.html
|
||||
- `portalocker`: README fetch 404; its primitives are **[UNVERIFIED]** (not read).
|
||||
- `os.replace` on Windows semantics (MoveFileEx REPLACE_EXISTING): **[UNVERIFIED]**, not fetched.
|
||||
|
||||
### 1.5 Interoperability matrix (flock / fcntl / LockFileEx / share modes)
|
||||
|
||||
| Question | Finding | Source |
|
||||
|---|---|---|
|
||||
| Linux, local FS: does `flock` exclude `fcntl` (POSIX byte-range) locks? | No. man flock(2): on Linux "there is no interaction between the types of lock placed by flock() and fcntl(2)" (local filesystems). | **[primary]** https://man7.org/linux/man-pages/man2/flock.2.html |
|
||||
| Linux over NFS (since 2.6.12) | flock is emulated as whole-file fcntl byte-range locks, so flock and fcntl **do** interact there. | same |
|
||||
| Linux over CIFS (since 5.5) | flock emulated with SMB byte-range locks; flock and fcntl interact; and the lock becomes **mandatory**: I/O from other descriptors on a locked file fails with EACCES. | same |
|
||||
| Duplicate fds / fork | A lock belongs to the open file description; shared by dup/fork; persists until `LOCK_UN` or **all** duplicates close. Independent `open()`s in the same process conflict with each other under flock. | same |
|
||||
| Does a Rust `flock` (std or fs2) exclude a .NET-on-Unix `FileShare.None` open? | Both are `flock(LOCK_EX)` on the same inode; by the sources above they should conflict (.NET's non-blocking attempt gets EWOULDBLOCK -> IOException -> CultCache C# retries). **Not tested.** | **[inferred]**; **[UNVERIFIED]** empirically |
|
||||
| Same, but .NET `FileShare.ReadWrite` opener (shared flock) vs Rust `lock_exclusive` | Conflicts (LOCK_SH vs LOCK_EX), so a reader opening the lock file with any FileShare would block/fail against a Rust holder. CultCache does not open the lock file for reading. | **[inferred]** |
|
||||
| Windows: does a share-mode-0 open (.NET `FileShare.None`) exclude a Rust `LockFileEx` locker? | Order A: .NET holds the file with share mode 0. Rust's `OpenOptions::open` (share mode default RWD) then fails at `CreateFile` with ERROR_SHARING_VIOLATION, before it can lock. In `open_lock_file` that is a `with_context` error, **not a wait/retry** (looked at the source). Order B: Rust holds a handle (RWD) and `LockFileEx`; .NET `CreateFile` with share mode 0 conflicts with the existing open handle's access -> ERROR_SHARING_VIOLATION -> `IOException` -> C# retries up to 30 s. So mutual exclusion holds in both orders, but in order A Rust errors instead of waiting. | **[inferred]** from MS CreateFile share-mode table + Rust OpenOptionsExt default; **[UNVERIFIED]** empirically |
|
||||
| Windows: is `LockFileEx` mandatory? | Exclusive region lock "denies all other processes both read and write access to the specified region"; shared lock denies writes; locks are not honoured through mapped views. If a process dies or closes the handle the OS releases the locks, but "the time it takes ... depends upon available system resources" (MS recommends explicit unlock). Handle needs GENERIC_READ or GENERIC_WRITE. | **[primary]** https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-lockfileex |
|
||||
| Windows: second handle in same process | "If the locking process opens the file a second time, it cannot access the specified region through this second handle until it unlocks the region." | same |
|
||||
| Rust-on-Windows `LockFileEx` vs Python `msvcrt.locking` (same region?) | `LockFileEx` regions conflict if they overlap; fs2 locks which byte range (offset 0, len u32::MAX..?) : **[UNVERIFIED]**; msvcrt.locking locks `nbytes` from the current position (so depends on `lseek`); whether CRT `_locking` uses LockFile/LockFileEx and which range would need to match: **[UNVERIFIED]**. |
|
||||
| Python Unix `flock` vs Rust/.NET flock | Same kernel primitive on Linux/macOS (Python's flock "may be emulated using fcntl on some systems", so platform-dependent). Python `lockf` is fcntl: independent from flock on local Linux FS. | **[primary]** python docs + man page |
|
||||
| macOS flock vs fcntl | **[UNVERIFIED]** (not fetched). |
|
||||
| POSIX fcntl lock semantics | Per-process: `close()` of **any** fd for the file by the process drops all of that process's fcntl locks (SQLite doc 2.2 below). flock locks are per open-file-description and do not have that hazard. | **[primary]** SQLite howtocorrupt; flock(2) |
|
||||
| Python `fcntl.flock` on Windows | Module is Unix only (docs). | **[primary]** |
|
||||
|
||||
---
|
||||
|
||||
## 2. Lockfile protocols in established software
|
||||
|
||||
### git
|
||||
- Lockfile API: lock for `foo` is `foo.lock`, created with `O_CREAT|O_EXCL`; writer writes new content into it; `commit_lock_file()` renames it over `foo`; `rollback_lock_file()` removes it; writers exclude each other; readers never block and see either old or new content (relies on atomic rename); cleanup of outstanding lockfiles is registered with `atexit` and signal handlers. **[primary]** https://git-scm.com/docs/api-lockfile
|
||||
- `lockfile.c`: retry with quadratic backoff for at least `timeout_ms`; PID file registered as a tempfile for signal/atexit cleanup; failure message says another git process may be running "or the lock file may be stale" and tells the user to remove it manually. **[primary]** https://raw.githubusercontent.com/git/git/master/lockfile.c
|
||||
- Consequences recorded in the docs: a hard kill (SIGKILL, power loss) leaves a `.lock` file and later writers fail until it is removed; git does not time-based-reclaim index.lock **[inferred from message text, not stated; UNVERIFIED]**. Note the git design makes the lock file **the temp file** (lock name = staging name); CultCache's current design has a separate sidecar lock plus uniquely named temp.
|
||||
|
||||
### SQLite (see also section 4)
|
||||
- Unix default VFS: POSIX advisory locks via `fcntl()`; Windows VFS: `LockFile`/`LockFileEx`/`UnlockFile`. Five states UNLOCKED/SHARED/RESERVED/PENDING/EXCLUSIVE. **[primary]** https://www.sqlite.org/lockingv3.html (byte-range layout not stated on that page).
|
||||
- Built-in unix VFS variants: `unix` (POSIX advisory), `unix-dotfile` (dot-file locking), `unix-excl` (holds exclusive lock, WAL index in heap), `unix-none` (no locking), `unix-namedsem` (VxWorks). "Except for 'unix' and 'unix-excl', the various Unix VFSes all use incompatible locking implementations"; processes using different VFSes on one DB "may not see each others locks ... resulting in database corruption". **[primary]** https://www.sqlite.org/vfs.html . (`unix-flock` / `unix-afp` / `unix-nfs` appear in SQLite's source as separate io-method variants; not listed on that page: **[UNVERIFIED]**.)
|
||||
|
||||
### LMDB
|
||||
- Uses a separate `lock.mdb` file for the reader table and writer mutex. Header warnings: stale reader slots from aborted programs make the DB grow quickly (`mdb_reader_check`); stale writer lock clears automatically on Windows, BSD with SysV semaphores, and Linux with robust POSIX mutexes, otherwise all DB users must be closed; "Do not have open an LMDB database twice in the same process at the same time. Not even from a plain open() call - close()ing it breaks flock() advisory locking."; "Do not use LMDB databases on remote filesystems, even between processes on the same host. This breaks flock() on some OSes"; `MDB_NOLOCK` disables locking entirely. **[primary]** https://raw.githubusercontent.com/LMDB/lmdb/mdb.master/libraries/liblmdb/lmdb.h
|
||||
- Note: that warning is about `flock` and `close()`, which contradicts the usual statement that only fcntl locks have the close() hazard; the source of the discrepancy (older Linux/BSD semantics, or the emulated flock on some OS) is **[UNVERIFIED]**.
|
||||
|
||||
### Cargo / npm / pip / Gradle
|
||||
- Cargo: package-cache and build-dir lock using an OS file lock, prints "Blocking waiting for file lock"; source fetch (`src/cargo/util/flock.rs`) 404; details (flock/fs4/std, handling of filesystems without locking) **[UNVERIFIED]**.
|
||||
- Gradle: `DefaultFileLockManager` holds cross-process locks on cache/daemon-registry files; reports of builds hanging on locks left by crashed or killed daemons. **[secondary]** web search snippets only (https://discuss.gradle.org/t/gradle-daemon-keeps-locking-intermediate-files-preventing-builds/38004 , https://www.javathinking.com/blog/gradle-build-is-hanging-without-failure-defaultfilelockmanager-acquiring-and-releasing-lock-on-daemon-addresses-registry/ ); Gradle's own docs on lock protocol not read. **[UNVERIFIED]**
|
||||
- npm: `write-file-atomic` has no cross-process lock (above); npm's cache (cacache) locking: **[UNVERIFIED]**, not fetched.
|
||||
- pip: **[UNVERIFIED]**, not fetched.
|
||||
|
||||
### Windows rename retry (Postgres)
|
||||
- `pgrename()` on Windows calls `MoveFileEx(from, to, MOVEFILE_REPLACE_EXISTING)` and retries on ERROR_ACCESS_DENIED, ERROR_SHARING_VIOLATION, ERROR_LOCK_VIOLATION: up to 100 retries, 0.1 s apart (~10 s). Comment: other applications may have the file open without sharing flags; LOCK_VIOLATION seen from some anti-virus software; bounded because the caller may hold locks affecting other backends. **[primary]** https://raw.githubusercontent.com/postgres/postgres/master/src/port/dirmod.c . CultCache Rust uses the same error set with 25 x 20 ms (0.5 s); TS retries EPERM/EBUSY/EACCES 10 times with doubling from 10 ms (about 10 s worst case) **[src]**.
|
||||
|
||||
---
|
||||
|
||||
## 3. Temp-file naming and rename atomicity
|
||||
|
||||
- Unique temp names per writer: C# GUID, Rust uuid v4, TS pid+time+random **[src]**; npm write-file-atomic pid + counter hash **[primary]**; Python CultCache fixed `.tmp` **[src]**. Rust additionally has a startup cleanup that deletes only temps matching `<store>.<uuid>.tmp` (tests at `lib.rs` ~3420, 4667-4689 distinguish `not-a-uuid.tmp`, bare `.tmp`, neighbour stores) **[src]**. Note the naming differs between runtimes: C# `.{name}.{guid:N}.tmp` (leading dot, no dashes) vs Rust `{name}.{uuid-with-dashes}.tmp` vs TS `{name}.tmp-...`; whether the Rust stale-temp sweeper recognises C#/TS temps: it matches the Rust format only (per the test names) **[src, partial reading]**.
|
||||
- Fixed temp name consequence (inferred, not tested): two processes writing `store.cc.tmp` concurrently share one file: interleaved `write_bytes` (truncate-and-write) can yield a mixed or truncated file that one process then renames into place, and the other process's `replace` can fail with source-not-found. **[inferred]**
|
||||
- POSIX `rename()`: if `new` exists it "shall be removed and old renamed to new"; the rationale requires the action to be atomic; a directory entry named `new` stays visible to other threads throughout and refers to either old or new file; on failure other than I/O errors `new` is unaffected; spec does not define crash durability. **[primary]** https://pubs.opengroup.org/onlinepubs/9799919799/functions/rename.html
|
||||
- Directory fsync: the usual pattern is write temp, fsync temp, rename, then fsync the parent directory so the rename survives power loss; many projects have filed bugs for omitting the directory fsync. **[secondary]** search snippets (e.g. https://github.com/npm/write-file-atomic/issues/64 titled "Rename atomicity is not enough"; https://0xkiire.com/crash-consistency-fsync-rename/). Linux ext4 `auto_da_alloc` replace-via-rename heuristic: **[UNVERIFIED]**, not fetched. Whether CultCache Rust/C# fsync the parent directory on Unix: **[UNVERIFIED]** (not seen in the excerpts read; Rust does `sync_all` on the temp, C# `Flush(true)` + `WriteThrough`; TS and Python do neither).
|
||||
- Windows `MoveFileExW`:
|
||||
- `MOVEFILE_REPLACE_EXISTING` replaces the destination if ACLs allow; errors if destination is an existing directory; `MOVEFILE_WRITE_THROUGH` waits for the move to be flushed (documented as guaranteeing flush of a copy+delete move). Same-volume rename is a metadata operation. The doc page does not use the word "atomic" and does not describe behavior when the destination is open by another handle. **[primary]** https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-movefileexw
|
||||
- Open-handle failure: reported from libuv/Bun and Postgres as ERROR_ACCESS_DENIED / SHARING_VIOLATION / LOCK_VIOLATION when another process has the destination open without FILE_SHARE_DELETE, or an anti-virus scan holds it. **[primary]** Postgres comment; **[secondary]** libuv/Bun.
|
||||
- Rust's std rename (1.0+ Windows 10 1607) may use `FileRenameInfoEx` with POSIX semantics, which can replace an open destination; CultCache Rust calls `MoveFileExW` directly instead **[src; primary for std]**.
|
||||
- Windows `ReplaceFileW` (used by .NET `File.Replace`): replaced file opened with GENERIC_READ|DELETE|SYNCHRONIZE and share mode `READ|WRITE|DELETE`; replacement file opened with **no sharing mode specified**; preserves creation time, short name, object id, DACLs, encryption, compression, named streams; resulting file has the replacement's file ID; all files must be on the same volume; documented failure states leave the system in partially-moved states: ERROR_UNABLE_TO_REMOVE_REPLACED (1175; names unchanged), ERROR_UNABLE_TO_MOVE_REPLACEMENT (1176; with no backup, the replaced file "no longer exists" and the replacement exists under its original name), ERROR_UNABLE_TO_MOVE_REPLACEMENT_2 (1177). `REPLACEFILE_WRITE_THROUGH` "not supported". The page makes no statement that ReplaceFile is atomic; it describes it as combining steps. **[primary]** https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-replacefilew
|
||||
- So on Windows, C# (`File.Replace`) and Rust/TS/Python (MoveFileEx or equivalent) use different primitives with different failure windows. **[inferred from the two pages]**
|
||||
- .NET `File.Move` with overwrite on Windows/Unix: **[UNVERIFIED]** (CultCache C# uses `File.Move(temp, path)` only when the target does not exist; there is a window in which another writer creates the target between the `File.Exists` check and the move; the lock covers it when taken **[src, inferred]**).
|
||||
|
||||
---
|
||||
|
||||
## 4. Known failures and warnings
|
||||
|
||||
SQLite "How To Corrupt An SQLite Database File" (https://www.sqlite.org/howtocorrupt.html) **[primary]**:
|
||||
- 2.1 Filesystems with broken or missing lock implementations (network filesystems, NFS) can corrupt when multiple processes access.
|
||||
- 2.2 POSIX advisory locks are cancelled by `close()`: `close()` on any descriptor for the file by any thread in the process releases the process's locks on that file; example: thread B opens, reads and closes the DB file for a backup and thread A's locks vanish silently. SQLite works around it with a mutex-protected global list of open files, which fails if two copies of SQLite are linked into one app (2.3; a commercial product shipped this bug with infrequent corruption on Linux/Mac). WAL multi-process defenses added in 3.51.0 (2025-11-04).
|
||||
- 2.4 Two processes using different locking protocols (e.g. POSIX advisory vs dot-file) cannot see each other's locks; all connections must use the same protocol.
|
||||
- 2.5 Unlinking or renaming the DB file while in use: processes end up with different physical files sharing one journal; SQLite warns (since 3.7.17) when the file is unlinked while open.
|
||||
- 2.6 Multiple links (hard/symbolic links): same hazard; resolved by canonicalising symlinks since 3.10.0.
|
||||
- 2.7 Carrying a connection across `fork()`: all locking mechanisms fail with unpredictable results.
|
||||
- 1.3/1.4 Hot journal deleted, moved or mispaired with database.
|
||||
- The SQLite VFS page: incompatible unix VFS locking => corruption (section 2 above).
|
||||
|
||||
Other recorded failure modes:
|
||||
- Windows `LockFileEx` locks are released by the OS on process death but with a lag (MS doc). **[primary]**
|
||||
- CIFS flock becomes mandatory (man flock(2)). **[primary]**
|
||||
- Lock file left behind: git (cleanup via atexit/signal; a hard kill leaves `.lock`, message tells operator to remove) **[primary]**; Gradle hangs after killed daemons **[secondary]**; `proper-lockfile` and `filelock.SoftFileLock` provide mtime / PID-based stale reclaim as a mitigation **[primary]**.
|
||||
- Lock protocols that are compatible only when everyone uses the same one: SQLite (above); `filelock` docs do not state cross-type exclusion between `UnixFileLock`/`SoftFileLock`. **[primary]**
|
||||
- Lost-update by missing cross-process lock around read-modify-write: `write-file-atomic` documents only same-process serialisation; no source read this pass reports a concrete lost-update bug in it. A search-based report of corrupted/missing "settings.json" on Windows from a failed atomic write exists as an unvetted issue (https://github.com/BarganConstantin/ccdeck/issues/772, **[secondary]**, read-only destination). Reports specific to cross-language writers of one file, other than SQLite's different-VFS warning: not found this pass. **[UNVERIFIED]**
|
||||
- Lock file deleted by one participant while others hold or wait on it (different inode afterward): general hazard of delete-on-unlock lock files, not sourced this pass beyond SQLite 2.5 (unlink of a live file); **[UNVERIFIED]** as a named issue for flock sidecars.
|
||||
|
||||
---
|
||||
|
||||
## 5. Open items not resolved by reading (candidates for an empirical check; nothing done)
|
||||
|
||||
1. Do the C# `FileShare.None` lock and Rust `fs2::lock_exclusive` actually exclude each other on Windows (both open orders) and on Linux? Only inferred above.
|
||||
2. Does fs2 on Windows lock the same byte range as std 1.89 `File::lock` and as Python `msvcrt.locking`/`filelock`? Unread.
|
||||
3. macOS behavior of flock vs fcntl and of .NET FileShare there. Unread.
|
||||
4. .NET release that introduced Unix FileShare-via-flock. Unread.
|
||||
5. Whether any runtime fsyncs the parent directory after rename on Unix. Unread.
|
||||
6. Cargo, npm, pip, Gradle lock protocol primary sources. Unread.
|
||||
7. `portalocker`, `fs-ext`, `lockfile`, `proper-lockfile` behavior under Windows share modes. Unread.
|
||||
305
docs/research/culling-efficiency-oracle-prior-art.md
Normal file
305
docs/research/culling-efficiency-oracle-prior-art.md
Normal file
|
|
@ -0,0 +1,305 @@
|
|||
# Culling Efficiency Against an Oracle: Prior Art Survey
|
||||
|
||||
This is the facts file for Eureka question `cultmath-tapes:question:wells-ceiling-oracle`,
|
||||
which interprets ruling `cultmath-tapes:ruling:operator-wells-contract-vs-ceiling`. That
|
||||
ruling holds scenario (c) to "at least 90% of the probe-free ceiling (the cost of the
|
||||
dense cells alone)". The question asks what "ceiling" means:
|
||||
|
||||
- (a) the pre-pass's own mask, under which a pre-pass that skips nothing scores 0.98;
|
||||
- (b) an oracle mask, the cells where at least one ray samples nonzero density.
|
||||
|
||||
Under (b), Imagination measured 0.38 at warp 0 and 0.19 at warp D.
|
||||
|
||||
This survey covers how published work measures culling or skipping efficiency against
|
||||
ground truth, and what efficiency figures conservative bounds reach. Eyes pass,
|
||||
2026-10-03. It gives facts and evidence pointers only, with no recommendation.
|
||||
|
||||
Verification marks:
|
||||
|
||||
- **[fetched]** The claim was read in the cited source's full text during this pass.
|
||||
PDFs were converted with `pdftotext -layout`.
|
||||
- **[search]** The claim came from a search-result summary, not a full read.
|
||||
- **[not found]** The source was read, and the named kind of measurement is absent from it.
|
||||
|
||||
Reference kinds used below:
|
||||
|
||||
- **oracle**: an exact or ground-truth answer computed independently of the method,
|
||||
such as the exact visible set or the set of truly non-empty cells.
|
||||
- **self**: the method's own result, or a baseline that does no culling.
|
||||
- **peer**: another approximate method.
|
||||
|
||||
## 1. Visibility culling: conservative versus exact visible set
|
||||
|
||||
### 1.1 Survey vocabulary
|
||||
|
||||
- **[fetched]** Cohen-Or, Chrysanthou, Silva, Durand, *A Survey of Visibility for
|
||||
Walkthrough Applications* (IEEE TVCG 2003). Section 2 lists "Tightness of
|
||||
approximation" as a review criterion. It notes that few papers report the ratio
|
||||
between the size of the potentially visible set and the size of the visible set,
|
||||
and asks later work to report it. Most surveyed techniques are conservative, which
|
||||
means they overestimate the visible set.
|
||||
https://www.cs.tau.ac.il/~dcor/online_papers/papers/visibility-survey-ieee.pdf
|
||||
- **[fetched]** Bittner, *Hierarchical Techniques for Visibility Computations* (PhD
|
||||
thesis, CTU Prague, 2002), chapter 2, equations 2.1 to 2.4. It defines a quality
|
||||
measure against the exact PVS `S_E`:
|
||||
- relative overestimation `Q_o = |S_A \ S_E| / |S_E|`;
|
||||
- relative underestimation `Q_u = |S_E \ S_A| / |S_E|`;
|
||||
- the expected quality, which is the expectation of these over inputs.
|
||||
|
||||
The same text appears in Bittner and Wonka, *Visibility in Computer Graphics*
|
||||
(section 4.3).
|
||||
https://dcgi.fel.cvut.cz/home/bittner/publications/diss_noimages.pdf
|
||||
http://www.casa.ucl.ac.uk/mike-michigan-april1/mike's%20stuff/attach/bittner_wonka.pdf
|
||||
- **[fetched]** Nirenstein, Blake, Gain, *Exact From-Region Visibility Culling* (EGWR
|
||||
2002), introduction and Table 1. The paper classifies algorithms as exact,
|
||||
conservative, aggressive or approximate. Conservative methods "incur a false
|
||||
visibility error". The paper states:
|
||||
- exact visibility "provides a benchmark for comparing other approaches";
|
||||
- the percentage of polygons culled is "a very crude and imperfect metric", because
|
||||
it ignores the type, distribution and magnitude of visibility error.
|
||||
|
||||
Reported results (Table 2) are culling fractions of the whole scene: 99.45% for the
|
||||
town and 99.12% for the forest. No conservative method is measured against the
|
||||
exact set in this paper **[not found]**. A search summary attributed a 95.5% figure
|
||||
for extended projection to this paper, but that figure is not in the full text.
|
||||
https://people.cs.uct.ac.za/~jgain/wp-content/papercite-data/pdf/nirenstein2002.pdf
|
||||
|
||||
### 1.2 Measured conservative-versus-exact ratios
|
||||
|
||||
- **[fetched]** Bittner, Wonka, Wimmer, *Fast Exact From-Region Visibility in Urban
|
||||
Scenes* (EGSR 2005), section 6. The exact 2.5D algorithm is used as the oracle, and
|
||||
the paper simulates conservative methods against it:
|
||||
- **Section 6.2, one penumbra wedge per occluder.** The conservative PVS was more
|
||||
than 47% larger than the exact PVS for 2 m view cells and more than 76% larger
|
||||
for 4 m view cells. As exact/conservative ratios these are ≤ 0.68 and ≤ 0.57.
|
||||
- **Section 6.3, object-space discretization** (Wonka et al.'s method, a 1400×1400
|
||||
grid, Vienna). The PVS overestimate averaged 17%, a ratio of about 0.85.
|
||||
- **Section 6.3, Table 4, line-space discretization** (Leyvand et al.). PVS sizes by
|
||||
grid resolution, with the exact PVS last:
|
||||
|
||||
| Scene | 512 | 1024 | 2048 | 16384 | exact |
|
||||
|---------|--------|--------|--------|-------|-------|
|
||||
| Vienna | 633 | 535 | 489 | 455 | 235 |
|
||||
| Atlanta | 50,744 | 25,751 | 10,082 | 2,656 | 1,152 |
|
||||
|
||||
The ratios exact/conservative below are computed from that table, not quoted from
|
||||
the paper:
|
||||
- Vienna: 0.37, 0.44, 0.48, 0.52;
|
||||
- Atlanta: 0.023, 0.045, 0.11, 0.43.
|
||||
|
||||
The paper says the overestimation comes from conservative shrinking and from gaps
|
||||
"between formerly connected occluders".
|
||||
|
||||
https://peterwonka.net/Publications/pdfs/2005.EGSR.Bittner.FastExactFromRegionVisibility.pdf
|
||||
|
||||
### 1.3 Run-time occlusion culling against an ideal renderer
|
||||
|
||||
- **[fetched]** Mattausch, Bittner, Wimmer, *CHC++: Coherent Hierarchical Culling
|
||||
Revisited* (Eurographics 2008), section 7 (Figure 7) and the conclusion. The
|
||||
reference algorithm "OPT" renders only the visible nodes of the hierarchy and
|
||||
issues no queries. It was implemented by recording visibility with an exact
|
||||
stop-and-wait pass, so it is an oracle at node granularity that is independent of
|
||||
the method under test. CHC++ is reported to be "for most cases within a few percent
|
||||
of the 'ideal' method".
|
||||
|
||||
Caveat: occlusion queries are exact per-node tests, not conservative range bounds.
|
||||
The gap to OPT measures query overhead and latency, not bound looseness.
|
||||
|
||||
The paper also separates out the "optimal" algorithm defined by Guthe et al.
|
||||
(NOHC-OPT), and shows CHC++ "clearly below" that optimum. That earlier optimum was a
|
||||
cost-model optimum, not an oracle.
|
||||
https://dcgi.fel.cvut.cz/home/bittner/publications/chc++.pdf
|
||||
- **[fetched]** Zhang et al., *Visibility Culling using Hierarchical Occlusion Maps*
|
||||
(SIGGRAPH 1997). It reports "% culling" of the total model, and frame time
|
||||
normalized to rendering without HOM. Both are **self** references. No comparison
|
||||
with the exact visible set **[not found]**.
|
||||
https://www.cs.princeton.edu/courses/archive/spr01/cs598b/papers/zhang97.pdf
|
||||
- **[search]** Wonka et al., *Guided Visibility Sampling* (SIGGRAPH 2006). This is
|
||||
an aggressive, sampling-based PVS method. Its Table 2 reports error as false pixels
|
||||
on a 1000×1000 screen, together with PVS size. Section 4.5 compares it to Bittner's
|
||||
exact algorithm on one scene, because exact solvers do not run on the larger test
|
||||
scenes. The text was extracted in this pass, but not read in full.
|
||||
https://peterwonka.net/Publications/pdfs/2006.SG.Wonka.GuidedVisibilitySampling.final.pdf
|
||||
|
||||
## 2. Empty-space skipping in volume rendering
|
||||
|
||||
- **[fetched]** Li, Mueller, Kaufman, *Empty Space Skipping and Occlusion Clipping for
|
||||
Texture-based Volume Rendering* (IEEE Vis 2003):
|
||||
- **Section 5, Table 1.** Empty-space skipping is measured as a frame-rate speedup
|
||||
over no skipping, 2.8× on average. This is a **self** reference.
|
||||
- **Section 5, Table 2.** It reports the percentage of non-empty voxels skipped
|
||||
through occlusion, 48% to 64% with a 56.2% average. The denominator is all
|
||||
non-empty voxels, not the truly occluded voxels. The authors write that "there
|
||||
are still many occluded voxels that have not been skipped" and call the number
|
||||
"smaller than we have expected". The truly occluded set is not computed
|
||||
**[not found]**.
|
||||
- **Section 5.** Overhead is reported separately. The opacity map and clipping cost
|
||||
about 10% of the empty-space-skipping render time, measured with a mode that pays
|
||||
the overhead but skips nothing ("ESS+M").
|
||||
|
||||
https://www3.cs.stonybrook.edu/~mueller/papers/OcclusionClipping.pdf
|
||||
- **[fetched]** Zellmann, *Comparing Hierarchical Data Structures for Sparse Volume
|
||||
Rendering with Empty Space Skipping* (arXiv 1912.09596, 2019). It reports frame
|
||||
rates and build times, and compares only against naive ray marching and simple
|
||||
macrocell grids, as the paper itself states. No step count or sample count against
|
||||
an ideal traversal **[not found]**.
|
||||
https://arxiv.org/abs/1912.09596
|
||||
- **[search]** Hadwiger et al., *SparseLeap* (IEEE TVCG 24(1), 2018). It builds
|
||||
per-pixel lists of ray segments by rasterizing occupancy geometry. The full text
|
||||
was not retrieved (the repository returned HTML), so it is unknown whether it
|
||||
reports skip efficiency against the true empty space.
|
||||
https://vccvisualization.org/research/sparseleap/
|
||||
- **[search]** Deakin and Knackstedt, *Efficient ray casting of volumetric images using
|
||||
distance maps for empty space skipping* (Computational Visual Media 6(1), 2020). The
|
||||
full text was not retrieved.
|
||||
|
||||
## 3. Interval and affine arithmetic for implicits, noise and SDF marching
|
||||
|
||||
- **[fetched]** Keeter, *Massively Parallel Rendering of Complex Closed-Form Implicit
|
||||
Surfaces* (SIGGRAPH 2020):
|
||||
- **Section 3, Interval arithmetic.** Ambiguous regions "either contain the shape's
|
||||
boundary or are a false positive (due to interval arithmetic's conservative
|
||||
behavior)". The false-positive share is not measured **[not found]**.
|
||||
- **Section 2.1, Figure 5.** Reported efficiency is against **self** and peer
|
||||
baselines: a brute-force per-pixel interpreter (about 58 ms/MP) and a compiled
|
||||
kernel (about 3 ms/MP).
|
||||
- **Section 3.2, Figure 6.** Tape length is reduced 17× in 64² tiles and 216× in 8²
|
||||
subtiles, from 6056 clauses to means of 356 and 28.
|
||||
- **Section 5, Figures 9 and 10.** Heatmaps of work per pixel show extra work at
|
||||
model edges, where interval evaluation "can't skip entire regions". The text says
|
||||
many smooth blends lead "to less useful interval evaluation results".
|
||||
- **Section 6.** It names reduced affine arithmetic as a way "to more tightly bound
|
||||
intervals".
|
||||
|
||||
https://www.mattkeeter.com/research/mpr/keeter_mpr20.pdf
|
||||
- **[fetched]** Keeter, *Gradients are the new intervals* (blog, 2025-05-14). It
|
||||
compares interval evaluation with gradient-based pseudo-intervals by tape length
|
||||
(120.2 against 121.5 clauses) and by render time. These are peer references. There
|
||||
are no tile-classification counts and no ground truth **[not found]**.
|
||||
https://www.mattkeeter.com/blog/2025-05-14-gradients/
|
||||
- **[fetched]** Heidrich, Slusallek, Seidel, *Sampling Procedural Shaders Using Affine
|
||||
Arithmetic* (ACM TOG 17(3), 1998):
|
||||
- **What "error" measures.** Error is the width of the computed range per pixel. It
|
||||
is not compared with the true range from dense sampling **[not found]**. The
|
||||
tightness against the true variation is argued qualitatively, from shader cross
|
||||
sections.
|
||||
- **Section 3.2.** Noise over an affine form that spans several lattice cells falls
|
||||
back to interval arithmetic, and a span of more than two cells returns the full
|
||||
noise range [0, 1]. For turbulence (blue marble), 81% of pixels lie within 5%
|
||||
error and 59% within 1%. The eroded shader, with high-frequency noise, gets 77%
|
||||
and 53%.
|
||||
- **Section 4.** Against AA, interval arithmetic gave errors "up to 50 percent where
|
||||
affine arithmetic produces errors below 1/256" (wood shader, Figures 6 and 7).
|
||||
|
||||
https://vccimaging.org/Publications/Heidrich1998SPS/Heidrich1998SPS.pdf
|
||||
- **[fetched]** Gamito and Maddock, *Ray casting implicit fractal surfaces with reduced
|
||||
affine arithmetic* (The Visual Computer 23(3), 2007). Section 5, Tables 1 to 3, use
|
||||
a sphere hypertextured with three octaves of noise. The accuracy proxy is the
|
||||
average number of interval evaluations per ray, a **peer** comparison with no oracle
|
||||
count. The rows below are reconstructed from a mangled text layout, and the
|
||||
reconstruction agrees with the paper's prose.
|
||||
|
||||
| Noise | IA evals/ray | IA time | Standard AA evals/ray | Reduced AA evals/ray | Reduced AA + interval optimisation, evals/ray | Its time |
|
||||
|------------------------|--------------|-----------|-----------------------|----------------------|-----------------------------------------------|-----------|
|
||||
| Perlin gradient | 78.40 | 8m27.5s | 34.60 | 34.60 | 20.81 | 3m43.2s |
|
||||
| Lewis sparse convolution | 48.44 | 26m31.0s | 23.25 | 23.25 | 13.46 | 6m29.3s |
|
||||
| Worley cellular | 45.70 | 25m54.7s | 32.56 | 43.78 | 21.29 | 14m25.9s |
|
||||
|
||||
The text cites "the excessive conservativeness of IA estimates", and says IA
|
||||
compensates by being fast.
|
||||
https://eprints.whiterose.ac.uk/id/eprint/3762/1/gamito_newraycastvisual.pdf
|
||||
- **[fetched]** Knoll, Hijazi, Kensler, Schott, Hansen, Hagen, *Fast Ray Tracing of
|
||||
Arbitrary Implicit Surfaces with Interval and Affine Arithmetic* (CGF 28(1), 2009).
|
||||
Section 6.1.1 and Tables 1 and 2 report frames per second for IA against reduced
|
||||
AA:
|
||||
- RAA is "generally 1.5 to 2× faster", and "3 to 4 times faster" for functions
|
||||
"with high bound overestimation";
|
||||
- IA is faster for superquadrics.
|
||||
|
||||
These are **peer** references, with no oracle count of wasted subdivisions
|
||||
**[not found]**.
|
||||
https://sci.utah.edu/~knolla/cgrtia.pdf
|
||||
- **[fetched]** Sharp and Jacobson, *Spelunking the Deep: Guaranteed Queries on General
|
||||
Neural Implicit Surfaces via Range Analysis* (SIGGRAPH 2022), section 3.4 and Table 1.
|
||||
Tightness is measured as "the typical size of a region which can be bounded away
|
||||
from the zero":
|
||||
|
||||
| Method | 1D length | 3D volume | Ray-cast time (relative to the fastest) |
|
||||
|---------------|-----------|-----------------|-----------------------------------------|
|
||||
| interval | 0.011 | < 0.001 × 10⁻³ | 34.3× |
|
||||
| affine (full) | 0.821 | 3.499 × 10⁻³ | 8.4× |
|
||||
| affine (fixed)| 0.306 | 0.267 × 10⁻³ | 1.0× |
|
||||
|
||||
The prose says interval arithmetic "yields extremely pessimistic bounds". These are
|
||||
**peer** references, with no oracle region size **[not found]**.
|
||||
https://arxiv.org/abs/2202.02444
|
||||
- **[fetched]** Mitchell, *Robust Ray Intersection with Interval Arithmetic* (Graphics
|
||||
Interface 1990). It reports root-finding timings for its method and for peer
|
||||
root finders. No pruning-against-oracle measure **[not found]**.
|
||||
http://graphicsinterface.org/wp-content/uploads/gi1990-8.pdf
|
||||
- Duff, *Interval Arithmetic and Recursive Subdivision for Implicit Functions and
|
||||
Constructive Solid Geometry* (SIGGRAPH 1992), and Snyder, *Interval Analysis for
|
||||
Computer Graphics* (SIGGRAPH 1992), were not retrieved in this pass.
|
||||
https://doi.org/10.1145/142920.134027
|
||||
|
||||
## 4. Conservative rasterization and tile classification
|
||||
|
||||
- **[fetched]** Hasselgren, Akenine-Möller, Ohlsson, *Conservative Rasterization*
|
||||
(GPU Gems 2, chapter 42):
|
||||
- **Section 42.1.** It defines overestimated rasterization as every pixel whose cell
|
||||
intersects the polygon, and underestimated rasterization as every pixel whose
|
||||
cell lies wholly inside it.
|
||||
- **Section 42.5.** Overdraw is discussed qualitatively: it depends on triangle
|
||||
acuity and resolution. Figure 42-7 compares the two proposed algorithms only. No
|
||||
count of excess fragments against the exact overlap set **[not found]**.
|
||||
|
||||
https://developer.nvidia.com/gpugems/gpugems2/part-v-image-oriented-computing/chapter-42-conservative-rasterization
|
||||
- **[search]** Antochi, Juurlink, Vassiliadis, Liuha, *Scene management models and
|
||||
overlap tests for tile-based rendering* (DSD 2004), and the companion *Efficient
|
||||
tile-aware bounding-box overlap test*. In a search summary, the bounding-box
|
||||
triangle-to-tile test "can generate up to 30% false positives" on common workloads,
|
||||
measured against exact overlap. The full text could not be retrieved (the TU Delft
|
||||
host refused the connection, and CiteSeerX returned HTML).
|
||||
https://citeseerx.ist.psu.edu/document?doi=5c78f05f185b9513bf930588dd2a4ae334090620
|
||||
|
||||
## 5. Summary of reference kinds and reported figures
|
||||
|
||||
| Source | Reference | Figure reported |
|
||||
|--------|-----------|-----------------|
|
||||
| Bittner et al. 2005, §6.2 | oracle (exact PVS) | conservative PVS +47% / +76% (ratio ≤ 0.68 / ≤ 0.57) |
|
||||
| Bittner et al. 2005, §6.3 | oracle | object discretization +17% (≈ 0.85); line-space 0.023–0.52 by scene and resolution |
|
||||
| Bittner thesis, ch. 2 | oracle | defines `Q_o`, `Q_u` relative to `|S_E|` |
|
||||
| Cohen-Or et al. 2003 | — | notes the PVS/visible-set ratio is rarely reported |
|
||||
| Nirenstein et al. 2002 | oracle (its own exact) | percent culled; calls that metric crude |
|
||||
| CHC++ 2008 | oracle (OPT, node level) | within a few percent of OPT (exact queries, not bounds) |
|
||||
| HOM 1997 | self | % of model culled, normalized frame time |
|
||||
| Li, Mueller, Kaufman 2003 | self / all non-empty | 2.8× speedup; 56% of non-empty voxels skipped; overhead ≈ 10% reported separately |
|
||||
| Zellmann 2019 | self | fps against no skipping |
|
||||
| Keeter 2020 | self (brute force, compiled) | 17× / 216× tape reduction; false-positive share not measured |
|
||||
| Heidrich et al. 1998 | none (range width) | IA error up to 50% where AA < 1/256 |
|
||||
| Gamito, Maddock 2007 | peer | IA 2.1–3.8× more evaluations per ray than reduced AA + optimisation on noise |
|
||||
| Knoll et al. 2009 | peer | RAA 1.5–4× faster than IA |
|
||||
| Sharp, Jacobson 2022 | peer | IA provable region about 75× smaller in 1D than full AA |
|
||||
| GPU Gems 2, ch. 42 | peer | qualitative overdraw |
|
||||
| Antochi et al. 2004 [search] | oracle (exact overlap) | bounding box up to 30% false positives |
|
||||
|
||||
On the interval side (section 3), none of the sources read in this pass reports a
|
||||
pruning or culling fraction against an oracle mask, such as the truly empty cells or
|
||||
the truly non-ambiguous tiles. They report only against self or peer baselines. The
|
||||
oracle-referenced ratios found are all on the visibility side (sections 1.2 and 1.3),
|
||||
and the one from rasterization (section 4) is search-only. No published figure was
|
||||
found for interval-arithmetic culling of noise or warped-noise fields as a fraction of
|
||||
an oracle.
|
||||
|
||||
## 6. Local context (from the eureka mind, not re-measured)
|
||||
|
||||
- **Question** `cultmath-tapes:question:wells-ceiling-oracle` (admitted 2026-10-03,
|
||||
Imagination). At 3ac7250a it gives:
|
||||
- warp 0: oracle efficiency 0.38, mask ceiling 0.96, cull fraction 0.95;
|
||||
- warp D = 60: oracle efficiency 0.19, mask ceiling 0.99, cull fraction 0.84;
|
||||
- a pre-pass that skips nothing: 0.14 against the oracle.
|
||||
- **Finding** `cultmath-tapes:finding:cut-interval-ops.s2.wells-ceiling-contract-vacuous`
|
||||
(Soul, confirmed by mutation). The mask-referenced (c) check reports 0.98 with the
|
||||
wells skip disabled. Locations are in
|
||||
`packages/cultmath/tests/CultMath.Tests/NoiseBoundTests.cs`: lines 1257–1260, 1437
|
||||
and 1461.
|
||||
75
docs/research/cultcache-union-decode-tolerance-prior-art.md
Normal file
75
docs/research/cultcache-union-decode-tolerance-prior-art.md
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
# Union and record decode tolerance: prior art and CultCache's stance
|
||||
|
||||
Fork: thing2:question:contract-decode-tolerance. Follow-up: thing2:follow_up:cultcache-union-parity.
|
||||
Eyes pass, 2026-10-10, session self-2026-10-10c-eureka. Facts only; no recommendation.
|
||||
Tags: [fetched] read this session; [local] read in the repo this session; [background] prior knowledge, not refetched; [not found] the fetched page did not say.
|
||||
|
||||
## 1. Established systems
|
||||
|
||||
### Protocol Buffers
|
||||
- Unknown fields: proto3 "preserve[s] unknown fields and include[s] them during parsing and in the serialized output", matching proto2. Lost on JSON serialization and on field-by-field copy into a new message; CopyFrom/MergeFrom avoid the loss. (protobuf.dev/programming-guides/proto3/, "Unknown Fields") [fetched]. The version proto3 started preserving (3.5) [background].
|
||||
- Unknown oneof case: no distinct state. The page warns a NOT_SET result is ambiguous: the oneof may be unset, or set to a field from a newer schema [fetched]. A oneof member the reader lacks is an ordinary unknown field, so it sits in the unknown-field set and is re-emitted [background].
|
||||
- Unknown enum values: "unrecognized enum values will be preserved in the message" (raw int in open-enum languages, accessor in Java) and re-serialized [fetched].
|
||||
|
||||
### Cap'n Proto
|
||||
- Union: a separate tag says which member is set. Adding a member to a union is safe because "existing programs should already know to check the union's tag"; they "may or may not behave reasonably when the tag has a value they don't recognize". Moving an existing field into a new union can show an old reader "a garbage value or throw an exception" (capnproto.org/language.html, "Unions", "Evolving Your Protocol") [fetched].
|
||||
- which() on an unknown discriminant: [not found] in the fetched language and encoding pages. C++ generated which() returns the tag as an enum and the reader is expected to switch with a default [background].
|
||||
- Preservation: [not found] on the fetched pages; structs "can be traversed (e.g., copied) without knowing their type" (encoding.html, Structs) [fetched]. Copy preservation of unknown data is [background].
|
||||
|
||||
### Avro (schema resolution; reader schema and writer schema both required)
|
||||
- Both unions: reader takes its first branch matching the writer's selected branch; "if none match, an error is signalled". Writer union, reader non-union: the selected writer branch must match, else error (Avro spec, Schema Resolution) [fetched; also quoted from the 1.11.1 spec in docs/research/read-only-record-signal-prior-art.md:176-178].
|
||||
- Record, writer has an extra field: "the writer's value for that field is ignored". Reader field missing from the writer: reader's default if it has one; no default is an error [fetched].
|
||||
- Enum, writer symbol absent in reader: reader's declared default if any, else error [fetched].
|
||||
- Preservation: none. Extra fields are dropped by resolution [fetched].
|
||||
|
||||
### FlatBuffers
|
||||
- Union evolution: appending a member is safe ("CodeV1 will not recognize the another_a"); inserting in the middle without an explicit discriminant misreads members; inserting with an explicit discriminant is safe (flatbuffers.dev/evolution/) [fetched].
|
||||
- What an old reader sees for an unknown union type, and re-serialization preservation: [not found] on that page. Generated readers expose a type byte plus a union table pointer; an unknown type value falls outside the generated enum [background].
|
||||
|
||||
### Thrift
|
||||
- Unknown fields and unknown union field ids: [not found] in thrift-rpc.md. Protocol readers skip unrecognized field ids and drop the data; an unknown union id leaves the union empty, and a union with no field set can fail validation [background].
|
||||
|
||||
### MessagePack-CSharp [Union]
|
||||
- README Union section says only "Unique union keys are required"; it states no behaviour for an unknown key and no option for it [fetched, first 100k chars of the README].
|
||||
- Missing keys: members initialize to default (README, Object Serialization) [fetched]. Extra array elements for [Key(int)] and unknown string keys: README silent; it shows a manual formatter that loops and skips extras [fetched].
|
||||
- Generated and dynamic union formatters skip the payload and yield null when the key is absent from the union's key map [background]. The estate's own measurement agrees: unknown arm key decodes to null, no error (question document, "Measured in the C# reference... MessagePack-CSharp 3.1.7") [local, via eureka-state view]. The vendored copy at F:\Projects\CultPong\Assets\Scripts\MessagePack\Resolvers\DynamicUnionResolver.cs does a key-map TryGetValue at :347 (type-map TryGetValue at :206); the miss branch was not read.
|
||||
- No configurable unknown-union behaviour found in the README; whether a newer version adds one [not found].
|
||||
|
||||
### serde
|
||||
- enum-representations page says nothing on unknown variant names, #[serde(other)] or deny_unknown_fields [fetched]. serde_derive de.rs was fetched but the identifier/enum_ modules holding unknown_variant were not in the excerpt [not found].
|
||||
- [background] default: an unknown variant is an error ("unknown variant `X`, expected one of ..."); #[serde(other)] on a unit variant makes the identifier decoder return it for any unknown name (units only, payload discarded); unknown struct fields are ignored unless #[serde(deny_unknown_fields)]; a missing field is an error unless #[serde(default)] or Option.
|
||||
|
||||
### Bincode / postcard
|
||||
- [background] Both are non-self-describing: an enum is a variant index (bincode u32, postcard varint) followed by fields in order; an out-of-range index is a decode error; there are no field tags, so an extra or missing slot is detectable only by running out of or leaving bytes. Evolution is by schema versioning outside the format. Not fetched.
|
||||
|
||||
## 2. Preservation across an older reader, and the failure each answers
|
||||
| System | Unknown data survives re-encode? | Failure answered |
|
||||
|---|---|---|
|
||||
| Protobuf | yes: unknown fields (hence unknown oneof cases) and unknown enum ints, in binary APIs only [fetched] | old intermediary re-serializing a newer message (purpose: background) |
|
||||
| Cap'n Proto | page silent; reader sees a tag it may not know and must handle it [fetched] | in-place access; append-only evolution |
|
||||
| Avro | no: extra field dropped, or error on no branch / no default [fetched] | writer schema travels with data, so resolution is exact and loud |
|
||||
| FlatBuffers | page silent [fetched] | append-only evolution, explicit discriminants |
|
||||
| Thrift | no (skipped) [background] | forward tolerance for old readers |
|
||||
| MessagePack-CSharp | no: arm becomes null (measured), extra slot skipped | not documented |
|
||||
| serde | no; error by default [background] | type safety; leniency is opt-in |
|
||||
| Bincode/postcard | n/a [background] | compactness; no evolution in the format |
|
||||
| Unity SerializeReference, DataContract ExtensionData | yes: bytes retained and recoverable (docs/research/read-only-record-signal-prior-art.md:182-205) [local] | data loss from missing types |
|
||||
|
||||
## 3. CultCache's own stance (F:\Projects\CultLib)
|
||||
- docs/persisted-record-encoding.md:1-19: persisted records are verified by re-encoding what was decoded and comparing bytes; a record that reads but re-encodes differently is refused, on live data at startup or next read. Three Idunn guards cited at :10-14. [local] A tolerated extra trailing slot or a null-collapsed arm would not re-encode to the stored bytes; whether those guards would run on such records was not tested.
|
||||
- No evolution/compatibility doc: `ls docs | grep persist|evol|compat|schema|version` returns only persisted-record-encoding.md. docs/document-variants-cut.md:327-333 covers union-slot reuse at registration ("late union-slot reuse passes registration"; "interface unions are never minted") [local, grep lines only].
|
||||
- Reference union handling: src/GameCult.Caching/CultInspectorModel.cs:768-774 classifies an abstract/interface type by its [UnionAttribute]s ordered by key and refuses a type with none ("declares no [Union] subtypes", :772); also :120. This is the inspector's shape classifier; decode is MessagePack-CSharp's. No other use of UnionAttribute in src/GameCult.Caching. [local]
|
||||
- Trailing-slot tolerance: packages/cultcache-ts/test/cult-cache.test.ts:1176-1195, "CultCache interop reader accepts missing compatible trailing slots and rejects mismatched slots": a legacy-payload store with fewer slots reads with `tags: []`; a mismatched-type payload rejects with /Expected string/u. Missing trailing slots are tested; extra trailing slots are not. [local]
|
||||
- TS decode: packages/cultcache-ts/src/cult-cache.ts:679-692 wraps a formatter as `schema.parse(decode(payload))`, so TS strictness is whatever the zod schema says; no TS union codec (follow-up text). [local]
|
||||
- Rust: packages/cultcache-rs/src/*.rs has no unknown-arm or extra-slot handling found by grep; "unknown" hits are store-header tests (:4889-4890 refuses an unknown header by name; :5009-5019 unknown-header.msgpack, variant-v2.msgpack). Rust enum arms persist as serde external tags (follow-up text). [local]
|
||||
- Consumers persisting unions: Aetheria (F:\Projects\Aetheria) has `[Union]` abstract classes in Assets/Scripts/ServerShared: Provenance.cs:96-98 (keys 0-2), ItemInstance.cs:18-21 (keys 0-3) and :29-31, Environment.cs:73. The assembly registers CultCache documents (AssemblyInfo.cs:3-4; Galaxy.cs, ItemData.cs, AetheriaStores.cs reference CultCache); ItemInstance is held in entity item lists (Entity.cs:2003). An older build reading a store with a newer arm key would take the C# null-arm path, if these types sit inside persisted CultCache documents; that persistence path was not traced. Aetheria-legacy has more unions (Behaviors.cs:29-38, Item.cs:43-63, Contract.cs:10-11); commented-out keys 8, 9 at Behaviors.cs:37-38 show arms retired in place. [local]
|
||||
- Ghostlight and Huginn: not searched for [Union] (the grep matched only Aetheria). Follow-up text: "No live record crosses runtimes as a union today" [local, view]. Same-runtime older-build-reads-newer-store: unverified.
|
||||
- The question document records the C# measurement: extra trailing slot skipped and equal; missing trailing slot leaves member default; unknown arm null, for a Node in a list and for an Outcome; Rust and TS union decoders with explicit keys refuse by construction; Rust extra-slot behaviour unmeasured [local, view].
|
||||
|
||||
## 4. Operator's stated value, and how each option relates (inferred)
|
||||
Verbatim, operator-rapport.md:50: "nobody should have to carry bytes they don't understand ... CultCache's whole promise is that a cache's contents are self-identifying via the upfront catalog." Context: pushing back on storing retired slots as metadata (:49). [local]
|
||||
- Preserve-unknown (protobuf, Unity): the older reader carries bytes the catalog does not describe. Opposite to the stated value.
|
||||
- Drop silently (Avro extra fields, MessagePack slot skipping, Thrift skip): nobody carries the bytes, but the loss is silent and a re-encode no longer equals the stored bytes (persisted-record-encoding.md:4-6).
|
||||
- Null the arm (current C# union behaviour): the unknown arm becomes a value the catalog does not describe either; the record decodes as if valid.
|
||||
- Refuse (Avro no-branch, serde default, Rust/TS explicit-key decoders, store-header refusal): the reader declares it cannot understand the bytes; consistent with self-identifying content because undescribed content is not accepted.
|
||||
- Tolerate trailing slots but refuse unknown arms (fork option 1): the catalog-described slot list governs required members; slots beyond it are skipped, which is the drop-silently pattern for slots and the refuse pattern for arms.
|
||||
83
docs/research/cycles-fma-contraction.md
Normal file
83
docs/research/cycles-fma-contraction.md
Normal file
|
|
@ -0,0 +1,83 @@
|
|||
# Cycles CPU FMA contraction: facts for the kernel-pin fork
|
||||
|
||||
Serves finding `cultmath-tapes:finding:cut-cycles-converters.s1.kernel-pin-unraised-fork` (kind Finding, InForce, Medium, admitted 2026-10-13, soul-cycles-converters-s1).
|
||||
Gathered by eyes-cycles-fma, session self-2026-10-14-eureka, 2026-10-14. Facts only; no recommendation.
|
||||
|
||||
Strength marks: [src] read from source text; [doc] vendor or standards documentation; [web] issue, forum or search-result summary; [abs] absence of evidence (searched, not found).
|
||||
"Raw" Blender paths below are fetched as `https://projects.blender.org/api/v1/repos/blender/blender/raw/<path>?ref=<tag or branch>`. Local copies of the main-branch files are in `...\scratchpad\eyes-cycles-fma\dl\`.
|
||||
|
||||
## 0. The finding's own record (what is being tested)
|
||||
|
||||
- [src] The finding quotes the oracle probes: with the AVX2 kernel, 17 function rows differ from committed fixtures (floored_modulo 151/1024 cases ... color 55/1024), worst `mix_overlay` 493 ulp, `cycles_floored_modulo` 958152704 ulp (sign flip). Yggdrasil's /proc/cpuinfo shows avx2 and fma.
|
||||
- [src] Oracle code: `kernel_check()` in `tools/cycles-oracle/oracle.py` bakes FLOORED_MODULO of 10000 by 0.1 and compares to numpy unfused `a - floor(a/b)*b`; exits 4 if the kernel fuses. Read with `git show e48f9488:packages/cultmath/tools/cycles-oracle/oracle.py` (lines ~528-551), README lines 20-30, `CyclesOracleTests.cs` lines 5-18 (those paths are not in the working tree at main; they exist at commit e48f9488). The oracle Blender is 5.2.2.
|
||||
|
||||
## 1. Cycles CPU kernels and flags
|
||||
|
||||
1. [src] The CMake file defines two x86 CPU kernel variants only: an SSE4.2 baseline and an AVX2 kernel (`WITH_KERNEL_AVX2`). No AVX-512 flag or kernel appears; `kernel.cpp` lists `cpu` and `cpu_avx2`. `intern/cycles/CMakeLists.txt` lines 76-130, 137-143 (main and v5.2.2); `intern/cycles/device/cpu/kernel.cpp` line 11 (v5.2.2): `KERNEL_NAME_EVAL(cpu, name), KERNEL_NAME_EVAL(cpu_avx2, name)`.
|
||||
2. [src] GCC/Clang flags (CMakeLists.txt lines 97-100): SSE4.2 = `-msse -msse2 -msse3 -mssse3 -msse4.1 -msse4.2`; AVX2 = SSE4.2 flags + `-mavx -mavx2 -mfma -mlzcnt -mbmi -mbmi2 -mf16c`. The `-mfma` flag is what makes FMA instructions available only in the AVX2 kernel. MSVC: AVX2 kernel `/arch:AVX2`, SSE4.2 kernel empty on x64 (lines 82-89). Intel compilers use `/QxCORE-AVX2` or `-xcore-avx2`.
|
||||
3. [src] Contraction flags, GCC/Clang block (CMakeLists.txt lines 160-180, main = v5.2.2): `-fno-trapping-math`, `-fno-math-errno`, `-fno-signed-zeros`, `-ffp-contract=on`, `-freciprocal-math`; `-fassociative-math` is commented out ("problems with bsdf_D for GGX on Linux (#130389)"); `-ffinite-math-only` deliberately not set. These are appended to the global `CMAKE_CXX_FLAGS`, so they apply to both kernels; only `-mfma` differs. GCC additionally gets `-fno-signaling-nans`, `-fno-rounding-math`, `-mfpmath=sse`.
|
||||
4. [src] MSVC (non-clang) block (line 149): `/fp:fast`, with the comment "Unlike GCC/clang we still use fast math, because there is no fine grained control and the speedup we get here is too big to ignore." For clang-cl the GCC/Clang flag list is passed with a `/clang:` prefix (line 198).
|
||||
5. [src] History of the contraction flag (Forgejo API commit messages):
|
||||
- `f96f3c33af`, 2024-09-30, "Cycles: Add some more math optimizations": added `-ffp-contract=fast`, `-freciprocal-math`, `-fassociative-math`. Message: "These are used on Windows and HIP anyways, so our code can't expect exact IEEE semantics in any case." Measured "~1.5% speedup in my very quick test".
|
||||
- `0fc58f0aba`, 2024-11-25, "Disable -fassociative-math on Linux to avoid GGX issues".
|
||||
- `7b19e74cad`, 2025-12-14 (PR 150318): changed `fast` to `on`: "Disable FMA auto-vectorization across different statements in Cycles, because GCC 15.2.1 manages to ruin the viewport's scaling and offset" (GCC bug 106902). It also removed a `remove_cc_flag("-ffp-contract=off")` block ("Not needed to make cycles automated tests pass with -march=native. However Blender itself needs this flag").
|
||||
- Before 2024-09-30 the CMake file carried no Cycles-specific contraction flag; the global Blender flag was `-ffp-contract=off` (stripped for Cycles by that `remove_cc_flag` block). [src, inferred from the removed lines; the earlier state was not read at an older tag.]
|
||||
6. [doc] GCC definition: `-ffp-contract=on` "enables contraction within one expression, but not across different statements"; `fast` forms FMA "if the target has native support"; default `off` for ISO C, `fast` otherwise. Source: https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html. (Which GCC release implemented `on` for C++ was not checked.)
|
||||
7. [src] Cycles' floored modulo is one C++ expression: `return (b != 0.0f) ? a - floorf(a / b) * b : 0.0f;` in `intern/cycles/util/math_base.h` (v5.2.2 line 613-616; main line 646-649). `NODE_MATH_FLOORED_MODULO` calls it from `kernel/svm/math_util.h` line 164. `safe_modulo` (truncated) uses `fmodf`, not an expression. `-freciprocal-math` also permits `a/b` to become `a * (1/b)`.
|
||||
8. [src] Env switch: `intern/cycles/util/debug.cpp` (v5.2.2) line 29 `CHECK_CPU_FLAGS(avx2, "CYCLES_CPU_NO_AVX2")`, line 23 `flag = (getenv(env) == nullptr)`; presence of the variable disables the AVX2 kernel. [web] added 2015-02 by Sergey Sharybin, commit 4b04a4e, described as developer-only: https://lists.blender.org/pipermail/bf-blender-cvs/2015-February/073396.html (via search summary).
|
||||
9. [src] The AVX2 kernel is selected at runtime by CPU capability: `system.cpp` `system_cpu_support_avx2()` requires avx2 and f16c ("F16C is considered part of AVX2 for our purpose"), so a default Blender on any AVX2 CPU uses it.
|
||||
10. [src] Cycles' own render tests are image tests with a default `fail_threshold = 0.016`, `fail_percent = 1` (`tests/python/modules/render_report.py` lines 287-288), overridden per test (e.g. 0.032, 0.06, 0.048; `tests/python/cycles_render_tests.py` ~339-357). They compare images, not per-node bit patterns. A grep for AVX/NO_AVX in these two files found nothing, so the tests do not appear to pin a kernel. [src for what was found; absence is [abs]]
|
||||
|
||||
## 1b. GPU backends
|
||||
|
||||
11. [src] CUDA: `intern/cycles/device/cuda/device_impl.cpp` line ~225 passes `--use_fast_math` to nvcc (nvcc fuses FMA by default; `--fmad` default is documented NVIDIA behaviour, not fetched here). `kernel/device/cuda/compat.h` line 89 has the comment "Use fast math functions".
|
||||
12. [src] HIP: `kernel/device/hip/compat.h` line 91 "Use fast math functions" (the HIP compile flags were not located; the commit message in item 5 states HIP already runs without exact IEEE semantics).
|
||||
13. [src] Metal: `device/metal/device_impl.mm` line 570 `options.fastMathEnabled = YES;`.
|
||||
14. [src] oneAPI: `kernel/device/oneapi/CMakeLists.txt` line 71 `-ffast-math`, line 83 `-cl-fast-relaxed-math` for spir64.
|
||||
15. [src] OptiX: not separately examined (OptiX kernels are CUDA-compiled).
|
||||
16. [src] The fp-contract/fast-math choices are thus explicit in all of: CPU (`on`, both kernels), MSVC CPU (`/fp:fast`), CUDA, HIP, Metal, oneAPI.
|
||||
|
||||
## 1c. Do Blender developers treat CPU/GPU numeric differences as bugs
|
||||
|
||||
17. [web] Issue #101114 (Power math node precision): a developer said they do not handle such precision issues as bugs since implementation is by the GPU driver and manufacturer. https://developer.blender.org/T101114 (search-result summary; page not read).
|
||||
18. [web] Issue #68687 (Eevee modulo inconsistent): a developer said the imprecision "is likely to remain as it is an implementation behavior we cannot ensure"; reporters noted Cycles gave the expected result. https://developer.blender.org/T68687 (summary).
|
||||
19. [web] Issue #53348 (Cycles CPU vs GPU in World nodes): a developer attributed the difference to "--fast-math we use for CUDA" and noted disabling it costs about 15% speed. https://projects.blender.org/blender/blender/issues/53348 (summary; page returned 403 to WebFetch).
|
||||
20. [web] Issue #67448 "Shader node float precision issue cause different results on CPU and GPU" exists (archived); its content was not read (redirect not followed). https://developer.blender.org/T67448
|
||||
21. [abs] No Blender issue specific to Floored Modulo and FMA/AVX2 was found; no Blender document stating a CPU/GPU numeric parity guarantee was found.
|
||||
|
||||
## 2. Shader languages
|
||||
|
||||
22. [doc] HLSL `precise`: separate operations stay separate ("where a mul and add operation might have been fused into a mad operation, precise forces the operations to remain separate"; fusion then only via the explicit `mad` intrinsic); order of operations preserved; IEEE NaN/INF honoured. It propagates only to operations that contribute to the `precise`-qualified variable; marking shader outputs is recommended. https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-variable-syntax
|
||||
23. [doc] HLSL `mad`: may be fused or mul+add in hardware; for `precise` values the hardware must be consistent across all uses of that mad on that hardware. https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/mad (search summary). [web] The HLSL team blog says any operation may be refactored unless `precise`, and `/Gis` makes all computations precise: https://learn.microsoft.com/ko-kr/archive/blogs/marcelolr/precise-and-ieee-strictness-in-hlsl (summary).
|
||||
24. [abs] DXC's default contraction of plain `a*b+c` was not confirmed from DXC docs or source; clang HLSL PR #119820 "Make fast math the default for HLSL" exists (https://lists.llvm.org/pipermail/cfe-commits/Week-of-Mon-20241209/654101.html), content not read.
|
||||
25. [src] Vulkan SPIR-V environment (https://registry.khronos.org/vulkan/specs/1.3/html/chap37.html, fetched and grepped): "Implementations may rearrange floating-point operations using any of the mathematical properties governing the expressions in precise arithmetic ... may involve a different number of rounding steps"; "This rearrangement can be prevented for particular operations by using the NoContraction decoration." Without NoContraction the flags AllowContract/AllowReassoc/AllowRecip/AllowTransform are assumed. Same page: OpFMod "Inherited from x - y * floor(x/y)"; OpFRem inherited from `x - y * trunc(x/y)`; OpFDiv 2.5 ULP for |y| in [2^-126, 2^126]; and the page lists `OpFmaKHR`/`shaderFmaFloat32` (a core-spec FMA capability) as new.
|
||||
26. [doc] GLSL: `precise` qualifier ("the qualifier precise will ensure that operations contributing to a variable's value are performed in the order and with the precision specified") "effectively prohibits the arbitrary use of fused multiply-add"; under `precise`, `fma()` is one operation and `a*b+c` is two. Sources: GL_ARB_gpu_shader5 / OES_gpu_shader5 text and https://registry.khronos.org/OpenGL-Refpages/gl4/html/fma.xhtml (search summary). `invariant` was not looked up.
|
||||
27. [doc] SPIR-V `NoContraction` goes on the intermediate-result instructions, not the variable; GLSL `precise` lowers to it in glslang/ANGLE. [web] LLVM-based backends have contracted NoContraction multiplies into fma before (bug report in search results, wording in item summary only).
|
||||
28. [web] Metal: `MTLCompileOptions.fastMathEnabled`/`mathMode` (fast vs safe); in safe mode MSL requires correctly rounded FP32 add, sub, mul, div, fma; `metal::precise` namespace gives precise library functions; explicit `fma()` is the advice for controlling fusion. https://developer.apple.com/documentation/metal/mtlcompileoptions/mathmode.md and https://developer.apple.com/forums/thread/90959 (summaries). Current Xcode default for fast math was not confirmed ([web] sources conflict). No Metal `fp_contract` pragma found [abs].
|
||||
29. [abs] Unity's shader compiler (FXC/DXC via HLSLcc/SPIRV-Cross) contraction behaviour: no documentation found.
|
||||
|
||||
## 3. C# / .NET
|
||||
|
||||
30. [doc] `Math.FusedMultiplyAdd` (and `MathF`): "Returns (x * y) + z, rounded as one ternary operation"; infinite-precision multiply and add then one rounding. Available .NET Core 3.0+ and .NET 5-11. https://learn.microsoft.com/en-us/dotnet/api/system.math.fusedmultiplyadd
|
||||
31. [web] dotnet/runtime issue #10137 "[Jit] Recognize FMA pattern and Emit Fused Multiply Add" closed 2024-02-05 as COMPLETED with the maintainer comment: "Closing this. We have explicit `FusedMultiplyAdd` APIs and will likely cover any future 'pick the better of MultiplyAdd or FusedMultiplyAdd' via an explicit `MultiplyAddEstimate` API." (read with `gh issue view 10137 -R dotnet/runtime`). Earlier comments there state the intent that `a*b+c` stay two IEEE roundings. PR #61037 adds an arm64 MADD fold for integers only (summary).
|
||||
32. [web] Issue #98704 "Math.FusedMultiplyAdd returns wrong results on systems without FMA3 support", closed COMPLETED 2025-05-06: the software fallback had been an estimate (suspected ucrtbase `fma`), so correct rounding was guaranteed only with hardware FMA3; `COMPlus_EnableFMA=0` did not reproduce it on FMA3 hardware. Fix details were not read. Also [web] TA-Lib issue #340 reports the same misrounding concern.
|
||||
33. [abs] A statement in .NET docs that RyuJIT never contracts floating-point `a*b+c` was not found; #10137's closure is the nearest evidence. The CultMath repo's own use of FusedMultiplyAdd/MathF.FusedMultiplyAdd was not searched.
|
||||
|
||||
## 4. Other reference implementations and tolerance policies
|
||||
|
||||
34. [src] OpenShadingLanguage testsuite (`testsuite/runtest.py` lines 82-87): image diff thresholds `failthresh = 0.004`, `hardfail = 0.01`, `failpercent = 0.02`, warn at 2x failthresh; "A test fails if more than failpercent of pixel values differ by more than failthresh ... or if even one pixel differs by more than hardfail." Raw URL: https://raw.githubusercontent.com/AcademySoftwareFoundation/OpenShadingLanguage/main/testsuite/runtest.py
|
||||
35. [src] Blender's Cycles render tests: item 10 (image thresholds, default 0.016/1%).
|
||||
36. [doc] Vulkan precision table lists per-operation ULP classes (item 25); functions defined as expressions inherit the budgets of their constituents (GLES3 CTS spec, https://fuchsia.googlesource.com/third_party/vulkan-cts/+/30e25b62d60b36b923d19a0c0759ef6cb7201f9e/doc/testspecs/GLES3/functional.shaders.builtin_functions.precision.txt, summary). Historical draft GL_ARB_shader_precision: `a*b+c` "correctly rounded single operation or sequence of two correctly rounded operations", fma same as a*b+c (https://developer.download.nvidia.com/opengl/specs/GL_ARB_shader_precision.txt, summary).
|
||||
37. [abs] Not found/not examined: MaterialX reference-vs-generated shader tolerances (only structure of MaterialXTest located); glTF sample renderer conformance; any published "bit-exact vs ulp class" policy statement from Khronos, MaterialX, OSL or Blender; the Vulkan CTS source ULP constants for mix/smoothstep/fma.
|
||||
|
||||
## 5. Floored modulo specifics
|
||||
|
||||
38. [src] Definition in Cycles: `a - floorf(a / b) * b` (item 7). For a=10000, b=0.1f the quotient a/b rounds to 100000 (float) and floorf gives 100000, so the unfused product 100000*b rounds to 10000 and the result is 0, as the oracle records; the fused form computes the residual of the exact product (b is not exactly 0.1), yielding -1.49e-4 as the finding records. [abs] This arithmetic was not re-run here; it restates the finding's `kernel_check` docstring (oracle.py).
|
||||
39. [abs] No Blender issue or commit mentioning Floored Modulo together with FMA, contraction or AVX2 was found. [web] Related reports concern modulo/wrap disagreements between Cycles and Eevee/GPU drivers (#101562, #68687, #88151).
|
||||
40. [doc] Vulkan states OpFMod is "inherited from x - y * floor(x/y)", i.e. the same formula, so a GPU implementation of it follows its own contraction/precision rules (item 25).
|
||||
|
||||
## Coverage and gaps
|
||||
|
||||
- Strong [src]: Cycles flag set per ISA and compiler, the history of `-ffp-contract`, `safe_floored_modulo`, `CYCLES_CPU_NO_AVX2` mechanism, GPU backends' fast-math flags, Cycles/OSL image-test thresholds, Vulkan NoContraction and OpFMod text, HLSL `precise`.
|
||||
- Gaps: which compiler/version builds official Blender 5.2.2 release binaries (matters for how `-ffp-contract=on` is honoured); the 4.x flags before/after 2024-09-30 at release tags; DXC/Unity default contraction; Metal contraction pragma; MaterialX, glTF and Vulkan CTS numeric tolerances; a direct statement that RyuJIT never contracts; Blender developer position on CPU/GPU parity beyond forum/issue summaries (several pages 403 to WebFetch).
|
||||
- Files of record: `C:\Users\Meta\AppData\Local\Temp\claude\F--Projects-CultLib\0d5eef6e-e366-457f-bbc6-0151080ae1a8\scratchpad\eyes-cycles-fma\dl\` (CMakeLists.txt, math_base.h, math_util.h, vk.html).
|
||||
83
docs/research/decode-stack-safety.md
Normal file
83
docs/research/decode-stack-safety.md
Normal file
|
|
@ -0,0 +1,83 @@
|
|||
# Decode stack safety: prior art (facts only)
|
||||
|
||||
Serves follow-up `cultlib-gaps:follow_up:decode-stack-safety` (campaign cultlib-gaps), source finding `thing2:finding:cut-contract-rs.s1.decode-stack-overflow-within-bound`.
|
||||
Gathered 2026-10-12 by eyes-decode-stack at CultLib `67c79d5c`. No recommendation. Web facts come from WebFetch/WebSearch summaries of the pages named; items marked UNVERIFIED were not confirmed against primary source.
|
||||
|
||||
## A. The local door (what exists today)
|
||||
|
||||
- `packages/cultcache-rs/src/lib.rs:503` `MAX_PAYLOAD_DEPTH = 256`; `check_payload_depth` (~526-540) is an iterative walk with a `[usize; 256]` count stack, scalars skipped by length.
|
||||
- `lib.rs:598-604` `decode_payload`: `check_payload_depth(payload)?; rmp_serde::from_slice(payload)`. Its doc comment calls rmp-serde's own counter (1024) "only a backstop".
|
||||
- Derive: `packages/cultcache-rs/cultcache-rs-derive/src/lib.rs:294-330` generates `impl Deserialize` with a `Visitor::visit_seq` over slot-ordered arrays (`deserialize_tuple`); unknown trailing elements are consumed via `IgnoredAny`.
|
||||
- rmp-serde resolved version: 1.3.1 (rmp 0.8.15; `packages/cultcache-rs/Cargo.lock`). Its depth limit is a `u16` `depth: 1024`, decremented per array/map/ext (`~/.cargo/registry/src/*/rmp-serde-1.3.1/src/decode.rs` lines 181, 213, 294, 566, 583, 616), error `DepthLimitExceeded`, tunable with `Deserializer::set_max_depth` (clamped to u16::MAX, lines 307-310). CHANGELOG line 95: "Default stack protector depth is now 1024 instead of 1000."
|
||||
- Upstream master rmp-serde (fetched summary, not checked line by line against 1.3.1): the `deserialize_newtype_struct` MSGPACK_EXT_STRUCT_NAME branch builds `ExtDeserializer` without `depth_count!`; the `any_inner` ext path does use it.
|
||||
- Existing local tests that already use sized threads: `packages/cultcache-rs/tests/union_parity.rs` ~786-830: `stack_budget_debug_2mib` (comment: "A debug build on a 2 MiB thread carries 405 containers of this document; the bound keeps every accepted payload below that") on a slim fixture (`wrap_chain(126, ...)`), and `the_walk_does_not_recurse` (100000 nested arrays refused on a 256 KiB thread). No stacker, `stack_size`, or thread spawn in `src/` or `Cargo.toml`.
|
||||
- The rmp-serde 1024 counter and the CultLib 256 bound both count containers; per-level stack cost depends on the target type (follow-up text: 15-19 KiB release, 87-95 KiB debug per level for contract-sized types).
|
||||
|
||||
## B. Rust serde ecosystem
|
||||
|
||||
### serde_json
|
||||
- Default limit 128: `Deserializer::new` sets `remaining_depth: 128` (field `u8`); `check_recursion!` returns `ErrorCode::RecursionLimitExceeded` at 0; invoked in `deserialize_any/seq/map/struct/enum`. https://github.com/serde-rs/json/blob/master/src/de.rs
|
||||
- `disable_recursion_limit()` exists only under Cargo feature `unbounded_depth`. Docs: "Parse arbitrarily deep JSON structures without any consideration for overflowing the stack"; tells the caller to "provide some other way to protect against stack overflows" and names `serde_stacker`. Docs also warn that Display, Debug and Drop on the result can overflow. https://docs.rs/serde_json/latest/serde_json/struct.Deserializer.html
|
||||
- The limit is a nesting-level count; no per-type frame accounting (code read: counter decrement only). The serde_json README mentions no recursion limit.
|
||||
|
||||
### serde_stacker (dtolnay)
|
||||
- Adapter wrapping a serde (de)serializer that grows the stack dynamically; README examples use `serde_json::Deserializer`, call `disable_recursion_limit()`, wrap with `serde_stacker::Deserializer::new`, nest 10,000 levels. README names Display/Debug/Drop as other overflow points and shows a manual iterative drop. README does not say it depends on `stacker` (UNVERIFIED). https://github.com/dtolnay/serde-stacker
|
||||
- It is a serde-level `Deserializer` wrapper, so it hooks calls routed through the wrapped deserializer.
|
||||
|
||||
### rmp-serde / rmpv
|
||||
- rmp-serde: depth counter 1024 default (section A). Search found no RUSTSEC advisory or issue for rmp / rmp-serde stack overflow (negative search, not proof). https://github.com/3Hren/msgpack-rust (rmp-serde/src/decode.rs).
|
||||
- rmpv not inspected.
|
||||
|
||||
### Other Rust deserializers
|
||||
- ciborium: `recurse: usize` default 256 in `from_reader`; `from_reader_with_recursion_limit`; doc: "Set a high recursion limit at your own risk (of stack exhaustion)!" https://github.com/enarx/ciborium (ciborium/src/de/mod.rs)
|
||||
- serde_cbor: RUSTSEC-2019-0025, tags nested without limit, <1 kB input overflows the stack, fixed in 0.10.2 by limiting nested tags. https://rustsec.org/advisories/RUSTSEC-2019-0025
|
||||
- rustc-serialize: RUSTSEC-2022-0004, JSON parser with no depth limit, "stack overflow, which aborts the process", unpatched, advises serde. https://rustsec.org/advisories/RUSTSEC-2022-0004
|
||||
- yaml-rust: RUSTSEC-2018-0006, deep nesting aborts, fixed by depth check. https://rustsec.org/advisories/RUSTSEC-2018-0006
|
||||
- serde-json-wasm: GHSA-j87p-gjr6-m4pv, overflow on deep untrusted JSON, fixed 1.0.1 by recursion depth check. https://advisories.gitlab.com/pkg/cargo/serde-json-wasm/GHSA-j87p-gjr6-m4pv/
|
||||
- quick-xml PR 982: adds a depth cap to its serde deserializer, default 128 "matching serde_json". https://github.com/tafia/quick-xml/pull/982
|
||||
- prost: `const RECURSION_LIMIT: u32 = 100`, comment "100 is the default recursion limit in the C++ implementation"; disabled by feature `no-recursion-limit`. https://github.com/tokio-rs/prost/blob/master/prost/src/lib.rs
|
||||
- bincode, postcard, simd-json: searches returned nothing on depth handling; not established either way.
|
||||
- Rust forum user report: serde overflowing the default stack beyond roughly 100 levels in some types, worked around with a 32 MiB thread. https://users.rust-lang.org/t/deserialize-large-nested-struct-without-stack-overflow/136335
|
||||
|
||||
## C. Stack-growth mechanism: stacker / psm / stacksafe
|
||||
|
||||
- `stacker::maybe_grow(red_zone, stack_size, f)`: checks whether the current stack is within `red_zone` bytes of its end; if so allocates a new stack of "at least `stack_size` bytes" and runs `f` there; else runs on the current stack. The closure runs on a stack with at least `red_zone` bytes available. https://docs.rs/stacker/latest/stacker/fn.maybe_grow.html
|
||||
- Source (rust-lang/stacker `src/lib.rs`): remaining stack = stack pointer minus thread-local `STACK_LIMIT` (lazily from `guess_os_stack_limit`); if `remaining_stack()` is `None`, `maybe_grow` "immediately grow[s]"; panics are caught on the new stack and re-raised after the segment is freed (`catch_unwind` / `resume_unwind`); on unsupported platforms `_grow` is a no-op that just calls the callback.
|
||||
- Platform: README says psm on most platforms, a Fibers-based implementation on Windows; "On all unsupported platforms this library is a noop... code will continue to hit the guard pages". https://github.com/rust-lang/stacker
|
||||
- psm README table (rust-lang/stacker/psm/README.mkd): Windows x86_64 Available Yes / Tested Yes / Callstack "Yes, but disabled"; Windows i686, aarch64, arm: No/No/No; Linux x86_64, i686, aarch64, arm: Yes/Yes/Yes; wasm: No/No/No ("callstack is not even in an address space"). Text: stacks allocated the usual way are not valid on Windows; Fibers offered as an "unnecessarily slow and inflexible" alternative.
|
||||
- CONFLICT, not reconciled: stacker's code selects a Windows backend (`backends::windows::_grow`, `cfg(all(windows, not(miri)))`) while the psm table marks Windows callstack "disabled"; stacker has a wasm32 branch (alloc-based restore guard) while psm lists wasm as No. An older docs.rs stacker 0.1.0 page lists a different verified-platform list.
|
||||
- Not found in sources read: per-call cost numbers; Windows aarch64 behavior of stacker beyond the psm table.
|
||||
- rustc usage (ensure_sufficient_stack, red zone / segment constants): two fetches returned 404; not recorded.
|
||||
- `stacksafe` (fast/stacksafe): `#[stacksafe]` attribute checks remaining stack at function entry and allocates a new segment below a threshold; defaults 128 KiB threshold, 2 MiB segment; optional `serde` feature gives stack-safe (de)serialization for the `StackSafe<T>` wrapper; MSRV 1.88.0; credits Orson Peters' `recursive` crate; says it supports platforms stacker supports (dependency on stacker not confirmed). https://github.com/fast/stacksafe
|
||||
|
||||
## D. Dedicated thread with sized stack
|
||||
|
||||
- `std::thread`: default spawned-thread stack "currently 2 MiB on all Tier-1 platforms"; `Builder::stack_size`; `RUST_MIN_STACK` (overridden by `stack_size`, "may be ignored after program start"); "the stack size of the main thread is not determined by Rust". https://doc.rust-lang.org/std/thread/index.html
|
||||
- Local use is in tests only (`union_parity.rs`, section A). No library was found in this pass that spawns its own decode thread for untrusted input; the Rust forum report (section B) and the protobuf.js advisory describe it as a caller-side or process-level workaround.
|
||||
- protobuf.js CVE-2026-44289 workarounds: reject excessively nested messages at an outer protocol boundary, or isolate decoding "in a process that can be safely restarted". https://corgea.com/advisories/vulnerabilities/CVE-2026-44289
|
||||
|
||||
## E. Non-recursive decoders
|
||||
|
||||
- `deser` crate (mitsuhiko, experimental): "does not recurse on the call stack, so deep nesting needs no recursion limit"; nested sinks/emitters kept in an arena; not serde-compatible; calls itself "an experiment". https://github.com/mitsuhiko/deser/wiki
|
||||
- `core-json`: no-std JSON parser with a fixed-size or caller-supplied state stack; typed layer is a separate crate, `core-json-traits`. https://docs.rs/core-json
|
||||
- No serde-compatible explicit-stack derive deserializer found (search negative).
|
||||
- msgpack-javascript: decoder iterative, `StackPool` array of states; DecoderOptions has no max depth, only length caps (`maxStrLength`, `maxBinLength`, `maxArrayLength`, `maxMapLength`, `maxExtLength`); pool memory grows with deepest nesting; array states allocate `new Array(size)` up front. https://github.com/msgpack/msgpack-javascript/blob/main/src/Decoder.ts
|
||||
- msgpack-python C unpacker (`unpack_template.h`): explicit `unpack_stack stack[MSGPACK_EMBED_STACK_SIZE]`, `start_container` returns -3 at `top >= SIZE`. `unpack.h` defines the size as 1024 (`unpack_define.h` default is 32). Local probe (msgpack 1.2.2, CPython 3.13.15, `python -I`): 100, 256, 1000 nested arrays decode ok; 100000 raises `StackError`.
|
||||
- CultLib's own `check_payload_depth` walkers are iterative (Rust lib.rs ~526; TS `packages/cultcache-ts/src/payload-depth.ts`; C# `CultPayloadDepth.cs`).
|
||||
|
||||
## F. Advisories and other-language limits
|
||||
|
||||
- MessagePack-CSharp CVE-2026-48506 / GHSA-vh6j-jc39-fggf (published 2026-06-25): `MessagePackReader.TrySkip()` recursed without counting depth, bypassing `MaximumObjectGraphDepth`; reachable through generated formatters' `reader.Skip()` on unknown keys; uncatchable StackOverflowException; affected <2.5.301 and 3.0.0 to <3.1.7; fix: iterative loop with a heap pending-count. https://securelayer7.net/lab/cve-2026-48506-messagepack-csharp-tryskip-uncontrolled-recursion-dos . Related: CVE-2026-48512 (`ConvertFromJson` recursion), CVE-2026-48513 (Union deserialization not consistently under depth enforcement).
|
||||
- Default `MaximumObjectGraphDepth`: the sources read do not state it (a figure of 500 was not confirmed).
|
||||
- protobuf: documented unmarshal depth limits Java 100, C++ 100, Go 10000 (plan to lower to 100); the page gives no rationale. https://protobuf.dev/programming-guides/proto-limits/ . CVE-2024-7254: protobuf-java nested SGROUP unknown fields/maps unbounded recursion, StackOverflow, CVSS 4.0 8.7, fixed 3.25.5 / 4.27.5 / 4.28.2. https://cveawg.mitre.org/api/cve/CVE-2024-7254 (CONFLICT: RHEL reports not affected; an OpenCVE page says no fix, against the CVE record's fixed versions).
|
||||
- Go encoding/gob CVE-2022-30635: uncontrolled recursion on ignored fields; fix adds a depth limit of 10,000; fixed in 1.17.12 / 1.18.4. https://go.googlesource.com/go/+/6fa37e98ea4382bf881428ee0c150ce591500eb7 . Go encoding/json nesting constant: not confirmed.
|
||||
- .NET System.Text.Json: `JsonSerializerOptions.MaxDepth` default 0 meaning 64; exceeding throws `JsonException`. https://learn.microsoft.com/en-us/dotnet/api/system.text.json.jsonserializeroptions.maxdepth
|
||||
- Python `json`: docs say the module "does not impose any such limits beyond those of the relevant Python datatypes themselves or the Python interpreter itself"; RecursionError for deep input not mentioned. https://docs.python.org/3/library/json.html . The pure-Python msgpack fallback Unpacker recurses (`# TODO should we eliminate the recursion?`), has no depth option, converts `RecursionError` to `StackError`. https://github.com/msgpack/msgpack-python/blob/main/msgpack/fallback.py
|
||||
- msgpack5 (JS) CVE-2026-107298: no nesting limit, deep input exhausts the decoder stack (title seen only). https://vulert.com/vuln-db/CVE-2026-107298
|
||||
|
||||
## G. CultLib's other runtimes
|
||||
|
||||
- C# reference: `src/GameCult.Caching.MessagePack/CultMessagePackSecurity.cs`: `UntrustedData.WithMaximumObjectGraphDepth(256)` as backstop; the rule is `CultPayloadDepth.Check`. MessagePack package pinned 3.1.7 (`GameCult.Caching.MessagePack.csproj`), the TrySkip fix version. Other C# surfaces use bare `MessagePackSecurity.UntrustedData` (`src/GameCult.Mesh/CultMeshProviderSessionWire.cs:231`, `src/GameCult.Networking/CultNetSchemaMessageSerialization.cs:15`, `src/GameCult.Networking/MessageSerialization.cs:8`).
|
||||
- TypeScript: `@msgpack/msgpack ^3.1.3` (`packages/cultcache-ts/package.json`); decoder iterative with no depth option (section E); encode passes `maxDepth: MAX_PAYLOAD_DEPTH * 2` (`src/document-formatter.ts:21`); `checkPayloadDepth` iterative. node_modules not present, so the installed version was not read.
|
||||
- Python: `msgpack>=1.0` (`packages/cultcache-py/pyproject.toml`); `documents.py:135` and `stores.py:97,384` call `msgpack.unpackb(..., raw=False)`; the C extension has an explicit 1024 stack, so 256-bounded payloads fit; the pure-Python fallback is recursive.
|
||||
- Whether a typed (class-mapped) TS/Py/C# decode layer above these raw decoders recurses per type was not inspected in this pass.
|
||||
462
docs/research/foreign-records-prior-art.md
Normal file
462
docs/research/foreign-records-prior-art.md
Normal file
|
|
@ -0,0 +1,462 @@
|
|||
# Foreign Records: Prior Art Survey
|
||||
|
||||
Facts file for the single-file "foreign records" fork (lay-back versus refusing
|
||||
whole-view writes while holding records the writer does not own). Eyes pass,
|
||||
2026-10-02. Facts and evidence pointers only; no recommendation.
|
||||
|
||||
Verification marks:
|
||||
|
||||
- **[fetched]** the claim was read on the cited page during this pass.
|
||||
- **[search]** the claim came from a search-result summary of the cited page,
|
||||
not a full read.
|
||||
- **[memory]** recalled from the cited source, not re-read in this pass.
|
||||
Treat it as unverified.
|
||||
|
||||
## 0. Our design, for comparison
|
||||
|
||||
Source: `src/GameCult.Caching/Contracts/cultcache-persistence-format.md` (main, 614fd445).
|
||||
|
||||
- Store is `[header, catalog, records]`; the catalog "must embed a catalog entry
|
||||
for every schema referenced by the records it contains" (Embedded Schema Catalog).
|
||||
- The stated purpose of the catalog is to let another implementation "decide
|
||||
whether it can: read directly, soft-migrate with warnings, or refuse the data
|
||||
honestly".
|
||||
- Soft migration lists "persisted schema has extra slots the local reader can
|
||||
safely ignore or preserve" and the warning "field preserved but not surfaced
|
||||
natively". That is slot-level preservation inside a record the reader owns. The
|
||||
contract does not mention records under schema ids the reader does not own;
|
||||
the lay-back ruling lives elsewhere (grep of `src/**/*.md` for "foreign" or
|
||||
"lay-back" found nothing).
|
||||
- Concurrency: "A plain flush and an unconditional commit are last-writer-wins
|
||||
... a single file is replaced by the writer's whole view." "Conditional commit
|
||||
is the only safe multi-process write." C# and Rust implement conditional
|
||||
commit; TypeScript and Python do not yet (Transaction Visibility).
|
||||
|
||||
Granularity note used throughout: most systems below handle unknown *fields
|
||||
inside a record whose type the writer knows*. Our fork is about unknown *whole
|
||||
records* (schema ids) inside a container the writer rewrites. Each entry says
|
||||
which granularity it covers.
|
||||
|
||||
## 1. Serialization formats
|
||||
|
||||
### 1.1 Protocol Buffers: unknown-field preservation
|
||||
|
||||
- **What it does.** Unknown fields are "well-formed protocol buffer serialized
|
||||
data representing fields that the parser does not recognize". Proto3 messages
|
||||
"preserve unknown fields and include them during parsing and in the serialized
|
||||
output, which matches proto2 behavior." [fetched] https://protobuf.dev/programming-guides/proto3/ (Unknown Fields)
|
||||
- **Where preservation fails, per the docs.** Serializing to JSON; iterating
|
||||
fields to populate a new message. Mitigation given: use binary, use
|
||||
`CopyFrom()`/`MergeFrom()`. TextFormat prints unknown fields by number but
|
||||
cannot parse them back. [fetched] same page.
|
||||
- **History.** Proto3 shipped dropping unknown fields. v3.5.0 release notes:
|
||||
"Unknown fields are now preserved in proto3 for most of the language
|
||||
implementations for proto3 by default." C++ and Python offer
|
||||
`DiscardUnknownFields()`, Java a `DiscardUnknownFieldsParser`, for callers who
|
||||
relied on dropping. The release notes give no rationale. [fetched]
|
||||
https://github.com/protocolbuffers/protobuf/releases/tag/v3.5.0
|
||||
- **Why it was restored.** No official rationale document was found. The
|
||||
user-facing request is issue #272 (2015-04-07): "I know that unknown fields
|
||||
have been removed from proto3, but I am trying to get an explanation about why
|
||||
this change was made". The thread body was not readable in this pass. [fetched,
|
||||
partial] https://github.com/protocolbuffers/protobuf/issues/272. Secondary
|
||||
accounts attribute the reversal to pass-through and read-modify-write
|
||||
intermediaries in uncoordinated upgrades. [search]
|
||||
https://github.com/scalapb/ScalaPB/issues/406, https://kmcd.dev/posts/protobuf-unknown-fields/.
|
||||
**The primary reasoning is unverified.**
|
||||
- **Cost and regret.** Go: preservation through `XXX_unrecognized []byte`
|
||||
broke users who compared proto3 messages with `==` or used them as map keys.
|
||||
[search] https://groups.google.com/d/msg/golang-nuts/F5xFHTfwRnY/sPv5nTVXBQAJ.
|
||||
JSON round trips still drop unknown fields; there is an open request to keep
|
||||
them. [search] https://github.com/golang/protobuf/issues/1390. A secondary
|
||||
source flags preserved unknown fields as a way to smuggle unvalidated payloads
|
||||
past validation at trust boundaries. [fetched] https://kmcd.dev/posts/protobuf-unknown-fields/
|
||||
- **Granularity.** Field level, inside a message the reader's code knows.
|
||||
Protobuf does not preserve unknown *message types*; the closest is
|
||||
`google.protobuf.Any` (type URL plus bytes), which carries an opaque typed
|
||||
payload as a declared field. [memory]
|
||||
- **Differs from us.** There is no in-band schema. Unknown bytes are
|
||||
uninterpretable without the newer `.proto`, and only tag and wire type are
|
||||
self-describing. There is no container rewrite or multi-process store
|
||||
concern; protobuf is a message codec.
|
||||
|
||||
### 1.2 Protobuf field-number reuse
|
||||
|
||||
- **Rule.** "Field numbers should never be reused. Never take a field number out
|
||||
of the reserved list for reuse with a new field definition." Listed
|
||||
consequences: "Developer time lost to debugging, A parse/merge error (best case
|
||||
scenario), Leaked PII/SPII, Data corruption." Syntax: `reserved 2, 15, 9 to 11;`
|
||||
and `reserved "foo", "bar";`. [fetched] https://protobuf.dev/programming-guides/proto3/
|
||||
- Best practices: "Never re-use a tag number. It messes up deserialization."
|
||||
Reserve deleted numbers. "Almost never change the type of a field." Renaming
|
||||
breaks JSON and text format because they key on names. [fetched]
|
||||
https://protobuf.dev/best-practices/dos-donts/
|
||||
- Kleppmann (2012): "you must never reuse the tag number for another field in
|
||||
future, because you may still have data stored that uses that tag for the field
|
||||
you deleted". [fetched] https://martin.kleppmann.com/2012/12/05/schema-evolution-in-avro-protocol-buffers-thrift.html
|
||||
- **Named public incidents:** none found in this pass. The docs' consequence
|
||||
list is the strongest primary evidence; blog posts repeat it. **Unverified.**
|
||||
- **Differs from us.** Our `schemaId` is a content hash of the canonical slot
|
||||
schema, so changing slot meaning changes the id. The reuse hazard moves from
|
||||
"number collides" to "a record under an old id is carried, or reinterpreted,
|
||||
after an undeclared rename".
|
||||
|
||||
### 1.3 Avro and schema registries
|
||||
|
||||
- **Resolution.** The reader needs the writer's schema. Fields in the writer
|
||||
schema but not the reader's are ignored. Reader fields missing from the writer
|
||||
take the reader default, or raise an error when there is no default. Aliases
|
||||
map renames. [fetched] https://avro.apache.org/docs/1.11.1/specification/ (Schema Resolution)
|
||||
- **Object Container Files** carry the schema once in the header (`avro.schema`,
|
||||
required). One file has one writer schema. [fetched] same page.
|
||||
- **Kleppmann (2012):** Avro needs "the exact same version of the schema as the
|
||||
writer of the data", so you either "annotate each record with its schema
|
||||
version" or use "a schema registry". [fetched] blog above.
|
||||
- **Confluent wire format:** byte 0 is the magic byte (0), bytes 1 to 4 are the
|
||||
big-endian schema id; the deserializer fetches the writer schema by id.
|
||||
[fetched] https://docs.confluent.io/platform/current/schema-registry/fundamentals/serdes-develop/index.html
|
||||
- **Compatibility modes:** BACKWARD (the default), FORWARD, FULL, their
|
||||
`_TRANSITIVE` forms, and NONE. BACKWARD is the default "so that you can rewind
|
||||
consumers to the beginning of the topic". Upgrade order follows the mode:
|
||||
consumers first for BACKWARD, producers first for FORWARD. [fetched]
|
||||
https://docs.confluent.io/platform/current/schema-registry/fundamentals/schema-evolution.html
|
||||
- **Failure mode.** Resolution projects writer data onto the reader schema, so
|
||||
writer-only fields are gone from the decoded object. A read-modify-write by an
|
||||
older reader loses them unless the application keeps the writer record.
|
||||
[inference from the spec; no Avro doc states it as a warning]
|
||||
- **Differs from us.** Kafka records are immutable log entries, so consumers
|
||||
never rewrite the producer's records. A container file is written once by one
|
||||
writer. Neither case has whole-file rewrite by several processes.
|
||||
|
||||
### 1.4 Thrift
|
||||
|
||||
- Generated readers switch on field id and call
|
||||
`TProtocolUtil.skip(iprot, schemeField.type)` in the default case: unknown
|
||||
fields are skipped. [search; generated-code pattern] Kleppmann (2012) says the
|
||||
same of protobuf and Thrift: the parser "can figure out how many bytes it needs
|
||||
to skip". [fetched]
|
||||
- **Conflict.** "Thrift: The Missing Guide" says unknown fields "are not
|
||||
discarded, and if the message is later serialized, the unknown fields are
|
||||
serialized along with it". That text reads as copied from protobuf docs.
|
||||
[fetched] https://diwakergupta.github.io/thrift-missing-guide/. Apache Thrift's
|
||||
generated Java skips without retaining. **Retention is unverified and likely
|
||||
false for stock Apache Thrift.**
|
||||
- Rules: never change numeric tags; new fields optional; prefix removed fields
|
||||
`OBSOLETE_`. [fetched] Missing Guide.
|
||||
|
||||
### 1.5 Cap'n Proto
|
||||
|
||||
- Field ordinals are append-only: "as long as each new member's number is larger
|
||||
than all previous members"; "You cannot change a field, method, or enumerant's
|
||||
number." [fetched] https://capnproto.org/language.html
|
||||
- Unknown fields survive a copy: "If you copy the struct from one message to
|
||||
another (e.g. by calling a set() method on a parent object), the extra fields
|
||||
will be preserved." Caveat: "copying a struct value from another message into
|
||||
an element of a list will truncate the value". [fetched] https://capnproto.org/cxx.html
|
||||
- The wire format carries just enough structure (struct or list, sizes) to copy
|
||||
an object recursively without its schema. [search]
|
||||
https://capnproto.org/encoding.html. Preservation is a property of the encoding,
|
||||
not of a per-type rule.
|
||||
- **Differs from us.** The copy is opaque; nothing is reinterpreted. There is no
|
||||
catalog and no store.
|
||||
|
||||
### 1.6 FlatBuffers
|
||||
|
||||
- Add new fields at the end; never remove one, mark it `deprecated` instead (no
|
||||
accessors are generated); explicit `id` attributes relax ordering. Old readers
|
||||
ignore unknown fields. [search] https://flatbuffers.dev/evolution/
|
||||
- The object API (unpack, mutate, pack) builds a fresh buffer from native
|
||||
fields. Whether unknown fields survive that round trip: **not verified in
|
||||
this pass** [memory: they do not].
|
||||
- Known defect: C++ object API with deprecated fields generated non-compiling
|
||||
code. [search] https://github.com/google/flatbuffers/issues/5186
|
||||
|
||||
### 1.7 Microsoft Bond
|
||||
|
||||
- `bonded<T>` defers deserialization and holds a reference to the serialized
|
||||
form. "Using bonded<Response> allows the intermediary to aggregate responses,
|
||||
preserving their full content, even though schema of Response is not known
|
||||
when the aggregator is built." Transcoding through a bonded value preserves
|
||||
fields not in `T`. [fetched] https://microsoft.github.io/bond/manual/bond_cpp.html
|
||||
- Untagged protocols (Simple Binary) "serialize only data and thus require that
|
||||
consumers know the payload schema via some out-of-band mechanism"; Bond also
|
||||
has runtime schemas (`SchemaDef`) for that. [fetched; SchemaDef from memory]
|
||||
- Changing ordinals is a breaking change. [fetched]
|
||||
- **Note.** Bond's preservation is an explicit opt-in wrapper type at the
|
||||
declared pass-through point, not default retention of everything.
|
||||
|
||||
### 1.8 MessagePack-based schema systems
|
||||
|
||||
- MessagePack itself has no schema. MessagePack-CSharp (`[Key(n)]` int keys, the
|
||||
basis of our slot layout) has no documented unknown-key or extension-data
|
||||
retention for typed objects. A search found no such feature and no issue
|
||||
requesting it. **Unverified absence.**
|
||||
https://github.com/MessagePack-CSharp/MessagePack-CSharp
|
||||
- Comparable opt-in field-level retention in other ecosystems:
|
||||
Newtonsoft.Json and System.Text.Json `[JsonExtensionData]` capture unmapped
|
||||
properties into a dictionary and write them back; serde `#[serde(flatten)]` into
|
||||
a map does the same, and is incompatible with `deny_unknown_fields`. [search]
|
||||
https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/migrate-from-newtonsoft,
|
||||
https://serde.rs/attr-flatten.html. All are field level and opt in per type.
|
||||
- **FIDL (Fuchsia), RFC-0033:** messages with unknown fields "MUST be validated
|
||||
and parsed successfully"; the default is `flexible` (unknown values allowed and
|
||||
exposed), and the `strict` keyword makes unknown fields invalid. Unknown
|
||||
handles must be closed by default. The RFC frames strictness as a security tool
|
||||
for protocols where misinterpreting new data is dangerous. [fetched]
|
||||
https://fuchsia.dev/fuchsia-src/contribute/governance/rfcs/0033_handling_unknown_fields_strictness
|
||||
|
||||
## 2. Embedded stores and document databases
|
||||
|
||||
### 2.1 SQLite
|
||||
|
||||
- **Unknown tables.** The writer modifies pages through the B-tree and rollback
|
||||
or WAL journal. Tables a program never touches are never rewritten, so there is
|
||||
no rule about them. [memory; consistent with the file format doc]
|
||||
- **Unknown schema syntax.** A library older than 3.31.0 opening a schema with
|
||||
generated columns "will perceive the generated column syntax as an error and
|
||||
will report that the database schema is corrupt". Older versions can read and
|
||||
write newer files "as long as the database schema does not contain features
|
||||
... not understood by the earlier version". [search] https://sqlite.org/gencol.html.
|
||||
The whole database is refused, not just the table.
|
||||
- **File format versions.** Write version > 2: "the database file must be treated
|
||||
as read-only". Read version > 2: "that database cannot be read or written".
|
||||
[fetched] https://www.sqlite.org/fileformat2.html (offsets 18 and 19). This is
|
||||
a format-level read-only fallback for content the library cannot safely write.
|
||||
- **Schema change across connections.** The schema cookie (offset 40) is bumped
|
||||
on every schema change. A prepared statement checks it and reprepares or fails
|
||||
with `SQLITE_SCHEMA`. [fetched] same page.
|
||||
- `user_version` (offset 60) and `application_id` (offset 68) are application
|
||||
owned; SQLite does not use them. [fetched]
|
||||
- **Whole-file rewrite.** SQLite's own comparison: custom and wrapped
|
||||
pile-of-files formats "usually require a rewrite of the entire document in
|
||||
order to change a single byte", and application concurrency logic for them is
|
||||
"a notorious bug-magnet". [fetched] https://www.sqlite.org/appfileformat.html
|
||||
- **Differs from us.** The schema is SQL text in `sqlite_schema`, not a typed
|
||||
slot catalog. Writes are partial and in place, and there is one implementation
|
||||
rather than five.
|
||||
|
||||
### 2.2 LMDB
|
||||
|
||||
- Opaque byte keys and values, no schema; named sub-databases. Copy-on-write
|
||||
B+tree with MVCC. One writer at a time, serialized by a mutex in the lock file;
|
||||
readers do not block the writer and the writer does not block readers;
|
||||
several processes may open one environment. [search; lmdb.tech/doc was not
|
||||
reachable over TLS in this pass] https://en.wikipedia.org/wiki/Lightning_Memory-Mapped_Database,
|
||||
https://lmdb.readthedocs.io/
|
||||
- `MDB_INCOMPATIBLE`: an operation does not match a database's flags (for
|
||||
example dupsort), or "the database type changed". [search]
|
||||
- **Differs from us.** There are no types, so "foreign" is not a concept;
|
||||
untouched keys are never rewritten.
|
||||
|
||||
### 2.3 Core Data (Apple)
|
||||
|
||||
- **Model mismatch is refused.** "The model used to open the store is
|
||||
incompatible with the one used to create the store" (Cocoa error 134100)
|
||||
unless a migration runs: lightweight (inferred mapping, using
|
||||
`NSMigratePersistentStoresAutomaticallyOption` and
|
||||
`NSInferMappingModelAutomaticallyOption`) or custom/staged. [search]
|
||||
https://developer.apple.com/forums/thread/100639
|
||||
- Store metadata holds per-entity version hashes (`NSStoreModelVersionHashes`).
|
||||
`isConfiguration(withName:compatibleWithStoreMetadata:)` compares them with
|
||||
the model. [search]
|
||||
https://developer.apple.com/documentation/coredata/nsmanagedobjectmodel/isconfiguration(withname:compatiblewithstoremetadata:)
|
||||
- **Atomic stores (XML, binary) are the closest analogue to our single file.**
|
||||
They keep the whole object graph in memory and save the whole file: "the old
|
||||
file is not deleted until the new one has been successfully written."
|
||||
[fetched] https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/CoreData/PersistentStoreFeatures.html.
|
||||
Combined with the refusal above, an atomic store is never rewritten by a model
|
||||
that does not cover every entity in it. The page says nothing on multi-process
|
||||
access to atomic stores. [fetched: absence]
|
||||
- **Differs from us.** Single runtime, entity-hash catalog in metadata, a
|
||||
migration-or-refuse gate at open. No foreign entity is ever carried.
|
||||
|
||||
### 2.4 Realm
|
||||
|
||||
- Opening with a changed schema requires a higher `schemaVersion`, plus a
|
||||
`migrationBlock` where needed; otherwise "Migration is required". Added and
|
||||
removed properties are applied to the on-disk schema automatically on
|
||||
migration. [search] https://github.com/realm/realm-js/issues/4752,
|
||||
https://realm.netlify.app/docs/swift/latest/
|
||||
- A changelog entry allows opening old frozen versions "with a schema that
|
||||
contains additional classes, but not additional properties". [search]
|
||||
https://github.com/realm/realm-core/releases?page=5
|
||||
- Whether a Realm opened with a class *subset* keeps the other tables untouched:
|
||||
**not verified** [memory: the tables are kept, since Realm writes in place by
|
||||
table and does not rewrite the whole file].
|
||||
- Realm file-format upgrades are one-way. [memory]
|
||||
|
||||
### 2.5 CouchDB and PouchDB
|
||||
|
||||
- `PUT /{db}/{docid}` writes a new revision of the whole document; there is no
|
||||
field merge, and omitted fields are gone in the new revision. A missing or
|
||||
stale `_rev` returns `409 Conflict`: "specified revision is not latest for
|
||||
target document". The revision may be given in the body, as `rev`, or in
|
||||
`If-Match`. [fetched] https://docs.couchdb.org/en/stable/api/document/common.html
|
||||
- Under replication, conflicting revisions are all kept; one deterministic
|
||||
winner is chosen and the others are marked `_conflicts`; CouchDB does not merge.
|
||||
[search] https://docs.couchdb.org/en/stable/replication/conflicts.html
|
||||
- There is no schema; unknown fields survive only if the client writes them
|
||||
back. Document-mapper layers drop them: Mongoose's `strict` option "ensures
|
||||
that values passed to our model constructor that were not specified in our
|
||||
schema do not get saved to the db", and is "enabled by default". [fetched]
|
||||
https://mongoosejs.com/docs/guide.html (MongoDB, cited as the same pattern).
|
||||
- **RxDB** (on PouchDB or other storage): any schema `version` > 0 requires
|
||||
`migrationStrategies` for each step; a strategy returning `null` deletes the
|
||||
document; writes during a running migration fail with `COL25`; in multi-tab
|
||||
setups "exactly one tab is running a migration of a collection". [fetched]
|
||||
https://rxdb.info/migration-schema.html. Opening storage written by a newer
|
||||
RxDB major is refused ("Cannot open database state with newer RxDB version").
|
||||
[search] https://github.com/pubkey/rxdb/issues/5836
|
||||
- **Differs from us.** The per-document `_rev` gives optimistic concurrency at
|
||||
record granularity, and documents are never rewritten as a side effect of
|
||||
writing another.
|
||||
|
||||
### 2.6 IndexedDB
|
||||
|
||||
- No field schema: values are structured clones, stored by value. Schema is
|
||||
object stores and indexes, versioned by an integer. [fetched] https://www.w3.org/TR/IndexedDB/
|
||||
- Opening with a higher version fires `upgradeneeded` inside a versionchange
|
||||
transaction. Opening with a *lower* version than the stored one fails with
|
||||
`VersionError`: "An attempt was made to open a database using a lower version
|
||||
than the existing version." Older code is refused outright. [fetched] same spec.
|
||||
- Other open connections receive `versionchange`; if they stay open the upgrader
|
||||
gets `blocked`. [fetched] same spec and
|
||||
https://developer.mozilla.org/en-US/docs/Web/API/IDBOpenDBRequest/blocked_event
|
||||
- **Differs from us.** The browser engine is the single writer implementation
|
||||
and the schema has one integer owner per database.
|
||||
|
||||
### 2.7 Whole-file rewrite while preserving unknown content
|
||||
|
||||
Systems found that rewrite a container while keeping parts they do not
|
||||
understand:
|
||||
|
||||
- **Automerge binary format.** Programs that edit documents must "maintain all
|
||||
columns, even those that they don't understand the meaning of" and write null
|
||||
into unknown columns for new rows. Implementations "must preserve operations
|
||||
containing actions they don't support". Unknown value type codes: "MUST read and
|
||||
store the type code and `length` bytes". Changes are SHA-256 hashed over their
|
||||
binary form, so byte preservation is required for hash integrity. [fetched]
|
||||
https://automerge.org/automerge-binary-format-spec/. The unit carried is an
|
||||
immutable, content-addressed change; nothing preserved is ever re-decided by
|
||||
the carrier.
|
||||
- **Core Data atomic stores** rewrite the whole file but refuse to open under an
|
||||
incompatible model (2.3), so they never carry unknown entities.
|
||||
- No system was found that rewrites a whole mutable file while carrying
|
||||
mutable records of unknown types that other writers may change concurrently.
|
||||
**Absence of evidence, not a verified negative.**
|
||||
|
||||
## 3. Literature
|
||||
|
||||
- **Kleppmann, *Designing Data-Intensive Applications* (1st ed., O'Reilly 2017),
|
||||
ch. 4 "Encoding and Evolution", section "Dataflow Through Databases".** [memory,
|
||||
not re-read] The section says an older version of code may read, update and
|
||||
write back a record written by newer code, and newer fields can be lost unless
|
||||
the old code keeps unknown fields. Figure 4-7 shows this. The section contains
|
||||
the line "data outlives code" [search; confirmed in secondary notes
|
||||
https://gist.github.com/bcherny/b870a60d1650973df7e400c8603ac76d]. It also says
|
||||
rewriting data into a new schema is possible but expensive, so most databases
|
||||
avoid it. **The exact wording is unverified.**
|
||||
- **Scherzinger, Klettke, Störl, "Managing Schema Evolution in NoSQL Data
|
||||
Stores", DBPL 2013.** Contrasts eager migration with *lazy* migration (migrate
|
||||
on read or touch) for schema-less stores whose data grows heterogeneous.
|
||||
[search] https://arxiv.org/abs/1308.0514
|
||||
- **Ringlstetter, Scherzinger, Bissyandé, "Data model evolution using
|
||||
object-NoSQL mappers: folklore or state-of-the-art?", BIGDSE@ICSE 2016,
|
||||
pp. 33-36.** Mapper evolution annotations (rename, remove, transform on load)
|
||||
are used on GitHub, but mostly for tasks other than evolving the data model.
|
||||
[search] https://dblp.org/rec/conf/icse/RinglstetterSB16.html
|
||||
- **Scherzinger and Sidortschuck, "An Empirical Study on the Design and Evolution
|
||||
of NoSQL Database Schemas", ER 2020.** [search, not read]
|
||||
https://arxiv.org/pdf/2003.00054
|
||||
- **Bancilhon and Spyratos, "Update semantics of relational views", ACM TODS
|
||||
6(4), 1981, pp. 557-575.** A view update is translated by holding a chosen
|
||||
*complement* constant; a complete set of view updates has a translator iff it
|
||||
is translatable under constant complement. [search]
|
||||
https://dl.acm.org/doi/10.1145/319628.319634. Mapping (this survey's framing,
|
||||
not the paper's): a writer's owned records are a view of the store, the foreign
|
||||
records are the complement, and lay-back is constant-complement translation.
|
||||
- **Foster, Greenwald, Moore, Pierce, Schmitt, "Combinators for bidirectional tree
|
||||
transformations", POPL 2005 / TOPLAS 2007.** A lens is `get: S -> V` and
|
||||
`put: V x S -> S`. Laws: GetPut, `put(get(s), s) = s`; PutGet,
|
||||
`get(put(v, s)) = v`; PutPut is the stronger optional law. `put` takes the
|
||||
source `s` as an argument, so the complement is restored from whatever `s` is
|
||||
supplied. [search for the paper; the law statements are from memory, and one
|
||||
search summary had GetPut and PutGet swapped]
|
||||
https://www.cis.upenn.edu/~bcpierce/papers/lenses-toplas-final.pdf
|
||||
- **Litt, van Hardenberg, Henry, "Project Cambria" (Ink & Switch, Oct 2020).**
|
||||
Bidirectional lenses between schema versions, arranged as a graph. In
|
||||
Cambria-Automerge every write is tagged with its writer's schema and translated
|
||||
at read time, so "old changes can be evolved using lenses that didn't even
|
||||
exist at the time of the original change". Lenses travel inside the document.
|
||||
Stated limits: lossy conversions (scalar to array), one-way changes
|
||||
(split/merge), no external lookups, untested performance. "There are limits to
|
||||
interoperability." [fetched] https://www.inkandswitch.com/cambria/
|
||||
- **Local-first and CRDT, Automerge:** see 2.7. Unknown ops, columns and value
|
||||
types from newer peers are preserved byte for byte and are immutable once
|
||||
written. [fetched]
|
||||
|
||||
## 4. Concurrency facts for whole-file rewrite
|
||||
|
||||
- **Last-writer-wins on whole replace** loses a concurrent writer's changes
|
||||
unless the write is conditional. Our contract already says this (section 0).
|
||||
- **HTTP optimistic concurrency.** RFC 9110 §13.1.1 If-Match exists to prevent
|
||||
the "lost update" problem; a failed precondition returns 412 Precondition
|
||||
Failed (§15.5.13). [memory; the page fetch truncated before those sections]
|
||||
https://www.rfc-editor.org/rfc/rfc9110.html#section-13.1.1
|
||||
- **Per-record CAS:** CouchDB `_rev`, 409 (2.5).
|
||||
- **Git ref update:** `git update-ref <ref> <new> <old>` stores the new value
|
||||
"after verifying that the current value of the <ref> matches <old-oid>".
|
||||
Transactions lock every ref (`.lock` files) at `prepare`; "If all <ref>s can be
|
||||
locked with matching <old-oid>s simultaneously, all modifications are
|
||||
performed. Otherwise, no modifications are performed." [fetched]
|
||||
https://git-scm.com/docs/git-update-ref. The pattern: take an exclusive lock
|
||||
file, compare the old value under the lock, write, rename into place.
|
||||
- **SQLite** serializes writers by file lock (rollback) or WAL write lock;
|
||||
schema-cookie checks catch schema drift between prepare and run (2.1).
|
||||
- **LMDB:** single writer mutex across processes, MVCC readers (2.2).
|
||||
- **IndexedDB:** schema change is an exclusive versionchange transaction that
|
||||
waits on other connections (2.6).
|
||||
- **RxDB:** one migrating tab, writes refused during migration (2.5).
|
||||
- **Crash consistency of temp-plus-rename.** Pillai et al., "All File Systems Are
|
||||
Not Created Equal: On the Complexity of Crafting Crash-Consistent
|
||||
Applications", OSDI 2014. The ALICE tool found 60 crash vulnerabilities across
|
||||
11 widely used applications; persistence properties, including how rename
|
||||
orders against data writes, vary across six Linux file systems. [search]
|
||||
https://research.cs.wisc.edu/adsl/Publications/alice-osdi14.pdf. Whether
|
||||
`fsync` of the temp file and its directory is needed for durability of the
|
||||
rename: [memory: yes on Linux ext4 and others]. Windows `MoveFileEx` with
|
||||
`MOVEFILE_REPLACE_EXISTING` and `ReplaceFile` atomicity guarantees: **not
|
||||
verified in this pass.**
|
||||
|
||||
## 5. Cross-cutting facts, as observed (not conclusions)
|
||||
|
||||
- Every system found that preserves unknown data does so at *field* level
|
||||
inside a record whose type the code owns (protobuf, Cap'n Proto, Bond opt-in,
|
||||
JSON extension data, serde flatten), or as *immutable content-addressed*
|
||||
units (Automerge changes).
|
||||
- Systems that hold several record types in one store either rewrite only what
|
||||
they touch (SQLite, LMDB, Realm [unverified], CouchDB, IndexedDB), or rewrite
|
||||
the whole file and refuse a model that does not cover the file (Core Data
|
||||
atomic stores).
|
||||
- Systems where older code meets a newer schema at open time do one of:
|
||||
refuse to open (IndexedDB `VersionError`, Core Data 134100, RxDB newer-major,
|
||||
SQLite unknown schema syntax), go read-only (SQLite write version > 2), or
|
||||
require a migration before any write (Realm, RxDB, Core Data).
|
||||
- Protobuf moved from dropping to preserving (3.5). Its documented residual
|
||||
losses are in conversion paths (JSON, field-by-field copy), and Go's
|
||||
preservation broke message comparability.
|
||||
- FIDL made preserve-and-expose the default and added `strict` as an opt-in
|
||||
refusal, justified on security grounds.
|
||||
|
||||
## Not verified in this pass
|
||||
|
||||
- Primary rationale for restoring proto3 unknown fields in 3.5.
|
||||
- Any named incident caused by protobuf field-number reuse.
|
||||
- Stock Apache Thrift retention of unknown fields (the Missing Guide says yes,
|
||||
the generated-code pattern says skip).
|
||||
- FlatBuffers object-API round trip of unknown fields.
|
||||
- MessagePack-CSharp unknown-key retention (absence).
|
||||
- Realm behaviour opening with a class subset.
|
||||
- Exact DDIA wording and figure number.
|
||||
- LMDB primary docs (TLS failure); RFC 9110 section text.
|
||||
- Windows rename and replace atomicity semantics.
|
||||
291
docs/research/integration-native-noise-domain.md
Normal file
291
docs/research/integration-native-noise-domain.md
Normal file
|
|
@ -0,0 +1,291 @@
|
|||
# An integration-native volumetric noise domain: probe
|
||||
|
||||
Campaign `cultmath-tapes`, Imagination probe, 2026-10-03, under ruling
|
||||
`cultmath-tapes:ruling:integration-native-noise-domain`. This is research under the
|
||||
parked tape target. It has no spec, no shipped-field change and no committed code.
|
||||
|
||||
It follows `analytic-integration-feasibility.md`, which found that exact noise
|
||||
integrals are cheap but that the shipped densities are nonlinear in the noise. The
|
||||
question here is the reverse one. Suppose a domain is designed so that span
|
||||
integration holds by construction. Does it buy more visual detail per unit cost
|
||||
than the shipped fields?
|
||||
|
||||
On the operator's instruction (relayed by Self), the reference is physical, not
|
||||
Aetheria's tuned compositing:
|
||||
- transmittance is Beer–Lambert, `T = exp(-τ)`;
|
||||
- the images use single scattering with Henyey–Greenstein `g = 0.6` and albedo 1;
|
||||
- both fields are integrated the same way.
|
||||
|
||||
The shipped look is a comparison, not a target.
|
||||
|
||||
## Verdict
|
||||
|
||||
**On the void, yes, by a wide margin. On the wells, modestly.** At or below the
|
||||
shipped march's cost, the integration-native field carries much more resolvable
|
||||
detail, and it is exact. The catches:
|
||||
- The look changes character. The default cascade reads as fibres or brush strokes,
|
||||
not as soft cloud.
|
||||
- The cost is traversal, not integration.
|
||||
- The field cannot be ray-marched at all. Every consumer, shadow rays included,
|
||||
must use the exact path.
|
||||
|
||||
Headline numbers, 512 x 256, single-threaded C# on Yggdrasil:
|
||||
|
||||
| Void, transmittance image | Cost per pixel | vs shipped march | msf (grad²/var) | Power above 1/8 cycle/px | Pixels with \|∇T\| > 0.05 |
|
||||
|---|---|---|---|---|---|
|
||||
| Shipped field, converged reference (595 samples) | n/a | n/a | 0.0111 | 0.20% | 0.00% |
|
||||
| Shipped march (11.4 samples) | 28.9 µs (44 snoise3) | 1.00x | 0.0178 | 0.71% | 0.00% |
|
||||
| Integration-native, 2 levels, exact | 13.9 µs | **0.48x** | **0.0755** | **2.95%** | 41.9% |
|
||||
| Integration-native, 3 levels, exact | 35.7 µs | 1.24x | 0.125 | 9.15% | 54.7% |
|
||||
| Integration-native, 6 levels (LOD stops at 4 to 5), exact | 74.2 µs | 2.57x | 0.159 | 12.5% | 60.9% |
|
||||
|
||||
- **Mean density is matched.**
|
||||
- The integration-native field places mass from the shipped field's noise-averaged
|
||||
density.
|
||||
- Mean window optical depth is 1.62 to 1.74 against the shipped 1.81.
|
||||
- Mean T is 0.25 to 0.40 against 0.17. The difference comes from intermittency:
|
||||
the image std is 0.29 against 0.05, at a near-equal mean.
|
||||
- **msf is normalised by variance.** It measures spatial frequency, not contrast.
|
||||
- **Single-scattering images, void.** The images are 256 x 128 with a point light at
|
||||
the sun, and both are tonemapped with the same exposure. The shipped image's msf
|
||||
is 0.0023, with 0.22% of power above 1/8. The integration-native image's msf is
|
||||
0.101, with 16.9% of power above 1/8.
|
||||
- **Wells.**
|
||||
- Transmittance is a near-opaque silhouette for both fields: equal msf (0.011),
|
||||
so it carries no signal.
|
||||
- Single scattering at 6 levels (1.20x the march cost):
|
||||
- msf is 0.073 against 0.069;
|
||||
- power above 1/8 is 10.1% against 7.0%;
|
||||
- the edge fraction is 16.7% against 9.5%.
|
||||
- At 4 levels the cost is 0.77x the march.
|
||||
|
||||
**Exactness.** Against a converged march of the same field at 0.02 world:
|
||||
- The relative τ error is a median 3e-5 and a maximum of 1.0e-4 on the void, and a
|
||||
median 1e-5 and a maximum of 1.0e-4 on the wells.
|
||||
- The binned gather against brute force over all roots differs by at most 1.3e-15.
|
||||
- The shipped march against its own converged reference: |ΔT| is a median 0.0055
|
||||
(p90 0.013) on the void and a median 0.0006 (max 0.83 on grazing rays) on the
|
||||
wells.
|
||||
|
||||
**The detail is only reachable by integration.**
|
||||
- Marching the same integration-native field at the shipped step gives a void |ΔT|
|
||||
median of 0.14, a p90 of 0.48 and a maximum of 0.83.
|
||||
- A field this detailed is beyond the march at its step. That is the operator's
|
||||
premise, measured: the shipped fields' softness fits the regime that renders them.
|
||||
|
||||
## The primitive set
|
||||
|
||||
The primitive set has one design rule: nonlinearity lives in kernel placement, and
|
||||
linearity lives in the integration. The density is a sum of nonnegative,
|
||||
compact-support kernels. Everything nonlinear is evaluated once per kernel, at its
|
||||
centre, and never per sample. That covers envelopes, clamps, `pow` profiles, the
|
||||
flow warp and placement.
|
||||
|
||||
### Bases (closed-form line integral over a segment)
|
||||
|
||||
| Primitive | Why it integrates | Cost per span (measured unless marked) |
|
||||
|---|---|---|
|
||||
| Compact polynomial ellipsoid kernel, `(1 − u)^k` with `u = \|A⁻¹(x − μ)\|²` | On a line, u is quadratic in t, so the kernel is a polynomial of degree 2k between the two roots of `u = 1`, which are closed form. Same algebra as the simplex lattice integral in the first probe | k = 0: 5.5 to 7.4 ns; k = 1: 8 to 9.5 ns; k = 2: 11.7 ns. About 0.01 to 0.02 snoise3 (snoise3 is 610 to 650 ns in C#) |
|
||||
| Truncated Gaussian ellipsoid, `exp(−κu)` on `u ≤ 1` | `exp` of a quadratic is a Gaussian in t, giving an erf difference. Truncation only clips the limits | 32 to 36 ns with A&S 7.1.26 erf (error ≤ 1.5e-7), about 0.05 snoise3 |
|
||||
| k = 0 ellipsoid (constant density) | Chord length; this is EVER's primitive (Mai et al. 2024 [memory]) | 5.5 ns |
|
||||
| Gabor kernel (Gaussian × cosine) | Complex erf, any affine transform (Gabor Fields 2026, eq. 9 [fetched in the prior-art file]) | Not probed. Up to 16 Taylor terms [paper] |
|
||||
| Cosine sum (Balint 2019) | Integral is a sum of sines | Not probed. Two noise-sized evaluations per segment [paper]. Signed, so it needs an offset; low contrast |
|
||||
| Simplex lattice (CultMath `snoise`) | First probe: degree 9 per lattice point | 0.16 snoise3 per point, 3.44 points per noise unit. Signed: only usable where density is affine in it |
|
||||
|
||||
### Warps
|
||||
|
||||
| Warp | Why it stays exact | Cost |
|
||||
|---|---|---|
|
||||
| Per-kernel affine warp: centre moved by `f(μ)·s`, shape by `(I + J·s)` | An affine image of an ellipsoid is an ellipsoid, so the ray stays straight and the kernel stays closed form. The warp *defines* the field, so there is no approximation error. It is evaluated once per root per frame (7 flow evaluations with the Jacobian) | Frame build 39 ms (void, 2540 roots) and 57 ms (wells, 16947 roots), or 19 and 27 ns per 1080p pixel amortised |
|
||||
| Children inherit the parent's affine frame | The cascade has descendants that are exact affine images, so the warp is evaluated only at the roots | One 3x3 product per child, from a table |
|
||||
| Not allowed | A per-point warp `x + w(x)` inside a span: the warped ray curves, which was the first probe's problem | n/a |
|
||||
|
||||
### Transfer and placement
|
||||
|
||||
| Rule | Status |
|
||||
|---|---|
|
||||
| Any function of the kernel centre: the shipped clamp, `pow`, the smoothstep fade, the noise-averaged density `E_n[ρ(x, n)]` from 16 empirical noise quantiles, through a 1D LUT over d (void) or s (wells) | Exact by construction, at one lookup per kernel |
|
||||
| Affine transfer of the sum (`a + b Σ K_i`) | Exact |
|
||||
| Any 1D function of an *affine* coordinate, `∫ f(a + bt) dt = ΔF / b` (pre-integration, Engel 2001) | Exact [derivation, not probed]: height fog `exp(−y/h)` and ramps in y |
|
||||
| Polynomial or exp of a *quadric* coordinate; an indicator or clamp of a quadric (chord through roots) | Exact [derivation, not probed]: spherical shells and paraboloid bowls as envelopes |
|
||||
| Product of the sum with a polynomial envelope in t | Exact, polynomial times polynomial [derivation, not probed] |
|
||||
| Forbidden inside a span: `f(Σ K_i)` for nonlinear f, `max`/`min` of fields, a clamp of a signed sum, or noise displacing an envelope's argument | These are exactly what broke the first probe |
|
||||
|
||||
### Composition: the mass-conserving multiplicative cascade
|
||||
|
||||
- **Roots** sit on a jittered grid: spacing H0 = 30 world on the void and 40 on the
|
||||
wells, one root per cell.
|
||||
- Mass is `P(μ)·H0³`, so the mean density equals the shipped noise-averaged
|
||||
density.
|
||||
- The ellipsoid is elongated along the flow direction projected on the shell or
|
||||
fog layer (aspect 1.3 to 2.4), with ±0.6 rad of jitter, and flattened along the
|
||||
normal (×0.5 void, ×0.4 wells).
|
||||
- There are two copies per root, at the shipped two-phase shifts with weights w0
|
||||
and 1 − w0. Time animation is therefore the shipped crossfade, exact under
|
||||
summation.
|
||||
- **Children.** Each node keeps 25% of its mass and gives 75% to Nc = 5 children.
|
||||
- Child weights are `u²·P(child)/P(parent)`, normalised. The `u²` makes the cascade
|
||||
intermittent; the P ratio sharpens it toward the envelope.
|
||||
- A child is scale 0.4, with aspect up to 1.6 and ±0.6 rad of rotation.
|
||||
- Children sit along the parent's major axis: offset 0.6 along it, 0.21 across.
|
||||
- All of this comes from a 256-entry table indexed by hash. A descendant bound of
|
||||
1.77 times the ellipsoid holds the subtree, so the parent is a BVH node.
|
||||
- **LOD.** A node is a leaf when its children would be smaller than 0.5 × the pixel
|
||||
footprint at that depth. It then keeps its full mass. Because the cascade conserves
|
||||
mass, truncation is a mean-preserving prefilter: the expectation step of the first
|
||||
probe, exact here instead of approximate.
|
||||
- **Gather.**
|
||||
- Roots are binned by their subtree AABB into a hash grid of H0 cells.
|
||||
- The ray walks the grid with Amanatides–Woo DDA and mailboxing, clipped to the
|
||||
shipped active windows, so both fields integrate the same span.
|
||||
- It exits early once Στ ≥ 7, which is valid because every term is nonnegative.
|
||||
|
||||
## "Juice" under these constraints
|
||||
|
||||
| Effect | Mechanism here | Measured or prior art |
|
||||
|---|---|---|
|
||||
| Filaments, wisps | Anisotropic children chained along the parent's major axis, which follows the flow | Visible in `void-T-IN-L6.png` as streaks along the flow. Gabor Fields uses anisotropic Gabor kernels for orientation-selective detail [fetched] |
|
||||
| Sharp edges | Low-order kernels: k = 1 is the default, k = 0 gives hard ellipsoids | k = 0 (`L6-hard`) changes msf by −9% on the void. Edges come from kernel boundaries, not clamps |
|
||||
| Voids | Regions with no kernel mass are exactly zero and are skipped by the gather at no cost | Structural |
|
||||
| Turbulent intermittency | Random multiplicative cascade, the p-model of turbulent dissipation (Meneveau & Sreenivasan 1987 [memory]); clustered kernels, as in a Neyman–Scott process [memory] | Image std 0.29 against 0.05 at near-equal mean OD |
|
||||
| Flow and animation | Per-kernel warp at the shipped flow and phases. Alternatives are Lagrangian advection of kernel centres with lifetimes (advected textures, Neyret 2003 [memory]) and Gabor phase for oscillatory detail (flow noise, Perlin & Neyret 2001 [memory]) | Only the two-phase crossfade was measured |
|
||||
| Fine detail riding on structure | Children exist only inside parents, so detail appears only where matter is. This is Schneider's erosion idea (2015 [fetched]) without the per-sample clamp | Structural |
|
||||
|
||||
Wavelet turbulence (Kim et al. 2008 [memory]) and curl noise (Bridson 2007 [memory])
|
||||
were not used. A per-point warp is ruled out above. Curl noise could orient kernels,
|
||||
evaluated per kernel, at no cost to exactness.
|
||||
|
||||
## Measurements
|
||||
|
||||
**Setup.**
|
||||
- Probe source: scratch clone `probe-clone@5ec9f529`,
|
||||
`packages/cultmath/probe/DomainProbe/Program.cs`, never merged.
|
||||
- Run on Yggdrasil through the verify stopgap: dotnet 10 container, 4 CPUs, tiered
|
||||
JIT off.
|
||||
- Full log: Self's scratchpad, `dom-full1.log`.
|
||||
- The scenes are those of the first probe, with fixed cameras:
|
||||
- Void: the shipped orbiting camera at time 20, at the 1920-wide f = 935 field of
|
||||
view, rendered at 512 x 256.
|
||||
- Wells: warp D = 60, camera at xz (1200, 0) looking at the central well, slopes
|
||||
x ±1 and y from −0.85 to 0.15.
|
||||
- The window is the shipped field's active intervals. Every method integrates the
|
||||
same window.
|
||||
|
||||
**Cost.**
|
||||
- Single-threaded C#, best of three passes over the same 2048 random pixels.
|
||||
- The host is shared, and absolute timings moved by up to 2x between the smoke run
|
||||
and the full run; Flow went from 125 to 660 ns. Ratios within one run are the
|
||||
reliable numbers.
|
||||
- Flow is 47% of a shipped sample in this run, so a flow-cached march would cost
|
||||
about 15 µs on the void and 31 µs on the wells.
|
||||
|
||||
| Config (void) | Cost vs march | Roots visited / nodes tested / kernels integrated per pixel | Kernels per level |
|
||||
|---|---|---|---|
|
||||
| L1 | 0.12x | 43 / 8 / 8 | 8 |
|
||||
| L2 | 0.48x | 59 / 25 / 20 | 8, 12 |
|
||||
| L3 | 1.24x | 74 / 42 / 28 | 8, 12, 8 |
|
||||
| L4 | 1.81x | 82 / 60 / 35 | 8, 12, 8, 7 |
|
||||
| L6 (default) | 2.57x | 93 / 86 / 36 | 8, 12, 8, 7, 1, 0 |
|
||||
| L6, no child placement | 1.79x | 93 / 91 / 39 | same metrics as L6 |
|
||||
| L6, no LOD | 2.95x | 93 / 103 / 49 | 8, 12, 8, 7, 7, 7 |
|
||||
|
||||
| Config (wells) | Cost vs march | Kernels integrated per pixel |
|
||||
|---|---|---|
|
||||
| L1 | 0.04x | 5 |
|
||||
| L2 | 0.23x | 11 |
|
||||
| L3 | 0.49x | 16 |
|
||||
| L4 | 0.77x | 20 |
|
||||
| L6 | 1.20x | 25 |
|
||||
| L6, no child placement | 0.62x | 27 |
|
||||
|
||||
**Where the time goes.**
|
||||
- The integrals are about 36 kernels × 10 ns, or 0.4 µs of a 74 µs pixel.
|
||||
- The rest is traversal:
|
||||
- roots visited but missed: 93 visited for 8 hits, because AABBs of elongated
|
||||
rotated ellipsoids are loose;
|
||||
- child generation;
|
||||
- placement lookups. The wells' placement costs a 5-bowl `Sdf`, and dropping
|
||||
child placement halves the wells cost with identical metrics.
|
||||
|
||||
**Aliasing.** One sample per pixel against four on the default void field: |ΔT| has
|
||||
an RMS of 0.015 (p90 0.022). At 4 spp the msf is 0.146 against 0.159. So about 92%
|
||||
of the measured detail is resolved structure, not sparkle. Exact along the ray is
|
||||
not the same thing as antialiased across the pixel; the LOD rule is the prefilter.
|
||||
|
||||
**Variants, void L6 (msf / power above 1/8).**
|
||||
- k = 1 default: 0.159 / 12.5%.
|
||||
- Hard k = 0: 0.145 / 11.0%.
|
||||
- Gaussian (erf): 0.174 / 14.2%, at 0.89x the polynomial cost here. The erf kernel is
|
||||
3x the polynomial kernel in isolation, but the kernel is not where the time goes.
|
||||
|
||||
## Images
|
||||
|
||||
All images are in Self's session scratchpad,
|
||||
`C:\Users\Meta\AppData\Local\Temp\claude\F--Projects-CultLib\b7e842a1-2045-474e-a51b-240d832b770b\scratchpad\integration-domain-images\`:
|
||||
|
||||
- **Transmittance, 512 x 256.** Shown as `sqrt(1 − T)`, white for opaque.
|
||||
- `void-T-shipped-ref.png`, `void-T-shipped-march.png`.
|
||||
- `void-T-IN-L1.png`, `void-T-IN-L3.png`, `void-T-IN-L6.png`,
|
||||
`void-T-IN-L6-hard.png`, `void-T-IN-L6-gauss.png`.
|
||||
- The wells equivalents, which are silhouettes and uninformative.
|
||||
- **Single scattering, 256 x 128.**
|
||||
- Method: HG g = 0.6 and albedo 1. The point light is at the void's sun with 1/r²
|
||||
falloff; the wells use a directional sun with a sky background.
|
||||
- Each view sample takes a shadow ray: a 2-world march for the shipped field, an
|
||||
exact traversal for the integration-native field.
|
||||
- Tonemap: `1 − exp(−1.5 L / p99(shipped))`, then gamma 2.2, the same exposure for
|
||||
both fields.
|
||||
- `void-SS-shipped.png`, `void-SS-IN-L6.png`, `wells-SS-shipped.png`,
|
||||
`wells-SS-IN-L6.png`.
|
||||
|
||||
What they show:
|
||||
- The shipped void is a soft, low-contrast haze.
|
||||
- The integration-native void is dense flow-aligned streaks with deep gaps, like
|
||||
hair or brush strokes.
|
||||
- The shipped wells are smooth rolling dunes. The integration-native wells are
|
||||
layered pancakes with streaked detail.
|
||||
|
||||
## The catches
|
||||
|
||||
1. **The character is a design parameter, and this probe picked one.**
|
||||
- High anisotropy, axis-chained children and an intermittent `u²` split give
|
||||
fibres.
|
||||
- A cloudier look would need rounder children, wider offsets and less
|
||||
intermittency. That trades away some measured detail and was not swept.
|
||||
- The detail metrics measure spatial frequency, not taste. The operator has to
|
||||
look at the images.
|
||||
2. **The cost is a BVH, not arithmetic.**
|
||||
- Integration is nearly free. Traversal, child generation and placement dominate.
|
||||
- Tighter root bounds (OBB tests before AABB bins), cheaper placement and fewer
|
||||
children are obvious levers, but none was measured.
|
||||
- On a GPU, variable-length kernel lists per ray diverge. 3DGRT (Moënne-Loccoz et
|
||||
al. 2024 [memory]) puts the same problem on hardware ray tracing.
|
||||
- CPU C# ratios do not transfer to the GPU, where snoise is relatively cheaper.
|
||||
3. **It is all or nothing.**
|
||||
- This field cannot be marched. At the shipped step, |ΔT| is a median 0.14.
|
||||
- Shadow rays, light probes and any sampler consumer need the exact traversal too.
|
||||
The single-scattering pass here cost an exact shadow traversal per view sample:
|
||||
257 s for both void SS images together, against 54 s for the whole 512 x 256
|
||||
shipped transmittance set.
|
||||
- Lighting has no closed form. The in-scatter integral is still quadrature. What
|
||||
the domain makes exact is every optical depth inside it. A per-kernel lighting
|
||||
cache would amortise shadows, but that is a different shading model (splat-like),
|
||||
and so a product fork.
|
||||
4. **Exact along the ray, not across the pixel.** The LOD truncation is the
|
||||
prefilter. 8% of the measured detail at 1 spp is aliasing.
|
||||
5. **The wells gain little** because the shipped wells fog is near-opaque. Its look
|
||||
is the surface silhouette, and that is set at root scale. The domain pays most
|
||||
where the medium is semi-transparent, as in the void.
|
||||
6. **Timing noise.** Absolute costs vary up to 2x between runs on the shared host.
|
||||
The cost ratios above are within one run.
|
||||
|
||||
## What would change the verdict
|
||||
|
||||
- A sweep toward a cloud-like character: round children, Nc = 8, wider offsets,
|
||||
Gaussian kernels. It should be judged on the single-scattering images against the
|
||||
same cost.
|
||||
- Tight root culling: an exact ellipsoid-versus-bin test, or roots stored by
|
||||
oriented bound. If roots visited fall from 93 to near the 8 hits, the void L3 cost
|
||||
would fall well under the march.
|
||||
- A GPU port of one level-limited configuration, to replace the C# ratios with
|
||||
shader timings.
|
||||
151
docs/research/inverse-procedural-modelling-prior-art.md
Normal file
151
docs/research/inverse-procedural-modelling-prior-art.md
Normal file
|
|
@ -0,0 +1,151 @@
|
|||
# Inverse procedural modelling: describing messy meshes as programs
|
||||
|
||||
Eyes pass, 2026-10-10. Operator: "What if the model had some trash geo and its goal is to describe it parametrically?" Context: Tripo hard-surface hulls; CultMath intervals and affine forms on main, tape/brush grammar parked (docs/cultmath-tape-target.md); the earlier GameCult/VibeGeometry attempt (2026-05). Facts only; tags mark FETCHED, SEARCH (search summary only) and KNOWLEDGE (unverified).
|
||||
|
||||
# Eyes facts: inverse procedural modelling (mesh -> parametric program)
|
||||
Date 2026-10-10. Tags: FETCHED (page/file read this session), SEARCH (search-result digest only), KNOWLEDGE (unverified recall).
|
||||
Search digests come from a small model; SEARCH numbers are not paper-verified.
|
||||
|
||||
## 0. What exists in GameCult
|
||||
- FETCHED F:\Projects\CultLib\docs\cultmath-tape-target.md: steps 2-5 (tape, pruning, HLSL interpreter, meshing) PARKED (2026-10-02,
|
||||
ruling tape-target-unparks-when-asura-stable). Step 1 intervals + affine forms are on main (docs/cultmath-interval-ground-cut.md).
|
||||
The "grammar of nested brushes" is operator intent only (quote 2026-10-02: space station from "a grammar of nested brushes");
|
||||
doc says the station project is "a separate project with its own target". Chosen shape (c): port Fidget ideas into CultLib (Fidget =
|
||||
MPL-2.0 Rust, v0.5.1). Meshing plan: surface nets + Asura tile pass (Newton refinement onto f=0, crease snapping from field gradients);
|
||||
"Thin authored bevels can be shaded by their analytic normals". Tape gradients "reuse CultMath's analytic-gradient primitives".
|
||||
- FETCHED grep CultLib\docs for brush/tape: "brush" hits in cultmath-interval-ground-cut.md are Aetheria noise/gravity-well field brushes
|
||||
(PowerBrush (1-x^2)^16 etc.), not CSG brushes. No CSG brush grammar or tape code exists in CultLib; only the parked doc.
|
||||
- FETCHED (voidbot) separate repo GameCult/GameCult.Geometry.Csg ("CultGeometry CSG", Rust; local F:\Projects\GameCult.Geometry.Csg).
|
||||
Mesh-based convex plane-splitting CSG (not SDF), RealtimeCSG-shaped API: ordered Additive/Subtractive/Intersecting brush streams, boxes,
|
||||
oriented boxes, CylinderZ/DomeCapZ/FloretArm, dirty-frontier, OBJ output, plus domain-tree/selected-cut LOD schemas (src/cult_geometry).
|
||||
Doc text: "agents should revise intent by moving, adding, or renaming brushes, not by poking triangles"; "brush list is the durable
|
||||
design surface. The mesh is a cache."
|
||||
|
||||
## 0b. The earlier "vibe geometry" attempt
|
||||
- FETCHED voidbot gamecult-site GameCult/Projects/VibeGeometry.md: repo GameCult/VibeGeometry, started 2026-05-04, last public push
|
||||
2026-05-07; "agent-authored Blender scene generation: geometry nodes, Python builders, semantic graph contracts, render evidence, and
|
||||
the ongoing war against decorative node spaghetti". Org ledger: "Started as architecture and persistence scaffolding, then dived almost
|
||||
immediately into CSG grammar, parity fixtures, native bridge probing, mesh generation, and performance work."
|
||||
- FETCHED local git F:\Projects\VibeGeometry-cultgeometry-rename (93 commits). Commit 09bff8c (2026-05-29, "Focus VibeGeometry on vg-csg")
|
||||
deleted the scene-generation tree; recoverable at 09bff8c^: docs/research/procedural-doctrine.md (~1000-line "spatial reasoning
|
||||
playbook"), dream-machine-grammar.md, geonodes-translation-corpus.md, ircss-french-houses-* (translations of Blender node graphs into
|
||||
Geometry Script Python), builds/{aetheria-bloom-habitat, lucent-tether-habitat, dream-machine-level, industrial-maintenance-loop}.md,
|
||||
notes/architecture-rationale.md, a "reusable procedural helper library" (aa4d49d). The DSL was Blender Python via Geometry Script
|
||||
(fork F:\Projects\geometry-script; upstream PR carson-katri/geometry-script#69 linked by Metacrat 2026-05-04) emitting geometry-node
|
||||
graphs, plus the Rust brush DSL (LevelDsl: solid_box, cut_box, solid_oriented_box, dome_cap_z, floret_arm).
|
||||
- FETCHED notes/architecture-rationale.md @09bff8c^, section "Core Failure": "The central failure mode is local plausibility without global
|
||||
coherence. An agent can write plausible Blender Python, create a large node graph, and still lose the visual machine ... the script
|
||||
runs, the graph exists, the render has objects in it, and somehow the target has been replaced by decorative procedural fog".
|
||||
"Seductive proxies": valid Python, non-empty renders, high node counts, pretty materials, parameter sliders.
|
||||
procedural-doctrine.md: "Ornament in the wrong frame is not detail. It is a confident lie". Commit titles record frame errors:
|
||||
"Correct Bloom terrace slum orientation", "Correct Lucent dome spin-gravity frame", "Move Lucent ray florets outside dome".
|
||||
- FETCHED VibeGeometry README: "failed experiments are useful without being allowed to hold a steering wheel"; old mission "deleted
|
||||
from the live tree"; live mission narrowed to runtime CSG (domain tree -> LOD CSG -> selected cut -> triangles).
|
||||
- NOT FOUND: no indexed operator or agent statement that models "weren't good enough at spatial reasoning to use the DSL". voidbot
|
||||
search_history (Discord) returned only unrelated hits. The repo docs above are the only failure statements in project words
|
||||
(coherence and frame errors; the phrase "spatial reasoning" appears only in the playbook title and its body).
|
||||
|
||||
## 1. Inverse CSG / shape-program synthesis
|
||||
Most train or test on DeepCAD / ShapeNet / ABC / Infinigen; none retrieved was evaluated on noisy AI-generated hard-surface meshes.
|
||||
- InverseCSG (Du et al., SIGGRAPH Asia 2018, MIT). SEARCH: mesh/point samples -> CSG program; geometric processing (RANSAC-style primitive
|
||||
detection) turns the mixed discrete/continuous problem into a purely discrete one; careful point samples guide a discrete search;
|
||||
divide-and-conquer segmentation; program synthesis (solver) per segment. Claims >100 primitive parts, compact programs, beats prior
|
||||
methods on compactness/runtime. D2CSG authors (SEARCH) criticise it: RANSAC needs tuning, noisy initial primitives, long search.
|
||||
Project page inversecsg.csail.mit.edu lists code; licence not checked.
|
||||
- CSGNet (Sharma 2018): KNOWLEDGE only; supervised, voxel/2D -> CSG sequence.
|
||||
- UCSG-Net (Kania, NeurIPS 2020). SEARCH: unsupervised; predicts box/sphere params; differentiable indicator on SDF; several CSG layers with
|
||||
soft operator choice; structure and params learned jointly by gradient descent; autoencoding scope (2D/3D), no mesh-to-program at test
|
||||
for unseen exotic shapes beyond the trained net.
|
||||
- CAPRI-Net (CVPR 2022). SEARCH: axis-aligned quadric primitives, fixed 3-layer assembly; ABC point-cloud Chamfer 0.09 vs UCSG 1.43; ~5.3 vs
|
||||
12.92 convex shapes. D2CSG (2023), CSG-Stump (2021): SEARCH, unsupervised compact trees. SECAD-Net (CVPR 2023): SEARCH, sketch-extrude,
|
||||
editable; CD 2.94/4.20 (ABC/Fusion) vs UCSG 3.14/4.45.
|
||||
- Point2CAD (Liu et al.): SEARCH only that a repo exists (jofcodeusal/point2cad mirror, Docker toshas/point2cad); method not retrieved.
|
||||
Point2Cyl (CVPR 2022): SEARCH, supervised net to extrusion cylinders. DeepCAD (Wu 2021): KNOWLEDGE, ~178k sketch-extrude sequences.
|
||||
- ShapeAssembly (Jones 2020, TOG): SEARCH; programs of cuboid proxies attached to each other with free parameters; extraction from PartNet.
|
||||
ShapeMOD (2021): SEARCH; discovers macros across a corpus minimising calls and free parameters. Repos/licences not found by search
|
||||
(KNOWLEDGE: github rkjones4/ShapeAssembly exists; unverified).
|
||||
- CAD-Recode (Rukhovich et al., ICCV 2025, arXiv 2412.14042). FETCHED abstract: point cloud -> CadQuery Python (sketch-extrude); point-cloud
|
||||
projector + small pretrained LLM decoder; trained on 1M procedurally generated CAD sequences; eval DeepCAD, Fusion360, CC3D (real scans);
|
||||
output usable by off-the-shelf LLMs for editing and QA. SEARCH (unverified): Qwen 0.5B/1.5B decoders; DeepCAD mean CD 3.43 -> 0.30, IoU
|
||||
77.6 -> 92.0 vs CAD-SIGNet; test time: 10 sampled candidates executed, min-Chamfer kept. Code github.com/filaPro/cad-recode (SEARCH);
|
||||
HF dataset filapro/cad-recode is CC-BY-NC-4.0 (SEARCH); repo licence unchecked. Structure by autoregressive decoding, params as literal
|
||||
tokens, re-ranking by Chamfer. Abstract says nothing on fillets/chamfers.
|
||||
- MeshCoder (Dai et al., NeurIPS 2025, arXiv 2508.14879). FETCHED: 16,384-point cloud -> triplane tokenizer -> Llama-3.2-1B (LoRA) ->
|
||||
Blender Python. API: cube/cylinder/UV-sphere/cone/torus, Translation (sweep 2D section along 3D trajectory), Bridge Loop, Boolean
|
||||
(union/intersect/diff), Array, Fill Grid, Spoon, Fork. Data: ~10M part-code pairs, ~1M object-code pairs, 41 categories (Infinigen
|
||||
Indoor). Table 2 averages CD x1e-2 / IoU%: Shape2Prog 6.00/45.0, PLAD 1.87/67.6, MeshCoder 0.06/86.75. Worst: Fork 58.9 IoU, CeilingLight
|
||||
65.8, Array parts 78.9. Limits: human-made objects only; geometry only; training objects kept only if every part CD < 5e-3. LLM does not
|
||||
edit; edits are manual param changes; GPT-4o used only for QA on the code. Output is part-segmented. Licence not stated in paper.
|
||||
- CADCodeVerify (Alrashedy, ICLR 2025, arXiv 2410.05340). SEARCH: text prompt -> CadQuery (GPT-4); VLM writes/answers validation questions
|
||||
about renders and refines; CADPrompt benchmark (200 objects); GPT-4 point-cloud distance -7.30%, compile rate +5.5% (v2; v1 said 5.0%
|
||||
success). Target is a prompt, not a mesh.
|
||||
- Newer render-loop agents (SEARCH): SEIG "Thinking in Blender" (arXiv 2606.02580): single reference image -> staged Blender code (geometry,
|
||||
materials, composition, lighting), VLM generator + verifier per stage; FETCHED abstract gives no numbers, no code link. LL3M (2508.08228):
|
||||
text -> Blender with critic reading renders. ShapeCraft (2510.17603): renders bbox/part/global views as feedback. SceneCraft (2403.01248):
|
||||
render-critique-revise. Not found by search: "3D-Premise", "LLMto3D", Img2CAD/Text2CAD specifics.
|
||||
|
||||
## 2. Classical primitive fitting as a front end
|
||||
- Efficient RANSAC (Schnabel/Wahl/Klein, CGF 2007): SEARCH/FETCHED page text: planes, spheres, cylinders, cones, tori in unorganised clouds;
|
||||
multi-million-point sets "within less than a minute". CGAL Shape Detection implements it plus Region Growing (Lafarge&Mallet). CGAL is
|
||||
dual GPL/LGPL + commercial; the Shape Detection package's own licence NOT confirmed (digest guessed GPL).
|
||||
- GlobFit (Li/Wu/Chrysanthou/Sharf/Cohen-Or/Mitra, SIGGRAPH 2011): SEARCH; starts from RANSAC primitives, discovers global relations
|
||||
(orientation, placement, equality; symmetry) and enforces them by constrained optimisation; assumes man-made, repeated, globally aligned
|
||||
parts. Code: archived code.google.com/archive/p/globfit, "research use only" wording.
|
||||
- Mitra 2006 symmetry detection, SPFN (2019): KNOWLEDGE/SEARCH only. ParSeNet (2020): SEARCH; B-spline patch decomposition, beats RANSAC
|
||||
and SPFN baselines. No repos/licences retrieved.
|
||||
- What fits supply as data: exact primitive parameters with inlier sets and residuals, segment labels, relation graph (GlobFit).
|
||||
InverseCSG uses the primitives to make the problem discrete. Recorded weakness: noisy primitives, parameter tuning (SEARCH).
|
||||
|
||||
## 3. Differentiable fitting of SDF/CSG programs
|
||||
- UCSG-Net (above): soft operator selection; structure learned jointly.
|
||||
- Fuzzy Boolean differentiable CSG (dgp.toronto.edu/~hsuehtil/pdf/fuzzyBoolean.pdf): SEARCH; gradient descent over boolean and primitive
|
||||
parameters; notes prior work pre-fixes tree structure and operators and optimises only primitive params; replaces min/max with a unified
|
||||
fuzzy operator so the operation type is optimised. Costs listed: analytic SDF per primitive type, per-iteration SDF evaluation, image
|
||||
losses need differentiable sphere tracing.
|
||||
- DiffCSG (arXiv 2409.01421): SEARCH; differentiable rasterisation of mesh CSG, image-space gradients to primitive params; image-guided
|
||||
editing, not mesh fitting.
|
||||
- ResFit, Residual Primitive Fitting with SuperFrusta (arXiv 2512.09201): SEARCH; one analytic SDF primitive with 8 params (dilation, taper,
|
||||
bulge, onion hollowing, profile roundness, axial scaling); alternates global shape analysis and local primitive optimisation; code "to be
|
||||
open-sourced upon acceptance".
|
||||
- Evolutionary mesh -> CSG abstraction (SEARCH; authors not retrieved): fast, coarse. Sigmoid-over-SDF soft occupancy with alternating
|
||||
add-primitive / joint-refine loop (SEARCH, primitive-scene paper).
|
||||
- Not found: a published gradient fit of an SDF program with bevel/round parameters to a messy hard-surface mesh.
|
||||
- Handling of discrete structure across sources: soft selection (UCSG, CSG-Stump, fuzzy Boolean); pre-fixed structure (InverseCSG after
|
||||
RANSAC; CAPRI-Net fixed layers); greedy add/prune (ResFit); neural token decoding (CAD-Recode, MeshCoder).
|
||||
|
||||
## 4. LLM spatial reasoning in 3D code generation
|
||||
- BlenderGym (Gu et al., CVPR 2025, arXiv 2504.01786). FETCHED: 245 start-goal Blender scene pairs, five tasks (placement, lighting,
|
||||
procedural material, blend shape, procedural geometry); the VLM sees start and goal and edits Blender code (target-matching setting).
|
||||
Table 1 best-VLM vs human: geometry Chamfer 1.120 (GPT-4-Turbo) vs 0.334; geometry photometric loss 6.747 vs 1.269; placement CD 8.324 vs
|
||||
1.532; blend shape CD 0.904 vs 0.399. Paper: VLMs "particularly poorly in procedural material and geometry editing"; all open-source
|
||||
models except MiniCPM failed to produce executable code on >75% of geometry instances. Verifier agreement with humans: human 0.79,
|
||||
Claude 3.5 Sonnet 0.66, random 0.5. Scaling a small verifier (InternVL2-8B, k 1 -> 64 over 32 candidates) beat unscaled GPT-4o and
|
||||
Claude 3.5 on blend shape. Low compute: less verification share (0.33); high compute: more (0.62-0.73). Models are 2024-25 era. Code
|
||||
licence not in retrieved text.
|
||||
- BenchCAD (arXiv 2605.10865): SEARCH; 17,900 CadQuery programs, 106 part families; frontier models recover coarse outer geometry but fail
|
||||
faithful parametric programs; sweeps/lofts/twist-extrudes replaced by sketch-extrude; single-literal errors (5.6 vs 5.85) at IoU >= 0.9.
|
||||
BenchCAD-Edit: text instruction sets the upper bound; the image is "at best a clarifier and at worst a distractor" for thinking models.
|
||||
- Text2CAD-Bench (2605.18430): SEARCH; execution failures even at easy level; sweep/loft/shell widely fail; executing != correct.
|
||||
- Text-to-B-Rep paper (2603.11831): SEARCH; spatial misalignment of primitives, omitted fillets, geometry contradicting described layout;
|
||||
authors blame weak precise 3D spatial reasoning.
|
||||
- "Foundation Models for Automatic CAD Generation" (2607.05573): SEARCH, single source; numeric analytic feedback peaked at round 1; VLM
|
||||
critique of renders kept improving in rounds 2-3 for DeepSeek/Qwen; VLM critics struggle on rotationally symmetric geometry.
|
||||
- Multi-view conditioning beat single-view and sketch on Chamfer/F-score in a B-Rep paper (SEARCH, not CadQuery).
|
||||
- Target vs description: BlenderGym gives a target and still shows a large human gap; CAD-Recode and MeshCoder avoid prompting by training
|
||||
point-cloud encoders; no controlled prompted-LLM study of target-vs-description was found.
|
||||
- MindCube spatial study (SEARCH): errors 20% final reasoning step, 13% 3D reconstruction, 6% generated programs.
|
||||
|
||||
## 5. Hard-surface specifics
|
||||
- SDF rounding (Quilez distfunctions, SEARCH): sdRoundBox = box SDF minus r, an iso-offset so the shape grows by r. Polynomial smin with k
|
||||
as blend band; Quilez marks smin as "bound" not exact. Chamfer/fillet operators not retrieved; KNOWLEDGE: hg_sdf (Mercury) has
|
||||
fOpUnionChamfer / fOpUnionRound / fOpUnionStairs (unverified here).
|
||||
- MeshCoder (FETCHED): no fillet/chamfer primitive; booleans, sweeps, bridge-loop, arrays only.
|
||||
- BenchCAD / text-to-B-Rep (SEARCH): omitted fillets/refinement features named as failure; sweeps/lofts degrade to extrudes.
|
||||
- CAD-Recode/DeepCAD data are sketch-extrude (SEARCH/KNOWLEDGE); fillet/chamfer not covered in what was retrieved.
|
||||
- InverseCSG output: boolean of primitives, no blends (KNOWLEDGE). CAPRI-Net quadrics: smooth surface in one primitive (SEARCH). ResFit
|
||||
primitive has a profile-roundness parameter (SEARCH).
|
||||
|
||||
## Gaps
|
||||
- Operator/agent words on why VibeGeometry failed: not indexed (see 0b).
|
||||
- Not read at body level: CAD-Recode fillet handling, InverseCSG experiments, GlobFit relation list, SEIG numbers, ResFit results.
|
||||
- Licences unverified: InverseCSG, ShapeAssembly, CAD-Recode repo, MeshCoder, GlobFit, CGAL Shape Detection, Point2CAD.
|
||||
221
docs/research/payload-depth-limit.md
Normal file
221
docs/research/payload-depth-limit.md
Normal file
|
|
@ -0,0 +1,221 @@
|
|||
# Payload nesting limits in comparable libraries
|
||||
|
||||
Fork: `cultlib-gaps:question:payload-depth-limit` (options reference-500, shared-256, shared-128).
|
||||
Raised in `cultlib-gaps:cut_spec:cut-union-bounds-cs.r1`. Gathered 2026-10-11 by Eyes
|
||||
(`eyes-depth-limit-prior-art`). Facts only; no recommendation. Source files were fetched
|
||||
from each project's default branch on 2026-10-11 (raw.githubusercontent.com); line numbers
|
||||
refer to those fetches and move with the branch. "(inferred)" marks a reading of code or
|
||||
text that the source does not state.
|
||||
|
||||
Terms: "read" = decode/parse; "write" = encode/serialize; "skipped" = content a decoder
|
||||
walks past without materialising (ignored fields, unknown fields).
|
||||
|
||||
## 1. Summary table
|
||||
|
||||
| Library | Default | Counts | Read / write | Source |
|
||||
|---|---|---|---|---|
|
||||
| MessagePack-CSharp (UntrustedData and TrustedData) | 500 (`MaximumObjectGraphDepth`) | each `DepthStep` call: formatter-driven, one step per container a formatter enters; check is `Depth >= max` before increment | read only; skipped content not counted unless a formatter calls DepthStep (see 2.1) | MessagePackSecurity.cs:31,41,92,266-273 |
|
||||
| rmp-serde | 1024 (`depth: u16`, `set_max_depth`) | containers (array, map, ext newtype) via `depth_count!`; counter decremented, error at 0 | read: yes; write: error variant exists but is never constructed | decode.rs:51-60,213,294,309-310,566,583,616; encode.rs:37,49,64 |
|
||||
| serde_json | 128 (`remaining_depth`, `disable_recursion_limit`) | each `[` and `{` entered by `deserialize_any`-style paths; error when the counter reaches 0 (deepest enterable container is 127, inferred from the decrement-then-test-zero code) | read only; serializer has no depth code; skipped values (`ignore_value`) are iterative and contain no `check_recursion!` call | de.rs:63,1357-1387,1434,1445,1102-1215; ser.rs (no match) |
|
||||
| msgpack-python (C unpacker) | 1024 (`MSGPACK_EMBED_STACK_SIZE`) | each container pushed on a fixed stack, before the zero-length check; raises `StackError` | read: yes (including `skip()`); write: `Packer` `DEFAULT_RECURSE_LIMIT = 1024` (`ValueError`) | unpack.h:19; unpack_template.h:117-127; _unpacker.pyx:208-211,524; _packer.pyx:42,259-262 |
|
||||
| msgpack-python (pure-Python fallback) | Python's recursion limit; `RecursionError` is mapped to `StackError` | recursion frames | read; write via `DEFAULT_RECURSE_LIMIT = 1024` | fallback.py:66,586-606 |
|
||||
| @msgpack/msgpack | decode: no depth limit found (heap-allocated `StackPool`, iterative); encode `maxDepth` 100 | encode: depth argument to `doEncode` | read: unbounded; write: yes (`Too deep objects in depth N`) | Decoder.ts:111-190,640-643; Encoder.ts:9,97,173; README.md:119 |
|
||||
| msgpackr | no depth option found | recursive `readObject` (inferred from the single recursion comment at unpack.js:506) | neither | unpack.js, pack.js (grep for depth/maxDepth: no hit) |
|
||||
| System.Text.Json | 64 (reader and serializer); writer default 1000 | `JsonReaderOptions.MaxDepth`; `JsonSerializerOptions.MaxDepth` default is the minimum of reader and writer defaults | read: yes; write: yes (writer 1000, serializer 64) | JsonReaderOptions.cs:13,43; JsonWriterOptions.cs:18; JsonSerializerOptions.cs:27-28,580-593 |
|
||||
| Newtonsoft.Json | 64 (`JsonReader` ctor; `MaxDepth` nullable) | reader `Depth + 1 > _maxDepth` | read; `JsonWriter.cs` has no MaxDepth match | JsonReader.cs:332,356-359 |
|
||||
| protobuf C++ | 100 (`default_recursion_limit_`) | recursion budget decremented per nested message/group | read | coded_stream.h:630,1588-1602,1637 |
|
||||
| protobuf C# | 100 (`DefaultRecursionLimit`) | CodedInputStream recursion | read | CodedInputStream.cs:57,120-147 |
|
||||
| protobuf Java | 100 (`defaultRecursionLimit`) | CodedInputStream recursion | read | CodedInputStream.java:45,52,521 |
|
||||
| protobuf upb | 100 (`kUpb_WireFormat_DefaultDepthLimit`) | `d->depth` per decode; max configurable up to a uint16 | read | upb/wire/internal/constants.h:11; decode.c:105,140,192,619,1306-1312 |
|
||||
| ciborium | 256 (`recurse` counter) | `recurse()` wrapper around array/map/tag decode | read only (cib_ser.rs has no depth/recurs match) | ciborium/src/de/mod.rs:54-74,812,854 |
|
||||
| cbor2 (Python) | 400 `max_depth` since 5.9.0 (CVE-2026-26209 fix); 6.0.0 (2026-04-28) rewrote the decoder in Rust as iterative, "limited only by the available memory" | containers | read | docs/versionhistory.rst:120-142,172-173 |
|
||||
| BSON (MongoDB) | 100 levels | "Each object or array adds a level" | the doc page does not say read vs write | mongodb.com/docs/manual/reference/limits/ |
|
||||
| Go encoding/json | 10000 (`maxNestingDepth`) | scanner `parseState` stack length; the scanner validates the whole input before decoding (`checkValid`) | read; encoder has no depth limit, only pointer-cycle detection after 1000 pointer levels (`startDetectingCyclesAfter`) | scanner.go:146-186; encode.go:298-305,764 |
|
||||
| simdjson | 1024 (`DEFAULT_MAX_DEPTH`) | parser allocation parameter | read | common_defs.h:49; dom/parser.h:596,599 |
|
||||
|
||||
## 2. Detail by library
|
||||
|
||||
### 2.1 MessagePack-CSharp (the C# reference's decoder)
|
||||
|
||||
- `UntrustedData` and `TrustedData` both set `MaximumObjectGraphDepth = 500`
|
||||
(MessagePackSecurity.cs:31, 41; property initialiser 92). `TrustedData` was lowered to 500
|
||||
by commit 6b025eab "Limit stack depth to 500 even for trusted data" (2024-10-29) and
|
||||
set from `UntrustedData` by 7c087905 (2024-11-28), per the commit history of
|
||||
MessagePackSecurity.cs (api.github.com/repos/MessagePack-CSharp/MessagePack-CSharp/commits?path=src/MessagePack/MessagePackSecurity.cs).
|
||||
The commit messages give no rationale for the value 500.
|
||||
- `DepthStep(ref MessagePackReader)` throws `InsufficientExecutionStackException` when
|
||||
`reader.Depth >= MaximumObjectGraphDepth`, else increments (MessagePackSecurity.cs:266-273).
|
||||
The doc comment says callers must decrement after leaving the edge (:254-260).
|
||||
- Counting is by contract with formatters, not by the reader: README.md says `DepthStep` and
|
||||
`Depth--` "should surround the bulk of any `IMessagePackFormatter<T>.Deserialize` method"
|
||||
(README lines ~1161-1175). So content no formatter reads is not counted (inferred from the
|
||||
README contract; the CultLib measurement in the question confirms it: an extra trailing slot
|
||||
of 100000 nested arrays is accepted).
|
||||
- Write: no depth check in the serializer or writer in the code fetched (MessagePackReader.cs
|
||||
holds `Depth` at :53-75,133; the writer was not fetched). The CultLib question reports a
|
||||
3001-deep payload written and then refused on read.
|
||||
- Advisory GHSA-7q36-4xx7-xcxf / CVE-2020-5234 (published 2020-01-31): "Untrusted data can lead
|
||||
to DoS attack due to hash collisions and stack overflow in MessagePack". Affected < 1.9.11 and
|
||||
>= 2.0.0 < 2.1.90. Mitigation is opting into `UntrustedData`; the advisory text does not state
|
||||
the depth value.
|
||||
- Advisory GHSA-cj9g-3mj2-g8vv / CVE-2026-48512 (published 2026-06-25), fixed in 2.5.301 and
|
||||
3.1.7: the JSON conversion helpers (`ConvertFromJson`, `TinyJsonReader.ReadNextToken`, the
|
||||
ext-100 branch of `ConvertToJson`) recursed without consulting `MaximumObjectGraphDepth`; the
|
||||
advisory says `UntrustedData` "does not fully mitigate" them. This is the class of defect
|
||||
"a depth limit exists but one recursive path skips it".
|
||||
|
||||
### 2.2 rmp-serde (the Rust runtime's decoder)
|
||||
|
||||
- `Deserializer` has `depth: u16`, initialised to 1024 (decode.rs:181, 213, 294);
|
||||
`set_max_depth` clamps to `u16::MAX` (:309-310).
|
||||
- `depth_count!` decrements, returns `DepthLimitExceeded` when the counter reaches 0, runs the
|
||||
body, increments (decode.rs:51-62). Used for arrays (:566), maps (:583) and ext newtype (:616).
|
||||
So the usable nesting is 1023 levels (inferred from decrement-then-test-zero).
|
||||
- `ignored_any` is forwarded to `deserialize_any` (decode.rs:~749-753 `forward_to_deserialize_any!`),
|
||||
which goes through the same counted paths: skipped containers are counted.
|
||||
- Write: `Error::DepthLimitExceeded` exists in encode.rs (:37, 49, 64) but a grep finds no site
|
||||
that constructs it (only definition, `source`, `Display`). The writer has no depth check
|
||||
(inferred from the three matches).
|
||||
- Crate version at fetch: 1.3.1 (Cargo.toml). No RUSTSEC advisory about depth was found for
|
||||
rmp-serde, rmpv or ciborium in a web search (search-engine result, not a database query).
|
||||
|
||||
### 2.3 serde_json
|
||||
|
||||
- `remaining_depth: u8 = 128` (de.rs:34, 63); `check_recursion!` decrements and errors with
|
||||
`RecursionLimitExceeded` when it reaches 0 (de.rs:1372-1387), used at the `[`/`{` branches of
|
||||
`deserialize_any` and the typed deserialize methods (de.rs:1434, 1445, 1750, 1801, 1838, 1849,
|
||||
1882). `disable_recursion_limit()` exists behind the `unbounded_depth` feature (de.rs:197-216,
|
||||
1357-1370). A third-party analysis (search result, not fetched) states the deepest enterable
|
||||
container is level 127.
|
||||
- `deserialize_ignored_any` calls `ignore_value()` (de.rs:1910-1916). `ignore_value` (:1102-~1215)
|
||||
is an explicit loop with a heap `scratch` stack of frames and contains no `check_recursion!`
|
||||
(the `check_recursion!` lines in the file are all at 1372+). Reading: ignored values in
|
||||
serde_json are walked iteratively and are not depth-limited (inferred from the code; not
|
||||
tested). This differs from the question's statement that "serde_json ... count ignored values
|
||||
the same way".
|
||||
- Serializer: grep of ser.rs for depth/recurs returns no match.
|
||||
- Related: serde-json-wasm GHSA-rr69-rxr6-8qwf / RUSTSEC-2024-0012 (2024-02-09), fixed in 1.0.1
|
||||
and 0.5.2: "This was fixed by adding a check for recursion depth"; the advisory text gives no value.
|
||||
rustc_serialize RUSTSEC-2022-0004: parsing had no stack-depth limit and "can cause a stack
|
||||
overflow, which aborts the process".
|
||||
- serde_stacker (crates.io description) grows the stack dynamically and is documented as paired
|
||||
with `disable_recursion_limit()`; its README warns that Drop, Debug and Display on deep values
|
||||
can still overflow. A forum thread reports dropping a deeply nested `Value` (~10 million
|
||||
levels) overflowing after a successful parse.
|
||||
|
||||
### 2.4 msgpack-python
|
||||
|
||||
- C unpacker: `MSGPACK_EMBED_STACK_SIZE` 1024 (unpack.h:19); `start_container` returns -3 when
|
||||
`top >= 1024` before it checks for an empty container (unpack_template.h:117-127), and -3 is
|
||||
raised as `StackError` (_unpacker.pyx:208-211, 521-524). The docstring says "Raises `StackError`
|
||||
when `packed` contains too nested" (_unpacker.pyx:158, 313). Empty containers at depth 1025 are
|
||||
therefore also refused (inferred from check order). `skip()` runs the same state machine
|
||||
(fallback.py:599-606 shows `skip` raising `StackError`; the C path is the same unpack function,
|
||||
inferred).
|
||||
- Pure-Python fallback: depth is Python's recursion limit; `RecursionError` is converted to
|
||||
`StackError` (fallback.py:586-606).
|
||||
- Packer: `DEFAULT_RECURSE_LIMIT = 1024`; `_pack` raises `ValueError("recursion limit exceeded.")`
|
||||
when `nest_limit < 0` and decrements per container (_packer.pyx:42, 259-262; fallback.py:66, 699-711, 801-804).
|
||||
|
||||
### 2.5 JavaScript
|
||||
|
||||
- @msgpack/msgpack Decoder: iterative, with a heap `StackPool` (Decoder.ts:111-190, loop :640-643);
|
||||
no depth option appears in the decoder (grep of "depth" returns only stack-pool lines). The
|
||||
README option table lists `maxDepth` default 100 (README.md:119) and Encoder.ts uses it
|
||||
(`DEFAULT_MAX_DEPTH = 100`, :9; `doEncode` throws `Too deep objects in depth N` when
|
||||
`depth > maxDepth`, :173). So the library is asymmetric: encode bounded, decode unbounded in
|
||||
depth (limited by memory). The CultLib question states TS "parse the whole payload"; consistent.
|
||||
- msgpackr: grep of unpack.js and pack.js finds no maxDepth option or depth counter.
|
||||
- msgpack5 (another npm package) GHSA-24ch-f2g6-9hhh (2026-10-08): "The decoder has no
|
||||
nesting-depth limit for arrays and maps ... exhaust the JavaScript call stack"; fix in 6.1.0
|
||||
limits depth to 100 by default, option `maxDepth`, error "Maximum decode depth exceeded".
|
||||
- msgpack-java: CVE record at vulncheck.com ("through 0.9.12", GitHub issue #1015):
|
||||
`MessageUnpacker.unpackValue()` "recursively deserializes arrays and maps without nesting
|
||||
depth limits", causing StackOverflowError. Fix value not retrieved.
|
||||
|
||||
### 2.6 .NET JSON
|
||||
|
||||
- System.Text.Json: `JsonReaderOptions.DefaultMaxDepth = 64` (JsonReaderOptions.cs:13);
|
||||
`JsonWriterOptions.DefaultMaxDepth = 1000` (JsonWriterOptions.cs:18);
|
||||
`JsonSerializerOptions.DefaultMaxDepth` = the reader's 64, with a comment that it is the
|
||||
minimum of the reader and writer defaults (JsonSerializerOptions.cs:27-28). So the serializer
|
||||
limit applies to both directions at 64; the bare writer at 1000.
|
||||
- Newtonsoft.Json: `JsonReader` constructor sets `_maxDepth = 64` (JsonReader.cs:332); exceeding
|
||||
throws `JsonReaderException` "The reader's MaxDepth of {0} has been exceeded" (:356-359).
|
||||
`JsonWriter.cs` has no MaxDepth match. Advisory GHSA-5crp-9r3c-p9vr / CVE-2024-21907
|
||||
(published 2022-06-22, affects < 13.0.1): "Insecure Defaults ... improper handling of
|
||||
expressions with high nesting level that lead to StackOverFlow exception or high CPU and RAM
|
||||
usage". Advisory figures: deserialising needs >10 million nesting (9.5 MB of `{a:{a:`) for >10 s
|
||||
of CPU; serialising (`SerializeObject`, `JObject.ToString`) overflowed the stack at about
|
||||
20,000 levels. The advisory's own mitigation example sets `MaxDepth = 128`; the 13.0.1 default
|
||||
is 64 (the changelog line was not retrieved; the 64 is read from the code above).
|
||||
|
||||
### 2.7 Protobuf
|
||||
|
||||
- Default recursion limit 100 in C++ (coded_stream.h:630 comment "100 by default"), C#
|
||||
(CodedInputStream.cs:57), Java (CodedInputStream.java:45) and upb (constants.h:11). C# rejects a
|
||||
non-positive limit (cs:142-144); upb stores it in a 16-bit field (`upb_DecodeOptions_MaxDepth`).
|
||||
- Skipped content: GHSA-735f-pc8j-v9w8 / CVE-2024-7254 (published 2024-09-19): in protobuf Java
|
||||
(full and lite), Kotlin and JRuby, "Parsing nested groups as unknown fields with
|
||||
DiscardUnknownFieldsParser or Java Protobuf Lite parser, or against Protobuf map fields,
|
||||
creates unbounded recursions". Fixed in 3.25.5, 4.27.5, 4.28.2. The advisory implies unknown
|
||||
(skipped) content had escaped the recursion limit until the fix.
|
||||
- No write-side limit was looked up.
|
||||
|
||||
### 2.8 CBOR, BSON, Go, simdjson
|
||||
|
||||
- ciborium: `recurse: 256` in `from_reader` and `deserializer_from_reader`
|
||||
(de/mod.rs:812, 854); `from_reader_with_recursion_limit` documents "Set a high recursion limit at
|
||||
your own risk (of stack exhaustion)!" (:819-822, 859-862). `recurse()` errors
|
||||
`RecursionLimitExceeded` at 0 (:64-74). No depth/recurs match in ser/mod.rs.
|
||||
- cbor2: advisory GHSA-3c37-wwvx-h642 / CVE-2026-26209 (published 2026-03-23, fixed 5.9.0):
|
||||
"uncontrolled recursion" in both the pure-Python and C decoders; PoC is 1000 nested `0x81`
|
||||
bytes raising `RecursionError`. The C decoder used `Py_EnterRecursiveCall` (Python's
|
||||
interpreter limit). Fix: `max_depth` parameter, default 400, in 5.9.0 (versionhistory.rst:172-173).
|
||||
6.0.0 (2026-04-28): decoder rewritten in Rust, iterative, depth "limited only by the available
|
||||
memory" (versionhistory.rst:138-140).
|
||||
- BSON: MongoDB documents "no more than 100 levels of nesting for BSON documents. Each object or
|
||||
array adds a level." The page does not state read vs write.
|
||||
- Go encoding/json: `maxNestingDepth = 10000` "limits the max nesting depth to prevent stack
|
||||
overflow" (scanner.go:146-148); `pushParseState` errors "exceeded max depth" when the parse stack
|
||||
exceeds it (:181-185). `checkValid` scans the whole input before decode (scanner.go:30), so every
|
||||
container, including ones the target type ignores, is counted (inferred from `checkValid` being
|
||||
the first step of `Unmarshal`; not read in decode.go). Encoder: `ptrLevel` over 1000 starts
|
||||
cycle detection, which is not a depth limit (encode.go:298-305).
|
||||
- simdjson: `constexpr size_t DEFAULT_MAX_DEPTH = 1024` (common_defs.h:49); `allocate(capacity,
|
||||
max_depth = DEFAULT_MAX_DEPTH)`. (The PHP binding defaults to 512 per the PHP manual.)
|
||||
|
||||
## 3. Read-side vs write-side, and skipped content
|
||||
|
||||
Enforces on write: rmp-serde (variant defined, no construction found: no); msgpack-python Packer
|
||||
(1024); @msgpack/msgpack Encoder (100); System.Text.Json (serializer 64, writer 1000); Go
|
||||
encoding/json (no depth limit; cycle detection only); MessagePack-CSharp (no); serde_json (no);
|
||||
ciborium (no); Newtonsoft (no match in JsonWriter.cs).
|
||||
|
||||
Counts skipped/ignored content: rmp-serde (yes, via `ignored_any` to `deserialize_any`);
|
||||
msgpack-python C unpacker (yes, `skip()` shares the stack); Go (scanner pre-pass, inferred);
|
||||
serde_json (apparently no: `ignore_value` is iterative and uncounted, inferred);
|
||||
MessagePack-CSharp (no: counting is by formatter contract); protobuf Java (unknown groups were
|
||||
unbounded before CVE-2024-7254).
|
||||
|
||||
## 4. Stack use per nesting level
|
||||
|
||||
No library documents bytes of stack per nesting level. What exists:
|
||||
- ciborium: "Set a high recursion limit at your own risk (of stack exhaustion)!"
|
||||
- Newtonsoft advisory: serialisation overflowed the default stack at about 20,000 levels
|
||||
(a count, not bytes; thread stack size not stated in the advisory).
|
||||
- cbor2 advisory PoC: 1000 nested arrays reached the Python recursion limit.
|
||||
- Rhai docs (search snippet, a different system): default call depth 64 in release, 8 in debug,
|
||||
an illustration that debug frames are larger.
|
||||
- CultLib's own measurement (from the question, not a prior-art source): Rust debug on 2 MiB
|
||||
aborts at about 408 containers, which is about 5 KiB per level (2 MiB / 408, inferred);
|
||||
release carries 1200+; Python near 1000; TS near 4000.
|
||||
- serde_json and rmp-serde pick 128 and 1024 respectively; neither source documents how the value
|
||||
was derived. Arrow Parquet Variant (docs.rs search result) says it picked MAX_NESTING_DEPTH 128
|
||||
"to match serde_json" because validation recurses.
|
||||
|
||||
## 5. Not retrieved
|
||||
|
||||
The rationale for 500 in MessagePack-CSharp; the Newtonsoft 13.0.1 release note; the fix depth
|
||||
chosen by msgpack-java and serde-json-wasm; protobuf write-side behaviour; decode.go's use of
|
||||
`checkValid`; MessagePack-CSharp writer code; simdjson's depth-error semantics.
|
||||
22
docs/research/py-msgpack-default/README.md
Normal file
22
docs/research/py-msgpack-default/README.md
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
# Python MessagePack default payload: history and probes (2026-10-11)
|
||||
|
||||
Serves `cultlib-gaps:ruling:py-msgpack-default` and `cultlib-gaps:cut_spec:cut-py-msgpack-default.r1`.
|
||||
|
||||
## How a JSON payload default got into .cc
|
||||
|
||||
1. Ghostlight `2531b42` (2026-05-06), the first consumer: "The JSONL store is deliberate bootstrap plumbing", msgpack optional.
|
||||
2. CultLib `b214daab` (2026-05-24) squashed in `python/cultcache-py` from GameCult/cultcache-py@9b4bbb8a with
|
||||
`define_document_type` already defaulting to `_json_payload_encoder`; msgpack was an optional extra and the README
|
||||
promised a standard-library-only bootstrap. JSON was the default because it was the only codec without msgpack.
|
||||
3. CultLib `a1ef58cb` (2026-06-13) made msgpack a hard dependency but kept the JSON default and the optional-import
|
||||
guards, so the default outlived its reason.
|
||||
4. Earlier history is unreachable (GameCult/cultcache-py no longer exists; CultLib holds only the squash). voidbot
|
||||
`search_history` found no discussion of the choice.
|
||||
|
||||
## Probes
|
||||
|
||||
- `probe1.py`, `probe2.py`: no runtime records a payload's format in the store, so a reader cannot tell JSON from
|
||||
MessagePack except by trying; a one-byte JSON payload `0`-`9` is valid MessagePack (48-57); a MessagePack map with
|
||||
a non-str/bytes key packs but `unpackb` refuses it.
|
||||
- `rmpprobe/`: `rmp_serde::from_slice` reads a JSON object's bytes as `Number(123)`, which is why Brokkr's daemon must
|
||||
read exactly one MessagePack value with a trailing-bytes check.
|
||||
47
docs/research/py-msgpack-default/probe1.py
Normal file
47
docs/research/py-msgpack-default/probe1.py
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
import json, sys, msgpack
|
||||
print(sys.version.split()[0], msgpack.version)
|
||||
def pk(v): return msgpack.packb(v, use_bin_type=True)
|
||||
def up(b): return msgpack.unpackb(b, raw=False)
|
||||
def jd(v): return json.dumps(v, ensure_ascii=False, sort_keys=True).encode()
|
||||
cases = {"dict": {"schema":"x","n":1}, "list":[1,2], "str":"hi", "digit":5, "neg":-3, "true":True, "null":None, "float":1.5, "bigdigit":12}
|
||||
print("== msgpack.unpackb on JSON payloads")
|
||||
for k,v in cases.items():
|
||||
b = jd(v)
|
||||
try: r = up(b); print(k, b, "->ACCEPTED", repr(r))
|
||||
except Exception as e: print(k, b, "->", type(e).__module__+"."+type(e).__name__, isinstance(e, ValueError), str(e)[:60])
|
||||
print("== json.loads on msgpack payloads")
|
||||
for k,v in cases.items():
|
||||
b = pk(v)
|
||||
try: r = json.loads(b.decode("utf-8")); print(k, b, "->ACCEPTED", repr(r))
|
||||
except Exception as e: print(k, b, "->", type(e).__name__, str(e)[:50])
|
||||
print("== semantic differences, value -> json roundtrip vs msgpack roundtrip")
|
||||
diffs = {"intkeys": {1:"a"}, "tuple": (1,2), "bytes": b"ab", "bigint": 2**70, "nan": float("nan"), "boolkey": {True:1}, "nested_intkey": {"a":{2:3}}, "set": {1,2}, "order": {"b":1,"a":2}}
|
||||
for k,v in diffs.items():
|
||||
out=[]
|
||||
try: out.append("json:"+repr(json.loads(jd(v))))
|
||||
except Exception as e: out.append("json:"+type(e).__name__)
|
||||
try: b=pk(v)
|
||||
except Exception as e: out.append("pack:"+type(e).__name__+":"+str(e)[:40]); print(k, out); continue
|
||||
try: out.append("mp:"+repr(up(b)))
|
||||
except Exception as e: out.append("unpack:"+type(e).__name__+":"+str(e)[:60])
|
||||
try: out.append("mp_nonstrict:"+repr(msgpack.unpackb(b, raw=False, strict_map_key=False)))
|
||||
except Exception as e: out.append("ns:"+type(e).__name__)
|
||||
print(k, out)
|
||||
print("== custom node classes")
|
||||
import collections, types
|
||||
class OnlyIter:
|
||||
def __iter__(self): return iter([1])
|
||||
for k,v in {"deque":collections.deque([1]), "mappingproxy":types.MappingProxyType({"a":1}), "userlist":collections.UserList([1]), "onlyiter":OnlyIter(), "frozenset":frozenset([1]), "userdict":collections.UserDict({"a":1})}.items():
|
||||
r=[]
|
||||
for name,f in (("pack",pk),("json",jd)):
|
||||
try: f(v); r.append(name+":ok")
|
||||
except Exception as e: r.append(name+":"+type(e).__name__)
|
||||
print(k, r)
|
||||
print("== JSON read recursion threshold")
|
||||
for d in (900, 1000, 3000, 5000, 10000, 100000):
|
||||
try: json.loads("["*d + "]"*d); print(d, "ok")
|
||||
except RecursionError: print(d, "RecursionError")
|
||||
print("== msgpack read deep")
|
||||
for d in (300, 1000, 2000, 100000):
|
||||
try: up(b"\x91"*d + b"\xc0"); print(d,"ok")
|
||||
except Exception as e: print(d, type(e).__module__, type(e).__name__)
|
||||
33
docs/research/py-msgpack-default/probe2.py
Normal file
33
docs/research/py-msgpack-default/probe2.py
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
# Brokkr-shaped flow at CultLib 9d7b5842: a store written by today's JSON default, then read by a MessagePack-default definition.
|
||||
import sys, tempfile, os, json, msgpack, timeit, dataclasses
|
||||
sys.path.insert(0, r"F:/Projects/CultLib/packages/cultcache-py/src")
|
||||
import cultcache_py as cc
|
||||
from cultcache_py.stores import SingleFileMessagePackBackingStore
|
||||
d = tempfile.mkdtemp(); path = os.path.join(d, "blender-editor.ccmp")
|
||||
def open_cache(defn):
|
||||
c = cc.CultCache.builder().register_document_type(defn).add_generic_store(SingleFileMessagePackBackingStore(path)).build()
|
||||
c.pull_all_backing_stores(); return c
|
||||
old = cc.define_document_type("brokkr.sync.var.v0")
|
||||
value = {"schema": "brokkr.sync.var.v0", "syncVarId": "v1", "enabled": True, "kind": "transform", "updatedAt": "2026-10-11T00:00:00Z"}
|
||||
c = open_cache(old); c.put(old, "sync/vars/v1", value)
|
||||
raw = msgpack.unpackb(open(path, "rb").read(), raw=False)
|
||||
print("store header", raw[0], "catalog entry", raw[1][0][:5] if raw[1] else None)
|
||||
print("record", raw[2][0][:3], "payload", raw[2][0][3][:40])
|
||||
# MessagePack-default reader, today's _messagepack pair standing in for the proposed default
|
||||
new = cc.define_document_type("brokkr.sync.var.v0", payload_encoder=lambda t: msgpack.packb(t, use_bin_type=True), payload_decoder=lambda b: msgpack.unpackb(b, raw=False))
|
||||
try: open_cache(new); print("new reader: ACCEPTED")
|
||||
except Exception as e: print("new reader refused:", type(e).__module__, type(e).__name__, str(e)[:80])
|
||||
# opt-in JSON pair reads it
|
||||
print("json opt-in reads:", open_cache(old).get(old, "sync/vars/v1") == value)
|
||||
# migration: read with JSON definition, write with MessagePack definition, same key
|
||||
v = open_cache(old).get(old, "sync/vars/v1"); c2 = cc.CultCache.builder().register_document_type(new).add_generic_store(SingleFileMessagePackBackingStore(path)).build()
|
||||
c2._state # not pulled: pull would fail on the JSON doc
|
||||
try:
|
||||
c2.put(new, "sync/vars/v1", v); print("put without pull ok")
|
||||
except Exception as e: print("put without pull:", type(e).__name__, str(e)[:80])
|
||||
print("after migration new reader reads:", open_cache(new).get(new, "sync/vars/v1") == value)
|
||||
# size and speed, one Brokkr-shaped document
|
||||
jb = json.dumps(value, ensure_ascii=False, sort_keys=True).encode(); mb = msgpack.packb(value, use_bin_type=True)
|
||||
print("bytes json", len(jb), "msgpack", len(mb))
|
||||
print("encode us json %.2f msgpack %.2f" % (timeit.timeit(lambda: json.dumps(value, ensure_ascii=False, sort_keys=True).encode(), number=100000)*10, timeit.timeit(lambda: msgpack.packb(value, use_bin_type=True), number=100000)*10))
|
||||
print("decode us json %.2f msgpack %.2f" % (timeit.timeit(lambda: json.loads(jb.decode()), number=100000)*10, timeit.timeit(lambda: msgpack.unpackb(mb, raw=False), number=100000)*10))
|
||||
8
docs/research/py-msgpack-default/rmpprobe/Cargo.toml
Normal file
8
docs/research/py-msgpack-default/rmpprobe/Cargo.toml
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
[package]
|
||||
name = "rmpprobe"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
[dependencies]
|
||||
rmp-serde = "=1.3.1"
|
||||
serde_json = "1"
|
||||
serde = "1"
|
||||
21
docs/research/py-msgpack-default/rmpprobe/src/main.rs
Normal file
21
docs/research/py-msgpack-default/rmpprobe/src/main.rs
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
fn main() {
|
||||
let json_obj = br#"{"enabled":true,"kind":"transform","schema":"brokkr.sync.var.v0"}"#;
|
||||
let r: Result<serde_json::Value, _> = rmp_serde::from_slice(json_obj);
|
||||
println!("rmp_serde on a JSON object payload: {:?}", r);
|
||||
let mp = rmp_serde::to_vec(&serde_json::json!({"schema":"x","n":1})).unwrap();
|
||||
println!("rmp_serde::to_vec of a json! object, first byte {:#04x} len {}", mp[0], mp.len());
|
||||
let j: Result<serde_json::Map<String, serde_json::Value>, _> = serde_json::from_slice(&mp);
|
||||
println!("serde_json on that MessagePack map: {:?}", j.map(|_| ()).map_err(|e| e.to_string()));
|
||||
let mut de = rmp_serde::Deserializer::from_read_ref(&json_obj[..]);
|
||||
let v: serde_json::Value = serde::Deserialize::deserialize(&mut de).unwrap();
|
||||
println!("one_value(json obj) = {:?}; one_value(mp) = {:?}", one_value(json_obj), one_value(&mp).map(|_| ()));
|
||||
println!("consumed {} of {} bytes, value {:?}", de.get_ref().len() as usize, json_obj.len(), v);
|
||||
}
|
||||
#[allow(dead_code)]
|
||||
fn one_value(bytes: &[u8]) -> Result<serde_json::Value, String> {
|
||||
let mut de = rmp_serde::Deserializer::new(std::io::Cursor::new(bytes));
|
||||
let v: serde_json::Value = serde::Deserialize::deserialize(&mut de).map_err(|e| e.to_string())?;
|
||||
let used = de.get_ref().position() as usize;
|
||||
if used != bytes.len() { return Err(format!("{} trailing bytes after the first MessagePack value", bytes.len() - used)); }
|
||||
Ok(v)
|
||||
}
|
||||
160
docs/research/py-slot-scalar-types-prior-art.md
Normal file
160
docs/research/py-slot-scalar-types-prior-art.md
Normal file
|
|
@ -0,0 +1,160 @@
|
|||
# Python slot scalar types vs the C# reference: facts and pointers
|
||||
|
||||
Fork served: cultlib-gaps: Python slot scalar types vs the C# reference's refusals, raised by cut-union-bounds-py.h1 undone.
|
||||
Date: 2026-10-11. Gathered by eyes-py-slot-scalar-types (read-only). Facts and pointers only; no recommendation.
|
||||
|
||||
Checkout caveat: line numbers below are the operator checkout at `main` 4ea296ae. cultcache-py's bounds cut lives on
|
||||
branch `hands/union-bounds-py` (head 4328ddb4); cultcache-ts's union codec lives on `hands/union-codec-ts`
|
||||
(absent from `main`: `git ls-tree HEAD packages/cultcache-ts/src` has no `codec.ts`).
|
||||
|
||||
## 1. In CultLib
|
||||
|
||||
### 1.1 The measured gap (the trigger)
|
||||
|
||||
Verdict `cultlib-gaps:verdict:cut-union-bounds-py.s1`, claim `scalar-type-parity-unproven`, outcome Unproven, no finding
|
||||
(spec did not promise it). Probe `cross.py g-` files, 168 cases, job1.log:
|
||||
- 13 scalar slots x 8 wrong values; agree 86; C# refuses and Python accepts 82; C# accepts and Python refuses 0.
|
||||
- String slots (Id, Box.Id, Text.Id, Text.Content, Image.Uri, Image.Alt, Comp.Name, Pending.Message, Tool.Name):
|
||||
Python accepts int, float, true, bin, array, map (refuses neither str nor nil, as C#).
|
||||
- Int slots (Version, Completed.SourceVersion, Tool.Uses, Part.Count): Python accepts float, str, true, bin, array, map
|
||||
and nil; int5 agrees.
|
||||
- All 8 container-shape slots (children list, record, slot list, outcomes list, arm slots, union x2, document) agree on
|
||||
every wrong value (64 shape replacements agree). So only scalar leaves differ.
|
||||
- Related earlier finding: `cultlib-gaps:finding:cut-union-codec-py.s2.python-decode-slot-strictness-differs`
|
||||
(Python accepts Tool wire value [1,['hammer',12]] as Text(content=12), C# refuses; Python refuses short Gem value,
|
||||
C# accepts with default). Resolved Deferred to `cultlib-gaps:cut_spec:cut-union-bounds-py.r1`.
|
||||
|
||||
### 1.2 C# reference: how a slot's scalar type is declared and refused
|
||||
|
||||
- Declaration is the C# member type plus `[Key(n)]`; there is no CultLib scalar-type vocabulary.
|
||||
`src/GameCult.Caching/README.md:16-27` (example), `src/GameCult.Caching/Contracts/cultcache-schema-compatibility.md:31-35`
|
||||
("A member's slot is its MessagePack `[Key(n)]` integer").
|
||||
- Registry checks are structural only (CultCache.cs:1015-1053, messages 1430-1461: needs [MessagePackObject], [Key] on every
|
||||
public member, no string keys, distinct keys, constructor shape).
|
||||
- The wrong-scalar refusal is made by MessagePack-CSharp's per-type formatter (external library, not CultLib code); CultLib
|
||||
contains no scalar-type check of its own. (Grep of `src/` for scalar/wrong-type checks found none; unions get a guard:
|
||||
`src/GameCult.Caching.MessagePack/CultUnionGuard.cs:44-50` refuses non-integer key, key outside Int32, undeclared key,
|
||||
nil arm slots.)
|
||||
- Published schema: each member's `TypeName` is generated from the member's CLR type,
|
||||
`CultCache.cs:647` `TypeName = CultSchemaTypeNames.FromType(member.MemberType)`; `CultSchemaTypeNames.cs:9-31` yields
|
||||
`System.String`, `System.Int32`, `System.String[]`, `System.Collections.Generic.List<...>`.
|
||||
Catalog members persisted with `Slot, MemberName, TypeName, IsReference, IsMany, TargetSchemaName, IndexAlias, IsName`
|
||||
(`CultDocumentMessagePackSerialization.cs:465-496`; `CultCache.cs:39,326`).
|
||||
- The catalog TypeName is load-bearing at open: `CultCache.cs:874-877` a persisted member with a different TypeName is an
|
||||
error (`slot N changed type 'A' -> 'B'`); an absent member is only a warning (`:863-872`). The catalog names a type; no
|
||||
code reads it to validate payload scalars on read.
|
||||
|
||||
### 1.3 cultcache-rs
|
||||
|
||||
- Slot types are the Rust field types, enforced by serde. `packages/cultcache-rs/cultcache-rs-derive/src/lib.rs`:
|
||||
`#[cultcache(key = N)]` per field (`:126-171`), `slot_codec` (`:177`) generates `Serialize` as a positional tuple with nil
|
||||
gaps and `Deserialize` by slot (`:213-258`), extra trailing slots skipped with `IgnoredAny` (`:233`, `:305`). `bytes` and
|
||||
`default` attributes are the only extras (`:175-176`). Union: `CultUnion` derive, arm key Int32, unknown key a decode error
|
||||
(`:87-97`, `:326-340`; `packages/cultcache-rs/README.md:187-196`).
|
||||
- No separate scalar-type vocabulary; no catalog-type derivation was looked for in rs here (not read).
|
||||
|
||||
### 1.4 cultcache-ts
|
||||
|
||||
- On `main`: no slot codec. `packages/cultcache-ts/src/document.ts:51-64` takes author-declared schema members and refuses
|
||||
an empty `typeName`; `types.ts:22-24` member has `slot`, `typeName`. `swarm-documents.ts:91-95` hand-writes
|
||||
`typeName: "string"|"long"|"object"`. Payload encode/decode is a user function (`types.ts:17-18`).
|
||||
- On branch `hands/union-codec-ts`, `packages/cultcache-ts/src/codec.ts`: typed leaf codecs `string`, `boolean`, `bytes`,
|
||||
`int32`, `int64`, `float32`, `float64`, `list`, `array`, `nullable`, each with the reference's `typeName`
|
||||
(`"System.String"`, `"System.Int32"`, ... lines 39-128) and `expect`/`refuse` on a wrong kind in both encode and decode
|
||||
(lines 31-42, 60-79). `SlotsCodec.members` derives the schema catalog from the slot codecs (lines 17-20). Header
|
||||
comment lines 5-8 say the reference refuses a store whose slot names another type.
|
||||
- Precedent in the mind: finding `cultlib-gaps:finding:cut-union-codec-ts.s1.codec-catalog-refused-by-reference` (High,
|
||||
Fixed 0882eee9): TS codec first derived `System.Object` for every slot; C# refused the whole store (7 slots).
|
||||
|
||||
### 1.5 cultcache-py today
|
||||
|
||||
- Slot = `DatabaseEntryField(name, key, default, codec, many)`; `codec` is a `SlotCodec` (encode/decode callables) only for
|
||||
nested record or union (`documents.py:61-92`). A scalar slot has no codec and no type: `encode_slot`/`decode_slot`
|
||||
return the value unchanged when `field.codec is None` (`:370-386`). Consumers write `("name", 0)` tuples, 3-tuples with a
|
||||
default, or `database_entry_field("body", 1, codec=..., many=True)` (`:276-283, 417-`;
|
||||
`packages/cultcache-py/tests/test_union_parity.py:25-59`; README `packages/cultcache-py/README.md:30,114-148`).
|
||||
- Python-side checks that exist: record is a list (`:394-396`), missing required slot (`:398-409`), union shape/arm key
|
||||
(`:313-325`, bool excluded by `_is_key` `:346-347`), many-slot is a list (`:383-384`), key >= 0 (`:88-89`).
|
||||
- Catalog: `define_database_entry_type` emits every member with `type_name="System.Object"` (`documents.py:244`) and
|
||||
`canonical_schema_json` built from the members (`:140-160`). `interop.py:38-46` instead hard-codes C# names
|
||||
(`System.String`, `System.String[]`) for its one fixed document.
|
||||
Same `System.Object` default earlier caused the TS finding in 1.4 (finding text: "the codec's default copies Python's
|
||||
define_database_entry_type, whose own stores would hit the same refusal").
|
||||
- Published schema carrying slot types for Python to read: the C# catalog carries `TypeName` per slot (1.2), persisted in
|
||||
the store and compared at open; `interop.py` shows Python reading catalog entries. No JSON Schema / CultNet schema with
|
||||
scalar types was found by grep in cultcache-py; `canonical_schema_json` in Python is built from `type_name` members.
|
||||
Whether a CultNet schema catalog outside the store (cultnet-py) exposes slot scalar types was not checked.
|
||||
|
||||
### 1.6 Probe: the C# reference opening Python-written stores (2026-10-11, imagination-cl-py-slot-types)
|
||||
|
||||
Section 1.5 left this untested. Python 3.13 and cultcache-py at main 2037dd44 wrote four single-file stores of
|
||||
`cultcache.interop-note`. The C# reference at 2037dd44 read them through
|
||||
`tests/GameCult.Caching.InteropPeer read --file` (dotnet sdk 10.0 on Yggdrasil, ygg-verify job1). The scripts and
|
||||
log are in the Imagination scratchpad `imagination-cl-py-slot-types/` (`write_stores.py`, `cmd.txt`, `job1.log`).
|
||||
|
||||
| Store | Python definition | Payload | C# result |
|
||||
|---|---|---|---|
|
||||
| a | `interop.py` (`define_document_type`, catalog members hand-typed `System.String`, `System.String[]`) | correct | opens, record read |
|
||||
| b | `define_database_entry_type`, same schema name and version as C# | correct | refused: `Persisted schema 'cultcache.interop-note' ... is incompatible ...: slot 0 changed type 'System.Object' -> 'System.String'; slot 1 ...` (every slot) |
|
||||
| c | as b | `title = 12` | refused at the catalog, as b |
|
||||
| d | as a (typed catalog) | `title = 12`, accepted by Python on write | refused at decode: `Record 'note:python-d' ... cannot be decoded ... Unexpected msgpack code 12 (positive fixint)` |
|
||||
|
||||
Mechanism (source read): the C# schema id is a SHA-256 of the semantic fingerprint (`CultCache.cs:656-658`), while
|
||||
Python's defaults to the type name. A Python-written entry therefore never matches by id. It resolves by schema name
|
||||
(`CultCache.cs:518-521`), and the content hashes differ, so `CompareSchemaShapes` runs and refuses any TypeName mismatch
|
||||
(`:874-877`). The refusal is thrown from the pull, so the C# cache does not open the store at all.
|
||||
|
||||
Consequences:
|
||||
- `define_database_entry_type` has no `members` or per-slot type parameter (`documents.py:214-229`). An ordinary
|
||||
Python consumer cannot write a store that a C# peer with the same schema name will open. The only way to get one is
|
||||
to hand-build `define_document_type` with typed members, as `interop.py` does. This is the TS finding
|
||||
`cut-union-codec-ts.s1.codec-catalog-refused-by-reference` again, this time in Python.
|
||||
- Store d: a wrong scalar that Python accepts on write makes the store unreadable to the C# reference.
|
||||
- A C# `object` member is also cataloged `System.Object`, and MessagePack-CSharp's object formatter accepts any
|
||||
value. Python's current default is therefore true of a C# `object` slot, and false for every typed C# slot.
|
||||
|
||||
Real consumer definitions for scale (source read): `cultnet_py/cultmesh_contracts.py:626-698`
|
||||
(`CultMeshSimulationFact`, a frozen dataclass annotated `str`, `int`, `float`, `str | None`, passed as `cls=`), and
|
||||
`repixelizer/src/repixelizer/verse_state.py:77-118` (dict values with no `cls`; `("value", 0)` and `("surface", 4)`
|
||||
hold whole nested structures in one slot, which is a genuine "any" slot). Python annotations do not carry the C# widths:
|
||||
`int` cannot say Int32 or Int64, and `float` cannot say Single or Double.
|
||||
|
||||
## 2. Prior art (dynamic host, declared field types)
|
||||
|
||||
| System | Types come from | Write | Read | Evidence |
|
||||
|---|---|---|---|---|
|
||||
| protobuf python | .proto IDL, generated classes | type-checked on field assignment (`TypeError`; `ValueError` out of range; bool rejected for int) | wire-type mismatch handling not stated in docs | protobuf.dev/reference/python/python-generated ("setting `foo` to a value of the wrong type will raise a `TypeError`"); `type_checkers.py` (IntValueChecker rejects bool `TypeError`, out of range `ValueError`; UnicodeValueChecker non-UTF-8 `ValueError`) https://raw.githubusercontent.com/protocolbuffers/protobuf/main/python/google/protobuf/internal/type_checkers.py ; proto3 guide: wire format "doesn't provide a way to detect fields encoded using one definition and decoded using another" https://protobuf.dev/programming-guides/proto3/ |
|
||||
| Apache Avro python | Avro schema (JSON), not host code | `DatumWriter.write` calls `validate(..., raise_on_error=True)` -> `AvroTypeException`; union branch picked by non-raising validate | reader does not validate values; checks schema resolution (`SchemaResolutionException`) and decodes by writer schema | https://raw.githubusercontent.com/apache/avro/main/lang/py/avro/io.py ; fastavro writer: `validator` parameter "validation will be done on the records" (opt-in) https://fastavro.readthedocs.io/en/latest/writer.html |
|
||||
| Thrift python | .thrift IDL, generated code | generated `write` calls `validate()` which checks required-field presence only (not scalar types); `writeFieldBegin` writes the given type unchecked | generated read emits `if ftype == TType.X:` ... `else: iprot.skip(ftype)`: a wrong wire type is silently skipped, field left unset | t_py_generator.cc `generate_py_struct_reader`, `generate_py_struct_required_validator` https://raw.githubusercontent.com/apache/thrift/master/compiler/cpp/src/thrift/generate/t_py_generator.cc ; TBinaryProtocol.py `writeFieldBegin`/`readFieldBegin` have no type check |
|
||||
| pydantic v2 | Python annotations in host code | validates input at construction / `validate_python` / `validate_json`; lax coercion default, strict opt-in per call, field or config | same entry points | https://pydantic.dev/docs/validation/latest/concepts/strict_mode/ ("Lax mode (default) coerces"; page does not say assignment or serialization validates) |
|
||||
| msgspec | Python annotations (Struct) in host code | docs (not retrieved; search snippet only): encode serializes values without enforcing annotations | decode validates against the `type=` and raises `ValidationError`; `array_like=True` encodes Struct as positional array | search result only, unverified: https://jcristharif.com/msgspec/usage.html (fetch returned 404 for usage/structs/supported-types pages) |
|
||||
| Cap'n Proto (pycapnp) | .capnp schema loaded at runtime (`capnp.load`) | assignment type-error behavior not documented on the fetched page | n/a (pointer-based, no parse step) | https://capnproto.github.io/pycapnp/capnp.html (schema loading: "much like loading a Python module") |
|
||||
| FlatBuffers python | .fbs schema, `flatc --python` generated typed accessors/builders | no runtime type validation stated on the fetched page | typed accessors read at fixed offsets; no value validation stated | https://flatbuffers.dev/languages/python/ |
|
||||
| MessagePack (msgpack-python) | none | none | none | no IDL; the format is schemaless (msgpack-python itself not fetched) |
|
||||
|
||||
Observed pattern in the fetched sources, stated as fact only:
|
||||
- Type source is an IDL/schema in protobuf, Avro, Thrift, Cap'n Proto, FlatBuffers; host-code annotations in pydantic and
|
||||
msgspec.
|
||||
- Write-side type checking: protobuf (assignment), Avro (default on), pydantic/msgspec (on construction/decode of input);
|
||||
Thrift write checks required presence only; fastavro opt-in.
|
||||
- Read-side: Avro reader trusts the writer schema; Thrift generated reader skips mismatched wire types; protobuf docs silent.
|
||||
|
||||
Not retrieved / unverified: pycapnp assignment error; FlatBuffers runtime checks; Thrift generated `validate` on type;
|
||||
msgspec authoritative statements; protobuf python parse behavior for wrong wire type.
|
||||
|
||||
## 3. Precedent in the mind
|
||||
|
||||
Tool `query` (`eureka-state`), semantic "python slot scalar type validation parity with C# reference", top_k 10, no schema
|
||||
filter (a `schemas` filter named Ruling/Resolution/Finding was refused: no such schema; schema names are
|
||||
`<campaign>.<kind>`-style, not enumerated here). Roots variants and cultlib-gaps both appeared; matched 40. Relevant hits:
|
||||
- `cultlib-gaps:finding:cut-union-codec-py.s2.python-decode-slot-strictness-differs` (PreExisting, Low, Deferred to
|
||||
union-bounds-py.r1): first record of Python decode strictness differing in both directions.
|
||||
- `cultlib-gaps:finding:cut-union-codec-ts.s1.codec-catalog-refused-by-reference` (High, Fixed): `System.Object` catalog
|
||||
types refused by the reference; evidence note says Python's `define_database_entry_type` default has the same shape.
|
||||
- `cultlib-gaps:finding:cut-union-codec-py.s1.missing-field-typed-item` (Fixed 36aa1a44): Python fixture declared slot 6 as
|
||||
Item union where C# says Node?; golden carried nil so tests passed.
|
||||
- `aetheria-release:follow_up:py-float-width-parity`: Python msgpack round-trip widens float32 to float64 (204 -> 284 bytes);
|
||||
float width is another undeclared-scalar-type consequence in Python (owner CultLib cultcache-py).
|
||||
- `cultlib-gaps:cut_spec:cut-slot-readonly-parity.r2` and `cut-slot-tolerance.r*`: read-only/unread-slot rules, adjacent.
|
||||
- No ruling or follow_up was returned that decides scalar-type parity for Python. A dedicated Ruling query was not run
|
||||
(schema id unknown; the only attempted names were refused).
|
||||
100
docs/research/py-typed-leaves-probe/PyLeavesProbe.cs
Normal file
100
docs/research/py-typed-leaves-probe/PyLeavesProbe.cs
Normal file
|
|
@ -0,0 +1,100 @@
|
|||
#nullable enable
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using GameCult.Caching;
|
||||
using GameCult.Caching.MessagePack;
|
||||
using MessagePack;
|
||||
using NUnit.Framework;
|
||||
|
||||
namespace GameCult.Caching.Tests.PyLeavesProbe
|
||||
{
|
||||
[MessagePackObject] public sealed class ProbeInner { [Key(0)] public string N = ""; [Key(1)] public float W; }
|
||||
[Union(0, typeof(ProbeCircle))] public interface IProbeShape { }
|
||||
[MessagePackObject] public sealed class ProbeCircle : IProbeShape { [Key(0)] public float R; }
|
||||
|
||||
[CultDocument("cultcache.py-leaves-probe", "cultcache.py_leaves_probe.v1")]
|
||||
[MessagePackObject]
|
||||
public sealed class ProbeDoc
|
||||
{
|
||||
[Key(0)] [CultName] public string Id = "";
|
||||
[Key(1)] public bool Flag;
|
||||
[Key(2)] public byte[] Blob = Array.Empty<byte>();
|
||||
[Key(3)] public int I;
|
||||
[Key(4)] public long L;
|
||||
[Key(5)] public float F;
|
||||
[Key(6)] public double D;
|
||||
[Key(7)] public int? MaybeI;
|
||||
[Key(8)] public List<string> Tags = new();
|
||||
[Key(9)] public string[] Names = Array.Empty<string>();
|
||||
[Key(10)] public object? Any;
|
||||
[Key(11)] public ProbeInner? Nested;
|
||||
[Key(12)] public List<ProbeInner> Items = new();
|
||||
[Key(13)] public IProbeShape? Shape;
|
||||
[Key(14)] public float[] Floats = Array.Empty<float>();
|
||||
[Key(15)] public float? MaybeF;
|
||||
}
|
||||
|
||||
[MessagePackObject] public sealed class S1 { [Key(0)] public string? V; }
|
||||
[MessagePackObject] public sealed class B1 { [Key(0)] public bool V; }
|
||||
[MessagePackObject] public sealed class Y1 { [Key(0)] public byte[]? V; }
|
||||
[MessagePackObject] public sealed class O1 { [Key(0)] public object? V; }
|
||||
[MessagePackObject] public sealed class LS1 { [Key(0)] public List<string>? V; }
|
||||
[MessagePackObject] public sealed class NI1 { [Key(0)] public int? V; }
|
||||
[MessagePackObject] public sealed class R1 { [Key(0)] public ProbeInner? V; }
|
||||
[MessagePackObject] public sealed class U1 { [Key(0)] public IProbeShape? V; }
|
||||
[MessagePackObject] public sealed class LI1 { [Key(0)] public List<int>? V; }
|
||||
|
||||
public class PyLeavesProbeTests
|
||||
{
|
||||
static readonly MessagePackSerializerOptions Options = CultDocumentMessagePackSerialization.OptionsFor(typeof(PyLeavesProbeTests).Assembly);
|
||||
|
||||
[Test]
|
||||
public void TypeNames()
|
||||
{
|
||||
var names = typeof(CultCache).Assembly.GetType("GameCult.Caching.CultSchemaTypeNames")!.GetMethod("FromType")!;
|
||||
foreach (var t in new[] { typeof(string), typeof(bool), typeof(byte[]), typeof(int), typeof(long), typeof(float), typeof(double),
|
||||
typeof(int?), typeof(bool?), typeof(float?), typeof(List<string>), typeof(string[]), typeof(List<int?>), typeof(object),
|
||||
typeof(ProbeInner), typeof(List<ProbeInner>), typeof(IProbeShape), typeof(float[]), typeof(List<List<string>>),
|
||||
typeof(Dictionary<string, int>), typeof(byte[][]) , typeof(List<byte[]>)})
|
||||
TestContext.Out.WriteLine($"TYPENAME {t} => {names.Invoke(null, new object[] { t })}");
|
||||
}
|
||||
|
||||
[TestCase("a-leaf-catalog.cc")]
|
||||
[TestCase("b-wrong-leaf.cc")]
|
||||
public async Task OpenPythonStore(string file)
|
||||
{
|
||||
var path = Path.Combine("/tmp/pyst", file);
|
||||
try
|
||||
{
|
||||
var cache = new CultCache();
|
||||
cache.AddBackingStore(new SingleFileMessagePackBackingStore(path));
|
||||
await cache.PullAllBackingStoresAsync();
|
||||
var doc = cache.AllEntries.OfType<ProbeDoc>().Single();
|
||||
var bytes = MessagePackSerializer.Serialize(doc, Options);
|
||||
TestContext.Out.WriteLine($"OPEN {file} OK id={doc.Id} F={doc.F:R} Shape={doc.Shape?.GetType().Name} Any={doc.Any?.GetType().Name} items={doc.Items.Count}");
|
||||
TestContext.Out.WriteLine($"CSHARP-REWRITE {file} {Convert.ToHexString(bytes).ToLowerInvariant()}");
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
TestContext.Out.WriteLine($"OPEN {file} REFUSED {e.GetType().Name}: {e.Message.Split('\n')[0]}");
|
||||
}
|
||||
}
|
||||
|
||||
static readonly string[] Values = { "05", "ff", "cb3ff8000000000000", "ca3fc00000", "c0", "c2", "c3", "a161", "d90161", "c40100", "90", "9101", "91a161", "80", "81a161a162", "920091ca3f800000" };
|
||||
|
||||
static string Try<T>(byte[] p) { try { var v = MessagePackSerializer.Deserialize<T>(p, Options); return "ok"; } catch { return "--"; } }
|
||||
|
||||
[Test]
|
||||
public void ScalarReads()
|
||||
{
|
||||
foreach (var v in Values)
|
||||
{
|
||||
var p = Convert.FromHexString("91" + v);
|
||||
TestContext.Out.WriteLine($"READ {v,-22} string={Try<S1>(p)} bool={Try<B1>(p)} bytes={Try<Y1>(p)} object={Try<O1>(p)} list<string>={Try<LS1>(p)} int?={Try<NI1>(p)} record={Try<R1>(p)} union={Try<U1>(p)} list<int>={Try<LI1>(p)}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
17
docs/research/py-typed-leaves-probe/README.md
Normal file
17
docs/research/py-typed-leaves-probe/README.md
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
# Python typed leaves: probe evidence (2026-10-11)
|
||||
|
||||
Serves `cultlib-gaps:ruling:py-slot-typed-leaves` and the specs
|
||||
`cultlib-gaps:cut_spec:cut-leaf-vectors-cs.r1` and `cut-py-typed-leaves.r1`.
|
||||
Run by the Imagination pass `imagination-cl-py-typed-leaves` on Yggdrasil at CultLib main 4ec4bfb7.
|
||||
|
||||
- `write_probe_stores.py` + `PyLeavesProbe.cs`: a Python store whose catalog uses the leaf type names
|
||||
(from `CultSchemaTypeNames.FromType`) is opened by the C# reference and its payload rewritten byte-identical,
|
||||
float32 included (except inside an `object` slot, where C# itself rewrites a fixint as uint8). Negative control:
|
||||
one slot named Int64 where C# has Int32 is refused ("slot 3 changed type").
|
||||
- `proto_leaves.py` + `run_vectors.py`: prototype leaves reproduce the C# numeric-leaves vectors (160 reads, 46 writes,
|
||||
the mixed record). `truth.py`: what C# accepts per slot type (byte[] accepts str; bool only false/true; record
|
||||
accepts []; nil in an int slot refused).
|
||||
- `perf.py`: float32 via a marker with packb-first fallback; a 1.5k-node record with float32 about 0.8 ms vs 0.1 ms.
|
||||
- `job1.log`: the verify run.
|
||||
|
||||
Scripts are probes, not a suite; they are kept so the next pass can rerun them.
|
||||
22
docs/research/py-typed-leaves-probe/perf.py
Normal file
22
docs/research/py-typed-leaves-probe/perf.py
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
import sys, time, msgpack
|
||||
sys.path.insert(0, sys.argv[1]); import proto_leaves as L
|
||||
# a HullData-like record: 20 float32 slots, strings, nested list of 200 small records
|
||||
rec = lambda i: ["part%d" % i, i, [L.Float32(0.5*i), L.Float32(1.5), L.Float32(2.5)], None]
|
||||
tree = ["id", 3, [L.Float32(float(i)) for i in range(20)], [rec(i) for i in range(200)]]
|
||||
plain = ["id", 3, [float(i) for i in range(20)], [["part%d" % i, i, [0.5*i,1.5,2.5], None] for i in range(200)]]
|
||||
N=300
|
||||
t=time.perf_counter(); [L.write(tree) for _ in range(N)]; a=time.perf_counter()-t
|
||||
t=time.perf_counter(); [msgpack.packb(plain, use_bin_type=True) for _ in range(N)]; b=time.perf_counter()-t
|
||||
t=time.perf_counter(); [msgpack.unpackb(msgpack.packb(plain)) for _ in range(N)]; c=time.perf_counter()-t
|
||||
print(f"walk-writer {a/N*1e6:.0f} us/rec, packb {b/N*1e6:.0f} us/rec, ratio {a/b:.1f}x; size {len(L.write(tree))} vs {len(msgpack.packb(plain))}")
|
||||
def pack_tree(t):
|
||||
try: return msgpack.packb(t, use_bin_type=True)
|
||||
except TypeError: return L.write(t)
|
||||
assert pack_tree(plain) == L.write(plain) == msgpack.packb(plain, use_bin_type=True)
|
||||
assert pack_tree(tree) == L.write(tree)
|
||||
t=time.perf_counter(); [pack_tree(plain) for _ in range(N)]; p=time.perf_counter()-t
|
||||
t=time.perf_counter(); [pack_tree(tree) for _ in range(N)]; q=time.perf_counter()-t
|
||||
print(f"pack_tree plain {p/N*1e6:.0f} us, float32 tree {q/N*1e6:.0f} us")
|
||||
try:
|
||||
pack_tree([object()])
|
||||
except TypeError as e: print("custom object:", e)
|
||||
87
docs/research/py-typed-leaves-probe/proto_leaves.py
Normal file
87
docs/research/py-typed-leaves-probe/proto_leaves.py
Normal file
|
|
@ -0,0 +1,87 @@
|
|||
"""Scratch prototype of cultcache_py.leaves, to establish mechanisms against the C# vectors. Not for the repo."""
|
||||
import math, struct, msgpack
|
||||
|
||||
class Refused(ValueError): pass
|
||||
|
||||
def kind(v):
|
||||
if v is None: return "nil"
|
||||
if isinstance(v, bool): return "a boolean"
|
||||
if isinstance(v, int): return "an integer"
|
||||
if isinstance(v, float): return "a float"
|
||||
if isinstance(v, str): return "a string"
|
||||
if isinstance(v, (bytes, bytearray, memoryview)): return "bytes"
|
||||
if isinstance(v, (list, tuple)): return "an array"
|
||||
if isinstance(v, dict): return "a map"
|
||||
return type(v).__name__
|
||||
|
||||
def refuse(what, v): raise Refused(f"expected {what}, found {kind(v)}")
|
||||
|
||||
class Float32: # tree marker: written as MessagePack float 32
|
||||
__slots__ = ("value",)
|
||||
def __init__(self, v): self.value = v
|
||||
|
||||
def int_to_f32(v: int) -> float:
|
||||
if abs(v) <= 2**53:
|
||||
return f32(float(v))
|
||||
m = abs(v); excess = m.bit_length() - 24
|
||||
kept = m >> excess; rest = m - (kept << excess); half = 1 << (excess - 1)
|
||||
if rest > half or (rest == half and kept & 1): kept += 1
|
||||
r = float(kept) * 2.0**excess # kept<=2^24 exact; scaling exact unless overflow
|
||||
return f32(-r if v < 0 else r)
|
||||
|
||||
def f32(x: float) -> float:
|
||||
try:
|
||||
return struct.unpack(">f", struct.pack(">f", x))[0]
|
||||
except OverflowError:
|
||||
return math.copysign(math.inf, x)
|
||||
|
||||
class Leaf:
|
||||
def __init__(self, type_name, enc, dec, value_type=False):
|
||||
self.type_name, self.encode, self.decode, self.value_type = type_name, enc, dec, value_type
|
||||
|
||||
def _int_leaf(name, what, lo, hi):
|
||||
def enc(v):
|
||||
if not isinstance(v, int) or isinstance(v, bool): refuse(what, v)
|
||||
if not lo <= v <= hi: raise Refused(f"expected {what}, found an integer out of range")
|
||||
return v
|
||||
return Leaf(name, enc, enc, True)
|
||||
|
||||
int32 = _int_leaf("System.Int32", "an int32", -2**31, 2**31-1)
|
||||
int64 = _int_leaf("System.Int64", "an int64", -2**63, 2**63-1)
|
||||
|
||||
def _f32_enc(v):
|
||||
if isinstance(v, bool) or not isinstance(v, (int, float)): refuse("a float32", v)
|
||||
return Float32(int_to_f32(v) if isinstance(v, int) else f32(v))
|
||||
def _f32_dec(v):
|
||||
if isinstance(v, bool) or not isinstance(v, (int, float)): refuse("a float32", v)
|
||||
return int_to_f32(v) if isinstance(v, int) else f32(v)
|
||||
float32 = Leaf("System.Single", _f32_enc, _f32_dec, True)
|
||||
def _f64(v):
|
||||
if isinstance(v, bool) or not isinstance(v, (int, float)): refuse("a float64", v)
|
||||
return float(v) # int > 2^53 rounds once (Python int->float is correctly rounded)
|
||||
float64 = Leaf("System.Double", _f64, _f64, True)
|
||||
def _str(v):
|
||||
if v is not None and not isinstance(v, str): refuse("a string", v)
|
||||
return v
|
||||
string = Leaf("System.String", _str, _str)
|
||||
def _bool(v):
|
||||
if not isinstance(v, bool): refuse("a boolean", v)
|
||||
return v
|
||||
boolean = Leaf("System.Boolean", _bool, _bool, True)
|
||||
|
||||
# writer: msgpack-python per value, float32 through a single-float packer, containers by header
|
||||
_P = msgpack.Packer(use_bin_type=True)
|
||||
_P32 = msgpack.Packer(use_bin_type=True, use_single_float=True)
|
||||
def write(tree) -> bytes:
|
||||
out = bytearray()
|
||||
stack = [tree]
|
||||
while stack:
|
||||
n = stack.pop()
|
||||
if isinstance(n, Float32): out += _P32.pack(n.value)
|
||||
elif isinstance(n, list):
|
||||
out += _P.pack_array_header(len(n)); stack.extend(reversed(n))
|
||||
elif isinstance(n, dict):
|
||||
out += _P.pack_map_header(len(n))
|
||||
for k, v in reversed(list(n.items())): stack.append(v); stack.append(k)
|
||||
else: out += _P.pack(n)
|
||||
return bytes(out)
|
||||
25
docs/research/py-typed-leaves-probe/run_vectors.py
Normal file
25
docs/research/py-typed-leaves-probe/run_vectors.py
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
import sys, struct, msgpack, math
|
||||
sys.path.insert(0, sys.argv[2])
|
||||
import proto_leaves as L
|
||||
d = sys.argv[1]
|
||||
leaves = {"int32": L.int32, "int64": L.int64, "float32": L.float32, "float64": L.float64}
|
||||
rows = msgpack.unpackb(open(d+"/reads.msgpack","rb").read(), raw=False)
|
||||
bad = 0
|
||||
for leaf, payload, ok, bits in rows:
|
||||
raw = msgpack.unpackb(payload, raw=False)[0]
|
||||
try:
|
||||
v = leaves[leaf].decode(raw); got = True
|
||||
b = struct.pack(">q", v) if leaf.startswith("int") else struct.pack(">d", v)
|
||||
except L.Refused: got, b = False, b""
|
||||
if got != ok or (ok and b != bits):
|
||||
bad += 1; print("READ DIFF", leaf, payload.hex(), "C#", ok, bits.hex(), "py", got, b.hex())
|
||||
print("reads", len(rows), "diffs", bad)
|
||||
wr = msgpack.unpackb(open(d+"/writes.msgpack","rb").read(), raw=False)
|
||||
bad = 0
|
||||
for leaf, text, want in wr:
|
||||
v = int(text) if leaf.startswith("int") else struct.unpack(">d", bytes.fromhex(text))[0]
|
||||
got = L.write([leaves[leaf].encode(v)])
|
||||
if got != want: bad += 1; print("WRITE DIFF", leaf, text, want.hex(), got.hex())
|
||||
print("writes", len(wr), "diffs", bad)
|
||||
mixed = L.write([L.string.encode("n1"), L.int32.encode(7), L.int64.encode(8), L.float32.encode(1.5), L.float64.encode(2.5)])
|
||||
print("mixed equal:", mixed == open(d+"/mixed-record.msgpack","rb").read(), mixed.hex())
|
||||
18
docs/research/py-typed-leaves-probe/truth.py
Normal file
18
docs/research/py-typed-leaves-probe/truth.py
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
import msgpack, struct, sys
|
||||
d = sys.argv[1]
|
||||
rows = msgpack.unpackb(open(d+"/reads.msgpack","rb").read(), raw=False)
|
||||
from collections import defaultdict
|
||||
t = defaultdict(list)
|
||||
for leaf, payload, ok, bits in rows:
|
||||
tok = payload[1:].hex()
|
||||
t[leaf].append((tok, ok, bits.hex()))
|
||||
for leaf, cases in t.items():
|
||||
print(leaf, "accepts", sum(ok for _,ok,_ in cases), "of", len(cases))
|
||||
print(" refused:", [tok for tok,ok,_ in cases if not ok])
|
||||
# float accepted from integer? int from float?
|
||||
f = msgpack.unpackb(open(d+"/float32-nan.msgpack","rb").read(), raw=False)
|
||||
for p, b in f:
|
||||
v = msgpack.unpackb(p)[0]
|
||||
bits = struct.pack(">d", v).hex()
|
||||
repacked = msgpack.packb([v], use_single_float=True).hex()
|
||||
print("nan in", p.hex(), "C# out", b.hex(), "py double", bits, "py repack f32", repacked)
|
||||
42
docs/research/py-typed-leaves-probe/write_probe_stores.py
Normal file
42
docs/research/py-typed-leaves-probe/write_probe_stores.py
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
"""Writes Python stores whose catalog carries the C# type names the proposed leaves would derive, for the C# reference to open."""
|
||||
import sys, os
|
||||
sys.path.insert(0, r"F:\Projects\CultLib\packages\cultcache-py\src"); sys.path.insert(0, os.path.dirname(__file__))
|
||||
import proto_leaves as L
|
||||
from cultcache_py import CultCache, SingleFileMessagePackBackingStore
|
||||
from cultcache_py.documents import define_document_type
|
||||
from cultcache_py.backing_store import CultCacheSchemaCatalogMember as M
|
||||
|
||||
NS = "GameCult.Caching.Tests.PyLeavesProbe"
|
||||
LIST = "System.Collections.Generic.List<{}>"
|
||||
MEMBERS = [ # slot, member, C# type name the leaf derives
|
||||
(0, "Id", "System.String"), (1, "Flag", "System.Boolean"), (2, "Blob", "System.Byte[]"),
|
||||
(3, "I", "System.Int32"), (4, "L", "System.Int64"), (5, "F", "System.Single"), (6, "D", "System.Double"),
|
||||
(7, "MaybeI", "System.Nullable<System.Int32>"), (8, "Tags", LIST.format("System.String")),
|
||||
(9, "Names", "System.String[]"), (10, "Any", "System.Object"), (11, "Nested", NS + ".ProbeInner"),
|
||||
(12, "Items", LIST.format(NS + ".ProbeInner")), (13, "Shape", NS + ".IProbeShape"),
|
||||
(14, "Floats", "System.Single[]"), (15, "MaybeF", "System.Nullable<System.Single>"),
|
||||
]
|
||||
F32 = lambda x: L.Float32(L.f32(x))
|
||||
def payload(doc_id):
|
||||
inner = lambda n, w: [n, F32(w)]
|
||||
return [doc_id, True, b"\x01\x02", 7, 2**40, F32(0.1), 0.1, None, ["a", "b"], ["x"], {"k": [1, "two"]},
|
||||
inner("n", 1.25), [inner("i0", 0.5), inner("i1", 2.0)], [0, [F32(3.5)]], [F32(1.0), F32(0.1)], F32(2.5)]
|
||||
|
||||
def write(path, members, tree_for):
|
||||
doc = define_document_type(
|
||||
"cultcache.py-leaves-probe", encode=lambda v: v, decode=lambda v: v,
|
||||
payload_encoder=L.write, payload_decoder=lambda b: b, name=lambda v: v[0],
|
||||
schema_name="cultcache.py-leaves-probe", schema_version="cultcache.py_leaves_probe.v1",
|
||||
members=[M(slot=s, member_name=n, type_name=t, is_name=(s == 0)) for s, n, t in members])
|
||||
if os.path.exists(path): os.remove(path)
|
||||
cache = CultCache.builder().register_document_type(doc).add_generic_store(SingleFileMessagePackBackingStore(path)).build()
|
||||
cache.pull_all_backing_stores()
|
||||
tree = tree_for(os.path.basename(path))
|
||||
cache.put(doc, tree[0], tree)
|
||||
print(path, "payload", L.write(tree).hex())
|
||||
|
||||
out = sys.argv[1]
|
||||
write(os.path.join(out, "a-leaf-catalog.cc"), MEMBERS, payload)
|
||||
# negative control: the int32 slot cataloged as the int64 leaf would name it
|
||||
wrong = [(s, n, "System.Int64" if s == 3 else t) for s, n, t in MEMBERS]
|
||||
write(os.path.join(out, "b-wrong-leaf.cc"), wrong, payload)
|
||||
310
docs/research/read-only-record-signal-prior-art.md
Normal file
310
docs/research/read-only-record-signal-prior-art.md
Normal file
|
|
@ -0,0 +1,310 @@
|
|||
# Read-Only Record Signal: Prior Art Survey
|
||||
|
||||
Facts file for Eureka question `variants:question:read-only-record-signal`: how a
|
||||
developer learns that a held record is read-only before a write is refused. Its
|
||||
options are (a) no new API, (b) a live query such as
|
||||
`CultCache.IsWritable(key)`, and (c) a list beside `ForeignRecords`. Eyes pass,
|
||||
2026-10-03. Facts and evidence pointers only; no recommendation.
|
||||
|
||||
Verification marks:
|
||||
|
||||
- **[fetched]** the claim was read on the cited page or source during this pass.
|
||||
- **[search]** the claim came from a search-result summary of the cited page,
|
||||
not a full read.
|
||||
- **[memory]** recalled from the cited source, not re-read in this pass.
|
||||
Treat it as unverified.
|
||||
|
||||
Signal shapes used below:
|
||||
|
||||
- **property**: a flag or state on the loaded object itself.
|
||||
- **query**: a call on the store, session or registry that answers at call time.
|
||||
- **list**: an enumeration of affected items, captured or computed.
|
||||
- **type**: the read-only status is a distinct static type.
|
||||
- **exception only**: nothing to ask; the write is the first signal.
|
||||
|
||||
## 0. Our design, for comparison
|
||||
|
||||
Source: branch `hands/variants-c2a` (head e9a66876), `src/GameCult.Caching/CultCache.cs`.
|
||||
|
||||
- `CultDocumentRegistry.Declares(string schemaId)` (line 738) is `internal`. Its
|
||||
comment: "The one answer to whether a cache may write, relabel or remove a
|
||||
record stored under this id ... Read live, so a type registered later that
|
||||
declares the id claims its records at their next write." [fetched]
|
||||
- `GetRequired<T>()` (line 631) registers lazily, so the set of declared ids can
|
||||
grow after load. [fetched]
|
||||
- The backing store already exposes `ForeignRecords` (line 3421), an
|
||||
`IReadOnlyList<CultForeignRecord>` "the last load found and carries untouched",
|
||||
set at load (`SetForeignRecords`, line 3599). `CultForeignRecord` (line 162)
|
||||
carries `Key`, `SchemaId`, `SchemaName`, `StoredAt`. [fetched]
|
||||
- The store also has a store-level `public bool IsReadOnly { get; }` (line 3419),
|
||||
fixed at construction. [fetched]
|
||||
- Main (162bd1fc) exposes `LastSchemaMigrationReports` (CultCache.cs:3136), whose
|
||||
entries carry no record key (per the question text). [fetched for the
|
||||
property; the no-key claim is the question's]
|
||||
|
||||
## 1. ORMs
|
||||
|
||||
### EF Core: no-tracking queries and keyless entity types
|
||||
|
||||
- Signal shape: **query** on the context, plus a **model** query.
|
||||
`context.Entry(e).State` returns an `EntityState`; `Detached` means "not being
|
||||
tracked by the DbContext", and its "Action on SaveChanges" is none.
|
||||
([Change Tracking](https://learn.microsoft.com/en-us/ef/core/change-tracking/), "Entity states" table) [fetched]
|
||||
- No-tracking results (`AsNoTracking`, or `QueryTrackingBehavior.NoTracking` on
|
||||
the context) are plain instances; changes to them are not persisted by
|
||||
`SaveChanges`. ([Tracking vs. No-Tracking](https://learn.microsoft.com/en-us/ef/core/querying/tracking), "No-tracking queries") [fetched]
|
||||
- Keyless entity types "are never tracked for changes in the DbContext and
|
||||
therefore are never inserted, updated or deleted"; their mapped object is
|
||||
"treated as a read-only query source".
|
||||
([Keyless Entity Types](https://learn.microsoft.com/en-us/ef/core/modeling/keyless-entity-types), "characteristics", "Mapping to database objects") [fetched]
|
||||
- Attempting to `Attach`/`Update` a keyless instance throws
|
||||
`InvalidOperationException` with `CoreStrings.KeylessTypeTracked`: "Unable to
|
||||
track an instance of type '{type}' because it does not have a primary key."
|
||||
([CoreStrings.KeylessTypeTracked](https://learn.microsoft.com/en-gb/dotnet/api/microsoft.entityframeworkcore.diagnostics.corestrings.keylesstypetracked?view=efcore-8.0)) [search]
|
||||
- The model answers keylessness: `IReadOnlyEntityType.IsKeyless` /
|
||||
`FindPrimaryKey() == null`. [memory]
|
||||
- Pitfall: modifying a no-tracking instance and calling `SaveChanges` is silent;
|
||||
nothing is written and nothing is thrown. `ChangeTracker.HasChanges()` returns
|
||||
false (Change Tracking page, closing tip). [fetched]
|
||||
|
||||
### Hibernate: @Immutable and read-only entities
|
||||
|
||||
- Signal shape: **query** on the session. `Session.isReadOnly(Object
|
||||
entityOrProxy)`: "Is the specified entity or proxy read-only?";
|
||||
`isDefaultReadOnly()` for the session default; `setReadOnly(Object, boolean)`
|
||||
flips one entity. ([Session javadoc 6.4](https://docs.hibernate.org/orm/6.4/javadocs/org/hibernate/Session.html)) [fetched]
|
||||
- Read-only can be set per session (`setDefaultReadOnly`), per query
|
||||
(`Query.setReadOnly(true)`, before execution) or per entity.
|
||||
([Hibernate 4.3 manual ch. 12, 12.1.2-12.1.3](https://docs.hibernate.org/orm/4.3/manual/en-US/html/ch12.html)) [fetched]
|
||||
- Write behaviour: changes to read-only entities are ignored at flush, no
|
||||
exception ("Hibernate will not update simple properties or updatable
|
||||
single-ended associations"); "A read-only entity can be deleted." (ch. 12.1) [fetched]
|
||||
- `@Immutable`: "Changes made in memory to the state of an immutable entity are
|
||||
never synchronized to the database. The changes are ignored, with no exception
|
||||
thrown." Immutable collections, by contrast, throw `HibernateException` on add
|
||||
or remove. ([@Immutable javadoc 6.2](https://docs.hibernate.org/orm/6.2/javadocs/org/hibernate/annotations/Immutable.html)) [fetched]
|
||||
- Bulk HQL updates of immutable entities: setting
|
||||
`hibernate.query.immutable_entity_update_query_handling_mode` chooses `warning`
|
||||
(default) or `exception`. ([QuerySettings 6.6](https://docs.hibernate.org/orm/6.6/javadocs/org/hibernate/cfg/QuerySettings.html)) [search]
|
||||
- Pitfall: the default for entity changes is silent loss; the read-only state is
|
||||
per session, so the same row is writable in another session.
|
||||
|
||||
### ActiveRecord: readonly?
|
||||
|
||||
- Signal shape: **property** on the record. `readonly?` "returns true if the
|
||||
record is marked as read-only"; `readonly!` marks it.
|
||||
([ActiveRecord::Core](https://api.rubyonrails.org/classes/ActiveRecord/Core.html)) [fetched]
|
||||
- Relation-level: `User.readonly` marks every loaded record;
|
||||
`users.first.save # => ActiveRecord::ReadOnlyRecord: User is marked as readonly`.
|
||||
([QueryMethods#readonly](https://api.rubyonrails.org/classes/ActiveRecord/QueryMethods.html)) [fetched]
|
||||
- Write behaviour: save, update or destroy raise `ActiveRecord::ReadOnlyRecord`. [fetched]
|
||||
- The flag is set when the record is loaded and lives on the in-memory object; it
|
||||
is not re-derived from the database or the model at write time. [memory]
|
||||
|
||||
## 2. Document stores and embedded databases
|
||||
|
||||
### Realm (Kotlin SDK): frozen objects
|
||||
|
||||
- Signal shape: **property** functions on the object.
|
||||
`BaseRealmObject.isFrozen()`: "A frozen object is tied to a specific version of
|
||||
the data in the realm and fields retrieved from this object instance will not
|
||||
update"; also `isManaged()` and `isValid()` ("the Realm is open and the
|
||||
underlying object has not been deleted").
|
||||
([BaseRealmObjectExt.kt L41-71](https://github.com/realm/realm-kotlin/blob/main/packages/library-base/src/commonMain/kotlin/io/realm/kotlin/ext/BaseRealmObjectExt.kt)) [fetched]
|
||||
- Recovery path: `MutableRealm.findLatest(obj)` returns a live, writable copy
|
||||
inside a write block, or `null` "if the object has been deleted".
|
||||
([MutableRealm.kt L50-56](https://github.com/realm/realm-kotlin/blob/main/packages/library-base/src/commonMain/kotlin/io/realm/kotlin/MutableRealm.kt)) [fetched]
|
||||
- Write behaviour: writing to a frozen object throws. Early SDKs threw a generic
|
||||
"Wrong transactional state ..." message; issue #297 asked for "Frozen objects
|
||||
cannot be modified" plus a pointer to `findLatest`.
|
||||
([realm-kotlin#297](https://github.com/realm/realm-kotlin/issues/297)) [fetched]
|
||||
- Pitfall: `isFrozen()` is stable for a given instance, but `isValid()` is live
|
||||
and can flip when another writer deletes the object.
|
||||
|
||||
### Couchbase Lite
|
||||
|
||||
- Signal shape: **type**. "By default, a document is immutable when it is read
|
||||
from the database. Use the Document.ToMutable() to create an updatable
|
||||
instance." `Document` versus `MutableDocument` makes the distinction static.
|
||||
([Couchbase Lite C# Documents](https://docs.couchbase.com/couchbase-lite/current/csharp/document.html), "Mutability") [fetched]
|
||||
- Write conflicts with other writers are handled at save by concurrency control
|
||||
(last-write-wins or fail-on-conflict) or a conflict handler. [memory]
|
||||
|
||||
### LiteDB
|
||||
|
||||
- Signal shape: **store-level option** only. Connection string `ReadOnly`
|
||||
("Open datafile in read-only mode"). No per-document read-only state found.
|
||||
([LiteDB connection string](https://www.litedb.org/docs/connection-string/)) [fetched]
|
||||
|
||||
### SQLite
|
||||
|
||||
- Signal shape: **store query**. `sqlite3_db_readonly(D,N)` "returns 1 if the
|
||||
database N of connection D is read-only, 0 if it is read/write, or -1 if N is
|
||||
not the name of a database". ([sqlite3_db_readonly](https://www.sqlite.org/c3ref/db_readonly.html)) [fetched]
|
||||
- `sqlite3_stmt_readonly()` answers whether a prepared statement writes. [memory]
|
||||
|
||||
### Core Data
|
||||
|
||||
- Signal shape: **store property** plus an open option.
|
||||
`NSPersistentStore.isReadOnly`: "A Boolean value that indicates whether the
|
||||
persistent store is read-only" (get/set);
|
||||
`NSReadOnlyPersistentStoreOption`: "A flag that indicates whether a store is
|
||||
treated as read-only", default false.
|
||||
([isReadOnly](https://developer.apple.com/documentation/coredata/nspersistentstore/isreadonly),
|
||||
[NSReadOnlyPersistentStoreOption](https://developer.apple.com/documentation/coredata/nsreadonlypersistentstoreoption)) [fetched]
|
||||
- Granularity: store, not object. An object's store is reachable through its
|
||||
`objectID.persistentStore`. [memory]
|
||||
|
||||
## 3. Serializers and schema evolution: unknown or foreign data
|
||||
|
||||
### Protocol Buffers
|
||||
|
||||
- Unknown fields: "Proto3 messages preserve unknown fields and include them
|
||||
during parsing and in the serialized output." They are lost on JSON
|
||||
serialization or when copying field by field into a new message.
|
||||
([proto3 guide, Unknown Fields](https://protobuf.dev/programming-guides/proto3/)) [fetched]
|
||||
- Signal shape for unknown fields: **property/list** on the message,
|
||||
`getUnknownFields()` returning an `UnknownFieldSet` (Java). [memory]
|
||||
- `Any` with a foreign type: **query** `any.is(Foo.class)` returns a boolean;
|
||||
`unpack(Class)` throws `InvalidProtocolBufferException`.
|
||||
([Any javadoc](https://protobuf.dev/reference/java/api-docs/com/google/protobuf/Any.html)) [fetched]
|
||||
- Granularity: fields inside a known message, or one embedded payload; no
|
||||
ownership or write-permission concept.
|
||||
|
||||
### Apache Avro
|
||||
|
||||
- Writer fields absent from the reader schema are dropped: "the writer's value
|
||||
for that field is ignored". A union branch the reader lacks: "if none match, an
|
||||
error is signalled". ([Avro 1.11.1 spec, Schema Resolution](https://avro.apache.org/docs/1.11.1/specification/)) [fetched]
|
||||
- Signal shape: **exception only** for unresolvable data; nothing marks a record
|
||||
as carrying dropped fields.
|
||||
|
||||
### Unity SerializeReference: missing types (closest found to CultCache)
|
||||
|
||||
- A host asset holds managed references whose recorded type (assembly,
|
||||
namespace, class) is not in the current project.
|
||||
- Signal shape: **query** returning a bool and a **list**.
|
||||
`SerializationUtility.HasManagedReferencesWithMissingTypes(Object obj)`: "returns
|
||||
true if one or more managed references is missing its type."
|
||||
`GetManagedReferencesWithMissingTypes` returns the
|
||||
`ManagedReferenceMissingType` entries: `assemblyName`, `className`,
|
||||
`namespaceName`, `referenceId`, `serializedData`.
|
||||
([HasManagedReferencesWithMissingTypes](https://docs.unity3d.com/6000.0/Documentation/ScriptReference/SerializationUtility.HasManagedReferencesWithMissingTypes.html),
|
||||
[ManagedReferenceMissingType](https://docs.unity3d.com/6000.0/Documentation/ScriptReference/ManagedReferenceMissingType.html)) [fetched]
|
||||
- Behaviour: the field stays null, the persisted state is retained on resave, and
|
||||
if the type returns later, "the state of the Managed Reference object can be
|
||||
recovered". `ClearManagedReferenceWithMissingType` removes one deliberately.
|
||||
([GetManagedReferencesWithMissingTypes](https://docs.unity3d.com/ScriptReference/SerializationUtility.GetManagedReferencesWithMissingTypes.html)) [search]
|
||||
- Both calls are made on demand against a host object; the docs do not say the
|
||||
list is cached at load. A sibling `PrefabUtility.HasManagedReferencesWithMissingTypes`
|
||||
exists for prefab instances. [search]
|
||||
|
||||
### .NET DataContractSerializer: IExtensibleDataObject
|
||||
|
||||
- Unknown members round-trip through an opaque `ExtensionDataObject` property on
|
||||
the object. It cannot be inspected, so it is a carrier, not a signal. [memory]
|
||||
|
||||
## 4. File systems and object stores
|
||||
|
||||
### POSIX access(2) and TOCTOU
|
||||
|
||||
- Signal shape: **query** on the path. `access(path, W_OK)` fails with `EROFS` on
|
||||
a read-only file system. The check uses the real UID/GID, "rather than the
|
||||
effective IDs as is done when actually attempting an operation".
|
||||
([access(2)](https://man7.org/linux/man-pages/man2/access.2.html)) [fetched]
|
||||
- Pitfall: checking before `open(2)` "creates a security hole" because the state
|
||||
can change between check and use (access(2) NOTES). [fetched]
|
||||
- Python's `os.access` docs repeat the warning and show the EAFP alternative: try
|
||||
the `open` and catch `PermissionError`.
|
||||
([os.access](https://docs.python.org/3/library/os.html#os.access)) [fetched]
|
||||
- CWE-367 defines TOCTOU as checking "the state of a resource before using that
|
||||
resource, but the resource's state can change between the check and the use".
|
||||
Mitigations listed: drop the check, make check and use atomic, lock before the
|
||||
check, recheck after use, shrink the window.
|
||||
([CWE-367](https://cwe.mitre.org/data/definitions/367.html)) [fetched]
|
||||
|
||||
### Amazon S3 Object Lock
|
||||
|
||||
- Signal shape: **metadata on the object version**, read with HEAD/GET.
|
||||
`HeadObject` returns `x-amz-object-lock-mode` (`GOVERNANCE | COMPLIANCE`),
|
||||
`x-amz-object-lock-retain-until-date` and `x-amz-object-lock-legal-hold`,
|
||||
"only returned if the requester has the `s3:GetObjectRetention` permission"
|
||||
(legal hold: `s3:GetObjectLegalHold`). Dedicated calls exist as well
|
||||
(`GetObjectRetention`, `GetObjectLegalHold`).
|
||||
([HeadObject](https://docs.aws.amazon.com/AmazonS3/latest/API/API_HeadObject.html)) [fetched]
|
||||
- Write behaviour: a versioned DELETE of a locked version returns `403 Access
|
||||
Denied`; a simple DELETE succeeds and adds a delete marker. A PUT to the same
|
||||
key succeeds and creates a new version; the old version stays locked. Governance
|
||||
mode can be bypassed with `s3:BypassGovernanceRetention` plus the
|
||||
`x-amz-bypass-governance-retention:true` header.
|
||||
([Object Lock](https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-lock.html), "How deletes work", "Retention modes") [fetched]
|
||||
- Pitfalls: the signal depends on read permission (absent header does not mean
|
||||
unlocked); legal holds can be "freely placed and removed" by anyone with
|
||||
`s3:PutObjectLegalHold`, so the answer can change between HEAD and DELETE; under
|
||||
variable retention the retain-until date "moves forward as time passes" while an
|
||||
event hold is on. (Object Lock page, "Legal holds", "Retain-until-date behavior") [fetched]
|
||||
|
||||
### Git LFS lockable files
|
||||
|
||||
- Ownership signal enforced through the file system: files marked lockable "are
|
||||
made read-only in the working copy when not locked by the current user"
|
||||
(`lfs.setlockablereadonly`, default true).
|
||||
([git-lfs-config](https://github.com/git-lfs/git-lfs/blob/main/docs/man/git-lfs-config.adoc), L448-455) [fetched]
|
||||
- The authoritative check is server-side at push: Git LFS "verifies that pushes
|
||||
don't alter files locked by others".
|
||||
([git-lfs-lock](https://github.com/git-lfs/git-lfs/blob/main/docs/man/git-lfs-lock.adoc)) [fetched]
|
||||
- Pitfall: the read-only bit reflects lock state as of the last checkout or lock
|
||||
command; `chmod` defeats it locally, and the push check decides. [memory for the
|
||||
staleness; the push check is fetched]
|
||||
|
||||
## 5. Collections (the type-system version of the same question)
|
||||
|
||||
- .NET `ICollection<T>.IsReadOnly`: a **property**. Read-only here "does not
|
||||
indicate whether individual elements of the collection can be modified"; an
|
||||
array cast to `ICollection<T>` reports true while its elements stay writable.
|
||||
Mutators throw `NotSupportedException`.
|
||||
([ICollection<T>.IsReadOnly](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.icollection-1.isreadonly)) [fetched; the exception is memory]
|
||||
- Java `Collection`: **exception only**. Mutators are "optional operations" that
|
||||
throw `UnsupportedOperationException`; the interface has no query for
|
||||
modifiability. ([Collection, Java 21](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/Collection.html)) [fetched]
|
||||
|
||||
## 6. Summary table
|
||||
|
||||
| System | Granularity | Signal shape | Write when read-only | Can the answer go stale? |
|
||||
|---|---|---|---|---|
|
||||
| EF Core no-tracking | entity instance | query (`Entry(e).State`) | silent no-op | yes, attach/detach changes it |
|
||||
| EF Core keyless | entity type | model query (`IsKeyless`) [memory] | throws on attach/update | no (model is fixed after build) |
|
||||
| Hibernate read-only | entity in session | query (`Session.isReadOnly(e)`) | ignored at flush; delete allowed | per session; settable |
|
||||
| Hibernate @Immutable | entity type | annotation | ignored, no exception; bulk HQL warns or throws | no |
|
||||
| ActiveRecord | record | property (`readonly?`) | raises `ReadOnlyRecord` | set at load, not re-derived [memory] |
|
||||
| Realm frozen | object version | property (`isFrozen()`, `isValid()`) | throws; `findLatest` for a writable copy | `isValid` is live |
|
||||
| Couchbase Lite | document | type (`Document` vs `MutableDocument`) | n/a, no mutators | no |
|
||||
| LiteDB, SQLite, Core Data | store or database | option plus store query/property | refused by the store | rarely |
|
||||
| protobuf unknown fields / Any | field / payload | property list [memory] / `is()` query | preserved / unpack throws | no |
|
||||
| Avro | field / union branch | exception only | field dropped / error | no |
|
||||
| Unity missing types | managed reference in a host | query (bool) plus list (key, type name, data) | data preserved; recoverable when type returns | answered on demand |
|
||||
| POSIX access(2) | path | query | open fails | yes, TOCTOU (documented) |
|
||||
| S3 Object Lock | object version | metadata via HEAD/GET | versioned delete 403; PUT makes a new version | yes, holds and event holds change |
|
||||
| Git LFS lockable | file | file-system read-only bit | push refused by server | yes, as of last checkout |
|
||||
| .NET ICollection | collection | property | `NotSupportedException` | no |
|
||||
| Java Collection | collection | exception only | `UnsupportedOperationException` | n/a |
|
||||
|
||||
Patterns observed, stated as facts across the sources above:
|
||||
|
||||
- Every system that offers an advance signal still has the write path decide:
|
||||
EF Core, Realm, ActiveRecord, S3, Git LFS and POSIX all refuse or ignore at the
|
||||
write regardless of what a check said.
|
||||
- Where the read-only state can change after it was observed (POSIX permissions,
|
||||
S3 holds, Git LFS locks, EF Core attach/detach), the documentation either warns
|
||||
of TOCTOU (POSIX, Python, CWE-367) or places the authoritative check at the
|
||||
write (S3, Git LFS push).
|
||||
- Silent-ignore write behaviour (Hibernate entities, EF Core no-tracking) is the
|
||||
case where the advance signal is the only signal; Hibernate added an opt-in
|
||||
exception mode for bulk updates.
|
||||
- The closest analog to records under an unregistered schema id (Unity missing
|
||||
types) exposes both an on-demand bool query and an on-demand list carrying the
|
||||
reference id and the recorded type name, and recovers the data when the type
|
||||
returns.
|
||||
- Store-level read-only (LiteDB, SQLite, Core Data, and CultCache's own
|
||||
`CacheBackingStore.IsReadOnly`) is a property or query on the store, not on the
|
||||
record.
|
||||
114
docs/research/ts-decode-owner-structural.md
Normal file
114
docs/research/ts-decode-owner-structural.md
Normal file
|
|
@ -0,0 +1,114 @@
|
|||
# TS document-payload decode owner: making the rule structural
|
||||
|
||||
Research for `cultlib-gaps:cut_spec:cut-union-codec-ts.r2` and
|
||||
`cultlib-gaps:question:ts-payload-opaque-type`. Body: branch `hands/union-codec-ts` at
|
||||
`294469e3`. Gathered 2026-10-11 by Imagination (`imagination-cl-decode-owner-ts`).
|
||||
|
||||
## The rule and why a guard does not hold it
|
||||
|
||||
The rule: one owner decodes a CultCache document payload, and it always has the
|
||||
definition. Five Soul passes on `cut-union-codec-ts` each found another payload reader
|
||||
outside the owner (s3 mesh readers, s4 RUDP put and browser, s5 provider command and the
|
||||
browser default path). The s5 guard (`payload-decode-owner.test.ts`, one per mesh package)
|
||||
bans the `@msgpack/msgpack` specifier. Soul's mutant S1 put `decodeWireValue(document.payload)`
|
||||
at the RUDP put site and the guard passed: a plain decode under another name is not a
|
||||
specifier. As long as a payload is typed `Uint8Array`, every byte decoder in the program
|
||||
accepts it, so the rule can only be policed by text.
|
||||
|
||||
## What the type system can enforce (probes)
|
||||
|
||||
Run with TypeScript 6.0.3 (`F:\Projects\Heimdall\node_modules\typescript`) against
|
||||
`@msgpack/msgpack` 3.1.3 source, `strict`. CultLib pins TypeScript `^5.9`; the rules used
|
||||
below (structural assignability, intersection widening) are unchanged between them, and
|
||||
Hands re-confirms on 5.9 with the compile-fail fixture the spec names. Scratch files:
|
||||
`scratchpad/brand/probe.ts`, `probe2.ts`, `probe3.ts`, `runtime.cjs`, `runtime2.cjs` in the
|
||||
session scratchpad (not committed).
|
||||
|
||||
| Shape of `payload` | `decode(p)` | `decodeWireValue(p)` | `const u: Uint8Array = p` | Notes |
|
||||
|---|---|---|---|---|
|
||||
| `Uint8Array & { __brand: true }` | compiles | compiles | compiles | Intersection brand leaks: still a Uint8Array. |
|
||||
| `Uint8Array & { [uniqueSymbol]: true }` | compiles | compiles | compiles | Same leak. |
|
||||
| unique-symbol brand plus a wire decoder typed `bytes & { [brand]?: never }` | compiles (raw msgpack) | error | compiles | The wire decoder refuses the brand, but `const u: Uint8Array = p` (no cast) or any helper taking `Uint8Array` strips it, and then `decodeWireValue(u)` compiles. Laundered with no greppable escape. |
|
||||
| class with ES `#bytes` field | error | error | error | Nominal. Forgery by object literal is an error. Escapes: `as any`, `as unknown as`, or a named method. Runtime: `decode(wrapper)` throws `RangeError: Offset is outside the bounds of the DataView`; `encode({ payload: wrapper })` silently writes an empty map (`81 a7 payload 80`), so a JS consumer that re-encodes a record corrupts it. Two installed copies of the package are incompatible at type level and at `instanceof`. |
|
||||
| opaque object type over the same runtime Uint8Array, keyed by a string property: `interface DocumentPayload { readonly "cultcache.documentPayload": true; readonly byteLength: number }` | error | error | error | `ArrayLike<number>`, `new Uint8Array(p)`, a `Uint8Array` helper param, a generic `T extends ArrayLike<number>` and a destructured field all refuse it. Forgery from bytes is an error. Escapes that compile: a named unwrap function, `as any`, `as unknown as Uint8Array`, a helper with an `unknown` parameter that casts inside. Runtime value is unchanged: frames still encode the bytes, JS consumers still work. Two package copies are structurally compatible (a unique-symbol key would make them incompatible). |
|
||||
|
||||
Conclusion: an intersection or unique-symbol brand on `Uint8Array` cannot hold the rule,
|
||||
because widening to `Uint8Array` is implicit. A class holds it but changes the runtime value
|
||||
and adds a silent-corruption hazard for JS consumers. The string-keyed opaque object type
|
||||
holds it at compile time with no runtime change. Every remaining way past it is a cast or a
|
||||
named call that a grep finds.
|
||||
|
||||
## Read sites at 294469e3
|
||||
|
||||
Document-payload reads (bytes typed `Uint8Array` that are a document's payload):
|
||||
|
||||
| Site | Today |
|
||||
|---|---|
|
||||
| `packages/cultcache-ts/src/cult-cache.ts:276-277, 457-458, 604-605` via `#createFormatter` 679-694 | the cache's own reads, through the definition |
|
||||
| `packages/cultcache-ts/src/document.ts:86-97` | `decodeDocumentPayload(definition | undefined, …)`: the `undefined` door is plain msgpack |
|
||||
| `packages/cultcache-ts/src/single-file-messagepack-backing-store.ts:331, 352-365` | `inferSchemaVersionFromPayload`: plain decode to recover a missing catalog version |
|
||||
| `packages/cultcache-ts/src/cult-cache-inspector.ts:289-291` | `previewPayload`: plain decode for inspection |
|
||||
| `packages/cultnet-ts/src/replication.ts:343-345, 433-440` | `decodeDocumentValue` through `resolveDocumentFormatter` (a second owner-shaped function) |
|
||||
| `packages/cultmesh-ts/src/index.ts:2641, 6334, 6643, 6682, 6782-6794` | through `decodeDocumentPayload`; the `string` schema overloads pass `undefined` (plain) |
|
||||
| `packages/cultmesh-ts/src/provider-session-wire.ts:158-171` | `decodeWireValue(document.payload)`: plain, provider command document |
|
||||
| `packages/cultmesh-browser/src/index.ts:763-776` | `decodeCultNetPayload(record, formatter?)`: plain without a formatter |
|
||||
| `packages/cultnet-ts/src/idunn-runtime-authority.ts:320-330, 603-605` | hand reader of a CultCache v1 file and fixed slot arrays (never sees a record type) |
|
||||
|
||||
`decodeWireValue` (cultnet-ts/wire) source consumers: 7. Legitimate (not a document payload): 5,
|
||||
namely cultmesh-ts `index.ts:5960` (frame), `provider-session-wire.ts:130` (provider-session
|
||||
operation payload), `:143` (connect evidence), cultmesh-browser `index.ts:788` (operation
|
||||
payload), `:826` (frame). Document payloads: 2 (`provider-session-wire.ts:165`, browser
|
||||
`index.ts:775`). Tests: 4 document-payload reads (`cultmesh.test.ts:3348, 3451`,
|
||||
`provider-rudp-transport.test.ts:49`, `cultmesh-browser.test.ts:981`), the rest frames and
|
||||
operation payloads.
|
||||
|
||||
Document payloads also arrive as `CultMeshRealtimeFrame.payload`
|
||||
(`packages/cultmesh-ts/src/realtime-wire.ts:51-59`): cultmesh-ts never decodes it, consumers
|
||||
do (StreamPixels `overlay-quic-publisher.test.ts:54-60` through the definition's formatter).
|
||||
|
||||
## Consumers outside CultLib (rg under F:\Projects, excluding CultLib clones, vendor, node_modules)
|
||||
|
||||
Hand payload decodes of CultNet records or store envelopes: weksa
|
||||
`scripts/weksa-rudp-command.cjs:133, 285` (`decode(message.document.payload)`), Heimdall
|
||||
`src/runtime-presence.ts:83`, `src/provider-health-identity.ts:53, 172` (builds and decodes a
|
||||
`CultCacheEnvelope` by hand), StreamPixels `apps/web/lib/server/idunn-runtime-launch.test.ts:37`,
|
||||
AetheriaEve `scripts/aetheria-browser-provider-witness.ts:55, 62, 161`
|
||||
(`decodeCultNetPayload` with no formatter). JS daemons that build `document_put_raw` records
|
||||
with pre-encoded or signed `Uint8Array` payloads and call `encodeCultNetMessageForWire`:
|
||||
Stonks `src/idunn-rudp.cjs`, Vili `scripts/idunn-rudp.cjs`, VoidBot
|
||||
`scripts/publish-idunn-rudp-health.cjs`, weksa `scripts/idunn-rudp-health.cjs`, Bifrost
|
||||
`tools/persona-feedback-idunn-health.mjs`. All consume vendored pins, so a change reaches them
|
||||
only on a pin bump.
|
||||
|
||||
## Test wiring at 294469e3
|
||||
|
||||
- cultcache-ts `package.json:26` runs an explicit list (`cult-cache`, `union-parity`);
|
||||
`test/decode-document-payload.test.ts` is compiled and never run.
|
||||
- cultnet-ts, cultmesh-ts and cultmesh-browser run `dist-test/test/*.test.js`;
|
||||
cultnet-ts `test/interop/*.test.ts` runs under `test:interop` and the interop workflow.
|
||||
- No workflow runs cultcache-ts's tests: `.github/workflows/cultmesh-portability.yml:107-119`
|
||||
runs cultnet-ts, cultmesh-browser and cultmesh-ts; `cultnet-interop.yml:112` only builds
|
||||
cultcache-ts. `scripts/run-typescript-workspaces.mjs test` covers all four, but no workflow
|
||||
calls it.
|
||||
|
||||
## Prior art: how decoding is kept schema-bound
|
||||
|
||||
- **protobuf-ts `Any`**: a message packed into a bytes field plus a `typeUrl`.
|
||||
`Any.unpack(any, type: IMessageType<T>): T` needs the message type; `Any.contains(any,
|
||||
type)` asks first; JSON reading needs a `typeRegistry`. The bytes stay publicly readable;
|
||||
the API is shaped so the typed path is the convenient one, not the only one.
|
||||
- **avsc (Avro JS)**: decoding is a method of a schema-built type
|
||||
(`Type.forSchema(schema).fromBuffer(buf)`); Avro binary carries no schema, so there is no
|
||||
schema-less decoder to misuse. The format itself enforces the owner.
|
||||
- **msgpack-javascript `ExtensionCodec`**: typed decoding of extension types is opt-in per
|
||||
call (`decode(bytes, { extensionCodec })`); an unregistered extension decodes to
|
||||
`ExtData` (`src/ExtensionCodec.ts:74, 86, 104`) rather than refusing, and plain `decode`
|
||||
stays available. It shows the failure mode: the schema-bound path is optional and nothing
|
||||
refuses the plain one. Its `DecoderOptions` have no `maxDepth` (encode defaults to 100).
|
||||
- **serde_json `RawValue`**: an unparsed span kept opaque (`&RawValue`), read as text only by
|
||||
the explicit `.get()`, or parsed into a typed value with `from_str`. The closest analogue to
|
||||
an opaque payload type with a named escape.
|
||||
|
||||
The pattern that holds the rule without trusting callers: the bytes travel as a type no plain
|
||||
decoder accepts, the typed decoder takes the schema as a required argument, and the escape to
|
||||
raw bytes is a named call.
|
||||
73
docs/research/windows-store-replace-prior-art.md
Normal file
73
docs/research/windows-store-replace-prior-art.md
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
# Windows store replace: prior art and probe (2026-10-03)
|
||||
|
||||
This research backs `variants:question:windows-store-replace-primitive`. It came from an Imagination pass during the variants campaign. The probe source and raw results lived in that session's scratchpad (`win-replace/probe/Replacers/Replacers.cs`, `result-net10.txt`, `result-mono.txt`).
|
||||
|
||||
## Problem
|
||||
|
||||
On Windows, CultCache C# replaces a single-file store with `File.Replace`, which calls Win32 `ReplaceFile`. While that replace runs, a lock-free reader can find nothing at the path, and the store opens as empty. Under the h1 cut's probe on Starfire, 1,722 of 17,313 opens came back empty. On Linux, which replaces with `rename`, 0 of 6,252 did.
|
||||
|
||||
## Probe
|
||||
|
||||
The probe copies the C# write path:
|
||||
- `<file>.lock` opened with `FileShare.None`;
|
||||
- a GUID temp file written with WriteThrough and `Flush(true)`;
|
||||
- the replace itself.
|
||||
|
||||
It copies the read path too: an attribute check, then an open with `ReadWrite|Delete`. A writer thread and a tight reader loop share one process. The store sits on NTFS (C:) with Defender real-time protection on. A hash check found no torn reads.
|
||||
|
||||
### Empty-store opens per primitive
|
||||
|
||||
| Primitive | .NET 10 (2,000 writes) | Unity Mono 6.13 (1,000 writes) | Notes |
|
||||
|---|---|---|---|
|
||||
| `File.Replace` (`ReplaceFile`) | 46,336 / 244,197 (19%) | 15,915 / 48,298 (33%) | Readers also hit sharing violations: 2,157 on .NET, 5 on Mono |
|
||||
| `MoveFileExW(REPLACE_EXISTING\|WRITE_THROUGH)` | 0 / 417,115 | 0 / 39,094 | 1,145 of 2,000 first writer attempts failed with error 5 (access denied); all landed after retries; 2x slower |
|
||||
| `SetFileInformationByHandle(FileRenameInfoEx, REPLACE_IF_EXISTS\|POSIX_SEMANTICS)` | 0 / 9,756 | 0 / 5,282 | 0 errors, fastest (7.2 s). The reader sampled sparsely, about 5 opens per write against 120-200 for the others |
|
||||
| Reader waits on `<file>.lock` when the path is empty | 50 / 12,660, all recovered | 37 / 2,275, all recovered | Reader waits up to 1,584 ms (mean 371 ms) |
|
||||
|
||||
### A reader holding the store open during one replace, no retry
|
||||
|
||||
| Holder's share mode | `File.Replace` | `MoveFileExW` | POSIX rename |
|
||||
|---|---|---|---|
|
||||
| `ReadWrite\|Delete` (C# readers, Rust std, libuv) | ok | error 5 | ok |
|
||||
| `ReadWrite` (CRT and Python `open`) | error 32 | error 5 | error 32 |
|
||||
| `Read` | error 32 | error 5 | error 32 |
|
||||
|
||||
When a replace succeeded, the holder kept reading the old bytes, and a new open got the new bytes.
|
||||
|
||||
## Primary sources
|
||||
|
||||
- **ReplaceFileW.** It renames the original aside and then moves the replacement in, which is the empty window. It opens the replacement with no sharing, and it makes no atomicity claim. https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-replacefilew
|
||||
- **FILE_RENAME_INFORMATION.** Under classic semantics, a rename fails if the target exists and has open handles; that is `MoveFileExW`'s error 5. POSIX semantics replaces a target that has open handles, and is available from Windows 10 1607. https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/ns-ntifs-_file_rename_information
|
||||
|
||||
## What established software does on Windows
|
||||
|
||||
| Software | Replace primitive on Windows |
|
||||
|---|---|
|
||||
| .NET `File.Replace` | `ReplaceFile` |
|
||||
| .NET `File.Move(overwrite)` | `MoveFileExW(COPY_ALLOWED\|REPLACE_EXISTING)`; not in netstandard2.1 |
|
||||
| Rust std `rename` | `MoveFileExW`, then POSIX rename if that returns access denied |
|
||||
| git-for-windows `mingw_rename` | POSIX rename first, then `MoveFileExW`, then clears read-only and retries |
|
||||
| Python `os.replace`, libuv (Node) | `MoveFileExW(REPLACE_EXISTING)` (Python from bug-tracker history) |
|
||||
| Postgres | `MoveFileEx` with 100 retries, 100 ms apart, on errors 5, 32 and 33 (antivirus named) |
|
||||
| SQLite, LMDB | Never rename the database. SQLite writes in place under a journal or WAL, and retries I/O on lock errors. LMDB uses copy-on-write pages and a meta-page switch, so readers take no locks |
|
||||
| Mono `File.Replace` | `ReplaceFileW` |
|
||||
| IL2CPP (Unity 6000.4.2f1) | `os/Win32/File.cpp:263` calls `ReplaceFileW`, so built players have the same window |
|
||||
|
||||
C# is the only CultCache runtime that uses `ReplaceFile`, and the only one with the empty window. CultCache Rust calls `MoveFileExW` directly.
|
||||
|
||||
## Portability of a P/Invoke path
|
||||
|
||||
- **netstandard2.1:** builds clean with the three kernel32 calls. A runtime OS check is enough; no platform split is needed.
|
||||
- **Unity Mono:** ran under the Editor's `mono.exe`.
|
||||
- **IL2CPP:** not run. Its Win32 loader hardcodes `CreateFileW`, `MoveFileExW` and `SetFileInformationByHandle`.
|
||||
- **GDK (`IL2CPP_TARGET_WINDOWS_GAMES`):** that loader table is absent, so behaviour is unverified. Catch `DllNotFoundException` and `EntryPointNotFoundException`, and fall back.
|
||||
- **FAT, exFAT and possibly SMB:** probably lack POSIX rename (unverified), so the `MoveFileExW` fallback is needed there.
|
||||
- **What leaving `ReplaceFile` drops:** creation time, DACL, object id and alternate streams. CultCache uses none of them.
|
||||
|
||||
## Caveats
|
||||
|
||||
- The POSIX-rename reader was sparse. 0 of 9,756 is still strong: about 1,850 empty opens would be expected at `File.Replace`'s rate.
|
||||
- All runs were in one process.
|
||||
- Mono reported `arch=X86`; the rename succeeded, so the struct layout was right.
|
||||
|
||||
What would change the conclusion: a cross-process rerun at h1's reader density that shows a window under POSIX rename, or an IL2CPP or GDK player where the P/Invoke does not resolve.
|
||||
|
|
@ -21,23 +21,29 @@ caught before it ships instead of written up afterward.
|
|||
|
||||
## Packages in scope
|
||||
|
||||
| Package | Kind | Tag prefix | Published by |
|
||||
| --- | --- | --- | --- |
|
||||
| `org.gamecult.cultlib` | Unity UPM | `cultlib-unity` | `scripts/build-unity-package.ps1`, consumed by git tag |
|
||||
| `org.gamecult.caching.unity` | Unity UPM | `caching-unity` | tagged directly (no build script; see "Coverage gaps") |
|
||||
| `org.gamecult.cultmath` | Unity UPM | `cultmath-unity` | `packages/cultmath/scripts/build-unity-package.ps1`, consumed by git tag |
|
||||
| `@gamecult/cultcache-ts` | npm | `cultcache-ts` | `.github/workflows/publish-packages.yml` |
|
||||
| `cultcache-py` | PyPI | `cultcache-py` | `.github/workflows/publish-packages.yml` |
|
||||
| `cultnet-py` | PyPI | `cultnet-py` | `.github/workflows/publish-packages.yml` |
|
||||
| `cultmesh-py` | PyPI | `cultmesh-py` | `.github/workflows/publish-packages.yml` |
|
||||
| Package | Kind | Published by |
|
||||
| --- | --- | --- |
|
||||
| `org.gamecult.cultlib` | Unity UPM | `scripts/build-unity-package.ps1`, consumed by git tag |
|
||||
| `org.gamecult.caching.unity` | Unity UPM | tagged directly (no build script; see "Coverage gaps") |
|
||||
| `org.gamecult.cultmath` | Unity UPM | `packages/cultmath/scripts/build-unity-package.ps1`, consumed by git tag |
|
||||
| `@gamecult/cultcache-ts` | npm | `.github/workflows/publish-packages.yml` |
|
||||
| `cultcache-py` | PyPI | `.github/workflows/publish-packages.yml` |
|
||||
| `cultnet-py` | PyPI | `.github/workflows/publish-packages.yml` |
|
||||
| `cultmesh-py` | PyPI | `.github/workflows/publish-packages.yml` |
|
||||
|
||||
Each package's tag prefix, changelog path and, for the packages that ship
|
||||
assemblies, the directory of tracked DLLs are declared in
|
||||
`scripts/release-packages.mjs`, the one copy. The check reads them by package
|
||||
name; no release script or workflow passes one.
|
||||
|
||||
Rust crates are consumed as pinned git revisions (see `publish-packages.yml`'s
|
||||
own header comment) and are out of scope for tagged-release semver policing;
|
||||
a `Cargo.toml` version still exists and should follow this policy by
|
||||
convention, but nothing in this repo checks it mechanically today.
|
||||
|
||||
Tag naming stays `<package>-v<version>` for every package above, matching the
|
||||
prefixes already in use.
|
||||
Releases are tags named `<tagPrefix>-v<version>`, with the prefix declared in
|
||||
`scripts/release-packages.mjs`. The check refuses a declaration in which two
|
||||
packages share a prefix or an entry lacks a string prefix or changelog.
|
||||
|
||||
## What counts as breaking
|
||||
|
||||
|
|
@ -105,7 +111,7 @@ swap under "Changed" rather than "Breaking".
|
|||
|
||||
## Pre-1.0 packages
|
||||
|
||||
A package at `0.y.z` (currently `org.gamecult.cultmath`, at `0.2.x`) uses the
|
||||
A package at `0.y.z` (currently `org.gamecult.cultmath`, at `0.4.x`) uses the
|
||||
standard pre-1.0 convention: `MAJOR` stays `0` during initial development, so
|
||||
`MINOR` carries what `MAJOR` means once the package reaches `1.0.0`. Concretely:
|
||||
|
||||
|
|
@ -120,7 +126,9 @@ considered stable), not something the checker infers on its own.
|
|||
Every published package keeps a `CHANGELOG.md` beside its manifest
|
||||
(`unity/org.gamecult.cultlib/CHANGELOG.md` and
|
||||
`src/GameCult.Unity/Assets/Caching/CHANGELOG.md` are the existing precedent).
|
||||
Each release adds a `## [<version>]` section containing:
|
||||
Each release adds a `## [<version>]` section (the check also reads
|
||||
`## <version>`, and either form followed by Keep a Changelog's
|
||||
` - YYYY-MM-DD` date, such as `## [0.4.0] - 2026-10-03`) containing:
|
||||
|
||||
- a category subsection per change (`### Added`, `### Changed`, `### Fixed`,
|
||||
etc., following Keep a Changelog style);
|
||||
|
|
@ -134,40 +142,216 @@ A version with no changelog entry at all fails the check below, the same as
|
|||
a mislabelled one — an undocumented release is not a smaller sin than a
|
||||
mislabelled one.
|
||||
|
||||
### First release of a package
|
||||
|
||||
A package with no `CHANGELOG.md` yet cannot release: the check refuses with
|
||||
"changelog not found". Its first release writes the file at the declared path,
|
||||
`packages/<package>/CHANGELOG.md`, with one section for the version being
|
||||
released. That version must still be exactly the next one after the package's
|
||||
nearest ancestor tag. As of 2026-10-03 the valid next versions are:
|
||||
|
||||
- `cultcache-ts`, after `cultcache-ts-v0.14.0`: `0.14.1`, `0.15.0` or `1.0.0`;
|
||||
- `cultcache-py`, after `cultcache-py-v0.3.0`: `0.3.1`, `0.4.0` or `1.0.0`;
|
||||
- `cultnet-py` and `cultmesh-py`, which have no tags: `0.1.0`, their manifest
|
||||
version, as a first release. Run it from a clone with the tags fetched, or
|
||||
the check cannot tell a first release from a missing record.
|
||||
|
||||
On `0.y.z` a `### Breaking` section needs at least a minor bump.
|
||||
|
||||
## Enforcement
|
||||
|
||||
`scripts/check-changelog-semver.mjs` is the mechanical check. Given a
|
||||
package name, its `CHANGELOG.md` path, the version being released, and a git
|
||||
tag prefix, it:
|
||||
package name and the version being released, it reads the package's
|
||||
declaration from `scripts/release-packages.mjs` in `--cwd` (an unknown package
|
||||
or a missing declaration refuses), and:
|
||||
|
||||
1. resolves the previous published version from the highest existing
|
||||
`<prefix>-v*` tag older than the version being released (or treats the
|
||||
release as a package's first if none exists);
|
||||
1. derives the release record from `git tag -l` in `--cwd`. A same-prefix tag
|
||||
is one that starts `<prefix>-v`; one that is not
|
||||
`<prefix>-vMAJOR.MINOR.PATCH` refuses, naming the tag, and is never
|
||||
skipped. The previous release is the newest same-prefix tag strictly older
|
||||
than the version being released, by version order, that is also an ancestor
|
||||
of the commit being checked: a backport tagged later on another branch is
|
||||
not part of that history, so it never moves a rebuild's predecessor. A tag
|
||||
equal to the version does not exempt
|
||||
it and does not count as a previous release: there is no "already
|
||||
published" skip, so a rebuild or a CI re-run at a tagged version is
|
||||
measured against that version's predecessor, exactly as at release, and
|
||||
gets the same verdict. With no older tag, a newer one refuses (the version
|
||||
is older than every release), and a repository that holds no tag other than
|
||||
the version's own refuses, because a first release cannot be told from a
|
||||
missing record. Older tags of which none is an ancestor leave the
|
||||
predecessor unknown and refuse. Otherwise it is a first release, which no
|
||||
caller declares. A package that declares an assemblies directory is a first
|
||||
release only when no tag in the repository, under any prefix, tracks a
|
||||
managed assembly under that directory: such a tag means the package has
|
||||
shipped, so the declared prefix is wrong and the check refuses, naming the
|
||||
tag and the assembly. A tag snapshots the whole tree of this monorepo, so a
|
||||
tag tracking a package's directory proves nothing; only a managed assembly in
|
||||
the declared directory does. This is read from git, never from the changelog's
|
||||
prose. The version's own tag does not count, so a first release can be
|
||||
rebuilt. Only the declared directory counts: a package whose directory moved
|
||||
after its releases has none of its old path's tags counted, so its release
|
||||
under a misspelled prefix reads as new, and the move itself is caught only
|
||||
under the right prefix, where the declared directory holds no managed assembly
|
||||
at the previous tag. A package that declares no assemblies directory (the
|
||||
Python and TypeScript packages and the Caching Unity package) has no such
|
||||
proof: with no tag of its own prefix it is a first release. The suite test
|
||||
that pins every declared prefix guards it: each prefix is declared once, each
|
||||
workflow tag trigger must be a declared prefix, and each such package's prefix
|
||||
must be a workflow trigger or, for the Caching Unity package the workflow does
|
||||
not build, the prefix of tags that hold its own manifest at the tag's own
|
||||
version, so a typo or a copied prefix fails the suite. Nothing releases
|
||||
without the suite passing; see below for how each release path runs it.
|
||||
Releases run from a full clone with every tag (`fetch-depth: 0` in CI), the
|
||||
recorded `partial-tags-first-release`.
|
||||
Tags that cannot be read (a `--cwd` that is not a git repository, or a tag
|
||||
whose tree cannot be listed) refuse;
|
||||
2. requires a `## [<version>]` changelog entry to exist at all;
|
||||
3. classifies the version bump (major/minor/patch) against the previous
|
||||
version, refusing anything that is not exactly the next version in some
|
||||
lane — a skip, a reversal, or a repeat are all refused, not just wrong
|
||||
bump sizes;
|
||||
4. if the changelog entry has a `### Breaking` section, requires the bump to
|
||||
be at least major (or, pre-1.0, at least minor);
|
||||
5. fails loudly, naming the package, the previous and new version, and (when
|
||||
relevant) the changelog heading that triggered the requirement.
|
||||
4. when the release script supplies built assemblies (below), treats the
|
||||
release as breaking if the public API measurably lost or changed a member
|
||||
against the previous tag, whether or not the changelog says so; a
|
||||
measured break with no `### Breaking` section is refused, naming the
|
||||
count, the first diagnostics, and the heading that must declare them;
|
||||
5. if the release is breaking (a `### Breaking` section, a measured break, or
|
||||
both), requires the bump to be at least major (or, pre-1.0, at least
|
||||
minor); a `### Breaking` section with nothing measured is valid, because
|
||||
behavioural breaks are invisible to a signature comparison;
|
||||
6. fails loudly, naming the package, the previous and new version, and (when
|
||||
relevant) the changelog heading or the measured diagnostics that
|
||||
triggered the requirement.
|
||||
|
||||
Additions are never a rule: adding a public member is not breaking (see
|
||||
above), and the check neither refuses nor demands a bump for one.
|
||||
|
||||
### Measured input
|
||||
|
||||
A package whose declaration names an `assemblies` directory is measured, and
|
||||
the release must hand over one `--api-built <dll>` per assembly it built (plus
|
||||
`--api-refs <dir>` for directories that hold the built assemblies'
|
||||
dependencies). A package with no such directory takes no `--api-built`, and one
|
||||
that has it cannot omit it. The measured set is every managed assembly tracked
|
||||
under that directory, at any depth, at the previous tag, read as git blobs (no
|
||||
worktree, no network, unaffected by what the working tree tracks now) and keyed
|
||||
by file name. A DLL is managed when its PE header carries a CLI header; a
|
||||
native DLL has none and is not measured, and a tracked `.dll` that is not a PE
|
||||
image refuses. Two managed assemblies with one name refuse. The checker
|
||||
compares each built assembly with its namesake using
|
||||
`Microsoft.DotNet.ApiCompat.Tool`; each `CPnnnn` diagnostic is one measured
|
||||
break. Every managed assembly the previous tag tracked that the build no
|
||||
longer hands over is itself a measured break, whatever its name or place, so a
|
||||
release script passes every assembly it ships. A built assembly with no
|
||||
namesake at the tag is an addition and is not examined.
|
||||
|
||||
Measuring nothing is a refusal, never a pass. The check refuses, naming what
|
||||
is missing, when the previous tag tracks no managed assembly under the
|
||||
declared directory (a wrong or moved directory, or a tag that predates it);
|
||||
when git cannot read the tracked assemblies; and when the tool fails to
|
||||
measure (not installed, an unreadable assembly, a crash: a non-zero exit with
|
||||
no diagnostic line). A first release measures nothing.
|
||||
|
||||
The tool and the `NETStandard.Library.Ref` 2.1.0 reference assemblies are
|
||||
pinned in `scripts/api-gate/` (`.config/dotnet-tools.json` and
|
||||
`ApiRefs.csproj`) and restored there by the check itself, so a release does
|
||||
not depend on any other tool in the repository's manifest. NuGet is needed
|
||||
until both are cached under `scripts/api-gate`. Both sides of every
|
||||
comparison resolve netstandard types through those reference assemblies, and the
|
||||
new side also through the built DLL's own directory and every `--api-refs`
|
||||
directory. No suppression file is kept: a suppression would be a second, silent
|
||||
declaration of a break, so a break is declared only under `### Breaking`.
|
||||
|
||||
A passing measured run prints that unmeasured changes still need declaring.
|
||||
|
||||
#### Unmeasured changes
|
||||
|
||||
ApiCompat does not report these changes to a public member, and the check
|
||||
therefore passes them. Each is a breaking change under the rules above and is
|
||||
declared under `### Breaking`, as behavioural breaks are:
|
||||
|
||||
- a member gaining or losing `static`;
|
||||
- a parameter gaining or losing `ref`, `out` or `in`;
|
||||
- a `const` field's value changing;
|
||||
- an enum member's underlying value changing;
|
||||
- a field gaining or losing `readonly`;
|
||||
- a default parameter value changing.
|
||||
|
||||
The release scripts run the check once the assemblies under judgement exist,
|
||||
after the build and before anything is copied into the package.
|
||||
|
||||
Run it directly: `node scripts/check-changelog-semver.mjs --package <name>
|
||||
--changelog <path> --version <x.y.z> --tag-prefix <prefix>`. Its own tests
|
||||
live in `scripts/check-changelog-semver.test.mjs` (`node --test
|
||||
--version <x.y.z> [--cwd <dir>] [--api-built <dll>... [--api-refs <dir>...]]`.
|
||||
Any other option is a usage error (exit 2). Its own tests live in
|
||||
`scripts/check-changelog-semver.test.mjs` (`node --test
|
||||
scripts/check-changelog-semver.test.mjs`).
|
||||
|
||||
It is wired into:
|
||||
|
||||
- `.github/workflows/publish-packages.yml`, right after each job's existing
|
||||
"tag matches manifest version" check, for `cultcache-ts`, `cultcache-py`,
|
||||
`cultnet-py`, and `cultmesh-py`;
|
||||
- `.github/workflows/publish-packages.yml`, through
|
||||
`scripts/release-after-suite.mjs`, for `cultcache-ts`, `cultcache-py`,
|
||||
`cultnet-py`, and `cultmesh-py`, with `fetch-depth: 0` so the checkout holds
|
||||
the tags;
|
||||
- `scripts/build-unity-package.ps1`, for `org.gamecult.cultlib`;
|
||||
- `packages/cultmath/scripts/build-unity-package.ps1`, for
|
||||
`org.gamecult.cultmath`;
|
||||
- `scripts/verify-caching-unity-release.ps1`, for `org.gamecult.caching.unity`.
|
||||
|
||||
Each of those runs the check's own tests before it releases. The Unity release
|
||||
scripts run them before they call the check, and the tests pin that order. In
|
||||
`publish-packages.yml` the release step runs `scripts/release-after-suite.mjs`
|
||||
with the run's git ref. From one process it checks that a tag ref is the
|
||||
package's declared prefix and manifest version, runs these tests, runs this
|
||||
check for the tagged version, runs the package's own tests (`npm test`, or the
|
||||
Python package's unit tests), and only then the release action: `npm publish`
|
||||
for `cultcache-ts`, which it refuses on any ref but a release tag, and for the
|
||||
Python packages the sdist and wheel build, whose output is all the PyPI upload
|
||||
step uploads. The checks run with the known test-runner and token variables
|
||||
removed (`NODE_OPTIONS`, `NODE_TEST_CONTEXT`, any other `NODE_TEST_*` variable,
|
||||
and `NODE_AUTH_TOKEN`), so none of those can make the tests run nothing and
|
||||
pass, and only the release action receives the token. That list names known
|
||||
variables; it does not prove that no other inherited variable can affect a
|
||||
check. The npm Publish step and the Python sdist and wheel build step start the
|
||||
guard under `env -u NODE_OPTIONS`, so a `NODE_OPTIONS` preload set in the
|
||||
workflow's or job's `env:` cannot run code inside the guard before its first
|
||||
line.
|
||||
The gate is that call, not a step condition, so no `if:` or `continue-on-error`
|
||||
can release what a check refused. The tests compare each job's release steps
|
||||
with their expected text exactly, less the steps' `if:` lines. Removing the call
|
||||
is still possible, but only as a visible edit to those steps and to the tests.
|
||||
|
||||
The guard and that pin stop accidental workflow edits. They do not stop a
|
||||
deliberate one: an extra step that publishes, a workflow-level `defaults:` or
|
||||
`env:`, or a fake `node` on `$GITHUB_PATH` all pass them. Deliberate edits are
|
||||
review's job, as ruled in `suite-gate-structural-not-parsed`, and the pin
|
||||
does not try to parse the workflow for them. For the same reason it has no ban
|
||||
on `shell` or `defaults`: such a ban defends only against a deliberate edit,
|
||||
and it also refused harmless settings such as `defaults.run.working-directory`.
|
||||
A step-level `shell:` on a release step still fails the exact comparison.
|
||||
A recommendation for the operator, not something this repository can set: the
|
||||
Python job already runs in the `pypi` GitHub environment, as PyPI trusted
|
||||
publishing expects. Putting the npm job in an environment with required
|
||||
reviewers would make every npm release wait for a person's approval. That is a
|
||||
GitHub settings change.
|
||||
|
||||
`org.gamecult.cultlib` compiles CultMath from source and ships beside
|
||||
`org.gamecult.cultmath`, so its build refuses unless it declares exactly the
|
||||
CultMath package's version and every `CultMath.dll` it built equals the one
|
||||
that package tracks, byte for byte. Any CultMath source change therefore means:
|
||||
release `org.gamecult.cultmath`, declare its new version in
|
||||
`org.gamecult.cultlib`, then release `org.gamecult.cultlib`. The bytes also
|
||||
depend on the checkout and the toolchain. `.gitattributes` pins CultMath
|
||||
source to CRLF on every checkout, because the tracked DLL was built from CRLF
|
||||
source and line endings reach the DLL through the pdb's document checksums; a
|
||||
clone checked out before that rule may still hold LF files (`git ls-files
|
||||
--eol packages/cultmath/src` shows `w/lf`) until they are checked out again.
|
||||
The build needs a git checkout, and refuses up front without `.git`: the repo
|
||||
root maps to `/_/` through git, so an archive or source zip would write its
|
||||
own path into the DLL. No `global.json` pins the .NET SDK, so the same refusal
|
||||
at unchanged source and CRLF checkout means this SDK or host differs from the
|
||||
one that built the tracked DLL.
|
||||
|
||||
### Coverage gaps
|
||||
|
||||
`publish-packages.yml` only triggers on `cultcache-ts-v*`, `cultcache-py-v*`,
|
||||
|
|
@ -193,6 +377,10 @@ existing assembly-version check does. A tag pushed by hand without running
|
|||
the release script bypasses both checks equally; closing that gap is a CI
|
||||
trigger on tag push for the Unity packages, not something this change adds.
|
||||
|
||||
What stays unmeasured: behaviour behind an unchanged signature, wire formats,
|
||||
native exports of the QUIC bridge, and the Caching Unity package's source
|
||||
(it has no assembly). Those rest on the `### Breaking` declaration.
|
||||
|
||||
Rust crates (consumed as pinned git revisions, not tagged releases in the
|
||||
usual sense) and the CultNet protocol surface itself (no automated wire
|
||||
compatibility test currently gates a release) are policy by convention only —
|
||||
|
|
@ -200,14 +388,13 @@ described above, not mechanically checked. Extending the checker to a Rust
|
|||
crate's `Cargo.toml`/`CHANGELOG.md` or to an automated CultNet interop
|
||||
compatibility gate is future work, not part of this change.
|
||||
|
||||
`@gamecult/cultcache-ts`, `cultcache-py`, `cultnet-py`, `cultmesh-py`, and
|
||||
`org.gamecult.cultmath` currently have **no `CHANGELOG.md` file at all**. This
|
||||
is a real, pre-existing gap, not something introduced by this policy: their
|
||||
next tagged release will fail the new check for exactly that reason ("no
|
||||
changelog entry for version X") until each package's `CHANGELOG.md` exists.
|
||||
That failure is intended — a release with no changelog is not a smaller
|
||||
problem than a mislabelled one — but it does mean the very next release of
|
||||
any of these five packages needs a `CHANGELOG.md` created first. Backfilling
|
||||
changelog content for their past releases is not part of this change: it
|
||||
would mean inventing release-note prose for history this pass has no
|
||||
first-hand knowledge of, which is worse than leaving the gap named.
|
||||
`@gamecult/cultcache-ts`, `cultcache-py`, `cultnet-py`, and `cultmesh-py`
|
||||
currently have **no `CHANGELOG.md` file at all**; the check refuses their next
|
||||
tagged release ("changelog not found at <declared path>") until each
|
||||
package's file exists. A release with no changelog is not a smaller problem
|
||||
than a mislabelled one. The next release of each creates its file:
|
||||
`packages/cultcache-ts/CHANGELOG.md` arrives with the document-variants work
|
||||
(`hands/variants-c2a`), and whoever cuts the next release of `cultcache-py`,
|
||||
`cultnet-py` or `cultmesh-py` creates that package's file. Backfilling
|
||||
changelog content for past releases would mean inventing release-note prose
|
||||
for history nobody here knows first-hand, so the gap stays named.
|
||||
|
|
|
|||
9
package-lock.json
generated
9
package-lock.json
generated
|
|
@ -1184,7 +1184,7 @@
|
|||
},
|
||||
"packages/cultcache-ts": {
|
||||
"name": "@gamecult/cultcache-ts",
|
||||
"version": "0.15.0",
|
||||
"version": "0.14.0",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@msgpack/msgpack": "^3.1.3",
|
||||
|
|
@ -1202,7 +1202,7 @@
|
|||
"version": "0.3.0",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@msgpack/msgpack": "^3.1.3",
|
||||
"@gamecult/cultcache-ts": "^0.14.0",
|
||||
"cultnet-ts": "^0.2.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
|
@ -1217,8 +1217,7 @@
|
|||
"version": "0.1.1",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@gamecult/cultcache-ts": "^0.15.0",
|
||||
"@msgpack/msgpack": "^3.1.2",
|
||||
"@gamecult/cultcache-ts": "^0.14.0",
|
||||
"cultnet-ts": "^0.2.0",
|
||||
"koffi": "3.3.0"
|
||||
},
|
||||
|
|
@ -1235,7 +1234,7 @@
|
|||
"version": "0.2.0",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@gamecult/cultcache-ts": "^0.15.0",
|
||||
"@gamecult/cultcache-ts": "^0.14.0",
|
||||
"@msgpack/msgpack": "^3.1.3",
|
||||
"ajv": "^8.17.1"
|
||||
},
|
||||
|
|
|
|||
|
|
@ -67,6 +67,7 @@ store.
|
|||
- `define_document_type(...)`
|
||||
- `define_database_entry_type(...)`
|
||||
- `database_entry_field(...)`
|
||||
- `leaves` (typed slot leaves)
|
||||
- `define_document_registry(...)`
|
||||
- `CultCache.builder()`
|
||||
- `register_document_type(...)`
|
||||
|
|
@ -148,6 +149,55 @@ That matches the Rust `#[derive(DatabaseEntry)]` formatter shape and the C#
|
|||
`[Key(n)]` intent: schema evolution comes from stable field slots, not source
|
||||
member order.
|
||||
|
||||
## Typed Leaves
|
||||
|
||||
A slot with no codec is untyped: it is an `object` in C#, cataloged `System.Object`, and takes any MessagePack value.
|
||||
Give a slot a leaf from `cultcache_py.leaves` and it writes and reads exactly what the C# type does, refuses the rest
|
||||
on write and on read, and carries the C# type name in the schema catalog, which the C# reference checks against its
|
||||
own class.
|
||||
|
||||
```python
|
||||
from cultcache_py import database_entry_field, define_database_entry_type, leaves as t
|
||||
|
||||
settings_doc = define_database_entry_type(
|
||||
"settings",
|
||||
[
|
||||
database_entry_field("theme", 0, codec=t.string),
|
||||
database_entry_field("retries", 1, codec=t.int32, default=0),
|
||||
database_entry_field("tags", 2, codec=t.list(t.string), default=list),
|
||||
],
|
||||
)
|
||||
```
|
||||
|
||||
| Leaf | C# type | Python value |
|
||||
| --- | --- | --- |
|
||||
| `t.string` | `string` | `str` |
|
||||
| `t.boolean` | `bool` | `bool` |
|
||||
| `t.bytes` | `byte[]` | `bytes`, `bytearray`, `memoryview`; a MessagePack str reads as its UTF-8 bytes |
|
||||
| `t.int32`, `t.int64` | `int`, `long` | `int` within range (not `bool`, not `float`) |
|
||||
| `t.float32`, `t.float64` | `float`, `double` | `int` or `float`; a float32 is written as MessagePack float 32 |
|
||||
| `t.list(x)` | `List<T>` | `list` or `tuple`, each element through `x` |
|
||||
| `t.array(x)` | `T[]` | the same wire as `t.list(x)` |
|
||||
| `t.any` | `object` | any plain MessagePack value or a timestamp; the default of an untyped slot |
|
||||
| `t.nullable(x)` | `T?` | `None`, or whatever `x` takes |
|
||||
| `t.lazy(get)` | | a leaf resolved on first use, for a union that refers to itself |
|
||||
|
||||
Nil is refused unless the slot is wrapped in `t.nullable`. Wrap a C# `string`, `byte[]`, `List`, array, class or
|
||||
interface slot that may hold null (`t.nullable(t.string)`), and a value type that may hold null (`int?` is
|
||||
`t.nullable(t.int32)`, cataloged `System.Nullable<System.Int32>`); a reference type keeps its own name. A `default`
|
||||
fills a slot the payload is too short to have, never a nil that is present.
|
||||
|
||||
A record or union is named for C# with `type_name=`, the class's `FullName` (a nested class joins with `+`):
|
||||
|
||||
```python
|
||||
inner = define_record_codec("Inner", [database_entry_field("n", 0, codec=t.string)], type_name="My.App.Doc+Inner")
|
||||
shape = define_union("Shape", {0: ("Circle", circle)}, type_name="My.App.Doc+IShape")
|
||||
```
|
||||
|
||||
Without `type_name=` the slot is cataloged `System.Object`. A refusal reads `<type> slot <key> (<field>): expected
|
||||
<what>, found <kind>`, prefixed `element <i>: ` inside a list and `Union '<name>' arm <key>: ` inside a union, and never
|
||||
carries the value.
|
||||
|
||||
## Wire Parity
|
||||
|
||||
See [docs/python-runtime-parity.md](../../docs/python-runtime-parity.md) for
|
||||
|
|
|
|||
|
|
@ -1,31 +1,47 @@
|
|||
from .backing_store import BackingStore, CultCacheEnvelope
|
||||
from .backing_store import CultCacheSchemaCatalogEntry, CultCacheSchemaCatalogMember
|
||||
from . import leaves
|
||||
from .cache import CultCache, CultCacheBuilder
|
||||
from .documents import (
|
||||
MAX_PAYLOAD_DEPTH,
|
||||
MAX_SLOT_KEY,
|
||||
CultCachePayloadDepthError,
|
||||
DatabaseEntryField,
|
||||
DocumentDefinition,
|
||||
UnionArm,
|
||||
database_entry_field,
|
||||
define_database_entry_type,
|
||||
define_document_registry,
|
||||
define_document_type,
|
||||
define_record_codec,
|
||||
define_union,
|
||||
)
|
||||
from .leaves import SlotCodec
|
||||
from .stores import JsonLinesBackingStore, SchemaConflictError, SingleFileMessagePackBackingStore, StoreUnreadableError
|
||||
|
||||
__all__ = [
|
||||
"BackingStore",
|
||||
"CultCache",
|
||||
"CultCacheBuilder",
|
||||
"CultCachePayloadDepthError",
|
||||
"CultCacheEnvelope",
|
||||
"CultCacheSchemaCatalogEntry",
|
||||
"CultCacheSchemaCatalogMember",
|
||||
"DatabaseEntryField",
|
||||
"DocumentDefinition",
|
||||
"JsonLinesBackingStore",
|
||||
"MAX_PAYLOAD_DEPTH",
|
||||
"MAX_SLOT_KEY",
|
||||
"SchemaConflictError",
|
||||
"SingleFileMessagePackBackingStore",
|
||||
"SlotCodec",
|
||||
"StoreUnreadableError",
|
||||
"UnionArm",
|
||||
"leaves",
|
||||
"database_entry_field",
|
||||
"define_database_entry_type",
|
||||
"define_document_registry",
|
||||
"define_document_type",
|
||||
"define_record_codec",
|
||||
"define_union",
|
||||
]
|
||||
|
|
|
|||
|
|
@ -2,9 +2,13 @@
|
|||
|
||||
import json
|
||||
from dataclasses import MISSING, dataclass, field
|
||||
from collections.abc import Mapping, Sequence, Set
|
||||
from itertools import chain
|
||||
from typing import Any, Callable, Generic, Iterable, TypeVar
|
||||
|
||||
from .backing_store import CultCacheSchemaCatalogEntry, CultCacheSchemaCatalogMember
|
||||
from .leaves import Float32, SlotCodec
|
||||
from .leaves import any as _any_leaf
|
||||
|
||||
T = TypeVar("T")
|
||||
|
||||
|
|
@ -13,6 +17,51 @@ Decoder = Callable[[Any], T]
|
|||
Validator = Callable[[T], None]
|
||||
Extractor = Callable[[T], str | int | float | bool | None]
|
||||
|
||||
MAX_PAYLOAD_DEPTH = 256
|
||||
"""The payload nesting limit, equal to the C# reference's `MaximumPayloadDepth`: every array and map counts, read
|
||||
or skipped, the outermost one is depth 1; depth 256 is accepted and 257 refused, on read and on write."""
|
||||
|
||||
MAX_SLOT_KEY = 65535
|
||||
"""The largest slot key a record may define: the largest MessagePack array16 length."""
|
||||
|
||||
try:
|
||||
from msgpack.exceptions import StackError as _MsgpackStackError
|
||||
|
||||
_STACK_FAULTS: tuple[type[BaseException], ...] = (_MsgpackStackError,)
|
||||
except ModuleNotFoundError:
|
||||
_STACK_FAULTS = ()
|
||||
|
||||
|
||||
_CONTAINERS = (Mapping, Sequence, Set)
|
||||
_SCALAR_SEQUENCES = (str, bytes, bytearray, memoryview)
|
||||
|
||||
|
||||
class CultCachePayloadDepthError(ValueError):
|
||||
"""A payload nests deeper than `MAX_PAYLOAD_DEPTH`. Names the type, the depth reached and the limit; never the payload."""
|
||||
|
||||
def __init__(self, type_name: str, direction: str) -> None:
|
||||
self.depth = MAX_PAYLOAD_DEPTH + 1
|
||||
self.limit = MAX_PAYLOAD_DEPTH
|
||||
super().__init__(
|
||||
f"{type_name} payload nests {self.depth} containers deep; the limit is {self.limit} (refused on {direction})."
|
||||
)
|
||||
|
||||
|
||||
def _refuse_past_depth_limit(tree: Any, type_name: str, direction: str) -> None:
|
||||
"""The one nesting count. Walks a payload tree iteratively (every mapping, sequence and set that is not text or
|
||||
bytes is a container), refusing the first container past `MAX_PAYLOAD_DEPTH`."""
|
||||
stack = [(tree, 1)] if _is_container(tree) else []
|
||||
while stack:
|
||||
node, depth = stack.pop()
|
||||
if depth > MAX_PAYLOAD_DEPTH:
|
||||
raise CultCachePayloadDepthError(type_name, direction)
|
||||
children = chain(node.keys(), node.values()) if isinstance(node, Mapping) else node
|
||||
stack.extend((child, depth + 1) for child in children if _is_container(child))
|
||||
|
||||
|
||||
def _is_container(node: Any) -> bool:
|
||||
return isinstance(node, _CONTAINERS) and not isinstance(node, _SCALAR_SEQUENCES)
|
||||
|
||||
|
||||
def _default_encode(value: Any) -> Any:
|
||||
if hasattr(value, "model_dump"):
|
||||
|
|
@ -36,7 +85,7 @@ def _json_payload_decoder(payload: bytes) -> Any:
|
|||
return json.loads(payload.decode("utf-8"))
|
||||
|
||||
|
||||
def _messagepack_payload_encoder(value: Any) -> bytes:
|
||||
def _msgpack() -> Any:
|
||||
try:
|
||||
import msgpack # type: ignore
|
||||
except ModuleNotFoundError as exc:
|
||||
|
|
@ -44,7 +93,35 @@ def _messagepack_payload_encoder(value: Any) -> bytes:
|
|||
"MessagePack payload encoding requires the optional 'msgpack' dependency. "
|
||||
"Install with: python -m pip install cultcache-py[msgpack]"
|
||||
) from exc
|
||||
return msgpack.packb(value, use_bin_type=True)
|
||||
return msgpack
|
||||
|
||||
|
||||
def _pack_tree(tree: Any) -> bytes:
|
||||
"""The bytes of the tree the leaves produced. `packb` writes everything but a `Float32`, which it refuses with a
|
||||
TypeError; only then does an iterative walk pack each array and map header and each value, a `Float32` through a
|
||||
single-float packer."""
|
||||
msgpack = _msgpack()
|
||||
try:
|
||||
return msgpack.packb(tree, use_bin_type=True) # type: ignore[no-any-return]
|
||||
except TypeError:
|
||||
pass
|
||||
plain = msgpack.Packer(use_bin_type=True)
|
||||
single = msgpack.Packer(use_bin_type=True, use_single_float=True)
|
||||
out: list[bytes] = []
|
||||
stack = [tree]
|
||||
while stack:
|
||||
node = stack.pop()
|
||||
if isinstance(node, Float32):
|
||||
out.append(single.pack(node.value))
|
||||
elif isinstance(node, (list, tuple)):
|
||||
out.append(plain.pack_array_header(len(node)))
|
||||
stack.extend(reversed(node))
|
||||
elif isinstance(node, dict):
|
||||
out.append(plain.pack_map_header(len(node)))
|
||||
stack.extend(reversed([part for pair in node.items() for part in pair]))
|
||||
else:
|
||||
out.append(plain.pack(node))
|
||||
return b"".join(out)
|
||||
|
||||
|
||||
def _messagepack_payload_decoder(payload: bytes) -> Any:
|
||||
|
|
@ -63,12 +140,33 @@ class DatabaseEntryField:
|
|||
name: str
|
||||
key: int
|
||||
default: Any = MISSING
|
||||
codec: SlotCodec = _any_leaf
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if not _is_key(self.key) or not 0 <= self.key <= MAX_SLOT_KEY:
|
||||
raise ValueError(f"DatabaseEntry field keys must be integers within 0..{MAX_SLOT_KEY}")
|
||||
if not isinstance(self.codec, SlotCodec):
|
||||
raise ValueError("DatabaseEntry field codec must be a SlotCodec: a leaf from cultcache_py.leaves, or leaves.lazy")
|
||||
|
||||
|
||||
def database_entry_field(name: str, key: int, *, default: Any = MISSING) -> DatabaseEntryField:
|
||||
if key < 0:
|
||||
raise ValueError("DatabaseEntry field keys must be non-negative integers")
|
||||
return DatabaseEntryField(name=name, key=key, default=default)
|
||||
def database_entry_field(
|
||||
name: str,
|
||||
key: int,
|
||||
*,
|
||||
default: Any = MISSING,
|
||||
codec: SlotCodec = _any_leaf,
|
||||
) -> DatabaseEntryField:
|
||||
"""A slot. `codec` is the slot's leaf (cultcache_py.leaves, a record or a union); with none the slot is untyped,
|
||||
an `object` in C#. A `default` fills a slot the payload is too short to have, never a nil."""
|
||||
return DatabaseEntryField(name=name, key=key, default=default, codec=codec)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class UnionArm:
|
||||
"""A decoded union value: the arm's declared name and its decoded record (None for a unit arm)."""
|
||||
|
||||
name: str
|
||||
value: Any = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
|
|
@ -88,16 +186,27 @@ class DocumentDefinition(Generic[T]):
|
|||
content_hash: str | None = None
|
||||
canonical_schema_json: str | None = None
|
||||
compatible_schema_ids: tuple[str, ...] = field(default_factory=tuple)
|
||||
members: tuple[CultCacheSchemaCatalogMember, ...] = field(default_factory=tuple)
|
||||
members: tuple[CultCacheSchemaCatalogMember, ...] | Callable[[], tuple[CultCacheSchemaCatalogMember, ...]] = field(
|
||||
default_factory=tuple
|
||||
)
|
||||
"""The catalog rows, or a function returning them: a document made of leaves derives them when the catalog is first
|
||||
built, so a `lazy` leaf can name a definition made later."""
|
||||
_catalog_entry: CultCacheSchemaCatalogEntry | None = field(default=None, init=False, repr=False, compare=False)
|
||||
|
||||
def encode_payload(self, value: T) -> bytes:
|
||||
if self.validate:
|
||||
self.validate(value)
|
||||
return self.payload_encoder(self.encode(value))
|
||||
tree = self.encode(value)
|
||||
_refuse_past_depth_limit(tree, self.type, "write")
|
||||
return self.payload_encoder(tree)
|
||||
|
||||
def decode_payload(self, payload: bytes) -> T:
|
||||
value = self.decode(self.payload_decoder(payload))
|
||||
try:
|
||||
tree = self.payload_decoder(payload)
|
||||
except _STACK_FAULTS:
|
||||
raise CultCachePayloadDepthError(self.type, "read") from None
|
||||
_refuse_past_depth_limit(tree, self.type, "read")
|
||||
value = self.decode(tree)
|
||||
if self.validate:
|
||||
self.validate(value)
|
||||
return value
|
||||
|
|
@ -105,6 +214,7 @@ class DocumentDefinition(Generic[T]):
|
|||
def catalog_entry(self) -> CultCacheSchemaCatalogEntry:
|
||||
if self._catalog_entry is not None:
|
||||
return self._catalog_entry
|
||||
members = tuple(self.members() if callable(self.members) else self.members)
|
||||
schema_id = self.schema_id or self.type
|
||||
schema_name = self.schema_name or self.type
|
||||
schema_version = self.schema_version or f"{schema_name}.v1"
|
||||
|
|
@ -123,7 +233,7 @@ class DocumentDefinition(Generic[T]):
|
|||
"indexAlias": member.index_alias,
|
||||
"isName": member.is_name,
|
||||
}
|
||||
for member in self.members
|
||||
for member in members
|
||||
],
|
||||
},
|
||||
ensure_ascii=False,
|
||||
|
|
@ -137,7 +247,7 @@ class DocumentDefinition(Generic[T]):
|
|||
content_hash=self.content_hash or schema_id,
|
||||
canonical_schema_json=canonical_schema_json,
|
||||
compatible_schema_ids=tuple(compatible_schema_ids),
|
||||
members=tuple(self.members),
|
||||
members=members,
|
||||
)
|
||||
object.__setattr__(self, "_catalog_entry", catalog_entry)
|
||||
return catalog_entry
|
||||
|
|
@ -160,7 +270,7 @@ def define_document_type(
|
|||
content_hash: str | None = None,
|
||||
canonical_schema_json: str | None = None,
|
||||
compatible_schema_ids: Iterable[str] | None = None,
|
||||
members: Iterable[CultCacheSchemaCatalogMember] | None = None,
|
||||
members: Iterable[CultCacheSchemaCatalogMember] | Callable[[], tuple[CultCacheSchemaCatalogMember, ...]] | None = None,
|
||||
) -> DocumentDefinition[T]:
|
||||
return DocumentDefinition(
|
||||
type=type,
|
||||
|
|
@ -178,7 +288,7 @@ def define_document_type(
|
|||
content_hash=content_hash,
|
||||
canonical_schema_json=canonical_schema_json,
|
||||
compatible_schema_ids=tuple(compatible_schema_ids or ()),
|
||||
members=tuple(members or ()),
|
||||
members=members if callable(members) else tuple(members or ()),
|
||||
)
|
||||
|
||||
|
||||
|
|
@ -205,65 +315,36 @@ def define_database_entry_type(
|
|||
and newly added fields can use higher keys without rewriting older payloads.
|
||||
"""
|
||||
|
||||
normalized = [_normalize_database_entry_field(field) for field in fields]
|
||||
if not normalized:
|
||||
raise ValueError("DatabaseEntry document types require at least one field")
|
||||
keys = [field.key for field in normalized]
|
||||
if len(keys) != len(set(keys)):
|
||||
raise ValueError(f"DatabaseEntry document type {type!r} has duplicate field keys")
|
||||
normalized.sort(key=lambda field: field.key)
|
||||
max_key = max(keys)
|
||||
normalized = _normalize_fields(type, fields)
|
||||
member_name_lookup = name if isinstance(name, str) else None
|
||||
index_lookup = indexes or {}
|
||||
members = tuple(
|
||||
CultCacheSchemaCatalogMember(
|
||||
slot=field.key,
|
||||
member_name=_pascal_case(field.name),
|
||||
type_name="System.Object",
|
||||
is_name=field.name == member_name_lookup,
|
||||
index_alias=next(
|
||||
(alias for alias, extractor in index_lookup.items() if extractor == field.name),
|
||||
None,
|
||||
),
|
||||
|
||||
def members() -> tuple[CultCacheSchemaCatalogMember, ...]:
|
||||
return tuple(
|
||||
CultCacheSchemaCatalogMember(
|
||||
slot=field.key,
|
||||
member_name=_pascal_case(field.name),
|
||||
type_name=field.codec.type_name or _any_leaf.type_name,
|
||||
is_name=field.name == member_name_lookup,
|
||||
index_alias=next(
|
||||
(alias for alias, extractor in index_lookup.items() if extractor == field.name),
|
||||
None,
|
||||
),
|
||||
)
|
||||
for field in normalized
|
||||
)
|
||||
for field in normalized
|
||||
)
|
||||
|
||||
def encode(value: Any) -> list[Any]:
|
||||
slots = [None] * (max_key + 1)
|
||||
for field in normalized:
|
||||
slots[field.key] = extract_value(value, field.name)
|
||||
return slots
|
||||
|
||||
def decode(raw: Any) -> Any:
|
||||
if not isinstance(raw, list):
|
||||
raise ValueError(f"DatabaseEntry document type {type!r} expected a MessagePack array")
|
||||
values: dict[str, Any] = {}
|
||||
for field in normalized:
|
||||
if field.key < len(raw):
|
||||
value = raw[field.key]
|
||||
elif field.default is not MISSING:
|
||||
value = field.default() if callable(field.default) else field.default
|
||||
else:
|
||||
raise ValueError(
|
||||
f"DatabaseEntry document type {type!r} is missing required slot {field.key}"
|
||||
)
|
||||
if value is None and field.default is not MISSING:
|
||||
value = field.default() if callable(field.default) else field.default
|
||||
values[field.name] = value
|
||||
if cls is None:
|
||||
return values
|
||||
return cls(**values)
|
||||
record = _record_codec(type, normalized, cls)
|
||||
|
||||
return define_document_type(
|
||||
type,
|
||||
encode=encode,
|
||||
decode=decode,
|
||||
encode=record.encode,
|
||||
decode=record.decode,
|
||||
validate=validate,
|
||||
global_document=global_document,
|
||||
name=name,
|
||||
indexes=indexes,
|
||||
payload_encoder=_messagepack_payload_encoder,
|
||||
payload_encoder=_pack_tree,
|
||||
payload_decoder=_messagepack_payload_decoder,
|
||||
schema_id=schema_id,
|
||||
schema_name=schema_name,
|
||||
|
|
@ -275,6 +356,81 @@ def define_database_entry_type(
|
|||
)
|
||||
|
||||
|
||||
def define_record_codec(
|
||||
name: str,
|
||||
fields: Iterable[DatabaseEntryField | tuple[str, int] | tuple[str, int, Any]],
|
||||
*,
|
||||
cls: type[Any] | None = None,
|
||||
type_name: str | None = None,
|
||||
) -> SlotCodec:
|
||||
"""A nested record: the same slot array as a document payload, usable as a field's codec or a union arm.
|
||||
`type_name` is the C# FullName of the class it mirrors, for the catalog; without it the catalog names the slot as an untyped one."""
|
||||
return _record_codec(name, _normalize_fields(name, fields), cls, type_name)
|
||||
|
||||
|
||||
def define_union(
|
||||
name: str,
|
||||
arms: Mapping[int, tuple[str, SlotCodec | None]],
|
||||
*,
|
||||
type_name: str | None = None,
|
||||
) -> SlotCodec:
|
||||
"""A union: `[armKey, [armSlots...]]`. Each arm is `(arm name, record codec)`; a unit arm has no codec and is
|
||||
written `[armKey, []]`. A key the union does not declare is refused, never carried, and so is nil: wrap the union
|
||||
in `leaves.nullable` for a slot that may be null. `type_name` is the C# FullName of the interface, for the catalog."""
|
||||
by_key = dict(arms)
|
||||
by_name = {arm_name: (key, codec) for key, (arm_name, codec) in by_key.items()}
|
||||
if not by_key:
|
||||
raise ValueError(f"Union {name!r} requires at least one arm")
|
||||
if len(by_name) != len(by_key):
|
||||
raise ValueError(f"Union {name!r} has duplicate arm names")
|
||||
if any(not _is_key(key) or not _INT32_MIN <= key <= _INT32_MAX for key in by_key):
|
||||
raise ValueError(f"Union {name!r} arm keys must be integers within Int32")
|
||||
if any(codec is not None and not isinstance(codec, SlotCodec) for _, codec in by_key.values()):
|
||||
raise ValueError(f"Union {name!r} arm codecs must be SlotCodecs or None")
|
||||
|
||||
def encode(value: Any) -> Any:
|
||||
if value is None:
|
||||
raise ValueError(f"Union {name!r}: expected an arm, found nil")
|
||||
if not isinstance(value, UnionArm) or value.name not in by_name:
|
||||
raise ValueError(f"Union {name!r} was given a value that is not one of its arms")
|
||||
key, codec = by_name[value.name]
|
||||
if codec is None:
|
||||
if value.value is not None:
|
||||
raise ValueError(f"Union {name!r} arm {key} is a unit arm and carries no value")
|
||||
return [key, []]
|
||||
try:
|
||||
return [key, codec.encode(value.value)]
|
||||
except ValueError as error:
|
||||
raise ValueError(f"Union {name!r} arm {key}: {error}") from None
|
||||
|
||||
def decode(raw: Any) -> Any:
|
||||
if raw is None:
|
||||
raise ValueError(f"Union {name!r}: expected an arm, found nil")
|
||||
if not isinstance(raw, list) or len(raw) != 2:
|
||||
raise ValueError(f"Union {name!r} value is malformed: expected [armKey, [armSlots]]")
|
||||
key = raw[0]
|
||||
if not _is_key(key):
|
||||
raise ValueError(f"Union {name!r} value is malformed: the arm key is non-integer")
|
||||
if not _INT32_MIN <= key <= _INT32_MAX:
|
||||
raise ValueError(f"Union {name!r} value is malformed: the arm key is outside Int32")
|
||||
if key not in by_key:
|
||||
declared = ", ".join(str(declared_key) for declared_key in sorted(by_key))
|
||||
raise ValueError(f"Union {name!r} does not declare arm key {key} (declared: {declared})")
|
||||
if raw[1] is None:
|
||||
raise ValueError(f"Union {name!r} arm {key} has nil slots")
|
||||
if not isinstance(raw[1], list):
|
||||
raise ValueError(f"Union {name!r} value is malformed: expected [armKey, [armSlots]]")
|
||||
arm_name, codec = by_key[key]
|
||||
if codec is None:
|
||||
return UnionArm(arm_name, None)
|
||||
try:
|
||||
return UnionArm(arm_name, codec.decode(raw[1]))
|
||||
except ValueError as error:
|
||||
raise ValueError(f"Union {name!r} arm {key}: {error}") from None
|
||||
|
||||
return SlotCodec(encode=encode, decode=decode, type_name=type_name)
|
||||
|
||||
|
||||
def define_document_registry(*documents: DocumentDefinition[Any]) -> tuple[DocumentDefinition[Any], ...]:
|
||||
return tuple(documents)
|
||||
|
||||
|
|
@ -287,6 +443,64 @@ def extract_value(value: Any, extractor: str | Extractor[Any]) -> str | int | fl
|
|||
return getattr(value, extractor, None)
|
||||
|
||||
|
||||
_INT32_MIN = -(2**31)
|
||||
_INT32_MAX = 2**31 - 1
|
||||
|
||||
|
||||
def _is_key(value: Any) -> bool:
|
||||
return isinstance(value, int) and not isinstance(value, bool)
|
||||
|
||||
|
||||
def _normalize_fields(
|
||||
type: str,
|
||||
fields: Iterable[DatabaseEntryField | tuple[str, int] | tuple[str, int, Any]],
|
||||
) -> list[DatabaseEntryField]:
|
||||
normalized = [_normalize_database_entry_field(field) for field in fields]
|
||||
if not normalized:
|
||||
raise ValueError("DatabaseEntry document types require at least one field")
|
||||
keys = [field.key for field in normalized]
|
||||
if len(keys) != len(set(keys)):
|
||||
raise ValueError(f"DatabaseEntry document type {type!r} has duplicate field keys")
|
||||
return sorted(normalized, key=lambda field: field.key)
|
||||
|
||||
|
||||
def _record_codec(
|
||||
type: str, normalized: list[DatabaseEntryField], cls: type[Any] | None, type_name: str | None = None
|
||||
) -> SlotCodec:
|
||||
max_key = normalized[-1].key
|
||||
|
||||
def encode(value: Any) -> list[Any]:
|
||||
if value is None:
|
||||
raise ValueError(f"DatabaseEntry document type {type!r}: expected a record, found nil")
|
||||
slots = [None] * (max_key + 1)
|
||||
for field in normalized:
|
||||
try:
|
||||
slots[field.key] = field.codec.encode(extract_value(value, field.name))
|
||||
except ValueError as error:
|
||||
raise ValueError(f"{type} slot {field.key} ({field.name}): {error}") from None
|
||||
return slots
|
||||
|
||||
def decode(raw: Any) -> Any:
|
||||
if not isinstance(raw, list):
|
||||
raise ValueError(f"DatabaseEntry document type {type!r} expected a MessagePack array")
|
||||
values: dict[str, Any] = {}
|
||||
for field in normalized:
|
||||
if field.key < len(raw):
|
||||
try:
|
||||
values[field.name] = field.codec.decode(raw[field.key])
|
||||
except ValueError as error:
|
||||
raise ValueError(f"{type} slot {field.key} ({field.name}): {error}") from None
|
||||
elif field.default is MISSING:
|
||||
values[field.name] = None
|
||||
else:
|
||||
values[field.name] = field.default() if callable(field.default) else field.default
|
||||
if cls is None:
|
||||
return values
|
||||
return cls(**values)
|
||||
|
||||
return SlotCodec(encode=encode, decode=decode, type_name=type_name)
|
||||
|
||||
|
||||
def _normalize_database_entry_field(
|
||||
field: DatabaseEntryField | tuple[str, int] | tuple[str, int, Any],
|
||||
) -> DatabaseEntryField:
|
||||
|
|
|
|||
|
|
@ -1,50 +1,29 @@
|
|||
from __future__ import annotations
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
import msgpack
|
||||
|
||||
from . import CultCache, CultCacheSchemaCatalogMember, SingleFileMessagePackBackingStore, define_document_type
|
||||
from . import CultCache, SingleFileMessagePackBackingStore, database_entry_field, define_database_entry_type, leaves as t
|
||||
|
||||
INTEROP_SCHEMA_VERSION = "cultcache.interop_note.v1"
|
||||
|
||||
interop_note_document = define_document_type(
|
||||
interop_note_document = define_database_entry_type(
|
||||
"cultcache.interop-note",
|
||||
encode=lambda note: [
|
||||
note["schemaVersion"],
|
||||
note["documentId"],
|
||||
note["authorRuntimeId"],
|
||||
note["title"],
|
||||
note["body"],
|
||||
note["tags"],
|
||||
[
|
||||
database_entry_field("schemaVersion", 0, codec=t.nullable(t.string)),
|
||||
database_entry_field("documentId", 1, codec=t.nullable(t.string)),
|
||||
database_entry_field("authorRuntimeId", 2, codec=t.nullable(t.string)),
|
||||
database_entry_field("title", 3, codec=t.nullable(t.string)),
|
||||
database_entry_field("body", 4, codec=t.nullable(t.string)),
|
||||
database_entry_field("tags", 5, default=list, codec=t.nullable(t.array(t.string))),
|
||||
],
|
||||
decode=lambda slots: {
|
||||
"schemaVersion": slots[0],
|
||||
"documentId": slots[1],
|
||||
"authorRuntimeId": slots[2],
|
||||
"title": slots[3],
|
||||
"body": slots[4],
|
||||
"tags": slots[5] if len(slots) > 5 and slots[5] is not None else [],
|
||||
},
|
||||
name="documentId",
|
||||
payload_encoder=lambda value: msgpack.packb(value, use_bin_type=True),
|
||||
payload_decoder=lambda payload: msgpack.unpackb(payload, raw=False),
|
||||
schema_id="cultcache.interop-note",
|
||||
schema_name="cultcache.interop-note",
|
||||
schema_version=INTEROP_SCHEMA_VERSION,
|
||||
content_hash="cultcache.interop-note",
|
||||
canonical_schema_json='{"schemaName":"cultcache.interop-note","schemaVersion":"cultcache.interop_note.v1","members":[{"slot":0,"name":"SchemaVersion","type":"System.String","isReference":false,"many":false,"targetSchemaName":null,"indexAlias":null,"isName":false},{"slot":1,"name":"DocumentId","type":"System.String","isReference":false,"many":false,"targetSchemaName":null,"indexAlias":null,"isName":true},{"slot":2,"name":"AuthorRuntimeId","type":"System.String","isReference":false,"many":false,"targetSchemaName":null,"indexAlias":null,"isName":false},{"slot":3,"name":"Title","type":"System.String","isReference":false,"many":false,"targetSchemaName":null,"indexAlias":null,"isName":false},{"slot":4,"name":"Body","type":"System.String","isReference":false,"many":false,"targetSchemaName":null,"indexAlias":null,"isName":false},{"slot":5,"name":"Tags","type":"System.String[]","isReference":false,"many":false,"targetSchemaName":null,"indexAlias":null,"isName":false}]}',
|
||||
compatible_schema_ids=("cultcache.interop-note",),
|
||||
members=(
|
||||
CultCacheSchemaCatalogMember(0, "SchemaVersion", "System.String"),
|
||||
CultCacheSchemaCatalogMember(1, "DocumentId", "System.String", is_name=True),
|
||||
CultCacheSchemaCatalogMember(2, "AuthorRuntimeId", "System.String"),
|
||||
CultCacheSchemaCatalogMember(3, "Title", "System.String"),
|
||||
CultCacheSchemaCatalogMember(4, "Body", "System.String"),
|
||||
CultCacheSchemaCatalogMember(5, "Tags", "System.String[]"),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
|
|
|
|||
294
packages/cultcache-py/src/cultcache_py/leaves.py
Normal file
294
packages/cultcache-py/src/cultcache_py/leaves.py
Normal file
|
|
@ -0,0 +1,294 @@
|
|||
"""Typed slot leaves: each owns its slot's C# type name, its write check and its read check, nil included.
|
||||
|
||||
A leaf is a `SlotCodec`. It turns a Python value into the tree the reference runtimes write and back, refusing a
|
||||
kind the C# type would refuse. Refusals read '<what was expected>, found <kind>' and never carry the value; the
|
||||
record codec prefixes them with the type, slot key and field, a list with the element, a union with its arm.
|
||||
|
||||
Several names here (`bytes`, `list`, `any`) shadow builtins inside this module on purpose: write
|
||||
`from cultcache_py import leaves as t` and use `t.string`, `t.list(t.string)`.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import struct
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Callable, NoReturn
|
||||
|
||||
try:
|
||||
from msgpack import ExtType as _ExtType
|
||||
except ModuleNotFoundError:
|
||||
_ExtType = () # type: ignore[assignment,misc]
|
||||
|
||||
_bool, _bytes, _list, _int, _float, _str = bool, bytes, list, int, float, str
|
||||
_BYTE_LIKE = (_bytes, bytearray, memoryview)
|
||||
_INT32 = (-(2**31), 2**31 - 1)
|
||||
_INT64 = (-(2**63), 2**63 - 1)
|
||||
_WRITABLE_INT = (-(2**63), 2**64 - 1)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SlotCodec:
|
||||
"""The leaf of one slot: how a value is written and read, and the C# type name the catalog carries for it.
|
||||
|
||||
`type_name` is the reference's name for the slot's type (None when only the consumer knows it: a record or union
|
||||
without `type_name=`, which the catalog lists as System.Object). `value_type` is True for a C# value type, which
|
||||
the reference makes `Nullable<T>` when the slot may be nil."""
|
||||
|
||||
encode: Callable[[Any], Any]
|
||||
decode: Callable[[Any], Any]
|
||||
type_name: str | None = None
|
||||
value_type: bool = False
|
||||
|
||||
|
||||
class _Derived(SlotCodec):
|
||||
"""A leaf whose name comes from another leaf, read when the catalog is built, so a `lazy` target defined later resolves."""
|
||||
|
||||
def __init__(self, encode: Callable[[Any], Any], decode: Callable[[Any], Any], name: Callable[[], str | None],
|
||||
value_type: Callable[[], _bool] = lambda: False) -> None:
|
||||
object.__setattr__(self, "encode", encode)
|
||||
object.__setattr__(self, "decode", decode)
|
||||
object.__setattr__(self, "_name", name)
|
||||
object.__setattr__(self, "_value_type", value_type)
|
||||
|
||||
@property # type: ignore[override]
|
||||
def type_name(self) -> str | None:
|
||||
return self._name() # type: ignore[attr-defined,no-any-return]
|
||||
|
||||
@property # type: ignore[override]
|
||||
def value_type(self) -> _bool:
|
||||
return self._value_type() # type: ignore[attr-defined,no-any-return]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Float32:
|
||||
"""A float32 the float32 leaf writes, already rounded to float32 (an overflow is infinity, as the C# cast): the
|
||||
payload packer writes it as MessagePack float 32."""
|
||||
|
||||
value: float
|
||||
|
||||
|
||||
def _kind(raw: Any) -> str:
|
||||
if raw is None:
|
||||
return "nil"
|
||||
if isinstance(raw, _bool):
|
||||
return "boolean"
|
||||
if isinstance(raw, _int):
|
||||
return "integer"
|
||||
if isinstance(raw, (_float, Float32)):
|
||||
return "float"
|
||||
if isinstance(raw, _str):
|
||||
return "string"
|
||||
if isinstance(raw, _BYTE_LIKE):
|
||||
return "bytes"
|
||||
if isinstance(raw, _ExtType): # a namedtuple, so before the arrays
|
||||
return "ext"
|
||||
if isinstance(raw, (_list, tuple)):
|
||||
return "array"
|
||||
return "map" if isinstance(raw, Mapping) else "other"
|
||||
|
||||
|
||||
def _refuse(what: str, found: str) -> NoReturn:
|
||||
raise ValueError(f"expected {what}, found {found}")
|
||||
|
||||
|
||||
def _is_int(raw: Any) -> _bool:
|
||||
return isinstance(raw, _int) and not isinstance(raw, _bool)
|
||||
|
||||
|
||||
def _string_encode(value: Any) -> Any:
|
||||
if not isinstance(value, _str):
|
||||
_refuse("a string", _kind(value))
|
||||
return value
|
||||
|
||||
|
||||
string = SlotCodec(_string_encode, _string_encode, "System.String")
|
||||
|
||||
|
||||
def _boolean_check(value: Any) -> Any:
|
||||
if not isinstance(value, _bool):
|
||||
_refuse("a boolean", _kind(value))
|
||||
return value
|
||||
|
||||
|
||||
boolean = SlotCodec(_boolean_check, _boolean_check, "System.Boolean", True)
|
||||
|
||||
|
||||
def _bytes_encode(value: Any) -> Any:
|
||||
if not isinstance(value, _BYTE_LIKE):
|
||||
_refuse("bytes", _kind(value))
|
||||
return value if isinstance(value, _bytes) else _bytes(value)
|
||||
|
||||
|
||||
def _bytes_decode(raw: Any) -> Any:
|
||||
# The reference's byte[] reads a MessagePack str as its UTF-8 bytes and writes bin.
|
||||
if isinstance(raw, _str):
|
||||
return raw.encode("utf-8")
|
||||
if not isinstance(raw, _bytes):
|
||||
_refuse("bytes", _kind(raw))
|
||||
return raw
|
||||
|
||||
|
||||
bytes = SlotCodec(_bytes_encode, _bytes_decode, "System.Byte[]")
|
||||
|
||||
|
||||
def _integer(type_name: str, what: str, low: _int, high: _int) -> SlotCodec:
|
||||
def check(value: Any) -> Any:
|
||||
if not _is_int(value):
|
||||
_refuse(what, _kind(value))
|
||||
if not low <= value <= high:
|
||||
_refuse(what, "an integer out of range")
|
||||
return value
|
||||
|
||||
return SlotCodec(check, check, type_name, True)
|
||||
|
||||
|
||||
int32 = _integer("System.Int32", "an int32", *_INT32)
|
||||
int64 = _integer("System.Int64", "an int64", *_INT64)
|
||||
|
||||
|
||||
def _round_to_float32(value: _float) -> _float:
|
||||
try:
|
||||
return struct.unpack(">f", struct.pack(">f", value))[0] # type: ignore[no-any-return]
|
||||
except OverflowError:
|
||||
return math.copysign(math.inf, value)
|
||||
|
||||
|
||||
def _int_to_float32(value: _int) -> _float:
|
||||
"""An integer to the nearest float32 in one rounding, ties to even, as the reference's cast does: through a double
|
||||
first, the two roundings can disagree past 2**53."""
|
||||
if -(2**53) <= value <= 2**53:
|
||||
return _round_to_float32(_float(value))
|
||||
magnitude = -value if value < 0 else value
|
||||
excess = magnitude.bit_length() - 24
|
||||
kept = magnitude >> excess
|
||||
rest = magnitude - (kept << excess)
|
||||
half = 1 << (excess - 1)
|
||||
rounded = _float((kept + 1 if rest > half or (rest == half and kept & 1) else kept) << excess)
|
||||
return -rounded if value < 0 else rounded
|
||||
|
||||
|
||||
def _checked_int(what: str, value: _int) -> _int:
|
||||
if not _WRITABLE_INT[0] <= value <= _WRITABLE_INT[1]:
|
||||
_refuse(what, "an integer out of range")
|
||||
return value
|
||||
|
||||
|
||||
def _number(what: str, value: Any) -> _float:
|
||||
"""A number as a double: a float as it is, an integer (within the 64-bit range) rounded once."""
|
||||
if isinstance(value, _float):
|
||||
return value
|
||||
if not _is_int(value):
|
||||
_refuse(what, _kind(value))
|
||||
return _float(_checked_int(what, value))
|
||||
|
||||
|
||||
def _float32_value(value: Any) -> _float:
|
||||
"""The float32 a number rounds to, in one rounding, as the reference's cast does."""
|
||||
if _is_int(value):
|
||||
return _int_to_float32(_checked_int("a float32", value))
|
||||
return _round_to_float32(_number("a float32", value))
|
||||
|
||||
|
||||
def _float32_encode(value: Any) -> Any:
|
||||
return Float32(_float32_value(value))
|
||||
|
||||
|
||||
def _float64_check(value: Any) -> Any:
|
||||
return _number("a float64", value)
|
||||
|
||||
|
||||
float32 = SlotCodec(_float32_encode, _float32_value, "System.Single", True)
|
||||
float64 = SlotCodec(_float64_check, _float64_check, "System.Double", True)
|
||||
|
||||
|
||||
def _refuse_ext(tree: Any) -> None:
|
||||
"""The reference reads an `object` slot as a plain value or a timestamp; any other extension is refused."""
|
||||
stack = [tree]
|
||||
while stack:
|
||||
node = stack.pop()
|
||||
if isinstance(node, _ExtType):
|
||||
_refuse("an object", "ext")
|
||||
if isinstance(node, Mapping):
|
||||
stack.extend(node.keys())
|
||||
stack.extend(node.values())
|
||||
elif isinstance(node, (_list, tuple)):
|
||||
stack.extend(node)
|
||||
|
||||
|
||||
def _any_check(value: Any) -> Any:
|
||||
_refuse_ext(value)
|
||||
return value
|
||||
|
||||
|
||||
any = SlotCodec(_any_check, _any_check, "System.Object")
|
||||
|
||||
|
||||
def _sequence(item: SlotCodec, wrap: Callable[[str], str]) -> SlotCodec:
|
||||
def encode(value: Any) -> Any:
|
||||
if not isinstance(value, (_list, tuple)):
|
||||
_refuse("an array", _kind(value))
|
||||
out = []
|
||||
for index, element in enumerate(value):
|
||||
try:
|
||||
out.append(item.encode(element))
|
||||
except ValueError as error:
|
||||
raise ValueError(f"element {index}: {error}") from None
|
||||
return out
|
||||
|
||||
def decode(raw: Any) -> Any:
|
||||
if not isinstance(raw, _list):
|
||||
_refuse("an array", _kind(raw))
|
||||
out = []
|
||||
for index, element in enumerate(raw):
|
||||
try:
|
||||
out.append(item.decode(element))
|
||||
except ValueError as error:
|
||||
raise ValueError(f"element {index}: {error}") from None
|
||||
return out
|
||||
|
||||
return _Derived(encode, decode, lambda: None if item.type_name is None else wrap(item.type_name))
|
||||
|
||||
|
||||
def list(item: SlotCodec) -> SlotCodec:
|
||||
"""C# `List<T>`."""
|
||||
return _sequence(item, lambda name: f"System.Collections.Generic.List<{name}>")
|
||||
|
||||
|
||||
def array(item: SlotCodec) -> SlotCodec:
|
||||
"""C# `T[]`: the same wire as `list`."""
|
||||
return _sequence(item, lambda name: f"{name}[]")
|
||||
|
||||
|
||||
def nullable(inner: SlotCodec) -> SlotCodec:
|
||||
"""A slot that may be nil: None both ways, otherwise `inner`. A C# reference type (string, byte[], List, array,
|
||||
class, interface) is nullable as it is; a value type is `Nullable<T>`."""
|
||||
|
||||
def name() -> str | None:
|
||||
if inner.type_name is not None and inner.value_type:
|
||||
return f"System.Nullable<{inner.type_name}>"
|
||||
return inner.type_name
|
||||
|
||||
return _Derived(
|
||||
lambda value: None if value is None else inner.encode(value),
|
||||
lambda raw: None if raw is None else inner.decode(raw),
|
||||
name,
|
||||
)
|
||||
|
||||
|
||||
def lazy(get: Callable[[], SlotCodec]) -> SlotCodec:
|
||||
"""A leaf that names its target on first use, so a union can refer to itself or to a definition made later."""
|
||||
resolved: _list[SlotCodec] = []
|
||||
|
||||
def target() -> SlotCodec:
|
||||
if not resolved:
|
||||
resolved.append(get())
|
||||
return resolved[0]
|
||||
|
||||
return _Derived(
|
||||
lambda value: target().encode(value),
|
||||
lambda raw: target().decode(raw),
|
||||
lambda: target().type_name,
|
||||
lambda: target().value_type,
|
||||
)
|
||||
733
packages/cultcache-py/tests/test_typed_leaves.py
Normal file
733
packages/cultcache-py/tests/test_typed_leaves.py
Normal file
|
|
@ -0,0 +1,733 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import struct
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
import msgpack
|
||||
|
||||
from cultcache_py import (
|
||||
CultCache,
|
||||
SingleFileMessagePackBackingStore,
|
||||
UnionArm,
|
||||
database_entry_field,
|
||||
define_database_entry_type,
|
||||
define_record_codec,
|
||||
define_union,
|
||||
leaves as t,
|
||||
)
|
||||
from cultcache_py.documents import _pack_tree
|
||||
from cultcache_py.interop import interop_note_document
|
||||
|
||||
VECTORS = Path(__file__).resolve().parents[3] / "tests" / "vectors" / "numeric-leaves"
|
||||
CANARY = "CANARY-leaf-9d41"
|
||||
REFERENCE = "GameCult.Caching.Tests.NumericLeafVectorTests+"
|
||||
|
||||
|
||||
def _vector(name: str) -> list:
|
||||
return msgpack.unpackb((VECTORS / name).read_bytes(), raw=False)
|
||||
|
||||
|
||||
def _slot(leaf: t.SlotCodec):
|
||||
return define_database_entry_type("tests.leaf", [database_entry_field("v", 0, codec=leaf)])
|
||||
|
||||
|
||||
def _doubles(bits: bytes) -> float:
|
||||
return struct.unpack(">d", bits)[0]
|
||||
|
||||
|
||||
def _is_signalling_float32(payload: bytes) -> bool:
|
||||
if len(payload) != 6 or payload[1] != 0xCA:
|
||||
return False
|
||||
word = struct.unpack(">I", payload[2:])[0]
|
||||
return word & 0x7F800000 == 0x7F800000 and word & 0x007FFFFF != 0 and word & 0x00400000 == 0
|
||||
|
||||
|
||||
def _kinded(node):
|
||||
"""A decoded tree with its kinds kept: bool, int and float never compare equal; numeric width is not part of it."""
|
||||
if isinstance(node, bool):
|
||||
return ("bool", node)
|
||||
if isinstance(node, int):
|
||||
return ("int", node)
|
||||
if isinstance(node, float):
|
||||
return ("float", "nan" if math.isnan(node) else struct.pack(">d", node))
|
||||
if isinstance(node, (list, tuple)):
|
||||
return ("array", [_kinded(item) for item in node])
|
||||
if isinstance(node, dict):
|
||||
return ("map", [(_kinded(k), _kinded(v)) for k, v in node.items()])
|
||||
return (type(node).__name__, node)
|
||||
|
||||
|
||||
NUMERIC = {"int32": t.int32, "int64": t.int64, "float32": t.float32, "float64": t.float64}
|
||||
|
||||
|
||||
class NumericVectorTests(unittest.TestCase):
|
||||
def test_reads_accept_refuse_and_round_exactly_as_the_reference(self) -> None:
|
||||
rows = _vector("reads.msgpack")
|
||||
self.assertEqual(len(rows), 160)
|
||||
accepted = refused = 0
|
||||
for leaf, payload, was_accepted, bits in rows:
|
||||
label = f"{leaf} {payload.hex()}"
|
||||
document = _slot(NUMERIC[leaf])
|
||||
if not was_accepted:
|
||||
with self.assertRaises(ValueError, msg=label):
|
||||
document.decode_payload(payload)
|
||||
refused += 1
|
||||
continue
|
||||
read = document.decode_payload(payload)["v"]
|
||||
if leaf.startswith("float"):
|
||||
if math.isnan(_doubles(bits)):
|
||||
self.assertTrue(math.isnan(read), label)
|
||||
else:
|
||||
self.assertEqual(struct.pack(">d", read), bits, label)
|
||||
else:
|
||||
self.assertEqual(read, int.from_bytes(bits, "big", signed=True), label)
|
||||
accepted += 1
|
||||
self.assertEqual((accepted + refused, accepted > 40, refused > 40), (160, True, True))
|
||||
|
||||
def test_writes_are_the_bytes_the_reference_writes(self) -> None:
|
||||
rows = _vector("writes.msgpack")
|
||||
self.assertEqual(len(rows), 46)
|
||||
for leaf, text, expected in rows:
|
||||
value = _doubles(bytes.fromhex(text)) if leaf.startswith("float") else int(text)
|
||||
self.assertEqual(_slot(NUMERIC[leaf]).encode_payload({"v": value}), expected, f"{leaf} {text}")
|
||||
|
||||
def test_the_mixed_record_is_written_byte_for_byte_and_read_back(self) -> None:
|
||||
mixed = define_database_entry_type(
|
||||
"tests.mixed",
|
||||
[
|
||||
database_entry_field("id", 0, codec=t.string),
|
||||
database_entry_field("i", 1, codec=t.int32),
|
||||
database_entry_field("l", 2, codec=t.int64),
|
||||
database_entry_field("f", 3, codec=t.float32),
|
||||
database_entry_field("d", 4, codec=t.float64),
|
||||
],
|
||||
)
|
||||
committed = (VECTORS / "mixed-record.msgpack").read_bytes()
|
||||
value = {"id": "n1", "i": 7, "l": 8, "f": 1.5, "d": 2.5}
|
||||
self.assertEqual(mixed.encode_payload(value), committed)
|
||||
self.assertEqual(mixed.decode_payload(committed), value)
|
||||
|
||||
def test_float32_infinities_and_quiet_nans_keep_their_bits_and_signalling_ones_come_back_quieted(self) -> None:
|
||||
rows = _vector("float32-nan.msgpack")
|
||||
self.assertEqual(len(rows), 6)
|
||||
document = _slot(t.float32)
|
||||
quieted = 0
|
||||
for payload, reference in rows:
|
||||
written = document.encode_payload(document.decode_payload(payload))
|
||||
if _is_signalling_float32(payload):
|
||||
# follow_up py-float32-snan-quieted: msgpack's unpacker quiets the NaN before the leaf sees it.
|
||||
self.assertEqual(reference, payload, "the reference keeps the signalling bits")
|
||||
word = struct.unpack(">I", payload[2:])[0] | 0x00400000
|
||||
self.assertEqual(written, b"\x91\xca" + struct.pack(">I", word))
|
||||
quieted += 1
|
||||
else:
|
||||
self.assertEqual(written, reference, payload.hex())
|
||||
self.assertEqual(quieted, 3)
|
||||
|
||||
|
||||
def _inner_record() -> t.SlotCodec:
|
||||
return define_record_codec(
|
||||
"LeafInner",
|
||||
[
|
||||
database_entry_field("n", 0, default="", codec=t.string),
|
||||
database_entry_field("w", 1, default=0.0, codec=t.float32),
|
||||
],
|
||||
type_name=REFERENCE + "LeafInner",
|
||||
)
|
||||
|
||||
|
||||
def _shape() -> t.SlotCodec:
|
||||
circle = define_record_codec(
|
||||
"LeafCircle", [database_entry_field("r", 0, default=0.0, codec=t.float32)], type_name=REFERENCE + "LeafCircle"
|
||||
)
|
||||
return define_union("LeafShape", {0: ("LeafCircle", circle)}, type_name=REFERENCE + "ILeafShape")
|
||||
|
||||
|
||||
# The C# slot types of leaves-reads.msgpack, each as a reference-type slot that may be null (nullable) and bare.
|
||||
def _reference_leaves(nullable: bool) -> dict[str, t.SlotCodec]:
|
||||
inner, shape = _inner_record(), _shape()
|
||||
wrap = t.nullable if nullable else (lambda leaf: leaf)
|
||||
return {
|
||||
"string": wrap(t.string),
|
||||
"bytes": wrap(t.bytes),
|
||||
"list-string": wrap(t.list(t.string)),
|
||||
"array-string": wrap(t.array(t.string)),
|
||||
"list-int32": wrap(t.list(t.int32)),
|
||||
"record": wrap(inner),
|
||||
"list-record": wrap(t.list(inner)),
|
||||
"union": wrap(shape),
|
||||
}
|
||||
|
||||
|
||||
class LeavesReadsVectorTests(unittest.TestCase):
|
||||
NIL = bytes.fromhex("91c0")
|
||||
|
||||
def _check(self, leaf_name: str, leaf: t.SlotCodec, rows: list, *, nil_refused: bool = False) -> int:
|
||||
document = _slot(leaf)
|
||||
checked = 0
|
||||
for name, payload, accepted, rewrite in rows:
|
||||
if name != leaf_name:
|
||||
continue
|
||||
label = f"{name} {payload.hex()}"
|
||||
if not accepted or (nil_refused and payload == self.NIL):
|
||||
with self.assertRaises(ValueError, msg=label):
|
||||
document.decode_payload(payload)
|
||||
else:
|
||||
value = document.decode_payload(payload)
|
||||
self.assertEqual(document.encode_payload(value), rewrite, label)
|
||||
checked += 1
|
||||
return checked
|
||||
|
||||
def test_reference_type_leaves_held_as_nullable_read_and_rewrite_exactly_as_csharp(self) -> None:
|
||||
rows = _vector("leaves-reads.msgpack")
|
||||
self.assertEqual(len(rows), 308)
|
||||
extra = {"nullable-int32": t.nullable(t.int32)}
|
||||
for name, leaf in {**_reference_leaves(True), **extra}.items():
|
||||
self.assertEqual(self._check(name, leaf, rows), 28, name)
|
||||
self.assertTrue(any(row[0] == name and row[2] for row in rows) and any(row[0] == name and not row[2] for row in rows), name)
|
||||
|
||||
def test_the_bare_leaf_accepts_the_same_rows_minus_nil(self) -> None:
|
||||
rows = _vector("leaves-reads.msgpack")
|
||||
for name, leaf in _reference_leaves(False).items():
|
||||
self.assertEqual(self._check(name, leaf, rows, nil_refused=True), 28, name)
|
||||
|
||||
def test_boolean_is_a_bare_value_leaf(self) -> None:
|
||||
self.assertEqual(self._check("boolean", t.boolean, _vector("leaves-reads.msgpack")), 28)
|
||||
|
||||
def test_any_reads_what_the_reference_reads_and_rewrites_to_the_same_value(self) -> None:
|
||||
# ruling any-rewrite-binds-kind-and-value: the kind and exact value of the rewrite, recursively; numeric width is free ("05" -> "cc05").
|
||||
rows = _vector("leaves-reads.msgpack")
|
||||
document = _slot(t.any)
|
||||
count = 0
|
||||
for name, payload, accepted, rewrite in rows:
|
||||
if name != "any":
|
||||
continue
|
||||
label = f"any {payload.hex()}"
|
||||
if not accepted:
|
||||
with self.assertRaises(ValueError, msg=label):
|
||||
document.decode_payload(payload)
|
||||
else:
|
||||
written = document.encode_payload(document.decode_payload(payload))
|
||||
self.assertEqual(_kinded(msgpack.unpackb(written, raw=False)), _kinded(msgpack.unpackb(rewrite, raw=False)), label)
|
||||
count += 1
|
||||
self.assertEqual(count, 28)
|
||||
|
||||
def test_the_any_comparison_tells_bool_int_and_float_apart_and_ignores_only_numeric_width(self) -> None:
|
||||
# ruling any-rewrite-binds-kind-and-value: Python's == makes True == 1 == 1.0; _kinded does not.
|
||||
self.assertNotEqual(_kinded([True]), _kinded([1]))
|
||||
self.assertNotEqual(_kinded([1]), _kinded([1.0]))
|
||||
self.assertNotEqual(_kinded({"k": [5]}), _kinded({"k": [5.0]}))
|
||||
self.assertNotEqual(_kinded([0.0]), _kinded([-0.0]))
|
||||
self.assertNotEqual(_kinded(["a"]), _kinded([b"a"]))
|
||||
self.assertEqual(_kinded(msgpack.unpackb(bytes.fromhex("9105"))), _kinded(msgpack.unpackb(bytes.fromhex("91cc05"))))
|
||||
self.assertEqual(
|
||||
_kinded(msgpack.unpackb(bytes.fromhex("91ca3fc00000"))), _kinded(msgpack.unpackb(bytes.fromhex("91cb3ff8000000000000")))
|
||||
)
|
||||
|
||||
def test_any_refuses_an_extension_that_is_not_a_timestamp_wherever_it_nests(self) -> None:
|
||||
document = _slot(t.any)
|
||||
for payload in (bytes.fromhex("91d40100"), bytes.fromhex("9191d40100"), bytes.fromhex("9181a161d40100")):
|
||||
with self.assertRaises(ValueError, msg=payload.hex()):
|
||||
document.decode_payload(payload)
|
||||
with self.assertRaises(ValueError):
|
||||
t.any.encode({"k": [msgpack.ExtType(1, b"\x00")]})
|
||||
with self.assertRaises(ValueError) as caught:
|
||||
t.any.decode(msgpack.ExtType(1, b"\x00"))
|
||||
self.assertEqual(str(caught.exception), "expected an object, found ext")
|
||||
self.assertIsNone(t.any.decode(None))
|
||||
self.assertIsNone(t.any.encode(None))
|
||||
|
||||
|
||||
def _leaf_record_document():
|
||||
inner, shape = _inner_record(), _shape()
|
||||
document = define_database_entry_type(
|
||||
"cultcache.leaf-record",
|
||||
[
|
||||
database_entry_field("id", 0, codec=t.string),
|
||||
database_entry_field("flag", 1, codec=t.boolean),
|
||||
database_entry_field("blob", 2, codec=t.bytes),
|
||||
database_entry_field("i", 3, codec=t.int32),
|
||||
database_entry_field("l", 4, codec=t.int64),
|
||||
database_entry_field("f", 5, codec=t.float32),
|
||||
database_entry_field("d", 6, codec=t.float64),
|
||||
database_entry_field("maybe_i", 7, codec=t.nullable(t.int32)),
|
||||
database_entry_field("tags", 8, codec=t.list(t.string)),
|
||||
database_entry_field("names", 9, codec=t.array(t.string)),
|
||||
database_entry_field("any", 10, codec=t.any),
|
||||
database_entry_field("nested", 11, codec=t.nullable(inner)),
|
||||
database_entry_field("items", 12, codec=t.list(inner)),
|
||||
database_entry_field("shape", 13, codec=t.nullable(shape)),
|
||||
database_entry_field("floats", 14, codec=t.array(t.float32)),
|
||||
database_entry_field("maybe_f", 15, codec=t.nullable(t.float32)),
|
||||
],
|
||||
name="id",
|
||||
)
|
||||
return document
|
||||
|
||||
|
||||
class LeafRecordCatalogTests(unittest.TestCase):
|
||||
def test_a_python_mirror_derives_the_catalog_the_csharp_store_writes_and_the_payload_round_trips(self) -> None:
|
||||
document = _leaf_record_document()
|
||||
members, payload = _vector("leaf-record.msgpack")
|
||||
derived = [
|
||||
[m.slot, m.member_name, m.type_name, m.is_reference, m.is_many, m.target_schema_name, m.is_name, m.index_alias]
|
||||
for m in document.catalog_entry().members
|
||||
]
|
||||
self.assertEqual(derived, members)
|
||||
self.assertEqual(document.encode_payload(document.decode_payload(payload)), payload)
|
||||
|
||||
def test_nullable_names_a_value_type_nullable_and_a_reference_type_as_itself(self) -> None:
|
||||
self.assertEqual(t.nullable(t.int32).type_name, "System.Nullable<System.Int32>")
|
||||
self.assertEqual(t.nullable(t.boolean).type_name, "System.Nullable<System.Boolean>")
|
||||
self.assertEqual(t.nullable(t.string).type_name, "System.String")
|
||||
self.assertEqual(t.nullable(t.list(t.string)).type_name, "System.Collections.Generic.List<System.String>")
|
||||
self.assertEqual(t.array(t.nullable(t.int64)).type_name, "System.Nullable<System.Int64>[]")
|
||||
self.assertEqual(t.array(t.float32).type_name, "System.Single[]")
|
||||
self.assertEqual(t.bytes.type_name, "System.Byte[]")
|
||||
self.assertFalse(t.nullable(t.int32).value_type)
|
||||
self.assertEqual([c.value_type for c in (t.string, t.boolean, t.bytes, t.int32, t.int64, t.float32, t.float64, t.any)],
|
||||
[False, True, False, True, True, True, True, False])
|
||||
|
||||
def test_an_unnamed_record_or_union_is_listed_as_an_untyped_slot_and_a_list_of_one_too(self) -> None:
|
||||
record = define_record_codec("Plain", [("a", 0)])
|
||||
self.assertIsNone(record.type_name)
|
||||
self.assertIsNone(t.list(record).type_name)
|
||||
self.assertIsNone(t.nullable(record).type_name)
|
||||
document = define_database_entry_type(
|
||||
"tests.unnamed", [database_entry_field("r", 0, codec=record), database_entry_field("l", 1, codec=t.list(record))]
|
||||
)
|
||||
self.assertEqual([m.type_name for m in document.catalog_entry().members], ["System.Object", "System.Object"])
|
||||
|
||||
def test_a_recursive_union_through_lazy_encodes_decodes_and_names_its_type(self) -> None:
|
||||
link = define_record_codec(
|
||||
"Link", [database_entry_field("next", 0, codec=t.nullable(t.lazy(lambda: chain)))], type_name="Tests.Link"
|
||||
)
|
||||
chain = define_union("Chain", {0: ("Link", link), 1: ("End", None)}, type_name="Tests.Chain")
|
||||
self.assertEqual(t.lazy(lambda: chain).type_name, "Tests.Chain")
|
||||
self.assertEqual(t.nullable(t.lazy(lambda: chain)).type_name, "Tests.Chain")
|
||||
value = UnionArm("Link", {"next": UnionArm("Link", {"next": UnionArm("End")})})
|
||||
written = chain.encode(value)
|
||||
self.assertEqual(written, [0, [[0, [[1, []]]]]])
|
||||
self.assertEqual(chain.decode(written), value)
|
||||
self.assertIs(t.lazy(lambda: t.int32).value_type, True)
|
||||
document = define_database_entry_type("tests.chain", [database_entry_field("root", 0, codec=t.nullable(chain))])
|
||||
self.assertEqual(document.catalog_entry().members[0].type_name, "Tests.Chain")
|
||||
|
||||
def test_a_lazy_leaf_resolves_its_target_once(self) -> None:
|
||||
calls = []
|
||||
leaf = t.lazy(lambda: calls.append(1) or t.int32)
|
||||
self.assertEqual(calls, [])
|
||||
leaf.encode(1)
|
||||
leaf.decode(2)
|
||||
leaf.type_name
|
||||
self.assertEqual(calls, [1])
|
||||
|
||||
|
||||
class SlotNilAndDefaultTests(unittest.TestCase):
|
||||
def test_a_present_nil_goes_to_the_leaf_and_a_default_fills_only_a_slot_past_the_payloads_end(self) -> None:
|
||||
document = define_database_entry_type(
|
||||
"tests.defaults",
|
||||
[
|
||||
database_entry_field("count", 0, default=0, codec=t.int32),
|
||||
database_entry_field("label", 1, default="", codec=t.string),
|
||||
database_entry_field("maybe", 2, default="dflt", codec=t.nullable(t.string)),
|
||||
database_entry_field("tags", 3, default=list, codec=t.list(t.string)),
|
||||
],
|
||||
)
|
||||
self.assertEqual(
|
||||
document.decode_payload(msgpack.packb([3, "x", None, ["a"]])), {"count": 3, "label": "x", "maybe": None, "tags": ["a"]}
|
||||
)
|
||||
self.assertEqual(document.decode_payload(msgpack.packb([3])), {"count": 3, "label": "", "maybe": "dflt", "tags": []})
|
||||
self.assertIsNot(
|
||||
document.decode_payload(msgpack.packb([3]))["tags"], document.decode_payload(msgpack.packb([3]))["tags"]
|
||||
)
|
||||
for bad in ([None], [3, None], [3, "x", None, None]):
|
||||
with self.assertRaises(ValueError, msg=str(bad)):
|
||||
document.decode_payload(msgpack.packb(bad))
|
||||
|
||||
def test_a_write_missing_a_non_nullable_field_is_refused_naming_the_slot(self) -> None:
|
||||
document = define_database_entry_type(
|
||||
"tests.required",
|
||||
[database_entry_field("count", 0, codec=t.int32), database_entry_field("label", 1, codec=t.nullable(t.string))],
|
||||
)
|
||||
self.assertEqual(document.encode_payload({"count": 1}), msgpack.packb([1, None]))
|
||||
with self.assertRaises(ValueError) as caught:
|
||||
document.encode_payload({"label": "x"})
|
||||
self.assertEqual(str(caught.exception), "tests.required slot 0 (count): expected an int32, found nil")
|
||||
with self.assertRaises(ValueError) as nil_record:
|
||||
define_record_codec("R", [("a", 0)]).encode(None)
|
||||
self.assertIn("found nil", str(nil_record.exception))
|
||||
|
||||
def test_an_untyped_definition_keeps_its_catalog_and_bytes_and_reads_a_present_nil_as_none(self) -> None:
|
||||
document = define_database_entry_type("tests.untyped", [("name", 0), ("owner_id", 1, "none"), ("tags", 3, list)])
|
||||
self.assertEqual([(m.slot, m.member_name, m.type_name) for m in document.catalog_entry().members],
|
||||
[(0, "Name", "System.Object"), (1, "OwnerId", "System.Object"), (3, "Tags", "System.Object")])
|
||||
# Values computed with the code at base 4ec4bfb7.
|
||||
self.assertEqual(document.encode_payload({"name": "n", "owner_id": "o", "tags": ["a"]}).hex(), "94a16ea16fc091a161")
|
||||
self.assertEqual(document.decode_payload(bytes.fromhex("94a16ea16fc091a161")), {"name": "n", "owner_id": "o", "tags": ["a"]})
|
||||
self.assertEqual(document.decode_payload(bytes.fromhex("94a16ec0c0c0")), {"name": "n", "owner_id": None, "tags": None})
|
||||
self.assertEqual(document.decode_payload(bytes.fromhex("91a16e")), {"name": "n", "owner_id": "none", "tags": []})
|
||||
self.assertEqual(_pack_tree(["x", 1.5, {"k": [b"y"]}]), msgpack.packb(["x", 1.5, {"k": [b"y"]}], use_bin_type=True))
|
||||
|
||||
def test_the_interop_note_catalog_is_the_one_the_hand_written_definition_had(self) -> None:
|
||||
entry = interop_note_document.catalog_entry()
|
||||
names = [(m.slot, m.member_name, m.type_name, m.is_name) for m in entry.members]
|
||||
self.assertEqual(
|
||||
names,
|
||||
[(0, "SchemaVersion", "System.String", False), (1, "DocumentId", "System.String", True),
|
||||
(2, "AuthorRuntimeId", "System.String", False), (3, "Title", "System.String", False),
|
||||
(4, "Body", "System.String", False), (5, "Tags", "System.String[]", False)],
|
||||
)
|
||||
# Captured from the hand-written definition at base 4ec4bfb7.
|
||||
self.assertEqual(entry.canonical_schema_json, _BASE_INTEROP_CATALOG)
|
||||
self.assertEqual(
|
||||
(entry.schema_id, entry.schema_name, entry.schema_version, entry.content_hash, entry.compatible_schema_ids),
|
||||
("cultcache.interop-note", "cultcache.interop-note", "cultcache.interop_note.v1", "cultcache.interop-note",
|
||||
("cultcache.interop-note",)),
|
||||
)
|
||||
note = {"schemaVersion": "cultcache.interop_note.v1", "documentId": "note:py", "authorRuntimeId": "py",
|
||||
"title": "t", "body": "b", "tags": ["py", "interop"]}
|
||||
self.assertEqual(interop_note_document.encode_payload(note).hex(), _BASE_INTEROP_PAYLOAD)
|
||||
self.assertEqual(interop_note_document.decode_payload(bytes.fromhex(_BASE_INTEROP_PAYLOAD)), note)
|
||||
self.assertEqual(interop_note_document.decode_payload(msgpack.packb(["v", "d", "a", "t", "b"]))["tags"], [])
|
||||
|
||||
|
||||
_BASE_INTEROP_CATALOG = (
|
||||
'{"schemaName":"cultcache.interop-note","schemaVersion":"cultcache.interop_note.v1","members":['
|
||||
'{"slot":0,"name":"SchemaVersion","type":"System.String","isReference":false,"many":false,"targetSchemaName":null,"indexAlias":null,"isName":false},'
|
||||
'{"slot":1,"name":"DocumentId","type":"System.String","isReference":false,"many":false,"targetSchemaName":null,"indexAlias":null,"isName":true},'
|
||||
'{"slot":2,"name":"AuthorRuntimeId","type":"System.String","isReference":false,"many":false,"targetSchemaName":null,"indexAlias":null,"isName":false},'
|
||||
'{"slot":3,"name":"Title","type":"System.String","isReference":false,"many":false,"targetSchemaName":null,"indexAlias":null,"isName":false},'
|
||||
'{"slot":4,"name":"Body","type":"System.String","isReference":false,"many":false,"targetSchemaName":null,"indexAlias":null,"isName":false},'
|
||||
'{"slot":5,"name":"Tags","type":"System.String[]","isReference":false,"many":false,"targetSchemaName":null,"indexAlias":null,"isName":false}]}'
|
||||
)
|
||||
_BASE_INTEROP_PAYLOAD = "96" + "".join(
|
||||
msgpack.packb(v, use_bin_type=True).hex()
|
||||
for v in ("cultcache.interop_note.v1", "note:py", "py", "t", "b", ["py", "interop"])
|
||||
)
|
||||
|
||||
|
||||
class LeafRuleTests(unittest.TestCase):
|
||||
def _refusal(self, run) -> str:
|
||||
with self.assertRaises(ValueError) as caught:
|
||||
run()
|
||||
return str(caught.exception)
|
||||
|
||||
def test_refusals_name_the_slot_and_the_kind_found_and_never_the_value(self) -> None:
|
||||
cases = [
|
||||
(t.int32, CANARY, "expected an int32, found string"),
|
||||
(t.int64, 1.5, "expected an int64, found float"),
|
||||
(t.string, b"bin", "expected a string, found bytes"),
|
||||
(t.boolean, 1, "expected a boolean, found integer"),
|
||||
(t.bytes, 5, "expected bytes, found integer"),
|
||||
(t.float32, CANARY, "expected a float32, found string"),
|
||||
(t.float64, [CANARY], "expected a float64, found array"),
|
||||
(t.list(t.string), {CANARY: 1}, "expected an array, found map"),
|
||||
(t.string, None, "expected a string, found nil"),
|
||||
(t.int32, True, "expected an int32, found boolean"),
|
||||
(t.int32, 2**31, "expected an int32, found an integer out of range"),
|
||||
]
|
||||
for leaf, value, expected in cases:
|
||||
document = _slot(leaf)
|
||||
with self.subTest(expected=expected, direction="write"):
|
||||
self.assertEqual(self._refusal(lambda: document.encode_payload({"v": value})), f"tests.leaf slot 0 (v): {expected}")
|
||||
with self.subTest(expected=expected, direction="read"):
|
||||
payload = msgpack.packb([value], use_bin_type=True)
|
||||
message = self._refusal(lambda: document.decode_payload(payload))
|
||||
self.assertTrue(message.startswith("tests.leaf slot 0 (v): expected "), message)
|
||||
self.assertNotIn(CANARY, message)
|
||||
|
||||
def test_a_list_element_refusal_names_the_element_and_a_union_arm_refusal_names_the_arm(self) -> None:
|
||||
self.assertEqual(
|
||||
self._refusal(lambda: t.list(t.int32).decode([1, "x"])), "element 1: expected an int32, found string"
|
||||
)
|
||||
self.assertEqual(
|
||||
self._refusal(lambda: t.array(t.list(t.int32)).encode([[1], [2, None]])),
|
||||
"element 1: element 1: expected an int32, found nil",
|
||||
)
|
||||
arm = define_union("U", {3: ("A", define_record_codec("A", [database_entry_field("n", 0, codec=t.int32)]))})
|
||||
self.assertEqual(
|
||||
self._refusal(lambda: arm.decode([3, [CANARY]])), "Union 'U' arm 3: A slot 0 (n): expected an int32, found string"
|
||||
)
|
||||
self.assertEqual(
|
||||
self._refusal(lambda: arm.encode(UnionArm("A", {"n": None}))), "Union 'U' arm 3: A slot 0 (n): expected an int32, found nil"
|
||||
)
|
||||
|
||||
def test_string_boolean_and_bytes_domains(self) -> None:
|
||||
self.assertEqual(t.string.encode("é"), "é")
|
||||
self.assertIs(t.boolean.decode(True), True)
|
||||
self.assertEqual(t.bytes.encode(bytearray(b"ab")), b"ab")
|
||||
self.assertEqual(t.bytes.encode(memoryview(b"ab")), b"ab")
|
||||
self.assertIs(type(t.bytes.encode(bytearray(b"ab"))), bytes)
|
||||
self.assertEqual(t.bytes.decode("é"), "é".encode("utf-8"))
|
||||
self.assertEqual(t.bytes.decode(b"\x00"), b"\x00")
|
||||
self.assertEqual(t.bytes.decode(""), b"")
|
||||
for refuse in (lambda: t.bytes.decode(5), lambda: t.bytes.encode("str")):
|
||||
self.assertIn("expected bytes", self._refusal(refuse))
|
||||
|
||||
def test_integer_leaves_hold_their_ranges_and_refuse_floats_and_booleans(self) -> None:
|
||||
self.assertEqual((t.int32.encode(-(2**31)), t.int32.encode(2**31 - 1)), (-(2**31), 2**31 - 1))
|
||||
self.assertEqual((t.int64.decode(-(2**63)), t.int64.decode(2**63 - 1)), (-(2**63), 2**63 - 1))
|
||||
for leaf, value in ((t.int32, -(2**31) - 1), (t.int32, 2**31), (t.int64, -(2**63) - 1), (t.int64, 2**63), (t.int64, 2**64 - 1)):
|
||||
self.assertIn("out of range", self._refusal(lambda: leaf.decode(value)))
|
||||
self.assertIn("out of range", self._refusal(lambda: leaf.encode(value)))
|
||||
for bad in (1.0, True, False, "1", None):
|
||||
self.assertIn("expected an int32", self._refusal(lambda: t.int32.decode(bad)))
|
||||
|
||||
def test_float_leaves_take_ints_and_floats_round_once_and_refuse_booleans(self) -> None:
|
||||
self.assertEqual(t.float32.decode(0.1), struct.unpack(">f", struct.pack(">f", 0.1))[0])
|
||||
self.assertEqual(t.float32.decode(2**24 + 1), float(2**24))
|
||||
self.assertEqual(t.float32.decode(1e300), math.inf)
|
||||
self.assertEqual(t.float32.decode(-1e300), -math.inf)
|
||||
self.assertEqual(t.float64.decode(2**53 + 1), float(2**53))
|
||||
# past 2**53 a double then a float32 rounding can differ from one rounding: 2**62 + 2**38 + 1 is above the tie.
|
||||
value = 2**62 + 2**38 + 1
|
||||
self.assertEqual(t.float32.decode(value), float(2**62 + 2**39))
|
||||
self.assertEqual(t.float32.decode(-value), -float(2**62 + 2**39))
|
||||
tie_even, tie_odd = 2**62 + 2**38, 2**62 + 2**39 + 2**38
|
||||
self.assertEqual(t.float32.decode(tie_even), float(2**62))
|
||||
self.assertEqual(t.float32.decode(tie_odd), float(2**62 + 2**40))
|
||||
self.assertEqual(t.float32.encode(2**64 - 1), t.Float32(float(2**64)))
|
||||
self.assertEqual(t.float32.encode(1.5), t.Float32(1.5))
|
||||
self.assertEqual(t.float64.encode(3), 3.0)
|
||||
self.assertIs(type(t.float64.encode(3)), float)
|
||||
for leaf in (t.float32, t.float64):
|
||||
for bad in (True, "1", None, [1.0]):
|
||||
self.assertIn("expected a float", self._refusal(lambda: leaf.decode(bad)))
|
||||
self.assertIn("expected a float", self._refusal(lambda: leaf.encode(bad)))
|
||||
self.assertIn("out of range", self._refusal(lambda: leaf.encode(2**64)))
|
||||
self.assertIn("out of range", self._refusal(lambda: leaf.encode(-(2**63) - 1)))
|
||||
|
||||
def test_list_and_array_write_lists_and_tuples_and_read_only_arrays(self) -> None:
|
||||
self.assertEqual(t.list(t.int32).encode((1, 2)), [1, 2])
|
||||
self.assertEqual(t.array(t.string).decode(["a"]), ["a"])
|
||||
self.assertEqual(t.list(t.int32).encode([]), [])
|
||||
self.assertIn("expected an array", self._refusal(lambda: t.list(t.int32).encode("12")))
|
||||
self.assertIn("expected an array", self._refusal(lambda: t.list(t.int32).decode((1,))))
|
||||
self.assertIn("expected an array", self._refusal(lambda: t.array(t.int32).decode(None)))
|
||||
|
||||
def test_nullable_passes_none_and_otherwise_defers(self) -> None:
|
||||
maybe = t.nullable(t.int32)
|
||||
self.assertIsNone(maybe.encode(None))
|
||||
self.assertIsNone(maybe.decode(None))
|
||||
self.assertEqual((maybe.encode(0), maybe.decode(0)), (0, 0))
|
||||
self.assertIn("expected an int32", self._refusal(lambda: maybe.decode("x")))
|
||||
self.assertEqual((t.nullable(t.boolean).encode(False), t.nullable(t.string).decode("")), (False, ""))
|
||||
|
||||
def test_a_field_codec_must_be_a_slot_codec(self) -> None:
|
||||
self.assertIn("must be a SlotCodec", self._refusal(lambda: database_entry_field("a", 0, codec=lambda: t.int32))) # type: ignore[arg-type]
|
||||
|
||||
|
||||
class LeafBoundaryTests(unittest.TestCase):
|
||||
def _refusal(self, run) -> str:
|
||||
with self.assertRaises(ValueError) as caught:
|
||||
run()
|
||||
return str(caught.exception)
|
||||
|
||||
def test_float32_writes_a_subnormal_as_a_float_32_with_its_exact_bits(self) -> None:
|
||||
document = _slot(t.float32)
|
||||
for value, expected in (
|
||||
(1e-40, "91ca000116c2"),
|
||||
(-1e-40, "91ca800116c2"),
|
||||
(1.401298464324817e-45, "91ca00000001"),
|
||||
(7e-46, "91ca00000000"),
|
||||
(1.1754942106924411e-38, "91ca007fffff"),
|
||||
):
|
||||
self.assertEqual(document.encode_payload({"v": value}).hex(), expected, repr(value))
|
||||
|
||||
def test_float_leaves_write_an_int_across_the_whole_64_bit_range_and_refuse_beyond_it(self) -> None:
|
||||
for leaf in (t.float32, t.float64):
|
||||
for ok in (3, 0, -(2**63), 2**64 - 1):
|
||||
leaf.encode(ok)
|
||||
for bad in (-(2**63) - 1, 2**64):
|
||||
what = "a float32" if leaf is t.float32 else "a float64"
|
||||
expected = f"expected {what}, found an integer out of range"
|
||||
self.assertEqual(self._refusal(lambda: leaf.encode(bad)), expected)
|
||||
self.assertEqual(self._refusal(lambda: leaf.decode(bad)), expected)
|
||||
self.assertEqual(t.float32.encode(3), t.Float32(3.0))
|
||||
self.assertEqual(t.float32.encode(-(2**63)), t.Float32(-float(2**63)))
|
||||
self.assertEqual(t.float64.encode(-(2**63)), -float(2**63))
|
||||
self.assertEqual(t.float64.encode(2**64 - 1), float(2**64))
|
||||
|
||||
def test_an_integer_past_2_to_53_rounds_to_float32_once_not_through_a_double(self) -> None:
|
||||
# 2**53 + 2**29 + 1 is above the float32 tie, but rounding to a double first lands on the tie and rounds down.
|
||||
value = 2**53 + 2**29 + 1
|
||||
self.assertEqual(t.float32.decode(value), float(2**53 + 2**30))
|
||||
self.assertEqual(t.float32.decode(-value), -float(2**53 + 2**30))
|
||||
self.assertEqual(t.float32.encode(value), t.Float32(float(2**53 + 2**30)))
|
||||
self.assertEqual(t.float32.decode(2**53), float(2**53))
|
||||
self.assertEqual(t.float32.decode(-(2**53)), -float(2**53))
|
||||
|
||||
def test_the_kind_a_refusal_reports(self) -> None:
|
||||
for value, kind in ((msgpack.ExtType(1, b""), "ext"), (object(), "other"), (t.Float32(1.0), "float"),
|
||||
(bytearray(1), "bytes"), ((1,), "array"), ({}, "map"), (True, "boolean")):
|
||||
self.assertEqual(self._refusal(lambda: t.int32.encode(value)), f"expected an int32, found {kind}")
|
||||
|
||||
def test_definition_time_refusals_say_what_is_wrong(self) -> None:
|
||||
self.assertEqual(
|
||||
self._refusal(lambda: database_entry_field("a", 0, codec=object)), # type: ignore[arg-type]
|
||||
"DatabaseEntry field codec must be a SlotCodec: a leaf from cultcache_py.leaves, or leaves.lazy",
|
||||
)
|
||||
self.assertEqual(
|
||||
self._refusal(lambda: define_union("Loose", {0: ("A", object)})), # type: ignore[dict-item]
|
||||
"Union 'Loose' arm codecs must be SlotCodecs or None",
|
||||
)
|
||||
self.assertEqual(
|
||||
self._refusal(lambda: define_record_codec("R", [("a", 0)]).encode(None)),
|
||||
"DatabaseEntry document type 'R': expected a record, found nil",
|
||||
)
|
||||
|
||||
def test_value_objects_are_immutable_and_unnamed_by_default(self) -> None:
|
||||
import dataclasses
|
||||
|
||||
plain = t.SlotCodec(lambda v: v, lambda v: v)
|
||||
self.assertIsNone(plain.type_name)
|
||||
self.assertIs(plain.value_type, False)
|
||||
self.assertIs(t.nullable(plain).value_type, False)
|
||||
self.assertIs(t.list(plain).value_type, False)
|
||||
self.assertIsNone(t.nullable(plain).type_name)
|
||||
for frozen, field_name in ((plain, "encode"), (t.Float32(1.0), "value"), (t.nullable(t.int32), "encode")):
|
||||
with self.assertRaises(dataclasses.FrozenInstanceError):
|
||||
setattr(frozen, field_name, None)
|
||||
|
||||
def test_a_definition_made_without_members_has_an_empty_catalog(self) -> None:
|
||||
from cultcache_py.documents import DocumentDefinition
|
||||
|
||||
self.assertEqual(DocumentDefinition(type="tests.bare").catalog_entry().members, ())
|
||||
|
||||
|
||||
class BytesAtTheDepthSeamTests(unittest.TestCase):
|
||||
def test_bytes_bytearray_and_memoryview_leaves_at_depth_256_are_accepted_on_write_and_read(self) -> None:
|
||||
blob = define_record_codec("Blob", [database_entry_field("data", 0, codec=t.list(t.bytes))])
|
||||
wrap = define_record_codec("Wrap", [database_entry_field("inner", 0, codec=t.nullable(t.lazy(lambda: deep_union)))])
|
||||
deep_union = define_union("Deep", {0: ("Wrap", wrap), 1: ("Blob", blob)})
|
||||
document = define_database_entry_type("tests.deep_bytes", [database_entry_field("root", 0, codec=deep_union)])
|
||||
for data in (b"\x01\x02", bytearray(b"\x01\x02"), memoryview(b"\x01\x02")):
|
||||
value = UnionArm("Blob", {"data": [data]})
|
||||
for _ in range(126):
|
||||
value = UnionArm("Wrap", {"inner": value})
|
||||
payload = document.encode_payload({"root": value})
|
||||
decoded = document.decode_payload(payload)
|
||||
self.assertEqual(document.encode_payload(decoded), payload)
|
||||
leaf = decoded["root"]
|
||||
while leaf.name == "Wrap":
|
||||
leaf = leaf.value["inner"]
|
||||
self.assertEqual(leaf.value["data"], [b"\x01\x02"])
|
||||
|
||||
|
||||
class PackTreeTests(unittest.TestCase):
|
||||
def test_a_float32_anywhere_in_the_tree_is_written_as_float_32_and_everything_else_as_packb_does(self) -> None:
|
||||
tree = [t.Float32(1.5), {"k": t.Float32(0.1), "b": b"\x01", "s": "x", "n": None}, (t.Float32(2.0), [True, 7, 2.5])]
|
||||
packer = msgpack.Packer(use_bin_type=True)
|
||||
single = msgpack.Packer(use_bin_type=True, use_single_float=True)
|
||||
expected = (
|
||||
packer.pack_array_header(3) + single.pack(1.5)
|
||||
+ packer.pack_map_header(4) + packer.pack("k") + single.pack(0.1) + packer.pack("b") + packer.pack(b"\x01")
|
||||
+ packer.pack("s") + packer.pack("x") + packer.pack("n") + packer.pack(None)
|
||||
+ packer.pack_array_header(2) + single.pack(2.0) + packer.pack([True, 7, 2.5])
|
||||
)
|
||||
self.assertEqual(_pack_tree(tree), expected)
|
||||
self.assertEqual(_pack_tree(t.Float32(1.5)), bytes.fromhex("ca3fc00000"))
|
||||
|
||||
def test_a_float32_overflow_is_infinity_and_a_value_nothing_can_pack_is_still_a_type_error(self) -> None:
|
||||
self.assertEqual(_pack_tree([t.float32.encode(1e300)]), bytes.fromhex("91ca7f800000"))
|
||||
self.assertEqual(_pack_tree([t.float32.encode(-1e300)]), bytes.fromhex("91caff800000"))
|
||||
with self.assertRaises(TypeError):
|
||||
_pack_tree([t.Float32(1.0), object()])
|
||||
with self.assertRaises(TypeError):
|
||||
_pack_tree([object()])
|
||||
|
||||
def test_a_tree_with_no_float32_is_packb_unchanged(self) -> None:
|
||||
tree = {"a": [1, 2.5, "x", b"y", None, True, {"b": -1}], "c": (3, 4)}
|
||||
self.assertEqual(_pack_tree(tree), msgpack.packb(tree, use_bin_type=True))
|
||||
|
||||
def test_the_union_golden_scalar_direction_is_refused_as_the_reference_refuses_it(self) -> None:
|
||||
from test_union_parity import node # the fixture with the C# golden's leaves
|
||||
|
||||
with self.assertRaises(ValueError) as caught:
|
||||
node.decode([1, ["hammer", 12]])
|
||||
self.assertEqual(str(caught.exception), "Union 'Node' arm 1: Text slot 1 (content): expected a string, found integer")
|
||||
self.assertNotIn("hammer", str(caught.exception))
|
||||
self.assertEqual(node.decode([1, ["hammer", "x"]]), UnionArm("Text", {"id": "hammer", "content": "x"}))
|
||||
|
||||
|
||||
PY_STORES = VECTORS / "py-store"
|
||||
# slot -> the C# type name a wrong catalog gives it; the reference refuses each ("slot N changed type").
|
||||
WRONG_NAMES = {3: "System.Int64", 5: "System.Double", 7: "System.Int32", 14: "System.Double[]"}
|
||||
|
||||
|
||||
def _python_authored_leaf_record() -> dict:
|
||||
return {
|
||||
"id": "py", "flag": False, "blob": bytearray([1, 255]), "i": -(2**31), "l": 2**63 - 1, "f": 0.1, "d": 1e-300,
|
||||
"maybe_i": None, "tags": [], "names": ("\u00e9", "z"), "any": {"k": [1, True, None, 2.5, "s"], "n": -3},
|
||||
"nested": None, "items": [{"n": "one", "w": 2**53 + 2**29 + 1}, {"n": "two", "w": 1e-40}],
|
||||
"shape": UnionArm("LeafCircle", {"r": 0.1}), "floats": [0.1, 3, -0.0, 1e39], "maybe_f": None,
|
||||
}
|
||||
|
||||
|
||||
def _write_store(path: Path, document, value: dict) -> None:
|
||||
path.unlink(missing_ok=True)
|
||||
cache = CultCache.builder().register_document_type(document).add_generic_store(SingleFileMessagePackBackingStore(path)).build()
|
||||
cache.pull_all_backing_stores()
|
||||
cache.put(document, value["id"], value)
|
||||
|
||||
|
||||
def _wrong_catalog(document, slot: int):
|
||||
import dataclasses
|
||||
|
||||
good = tuple(document.catalog_entry().members)
|
||||
return dataclasses.replace(
|
||||
document, members=lambda: tuple(dataclasses.replace(m, type_name=WRONG_NAMES[slot]) if m.slot == slot else m for m in good)
|
||||
)
|
||||
|
||||
|
||||
class PythonWrittenStoreVectorTests(unittest.TestCase):
|
||||
"""The stores under tests/vectors/numeric-leaves/py-store are written only by this class, with CULTCACHE_WRITE_VECTORS=1;
|
||||
GameCult.Caching.Tests (PythonWrittenStoreTests) opens them with the C# reference and asserts every field."""
|
||||
|
||||
def test_the_committed_stores_are_what_the_definition_writes_and_read_back(self) -> None:
|
||||
import os
|
||||
import tempfile
|
||||
|
||||
document = _leaf_record_document()
|
||||
value = _python_authored_leaf_record()
|
||||
if os.environ.get("CULTCACHE_WRITE_VECTORS"):
|
||||
PY_STORES.mkdir(exist_ok=True)
|
||||
_write_store(PY_STORES / "leaf-record.cc", document, value)
|
||||
for slot in WRONG_NAMES:
|
||||
_write_store(PY_STORES / f"wrong-slot-{slot}.cc", _wrong_catalog(document, slot), value)
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
fresh = Path(tmp) / "fresh.cc"
|
||||
_write_store(fresh, document, value)
|
||||
[committed] = SingleFileMessagePackBackingStore(PY_STORES / "leaf-record.cc").pull_all()
|
||||
[again] = SingleFileMessagePackBackingStore(fresh).pull_all()
|
||||
self.assertEqual(committed.payload, again.payload)
|
||||
self.assertEqual(committed.catalog_entry.members, again.catalog_entry.members)
|
||||
self.assertEqual(committed.payload, document.encode_payload(value))
|
||||
for slot, name in WRONG_NAMES.items():
|
||||
[wrong] = SingleFileMessagePackBackingStore(PY_STORES / f"wrong-slot-{slot}.cc").pull_all()
|
||||
self.assertEqual(wrong.catalog_entry.members[slot].type_name, name)
|
||||
self.assertEqual(wrong.payload, committed.payload)
|
||||
|
||||
|
||||
class StoreRoundTripTests(unittest.TestCase):
|
||||
def test_a_float32_slot_survives_a_single_file_store(self) -> None:
|
||||
import tempfile
|
||||
|
||||
document = define_database_entry_type(
|
||||
"tests.store", [database_entry_field("id", 0, codec=t.string), database_entry_field("f", 1, codec=t.float32)], name="id"
|
||||
)
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = Path(tmp) / "store.cc"
|
||||
cache = CultCache.builder().register_document_type(document).add_generic_store(SingleFileMessagePackBackingStore(path)).build()
|
||||
cache.pull_all_backing_stores()
|
||||
cache.put(document, "a", {"id": "a", "f": 0.1})
|
||||
[envelope] = SingleFileMessagePackBackingStore(path).pull_all()
|
||||
self.assertEqual(envelope.payload, bytes.fromhex("92a161ca3dcccccd"))
|
||||
self.assertEqual(envelope.catalog_entry.members[1].type_name, "System.Single")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
717
packages/cultcache-py/tests/test_union_parity.py
Normal file
717
packages/cultcache-py/tests/test_union_parity.py
Normal file
|
|
@ -0,0 +1,717 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import collections
|
||||
import dataclasses
|
||||
import shutil
|
||||
import tempfile
|
||||
import traceback
|
||||
import types
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
import msgpack
|
||||
|
||||
from cultcache_py import (
|
||||
MAX_PAYLOAD_DEPTH,
|
||||
MAX_SLOT_KEY,
|
||||
CultCache,
|
||||
CultCachePayloadDepthError,
|
||||
DatabaseEntryField,
|
||||
SlotCodec,
|
||||
SingleFileMessagePackBackingStore,
|
||||
UnionArm,
|
||||
database_entry_field,
|
||||
define_database_entry_type,
|
||||
define_document_type,
|
||||
define_record_codec,
|
||||
define_union,
|
||||
leaves as t,
|
||||
)
|
||||
|
||||
VECTORS = Path(__file__).resolve().parents[3] / "tests" / "vectors" / "union-parity"
|
||||
|
||||
_GOLDEN = "GameCult.Caching.Tests.UnionParityVectorTests+"
|
||||
_node = t.nullable(t.lazy(lambda: node))
|
||||
composition = define_record_codec(
|
||||
"Composition",
|
||||
[database_entry_field("name", 0, codec=t.string), database_entry_field("body", 1, codec=_node)],
|
||||
type_name=_GOLDEN + "Composition",
|
||||
)
|
||||
box = define_record_codec(
|
||||
"Box",
|
||||
[
|
||||
database_entry_field("id", 0, codec=t.string),
|
||||
database_entry_field("children", 1, codec=t.list(t.lazy(lambda: node))),
|
||||
],
|
||||
type_name=_GOLDEN + "Box",
|
||||
)
|
||||
text = define_record_codec(
|
||||
"Text",
|
||||
[database_entry_field("id", 0, codec=t.string), database_entry_field("content", 1, codec=t.string)],
|
||||
type_name=_GOLDEN + "Text",
|
||||
)
|
||||
use = define_record_codec(
|
||||
"Use",
|
||||
[
|
||||
database_entry_field("id", 0, codec=t.string),
|
||||
database_entry_field("composition", 1, codec=composition),
|
||||
database_entry_field("slots", 2, codec=t.list(t.nullable(t.lazy(lambda: node)))),
|
||||
],
|
||||
type_name=_GOLDEN + "Use",
|
||||
)
|
||||
image = define_record_codec(
|
||||
"Image",
|
||||
[
|
||||
database_entry_field("id", 0, codec=t.string),
|
||||
database_entry_field("uri", 1, codec=t.string),
|
||||
database_entry_field("alt", 3, codec=t.string),
|
||||
],
|
||||
type_name=_GOLDEN + "Image",
|
||||
)
|
||||
wrap = define_record_codec("Wrap", [database_entry_field("inner", 0, codec=_node)], type_name=_GOLDEN + "Wrap")
|
||||
node = define_union(
|
||||
"Node",
|
||||
{0: ("Box", box), 1: ("Text", text), 2: ("Use", use), 5: ("Image", image), 6: ("Wrap", wrap)},
|
||||
type_name=_GOLDEN + "Node",
|
||||
)
|
||||
outcome = define_union(
|
||||
"Outcome",
|
||||
{
|
||||
0: ("Pending", define_record_codec("Pending", [database_entry_field("message", 0, codec=t.string)])),
|
||||
1: ("Completed", define_record_codec("Completed", [database_entry_field("source_version", 0, codec=t.int32)])),
|
||||
2: ("Denied", None),
|
||||
-2147483648: ("Floor", None),
|
||||
2147483647: ("Ceiling", None),
|
||||
},
|
||||
type_name=_GOLDEN + "Outcome",
|
||||
)
|
||||
tool = define_record_codec(
|
||||
"Tool",
|
||||
[database_entry_field("name", 0, codec=t.string), database_entry_field("uses", 1, codec=t.int32)],
|
||||
type_name=_GOLDEN + "Tool",
|
||||
)
|
||||
part = define_record_codec(
|
||||
"Part",
|
||||
[database_entry_field("name", 0, codec=t.string), database_entry_field("count", 1, codec=t.int32)],
|
||||
type_name=_GOLDEN + "Part",
|
||||
)
|
||||
gem = define_record_codec("Gem", [database_entry_field("name", 0, codec=t.string)], type_name=_GOLDEN + "Gem")
|
||||
item = define_union("Item", {0: ("Gem", gem), 1: ("Tool", tool), 2: ("Part", part)}, type_name=_GOLDEN + "Item")
|
||||
crafted = define_union("CraftedItem", {0: ("Tool", tool), 1: ("Part", part)}, type_name=_GOLDEN + "CraftedItem")
|
||||
|
||||
surface_document = define_database_entry_type(
|
||||
"tests.union_surface",
|
||||
[
|
||||
database_entry_field("id", 0, codec=t.string),
|
||||
database_entry_field("version", 1, codec=t.int32),
|
||||
database_entry_field("root", 2, codec=_node),
|
||||
database_entry_field("outcomes", 3, codec=t.list(outcome)),
|
||||
database_entry_field("part", 4, codec=t.nullable(item)),
|
||||
database_entry_field("crafted", 5, codec=t.nullable(crafted)),
|
||||
database_entry_field("missing", 6, codec=_node),
|
||||
],
|
||||
name="id",
|
||||
)
|
||||
|
||||
|
||||
def _surface_value() -> dict:
|
||||
return {
|
||||
"id": "surface",
|
||||
"version": 3,
|
||||
"root": UnionArm(
|
||||
"Box",
|
||||
{
|
||||
"id": "root",
|
||||
"children": [
|
||||
UnionArm("Text", {"id": "t1", "content": "hello"}),
|
||||
UnionArm(
|
||||
"Use",
|
||||
{
|
||||
"id": "u1",
|
||||
"composition": {
|
||||
"name": "comp",
|
||||
"body": UnionArm(
|
||||
"Box",
|
||||
{
|
||||
"id": "inner",
|
||||
"children": [
|
||||
UnionArm("Text", {"id": "deep", "content": "x"}),
|
||||
UnionArm("Image", {"id": "img", "uri": "uri://a", "alt": "alt"}),
|
||||
],
|
||||
},
|
||||
),
|
||||
},
|
||||
"slots": [
|
||||
UnionArm("Text", {"id": "s1", "content": "slot"}),
|
||||
None,
|
||||
UnionArm("Box", {"id": "b2", "children": []}),
|
||||
],
|
||||
},
|
||||
),
|
||||
UnionArm("Image", {"id": "i2", "uri": "uri://b", "alt": ""}),
|
||||
],
|
||||
},
|
||||
),
|
||||
"outcomes": [
|
||||
UnionArm("Pending", {"message": "wait"}),
|
||||
UnionArm("Completed", {"source_version": 7}),
|
||||
UnionArm("Denied"),
|
||||
],
|
||||
"part": UnionArm("Tool", {"name": "hammer", "uses": 12}),
|
||||
"crafted": UnionArm("Part", {"name": "gear", "count": 4}),
|
||||
"missing": None,
|
||||
}
|
||||
|
||||
|
||||
def _vector(name: str) -> bytes:
|
||||
return (VECTORS / name).read_bytes()
|
||||
|
||||
|
||||
class UnionSurfaceVectorTests(unittest.TestCase):
|
||||
def test_surface_payload_decodes_to_the_value_and_re_encodes_byte_identical(self) -> None:
|
||||
payload = _vector("union-surface.msgpack")
|
||||
decoded = surface_document.decode_payload(payload)
|
||||
self.assertEqual(decoded, _surface_value())
|
||||
self.assertEqual(surface_document.encode_payload(decoded), payload)
|
||||
|
||||
def test_the_csharp_written_store_reads_and_the_cache_rewrites_the_same_payload(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = Path(tmp) / "union-surface.cc"
|
||||
shutil.copyfile(VECTORS / "union-surface.cc", path)
|
||||
cache = (
|
||||
CultCache.builder()
|
||||
.register_document_type(surface_document)
|
||||
.add_generic_store(SingleFileMessagePackBackingStore(path))
|
||||
.build()
|
||||
)
|
||||
cache.pull_all_backing_stores()
|
||||
self.assertEqual(cache.get(surface_document, "surface"), _surface_value())
|
||||
fresh = Path(tmp) / "fresh.cc"
|
||||
writer = (
|
||||
CultCache.builder()
|
||||
.register_document_type(surface_document)
|
||||
.add_generic_store(SingleFileMessagePackBackingStore(fresh))
|
||||
.build()
|
||||
)
|
||||
writer.pull_all_backing_stores()
|
||||
writer.put(surface_document, "surface", _surface_value())
|
||||
[envelope] = SingleFileMessagePackBackingStore(fresh).pull_all()
|
||||
self.assertEqual(envelope.payload, _vector("union-surface.msgpack"))
|
||||
|
||||
def test_the_missing_slot_is_a_node_and_agrees_with_the_csharp_written_root(self) -> None:
|
||||
payload = _vector("union-surface.msgpack")
|
||||
slots = msgpack.unpackb(payload, raw=False)
|
||||
slots[6] = slots[2]
|
||||
decoded = surface_document.decode_payload(msgpack.packb(slots, use_bin_type=True))
|
||||
self.assertEqual(decoded["missing"], _surface_value()["root"])
|
||||
self.assertEqual(surface_document.encode_payload(decoded), msgpack.packb(slots, use_bin_type=True))
|
||||
with self.assertRaises(ValueError):
|
||||
surface_document.encode_payload({**_surface_value(), "missing": UnionArm("Part", {"name": "gear", "count": 4})})
|
||||
|
||||
def test_the_store_vector_payload_equals_the_surface_payload(self) -> None:
|
||||
[envelope] = SingleFileMessagePackBackingStore(VECTORS / "union-surface.cc").pull_all()
|
||||
self.assertEqual(envelope.payload, _vector("union-surface.msgpack"))
|
||||
|
||||
def test_every_outcome_in_the_manifest_is_held(self) -> None:
|
||||
outcomes = msgpack.unpackb(_vector("outcomes.msgpack"), raw=False)
|
||||
self.assertEqual(len(outcomes), 9)
|
||||
refused = read_only = 0
|
||||
for file, outcome_kind, union, key, detail in outcomes:
|
||||
payload = _vector(file)
|
||||
if outcome_kind == "refused":
|
||||
refused += 1
|
||||
with self.assertRaises(ValueError, msg=file) as caught:
|
||||
surface_document.decode_payload(payload)
|
||||
message = str(caught.exception)
|
||||
self.assertIn(union, message, file)
|
||||
if detail == "unknown-arm":
|
||||
self.assertIn(f"arm key {key} ", message, file)
|
||||
else:
|
||||
self.assertEqual(detail, "arity")
|
||||
self.assertIn("malformed", message, file)
|
||||
else:
|
||||
read_only += 1
|
||||
self.assertEqual(outcome_kind, "read-only", file)
|
||||
self.assertEqual(surface_document.decode_payload(payload), _surface_value(), file)
|
||||
self.assertEqual((refused, read_only), (5, 4))
|
||||
|
||||
|
||||
class UnionCodecRuleTests(unittest.TestCase):
|
||||
CANARY = "canary-7f3a91"
|
||||
|
||||
def test_a_union_refuses_nil_both_ways_unless_it_is_wrapped_in_nullable(self) -> None:
|
||||
for refuse in (lambda: node.encode(None), lambda: node.decode(None)):
|
||||
with self.assertRaises(ValueError) as caught:
|
||||
refuse()
|
||||
self.assertEqual(str(caught.exception), "Union 'Node': expected an arm, found nil")
|
||||
maybe = t.nullable(node)
|
||||
self.assertIsNone(maybe.encode(None))
|
||||
self.assertIsNone(maybe.decode(None))
|
||||
self.assertEqual(maybe.decode(maybe.encode(UnionArm("Text", {"id": "a", "content": "b"}))), UnionArm("Text", {"id": "a", "content": "b"}))
|
||||
with self.assertRaises(ValueError) as write:
|
||||
surface_document.encode_payload({**_surface_value(), "outcomes": [None]})
|
||||
self.assertEqual(
|
||||
str(write.exception),
|
||||
"tests.union_surface slot 3 (outcomes): element 0: Union 'Outcome': expected an arm, found nil",
|
||||
)
|
||||
|
||||
def test_unit_arm_is_written_with_empty_slots_and_reads_back(self) -> None:
|
||||
self.assertEqual(outcome.encode(UnionArm("Denied")), [2, []])
|
||||
self.assertEqual(outcome.decode([2, []]), UnionArm("Denied", None))
|
||||
|
||||
def test_unit_arm_refuses_a_value_to_carry(self) -> None:
|
||||
with self.assertRaises(ValueError) as caught:
|
||||
outcome.encode(UnionArm("Denied", {"message": self.CANARY}))
|
||||
self.assertEqual(str(caught.exception), "Union 'Outcome' arm 2 is a unit arm and carries no value")
|
||||
|
||||
def test_arm_keys_are_written_as_declared(self) -> None:
|
||||
self.assertEqual(node.encode(UnionArm("Image", {"id": "a", "uri": "b", "alt": "c"})), [5, ["a", "b", None, "c"]])
|
||||
self.assertEqual(node.encode(UnionArm("Text", {"id": "a", "content": "b"})), [1, ["a", "b"]])
|
||||
|
||||
def test_encode_refuses_an_arm_the_union_does_not_declare_without_echoing_it(self) -> None:
|
||||
with self.assertRaises(ValueError) as caught:
|
||||
crafted.encode(UnionArm("Gem", {"name": self.CANARY}))
|
||||
self.assertEqual(
|
||||
str(caught.exception), "Union 'CraftedItem' was given a value that is not one of its arms"
|
||||
)
|
||||
with self.assertRaises(ValueError):
|
||||
node.encode({"id": "a"})
|
||||
|
||||
def test_unknown_key_names_the_union_the_key_and_the_declared_keys_never_the_payload(self) -> None:
|
||||
with self.assertRaises(ValueError) as caught:
|
||||
node.decode([4, [self.CANARY]])
|
||||
message = str(caught.exception)
|
||||
self.assertEqual(message, "Union 'Node' does not declare arm key 4 (declared: 0, 1, 2, 5, 6)")
|
||||
|
||||
def test_a_malformed_union_value_is_refused_without_echoing_it(self) -> None:
|
||||
for raw in (
|
||||
[1],
|
||||
[1, ["a"], "extra"],
|
||||
[1, self.CANARY],
|
||||
self.CANARY,
|
||||
{"k": self.CANARY},
|
||||
[self.CANARY, []],
|
||||
[True, []],
|
||||
[1.0, []],
|
||||
):
|
||||
with self.subTest(raw=type(raw).__name__):
|
||||
with self.assertRaises(ValueError) as caught:
|
||||
node.decode(raw)
|
||||
message = str(caught.exception)
|
||||
self.assertTrue(message.startswith("Union 'Node' value is malformed: "), message)
|
||||
self.assertNotIn(self.CANARY, message)
|
||||
|
||||
def test_extra_trailing_arm_slots_are_read(self) -> None:
|
||||
self.assertEqual(
|
||||
node.decode([1, ["a", "b", "extra"]]),
|
||||
UnionArm("Text", {"id": "a", "content": "b"}),
|
||||
)
|
||||
|
||||
def test_a_list_slot_requires_an_array_and_keeps_nil_elements_of_a_nullable_item(self) -> None:
|
||||
slots = [UnionArm("Text", {"id": "a", "content": "b"}), None]
|
||||
inner = {"name": "c", "body": None}
|
||||
encoded = use.encode({"id": "u", "composition": inner, "slots": slots})
|
||||
self.assertEqual(encoded, ["u", ["c", None], [[1, ["a", "b"]], None]])
|
||||
self.assertEqual(use.decode(encoded)["slots"], slots)
|
||||
with self.assertRaises(ValueError) as caught:
|
||||
use.decode(["u", ["c", None], self.CANARY])
|
||||
self.assertEqual(str(caught.exception), "Use slot 2 (slots): expected an array, found string")
|
||||
with self.assertRaises(ValueError) as nil_element:
|
||||
box.decode(["b", [None]])
|
||||
self.assertEqual(
|
||||
str(nil_element.exception),
|
||||
"Box slot 1 (children): element 0: Union 'Node': expected an arm, found nil",
|
||||
)
|
||||
|
||||
def test_a_list_of_nested_records_keeps_a_nil_element_as_csharp_writes_it(self) -> None:
|
||||
row = define_record_codec(
|
||||
"Row", [("id", 0), database_entry_field("cells", 1, codec=t.list(t.nullable(text)))]
|
||||
)
|
||||
cells = [None, {"id": "c", "content": "x"}, None]
|
||||
encoded = row.encode({"id": "r", "cells": cells})
|
||||
self.assertEqual(encoded, ["r", [None, ["c", "x"], None]])
|
||||
self.assertEqual(row.decode(encoded), {"id": "r", "cells": cells})
|
||||
|
||||
def test_a_unit_arm_with_extra_slots_is_read_past(self) -> None:
|
||||
self.assertEqual(outcome.decode([2, ["extra"]]), UnionArm("Denied"))
|
||||
|
||||
def test_union_arms_are_immutable_hashable_values(self) -> None:
|
||||
arm = UnionArm("Denied")
|
||||
with self.assertRaises(dataclasses.FrozenInstanceError):
|
||||
arm.name = "Pending" # type: ignore[misc]
|
||||
self.assertEqual(len({UnionArm("Denied"), UnionArm("Denied"), UnionArm("Pending", "wait")}), 2)
|
||||
|
||||
def test_a_short_record_is_read_with_nil_for_the_slots_it_lacks_as_the_reference_reads_it(self) -> None:
|
||||
self.assertEqual(node.decode([1, ["only-id"]]), UnionArm("Text", {"id": "only-id", "content": None}))
|
||||
self.assertEqual(node.decode([0, ["sapphire"]]), UnionArm("Box", {"id": "sapphire", "children": None}))
|
||||
|
||||
def test_definition_rules(self) -> None:
|
||||
cases = [
|
||||
("Empty", {}, "Union 'Empty' requires at least one arm"),
|
||||
("Dup", {0: ("A", None), 1: ("A", None)}, "Union 'Dup' has duplicate arm names"),
|
||||
("Wide", {2**31: ("A", None)}, "Union 'Wide' arm keys must be integers within Int32"),
|
||||
("Narrow", {-(2**31) - 1: ("A", None)}, "Union 'Narrow' arm keys must be integers within Int32"),
|
||||
("Flag", {True: ("A", None), "x": ("B", None)}, "Union 'Flag' arm keys must be integers within Int32"),
|
||||
]
|
||||
for union_name, arms, expected in cases:
|
||||
with self.subTest(union=union_name):
|
||||
with self.assertRaises(ValueError) as caught:
|
||||
define_union(union_name, arms)
|
||||
self.assertEqual(str(caught.exception), expected)
|
||||
for union_name, key in (("TrueKey", True), ("FalseKey", False)):
|
||||
with self.assertRaises(ValueError) as caught:
|
||||
define_union(union_name, {key: ("A", None)})
|
||||
self.assertEqual(str(caught.exception), f"Union {union_name!r} arm keys must be integers within Int32")
|
||||
edge = define_union("Edge", {-(2**31): ("Low", None), -1: ("Negative", None), 2**31 - 1: ("High", None)})
|
||||
for arm_name, key in (("Low", -(2**31)), ("Negative", -1), ("High", 2**31 - 1)):
|
||||
self.assertEqual(edge.encode(UnionArm(arm_name)), [key, []])
|
||||
self.assertEqual(edge.decode([key, []]), UnionArm(arm_name))
|
||||
for loose in (lambda: node, node.encode, "node", object):
|
||||
with self.assertRaises(ValueError) as caught:
|
||||
database_entry_field("loose", 1, codec=loose) # type: ignore[arg-type]
|
||||
self.assertIn("must be a SlotCodec", str(caught.exception))
|
||||
with self.assertRaises(ValueError):
|
||||
define_union("Loose", {0: ("A", lambda: node)}) # type: ignore[dict-item]
|
||||
|
||||
|
||||
class RecordCodecTests(unittest.TestCase):
|
||||
def test_a_default_fills_a_slot_past_the_payloads_end_and_a_callable_default_is_called(self) -> None:
|
||||
record = define_record_codec(
|
||||
"Defaulted",
|
||||
[("id", 0), ("label", 1, "none"), ("tags", 2, list), ("plain", 3, 0)],
|
||||
)
|
||||
self.assertEqual(record.decode(["a"]), {"id": "a", "label": "none", "tags": [], "plain": 0})
|
||||
self.assertEqual(record.decode(["a", "x"]), {"id": "a", "label": "x", "tags": [], "plain": 0})
|
||||
self.assertEqual(record.decode(["a", None, None, None]), {"id": "a", "label": None, "tags": None, "plain": None})
|
||||
self.assertEqual(record.decode(["a", "x", ["t"], 5]), {"id": "a", "label": "x", "tags": ["t"], "plain": 5})
|
||||
|
||||
def test_a_document_type_names_its_members_and_marks_the_name_and_index_slots(self) -> None:
|
||||
document = define_database_entry_type(
|
||||
"tests.members",
|
||||
[("id", 0), ("source_version", 1), ("owner", 2)],
|
||||
name="id",
|
||||
indexes={"by_owner": "owner"},
|
||||
)
|
||||
members = {member.slot: member for member in document.catalog_entry().members}
|
||||
self.assertEqual(
|
||||
[members[slot].member_name for slot in (0, 1, 2)], ["Id", "SourceVersion", "Owner"]
|
||||
)
|
||||
self.assertEqual([members[slot].is_name for slot in (0, 1, 2)], [True, False, False])
|
||||
self.assertEqual([members[slot].index_alias for slot in (0, 1, 2)], [None, None, "by_owner"])
|
||||
|
||||
def test_a_document_without_a_string_name_marks_no_member_as_the_name(self) -> None:
|
||||
document = define_database_entry_type("tests.named", [("id", 0)], name=lambda value: value["id"])
|
||||
self.assertFalse(document.catalog_entry().members[0].is_name)
|
||||
|
||||
def test_a_record_that_is_not_an_array_is_refused_naming_the_type_only(self) -> None:
|
||||
for refuse in (lambda r: r.decode({"id": "canary-7f3a91"}), lambda r: r.decode("canary-7f3a91")):
|
||||
record = define_record_codec("Plain", [("id", 0)])
|
||||
with self.assertRaises(ValueError) as caught:
|
||||
refuse(record)
|
||||
self.assertEqual(str(caught.exception), "DatabaseEntry document type 'Plain' expected a MessagePack array")
|
||||
self.assertNotIn("canary-7f3a91", str(caught.exception))
|
||||
|
||||
def test_field_tuples_of_the_wrong_length_are_refused(self) -> None:
|
||||
for fields in ([("id",)], [("id", 0, 1, 2)]):
|
||||
with self.assertRaises(ValueError) as caught:
|
||||
define_record_codec("Bad", fields)
|
||||
self.assertEqual(
|
||||
str(caught.exception), "DatabaseEntry field tuples must be (name, key) or (name, key, default)"
|
||||
)
|
||||
self.assertEqual(define_record_codec("Pair", [("id", 0)]).decode(["a"]), {"id": "a"})
|
||||
self.assertEqual(define_record_codec("Triple", [("id", 1, "d")]).decode([None]), {"id": "d"})
|
||||
|
||||
def test_duplicate_and_empty_field_lists_are_refused_naming_the_type(self) -> None:
|
||||
with self.assertRaises(ValueError) as caught:
|
||||
define_record_codec("Twice", [("a", 0), ("b", 0)])
|
||||
self.assertEqual(str(caught.exception), "DatabaseEntry document type 'Twice' has duplicate field keys")
|
||||
with self.assertRaises(ValueError) as empty:
|
||||
define_record_codec("Nothing", [])
|
||||
self.assertEqual(str(empty.exception), "DatabaseEntry document types require at least one field")
|
||||
|
||||
def test_a_plain_field_helper_makes_an_untyped_slot(self) -> None:
|
||||
plain = define_record_codec("Plain", [database_entry_field("id", 0), database_entry_field("label", 1)])
|
||||
self.assertEqual(plain.decode(plain.encode({"id": "a", "label": "b"})), {"id": "a", "label": "b"})
|
||||
self.assertEqual(plain.decode(["a"]), {"id": "a", "label": None})
|
||||
field = database_entry_field("id", 0)
|
||||
self.assertIs(field.codec, t.any)
|
||||
|
||||
def test_a_directly_constructed_field_requires_a_default_and_is_untyped(self) -> None:
|
||||
with self.assertRaises(TypeError):
|
||||
DatabaseEntryField(name="id", key=0) # type: ignore[call-arg]
|
||||
field = DatabaseEntryField(name="id", key=0, default=dataclasses.MISSING)
|
||||
self.assertIs(field.codec, t.any)
|
||||
|
||||
def test_slot_codecs_and_fields_are_immutable(self) -> None:
|
||||
with self.assertRaises(dataclasses.FrozenInstanceError):
|
||||
node.encode = None # type: ignore[misc]
|
||||
with self.assertRaises(dataclasses.FrozenInstanceError):
|
||||
database_entry_field("id", 0).key = 1 # type: ignore[misc]
|
||||
|
||||
def test_slot_keys_are_integers_within_zero_and_the_cap_however_the_field_is_made(self) -> None:
|
||||
message = "DatabaseEntry field keys must be integers within 0..65535"
|
||||
self.assertEqual(MAX_SLOT_KEY, 65535)
|
||||
database_entry_field("zero", 0)
|
||||
top = define_record_codec("Top", [("last", MAX_SLOT_KEY)])
|
||||
self.assertEqual(len(top.encode({"last": "x"})), MAX_SLOT_KEY + 1)
|
||||
self.assertEqual(top.decode(top.encode({"last": "x"})), {"last": "x"})
|
||||
for make in (
|
||||
lambda key: database_entry_field("bad", key),
|
||||
lambda key: DatabaseEntryField(name="bad", key=key, default=dataclasses.MISSING),
|
||||
lambda key: define_record_codec("Bad", [("bad", key)]),
|
||||
lambda key: define_record_codec("Bad", [("bad", key, "d")]),
|
||||
):
|
||||
for key in (-1, MAX_SLOT_KEY + 1, 2**31, True, 1.0, "1"):
|
||||
with self.subTest(key=key):
|
||||
with self.assertRaises(ValueError) as caught:
|
||||
make(key)
|
||||
self.assertEqual(str(caught.exception), message)
|
||||
|
||||
def test_slot_order_follows_keys_not_declaration_order(self) -> None:
|
||||
record = define_record_codec("Ordered", [("b", 2), ("a", 0)])
|
||||
self.assertEqual(record.encode({"a": "x", "b": "y"}), ["x", None, "y"])
|
||||
|
||||
|
||||
CANARY = "CANARY-union-golden-4c2a"
|
||||
|
||||
|
||||
def _wrap_chain(wraps: int, leaf: UnionArm) -> UnionArm:
|
||||
value = leaf
|
||||
for _ in range(wraps):
|
||||
value = UnionArm("Wrap", {"inner": value})
|
||||
return value
|
||||
|
||||
|
||||
class BoundsVectorTests(unittest.TestCase):
|
||||
def test_every_bounds_outcome_is_held(self) -> None:
|
||||
entries = msgpack.unpackb(_vector("bounds-outcomes.msgpack"), raw=False)
|
||||
self.assertEqual(entries[0], ["limit", MAX_PAYLOAD_DEPTH])
|
||||
counts = {"accepted": 0, "refused": 0, "read-only": 0}
|
||||
for file, outcome_kind, union, key, detail in entries[1:]:
|
||||
counts[outcome_kind] += 1
|
||||
payload = _vector(file)
|
||||
if outcome_kind == "accepted":
|
||||
self.assertEqual(
|
||||
surface_document.encode_payload(surface_document.decode_payload(payload)), _vector(detail), file
|
||||
)
|
||||
elif outcome_kind == "read-only":
|
||||
self.assertEqual(surface_document.decode_payload(payload), _surface_value(), file)
|
||||
else:
|
||||
with self.assertRaises(ValueError, msg=file) as caught:
|
||||
surface_document.decode_payload(payload)
|
||||
message = str(caught.exception)
|
||||
self.assertNotIn(CANARY, message, file)
|
||||
if detail == "depth":
|
||||
self.assertIsInstance(caught.exception, CultCachePayloadDepthError, file)
|
||||
self.assertIn(surface_document.type, message, file)
|
||||
self.assertIn("nests 257 containers deep", message, file)
|
||||
self.assertIn("the limit is 256", message, file)
|
||||
self.assertIn("refused on read", message, file)
|
||||
continue
|
||||
self.assertNotIsInstance(caught.exception, CultCachePayloadDepthError, file)
|
||||
self.assertIn(f"Union '{union}' ", message, file)
|
||||
if detail == "key-out-of-range":
|
||||
self.assertIn("outside Int32", message, file)
|
||||
self.assertNotIn("does not declare", message, file)
|
||||
elif detail == "key-not-integer":
|
||||
self.assertIn("non-integer", message, file)
|
||||
else:
|
||||
self.assertEqual(detail, "nil-slots")
|
||||
self.assertIn(f"arm {key} has nil slots", message, file)
|
||||
self.assertEqual(counts, {"accepted": 4, "refused": 7, "read-only": 1})
|
||||
|
||||
def test_the_value_at_the_limit_writes_the_vector_and_the_value_past_it_is_refused_on_write(self) -> None:
|
||||
at_limit = {**_surface_value(), "root": _wrap_chain(126, UnionArm("Box", {"id": "leaf", "children": []}))}
|
||||
self.assertEqual(surface_document.encode_payload(at_limit), _vector("depth-at-limit.msgpack"))
|
||||
past = {**_surface_value(), "root": _wrap_chain(127, UnionArm("Text", {"id": "leaf", "content": CANARY}))}
|
||||
with self.assertRaises(CultCachePayloadDepthError) as caught:
|
||||
surface_document.encode_payload(past)
|
||||
message = str(caught.exception)
|
||||
self.assertEqual((caught.exception.depth, caught.exception.limit), (257, 256))
|
||||
self.assertIn("the limit is 256", message)
|
||||
self.assertIn("refused on write", message)
|
||||
self.assertNotIn(CANARY, message)
|
||||
|
||||
def test_a_cache_put_of_the_value_past_the_limit_refuses_and_stores_nothing(self) -> None:
|
||||
past = {**_surface_value(), "root": _wrap_chain(127, UnionArm("Box", {"id": "leaf", "children": []}))}
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = Path(tmp) / "store.cc"
|
||||
cache = (
|
||||
CultCache.builder()
|
||||
.register_document_type(surface_document)
|
||||
.add_generic_store(SingleFileMessagePackBackingStore(path))
|
||||
.build()
|
||||
)
|
||||
with self.assertRaises(CultCachePayloadDepthError):
|
||||
cache.put(surface_document, "surface", past)
|
||||
self.assertIsNone(cache.get(surface_document, "surface"))
|
||||
|
||||
def test_a_payload_beyond_the_c_unpackers_own_stack_is_the_depth_refusal(self) -> None:
|
||||
deep = b"\x91" * 2000 + b"\xc0"
|
||||
with self.assertRaises(CultCachePayloadDepthError) as caught:
|
||||
surface_document.decode_payload(deep)
|
||||
self.assertEqual(str(caught.exception).count("refused on read"), 1)
|
||||
huge = b"\x98" + b"\xc0" * 7 + b"\x91" * 100000 + b"\xc0"
|
||||
with self.assertRaises(CultCachePayloadDepthError):
|
||||
surface_document.decode_payload(huge)
|
||||
|
||||
def test_a_deep_value_is_refused_by_the_depth_error_not_a_recursion_error(self) -> None:
|
||||
tree = define_document_type("tests.deep_tree", encode=lambda value: value)
|
||||
with self.assertRaises(CultCachePayloadDepthError) as caught:
|
||||
tree.encode_payload(_nest(5000))
|
||||
self.assertIn("refused on write", str(caught.exception))
|
||||
document = define_document_type("tests.json_tree")
|
||||
with self.assertRaises(CultCachePayloadDepthError) as read:
|
||||
document.decode_payload(b"[" * 300 + b"]" * 300)
|
||||
self.assertIn("refused on read", str(read.exception))
|
||||
|
||||
def test_a_codec_that_exhausts_the_interpreter_stack_keeps_its_own_recursion_error_on_each_side(self) -> None:
|
||||
def boom(value: object) -> object:
|
||||
return boom(value)
|
||||
|
||||
document = define_document_type("tests.boom", encode=boom, decode=boom)
|
||||
for run in (lambda: document.encode_payload("x"), lambda: document.decode_payload(b'"x"')):
|
||||
try:
|
||||
run()
|
||||
except RecursionError as caught:
|
||||
self.assertNotIsInstance(caught, CultCachePayloadDepthError)
|
||||
self.assertIn("boom", [frame.name for frame in traceback.extract_tb(caught.__traceback__)])
|
||||
else:
|
||||
self.fail("the codec's RecursionError was swallowed")
|
||||
with self.assertRaises(CultCachePayloadDepthError) as stack:
|
||||
surface_document.decode_payload(bytes([0x91]) * 2000 + bytes([0xC0]))
|
||||
self.assertEqual(
|
||||
str(stack.exception),
|
||||
"tests.union_surface payload nests 257 containers deep; the limit is 256 (refused on read).",
|
||||
)
|
||||
|
||||
def test_a_json_payload_past_the_interpreters_own_stack_keeps_the_decoders_recursion_error(self) -> None:
|
||||
document = define_document_type("tests.json_tree")
|
||||
with self.assertRaises(RecursionError) as caught:
|
||||
document.decode_payload(b"[" * 100000)
|
||||
self.assertNotIsInstance(caught.exception, CultCachePayloadDepthError)
|
||||
|
||||
def test_a_refusal_reports_the_depth_where_the_walk_stopped_whatever_the_payloads_real_depth(self) -> None:
|
||||
document = define_document_type("tests.json_tree", encode=lambda value: value)
|
||||
for depth in (257, 300, 900):
|
||||
with self.assertRaises(CultCachePayloadDepthError) as write:
|
||||
document.encode_payload(_nest(depth))
|
||||
self.assertEqual((write.exception.depth, write.exception.limit), (257, 256), depth)
|
||||
with self.assertRaises(CultCachePayloadDepthError) as read:
|
||||
document.decode_payload(b"[" * depth + b"]" * depth)
|
||||
self.assertEqual((read.exception.depth, read.exception.limit), (257, 256), depth)
|
||||
|
||||
def test_the_validator_sees_the_value_on_write_and_the_decoded_value_on_read(self) -> None:
|
||||
seen: list[object] = []
|
||||
document = define_document_type("tests.validated", validate=seen.append)
|
||||
document.decode_payload(document.encode_payload({"a": 1}))
|
||||
self.assertEqual(seen, [{"a": 1}, {"a": 1}])
|
||||
|
||||
def test_a_cycle_is_refused_as_depth(self) -> None:
|
||||
loop: list = []
|
||||
loop.append(loop)
|
||||
document = define_document_type("tests.cycle", encode=lambda value: value)
|
||||
with self.assertRaises(CultCachePayloadDepthError):
|
||||
document.encode_payload(loop)
|
||||
|
||||
|
||||
def _nest(depth: int, mixed: bool = False) -> object:
|
||||
value: object = "leaf"
|
||||
for level in range(depth):
|
||||
value = {"k": value} if mixed and level % 2 == 0 else [value]
|
||||
return value
|
||||
|
||||
|
||||
def _as_tuple(tree: object) -> object:
|
||||
return tuple(_as_tuple(child) for child in tree) if isinstance(tree, list) else tree
|
||||
|
||||
|
||||
class PayloadDepthRuleTests(unittest.TestCase):
|
||||
"""The nesting rule at its seam, on definitions that are not unions: the same routine serves any payload codec."""
|
||||
|
||||
def test_the_limit_is_256_and_depth_256_is_accepted_on_read_and_write_while_257_is_refused(self) -> None:
|
||||
self.assertEqual(MAX_PAYLOAD_DEPTH, 256)
|
||||
document = define_document_type("tests.json_tree", encode=lambda value: value)
|
||||
for mixed in (False, True):
|
||||
at_limit = _nest(256, mixed)
|
||||
self.assertEqual(document.decode_payload(document.encode_payload(at_limit)), at_limit)
|
||||
past = _nest(257, mixed)
|
||||
with self.assertRaises(CultCachePayloadDepthError):
|
||||
document.encode_payload(past)
|
||||
with self.assertRaises(CultCachePayloadDepthError):
|
||||
document.decode_payload(document.payload_encoder(past))
|
||||
|
||||
def test_a_tuple_and_a_container_dict_key_count_as_containers(self) -> None:
|
||||
document = define_document_type("tests.tuple_tree", encode=lambda value: value, payload_encoder=lambda tree: b"ok")
|
||||
self.assertEqual(document.encode_payload(_as_tuple(_nest(256))), b"ok")
|
||||
with self.assertRaises(CultCachePayloadDepthError):
|
||||
document.encode_payload(_as_tuple(_nest(257)))
|
||||
self.assertEqual(document.encode_payload({_as_tuple(_nest(255)): 1}), b"ok")
|
||||
with self.assertRaises(CultCachePayloadDepthError):
|
||||
document.encode_payload({_as_tuple(_nest(256)): 1})
|
||||
|
||||
def test_every_mapping_sequence_and_set_counts_not_only_list_tuple_and_dict(self) -> None:
|
||||
wrappers = {
|
||||
"deque": lambda inner: collections.deque([inner]),
|
||||
"mappingproxy": lambda inner: types.MappingProxyType({"k": inner}),
|
||||
"frozenset": lambda inner: frozenset([inner]),
|
||||
"userlist": lambda inner: collections.UserList([inner]),
|
||||
}
|
||||
for name, wrap in wrappers.items():
|
||||
document = define_document_type(f"tests.{name}", encode=lambda value: value, payload_encoder=lambda tree: b"ok")
|
||||
at_limit: object = "leaf"
|
||||
for _ in range(256):
|
||||
at_limit = wrap(at_limit)
|
||||
self.assertEqual(document.encode_payload(at_limit), b"ok", name)
|
||||
with self.assertRaises(CultCachePayloadDepthError, msg=name):
|
||||
document.encode_payload(wrap(at_limit))
|
||||
decoding = define_document_type(f"tests.{name}.read", payload_decoder=lambda payload, w=wrap: w(at_limit))
|
||||
with self.assertRaises(CultCachePayloadDepthError, msg=name):
|
||||
decoding.decode_payload(b"x")
|
||||
|
||||
def test_text_and_bytes_are_leaves_however_long(self) -> None:
|
||||
document = define_document_type("tests.leaves", encode=lambda value: value, payload_encoder=lambda tree: b"ok")
|
||||
self.assertEqual(document.encode_payload([["x" * 100000, b"y" * 100000, bytearray(5), memoryview(b"z")]]), b"ok")
|
||||
|
||||
def test_a_scalar_payload_has_no_depth(self) -> None:
|
||||
document = define_document_type("tests.scalar", encode=lambda value: value)
|
||||
for scalar in ("x", 5, None):
|
||||
self.assertEqual(document.decode_payload(document.encode_payload(scalar)), scalar)
|
||||
|
||||
def test_the_refusal_names_the_type_the_depth_and_the_limit_and_never_the_payload(self) -> None:
|
||||
document = define_document_type("tests.json_tree", encode=lambda value: value)
|
||||
value: object = CANARY
|
||||
for _ in range(257):
|
||||
value = [value]
|
||||
with self.assertRaises(CultCachePayloadDepthError) as caught:
|
||||
document.encode_payload(value)
|
||||
self.assertEqual(
|
||||
str(caught.exception),
|
||||
"tests.json_tree payload nests 257 containers deep; the limit is 256 (refused on write).",
|
||||
)
|
||||
self.assertIsInstance(caught.exception, ValueError)
|
||||
|
||||
|
||||
class UnionDecodeBoundsTests(unittest.TestCase):
|
||||
def test_the_arm_key_refusals_name_the_union_and_say_what_is_wrong(self) -> None:
|
||||
cases = [
|
||||
([2**31, []], "Union 'Node' value is malformed: the arm key is outside Int32"),
|
||||
([-(2**31) - 1, []], "Union 'Node' value is malformed: the arm key is outside Int32"),
|
||||
([1.0, []], "Union 'Node' value is malformed: the arm key is non-integer"),
|
||||
([True, []], "Union 'Node' value is malformed: the arm key is non-integer"),
|
||||
([1, None], "Union 'Node' arm 1 has nil slots"),
|
||||
([1, CANARY], "Union 'Node' value is malformed: expected [armKey, [armSlots]]"),
|
||||
]
|
||||
for raw, expected in cases:
|
||||
with self.subTest(key=raw[0], slots=type(raw[1]).__name__):
|
||||
with self.assertRaises(ValueError) as caught:
|
||||
node.decode(raw)
|
||||
self.assertEqual(str(caught.exception), expected)
|
||||
|
||||
def test_the_ends_of_the_int32_key_domain_are_unit_arms_that_read_and_write(self) -> None:
|
||||
self.assertEqual(outcome.decode([-(2**31), []]), UnionArm("Floor"))
|
||||
self.assertEqual(outcome.encode(UnionArm("Ceiling")), [2**31 - 1, []])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
|
@ -184,6 +184,49 @@ without pretending Rust has runtime reflection hiding under the floorboards.
|
|||
- `load_soa`
|
||||
- `SingleFileMessagePackBackingStore`
|
||||
|
||||
## Unions
|
||||
|
||||
A union that crosses runtimes is written `[armKey, [armSlots...]]`, the shape the C# reference writes for
|
||||
`[Union(key, type)]`. Derive `CultUnion` on an enum: every variant carries `#[cultcache(key = N)]` and is a unit
|
||||
(`[N, []]`) or a newtype over a `#[derive(CultSlots)]` struct, which is a `DatabaseEntry`'s slot array without the
|
||||
entry consts (a `String` or an `Option` is not an arm, and is a compile error). An arm key is the reference's Int32, negatives included, and is given once. A key the enum does not declare is a decode error naming the enum and the declared keys, and never
|
||||
quoting the payload. A null union is `Option<Enum>`. Plain serde enums are untouched and keep their bytes.
|
||||
|
||||
```rust
|
||||
use cultcache_rs::{CultSlots, CultUnion};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
||||
enum Node {
|
||||
#[cultcache(key = 0)]
|
||||
Box(BoxArm),
|
||||
#[cultcache(key = 1)]
|
||||
Text(TextArm),
|
||||
#[cultcache(key = 5)]
|
||||
Spacer, // a unit arm: [5, []]
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
||||
struct BoxArm {
|
||||
#[cultcache(key = 0)]
|
||||
id: String,
|
||||
#[cultcache(key = 1)]
|
||||
children: Vec<Node>, // recursive
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
||||
struct TextArm {
|
||||
#[cultcache(key = 0)]
|
||||
id: String,
|
||||
#[cultcache(key = 1)]
|
||||
content: String,
|
||||
}
|
||||
|
||||
let tree = Node::Box(BoxArm { id: "root".into(), children: vec![Node::Spacer] });
|
||||
let bytes = rmp_serde::to_vec(&tree)?;
|
||||
assert_eq!(rmp_serde::from_slice::<Node>(&bytes)?, tree);
|
||||
# Ok::<(), Box<dyn std::error::Error>>(())
|
||||
```
|
||||
|
||||
## Structure Of Arrays
|
||||
|
||||
The C# CultCache hot path exposes CPU-local SoA scans as:
|
||||
|
|
|
|||
|
|
@ -12,6 +12,13 @@ use syn::parse_macro_input;
|
|||
#[proc_macro_derive(DatabaseEntry, attributes(cultcache))]
|
||||
pub fn derive_database_entry(input: TokenStream) -> TokenStream {
|
||||
let input = parse_macro_input!(input as DeriveInput);
|
||||
match database_entry_codec(input) {
|
||||
Ok(tokens) => tokens.into(),
|
||||
Err(error) => error.to_compile_error().into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn database_entry_codec(input: DeriveInput) -> syn::Result<proc_macro2::TokenStream> {
|
||||
let ident = input.ident.clone();
|
||||
let mut entry_type: Option<LitStr> = None;
|
||||
let mut schema_name: Option<LitStr> = None;
|
||||
|
|
@ -23,55 +30,105 @@ pub fn derive_database_entry(input: TokenStream) -> TokenStream {
|
|||
{
|
||||
let parse_result = attribute.parse_nested_meta(|meta| {
|
||||
if meta.path.is_ident("type") {
|
||||
once(&entry_type, &meta, "type")?;
|
||||
entry_type = Some(meta.value()?.parse()?);
|
||||
Ok(())
|
||||
} else if meta.path.is_ident("schema") {
|
||||
once(&schema_name, &meta, "schema")?;
|
||||
schema_name = Some(meta.value()?.parse()?);
|
||||
Ok(())
|
||||
} else {
|
||||
Err(meta.error("unsupported cultcache attribute"))
|
||||
}
|
||||
});
|
||||
if let Err(error) = parse_result {
|
||||
return error.to_compile_error().into();
|
||||
}
|
||||
parse_result?;
|
||||
}
|
||||
|
||||
let Some(entry_type) = entry_type else {
|
||||
return syn::Error::new_spanned(
|
||||
return Err(syn::Error::new_spanned(
|
||||
ident,
|
||||
"DatabaseEntry derive requires #[cultcache(type = \"...\")]",
|
||||
)
|
||||
.to_compile_error()
|
||||
.into();
|
||||
));
|
||||
};
|
||||
let schema_name = schema_name.unwrap_or_else(|| LitStr::new(&ident.to_string(), ident.span()));
|
||||
|
||||
let fields = match input.data {
|
||||
let slots = named_slots(input.data, &ident, "DatabaseEntry")?;
|
||||
let codec = slot_codec(&ident, &slots);
|
||||
|
||||
Ok(quote! {
|
||||
impl ::cultcache_rs::DatabaseEntry for #ident {
|
||||
const TYPE: &'static str = #entry_type;
|
||||
const SCHEMA_NAME: &'static str = #schema_name;
|
||||
}
|
||||
|
||||
#codec
|
||||
})
|
||||
}
|
||||
|
||||
/// A named struct whose fields carry `#[cultcache(key = N)]`: the same positional
|
||||
/// array a `DatabaseEntry` is, without the entry consts. The payload of a union arm,
|
||||
/// or any nested record that crosses runtimes.
|
||||
#[proc_macro_derive(CultSlots, attributes(cultcache))]
|
||||
pub fn derive_cult_slots(input: TokenStream) -> TokenStream {
|
||||
let input = parse_macro_input!(input as DeriveInput);
|
||||
match cult_slots_codec(input) {
|
||||
Ok(tokens) => tokens.into(),
|
||||
Err(error) => error.to_compile_error().into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn cult_slots_codec(input: DeriveInput) -> syn::Result<proc_macro2::TokenStream> {
|
||||
let ident = input.ident.clone();
|
||||
if !input.generics.params.is_empty() {
|
||||
return Err(syn::Error::new_spanned(ident, "CultSlots derive does not support generics"));
|
||||
}
|
||||
let slots = named_slots(input.data, &ident, "CultSlots")?;
|
||||
Ok(slot_codec(&ident, &slots))
|
||||
}
|
||||
|
||||
/// An enum written as `[key, armSlots]`. Every variant carries `#[cultcache(key = N)]`
|
||||
/// and is a unit (`[N, []]`) or a newtype over a type that serializes as an array.
|
||||
/// A key the enum does not declare is a decode error; there is no catch-all arm.
|
||||
#[proc_macro_derive(CultUnion, attributes(cultcache))]
|
||||
pub fn derive_cult_union(input: TokenStream) -> TokenStream {
|
||||
let input = parse_macro_input!(input as DeriveInput);
|
||||
match union_codec(input) {
|
||||
Ok(tokens) => tokens.into(),
|
||||
Err(error) => error.to_compile_error().into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The largest array16 length: a slot record is written as a dense array, so a key above it would
|
||||
/// make every encode allocate and write an unbounded run of nils. Every runtime and the C# catalog
|
||||
/// refuse the same domain.
|
||||
const MAX_SLOT_KEY: usize = 65535;
|
||||
|
||||
fn named_slots(data: Data, ident: &syn::Ident, owner: &str) -> syn::Result<Vec<CultCacheSlot>> {
|
||||
let fields = match data {
|
||||
Data::Struct(data) => match data.fields {
|
||||
Fields::Named(fields) => fields.named,
|
||||
_ => {
|
||||
return syn::Error::new_spanned(
|
||||
return Err(syn::Error::new_spanned(
|
||||
ident,
|
||||
"DatabaseEntry derive requires a named struct",
|
||||
)
|
||||
.to_compile_error()
|
||||
.into();
|
||||
format!("{owner} derive requires a named struct"),
|
||||
));
|
||||
}
|
||||
},
|
||||
_ => {
|
||||
return syn::Error::new_spanned(ident, "DatabaseEntry derive requires a struct")
|
||||
.to_compile_error()
|
||||
.into();
|
||||
return Err(syn::Error::new_spanned(
|
||||
ident,
|
||||
format!("{owner} derive requires a struct"),
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
let mut slots: Vec<CultCacheSlot> = Vec::new();
|
||||
for field in fields {
|
||||
let Some(field_ident) = field.ident else {
|
||||
return syn::Error::new_spanned(field.ty, "DatabaseEntry derive requires named fields")
|
||||
.to_compile_error()
|
||||
.into();
|
||||
return Err(syn::Error::new_spanned(
|
||||
field.ty,
|
||||
format!("{owner} derive requires named fields"),
|
||||
));
|
||||
};
|
||||
let mut key: Option<usize> = None;
|
||||
let mut default = false;
|
||||
|
|
@ -81,10 +138,18 @@ pub fn derive_database_entry(input: TokenStream) -> TokenStream {
|
|||
.iter()
|
||||
.filter(|attr| attr.path().is_ident("cultcache"))
|
||||
{
|
||||
let parse_result = attribute.parse_nested_meta(|meta| {
|
||||
attribute.parse_nested_meta(|meta| {
|
||||
if meta.path.is_ident("key") {
|
||||
once(&key, &meta, "key")?;
|
||||
let value: LitInt = meta.value()?.parse()?;
|
||||
key = Some(value.base10_parse()?);
|
||||
let slot: usize = value.base10_parse()?;
|
||||
if slot > MAX_SLOT_KEY {
|
||||
return Err(syn::Error::new_spanned(
|
||||
&value,
|
||||
format!("{owner} slot key {slot} is outside 0..={MAX_SLOT_KEY}"),
|
||||
));
|
||||
}
|
||||
key = Some(slot);
|
||||
Ok(())
|
||||
} else if meta.path.is_ident("default") {
|
||||
default = true;
|
||||
|
|
@ -95,26 +160,19 @@ pub fn derive_database_entry(input: TokenStream) -> TokenStream {
|
|||
} else {
|
||||
Err(meta.error("unsupported field cultcache attribute"))
|
||||
}
|
||||
});
|
||||
if let Err(error) = parse_result {
|
||||
return error.to_compile_error().into();
|
||||
}
|
||||
})?;
|
||||
}
|
||||
let Some(key) = key else {
|
||||
return syn::Error::new_spanned(
|
||||
return Err(syn::Error::new_spanned(
|
||||
field_ident,
|
||||
"DatabaseEntry fields require #[cultcache(key = N)]",
|
||||
)
|
||||
.to_compile_error()
|
||||
.into();
|
||||
format!("{owner} fields require #[cultcache(key = N)]"),
|
||||
));
|
||||
};
|
||||
if slots.iter().any(|slot| slot.key == key) {
|
||||
return syn::Error::new_spanned(
|
||||
return Err(syn::Error::new_spanned(
|
||||
field_ident,
|
||||
format!("duplicate DatabaseEntry slot {key}"),
|
||||
)
|
||||
.to_compile_error()
|
||||
.into();
|
||||
format!("duplicate {owner} slot {key}"),
|
||||
));
|
||||
}
|
||||
slots.push(CultCacheSlot {
|
||||
key,
|
||||
|
|
@ -125,6 +183,12 @@ pub fn derive_database_entry(input: TokenStream) -> TokenStream {
|
|||
});
|
||||
}
|
||||
slots.sort_by_key(|slot| slot.key);
|
||||
Ok(slots)
|
||||
}
|
||||
|
||||
/// The one slot generator: Serialize as a positional array with nil gaps, Deserialize
|
||||
/// by slot with the `default` and `bytes` attributes.
|
||||
fn slot_codec(ident: &syn::Ident, slots: &[CultCacheSlot]) -> proc_macro2::TokenStream {
|
||||
let max_slot = slots.iter().map(|slot| slot.key).max().unwrap_or(0);
|
||||
|
||||
let serialize_elements = (0..=max_slot).map(|slot| {
|
||||
|
|
@ -211,15 +275,14 @@ pub fn derive_database_entry(input: TokenStream) -> TokenStream {
|
|||
});
|
||||
|
||||
quote! {
|
||||
impl ::cultcache_rs::DatabaseEntry for #ident {
|
||||
const TYPE: &'static str = #entry_type;
|
||||
const SCHEMA_NAME: &'static str = #schema_name;
|
||||
impl ::cultcache_rs::SlotRecord for #ident {
|
||||
fn __slots_array() {}
|
||||
}
|
||||
|
||||
impl ::serde::Serialize for #ident {
|
||||
fn serialize<S>(&self, serializer: S) -> ::std::result::Result<S::Ok, S::Error>
|
||||
fn serialize<__S>(&self, serializer: __S) -> ::std::result::Result<__S::Ok, __S::Error>
|
||||
where
|
||||
S: ::serde::Serializer,
|
||||
__S: ::serde::Serializer,
|
||||
{
|
||||
use ::serde::ser::SerializeTuple;
|
||||
let mut tuple = serializer.serialize_tuple(#max_slot + 1)?;
|
||||
|
|
@ -229,22 +292,22 @@ pub fn derive_database_entry(input: TokenStream) -> TokenStream {
|
|||
}
|
||||
|
||||
impl<'de> ::serde::Deserialize<'de> for #ident {
|
||||
fn deserialize<D>(deserializer: D) -> ::std::result::Result<Self, D::Error>
|
||||
fn deserialize<__D>(deserializer: __D) -> ::std::result::Result<Self, __D::Error>
|
||||
where
|
||||
D: ::serde::Deserializer<'de>,
|
||||
__D: ::serde::Deserializer<'de>,
|
||||
{
|
||||
struct CultCacheVisitor;
|
||||
struct __CultCacheVisitor;
|
||||
|
||||
impl<'de> ::serde::de::Visitor<'de> for CultCacheVisitor {
|
||||
impl<'de> ::serde::de::Visitor<'de> for __CultCacheVisitor {
|
||||
type Value = #ident;
|
||||
|
||||
fn expecting(&self, formatter: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
|
||||
formatter.write_str(concat!("a CultCache array for ", stringify!(#ident)))
|
||||
}
|
||||
|
||||
fn visit_seq<A>(self, mut seq: A) -> ::std::result::Result<Self::Value, A::Error>
|
||||
fn visit_seq<__A>(self, mut seq: __A) -> ::std::result::Result<Self::Value, __A::Error>
|
||||
where
|
||||
A: ::serde::de::SeqAccess<'de>,
|
||||
__A: ::serde::de::SeqAccess<'de>,
|
||||
{
|
||||
#(#option_declarations)*
|
||||
let mut index = 0usize;
|
||||
|
|
@ -262,11 +325,35 @@ pub fn derive_database_entry(input: TokenStream) -> TokenStream {
|
|||
}
|
||||
}
|
||||
|
||||
deserializer.deserialize_tuple(#max_slot + 1, CultCacheVisitor)
|
||||
deserializer.deserialize_tuple(#max_slot + 1, __CultCacheVisitor)
|
||||
}
|
||||
}
|
||||
}
|
||||
.into()
|
||||
}
|
||||
|
||||
/// An attribute names each thing once; a second `key = N` would silently win otherwise.
|
||||
fn once<T>(seen: &Option<T>, meta: &syn::meta::ParseNestedMeta, name: &str) -> syn::Result<()> {
|
||||
if seen.is_some() {
|
||||
return Err(meta.error(format!("repeated `{name}`: #[cultcache({name} = ...)] is given once")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// An arm key is the reference's Int32, negatives included: `key = 5` or `key = -1`.
|
||||
fn arm_key(meta: &syn::meta::ParseNestedMeta) -> syn::Result<i32> {
|
||||
let expr: syn::Expr = meta.value()?.parse()?;
|
||||
let (negative, literal) = match expr {
|
||||
syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Int(literal), .. }) => (false, literal),
|
||||
syn::Expr::Unary(syn::ExprUnary { op: syn::UnOp::Neg(_), expr, .. }) => match *expr {
|
||||
syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Int(literal), .. }) => (true, literal),
|
||||
other => return Err(syn::Error::new_spanned(other, "a CultUnion arm key is an integer literal")),
|
||||
},
|
||||
other => return Err(syn::Error::new_spanned(other, "a CultUnion arm key is an integer literal")),
|
||||
};
|
||||
let magnitude: i128 = literal.base10_parse()?;
|
||||
let value = if negative { -magnitude } else { magnitude };
|
||||
i32::try_from(value)
|
||||
.map_err(|_| syn::Error::new_spanned(&literal, format!("CultUnion arm key {value} is outside Int32")))
|
||||
}
|
||||
|
||||
struct CultCacheSlot {
|
||||
|
|
@ -276,3 +363,473 @@ struct CultCacheSlot {
|
|||
default: bool,
|
||||
bytes: bool,
|
||||
}
|
||||
|
||||
fn union_codec(input: DeriveInput) -> syn::Result<proc_macro2::TokenStream> {
|
||||
let ident = input.ident.clone();
|
||||
if !input.generics.params.is_empty() {
|
||||
return Err(syn::Error::new_spanned(
|
||||
ident,
|
||||
"CultUnion derive does not support generics",
|
||||
));
|
||||
}
|
||||
let Data::Enum(data) = input.data else {
|
||||
return Err(syn::Error::new_spanned(ident, "CultUnion derive requires an enum"));
|
||||
};
|
||||
if data.variants.is_empty() {
|
||||
return Err(syn::Error::new_spanned(ident, "CultUnion derive requires at least one variant"));
|
||||
}
|
||||
|
||||
struct Arm {
|
||||
key: i32,
|
||||
ident: syn::Ident,
|
||||
payload: Option<Type>,
|
||||
}
|
||||
let mut arms: Vec<Arm> = Vec::new();
|
||||
for variant in data.variants {
|
||||
let mut key: Option<i32> = None;
|
||||
for attribute in variant
|
||||
.attrs
|
||||
.iter()
|
||||
.filter(|attr| attr.path().is_ident("cultcache"))
|
||||
{
|
||||
attribute.parse_nested_meta(|meta| {
|
||||
if meta.path.is_ident("key") {
|
||||
once(&key, &meta, "key")?;
|
||||
key = Some(arm_key(&meta)?);
|
||||
Ok(())
|
||||
} else {
|
||||
Err(meta.error("unsupported variant cultcache attribute"))
|
||||
}
|
||||
})?;
|
||||
}
|
||||
let Some(key) = key else {
|
||||
return Err(syn::Error::new_spanned(
|
||||
&variant.ident,
|
||||
"CultUnion variants require #[cultcache(key = N)]",
|
||||
));
|
||||
};
|
||||
if arms.iter().any(|arm| arm.key == key) {
|
||||
return Err(syn::Error::new_spanned(
|
||||
&variant.ident,
|
||||
format!("duplicate CultUnion key {key}"),
|
||||
));
|
||||
}
|
||||
let payload = match variant.fields {
|
||||
Fields::Unit => None,
|
||||
Fields::Unnamed(fields) if fields.unnamed.len() == 1 => {
|
||||
Some(fields.unnamed.into_iter().next().expect("one field").ty)
|
||||
}
|
||||
_ => {
|
||||
return Err(syn::Error::new_spanned(
|
||||
&variant.ident,
|
||||
"a CultUnion variant is a unit or a newtype: use a newtype over a #[derive(CultSlots)] struct",
|
||||
));
|
||||
}
|
||||
};
|
||||
arms.push(Arm {
|
||||
key,
|
||||
ident: variant.ident,
|
||||
payload,
|
||||
});
|
||||
}
|
||||
|
||||
let enum_name = ident.to_string();
|
||||
let mut declared_keys: Vec<i32> = arms.iter().map(|arm| arm.key).collect();
|
||||
declared_keys.sort_unstable();
|
||||
let declared = declared_keys.iter().map(i32::to_string).collect::<Vec<_>>().join(", ");
|
||||
let unknown_message = format!("unknown arm key {{}} for union {enum_name}; declared keys: {declared}");
|
||||
let arity_message = format!("union {enum_name} is not a [key, slots] pair");
|
||||
let non_integer_message = format!("union {enum_name} has a non-integer arm key; declared keys: {declared}");
|
||||
let nil_slots_message = format!("union {enum_name} arm {{}} has nil slots; declared keys: {declared}");
|
||||
let out_of_range_message = format!("union {enum_name} has an arm key outside Int32; declared keys: {declared}");
|
||||
let payload_checks = arms.iter().filter_map(|arm| arm.payload.as_ref()).map(|ty| {
|
||||
quote! { assert_slot_record::<#ty>(); }
|
||||
});
|
||||
|
||||
let serialize_arms = arms.iter().map(|arm| {
|
||||
let variant = &arm.ident;
|
||||
let key = arm.key;
|
||||
if arm.payload.is_some() {
|
||||
quote! {
|
||||
Self::#variant(arm) => {
|
||||
tuple.serialize_element(&#key)?;
|
||||
tuple.serialize_element(arm)?;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
quote! {
|
||||
Self::#variant => {
|
||||
tuple.serialize_element(&#key)?;
|
||||
tuple.serialize_element(&[(); 0])?;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let deserialize_arms = arms.iter().map(|arm| {
|
||||
let variant = &arm.ident;
|
||||
let key = arm.key;
|
||||
if let Some(ty) = &arm.payload {
|
||||
quote! {
|
||||
#key => {
|
||||
// A nil in the slots position is not an empty record.
|
||||
match seq.next_element::<::std::option::Option<#ty>>()? {
|
||||
::std::option::Option::Some(::std::option::Option::Some(arm)) => #ident::#variant(arm),
|
||||
::std::option::Option::Some(::std::option::Option::None) => {
|
||||
return ::std::result::Result::Err(::serde::de::Error::custom(
|
||||
format!(#nil_slots_message, #key),
|
||||
));
|
||||
}
|
||||
::std::option::Option::None => {
|
||||
return ::std::result::Result::Err(::serde::de::Error::custom(#arity_message));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
quote! {
|
||||
#key => {
|
||||
match seq
|
||||
.next_element::<::std::option::Option<[(); 0]>>()
|
||||
.map_err(|_| ::serde::de::Error::custom(#arity_message))?
|
||||
{
|
||||
::std::option::Option::Some(::std::option::Option::Some(_)) => #ident::#variant,
|
||||
::std::option::Option::Some(::std::option::Option::None) => {
|
||||
return ::std::result::Result::Err(::serde::de::Error::custom(
|
||||
format!(#nil_slots_message, #key),
|
||||
));
|
||||
}
|
||||
::std::option::Option::None => {
|
||||
return ::std::result::Result::Err(::serde::de::Error::custom(#arity_message));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Ok(quote! {
|
||||
// An arm is a slots array: a newtype over anything else is refused here, by the
|
||||
// trait the CultSlots and DatabaseEntry derives implement.
|
||||
const _: fn() = || {
|
||||
#[allow(dead_code)]
|
||||
fn assert_slot_record<T: ::cultcache_rs::SlotRecord>() {}
|
||||
#(#payload_checks)*
|
||||
};
|
||||
|
||||
impl ::serde::Serialize for #ident {
|
||||
fn serialize<__S>(&self, serializer: __S) -> ::std::result::Result<__S::Ok, __S::Error>
|
||||
where
|
||||
__S: ::serde::Serializer,
|
||||
{
|
||||
use ::serde::ser::SerializeTuple;
|
||||
let mut tuple = serializer.serialize_tuple(2)?;
|
||||
match self {
|
||||
#(#serialize_arms)*
|
||||
}
|
||||
tuple.end()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> ::serde::Deserialize<'de> for #ident {
|
||||
fn deserialize<__D>(deserializer: __D) -> ::std::result::Result<Self, __D::Error>
|
||||
where
|
||||
__D: ::serde::Deserializer<'de>,
|
||||
{
|
||||
// The reference classifies the key before the arm: an integer in Int32, an
|
||||
// integer outside it, or not an integer. No input value is kept or echoed.
|
||||
enum __ArmKey {
|
||||
Int(i64),
|
||||
OutOfRange,
|
||||
NonInteger,
|
||||
}
|
||||
struct __ArmKeyProbe(__ArmKey);
|
||||
struct __ArmKeyVisitor;
|
||||
|
||||
impl<'de> ::serde::de::Visitor<'de> for __ArmKeyVisitor {
|
||||
type Value = __ArmKeyProbe;
|
||||
|
||||
fn expecting(&self, formatter: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
|
||||
formatter.write_str("an integer arm key")
|
||||
}
|
||||
|
||||
fn visit_i64<__E>(self, value: i64) -> ::std::result::Result<Self::Value, __E> {
|
||||
Ok(__ArmKeyProbe(__ArmKey::Int(value)))
|
||||
}
|
||||
|
||||
fn visit_u64<__E>(self, value: u64) -> ::std::result::Result<Self::Value, __E> {
|
||||
Ok(__ArmKeyProbe(match i64::try_from(value) {
|
||||
Ok(value) => __ArmKey::Int(value),
|
||||
Err(_) => __ArmKey::OutOfRange,
|
||||
}))
|
||||
}
|
||||
|
||||
fn visit_bool<__E>(self, _: bool) -> ::std::result::Result<Self::Value, __E> {
|
||||
Ok(__ArmKeyProbe(__ArmKey::NonInteger))
|
||||
}
|
||||
|
||||
fn visit_f64<__E>(self, _: f64) -> ::std::result::Result<Self::Value, __E> {
|
||||
Ok(__ArmKeyProbe(__ArmKey::NonInteger))
|
||||
}
|
||||
|
||||
fn visit_str<__E>(self, _: &str) -> ::std::result::Result<Self::Value, __E> {
|
||||
Ok(__ArmKeyProbe(__ArmKey::NonInteger))
|
||||
}
|
||||
|
||||
fn visit_bytes<__E>(self, _: &[u8]) -> ::std::result::Result<Self::Value, __E> {
|
||||
Ok(__ArmKeyProbe(__ArmKey::NonInteger))
|
||||
}
|
||||
|
||||
fn visit_unit<__E>(self) -> ::std::result::Result<Self::Value, __E> {
|
||||
Ok(__ArmKeyProbe(__ArmKey::NonInteger))
|
||||
}
|
||||
|
||||
fn visit_none<__E>(self) -> ::std::result::Result<Self::Value, __E> {
|
||||
Ok(__ArmKeyProbe(__ArmKey::NonInteger))
|
||||
}
|
||||
|
||||
fn visit_some<__D>(self, deserializer: __D) -> ::std::result::Result<Self::Value, __D::Error>
|
||||
where
|
||||
__D: ::serde::Deserializer<'de>,
|
||||
{
|
||||
<::serde::de::IgnoredAny as ::serde::Deserialize>::deserialize(deserializer)?;
|
||||
Ok(__ArmKeyProbe(__ArmKey::NonInteger))
|
||||
}
|
||||
|
||||
// A MessagePack ext value (fixext, timestamp, ext8) reaches the visitor here.
|
||||
fn visit_newtype_struct<__D>(self, deserializer: __D) -> ::std::result::Result<Self::Value, __D::Error>
|
||||
where
|
||||
__D: ::serde::Deserializer<'de>,
|
||||
{
|
||||
<::serde::de::IgnoredAny as ::serde::Deserialize>::deserialize(deserializer)?;
|
||||
Ok(__ArmKeyProbe(__ArmKey::NonInteger))
|
||||
}
|
||||
|
||||
fn visit_seq<__A>(self, mut seq: __A) -> ::std::result::Result<Self::Value, __A::Error>
|
||||
where
|
||||
__A: ::serde::de::SeqAccess<'de>,
|
||||
{
|
||||
while seq.next_element::<::serde::de::IgnoredAny>()?.is_some() {}
|
||||
Ok(__ArmKeyProbe(__ArmKey::NonInteger))
|
||||
}
|
||||
|
||||
fn visit_map<__A>(self, mut map: __A) -> ::std::result::Result<Self::Value, __A::Error>
|
||||
where
|
||||
__A: ::serde::de::MapAccess<'de>,
|
||||
{
|
||||
while map.next_entry::<::serde::de::IgnoredAny, ::serde::de::IgnoredAny>()?.is_some() {}
|
||||
Ok(__ArmKeyProbe(__ArmKey::NonInteger))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> ::serde::Deserialize<'de> for __ArmKeyProbe {
|
||||
fn deserialize<__D>(deserializer: __D) -> ::std::result::Result<Self, __D::Error>
|
||||
where
|
||||
__D: ::serde::Deserializer<'de>,
|
||||
{
|
||||
deserializer.deserialize_any(__ArmKeyVisitor)
|
||||
}
|
||||
}
|
||||
|
||||
struct __CultUnionVisitor;
|
||||
|
||||
impl<'de> ::serde::de::Visitor<'de> for __CultUnionVisitor {
|
||||
type Value = #ident;
|
||||
|
||||
fn expecting(&self, formatter: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
|
||||
formatter.write_str(concat!("a [key, slots] pair for union ", stringify!(#ident)))
|
||||
}
|
||||
|
||||
fn visit_seq<__A>(self, mut seq: __A) -> ::std::result::Result<Self::Value, __A::Error>
|
||||
where
|
||||
__A: ::serde::de::SeqAccess<'de>,
|
||||
{
|
||||
if seq.size_hint().is_some_and(|len| len != 2) {
|
||||
return ::std::result::Result::Err(::serde::de::Error::custom(#arity_message));
|
||||
}
|
||||
let key = match seq
|
||||
.next_element::<__ArmKeyProbe>()
|
||||
.map_err(|_| ::serde::de::Error::custom(#arity_message))?
|
||||
.ok_or_else(|| ::serde::de::Error::custom(#arity_message))?
|
||||
.0
|
||||
{
|
||||
__ArmKey::Int(wide) => match i32::try_from(wide) {
|
||||
Ok(key) => key,
|
||||
Err(_) => {
|
||||
return ::std::result::Result::Err(::serde::de::Error::custom(#out_of_range_message));
|
||||
}
|
||||
},
|
||||
__ArmKey::OutOfRange => {
|
||||
return ::std::result::Result::Err(::serde::de::Error::custom(#out_of_range_message));
|
||||
}
|
||||
__ArmKey::NonInteger => {
|
||||
return ::std::result::Result::Err(::serde::de::Error::custom(#non_integer_message));
|
||||
}
|
||||
};
|
||||
let value = match key {
|
||||
#(#deserialize_arms)*
|
||||
other => {
|
||||
return ::std::result::Result::Err(::serde::de::Error::custom(
|
||||
format!(#unknown_message, other),
|
||||
));
|
||||
}
|
||||
};
|
||||
if seq.next_element::<::serde::de::IgnoredAny>()?.is_some() {
|
||||
return ::std::result::Result::Err(::serde::de::Error::custom(#arity_message));
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
}
|
||||
|
||||
deserializer.deserialize_tuple(2, __CultUnionVisitor)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn union_error(source: &str) -> String {
|
||||
let input: DeriveInput = syn::parse_str(source).expect("the fixture parses");
|
||||
union_codec(input).expect_err("the fixture is refused").to_string()
|
||||
}
|
||||
|
||||
fn slots_error(source: &str) -> String {
|
||||
let input: DeriveInput = syn::parse_str(source).expect("the fixture parses");
|
||||
let Err(error) = named_slots(input.data, &input.ident, "CultSlots") else {
|
||||
panic!("the fixture is refused");
|
||||
};
|
||||
error.to_string()
|
||||
}
|
||||
|
||||
fn union_ok(source: &str) {
|
||||
let input: DeriveInput = syn::parse_str(source).expect("the fixture parses");
|
||||
union_codec(input).expect("the fixture is accepted");
|
||||
}
|
||||
|
||||
// Keys other than 0 throughout, so a default of 0 cannot stand in for a missing key.
|
||||
#[test]
|
||||
fn a_variant_without_a_key_is_refused_for_that_reason() {
|
||||
let message = union_error("enum E { #[cultcache(key = 4)] A(Arm), B }");
|
||||
assert!(message.contains("require #[cultcache(key = N)]"), "{message}");
|
||||
let message = union_error("enum E { B, #[cultcache(key = 4)] A(Arm) }");
|
||||
assert!(message.contains("require #[cultcache(key = N)]"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_variants_with_one_key_are_refused_for_that_reason() {
|
||||
let message = union_error("enum E { #[cultcache(key = 4)] A(Arm), #[cultcache(key = 4)] B }");
|
||||
assert!(message.contains("duplicate CultUnion key 4"), "{message}");
|
||||
let message = union_error("enum E { #[cultcache(key = 0x4)] A(Arm), #[cultcache(key = 4)] B }");
|
||||
assert!(message.contains("duplicate CultUnion key 4"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_repeated_key_attribute_is_refused_on_a_variant_and_on_a_field() {
|
||||
for source in [
|
||||
"enum E { #[cultcache(key = 7)] #[cultcache(key = 0)] A(Arm) }",
|
||||
"enum E { #[cultcache(key = 7, key = 0)] A(Arm) }",
|
||||
] {
|
||||
let message = union_error(source);
|
||||
assert!(message.contains("repeated `key`"), "{source}: {message}");
|
||||
}
|
||||
for source in [
|
||||
"struct S { #[cultcache(key = 7)] #[cultcache(key = 0)] a: String }",
|
||||
"struct S { #[cultcache(key = 7, key = 0)] a: String }",
|
||||
] {
|
||||
let message = slots_error(source);
|
||||
assert!(message.contains("repeated `key`"), "{source}: {message}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_duplicate_slot_is_refused_for_that_reason() {
|
||||
let message = slots_error("struct S { #[cultcache(key = 3)] a: String, #[cultcache(key = 3)] b: String }");
|
||||
assert!(message.contains("duplicate CultSlots slot 3"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_field_without_a_key_is_refused_for_that_reason() {
|
||||
let message = slots_error("struct S { #[cultcache(key = 3)] a: String, b: String }");
|
||||
assert!(message.contains("fields require #[cultcache(key = N)]"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn struct_multi_field_and_generic_variants_are_refused_for_their_reasons() {
|
||||
let message = union_error("enum E { #[cultcache(key = 4)] A { id: String } }");
|
||||
assert!(message.contains("use a newtype over a #[derive(CultSlots)] struct"), "{message}");
|
||||
let message = union_error("enum E { #[cultcache(key = 4)] A(Arm, Arm) }");
|
||||
assert!(message.contains("use a newtype over a #[derive(CultSlots)] struct"), "{message}");
|
||||
let message = union_error("enum E<T> { #[cultcache(key = 4)] A(Arm), #[cultcache(key = 5)] B(T) }");
|
||||
assert!(message.contains("does not support generics"), "{message}");
|
||||
}
|
||||
|
||||
// The arm key domain is the reference's Int32: negatives declare, Int32::MAX declares,
|
||||
// one past it is a compile error.
|
||||
#[test]
|
||||
fn the_arm_key_domain_is_int32() {
|
||||
union_ok("enum E { #[cultcache(key = -1)] A(Arm), #[cultcache(key = 2147483647)] B, #[cultcache(key = -2147483648)] C }");
|
||||
for source in [
|
||||
"enum E { #[cultcache(key = 2147483648)] A(Arm) }",
|
||||
"enum E { #[cultcache(key = -2147483649)] A(Arm) }",
|
||||
"enum E { #[cultcache(key = 4294967296)] A(Arm) }",
|
||||
] {
|
||||
let message = union_error(source);
|
||||
assert!(message.contains("outside Int32"), "{source}: {message}");
|
||||
}
|
||||
let message = union_error("enum E { #[cultcache(key = \"1\")] A(Arm) }");
|
||||
assert!(message.contains("integer literal"), "{message}");
|
||||
}
|
||||
fn entry_result(source: &str) -> syn::Result<proc_macro2::TokenStream> {
|
||||
database_entry_codec(syn::parse_str(source).expect("the fixture parses"))
|
||||
}
|
||||
|
||||
fn slots_result(source: &str) -> syn::Result<proc_macro2::TokenStream> {
|
||||
cult_slots_codec(syn::parse_str(source).expect("the fixture parses"))
|
||||
}
|
||||
|
||||
// Each attribute names a thing once; the second would silently win otherwise.
|
||||
#[test]
|
||||
fn a_repeated_type_or_schema_attribute_is_refused_for_that_reason() {
|
||||
for source in [
|
||||
"#[cultcache(type = \"a.one\")] #[cultcache(type = \"a.two\")] struct S { #[cultcache(key = 0)] id: String }",
|
||||
"#[cultcache(type = \"a.one\", type = \"a.two\")] struct S { #[cultcache(key = 0)] id: String }",
|
||||
"#[cultcache(type = \"a.one\", schema = \"s.one\")] #[cultcache(schema = \"s.two\")] struct S { #[cultcache(key = 0)] id: String }",
|
||||
"#[cultcache(type = \"a.one\", schema = \"s.one\", schema = \"s.two\")] struct S { #[cultcache(key = 0)] id: String }",
|
||||
] {
|
||||
let message = entry_result(source).expect_err(source).to_string();
|
||||
assert!(message.contains("repeated `type`") || message.contains("repeated `schema`"), "{source}: {message}");
|
||||
}
|
||||
entry_result("#[cultcache(type = \"a.one\", schema = \"s.one\")] struct S { #[cultcache(key = 0)] id: String }")
|
||||
.expect("one type and one schema are accepted");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_generic_slots_struct_and_a_missing_type_are_refused_for_their_reasons() {
|
||||
let message = slots_result("struct S<T> { #[cultcache(key = 0)] id: T }").unwrap_err().to_string();
|
||||
assert!(message.contains("does not support generics"), "{message}");
|
||||
let message = entry_result("struct S { #[cultcache(key = 0)] id: String }").unwrap_err().to_string();
|
||||
assert!(message.contains("requires #[cultcache(type"), "{message}");
|
||||
}
|
||||
|
||||
// A slot record is a dense array: keys stop at the largest array16 length.
|
||||
#[test]
|
||||
fn the_slot_key_domain_ends_at_65535() {
|
||||
slots_error_free("struct S { #[cultcache(key = 0)] a: String, #[cultcache(key = 65535)] b: String }");
|
||||
for source in [
|
||||
"struct S { #[cultcache(key = 65536)] a: String }",
|
||||
"struct S { #[cultcache(key = 4294967296)] a: String }",
|
||||
"struct S { #[cultcache(key = 0x10000)] a: String }",
|
||||
] {
|
||||
let message = slots_error(source);
|
||||
assert!(message.contains("outside 0..=65535"), "{source}: {message}");
|
||||
}
|
||||
}
|
||||
|
||||
fn slots_error_free(source: &str) {
|
||||
let input: DeriveInput = syn::parse_str(source).expect("the fixture parses");
|
||||
named_slots(input.data, &input.ident, "CultSlots").expect("the fixture is accepted");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,3 +1,138 @@
|
|||
//! The derives refuse a malformed union at compile time. Each block below is a valid
|
||||
//! union with one property changed; keys are never 0, so a refusal cannot be a default
|
||||
//! key colliding with a declared 0. The derive crate's unit tests assert the message of
|
||||
//! every refusal the derive itself makes; a `compile_fail` block shows only that it fails.
|
||||
//!
|
||||
//! ```
|
||||
//! use cultcache_rs::{CultSlots, CultUnion};
|
||||
//! #[derive(CultSlots)]
|
||||
//! struct Arm { #[cultcache(key = 3)] id: String }
|
||||
//! #[derive(CultUnion)]
|
||||
//! enum Fine { #[cultcache(key = -1)] A(Arm), #[cultcache(key = 2147483647)] B, #[cultcache(key = 4)] C }
|
||||
//! ```
|
||||
//!
|
||||
//! A variant without a key, first and last:
|
||||
//!
|
||||
//! ```compile_fail
|
||||
//! use cultcache_rs::{CultSlots, CultUnion};
|
||||
//! #[derive(CultSlots)]
|
||||
//! struct Arm { #[cultcache(key = 3)] id: String }
|
||||
//! #[derive(CultUnion)]
|
||||
//! enum Bad { #[cultcache(key = 4)] A(Arm), B }
|
||||
//! ```
|
||||
//!
|
||||
//! ```compile_fail
|
||||
//! use cultcache_rs::{CultSlots, CultUnion};
|
||||
//! #[derive(CultSlots)]
|
||||
//! struct Arm { #[cultcache(key = 3)] id: String }
|
||||
//! #[derive(CultUnion)]
|
||||
//! enum Bad { B, #[cultcache(key = 4)] A(Arm) }
|
||||
//! ```
|
||||
//!
|
||||
//! Two variants with one key:
|
||||
//!
|
||||
//! ```compile_fail
|
||||
//! use cultcache_rs::{CultSlots, CultUnion};
|
||||
//! #[derive(CultSlots)]
|
||||
//! struct Arm { #[cultcache(key = 3)] id: String }
|
||||
//! #[derive(CultUnion)]
|
||||
//! enum Bad { #[cultcache(key = 4)] A(Arm), #[cultcache(key = 4)] B }
|
||||
//! ```
|
||||
//!
|
||||
//! A key attribute given twice:
|
||||
//!
|
||||
//! ```compile_fail
|
||||
//! use cultcache_rs::CultUnion;
|
||||
//! #[derive(CultUnion)]
|
||||
//! enum Bad { #[cultcache(key = 4)] #[cultcache(key = 5)] A }
|
||||
//! ```
|
||||
//!
|
||||
//! A key outside Int32:
|
||||
//!
|
||||
//! ```compile_fail
|
||||
//! use cultcache_rs::CultUnion;
|
||||
//! #[derive(CultUnion)]
|
||||
//! enum Bad { #[cultcache(key = 2147483648)] A }
|
||||
//! ```
|
||||
//!
|
||||
//! A struct variant:
|
||||
//!
|
||||
//! ```compile_fail
|
||||
//! use cultcache_rs::CultUnion;
|
||||
//! #[derive(CultUnion)]
|
||||
//! enum Bad { #[cultcache(key = 4)] A { id: String }, #[cultcache(key = 5)] B }
|
||||
//! ```
|
||||
//!
|
||||
//! A multi-field tuple variant:
|
||||
//!
|
||||
//! ```compile_fail
|
||||
//! use cultcache_rs::{CultSlots, CultUnion};
|
||||
//! #[derive(CultSlots)]
|
||||
//! struct Arm { #[cultcache(key = 3)] id: String }
|
||||
//! #[derive(CultUnion)]
|
||||
//! enum Bad { #[cultcache(key = 4)] A(Arm, Arm), #[cultcache(key = 5)] B }
|
||||
//! ```
|
||||
//!
|
||||
//! A generic enum:
|
||||
//!
|
||||
//! ```compile_fail
|
||||
//! use cultcache_rs::{CultSlots, CultUnion};
|
||||
//! #[derive(CultSlots)]
|
||||
//! struct Arm { #[cultcache(key = 3)] id: String }
|
||||
//! #[derive(CultUnion)]
|
||||
//! enum Bad<T> { #[cultcache(key = 4)] A(Arm), #[cultcache(key = 5)] B(std::marker::PhantomData<T>) }
|
||||
//! ```
|
||||
//!
|
||||
//! An arm that is not a slots record (rustc's `SlotRecord` bound, not the derive, refuses it):
|
||||
//!
|
||||
//! ```compile_fail
|
||||
//! use cultcache_rs::CultUnion;
|
||||
//! #[derive(CultUnion)]
|
||||
//! enum Bad { #[cultcache(key = 4)] A(String) }
|
||||
//! ```
|
||||
//!
|
||||
//! ```compile_fail
|
||||
//! use cultcache_rs::{CultSlots, CultUnion};
|
||||
//! #[derive(CultSlots)]
|
||||
//! struct Arm { #[cultcache(key = 3)] id: String }
|
||||
//! #[derive(CultUnion)]
|
||||
//! enum Bad { #[cultcache(key = 4)] A(Option<Arm>) }
|
||||
//! ```
|
||||
//!
|
||||
//! A hand-written `SlotRecord` impl, which only the derives provide:
|
||||
//!
|
||||
//! ```compile_fail,E0046
|
||||
//! use cultcache_rs::SlotRecord;
|
||||
//! struct Sneaky(String);
|
||||
//! impl SlotRecord for Sneaky {}
|
||||
//! ```
|
||||
//!
|
||||
//! A CultSlots field without a key, a repeated slot, a repeated key attribute, and a generic struct:
|
||||
//!
|
||||
//! ```compile_fail
|
||||
//! use cultcache_rs::CultSlots;
|
||||
//! #[derive(CultSlots)]
|
||||
//! struct Arm { #[cultcache(key = 3)] id: String, name: String }
|
||||
//! ```
|
||||
//!
|
||||
//! ```compile_fail
|
||||
//! use cultcache_rs::CultSlots;
|
||||
//! #[derive(CultSlots)]
|
||||
//! struct Arm { #[cultcache(key = 3)] id: String, #[cultcache(key = 3)] name: String }
|
||||
//! ```
|
||||
//!
|
||||
//! ```compile_fail
|
||||
//! use cultcache_rs::CultSlots;
|
||||
//! #[derive(CultSlots)]
|
||||
//! struct Arm { #[cultcache(key = 3)] #[cultcache(key = 4)] id: String }
|
||||
//! ```
|
||||
//!
|
||||
//! ```compile_fail
|
||||
//! use cultcache_rs::CultSlots;
|
||||
//! #[derive(CultSlots)]
|
||||
//! struct Arm<T> { #[cultcache(key = 3)] id: T }
|
||||
//! ```
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::anyhow;
|
||||
|
|
@ -20,6 +155,8 @@ use redb::{Database, ReadableDatabase, ReadableTable, TableDefinition};
|
|||
|
||||
extern crate self as cultcache_rs;
|
||||
|
||||
pub use cultcache_rs_derive::CultSlots;
|
||||
pub use cultcache_rs_derive::CultUnion;
|
||||
pub use cultcache_rs_derive::DatabaseEntry;
|
||||
|
||||
pub trait DatabaseEntry: Serialize + DeserializeOwned + Clone + Send + 'static {
|
||||
|
|
@ -27,6 +164,19 @@ pub trait DatabaseEntry: Serialize + DeserializeOwned + Clone + Send + 'static {
|
|||
const SCHEMA_NAME: &'static str = "DatabaseEntry";
|
||||
}
|
||||
|
||||
/// A type written as a positional slots array: what the `CultSlots` and `DatabaseEntry`
|
||||
/// derives implement, and what a `CultUnion` arm must carry.
|
||||
#[diagnostic::on_unimplemented(
|
||||
message = "`{Self}` is not a slots record",
|
||||
label = "a CultUnion arm is a newtype over a #[derive(CultSlots)] struct",
|
||||
note = "a String, an Option or any other type is not written as an array of slots"
|
||||
)]
|
||||
pub trait SlotRecord {
|
||||
/// Implemented only by the derives, which write the positional array the contract names.
|
||||
#[doc(hidden)]
|
||||
fn __slots_array();
|
||||
}
|
||||
|
||||
pub trait CultCacheRegistry {
|
||||
fn register_entries(&self, cache: &mut CultCache) -> Result<()>;
|
||||
}
|
||||
|
|
@ -351,6 +501,124 @@ fn describe_undecodable(error: &anyhow::Error) -> String {
|
|||
parts.join(": ")
|
||||
}
|
||||
|
||||
/// The deepest a document payload may nest, on read and on write, in every CultCache runtime: every
|
||||
/// MessagePack array and map counts, read by a deserializer or skipped past it, and the outermost
|
||||
/// array is depth 1. A payload of this depth is accepted and one container deeper is refused. It is
|
||||
/// the C# reference's `CultMessagePackSecurity.MaximumPayloadDepth`.
|
||||
pub const MAX_PAYLOAD_DEPTH: usize = 256;
|
||||
|
||||
/// A payload nests more containers than [`MAX_PAYLOAD_DEPTH`]. It names the depth reached and the
|
||||
/// limit, never payload bytes, and can be recovered from the `anyhow::Error` a read or write returns.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct PayloadTooDeep {
|
||||
pub depth: usize,
|
||||
pub limit: usize,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for PayloadTooDeep {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(
|
||||
formatter,
|
||||
"payload nests {} MessagePack containers deep; the limit is {}",
|
||||
self.depth, self.limit
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for PayloadTooDeep {}
|
||||
|
||||
/// Walks the MessagePack headers of one payload without recursion, counting every array and map and
|
||||
/// refusing the first container past [`MAX_PAYLOAD_DEPTH`]. Scalars are skipped by length and nothing
|
||||
/// is allocated per element. A payload that ends early is the decoder's to refuse.
|
||||
pub fn check_payload_depth(bytes: &[u8]) -> std::result::Result<(), PayloadTooDeep> {
|
||||
let mut remaining = [0usize; MAX_PAYLOAD_DEPTH];
|
||||
let mut depth = 0usize;
|
||||
let mut position = 0usize;
|
||||
while position < bytes.len() {
|
||||
let Some((advance, children)) = element_header(bytes, position) else {
|
||||
return Ok(());
|
||||
};
|
||||
position = position.saturating_add(advance);
|
||||
if let Some(children) = children {
|
||||
if depth == MAX_PAYLOAD_DEPTH {
|
||||
return Err(PayloadTooDeep { depth: MAX_PAYLOAD_DEPTH + 1, limit: MAX_PAYLOAD_DEPTH });
|
||||
}
|
||||
if children > 0 {
|
||||
remaining[depth] = children;
|
||||
depth += 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
// One element is complete; close every container it was the last element of.
|
||||
while depth > 0 {
|
||||
remaining[depth - 1] -= 1;
|
||||
if remaining[depth - 1] != 0 {
|
||||
break;
|
||||
}
|
||||
depth -= 1;
|
||||
}
|
||||
if depth == 0 {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The element at `position`: how many bytes to advance past it (its whole length for a scalar, its
|
||||
/// header for a container) and, for a container, how many child elements follow. `None` when the
|
||||
/// payload ends inside the header.
|
||||
fn element_header(bytes: &[u8], position: usize) -> Option<(usize, Option<usize>)> {
|
||||
// The big-endian length after the code byte.
|
||||
let length = |width: usize| -> Option<usize> {
|
||||
let field = bytes.get(position + 1..position + 1 + width)?;
|
||||
Some(field.iter().fold(0usize, |length, byte| (length << 8) | usize::from(*byte)))
|
||||
};
|
||||
let code = bytes[position];
|
||||
Some(match code {
|
||||
0x00..=0x7f | 0xe0..=0xff | 0xc0..=0xc3 => (1, None),
|
||||
0x80..=0x8f => (1, Some(2 * usize::from(code & 0x0f))),
|
||||
0x90..=0x9f => (1, Some(usize::from(code & 0x0f))),
|
||||
0xa0..=0xbf => (1 + usize::from(code & 0x1f), None),
|
||||
0xc4 | 0xd9 => (2usize.saturating_add(length(1)?), None),
|
||||
0xc5 | 0xda => (3usize.saturating_add(length(2)?), None),
|
||||
0xc6 | 0xdb => (5usize.saturating_add(length(4)?), None),
|
||||
0xc7 => (3usize.saturating_add(length(1)?), None),
|
||||
0xc8 => (4usize.saturating_add(length(2)?), None),
|
||||
0xc9 => (6usize.saturating_add(length(4)?), None),
|
||||
0xca | 0xce | 0xd2 => (5, None),
|
||||
0xcb | 0xcf | 0xd3 => (9, None),
|
||||
0xcc | 0xd0 => (2, None),
|
||||
0xcd | 0xd1 | 0xd4 => (3, None),
|
||||
0xd5 => (4, None),
|
||||
0xd6 => (6, None),
|
||||
0xd7 => (10, None),
|
||||
0xd8 => (18, None),
|
||||
0xdc => (3, Some(length(2)?)),
|
||||
0xdd => (5, Some(length(4)?)),
|
||||
0xde => (3, Some(length(2)?.saturating_mul(2))),
|
||||
0xdf => (5, Some(length(4)?.saturating_mul(2))),
|
||||
})
|
||||
}
|
||||
|
||||
/// The one decode of a document payload: the nesting bound first, then the deserializer, whose own
|
||||
/// depth counter (1024) is only a backstop. A failure keeps its kind and never quotes the bytes.
|
||||
/// Readers of stored envelope payloads outside this crate decode through it too.
|
||||
pub fn decode_payload<T: serde::de::DeserializeOwned>(payload: &[u8]) -> Result<T> {
|
||||
check_payload_depth(payload)?;
|
||||
rmp_serde::from_slice(payload).map_err(opaque_decode_error)
|
||||
}
|
||||
|
||||
/// The nesting bound for an envelope admitted without a typed decode, from the same walk that
|
||||
/// [`decode_payload`] runs first. Names the entry's type and key, never the payload.
|
||||
fn require_payload_depth(entry: &CultCacheEnvelope) -> Result<()> {
|
||||
check_payload_depth(&entry.payload).with_context(|| {
|
||||
format!(
|
||||
"refused CultCache envelope {:?} at key {:?}",
|
||||
entry.r#type, entry.key
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// A decoder failure as an error that keeps only its kind. Every decode of stored bytes
|
||||
/// goes through this or [`describe_undecodable`], so no error text quotes a stored value.
|
||||
fn opaque_decode_error(error: rmp_serde::decode::Error) -> anyhow::Error {
|
||||
|
|
@ -2390,7 +2658,7 @@ impl CultCache {
|
|||
let Some(entry) = self.entries.get(&entry_id_parts(T::TYPE, key)) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let payload = rmp_serde::from_slice(&entry.payload).map_err(opaque_decode_error).with_context(|| {
|
||||
let payload = decode_payload(&entry.payload).with_context(|| {
|
||||
format!(
|
||||
"failed to decode CultCache entry {:?} at key {:?} as {}",
|
||||
T::TYPE,
|
||||
|
|
@ -2423,7 +2691,7 @@ impl CultCache {
|
|||
if entry.r#type != T::TYPE {
|
||||
continue;
|
||||
}
|
||||
values.push(rmp_serde::from_slice(&entry.payload).map_err(opaque_decode_error).with_context(|| {
|
||||
values.push(decode_payload(&entry.payload).with_context(|| {
|
||||
format!(
|
||||
"failed to decode CultCache entry {:?} at key {:?} as {}",
|
||||
T::TYPE,
|
||||
|
|
@ -2444,7 +2712,7 @@ impl CultCache {
|
|||
}
|
||||
values.push((
|
||||
entry.key.clone(),
|
||||
rmp_serde::from_slice(&entry.payload).map_err(opaque_decode_error).with_context(|| {
|
||||
decode_payload(&entry.payload).with_context(|| {
|
||||
format!(
|
||||
"failed to decode CultCache entry {:?} at key {:?} as {}",
|
||||
T::TYPE,
|
||||
|
|
@ -2526,7 +2794,7 @@ impl CultCache {
|
|||
key: String,
|
||||
payload: Vec<u8>,
|
||||
) -> Result<(CultCacheEnvelope, T)> {
|
||||
let parsed: T = rmp_serde::from_slice(&payload).map_err(opaque_decode_error).with_context(|| {
|
||||
let parsed: T = decode_payload(&payload).with_context(|| {
|
||||
format!(
|
||||
"failed to validate CultCache entry {:?} at key {:?} as {}",
|
||||
T::TYPE,
|
||||
|
|
@ -2569,6 +2837,7 @@ impl CultCache {
|
|||
entry.r#type
|
||||
));
|
||||
}
|
||||
require_payload_depth(entry)?;
|
||||
let Some(home) = self.home_index(&entry.r#type)? else {
|
||||
continue;
|
||||
};
|
||||
|
|
@ -2613,7 +2882,7 @@ impl CultCache {
|
|||
/// claiming compile-time knowledge of its payload schema. This is the
|
||||
/// CultMesh/schema-registry boundary: callers own payload validation before
|
||||
/// admission; CultCache still enforces registered type, identity, timestamp,
|
||||
/// routing, and persistence.
|
||||
/// the payload nesting bound ([`MAX_PAYLOAD_DEPTH`]), routing, and persistence.
|
||||
pub fn put_raw_envelope(&mut self, entry: CultCacheEnvelope) -> Result<()> {
|
||||
if !self.definitions.contains_key(&entry.r#type) {
|
||||
return Err(anyhow!(
|
||||
|
|
@ -2633,6 +2902,7 @@ impl CultCache {
|
|||
entry.r#type
|
||||
));
|
||||
}
|
||||
require_payload_depth(&entry)?;
|
||||
if let Some(home) = self.home_index(&entry.r#type)? {
|
||||
self.stores[home].store.push(&entry)?;
|
||||
}
|
||||
|
|
@ -2662,7 +2932,7 @@ impl CultCache {
|
|||
));
|
||||
}
|
||||
|
||||
rmp_serde::from_slice(&entry.payload).map_err(opaque_decode_error).with_context(|| {
|
||||
decode_payload(&entry.payload).with_context(|| {
|
||||
format!(
|
||||
"failed to validate CultCache envelope {:?} at key {:?} as {}",
|
||||
T::TYPE,
|
||||
|
|
|
|||
945
packages/cultcache-rs/tests/union_parity.rs
Normal file
945
packages/cultcache-rs/tests/union_parity.rs
Normal file
|
|
@ -0,0 +1,945 @@
|
|||
//! The Rust runtime held to tests/vectors/union-parity, written by the C# reference.
|
||||
//! Bytes and outcomes are read from the committed files; only the constructed value is spelled here.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use cultcache_rs::CultCache;
|
||||
use cultcache_rs::CacheBackingStore;
|
||||
use cultcache_rs::CultCacheEnvelope;
|
||||
use cultcache_rs::MAX_PAYLOAD_DEPTH;
|
||||
use cultcache_rs::PayloadTooDeep;
|
||||
use cultcache_rs::check_payload_depth;
|
||||
use cultcache_rs::CultSlots;
|
||||
use cultcache_rs::CultUnion;
|
||||
use cultcache_rs::DatabaseEntry;
|
||||
use cultcache_rs::SingleFileMessagePackBackingStore;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
||||
enum Node {
|
||||
#[cultcache(key = 0)]
|
||||
Box(BoxArm),
|
||||
#[cultcache(key = 1)]
|
||||
Text(TextArm),
|
||||
#[cultcache(key = 2)]
|
||||
Use(UseArm),
|
||||
#[cultcache(key = 5)]
|
||||
Image(ImageArm),
|
||||
#[cultcache(key = 6)]
|
||||
Wrap(WrapArm),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
||||
struct WrapArm {
|
||||
#[cultcache(key = 0)]
|
||||
inner: Option<std::boxed::Box<Node>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
||||
struct BoxArm {
|
||||
#[cultcache(key = 0)]
|
||||
id: String,
|
||||
#[cultcache(key = 1)]
|
||||
children: Vec<Node>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
||||
struct TextArm {
|
||||
#[cultcache(key = 0)]
|
||||
id: String,
|
||||
#[cultcache(key = 1)]
|
||||
content: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
||||
struct UseArm {
|
||||
#[cultcache(key = 0)]
|
||||
id: String,
|
||||
#[cultcache(key = 1)]
|
||||
composition: Composition,
|
||||
#[cultcache(key = 2)]
|
||||
slots: Vec<Option<Node>>,
|
||||
}
|
||||
|
||||
// Slot 2 is retired: a gap written nil.
|
||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
||||
struct ImageArm {
|
||||
#[cultcache(key = 0)]
|
||||
id: String,
|
||||
#[cultcache(key = 1)]
|
||||
uri: String,
|
||||
#[cultcache(key = 3)]
|
||||
alt: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
||||
struct Composition {
|
||||
#[cultcache(key = 0)]
|
||||
name: String,
|
||||
#[cultcache(key = 1)]
|
||||
body: Option<std::boxed::Box<Node>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
||||
enum Outcome {
|
||||
#[cultcache(key = 0)]
|
||||
Pending(PendingArm),
|
||||
#[cultcache(key = 1)]
|
||||
Completed(CompletedArm),
|
||||
#[cultcache(key = 2)]
|
||||
Denied,
|
||||
#[cultcache(key = -2147483648)]
|
||||
Floor,
|
||||
#[cultcache(key = 2147483647)]
|
||||
Ceiling,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
||||
struct PendingArm {
|
||||
#[cultcache(key = 0)]
|
||||
message: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
||||
struct CompletedArm {
|
||||
#[cultcache(key = 0)]
|
||||
source_version: i32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
||||
struct NamedArm {
|
||||
#[cultcache(key = 0)]
|
||||
name: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
||||
struct UsesArm {
|
||||
#[cultcache(key = 0)]
|
||||
name: String,
|
||||
#[cultcache(key = 1)]
|
||||
uses: i32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
||||
struct CountArm {
|
||||
#[cultcache(key = 0)]
|
||||
name: String,
|
||||
#[cultcache(key = 1)]
|
||||
count: i32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
||||
enum Item {
|
||||
#[cultcache(key = 0)]
|
||||
Gem(NamedArm),
|
||||
#[cultcache(key = 1)]
|
||||
Tool(UsesArm),
|
||||
#[cultcache(key = 2)]
|
||||
Part(CountArm),
|
||||
}
|
||||
|
||||
// The same arms as Item under its own keys: key 2 is unknown to it.
|
||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
||||
enum CraftedItem {
|
||||
#[cultcache(key = 0)]
|
||||
Tool(UsesArm),
|
||||
#[cultcache(key = 1)]
|
||||
Part(CountArm),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
|
||||
#[cultcache(type = "tests.union_surface", schema = "tests.union_surface.v1")]
|
||||
struct UnionSurface {
|
||||
#[cultcache(key = 0)]
|
||||
id: String,
|
||||
#[cultcache(key = 1)]
|
||||
version: i32,
|
||||
#[cultcache(key = 2)]
|
||||
root: Option<Node>,
|
||||
#[cultcache(key = 3)]
|
||||
outcomes: Vec<Outcome>,
|
||||
#[cultcache(key = 4)]
|
||||
part: Option<Item>,
|
||||
#[cultcache(key = 5)]
|
||||
crafted: Option<CraftedItem>,
|
||||
#[cultcache(key = 6)]
|
||||
missing: Option<Node>,
|
||||
}
|
||||
|
||||
fn text(id: &str, content: &str) -> Node {
|
||||
Node::Text(TextArm { id: id.into(), content: content.into() })
|
||||
}
|
||||
|
||||
fn image(id: &str, uri: &str, alt: &str) -> Node {
|
||||
Node::Image(ImageArm { id: id.into(), uri: uri.into(), alt: alt.into() })
|
||||
}
|
||||
|
||||
fn boxed(id: &str, children: Vec<Node>) -> Node {
|
||||
Node::Box(BoxArm { id: id.into(), children })
|
||||
}
|
||||
|
||||
fn constructed() -> UnionSurface {
|
||||
let inner = boxed("inner", vec![text("deep", "x"), image("img", "uri://a", "alt")]);
|
||||
UnionSurface {
|
||||
id: "surface".into(),
|
||||
version: 3,
|
||||
root: Some(boxed(
|
||||
"root",
|
||||
vec![
|
||||
text("t1", "hello"),
|
||||
Node::Use(UseArm {
|
||||
id: "u1".into(),
|
||||
composition: Composition { name: "comp".into(), body: Some(std::boxed::Box::new(inner)) },
|
||||
slots: vec![Some(text("s1", "slot")), None, Some(boxed("b2", vec![]))],
|
||||
}),
|
||||
image("i2", "uri://b", ""),
|
||||
],
|
||||
)),
|
||||
outcomes: vec![
|
||||
Outcome::Pending(PendingArm { message: "wait".into() }),
|
||||
Outcome::Completed(CompletedArm { source_version: 7 }),
|
||||
Outcome::Denied,
|
||||
],
|
||||
part: Some(Item::Tool(UsesArm { name: "hammer".into(), uses: 12 })),
|
||||
crafted: Some(CraftedItem::Part(CountArm { name: "gear".into(), count: 4 })),
|
||||
missing: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn vector(name: &str) -> Vec<u8> {
|
||||
let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../../tests/vectors/union-parity")
|
||||
.join(name);
|
||||
std::fs::read(&path).unwrap_or_else(|error| panic!("{}: {error}", path.display()))
|
||||
}
|
||||
|
||||
fn decode(bytes: &[u8]) -> Result<UnionSurface, String> {
|
||||
rmp_serde::from_slice(bytes).map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn union_surface_decodes_and_reencodes() {
|
||||
let payload = vector("union-surface.msgpack");
|
||||
let value = constructed();
|
||||
assert_eq!(decode(&payload).unwrap(), value);
|
||||
assert_eq!(rmp_serde::to_vec(&value).unwrap(), payload);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_unit_arm_is_a_key_and_an_empty_slots_array() {
|
||||
assert_eq!(rmp_serde::to_vec(&Outcome::Denied).unwrap(), [0x92, 0x02, 0x90]);
|
||||
assert_eq!(rmp_serde::from_slice::<Outcome>(&[0x92, 0x02, 0x90]).unwrap(), Outcome::Denied);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn union_refusal_vectors() {
|
||||
let outcomes: Vec<(String, String, String, Option<u64>, String)> =
|
||||
rmp_serde::from_slice(&vector("outcomes.msgpack")).unwrap();
|
||||
let (mut refused, mut read_only) = (0, 0);
|
||||
for (file, outcome, union, key, detail) in outcomes {
|
||||
let result = decode(&vector(&file));
|
||||
match outcome.as_str() {
|
||||
"refused" => {
|
||||
refused += 1;
|
||||
let message = result.expect_err(&file);
|
||||
assert!(message.contains(&union), "{file}: {message}");
|
||||
if detail == "unknown-arm" {
|
||||
let key = key.expect(&file);
|
||||
assert!(message.contains(&format!("unknown arm key {key} ")), "{file}: {message}");
|
||||
}
|
||||
for canary in ["root", "hello", "uri://", "surface"] {
|
||||
assert!(!message.contains(canary), "{file} echoed a value: {message}");
|
||||
}
|
||||
}
|
||||
"read-only" => {
|
||||
read_only += 1;
|
||||
assert_eq!(result.expect(&file), constructed(), "{file}");
|
||||
}
|
||||
other => panic!("{file}: unknown outcome {other}"),
|
||||
}
|
||||
}
|
||||
assert_eq!((refused, read_only), (5, 4));
|
||||
}
|
||||
|
||||
// A nil where the arm's slots belong is not an empty record, for an arm with slots and a unit arm.
|
||||
#[test]
|
||||
fn nil_slots_are_refused_naming_the_union_and_the_key() {
|
||||
for (bytes, key) in [(vec![0x92, 0x01, 0xc0], "1"), (vec![0x92, 0x02, 0xc0], "2")] {
|
||||
let message = rmp_serde::from_slice::<Outcome>(&bytes).unwrap_err().to_string();
|
||||
assert!(message.contains("Outcome") && message.contains(&format!("arm {key} has nil slots")), "{message}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_arm_lists_the_declared_keys_and_never_echoes_the_payload() {
|
||||
// Shaped like a real arm, an array of strings, under an undeclared key.
|
||||
let bytes = rmp_serde::to_vec(&(99u64, ("CANARY-7f3a", "CANARY-91bc"))).unwrap();
|
||||
let message = rmp_serde::from_slice::<Node>(&bytes).unwrap_err().to_string();
|
||||
assert!(message.contains("Node") && message.contains("99") && message.contains("0, 1, 2, 5"), "{message}");
|
||||
assert!(!message.contains("CANARY"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_union_that_is_not_a_key_and_slots_pair_is_refused_naming_the_enum() {
|
||||
let cases: [(&str, Vec<u8>); 4] = [
|
||||
("an empty array", vec![0x90]),
|
||||
("a trailing element", rmp_serde::to_vec(&(1u64, (7u8,), 0u8)).unwrap()),
|
||||
("a string key", rmp_serde::to_vec(&("CANARY-key", (7u8,))).unwrap()),
|
||||
("a unit arm with slots", rmp_serde::to_vec(&(2u64, ("CANARY-slot",))).unwrap()),
|
||||
];
|
||||
for (label, bytes) in cases {
|
||||
let message = rmp_serde::from_slice::<Outcome>(&bytes).unwrap_err().to_string();
|
||||
assert!(message.contains("Outcome"), "{label}: {message}");
|
||||
assert!(!message.contains("CANARY"), "{label}: {message}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_key_decides_the_arm() {
|
||||
// Tool and Part carry different slots under different keys in the two unions.
|
||||
let bytes = rmp_serde::to_vec(&(1u64, ("hammer", 3u8))).unwrap();
|
||||
assert_eq!(
|
||||
rmp_serde::from_slice::<Item>(&bytes).unwrap(),
|
||||
Item::Tool(UsesArm { name: "hammer".into(), uses: 3 })
|
||||
);
|
||||
assert_eq!(
|
||||
rmp_serde::from_slice::<CraftedItem>(&bytes).unwrap(),
|
||||
CraftedItem::Part(CountArm { name: "hammer".into(), count: 3 })
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn union_store_reads() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let path = temp.path().join("union-surface.cc");
|
||||
std::fs::write(&path, vector("union-surface.cc")).unwrap();
|
||||
let mut cache = CultCache::new();
|
||||
cache.register_entry_type::<UnionSurface>().unwrap();
|
||||
cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&path)).unwrap();
|
||||
cache.pull_all_backing_stores().unwrap();
|
||||
assert_eq!(cache.get::<UnionSurface>("surface").unwrap(), Some(constructed()));
|
||||
}
|
||||
|
||||
// The arm key domain is the reference's Int32. Expected bytes are what MessagePack-CSharp writes
|
||||
// for the same keys (WriteInt32: fixneg, uint32, int32); the refusal classes are CultUnionGuard's.
|
||||
mod arm_keys {
|
||||
use cultcache_rs::CultSlots;
|
||||
use cultcache_rs::CultUnion;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
||||
struct Count {
|
||||
#[cultcache(key = 0)]
|
||||
name: String,
|
||||
#[cultcache(key = 1)]
|
||||
count: i32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
||||
enum Keyed {
|
||||
#[cultcache(key = -1)]
|
||||
Negative(Count),
|
||||
#[cultcache(key = 2147483647)]
|
||||
Max(Count),
|
||||
#[cultcache(key = -2147483648)]
|
||||
Min,
|
||||
#[cultcache(key = 7)]
|
||||
Plain(Count),
|
||||
}
|
||||
|
||||
fn count() -> Count {
|
||||
Count { name: "n".into(), count: 1 }
|
||||
}
|
||||
|
||||
fn message(bytes: &[u8]) -> String {
|
||||
rmp_serde::from_slice::<Keyed>(bytes).unwrap_err().to_string()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn negative_and_int32_max_keys_are_declared_and_round_trip() {
|
||||
let cases: [(Keyed, &[u8]); 4] = [
|
||||
(Keyed::Negative(count()), &[0x92, 0xff, 0x92, 0xa1, b'n', 0x01]),
|
||||
(Keyed::Max(count()), &[0x92, 0xce, 0x7f, 0xff, 0xff, 0xff, 0x92, 0xa1, b'n', 0x01]),
|
||||
(Keyed::Min, &[0x92, 0xd2, 0x80, 0x00, 0x00, 0x00, 0x90]),
|
||||
(Keyed::Plain(count()), &[0x92, 0x07, 0x92, 0xa1, b'n', 0x01]),
|
||||
];
|
||||
for (value, bytes) in cases {
|
||||
assert_eq!(rmp_serde::to_vec(&value).unwrap(), bytes, "{value:?}");
|
||||
assert_eq!(rmp_serde::from_slice::<Keyed>(bytes).unwrap(), value);
|
||||
}
|
||||
}
|
||||
|
||||
// Every integer width of a negative key reads as the same arm.
|
||||
#[test]
|
||||
fn a_negative_key_reads_in_every_integer_width() {
|
||||
for key in [&[0xff][..], &[0xd0, 0xff], &[0xd1, 0xff, 0xff], &[0xd2, 0xff, 0xff, 0xff, 0xff], &[0xd3, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]] {
|
||||
let mut bytes = vec![0x92];
|
||||
bytes.extend_from_slice(key);
|
||||
bytes.extend_from_slice(&[0x92, 0xa1, b'n', 0x01]);
|
||||
assert_eq!(rmp_serde::from_slice::<Keyed>(&bytes).unwrap(), Keyed::Negative(count()), "{key:02x?}");
|
||||
}
|
||||
}
|
||||
|
||||
fn pair(key: &[u8]) -> Vec<u8> {
|
||||
let mut bytes = vec![0x92];
|
||||
bytes.extend_from_slice(key);
|
||||
bytes.extend_from_slice(&[0x92, 0xa1, b'C', 0xa1, b'A']);
|
||||
bytes
|
||||
}
|
||||
|
||||
// A negative key the union does not declare is an unknown arm naming the key, as in the reference.
|
||||
#[test]
|
||||
fn a_negative_undeclared_key_is_an_unknown_arm_naming_the_key() {
|
||||
for (key, shown) in [(&[0xe0][..], "-32"), (&[0xd0, 0xdf], "-33"), (&[0xd1, 0x80, 0x00], "-32768"), (&[0xd2, 0x80, 0x00, 0x00, 0x01], "-2147483647")] {
|
||||
let text = message(&pair(key));
|
||||
assert!(text.contains(&format!("unknown arm key {shown} ")), "{text}");
|
||||
assert!(text.contains("declared keys: -2147483648, -1, 7, 2147483647"), "{text}");
|
||||
assert!(!text.contains("CA"), "{text}");
|
||||
}
|
||||
}
|
||||
|
||||
// Outside Int32 is its own class, naming neither the value nor the payload.
|
||||
#[test]
|
||||
fn keys_outside_int32_are_their_own_class_and_never_echoed() {
|
||||
let wide: [&[u8]; 6] = [
|
||||
&[0xce, 0x80, 0x00, 0x00, 0x00],
|
||||
&[0xcf, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00],
|
||||
&[0xcf, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff],
|
||||
&[0xd3, 0xff, 0xff, 0xff, 0xff, 0x7f, 0xff, 0xff, 0xff],
|
||||
&[0xd3, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
|
||||
&[0xcf, 0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff],
|
||||
];
|
||||
for key in wide {
|
||||
let text = message(&pair(key));
|
||||
assert!(text.contains("an arm key outside Int32"), "{key:02x?}: {text}");
|
||||
assert!(text.contains("Keyed") && !text.contains("CA"), "{text}");
|
||||
for value in ["4294967296", "9223372036854775807", "9223372036854775808", "18446744073709551615"] {
|
||||
assert!(!text.contains(value), "{text}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_key_that_is_not_an_integer_is_its_own_class_and_never_echoed() {
|
||||
let keys: [&[u8]; 10] = [
|
||||
// A MessagePack ext: fixext 1, the timestamp extension and ext 8.
|
||||
&[0xd4, 0x01, 0x00],
|
||||
&[0xd6, 0xff, 0x00, 0x00, 0x00, 0x00],
|
||||
&[0xc7, 0x02, 0x05, b'C', b'A'],
|
||||
&[0xc0],
|
||||
&[0xc3],
|
||||
&[0xcb, 0x3f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
|
||||
&[0xa6, b'C', b'A', b'N', b'A', b'R', b'Y'],
|
||||
&[0xc4, 0x02, b'C', b'A'],
|
||||
&[0x91, 0xa6, b'C', b'A', b'N', b'A', b'R', b'Y'],
|
||||
&[0x81, 0xa6, b'C', b'A', b'N', b'A', b'R', b'Y', 0x01],
|
||||
];
|
||||
for key in keys {
|
||||
let text = message(&pair(key));
|
||||
assert!(text.contains("a non-integer arm key") && text.contains("Keyed"), "{key:02x?}: {text}");
|
||||
assert!(!text.contains("CANARY") && !text.contains("CA"), "{text}");
|
||||
}
|
||||
}
|
||||
|
||||
// Anything that is not a two-element array is the arity class, whatever its first element is.
|
||||
#[test]
|
||||
fn a_pair_of_the_wrong_length_is_refused_before_its_key_is_read() {
|
||||
for bytes in [&[0x91, 0xa1, b'x'][..], &[0x93, 0x07, 0x90, 0x00], &[0x90]] {
|
||||
let text = message(bytes);
|
||||
assert!(text.contains("is not a [key, slots] pair"), "{bytes:02x?}: {text}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
mod serde_enum_bytes {
|
||||
use cultcache_rs::DatabaseEntry;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
enum External {
|
||||
Unit,
|
||||
Newtype(u32),
|
||||
Struct { n: u8 },
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(tag = "kind")]
|
||||
enum Internal {
|
||||
A { n: u8 },
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
|
||||
#[cultcache(type = "tests.plain_enums")]
|
||||
struct PlainEnums {
|
||||
#[cultcache(key = 0)]
|
||||
unit: External,
|
||||
#[cultcache(key = 1)]
|
||||
newtype: External,
|
||||
#[cultcache(key = 2)]
|
||||
structured: External,
|
||||
#[cultcache(key = 3)]
|
||||
tagged: Internal,
|
||||
}
|
||||
|
||||
// Computed with the derive and serde at b0f40577, before CultUnion existed.
|
||||
const AT_BASE: &[u8] = &[
|
||||
0x94, 0xa4, b'U', b'n', b'i', b't', 0x81, 0xa7, b'N', b'e', b'w', b't', b'y', b'p', b'e', 0x05, 0x81,
|
||||
0xa6, b'S', b't', b'r', b'u', b'c', b't', 0x91, 0x01, 0x92, 0xa1, b'A', 0x01,
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn serde_enum_bytes_stable() {
|
||||
let value = PlainEnums {
|
||||
unit: External::Unit,
|
||||
newtype: External::Newtype(5),
|
||||
structured: External::Struct { n: 1 },
|
||||
tagged: Internal::A { n: 1 },
|
||||
};
|
||||
let bytes = rmp_serde::to_vec(&value).unwrap();
|
||||
assert_eq!(bytes, AT_BASE);
|
||||
assert_eq!(rmp_serde::from_slice::<PlainEnums>(AT_BASE).unwrap(), value);
|
||||
}
|
||||
}
|
||||
|
||||
// Names a derive's generated code must not capture: the generic parameters and the local items of the
|
||||
// expansion, used as user type names.
|
||||
mod generated_names {
|
||||
use cultcache_rs::CultSlots;
|
||||
use cultcache_rs::CultUnion;
|
||||
use cultcache_rs::DatabaseEntry;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
||||
struct D {
|
||||
#[cultcache(key = 0)]
|
||||
name: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
||||
struct S {
|
||||
#[cultcache(key = 0)]
|
||||
count: i32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
||||
struct ArmKey {
|
||||
#[cultcache(key = 0)]
|
||||
id: i32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
||||
enum A {
|
||||
#[cultcache(key = 1)]
|
||||
D(D),
|
||||
#[cultcache(key = 2)]
|
||||
S(S),
|
||||
#[cultcache(key = 3)]
|
||||
ArmKey(ArmKey),
|
||||
#[cultcache(key = 4)]
|
||||
E,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
||||
enum CultUnionVisitor {
|
||||
#[cultcache(key = 1)]
|
||||
A(ArmKey),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
|
||||
#[cultcache(type = "tests.names")]
|
||||
struct E {
|
||||
#[cultcache(key = 0)]
|
||||
union: A,
|
||||
#[cultcache(key = 1)]
|
||||
other: CultUnionVisitor,
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn types_named_like_generated_generics_and_locals_round_trip() {
|
||||
let value = E {
|
||||
union: A::D(D { name: "n".into() }),
|
||||
other: CultUnionVisitor::A(ArmKey { id: 9 }),
|
||||
};
|
||||
let bytes = rmp_serde::to_vec(&value).unwrap();
|
||||
assert_eq!(rmp_serde::from_slice::<E>(&bytes).unwrap(), value);
|
||||
for union in [A::S(S { count: 2 }), A::ArmKey(ArmKey { id: 3 }), A::E] {
|
||||
let bytes = rmp_serde::to_vec(&union).unwrap();
|
||||
assert_eq!(rmp_serde::from_slice::<A>(&bytes).unwrap(), union);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The reference's CultUnionGuard classes, from bounds-outcomes.msgpack; depth entries go through the
|
||||
// cache because the nesting rule lives in its one decode.
|
||||
const CANARY: &str = "CANARY-union-golden-4c2a";
|
||||
|
||||
fn envelope(key: &str, payload: &[u8]) -> CultCacheEnvelope {
|
||||
CultCacheEnvelope {
|
||||
key: key.into(),
|
||||
r#type: UnionSurface::TYPE.into(),
|
||||
payload: payload.to_vec(),
|
||||
stored_at: "2026-01-01T00:00:00Z".into(),
|
||||
schema_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
// A payload past the bound cannot be admitted through the cache, so a store file written behind its
|
||||
// back stands in for one a peer or an older runtime left.
|
||||
fn through_cache(payload: &[u8]) -> Result<UnionSurface, String> {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let path = temp.path().join("foreign.cc");
|
||||
SingleFileMessagePackBackingStore::new(&path).push(&envelope("k", payload)).unwrap();
|
||||
let mut cache = CultCache::new();
|
||||
cache.register_entry_type::<UnionSurface>().unwrap();
|
||||
cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&path)).unwrap();
|
||||
cache.pull_all_backing_stores().unwrap();
|
||||
match cache.get::<UnionSurface>("k") {
|
||||
Ok(value) => Ok(value.expect("the envelope was stored")),
|
||||
Err(error) => Err(format!("{error:#}")),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bounds_vectors() {
|
||||
let entries: Vec<serde_json::Value> = rmp_serde::from_slice(&vector("bounds-outcomes.msgpack")).unwrap();
|
||||
assert_eq!(entries[0], serde_json::json!(["limit", 256]));
|
||||
assert_eq!(MAX_PAYLOAD_DEPTH, 256);
|
||||
let (mut accepted, mut refused, mut read_only) = (0, 0, 0);
|
||||
for entry in &entries[1..] {
|
||||
let fields: Vec<&str> = entry.as_array().unwrap().iter().filter_map(|field| field.as_str()).collect();
|
||||
let (file, outcome, union, detail) = (fields[0], fields[1], fields[2], fields[3]);
|
||||
let bytes = vector(file);
|
||||
let result = if union == "UnionSurface" { through_cache(&bytes) } else { decode(&bytes) };
|
||||
match outcome {
|
||||
"accepted" => {
|
||||
accepted += 1;
|
||||
let value = result.unwrap_or_else(|message| panic!("{file}: {message}"));
|
||||
assert_eq!(rmp_serde::to_vec(&value).unwrap(), vector(detail), "{file}");
|
||||
match file {
|
||||
"arm-key-int32-min.msgpack" => assert_eq!(value.outcomes.last(), Some(&Outcome::Floor)),
|
||||
"arm-key-int32-max.msgpack" | "arm-key-wide-coding.msgpack" => {
|
||||
assert_eq!(value.outcomes.last(), Some(&Outcome::Ceiling))
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
"read-only" => {
|
||||
read_only += 1;
|
||||
assert_eq!(result.unwrap_or_else(|message| panic!("{file}: {message}")), constructed(), "{file}");
|
||||
}
|
||||
"refused" => {
|
||||
refused += 1;
|
||||
let message = result.expect_err(file);
|
||||
// The cache path names the entry type in its context; the union names itself.
|
||||
let names = if union == "UnionSurface" { UnionSurface::TYPE } else { union };
|
||||
assert!(message.contains(names), "{file}: {message}");
|
||||
let class = match detail {
|
||||
"key-out-of-range" => "outside Int32",
|
||||
"key-not-integer" => "non-integer",
|
||||
"nil-slots" => "arm 1 has nil slots",
|
||||
"depth" => "the limit is 256",
|
||||
other => panic!("{file}: unknown class {other}"),
|
||||
};
|
||||
assert!(message.contains(class), "{file}: {message}");
|
||||
assert!(!message.contains(CANARY), "{file} echoed a value: {message}");
|
||||
}
|
||||
other => panic!("{file}: unknown outcome {other}"),
|
||||
}
|
||||
}
|
||||
assert_eq!((accepted, refused, read_only), (4, 7, 1));
|
||||
}
|
||||
|
||||
fn wrap_chain(wraps: usize, leaf: Node) -> UnionSurface {
|
||||
let mut node = leaf;
|
||||
for _ in 0..wraps {
|
||||
node = Node::Wrap(WrapArm { inner: Some(std::boxed::Box::new(node)) });
|
||||
}
|
||||
UnionSurface { root: Some(node), ..constructed() }
|
||||
}
|
||||
|
||||
// Each Wrap adds a pair and a slots array; the surface array is depth 1, so a Box leaf (pair, slots,
|
||||
// children) ends at 2 * (wraps + 1) + 2 and a Text leaf at 2 * (wraps + 1) + 1.
|
||||
#[test]
|
||||
fn the_constructed_chains_write_the_vector_bytes() {
|
||||
let at_limit = wrap_chain(126, boxed("leaf", vec![]));
|
||||
assert_eq!(rmp_serde::to_vec(&at_limit).unwrap(), vector("depth-at-limit.msgpack"));
|
||||
let past_limit = wrap_chain(127, text("leaf", CANARY));
|
||||
assert_eq!(rmp_serde::to_vec(&past_limit).unwrap(), vector("depth-past-limit.msgpack"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_canary_is_in_the_committed_bytes() {
|
||||
let bytes = vector("depth-past-limit.msgpack");
|
||||
assert!(bytes.windows(CANARY.len()).any(|window| window == CANARY.as_bytes()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_refused_past_limit() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let path = temp.path().join("depth.cc");
|
||||
let mut cache = CultCache::new();
|
||||
cache.register_entry_type::<UnionSurface>().unwrap();
|
||||
cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&path)).unwrap();
|
||||
|
||||
let at_limit = wrap_chain(126, boxed("leaf", vec![]));
|
||||
assert_eq!(cache.put("at", &at_limit).unwrap(), at_limit);
|
||||
let stored = cache.snapshot_envelopes();
|
||||
assert_eq!(stored.len(), 1);
|
||||
assert_eq!(stored[0].payload, vector("depth-at-limit.msgpack"));
|
||||
let file_before = std::fs::read(&path).unwrap();
|
||||
|
||||
let error = cache.put("past", &wrap_chain(127, text("leaf", CANARY))).unwrap_err();
|
||||
assert_eq!(error.downcast_ref::<PayloadTooDeep>(), Some(&PayloadTooDeep { depth: 257, limit: 256 }));
|
||||
assert!(!format!("{error:#}").contains(CANARY), "{error:#}");
|
||||
assert_eq!(cache.get::<UnionSurface>("past").unwrap(), None);
|
||||
assert_eq!(cache.snapshot_envelopes(), stored);
|
||||
assert_eq!(std::fs::read(&path).unwrap(), file_before);
|
||||
}
|
||||
|
||||
// Every door an envelope enters the store by holds the one bound: the typed put above, and the raw
|
||||
// doors a peer's bytes arrive through. Three nestings: union arms and maps
|
||||
// written by the production encoder, and the arrays of the committed vector.
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
struct MapNest {
|
||||
inner: Option<std::boxed::Box<MapNest>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
|
||||
#[cultcache(type = "tests.map_doc", schema = "tests.map_doc.v1")]
|
||||
struct MapDoc {
|
||||
#[cultcache(key = 0)]
|
||||
root: Option<MapNest>,
|
||||
}
|
||||
|
||||
// The document array is depth 1 and each MapNest is one map.
|
||||
fn map_doc(maps: usize) -> MapDoc {
|
||||
let mut nest = MapNest { inner: None };
|
||||
for _ in 1..maps {
|
||||
nest = MapNest { inner: Some(std::boxed::Box::new(nest)) };
|
||||
}
|
||||
MapDoc { root: Some(nest) }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maps_count_one_level_each_on_every_write_door() {
|
||||
let at_limit = map_doc(MAX_PAYLOAD_DEPTH - 1);
|
||||
let past_limit = map_doc(MAX_PAYLOAD_DEPTH);
|
||||
let at_bytes = rmp_serde::to_vec_named(&at_limit).unwrap();
|
||||
let past_bytes = rmp_serde::to_vec_named(&past_limit).unwrap();
|
||||
assert_eq!(check_payload_depth(&at_bytes), Ok(()));
|
||||
assert_eq!(check_payload_depth(&past_bytes), Err(TOO_DEEP));
|
||||
|
||||
let mut cache = CultCache::new();
|
||||
cache.register_entry_type::<MapDoc>().unwrap();
|
||||
let (prepared, parsed) = cache.prepare_entry_named("at", &at_limit).unwrap();
|
||||
assert_eq!((prepared.payload.as_slice(), &parsed), (at_bytes.as_slice(), &at_limit));
|
||||
cache.put_prepared_batch(vec![prepared]).unwrap();
|
||||
assert_eq!(cache.get::<MapDoc>("at").unwrap(), Some(at_limit));
|
||||
let error = cache.prepare_entry_named("past", &past_limit).unwrap_err();
|
||||
assert_eq!(error.downcast_ref::<PayloadTooDeep>(), Some(&TOO_DEEP));
|
||||
}
|
||||
|
||||
fn raw(type_name: &str, key: &str, payload: Vec<u8>) -> CultCacheEnvelope {
|
||||
CultCacheEnvelope { r#type: type_name.into(), ..envelope(key, &payload) }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_raw_doors_hold_the_bound_for_arms_maps_and_arrays() {
|
||||
let arms_at = rmp_serde::to_vec(&wrap_chain(126, boxed("leaf", vec![]))).unwrap();
|
||||
let arms_past = rmp_serde::to_vec(&wrap_chain(127, text("leaf", CANARY))).unwrap();
|
||||
let maps_at = rmp_serde::to_vec_named(&map_doc(MAX_PAYLOAD_DEPTH - 1)).unwrap();
|
||||
let maps_past = rmp_serde::to_vec_named(&map_doc(MAX_PAYLOAD_DEPTH)).unwrap();
|
||||
let arrays_at = vector("depth-at-limit.msgpack");
|
||||
let arrays_past = vector("depth-past-limit.msgpack");
|
||||
let cases = [
|
||||
(UnionSurface::TYPE, "arms", arms_at, arms_past),
|
||||
(MapDoc::TYPE, "maps", maps_at, maps_past),
|
||||
(UnionSurface::TYPE, "arrays", arrays_at, arrays_past),
|
||||
];
|
||||
for (type_name, name, at, past) in cases {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let path = temp.path().join("doors.cc");
|
||||
let mut cache = CultCache::new();
|
||||
cache.register_entry_type::<UnionSurface>().unwrap();
|
||||
cache.register_entry_type::<MapDoc>().unwrap();
|
||||
cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&path)).unwrap();
|
||||
cache.put_raw_envelope(raw(type_name, "at-raw", at.clone())).unwrap();
|
||||
cache.put_prepared_batch(vec![raw(type_name, "at-batch", at.clone())]).unwrap();
|
||||
let stored = cache.snapshot_envelopes();
|
||||
let file_before = std::fs::read(&path).unwrap();
|
||||
|
||||
let refusals = [
|
||||
cache.put_raw_envelope(raw(type_name, "past-raw", past.clone())).unwrap_err(),
|
||||
// The valid entry staged beside it must not land either.
|
||||
cache
|
||||
.put_prepared_batch(vec![raw(type_name, "ok-staged", at.clone()), raw(type_name, "past-batch", past.clone())])
|
||||
.unwrap_err(),
|
||||
];
|
||||
for error in refusals {
|
||||
assert_eq!(error.downcast_ref::<PayloadTooDeep>(), Some(&TOO_DEEP), "{name}");
|
||||
let message = format!("{error:#}");
|
||||
assert!(message.contains(type_name) && !message.contains(CANARY), "{name}: {message}");
|
||||
}
|
||||
assert_eq!(cache.snapshot_envelopes(), stored, "{name}");
|
||||
assert_eq!(std::fs::read(&path).unwrap(), file_before, "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
// A debug build on a 2 MiB thread carries 405 containers of this document; the bound keeps every
|
||||
// accepted payload below that, and every refusal is an error, not an abort.
|
||||
#[test]
|
||||
fn stack_budget_debug_2mib() {
|
||||
std::thread::Builder::new()
|
||||
.stack_size(2 * 1024 * 1024)
|
||||
.spawn(|| {
|
||||
assert_eq!(
|
||||
through_cache(&vector("depth-at-limit.msgpack")).unwrap(),
|
||||
wrap_chain(126, boxed("leaf", vec![]))
|
||||
);
|
||||
let refused = through_cache(&vector("depth-past-limit.msgpack")).unwrap_err();
|
||||
assert!(refused.contains("the limit is 256"), "{refused}");
|
||||
let mut cache = CultCache::new();
|
||||
cache.register_entry_type::<UnionSurface>().unwrap();
|
||||
let value = wrap_chain(126, boxed("leaf", vec![]));
|
||||
assert_eq!(cache.put("at", &value).unwrap(), value);
|
||||
assert_eq!(cache.get::<UnionSurface>("at").unwrap(), Some(value));
|
||||
let mut deep = vec![0x91u8; 100_000];
|
||||
deep.push(0xc0);
|
||||
let refused = through_cache(&deep).unwrap_err();
|
||||
assert!(refused.contains("the limit is 256"), "{refused}");
|
||||
})
|
||||
.unwrap()
|
||||
.join()
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
// The walk is iterative: 100000 nested arrays are refused on a 256 KiB stack.
|
||||
#[test]
|
||||
fn the_walk_does_not_recurse() {
|
||||
std::thread::Builder::new()
|
||||
.stack_size(256 * 1024)
|
||||
.spawn(|| {
|
||||
let mut deep = vec![0x91u8; 100_000];
|
||||
deep.push(0xc0);
|
||||
assert_eq!(check_payload_depth(&deep), Err(PayloadTooDeep { depth: 257, limit: 256 }));
|
||||
})
|
||||
.unwrap()
|
||||
.join()
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
fn nested(open: &[u8], levels: usize, leaf: &[u8]) -> Vec<u8> {
|
||||
let mut bytes = open.repeat(levels);
|
||||
bytes.extend_from_slice(leaf);
|
||||
bytes
|
||||
}
|
||||
|
||||
const TOO_DEEP: PayloadTooDeep = PayloadTooDeep { depth: 257, limit: 256 };
|
||||
|
||||
// Every container header width counts one level, and the bound sits between 256 and 257 for each.
|
||||
#[test]
|
||||
fn every_container_header_counts_one_level() {
|
||||
let openers: [(&str, &[u8]); 6] = [
|
||||
("fixarray", &[0x91]),
|
||||
("array16", &[0xdc, 0x00, 0x01]),
|
||||
("array32", &[0xdd, 0x00, 0x00, 0x00, 0x01]),
|
||||
("fixmap", &[0x81, 0x01]),
|
||||
("map16", &[0xde, 0x00, 0x01, 0x01]),
|
||||
("map32", &[0xdf, 0x00, 0x00, 0x00, 0x01, 0x01]),
|
||||
];
|
||||
for (name, open) in openers {
|
||||
assert_eq!(check_payload_depth(&nested(open, 256, &[0xc0])), Ok(()), "{name} at the limit");
|
||||
assert_eq!(check_payload_depth(&nested(open, 257, &[0xc0])), Err(TOO_DEEP), "{name} past the limit");
|
||||
}
|
||||
// An empty container still counts the level it sits on.
|
||||
assert_eq!(check_payload_depth(&nested(&[0x91], 255, &[0x90])), Ok(()));
|
||||
assert_eq!(check_payload_depth(&nested(&[0x91], 256, &[0x90])), Err(TOO_DEEP));
|
||||
assert_eq!(check_payload_depth(&nested(&[0x91], 255, &[0x80])), Ok(()));
|
||||
assert_eq!(check_payload_depth(&nested(&[0x91], 256, &[0x80])), Err(TOO_DEEP));
|
||||
}
|
||||
|
||||
// Every scalar and container header is followed by the chain that tests the bound. The skipped bytes
|
||||
// are filled with the array marker, so a skip that stops short reads them as containers and a skip
|
||||
// that runs long eats the chain: either way the chain's depth stops reading as 256 and 257.
|
||||
#[test]
|
||||
fn every_element_is_skipped_by_its_length_and_counted_by_its_children() {
|
||||
const FILL: u8 = 0x91;
|
||||
let filled = |head: &[u8], bytes: usize| -> Vec<u8> { [head.to_vec(), vec![FILL; bytes]].concat() };
|
||||
let long = |code: u8, width: usize, length: usize, extra: usize| -> Vec<u8> {
|
||||
let size = length.to_be_bytes();
|
||||
filled(&[&[code][..], &size[size.len() - width..]].concat(), length + extra)
|
||||
};
|
||||
let mut elements: Vec<Vec<u8>> = vec![
|
||||
vec![0x00],
|
||||
vec![0xff],
|
||||
vec![0xc0],
|
||||
vec![0xc2],
|
||||
vec![0xc3],
|
||||
filled(&[0xcc], 1),
|
||||
filled(&[0xcd], 2),
|
||||
filled(&[0xce], 4),
|
||||
filled(&[0xcf], 8),
|
||||
filled(&[0xd0], 1),
|
||||
filled(&[0xd1], 2),
|
||||
filled(&[0xd2], 4),
|
||||
filled(&[0xd3], 8),
|
||||
filled(&[0xca], 4),
|
||||
filled(&[0xcb], 8),
|
||||
filled(&[0xa3], 3),
|
||||
filled(&[0xbf], 31),
|
||||
filled(&[0xd4], 2),
|
||||
filled(&[0xd5], 3),
|
||||
filled(&[0xd6], 5),
|
||||
filled(&[0xd7], 9),
|
||||
filled(&[0xd8], 17),
|
||||
];
|
||||
for (code, width) in [(0xd9, 1), (0xc4, 1), (0xda, 2), (0xc5, 2), (0xdb, 4), (0xc6, 4)] {
|
||||
for length in [3, 200, 256, 65536] {
|
||||
if length < (1usize << (8 * width)) {
|
||||
elements.push(long(code, width, length, 0));
|
||||
}
|
||||
}
|
||||
}
|
||||
// An ext carries a type byte after its length.
|
||||
for (code, width) in [(0xc7, 1), (0xc8, 2), (0xc9, 4)] {
|
||||
for length in [3, 200, 256, 65536] {
|
||||
if length < (1usize << (8 * width)) {
|
||||
elements.push(long(code, width, length, 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
// Containers whose children are scalars, so a wrong child count shifts everything after them.
|
||||
elements.push(vec![0x92, 0x00, 0x00]);
|
||||
elements.push(vec![0x93, 0x00, 0x00, 0x00]);
|
||||
elements.push(vec![0x82, 0x00, 0x00, 0x00, 0x00]);
|
||||
elements.push(vec![0x83, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
|
||||
elements.push([vec![0xdc, 0x01, 0x00], vec![0x00; 256]].concat());
|
||||
elements.push([vec![0xdd, 0x00, 0x00, 0x00, 0x03], vec![0x00; 3]].concat());
|
||||
elements.push([vec![0xde, 0x00, 0x03], vec![0x00; 6]].concat());
|
||||
elements.push([vec![0xde, 0x01, 0x00], vec![0x00; 512]].concat());
|
||||
elements.push([vec![0xdf, 0x00, 0x00, 0x00, 0x03], vec![0x00; 6]].concat());
|
||||
elements.push(vec![0xdc, 0x00, 0x00]);
|
||||
elements.push(vec![0xdf, 0x00, 0x00, 0x00, 0x00]);
|
||||
|
||||
let with_chain = |levels: usize| {
|
||||
let mut bytes = vec![0xdd];
|
||||
bytes.extend_from_slice(&u32::try_from(elements.len() + 1).unwrap().to_be_bytes());
|
||||
for element in &elements {
|
||||
bytes.extend_from_slice(element);
|
||||
}
|
||||
bytes.extend(nested(&[0x91], levels, &[0xc0]));
|
||||
bytes
|
||||
};
|
||||
assert_eq!(check_payload_depth(&with_chain(255)), Ok(()));
|
||||
assert_eq!(check_payload_depth(&with_chain(256)), Err(TOO_DEEP));
|
||||
}
|
||||
|
||||
// An ending cut short is the decoder's to refuse, never a panic or a depth error.
|
||||
#[test]
|
||||
fn a_payload_cut_short_is_not_a_depth_error() {
|
||||
for bytes in [&[0xdc, 0x00][..], &[0xdd, 0, 0], &[0xd9], &[0xc5, 0x00], &[0xde], &[0xdf, 0, 0, 0], &[0x91], &[]] {
|
||||
assert_eq!(check_payload_depth(bytes), Ok(()), "{bytes:02x?}");
|
||||
}
|
||||
assert_eq!(check_payload_depth(&[0xdb, 0xff, 0xff, 0xff, 0xff, b'a']), Ok(()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_refusal_names_depth_and_limit_only() {
|
||||
assert_eq!(TOO_DEEP.to_string(), "payload nests 257 MessagePack containers deep; the limit is 256");
|
||||
}
|
||||
|
|
@ -32,6 +32,37 @@ This is not an ORM in a fake mustache. It is for cases where you want:
|
|||
|
||||
That keeps the polymorphic boundary tight without making callers write boilerplate by candlelight.
|
||||
|
||||
## Reading And Writing Payloads
|
||||
|
||||
A document's bytes travel as a `DocumentPayload`: in a store envelope, a CultNet record and a
|
||||
realtime frame. At run time it is the same `Uint8Array`, so nothing on the wire changes. At compile
|
||||
time it is opaque: it is assignable to and from neither `Uint8Array` nor `ArrayLike<number>`, so no
|
||||
MessagePack decoder accepts it.
|
||||
|
||||
What the type guarantees is that a payload cannot be read or assigned directly: a decoder call, an
|
||||
assignment to `Uint8Array` and `new Uint8Array(payload)` fail to compile. It does not stop what the
|
||||
runtime value allows, because the value is a `Uint8Array`. These routes read it without the owner:
|
||||
`instanceof Uint8Array` or `ArrayBuffer.isView` narrowing, `Object.values`, `Object.assign` onto a
|
||||
`Uint8Array`, a JSON round trip, `Reflect.get`, and a cast. A read made that way sees the raw bytes,
|
||||
which for a codec or formatter document are not the document. No lint or guard closes them. Read
|
||||
through `decodeDocumentPayload`, and when you need the bytes themselves (hashing, signing, a store
|
||||
write) take them with `documentPayloadBytes`, the sanctioned escape.
|
||||
|
||||
- `decodeDocumentPayload(definition, payload)` reads a payload through the definition's formatter,
|
||||
codec or plain map and then its schema. The definition is required.
|
||||
- `encodeDocumentPayload(definition, value)` is the writer: the schema first, then the formatter,
|
||||
codec or plain map.
|
||||
- `documentPayloadFromBytes(bytes)` is where bytes enter (a record you validated, a store read, a
|
||||
writer of pre-encoded or signed bytes) and `documentPayloadBytes(payload)` is where they leave (a
|
||||
store write, a frame encode, hashing or signing). Reach for them only at those edges.
|
||||
|
||||
```ts
|
||||
const note = decodeDocumentPayload(noteDocument, envelope.payload); // parsed Note
|
||||
const payload = encodeDocumentPayload(noteDocument, note); // DocumentPayload
|
||||
```
|
||||
|
||||
Browsers import the same names from `@gamecult/cultcache-ts/document`, which holds no Node built-ins.
|
||||
|
||||
## `.cc` Inspection
|
||||
|
||||
CultCache files may use the `.cc` extension. The bytes are still the canonical
|
||||
|
|
@ -222,6 +253,10 @@ const combatLogDocument = defineDocumentType({
|
|||
|
||||
If you do not supply one, `CultCacheTS` uses MessagePack plus Zod validation by default.
|
||||
|
||||
The 256-container nesting bound (`MAX_PAYLOAD_DEPTH`, refused with `CultCachePayloadDepthError`) covers the MessagePack the
|
||||
library itself writes: the default format and a codec. A payload your formatter writes is opaque bytes in any format, so the
|
||||
library does not walk it as MessagePack; its format and its bounds are your formatter's.
|
||||
|
||||
Zod is no longer mandatory. Any schema object with a `parse(...)` function will
|
||||
do, which means generated Ajv-backed JSON-schema contracts can feed the cache
|
||||
directly as long as they expose the same parse surface.
|
||||
|
|
@ -234,6 +269,54 @@ The important boundary is this:
|
|||
|
||||
So callers get typed values, and the persistence layer does not become an open polymorphic sewer.
|
||||
|
||||
## Slot Records and Unions
|
||||
|
||||
`codec` writes the reference runtimes' record shape: a MessagePack array indexed by slot key, nil in a gap, and a
|
||||
union as `[armKey, [armSlots...]]`. A union value is `{ kind: armName, ...armFields }`.
|
||||
|
||||
```ts
|
||||
import { codecs, defineDocumentType } from "@gamecult/cultcache-ts";
|
||||
const { slots, union, list, lazy, string } = codecs;
|
||||
|
||||
const NS = "MyApp.Scene+"; // the C# names of the types, as the reference writes them into a store's schema catalog
|
||||
|
||||
type Node =
|
||||
| { kind: "Box"; id: string; children: (Node | null)[] }
|
||||
| { kind: "Text"; id: string; content: string }
|
||||
| { kind: "Image"; id: string; uri: string; alt: string };
|
||||
|
||||
const node: codecs.Codec<Node | null> = union<Node>("Node", {
|
||||
0: ["Box", slots<{ id: string; children: (Node | null)[] }>({ 0: ["id", string], 1: ["children", list(lazy(() => node))] })],
|
||||
1: ["Text", slots<{ id: string; content: string }>({ 0: ["id", string], 1: ["content", string] })],
|
||||
5: ["Image", slots<{ id: string; uri: string; alt: string }>({ 0: ["id", string], 1: ["uri", string], 3: ["alt", string] })], // slot 2 retired
|
||||
}, `${NS}Node`);
|
||||
|
||||
const sceneDocument = defineDocumentType({
|
||||
type: "scene",
|
||||
schema: sceneSchema,
|
||||
codec: slots<Scene>({ 0: ["id", string], 1: ["root", node], 2: ["title", string, ""] }),
|
||||
name: "id",
|
||||
});
|
||||
```
|
||||
|
||||
- A slot is `[name, codec, default?]`. A gap is written nil and skipped on read; an extra trailing slot is skipped; a
|
||||
slot missing from the payload (or nil, when a default is declared) takes its default, and is refused without one.
|
||||
- A union refuses an undeclared arm key on read, naming the union, the key and the declared keys. Nothing falls back
|
||||
to a default arm. An arm with no slots is `codecs.unit` and is written `[key, []]`.
|
||||
- A refusal names the union, the field and the slot; it never echoes the value it refused.
|
||||
- The leaves are `string`, `boolean`, `bytes`, `int32`, `int64`, `float32` and `float64`, each writing the MessagePack the
|
||||
C# type writes and refusing what C# refuses (a float in an int slot, an `int` outside Int32). `int64` reads a number
|
||||
when the value is a safe integer and a bigint beyond 2^53, and refuses a number beyond 2^53 on write. `list`, `array`
|
||||
and `nullable` wrap a leaf, a union or a record. A `float32` slot rounds an integer once, as the reference's cast does.
|
||||
- Every codec carries the reference's type name, and a store's schema catalog is derived from those names, because the
|
||||
reference refuses a store whose slot names another type. The leaves know theirs; give a union or a record its C# name
|
||||
as the last argument of `union(name, arms, typeName)` or `slots(spec, typeName)`. A codec with a slot it cannot name
|
||||
refuses to derive members: pass `members` instead.
|
||||
- An arm key is an integer within Int32 (negative too), in any MessagePack integer encoding. A float key (even `1.0`) is
|
||||
refused on read, and a union refuses a key outside Int32 when it is defined. A slot key is within 0 to Int32 max.
|
||||
- `codec` supplies the document's formatter and, unless `members` is given, its catalog members. A definition may not
|
||||
carry both `codec` and `formatter`. `schema.parse` still runs on every decoded value.
|
||||
|
||||
## Raw Envelope Fast Path
|
||||
|
||||
For bit-compatible neighbors such as CultNet peers that already share the same
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "@gamecult/cultcache-ts",
|
||||
"version": "0.15.0",
|
||||
"version": "0.14.0",
|
||||
"description": "CultCache-style typed persistence for TypeScript with schema-backed polymorphic MessagePack storage.",
|
||||
"main": "dist/index.js",
|
||||
"types": "dist/index.d.ts",
|
||||
|
|
@ -10,12 +10,24 @@
|
|||
"require": "./dist/index.js",
|
||||
"default": "./dist/index.js"
|
||||
},
|
||||
"./document": {
|
||||
"types": "./dist/document.d.ts",
|
||||
"require": "./dist/document.js",
|
||||
"default": "./dist/document.js"
|
||||
},
|
||||
"./inspection": {
|
||||
"types": "./dist/cult-cache-inspector.d.ts",
|
||||
"require": "./dist/cult-cache-inspector.js",
|
||||
"default": "./dist/cult-cache-inspector.js"
|
||||
}
|
||||
},
|
||||
"typesVersions": {
|
||||
"*": {
|
||||
"document": [
|
||||
"dist/document.d.ts"
|
||||
]
|
||||
}
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
|
|
@ -23,7 +35,7 @@
|
|||
"build": "node ../../node_modules/typescript/bin/tsc -p tsconfig.json",
|
||||
"prepack": "node ../../node_modules/typescript/bin/tsc -p tsconfig.json",
|
||||
"typecheck": "node ../../node_modules/typescript/bin/tsc -p tsconfig.json --pretty false",
|
||||
"test": "node ../../node_modules/typescript/bin/tsc -p tsconfig.json && node ../../node_modules/typescript/bin/tsc -p tsconfig.test.json && node --test dist-test/test/cult-cache.test.js"
|
||||
"test": "node ../../node_modules/typescript/bin/tsc -p tsconfig.json && node ../../node_modules/typescript/bin/tsc -p tsconfig.test.json && node --test dist-test/test/*.test.js"
|
||||
},
|
||||
"keywords": [
|
||||
"messagepack",
|
||||
|
|
|
|||
370
packages/cultcache-ts/src/codec.ts
Normal file
370
packages/cultcache-ts/src/codec.ts
Normal file
|
|
@ -0,0 +1,370 @@
|
|||
import type { CultCacheSchemaCatalogMember } from "./types";
|
||||
import { WireFloat } from "./wire";
|
||||
|
||||
// A codec turns a value into the shape the reference runtimes write and back. Slot records are positional arrays with
|
||||
// nil gaps; a union value is { kind: armName, ...armFields }, written [armKey, [armSlots...]]. Refusals name the union
|
||||
// or the slot and the key or code, and never echo a decoded value. `typeName` is the reference's name for the type
|
||||
// (CultSchemaTypeNames.FromType): a store's schema catalog carries it per slot, and the reference refuses a store whose
|
||||
// slot names another type. The leaves know theirs; a union or a record the codec cannot name from C# is given it.
|
||||
export interface Codec<TValue> {
|
||||
encode(value: TValue): unknown;
|
||||
decode(raw: unknown): TValue;
|
||||
readonly typeName?: string;
|
||||
// True for a type the reference makes Nullable<T> when the slot may be nil (int, long, float, double, bool).
|
||||
readonly valueType?: boolean;
|
||||
}
|
||||
|
||||
export interface SlotsCodec<TValue extends object> extends Codec<TValue> {
|
||||
// Throws when a slot's codec has no typeName: the catalog cannot be derived without the reference's names.
|
||||
readonly members: readonly CultCacheSchemaCatalogMember[];
|
||||
readonly names: readonly string[];
|
||||
}
|
||||
|
||||
function kindOf(raw: unknown): string {
|
||||
if (raw === null || raw === undefined) return "nil";
|
||||
if (Array.isArray(raw)) return "array";
|
||||
if (raw instanceof WireFloat) return "float";
|
||||
if (typeof raw === "bigint") return "integer";
|
||||
return typeof raw;
|
||||
}
|
||||
|
||||
function refuse(what: string, found: string): never {
|
||||
throw new Error(`expected ${what}, found ${found}`);
|
||||
}
|
||||
|
||||
function expect(raw: unknown, what: string, ok: boolean): asserts ok {
|
||||
if (!ok) refuse(what, kindOf(raw));
|
||||
}
|
||||
|
||||
export const string: Codec<string> = {
|
||||
typeName: "System.String",
|
||||
encode: (value) => (expect(value, "a string", typeof value === "string"), value),
|
||||
decode: (raw) => (expect(raw, "a string", typeof raw === "string"), raw as string),
|
||||
};
|
||||
|
||||
export const boolean: Codec<boolean> = {
|
||||
typeName: "System.Boolean",
|
||||
valueType: true,
|
||||
encode: (value) => (expect(value, "a boolean", typeof value === "boolean"), value),
|
||||
decode: (raw) => (expect(raw, "a boolean", typeof raw === "boolean"), raw as boolean),
|
||||
};
|
||||
|
||||
// The reference's byte[] reads a MessagePack str as its bytes and writes bin (an old-spec writer's output), so a str is
|
||||
// accepted and re-encodes as bin. The wire reader has already decoded the str, so a str that held invalid UTF-8 (it
|
||||
// reads back U+FFFD) is refused rather than turned into other bytes.
|
||||
export const bytes: Codec<Uint8Array> = {
|
||||
typeName: "System.Byte[]",
|
||||
encode: (value) => (expect(value, "bytes", value instanceof Uint8Array), value),
|
||||
decode(raw) {
|
||||
if (typeof raw === "string") {
|
||||
if (raw.includes("<22>")) refuse("bytes", "a string that is not valid UTF-8");
|
||||
return new TextEncoder().encode(raw);
|
||||
}
|
||||
expect(raw, "bytes", raw instanceof Uint8Array);
|
||||
return raw as Uint8Array;
|
||||
},
|
||||
};
|
||||
|
||||
// A C# integer slot: written as the smallest MessagePack integer and read from any integer encoding in range. A float is
|
||||
// refused even when it holds a whole number, as the reference refuses it.
|
||||
function integerCodec(typeName: string, what: string, low: bigint, high: bigint): Codec<number | bigint> {
|
||||
const inRange = (value: number | bigint) => value >= low && value <= high;
|
||||
return {
|
||||
typeName,
|
||||
valueType: true,
|
||||
encode(value) {
|
||||
if (typeof value === "bigint") {
|
||||
if (!inRange(value)) refuse(what, "an integer out of range");
|
||||
return value;
|
||||
}
|
||||
if (typeof value !== "number") refuse(what, kindOf(value));
|
||||
if (!Number.isSafeInteger(value)) {
|
||||
refuse(what, Number.isInteger(value) ? "a number beyond 2^53, which needs a bigint" : "a non-integer number");
|
||||
}
|
||||
if (!inRange(value)) refuse(what, "an integer out of range");
|
||||
return value;
|
||||
},
|
||||
decode(raw) {
|
||||
if (typeof raw !== "number" && typeof raw !== "bigint") refuse(what, kindOf(raw));
|
||||
if (!inRange(raw)) refuse(what, "an integer out of range");
|
||||
return raw;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// C# int. Always a number.
|
||||
export const int32 = integerCodec("System.Int32", "an int32", -(2n ** 31n), 2n ** 31n - 1n) as Codec<number>;
|
||||
// C# long. A number when the value is a safe integer, a bigint beyond 2^53 (so 64-bit values never lose precision).
|
||||
export const int64 = integerCodec("System.Int64", "an int64", -(2n ** 63n), 2n ** 63n - 1n);
|
||||
|
||||
// A 64-bit integer to the nearest float32 in one rounding, ties to even, as the reference's cast does. Number(value)
|
||||
// first would round to a double and then again, and the two roundings can disagree. A bigint reaches here only beyond
|
||||
// 2^53 (the wire reader returns a number for any smaller integer), so at least 30 bits are rounded away.
|
||||
function bigintToFloat32(value: bigint): number {
|
||||
const magnitude = value < 0n ? -value : value;
|
||||
const excess = magnitude.toString(2).length - 24;
|
||||
const kept = magnitude >> BigInt(excess);
|
||||
const rest = magnitude - (kept << BigInt(excess));
|
||||
const half = 1n << BigInt(excess - 1);
|
||||
const rounded = Number(rest > half || (rest === half && (kept & 1n) === 1n) ? kept + 1n : kept) * 2 ** excess;
|
||||
return value < 0n ? -rounded : rounded;
|
||||
}
|
||||
|
||||
function floatCodec(typeName: string, wide: boolean): Codec<number> {
|
||||
const what = wide ? "a float64" : "a float32";
|
||||
return {
|
||||
typeName,
|
||||
valueType: true,
|
||||
encode(value) {
|
||||
expect(value, what, typeof value === "number");
|
||||
return new WireFloat(value, wide);
|
||||
},
|
||||
decode(raw) {
|
||||
if (raw instanceof WireFloat) {
|
||||
// A JS number has no NaN payload, so a signalling float32 NaN cannot be kept; refusing beats changing its bytes.
|
||||
if (raw.signalling && !wide) refuse(what, "a signalling NaN");
|
||||
return wide ? raw.value : Math.fround(raw.value);
|
||||
}
|
||||
if (typeof raw === "number") return wide ? raw : Math.fround(raw);
|
||||
if (typeof raw === "bigint") return wide ? Number(raw) : bigintToFloat32(raw);
|
||||
return refuse(what, kindOf(raw));
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// C# float, written as MessagePack float 32.
|
||||
export const float32 = floatCodec("System.Single", false);
|
||||
// C# double, written as MessagePack float 64.
|
||||
export const float64 = floatCodec("System.Double", true);
|
||||
|
||||
function sequence<TItem>(item: Codec<TItem>, nameOf: (itemName: string) => string): Codec<TItem[]> {
|
||||
return {
|
||||
get typeName() { return item.typeName === undefined ? undefined : nameOf(item.typeName); },
|
||||
encode(value) {
|
||||
expect(value, "an array", Array.isArray(value));
|
||||
return value.map((element, index) => at(`element ${index}`, () => item.encode(element)));
|
||||
},
|
||||
decode(raw) {
|
||||
expect(raw, "an array", Array.isArray(raw));
|
||||
return (raw as unknown[]).map((element, index) => at(`element ${index}`, () => item.decode(element)));
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// C# List<T>.
|
||||
export function list<TItem>(item: Codec<TItem>): Codec<TItem[]> {
|
||||
return sequence(item, (name) => `System.Collections.Generic.List<${name}>`);
|
||||
}
|
||||
|
||||
// C# T[]. The same wire as list.
|
||||
export function array<TItem>(item: Codec<TItem>): Codec<TItem[]> {
|
||||
return sequence(item, (name) => `${name}[]`);
|
||||
}
|
||||
|
||||
// A slot that may be nil. For a value type the reference's name is Nullable<T>; for a reference type it is unchanged.
|
||||
export function nullable<TValue>(inner: Codec<TValue>): Codec<TValue | null> {
|
||||
return {
|
||||
get typeName() {
|
||||
return inner.typeName !== undefined && inner.valueType ? `System.Nullable<${inner.typeName}>` : inner.typeName;
|
||||
},
|
||||
encode: (value) => (value === null || value === undefined ? null : inner.encode(value)),
|
||||
decode: (raw) => (raw === null ? null : inner.decode(raw)),
|
||||
};
|
||||
}
|
||||
|
||||
export function lazy<TValue>(get: () => Codec<TValue>): Codec<TValue> {
|
||||
let resolved: Codec<TValue> | undefined;
|
||||
const codec = () => (resolved ??= get());
|
||||
return {
|
||||
get typeName() { return codec().typeName; },
|
||||
get valueType() { return codec().valueType; },
|
||||
encode: (value) => codec().encode(value),
|
||||
decode: (raw) => codec().decode(raw),
|
||||
};
|
||||
}
|
||||
|
||||
// Prefixes a refusal with where it happened, so a nested refusal still names its field and its union.
|
||||
function at<TResult>(where: string, run: () => TResult): TResult {
|
||||
try {
|
||||
return run();
|
||||
} catch (error) {
|
||||
throw new Error(`${where}: ${(error as Error).message}`);
|
||||
}
|
||||
}
|
||||
|
||||
type SlotSpec<TValue, TName extends string = string> =
|
||||
| readonly [name: TName, codec: Codec<TValue>]
|
||||
| readonly [name: TName, codec: Codec<TValue>, defaultValue: TValue | (() => TValue)];
|
||||
|
||||
type SlotsSpec<TValue> = Readonly<Record<number, { [K in keyof TValue & string]: SlotSpec<TValue[K], K> }[keyof TValue & string]>>;
|
||||
|
||||
const INT32_MIN = -(2 ** 31);
|
||||
const INT32_MAX = 2 ** 31 - 1;
|
||||
|
||||
// The largest slot key. A slot record is written as a dense array of key+1 slots (the reference writes the same, nil
|
||||
// in every gap), so a key is a payload length: the cap keeps a definition's typo from allocating without bound.
|
||||
export const MAX_SLOT_KEY = 65535;
|
||||
|
||||
// The declared keys, ascending. The reference's keys are Int32: a union arm may be any (a negative one too), a slot is
|
||||
// 0 to MAX_SLOT_KEY, and a key outside its range is refused at definition rather than allocated for.
|
||||
function slotKeys(spec: Readonly<Record<string, unknown>>, owner: string, low: number, high: number): number[] {
|
||||
return Object.keys(spec)
|
||||
.map((text) => {
|
||||
if (!/^-?(0|[1-9][0-9]*)$/u.test(text) || (low >= 0 && text.startsWith("-"))) {
|
||||
throw new Error(`${owner} declares the key "${text}", which is not ${low < 0 ? "an" : "a non-negative"} integer.`);
|
||||
}
|
||||
const key = BigInt(text);
|
||||
if (key < BigInt(low) || key > BigInt(high)) {
|
||||
throw new Error(`${owner} declares the key ${text}, which is ${high === INT32_MAX ? "outside Int32" : `above the slot key limit ${high}`}.`);
|
||||
}
|
||||
return Number(key);
|
||||
})
|
||||
// Object.keys lists negative keys after the others, in the order they were written: sort them numerically.
|
||||
.sort((left, right) => left - right);
|
||||
}
|
||||
|
||||
function pascalCase(name: string): string {
|
||||
return name
|
||||
.split(/[^A-Za-z0-9]/u)
|
||||
.filter((part) => part.length > 0)
|
||||
.map((part) => part[0].toUpperCase() + part.slice(1))
|
||||
.join("");
|
||||
}
|
||||
|
||||
// A positional record: slot `key` holds field `name`. Gaps are written nil and skipped on read, extra trailing slots
|
||||
// are skipped, and a slot missing from the payload takes its declared default or is refused. A default fills only a
|
||||
// missing trailing slot, never a nil: as in the reference, a nil in a reference slot (string, bytes, record, union,
|
||||
// list) reads as null and writes back as nil, so a record the reference wrote re-encodes byte-identical, and a nil in
|
||||
// a value slot (int, float, bool) is refused unless the slot is nullable.
|
||||
export function slots<TValue extends object>(spec: SlotsSpec<TValue>, typeName?: string): SlotsCodec<TValue> {
|
||||
const keys = slotKeys(spec, "A slot record", 0, MAX_SLOT_KEY);
|
||||
if (keys.length === 0) {
|
||||
throw new Error("A slot record declares no slots.");
|
||||
}
|
||||
const fields = keys.map((key) => {
|
||||
const [name, codec, ...rest] = (spec as unknown as Readonly<Record<number, SlotSpec<unknown>>>)[key];
|
||||
return { key, name, codec, hasDefault: rest.length > 0, defaultValue: rest[0] };
|
||||
});
|
||||
const seen = new Set<string>();
|
||||
for (const field of fields) {
|
||||
if (seen.has(field.name)) {
|
||||
throw new Error(`A slot record declares the field "${field.name}" twice.`);
|
||||
}
|
||||
seen.add(field.name);
|
||||
}
|
||||
const length = keys[keys.length - 1] + 1;
|
||||
const defaultOf = (field: (typeof fields)[number]): unknown =>
|
||||
typeof field.defaultValue === "function" ? (field.defaultValue as () => unknown)() : field.defaultValue;
|
||||
|
||||
return {
|
||||
names: fields.map((field) => field.name),
|
||||
typeName,
|
||||
get members() {
|
||||
return fields.map((field) => {
|
||||
if (field.codec.typeName === undefined) {
|
||||
throw new Error(`${field.name} (slot ${field.key}) has no C# type name for the schema catalog; give its union or record a typeName, or give the document its members.`);
|
||||
}
|
||||
return { slot: field.key, memberName: pascalCase(field.name), typeName: field.codec.typeName };
|
||||
});
|
||||
},
|
||||
encode(value) {
|
||||
expect(value, "a record", typeof value === "object" && value !== null);
|
||||
const out: unknown[] = new Array(length).fill(null);
|
||||
for (const field of fields) {
|
||||
const member = (value as Record<string, unknown>)[field.name];
|
||||
out[field.key] = member === null && !field.codec.valueType
|
||||
? null
|
||||
: at(`${field.name} (slot ${field.key})`, () => field.codec.encode(member));
|
||||
}
|
||||
return out;
|
||||
},
|
||||
decode(raw) {
|
||||
expect(raw, "an array of slots", Array.isArray(raw));
|
||||
const input = raw as unknown[];
|
||||
const out: Record<string, unknown> = {};
|
||||
for (const field of fields) {
|
||||
const present = field.key < input.length;
|
||||
if (!present && !field.hasDefault) {
|
||||
throw new Error(`${field.name} (slot ${field.key}): the slot is missing and declares no default.`);
|
||||
}
|
||||
out[field.name] = !present
|
||||
? defaultOf(field)
|
||||
: input[field.key] === null && !field.codec.valueType
|
||||
? null
|
||||
: at(`${field.name} (slot ${field.key})`, () => field.codec.decode(input[field.key]));
|
||||
}
|
||||
return out as TValue;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// An arm with no slots. It is written [key, []], never [key, nil].
|
||||
export interface UnitArm {
|
||||
readonly unit: true;
|
||||
}
|
||||
export const unit: UnitArm = Object.freeze({ unit: true });
|
||||
|
||||
type ArmSpec<TKind extends string> = readonly [armName: TKind, body: SlotsCodec<any> | UnitArm];
|
||||
|
||||
// A tagged union written [armKey, [armSlots...]]. The reader refuses an undeclared key, naming the union, the key and
|
||||
// the declared keys; there is no fallback arm.
|
||||
export function union<TValue extends { kind: string }>(
|
||||
name: string,
|
||||
arms: Readonly<Record<number, ArmSpec<TValue["kind"]>>>,
|
||||
typeName?: string,
|
||||
): Codec<TValue | null> {
|
||||
const keys = slotKeys(arms, `Union ${name}`, INT32_MIN, INT32_MAX);
|
||||
if (keys.length === 0) {
|
||||
throw new Error(`Union ${name} declares no arms.`);
|
||||
}
|
||||
const byKey = new Map<number, { armName: string; body: SlotsCodec<any> | UnitArm }>();
|
||||
const byName = new Map<string, number>();
|
||||
for (const key of keys) {
|
||||
const [armName, body] = arms[key];
|
||||
if (byName.has(armName)) {
|
||||
throw new Error(`Union ${name} declares the arm "${armName}" twice.`);
|
||||
}
|
||||
if (body !== unit && (body as SlotsCodec<any>).names.includes("kind")) {
|
||||
throw new Error(`Union ${name} arm "${armName}" declares a slot named kind, which is the union's own tag.`);
|
||||
}
|
||||
byKey.set(key, { armName, body });
|
||||
byName.set(armName, key);
|
||||
}
|
||||
const declared = keys.join(", ");
|
||||
|
||||
return {
|
||||
typeName,
|
||||
encode(value) {
|
||||
if (value === null || value === undefined) {
|
||||
return null;
|
||||
}
|
||||
const key = byName.get((value as { kind?: string }).kind as string);
|
||||
if (key === undefined) {
|
||||
throw new Error(`Union ${name}: the value's kind is not one of its arms (${[...byName.keys()].join(", ")}).`);
|
||||
}
|
||||
const { armName, body } = byKey.get(key)!;
|
||||
return [key, body === unit ? [] : at(`arm ${armName}`, () => (body as SlotsCodec<any>).encode(value))];
|
||||
},
|
||||
decode(raw) {
|
||||
if (raw === null) {
|
||||
return null;
|
||||
}
|
||||
if (!Array.isArray(raw) || raw.length !== 2 || !Array.isArray(raw[1])) {
|
||||
throw new Error(`Union ${name}: expected [key, slots] and found something else.`);
|
||||
}
|
||||
const key: unknown = raw[0];
|
||||
if (typeof key !== "number" && typeof key !== "bigint") {
|
||||
throw new Error(`Union ${name}: the arm key is not an integer (declared keys: ${declared}).`);
|
||||
}
|
||||
if (key < INT32_MIN || key > INT32_MAX) {
|
||||
throw new Error(`Union ${name}: the arm key is outside Int32 (declared keys: ${declared}).`);
|
||||
}
|
||||
const arm = byKey.get(Number(key));
|
||||
if (arm === undefined) {
|
||||
throw new Error(`Union ${name}: unknown arm key ${key} (declared keys: ${declared}).`);
|
||||
}
|
||||
const fields = arm.body === unit ? {} : at(`arm ${arm.armName}`, () => (arm.body as SlotsCodec<any>).decode(raw[1]));
|
||||
return { kind: arm.armName, ...fields } as unknown as TValue;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
|
@ -1,5 +1,6 @@
|
|||
import { decode } from "@msgpack/msgpack";
|
||||
|
||||
import { checkPayloadDepth } from "./payload-depth";
|
||||
import { type StoreFormat, isStoreSnapshot, requireStoreSlots, requireV1RecordSlots } from "./store-format";
|
||||
|
||||
export interface CultCacheInspection {
|
||||
|
|
@ -233,9 +234,15 @@ function decodeLegacyEnvelope(value: unknown): InspectedRecord {
|
|||
};
|
||||
}
|
||||
|
||||
// The inspector's one payload read: the depth walk first, so a payload past the limit is refused before any decoder sees it.
|
||||
function decodeBoundedPayload(payload: Uint8Array): unknown {
|
||||
checkPayloadDepth(payload);
|
||||
return decode(payload);
|
||||
}
|
||||
|
||||
function previewPayload(payload: Uint8Array): Pick<InspectedRecord, "payloadPreview" | "payloadDecodeError"> {
|
||||
try {
|
||||
return { payloadPreview: toJsonSafe(decode(payload)) };
|
||||
return { payloadPreview: toJsonSafe(decodeBoundedPayload(payload)) };
|
||||
} catch (error) {
|
||||
return {
|
||||
payloadPreview: {
|
||||
|
|
|
|||
|
|
@ -1,13 +1,19 @@
|
|||
import { decode, encode } from "@msgpack/msgpack";
|
||||
|
||||
import { schemaIdentityOf } from "./document";
|
||||
import {
|
||||
decodeDocumentPayload,
|
||||
documentPayloadBytes,
|
||||
documentPayloadFromBytes,
|
||||
encodeDocumentPayload,
|
||||
resolveDocumentMembers,
|
||||
schemaIdentityOf,
|
||||
} from "./document";
|
||||
import { resolveDocumentFormatter } from "./document-formatter";
|
||||
import type { DocumentPayload } from "./document";
|
||||
import { SchemaConflictError } from "./store-format";
|
||||
import type {
|
||||
AnyCultCacheDocumentDefinition,
|
||||
CacheBackingStore,
|
||||
CultCacheDocumentAccessor,
|
||||
CultCacheDocumentDefinition,
|
||||
CultCacheDocumentFormatter,
|
||||
CultCacheDocumentRegistry,
|
||||
CultCacheDocumentValue,
|
||||
CultCacheEnvelope,
|
||||
|
|
@ -17,10 +23,16 @@ import type {
|
|||
|
||||
type Accessor = (value: unknown) => string | undefined;
|
||||
|
||||
// A registered definition reads and writes its documents through the owner, on payloads the cache has cloned.
|
||||
type RegisteredFormatter = {
|
||||
encode(value: unknown): DocumentPayload;
|
||||
decode(payload: DocumentPayload): unknown;
|
||||
};
|
||||
|
||||
type RegisteredDefinition = {
|
||||
readonly definition: AnyCultCacheDocumentDefinition;
|
||||
readonly global: boolean;
|
||||
readonly formatter: CultCacheDocumentFormatter<unknown>;
|
||||
readonly formatter: RegisteredFormatter;
|
||||
readonly catalogEntry: CultCacheSchemaCatalogEntry;
|
||||
nameAccessor?: Accessor;
|
||||
indexAccessors: ReadonlyMap<string, Accessor>;
|
||||
|
|
@ -688,21 +700,13 @@ export class CultCache {
|
|||
}
|
||||
}
|
||||
|
||||
#createFormatter(definition: AnyCultCacheDocumentDefinition): CultCacheDocumentFormatter<unknown> {
|
||||
const userFormatter = definition.formatter ?? {
|
||||
encode: (value: unknown) => encode(value),
|
||||
decode: (payload: Uint8Array) => decode(payload),
|
||||
};
|
||||
#createFormatter(definition: AnyCultCacheDocumentDefinition): RegisteredFormatter {
|
||||
// A definition that declares both a codec and a formatter is refused here, where it is registered.
|
||||
resolveDocumentFormatter(definition);
|
||||
|
||||
return {
|
||||
encode: (value: unknown) => {
|
||||
const parsed = definition.schema.parse(value);
|
||||
return this.#cloneBytes(userFormatter.encode(parsed));
|
||||
},
|
||||
decode: (payload: Uint8Array) => {
|
||||
const decoded = userFormatter.decode(this.#cloneBytes(payload));
|
||||
return definition.schema.parse(decoded);
|
||||
},
|
||||
encode: (value: unknown) => this.#cloneBytes(encodeDocumentPayload(definition, value)),
|
||||
decode: (payload: DocumentPayload) => decodeDocumentPayload(definition, this.#cloneBytes(payload)),
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -711,7 +715,7 @@ export class CultCache {
|
|||
const canonicalSchemaJson = definition.canonicalSchemaJson ?? JSON.stringify({
|
||||
schemaName,
|
||||
schemaVersion,
|
||||
members: [...(definition.members ?? [])]
|
||||
members: [...resolveDocumentMembers(definition)]
|
||||
.sort((left, right) => left.slot - right.slot)
|
||||
.map((member) => ({
|
||||
slot: member.slot,
|
||||
|
|
@ -732,7 +736,7 @@ export class CultCache {
|
|||
contentHash: definition.contentHash ?? schemaId,
|
||||
canonicalSchemaJson,
|
||||
compatibleSchemaIds: [...compatibleSchemaIds],
|
||||
members: [...(definition.members ?? [])]
|
||||
members: [...resolveDocumentMembers(definition)]
|
||||
.sort((left, right) => left.slot - right.slot)
|
||||
.map((member) => ({
|
||||
slot: member.slot,
|
||||
|
|
@ -1049,7 +1053,7 @@ export class CultCache {
|
|||
return `${type}::${indexName}`;
|
||||
}
|
||||
|
||||
#cloneBytes(payload: Uint8Array): Uint8Array {
|
||||
return new Uint8Array(payload);
|
||||
#cloneBytes(payload: DocumentPayload): DocumentPayload {
|
||||
return documentPayloadFromBytes(new Uint8Array(documentPayloadBytes(payload)));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
32
packages/cultcache-ts/src/document-formatter.ts
Normal file
32
packages/cultcache-ts/src/document-formatter.ts
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
import { decode, encode } from "@msgpack/msgpack";
|
||||
|
||||
import { MAX_PAYLOAD_DEPTH } from "./payload-depth";
|
||||
import type { SlotsCodec } from "./codec";
|
||||
import type { AnyCultCacheDocumentDefinition, CultCacheDocumentFormatter } from "./types";
|
||||
import { readWire, writeWire } from "./wire";
|
||||
|
||||
// The one place that decides how a document is encoded: its own formatter, or its codec's, or a plain map. A codec and a
|
||||
// formatter are two answers to one question, so a definition that carries both is refused wherever it enters (the
|
||||
// builder resolves through here as well). Package-internal: no entry of the package's exports map names this module, so
|
||||
// a consumer cannot import the formatter and read a payload around the schema.
|
||||
export function resolveDocumentFormatter(definition: AnyCultCacheDocumentDefinition): CultCacheDocumentFormatter<unknown> {
|
||||
if (definition.codec && definition.formatter) {
|
||||
throw new Error(`CultCache document type "${definition.type}" declares both a codec and a formatter.`);
|
||||
}
|
||||
return definition.formatter ?? (definition.codec ? codecFormatter(definition.codec) : plainDocumentFormatter);
|
||||
}
|
||||
|
||||
const plainDocumentFormatter: CultCacheDocumentFormatter<unknown> = {
|
||||
// The encoder's own depth refusal (100 by default) is set above the limit, so the payload walk decides.
|
||||
encode: (value: unknown) => encode(value, { maxDepth: MAX_PAYLOAD_DEPTH * 2 }),
|
||||
decode: (payload: Uint8Array) => decode(payload),
|
||||
};
|
||||
|
||||
// The formatter a document gets from a slot codec: the codec's value as one MessagePack payload. Private to this module
|
||||
// for the same reason as the resolver: exported, it would read a payload without the schema.
|
||||
function codecFormatter<TValue extends object>(codec: SlotsCodec<TValue>): CultCacheDocumentFormatter<TValue> {
|
||||
return {
|
||||
encode: (value) => writeWire(codec.encode(value)),
|
||||
decode: (payload) => codec.decode(readWire(payload)),
|
||||
};
|
||||
}
|
||||
|
|
@ -1,7 +1,11 @@
|
|||
import { resolveDocumentFormatter } from "./document-formatter";
|
||||
import { checkPayloadDepth } from "./payload-depth";
|
||||
import type {
|
||||
AnyCultCacheDocumentDefinition,
|
||||
CultCacheSchemaCatalogMember,
|
||||
CultCacheDocumentDefinition,
|
||||
CultCacheDocumentRegistry,
|
||||
CultCacheDocumentValue,
|
||||
CultCacheSchema,
|
||||
} from "./types";
|
||||
|
||||
|
|
@ -66,7 +70,83 @@ export function defineDocumentType<TSchema extends CultCacheSchema>(
|
|||
}
|
||||
}
|
||||
|
||||
return Object.freeze({ ...definition });
|
||||
resolveDocumentFormatter(definition);
|
||||
return Object.freeze(definition.codec ? { ...definition, members: resolveDocumentMembers(definition) } : { ...definition });
|
||||
}
|
||||
|
||||
/**
|
||||
* The bytes of one document, as they travel in a store envelope, a CultNet record or a realtime frame.
|
||||
*
|
||||
* At run time this is the same `Uint8Array`, so frames encode as they always did. At compile time it is opaque: it is not
|
||||
* assignable to or from `Uint8Array` or `ArrayLike<number>`, so no byte decoder accepts it. The only reader is
|
||||
* `decodeDocumentPayload(definition, payload)`, which needs the definition that says how the bytes are laid out, and the
|
||||
* only writer is `encodeDocumentPayload(definition, value)`. The two escapes are named: `documentPayloadFromBytes` where
|
||||
* bytes enter (a validated record, a store read, tests, a writer of pre-encoded or signed bytes) and
|
||||
* `documentPayloadBytes` where they leave (a store write, a frame encode, hashing or signing).
|
||||
*
|
||||
* The key is a plain string, not a unique symbol, so two installed copies of this package stay compatible.
|
||||
*
|
||||
* What the type guarantees: a payload cannot be read or assigned directly (a decoder call, `const b: Uint8Array = p`,
|
||||
* `new Uint8Array(p)` fail to compile). What it does not: the runtime value is a `Uint8Array`, so these routes read it
|
||||
* without the owner: `instanceof Uint8Array` or `ArrayBuffer.isView` narrowing, `Object.values`, `Object.assign` onto a
|
||||
* `Uint8Array`, a JSON round trip, `Reflect.get`, and a cast. A codec or formatter document read that way is raw bytes,
|
||||
* not the document. The sanctioned escape for bytes is `documentPayloadBytes`; the reader is `decodeDocumentPayload`.
|
||||
*/
|
||||
export interface DocumentPayload {
|
||||
readonly "cultcache.documentPayload": true;
|
||||
readonly byteLength: number;
|
||||
}
|
||||
|
||||
export function documentPayloadFromBytes(bytes: Uint8Array): DocumentPayload {
|
||||
return bytes as unknown as DocumentPayload;
|
||||
}
|
||||
|
||||
export function documentPayloadBytes(payload: DocumentPayload): Uint8Array {
|
||||
return payload as unknown as Uint8Array;
|
||||
}
|
||||
|
||||
export { CultCachePayloadDepthError, MAX_PAYLOAD_DEPTH } from "./payload-depth";
|
||||
|
||||
// The payload nesting bound covers the MessagePack the library itself writes: the plain default formatter and a codec. A
|
||||
// user formatter's bytes are opaque and in any format; its format and bounds are its own.
|
||||
function writesLibraryMessagePack(definition: AnyCultCacheDocumentDefinition): boolean {
|
||||
return !definition.formatter;
|
||||
}
|
||||
|
||||
// The one reader of a document payload: through the definition's formatter, codec or plain map, then its schema. A
|
||||
// reader holds the definition or it has no business reading the bytes, so there is no definition-less form.
|
||||
export function decodeDocumentPayload<TDefinition extends AnyCultCacheDocumentDefinition>(
|
||||
definition: TDefinition,
|
||||
payload: DocumentPayload,
|
||||
): CultCacheDocumentValue<TDefinition> {
|
||||
const bytes = documentPayloadBytes(payload);
|
||||
if (writesLibraryMessagePack(definition)) checkPayloadDepth(bytes, `document type "${definition.type}" payload`);
|
||||
const decoded = resolveDocumentFormatter(definition).decode(bytes);
|
||||
return definition.schema.parse(decoded) as CultCacheDocumentValue<TDefinition>;
|
||||
}
|
||||
|
||||
// The one writer: the definition's schema first, then its formatter, codec or plain map.
|
||||
export function encodeDocumentPayload(definition: AnyCultCacheDocumentDefinition, value: unknown): DocumentPayload {
|
||||
const bytes = resolveDocumentFormatter(definition).encode(definition.schema.parse(value));
|
||||
if (writesLibraryMessagePack(definition)) checkPayloadDepth(bytes, `document type "${definition.type}" value`);
|
||||
return documentPayloadFromBytes(bytes);
|
||||
}
|
||||
|
||||
// The schema members of a document: the ones it declares, else those its codec derives, else none.
|
||||
export function resolveDocumentMembers(definition: AnyCultCacheDocumentDefinition): readonly CultCacheSchemaCatalogMember[] {
|
||||
if (definition.members || !definition.codec) {
|
||||
return definition.members ?? [];
|
||||
}
|
||||
const codec = definition.codec;
|
||||
const indexAlias = (slotName: string) =>
|
||||
!Array.isArray(definition.indexes) && definition.indexes
|
||||
? Object.entries(definition.indexes).find(([, accessor]) => accessor === slotName)?.[0] ?? null
|
||||
: null;
|
||||
return codec.members.map((member, index) => ({
|
||||
...member,
|
||||
isName: (definition.name as unknown) === codec.names[index],
|
||||
indexAlias: indexAlias(codec.names[index]),
|
||||
}));
|
||||
}
|
||||
|
||||
// The identity a definition's records carry: the schema id they are stamped with, the schema name and version, and every id
|
||||
|
|
|
|||
|
|
@ -1,6 +1,19 @@
|
|||
export * as codecs from "./codec";
|
||||
export type { Codec, SlotsCodec } from "./codec";
|
||||
export { CultCache, CultCacheBuilder } from "./cult-cache";
|
||||
export { inspectCultCacheBytes } from "./cult-cache-inspector";
|
||||
export { defineDocumentRegistry, defineDocumentType, schemaIdentityOf, type CultCacheSchemaIdentity } from "./document";
|
||||
export {
|
||||
decodeDocumentPayload,
|
||||
defineDocumentRegistry,
|
||||
defineDocumentType,
|
||||
documentPayloadBytes,
|
||||
documentPayloadFromBytes,
|
||||
encodeDocumentPayload,
|
||||
schemaIdentityOf,
|
||||
type CultCacheSchemaIdentity,
|
||||
} from "./document";
|
||||
export { CultCachePayloadDepthError, MAX_PAYLOAD_DEPTH } from "./payload-depth";
|
||||
export type { DocumentPayload } from "./document";
|
||||
export { SingleFileMessagePackBackingStore, readSingleFileStore, type SingleFileStoreRead } from "./single-file-messagepack-backing-store";
|
||||
export { SchemaConflictError, StoreUnreadableError } from "./store-format";
|
||||
export type {
|
||||
|
|
|
|||
70
packages/cultcache-ts/src/payload-depth.ts
Normal file
70
packages/cultcache-ts/src/payload-depth.ts
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
// The one payload nesting rule in TypeScript, the twin of the C# reference's CultPayloadDepth.Check: every MessagePack
|
||||
// array and map counts, whether a reader reads it or skips past it, and the outermost array is depth 1. Depth
|
||||
// MAX_PAYLOAD_DEPTH is accepted and one container deeper is refused, on read and on write.
|
||||
export const MAX_PAYLOAD_DEPTH = 256;
|
||||
|
||||
export class CultCachePayloadDepthError extends Error {
|
||||
constructor(readonly depth: number, readonly limit: number, subject: string) {
|
||||
super(`${subject} nests ${depth} MessagePack containers deep; the limit is ${limit}.`);
|
||||
this.name = "CultCachePayloadDepthError";
|
||||
}
|
||||
}
|
||||
|
||||
// Walks the headers of one MessagePack value iteratively (a count stack bounded by the limit, scalars skipped by length,
|
||||
// nothing read) and throws at the first container past the limit. The message names the subject, the depth and the limit,
|
||||
// never payload bytes. A payload that ends early is the reader's to refuse.
|
||||
export function checkPayloadDepth(bytes: Uint8Array, subject = "document payload"): void {
|
||||
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
||||
const remaining = new Float64Array(MAX_PAYLOAD_DEPTH);
|
||||
let depth = 0;
|
||||
let position = 0;
|
||||
// The big-endian length that follows the code byte, when the payload is long enough to hold it.
|
||||
const width = (size: 1 | 2 | 4): number | undefined => {
|
||||
if (position + 1 + size > bytes.length) return undefined;
|
||||
return size === 1 ? view.getUint8(position + 1) : size === 2 ? view.getUint16(position + 1) : view.getUint32(position + 1);
|
||||
};
|
||||
while (position < bytes.length) {
|
||||
const code = bytes[position];
|
||||
let header = 0;
|
||||
let children = 0;
|
||||
let skip = 0;
|
||||
let container = false;
|
||||
if (code <= 0x7f || code >= 0xe0 || code === 0xc0 || code === 0xc1 || code === 0xc2 || code === 0xc3) skip = 1;
|
||||
else if (code <= 0x8f) { container = true; header = 1; children = 2 * (code & 0x0f); }
|
||||
else if (code <= 0x9f) { container = true; header = 1; children = code & 0x0f; }
|
||||
else if (code <= 0xbf) skip = 1 + (code & 0x1f);
|
||||
else if (code === 0xc4 || code === 0xd9) { const n = width(1); if (n === undefined) return; skip = 2 + n; }
|
||||
else if (code === 0xc5 || code === 0xda) { const n = width(2); if (n === undefined) return; skip = 3 + n; }
|
||||
else if (code === 0xc6 || code === 0xdb) { const n = width(4); if (n === undefined) return; skip = 5 + n; }
|
||||
else if (code === 0xc7) { const n = width(1); if (n === undefined) return; skip = 3 + n; }
|
||||
else if (code === 0xc8) { const n = width(2); if (n === undefined) return; skip = 4 + n; }
|
||||
else if (code === 0xc9) { const n = width(4); if (n === undefined) return; skip = 6 + n; }
|
||||
else if (code === 0xca || code === 0xce || code === 0xd2) skip = 5;
|
||||
else if (code === 0xcb || code === 0xcf || code === 0xd3) skip = 9;
|
||||
else if (code === 0xcc || code === 0xd0) skip = 2;
|
||||
else if (code === 0xcd || code === 0xd1 || code === 0xd4) skip = 3;
|
||||
else if (code === 0xd5) skip = 4;
|
||||
else if (code === 0xd6) skip = 6;
|
||||
else if (code === 0xd7) skip = 10;
|
||||
else if (code === 0xd8) skip = 18;
|
||||
else if (code === 0xdc) { const n = width(2); if (n === undefined) return; container = true; header = 3; children = n; }
|
||||
else if (code === 0xdd) { const n = width(4); if (n === undefined) return; container = true; header = 5; children = n; }
|
||||
else if (code === 0xde) { const n = width(2); if (n === undefined) return; container = true; header = 3; children = 2 * n; }
|
||||
else { const n = width(4); if (n === undefined) return; container = true; header = 5; children = 2 * n; }
|
||||
|
||||
if (container) {
|
||||
if (depth === MAX_PAYLOAD_DEPTH) throw new CultCachePayloadDepthError(MAX_PAYLOAD_DEPTH + 1, MAX_PAYLOAD_DEPTH, subject);
|
||||
position += header;
|
||||
if (children > 0) {
|
||||
remaining[depth++] = children;
|
||||
continue;
|
||||
}
|
||||
} else {
|
||||
position += skip;
|
||||
}
|
||||
|
||||
// One element is complete; close every container it was the last element of.
|
||||
while (depth > 0 && --remaining[depth - 1] === 0) depth--;
|
||||
if (depth === 0) return;
|
||||
}
|
||||
}
|
||||
|
|
@ -5,6 +5,7 @@ import { dirname, resolve } from "node:path";
|
|||
import { decode, encode } from "@msgpack/msgpack";
|
||||
import { z } from "zod";
|
||||
|
||||
import { documentPayloadBytes, documentPayloadFromBytes } from "./document";
|
||||
import { STORE_FORMAT_VERSION, SchemaConflictError, type StoreFormat, StoreUnreadableError, isStoreSnapshot, requireStoreSlots, requireV1RecordSlots } from "./store-format";
|
||||
import type {
|
||||
CacheBackingStore,
|
||||
|
|
@ -248,7 +249,7 @@ function encodeSnapshot(supplied: CultCacheEnvelope[], arrived: CultCacheEnvelop
|
|||
entry.key,
|
||||
schemaIdForEnvelope(entry),
|
||||
entry.storedAt,
|
||||
entry.payload,
|
||||
documentPayloadBytes(entry.payload),
|
||||
]);
|
||||
|
||||
return [
|
||||
|
|
@ -435,7 +436,7 @@ function decodeStoreFile(data: Uint8Array): Omit<SingleFileStoreRead, "absent">
|
|||
type: catalogEntry.schemaName,
|
||||
schemaId: record.schemaId,
|
||||
catalogEntry,
|
||||
payload: record.payload,
|
||||
payload: documentPayloadFromBytes(record.payload),
|
||||
storedAt: record.storedAt,
|
||||
};
|
||||
});
|
||||
|
|
@ -459,7 +460,7 @@ function decodeStoreFile(data: Uint8Array): Omit<SingleFileStoreRead, "absent">
|
|||
payload,
|
||||
};
|
||||
});
|
||||
return { format: STORE_FORMAT_VERSION, envelopes: envelopeArraySchema.parse(normalized) as CultCacheEnvelope[], repairedLegacyPayload };
|
||||
return { format: STORE_FORMAT_VERSION, envelopes: envelopeArraySchema.parse(normalized).map((entry) => ({ ...entry, payload: documentPayloadFromBytes(entry.payload) })) as CultCacheEnvelope[], repairedLegacyPayload };
|
||||
}
|
||||
|
||||
function decodeSnapshot(decoded: unknown): DecodedSnapshot | undefined {
|
||||
|
|
|
|||
|
|
@ -1,3 +1,6 @@
|
|||
import type { SlotsCodec } from "./codec";
|
||||
import type { DocumentPayload } from "./document";
|
||||
|
||||
export type CultCacheIndexScalar = string | number | boolean | bigint;
|
||||
|
||||
export interface CultCacheSchema<TValue = unknown> {
|
||||
|
|
@ -60,6 +63,7 @@ export interface CultCacheDocumentDefinition<TSchema extends CultCacheSchema = C
|
|||
| Readonly<Record<string, CultCacheDocumentAccessor<InferCultCacheSchemaValue<TSchema>>>>
|
||||
| readonly CultCacheDocumentIndexDefinition<InferCultCacheSchemaValue<TSchema>>[];
|
||||
formatter?: CultCacheDocumentFormatter<InferCultCacheSchemaValue<TSchema>>;
|
||||
codec?: SlotsCodec<InferCultCacheSchemaValue<TSchema> & object>;
|
||||
}
|
||||
|
||||
export type CultCacheDocumentValue<TDefinition extends CultCacheDocumentDefinition> = InferCultCacheSchemaValue<
|
||||
|
|
@ -77,7 +81,7 @@ export interface CultCacheDocumentRegistry<
|
|||
export interface CultCacheEnvelope {
|
||||
key: string;
|
||||
type: string;
|
||||
payload: Uint8Array;
|
||||
payload: DocumentPayload;
|
||||
storedAt: string;
|
||||
schemaId?: string;
|
||||
catalogEntry?: CultCacheSchemaCatalogEntry;
|
||||
|
|
|
|||
134
packages/cultcache-ts/src/wire.ts
Normal file
134
packages/cultcache-ts/src/wire.ts
Normal file
|
|
@ -0,0 +1,134 @@
|
|||
// The slice of MessagePack a codec value uses: nil, booleans, integers, floats, strings, binaries and arrays. A codec
|
||||
// must tell an integer from a float and keep 64-bit integers whole, which a general decoder that hands back JS numbers
|
||||
// cannot; so the codec path owns its reader and writer. An integer decodes to a number, or to a bigint when it is
|
||||
// outside the safe range. A float decodes to a WireFloat, whatever its value.
|
||||
|
||||
export class WireFloat {
|
||||
// signalling: a float32 NaN whose quiet bit is clear. The JS number it becomes has lost that payload.
|
||||
constructor(readonly value: number, readonly wide: boolean, readonly signalling = false) {}
|
||||
}
|
||||
|
||||
const SAFE_MIN = BigInt(Number.MIN_SAFE_INTEGER);
|
||||
const SAFE_MAX = BigInt(Number.MAX_SAFE_INTEGER);
|
||||
const utf8 = new TextEncoder();
|
||||
const utf8Decoder = new TextDecoder();
|
||||
|
||||
export function writeWire(tree: unknown): Uint8Array {
|
||||
const parts: number[] = [];
|
||||
put(tree, parts);
|
||||
return Uint8Array.from(parts);
|
||||
}
|
||||
|
||||
function be(parts: number[], bytes: number, value: bigint): void {
|
||||
for (let shift = BigInt((bytes - 1) * 8); shift >= 0n; shift -= 8n) {
|
||||
parts.push(Number((value >> shift) & 0xffn));
|
||||
}
|
||||
}
|
||||
|
||||
function putInt(value: bigint, parts: number[]): void {
|
||||
if (value >= 0n) {
|
||||
if (value < 128n) parts.push(Number(value));
|
||||
else if (value < 0x100n) { parts.push(0xcc); be(parts, 1, value); }
|
||||
else if (value < 0x10000n) { parts.push(0xcd); be(parts, 2, value); }
|
||||
else if (value < 0x100000000n) { parts.push(0xce); be(parts, 4, value); }
|
||||
else if (value < 0x10000000000000000n) { parts.push(0xcf); be(parts, 8, value); }
|
||||
else throw new Error("cannot write an integer wider than 64 bits.");
|
||||
} else if (value >= -32n) parts.push(0x100 + Number(value));
|
||||
else if (value >= -0x80n) { parts.push(0xd0); be(parts, 1, value & 0xffn); }
|
||||
else if (value >= -0x8000n) { parts.push(0xd1); be(parts, 2, value & 0xffffn); }
|
||||
else if (value >= -0x80000000n) { parts.push(0xd2); be(parts, 4, value & 0xffffffffn); }
|
||||
else if (value >= -0x8000000000000000n) { parts.push(0xd3); be(parts, 8, value & 0xffffffffffffffffn); }
|
||||
else throw new Error("cannot write an integer wider than 64 bits.");
|
||||
}
|
||||
|
||||
function putLength(length: number, parts: number[], fix: number, fixMax: number, codes: readonly [number, number, number]): void {
|
||||
if (length <= fixMax) parts.push(fix | length);
|
||||
else if (codes[0] !== 0 && length < 0x100) { parts.push(codes[0]); be(parts, 1, BigInt(length)); }
|
||||
else if (length < 0x10000) { parts.push(codes[1]); be(parts, 2, BigInt(length)); }
|
||||
else { parts.push(codes[2]); be(parts, 4, BigInt(length)); }
|
||||
}
|
||||
|
||||
function put(node: unknown, parts: number[]): void {
|
||||
if (node === null) parts.push(0xc0);
|
||||
else if (typeof node === "boolean") parts.push(node ? 0xc3 : 0xc2);
|
||||
else if (typeof node === "bigint") putInt(node, parts);
|
||||
else if (typeof node === "number") {
|
||||
if (!Number.isSafeInteger(node)) throw new Error("cannot write a number that is not a safe integer; floats are WireFloat.");
|
||||
putInt(BigInt(node), parts);
|
||||
} else if (node instanceof WireFloat) {
|
||||
const view = new DataView(new ArrayBuffer(8));
|
||||
if (node.wide) { view.setFloat64(0, node.value); parts.push(0xcb); } else { view.setFloat32(0, node.value); parts.push(0xca); }
|
||||
for (let index = 0; index < (node.wide ? 8 : 4); index += 1) parts.push(view.getUint8(index));
|
||||
} else if (typeof node === "string") {
|
||||
const text = utf8.encode(node);
|
||||
putLength(text.length, parts, 0xa0, 31, [0xd9, 0xda, 0xdb]);
|
||||
for (const byte of text) parts.push(byte);
|
||||
} else if (node instanceof Uint8Array) {
|
||||
putLength(node.length, parts, 0, -1, [0xc4, 0xc5, 0xc6]);
|
||||
for (const byte of node) parts.push(byte);
|
||||
} else if (Array.isArray(node)) {
|
||||
putLength(node.length, parts, 0x90, 15, [0, 0xdc, 0xdd]);
|
||||
for (const element of node) put(element, parts);
|
||||
} else {
|
||||
throw new Error("cannot write this kind of value.");
|
||||
}
|
||||
}
|
||||
|
||||
export function readWire(payload: Uint8Array): unknown {
|
||||
const view = new DataView(payload.buffer, payload.byteOffset, payload.byteLength);
|
||||
let offset = 0;
|
||||
|
||||
const take = (count: number): number => {
|
||||
if (offset + count > payload.length) throw new Error("the MessagePack payload is truncated.");
|
||||
offset += count;
|
||||
return offset - count;
|
||||
};
|
||||
const integer = (value: bigint): number | bigint => (value >= SAFE_MIN && value <= SAFE_MAX ? Number(value) : value);
|
||||
const string = (length: number): string => utf8Decoder.decode(payload.subarray(take(length), offset));
|
||||
const binary = (length: number): Uint8Array => payload.slice(take(length), offset);
|
||||
const array = (length: number): unknown[] => {
|
||||
const out: unknown[] = [];
|
||||
for (let index = 0; index < length; index += 1) out.push(next());
|
||||
return out;
|
||||
};
|
||||
|
||||
function next(): unknown {
|
||||
const head = payload[take(1)];
|
||||
if (head < 0x80) return head;
|
||||
if (head >= 0xe0) return head - 0x100;
|
||||
if (head >= 0xa0 && head <= 0xbf) return string(head & 0x1f);
|
||||
if (head >= 0x90 && head <= 0x9f) return array(head & 0x0f);
|
||||
switch (head) {
|
||||
case 0xc0: return null;
|
||||
case 0xc2: return false;
|
||||
case 0xc3: return true;
|
||||
case 0xc4: return binary(view.getUint8(take(1)));
|
||||
case 0xc5: return binary(view.getUint16(take(2)));
|
||||
case 0xc6: return binary(view.getUint32(take(4)));
|
||||
case 0xca: {
|
||||
const at = take(4);
|
||||
const bits = view.getUint32(at);
|
||||
return new WireFloat(view.getFloat32(at), false, (bits & 0x7f800000) === 0x7f800000 && (bits & 0x007fffff) !== 0 && (bits & 0x00400000) === 0);
|
||||
}
|
||||
case 0xcb: return new WireFloat(view.getFloat64(take(8)), true);
|
||||
case 0xcc: return view.getUint8(take(1));
|
||||
case 0xcd: return view.getUint16(take(2));
|
||||
case 0xce: return view.getUint32(take(4));
|
||||
case 0xcf: return integer(view.getBigUint64(take(8)));
|
||||
case 0xd0: return view.getInt8(take(1));
|
||||
case 0xd1: return view.getInt16(take(2));
|
||||
case 0xd2: return view.getInt32(take(4));
|
||||
case 0xd3: return integer(view.getBigInt64(take(8)));
|
||||
case 0xd9: return string(view.getUint8(take(1)));
|
||||
case 0xda: return string(view.getUint16(take(2)));
|
||||
case 0xdb: return string(view.getUint32(take(4)));
|
||||
case 0xdc: return array(view.getUint16(take(2)));
|
||||
case 0xdd: return array(view.getUint32(take(4)));
|
||||
default: throw new Error("the MessagePack payload holds a type a codec does not read (map, extension or reserved).");
|
||||
}
|
||||
}
|
||||
|
||||
const tree = next();
|
||||
if (offset !== payload.length) throw new Error("the MessagePack payload has bytes after its value.");
|
||||
return tree;
|
||||
}
|
||||
|
|
@ -13,7 +13,7 @@ import { z } from "zod";
|
|||
|
||||
import { CultCache } from "../src/cult-cache";
|
||||
import { inspectCultCacheBytes } from "../src/cult-cache-inspector";
|
||||
import { defineDocumentRegistry, defineDocumentType } from "../src/document";
|
||||
import { defineDocumentRegistry, defineDocumentType, documentPayloadBytes, documentPayloadFromBytes } from "../src/document";
|
||||
import { SingleFileMessagePackBackingStore, readStoreBytes } from "../src/single-file-messagepack-backing-store";
|
||||
import { SchemaConflictError, StoreUnreadableError } from "../src/store-format";
|
||||
import type { AnyCultCacheDocumentDefinition, CacheBackingStore, CultCacheEnvelope, CultCacheSchema } from "../src/types";
|
||||
|
|
@ -203,7 +203,7 @@ test("CultCache fails closed on unknown or illegal persisted polymorphic state",
|
|||
{
|
||||
key: "mystery",
|
||||
type: "forbidden",
|
||||
payload: encode({ theme: "ash" }),
|
||||
payload: documentPayloadFromBytes(encode({ theme: "ash" })),
|
||||
storedAt: new Date().toISOString(),
|
||||
},
|
||||
]))
|
||||
|
|
@ -220,13 +220,13 @@ test("CultCache fails closed on unknown or illegal persisted polymorphic state",
|
|||
{
|
||||
key: "one",
|
||||
type: "settings",
|
||||
payload: encode({ theme: "ash" }),
|
||||
payload: documentPayloadFromBytes(encode({ theme: "ash" })),
|
||||
storedAt: new Date().toISOString(),
|
||||
},
|
||||
{
|
||||
key: "two",
|
||||
type: "settings",
|
||||
payload: encode({ theme: "ember" }),
|
||||
payload: documentPayloadFromBytes(encode({ theme: "ember" })),
|
||||
storedAt: new Date().toISOString(),
|
||||
},
|
||||
]))
|
||||
|
|
@ -329,6 +329,26 @@ test("CultCache can ingest raw envelopes without re-encoding the payload", async
|
|||
assert.deepEqual(target.getRequiredEnvelope(noteDocument, "note:hello").payload, envelope.payload);
|
||||
});
|
||||
|
||||
test("the cache keeps its own copy of an envelope's bytes: a caller mutating them afterwards changes nothing", async () => {
|
||||
const noteDocument = defineDocumentType({ type: "note", schema: z.object({ title: z.string(), body: z.string() }) });
|
||||
const origin = CultCache.builder().withDocumentType(noteDocument)
|
||||
.withGenericStore(new SingleFileMessagePackBackingStore(join(await mkdtemp(join(tmpdir(), "cultcache-ts-")), "origin.msgpack"))).build();
|
||||
const target = CultCache.builder().withDocumentType(noteDocument)
|
||||
.withGenericStore(new SingleFileMessagePackBackingStore(join(await mkdtemp(join(tmpdir(), "cultcache-ts-")), "target.msgpack"))).build();
|
||||
await origin.put(noteDocument, "note:hello", { title: "Hello", body: "world" });
|
||||
|
||||
const envelope = origin.getRequiredEnvelope(noteDocument, "note:hello");
|
||||
const before = Buffer.from(documentPayloadBytes(envelope.payload));
|
||||
await target.putEnvelope(noteDocument, envelope);
|
||||
documentPayloadBytes(envelope.payload).fill(0);
|
||||
|
||||
assert.deepEqual(Buffer.from(documentPayloadBytes(target.getRequiredEnvelope(noteDocument, "note:hello").payload)), before);
|
||||
const read = target.getRequiredEnvelope(noteDocument, "note:hello");
|
||||
documentPayloadBytes(read.payload).fill(0);
|
||||
assert.deepEqual(Buffer.from(documentPayloadBytes(target.getRequiredEnvelope(noteDocument, "note:hello").payload)), before);
|
||||
assert.deepEqual(target.getRequired(noteDocument, "note:hello"), { title: "Hello", body: "world" });
|
||||
});
|
||||
|
||||
test("SingleFileMessagePackBackingStore writes the CultCache v1 snapshot shape", async () => {
|
||||
const namedDocument = defineDocumentType({
|
||||
type: "tests.named_entry",
|
||||
|
|
@ -642,7 +662,7 @@ async function storeState(path: string): Promise<string[]> {
|
|||
return [];
|
||||
}
|
||||
return (await new SingleFileMessagePackBackingStore(path).pullAll())
|
||||
.map((entry) => `${entry.type}:${entry.key}:${Buffer.from(entry.payload).toString("hex")}`)
|
||||
.map((entry) => `${entry.type}:${entry.key}:${Buffer.from(documentPayloadBytes(entry.payload)).toString("hex")}`)
|
||||
.sort();
|
||||
}
|
||||
|
||||
|
|
@ -813,8 +833,8 @@ test("concurrentGlobalPutsCannotBothReachDisk", async () => {
|
|||
const onDisk = await inner.pullAll();
|
||||
assert.deepEqual(onDisk.map((entry) => entry.key), [CultCache.GLOBAL_KEY]);
|
||||
assert.deepEqual(
|
||||
Buffer.from(onDisk[0].payload),
|
||||
Buffer.from(cache.getRequiredEnvelope(settingsDocument, CultCache.GLOBAL_KEY).payload),
|
||||
Buffer.from(documentPayloadBytes(onDisk[0].payload)),
|
||||
Buffer.from(documentPayloadBytes(cache.getRequiredEnvelope(settingsDocument, CultCache.GLOBAL_KEY).payload)),
|
||||
);
|
||||
assert.deepEqual(cache.getRequiredGlobal(settingsDocument), { t: "second" });
|
||||
const reloaded = build(new SingleFileMessagePackBackingStore(storePath));
|
||||
|
|
@ -1034,7 +1054,7 @@ test("pullWithThrowingIndexAccessorLeavesCacheUnchanged", async () => {
|
|||
await new SingleFileMessagePackBackingStore(storePath).push({
|
||||
...potion,
|
||||
key: "bomb",
|
||||
payload: encode({ name: "Bomb", category: "explosive" }),
|
||||
payload: documentPayloadFromBytes(encode({ name: "Bomb", category: "explosive" })),
|
||||
});
|
||||
|
||||
await assert.rejects(cache.pullAllBackingStores(), /category accessor refuses Bomb/u);
|
||||
|
|
@ -1931,7 +1951,7 @@ async function writeTsInteropStore(
|
|||
members: interopNoteDocument.members,
|
||||
},
|
||||
storedAt: new Date().toISOString(),
|
||||
payload,
|
||||
payload: documentPayloadFromBytes(payload),
|
||||
});
|
||||
return note;
|
||||
}
|
||||
|
|
@ -2186,7 +2206,7 @@ test("SingleFileMessagePackBackingStore refuses a dangling symlink at its path a
|
|||
const file = join(dir, "store.cc");
|
||||
await symlink(join(volume, "store.cc"), file);
|
||||
const store = new SingleFileMessagePackBackingStore(file);
|
||||
const envelope = { key: "k", type: "t", payload: Uint8Array.of(0x90), storedAt: "2026-09-30T00:00:00Z" };
|
||||
const envelope = { key: "k", type: "t", payload: documentPayloadFromBytes(Uint8Array.of(0x90)), storedAt: "2026-09-30T00:00:00Z" };
|
||||
await assert.rejects(
|
||||
() => store.pullAll(),
|
||||
(error: NodeJS.ErrnoException) => error.code === "ENOENT" && error.message.includes("symbolic link") && error.message.includes(file),
|
||||
|
|
@ -2240,7 +2260,7 @@ test("R3 decides resolve-or-refuse: a push through a live link replaces the link
|
|||
const volume = join(dir, "volume");
|
||||
await mkdir(volume);
|
||||
const target = join(volume, "store.cc");
|
||||
const envelope = { key: "a", type: "t", payload: Uint8Array.of(0x90), storedAt: "2026-09-30T00:00:00Z" };
|
||||
const envelope = { key: "a", type: "t", payload: documentPayloadFromBytes(Uint8Array.of(0x90)), storedAt: "2026-09-30T00:00:00Z" };
|
||||
await new SingleFileMessagePackBackingStore(target).push(envelope);
|
||||
const before = await readFile(target);
|
||||
const link = join(dir, "store.cc");
|
||||
|
|
@ -2256,7 +2276,7 @@ test("R3 decides resolve-or-refuse: a pushAll through a dangling link replaces t
|
|||
await mkdir(volume);
|
||||
const link = join(dir, "store.cc");
|
||||
await symlink(join(volume, "store.cc"), link);
|
||||
await new SingleFileMessagePackBackingStore(link).pushAll([{ key: "a", type: "t", payload: Uint8Array.of(0x90), storedAt: "2026-09-30T00:00:00Z" }]);
|
||||
await new SingleFileMessagePackBackingStore(link).pushAll([{ key: "a", type: "t", payload: documentPayloadFromBytes(Uint8Array.of(0x90)), storedAt: "2026-09-30T00:00:00Z" }]);
|
||||
assert.ok((await lstat(link)).isFile());
|
||||
assert.deepEqual(await readdir(volume), []);
|
||||
});
|
||||
|
|
@ -2273,8 +2293,8 @@ test("CultCache inspector refuses the same vectors by name", async () => {
|
|||
test("a v1 store written at the base commit still reads byte for byte", async () => {
|
||||
const envelopes = await pullVector("v1-base.msgpack");
|
||||
assert.deepEqual(envelopes.map((entry) => [entry.key, entry.type]), [["alpha", "vectors.item"], ["beta", "vectors.item"]]);
|
||||
assert.deepEqual([...envelopes[0]!.payload], [0x92, 0xa5, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x01]);
|
||||
assert.deepEqual([...envelopes[1]!.payload], [0x92, 0xa4, 0x62, 0x65, 0x74, 0x61, 0x02]);
|
||||
assert.deepEqual([...documentPayloadBytes(envelopes[0]!.payload)], [0x92, 0xa5, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x01]);
|
||||
assert.deepEqual([...documentPayloadBytes(envelopes[1]!.payload)], [0x92, 0xa4, 0x62, 0x65, 0x74, 0x61, 0x02]);
|
||||
});
|
||||
|
||||
// The element-id marker: tests/vectors/document-variants-c2a/v3-base.msgpack is v1-base with its header replaced.
|
||||
|
|
|
|||
43
packages/cultcache-ts/test/decode-document-payload.test.ts
Normal file
43
packages/cultcache-ts/test/decode-document-payload.test.ts
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
|
||||
import { encode } from "@msgpack/msgpack";
|
||||
import { z } from "zod";
|
||||
|
||||
import { codecs, decodeDocumentPayload, defineDocumentType, documentPayloadBytes, documentPayloadFromBytes, encodeDocumentPayload } from "../src";
|
||||
|
||||
const payloadOf = (bytes: Uint8Array) => documentPayloadFromBytes(bytes);
|
||||
const note = z.object({ id: z.string(), count: z.number() });
|
||||
const plain = defineDocumentType({ type: "t.plain", schemaId: "t.plain.v0", schema: note, name: "id" });
|
||||
const codec = defineDocumentType({
|
||||
type: "t.codec",
|
||||
schemaId: "t.codec.v0",
|
||||
schema: note,
|
||||
name: "id",
|
||||
codec: codecs.slots<{ id: string; count: number }>({ 0: ["id", codecs.string], 1: ["count", codecs.int32] }, "T.Note"),
|
||||
});
|
||||
const formatted = defineDocumentType({
|
||||
type: "t.formatted",
|
||||
schemaId: "t.formatted.v0",
|
||||
schema: note,
|
||||
name: "id",
|
||||
formatter: { encode: (value) => encode([(value as { id: string }).id]), decode: () => ({ id: "from-formatter", count: 0 }) },
|
||||
});
|
||||
|
||||
test("a payload is read by its definition's formatter, a codec's, or a plain map", () => {
|
||||
assert.deepEqual(decodeDocumentPayload(plain, payloadOf(encode({ id: "a", count: 1 }))), { id: "a", count: 1 });
|
||||
assert.deepEqual(decodeDocumentPayload(codec, payloadOf(encode(["a", 1]))), { id: "a", count: 1 });
|
||||
assert.deepEqual(decodeDocumentPayload(formatted, payloadOf(new Uint8Array([0xc0]))), { id: "from-formatter", count: 0 });
|
||||
});
|
||||
|
||||
test("a definition that declares both a codec and a formatter is refused where its payload is read", () => {
|
||||
const both = { ...codec, formatter: formatted.formatter } as typeof codec;
|
||||
assert.throws(() => decodeDocumentPayload(both, payloadOf(encode(["a", 1]))), (error: Error) =>
|
||||
error.message === 'CultCache document type "t.codec" declares both a codec and a formatter.');
|
||||
});
|
||||
|
||||
test("a payload is written by its definition's codec or formatter, the way it is read", () => {
|
||||
assert.deepEqual(documentPayloadBytes(encodeDocumentPayload(codec, { id: "a", count: 1 })), encode(["a", 1]));
|
||||
assert.deepEqual(documentPayloadBytes(encodeDocumentPayload(plain, { id: "a", count: 1 })), encode({ id: "a", count: 1 }));
|
||||
assert.deepEqual(documentPayloadBytes(encodeDocumentPayload(formatted, { id: "a", count: 1 })), encode(["a"]));
|
||||
});
|
||||
273
packages/cultcache-ts/test/payload-depth.test.ts
Normal file
273
packages/cultcache-ts/test/payload-depth.test.ts
Normal file
|
|
@ -0,0 +1,273 @@
|
|||
import assert from "node:assert/strict";
|
||||
import { mkdtemp, readFile, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { test } from "node:test";
|
||||
|
||||
import { encode } from "@msgpack/msgpack";
|
||||
import { z } from "zod";
|
||||
|
||||
import * as root from "../src";
|
||||
import { inspectCultCacheBytes } from "../src/cult-cache-inspector";
|
||||
import {
|
||||
CultCachePayloadDepthError,
|
||||
MAX_PAYLOAD_DEPTH,
|
||||
decodeDocumentPayload,
|
||||
defineDocumentType,
|
||||
documentPayloadBytes,
|
||||
documentPayloadFromBytes,
|
||||
encodeDocumentPayload,
|
||||
} from "../src/document";
|
||||
import * as codecs from "../src/codec";
|
||||
import { checkPayloadDepth } from "../src/payload-depth";
|
||||
import { SingleFileMessagePackBackingStore } from "../src/single-file-messagepack-backing-store";
|
||||
|
||||
const L = MAX_PAYLOAD_DEPTH;
|
||||
const CANARY = "CANARY-payload-depth-91d3";
|
||||
|
||||
const cat = (...parts: Uint8Array[]) => Uint8Array.from(parts.flatMap((part) => [...part]));
|
||||
const bytes = (...values: number[]) => Uint8Array.from(values);
|
||||
const repeat = (unit: Uint8Array, times: number) => {
|
||||
const out = new Uint8Array(unit.length * times);
|
||||
for (let index = 0; index < times; index += 1) out.set(unit, index * unit.length);
|
||||
return out;
|
||||
};
|
||||
// n containers nested in one another around a leaf; `open` is one container's header with one child (two for a map).
|
||||
const chain = (open: Uint8Array, n: number, leaf: Uint8Array = bytes(0xc0)) => cat(repeat(open, n), leaf);
|
||||
const arrays = (n: number, leaf?: Uint8Array) => chain(bytes(0x91), n, leaf);
|
||||
|
||||
const refused = (payload: Uint8Array, label: string) =>
|
||||
assert.throws(() => checkPayloadDepth(payload), (error: unknown) =>
|
||||
error instanceof CultCachePayloadDepthError && error.depth === L + 1 && error.limit === L, label);
|
||||
|
||||
test("the limit is 256: depth 256 passes and 257 is refused, for every array and map header width", () => {
|
||||
assert.equal(L, 256);
|
||||
const kinds: [string, Uint8Array][] = [
|
||||
["fixarray", bytes(0x91)],
|
||||
["array16", bytes(0xdc, 0, 1)],
|
||||
["array32", bytes(0xdd, 0, 0, 0, 1)],
|
||||
["fixmap", bytes(0x81, 0x00)],
|
||||
["map16", bytes(0xde, 0, 1, 0x00)],
|
||||
["map32", bytes(0xdf, 0, 0, 0, 1, 0x00)],
|
||||
];
|
||||
for (const [name, open] of kinds) {
|
||||
assert.doesNotThrow(() => checkPayloadDepth(chain(open, L)), `${name} at the limit`);
|
||||
refused(chain(open, L + 1), `${name} past the limit`);
|
||||
}
|
||||
});
|
||||
|
||||
test("an empty map or array as the innermost container counts like any other", () => {
|
||||
for (const empty of [bytes(0x90), bytes(0x80), bytes(0xdc, 0, 0), bytes(0xdd, 0, 0, 0, 0), bytes(0xde, 0, 0), bytes(0xdf, 0, 0, 0, 0)]) {
|
||||
assert.doesNotThrow(() => checkPayloadDepth(arrays(L - 1, empty)));
|
||||
refused(arrays(L, empty), "empty innermost past the limit");
|
||||
}
|
||||
// [a chain of 255, a chain of 255]: the first sibling closes before the second opens, so the depth is 256, not 511.
|
||||
const sibling = arrays(L - 1);
|
||||
assert.doesNotThrow(() => checkPayloadDepth(cat(bytes(0x92), sibling, sibling)));
|
||||
refused(cat(bytes(0x92), sibling, arrays(L)), "the second sibling is one deeper");
|
||||
// A map's key and value both count as elements: {key: chain, key: chain} closes after four elements.
|
||||
assert.doesNotThrow(() => checkPayloadDepth(cat(bytes(0x82, 0x00), sibling, bytes(0x01), sibling)));
|
||||
refused(cat(bytes(0x82, 0x00), sibling, bytes(0x01), arrays(L)), "the second map value is one deeper");
|
||||
refused(cat(bytes(0x82), arrays(L), sibling, bytes(0x01), sibling), "a map key one deeper");
|
||||
});
|
||||
|
||||
test("a header counts every child it announces, up to the widest of each kind", () => {
|
||||
const nils = (count: number) => repeat(bytes(0xc0), count);
|
||||
const kinds: [string, Uint8Array, number][] = [
|
||||
["the longest fixarray", bytes(0x9f), 15],
|
||||
["the longest fixmap", bytes(0x8f), 30],
|
||||
["array16 of two", bytes(0xdc, 0, 2), 2],
|
||||
["array32 of two", bytes(0xdd, 0, 0, 0, 2), 2],
|
||||
["map16 of two pairs", bytes(0xde, 0, 2), 4],
|
||||
["map32 of two pairs", bytes(0xdf, 0, 0, 0, 2), 4],
|
||||
];
|
||||
for (const [name, header, elements] of kinds) {
|
||||
assert.doesNotThrow(() => checkPayloadDepth(cat(header, nils(elements - 1), arrays(L - 1))), `${name}: the last child at the limit`);
|
||||
refused(cat(header, nils(elements - 1), arrays(L)), `${name}: the last child past it`);
|
||||
}
|
||||
});
|
||||
|
||||
test("every scalar is skipped by its length, whatever bytes it holds", () => {
|
||||
const filler = (count: number) => repeat(bytes(0x91), count);
|
||||
const scalars: [string, Uint8Array][] = [
|
||||
["nil", bytes(0xc0)], ["the never-used 0xc1", bytes(0xc1)], ["false", bytes(0xc2)], ["true", bytes(0xc3)], ["positive fixint", bytes(0x7f)], ["negative fixint", bytes(0xe0)],
|
||||
["uint8", bytes(0xcc, 0x91)], ["uint16", cat(bytes(0xcd), filler(2))], ["uint32", cat(bytes(0xce), filler(4))], ["uint64", cat(bytes(0xcf), filler(8))],
|
||||
["int8", bytes(0xd0, 0x91)], ["int16", cat(bytes(0xd1), filler(2))], ["int32", cat(bytes(0xd2), filler(4))], ["int64", cat(bytes(0xd3), filler(8))],
|
||||
["float32", cat(bytes(0xca), filler(4))], ["float64", cat(bytes(0xcb), filler(8))],
|
||||
["fixext1", cat(bytes(0xd4), filler(2))], ["fixext2", cat(bytes(0xd5), filler(3))], ["fixext4", cat(bytes(0xd6), filler(5))],
|
||||
["fixext8", cat(bytes(0xd7), filler(9))], ["fixext16", cat(bytes(0xd8), filler(17))],
|
||||
["fixstr", cat(bytes(0xa3), filler(3))], ["the longest fixstr", cat(bytes(0xbf), filler(31))], ["str8", cat(bytes(0xd9, 3), filler(3))], ["str16", cat(bytes(0xda, 0, 3), filler(3))],
|
||||
["str32", cat(bytes(0xdb, 0, 0, 0, 3), filler(3))],
|
||||
["bin8", cat(bytes(0xc4, 3), filler(3))], ["bin16", cat(bytes(0xc5, 0, 3), filler(3))], ["bin32", cat(bytes(0xc6, 0, 0, 0, 3), filler(3))],
|
||||
["ext8", cat(bytes(0xc7, 3, 0x7f), filler(3))], ["ext16", cat(bytes(0xc8, 0, 3, 0x7f), filler(3))],
|
||||
["ext32", cat(bytes(0xc9, 0, 0, 0, 3, 0x7f), filler(3))],
|
||||
["str16 of 300 bytes", cat(bytes(0xda, 0x01, 0x2c), filler(300))],
|
||||
];
|
||||
for (const [name, scalar] of scalars) {
|
||||
assert.doesNotThrow(() => checkPayloadDepth(cat(bytes(0x92), scalar, arrays(L - 1))), `${name} then a chain at the limit`);
|
||||
refused(cat(bytes(0x92), scalar, arrays(L)), `${name} then a chain past it`);
|
||||
// As the leaf of a chain: a scalar read at the wrong length leaves containers open, and the sibling chain then reads one deeper.
|
||||
assert.doesNotThrow(() => checkPayloadDepth(cat(bytes(0x92), arrays(L - 1, scalar), arrays(L - 1))), `${name} closes the chain it ends`);
|
||||
}
|
||||
});
|
||||
|
||||
test("a payload that ends early, is empty or carries trailing bytes is the reader's business, not the walk's", () => {
|
||||
for (const early of [[], [0xd9], [0xda, 0], [0xdb, 0, 0, 0], [0xc4], [0xc5, 0], [0xc6, 0, 0, 0], [0xc7], [0xc8, 0], [0xc9, 0, 0, 0], [0xdc, 0], [0xdd, 0, 0, 0], [0xde, 0], [0xdf, 0, 0, 0]]) {
|
||||
assert.doesNotThrow(() => checkPayloadDepth(bytes(...early)), early.map((value) => value.toString(16)).join(" "));
|
||||
}
|
||||
assert.doesNotThrow(() => checkPayloadDepth(arrays(L - 1, bytes(0x91))), "a chain cut off before its leaf");
|
||||
assert.doesNotThrow(() => checkPayloadDepth(cat(bytes(0x90), arrays(L + 50))), "bytes after the first complete value are not walked");
|
||||
assert.doesNotThrow(() => checkPayloadDepth(bytes(0xc0)));
|
||||
});
|
||||
|
||||
test("the walk is iterative: 100000 nested arrays are refused with the depth error, not a RangeError", () => {
|
||||
refused(arrays(100_000), "100000 nested arrays");
|
||||
refused(chain(bytes(0x81, 0x00), 100_000), "100000 nested maps");
|
||||
});
|
||||
|
||||
test("a refusal names the subject, the depth and the limit and never a byte of the payload", () => {
|
||||
const payload = chain(bytes(0x91), L + 1, cat(bytes(0xd9, CANARY.length), new TextEncoder().encode(CANARY)));
|
||||
assert.throws(
|
||||
() => checkPayloadDepth(payload, 'document type "t.note" payload'),
|
||||
(error: unknown) => error instanceof CultCachePayloadDepthError
|
||||
&& error.name === "CultCachePayloadDepthError"
|
||||
&& error.message === 'document type "t.note" payload nests 257 MessagePack containers deep; the limit is 256.',
|
||||
);
|
||||
const canaryPayload = payload;
|
||||
assert.throws(() => checkPayloadDepth(canaryPayload), (error: Error) => !error.message.includes(CANARY) && !JSON.stringify(error).includes(CANARY));
|
||||
});
|
||||
|
||||
const note = z.object({ id: z.string(), count: z.number() });
|
||||
const slotCalls: string[] = [];
|
||||
const watched = { ...codecs.string, decode: (raw: unknown) => (slotCalls.push("decode"), codecs.string.decode(raw)), encode: (value: string) => (slotCalls.push("encode"), codecs.string.encode(value)) };
|
||||
const guarded = defineDocumentType({
|
||||
type: "t.guarded",
|
||||
schemaId: "t.guarded.v0",
|
||||
schema: note,
|
||||
name: "id",
|
||||
codec: codecs.slots<{ id: string; count: number }>({ 0: ["id", watched], 1: ["count", codecs.int32] }, "T.Guarded"),
|
||||
});
|
||||
|
||||
test("the owner refuses a payload past the limit before a codec reads it, and a codec's bytes before they are wrapped", () => {
|
||||
assert.throws(() => decodeDocumentPayload(guarded, documentPayloadFromBytes(arrays(L + 1))), CultCachePayloadDepthError);
|
||||
assert.deepEqual(slotCalls, [], "the codec never saw the deep payload");
|
||||
assert.deepEqual(decodeDocumentPayload(guarded, documentPayloadFromBytes(encode(["a", 1]))), { id: "a", count: 1 });
|
||||
|
||||
const formatterBytes = (value: unknown) => documentPayloadBytes(encodeDocumentPayload(guarded, value));
|
||||
assert.deepEqual(formatterBytes({ id: "a", count: 1 }), encode(["a", 1]));
|
||||
});
|
||||
|
||||
test("a document without a codec or formatter writes a value L deep and refuses L+1 by the walk", () => {
|
||||
const anything = defineDocumentType({ type: "t.any", schemaId: "t.any.v0", schema: z.any(), name: "id" });
|
||||
const nest = (n: number): unknown => (n === 1 ? [] : [nest(n - 1)]);
|
||||
const atLimit = encodeDocumentPayload(anything, nest(L));
|
||||
assert.deepEqual(documentPayloadBytes(atLimit), encode(nest(L), { maxDepth: 1000 }));
|
||||
assert.deepEqual(decodeDocumentPayload(anything, atLimit), nest(L));
|
||||
assert.throws(() => encodeDocumentPayload(anything, nest(L + 1)), (error: unknown) =>
|
||||
error instanceof CultCachePayloadDepthError && error.depth === L + 1 && error.limit === L
|
||||
&& error.message === 'document type "t.any" value nests 257 MessagePack containers deep; the limit is 256.');
|
||||
assert.throws(() => decodeDocumentPayload(anything, documentPayloadFromBytes(arrays(L + 1))), CultCachePayloadDepthError);
|
||||
});
|
||||
|
||||
test("the limit and its error are exported from the root, and the walk itself is not", () => {
|
||||
assert.equal(root.MAX_PAYLOAD_DEPTH, 256);
|
||||
assert.equal(root.CultCachePayloadDepthError, CultCachePayloadDepthError);
|
||||
assert.equal("checkPayloadDepth" in root, false);
|
||||
});
|
||||
|
||||
// A v1 store whose one record carries `payload` as bin and no catalog entry, so the record's schema is inferred from the
|
||||
// payload's first element.
|
||||
async function storeWith(payload: Uint8Array): Promise<string> {
|
||||
const file = join(await mkdtemp(join(tmpdir(), "cultcache-payload-depth-")), "deep.cc");
|
||||
await writeFile(file, encode(["cultcache.store.v1", [], [["record-1", "sha256:stale", "2026-06-25T12:00:00Z", payload]]]));
|
||||
return file;
|
||||
}
|
||||
const stamped = (containersInsideTheStamp: number) =>
|
||||
cat(bytes(0x92), encode("tests.schema_stamped_entry.v1"), arrays(containersInsideTheStamp));
|
||||
|
||||
test("the inspector previews a payload at the limit and reports one past it, or 100000 deep, as a decode error", async () => {
|
||||
const atLimit = await storeWith(stamped(L - 1));
|
||||
const previewed = inspectCultCacheBytes(atLimit, await readFile(atLimit)).records[0]!;
|
||||
assert.equal(previewed.payloadDecodeError, undefined);
|
||||
assert.equal(previewed.schemaName, "tests.schema_stamped_entry", "a payload the walk accepts yields its stamp");
|
||||
|
||||
for (const inside of [L, 100_000]) {
|
||||
const file = await storeWith(stamped(inside));
|
||||
const record = inspectCultCacheBytes(file, await readFile(file)).records[0]!;
|
||||
assert.equal(record.payloadDecodeError, "document payload nests 257 MessagePack containers deep; the limit is 256.");
|
||||
assert.equal(record.schemaName, "<missing catalog entry>", "the stamp of a payload the walk refuses is not recovered");
|
||||
}
|
||||
});
|
||||
|
||||
test("the single-file store infers a legacy record's schema from a payload at the limit and from none past it", async () => {
|
||||
const atLimit = await storeWith(stamped(L - 1));
|
||||
const [read] = await new SingleFileMessagePackBackingStore(atLimit).pullAll();
|
||||
assert.equal(read.catalogEntry?.schemaVersion, "tests.schema_stamped_entry.v1");
|
||||
|
||||
const past = await storeWith(stamped(L));
|
||||
await assert.rejects(() => new SingleFileMessagePackBackingStore(past).pullAll(), /missing schema id/u);
|
||||
});
|
||||
|
||||
// A header whose length or count needs all four bytes: the low sixteen bits of the length are small, the whole is not.
|
||||
const be32 = (n: number) => bytes((n >>> 24) & 0xff, (n >>> 16) & 0xff, (n >>> 8) & 0xff, n & 0xff);
|
||||
|
||||
test("a 32-bit length or count is read whole: the walk skips a 65539-byte scalar and counts 65540 children", () => {
|
||||
const blob = repeat(bytes(0x91), 65539);
|
||||
const scalars: [string, Uint8Array][] = [
|
||||
["bin32", cat(bytes(0xc6), be32(65539), blob)],
|
||||
["str32", cat(bytes(0xdb), be32(65539), blob)],
|
||||
["ext32", cat(bytes(0xc9), be32(65539), bytes(0x7f), blob)],
|
||||
];
|
||||
for (const [name, scalar] of scalars) {
|
||||
assert.doesNotThrow(() => checkPayloadDepth(cat(bytes(0x92), scalar, arrays(L - 1))), `${name} of 65539 bytes then a chain at the limit`);
|
||||
refused(cat(bytes(0x92), scalar, arrays(L)), `${name} of 65539 bytes then a chain past it`);
|
||||
}
|
||||
// Both counts exceed 65535 and their low sixteen bits are small (4 children; 1 pair), so a count cut to 16 bits closes the container early.
|
||||
const wide: [string, Uint8Array, number][] = [
|
||||
["array32", cat(bytes(0xdd), be32(65540)), 65540],
|
||||
["map32", cat(bytes(0xdf), be32(65537)), 2 * 65537],
|
||||
];
|
||||
for (const [name, header, children] of wide) {
|
||||
const nils = repeat(bytes(0xc0), children);
|
||||
refused(cat(bytes(0x92), header, nils, arrays(L)), `${name} announcing more than 65535: the sibling chain past the limit`);
|
||||
assert.doesNotThrow(() => checkPayloadDepth(cat(bytes(0x92), header, nils, arrays(L - 1))), `${name}: the sibling chain at the limit`);
|
||||
}
|
||||
});
|
||||
|
||||
test("a user formatter's bytes are its own: a 0x91 grey image round-trips, while plain and codec documents are still walked", () => {
|
||||
const grey = defineDocumentType({
|
||||
type: "t.grey",
|
||||
schemaId: "t.grey.v0",
|
||||
schema: z.object({ pixels: z.custom<Uint8Array>() }),
|
||||
name: "pixels",
|
||||
formatter: { encode: (value) => (value as { pixels: Uint8Array }).pixels, decode: (payload) => ({ pixels: payload }) },
|
||||
});
|
||||
for (const size of [300, 4096]) {
|
||||
const pixels = new Uint8Array(size).fill(0x91);
|
||||
const written = encodeDocumentPayload(grey, { pixels });
|
||||
assert.deepEqual(documentPayloadBytes(written), pixels, `${size} bytes written as the formatter made them`);
|
||||
assert.deepEqual(decodeDocumentPayload(grey, written), { pixels }, `${size} bytes read back through the formatter`);
|
||||
}
|
||||
|
||||
const anything = defineDocumentType({ type: "t.any2", schemaId: "t.any2.v0", schema: z.any(), name: "id" });
|
||||
const nest = (n: number): unknown => (n === 1 ? [] : [nest(n - 1)]);
|
||||
assert.throws(() => encodeDocumentPayload(anything, nest(L + 1)), CultCachePayloadDepthError);
|
||||
assert.throws(() => decodeDocumentPayload(anything, documentPayloadFromBytes(arrays(L + 1))), CultCachePayloadDepthError);
|
||||
|
||||
// A slot that writes `depth` nested arrays, so a codec document can be made as deep as the test needs.
|
||||
const nested: codecs.Codec<number> = {
|
||||
typeName: "System.Object",
|
||||
encode: (depth) => nest(depth),
|
||||
decode: (raw) => (raw as unknown[]).length,
|
||||
};
|
||||
const coded = defineDocumentType({
|
||||
type: "t.coded",
|
||||
schemaId: "t.coded.v0",
|
||||
schema: z.any(),
|
||||
name: "id",
|
||||
codec: codecs.slots<{ id: string; depth: number }>({ 0: ["id", codecs.string], 1: ["depth", nested] }, "T.Coded"),
|
||||
});
|
||||
assert.doesNotThrow(() => encodeDocumentPayload(coded, { id: "a", depth: L - 1 }));
|
||||
assert.throws(() => encodeDocumentPayload(coded, { id: "a", depth: L }), CultCachePayloadDepthError);
|
||||
assert.throws(() => decodeDocumentPayload(coded, documentPayloadFromBytes(arrays(L + 1))), CultCachePayloadDepthError);
|
||||
});
|
||||
61
packages/cultcache-ts/test/payload-type.test.ts
Normal file
61
packages/cultcache-ts/test/payload-type.test.ts
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
|
||||
import { decode, encode } from "@msgpack/msgpack";
|
||||
import { z } from "zod";
|
||||
|
||||
import {
|
||||
decodeDocumentPayload,
|
||||
defineDocumentType,
|
||||
documentPayloadBytes,
|
||||
documentPayloadFromBytes,
|
||||
encodeDocumentPayload,
|
||||
type AnyCultCacheDocumentDefinition,
|
||||
type CultCacheEnvelope,
|
||||
type DocumentPayload,
|
||||
} from "../src";
|
||||
|
||||
// The rule: a document payload is read only through its definition. The type is the enforcement, so this file is the
|
||||
// proof: tsc compiles it only if every line below that carries @ts-expect-error is an error. A line that starts to
|
||||
// compile makes its @ts-expect-error unused, which is itself an error, so the suite stops until the payload is opaque
|
||||
// again. The function is never called; the lines are not meant to run.
|
||||
export function refusedReaders(envelope: CultCacheEnvelope, definition: AnyCultCacheDocumentDefinition, payload: DocumentPayload): void {
|
||||
// @ts-expect-error a plain msgpack decoder does not accept a document payload
|
||||
decode(envelope.payload);
|
||||
// @ts-expect-error a payload is not assignable to bytes
|
||||
const bytes: Uint8Array = envelope.payload;
|
||||
// @ts-expect-error nor is it a byte source a copy may be taken from
|
||||
new Uint8Array(envelope.payload);
|
||||
// @ts-expect-error a definition's formatter reads bytes, not a payload; the owner unwraps for it
|
||||
definition.formatter!.decode(envelope.payload);
|
||||
// @ts-expect-error the owner needs the definition that says how the bytes are laid out
|
||||
decodeDocumentPayload(undefined, payload);
|
||||
// @ts-expect-error bytes are not a payload until they enter by name
|
||||
const forged: DocumentPayload = new Uint8Array();
|
||||
void [bytes, forged];
|
||||
}
|
||||
|
||||
const note = defineDocumentType({
|
||||
type: "t.note",
|
||||
schemaId: "t.note.v0",
|
||||
schema: z.object({ id: z.string(), count: z.number() }),
|
||||
name: "id",
|
||||
});
|
||||
|
||||
test("a payload is the same bytes at run time, so frames and stores see no change", () => {
|
||||
const bytes = encode({ id: "a", count: 1 });
|
||||
const payload = documentPayloadFromBytes(bytes);
|
||||
assert.equal(documentPayloadBytes(payload), bytes);
|
||||
assert.equal(payload.byteLength, bytes.byteLength);
|
||||
});
|
||||
|
||||
test("the owner writes a payload through the definition's schema and reads it back through the same one", () => {
|
||||
const payload = encodeDocumentPayload(note, { id: "a", count: 1 });
|
||||
assert.deepEqual(decode(documentPayloadBytes(payload)), { id: "a", count: 1 });
|
||||
assert.deepEqual(decodeDocumentPayload(note, payload), { id: "a", count: 1 });
|
||||
// A refusal names the field and never echoes the value it refused.
|
||||
const refusesWithoutEchoing = (action: () => unknown) =>
|
||||
assert.throws(action, (error: Error) => /count/.test(error.message) && !error.message.includes("canary-value"));
|
||||
refusesWithoutEchoing(() => encodeDocumentPayload(note, { id: "a", count: "canary-value" }));
|
||||
refusesWithoutEchoing(() => decodeDocumentPayload(note, documentPayloadFromBytes(encode({ id: "a", count: "canary-value" }))));
|
||||
});
|
||||
893
packages/cultcache-ts/test/union-parity.test.ts
Normal file
893
packages/cultcache-ts/test/union-parity.test.ts
Normal file
|
|
@ -0,0 +1,893 @@
|
|||
import assert from "node:assert/strict";
|
||||
import { existsSync } from "node:fs";
|
||||
import { mkdtemp, readFile, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join, resolve } from "node:path";
|
||||
import { test } from "node:test";
|
||||
|
||||
import { decode, encode } from "@msgpack/msgpack";
|
||||
import { z } from "zod";
|
||||
|
||||
import { codecs } from "../src";
|
||||
import { MAX_SLOT_KEY, type Codec } from "../src/codec";
|
||||
import { CultCache } from "../src/cult-cache";
|
||||
import { readWire, WireFloat, writeWire } from "../src/wire";
|
||||
import {
|
||||
CultCachePayloadDepthError,
|
||||
MAX_PAYLOAD_DEPTH,
|
||||
decodeDocumentPayload,
|
||||
defineDocumentType,
|
||||
documentPayloadBytes,
|
||||
documentPayloadFromBytes,
|
||||
encodeDocumentPayload,
|
||||
} from "../src/document";
|
||||
import { SingleFileMessagePackBackingStore } from "../src/single-file-messagepack-backing-store";
|
||||
import type { AnyCultCacheDocumentDefinition, CacheBackingStore, CultCacheEnvelope } from "../src/types";
|
||||
|
||||
const { array, boolean, bytes, float32, float64, int32, int64, lazy, list, nullable, slots, string, union, unit } = codecs;
|
||||
|
||||
// The names the C# reference gives the fixture's types (CultSchemaTypeNames.FromType), as union-surface.cc carries them.
|
||||
const CS = "GameCult.Caching.Tests.UnionParityVectorTests+";
|
||||
|
||||
// The golden is tests/vectors/union-parity, written by the C# reference. Everything below that is bytes or an expected
|
||||
// outcome is read from those committed files; only the value the payload must decode to is spelled here.
|
||||
function findVectors(from: string): string {
|
||||
for (let dir = from; ; dir = resolve(dir, "..")) {
|
||||
if (existsSync(join(dir, "tests", "vectors", "union-parity"))) return join(dir, "tests", "vectors", "union-parity");
|
||||
if (resolve(dir, "..") === dir) throw new Error("tests/vectors/union-parity not found above the test.");
|
||||
}
|
||||
}
|
||||
const vectors = findVectors(__dirname);
|
||||
const read = async (name: string) => new Uint8Array(await readFile(join(vectors, name)));
|
||||
|
||||
// The string the C# writer put inside every refusal payload, to prove a refusal never echoes the payload.
|
||||
const CANARY = "CANARY-union-golden-4c2a";
|
||||
|
||||
type Node =
|
||||
| { kind: "Box"; id: string; children: (Node | null)[] }
|
||||
| { kind: "Text"; id: string; content: string }
|
||||
| { kind: "Use"; id: string; composition: Composition; slots: (Node | null)[] }
|
||||
| { kind: "Image"; id: string; uri: string; alt: string }
|
||||
| { kind: "Wrap"; inner: Node | null };
|
||||
interface Composition { name: string; body: Node | null }
|
||||
type Outcome = { kind: "Pending"; message: string } | { kind: "Completed"; sourceVersion: number } | { kind: "Denied" } | { kind: "Floor" } | { kind: "Ceiling" };
|
||||
type Item = { kind: "Gem"; name: string } | { kind: "Tool"; name: string; uses: number } | { kind: "Part"; name: string; count: number };
|
||||
type CraftedItem = { kind: "Tool"; name: string; uses: number } | { kind: "Part"; name: string; count: number };
|
||||
interface Surface {
|
||||
id: string;
|
||||
version: number;
|
||||
root: Node | null;
|
||||
outcomes: (Outcome | null)[];
|
||||
part: Item | null;
|
||||
crafted: CraftedItem | null;
|
||||
missing: Node | null;
|
||||
}
|
||||
|
||||
const composition = slots<Composition>({ 0: ["name", string], 1: ["body", lazy(() => node)] }, `${CS}Composition`);
|
||||
const node: Codec<Node | null> = union<Node>("Node", {
|
||||
0: ["Box", slots<{ id: string; children: (Node | null)[] }>({ 0: ["id", string], 1: ["children", list(lazy(() => node))] })],
|
||||
1: ["Text", slots<{ id: string; content: string }>({ 0: ["id", string], 1: ["content", string] })],
|
||||
2: ["Use", slots<{ id: string; composition: Composition; slots: (Node | null)[] }>({
|
||||
0: ["id", string], 1: ["composition", composition], 2: ["slots", list(lazy(() => node))],
|
||||
})],
|
||||
5: ["Image", slots<{ id: string; uri: string; alt: string }>({ 0: ["id", string], 1: ["uri", string], 3: ["alt", string] })],
|
||||
6: ["Wrap", slots<{ inner: Node | null }>({ 0: ["inner", lazy(() => node)] })],
|
||||
}, `${CS}Node`);
|
||||
const outcome = union<Outcome>("Outcome", {
|
||||
0: ["Pending", slots<{ message: string }>({ 0: ["message", string] })],
|
||||
1: ["Completed", slots<{ sourceVersion: number }>({ 0: ["sourceVersion", int32] })],
|
||||
2: ["Denied", unit],
|
||||
[-2147483648]: ["Floor", unit],
|
||||
2147483647: ["Ceiling", unit],
|
||||
}, `${CS}Outcome`);
|
||||
const toolArm = slots<{ name: string; uses: number }>({ 0: ["name", string], 1: ["uses", int32] });
|
||||
const partArm = slots<{ name: string; count: number }>({ 0: ["name", string], 1: ["count", int32] });
|
||||
const item = union<Item>("Item", {
|
||||
0: ["Gem", slots<{ name: string }>({ 0: ["name", string] })],
|
||||
1: ["Tool", toolArm],
|
||||
2: ["Part", partArm],
|
||||
}, `${CS}Item`);
|
||||
const craftedItem = union<CraftedItem>("CraftedItem", { 0: ["Tool", toolArm], 1: ["Part", partArm] }, `${CS}CraftedItem`);
|
||||
const surfaceCodec = slots<Surface>({
|
||||
0: ["id", string],
|
||||
1: ["version", int32],
|
||||
2: ["root", node],
|
||||
3: ["outcomes", list(outcome)],
|
||||
4: ["part", item],
|
||||
5: ["crafted", craftedItem],
|
||||
6: ["missing", node, null],
|
||||
}, `${CS}UnionSurface`);
|
||||
|
||||
const nodeSchema: z.ZodType<Node | null> = z.lazy(() =>
|
||||
z.union([
|
||||
z.null(),
|
||||
z.discriminatedUnion("kind", [
|
||||
z.object({ kind: z.literal("Box"), id: z.string(), children: z.array(nodeSchema) }),
|
||||
z.object({ kind: z.literal("Text"), id: z.string(), content: z.string() }),
|
||||
z.object({
|
||||
kind: z.literal("Use"),
|
||||
id: z.string(),
|
||||
composition: z.object({ name: z.string(), body: nodeSchema }),
|
||||
slots: z.array(nodeSchema),
|
||||
}),
|
||||
z.object({ kind: z.literal("Image"), id: z.string(), uri: z.string(), alt: z.string() }),
|
||||
z.object({ kind: z.literal("Wrap"), inner: nodeSchema }),
|
||||
]),
|
||||
]));
|
||||
const surfaceSchema = z.object({
|
||||
id: z.string(),
|
||||
version: z.number(),
|
||||
root: nodeSchema,
|
||||
outcomes: z.array(z.union([
|
||||
z.null(),
|
||||
z.discriminatedUnion("kind", [
|
||||
z.object({ kind: z.literal("Pending"), message: z.string() }),
|
||||
z.object({ kind: z.literal("Completed"), sourceVersion: z.number() }),
|
||||
z.object({ kind: z.literal("Denied") }),
|
||||
z.object({ kind: z.literal("Floor") }),
|
||||
z.object({ kind: z.literal("Ceiling") }),
|
||||
]),
|
||||
])),
|
||||
part: z.union([z.null(), z.discriminatedUnion("kind", [
|
||||
z.object({ kind: z.literal("Gem"), name: z.string() }),
|
||||
z.object({ kind: z.literal("Tool"), name: z.string(), uses: z.number() }),
|
||||
z.object({ kind: z.literal("Part"), name: z.string(), count: z.number() }),
|
||||
])]),
|
||||
crafted: z.union([z.null(), z.discriminatedUnion("kind", [
|
||||
z.object({ kind: z.literal("Tool"), name: z.string(), uses: z.number() }),
|
||||
z.object({ kind: z.literal("Part"), name: z.string(), count: z.number() }),
|
||||
])]),
|
||||
missing: nodeSchema,
|
||||
}) as unknown as z.ZodType<Surface>;
|
||||
|
||||
function surfaceDocument(schemaId?: string) {
|
||||
return defineDocumentType({
|
||||
type: "tests.union_surface",
|
||||
schemaId: schemaId ?? "tests.union_surface.v1",
|
||||
schemaName: "tests.union_surface",
|
||||
schemaVersion: "tests.union_surface.v1",
|
||||
schema: surfaceSchema,
|
||||
codec: surfaceCodec,
|
||||
name: "id",
|
||||
});
|
||||
}
|
||||
|
||||
const golden: Surface = {
|
||||
id: "surface",
|
||||
version: 3,
|
||||
root: {
|
||||
kind: "Box",
|
||||
id: "root",
|
||||
children: [
|
||||
{ kind: "Text", id: "t1", content: "hello" },
|
||||
{
|
||||
kind: "Use",
|
||||
id: "u1",
|
||||
composition: {
|
||||
name: "comp",
|
||||
body: {
|
||||
kind: "Box",
|
||||
id: "inner",
|
||||
children: [
|
||||
{ kind: "Text", id: "deep", content: "x" },
|
||||
{ kind: "Image", id: "img", uri: "uri://a", alt: "alt" },
|
||||
],
|
||||
},
|
||||
},
|
||||
slots: [{ kind: "Text", id: "s1", content: "slot" }, null, { kind: "Box", id: "b2", children: [] }],
|
||||
},
|
||||
{ kind: "Image", id: "i2", uri: "uri://b", alt: "" },
|
||||
],
|
||||
},
|
||||
outcomes: [{ kind: "Pending", message: "wait" }, { kind: "Completed", sourceVersion: 7 }, { kind: "Denied" }],
|
||||
part: { kind: "Tool", name: "hammer", uses: 12 },
|
||||
crafted: { kind: "Part", name: "gear", count: 4 },
|
||||
missing: null,
|
||||
};
|
||||
|
||||
const hex = (data: Uint8Array) => Buffer.from(data).toString("hex");
|
||||
|
||||
async function outcomeEntries() {
|
||||
const entries = decode(await read("outcomes.msgpack")) as [string, string, string, number | null, string][];
|
||||
return entries.map(([file, outcome, unionName, key, detail]) => ({ file, outcome, unionName, key, detail }));
|
||||
}
|
||||
|
||||
test("the union surface vector decodes to the constructed value and re-encodes byte-identical", async () => {
|
||||
const committed = await read("union-surface.msgpack");
|
||||
const decoded = surfaceCodec.decode(readWire(committed));
|
||||
assert.deepEqual(decoded, golden);
|
||||
assert.equal(hex(writeWire(surfaceCodec.encode(decoded))), hex(committed));
|
||||
assert.equal(hex(writeWire(surfaceCodec.encode(golden))), hex(committed));
|
||||
});
|
||||
|
||||
test("a unit arm is written [key, []] and its payload must be an array", () => {
|
||||
assert.deepEqual(outcome.encode({ kind: "Denied" }), [2, []]);
|
||||
assert.throws(() => outcome.decode([2, null]), /Union Outcome/u);
|
||||
});
|
||||
|
||||
test("union-surface.cc reads through SingleFileMessagePackBackingStore and writes the same payload", async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), "union-parity-"));
|
||||
const file = join(dir, "union-surface.cc");
|
||||
await writeFile(file, await read("union-surface.cc"));
|
||||
const [envelope] = await new SingleFileMessagePackBackingStore(file).pullAll();
|
||||
assert.equal(hex(documentPayloadBytes(envelope.payload)), hex(await read("union-surface.msgpack")));
|
||||
|
||||
const document = surfaceDocument(envelope.schemaId);
|
||||
const cache = CultCache.builder().withDocumentType(document).withGenericStore(new SingleFileMessagePackBackingStore(file)).build();
|
||||
await cache.pullAllBackingStores();
|
||||
assert.deepEqual(cache.get(document, envelope.key), golden);
|
||||
|
||||
const written = join(dir, "written.cc");
|
||||
const fresh = CultCache.builder().withDocumentType(document).withGenericStore(new SingleFileMessagePackBackingStore(written)).build();
|
||||
await fresh.put(document, envelope.key, golden);
|
||||
const [rewritten] = await new SingleFileMessagePackBackingStore(written).pullAll();
|
||||
assert.equal(hex(documentPayloadBytes(rewritten.payload)), hex(documentPayloadBytes(envelope.payload)));
|
||||
|
||||
// The reference refuses a store whose schema catalog names another type for a slot, so the catalog TS writes must be
|
||||
// the one C# wrote: same canonical schema text, same member names, slots and types.
|
||||
assert.equal(rewritten.catalogEntry!.canonicalSchemaJson, envelope.catalogEntry!.canonicalSchemaJson);
|
||||
const shape = (members: readonly { slot: number; memberName: string; typeName: string; isName?: boolean }[]) =>
|
||||
members.map((member) => [member.slot, member.memberName, member.typeName, member.isName === true]);
|
||||
assert.deepEqual(shape(rewritten.catalogEntry!.members!), shape(envelope.catalogEntry!.members!));
|
||||
assert.equal(rewritten.catalogEntry!.members!.length, 7);
|
||||
});
|
||||
|
||||
test("every outcome vector is listed and holds: refusals name the union and key, never the payload", async () => {
|
||||
const entries = await outcomeEntries();
|
||||
assert.equal(entries.length, 9);
|
||||
const document = surfaceDocument();
|
||||
let refused = 0;
|
||||
const carrying: string[] = [];
|
||||
let readOnly = 0;
|
||||
|
||||
for (const { file, outcome: expected, unionName, key, detail } of entries) {
|
||||
const payload = await read(file);
|
||||
if (expected === "refused") {
|
||||
refused += 1;
|
||||
if (Buffer.from(payload).includes(CANARY)) carrying.push(file);
|
||||
assert.throws(
|
||||
() => surfaceCodec.decode(readWire(payload)),
|
||||
(error: Error) => {
|
||||
assert.ok(!error.message.includes(CANARY), `${file}: the refusal echoed the payload`);
|
||||
if (detail === "arity") {
|
||||
return error.message.includes(`Union ${unionName}`) && error.message.includes("expected [key, slots]");
|
||||
}
|
||||
return error.message.includes(`Union ${unionName}:`) && error.message.includes(`key ${key} `);
|
||||
},
|
||||
file,
|
||||
);
|
||||
const refusingCache = CultCache.builder().withDocumentType(document).withGenericStore(memoryStore([envelopeOf(payload)])).build();
|
||||
await assert.rejects(() => refusingCache.pullAllBackingStores(), new RegExp(`Union ${unionName}`, "u"), file);
|
||||
} else {
|
||||
readOnly += 1;
|
||||
assert.equal(expected, "read-only");
|
||||
assert.deepEqual(surfaceCodec.decode(readWire(payload)), golden, `${file}: the extra slot is read past`);
|
||||
}
|
||||
}
|
||||
assert.deepEqual([refused, readOnly], [5, 4]);
|
||||
assert.deepEqual(carrying, ["unknown-arm-field.msgpack", "unknown-arm-list.msgpack", "unknown-arm-nested.msgpack"], "the canary is in the payloads whose arm is unknown");
|
||||
});
|
||||
|
||||
test("a refusal lists the declared keys, so a key only the outer union declares is unknown to the inner", async () => {
|
||||
const entry = (await outcomeEntries()).find((candidate) => candidate.file === "inner-union-outer-key.msgpack")!;
|
||||
const payload = readWire(await read(entry.file)) as unknown[];
|
||||
assert.throws(
|
||||
() => surfaceCodec.decode(payload),
|
||||
/Union CraftedItem: unknown arm key 2 \(declared keys: 0, 1\)\./u,
|
||||
);
|
||||
});
|
||||
|
||||
test("an arm that is not [key, slots] is refused naming the union, and a non-integer key is not echoed", () => {
|
||||
for (const bad of [[1], [1, null], [1, [], []], "x", 7, {}]) {
|
||||
assert.throws(() => node.decode(bad), /^Error: Union Node: expected \[key, slots\]/u);
|
||||
}
|
||||
assert.throws(
|
||||
() => node.decode([CANARY, []]),
|
||||
(error: Error) => error.message.includes("Union Node") && error.message.includes("not an integer") && !error.message.includes(CANARY),
|
||||
);
|
||||
});
|
||||
|
||||
test("an arm key that is not a declared key is refused, with no fallback", () => {
|
||||
assert.throws(() => node.decode([4, []]), /Union Node: unknown arm key 4 \(declared keys: 0, 1, 2, 5, 6\)/u);
|
||||
assert.throws(() => outcome.decode([3, []]), /Union Outcome: unknown arm key 3/u);
|
||||
});
|
||||
|
||||
test("a union encodes by kind and refuses a kind it does not declare without echoing it", () => {
|
||||
assert.deepEqual(node.encode({ kind: "Text", id: "a", content: "b" }), [1, ["a", "b"]]);
|
||||
assert.equal(node.encode(null), null);
|
||||
assert.throws(
|
||||
() => node.encode({ kind: CANARY, id: "a" } as unknown as Node),
|
||||
(error: Error) => error.message.includes("Union Node") && !error.message.includes(CANARY),
|
||||
);
|
||||
});
|
||||
|
||||
test("slots: a gap writes nil, a missing slot reads its default, one without a default is refused naming the slot", () => {
|
||||
const record = slots<{ a: string; c: string; d: number }>({ 0: ["a", string], 2: ["c", string], 4: ["d", int32, 9] });
|
||||
assert.deepEqual(record.encode({ a: "x", c: "y", d: 1 }), ["x", null, "y", null, 1]);
|
||||
assert.deepEqual(record.decode(["x", null, "y"]), { a: "x", c: "y", d: 9 });
|
||||
assert.deepEqual(record.decode(["x", 5, "y", null]), { a: "x", c: "y", d: 9 });
|
||||
assert.throws(() => record.decode(["x", 5, "y", null, null]), { message: "d (slot 4): expected an int32, found nil" });
|
||||
assert.throws(() => record.decode(["x"]), /c \(slot 2\): the slot is missing and declares no default/u);
|
||||
assert.deepEqual(record.decode(["x", null, "y", null, 1, "extra", "slots"]), { a: "x", c: "y", d: 1 });
|
||||
assert.throws(() => record.decode({ a: "x" }), /expected an array of slots/u);
|
||||
});
|
||||
|
||||
test("slots: a default may be a function and fills only a missing slot, never a nil", () => {
|
||||
const record = slots<{ tags: string[] }>({ 0: ["tags", list(string), () => ["fresh"]] });
|
||||
assert.deepEqual(record.decode([]), { tags: ["fresh"] });
|
||||
assert.deepEqual(record.decode([null]), { tags: null });
|
||||
const counted = slots<{ n: number }>({ 0: ["n", int32, 4] });
|
||||
assert.deepEqual(counted.decode([]), { n: 4 });
|
||||
assert.throws(() => counted.decode([null]), { message: "n (slot 0): expected an int32, found nil" });
|
||||
});
|
||||
|
||||
test("a slot refusal names the field and slot and never the value", () => {
|
||||
const record = slots<{ name: string }>({ 3: ["name", string] });
|
||||
assert.throws(
|
||||
() => record.decode([null, null, null, { secret: CANARY }]),
|
||||
(error: Error) => error.message.startsWith("name (slot 3):") && !error.message.includes(CANARY),
|
||||
);
|
||||
});
|
||||
|
||||
test("leaf codecs refuse the wrong shape on both sides, saying what was expected and what kind was found", () => {
|
||||
const table: [string, Codec<unknown>, string, unknown, string][] = [
|
||||
["string", string, "a string", 5, "number"],
|
||||
["int32", int32, "an int32", "5", "string"],
|
||||
["int32", int32, "an int32", Number.POSITIVE_INFINITY, "a non-integer number"],
|
||||
["int32", int32, "an int32", Number.NaN, "a non-integer number"],
|
||||
["int32", int32, "an int32", 1.5, "a non-integer number"],
|
||||
["int32", int32, "an int32", 2 ** 31, "an integer out of range"],
|
||||
["int64", int64, "an int64", 2 ** 53, "a number beyond 2^53, which needs a bigint"],
|
||||
["int64", int64, "an int64", 2n ** 63n, "an integer out of range"],
|
||||
["float64", float64, "a float64", "1.5", "string"],
|
||||
["float32", float32, "a float32", null, "nil"],
|
||||
["boolean", boolean, "a boolean", "true", "string"],
|
||||
["bytes", bytes, "bytes", [1, 2], "array"],
|
||||
["string", string, "a string", null, "nil"],
|
||||
["list", list(string), "an array", "abc", "string"],
|
||||
];
|
||||
for (const [label, codec, what, bad, found] of table) {
|
||||
for (const side of ["encode", "decode"] as const) {
|
||||
// Decode sees the wire's shapes: a JS float or a number beyond 2^53 never arrives from a payload.
|
||||
if (side === "decode" && (typeof bad === "number" && (!Number.isInteger(bad) || Math.abs(bad) >= 2 ** 53))) continue;
|
||||
assert.throws(() => codec[side](bad), { message: `expected ${what}, found ${found}` }, `${label} ${side}`);
|
||||
}
|
||||
}
|
||||
for (const [codec, good] of [[string, "s"], [int32, 1], [int64, 5], [float64, 1.5], [float32, 1.5], [boolean, false], [bytes, new Uint8Array([7])], [list(int32), [1, 2]]] as [Codec<unknown>, unknown][]) {
|
||||
assert.deepEqual(codec.decode(codec.encode(good)), good);
|
||||
}
|
||||
});
|
||||
|
||||
test("a list element refusal names the element, and nullable writes nil for null and undefined", () => {
|
||||
const numbers = list(int32);
|
||||
assert.throws(() => numbers.encode([1, "x" as unknown as number]), /^Error: element 1: expected an int32, found string$/u);
|
||||
assert.throws(() => numbers.decode([1, 2, null]), /^Error: element 2: expected an int32, found nil$/u);
|
||||
const maybe = nullable(int32);
|
||||
assert.equal(maybe.encode(null), null);
|
||||
assert.equal(maybe.encode(undefined as unknown as null), null);
|
||||
assert.equal(maybe.encode(0), 0);
|
||||
assert.equal(maybe.decode(null), null);
|
||||
assert.equal(maybe.decode(0), 0);
|
||||
assert.throws(() => maybe.decode("x"), /expected an int32/u);
|
||||
});
|
||||
|
||||
test("a record refuses what is not a record and names the field and slot of a bad value", () => {
|
||||
const record = slots<{ name: string }>({ 3: ["name", string] });
|
||||
assert.throws(() => record.encode(null as unknown as { name: string }), /^Error: expected a record, found nil$/u);
|
||||
assert.throws(() => record.encode("x" as unknown as { name: string }), /^Error: expected a record, found string$/u);
|
||||
assert.throws(() => record.encode({ name: 5 as unknown as string }), /^Error: name \(slot 3\): expected a string, found number$/u);
|
||||
});
|
||||
|
||||
test("a union names itself, its arm and the field when an arm's slots are refused", () => {
|
||||
assert.throws(() => node.encode({ kind: "Text", id: "a", content: 5 as unknown as string }), /^Error: arm Text: content \(slot 1\): expected a string, found number$/u);
|
||||
assert.throws(() => node.decode([1, ["a", 5]]), /^Error: arm Text: content \(slot 1\): expected a string, found number$/u);
|
||||
assert.equal(node.encode(undefined as unknown as null), null);
|
||||
assert.throws(
|
||||
() => node.encode({ kind: "Nope" } as unknown as Node),
|
||||
/^Error: Union Node: the value's kind is not one of its arms \(Box, Text, Use, Image, Wrap\)\.$/u,
|
||||
);
|
||||
});
|
||||
|
||||
test("slot names become catalog member names in Pascal case", () => {
|
||||
const record = slots<{ _hidden: string; two_words: string; Mixed9: string }>({ 0: ["_hidden", string], 1: ["two_words", string], 2: ["Mixed9", string] });
|
||||
assert.deepEqual(record.members.map((member) => member.memberName), ["Hidden", "TwoWords", "Mixed9"]);
|
||||
});
|
||||
|
||||
test("definitions are refused at definition time", () => {
|
||||
assert.throws(() => union<{ kind: "A" }>("U", { 0: ["A", slots<{ kind: string }>({ 0: ["kind", string] })] }), /Union U arm "A" declares a slot named kind/u);
|
||||
assert.throws(() => union<{ kind: "A" | "B" }>("U", { 0: ["A", unit], 1: ["A" as "B", unit] }), /declares the arm "A" twice/u);
|
||||
assert.throws(() => union<{ kind: "A" }>("U", { x: ["A", unit] } as never), /^Error: Union U declares the key "x", which is not an integer\.$/u);
|
||||
assert.throws(() => union<{ kind: "A" }>("U", { "01": ["A", unit] } as never), /key "01"/u);
|
||||
assert.throws(() => union<{ kind: "A" }>("U", { "1.5": ["A", unit] } as never), /key "1\.5"/u);
|
||||
assert.throws(() => union<{ kind: "A" }>("U", {} as never), /^Error: Union U declares no arms\.$/u);
|
||||
assert.throws(() => slots<{ a: string; b: string }>({ 0: ["a", string], 1: ["a" as "b", string] }), /declares the field "a" twice/u);
|
||||
assert.throws(() => slots<{ a: string }>({}), /declares no slots/u);
|
||||
assert.throws(() => slots<{ a: string }>({ [-1]: ["a", string] }), /^Error: A slot record declares the key "-1"/u);
|
||||
assert.throws(
|
||||
() => defineDocumentType({
|
||||
type: "t",
|
||||
schema: surfaceSchema,
|
||||
codec: surfaceCodec,
|
||||
formatter: { encode: () => new Uint8Array(), decode: () => golden },
|
||||
}),
|
||||
/declares both a codec and a formatter/u,
|
||||
);
|
||||
});
|
||||
|
||||
test("a codec supplies the document's catalog members unless it is given its own", () => {
|
||||
const document = defineDocumentType({
|
||||
type: "t",
|
||||
schema: z.object({ a: z.string(), the_b: z.string() }),
|
||||
codec: slots<{ a: string; the_b: string }>({ 0: ["a", string], 3: ["the_b", string] }),
|
||||
name: "a",
|
||||
indexes: { byB: "the_b" },
|
||||
});
|
||||
assert.deepEqual(document.members, [
|
||||
{ slot: 0, memberName: "A", typeName: "System.String", isName: true, indexAlias: null },
|
||||
{ slot: 3, memberName: "TheB", typeName: "System.String", isName: false, indexAlias: "byB" },
|
||||
]);
|
||||
const given = [{ slot: 9, memberName: "Mine", typeName: "System.String" }];
|
||||
const own = defineDocumentType({ type: "t", schema: z.object({ a: z.string() }), codec: slots<{ a: string }>({ 0: ["a", string] }), members: given });
|
||||
assert.deepEqual(own.members, given);
|
||||
});
|
||||
|
||||
test("schema.parse still runs on a decoded value, and a document without a codec still writes a map", async () => {
|
||||
const strict = defineDocumentType({
|
||||
type: "t",
|
||||
schema: z.object({ a: z.string().min(3) }),
|
||||
codec: slots<{ a: string }>({ 0: ["a", string] }),
|
||||
});
|
||||
const store = memoryStore([{ key: "k", type: "t", payload: documentPayloadFromBytes(encode(["xy"])), storedAt: new Date().toISOString() }]);
|
||||
await assert.rejects(() => CultCache.builder().withDocumentType(strict).withGenericStore(store).build().pullAllBackingStores());
|
||||
|
||||
const plain = defineDocumentType({ type: "p", schema: z.object({ id: z.string() }) });
|
||||
const holder = memoryStore([]);
|
||||
await CultCache.builder().withDocumentType(plain).withGenericStore(holder).build().put(plain, "k", { id: "d" });
|
||||
assert.deepEqual(decode(documentPayloadBytes(holder.entries[0].payload)), { id: "d" });
|
||||
});
|
||||
|
||||
test("bytes and nullable round-trip through a slot record", () => {
|
||||
const record = slots<{ blob: Uint8Array; maybe: string | null }>({ 0: ["blob", bytes], 1: ["maybe", nullable(string)] });
|
||||
const wire = encode(record.encode({ blob: new Uint8Array([1, 2]), maybe: null }));
|
||||
assert.deepEqual(record.decode(decode(wire)), { blob: new Uint8Array([1, 2]), maybe: null });
|
||||
assert.throws(() => record.decode([new Uint8Array(), 4]), /maybe \(slot 1\): expected a string/u);
|
||||
});
|
||||
|
||||
const fromHex = (text: string) => new Uint8Array(Buffer.from(text, "hex"));
|
||||
|
||||
// Arm keys are integers within Int32 in the reference: a float key is refused even when it holds a whole number, and a
|
||||
// key outside Int32 is refused whether it is declared or read. Every payload below is [key, [7]] or [key, ["wait"]].
|
||||
test("an arm key is an integer in any MessagePack integer encoding, and a float-typed key is refused", () => {
|
||||
const completed = { kind: "Completed", sourceVersion: 7 };
|
||||
for (const key of ["01", "cc01", "cd0001", "ce00000001", "cf0000000000000001", "d001", "d10001", "d200000001", "d30000000000000001"]) {
|
||||
assert.deepEqual(outcome.decode(readWire(fromHex(`92${key}9107`))), completed, key);
|
||||
}
|
||||
for (const key of ["ca3f800000", "cb3ff0000000000000"]) {
|
||||
assert.throws(() => outcome.decode(readWire(fromHex(`92${key}9107`))), { message: "Union Outcome: the arm key is not an integer (declared keys: -2147483648, 0, 1, 2, 2147483647)." }, key);
|
||||
}
|
||||
assert.throws(() => outcome.decode(readWire(fromHex("92cb800000000000000091a477616974"))), /^Error: Union Outcome: the arm key is not an integer/u, "-0.0 is a float, not key 0");
|
||||
for (const key of ["ce80000000", "cf8000000000000000", "d30000000080000000"]) {
|
||||
assert.throws(() => outcome.decode(readWire(fromHex(`92${key}9107`))), { message: "Union Outcome: the arm key is outside Int32 (declared keys: -2147483648, 0, 1, 2, 2147483647)." }, key);
|
||||
}
|
||||
assert.throws(() => outcome.decode(readWire(fromHex("92d2800000019107"))), { message: "Union Outcome: unknown arm key -2147483647 (declared keys: -2147483648, 0, 1, 2, 2147483647)." });
|
||||
assert.throws(() => outcome.decode(readWire(fromHex("92ff9107"))), { message: "Union Outcome: unknown arm key -1 (declared keys: -2147483648, 0, 1, 2, 2147483647)." });
|
||||
});
|
||||
|
||||
test("a union refuses a declared arm key outside Int32", () => {
|
||||
assert.doesNotThrow(() => union<{ kind: "A" }>("U", { 2147483647: ["A", unit] }));
|
||||
assert.throws(() => union<{ kind: "A" }>("U", { 2147483648: ["A", unit] }), { message: "Union U declares the key 2147483648, which is outside Int32." });
|
||||
assert.throws(() => union<{ kind: "A" }>("U", { 3000000000: ["A", unit] }), /outside Int32/u);
|
||||
});
|
||||
|
||||
test("the wire reader keeps 64-bit integers whole, tells a float from an integer, and refuses what is not a value", () => {
|
||||
assert.equal(readWire(fromHex("cf0020000000000001")), 2n ** 53n + 1n);
|
||||
assert.equal(readWire(fromHex("cf001fffffffffffff")), 2 ** 53 - 1);
|
||||
assert.equal(readWire(fromHex("d38000000000000000")), -(2n ** 63n));
|
||||
assert.equal(readWire(fromHex("cfffffffffffffffff")), 2n ** 64n - 1n);
|
||||
assert.ok(readWire(fromHex("cb3ff0000000000000")) instanceof WireFloat);
|
||||
assert.ok(readWire(fromHex("ca3f800000")) instanceof WireFloat);
|
||||
assert.equal(readWire(fromHex("01")), 1);
|
||||
assert.throws(() => readWire(fromHex("92a161")), /truncated/u, "an array that promises more than the payload holds");
|
||||
assert.throws(() => readWire(fromHex("dd")), /truncated/u);
|
||||
assert.throws(() => readWire(fromHex("ddffffffff")), /truncated/u, "a huge array header reserves nothing");
|
||||
assert.throws(() => readWire(fromHex("a5616263")), /truncated/u);
|
||||
assert.throws(() => readWire(fromHex("0102")), /bytes after its value/u);
|
||||
assert.throws(() => readWire(fromHex("81a161a162")), /map, extension or reserved/u);
|
||||
assert.throws(() => readWire(fromHex("c1")), /map, extension or reserved/u);
|
||||
assert.throws(() => readWire(fromHex("d4010a")), /map, extension or reserved/u);
|
||||
});
|
||||
|
||||
test("the wire writer writes the smallest integer, keeps a float's width, and round-trips what it reads", () => {
|
||||
const tree = [0, 127, 128, 255, 256, 65535, 65536, 4294967295, 4294967296, -1, -32, -33, -128, -129, -32768, -32769, -2147483648, -2147483649,
|
||||
2n ** 53n, 2n ** 64n - 1n, -(2n ** 63n), new WireFloat(1.5, false), new WireFloat(1.5, true), "", "a".repeat(31), "a".repeat(32), "a".repeat(256),
|
||||
new Uint8Array(0), new Uint8Array(300), [], null, true, false, "héllo"];
|
||||
assert.deepEqual(readWire(writeWire(tree)), tree);
|
||||
assert.equal(hex(writeWire(5)), "05");
|
||||
assert.equal(hex(writeWire(128)), "cc80");
|
||||
assert.equal(hex(writeWire(-33)), "d0df");
|
||||
assert.equal(hex(writeWire(2n ** 53n + 2n)), "cf0020000000000002");
|
||||
assert.equal(hex(writeWire(new WireFloat(3, true))), "cb4008000000000000");
|
||||
assert.equal(hex(writeWire(new WireFloat(1.5, false))), "ca3fc00000");
|
||||
assert.equal(hex(writeWire(new Array(16).fill(null))), `dc0010${"c0".repeat(16)}`);
|
||||
assert.throws(() => writeWire(1.5), /not a safe integer/u);
|
||||
assert.throws(() => writeWire(2 ** 53), /not a safe integer/u);
|
||||
assert.throws(() => writeWire(2n ** 64n), /wider than 64 bits/u);
|
||||
assert.throws(() => writeWire({}), /this kind of value/u);
|
||||
});
|
||||
|
||||
test("a codec and a formatter are refused together wherever the definition enters", () => {
|
||||
const both = { type: "t", schema: surfaceSchema, codec: surfaceCodec, formatter: { encode: () => new Uint8Array(), decode: () => golden } };
|
||||
assert.throws(() => defineDocumentType(both), /declares both a codec and a formatter/u);
|
||||
assert.throws(() => CultCache.builder().withDocumentType(both), /declares both a codec and a formatter/u);
|
||||
assert.throws(() => CultCache.builder().withRegistry([both]), /declares both a codec and a formatter/u);
|
||||
});
|
||||
|
||||
test("a definition that skips defineDocumentType still writes its codec's bytes and its derived catalog", async () => {
|
||||
const raw = { type: "tests.union_surface", schemaId: "tests.union_surface.v1", schema: surfaceSchema, codec: surfaceCodec, name: "id" } as unknown as AnyCultCacheDocumentDefinition;
|
||||
const holder = memoryStore([]);
|
||||
const cache = CultCache.builder().withDocumentType(raw).withGenericStore(holder).build();
|
||||
await cache.put(raw as never, "surface", golden as never);
|
||||
assert.equal(hex(documentPayloadBytes(holder.entries[0].payload)), hex(await read("union-surface.msgpack")));
|
||||
const [snapshot] = cache.snapshot();
|
||||
assert.deepEqual(snapshot.catalogEntry!.members!.map((member) => member.typeName).slice(0, 2), ["System.String", "System.Int32"]);
|
||||
});
|
||||
|
||||
test("every leaf and wrapper carries the reference's type name, and a catalog is not derived from a codec that cannot name a slot", () => {
|
||||
assert.deepEqual(
|
||||
[string, boolean, bytes, int32, int64, float32, float64].map((codec) => codec.typeName),
|
||||
["System.String", "System.Boolean", "System.Byte[]", "System.Int32", "System.Int64", "System.Single", "System.Double"],
|
||||
);
|
||||
assert.equal(list(int64).typeName, "System.Collections.Generic.List<System.Int64>");
|
||||
assert.equal(array(string).typeName, "System.String[]");
|
||||
assert.equal(nullable(int32).typeName, "System.Nullable<System.Int32>");
|
||||
assert.equal(nullable(string).typeName, "System.String");
|
||||
assert.equal(nullable(list(string)).typeName, "System.Collections.Generic.List<System.String>");
|
||||
assert.equal(list(union<{ kind: "A" }>("U", { 0: ["A", unit] })).typeName, undefined);
|
||||
const unnamed = slots<{ id: string; what: { kind: "A" } | null }>({ 0: ["id", string], 1: ["what", union<{ kind: "A" }>("U", { 0: ["A", unit] })] });
|
||||
assert.throws(() => unnamed.members, /^Error: what \(slot 1\) has no C# type name for the schema catalog/u);
|
||||
assert.throws(() => defineDocumentType({ type: "t", schema: z.any(), codec: unnamed as never }), /what \(slot 1\) has no C# type name/u);
|
||||
const given = defineDocumentType({ type: "t", schema: z.any(), codec: unnamed as never, members: [{ slot: 0, memberName: "Id", typeName: "System.String" }] });
|
||||
assert.equal(given.members!.length, 1);
|
||||
});
|
||||
|
||||
// tests/vectors/numeric-leaves is written by the C# reference (NumericLeafVectorTests): what it reads and refuses for each
|
||||
// numeric leaf, and the bytes it writes.
|
||||
const numericVectors = join(vectors, "..", "numeric-leaves");
|
||||
const numericLeaves: Record<string, Codec<unknown>> = { int32, int64, float32, float64 };
|
||||
const doubleBitsHex = (value: number) => {
|
||||
const view = new DataView(new ArrayBuffer(8));
|
||||
view.setFloat64(0, value);
|
||||
return Buffer.from(view.buffer).toString("hex");
|
||||
};
|
||||
const int64BitsHex = (value: number | bigint) => BigInt.asUintN(64, BigInt(value)).toString(16).padStart(16, "0");
|
||||
const isNaNBits = (bitsHex: string) => {
|
||||
const bits = BigInt(`0x${bitsHex}`);
|
||||
return ((bits >> 52n) & 0x7ffn) === 0x7ffn && (bits & ((1n << 52n) - 1n)) !== 0n;
|
||||
};
|
||||
|
||||
const isSignallingFloat32 = (payload: Uint8Array) => {
|
||||
// payload is a one-slot record [float32]: 91 ca b0 b1 b2 b3
|
||||
if (payload.length !== 6 || payload[1] !== 0xca) return false;
|
||||
const bits = new DataView(payload.buffer, payload.byteOffset).getUint32(2);
|
||||
return (bits & 0x7f800000) === 0x7f800000 && (bits & 0x007fffff) !== 0 && (bits & 0x00400000) === 0;
|
||||
};
|
||||
|
||||
test("numeric leaves read and refuse exactly what the C# reference does", async () => {
|
||||
const rows = readWire(new Uint8Array(await readFile(join(numericVectors, "reads.msgpack")))) as [string, Uint8Array, boolean, Uint8Array][];
|
||||
assert.equal(rows.length, 160);
|
||||
let accepted = 0;
|
||||
let refused = 0;
|
||||
for (const [leaf, payload, wasAccepted, bits] of rows) {
|
||||
const label = `${leaf} ${hex(payload)}`;
|
||||
const record = slots<{ v: unknown }>({ 0: ["v", numericLeaves[leaf]] });
|
||||
if (wasAccepted && leaf === "float32" && isSignallingFloat32(payload)) {
|
||||
// The one reading that differs from the reference: it reads a float32 signalling NaN, this runtime refuses it
|
||||
// (float32-nan.msgpack shows the reference keeps its bits, which a JS number cannot).
|
||||
assert.throws(() => record.decode(readWire(payload)), (error: Error) => !error.message.includes(hex(payload).slice(2)), label);
|
||||
refused += 1;
|
||||
} else if (wasAccepted) {
|
||||
const read = record.decode(readWire(payload)).v as number | bigint;
|
||||
const wanted = hex(bits);
|
||||
if (leaf.startsWith("float")) {
|
||||
if (isNaNBits(wanted)) assert.ok(Number.isNaN(read), label);
|
||||
else assert.equal(doubleBitsHex(read as number), wanted, label);
|
||||
} else {
|
||||
assert.equal(int64BitsHex(read), wanted, label);
|
||||
}
|
||||
accepted += 1;
|
||||
} else {
|
||||
assert.throws(() => record.decode(readWire(payload)), (error: Error) => !error.message.includes(hex(payload).slice(2)), label);
|
||||
refused += 1;
|
||||
}
|
||||
}
|
||||
assert.ok(accepted > 40 && refused > 40, `accepted ${accepted}, refused ${refused}`);
|
||||
assert.equal(accepted + refused, rows.length);
|
||||
});
|
||||
|
||||
// float32-nan.msgpack: [payload, bytes the reference writes after reading it] for a float32 slot holding an infinity or a NaN.
|
||||
// The reference keeps every payload bit; a JS number cannot keep a signalling NaN's, so that read is refused.
|
||||
test("a float32 NaN round-trips with its bits, and a signalling one is refused on read", async () => {
|
||||
const rows = readWire(new Uint8Array(await readFile(join(numericVectors, "float32-nan.msgpack")))) as [Uint8Array, Uint8Array][];
|
||||
assert.equal(rows.length, 6);
|
||||
const record = slots<{ v: number }>({ 0: ["v", float32] });
|
||||
let refused = 0;
|
||||
for (const [payload, rewritten] of rows) {
|
||||
if (isSignallingFloat32(payload)) {
|
||||
assert.equal(hex(rewritten), hex(payload), "the reference keeps the signalling bits");
|
||||
assert.throws(() => record.decode(readWire(payload)), { message: "v (slot 0): expected a float32, found a signalling NaN" }, hex(payload));
|
||||
refused += 1;
|
||||
} else {
|
||||
assert.equal(hex(writeWire(record.encode(record.decode(readWire(payload))))), hex(rewritten), hex(payload));
|
||||
}
|
||||
}
|
||||
assert.equal(refused, 3);
|
||||
});
|
||||
|
||||
test("only a NaN with its quiet bit clear is signalling: a finite float32 with a clear bit 22 reads, and a float64 slot reads any float32 NaN", () => {
|
||||
const f32 = slots<{ v: number }>({ 0: ["v", float32] });
|
||||
const f64 = slots<{ v: number }>({ 0: ["v", float64] });
|
||||
assert.equal(f32.decode(readWire(fromHex("91ca3f800001"))).v, Math.fround(1.0000001192092896));
|
||||
assert.equal(f32.decode(readWire(fromHex("91ca00000001"))).v, Math.fround(1e-45));
|
||||
assert.equal(f32.decode(readWire(fromHex("91ca7f800000"))).v, Infinity);
|
||||
assert.ok(Number.isNaN(f32.decode(readWire(fromHex("91ca7fc00001"))).v));
|
||||
assert.ok(Number.isNaN(f64.decode(readWire(fromHex("91ca7f800001"))).v));
|
||||
});
|
||||
|
||||
test("numeric leaves write the bytes the C# reference writes, and 64-bit values lose nothing", async () => {
|
||||
const rows = readWire(new Uint8Array(await readFile(join(numericVectors, "writes.msgpack")))) as [string, string, Uint8Array][];
|
||||
assert.equal(rows.length, 46);
|
||||
for (const [leaf, text, expected] of rows) {
|
||||
const value = leaf.startsWith("float") ? new DataView(Uint8Array.from(Buffer.from(text, "hex")).buffer).getFloat64(0) : leaf === "int32" ? Number(text) : BigInt(text);
|
||||
const record = slots<{ v: unknown }>({ 0: ["v", numericLeaves[leaf]] });
|
||||
assert.equal(hex(writeWire(record.encode({ v: value }))), hex(expected), `${leaf} ${text}`);
|
||||
}
|
||||
const wide = slots<{ v: number | bigint }>({ 0: ["v", int64] });
|
||||
for (const value of [2n ** 53n + 1n, 2n ** 63n - 1n, -(2n ** 63n), -(2n ** 53n) - 1n]) {
|
||||
assert.equal(wide.decode(readWire(writeWire(wide.encode({ v: value })))).v, value);
|
||||
}
|
||||
assert.equal(wide.decode(readWire(writeWire(wide.encode({ v: 2n })))).v, 2, "a bigint that fits comes back a number");
|
||||
});
|
||||
|
||||
test("the wire writer's width boundaries: where a length or an integer changes its header", () => {
|
||||
assert.equal(hex(writeWire(0)), "00");
|
||||
assert.equal(hex(writeWire("a".repeat(31))).slice(0, 2), "bf");
|
||||
assert.equal(hex(writeWire("a".repeat(32))).slice(0, 4), "d920");
|
||||
assert.equal(hex(writeWire("a".repeat(255))).slice(0, 4), "d9ff");
|
||||
assert.equal(hex(writeWire("a".repeat(256))).slice(0, 6), "da0100");
|
||||
assert.equal(hex(writeWire("a".repeat(65535))).slice(0, 6), "daffff");
|
||||
assert.equal(hex(writeWire("a".repeat(65536))).slice(0, 10), "db00010000");
|
||||
assert.equal(hex(writeWire(new Uint8Array(1))), "c40100");
|
||||
assert.equal(hex(writeWire(new Uint8Array(256))).slice(0, 6), "c50100");
|
||||
assert.equal(hex(writeWire(new Uint8Array(65536))).slice(0, 10), "c600010000");
|
||||
assert.equal(hex(writeWire(new Array(15).fill(null))), `9f${"c0".repeat(15)}`);
|
||||
assert.equal(hex(writeWire(new Array(65535).fill(null))).slice(0, 6), "dcffff");
|
||||
assert.equal(hex(writeWire(new Array(65536).fill(null))).slice(0, 10), "dd00010000");
|
||||
assert.throws(() => writeWire(-(2n ** 63n) - 1n), { message: "cannot write an integer wider than 64 bits." });
|
||||
assert.throws(() => writeWire(undefined), /this kind of value/u);
|
||||
assert.equal(hex(writeWire(-(2n ** 63n))), "d38000000000000000");
|
||||
});
|
||||
|
||||
test("the wire reader's boundaries: the largest fixarray, the 32-bit binary and string, the safe integer edge", () => {
|
||||
assert.deepEqual(readWire(fromHex(`9f${"c0".repeat(15)}`)), new Array(15).fill(null));
|
||||
assert.deepEqual(readWire(fromHex("c600000001aa")), new Uint8Array([0xaa]));
|
||||
assert.equal(readWire(fromHex("db0000000161")), "a");
|
||||
assert.equal(readWire(fromHex("d3ffe0000000000001")), -(2 ** 53 - 1));
|
||||
assert.equal(readWire(fromHex("d3ffe0000000000000")), -(2n ** 53n));
|
||||
assert.equal(readWire(fromHex("cf0020000000000000")), 2n ** 53n);
|
||||
});
|
||||
|
||||
test("a refusal says what was found: nil, a float, an integer that is not the slot's, a plain kind", () => {
|
||||
assert.throws(() => int32.encode(undefined as unknown as number), { message: "expected an int32, found nil" });
|
||||
assert.throws(() => string.decode(new WireFloat(1, true)), { message: "expected a string, found float" });
|
||||
assert.throws(() => string.decode(5n), { message: "expected a string, found integer" });
|
||||
assert.throws(() => int32.decode(new WireFloat(7, true)), { message: "expected an int32, found float" });
|
||||
assert.throws(() => float64.decode("1"), { message: "expected a float64, found string" });
|
||||
assert.throws(() => int64.encode(1.5), { message: "expected an int64, found a non-integer number" });
|
||||
});
|
||||
|
||||
test("nullable names a value type Nullable<T> and anything else as itself", () => {
|
||||
assert.equal(nullable(boolean).typeName, "System.Nullable<System.Boolean>");
|
||||
assert.equal(nullable(int64).typeName, "System.Nullable<System.Int64>");
|
||||
assert.equal(nullable(float32).typeName, "System.Nullable<System.Single>");
|
||||
assert.equal(nullable(float64).typeName, "System.Nullable<System.Double>");
|
||||
assert.equal(nullable(bytes).typeName, "System.Byte[]");
|
||||
const unnamedValueType: Codec<number> = { valueType: true, encode: (value) => value, decode: (raw) => raw as number };
|
||||
assert.equal(nullable(unnamedValueType).typeName, undefined);
|
||||
assert.equal(lazy(() => int32).valueType, true);
|
||||
});
|
||||
|
||||
test("the Int32 edges of an arm key: the largest is an arm, one past either end is outside", () => {
|
||||
const edge = union<{ kind: "A" }>("U", { 2147483647: ["A", unit] });
|
||||
assert.deepEqual(edge.decode(readWire(fromHex("92ce7fffffff90"))), { kind: "A" });
|
||||
assert.deepEqual(edge.encode({ kind: "A" }), [2147483647, []]);
|
||||
assert.throws(() => edge.decode(readWire(fromHex("92ce8000000090"))), { message: "Union U: the arm key is outside Int32 (declared keys: 2147483647)." });
|
||||
assert.throws(() => edge.decode(readWire(fromHex("92d3ffffffff7fffffff90"))), { message: "Union U: the arm key is outside Int32 (declared keys: 2147483647)." });
|
||||
assert.throws(() => edge.decode(readWire(fromHex("92d3ffffffff8000000090"))), { message: "Union U: unknown arm key -2147483648 (declared keys: 2147483647)." });
|
||||
});
|
||||
|
||||
function envelopeOf(payload: Uint8Array): CultCacheEnvelope {
|
||||
return { key: "surface", type: "tests.union_surface", payload: documentPayloadFromBytes(payload), storedAt: new Date().toISOString() };
|
||||
}
|
||||
|
||||
function memoryStore(entries: CultCacheEnvelope[]): CacheBackingStore & { entries: CultCacheEnvelope[] } {
|
||||
return {
|
||||
entries,
|
||||
async pullAll() { return entries.map((entry) => ({ ...entry })); },
|
||||
async push(entry) { entries.push(entry); },
|
||||
async delete() {},
|
||||
};
|
||||
}
|
||||
|
||||
test("arm keys span Int32 and are listed ascending; slot keys are non-negative Int32", () => {
|
||||
const keys = union<{ kind: "High" | "Zero" | "Neg" | "Low" }>("U", {
|
||||
2147483647: ["High", unit],
|
||||
0: ["Zero", unit],
|
||||
[-1]: ["Neg", unit],
|
||||
[-2147483648]: ["Low", unit],
|
||||
});
|
||||
for (const [kind, key] of [["High", 2147483647], ["Zero", 0], ["Neg", -1], ["Low", -2147483648]] as const) {
|
||||
const written = keys.encode({ kind });
|
||||
assert.deepEqual(written, [key, []]);
|
||||
assert.deepEqual(keys.decode(readWire(writeWire(written))), { kind });
|
||||
}
|
||||
assert.throws(() => keys.decode(readWire(fromHex("920590"))), { message: "Union U: unknown arm key 5 (declared keys: -2147483648, -1, 0, 2147483647)." });
|
||||
assert.throws(() => union<{ kind: "A" }>("U", { [-2147483649]: ["A", unit] }), { message: "Union U declares the key -2147483649, which is outside Int32." });
|
||||
assert.throws(() => union<{ kind: "A" }>("U", { 99999999999999999999: ["A", unit] } as never), { message: "Union U declares the key 100000000000000000000, which is outside Int32." });
|
||||
assert.throws(() => slots<{ a: string }>({ 2147483647: ["a", string] }), { message: "A slot record declares the key 2147483647, which is above the slot key limit 65535." });
|
||||
assert.throws(() => slots<{ a: string }>({ 2147483648: ["a", string] }), { message: "A slot record declares the key 2147483648, which is above the slot key limit 65535." });
|
||||
assert.throws(() => slots<{ a: string }>({ [-1]: ["a", string] }), { message: 'A slot record declares the key "-1", which is not a non-negative integer.' });
|
||||
});
|
||||
|
||||
// A slot record is a dense array of key+1 slots, as the reference writes it, so the key is capped: the largest accepted
|
||||
// key writes a 65536-slot payload, one more is refused at definition.
|
||||
test("a slot key is capped at 65535: the cap is the largest slot record, one past it is refused at definition", () => {
|
||||
assert.equal(MAX_SLOT_KEY, 65535);
|
||||
const edge = slots<{ a: string }>({ 65535: ["a", string] });
|
||||
const written = edge.encode({ a: "x" }) as unknown[];
|
||||
assert.equal(written.length, 65536);
|
||||
assert.equal(written[65535], "x");
|
||||
assert.equal(written.filter((slot) => slot === null).length, 65535);
|
||||
assert.deepEqual(edge.decode(readWire(writeWire(written))), { a: "x" });
|
||||
assert.throws(() => slots<{ a: string }>({ 65536: ["a", string] }), { message: "A slot record declares the key 65536, which is above the slot key limit 65535." });
|
||||
});
|
||||
|
||||
test("the mixed-record vector is the bytes the reference writes for a record of every leaf kind", async () => {
|
||||
const mixed = slots<{ id: string; i: number; l: number | bigint; f: number; d: number }>({
|
||||
0: ["id", string], 1: ["i", int32], 2: ["l", int64], 3: ["f", float32], 4: ["d", float64],
|
||||
});
|
||||
const committed = new Uint8Array(await readFile(join(vectors, "..", "numeric-leaves", "mixed-record.msgpack")));
|
||||
assert.equal(hex(writeWire(mixed.encode({ id: "n1", i: 7, l: 8, f: 1.5, d: 2.5 }))), hex(committed));
|
||||
assert.deepEqual(mixed.decode(readWire(committed)), { id: "n1", i: 7, l: 8, f: 1.5, d: 2.5 });
|
||||
});
|
||||
|
||||
// tests/vectors/slot-nil is written by the C# reference (SlotNilVectorTests): what it reads and rewrites for a nil, a str in a
|
||||
// byte[] slot, and a record short of its last slots. A runtime accepts what it accepts and rewrites the same bytes.
|
||||
test("slots read and rewrite exactly what the C# reference does for nil, a str in bytes, and short records", async () => {
|
||||
const inner = slots<{ x: string }>({ 0: ["x", string, ""] });
|
||||
const probe = slots<{ s: string; i: number; b: Uint8Array; r: { x: string }; l: string[] }>({
|
||||
0: ["s", string, ""],
|
||||
1: ["i", int32, 0],
|
||||
2: ["b", bytes, () => new Uint8Array()],
|
||||
3: ["r", inner, null as unknown as { x: string }],
|
||||
4: ["l", list(string), () => []],
|
||||
});
|
||||
const rows = readWire(new Uint8Array(await readFile(join(vectors, "..", "slot-nil", "reads.msgpack")))) as [string, Uint8Array, boolean, Uint8Array][];
|
||||
assert.equal(rows.length, 17);
|
||||
let accepted = 0;
|
||||
for (const [name, payload, wasAccepted, rewritten] of rows) {
|
||||
if (wasAccepted) {
|
||||
assert.equal(hex(writeWire(probe.encode(probe.decode(readWire(payload))))), hex(rewritten), name);
|
||||
accepted += 1;
|
||||
} else {
|
||||
assert.throws(() => probe.decode(readWire(payload)), (error: Error) => !error.message.includes(hex(payload).slice(2)), name);
|
||||
}
|
||||
}
|
||||
assert.equal(accepted, 15);
|
||||
// A character outside the BMP is four UTF-8 bytes (U+1F600 is f0 9f 98 80); a CESU-8 reader, or one with no four-byte
|
||||
// branch, fails here against the bytes the C# reference wrote.
|
||||
const astral = rows.find(([name]) => name === "string-astral")!;
|
||||
assert.equal(probe.decode(readWire(astral[1])).s, "\u{1F600}");
|
||||
assert.equal(hex(writeWire(probe.encode(probe.decode(readWire(astral[1]))))), hex(astral[3]));
|
||||
const astralInBytes = rows.find(([name]) => name === "bytes-str-astral")!;
|
||||
assert.equal(hex(probe.decode(readWire(astralInBytes[1])).b), "f09f9880");
|
||||
});
|
||||
|
||||
test("a nil reads as null and writes as nil in every reference slot, and a value slot refuses it", () => {
|
||||
const record = slots<{ s: string; b: Uint8Array; i: number }>({ 0: ["s", string], 1: ["b", bytes], 2: ["i", int32, 5] });
|
||||
const read = record.decode([null, null, 3]);
|
||||
assert.deepEqual(read, { s: null, b: null, i: 3 });
|
||||
assert.deepEqual(record.encode(read), [null, null, 3]);
|
||||
assert.throws(() => record.encode({ s: "a", b: new Uint8Array(), i: null as unknown as number }), { message: "i (slot 2): expected an int32, found nil" });
|
||||
assert.throws(() => record.decode(["a", new Uint8Array(), null]), { message: "i (slot 2): expected an int32, found nil" });
|
||||
});
|
||||
|
||||
test("a bytes slot reads a MessagePack str as its bytes and writes bin, and refuses a str that was not valid UTF-8", () => {
|
||||
const record = slots<{ b: Uint8Array }>({ 0: ["b", bytes] });
|
||||
const read = record.decode(readWire(fromHex("91a3616263")));
|
||||
assert.equal(hex(read.b), "616263");
|
||||
assert.equal(hex(writeWire(record.encode(read))), "91c403616263");
|
||||
assert.throws(() => record.decode(readWire(fromHex("91a2c328"))), { message: "b (slot 0): expected bytes, found a string that is not valid UTF-8" });
|
||||
assert.throws(() => record.decode([5]), { message: "b (slot 0): expected bytes, found number" });
|
||||
});
|
||||
|
||||
// ---- the bounds vectors: arm keys at the ends of the Int32 domain, nil arm slots, payload nesting ----
|
||||
|
||||
const wrapChain = (wraps: number, leaf: Node): Node => {
|
||||
let node: Node = leaf;
|
||||
for (let index = 0; index < wraps; index += 1) node = { kind: "Wrap", inner: node };
|
||||
return node;
|
||||
};
|
||||
// A Wrap adds 2 containers, a Box with no children 3, a Text leaf 2, and the outermost array is 1 (the C# test's arithmetic).
|
||||
const AT_LIMIT_WRAPS = (MAX_PAYLOAD_DEPTH - 1 - 3) / 2;
|
||||
const PAST_LIMIT_WRAPS = (MAX_PAYLOAD_DEPTH + 1 - 1 - 2) / 2;
|
||||
const atLimitValue: Surface = { ...golden, root: wrapChain(AT_LIMIT_WRAPS, { kind: "Box", id: "leaf", children: [] }) };
|
||||
const pastLimitValue: Surface = { ...golden, root: wrapChain(PAST_LIMIT_WRAPS, { kind: "Text", id: "leaf", content: CANARY }) };
|
||||
|
||||
async function boundsEntries() {
|
||||
const raw = decode(await read("bounds-outcomes.msgpack")) as unknown[][];
|
||||
const [limit, ...rest] = raw;
|
||||
return { limit, entries: rest.map(([file, outcome, unionName, key, detail]) => ({ file: file as string, outcome: outcome as string, unionName: unionName as string, key: key as number | null, detail: detail as string })) };
|
||||
}
|
||||
|
||||
test("every bounds vector is listed and holds: accepted files decode and re-encode, refused files are refused naming the union or the depth", async () => {
|
||||
const { limit, entries } = await boundsEntries();
|
||||
assert.deepEqual(limit, ["limit", MAX_PAYLOAD_DEPTH]);
|
||||
assert.equal(entries.length, 12);
|
||||
const document = surfaceDocument();
|
||||
const counts = { accepted: 0, refused: 0, readOnly: 0 };
|
||||
|
||||
for (const { file, outcome: expected, unionName, key, detail } of entries) {
|
||||
const payload = documentPayloadFromBytes(await read(file));
|
||||
if (expected === "accepted") {
|
||||
counts.accepted += 1;
|
||||
const value = decodeDocumentPayload(document, payload);
|
||||
assert.equal(hex(documentPayloadBytes(encodeDocumentPayload(document, value))), hex(await read(detail)), `${file}: re-encodes to ${detail}`);
|
||||
} else if (expected === "read-only") {
|
||||
counts.readOnly += 1;
|
||||
assert.deepEqual(decodeDocumentPayload(document, payload), golden, `${file}: the extra slots are read past`);
|
||||
} else {
|
||||
counts.refused += 1;
|
||||
assert.throws(
|
||||
() => decodeDocumentPayload(document, payload),
|
||||
(error: Error) => {
|
||||
assert.ok(!error.message.includes(CANARY), `${file}: the refusal echoed the payload`);
|
||||
if (detail === "depth") {
|
||||
return error instanceof CultCachePayloadDepthError && error.depth === MAX_PAYLOAD_DEPTH + 1 && error.limit === MAX_PAYLOAD_DEPTH
|
||||
&& error.message.includes(`"${document.type}"`) && error.message.includes("257") && error.message.includes("256");
|
||||
}
|
||||
assert.ok(!(error instanceof CultCachePayloadDepthError), file);
|
||||
const said = detail === "key-out-of-range" ? "outside Int32" : detail === "key-not-integer" ? "not an integer" : "expected [key, slots]";
|
||||
return error.message.includes(`Union ${unionName}:`) && error.message.includes(said);
|
||||
},
|
||||
file,
|
||||
);
|
||||
}
|
||||
}
|
||||
assert.deepEqual(counts, { accepted: 3 + 1, refused: 4 + 1 + 2, readOnly: 1 });
|
||||
});
|
||||
|
||||
test("the constructed values write the committed at-limit payload byte for byte, and the past-limit value is refused and stored nowhere", async () => {
|
||||
const document = surfaceDocument();
|
||||
assert.equal(hex(documentPayloadBytes(encodeDocumentPayload(document, atLimitValue))), hex(await read("depth-at-limit.msgpack")));
|
||||
assert.deepEqual(decodeDocumentPayload(document, documentPayloadFromBytes(await read("depth-at-limit.msgpack"))), atLimitValue);
|
||||
|
||||
assert.throws(
|
||||
() => encodeDocumentPayload(document, pastLimitValue),
|
||||
(error: Error) => error instanceof CultCachePayloadDepthError && error.depth === 257 && !error.message.includes(CANARY),
|
||||
);
|
||||
|
||||
const entries: CultCacheEnvelope[] = [];
|
||||
const cache = CultCache.builder().withDocumentType(document).withGenericStore(memoryStore(entries)).build();
|
||||
await assert.rejects(() => cache.put(document, "past", pastLimitValue), CultCachePayloadDepthError);
|
||||
assert.equal(entries.length, 0, "nothing reached the store");
|
||||
assert.equal(cache.get(document, "past"), undefined, "nothing is held in memory");
|
||||
await cache.put(document, "at", atLimitValue);
|
||||
assert.equal(entries.length, 1);
|
||||
assert.equal(hex(documentPayloadBytes(entries[0]!.payload)), hex(await read("depth-at-limit.msgpack")));
|
||||
});
|
||||
|
||||
test("a cache load refuses a store whose record is past the limit, naming the type and not the payload", async () => {
|
||||
const document = surfaceDocument();
|
||||
const refusing = CultCache.builder().withDocumentType(document).withGenericStore(memoryStore([envelopeOf(await read("depth-past-limit.msgpack"))])).build();
|
||||
await assert.rejects(() => refusing.pullAllBackingStores(), (error: Error) => error instanceof CultCachePayloadDepthError && !error.message.includes(CANARY));
|
||||
});
|
||||
|
|
@ -33,8 +33,37 @@ shader semantics.
|
|||
- `shaders/CultMath.hlsl`, a canonical HLSL mirror include for shader-side
|
||||
parity. HLSL already owns `float2`, `float3`, and `float4`; the include
|
||||
exposes `cultmath_*` functions for shared semantics HLSL does not provide.
|
||||
It includes `shaders/CultMath.Phacelle.hlsl` (MPL-2.0) from the same
|
||||
directory, so ship both files.
|
||||
It includes `shaders/CultMath.Phacelle.hlsl` (MPL-2.0) and
|
||||
`shaders/CultMath.Interval.hlsl` and `shaders/CultMath.Affine.hlsl` from the same
|
||||
directory, so ship all four.
|
||||
- interval arithmetic for culling empty space: `iv_*` functions
|
||||
over `float2(lo, hi)` (`iv_add`, `iv_mul`, `iv_exp`, `iv_smoothstep`, ...)
|
||||
and `iv_snoise_ball`/`iv_fbm_ball`, which bound `snoise` and `fbm_grad` over a
|
||||
ball, and `iv_frustum_ball`, the ball around a screen tile's rays over a depth
|
||||
segment, so one probe serves the whole tile (its radius carries its own
|
||||
float32 rounding bound). The arithmetic functions return an interval built to
|
||||
contain the function's value over their operand intervals, so a raymarch
|
||||
can skip a segment whose `hi` is below its cutoff; `cultmath_iv_*` in HLSL.
|
||||
The noise functions rest on empirical constants with a margin, not a proof:
|
||||
`iv_snoise_ball(float3)` on `SNOISE_LIPSCHITZ` (`iv_fbm_ball` through it),
|
||||
`iv_snoise_ball(float2)` on `SNOISE2_LIPSCHITZ`, and `af_snoise` on
|
||||
`SNOISE_HESSIAN` and `SNOISE_LIPSCHITZ` (`af_fbm` through it); the enclosure
|
||||
tests sample them. `iv_frustum_ball` and `af_frustum_ball` read no noise
|
||||
constant: the ball is geometry plus a rounding widening, and the noise call
|
||||
it feeds carries the constant.
|
||||
The bounds compose with a consumer's own analytic envelope (a height fog, a
|
||||
carved sphere): its interval over the segment proves empty space in one probe,
|
||||
and the noise ball is consulted only near the surface. See `docs/design.md`,
|
||||
"Intervals".
|
||||
- `shaders/CultMath.glsl` (MIT), the same `cultmath_*` library in GLSL ES 3.00
|
||||
for WebGL2, generated from `CultMath.hlsl` (never edited by hand), and
|
||||
`shaders/CultMath.Phacelle.glsl` (MPL-2.0), generated from
|
||||
`CultMath.Phacelle.hlsl`, which holds `cultmath_phacelle` alone. GLSL has no
|
||||
`#include`: a WebGL consumer concatenates `CultMath.glsl` after its own
|
||||
`#version 300 es` line and `precision highp float; precision highp int;`
|
||||
(the library declares no precision, and its hashes need 32-bit integers),
|
||||
then `CultMath.Phacelle.glsl` only if it calls `cultmath_phacelle`, then its
|
||||
own shader source.
|
||||
- `Voronoi.SampleTones`, a C# batch surface that calls the Rust
|
||||
`cultmath-core` native kernel when `cultmath_core` is available and falls back
|
||||
to the managed parity path otherwise.
|
||||
|
|
@ -100,6 +129,12 @@ The repository root is not a Unity package. Build the tracked package with
|
|||
assembly and rejects stale binaries, missing metadata, unexpected assemblies,
|
||||
or leaked C# source.
|
||||
|
||||
Before tagging `cultmath-unity-v*`, run the import and dispatch smoke on a Windows machine with a GPU,
|
||||
alone: `packages/cultmath/scripts/unity-smoke/run-unity-smoke.ps1 -UnityExe <path to Unity.exe>`. It
|
||||
builds a scratch project outside the repository that references the package by a `file:` path,
|
||||
dispatches a compute shader that includes `CultMath.Interval.hlsl` and `CultMath.Affine.hlsl`, requires
|
||||
a deliberately broken control shader to be rejected, and deletes the project afterwards.
|
||||
|
||||
## Shader Tooling
|
||||
|
||||
CultMath keeps portable DXC outside git under `packages/cultmath/.tools/`:
|
||||
|
|
|
|||
|
|
@ -9,7 +9,9 @@ Gustavson's `webgl-noise` project and Unity Mathematics.
|
|||
`math.snoise(float3)` and `cultmath_snoise(float3)` follow `src/noise3D.glsl` and
|
||||
`math.snoise(float2)` follows `src/noise2D.glsl` of stegu/webgl-noise at commit
|
||||
`22434e04d7753f7e949e8d724ab3da2864c17a0f` (the simplex-boundary fix is
|
||||
`21d9fe23d7`, scale `ff3b5d34ea`, permutation `a3e6d57095`).
|
||||
`21d9fe23d7`, scale `ff3b5d34ea`, permutation `a3e6d57095`). Modified from upstream:
|
||||
the 3D corner tie order follows Gustavson's `simplexnoise1234`, because the
|
||||
upstream `step` compares are cyclic where the offset's components are equal.
|
||||
|
||||
`math.snoise_grad`/`cultmath_snoise_grad` (and the `fbm_grad`/`ridged_grad`
|
||||
octave sums built on them) follow the analytic-gradient differentiation from
|
||||
|
|
@ -35,7 +37,9 @@ gradient and the exact pruning are new here.
|
|||
- License: MPL-2.0 (<https://mozilla.org/MPL/2.0/>). MPL-2.0 is file-level, so it
|
||||
covers exactly the files that carry the port and nothing else:
|
||||
`src/CultMath/math.Phacelle.cs`, `src/CultMath/CultPhasor.cs`,
|
||||
`shaders/CultMath.Phacelle.hlsl` and the Unity copy of that include. Each
|
||||
carries the MPL-2.0 header and this attribution. The rest of CultMath is MIT,
|
||||
so the `GameCult.Math` NuGet package declares `MIT AND MPL-2.0` and ships this
|
||||
file. The Unity package as a whole is MPL-2.0.
|
||||
`shaders/CultMath.Phacelle.hlsl` and the Unity copy of that include, and
|
||||
`shaders/CultMath.Phacelle.glsl`, which is generated from that include. Each
|
||||
carries the MPL-2.0 header and this attribution. The rest of CultMath, the
|
||||
generated GLSL library included, is MIT, so the `GameCult.Math` NuGet
|
||||
package and the `org.gamecult.cultmath` Unity package both declare
|
||||
`MIT AND MPL-2.0` and ship this file.
|
||||
|
|
|
|||
|
|
@ -133,6 +133,130 @@ as its value. `CultCellular` (`math.cs`, `cellular`) and `CultPhasor`
|
|||
retyped field does not get a second comparison path or a shape of its own;
|
||||
it fails the same walk that already handles a bare vector return.
|
||||
|
||||
### GLSL Target: Source Transformations
|
||||
|
||||
`shaders/CultMath.glsl` is a GLSL ES 3.00 (WebGL2) library generated from
|
||||
`shaders/CultMath.hlsl` by `GlslLowering` (in the test project), and
|
||||
`shaders/CultMath.Phacelle.glsl` is generated beside it from
|
||||
`shaders/CultMath.Phacelle.hlsl`. Both are derived files: never edit them by
|
||||
hand. Regenerate them, and the golden fixture
|
||||
`tests/CultMath.Tests/fixtures/glsl-parity.json`, with:
|
||||
|
||||
```powershell
|
||||
$env:CULTMATH_WRITE_GLSL = "1"; dotnet test packages/cultmath/tests/CultMath.Tests --filter GlslMirrorTests
|
||||
```
|
||||
|
||||
`GlslMirrorTests.CommittedGlslEqualsLowering` fails on any difference between
|
||||
either committed file and the lowering of the committed HLSL. These
|
||||
transformations, in order, are the complete list:
|
||||
|
||||
1. Each `#include "name"` is replaced in place by the included file, by the
|
||||
same resolver the C# mirror uses; GLSL has no `#include`. The exception is
|
||||
an include under a file-level licence of its own, listed in one table,
|
||||
`GlslLowering.SeparateFiles`: its line is dropped and the file is lowered on
|
||||
its own, by the same steps, into its own output. The table has one entry,
|
||||
`CultMath.Phacelle.hlsl` to `CultMath.Phacelle.glsl`, because Phacelle is
|
||||
MPL-2.0 and MPL-2.0 is file-level: kept separate, it leaves
|
||||
`CultMath.glsl` MIT. Nothing else in the lowering is keyed by name.
|
||||
2. Include guards are dropped, and so are the functions taking
|
||||
`Texture2D`/`SamplerState`; the host shader samples its own textures.
|
||||
3. Type names: `floatN`, `intN`, `uintN` and `boolN` become `vecN`, `ivecN`,
|
||||
`uvecN` and `bvecN`.
|
||||
4. File-scope `static const` becomes `const`.
|
||||
5. C-style casts `(float)x`, `(int)x` and `(uint)x` become `float(x)`, `int(x)`
|
||||
and `uint(x)`. The operand is found by a balanced-bracket scanner:
|
||||
`(int)((state >> 28) + 4u)` nests parentheses.
|
||||
6. Intrinsics are renamed: `lerp` to `mix`, `frac` to `fract`, `rsqrt` to
|
||||
`inversesqrt`, `asuint` to `floatBitsToUint`, `asfloat` to
|
||||
`uintBitsToFloat`, and `saturate(x)` becomes `clamp(x, 0.0, 1.0)`.
|
||||
7. Float literals pass through unchanged.
|
||||
8. Each output is wrapped in a guard named for its file: `CULTMATH_GLSL`,
|
||||
`CULTMATH_PHACELLE_GLSL`.
|
||||
9. The first line names the file as generated, its sources and its licence,
|
||||
and says how to regenerate it; `CultMath.glsl`'s also says which
|
||||
functions live in the separate file.
|
||||
|
||||
GLSL ES 3.00 is stricter than HLSL: no implicit conversions between int, uint
|
||||
and float, no C-style casts, and no `step(genType, float)` overload. Those gaps
|
||||
are closed in the HLSL, never in the lowering: the HLSL is written in the subset
|
||||
both languages share, with edits that are legal HLSL and compute the same bits
|
||||
(`step(h, float4(0.0, 0.0, 0.0, 0.0))` rather than `step(h, 0.0)`, `+ 4u` where
|
||||
a uint is added, `(float)((uint)hash.x >> 8)` before a float multiply). The C#
|
||||
mirror and the FXC and dxc compiles keep those edits honest. A body that needs a
|
||||
transformation outside the list fails `GlslMirrorTests.NoHlslOnlyTokensSurvive`
|
||||
rather than gaining a special case.
|
||||
|
||||
The library declares no precision. The host shader does, and it must be
|
||||
`precision highp float; precision highp int;`: the PCG hashes need 32-bit
|
||||
integers. `tools/compile-glsl.ps1` writes such a wrapper (its own `#version
|
||||
300 es` line, the precision, the library by string concatenation, and one call
|
||||
of every public function) and compiles it with glslang, which
|
||||
`tools/get-glslang.ps1` fetches pinned. It runs twice: over `CultMath.glsl`
|
||||
alone, and with `-Phacelle` over `CultMath.glsl` followed by
|
||||
`CultMath.Phacelle.glsl`, the order a consumer that calls `cultmath_phacelle`
|
||||
concatenates them in. Two negative controls must fail: `-Body` with an HLSL
|
||||
token (`float x = lerp(0.0, 1.0, 0.5);`), and `-Body` calling
|
||||
`cultmath_phacelle` without `-Phacelle`, which proves the MIT file does not
|
||||
carry it. The Unity package ships neither GLSL file.
|
||||
|
||||
Parity runs in two legs, each with one owner: HLSL against C# by the mirror
|
||||
test, bit for bit; GLSL against C# by the golden fixture, which records 256
|
||||
seeded cases per function family as float32 bit patterns, evaluated by the
|
||||
consumer on WebGL2 and read back. The families `pcg3d` and `pcg4d` are marked
|
||||
exact; the float families are ulp-bounded, the bound measured on the device.
|
||||
|
||||
`iv_frustum_ball` is ulp-bounded, not exact: it calls `sqrt`, which GLSL ES
|
||||
3.00 does not require to be correctly rounded, and WebGL2 compilers may
|
||||
reassociate. On a GTX 1070 under ANGLE's D3D11 backend its radius differs from
|
||||
C# by up to 2 ulp in 43 of 256 cases, sometimes smaller. What the march needs
|
||||
is enclosure, and what culling needs is a ball no wider than its rounding
|
||||
widening, so the family's fixture entry carries a `check` the consumer applies
|
||||
to every case: from the case's arguments `(mx, my, z0, z1, fp, warp)`, compute
|
||||
in double `zm = (z0 + z1) / 2`, the centre `c = (mx zm, my zm, zm)`, its
|
||||
`|c|_1 = |mx zm| + |my zm| + |zm|`, the radius
|
||||
`r = (z1 - z0) / 2 sqrt(mx^2 + my^2 + 1) + z1 fp + warp` and
|
||||
`d = |GPU centre - c|`, and require
|
||||
`r + d <= GPU radius <= r + d + 2^-19 (r + |c|_1)`. The lower side is
|
||||
enclosure; the upper side is the bound `NoiseBoundTests` pins in C#, so a
|
||||
lowering that inflates the ball fails too. Only those two bounds fail the
|
||||
check; the largest ulp distance is reported as for any ulp-bounded family.
|
||||
`GoldenFixtureMatchesCSharp` applies the same check to C#'s own results.
|
||||
|
||||
Every `af_*` function is an ulp-bounded family, and `af_snoise`, `af_fbm` and `af_frustum_ball` also carry a two-sided `check`
|
||||
of their own, applied the same way: the device's own `snoise` or fBm at 75 sampled points of the case's set must lie in the device's
|
||||
form with no tolerance (a device whose gradient error exceeds the allowance fails), its width must not pass the Lipschitz form's
|
||||
allowance, and the device's `af_frustum_ball` radius must enclose the sampled ray points and stay within its rounding widening.
|
||||
The reference is the device's own noise, which is right for culling soundness but would pass a device whose noise is wrong
|
||||
everywhere, so two appended families (`af_snoise` and `af_fbm`, 256 cases each) add the centre leg: the fixture's own `x0`
|
||||
(C#'s value at the centre) must lie in the device form's `[x0 - e, x0 + e]`, for every `af_snoise` and `af_fbm` family. They
|
||||
also draw reach `|axis| + radius` from 1e-6 to 1e-3, the short slices near a camera, where the float32 allowance is most of `e`:
|
||||
the main families' reach is at least about 1e-3, where the second-order remainder is far larger and a device that drops the
|
||||
allowance still passes. `GoldenFixtureMatchesCSharp` requires each of the two to hold cases that fail on C#'s own results once
|
||||
the allowance is removed.
|
||||
|
||||
`GoldenFixtureMatchesCSharp` evaluates C# on the committed fixture's own
|
||||
arguments. Arguments are drawn only when the fixture is regenerated
|
||||
(`CULTMATH_WRITE_GLSL=1`), because the draw itself calls `MathF.Pow`, whose
|
||||
bits differ by OS. `iv_exp` and `phacelle` take their C# results from the
|
||||
platform's `exp`, `sin` and `cos`, which also differ by OS, so their entries
|
||||
name the platform that generated them and the test compares them case by case
|
||||
against the running platform, printing the largest distance. `iv_exp`
|
||||
("ulp-bounded, platform exp") must agree within one ulp. `phacelle`
|
||||
("ulp-bounded, platform exp, sin, cos; across platforms |diff| <= 2^-20
|
||||
max(|v|, 1)") must agree within `2^-20 max(|v|, 1)` per component, `v` being
|
||||
the fixture's value: its sums of `exp`, `sin` and `cos` cancel near zero, where
|
||||
ulps mean nothing, and Windows differs from the Linux fixture by up to
|
||||
`3.6e-7 max(|v|, 1)`. Every other family is compared as text. `phacelle` is in
|
||||
`CultMath.Phacelle.glsl`, so the evaluator concatenates
|
||||
`CultMath.Phacelle.glsl` after `CultMath.glsl` for that family, with
|
||||
normalization 0.5. The site does not vendor the MPL file and skips the family.
|
||||
Its evaluator is the cultmath-tapes follow-up `glsl-browser-parity-run`, owned
|
||||
by the next CultMath parity cut: a repeatable CultLib WebGL2 run of every
|
||||
fixture family, `phacelle` included. Until it lands, the one GLSL evaluation of
|
||||
`phacelle` is a single probe (GTX 1070, ANGLE D3D11: within `3.1e-6 max(|v|, 1)`
|
||||
of C#). Asura's `gpu-snoise-parity` is a different check, an FXC and Unity
|
||||
readback of `snoise`, and evaluates no GLSL.
|
||||
|
||||
## Invariant 8: Value-and-Gradient Primitives
|
||||
|
||||
A primitive tagged invariant 8 returns its value and analytic gradient
|
||||
|
|
@ -244,7 +368,14 @@ together, laid out as `float4(gradient.xyz, value.w)`, with no value-only twin
|
|||
that permutation helper, so its values changed too, while its own kernel
|
||||
(`0.5`) and scale (`130`) already matched upstream.
|
||||
`NoiseGradTests.SnoiseAndItsGradientAreContinuousAcrossSimplexCellBoundaries`
|
||||
pins the continuity.
|
||||
pins the continuity. Ties in the offset `x0` resolve in Gustavson's
|
||||
`simplexnoise1234` order (x over y, y over z, x over z), a total order, so the
|
||||
four corners are always a simplex. Upstream's `step` compares are cyclic: where
|
||||
the three components are equal, which is every input whose differences `y - x`
|
||||
and `z - x` are whole numbers (every integer point, the origin and every
|
||||
`(t, t, t)` among them), the corners repeat the origin vertex and the value
|
||||
jumps by about 0.77 near the origin and up to 1.56 at magnitudes of 64 and
|
||||
above. `SnoiseTieScopeTests` pins the set against the 0.3.0 values. `NoiseGradTests.SnoiseIsContinuousOnTheSimplexDiagonal` pins the order.
|
||||
- `snoise_grad(float3 p)` carries `snoise(float3)` to value-and-gradient form,
|
||||
following the differentiation in webgl-noise `src/noise3Dgrad.glsl` (Ashima
|
||||
Arts / Ian McEwan, MIT), which uses the same radius, permutation and scale as
|
||||
|
|
@ -341,6 +472,368 @@ Known C# friction: under `using static CultMath.math;` the constructor
|
|||
functions (`float3(...)`, `float3x3(...)`) hide the type names in member access,
|
||||
so static members need a qualified type (`CultMath.float3x3.Euler(...)`).
|
||||
|
||||
## Intervals
|
||||
|
||||
`math.Interval.cs` and `shaders/CultMath.Interval.hlsl` (included from
|
||||
`CultMath.hlsl` after the Phacelle include) carry interval arithmetic for
|
||||
culling empty space with a proof. Their invariant, **intervals-enclose**: every
|
||||
interval function returns a `[lo, hi]` that contains `f(x)` for every `x` in
|
||||
its input region, where `f(x)` is the same function evaluated pointwise in
|
||||
float32. A consumer that skips a region because `hi < cutoff` has skipped
|
||||
nothing that was there.
|
||||
|
||||
Representation: an interval is `float2(lo, hi)` with `lo <= hi`, both finite.
|
||||
There is no empty interval; a caller that needs "provably empty" tests
|
||||
`hi < cutoff`. `iv_point(x)` is `float2(x, x)`.
|
||||
|
||||
Ops: `iv_point`, `iv_add`, `iv_sub`, `iv_neg`, `iv_mul` (the least and greatest
|
||||
of the four corner products), `iv_scale(iv, float)`, `iv_abs` and `iv_sqr`
|
||||
(an interval straddling zero starts at 0), `iv_min`, `iv_max`, `iv_sqrt`
|
||||
(`lo` clamped at 0), `iv_exp`, `iv_clamp(iv, float, float)`, `iv_saturate`,
|
||||
`iv_smoothstep(float, float, iv)` (its ordered endpoints) and
|
||||
`iv_lerp(iv, iv, float)`. No others until a consumer names one. Each has an
|
||||
HLSL mirror named `cultmath_iv_*`, compared bit for bit by
|
||||
`HlslSourceCompatibilityTests`.
|
||||
|
||||
The ulp-widening rule. Each bound is computed with the pointwise function's
|
||||
own float32 operations. IEEE round-to-nearest is monotone, so an op that is
|
||||
monotone on its region encloses its float32 evaluation exactly, with no
|
||||
widening; that covers every op above except two, which widen by exactly one
|
||||
ulp, in the implementation and never in the test:
|
||||
|
||||
- `iv_exp`: `exp` is not required to be correctly rounded, so a libm need not
|
||||
be monotone. .NET's `MathF.Exp` on Linux steps down 0 times over every float
|
||||
in [-87, 88.7] (`IntervalTests.MeasureMonotonicity`), so on that CPU the
|
||||
widening is a margin; it is there for other libms and GPUs.
|
||||
- `iv_smoothstep`: `t * t * (3 - 2t)` in float32 steps down 337,095 times over
|
||||
the floats in [0, 1], each time by at most 1 ulp (`MeasureMonotonicity`).
|
||||
Since `t = saturate((x - minimum) / (maximum - minimum))` is itself monotone
|
||||
in `x`, that covers every `smoothstep`.
|
||||
|
||||
`iv_lerp` is the natural interval extension of `x + (y - x) * amount`, which is
|
||||
how `lerp` evaluates; every step is monotone, so it encloses with no widening
|
||||
for any `amount`, and it is tight only when `a` is a point, because `x` appears
|
||||
twice.
|
||||
|
||||
`IntervalTests` runs every op over 10,000 seeded intervals (centres in
|
||||
[-20, 20], widths log-uniform in [1e-4, 10], every eighth a point) and 16
|
||||
points inside each, endpoints and zero included, with no tolerance; and for
|
||||
every op it raises `lo` and lowers `hi` by one ulp and requires the harness to
|
||||
catch each. A new op is one entry in that table.
|
||||
|
||||
Noise bounds. `iv_snoise_ball(c, r)` is `[n - L r, n + L r]` intersected with
|
||||
`[-1, 1]`, where `n = snoise(c)` and `L = SNOISE_LIPSCHITZ`: one `snoise`, value
|
||||
only. No interval function reads `snoise_grad`, and none has a value-only or
|
||||
gradient twin. `iv_fbm_ball(c, r, octaves, lacunarity, gain)` is the octave sum
|
||||
of `iv_snoise_ball(c * f_i, r * |f_i|)` scaled by `a_i`, compounding frequency
|
||||
and amplitude exactly as `fbm_grad` does, octaves clamped to [0, 16]. A domain
|
||||
warp that moves a point by at most `D` is enclosed by the radius `r + D`
|
||||
(`NoiseBoundTests.WarpedPointsStayEnclosed`); this is what the gamecult.org
|
||||
ground's march rests on.
|
||||
|
||||
`iv_frustum_ball(m_c, z0, z1, footprintPerDepth, warp)` is the ball one probe
|
||||
serves a whole screen tile with. In a pinhole camera frame looking down `+z`,
|
||||
where the ray of slope `m` is the points `(m z, z)`, it encloses every point of
|
||||
every ray whose slope lies within `footprintPerDepth` of `m_c` (`N / (sqrt(2) f)`
|
||||
for an `N x N` tile at focal length `f` pixels: the full pixel footprint, so
|
||||
sub-pixel jitter is covered), over depths `[z0, z1]`, each point moved by a warp
|
||||
of length at most `warp`. The centre is `(m_c z_m, z_m)`, `z_m` the mid-depth;
|
||||
the radius is `((z1 - z0) / 2) |(m_c, 1)| + z1 footprintPerDepth + warp`. A point
|
||||
of slope `m_c + e` at depth `z` is the centre plus `(z - z_m)(m_c, 1)` plus
|
||||
`z (e, 0)`. The returned ball is float32, and on a degenerate (`z0 == z1`),
|
||||
thin or far segment the rounding of the centre alone exceeds the gap the
|
||||
triangle inequality leaves, so the radius is widened by
|
||||
`(|c|_1 + radius) 2^-20`. With `u = 2^-24`, each centre component carries at most
|
||||
two roundings (`z_m`, then the product), so the float centre is within
|
||||
`2u |c|_1` of the exact one; the radius carries at most seven (`z1 - z0`, the
|
||||
axis length at `3u`, the product, `z1 footprintPerDepth`, the sum, `+ warp`), so
|
||||
the exact radius is at most `(1 + 7u)` times the float one; the widening rounds
|
||||
once more. `2^-20 = 16u` covers `8u (|c|_1 + radius)` twice over, and fma
|
||||
contraction only removes roundings. The axis count assumes a correctly rounded
|
||||
`sqrt`, which IEEE gives C#. GLSL ES 3.00 does not: it inherits `sqrt`'s
|
||||
precision from `inversesqrt`, and D3D-backed compilers may reassociate. So the
|
||||
bound is proven for C# and HLSL on IEEE hardware, and on GLSL it is measured:
|
||||
on a GTX 1070 under ANGLE's D3D11 backend the fixture's 256 cases keep a
|
||||
minimum relative slack of `1.98e-6` (about `33u`), the same as C#'s. The
|
||||
fixture's enclosure check is what measures it on each device. The caller rotates and translates the centre into world space and scales
|
||||
centre and radius by its noise frequency; the rounding of that transform is the
|
||||
caller's. `NoiseBoundTests.TileBallEnclosesEveryRaySegment` checks 2,000 seeded
|
||||
tiles x 64 points of the r2 domain and 2,000 tiles x 8 corner points of each of
|
||||
seven extreme families (`z0 == z1`, `z1 - z0 = 1e-6 z1`, `|m_c|` to 1000, `z` to
|
||||
`1e7`, `z0 = 0` with `z1` to `1e-3`, `f` down to 1, warp to `1e6`), corner flows
|
||||
full-length and outward, distances in double, with no tolerance. It pins the ball
|
||||
to the derivation both ways (`r <= ball.w <= r + 2^-19 (r + |c|_1)`), so a ball
|
||||
that forgets the widening fails and one grown past it fails too. A moving camera needs nothing
|
||||
more: each frame's probes use that frame's camera, and no ball, mask or probe
|
||||
result is carried from one frame to the next.
|
||||
|
||||
The noise ball alone proves little: at `L` near 10 it bounds `snoise` to a width
|
||||
of `2 L r`, which covers all of `[-1, 1]` once `L r` reaches 1. Empty space
|
||||
becomes provable through an analytic envelope. The consumer's density is a
|
||||
pre-distortion SDF (a height fog, a well map, a carved sphere) that noise
|
||||
displaces only near its surface, and the consumer composes the bound from `iv_*`
|
||||
ops. The envelope is taken over the slice's exact box (`iv_mul` of the depth
|
||||
range by each slope range, then the SDF's own monotone pieces), together with its
|
||||
fade. The noise is `iv_snoise_ball` over `iv_frustum_ball`, scaled by the noise
|
||||
frequency. The warp moves only the noise argument, so it enlarges the ball and
|
||||
the envelope's box takes none of it. Where the fade's upper end is 0 the noise
|
||||
term is identically 0 and no `snoise` is evaluated. Where the envelope already
|
||||
proves the slice empty with the noise at its full range, the ball is not
|
||||
evaluated either. A probe is worth attempting only when the best result any
|
||||
centre value could give would prove the slice, and a ball with `L r >= 2` is
|
||||
`[-1, 1]` whatever `snoise(c)` is, so it costs nothing. CultMath owns none of the
|
||||
envelope: the interval files have no envelope function, and each consumer composes
|
||||
its own. `NoiseBoundTests.EnvelopeBoundEnclosesDensity` checks that composition,
|
||||
the one the site and Aetheria use, over 2,000 seeded slices x 64 warped points
|
||||
with no tolerance.
|
||||
|
||||
`L` has provenance, not a proof. `NoiseBoundTests.MeasureLipschitz` (slow,
|
||||
explicit) takes the largest `|snoise_grad|` over 1e6 seeded points in
|
||||
[-256, 256]^3 (7.1933103), refines the 1e4 largest by gradient ascent
|
||||
(7.2400064), and multiplies by 1.10: `L = 7.9640074`. It also reaches
|
||||
`|snoise| = 0.9718335` by the same ascent on the value, which is what lets the
|
||||
bound intersect with `[-1, 1]`. `LipschitzConstantPinsSampledGradients`
|
||||
checks 1e5 more seeded points against `L` and climbs again from the start
|
||||
`MeasureLipschitz` prints as its witness, failing if `L` is not 1.10 times that
|
||||
maximum to within half a percent, so a 1% move of `L` fails. The enclosure tests
|
||||
over 2,000 balls x 64 points are the defence. A change to the `snoise` kernel
|
||||
must re-run `MeasureLipschitz` and re-pin `L` and the witness.
|
||||
|
||||
What the ball bounds guarantee: enclosure of `snoise` and `fbm_grad(...).w` over
|
||||
the ball, in float32. What they do not: anything about tapes, pruning or choice tracking. Correlation
|
||||
between the operands of one expression is what "Affine forms" below adds.
|
||||
How loose the ball bounds are is a number:
|
||||
`NoiseBoundTests.TightnessReport` prints the mean interval width over the
|
||||
sampled range: 5.08 for `iv_snoise_ball` at `r = 0.05`, 1.96 at 0.25 and 1.28
|
||||
at 1.0; 6.64 and 2.82 for 4-octave `iv_fbm_ball` at 0.05 and 0.25.
|
||||
|
||||
The saving is measured where there is empty space to find.
|
||||
`NoiseBoundTests.IntervalSkipHalvesEvaluations` draws screen tiles, each with
|
||||
its own camera, and runs one pre-pass per tile over the dense grid's cell ranges:
|
||||
it starts with the whole grid, skips and doubles a range it proves empty, halves
|
||||
one it cannot, and runs to the grid's end. It then draws the tile's `N^2` ray
|
||||
slopes, one per pixel, jittered inside it. Each ray is marched three times with
|
||||
the same integrator and the same early-out at transmittance 0.02: over every
|
||||
cell (dense), over the tile's unproven cells (the tile march), and over the
|
||||
oracle mask, the cells whose mid-depth density is nonzero for at least one of
|
||||
the tile's rays. The tile march and the oracle march integrate the dense march's
|
||||
nonzero cells, so their transmittance agrees with it exactly in every
|
||||
configuration. The oracle is a ceiling the pre-pass cannot move: dense cost over
|
||||
oracle cost. Against it the test prints the efficiency (oracle cost over the
|
||||
tile march's cost with its probes) and the cull fraction (the oracle-empty cells
|
||||
the pre-pass proves empty). The probe overhead is the tile march's cost over that
|
||||
cost plus the probes'. Cost is counted in `snoise` evaluations, with an envelope
|
||||
evaluation or probe weighted 0.2. That weight is an estimate, and both counts are
|
||||
printed. The flow is not counted. At `N = 8`, in Aetheria's units on its
|
||||
256-cell quadratic grid out to the Main Camera's far plane, 2048:
|
||||
|
||||
- (a) Height fog, camera above the safety band, rays level and up: the whole
|
||||
grid is one envelope probe per tile, against 256 envelope evaluations per ray,
|
||||
16384x. Every cell is oracle-empty and the pre-pass proves them all.
|
||||
- (b) Inside the fog: 1.16x, and 1.11x with the warp. Most cells are fog, and
|
||||
the pre-pass probes each one.
|
||||
- (c) The deep well (ruling `wells-scale-order-of-magnitude`): the zone bowl
|
||||
plus one well at its centre, `PowerPulse` exponent 2, scale 2220, depth 600.
|
||||
The band `G = 60` is where only the noise decides density (`s` within
|
||||
`F -+ 1.5 A` with the fade at 1); depth and half-depth radius are each
|
||||
`10 G`. The camera's `xz` is uniform within 300 of the centre, at
|
||||
`y = F - h(xz) / 2`, so it looks across the bowl from inside it. Both rows run
|
||||
on the same seeds. With no warp, the centred interval takes 3.20x (oracle
|
||||
ceiling 5.24x, efficiency 0.611, cull fraction 0.988, probe overhead 0.940)
|
||||
and the affine bound 3.57x (efficiency 0.682, cull 0.993, overhead 0.905). With
|
||||
the warp `D = 60`: 3.12x (ceiling 5.31x, efficiency 0.588, cull 0.987, overhead
|
||||
0.929) against 3.46x (efficiency 0.651, cull 0.993, overhead 0.880), so affine
|
||||
is 1.12x and 1.11x cheaper. The range mask (the oracle cells plus every cell
|
||||
where any of 5 x 5 slopes x 9 depths has density above zero) gives a range
|
||||
ceiling of 0.859 (0.848 with the warp), the cost a bound that proves exactly
|
||||
the range-empty cells would reach against the oracle's; the efficiencies
|
||||
against it are 0.794 and 0.712 (warp 0), 0.768 and 0.694 (warp `D`).
|
||||
- (c-band) The shallow wells, four mass-derived wells in the zone bowl with
|
||||
the camera gazing across, whose geometry is band-dominated, printed only.
|
||||
Centred interval 3.01x (efficiency 0.414, cull 0.960, overhead 0.958), affine
|
||||
3.95x (0.544, 0.980, 0.901); with the warp 2.75x (0.383, 0.954, 0.944) against
|
||||
3.54x (0.494, 0.976, 0.865).
|
||||
- (d) r1's uniform slab, which has no envelope: 1.38x with the warp 0.05, and
|
||||
1.67x with no warp.
|
||||
- (e) The void at the shipped point (ruling `operator-shipped-void`): `Rh = 198`,
|
||||
`S = 50`, `Rc = Rh + S = 248`, `e = -ln 1.5 / ln(1 - (Rh / Rc)^2)`, the
|
||||
shipped camera, 200 tiles. The fixed-step reference takes 36.34 steps per
|
||||
pixel. The same cells masked by the pre-pass take 20.08, with identical
|
||||
transmittance. The footprint-aware march takes 13.50: 2.69x fewer. `snoise`
|
||||
per pixel goes from 32.98 to 26.70, and combined cost from 40.25 to 29.54 with
|
||||
the probes, 1.36x. Every one of the 200 tiles proves a body. Before the body
|
||||
both marches are measured against a converged one (midpoint quadrature at
|
||||
`h = 0.5` over every cell, trusting no pre-pass): the relative optical-depth
|
||||
error at the body start is at most 0.0608 for the fixed-step march and 0.08639
|
||||
for the footprint march, 1.42x. Over the grid of hollow radius, camera offset
|
||||
and ramp width the steps ratio runs from 1.59x (`Rh = 100`, low, `S = 150`) to
|
||||
27.45x (`Rh = 1000`, centred, `S = 10`), the cost ratio from 1.26x to 3.89x,
|
||||
and the depth-error ratio from 0.85 to 4.72 (`Rh = 200`, centred, `S = 150`,
|
||||
where the errors are 0.01504 and 0.003188). LOD-far takes 14.19x fewer steps;
|
||||
its depth errors, 0.2849 and 0.205, are not comparable, because its
|
||||
fixed-step reference keeps the octaves the footprint march truncates.
|
||||
|
||||
The analytic body (ruling `operator-analytic-wall-body`). When a single dense
|
||||
cell's own bound is a positive point, the pre-pass spends one more probe over
|
||||
the rest of the grid. If that bound is a positive point too, every point of
|
||||
every ray of the tile from there on has exactly that density, so the footprint
|
||||
march takes one closed-form step, `exp(-BodyDepth)`, from the body start to the
|
||||
grid's end and stops. `BodyDepth` is density x extinction x length x `|dir|`.
|
||||
`NoiseBoundTests.AnalyticBodyMatchesFineMarch` pins it: the bound, the mask and
|
||||
the pointwise densities agree exactly at the body, and `BodyDepth` equals the
|
||||
summed fixed-step depth of the body cells within 1e-4 relative. The comparison
|
||||
is in the depth domain, so LOD-far's deep bodies do not underflow.
|
||||
|
||||
The footprint-truncated void weights its octaves by `w_i(z)`, decreasing in `z`.
|
||||
Its bound takes each weight over `[w_i(z1), 1]` rather than
|
||||
`[w_i(z1), w_i(z0)]`, because one bound serves both the full field (`w = 1`) and
|
||||
the truncated one. `[w_i(z1), 1]` contains both, and `iv_mul` is monotone in its
|
||||
interval argument, so the composed interval encloses both fields.
|
||||
`NoiseBoundTests.WeightBoundEnclosesOneSignedNoise` checks it on LOD-far over
|
||||
2,000 segments: each weight lies in its bound, and `w(z) n` lies in
|
||||
`iv_mul(bound, n)` for a one-signed `n`. A lower end of `w(z0)` fails it.
|
||||
|
||||
The contracts, at `N = 8`, the lower of warp 0 and `D`:
|
||||
|
||||
- (a) at least 2x combined cost;
|
||||
- (c) on the deep well (rulings `affine-wells-contract-cheaper-than-interval`
|
||||
and `wells-overhead-plus-floor`): the affine bound's combined cost ratio is
|
||||
above the centred interval's at warp 0 and at warp `D`; and, hard, the
|
||||
pre-pass proves at least half of the oracle-empty cells empty under both
|
||||
bounds, so a pre-pass that skips nothing fails. The probe overhead, the
|
||||
efficiencies against the oracle and the range ceiling, the ceilings and the
|
||||
cull fraction are printed, not asserted; (c-band) is printed only;
|
||||
- (e) at the shipped void: the masked fixed-step march agrees with the reference
|
||||
exactly; the footprint march's optical depth at the body start is off the
|
||||
converged march's by at most twice the fixed-step march's error; and it takes
|
||||
at most half the reference's steps per pixel.
|
||||
|
||||
This run meets every contract: (a) 16384x, (c) affine 3.57x and 3.46x against
|
||||
the centred interval's 3.20x and 3.12x, with a cull fraction of 0.987 at the
|
||||
lowest, (e) 2.69x fewer steps and a depth error 1.42x the fixed-step march's.
|
||||
The fields, the grids, the 0.2 envelope weight and the 2.0 gradient weight are
|
||||
not tuned toward the contracts. An affine probe is one `snoise_grad`, counted at
|
||||
2.0 `snoise` evaluations (an estimate, printed beside the count).
|
||||
|
||||
Consumers: the gamecult.org ground shader (through the GLSL lowering) and
|
||||
Aetheria's nebula raymarch at its CultMath pin bump.
|
||||
|
||||
## Affine forms
|
||||
|
||||
`math.Affine.cs` carries reduced affine forms with one shared symbol: a
|
||||
`float3(x0, a, e)` is the set `x0 + a eps + e delta` with `eps` and `delta` in
|
||||
`[-1, 1]` and `e >= 0` (Messine's AF1, as Gamito and Maddock use it for gradient
|
||||
noise, in one register as an interval is a `float2`). `eps` is shared by every
|
||||
form over one region (for a screen-tile slice, the depth parameter, `z = z_m +
|
||||
h eps`), so `af_sub(x, x)` has `a = 0`; `delta` is private to the form, and
|
||||
every term that cannot be tracked is condensed into `e`. A slice is a
|
||||
`float4(centre, radius)` with a `float3` axis. No op takes a compound type, a
|
||||
reference parameter or a swizzle write, so each mirrors into the HLSL common
|
||||
subset.
|
||||
|
||||
The ops: `af_point`, `af_symbol`, `af_from_iv`, `af_range` (the bridge back to
|
||||
`iv_*`), `af_add`, `af_sub`, `af_neg`, `af_scale`, `af_add_iv`, `af_mul` (the
|
||||
product `|a_x a_y|` and the cross-error terms condensed into `e`, so there is
|
||||
no `af_sqr`), `af_snoise` and `af_fbm`, and the slice pair `af_frustum_axis` and
|
||||
`af_frustum_ball`.
|
||||
|
||||
Rounding. Every op returns a form whose set at each `eps` contains the float32
|
||||
value of its function at every point of its operands' sets at that `eps`. Each
|
||||
op folds its own float32 rounding into `e` as `S 2^-20`, `S` the sum of the
|
||||
magnitudes its roundings are relative to (named in the op's comment): at most
|
||||
`8u S` is needed with `u = 2^-24`, and the factor of two over that is the
|
||||
allowance for a device whose `+` and `*` are faithful rather than correctly
|
||||
rounded. `AffineTests.EveryOpEnclosesItsPoints` evaluates the form's set in
|
||||
double and the function in float32 with no tolerance. Products and `af_from_iv` also
|
||||
add `2^-126`, the most an underflow to a subnormal can lose (`TinyOperandsEncloseTheirPoints`).
|
||||
`af_from_iv` halves its endpoints before it sums and differences them, and `af_range`
|
||||
scales its terms before it sums them, so endpoints near the float maximum do not overflow
|
||||
in the middle of the op; a form that overflows anyway gives `af_range` infinite endpoints,
|
||||
never NaN (`FromIntervalAndRangeHoldAtTheExtremes`). `af_range` finds a NaN endpoint by its bit pattern, because
|
||||
`lo == lo` is a compare dxc marks `fast` and deletes under its default flags. `AbsorptionsArePinned` and
|
||||
`SnoiseFormCarriesItsDocumentedWidth` pin each absorption and `af_snoise`'s float32 allowance both
|
||||
ways: the enclosure tests alone cannot see them on a CPU, where float32 is exact.
|
||||
|
||||
`af_snoise(centre, axis, radius)` encloses `snoise` over `centre + axis eps + w`,
|
||||
`|w| <= radius`, from one `snoise_grad`. It returns the narrower of the
|
||||
Lipschitz form `(n, 0, L R)` and the centred form `(n, g . axis, |g| radius +
|
||||
M R^2 / 2)` (`R = |axis| + radius`, `L = SNOISE_LIPSCHITZ`, `M =
|
||||
SNOISE_HESSIAN`), so its total width is never more than the Lipschitz form's.
|
||||
The centred form is Taylor's theorem, which is why it beats the ball when the
|
||||
radius is small and the axis carries the variation. `af_fbm` compounds octaves
|
||||
as `iv_fbm_ball` does. The float32 evaluation allowance is derived in
|
||||
`af_snoise`'s comment.
|
||||
|
||||
`SNOISE_HESSIAN = 56.050385` is 1.10 times the refined maximum of the spectral
|
||||
norm of the Hessian of `snoise(float3)`, measured by
|
||||
`NoiseBoundTests.MeasureHessian` over 1e6 seeded points (central differences of
|
||||
`snoise_grad`) and refined by ascent from the 1e4 largest: sampled 50.1366,
|
||||
refined 50.9549, witness (-245.19885, -53.01323, -91.47363).
|
||||
`HessianConstantPinsSampledCurvature` fails on a 1% move.
|
||||
`SNOISE2_LIPSCHITZ = 8.117002` is the same for the gradient of `snoise(float2)`
|
||||
(`MeasureLipschitz2`: sampled 7.2575, refined 7.3791, witness (-67.12454,
|
||||
-129.53296), `|snoise2|` at most 0.99964), and it backs `iv_snoise_ball(float2,
|
||||
float)`. Both are empirical with a margin, not proofs. A random ball cannot see a
|
||||
curvature constant 20% low, so `SNOISE_HESSIAN` is defended by
|
||||
`HessianConstantPinsSampledCurvature` and `SnoiseFormEnclosesTheCurvatureWitness`
|
||||
(`af_snoise` at the point where the curvature is realised, along 4,000 directions: a
|
||||
constant of 40 misses there). The margin over the function itself: a scan of the whole
|
||||
289^3 hash period found a realised maximum of 50.58, and bounding each corner's gradient
|
||||
independently over every hash configuration gives 52.22, so 56.05 sits 7% above the
|
||||
configuration bound. A change to the kernels must re-run the measurements.
|
||||
|
||||
The slice. `af_frustum_ball(centreSlope, z0, z1, footprintPerDepth,
|
||||
warpVariation)` returns the centre `(m_c z_m, z_m)` and a radius `z1
|
||||
footprintPerDepth + warpVariation`, with `af_frustum_axis` the axis `(m_c, 1) h`:
|
||||
every ray point at depth `z` is `centre + axis eps(z) + w`. Its derivation
|
||||
and the clamp residual are in the comment. The caller rotates, translates and
|
||||
scales the slice into the noise's frame, and owns the rounding of that.
|
||||
|
||||
The centred warp. A flow-warped sample reads `snoise` at `p + flow(p) shift`. The
|
||||
caller does not enlarge the ball by the whole displacement `|flow| shift`; it
|
||||
moves the centre by the flow at the centre, `c + flow(c) shift`, and widens the
|
||||
radius by the flow's variation across the ball, `r + |shift| rho` with `rho =
|
||||
FlowAmplitude (SNOISE2_LIPSCHITZ FlowFrequency r + a) sqrt 2` (the clamp to the unit
|
||||
disc is nonexpansive), where `a = 2^-14 + L2 2^-20 (|q|_1 + r FlowFrequency)` is the
|
||||
float32 allowance of the flow's two `snoise(float2)` reads (the point `q` plus its offset rounds at the
|
||||
magnitude of `q`, and a float32 flow at two points of a ball differs by more than the exact
|
||||
function can). CultMath owns neither the flow nor the envelope: the warp's
|
||||
centre and variation are the caller's, and a consumer adds them to the slice's
|
||||
`warpVariation` or to the form's radius. With two phases that cross-fade, each
|
||||
phase takes its own centre; one ball serves when the phases' centres coincide
|
||||
(warp 0). `NoiseBoundTests.CentredWarpStaysEnclosed` checks 2,000 balls, radius 1e-3 to
|
||||
500, and fails when `rho` is dropped or halved; `AffineWarpStaysEnclosed` checks
|
||||
3,000 tile slices of `FogField.Slice`, which returns the final `af_snoise` arguments
|
||||
(each phase's moved centre and grown radius, the detail's unwarped set, the shared axis),
|
||||
so the affine bound wires nothing itself: the reach over which the flow is varied is
|
||||
`|axis| + radius`, each phase carries its own growth, and the gate reads each argument's
|
||||
reach. It fails when the reach is the ball's radius or the larger of the two, a phase's
|
||||
growth is dropped or taken from the other phase, the axis or the detail radius is scaled,
|
||||
or `rho` is halved. `AffineCompositionTightensItsRanges` sees the shared-symbol
|
||||
composition itself: the bound is exactly the intersection of the affine arithmetic's piece
|
||||
and the interval composition over the forms' ranges, and the affine piece is the narrower
|
||||
of the two in at least 35% of the open slices (the piece alone is wider in total).
|
||||
|
||||
The deep well is the representative Aetheria case: the camera inside a sun's
|
||||
bowl, looking across. `DeepWellIsTenBandsDeepAndWide` computes the band `G` from
|
||||
`FogField`'s own floor offset, amplitude and noise range (60) and requires the
|
||||
depth (633 at the centre against the rim) and the half-depth radius to be at
|
||||
least `10 G`, every drawn camera sitting inside the well below the rim; a well of
|
||||
depth 150 fails. The shallow wells stay as the printed shallow-well, band-dominated row (c-band).
|
||||
|
||||
The test field's affine bound takes depth as `af_symbol(z_m, h)`, builds `s`
|
||||
affine in it with the height interval, the footprint and the slope-depth
|
||||
product in `e` through `af_add_iv`, takes the noise through `af_frustum_*` and
|
||||
`af_snoise` per phase and for the detail octave, fades by `af_from_iv` and
|
||||
`af_mul`, reads the range with `af_range`, and intersects with the centred
|
||||
interval's bound (both sound). `FogField.Bound` makes no direct `snoise` call.
|
||||
The cull-map render (`DeepWellCullMap`, explicit) writes a PNG when
|
||||
`CULTMATH_WRITE_CULLMAP` names a directory: one deep-well camera at warp `D`,
|
||||
960 x 540 in 8 x 8 tiles, with panels for dense cells per ray under the centred
|
||||
interval, under the affine bound and under the oracle mask (one logarithmic
|
||||
scale) and the transmittance. Its run: 4.23, 3.60 and 2.02 cells per ray on
|
||||
average, 44 the most, mean transmittance 0.278.
|
||||
|
||||
## Rules
|
||||
|
||||
- Keep type names HLSL-shaped: `float2`, `float3`, `float4`, `float3x3`, and `math`.
|
||||
|
|
|
|||
|
|
@ -27,25 +27,6 @@ if (Test-Path -LiteralPath $outputRoot) {
|
|||
Remove-Item -LiteralPath $outputRoot -Recurse -Force
|
||||
}
|
||||
|
||||
# docs/semver-policy.md (CultLib root, two levels up from this script):
|
||||
# refuse to build a release whose CHANGELOG.md entry claims a breaking change
|
||||
# under too small a bump, or whose version skips or reverses the previous
|
||||
# published tag. Runs before the build below so a bad version number fails
|
||||
# fast. cultmath is pre-1.0 (0.y.z): a breaking change must be at least a
|
||||
# minor bump. $repoRoot above is this package's own root (packages\cultmath),
|
||||
# not CultLib's; the shared checker script lives one level above that.
|
||||
$cultLibRoot = Split-Path -Parent (Split-Path -Parent $repoRoot)
|
||||
$cultmathVersion = (Get-Content -LiteralPath (Join-Path $templateRoot "package.json") -Raw | ConvertFrom-Json).version
|
||||
& node (Join-Path $cultLibRoot "scripts\check-changelog-semver.mjs") `
|
||||
--package "org.gamecult.cultmath" `
|
||||
--changelog (Join-Path $templateRoot "CHANGELOG.md") `
|
||||
--version $cultmathVersion `
|
||||
--tag-prefix "cultmath-unity" `
|
||||
--cwd $cultLibRoot
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "CultMath Unity package failed the semver policy check (see docs/semver-policy.md)."
|
||||
}
|
||||
|
||||
# The tracked DLL and pdb are committed beside their source, so neither may name a commit: Source Link
|
||||
# writes the commit SHA into the pdb, and the DLL carries that pdb's content id.
|
||||
dotnet build $projectPath -c $Configuration -f netstandard2.1 -o $buildRoot --no-incremental `
|
||||
|
|
@ -60,6 +41,27 @@ foreach ($path in @($freshAssembly, $freshSymbols)) {
|
|||
}
|
||||
}
|
||||
|
||||
# docs/semver-policy.md (CultLib root, two levels up from this script): refuse a release whose version
|
||||
# does not tell the truth. The check measures the freshly built CultMath.dll's public API against the
|
||||
# DLL the previous cultmath-unity tag tracked (read from git), so it runs once the build exists.
|
||||
# cultmath is pre-1.0 (0.y.z): a break must be at least a minor bump. $repoRoot above is this package's
|
||||
# own root (packages\cultmath), not CultLib's; the shared checker script lives one level above that.
|
||||
$cultLibRoot = Split-Path -Parent (Split-Path -Parent $repoRoot)
|
||||
$cultmathVersion = (Get-Content -LiteralPath (Join-Path $templateRoot "package.json") -Raw | ConvertFrom-Json).version
|
||||
# The suite pins the checker's rules and the declared tag prefixes, so it runs first.
|
||||
& node --test (Join-Path $cultLibRoot "scripts\check-changelog-semver.test.mjs")
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "The release check suite failed (scripts/check-changelog-semver.test.mjs); not releasing."
|
||||
}
|
||||
& node (Join-Path $cultLibRoot "scripts\check-changelog-semver.mjs") `
|
||||
--package "org.gamecult.cultmath" `
|
||||
--version $cultmathVersion `
|
||||
--cwd $cultLibRoot `
|
||||
--api-built $freshAssembly
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "CultMath Unity package failed the semver policy check (see docs/semver-policy.md)."
|
||||
}
|
||||
|
||||
$requiredTemplateFiles = @(
|
||||
"LICENSE.md",
|
||||
"LICENSE.md.meta",
|
||||
|
|
@ -80,7 +82,11 @@ $requiredTemplateFiles = @(
|
|||
"Shaders\CultMath.hlsl",
|
||||
"Shaders\CultMath.hlsl.meta",
|
||||
"Shaders\CultMath.Phacelle.hlsl",
|
||||
"Shaders\CultMath.Phacelle.hlsl.meta"
|
||||
"Shaders\CultMath.Phacelle.hlsl.meta",
|
||||
"Shaders\CultMath.Interval.hlsl",
|
||||
"Shaders\CultMath.Interval.hlsl.meta",
|
||||
"Shaders\CultMath.Affine.hlsl",
|
||||
"Shaders\CultMath.Affine.hlsl.meta"
|
||||
)
|
||||
foreach ($relativePath in $requiredTemplateFiles) {
|
||||
if (-not (Test-Path -LiteralPath (Join-Path $templateRoot $relativePath) -PathType Leaf)) {
|
||||
|
|
|
|||
11
packages/cultmath/scripts/unity-smoke/Broken.compute
Normal file
11
packages/cultmath/scripts/unity-smoke/Broken.compute
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
#pragma kernel CSMain
|
||||
#include "Packages/org.gamecult.cultmath/Shaders/CultMath.hlsl"
|
||||
#include "Packages/org.gamecult.cultmath/Shaders/CultMath.Interval.hlsl"
|
||||
#include "Packages/org.gamecult.cultmath/Shaders/CultMath.Affine.hlsl"
|
||||
RWStructuredBuffer<float4> Out;
|
||||
[numthreads(1,1,1)] void CSMain(uint3 id : SV_DispatchThreadID)
|
||||
{
|
||||
float2 r = cultmath_iv_add_missing(float2(1, 2), float2(3, 5));
|
||||
float2 a = cultmath_af_range(cultmath_af_add(cultmath_af_point(3), cultmath_af_point(5)));
|
||||
Out[0] = float4(r, a);
|
||||
}
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
{
|
||||
"name": "CultMath.Smoke.Tests",
|
||||
"rootNamespace": "",
|
||||
"references": [ "UnityEngine.TestRunner", "UnityEditor.TestRunner" ],
|
||||
"includePlatforms": [ "Editor" ],
|
||||
"excludePlatforms": [],
|
||||
"allowUnsafeCode": false,
|
||||
"overrideReferences": true,
|
||||
"precompiledReferences": [ "nunit.framework.dll", "CultMath.dll" ],
|
||||
"autoReferenced": false,
|
||||
"defineConstraints": [ "UNITY_INCLUDE_TESTS" ],
|
||||
"versionDefines": [],
|
||||
"noEngineReferences": false
|
||||
}
|
||||
11
packages/cultmath/scripts/unity-smoke/Good.compute
Normal file
11
packages/cultmath/scripts/unity-smoke/Good.compute
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
#pragma kernel CSMain
|
||||
#include "Packages/org.gamecult.cultmath/Shaders/CultMath.hlsl"
|
||||
#include "Packages/org.gamecult.cultmath/Shaders/CultMath.Interval.hlsl"
|
||||
#include "Packages/org.gamecult.cultmath/Shaders/CultMath.Affine.hlsl"
|
||||
RWStructuredBuffer<float4> Out;
|
||||
[numthreads(1,1,1)] void CSMain(uint3 id : SV_DispatchThreadID)
|
||||
{
|
||||
float2 r = cultmath_iv_add(float2(1, 2), float2(3, 5));
|
||||
float2 a = cultmath_af_range(cultmath_af_add(cultmath_af_point(3), cultmath_af_point(5)));
|
||||
Out[0] = float4(r, a);
|
||||
}
|
||||
44
packages/cultmath/scripts/unity-smoke/SmokeTests.cs
Normal file
44
packages/cultmath/scripts/unity-smoke/SmokeTests.cs
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
using System;
|
||||
using CultMath;
|
||||
using NUnit.Framework;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
using UnityEngine.TestTools;
|
||||
|
||||
public class SmokeTests
|
||||
{
|
||||
// Compiles by FindKernel and dispatches on the device; false when the shader does not compile or the output is wrong.
|
||||
static bool CompilesAndRuns(string path)
|
||||
{
|
||||
var cs = AssetDatabase.LoadAssetAtPath<ComputeShader>(path);
|
||||
Assert.IsNotNull(cs, path);
|
||||
int k;
|
||||
try { k = cs.FindKernel("CSMain"); } catch (Exception e) { Debug.Log("SMOKE " + path + " FindKernel threw: " + e.Message); return false; }
|
||||
if (!cs.HasKernel("CSMain") || !cs.IsSupported(k)) { Debug.Log("SMOKE " + path + " kernel unusable"); return false; }
|
||||
var buf = new ComputeBuffer(1, 16);
|
||||
try
|
||||
{
|
||||
cs.SetBuffer(k, "Out", buf);
|
||||
cs.Dispatch(k, 1, 1, 1);
|
||||
var o = new Vector4[1]; buf.GetData(o);
|
||||
Debug.Log($"SMOKE {path} out=({o[0].x},{o[0].y},{o[0].z},{o[0].w}) gpu={SystemInfo.graphicsDeviceType}");
|
||||
return o[0].x == 4f && o[0].y == 7f && o[0].z <= 8f && o[0].w >= 8f && o[0].w - o[0].z < 1e-3f;
|
||||
}
|
||||
finally { buf.Release(); }
|
||||
}
|
||||
|
||||
[Test] public void CSharpIntervalAndAffineWork()
|
||||
{
|
||||
var r = math.iv_add(new float2(1, 2), new float2(3, 5));
|
||||
Assert.AreEqual(4f, r.x); Assert.AreEqual(7f, r.y);
|
||||
Assert.AreEqual(0f, math.snoise(new float3(0, 0, 0)));
|
||||
}
|
||||
|
||||
[Test] public void RealShaderCompilesAndDispatches() { Assert.IsTrue(CompilesAndRuns("Assets/Shaders/Good.compute")); }
|
||||
|
||||
[Test] public void BrokenShaderIsDetected()
|
||||
{
|
||||
LogAssert.ignoreFailingMessages = true;
|
||||
Assert.IsFalse(CompilesAndRuns("Assets/Shaders/Broken.compute"));
|
||||
}
|
||||
}
|
||||
94
packages/cultmath/scripts/unity-smoke/run-unity-smoke.ps1
Normal file
94
packages/cultmath/scripts/unity-smoke/run-unity-smoke.ps1
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
<#
|
||||
.SYNOPSIS
|
||||
The release smoke for the tracked org.gamecult.cultmath Unity package: imports it into a
|
||||
scratch project, compiles and dispatches a compute shader that includes the package's
|
||||
CultMath.Interval.hlsl and CultMath.Affine.hlsl on a real graphics device, and proves a
|
||||
deliberately broken shader is rejected.
|
||||
|
||||
.DESCRIPTION
|
||||
Run it on a Windows machine with a GPU, alone, before tagging cultmath-unity-v*. The scratch
|
||||
project is built outside the repository under -WorkRoot, references the package by a file: path,
|
||||
and is deleted afterwards (-Keep leaves it). Exit 0 only when Unity exited 0, this run wrote the
|
||||
results file (earlier ones are deleted before launch), and all three tests of SmokeTests.cs
|
||||
passed: the C# calls, the real shader dispatched with the right output, and the broken control
|
||||
shader detected.
|
||||
|
||||
Never add -nographics. Without a device nothing compiles, and
|
||||
ShaderUtil.GetComputeShaderMessageCount reports 0 messages for a compute shader that calls an
|
||||
undeclared function until FindKernel or Dispatch compiles it, so a message-count check passes a
|
||||
broken shader. SmokeTests.cs compiles by FindKernel, dispatches, and reads the output back.
|
||||
|
||||
For a long run start it detached and poll the log, for example:
|
||||
Start-Process powershell -WindowStyle Hidden -ArgumentList '-File', '<this script>', '-UnityExe', '<Unity.exe>', '-WorkRoot', '<dir>'
|
||||
The script writes unity.pid and unity.log under the scratch root's logs folder (kept after the run).
|
||||
|
||||
.PARAMETER UnityExe
|
||||
Path to Unity.exe of the editor to test with (the cut that released 0.4.0 used 6000.3.24f1).
|
||||
.PARAMETER WorkRoot
|
||||
Directory outside the repository for the scratch project and logs. Default: a new folder under TEMP.
|
||||
.PARAMETER Keep
|
||||
Keep the scratch project instead of deleting it.
|
||||
#>
|
||||
param(
|
||||
[Parameter(Mandatory)] [string] $UnityExe,
|
||||
[string] $WorkRoot = (Join-Path $env:TEMP ("cultmath-unity-smoke-" + [guid]::NewGuid().ToString('N').Substring(0, 8))),
|
||||
[switch] $Keep
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
if (-not (Test-Path -LiteralPath $UnityExe -PathType Leaf)) { throw "UnityExe not found: $UnityExe" }
|
||||
|
||||
$smoke = $PSScriptRoot
|
||||
$package = (Resolve-Path (Join-Path $smoke '..\..\unity\org.gamecult.cultmath')).Path
|
||||
$repoRoot = (git -C $smoke rev-parse --show-toplevel).Trim()
|
||||
$work = [IO.Path]::GetFullPath($WorkRoot)
|
||||
if ($work.StartsWith([IO.Path]::GetFullPath($repoRoot), [StringComparison]::OrdinalIgnoreCase)) {
|
||||
throw "WorkRoot must be outside the repository: $work"
|
||||
}
|
||||
$project = Join-Path $work 'project'
|
||||
$logs = Join-Path $work 'logs'
|
||||
New-Item -ItemType Directory -Force -Path $logs | Out-Null
|
||||
foreach ($d in 'Packages', 'Assets\Shaders', 'Assets\Tests') { New-Item -ItemType Directory -Force -Path (Join-Path $project $d) | Out-Null }
|
||||
|
||||
Copy-Item -LiteralPath (Join-Path $smoke 'Good.compute'), (Join-Path $smoke 'Broken.compute') -Destination (Join-Path $project 'Assets\Shaders')
|
||||
Copy-Item -LiteralPath (Join-Path $smoke 'SmokeTests.cs'), (Join-Path $smoke 'CultMath.Smoke.Tests.asmdef') -Destination (Join-Path $project 'Assets\Tests')
|
||||
|
||||
$packageUri = 'file:' + $package.Replace([string][char]92, '/')
|
||||
$manifest = [ordered]@{
|
||||
dependencies = [ordered]@{
|
||||
'com.unity.test-framework' = '1.6.0'
|
||||
'org.gamecult.cultmath' = $packageUri
|
||||
}
|
||||
}
|
||||
[IO.File]::WriteAllText((Join-Path $project 'Packages\manifest.json'), ($manifest | ConvertTo-Json -Depth 4), (New-Object Text.UTF8Encoding($false)))
|
||||
|
||||
$log = Join-Path $logs 'unity.log'
|
||||
$results = Join-Path $logs 'results.xml'
|
||||
# A kept logs folder may hold an earlier run's evidence: nothing from a previous run may decide this one.
|
||||
foreach ($stale in $log, $results, (Join-Path $logs 'unity.pid')) { Remove-Item -LiteralPath $stale -Force -ErrorAction SilentlyContinue }
|
||||
if (Test-Path -LiteralPath $results) { throw "could not clear the previous results file: $results" }
|
||||
$unityArgs = @('-batchmode', '-projectPath', $project, '-runTests', '-testPlatform', 'EditMode',
|
||||
'-testResults', $results, '-logFile', $log)
|
||||
$launched = Get-Date
|
||||
$p = Start-Process -PassThru -FilePath $UnityExe -ArgumentList $unityArgs -WindowStyle Hidden
|
||||
$p.Id | Out-File (Join-Path $logs 'unity.pid') -Encoding ascii
|
||||
"unity pid=$($p.Id) log=$log"
|
||||
$p.WaitForExit()
|
||||
"unity exit=$($p.ExitCode)"
|
||||
|
||||
# Pass needs all of: Unity exited 0; a results file written by this run; the real shader test passed and
|
||||
# the broken control test passed (it asserts that the broken shader is rejected).
|
||||
$ok = $false
|
||||
if ($p.ExitCode -ne 0) { "unity exited non-zero: $($p.ExitCode)" }
|
||||
elseif (-not (Test-Path -LiteralPath $results)) { 'no results file from this run' }
|
||||
elseif ((Get-Item -LiteralPath $results).LastWriteTime -lt $launched) { 'results file predates this run' }
|
||||
else {
|
||||
$cases = @(([xml](Get-Content -LiteralPath $results -Raw)).SelectNodes('//test-case'))
|
||||
$cases | ForEach-Object { "{0} {1}" -f $_.result, $_.name }
|
||||
$want = 'CSharpIntervalAndAffineWork', 'RealShaderCompilesAndDispatches', 'BrokenShaderIsDetected'
|
||||
$passed = @($cases | Where-Object { $_.result -eq 'Passed' } | ForEach-Object { ($_.name -split '\.')[-1] })
|
||||
$ok = (@($want | Where-Object { $passed -contains $_ }).Count -eq $want.Count)
|
||||
}
|
||||
Get-Content -LiteralPath $log -ErrorAction SilentlyContinue | Select-String -CaseSensitive -Pattern '^SMOKE ' | ForEach-Object { $_.Line }
|
||||
|
||||
if (-not $Keep) { Remove-Item -LiteralPath $project -Recurse -Force }
|
||||
if ($ok) { 'SMOKE PASSED'; exit 0 } else { 'SMOKE FAILED'; exit 1 }
|
||||
132
packages/cultmath/shaders/CultMath.Affine.hlsl
Normal file
132
packages/cultmath/shaders/CultMath.Affine.hlsl
Normal file
|
|
@ -0,0 +1,132 @@
|
|||
#ifndef CULTMATH_AFFINE_HLSL
|
||||
#define CULTMATH_AFFINE_HLSL
|
||||
|
||||
// Reduced affine forms with one shared symbol over float3(x0, a, e): the set { x0 + a eps + e delta :
|
||||
// delta in [-1, 1] } at the region's shared eps in [-1, 1], e >= 0. Every cultmath_af_* function mirrors
|
||||
// math.Affine.cs bit for bit; see that file and docs/design.md ("Affine forms") for each op's enclosure
|
||||
// and the float32 rounding allowance it folds into e. Included by CultMath.hlsl after
|
||||
// CultMath.Interval.hlsl, whose CULTMATH_SNOISE_LIPSCHITZ it shares, and after its own
|
||||
// definition of cultmath_snoise_grad.
|
||||
|
||||
// An upper bound on the spectral norm of the Hessian of cultmath_snoise(float3); provenance in
|
||||
// math.Affine.cs (SNOISE_HESSIAN).
|
||||
static const float CULTMATH_SNOISE_HESSIAN = 56.050385;
|
||||
|
||||
float3 cultmath_af_point(float value) { return float3(value, 0.0, 0.0); }
|
||||
float3 cultmath_af_symbol(float x0, float a) { return float3(x0, a, 0.0); }
|
||||
|
||||
float3 cultmath_af_from_iv(float2 interval)
|
||||
{
|
||||
float x0 = interval.x * 0.5 + interval.y * 0.5;
|
||||
float e = interval.y * 0.5 - interval.x * 0.5;
|
||||
return float3(x0, 0.0, e + (abs(x0) + e) * 9.5367431640625e-7 + 1.17549435e-38);
|
||||
}
|
||||
|
||||
// An endpoint that would be NaN is the infinity on its side. NaN is found by its bit pattern: dxc marks
|
||||
// compares fast, so a test that needs NaN to make `lo == lo` false is deleted under its default flags.
|
||||
float2 cultmath_af_range(float3 x)
|
||||
{
|
||||
float r = abs(x.y) + x.z;
|
||||
float w = abs(x.x) * 9.5367431640625e-7 + r * 9.5367431640625e-7;
|
||||
float lo = x.x - r - w;
|
||||
float hi = x.x + r + w;
|
||||
return float2((asuint(lo) & 0x7fffffffu) > 0x7f800000u ? asfloat(0xff800000u) : lo,
|
||||
(asuint(hi) & 0x7fffffffu) > 0x7f800000u ? asfloat(0x7f800000u) : hi);
|
||||
}
|
||||
|
||||
float3 cultmath_af_add(float3 x, float3 y)
|
||||
{
|
||||
float x0 = x.x + y.x;
|
||||
float a = x.y + y.y;
|
||||
float e = x.z + y.z;
|
||||
return float3(x0, a, e + (abs(x0) + abs(a) + e) * 9.5367431640625e-7);
|
||||
}
|
||||
|
||||
float3 cultmath_af_sub(float3 x, float3 y)
|
||||
{
|
||||
float x0 = x.x - y.x;
|
||||
float a = x.y - y.y;
|
||||
float e = x.z + y.z;
|
||||
return float3(x0, a, e + (abs(x0) + abs(a) + e) * 9.5367431640625e-7);
|
||||
}
|
||||
|
||||
float3 cultmath_af_neg(float3 x) { return float3(-x.x, -x.y, x.z); }
|
||||
|
||||
float3 cultmath_af_scale(float3 x, float s)
|
||||
{
|
||||
float x0 = x.x * s;
|
||||
float a = x.y * s;
|
||||
float e = x.z * abs(s);
|
||||
return float3(x0, a, e + (abs(x0) + abs(a) + e) * 9.5367431640625e-7 + 1.17549435e-38);
|
||||
}
|
||||
|
||||
float3 cultmath_af_add_iv(float3 x, float2 interval) { return cultmath_af_add(x, cultmath_af_from_iv(interval)); }
|
||||
|
||||
float3 cultmath_af_mul(float3 x, float3 y)
|
||||
{
|
||||
float x0 = x.x * y.x;
|
||||
float p = x.x * y.y;
|
||||
float q = y.x * x.y;
|
||||
float a = p + q;
|
||||
float e = abs(x.x) * y.z + abs(y.x) * x.z + (abs(x.y) + x.z) * (abs(y.y) + y.z);
|
||||
return float3(x0, a, e + (abs(x0) + abs(p) + abs(q) + e) * 9.5367431640625e-7 + 1.17549435e-38);
|
||||
}
|
||||
|
||||
// The narrower of the Lipschitz form and the centred (Taylor) form over every p = centre + axis eps + w,
|
||||
// |w| <= radius, from one cultmath_snoise_grad at the centre; the allowance for the float32 evaluation is
|
||||
// in math.Affine.cs.
|
||||
float3 cultmath_af_snoise(float3 centre, float3 axis, float radius)
|
||||
{
|
||||
float4 g = cultmath_snoise_grad(centre);
|
||||
float3 gradient = float3(g.x, g.y, g.z);
|
||||
float reach = length(axis) + radius;
|
||||
float lipschitz = CULTMATH_SNOISE_LIPSCHITZ * reach;
|
||||
float a = dot(gradient, axis);
|
||||
float remainder = length(gradient) * radius + 0.5 * CULTMATH_SNOISE_HESSIAN * reach * reach;
|
||||
float allowance = 6.103515625e-5 + 2.44140625e-4 * reach
|
||||
+ CULTMATH_SNOISE_LIPSCHITZ * 9.5367431640625e-7 * (abs(centre.x) + abs(centre.y) + abs(centre.z) + reach);
|
||||
bool centred = abs(a) + remainder < lipschitz;
|
||||
float slope = centred ? a : 0.0;
|
||||
float e = (centred ? remainder : lipschitz) + allowance;
|
||||
return float3(g.w, slope, e + (abs(g.w) + abs(slope) + e) * 9.5367431640625e-7);
|
||||
}
|
||||
|
||||
// Octave sum of cultmath_af_snoise, compounding frequency and amplitude as the value-and-gradient fBm does.
|
||||
float3 cultmath_af_fbm(float3 centre, float3 axis, float radius, int octaves, float lacunarity, float gain)
|
||||
{
|
||||
octaves = clamp(octaves, 0, 16);
|
||||
float amplitude = 1.0;
|
||||
float frequency = 1.0;
|
||||
float3 sum = float3(0.0, 0.0, 0.0);
|
||||
for (int i = 0; i < octaves; i++)
|
||||
{
|
||||
sum = cultmath_af_add(sum, cultmath_af_scale(cultmath_af_snoise(centre * frequency, axis * frequency, radius * abs(frequency)), amplitude));
|
||||
frequency *= lacunarity;
|
||||
amplitude *= gain;
|
||||
}
|
||||
|
||||
return sum;
|
||||
}
|
||||
|
||||
// The axis of a screen tile's slice over the depth segment [z0, z1]; camera frame of
|
||||
// cultmath_iv_frustum_ball.
|
||||
float3 cultmath_af_frustum_axis(float2 centreSlope, float z0, float z1)
|
||||
{
|
||||
float h = (z1 - z0) * 0.5;
|
||||
return float3(centreSlope.x * h, centreSlope.y * h, h);
|
||||
}
|
||||
|
||||
// The affine slice of a screen tile over [z0, z1]: centre xyz, radius w. Derivation in math.Affine.cs.
|
||||
float4 cultmath_af_frustum_ball(float2 centreSlope, float z0, float z1, float footprintPerDepth, float warpVariation)
|
||||
{
|
||||
float zm = (z0 + z1) * 0.5;
|
||||
float h = (z1 - z0) * 0.5;
|
||||
float cx = centreSlope.x * zm;
|
||||
float cy = centreSlope.y * zm;
|
||||
float spread = (abs(centreSlope.x) + abs(centreSlope.y) + 1.0) * h;
|
||||
float radius = z1 * footprintPerDepth + warpVariation;
|
||||
radius += (abs(cx) + abs(cy) + abs(zm) + spread + radius) * 9.5367431640625e-7;
|
||||
return float4(cx, cy, zm, radius);
|
||||
}
|
||||
|
||||
#endif
|
||||
7
packages/cultmath/shaders/CultMath.Affine.hlsl.meta
Normal file
7
packages/cultmath/shaders/CultMath.Affine.hlsl.meta
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 26f28fce38e14eed8b9b5dbd758e4ffc
|
||||
ShaderIncludeImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
133
packages/cultmath/shaders/CultMath.Interval.hlsl
Normal file
133
packages/cultmath/shaders/CultMath.Interval.hlsl
Normal file
|
|
@ -0,0 +1,133 @@
|
|||
#ifndef CULTMATH_INTERVAL_HLSL
|
||||
#define CULTMATH_INTERVAL_HLSL
|
||||
|
||||
// Interval arithmetic over float2(lo, hi), lo <= hi, both finite. Every cultmath_iv_* function returns
|
||||
// an interval containing f(x) for every x in its input intervals, mirroring math.Interval.cs bit for
|
||||
// bit; see that file and docs/design.md ("Intervals") for each op's enclosure and its ulp widening.
|
||||
// Included by CultMath.hlsl after its own definitions of cultmath_smoothstep and cultmath_snoise.
|
||||
|
||||
// Lipschitz constant of cultmath_snoise(float3); provenance in math.Interval.cs (SNOISE_LIPSCHITZ).
|
||||
static const float CULTMATH_SNOISE_LIPSCHITZ = 7.9640074;
|
||||
|
||||
// Lipschitz constant of cultmath_snoise(float2); provenance in math.Interval.cs (SNOISE2_LIPSCHITZ).
|
||||
static const float CULTMATH_SNOISE2_LIPSCHITZ = 8.117002;
|
||||
|
||||
float2 cultmath_iv_point(float value) { return float2(value, value); }
|
||||
float2 cultmath_iv_add(float2 a, float2 b) { return float2(a.x + b.x, a.y + b.y); }
|
||||
float2 cultmath_iv_sub(float2 a, float2 b) { return float2(a.x - b.y, a.y - b.x); }
|
||||
float2 cultmath_iv_neg(float2 a) { return float2(-a.y, -a.x); }
|
||||
|
||||
float2 cultmath_iv_mul(float2 a, float2 b)
|
||||
{
|
||||
float p0 = a.x * b.x;
|
||||
float p1 = a.x * b.y;
|
||||
float p2 = a.y * b.x;
|
||||
float p3 = a.y * b.y;
|
||||
return float2(min(min(p0, p1), min(p2, p3)), max(max(p0, p1), max(p2, p3)));
|
||||
}
|
||||
|
||||
float2 cultmath_iv_scale(float2 a, float s) { return s >= 0.0 ? float2(a.x * s, a.y * s) : float2(a.y * s, a.x * s); }
|
||||
|
||||
float2 cultmath_iv_abs(float2 a)
|
||||
{
|
||||
if (a.x >= 0.0)
|
||||
return a;
|
||||
if (a.y <= 0.0)
|
||||
return float2(-a.y, -a.x);
|
||||
return float2(0.0, max(-a.x, a.y));
|
||||
}
|
||||
|
||||
float2 cultmath_iv_min(float2 a, float2 b) { return float2(min(a.x, b.x), min(a.y, b.y)); }
|
||||
float2 cultmath_iv_max(float2 a, float2 b) { return float2(max(a.x, b.x), max(a.y, b.y)); }
|
||||
|
||||
float2 cultmath_iv_sqr(float2 a)
|
||||
{
|
||||
float l = a.x * a.x;
|
||||
float h = a.y * a.y;
|
||||
if (a.x >= 0.0)
|
||||
return float2(l, h);
|
||||
if (a.y <= 0.0)
|
||||
return float2(h, l);
|
||||
return float2(0.0, max(l, h));
|
||||
}
|
||||
|
||||
float2 cultmath_iv_sqrt(float2 a) { return float2(sqrt(max(a.x, 0.0)), sqrt(max(a.y, 0.0))); }
|
||||
|
||||
// Widened by one ulp on each side: exp is not required to be correctly rounded.
|
||||
float2 cultmath_iv_exp(float2 a)
|
||||
{
|
||||
float lo = exp(a.x);
|
||||
float hi = exp(a.y);
|
||||
return float2(lo > 0.0 ? asfloat(asuint(lo) - 1u) : 0.0, asfloat(asuint(hi) + 1u));
|
||||
}
|
||||
|
||||
float2 cultmath_iv_clamp(float2 a, float minimum, float maximum)
|
||||
{
|
||||
return float2(cultmath_clamp(a.x, minimum, maximum), cultmath_clamp(a.y, minimum, maximum));
|
||||
}
|
||||
|
||||
float2 cultmath_iv_saturate(float2 a) { return float2(cultmath_saturate(a.x), cultmath_saturate(a.y)); }
|
||||
|
||||
// The endpoints, ordered, widened by one ulp inside [0, 1]: the float32 evaluation of smoothstep is
|
||||
// monotone only to within one ulp.
|
||||
float2 cultmath_iv_smoothstep(float minimum, float maximum, float2 a)
|
||||
{
|
||||
float s0 = cultmath_smoothstep(minimum, maximum, a.x);
|
||||
float s1 = cultmath_smoothstep(minimum, maximum, a.y);
|
||||
float lo = min(s0, s1);
|
||||
float hi = max(s0, s1);
|
||||
return float2(lo > 0.0 ? asfloat(asuint(lo) - 1u) : 0.0, hi < 1.0 ? asfloat(asuint(hi) + 1u) : 1.0);
|
||||
}
|
||||
|
||||
// The natural interval extension of x + (y - x) * amount, which is how cultmath_lerp evaluates.
|
||||
float2 cultmath_iv_lerp(float2 a, float2 b, float amount) { return cultmath_iv_add(a, cultmath_iv_scale(cultmath_iv_sub(b, a), amount)); }
|
||||
|
||||
// [n - L r, n + L r] intersected with [-1, 1], n = cultmath_snoise(centre). One snoise, value only.
|
||||
float2 cultmath_iv_snoise_ball(float3 centre, float radius)
|
||||
{
|
||||
float n = cultmath_snoise(centre);
|
||||
float e = CULTMATH_SNOISE_LIPSCHITZ * radius;
|
||||
return float2(max(n - e, -1.0), min(n + e, 1.0));
|
||||
}
|
||||
|
||||
// The 2D overload: [n - L2 r, n + L2 r] intersected with [-1, 1], n = cultmath_snoise(centre). One snoise, value only.
|
||||
float2 cultmath_iv_snoise_ball(float2 centre, float radius)
|
||||
{
|
||||
float n = cultmath_snoise(centre);
|
||||
float e = CULTMATH_SNOISE2_LIPSCHITZ * radius;
|
||||
return float2(max(n - e, -1.0), min(n + e, 1.0));
|
||||
}
|
||||
|
||||
// Octave sum of cultmath_iv_snoise_ball, compounding frequency and amplitude as the value-and-gradient fBm does.
|
||||
float2 cultmath_iv_fbm_ball(float3 centre, float radius, int octaves, float lacunarity, float gain)
|
||||
{
|
||||
octaves = clamp(octaves, 0, 16);
|
||||
float amplitude = 1.0;
|
||||
float frequency = 1.0;
|
||||
float2 sum = float2(0.0, 0.0);
|
||||
for (int i = 0; i < octaves; i++)
|
||||
{
|
||||
sum = cultmath_iv_add(sum, cultmath_iv_scale(cultmath_iv_snoise_ball(centre * frequency, radius * abs(frequency)), amplitude));
|
||||
frequency *= lacunarity;
|
||||
amplitude *= gain;
|
||||
}
|
||||
|
||||
return sum;
|
||||
}
|
||||
|
||||
// A ball (xyz centre, w radius) enclosing every point of every ray of a screen tile over the depth segment
|
||||
// [z0, z1], warped by at most warp. Camera frame: pinhole at the origin looking down +z, ray (m z, z).
|
||||
// footprintPerDepth = N / (sqrt(2) f) for an N x N tile at focal length f. The radius is widened by
|
||||
// (|c|_1 + radius) 2^-20, which covers the ball's own float32 rounding. Derivation in math.Interval.cs.
|
||||
float4 cultmath_iv_frustum_ball(float2 centreSlope, float z0, float z1, float footprintPerDepth, float warp)
|
||||
{
|
||||
float zm = (z0 + z1) * 0.5;
|
||||
float axis = sqrt(centreSlope.x * centreSlope.x + centreSlope.y * centreSlope.y + 1.0);
|
||||
float cx = centreSlope.x * zm;
|
||||
float cy = centreSlope.y * zm;
|
||||
float radius = (z1 - z0) * 0.5 * axis + z1 * footprintPerDepth + warp;
|
||||
radius += (abs(cx) + abs(cy) + abs(zm) + radius) * 9.5367431640625e-7;
|
||||
return float4(cx, cy, zm, radius);
|
||||
}
|
||||
|
||||
#endif
|
||||
7
packages/cultmath/shaders/CultMath.Interval.hlsl.meta
Normal file
7
packages/cultmath/shaders/CultMath.Interval.hlsl.meta
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 4d8a899561654ac990cab0bf48658cc1
|
||||
ShaderIncludeImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
99
packages/cultmath/shaders/CultMath.Phacelle.glsl
Normal file
99
packages/cultmath/shaders/CultMath.Phacelle.glsl
Normal file
|
|
@ -0,0 +1,99 @@
|
|||
// Generated from shaders/CultMath.Phacelle.hlsl by GlslLowering (packages/cultmath/tests/CultMath.Tests/GlslLowering.cs). Do not edit; regenerate with CULTMATH_WRITE_GLSL=1 dotnet test --filter GlslMirrorTests. MPL-2.0; requires CultMath.glsl before it.
|
||||
#ifndef CULTMATH_PHACELLE_GLSL
|
||||
#define CULTMATH_PHACELLE_GLSL
|
||||
// This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of
|
||||
// the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
//
|
||||
// Phacelle noise. Copyright (c) 2025 Rune Skovbo Johansen (Shadertoy t3dyWl; MPL-2.0), read from the
|
||||
// C# port PhacelleNoise in lpmitchell/AdvancedTerrainErosion, converted to burstable C# by Luke
|
||||
// Mitchell (2026). Modified by GameCult: 3D cells, a caller-supplied stripe wave vector, an exact
|
||||
// gradient and exact pruning. This file is an MPL-2.0 file; CultMath.hlsl, which includes it after
|
||||
// its own definitions of CULTMATH_TAU and cultmath_pcg3d, is MIT (see THIRD-PARTY-NOTICES.md).
|
||||
|
||||
// Invariant 8's struct return shape for cultmath_phacelle, compared field by field and bit for bit
|
||||
// against CultMath.CultPhasor, same field order.
|
||||
struct CultPhasor
|
||||
{
|
||||
vec4 cos;
|
||||
vec4 sin;
|
||||
};
|
||||
|
||||
// Johansen's Phacelle noise on 3D cells. See math.phacelle's comment (math.Phacelle.cs) for the stripe wave
|
||||
// vector, the weight, the normalization, the exact gradient and why the prune is exact. Mirrors
|
||||
// the C# body operation for operation; the C#-only internal overload that switches the prune off
|
||||
// has no shader twin.
|
||||
CultPhasor cultmath_phacelle(vec3 p, vec3 side, float offset, float normalization)
|
||||
{
|
||||
vec3 cell = floor(p);
|
||||
vec3 local = p - cell;
|
||||
float phaseOffset = offset * CULTMATH_TAU;
|
||||
float sumW = 0.0;
|
||||
float sumCos = 0.0;
|
||||
float sumSin = 0.0;
|
||||
vec3 gradW = vec3(0.0, 0.0, 0.0);
|
||||
vec3 gradCos = vec3(0.0, 0.0, 0.0);
|
||||
vec3 gradSin = vec3(0.0, 0.0, 0.0);
|
||||
|
||||
for (int dz = -1; dz <= 2; dz++)
|
||||
{
|
||||
float gz = max(0.0, abs(local.z - float(dz)) - 0.5);
|
||||
for (int dy = -1; dy <= 2; dy++)
|
||||
{
|
||||
float gy = max(0.0, abs(local.y - float(dy)) - 0.5);
|
||||
for (int dx = -1; dx <= 2; dx++)
|
||||
{
|
||||
float gx = max(0.0, abs(local.x - float(dx)) - 0.5);
|
||||
if (gx * gx + gy * gy + gz * gz >= 2.25)
|
||||
continue;
|
||||
|
||||
vec3 gridStep = vec3(dx, dy, dz);
|
||||
ivec3 hash = cultmath_pcg3d(ivec3(cell + gridStep));
|
||||
vec3 jitter = vec3(
|
||||
float(uint(hash.x) >> 8) * (1.0 / 16777216.0) - 0.5,
|
||||
float(uint(hash.y) >> 8) * (1.0 / 16777216.0) - 0.5,
|
||||
float(uint(hash.z) >> 8) * (1.0 / 16777216.0) - 0.5);
|
||||
vec3 v = local - gridStep - jitter;
|
||||
float falloff = exp(-2.0 * dot(v, v));
|
||||
float w = max(0.0, falloff - 0.01111);
|
||||
vec3 dw = w > 0.0 ? (-4.0 * falloff) * v : vec3(0.0, 0.0, 0.0);
|
||||
float phase = dot(v, side) + phaseOffset;
|
||||
float c = cos(phase);
|
||||
float s = sin(phase);
|
||||
|
||||
sumW += w;
|
||||
sumCos += w * c;
|
||||
sumSin += w * s;
|
||||
gradW += dw;
|
||||
gradCos += dw * c - (w * s) * side;
|
||||
gradSin += dw * s + (w * c) * side;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
float invW = 1.0 / sumW;
|
||||
float rawCos = sumCos * invW;
|
||||
float rawSin = sumSin * invW;
|
||||
vec3 gradRawCos = (gradCos - rawCos * gradW) * invW;
|
||||
vec3 gradRawSin = (gradSin - rawSin * gradW) * invW;
|
||||
float rawLength = sqrt(rawCos * rawCos + rawSin * rawSin);
|
||||
float floorLength = 1.0 - normalization;
|
||||
|
||||
CultPhasor result;
|
||||
if (rawLength > floorLength)
|
||||
{
|
||||
float outCos = rawCos / rawLength;
|
||||
float outSin = rawSin / rawLength;
|
||||
vec3 gradLength = (rawCos * gradRawCos + rawSin * gradRawSin) / rawLength;
|
||||
result.cos = vec4((gradRawCos - outCos * gradLength) / rawLength, outCos);
|
||||
result.sin = vec4((gradRawSin - outSin * gradLength) / rawLength, outSin);
|
||||
}
|
||||
else
|
||||
{
|
||||
result.cos = vec4(gradRawCos / floorLength, rawCos / floorLength);
|
||||
result.sin = vec4(gradRawSin / floorLength, rawSin / floorLength);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
#endif
|
||||
|
|
@ -49,9 +49,9 @@ CultPhasor cultmath_phacelle(float3 p, float3 side, float offset, float normaliz
|
|||
float3 gridStep = float3(dx, dy, dz);
|
||||
int3 hash = cultmath_pcg3d(int3(cell + gridStep));
|
||||
float3 jitter = float3(
|
||||
((uint)hash.x >> 8) * (1.0 / 16777216.0) - 0.5,
|
||||
((uint)hash.y >> 8) * (1.0 / 16777216.0) - 0.5,
|
||||
((uint)hash.z >> 8) * (1.0 / 16777216.0) - 0.5);
|
||||
(float)((uint)hash.x >> 8) * (1.0 / 16777216.0) - 0.5,
|
||||
(float)((uint)hash.y >> 8) * (1.0 / 16777216.0) - 0.5,
|
||||
(float)((uint)hash.z >> 8) * (1.0 / 16777216.0) - 0.5);
|
||||
float3 v = local - gridStep - jitter;
|
||||
float falloff = exp(-2.0 * dot(v, v));
|
||||
float w = max(0.0, falloff - 0.01111);
|
||||
|
|
|
|||
805
packages/cultmath/shaders/CultMath.glsl
Normal file
805
packages/cultmath/shaders/CultMath.glsl
Normal file
|
|
@ -0,0 +1,805 @@
|
|||
// Generated from shaders/CultMath.hlsl and CultMath.Interval.hlsl and CultMath.Affine.hlsl by GlslLowering (packages/cultmath/tests/CultMath.Tests/GlslLowering.cs). Do not edit; regenerate with CULTMATH_WRITE_GLSL=1 dotnet test --filter GlslMirrorTests. MIT. cultmath_phacelle is in CultMath.Phacelle.glsl, to be concatenated after this file by consumers that call it.
|
||||
#ifndef CULTMATH_GLSL
|
||||
#define CULTMATH_GLSL
|
||||
// CultMath HLSL mirror.
|
||||
//
|
||||
// HLSL already owns the vec2/vec3/vec4 type names and most primitive
|
||||
// intrinsics. This include names the CultMath semantic surface explicitly so
|
||||
// shader code, C# wrappers, and Rust/native parity fixtures can share the same
|
||||
// small vocabulary without local helper drift.
|
||||
|
||||
const float CULTMATH_PI = 3.14159265358979323846;
|
||||
const float CULTMATH_TAU = 6.28318530717958647692;
|
||||
const float CULTMATH_HALF_PI = 1.57079632679489661923;
|
||||
|
||||
float cultmath_radians(float degrees_value) { return degrees_value * (CULTMATH_PI / 180.0); }
|
||||
float cultmath_degrees(float radians_value) { return radians_value * (180.0 / CULTMATH_PI); }
|
||||
|
||||
float cultmath_frac(float value) { return value - floor(value); }
|
||||
vec2 cultmath_frac(vec2 value) { return value - floor(value); }
|
||||
vec3 cultmath_frac(vec3 value) { return value - floor(value); }
|
||||
vec4 cultmath_frac(vec4 value) { return value - floor(value); }
|
||||
|
||||
float cultmath_clamp(float value, float minimum, float maximum) { return min(max(value, minimum), maximum); }
|
||||
vec2 cultmath_clamp(vec2 value, vec2 minimum, vec2 maximum) { return min(max(value, minimum), maximum); }
|
||||
vec3 cultmath_clamp(vec3 value, vec3 minimum, vec3 maximum) { return min(max(value, minimum), maximum); }
|
||||
vec4 cultmath_clamp(vec4 value, vec4 minimum, vec4 maximum) { return min(max(value, minimum), maximum); }
|
||||
|
||||
// DXIL Saturate is FMin(1, FMax(0, x)); dxc lowers min/max to the same FMin/FMax, NaN rules included.
|
||||
float cultmath_saturate(float value) { return min(1.0, max(0.0, value)); }
|
||||
vec2 cultmath_saturate(vec2 value) { return min(vec2(1.0, 1.0), max(vec2(0.0, 0.0), value)); }
|
||||
vec3 cultmath_saturate(vec3 value) { return min(vec3(1.0, 1.0, 1.0), max(vec3(0.0, 0.0, 0.0), value)); }
|
||||
vec4 cultmath_saturate(vec4 value) { return min(vec4(1.0, 1.0, 1.0, 1.0), max(vec4(0.0, 0.0, 0.0, 0.0), value)); }
|
||||
|
||||
float cultmath_lerp(float start, float end, float amount) { return start + (end - start) * amount; }
|
||||
vec2 cultmath_lerp(vec2 start, vec2 end, vec2 amount) { return start + (end - start) * amount; }
|
||||
vec3 cultmath_lerp(vec3 start, vec3 end, vec3 amount) { return start + (end - start) * amount; }
|
||||
vec4 cultmath_lerp(vec4 start, vec4 end, vec4 amount) { return start + (end - start) * amount; }
|
||||
|
||||
float cultmath_step(float edge, float value) { return value < edge ? 0.0 : 1.0; }
|
||||
vec2 cultmath_step(vec2 edge, vec2 value) { return vec2(cultmath_step(edge.x, value.x), cultmath_step(edge.y, value.y)); }
|
||||
vec3 cultmath_step(vec3 edge, vec3 value) { return vec3(cultmath_step(edge.x, value.x), cultmath_step(edge.y, value.y), cultmath_step(edge.z, value.z)); }
|
||||
vec4 cultmath_step(vec4 edge, vec4 value) { return vec4(cultmath_step(edge.x, value.x), cultmath_step(edge.y, value.y), cultmath_step(edge.z, value.z), cultmath_step(edge.w, value.w)); }
|
||||
|
||||
float cultmath_smoothstep(float minimum, float maximum, float value)
|
||||
{
|
||||
float t = cultmath_saturate((value - minimum) / (maximum - minimum));
|
||||
return t * t * (3.0 - 2.0 * t);
|
||||
}
|
||||
|
||||
vec2 cultmath_smoothstep(vec2 minimum, vec2 maximum, vec2 value)
|
||||
{
|
||||
vec2 t = cultmath_saturate((value - minimum) / (maximum - minimum));
|
||||
return t * t * (vec2(3.0, 3.0) - vec2(2.0, 2.0) * t);
|
||||
}
|
||||
|
||||
vec3 cultmath_smoothstep(vec3 minimum, vec3 maximum, vec3 value)
|
||||
{
|
||||
vec3 t = cultmath_saturate((value - minimum) / (maximum - minimum));
|
||||
return t * t * (vec3(3.0, 3.0, 3.0) - vec3(2.0, 2.0, 2.0) * t);
|
||||
}
|
||||
|
||||
vec4 cultmath_smoothstep(vec4 minimum, vec4 maximum, vec4 value)
|
||||
{
|
||||
vec4 t = cultmath_saturate((value - minimum) / (maximum - minimum));
|
||||
return t * t * (vec4(3.0, 3.0, 3.0, 3.0) - vec4(2.0, 2.0, 2.0, 2.0) * t);
|
||||
}
|
||||
|
||||
float cultmath_smoothstep01(float value) { return cultmath_smoothstep(0.0, 1.0, value); }
|
||||
|
||||
float cultmath_smootherstep(float value)
|
||||
{
|
||||
value = cultmath_saturate(value);
|
||||
return value * value * value * (value * (value * 6.0 - 15.0) + 10.0);
|
||||
}
|
||||
|
||||
vec2 cultmath_snoise_mod289(vec2 value) { return value - floor(value * (1.0 / 289.0)) * 289.0; }
|
||||
vec3 cultmath_snoise_mod289(vec3 value) { return value - floor(value * (1.0 / 289.0)) * 289.0; }
|
||||
vec4 cultmath_snoise_mod289(vec4 value) { return value - floor(value * (1.0 / 289.0)) * 289.0; }
|
||||
vec3 cultmath_snoise_permute(vec3 value) { return cultmath_snoise_mod289(((value * 34.0) + 10.0) * value); }
|
||||
vec4 cultmath_snoise_permute(vec4 value) { return cultmath_snoise_mod289(((value * 34.0) + 10.0) * value); }
|
||||
|
||||
// Ashima Arts / Ian McEwan 3D simplex noise (MIT), same float32 evaluation
|
||||
// order as the C# math.snoise(vec3) mirror. Ties resolve in simplexnoise1234's
|
||||
// total order; see math.snoise.
|
||||
float cultmath_snoise(vec3 value)
|
||||
{
|
||||
vec2 c = vec2(1.0 / 6.0, 1.0 / 3.0);
|
||||
vec3 i = floor(value + dot(value, c.yyy));
|
||||
vec3 x0 = value - i + dot(i, c.xxx);
|
||||
vec3 g = vec3(step(x0.y, x0.x), step(x0.z, x0.y), 1.0 - step(x0.z, x0.x));
|
||||
vec3 l = 1.0 - g;
|
||||
vec3 i1 = min(g.xyz, l.zxy);
|
||||
vec3 i2 = max(g.xyz, l.zxy);
|
||||
vec3 x1 = x0 - i1 + c.xxx;
|
||||
vec3 x2 = x0 - i2 + c.yyy;
|
||||
vec3 x3 = x0 - 0.5;
|
||||
|
||||
i = cultmath_snoise_mod289(i);
|
||||
vec4 p = cultmath_snoise_permute(cultmath_snoise_permute(cultmath_snoise_permute(
|
||||
i.z + vec4(0.0, i1.z, i2.z, 1.0)) + i.y + vec4(0.0, i1.y, i2.y, 1.0)) + i.x + vec4(0.0, i1.x, i2.x, 1.0));
|
||||
|
||||
const float n_ = 0.142857142857;
|
||||
vec3 ns = vec3(2.0 * n_, 0.5 * n_ - 1.0, n_);
|
||||
vec4 j = p - 49.0 * floor(p * ns.z * ns.z);
|
||||
vec4 x_ = floor(j * ns.z);
|
||||
vec4 y_ = floor(j - 7.0 * x_);
|
||||
vec4 x = x_ * ns.x + ns.yyyy;
|
||||
vec4 y = y_ * ns.x + ns.yyyy;
|
||||
vec4 h = 1.0 - abs(x) - abs(y);
|
||||
|
||||
vec4 b0 = vec4(x.xy, y.xy);
|
||||
vec4 b1 = vec4(x.zw, y.zw);
|
||||
vec4 s0 = floor(b0) * 2.0 + 1.0;
|
||||
vec4 s1 = floor(b1) * 2.0 + 1.0;
|
||||
vec4 sh = -step(h, vec4(0.0, 0.0, 0.0, 0.0));
|
||||
vec4 a0 = b0.xzyw + s0.xzyw * sh.xxyy;
|
||||
vec4 a1 = b1.xzyw + s1.xzyw * sh.zzww;
|
||||
|
||||
vec3 p0 = vec3(a0.xy, h.x);
|
||||
vec3 p1 = vec3(a0.zw, h.y);
|
||||
vec3 p2 = vec3(a1.xy, h.z);
|
||||
vec3 p3 = vec3(a1.zw, h.w);
|
||||
vec4 norm = 1.79284291400159 - 0.85373472095314 * vec4(dot(p0, p0), dot(p1, p1), dot(p2, p2), dot(p3, p3));
|
||||
p0 *= norm.x;
|
||||
p1 *= norm.y;
|
||||
p2 *= norm.z;
|
||||
p3 *= norm.w;
|
||||
|
||||
vec4 m = max(0.5 - vec4(dot(x0, x0), dot(x1, x1), dot(x2, x2), dot(x3, x3)), 0.0);
|
||||
m = m * m;
|
||||
return 105.0 * dot(m * m, vec4(dot(p0, x0), dot(p1, x1), dot(p2, x2), dot(p3, x3)));
|
||||
}
|
||||
|
||||
float cultmath_snoise(vec2 value)
|
||||
{
|
||||
vec4 c = vec4(
|
||||
0.211324865405187,
|
||||
0.366025403784439,
|
||||
-0.577350269189626,
|
||||
0.024390243902439);
|
||||
vec2 i = floor(value + dot(value, c.yy));
|
||||
vec2 x0 = value - i + dot(i, c.xx);
|
||||
vec2 i1 = x0.x > x0.y ? vec2(1.0, 0.0) : vec2(0.0, 1.0);
|
||||
vec4 x12 = vec4(x0.x + c.x - i1.x, x0.y + c.x - i1.y, x0.x + c.z, x0.y + c.z);
|
||||
|
||||
i = cultmath_snoise_mod289(i);
|
||||
vec3 p = cultmath_snoise_permute(
|
||||
cultmath_snoise_permute(i.y + vec3(0.0, i1.y, 1.0)) + i.x + vec3(0.0, i1.x, 1.0));
|
||||
vec3 m = max(0.5 - vec3(dot(x0, x0), dot(x12.xy, x12.xy), dot(x12.zw, x12.zw)), 0.0);
|
||||
m *= m;
|
||||
m *= m;
|
||||
|
||||
vec3 x = 2.0 * fract(p * c.w) - 1.0;
|
||||
vec3 h = abs(x) - 0.5;
|
||||
vec3 ox = floor(x + 0.5);
|
||||
vec3 a0 = x - ox;
|
||||
m *= 1.79284291400159 - 0.85373472095314 * (a0 * a0 + h * h);
|
||||
|
||||
vec3 g = vec3(
|
||||
a0.x * x0.x + h.x * x0.y,
|
||||
a0.y * x12.x + h.y * x12.y,
|
||||
a0.z * x12.z + h.z * x12.w);
|
||||
return 130.0 * dot(m, g);
|
||||
}
|
||||
|
||||
// Analytic gradient of cultmath_snoise(vec3) (invariant 8), following webgl-noise
|
||||
// src/noise3Dgrad.glsl (Ashima Arts / McEwan, MIT); same kernel, permutation and scale as
|
||||
// cultmath_snoise(vec3) (stegu/webgl-noise 22434e04d7). See the C# math.snoise_grad comment for the
|
||||
// derivation. Every local up through p0..p3 and x0..x3 is cultmath_snoise(vec3)'s own derivation
|
||||
// verbatim.
|
||||
vec4 cultmath_snoise_grad(vec3 value)
|
||||
{
|
||||
vec2 c = vec2(1.0 / 6.0, 1.0 / 3.0);
|
||||
vec3 i = floor(value + dot(value, c.yyy));
|
||||
vec3 x0 = value - i + dot(i, c.xxx);
|
||||
vec3 g = vec3(step(x0.y, x0.x), step(x0.z, x0.y), 1.0 - step(x0.z, x0.x));
|
||||
vec3 l = 1.0 - g;
|
||||
vec3 i1 = min(g.xyz, l.zxy);
|
||||
vec3 i2 = max(g.xyz, l.zxy);
|
||||
vec3 x1 = x0 - i1 + c.xxx;
|
||||
vec3 x2 = x0 - i2 + c.yyy;
|
||||
vec3 x3 = x0 - 0.5;
|
||||
|
||||
i = cultmath_snoise_mod289(i);
|
||||
vec4 p = cultmath_snoise_permute(cultmath_snoise_permute(cultmath_snoise_permute(
|
||||
i.z + vec4(0.0, i1.z, i2.z, 1.0)) + i.y + vec4(0.0, i1.y, i2.y, 1.0)) + i.x + vec4(0.0, i1.x, i2.x, 1.0));
|
||||
|
||||
const float n_ = 0.142857142857;
|
||||
vec3 ns = vec3(2.0 * n_, 0.5 * n_ - 1.0, n_);
|
||||
vec4 j = p - 49.0 * floor(p * ns.z * ns.z);
|
||||
vec4 x_ = floor(j * ns.z);
|
||||
vec4 y_ = floor(j - 7.0 * x_);
|
||||
vec4 x = x_ * ns.x + ns.yyyy;
|
||||
vec4 y = y_ * ns.x + ns.yyyy;
|
||||
vec4 h = 1.0 - abs(x) - abs(y);
|
||||
|
||||
vec4 b0 = vec4(x.xy, y.xy);
|
||||
vec4 b1 = vec4(x.zw, y.zw);
|
||||
vec4 s0 = floor(b0) * 2.0 + 1.0;
|
||||
vec4 s1 = floor(b1) * 2.0 + 1.0;
|
||||
vec4 sh = -step(h, vec4(0.0, 0.0, 0.0, 0.0));
|
||||
vec4 a0 = b0.xzyw + s0.xzyw * sh.xxyy;
|
||||
vec4 a1 = b1.xzyw + s1.xzyw * sh.zzww;
|
||||
|
||||
vec3 p0 = vec3(a0.xy, h.x);
|
||||
vec3 p1 = vec3(a0.zw, h.y);
|
||||
vec3 p2 = vec3(a1.xy, h.z);
|
||||
vec3 p3 = vec3(a1.zw, h.w);
|
||||
vec4 norm = 1.79284291400159 - 0.85373472095314 * vec4(dot(p0, p0), dot(p1, p1), dot(p2, p2), dot(p3, p3));
|
||||
p0 *= norm.x;
|
||||
p1 *= norm.y;
|
||||
p2 *= norm.z;
|
||||
p3 *= norm.w;
|
||||
|
||||
vec4 m0 = max(0.5 - vec4(dot(x0, x0), dot(x1, x1), dot(x2, x2), dot(x3, x3)), 0.0);
|
||||
vec4 m2 = m0 * m0;
|
||||
vec4 m3 = m2 * m0;
|
||||
vec4 m4 = m2 * m2;
|
||||
|
||||
vec4 px = vec4(dot(p0, x0), dot(p1, x1), dot(p2, x2), dot(p3, x3));
|
||||
float value2 = 105.0 * dot(m4, px);
|
||||
vec3 grad = -8.0 * m3.x * x0 * px.x + m4.x * p0
|
||||
+ -8.0 * m3.y * x1 * px.y + m4.y * p1
|
||||
+ -8.0 * m3.z * x2 * px.z + m4.z * p2
|
||||
+ -8.0 * m3.w * x3 * px.w + m4.w * p3;
|
||||
grad *= 105.0;
|
||||
|
||||
return vec4(grad, value2);
|
||||
}
|
||||
|
||||
// Octave sum of cultmath_snoise_grad (invariant 8); see the C# math.fbm_grad comment for the
|
||||
// per-octave frequency/amplitude derivation and why octaves is clamped.
|
||||
vec4 cultmath_fbm_grad(vec3 p, int octaves, float lacunarity, float gain)
|
||||
{
|
||||
octaves = clamp(octaves, 0, 16);
|
||||
float amplitude = 1.0;
|
||||
float frequency = 1.0;
|
||||
float value = 0.0;
|
||||
vec3 gradient = vec3(0.0, 0.0, 0.0);
|
||||
for (int i = 0; i < octaves; i++)
|
||||
{
|
||||
vec4 n = cultmath_snoise_grad(p * frequency);
|
||||
value += amplitude * n.w;
|
||||
gradient += amplitude * frequency * n.xyz;
|
||||
frequency *= lacunarity;
|
||||
amplitude *= gain;
|
||||
}
|
||||
|
||||
return vec4(gradient, value);
|
||||
}
|
||||
|
||||
// Ridged multifractal noise (Musgrave, Texturing and Modeling, ch. 16); see the C# math.ridged_grad
|
||||
// comment for the fold/sign derivation, the deliberate crease at n = 0, and why octaves is clamped.
|
||||
vec4 cultmath_ridged_grad(vec3 p, int octaves, float lacunarity, float gain)
|
||||
{
|
||||
octaves = clamp(octaves, 0, 16);
|
||||
float amplitude = 1.0;
|
||||
float frequency = 1.0;
|
||||
float value = 0.0;
|
||||
vec3 gradient = vec3(0.0, 0.0, 0.0);
|
||||
for (int i = 0; i < octaves; i++)
|
||||
{
|
||||
vec4 n = cultmath_snoise_grad(p * frequency);
|
||||
float s = sign(n.w);
|
||||
value += amplitude * (1.0 - abs(n.w));
|
||||
gradient += -amplitude * frequency * s * n.xyz;
|
||||
frequency *= lacunarity;
|
||||
amplitude *= gain;
|
||||
}
|
||||
|
||||
return vec4(gradient, value);
|
||||
}
|
||||
|
||||
float cultmath_lengthsq(vec2 value) { return dot(value, value); }
|
||||
float cultmath_lengthsq(vec3 value) { return dot(value, value); }
|
||||
float cultmath_lengthsq(vec4 value) { return dot(value, value); }
|
||||
|
||||
float cultmath_distance(vec2 left, vec2 right) { return length(left - right); }
|
||||
float cultmath_distance(vec3 left, vec3 right) { return length(left - right); }
|
||||
float cultmath_distance(vec4 left, vec4 right) { return length(left - right); }
|
||||
|
||||
vec2 cultmath_reflect(vec2 incident, vec2 normal_value)
|
||||
{
|
||||
return incident - 2.0 * dot(normal_value, incident) * normal_value;
|
||||
}
|
||||
|
||||
vec3 cultmath_reflect(vec3 incident, vec3 normal_value)
|
||||
{
|
||||
return incident - 2.0 * dot(normal_value, incident) * normal_value;
|
||||
}
|
||||
|
||||
vec2 cultmath_rotate(vec2 value, float radians_value)
|
||||
{
|
||||
float s = sin(radians_value);
|
||||
float c = cos(radians_value);
|
||||
return vec2(value.x * c - value.y * s, value.x * s + value.y * c);
|
||||
}
|
||||
|
||||
vec2 cultmath_rotate_degrees(vec2 value, float degrees_value)
|
||||
{
|
||||
return cultmath_rotate(value, cultmath_radians(degrees_value));
|
||||
}
|
||||
|
||||
float cultmath_csum(vec2 value) { return value.x + value.y; }
|
||||
float cultmath_csum(vec3 value) { return value.x + value.y + value.z; }
|
||||
float cultmath_csum(vec4 value) { return value.x + value.y + value.z + value.w; }
|
||||
|
||||
float cultmath_decay(float source, float lambda_value, float dt) { return source * exp(-lambda_value * dt); }
|
||||
vec2 cultmath_decay(vec2 source, float lambda_value, float dt) { return source * exp(-lambda_value * dt); }
|
||||
vec3 cultmath_decay(vec3 source, float lambda_value, float dt) { return source * exp(-lambda_value * dt); }
|
||||
vec4 cultmath_decay(vec4 source, float lambda_value, float dt) { return source * exp(-lambda_value * dt); }
|
||||
|
||||
float cultmath_damp(float start, float end, float lambda_value, float dt)
|
||||
{
|
||||
return cultmath_lerp(start, end, 1.0 - exp(-lambda_value * dt));
|
||||
}
|
||||
|
||||
vec2 cultmath_damp(vec2 start, vec2 end, float lambda_value, float dt)
|
||||
{
|
||||
float amount = 1.0 - exp(-lambda_value * dt);
|
||||
return cultmath_lerp(start, end, vec2(amount, amount));
|
||||
}
|
||||
|
||||
vec3 cultmath_damp(vec3 start, vec3 end, float lambda_value, float dt)
|
||||
{
|
||||
float amount = 1.0 - exp(-lambda_value * dt);
|
||||
return cultmath_lerp(start, end, vec3(amount, amount, amount));
|
||||
}
|
||||
|
||||
vec4 cultmath_damp(vec4 start, vec4 end, float lambda_value, float dt)
|
||||
{
|
||||
float amount = 1.0 - exp(-lambda_value * dt);
|
||||
return cultmath_lerp(start, end, vec4(amount, amount, amount, amount));
|
||||
}
|
||||
|
||||
float cultmath_catmullrom(float p0, float p1, float p2, float p3, float t)
|
||||
{
|
||||
float t2 = t * t;
|
||||
float t3 = t2 * t;
|
||||
return 0.5 * ((2.0 * p1) + (p2 - p0) * t + (2.0 * p0 - 5.0 * p1 + 4.0 * p2 - p3) * t2 + (-p0 + 3.0 * p1 - 3.0 * p2 + p3) * t3);
|
||||
}
|
||||
|
||||
vec2 cultmath_catmullrom(vec2 p0, vec2 p1, vec2 p2, vec2 p3, float t)
|
||||
{
|
||||
float t2 = t * t;
|
||||
float t3 = t2 * t;
|
||||
return 0.5 * ((2.0 * p1) + (p2 - p0) * t + (2.0 * p0 - 5.0 * p1 + 4.0 * p2 - p3) * t2 + (-p0 + 3.0 * p1 - 3.0 * p2 + p3) * t3);
|
||||
}
|
||||
|
||||
vec3 cultmath_catmullrom(vec3 p0, vec3 p1, vec3 p2, vec3 p3, float t)
|
||||
{
|
||||
float t2 = t * t;
|
||||
float t3 = t2 * t;
|
||||
return 0.5 * ((2.0 * p1) + (p2 - p0) * t + (2.0 * p0 - 5.0 * p1 + 4.0 * p2 - p3) * t2 + (-p0 + 3.0 * p1 - 3.0 * p2 + p3) * t3);
|
||||
}
|
||||
|
||||
vec4 cultmath_catmullrom(vec4 p0, vec4 p1, vec4 p2, vec4 p3, float t)
|
||||
{
|
||||
float t2 = t * t;
|
||||
float t3 = t2 * t;
|
||||
return 0.5 * ((2.0 * p1) + (p2 - p0) * t + (2.0 * p0 - 5.0 * p1 + 4.0 * p2 - p3) * t2 + (-p0 + 3.0 * p1 - 3.0 * p2 + p3) * t3);
|
||||
}
|
||||
|
||||
float cultmath_quadratic_bezier(float p0, float p1, float p2, float t)
|
||||
{
|
||||
t = cultmath_saturate(t);
|
||||
float inv = 1.0 - t;
|
||||
return inv * inv * p0 + 2.0 * inv * t * p1 + t * t * p2;
|
||||
}
|
||||
|
||||
vec3 cultmath_quadratic_bezier(vec3 p0, vec3 p1, vec3 p2, float t)
|
||||
{
|
||||
t = cultmath_saturate(t);
|
||||
float inv = 1.0 - t;
|
||||
return inv * inv * p0 + 2.0 * inv * t * p1 + t * t * p2;
|
||||
}
|
||||
|
||||
float cultmath_cubic_bezier(float p0, float p1, float p2, float p3, float t)
|
||||
{
|
||||
t = cultmath_saturate(t);
|
||||
float inv = 1.0 - t;
|
||||
return inv * inv * inv * p0 + 3.0 * inv * inv * t * p1 + 3.0 * inv * t * t * p2 + t * t * t * p3;
|
||||
}
|
||||
|
||||
vec3 cultmath_cubic_bezier(vec3 p0, vec3 p1, vec3 p2, vec3 p3, float t)
|
||||
{
|
||||
t = cultmath_saturate(t);
|
||||
float inv = 1.0 - t;
|
||||
return inv * inv * inv * p0 + 3.0 * inv * inv * t * p1 + 3.0 * inv * t * t * p2 + t * t * t * p3;
|
||||
}
|
||||
|
||||
float cultmath_hash(float value) { return cultmath_frac(sin(value) * 43758.5453); }
|
||||
float cultmath_hash(vec2 value) { return cultmath_hash(dot(value, vec2(127.1, 311.7))); }
|
||||
float cultmath_hash(vec3 value) { return cultmath_hash(dot(value, vec3(127.1, 311.7, 74.7))); }
|
||||
|
||||
// PCG hashes (Jarzynski and Olano, JCGT 2020), written over scalar uints so CultMath's ivec3/ivec4 carry the bits.
|
||||
uint cultmath_pcg(uint value)
|
||||
{
|
||||
uint state = value * 747796405u + 2891336453u;
|
||||
uint word = ((state >> int((state >> 28) + 4u)) ^ state) * 277803737u;
|
||||
return (word >> 22) ^ word;
|
||||
}
|
||||
|
||||
ivec3 cultmath_pcg3d(ivec3 value)
|
||||
{
|
||||
uint x = uint(value.x) * 1664525u + 1013904223u, y = uint(value.y) * 1664525u + 1013904223u, z = uint(value.z) * 1664525u + 1013904223u;
|
||||
x += y * z; y += z * x; z += x * y;
|
||||
x ^= x >> 16; y ^= y >> 16; z ^= z >> 16;
|
||||
x += y * z; y += z * x; z += x * y;
|
||||
return ivec3(int(x), int(y), int(z));
|
||||
}
|
||||
|
||||
ivec3 cultmath_pcg3d(vec3 value) { return cultmath_pcg3d(ivec3(int(floatBitsToUint(value.x)), int(floatBitsToUint(value.y)), int(floatBitsToUint(value.z)))); }
|
||||
ivec3 cultmath_pcg3d(vec2 value) { return cultmath_pcg3d(vec3(value, 0.0)); }
|
||||
|
||||
ivec4 cultmath_pcg4d(ivec4 value)
|
||||
{
|
||||
uint x = uint(value.x) * 1664525u + 1013904223u, y = uint(value.y) * 1664525u + 1013904223u;
|
||||
uint z = uint(value.z) * 1664525u + 1013904223u, w = uint(value.w) * 1664525u + 1013904223u;
|
||||
x += y * w; y += z * x; z += x * y; w += y * z;
|
||||
x ^= x >> 16; y ^= y >> 16; z ^= z >> 16; w ^= w >> 16;
|
||||
x += y * w; y += z * x; z += x * y; w += y * z;
|
||||
return ivec4(int(x), int(y), int(z), int(w));
|
||||
}
|
||||
|
||||
ivec4 cultmath_pcg4d(vec4 value) { return cultmath_pcg4d(ivec4(int(floatBitsToUint(value.x)), int(floatBitsToUint(value.y)), int(floatBitsToUint(value.z)), int(floatBitsToUint(value.w)))); }
|
||||
|
||||
// Inigo Quilez, "smooth minimum": quadratic-polynomial smin carried to value-and-gradient form. See
|
||||
// math.smin_grad's comment (math.cs) for why the gradient blend is exact, not an approximation.
|
||||
vec4 cultmath_smin_grad(vec4 a, vec4 b, float k)
|
||||
{
|
||||
float h = clamp(0.5 + 0.5 * (b.w - a.w) / k, 0.0, 1.0);
|
||||
float value = mix(b.w, a.w, h) - k * h * (1.0 - h);
|
||||
vec3 gradient = mix(b.xyz, a.xyz, h);
|
||||
return vec4(gradient, value);
|
||||
}
|
||||
|
||||
// Invariant 8's one struct return shape (design.md, "HLSL Target: Source Transformations"):
|
||||
// compared field by field and bit for bit against CultMath.CultCellular, same field order.
|
||||
struct CultCellular
|
||||
{
|
||||
vec4 nearest;
|
||||
vec4 edge;
|
||||
float id;
|
||||
};
|
||||
|
||||
// Worley, "A Cellular Texture Basis Function" (SIGGRAPH 1996). See math.cellular's comment
|
||||
// (math.cs) for the hashing, gradient, search-radius exactness proof, id source and
|
||||
// degenerate-point conventions this mirrors exactly, including the 5x5x5 lower-bound prune.
|
||||
CultCellular cultmath_cellular(vec3 p)
|
||||
{
|
||||
vec3 cell = floor(p);
|
||||
float f1 = 1.0e30;
|
||||
float f2 = 1.0e30;
|
||||
vec3 c1 = vec3(0.0, 0.0, 0.0);
|
||||
vec3 c2 = vec3(0.0, 0.0, 0.0);
|
||||
vec3 cellId = vec3(0.0, 0.0, 0.0);
|
||||
|
||||
for (int dz = -2; dz <= 2; dz++)
|
||||
{
|
||||
float lz = max(0.0, abs(float(dz)) - 1.0);
|
||||
for (int dy = -2; dy <= 2; dy++)
|
||||
{
|
||||
float ly = max(0.0, abs(float(dy)) - 1.0);
|
||||
for (int dx = -2; dx <= 2; dx++)
|
||||
{
|
||||
float lx = max(0.0, abs(float(dx)) - 1.0);
|
||||
float lowerBound = sqrt(lx * lx + ly * ly + lz * lz);
|
||||
if (lowerBound >= f2)
|
||||
continue;
|
||||
|
||||
vec3 neighbor = cell + vec3(dx, dy, dz);
|
||||
ivec3 hash = cultmath_pcg3d(ivec3(neighbor));
|
||||
vec3 jitter = vec3(
|
||||
float(uint(hash.x) >> 8) * (1.0 / 16777216.0),
|
||||
float(uint(hash.y) >> 8) * (1.0 / 16777216.0),
|
||||
float(uint(hash.z) >> 8) * (1.0 / 16777216.0));
|
||||
vec3 feature = neighbor + jitter;
|
||||
float d = cultmath_distance(p, feature);
|
||||
|
||||
if (d < f1)
|
||||
{
|
||||
f2 = f1; c2 = c1;
|
||||
f1 = d; c1 = feature; cellId = neighbor;
|
||||
}
|
||||
else if (d < f2)
|
||||
{
|
||||
f2 = d; c2 = feature;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// F1 = 0 and F2 = 0 share the same degenerate-gradient guard; see math.cellular's comment
|
||||
// (math.cs) for why F2 = 0 is reachable past roughly |p| = 2^23.
|
||||
vec3 grad1 = f1 > 0.0 ? (p - c1) / f1 : vec3(0.0, 0.0, 0.0);
|
||||
vec3 grad2 = f2 > 0.0 ? (p - c2) / f2 : vec3(0.0, 0.0, 0.0);
|
||||
|
||||
// id comes from pcg4d over the winning cell's integer coordinate alone (same int-hashing rule
|
||||
// as the jitter above), never from the pcg3d hash that produced its jitter (F4).
|
||||
ivec4 idHash = cultmath_pcg4d(ivec4(ivec3(cellId), 0));
|
||||
|
||||
CultCellular result;
|
||||
result.nearest = vec4(grad1, f1);
|
||||
result.edge = vec4(grad2 - grad1, f2 - f1);
|
||||
result.id = float(uint(idHash.w) >> 8) * (1.0 / 16777216.0);
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
// Interval arithmetic over vec2(lo, hi), lo <= hi, both finite. Every cultmath_iv_* function returns
|
||||
// an interval containing f(x) for every x in its input intervals, mirroring math.Interval.cs bit for
|
||||
// bit; see that file and docs/design.md ("Intervals") for each op's enclosure and its ulp widening.
|
||||
// Included by CultMath.hlsl after its own definitions of cultmath_smoothstep and cultmath_snoise.
|
||||
|
||||
// Lipschitz constant of cultmath_snoise(vec3); provenance in math.Interval.cs (SNOISE_LIPSCHITZ).
|
||||
const float CULTMATH_SNOISE_LIPSCHITZ = 7.9640074;
|
||||
|
||||
// Lipschitz constant of cultmath_snoise(vec2); provenance in math.Interval.cs (SNOISE2_LIPSCHITZ).
|
||||
const float CULTMATH_SNOISE2_LIPSCHITZ = 8.117002;
|
||||
|
||||
vec2 cultmath_iv_point(float value) { return vec2(value, value); }
|
||||
vec2 cultmath_iv_add(vec2 a, vec2 b) { return vec2(a.x + b.x, a.y + b.y); }
|
||||
vec2 cultmath_iv_sub(vec2 a, vec2 b) { return vec2(a.x - b.y, a.y - b.x); }
|
||||
vec2 cultmath_iv_neg(vec2 a) { return vec2(-a.y, -a.x); }
|
||||
|
||||
vec2 cultmath_iv_mul(vec2 a, vec2 b)
|
||||
{
|
||||
float p0 = a.x * b.x;
|
||||
float p1 = a.x * b.y;
|
||||
float p2 = a.y * b.x;
|
||||
float p3 = a.y * b.y;
|
||||
return vec2(min(min(p0, p1), min(p2, p3)), max(max(p0, p1), max(p2, p3)));
|
||||
}
|
||||
|
||||
vec2 cultmath_iv_scale(vec2 a, float s) { return s >= 0.0 ? vec2(a.x * s, a.y * s) : vec2(a.y * s, a.x * s); }
|
||||
|
||||
vec2 cultmath_iv_abs(vec2 a)
|
||||
{
|
||||
if (a.x >= 0.0)
|
||||
return a;
|
||||
if (a.y <= 0.0)
|
||||
return vec2(-a.y, -a.x);
|
||||
return vec2(0.0, max(-a.x, a.y));
|
||||
}
|
||||
|
||||
vec2 cultmath_iv_min(vec2 a, vec2 b) { return vec2(min(a.x, b.x), min(a.y, b.y)); }
|
||||
vec2 cultmath_iv_max(vec2 a, vec2 b) { return vec2(max(a.x, b.x), max(a.y, b.y)); }
|
||||
|
||||
vec2 cultmath_iv_sqr(vec2 a)
|
||||
{
|
||||
float l = a.x * a.x;
|
||||
float h = a.y * a.y;
|
||||
if (a.x >= 0.0)
|
||||
return vec2(l, h);
|
||||
if (a.y <= 0.0)
|
||||
return vec2(h, l);
|
||||
return vec2(0.0, max(l, h));
|
||||
}
|
||||
|
||||
vec2 cultmath_iv_sqrt(vec2 a) { return vec2(sqrt(max(a.x, 0.0)), sqrt(max(a.y, 0.0))); }
|
||||
|
||||
// Widened by one ulp on each side: exp is not required to be correctly rounded.
|
||||
vec2 cultmath_iv_exp(vec2 a)
|
||||
{
|
||||
float lo = exp(a.x);
|
||||
float hi = exp(a.y);
|
||||
return vec2(lo > 0.0 ? uintBitsToFloat(floatBitsToUint(lo) - 1u) : 0.0, uintBitsToFloat(floatBitsToUint(hi) + 1u));
|
||||
}
|
||||
|
||||
vec2 cultmath_iv_clamp(vec2 a, float minimum, float maximum)
|
||||
{
|
||||
return vec2(cultmath_clamp(a.x, minimum, maximum), cultmath_clamp(a.y, minimum, maximum));
|
||||
}
|
||||
|
||||
vec2 cultmath_iv_saturate(vec2 a) { return vec2(cultmath_saturate(a.x), cultmath_saturate(a.y)); }
|
||||
|
||||
// The endpoints, ordered, widened by one ulp inside [0, 1]: the float32 evaluation of smoothstep is
|
||||
// monotone only to within one ulp.
|
||||
vec2 cultmath_iv_smoothstep(float minimum, float maximum, vec2 a)
|
||||
{
|
||||
float s0 = cultmath_smoothstep(minimum, maximum, a.x);
|
||||
float s1 = cultmath_smoothstep(minimum, maximum, a.y);
|
||||
float lo = min(s0, s1);
|
||||
float hi = max(s0, s1);
|
||||
return vec2(lo > 0.0 ? uintBitsToFloat(floatBitsToUint(lo) - 1u) : 0.0, hi < 1.0 ? uintBitsToFloat(floatBitsToUint(hi) + 1u) : 1.0);
|
||||
}
|
||||
|
||||
// The natural interval extension of x + (y - x) * amount, which is how cultmath_lerp evaluates.
|
||||
vec2 cultmath_iv_lerp(vec2 a, vec2 b, float amount) { return cultmath_iv_add(a, cultmath_iv_scale(cultmath_iv_sub(b, a), amount)); }
|
||||
|
||||
// [n - L r, n + L r] intersected with [-1, 1], n = cultmath_snoise(centre). One snoise, value only.
|
||||
vec2 cultmath_iv_snoise_ball(vec3 centre, float radius)
|
||||
{
|
||||
float n = cultmath_snoise(centre);
|
||||
float e = CULTMATH_SNOISE_LIPSCHITZ * radius;
|
||||
return vec2(max(n - e, -1.0), min(n + e, 1.0));
|
||||
}
|
||||
|
||||
// The 2D overload: [n - L2 r, n + L2 r] intersected with [-1, 1], n = cultmath_snoise(centre). One snoise, value only.
|
||||
vec2 cultmath_iv_snoise_ball(vec2 centre, float radius)
|
||||
{
|
||||
float n = cultmath_snoise(centre);
|
||||
float e = CULTMATH_SNOISE2_LIPSCHITZ * radius;
|
||||
return vec2(max(n - e, -1.0), min(n + e, 1.0));
|
||||
}
|
||||
|
||||
// Octave sum of cultmath_iv_snoise_ball, compounding frequency and amplitude as the value-and-gradient fBm does.
|
||||
vec2 cultmath_iv_fbm_ball(vec3 centre, float radius, int octaves, float lacunarity, float gain)
|
||||
{
|
||||
octaves = clamp(octaves, 0, 16);
|
||||
float amplitude = 1.0;
|
||||
float frequency = 1.0;
|
||||
vec2 sum = vec2(0.0, 0.0);
|
||||
for (int i = 0; i < octaves; i++)
|
||||
{
|
||||
sum = cultmath_iv_add(sum, cultmath_iv_scale(cultmath_iv_snoise_ball(centre * frequency, radius * abs(frequency)), amplitude));
|
||||
frequency *= lacunarity;
|
||||
amplitude *= gain;
|
||||
}
|
||||
|
||||
return sum;
|
||||
}
|
||||
|
||||
// A ball (xyz centre, w radius) enclosing every point of every ray of a screen tile over the depth segment
|
||||
// [z0, z1], warped by at most warp. Camera frame: pinhole at the origin looking down +z, ray (m z, z).
|
||||
// footprintPerDepth = N / (sqrt(2) f) for an N x N tile at focal length f. The radius is widened by
|
||||
// (|c|_1 + radius) 2^-20, which covers the ball's own float32 rounding. Derivation in math.Interval.cs.
|
||||
vec4 cultmath_iv_frustum_ball(vec2 centreSlope, float z0, float z1, float footprintPerDepth, float warp)
|
||||
{
|
||||
float zm = (z0 + z1) * 0.5;
|
||||
float axis = sqrt(centreSlope.x * centreSlope.x + centreSlope.y * centreSlope.y + 1.0);
|
||||
float cx = centreSlope.x * zm;
|
||||
float cy = centreSlope.y * zm;
|
||||
float radius = (z1 - z0) * 0.5 * axis + z1 * footprintPerDepth + warp;
|
||||
radius += (abs(cx) + abs(cy) + abs(zm) + radius) * 9.5367431640625e-7;
|
||||
return vec4(cx, cy, zm, radius);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
// Reduced affine forms with one shared symbol over vec3(x0, a, e): the set { x0 + a eps + e delta :
|
||||
// delta in [-1, 1] } at the region's shared eps in [-1, 1], e >= 0. Every cultmath_af_* function mirrors
|
||||
// math.Affine.cs bit for bit; see that file and docs/design.md ("Affine forms") for each op's enclosure
|
||||
// and the float32 rounding allowance it folds into e. Included by CultMath.hlsl after
|
||||
// CultMath.Interval.hlsl, whose CULTMATH_SNOISE_LIPSCHITZ it shares, and after its own
|
||||
// definition of cultmath_snoise_grad.
|
||||
|
||||
// An upper bound on the spectral norm of the Hessian of cultmath_snoise(vec3); provenance in
|
||||
// math.Affine.cs (SNOISE_HESSIAN).
|
||||
const float CULTMATH_SNOISE_HESSIAN = 56.050385;
|
||||
|
||||
vec3 cultmath_af_point(float value) { return vec3(value, 0.0, 0.0); }
|
||||
vec3 cultmath_af_symbol(float x0, float a) { return vec3(x0, a, 0.0); }
|
||||
|
||||
vec3 cultmath_af_from_iv(vec2 interval)
|
||||
{
|
||||
float x0 = interval.x * 0.5 + interval.y * 0.5;
|
||||
float e = interval.y * 0.5 - interval.x * 0.5;
|
||||
return vec3(x0, 0.0, e + (abs(x0) + e) * 9.5367431640625e-7 + 1.17549435e-38);
|
||||
}
|
||||
|
||||
// An endpoint that would be NaN is the infinity on its side. NaN is found by its bit pattern: dxc marks
|
||||
// compares fast, so a test that needs NaN to make `lo == lo` false is deleted under its default flags.
|
||||
vec2 cultmath_af_range(vec3 x)
|
||||
{
|
||||
float r = abs(x.y) + x.z;
|
||||
float w = abs(x.x) * 9.5367431640625e-7 + r * 9.5367431640625e-7;
|
||||
float lo = x.x - r - w;
|
||||
float hi = x.x + r + w;
|
||||
return vec2((floatBitsToUint(lo) & 0x7fffffffu) > 0x7f800000u ? uintBitsToFloat(0xff800000u) : lo,
|
||||
(floatBitsToUint(hi) & 0x7fffffffu) > 0x7f800000u ? uintBitsToFloat(0x7f800000u) : hi);
|
||||
}
|
||||
|
||||
vec3 cultmath_af_add(vec3 x, vec3 y)
|
||||
{
|
||||
float x0 = x.x + y.x;
|
||||
float a = x.y + y.y;
|
||||
float e = x.z + y.z;
|
||||
return vec3(x0, a, e + (abs(x0) + abs(a) + e) * 9.5367431640625e-7);
|
||||
}
|
||||
|
||||
vec3 cultmath_af_sub(vec3 x, vec3 y)
|
||||
{
|
||||
float x0 = x.x - y.x;
|
||||
float a = x.y - y.y;
|
||||
float e = x.z + y.z;
|
||||
return vec3(x0, a, e + (abs(x0) + abs(a) + e) * 9.5367431640625e-7);
|
||||
}
|
||||
|
||||
vec3 cultmath_af_neg(vec3 x) { return vec3(-x.x, -x.y, x.z); }
|
||||
|
||||
vec3 cultmath_af_scale(vec3 x, float s)
|
||||
{
|
||||
float x0 = x.x * s;
|
||||
float a = x.y * s;
|
||||
float e = x.z * abs(s);
|
||||
return vec3(x0, a, e + (abs(x0) + abs(a) + e) * 9.5367431640625e-7 + 1.17549435e-38);
|
||||
}
|
||||
|
||||
vec3 cultmath_af_add_iv(vec3 x, vec2 interval) { return cultmath_af_add(x, cultmath_af_from_iv(interval)); }
|
||||
|
||||
vec3 cultmath_af_mul(vec3 x, vec3 y)
|
||||
{
|
||||
float x0 = x.x * y.x;
|
||||
float p = x.x * y.y;
|
||||
float q = y.x * x.y;
|
||||
float a = p + q;
|
||||
float e = abs(x.x) * y.z + abs(y.x) * x.z + (abs(x.y) + x.z) * (abs(y.y) + y.z);
|
||||
return vec3(x0, a, e + (abs(x0) + abs(p) + abs(q) + e) * 9.5367431640625e-7 + 1.17549435e-38);
|
||||
}
|
||||
|
||||
// The narrower of the Lipschitz form and the centred (Taylor) form over every p = centre + axis eps + w,
|
||||
// |w| <= radius, from one cultmath_snoise_grad at the centre; the allowance for the float32 evaluation is
|
||||
// in math.Affine.cs.
|
||||
vec3 cultmath_af_snoise(vec3 centre, vec3 axis, float radius)
|
||||
{
|
||||
vec4 g = cultmath_snoise_grad(centre);
|
||||
vec3 gradient = vec3(g.x, g.y, g.z);
|
||||
float reach = length(axis) + radius;
|
||||
float lipschitz = CULTMATH_SNOISE_LIPSCHITZ * reach;
|
||||
float a = dot(gradient, axis);
|
||||
float remainder = length(gradient) * radius + 0.5 * CULTMATH_SNOISE_HESSIAN * reach * reach;
|
||||
float allowance = 6.103515625e-5 + 2.44140625e-4 * reach
|
||||
+ CULTMATH_SNOISE_LIPSCHITZ * 9.5367431640625e-7 * (abs(centre.x) + abs(centre.y) + abs(centre.z) + reach);
|
||||
bool centred = abs(a) + remainder < lipschitz;
|
||||
float slope = centred ? a : 0.0;
|
||||
float e = (centred ? remainder : lipschitz) + allowance;
|
||||
return vec3(g.w, slope, e + (abs(g.w) + abs(slope) + e) * 9.5367431640625e-7);
|
||||
}
|
||||
|
||||
// Octave sum of cultmath_af_snoise, compounding frequency and amplitude as the value-and-gradient fBm does.
|
||||
vec3 cultmath_af_fbm(vec3 centre, vec3 axis, float radius, int octaves, float lacunarity, float gain)
|
||||
{
|
||||
octaves = clamp(octaves, 0, 16);
|
||||
float amplitude = 1.0;
|
||||
float frequency = 1.0;
|
||||
vec3 sum = vec3(0.0, 0.0, 0.0);
|
||||
for (int i = 0; i < octaves; i++)
|
||||
{
|
||||
sum = cultmath_af_add(sum, cultmath_af_scale(cultmath_af_snoise(centre * frequency, axis * frequency, radius * abs(frequency)), amplitude));
|
||||
frequency *= lacunarity;
|
||||
amplitude *= gain;
|
||||
}
|
||||
|
||||
return sum;
|
||||
}
|
||||
|
||||
// The axis of a screen tile's slice over the depth segment [z0, z1]; camera frame of
|
||||
// cultmath_iv_frustum_ball.
|
||||
vec3 cultmath_af_frustum_axis(vec2 centreSlope, float z0, float z1)
|
||||
{
|
||||
float h = (z1 - z0) * 0.5;
|
||||
return vec3(centreSlope.x * h, centreSlope.y * h, h);
|
||||
}
|
||||
|
||||
// The affine slice of a screen tile over [z0, z1]: centre xyz, radius w. Derivation in math.Affine.cs.
|
||||
vec4 cultmath_af_frustum_ball(vec2 centreSlope, float z0, float z1, float footprintPerDepth, float warpVariation)
|
||||
{
|
||||
float zm = (z0 + z1) * 0.5;
|
||||
float h = (z1 - z0) * 0.5;
|
||||
float cx = centreSlope.x * zm;
|
||||
float cy = centreSlope.y * zm;
|
||||
float spread = (abs(centreSlope.x) + abs(centreSlope.y) + 1.0) * h;
|
||||
float radius = z1 * footprintPerDepth + warpVariation;
|
||||
radius += (abs(cx) + abs(cy) + abs(zm) + spread + radius) * 9.5367431640625e-7;
|
||||
return vec4(cx, cy, zm, radius);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
float cultmath_value_noise(vec2 position)
|
||||
{
|
||||
vec2 cell = floor(position);
|
||||
vec2 local = cultmath_frac(position);
|
||||
vec2 u = local * local * (vec2(3.0, 3.0) - vec2(2.0, 2.0) * local);
|
||||
|
||||
float a = cultmath_hash(cell);
|
||||
float b = cultmath_hash(cell + vec2(1.0, 0.0));
|
||||
float c = cultmath_hash(cell + vec2(0.0, 1.0));
|
||||
float d = cultmath_hash(cell + vec2(1.0, 1.0));
|
||||
|
||||
return cultmath_lerp(cultmath_lerp(a, b, u.x), cultmath_lerp(c, d, u.x), u.y);
|
||||
}
|
||||
|
||||
float cultmath_value_noise_bicubic(vec2 position)
|
||||
{
|
||||
vec2 cell = floor(position);
|
||||
vec2 local = cultmath_frac(position);
|
||||
|
||||
float y0 = cultmath_catmullrom(cultmath_hash(cell + vec2(-1.0, -1.0)), cultmath_hash(cell + vec2(0.0, -1.0)), cultmath_hash(cell + vec2(1.0, -1.0)), cultmath_hash(cell + vec2(2.0, -1.0)), local.x);
|
||||
float y1 = cultmath_catmullrom(cultmath_hash(cell + vec2(-1.0, 0.0)), cultmath_hash(cell + vec2(0.0, 0.0)), cultmath_hash(cell + vec2(1.0, 0.0)), cultmath_hash(cell + vec2(2.0, 0.0)), local.x);
|
||||
float y2 = cultmath_catmullrom(cultmath_hash(cell + vec2(-1.0, 1.0)), cultmath_hash(cell + vec2(0.0, 1.0)), cultmath_hash(cell + vec2(1.0, 1.0)), cultmath_hash(cell + vec2(2.0, 1.0)), local.x);
|
||||
float y3 = cultmath_catmullrom(cultmath_hash(cell + vec2(-1.0, 2.0)), cultmath_hash(cell + vec2(0.0, 2.0)), cultmath_hash(cell + vec2(1.0, 2.0)), cultmath_hash(cell + vec2(2.0, 2.0)), local.x);
|
||||
|
||||
return cultmath_catmullrom(y0, y1, y2, y3, local.y);
|
||||
}
|
||||
|
||||
#endif
|
||||
|
|
@ -80,13 +80,14 @@ float3 cultmath_snoise_permute(float3 value) { return cultmath_snoise_mod289(((v
|
|||
float4 cultmath_snoise_permute(float4 value) { return cultmath_snoise_mod289(((value * 34.0) + 10.0) * value); }
|
||||
|
||||
// Ashima Arts / Ian McEwan 3D simplex noise (MIT), same float32 evaluation
|
||||
// order as the C# math.snoise(float3) mirror.
|
||||
// order as the C# math.snoise(float3) mirror. Ties resolve in simplexnoise1234's
|
||||
// total order; see math.snoise.
|
||||
float cultmath_snoise(float3 value)
|
||||
{
|
||||
float2 c = float2(1.0 / 6.0, 1.0 / 3.0);
|
||||
float3 i = floor(value + dot(value, c.yyy));
|
||||
float3 x0 = value - i + dot(i, c.xxx);
|
||||
float3 g = step(x0.yzx, x0.xyz);
|
||||
float3 g = float3(step(x0.y, x0.x), step(x0.z, x0.y), 1.0 - step(x0.z, x0.x));
|
||||
float3 l = 1.0 - g;
|
||||
float3 i1 = min(g.xyz, l.zxy);
|
||||
float3 i2 = max(g.xyz, l.zxy);
|
||||
|
|
@ -111,7 +112,7 @@ float cultmath_snoise(float3 value)
|
|||
float4 b1 = float4(x.zw, y.zw);
|
||||
float4 s0 = floor(b0) * 2.0 + 1.0;
|
||||
float4 s1 = floor(b1) * 2.0 + 1.0;
|
||||
float4 sh = -step(h, 0.0);
|
||||
float4 sh = -step(h, float4(0.0, 0.0, 0.0, 0.0));
|
||||
float4 a0 = b0.xzyw + s0.xzyw * sh.xxyy;
|
||||
float4 a1 = b1.xzyw + s1.xzyw * sh.zzww;
|
||||
|
||||
|
|
@ -172,7 +173,7 @@ float4 cultmath_snoise_grad(float3 value)
|
|||
float2 c = float2(1.0 / 6.0, 1.0 / 3.0);
|
||||
float3 i = floor(value + dot(value, c.yyy));
|
||||
float3 x0 = value - i + dot(i, c.xxx);
|
||||
float3 g = step(x0.yzx, x0.xyz);
|
||||
float3 g = float3(step(x0.y, x0.x), step(x0.z, x0.y), 1.0 - step(x0.z, x0.x));
|
||||
float3 l = 1.0 - g;
|
||||
float3 i1 = min(g.xyz, l.zxy);
|
||||
float3 i2 = max(g.xyz, l.zxy);
|
||||
|
|
@ -197,7 +198,7 @@ float4 cultmath_snoise_grad(float3 value)
|
|||
float4 b1 = float4(x.zw, y.zw);
|
||||
float4 s0 = floor(b0) * 2.0 + 1.0;
|
||||
float4 s1 = floor(b1) * 2.0 + 1.0;
|
||||
float4 sh = -step(h, 0.0);
|
||||
float4 sh = -step(h, float4(0.0, 0.0, 0.0, 0.0));
|
||||
float4 a0 = b0.xzyw + s0.xzyw * sh.xxyy;
|
||||
float4 a1 = b1.xzyw + s1.xzyw * sh.zzww;
|
||||
|
||||
|
|
@ -316,17 +317,20 @@ float cultmath_damp(float start, float end, float lambda_value, float dt)
|
|||
|
||||
float2 cultmath_damp(float2 start, float2 end, float lambda_value, float dt)
|
||||
{
|
||||
return cultmath_lerp(start, end, 1.0 - exp(-lambda_value * dt));
|
||||
float amount = 1.0 - exp(-lambda_value * dt);
|
||||
return cultmath_lerp(start, end, float2(amount, amount));
|
||||
}
|
||||
|
||||
float3 cultmath_damp(float3 start, float3 end, float lambda_value, float dt)
|
||||
{
|
||||
return cultmath_lerp(start, end, 1.0 - exp(-lambda_value * dt));
|
||||
float amount = 1.0 - exp(-lambda_value * dt);
|
||||
return cultmath_lerp(start, end, float3(amount, amount, amount));
|
||||
}
|
||||
|
||||
float4 cultmath_damp(float4 start, float4 end, float lambda_value, float dt)
|
||||
{
|
||||
return cultmath_lerp(start, end, 1.0 - exp(-lambda_value * dt));
|
||||
float amount = 1.0 - exp(-lambda_value * dt);
|
||||
return cultmath_lerp(start, end, float4(amount, amount, amount, amount));
|
||||
}
|
||||
|
||||
float cultmath_catmullrom(float p0, float p1, float p2, float p3, float t)
|
||||
|
|
@ -393,7 +397,7 @@ float cultmath_hash(float3 value) { return cultmath_hash(dot(value, float3(127.1
|
|||
uint cultmath_pcg(uint value)
|
||||
{
|
||||
uint state = value * 747796405u + 2891336453u;
|
||||
uint word = ((state >> (int)((state >> 28) + 4)) ^ state) * 277803737u;
|
||||
uint word = ((state >> (int)((state >> 28) + 4u)) ^ state) * 277803737u;
|
||||
return (word >> 22) ^ word;
|
||||
}
|
||||
|
||||
|
|
@ -406,8 +410,8 @@ int3 cultmath_pcg3d(int3 value)
|
|||
return int3((int)x, (int)y, (int)z);
|
||||
}
|
||||
|
||||
int3 cultmath_pcg3d(float2 value) { return cultmath_pcg3d(float3(value, 0.0)); }
|
||||
int3 cultmath_pcg3d(float3 value) { return cultmath_pcg3d(int3((int)asuint(value.x), (int)asuint(value.y), (int)asuint(value.z))); }
|
||||
int3 cultmath_pcg3d(float2 value) { return cultmath_pcg3d(float3(value, 0.0)); }
|
||||
|
||||
int4 cultmath_pcg4d(int4 value)
|
||||
{
|
||||
|
|
@ -468,9 +472,9 @@ CultCellular cultmath_cellular(float3 p)
|
|||
float3 neighbor = cell + float3(dx, dy, dz);
|
||||
int3 hash = cultmath_pcg3d(int3(neighbor));
|
||||
float3 jitter = float3(
|
||||
((uint)hash.x >> 8) * (1.0 / 16777216.0),
|
||||
((uint)hash.y >> 8) * (1.0 / 16777216.0),
|
||||
((uint)hash.z >> 8) * (1.0 / 16777216.0));
|
||||
(float)((uint)hash.x >> 8) * (1.0 / 16777216.0),
|
||||
(float)((uint)hash.y >> 8) * (1.0 / 16777216.0),
|
||||
(float)((uint)hash.z >> 8) * (1.0 / 16777216.0));
|
||||
float3 feature = neighbor + jitter;
|
||||
float d = cultmath_distance(p, feature);
|
||||
|
||||
|
|
@ -499,11 +503,13 @@ CultCellular cultmath_cellular(float3 p)
|
|||
CultCellular result;
|
||||
result.nearest = float4(grad1, f1);
|
||||
result.edge = float4(grad2 - grad1, f2 - f1);
|
||||
result.id = ((uint)idHash.w >> 8) * (1.0 / 16777216.0);
|
||||
result.id = (float)((uint)idHash.w >> 8) * (1.0 / 16777216.0);
|
||||
return result;
|
||||
}
|
||||
|
||||
#include "CultMath.Phacelle.hlsl"
|
||||
#include "CultMath.Interval.hlsl"
|
||||
#include "CultMath.Affine.hlsl"
|
||||
|
||||
float cultmath_value_noise(float2 position)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ using System.Runtime.InteropServices;
|
|||
|
||||
namespace CultMath;
|
||||
|
||||
/// <summary>Outcome of <see cref="BoundedLeastSquares.Solve"/>.</summary>
|
||||
/// <summary>Outcome of a <see cref="BoundedLeastSquares"/> solve.</summary>
|
||||
public enum BoundedLeastSquaresStatus
|
||||
{
|
||||
/// <summary>The KKT conditions hold: every free variable has zero gradient and every bound has a gradient pointing into it.</summary>
|
||||
|
|
@ -11,10 +11,63 @@ public enum BoundedLeastSquaresStatus
|
|||
/// <summary>The iteration cap was reached. <c>x</c> holds the last feasible iterate, which is never worse than the clamped start.</summary>
|
||||
IterationLimit,
|
||||
|
||||
/// <summary>The input broke the contract; nothing was solved and <c>x</c> is exactly as passed.</summary>
|
||||
/// <summary>The input broke the contract; nothing was solved and <c>x</c> is exactly as passed. <see cref="BoundedLeastSquares.Validate"/> names which input.</summary>
|
||||
InvalidInput,
|
||||
}
|
||||
|
||||
/// <summary>Which input of <see cref="BoundedLeastSquares"/> breaks its contract; the first failure in the order of the members.</summary>
|
||||
public enum BoundedLeastSquaresInput
|
||||
{
|
||||
/// <summary>Every input meets the contract; <c>Solve</c> will not return <see cref="BoundedLeastSquaresStatus.InvalidInput"/>.</summary>
|
||||
Valid,
|
||||
|
||||
/// <summary>The KKT tolerance is not finite and greater than zero.</summary>
|
||||
InvalidTolerance,
|
||||
|
||||
/// <summary>Some <c>lo</c> or <c>hi</c> is NaN, <c>lo[j] > hi[j]</c>, <c>lo[j]</c> is <c>+Inf</c> or <c>hi[j]</c> is <c>-Inf</c>.</summary>
|
||||
InvalidBounds,
|
||||
|
||||
/// <summary>Some entry of <c>a</c> is NaN or infinite.</summary>
|
||||
NonFiniteMatrix,
|
||||
|
||||
/// <summary>Some entry of <c>b</c> is NaN or infinite. With <c>n = 0</c> there is no unknown, <c>b</c> is never read and no entry is judged.</summary>
|
||||
NonFiniteTarget,
|
||||
}
|
||||
|
||||
/// <summary>A decision <see cref="BoundedLeastSquares"/> took, for tests that pin the stopping rule by its decisions.</summary>
|
||||
internal enum SolveEvent
|
||||
{
|
||||
/// <summary>A step stopped at a bound: column, step length.</summary>
|
||||
Step,
|
||||
|
||||
/// <summary>A bound whose violation beat the best so far, judged against its rounding bound: column, violation, noise, best before.</summary>
|
||||
Candidate,
|
||||
|
||||
/// <summary>A bound released: column, the stall mark after the release.</summary>
|
||||
Release,
|
||||
|
||||
/// <summary>A free column whose gradient is above the tolerance, so the free set is not stationary: column, the gradient's magnitude, the tolerance it was judged against. One per such column, before the pass's other decisions.</summary>
|
||||
FreeViolated,
|
||||
|
||||
/// <summary>KKT holds and the solve is over: the tolerance.</summary>
|
||||
Kkt,
|
||||
|
||||
/// <summary>A stationarity miss with no release, the cost fell and the solve goes on: cost, mark before, allowance.</summary>
|
||||
Miss,
|
||||
|
||||
/// <summary>A stationarity miss with no release, the cost did not fall: the solve is over: cost, mark, allowance.</summary>
|
||||
Stall,
|
||||
|
||||
/// <summary>The iteration cap ended the solve.</summary>
|
||||
Cap,
|
||||
}
|
||||
|
||||
/// <summary>Observes the decisions of one solve in order; never changes one.</summary>
|
||||
internal interface ISolveTrace
|
||||
{
|
||||
void Record(SolveEvent kind, int column, double a, double b, double c);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Dense bounded least squares: <c>min ||A x - b||^2</c> subject to <c>lo <= x <= hi</c>, for small problems
|
||||
/// (tens of rows and columns). C#-only, like the intercept helpers in <see cref="math"/>; there is no HLSL mirror.
|
||||
|
|
@ -31,12 +84,16 @@ public enum BoundedLeastSquaresStatus
|
|||
/// inside the box.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Stopping. KKT termination uses a tolerance of 1e-6 times the problem's gradient scale (the largest gradient
|
||||
/// component at the box point nearest the origin), so scaling A, b or the bounds, and the choice of warm start, do
|
||||
/// not change it. The tolerance is only a resolution: once a stationarity miss or a
|
||||
/// bound release has been followed by a pass that lowers the cost by no more than rounding, the solver reports
|
||||
/// <see cref="BoundedLeastSquaresStatus.Converged"/>, so an optimal point whose double gradient sits above the
|
||||
/// tolerance costs one confirming iteration rather than the iteration cap.
|
||||
/// Stopping. KKT termination uses a tolerance of <see cref="DefaultKktRelativeTolerance"/> (1e-6) times the problem's
|
||||
/// gradient scale (the largest gradient component at the box point nearest the origin), so scaling A, b or the
|
||||
/// bounds, and the choice of warm start, do not change it. A caller whose rows span many decades of weight can pass
|
||||
/// a smaller <c>kktRelativeTolerance</c>, which changes only this tolerance: the rounding bound and progress rule
|
||||
/// below and the pivot threshold are fixed. A bound is released only when its violation exceeds both the tolerance
|
||||
/// and the rounding bound of its double gradient, so a tolerance below the noise cannot cycle on a release. The
|
||||
/// tolerance is otherwise only a resolution: once a stationarity miss that releases nothing has been followed by a
|
||||
/// pass that lowers the cost by no more than rounding, the solver reports
|
||||
/// <see cref="BoundedLeastSquaresStatus.Converged"/>, so a free set whose residual is rounding costs one confirming
|
||||
/// iteration rather than the iteration cap. A pass that releases a bound is never judged by the cost.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Near-singular problems. The normal equations square the condition number, so the cost gap grows with cond(A)
|
||||
|
|
@ -48,27 +105,69 @@ public enum BoundedLeastSquaresStatus
|
|||
/// </para>
|
||||
/// The solver allocates nothing and is deterministic.
|
||||
/// <para>
|
||||
/// Input contract: <c>a</c> and <c>b</c> must be finite; <c>lo</c> and <c>hi</c> must not be NaN and need
|
||||
/// Input contract: <c>kktRelativeTolerance</c> must be finite and greater than zero; <c>a</c> and <c>b</c> must be finite; <c>lo</c> and <c>hi</c> must not be NaN and need
|
||||
/// <c>lo <= hi</c>. Infinite bounds are allowed and mean unbounded on that side (<c>lo = -Inf</c>,
|
||||
/// <c>hi = +Inf</c>); <c>lo = +Inf</c> or <c>hi = -Inf</c> is invalid. Any violation returns
|
||||
/// <see cref="BoundedLeastSquaresStatus.InvalidInput"/> without throwing, with <c>iterations</c> 0 and
|
||||
/// <c>x</c> exactly as passed. A NaN or infinite warm start is legal: it is clamped into the box (an infinite
|
||||
/// result on an unbounded side becomes 0 clamped to the box). Spans shorter than the stated dimensions are a
|
||||
/// caller bug and throw <see cref="ArgumentException"/>.
|
||||
/// caller bug and throw <see cref="ArgumentException"/>. <see cref="Validate"/> reports which input broke the
|
||||
/// contract, and <c>Solve</c> returns <c>InvalidInput</c> exactly when it does not return
|
||||
/// <see cref="BoundedLeastSquaresInput.Valid"/>.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public static class BoundedLeastSquares
|
||||
{
|
||||
/// <summary>Default iteration cap for <see cref="Solve"/>.</summary>
|
||||
/// <summary>Default iteration cap for <c>Solve</c>.</summary>
|
||||
public const int DefaultMaxIterations = 100;
|
||||
|
||||
/// <summary>Default KKT tolerance, relative to the gradient scale; see Stopping in the type remarks.</summary>
|
||||
public const double DefaultKktRelativeTolerance = 1e-6;
|
||||
|
||||
private const double PivotRelativeTolerance = 1e-12;
|
||||
private const double KktRelativeTolerance = 1e-6;
|
||||
private const double StallRelativeTolerance = 1e-15;
|
||||
|
||||
/// <summary>Floats of caller-supplied workspace needed for <paramref name="n"/> columns.</summary>
|
||||
public static int WorkspaceLength(int n) => 2 * (2 * n * n + 6 * n) + 3 * n;
|
||||
|
||||
/// <summary>
|
||||
/// Checks the inputs of <c>Solve</c> against its contract and names the first one that breaks it, in the order
|
||||
/// tolerance, bounds, matrix, target. <c>Solve</c> calls this and returns
|
||||
/// <see cref="BoundedLeastSquaresStatus.InvalidInput"/> for any result but <see cref="BoundedLeastSquaresInput.Valid"/>.
|
||||
/// It reads its arguments only, allocates nothing and does not throw for a bad value.
|
||||
/// </summary>
|
||||
/// <param name="m">Rows of <paramref name="a"/>.</param>
|
||||
/// <param name="n">Columns of <paramref name="a"/>, and length of <paramref name="lo"/> and <paramref name="hi"/>.</param>
|
||||
/// <param name="a">Row-major <c>m * n</c> matrix.</param>
|
||||
/// <param name="b">Length <c>m</c> target. With <c>n = 0</c> there is no unknown and <paramref name="b"/> is not read.</param>
|
||||
/// <param name="lo">Lower bounds.</param>
|
||||
/// <param name="hi">Upper bounds.</param>
|
||||
/// <param name="kktRelativeTolerance">The tolerance <c>Solve</c> will be given.</param>
|
||||
/// <exception cref="ArgumentException">A span is shorter than the stated dimensions, or <paramref name="m"/> or <paramref name="n"/> is negative: a caller bug, not an invalid input.</exception>
|
||||
public static BoundedLeastSquaresInput Validate(
|
||||
int m, int n,
|
||||
ReadOnlySpan<float> a, ReadOnlySpan<float> b,
|
||||
ReadOnlySpan<float> lo, ReadOnlySpan<float> hi,
|
||||
double kktRelativeTolerance = DefaultKktRelativeTolerance)
|
||||
{
|
||||
if (m < 0 || n < 0 || a.Length < m * n || b.Length < m || lo.Length < n || hi.Length < n)
|
||||
throw new ArgumentException("BoundedLeastSquares: span shorter than the stated dimensions.");
|
||||
|
||||
if (!(kktRelativeTolerance > 0.0) || double.IsPositiveInfinity(kktRelativeTolerance))
|
||||
return BoundedLeastSquaresInput.InvalidTolerance;
|
||||
for (var j = 0; j < n; j++)
|
||||
if (!(lo[j] <= hi[j]) || float.IsPositiveInfinity(lo[j]) || float.IsNegativeInfinity(hi[j]))
|
||||
return BoundedLeastSquaresInput.InvalidBounds;
|
||||
for (var i = 0; i < m * n; i++)
|
||||
if (!float.IsFinite(a[i]))
|
||||
return BoundedLeastSquaresInput.NonFiniteMatrix;
|
||||
if (n > 0)
|
||||
for (var r = 0; r < m; r++)
|
||||
if (!float.IsFinite(b[r]))
|
||||
return BoundedLeastSquaresInput.NonFiniteTarget;
|
||||
return BoundedLeastSquaresInput.Valid;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Minimises <c>||A x - b||^2</c> subject to <c>lo <= x <= hi</c>. <paramref name="x"/> is the warm start
|
||||
/// on entry (clamped to the box first) and the result on exit.
|
||||
|
|
@ -90,10 +189,51 @@ public static class BoundedLeastSquares
|
|||
Span<float> x, Span<float> workspace,
|
||||
out int iterations,
|
||||
int maxIterations = DefaultMaxIterations)
|
||||
=> Solve(m, n, a, b, lo, hi, x, workspace, out iterations, DefaultKktRelativeTolerance, maxIterations);
|
||||
|
||||
/// <summary>
|
||||
/// Minimises <c>||A x - b||^2</c> subject to <c>lo <= x <= hi</c>. <paramref name="x"/> is the warm start
|
||||
/// on entry (clamped to the box first) and the result on exit. <paramref name="kktRelativeTolerance"/> is the
|
||||
/// stationarity resolution relative to the gradient scale defined under Stopping; the overload without it passes
|
||||
/// <see cref="DefaultKktRelativeTolerance"/> and gives the same result.
|
||||
/// </summary>
|
||||
/// <param name="m">Rows of <paramref name="a"/>.</param>
|
||||
/// <param name="n">Columns of <paramref name="a"/>, and length of <paramref name="lo"/>, <paramref name="hi"/> and <paramref name="x"/>.</param>
|
||||
/// <param name="a">Row-major <c>m * n</c> matrix.</param>
|
||||
/// <param name="b">Length <c>m</c> target.</param>
|
||||
/// <param name="lo">Lower bounds; each must be <c><= hi</c>; <c>-Inf</c> means unbounded below.</param>
|
||||
/// <param name="hi">Upper bounds; <c>+Inf</c> means unbounded above.</param>
|
||||
/// <param name="x">Warm start in, solution out.</param>
|
||||
/// <param name="workspace">At least <see cref="WorkspaceLength"/> floats; contents on entry are ignored.</param>
|
||||
/// <param name="iterations">Active-set iterations used.</param>
|
||||
/// <param name="kktRelativeTolerance">Finite and greater than zero, else <see cref="BoundedLeastSquaresStatus.InvalidInput"/>. Tighten it when rows span many decades of weight; releases below the gradient's rounding bound are not taken, and free-set residuals at rounding level end on the progress rule.</param>
|
||||
/// <param name="maxIterations">Iteration cap.</param>
|
||||
public static BoundedLeastSquaresStatus Solve(
|
||||
int m, int n,
|
||||
ReadOnlySpan<float> a, ReadOnlySpan<float> b,
|
||||
ReadOnlySpan<float> lo, ReadOnlySpan<float> hi,
|
||||
Span<float> x, Span<float> workspace,
|
||||
out int iterations,
|
||||
double kktRelativeTolerance,
|
||||
int maxIterations = DefaultMaxIterations)
|
||||
=> SolveTraced(m, n, a, b, lo, hi, x, workspace, out iterations, kktRelativeTolerance, maxIterations, null);
|
||||
|
||||
// The whole solve. A trace sink only observes: every decision below is taken from the same values with or without one.
|
||||
internal static BoundedLeastSquaresStatus SolveTraced(
|
||||
int m, int n,
|
||||
ReadOnlySpan<float> a, ReadOnlySpan<float> b,
|
||||
ReadOnlySpan<float> lo, ReadOnlySpan<float> hi,
|
||||
Span<float> x, Span<float> workspace,
|
||||
out int iterations,
|
||||
double kktRelativeTolerance,
|
||||
int maxIterations,
|
||||
ISolveTrace? trace)
|
||||
{
|
||||
if (m < 0 || n < 0 || a.Length < m * n || b.Length < m || lo.Length < n || hi.Length < n
|
||||
|| x.Length < n || workspace.Length < WorkspaceLength(n))
|
||||
if (x.Length < n || workspace.Length < WorkspaceLength(n))
|
||||
throw new ArgumentException("BoundedLeastSquares: span shorter than the stated dimensions.");
|
||||
iterations = 0;
|
||||
if (Validate(m, n, a, b, lo, hi, kktRelativeTolerance) != BoundedLeastSquaresInput.Valid)
|
||||
return BoundedLeastSquaresStatus.InvalidInput;
|
||||
|
||||
// Double-precision vectors and matrices first, then the integer flags, all carved from the caller's floats.
|
||||
var doubleCount = 2 * n * n + 6 * n;
|
||||
|
|
@ -112,20 +252,11 @@ public static class BoundedLeastSquares
|
|||
var freeIndex = Take(ref ints, n);
|
||||
var dependent = Take(ref ints, n);
|
||||
|
||||
iterations = 0;
|
||||
for (var j = 0; j < n; j++)
|
||||
if (!(lo[j] <= hi[j]) || float.IsPositiveInfinity(lo[j]) || float.IsNegativeInfinity(hi[j]))
|
||||
return BoundedLeastSquaresStatus.InvalidInput;
|
||||
|
||||
// A float is never large enough to overflow a double product or a sum of tens of them, so a non-finite
|
||||
// A^T b entry is exactly a non-finite entry of A or b (NaN and infinity never cancel to a finite value).
|
||||
for (var j = 0; j < n; j++)
|
||||
{
|
||||
var sb = 0.0;
|
||||
for (var r = 0; r < m; r++)
|
||||
sb += (double)a[r * n + j] * b[r];
|
||||
if (!double.IsFinite(sb))
|
||||
return BoundedLeastSquaresStatus.InvalidInput;
|
||||
atb[j] = sb;
|
||||
for (var k = 0; k <= j; k++)
|
||||
{
|
||||
|
|
@ -165,11 +296,11 @@ public static class BoundedLeastSquares
|
|||
s += ata[j * n + k] * Math.Clamp(0.0, lo[k], hi[k]);
|
||||
gScale = Math.Max(gScale, Math.Abs(s));
|
||||
}
|
||||
var kktTol = KktRelativeTolerance * gScale;
|
||||
var kktTol = kktRelativeTolerance * gScale;
|
||||
|
||||
// Cost at the last point from which the solver chose to continue past a stationarity miss or a
|
||||
// release. A pass that ends without lowering it has nothing left to gain: the tolerance is a
|
||||
// resolution, not the stopping rule, and a noise floor above it must not spin to the cap.
|
||||
// Cost at the last point from which the solver continued past a stationarity miss with no release; a
|
||||
// release resets it. A stationarity miss that ends without lowering it has nothing left to gain: the
|
||||
// tolerance is a resolution, not the stopping rule, and a noise floor above it must not spin to the cap.
|
||||
var fMark = double.PositiveInfinity;
|
||||
var status = BoundedLeastSquaresStatus.IterationLimit;
|
||||
while (true)
|
||||
|
|
@ -199,8 +330,9 @@ public static class BoundedLeastSquares
|
|||
|
||||
if (block >= 0)
|
||||
{
|
||||
if (iterations >= maxIterations) { status = BoundedLeastSquaresStatus.IterationLimit; break; }
|
||||
if (iterations >= maxIterations) { trace?.Record(SolveEvent.Cap, -1, 0.0, 0.0, 0.0); status = BoundedLeastSquaresStatus.IterationLimit; break; }
|
||||
iterations++;
|
||||
trace?.Record(SolveEvent.Step, block, t, 0.0, 0.0);
|
||||
for (var i = 0; i < freeCount; i++)
|
||||
{
|
||||
var j = freeIndex[i];
|
||||
|
|
@ -219,30 +351,10 @@ public static class BoundedLeastSquares
|
|||
Gradient(ata, atb, xd, g, n);
|
||||
|
||||
// Stationarity of the free set is part of KKT: a Newton step on a near-singular free set can leave a residual gradient.
|
||||
var freeViolated = false;
|
||||
for (var i = 0; i < freeCount; i++)
|
||||
if (Math.Abs(g[freeIndex[i]]) > kktTol)
|
||||
freeViolated = true;
|
||||
|
||||
var release = -1;
|
||||
var worst = kktTol;
|
||||
for (var j = 0; j < n; j++)
|
||||
{
|
||||
if (lo[j] == hi[j]) continue;
|
||||
// A bound at lo wants a positive gradient and one at hi a negative one; a free column has state 0.
|
||||
var violation = state[j] * g[j];
|
||||
if (violation > worst)
|
||||
{
|
||||
worst = violation;
|
||||
release = j;
|
||||
}
|
||||
}
|
||||
if (release < 0 && !freeViolated) { status = BoundedLeastSquaresStatus.Converged; break; }
|
||||
|
||||
var f = Objective(xd, g, atb, n, out var fScale);
|
||||
if (f >= fMark - StallRelativeTolerance * fScale) { status = BoundedLeastSquaresStatus.Converged; break; }
|
||||
fMark = f;
|
||||
if (iterations >= maxIterations) { status = BoundedLeastSquaresStatus.IterationLimit; break; }
|
||||
var freeViolated = FreeSetViolated(g, freeIndex, freeCount, kktTol, trace);
|
||||
var release = SelectRelease(ata, atb, xd, g, state, lo, hi, kktTol, n, trace);
|
||||
if (JudgePass(release, freeViolated, kktTol, ref fMark, xd, g, atb, n, trace)) { status = BoundedLeastSquaresStatus.Converged; break; }
|
||||
if (iterations >= maxIterations) { trace?.Record(SolveEvent.Cap, -1, 0.0, 0.0, 0.0); status = BoundedLeastSquaresStatus.IterationLimit; break; }
|
||||
iterations++;
|
||||
// A stationarity miss re-solves the same free set from the improved point.
|
||||
if (release >= 0) state[release] = 0;
|
||||
|
|
@ -253,6 +365,79 @@ public static class BoundedLeastSquares
|
|||
return status;
|
||||
}
|
||||
|
||||
// Whether any free column's gradient is above the tolerance; every such column is recorded with the magnitude and the threshold it was judged against.
|
||||
internal static bool FreeSetViolated(ReadOnlySpan<double> g, ReadOnlySpan<int> freeIndex, int freeCount, double kktTol, ISolveTrace? trace)
|
||||
{
|
||||
var violated = false;
|
||||
for (var i = 0; i < freeCount; i++)
|
||||
{
|
||||
var magnitude = Math.Abs(g[freeIndex[i]]);
|
||||
if (magnitude > kktTol)
|
||||
{
|
||||
trace?.Record(SolveEvent.FreeViolated, freeIndex[i], magnitude, kktTol, 0.0);
|
||||
violated = true;
|
||||
}
|
||||
}
|
||||
return violated;
|
||||
}
|
||||
|
||||
// The bound to release: the one with the most violated gradient sign, the first of equal violations, and only if
|
||||
// the violation exceeds both the tolerance (the starting `worst`) and the rounding bound of its own gradient.
|
||||
// -1 when none qualifies.
|
||||
internal static int SelectRelease(
|
||||
ReadOnlySpan<double> ata, ReadOnlySpan<double> atb, ReadOnlySpan<double> x, ReadOnlySpan<double> g,
|
||||
ReadOnlySpan<int> state, ReadOnlySpan<float> lo, ReadOnlySpan<float> hi, double kktTol, int n, ISolveTrace? trace)
|
||||
{
|
||||
var release = -1;
|
||||
var worst = kktTol;
|
||||
for (var j = 0; j < n; j++)
|
||||
{
|
||||
if (lo[j] == hi[j]) continue;
|
||||
// A bound at lo wants a positive gradient and one at hi a negative one; a free column has state 0.
|
||||
var violation = state[j] * g[j];
|
||||
if (violation > worst)
|
||||
{
|
||||
var noise = ReleaseNoise(ata, atb, x, j, n);
|
||||
trace?.Record(SolveEvent.Candidate, j, violation, noise, worst);
|
||||
if (violation > noise)
|
||||
{
|
||||
worst = violation;
|
||||
release = j;
|
||||
}
|
||||
}
|
||||
}
|
||||
return release;
|
||||
}
|
||||
|
||||
// What a full step's outcome means for the solve: true when it is over. Nothing to release and a stationary free
|
||||
// set is KKT. Nothing to release with a stationarity miss ends when the cost has not fallen below the last such
|
||||
// miss's by more than rounding, else it records the cost. A release is never judged by the cost and resets the mark.
|
||||
internal static bool JudgePass(
|
||||
int release, bool freeViolated, double kktTol, ref double fMark,
|
||||
ReadOnlySpan<double> x, ReadOnlySpan<double> g, ReadOnlySpan<double> atb, int n, ISolveTrace? trace)
|
||||
{
|
||||
if (release < 0 && !freeViolated)
|
||||
{
|
||||
trace?.Record(SolveEvent.Kkt, -1, kktTol, 0.0, 0.0);
|
||||
return true;
|
||||
}
|
||||
if (release < 0)
|
||||
{
|
||||
var f = Objective(x, g, atb, n, out var fScale);
|
||||
var allowance = StallRelativeTolerance * fScale;
|
||||
var stalled = f >= fMark - allowance;
|
||||
trace?.Record(stalled ? SolveEvent.Stall : SolveEvent.Miss, -1, f, fMark, allowance);
|
||||
if (stalled) return true;
|
||||
fMark = f;
|
||||
}
|
||||
else
|
||||
{
|
||||
fMark = double.PositiveInfinity;
|
||||
trace?.Record(SolveEvent.Release, release, fMark, 0.0, 0.0);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static Span<T> Take<T>(ref Span<T> pool, int length)
|
||||
{
|
||||
var head = pool.Slice(0, length);
|
||||
|
|
@ -274,6 +459,14 @@ public static class BoundedLeastSquares
|
|||
return f;
|
||||
}
|
||||
|
||||
// Rounding bound of the double gradient component j: gamma_(n+1) (Higham, inner products) times the magnitude of its terms.
|
||||
internal static double ReleaseNoise(ReadOnlySpan<double> ata, ReadOnlySpan<double> atb, ReadOnlySpan<double> x, int j, int n)
|
||||
{
|
||||
var s = Math.Abs(atb[j]);
|
||||
for (var k = 0; k < n; k++) s += Math.Abs(ata[j * n + k] * x[k]);
|
||||
return (n + 1) * 2.220446049250313e-16 * s;
|
||||
}
|
||||
|
||||
private static void Gradient(ReadOnlySpan<double> ata, ReadOnlySpan<double> atb, ReadOnlySpan<double> x, Span<double> g, int n)
|
||||
{
|
||||
for (var j = 0; j < n; j++)
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@
|
|||
<PackageId>GameCult.Math</PackageId>
|
||||
<!-- MIT overall; math.Phacelle.cs and CultPhasor.cs (and the two Phacelle HLSL files) are MPL-2.0. -->
|
||||
<PackageLicenseExpression>MIT AND MPL-2.0</PackageLicenseExpression>
|
||||
<Version>0.2.4</Version>
|
||||
<Version>0.4.1</Version>
|
||||
<Description>Clean-room C# math shaped for HLSL-style renderer code.</Description>
|
||||
<Authors>GameCult</Authors>
|
||||
<PackageReadmeFile>README.md</PackageReadmeFile>
|
||||
|
|
@ -24,6 +24,8 @@
|
|||
<None Include="..\..\README.md" Pack="true" PackagePath="\" />
|
||||
<None Include="..\..\shaders\CultMath.hlsl" Pack="true" PackagePath="contentFiles\any\any\shaders\CultMath.hlsl" CopyToOutputDirectory="PreserveNewest" />
|
||||
<None Include="..\..\shaders\CultMath.Phacelle.hlsl" Pack="true" PackagePath="contentFiles\any\any\shaders\CultMath.Phacelle.hlsl" CopyToOutputDirectory="PreserveNewest" />
|
||||
<None Include="..\..\shaders\CultMath.Interval.hlsl" Pack="true" PackagePath="contentFiles\any\any\shaders\CultMath.Interval.hlsl" CopyToOutputDirectory="PreserveNewest" />
|
||||
<None Include="..\..\shaders\CultMath.Affine.hlsl" Pack="true" PackagePath="contentFiles\any\any\shaders\CultMath.Affine.hlsl" CopyToOutputDirectory="PreserveNewest" />
|
||||
<None Include="..\..\THIRD-PARTY-NOTICES.md" Pack="true" PackagePath="\" />
|
||||
</ItemGroup>
|
||||
|
||||
|
|
|
|||
241
packages/cultmath/src/CultMath/math.Affine.cs
Normal file
241
packages/cultmath/src/CultMath/math.Affine.cs
Normal file
|
|
@ -0,0 +1,241 @@
|
|||
namespace CultMath;
|
||||
|
||||
public static partial class math
|
||||
{
|
||||
// Reduced affine forms with one shared symbol (design.md, "Affine forms"): float3(x0, a, e) is the
|
||||
// set { x0 + a eps + e delta : delta in [-1, 1] } at the region's shared eps in [-1, 1], with
|
||||
// e >= 0. Every form over one region shares that eps (for a screen-tile slice, the depth
|
||||
// parameter), and delta is private to the form. This is Messine's AF1 as Gamito and Maddock use it
|
||||
// for gradient noise (t0 + t1 e1 + t2 e2), in one register, as an interval is a float2.
|
||||
//
|
||||
// Every af_* op returns a form whose set, at each eps, contains f evaluated pointwise in float32 at
|
||||
// every point of its operands' sets at that same eps. Rounding rule: each op folds its own float32
|
||||
// rounding into e as (S) 2^-20, where S is the sum of the magnitudes the op's roundings are
|
||||
// relative to (named in each comment). With u = 2^-24, every op below needs at most 8u S (its
|
||||
// component roundings, the pointwise result's own rounding, and the roundings of computing e), so
|
||||
// 2^-20 = 16u covers it twice over; the factor of two is the allowance for a device whose + and *
|
||||
// are faithful (within one ulp) rather than correctly rounded, and fma contraction only removes
|
||||
// roundings. Products also add 2^-126, the most any underflow to a subnormal can lose. The
|
||||
// enclosure tests evaluate the form's set in double and f in float32 with no tolerance
|
||||
// (AffineTests.EveryOpEnclosesItsPoints). No op takes a compound type or a reference parameter: each is a
|
||||
// plain function of float values, so it mirrors into the HLSL common subset.
|
||||
|
||||
// An upper bound on the spectral norm of the Hessian of snoise(float3). Provenance:
|
||||
// NoiseBoundTests.MeasureHessian (slow, explicit) takes the largest Hessian norm (central
|
||||
// differences of snoise_grad, largest absolute eigenvalue) over 1e6 seeded points, refines the 1e4
|
||||
// largest by ascent, and multiplies the refined maximum by 1.10;
|
||||
// NoiseBoundTests.HessianConstantPinsSampledCurvature pins this value against a fast re-measure and
|
||||
// the ascent from MeasureHessian's witness. Empirical with a margin, not a proof. Random balls
|
||||
// cannot see a constant 20% low, so the defence is those two curvature tests plus
|
||||
// NoiseBoundTests.SnoiseFormEnclosesTheCurvatureWitness, where af_snoise misses at the point the
|
||||
// curvature is realised if the constant is under it. The margin over the function: a scan of the
|
||||
// whole 289^3 hash period found a realised maximum of 50.58, and bounding each corner's gradient
|
||||
// independently over every hash configuration gives 52.22 (Soul pass s1). A change to the snoise
|
||||
// kernel must re-run MeasureHessian and re-pin it.
|
||||
public const float SNOISE_HESSIAN = 56.050385f;
|
||||
|
||||
/// <summary>The point form (x, 0, 0): the value x at every eps. Exact.</summary>
|
||||
public static float3 af_point(float value) => new(value, 0.0f, 0.0f);
|
||||
|
||||
/// <summary>
|
||||
/// The shared symbol itself, (x0, a, 0): the value x0 + a eps. It is how a region's parameter enters
|
||||
/// (for a tile slice, depth z = z_m + h eps), so it is exact by definition: eps is defined through it.
|
||||
/// </summary>
|
||||
public static float3 af_symbol(float x0, float a) => new(x0, a, 0.0f);
|
||||
|
||||
/// <summary>
|
||||
/// Every value of the interval [lo, hi], uncorrelated with eps: (lo / 2 + hi / 2, 0, hi / 2 - lo / 2),
|
||||
/// the halves taken before the sum and the difference so that endpoints near the float maximum do not
|
||||
/// overflow in them. Rounding: x0 and e each round once, and a value of the interval is within e of x0
|
||||
/// only up to those; S = |x0| + e. Halving a subnormal endpoint loses at most 2^-150, and the sum and
|
||||
/// difference of subnormals are exact, so 2^-126 covers the underflow (the e of an interval spanning
|
||||
/// one subnormal step would otherwise round to 0). |x0| + e is at most the larger endpoint
|
||||
/// in magnitude, so it does not overflow. If e + its absorption exceeds the float maximum it is
|
||||
/// infinity, which still encloses.
|
||||
/// </summary>
|
||||
public static float3 af_from_iv(float2 interval)
|
||||
{
|
||||
var x0 = interval.x * 0.5f + interval.y * 0.5f;
|
||||
var e = interval.y * 0.5f - interval.x * 0.5f;
|
||||
return new float3(x0, 0.0f, e + (abs(x0) + e) * 9.5367431640625e-7f + 1.17549435e-38f);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The interval of every value of the form over every eps: x0 -+ (|a| + e), the bridge to iv_*. The
|
||||
/// endpoints round inward by at most u (|x0| + |a| + e) each, so each is moved outward by
|
||||
/// (|x0| + |a| + e) 2^-20, formed term by term so that the sum never passes the float maximum before it
|
||||
/// is scaled. A form with an infinite component (an overflowed op) gives infinite
|
||||
/// endpoints, and an endpoint that would be NaN (infinity minus infinity, or a NaN component) is
|
||||
/// the infinity on its side, so the result is never NaN and still encloses. NaN is found by its bit
|
||||
/// pattern, not by <c>lo == lo</c>, which a compiler that assumes no NaNs (dxc's default) deletes.
|
||||
/// </summary>
|
||||
public static float2 af_range(float3 x)
|
||||
{
|
||||
var r = abs(x.y) + x.z;
|
||||
var w = abs(x.x) * 9.5367431640625e-7f + r * 9.5367431640625e-7f;
|
||||
var lo = x.x - r - w;
|
||||
var hi = x.x + r + w;
|
||||
return new float2((asuint(lo) & 0x7fffffffu) > 0x7f800000u ? float.NegativeInfinity : lo,
|
||||
(asuint(hi) & 0x7fffffffu) > 0x7f800000u ? float.PositiveInfinity : hi);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Encloses x + y: (x0 + y0, a_x + a_y, e_x + e_y). The shared symbol keeps the two forms
|
||||
/// correlated, so af_sub(x, x) has a = 0. Rounding: S = |x0| + |a| + e of the result.
|
||||
/// </summary>
|
||||
public static float3 af_add(float3 x, float3 y)
|
||||
{
|
||||
var x0 = x.x + y.x;
|
||||
var a = x.y + y.y;
|
||||
var e = x.z + y.z;
|
||||
return new float3(x0, a, e + (abs(x0) + abs(a) + e) * 9.5367431640625e-7f);
|
||||
}
|
||||
|
||||
/// <summary>Encloses x - y: (x0 - y0, a_x - a_y, e_x + e_y). Rounding as af_add.</summary>
|
||||
public static float3 af_sub(float3 x, float3 y)
|
||||
{
|
||||
var x0 = x.x - y.x;
|
||||
var a = x.y - y.y;
|
||||
var e = x.z + y.z;
|
||||
return new float3(x0, a, e + (abs(x0) + abs(a) + e) * 9.5367431640625e-7f);
|
||||
}
|
||||
|
||||
/// <summary>Encloses -x: (-x0, -a, e). Exact.</summary>
|
||||
public static float3 af_neg(float3 x) => new(-x.x, -x.y, x.z);
|
||||
|
||||
/// <summary>
|
||||
/// Encloses x * s: (x0 s, a s, e |s|). Rounding: S = |x0| + |a| + e of the result, plus 2^-126
|
||||
/// for underflow.
|
||||
/// </summary>
|
||||
public static float3 af_scale(float3 x, float s)
|
||||
{
|
||||
var x0 = x.x * s;
|
||||
var a = x.y * s;
|
||||
var e = x.z * abs(s);
|
||||
return new float3(x0, a, e + (abs(x0) + abs(a) + e) * 9.5367431640625e-7f + 1.17549435e-38f);
|
||||
}
|
||||
|
||||
/// <summary>Encloses x + v for v in the interval, uncorrelated with eps: af_add(x, af_from_iv(interval)).</summary>
|
||||
public static float3 af_add_iv(float3 x, float2 interval) => af_add(x, af_from_iv(interval));
|
||||
|
||||
/// <summary>
|
||||
/// Encloses x * y, AF1's product: (x0 y0, x0 a_y + y0 a_x, |x0| e_y + |y0| e_x + (|a_x| + e_x)(|a_y| + e_y)).
|
||||
/// The last term condenses the eps^2 term a_x a_y and every cross term with an error symbol into e,
|
||||
/// so a form multiplied by itself is wider than its square: there is no af_sqr until a consumer
|
||||
/// names one. Rounding: a can cancel, so S = |x0| + |x0 a_y| + |y0 a_x| + e, plus 2^-126 for
|
||||
/// underflow.
|
||||
/// </summary>
|
||||
public static float3 af_mul(float3 x, float3 y)
|
||||
{
|
||||
var x0 = x.x * y.x;
|
||||
var p = x.x * y.y;
|
||||
var q = y.x * x.y;
|
||||
var a = p + q;
|
||||
var e = abs(x.x) * y.z + abs(y.x) * x.z + (abs(x.y) + x.z) * (abs(y.y) + y.z);
|
||||
return new float3(x0, a, e + (abs(x0) + abs(p) + abs(q) + e) * 9.5367431640625e-7f + 1.17549435e-38f);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Encloses snoise(p) for every p = centre + axis eps + w with |w| <= radius, from one snoise_grad at
|
||||
/// the centre (value n, gradient g). With R = |axis| + radius it returns the narrower of two sound
|
||||
/// forms: the Lipschitz form (n, 0, L R), L = SNOISE_LIPSCHITZ, and the centred form
|
||||
/// (n, g . axis, |g| radius + M R^2 / 2), M = SNOISE_HESSIAN. The centred form is Taylor's theorem:
|
||||
/// snoise(c + d) = n + g . d + r with |r| <= M |d|^2 / 2, d = axis eps + w, g . w <= |g| radius.
|
||||
/// radius must be at least 0.
|
||||
///
|
||||
/// Both forms carry an allowance for the float32 evaluation of snoise, which is not the exact
|
||||
/// function: 2^-14 + 2^-12 R + L 2^-20 (|centre|_1 + R). The skew and the corner offsets round the
|
||||
/// input point by at most about 2u |p|_1 before any kernel term is formed (the hashing is exact on
|
||||
/// integers below 2^24), so a float32 snoise of p is the exact one at a point within 2u |p|_1, which
|
||||
/// moves the value by at most L 2u |p|_1; for both p and the centre, with the caller's scaling of the
|
||||
/// point by a frequency (one rounding) and a factor of two for a GPU, 16u = 2^-20. The kernel's
|
||||
/// absolute rounding is at most 105 x four corners x terms of magnitude below 0.5^4 x 1.8 over about
|
||||
/// 30 operations, under 2^-15, doubled to 2^-14; the gradient's error times |d| <= R is under 2^-13 R,
|
||||
/// doubled to 2^-12 R. AffineTests.SnoiseFormEnclosesBall checks the result with no tolerance on the
|
||||
/// CPU, and the fixture's enclosure check measures it on a GPU. Rounding of the form itself: S =
|
||||
/// |n| + |a| + e. The Lipschitz form is chosen when its half-width L R is at most the centred form's
|
||||
/// |a| + |g| radius + M R^2 / 2, so the total width is never more than the Lipschitz form's.
|
||||
/// </summary>
|
||||
public static float3 af_snoise(float3 centre, float3 axis, float radius)
|
||||
{
|
||||
var g = snoise_grad(centre);
|
||||
var gradient = new float3(g.x, g.y, g.z);
|
||||
var reach = length(axis) + radius;
|
||||
var lipschitz = SNOISE_LIPSCHITZ * reach;
|
||||
var a = dot(gradient, axis);
|
||||
var remainder = length(gradient) * radius + 0.5f * SNOISE_HESSIAN * reach * reach;
|
||||
var allowance = 6.103515625e-5f + 2.44140625e-4f * reach
|
||||
+ SNOISE_LIPSCHITZ * 9.5367431640625e-7f * (abs(centre.x) + abs(centre.y) + abs(centre.z) + reach);
|
||||
var centred = abs(a) + remainder < lipschitz;
|
||||
var slope = centred ? a : 0.0f;
|
||||
var e = (centred ? remainder : lipschitz) + allowance;
|
||||
return new float3(g.w, slope, e + (abs(g.w) + abs(slope) + e) * 9.5367431640625e-7f);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Encloses the fBm value, sum of a_i snoise(p f_i) over the octaves, for every p = centre + axis eps
|
||||
/// + w with |w| <= radius: the octave sum of af_snoise(centre f_i, axis f_i, radius |f_i|) scaled by
|
||||
/// a_i, with frequency f_i and amplitude a_i compounded exactly as fbm_grad compounds them (its .w is
|
||||
/// what AffineTests.SnoiseFormEnclosesBall encloses). The rounding of p f_i, inside fbm_grad, and of
|
||||
/// the scaled centre and axis here, moves each point by at most 3u (|centre f_i|_1 + R f_i), inside
|
||||
/// af_snoise's allowance for its input point. octaves is clamped to [0, 16] as there.
|
||||
/// </summary>
|
||||
public static float3 af_fbm(float3 centre, float3 axis, float radius, int octaves, float lacunarity, float gain)
|
||||
{
|
||||
octaves = clamp(octaves, 0, 16);
|
||||
var amplitude = 1.0f;
|
||||
var frequency = 1.0f;
|
||||
var sum = new float3(0.0f, 0.0f, 0.0f);
|
||||
for (var i = 0; i < octaves; i++)
|
||||
{
|
||||
sum = af_add(sum, af_scale(af_snoise(centre * frequency, axis * frequency, radius * abs(frequency)), amplitude));
|
||||
frequency *= lacunarity;
|
||||
amplitude *= gain;
|
||||
}
|
||||
|
||||
return sum;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The axis of a screen tile's slice over the depth segment [z0, z1], for af_frustum_ball's centre:
|
||||
/// (m_c, 1) h with h = (z1 - z0) / 2, in the camera frame of iv_frustum_ball (a pinhole at the
|
||||
/// origin looking down +z, the ray of slope m the points (m z, z)). Its z component is h itself, the
|
||||
/// symbol's coefficient for depth: z = z_m + h eps. Its rounding is af_frustum_ball's.
|
||||
/// </summary>
|
||||
public static float3 af_frustum_axis(float2 centreSlope, float z0, float z1)
|
||||
{
|
||||
var h = (z1 - z0) * 0.5f;
|
||||
return new float3(centreSlope.x * h, centreSlope.y * h, h);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The affine slice of a screen tile over [z0, z1]: a centre (xyz) and radius (w) such that every point
|
||||
/// of every ray of the tile at depth z in [z0, z1] is centre + axis eps(z) + w', |w'| <= radius, with
|
||||
/// axis = af_frustum_axis(centreSlope, z0, z1), z_m = (z0 + z1) / 2, h = (z1 - z0) / 2 (both float32,
|
||||
/// as computed here) and eps(z) = clamp((z - z_m) / h, -1, 1) (0 where h is 0). The centre is
|
||||
/// (m_c z_m, z_m) and the radius z1 footprintPerDepth + warpVariation, where footprintPerDepth is
|
||||
/// iv_frustum_ball's and warpVariation is what the caller's warp can add once its value at the centre
|
||||
/// is applied to the centre (design.md, "Affine forms", the centred warp). Derivation: a point of
|
||||
/// slope m_c + e (|e| <= footprintPerDepth) at depth z is (m_c z_m, z_m) + (m_c, 1)(z - z_m) +
|
||||
/// (e z, 0), and (m_c, 1)(z - z_m) = axis eps(z) + (m_c, 1) r(z), where the clamp residual
|
||||
/// |r(z)| = |z - z_m - h eps(z)| is at most u (|z_m| + h), one rounding each of z_m and h. A caller
|
||||
/// taking depth as af_symbol(z_m, h) adds the same residual, 2^-23 (|z_m| + h) covers it, to that
|
||||
/// form's e. Rounding: the centre's products and the axis's products round once each (u |c|_1 and
|
||||
/// u |axis|_1 against |eps| <= 1), the residual is at most u (|c|_1 + |axis|_1) since
|
||||
/// |(m_c, 1)| <= |m_c|_1 + 1, and the radius rounds at most four times; 2^-20 (|c|_1 + |axis|_1 +
|
||||
/// radius) covers it twice over (AffineTests.FrustumSliceEnclosesEveryRayPoint, extreme families
|
||||
/// included). The caller rotates and translates the centre into world space, rotates the axis, and
|
||||
/// scales all three by its noise frequency; the rounding of that transform is the caller's.
|
||||
/// </summary>
|
||||
public static float4 af_frustum_ball(float2 centreSlope, float z0, float z1, float footprintPerDepth, float warpVariation)
|
||||
{
|
||||
var zm = (z0 + z1) * 0.5f;
|
||||
var h = (z1 - z0) * 0.5f;
|
||||
var cx = centreSlope.x * zm;
|
||||
var cy = centreSlope.y * zm;
|
||||
var spread = (abs(centreSlope.x) + abs(centreSlope.y) + 1.0f) * h;
|
||||
var radius = z1 * footprintPerDepth + warpVariation;
|
||||
radius += (abs(cx) + abs(cy) + abs(zm) + spread + radius) * 9.5367431640625e-7f;
|
||||
return new float4(cx, cy, zm, radius);
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue