Skip to content

feat: wire belief propagation into handle_match() + GATE dispatch recipe#91

Open
cryptoxdog wants to merge 3 commits into
mainfrom
feat/belief-propagation-wiring
Open

feat: wire belief propagation into handle_match() + GATE dispatch recipe#91
cryptoxdog wants to merge 3 commits into
mainfrom
feat/belief-propagation-wiring

Conversation

@cryptoxdog

@cryptoxdog cryptoxdog commented Mar 31, 2026

Copy link
Copy Markdown
Collaborator

What

Wires the belief propagation module (PR #90) into the two live integration points.

engine/handlers.py — handle_match()

Injection point: after confidence checker + causal BFS, before response = {...} assembly.

# --- Belief Propagation Re-ranking (ToTh §3) ---
if candidates_out:
    from engine.scoring.belief_propagation import rescore_candidates
    dimension_keys = scoring_assembler.last_active_dimension_names or []
    if dimension_keys:
        candidates_out = rescore_candidates(
            candidates_out,
            dimension_keys,
            prior_key="confidence",
            score_key="belief_score",
        )
        intelligence_quality = {
            "method": "entropy_penalized_composite",
            "dimensions_used": dimension_keys,
            "prior_source": "node.confidence",
        }
  • belief_score is an additive field — does not replace score. Pareto logic unchanged.
  • Guard: skips if no candidates or no active dimension names.
  • intelligence_quality added to response dict.

docs/gate_dispatch_wiring.md

Wire-up recipe for gate/engine/dispatch.py (separate GATE node repo — can't push directly).

Adds chain_confidence, chain_quality, hop_count to intelligence_quality via packet.derive() after hop trace accumulation.

Note

handlers.py is a protected file per GUARDRAILS — requires your review before merge.

Summary by CodeRabbit

  • New Features

    • Added belief propagation-based re-ranking to improve candidate ordering using chain confidence and quality metrics.
    • Integrated intelligence quality metadata into responses, providing scoring methodology and confidence information.
  • Documentation

    • Added documentation describing belief propagation scoring integration, trust derivation across hops, and quality metric calculations.

engine/handlers.py — handle_match()
  Injection point: after confidence checker + causal BFS, before response assembly.
  Block: '--- Belief Propagation Re-ranking (ToTh §3) ---'
  - Extracts dimension_keys from scoring_assembler.last_active_dimension_names
  - Calls rescore_candidates(candidates_out, dimension_keys, prior_key='confidence', score_key='belief_score')
  - Adds intelligence_quality to response dict:
      method='entropy_penalized_composite', dimensions_used, prior_source='node.confidence'
  - Guard: only runs if candidates_out non-empty AND dimension_keys non-empty
  - No change to Pareto logic — belief_score is an additive field, not a replacement

docs/gate_dispatch_wiring.md
  Wire-up recipe for gate/engine/dispatch.py (separate GATE node repo).
  Position: after PacketEnvelope.parse_obj(), before packet store write.
  Adds chain_confidence (propagate_chain), chain_quality (chain_composite),
  hop_count to intelligence_quality via packet.derive() (immutable).
  Includes trust tier table and output field reference.
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@github-actions

github-actions Bot commented Mar 31, 2026

Copy link
Copy Markdown

Too Many Files Changed
Changed: 100 files
Limit: 50 files
Action Required: Split into multiple focused PRs

PR Too Large
Lines changed: 2123
Limit: 1000 lines
Action Required: Break into smaller, atomic PRs

📋 Best Practices for Large Changes

  1. Refactoring + Features: Separate into 2 PRs
  2. Multiple Features: One PR per feature
  3. Database + Code: Separate migration from logic
  4. Generated Code: Separate from manual changes

🚫 This PR is blocked from merging until size limits are met.

@coderabbitai

coderabbitai Bot commented Mar 31, 2026

Copy link
Copy Markdown

Warning

Rate limit exceeded

@cryptoxdog has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 11 minutes and 31 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 11 minutes and 31 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 8d8751a7-40d5-423d-9b81-c045f90c62c6

📥 Commits

Reviewing files that changed from the base of the PR and between 8a0cd7a and ee67ae9.

📒 Files selected for processing (100)
  • chassis/errors.py
  • docs/gate_dispatch_wiring.md
  • engine/arbitration/engine.py
  • engine/arbitration/schema.py
  • engine/auth/capabilities.py
  • engine/boot.py
  • engine/causal/attribution.py
  • engine/causal/causal_compiler.py
  • engine/compliance/audit_persistence.py
  • engine/contract_enforcement.py
  • engine/convergence_controller_patch.py
  • engine/diagnostics/__init__.py
  • engine/diagnostics/dissimilarity.py
  • engine/diagnostics/fingerprint.py
  • engine/gds/scheduler.py
  • engine/graph/circuit_breaker.py
  • engine/graph/community_export.py
  • engine/graph/driver.py
  • engine/graph/graph_sync_client_fix.py
  • engine/graph_return_channel.py
  • engine/handlers.py
  • engine/hoprag/config.py
  • engine/hoprag/indexer.py
  • engine/inference_bridge.py
  • engine/inference_rule_registry.py
  • engine/kge/cross_dimensional_ensemble.py
  • engine/models/outcomes.py
  • engine/outcomes/schema.py
  • engine/packet/bridge.py
  • engine/packet/packet_store.py
  • engine/personas/composer.py
  • engine/personas/suppression.py
  • engine/personas/synthesis.py
  • engine/scoring/assembler.py
  • engine/scoring/belief_propagation.py
  • engine/scoring/confidence.py
  • engine/scoring/helpfulness.py
  • engine/scoring/importance.py
  • engine/scoring/pareto_integrator.py
  • engine/scoring/weight_discovery.py
  • engine/security/P2_9_llm_schemas.py
  • engine/startup_wiring.py
  • engine/state.py
  • engine/traversal/edge_merger.py
  • engine/traversal/multihop.py
  • engine/traversal/pseudo_query.py
  • l9_core/models.py
  • tests/conftest.py
  • tests/contracts/test_contracts.py
  • tests/gap_fixes/test_gap1_contract.py
  • tests/gap_fixes/test_gap2_return_channel.py
  • tests/gap_fixes/test_gap3_inference_registry.py
  • tests/gap_fixes/test_gap5_audit.py
  • tests/integration/test_admin_handler.py
  • tests/integration/test_graph_driver.py
  • tests/integration/test_handlers.py
  • tests/integration/test_hoprag_pipeline.py
  • tests/integration/test_match_handler.py
  • tests/integration/test_outcomes_handler.py
  • tests/integration/test_sync_handler.py
  • tests/invariants/test_compliance.py
  • tests/invariants/test_configuration.py
  • tests/invariants/test_trust_boundary.py
  • tests/performance/test_query_latency.py
  • tests/performance/test_sync_throughput.py
  • tests/property/test_gates_property.py
  • tests/property/test_scoring_property.py
  • tests/scoring/test_benchmark.py
  • tests/security/test_compliance_security.py
  • tests/security/test_injection.py
  • tests/test_algorithmic_upgrades.py
  • tests/test_pareto_wiring.py
  • tests/unit/test_arbitration.py
  • tests/unit/test_compliance_checker.py
  • tests/unit/test_cross_dimensional_ensemble.py
  • tests/unit/test_cypher_utils.py
  • tests/unit/test_domain_loader.py
  • tests/unit/test_edge_merger.py
  • tests/unit/test_gate_compiler.py
  • tests/unit/test_handlers_enrich_health.py
  • tests/unit/test_handlers_extended.py
  • tests/unit/test_hgkr_gds_dag.py
  • tests/unit/test_loader.py
  • tests/unit/test_multihop_traversal.py
  • tests/unit/test_outcomes.py
  • tests/unit/test_packet_bridge.py
  • tests/unit/test_parameter_resolver.py
  • tests/unit/test_persona_composer.py
  • tests/unit/test_persona_selector.py
  • tests/unit/test_persona_synthesis.py
  • tests/unit/test_sanitize.py
  • tests/unit/test_scoring_assembler.py
  • tests/unit/test_sync_and_traversal.py
  • tests/unit/test_sync_generator.py
  • tests/unit/test_traversal_assembler.py
  • tests/unit/test_wave4_state_resilience.py
  • tests/unit/test_wave6_dormant_features.py
  • tools/contract_report.py
  • tools/hoprag_benchmark.py
  • tools/validate_domain.py
📝 Walkthrough

Walkthrough

Added documentation for GATE dispatch belief propagation scoring integration and modified the match handler to conditionally apply belief propagation re-ranking to candidates, including computation of trust metrics and updated intelligence quality metadata in the response.

Changes

Cohort / File(s) Summary
Belief Propagation Integration Documentation
docs/gate_dispatch_wiring.md
New documentation describing how belief propagation scoring is wired into packet handling, including per-hop trust computation, aggregate metrics (chain_confidence, chain_quality), and intelligence quality metadata merging.
Match Handler Belief Propagation Re-ranking
engine/handlers.py
Added conditional belief propagation re-ranking step after normalization and explanation generation, with reassignment of candidate scores using score_key="belief_score" and prior_key="confidence", plus construction and inclusion of intelligence_quality metadata in the response.

Sequence Diagram

sequenceDiagram
    participant Handler as Match Handler
    participant Normalizer as Normalizer
    participant Explainer as BFS Explainer
    participant BPScorer as Belief Propagation Scorer
    participant Response as Response Builder

    Handler->>Normalizer: normalize candidates
    Normalizer-->>Handler: normalized candidates
    Handler->>Explainer: generate causal explanations
    Explainer-->>Handler: explanation data
    
    alt has_candidates && active_dimensions
        Handler->>BPScorer: rescore_candidates(score_key="belief_score"<br/>prior_key="confidence")
        BPScorer-->>Handler: re-ranked candidates with belief scores
    end
    
    Handler->>Handler: construct intelligence_quality metadata<br/>(method, dimensions, prior_source)
    Handler->>Response: include intelligence_quality in response
    Response-->>Handler: augmented response
Loading

Estimated Code Review Effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Poem

🐰 Through wires of trust and hop-by-hop grace,
We propagate belief across dispatch space,
Each candidate scored by the chain's noble song,
Where confidence and quality help us along!
Intelligence blooms in the metadata's light,
As belief scores guide our packets right. ✨

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The pull request title accurately describes the main changes: wiring belief propagation into handle_match() and documenting the GATE dispatch recipe.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/belief-propagation-wiring

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 and usage tips.

@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: 2

🧹 Nitpick comments (1)
engine/handlers.py (1)

601-605: Comment is misleading about execution order.

The comment states "Position: after confidence checker + causal BFS, before Pareto" but in the current code flow, Pareto logic (lines 473-529) executes before this belief propagation block. The clarification "Pareto operates on belief_score-ranked list in the next iteration" is accurate but the initial positioning statement is confusing.

Consider revising to:

-# Position: after confidence checker + causal BFS, before Pareto (Pareto
-# operates on belief_score-ranked list in the next iteration if enabled).
+# Position: after confidence checker + causal BFS, following Pareto.
+# (Pareto operates on belief_score-ranked list in subsequent iterations.)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@engine/handlers.py` around lines 601 - 605, Update the misleading comment in
the Belief Propagation Re-ranking block: clarify that the Pareto logic (the
Pareto section around the "Pareto" functions/logic) currently runs before the
belief propagation re-ranking code rather than after it, and state that Pareto
will operate on the belief_score-ranked list only in the next iteration; modify
the comment in the Belief Propagation section (the block labeled "Belief
Propagation Re-ranking (ToTh §3)") to reflect the actual execution order and
remove the "Position: after confidence checker + causal BFS, before Pareto"
phrasing, referencing the Pareto logic and belief propagation by name so readers
can locate the relevant code.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@docs/gate_dispatch_wiring.md`:
- Around line 18-25: The example incorrectly references
packet_with_hop.header.timeout_ms (PacketEnvelope has no header and timeout_ms
isn't a packet field); update the hop_trusts comprehension so
hop_trust_from_entry receives a real timeout source—e.g., replace
packet_with_hop.header.timeout_ms with a timeout variable supplied by the caller
(like request_context.timeout_ms or a local timeout_ms) or with an existing
packet field if one exists (ensure the variable name you use is in scope);
adjust the example line accordingly and keep hop_trusts, hop_trust_from_entry,
response_packet.hop_trace and PacketEnvelope in mind when making the change.

In `@engine/handlers.py`:
- Around line 607-622: The import of rescore_candidates from
engine.scoring.belief_propagation will raise ImportError because that
module/function is missing; either implement a new module
engine/scoring/belief_propagation.py that defines
rescore_candidates(candidates_out: list, dimension_keys: list, prior_key: str,
score_key: str) and return the rescored candidates (ensure compatibility with
the callers in handlers.py and use prior_key/score_key to read/write node
properties), or guard the call in handlers.py by feature-flagging or catching
ImportError/NotImplementedError and log the deferral (e.g., reference
scoring_assembler.last_active_dimension_names and set/omit intelligence_quality
accordingly) and add a note to DEFERRED.md; ensure you reference
rescore_candidates and engine.scoring.belief_propagation so the runtime path is
resolved.

---

Nitpick comments:
In `@engine/handlers.py`:
- Around line 601-605: Update the misleading comment in the Belief Propagation
Re-ranking block: clarify that the Pareto logic (the Pareto section around the
"Pareto" functions/logic) currently runs before the belief propagation
re-ranking code rather than after it, and state that Pareto will operate on the
belief_score-ranked list only in the next iteration; modify the comment in the
Belief Propagation section (the block labeled "Belief Propagation Re-ranking
(ToTh §3)") to reflect the actual execution order and remove the "Position:
after confidence checker + causal BFS, before Pareto" phrasing, referencing the
Pareto logic and belief propagation by name so readers can locate the relevant
code.
🪄 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: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 14987510-7ab3-403f-a8da-d5fbadc4394d

📥 Commits

Reviewing files that changed from the base of the PR and between 4c0fb58 and 8a0cd7a.

📒 Files selected for processing (2)
  • docs/gate_dispatch_wiring.md
  • engine/handlers.py

Comment thread docs/gate_dispatch_wiring.md
Comment thread engine/handlers.py
IgorBot and others added 2 commits April 3, 2026 13:11
Resolve remaining terminology-guard offenders, eliminate contract-scanner false positives in sanitized causal Cypher builders, and bring ruff back to green with bounded mechanical edits.

GMP: Phase 0-6 complete; Scope: shared-blockers remediation on fix/shared-blockers-all-prs; Blast radius: engine/tests/tools mechanical lint+contract fixes; Validation: python3 tools/contract_scanner.py=PASS, ruff check .=PASS, terminology grep=PASS; Note: .pre-commit-config.yaml present but pre-commit executable/module unavailable in this environment.
- carry forward shared-blocker cleanup onto PR #91 branch
- add belief_propagation scorer module required by handlers import
- clarify belief_score semantics as additive/new field alongside score
- fix GATE docs to use PacketEnvelope.metadata references

Verification:
- python3 tools/contract_scanner.py ✅
- ruff check . ✅
- dynamic import/runtime tests not executed here because local environment is missing neo4j package required by engine import path

GMP: Phase 0-4 complete; scoped PR91 remediation only; static verification green; runtime verification partially blocked by missing local dependency.
@sonarqubecloud

sonarqubecloud Bot commented Apr 3, 2026

Copy link
Copy Markdown

Quality Gate Failed Quality Gate failed

Failed conditions
C Reliability Rating on New Code (required ≥ A)

See analysis details on SonarQube Cloud

Catch issues before they fail your Quality Gate with our IDE extension SonarQube for IDE

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.

1 participant