diff --git a/research/physical-scalar-stream/PROOF.md b/research/physical-scalar-stream/PROOF.md new file mode 100644 index 0000000000..a986ce46de --- /dev/null +++ b/research/physical-scalar-stream/PROOF.md @@ -0,0 +1,227 @@ +# Sequential scalar packets with fixed local word roles + +Jose Manuel (`jmbarrancoml`), with substantial OpenAI Codex assistance. + +I implement sequential access and local lifetime around PR3078's literal +scalar recipes. I retain PR3090's conditional capacity argument and PR3091's +signed tape arithmetic. Nick Petalas supplies the guarded reversible Boolean +caller in PR3094. I use the inherited unit-step tape model, +including charged writes and erasure; I coordinate that distinction in the +linked claim and do not claim his circuit or whole-caller result. + +## 1. Compiled program and input contract + +Compile a finite catalogue of at most 96 ADD/SCALE literals before numerical +input. Each literal includes its original integer numerator/denominator and +one of the inherited scratch, source-walk or target-walk policies. I retain +negative-denominator spellings. The frozen lowerer limits the reduced +numerator magnitude to 255, the dyadic denominator to 4096 and the recipe +to at most I=32 instructions per real component. I also bound the original +literal integers before compilation. + +The instruction alphabet is signed ADD, COPY, CLEAR, NEG, DOUBLE and HALF +on local ports 0=target, 1=source, 2=initially-zero scratch. Binary operands +must differ. I check the inherited symbolic macro identity and require a +formally zero COPY destination at each compilation prefix. This is the COPY +contract used by PR3090's integer interpreter. + +Supply canonical Count tapes for component width h>=2 and Gaussian count +N>=1, and complete aligned target/source streams at their local origins. +Each Gaussian value occupies h real bits followed by h imaginary bits, +least significant bit first in signed two's-complement notation. Use one +common caller-supplied grid. Write V=2hN for each operand's length. + +ADD receives distinct target/source streams. SCALE has no source operand; +I use logical zero for its unused local source role. The input and protected +output ports are distinct. The caller supplies matching component order and +frame/scale interpretation. Equal lengths alone do not establish alignment. + +On success I preserve borrowed inputs and descriptors, return the complete +target output at its origin, and erase owned work and markers. The caller +consumes that protected output before selecting another compiled recipe or +reusing the engine. I guarantee cleanup for the named arithmetic/contract +errors below on otherwise admitted input. I do not promise rollback for +arbitrary malformed extents or interruption. + +## 2. Execute the literal unit instructions + +I keep the three local words, one work word and one constant-zero word at +exactly h bits. I never normalize signed words as unsigned Counts. I retain +high zero bits and distinguish a logical h-bit zero word from blank storage. + +For ADD and subtraction I use PR3091's encoded-width finite-carry routine, +including its extra sign-bit check. For NEG I apply the same subtraction +routine to the constant-zero word and the target. Its guard excludes the +most-negative input whose negative cannot fit. The routine preserves its +input words and writes the candidate result into the work role. + +For DOUBLE I emit a low zero and the first h-1 source bits. I require the +discarded old sign bit to equal the preceding bit, which becomes the new +sign. This is necessary and sufficient for signed multiplication by two to +fit the original width. For HALF I require the low bit to be zero, emit the +remaining h-1 bits, then append the old sign. This gives exact signed division +by two at the same width and on the same grid. + +COPY first scans its destination and requires h zero bits, then copies h +source bits. CLEAR writes h actual zero bits. For each non-CLEAR instruction +I clear the old target body, copy back the h-bit work result and clear the +work body. I retain active leases during these body resets. Each operation +returns the local word heads to their origins. + +Induction over a fixed recipe gives its exact signed integer microstates +whenever the guards succeed. I preserve literal order. For example, SCALE +(-1)/2 executes NEG before HALF and rejects the most-negative input even +though its final mathematical half-negative would fit. A target walk may +overflow at DOUBLE and later return to range; the earlier failure still +rejects the call. Final endpoint representability cannot replace these +prefix conditions. + +## 3. Interchange the component and instruction loops + +Each unit operation acts within one real component and has no access to a +different record or component. I can therefore execute a complete recipe on +component 0, then component 1, and so on, instead of allocating full packet +registers and traversing the packet once per instruction. + +For each of the 2N components, `ScalarEngine.run` loads its target word and +its source word, or a zero source for SCALE. I initialize the local scratch +and constant-zero word. I execute the compiled recipe, require scratch to +equal the h-bit zero word and check the local source's restoration. I append +the completed target word to the protected output, then erase all five local +word bodies before advancing the encoded component counter. + +The inherited symbolic recipe certificate supplies, for arbitrary t,s, + + ADD: (t,s,0) -> (t+q*s,s,0), + SCALE: (t,0,0) -> (q*t,0,0). + +The unit refinement and induction over components lift these identities to +the full Gaussian packet. The source, target and scratch may have correlated +values; I need no independence assumption. Processing real and imaginary +components at different times preserves the componentwise bounds in PR3090. +No other macro observes this invocation until its complete return. + +This loop interchange permits one h-bit scratch word. Unstarted components' +logical scratch values are zero, and completed components' scratch values +are zero again. A unit instruction never requests another component's +scratch, so I need not materialize an entire zero packet. I still charge +initialization, checks and erasure for each component. + +## 4. Borrowed source and local restoration + +I load every ADD source component into owned register 1. A source walk writes +that private word. It never writes the borrowed source stream. I nevertheless +execute the inherited inverse shifts and check that register 1 returns to +its initial value before disposal. + +After loading a source component the borrowed cursor lies immediately after +it. `restored_source` moves back exactly h cells, compares those h cells with +the local source word, then advances exactly h cells to resume the input. +It never rereads an earlier component or decodes a packet offset. This check +costs O(h), not a scan of the preceding packet prefix. At the end I require +both borrowed streams to be exhausted and rewind them to their origins. + +PR3090's source-write count describes logical port 1. In this implementation +those writes target the private component copy; they do not count writes to +the borrowed physical input. Target-walk recipes retain their logical +read-only-source property, while both policies use the same charged input +and return convention here. + +For nested calls I suspend the parent allocation scope and pass physical +`borrowed_tape`/`borrowed_count` views. I resume the parent scope after return, +copy the protected result into a parent lease, then clear the scalar output +and marker. I test this exchange with live parent Counts and payload leases. + +## 5. Complete cost and storage + +Each unit instruction costs at most K_op*h for a fixed constant K_op, +including arithmetic, result replacement, rewinds and clearing. ADD/NEG +use finite carry; HALF/DOUBLE use fixed-width scans. COPY includes its +zero-destination check; CLEAR includes h writes. Counter initialization +costs O(log h), which the subsequent complete traversal pays. + +Outside the I unit instructions, each component incurs O(h) for input loads, +the private source copy, zero initialization, source/scratch checks, output +append and local disposal. The encoded 2N counter costs O(N+log N) over its +full traversal. Initial/final input and output head restoration costs O(V). +Thus, including I=0, I obtain + + T_macro <= K*(I+1)*V, V=2hN. + +K is uniform in h,N and the admitted data; the compiled catalogue and source +preparation contribute fixed costs outside numerical execution. The code +does not decode h or N into host loop bounds. Its host-side register indices, +instruction lists and policy tags belong to the compiled finite vocabulary. + +For multiple macro invocations I sum `K*(I_j+1)*V_j`. If h and N are common +through PR3090's covered scalar subsequence, I obtain + + O(hN*(U+9992)), U=57710, + +where U counts instructions for both real components. I retain caller +alignment, routing and other excluded operations as additional obligations. +This upper bound does not establish a `7072*hN` time saving. Such a comparison +needs opcode-specific constants, actual widths and identical entry/return +conventions for both policies. PR3078's 9,760 count covers a different interval. + +The code needs at most nine live pool leases: three persistent Count/Counter +roles (`two`, `components`, `remaining`), five word roles, and one temporary +Counter during a word operation. Literal-constructor duplication occurs +before the five word roles exist. I preallocate 128 scratch tapes and one +protected output before numerical input. + +Local occupied contents satisfy + + 5h+O(log N+log h+128)=O(h+log N). + +Add the V-bit protected output and two borrowed V-bit inputs for ADD, or +one borrowed input for SCALE. No pool role holds a complete packet. Fresh +backing has the same local asymptotic bound because pool capacity is fixed. +Reused roles retain their historical maximum extent: erasure blanks cells +without shrinking the simulator's backing arrays. Neither N nor I multiplies +the number of physical roles. I keep simulator counters and Python object +bookkeeping outside the tape program's numerical control. + +## 6. Named rejection and conditional capacity + +`ScalarContractError` subclasses the inherited `CoefficientDomainError`. +The enclosing handler therefore covers inexact HALF, signed overflow, +nonzero required scratch and failed local source restoration. The unit +routine clears its partial work word. The engine rewinds borrowed inputs, +clears its five word roles, closes Counts/Counters, checks the empty pool, +erases markers, closes the invocation and erases any partial protected output +before rethrowing. This costs O(V+h+log N) beyond completed work and preserves +borrowed contents and descriptor heads, including a late-component failure. + +PR3090 proves a conditional D=7, h=P+20 capacity for its actual correlated +prelude/A rows and frame hypotheses, P>=3. Its strict bound is +`4896*128=626688<2^20`. I inherit that argument as a capacity premise and +match its literal unit checkpoints. I do not assign its 84-bit guarantee +to arbitrary 84-bit operands. I do not repeat its normalized-row audit or +claim actual residual adapters, centres or native/recursive interiors here. + +## 7. Source binding and finite evidence + +I authenticate the unchanged PR3090/3091 archives before import, preserving +their nested source notices. The binding checker recompiles both frozen +provider words, checks inherited program hashes, extracts the prelude/A +scalar events, and compares the recipe hashes/counts with PR3090's receipt. +I omit its capacity propagation and frame census. + +Each of the four streams has 9,992 scalar macros and 29 literal templates; +the union has 31. Scratch, source-walk and target-walk counts are respectively +32,391, 28,855 and 28,855 instructions per component. The two providers share +those literal programs but have different canonical frame payloads. Template +equality does not establish identical physical entrance values. + +I execute all 31 templates under all three policies on complete seven-value +84-bit Gaussian packets. A separate integer interpreter checks each recipe +prefix, exact division and signed fit. I also exhaust 4,440 small-width +ADD/SCALE cases and check 612 HALF/DOUBLE cases through width 65. + +The event-109/110 fixture composes the actual literal SCALE(-1/2) and +ADD(+1/2) programs on aligned test packets. I do not reconstruct the original +632-input prelude values in that fixture. Further checks cover later-field +rejection, valid policy retry, nested parent return and eight injected +source/shift/scratch/ownership failures. Finite evidence complements the +quantified refinement; I claim no formal machine or independent human review. diff --git a/research/physical-scalar-stream/README.md b/research/physical-scalar-stream/README.md new file mode 100644 index 0000000000..b2ea16341d --- /dev/null +++ b/research/physical-scalar-stream/README.md @@ -0,0 +1,87 @@ +# Sequential scalar packet access and local return + +I execute inherited scalar recipes on complete aligned Gaussian streams with +encoded widths/counts and a fixed physical tape inventory. I preserve borrowed +operands, initialize and charge logical-zero scratch, check each instruction's +grid/headroom conditions, and verify local source/scratch return before disposal. + +Each instruction acts within one component. I process a full recipe on that +component before advancing, so I need O(h+log N) local scratch for N Gaussian +values of component width h, plus the protected output. I give the complete +bound `O((I+1)V)`, V=2hN, in [PROOF.md](PROOF.md), including loads, copies, +zero writes, counters, rewind and erasure. I preserve the original recipe +order and guards. + +I coordinated this scope with Nick Petalas's +[Boolean coefficient-caller work in PR3094](https://github.com/CrocSwap/integer-mult-bounds/pull/3094). +His work concerns guarded reversible circuits. This package supplies sequential +packet access and local tape ownership around the existing recipes. Actual +family alignment, routing and the complete caller invoice remain separate. + +## Evidence and reproduction + +From the repository root, with Python 3.12: + +```sh +python3.12 scripts/research_package.py --package research/physical-scalar-stream +``` + +I register eight bounded cold commands. I recompile source programs to bind +the literal templates, then check packet execution, every scalar prefix, +named rejection and ownership. I run the prefix and failure checks under +`-O` as well. [RESULT.json](RESULT.json) stores complete typed receipts; +[SOURCES.json](SOURCES.json) authenticates live inputs and frozen archives. + +I passed all eight registered commands on Python 3.12.13/macOS arm64 by +00:20 UTC on October 17, 2026, using the updated main runner. I have not +claimed a hosted CI pass. + +| Check | Coverage | +|---|---| +| Source binding | Two providers and two orientations; 9,992 macros and 29 literal templates each, 31-template union; inherited policy hashes/counts | +| Complete packets | All 31 templates under three policies, seven Gaussian values at 84 bits | +| Prefix oracle | 4,440 small signed ADD/SCALE cases, including intermediate failures | +| Shifts | 612 exact HALF/DOUBLE cases through width 65 | +| Composition | Literal event-109/110 programs on aligned test packets | +| Return | Later-field rejection, policy retry, three live parent Counts and borrowed payloads | +| Fault controls | Eight source, shift, source/scratch-return and protected-output failures | + +The source's 7,072 saving counts logical real instructions. I supply a complete +execution upper bound; I have not measured or proved a `7072*hN` bit-time +reduction. PR3090's D=7, P+20 capacity remains conditional on its actual +correlated input/frame hypotheses. My 84-bit packet fixtures do not establish +those whole-provider hypotheses. + +## Open next questions + +1. Bind this packet interface to an actual aligned caller entry. Start with + one named scalar event and its physical owner descriptors, then account + for gathering and returning its complete streams. Residual adapters, + routing and the later consumer remain blockers to full caller admission. +2. Compare source policies under the same bit-level boundary. Start with + opcode-specific scan counts, equal widths and equal source/scratch + conventions. Logical instruction counts alone cannot price that comparison. + Keep the source/capacity and Boolean-circuit contributions separate. + +I record structured scope and expansion decisions in [TASK.json](TASK.json). +Canonical coordination: +[Discussion2238](https://github.com/CrocSwap/integer-mult-bounds/discussions/2238#discussioncomment-18985356). +I posted the access/lifetime boundary in this +[peer coordination reply](https://github.com/CrocSwap/integer-mult-bounds/discussions/2612#discussioncomment-18985305). + +## Attribution and limits + +Jose Manuel (`jmbarrancoml`), with substantial OpenAI Codex assistance in +mathematics, implementation, source analysis and prose, including analysis +subagents. Apache-2.0 with retained source-specific notices. + +I retain Nick Petalas's PR3078 recipes and PR3090 conditional microstate +capacity, Sagar Thakrar's PR696 dyadic lowering, James Chang's PR1869 ripple +interface and PR3091's encoded signed arithmetic. The frozen archives retain +the native, geometry and physical-tape lineage, including the source credit +to dcharb78, Jeremy Kothe, Marius-Paul Dumitrean, Cinna Davis, DLamdata, +eumemic, icekylinx and Tekalign. + +I have not completed residual adapters, native/recursive children, private +centres or the full caller. I leave the selected frontier unchanged and claim +no new exponent, independent human review or formal proof of this program. diff --git a/research/physical-scalar-stream/RESULT.json b/research/physical-scalar-stream/RESULT.json new file mode 100644 index 0000000000..641f6ddcfa --- /dev/null +++ b/research/physical-scalar-stream/RESULT.json @@ -0,0 +1,8 @@ +{ + "bindings":"3d0002a8897666b754a72da024e1f98d3dcee471b09a3325694cfff85cf53e2c", + "shifts":"0f4da5bf74848ea0aa74fa8828fbd7a4d76f5fa2a4e09ced72d896153d93d376", + "packets":"f5979ae07ff6c6b7e56655c9e0e151e4a1648f460b3efc29c4176f00cc222678", + "prefixes":"ba8bbf73061af95ca360e32827d3f287061d884a51a24b84780818526ab9785e", + "returns":"c46ffb21c144625bf348205be926546ec83b7a3fcc16a38680c42bda9bd770da", + "failures":"696e4e959b278f4dc08687ee3edd8348f8e0ef9e9a940b98c36d6877630f4285" +} diff --git a/research/physical-scalar-stream/SOURCES.json b/research/physical-scalar-stream/SOURCES.json new file mode 100644 index 0000000000..b617c02f82 --- /dev/null +++ b/research/physical-scalar-stream/SOURCES.json @@ -0,0 +1,37 @@ +{ + "schema_version":1, + "base_commit":"18aacb215fc3717b06be8ceb9fca62aeca0d3e99", + "files":[ + {"path":"docs/research/agent-task-catalog.json","usage":"provenance","git_blob":"67f085acd86acd7d4e03922d9cf4b26bca66fed5","sha256":"47b42433f5a85809a3aadd29c2c339da2c6ed728e4f7762df6b88bccb7874cf0"}, + {"path":"certificates/selected-result.json","usage":"input","git_blob":"b1fea0c94436b236cc2b7d41a7be032811b94c81","sha256":"bb2eaa58647b353f88d0aec2eafb9d30df1be53589231b23e12ceef3e4bad129"}, + {"path":"notes/compact-control-layout.tex","usage":"input","git_blob":"16f4d233471a7d189163ae7e7902becadecbba64","sha256":"2bc28e50f3eb092195294cafa81213e520f6d42e7935e9905ad8a6199e2a7c87"}, + {"path":"notes/compact-control-movement.tex","usage":"input","git_blob":"06b6a9ef24245ac7b724c53a204635415b402357","sha256":"b963c3d2f4e1b7059aa289bb4b4ac89b688920bcf42f5b20d7698cdef0132cc6"}, + {"path":"research/bit2234-stock-threshold/README.md","usage":"input","git_blob":"ede0d322c477af91d4c2cc33db0fd10958f45eab","sha256":"1e050c9f963421d751d9208092f9a15321ed77810e03912df8eb5eb56bbb06e7"}, + {"path":"research/community-hyperplane599-audit/pr589/bit589/v9/hosted/GLOBAL-TEMPLATE.json.gz","usage":"input","git_blob":"9eafb8776cbf78c72124f833534469ddfa5e98ec","sha256":"0357b7cfbd7c29b4983982baf153c8a9f1e1e412690cd7fa9fc3d23d7963b20f"}, + {"path":"research/community-hyperplane599-audit/pr589/bit589/v9/nine/GEOMETRY.json","usage":"input","git_blob":"44006542202ca6037533a754f0bcd00549d7e088","sha256":"0058c491d839142aa99ef86a5ec697ce99857632228531512ea3fa74fb24d734"}, + {"path":"research/e8-bit-p111-tuned/tune/EXPECTED.json","usage":"input","git_blob":"e293ddc557742637f9f679f083a1a282d87b1b13","sha256":"b9f0e5ca038abe837b0007c8fe006f366a6f02009244ac57705a8a200e2301f4"}, + {"path":"research/e8-bit-p111-tuned/tune/bitE8mut-p111-tuned.json.gz","usage":"input","git_blob":"85a4499bf9e4911a705d50567a2c2ef6cf23739a","sha256":"e3e301e62bc2b41dbf1ceac0acf3d35824ebeab1848c5a2142d4577b109da52f"}, + {"path":"research/pr589-five-helper-hosting/PROOF.md","usage":"input","git_blob":"bbd3f12b9a32b3ad3cba85a2d5a1b3054214fa02","sha256":"59cae781bfbe1a01ed9e66a8efeeb5a2b995e5ecdf908586b23ecc39f2b8d647"}, + {"path":"research/pr589-five-helper-hosting/verify.py","usage":"input","git_blob":"dbc71f56bb4205ebe378ada1f9f4ea88630d1d39","sha256":"cf90e19ae9991b0698be03d395a8cc29061ecb307eb7fea19adfb2d23c25a367"}, + {"path":"research/recursive-parking-boundary/README.md","usage":"input","git_blob":"251f335ebaccc11d69393ee7aeb5a2e84526d0bb","sha256":"491aa208391ee4c2936510b1a5c5c018dd5509d9a0e88687c72ab8406cd77b18"}, + {"path":"research/selected-bit-local-ring-sweeps/PROOF.md","usage":"input","git_blob":"4330de85dd9862ed15d84ab917887d249753df99","sha256":"846c59440cc99e28bae93ad2af99525bc769de29368080071b8427141215b4f7"}, + {"path":"research/selected-bit-recursive-closure/PROOF.md","usage":"input","git_blob":"6c410cab5713979214a45835091fbeb9ee9b8531","sha256":"74cc8de20f21acb5123fe2d20996fe0925ea6e51b3dec633bd5221fb719b3344"}, + {"path":"research/selected-complex-layer-closure/PROOF.md","usage":"input","git_blob":"d7ec0d101405a5f099f55f6a73e9791731737fd0","sha256":"43feda0342c07a9429699c3a44e8936a3f3fb57ce9b32f38ff3dc06ac887b265"}, + {"path":"upstream/build/sections/02-streams.tex","usage":"input","git_blob":"088fceea1867abc76271d7efe7532b779fee9039","sha256":"606c80db61cad13aa0c3b6060dc4b88dbbe7ac60cdd831aa93f28d908fd09dab"} + ], + "archives":[ + {"path":"inputs/pr3091.tar","head":"d546815f4b116a79bd0ecec6661d2b2b3de29377","source_path":"research/physical-gaussian-leaf","git_tree":"26a4dbca8932c68e45ec927d4a0871a3e93d8d9b","sha256":"745e3dcf93e44d0f6972b50326d6be907fb7dbf80b93dc71bad26df8c40f4fb0"}, + {"path":"inputs/pr3090.tar","head":"47a2bcec53667f490df6d40550e14a8ae465cba4","source_path":"research/rank7-coefficient-capacity","git_tree":"1ab3f1722e7a255117dcc2b94e54d26c7015d1b3","sha256":"b76cd97a4dbc07aa0662b38b6dda726e0dfe8a231dd103f569559fb962768c20"} + ], + "predecessors":[ + {"pr":3090,"head":"47a2bcec53667f490df6d40550e14a8ae465cba4","credit":"Nick Petalas: actual correlated coefficient microstates and conditional D7/P+20 capacity; full native/geometry/owner attribution remains in the unchanged archive."}, + {"pr":3078,"head":"3da2ea9729f70b074713a5d0f69f0bdab32f2b47","credit":"Nick Petalas: inherited scratch/source-walk/target-walk recipes, exact symbolic identities and logical instruction counts."}, + {"pr":696,"head":"5a3f983715027c4fd83f50bc9001d4b18463bed1","credit":"Sagar Thakrar: earlier selected dyadic lowering, exact rational interpretation and source/private restoration."}, + {"pr":1869,"head":"65ab016b4a464e3f5e2dd26c1bb0ae477e1ebce8","credit":"James Chang/jamesyc: finite ripple addition with supplied tracks; encoded layout/allocation remain separate in that source."}, + {"pr":3091,"head":"d546815f4b116a79bd0ecec6661d2b2b3de29377","credit":"Jose Manuel: encoded signed Gaussian arithmetic and fixed tape framework, retaining PR3087/3055/2899/C0 sources and their complete notices."}, + {"pr":3094,"head":"b7a761ce2d6198509adb4b09ebf22b5b17ea2f55","credit":"Nick Petalas: complementary guarded reversible Boolean coefficient caller; I coordinated the distinct sequential-access scope and import no circuit code from this package."} + ], + "authentication":"I authenticate both exact archives and the 15 transitive live tape-source inputs before execution. I activate the pinned physical framework through scalar_sources.py and import the unchanged lowerer under a separate module name. Through check_bindings.py I check PR3090's 20 internal vendor pins, compile both providers in fresh temporary directories, and bind the literal templates/hashes. I leave normalized-row capacity and frame-census work outside this replay.", + "coordination":"I separated this Count-driven sequential packet/lifetime scope from the active Boolean caller at2612#18984751 in reply2612#18985305. The canonical claim is2238#18985356.", + "attribution":"Jose Manuel (jmbarrancoml), with substantial OpenAI Codex assistance including analysis subagents. Apache-2.0 with retained source notices. I preserve prior recipes, capacity, arithmetic and physical-tape credit and claim no independent human or formal verification." +} diff --git a/research/physical-scalar-stream/TASK.json b/research/physical-scalar-stream/TASK.json new file mode 100644 index 0000000000..db9dddfa2e --- /dev/null +++ b/research/physical-scalar-stream/TASK.json @@ -0,0 +1,48 @@ +{ + "schema_version":1, + "task_id":"uniform-transfer-audit", + "priority_revision":6, + "base_commit":"18aacb215fc3717b06be8ceb9fca62aeca0d3e99", + "original_card":{ + "id":"uniform-transfer-audit", + "question":"Can one exact all-size/compiler, precision, hosting or restoration implication be proved or falsified?", + "starting_points":["certificates/selected-result.json","docs/audit.md"], + "methods":["Prove one missing implication with explicit quantified hypotheses.","Find an exact counterexample at the claimed interface boundary."], + "acceptance_gate":"Identify the proposition and what would change downstream; do not equate a finite replay with a universal proof.", + "first_step":{"command":["python3","-B","scripts/research_baseline.py"],"expected":"PASS_RESEARCH_BASELINE_BINDINGS_ONLY","inspect":"Read the selected review scope and choose one exact all-size or precision implication.","scope":"Positive control / source-bound orientation only; this is not a new construction or full cold replay."}, + "first_experiment":"Write its quantified inputs and conclusion; find a missing hypothesis or construct a minimal exact adversarial instance.", + "bottleneck_link":"Finite supplier improvements are useful only under the retained transfer obligations.", + "allowed_variations":["Choose one tape, precision, hosting or restoration lemma."], + "scope_change_triggers":["Replacing a quantified obligation with another finite smoke test."], + "overlap_terms":["uniform transfer","all-size","precision"] + }, + "scope_status":"refined", + "actual_scope":"Execute inherited scalar recipes over complete aligned Gaussian packets with encoded widths/counts, fixed local word roles, paid logical-zero scratch, preserved borrowed input and checked source/scratch return.", + "scope_change_reason":"PR3090 supplies actual coefficient microstates and conditional capacity; the active Boolean-caller scope became PR3094. I coordinated and implemented the distinct sequential packet-access and tape-ownership boundary, preserving the inherited recipes and their instruction counts.", + "bottleneck_link":"A physical caller needs paid component access and scratch lifetime around its coefficient arithmetic. This package supplies that local interface while leaving actual alignment, routing and the complete caller invoice open.", + "stop_rule":"Require exact literal-prefix semantics, complete packet traversal, charged zero initialization and source/scratch return, fixed roles, named-error cleanup and a complete O((I+1)V) bound. Stop at a failed arithmetic, access or cost implication. Do not repeat active capacity audits or claim logical instruction savings as bit-time savings.", + "outcome":"completed", + "evidence":"I passed all eight registered cold commands on Python3.12.13/macOS arm64 by00:20UTC on October17,2026, using the updated main runner. Source compilation binds31literal templates across four streams; all93template-policy packets at84bits agree with integer prefixes;4440small signed cases and612shift cases cover valid and rejected arithmetic. Later-field rejection, policy reuse, nested parent handoff and eight fault controls pass. Prefix/failure checks also passed with assertions disabled. PROOF.md gives the quantified endpoint, loop-interchange, complete cost and local-space arguments. I claim no hosted CI, independent human or formal-machine pass.", + "author":"Jose Manuel (jmbarrancoml)", + "ai_assistance":"Substantial OpenAI Codex assistance in mathematics, implementation, source analysis and prose, including analysis subagents. I claim no independent human or proof-assistant verification of the new program.", + "discussion":"https://github.com/CrocSwap/integer-mult-bounds/discussions/2238#discussioncomment-18985356", + "coordination":"I posted the distinct access/lifetime boundary under the active Boolean caller at2612#18985305. I rechecked it at00:01 and found no response. The final scope preserves PR3094's guarded-circuit contribution and excludes its all9992-macro physical-circuit claim.", + "freshness":{ + "canonical_main":"18aacb215fc3717b06be8ceb9fca62aeca0d3e99", + "upstream_checked_utc":"2026-10-17T00:16Z", + "overlap_checked_utc":"2026-10-17T00:13:41Z", + "coverage":"I checked current2612/2253 and hub1166, older exact arithmetic interfaces, and all updated PRs. At00:13:41 the delta contained93 records:4open and89closed. I read complete2238/2612 comments/replies, latest20 hubcomments, exact3090/3091heads and feedback. PR3094 b7a761ce2d6198509adb4b09ebf22b5b17ea2f55 completed the separate Boolean caller; PR3092 764123a9e18c9a838aee917af7657aa639804680 corroborated capacity arithmetic. I found no objection or competing Count-driven packet-access claim in that coverage.", + "history":"I began from d8e0f83f00191df62174b641e9fff055c357f641. Before publication I fetched and fast-forwarded the working branch to18aacb215fc3717b06be8ceb9fca62aeca0d3e99. Guidance, priority6 and selection were unchanged; the shared replay runner gained stricter input-path validation. I preserve the frozen source archives and source pins." + }, + "expansion_decision":{ + "proved_costs":"I retain PR3078's symbolic recipe identities and PR3090's conditional prefix capacity, then refine the literal units and component loop on encoded sequential tapes. I charge private source copies, zero writes, restoration checks and disposal.", + "constructive_upper_bound":"I obtain T_macro<=K(I+1)V, V=2hN, with nine live leases within128preallocated scratch tapes. Local scratch is O(h+log N), plus protected output and borrowed streams; retained backing uses each role's historical maximum.", + "unknowns":"Actual frame/order alignment, residual adapters, native/recursive child interiors, private centres and the complete caller invoice remain outside this interface. The7072 logical instruction saving does not establish a bit-time saving.", + "comparison":"PR3094 supplies guarded reversible circuits; this contribution supplies sequential access and local tape lifetime. I preserve PR696/1869 arithmetic and PR3078/3090 recipe/capacity attribution and do not search for more coefficients.", + "decision":"Finish this named packet interface. A next round needs one actual owner/alignment boundary or an opcode-priced policy comparison under equal widths and entry/return conventions." + }, + "open_questions":[ + {"question":"Bind this packet interface to an actual aligned caller entry.","why_it_matters":"A scalar endpoint alone does not supply family gathering, frame alignment and the later consumer.","first_step":"Choose one named scalar event with physical owner descriptors and price gathering and returning its complete input streams.","blocked_by":"Residual adapters, routing and complete caller ownership remain separate."}, + {"question":"Compare source policies under the same bit-level boundary.","why_it_matters":"Logical instruction counts omit opcode-specific scan and ownership costs.","first_step":"Fix equal widths, operand alignment and source/scratch conventions, then count complete opcode scans and boundary costs for both policies.","blocked_by":"This package establishes a complete upper bound, not a uniform7072hN time reduction."} + ] +} diff --git a/research/physical-scalar-stream/VERIFY.json b/research/physical-scalar-stream/VERIFY.json new file mode 100644 index 0000000000..3878854681 --- /dev/null +++ b/research/physical-scalar-stream/VERIFY.json @@ -0,0 +1,33 @@ +{ + "schema_version":1, + "status":"ready", + "python":"3.12", + "requirements":[], + "inputs":[ + "certificates/selected-result.json", + "notes/compact-control-layout.tex", + "notes/compact-control-movement.tex", + "research/bit2234-stock-threshold/README.md", + "research/community-hyperplane599-audit/pr589/bit589/v9/hosted/GLOBAL-TEMPLATE.json.gz", + "research/community-hyperplane599-audit/pr589/bit589/v9/nine/GEOMETRY.json", + "research/e8-bit-p111-tuned/tune/EXPECTED.json", + "research/e8-bit-p111-tuned/tune/bitE8mut-p111-tuned.json.gz", + "research/pr589-five-helper-hosting/PROOF.md", + "research/pr589-five-helper-hosting/verify.py", + "research/recursive-parking-boundary/README.md", + "research/selected-bit-local-ring-sweeps/PROOF.md", + "research/selected-bit-recursive-closure/PROOF.md", + "research/selected-complex-layer-closure/PROOF.md", + "upstream/build/sections/02-streams.tex" + ], + "commands":[ + {"argv":["{python}","-I","-B","{package}/verify.py","--suite","bindings"],"timeout_seconds":420,"checks":"Fresh source compilation for two providers/four streams, complete literal template union and inherited policy hashes/counts"}, + {"argv":["{python}","-I","-B","{package}/verify.py","--suite","shifts"],"timeout_seconds":30,"checks":"612 signed HALF/DOUBLE cases, exact parity and overflow, widths through65"}, + {"argv":["{python}","-I","-B","{package}/verify.py","--suite","packets"],"timeout_seconds":90,"checks":"31literal templates under3policies on complete84-bit Gaussian packets and literal109/110 composition"}, + {"argv":["{python}","-I","-B","{package}/verify.py","--suite","prefixes"],"timeout_seconds":180,"checks":"4440 small signed cases against an independent integer recipe-prefix oracle"}, + {"argv":["{python}","-I","-O","-B","{package}/verify.py","--suite","prefixes"],"timeout_seconds":180,"checks":"Same complete scalar prefix receipt with assertions disabled"}, + {"argv":["{python}","-I","-B","{package}/verify.py","--suite","returns"],"timeout_seconds":30,"checks":"Later-field rejection, valid policy retry and nested parent handoff with live Counts/payloads"}, + {"argv":["{python}","-I","-B","{package}/verify.py","--suite","failures"],"timeout_seconds":60,"checks":"Eight archive, shift, source/scratch restoration and protected-output controls"}, + {"argv":["{python}","-I","-O","-B","{package}/verify.py","--suite","failures"],"timeout_seconds":60,"checks":"Same eight failure controls with assertions disabled"} + ] +} diff --git a/research/physical-scalar-stream/check_bindings.py b/research/physical-scalar-stream/check_bindings.py new file mode 100644 index 0000000000..41482dc5ac --- /dev/null +++ b/research/physical-scalar-stream/check_bindings.py @@ -0,0 +1,98 @@ +"""Recompile literal source templates without repeating the capacity audit.""" +from collections import Counter +from hashlib import sha256 +from pathlib import Path +import json +import sys +import tempfile + +HERE = Path(__file__).resolve().parent +sys.path.insert(0,str(HERE)) +import scalar_sources +from literal_templates import TEMPLATES,POLICIES + + +def need(condition,message): + if not condition: + raise ValueError(message) + + +def canonical(value): + return json.dumps(value,sort_keys=True,separators=(",",":")).encode() + + +def run(): + need(not any(name in sys.modules for name in ("replay_parent","contractions","frames","tariff","words")), + "cold provider binding namespace") + package = scalar_sources.exports()["pr3090"] + records = json.loads((package/"VENDOR.json").read_text())["files"] + for row in records: + need(sha256((package/row["path"]).read_bytes()).hexdigest() == row["sha256"], "frozen coefficient provider bytes") + lower = scalar_sources.module("binding_lower",package/"vendor/lowering/lower.py") + sys.path.insert(0,str(package/"vendor/native/vendor/parent")) + import replay_parent as parent + from contractions import produce + from tariff import produce as tariff_parent + parent.check_pins() + expected = json.loads((package/"RESULT.json").read_text()) + inherited = json.loads((package/"vendor/native/RESULT.json").read_text()) + union,results = set(),{} + with tempfile.TemporaryDirectory(prefix="scalar-source-binding-") as directory: + for provider in ("base","extra"): + raw = parent.read(package/f"vendor/native/vendor/parent/vendor/WORD-{provider}.json.gz") + word = produce(tariff_parent(raw),parent.read(package/"vendor/native/vendor/parent/EDITS.json")) + programs,checks = parent.compile_word(word,Path(directory)/provider) + need(checks == inherited["providers"][provider]["native_checks"], "inherited complete compiler binding") + need(sha256(canonical(word)).hexdigest() == expected["providers"][provider]["word_sha256"], "produced provider word binding") + for direction,events in programs.items(): + counts,templates = Counter(),{} + digests = {policy:sha256() for policy in POLICIES} + totals = {policy:dict(instructions=0,source_writes=0,scratch_macros=0,maximum_length=0) for policy in POLICIES} + active,cut = False,None + for index,event in enumerate(events): + if event[0] == "phase": + if event[1] == "A": + active = True + elif active: + need(event[1] == "centers", "complete prelude/A binding endpoint") + cut = index + break + continue + if event[0] != "scalar": + continue + gate = event[1] + key = (gate[0],*gate[-2:]) + need(key[0] in ("add","scale"), "literal prelude/A scalar kind") + counts[key] += 1 + if key not in templates: + templates[key] = {policy:lower.certify(*key,policy=policy) for policy in POLICIES} + for policy,recipe in templates[key].items(): + row = totals[policy] + row["instructions"] += len(recipe) + row["source_writes"] += sum(op[1] == 1 for op in recipe) + row["scratch_macros"] += int(any(op[1] == 2 for op in recipe)) + row["maximum_length"] = max(row["maximum_length"],len(recipe)) + digests[policy].update(canonical([index,recipe])) + need(cut == 11743 and sum(counts.values()) == 9992 and len(templates) == 29, + "actual complete literal macro inventory") + expected_stream = expected["providers"][provider]["streams"][direction] + for policy,row in totals.items(): + prior = expected_stream["policies"][policy] + need((row["instructions"],row["source_writes"],row["scratch_macros"],digests[policy].hexdigest()) == + (prior["single_component_instructions"],prior["source_writes"],prior["scratch_macros"],prior["recipe_sha256"]), + "literal policy counts and recipe hashes match source receipt") + union.update(templates) + inventory = [[*key,count] for key,count in sorted(counts.items())] + results[provider+"/"+direction] = dict(events=len(events),stop=cut,macros=sum(counts.values()), + templates=len(templates),inventory_sha256=sha256(canonical(inventory)).hexdigest(), + program_sha256=sha256(canonical(events)).hexdigest(), + policies={policy:dict(**totals[policy],sha256=digests[policy].hexdigest()) for policy in POLICIES}, + first_nonunit=events[109:111]) + need(tuple(sorted(union)) == TEMPLATES, "complete literal template union including denominator spellings") + return dict(streams=results,union=len(union),union_sha256=sha256(canonical(sorted(union))).hexdigest(), + scope="Bounded source compilation and literal template binding only; no new normalized-row/capacity/frame audit or physical full-caller claim") + + +if __name__ == "__main__": + print(json.dumps(run(),sort_keys=True,indent=2)) + print("PASS_SCALAR_SOURCE_BINDINGS") diff --git a/research/physical-scalar-stream/check_failures.py b/research/physical-scalar-stream/check_failures.py new file mode 100644 index 0000000000..3e9a7d3aae --- /dev/null +++ b/research/physical-scalar-stream/check_failures.py @@ -0,0 +1,103 @@ +"""Reject source, shift, local-lifetime and protected-return perturbations.""" +from pathlib import Path +from types import ModuleType +import importlib.util +import json +import sys +from unittest.mock import patch + +HERE = Path(__file__).resolve().parent +sys.path.insert(0,str(HERE)) + + +def rejected(label,call,message): + try: + call() + except ValueError as error: + if message not in str(error): + raise ValueError("unexpected scalar control failure for "+label+": "+str(error)) from error + else: + raise ValueError("accepted scalar fault: "+label) + return label + + +def fresh_sources(): + spec = importlib.util.spec_from_file_location("failure_scalar_sources",HERE/"scalar_sources.py") + result = importlib.util.module_from_spec(spec) + spec.loader.exec_module(result) + return result + + +def run(): + controls = [] + source = fresh_sources() + with patch.dict(sys.modules,{"words":ModuleType("words")}): + controls.append(rejected("warm physical namespace",source.activate,"cold physical scalar namespace")) + source = fresh_sources() + with patch.dict(source.ARCHIVES,{"pr3090":"0"*64}): + controls.append(rejected("changed recipe source archive",source.exports,"immutable scalar source archive")) + + import check_shifts + import check_packets + import scalar_engine + import scalar_words + from scalar_test_support import body + from session import erase_marker,initialize_marker + from signed_linear import CoefficientDomainError + from words import need + + actual_shift = scalar_words.shifted + def suppress(category): + def faulty(*args,**kwargs): + try: + return actual_shift(*args,**kwargs) + except CoefficientDomainError as error: + if category not in str(error): + raise + return faulty + for category in ("inexact","headroom"): + with patch.object(check_shifts,"shifted",suppress(category)): + controls.append(rejected("suppress shift "+category,check_shifts.run,"exact signed shift value")) + + actual_instruction = scalar_engine.instruction + def omit_clear(registers,operation,*args): + if operation == ("clear",2): + return + return actual_instruction(registers,operation,*args) + with patch.object(scalar_engine,"instruction",omit_clear): + controls.append(rejected("omit local scratch CLEAR",check_packets.run,"scalar logical scratch is not zero")) + + def omit_restore(registers,operation,*args): + if operation == ("double",1): + return + return actual_instruction(registers,operation,*args) + with patch.object(scalar_engine,"instruction",omit_restore): + controls.append(rejected("omit source-walk inverse shifts",check_packets.run,"scalar source component not restored")) + + actual_zero,calls = scalar_engine.zero_word,0 + def dirty_initial_zero(tape,width): + nonlocal calls + actual_zero(tape,width) + if calls == 0: + tape.write(1) + calls += 1 + with patch.object(scalar_engine,"zero_word",dirty_initial_zero): + controls.append(rejected("COPY into nonzero local scratch",check_packets.run,"scalar logical scratch is not zero")) + + key = ("scale",1,1,"scratch") + engine = scalar_engine.ScalarEngine((key,)) + initialize_marker(engine.output) + engine.output.append(1) + engine.output.rewind() + saved = body(engine.output) + controls.append(rejected("select with unconsumed return",lambda:engine.select(key),"closed consumed scalar selection boundary")) + need(body(engine.output) == saved and engine.output.head == 1 and engine.closed, + "scalar selection rejection preserves protected output") + engine.output.clear() + erase_marker(engine.output) + return dict(controls=controls,rejected=len(controls),scope="Eight archive, shift, source/scratch return and protected-output failures; no arbitrary-interruption rollback claim") + + +if __name__ == "__main__": + print(json.dumps(run(),sort_keys=True,indent=2)) + print("PASS_PHYSICAL_SCALAR_FAILURES") diff --git a/research/physical-scalar-stream/check_packets.py b/research/physical-scalar-stream/check_packets.py new file mode 100644 index 0000000000..b3d664a901 --- /dev/null +++ b/research/physical-scalar-stream/check_packets.py @@ -0,0 +1,90 @@ +"""Complete packets through every compiled literal and policy.""" +from hashlib import sha256 +from pathlib import Path +import json +import sys +from unittest.mock import patch + +sys.path.insert(0,str(Path(__file__).resolve().parent)) +import scalar_sources +lower = scalar_sources.activate() +from cardinal_counts import Count +from check_support import no_decode +from compact_counts import append_bits +from records import Tape +from scalar_engine import ScalarEngine +from scalar_test_support import (POLICIES,TEMPLATES,body,closed_work,fill,packet, + prefix_oracle,snapshot) +from session import erase_marker +from words import need + + +def forbidden(*_args,**_kwargs): + raise ValueError("indexed recipe interpreter reached physical scalar execution") + + +def run(): + literals = tuple((*template,policy) for template in TEMPLATES for policy in POLICIES) + engine = ScalarEngine(literals) + width,count = Count.literal(84),Count.literal(7) + left,right,middle = Tape(),Tape(),Tape() + left_values = [(((index*31)%17)-8)*(1<<37) for index in range(14)] + right_values = [(((index*7)%19)-9)*(1<<35) for index in range(14)] + left_raw,right_raw = packet(left_values,84),packet(right_values,84) + saved = snapshot((width,count)) + digest,cases = sha256(),0 + for literal in literals: + engine.select(literal) + recipe = engine.recipe + expected = [] + for x,y in zip(left_values,right_values): + value,error = prefix_oracle(recipe,x,y if recipe.kind == "add" else 0,84) + need(error is None, "admitted complete scalar fixture") + expected.append(value) + fill(left,left_raw) + fill(right,right_raw) + with no_decode(),patch.multiple(lower,execute=forbidden,certify=forbidden,lower=forbidden): + returned = engine.run(left,right if recipe.kind == "add" else None,width,count) + need(body(returned) == packet(expected,84), "complete physical scalar packet endpoint") + need(body(left) == left_raw and body(right) == right_raw and left.head == right.head == returned.head == 1 and + snapshot((width,count)) == saved, "scalar packet borrowed inputs and descriptors") + closed_work(engine) + digest.update(json.dumps(literal,separators=(",",":")).encode()+body(returned)) + returned.clear() + erase_marker(returned) + cases += 1 + + pipeline = [] + for policy in POLICIES: + fill(left,left_raw) + fill(right,right_raw) + engine.select(("scale",-1,2,policy)) + with no_decode(): + returned = engine.run(left,None,width,count) + append_bits(returned,middle) + middle.rewind() + returned.clear() + erase_marker(returned) + engine.select(("add",1,2,policy)) + with no_decode(): + returned = engine.run(middle,right,width,count) + expected = packet([(y-x)//2 for x,y in zip(left_values,right_values)],84) + need(body(returned) == expected and body(left) == left_raw and body(right) == right_raw, + "literal forward109/110 two-macro packet composition") + closed_work(engine) + pipeline.append(sha256(expected).hexdigest()) + returned.clear() + erase_marker(returned) + middle.clear() + for tape in (left,right,middle): + tape.clear() + width.close() + count.close() + return dict(literal_templates=31,policy_cases=cases,component_bits=84,gaussians=7,peak=engine.pool.peak, + sha256=digest.hexdigest(),event109_110_sha256=pipeline, + scope="Complete aligned packets for31literal templates and3policies; literal109/110 composition, not reconstructed632-input prelude values") + + +if __name__ == "__main__": + print(json.dumps(run(),sort_keys=True,indent=2)) + print("PASS_PHYSICAL_SCALAR_PACKETS") diff --git a/research/physical-scalar-stream/check_prefixes.py b/research/physical-scalar-stream/check_prefixes.py new file mode 100644 index 0000000000..6e83404ef4 --- /dev/null +++ b/research/physical-scalar-stream/check_prefixes.py @@ -0,0 +1,69 @@ +"""Exhaust small signed packets against every literal instruction prefix.""" +from hashlib import sha256 +from pathlib import Path +import json +import sys + +sys.path.insert(0,str(Path(__file__).resolve().parent)) +import scalar_sources +scalar_sources.activate() +from cardinal_counts import Count +from check_support import no_decode +from records import Tape +from scalar_engine import ScalarEngine +from scalar_test_support import (POLICIES,TEMPLATES,body,closed_work,fill,packet, + prefix_oracle,snapshot) +from session import erase_marker +from signed_linear import CoefficientDomainError +from words import need + + +def run(): + literals = tuple((*template,policy) for template in TEMPLATES for policy in POLICIES) + engine = ScalarEngine(literals) + width,count = Count.literal(3),Count.literal(1) + left,right = Tape(),Tape() + saved = snapshot((width,count)) + digest,counts = sha256(),dict(valid=0,inexact=0,headroom=0) + for literal in literals: + engine.select(literal) + recipe = engine.recipe + for x in range(-4,4): + for y in range(-4,4) if recipe.kind == "add" else (0,): + xs = (x,-x if x != -4 else x) + ys = (y,-y if y != -4 else y) + left_raw,right_raw = packet(xs,3),packet(ys,3) + expected,error = [],None + for a,b in zip(xs,ys): + value,error = prefix_oracle(recipe,a,b,3) + if error is not None: + break + expected.append(value) + fill(left,left_raw) + fill(right,right_raw) + with no_decode(): + try: + returned = engine.run(left,right if recipe.kind == "add" else None,width,count) + except CoefficientDomainError as failure: + need(error is not None and error in str(failure), "exact literal scalar prefix rejection") + closed_work(engine,True) + else: + need(error is None and body(returned) == packet(expected,3), "exact literal scalar prefix endpoint") + closed_work(engine) + returned.clear() + erase_marker(returned) + need(body(left) == left_raw and body(right) == right_raw and left.head == right.head == 1 and + snapshot((width,count)) == saved, "prefix guard preserves complete borrowed data") + counts[error or "valid"] += 1 + digest.update(json.dumps((literal,x,y,expected,error),separators=(",",":")).encode()) + left.clear() + right.clear() + width.close() + count.close() + return dict(counts=counts,cases=sum(counts.values()),peak=engine.pool.peak,sha256=digest.hexdigest(), + scope="All signed3-bit component pairs for ADD and all3-bit SCALE targets across31literals/3policies; compare every recipe prefix") + + +if __name__ == "__main__": + print(json.dumps(run(),sort_keys=True,indent=2)) + print("PASS_PHYSICAL_SCALAR_PREFIXES") diff --git a/research/physical-scalar-stream/check_returns.py b/research/physical-scalar-stream/check_returns.py new file mode 100644 index 0000000000..85c70d5743 --- /dev/null +++ b/research/physical-scalar-stream/check_returns.py @@ -0,0 +1,116 @@ +"""Later-field rejection, policy reuse and a live parent handoff.""" +from pathlib import Path +import json +import sys + +sys.path.insert(0,str(Path(__file__).resolve().parent)) +import scalar_sources +scalar_sources.activate() +from cardinal_counts import Count +from check_support import no_decode +from compact_counts import append_bits +from records import Tape +from scalar_engine import ScalarEngine +from scalar_test_support import body,closed_work,fill,packet,snapshot +from scratch_pool import ScratchPool +from session import (OuterScope,borrowed_count,borrowed_tape,erase_marker, + sealed_constructors) +from signed_linear import CoefficientDomainError +from words import BLANK,need + + +def handoff(): + engine = ScalarEngine((("scale",-1,2,"scratch"),("add",1,2,"source_walk"))) + parent = ScratchPool(64) + scope = OuterScope(parent) + xs,ys = (64,-64,128,-128),(128,64,-64,-128) + xraw,yraw = packet(xs,9),packet(ys,9) + with no_decode(),sealed_constructors(),scope.installed(): + width,count,sentinel = Count.literal(9),Count.literal(2),Count.literal(12345) + saved = snapshot((width,count,sentinel)) + left,right = parent.acquire(),parent.acquire() + for tape,raw in ((left,xraw),(right,yraw)): + for bit in raw: + tape.append(bit) + tape.rewind() + with scope.suspended(): + returned = engine.run(borrowed_tape(left),None,borrowed_count(width),borrowed_count(count)) + middle = parent.acquire() + append_bits(returned,middle) + middle.rewind() + returned.clear() + erase_marker(returned) + closed_work(engine,True) + engine.select(("add",1,2,"source_walk")) + with scope.suspended(): + returned = engine.run(borrowed_tape(middle),borrowed_tape(right),borrowed_count(width),borrowed_count(count)) + result = parent.acquire() + append_bits(returned,result) + result.rewind() + returned.clear() + erase_marker(returned) + need(body(result) == packet([(y-x)//2 for x,y in zip(xs,ys)],9), "nested scalar macro endpoint") + need(body(left) == xraw and body(right) == yraw and snapshot((width,count,sentinel)) == saved, + "scalar handoff preserves live parent objects") + closed_work(engine,True) + for tape in (left,right,middle,result): + tape.clear() + for value in (width,count,sentinel): + value.close() + parent.empty() + for tape in parent.tapes: + erase_marker(tape) + need(all(all(bit == BLANK for bit in tape.cells) for tape in parent.tapes), "erased scalar caller work") + return dict(parent_peak=parent.peak,scalar_peak=engine.pool.peak,live_parent_counts=3) + + +def run(): + literals = (("scale",-1,2,"scratch"),("scale",1,2,"scratch"), + ("add",1,2,"target_walk"),("add",1,2,"source_walk"),("add",3,4,"source_walk")) + engine = ScalarEngine(literals) + width,count = Count.literal(3),Count.literal(2) + saved = snapshot((width,count)) + left,right = Tape(),Tape() + cases = ((literals[0],[0,0,0,-4],None,"headroom"), + (literals[1],[0,0,0,3],None,"inexact"), + (literals[2],[0,0,0,2],[0,0,0,0],"headroom"), + (literals[4],[0,0,0,0],[0,0,0,2],"inexact")) + for literal,xs,ys,category in cases: + xraw,yraw = packet(xs,3),None if ys is None else packet(ys,3) + fill(left,xraw) + if yraw is not None: + fill(right,yraw) + engine.select(literal) + with no_decode(): + try: + engine.run(left,right if ys is not None else None,width,count) + except CoefficientDomainError as error: + need(category in str(error), "named later-field scalar rejection") + else: + raise ValueError("invalid later scalar prefix accepted") + need(body(left) == xraw and left.head == 1 and + (yraw is None or (body(right) == yraw and right.head == 1)) and snapshot((width,count)) == saved, + "scalar rejection preserves original complete operands") + closed_work(engine,True) + # The previous target-walk fixture has a valid endpoint but an invalid + # doubling prefix. The source-walk policy accepts those same operands. + fill(left,packet([0,0,0,2],3)) + fill(right,packet([0,0,0,0],3)) + engine.select(literals[3]) + with no_decode(): + returned = engine.run(left,right,width,count) + need(body(returned) == packet([0,0,0,2],3), "valid policy retry after scalar rejection") + closed_work(engine) + returned.clear() + erase_marker(returned) + left.clear() + right.clear() + width.close() + count.close() + return dict(later_rejections=len(cases),valid_policy_retry=True,peak=engine.pool.peak,handoff=handoff(), + scope="Named later-field prefix rejection, input/descriptor preservation, closed output and nested parent reuse") + + +if __name__ == "__main__": + print(json.dumps(run(),sort_keys=True,indent=2)) + print("PASS_PHYSICAL_SCALAR_RETURNS") diff --git a/research/physical-scalar-stream/check_shifts.py b/research/physical-scalar-stream/check_shifts.py new file mode 100644 index 0000000000..937f77de1c --- /dev/null +++ b/research/physical-scalar-stream/check_shifts.py @@ -0,0 +1,57 @@ +"""Exact signed HALF/DOUBLE transducers, including wider-word boundaries.""" +from hashlib import sha256 +from pathlib import Path +import json +import sys + +sys.path.insert(0,str(Path(__file__).resolve().parent)) +import scalar_sources +scalar_sources.activate() +from cardinal_counts import Count +from check_support import no_decode +from records import Tape +from scalar_test_support import body,encode,snapshot +from scalar_words import shifted +from scratch_pool import ScratchPool +from session import sealed_constructors +from signed_linear import CoefficientDomainError +from words import need + + +def run(): + source,output,pool = Tape(),Tape(),ScratchPool(32) + counts,digest = dict(valid=0,inexact=0,headroom=0),sha256() + for bits in (2,3,4,8,17,65): + width = Count.literal(bits) + saved = snapshot((width,)) + limit = 1<<(bits-1) + values = range(-limit,limit) if bits <= 8 else (-limit,-limit+1,-limit//2-1,-limit//2,-1,0,1,limit//2-1,limit//2,limit-2,limit-1) + with no_decode(),sealed_constructors(),pool.install(): + for value in values: + raw = encode(value,bits) + for bit in raw: + source.append(bit) + source.rewind() + for double in (False,True): + expected = 2*value if double else value//2 + category = "inexact" if not double and value%2 else "headroom" if not -limit <= expected < limit else "valid" + try: + shifted(source,output,width,double) + except CoefficientDomainError as error: + need(category != "valid" and category in str(error), "exact signed shift rejection") + else: + need(category == "valid" and body(output) == encode(expected,bits), "exact signed shift value") + need(body(source) == raw and source.head == 1 and snapshot((width,)) == saved, + "signed shift preserves borrowed word and width") + counts[category] += 1 + digest.update(json.dumps((bits,value,double,category,expected),separators=(",",":")).encode()) + output.clear() + pool.empty() + source.clear() + width.close() + return dict(counts=counts,peak=pool.peak,sha256=digest.hexdigest(),scope="Exhaust widths2/3/4/8 and17/65 signed boundaries; exact HALF and final DOUBLE fit") + + +if __name__ == "__main__": + print(json.dumps(run(),sort_keys=True,indent=2)) + print("PASS_PHYSICAL_SCALAR_SHIFTS") diff --git a/research/physical-scalar-stream/inputs/pr3090.tar b/research/physical-scalar-stream/inputs/pr3090.tar new file mode 100644 index 0000000000..162fbc3b06 Binary files /dev/null and b/research/physical-scalar-stream/inputs/pr3090.tar differ diff --git a/research/physical-scalar-stream/inputs/pr3091.tar b/research/physical-scalar-stream/inputs/pr3091.tar new file mode 100644 index 0000000000..eafceefa99 Binary files /dev/null and b/research/physical-scalar-stream/inputs/pr3091.tar differ diff --git a/research/physical-scalar-stream/literal_templates.py b/research/physical-scalar-stream/literal_templates.py new file mode 100644 index 0000000000..8d93eb97c7 --- /dev/null +++ b/research/physical-scalar-stream/literal_templates.py @@ -0,0 +1,10 @@ +"""Literal union reconstructed from both frozen prelude/A orientations.""" +TEMPLATES = ( + ("add",-7,4),("add",-7,8),("add",-5,8),("add",-3,2),("add",-3,4),("add",-3,8), + ("add",-2,1),("add",-1,1),("add",-1,2),("add",-1,4),("add",-1,8), + ("add",1,1),("add",1,2),("add",1,4),("add",1,8),("add",2,1), + ("add",3,2),("add",3,4),("add",3,8),("add",5,8),("add",7,4),("add",7,8), + ("scale",-2,1),("scale",-1,1),("scale",-1,2),("scale",1,-2),("scale",1,-1), + ("scale",1,1),("scale",1,2),("scale",2,-1),("scale",2,1), +) +POLICIES = ("scratch","source_walk","target_walk") diff --git a/research/physical-scalar-stream/scalar_engine.py b/research/physical-scalar-stream/scalar_engine.py new file mode 100644 index 0000000000..aea19253f6 --- /dev/null +++ b/research/physical-scalar-stream/scalar_engine.py @@ -0,0 +1,118 @@ +"""One fixed physical word inventory around compiled scalar recipes.""" +import scalar_sources +scalar_sources.activate() +from cardinal_counts import Count,positive +from compact_counts import append_bits,copy_bits +from encoded import compare +from records import Tape +from scalar_recipe import Recipe +from scalar_words import instruction,require_zero,restored_source,zero_word +from scratch_pool import ScratchPool +from session import (OuterScope,borrowed_tape,erase_marker,initialize_marker, + sealed_constructors) +from signed_linear import CoefficientDomainError +from stream import Counter +from words import BLANK,LEFT,need + + +class ScalarEngine: + def __init__(self,literals): + need(type(literals) is tuple and 0 < len(literals) <= 96 and len(set(literals)) == len(literals), + "fixed finite scalar recipe catalogue") + self.recipes = {literal:Recipe(*literal) for literal in literals} + self.recipe = self.recipes[literals[0]] + self.pool = ScratchPool(128) + self.scope = OuterScope(self.pool) + self.output = Tape() + for tape in (*self.pool.tapes,self.output): + erase_marker(tape) + self.closed = True + + def select(self,literal): + need(literal in self.recipes, "scalar selection belongs to compiled catalogue") + need(self.closed and self.output.read() == BLANK and not self.pool.live, + "closed consumed scalar selection boundary") + self.recipe = self.recipes[literal] + + def rearm(self): + need(self.closed and self.output.read() == BLANK, "consume previous scalar output") + self.output.step(-1) + marker = self.output.read() + need(marker in (LEFT,BLANK), "scalar output origin") + if marker == BLANK: + self.output.write(LEFT) + self.output.step(1) + for tape in self.pool.tapes: + initialize_marker(tape) + self.closed = False + + def run(self,target,source,width,gaussians): + positive(width) + positive(gaussians) + left = borrowed_tape(target) + right = None if source is None else borrowed_tape(source) + need((self.recipe.kind == "scale") == (right is None), "compiled scalar operand arity") + need(left is not self.output and right is not self.output and left is not right, + "distinct borrowed scalar operands and return") + self.rearm() + two = components = remaining = None + registers = () + work = zero = None + error = None + with sealed_constructors(),self.scope.installed(): + try: + two = Count.literal(2) + need(compare(width,two) >= 0, "signed scalar component width") + components = Count(gaussians) + components.multiply_small(2) + remaining = Counter(components) + registers = tuple(self.pool.acquire() for _ in range(3)) + work,zero = self.pool.acquire(),self.pool.acquire() + left.rewind() + if right is not None: + right.rewind() + while not remaining.finished: + copy_bits(left,registers[0],width) + registers[0].rewind() + if right is None: + zero_word(registers[1],width) + else: + copy_bits(right,registers[1],width) + registers[1].rewind() + zero_word(registers[2],width) + zero_word(zero,width) + for operation in self.recipe.program: + instruction(registers,operation,width,work,zero) + if right is None: + require_zero(registers[1],width) + else: + restored_source(registers[1],right,width) + require_zero(registers[2],width) + append_bits(registers[0],self.output) + for tape in (*registers,work,zero): + borrowed_tape(tape).clear() + remaining.decrement() + need(left.read() == BLANK and (right is None or right.read() == BLANK), + "complete scalar Gaussian operands") + except CoefficientDomainError as failure: + error = failure + finally: + left.rewind() + if right is not None: + right.rewind() + for tape in (*registers,work,zero): + if tape is not None: + tape.clear() + for value in (two,components,remaining): + if value is not None: + value.close() + self.pool.empty() + for tape in self.pool.tapes: + erase_marker(tape) + self.output.rewind() + self.closed = True + if error is not None: + self.output.clear() + erase_marker(self.output) + raise error + return self.output diff --git a/research/physical-scalar-stream/scalar_recipe.py b/research/physical-scalar-stream/scalar_recipe.py new file mode 100644 index 0000000000..cfb0dda8b6 --- /dev/null +++ b/research/physical-scalar-stream/scalar_recipe.py @@ -0,0 +1,23 @@ +"""Compile bounded inherited recipes before any numerical input.""" +import scalar_sources +lower = scalar_sources.activate() +from fractions import Fraction +from words import need + + +class Recipe: + def __init__(self,kind,numerator,denominator,policy): + need(kind in ("add","scale") and type(numerator) is int and type(denominator) is int and + abs(numerator) <= 4096 and 0 < abs(denominator) <= 4096, + "fixed scalar literal vocabulary") + self.key = kind,numerator,denominator,policy + self.kind,self.coefficient = kind,Fraction(numerator,denominator) + self.program = tuple(tuple(row) for row in lower.certify(kind,numerator,denominator,policy=policy)) + need(len(self.program) <= 32, "bounded compiled scalar recipe") + rows = ((Fraction(1),Fraction(0)),(Fraction(0),Fraction(1)),(Fraction(0),Fraction(0))) + for instruction in self.program: + if instruction[0] == "copy": + need(rows[instruction[1]] == (0,0), "literal COPY destination starts zero") + rows = lower.execute((instruction,),rows) + self.source_writes = any(instruction[1] == 1 for instruction in self.program) + self.uses_scratch = any(instruction[1] == 2 for instruction in self.program) diff --git a/research/physical-scalar-stream/scalar_sources.py b/research/physical-scalar-stream/scalar_sources.py new file mode 100644 index 0000000000..b4fd1ab874 --- /dev/null +++ b/research/physical-scalar-stream/scalar_sources.py @@ -0,0 +1,66 @@ +"""Authenticate physical tape primitives and inherited scalar recipe sources.""" +from hashlib import sha256 +import importlib.util +from pathlib import Path, PurePosixPath +import sys +import tarfile +import tempfile + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[1] +ARCHIVES = { + "pr3091":"745e3dcf93e44d0f6972b50326d6be907fb7dbf80b93dc71bad26df8c40f4fb0", + "pr3090":"b76cd97a4dbc07aa0662b38b6dda726e0dfe8a231dd103f569559fb962768c20", +} +_temporary = None +_exports = None +_loaded = None + + +def exports(): + global _temporary,_exports + if _exports is not None: + return _exports + _temporary = tempfile.TemporaryDirectory(prefix="physical-scalar-stream-") + result = {} + for name,digest in ARCHIVES.items(): + archive = HERE/"inputs"/(name+".tar") + if sha256(archive.read_bytes()).hexdigest() != digest: + raise ValueError("immutable scalar source archive: "+name) + destination = Path(_temporary.name)/name + destination.mkdir() + with tarfile.open(archive,"r:") as contents: + seen = set() + for entry in contents.getmembers(): + path = PurePosixPath(entry.name) + if path.is_absolute() or ".." in path.parts or entry.name in seen or not (entry.isfile() or entry.isdir()): + raise ValueError("regular relative scalar source archive") + seen.add(entry.name) + contents.extractall(destination,filter="data") + result[name] = destination + _exports = result + return result + + +def module(name,path): + spec = importlib.util.spec_from_file_location(name,path) + value = importlib.util.module_from_spec(spec) + sys.modules[name] = value + spec.loader.exec_module(value) + return value + + +def activate(): + global _loaded + if _loaded is not None: + return _loaded + if any(name in sys.modules for name in ("leaf_sources","phase_sources","native_sources","source","words","signed_linear")): + raise ValueError("cold physical scalar namespace") + paths = exports() + leaf = module("leaf_sources",paths["pr3091"]/"leaf_sources.py") + leaf.ROOT = ROOT + leaf.activate() + sys.path.insert(0,str(paths["pr3091"])) + lower = module("scalar_lower",paths["pr3090"]/"vendor/lowering/lower.py") + _loaded = lower + return lower diff --git a/research/physical-scalar-stream/scalar_test_support.py b/research/physical-scalar-stream/scalar_test_support.py new file mode 100644 index 0000000000..d6794a22c3 --- /dev/null +++ b/research/physical-scalar-stream/scalar_test_support.py @@ -0,0 +1,67 @@ +"""Checker-only literal inventory, signed integers and prefix oracle.""" +import scalar_sources +scalar_sources.activate() +from fractions import Fraction +from literal_templates import TEMPLATES,POLICIES +from words import BLANK,need + + +def body(tape): + tape = getattr(tape,"physical",tape) + return bytes(tape.cells[1:]).rstrip(bytes([BLANK])) + + +def encode(value,width): + return bytes((value>>index)&1 for index in range(width)) + + +def packet(values,width): + return b"".join(encode(value,width) for value in values) + + +def fill(tape,raw): + tape.clear() + for bit in raw: + tape.append(bit) + tape.rewind() + + +def prefix_oracle(recipe,x,y,width): + registers = [x,y,0] + limit = 1<<(width-1) + for operation in recipe.program: + kind,target = operation[:2] + value = registers[target] + if kind == "add": + value += operation[3]*registers[operation[2]] + elif kind == "copy": + need(value == 0, "checker COPY destination zero") + value = registers[operation[2]] + elif kind == "clear": + value = 0 + elif kind == "neg": + value = -value + elif kind == "double": + value *= 2 + else: + need(kind == "half", "checker finite scalar alphabet") + if value%2: + return None,"inexact" + value //= 2 + if not -limit <= value < limit: + return None,"headroom" + registers[target] = value + expected = Fraction(x)+recipe.coefficient*y if recipe.kind == "add" else recipe.coefficient*x + need(expected.denominator == 1 and registers == [expected,y,0], "independent scalar/source/scratch endpoint") + return int(expected),None + + +def snapshot(values): + return [(bytes(getattr(value.tape,"physical",value.tape).cells),value.tape.head) for value in values] + + +def closed_work(engine,include_output=False): + tapes = (*engine.pool.tapes,engine.output) if include_output else engine.pool.tapes + need(engine.closed and not engine.pool.live, "closed scalar inventory") + need(all(tape.head == 1 and all(bit == BLANK for bit in tape.cells) for tape in tapes), + "erased scalar scratch and local heads") diff --git a/research/physical-scalar-stream/scalar_words.py b/research/physical-scalar-stream/scalar_words.py new file mode 100644 index 0000000000..36919dc569 --- /dev/null +++ b/research/physical-scalar-stream/scalar_words.py @@ -0,0 +1,127 @@ +"""Encoded fixed-width shifts, logical zeros and owned scalar word updates.""" +import scalar_sources +scalar_sources.activate() +from compact_counts import copy_bits +from session import borrowed_tape +from signed_linear import CoefficientDomainError,linear_word +from stream import Counter +from words import BLANK,need + + +class ScalarContractError(CoefficientDomainError): + pass + + +def zero_word(tape,width): + tape.rewind() + remaining = Counter(width) + try: + while not remaining.finished: + tape.write(0) + tape.step(1) + remaining.decrement() + need(tape.read() == BLANK, "complete scalar logical-zero extent") + finally: + remaining.close() + tape.rewind() + + +def require_zero(tape,width): + tape.rewind() + remaining = Counter(width) + try: + while not remaining.finished: + if tape.read() != 0: + raise ScalarContractError("scalar logical scratch is not zero") + tape.step(1) + remaining.decrement() + need(tape.read() == BLANK, "complete scalar zero word") + finally: + remaining.close() + tape.rewind() + + +def shifted(source,target,width,double): + source.rewind() + remaining = Counter(width) + first,previous,last = True,0,0 + try: + if double: + target.append(0) + while not remaining.finished: + bit = source.read() + need(bit in (0,1), "complete scalar shift input") + source.step(1) + remaining.decrement() + if double: + if remaining.finished: + if bit != previous: + raise CoefficientDomainError("signed scalar DOUBLE headroom") + else: + target.append(bit) + elif first: + if bit: + raise CoefficientDomainError("inexact scalar HALF") + else: + target.append(bit) + first,previous,last = False,bit,bit + need(source.read() == BLANK, "complete fixed scalar shift width") + if not double: + target.append(last) + finally: + remaining.close() + source.rewind() + + +def instruction(registers,operation,width,work,zero): + kind,port = operation[:2] + target = registers[port] + if kind == "clear": + zero_word(target,width) + return + try: + if kind == "add": + linear_word((target,registers[operation[2]]),work,width,(1,operation[3])) + elif kind == "copy": + require_zero(target,width) + source = registers[operation[2]] + source.rewind() + copy_bits(source,work,width) + need(source.read() == BLANK, "complete scalar COPY source") + source.rewind() + elif kind == "neg": + linear_word((zero,target),work,width,(1,-1)) + else: + need(kind in ("double","half"), "compiled scalar shift kind") + shifted(target,work,width,kind == "double") + work.rewind() + borrowed_tape(target).clear() + copy_bits(work,target,width) + need(work.read() == BLANK, "complete scalar unit result") + target.rewind() + finally: + borrowed_tape(work).clear() + + +def restored_source(local,borrowed,width): + """Compare only the current borrowed component, then resume its cursor.""" + back = Counter(width) + try: + while not back.finished: + borrowed.step(-1) + back.decrement() + finally: + back.close() + local.rewind() + forward = Counter(width) + try: + while not forward.finished: + if local.read() != borrowed.read(): + raise ScalarContractError("scalar source component not restored") + local.step(1) + borrowed.step(1) + forward.decrement() + need(local.read() == BLANK, "complete restored scalar source") + finally: + forward.close() + local.rewind() diff --git a/research/physical-scalar-stream/verify.py b/research/physical-scalar-stream/verify.py new file mode 100644 index 0000000000..7b1155503a --- /dev/null +++ b/research/physical-scalar-stream/verify.py @@ -0,0 +1,46 @@ +"""Authenticate sources and compare one complete cold scalar receipt.""" +import argparse +from hashlib import sha256 +import importlib +import json +from pathlib import Path +import sys + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[1] +sys.path.insert(0,str(HERE)) + + +def authenticate(): + sources = json.loads((HERE/"SOURCES.json").read_text()) + manifest = json.loads((HERE/"VERIFY.json").read_text()) + inputs = {row["path"]:row for row in sources["files"] if row["usage"] == "input"} + if set(inputs) != set(manifest["inputs"]): + raise ValueError("complete scalar input inventory") + for name,row in inputs.items(): + if sha256((ROOT/name).read_bytes()).hexdigest() != row["sha256"]: + raise ValueError("changed live tape-source input: "+name) + for row in sources["archives"]: + if sha256((HERE/row["path"]).read_bytes()).hexdigest() != row["sha256"]: + raise ValueError("changed immutable scalar source archive") + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--suite",required=True,choices=("bindings","shifts","packets","prefixes","returns","failures")) + parser.add_argument("--emit",action="store_true") + args = parser.parse_args() + authenticate() + checks = importlib.import_module("check_"+args.suite) + result = checks.run() + digest = sha256(json.dumps(result,sort_keys=True,separators=(",",":"),allow_nan=False).encode()).hexdigest() + if not args.emit: + expected = json.loads((HERE/"RESULT.json").read_text())[args.suite] + if digest != expected: + raise ValueError("complete typed scalar receipt differs: "+args.suite+": "+digest) + print(json.dumps(dict(suite=args.suite,sha256=digest,result=result),sort_keys=True,indent=2)) + print("PASS_PHYSICAL_SCALAR_"+args.suite.upper()) + + +if __name__ == "__main__": + main()