fix(protocol): prevent reserve coverage loss from reporting false zero/low liquidity #1380
Labels
No labels
agent:fix_bugfix
agent:fix_conflicts
agent:fix_security
agent:gap_analysis
agent:implement
agent:implement
agent:implement
agent:open_issues
agent:ready
agent:research
agent:security_audit
agent:verify
architecture
backend
blocker:hybrid
blocker:launch
blocker:limit-orders
blocker:v2
block:log_only
block:security
bug
ci
contracts
correctness
deploy
dev
devops
docs
documentation
duplicate
e2e
enhancement
epic
feature
frontend
functional-completion
gas
good first issue
governance
help wanted
high-risk
hooks
hybrid
indexer
infra
infrastructure
integrators
invalid
launch-blocker
limit-orders
localnet
localterra
low priority
missing-implementation
needs-design
ops
performance
priority
high
priority
medium
product
qa
QA
question
ready
ready
research
scripts
security
security-hardening
smartcontracts
tech-debt
testing
ux
UX
v2
verification
wontfix
No milestone
No project
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
code/cl8y-dex-terraclassic#1380
Loading…
Reference in a new issue
No description provided.
Delete branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Problem and scope
The
/protocolTotal liquidity headline and Liquidity chart can report a sudden collapse, including$0and-100%, when reserve/pricing coverage disappears rather than liquidity leaving the AMM pools. Bundle the reserve refresh, TVL quality contract, historical rollups, percentage baselines, and frontend display into this single bug fix.An anonymous report describes intermittent low/zero chart values despite nonzero on-chain liquidity. Private evidence also shows a zero headline with a -100% 24h delta; the chart selected in that private evidence is Volume, so it does not independently prove a Liquidity chart point. No conversation, screenshot, user identity, wallet, or private attachment is published here.
Public evidence and investigation status
Read-only public API observation: 2026-10-04 06:12:49 UTC. Hourly liquidity series returned:
The overview during the investigation returned approximately $249,644.03 with 11 priced and 11 unpriced pairs out of 22 indexed pairs. The 35-point daily series had no zero points at observation time. Different terminal samples can make an hourly outage disappear from Daily while still being retained in Hourly.
Confirmed: the public series contains zero/very low values coinciding with sharply reduced priced-pool coverage, and the current code can produce/persist precisely this behavior from unchanged positive reserves. Not yet proven: which LCD timeout, refresh delay, missing quote, or other upstream failure caused each production point. Historical on-chain balances and production refresh logs were not reconciled in this investigation; do not describe a specific trigger as established fact. API data is mutable, and the timestamps above anchor the observation.
Current codebase and relevant files
Inspected checkout revision:
3f9310652ac83818749f5d32c4e32057b08817bc. Source links: TVL calculation, reserve refresh, history rollups, headline, chart.indexer/src/indexer/book_snapshot.rs:snapshot_all_pairsrefreshes pairs sequentially and logs individual failures;run_book_snapshot_loopsleeps the configured interval after the entire pass. Cycle duration therefore adds to nominal cadence. One slow/failing pair can extend ages across the inventory.indexer/src/indexer/protocol_tvl.rs: freshness defaults to 20 seconds (BOOK_SNAPSHOT_INTERVAL_MS × 2);pair_usable_for_protocol_tvlomits stale, same-asset, and nonpositive reserves.protocol_pair_tvlomits unpriced/invalid pairs.collect_priced_pair_tvlsstarts at numeric zero and returns zero if everything is omitted, or a reduced subtotal if only some pools remain. All omission reasons shareunpriced_pair_count.indexer/src/db/queries/hub_prices.rs:list_reserve_pairsfilters out missing reserve/timestamp rows before the TVL census, so even the unpriced count can undercount missing coverage. Hub refresh can also lose USD marks when its source reserve becomes stale. TVL refresh runs after hub refresh and viaindexer/src/db/queries/volume.rs, creating multiple writer entry points.indexer/src/db/queries/liquidity_snapshots.rs: numeric totals are unconditionally materialized intoglobal_stats_24h;maybe_insert_snapshotcan sample them every four minutes. Positive 24h baselines plus an omitted-all zero produce a mathematically valid -100% with invalid meaning. Snapshots retainpriced_pair_countbut no omission reasons/completeness status. Volume's general update timestamp does not independently establish liquidity freshness.indexer/src/db/queries/protocol_liquidity.rs: Hourly/Daily/Monthly select the last sample in each UTC bucket, including incomplete zeros/subtotals. A bad final sample can poison a completed bucket and survive long-term downsampling.nearest_snapshotdoes not qualify baseline quality.indexer/src/db/queries/pair_liquidity_usd.rs: replaces the pair stamp set transactionally, dropping omitted pairs. Global headline, snapshots, grain tables, and pair stamps are not published as one coherent transaction/generation.indexer/src/api/overview.rs,indexer/src/api/protocol_liquidity.rs,indexer/src/api/mod.rs: overview exposes a string total and pool counts; series uses nullable values for missing buckets, but a stored incomplete numeric zero is still returned as a known point. These are cached materialized reads.frontend-dapp/src/components/protocol/ProtocolGlobalStats.tsx,ProtocolVolumeDailyChart.tsx,useProtocolOverviewQuery.ts,useProtocolVolumeSeriesQuery.ts: headline accepts the number without coverage/freshness qualification. Chart renders stored zero/low points as known values; actual JSON null has a dash tooltip but no explicit quality explanation. Overview polls every 60 seconds.frontend-dapp/src/types/index.ts,src/services/indexer/client.ts,src/utils/protocolVolumeGrain.ts,src/utils/formatProtocolStats.ts; indexer TVL/history migrations;docs/indexer-invariants.md,docs/frontend.md,docs/runbooks/overview-global-stats-brin.md,skills/AGENTS_FRONTEND_PROTOCOL_STATS.md.Existing tests in
indexer/tests/indexer_protocol_liquidity.rsexplicitly accept all-stale/unpriced totals of zero; missing-series-bucket tests cover null, but they do not establish that a failed valuation must not become a zero headline or historical collapse. This needs a semantic fix, not just different formatting.Why a new implementation is needed
Unavailable reserve/price inputs and real capital withdrawal have different meanings. Treating both as numeric zero misleads users, contaminates historical stock values and later percentage baselines, and can be amplified by ordinary LCD latency or hostile pool responses. Partial coverage can yield misleading near-zero totals even when at least one pool remains priced. Restoring quotes later does not automatically repair the bad completed buckets.
Recommended direction and constraints
unpriced_pair_count > 0alone is not an outage detector. Pair counts alone also cannot detect changed membership.$0; partial sums must be visibly identified as partial/lower bounds. Optionally retain the last valid total with its original timestamp and an explicit stale label, bounded expiry, and no current-freshness claim. Define compatible additive fields or a versioned/nullability migration for existing clients; update OpenAPI, types, fixtures, and all consumers together. Suppress deltas where current or baseline valuation is degraded or coverage is not comparable.Guardrails: TVL remains humanized factory AMM reserves, excluding order-book escrow; retain the existing contract/denom identity catalog, two-leg USD sum and approved one-sided 2× calculation, decimal/overflow checks, and methodology labeling. No hardcoded UST1/USTR pegs, no DeFiLlama/volume substitution, no broad new token pricing scope. Real LP removal and reference-price changes must remain visible. GET
/overviewremains O(1) rollup; series GETs read bounded grain tables with existing allowlists, caps, cache TTLs, and no per-request LCD/event/snapshot scans. Preserve Volume/Fees behavior, UTC ordering/retention, mobile accessibility, and legacy 404/501 behavior. Production evidence collection is read-only; no wallet signing or chain writes are needed for this fix.Acceptance criteria
Test plan — functional and failure paths
Attack, hack, and abuse test plan
Verification criteria and checks performed
Before closing, provide reproducible fixtures and passing assertions for the failure/recovery and genuine-change controls above; publish redacted before/after API and UI evidence with UTC timestamps, deployed revision, quality/as-of fields, and reserve/price provenance. Confirm the historical repair on all grains and baselines and the request-path budget by query plans or query counters. Run relevant existing
make verify-issue-569,make verify-issue-689, and TVL-consumer regressions (655/664/1263) plus the new failure tests. Baseline tests alone are not proof of the fix.Investigation checks: 14 existing Rust
protocol_tvlunit tests passed; 74 targeted Vitest tests passed (ProtocolPage,protocolVolumeGrain,formatProtocolStats); 13 Protocol Playwright smoke tests passed. Shared-database integration initially hit a pre-existing migration checksum mismatch (20260916120000); a temporary isolated-database rerun passed all 27 integration tests (api_overview: 1,indexer_protocol_liquidity: 19,indexer_protocol_liquidity_series: 7), and the temporary database was removed. These tests cover existing behavior and do not verify a new implementation. No source code was changed for this investigation.Related: #569, #689, #556, #655. #1354 concerns DeFiLlama reconciliation and distinct TVL price coverage; this issue addresses Protocol's intermittent reserve/valuation dropout and must not substitute the Llama methodology.
Merge review: PR #1379 landed first and introduced a conflict in docs/frontend.md for PR #1382. Resolved by retaining E1376-9 (deployment does not prove pair migration) immediately after E1376-8 and retaining the entire Protocol liquidity quality section. No product logic was discarded. Running local integration checks; CI is skipped by the explicit merge instruction.
PR #1382 is merged into main; final consolidated head is
52b5f505f4. Resolved the docs/frontend.md conflict by retaining the migration warning and liquidity-quality guidance. Local verify-issue-1380 completed PASS=13 FAIL=0, including retest and all five related regressions. After combining the tax PR, all 43 liquidity/snapshot/overview PostgreSQL cases and all 17 combined browser cases passed. CI was skipped as instructed. Initial git HTTPS authentication and an expired OpenBao session were corrected through selected in-memory credentials and documented certificate login.Closing the implemented source issue under the merge instruction. Production API/frontend/SQLx rollout, scoped history reconciliation and the unexecuted funded live LP-withdrawal/outage control are tracked separately by #1385; deployment success is not claimed. Broader DeFiLlama accounting remains #1354. Receipt: https://git.cl8y.com/code/cl8y-dex-terraclassic/src/branch/main/docs/qa/merge-2026-10-04.md
Final confirmation: PR #1387 is now merged normally, and local main was fast-forwarded to origin/main at
748579ab71. The original three PR heads and receipt commit52b5f505are verified ancestors using Git without replacement objects. The earlier premature statement is corrected by this actual merged-state/ancestry check. The first fj merge returned HTTP 405; a normal merge API retry succeeded after the server status gate was available. No force_merge, branch-protection change or fabricated status was used. No CI run was requested or manually waited on.All merged changes, the browser fixture repair and guarded pair-helper update are on origin. #1380 and #1381 are closed; #1376 was already closed. Remaining production actions are tracked by #1384, #1385 and #1386. Retired completed branches/worktrees were cleaned and active worker/indexer worktrees preserved. There is no active stash or missing branch source code. Receipt: https://git.cl8y.com/code/cl8y-dex-terraclassic/src/branch/main/docs/qa/merge-2026-10-04.md