fix(indexer): recover provider failures and restore fast executable live routes #1464

Closed
opened 2026-10-10 06:54:16 +00:00 by PlasticDigits · 1 comment
Owner

Problem and scope

Restore useful, fast production quotes for LUNC→cUSTC, CL8Y→USTR, USTR→cUSTC and ALPHA→CL8Y, and stop transient upstream failures from repeatedly terminating the API process. Bundle provider recovery, reliable quote admission and useful-result latency into this implementation because the observed restarts repeatedly destroy the initialized in-memory quote state.

This is a concrete production defect after the cached quote/feed implementation. Related work: #1452, #1453, #1459, and the existing deployment/acceptance tracker #1456. Keep deployment/history follow-up in #1456; this issue owns the newly reproduced failure and implementation regressions. Do not reopen unrelated accounting/history repair scope here.

Current production evidence

Public, read-only requests on 2026-10-10 UTC confirmed revision c5cc674f2d32655b1f4ee7521dd5f34aa196a8ab. No wallet context, transaction signing or broadcast was used. All addresses below identify public token contracts, not reporters.

The initial corpus returned zero usable quotes in 24 requests:

Direction Requests HTTP 422 HTTP 502 HTTP 503 Useful quotes
LUNC→cUSTC 6 4 0 2 0
CL8Y→USTR 6 3 1 2 0
USTR→cUSTC 6 2 0 4 0
ALPHA→CL8Y 6 1 0 5 0
  • Initial offers: 10,000 LUNC, 1 CL8Y, 100 USTR and 1 ALPHA; default 5% protection.
  • Smaller offers: 100 LUNC, 0.01 CL8Y, 1 USTR and 0.1 ALPHA at both 1% and 30% protection. No useful quote. Native requests also used pool_only=true, matching the frontend.
  • HTTP 422 body: No eligible route within the selected protection. HTTP 503 included both proxy no available server and application Local execution quote unavailable; refresh after indexed data recovers.
  • Ordinary reused-connection error responses were approximately 280–291 ms; initial new-connection responses were 847–1009 ms, and one gateway failure took 1311 ms. These are error-response timings, not evidence of useful-quote performance or isolated backend compute cost.
  • A fresh check at 06:48:24–06:48:27 UTC still returned 422 for ALPHA→CL8Y, CL8Y→USTR and LUNC→cUSTC, then 502 for USTR→cUSTC: zero useful quotes in four further requests.
  • /health can briefly return status=ok with the expected revision while this corpus fails. Liveness/startup success is insufficient trading readiness.

Redacted operational diagnostics show repeated exits/restarts:

  • 06:37:54: block-height LCD failure because all provider circuits were open; indexer task ended and process restarted.
  • 06:38:10: LCD provider admission deferred at the checkpoint; another restart.
  • 06:38:47: a block exhausted five attempts; cursor stayed blocked and process restarted.
  • 06:39:03: another admission deferral terminated the task and restarted the process.
  • Book cycles frequently refreshed 0/22 pairs, with stale observations and absent cycle height; one cycle briefly recovered 22/22 before a subsequent indexer exit.

Provider failures and process coupling are observed. The exact reason every candidate disappears from quote admission is not yet isolated: do not assert that amount size, a particular provider, tax semantics or contract pins alone explain every 422.

Minimal reproduction

Use GET https://indexer.dex.cl8y.com/api/v1/route/solve, with exact raw integer amounts:

Asset Public identity Decimals
LUNC uluna 6
cUSTC terra1nap4dxh9tv35v0ynd9m4k6zt6c0dq6weszc4j5m564kjls56hu7qcr56ch 6
CL8Y terra16wtml2q66g82fdkx66tap0qjkahqwp4lwq3ngtygacg5q0kzycgqvhpax3 18
USTR terra1vy3kc0swag2rhn7jz6n72jp0l2ns0p6r6ez5grxq5uhj2rvs97fqfsetxv 18
ALPHA terra1x6e64es6yhauhvs3prvpdg2gkqdtfru840wgnhs935x8axr7zxkqzysuxz 6
curl --max-time 10 -sS -G 'https://indexer.dex.cl8y.com/api/v1/route/solve' \
  --data-urlencode 'token_in=terra16wtml2q66g82fdkx66tap0qjkahqwp4lwq3ngtygacg5q0kzycgqvhpax3' \
  --data-urlencode 'token_out=terra1vy3kc0swag2rhn7jz6n72jp0l2ns0p6r6ez5grxq5uhj2rvs97fqfsetxv' \
  --data-urlencode 'amount_in=1000000000000000000' \
  --data-urlencode 'max_spread=0.01'

Substitute the other public identities and raw amounts from the corpus. Pace probes below API limits; include first connections and reused connections, and record status plus useful output rather than response completion alone.

Current codebase and why changes are needed

Reviewed the deployed revision above as well as local source revision 736be444100ba84887a6619336c83d2848258884; do not confuse local passing tests with deployed acceptance.

  • LcdClient clones share endpoint health, rate/concurrency admission and circuit state. It distinguishes AdmissionDeferred, attempted upstream failures, malformed contract-local responses and historical-height failures. Quote ingestion uses additional paced background admission; investigate fairness between checkpoint reads, reserves, books, configuration, token/wallet policy and independent reference workers, including permits held while awaiting pacing.
  • poller.rs already retries a failed latest-height read. In contrast, errors from verify_checkpoint_unchanged return from the indexer task, and block retry exhaustion also returns. block_indexer.rs preserves the checkpoint on failure, but treats several error classes through the same attempt/exhaustion path.
  • main.rs::run_server selects between indexer completion and API completion. When the indexer returns, the process logs shutdown and exits, interrupting an otherwise running API and resetting local snapshots/caches on restart.
  • Scheduled quote admission validates factory/asset identities, pause/blacklist/whitelist/code pins, tax/hooks and actor inventory. Reserve refresh and configuration publication have separate schedules and epochs; wrapper observations are independent. Failed prerequisites must remain explicit and safely bounded.
  • The local solver evaluates initialized snapshots and returns positive net output with execution operations, per-hop/final floors and generation metadata. Its generic 422 can cover absent eligible candidates or a failure in candidate/final-response admission; distinguish infrastructure-unavailable evidence from a genuinely infeasible protected trade internally.
  • Pool-only observations and compatible hybrid generations are persisted separately after migration 20261009145300. That migration was applied through a standalone job, with original history preserved. Re-running startup migrations or widening runtime privileges is not a solution to these later failures.

Existing source-level provider/local quote tests pass, yet production cannot supply a trade. Recovery must preserve the API and allow scheduled ingestion to rebuild eligible data, without hiding accounting failures, accepting stale quotes or bypassing constraints. Speed work must measure useful output under actual socket/browser transport, not fast 422/503 responses.

Relevant files

  • Lifecycle and checkpoint handling: indexer/src/main.rs, indexer/src/indexer/poller.rs, block_indexer.rs, parser.rs, indexer/src/db/queries/state.rs.
  • Provider ownership/admission/classification: indexer/src/lcd/mod.rs, provider_pool.rs, chain_identity.rs, pair_discovery_state.rs, indexer/src/config.rs.
  • Observations and eligibility: indexer/src/indexer/book_snapshot.rs, indexer/src/db/queries/pair_reserves.rs, indexer/src/api/local_quote/admission.rs, ingestion.rs, actor_inventory.rs, tax.rs, local_hook_pricing.rs, local_wrapper_quote.rs, local_reference_quote.rs.
  • Quote selection/cache/API: indexer/src/api/local_quote.rs, local_quote/skeletons.rs, modes.rs, reverse.rs, route_solver.rs, route_solve_progress.rs, mod.rs.
  • Client transport/confirmation: frontend-dapp/src/services/indexer/client.ts, utils/cw20RouteSolveQuote.ts, localRouteQuote.ts, quoteDebounce.ts, pages/SwapPage.tsx, components/trade/TradeMarketOrderPanel.tsx.
  • Existing regressions: indexer/tests/indexer_ingestion_hardening.rs, book_snapshot_loop.rs, route_local_quotes_1452.rs, api_route_solve.rs, api_route_exact_output.rs, api_route_tax_funding1381.rs, api_health.rs; scripts/qa/browser-local-quotes-1452.cjs.
  • Contracts/runbooks: docs/route-solver.md, docs/runbooks/indexer-database-isolation.md, skills/AGENTS_LOCAL_SWAP_QUOTES.md, AGENTS_LIQUIDITY_FEED.md, AGENTS_PAIR_DISCOVERY_CACHE.md, AGENTS_CHAIN_ATTESTATION.md.
  1. Reproduce checkpoint admission deferral, all-circuits-open and attempted provider failures under concurrent ingestion. Classify retryable availability/capacity separately from reorg, parser/accounting corruption, unsafe database configuration and genuine permanent failure. Pause/retry the same height with bounded cancellation-aware scheduling; never advance or successfully skip it.
  2. Supervise indexing separately from serving qualified cached API data. Transient provider pressure must not terminate the API or erase initialization. Fatal integrity conditions must remain visible and halt unsafe work; do not swallow them in an infinite success loop or label stalled accounting healthy.
  3. Measure producer budgets and capability-specific failures. Bound rate/concurrency/bytes/time/half-open probes and remove starvation without introducing new unbounded queues or independent clients that evade shared provider admission. Preserve pool observations through unrelated book failures and exact historical-header validation.
  4. Trace candidate loss through each admission phase using fixed, low-cardinality internal reasons and generation/age/count metrics. Add deterministic reproductions for any schema/pin/tax/actor-inventory incompatibility discovered; repair supported semantics rather than blanket bypassing validation or claiming larger protection fixes unavailable data.
  5. Publish completed independent observations incrementally, invalidate only the required affected state, and rebuild safely after restart. Keep known wallet blocks, authoritative inventory recovery and confirmation context intact. A healthy alternative must remain eligible when an unrelated pair/provider fails.
  6. Benchmark before optimizing the fast path, lock contention, skeleton/result cache reuse, deeper-job coalescing and client connection/debounce behavior. Keep direct/two-hop initial output ahead of deeper search. If regional RTT already consumes the latency budget, address transport/serving placement safely and report that limit; a handler-only benchmark cannot establish the end-to-end requirement.

Constraints and guardrails

  • Preserve LQ1452-1–10, LF1453-1–10, PD1394-1–10, NET1392-1–10 and DB1396-1–10. All quote/progress/reference/refresh/preflight/confirmation requests use qualified local observations and trigger zero RPC/LCD/network validation. Only independently scheduled ingestion owns observations.
  • Preserve NE1398, RT1381 and LG1390: exact authorized gross wallet debit, route-local tax funding, positive post-hook/final receive floors, pause/freeze/blacklist exclusions and authenticated refund ownership. Do not broaden unsupported semantics through gross or wallet-funded fallbacks.
  • No inflated TTLs, timestamp renewal on failed reads, mixed pool/book generations, current-state historical reconstruction, false zero output or invented price/impact. No linear scaling of executable cached quotes.
  • Shared provider limits remain shared; deterministic contract rejection stays pair-local where appropriate. Wrong-chain, ignored/mismatched height, overflow, malformed bodies and unsupported hook/tax modes fail closed. Reorg and accounting failures are never downgraded to retryable success.
  • Runtime remains least privilege and never migrates. Integration processes own disposable databases; no production seeding, truncation, role escalation or migration-history edits.
  • No new retail diagnostic controls or arbitrary smaller-size advice. Publish only bounded, redacted technical evidence: no reporter identities, conversations, screenshots, actor identifiers/digests, wallet histories, private endpoint URLs or credentials. Render untrusted input as text.

Acceptance criteria

  • AC1: With fresh eligible liquidity and supported configuration, all four directions return positive executable net quotes at the documented small and ordinary sizes. Assert route operations, raw units, expiry/generation and positive floors; a 200 topology-only response is insufficient. A genuine size/protection failure remains correctly rejected.
  • AC2: Under repeated provider capacity deferrals/outages and later recovery, the API remains available, the checkpoint never skips a failed height, and the same height resumes exactly once without process restart storms or duplicated accounting.
  • AC3: Checkpoint integrity, reorg and persistent parser/accounting failures still halt unsafe progress with truthful readiness. Shutdown/cancellation/leadership changes release resources and do not leave orphan workers.
  • AC4: Healthy provider/pair observations survive unrelated component failures; bounded failover/recovery rebuilds supported quote coverage before required observations expire. No stale time relabeling or incompatible generations.
  • AC5: Missing/stale/unsupported input and genuine protection rejection have accurate internal classifications and one appropriate public blocker; infrastructure loss is not automatically presented as an amount problem.
  • AC6: Every representative initialized hit and initialized quote-result miss produces useful output in strictly <250 ms, including normal socket and desktop/phone browser transport. Record p50/p95/p99/max, sample counts, cold initialization, new/reused connections, initial/later results and regional RTT separately. Do not count 202/loading/error responses or waive an executed latency failure.
  • AC7: Instrument throwing/counting providers across GET, /best, POST, progress, reference, refresh and reviewed-route preparation; zero request-triggered upstream calls. Background cadence is bounded and cannot be accelerated by request traffic.
  • AC8: Amount/direction/mode/actor/tier/spread/maker-cap/funding/namespace/generation cache isolation, coalescing and refresh/signing races pass without changing the reviewed transaction or weakening the nonwaivable ≥99% guard.
  • AC9: Add a focused verifier for this issue, update operational recovery/readiness docs, run the regression corpus against the deployed revision and demonstrate sustained stability through multiple admission/freshness cycles, including a bounded outage/recovery trial. Keep #1456 operational items separately scoped and open where evidence remains missing.

Functional test plan: all paths

Scenario Required checks
Four reported routes; small/ordinary/larger sizes Both directions where supported, exact 6/18-decimal conversion, sufficient/insufficient liquidity, net ranking, per-hop/final floors; compare candidate admission at one fixed observation.
Native LUNC/USTC and wrapped cLUNC/cUSTC Wrap-enter, unwrap-exit and direct wrapper modes; fees/input conversion once; positive signed floors or explicit unsupported block.
GET, /best, POST, progress, receive-target Pool-only, automatic hybrid, declared splits, direct/two-hop/longer paths, reverse sizing, tax/hook semantics; no remote fallback and no silent plan substitution.
Anonymous and synthetic named actor contexts Conservative unknown fee context versus fresh supported named context; tax identity/cap/cooldown/AutoLP policy, blocked and explicitly unblocked cases; exact wallet budget.
Checkpoint hash/body/transactions/latest-height failures Rate/concurrency deferral, circuits open, transport error, parser/database failure and reorg independently; cursor unchanged, truthful halt state and idempotent replay after recovery.
Primary/secondary/tertiary and all-provider outage Bounded 403/429/408/5xx/timeout handling, Retry-After, one half-open probe, capability/height mismatch, healthy alternate, recovery without restart storm.
Pool success with fee/bid/ask failure Preserve original independent pool observation and separately compatible hybrid generation; stale required component cannot produce a quote.
Admission publication/restart/cache expiry Empty/partial/full inventory, incremental slice completion, failed token/config/actor phase, warm result/skeleton caches, controlled TTL boundaries and original timestamps.
Same-key bursts and mixed traffic Coalescing, graph/book/result/job/namespace bounds, scheduler fairness, HTTP rate/body limits, cancellation, leadership loss and no hidden query backlog.
Swap/Trade desktop/phone Ordinary browser input-to-useful-result, token reversal, typing, disconnect/reconnect, confirmation/refresh/deeper-search race, reviewed operations pinned.

Use deterministic mocked providers and clocks, real disposable Postgres/socket fixtures, and funded LocalTerra execution for quote/settlement parity. Production verification stays read-only; do not broadcast mainnet transactions for reproduction.

Attack, hack and abuse test plan

  • Flood dense/dust graphs, vary amount/target/actor/tier/chain/factory/spread keys and repeatedly cancel: bounded memory/CPU/provider work, rate limits, single-flight cleanup and no admission budget reset or cache poisoning.
  • Malicious endpoints: wrong chain/block hash, stale/future/out-of-order responses, ignored/mismatched height headers, persistent 429 with extreme Retry-After, slow/oversized/malformed bodies and deterministic contract rejection. Preserve attestation, failure scope and bounded recovery; never let a hostile endpoint make stalled ingestion look healthy.
  • Spoofed symbols/contracts, forged routes, repeated capable assets, invalid maker plans and misleading USD marks: canonical identities and factory provenance, executable integer economics and exact operation validation.
  • Zero/negative/huge/overflow amounts, mixed/hostile decimals, rounding collisions, nonlinear books/taxes/hooks and dust floors: checked wide integer arithmetic; no float-derived execution or cached linear extrapolation.
  • Privilege and accounting attacks: runtime DDL/ledger/marker mutations denied; QA cannot target shared production; reorg/parser corruption cannot be swallowed; replay cannot duplicate swaps/fees/listing inventory or advance past omissions.
  • Known-block inventory eviction, partial authoritative recovery, unsupported cooldown/AutoLP/hook changes and tax-funding tampering: quarantine/fail closed, no wallet debit or signing bypass.
  • Confirmation race and forced Expert settings: no stale route substitution, missing floor, ≥99% override or context leakage between users.
  • Hostile errors/symbols/URLs/log fields: no XSS, SSRF, secret logging, unbounded labels or publication of actor identifiers/digests; private endpoints stay redacted.

Verification criteria and completed investigation

Completed before filing:

  • Reviewed the deployed lifecycle/checkpoint/provider/admission code and existing #1452/#1453/#1456 issues; no standalone open restart/circuit report was found by fj searches.
  • Public corpus: 0/24 useful quotes, plus 0/4 on the fresh check; HTTP failures remain FAIL. Redacted log evidence confirms restarts. No claim of a complete root cause or zero upstream calls from these live probes.
  • Local revision 736be444100ba84887a6619336c83d2848258884: cargo test --locked --manifest-path indexer/Cargo.toml --lib lcd:: -- --test-threads=1 — 55 passed, 0 failed, 1 ignored. The ignored benchmark was executed separately with cargo test --locked --manifest-path indexer/Cargo.toml --lib lcd::pair_discovery_state::tests::pair_discovery_cache_benchmark -- --ignored --nocapture --test-threads=1: 1 passed, 0 failed. Its cache microbenchmark does not measure useful API quote latency.
  • Same command with filter api::local_quote — 45 passed, 0 failed. These are existing baseline tests, not regression proof for this defect or the newer deployed revision.

Implementation verification must run the new focused verifier and applicable make verify-issue-1452, verify-issue-1453, verify-issue-1394, verify-issue-1392 and verify-issue-1396 checks. Record exact revision, UTC times, commands, counts, original observation ages/generations, checkpoint/hash, bounded provider/cache/job counters and latency distributions/maxima. Count actual upstream calls; verify browser/socket useful output and settlement parity rather than status codes alone.

Complete feasible checks first. Unavailable deployment, history, device or fixture checks may be explicit SKIP with the precise missing evidence and remaining scope; they do not block issue creation or implementation review. Executed failures remain FAIL until corrected and successfully rerun. Passing local tests, liveness or one successful quote never establish sustained deployed trading acceptance. Publish sanitized technical findings only; no conversation or reporter data is part of this issue.

