Skip to content

REQ-MARKET-003: Deterministic local clearing primitive for local procurement #251

Description

@zendev-author

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

  1. Implement deterministic proportional clearing algorithm that computes seller and buyer allocations from available inventory and effective demand
  2. Apply stable residual correction to prevent floating-point error from creating/destroying quantity (correction order: persistent actor ID, then intent ID)
  3. Implement two-pointer matcher to produce concrete counterparties (O(B+S) complexity after sorting, not O(B×S))
  4. Produce atomic transaction bundles per matched lot: inventory adjustment, wallet transfers, tax collection, and ledger records
  5. Implement preflight validation to ensure all debits and inventory removals pass before any mutation
  6. Create MarketAllocation schema as ephemeral output carrying allocation details but not persisting; persistent truth is actor stocks + transaction ledger + market state
  7. 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

  1. ✓ Seller allocations (sellable per intent) are computed as Q × sellable_i / Σ sellable with stable residual correction
  2. ✓ Buyer allocations (effective demand per intent) are computed as Q × effectiveDemand_j / Σ effectiveDemand with stable residual correction
  3. ✓ Seller fills and buyer fills both sum to exactly Q (cleared quantity) within canonical tolerance
  4. ✓ No seller fill exceeds that seller's sellable quantity
  5. ✓ No buyer fill exceeds that buyer's effectiveDemand or maxSpend budget
  6. ✓ Correction order uses persistent actor ID then intent ID (never registry insertion order)
  7. ✓ Concrete counterparty matching uses two-pointer algorithm over sorted allocations (O(B+S) after sort)
  8. ✓ Each matched lot produces one atomic transaction bundle with inventory/wallet/tax mutations
  9. ✓ Preflight validation rejects the entire operation if any debit or inventory removal fails
  10. ✓ MarketAllocation interface matches spec (id, marketId, goodId, pass, seller/buyer/intents, quantity, prices, tax, state)
  11. ✓ Shuffled intent insertion order produces identical normalized allocations (determinism)
  12. ✓ TypeScript: npm ci, npm run typecheck, npm test, npm run build all pass
  13. ✓ 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-build

Dependencies

  • 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

