Repository navigation
REQ-MARKET-003: Deterministic local clearing primitive for local procurement #251
Copy link
Copy link
Labels
area:simulation-coreTick loop, ordering, determinism, configurationTick loop, ordering, determinism, configurationpriority:highImportant and time-sensitive; schedule ahead of normal workImportant and time-sensitive; schedule ahead of normal workstatus:in-progressClaimed work with an active branch or pull requestClaimed work with an active branch or pull requesttype:featureNew simulation capability or observable behaviorNew simulation capability or observable behavior
Description
Goal
Implement deterministic proportional local clearing and MarketAllocation construction for one Region, Good and local market pass, proving that seller fills and buyer fills sum to the same cleared quantity within canonical tolerance, with no fill exceeding available inventory, reserve, effective demand or budget.
Evidence
Specification: docs/spec/mirror/06 - Handoff/MARKETS_TRADE_FX_CONTRACTS.md
- Requirement ID: REQ-MARKET-003
- Registry status: READY
- Priority: P0
- Type: functional
- Dependencies: REQ-MARKET-001, REQ-CORE-002
- Section references: 7 (sellable/effectiveDemand inputs), 10 (clearing primitive), 11 (MarketAllocation output schema)
Scope
- Implement deterministic proportional clearing algorithm that computes seller and buyer allocations from available inventory and effective demand
- Apply stable residual correction to prevent floating-point error from creating/destroying quantity (correction order: persistent actor ID, then intent ID)
- Implement two-pointer matcher to produce concrete counterparties (O(B+S) complexity after sorting, not O(B×S))
- Produce atomic transaction bundles per matched lot: inventory adjustment, wallet transfers, tax collection, and ledger records
- Implement preflight validation to ensure all debits and inventory removals pass before any mutation
- Create MarketAllocation schema as ephemeral output carrying allocation details but not persisting; persistent truth is actor stocks + transaction ledger + market state
- Add comprehensive test coverage for deterministic clearing under all actor/budget/inventory combinations
Non-goals
- Do not implement order books, auctions, or strategic bidding
- Do not add market-owned inventory or warehouses
- Do not implement multi-hop pathfinding or trade topology
- Do not add FX speculation, credit mechanisms, or financial derivatives
- Do not implement Phase-4/Phase-7 settling logic (those are separate Phase handlers)
Acceptance criteria
- ✓ Seller allocations (sellable per intent) are computed as Q × sellable_i / Σ sellable with stable residual correction
- ✓ Buyer allocations (effective demand per intent) are computed as Q × effectiveDemand_j / Σ effectiveDemand with stable residual correction
- ✓ Seller fills and buyer fills both sum to exactly Q (cleared quantity) within canonical tolerance
- ✓ No seller fill exceeds that seller's sellable quantity
- ✓ No buyer fill exceeds that buyer's effectiveDemand or maxSpend budget
- ✓ Correction order uses persistent actor ID then intent ID (never registry insertion order)
- ✓ Concrete counterparty matching uses two-pointer algorithm over sorted allocations (O(B+S) after sort)
- ✓ Each matched lot produces one atomic transaction bundle with inventory/wallet/tax mutations
- ✓ Preflight validation rejects the entire operation if any debit or inventory removal fails
- ✓ MarketAllocation interface matches spec (id, marketId, goodId, pass, seller/buyer/intents, quantity, prices, tax, state)
- ✓ Shuffled intent insertion order produces identical normalized allocations (determinism)
- ✓ TypeScript: npm ci, npm run typecheck, npm test, npm run build all pass
- ✓ C#/.NET: dotnet build/test remain green (REQ-MIGRATION-003 requirement maintained)
Verification
npm ci && npm run typecheck && npm test && npm run build
dotnet restore && dotnet build --configuration Release --no-restore
dotnet test --configuration Release --no-buildDependencies
- REQ-MARKET-001: IMPLEMENTED ✓ (MarketIntent contract and budget ledger)
- REQ-CORE-002: IMPLEMENTED ✓ (Deterministic ordering and finite numbers)
- M2 gate: READY (blocks M3 work; this issue is selectable only when M2 closes)
Notes
- Section 7 (docs/spec/mirror/06 - Handoff/MARKETS_TRADE_FX_CONTRACTS.md) defines sellable_i and effectiveDemand_j inputs
- Section 11 defines MarketAllocation output schema with all required fields
- This requirement is part of M3 local markets and is indexed as one of seven planned units
- Do not implement Phase-4 or Phase-7 market passes; those are separate requirements
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
area:simulation-coreTick loop, ordering, determinism, configurationTick loop, ordering, determinism, configurationpriority:highImportant and time-sensitive; schedule ahead of normal workImportant and time-sensitive; schedule ahead of normal workstatus:in-progressClaimed work with an active branch or pull requestClaimed work with an active branch or pull requesttype:featureNew simulation capability or observable behaviorNew simulation capability or observable behavior
Activity
zendev-author commentedon Sep 7, 2026
AUTHOR claim
Role: AUTHOR
Scope: Implement REQ-MARKET-003 - Deterministic local clearing primitive
Branch: claude/issue-251-market-003-clearing
Status: status:in-progress
No known blockers. Work begins.
zendev-author commentedon Sep 7, 2026
AUTHOR handoff
Branch: claude/issue-251-market-003-clearing
Tested revision: 0065a0e
PR: #252
Implementation complete: deterministic local clearing primitive for M3 local markets.
Implementation:
Checks:
Acceptance criteria verified:
✅ Seller fills + buyer fills = cleared quantity within tolerance
✅ No fill exceeds sellable stock or effective demand
✅ Residual correction ensures floating-point accuracy
✅ Shuffled intent insertion produces identical allocations
✅ Stable ID ordering guarantees determinism
No remaining gates. Ready for ACCEPTOR review.
zendev-author commentedon Sep 7, 2026
AUTHOR handoff: Addressed ACCEPTOR feedback (round 1)
Branch: claude/issue-251-market-003-clearing
Tested revision: 0065a0e
PR: #252
Change made
Updated PR #252 body to declare complete Changed artifacts list. The scope-guard check identified two missing files in the handoff record:
These files are part of the ledger update for REQ-MARKET-003 and must be declared per AGENTS.md section 'Handoff'.
Checks
Decision
Per AUTHOR_RUNBOOK section 7, the handoff can be corrected by editing the PR body without a new commit. The scope-guard check re-ran and passed with the complete artifact list.
No remaining gates for this rework cycle.
zendev-author commentedon Sep 7, 2026
AUTHOR blocker: Unresolvable merge conflicts
Gate: Merge conflict in implementation ledger files while addressing ACCEPTOR REQUEST_CHANGES on PR #252
Conflicting paths:
Issue:
PR #252 carries ACCEPTOR REQUEST_CHANGES about incomplete handoff record. The PR body has been updated with the missing artifacts. However, master has moved ahead with 12+ commits (most recently PR #208 fixing REQ-CONFIG-004). When merging origin/master into this branch:
What would unblock: Master's ledger state must be integrated with this branch's ledger additions. Per AGENTS.md, this is a three-way merge by requirement identifier — a judgment call that belongs to either a later run that chooses to re-integrate, or the ACCEPTOR/operator understanding both sides' evidence.
Status: Setting issue #251 to status:blocked pending ledger resolution or rebase instruction.
6 remaining items
zendev-author commentedon Sep 8, 2026
AUTHOR handoff: REQ-MARKET-003 rework complete
Branch:
claude/issue-251-market-clearingTested revision:
e56dac8Acceptance criteria status
Checks (at revision e56dac8)
policy-guard: passedimplementation-status: passedstatus-lint: passedChanged artifacts
src/simulation/marketClearing.ts— new file with deterministic clearing algorithmsrc/simulation/marketClearing.test.ts— new file with 19 comprehensive testsdocs/spec/implementation_status.csv— removed pre-merge row (will be re-added in follow-up PR)docs/spec/IMPLEMENTATION_STATUS.md— regeneratedRework summary
Addressed ACCEPTOR feedback from #293:
Closes #251) to PR bodyNo remaining gates. PR #293 ready for ACCEPTOR review and merge.
REQ-MARKET-003 ledger row: Add missing provenance for merged PR #293 (#…
drevendev commentedon Sep 30, 2026
Resuming the existing implementation on
zen/issue-251-phase8-hardening-r615/ draft PR #768, starting from12c065ae240bfef9e10fe241fff1d5ffd2a3e21b.Bounded repair: finish HANDOFF-REPAIR-M4-008 maximum reserve per shared physical seller endpoint, add sensitive repository regressions (including insertion order and independent inventory buckets), and repair the failing cross-good test fixture without weakening its requirement for two actual allocations. CI #1692 currently fails because that fixture offers tools from a food producer without putting tools in its OUTPUT inventory; all other 1034 tests passed.
No new branch, economic redesign, Phase-4 changes or acceptance claim. Verification will use the real repository CI on the applied code head, not a standalone substitute algorithm.
drevendev commentedon Oct 3, 2026
Continuing PR #768 at
5d71f60d8cbddab1b6b4c53be317b6a054dbc09e: canonicalize buyer/seller order before callback evaluation and total reduction, and use exact capacities for a saturated side instead of Q*capacity/total. Add repository tests for all 24 permutations of the four-capacity large-dynamic-range witness, in both buyer- and seller-saturated markets. Preserve the landed positive-micro-lot fix. This bounded repair addresses order-dependent totals and saturated residual throws; it does NOT establish the separate fixed-absolute-epsilon guarantee for every high-magnitude binary64 recomposition. That remaining numerical question must remain explicit in the handoff rather than silently marked complete.