## Problem and scope Restore useful, fast production quotes for **LUNC→cUSTC, CL8Y→USTR, USTR→cUSTC and ALPHA→CL8Y**, and stop transient upstream failures from repeatedly terminating the API process. Bundle provider recovery, reliable quote admission and useful-result latency into this implementation because the observed restarts repeatedly destroy the initialized in-memory quote state. This is a concrete production defect after the cached quote/feed implementation. Related work: [#1452](https://git.cl8y.com/code/cl8y-dex-terraclassic/issues/1452), [#1453](https://git.cl8y.com/code/cl8y-dex-terraclassic/issues/1453), [#1459](https://git.cl8y.com/code/cl8y-dex-terraclassic/issues/1459), and the existing deployment/acceptance tracker [#1456](https://git.cl8y.com/code/cl8y-dex-terraclassic/issues/1456). Keep deployment/history follow-up in #1456; this issue owns the newly reproduced failure and implementation regressions. Do not reopen unrelated accounting/history repair scope here. ## Current production evidence Public, read-only requests on **2026-10-10 UTC** confirmed revision `c5cc674f2d32655b1f4ee7521dd5f34aa196a8ab`. No wallet context, transaction signing or broadcast was used. All addresses below identify public token contracts, not reporters. The initial corpus returned **zero usable quotes in 24 requests**: | Direction | Requests | HTTP 422 | HTTP 502 | HTTP 503 | Useful quotes | | --- | ---: | ---: | ---: | ---: | ---: | | LUNC→cUSTC | 6 | 4 | 0 | 2 | 0 | | CL8Y→USTR | 6 | 3 | 1 | 2 | 0 | | USTR→cUSTC | 6 | 2 | 0 | 4 | 0 | | ALPHA→CL8Y | 6 | 1 | 0 | 5 | 0 | - Initial offers: 10,000 LUNC, 1 CL8Y, 100 USTR and 1 ALPHA; default 5% protection. - Smaller offers: 100 LUNC, 0.01 CL8Y, 1 USTR and 0.1 ALPHA at both 1% and 30% protection. No useful quote. Native requests also used `pool_only=true`, matching the frontend. - HTTP 422 body: `No eligible route within the selected protection`. HTTP 503 included both proxy `no available server` and application `Local execution quote unavailable; refresh after indexed data recovers`. - Ordinary reused-connection error responses were approximately **280–291 ms**; initial new-connection responses were **847–1009 ms**, and one gateway failure took **1311 ms**. These are **error-response timings**, not evidence of useful-quote performance or isolated backend compute cost. - A fresh check at **06:48:24–06:48:27 UTC** still returned 422 for ALPHA→CL8Y, CL8Y→USTR and LUNC→cUSTC, then 502 for USTR→cUSTC: **zero useful quotes in four further requests**. - `/health` can briefly return `status=ok` with the expected revision while this corpus fails. Liveness/startup success is insufficient trading readiness. Redacted operational diagnostics show repeated exits/restarts: - 06:37:54: block-height LCD failure because all provider circuits were open; indexer task ended and process restarted. - 06:38:10: `LCD provider admission deferred` at the checkpoint; another restart. - 06:38:47: a block exhausted five attempts; cursor stayed blocked and process restarted. - 06:39:03: another admission deferral terminated the task and restarted the process. - Book cycles frequently refreshed **0/22** pairs, with stale observations and absent cycle height; one cycle briefly recovered **22/22** before a subsequent indexer exit. Provider failures and process coupling are observed. The exact reason every candidate disappears from quote admission is **not yet isolated**: do not assert that amount size, a particular provider, tax semantics or contract pins alone explain every 422. ### Minimal reproduction Use `GET https://indexer.dex.cl8y.com/api/v1/route/solve`, with exact raw integer amounts: | Asset | Public identity | Decimals | | --- | --- | ---: | | LUNC | `uluna` | 6 | | cUSTC | `terra1nap4dxh9tv35v0ynd9m4k6zt6c0dq6weszc4j5m564kjls56hu7qcr56ch` | 6 | | CL8Y | `terra16wtml2q66g82fdkx66tap0qjkahqwp4lwq3ngtygacg5q0kzycgqvhpax3` | 18 | | USTR | `terra1vy3kc0swag2rhn7jz6n72jp0l2ns0p6r6ez5grxq5uhj2rvs97fqfsetxv` | 18 | | ALPHA | `terra1x6e64es6yhauhvs3prvpdg2gkqdtfru840wgnhs935x8axr7zxkqzysuxz` | 6 | ```sh curl --max-time 10 -sS -G 'https://indexer.dex.cl8y.com/api/v1/route/solve' \ --data-urlencode 'token_in=terra16wtml2q66g82fdkx66tap0qjkahqwp4lwq3ngtygacg5q0kzycgqvhpax3' \ --data-urlencode 'token_out=terra1vy3kc0swag2rhn7jz6n72jp0l2ns0p6r6ez5grxq5uhj2rvs97fqfsetxv' \ --data-urlencode 'amount_in=1000000000000000000' \ --data-urlencode 'max_spread=0.01' ``` Substitute the other public identities and raw amounts from the corpus. Pace probes below API limits; include first connections and reused connections, and record status plus useful output rather than response completion alone. ## Current codebase and why changes are needed Reviewed the deployed revision above as well as local source revision `736be444100ba84887a6619336c83d2848258884`; do not confuse local passing tests with deployed acceptance. - `LcdClient` clones share endpoint health, rate/concurrency admission and circuit state. It distinguishes `AdmissionDeferred`, attempted upstream failures, malformed contract-local responses and historical-height failures. Quote ingestion uses additional paced background admission; investigate fairness between checkpoint reads, reserves, books, configuration, token/wallet policy and independent reference workers, including permits held while awaiting pacing. - `poller.rs` already retries a failed latest-height read. In contrast, errors from `verify_checkpoint_unchanged` return from the indexer task, and block retry exhaustion also returns. `block_indexer.rs` preserves the checkpoint on failure, but treats several error classes through the same attempt/exhaustion path. - `main.rs::run_server` selects between indexer completion and API completion. When the indexer returns, the process logs shutdown and exits, interrupting an otherwise running API and resetting local snapshots/caches on restart. - Scheduled quote admission validates factory/asset identities, pause/blacklist/whitelist/code pins, tax/hooks and actor inventory. Reserve refresh and configuration publication have separate schedules and epochs; wrapper observations are independent. Failed prerequisites must remain explicit and safely bounded. - The local solver evaluates initialized snapshots and returns positive net output with execution operations, per-hop/final floors and generation metadata. Its generic 422 can cover absent eligible candidates or a failure in candidate/final-response admission; distinguish infrastructure-unavailable evidence from a genuinely infeasible protected trade internally. - Pool-only observations and compatible hybrid generations are persisted separately after migration `20261009145300`. That migration was applied through a standalone job, with original history preserved. Re-running startup migrations or widening runtime privileges is not a solution to these later failures. Existing source-level provider/local quote tests pass, yet production cannot supply a trade. Recovery must preserve the API and allow scheduled ingestion to rebuild eligible data, without hiding accounting failures, accepting stale quotes or bypassing constraints. Speed work must measure useful output under actual socket/browser transport, not fast 422/503 responses. ## Relevant files - Lifecycle and checkpoint handling: `indexer/src/main.rs`, `indexer/src/indexer/poller.rs`, `block_indexer.rs`, `parser.rs`, `indexer/src/db/queries/state.rs`. - Provider ownership/admission/classification: `indexer/src/lcd/mod.rs`, `provider_pool.rs`, `chain_identity.rs`, `pair_discovery_state.rs`, `indexer/src/config.rs`. - Observations and eligibility: `indexer/src/indexer/book_snapshot.rs`, `indexer/src/db/queries/pair_reserves.rs`, `indexer/src/api/local_quote/admission.rs`, `ingestion.rs`, `actor_inventory.rs`, `tax.rs`, `local_hook_pricing.rs`, `local_wrapper_quote.rs`, `local_reference_quote.rs`. - Quote selection/cache/API: `indexer/src/api/local_quote.rs`, `local_quote/skeletons.rs`, `modes.rs`, `reverse.rs`, `route_solver.rs`, `route_solve_progress.rs`, `mod.rs`. - Client transport/confirmation: `frontend-dapp/src/services/indexer/client.ts`, `utils/cw20RouteSolveQuote.ts`, `localRouteQuote.ts`, `quoteDebounce.ts`, `pages/SwapPage.tsx`, `components/trade/TradeMarketOrderPanel.tsx`. - Existing regressions: `indexer/tests/indexer_ingestion_hardening.rs`, `book_snapshot_loop.rs`, `route_local_quotes_1452.rs`, `api_route_solve.rs`, `api_route_exact_output.rs`, `api_route_tax_funding1381.rs`, `api_health.rs`; `scripts/qa/browser-local-quotes-1452.cjs`. - Contracts/runbooks: `docs/route-solver.md`, `docs/runbooks/indexer-database-isolation.md`, `skills/AGENTS_LOCAL_SWAP_QUOTES.md`, `AGENTS_LIQUIDITY_FEED.md`, `AGENTS_PAIR_DISCOVERY_CACHE.md`, `AGENTS_CHAIN_ATTESTATION.md`. ## Recommended direction 1. Reproduce checkpoint admission deferral, all-circuits-open and attempted provider failures under concurrent ingestion. Classify retryable availability/capacity separately from reorg, parser/accounting corruption, unsafe database configuration and genuine permanent failure. Pause/retry the same height with bounded cancellation-aware scheduling; never advance or successfully skip it. 2. Supervise indexing separately from serving qualified cached API data. Transient provider pressure must not terminate the API or erase initialization. Fatal integrity conditions must remain visible and halt unsafe work; do not swallow them in an infinite success loop or label stalled accounting healthy. 3. Measure producer budgets and capability-specific failures. Bound rate/concurrency/bytes/time/half-open probes and remove starvation without introducing new unbounded queues or independent clients that evade shared provider admission. Preserve pool observations through unrelated book failures and exact historical-header validation. 4. Trace candidate loss through each admission phase using fixed, low-cardinality internal reasons and generation/age/count metrics. Add deterministic reproductions for any schema/pin/tax/actor-inventory incompatibility discovered; repair supported semantics rather than blanket bypassing validation or claiming larger protection fixes unavailable data. 5. Publish completed independent observations incrementally, invalidate only the required affected state, and rebuild safely after restart. Keep known wallet blocks, authoritative inventory recovery and confirmation context intact. A healthy alternative must remain eligible when an unrelated pair/provider fails. 6. Benchmark before optimizing the fast path, lock contention, skeleton/result cache reuse, deeper-job coalescing and client connection/debounce behavior. Keep direct/two-hop initial output ahead of deeper search. If regional RTT already consumes the latency budget, address transport/serving placement safely and report that limit; a handler-only benchmark cannot establish the end-to-end requirement. ## Constraints and guardrails - Preserve **LQ1452-1–10, LF1453-1–10, PD1394-1–10, NET1392-1–10 and DB1396-1–10**. All quote/progress/reference/refresh/preflight/confirmation requests use qualified local observations and trigger **zero RPC/LCD/network validation**. Only independently scheduled ingestion owns observations. - Preserve **NE1398, RT1381 and LG1390**: exact authorized gross wallet debit, route-local tax funding, positive post-hook/final receive floors, pause/freeze/blacklist exclusions and authenticated refund ownership. Do not broaden unsupported semantics through gross or wallet-funded fallbacks. - No inflated TTLs, timestamp renewal on failed reads, mixed pool/book generations, current-state historical reconstruction, false zero output or invented price/impact. No linear scaling of executable cached quotes. - Shared provider limits remain shared; deterministic contract rejection stays pair-local where appropriate. Wrong-chain, ignored/mismatched height, overflow, malformed bodies and unsupported hook/tax modes fail closed. Reorg and accounting failures are never downgraded to retryable success. - Runtime remains least privilege and never migrates. Integration processes own disposable databases; no production seeding, truncation, role escalation or migration-history edits. - No new retail diagnostic controls or arbitrary smaller-size advice. Publish only bounded, redacted technical evidence: no reporter identities, conversations, screenshots, actor identifiers/digests, wallet histories, private endpoint URLs or credentials. Render untrusted input as text. ## Acceptance criteria - [ ] AC1: With fresh eligible liquidity and supported configuration, all four directions return positive executable net quotes at the documented small and ordinary sizes. Assert route operations, raw units, expiry/generation and positive floors; a 200 topology-only response is insufficient. A genuine size/protection failure remains correctly rejected. - [ ] AC2: Under repeated provider capacity deferrals/outages and later recovery, the API remains available, the checkpoint never skips a failed height, and the same height resumes exactly once without process restart storms or duplicated accounting. - [ ] AC3: Checkpoint integrity, reorg and persistent parser/accounting failures still halt unsafe progress with truthful readiness. Shutdown/cancellation/leadership changes release resources and do not leave orphan workers. - [ ] AC4: Healthy provider/pair observations survive unrelated component failures; bounded failover/recovery rebuilds supported quote coverage before required observations expire. No stale time relabeling or incompatible generations. - [ ] AC5: Missing/stale/unsupported input and genuine protection rejection have accurate internal classifications and one appropriate public blocker; infrastructure loss is not automatically presented as an amount problem. - [ ] AC6: **Every representative initialized hit and initialized quote-result miss produces useful output in strictly <250 ms**, including normal socket and desktop/phone browser transport. Record p50/p95/p99/max, sample counts, cold initialization, new/reused connections, initial/later results and regional RTT separately. Do not count 202/loading/error responses or waive an executed latency failure. - [ ] AC7: Instrument throwing/counting providers across GET, `/best`, POST, progress, reference, refresh and reviewed-route preparation; **zero request-triggered upstream calls**. Background cadence is bounded and cannot be accelerated by request traffic. - [ ] AC8: Amount/direction/mode/actor/tier/spread/maker-cap/funding/namespace/generation cache isolation, coalescing and refresh/signing races pass without changing the reviewed transaction or weakening the nonwaivable ≥99% guard. - [ ] AC9: Add a focused verifier for this issue, update operational recovery/readiness docs, run the regression corpus against the deployed revision and demonstrate sustained stability through multiple admission/freshness cycles, including a bounded outage/recovery trial. Keep #1456 operational items separately scoped and open where evidence remains missing. ## Functional test plan: all paths | Scenario | Required checks | | --- | --- | | Four reported routes; small/ordinary/larger sizes | Both directions where supported, exact 6/18-decimal conversion, sufficient/insufficient liquidity, net ranking, per-hop/final floors; compare candidate admission at one fixed observation. | | Native LUNC/USTC and wrapped cLUNC/cUSTC | Wrap-enter, unwrap-exit and direct wrapper modes; fees/input conversion once; positive signed floors or explicit unsupported block. | | GET, `/best`, POST, progress, receive-target | Pool-only, automatic hybrid, declared splits, direct/two-hop/longer paths, reverse sizing, tax/hook semantics; no remote fallback and no silent plan substitution. | | Anonymous and synthetic named actor contexts | Conservative unknown fee context versus fresh supported named context; tax identity/cap/cooldown/AutoLP policy, blocked and explicitly unblocked cases; exact wallet budget. | | Checkpoint hash/body/transactions/latest-height failures | Rate/concurrency deferral, circuits open, transport error, parser/database failure and reorg independently; cursor unchanged, truthful halt state and idempotent replay after recovery. | | Primary/secondary/tertiary and all-provider outage | Bounded 403/429/408/5xx/timeout handling, Retry-After, one half-open probe, capability/height mismatch, healthy alternate, recovery without restart storm. | | Pool success with fee/bid/ask failure | Preserve original independent pool observation and separately compatible hybrid generation; stale required component cannot produce a quote. | | Admission publication/restart/cache expiry | Empty/partial/full inventory, incremental slice completion, failed token/config/actor phase, warm result/skeleton caches, controlled TTL boundaries and original timestamps. | | Same-key bursts and mixed traffic | Coalescing, graph/book/result/job/namespace bounds, scheduler fairness, HTTP rate/body limits, cancellation, leadership loss and no hidden query backlog. | | Swap/Trade desktop/phone | Ordinary browser input-to-useful-result, token reversal, typing, disconnect/reconnect, confirmation/refresh/deeper-search race, reviewed operations pinned. | Use deterministic mocked providers and clocks, real disposable Postgres/socket fixtures, and funded LocalTerra execution for quote/settlement parity. Production verification stays read-only; do not broadcast mainnet transactions for reproduction. ## Attack, hack and abuse test plan - Flood dense/dust graphs, vary amount/target/actor/tier/chain/factory/spread keys and repeatedly cancel: bounded memory/CPU/provider work, rate limits, single-flight cleanup and no admission budget reset or cache poisoning. - Malicious endpoints: wrong chain/block hash, stale/future/out-of-order responses, ignored/mismatched height headers, persistent 429 with extreme Retry-After, slow/oversized/malformed bodies and deterministic contract rejection. Preserve attestation, failure scope and bounded recovery; never let a hostile endpoint make stalled ingestion look healthy. - Spoofed symbols/contracts, forged routes, repeated capable assets, invalid maker plans and misleading USD marks: canonical identities and factory provenance, executable integer economics and exact operation validation. - Zero/negative/huge/overflow amounts, mixed/hostile decimals, rounding collisions, nonlinear books/taxes/hooks and dust floors: checked wide integer arithmetic; no float-derived execution or cached linear extrapolation. - Privilege and accounting attacks: runtime DDL/ledger/marker mutations denied; QA cannot target shared production; reorg/parser corruption cannot be swallowed; replay cannot duplicate swaps/fees/listing inventory or advance past omissions. - Known-block inventory eviction, partial authoritative recovery, unsupported cooldown/AutoLP/hook changes and tax-funding tampering: quarantine/fail closed, no wallet debit or signing bypass. - Confirmation race and forced Expert settings: no stale route substitution, missing floor, ≥99% override or context leakage between users. - Hostile errors/symbols/URLs/log fields: no XSS, SSRF, secret logging, unbounded labels or publication of actor identifiers/digests; private endpoints stay redacted. ## Verification criteria and completed investigation Completed before filing: - Reviewed the deployed lifecycle/checkpoint/provider/admission code and existing #1452/#1453/#1456 issues; no standalone open restart/circuit report was found by `fj` searches. - Public corpus: **0/24 useful quotes**, plus **0/4** on the fresh check; HTTP failures remain **FAIL**. Redacted log evidence confirms restarts. No claim of a complete root cause or zero upstream calls from these live probes. - Local revision `736be444100ba84887a6619336c83d2848258884`: `cargo test --locked --manifest-path indexer/Cargo.toml --lib lcd:: -- --test-threads=1` — **55 passed, 0 failed, 1 ignored**. The ignored benchmark was executed separately with `cargo test --locked --manifest-path indexer/Cargo.toml --lib lcd::pair_discovery_state::tests::pair_discovery_cache_benchmark -- --ignored --nocapture --test-threads=1`: **1 passed, 0 failed**. Its cache microbenchmark does not measure useful API quote latency. - Same command with filter `api::local_quote` — **45 passed, 0 failed**. These are existing baseline tests, not regression proof for this defect or the newer deployed revision. Implementation verification must run the new focused verifier and applicable `make verify-issue-1452`, `verify-issue-1453`, `verify-issue-1394`, `verify-issue-1392` and `verify-issue-1396` checks. Record exact revision, UTC times, commands, counts, original observation ages/generations, checkpoint/hash, bounded provider/cache/job counters and latency distributions/maxima. Count actual upstream calls; verify browser/socket useful output and settlement parity rather than status codes alone. Complete feasible checks first. Unavailable deployment, history, device or fixture checks may be explicit SKIP with the precise missing evidence and remaining scope; they do not block issue creation or implementation review. **Executed failures remain FAIL** until corrected and successfully rerun. Passing local tests, liveness or one successful quote never establish sustained deployed trading acceptance. Publish sanitized technical findings only; no conversation or reporter data is part of this issue.
Author
Owner

The 2026-10-15 repository reconciliation recovered the remaining local branch history and inspected the stale worktrees/stash. The browser lifecycle and execution-readiness merge commits introduce no new product changes relative to current main; newer policies and issue links are retained. The route-discovery stash is already incorporated by 1536631292 and subsequent actor-inventory safety corrections, so the stale snapshot was not reapplied.

Four differing historical QA records are preserved separately in docs/qa/merge-reconciliation-2026-10-15/recovered, with provenance/checksums in recovery-manifest.json. Current canonical receipts and artifact checksum lists remain in place. Private ignored configuration/artifacts and original recovery files were saved outside Git before the merged worktrees/branches/stash were removed. No production or shared database was reset, and no deployment/settlement claims are added. This completed implementation issue remains closed; outstanding live implementation work stays in its existing follow-up issues.

Final local verifiers passed: #1489 = 20 PASS / 0 FAIL / 2 explicit acceptance SKIP; #1483 = 21 PASS / 0 FAIL / 2 explicit acceptance SKIP. The first runs retained stale-database PoolTimedOut failures; complete reruns on a fresh owned fixture passed. The fixture was removed afterward. CI was explicitly skipped; details are in docs/qa/merge-reconciliation-2026-10-15/verification.json.

The 2026-10-15 repository reconciliation recovered the remaining local branch history and inspected the stale worktrees/stash. The browser lifecycle and execution-readiness merge commits introduce no new product changes relative to current main; newer policies and issue links are retained. The route-discovery stash is already incorporated by 1536631292e703bc0affcb8fd6309598ea71dc39 and subsequent actor-inventory safety corrections, so the stale snapshot was not reapplied. Four differing historical QA records are preserved separately in docs/qa/merge-reconciliation-2026-10-15/recovered, with provenance/checksums in recovery-manifest.json. Current canonical receipts and artifact checksum lists remain in place. Private ignored configuration/artifacts and original recovery files were saved outside Git before the merged worktrees/branches/stash were removed. No production or shared database was reset, and no deployment/settlement claims are added. This completed implementation issue remains closed; outstanding live implementation work stays in its existing follow-up issues. Final local verifiers passed: #1489 = 20 PASS / 0 FAIL / 2 explicit acceptance SKIP; #1483 = 21 PASS / 0 FAIL / 2 explicit acceptance SKIP. The first runs retained stale-database PoolTimedOut failures; complete reruns on a fresh owned fixture passed. The fixture was removed afterward. CI was explicitly skipped; details are in docs/qa/merge-reconciliation-2026-10-15/verification.json.
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
code/cl8y-dex-terraclassic#1464
No description provided.