Skip to content

fix(engine): require authoritative account reconciliation - #60

Merged
proerror77 merged 2 commits into
mainfrom
codex/reconciliation-account-truth
Jul 16, 2026
Merged

proerror77 merged 2 commits into
mainfrom
codex/reconciliation-account-truth

Conversation

@proerror77

@proerror77 proerror77 commented Jul 16, 2026

Copy link
Copy Markdown
Owner

Change contract

Require reconciliation truth to come from a complete, account- and venue-scoped authoritative snapshot. Export the typed account-truth facts from the engine through its metrics handoff; readiness policy remains downstream.

Out of scope

No readiness/liveness policy or endpoint behavior (#62), batch exposure policy (#61), LiveSmall promotion policy (#64), backtest, or market-data adapter change.

Dependencies and merge order

Independent; merge to main before #61 and #62.

Focused validation

  • cargo test -p hft-engine
  • cargo test -p hft-portfolio-core
  • cargo test -p hft-infra-metrics
  • cargo check -p hft-live --features clickhouse,redis,grpc --locked

Rollout / rollback

Fail closed: incomplete or identity-ambiguous account data cannot establish reconciliation truth. Revert this PR to remove the producer-side truth contract.

Scope exception

None.

Summary by CodeRabbit

  • New Features

    • Position reporting now includes realized PnL for each position.
    • Runtime status and monitoring now expose reconciliation health, risk halts, data-integrity gaps, position counts, and notional value.
    • Account state initialization now preserves historical fill information.
  • Bug Fixes

    • Improved detection of missing or unmatched fills and open orders.
    • Prevented duplicate orders and rejected private events from the wrong execution source.
    • Realized PnL is now consistently reflected in position and portfolio totals.

@coderabbitai

coderabbitai Bot commented Jul 16, 2026

Copy link
Copy Markdown

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: b031c525-50e7-47e7-841b-5f75c38d39cc

📥 Commits

Reviewing files that changed from the base of the PR and between 42ade9a and d44f218.

⛔ Files ignored due to path filters (1)
  • rust_hft/Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (11)
  • rust_hft/execution-gateway/adapters/adapter-polymarket/src/lib.rs
  • rust_hft/infra-services/core/metrics/src/lib.rs
  • rust_hft/market-core/engine/Cargo.toml
  • rust_hft/market-core/engine/src/execution_control.rs
  • rust_hft/market-core/engine/src/execution_queues.rs
  • rust_hft/market-core/engine/src/execution_worker.rs
  • rust_hft/market-core/engine/src/lib.rs
  • rust_hft/market-core/ports/src/traits.rs
  • rust_hft/market-core/runtime/src/ipc_handler.rs
  • rust_hft/market-core/runtime/src/system_builder.rs
  • rust_hft/risk-control/portfolio-core/src/lib.rs

📝 Walkthrough

Walkthrough

The PR adds per-position realized PnL propagation, duplicate-order and client-event safeguards, recent-fill reconciliation with runtime truth publication, OMS account-aware order reconciliation, and expanded engine integrity metrics.

Changes

Runtime integrity and accounting

Layer / File(s) Summary
Position realized PnL propagation
rust_hft/market-core/ports/src/traits.rs, rust_hft/risk-control/portfolio-core/src/lib.rs, rust_hft/execution-gateway/adapters/adapter-polymarket/src/lib.rs, rust_hft/market-core/runtime/src/ipc_handler.rs
Positions now store realized PnL, portfolio fills update it, and Polymarket and IPC responses propagate it.
Execution identity safeguards
rust_hft/market-core/engine/src/execution_worker.rs, rust_hft/market-core/engine/src/execution_queues.rs
Duplicate order IDs latch intake and emergency state, while mismatched private events are discarded and trigger stream recovery.
Fill and account reconciliation
rust_hft/market-core/engine/src/execution_control.rs, rust_hft/market-core/engine/src/lib.rs, rust_hft/market-core/engine/Cargo.toml
Bootstrap imports historical fill identities; reconciliation checks recent fills, account identity, and OMS order identity, then publishes runtime truth status.
Engine integrity and metrics export
rust_hft/market-core/engine/src/lib.rs, rust_hft/infra-services/core/metrics/src/lib.rs, rust_hft/market-core/runtime/src/system_builder.rs
Disconnect gaps and additional position/statistics fields are tracked, while the periodic metrics path synchronizes latency metrics directly.

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

Sequence Diagram(s)

sequenceDiagram
  participant ExecutionControlHandle
  participant ExecutionWorker
  participant Engine
  ExecutionControlHandle->>ExecutionWorker: request reconciliation snapshot
  ExecutionWorker-->>ExecutionControlHandle: return orders, positions, and recent fills
  ExecutionControlHandle->>Engine: publish reconciliation progress
  ExecutionControlHandle->>Engine: publish final runtime truth status
Loading

Possibly related PRs

  • proerror77/monday#28: Polymarket fill and fee deduplication changes relate to the new position realized-PnL and fill-accounting propagation.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/reconciliation-account-truth

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.

@proerror77
proerror77 marked this pull request as ready for review July 16, 2026 07:25
@proerror77
proerror77 merged commit 3d6cc9d into main Jul 16, 2026
21 of 22 checks passed

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

ℹ️ 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".

)),
Some(Ok(fills)) => {
for fill in fills {
let identity = (fill.order_id.clone(), fill.fill_id.clone());

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 Scope fill reconciliation by client identity

When full reconciliation runs with multiple execution clients, venue order IDs and fill IDs are not globally unique across accounts/venues (the open-order path in this change already treats client identity as part of the match). This unscoped (order_id, fill_id) key causes a legitimate fill from a second client with the same IDs to be reported as a duplicate, and the subsequent local lookup can also treat another account’s processed fill as matched. That can either block live startup incorrectly or hide an unaccounted authoritative fill; include the client/venue/account identity in the fill key used for duplicate detection and local matching.

Useful? React with 👍 / 👎.

Comment on lines +572 to +574
if self.latch_duplicate_order_id(&order_id, client_idx) {
self.stats.orders_failed += 1;
continue;

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 Track duplicate accepted orders before latching

When a second execution client successfully returns an order_id that is already tracked for another client, this branch runs after the venue accepted the order. Continuing here drops the second account's order without emitting OrderNew or retaining client-specific metadata, so emergency cancellation and later reconciliation can only route that order_id to the first client and the duplicate live order is left unmanaged. Record or explicitly cancel the accepted duplicate on client_idx before discarding it.

Useful? React with 👍 / 👎.

Comment on lines +573 to +575
order.symbol == exchange_order.symbol
&& order.venue == client.venue
&& self.order_account_map.get(&order.order_id) == client.account_id.as_ref()

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 Allow same-venue account matches without snapshot venue

In a same-venue multi-account runtime, venue_to_client is a HashMap<VenueId, usize>, so only one of two clients for the same venue can round-trip a client.venue in the worker snapshot while the other still has the correct account_id. This exact venue equality then classifies otherwise matching orders for that second account as identity conflicts/local-only and keeps startup reconciliation unhealthy. Treat an absent snapshot venue as non-conflicting when the account identity matches, or carry per-client venue identity separately.

Useful? React with 👍 / 👎.

Comment on lines +91 to +95
pub runtime_truth_observed_at_us: u64,
pub reconciliation_complete: bool,
pub reconciliation_healthy: bool,
pub risk_halted: bool,
pub data_integrity_gaps: u64,

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 Wire account-truth fields into readiness

When reconciliation is incomplete/unhealthy or the runtime is risk-halted, these new fields are populated by the engine but update_engine_statistics still drops them and assess_readiness still returns ready using only idle time and queue utilization. In operator-control or degraded-account starts this can expose /readiness as ready while the authoritative-account facts are false, so persist these values in the registry and include them in the readiness decision or exported health detail.

Useful? React with 👍 / 👎.

@proerror77
proerror77 deleted the codex/reconciliation-account-truth branch July 16, 2026 08:19
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