Skip to content

fix(theorem): partial-eval constraint body before visiting (cross-submission capture) - #43

Closed
jsboige wants to merge 4 commits into
endjin:mainfrom
MyIntelligenceAgency:fix/c805-fc44dfa-partial-eval-cross-submission
Closed

jsboige wants to merge 4 commits into
endjin:mainfrom
MyIntelligenceAgency:fix/c805-fc44dfa-partial-eval-cross-submission

Conversation

@jsboige

@jsboige jsboige commented Sep 1, 2026

Copy link
Copy Markdown

Summary

Fixes a crash in Theorem.AssertConstraints when the constraint lambda captures a local declared in a different .NET Interactive / Polyglot Notebooks submission.

Theorem.AssertConstraints now runs PartialEvaluator.PartialEval on each constraint body before ExpressionVisitor.Visit. This folds host-captured constants (locals declared outside the theorem parameter scope, e.g. in a different .NET Interactive submission or closure) into literal ConstantExpressions, sidestepping the reflective MemberExpression resolution in ExpressionVisitor.VisitMember that crashed across dynamic-assembly boundaries.

Bug

In .NET Interactive / Polyglot Notebooks, each cell compiles as a separate dynamic assembly (Submission#N). When a constraint lambda captures a local declared in another submission, VisitMember resolved the FieldInfo on the lambda submission type while the closure target carried the declaring submission type:

System.ArgumentException: Field 'b0' defined on type 'Submission#N' is
not a field on the target object of type 'Submission#M'

This was invisible in xUnit (single-assembly) because the closure and the field live in the same assembly there.

Repro (manual, .NET Interactive)

Two consecutive cells in a .NET Interactive notebook (Polyglot Notebooks):

// Cell 1 (submission #N)
var b = 5;          // local declared here

// Cell 2 (submission #M)
var t = Z3.Linq.Theorem.Z3;
var x = t.IntConst();
t.Assert(t.And(x >= 0, x <= b));   // captures `b` from cell 1
var s = t.Solve();                  // <-- crashes here

Before the fix, Solve() raised ArgumentException: Field 'b0' defined on type 'Submission#N' is not a field on the target object of type 'Submission#M'.

After the fix, Solve() returns the expected model x = 0.

Fix

Theorem.AssertConstraints now calls PartialEvaluator.PartialEval on each constraint body before handing it to ExpressionVisitor.Visit. The partial evaluator folds host-captured constants (locals declared outside the theorem parameter scope) into literal ConstantExpressions, so VisitMember is never asked to resolve them reflectively.

// before
foreach (var constraint in body)
//   constraint.Accept(this.ExpressionVisitor);

// after
foreach (var constraint in body)
{
    var partial = PartialEvaluator.PartialEval(constraint, ...);
    partial.Accept(this.ExpressionVisitor);
}

The fix is a no-op for same-assembly captures (PartialEval folds them to the same literal VisitMember would have produced via reflection), so all existing xUnit tests pass unchanged.

Subtrees referencing the theorem parameter (e.g. t.Values[i]) are preserved — they are not evaluable without a parameter binding and are left for the visitor to handle.

.gitignore

Adds .deploy/ to the ignore list — used by dotnet publish -o .deploy for the polyglot repro infrastructure.

Tests

This repository has no xUnit test infrastructure covering the cross-submission capture scenario (the bug is invisible there by construction — single-assembly), so no new test is included. The repro above is the canonical failing case and is exercised in the companion pedagogical repository (MyIA.AI.Notebooks/ML/DataScienceWithAgents/02-ML-Cours/2.8b-Theorie-PAC-Lean.ipynb family + the standalone polyglot-repro/CrossSubmissionCaptureRepro.ipynb reproduction).

Notes

Cherry-picked from a downstream fork (MyIntelligenceAgency/Z3.Linq, branch fix/c805-fc44dfa-partial-eval-cross-submission). The companion reproduction notebook and downstream .csproj glue are intentionally not included in this PR — they belong in the downstream pedagogical repo, not here.

@HowardvanRooijen

Copy link
Copy Markdown
Member

Very interesting - revisiting your suggestion in #29 has been on my backlog for a while - especially as we could leverage some agentic AI to help with any of the integration.

@jsboige

jsboige commented Sep 17, 2026

Copy link
Copy Markdown
Author

Thanks Howard — read your note on #29 and the stack (congrats on the sweep, #110 looks like the right capstone). Three quick things on this PR:

Scope reframed beyond .NET Interactive. Now that Polyglot Notebooks are dropped upstream, I want to be explicit that this fix is not Interactive-specific: any host that compiles expression trees with closures across assembly boundaries — dynamic assemblies (Submission#N is just the common case), plugin architectures, add-in models — hits the same reflective MemberExpression crash in VisitMember. Interactive was merely the repro surface. The community fork (Polyglossy/interactive) also keeps that surface alive for notebooks.

Test, as offered. A real test for this rides with the test-project PR I promised on #29 rather than ballooning this one: the honest xUnit reproduction needs the closure field to live on a foreign type, which single-assembly tests cannot produce by construction — so the design is a small compiled-on-the-fly assembly (Roslyn scripting) that captures a local and hands the constraint across, making the pre-fix ArgumentException visible in the suite. This branch stays minimal on purpose.

Targeting. The two scoping questions from #29 still stand (main vs staging branch, anything to leave alone) — happy to aim this and the upcoming PRs at the tip of your stack if that saves you rebase work; on our side the drift adaptation is agent-driven, matching the workflow you described.

@jsboige

jsboige commented Sep 18, 2026

Copy link
Copy Markdown
Author

The reproduction I offered earlier is in — and it landed one branch over rather than inside this PR, to keep the fix diff surgical (this branch still touches exactly the two files).

Where it lives: test/c805-cross-submission — this PR's branch plus a self-contained xUnit test project. The test compiles two chained C# scripts (Roslyn scripting — the same compiler .NET Interactive uses for its cells), so the captured local and the constraint lambda land in two different dynamic assemblies (Submission#0 / Submission#1): exactly the tree shape a single-assembly suite cannot produce by construction.

Red on main (same test project carried onto vanilla main):

Failed CrossSubmissionCaptureTests.Solve_ConstraintCapturingLocalFromPreviousSubmission_ReturnsModel
  Error Message:
   System.ArgumentException : Field 'b' defined on type 'Submission#0' is not a field on the target object which is of type 'Submission#1'.
  Stack Trace:
     at System.Reflection.RtFieldInfo.GetValue(Object obj)
   at Z3.Linq.ExpressionVisitor.VisitMember(...) ExpressionVisitor.cs:line 358
   at Z3.Linq.Theorem.AssertConstraints[T](...) Theorem.cs:line 166
   at Z3.Linq.Theorem`1.Solve() Theorem{T}.cs:line 39

1 failed / 0 passed — the exact exception from the wild, down to the submission numbering.

Green on this PR's branch: 1 passed / 0 failed, same test, same machine, only the partial-eval change in between.

The single added dependency is Microsoft.CodeAnalysis.CSharp.Scripting, in the test project only — it is the reproduction mechanism, another reason it stays off the fix branch. Happy to fold the branch into this PR, or rebase it on top of the test-infrastructure PR (#111) once that lands — your call; either way it's a fast-forward from where it sits.

jsboige referenced this pull request in MyIntelligenceAgency/Z3.Linq Oct 4, 2026
#43 poste, endjin#88 bras element, bound scalars no-op)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@jsboige

jsboige commented Oct 25, 2026

Copy link
Copy Markdown
Author

Rebased onto the tip of the pile, as requested — published as fix/c805-partial-eval-on-spectre-pile (ab2dc807), on top of feature/spectre-demos (b425802).

The branch of this PR is deliberately untouched: its base is still main, and which base the rebased work should target is your call. Say the word and I retarget this PR (or open a fresh one) onto feature/spectre-demos with the same content.

What the rebase had to adapt

Two things, both measured on the rebased tree rather than guessed:

  1. ExpressionVisitor.Visit is ExpressionVisitor.Translate in the pile, so the call site follows the rename.
  2. Under the pile's central package management, MiaPlaza.ExpressionUtils is 1.3.1, where PartialEval is generic over LambdaExpression. Passing constraint.Body no longer compiles (CS0311: Expression has no implicit reference conversion to LambdaExpression). The lambda itself goes in and its body comes back out: PartialEvaluator.PartialEval(constraint, ExpressionInterpreter.Instance).Body.

The .gitignore hunk is kept as a union — the pile's test-artefact entries plus the .deploy/ entry this branch adds.

Test results on the rebased head

dotnet test --solution solutions/Z3.Linq.slnx
total : 322 | échec : 0 | réussie : 322 | ignoré : 0 | durée : 8s 204ms

Build is clean (TreatWarningsAsErrors, net10.0, Microsoft.Z3 5.1.0 from the local feed).

One honest caveat: the suite passes identically without this fix — it does not discriminate it. That is expected: the defect does not reproduce in ordinary compilation, where a captured constant's declaring type and the target object's type agree. It reproduces where they do not, i.e. across .NET Interactive submissions, each of which is its own dynamic assembly:

Field 'X' defined on type 'Submission#N' is not a field on the target object of type 'Submission#M'

The pile still resolves captured members reflectively (PropertyInfo.GetValue / FieldInfo.GetValue on a ConstantExpression target in VisitMember), so that path is unchanged. A discriminating regression test would need the two-assembly setup; if you want one in this PR I will add it, otherwise the notebook scenario stays the operative evidence.

@HowardvanRooijen

Copy link
Copy Markdown
Member

Do you want to try and rebase this onto the latest in main now that the stacked PR is merged?

@jsboige

jsboige commented Oct 31, 2026

Copy link
Copy Markdown
Author

Yes — and thank you for the pointer. I rebased onto current main locally and measured what it costs, rather than pushing blind. Summary: two API breaks, both mechanical, and one real conflict with #118 that I'd rather fix properly than paper over.

The two API breaks

  1. ExpressionVisitor.Visit(...) became internal static Expr Translate(...) — our call site is adapted.
  2. PartialEvaluator.PartialEval now only accepts a LambdaExpression; a constraint body is not one. I used the idiom your own ExpressionVisitor.VisitCall documents (wrap in Expression.Lambda(...), take the partially evaluated .Body back off), with the same rationale in the comment.

After those two adaptations the rebased branch builds clean on the current main (0 warnings, 0 errors).

The real conflict, with numbers

Your #118 added ConstantMemberTests.Solve_MemberChainThroughANull_ThrowsNamingTheExpression, which asserts that a member chain through a null names the offending expression (holder.In). Our patch's blanket PartialEval folds that subtree before the visitor ever sees it, so the caller now gets Unknown method call:Int32 Invoke[Int32]() instead.

Deterministic comparison, same machine, same SDK, full suite run twice:

Tree Result
main at 964f177 368 / 368 pass
our branch rebased onto 964f177 367 / 368 — the one failure is the null-chain diagnostic above

Why I still think the fix is worth having, and where I could be wrong. Our case is a capture that crosses .NET Interactive submissions: the constraint body holds a member access whose target object is an instance of a different dynamic assembly than the field declaring type, which is what produced Field 'X' defined on type 'Submission#N' is not a field on the target object of type 'Submission#M'. Reading captured chains at solve time, as #118 now does well, still resolves through the same reflective member access that throws across that boundary — so #118 and this patch sit on different ground, and I do not read #118 as superseding it.

What is clearly wrong is the breadth of the fold: partial-evaluating every closed subtree is a sledgehammer that also swallows the null diagnostic you just wrote. Before pushing anything I would narrow it — fold only when the subtree actually crosses a submission boundary (or leave the tree untouched and fall back when the fold is not a clean constant), so holder.In keeps its named error.

Two questions, and I am happy to be told either answer:

  1. Would you prefer the narrow fold aimed at the dynamic-assembly case, or should this wait until the Submission#N failure can be reproduced in a plain test (no .NET Interactive), which would make the whole patch easier to justify and to regress-test?
  2. If the narrow version passes the full suite, do you want it as a rebased force-push on this branch, or as a fresh PR against main so Read static members and captured member chains as constants #118's behaviour is visible in the diff?

Nothing has been pushed — the branch is still at c62253e.

jsboigeEpita and others added 4 commits November 3, 2026 20:38
feat: add nested int[][] array support to Z3.Linq theorem environment

Port the nested collection handling from Z3.LinqBinding@EPFdevelopment
(commit a94ecce) into the modern split architecture (Theorem +
ExpressionVisitor + Environment).

Changes:
- Environment.cs: add CollectionHandling enum + MultipleEnvironment class
- Theorem.cs: unify GetEnvironment(Type, prefix, isArray) with scalar
  leaf handling, nested array sort construction (Array Int (Array Int Int)),
  and ExtractCollection recursive extraction for int[][] solution rebuild
- ExpressionVisitor: nested array access (Cells[i][j]) works natively via
  existing ArrayIndex/MkSelect chaining
- SudokuGrid.cs + SudokuGridTheorem.cs: smoke test using int[][] Cells
  with standard Sudoku constraints (range 1-9, distinct rows/columns/boxes)

Verified: Theorem<SudokuGrid> with int[][] Cells compiles and solves a
9x9 Sudoku grid in ~595ms. All existing examples (Missionaries & Cannibals,
SudokuTable, ValueTuples, Symbols) pass unchanged — no regression.

dotnet build Z3.Linq.sln: 0 warnings, 0 errors.

See #1206

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@
The CollectionHandling enum { Constants, Array } and the MultipleEnvironment
class were defined but never referenced — dead code. The library hardcoded the
Array mode (Z3 array theory via MkArrayConst + Select/Store, incl. nested
int[][]). This commit resurrects the Constants mode (one Z3 constant per
element, lazily created on index access) as a selectable alternative, while
preserving Array as the default so existing behavior is unchanged.

Library (solutions/Z3.Linq/):
- Theorem.DefaultCollectionHandling property (default = Array, anti-regression).
- GetEnvironment switches on the mode: Constants -> MultipleEnvironment,
  Array -> existing MkArrayConst branch (nested-array Object branch preserved).
- ExtractCollection reads Constants-mode collections from SubEnvironments
  (incl. nested int[][] via per-row MultipleEnvironment recursion). Scalar
  conversion factored into ConvertScalarExpr, shared by both modes.
- ExpressionVisitor: new VisitArrayIndex resolves Cells[i] (and nested
  Cells[i][j] recursively) against a MultipleEnvironment, materializing one
  Z3 constant per element (Cells_i, Cells_i_j). ResolveMemberEnvironment /
  GetMemberHierarchy factored out of VisitMember to support this. Array mode
  unchanged (falls back to MkSelect).
- Z3Context.DefaultCollectionHandling propagated to NewTheorem<T>().
- Theorem<T>.Where propagates the mode across constraint chains.

Tests (new solutions/Z3.Linq.Tests/, xUnit):
- Sudoku 4x4 (int[][]) solvable in BOTH modes (Array = array theory,
  Constants = per-element constants) — keystone proving both paths work
  end-to-end for nested arrays.
- Flat int[] in Constants mode (Triple: three cells == 7).
- Hint honored in both modes.
- Default = Array guard (anti-regression).

dotnet test: 6/6 PASS. Array mode unchanged (nested int[][] Sudoku green).

Co-authored-by: jsboigeEpita <jean-sylvain.boige@epita.fr>
Co-authored-by: Claude <noreply@anthropic.com>
…mission capture) (#3)

Theorem.AssertConstraints now calls PartialEvaluator.PartialEval on each
constraint body before ExpressionVisitor.Visit. This folds host-captured
constants (locals declared outside the theorem parameter scope, e.g. in a
different .NET Interactive submission or closure) into literal
ConstantExpressions, sidestepping the reflective MemberExpression resolution
in ExpressionVisitor.VisitMember that crashed across dynamic-assembly
boundaries.

Bug: in .NET Interactive / Polyglot Notebooks, each cell compiles as a
separate dynamic assembly (Submission#N). When a constraint lambda captures
a local declared in another submission, VisitMember resolved the FieldInfo
on the lambda submission type while the closure target carried the declaring
submission type:

  System.ArgumentException: Field 'b0' defined on type 'Submission#N' is
  not a field on the target object of type 'Submission#M'

This was invisible in xUnit (single-assembly) because the closure and the
field live in the same assembly there.

The fix is a no-op for same-assembly captures (PartialEval folds them to the
same literal VisitMember would have produced via reflection), so all existing
tests pass unchanged. Subtrees referencing the theorem parameter (e.g.
t.Values[i]) are preserved (not evaluable without a parameter binding).

Validation:
- dotnet test: 6/6 passing (Z3.Linq.Tests, both CollectionHandling modes)
- polyglot-repro/CrossSubmissionCaptureRepro.ipynb: cross-submission capture
  now solves (7,8,9); before the fix it raised ArgumentException.

See #2.

Developed with AI assistance (GLM-5.2) as part of the CoursIA pedagogical
Z3.Linq series (https://github.com/jsboige/CoursIA).
Build green (0 warnings under TreatWarningsAsErrors), 371/372 tests passing. Aligns the rebased partial-eval branch with the newer upstream base: GetEnvironment/GetSolution call sites after the expression-visitor rewrite (endjin#100); ExtractCollection now uses upstream template-length sizing, the complete ReadZ3Value scalar conversion, EvaluateWithCompletion for free elements, and the no-length NotSupportedException parity. Keystone CollectionHandling tests moved to MSTest.Sdk/Shouldly.

One expected failure remains: Solve_MemberChainThroughANull_ThrowsNamingTheExpression (endjin#118) - the global PartialEval fold preempts the null member-chain path.

Co-Authored-By: Claude-Code <noreply@anthropic.com>
@jsboige
jsboige force-pushed the fix/c805-fc44dfa-partial-eval-cross-submission branch from c62253e to 7a4f0d0 Compare November 4, 2026 01:13
@jsboige

jsboige commented Nov 4, 2026

Copy link
Copy Markdown
Author

Rebased onto current main (964f177, including the #100 expression-visitor rewrite and #118).

The rebase also required porting the nested int[][] collection extraction over upstream's newer collection/template handling: template-based length sizing, the full ReadZ3Value scalar conversion, EvaluateWithCompletion for free (unconstrained) elements, and the no-length NotSupportedException parity.

@HowardvanRooijen

Copy link
Copy Markdown
Member

Thank you for this PR, the repro notebook and the detailed follow-ups. They made it much easier to find the cause. PR #43 contains three different changes, so I've split it into a stack of smaller PRs and rewritten each one in the style of the rest of the codebase:

The cross-submission capture is already fixed by #118

When a later submission uses a local from an earlier one, the constraint reaches the visitor as a member chain that starts at a constant:

value(Submission#1).<Submission#0>.b0

Before #118, VisitMember read every link of that chain from the first constant. It asked Submission#1 for b0, which only Submission#0 has, and that is the ArgumentException you reported. Since #118, it reads each link from the value of the link before it, which covers this shape.

We checked this in two ways:

  • Demo: your notebook is now demos/cross-submission-capture.cs, a single-file app with the text in English. It runs real chained Roslyn scripting submissions, prints the member chain, and solves to 7, 8, 9 on main. When we temporarily put back the old behaviour, it fails with your exact error.
  • Test: CrossAssemblyCaptureTests uses Reflection.Emit to put the two submission types in two dynamic assemblies, so it needs no new package. All three of its tests fail with the old behaviour.

So #122 adds no library fix, only the test, the demo and one comment line. We left out the general PartialEval fold because it isn't needed, and because it breaks the null-chain diagnostic that #118 added.

Nested collections (#123)

int[][], List<int[]>, List<List<int>> and deeper nesting now work as symbols. The change is in Theorem.cs only, and the expression visitor needs no change. The read-back keeps the existing behaviour:

  • It fills typed arrays.
  • It takes lengths from the template, including row lengths.
  • It fills elements that no constraint uses through model completion, as for flat arrays.
  • It throws a NotSupportedException that names a null row.

A row index chosen by a symbol, such as Cells[t.Row][0], also works. The PR adds 16 tests.

Why the Constants mode is not included

With literal indices, Z3 already reduces array selects to individual constants, so a mode with one constant per element adds no new capability. The array mode can also do more, because it supports an index chosen by a symbol. The Constants mode would also add public API that we would need to maintain. #123's description explains this too.

Sudoku (#124)

Your 9x9 example is now an Examples class with tests. It uses the same published puzzle as the existing Sudoku tests, and it solves in about 40 ms, which is the same speed as the existing example.

Because these PRs cover everything useful from #43, this PR can be closed in favour of the stack. Reviews of #122, #123 and #124 are welcome, especially if something from your downstream work is missing.

@jsboige

jsboige commented Nov 14, 2026

Copy link
Copy Markdown
Author

Superseded by #118 — closing with the measurement

Howard's note of 5 Nov is right, and I verified it firsthand rather than taking it on trust: checked out upstream/main at 964f177, dropped in CrossAssemblyCaptureTests.cs from #122 unmodified, and ran the full suite.

371 / 371 passed, 0 failed — the cross-assembly capture test included, with none of this PR's code.

Two further reasons not to push this branch:

Thank you for the careful read and the rewrite, Howard — the split made the fix and the tests better than this PR would have. Closing as superseded.

@jsboige jsboige closed this Nov 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants