Skip to content

refactor(research): unify Formula MCTS state - #206

Merged
proerror77 merged 2 commits into
mainfrom
codex/formula-mcts-adapter-203
Jul 22, 2026
Merged

refactor(research): unify Formula MCTS state#206
proerror77 merged 2 commits into
mainfrom
codex/formula-mcts-adapter-203

Conversation

@proerror77

@proerror77 proerror77 commented Jul 22, 2026

Copy link
Copy Markdown
Owner

Change contract

Move Formula Alpha Search control state onto the existing shared hft-search-kernel: formula-mcts-checkpoint.json is the sole resumable state, while mcts-state.json and mcts-expansion-plan.json are deterministic read-only projections.

Closes #203.

Out of scope

Prediction MCTS artifact publication, collector or snapshot changes, evaluator metric redesign, cloud result publication, Paper/Live, OMS, RiskGate, and execution adapters.

Dependency / merge order

Depends on merged #185 and merged #204. No stacked PR; merge this PR directly after CI and review.

Focused validation

  • cargo test -p ploy-research --no-default-features (280 library tests + 2 CLI tests)
  • cargo clippy -p ploy-research --no-default-features --no-deps -- -D warnings
  • cargo fmt --check
  • git diff --check
  • Printed policy snapshot sha256:e98b091da59ca2878c79d817b5d774cc8f3591384730eea93b76499f0c0eea79, matching both checked-in BTC/SOL mission templates.
  • Counterexamples reject legacy versions, forged target identity, altered selection budget, reordered root, and cyclic/missing parent lineage.
  • Deterministic resume matches uninterrupted checkpoint bytes.

Rollout / rollback impact

The new Formula image writes one versioned checkpoint plus read-only projections. Mixed checkpoint writers are forbidden; legacy --alpha-search-state-json input fails with an explicit migration diagnostic. Rollback selects the previous Formula image and its prior checkpoint schema. No runtime, collector, or trading deployment changes.

Scope assessment

This is 6 files and 857 changed non-generated lines, above the 750-line assessment threshold. It remains one atomic schema rollout because the checkpoint writer, reader flag, projection contract, policy pins, and migration documentation must move together; splitting would create a new-writer/old-reader or old-writer/new-reader intermediate that cannot safely resume. The rollback unit is likewise the prior Formula image plus prior checkpoint schema. Read-only reviewers standards_review_203 and spec_review_203 approved this atomic boundary after the root-order, budget-resume, and documentation findings were fixed.

Summary by CodeRabbit

  • New Features

    • Introduced a resumable Formula MCTS checkpoint format for search workflows.
    • Added checkpoint validation to prevent invalid, altered, or legacy state from being reused.
    • Search artifacts now include the new checkpoint alongside read-only state and expansion views.
  • Bug Fixes

    • Improved consistency when resuming searches from saved checkpoints.
  • Documentation

    • Updated CI/CD guidance with the new checkpoint workflow and migration instructions.
    • Deprecated legacy alpha-search state input in favor of Formula MCTS checkpoints.

Move Formula Alpha Search state, selection, backpropagation, budget, and resume onto the shared UCT kernel adapter. Publish deterministic read-only projections and reject legacy or forged checkpoints fail closed.\n\nCloses #203
@coderabbitai

coderabbitai Bot commented Jul 22, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@proerror77, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 45 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 48672768-3c1e-4fe0-a912-40a3ee52242c

📥 Commits

Reviewing files that changed from the base of the PR and between 49edaef and 54c933c.

📒 Files selected for processing (4)
  • rust_hft/prediction-markets/config/research_missions/polymarket-btc-5m.example.json
  • rust_hft/prediction-markets/config/research_missions/polymarket-sol-5m.example.json
  • rust_hft/prediction-markets/crates/ploy-research/src/bin/monday-prediction-evaluator.rs
  • rust_hft/prediction-markets/docs/ALPHA_FACTOR_SEARCH_CICD.md
📝 Walkthrough

Walkthrough

Formula Alpha Search now uses a versioned FormulaMctsCheckpoint backed by the shared UCT kernel. Artifact projections, evaluator resume handling, validation tests, documentation, and mission snapshot identifiers are updated accordingly.

Changes

Formula MCTS checkpoint migration

Layer / File(s) Summary
Checkpoint contract and public API
rust_hft/prediction-markets/crates/ploy-research/src/alpha_search.rs, rust_hft/prediction-markets/crates/ploy-research/src/lib.rs
Introduces versioned Formula MCTS checkpoint types, validation errors, a checkpoint reader, and public re-exports.
Kernel-backed artifact generation
rust_hft/prediction-markets/crates/ploy-research/src/alpha_search.rs
Builds checkpoints through shared UCT validation, backpropagation, and selection, then generates read-only MCTS state and expansion-plan projections.
Checkpoint validation and resume tests
rust_hft/prediction-markets/crates/ploy-research/src/alpha_search.rs
Tests lineage validation, deterministic resume, prior-state merging, forged identities, and legacy checkpoint rejection.
Evaluator wiring and documented control-state contract
rust_hft/prediction-markets/crates/ploy-research/src/bin/monday-prediction-evaluator.rs, rust_hft/prediction-markets/docs/ALPHA_FACTOR_SEARCH_CICD.md, rust_hft/prediction-markets/config/research_missions/*.json
Loads and hashes Formula checkpoints, rejects legacy resume flags, documents checkpoint usage, and updates BTC and SOL mission snapshot identifiers.

Estimated code review effort: 4 (Complex) | ~60 minutes

Possibly related issues

  • proerror77/monday#184 — The checkpoint and shared-kernel architecture directly implements the issue’s Formula MCTS migration objectives.
  • proerror77/monday#189 — The legacy state cutover and explicit rejection of legacy inputs match this PR’s state migration.

Possibly related PRs

  • proerror77/monday#190 — Introduces the shared UCT kernel used by this PR’s checkpoint selection, validation, and backpropagation.
  • proerror77/monday#147 — Touches the same alpha-search artifact writers and evaluator integration paths.
  • proerror77/monday#67 — Relates to Formula/MCTS checkpoint persistence and validation semantics.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: unifying Formula MCTS state under the shared kernel.
Description check ✅ Passed The PR description matches the template and fills all required sections, including scope, dependencies, validation, rollout, and scope exception.
Linked Issues check ✅ Passed The changes satisfy #203 by moving Formula state to the shared kernel, rejecting legacy state, preserving identity, and adding deterministic resume tests.
Out of Scope Changes check ✅ Passed The included file changes appear aligned with #203 and its rollout/docs; no clearly unrelated code changes are introduced.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/formula-mcts-adapter-203

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@rust_hft/prediction-markets/crates/ploy-research/src/bin/monday-prediction-evaluator.rs`:
- Around line 2016-2021: Move the `formula_mcts_checkpoint_json` loading and
validation block using `read_formula_mcts_checkpoint` to immediately after CLI
argument parsing, before report artifacts or prediction feedback are written.
Preserve the existing panic-on-error behavior and retain the validated
`mcts_state` for later evaluation, while keeping the load-status message tied to
the checkpoint path.
- Line 118: Update the reprice-pilot artifact schema identifier from
monday.polymarket.reprice_pilot.v1 to the next version wherever it is declared
or emitted, including the artifact path around the evaluator’s schema metadata.
Keep formula_mcts_checkpoint_sha256 required in the serialized shape so new
readers can distinguish and validate the updated payload.

In `@rust_hft/prediction-markets/docs/ALPHA_FACTOR_SEARCH_CICD.md`:
- Around line 769-772: Update the documentation entry for
--alpha-search-state-json to describe it as a rejected legacy state input, not a
legacy projection. Keep the documented projection names mcts-state.json and
mcts-expansion-plan.json unchanged, and retain the explicit migration diagnostic
behavior.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: e515d137-2d6d-41ce-9cf3-0a183a0fc803

📥 Commits

Reviewing files that changed from the base of the PR and between 228ec21 and 49edaef.

📒 Files selected for processing (6)
  • rust_hft/prediction-markets/config/research_missions/polymarket-btc-5m.example.json
  • rust_hft/prediction-markets/config/research_missions/polymarket-sol-5m.example.json
  • rust_hft/prediction-markets/crates/ploy-research/src/alpha_search.rs
  • rust_hft/prediction-markets/crates/ploy-research/src/bin/monday-prediction-evaluator.rs
  • rust_hft/prediction-markets/crates/ploy-research/src/lib.rs
  • rust_hft/prediction-markets/docs/ALPHA_FACTOR_SEARCH_CICD.md

#[derive(serde::Serialize)]
struct RepricePilotSearchArtifact {
summary: AlphaSearchArtifactSummary,
formula_mcts_checkpoint_sha256: String,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Bump the reprice-pilot artifact schema version.

formula_mcts_checkpoint_sha256 is a required serialized field, but the enclosing artifact still advertises monday.polymarket.reprice_pilot.v1 at Line 571. New readers cannot distinguish old v1 payloads from the new shape and may fail on the missing field.

Suggested contract update
- schema_version: "monday.polymarket.reprice_pilot.v1",
+ schema_version: "monday.polymarket.reprice_pilot.v2",
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
formula_mcts_checkpoint_sha256: String,
schema_version: "monday.polymarket.reprice_pilot.v2",
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@rust_hft/prediction-markets/crates/ploy-research/src/bin/monday-prediction-evaluator.rs`
at line 118, Update the reprice-pilot artifact schema identifier from
monday.polymarket.reprice_pilot.v1 to the next version wherever it is declared
or emitted, including the artifact path around the evaluator’s schema metadata.
Keep formula_mcts_checkpoint_sha256 required in the serialized shape so new
readers can distinguish and validate the updated payload.

Comment thread rust_hft/prediction-markets/docs/ALPHA_FACTOR_SEARCH_CICD.md

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 49edaef14d

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

) -> Result<FormulaMctsCheckpoint, AlphaSearchArtifactError> {
if let Some(prior) = prior_state {
validate_formula_mcts_checkpoint(prior)?;
if prior.target != target || prior.side != side {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Scope the resume checkpoint to its matching target

When the evaluator receives --formula-mcts-checkpoint-json, it iterates over both non-side settlement targets and passes the same checkpoint to each writer (monday-prediction-evaluator.rs lines 2049-2055 and 2090). This identity check therefore rejects the unrelated target; the caller only logs that failure and still exits successfully, leaving that target's artifact bundle stale or missing on every legitimate resume. Previously, mismatched prior state was ignored for the other target, so the caller should pass the checkpoint only to its matching target while initializing unrelated targets without prior state.

Useful? React with 👍 / 👎.

Comment on lines +1664 to +1668
checkpoint
.nodes
.iter()
.map(|node| (node.factor_name.clone(), node.clone()))
.collect(),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Exclude stale checkpoint nodes from the expansion projection

When a resumed run no longer generates a historical candidate—for example after changing the typed LLM prior—this constructs the selectable tree from every checkpoint node rather than restricting it to the current run's metrics. A stale high-scoring leaf can consequently consume one of the 12 selections, but domain_candidates_for_target_with_guidance only expands selected names found in the current candidate set (autofactor.rs lines 2050-2056), so enough stale leaves can yield a nonempty plan that produces no guided mutations. Preserve cumulative statistics, but select only nodes represented by the current evaluation.

Useful? React with 👍 / 👎.

Comment on lines +7 to +10
use hft_search_kernel::{
backpropagate as kernel_backpropagate, select_expandable as kernel_select_expandable,
validate_tree as validate_kernel_tree, UctError, UctNode, UctStats,
};

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Include the shared kernel source in the policy snapshot

This refactor makes Formula selection and backpropagation depend on research-core/search-kernel/src/lib.rs, but current_prediction_policy_snapshot_id() hashes alpha_search.rs and a dependency graph where the local hft-search-kernel has checksum=none; it never hashes the kernel source itself. A later source-only kernel change can therefore alter governed MCTS results without changing the policy snapshot ID, allowing missions pinned to the previous behavior to pass validation. Add the kernel source to prediction_policy_sources() and cover a changed-kernel counterexample.

AGENTS.md reference: AGENTS.md:L93-L96

Useful? React with 👍 / 👎.

"legacy alpha search state `{path}` is not resumable; use --formula-mcts-checkpoint-json"
);
}
let formula_mcts_checkpoint_json = flag_value(&args, "--formula-mcts-checkpoint-json");

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reject a value-less checkpoint flag

When --formula-mcts-checkpoint-json is the final argument without a value, flag_value() returns None, so the evaluator silently starts a fresh search instead of rejecting the malformed resume request. If the same output directory is reused, this can overwrite the intended cumulative checkpoint and projections with newly initialized state. Check flag_present() and require a nonempty following value before treating the checkpoint as absent.

Useful? React with 👍 / 👎.

"Formula MCTS checkpoint contains duplicate candidate identities".to_string(),
));
}
formula_mcts_kernel_nodes(records)?;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Validate checkpoint visit propagation invariants

The checkpoint validator checks individual UctStats values and topology but not the ancestor statistics guaranteed by kernel_backpropagate. For example, a checkpoint with a synthetic root at zero visits and a child at one visit passes this call, even though the writer can never produce it; projection then reports total_visits = 0, and UCT selection calculates exploration using the forged parent count. Reject checkpoints whose root/ancestor visit counts are inconsistent with their descendants, with a targeted corrupted-state counterexample.

AGENTS.md reference: AGENTS.md:L93-L96

Useful? React with 👍 / 👎.

@proerror77
proerror77 merged commit 0bdc61e into main Jul 22, 2026
26 checks passed
@proerror77
proerror77 deleted the codex/formula-mcts-adapter-203 branch July 24, 2026 08:44
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.

Migrate Formula Alpha Search control state to the shared MCTS kernel

1 participant