Ship oracle journal values, bytecode/frontend hardening, and replay-policy Lean.

Host exposes oracle journals as language values with refuse/copy gates; bytecode and foreign session paths get modularized; applications and verification replay-policy sources land with Lake builds ignored.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-11-06 15:04:27 +08:00
1 parent e3d9021bb6
commit 8f1010f967
101 files changed
+17962 -1727

No files matched your search

@@ -0,0 +1,24 @@
# 外联库论文的研究方向
作者于 2026-11-05 将论文主线明确为:**叙述本身是程序,外部代码是值**。
Marqdo 的外联库用于在这一宿主模型中组合既有语言的计算能力,统一说明、控制流、
代码复用、状态与显式数据交换。论文应先解释 Notebook/文学编程中的实际设计问题,
再给出解决方案、可核验的收益、形式化依据和应用实验。
后续实现工作围绕绑定的代码值、参数化调用、持久会话、复制值和文档计划展开。
生命周期、值域和重放机制为这个统一设计提供保证;不能将重放检查器重新提升成
取代外联库与叙述式编程的论文主题。不得把未测的人因优势或未证明的实现正确性
写成既成事实。
完整方向文件在论文工作区:
- 方向(当前):`MarqdoThesis/PLDI/design/V7-NARRATIVE-FIRST-DIRECTION-2026-11-05.md`
- v6 方向(历史):`MarqdoThesis/PLDI/design/V6-NARRATIVE-FIRST-DIRECTION-2026-11-05.md`
- 证据映射:`MarqdoThesis/PLDI/design/V6-EVIDENCE-MAP-2026-11-05.md`
- 章节与页预算:`MarqdoThesis/PLDI/design/V6-OUTLINE-2026-11-05.md`
当前稿位于 `MarqdoThesis/PLDI/paper-v7`;v6 保留,历史 v5 及其证据保留。方向文件取代了
此前把论文缩成“外联会话值 + 因果重放”的 N3 路线:重放是支撑机制,不是主线。
2026-11-05 交付:`MarqdoThesis/PLDI/paper-v7/main.pdf`,正文(含 AI Use)20 页。
v6 保留为上一版尝试;更早的 v6 草稿保留在 `paper-v6-draft-2026-11-05/`。
@@ -1,5 +1,14 @@
# Foreign Strong: Lean ↔ host correspondence
2026-11-02 补充:`ForeignSource.lean` 对显式局部环境、返回、函数调用/递归、
分支和有界 while 的源解释器与独立 effect 编译器证明一般精化,并推出安全
观察和旧句柄不可复活。`CheckForeignSource.lean` 消费真实加载后 AST 的显式
适配格式,用独立 counter oracle 对照 tree/bytecode 的返回、journal、fault
与故障后 n。它已用于发现并修复 tree 的父词法作用域查找缺陷。
这是源控制流层的证明与实现 translation validation;Rust parser/adapter、
全部 AST 构造、机器数值运算和物理调度的完整 refinement 仍须完成。
模型中的 fuel 是分析界限,不能称为真实程序必然终止或有界取消。
Pinned with PLDI Strong / paper-v5 (sessions as values; three gates).
Marqdo **2.3.0** host implements the same objects the Lean development decides.
@@ -23,3 +32,13 @@ Marqdo **2.3.0** host implements the same objects the Lean development decides.
- SafeVal mechanization covers the **integer** fragment; finite floats are admitted by the host under the same refuse-not-coerce bridge policy for non-integers already in SafeVal.
- Session discipline is a **dynamic registry** (affine close + borrow-use). Static linear types over OS-killable processes are out of scope by design, not an unfinished host feature.
- Correspondence is mechanized for the **closed / fresh-open / functional-Ω** fragment (`corr_fresh_functional`): per-step interactive value = Ω answer, interactive runner = normative runner, `replayCheck` on the journal. Broken hypotheses are `corr_fail_*`. Host discharge is foreign-session gold plus R1–R3, not R1–R3 alone.
## Reviewer-driven implementation update (2026-11-01)
The independent live cursor and multisession action-plan simulation are in
`DocCalc.runForeignLive_simulation` and `MarqdoProof.ForeignTrace`. The language
now exposes oracle observations and pure journal comparison through
`foreign.oracle_journal` / `foreign.replay_check`. Strict interactive snapshot
replay uses the full oracle history with source identity and per-step input.
See `oracle-journal-values.md` for the API and the research experiment manifest
under `PLDI/experiments/reviewer-v5/` for exact source hashes and actual runs.
@@ -0,0 +1,336 @@
# Executable call and integer semantics
This describes the implementation contract exercised by
`src/frontend_elaboration_tests.rs`; it is not a claim of a verified parser.
All explicit actual arguments evaluate once in authored order, including extra
named arguments whose values the callee does not read. Binding then permutes
already computed values into parameter slots. Named arguments take precedence
over positional filling; duplicate names and excess positional arguments fail.
A duplicate-actual binding fault occurs only when its call is reached, after
all explicit actuals have evaluated; it cannot reject an unused function at
compile time or erase an earlier argument effect.
Local calls and imported calls use the same order. Builtins and host primitives
must not reorder expression evaluation when selecting their parameter values.
All supplied parameters are available before defaults. Missing defaults execute
in parameter declaration order, once per call, in the target definition's
module and lexical scope. A default can see supplied parameters, earlier
computed defaults, and an explicitly bound method receiver. It cannot capture
the caller's locals. A still omitted later parameter is unbound. Explicit None
is a supplied value and never triggers a default. Required-argument validation
precedes default execution. Default expressions participate in receiver
classification, dependency analysis and transitive effect inference.
A dynamic method's signature belongs to the resolved receiver and selected
method; a different object's same-named method cannot supply its parameter
list. Imported definitions retain their module scope. A compiled document's
entry is selected only from its own module; an imported `main` is not an entry.
The bytecode retains argument names and explicit presence bits. Callee
prologues evaluate defaults in their own frame. Local slots distinguish an
unbound slot from a slot holding None. Local, constant, call-layout and jump
indices use container-sized indices rather than unchecked 8/16-bit casts.
Scratch slots are reused across sequential calls while pending outer actuals
remain live. Scalar constant interning uses a hash table; floating constants
are keyed by their exact bits.
Host integers are signed 64-bit values. Add, subtract, multiply, divide and
negation report a language error on overflow in every build profile; division
by zero is a separate error. Division truncates toward zero. The negative
endpoint has a valid signed literal. Float-to-int conversion rejects nonfinite
or out-of-range inputs instead of silently saturating. This local integer
domain is distinct from the narrower continuous foreign-copy domain.
The Lean call-combinator proof preserves complete interaction programs for
arbitrary argument evaluators, including failure and reply-dependent requests.
The integer model specifies exact arithmetic followed by representability
checking. Native documents, independently derived Python expectations, a Lean
arithmetic consumer and isolated source mutations validate the implementation
links. These do not prove the entire Rust parser, binder, object representation
or adapter. The research coverage ledger must keep those obligations explicit.
## Module identity, entry inputs and source-bound invocation
Instances retain the existing map representation and safe-copy domain. The
reserved `_type_module` field is a list of import binding names, paired with
`_type`. Class selection uses that module instance within the active import
tree; inherited methods resolve their bases in the defining module. Equal
class names in different imports remain distinct. These fields are ordinary,
forgeable data, not capabilities or globally portable nominal identities.
Round trips through Python/Node preserve these descriptors in the same module
context. Opaque session handles remain outside the copy domain.
Entry metadata is passed to `Vm::run`, never compiled into `main`'s body.
Explicit named/recursive invocations of `main` therefore keep their own inputs.
Defaults run with the invocation's actual registry; a session-valued default
must not be evaluated in a separate interpreter and then injected into a VM.
Reads appearing only in explicit/prose defaults participate in input inference
and effect analysis. Default failures use the parameter declaration's span.
Source-bound APIs preserve the selected declaration's source identity and
span, even when two declarations have the same dotted path. Textual path calls
retain the existing first-declaration rule. Duplicate parameter names are
rejected because they cannot define distinct binding slots.
Both backends retain parameter, return and local field contracts. Bytecode
checks supplied/defaulted inputs before the body, explicit returns before
returning, table bindings before writing a local and direct footnote accesses
before/after lookup. Unknown fields report the contract error before a generic
missing-key error. Entry/raw invocations also check their completed inputs.
Contract diagnostics retain the declaration quote and the failure location.
## Refinement obligations and current evidence
| Link | Mechanized result or implementation evidence | Remaining obligation |
|---|---|---|
| Raw Markdown to executable AST | Native explicit/prose defaults, source snapshots, parameter spans, inference and duplicate-parameter diagnostics | Prove the actual Rust classifier/parser and extraction rules; the older abstract grammar is not that proof |
| Loaded module tree to flattened declarations | Independent inventories of source digests, module instances, lexical parents, class/method ownership and resolved bases | Connect the actual resolver to the Lean namespace lookup model, including failed/ambiguous resolution |
| Effectful actual evaluation to parameter values | `FrontendCalls` proves interaction-program equality for arbitrary expression evaluators; native authored-order/unused-actual/builtin/foreign probes | Prove Rust scratch allocation, every expression case and its stack invariant against that combinator |
| Default evaluation and invocation inputs | Native callee-scope, presence, receiver, entry/raw/metadata, inference, error-span and stateful-session cases | A complete default-binding semantics and universal compiler refinement, including errors and host context |
| Module-qualified object dispatch | `ModularObjects` proves namespace flattening lookup, resolved-parent dispatch and safe descriptor round trips | Connect every real object constructor, resolver and copied descriptor to the model; justify Rust module-root lifetimes |
| Machine integers | `MachineInts` exact signed-64 model, checked boundary implementation, independent Python and Lean consumers | Connect Rust checked arithmetic and every conversion to the mathematical evaluator; floats remain an extension |
| Progressive contracts | Four real source boundary failures preserve codes, anchors and failure spans; valid contract execution | Universal contract-preservation theorem and imported declaration/call-site attribution |
| Source-bound external calls | Two same-path declarations execute their separately selected source lines on both backends | Full external argument validation, effect-policy and environment-injection refinement |
The ledger deliberately does not turn a new model lemma, a finite passing
corpus, or independent reconstruction into a complete frontend theorem. Those
remaining proof links are required to discharge the full frontend objective.
## Default prologue proof and imported contract attribution (November 4)
`DefaultPrologue.default_prologue_refines` relates source default binding, which
rechecks the current environment for omission, to a guarded block machine with
an immutable initial presence mask. It proves whole interaction-program equality
for arbitrary effectful evaluators, assuming distinct parameter slots and an
initially faithful presence mask. Earlier default stores preserve that invariant
for later parameters. The duplicate-slot counterexample issues two requests in
the machine versus one in the source, demonstrating why slot uniqueness matters.
Explicit None skips and immediate failure stopping are separately checked.
This is a model of guard/evaluate/store blocks, not a proof of the Rust emitter,
flat instruction stepping, actual expression compilation or parser.
The generated implementation family crosses all 27 omitted/int/None states for
three parameters with all six declaration orders. An independent environment
model checks 162 documents and 324 executions, including 34 faults when a default
reads a later omitted parameter. Source text is reconstructed independently;
expected traces are not derived from either backend. This finite family does
not prove arbitrary defaults. Imported argument-contract diagnostics now retain
the caller's failure span and source revision while pointing the declaration
anchor and suggestion at the actual library. Supplied and defaulted invalid
arguments both refuse before entering the callee body.
## Concrete name and flat-code interfaces
The compiler now borrows each original declaration and owning module while
flattening. Bare-call selection uses the same source `lookup_local` operation
as Tree, then maps the selected declaration identity to its flat index. This
removes a second, subtly different lookup algorithm: repeated top-level names
previously selected the first declaration in Tree but failed compilation in VM.
It does not prove the source lookup operation itself.
`NameSlots` proves reads, writes and the complete named-argument binding fold
commute with an injective local-name vector. Unknown names and repeated raw
API names are covered; repeated raw names retain last-write semantics. A
presence mask computed from initialized slots is faithful by construction.
The Rust raw entry and argument binder now derive their mask from the actual
initial logical slots. Method receiver aliases are overlaid only for default
evaluation, and restored into the body frame after logical argument checks.
`ReceiverDefaults` supplies the additional environment reasoning for explicitly
declared self/自 parameters; the slot theorem alone does not cover that case.
Every compiled Program is structurally verified before return, and the VM
verifies even publicly constructed/mutated Programs before any instruction.
All current opcode variants are handled exhaustively. Checks include operand
bounds, parameter/local prefix and injectivity, declaration and inheritance
forests, call-layout and function references, spans, reachable stack underflow,
branch/loop join heights and absence of leaked stack values on return. Missing
variable values remain language faults; this checker does not prohibit them.
Rust exports the computed per-PC heights alongside the real emitted opcode
text. `CheckFlatCertificate.lean` independently decodes that text and applies
an executable checker whose soundness is proved in `FlatCertificate`. Accepted
certificates preserve heights along every finite path and guarantee a valid
fetch with sufficient operands on each reachable PC, including loop prefixes.
The independent reader rejects unmodeled opcodes. Rust debug serialization and
opcode-to-concrete-VM-step correspondence remain interfaces to justify; a
structural certificate does not establish source/bytecode functional equality.
Neither this ordinary bytecode verification technique nor reuse of a resolver
is an originality claim. Complete functional lowering, parser semantics and the
Rust implementation correspondence remain open proof obligations.
## Functional expression checks and receiver views (November 4)
The emitter now records source-directed expression rules before emission, with
child order and exact instruction intervals. The mandatory native verifier
checks literal identity (including floating-point bits), local names, unary and
binary operators, short-circuit targets, interpolation, collections, indexing
and occlusion. Calls delegate staging and selection checks to `bytecode/call.rs`;
resolution and dispatch semantics remain explicit boundaries.
All seven statement forms have source-directed templates; a separate forest
check covers the entire default prologue, statement body and implicit return.
These checks detect stack-preserving semantic corruption, including Add to Sub,
and refuse it before host effects. A forged source witness remains outside this
check's guarantee; the recorder and actual AST correspondence need justification.
`ExpressionLowering` proves postfix expression compilation preserves complete
interaction programs for arbitrary effectful leaves and operator interpretations,
including faults and an arbitrary caller stack and continuation. `ShortCircuit`
proves the exact absolute-PC AND/OR macros under arbitrary effectful child
evaluation. `CheckExpressionLowering.lean` independently reads actual emitted
operators, constants and local names, and applies the proved core checker.
It counts call, collection, index and interpolation boundaries explicitly.
Child inlining, Rust VM stepping, leaf interpretation and source-witness fidelity
remain obligations; none of these results is whole-frontend functional refinement.
`ReceiverDefaults` proves that the source's separately maintained default
environment equals the machine's receiver view after every successful prefix.
The mask describes logical argument slots, while omitted self/自 defaults may
replace the evaluation view. Supplied None remains present. The real receiver
is restored before entering the body; argument contracts check both the logical
arguments at the call site and the restored frame at the declaration, preserving
source identity and diagnostic frames. The theorem composes this view invariant
with `DefaultPrologue` for arbitrary effectful defaults and distinct slots.
Concrete repairs also share scalar/unary semantics across evaluators, stringify
every interpolation part, allocate fresh loop temporaries, restrict dynamic
calls to their defining module scope, and enforce the existing one-million
truthy-iteration limit in VM as well as Tree. Regression evidence records each
repair separately from proof claims. These compiler techniques are not new
originality claims.
## Actual call staging and bounded control-flow macros
Every emitted call now has a separate source obligation captured before actuals
are replaced with scratch reads. The checker covers authored actual order,
evaluate/store/pop triples, source-local and loop-slot separation, nested-call
scratch separation, argument reloads, layouts, builtin selection/defaults, host
primitive identity, plugin name/pair ordering, method name/receiver and resolved
user target/tag. Every call expression must have exactly one obligation. The
reserved source-local prefix is established before any synthetic slots are
allocated. Disjoint nested calls may reuse scratch slots after their lifetimes.
`CallStaging` proves the flat evaluate/save/pop program restores an arbitrary
caller stack and has the same effects and failures as authored-order collection.
It proves outside slots unchanged and unique staged slots read back the exact
actual vector. The dispatch continuation is arbitrary and effectful, so binding,
defaults and receiver effects can follow collection without commuting effects.
`CheckCallStaging.lean` decodes real stores and reloads, applies the proved stage
checker and independently checks the complete selection/dispatch template.
Source-expression callback correspondence, name resolution and the semantics of
each dispatch continuation remain proof interfaces. Host parameter metadata is
an exported registry interface, not an independently verified registry theorem.
`WhileLowering` proves the condition/JF/check/body/backedge macro preserves the
complete interaction program for a bounded loop, including a final false
condition, condition/body faults, the truthy-iteration limit and early returns.
It relates an increasing native counter to a decreasing model budget and proves
admitted increments below one million fit u32. Model machine-step fuel is
distinct from this language-visible iteration budget.
`CheckStatementLowering.lean` checks actual default prologues, all seven statement
templates, forests and implicit returns, including the exact while macro layout.
The while theorem uses condition/body callbacks; concrete child inlining and the
full Rust state machine are not discharged by checking those layouts. Branches
and foreach currently have independent template evidence, not new functional
refinement theorems. No ordinary compiler-checking technique is a novelty claim.
## Loaded executable AST and coherent witness corruption
`SourceFunction` now captures parameters, defaults, executable bodies and complete
contract data directly from the loaded declaration before emission. The native
source checker walks that snapshot separately from the rule recorder, checks
ordered expression/statement correspondence and complete witness ownership,
and accounts for the generated scratch reloads explicitly. It also compares
full contracts with structural Rust equality, including types, nullable fields,
descriptions, source lines and declaration quotes. Contract presence alone would
not detect a Number-to-Any weakening.
The evidence exports the executable AST separately from the original module and
from the compiled snapshot. `CheckSourceWitness.lean` matches declaration
identities and applies `SourceWitness`'s proved ordered-tree reconstruction
checker. Interpolation parts, index labels, code payloads and formula structure
are retained; all formula floats and matrix entries retain their exact bits.
The old Debug formula text was insufficient for NaN payload identity. Inert
occlusion prose and pre-inference parser metadata are not execution-tree nodes.
Ten native coordinated-corruption cases change code together with its witness,
including operators, constants, variables, assignments, callees, NaN payloads,
index keys, interpolation, contract metadata and an orphan expression record.
Eight independent source-witness negatives include changing the compiled snapshot
as well. A coordinated wrong operator is a positive acceptance control for all
four earlier independent consumers and a rejection control for the AST checker.
This distinguishes trusted source correspondence from agreement among emitted
metadata fields.
The theorem proves exact correspondence of the supplied executable trees, hence
preservation under any interpretation of those trees. The native and JSON AST
adapters, normalization helpers and snapshot capture remain trusted interfaces.
No theorem here verifies the actual Markdown classifier/parser/inference or
connects every concrete Rust operation to the semantic models. A caller who
changes both the reference AST and its program has supplied a different
translation-validation input; this is not source authentication.
## Runtime argument-preparation faults
The expanded AST audit exposed a concrete acceptance mismatch: Tree can execute
main while an unused function contains a conflicting bracket modifier, whereas
VM compilation previously rejected the entire module. Modifier preparation now
lowers its failure to `RejectArgumentExpansion` before actual evaluation. A
provided default parameter, including explicit None, skips that fault; reaching
it preserves prior output and stops before actual effects or a suffix. The
error's message, span, source revision and diagnostic frames match Tree.
`CallExpr::for_evaluation` normalizes bare aliases before modifier expansion,
matching Tree's existing order. The expression checker validates an effect-free
fault leaf and the independent decoder handles its actual terminal opcode.
The AST adapter explicitly represents that executable fault without children;
unexecuted actual expressions are not falsely counted as evaluated code.
Two independent fault-opcode/message negatives and a positive AST-identity-only
control keep representation checking distinct from instruction interpretation.
The independent Python oracle now compares JSON values with exact recursive
types and requires integer arithmetic inputs to be actual integers. Python's
True==1 and 1==1.0 equalities must not erase language-visible value distinctions.
Four type-corruption controls are added. These improvements do not discharge
other call-error timing, parser, resolver, dispatch or Rust-step proof obligations.
## Native binding and declaration graph validation
Builtins, host primitives and plugins retain authored labels in native bytecode.
The shared value-independent binding plan selects named parameters before
positionals, preserves omitted optional bindings and unknown named extras, and
reports duplicate, missing and surplus positional arguments after actual effects.
Plugin lookup precedes signature binding. Eighteen reached/unreached error cases
check explicit expected output, messages, spans, source revisions and frames.
A registered C ABI echo probe checks mixed and extra named arguments. Execution
uses the native VM and plugin bridge throughout.
The source and flat declaration views share ordered resolution. A loaded snapshot
captures ordinal declaration paths, levels, child/root counts, imports and ordered
use aliases before emission. Verification checks identity, parent/child/root order,
module scopes and object/method names, then derives call targets independently of
emitted target records. Two-component paths check runtime receiver presence before
static fallback; an unbound reserved slot differs from a supplied None. Imports
retain priority. Resolution failures are native terminal instructions after actuals.
`NameResolution` proves first-match, path and lexical commutation under an
ordered embedding. Its rank checker proves sufficient depth and connects a
well-founded total source policy to flat lookup. Rust uses the same parent-chain
policy; parent-view extraction remains a trusted adapter. The finite checkers consume actual AST/flat evidence in
`CheckNameResolution.lean`. Nine native corruptions and seven independent graph
negatives test this boundary. A coordinated wrong target remains a positive control
for the older stack, staging and AST-shape consumers. Ordinary compiler correctness
ingredients are not novelty claims. Snapshot/JSON adapters, primitive registries,
parent-view extraction and concrete Rust
instruction refinement remain explicit obligations; universal frontend verification
and overall paper readiness are not established by these results.
`ArgumentBinding` separately models per-parameter omission permission and proves
value substitution preserves selections and faults. A successful index plan has
a finite-index witness. `CheckArgumentBinding.lean` checks actual static call
plans and an independently enumerated mask/label corpus. User VM calls now use
the shared planner with the callee default mask, correcting their surplus-count
diagnostic and preserving missing-required-before-default priority. Default
evaluation, contracts, dynamic signature selection and concrete Rust/JSON steps
remain separate interfaces. The mathematical planner is not a proof of the
entire native binding implementation.
+30
View File
@@ -1,5 +1,35 @@
# 文档会话(View Cells)
## 2026-11-02:并发控制与完整历史 v5
以下为当前实现;后文保留首版设计与当时的状态表。
- HTTP `kernel/interrupt` 查找已存在的会话,经独立控制器发送请求,不等待单元执行锁或其他文档的初始化。未打开、尚在初始化的会话返回错误,不启动新内核。已加载文档的源码文件被删除后仍可取消正在执行的单元。
- 内核的中断能力绑定其持有的子进程,并在回收前撤销;旧能力不能指向后来启动的内核。引导阶段的取消被暂存,收到 ready 后投递。逻辑取消输入会合并重复信号;投递错误明确返回。Windows 尚无对应的保状态中断实现。
- 取消使 Run All 在当前单元结束后停止,返回实际 `ran`、`remaining` 和 `cancelled`;不会继续运行后续单元。内核没有退出时,取消前已发生的状态修改保留。close 撤销 API 会话,重新打开不会激活旧引用。
- 完整历史 v5 将并发取消作为所在操作的 `controls` 输入记录:操作起点之后的微秒偏移及各内核的真实接收结果。严格回放按输入重新投递并重新观察回执;操作先结束时撤销剩余定时请求,不能流入下一操作。实际回执或观察不匹配就报告差异。v4 无控制输入的历史仍可检查;v4 中出现 controls 字段会被拒绝。
- 严格检查先完成纯验证,再启动回放内核。实际执行中,每次协议请求必须先与预期请求一致;实际回复和每个单元的观察、批次结果也立即比较。首个差异后停止依赖后缀,包括同一个 Run All 内的后续单元。未执行的观察标记 `compared=false`,不冒充已比较的第二个差异。
快照导出支持可选 `compact:true`。默认仍为完整 JSON;紧凑格式
`marqdo.history.dag` v1 对相同子值做自底向上共享,整数使用十进制文本、
浮点数保存 IEEE 位模式,保留映射顺序和全部历史字段。导入和严格回放会自动
识别格式。SHA-256 校验只检测内容一致性,不提供来源认证。
解码要求规范节点、向后引用、全部可达和唯一键,并在展开前检查最多
1,000,000 个节点、8,000,000 个展开值、512 MiB 保守展开预算、128 层深度;
展开后再次检查安全值域。此格式减少导出字节数,尚未减少录制时内存,也不保证更快。
实际取消实验覆盖 Unix 上同步 Python/Node 持久会话;不能推导任意外部代码均有界停止。
[Python 3.14 信号文档](https://docs.python.org/3.14/library/signal.html#execution-of-python-signal-handlers)
说明纯 C 计算可延迟信号处理;
[Node 22.22.1 vm 文档](https://nodejs.org/download/release/v22.22.1/docs/api/vm.html#timeout-interactions-with-asynchronous-tasks-and-promises)
说明异步任务可能逃出同步求值的中断范围。完整源码 elaboration、控制适配器、
真实时钟与信号调度到形式模型的 refinement 仍需完成,不能以这些测试代替。
相关实现:`foreign_session/control.rs`、`foreign_doc/control.rs`、
`foreign_doc/packing.rs`、`foreign_doc/replay.rs` 与 `view/notebook_api.rs`。
真实 TCP/HTTP 取消、逐单元副作用屏障和独立快照消费记录位于论文
`PLDI/experiments/reviewer-v5/`。
| | |
|---|---|
| 状态 | **D1–D3 首版已实现;D4/D5 待做** |
+131
View File
@@ -0,0 +1,131 @@
# Document oracle observations and strict replay
`foreign.oracle_journal` returns a copy of this evaluation's observations as
ordinary `index/channel/value` records. Successful admitted `session_eval`,
`session_get`, and document `json.parse` operations append `eval`, `get`, and
`decode`, respectively. Set/open/close do not append. An observation is
validated recursively before append; handles and code objects cannot enter.
Each new HostContext starts with an empty observation list.
`foreign.replay_check expected=J observed=J2` is a pure comparison, with no
foreign execution. It validates contiguous zero-based indices, channel tags
and crossing-domain membership. Records compare structurally by field name,
independent of field order. The result contains `ok`, the least mismatching
`index`, and both records (None for a missing entry). Two empty journals
match. Failure to provide a valid journal is an error, not a match.
The interactive `DocumentSession::replay_check(snapshot)` is a different layer:
it executes a recorded trace from fresh state. Version-2 snapshots contain the
full chronological oracle trace, recorded stdin per step, its declared count,
the plan and source identity. Preflight validates every step before any foreign
execution. Every step is compared; none is skipped. Repeated cell executions
are distinct observations. Execution timing logs and cell display summaries
are not comparison inputs. Matching input values in a supplied snapshot is
consistency checking, not cryptographic authentication of the recording.
Snapshots carry the SHA-256 of the loaded document text. Import checks it
before restoring foreign bindings, and preflights all crossing payloads before
mutation. Reload retains prior oracle observations with their original source
hashes, so a later checker can reject an incompatible trace.
Lean: DocCalc's independent `runForeignLive` cursor simulates `runForeignAcc`
for arbitrary prefixes, observation accumulators and code sequences, including
oracle failures. `ForeignTrace` composes the registry's open/eval/close
judgments using independent normative and interactive execution control;
`trace_simulation`, `trace_correspondence`, and `trace_replay` quantify arbitrary
multisession action sequences, also when a run faults. These supplement the
existing theorems without removing them.
Tests: `tests/oracle_journal.rs` runs the public document API on both evaluators;
`host::oracle::tests` covers journal equality and length localization;
`host::foreign_doc::tests` covers the live trace preflight and actual replay;
`host::foreign_session::tests` includes generated two-session model checks and
Python/Node boundary and process-failure experiments. The research runner is
`MarqdoThesis/PLDI/experiments/reviewer-v5/run.py`.
## Stateful requests and semantic projection
`HostContext.foreign_protocol_steps` records internal request attempts and
replies, including set values, copied eval input and raw stdin. It is separate
from the admitted language journal: rejected inbound responses belong to the
protocol evidence, while only admitted values belong to the oracle journal.
An input refused before send produces no protocol request. A response refused
after execution does not undo kernel effects; the post-state is retained.
Language observations are recorded at the document API boundary and by live
cell evaluation. Low-level get/names used during snapshot export do not append
language observations. A successful eval projects to its result. A failed eval
projects to a record of stable status, output and diagnostics. Process timing,
commands and handles are not semantic values. The exact source path allocated
for one-shot execution is alpha-renamed only in diagnostic fields; raw stderr
and stdout remain available unchanged, and ordinary paths/error differences
are still compared. Live oracle records carry this same projected `value`.
Python/Node replies mark serialization-domain failure with `domain_error`.
Error text is not used to infer this flag. Python refuses non-string object
keys; Node sanitizes objects with a null prototype to preserve special keys.
The common strict JSON decoder checks duplicate keys before materializing a
map, rather than losing them through overwrite.
`ForeignState.lean` refines the earlier eval-only fragment with opaque kernel
state, complete request histories, set/get/eval input/decode, monotonic handle
allocation and fault outcomes carrying the admitted prefix. An adaptive
Program has continuations on actual observations; its correspondence theorem
covers data-dependent next actions, not just a fixed schedule. Mapping actual
document elaboration and host bindings to this program is a further proof
obligation recorded in the research status file.
## Complete history, snapshot version 4 (2026-11-02)
Strict interactive replay now records operations, not just successful cells.
Each public execution/mutation boundary records typed arguments, success or
failure, admitted observations, cell-oracle records, and stable resulting
state. Nested implementation calls are grouped under the user's operation.
The history includes set/get, run/step/run-all, restart, reload, plan edits,
clear, snapshot inspection and imported values. Failed attempts remain in the
history; rejected handles and secrets have only non-capability/redacted tags.
Clearing display outputs cannot erase the history's oracle projection.
The snapshot stores the materialized initial plan and historical reload plans.
Entry text is parsed at its original path, retaining relative imports without
rewriting the user's document. Initial bindings are reapplied when a kernel is
reopened; unchanged reload kernels retain state, whereas changed language or
command retires the incompatible process. Loaded source/metadata and cached
cell outputs are updated consistently.
Preflight checks the entire operation stream, all source revisions, plan edits,
binding/cursor/generation transitions, and oracle projections before starting
any replay kernel. Executing the trace compares each result, admitted value,
cell result and stable state. The first mismatch stops its dependent suffix;
`executed_actions` and `remaining_actions` make this explicit. `matched` counts
admitted observations and `matched_actions` counts operations. No missing
record is silently accepted or skipped.
The HTTP replay-check endpoint performs an isolated comparison and retains an
existing warm session. It validates malformed input before starting even a
seed kernel; duplicate JSON fields are refused before overwrite. Verification
can still run recorded foreign work and its external effects: isolation is of
the document session, not a process sandbox. `replay_snapshot` remains the
separate legacy cell re-run API and makes no strict-history comparison claim.
Older version-2/3 snapshots may be used by legacy restoration/re-run surfaces;
they cannot prove a complete action history and strict checking requires v4.
`ForeignHistory.lean` models explicit command boundaries. A fault terminates
its command, a later command receives the actual retained registry, and the
history retains all command faults and admitted observations. It proves
command-history correspondence, journal membership and no alias resurrection
through arbitrary recovery histories. This extends the adaptive Program
results; the general source-elaboration refinement is a separate outstanding
proof obligation.
Experiment source inputs are frozen before running, checked again afterward,
and archived with their hashes. The current passing bundle is identified by
`MarqdoThesis/PLDI/experiments/reviewer-v5/LATEST-PASSING.json`.
Each operation also retains its internal protocol attempts/replies, including
refused inspection results. Those records are compared even when an inspector
could not return a value. They are control evidence and do not admit rejected
payloads into the language journal. An explicit document session_names request
adds its admitted array on the decode channel; internal names/get probes do not.
Reload records either a historical source/plan input or its input-read error;
replay consumes that captured version input and does not rewrite past files.
+13 -1
View File
@@ -24,7 +24,7 @@ MAX_SAFE = 9007199254740991 # 2^53 - 1
| `array` | `List` |
| `object` | `Map` |
**Host extension (not in Lean `SafeVal`):** JSON non-integer numbers → `Value::Num(f64)` (NaN/Inf encode as `null`). Floats are documented host behavior; they are **not** claimed as mechanized \(V_{\mathsf{safe}}\) fidelity.
**Host extension (not in Lean `SafeVal`):** JSON non-integer numbers → `Value::Num(f64)`. Non-finite numbers (NaN/Inf) are refused on encode and in Python/Node oracle responses, including nested payloads. Floats are documented host behavior; they are **not** claimed as mechanized \(V_{\mathsf{safe}}\) fidelity.
## Encode (`value_to_json`)
@@ -76,3 +76,15 @@ json: integer outside V_safe (±(2^53-1)): <n>
- Not automatic BigInt promotion inside Node/Python bootstraps.
- Document-level `Value::Int` may still hold i64 values that are OOD for JSON;
the gate fires when those values enter JSON encode/decode.
## Strict request boundary update
The numeric gate applies to the represented value, including integer-valued
floats and exponent notation. `9007199254740992.0` and
`9.007199254740992e15` are refused; fractions such as `1.5` remain in the host
extension. `serde_json` uses `float_roundtrip` to avoid endpoint decoding loss.
The strict text decoder rejects duplicate object keys and unequal column maps
before information is lost. One-shot, call_many and persistent input paths
use recursive domain admission; code, handle and secret values are not copied
implicitly. Auto-detection may leave non-JSON output as text, but valid JSON
outside the domain is a refusal, including in batch results.