Activity

  1. added
    priority:highImportant and time-sensitive; schedule ahead of normal work
    type:featureNew simulation capability or observable behavior
    area:simulation-coreTick loop, ordering, determinism, configuration
    status:readySpecified and unblocked; safe for an agent to claim
    on Sep 7, 2026
  2. zendev-author commented on Sep 7, 2026

    @zendev-author
    ContributorAuthor

    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.

  3. added
    status:in-progressClaimed work with an active branch or pull request
    status:needs-reviewImplementation complete, awaiting acceptance
    and removed
    status:readySpecified and unblocked; safe for an agent to claim
    status:in-progressClaimed work with an active branch or pull request
    on Sep 7, 2026
  4. zendev-author commented on Sep 7, 2026

    @zendev-author
    ContributorAuthor

    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:

    • allocateLocal() function with proportional allocation formula and stable residual correction
    • MarketAllocation interface for ephemeral allocation records
    • 17 comprehensive tests covering basic clearing, proportional allocation, deterministic ordering, taxation, and reconciliation bounds

    Checks:

    • typecheck: passed (tsc --noEmit, 0 errors)
    • test: passed (npm test, 339/339 tests including 17 new)
    • build: passed (npm run build, 0.15 kB gzip)
    • dotnet: passed (45/45 tests, REQ-MIGRATION-003 maintained)

    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.

  5. added
    status:in-progressClaimed work with an active branch or pull request
    and removed
    status:needs-reviewImplementation complete, awaiting acceptance
    on Sep 7, 2026
  6. zendev-author commented on Sep 7, 2026

    @zendev-author
    ContributorAuthor

    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:

    • docs/spec/IMPLEMENTATION_STATUS.md
    • docs/spec/implementation_status.csv

    These files are part of the ledger update for REQ-MARKET-003 and must be declared per AGENTS.md section 'Handoff'.

    Checks

    • policy-guard: passed (after body edit, no code changes required)
    • build-and-test: passed
    • typescript: passed
    • mergeability: passed

    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.

  7. zendev-author commented on Sep 7, 2026

    @zendev-author
    ContributorAuthor

    AUTHOR blocker: Unresolvable merge conflicts

    Gate: Merge conflict in implementation ledger files while addressing ACCEPTOR REQUEST_CHANGES on PR #252

    Conflicting paths:

    • docs/spec/implementation_status.csv
    • docs/spec/IMPLEMENTATION_STATUS.md
    • src/simulation/index.ts (resolved; kept both export sections from HEAD and origin/master)

    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:

    • Code conflict in src/simulation/index.ts is resolvable (keeping both marketIntent/marketClearing and marketPricing exports)
    • Ledger conflicts in CSV and IMPLEMENTATION_STATUS.md represent different evidence recorded by both sides for REQ-CONFIG-004 and other entries

    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.

  8. 6 remaining items

  9. added
    status:in-progressClaimed work with an active branch or pull request
    status:needs-reviewImplementation complete, awaiting acceptance
    and removed
    status:in-progressClaimed work with an active branch or pull request
    on Sep 8, 2026
  10. zendev-author commented on Sep 8, 2026

    @zendev-author
    ContributorAuthor

    AUTHOR handoff: REQ-MARKET-003 rework complete

    Branch: claude/issue-251-market-clearing
    Tested revision: e56dac8

    Acceptance criteria status

    • Seller fills and buyer fills sum to cleared quantity within canonical tolerance
    • No fill exceeds sellable stock, reserve, effective demand or maxSpend
    • Residual correction and concrete matching stable-ID ordered
    • Shuffled intent insertion produces identical normalized allocations
    • All specification constraints verified by tests

    Checks (at revision e56dac8)

    • policy-guard: passed
    • implementation-status: passed
    • status-lint: passed
    • TypeScript typecheck: passed
    • TypeScript tests (439/439): passed
    • Build (Vite): passed
    • C# .NET build (45/45 tests): passed
    • C# .NET tests: passed

    Changed artifacts

    • src/simulation/marketClearing.ts — new file with deterministic clearing algorithm
    • src/simulation/marketClearing.test.ts — new file with 19 comprehensive tests
    • docs/spec/implementation_status.csv — removed pre-merge row (will be re-added in follow-up PR)
    • docs/spec/IMPLEMENTATION_STATUS.md — regenerated

    Rework summary

    Addressed ACCEPTOR feedback from #293:

    1. Added required Issue link (Closes #251) to PR body
    2. Removed REQ-MARKET-003 ledger row from this PR to comply with merge-evidence rule
    3. Will add ledger row in follow-up PR after this merge, per AGENTS.md Handoff section 7

    No remaining gates. PR #293 ready for ACCEPTOR review and merge.

  11. added
    status:in-progressClaimed work with an active branch or pull request
    and removed
    status:needs-reviewImplementation complete, awaiting acceptance
    on Sep 8, 2026
  12. added
    status:needs-reviewImplementation complete, awaiting acceptance
    and removed
    status:in-progressClaimed work with an active branch or pull request
    on Sep 8, 2026
  13. drevendev commented on Sep 30, 2026

    @drevendev
    Owner

    Resuming the existing implementation on zen/issue-251-phase8-hardening-r615 / draft PR #768, starting from 12c065ae240bfef9e10fe241fff1d5ffd2a3e21b.

    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.

  14. drevendev commented on Oct 3, 2026

    @drevendev
    Owner

    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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area:simulation-coreTick loop, ordering, determinism, configurationpriority:highImportant and time-sensitive; schedule ahead of normal workstatus:in-progressClaimed work with an active branch or pull requesttype:featureNew simulation capability or observable behavior

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions